Skip to main content

arachne_security/
invitation.rs

1//! Fixed ordinary-member invitation and request codec. No addresses or UI types.
2use super::{
3    AdmissionAuthorization, JoinProof, MembershipAuthorization, SUITE, Workspace, bootstrap,
4    storage,
5};
6use openmls::prelude::{
7    tls_codec::{Deserialize, Serialize},
8    *,
9};
10use openmls_basic_credential::SignatureKeyPair;
11use openmls_rust_crypto::OpenMlsRustCrypto;
12use openmls_traits::{OpenMlsProvider, crypto::OpenMlsCrypto, signatures::Signer};
13use sha2::{Digest, Sha256};
14use std::collections::BTreeSet;
15use zeroize::Zeroizing;
16
17const TOKEN: &[u8; 5] = b"DFIV\x01";
18const REQUEST: &[u8; 5] = b"DFJR\x01";
19pub(super) const PUBLIC: usize = 261;
20pub(super) const TOKEN_SIZE: usize = PUBLIC + 32;
21const REQUEST_HEADER: usize = 5 + PUBLIC + 64;
22const CHECKPOINT_REQUEST_SIZE: usize = PUBLIC + 64;
23pub(super) const MAX_REQUEST: usize = REQUEST_HEADER + 16 * 1024;
24pub(super) const MAX_RETAINED_CHECKPOINTS: usize = 256;
25const MAX_RETAINED_CHECKPOINT_BYTES: usize = 2 * 1024 * 1024;
26
27/// Reusable bearer authorization. Never log or publish its secret token.
28/// Receiving it via a trusted human/application channel establishes the initial
29/// workspace trust root; self-consistent signatures alone do not identify a person.
30pub struct Invitation {
31    grant: [u8; PUBLIC],
32    secret: Zeroizing<[u8; 32]>,
33}
34
35#[derive(Clone)]
36pub(super) struct RetainedInvitationCheckpoint {
37    pub grant: [u8; PUBLIC],
38    pub checkpoint: Vec<u8>,
39}
40
41/// Accepted membership transitions in epoch order, each with the authorization
42/// that permitted it.
43type MembershipSteps = Vec<(MembershipAuthorization, Vec<u8>)>;
44
45/// One accepted transition, borrowed from wherever this owner already keeps it.
46/// Retained admissions store the authorization and commit separately from the
47/// join history's steps, so this names both without copying either.
48enum AcceptedStep<'a> {
49    History(&'a (MembershipAuthorization, Vec<u8>)),
50    Admission(&'a RetainedAdmission),
51}
52
53impl AcceptedStep<'_> {
54    fn commit(&self) -> &[u8] {
55        match self {
56            Self::History((_, commit)) => commit,
57            Self::Admission(admission) => &admission.reply.commit,
58        }
59    }
60    fn to_step(&self) -> (MembershipAuthorization, Vec<u8>) {
61        match self {
62            Self::History((authorization, commit)) => (authorization.clone(), commit.clone()),
63            Self::Admission(admission) => (
64                MembershipAuthorization::Admission(admission.reply.authorization.clone()),
65                admission.reply.commit.to_vec(),
66            ),
67        }
68    }
69}
70
71/// Place one accepted transition at its epoch. Transitions outside the range
72/// are ignored; a second, different commit for an epoch already filled means
73/// the records disagree, and `None` sends the caller to full verification.
74fn place_accepted<'a>(
75    slots: &mut [Option<AcceptedStep<'a>>],
76    start: u64,
77    candidate: AcceptedStep<'a>,
78) -> Option<()> {
79    let epoch = commit_epoch(candidate.commit())?;
80    let Some(index) = epoch
81        .checked_sub(start)
82        .and_then(|index| usize::try_from(index).ok())
83    else {
84        return Some(());
85    };
86    match slots.get_mut(index) {
87        None => Some(()),
88        Some(Some(existing)) if existing.commit() != candidate.commit() => None,
89        Some(Some(_)) => Some(()),
90        Some(slot) => {
91            *slot = Some(candidate);
92            Some(())
93        }
94    }
95}
96
97/// The epoch a signed commit advances from. Reading the epoch is parsing, not
98/// verification: callers must already know the commit is one they accepted.
99fn commit_epoch(commit: &[u8]) -> Option<u64> {
100    MlsMessageIn::tls_deserialize_exact(commit)
101        .ok()
102        .and_then(|message| message.try_into_protocol_message().ok())
103        .map(|message| message.epoch().as_u64())
104}
105
106/// The epoch a checkpoint describes, without building the public group. Used
107/// only for checkpoints this owner issued and retained itself.
108fn checkpoint_epoch(checkpoint: &[u8]) -> Result<u64, &'static str> {
109    let message =
110        MlsMessageIn::tls_deserialize_exact(checkpoint).map_err(|_| "invalid checkpoint")?;
111    let MlsMessageBodyIn::GroupInfo(info) = message.extract() else {
112        return Err("expected GroupInfo");
113    };
114    Ok(info.epoch().as_u64())
115}
116
117fn binding_message(grant: &[u8]) -> Vec<u8> {
118    let mut bytes = b"data-fabric/invitation-checkpoint/v1/".to_vec();
119    bytes.extend(&grant[..197]);
120    bytes
121}
122fn checkpoint_request_message(grant: &[u8], requester: [u8; 32], responder: [u8; 32]) -> Vec<u8> {
123    let mut bytes = b"data-fabric/invitation-checkpoint-request/v1/".to_vec();
124    bytes.extend(grant);
125    bytes.extend(requester);
126    bytes.extend(responder);
127    bytes
128}
129fn verify_grant(provider: &OpenMlsRustCrypto, grant: &[u8]) -> Result<(), &'static str> {
130    if grant.len() != PUBLIC || !grant.starts_with(TOKEN) {
131        return Err("invalid invitation format");
132    }
133    let workspace = GroupId::from_slice(&grant[5..37]);
134    let invite_key = grant[101..133].try_into().unwrap();
135    provider
136        .crypto()
137        .verify_signature(
138            SUITE.signature_algorithm(),
139            &bootstrap::grant(&workspace, invite_key),
140            &grant[69..101],
141            &grant[133..197],
142        )
143        .map_err(|_| "invalid invitation grant signature")?;
144    provider
145        .crypto()
146        .verify_signature(
147            SUITE.signature_algorithm(),
148            &binding_message(grant),
149            &grant[69..101],
150            &grant[197..261],
151        )
152        .map_err(|_| "invalid invitation checkpoint signature")
153}
154impl Invitation {
155    pub fn from_bytes(bytes: &[u8]) -> Result<Self, &'static str> {
156        if bytes.len() != TOKEN_SIZE {
157            return Err("invalid invitation size");
158        }
159        let provider = OpenMlsRustCrypto::default();
160        verify_grant(&provider, &bytes[..PUBLIC])?;
161        let value = Self {
162            grant: bytes[..PUBLIC].try_into().unwrap(),
163            secret: Zeroizing::new(bytes[PUBLIC..].try_into().unwrap()),
164        };
165        let signer = value.signer();
166        let challenge = b"data-fabric/invitation-key-check/v1";
167        let signature = signer
168            .sign(challenge)
169            .map_err(|_| "invalid invitation key")?;
170        provider
171            .crypto()
172            .verify_signature(
173                SUITE.signature_algorithm(),
174                challenge,
175                &value.grant[101..133],
176                &signature,
177            )
178            .map_err(|_| "invitation bearer key mismatch")?;
179        Ok(value)
180    }
181    pub fn export_secret_token(&self) -> Zeroizing<Vec<u8>> {
182        let mut bytes = Zeroizing::new(self.grant.to_vec());
183        bytes.extend(self.secret.as_slice());
184        bytes
185    }
186    pub fn key(&self) -> [u8; 32] {
187        self.grant[101..133].try_into().unwrap()
188    }
189    pub fn workspace_id(&self) -> [u8; 32] {
190        self.grant[5..37].try_into().unwrap()
191    }
192    pub fn checkpoint_digest(&self) -> [u8; 32] {
193        self.grant[37..69].try_into().unwrap()
194    }
195    pub fn public_grant(&self) -> &[u8] {
196        &self.grant
197    }
198    pub fn join_proof(&self, checkpoint: &[u8]) -> Result<JoinProof, &'static str> {
199        let proof = JoinProof::from_trusted_checkpoint(
200            self.workspace_id(),
201            self.checkpoint_digest(),
202            checkpoint,
203        )?;
204        if !proof.authorizes_issuer(&self.grant[69..101])? {
205            return Err("invitation issuer is not a checkpoint administrator");
206        }
207        Ok(proof)
208    }
209    /// Prove bearer possession without transmitting the invitation secret.
210    /// Both authenticated Iroh endpoint identities are bound to prevent replay
211    /// through a substituted bootstrap peer.
212    pub fn checkpoint_request(
213        &self,
214        requester: [u8; 32],
215        responder: [u8; 32],
216    ) -> Result<Vec<u8>, &'static str> {
217        if requester == [0; 32] || responder == [0; 32] || requester == responder {
218            return Err("invalid checkpoint request endpoints");
219        }
220        let mut bytes = self.grant.to_vec();
221        bytes.extend(
222            self.signer()
223                .sign(&checkpoint_request_message(
224                    &self.grant,
225                    requester,
226                    responder,
227                ))
228                .map_err(|_| "checkpoint request signing failed")?,
229        );
230        Ok(bytes)
231    }
232    fn signer(&self) -> SignatureKeyPair {
233        SignatureKeyPair::from_raw(
234            SUITE.signature_algorithm(),
235            self.secret.to_vec(),
236            self.grant[101..133].to_vec(),
237        )
238    }
239    pub(super) fn request(&self, package: &KeyPackage) -> Result<Vec<u8>, &'static str> {
240        let proof = self
241            .signer()
242            .sign(&bootstrap::redemption(
243                &GroupId::from_slice(&self.workspace_id()),
244                self.grant[101..133].try_into().unwrap(),
245                package,
246            )?)
247            .map_err(|_| "redemption signing failed")?;
248        let mut bytes = REQUEST.to_vec();
249        bytes.extend(self.grant);
250        bytes.extend(proof);
251        bytes.extend(
252            package
253                .tls_serialize_detached()
254                .map_err(|_| "KeyPackage encoding failed")?,
255        );
256        if bytes.len() > MAX_REQUEST {
257            return Err("admission request exceeds bounds");
258        }
259        Ok(bytes)
260    }
261}
262
263pub struct ValidatedAdmission {
264    pub(super) workspace: [u8; 32],
265    pub(super) checkpoint_digest: [u8; 32],
266    pub(super) issuer: [u8; 32],
267    pub(super) package: KeyPackage,
268    pub(super) authorization: AdmissionAuthorization,
269    digest: [u8; 32],
270    endpoint: [u8; 32],
271}
272pub(super) fn decode_request(
273    provider: &OpenMlsRustCrypto,
274    bytes: &[u8],
275) -> Result<ValidatedAdmission, &'static str> {
276    decode_request_with_grant_check(provider, bytes, true)
277}
278
279fn decode_request_with_grant_check(
280    provider: &OpenMlsRustCrypto,
281    bytes: &[u8],
282    check_grant: bool,
283) -> Result<ValidatedAdmission, &'static str> {
284    if bytes.len() <= REQUEST_HEADER || bytes.len() > MAX_REQUEST || !bytes.starts_with(REQUEST) {
285        return Err("invalid admission request");
286    }
287    let grant = &bytes[5..5 + PUBLIC];
288    if check_grant {
289        verify_grant(provider, grant)?;
290    }
291    let package = KeyPackageIn::tls_deserialize_exact(&bytes[REQUEST_HEADER..])
292        .map_err(|_| "invalid admission KeyPackage")?
293        .validate(provider.crypto(), ProtocolVersion::Mls10)
294        .map_err(|_| "admission KeyPackage invalid or expired")?;
295    if package.ciphersuite() != SUITE {
296        return Err("wrong admission ciphersuite");
297    }
298    let workspace: [u8; 32] = grant[5..37].try_into().unwrap();
299    let authorization = AdmissionAuthorization {
300        invitation_key: grant[101..133].try_into().unwrap(),
301        grant_signature: grant[133..197].try_into().unwrap(),
302        redemption_signature: bytes[5 + PUBLIC..REQUEST_HEADER].try_into().unwrap(),
303    };
304    provider
305        .crypto()
306        .verify_signature(
307            SUITE.signature_algorithm(),
308            &bootstrap::redemption(
309                &GroupId::from_slice(&workspace),
310                &authorization.invitation_key,
311                &package,
312            )?,
313            &authorization.invitation_key,
314            &authorization.redemption_signature,
315        )
316        .map_err(|_| "redemption does not match KeyPackage")?;
317    Ok(ValidatedAdmission {
318        workspace,
319        checkpoint_digest: grant[37..69].try_into().unwrap(),
320        issuer: grant[69..101].try_into().unwrap(),
321        package,
322        authorization,
323        digest: Sha256::digest(bytes).into(),
324        endpoint: [0; 32],
325    })
326}
327
328pub enum AdmissionAssessment {
329    Ready(ValidatedAdmission),
330    ApprovalRequired(ValidatedAdmission),
331    AutomaticApprovalRequired(ValidatedAdmission),
332}
333
334/// Exact response retained with the group transition. A retry must reuse these bytes.
335#[derive(Clone)]
336pub struct AdmissionReply {
337    pub epoch: u64,
338    pub commit: Vec<u8>,
339    pub welcome: Vec<u8>,
340    pub authorization: AdmissionAuthorization,
341}
342#[derive(Clone)]
343pub(super) struct RetainedAdmission {
344    pub digest: [u8; 32],
345    pub endpoint: [u8; 32],
346    pub issuer: [u8; 32],
347    pub reply: RetainedReply,
348}
349
350/// A retained reply. One batch admits up to 16 joiners with one commit and
351/// one Welcome; every joiner's entry points at the same bytes, and a
352/// workspace copy copies pointers only. At 500 members the 16 copies per batch
353/// held 4.1 MB per workspace copy (host measurement, 2026-09-19).
354#[derive(Clone)]
355pub(super) struct RetainedReply {
356    pub epoch: u64,
357    pub commit: std::sync::Arc<[u8]>,
358    pub welcome: std::sync::Arc<[u8]>,
359    pub authorization: AdmissionAuthorization,
360}
361
362impl RetainedReply {
363    fn to_reply(&self) -> AdmissionReply {
364        AdmissionReply {
365            epoch: self.epoch,
366            commit: self.commit.to_vec(),
367            welcome: self.welcome.to_vec(),
368            authorization: self.authorization.clone(),
369        }
370    }
371}
372
373/// Restores share each epoch's commit and Welcome again, as a batch did.
374type SharedReplyParts = (std::sync::Arc<[u8]>, std::sync::Arc<[u8]>);
375
376#[derive(Default)]
377pub(super) struct SharedReplies(std::collections::HashMap<u64, SharedReplyParts>);
378
379impl SharedReplies {
380    pub fn reply(&mut self, epoch: u64, commit: Vec<u8>, welcome: Vec<u8>, authorization: AdmissionAuthorization) -> RetainedReply {
381        let (commit, welcome) = match self.0.get(&epoch) {
382            Some((shared_commit, shared_welcome)) if **shared_commit == *commit && **shared_welcome == *welcome => {
383                (shared_commit.clone(), shared_welcome.clone())
384            }
385            _ => {
386                let pair: SharedReplyParts = (commit.into(), welcome.into());
387                self.0.insert(epoch, pair.clone());
388                pair
389            }
390        };
391        RetainedReply { epoch, commit, welcome, authorization }
392    }
393}
394// Legacy inline snapshot format only; not a membership or incremental-store limit.
395pub(super) const MAX_ADMISSIONS: usize = 16;
396
397/// Provisional membership transition. The host must atomically retain the new
398/// workspace AND response/history before adopting it or sending these messages.
399pub struct PreparedAdmission {
400    pub workspace: Workspace,
401    pub commit: Vec<u8>,
402    pub welcome: Vec<u8>,
403    pub authorization: AdmissionAuthorization,
404}
405
406/// One MLS transition for a bounded set of independently authenticated joins.
407/// Each retained reply points at the same commit and Welcome.
408pub struct PreparedAdmissionBatch {
409    pub workspace: Workspace,
410    pub commit: Vec<u8>,
411    pub welcome: Vec<u8>,
412    pub replies: Vec<AdmissionReply>,
413}
414impl Workspace {
415    /// Serve only the exact current checkpoint to a holder of this invitation.
416    pub fn checkpoint_for_invitation(
417        &self,
418        requester: [u8; 32],
419        responder: [u8; 32],
420        request: &[u8],
421    ) -> Result<Vec<u8>, &'static str> {
422        if request.len() != CHECKPOINT_REQUEST_SIZE
423            || requester == [0; 32]
424            || responder != self.endpoint
425            || requester == responder
426        {
427            return Err("invalid invitation checkpoint request");
428        }
429        let (grant, signature) = request.split_at(PUBLIC);
430        verify_grant(&self.provider, grant)?;
431        self.provider
432            .crypto()
433            .verify_signature(
434                SUITE.signature_algorithm(),
435                &checkpoint_request_message(grant, requester, responder),
436                &grant[101..133],
437                signature,
438            )
439            .map_err(|_| "invalid invitation checkpoint proof")?;
440        if grant[5..37] != self.id() {
441            return Err("invitation belongs to another workspace");
442        }
443        let digest: [u8; 32] = grant[37..69].try_into().unwrap();
444        let checkpoint = match self
445            .join_history
446            .as_ref()
447            .filter(|history| <[u8; 32]>::from(Sha256::digest(&history.checkpoint)) == digest)
448        {
449            Some(history) => {
450                history.verify(self)?;
451                history.checkpoint.clone()
452            }
453            None => match self
454                .invitation_checkpoints
455                .iter()
456                .find(|saved| saved.grant.as_slice() == grant)
457            {
458                Some(saved) => saved.checkpoint.clone(),
459                None => self.join_checkpoint()?,
460            },
461        };
462        let proof = JoinProof::from_trusted_checkpoint(self.id(), digest, &checkpoint)?;
463        if !proof.authorizes_issuer(&grant[69..101])? {
464            return Err("invitation issuer is not a checkpoint administrator");
465        }
466        Ok(checkpoint)
467    }
468
469    /// Verify the invitation holder and reconstruct the exact accepted branch
470    /// from its pinned checkpoint before admitting or replying. Missing history
471    /// is an error; it must not become a new Add with an unusable Welcome.
472    pub fn admission_history(
473        &self,
474        remote_endpoint: [u8; 32],
475        request: &[u8],
476        checkpoint: &[u8],
477    ) -> Result<Vec<(AdmissionAuthorization, Vec<u8>)>, &'static str> {
478        self.membership_history(remote_endpoint, request, checkpoint)?
479            .into_iter()
480            .map(|(auth, commit)| match auth {
481                MembershipAuthorization::Admission(auth) => Ok((auth, commit)),
482                MembershipAuthorization::AdmissionBatch(_) => {
483                    Err("admission history requires membership support")
484                }
485                MembershipAuthorization::Management(_) => {
486                    Err("membership history requires management support")
487                }
488            })
489            .collect()
490    }
491
492    /// Everything an arriving admission must satisfy on its own account:
493    /// a decodable, signed request, live invitation controls, the pinned
494    /// workspace, the bound endpoint and a current administrator as issuer.
495    /// None of this is ever reused between requests.
496    fn authorize_history_request(
497        &self,
498        remote_endpoint: [u8; 32],
499        request: &[u8],
500    ) -> Result<ValidatedAdmission, &'static str> {
501        let parsed = decode_request(&self.provider, request)?;
502        if self.retained_admission(remote_endpoint, request)?.is_none() {
503            super::invitation_controls::check(
504                self.group.extensions(),
505                parsed.authorization.invitation_key,
506                Some(super::invitation_controls::now()?),
507                &parsed.package,
508            )?;
509        }
510        if parsed.workspace != self.id()
511            || bootstrap::binding(parsed.package.leaf_node().credential())?.1 != remote_endpoint
512            || !bootstrap::authority(self.group.extensions())?.contains(&parsed.issuer.to_vec())
513        {
514            return Err("unauthorized admission history request");
515        }
516        Ok(parsed)
517    }
518
519    /// Whether this admission's pinned history can be served, without building
520    /// the history. Admission intake only needs the answer; only the reply path
521    /// needs the transitions, so intake does not pay to materialize and discard
522    /// them.
523    pub fn check_membership_history(
524        &self,
525        remote_endpoint: [u8; 32],
526        request: &[u8],
527        checkpoint: &[u8],
528    ) -> Result<(), &'static str> {
529        let parsed = self.authorize_history_request(remote_endpoint, request)?;
530        if let Some(start) = self.retained_checkpoint_start(&parsed, checkpoint)?
531            && self.accepted_range(start).is_some()
532        {
533            return Ok(());
534        }
535        // Not retained, or the records do not cover the range: the only honest
536        // answer is the full one. Authorization is not repeated for it.
537        self.authorized_membership_history(&parsed, checkpoint)
538            .map(|_| ())
539    }
540
541    pub fn membership_history(
542        &self,
543        remote_endpoint: [u8; 32],
544        request: &[u8],
545        checkpoint: &[u8],
546    ) -> Result<Vec<(MembershipAuthorization, Vec<u8>)>, &'static str> {
547        let request = self.authorize_history_request(remote_endpoint, request)?;
548        self.authorized_membership_history(&request, checkpoint)
549    }
550
551    fn authorized_membership_history(
552        &self,
553        request: &ValidatedAdmission,
554        checkpoint: &[u8],
555    ) -> Result<Vec<(MembershipAuthorization, Vec<u8>)>, &'static str> {
556        // This owner issued this checkpoint, retained it with its authenticated
557        // invitation transition, and proved it an ancestor of the accepted
558        // branch then and again at every restore. Its own branch only extends,
559        // so that proof stays good; replaying it commit by commit for every
560        // arriving request is redundant work, and the cost of that replay grows
561        // with the branch. Everything above this point -- the request decode,
562        // invitation controls, issuer authority and endpoint binding -- is
563        // per-request and is not skipped.
564        if let Some(steps) = self.retained_checkpoint_steps(request, checkpoint)? {
565            return Ok(steps);
566        }
567        let mut proof = super::MembershipVerifier::from_trusted_checkpoint(
568            self.id(),
569            request.checkpoint_digest,
570            checkpoint,
571        )?;
572        if !proof.authorizes_issuer(&request.issuer)? || proof.epoch() > self.epoch() {
573            return Err("invitation checkpoint is not an authorized ancestor");
574        }
575        // Stored history is verified at restore and extended only with an
576        // accepted transition. When the requester pins that exact checkpoint,
577        // replaying the owner's entire branch on every request is redundant.
578        if let Some(history) = &self.join_history
579            && history.checkpoint == checkpoint
580        {
581            return Ok(history.steps.clone());
582        }
583        self.advance_membership_proof(&mut proof)
584    }
585
586    /// The epoch a joiner pinning this checkpoint must be advanced from, when
587    /// the checkpoint is one this owner issued and retained itself. `None`
588    /// means it is not, so the caller falls back to full verification.
589    fn retained_checkpoint_start(
590        &self,
591        request: &ValidatedAdmission,
592        checkpoint: &[u8],
593    ) -> Result<Option<u64>, &'static str> {
594        let Some(saved) = self.invitation_checkpoints.iter().find(|saved| {
595            saved.checkpoint == checkpoint
596                && <[u8; 32]>::from(Sha256::digest(&saved.checkpoint))
597                    == request.checkpoint_digest
598                && saved.grant[69..101] == request.issuer
599                && saved.grant[101..133] == request.authorization.invitation_key
600        }) else {
601            return Ok(None);
602        };
603        let start = checkpoint_epoch(&saved.checkpoint)?;
604        if start > self.epoch() {
605            return Err("invitation checkpoint is not an authorized ancestor");
606        }
607        Ok(Some(start))
608    }
609
610    /// Borrow this owner's accepted transition for every epoch from `start` to
611    /// the head, in order. Nothing is copied: the result points into the
612    /// owner's own records, so a caller that only needs to know the range
613    /// exists pays no allocation for the transitions themselves. `None` means
614    /// the records are incomplete or disagree about an epoch in that range, so
615    /// the caller falls back to full verification rather than guessing.
616    fn accepted_range(&self, start: u64) -> Option<Vec<AcceptedStep<'_>>> {
617        let span = usize::try_from(self.epoch().checked_sub(start)?).ok()?;
618        let mut slots: Vec<Option<AcceptedStep<'_>>> = Vec::new();
619        slots.resize_with(span, || None);
620        // The retained join history is the authoritative ordered log, so it is
621        // placed first; retained admissions only fill epochs it does not cover.
622        if let Some(history) = &self.join_history {
623            for step in &history.steps {
624                place_accepted(&mut slots, start, AcceptedStep::History(step))?;
625            }
626        }
627        for admission in &self.admissions {
628            place_accepted(&mut slots, start, AcceptedStep::Admission(admission))?;
629        }
630        slots.into_iter().collect()
631    }
632
633    /// Transitions from a checkpoint this owner issued and retained itself,
634    /// taken from its own accepted records rather than replayed. Only the
635    /// requested range is copied, and only for a caller that needs to send it.
636    fn retained_checkpoint_steps(
637        &self,
638        request: &ValidatedAdmission,
639        checkpoint: &[u8],
640    ) -> Result<Option<MembershipSteps>, &'static str> {
641        let Some(start) = self.retained_checkpoint_start(request, checkpoint)? else {
642            return Ok(None);
643        };
644        Ok(self
645            .accepted_range(start)
646            .map(|range| range.iter().map(AcceptedStep::to_step).collect()))
647    }
648
649    fn advance_membership_proof(
650        &self,
651        proof: &mut super::MembershipVerifier,
652    ) -> Result<Vec<(MembershipAuthorization, Vec<u8>)>, &'static str> {
653        if proof.epoch() > self.epoch() {
654            return Err("invitation checkpoint is not an authorized ancestor");
655        }
656        let mut candidates = match &self.join_history {
657            Some(history) => history.steps.clone(),
658            None => Vec::new(),
659        };
660        candidates.extend(self.admissions.iter().map(|a| {
661            (
662                MembershipAuthorization::Admission(a.reply.authorization.clone()),
663                a.reply.commit.to_vec(),
664            )
665        }));
666        let mut steps = Vec::new();
667        while proof.epoch() < self.epoch() {
668            let next = candidates
669                .iter()
670                .find(|(_, commit)| {
671                    MlsMessageIn::tls_deserialize_exact(commit)
672                        .ok()
673                        .and_then(|m| m.try_into_protocol_message().ok())
674                        .is_some_and(|m| m.epoch().as_u64() == proof.epoch())
675                })
676                .ok_or("invitation history unavailable")?;
677            proof.apply_transition(&next.0, &next.1)?;
678            steps.push(next.clone());
679        }
680        if !proof.matches_workspace(self)? {
681            return Err("invitation checkpoint conflicts with accepted branch");
682        }
683        Ok(steps)
684    }
685
686    /// Look up a byte-identical retry from the authenticated endpoint. Only use
687    /// this on the adopted, durably saved owner; this method does not perform I/O.
688    pub fn retained_admission(
689        &self,
690        remote_endpoint: [u8; 32],
691        request: &[u8],
692    ) -> Result<Option<AdmissionReply>, &'static str> {
693        if request.len() <= REQUEST_HEADER || request.len() > MAX_REQUEST {
694            return Err("invalid admission request size");
695        }
696        let digest: [u8; 32] = Sha256::digest(request).into();
697        let Some(entry) = self.admissions.iter().find(|entry| entry.digest == digest) else {
698            return Ok(None);
699        };
700        if entry.endpoint != remote_endpoint {
701            return Err("admission retry endpoint mismatch");
702        }
703        if !bootstrap::authority(self.group.extensions())?.contains(&entry.issuer.to_vec()) {
704            return Err("invitation issuer is no longer an administrator");
705        }
706        if !self.group.members().any(|member| {
707            bootstrap::binding(&member.credential)
708                .is_ok_and(|(_, endpoint)| endpoint == remote_endpoint)
709        }) {
710            return Err("admitted member is no longer authorized");
711        }
712        Ok(Some(entry.reply.to_reply()))
713    }
714
715    /// Returns a secret bearer token owner and the public checkpoint it pins.
716    /// Checkpoint distribution/retention is part of invitation handoff.
717    pub fn issue_invitation(&self) -> Result<(Invitation, Vec<u8>), &'static str> {
718        let checkpoint = self.join_checkpoint()?;
719        let (private, public) = self
720            .provider
721            .crypto()
722            .signature_key_gen(SUITE.signature_algorithm())
723            .map_err(|_| "invitation randomness failed")?;
724        let private = Zeroizing::new(private);
725        let mut grant = [0; PUBLIC];
726        grant[..5].copy_from_slice(TOKEN);
727        grant[5..37].copy_from_slice(&self.id());
728        grant[37..69].copy_from_slice(&Sha256::digest(&checkpoint));
729        grant[69..101].copy_from_slice(self._signer.public());
730        grant[101..133].copy_from_slice(&public);
731        let signature = self
732            ._signer
733            .sign(&bootstrap::grant(
734                self.group.group_id(),
735                public
736                    .as_slice()
737                    .try_into()
738                    .map_err(|_| "invalid invitation public key")?,
739            ))
740            .map_err(|_| "invitation signing failed")?;
741        grant[133..197].copy_from_slice(&signature);
742        let signature = self
743            ._signer
744            .sign(&binding_message(&grant))
745            .map_err(|_| "checkpoint signing failed")?;
746        grant[197..261].copy_from_slice(&signature);
747        Ok((
748            Invitation {
749                grant,
750                secret: Zeroizing::new(
751                    private
752                        .as_slice()
753                        .try_into()
754                        .map_err(|_| "invalid invitation private key")?,
755                ),
756            },
757            checkpoint,
758        ))
759    }
760    /// Register a reusable link in shared policy before releasing its bearer
761    /// token. The caller must persist the returned workspace before sharing.
762    pub fn prepare_invitation(
763        &self,
764        expires_at: u64,
765        personal: bool,
766        automatic: bool,
767    ) -> Result<(super::PreparedManagement, Invitation, Vec<u8>), &'static str> {
768        self.prepare_invitation_mode(expires_at, personal, automatic, false)
769    }
770
771    pub fn prepare_request_invitation(
772        &self,
773        expires_at: u64,
774    ) -> Result<(super::PreparedManagement, Invitation, Vec<u8>), &'static str> {
775        self.prepare_invitation_mode(expires_at, true, false, true)
776    }
777
778    fn prepare_invitation_mode(
779        &self,
780        expires_at: u64,
781        personal: bool,
782        automatic: bool,
783        request_access: bool,
784    ) -> Result<(super::PreparedManagement, Invitation, Vec<u8>), &'static str> {
785        if expires_at != 0 && expires_at <= super::invitation_controls::now()? {
786            return Err("Choose an expiry in the future.");
787        }
788        let (mut invitation, _) = self.issue_invitation()?;
789        let key = invitation.grant[101..133].try_into().unwrap();
790        if automatic && !personal {
791            return Err("Only a personal invitation can use automatic approval.");
792        }
793        let action = if request_access {
794            super::ManagementAction::CreateRequestInvitation(key, expires_at)
795        } else if automatic {
796            super::ManagementAction::CreateAutomaticInvitation(key, expires_at)
797        } else {
798            super::ManagementAction::CreateInvitation(key, expires_at, personal)
799        };
800        let mut prepared = self.prepare_management(action)?;
801        let checkpoint = prepared.workspace.join_checkpoint()?;
802        invitation.grant[37..69].copy_from_slice(&Sha256::digest(&checkpoint));
803        let binding = binding_message(&invitation.grant);
804        invitation.grant[197..261].copy_from_slice(
805            &self
806                ._signer
807                .sign(&binding)
808                .map_err(|_| "checkpoint signing failed")?,
809        );
810        prepared.workspace.retain_invitation_checkpoint(
811            action,
812            invitation.public_grant(),
813            &checkpoint,
814        )?;
815        Ok((prepared, invitation, checkpoint))
816    }
817
818    /// Retain one admin-signed public checkpoint carried with its authenticated
819    /// invitation-management transition. The bearer secret is never retained.
820    pub fn retain_invitation_checkpoint(
821        &mut self,
822        action: super::ManagementAction,
823        grant: &[u8],
824        checkpoint: &[u8],
825    ) -> Result<(), &'static str> {
826        self.prune_invitation_checkpoints()?;
827        let key = match action {
828            super::ManagementAction::CreateInvitation(key, ..)
829            | super::ManagementAction::CreateRequestInvitation(key, ..)
830            | super::ManagementAction::CreateAutomaticInvitation(key, ..) => key,
831            _ => return Err("checkpoint requires an invitation creation"),
832        };
833        verify_grant(&self.provider, grant)?;
834        if grant[5..37] != self.id() || grant[101..133] != key {
835            return Err("invitation checkpoint does not match action");
836        }
837        let digest: [u8; 32] = grant[37..69].try_into().unwrap();
838        let proof = JoinProof::from_trusted_checkpoint(self.id(), digest, checkpoint)?;
839        if !proof.authorizes_issuer(&grant[69..101])? || !proof.matches_workspace(self)? {
840            return Err("invitation checkpoint does not match accepted workspace");
841        }
842        if self
843            .invitation_checkpoints
844            .iter()
845            .any(|saved| saved.grant.as_slice() == grant)
846        {
847            return Ok(());
848        }
849        let total = self
850            .invitation_checkpoints
851            .iter()
852            .try_fold(checkpoint.len(), |sum, saved| {
853                sum.checked_add(saved.checkpoint.len())
854            })
855            .ok_or("retained invitation checkpoints exceed bounds")?;
856        if self.invitation_checkpoints.len() >= MAX_RETAINED_CHECKPOINTS
857            || total > MAX_RETAINED_CHECKPOINT_BYTES
858        {
859            return Err("retained invitation checkpoints exceed bounds");
860        }
861        self.invitation_checkpoints
862            .push(RetainedInvitationCheckpoint {
863                grant: grant
864                    .try_into()
865                    .map_err(|_| "invalid invitation grant size")?,
866                checkpoint: checkpoint.to_vec(),
867            });
868        Ok(())
869    }
870
871    pub(super) fn prune_invitation_checkpoints(&mut self) -> Result<(), &'static str> {
872        let now = super::invitation_controls::now()?;
873        let (_, controls) = self.invitation_controls()?;
874        self.invitation_checkpoints.retain(|saved| {
875            let key: [u8; 32] = saved.grant[101..133].try_into().unwrap();
876            controls.iter().any(|control| {
877                control.key == key
878                    && control.enabled
879                    && (control.expires_at == 0 || control.expires_at > now)
880            })
881        });
882        Ok(())
883    }
884
885    pub(super) fn verify_retained_invitation_checkpoints(&self) -> Result<(), &'static str> {
886        if self.invitation_checkpoints.len() > MAX_RETAINED_CHECKPOINTS
887            || self
888                .invitation_checkpoints
889                .iter()
890                .try_fold(0usize, |sum, saved| sum.checked_add(saved.checkpoint.len()))
891                .is_none_or(|total| total > MAX_RETAINED_CHECKPOINT_BYTES)
892        {
893            return Err("retained invitation checkpoints exceed bounds");
894        }
895        if self.invitation_checkpoints.is_empty() {
896            return Ok(());
897        }
898        let (_, controls) = self.invitation_controls()?;
899        for saved in &self.invitation_checkpoints {
900            verify_grant(&self.provider, &saved.grant)?;
901            let key: [u8; 32] = saved.grant[101..133].try_into().unwrap();
902            if saved.grant[5..37] != self.id() || !controls.iter().any(|control| control.key == key)
903            {
904                return Err("retained invitation checkpoint is not registered");
905            }
906            let digest: [u8; 32] = saved.grant[37..69].try_into().unwrap();
907            let mut proof = super::MembershipVerifier::from_trusted_checkpoint(
908                self.id(),
909                digest,
910                &saved.checkpoint,
911            )?;
912            if !proof.authorizes_issuer(&saved.grant[69..101])?
913                || self.advance_membership_proof(&mut proof).is_err()
914            {
915                return Err("retained invitation checkpoint does not match workspace");
916            }
917        }
918        Ok(())
919    }
920
921    pub fn retained_invitation_checkpoint(
922        &self,
923        action: &super::ManagementAction,
924    ) -> Option<(&[u8], &[u8])> {
925        let key = match action {
926            super::ManagementAction::CreateInvitation(key, ..)
927            | super::ManagementAction::CreateRequestInvitation(key, ..)
928            | super::ManagementAction::CreateAutomaticInvitation(key, ..) => key,
929            _ => return None,
930        };
931        self.invitation_checkpoints
932            .iter()
933            .find(|saved| saved.grant[101..133] == *key)
934            .map(|saved| (saved.grant.as_slice(), saved.checkpoint.as_slice()))
935    }
936
937    pub fn prepare_invitation_approval(
938        &self,
939        bytes: &[u8],
940    ) -> Result<super::PreparedManagement, &'static str> {
941        let request = decode_request(&self.provider, bytes)?;
942        if request.workspace != self.id() {
943            return Err("Join request belongs to another workspace.");
944        }
945        let (_, controls) = self.invitation_controls()?;
946        let control = controls
947            .iter()
948            .find(|c| c.key == request.authorization.invitation_key)
949            .ok_or("unknown invitation")?;
950        if control.expires_at != 0 && super::invitation_controls::now()? >= control.expires_at {
951            return Err("This invitation has expired.");
952        }
953        self.prepare_management(super::ManagementAction::ApproveInvitation(
954            control.key,
955            super::invitation_controls::package_digest(&request.package)?,
956        ))
957    }
958
959    pub fn prepare_invitation_decline(
960        &self,
961        bytes: &[u8],
962    ) -> Result<super::PreparedManagement, &'static str> {
963        let request = decode_request(&self.provider, bytes)?;
964        if request.workspace != self.id() {
965            return Err("Join request belongs to another workspace.");
966        }
967        let (_, controls) = self.invitation_controls()?;
968        let control = controls
969            .iter()
970            .find(|c| c.key == request.authorization.invitation_key)
971            .ok_or("unknown invitation")?;
972        if !control.personal {
973            return Err("Only personal invitation requests can be declined.");
974        }
975        self.prepare_management(if control.request_access() {
976            super::ManagementAction::DeclineInvitationRequest(
977                control.key,
978                super::invitation_controls::package_digest(&request.package)?,
979            )
980        } else {
981            super::ManagementAction::DisableInvitation(control.key)
982        })
983    }
984
985    /// remote_endpoint MUST come from authenticated transport, not request JSON.
986    /// The original owner is unchanged on both success and rejection.
987    /// One retained update for an authenticated endpoint. Current members may
988    /// retrieve history; a former member may retrieve only its own exact removal
989    /// from a parent state that proves its binding, never subsequent roster data.
990    pub fn membership_update_for(
991        &self,
992        endpoint: [u8; 32],
993        after: u64,
994    ) -> Result<Option<(MembershipAuthorization, Vec<u8>)>, &'static str> {
995        let current = self.member_id_for_endpoint(endpoint).is_ok();
996        if let Some(history) = &self.join_history {
997            if current {
998                // Restored history is verified once and extended only by
999                // accepted transitions. Index it directly instead of replaying
1000                // the full history for every step in a range catch-up.
1001                let start = checkpoint_epoch(&history.checkpoint)?;
1002                if let Some((auth, commit)) = after
1003                    .checked_sub(start)
1004                    .and_then(|offset| usize::try_from(offset).ok())
1005                    .and_then(|index| history.steps.get(index))
1006                {
1007                    return Ok(Some((auth.clone(), commit.clone())));
1008                }
1009            } else {
1010                let mut proof = history.verifier(self.id)?;
1011                for (auth, commit) in &history.steps {
1012                    if proof.epoch() == after {
1013                        let terminal = match auth {
1014                            MembershipAuthorization::Management(
1015                                super::ManagementAction::Remove(id)
1016                                | super::ManagementAction::Leave(id, _),
1017                            ) => proof.member_for_endpoint(endpoint)? == Some(*id),
1018                            _ => false,
1019                        };
1020                        if terminal {
1021                            return Ok(Some((auth.clone(), commit.clone())));
1022                        }
1023                        return Ok(None);
1024                    }
1025                    proof.apply_transition(auth, commit)?;
1026                }
1027            }
1028        }
1029        Ok(if current {
1030            self.admission_update_after(after)
1031        } else {
1032            None
1033        })
1034    }
1035
1036    /// Return the next locally retained admission for an existing member's epoch.
1037    /// None means this owner has no such retained step, not that the requester is current.
1038    /// The host must authorize the requester before sharing workspace metadata.
1039    pub fn admission_update_after(
1040        &self,
1041        epoch: u64,
1042    ) -> Option<(MembershipAuthorization, Vec<u8>)> {
1043        let next = epoch.checked_add(1)?;
1044        let entries: Vec<_> = self
1045            .admissions
1046            .iter()
1047            .filter(|entry| entry.reply.epoch == next)
1048            .collect();
1049        let first = entries.first()?;
1050        let authorization = if entries.len() == 1 {
1051            MembershipAuthorization::Admission(first.reply.authorization.clone())
1052        } else {
1053            MembershipAuthorization::AdmissionBatch(
1054                entries
1055                    .iter()
1056                    .map(|entry| entry.reply.authorization.clone())
1057                    .collect(),
1058            )
1059        };
1060        Some((authorization, first.reply.commit.to_vec()))
1061    }
1062
1063    /// Prepare an existing member's next epoch from an authorized ordinary-member Add.
1064    /// Leaves this owner unchanged on success or failure. The caller must save the
1065    /// returned owner before adoption and resolve old-epoch pending delivery explicitly.
1066    /// This is not a policy-change, removal or concurrent-branch merge operation.
1067    pub fn prepare_admission_update(
1068        &self,
1069        authorization: &AdmissionAuthorization,
1070        commit: &[u8],
1071    ) -> Result<Workspace, &'static str> {
1072        self.prepare_admission_batch_update(std::slice::from_ref(authorization), commit)
1073    }
1074
1075    /// Prepare an existing member's next epoch from a bounded batch Add.
1076    pub fn prepare_admission_batch_update(
1077        &self,
1078        authorizations: &[AdmissionAuthorization],
1079        commit: &[u8],
1080    ) -> Result<Workspace, &'static str> {
1081        if authorizations.is_empty() || authorizations.len() > super::MAX_ADMISSION_BATCH {
1082            return Err("invalid admission batch size");
1083        }
1084        let authorization = if let [authorization] = authorizations {
1085            MembershipAuthorization::Admission(authorization.clone())
1086        } else {
1087            MembershipAuthorization::AdmissionBatch(authorizations.to_vec())
1088        };
1089        let mut proof = super::MembershipVerifier::from_workspace(self)?;
1090        proof.apply_transition(&authorization, commit)?;
1091        let provider = storage::copy_provider(&self.provider)?;
1092        let mut group = MlsGroup::load(provider.storage(), &GroupId::from_slice(&self.id()))
1093            .map_err(|_| "group copy failed")?
1094            .ok_or("missing group copy")?;
1095        let signer = SignatureKeyPair::read(
1096            provider.storage(),
1097            self._signer.public(),
1098            SUITE.signature_algorithm(),
1099        )
1100        .ok_or("missing copied signer")?;
1101        let message = MlsMessageIn::tls_deserialize_exact(commit)
1102            .map_err(|_| "invalid admission commit")?
1103            .try_into_protocol_message()
1104            .map_err(|_| "expected admission commit")?;
1105        let processed = group
1106            .process_message(&provider, message)
1107            .map_err(|_| "admission update authentication failed")?;
1108        let ProcessedMessageContent::StagedCommitMessage(staged) = processed.into_content() else {
1109            return Err("not an admission commit");
1110        };
1111        group
1112            .merge_staged_commit(&provider, *staged)
1113            .map_err(|_| "admission update merge failed")?;
1114        let updated = Workspace {
1115            provider,
1116            _signer: signer,
1117            group,
1118            id: self.id,
1119            endpoint: self.endpoint,
1120            member: self.member.clone(),
1121            admissions: self.admissions.clone(),
1122            invitation_checkpoints: self.invitation_checkpoints.clone(),
1123            // Received Adds have no local Welcome/retry entry to retain their
1124            // commit. Keep the verified history even on a creator's first update.
1125            join_history: Some(self.append_history(authorization, commit)?),
1126        };
1127        if !proof.matches_workspace(&updated)? {
1128            return Err("admission update does not match authorized branch");
1129        }
1130        Ok(updated)
1131    }
1132
1133    fn check_validated_admission(
1134        &self,
1135        remote_endpoint: [u8; 32],
1136        request: &ValidatedAdmission,
1137    ) -> Result<(), &'static str> {
1138        if request.workspace != self.id() {
1139            return Err("admission belongs to another workspace");
1140        }
1141        super::invitation_controls::check(
1142            self.group.extensions(),
1143            request.authorization.invitation_key,
1144            Some(super::invitation_controls::now()?),
1145            &request.package,
1146        )?;
1147        if !bootstrap::authority(self.group.extensions())?.contains(&request.issuer.to_vec()) {
1148            return Err("invitation issuer is no longer an administrator");
1149        }
1150        let (member_id, endpoint) = bootstrap::binding(request.package.leaf_node().credential())?;
1151        if endpoint != remote_endpoint {
1152            return Err("admission endpoint mismatch");
1153        }
1154        for member in self.group.members() {
1155            let existing = bootstrap::binding(&member.credential)?;
1156            if existing.0 == member_id || existing.1 == endpoint {
1157                return Err("member already admitted");
1158            }
1159        }
1160        Ok(())
1161    }
1162
1163    /// Authenticate and classify a request without creating an MLS commit.
1164    /// Hosts can retain this result while an owner queues the transition.
1165    pub fn assess_admission(
1166        &self,
1167        remote_endpoint: [u8; 32],
1168        bytes: &[u8],
1169    ) -> Result<AdmissionAssessment, &'static str> {
1170        let trusted_grant = bytes
1171            .get(5..5 + PUBLIC)
1172            .is_some_and(|grant| {
1173                self.invitation_checkpoints
1174                    .iter()
1175                    .any(|saved| saved.grant.as_slice() == grant)
1176            });
1177        let mut request = decode_request_with_grant_check(&self.provider, bytes, !trusted_grant)?;
1178        request.endpoint = remote_endpoint;
1179        if request.workspace != self.id() {
1180            return Err("admission belongs to another workspace");
1181        }
1182        if let Err(error) = self.check_validated_admission(remote_endpoint, &request) {
1183            return match error {
1184                super::INVITATION_APPROVAL_REQUIRED => Ok(AdmissionAssessment::ApprovalRequired(request)),
1185                super::INVITATION_AUTOMATIC_APPROVAL_REQUIRED => {
1186                    Ok(AdmissionAssessment::AutomaticApprovalRequired(request))
1187                }
1188                _ => Err(error),
1189            };
1190        }
1191        Ok(AdmissionAssessment::Ready(request))
1192    }
1193
1194    pub fn prepare_admission(
1195        &self,
1196        remote_endpoint: [u8; 32],
1197        bytes: &[u8],
1198    ) -> Result<PreparedAdmission, &'static str> {
1199        let request = match self.assess_admission(remote_endpoint, bytes)? {
1200            AdmissionAssessment::Ready(request) => request,
1201            AdmissionAssessment::ApprovalRequired(_) => {
1202                return Err(super::INVITATION_APPROVAL_REQUIRED)
1203            }
1204            AdmissionAssessment::AutomaticApprovalRequired(_) => {
1205                return Err(super::INVITATION_AUTOMATIC_APPROVAL_REQUIRED)
1206            }
1207        };
1208        self.prepare_validated_admission(remote_endpoint, bytes, &request)
1209    }
1210
1211    /// Prepare the commit from a request already authenticated by
1212    /// [`Workspace::assess_admission`]. The current workspace policy is still
1213    /// checked because a queued invitation may expire or be consumed first.
1214    pub fn prepare_validated_admission(
1215        &self,
1216        remote_endpoint: [u8; 32],
1217        bytes: &[u8],
1218        request: &ValidatedAdmission,
1219    ) -> Result<PreparedAdmission, &'static str> {
1220        let prepared = self.prepare_validated_admission_batch(&[(remote_endpoint, bytes, request)])?;
1221        let reply = prepared.replies.into_iter().next().unwrap();
1222        Ok(PreparedAdmission {
1223            workspace: prepared.workspace,
1224            commit: prepared.commit,
1225            welcome: prepared.welcome,
1226            authorization: reply.authorization,
1227        })
1228    }
1229
1230    /// Prepare one bounded MLS transition for already authenticated requests.
1231    /// Authentication and policy checks happen once per request; MLS state is
1232    /// cloned and advanced once for the whole batch.
1233    pub fn prepare_validated_admission_batch(
1234        &self,
1235        admissions: &[([u8; 32], &[u8], &ValidatedAdmission)],
1236    ) -> Result<PreparedAdmissionBatch, &'static str> {
1237        if admissions.is_empty() || admissions.len() > super::MAX_ADMISSION_BATCH {
1238            return Err("invalid admission batch size");
1239        }
1240        let profile = std::env::var_os("ARACHNE_PROFILE_ADMISSION").is_some();
1241        let profile_started = std::time::Instant::now();
1242        let mut bindings = BTreeSet::new();
1243        let mut packages = Vec::with_capacity(admissions.len());
1244        for (remote_endpoint, bytes, request) in admissions {
1245            let digest: [u8; 32] = Sha256::digest(bytes).into();
1246            if request.endpoint != *remote_endpoint || request.digest != digest {
1247                return Err("validated admission does not match request");
1248            }
1249            self.check_validated_admission(*remote_endpoint, request)?;
1250            if !bindings.insert(bootstrap::binding(request.package.leaf_node().credential())?) {
1251                return Err("duplicate member binding");
1252            }
1253            packages.push(request.package.clone());
1254        }
1255        let provider = storage::copy_provider(&self.provider)?;
1256        let mut group = MlsGroup::load(provider.storage(), &GroupId::from_slice(&self.id()))
1257            .map_err(|_| "group copy failed")?
1258            .ok_or("missing group copy")?;
1259        let signer = SignatureKeyPair::read(
1260            provider.storage(),
1261            self._signer.public(),
1262            SUITE.signature_algorithm(),
1263        )
1264        .ok_or("missing copied signer")?;
1265        // Older saved groups need public handshakes for the admission proof;
1266        // this configuration change is confined to the provisional transition.
1267        let config = MlsGroupJoinConfig::builder()
1268            .wire_format_policy(PURE_PLAINTEXT_WIRE_FORMAT_POLICY)
1269            .use_ratchet_tree_extension(false)
1270            .build();
1271        group
1272            .set_configuration(provider.storage(), &config)
1273            .map_err(|_| "admission configuration failed")?;
1274        let (commit, welcome, _) = group
1275            .add_members_without_update(&provider, &signer, &packages)
1276            .map_err(|_| "admission preparation failed")?;
1277        let commit = commit.to_bytes().map_err(|_| "commit encoding failed")?;
1278        let welcome = welcome.to_bytes().map_err(|_| "Welcome encoding failed")?;
1279        if welcome.len() > 64 * 1024 {
1280            if profile {
1281                eprintln!("admission_profile welcome_len={}", welcome.len());
1282            }
1283            return Err("Welcome exceeds bounds");
1284        }
1285        group
1286            .merge_pending_commit(&provider)
1287            .map_err(|_| "admission merge failed")?;
1288        let epoch = group.epoch().as_u64();
1289        let replies: Vec<_> = admissions
1290            .iter()
1291            .map(|(_, _, request)| AdmissionReply {
1292                epoch,
1293                commit: commit.clone(),
1294                welcome: welcome.clone(),
1295                authorization: request.authorization.clone(),
1296            })
1297            .collect();
1298        let mut retained_admissions = self.admissions.clone();
1299        let shared_commit: std::sync::Arc<[u8]> = commit.as_slice().into();
1300        let shared_welcome: std::sync::Arc<[u8]> = welcome.as_slice().into();
1301        for ((remote_endpoint, bytes, request), reply) in admissions.iter().zip(&replies) {
1302            retained_admissions.push(RetainedAdmission {
1303                digest: Sha256::digest(bytes).into(),
1304                endpoint: *remote_endpoint,
1305                issuer: request.issuer,
1306                reply: RetainedReply {
1307                    epoch: reply.epoch,
1308                    commit: shared_commit.clone(),
1309                    welcome: shared_welcome.clone(),
1310                    authorization: reply.authorization.clone(),
1311                },
1312            });
1313        }
1314        let authorizations: Vec<_> = replies
1315            .iter()
1316            .map(|reply| reply.authorization.clone())
1317            .collect();
1318        let authorization = if let [authorization] = authorizations.as_slice() {
1319            MembershipAuthorization::Admission(authorization.clone())
1320        } else {
1321            MembershipAuthorization::AdmissionBatch(authorizations)
1322        };
1323        let join_history = if replies.len() == 1 {
1324            self.join_history
1325                .as_ref()
1326                .map(|_| self.append_history(authorization.clone(), &commit))
1327                .transpose()?
1328        } else {
1329            Some(self.append_history(authorization, &commit)?)
1330        };
1331        if profile {
1332            eprintln!(
1333                "admission_profile batch={} commit_ms={}",
1334                replies.len(),
1335                profile_started.elapsed().as_millis()
1336            );
1337        }
1338        Ok(PreparedAdmissionBatch {
1339            workspace: Workspace {
1340                provider,
1341                _signer: signer,
1342                group,
1343                id: self.id,
1344                endpoint: self.endpoint,
1345                member: self.member.clone(),
1346                admissions: retained_admissions,
1347                invitation_checkpoints: self.invitation_checkpoints.clone(),
1348                join_history,
1349            },
1350            commit,
1351            welcome,
1352            replies,
1353        })
1354    }
1355}
1356
1357#[test]
1358fn checkpoint_request_keeps_the_bearer_secret_local_and_binds_both_endpoints() {
1359    let admin = Workspace::create([1; 32], "Coordinator").unwrap();
1360    let (invitation, checkpoint) = admin.issue_invitation().unwrap();
1361    let token = invitation.export_secret_token();
1362    let request = invitation.checkpoint_request([2; 32], [1; 32]).unwrap();
1363    assert_eq!(request.len(), CHECKPOINT_REQUEST_SIZE);
1364    assert_eq!(&request[..PUBLIC], &token[..PUBLIC]);
1365    assert!(!request.windows(32).any(|part| part == &token[PUBLIC..]));
1366    assert_eq!(
1367        admin
1368            .checkpoint_for_invitation([2; 32], [1; 32], &request)
1369            .unwrap(),
1370        checkpoint
1371    );
1372    assert!(
1373        admin
1374            .checkpoint_for_invitation([3; 32], [1; 32], &request)
1375            .is_err()
1376    );
1377    assert!(
1378        admin
1379            .checkpoint_for_invitation([2; 32], [9; 32], &request)
1380            .is_err()
1381    );
1382    let mut tampered = request;
1383    tampered[PUBLIC] ^= 1;
1384    assert!(
1385        admin
1386            .checkpoint_for_invitation([2; 32], [1; 32], &tampered)
1387            .is_err()
1388    );
1389}
1390
1391#[test]
1392fn signed_invitation_survives_pending_restart_and_offline_issuer() {
1393    use super::{PendingJoin, StorageKey};
1394    let admin = Workspace::create([1; 32], "Coordinator").unwrap();
1395    let (invitation, checkpoint) = admin.issue_invitation().unwrap();
1396    let token = invitation.export_secret_token();
1397    assert_eq!(token.len(), TOKEN_SIZE);
1398    let invitation = Invitation::from_bytes(&token).unwrap();
1399    assert_eq!(
1400        invitation.export_secret_token().as_slice(),
1401        token.as_slice()
1402    );
1403    for length in 0..TOKEN_SIZE {
1404        assert!(Invitation::from_bytes(&token[..length]).is_err());
1405    }
1406    let mut trailing = token.to_vec();
1407    trailing.push(0);
1408    assert!(Invitation::from_bytes(&trailing).is_err());
1409    for index in [0, 4, 5, 37, 69, 101, 133, 197, 261, 292] {
1410        let mut bad = Zeroizing::new(token.to_vec());
1411        bad[index] ^= 1;
1412        assert!(Invitation::from_bytes(&bad).is_err());
1413    }
1414    let other = Workspace::create([9; 32], "Coordinator").unwrap();
1415    assert!(
1416        invitation
1417            .join_proof(&other.join_checkpoint().unwrap())
1418            .is_err()
1419    );
1420    let pending =
1421        PendingJoin::from_invitation(&invitation, &checkpoint, [2; 32], "Field helper").unwrap();
1422    let key = StorageKey::derive(&[7; 32]).unwrap();
1423    let request = pending.admission_request().unwrap().to_vec();
1424    let member = pending.member().clone();
1425    let sealed = pending.seal(&key).unwrap();
1426    assert!(sealed.starts_with(b"DFPJ\x02"));
1427    drop(pending);
1428    let pending = PendingJoin::restore(&key, [2; 32], admin.id(), &sealed).unwrap();
1429    assert_eq!(pending.admission_request().unwrap(), request);
1430    assert_eq!(pending.member(), &member);
1431    let mut proof = pending.join_proof().unwrap();
1432    assert!(admin.prepare_admission([3; 32], &request).is_err());
1433    assert!(other.prepare_admission([2; 32], &request).is_err());
1434    for index in [0, 5, 42, 106, 202, 266, request.len() - 1] {
1435        let mut bad = request.clone();
1436        bad[index] ^= 1;
1437        assert!(admin.prepare_admission([2; 32], &bad).is_err());
1438    }
1439    let mut extra = request.clone();
1440    extra.push(0);
1441    assert!(admin.prepare_admission([2; 32], &extra).is_err());
1442    let first = admin.prepare_admission([2; 32], &request).unwrap();
1443    assert_eq!(admin.epoch(), 0);
1444    assert_eq!(admin.member_count(), 1);
1445    assert!(
1446        admin
1447            .retained_admission([2; 32], &request)
1448            .unwrap()
1449            .is_none()
1450    );
1451    let snapshot = first.workspace.seal(&key).unwrap();
1452    assert!(snapshot.starts_with(b"DFWS\x03"));
1453    // Authenticated malformed format must fail at the bounded parser too.
1454    let plain = key
1455        .unprotect(b"DFWS\x03", admin.id(), [1; 32], &snapshot)
1456        .unwrap();
1457    let count_offset = 8 + 32 + 4 + admin.member().unwrap().display_name().len();
1458    for count in [0u32, MAX_ADMISSIONS as u32 + 1, u32::MAX] {
1459        let mut invalid = plain.clone();
1460        invalid[count_offset..count_offset + 4].copy_from_slice(&count.to_be_bytes());
1461        let sealed = key
1462            .protect(&admin.provider, b"DFWS\x03", admin.id(), [1; 32], &invalid)
1463            .unwrap();
1464        assert!(Workspace::restore(&key, [1; 32], admin.id(), &sealed).is_err());
1465    }
1466    let mut invalid = plain.clone();
1467    let epoch_offset = count_offset + 4 + 96;
1468    invalid[epoch_offset..epoch_offset + 8].copy_from_slice(&2u64.to_be_bytes());
1469    let sealed = key
1470        .protect(&admin.provider, b"DFWS\x03", admin.id(), [1; 32], &invalid)
1471        .unwrap();
1472    assert!(Workspace::restore(&key, [1; 32], admin.id(), &sealed).is_err());
1473    let expected_commit = first.commit.clone();
1474    let expected_welcome = first.welcome.clone();
1475    drop(first);
1476    // The candidate and reply survive together; recovery does not run Add again.
1477    let recovered = Workspace::restore(&key, [1; 32], admin.id(), &snapshot).unwrap();
1478    assert_eq!(recovered.epoch(), 1);
1479    assert_eq!(recovered.member_count(), 2);
1480    assert!(recovered.retained_admission([3; 32], &request).is_err());
1481    let mut changed_request = request.clone();
1482    *changed_request.last_mut().unwrap() ^= 1;
1483    assert!(
1484        recovered
1485            .retained_admission([2; 32], &changed_request)
1486            .unwrap()
1487            .is_none()
1488    );
1489    let retry = recovered
1490        .retained_admission([2; 32], &request)
1491        .unwrap()
1492        .unwrap();
1493    assert_eq!(retry.commit, expected_commit);
1494    assert_eq!(retry.welcome, expected_welcome);
1495    assert_eq!(retry.epoch, 1);
1496    proof
1497        .apply_add(&retry.authorization, &retry.commit)
1498        .unwrap();
1499    let helper = pending.prepare_workspace(&proof, &retry.welcome).unwrap();
1500    let mut tampered = snapshot.clone();
1501    *tampered.last_mut().unwrap() ^= 1;
1502    assert!(Workspace::restore(&key, [1; 32], admin.id(), &tampered).is_err());
1503    assert!(
1504        Workspace::restore(&key, [1; 32], admin.id(), &snapshot[..snapshot.len() - 1]).is_err()
1505    );
1506    assert_eq!(helper.member(), Some(&member));
1507    assert!(helper.issue_invitation().is_err());
1508    let encoded = proof.history();
1509    assert!(JoinProof::from_history(admin.id(), [0; 32], encoded).is_err());
1510    assert!(
1511        JoinProof::from_history(
1512            admin.id(),
1513            invitation.checkpoint_digest(),
1514            &encoded[..encoded.len() - 1]
1515        )
1516        .is_err()
1517    );
1518    let mut altered = encoded.to_vec();
1519    let checkpoint_length = u32::from_be_bytes(altered[37..41].try_into().unwrap()) as usize;
1520    altered[41 + checkpoint_length + 32] ^= 1; // Administrator grant signature, not the secret-only membership MAC.
1521    assert!(JoinProof::from_history(admin.id(), invitation.checkpoint_digest(), &altered).is_err());
1522    let helper_snapshot = helper.seal(&key).unwrap();
1523    assert!(helper_snapshot.starts_with(b"DFWS\x04"));
1524    drop(helper);
1525    let helper = Workspace::restore(&key, [2; 32], admin.id(), &helper_snapshot).unwrap();
1526    let admin_state = recovered.seal(&key).unwrap();
1527    let workspace_id = admin.id();
1528    drop(recovered);
1529    drop(admin);
1530    // The issuer is gone. The same preissued token works through an ordinary member.
1531    let newcomer =
1532        PendingJoin::from_invitation(&invitation, &checkpoint, [3; 32], "Jordan Lee").unwrap();
1533    let request = newcomer.admission_request().unwrap();
1534    assert_eq!(
1535        helper
1536            .admission_history([3; 32], request, &checkpoint)
1537            .unwrap()
1538            .len(),
1539        1
1540    );
1541    assert!(
1542        helper
1543            .admission_history([9; 32], request, &checkpoint)
1544            .is_err()
1545    );
1546    let mut bad_checkpoint = checkpoint.clone();
1547    *bad_checkpoint.last_mut().unwrap() ^= 1;
1548    assert!(
1549        helper
1550            .admission_history([3; 32], request, &bad_checkpoint)
1551            .is_err()
1552    );
1553    let mut bad_request = request.to_vec();
1554    bad_request[5 + 133] ^= 1;
1555    assert!(
1556        helper
1557            .admission_history([3; 32], &bad_request, &checkpoint)
1558            .is_err()
1559    );
1560    let mut missing = Workspace::restore(&key, [2; 32], workspace_id, &helper_snapshot).unwrap();
1561    missing.join_history = None;
1562    assert_eq!(
1563        missing
1564            .admission_history([3; 32], request, &checkpoint)
1565            .err(),
1566        Some("invitation history unavailable")
1567    );
1568    assert_eq!(missing.epoch(), 1);
1569    assert_eq!(missing.member_count(), 2);
1570    let second = helper
1571        .prepare_admission([3; 32], newcomer.admission_request().unwrap())
1572        .unwrap();
1573    assert_eq!(helper.epoch(), 1);
1574    assert_eq!(helper.member_count(), 2);
1575    proof
1576        .apply_add(&second.authorization, &second.commit)
1577        .unwrap();
1578    let joined = newcomer.prepare_workspace(&proof, &second.welcome).unwrap();
1579    assert_eq!(joined.member_count(), 3);
1580    assert_eq!(joined.member().unwrap().display_name(), "Jordan Lee");
1581    assert_eq!(
1582        second
1583            .workspace
1584            .prepare_admission([3; 32], newcomer.admission_request().unwrap())
1585            .err(),
1586        Some("member already admitted")
1587    );
1588    assert_eq!(
1589        second
1590            .workspace
1591            .prepare_admission([4; 32], newcomer.admission_request().unwrap())
1592            .err(),
1593        Some("admission endpoint mismatch")
1594    );
1595    // Durability/response retention must prevent retry from becoming another Add.
1596    let joined_state = joined.seal(&key).unwrap();
1597    let mut joined = Workspace::restore(&key, [3; 32], workspace_id, &joined_state).unwrap();
1598    let updated_admin = Workspace::restore(&key, [1; 32], workspace_id, &admin_state)
1599        .unwrap()
1600        .prepare_admission_update(&second.authorization, &second.commit)
1601        .unwrap();
1602    let mut helper = second.workspace;
1603    let encrypted = joined
1604        .group
1605        .create_message(&joined.provider, &joined._signer, b"generic fabric payload")
1606        .unwrap();
1607    let wire = MlsMessageIn::tls_deserialize_exact(encrypted.to_bytes().unwrap())
1608        .unwrap()
1609        .try_into_protocol_message()
1610        .unwrap();
1611    let message = helper
1612        .group
1613        .process_message(&helper.provider, wire)
1614        .unwrap();
1615    let ProcessedMessageContent::ApplicationMessage(message) = message.into_content() else {
1616        panic!("not application data")
1617    };
1618    assert_eq!(message.into_bytes(), b"generic fabric payload");
1619    let returning = Workspace::restore(&key, [1; 32], workspace_id, &admin_state).unwrap();
1620    assert_eq!(returning.epoch(), 1);
1621    let mut bad = second.authorization.clone();
1622    bad.grant_signature[0] ^= 1;
1623    assert!(
1624        returning
1625            .prepare_admission_update(&bad, &second.commit)
1626            .is_err()
1627    );
1628    let mut bad_commit = second.commit.clone();
1629    *bad_commit.last_mut().unwrap() ^= 1;
1630    assert!(
1631        returning
1632            .prepare_admission_update(&second.authorization, &bad_commit)
1633            .is_err()
1634    );
1635    assert_eq!(returning.epoch(), 1); // Rejection and preparation never mutate the accepted owner.
1636    assert!(
1637        updated_admin
1638            .prepare_admission_update(&second.authorization, &second.commit)
1639            .is_err()
1640    );
1641    let stored_update = updated_admin.seal(&key).unwrap();
1642    let mut returning = Workspace::restore(&key, [1; 32], workspace_id, &stored_update).unwrap();
1643    assert_eq!(returning.epoch(), 2);
1644    assert_eq!(returning.member_count(), 3);
1645    // A restored creator must relay the helper's accepted Add, not only Adds
1646    // it originated. This history must not depend on retaining a Welcome reply.
1647    let (_, relayed) = returning
1648        .membership_update_for([2; 32], 1)
1649        .unwrap()
1650        .expect("restored creator retains the helper admission");
1651    assert_eq!(relayed, second.commit);
1652    assert!(
1653        returning
1654            .membership_update_for([9; 32], 1)
1655            .unwrap()
1656            .is_none()
1657    );
1658    let later =
1659        PendingJoin::from_invitation(&invitation, &checkpoint, [8; 32], "Later member").unwrap();
1660    assert_eq!(
1661        returning
1662            .membership_history([8; 32], later.admission_request().unwrap(), &checkpoint,)
1663            .unwrap()
1664            .len(),
1665        2
1666    );
1667    let sample = joined
1668        .protect_object(b"feed/opaque", b"third member sample")
1669        .unwrap();
1670    assert_eq!(
1671        returning
1672            .unprotect_object(b"feed/opaque", &sample)
1673            .unwrap()
1674            .message
1675            .payload,
1676        b"third member sample"
1677    );
1678    let reply = returning
1679        .protect_object(b"chat", b"returning member reply")
1680        .unwrap();
1681    for reader in [&helper, &joined] {
1682        assert_eq!(
1683            reader
1684                .unprotect_object(b"chat", &reply)
1685                .unwrap()
1686                .message
1687                .payload,
1688            b"returning member reply"
1689        );
1690    }
1691    // An ordinary existing member carries its anchored authorization history forward too.
1692    let (next_invite, next_checkpoint) = returning.issue_invitation().unwrap();
1693    let fourth =
1694        PendingJoin::from_invitation(&next_invite, &next_checkpoint, [4; 32], "Second service")
1695            .unwrap();
1696    let fourth_add = returning
1697        .prepare_admission([4; 32], fourth.admission_request().unwrap())
1698        .unwrap();
1699    let helper_updated = helper
1700        .prepare_admission_update(&fourth_add.authorization, &fourth_add.commit)
1701        .unwrap();
1702    let helper_saved = helper_updated.seal(&key).unwrap();
1703    let helper_updated = Workspace::restore(&key, [2; 32], workspace_id, &helper_saved).unwrap();
1704    assert_eq!(helper_updated.member_count(), 4);
1705    let mut fourth_proof = fourth.join_proof().unwrap();
1706    fourth_proof
1707        .apply_add(&fourth_add.authorization, &fourth_add.commit)
1708        .unwrap();
1709    let mut fourth = fourth
1710        .prepare_workspace(&fourth_proof, &fourth_add.welcome)
1711        .unwrap();
1712    let sample = fourth
1713        .protect_object(b"feed/opaque", b"fourth member sample")
1714        .unwrap();
1715    assert_eq!(
1716        helper_updated
1717            .unprotect_object(b"feed/opaque", &sample)
1718            .unwrap()
1719            .message
1720            .payload,
1721        b"fourth member sample"
1722    );
1723    // A different valid admission from the same parent must not merge silently.
1724    let competing =
1725        PendingJoin::from_invitation(&next_invite, &next_checkpoint, [5; 32], "Competing service")
1726            .unwrap();
1727    let fork = helper
1728        .prepare_admission([5; 32], competing.admission_request().unwrap())
1729        .unwrap();
1730    assert!(
1731        helper_updated
1732            .prepare_admission_update(&fork.authorization, &fork.commit)
1733            .is_err()
1734    );
1735    assert_eq!(helper_updated.member_count(), 4);
1736}
1737
1738/// FUT-35: the owner must not re-verify its own already-accepted branch for
1739/// every arriving admission. When the pinned checkpoint is one this owner
1740/// issued and retained, the transitions come from its own records instead --
1741/// and they must be exactly the transitions full verification would produce,
1742/// including after a restore, and only for the invitation they belong to.
1743#[test]
1744fn retained_checkpoint_preflight_matches_full_verification_and_survives_restore() {
1745    use super::{PendingJoin, StorageKey};
1746    let admin = Workspace::create([1; 32], "Organizer").unwrap();
1747    let (created, invitation, checkpoint) = admin.prepare_invitation(0, false, false).unwrap();
1748    let mut owner = created.workspace;
1749    assert!(
1750        owner
1751            .retained_invitation_checkpoint(&created.action)
1752            .is_some(),
1753        "a registered invitation retains the checkpoint it pinned"
1754    );
1755
1756    // Grow the accepted branch so a full replay has real work to do.
1757    for endpoint in 2..6u8 {
1758        let pending =
1759            PendingJoin::from_invitation(&invitation, &checkpoint, [endpoint; 32], "Attendee")
1760                .unwrap();
1761        owner = owner
1762            .prepare_admission([endpoint; 32], pending.admission_request().unwrap())
1763            .unwrap()
1764            .workspace;
1765    }
1766
1767    let later =
1768        PendingJoin::from_invitation(&invitation, &checkpoint, [9; 32], "Later member").unwrap();
1769    let request = later.admission_request().unwrap();
1770    let fast = owner
1771        .membership_history([9; 32], request, &checkpoint)
1772        .unwrap();
1773
1774    // Force the slow path by dropping the retention, and require the same
1775    // answer. A cheaper preflight that accepted a different branch, or a
1776    // differently tagged one, would break the joiner it is meant to serve.
1777    let mut without_retention = owner.seal(&StorageKey::derive(&[7; 32]).unwrap()).unwrap();
1778    let mut stripped = Workspace::restore(
1779        &StorageKey::derive(&[7; 32]).unwrap(),
1780        owner.endpoint(),
1781        owner.id(),
1782        &without_retention,
1783    )
1784    .unwrap();
1785    stripped.invitation_checkpoints.clear();
1786    let slow = stripped
1787        .membership_history([9; 32], request, &checkpoint)
1788        .unwrap();
1789    assert_eq!(fast.len(), slow.len(), "fast path lost or invented a step");
1790    for (fast, slow) in fast.iter().zip(&slow) {
1791        assert_eq!(fast.1, slow.1, "fast path chose a different commit");
1792    }
1793
1794    // The retention is durable, so a restarted owner keeps the cheap path.
1795    without_retention.clear();
1796    let sealed = owner.seal(&StorageKey::derive(&[8; 32]).unwrap()).unwrap();
1797    let restored = Workspace::restore(
1798        &StorageKey::derive(&[8; 32]).unwrap(),
1799        owner.endpoint(),
1800        owner.id(),
1801        &sealed,
1802    )
1803    .unwrap();
1804    assert!(
1805        restored
1806            .retained_checkpoint_steps(
1807                &decode_request(&restored.provider, request).unwrap(),
1808                &checkpoint,
1809            )
1810            .unwrap()
1811            .is_some(),
1812        "a restarted owner must still take the retained-checkpoint path"
1813    );
1814
1815    // A request that does not belong to this invitation never takes it.
1816    let (other, other_invitation, other_checkpoint) =
1817        owner.prepare_invitation(0, false, false).unwrap();
1818    let owner = other.workspace;
1819    let outsider = PendingJoin::from_invitation(
1820        &other_invitation,
1821        &other_checkpoint,
1822        [10; 32],
1823        "Other link",
1824    )
1825    .unwrap();
1826    let parsed = decode_request(&owner.provider, outsider.admission_request().unwrap()).unwrap();
1827    assert!(
1828        owner
1829            .retained_checkpoint_steps(&parsed, &checkpoint)
1830            .unwrap()
1831            .is_none(),
1832        "another invitation's checkpoint must not match this request"
1833    );
1834}
1835
1836#[test]
1837fn batch_replies_share_one_commit_and_welcome_across_copies_and_restores() {
1838    use super::{PendingJoin, StorageKey};
1839    let owner = Workspace::create([1; 32], "Organizer").unwrap();
1840    let (invitation, checkpoint) = owner.issue_invitation().unwrap();
1841    let mut requests = Vec::new();
1842    for endpoint in 2..5u8 {
1843        let pending =
1844            PendingJoin::from_invitation(&invitation, &checkpoint, [endpoint; 32], "Attendee")
1845                .unwrap();
1846        requests.push(([endpoint; 32], pending.admission_request().unwrap().to_vec()));
1847    }
1848    let validated: Vec<_> = requests
1849        .iter()
1850        .map(|(endpoint, request)| match owner.assess_admission(*endpoint, request).unwrap() {
1851            AdmissionAssessment::Ready(validated) => validated,
1852            _ => panic!("invitation unexpectedly needs approval"),
1853        })
1854        .collect();
1855    let entries: Vec<_> = requests
1856        .iter()
1857        .zip(&validated)
1858        .map(|((endpoint, request), validated)| (*endpoint, request.as_slice(), validated))
1859        .collect();
1860    let prepared = owner.prepare_validated_admission_batch(&entries).unwrap();
1861    let shared = prepared.commit.len() + prepared.welcome.len();
1862    let owner = prepared.workspace;
1863
1864    // One batch is one commit and one Welcome in memory, however many joiners it admits.
1865    let assert_shared = |workspace: &Workspace| {
1866        assert_eq!(workspace.admissions.len(), 3);
1867        let first = &workspace.admissions[0].reply;
1868        for entry in &workspace.admissions[1..] {
1869            assert_eq!(entry.reply.commit.as_ptr(), first.commit.as_ptr());
1870            assert_eq!(entry.reply.welcome.as_ptr(), first.welcome.as_ptr());
1871        }
1872        assert_eq!(workspace.memory_report().admission_bytes, shared);
1873    };
1874    assert_shared(&owner);
1875
1876    // A provisional copy points at the same bytes instead of copying them.
1877    let copy = owner.provisional_copy().unwrap();
1878    assert_shared(&copy);
1879    assert_eq!(
1880        copy.admissions[0].reply.commit.as_ptr(),
1881        owner.admissions[0].reply.commit.as_ptr()
1882    );
1883
1884    // The record format is unchanged: a restored owner exports the same bytes
1885    // and shares the batch again.
1886    let records = owner.export_records().unwrap();
1887    let restored = Workspace::restore_records([1; 32], owner.id(), &records).unwrap();
1888    assert_shared(&restored);
1889    assert_eq!(restored.export_records().unwrap(), records);
1890    for (endpoint, request) in &requests {
1891        let before = owner.retained_admission(*endpoint, request).unwrap().unwrap();
1892        let after = restored.retained_admission(*endpoint, request).unwrap().unwrap();
1893        assert_eq!((before.epoch, &before.commit, &before.welcome), (after.epoch, &after.commit, &after.welcome));
1894    }
1895
1896    // The sealed snapshot is unchanged too: seal, restore, and seal again give
1897    // the same plaintext.
1898    let single = Workspace::create([1; 32], "Organizer").unwrap();
1899    let (invitation, checkpoint) = single.issue_invitation().unwrap();
1900    let pending =
1901        PendingJoin::from_invitation(&invitation, &checkpoint, [2; 32], "Attendee").unwrap();
1902    let single = single
1903        .prepare_admission([2; 32], pending.admission_request().unwrap())
1904        .unwrap()
1905        .workspace;
1906    let key = StorageKey::derive(&[7; 32]).unwrap();
1907    let sealed = single.seal(&key).unwrap();
1908    let reopened = Workspace::restore(&key, [1; 32], single.id(), &sealed).unwrap();
1909    let resealed = reopened.seal(&key).unwrap();
1910    let plain = |bytes: &[u8]| {
1911        let magic: &[u8; 5] = bytes[..5].try_into().unwrap();
1912        key.unprotect(magic, single.id(), [1; 32], bytes).unwrap()
1913    };
1914    assert_eq!(resealed[..5], sealed[..5]);
1915    assert_eq!(plain(&resealed), plain(&sealed));
1916}