| 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 crate::cipher_suite::CipherSuite; |
| 6 |
use crate::client_builder::{recreate_config, BaseConfig, ClientBuilder, MakeConfig}; |
| 7 |
use crate::client_config::ClientConfig; |
| 8 |
use crate::group::framing::MlsMessage; |
| 9 |
|
| 10 |
use crate::group::{cipher_suite_provider, validate_group_info_joiner, GroupInfo}; |
| 11 |
use crate::group::{ |
| 12 |
framing::MlsMessagePayload, snapshot::Snapshot, ExportedTree, Group, NewMemberInfo, |
| 13 |
}; |
| 14 |
#[cfg(feature = "by_ref_proposal")] |
| 15 |
use crate::group::{ |
| 16 |
framing::{Content, PublicMessage, Sender, WireFormat}, |
| 17 |
message_signature::AuthenticatedContent, |
| 18 |
proposal::{AddProposal, Proposal}, |
| 19 |
}; |
| 20 |
use crate::identity::SigningIdentity; |
| 21 |
use crate::key_package::{KeyPackageGeneration, KeyPackageGenerator}; |
| 22 |
use crate::protocol_version::ProtocolVersion; |
| 23 |
use crate::tree_kem::node::NodeIndex; |
| 24 |
use alloc::vec::Vec; |
| 25 |
use mls_rs_codec::MlsDecode; |
| 26 |
use mls_rs_core::crypto::{CryptoProvider, SignatureSecretKey}; |
| 27 |
use mls_rs_core::error::{AnyError, IntoAnyError}; |
| 28 |
use mls_rs_core::extension::{ExtensionError, ExtensionList, ExtensionType}; |
| 29 |
use mls_rs_core::group::{GroupStateStorage, ProposalType}; |
| 30 |
use mls_rs_core::identity::{CredentialType, IdentityProvider, MemberValidationContext}; |
| 31 |
use mls_rs_core::key_package::KeyPackageStorage; |
| 32 |
|
| 33 |
use crate::group::external_commit::ExternalCommitBuilder; |
| 34 |
|
| 35 |
#[cfg(feature = "by_ref_proposal")] |
| 36 |
use alloc::boxed::Box; |
| 37 |
|
| 38 |
#[derive(Debug)] |
| 39 |
#[cfg_attr(feature = "std", derive(thiserror::Error))] |
| 40 |
#[cfg_attr(all(feature = "ffi", not(test)), safer_ffi_gen::enum_to_error_code)] |
| 41 |
#[non_exhaustive] |
| 42 |
pub enum MlsError { |
| 43 |
#[cfg_attr(feature = "std", error(transparent))] |
| 44 |
IdentityProviderError(AnyError), |
| 45 |
#[cfg_attr(feature = "std", error(transparent))] |
| 46 |
CryptoProviderError(AnyError), |
| 47 |
#[cfg_attr(feature = "std", error(transparent))] |
| 48 |
KeyPackageRepoError(AnyError), |
| 49 |
#[cfg_attr(feature = "std", error(transparent))] |
| 50 |
GroupStorageError(AnyError), |
| 51 |
#[cfg_attr(feature = "std", error(transparent))] |
| 52 |
PskStoreError(AnyError), |
| 53 |
#[cfg_attr(feature = "std", error(transparent))] |
| 54 |
MlsRulesError(AnyError), |
| 55 |
#[cfg_attr(feature = "std", error(transparent))] |
| 56 |
SerializationError(AnyError), |
| 57 |
#[cfg_attr(feature = "std", error(transparent))] |
| 58 |
ExtensionError(AnyError), |
| 59 |
#[cfg_attr(feature = "std", error("Cipher suite does not match"))] |
| 60 |
CipherSuiteMismatch, |
| 61 |
#[cfg_attr(feature = "std", error("Invalid commit, missing required path"))] |
| 62 |
CommitMissingPath, |
| 63 |
#[cfg_attr(feature = "std", error("plaintext message for incorrect epoch"))] |
| 64 |
InvalidEpoch, |
| 65 |
#[cfg_attr(feature = "std", error("invalid signature found"))] |
| 66 |
InvalidSignature, |
| 67 |
#[cfg_attr(feature = "std", error("invalid confirmation tag"))] |
| 68 |
InvalidConfirmationTag, |
| 69 |
#[cfg_attr(feature = "std", error("invalid membership tag"))] |
| 70 |
InvalidMembershipTag, |
| 71 |
#[cfg_attr(feature = "std", error("corrupt private key, missing required values"))] |
| 72 |
InvalidTreeKemPrivateKey, |
| 73 |
#[cfg_attr(feature = "std", error("key package not found, unable to process"))] |
| 74 |
WelcomeKeyPackageNotFound, |
| 75 |
#[cfg_attr(feature = "std", error("leaf not found in tree for index {0}"))] |
| 76 |
LeafNotFound(u32), |
| 77 |
#[cfg_attr(feature = "std", error("message from self can't be processed"))] |
| 78 |
CantProcessMessageFromSelf, |
| 79 |
#[cfg_attr( |
| 80 |
feature = "std", |
| 81 |
error("pending proposals found, commit required before application messages can be sent") |
| 82 |
)] |
| 83 |
CommitRequired, |
| 84 |
#[cfg_attr( |
| 85 |
feature = "std", |
| 86 |
error("ratchet tree not provided or discovered in GroupInfo") |
| 87 |
)] |
| 88 |
RatchetTreeNotFound, |
| 89 |
#[cfg_attr(feature = "std", error("External sender cannot commit"))] |
| 90 |
ExternalSenderCannotCommit, |
| 91 |
#[cfg_attr(feature = "std", error("Unsupported protocol version {0:?}"))] |
| 92 |
UnsupportedProtocolVersion(ProtocolVersion), |
| 93 |
#[cfg_attr(feature = "std", error("Protocol version mismatch"))] |
| 94 |
ProtocolVersionMismatch, |
| 95 |
#[cfg_attr(feature = "std", error("Unsupported cipher suite {0:?}"))] |
| 96 |
UnsupportedCipherSuite(CipherSuite), |
| 97 |
#[cfg_attr(feature = "std", error("Signing key of external sender is unknown"))] |
| 98 |
UnknownSigningIdentityForExternalSender, |
| 99 |
#[cfg_attr( |
| 100 |
feature = "std", |
| 101 |
error("External proposals are disabled for this group") |
| 102 |
)] |
| 103 |
ExternalProposalsDisabled, |
| 104 |
#[cfg_attr( |
| 105 |
feature = "std", |
| 106 |
error("Signing identity is not allowed to externally propose") |
| 107 |
)] |
| 108 |
InvalidExternalSigningIdentity, |
| 109 |
#[cfg_attr(feature = "std", error("Missing ExternalPub extension"))] |
| 110 |
MissingExternalPubExtension, |
| 111 |
#[cfg_attr(feature = "std", error("Epoch not found"))] |
| 112 |
EpochNotFound, |
| 113 |
#[cfg_attr(feature = "std", error("Unencrypted application message"))] |
| 114 |
UnencryptedApplicationMessage, |
| 115 |
#[cfg_attr( |
| 116 |
feature = "std", |
| 117 |
error("NewMemberCommit sender type can only be used to send Commit content") |
| 118 |
)] |
| 119 |
ExpectedCommitForNewMemberCommit, |
| 120 |
#[cfg_attr( |
| 121 |
feature = "std", |
| 122 |
error("NewMemberProposal sender type can only be used to send add proposals") |
| 123 |
)] |
| 124 |
ExpectedAddProposalForNewMemberProposal, |
| 125 |
#[cfg_attr( |
| 126 |
feature = "std", |
| 127 |
error("External commit missing ExternalInit proposal") |
| 128 |
)] |
| 129 |
ExternalCommitMissingExternalInit, |
| 130 |
#[cfg_attr( |
| 131 |
feature = "std", |
| 132 |
error( |
| 133 |
"A ReIinit has been applied. The next action must be creating or receiving a welcome." |
| 134 |
) |
| 135 |
)] |
| 136 |
GroupUsedAfterReInit, |
| 137 |
#[cfg_attr(feature = "std", error("Pending ReIinit not found."))] |
| 138 |
PendingReInitNotFound, |
| 139 |
#[cfg_attr( |
| 140 |
feature = "std", |
| 141 |
error("The extensions in the welcome message and in the reinit do not match.") |
| 142 |
)] |
| 143 |
ReInitExtensionsMismatch, |
| 144 |
#[cfg_attr(feature = "std", error("signer not found for given identity"))] |
| 145 |
SignerNotFound, |
| 146 |
#[cfg_attr(feature = "std", error("commit already pending"))] |
| 147 |
ExistingPendingCommit, |
| 148 |
#[cfg_attr(feature = "std", error("pending commit not found"))] |
| 149 |
PendingCommitNotFound, |
| 150 |
#[cfg_attr(feature = "std", error("unexpected message type for action"))] |
| 151 |
UnexpectedMessageType, |
| 152 |
#[cfg_attr( |
| 153 |
feature = "std", |
| 154 |
error("membership tag on MlsPlaintext for non-member sender") |
| 155 |
)] |
| 156 |
MembershipTagForNonMember, |
| 157 |
#[cfg_attr(feature = "std", error("No member found for given identity id."))] |
| 158 |
MemberNotFound, |
| 159 |
#[cfg_attr(feature = "std", error("group not found"))] |
| 160 |
GroupNotFound, |
| 161 |
#[cfg_attr(feature = "std", error("unexpected PSK ID"))] |
| 162 |
UnexpectedPskId, |
| 163 |
#[cfg_attr(feature = "std", error("invalid sender for content type"))] |
| 164 |
InvalidSender, |
| 165 |
#[cfg_attr(feature = "std", error("GroupID mismatch"))] |
| 166 |
GroupIdMismatch, |
| 167 |
#[cfg_attr(feature = "std", error("storage retention can not be zero"))] |
| 168 |
NonZeroRetentionRequired, |
| 169 |
#[cfg_attr(feature = "std", error("Too many PSK IDs to compute PSK secret"))] |
| 170 |
TooManyPskIds, |
| 171 |
#[cfg_attr(feature = "std", error("Missing required Psk"))] |
| 172 |
MissingRequiredPsk, |
| 173 |
#[cfg_attr(feature = "std", error("Old group state not found"))] |
| 174 |
OldGroupStateNotFound, |
| 175 |
#[cfg_attr(feature = "std", error("leaf secret already consumed"))] |
| 176 |
InvalidLeafConsumption, |
| 177 |
#[cfg_attr(feature = "std", error("key not available, invalid generation {0}"))] |
| 178 |
KeyMissing(u32), |
| 179 |
#[cfg_attr( |
| 180 |
feature = "std", |
| 181 |
error("requested generation {0} is too far ahead of current generation") |
| 182 |
)] |
| 183 |
InvalidFutureGeneration(u32), |
| 184 |
#[cfg_attr(feature = "std", error("leaf node has no children"))] |
| 185 |
LeafNodeNoChildren, |
| 186 |
#[cfg_attr(feature = "std", error("root node has no parent"))] |
| 187 |
LeafNodeNoParent, |
| 188 |
#[cfg_attr(feature = "std", error("index out of range"))] |
| 189 |
InvalidTreeIndex, |
| 190 |
#[cfg_attr(feature = "std", error("time overflow"))] |
| 191 |
TimeOverflow, |
| 192 |
#[cfg_attr(feature = "std", error("invalid leaf_node_source"))] |
| 193 |
InvalidLeafNodeSource, |
| 194 |
#[cfg_attr(feature = "std", error("key package has expired or is not valid yet"))] |
| 195 |
InvalidLifetime, |
| 196 |
#[cfg_attr(feature = "std", error("required extension not found"))] |
| 197 |
RequiredExtensionNotFound(ExtensionType), |
| 198 |
#[cfg_attr(feature = "std", error("required proposal not found"))] |
| 199 |
RequiredProposalNotFound(ProposalType), |
| 200 |
#[cfg_attr(feature = "std", error("required credential not found"))] |
| 201 |
RequiredCredentialNotFound(CredentialType), |
| 202 |
#[cfg_attr(feature = "std", error("capabilities must describe extensions used"))] |
| 203 |
ExtensionNotInCapabilities(ExtensionType), |
| 204 |
#[cfg_attr(feature = "std", error("expected non-blank node"))] |
| 205 |
ExpectedNode, |
| 206 |
#[cfg_attr(feature = "std", error("node index is out of bounds {0}"))] |
| 207 |
InvalidNodeIndex(NodeIndex), |
| 208 |
#[cfg_attr(feature = "std", error("unexpected empty node found"))] |
| 209 |
UnexpectedEmptyNode, |
| 210 |
#[cfg_attr( |
| 211 |
feature = "std", |
| 212 |
error("duplicate signature key, hpke key or identity found at index {0}") |
| 213 |
)] |
| 214 |
DuplicateLeafData(u32), |
| 215 |
#[cfg_attr( |
| 216 |
feature = "std", |
| 217 |
error("In-use credential type not supported by new leaf at index") |
| 218 |
)] |
| 219 |
InUseCredentialTypeUnsupportedByNewLeaf, |
| 220 |
#[cfg_attr( |
| 221 |
feature = "std", |
| 222 |
error("Not all members support the credential type used by new leaf") |
| 223 |
)] |
| 224 |
CredentialTypeOfNewLeafIsUnsupported, |
| 225 |
#[cfg_attr( |
| 226 |
feature = "std", |
| 227 |
error("the length of the update path is different than the length of the direct path") |
| 228 |
)] |
| 229 |
WrongPathLen, |
| 230 |
#[cfg_attr( |
| 231 |
feature = "std", |
| 232 |
error("same HPKE leaf key before and after applying the update path for leaf {0}") |
| 233 |
)] |
| 234 |
SameHpkeKey(u32), |
| 235 |
#[cfg_attr(feature = "std", error("init key is not valid for cipher suite"))] |
| 236 |
InvalidInitKey, |
| 237 |
#[cfg_attr( |
| 238 |
feature = "std", |
| 239 |
error("init key can not be equal to leaf node public key") |
| 240 |
)] |
| 241 |
InitLeafKeyEquality, |
| 242 |
#[cfg_attr(feature = "std", error("different identity in update for leaf {0}"))] |
| 243 |
DifferentIdentityInUpdate(u32), |
| 244 |
#[cfg_attr(feature = "std", error("update path pub key mismatch"))] |
| 245 |
PubKeyMismatch, |
| 246 |
#[cfg_attr(feature = "std", error("tree hash mismatch"))] |
| 247 |
TreeHashMismatch, |
| 248 |
#[cfg_attr(feature = "std", error("bad update: no suitable secret key"))] |
| 249 |
UpdateErrorNoSecretKey, |
| 250 |
#[cfg_attr(feature = "std", error("invalid lca, not found on direct path"))] |
| 251 |
LcaNotFoundInDirectPath, |
| 252 |
#[cfg_attr(feature = "std", error("update path parent hash mismatch"))] |
| 253 |
ParentHashMismatch, |
| 254 |
#[cfg_attr(feature = "std", error("unexpected pattern of unmerged leaves"))] |
| 255 |
UnmergedLeavesMismatch, |
| 256 |
#[cfg_attr(feature = "std", error("empty tree"))] |
| 257 |
UnexpectedEmptyTree, |
| 258 |
#[cfg_attr(feature = "std", error("trailing blanks"))] |
| 259 |
UnexpectedTrailingBlanks, |
| 260 |
// Proposal Rules errors |
| 261 |
#[cfg_attr( |
| 262 |
feature = "std", |
| 263 |
error("Commiter must not include any update proposals generated by the commiter") |
| 264 |
)] |
| 265 |
InvalidCommitSelfUpdate, |
| 266 |
#[cfg_attr(feature = "std", error("A PreSharedKey proposal must have a PSK of type External or type Resumption and usage Application"))] |
| 267 |
InvalidTypeOrUsageInPreSharedKeyProposal, |
| 268 |
#[cfg_attr(feature = "std", error("psk nonce length does not match cipher suite"))] |
| 269 |
InvalidPskNonceLength, |
| 270 |
#[cfg_attr( |
| 271 |
feature = "std", |
| 272 |
error("ReInit proposal protocol version is less than the version of the original group") |
| 273 |
)] |
| 274 |
InvalidProtocolVersionInReInit, |
| 275 |
#[cfg_attr(feature = "std", error("More than one proposal applying to leaf: {0}"))] |
| 276 |
MoreThanOneProposalForLeaf(u32), |
| 277 |
#[cfg_attr( |
| 278 |
feature = "std", |
| 279 |
error("More than one GroupContextExtensions proposal") |
| 280 |
)] |
| 281 |
MoreThanOneGroupContextExtensionsProposal, |
| 282 |
#[cfg_attr(feature = "std", error("Invalid proposal type for sender"))] |
| 283 |
InvalidProposalTypeForSender, |
| 284 |
#[cfg_attr( |
| 285 |
feature = "std", |
| 286 |
error("External commit must have exactly one ExternalInit proposal") |
| 287 |
)] |
| 288 |
ExternalCommitMustHaveExactlyOneExternalInit, |
| 289 |
#[cfg_attr(feature = "std", error("External commit must have a new leaf"))] |
| 290 |
ExternalCommitMustHaveNewLeaf, |
| 291 |
#[cfg_attr( |
| 292 |
feature = "std", |
| 293 |
error("External commit contains removal of other identity") |
| 294 |
)] |
| 295 |
ExternalCommitRemovesOtherIdentity, |
| 296 |
#[cfg_attr( |
| 297 |
feature = "std", |
| 298 |
error("External commit contains more than one Remove proposal") |
| 299 |
)] |
| 300 |
ExternalCommitWithMoreThanOneRemove, |
| 301 |
#[cfg_attr(feature = "std", error("Duplicate PSK IDs"))] |
| 302 |
DuplicatePskIds, |
| 303 |
#[cfg_attr( |
| 304 |
feature = "std", |
| 305 |
error("Invalid proposal type {0:?} in external commit") |
| 306 |
)] |
| 307 |
InvalidProposalTypeInExternalCommit(ProposalType), |
| 308 |
#[cfg_attr(feature = "std", error("Committer can not remove themselves"))] |
| 309 |
CommitterSelfRemoval, |
| 310 |
#[cfg_attr( |
| 311 |
feature = "std", |
| 312 |
error("Only members can commit proposals by reference") |
| 313 |
)] |
| 314 |
OnlyMembersCanCommitProposalsByRef, |
| 315 |
#[cfg_attr(feature = "std", error("Other proposal with ReInit"))] |
| 316 |
OtherProposalWithReInit, |
| 317 |
#[cfg_attr(feature = "std", error("Unsupported group extension {0:?}"))] |
| 318 |
UnsupportedGroupExtension(ExtensionType), |
| 319 |
#[cfg_attr(feature = "std", error("Unsupported custom proposal type {0:?}"))] |
| 320 |
UnsupportedCustomProposal(ProposalType), |
| 321 |
#[cfg_attr(feature = "std", error("by-ref proposal not found"))] |
| 322 |
ProposalNotFound, |
| 323 |
#[cfg_attr( |
| 324 |
feature = "std", |
| 325 |
error("Removing non-existing member (or removing a member twice)") |
| 326 |
)] |
| 327 |
RemovingNonExistingMember, |
| 328 |
#[cfg_attr(feature = "std", error("Updated identity not a valid successor"))] |
| 329 |
InvalidSuccessor, |
| 330 |
#[cfg_attr( |
| 331 |
feature = "std", |
| 332 |
error("Updating non-existing member (or updating a member twice)") |
| 333 |
)] |
| 334 |
UpdatingNonExistingMember, |
| 335 |
#[cfg_attr(feature = "std", error("Failed generating next path secret"))] |
| 336 |
FailedGeneratingPathSecret, |
| 337 |
#[cfg_attr(feature = "std", error("Invalid group info"))] |
| 338 |
InvalidGroupInfo, |
| 339 |
#[cfg_attr(feature = "std", error("Invalid welcome message"))] |
| 340 |
InvalidWelcomeMessage, |
| 341 |
#[cfg_attr(feature = "std", error("Exporter deleted"))] |
| 342 |
ExporterDeleted, |
| 343 |
} |
| 344 |
|
| 345 |
impl IntoAnyError for MlsError { |
| 346 |
#[cfg(feature = "std")] |
| 347 |
fn into_dyn_error(self) -> Result<Box<dyn std::error::Error + Send + Sync>, Self> { |
| 348 |
Ok(self.into()) |
| 349 |
} |
| 350 |
} |
| 351 |
|
| 352 |
impl From<mls_rs_codec::Error> for MlsError { |
| 353 |
#[inline] |
| 354 |
fn from(e: mls_rs_codec::Error) -> Self { |
| 355 |
MlsError::SerializationError(e.into_any_error()) |
| 356 |
} |
| 357 |
} |
| 358 |
|
| 359 |
impl From<ExtensionError> for MlsError { |
| 360 |
#[inline] |
| 361 |
fn from(e: ExtensionError) -> Self { |
| 362 |
MlsError::ExtensionError(e.into_any_error()) |
| 363 |
} |
| 364 |
} |
| 365 |
|
| 366 |
/// MLS client used to create key packages and manage groups. |
| 367 |
/// |
| 368 |
/// [`Client::builder`] can be used to instantiate it. |
| 369 |
/// |
| 370 |
/// Clients are able to support multiple protocol versions, ciphersuites |
| 371 |
/// and underlying identities used to join groups and generate key packages. |
| 372 |
/// Applications may decide to create one or many clients depending on their |
| 373 |
/// specific needs. |
| 374 |
#[cfg_attr(all(feature = "ffi", not(test)), safer_ffi_gen::ffi_type(opaque))] |
| 375 |
#[derive(Clone, Debug)] |
| 376 |
pub struct Client<C> { |
| 377 |
pub(crate) config: C, |
| 378 |
pub(crate) signing_identity: Option<(SigningIdentity, CipherSuite)>, |
| 379 |
pub(crate) signer: Option<SignatureSecretKey>, |
| 380 |
pub(crate) version: ProtocolVersion, |
| 381 |
} |
| 382 |
|
| 383 |
impl Client<()> { |
| 384 |
/// Returns a [`ClientBuilder`] |
| 385 |
/// used to configure client preferences and providers. |
| 386 |
pub fn builder() -> ClientBuilder<BaseConfig> { |
| 387 |
ClientBuilder::new() |
| 388 |
} |
| 389 |
} |
| 390 |
|
| 391 |
#[cfg_attr(all(feature = "ffi", not(test)), safer_ffi_gen::safer_ffi_gen)] |
| 392 |
impl<C> Client<C> |
| 393 |
where |
| 394 |
C: ClientConfig + Clone, |
| 395 |
{ |
| 396 |
pub(crate) fn new( |
| 397 |
config: C, |
| 398 |
signer: Option<SignatureSecretKey>, |
| 399 |
signing_identity: Option<(SigningIdentity, CipherSuite)>, |
| 400 |
version: ProtocolVersion, |
| 401 |
) -> Self { |
| 402 |
Client { |
| 403 |
config, |
| 404 |
signer, |
| 405 |
signing_identity, |
| 406 |
version, |
| 407 |
} |
| 408 |
} |
| 409 |
|
| 410 |
#[cfg_attr(all(feature = "ffi", not(test)), safer_ffi_gen::safer_ffi_gen_ignore)] |
| 411 |
pub fn to_builder(&self) -> ClientBuilder<MakeConfig<C>> { |
| 412 |
ClientBuilder::from_config(recreate_config( |
| 413 |
self.config.clone(), |
| 414 |
self.signer.clone(), |
| 415 |
self.signing_identity.clone(), |
| 416 |
self.version, |
| 417 |
)) |
| 418 |
} |
| 419 |
|
| 420 |
/// Creates a new key package message that can be used to to add this |
| 421 |
/// client to a [Group](crate::group::Group). Each call to this function |
| 422 |
/// will produce a unique value that is signed by `signing_identity`. |
| 423 |
/// |
| 424 |
/// The secret keys for the resulting key package message will be stored in |
| 425 |
/// the [KeyPackageStorage](crate::KeyPackageStorage) |
| 426 |
/// that was used to configure the client and will |
| 427 |
/// automatically be erased when this key package is used to |
| 428 |
/// [join a group](Client::join_group). |
| 429 |
/// |
| 430 |
/// # Warning |
| 431 |
/// |
| 432 |
/// A key package message may only be used once. |
| 433 |
#[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)] |
| 434 |
pub async fn generate_key_package_message( |
| 435 |
&self, |
| 436 |
key_package_extensions: ExtensionList, |
| 437 |
leaf_node_extensions: ExtensionList, |
| 438 |
) -> Result<MlsMessage, MlsError> { |
| 439 |
Ok(self |
| 440 |
.generate_key_package(key_package_extensions, leaf_node_extensions) |
| 441 |
.await? |
| 442 |
.key_package_message()) |
| 443 |
} |
| 444 |
|
| 445 |
#[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)] |
| 446 |
async fn generate_key_package( |
| 447 |
&self, |
| 448 |
key_package_extensions: ExtensionList, |
| 449 |
leaf_node_extensions: ExtensionList, |
| 450 |
) -> Result<KeyPackageGeneration, MlsError> { |
| 451 |
let (signing_identity, cipher_suite) = self.signing_identity()?; |
| 452 |
|
| 453 |
let cipher_suite_provider = self |
| 454 |
.config |
| 455 |
.crypto_provider() |
| 456 |
.cipher_suite_provider(cipher_suite) |
| 457 |
.ok_or(MlsError::UnsupportedCipherSuite(cipher_suite))?; |
| 458 |
|
| 459 |
let key_package_generator = KeyPackageGenerator { |
| 460 |
protocol_version: self.version, |
| 461 |
cipher_suite_provider: &cipher_suite_provider, |
| 462 |
signing_key: self.signer()?, |
| 463 |
signing_identity, |
| 464 |
}; |
| 465 |
|
| 466 |
let key_pkg_gen = key_package_generator |
| 467 |
.generate( |
| 468 |
self.config.lifetime(), |
| 469 |
self.config.capabilities(), |
| 470 |
key_package_extensions, |
| 471 |
leaf_node_extensions, |
| 472 |
) |
| 473 |
.await?; |
| 474 |
|
| 475 |
let (id, key_package_data) = key_pkg_gen.to_storage()?; |
| 476 |
|
| 477 |
self.config |
| 478 |
.key_package_repo() |
| 479 |
.insert(id, key_package_data) |
| 480 |
.await |
| 481 |
.map_err(|e| MlsError::KeyPackageRepoError(e.into_any_error()))?; |
| 482 |
|
| 483 |
Ok(key_pkg_gen) |
| 484 |
} |
| 485 |
|
| 486 |
/// Create a group with a specific group_id. |
| 487 |
/// |
| 488 |
/// This function behaves the same way as |
| 489 |
/// [create_group](Client::create_group) except that it |
| 490 |
/// specifies a specific unique group identifier to be used. |
| 491 |
/// |
| 492 |
/// # Warning |
| 493 |
/// |
| 494 |
/// It is recommended to use [create_group](Client::create_group) |
| 495 |
/// instead of this function because it guarantees that group_id values |
| 496 |
/// are globally unique. |
| 497 |
#[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)] |
| 498 |
pub async fn create_group_with_id( |
| 499 |
&self, |
| 500 |
group_id: Vec<u8>, |
| 501 |
group_context_extensions: ExtensionList, |
| 502 |
leaf_node_extensions: ExtensionList, |
| 503 |
) -> Result<Group<C>, MlsError> { |
| 504 |
let (signing_identity, cipher_suite) = self.signing_identity()?; |
| 505 |
|
| 506 |
Group::new( |
| 507 |
self.config.clone(), |
| 508 |
Some(group_id), |
| 509 |
cipher_suite, |
| 510 |
self.version, |
| 511 |
signing_identity.clone(), |
| 512 |
group_context_extensions, |
| 513 |
leaf_node_extensions, |
| 514 |
self.signer()?.clone(), |
| 515 |
) |
| 516 |
.await |
| 517 |
} |
| 518 |
|
| 519 |
/// Create a MLS group. |
| 520 |
/// |
| 521 |
/// The `cipher_suite` provided must be supported by the |
| 522 |
/// [CipherSuiteProvider](crate::CipherSuiteProvider) |
| 523 |
/// that was used to build the client. |
| 524 |
#[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)] |
| 525 |
pub async fn create_group( |
| 526 |
&self, |
| 527 |
group_context_extensions: ExtensionList, |
| 528 |
leaf_node_extensions: ExtensionList, |
| 529 |
) -> Result<Group<C>, MlsError> { |
| 530 |
let (signing_identity, cipher_suite) = self.signing_identity()?; |
| 531 |
|
| 532 |
Group::new( |
| 533 |
self.config.clone(), |
| 534 |
None, |
| 535 |
cipher_suite, |
| 536 |
self.version, |
| 537 |
signing_identity.clone(), |
| 538 |
group_context_extensions, |
| 539 |
leaf_node_extensions, |
| 540 |
self.signer()?.clone(), |
| 541 |
) |
| 542 |
.await |
| 543 |
} |
| 544 |
|
| 545 |
/// Join a MLS group via a welcome message created by a |
| 546 |
/// [Commit](crate::group::CommitOutput). |
| 547 |
/// |
| 548 |
/// `tree_data` is required to be provided out of band if the client that |
| 549 |
/// created `welcome_message` did not use the `ratchet_tree_extension` |
| 550 |
/// according to [`MlsRules::commit_options`](`crate::MlsRules::commit_options`). |
| 551 |
/// at the time the welcome message was created. `tree_data` can |
| 552 |
/// be exported from a group using the |
| 553 |
/// [export tree function](crate::group::Group::export_tree). |
| 554 |
#[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)] |
| 555 |
pub async fn join_group( |
| 556 |
&self, |
| 557 |
tree_data: Option<ExportedTree<'_>>, |
| 558 |
welcome_message: &MlsMessage, |
| 559 |
) -> Result<(Group<C>, NewMemberInfo), MlsError> { |
| 560 |
Group::join( |
| 561 |
welcome_message, |
| 562 |
tree_data, |
| 563 |
self.config.clone(), |
| 564 |
self.signer()?.clone(), |
| 565 |
) |
| 566 |
.await |
| 567 |
} |
| 568 |
|
| 569 |
/// Decrypt GroupInfo encrypted in the Welcome message without actually joining |
| 570 |
/// the group. The ratchet tree is not needed. |
| 571 |
#[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)] |
| 572 |
pub async fn examine_welcome_message( |
| 573 |
&self, |
| 574 |
welcome_message: &MlsMessage, |
| 575 |
) -> Result<GroupInfo, MlsError> { |
| 576 |
Group::decrypt_group_info(welcome_message, &self.config).await |
| 577 |
} |
| 578 |
|
| 579 |
/// Validate GroupInfo message. This does NOT validate the ratchet tree in case |
| 580 |
/// it is provided in the extension. It validates the signature, identity of the |
| 581 |
/// signer, identities of external senders and cipher suite. |
| 582 |
#[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)] |
| 583 |
pub async fn validate_group_info( |
| 584 |
&self, |
| 585 |
group_info_message: &MlsMessage, |
| 586 |
signer: &SigningIdentity, |
| 587 |
) -> Result<(), MlsError> { |
| 588 |
let MlsMessagePayload::GroupInfo(group_info) = &group_info_message.payload else { |
| 589 |
return Err(MlsError::UnexpectedMessageType); |
| 590 |
}; |
| 591 |
|
| 592 |
let cs = cipher_suite_provider( |
| 593 |
self.config.crypto_provider(), |
| 594 |
group_info.group_context.cipher_suite, |
| 595 |
)?; |
| 596 |
|
| 597 |
let id = self.config.identity_provider(); |
| 598 |
|
| 599 |
validate_group_info_joiner(group_info_message.version, group_info, signer, &id, &cs) |
| 600 |
.await?; |
| 601 |
|
| 602 |
let context = MemberValidationContext::ForNewGroup { |
| 603 |
current_context: &group_info.group_context, |
| 604 |
}; |
| 605 |
|
| 606 |
id.validate_member(signer, None, context) |
| 607 |
.await |
| 608 |
.map_err(|e| MlsError::IdentityProviderError(e.into_any_error()))?; |
| 609 |
|
| 610 |
Ok(()) |
| 611 |
} |
| 612 |
|
| 613 |
/// 0-RTT add to an existing [group](crate::group::Group) |
| 614 |
/// |
| 615 |
/// External commits allow for immediate entry into a |
| 616 |
/// [group](crate::group::Group), even if all of the group members |
| 617 |
/// are currently offline and unable to process messages. Sending an |
| 618 |
/// external commit is only allowed for groups that have provided |
| 619 |
/// a public `group_info_message` containing an |
| 620 |
/// [ExternalPubExt](crate::extension::ExternalPubExt), which can be |
| 621 |
/// generated by an existing group member using the |
| 622 |
/// [group_info_message](crate::group::Group::group_info_message) |
| 623 |
/// function. |
| 624 |
/// |
| 625 |
/// `tree_data` may be provided following the same rules as [Client::join_group] |
| 626 |
/// |
| 627 |
/// If PSKs are provided in `external_psks`, the |
| 628 |
/// [PreSharedKeyStorage](crate::PreSharedKeyStorage) |
| 629 |
/// used to configure the client will be searched to resolve their values. |
| 630 |
/// |
| 631 |
/// `to_remove` may be used to remove an existing member provided that the |
| 632 |
/// identity of the existing group member at that [index](crate::group::Member::index) |
| 633 |
/// is a [valid successor](crate::IdentityProvider::valid_successor) |
| 634 |
/// of `signing_identity` as defined by the |
| 635 |
/// [IdentityProvider](crate::IdentityProvider) that this client |
| 636 |
/// was configured with. |
| 637 |
/// |
| 638 |
/// # Warning |
| 639 |
/// |
| 640 |
/// Only one external commit can be performed against a given group info. |
| 641 |
/// There may also be security trade-offs to this approach. |
| 642 |
/// |
| 643 |
// TODO: Add a comment about forward secrecy and a pointer to the future |
| 644 |
// book chapter on this topic |
| 645 |
#[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)] |
| 646 |
pub async fn commit_external( |
| 647 |
&self, |
| 648 |
group_info_msg: MlsMessage, |
| 649 |
) -> Result<(Group<C>, MlsMessage), MlsError> { |
| 650 |
ExternalCommitBuilder::new( |
| 651 |
self.signer()?.clone(), |
| 652 |
self.signing_identity()?.0.clone(), |
| 653 |
self.config.clone(), |
| 654 |
) |
| 655 |
.build(group_info_msg) |
| 656 |
.await |
| 657 |
} |
| 658 |
|
| 659 |
pub fn external_commit_builder(&self) -> Result<ExternalCommitBuilder<C>, MlsError> { |
| 660 |
Ok(ExternalCommitBuilder::new( |
| 661 |
self.signer()?.clone(), |
| 662 |
self.signing_identity()?.0.clone(), |
| 663 |
self.config.clone(), |
| 664 |
)) |
| 665 |
} |
| 666 |
|
| 667 |
/// Load an existing group state into this client using the |
| 668 |
/// [GroupStateStorage](crate::GroupStateStorage) that |
| 669 |
/// this client was configured to use. |
| 670 |
#[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)] |
| 671 |
#[inline(never)] |
| 672 |
pub async fn load_group(&self, group_id: &[u8]) -> Result<Group<C>, MlsError> { |
| 673 |
let snapshot = self |
| 674 |
.config |
| 675 |
.group_state_storage() |
| 676 |
.state(group_id) |
| 677 |
.await |
| 678 |
.map_err(|e| MlsError::GroupStorageError(e.into_any_error()))? |
| 679 |
.ok_or(MlsError::GroupNotFound)?; |
| 680 |
|
| 681 |
let snapshot = Snapshot::mls_decode(&mut &*snapshot)?; |
| 682 |
|
| 683 |
Group::from_snapshot(self.config.clone(), snapshot).await |
| 684 |
} |
| 685 |
|
| 686 |
/// Load an existing group state into this client using the |
| 687 |
/// [GroupStateStorage](crate::GroupStateStorage) that |
| 688 |
/// this client was configured to use. The tree is taken from |
| 689 |
/// `tree_data` instead of the stored state. |
| 690 |
#[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)] |
| 691 |
#[inline(never)] |
| 692 |
pub async fn load_group_with_ratchet_tree( |
| 693 |
&self, |
| 694 |
group_id: &[u8], |
| 695 |
tree_data: ExportedTree<'_>, |
| 696 |
) -> Result<Group<C>, MlsError> { |
| 697 |
let snapshot = self |
| 698 |
.config |
| 699 |
.group_state_storage() |
| 700 |
.state(group_id) |
| 701 |
.await |
| 702 |
.map_err(|e| MlsError::GroupStorageError(e.into_any_error()))? |
| 703 |
.ok_or(MlsError::GroupNotFound)?; |
| 704 |
|
| 705 |
let mut snapshot = Snapshot::mls_decode(&mut &*snapshot)?; |
| 706 |
snapshot.state.public_tree.nodes = tree_data.0.into_owned(); |
| 707 |
|
| 708 |
Group::from_snapshot(self.config.clone(), snapshot).await |
| 709 |
} |
| 710 |
|
| 711 |
/// Request to join an existing [group](crate::group::Group). |
| 712 |
/// |
| 713 |
/// An existing group member will need to perform a |
| 714 |
/// [commit](crate::Group::commit) to complete the add and the resulting |
| 715 |
/// welcome message can be used by [join_group](Client::join_group). |
| 716 |
#[cfg(feature = "by_ref_proposal")] |
| 717 |
#[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)] |
| 718 |
pub async fn external_add_proposal( |
| 719 |
&self, |
| 720 |
group_info: &MlsMessage, |
| 721 |
tree_data: Option<crate::group::ExportedTree<'_>>, |
| 722 |
authenticated_data: Vec<u8>, |
| 723 |
key_package_extensions: ExtensionList, |
| 724 |
leaf_node_extensions: ExtensionList, |
| 725 |
) -> Result<MlsMessage, MlsError> { |
| 726 |
let protocol_version = group_info.version; |
| 727 |
|
| 728 |
if !self.config.version_supported(protocol_version) && protocol_version == self.version { |
| 729 |
return Err(MlsError::UnsupportedProtocolVersion(protocol_version)); |
| 730 |
} |
| 731 |
|
| 732 |
let group_info = group_info |
| 733 |
.as_group_info() |
| 734 |
.ok_or(MlsError::UnexpectedMessageType)?; |
| 735 |
|
| 736 |
let cipher_suite = group_info.group_context.cipher_suite; |
| 737 |
|
| 738 |
let cipher_suite_provider = self |
| 739 |
.config |
| 740 |
.crypto_provider() |
| 741 |
.cipher_suite_provider(cipher_suite) |
| 742 |
.ok_or(MlsError::UnsupportedCipherSuite(cipher_suite))?; |
| 743 |
|
| 744 |
crate::group::validate_tree_and_info_joiner( |
| 745 |
protocol_version, |
| 746 |
group_info, |
| 747 |
tree_data, |
| 748 |
&self.config.identity_provider(), |
| 749 |
&cipher_suite_provider, |
| 750 |
) |
| 751 |
.await?; |
| 752 |
|
| 753 |
let key_package = self |
| 754 |
.generate_key_package(key_package_extensions, leaf_node_extensions) |
| 755 |
.await? |
| 756 |
.key_package; |
| 757 |
|
| 758 |
(key_package.cipher_suite == cipher_suite) |
| 759 |
.then_some(()) |
| 760 |
.ok_or(MlsError::UnsupportedCipherSuite(cipher_suite))?; |
| 761 |
|
| 762 |
let message = AuthenticatedContent::new_signed( |
| 763 |
&cipher_suite_provider, |
| 764 |
&group_info.group_context, |
| 765 |
Sender::NewMemberProposal, |
| 766 |
Content::Proposal(Box::new(Proposal::Add(Box::new(AddProposal { |
| 767 |
key_package, |
| 768 |
})))), |
| 769 |
self.signer()?, |
| 770 |
WireFormat::PublicMessage, |
| 771 |
authenticated_data, |
| 772 |
) |
| 773 |
.await?; |
| 774 |
|
| 775 |
let plaintext = PublicMessage { |
| 776 |
content: message.content, |
| 777 |
auth: message.auth, |
| 778 |
membership_tag: None, |
| 779 |
}; |
| 780 |
|
| 781 |
Ok(MlsMessage { |
| 782 |
version: protocol_version, |
| 783 |
payload: MlsMessagePayload::Plain(plaintext), |
| 784 |
}) |
| 785 |
} |
| 786 |
|
| 787 |
fn signer(&self) -> Result<&SignatureSecretKey, MlsError> { |
| 788 |
self.signer.as_ref().ok_or(MlsError::SignerNotFound) |
| 789 |
} |
| 790 |
|
| 791 |
#[cfg_attr(all(feature = "ffi", not(test)), safer_ffi_gen::safer_ffi_gen_ignore)] |
| 792 |
pub fn signing_identity(&self) -> Result<(&SigningIdentity, CipherSuite), MlsError> { |
| 793 |
self.signing_identity |
| 794 |
.as_ref() |
| 795 |
.map(|(id, cs)| (id, *cs)) |
| 796 |
.ok_or(MlsError::SignerNotFound) |
| 797 |
} |
| 798 |
|
| 799 |
/// The [KeyPackageStorage] that this client was configured to use. |
| 800 |
#[cfg_attr(all(feature = "ffi", not(test)), safer_ffi_gen::safer_ffi_gen_ignore)] |
| 801 |
pub fn key_package_store(&self) -> <C as ClientConfig>::KeyPackageRepository { |
| 802 |
self.config.key_package_repo() |
| 803 |
} |
| 804 |
|
| 805 |
/// The [PreSharedKeyStorage](crate::PreSharedKeyStorage) that |
| 806 |
/// this client was configured to use. |
| 807 |
#[cfg_attr(all(feature = "ffi", not(test)), safer_ffi_gen::safer_ffi_gen_ignore)] |
| 808 |
pub fn secret_store(&self) -> <C as ClientConfig>::PskStore { |
| 809 |
self.config.secret_store() |
| 810 |
} |
| 811 |
|
| 812 |
/// The [GroupStateStorage] that this client was configured to use. |
| 813 |
#[cfg_attr(all(feature = "ffi", not(test)), safer_ffi_gen::safer_ffi_gen_ignore)] |
| 814 |
pub fn group_state_storage(&self) -> <C as ClientConfig>::GroupStateStorage { |
| 815 |
self.config.group_state_storage() |
| 816 |
} |
| 817 |
|
| 818 |
/// The [IdentityProvider](crate::IdentityProvider) that this client was configured to use. |
| 819 |
#[cfg_attr(all(feature = "ffi", not(test)), safer_ffi_gen::safer_ffi_gen_ignore)] |
| 820 |
pub fn identity_provider(&self) -> <C as ClientConfig>::IdentityProvider { |
| 821 |
self.config.identity_provider() |
| 822 |
} |
| 823 |
} |
| 824 |
|
| 825 |
#[cfg(test)] |
| 826 |
pub(crate) mod test_utils { |
| 827 |
use super::*; |
| 828 |
use crate::identity::test_utils::get_test_signing_identity; |
| 829 |
|
| 830 |
pub use crate::client_builder::test_utils::{TestClientBuilder, TestClientConfig}; |
| 831 |
|
| 832 |
pub const TEST_PROTOCOL_VERSION: ProtocolVersion = ProtocolVersion::MLS_10; |
| 833 |
pub const TEST_CIPHER_SUITE: CipherSuite = CipherSuite::P256_AES128; |
| 834 |
pub const TEST_CUSTOM_PROPOSAL_TYPE: ProposalType = ProposalType::new(65001); |
| 835 |
|
| 836 |
#[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)] |
| 837 |
pub async fn test_client_with_key_pkg( |
| 838 |
protocol_version: ProtocolVersion, |
| 839 |
cipher_suite: CipherSuite, |
| 840 |
identity: &str, |
| 841 |
) -> (Client<TestClientConfig>, MlsMessage) { |
| 842 |
test_client_with_key_pkg_custom( |
| 843 |
protocol_version, |
| 844 |
cipher_suite, |
| 845 |
identity, |
| 846 |
Default::default(), |
| 847 |
Default::default(), |
| 848 |
|_| {}, |
| 849 |
) |
| 850 |
.await |
| 851 |
} |
| 852 |
|
| 853 |
#[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)] |
| 854 |
pub async fn test_client_with_key_pkg_custom<F>( |
| 855 |
protocol_version: ProtocolVersion, |
| 856 |
cipher_suite: CipherSuite, |
| 857 |
identity: &str, |
| 858 |
key_package_extensions: ExtensionList, |
| 859 |
leaf_node_extensions: ExtensionList, |
| 860 |
mut config: F, |
| 861 |
) -> (Client<TestClientConfig>, MlsMessage) |
| 862 |
where |
| 863 |
F: FnMut(&mut TestClientConfig), |
| 864 |
{ |
| 865 |
let (identity, secret_key) = |
| 866 |
get_test_signing_identity(cipher_suite, identity.as_bytes()).await; |
| 867 |
|
| 868 |
let mut client = TestClientBuilder::new_for_test() |
| 869 |
.used_protocol_version(protocol_version) |
| 870 |
.signing_identity(identity.clone(), secret_key, cipher_suite) |
| 871 |
.build(); |
| 872 |
|
| 873 |
config(&mut client.config); |
| 874 |
|
| 875 |
let key_package = client |
| 876 |
.generate_key_package_message(key_package_extensions, leaf_node_extensions) |
| 877 |
.await |
| 878 |
.unwrap(); |
| 879 |
|
| 880 |
(client, key_package) |
| 881 |
} |
| 882 |
} |
| 883 |
|
| 884 |
#[cfg(test)] |
| 885 |
mod tests { |
| 886 |
use super::test_utils::*; |
| 887 |
|
| 888 |
use super::*; |
| 889 |
use crate::{ |
| 890 |
crypto::test_utils::TestCryptoProvider, |
| 891 |
identity::test_utils::{get_test_basic_credential, get_test_signing_identity}, |
| 892 |
tree_kem::leaf_node::LeafNodeSource, |
| 893 |
}; |
| 894 |
use assert_matches::assert_matches; |
| 895 |
|
| 896 |
#[cfg(feature = "by_ref_proposal")] |
| 897 |
use crate::group::message_processor::ProposalMessageDescription; |
| 898 |
#[cfg(feature = "by_ref_proposal")] |
| 899 |
use crate::group::proposal::Proposal; |
| 900 |
use crate::group::test_utils::test_group; |
| 901 |
#[cfg(feature = "psk")] |
| 902 |
use crate::group::test_utils::test_group_custom_config; |
| 903 |
#[cfg(feature = "by_ref_proposal")] |
| 904 |
use crate::group::ReceivedMessage; |
| 905 |
#[cfg(feature = "psk")] |
| 906 |
use crate::psk::{ExternalPskId, PreSharedKey}; |
| 907 |
use alloc::vec; |
| 908 |
|
| 909 |
#[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))] |
| 910 |
async fn test_keygen() { |
| 911 |
// This is meant to test the inputs to the internal key package generator |
| 912 |
// See KeyPackageGenerator tests for key generation specific tests |
| 913 |
for (protocol_version, cipher_suite) in ProtocolVersion::all().flat_map(|p| { |
| 914 |
TestCryptoProvider::all_supported_cipher_suites() |
| 915 |
.into_iter() |
| 916 |
.map(move |cs| (p, cs)) |
| 917 |
}) { |
| 918 |
let (identity, secret_key) = get_test_signing_identity(cipher_suite, b"foo").await; |
| 919 |
|
| 920 |
let client = TestClientBuilder::new_for_test() |
| 921 |
.signing_identity(identity.clone(), secret_key, cipher_suite) |
| 922 |
.build(); |
| 923 |
|
| 924 |
// TODO: Tests around extensions |
| 925 |
let key_package = client |
| 926 |
.generate_key_package_message(Default::default(), Default::default()) |
| 927 |
.await |
| 928 |
.unwrap(); |
| 929 |
|
| 930 |
assert_eq!(key_package.version, protocol_version); |
| 931 |
|
| 932 |
let key_package = key_package.into_key_package().unwrap(); |
| 933 |
|
| 934 |
assert_eq!(key_package.cipher_suite, cipher_suite); |
| 935 |
|
| 936 |
assert_eq!( |
| 937 |
&key_package.leaf_node.signing_identity.credential, |
| 938 |
&get_test_basic_credential(b"foo".to_vec()) |
| 939 |
); |
| 940 |
|
| 941 |
assert_eq!(key_package.leaf_node.signing_identity, identity); |
| 942 |
|
| 943 |
let capabilities = key_package.leaf_node.ungreased_capabilities(); |
| 944 |
assert_eq!(capabilities, client.config.capabilities()); |
| 945 |
|
| 946 |
let client_lifetime = client.config.lifetime(); |
| 947 |
assert_matches!(key_package.leaf_node.leaf_node_source, LeafNodeSource::KeyPackage(lifetime) if (lifetime.not_after - lifetime.not_before) == (client_lifetime.not_after - client_lifetime.not_before)); |
| 948 |
} |
| 949 |
} |
| 950 |
|
| 951 |
#[cfg(feature = "by_ref_proposal")] |
| 952 |
#[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))] |
| 953 |
async fn new_member_add_proposal_adds_to_group() { |
| 954 |
let mut alice_group = test_group(TEST_PROTOCOL_VERSION, TEST_CIPHER_SUITE).await; |
| 955 |
|
| 956 |
let (bob_identity, secret_key) = get_test_signing_identity(TEST_CIPHER_SUITE, b"bob").await; |
| 957 |
|
| 958 |
let bob = TestClientBuilder::new_for_test() |
| 959 |
.signing_identity(bob_identity.clone(), secret_key, TEST_CIPHER_SUITE) |
| 960 |
.build(); |
| 961 |
|
| 962 |
let proposal = bob |
| 963 |
.external_add_proposal( |
| 964 |
&alice_group.group_info_message(true).await.unwrap(), |
| 965 |
None, |
| 966 |
vec![], |
| 967 |
Default::default(), |
| 968 |
Default::default(), |
| 969 |
) |
| 970 |
.await |
| 971 |
.unwrap(); |
| 972 |
|
| 973 |
let message = alice_group |
| 974 |
.process_incoming_message(proposal) |
| 975 |
.await |
| 976 |
.unwrap(); |
| 977 |
|
| 978 |
assert_matches!( |
| 979 |
message, |
| 980 |
ReceivedMessage::Proposal(ProposalMessageDescription { |
| 981 |
proposal: Proposal::Add(p), ..} |
| 982 |
) if p.key_package.leaf_node.signing_identity == bob_identity |
| 983 |
); |
| 984 |
|
| 985 |
alice_group.commit(vec![]).await.unwrap(); |
| 986 |
alice_group.apply_pending_commit().await.unwrap(); |
| 987 |
|
| 988 |
// Check that the new member is in the group |
| 989 |
assert!(alice_group |
| 990 |
.roster() |
| 991 |
.members_iter() |
| 992 |
.any(|member| member.signing_identity == bob_identity)) |
| 993 |
} |
| 994 |
|
| 995 |
#[cfg(feature = "psk")] |
| 996 |
#[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)] |
| 997 |
async fn join_via_external_commit(do_remove: bool, with_psk: bool) -> Result<(), MlsError> { |
| 998 |
// An external commit cannot be the first commit in a group as it requires |
| 999 |
// interim_transcript_hash to be computed from the confirmed_transcript_hash and |
| 1000 |
// confirmation_tag, which is not the case for the initial interim_transcript_hash. |
| 1001 |
|
| 1002 |
use crate::group::{message_processor::CommitEffect, CommitMessageDescription}; |
| 1003 |
|
| 1004 |
let psk = PreSharedKey::from(b"psk".to_vec()); |
| 1005 |
let psk_id = ExternalPskId::new(b"psk id".to_vec()); |
| 1006 |
|
| 1007 |
let mut alice_group = |
| 1008 |
test_group_custom_config(TEST_PROTOCOL_VERSION, TEST_CIPHER_SUITE, |c| { |
| 1009 |
c.psk(psk_id.clone(), psk.clone()) |
| 1010 |
}) |
| 1011 |
.await; |
| 1012 |
|
| 1013 |
let (mut bob_group, _) = alice_group |
| 1014 |
.join_with_custom_config("bob", false, |c| { |
| 1015 |
c.0.psk_store.insert(psk_id.clone(), psk.clone()); |
| 1016 |
}) |
| 1017 |
.await |
| 1018 |
.unwrap(); |
| 1019 |
|
| 1020 |
let group_info_msg = alice_group |
| 1021 |
.group_info_message_allowing_ext_commit(true) |
| 1022 |
.await |
| 1023 |
.unwrap(); |
| 1024 |
|
| 1025 |
let new_client_id = if do_remove { "bob" } else { "charlie" }; |
| 1026 |
|
| 1027 |
let (new_client_identity, secret_key) = |
| 1028 |
get_test_signing_identity(TEST_CIPHER_SUITE, new_client_id.as_bytes()).await; |
| 1029 |
|
| 1030 |
let new_client = TestClientBuilder::new_for_test() |
| 1031 |
.psk(psk_id.clone(), psk) |
| 1032 |
.signing_identity(new_client_identity.clone(), secret_key, TEST_CIPHER_SUITE) |
| 1033 |
.build(); |
| 1034 |
|
| 1035 |
let mut builder = new_client.external_commit_builder().unwrap(); |
| 1036 |
|
| 1037 |
if do_remove { |
| 1038 |
builder = builder.with_removal(1); |
| 1039 |
} |
| 1040 |
|
| 1041 |
if with_psk { |
| 1042 |
builder = builder.with_external_psk(psk_id); |
| 1043 |
} |
| 1044 |
|
| 1045 |
let (new_group, external_commit) = builder.build(group_info_msg).await?; |
| 1046 |
|
| 1047 |
let num_members = if do_remove { 2 } else { 3 }; |
| 1048 |
|
| 1049 |
assert_eq!(new_group.roster().members_iter().count(), num_members); |
| 1050 |
|
| 1051 |
let _ = alice_group |
| 1052 |
.process_incoming_message(external_commit.clone()) |
| 1053 |
.await |
| 1054 |
.unwrap(); |
| 1055 |
|
| 1056 |
let bob_current_epoch = bob_group.current_epoch(); |
| 1057 |
|
| 1058 |
let message = bob_group |
| 1059 |
.process_incoming_message(external_commit) |
| 1060 |
.await |
| 1061 |
.unwrap(); |
| 1062 |
|
| 1063 |
assert!(alice_group.roster().members_iter().count() == num_members); |
| 1064 |
|
| 1065 |
if !do_remove { |
| 1066 |
assert!(bob_group.roster().members_iter().count() == num_members); |
| 1067 |
} else { |
| 1068 |
// Bob was removed so his epoch must stay the same |
| 1069 |
assert_eq!(bob_group.current_epoch(), bob_current_epoch); |
| 1070 |
|
| 1071 |
assert_matches!( |
| 1072 |
message, |
| 1073 |
ReceivedMessage::Commit(CommitMessageDescription { |
| 1074 |
effect: CommitEffect::Removed { |
| 1075 |
new_epoch: _, |
| 1076 |
remover: _ |
| 1077 |
}, |
| 1078 |
.. |
| 1079 |
}) |
| 1080 |
); |
| 1081 |
} |
| 1082 |
|
| 1083 |
// Comparing epoch authenticators is sufficient to check that members are in sync. |
| 1084 |
assert_eq!( |
| 1085 |
alice_group.epoch_authenticator().unwrap(), |
| 1086 |
new_group.epoch_authenticator().unwrap() |
| 1087 |
); |
| 1088 |
|
| 1089 |
Ok(()) |
| 1090 |
} |
| 1091 |
|
| 1092 |
#[cfg(feature = "psk")] |
| 1093 |
#[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))] |
| 1094 |
async fn test_external_commit() { |
| 1095 |
// New member can join |
| 1096 |
join_via_external_commit(false, false).await.unwrap(); |
| 1097 |
// New member can remove an old copy of themselves |
| 1098 |
join_via_external_commit(true, false).await.unwrap(); |
| 1099 |
// New member can inject a PSK |
| 1100 |
join_via_external_commit(false, true).await.unwrap(); |
| 1101 |
// All works together |
| 1102 |
join_via_external_commit(true, true).await.unwrap(); |
| 1103 |
} |
| 1104 |
|
| 1105 |
#[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))] |
| 1106 |
async fn creating_an_external_commit_requires_a_group_info_message() { |
| 1107 |
let (alice_identity, secret_key) = |
| 1108 |
get_test_signing_identity(TEST_CIPHER_SUITE, b"alice").await; |
| 1109 |
|
| 1110 |
let alice = TestClientBuilder::new_for_test() |
| 1111 |
.signing_identity(alice_identity.clone(), secret_key, TEST_CIPHER_SUITE) |
| 1112 |
.build(); |
| 1113 |
|
| 1114 |
let msg = alice |
| 1115 |
.generate_key_package_message(Default::default(), Default::default()) |
| 1116 |
.await |
| 1117 |
.unwrap(); |
| 1118 |
let res = alice.commit_external(msg).await.map(|_| ()); |
| 1119 |
|
| 1120 |
assert_matches!(res, Err(MlsError::UnexpectedMessageType)); |
| 1121 |
} |
| 1122 |
|
| 1123 |
#[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))] |
| 1124 |
async fn external_commit_with_invalid_group_info_fails() { |
| 1125 |
let mut alice_group = test_group(TEST_PROTOCOL_VERSION, TEST_CIPHER_SUITE).await; |
| 1126 |
let mut bob_group = test_group(TEST_PROTOCOL_VERSION, TEST_CIPHER_SUITE).await; |
| 1127 |
|
| 1128 |
bob_group.commit(vec![]).await.unwrap(); |
| 1129 |
bob_group.apply_pending_commit().await.unwrap(); |
| 1130 |
|
| 1131 |
let group_info_msg = bob_group |
| 1132 |
.group_info_message_allowing_ext_commit(true) |
| 1133 |
.await |
| 1134 |
.unwrap(); |
| 1135 |
|
| 1136 |
let (carol_identity, secret_key) = |
| 1137 |
get_test_signing_identity(TEST_CIPHER_SUITE, b"carol").await; |
| 1138 |
|
| 1139 |
let carol = TestClientBuilder::new_for_test() |
| 1140 |
.signing_identity(carol_identity, secret_key, TEST_CIPHER_SUITE) |
| 1141 |
.build(); |
| 1142 |
|
| 1143 |
let (_, external_commit) = carol |
| 1144 |
.external_commit_builder() |
| 1145 |
.unwrap() |
| 1146 |
.build(group_info_msg) |
| 1147 |
.await |
| 1148 |
.unwrap(); |
| 1149 |
|
| 1150 |
// If Carol tries to join Alice's group using the group info from Bob's group, that fails. |
| 1151 |
let res = alice_group.process_incoming_message(external_commit).await; |
| 1152 |
assert_matches!(res, Err(_)); |
| 1153 |
} |
| 1154 |
|
| 1155 |
#[test] |
| 1156 |
fn builder_can_be_obtained_from_client_to_edit_properties_for_new_client() { |
| 1157 |
let alice = TestClientBuilder::new_for_test() |
| 1158 |
.extension_type(33.into()) |
| 1159 |
.build(); |
| 1160 |
let bob = alice.to_builder().extension_type(34.into()).build(); |
| 1161 |
assert_eq!(bob.config.supported_extensions(), [33, 34].map(Into::into)); |
| 1162 |
} |
| 1163 |
|
| 1164 |
#[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))] |
| 1165 |
async fn examine_welcome_message() { |
| 1166 |
let mut alice = test_group(TEST_PROTOCOL_VERSION, TEST_CIPHER_SUITE) |
| 1167 |
.await |
| 1168 |
.group; |
| 1169 |
|
| 1170 |
let (bob, kp) = |
| 1171 |
test_client_with_key_pkg(TEST_PROTOCOL_VERSION, TEST_CIPHER_SUITE, "bob").await; |
| 1172 |
|
| 1173 |
let commit = alice |
| 1174 |
.commit_builder() |
| 1175 |
.add_member(kp) |
| 1176 |
.unwrap() |
| 1177 |
.build() |
| 1178 |
.await |
| 1179 |
.unwrap(); |
| 1180 |
|
| 1181 |
alice.apply_pending_commit().await.unwrap(); |
| 1182 |
|
| 1183 |
let mut group_info = bob |
| 1184 |
.examine_welcome_message(&commit.welcome_messages[0]) |
| 1185 |
.await |
| 1186 |
.unwrap(); |
| 1187 |
|
| 1188 |
// signature is random so we won't compare it |
| 1189 |
group_info.signature = vec![]; |
| 1190 |
group_info.ungrease(); |
| 1191 |
|
| 1192 |
let mut expected_group_info = alice |
| 1193 |
.group_info_message(commit.ratchet_tree.is_none()) |
| 1194 |
.await |
| 1195 |
.unwrap() |
| 1196 |
.into_group_info() |
| 1197 |
.unwrap(); |
| 1198 |
|
| 1199 |
expected_group_info.signature = vec![]; |
| 1200 |
expected_group_info.ungrease(); |
| 1201 |
|
| 1202 |
assert_eq!(expected_group_info, group_info); |
| 1203 |
} |
| 1204 |
|
| 1205 |
#[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))] |
| 1206 |
async fn validate_group_info() { |
| 1207 |
let alice = test_group(TEST_PROTOCOL_VERSION, TEST_CIPHER_SUITE) |
| 1208 |
.await |
| 1209 |
.group; |
| 1210 |
|
| 1211 |
let bob = test_client_with_key_pkg(TEST_PROTOCOL_VERSION, TEST_CIPHER_SUITE, "bob") |
| 1212 |
.await |
| 1213 |
.0; |
| 1214 |
|
| 1215 |
let group_info = alice.group_info_message(false).await.unwrap(); |
| 1216 |
let alice_signer = alice.current_member_signing_identity().unwrap().clone(); |
| 1217 |
|
| 1218 |
bob.validate_group_info(&group_info, &alice_signer) |
| 1219 |
.await |
| 1220 |
.unwrap(); |
| 1221 |
|
| 1222 |
let other_signer = get_test_signing_identity(TEST_CIPHER_SUITE, b"alice") |
| 1223 |
.await |
| 1224 |
.0; |
| 1225 |
|
| 1226 |
let res = bob.validate_group_info(&group_info, &other_signer).await; |
| 1227 |
assert_matches!(res, Err(MlsError::InvalidSignature)); |
| 1228 |
} |
| 1229 |
} |