Debian Codegraph @

mlspp/src/state.cpp

raw symbols SCIP
1 #include <mls/state.h>
2 #include <set>
3
4 namespace mlspp {
5
6 ///
7 /// Constructors
8 ///
9
10 State::State(bytes group_id,
11 CipherSuite suite,
12 HPKEPrivateKey enc_priv,
13 SignaturePrivateKey sig_priv,
14 const LeafNode& leaf_node,
15 ExtensionList extensions)
16 : _suite(suite)
17 , _group_id(std::move(group_id))
18 , _epoch(0)
19 , _tree(suite)
20 , _transcript_hash(suite)
21 , _extensions(std::move(extensions))
22 , _index(0)
23 , _identity_priv(std::move(sig_priv))
24 {
25 // Verify that the client supports the proposed group extensions
26 if (!leaf_node.verify_extension_support(_extensions)) {
27 throw InvalidParameterError("Client doesn't support required extensions");
28 }
29
30 _index = _tree.add_leaf(leaf_node);
31 _tree.set_hash_all();
32 _tree_priv = TreeKEMPrivateKey::solo(suite, _index, std::move(enc_priv));
33 if (!_tree_priv.consistent(_tree)) {
34 throw InvalidParameterError("LeafNode inconsistent with private key");
35 }
36
37 // XXX(RLB): Convert KeyScheduleEpoch to take GroupContext?
38 auto ctx = tls::marshal(group_context());
39 _key_schedule =
40 KeyScheduleEpoch(_suite, random_bytes(_suite.secret_size()), ctx);
41 _keys = _key_schedule.encryption_keys(_tree.size);
42
43 // Update the interim transcript hash with a virtual confirmation tag
44 _transcript_hash.update_interim(
45 _key_schedule.confirmation_tag(_transcript_hash.confirmed));
46 }
47
48 TreeKEMPublicKey
49 State::import_tree(const bytes& tree_hash,
50 const std::optional<TreeKEMPublicKey>& external,
51 const ExtensionList& extensions)
52 {
53 auto tree = TreeKEMPublicKey(_suite);
54 auto maybe_tree_extn = extensions.find<RatchetTreeExtension>();
55 if (external) {
56 tree = opt::get(external);
57 } else if (maybe_tree_extn) {
58 tree = opt::get(maybe_tree_extn).tree;
59 } else {
60 throw InvalidParameterError("No tree available");
61 }
62
63 tree.suite = _suite;
64
65 tree.set_hash_all();
66 if (tree.root_hash() != tree_hash) {
67 throw InvalidParameterError("Tree does not match GroupInfo");
68 }
69
70 return tree;
71 }
72
73 bool
74 State::validate_tree() const
75 {
76 // The functionality here is somewhat duplicative of State::valid(const
77 // LeafNode&). Simply calling that method, however, would result in this
78 // method having quadratic scaling, since each call to valid() does a linear
79 // scan through the tree to check uniqueness of keys and compatibility of
80 // credential support.
81
82 // Validate that the tree is parent-hash valid
83 if (!_tree.parent_hash_valid()) {
84 return false;
85 }
86
87 // Validate the signatures on all leaves
88 const auto signature_valid =
89 _tree.all_leaves([&](auto i, const auto& leaf_node) {
90 auto binding = std::optional<LeafNode::MemberBinding>{};
91 switch (leaf_node.source()) {
92 case LeafNodeSource::commit:
93 case LeafNodeSource::update:
94 binding = LeafNode::MemberBinding{ _group_id, i };
95 break;
96
97 default:
98 // Nothing to do
99 break;
100 }
101
102 return leaf_node.verify(_suite, binding);
103 });
104 if (!signature_valid) {
105 return false;
106 }
107
108 // Collect cross-tree properties
109 auto n_leaves = size_t(0);
110 auto encryption_keys = std::set<bytes>{};
111 auto signature_keys = std::set<bytes>{};
112 auto credential_types = std::set<CredentialType>{};
113 _tree.all_leaves([&](auto /* i */, const auto& leaf_node) {
114 n_leaves += 1;
115 encryption_keys.insert(leaf_node.encryption_key.data);
116 signature_keys.insert(leaf_node.signature_key.data);
117 credential_types.insert(leaf_node.credential.type());
118 return true;
119 });
120
121 // Verify uniqueness of keys
122 if (encryption_keys.size() != n_leaves) {
123 return false;
124 }
125
126 if (signature_keys.size() != n_leaves) {
127 return false;
128 }
129
130 // Verify that each leaf indicates support for all required parameters
131 return _tree.all_leaves([&](auto /* i */, const auto& leaf_node) {
132 const auto supports_group_extensions =
133 leaf_node.verify_extension_support(_extensions);
134 const auto supports_own_extensions =
135 leaf_node.verify_extension_support(leaf_node.extensions);
136 const auto supports_group_credentials =
137 leaf_node.capabilities.credentials_supported(credential_types);
138 return supports_group_extensions && supports_own_extensions &&
139 supports_group_credentials;
140 });
141 }
142
143 State::State(SignaturePrivateKey sig_priv,
144 const GroupInfo& group_info,
145 const std::optional<TreeKEMPublicKey>& tree)
146 : _suite(group_info.group_context.cipher_suite)
147 , _group_id(group_info.group_context.group_id)
148 , _epoch(group_info.group_context.epoch)
149 , _tree(import_tree(group_info.group_context.tree_hash,
150 tree,
151 group_info.extensions))
152 , _transcript_hash(_suite,
153 group_info.group_context.confirmed_transcript_hash,
154 group_info.confirmation_tag)
155 , _extensions(group_info.group_context.extensions)
156 , _key_schedule(_suite)
157 , _index(0)
158 , _identity_priv(std::move(sig_priv))
159 {
160 if (!validate_tree()) {
161 throw InvalidParameterError("Invalid tree");
162 }
163
164 // The following are not set:
165 // _index
166 // _tree_priv
167 //
168 // This ctor should only be used within external_commit, in which case these
169 // fields are populated by the subsequent commit()
170 }
171
172 // Initialize a group from a Welcome
173 State::State(const HPKEPrivateKey& init_priv,
174 HPKEPrivateKey leaf_priv,
175 SignaturePrivateKey sig_priv,
176 const KeyPackage& key_package,
177 const Welcome& welcome,
178 const std::optional<TreeKEMPublicKey>& tree,
179 std::map<bytes, bytes> external_psks)
180 : State(init_priv,
181 std::move(leaf_priv),
182 std::move(sig_priv),
183 key_package,
184 welcome,
185 tree,
186 std::move(external_psks),
187 {})
188 {
189 }
190
191 State::State(const HPKEPrivateKey& init_priv,
192 HPKEPrivateKey leaf_priv,
193 SignaturePrivateKey sig_priv,
194 const KeyPackage& key_package,
195 const Welcome& welcome,
196 const std::optional<TreeKEMPublicKey>& tree,
197 std::map<bytes, bytes> external_psks,
198 std::map<EpochRef, bytes> resumption_psks)
199 : _suite(welcome.cipher_suite)
200 , _epoch(0)
201 , _tree(welcome.cipher_suite)
202 , _transcript_hash(welcome.cipher_suite)
203 , _identity_priv(std::move(sig_priv))
204 , _external_psks(std::move(external_psks))
205 , _resumption_psks(std::move(resumption_psks))
206 {
207 auto maybe_kpi = welcome.find(key_package);
208 if (!maybe_kpi) {
209 throw InvalidParameterError("Welcome not intended for key package");
210 }
211 auto kpi = opt::get(maybe_kpi);
212
213 if (key_package.cipher_suite != welcome.cipher_suite) {
214 throw InvalidParameterError("Ciphersuite mismatch");
215 }
216
217 // Decrypt the GroupSecrets and look up required PSKs
218 auto secrets = welcome.decrypt_secrets(kpi, init_priv);
219 auto psks = resolve(secrets.psks.psks);
220
221 // Decrypt the GroupInfo
222 auto group_info = welcome.decrypt(secrets.joiner_secret, psks);
223 if (group_info.group_context.cipher_suite != _suite) {
224 throw InvalidParameterError("GroupInfo and Welcome ciphersuites disagree");
225 }
226
227 // Import the tree from the argument or from the extension
228 _tree = import_tree(
229 group_info.group_context.tree_hash, tree, group_info.extensions);
230
231 // Verify the signature on the GroupInfo
232 if (!group_info.verify(_tree)) {
233 throw InvalidParameterError("Invalid GroupInfo");
234 }
235
236 // Ingest the GroupSecrets and GroupInfo
237 _epoch = group_info.group_context.epoch;
238 _group_id = group_info.group_context.group_id;
239
240 _transcript_hash.confirmed =
241 group_info.group_context.confirmed_transcript_hash;
242 _transcript_hash.update_interim(group_info.confirmation_tag);
243
244 _extensions = group_info.group_context.extensions;
245
246 // Validate that the tree is in fact consistent with the group's parameters
247 if (!validate_tree()) {
248 throw InvalidParameterError("Invalid tree");
249 }
250
251 // Construct TreeKEM private key from parts provided
252 auto maybe_index = _tree.find(key_package.leaf_node);
253 if (!maybe_index) {
254 throw InvalidParameterError("New joiner not in tree");
255 }
256
257 _index = opt::get(maybe_index);
258
259 auto ancestor = _index.ancestor(group_info.signer);
260 auto path_secret = std::optional<bytes>{};
261 if (secrets.path_secret) {
262 path_secret = opt::get(secrets.path_secret).secret;
263 }
264
265 _tree_priv = TreeKEMPrivateKey::joiner(
266 _tree, _index, std::move(leaf_priv), ancestor, path_secret);
267
268 // Ratchet forward into the current epoch
269 auto group_ctx = tls::marshal(group_context());
270 _key_schedule =
271 KeyScheduleEpoch::joiner(_suite, secrets.joiner_secret, psks, group_ctx);
272 _keys = _key_schedule.encryption_keys(_tree.size);
273
274 // Verify the confirmation
275 const auto confirmation_tag =
276 _key_schedule.confirmation_tag(_transcript_hash.confirmed);
277 if (confirmation_tag != group_info.confirmation_tag) {
278 throw ProtocolError("Confirmation failed to verify");
279 }
280 }
281
282 std::tuple<MLSMessage, State>
283 State::external_join(const bytes& leaf_secret,
284 SignaturePrivateKey sig_priv,
285 const KeyPackage& key_package,
286 const GroupInfo& group_info,
287 const std::optional<TreeKEMPublicKey>& tree,
288 const MessageOpts& msg_opts,
289 std::optional<LeafIndex> remove_prior,
290 const std::map<bytes, bytes>& psks)
291 {
292 // Create a preliminary state
293 auto initial_state = State(std::move(sig_priv), group_info, tree);
294
295 // Look up the external public key for the group
296 const auto maybe_external_pub =
297 group_info.extensions.find<ExternalPubExtension>();
298 if (!maybe_external_pub) {
299 throw InvalidParameterError("No external pub in GroupInfo");
300 }
301
302 const auto& external_pub = opt::get(maybe_external_pub).external_pub;
303
304 // Insert an ExternalInit proposal
305 auto opts = CommitOpts{};
306 auto [enc, force_init_secret] =
307 KeyScheduleEpoch::external_init(key_package.cipher_suite, external_pub);
308 auto ext_init = Proposal{ ExternalInit{ enc } };
309 opts.extra_proposals.push_back(ext_init);
310
311 // Evict a prior appearance if required
312 if (remove_prior) {
313 auto remove = initial_state.remove_proposal(opt::get(remove_prior));
314 opts.extra_proposals.push_back(remove);
315 }
316
317 // Inject PSKs
318 for (const auto& [id, secret] : psks) {
319 initial_state.add_external_psk(id, secret);
320 auto psk = initial_state.pre_shared_key_proposal(id);
321 opts.extra_proposals.push_back(psk);
322 }
323
324 // Use the preliminary state to create a commit and advance to a real state
325 auto params = ExternalCommitParams{ key_package, force_init_secret };
326 auto [commit_msg, welcome, state] =
327 initial_state.commit(leaf_secret, opts, msg_opts, params);
328 silence_unused(welcome);
329 return { commit_msg, state };
330 }
331
332 MLSMessage
333 State::new_member_add(const bytes& group_id,
334 epoch_t epoch,
335 const KeyPackage& new_member,
336 const SignaturePrivateKey& sig_priv)
337 {
338 const auto suite = new_member.cipher_suite;
339 auto proposal = Proposal{ Add{ new_member } };
340 auto content = GroupContent{ group_id,
341 epoch,
342 { NewMemberProposalSender{} },
343 { /* no authenticated data */ },
344 { std::move(proposal) } };
345 auto content_auth = AuthenticatedContent::sign(
346 WireFormat::mls_public_message, std::move(content), suite, sig_priv, {});
347
348 return PublicMessage::protect(std::move(content_auth), suite, {}, {});
349 }
350
351 ///
352 /// Proposal and commit factories
353 ///
354 template<typename Inner>
355 MLSMessage
356 State::protect_full(Inner&& inner_content, const MessageOpts& msg_opts)
357 {
358 auto content_auth = sign({ MemberSender{ _index } },
359 std::forward<Inner>(inner_content),
360 msg_opts.authenticated_data,
361 msg_opts.encrypt);
362 return protect(std::move(content_auth), msg_opts.padding_size);
363 }
364
365 template<typename Inner>
366 AuthenticatedContent
367 State::sign(const Sender& sender,
368 Inner&& inner_content,
369 const bytes& authenticated_data,
370 bool encrypt) const
371 {
372 auto content = GroupContent{ _group_id,
373 _epoch,
374 sender,
375 authenticated_data,
376 { std::forward<Inner>(inner_content) } };
377
378 auto wire_format = (encrypt) ? WireFormat::mls_private_message
379 : WireFormat::mls_public_message;
380
381 auto content_auth = AuthenticatedContent::sign(
382 wire_format, std::move(content), _suite, _identity_priv, group_context());
383
384 return content_auth;
385 }
386
387 MLSMessage
388 State::protect(AuthenticatedContent&& content_auth, size_t padding_size)
389 {
390 switch (content_auth.wire_format) {
391 case WireFormat::mls_public_message:
392 return PublicMessage::protect(std::move(content_auth),
393 _suite,
394 _key_schedule.membership_key,
395 group_context());
396
397 case WireFormat::mls_private_message:
398 return PrivateMessage::protect(std::move(content_auth),
399 _suite,
400 _keys,
401 _key_schedule.sender_data_secret,
402 padding_size);
403
404 default:
405 throw InvalidParameterError("Malformed AuthenticatedContent");
406 }
407 }
408
409 ValidatedContent
410 State::unwrap(const MLSMessage& msg)
411 {
412 if (msg.version != ProtocolVersion::mls10) {
413 throw InvalidParameterError("Unsupported version");
414 }
415
416 const auto unprotect = overloaded{
417 [&](const PublicMessage& pt) -> ValidatedContent {
418 if (pt.get_group_id() != _group_id) {
419 throw ProtocolError("PublicMessage not for this group");
420 }
421
422 if (pt.get_epoch() != _epoch) {
423 throw ProtocolError("PublicMessage not for this epoch");
424 }
425
426 auto maybe_content_auth =
427 pt.unprotect(_suite, _key_schedule.membership_key, group_context());
428 if (!maybe_content_auth) {
429 throw ProtocolError("Membership tag failed to verify");
430 }
431 return opt::get(maybe_content_auth);
432 },
433
434 [&](const PrivateMessage& ct) -> ValidatedContent {
435 if (ct.get_group_id() != _group_id) {
436 throw ProtocolError("PrivateMessage not for this group");
437 }
438
439 if (ct.get_epoch() != _epoch) {
440 throw ProtocolError("PrivateMessage not for this epoch");
441 }
442
443 auto maybe_content_auth =
444 ct.unprotect(_suite, _keys, _key_schedule.sender_data_secret);
445 if (!maybe_content_auth) {
446 throw ProtocolError("PrivateMessage decryption failure");
447 }
448 return opt::get(maybe_content_auth);
449 },
450
451 [](const auto& /* unused */) -> ValidatedContent {
452 throw ProtocolError("Invalid wire format");
453 },
454 };
455
456 auto val_content = var::visit(unprotect, msg.message);
457 if (!verify(val_content.content_auth)) {
458 throw InvalidParameterError("Message signature failed to verify");
459 }
460
461 return val_content;
462 }
463
464 Proposal
465 State::add_proposal(const KeyPackage& key_package) const
466 {
467 // Check that the key package is validly signed
468 if (!key_package.verify()) {
469 throw InvalidParameterError("Invalid signature on key package");
470 }
471
472 // Check that the group's basic properties are supported
473 auto now = seconds_since_epoch();
474 if (!key_package.leaf_node.verify_expiry(now)) {
475 throw InvalidParameterError("Expired key package");
476 }
477
478 // Check that the group's extensions are supported
479 if (!key_package.leaf_node.verify_extension_support(_extensions)) {
480 throw InvalidParameterError(
481 "Key package does not support group's extensions");
482 }
483
484 return { Add{ key_package } };
485 }
486
487 Proposal
488 State::update_proposal(HPKEPrivateKey leaf_priv, const LeafNodeOptions& opts)
489 {
490 if (_cached_update) {
491 throw ProtocolError("Only one update may be generated per epoch");
492 }
493
494 auto leaf = opt::get(_tree.leaf_node(_index));
495
496 auto new_leaf = leaf.for_update(
497 _suite, _group_id, _index, leaf_priv.public_key, opts, _identity_priv);
498
499 auto update = Update{ new_leaf };
500 _cached_update = CachedUpdate{ std::move(leaf_priv), update };
501 return { update };
502 }
503
504 Proposal
505 State::remove_proposal(RosterIndex index) const
506 {
507 return remove_proposal(leaf_for_roster_entry(index));
508 }
509
510 Proposal
511 State::remove_proposal(LeafIndex removed) const
512 {
513 if (!_tree.has_leaf(removed)) {
514 throw InvalidParameterError("Remove on blank leaf");
515 }
516
517 return { Remove{ removed } };
518 }
519
520 Proposal
521 State::group_context_extensions_proposal(ExtensionList exts) const
522 {
523 if (!extensions_supported(exts)) {
524 throw InvalidParameterError("Unsupported extensions");
525 }
526
527 return { GroupContextExtensions{ std::move(exts) } };
528 }
529
530 Proposal
531 State::pre_shared_key_proposal(const bytes& external_psk_id) const
532 {
533 if (_external_psks.count(external_psk_id) == 0) {
534 throw InvalidParameterError("Unknown PSK");
535 }
536
537 auto psk_id = PreSharedKeyID{
538 { ExternalPSK{ external_psk_id } },
539 random_bytes(_suite.secret_size()),
540 };
541 return { PreSharedKey{ psk_id } };
542 }
543
544 Proposal
545 State::pre_shared_key_proposal(const bytes& group_id, epoch_t epoch) const
546 {
547 if (epoch != _epoch && _resumption_psks.count({ group_id, epoch }) == 0) {
548 throw InvalidParameterError("Unknown PSK");
549 }
550
551 auto psk_id = PreSharedKeyID{
552 { ResumptionPSK{ ResumptionPSKUsage::application, group_id, epoch } },
553 random_bytes(_suite.secret_size()),
554 };
555 return { PreSharedKey{ psk_id } };
556 }
557
558 Proposal
559 State::reinit_proposal(bytes group_id,
560 ProtocolVersion version,
561 CipherSuite cipher_suite,
562 ExtensionList extensions)
563 {
564 return { ReInit{
565 std::move(group_id), version, cipher_suite, std::move(extensions) } };
566 }
567
568 MLSMessage
569 State::add(const KeyPackage& key_package, const MessageOpts& msg_opts)
570 {
571 return protect_full(add_proposal(key_package), msg_opts);
572 }
573
574 MLSMessage
575 State::update(HPKEPrivateKey leaf_priv,
576 const LeafNodeOptions& opts,
577 const MessageOpts& msg_opts)
578 {
579 return protect_full(update_proposal(std::move(leaf_priv), opts), msg_opts);
580 }
581
582 MLSMessage
583 State::remove(RosterIndex index, const MessageOpts& msg_opts)
584 {
585 return protect_full(remove_proposal(index), msg_opts);
586 }
587
588 MLSMessage
589 State::remove(LeafIndex removed, const MessageOpts& msg_opts)
590 {
591 return protect_full(remove_proposal(removed), msg_opts);
592 }
593
594 MLSMessage
595 State::group_context_extensions(ExtensionList exts, const MessageOpts& msg_opts)
596 {
597 return protect_full(group_context_extensions_proposal(std::move(exts)),
598 msg_opts);
599 }
600
601 MLSMessage
602 State::pre_shared_key(const bytes& external_psk_id, const MessageOpts& msg_opts)
603 {
604 return protect_full(pre_shared_key_proposal(external_psk_id), msg_opts);
605 }
606
607 MLSMessage
608 State::pre_shared_key(const bytes& group_id,
609 epoch_t epoch,
610 const MessageOpts& msg_opts)
611 {
612 return protect_full(pre_shared_key_proposal(group_id, epoch), msg_opts);
613 }
614
615 MLSMessage
616 State::reinit(bytes group_id,
617 ProtocolVersion version,
618 CipherSuite cipher_suite,
619 ExtensionList extensions,
620 const MessageOpts& msg_opts)
621 {
622 return protect_full(
623 reinit_proposal(
624 std::move(group_id), version, cipher_suite, std::move(extensions)),
625 msg_opts);
626 }
627
628 std::tuple<MLSMessage, Welcome, State>
629 State::commit(const bytes& leaf_secret,
630 const std::optional<CommitOpts>& opts,
631 const MessageOpts& msg_opts)
632 {
633 return commit(leaf_secret, opts, msg_opts, NormalCommitParams{});
634 }
635
636 std::tuple<MLSMessage, Welcome, State>
637 State::commit(const bytes& leaf_secret,
638 const std::optional<CommitOpts>& opts,
639 const MessageOpts& msg_opts,
640 CommitParams params)
641 {
642 // Construct a commit from cached proposals
643 // TODO(rlb) ignore some proposals:
644 // * Update after Update
645 // * Update after Remove
646 // * Remove after Remove
647 Commit commit;
648 auto joiners = std::vector<KeyPackage>{};
649 for (const auto& cached : _pending_proposals) {
650 if (var::holds_alternative<Add>(cached.proposal.content)) {
651 const auto& add = var::get<Add>(cached.proposal.content);
652 joiners.push_back(add.key_package);
653 }
654
655 commit.proposals.push_back({ cached.ref });
656 }
657
658 // Add the extra proposals to those we had cached
659 if (opts) {
660 const auto& extra_proposals = opt::get(opts).extra_proposals;
661 for (const auto& proposal : extra_proposals) {
662 if (var::holds_alternative<Add>(proposal.content)) {
663 const auto& add = var::get<Add>(proposal.content);
664 joiners.push_back(add.key_package);
665 }
666
667 commit.proposals.push_back({ proposal });
668 }
669 }
670
671 // If this is an external commit, insert an ExternalInit proposal
672 auto external_commit = std::optional<ExternalCommitParams>{};
673 if (var::holds_alternative<ExternalCommitParams>(params)) {
674 external_commit = var::get<ExternalCommitParams>(params);
675 }
676
677 auto force_init_secret = std::optional<bytes>{};
678 if (external_commit) {
679 force_init_secret = opt::get(external_commit).force_init_secret;
680 }
681
682 // Apply proposals
683 State next = successor();
684
685 const auto proposals = must_resolve(commit.proposals, _index);
686 if (!valid(proposals, _index, params)) {
687 throw ProtocolError("Invalid proposal list");
688 }
689
690 const auto [joiner_locations, psks] = next.apply(proposals);
691
692 if (external_commit) {
693 const auto& leaf_node =
694 opt::get(external_commit).joiner_key_package.leaf_node;
695 next._index = next._tree.add_leaf(leaf_node);
696 }
697
698 // If this is an external commit, indicate it in the sender field
699 auto sender = Sender{ MemberSender{ _index } };
700 if (external_commit) {
701 sender = Sender{ NewMemberCommitSender{} };
702 }
703
704 // KEM new entropy to the group and the new joiners
705 auto commit_secret = _suite.zero();
706 auto path_secrets =
707 std::vector<std::optional<bytes>>(joiner_locations.size());
708 auto force_path = opts && opt::get(opts).force_path;
709 if (force_path || path_required(proposals)) {
710 auto leaf_node_opts = LeafNodeOptions{};
711 if (opts) {
712 leaf_node_opts = opt::get(opts).leaf_node_opts;
713 }
714
715 auto new_priv = next._tree.update(
716 next._index, leaf_secret, next._group_id, _identity_priv, leaf_node_opts);
717
718 auto ctx = tls::marshal(GroupContext{
719 next._suite,
720 next._group_id,
721 next._epoch + 1,
722 next._tree.root_hash(),
723 next._transcript_hash.confirmed,
724 next._extensions,
725 });
726 auto path = next._tree.encap(new_priv, ctx, joiner_locations);
727
728 next._tree_priv = new_priv;
729 commit.path = path;
730 commit_secret = new_priv.update_secret;
731
732 for (size_t i = 0; i < joiner_locations.size(); i++) {
733 auto [overlap, shared_path_secret, ok] =
734 new_priv.shared_path_secret(joiner_locations[i]);
735 silence_unused(overlap);
736 silence_unused(ok);
737
738 path_secrets[i] = shared_path_secret;
739 }
740 }
741
742 // Create the Commit message and advance the transcripts / key schedule
743 auto commit_content_auth =
744 sign(sender, commit, msg_opts.authenticated_data, msg_opts.encrypt);
745
746 next._transcript_hash.update_confirmed(commit_content_auth);
747 next._epoch += 1;
748 next.update_epoch_secrets(commit_secret, psks, force_init_secret);
749
750 const auto confirmation_tag =
751 next._key_schedule.confirmation_tag(next._transcript_hash.confirmed);
752 commit_content_auth.set_confirmation_tag(confirmation_tag);
753
754 next._transcript_hash.update_interim(commit_content_auth);
755
756 auto commit_message =
757 protect(std::move(commit_content_auth), msg_opts.padding_size);
758
759 // Complete the GroupInfo and form the Welcome
760 auto group_info = GroupInfo{
761 {
762 next._suite,
763 next._group_id,
764 next._epoch,
765 next._tree.root_hash(),
766 next._transcript_hash.confirmed,
767 next._extensions,
768 },
769 { /* No other extensions */ },
770 { confirmation_tag },
771 };
772 if (opts && opt::get(opts).inline_tree) {
773 group_info.extensions.add(RatchetTreeExtension{ next._tree });
774 }
775 group_info.sign(next._tree, next._index, next._identity_priv);
776
777 auto welcome =
778 Welcome{ _suite, next._key_schedule.joiner_secret, psks, group_info };
779 for (size_t i = 0; i < joiners.size(); i++) {
780 welcome.encrypt(joiners[i], path_secrets[i]);
781 }
782
783 return std::make_tuple(commit_message, welcome, next);
784 }
785
786 ///
787 /// Message handlers
788 ///
789
790 GroupContext
791 State::group_context() const
792 {
793 return GroupContext{
794 _suite,
795 _group_id,
796 _epoch,
797 _tree.root_hash(),
798 _transcript_hash.confirmed,
799 _extensions,
800 };
801 }
802
803 std::optional<State>
804 State::handle(const MLSMessage& msg)
805 {
806 return handle(unwrap(msg), std::nullopt, std::nullopt);
807 }
808
809 std::optional<State>
810 State::handle(const MLSMessage& msg, std::optional<State> cached_state)
811 {
812 return handle(unwrap(msg), std::move(cached_state), std::nullopt);
813 }
814
815 std::optional<State>
816 State::handle(const ValidatedContent& content_auth)
817 {
818 return handle(content_auth, std::nullopt, std::nullopt);
819 }
820
821 std::optional<State>
822 State::handle(const ValidatedContent& content_auth,
823 std::optional<State> cached_state)
824 {
825 return handle(content_auth, std::move(cached_state), std::nullopt);
826 }
827
828 std::optional<State>
829 State::handle(const MLSMessage& msg,
830 std::optional<State> cached_state,
831 const std::optional<CommitParams>& expected_params)
832 {
833 return handle(unwrap(msg), std::move(cached_state), expected_params);
834 }
835
836 std::optional<State>
837 State::handle(const ValidatedContent& val_content,
838 std::optional<State> cached_state,
839 const std::optional<CommitParams>& expected_params)
840 {
841 // Dispatch on content type
842 const auto& content_auth = val_content.authenticated_content();
843 const auto& content = content_auth.content;
844 switch (content.content_type()) {
845 // Proposals get queued, do not result in a state transition
846 case ContentType::proposal:
847 cache_proposal(content_auth);
848 return std::nullopt;
849
850 // Commits are handled in the remainder of this method
851 case ContentType::commit:
852 break;
853
854 // Any other content type in this method is an error
855 default:
856 throw InvalidParameterError("Invalid content type");
857 }
858
859 switch (content.sender.sender_type()) {
860 case SenderType::member:
861 case SenderType::new_member_commit:
862 break;
863
864 default:
865 throw ProtocolError("Invalid commit sender type");
866 }
867
868 auto sender = std::optional<LeafIndex>();
869 if (content.sender.sender_type() == SenderType::member) {
870 sender = var::get<MemberSender>(content.sender.sender).sender;
871 }
872
873 if (sender == _index) {
874 if (cached_state) {
875 // Verify that the cached state is a plausible successor to this state
876 const auto& next = opt::get(cached_state);
877 if (next._group_id != _group_id || next._epoch != _epoch + 1 ||
878 next._index != _index) {
879 throw InvalidParameterError("Invalid successor state");
880 }
881
882 return next;
883 }
884
885 throw InvalidParameterError("Handle own commits with caching");
886 }
887
888 // Apply the commit
889 const auto& commit = var::get<Commit>(content.content);
890 const auto proposals = must_resolve(commit.proposals, sender);
891
892 const auto params = infer_commit_type(sender, proposals, expected_params);
893 auto external_commit = var::holds_alternative<ExternalCommitParams>(params);
894
895 // Check that a path is present when required
896 if (path_required(proposals) && !commit.path) {
897 throw ProtocolError("Path required but not present");
898 }
899
900 // Apply the proposals
901 auto next = successor();
902 auto [joiner_locations, psks] = next.apply(proposals);
903
904 // If this is an external commit, add the joiner to the tree and note the
905 // location where they were added. Also, compute the "externally forced"
906 // value that we will use for the init_secret (as opposed to the init_secret
907 // from the key schedule).
908 auto force_init_secret = std::optional<bytes>{};
909 auto sender_location = LeafIndex{ 0 };
910 if (!external_commit) {
911 sender_location = opt::get(sender);
912 } else {
913 // Find where the joiner will be added
914 sender_location = next._tree.allocate_leaf();
915
916 // Extract the forced init secret
917 auto kem_output = commit.valid_external();
918 if (!kem_output) {
919 throw ProtocolError("Invalid external commit");
920 }
921
922 force_init_secret =
923 _key_schedule.receive_external_init(opt::get(kem_output));
924 }
925
926 // Decapsulate and apply the UpdatePath, if provided
927 auto commit_secret = _suite.zero();
928 if (commit.path) {
929 const auto& path = opt::get(commit.path);
930
931 if (!valid(path.leaf_node, LeafNodeSource::commit, sender_location)) {
932 throw ProtocolError("Commit path has invalid leaf node");
933 }
934
935 if (!next._tree.parent_hash_valid(sender_location, path)) {
936 throw ProtocolError("Commit path has invalid parent hash");
937 }
938
939 next._tree.merge(sender_location, path);
940
941 auto ctx = tls::marshal(GroupContext{
942 next._suite,
943 next._group_id,
944 next._epoch + 1,
945 next._tree.root_hash(),
946 next._transcript_hash.confirmed,
947 next._extensions,
948 });
949 next._tree_priv.decap(
950 sender_location, next._tree, ctx, path, joiner_locations);
951
952 commit_secret = next._tree_priv.update_secret;
953 }
954
955 // Update the transcripts and advance the key schedule
956 next._transcript_hash.update(content_auth);
957 next._epoch += 1;
958 next.update_epoch_secrets(commit_secret, { psks }, force_init_secret);
959
960 // Verify the confirmation MAC
961 const auto confirmation_tag =
962 next._key_schedule.confirmation_tag(next._transcript_hash.confirmed);
963 if (!content_auth.check_confirmation_tag(confirmation_tag)) {
964 throw ProtocolError("Confirmation failed to verify");
965 }
966
967 return next;
968 }
969
970 ///
971 /// Subgroup branching
972 ///
973
974 // Parameters:
975 // * ctor inputs
976 // * leaf_secret
977 // * commit_opts
978 std::tuple<State, Welcome>
979 State::create_branch(bytes group_id,
980 HPKEPrivateKey enc_priv,
981 SignaturePrivateKey sig_priv,
982 const LeafNode& leaf_node,
983 ExtensionList extensions,
984 const std::vector<KeyPackage>& key_packages,
985 const bytes& leaf_secret,
986 const CommitOpts& commit_opts) const
987 {
988 // Create new empty group with the appropriate PSK
989 auto new_group =
990 State{ std::move(group_id), _suite, std::move(enc_priv),
991 std::move(sig_priv), leaf_node, std::move(extensions) };
992
993 new_group.add_resumption_psk(_group_id, _epoch, _key_schedule.resumption_psk);
994
995 // Create Add proposals
996 auto proposals = stdx::transform<Proposal>(
997 key_packages, [&](const auto& kp) { return new_group.add_proposal(kp); });
998
999 // Create PSK proposal
1000 proposals.push_back({ PreSharedKey{
1001 { ResumptionPSK{ ResumptionPSKUsage::branch, _group_id, _epoch },
1002 random_bytes(_suite.secret_size()) } } });
1003
1004 // Commit the Add and PSK proposals
1005 auto opts = CommitOpts{
1006 proposals,
1007 commit_opts.inline_tree,
1008 commit_opts.force_path,
1009 commit_opts.leaf_node_opts,
1010 };
1011 auto [_commit, welcome, state] = new_group.commit(
1012 leaf_secret, opts, {}, RestartCommitParams{ ResumptionPSKUsage::branch });
1013 return { state, welcome };
1014 }
1015
1016 State
1017 State::handle_branch(const HPKEPrivateKey& init_priv,
1018 HPKEPrivateKey enc_priv,
1019 SignaturePrivateKey sig_priv,
1020 const KeyPackage& key_package,
1021 const Welcome& welcome,
1022 const std::optional<TreeKEMPublicKey>& tree) const
1023 {
1024 auto resumption_psks =
1025 std::map<EpochRef, bytes>{ { { _group_id, _epoch },
1026 _key_schedule.resumption_psk } };
1027 auto branch_state = State{
1028 init_priv,
1029 std::move(enc_priv),
1030 std::move(sig_priv),
1031 key_package,
1032 welcome,
1033 tree,
1034 {},
1035 resumption_psks,
1036 };
1037
1038 if (branch_state._suite != _suite) {
1039 throw ProtocolError("Attempt to branch with a different ciphersuite");
1040 }
1041
1042 if (branch_state._epoch != 1) {
1043 throw ProtocolError("Branch not done at the beginning of the group");
1044 }
1045
1046 return branch_state;
1047 }
1048
1049 State::Tombstone::Tombstone(const State& state_in, ReInit reinit_in)
1050 : epoch_authenticator(state_in.epoch_authenticator())
1051 , reinit(std::move(reinit_in))
1052 , prior_group_id(state_in._group_id)
1053 , prior_epoch(state_in._epoch)
1054 , resumption_psk(state_in._key_schedule.resumption_psk)
1055 {
1056 }
1057
1058 std::tuple<State, Welcome>
1059 State::Tombstone::create_welcome(HPKEPrivateKey enc_priv,
1060 SignaturePrivateKey sig_priv,
1061 const LeafNode& leaf_node,
1062 const std::vector<KeyPackage>& key_packages,
1063 const bytes& leaf_secret,
1064 const CommitOpts& commit_opts) const
1065 {
1066 // Create new empty group with the appropriate PSK
1067 auto new_group =
1068 State{ reinit.group_id, reinit.cipher_suite, std::move(enc_priv),
1069 std::move(sig_priv), leaf_node, reinit.extensions };
1070
1071 new_group.add_resumption_psk(prior_group_id, prior_epoch, resumption_psk);
1072
1073 // Create Add proposals
1074 auto proposals = stdx::transform<Proposal>(
1075 key_packages, [&](const auto& kp) { return new_group.add_proposal(kp); });
1076
1077 // Create PSK proposal
1078 proposals.push_back({ PreSharedKey{
1079 { ResumptionPSK{ ResumptionPSKUsage::reinit, prior_group_id, prior_epoch },
1080 random_bytes(reinit.cipher_suite.secret_size()) } } });
1081
1082 // Commit the Add and PSK proposals
1083 auto opts = CommitOpts{
1084 proposals,
1085 commit_opts.inline_tree,
1086 commit_opts.force_path,
1087 commit_opts.leaf_node_opts,
1088 };
1089 auto [_commit, welcome, state] = new_group.commit(
1090 leaf_secret, opts, {}, RestartCommitParams{ ResumptionPSKUsage::reinit });
1091 return { state, welcome };
1092 }
1093
1094 State
1095 State::Tombstone::handle_welcome(
1096 const HPKEPrivateKey& init_priv,
1097 HPKEPrivateKey enc_priv,
1098 SignaturePrivateKey sig_priv,
1099 const KeyPackage& key_package,
1100 const Welcome& welcome,
1101 const std::optional<TreeKEMPublicKey>& tree) const
1102 {
1103 auto resumption_psks =
1104 std::map<EpochRef, bytes>{ { { prior_group_id, prior_epoch },
1105 resumption_psk } };
1106 auto new_state = State{
1107 init_priv,
1108 std::move(enc_priv),
1109 std::move(sig_priv),
1110 key_package,
1111 welcome,
1112 tree,
1113 {},
1114 resumption_psks,
1115 };
1116
1117 if (new_state._suite != reinit.cipher_suite) {
1118 throw ProtocolError("Attempt to reinit with the wrong ciphersuite");
1119 }
1120
1121 if (new_state._epoch != 1) {
1122 throw ProtocolError("ReInit not done at the beginning of the group");
1123 }
1124
1125 return new_state;
1126 }
1127
1128 std::tuple<State::Tombstone, MLSMessage>
1129 State::reinit_commit(const bytes& leaf_secret,
1130 const std::optional<CommitOpts>& opts,
1131 const MessageOpts& msg_opts)
1132 {
1133 // Ensure that either the proposal cache or the inline proposals have a ReInit
1134 // proposal, and no others.
1135 auto reinit_proposal = Proposal{};
1136 if (_pending_proposals.size() == 1) {
1137 reinit_proposal = _pending_proposals.front().proposal;
1138 } else if (opts && opt::get(opts).extra_proposals.size() == 1) {
1139 reinit_proposal = opt::get(opts).extra_proposals.front();
1140 } else {
1141 throw ProtocolError("Illegal proposals for reinitialization");
1142 }
1143
1144 auto reinit = var::get<ReInit>(reinit_proposal.content);
1145
1146 // Create the commit
1147 const auto [commit_msg, welcome, new_state] =
1148 commit(leaf_secret, opts, msg_opts, ReInitCommitParams{});
1149 silence_unused(welcome);
1150
1151 // Create the Tombstone from the terminal state
1152 return { { new_state, reinit }, commit_msg };
1153 }
1154
1155 State::Tombstone
1156 State::handle_reinit_commit(const MLSMessage& commit_msg)
1157 {
1158 // Verify the signature and process the commit
1159 const auto val_content = unwrap(commit_msg);
1160 const auto& content_auth = val_content.authenticated_content();
1161 if (!verify(content_auth)) {
1162 throw InvalidParameterError("Message signature failed to verify");
1163 }
1164
1165 auto new_state =
1166 opt::get(handle(content_auth, std::nullopt, ReInitCommitParams{}));
1167
1168 // Extract the ReInit and create the Tombstone
1169 const auto& commit = var::get<Commit>(content_auth.content.content);
1170 const auto proposals = must_resolve(commit.proposals, std::nullopt);
1171 if (!valid_reinit(proposals)) {
1172 throw ProtocolError("Invalid proposals for reinit");
1173 }
1174
1175 const auto& reinit_proposal = proposals.front();
1176 const auto& reinit = var::get<ReInit>(reinit_proposal.proposal.content);
1177 return Tombstone{ new_state, reinit };
1178 }
1179
1180 ///
1181 /// Internals
1182 ///
1183
1184 LeafIndex
1185 State::apply(const Add& add)
1186 {
1187 return _tree.add_leaf(add.key_package.leaf_node);
1188 }
1189
1190 void
1191 State::apply(LeafIndex target, const Update& update)
1192 {
1193 _tree.update_leaf(target, update.leaf_node);
1194 }
1195
1196 void
1197 State::apply(LeafIndex target,
1198 const Update& update,
1199 const HPKEPrivateKey& leaf_priv)
1200 {
1201 _tree.update_leaf(target, update.leaf_node);
1202 _tree_priv.set_leaf_priv(leaf_priv);
1203 }
1204
1205 LeafIndex
1206 State::apply(const Remove& remove)
1207 {
1208 if (!_tree.has_leaf(remove.removed)) {
1209 throw ProtocolError("Attempt to remove non-member");
1210 }
1211
1212 _tree.blank_path(remove.removed);
1213 return remove.removed;
1214 }
1215
1216 void
1217 State::apply(const GroupContextExtensions& gce)
1218 {
1219 // TODO(RLB): Update spec to clarify that you MUST verify that the new
1220 // extensions are compatible with all members.
1221 if (!extensions_supported(gce.group_context_extensions)) {
1222 throw ProtocolError("Unsupported extensions in GroupContextExtensions");
1223 }
1224
1225 _extensions = gce.group_context_extensions;
1226 }
1227
1228 bool
1229 State::extensions_supported(const ExtensionList& exts) const
1230 {
1231 return _tree.all_leaves([&](auto /* i */, const auto& leaf_node) {
1232 return leaf_node.verify_extension_support(exts);
1233 });
1234 }
1235
1236 void
1237 State::cache_proposal(AuthenticatedContent content_auth)
1238 {
1239 auto ref = _suite.ref(content_auth);
1240 if (stdx::any_of(_pending_proposals,
1241 [&](const auto& cached) { return cached.ref == ref; })) {
1242 return;
1243 }
1244
1245 auto sender_location = std::optional<LeafIndex>();
1246 if (content_auth.content.sender.sender_type() == SenderType::member) {
1247 const auto& sender = content_auth.content.sender.sender;
1248 sender_location = var::get<MemberSender>(sender).sender;
1249 }
1250
1251 const auto& proposal = var::get<Proposal>(content_auth.content.content);
1252
1253 if (content_auth.content.sender.sender_type() == SenderType::external &&
1254 !valid_external_proposal_type(proposal.proposal_type())) {
1255 throw ProtocolError("Invalid external proposal");
1256 }
1257
1258 if (!valid(sender_location, proposal)) {
1259 throw ProtocolError("Invalid proposal");
1260 }
1261
1262 _pending_proposals.push_back({
1263 _suite.ref(content_auth),
1264 proposal,
1265 sender_location,
1266 });
1267 }
1268
1269 std::optional<State::CachedProposal>
1270 State::resolve(const ProposalOrRef& id,
1271 std::optional<LeafIndex> sender_index) const
1272 {
1273 if (var::holds_alternative<Proposal>(id.content)) {
1274 return CachedProposal{
1275 {},
1276 var::get<Proposal>(id.content),
1277 sender_index,
1278 };
1279 }
1280
1281 const auto& ref = var::get<ProposalRef>(id.content);
1282 for (const auto& cached : _pending_proposals) {
1283 if (cached.ref == ref) {
1284 return cached;
1285 }
1286 }
1287
1288 return std::nullopt;
1289 }
1290
1291 std::vector<State::CachedProposal>
1292 // NOLINTNEXTLINE(readability-convert-member-functions-to-static)
1293 State::must_resolve(const std::vector<ProposalOrRef>& ids,
1294 std::optional<LeafIndex> sender_index) const
1295 {
1296 auto must_resolve = [&](const auto& id) {
1297 return opt::get(resolve(id, sender_index));
1298 };
1299 return stdx::transform<CachedProposal>(ids, must_resolve);
1300 }
1301
1302 std::vector<PSKWithSecret>
1303 State::resolve(const std::vector<PreSharedKeyID>& psks) const
1304 {
1305 return stdx::transform<PSKWithSecret>(psks, [&](const auto& psk_id) {
1306 auto get_secret = overloaded{
1307 [&](const ExternalPSK& ext_psk) {
1308 if (_external_psks.count(ext_psk.psk_id) == 0) {
1309 throw ProtocolError("Unknown external PSK");
1310 }
1311
1312 return _external_psks.at(ext_psk.psk_id);
1313 },
1314
1315 [&](const ResumptionPSK& res_psk) {
1316 if (res_psk.psk_epoch == _epoch) {
1317 return _key_schedule.resumption_psk;
1318 }
1319
1320 auto key = std::make_tuple(res_psk.psk_group_id, res_psk.psk_epoch);
1321 if (_resumption_psks.count(key) == 0) {
1322 throw ProtocolError("Unknown Resumption PSK");
1323 }
1324
1325 return _resumption_psks.at(key);
1326 },
1327 };
1328
1329 auto secret = var::visit(get_secret, psk_id.content);
1330 return PSKWithSecret{ psk_id, secret };
1331 });
1332 }
1333
1334 std::vector<LeafIndex>
1335 State::apply(const std::vector<CachedProposal>& proposals,
1336 Proposal::Type required_type)
1337 {
1338 auto locations = std::vector<LeafIndex>{};
1339 for (const auto& cached : proposals) {
1340 auto proposal_type = cached.proposal.proposal_type();
1341 if (proposal_type != required_type) {
1342 continue;
1343 }
1344
1345 switch (proposal_type) {
1346 case ProposalType::add: {
1347 locations.push_back(apply(var::get<Add>(cached.proposal.content)));
1348 break;
1349 }
1350
1351 case ProposalType::update: {
1352 const auto& update = var::get<Update>(cached.proposal.content);
1353
1354 if (!cached.sender) {
1355 throw ProtocolError("Update without target leaf");
1356 }
1357
1358 auto target = opt::get(cached.sender);
1359 if (target != _index) {
1360 apply(target, update);
1361 break;
1362 }
1363
1364 if (!_cached_update) {
1365 throw ProtocolError("Self-update with no cached secret");
1366 }
1367
1368 const auto& cached_update = opt::get(_cached_update);
1369 if (update != cached_update.proposal) {
1370 throw ProtocolError("Self-update does not match cached data");
1371 }
1372
1373 apply(target, update, cached_update.update_priv);
1374 locations.push_back(target);
1375 break;
1376 }
1377
1378 case ProposalType::remove: {
1379 const auto& remove = var::get<Remove>(cached.proposal.content);
1380 locations.push_back(apply(remove));
1381 break;
1382 }
1383
1384 case ProposalType::group_context_extensions: {
1385 const auto& gce =
1386 var::get<GroupContextExtensions>(cached.proposal.content);
1387 apply(gce);
1388 break;
1389 }
1390
1391 default:
1392 throw ProtocolError("Unsupported proposal type");
1393 }
1394 }
1395
1396 // The cached update needs to be reset after applying proposals, so that it is
1397 // in a clean state for the next epoch.
1398 _cached_update.reset();
1399
1400 return locations;
1401 }
1402
1403 std::tuple<std::vector<LeafIndex>, std::vector<PSKWithSecret>>
1404 State::apply(const std::vector<CachedProposal>& proposals)
1405 {
1406 apply(proposals, ProposalType::update);
1407 apply(proposals, ProposalType::remove);
1408 auto joiner_locations = apply(proposals, ProposalType::add);
1409 apply(proposals, ProposalType::group_context_extensions);
1410
1411 // Extract the PSK proposals and look up the secrets
1412 // TODO(RLB): Factor this out, and also factor the above methods into
1413 // apply_update, apply_remove, etc.
1414 auto psk_ids = std::vector<PreSharedKeyID>{};
1415 for (const auto& cached : proposals) {
1416 if (cached.proposal.proposal_type() != ProposalType::psk) {
1417 continue;
1418 }
1419
1420 const auto& proposal = var::get<PreSharedKey>(cached.proposal.content);
1421 psk_ids.push_back(proposal.psk);
1422 }
1423 auto psks = resolve(psk_ids);
1424
1425 _tree.truncate();
1426 _tree_priv.truncate(_tree.size);
1427 _tree.set_hash_all();
1428 return { joiner_locations, psks };
1429 }
1430
1431 ///
1432 /// Message protection
1433 ///
1434
1435 MLSMessage
1436 State::protect(const bytes& authenticated_data,
1437 const bytes& pt,
1438 size_t padding_size)
1439 {
1440 auto msg_opts = MessageOpts{ true, authenticated_data, padding_size };
1441 return protect_full(ApplicationData{ pt }, msg_opts);
1442 }
1443
1444 std::tuple<bytes, bytes>
1445 State::unprotect(const MLSMessage& ct)
1446 {
1447 const auto val_content = unwrap(ct);
1448 const auto& content_auth = val_content.authenticated_content();
1449
1450 if (!verify(content_auth)) {
1451 throw InvalidParameterError("Message signature failed to verify");
1452 }
1453
1454 if (content_auth.content.content_type() != ContentType::application) {
1455 throw ProtocolError("Unprotect of handshake message");
1456 }
1457
1458 if (content_auth.wire_format != WireFormat::mls_private_message) {
1459 throw ProtocolError("Application data not sent as PrivateMessage");
1460 }
1461
1462 return {
1463 content_auth.content.authenticated_data,
1464 var::get<ApplicationData>(content_auth.content.content).data,
1465 };
1466 }
1467
1468 ///
1469 /// Properties of a proposal list
1470 ///
1471
1472 bool
1473 State::valid(const LeafNode& leaf_node,
1474 LeafNodeSource required_source,
1475 std::optional<LeafIndex> index) const
1476 {
1477 // Verify that the credential in the LeafNode is valid as described in Section
1478 // 5.3.1.
1479 // XXX(RLB) N/A, no credential validation in the library right now
1480
1481 // Verify the leaf_node_source field:
1482 const auto correct_source = (leaf_node.source() == required_source);
1483
1484 // Verify that the signature on the LeafNode is valid using signature_key.
1485 auto binding = std::optional<LeafNode::MemberBinding>{};
1486 switch (required_source) {
1487 case LeafNodeSource::commit:
1488 case LeafNodeSource::update:
1489 binding = LeafNode::MemberBinding{ _group_id, opt::get(index) };
1490 break;
1491
1492 default:
1493 // Nothing to do
1494 break;
1495 }
1496
1497 const auto signature_valid = leaf_node.verify(_suite, binding);
1498
1499 // Verify that the LeafNode is compatible with the group's parameters. If the
1500 // GroupContext has a required_capabilities extension, then the required
1501 // extensions, proposals, and credential types MUST be listed in the
1502 // LeafNode's capabilities field.
1503 const auto supports_group_extensions =
1504 leaf_node.verify_extension_support(_extensions);
1505
1506 // TODO(RLB) Verify the lifetime field
1507
1508 // Verify that the credential type is supported by all members of the group,
1509 // as specified by the capabilities field of each member's LeafNode, and that
1510 // the capabilities field of this LeafNode indicates support for all the
1511 // credential types currently in use by other members.
1512 //
1513 // Verify that the following fields are unique among the members of the group:
1514 // signature_key
1515 // encryption_key
1516 //
1517 // Note: Uniqueness of signature and encryption keys is assured by the
1518 // tree operations (add/update), so we do not need to verify those here.
1519 const auto mutual_credential_support =
1520 _tree.all_leaves([&](auto /* i */, const auto& leaf) {
1521 return leaf.capabilities.credential_supported(leaf_node.credential) &&
1522 leaf_node.capabilities.credential_supported(leaf.credential);
1523 });
1524
1525 // Verify that the extensions in the LeafNode are supported by checking that
1526 // the ID for each extension in the extensions field is listed in the
1527 // capabilities.extensions field of the LeafNode.
1528 auto supports_own_extensions =
1529 leaf_node.verify_extension_support(leaf_node.extensions);
1530
1531 return (signature_valid && supports_group_extensions && correct_source &&
1532 mutual_credential_support && supports_own_extensions);
1533 }
1534
1535 bool
1536 State::valid(const KeyPackage& key_package) const
1537 {
1538 // Verify that the ciphersuite and protocol version of the KeyPackage match
1539 // those in the GroupContext.
1540 const auto correct_ciphersuite = (key_package.cipher_suite == _suite);
1541
1542 // Verify that the signature on the KeyPackage is valid using the public key
1543 // in leaf_node.credential.
1544 const auto valid_signature = key_package.verify();
1545
1546 // Verify that the leaf_node of the KeyPackage is valid for a KeyPackage
1547 // according to Section 7.3.
1548 const auto leaf_node_valid =
1549 valid(key_package.leaf_node, LeafNodeSource::key_package, std::nullopt);
1550
1551 // Verify that the value of leaf_node.encryption_key is different from the
1552 // value of the init_key field.
1553 const auto distinct_keys =
1554 (key_package.init_key != key_package.leaf_node.encryption_key);
1555
1556 return (correct_ciphersuite && valid_signature && leaf_node_valid &&
1557 distinct_keys);
1558 }
1559
1560 bool
1561 State::valid(const Add& add) const
1562 {
1563 return valid(add.key_package);
1564 }
1565
1566 bool
1567 State::valid(LeafIndex sender, const Update& update) const
1568 {
1569 const auto maybe_leaf = _tree.leaf_node(sender);
1570 if (!maybe_leaf) {
1571 return false;
1572 }
1573
1574 return valid(update.leaf_node, LeafNodeSource::update, sender);
1575 }
1576
1577 bool
1578 State::valid(const Remove& remove) const
1579 {
1580 // We mark self-removes invalid here even though a resync Commit will
1581 // sometimes cause them. This is OK because this method is only called from
1582 // the normal proposal list validation method, not the external commit one.
1583 auto in_tree = remove.removed < _tree.size && _tree.has_leaf(remove.removed);
1584 auto not_me = remove.removed != _index;
1585 return in_tree && not_me;
1586 }
1587
1588 bool
1589 State::valid(const PreSharedKey& psk) const
1590 {
1591 // External PSKs are allowed if we have the corresponding secret
1592 if (var::holds_alternative<ExternalPSK>(psk.psk.content)) {
1593 const auto& ext_psk = var::get<ExternalPSK>(psk.psk.content);
1594 return _external_psks.count(ext_psk.psk_id) > 0;
1595 }
1596
1597 // Resumption PSKs are allowed only with usage 'application', and only if we
1598 // have the corresponding secret.
1599 if (var::holds_alternative<ResumptionPSK>(psk.psk.content)) {
1600 const auto& res_psk = var::get<ResumptionPSK>(psk.psk.content);
1601 if (res_psk.usage != ResumptionPSKUsage::application) {
1602 return false;
1603 }
1604
1605 const auto key = std::make_tuple(res_psk.psk_group_id, res_psk.psk_epoch);
1606 return res_psk.psk_epoch == _epoch || _resumption_psks.count(key) > 0;
1607 }
1608
1609 return false;
1610 }
1611
1612 bool
1613 State::valid(const ReInit& reinit)
1614 {
1615 // Check that the version and CipherSuite are ones we support
1616 auto supported_version = (reinit.version == ProtocolVersion::mls10);
1617 auto supported_suite =
1618 stdx::contains(all_supported_suites, reinit.cipher_suite.cipher_suite());
1619
1620 return supported_version && supported_suite;
1621 }
1622
1623 bool
1624 State::valid(const ExternalInit& external_init) const
1625 {
1626 return external_init.kem_output.size() == _suite.hpke().kem.enc_size;
1627 }
1628
1629 bool
1630 State::valid(const GroupContextExtensions& gce) const
1631 {
1632 return extensions_supported(gce.group_context_extensions);
1633 }
1634
1635 bool
1636 State::valid(std::optional<LeafIndex> sender, const Proposal& proposal) const
1637 {
1638 const auto specifically_valid = overloaded{
1639 [&](const Update& update) { return valid(opt::get(sender), update); },
1640 [&](const auto& proposal) { return valid(proposal); },
1641 };
1642 return var::visit(specifically_valid, proposal.content);
1643 }
1644
1645 bool
1646 State::valid(const std::vector<CachedProposal>& proposals,
1647 LeafIndex commit_sender,
1648 const CommitParams& params) const
1649 {
1650 auto specifically = overloaded{
1651 [&](const NormalCommitParams& /* unused */) {
1652 return valid_normal(proposals, commit_sender);
1653 },
1654 [&](const ExternalCommitParams& /* unused */) {
1655 return valid_external(proposals);
1656 },
1657 [&](const RestartCommitParams& params) {
1658 return valid_restart(proposals, params.allowed_usage);
1659 },
1660 [&](const ReInitCommitParams& /* unused */) {
1661 return valid_reinit(proposals);
1662 },
1663 };
1664
1665 return var::visit(specifically, params);
1666 }
1667
1668 bool
1669 // NB(RLB): clang-tidy thinks this can be static, but it can't.
1670 // NOLINTNEXTLINE(readability-convert-member-functions-to-static)
1671 State::valid_normal(const std::vector<CachedProposal>& proposals,
1672 LeafIndex commit_sender) const
1673 {
1674 // It contains an individual proposal that is invalid as specified in Section
1675 // 12.1.
1676 const auto has_invalid_proposal =
1677 stdx::any_of(proposals, [&](const auto& cached) {
1678 return !valid(cached.sender, cached.proposal);
1679 });
1680
1681 // It contains an Update proposal generated by the committer.
1682 const auto has_self_update = stdx::any_of(proposals, [&](const auto& cached) {
1683 return cached.proposal.proposal_type() == ProposalType::update &&
1684 cached.sender == commit_sender;
1685 });
1686
1687 // It contains a Remove proposal that removes the committer.
1688 const auto has_self_remove = stdx::any_of(proposals, [&](const auto& cached) {
1689 return cached.proposal.proposal_type() == ProposalType::remove &&
1690 var::get<Remove>(cached.proposal.content).removed == commit_sender;
1691 });
1692
1693 // It contains multiple Update and/or Remove proposals that apply to the same
1694 // leaf. If the committer has received multiple such proposals they SHOULD
1695 // prefer any Remove received, or the most recent Update if there are no
1696 // Removes.
1697 auto updated_or_removed = std::set<LeafIndex>{};
1698 const auto has_dup_update_remove =
1699 stdx::any_of(proposals, [&](const auto& cached) {
1700 auto index = LeafIndex{ 0 };
1701 switch (cached.proposal.proposal_type()) {
1702 case ProposalType::update:
1703 index = opt::get(cached.sender);
1704 break;
1705
1706 case ProposalType::remove:
1707 index = var::get<Remove>(cached.proposal.content).removed;
1708 break;
1709
1710 default:
1711 return false;
1712 }
1713
1714 if (stdx::contains(updated_or_removed, index)) {
1715 return true;
1716 }
1717
1718 updated_or_removed.insert(index);
1719 return false;
1720 });
1721
1722 // It contains multiple Add proposals that contain KeyPackages that represent
1723 // the same client according to the application (for example, identical
1724 // signature keys).
1725 auto signature_keys = std::vector<SignaturePublicKey>{};
1726 const auto has_dup_signature_key =
1727 stdx::any_of(proposals, [&](const auto& cached) {
1728 if (cached.proposal.proposal_type() != ProposalType::add) {
1729 return false;
1730 }
1731
1732 auto key_package = var::get<Add>(cached.proposal.content).key_package;
1733 auto signature_key = key_package.leaf_node.signature_key;
1734 if (stdx::contains(signature_keys, signature_key)) {
1735 return true;
1736 }
1737
1738 signature_keys.push_back(signature_key);
1739 return false;
1740 });
1741
1742 // It contains an Add proposal with a KeyPackage that represents a client
1743 // already in the group according to the application, unless there is a Remove
1744 // proposal in the list removing the matching client from the group.
1745 // TODO(RLB)
1746
1747 // It contains multiple PreSharedKey proposals that reference the same
1748 // PreSharedKeyID.
1749 auto psk_ids = std::vector<PreSharedKeyID>{};
1750 const auto has_dup_psk_id = stdx::any_of(proposals, [&](const auto& cached) {
1751 if (cached.proposal.proposal_type() != ProposalType::psk) {
1752 return false;
1753 }
1754
1755 auto psk_id = var::get<PreSharedKey>(cached.proposal.content).psk;
1756 if (stdx::contains(psk_ids, psk_id)) {
1757 return true;
1758 }
1759
1760 psk_ids.push_back(psk_id);
1761 return false;
1762 });
1763
1764 // It contains multiple GroupContextExtensions proposals.
1765 const auto gce_count = stdx::count_if(proposals, [](const auto& cached) {
1766 return cached.proposal.proposal_type() ==
1767 ProposalType::group_context_extensions;
1768 });
1769 const auto has_multiple_gce = (gce_count > 1);
1770
1771 // It contains a ReInit proposal together with any other proposal. If the
1772 // committer has received other proposals during the epoch, they SHOULD prefer
1773 // them over the ReInit proposal, allowing the ReInit to be resent and applied
1774 // in a subsequent epoch.
1775 const auto has_reinit = stdx::any_of(proposals, [](const auto& cached) {
1776 return cached.proposal.proposal_type() == ProposalType::reinit;
1777 });
1778
1779 // It contains an ExternalInit proposal.
1780 const auto has_external_init =
1781 stdx::any_of(proposals, [](const auto& cached) {
1782 return cached.proposal.proposal_type() == ProposalType::external_init;
1783 });
1784
1785 // It contains a proposal with a non-default proposal type that is not
1786 // supported by some members of the group that will process the Commit (i.e.,
1787 // members being added or removed by the Commit do not need to support the
1788 // proposal type).
1789 // XXX(RLB): N/A, no non-default proposal types
1790
1791 // After processing the commit the ratchet tree is invalid, in particular, if
1792 // it contains any leaf node that is invalid according to Section 7.3.
1793 //
1794 // NB(RLB): Leaf nodes are already checked in the individual proposal check at
1795 // the top. So the focus here is key uniqueness. We check this by checking
1796 // uniqueness of encryption keys across the Adds and Updates in this list of
1797 // proposals. The keys have already been checked to be distinct from any keys
1798 // already in the tree.
1799 auto enc_keys = std::vector<HPKEPublicKey>{};
1800 const auto has_dup_enc_key = stdx::any_of(proposals, [&](const auto& cached) {
1801 const auto get_enc_key =
1802 overloaded{ [](const Add& add) -> std::optional<HPKEPublicKey> {
1803 return add.key_package.leaf_node.encryption_key;
1804 },
1805 [](const Update& update) -> std::optional<HPKEPublicKey> {
1806 return update.leaf_node.encryption_key;
1807 },
1808
1809 [](const auto& /* default */)
1810 -> std::optional<HPKEPublicKey> { return std::nullopt; } };
1811 auto maybe_enc_key = var::visit(get_enc_key, cached.proposal.content);
1812 if (!maybe_enc_key) {
1813 return false;
1814 }
1815
1816 const auto& enc_key = opt::get(maybe_enc_key);
1817 if (stdx::contains(enc_keys, enc_key)) {
1818 return true;
1819 }
1820
1821 enc_keys.push_back(enc_key);
1822 return false;
1823 });
1824
1825 return !(has_invalid_proposal || has_self_update || has_self_remove ||
1826 has_dup_update_remove || has_dup_signature_key || has_dup_psk_id ||
1827 has_multiple_gce || has_reinit || has_external_init ||
1828 has_dup_enc_key);
1829 }
1830
1831 bool
1832 State::valid_reinit(const std::vector<CachedProposal>& proposals)
1833 {
1834 // Check that the list contains a ReInit proposal
1835 const auto has_reinit = stdx::any_of(proposals, [](const auto& cached) {
1836 return cached.proposal.proposal_type() == ProposalType::reinit;
1837 });
1838
1839 // Check whether the list contains any disallowed proposals
1840 const auto has_disallowed = stdx::any_of(proposals, [](const auto& cached) {
1841 return cached.proposal.proposal_type() != ProposalType::reinit;
1842 });
1843
1844 return has_reinit && !has_disallowed;
1845 }
1846
1847 bool
1848 State::valid_restart(const std::vector<CachedProposal>& proposals,
1849 ResumptionPSKUsage allowed_usage)
1850 {
1851 // Check that the list has exactly one resumption PSK proposal with the
1852 // allowed usage and any other PSKs are external
1853 auto found_allowed = false;
1854 const auto acceptable_psks = stdx::all_of(proposals, [&](const auto& cached) {
1855 if (cached.proposal.proposal_type() != ProposalType::psk) {
1856 return true;
1857 }
1858
1859 const auto& psk = var::get<PreSharedKey>(cached.proposal.content);
1860 if (var::holds_alternative<ExternalPSK>(psk.psk.content)) {
1861 return true;
1862 }
1863
1864 const auto& res_psk = var::get<ResumptionPSK>(psk.psk.content);
1865 const auto allowed = res_psk.usage == allowed_usage;
1866 if (found_allowed && allowed) {
1867 return false;
1868 }
1869
1870 found_allowed = found_allowed || allowed;
1871 return true;
1872 });
1873
1874 return acceptable_psks && found_allowed;
1875 }
1876
1877 bool
1878 State::valid_external_proposal_type(const Proposal::Type proposal_type)
1879 {
1880 switch (proposal_type) {
1881 case ProposalType::add:
1882 case ProposalType::remove:
1883 case ProposalType::psk:
1884 case ProposalType::reinit:
1885 case ProposalType::group_context_extensions:
1886 return true;
1887
1888 default:
1889 return false;
1890 }
1891 }
1892
1893 bool
1894 // NOLINTNEXTLINE(readability-convert-member-functions-to-static)
1895 State::valid_external(const std::vector<CachedProposal>& proposals) const
1896 {
1897 // Exactly one ExternalInit
1898 auto ext_init_count = stdx::count_if(proposals, [](const auto& cached) {
1899 return cached.proposal.proposal_type() == ProposalType::external_init;
1900 });
1901 auto one_ext_init = (ext_init_count == 1);
1902
1903 // At most one Remove proposal, with which the joiner removes an old version
1904 // of themselves. If a Remove proposal is present, then the LeafNode in the
1905 // path field of the external commit MUST meet the same criteria as would the
1906 // LeafNode in an Update for the removed leaf (see Section 12.1.2). In
1907 // particular, the credential in the LeafNode MUST present a set of
1908 // identifiers that is acceptable to the application for the removed
1909 // participant.
1910 // TODO(RLB) Verify that Remove is properly formed
1911 auto remove_count = stdx::count_if(proposals, [](const auto& cached) {
1912 return cached.proposal.proposal_type() == ProposalType::remove;
1913 });
1914 auto no_dup_remove = (remove_count <= 1);
1915
1916 // Zero or more PreSharedKey proposals.
1917 // No other proposals.
1918 auto no_disallowed = stdx::all_of(proposals, [&](const auto& cached) {
1919 switch (cached.proposal.proposal_type()) {
1920 case ProposalType::external_init:
1921 case ProposalType::remove:
1922 return true;
1923
1924 case ProposalType::psk:
1925 return valid(var::get<PreSharedKey>(cached.proposal.content));
1926
1927 default:
1928 return false;
1929 }
1930 });
1931
1932 return one_ext_init && no_dup_remove && no_disallowed;
1933 }
1934
1935 State::CommitParams
1936 State::infer_commit_type(
1937 const std::optional<LeafIndex>& sender,
1938 const std::vector<CachedProposal>& proposals,
1939 const std::optional<CommitParams>& expected_params) const
1940 {
1941 // If an expected type was provided, validate against it
1942 if (expected_params) {
1943 const auto& expected = opt::get(expected_params);
1944
1945 auto specifically = overloaded{
1946 [&](const NormalCommitParams& /* unused */) {
1947 return sender && valid_normal(proposals, opt::get(sender));
1948 },
1949 [&](const ExternalCommitParams& /* unused */) {
1950 return !sender && valid_external(proposals);
1951 },
1952 [&](const RestartCommitParams& params) {
1953 return sender && valid_restart(proposals, params.allowed_usage);
1954 },
1955 [&](const ReInitCommitParams& /* unused */) {
1956 return sender && valid_reinit(proposals);
1957 },
1958 };
1959
1960 if (!var::visit(specifically, expected)) {
1961 throw ProtocolError("Invalid proposal list");
1962 }
1963
1964 return expected;
1965 }
1966
1967 // Otherwise, check to see if this is a valid external or normal commit
1968 if (!sender && valid_external(proposals)) {
1969 return ExternalCommitParams{};
1970 }
1971
1972 if (sender && valid_normal(proposals, opt::get(sender))) {
1973 return NormalCommitParams{};
1974 }
1975
1976 throw ProtocolError("Invalid proposal list");
1977 }
1978
1979 bool
1980 State::path_required(const std::vector<CachedProposal>& proposals)
1981 {
1982 static const auto path_required_types = std::set<Proposal::Type>{
1983 ProposalType::update,
1984 ProposalType::remove,
1985 ProposalType::external_init,
1986 ProposalType::group_context_extensions,
1987 };
1988
1989 if (proposals.empty()) {
1990 return true;
1991 }
1992
1993 return stdx::any_of(proposals, [](const auto& cp) {
1994 return path_required_types.count(cp.proposal.proposal_type()) != 0;
1995 });
1996 }
1997
1998 ///
1999 /// Inner logic and convenience functions
2000 ///
2001
2002 bool
2003 operator==(const State& lhs, const State& rhs)
2004 {
2005 auto suite = (lhs._suite == rhs._suite);
2006 auto group_id = (lhs._group_id == rhs._group_id);
2007 auto epoch = (lhs._epoch == rhs._epoch);
2008 auto tree = (lhs._tree == rhs._tree);
2009 auto transcript_hash = (lhs._transcript_hash == rhs._transcript_hash);
2010 auto key_schedule = (lhs._key_schedule == rhs._key_schedule);
2011 auto extensions = (lhs._extensions == rhs._extensions);
2012
2013 return suite && group_id && epoch && tree && transcript_hash &&
2014 key_schedule && extensions;
2015 }
2016
2017 bool
2018 operator!=(const State& lhs, const State& rhs)
2019 {
2020 return !(lhs == rhs);
2021 }
2022
2023 void
2024 State::update_epoch_secrets(const bytes& commit_secret,
2025 const std::vector<PSKWithSecret>& psks,
2026 const std::optional<bytes>& force_init_secret)
2027 {
2028 auto ctx = tls::marshal(GroupContext{
2029 _suite,
2030 _group_id,
2031 _epoch,
2032 _tree.root_hash(),
2033 _transcript_hash.confirmed,
2034 _extensions,
2035 });
2036 _key_schedule =
2037 _key_schedule.next(commit_secret, psks, force_init_secret, ctx);
2038 _keys = _key_schedule.encryption_keys(_tree.size);
2039 }
2040
2041 ///
2042 /// Message encryption and decryption
2043 ///
2044 bool
2045 State::verify_internal(const AuthenticatedContent& content_auth) const
2046 {
2047 const auto& sender =
2048 var::get<MemberSender>(content_auth.content.sender.sender).sender;
2049 auto maybe_leaf = _tree.leaf_node(sender);
2050 if (!maybe_leaf) {
2051 throw InvalidParameterError("Signature from blank node");
2052 }
2053
2054 const auto& pub = opt::get(maybe_leaf).signature_key;
2055 return content_auth.verify(_suite, pub, group_context());
2056 }
2057
2058 bool
2059 State::verify_external(const AuthenticatedContent& content_auth) const
2060 {
2061 const auto& ext_sender =
2062 var::get<ExternalSenderIndex>(content_auth.content.sender.sender);
2063 const auto senders_ext = _extensions.find<ExternalSendersExtension>();
2064 const auto& senders = opt::get(senders_ext).senders;
2065 const auto& pub = senders.at(ext_sender.sender_index).signature_key;
2066 return content_auth.verify(_suite, pub, group_context());
2067 }
2068
2069 bool
2070 State::verify_new_member_proposal(
2071 const AuthenticatedContent& content_auth) const
2072 {
2073 const auto& proposal = var::get<Proposal>(content_auth.content.content);
2074 const auto& add = var::get<Add>(proposal.content);
2075 const auto& pub = add.key_package.leaf_node.signature_key;
2076 return content_auth.verify(_suite, pub, group_context());
2077 }
2078
2079 bool
2080 State::verify_new_member_commit(const AuthenticatedContent& content_auth) const
2081 {
2082 const auto& commit = var::get<Commit>(content_auth.content.content);
2083 const auto& path = opt::get(commit.path);
2084 const auto& pub = path.leaf_node.signature_key;
2085 return content_auth.verify(_suite, pub, group_context());
2086 }
2087
2088 bool
2089 State::verify(const AuthenticatedContent& content_auth) const
2090 {
2091 switch (content_auth.content.sender.sender_type()) {
2092 case SenderType::member:
2093 return verify_internal(content_auth);
2094
2095 case SenderType::external:
2096 return verify_external(content_auth);
2097
2098 case SenderType::new_member_proposal:
2099 return verify_new_member_proposal(content_auth);
2100
2101 case SenderType::new_member_commit:
2102 return verify_new_member_commit(content_auth);
2103
2104 default:
2105 throw ProtocolError("Invalid sender type");
2106 }
2107 }
2108
2109 void
2110 State::add_resumption_psk(const bytes& group_id, epoch_t epoch, bytes secret)
2111 {
2112 _resumption_psks.insert_or_assign({ group_id, epoch }, std::move(secret));
2113 }
2114
2115 void
2116 State::remove_resumption_psk(const bytes& group_id, epoch_t epoch)
2117 {
2118 _resumption_psks.erase({ group_id, epoch });
2119 }
2120
2121 void
2122 State::add_external_psk(const bytes& id, const bytes& secret)
2123 {
2124 _external_psks.insert_or_assign(id, secret);
2125 }
2126
2127 void
2128 State::remove_external_psk(const bytes& id)
2129 {
2130 _external_psks.erase(id);
2131 }
2132
2133 bytes
2134 State::do_export(const std::string& label,
2135 const bytes& context,
2136 size_t size) const
2137 {
2138 return _key_schedule.do_export(label, context, size);
2139 }
2140
2141 GroupInfo
2142 State::group_info(bool inline_tree) const
2143 {
2144 auto group_info = GroupInfo{
2145 {
2146 _suite,
2147 _group_id,
2148 _epoch,
2149 _tree.root_hash(),
2150 _transcript_hash.confirmed,
2151 _extensions,
2152 },
2153 { /* No other extensions */ },
2154 _key_schedule.confirmation_tag(_transcript_hash.confirmed),
2155 };
2156
2157 group_info.extensions.add(
2158 ExternalPubExtension{ _key_schedule.external_priv.public_key });
2159
2160 if (inline_tree) {
2161 group_info.extensions.add(RatchetTreeExtension{ _tree });
2162 }
2163
2164 group_info.sign(_tree, _index, _identity_priv);
2165 return group_info;
2166 }
2167
2168 std::vector<LeafNode>
2169 State::roster() const
2170 {
2171 auto leaves = std::vector<LeafNode>{};
2172 leaves.reserve(_tree.size.val);
2173
2174 _tree.all_leaves([&](auto /* i */, auto leaf) {
2175 leaves.push_back(leaf);
2176 return true;
2177 });
2178
2179 return leaves;
2180 }
2181
2182 bytes
2183 State::epoch_authenticator() const
2184 {
2185 return _key_schedule.epoch_authenticator;
2186 }
2187
2188 LeafIndex
2189 State::leaf_for_roster_entry(RosterIndex index) const
2190 {
2191 auto visited = RosterIndex{ 0 };
2192 auto found = std::optional<LeafIndex>{};
2193 _tree.all_leaves([&](auto i, const auto& /* leaf_node */) {
2194 if (visited == index) {
2195 found = i;
2196 return false;
2197 }
2198
2199 visited.val += 1;
2200 return true;
2201 });
2202
2203 return opt::get(found);
2204 }
2205
2206 State
2207 State::successor() const
2208 {
2209 // Copy everything, then clear things that shouldn't be copied
2210 auto next = *this;
2211 next._pending_proposals.clear();
2212
2213 // Copy forward a resumption PSK
2214 next.add_resumption_psk(_group_id, _epoch, _key_schedule.resumption_psk);
2215
2216 return next;
2217 }
2218
2219 } // namespace mlspp