Skip to main content

arachne_security/
bootstrap.rs

1//! Public membership proof for a prospective joiner. No group secrets are needed.
2//! The checkpoint digest must come from the user's trusted invitation, never
3//! from the peer response carrying the checkpoint. Wire invitation UX is separate.
4use super::{AUTHORITY, SUITE, Workspace};
5use openmls::prelude::{
6    tls_codec::{Deserialize, Serialize},
7    *,
8};
9use openmls::treesync::RatchetTree;
10use openmls_rust_crypto::OpenMlsRustCrypto;
11use openmls_traits::{OpenMlsProvider, crypto::OpenMlsCrypto};
12use sha2::{Digest, Sha256};
13
14const MAX_BYTES: usize = 64 * 1024;
15/// Bound for this device's own group state re-read for verification. It never
16/// crosses the network, so the 64 KiB wire bound does not apply: GroupInfo
17/// with the ratchet tree passes 64 KiB near 250 members (measured ~255 B per
18/// member), and members then rejected every later update.
19const MAX_LOCAL_STATE_BYTES: usize = 8 * 1024 * 1024;
20// ponytail: bounded in-memory/history replay budget. Checkpoint rollover
21// (below) removes the 64-step ceiling; this byte budget still applies.
22const MAX_HISTORY_BYTES: usize = 2 * 1024 * 1024;
23
24/// Transitions one chunk of a join history carries. A branch longer than this
25/// is verified chunk by chunk: rollover adds a chunk, it never widens one, so
26/// no single request, reply page or `StageJoin` call ever carries more steps
27/// than it always did.
28pub const HISTORY_CHUNK_STEPS: usize = 64;
29/// Chunks a joiner will roll through from one pinned invitation checkpoint.
30const MAX_HISTORY_CHUNKS: usize = 64;
31/// Transitions a joiner will replay from one pinned invitation checkpoint.
32pub const MAX_JOIN_HISTORY_STEPS: usize = HISTORY_CHUNK_STEPS * MAX_HISTORY_CHUNKS;
33/// Bytes a joiner will accept across a whole paged history exchange, including
34/// pages it has not yet verified. A reachable but hostile member must not be
35/// able to grow a pending join's memory one page at a time.
36pub const MAX_JOIN_HISTORY_BYTES: usize = MAX_HISTORY_BYTES;
37
38/// Public proof of an ordinary-member invitation and its exact redemption.
39/// No bearer private key is carried here. Fields are untrusted until verified.
40#[derive(Clone)]
41pub struct AdmissionAuthorization {
42    pub invitation_key: [u8; 32],
43    pub grant_signature: [u8; 64],
44    pub redemption_signature: [u8; 64],
45}
46
47/// Authorization for one exact membership transition. Tags cannot substitute
48/// for checking the signed MLS commit against its parent state.
49#[derive(Clone)]
50pub enum MembershipAuthorization {
51    Admission(AdmissionAuthorization),
52    AdmissionBatch(Vec<AdmissionAuthorization>),
53    Management(super::ManagementAction),
54}
55
56/// Tracks a branch from a trusted checkpoint. This does not settle competing
57/// branches, authenticate a real-world group name, or establish MLS membership.
58pub struct JoinProof {
59    pub(super) checkpoint_digest: [u8; 32],
60    verifier: MembershipVerifier,
61    pub(super) name_checkpoint: super::name::NameState,
62    history: Vec<u8>,
63    /// Verified transitions already carried by `history`. Tracked rather than
64    /// re-parsed on every append, which was quadratic in the branch length.
65    steps: usize,
66}
67
68/// A candidate history produced before the transition is verified. It is
69/// adopted only once the verifier has accepted the same transition.
70struct AppendedHistory {
71    history: Vec<u8>,
72    steps: usize,
73}
74
75/// Incrementally verifies exact membership transitions from a trusted checkpoint.
76/// Holds the current public roster, not a lifetime log or secret group keys.
77/// The caller retains the checkpoint and accepted transitions for durable replay;
78/// verification does not persist them, establish membership, or resolve forks.
79pub struct MembershipVerifier {
80    provider: OpenMlsRustCrypto,
81    pub(super) group: PublicGroup,
82}
83
84pub(super) fn authority(
85    extensions: &Extensions<GroupContext>,
86) -> Result<Vec<Vec<u8>>, &'static str> {
87    let bytes = &extensions.unknown(AUTHORITY).ok_or("missing authority")?.0;
88    if bytes.len() < 2
89        || !matches!(bytes[0], 1 | 2)
90        || !(1..=64).contains(&bytes[1])
91        || bytes.len() < 2 + usize::from(bytes[1]) * 32
92    {
93        return Err("invalid authority encoding");
94    }
95    let end = 2 + usize::from(bytes[1]) * 32;
96    if bytes[0] == 1 {
97        if bytes.len() != end {
98            return Err("invalid authority length");
99        }
100    } else {
101        super::invitation_controls::decode(&bytes[end..])?;
102    }
103    let keys: Vec<Vec<u8>> = bytes[2..end]
104        .as_chunks::<32>()
105        .0
106        .iter()
107        .map(|key| key.to_vec())
108        .collect();
109    if keys.windows(2).any(|pair| pair[0] >= pair[1]) {
110        return Err("noncanonical authority");
111    }
112    Ok(keys)
113}
114
115pub(super) fn binding(credential: &Credential) -> Result<([u8; 32], [u8; 32]), &'static str> {
116    let credential =
117        BasicCredential::try_from(credential.clone()).map_err(|_| "unsupported credential")?;
118    let bytes = credential
119        .identity()
120        .strip_prefix(b"data-fabric/candidate-member/v2/")
121        .ok_or("member credential upgrade required")?;
122    if bytes.len() != 64 || bytes[..32] == [0; 32] || bytes[32..] == [0; 32] {
123        return Err("invalid member binding");
124    }
125    Ok((
126        bytes[..32].try_into().unwrap(),
127        bytes[32..].try_into().unwrap(),
128    ))
129}
130
131pub(super) fn grant(group: &GroupId, key: &[u8; 32]) -> Vec<u8> {
132    // Matches the bounded ordinary-member grant exercised by the admission gate.
133    let mut bytes = b"data-fabric/candidate-invite/v1/ordinary-member".to_vec();
134    bytes.extend((group.as_slice().len() as u32).to_be_bytes());
135    bytes.extend(group.as_slice());
136    bytes.extend(key);
137    bytes
138}
139
140pub(super) fn redemption(
141    group: &GroupId,
142    key: &[u8; 32],
143    package: &KeyPackage,
144) -> Result<Vec<u8>, &'static str> {
145    let mut bytes = b"data-fabric/candidate-redemption/v1".to_vec();
146    bytes.extend(grant(group, key));
147    bytes.extend(
148        package
149            .tls_serialize_detached()
150            .map_err(|_| "KeyPackage encoding failed")?,
151    );
152    Ok(bytes)
153}
154
155impl Workspace {
156    /// Public, signed MLS state containing the roster. Only distribute to
157    /// authorized recipients; an invitation must bind its digest separately.
158    pub fn join_checkpoint(&self) -> Result<Vec<u8>, &'static str> {
159        if self.member().is_none() {
160            return Err("member credential upgrade required");
161        }
162        if !authority(self.group.extensions())?
163            .iter()
164            .any(|key| key == self._signer.public())
165        {
166            return Err("only an administrator may issue a checkpoint");
167        }
168        let bytes = self
169            .group
170            .export_group_info_with_additional_extensions(
171                self.provider.crypto(),
172                &self._signer,
173                true,
174                self.name_checkpoint_extension()?,
175            )
176            .map_err(|_| "checkpoint creation failed")?
177            .to_bytes()
178            .map_err(|_| "checkpoint encoding failed")?;
179        if bytes.len() > MAX_BYTES {
180            return Err("checkpoint exceeds bounds");
181        }
182        Ok(bytes)
183    }
184}
185
186impl MembershipVerifier {
187    /// The expected digest comes from the trusted invitation, not from the peer
188    /// supplying the checkpoint. The signed checkpoint includes roster metadata.
189    pub fn from_trusted_checkpoint(
190        workspace: [u8; 32],
191        digest: [u8; 32],
192        bytes: &[u8],
193    ) -> Result<Self, &'static str> {
194        Self::from_checkpoint_within(workspace, digest, bytes, MAX_BYTES)
195    }
196
197    fn from_checkpoint_within(
198        workspace: [u8; 32],
199        digest: [u8; 32],
200        bytes: &[u8],
201        limit: usize,
202    ) -> Result<Self, &'static str> {
203        if bytes.len() > limit {
204            return Err("checkpoint exceeds bounds");
205        }
206        if <[u8; 32]>::from(Sha256::digest(bytes)) != digest {
207            return Err("checkpoint does not match invitation");
208        }
209        let message =
210            MlsMessageIn::tls_deserialize_exact(bytes).map_err(|_| "invalid checkpoint")?;
211        let MlsMessageBodyIn::GroupInfo(info) = message.extract() else {
212            return Err("expected GroupInfo");
213        };
214        if info.group_id().as_slice() != workspace || info.ciphersuite() != SUITE {
215            return Err("wrong checkpoint workspace");
216        }
217        let tree = info
218            .extensions()
219            .ratchet_tree()
220            .ok_or("missing checkpoint tree")?
221            .ratchet_tree()
222            .clone();
223        let provider = OpenMlsRustCrypto::default();
224        let (group, _) = PublicGroup::from_external(
225            provider.crypto(),
226            provider.storage(),
227            tree,
228            info,
229            ProposalStore::new(),
230        )
231        .map_err(|_| "invalid checkpoint signature or tree")?;
232        let admins = authority(group.group_context().extensions())?;
233        let members: Vec<_> = group.members().collect();
234        let mut ids = std::collections::BTreeSet::new();
235        let mut endpoints = std::collections::BTreeSet::new();
236        for member in &members {
237            let (id, endpoint) = binding(&member.credential)?;
238            if !ids.insert(id) || !endpoints.insert(endpoint) {
239                return Err("duplicate member binding");
240            }
241        }
242        if !admins
243            .iter()
244            .all(|key| members.iter().any(|member| &member.signature_key == key))
245        {
246            return Err("administrator is not a member");
247        }
248        Ok(Self { provider, group })
249    }
250
251    /// Validate one bounded commit against current authority and advance exactly
252    /// one epoch. The caller must retain accepted records separately for replay.
253    pub fn apply_transition(
254        &mut self,
255        authorization: &MembershipAuthorization,
256        commit: &[u8],
257    ) -> Result<(), &'static str> {
258        match authorization {
259            MembershipAuthorization::Admission(auth) => self.apply_add(auth, commit),
260            MembershipAuthorization::AdmissionBatch(auths) => self.apply_add_batch(auths, commit),
261            MembershipAuthorization::Management(action) => self.apply_management(*action, commit),
262        }
263    }
264
265    fn apply_management(
266        &mut self,
267        action: super::ManagementAction,
268        commit: &[u8],
269    ) -> Result<(), &'static str> {
270        let staged = self.management_commit(action, commit)?;
271        self.group
272            .merge_commit(self.provider.storage(), staged)
273            .map_err(|_| "public management merge failed")?;
274        Ok(())
275    }
276
277    fn apply_add(
278        &mut self,
279        authorization: &AdmissionAuthorization,
280        commit: &[u8],
281    ) -> Result<(), &'static str> {
282        self.apply_add_batch(std::slice::from_ref(authorization), commit)
283    }
284
285    fn apply_add_batch(
286        &mut self,
287        authorizations: &[AdmissionAuthorization],
288        commit: &[u8],
289    ) -> Result<(), &'static str> {
290        if authorizations.is_empty() || authorizations.len() > super::MAX_ADMISSION_BATCH {
291            return Err("invalid admission batch size");
292        }
293        if commit.is_empty() || commit.len() > MAX_BYTES {
294            return Err("admission commit exceeds bounds");
295        }
296        let message = MlsMessageIn::tls_deserialize_exact(commit)
297            .map_err(|_| "invalid admission commit")?
298            .try_into_protocol_message()
299            .map_err(|_| "expected admission commit")?;
300        let processed = self
301            .group
302            .process_message(self.provider.crypto(), message)
303            .map_err(|_| "invalid admission signature or epoch")?;
304        let Sender::Member(index) = processed.sender() else {
305            return Err("committer is not a member");
306        };
307        let actor = self
308            .group
309            .members()
310            .find(|member| member.index == *index)
311            .ok_or("unknown committer")?;
312        let ProcessedMessageContent::StagedCommitMessage(staged) = processed.into_content() else {
313            return Err("not a commit");
314        };
315        if staged.queued_proposals().count() != authorizations.len()
316            || staged.group_context().extensions() != self.group.group_context().extensions()
317        {
318            return Err("invitation authorizes only Adds without policy changes");
319        }
320        if let Some(leaf) = staged.update_path_leaf_node()
321            && (leaf.credential() != &actor.credential
322                || leaf.signature_key().as_slice() != actor.signature_key)
323        {
324            return Err("admission cannot replace committer identity");
325        }
326        let adds: Vec<_> = staged.add_proposals().collect();
327        if adds.len() != authorizations.len() {
328            return Err("admission authorizes only Add proposals");
329        }
330        let mut bindings = std::collections::BTreeSet::new();
331        let admins = authority(self.group.group_context().extensions())?;
332        let crypto = self.provider.crypto();
333        for (authorization, add) in authorizations.iter().zip(adds) {
334            let package = add.add_proposal().key_package();
335            let (id, endpoint) = binding(package.leaf_node().credential())?;
336            if !bindings.insert((id, endpoint))
337                || self.group.members().any(|member| {
338                    binding(&member.credential)
339                        .map(|(existing_id, existing_endpoint)| {
340                            existing_id == id || existing_endpoint == endpoint
341                        })
342                        .unwrap_or(true)
343                })
344            {
345                return Err("duplicate member binding");
346            }
347            super::invitation_controls::check(
348                self.group.group_context().extensions(),
349                authorization.invitation_key,
350                None,
351                package,
352            )?;
353            if !admins.iter().any(|admin| {
354                crypto
355                    .verify_signature(
356                        SUITE.signature_algorithm(),
357                        &grant(self.group.group_id(), &authorization.invitation_key),
358                        admin,
359                        &authorization.grant_signature,
360                    )
361                    .is_ok()
362            }) {
363                return Err("unapproved invitation");
364            }
365            crypto
366                .verify_signature(
367                    SUITE.signature_algorithm(),
368                    &redemption(
369                        self.group.group_id(),
370                        &authorization.invitation_key,
371                        package,
372                    )?,
373                    &authorization.invitation_key,
374                    &authorization.redemption_signature,
375                )
376                .map_err(|_| "redemption does not match Add")?;
377        }
378        self.group
379            .merge_commit(self.provider.storage(), *staged)
380            .map_err(|_| "public state merge failed")?;
381        Ok(())
382    }
383
384    pub(super) fn authorizes_issuer(&self, issuer: &[u8]) -> Result<bool, &'static str> {
385        Ok(authority(self.group.group_context().extensions())?
386            .iter()
387            .any(|key| key == issuer))
388    }
389
390    pub(super) fn from_workspace(workspace: &Workspace) -> Result<Self, &'static str> {
391        let bytes = workspace
392            .group
393            .export_group_info(workspace.provider.crypto(), &workspace._signer, true)
394            .map_err(|_| "group comparison export failed")?
395            .to_bytes()
396            .map_err(|_| "group comparison encoding failed")?;
397        Self::from_checkpoint_within(workspace.id(), Sha256::digest(&bytes).into(), &bytes, MAX_LOCAL_STATE_BYTES)
398    }
399
400    pub(super) fn member_for_endpoint(
401        &self,
402        endpoint: [u8; 32],
403    ) -> Result<Option<[u8; 32]>, &'static str> {
404        for member in self.group.members() {
405            let (id, bound_endpoint) = binding(&member.credential)?;
406            if bound_endpoint == endpoint {
407                return Ok(Some(id));
408            }
409        }
410        Ok(None)
411    }
412
413    pub fn epoch(&self) -> u64 {
414        self.group.group_context().epoch().as_u64()
415    }
416
417    pub(super) fn verify_management(
418        &self,
419        action: super::ManagementAction,
420        commit: &[u8],
421    ) -> Result<(), &'static str> {
422        self.management_commit(action, commit).map(|_| ())
423    }
424
425    fn management_commit(
426        &self,
427        action: super::ManagementAction,
428        commit: &[u8],
429    ) -> Result<StagedCommit, &'static str> {
430        if commit.is_empty() || commit.len() > MAX_BYTES {
431            return Err("management commit exceeds bounds");
432        }
433        let message = MlsMessageIn::tls_deserialize_exact(commit)
434            .map_err(|_| "invalid management commit")?
435            .try_into_protocol_message()
436            .map_err(|_| "expected management commit")?;
437        let processed = self
438            .group
439            .process_message(self.provider.crypto(), message)
440            .map_err(|_| "invalid management signature or epoch")?;
441        let sender = processed.sender().clone();
442        let ProcessedMessageContent::StagedCommitMessage(staged) = processed.into_content() else {
443            return Err("not a management commit");
444        };
445        super::management::verify(
446            self.provider.crypto(),
447            &self.group,
448            &sender,
449            &staged,
450            action,
451        )?;
452        Ok(*staged)
453    }
454
455    /// Compare context, confirmation tag and complete tree with an independently
456    /// MLS-validated workspace. Public proof alone cannot validate Welcome secrets.
457    pub fn matches_workspace(&self, workspace: &Workspace) -> Result<bool, &'static str> {
458        Ok(
459            self.group.group_context() == workspace.group.public_group().group_context()
460                && self.group.confirmation_tag() == workspace.group.confirmation_tag()
461                && self.group.export_ratchet_tree() == workspace.group.export_ratchet_tree(),
462        )
463    }
464}
465
466impl JoinProof {
467    pub(super) fn export_ratchet_tree(&self) -> RatchetTree {
468        self.verifier.group.export_ratchet_tree()
469    }
470
471    pub fn from_trusted_checkpoint(
472        workspace: [u8; 32],
473        digest: [u8; 32],
474        bytes: &[u8],
475    ) -> Result<Self, &'static str> {
476        if bytes.len() > MAX_BYTES - 41 {
477            return Err("checkpoint exceeds inline history bounds");
478        }
479        let verifier = MembershipVerifier::from_trusted_checkpoint(workspace, digest, bytes)?;
480        let message =
481            MlsMessageIn::tls_deserialize_exact(bytes).map_err(|_| "invalid checkpoint")?;
482        let MlsMessageBodyIn::GroupInfo(info) = message.extract() else {
483            return Err("expected GroupInfo");
484        };
485        let name_checkpoint = info
486            .extensions()
487            .unknown(super::name::EXTENSION)
488            .map(|e| super::name::NameState::decode(&e.0))
489            .transpose()?
490            .unwrap_or_default();
491        let mut history = b"DFJH\x01".to_vec();
492        history.extend(digest);
493        history.extend((bytes.len() as u32).to_be_bytes());
494        history.extend(bytes);
495        Ok(Self {
496            checkpoint_digest: digest,
497            name_checkpoint,
498            verifier,
499            history,
500            steps: 0,
501        })
502    }
503
504    pub fn workspace_name(&self) -> Result<Option<String>, &'static str> {
505        Ok(self.name_checkpoint.name.clone())
506    }
507    pub fn history(&self) -> &[u8] {
508        &self.history
509    }
510
511    pub(super) fn history_steps(
512        encoded: &[u8],
513    ) -> Result<Vec<(MembershipAuthorization, Vec<u8>)>, &'static str> {
514        Self::history_steps_with_limit(encoded, MAX_HISTORY_BYTES)
515    }
516
517    fn history_steps_with_limit(
518        encoded: &[u8],
519        limit: usize,
520    ) -> Result<Vec<(MembershipAuthorization, Vec<u8>)>, &'static str> {
521        use super::storage::{number, take};
522        if encoded.len() > limit
523            || !(encoded.starts_with(b"DFJH\x01") || encoded.starts_with(b"DFJH\x02"))
524        {
525            return Err("invalid join history");
526        }
527        let version = encoded[4];
528        let mut bytes = &encoded[5..];
529        take(&mut bytes, 32)?;
530        let length = number(&mut bytes)?;
531        take(&mut bytes, length)?;
532        let mut steps = Vec::new();
533        while !bytes.is_empty() {
534            // A branch longer than one chunk is verified chunk by chunk, so the
535            // stored form carries the whole branch while every call, request and
536            // page still handles at most HISTORY_CHUNK_STEPS of it.
537            if steps.len() == MAX_JOIN_HISTORY_STEPS {
538                return Err("join history exceeds step bounds");
539            }
540            steps.push(Self::read_step(&mut bytes, version == 2)?);
541        }
542        Ok(steps)
543    }
544
545    fn read_step(
546        rest: &mut &[u8],
547        tagged: bool,
548    ) -> Result<(MembershipAuthorization, Vec<u8>), &'static str> {
549        use super::storage::{number, take};
550        let mut bytes = *rest;
551        let step = {
552            let tag = if tagged { take(&mut bytes, 1)?[0] } else { 0 };
553            let authorization = match tag {
554                0 => MembershipAuthorization::Admission(AdmissionAuthorization {
555                    invitation_key: take(&mut bytes, 32)?.try_into().unwrap(),
556                    grant_signature: take(&mut bytes, 64)?.try_into().unwrap(),
557                    redemption_signature: take(&mut bytes, 64)?.try_into().unwrap(),
558                }),
559                11 => {
560                    let count = u16::from_be_bytes(take(&mut bytes, 2)?.try_into().unwrap()) as usize;
561                    if count == 0 || count > super::MAX_ADMISSION_BATCH {
562                        return Err("invalid admission batch size");
563                    }
564                    MembershipAuthorization::AdmissionBatch(
565                        (0..count)
566                            .map(|_| {
567                                Ok(AdmissionAuthorization {
568                                    invitation_key: take(&mut bytes, 32)?.try_into().unwrap(),
569                                    grant_signature: take(&mut bytes, 64)?.try_into().unwrap(),
570                                    redemption_signature: take(&mut bytes, 64)?.try_into().unwrap(),
571                                })
572                            })
573                            .collect::<Result<Vec<_>, _>>()?,
574                    )
575                }
576                1..=10 => {
577                    let id = take(&mut bytes, 32)?.try_into().unwrap();
578                    MembershipAuthorization::Management(match tag {
579                        1 => super::ManagementAction::Promote(id),
580                        2 => super::ManagementAction::Demote(id),
581                        3 => super::ManagementAction::Remove(id),
582                        4 => super::ManagementAction::Leave(
583                            id,
584                            take(&mut bytes, 64)?.try_into().unwrap(),
585                        ),
586                        5 => super::ManagementAction::CreateInvitation(
587                            id,
588                            u64::from_be_bytes(take(&mut bytes, 8)?.try_into().unwrap()),
589                            match take(&mut bytes, 1)?[0] {
590                                0 => false,
591                                1 => true,
592                                _ => return Err("invalid invitation mode"),
593                            },
594                        ),
595                        6 => super::ManagementAction::DisableInvitation(id),
596                        7 => super::ManagementAction::ApproveInvitation(
597                            id,
598                            take(&mut bytes, 32)?.try_into().unwrap(),
599                        ),
600                        9 => super::ManagementAction::CreateRequestInvitation(
601                            id,
602                            u64::from_be_bytes(take(&mut bytes, 8)?.try_into().unwrap()),
603                        ),
604                        10 => super::ManagementAction::DeclineInvitationRequest(
605                            id,
606                            take(&mut bytes, 32)?.try_into().unwrap(),
607                        ),
608                        _ => super::ManagementAction::CreateAutomaticInvitation(
609                            id,
610                            u64::from_be_bytes(take(&mut bytes, 8)?.try_into().unwrap()),
611                        ),
612                    })
613                }
614                _ => return Err("unknown membership history action"),
615            };
616            let length = number(&mut bytes)?;
617            if length == 0 {
618                return Err("empty membership history commit");
619            }
620            (authorization, take(&mut bytes, length)?.to_vec())
621        };
622        *rest = bytes;
623        Ok(step)
624    }
625
626    pub fn from_history(
627        workspace: [u8; 32],
628        digest: [u8; 32],
629        encoded: &[u8],
630    ) -> Result<Self, &'static str> {
631        use super::storage::{number, take};
632        if encoded.len() > MAX_BYTES {
633            return Err("invalid join history");
634        }
635        let steps = Self::history_steps(encoded)?;
636        let mut bytes = &encoded[5..];
637        if take(&mut bytes, 32)? != digest {
638            return Err("history checkpoint mismatch");
639        }
640        let length = number(&mut bytes)?;
641        let checkpoint = take(&mut bytes, length)?;
642        let mut proof = Self::from_trusted_checkpoint(workspace, digest, checkpoint)?;
643        if encoded[4] == 2 {
644            proof.history[4] = 2;
645        }
646        for (authorization, commit) in steps {
647            proof.apply_transition(&authorization, &commit)?;
648        }
649        Ok(proof)
650    }
651
652    pub fn invitation_control(
653        &self,
654        key: [u8; 32],
655    ) -> Result<Option<super::InvitationControl>, &'static str> {
656        let (_, controls) =
657            super::invitation_controls::decode(&super::invitation_controls::policy_bytes(
658                self.verifier.group.group_context().extensions(),
659            )?)?;
660        Ok(controls.into_iter().find(|c| c.key == key))
661    }
662
663    pub fn apply_transition(
664        &mut self,
665        authorization: &MembershipAuthorization,
666        commit: &[u8],
667    ) -> Result<(), &'static str> {
668        match authorization {
669            MembershipAuthorization::Admission(auth) => self.apply_add(auth, commit),
670            MembershipAuthorization::AdmissionBatch(auths) => {
671                let appended = self.appended_history(authorization, commit)?;
672                self.verifier.apply_add_batch(auths, commit)?;
673                self.adopt_history(appended);
674                Ok(())
675            }
676            MembershipAuthorization::Management(action) => self.apply_management(*action, commit),
677        }
678    }
679
680    fn appended_history(
681        &self,
682        authorization: &MembershipAuthorization,
683        commit: &[u8],
684    ) -> Result<AppendedHistory, &'static str> {
685        if self.steps >= MAX_JOIN_HISTORY_STEPS || commit.is_empty() || commit.len() > MAX_BYTES {
686            return Err("membership history exceeds bounds");
687        }
688        let mut history = self.history.clone();
689        if history[4] == 1 && !matches!(authorization, MembershipAuthorization::Admission(_)) {
690            let steps = Self::history_steps_with_limit(&self.history, MAX_HISTORY_BYTES)?;
691            let length = u32::from_be_bytes(history[37..41].try_into().unwrap()) as usize;
692            history.truncate(41 + length);
693            history[4] = 2;
694            for (auth, bytes) in &steps {
695                Self::write_step(&mut history, auth, bytes);
696            }
697        }
698        Self::write_step(&mut history, authorization, commit);
699        if history.len() > MAX_HISTORY_BYTES {
700            return Err("membership history exceeds bounds");
701        }
702        Ok(AppendedHistory {
703            history,
704            steps: self.steps + 1,
705        })
706    }
707
708    fn adopt_history(&mut self, appended: AppendedHistory) {
709        self.history = appended.history;
710        self.steps = appended.steps;
711    }
712
713    fn write_step(history: &mut Vec<u8>, authorization: &MembershipAuthorization, commit: &[u8]) {
714        match authorization {
715            MembershipAuthorization::Admission(auth) => {
716                if history[4] >= 2 {
717                    history.push(0);
718                }
719                history.extend(auth.invitation_key);
720                history.extend(auth.grant_signature);
721                history.extend(auth.redemption_signature);
722            }
723            MembershipAuthorization::AdmissionBatch(auths) => {
724                history.push(11);
725                history.extend((auths.len() as u16).to_be_bytes());
726                for auth in auths {
727                    history.extend(auth.invitation_key);
728                    history.extend(auth.grant_signature);
729                    history.extend(auth.redemption_signature);
730                }
731            }
732            MembershipAuthorization::Management(action) => {
733                let (tag, id) = match action {
734                    super::ManagementAction::Promote(id) => (1, id),
735                    super::ManagementAction::Demote(id) => (2, id),
736                    super::ManagementAction::Remove(id) => (3, id),
737                    super::ManagementAction::Leave(id, _) => (4, id),
738                    super::ManagementAction::CreateInvitation(id, ..) => (5, id),
739                    super::ManagementAction::CreateAutomaticInvitation(id, ..) => (8, id),
740                    super::ManagementAction::CreateRequestInvitation(id, ..) => (9, id),
741                    super::ManagementAction::DeclineInvitationRequest(id, _) => (10, id),
742                    super::ManagementAction::DisableInvitation(id) => (6, id),
743                    super::ManagementAction::ApproveInvitation(id, _) => (7, id),
744                };
745                history.push(tag);
746                history.extend(id);
747                if let super::ManagementAction::Leave(_, signature) = action {
748                    history.extend(signature);
749                }
750                if let super::ManagementAction::CreateInvitation(_, expires, personal) = action {
751                    history.extend(expires.to_be_bytes());
752                    history.push(u8::from(*personal));
753                }
754                if let super::ManagementAction::CreateAutomaticInvitation(_, expires)
755                | super::ManagementAction::CreateRequestInvitation(_, expires) = action
756                {
757                    history.extend(expires.to_be_bytes());
758                }
759                if let super::ManagementAction::ApproveInvitation(_, package)
760                | super::ManagementAction::DeclineInvitationRequest(_, package) = action
761                {
762                    history.extend(package);
763                }
764            }
765        }
766        history.extend((commit.len() as u32).to_be_bytes());
767        history.extend(commit);
768    }
769
770    pub(super) fn from_workspace(workspace: &Workspace) -> Result<Self, &'static str> {
771        let bytes = workspace
772            .group
773            .export_group_info(workspace.provider.crypto(), &workspace._signer, true)
774            .map_err(|_| "group comparison export failed")?
775            .to_bytes()
776            .map_err(|_| "group comparison encoding failed")?;
777        Self::from_trusted_checkpoint(workspace.id(), Sha256::digest(&bytes).into(), &bytes)
778    }
779
780    pub fn apply_management(
781        &mut self,
782        action: super::ManagementAction,
783        commit: &[u8],
784    ) -> Result<(), &'static str> {
785        let appended =
786            self.appended_history(&MembershipAuthorization::Management(action), commit)?;
787        self.verifier.apply_management(action, commit)?;
788        self.adopt_history(appended);
789        Ok(())
790    }
791    pub fn apply_add(
792        &mut self,
793        authorization: &AdmissionAuthorization,
794        commit: &[u8],
795    ) -> Result<(), &'static str> {
796        let appended = self.appended_history(
797            &MembershipAuthorization::Admission(authorization.clone()),
798            commit,
799        )?;
800        self.verifier.apply_add(authorization, commit)?;
801        self.adopt_history(appended);
802        Ok(())
803    }
804    pub(super) fn authorizes_issuer(&self, issuer: &[u8]) -> Result<bool, &'static str> {
805        self.verifier.authorizes_issuer(issuer)
806    }
807    pub fn epoch(&self) -> u64 {
808        self.verifier.epoch()
809    }
810    pub(super) fn verify_management(
811        &self,
812        action: super::ManagementAction,
813        commit: &[u8],
814    ) -> Result<(), &'static str> {
815        self.verifier.verify_management(action, commit)
816    }
817    pub fn matches_workspace(&self, workspace: &Workspace) -> Result<bool, &'static str> {
818        self.verifier.matches_workspace(workspace)
819    }
820}
821
822#[cfg(test)]
823mod tests {
824    use super::*;
825    use crate::{MemberProfile, credential_identity};
826    use openmls_basic_credential::SignatureKeyPair;
827    use openmls_traits::signatures::Signer;
828
829    struct Candidate {
830        provider: OpenMlsRustCrypto,
831        signer: SignatureKeyPair,
832        profile: MemberProfile,
833        endpoint: [u8; 32],
834        package: KeyPackage,
835    }
836    impl Candidate {
837        fn new(n: u8) -> Self {
838            let provider = OpenMlsRustCrypto::default();
839            let signer = SignatureKeyPair::new(SUITE.signature_algorithm()).unwrap();
840            signer.store(provider.storage()).unwrap();
841            let profile = MemberProfile::new([n; 32], "Alex").unwrap();
842            let endpoint = [n + 10; 32];
843            let credential = CredentialWithKey {
844                credential: BasicCredential::new(credential_identity(endpoint, Some(&profile)))
845                    .into(),
846                signature_key: signer.to_public_vec().into(),
847            };
848            let package = KeyPackage::builder()
849                .leaf_node_capabilities(Capabilities::new(
850                    None,
851                    None,
852                    Some(&[ExtensionType::Unknown(AUTHORITY)]),
853                    None,
854                    None,
855                ))
856                .build(SUITE, &provider, &signer, credential)
857                .unwrap()
858                .key_package()
859                .clone();
860            Self {
861                provider,
862                signer,
863                profile,
864                endpoint,
865                package,
866            }
867        }
868        fn join(self, id: [u8; 32], welcome: MlsMessageOut) -> Workspace {
869            let MlsMessageBodyIn::Welcome(welcome) =
870                MlsMessageIn::tls_deserialize_exact(welcome.to_bytes().unwrap())
871                    .unwrap()
872                    .extract()
873            else {
874                panic!("not a Welcome")
875            };
876            let config = MlsGroupJoinConfig::builder()
877                .wire_format_policy(PURE_PLAINTEXT_WIRE_FORMAT_POLICY)
878                .use_ratchet_tree_extension(true)
879                .build();
880            let group = StagedWelcome::new_from_welcome(&self.provider, &config, welcome, None)
881                .unwrap()
882                .into_group(&self.provider)
883                .unwrap();
884            Workspace {
885                provider: self.provider,
886                _signer: self.signer,
887                group,
888                id,
889                endpoint: self.endpoint,
890                member: Some(self.profile),
891                admissions: Vec::new(),
892                join_history: None,
893                invitation_checkpoints: Vec::new(),
894            }
895        }
896    }
897
898    #[test]
899    fn trusted_checkpoint_rejects_substitution_and_unauthorized_branch() {
900        let invalid = BasicCredential::new(credential_identity(
901            [0; 32],
902            Some(&MemberProfile::new([1; 32], "Alex").unwrap()),
903        ))
904        .into();
905        assert!(binding(&invalid).is_err());
906        let mut admin = Workspace::create([1; 32], "Coordinator").unwrap();
907        let checkpoint = admin.join_checkpoint().unwrap();
908        let digest: [u8; 32] = Sha256::digest(&checkpoint).into();
909        let mut proof =
910            JoinProof::from_trusted_checkpoint(admin.id(), digest, &checkpoint).unwrap();
911        assert!(proof.matches_workspace(&admin).unwrap());
912        let other = Workspace::create([2; 32], "Coordinator")
913            .unwrap()
914            .join_checkpoint()
915            .unwrap();
916        assert!(JoinProof::from_trusted_checkpoint(admin.id(), digest, &other).is_err());
917        assert!(JoinProof::from_trusted_checkpoint([99; 32], digest, &checkpoint).is_err());
918        let mut damaged = checkpoint.clone();
919        let end = damaged.len() - 1;
920        damaged[end] ^= 1;
921        assert!(JoinProof::from_trusted_checkpoint(admin.id(), digest, &damaged).is_err());
922        // Even a caller supplying the damaged hash cannot bypass MLS signature validation.
923        assert!(
924            JoinProof::from_trusted_checkpoint(
925                admin.id(),
926                Sha256::digest(&damaged).into(),
927                &damaged
928            )
929            .is_err()
930        );
931        assert!(
932            JoinProof::from_trusted_checkpoint(admin.id(), [0; 32], &vec![0; MAX_BYTES + 1])
933                .is_err()
934        );
935
936        let helper = Candidate::new(3);
937        let invite = SignatureKeyPair::new(SUITE.signature_algorithm()).unwrap();
938        let invitation_key = invite.public().try_into().unwrap();
939        let grant_signature = admin
940            ._signer
941            .sign(&grant(admin.group.group_id(), &invitation_key))
942            .unwrap()
943            .try_into()
944            .unwrap();
945        let authorize = |group: &GroupId, package: &KeyPackage| AdmissionAuthorization {
946            invitation_key,
947            grant_signature,
948            redemption_signature: invite
949                .sign(&redemption(group, &invitation_key, package).unwrap())
950                .unwrap()
951                .try_into()
952                .unwrap(),
953        };
954        let helper_auth = authorize(admin.group.group_id(), &helper.package);
955        let (commit, welcome, _) = admin
956            .group
957            .add_members(
958                &admin.provider,
959                &admin._signer,
960                std::slice::from_ref(&helper.package),
961            )
962            .unwrap();
963        let commit = commit.to_bytes().unwrap();
964        let mut invalid_auth = authorize(admin.group.group_id(), &helper.package);
965        invalid_auth.grant_signature[0] ^= 1;
966        assert!(proof.apply_add(&invalid_auth, &commit).is_err());
967        assert_eq!(proof.epoch(), 0);
968        let mut trailing = commit.clone();
969        trailing.push(0);
970        assert!(proof.apply_add(&helper_auth, &trailing).is_err());
971        assert_eq!(proof.epoch(), 0);
972        proof.apply_add(&helper_auth, &commit).unwrap();
973        assert!(proof.apply_add(&helper_auth, &commit).is_err()); // replay
974        assert_eq!(proof.epoch(), 1);
975        admin.group.merge_pending_commit(&admin.provider).unwrap();
976        let mut helper = helper.join(admin.id(), welcome);
977        assert!(proof.matches_workspace(&helper).unwrap());
978        assert!(helper.join_checkpoint().is_err()); // ordinary member cannot issue a new trust root
979
980        // Admin is no longer involved. An ordinary helper fulfills the existing grant.
981        let fork_key = crate::StorageKey::derive(&[42; 32]).unwrap();
982        let fork_snapshot = helper.seal(&fork_key).unwrap();
983        let mut fork =
984            Workspace::restore(&fork_key, helper.endpoint, helper.id(), &fork_snapshot).unwrap();
985        let joined = Candidate::new(4);
986        let joined_auth = authorize(helper.group.group_id(), &joined.package);
987        let (commit, welcome, _) = helper
988            .group
989            .add_members(
990                &helper.provider,
991                &helper._signer,
992                std::slice::from_ref(&joined.package),
993            )
994            .unwrap();
995        let commit = commit.to_bytes().unwrap();
996        let mismatched = authorize(helper.group.group_id(), &Candidate::new(5).package);
997        assert!(proof.apply_add(&mismatched, &commit).is_err());
998        assert_eq!(proof.epoch(), 1);
999        proof.apply_add(&joined_auth, &commit).unwrap();
1000        helper.group.merge_pending_commit(&helper.provider).unwrap();
1001        let mut joined = joined.join(helper.id(), welcome);
1002        assert!(proof.matches_workspace(&joined).unwrap());
1003        assert!(!proof.matches_workspace(&admin).unwrap()); // same ID and admin, older branch
1004        let encrypted = joined
1005            .group
1006            .create_message(
1007                &joined.provider,
1008                &joined._signer,
1009                b"arbitrary application bytes",
1010            )
1011            .unwrap();
1012        let message = MlsMessageIn::tls_deserialize_exact(encrypted.to_bytes().unwrap()).unwrap();
1013        assert!(matches!(
1014            message.extract(),
1015            MlsMessageBodyIn::PrivateMessage(_)
1016        ));
1017
1018        // A fully MLS-valid unauthorized Welcome at the SAME epoch/ID/admin
1019        // roster is not the authorized branch. This catches more than staleness.
1020        let uninvited = Candidate::new(6);
1021        let mut forged = authorize(fork.group.group_id(), &uninvited.package);
1022        forged.grant_signature = fork
1023            ._signer
1024            .sign(&grant(fork.group.group_id(), &invitation_key))
1025            .unwrap()
1026            .try_into()
1027            .unwrap();
1028        let (bad_commit, bad_welcome, _) = fork
1029            .group
1030            .add_members(
1031                &fork.provider,
1032                &fork._signer,
1033                std::slice::from_ref(&uninvited.package),
1034            )
1035            .unwrap();
1036        fork.group.merge_pending_commit(&fork.provider).unwrap();
1037        let uninvited = uninvited.join(fork.id(), bad_welcome);
1038        assert_eq!(uninvited.epoch(), proof.epoch());
1039        assert_eq!(uninvited.id(), joined.id());
1040        assert_eq!(uninvited.group.extensions(), joined.group.extensions());
1041        assert!(!proof.matches_workspace(&uninvited).unwrap());
1042        // Verify authorization rejection from the correct previous epoch too.
1043        // A separate verifier starts at the pre-fork checkpoint, so this
1044        // negative assertion tests grant authority rather than epoch mismatch.
1045        let before_fork = admin.join_checkpoint().unwrap();
1046        let mut fork_proof = JoinProof::from_trusted_checkpoint(
1047            admin.id(),
1048            Sha256::digest(&before_fork).into(),
1049            &before_fork,
1050        )
1051        .unwrap();
1052        assert_eq!(
1053            fork_proof.apply_add(&forged, &bad_commit.to_bytes().unwrap()),
1054            Err("unapproved invitation")
1055        );
1056        assert_eq!(fork_proof.epoch(), 1);
1057        assert_eq!(proof.epoch(), 2);
1058        assert!(proof.matches_workspace(&joined).unwrap());
1059    }
1060}