Debian Codegraph @

third_party/rust/mls-rs/src/group/mod.rs

raw
1 // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2 // Copyright by contributors to this project.
3 // SPDX-License-Identifier: (Apache-2.0 OR MIT)
4
5 use alloc::vec;
6 use alloc::vec::Vec;
7 use core::fmt::{self, Debug};
8 use mls_rs_codec::{MlsDecode, MlsEncode, MlsSize};
9 use mls_rs_core::error::IntoAnyError;
10 #[cfg(feature = "last_resort_key_package_ext")]
11 use mls_rs_core::extension::MlsExtension;
12 use mls_rs_core::identity::MemberValidationContext;
13 use mls_rs_core::secret::Secret;
14 use mls_rs_core::time::MlsTime;
15 use snapshot::PendingCommitSnapshot;
16
17 use crate::cipher_suite::CipherSuite;
18 use crate::client::MlsError;
19 use crate::client_config::ClientConfig;
20 use crate::crypto::{HpkeCiphertext, SignatureSecretKey};
21 #[cfg(feature = "last_resort_key_package_ext")]
22 use crate::extension::LastResortKeyPackageExt;
23 use crate::extension::RatchetTreeExt;
24 use crate::identity::SigningIdentity;
25 use crate::key_package::{KeyPackage, KeyPackageGeneration, KeyPackageRef};
26 use crate::protocol_version::ProtocolVersion;
27 use crate::psk::secret::PskSecret;
28 use crate::psk::PreSharedKeyID;
29 use crate::signer::Signable;
30 use crate::tree_kem::hpke_encryption::HpkeEncryptable;
31 use crate::tree_kem::kem::TreeKem;
32 use crate::tree_kem::leaf_node::LeafNode;
33 use crate::tree_kem::leaf_node_validator::{LeafNodeValidator, ValidationContext};
34 use crate::tree_kem::node::LeafIndex;
35 use crate::tree_kem::path_secret::PathSecret;
36 pub use crate::tree_kem::Capabilities;
37 use crate::tree_kem::{math as tree_math, ValidatedUpdatePath};
38 use crate::tree_kem::{TreeKemPrivate, TreeKemPublic};
39 use crate::{CipherSuiteProvider, CryptoProvider};
40 pub use state::GroupState;
41
42 #[cfg(feature = "by_ref_proposal")]
43 use crate::crypto::{HpkePublicKey, HpkeSecretKey};
44
45 use crate::extension::ExternalPubExt;
46
47 use self::message_hash::MessageHash;
48 #[cfg(feature = "private_message")]
49 use self::mls_rules::{EncryptionOptions, MlsRules};
50
51 #[cfg(feature = "psk")]
52 pub use self::resumption::ReinitClient;
53
54 #[cfg(feature = "psk")]
55 use crate::psk::{
56 resolver::PskResolver, secret::PskSecretInput, ExternalPskId, JustPreSharedKeyID, PskGroupId,
57 ResumptionPSKUsage, ResumptionPsk,
58 };
59
60 #[cfg(feature = "private_message")]
61 use ciphertext_processor::*;
62
63 use component_operation::{ComponentID, ComponentOperationLabel};
64 use confirmation_tag::*;
65 use framing::*;
66 use key_schedule::*;
67 use membership_tag::*;
68 use message_signature::*;
69 use message_verifier::*;
70 use proposal::*;
71 #[cfg(feature = "by_ref_proposal")]
72 use proposal_cache::*;
73 use transcript_hash::*;
74
75 #[cfg(test)]
76 pub(crate) use self::commit::test_utils::CommitModifiers;
77
78 #[cfg(all(test, feature = "private_message"))]
79 pub use self::framing::PrivateMessage;
80
81 use self::proposal_filter::ProposalInfo;
82
83 #[cfg(any(feature = "secret_tree_access", feature = "private_message"))]
84 use secret_tree::*;
85
86 #[cfg(feature = "prior_epoch")]
87 use self::epoch::PriorEpoch;
88
89 use self::epoch::EpochSecrets;
90 pub use self::message_processor::{
91 ApplicationMessageDescription, CommitEffect, CommitMessageDescription, NewEpoch,
92 ProposalMessageDescription, ProposalSender, ReceivedMessage,
93 };
94 use self::message_processor::{EventOrContent, MessageProcessor, ProvisionalState};
95 #[cfg(feature = "by_ref_proposal")]
96 use self::proposal_ref::ProposalRef;
97 use self::state_repo::GroupStateRepository;
98 pub use group_info::GroupInfo;
99
100 pub use self::framing::{ContentType, Sender};
101 pub use commit::*;
102 pub use mls_rs_core::group::GroupContext;
103 pub use roster::*;
104
105 pub(crate) use mls_rs_core::group::ConfirmedTranscriptHash;
106 pub(crate) use util::*;
107
108 #[cfg(all(feature = "by_ref_proposal", feature = "external_client"))]
109 pub use self::message_processor::CachedProposal;
110
111 #[cfg(feature = "private_message")]
112 mod ciphertext_processor;
113
114 mod commit;
115 pub mod component_operation;
116 pub(crate) mod confirmation_tag;
117 pub(crate) mod epoch;
118 pub(crate) mod framing;
119 mod group_info;
120 pub(crate) mod key_schedule;
121 mod membership_tag;
122 pub(crate) mod message_hash;
123 pub(crate) mod message_processor;
124 pub(crate) mod message_signature;
125 pub(crate) mod message_verifier;
126 pub mod mls_rules;
127 #[cfg(feature = "private_message")]
128 pub(crate) mod padding;
129 /// Proposals to evolve a MLS [`Group`]
130 pub mod proposal;
131 mod proposal_cache;
132 pub(crate) mod proposal_filter;
133 #[cfg(feature = "by_ref_proposal")]
134 pub(crate) mod proposal_ref;
135 #[cfg(feature = "psk")]
136 mod resumption;
137 mod roster;
138 pub(crate) mod snapshot;
139 pub(crate) mod state;
140
141 #[cfg(feature = "prior_epoch")]
142 pub(crate) mod state_repo;
143 #[cfg(not(feature = "prior_epoch"))]
144 pub(crate) mod state_repo_light;
145 #[cfg(not(feature = "prior_epoch"))]
146 pub(crate) use state_repo_light as state_repo;
147
148 pub(crate) mod transcript_hash;
149 mod util;
150
151 /// External commit building.
152 pub mod external_commit;
153
154 #[cfg(any(feature = "secret_tree_access", feature = "private_message"))]
155 pub(crate) mod secret_tree;
156
157 #[cfg(any(feature = "secret_tree_access", feature = "private_message"))]
158 pub use secret_tree::MessageKeyData as MessageKey;
159
160 #[cfg(all(test, feature = "rfc_compliant"))]
161 mod interop_test_vectors;
162
163 mod exported_tree;
164
165 pub use exported_tree::ExportedTree;
166
167 #[derive(Clone, Debug, PartialEq, MlsSize, MlsEncode, MlsDecode)]
168 struct GroupSecrets {
169 joiner_secret: JoinerSecret,
170 path_secret: Option<PathSecret>,
171 psks: Vec<PreSharedKeyID>,
172 }
173
174 impl HpkeEncryptable for GroupSecrets {
175 const ENCRYPT_LABEL: &'static str = "Welcome";
176
177 fn from_bytes(bytes: Vec<u8>) -> Result<Self, MlsError> {
178 Self::mls_decode(&mut bytes.as_slice()).map_err(Into::into)
179 }
180
181 fn get_bytes(&self) -> Result<Vec<u8>, MlsError> {
182 self.mls_encode_to_vec().map_err(Into::into)
183 }
184 }
185
186 #[derive(Clone, Debug, PartialEq, Eq, MlsSize, MlsEncode, MlsDecode)]
187 #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
188 pub(crate) struct EncryptedGroupSecrets {
189 pub new_member: KeyPackageRef,
190 pub encrypted_group_secrets: HpkeCiphertext,
191 }
192
193 #[derive(Clone, Eq, PartialEq, MlsSize, MlsEncode, MlsDecode)]
194 #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
195 pub(crate) struct Welcome {
196 pub cipher_suite: CipherSuite,
197 pub secrets: Vec<EncryptedGroupSecrets>,
198 #[mls_codec(with = "mls_rs_codec::byte_vec")]
199 pub encrypted_group_info: Vec<u8>,
200 }
201
202 impl Debug for Welcome {
203 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
204 f.debug_struct("Welcome")
205 .field("cipher_suite", &self.cipher_suite)
206 .field("secrets", &self.secrets)
207 .field(
208 "encrypted_group_info",
209 &mls_rs_core::debug::pretty_bytes(&self.encrypted_group_info),
210 )
211 .finish()
212 }
213 }
214
215 #[derive(Clone, Debug)]
216 // #[cfg_attr(
217 // all(feature = "ffi", not(test)),
218 // safer_ffi_gen::ffi_type(clone, opaque)
219 // )]
220 #[non_exhaustive]
221 /// Information provided to new members upon joining a group.
222 pub struct NewMemberInfo {
223 /// Group info extensions found within the Welcome message used to join
224 /// the group.
225 pub group_info_extensions: ExtensionList,
226 /// The group member who generated the Commit adding the joiner to the
227 /// group. This may not be the party who generated the corresponding
228 /// add proposal
229 pub sender: u32,
230 }
231
232 // #[cfg_attr(all(feature = "ffi", not(test)), safer_ffi_gen::safer_ffi_gen)]
233 impl NewMemberInfo {
234 pub(crate) fn new(group_info_extensions: ExtensionList, sender: u32) -> Self {
235 let mut new_member_info = Self {
236 group_info_extensions,
237 sender,
238 };
239
240 new_member_info.ungrease();
241
242 new_member_info
243 }
244
245 /// Group info extensions found within the Welcome message used to join
246 /// the group.
247 #[cfg(feature = "ffi")]
248 pub fn group_info_extensions(&self) -> &ExtensionList {
249 &self.group_info_extensions
250 }
251 }
252
253 /// An MLS end-to-end encrypted group.
254 ///
255 /// # Group Evolution
256 ///
257 /// MLS Groups are evolved via a propose-then-commit system. Each group state
258 /// produced by a commit is called an epoch and can produce and consume
259 /// application, proposal, and commit messages. A [commit](Group::commit) is used
260 /// to advance to the next epoch by applying existing proposals sent in
261 /// the current epoch by-reference along with an optional set of proposals
262 /// that are included by-value using a [`CommitBuilder`].
263 // #[cfg_attr(all(feature = "ffi", not(test)), safer_ffi_gen::ffi_type(opaque))]
264 #[derive(Clone)]
265 pub struct Group<C>
266 where
267 C: ClientConfig,
268 {
269 config: C,
270 cipher_suite_provider: <C::CryptoProvider as CryptoProvider>::CipherSuiteProvider,
271 state_repo: GroupStateRepository<C::GroupStateStorage, C::KeyPackageRepository>,
272 pub(crate) state: GroupState,
273 epoch_secrets: EpochSecrets,
274 private_tree: TreeKemPrivate,
275 key_schedule: KeySchedule,
276 #[cfg(feature = "by_ref_proposal")]
277 pending_updates:
278 crate::map::SmallMap<HpkePublicKey, (HpkeSecretKey, Option<SignatureSecretKey>)>,
279 pending_commit: PendingCommitSnapshot,
280 #[cfg(feature = "psk")]
281 previous_psk: Option<PskSecretInput>,
282 #[cfg(test)]
283 pub(crate) commit_modifiers: CommitModifiers,
284 pub(crate) signer: SignatureSecretKey,
285 }
286
287 // #[cfg_attr(all(feature = "ffi", not(test)), safer_ffi_gen::safer_ffi_gen)]
288 impl<C> Group<C>
289 where
290 C: ClientConfig + Clone,
291 {
292 #[allow(clippy::too_many_arguments)]
293 #[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)]
294 pub(crate) async fn new(
295 config: C,
296 group_id: Option<Vec<u8>>,
297 cipher_suite: CipherSuite,
298 protocol_version: ProtocolVersion,
299 signing_identity: SigningIdentity,
300 group_context_extensions: ExtensionList,
301 leaf_node_extensions: ExtensionList,
302 signer: SignatureSecretKey,
303 ) -> Result<Self, MlsError> {
304 let cipher_suite_provider = cipher_suite_provider(config.crypto_provider(), cipher_suite)?;
305
306 let (leaf_node, leaf_node_secret) = LeafNode::generate(
307 &cipher_suite_provider,
308 config.leaf_properties(leaf_node_extensions),
309 signing_identity,
310 &signer,
311 config.lifetime(),
312 )
313 .await?;
314
315 let (mut public_tree, private_tree) = TreeKemPublic::derive(
316 leaf_node,
317 leaf_node_secret,
318 &config.identity_provider(),
319 &group_context_extensions,
320 )
321 .await?;
322
323 let tree_hash = public_tree.tree_hash(&cipher_suite_provider).await?;
324
325 let group_id = group_id.map(Ok).unwrap_or_else(|| {
326 cipher_suite_provider
327 .random_bytes_vec(cipher_suite_provider.kdf_extract_size())
328 .map_err(|e| MlsError::CryptoProviderError(e.into_any_error()))
329 })?;
330
331 let context = GroupContext::new(
332 protocol_version,
333 cipher_suite,
334 group_id,
335 tree_hash,
336 group_context_extensions,
337 );
338
339 let identity_provider = config.identity_provider();
340
341 let member_validation_context = MemberValidationContext::ForNewGroup {
342 current_context: &context,
343 };
344
345 let leaf_node_validator = LeafNodeValidator::new(
346 &cipher_suite_provider,
347 &identity_provider,
348 member_validation_context,
349 );
350
351 leaf_node_validator
352 .check_if_valid(
353 public_tree.get_leaf_node(LeafIndex(0))?,
354 ValidationContext::Add(None),
355 )
356 .await?;
357
358 let state_repo = GroupStateRepository::new(
359 #[cfg(feature = "prior_epoch")]
360 context.group_id.clone(),
361 config.group_state_storage(),
362 config.key_package_repo(),
363 None,
364 )?;
365
366 let key_schedule_result = KeySchedule::from_random_epoch_secret(
367 &cipher_suite_provider,
368 #[cfg(any(feature = "secret_tree_access", feature = "private_message"))]
369 public_tree.total_leaf_count(),
370 )
371 .await?;
372
373 let confirmation_tag = ConfirmationTag::create(
374 &key_schedule_result.confirmation_key,
375 &vec![].into(),
376 &cipher_suite_provider,
377 )
378 .await?;
379
380 let interim_hash = InterimTranscriptHash::create(
381 &cipher_suite_provider,
382 &vec![].into(),
383 &confirmation_tag,
384 )
385 .await?;
386
387 Ok(Self {
388 config,
389 state: GroupState::new(context, public_tree, interim_hash, confirmation_tag),
390 private_tree,
391 key_schedule: key_schedule_result.key_schedule,
392 #[cfg(feature = "by_ref_proposal")]
393 pending_updates: Default::default(),
394 pending_commit: Default::default(),
395 #[cfg(test)]
396 commit_modifiers: Default::default(),
397 epoch_secrets: key_schedule_result.epoch_secrets,
398 state_repo,
399 cipher_suite_provider,
400 #[cfg(feature = "psk")]
401 previous_psk: None,
402 signer,
403 })
404 }
405
406 #[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)]
407 pub(crate) async fn join(
408 welcome: &MlsMessage,
409 tree_data: Option<ExportedTree<'_>>,
410 config: C,
411 signer: SignatureSecretKey,
412 ) -> Result<(Self, NewMemberInfo), MlsError> {
413 Self::from_welcome_message(
414 welcome,
415 tree_data,
416 config,
417 signer,
418 #[cfg(feature = "psk")]
419 None,
420 )
421 .await
422 }
423
424 #[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)]
425 async fn from_welcome_message(
426 welcome: &MlsMessage,
427 tree_data: Option<ExportedTree<'_>>,
428 config: C,
429 signer: SignatureSecretKey,
430 #[cfg(feature = "psk")] additional_psk: Option<PskSecretInput>,
431 ) -> Result<(Self, NewMemberInfo), MlsError> {
432 let (group_info, key_package_generation, group_secrets, psk_secret) =
433 Self::decrypt_group_info_internal(
434 welcome,
435 &config,
436 #[cfg(feature = "psk")]
437 additional_psk,
438 )
439 .await?;
440
441 let cipher_suite_provider = cipher_suite_provider(
442 config.crypto_provider(),
443 group_info.group_context.cipher_suite,
444 )?;
445
446 let id_provider = config.identity_provider();
447
448 let public_tree = validate_tree_and_info_joiner(
449 welcome.version,
450 &group_info,
451 tree_data,
452 &id_provider,
453 &cipher_suite_provider,
454 )
455 .await?;
456
457 let key_package = key_package_generation.key_package;
458
459 // Identify a leaf in the tree array (any even-numbered node) whose leaf_node is identical
460 // to the leaf_node field of the KeyPackage. If no such field exists, return an error. Let
461 // index represent the index of this node among the leaves in the tree, namely the index of
462 // the node in the tree array divided by two.
463 let self_index = public_tree
464 .find_leaf_node(&key_package.leaf_node)
465 .ok_or(MlsError::WelcomeKeyPackageNotFound)?;
466
467 #[cfg(not(feature = "last_resort_key_package_ext"))]
468 let is_last_resort = false;
469 #[cfg(feature = "last_resort_key_package_ext")]
470 let is_last_resort = key_package
471 .extensions
472 .has_extension(LastResortKeyPackageExt::extension_type());
473 // Delete the key just used if this is not a last-resort key package.
474 let used_key_package_ref = (!is_last_resort).then_some(key_package_generation.reference);
475
476 let mut private_tree =
477 TreeKemPrivate::new_self_leaf(self_index, key_package_generation.leaf_node_secret_key);
478
479 // If the path_secret value is set in the GroupSecrets object
480 if let Some(path_secret) = group_secrets.path_secret {
481 private_tree
482 .update_secrets(
483 &cipher_suite_provider,
484 group_info.signer,
485 path_secret,
486 &public_tree,
487 )
488 .await?;
489 }
490
491 // Use the joiner_secret from the GroupSecrets object to generate the epoch secret and
492 // other derived secrets for the current epoch.
493 let key_schedule_result = KeySchedule::from_joiner(
494 &cipher_suite_provider,
495 &group_secrets.joiner_secret,
496 &group_info.group_context,
497 #[cfg(any(feature = "secret_tree_access", feature = "private_message"))]
498 public_tree.total_leaf_count(),
499 &psk_secret,
500 )
501 .await?;
502
503 // Verify the confirmation tag in the GroupInfo using the derived confirmation key and the
504 // confirmed_transcript_hash from the GroupInfo.
505 if !group_info
506 .confirmation_tag
507 .matches(
508 &key_schedule_result.confirmation_key,
509 &group_info.group_context.confirmed_transcript_hash,
510 &cipher_suite_provider,
511 )
512 .await?
513 {
514 return Err(MlsError::InvalidConfirmationTag);
515 }
516
517 Self::join_with(
518 config,
519 group_info,
520 public_tree,
521 key_schedule_result.key_schedule,
522 key_schedule_result.epoch_secrets,
523 private_tree,
524 used_key_package_ref,
525 signer,
526 )
527 .await
528 }
529
530 #[allow(clippy::too_many_arguments)]
531 #[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)]
532 async fn join_with(
533 config: C,
534 group_info: GroupInfo,
535 public_tree: TreeKemPublic,
536 key_schedule: KeySchedule,
537 epoch_secrets: EpochSecrets,
538 private_tree: TreeKemPrivate,
539 used_key_package_ref: Option<KeyPackageRef>,
540 signer: SignatureSecretKey,
541 ) -> Result<(Self, NewMemberInfo), MlsError> {
542 let cs = group_info.group_context.cipher_suite;
543
544 let cs = config
545 .crypto_provider()
546 .cipher_suite_provider(cs)
547 .ok_or(MlsError::UnsupportedCipherSuite(cs))?;
548
549 // Use the confirmed transcript hash and confirmation tag to compute the interim transcript
550 // hash in the new state.
551 let interim_transcript_hash = InterimTranscriptHash::create(
552 &cs,
553 &group_info.group_context.confirmed_transcript_hash,
554 &group_info.confirmation_tag,
555 )
556 .await?;
557
558 let state_repo = GroupStateRepository::new(
559 #[cfg(feature = "prior_epoch")]
560 group_info.group_context.group_id.clone(),
561 config.group_state_storage(),
562 config.key_package_repo(),
563 used_key_package_ref,
564 )?;
565
566 let group = Group {
567 config,
568 state: GroupState::new(
569 group_info.group_context,
570 public_tree,
571 interim_transcript_hash,
572 group_info.confirmation_tag,
573 ),
574 private_tree,
575 key_schedule,
576 #[cfg(feature = "by_ref_proposal")]
577 pending_updates: Default::default(),
578 pending_commit: Default::default(),
579 #[cfg(test)]
580 commit_modifiers: Default::default(),
581 epoch_secrets,
582 state_repo,
583 cipher_suite_provider: cs,
584 #[cfg(feature = "psk")]
585 previous_psk: None,
586 signer,
587 };
588
589 Ok((
590 group,
591 NewMemberInfo::new(group_info.extensions, *group_info.signer),
592 ))
593 }
594
595 #[inline(always)]
596 pub(crate) fn current_epoch_tree(&self) -> &TreeKemPublic {
597 &self.state.public_tree
598 }
599
600 /// The current epoch of the group. This value is incremented each
601 /// time a [`Group::commit`] message is processed.
602 #[inline(always)]
603 pub fn current_epoch(&self) -> u64 {
604 self.context().epoch
605 }
606
607 #[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)]
608 async fn hpke_encrypt_to_recipient_with_generic_context(
609 &self,
610 recipient_index: u32,
611 context_info: &[u8],
612 associated_data: Option<&[u8]>,
613 plaintext: &[u8],
614 ) -> Result<HpkeCiphertext, MlsError> {
615 let member_leaf_node = self
616 .group_state()
617 .public_tree
618 .get_leaf_node(LeafIndex(recipient_index))?;
619 let member_public_key = &member_leaf_node.public_key;
620 let hpke_ciphertext = self
621 .cipher_suite_provider
622 .hpke_seal(member_public_key, context_info, associated_data, plaintext)
623 .await
624 .map_err(|e| MlsError::CryptoProviderError(e.into_any_error()))?;
625 Ok(hpke_ciphertext)
626 }
627
628 /// HPKE encrypts a message to the member at the specified `recipient_index` in the group.
629 ///
630 /// Takes `context_info`, `associated_data`, and `plaintext`.
631 /// Returns `ciphertext` and `kem_output` inside `HpkeCiphertext`.
632 ///
633 /// WARNING: The message sender is not authenticated.
634 #[cfg(all(feature = "non_domain_separated_hpke_encrypt_decrypt", feature = "ffi"))]
635 #[cfg_attr(
636 not(mls_build_async),
637 maybe_async::must_be_sync,
638 safer_ffi_gen::safer_ffi_gen_ignore
639 )]
640 pub async fn hpke_encrypt_to_recipient(
641 &self,
642 recipient_index: u32,
643 context_info: &[u8],
644 associated_data: Option<&[u8]>,
645 plaintext: &[u8],
646 ) -> Result<HpkeCiphertext, MlsError> {
647 self.hpke_encrypt_to_recipient_with_generic_context(
648 recipient_index,
649 context_info,
650 associated_data,
651 plaintext,
652 )
653 .await
654 }
655
656 /// HPKE encrypts a message to the member at the specified `recipient_index` in the group.
657 ///
658 /// Takes a `component_id` and `context` to construct a `ComponentOperationLabel`, to be used as
659 /// the HPKE seal context, to ensure domain separation.
660 /// Also takes an `associated_data` and `plaintext`.
661 /// Returns `ciphertext` and `kem_output` inside `HpkeCiphertext`.
662 #[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)]
663 pub async fn safe_encrypt_with_context_to_recipient(
664 &self,
665 recipient_index: u32,
666 component_id: ComponentID,
667 context: &[u8],
668 associated_data: Option<&[u8]>,
669 plaintext: &[u8],
670 ) -> Result<HpkeCiphertext, MlsError> {
671 let component_operation_label = ComponentOperationLabel::new(component_id, context);
672 self.hpke_encrypt_to_recipient_with_generic_context(
673 recipient_index,
674 &component_operation_label.get_bytes()?,
675 associated_data,
676 plaintext,
677 )
678 .await
679 }
680
681 #[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)]
682 async fn hpke_decrypt_for_current_member_with_generic_context(
683 &self,
684 context_info: &[u8],
685 associated_data: Option<&[u8]>,
686 hpke_ciphertext: HpkeCiphertext,
687 ) -> Result<Vec<u8>, MlsError> {
688 let self_private_key = &self.private_tree.secret_keys[0]
689 .as_ref()
690 .ok_or(MlsError::InvalidTreeKemPrivateKey)?;
691 let self_public_key = &self.current_user_leaf_node()?.public_key;
692 let plaintext = self
693 .cipher_suite_provider
694 .hpke_open(
695 &hpke_ciphertext,
696 self_private_key,
697 self_public_key,
698 context_info,
699 associated_data,
700 )
701 .await
702 .map_err(|e| MlsError::CryptoProviderError(e.into_any_error()))?;
703 Ok(plaintext)
704 }
705
706 /// HPKE decrypts a message sent to the current member.
707 ///
708 /// Takes `HpkeCiphertext` generated by `hpke_encrypt_to_recipient` intended for the
709 /// current member.
710 ///
711 /// WARNING: The message sender is not authenticated.
712 #[cfg(all(feature = "non_domain_separated_hpke_encrypt_decrypt", feature = "ffi"))]
713 #[cfg_attr(
714 not(mls_build_async),
715 // all(feature = "ffi", not(test)),
716 maybe_async::must_be_sync,
717 safer_ffi_gen::safer_ffi_gen_ignore
718 )]
719 pub async fn hpke_decrypt_for_current_member(
720 &self,
721 context_info: &[u8],
722 associated_data: Option<&[u8]>,
723 hpke_ciphertext: HpkeCiphertext,
724 ) -> Result<Vec<u8>, MlsError> {
725 self.hpke_decrypt_for_current_member_with_generic_context(
726 context_info,
727 associated_data,
728 hpke_ciphertext,
729 )
730 .await
731 }
732
733 /// HPKE decrypts a message sent to the current member.
734 ///
735 /// Takes `HpkeCiphertext` generated by `hpke_encrypt_to_recipient` intended for the
736 /// current member.
737 #[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)]
738 pub async fn safe_decrypt_with_context_for_current_member(
739 &self,
740 component_id: ComponentID,
741 context: &[u8],
742 associated_data: Option<&[u8]>,
743 hpke_ciphertext: HpkeCiphertext,
744 ) -> Result<Vec<u8>, MlsError> {
745 let component_operation_label = ComponentOperationLabel::new(component_id, context);
746 self.hpke_decrypt_for_current_member_with_generic_context(
747 &component_operation_label.get_bytes()?,
748 associated_data,
749 hpke_ciphertext,
750 )
751 .await
752 }
753
754 /// Index within the group's state for the local group instance.
755 ///
756 /// This index corresponds to indexes in content descriptions within
757 /// [`ReceivedMessage`].
758 #[inline(always)]
759 pub fn current_member_index(&self) -> u32 {
760 self.private_tree.self_index.0
761 }
762
763 fn current_user_leaf_node(&self) -> Result<&LeafNode, MlsError> {
764 self.current_epoch_tree()
765 .get_leaf_node(self.private_tree.self_index)
766 }
767
768 /// Signing identity currently in use by the local group instance.
769 // #[cfg_attr(all(feature = "ffi", not(test)), safer_ffi_gen::safer_ffi_gen_ignore)]
770 pub fn current_member_signing_identity(&self) -> Result<&SigningIdentity, MlsError> {
771 self.current_user_leaf_node().map(|ln| &ln.signing_identity)
772 }
773
774 /// Member at a specific index in the group state.
775 ///
776 /// These indexes correspond to indexes in content descriptions within
777 /// [`ReceivedMessage`].
778 pub fn member_at_index(&self, index: u32) -> Option<Member> {
779 self.group_state().member_at_index(index)
780 }
781
782 #[cfg(feature = "by_ref_proposal")]
783 #[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)]
784 async fn proposal_message(
785 &mut self,
786 proposal: Proposal,
787 authenticated_data: Vec<u8>,
788 ) -> Result<MlsMessage, MlsError> {
789 let sender = Sender::Member(*self.private_tree.self_index);
790
791 let auth_content = AuthenticatedContent::new_signed(
792 &self.cipher_suite_provider,
793 self.context(),
794 sender,
795 Content::Proposal(alloc::boxed::Box::new(proposal.clone())),
796 &self.signer,
797 #[cfg(feature = "private_message")]
798 self.encryption_options()?.control_wire_format(sender),
799 #[cfg(not(feature = "private_message"))]
800 WireFormat::PublicMessage,
801 authenticated_data,
802 )
803 .await?;
804
805 let sender = auth_content.content.sender;
806
807 let proposal_desc =
808 ProposalMessageDescription::new(&self.cipher_suite_provider, &auth_content, proposal)
809 .await?;
810
811 let message = self.format_for_wire(auth_content).await?;
812
813 self.state
814 .proposals
815 .insert_own(proposal_desc, &message, sender, &self.cipher_suite_provider)
816 .await?;
817
818 Ok(message)
819 }
820
821 /// Unique identifier for this group.
822 pub fn group_id(&self) -> &[u8] {
823 &self.context().group_id
824 }
825
826 fn provisional_private_tree(
827 &self,
828 provisional_state: &ProvisionalState,
829 ) -> Result<(TreeKemPrivate, Option<SignatureSecretKey>), MlsError> {
830 let mut provisional_private_tree = self.private_tree.clone();
831 let self_index = provisional_private_tree.self_index;
832
833 // Remove secret keys for blanked nodes
834 let path = provisional_state
835 .public_tree
836 .nodes
837 .direct_copath(self_index);
838
839 provisional_private_tree
840 .secret_keys
841 .resize(path.len() + 1, None);
842
843 for (i, n) in path.iter().enumerate() {
844 if provisional_state.public_tree.nodes.is_blank(n.path)? {
845 provisional_private_tree.secret_keys[i + 1] = None;
846 }
847 }
848
849 // Apply own update
850 let new_signer = None;
851
852 #[cfg(feature = "by_ref_proposal")]
853 let mut new_signer = new_signer;
854
855 #[cfg(feature = "by_ref_proposal")]
856 for p in &provisional_state.applied_proposals.updates {
857 if p.sender == Sender::Member(*self_index) {
858 let leaf_pk = &p.proposal.leaf_node.public_key;
859
860 // Update the leaf in the private tree if this is our update
861 #[cfg(feature = "std")]
862 let new_leaf_sk_and_signer = self.pending_updates.get(leaf_pk);
863
864 #[cfg(not(feature = "std"))]
865 let new_leaf_sk_and_signer = self
866 .pending_updates
867 .iter()
868 .find_map(|(pk, sk)| (pk == leaf_pk).then_some(sk));
869
870 let new_leaf_sk = new_leaf_sk_and_signer.map(|(sk, _)| sk.clone());
871 new_signer = new_leaf_sk_and_signer.and_then(|(_, sk)| sk.clone());
872
873 provisional_private_tree
874 .update_leaf(new_leaf_sk.ok_or(MlsError::UpdateErrorNoSecretKey)?);
875
876 break;
877 }
878 }
879
880 Ok((provisional_private_tree, new_signer))
881 }
882
883 #[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)]
884 async fn encrypt_group_secrets(
885 &self,
886 key_package: &KeyPackage,
887 leaf_index: LeafIndex,
888 joiner_secret: &JoinerSecret,
889 path_secrets: Option<&Vec<Option<PathSecret>>>,
890 #[cfg(feature = "psk")] psks: Vec<PreSharedKeyID>,
891 encrypted_group_info: &[u8],
892 ) -> Result<EncryptedGroupSecrets, MlsError> {
893 let path_secret = path_secrets
894 .map(|secrets| {
895 secrets
896 .get(
897 tree_math::leaf_lca_level(*self.private_tree.self_index, *leaf_index)
898 as usize
899 - 1,
900 )
901 .cloned()
902 .flatten()
903 .ok_or(MlsError::InvalidTreeKemPrivateKey)
904 })
905 .transpose()?;
906
907 #[cfg(not(feature = "psk"))]
908 let psks = Vec::new();
909
910 let group_secrets = GroupSecrets {
911 joiner_secret: joiner_secret.clone(),
912 path_secret,
913 psks,
914 };
915
916 let encrypted_group_secrets = group_secrets
917 .encrypt(
918 &self.cipher_suite_provider,
919 &key_package.hpke_init_key,
920 encrypted_group_info,
921 )
922 .await?;
923
924 Ok(EncryptedGroupSecrets {
925 new_member: key_package
926 .to_reference(&self.cipher_suite_provider)
927 .await?,
928 encrypted_group_secrets,
929 })
930 }
931
932 /// Create a proposal message that adds a new member to the group.
933 ///
934 /// `authenticated_data` will be sent unencrypted along with the contents
935 /// of the proposal message.
936 #[cfg(feature = "by_ref_proposal")]
937 #[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)]
938 pub async fn propose_add(
939 &mut self,
940 key_package: MlsMessage,
941 authenticated_data: Vec<u8>,
942 ) -> Result<MlsMessage, MlsError> {
943 let proposal = self.add_proposal(key_package)?;
944 self.proposal_message(proposal, authenticated_data).await
945 }
946
947 fn add_proposal(&self, key_package: MlsMessage) -> Result<Proposal, MlsError> {
948 Ok(Proposal::Add(alloc::boxed::Box::new(AddProposal {
949 key_package: key_package
950 .into_key_package()
951 .ok_or(MlsError::UnexpectedMessageType)?,
952 })))
953 }
954
955 /// Create a proposal message that updates your own public keys.
956 ///
957 /// This proposal is useful for contributing additional forward secrecy
958 /// and post-compromise security to the group without having to perform
959 /// the necessary computation of a [`Group::commit`].
960 ///
961 /// `authenticated_data` will be sent unencrypted along with the contents
962 /// of the proposal message.
963 #[cfg(feature = "by_ref_proposal")]
964 #[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)]
965 pub async fn propose_update(
966 &mut self,
967 authenticated_data: Vec<u8>,
968 ) -> Result<MlsMessage, MlsError> {
969 let proposal = self.update_proposal(None, None, None).await?;
970 self.proposal_message(proposal, authenticated_data).await
971 }
972
973 /// Create a proposal message that updates your own public keys
974 /// as well as your credential.
975 ///
976 /// This proposal is useful for contributing additional forward secrecy
977 /// and post-compromise security to the group without having to perform
978 /// the necessary computation of a [`Group::commit`].
979 ///
980 /// Identity updates are allowed by the group by default assuming that the
981 /// new identity provided is considered
982 /// [valid](crate::IdentityProvider::validate_member)
983 /// by and matches the output of the
984 /// [identity](crate::IdentityProvider)
985 /// function of the current
986 /// [`IdentityProvider`](crate::IdentityProvider).
987 ///
988 /// `authenticated_data` will be sent unencrypted along with the contents
989 /// of the proposal message.
990 #[cfg(feature = "by_ref_proposal")]
991 #[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)]
992 pub async fn propose_update_with_identity(
993 &mut self,
994 signer: SignatureSecretKey,
995 signing_identity: SigningIdentity,
996 authenticated_data: Vec<u8>,
997 ) -> Result<MlsMessage, MlsError> {
998 let proposal = self
999 .update_proposal(Some(signer), Some(signing_identity), None)
1000 .await?;
1001
1002 self.proposal_message(proposal, authenticated_data).await
1003 }
1004
1005 #[cfg(feature = "by_ref_proposal")]
1006 #[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)]
1007 async fn update_proposal(
1008 &mut self,
1009 signer: Option<SignatureSecretKey>,
1010 signing_identity: Option<SigningIdentity>,
1011 leaf_node_extensions: Option<ExtensionList>,
1012 ) -> Result<Proposal, MlsError> {
1013 // Grab a copy of the current node and update it to have new key material
1014 let mut new_leaf_node: LeafNode = self.current_user_leaf_node()?.clone();
1015
1016 let new_leaf_node_extensions =
1017 leaf_node_extensions.unwrap_or(new_leaf_node.ungreased_extensions());
1018 let secret_key = new_leaf_node
1019 .update(
1020 &self.cipher_suite_provider,
1021 self.group_id(),
1022 self.current_member_index(),
1023 Some(self.config.leaf_properties(new_leaf_node_extensions)),
1024 signing_identity,
1025 signer.as_ref().unwrap_or(&self.signer),
1026 )
1027 .await?;
1028
1029 // Store the secret key in the pending updates storage for later
1030 #[cfg(feature = "std")]
1031 self.pending_updates
1032 .insert(new_leaf_node.public_key.clone(), (secret_key, signer));
1033
1034 #[cfg(not(feature = "std"))]
1035 self.pending_updates
1036 .push((new_leaf_node.public_key.clone(), (secret_key, signer)));
1037
1038 Ok(Proposal::Update(UpdateProposal {
1039 leaf_node: new_leaf_node,
1040 }))
1041 }
1042
1043 /// Create a proposal message that removes an existing member from the
1044 /// group.
1045 ///
1046 /// `authenticated_data` will be sent unencrypted along with the contents
1047 /// of the proposal message.
1048 #[cfg(feature = "by_ref_proposal")]
1049 #[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)]
1050 pub async fn propose_remove(
1051 &mut self,
1052 index: u32,
1053 authenticated_data: Vec<u8>,
1054 ) -> Result<MlsMessage, MlsError> {
1055 let proposal = self.remove_proposal(index)?;
1056 self.proposal_message(proposal, authenticated_data).await
1057 }
1058
1059 fn remove_proposal(&self, index: u32) -> Result<Proposal, MlsError> {
1060 let leaf_index = LeafIndex(index);
1061
1062 // Verify that this leaf is actually in the tree
1063 self.current_epoch_tree().get_leaf_node(leaf_index)?;
1064
1065 Ok(Proposal::Remove(RemoveProposal {
1066 to_remove: leaf_index,
1067 }))
1068 }
1069
1070 /// Create a proposal message that adds an external pre shared key to the group.
1071 ///
1072 /// Each group member will need to have the PSK associated with
1073 /// [`ExternalPskId`](mls_rs_core::psk::ExternalPskId) installed within
1074 /// the [`PreSharedKeyStorage`](mls_rs_core::psk::PreSharedKeyStorage)
1075 /// in use by this group upon processing a [commit](Group::commit) that
1076 /// contains this proposal.
1077 ///
1078 /// `authenticated_data` will be sent unencrypted along with the contents
1079 /// of the proposal message.
1080 #[cfg(all(feature = "by_ref_proposal", feature = "psk"))]
1081 #[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)]
1082 pub async fn propose_external_psk(
1083 &mut self,
1084 psk: ExternalPskId,
1085 authenticated_data: Vec<u8>,
1086 ) -> Result<MlsMessage, MlsError> {
1087 let proposal = self.psk_proposal(JustPreSharedKeyID::External(psk))?;
1088 self.proposal_message(proposal, authenticated_data).await
1089 }
1090
1091 #[cfg(feature = "psk")]
1092 fn psk_proposal(&self, key_id: JustPreSharedKeyID) -> Result<Proposal, MlsError> {
1093 Ok(Proposal::Psk(PreSharedKeyProposal {
1094 psk: PreSharedKeyID::new(key_id, &self.cipher_suite_provider)?,
1095 }))
1096 }
1097
1098 /// Create a proposal message that adds a pre shared key from a previous
1099 /// epoch to the current group state.
1100 ///
1101 /// Each group member will need to have the secret state from `psk_epoch`.
1102 /// In particular, the members who joined between `psk_epoch` and the
1103 /// current epoch cannot process a commit containing this proposal.
1104 ///
1105 /// `authenticated_data` will be sent unencrypted along with the contents
1106 /// of the proposal message.
1107 #[cfg(all(feature = "by_ref_proposal", feature = "psk"))]
1108 #[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)]
1109 pub async fn propose_resumption_psk(
1110 &mut self,
1111 psk_epoch: u64,
1112 authenticated_data: Vec<u8>,
1113 ) -> Result<MlsMessage, MlsError> {
1114 let key_id = ResumptionPsk {
1115 psk_epoch,
1116 usage: ResumptionPSKUsage::Application,
1117 psk_group_id: PskGroupId(self.group_id().to_vec()),
1118 };
1119
1120 let proposal = self.psk_proposal(JustPreSharedKeyID::Resumption(key_id))?;
1121 self.proposal_message(proposal, authenticated_data).await
1122 }
1123
1124 /// Create a proposal message that requests for this group to be
1125 /// reinitialized.
1126 ///
1127 /// Once a [`ReInitProposal`](proposal::ReInitProposal)
1128 /// has been sent, another group member can complete reinitialization of
1129 /// the group by calling [`Group::get_reinit_client`].
1130 ///
1131 /// `authenticated_data` will be sent unencrypted along with the contents
1132 /// of the proposal message.
1133 #[cfg(feature = "by_ref_proposal")]
1134 #[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)]
1135 pub async fn propose_reinit(
1136 &mut self,
1137 group_id: Option<Vec<u8>>,
1138 version: ProtocolVersion,
1139 cipher_suite: CipherSuite,
1140 extensions: ExtensionList,
1141 authenticated_data: Vec<u8>,
1142 ) -> Result<MlsMessage, MlsError> {
1143 let proposal = self.reinit_proposal(group_id, version, cipher_suite, extensions)?;
1144 self.proposal_message(proposal, authenticated_data).await
1145 }
1146
1147 fn reinit_proposal(
1148 &self,
1149 group_id: Option<Vec<u8>>,
1150 version: ProtocolVersion,
1151 cipher_suite: CipherSuite,
1152 extensions: ExtensionList,
1153 ) -> Result<Proposal, MlsError> {
1154 let group_id = group_id.map(Ok).unwrap_or_else(|| {
1155 self.cipher_suite_provider
1156 .random_bytes_vec(self.cipher_suite_provider.kdf_extract_size())
1157 .map_err(|e| MlsError::CryptoProviderError(e.into_any_error()))
1158 })?;
1159
1160 Ok(Proposal::ReInit(ReInitProposal {
1161 group_id,
1162 version,
1163 cipher_suite,
1164 extensions,
1165 }))
1166 }
1167
1168 /// Create a proposal message that sets extensions stored in the group
1169 /// state.
1170 ///
1171 /// # Warning
1172 ///
1173 /// This function does not create a diff that will be applied to the
1174 /// current set of extension that are in use. In order for an existing
1175 /// extension to not be overwritten by this proposal, it must be included
1176 /// in the new set of extensions being proposed.
1177 ///
1178 ///
1179 /// `authenticated_data` will be sent unencrypted along with the contents
1180 /// of the proposal message.
1181 #[cfg(feature = "by_ref_proposal")]
1182 #[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)]
1183 pub async fn propose_group_context_extensions(
1184 &mut self,
1185 extensions: ExtensionList,
1186 authenticated_data: Vec<u8>,
1187 ) -> Result<MlsMessage, MlsError> {
1188 let proposal = self.group_context_extensions_proposal(extensions);
1189 self.proposal_message(proposal, authenticated_data).await
1190 }
1191
1192 fn group_context_extensions_proposal(&self, extensions: ExtensionList) -> Proposal {
1193 Proposal::GroupContextExtensions(extensions)
1194 }
1195
1196 /// Create a custom proposal message.
1197 ///
1198 /// `authenticated_data` will be sent unencrypted along with the contents
1199 /// of the proposal message.
1200 #[cfg(all(feature = "custom_proposal", feature = "by_ref_proposal"))]
1201 #[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)]
1202 pub async fn propose_custom(
1203 &mut self,
1204 proposal: CustomProposal,
1205 authenticated_data: Vec<u8>,
1206 ) -> Result<MlsMessage, MlsError> {
1207 self.proposal_message(Proposal::Custom(proposal), authenticated_data)
1208 .await
1209 }
1210
1211 /// Delete all sent and received proposals cached for commit.
1212 #[cfg(feature = "by_ref_proposal")]
1213 pub fn clear_proposal_cache(&mut self) {
1214 self.state.proposals.clear()
1215 }
1216
1217 #[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)]
1218 pub(crate) async fn format_for_wire(
1219 &mut self,
1220 content: AuthenticatedContent,
1221 ) -> Result<MlsMessage, MlsError> {
1222 #[cfg(feature = "private_message")]
1223 let payload = if content.wire_format == WireFormat::PrivateMessage {
1224 MlsMessagePayload::Cipher(self.create_ciphertext(content).await?)
1225 } else {
1226 MlsMessagePayload::Plain(self.create_plaintext(content).await?)
1227 };
1228 #[cfg(not(feature = "private_message"))]
1229 let payload = MlsMessagePayload::Plain(self.create_plaintext(content).await?);
1230
1231 Ok(MlsMessage::new(self.protocol_version(), payload))
1232 }
1233
1234 #[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)]
1235 async fn create_plaintext(
1236 &self,
1237 auth_content: AuthenticatedContent,
1238 ) -> Result<PublicMessage, MlsError> {
1239 let membership_tag = if matches!(auth_content.content.sender, Sender::Member(_)) {
1240 let tag = self
1241 .key_schedule
1242 .get_membership_tag(&auth_content, self.context(), &self.cipher_suite_provider)
1243 .await?;
1244
1245 Some(tag)
1246 } else {
1247 None
1248 };
1249
1250 Ok(PublicMessage {
1251 content: auth_content.content,
1252 auth: auth_content.auth,
1253 membership_tag,
1254 })
1255 }
1256
1257 #[cfg(feature = "private_message")]
1258 #[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)]
1259 async fn create_ciphertext(
1260 &mut self,
1261 auth_content: AuthenticatedContent,
1262 ) -> Result<PrivateMessage, MlsError> {
1263 let padding_mode = self.encryption_options()?.padding_mode;
1264
1265 let mut encryptor = CiphertextProcessor::new(self, self.cipher_suite_provider.clone());
1266
1267 encryptor.seal(auth_content, padding_mode).await
1268 }
1269
1270 /// Encrypt an application message using the current group state.
1271 ///
1272 /// `authenticated_data` will be sent unencrypted along with the contents
1273 /// of the proposal message.
1274 #[cfg(feature = "private_message")]
1275 #[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)]
1276 pub async fn encrypt_application_message(
1277 &mut self,
1278 message: &[u8],
1279 authenticated_data: Vec<u8>,
1280 ) -> Result<MlsMessage, MlsError> {
1281 // A group member that has observed one or more proposals within an epoch MUST send a Commit message
1282 // before sending application data
1283 #[cfg(feature = "by_ref_proposal")]
1284 if !self.state.proposals.is_empty() {
1285 return Err(MlsError::CommitRequired);
1286 }
1287
1288 let auth_content = AuthenticatedContent::new_signed(
1289 &self.cipher_suite_provider,
1290 self.context(),
1291 Sender::Member(*self.private_tree.self_index),
1292 Content::Application(message.to_vec().into()),
1293 &self.signer,
1294 WireFormat::PrivateMessage,
1295 authenticated_data,
1296 )
1297 .await?;
1298
1299 self.format_for_wire(auth_content).await
1300 }
1301
1302 #[cfg(feature = "private_message")]
1303 #[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)]
1304 async fn decrypt_incoming_ciphertext(
1305 &mut self,
1306 message: &PrivateMessage,
1307 ) -> Result<AuthenticatedContent, MlsError> {
1308 let epoch_id = message.epoch;
1309
1310 let auth_content = if epoch_id == self.context().epoch {
1311 let content = CiphertextProcessor::new(self, self.cipher_suite_provider.clone())
1312 .open(message)
1313 .await?;
1314
1315 verify_auth_content_signature(
1316 &self.cipher_suite_provider,
1317 SignaturePublicKeysContainer::RatchetTree(&self.state.public_tree),
1318 self.context(),
1319 &content,
1320 #[cfg(feature = "by_ref_proposal")]
1321 &[],
1322 )
1323 .await?;
1324
1325 Ok::<_, MlsError>(content)
1326 } else {
1327 #[cfg(feature = "prior_epoch")]
1328 {
1329 let epoch = self
1330 .state_repo
1331 .get_epoch_mut(epoch_id)
1332 .await?
1333 .ok_or(MlsError::EpochNotFound)?;
1334
1335 let content = CiphertextProcessor::new(epoch, self.cipher_suite_provider.clone())
1336 .open(message)
1337 .await?;
1338
1339 verify_auth_content_signature(
1340 &self.cipher_suite_provider,
1341 SignaturePublicKeysContainer::List(&epoch.signature_public_keys),
1342 &epoch.context,
1343 &content,
1344 #[cfg(feature = "by_ref_proposal")]
1345 &[],
1346 )
1347 .await?;
1348
1349 Ok(content)
1350 }
1351
1352 #[cfg(not(feature = "prior_epoch"))]
1353 Err(MlsError::EpochNotFound)
1354 }?;
1355
1356 Ok(auth_content)
1357 }
1358
1359 /// Apply a pending commit that was created by [`Group::commit`] or
1360 /// [`CommitBuilder::build`].
1361 #[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)]
1362 pub async fn apply_pending_commit(&mut self) -> Result<CommitMessageDescription, MlsError> {
1363 let pending = core::mem::take(&mut self.pending_commit);
1364 self.apply_detached_commit(CommitSecrets(pending)).await
1365 }
1366
1367 #[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)]
1368 pub async fn apply_pending_commit_backwards_compatible(
1369 &mut self,
1370 ) -> Result<CommitMessageDescription, MlsError> {
1371 let pending = core::mem::take(&mut self.pending_commit);
1372 self.apply_detached_commit_backwards_compatible(CommitSecrets(pending))
1373 .await
1374 }
1375
1376 /// Apply a detached commit that was created by [`Group::commit_detached`] or
1377 /// [`CommitBuilder::build_detached`].
1378 #[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)]
1379 pub async fn apply_detached_commit(
1380 &mut self,
1381 commit_secrets: CommitSecrets,
1382 ) -> Result<CommitMessageDescription, MlsError> {
1383 let pending = match commit_secrets.0 {
1384 PendingCommitSnapshot::PendingCommit(bytes) => PendingCommit::mls_decode(&mut &*bytes)?,
1385 _ => return Err(MlsError::PendingCommitNotFound),
1386 };
1387
1388 self.insert_past_epoch().await?;
1389
1390 self.state = pending.state;
1391 self.epoch_secrets = pending.epoch_secrets;
1392 self.private_tree = pending.private_tree;
1393 self.key_schedule = pending.key_schedule;
1394 self.signer = pending.signer;
1395
1396 Ok(pending.output)
1397 }
1398
1399 #[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)]
1400 pub async fn apply_detached_commit_backwards_compatible(
1401 &mut self,
1402 commit_secrets: CommitSecrets,
1403 ) -> Result<CommitMessageDescription, MlsError> {
1404 match commit_secrets.0 {
1405 PendingCommitSnapshot::None | PendingCommitSnapshot::PendingCommit(_) => {
1406 self.apply_detached_commit(commit_secrets).await
1407 }
1408 PendingCommitSnapshot::LegacyPendingCommit(legacy_pending) => {
1409 let content = legacy_pending.content.clone();
1410 self.pending_commit = PendingCommitSnapshot::LegacyPendingCommit(legacy_pending);
1411 self.process_commit(content, None).await
1412 }
1413 }
1414 }
1415
1416 /// Returns true if a commit has been created but not yet applied
1417 /// with [`Group::apply_pending_commit`] or cleared with [`Group::clear_pending_commit`]
1418 pub fn has_pending_commit(&self) -> bool {
1419 !self.pending_commit.is_none()
1420 }
1421
1422 /// Clear the currently pending commit.
1423 ///
1424 /// This function will automatically be called in the event that a
1425 /// commit message is processed using [`Group::process_incoming_message`]
1426 /// before [`Group::apply_pending_commit`] is called.
1427 pub fn clear_pending_commit(&mut self) {
1428 self.pending_commit = Default::default()
1429 }
1430
1431 /// Returns true if the client has received or issued a proposal
1432 /// that needs to be committed to with [`Group::commit`] before encrypting an
1433 /// application message.
1434 #[cfg(feature = "by_ref_proposal")]
1435 pub fn commit_required(&self) -> bool {
1436 !self.state.proposals.is_empty()
1437 }
1438
1439 /// Process an inbound message for this group.
1440 ///
1441 /// # Warning
1442 ///
1443 /// Changes to the group's state as a result of processing `message` will
1444 /// not be persisted by the
1445 /// [`GroupStateStorage`](crate::GroupStateStorage)
1446 /// in use by this group until [`Group::write_to_storage`] is called.
1447 #[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)]
1448 #[inline(never)]
1449 pub async fn process_incoming_message(
1450 &mut self,
1451 message: MlsMessage,
1452 ) -> Result<ReceivedMessage, MlsError> {
1453 if let Some(pending) = self.pending_commit.commit_hash()? {
1454 let message_hash = MessageHash::compute(&self.cipher_suite_provider, &message).await?;
1455
1456 if message_hash == pending {
1457 let message_description = self.apply_pending_commit().await?;
1458
1459 return Ok(ReceivedMessage::Commit(message_description));
1460 }
1461 }
1462
1463 #[cfg(feature = "by_ref_proposal")]
1464 if message.wire_format() == WireFormat::PrivateMessage {
1465 let cached_own_proposal = self
1466 .state
1467 .proposals
1468 .get_own(&self.cipher_suite_provider, &message)
1469 .await?;
1470
1471 if let Some(cached) = cached_own_proposal {
1472 return Ok(ReceivedMessage::Proposal(cached));
1473 }
1474 }
1475
1476 MessageProcessor::process_incoming_message(
1477 self,
1478 message,
1479 #[cfg(feature = "by_ref_proposal")]
1480 true,
1481 )
1482 .await
1483 }
1484
1485 /// Process an inbound message for this group, providing additional context
1486 /// with a message timestamp.
1487 ///
1488 /// Providing a timestamp is useful when the
1489 /// [`IdentityProvider`](crate::IdentityProvider)
1490 /// in use by the group can determine validity based on a timestamp.
1491 /// For example, this allows for checking X.509 certificate expiration
1492 /// at the time when `message` was received by a server rather than when
1493 /// a specific client asynchronously received `message`
1494 ///
1495 /// # Warning
1496 ///
1497 /// Changes to the group's state as a result of processing `message` will
1498 /// not be persisted by the
1499 /// [`GroupStateStorage`](crate::GroupStateStorage)
1500 /// in use by this group until [`Group::write_to_storage`] is called.
1501 #[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)]
1502 pub async fn process_incoming_message_with_time(
1503 &mut self,
1504 message: MlsMessage,
1505 time: MlsTime,
1506 ) -> Result<ReceivedMessage, MlsError> {
1507 MessageProcessor::process_incoming_message_with_time(
1508 self,
1509 message,
1510 #[cfg(feature = "by_ref_proposal")]
1511 true,
1512 Some(time),
1513 )
1514 .await
1515 }
1516
1517 /// Find a group member by
1518 /// [identity](crate::IdentityProvider::identity)
1519 ///
1520 /// This function determines identity by calling the
1521 /// [`IdentityProvider`](crate::IdentityProvider)
1522 /// currently in use by the group.
1523 #[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)]
1524 pub async fn member_with_identity(&self, identity: &[u8]) -> Result<Member, MlsError> {
1525 let tree = &self.state.public_tree;
1526
1527 #[cfg(feature = "tree_index")]
1528 let index = tree.get_leaf_node_with_identity(identity);
1529
1530 #[cfg(not(feature = "tree_index"))]
1531 let index = tree
1532 .get_leaf_node_with_identity(
1533 identity,
1534 &self.identity_provider(),
1535 &self.state.context.extensions,
1536 )
1537 .await?;
1538
1539 let index = index.ok_or(MlsError::MemberNotFound)?;
1540 let node = self.state.public_tree.get_leaf_node(index)?;
1541
1542 Ok(member_from_leaf_node(node, index))
1543 }
1544
1545 /// Create a group info message that can be used for external proposals and commits.
1546 ///
1547 /// The returned `GroupInfo` is suitable for one external commit for the current epoch.
1548 /// If `with_tree_in_extension` is set to true, the returned `GroupInfo` contains the
1549 /// ratchet tree and therefore contains all information needed to join the group. Otherwise,
1550 /// the ratchet tree must be obtained separately, e.g. via
1551 /// (ExternalClient::export_tree)[crate::external_client::ExternalGroup::export_tree].
1552 #[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)]
1553 pub async fn group_info_message_allowing_ext_commit(
1554 &self,
1555 with_tree_in_extension: bool,
1556 ) -> Result<MlsMessage, MlsError> {
1557 let mut extensions = ExtensionList::new();
1558
1559 extensions.set_from({
1560 self.key_schedule
1561 .get_external_key_pair_ext(&self.cipher_suite_provider)
1562 .await?
1563 })?;
1564
1565 self.group_info_message_internal(extensions, with_tree_in_extension)
1566 .await
1567 }
1568
1569 /// Create a group info message that can be used for external proposals.
1570 #[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)]
1571 pub async fn group_info_message(
1572 &self,
1573 with_tree_in_extension: bool,
1574 ) -> Result<MlsMessage, MlsError> {
1575 self.group_info_message_internal(ExtensionList::new(), with_tree_in_extension)
1576 .await
1577 }
1578
1579 #[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)]
1580 pub async fn group_info_message_internal(
1581 &self,
1582 mut initial_extensions: ExtensionList,
1583 with_tree_in_extension: bool,
1584 ) -> Result<MlsMessage, MlsError> {
1585 if with_tree_in_extension {
1586 initial_extensions.set_from(RatchetTreeExt {
1587 tree_data: ExportedTree::new(self.state.public_tree.nodes.clone()),
1588 })?;
1589 }
1590
1591 let mut info = GroupInfo {
1592 group_context: self.context().clone(),
1593 extensions: initial_extensions,
1594 confirmation_tag: self.state.confirmation_tag.clone(),
1595 signer: self.private_tree.self_index,
1596 signature: Vec::new(),
1597 };
1598
1599 info.grease(self.cipher_suite_provider())?;
1600
1601 info.sign(&self.cipher_suite_provider, &self.signer, &())
1602 .await?;
1603
1604 Ok(MlsMessage::new(
1605 self.protocol_version(),
1606 MlsMessagePayload::GroupInfo(info),
1607 ))
1608 }
1609
1610 /// Get the current group context summarizing various information about the group.
1611 #[inline(always)]
1612 pub fn context(&self) -> &GroupContext {
1613 &self.group_state().context
1614 }
1615
1616 /// Get the
1617 /// [epoch_authenticator](https://messaginglayersecurity.rocks/mls-protocol/draft-ietf-mls-protocol.html#name-key-schedule)
1618 /// of the current epoch.
1619 pub fn epoch_authenticator(&self) -> Result<Secret, MlsError> {
1620 Ok(self.key_schedule.authentication_secret.clone().into())
1621 }
1622
1623 /// Export a secret for use outside of MLS. Each epoch, label, context
1624 /// combination has a unique and independent secret. Secrets for all
1625 /// epochs, labels and contexts can be derived until either the epoch
1626 /// changes, i.e. a commit is received (or own commit is applied), or
1627 /// [Group::delete_exporter] is called.
1628 #[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)]
1629 pub async fn export_secret(
1630 &self,
1631 label: &[u8],
1632 context: &[u8],
1633 len: usize,
1634 ) -> Result<Secret, MlsError> {
1635 self.key_schedule
1636 .export_secret(label, context, len, &self.cipher_suite_provider)
1637 .await
1638 .map(Into::into)
1639 }
1640
1641 /// Delete the exporter secret. Afterwards the state contains no information
1642 /// about any secrets outputted by [Group::export_secret] (for the current or
1643 /// past epochs). This means that after calling this function, [Group::export_secret]
1644 /// can no longer be used and we get forward secrecy for all secrets derived using
1645 /// [Group::export_secret].
1646 pub fn delete_exporter(&mut self) {
1647 self.key_schedule.delete_exporter();
1648 }
1649
1650 /// Export the current epoch's ratchet tree in serialized format.
1651 ///
1652 /// This function is used to provide the current group tree to new members
1653 /// when the `ratchet_tree_extension` is not used according to [`MlsRules::commit_options`].
1654 pub fn export_tree(&self) -> ExportedTree<'_> {
1655 ExportedTree::new_borrowed(&self.current_epoch_tree().nodes)
1656 }
1657
1658 /// Current version of the MLS protocol in use by this group.
1659 pub fn protocol_version(&self) -> ProtocolVersion {
1660 self.context().protocol_version
1661 }
1662
1663 /// Current cipher suite in use by this group.
1664 pub fn cipher_suite(&self) -> CipherSuite {
1665 self.context().cipher_suite
1666 }
1667
1668 /// Current roster
1669 pub fn roster(&self) -> Roster<'_> {
1670 self.group_state().public_tree.roster()
1671 }
1672
1673 /// Determines equality of two different groups internal states.
1674 /// Useful for testing.
1675 ///
1676 pub fn equal_group_state(a: &Group<C>, b: &Group<C>) -> bool {
1677 a.state == b.state && a.key_schedule == b.key_schedule && a.epoch_secrets == b.epoch_secrets
1678 }
1679
1680 #[cfg(feature = "psk")]
1681 #[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)]
1682 async fn get_psk(
1683 &self,
1684 psks: &[ProposalInfo<PreSharedKeyProposal>],
1685 ) -> Result<(PskSecret, Vec<PreSharedKeyID>), MlsError> {
1686 if let Some(psk) = self.previous_psk.clone() {
1687 // TODO consider throwing error if psks not empty
1688 let psk_id = vec![psk.id.clone()];
1689 let psk = PskSecret::calculate(&[psk], self.cipher_suite_provider()).await?;
1690
1691 Ok((psk, psk_id))
1692 } else {
1693 let psks = psks
1694 .iter()
1695 .map(|psk| psk.proposal.psk.clone())
1696 .collect::<Vec<_>>();
1697
1698 let psk = PskResolver {
1699 group_context: Some(self.context()),
1700 current_epoch: Some(&self.epoch_secrets),
1701 prior_epochs: Some(&self.state_repo),
1702 psk_store: &self.config.secret_store(),
1703 }
1704 .resolve_to_secret(&psks, self.cipher_suite_provider())
1705 .await?;
1706
1707 Ok((psk, psks))
1708 }
1709 }
1710
1711 #[cfg(feature = "private_message")]
1712 pub(crate) fn encryption_options(&self) -> Result<EncryptionOptions, MlsError> {
1713 self.config
1714 .mls_rules()
1715 .encryption_options(&self.roster(), self.group_context())
1716 .map_err(|e| MlsError::MlsRulesError(e.into_any_error()))
1717 }
1718
1719 #[cfg(not(feature = "psk"))]
1720 fn get_psk(&self) -> PskSecret {
1721 PskSecret::new(self.cipher_suite_provider())
1722 }
1723
1724 #[cfg(feature = "secret_tree_access")]
1725 #[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)]
1726 #[inline(never)]
1727 pub async fn next_encryption_key(&mut self) -> Result<MessageKey, MlsError> {
1728 self.epoch_secrets
1729 .secret_tree
1730 .next_message_key(
1731 &self.cipher_suite_provider,
1732 crate::tree_kem::node::NodeIndex::from(self.private_tree.self_index),
1733 KeyType::Application,
1734 )
1735 .await
1736 }
1737
1738 #[cfg(feature = "secret_tree_access")]
1739 #[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)]
1740 pub async fn derive_decryption_key(
1741 &mut self,
1742 sender: u32,
1743 generation: u32,
1744 ) -> Result<MessageKey, MlsError> {
1745 self.epoch_secrets
1746 .secret_tree
1747 .message_key_generation(
1748 &self.cipher_suite_provider,
1749 crate::tree_kem::node::NodeIndex::from(sender),
1750 KeyType::Application,
1751 generation,
1752 )
1753 .await
1754 }
1755 }
1756
1757 impl<C: ClientConfig> Group<C> {
1758 #[cfg(feature = "psk")]
1759 #[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)]
1760 async fn psk_secret<CS: CipherSuiteProvider>(
1761 config: &C,
1762 cipher_suite_provider: &CS,
1763 psks: &[PreSharedKeyID],
1764 additional_psk: Option<PskSecretInput>,
1765 ) -> Result<PskSecret, MlsError> {
1766 if let Some(psk) = additional_psk {
1767 let psk_id = psks.first().ok_or(MlsError::UnexpectedPskId)?;
1768
1769 match &psk_id.key_id {
1770 JustPreSharedKeyID::Resumption(r) if r.usage != ResumptionPSKUsage::Application => {
1771 Ok(())
1772 }
1773 _ => Err(MlsError::UnexpectedPskId),
1774 }?;
1775
1776 let mut psk = psk;
1777 psk.id.psk_nonce = psk_id.psk_nonce.clone();
1778 PskSecret::calculate(&[psk], cipher_suite_provider).await
1779 } else {
1780 PskResolver::<
1781 <C as ClientConfig>::GroupStateStorage,
1782 <C as ClientConfig>::KeyPackageRepository,
1783 <C as ClientConfig>::PskStore,
1784 > {
1785 group_context: None,
1786 current_epoch: None,
1787 prior_epochs: None,
1788 psk_store: &config.secret_store(),
1789 }
1790 .resolve_to_secret(psks, cipher_suite_provider)
1791 .await
1792 }
1793 }
1794
1795 #[cfg(not(feature = "psk"))]
1796 #[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)]
1797 async fn psk_secret<CS: CipherSuiteProvider>(
1798 _config: &C,
1799 cipher_suite_provider: &CS,
1800 _psks: &[PreSharedKeyID],
1801 ) -> Result<PskSecret, MlsError> {
1802 Ok(PskSecret::new(cipher_suite_provider))
1803 }
1804
1805 #[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)]
1806 pub(crate) async fn decrypt_group_info(
1807 welcome: &MlsMessage,
1808 config: &C,
1809 ) -> Result<GroupInfo, MlsError> {
1810 Self::decrypt_group_info_internal(
1811 welcome,
1812 config,
1813 #[cfg(feature = "psk")]
1814 None,
1815 )
1816 .await
1817 .map(|info| info.0)
1818 }
1819
1820 #[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)]
1821 async fn decrypt_group_info_internal(
1822 welcome: &MlsMessage,
1823 config: &C,
1824 #[cfg(feature = "psk")] additional_psk: Option<PskSecretInput>,
1825 ) -> Result<(GroupInfo, KeyPackageGeneration, GroupSecrets, PskSecret), MlsError> {
1826 let protocol_version = welcome.version;
1827
1828 if !config.version_supported(protocol_version) {
1829 return Err(MlsError::UnsupportedProtocolVersion(protocol_version));
1830 }
1831
1832 let MlsMessagePayload::Welcome(welcome) = &welcome.payload else {
1833 return Err(MlsError::UnexpectedMessageType);
1834 };
1835
1836 let cipher_suite_provider =
1837 cipher_suite_provider(config.crypto_provider(), welcome.cipher_suite)?;
1838
1839 let (encrypted_group_secrets, key_package_generation) =
1840 find_key_package_generation(&config.key_package_repo(), &welcome.secrets).await?;
1841
1842 let key_package_version = key_package_generation.key_package.version;
1843
1844 if key_package_version != protocol_version {
1845 return Err(MlsError::ProtocolVersionMismatch);
1846 }
1847
1848 // Decrypt the encrypted_group_secrets using HPKE with the algorithms indicated by the
1849 // cipher suite and the HPKE private key corresponding to the GroupSecrets. If a
1850 // PreSharedKeyID is part of the GroupSecrets and the client is not in possession of
1851 // the corresponding PSK, return an error
1852 let group_secrets = GroupSecrets::decrypt(
1853 &cipher_suite_provider,
1854 &key_package_generation.init_secret_key,
1855 &key_package_generation.key_package.hpke_init_key,
1856 &welcome.encrypted_group_info,
1857 &encrypted_group_secrets.encrypted_group_secrets,
1858 )
1859 .await?;
1860
1861 let psk_secret = Self::psk_secret(
1862 config,
1863 &cipher_suite_provider,
1864 &group_secrets.psks,
1865 #[cfg(feature = "psk")]
1866 additional_psk,
1867 )
1868 .await?;
1869
1870 // From the joiner_secret in the decrypted GroupSecrets object and the PSKs specified in
1871 // the GroupSecrets, derive the welcome_secret and using that the welcome_key and
1872 // welcome_nonce.
1873 let welcome_secret = WelcomeSecret::from_joiner_secret(
1874 &cipher_suite_provider,
1875 &group_secrets.joiner_secret,
1876 &psk_secret,
1877 )
1878 .await?;
1879
1880 // Use the key and nonce to decrypt the encrypted_group_info field.
1881 let decrypted_group_info = welcome_secret
1882 .decrypt(&welcome.encrypted_group_info)
1883 .await?;
1884
1885 let group_info = GroupInfo::mls_decode(&mut &**decrypted_group_info)?;
1886
1887 Ok((
1888 group_info,
1889 key_package_generation,
1890 group_secrets,
1891 psk_secret,
1892 ))
1893 }
1894
1895 #[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)]
1896 #[cfg(feature = "prior_epoch")]
1897 pub(crate) async fn insert_past_epoch(&mut self) -> Result<(), MlsError> {
1898 let signature_public_keys = self
1899 .state
1900 .public_tree
1901 .leaves()
1902 .map(|l| l.map(|n| n.signing_identity.signature_key.clone()))
1903 .collect();
1904
1905 let past_epoch = PriorEpoch {
1906 context: self.context().clone(),
1907 self_index: self.private_tree.self_index,
1908 secrets: self.epoch_secrets.clone(),
1909 signature_public_keys,
1910 };
1911
1912 self.state_repo.insert(past_epoch).await?;
1913
1914 Ok(())
1915 }
1916
1917 #[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)]
1918 #[cfg(not(feature = "prior_epoch"))]
1919 pub(crate) async fn insert_past_epoch(&mut self) -> Result<(), MlsError> {
1920 Ok(())
1921 }
1922 }
1923
1924 #[cfg(feature = "private_message")]
1925 impl<C> GroupStateProvider for Group<C>
1926 where
1927 C: ClientConfig + Clone,
1928 {
1929 fn group_context(&self) -> &GroupContext {
1930 self.context()
1931 }
1932
1933 fn self_index(&self) -> LeafIndex {
1934 self.private_tree.self_index
1935 }
1936
1937 fn epoch_secrets_mut(&mut self) -> &mut EpochSecrets {
1938 &mut self.epoch_secrets
1939 }
1940
1941 fn epoch_secrets(&self) -> &EpochSecrets {
1942 &self.epoch_secrets
1943 }
1944 }
1945
1946 #[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)]
1947 #[cfg_attr(all(target_arch = "wasm32", mls_build_async), maybe_async::must_be_async(?Send))]
1948 #[cfg_attr(
1949 all(not(target_arch = "wasm32"), mls_build_async),
1950 maybe_async::must_be_async
1951 )]
1952 impl<C> MessageProcessor for Group<C>
1953 where
1954 C: ClientConfig + Clone,
1955 {
1956 type MlsRules = C::MlsRules;
1957 type IdentityProvider = C::IdentityProvider;
1958 type PreSharedKeyStorage = C::PskStore;
1959 type OutputType = ReceivedMessage;
1960 type CipherSuiteProvider = <C::CryptoProvider as CryptoProvider>::CipherSuiteProvider;
1961
1962 #[cfg(feature = "private_message")]
1963 async fn process_ciphertext(
1964 &mut self,
1965 cipher_text: &PrivateMessage,
1966 ) -> Result<EventOrContent<Self::OutputType>, MlsError> {
1967 self.decrypt_incoming_ciphertext(cipher_text)
1968 .await
1969 .map(EventOrContent::Content)
1970 }
1971
1972 async fn verify_plaintext_authentication(
1973 &self,
1974 message: PublicMessage,
1975 ) -> Result<EventOrContent<Self::OutputType>, MlsError> {
1976 let auth_content = verify_plaintext_authentication(
1977 &self.cipher_suite_provider,
1978 message,
1979 Some(&self.key_schedule),
1980 &self.state,
1981 )
1982 .await?;
1983
1984 Ok(EventOrContent::Content(auth_content))
1985 }
1986
1987 async fn apply_update_path(
1988 &mut self,
1989 sender: LeafIndex,
1990 update_path: &ValidatedUpdatePath,
1991 provisional_state: &mut ProvisionalState,
1992 ) -> Result<Option<(TreeKemPrivate, PathSecret)>, MlsError> {
1993 // Update the private tree to create a provisional private tree
1994 let (mut provisional_private_tree, new_signer) =
1995 self.provisional_private_tree(provisional_state)?;
1996
1997 if let Some(signer) = new_signer {
1998 self.signer = signer;
1999 }
2000
2001 provisional_state
2002 .public_tree
2003 .apply_update_path(
2004 sender,
2005 update_path,
2006 &provisional_state.group_context.extensions,
2007 self.identity_provider(),
2008 self.cipher_suite_provider(),
2009 )
2010 .await?;
2011
2012 if sender == self.private_tree.self_index {
2013 let PendingCommitSnapshot::LegacyPendingCommit(legacy_pending) = &self.pending_commit
2014 else {
2015 return Err(MlsError::CantProcessMessageFromSelf);
2016 };
2017
2018 return Ok(Some((
2019 legacy_pending.private_tree.clone(),
2020 legacy_pending.commit_secret.clone(),
2021 )));
2022 }
2023
2024 // Update the tree hash to get context for decryption
2025 provisional_state.group_context.tree_hash = provisional_state
2026 .public_tree
2027 .tree_hash(&self.cipher_suite_provider)
2028 .await?;
2029
2030 let context_bytes = provisional_state.group_context.mls_encode_to_vec()?;
2031
2032 TreeKem::new(
2033 &mut provisional_state.public_tree,
2034 &mut provisional_private_tree,
2035 )
2036 .decap(
2037 sender,
2038 update_path,
2039 &provisional_state.indexes_of_added_kpkgs,
2040 &context_bytes,
2041 &self.cipher_suite_provider,
2042 )
2043 .await
2044 .map(|root_secret| Some((provisional_private_tree, root_secret)))
2045 }
2046
2047 async fn update_key_schedule(
2048 &mut self,
2049 secrets: Option<(TreeKemPrivate, PathSecret)>,
2050 interim_transcript_hash: InterimTranscriptHash,
2051 confirmation_tag: &ConfirmationTag,
2052 provisional_state: ProvisionalState,
2053 ) -> Result<(), MlsError> {
2054 let commit_secret = if let Some(secrets) = secrets {
2055 self.private_tree = secrets.0;
2056 secrets.1
2057 } else {
2058 PathSecret::empty(&self.cipher_suite_provider)
2059 };
2060
2061 // Use the commit_secret, the psk_secret, the provisional GroupContext, and the init secret
2062 // from the previous epoch (or from the external init) to compute the epoch secret and
2063 // derived secrets for the new epoch
2064
2065 let key_schedule = match provisional_state
2066 .applied_proposals
2067 .external_initializations
2068 .first()
2069 .cloned()
2070 {
2071 Some(ext_init) if self.pending_commit.is_none() => {
2072 self.key_schedule
2073 .derive_for_external(&ext_init.proposal.kem_output, &self.cipher_suite_provider)
2074 .await?
2075 }
2076 _ => self.key_schedule.clone(),
2077 };
2078
2079 #[cfg(feature = "psk")]
2080 let (psk, _) = self
2081 .get_psk(&provisional_state.applied_proposals.psks)
2082 .await?;
2083
2084 #[cfg(not(feature = "psk"))]
2085 let psk = self.get_psk();
2086
2087 let key_schedule_result = KeySchedule::from_key_schedule(
2088 &key_schedule,
2089 &commit_secret,
2090 &provisional_state.group_context,
2091 #[cfg(any(feature = "secret_tree_access", feature = "private_message"))]
2092 provisional_state.public_tree.total_leaf_count(),
2093 &psk,
2094 &self.cipher_suite_provider,
2095 )
2096 .await?;
2097
2098 // Use the confirmation_key for the new epoch to compute the confirmation tag for
2099 // this message, as described below, and verify that it is the same as the
2100 // confirmation_tag field in the MlsPlaintext object.
2101 let new_confirmation_tag = ConfirmationTag::create(
2102 &key_schedule_result.confirmation_key,
2103 &provisional_state.group_context.confirmed_transcript_hash,
2104 &self.cipher_suite_provider,
2105 )
2106 .await?;
2107
2108 if &new_confirmation_tag != confirmation_tag {
2109 return Err(MlsError::InvalidConfirmationTag);
2110 }
2111
2112 self.insert_past_epoch().await?;
2113
2114 self.epoch_secrets = key_schedule_result.epoch_secrets;
2115 self.state.context = provisional_state.group_context;
2116 self.state.interim_transcript_hash = interim_transcript_hash;
2117 self.key_schedule = key_schedule_result.key_schedule;
2118 self.state.public_tree = provisional_state.public_tree;
2119 self.state.confirmation_tag = new_confirmation_tag;
2120
2121 // Clear the proposals list
2122 #[cfg(feature = "by_ref_proposal")]
2123 self.state.proposals.clear();
2124
2125 // Clear the pending updates list
2126 #[cfg(feature = "by_ref_proposal")]
2127 {
2128 self.pending_updates = Default::default();
2129 }
2130
2131 self.pending_commit = Default::default();
2132
2133 Ok(())
2134 }
2135
2136 fn mls_rules(&self) -> Self::MlsRules {
2137 self.config.mls_rules()
2138 }
2139
2140 fn identity_provider(&self) -> Self::IdentityProvider {
2141 self.config.identity_provider()
2142 }
2143
2144 fn psk_storage(&self) -> Self::PreSharedKeyStorage {
2145 self.config.secret_store()
2146 }
2147
2148 fn group_state(&self) -> &GroupState {
2149 &self.state
2150 }
2151
2152 fn group_state_mut(&mut self) -> &mut GroupState {
2153 &mut self.state
2154 }
2155
2156 fn removal_proposal(
2157 &self,
2158 provisional_state: &ProvisionalState,
2159 ) -> Option<ProposalInfo<RemoveProposal>> {
2160 provisional_state
2161 .applied_proposals
2162 .removals
2163 .iter()
2164 .find(|p| p.proposal.to_remove == self.private_tree.self_index)
2165 .cloned()
2166 }
2167
2168 #[cfg(feature = "private_message")]
2169 fn min_epoch_available(&self) -> Option<u64> {
2170 None
2171 }
2172
2173 fn cipher_suite_provider(&self) -> &Self::CipherSuiteProvider {
2174 &self.cipher_suite_provider
2175 }
2176 }
2177
2178 #[cfg(test)]
2179 pub(crate) mod test_utils;
2180
2181 #[cfg(test)]
2182 mod tests {
2183 use crate::{
2184 client::test_utils::{
2185 test_client_with_key_pkg, TestClientBuilder, TEST_CIPHER_SUITE, TEST_PROTOCOL_VERSION,
2186 },
2187 client_builder::test_utils::TestClientConfig,
2188 crypto::test_utils::TestCryptoProvider,
2189 group::proposal_filter::ProposalInfo,
2190 identity::test_utils::get_test_signing_identity,
2191 key_package::test_utils::test_key_package_message,
2192 mls_rules::CommitOptions,
2193 tree_kem::{
2194 leaf_node::{test_utils::get_test_capabilities, LeafNodeSource},
2195 UpdatePathNode,
2196 },
2197 };
2198
2199 #[cfg(feature = "by_ref_proposal")]
2200 use crate::{
2201 client::test_utils::{test_client_with_key_pkg_custom, TEST_CUSTOM_PROPOSAL_TYPE},
2202 client_builder::{ClientBuilder, MlsConfig},
2203 group::{
2204 component_operation::ComponentID,
2205 mls_rules::{CommitDirection, CommitSource},
2206 proposal_filter::ProposalBundle,
2207 },
2208 identity::basic::BasicIdentityProvider,
2209 identity::test_utils::BasicWithCustomProvider,
2210 };
2211
2212 #[cfg(any(feature = "private_message", feature = "custom_proposal"))]
2213 use crate::group::mls_rules::DefaultMlsRules;
2214
2215 #[cfg(feature = "prior_epoch")]
2216 use crate::group::padding::PaddingMode;
2217
2218 use crate::{extension::RequiredCapabilitiesExt, key_package::test_utils::test_key_package};
2219
2220 #[cfg(all(feature = "by_ref_proposal", feature = "custom_proposal"))]
2221 use super::test_utils::test_group_custom_config;
2222
2223 #[cfg(any(feature = "psk", feature = "std"))]
2224 use crate::client::Client;
2225
2226 #[cfg(feature = "psk")]
2227 use crate::psk::PreSharedKey;
2228
2229 #[cfg(any(feature = "by_ref_proposal", feature = "private_message"))]
2230 use crate::group::test_utils::random_bytes;
2231
2232 #[cfg(feature = "by_ref_proposal")]
2233 use crate::{
2234 extension::test_utils::TestExtension, identity::test_utils::get_test_basic_credential,
2235 time::MlsTime,
2236 };
2237
2238 use super::{
2239 test_utils::{
2240 get_test_25519_key, get_test_groups_with_features, group_extensions, process_commit,
2241 test_group, test_group_custom, test_n_member_group, TestGroup, TEST_GROUP,
2242 },
2243 *,
2244 };
2245
2246 use assert_matches::assert_matches;
2247
2248 use message_processor::CommitEffect;
2249 use mls_rs_core::extension::{Extension, ExtensionType};
2250 use mls_rs_core::identity::{Credential, CredentialType, CustomCredential};
2251
2252 #[cfg(feature = "by_ref_proposal")]
2253 use mls_rs_core::identity::CertificateChain;
2254
2255 #[cfg(feature = "by_ref_proposal")]
2256 use crate::{crypto::test_utils::test_cipher_suite_provider, extension::ExternalSendersExt};
2257
2258 #[cfg(feature = "private_message")]
2259 use super::test_utils::test_member;
2260
2261 use mls_rs_core::extension::MlsExtension;
2262
2263 #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
2264 async fn test_create_group() {
2265 for (protocol_version, cipher_suite) in ProtocolVersion::all().flat_map(|p| {
2266 TestCryptoProvider::all_supported_cipher_suites()
2267 .into_iter()
2268 .map(move |cs| (p, cs))
2269 }) {
2270 let group = test_group(protocol_version, cipher_suite).await;
2271
2272 assert_eq!(group.cipher_suite(), cipher_suite);
2273 assert_eq!(group.state.context.epoch, 0);
2274 assert_eq!(group.state.context.group_id, TEST_GROUP.to_vec());
2275 assert_eq!(group.state.context.extensions, group_extensions());
2276
2277 assert_eq!(
2278 group.state.context.confirmed_transcript_hash,
2279 ConfirmedTranscriptHash::from(vec![])
2280 );
2281
2282 #[cfg(feature = "private_message")]
2283 assert!(group.state.proposals.is_empty());
2284
2285 #[cfg(feature = "by_ref_proposal")]
2286 assert!(group.pending_updates.is_empty());
2287
2288 assert!(!group.has_pending_commit());
2289
2290 assert_eq!(
2291 group.private_tree.self_index.0,
2292 group.current_member_index()
2293 );
2294 }
2295 }
2296
2297 #[cfg(feature = "private_message")]
2298 #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
2299 async fn test_pending_proposals_application_data() {
2300 let mut test_group = test_group(TEST_PROTOCOL_VERSION, TEST_CIPHER_SUITE).await;
2301
2302 // Create a proposal
2303 let (bob_key_package, _) =
2304 test_member(TEST_PROTOCOL_VERSION, TEST_CIPHER_SUITE, b"bob").await;
2305
2306 let proposal = test_group
2307 .add_proposal(bob_key_package.key_package_message())
2308 .unwrap();
2309
2310 test_group.proposal_message(proposal, vec![]).await.unwrap();
2311
2312 // We should not be able to send application messages until a commit happens
2313 let res = test_group
2314 .encrypt_application_message(b"test", vec![])
2315 .await;
2316
2317 assert_matches!(res, Err(MlsError::CommitRequired));
2318
2319 // We should be able to send application messages after a commit
2320 test_group.commit(vec![]).await.unwrap();
2321
2322 assert!(test_group.has_pending_commit());
2323
2324 test_group.apply_pending_commit().await.unwrap();
2325
2326 let res = test_group
2327 .encrypt_application_message(b"test", vec![])
2328 .await;
2329
2330 assert!(res.is_ok());
2331 }
2332
2333 #[cfg(feature = "by_ref_proposal")]
2334 #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
2335 async fn test_update_proposals() {
2336 let new_extension = TestExtension { foo: 10 };
2337 let mut extension_list = ExtensionList::default();
2338 extension_list.set_from(new_extension).unwrap();
2339
2340 let mut test_group = test_group_custom(
2341 TEST_PROTOCOL_VERSION,
2342 TEST_CIPHER_SUITE,
2343 vec![42.into()],
2344 Some(extension_list.clone()),
2345 None,
2346 )
2347 .await;
2348
2349 let existing_leaf = test_group.current_user_leaf_node().unwrap().clone();
2350
2351 // Create an update proposal
2352 let proposal = test_group.update_proposal().await;
2353
2354 let update = match proposal {
2355 Proposal::Update(update) => update,
2356 _ => panic!("non update proposal found"),
2357 };
2358
2359 assert_ne!(update.leaf_node.public_key, existing_leaf.public_key);
2360
2361 assert_eq!(
2362 update.leaf_node.signing_identity,
2363 existing_leaf.signing_identity
2364 );
2365
2366 assert_eq!(update.leaf_node.ungreased_extensions(), extension_list);
2367 assert_eq!(
2368 update.leaf_node.ungreased_capabilities().sorted(),
2369 Capabilities {
2370 extensions: vec![42.into()],
2371 ..get_test_capabilities()
2372 }
2373 .sorted()
2374 );
2375 }
2376
2377 #[cfg(feature = "by_ref_proposal")]
2378 #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
2379 async fn test_invalid_commit_self_update() {
2380 let mut test_group = test_group(TEST_PROTOCOL_VERSION, TEST_CIPHER_SUITE).await;
2381
2382 // Create an update proposal
2383 let proposal_msg = test_group.propose_update(vec![]).await.unwrap();
2384
2385 let proposal = match proposal_msg.into_plaintext().unwrap().content.content {
2386 Content::Proposal(p) => p,
2387 _ => panic!("found non-proposal message"),
2388 };
2389
2390 let update_leaf = match *proposal {
2391 Proposal::Update(u) => u.leaf_node,
2392 _ => panic!("found proposal message that isn't an update"),
2393 };
2394
2395 test_group.commit(vec![]).await.unwrap();
2396 test_group.apply_pending_commit().await.unwrap();
2397
2398 // The leaf node should not be the one from the update, because the committer rejects it
2399 assert_ne!(&update_leaf, test_group.current_user_leaf_node().unwrap());
2400 }
2401
2402 #[cfg(feature = "by_ref_proposal")]
2403 #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
2404 async fn update_proposal_with_bad_key_package_is_ignored_when_committing() {
2405 let (mut alice_group, mut bob_group) =
2406 test_two_member_group(TEST_PROTOCOL_VERSION, TEST_CIPHER_SUITE, true).await;
2407
2408 let mut proposal = alice_group.update_proposal().await;
2409
2410 if let Proposal::Update(ref mut update) = proposal {
2411 update.leaf_node.signature = random_bytes(32);
2412 } else {
2413 panic!("Invalid update proposal")
2414 }
2415
2416 let proposal_message = alice_group
2417 .proposal_message(proposal.clone(), vec![])
2418 .await
2419 .unwrap();
2420
2421 let proposal_plaintext = match proposal_message.payload {
2422 MlsMessagePayload::Plain(p) => p,
2423 _ => panic!("Unexpected non-plaintext message"),
2424 };
2425
2426 let proposal_ref = ProposalRef::from_content(
2427 &bob_group.cipher_suite_provider,
2428 &proposal_plaintext.clone().into(),
2429 )
2430 .await
2431 .unwrap();
2432
2433 // Hack bob's receipt of the proposal
2434 bob_group
2435 .state
2436 .proposals
2437 .insert(proposal_ref, proposal, proposal_plaintext.content.sender);
2438
2439 let commit_output = bob_group.commit(vec![]).await.unwrap();
2440
2441 assert_matches!(
2442 commit_output.commit_message,
2443 MlsMessage {
2444 payload: MlsMessagePayload::Plain(
2445 PublicMessage {
2446 content: FramedContent {
2447 content: Content::Commit(c),
2448 ..
2449 },
2450 ..
2451 }),
2452 ..
2453 } if c.proposals.is_empty()
2454 );
2455 }
2456
2457 #[cfg(feature = "non_domain_separated_hpke_encrypt_decrypt")]
2458 #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
2459 async fn test_hpke_encrypt_decrypt() {
2460 let (alice_group, bob_group) =
2461 test_two_member_group(TEST_PROTOCOL_VERSION, TEST_CIPHER_SUITE, true).await;
2462 let receiver_index = alice_group.current_member_index();
2463 let sender_index = bob_group.current_member_index();
2464
2465 let context_info: Vec<u8> = vec![
2466 receiver_index.try_into().unwrap(),
2467 sender_index.try_into().unwrap(),
2468 ];
2469 let plaintext = b"message";
2470
2471 let hpke_ciphertext = bob_group
2472 .hpke_encrypt_to_recipient(receiver_index, &context_info, None, plaintext)
2473 .await
2474 .unwrap();
2475 let hpke_decrypted = alice_group
2476 .hpke_decrypt_for_current_member(&context_info, None, hpke_ciphertext)
2477 .await
2478 .unwrap();
2479
2480 assert_eq!(plaintext.to_vec(), hpke_decrypted);
2481 }
2482
2483 #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
2484 async fn safe_context_test_hpke_encrypt_decrypt() {
2485 let component_id: ComponentID = 1;
2486 let (alice_group, bob_group) =
2487 test_two_member_group(TEST_PROTOCOL_VERSION, TEST_CIPHER_SUITE, true).await;
2488 let receiver_index = alice_group.current_member_index();
2489 let sender_index = bob_group.current_member_index();
2490
2491 let context_info: Vec<u8> = vec![
2492 receiver_index.try_into().unwrap(),
2493 sender_index.try_into().unwrap(),
2494 ];
2495 let plaintext = b"message";
2496
2497 let hpke_ciphertext = bob_group
2498 .safe_encrypt_with_context_to_recipient(
2499 receiver_index,
2500 component_id,
2501 &context_info,
2502 None,
2503 plaintext,
2504 )
2505 .await
2506 .unwrap();
2507 let hpke_decrypted = alice_group
2508 .safe_decrypt_with_context_for_current_member(
2509 component_id,
2510 &context_info,
2511 None,
2512 hpke_ciphertext,
2513 )
2514 .await
2515 .unwrap();
2516
2517 assert_eq!(plaintext.to_vec(), hpke_decrypted);
2518 }
2519
2520 #[cfg(feature = "non_domain_separated_hpke_encrypt_decrypt")]
2521 #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
2522 async fn test_hpke_non_recipient_cant_decrypt() {
2523 let mut alice = test_group(TEST_PROTOCOL_VERSION, TEST_CIPHER_SUITE).await;
2524 let (mut bob, _) = alice.join("bob").await;
2525 let (carol, commit) = alice.join("carol").await;
2526
2527 // Apply the commit that adds carol
2528 bob.process_incoming_message(commit).await.unwrap();
2529
2530 let receiver_index = alice.current_member_index();
2531 let sender_index = bob.current_member_index();
2532
2533 let context_info: Vec<u8> = vec![
2534 receiver_index.try_into().unwrap(),
2535 sender_index.try_into().unwrap(),
2536 ];
2537 let plaintext = b"message";
2538
2539 let hpke_ciphertext = bob
2540 .hpke_encrypt_to_recipient(receiver_index, &context_info, None, plaintext)
2541 .await
2542 .unwrap();
2543
2544 // different recipient tries to decrypt
2545 let hpke_decrypted = carol
2546 .hpke_decrypt_for_current_member(&context_info, None, hpke_ciphertext)
2547 .await;
2548
2549 // should fail because carol can't decrypt the message encrypted for alice
2550 assert_matches!(hpke_decrypted, Err(MlsError::CryptoProviderError(_)));
2551 }
2552
2553 #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
2554 async fn safe_context_test_hpke_non_recipient_cant_decrypt() {
2555 let component_id: ComponentID = 345;
2556 let mut alice = test_group(TEST_PROTOCOL_VERSION, TEST_CIPHER_SUITE).await;
2557 let (mut bob, _) = alice.join("bob").await;
2558 let (carol, commit) = alice.join("carol").await;
2559
2560 // Apply the commit that adds carol
2561 bob.process_incoming_message(commit).await.unwrap();
2562
2563 let receiver_index = alice.current_member_index();
2564 let sender_index = bob.current_member_index();
2565
2566 let context_info: Vec<u8> = vec![
2567 receiver_index.try_into().unwrap(),
2568 sender_index.try_into().unwrap(),
2569 ];
2570 let plaintext = b"message";
2571
2572 let hpke_ciphertext = bob
2573 .safe_encrypt_with_context_to_recipient(
2574 receiver_index,
2575 component_id,
2576 &context_info,
2577 None,
2578 plaintext,
2579 )
2580 .await
2581 .unwrap();
2582
2583 // different recipient tries to decrypt
2584 let hpke_decrypted = carol
2585 .safe_decrypt_with_context_for_current_member(
2586 component_id,
2587 &context_info,
2588 None,
2589 hpke_ciphertext,
2590 )
2591 .await;
2592
2593 // should fail because carol can't decrypt the message encrypted for alice
2594 assert_matches!(hpke_decrypted, Err(MlsError::CryptoProviderError(_)));
2595 }
2596
2597 #[cfg(feature = "non_domain_separated_hpke_encrypt_decrypt")]
2598 #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
2599 async fn test_hpke_can_decrypt_after_group_changes() {
2600 let mut alice = test_group(TEST_PROTOCOL_VERSION, TEST_CIPHER_SUITE).await;
2601 let (mut bob, _) = alice.join("bob").await;
2602
2603 let receiver_index = alice.current_member_index();
2604 let sender_index = bob.current_member_index();
2605 let context_info: Vec<u8> = vec![
2606 receiver_index.try_into().unwrap(),
2607 sender_index.try_into().unwrap(),
2608 ];
2609 let associated_data: Vec<u8> = vec![1, 2, 3, 4];
2610 let plaintext = b"message";
2611
2612 // encrypt the message to alice
2613 let hpke_ciphertext = bob
2614 .hpke_encrypt_to_recipient(
2615 receiver_index,
2616 &context_info,
2617 Some(&associated_data),
2618 plaintext,
2619 )
2620 .await
2621 .unwrap();
2622
2623 // add carol to the group
2624 let (_carol, commit) = alice.join("carol").await;
2625 bob.process_incoming_message(commit).await.unwrap();
2626
2627 // make sure alice can still decrypt
2628 let hpke_decrypted = alice
2629 .hpke_decrypt_for_current_member(&context_info, Some(&associated_data), hpke_ciphertext)
2630 .await
2631 .unwrap();
2632 assert_eq!(plaintext.to_vec(), hpke_decrypted);
2633 }
2634
2635 #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
2636 async fn safe_context_test_hpke_can_decrypt_after_group_changes() {
2637 let component_id: ComponentID = 2;
2638 let mut alice = test_group(TEST_PROTOCOL_VERSION, TEST_CIPHER_SUITE).await;
2639 let (mut bob, _) = alice.join("bob").await;
2640
2641 let receiver_index = alice.current_member_index();
2642 let sender_index = bob.current_member_index();
2643 let context_info: Vec<u8> = vec![
2644 receiver_index.try_into().unwrap(),
2645 sender_index.try_into().unwrap(),
2646 ];
2647 let associated_data: Vec<u8> = vec![1, 2, 3, 4];
2648 let plaintext = b"message";
2649
2650 // encrypt the message to alice
2651 let hpke_ciphertext = bob
2652 .safe_encrypt_with_context_to_recipient(
2653 receiver_index,
2654 component_id,
2655 &context_info,
2656 Some(&associated_data),
2657 plaintext,
2658 )
2659 .await
2660 .unwrap();
2661
2662 // add carol to the group
2663 let (_carol, commit) = alice.join("carol").await;
2664 bob.process_incoming_message(commit).await.unwrap();
2665
2666 // make sure alice can still decrypt
2667 let hpke_decrypted = alice
2668 .safe_decrypt_with_context_for_current_member(
2669 component_id,
2670 &context_info,
2671 Some(&associated_data),
2672 hpke_ciphertext,
2673 )
2674 .await
2675 .unwrap();
2676 assert_eq!(plaintext.to_vec(), hpke_decrypted);
2677 }
2678
2679 #[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)]
2680 async fn test_two_member_group(
2681 protocol_version: ProtocolVersion,
2682 cipher_suite: CipherSuite,
2683 tree_ext: bool,
2684 ) -> (TestGroup, TestGroup) {
2685 let mut test_group = test_group_custom(
2686 protocol_version,
2687 cipher_suite,
2688 Default::default(),
2689 None,
2690 Some(CommitOptions::new().with_ratchet_tree_extension(tree_ext)),
2691 )
2692 .await;
2693
2694 let (bob_test_group, _) = test_group.join("bob").await;
2695
2696 assert!(Group::equal_group_state(&test_group, &bob_test_group));
2697
2698 (test_group, bob_test_group)
2699 }
2700
2701 #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
2702 async fn test_welcome_processing_exported_tree() {
2703 test_two_member_group(TEST_PROTOCOL_VERSION, TEST_CIPHER_SUITE, false).await;
2704 }
2705
2706 #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
2707 async fn test_welcome_processing_tree_extension() {
2708 test_two_member_group(TEST_PROTOCOL_VERSION, TEST_CIPHER_SUITE, true).await;
2709 }
2710
2711 #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
2712 async fn test_welcome_processing_missing_tree() {
2713 let mut test_group = test_group_custom(
2714 TEST_PROTOCOL_VERSION,
2715 TEST_CIPHER_SUITE,
2716 Default::default(),
2717 None,
2718 Some(CommitOptions::new().with_ratchet_tree_extension(false)),
2719 )
2720 .await;
2721
2722 let (bob_client, bob_key_package) =
2723 test_client_with_key_pkg(TEST_PROTOCOL_VERSION, TEST_CIPHER_SUITE, "bob").await;
2724
2725 // Add bob to the group
2726 let commit_output = test_group
2727 .commit_builder()
2728 .add_member(bob_key_package)
2729 .unwrap()
2730 .build()
2731 .await
2732 .unwrap();
2733
2734 // Group from Bob's perspective
2735 let bob_group = Group::join(
2736 &commit_output.welcome_messages[0],
2737 None,
2738 bob_client.config,
2739 bob_client.signer.unwrap(),
2740 )
2741 .await
2742 .map(|_| ());
2743
2744 assert_matches!(bob_group, Err(MlsError::RatchetTreeNotFound));
2745 }
2746
2747 #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
2748 async fn test_reused_key_package() {
2749 let mut alice_group = test_group(TEST_PROTOCOL_VERSION, TEST_CIPHER_SUITE).await;
2750 let (bob_client, bob_key_package) =
2751 test_client_with_key_pkg(TEST_PROTOCOL_VERSION, TEST_CIPHER_SUITE, "bob").await;
2752 let mut carla_group = test_group(TEST_PROTOCOL_VERSION, TEST_CIPHER_SUITE).await;
2753
2754 // Alice adds Bob to her group.
2755 let commit_output = alice_group
2756 .group
2757 .commit_builder()
2758 .add_member(bob_key_package.clone())
2759 .unwrap()
2760 .build()
2761 .await
2762 .unwrap();
2763
2764 // Bob joins group.
2765 let (mut bob_group, _) = bob_client
2766 .join_group(None, &commit_output.welcome_messages[0])
2767 .await
2768 .unwrap();
2769 // This deletes the key package used to join the group.
2770 bob_group.write_to_storage().await.unwrap();
2771
2772 // Carla adds Bob, reusing the same key package.
2773 let commit_output = carla_group
2774 .group
2775 .commit_builder()
2776 .add_member(bob_key_package.clone())
2777 .unwrap()
2778 .build()
2779 .await
2780 .unwrap();
2781
2782 // Bob cannot join Carla's group.
2783 let bob_group = bob_client
2784 .join_group(None, &commit_output.welcome_messages[0])
2785 .await
2786 .map(|_| ());
2787 assert_matches!(bob_group, Err(MlsError::WelcomeKeyPackageNotFound));
2788 }
2789
2790 #[cfg(feature = "last_resort_key_package_ext")]
2791 #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
2792 async fn test_last_resort_key_package() -> Result<(), MlsError> {
2793 let mut alice_group = test_group(TEST_PROTOCOL_VERSION, TEST_CIPHER_SUITE).await;
2794 let (bob_client, bob_key_package) = test_client_with_key_pkg_custom(
2795 TEST_PROTOCOL_VERSION,
2796 TEST_CIPHER_SUITE,
2797 "bob",
2798 vec![LastResortKeyPackageExt.into_extension().unwrap()].into(),
2799 Default::default(),
2800 |_| {},
2801 )
2802 .await;
2803 let mut carla_group = test_group(TEST_PROTOCOL_VERSION, TEST_CIPHER_SUITE).await;
2804
2805 // Alice adds Bob to her group.
2806 let commit_output = alice_group
2807 .group
2808 .commit_builder()
2809 .add_member(bob_key_package.clone())?
2810 .build()
2811 .await?;
2812
2813 // Bob joins group.
2814 let (mut bob_group, _) = bob_client
2815 .join_group(None, &commit_output.welcome_messages[0])
2816 .await?;
2817 // This no longer deletes the key package
2818 bob_group.write_to_storage()?;
2819
2820 // Carla adds Bob, reusing the same key package.
2821 let commit_output = carla_group
2822 .group
2823 .commit_builder()
2824 .add_member(bob_key_package.clone())?
2825 .build()
2826 .await?;
2827
2828 // Bob can join Carla's group.
2829 bob_client
2830 .join_group(None, &commit_output.welcome_messages[0])
2831 .await?;
2832
2833 Ok(())
2834 }
2835
2836 #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
2837 async fn test_group_context_ext_proposal_create() {
2838 let test_group = test_group(TEST_PROTOCOL_VERSION, TEST_CIPHER_SUITE).await;
2839
2840 let mut extension_list = ExtensionList::new();
2841 extension_list
2842 .set_from(RequiredCapabilitiesExt {
2843 extensions: vec![42.into()],
2844 proposals: vec![],
2845 credentials: vec![],
2846 })
2847 .unwrap();
2848
2849 let proposal = test_group.group_context_extensions_proposal(extension_list.clone());
2850
2851 assert_matches!(proposal, Proposal::GroupContextExtensions(ext) if ext == extension_list);
2852 }
2853
2854 #[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)]
2855 async fn group_context_extension_proposal_test(
2856 ext_list: ExtensionList,
2857 ) -> (TestGroup, Result<MlsMessage, MlsError>) {
2858 let protocol_version = TEST_PROTOCOL_VERSION;
2859 let cipher_suite = TEST_CIPHER_SUITE;
2860
2861 let mut test_group =
2862 test_group_custom(protocol_version, cipher_suite, vec![42.into()], None, None).await;
2863
2864 let commit = test_group
2865 .commit_builder()
2866 .set_group_context_ext(ext_list)
2867 .unwrap()
2868 .build()
2869 .await
2870 .map(|commit_output| commit_output.commit_message);
2871
2872 (test_group, commit)
2873 }
2874
2875 #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
2876 async fn test_group_context_ext_proposal_commit() {
2877 use message_processor::CommitEffect;
2878
2879 let mut extension_list = ExtensionList::new();
2880
2881 extension_list
2882 .set_from(RequiredCapabilitiesExt {
2883 extensions: vec![42.into()],
2884 proposals: vec![],
2885 credentials: vec![],
2886 })
2887 .unwrap();
2888
2889 let (mut test_group, _) =
2890 group_context_extension_proposal_test(extension_list.clone()).await;
2891
2892 let update = test_group.apply_pending_commit().await.unwrap();
2893
2894 // FIXME: Test Reporting
2895 assert_matches!(update.effect, CommitEffect::NewEpoch(_));
2896
2897 assert_eq!(test_group.state.context.extensions, extension_list)
2898 }
2899
2900 #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
2901 async fn test_group_context_ext_proposal_invalid() {
2902 let mut extension_list = ExtensionList::new();
2903 extension_list
2904 .set_from(RequiredCapabilitiesExt {
2905 extensions: vec![999.into()],
2906 proposals: vec![],
2907 credentials: vec![],
2908 })
2909 .unwrap();
2910
2911 let (_, commit) = group_context_extension_proposal_test(extension_list.clone()).await;
2912
2913 assert_matches!(
2914 commit,
2915 Err(MlsError::RequiredExtensionNotFound(a)) if a == 999.into()
2916 );
2917 }
2918
2919 #[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)]
2920 async fn make_group_with_required_capabilities(
2921 required_caps: RequiredCapabilitiesExt,
2922 ) -> Result<Group<TestClientConfig>, MlsError> {
2923 test_client_with_key_pkg(TEST_PROTOCOL_VERSION, TEST_CIPHER_SUITE, "alice")
2924 .await
2925 .0
2926 .create_group(
2927 core::iter::once(required_caps.into_extension().unwrap()).collect(),
2928 Default::default(),
2929 )
2930 .await
2931 }
2932
2933 #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
2934 async fn creating_group_with_member_not_supporting_required_credential_type_fails() {
2935 let group_creation = make_group_with_required_capabilities(RequiredCapabilitiesExt {
2936 credentials: vec![CredentialType::BASIC, CredentialType::X509],
2937 ..Default::default()
2938 })
2939 .await
2940 .map(|_| ());
2941
2942 assert_matches!(
2943 group_creation,
2944 Err(MlsError::RequiredCredentialNotFound(CredentialType::X509))
2945 );
2946 }
2947
2948 #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
2949 async fn creating_group_with_member_not_supporting_required_extension_type_fails() {
2950 const EXTENSION_TYPE: ExtensionType = ExtensionType::new(33);
2951
2952 let group_creation = make_group_with_required_capabilities(RequiredCapabilitiesExt {
2953 extensions: vec![EXTENSION_TYPE],
2954 ..Default::default()
2955 })
2956 .await
2957 .map(|_| ());
2958
2959 assert_matches!(
2960 group_creation,
2961 Err(MlsError::RequiredExtensionNotFound(EXTENSION_TYPE))
2962 );
2963 }
2964
2965 #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
2966 async fn creating_group_with_member_not_supporting_required_proposal_type_fails() {
2967 const PROPOSAL_TYPE: ProposalType = ProposalType::new(33);
2968
2969 let group_creation = make_group_with_required_capabilities(RequiredCapabilitiesExt {
2970 proposals: vec![PROPOSAL_TYPE],
2971 ..Default::default()
2972 })
2973 .await
2974 .map(|_| ());
2975
2976 assert_matches!(
2977 group_creation,
2978 Err(MlsError::RequiredProposalNotFound(PROPOSAL_TYPE))
2979 );
2980 }
2981
2982 #[cfg(feature = "by_ref_proposal")]
2983 #[cfg(not(target_arch = "wasm32"))]
2984 #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
2985 async fn creating_group_with_member_not_supporting_external_sender_credential_fails() {
2986 let ext_senders = make_x509_external_senders_ext()
2987 .await
2988 .into_extension()
2989 .unwrap();
2990
2991 let group_creation =
2992 test_client_with_key_pkg(TEST_PROTOCOL_VERSION, TEST_CIPHER_SUITE, "alice")
2993 .await
2994 .0
2995 .create_group(core::iter::once(ext_senders).collect(), Default::default())
2996 .await
2997 .map(|_| ());
2998
2999 assert_matches!(
3000 group_creation,
3001 Err(MlsError::RequiredCredentialNotFound(CredentialType::X509))
3002 );
3003 }
3004
3005 #[cfg(all(not(target_arch = "wasm32"), feature = "private_message"))]
3006 #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
3007 async fn test_group_encrypt_plaintext_padding() {
3008 let protocol_version = TEST_PROTOCOL_VERSION;
3009 // This test requires a cipher suite whose signatures are not variable in length.
3010 let cipher_suite = CipherSuite::CURVE25519_AES128;
3011
3012 let mut test_group = test_group_custom_config(protocol_version, cipher_suite, |b| {
3013 b.mls_rules(
3014 DefaultMlsRules::default()
3015 .with_encryption_options(EncryptionOptions::new(true, PaddingMode::None)),
3016 )
3017 })
3018 .await;
3019
3020 let without_padding = test_group
3021 .encrypt_application_message(&random_bytes(150), vec![])
3022 .await
3023 .unwrap();
3024
3025 let mut test_group =
3026 test_group_custom_config(protocol_version, cipher_suite, |b| {
3027 b.mls_rules(DefaultMlsRules::default().with_encryption_options(
3028 EncryptionOptions::new(true, PaddingMode::StepFunction),
3029 ))
3030 })
3031 .await;
3032
3033 let with_padding = test_group
3034 .encrypt_application_message(&random_bytes(150), vec![])
3035 .await
3036 .unwrap();
3037
3038 assert!(with_padding.mls_encoded_len() > without_padding.mls_encoded_len());
3039 }
3040
3041 #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
3042 async fn external_commit_requires_external_pub_extension() {
3043 let protocol_version = TEST_PROTOCOL_VERSION;
3044 let cipher_suite = TEST_CIPHER_SUITE;
3045 let group = test_group(protocol_version, cipher_suite).await;
3046
3047 let info = group
3048 .group_info_message(false)
3049 .await
3050 .unwrap()
3051 .into_group_info()
3052 .unwrap();
3053
3054 let info_msg = MlsMessage::new(protocol_version, MlsMessagePayload::GroupInfo(info));
3055
3056 let signing_identity = group.current_member_signing_identity().unwrap().clone();
3057
3058 let res = external_commit::ExternalCommitBuilder::new(
3059 group.group.signer,
3060 signing_identity,
3061 group.group.config,
3062 )
3063 .build(info_msg)
3064 .await
3065 .map(|_| {});
3066
3067 assert_matches!(res, Err(MlsError::MissingExternalPubExtension));
3068 }
3069
3070 #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
3071 async fn external_commit_via_commit_options_round_trip() {
3072 let mut group = test_group_custom(
3073 TEST_PROTOCOL_VERSION,
3074 TEST_CIPHER_SUITE,
3075 vec![],
3076 None,
3077 CommitOptions::default()
3078 .with_allow_external_commit(true)
3079 .into(),
3080 )
3081 .await;
3082
3083 let commit_output = group.commit(vec![]).await.unwrap();
3084
3085 let (test_client, _) =
3086 test_client_with_key_pkg(TEST_PROTOCOL_VERSION, TEST_CIPHER_SUITE, "bob").await;
3087
3088 test_client
3089 .external_commit_builder()
3090 .unwrap()
3091 .build(commit_output.external_commit_group_info.unwrap())
3092 .await
3093 .unwrap();
3094 }
3095
3096 #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
3097 async fn test_path_update_preference() {
3098 let protocol_version = TEST_PROTOCOL_VERSION;
3099 let cipher_suite = TEST_CIPHER_SUITE;
3100
3101 let mut test_group = test_group_custom(
3102 protocol_version,
3103 cipher_suite,
3104 Default::default(),
3105 None,
3106 Some(CommitOptions::new()),
3107 )
3108 .await;
3109
3110 let test_key_package =
3111 test_key_package_message(protocol_version, cipher_suite, "alice").await;
3112
3113 let has_path = test_group
3114 .commit_builder()
3115 .add_member(test_key_package.clone())
3116 .unwrap()
3117 .build()
3118 .await
3119 .unwrap()
3120 .contains_update_path;
3121
3122 assert!(!has_path);
3123
3124 let mut test_group = test_group_custom(
3125 protocol_version,
3126 cipher_suite,
3127 Default::default(),
3128 None,
3129 Some(CommitOptions::new().with_path_required(true)),
3130 )
3131 .await;
3132
3133 let has_path = test_group
3134 .commit_builder()
3135 .add_member(test_key_package)
3136 .unwrap()
3137 .build()
3138 .await
3139 .unwrap()
3140 .contains_update_path;
3141
3142 assert!(has_path)
3143 }
3144
3145 #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
3146 async fn test_path_update_preference_override() {
3147 let protocol_version = TEST_PROTOCOL_VERSION;
3148 let cipher_suite = TEST_CIPHER_SUITE;
3149
3150 let mut test_group = test_group_custom(
3151 protocol_version,
3152 cipher_suite,
3153 Default::default(),
3154 None,
3155 Some(CommitOptions::new()),
3156 )
3157 .await;
3158
3159 let has_path = test_group
3160 .commit(vec![])
3161 .await
3162 .unwrap()
3163 .contains_update_path;
3164
3165 assert!(has_path);
3166 }
3167
3168 #[cfg(feature = "private_message")]
3169 #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
3170 async fn group_rejects_unencrypted_application_message() {
3171 let protocol_version = TEST_PROTOCOL_VERSION;
3172 let cipher_suite = TEST_CIPHER_SUITE;
3173
3174 let mut alice = test_group(protocol_version, cipher_suite).await;
3175 let (mut bob, _) = alice.join("bob").await;
3176
3177 let message = alice
3178 .make_plaintext(Content::Application(b"hello".to_vec().into()))
3179 .await;
3180
3181 let res = bob.process_incoming_message(message).await;
3182
3183 assert_matches!(res, Err(MlsError::UnencryptedApplicationMessage));
3184 }
3185
3186 #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
3187 async fn commit_description_external_commit() {
3188 let mut alice_group = test_group(TEST_PROTOCOL_VERSION, TEST_CIPHER_SUITE).await;
3189
3190 let (bob_identity, secret_key) = get_test_signing_identity(TEST_CIPHER_SUITE, b"bob").await;
3191
3192 let bob = TestClientBuilder::new_for_test()
3193 .signing_identity(bob_identity, secret_key, TEST_CIPHER_SUITE)
3194 .build();
3195
3196 let (bob_group, commit) = bob
3197 .external_commit_builder()
3198 .unwrap()
3199 .build(
3200 alice_group
3201 .group_info_message_allowing_ext_commit(true)
3202 .await
3203 .unwrap(),
3204 )
3205 .await
3206 .unwrap();
3207
3208 let event = alice_group.process_message(commit).await.unwrap();
3209
3210 let ReceivedMessage::Commit(commit_description) = event else {
3211 panic!("expected commit");
3212 };
3213
3214 assert!(commit_description.is_external);
3215 assert_eq!(commit_description.committer, 1);
3216
3217 let new_epoch = match commit_description.effect {
3218 CommitEffect::NewEpoch(new_epoch) => new_epoch,
3219 _ => panic!("unexpected commit effect"),
3220 };
3221
3222 assert_eq!(new_epoch.applied_proposals.len(), 1);
3223
3224 itertools::assert_equal(
3225 bob_group.roster().members_iter(),
3226 alice_group.roster().members_iter(),
3227 );
3228 }
3229
3230 #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
3231 async fn can_join_new_group_externally() {
3232 use crate::client::test_utils::TestClientBuilder;
3233
3234 let mut alice_group = test_group(TEST_PROTOCOL_VERSION, TEST_CIPHER_SUITE).await;
3235
3236 let (bob_identity, secret_key) = get_test_signing_identity(TEST_CIPHER_SUITE, b"bob").await;
3237
3238 let bob = TestClientBuilder::new_for_test()
3239 .signing_identity(bob_identity, secret_key, TEST_CIPHER_SUITE)
3240 .build();
3241
3242 let (_, commit) = bob
3243 .external_commit_builder()
3244 .unwrap()
3245 .with_tree_data(alice_group.export_tree().into_owned())
3246 .build(
3247 alice_group
3248 .group_info_message_allowing_ext_commit(false)
3249 .await
3250 .unwrap(),
3251 )
3252 .await
3253 .unwrap();
3254
3255 alice_group.process_message(commit).await.unwrap();
3256 }
3257
3258 #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
3259 async fn test_membership_tag_from_non_member() {
3260 let (mut alice_group, mut bob_group) =
3261 test_two_member_group(TEST_PROTOCOL_VERSION, TEST_CIPHER_SUITE, true).await;
3262
3263 let mut commit_output = alice_group.commit(vec![]).await.unwrap();
3264
3265 let plaintext = match commit_output.commit_message.payload {
3266 MlsMessagePayload::Plain(ref mut plain) => plain,
3267 _ => panic!("Non plaintext message"),
3268 };
3269
3270 plaintext.content.sender = Sender::NewMemberCommit;
3271
3272 let res = bob_group
3273 .process_message(commit_output.commit_message)
3274 .await;
3275
3276 assert_matches!(res, Err(MlsError::MembershipTagForNonMember));
3277 }
3278
3279 #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
3280 async fn test_partial_commits() {
3281 let protocol_version = TEST_PROTOCOL_VERSION;
3282 let cipher_suite = TEST_CIPHER_SUITE;
3283
3284 let mut alice = test_group(protocol_version, cipher_suite).await;
3285 let (mut bob, _) = alice.join("bob").await;
3286 let (mut charlie, commit) = alice.join("charlie").await;
3287 bob.process_message(commit).await.unwrap();
3288
3289 let (_, commit) = charlie.join("dave").await;
3290
3291 alice.process_message(commit.clone()).await.unwrap();
3292 bob.process_message(commit.clone()).await.unwrap();
3293
3294 let Content::Commit(commit) = commit.into_plaintext().unwrap().content.content else {
3295 panic!("Expected commit")
3296 };
3297
3298 assert!(commit.path.is_none());
3299 }
3300
3301 #[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)]
3302 async fn group_with_path_required() -> TestGroup {
3303 let mut alice = test_group(TEST_PROTOCOL_VERSION, TEST_CIPHER_SUITE).await;
3304
3305 alice.config.0.mls_rules.commit_options.path_required = true;
3306
3307 alice
3308 }
3309
3310 #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
3311 async fn old_hpke_secrets_are_removed() {
3312 let mut alice = group_with_path_required().await;
3313 alice.join("bob").await;
3314 alice.join("charlie").await;
3315
3316 alice
3317 .commit_builder()
3318 .remove_member(1)
3319 .unwrap()
3320 .build()
3321 .await
3322 .unwrap();
3323
3324 assert!(alice.private_tree.secret_keys[1].is_some());
3325 alice.process_pending_commit().await.unwrap();
3326 assert!(alice.private_tree.secret_keys[1].is_none());
3327 }
3328
3329 #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
3330 async fn old_hpke_secrets_of_removed_are_removed() {
3331 let mut alice = group_with_path_required().await;
3332 alice.join("bob").await;
3333 let (mut charlie, _) = alice.join("charlie").await;
3334
3335 let commit = charlie
3336 .commit_builder()
3337 .remove_member(1)
3338 .unwrap()
3339 .build()
3340 .await
3341 .unwrap();
3342
3343 assert!(alice.private_tree.secret_keys[1].is_some());
3344 alice.process_message(commit.commit_message).await.unwrap();
3345 assert!(alice.private_tree.secret_keys[1].is_none());
3346 }
3347
3348 #[cfg(feature = "by_ref_proposal")]
3349 #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
3350 async fn old_hpke_secrets_of_updated_are_removed() {
3351 let mut alice = group_with_path_required().await;
3352 let (mut bob, _) = alice.join("bob").await;
3353 let (mut charlie, commit) = alice.join("charlie").await;
3354 bob.process_message(commit).await.unwrap();
3355
3356 let update = bob.propose_update(vec![]).await.unwrap();
3357 charlie.process_message(update.clone()).await.unwrap();
3358 alice.process_message(update).await.unwrap();
3359
3360 let commit = charlie.commit(vec![]).await.unwrap();
3361
3362 assert!(alice.private_tree.secret_keys[1].is_some());
3363 alice.process_message(commit.commit_message).await.unwrap();
3364 assert!(alice.private_tree.secret_keys[1].is_none());
3365 }
3366
3367 #[cfg(feature = "psk")]
3368 #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
3369 async fn only_selected_members_of_the_original_group_can_join_subgroup() {
3370 let mut alice = test_group(TEST_PROTOCOL_VERSION, TEST_CIPHER_SUITE).await;
3371 let (mut bob, _) = alice.join("bob").await;
3372 let (carol, commit) = alice.join("carol").await;
3373
3374 // Apply the commit that adds carol
3375 bob.process_incoming_message(commit).await.unwrap();
3376
3377 let bob_identity = bob.current_member_signing_identity().unwrap().clone();
3378 let signer = bob.signer.clone();
3379
3380 let new_key_pkg = Client::new(
3381 bob.config.clone(),
3382 Some(signer),
3383 Some((bob_identity, TEST_CIPHER_SUITE)),
3384 TEST_PROTOCOL_VERSION,
3385 )
3386 .generate_key_package_message(Default::default(), Default::default())
3387 .await
3388 .unwrap();
3389
3390 let (mut alice_sub_group, welcome) = alice
3391 .branch(b"subgroup".to_vec(), vec![new_key_pkg])
3392 .await
3393 .unwrap();
3394
3395 let welcome = &welcome[0];
3396
3397 let (mut bob_sub_group, _) = bob.join_subgroup(welcome, None).await.unwrap();
3398
3399 // Carol can't join
3400 let res = carol.join_subgroup(welcome, None).await.map(|_| ());
3401 assert_matches!(res, Err(_));
3402
3403 // Alice and Bob can still talk
3404 let commit_output = alice_sub_group.commit(vec![]).await.unwrap();
3405
3406 bob_sub_group
3407 .process_incoming_message(commit_output.commit_message)
3408 .await
3409 .unwrap();
3410 }
3411
3412 #[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)]
3413 async fn joining_group_fails_if_unsupported<F>(
3414 f: F,
3415 ) -> Result<(TestGroup, MlsMessage), MlsError>
3416 where
3417 F: FnMut(&mut TestClientConfig),
3418 {
3419 let mut alice_group = test_group(TEST_PROTOCOL_VERSION, TEST_CIPHER_SUITE).await;
3420 alice_group.join_with_custom_config("alice", false, f).await
3421 }
3422
3423 #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
3424 async fn joining_group_fails_if_protocol_version_is_not_supported() {
3425 let res = joining_group_fails_if_unsupported(|config| {
3426 config.0.settings.protocol_versions.clear();
3427 })
3428 .await
3429 .map(|_| ());
3430
3431 assert_matches!(
3432 res,
3433 Err(MlsError::UnsupportedProtocolVersion(v)) if v ==
3434 TEST_PROTOCOL_VERSION
3435 );
3436 }
3437
3438 // WebCrypto does not support disabling ciphersuites
3439 #[cfg(not(target_arch = "wasm32"))]
3440 #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
3441 async fn joining_group_fails_if_cipher_suite_is_not_supported() {
3442 let res = joining_group_fails_if_unsupported(|config| {
3443 config
3444 .0
3445 .crypto_provider
3446 .enabled_cipher_suites
3447 .retain(|&x| x != TEST_CIPHER_SUITE);
3448 })
3449 .await
3450 .map(|_| ());
3451
3452 assert_matches!(
3453 res,
3454 Err(MlsError::UnsupportedCipherSuite(TEST_CIPHER_SUITE))
3455 );
3456 }
3457
3458 #[cfg(feature = "private_message")]
3459 #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
3460 async fn member_can_see_sender_creds() {
3461 let mut alice_group = test_group(TEST_PROTOCOL_VERSION, TEST_CIPHER_SUITE).await;
3462 let (mut bob_group, _) = alice_group.join("bob").await;
3463
3464 let bob_msg = b"I'm Bob";
3465
3466 let msg = bob_group
3467 .encrypt_application_message(bob_msg, vec![])
3468 .await
3469 .unwrap();
3470
3471 let received_by_alice = alice_group.process_incoming_message(msg).await.unwrap();
3472
3473 assert_matches!(
3474 received_by_alice,
3475 ReceivedMessage::ApplicationMessage(ApplicationMessageDescription { sender_index, .. })
3476 if sender_index == bob_group.current_member_index()
3477 );
3478 }
3479
3480 #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
3481 async fn members_of_a_group_have_identical_authentication_secrets() {
3482 let mut alice_group = test_group(TEST_PROTOCOL_VERSION, TEST_CIPHER_SUITE).await;
3483 let (bob_group, _) = alice_group.join("bob").await;
3484
3485 assert_eq!(
3486 alice_group.epoch_authenticator().unwrap(),
3487 bob_group.epoch_authenticator().unwrap()
3488 );
3489 }
3490
3491 #[cfg(feature = "private_message")]
3492 #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
3493 async fn member_cannot_decrypt_same_message_twice() {
3494 let mut alice_group = test_group(TEST_PROTOCOL_VERSION, TEST_CIPHER_SUITE).await;
3495 let (mut bob_group, _) = alice_group.join("bob").await;
3496
3497 let message = alice_group
3498 .encrypt_application_message(b"foobar", Vec::new())
3499 .await
3500 .unwrap();
3501
3502 let received_message = bob_group
3503 .process_incoming_message(message.clone())
3504 .await
3505 .unwrap();
3506
3507 assert_matches!(
3508 received_message,
3509 ReceivedMessage::ApplicationMessage(m) if m.data() == b"foobar"
3510 );
3511
3512 let res = bob_group.process_incoming_message(message).await;
3513
3514 assert_matches!(res, Err(MlsError::KeyMissing(0)));
3515 }
3516
3517 #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
3518 async fn removing_requirements_allows_to_add() {
3519 let mut alice_group = test_group_custom(
3520 TEST_PROTOCOL_VERSION,
3521 TEST_CIPHER_SUITE,
3522 vec![17.into()],
3523 None,
3524 None,
3525 )
3526 .await;
3527
3528 alice_group
3529 .commit_builder()
3530 .set_group_context_ext(
3531 vec![RequiredCapabilitiesExt {
3532 extensions: vec![17.into()],
3533 ..Default::default()
3534 }
3535 .into_extension()
3536 .unwrap()]
3537 .try_into()
3538 .unwrap(),
3539 )
3540 .unwrap()
3541 .build()
3542 .await
3543 .unwrap();
3544
3545 alice_group.process_pending_commit().await.unwrap();
3546
3547 let test_key_package =
3548 test_key_package(TEST_PROTOCOL_VERSION, TEST_CIPHER_SUITE, "bob").await;
3549
3550 let test_key_package = MlsMessage::new(
3551 TEST_PROTOCOL_VERSION,
3552 MlsMessagePayload::KeyPackage(test_key_package),
3553 );
3554
3555 alice_group
3556 .commit_builder()
3557 .add_member(test_key_package.clone())
3558 .unwrap()
3559 .set_group_context_ext(Default::default())
3560 .unwrap()
3561 .build()
3562 .await
3563 .unwrap();
3564
3565 let CommitEffect::NewEpoch(new_epoch) =
3566 alice_group.process_pending_commit().await.unwrap().effect
3567 else {
3568 panic!("unexpected commit effect")
3569 };
3570
3571 assert_eq!(new_epoch.applied_proposals.len(), 2);
3572
3573 assert_matches!(
3574 new_epoch.applied_proposals[0],
3575 ProposalInfo { proposal: Proposal::Add(ref add), .. }
3576 if add.key_package == test_key_package.into_key_package().unwrap()
3577 );
3578
3579 assert_eq!(alice_group.roster().members_iter().count(), 2);
3580 }
3581
3582 #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
3583 async fn commit_leaf_wrong_source() {
3584 // RFC, 13.4.2. "The leaf_node_source field MUST be set to commit."
3585 let mut groups = test_n_member_group(TEST_PROTOCOL_VERSION, TEST_CIPHER_SUITE, 3).await;
3586
3587 groups[0].commit_modifiers.modify_leaf = |leaf, sk| {
3588 leaf.leaf_node_source = LeafNodeSource::Update;
3589 Some(sk.clone())
3590 };
3591
3592 let commit_output = groups[0].commit(vec![]).await.unwrap();
3593
3594 let res = groups[2]
3595 .process_message(commit_output.commit_message)
3596 .await;
3597
3598 assert_matches!(res, Err(MlsError::InvalidLeafNodeSource));
3599 }
3600
3601 #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
3602 async fn commit_leaf_same_hpke_key() {
3603 // RFC 13.4.2. "Verify that the encryption_key value in the LeafNode is different from the committer's current leaf node"
3604
3605 let mut groups = test_n_member_group(TEST_PROTOCOL_VERSION, TEST_CIPHER_SUITE, 3).await;
3606
3607 // Group 0 starts using fixed key
3608 groups[0].commit_modifiers.modify_leaf = |leaf, sk| {
3609 leaf.public_key = get_test_25519_key(1u8);
3610 Some(sk.clone())
3611 };
3612
3613 let commit_output = groups[0].commit(vec![]).await.unwrap();
3614 groups[0].process_pending_commit().await.unwrap();
3615 groups[2]
3616 .process_message(commit_output.commit_message)
3617 .await
3618 .unwrap();
3619
3620 // Group 0 tries to use the fixed key againd
3621 let commit_output = groups[0].commit(vec![]).await.unwrap();
3622
3623 let res = groups[2]
3624 .process_message(commit_output.commit_message)
3625 .await;
3626
3627 assert_matches!(res, Err(MlsError::SameHpkeKey(0)));
3628 }
3629
3630 #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
3631 async fn commit_leaf_duplicate_hpke_key() {
3632 // RFC 8.3 "Verify that the following fields are unique among the members of the group: `encryption_key`"
3633
3634 if TEST_CIPHER_SUITE != CipherSuite::CURVE25519_AES128
3635 && TEST_CIPHER_SUITE != CipherSuite::CURVE25519_CHACHA
3636 {
3637 return;
3638 }
3639
3640 let mut groups = test_n_member_group(TEST_PROTOCOL_VERSION, TEST_CIPHER_SUITE, 10).await;
3641
3642 // Group 1 uses the fixed key
3643 groups[1].commit_modifiers.modify_leaf = |leaf, sk| {
3644 leaf.public_key = get_test_25519_key(1u8);
3645 Some(sk.clone())
3646 };
3647
3648 let commit_output = groups.get_mut(1).unwrap().commit(vec![]).await.unwrap();
3649
3650 process_commit(&mut groups, commit_output.commit_message, 1).await;
3651
3652 // Group 0 tries to use the fixed key too
3653 groups[0].commit_modifiers.modify_leaf = |leaf, sk| {
3654 leaf.public_key = get_test_25519_key(1u8);
3655 Some(sk.clone())
3656 };
3657
3658 let commit_output = groups[0].commit(vec![]).await.unwrap();
3659
3660 let res = groups[7]
3661 .process_message(commit_output.commit_message)
3662 .await;
3663
3664 assert_matches!(res, Err(MlsError::DuplicateLeafData(_)));
3665 }
3666
3667 #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
3668 async fn commit_leaf_duplicate_signature_key() {
3669 // RFC 8.3 "Verify that the following fields are unique among the members of the group: `signature_key`"
3670
3671 if TEST_CIPHER_SUITE != CipherSuite::CURVE25519_AES128
3672 && TEST_CIPHER_SUITE != CipherSuite::CURVE25519_CHACHA
3673 {
3674 return;
3675 }
3676
3677 let mut groups = test_n_member_group(TEST_PROTOCOL_VERSION, TEST_CIPHER_SUITE, 10).await;
3678
3679 // Group 1 uses the fixed key
3680 groups[1].commit_modifiers.modify_leaf = |leaf, _| {
3681 let sk = hex!(
3682 "3468b4c890255c983e3d5cbf5cb64c1ef7f6433a518f2f3151d6672f839a06ebcad4fc381fe61822af45135c82921a348e6f46643d66ddefc70483565433714b"
3683 )
3684 .into();
3685
3686 leaf.signing_identity.signature_key =
3687 hex!("cad4fc381fe61822af45135c82921a348e6f46643d66ddefc70483565433714b").into();
3688
3689 Some(sk)
3690 };
3691
3692 let commit_output = groups.get_mut(1).unwrap().commit(vec![]).await.unwrap();
3693
3694 process_commit(&mut groups, commit_output.commit_message, 1).await;
3695
3696 // Group 0 tries to use the fixed key too
3697 groups[0].commit_modifiers.modify_leaf = |leaf, _| {
3698 let sk = hex!(
3699 "3468b4c890255c983e3d5cbf5cb64c1ef7f6433a518f2f3151d6672f839a06ebcad4fc381fe61822af45135c82921a348e6f46643d66ddefc70483565433714b"
3700 )
3701 .into();
3702
3703 leaf.signing_identity.signature_key =
3704 hex!("cad4fc381fe61822af45135c82921a348e6f46643d66ddefc70483565433714b").into();
3705
3706 Some(sk)
3707 };
3708
3709 let commit_output = groups[0].commit(vec![]).await.unwrap();
3710
3711 let res = groups[7]
3712 .process_message(commit_output.commit_message)
3713 .await;
3714
3715 assert_matches!(res, Err(MlsError::DuplicateLeafData(_)));
3716 }
3717
3718 #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
3719 async fn commit_leaf_incorrect_signature() {
3720 let mut groups = test_n_member_group(TEST_PROTOCOL_VERSION, TEST_CIPHER_SUITE, 3).await;
3721
3722 groups[0].commit_modifiers.modify_leaf = |leaf, _| {
3723 leaf.signature[0] ^= 1;
3724 None
3725 };
3726
3727 let commit_output = groups[0].commit(vec![]).await.unwrap();
3728
3729 let res = groups[2]
3730 .process_message(commit_output.commit_message)
3731 .await;
3732
3733 assert_matches!(res, Err(MlsError::InvalidSignature));
3734 }
3735
3736 #[cfg(not(target_arch = "wasm32"))]
3737 #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
3738 async fn commit_leaf_not_supporting_used_context_extension() {
3739 const EXT_TYPE: ExtensionType = ExtensionType::new(999);
3740
3741 // The new leaf of the committer doesn't support an extension set in group context
3742 let extension = Extension::new(EXT_TYPE, vec![]);
3743
3744 let mut groups =
3745 get_test_groups_with_features(3, vec![extension].into(), Default::default()).await;
3746
3747 groups[0].commit_modifiers.modify_leaf = |leaf, sk| {
3748 leaf.capabilities = get_test_capabilities();
3749 Some(sk.clone())
3750 };
3751
3752 let commit_output = groups[0].commit(vec![]).await.unwrap();
3753
3754 let res = groups[1]
3755 .process_incoming_message(commit_output.commit_message)
3756 .await;
3757
3758 assert_matches!(res, Err(MlsError::UnsupportedGroupExtension(EXT_TYPE)));
3759 }
3760
3761 #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
3762 async fn commit_leaf_not_supporting_required_extension() {
3763 // The new leaf of the committer doesn't support an extension required by group context
3764
3765 let extension = RequiredCapabilitiesExt {
3766 extensions: vec![999.into()],
3767 proposals: vec![],
3768 credentials: vec![],
3769 };
3770
3771 let extensions = vec![extension.into_extension().unwrap()];
3772 let mut groups =
3773 get_test_groups_with_features(3, extensions.into(), Default::default()).await;
3774
3775 groups[0].commit_modifiers.modify_leaf = |leaf, sk| {
3776 leaf.capabilities = Capabilities::default();
3777 Some(sk.clone())
3778 };
3779
3780 let commit_output = groups[0].commit(vec![]).await.unwrap();
3781
3782 let res = groups[2]
3783 .process_incoming_message(commit_output.commit_message)
3784 .await;
3785
3786 assert!(res.is_err());
3787 }
3788
3789 #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
3790 async fn commit_leaf_has_unsupported_credential() {
3791 // The new leaf of the committer has a credential unsupported by another leaf
3792 let mut groups =
3793 get_test_groups_with_features(3, Default::default(), Default::default()).await;
3794
3795 for group in groups.iter_mut() {
3796 group.config.0.identity_provider.allow_any_custom = true;
3797 }
3798
3799 groups[0].commit_modifiers.modify_leaf = |leaf, sk| {
3800 leaf.signing_identity.credential = Credential::Custom(CustomCredential::new(
3801 CredentialType::new(43),
3802 leaf.signing_identity
3803 .credential
3804 .as_basic()
3805 .unwrap()
3806 .identifier
3807 .to_vec(),
3808 ));
3809
3810 Some(sk.clone())
3811 };
3812
3813 let commit_output = groups[0].commit(vec![]).await.unwrap();
3814
3815 let res = groups[2]
3816 .process_incoming_message(commit_output.commit_message)
3817 .await;
3818
3819 assert_matches!(res, Err(MlsError::CredentialTypeOfNewLeafIsUnsupported));
3820 }
3821
3822 #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
3823 async fn commit_leaf_not_supporting_credential_used_in_another_leaf() {
3824 // The new leaf of the committer doesn't support another leaf's credential
3825
3826 let mut groups =
3827 get_test_groups_with_features(3, Default::default(), Default::default()).await;
3828
3829 groups[0].commit_modifiers.modify_leaf = |leaf, sk| {
3830 leaf.capabilities.credentials = vec![2.into()];
3831 Some(sk.clone())
3832 };
3833
3834 let commit_output = groups[0].commit(vec![]).await.unwrap();
3835
3836 let res = groups[2]
3837 .process_incoming_message(commit_output.commit_message)
3838 .await;
3839
3840 assert_matches!(res, Err(MlsError::InUseCredentialTypeUnsupportedByNewLeaf));
3841 }
3842
3843 #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
3844 async fn commit_leaf_not_supporting_required_credential() {
3845 // The new leaf of the committer doesn't support a credential required by group context
3846
3847 let extension = RequiredCapabilitiesExt {
3848 extensions: vec![],
3849 proposals: vec![],
3850 credentials: vec![1.into()],
3851 };
3852
3853 let extensions = vec![extension.into_extension().unwrap()];
3854 let mut groups =
3855 get_test_groups_with_features(3, extensions.into(), Default::default()).await;
3856
3857 groups[0].commit_modifiers.modify_leaf = |leaf, sk| {
3858 leaf.capabilities.credentials = vec![2.into()];
3859 Some(sk.clone())
3860 };
3861
3862 let commit_output = groups[0].commit(vec![]).await.unwrap();
3863
3864 let res = groups[2]
3865 .process_incoming_message(commit_output.commit_message)
3866 .await;
3867
3868 assert_matches!(res, Err(MlsError::RequiredCredentialNotFound(_)));
3869 }
3870
3871 #[cfg(feature = "by_ref_proposal")]
3872 #[cfg(not(target_arch = "wasm32"))]
3873 #[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)]
3874 async fn make_x509_external_senders_ext() -> ExternalSendersExt {
3875 let (_, ext_sender_pk) = test_cipher_suite_provider(TEST_CIPHER_SUITE)
3876 .signature_key_generate()
3877 .await
3878 .unwrap();
3879
3880 let ext_sender_id = SigningIdentity {
3881 signature_key: ext_sender_pk,
3882 credential: Credential::X509(CertificateChain::from(vec![random_bytes(32)])),
3883 };
3884
3885 ExternalSendersExt::new(vec![ext_sender_id])
3886 }
3887
3888 #[cfg(feature = "by_ref_proposal")]
3889 #[cfg(not(target_arch = "wasm32"))]
3890 #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
3891 async fn commit_leaf_not_supporting_external_sender_credential_leads_to_rejected_commit() {
3892 let ext_senders = make_x509_external_senders_ext()
3893 .await
3894 .into_extension()
3895 .unwrap();
3896
3897 let mut alice = ClientBuilder::new()
3898 .crypto_provider(TestCryptoProvider::new())
3899 .identity_provider(
3900 BasicWithCustomProvider::default().with_credential_type(CredentialType::X509),
3901 )
3902 .with_random_signing_identity("alice", TEST_CIPHER_SUITE)
3903 .await
3904 .build()
3905 .create_group(vec![ext_senders].into(), Default::default())
3906 .await
3907 .unwrap();
3908
3909 let bob = ClientBuilder::new()
3910 .crypto_provider(TestCryptoProvider::new())
3911 .identity_provider(
3912 BasicWithCustomProvider::default().with_credential_type(CredentialType::X509),
3913 )
3914 .with_random_signing_identity("bob", TEST_CIPHER_SUITE)
3915 .await
3916 .build();
3917
3918 let kp = bob
3919 .generate_key_package_message(Default::default(), Default::default())
3920 .await
3921 .unwrap();
3922
3923 let commit = alice
3924 .commit_builder()
3925 .add_member(kp)
3926 .unwrap()
3927 .build()
3928 .await
3929 .unwrap();
3930
3931 let (mut bob, _) = bob
3932 .join_group(None, &commit.welcome_messages[0])
3933 .await
3934 .unwrap();
3935
3936 alice.apply_pending_commit().await.unwrap();
3937
3938 // New leaf supports only basic credentials (used by the group) but not X509 used by external sender
3939 alice.commit_modifiers.modify_leaf = |leaf, sk| {
3940 leaf.capabilities.credentials = vec![CredentialType::BASIC];
3941 Some(sk.clone())
3942 };
3943
3944 let commit = alice.commit(vec![]).await.unwrap();
3945 let res = bob.process_incoming_message(commit.commit_message).await;
3946
3947 assert_matches!(
3948 res,
3949 Err(MlsError::RequiredCredentialNotFound(CredentialType::X509))
3950 );
3951 }
3952
3953 #[cfg(feature = "by_ref_proposal")]
3954 #[cfg(not(target_arch = "wasm32"))]
3955 #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
3956 async fn node_not_supporting_external_sender_credential_cannot_join_group() {
3957 let ext_senders = make_x509_external_senders_ext()
3958 .await
3959 .into_extension()
3960 .unwrap();
3961
3962 let mut alice = ClientBuilder::new()
3963 .crypto_provider(TestCryptoProvider::new())
3964 .identity_provider(
3965 BasicWithCustomProvider::default().with_credential_type(CredentialType::X509),
3966 )
3967 .with_random_signing_identity("alice", TEST_CIPHER_SUITE)
3968 .await
3969 .build()
3970 .create_group(core::iter::once(ext_senders).collect(), Default::default())
3971 .await
3972 .unwrap();
3973
3974 let (_, bob_key_pkg) =
3975 test_client_with_key_pkg(TEST_PROTOCOL_VERSION, TEST_CIPHER_SUITE, "bob").await;
3976
3977 let commit = alice
3978 .commit_builder()
3979 .add_member(bob_key_pkg)
3980 .unwrap()
3981 .build()
3982 .await;
3983
3984 assert_matches!(
3985 commit,
3986 Err(MlsError::RequiredCredentialNotFound(CredentialType::X509))
3987 );
3988 }
3989
3990 #[cfg(feature = "by_ref_proposal")]
3991 #[cfg(not(target_arch = "wasm32"))]
3992 #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
3993 async fn external_senders_extension_is_rejected_if_member_does_not_support_credential_type() {
3994 let mut alice = ClientBuilder::new()
3995 .crypto_provider(TestCryptoProvider::new())
3996 .identity_provider(
3997 BasicWithCustomProvider::default().with_credential_type(CredentialType::X509),
3998 )
3999 .with_random_signing_identity("alice", TEST_CIPHER_SUITE)
4000 .await
4001 .build()
4002 .create_group(Default::default(), Default::default())
4003 .await
4004 .unwrap();
4005
4006 let (_, bob_key_pkg) =
4007 test_client_with_key_pkg(TEST_PROTOCOL_VERSION, TEST_CIPHER_SUITE, "bob").await;
4008
4009 alice
4010 .commit_builder()
4011 .add_member(bob_key_pkg)
4012 .unwrap()
4013 .build()
4014 .await
4015 .unwrap();
4016
4017 alice.apply_pending_commit().await.unwrap();
4018 assert_eq!(alice.roster().members_iter().count(), 2);
4019
4020 let ext_senders = make_x509_external_senders_ext()
4021 .await
4022 .into_extension()
4023 .unwrap();
4024
4025 let res = alice
4026 .commit_builder()
4027 .set_group_context_ext(core::iter::once(ext_senders).collect())
4028 .unwrap()
4029 .build()
4030 .await;
4031
4032 assert_matches!(
4033 res,
4034 Err(MlsError::RequiredCredentialNotFound(CredentialType::X509))
4035 );
4036 }
4037
4038 /*
4039 * Edge case paths
4040 */
4041
4042 #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
4043 async fn committing_degenerate_path_succeeds() {
4044 let mut groups = test_n_member_group(TEST_PROTOCOL_VERSION, TEST_CIPHER_SUITE, 10).await;
4045
4046 groups[0].commit_modifiers.modify_tree = |tree: &mut TreeKemPublic| {
4047 tree.update_node(get_test_25519_key(1u8), 1).unwrap();
4048 tree.update_node(get_test_25519_key(1u8), 3).unwrap();
4049 };
4050
4051 groups[0].commit_modifiers.modify_leaf = |leaf, sk| {
4052 leaf.public_key = get_test_25519_key(1u8);
4053 Some(sk.clone())
4054 };
4055
4056 let commit_output = groups[0].commit(vec![]).await.unwrap();
4057
4058 let res = groups[7]
4059 .process_message(commit_output.commit_message)
4060 .await;
4061
4062 assert!(res.is_ok());
4063 }
4064
4065 #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
4066 async fn inserting_key_in_filtered_node_fails() {
4067 let mut groups = test_n_member_group(TEST_PROTOCOL_VERSION, TEST_CIPHER_SUITE, 10).await;
4068
4069 let commit_output = groups[0]
4070 .commit_builder()
4071 .remove_member(1)
4072 .unwrap()
4073 .build()
4074 .await
4075 .unwrap();
4076
4077 groups[0].process_pending_commit().await.unwrap();
4078
4079 for group in groups.iter_mut().skip(2) {
4080 group
4081 .process_message(commit_output.commit_message.clone())
4082 .await
4083 .unwrap();
4084 }
4085
4086 groups[0].commit_modifiers.modify_tree = |tree: &mut TreeKemPublic| {
4087 tree.update_node(get_test_25519_key(1u8), 1).unwrap();
4088 };
4089
4090 groups[0].commit_modifiers.modify_path = |path: Vec<UpdatePathNode>| {
4091 let mut path = path;
4092 let mut node = path[0].clone();
4093 node.public_key = get_test_25519_key(1u8);
4094 path.insert(0, node);
4095 path
4096 };
4097
4098 let commit_output = groups[0].commit(vec![]).await.unwrap();
4099
4100 let res = groups[7]
4101 .process_message(commit_output.commit_message)
4102 .await;
4103
4104 // We should get a path validation error, since the path is too long
4105 assert_matches!(res, Err(MlsError::WrongPathLen));
4106 }
4107
4108 #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
4109 async fn commit_with_too_short_path_fails() {
4110 let mut groups = test_n_member_group(TEST_PROTOCOL_VERSION, TEST_CIPHER_SUITE, 10).await;
4111
4112 let commit_output = groups[0]
4113 .commit_builder()
4114 .remove_member(1)
4115 .unwrap()
4116 .build()
4117 .await
4118 .unwrap();
4119
4120 groups[0].process_pending_commit().await.unwrap();
4121
4122 for group in groups.iter_mut().skip(2) {
4123 group
4124 .process_message(commit_output.commit_message.clone())
4125 .await
4126 .unwrap();
4127 }
4128
4129 groups[0].commit_modifiers.modify_path = |path: Vec<UpdatePathNode>| {
4130 let mut path = path;
4131 path.pop();
4132 path
4133 };
4134
4135 let commit_output = groups[0].commit(vec![]).await.unwrap();
4136
4137 let res = groups[7]
4138 .process_message(commit_output.commit_message)
4139 .await;
4140
4141 assert!(res.is_err());
4142 }
4143
4144 #[cfg(feature = "by_ref_proposal")]
4145 #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
4146 async fn update_proposal_can_change_credential() {
4147 let mut groups = test_n_member_group(TEST_PROTOCOL_VERSION, TEST_CIPHER_SUITE, 3).await;
4148 let (identity, secret_key) = get_test_signing_identity(TEST_CIPHER_SUITE, b"member").await;
4149
4150 let update = groups[0]
4151 .propose_update_with_identity(secret_key, identity.clone(), vec![])
4152 .await
4153 .unwrap();
4154
4155 groups[1].process_message(update).await.unwrap();
4156 let commit_output = groups[1].commit(vec![]).await.unwrap();
4157
4158 // Check that the credential was updated by in the committer's state.
4159 groups[1].process_pending_commit().await.unwrap();
4160 let new_member = groups[1].roster().member_with_index(0).unwrap();
4161
4162 assert_eq!(
4163 new_member.signing_identity.credential,
4164 get_test_basic_credential(b"member".to_vec())
4165 );
4166
4167 assert_eq!(
4168 new_member.signing_identity.signature_key,
4169 identity.signature_key
4170 );
4171
4172 // Check that the credential was updated in the updater's state.
4173 groups[0]
4174 .process_message(commit_output.commit_message)
4175 .await
4176 .unwrap();
4177 let new_member = groups[0].roster().member_with_index(0).unwrap();
4178
4179 assert_eq!(
4180 new_member.signing_identity.credential,
4181 get_test_basic_credential(b"member".to_vec())
4182 );
4183
4184 assert_eq!(
4185 new_member.signing_identity.signature_key,
4186 identity.signature_key
4187 );
4188 }
4189
4190 #[cfg(feature = "by_ref_proposal")]
4191 #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
4192 async fn receiving_commit_with_old_adds_fails() {
4193 let mut groups = test_n_member_group(TEST_PROTOCOL_VERSION, TEST_CIPHER_SUITE, 2).await;
4194
4195 let key_package =
4196 test_key_package_message(TEST_PROTOCOL_VERSION, TEST_CIPHER_SUITE, "foobar").await;
4197
4198 let proposal = groups[0].propose_add(key_package, vec![]).await.unwrap();
4199
4200 let commit = groups[0].commit(vec![]).await.unwrap().commit_message;
4201
4202 // 10 years from now
4203 let future_time = MlsTime::now().seconds_since_epoch() + 10 * 365 * 24 * 3600;
4204
4205 let future_time =
4206 MlsTime::from_duration_since_epoch(core::time::Duration::from_secs(future_time));
4207
4208 groups[1].process_incoming_message(proposal).await.unwrap();
4209 let res = groups[1]
4210 .process_incoming_message_with_time(commit, future_time)
4211 .await;
4212
4213 assert_matches!(res, Err(MlsError::InvalidLifetime));
4214 }
4215
4216 #[cfg(feature = "custom_proposal")]
4217 #[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)]
4218 async fn custom_proposal_setup() -> (TestGroup, TestGroup) {
4219 let mut alice = test_group_custom_config(TEST_PROTOCOL_VERSION, TEST_CIPHER_SUITE, |b| {
4220 b.custom_proposal_type(TEST_CUSTOM_PROPOSAL_TYPE)
4221 })
4222 .await;
4223
4224 let (bob, _) = alice
4225 .join_with_custom_config("bob", true, |c| {
4226 c.0.settings
4227 .custom_proposal_types
4228 .push(TEST_CUSTOM_PROPOSAL_TYPE)
4229 })
4230 .await
4231 .unwrap();
4232
4233 (alice, bob)
4234 }
4235
4236 #[cfg(feature = "custom_proposal")]
4237 #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
4238 async fn custom_proposal_by_value() {
4239 let (mut alice, mut bob) = custom_proposal_setup().await;
4240
4241 let custom_proposal = CustomProposal::new(TEST_CUSTOM_PROPOSAL_TYPE, vec![0, 1, 2]);
4242
4243 let commit = alice
4244 .commit_builder()
4245 .custom_proposal(custom_proposal.clone())
4246 .build()
4247 .await
4248 .unwrap()
4249 .commit_message;
4250
4251 let ReceivedMessage::Commit(CommitMessageDescription {
4252 effect: CommitEffect::NewEpoch(new_epoch),
4253 ..
4254 }) = bob.process_incoming_message(commit).await.unwrap()
4255 else {
4256 panic!("unexpected commit effect");
4257 };
4258
4259 assert_eq!(new_epoch.applied_proposals.len(), 1);
4260
4261 assert_eq!(
4262 new_epoch.applied_proposals[0].proposal,
4263 Proposal::Custom(custom_proposal)
4264 );
4265 }
4266
4267 #[cfg(feature = "custom_proposal")]
4268 #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
4269 async fn custom_proposal_by_reference() {
4270 let (mut alice, mut bob) = custom_proposal_setup().await;
4271
4272 let custom_proposal = CustomProposal::new(TEST_CUSTOM_PROPOSAL_TYPE, vec![0, 1, 2]);
4273
4274 let proposal = alice
4275 .propose_custom(custom_proposal.clone(), vec![])
4276 .await
4277 .unwrap();
4278
4279 let recv_prop = bob.process_incoming_message(proposal).await.unwrap();
4280
4281 assert_matches!(recv_prop, ReceivedMessage::Proposal(ProposalMessageDescription { proposal: Proposal::Custom(c), ..})
4282 if c == custom_proposal);
4283
4284 let commit = bob.commit(vec![]).await.unwrap().commit_message;
4285
4286 let ReceivedMessage::Commit(CommitMessageDescription {
4287 effect: CommitEffect::NewEpoch(new_epoch),
4288 ..
4289 }) = bob.process_incoming_message(commit).await.unwrap()
4290 else {
4291 panic!("unexpected commit effect");
4292 };
4293
4294 assert_eq!(new_epoch.applied_proposals.len(), 1);
4295
4296 assert_eq!(
4297 new_epoch.applied_proposals[0].proposal,
4298 Proposal::Custom(custom_proposal)
4299 );
4300 }
4301
4302 #[cfg(feature = "psk")]
4303 #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
4304 async fn can_join_with_psk() {
4305 let mut alice = test_group(TEST_PROTOCOL_VERSION, TEST_CIPHER_SUITE).await;
4306
4307 let (bob, key_pkg) =
4308 test_client_with_key_pkg(TEST_PROTOCOL_VERSION, TEST_CIPHER_SUITE, "bob").await;
4309
4310 let psk_id = ExternalPskId::new(vec![0]);
4311 let psk = PreSharedKey::from(vec![0]);
4312
4313 alice
4314 .config
4315 .secret_store()
4316 .insert(psk_id.clone(), psk.clone());
4317
4318 bob.config.secret_store().insert(psk_id.clone(), psk);
4319
4320 let commit = alice
4321 .commit_builder()
4322 .add_member(key_pkg)
4323 .unwrap()
4324 .add_external_psk(psk_id)
4325 .unwrap()
4326 .build()
4327 .await
4328 .unwrap();
4329
4330 bob.join_group(None, &commit.welcome_messages[0])
4331 .await
4332 .unwrap();
4333 }
4334
4335 #[cfg(feature = "by_ref_proposal")]
4336 #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
4337 async fn invalid_update_does_not_prevent_other_updates() {
4338 const EXTENSION_TYPE: ExtensionType = ExtensionType::new(33);
4339
4340 let group_extensions = ExtensionList::from(vec![RequiredCapabilitiesExt {
4341 extensions: vec![EXTENSION_TYPE],
4342 ..Default::default()
4343 }
4344 .into_extension()
4345 .unwrap()]);
4346
4347 // Alice creates a group requiring support for an extension
4348 let mut alice = TestClientBuilder::new_for_test()
4349 .with_random_signing_identity("alice", TEST_CIPHER_SUITE)
4350 .await
4351 .extension_type(EXTENSION_TYPE)
4352 .build()
4353 .create_group(group_extensions.clone(), Default::default())
4354 .await
4355 .unwrap();
4356
4357 let (bob_signing_identity, bob_secret_key) =
4358 get_test_signing_identity(TEST_CIPHER_SUITE, b"bob").await;
4359
4360 let bob_client = TestClientBuilder::new_for_test()
4361 .signing_identity(
4362 bob_signing_identity.clone(),
4363 bob_secret_key.clone(),
4364 TEST_CIPHER_SUITE,
4365 )
4366 .extension_type(EXTENSION_TYPE)
4367 .build();
4368
4369 let carol_client = TestClientBuilder::new_for_test()
4370 .with_random_signing_identity("carol", TEST_CIPHER_SUITE)
4371 .await
4372 .extension_type(EXTENSION_TYPE)
4373 .build();
4374
4375 let dave_client = TestClientBuilder::new_for_test()
4376 .with_random_signing_identity("dave", TEST_CIPHER_SUITE)
4377 .await
4378 .extension_type(EXTENSION_TYPE)
4379 .build();
4380
4381 // Alice adds Bob, Carol and Dave to the group. They all support the mandatory extension.
4382 let commit = alice
4383 .commit_builder()
4384 .add_member(
4385 bob_client
4386 .generate_key_package_message(Default::default(), Default::default())
4387 .await
4388 .unwrap(),
4389 )
4390 .unwrap()
4391 .add_member(
4392 carol_client
4393 .generate_key_package_message(Default::default(), Default::default())
4394 .await
4395 .unwrap(),
4396 )
4397 .unwrap()
4398 .add_member(
4399 dave_client
4400 .generate_key_package_message(Default::default(), Default::default())
4401 .await
4402 .unwrap(),
4403 )
4404 .unwrap()
4405 .build()
4406 .await
4407 .unwrap();
4408
4409 alice.apply_pending_commit().await.unwrap();
4410
4411 let mut bob = bob_client
4412 .join_group(None, &commit.welcome_messages[0])
4413 .await
4414 .unwrap()
4415 .0;
4416
4417 bob.write_to_storage().await.unwrap();
4418
4419 // Bob reloads his group data, but with parameters that will cause his generated leaves to
4420 // not support the mandatory extension.
4421 let mut bob = TestClientBuilder::new_for_test()
4422 .signing_identity(bob_signing_identity, bob_secret_key, TEST_CIPHER_SUITE)
4423 .key_package_repo(bob.config.key_package_repo())
4424 .group_state_storage(bob.config.group_state_storage())
4425 .build()
4426 .load_group(alice.group_id())
4427 .await
4428 .unwrap();
4429
4430 let mut carol = carol_client
4431 .join_group(None, &commit.welcome_messages[0])
4432 .await
4433 .unwrap()
4434 .0;
4435
4436 let mut dave = dave_client
4437 .join_group(None, &commit.welcome_messages[0])
4438 .await
4439 .unwrap()
4440 .0;
4441
4442 // Bob's updated leaf does not support the mandatory extension.
4443 let bob_update = bob.propose_update(Vec::new()).await.unwrap();
4444 let carol_update = carol.propose_update(Vec::new()).await.unwrap();
4445 let dave_update = dave.propose_update(Vec::new()).await.unwrap();
4446
4447 // Alice receives the update proposals to be committed.
4448 alice.process_incoming_message(bob_update).await.unwrap();
4449 alice.process_incoming_message(carol_update).await.unwrap();
4450 alice.process_incoming_message(dave_update).await.unwrap();
4451
4452 // Alice commits the update proposals.
4453 alice.commit(Vec::new()).await.unwrap();
4454
4455 let CommitEffect::NewEpoch(new_epoch) = alice.apply_pending_commit().await.unwrap().effect
4456 else {
4457 panic!("unexpected commit effect");
4458 };
4459
4460 let find_update_for = |id: &str| {
4461 new_epoch
4462 .applied_proposals
4463 .iter()
4464 .filter_map(|p| match p.proposal {
4465 Proposal::Update(ref u) => u.signing_identity().credential.as_basic(),
4466 _ => None,
4467 })
4468 .any(|c| c.identifier == id.as_bytes())
4469 };
4470
4471 // Carol's and Dave's updates should be part of the commit.
4472 assert!(find_update_for("carol"));
4473 assert!(find_update_for("dave"));
4474
4475 // Bob's update should be rejected.
4476 assert!(!find_update_for("bob"));
4477
4478 // Check that all members are still in the group.
4479 let all_members_are_in = alice
4480 .roster()
4481 .members_iter()
4482 .zip(["alice", "bob", "carol", "dave"])
4483 .all(|(member, id)| {
4484 member
4485 .signing_identity
4486 .credential
4487 .as_basic()
4488 .unwrap()
4489 .identifier
4490 == id.as_bytes()
4491 });
4492
4493 assert!(all_members_are_in);
4494 }
4495
4496 #[cfg(feature = "custom_proposal")]
4497 #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
4498 async fn custom_proposal_may_enforce_path() {
4499 test_custom_proposal_mls_rules(true).await;
4500 }
4501
4502 #[cfg(feature = "custom_proposal")]
4503 #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
4504 async fn custom_proposal_need_not_enforce_path() {
4505 test_custom_proposal_mls_rules(false).await;
4506 }
4507
4508 #[cfg(feature = "custom_proposal")]
4509 #[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)]
4510 async fn test_custom_proposal_mls_rules(path_required_for_custom: bool) {
4511 let mls_rules = CustomMlsRules {
4512 path_required_for_custom,
4513 external_joiner_can_send_custom: true,
4514 };
4515
4516 let mut alice = client_with_custom_rules(b"alice", mls_rules.clone())
4517 .await
4518 .create_group(Default::default(), Default::default())
4519 .await
4520 .unwrap();
4521
4522 let alice_pub_before = alice.current_user_leaf_node().unwrap().public_key.clone();
4523
4524 let kp = client_with_custom_rules(b"bob", mls_rules)
4525 .await
4526 .generate_key_package_message(Default::default(), Default::default())
4527 .await
4528 .unwrap();
4529
4530 alice
4531 .commit_builder()
4532 .custom_proposal(CustomProposal::new(TEST_CUSTOM_PROPOSAL_TYPE, vec![]))
4533 .add_member(kp)
4534 .unwrap()
4535 .build()
4536 .await
4537 .unwrap();
4538
4539 alice.apply_pending_commit().await.unwrap();
4540
4541 let alice_pub_after = &alice.current_user_leaf_node().unwrap().public_key;
4542
4543 if path_required_for_custom {
4544 assert_ne!(alice_pub_after, &alice_pub_before);
4545 } else {
4546 assert_eq!(alice_pub_after, &alice_pub_before);
4547 }
4548 }
4549
4550 #[cfg(feature = "custom_proposal")]
4551 #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
4552 async fn custom_proposal_by_value_in_external_join_may_be_allowed() {
4553 test_custom_proposal_by_value_in_external_join(true).await
4554 }
4555
4556 #[cfg(feature = "custom_proposal")]
4557 #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
4558 async fn custom_proposal_by_value_in_external_join_may_not_be_allowed() {
4559 test_custom_proposal_by_value_in_external_join(false).await
4560 }
4561
4562 #[cfg(feature = "custom_proposal")]
4563 #[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)]
4564 async fn test_custom_proposal_by_value_in_external_join(external_joiner_can_send_custom: bool) {
4565 let mls_rules = CustomMlsRules {
4566 path_required_for_custom: true,
4567 external_joiner_can_send_custom,
4568 };
4569
4570 let mut alice = client_with_custom_rules(b"alice", mls_rules.clone())
4571 .await
4572 .create_group(Default::default(), Default::default())
4573 .await
4574 .unwrap();
4575
4576 let group_info = alice
4577 .group_info_message_allowing_ext_commit(true)
4578 .await
4579 .unwrap();
4580
4581 let commit = client_with_custom_rules(b"bob", mls_rules)
4582 .await
4583 .external_commit_builder()
4584 .unwrap()
4585 .with_custom_proposal(CustomProposal::new(TEST_CUSTOM_PROPOSAL_TYPE, vec![]))
4586 .build(group_info)
4587 .await;
4588
4589 if external_joiner_can_send_custom {
4590 let commit = commit.unwrap().1;
4591 alice.process_incoming_message(commit).await.unwrap();
4592 } else {
4593 assert_matches!(commit.map(|_| ()), Err(MlsError::MlsRulesError(_)));
4594 }
4595 }
4596
4597 #[cfg(feature = "custom_proposal")]
4598 #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
4599 async fn custom_proposal_by_ref_in_external_join() {
4600 let mls_rules = CustomMlsRules {
4601 path_required_for_custom: true,
4602 external_joiner_can_send_custom: true,
4603 };
4604
4605 let mut alice = client_with_custom_rules(b"alice", mls_rules.clone())
4606 .await
4607 .create_group(Default::default(), Default::default())
4608 .await
4609 .unwrap();
4610
4611 let by_ref = CustomProposal::new(TEST_CUSTOM_PROPOSAL_TYPE, vec![]);
4612 let by_ref = alice.propose_custom(by_ref, vec![]).await.unwrap();
4613
4614 let group_info = alice
4615 .group_info_message_allowing_ext_commit(true)
4616 .await
4617 .unwrap();
4618
4619 let (_, commit) = client_with_custom_rules(b"bob", mls_rules)
4620 .await
4621 .external_commit_builder()
4622 .unwrap()
4623 .with_received_custom_proposal(by_ref)
4624 .build(group_info)
4625 .await
4626 .unwrap();
4627
4628 alice.process_incoming_message(commit).await.unwrap();
4629 }
4630
4631 #[cfg(feature = "custom_proposal")]
4632 #[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)]
4633 async fn client_with_custom_rules(
4634 name: &[u8],
4635 mls_rules: CustomMlsRules,
4636 ) -> Client<impl MlsConfig> {
4637 let (signing_identity, signer) = get_test_signing_identity(TEST_CIPHER_SUITE, name).await;
4638
4639 ClientBuilder::new()
4640 .crypto_provider(TestCryptoProvider::new())
4641 .identity_provider(BasicWithCustomProvider::new(BasicIdentityProvider::new()))
4642 .signing_identity(signing_identity, signer, TEST_CIPHER_SUITE)
4643 .custom_proposal_type(TEST_CUSTOM_PROPOSAL_TYPE)
4644 .mls_rules(mls_rules)
4645 .build()
4646 }
4647
4648 #[derive(Debug, Clone)]
4649 struct CustomMlsRules {
4650 path_required_for_custom: bool,
4651 external_joiner_can_send_custom: bool,
4652 }
4653
4654 #[cfg(feature = "custom_proposal")]
4655 impl ProposalBundle {
4656 fn has_test_custom_proposal(&self) -> bool {
4657 self.custom_proposal_types()
4658 .any(|t| t == TEST_CUSTOM_PROPOSAL_TYPE)
4659 }
4660 }
4661
4662 #[cfg(feature = "custom_proposal")]
4663 #[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)]
4664 #[cfg_attr(mls_build_async, maybe_async::must_be_async)]
4665 impl crate::MlsRules for CustomMlsRules {
4666 type Error = MlsError;
4667
4668 fn commit_options(
4669 &self,
4670 _: &Roster,
4671 _: &GroupContext,
4672 proposals: &ProposalBundle,
4673 ) -> Result<CommitOptions, MlsError> {
4674 Ok(CommitOptions::default().with_path_required(
4675 !proposals.has_test_custom_proposal() || self.path_required_for_custom,
4676 ))
4677 }
4678
4679 fn encryption_options(
4680 &self,
4681 _: &Roster,
4682 _: &GroupContext,
4683 ) -> Result<crate::mls_rules::EncryptionOptions, MlsError> {
4684 Ok(Default::default())
4685 }
4686
4687 async fn filter_proposals(
4688 &self,
4689 _: CommitDirection,
4690 sender: CommitSource,
4691 _: &Roster,
4692 _: &GroupContext,
4693 proposals: ProposalBundle,
4694 ) -> Result<ProposalBundle, MlsError> {
4695 let is_external = matches!(sender, CommitSource::NewMember(_));
4696 let has_custom = proposals.has_test_custom_proposal();
4697 let allowed = !has_custom || !is_external || self.external_joiner_can_send_custom;
4698
4699 allowed.then_some(proposals).ok_or(MlsError::InvalidSender)
4700 }
4701 }
4702
4703 #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
4704 async fn group_can_receive_commit_from_self() {
4705 let mut group = test_group(TEST_PROTOCOL_VERSION, TEST_CIPHER_SUITE).await;
4706
4707 let commit = group.commit(vec![]).await.unwrap();
4708
4709 let update = group
4710 .process_incoming_message(commit.commit_message)
4711 .await
4712 .unwrap();
4713
4714 let ReceivedMessage::Commit(update) = update else {
4715 panic!("expected commit message")
4716 };
4717
4718 assert_eq!(update.committer, *group.private_tree.self_index);
4719 }
4720
4721 #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
4722 async fn can_process_commit_when_pending_commit() {
4723 let mut groups = test_n_member_group(TEST_PROTOCOL_VERSION, TEST_CIPHER_SUITE, 2).await;
4724
4725 let commit = groups[0].commit(vec![]).await.unwrap().commit_message;
4726 groups[1].commit(vec![]).await.unwrap();
4727
4728 groups[1].process_incoming_message(commit).await.unwrap();
4729
4730 let res = groups[1].apply_pending_commit().await;
4731 assert_matches!(res, Err(MlsError::PendingCommitNotFound));
4732 }
4733
4734 #[cfg(feature = "by_ref_proposal")]
4735 #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
4736 async fn can_process_own_plaintext_proposal() {
4737 can_process_own_proposal(false).await;
4738 }
4739
4740 #[cfg(feature = "by_ref_proposal")]
4741 #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
4742 async fn can_process_own_ciphertext_proposal() {
4743 can_process_own_proposal(true).await;
4744 }
4745
4746 #[cfg(feature = "by_ref_proposal")]
4747 #[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)]
4748 async fn can_process_own_proposal(encrypt_proposal: bool) {
4749 let (alice, _) = test_client_with_key_pkg_custom(
4750 TEST_PROTOCOL_VERSION,
4751 TEST_CIPHER_SUITE,
4752 "alice",
4753 Default::default(),
4754 Default::default(),
4755 |c| c.0.mls_rules.encryption_options.encrypt_control_messages = encrypt_proposal,
4756 )
4757 .await;
4758
4759 let mut alice = TestGroup {
4760 group: alice
4761 .create_group(Default::default(), Default::default())
4762 .await
4763 .unwrap(),
4764 };
4765
4766 let mut bob = alice.join("bob").await.0;
4767 let mut alice = alice;
4768
4769 let upd = alice.propose_update(vec![]).await.unwrap();
4770 alice.process_incoming_message(upd.clone()).await.unwrap();
4771
4772 bob.process_incoming_message(upd).await.unwrap();
4773 let commit = bob.commit(vec![]).await.unwrap().commit_message;
4774 let update = alice.process_incoming_message(commit).await.unwrap();
4775
4776 let ReceivedMessage::Commit(CommitMessageDescription {
4777 effect: CommitEffect::NewEpoch(new_epoch),
4778 ..
4779 }) = update
4780 else {
4781 panic!("unexpected commit effect")
4782 };
4783
4784 assert_eq!(new_epoch.applied_proposals.len(), 1);
4785 assert_eq!(new_epoch.applied_proposals[0].sender, Sender::Member(0));
4786 }
4787
4788 #[cfg(feature = "by_ref_proposal")]
4789 #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
4790 async fn commit_clears_proposals() {
4791 let mut groups = test_n_member_group(TEST_PROTOCOL_VERSION, TEST_CIPHER_SUITE, 2).await;
4792
4793 groups[0].propose_update(vec![]).await.unwrap();
4794
4795 assert_eq!(groups[0].state.proposals.proposals.len(), 1);
4796 assert_eq!(groups[0].state.proposals.own_proposals.len(), 1);
4797
4798 let commit = groups[1].commit(vec![]).await.unwrap().commit_message;
4799 groups[0].process_message(commit).await.unwrap();
4800
4801 assert!(groups[0].state.proposals.proposals.is_empty());
4802 assert!(groups[0].state.proposals.own_proposals.is_empty());
4803 }
4804
4805 #[cfg(feature = "by_ref_proposal")]
4806 #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
4807 async fn commit_required_is_true_when_proposals_pending() {
4808 let mut group = test_group(TEST_PROTOCOL_VERSION, TEST_CIPHER_SUITE).await;
4809
4810 assert!(!group.commit_required());
4811
4812 group
4813 .propose_group_context_extensions(ExtensionList::new(), vec![])
4814 .await
4815 .unwrap();
4816
4817 assert!(group.commit_required());
4818
4819 let res = group.encrypt_application_message(&[0u8; 32], vec![]).await;
4820
4821 assert_matches!(res, Err(MlsError::CommitRequired));
4822
4823 group.commit(vec![]).await.unwrap();
4824 group.apply_pending_commit().await.unwrap();
4825
4826 assert!(!group.commit_required());
4827 }
4828
4829 // Testing with std is sufficient. Non-std creates incompatible storage and a lot of special cases.
4830 #[cfg(feature = "std")]
4831 #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
4832 async fn can_be_stored_without_tree() {
4833 let mut group = test_group(TEST_PROTOCOL_VERSION, TEST_CIPHER_SUITE).await;
4834 let storage = group.config.group_state_storage().inner;
4835
4836 group.write_to_storage().await.unwrap();
4837 let snapshot_with_tree = storage.lock().unwrap().drain().next().unwrap().1;
4838
4839 group.write_to_storage_without_ratchet_tree().await.unwrap();
4840 let snapshot_without_tree = storage.lock().unwrap().iter().next().unwrap().1.clone();
4841
4842 let tree = group.state.public_tree.nodes.mls_encode_to_vec().unwrap();
4843 let empty_tree = Vec::<u8>::new().mls_encode_to_vec().unwrap();
4844
4845 assert_eq!(
4846 snapshot_with_tree.state_data.len() - snapshot_without_tree.state_data.len(),
4847 tree.len() - empty_tree.len()
4848 );
4849
4850 let exported_tree = group.export_tree();
4851
4852 let restored = Client::new(group.config.clone(), None, None, TEST_PROTOCOL_VERSION)
4853 .load_group_with_ratchet_tree(group.group_id(), exported_tree)
4854 .await
4855 .unwrap();
4856
4857 assert_eq!(restored.group_state(), group.group_state());
4858 }
4859
4860 #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
4861 async fn delete_exporter() {
4862 let mut group = test_group(TEST_PROTOCOL_VERSION, TEST_CIPHER_SUITE).await;
4863
4864 group.export_secret(b"123", b"", 15).await.unwrap();
4865
4866 group.delete_exporter();
4867 let res = group.export_secret(b"123", b"", 15).await;
4868 assert_matches!(res, Err(MlsError::ExporterDeleted));
4869
4870 group.commit(vec![]).await.unwrap();
4871 group.apply_pending_commit().await.unwrap();
4872 group.export_secret(b"123", b"", 15).await.unwrap();
4873 }
4874 }