Skip to main content

arachne_security/
storage.rs

1//! Bounded encrypted provider snapshot. Host owns atomic file replacement.
2use super::{MemberProfile, SUITE, Workspace, credential_identity};
3use aes_gcm::{
4    Aes256Gcm, KeyInit,
5    aead::{Aead, Payload},
6};
7use openmls::prelude::*;
8use openmls_basic_credential::SignatureKeyPair;
9use openmls_rust_crypto::OpenMlsRustCrypto;
10use openmls_traits::{OpenMlsProvider, random::OpenMlsRand};
11use zeroize::Zeroizing;
12
13const LEGACY: &[u8; 5] = b"DFWS\x01";
14const MAGIC: &[u8; 5] = b"DFWS\x02";
15const WITH_HISTORY: &[u8; 5] = b"DFWS\x04";
16const WITH_INVITATION_CHECKPOINTS: &[u8; 5] = b"DFWS\x05";
17const WITH_ADMISSIONS: &[u8; 5] = b"DFWS\x03";
18const HEADER: usize = 5 + 32 + 12;
19pub(super) const MAX_PLAIN: usize = 128 * 1024;
20const MAX_RECORDS: usize = 256;
21pub const MAX_SEALED_WORKSPACE: usize = HEADER + MAX_PLAIN + 16;
22const BUNDLE: &[u8; 5] = b"DFWB\x01";
23pub const MAX_WORKSPACE_ATTACHMENT: usize = 528 * 1024;
24pub const MAX_SEALED_BUNDLE: usize =
25    HEADER + 16 + 8 + MAX_SEALED_WORKSPACE + MAX_WORKSPACE_ATTACHMENT;
26
27/// Derived storage key has a distinct cryptographic purpose from endpoint TLS.
28/// Root material is supplied by the host's protected credential store.
29pub struct StorageKey(Zeroizing<[u8; 32]>);
30impl StorageKey {
31    pub fn derive(root: &[u8; 32]) -> Result<Self, &'static str> {
32        let mut key = Zeroizing::new([0; 32]);
33        hkdf::Hkdf::<sha2::Sha256>::new(Some(b"data-fabric/storage/v1"), root)
34            .expand(b"workspace-snapshot/aes256gcm", key.as_mut())
35            .map_err(|_| "storage key derivation failed")?;
36        Ok(Self(key))
37    }
38}
39
40pub(super) fn take<'a>(bytes: &mut &'a [u8], count: usize) -> Result<&'a [u8], &'static str> {
41    let (head, tail) = bytes
42        .split_at_checked(count)
43        .ok_or("truncated protected state")?;
44    *bytes = tail;
45    Ok(head)
46}
47pub(super) fn number(bytes: &mut &[u8]) -> Result<usize, &'static str> {
48    Ok(u32::from_be_bytes(take(bytes, 4)?.try_into().unwrap()) as usize)
49}
50pub(super) fn write_profile(bytes: &mut Vec<u8>, member: &MemberProfile) {
51    bytes.extend(member.id);
52    bytes.extend((member.display_name.len() as u32).to_be_bytes());
53    bytes.extend(member.display_name.as_bytes());
54}
55pub(super) fn read_profile(bytes: &mut &[u8]) -> Result<MemberProfile, &'static str> {
56    let id = take(bytes, 32)?.try_into().unwrap();
57    let length = number(bytes)?;
58    if length > 256 {
59        return Err("member name exceeds bounds");
60    }
61    let name = std::str::from_utf8(take(bytes, length)?).map_err(|_| "invalid member name")?;
62    let profile = MemberProfile::new(id, name)?;
63    if profile.display_name() != name {
64        return Err("noncanonical member name");
65    }
66    Ok(profile)
67}
68pub(super) fn encode_provider(
69    provider: &OpenMlsRustCrypto,
70    mut prefix: Zeroizing<Vec<u8>>,
71) -> Result<Zeroizing<Vec<u8>>, &'static str> {
72    let state = provider
73        .storage()
74        .values
75        .read()
76        .map_err(|_| "storage unavailable")?;
77    if state.len() > MAX_RECORDS {
78        return Err("protected state exceeds bounds");
79    }
80    let size = state
81        .iter()
82        .try_fold(prefix.len() + 4, |total, (k, v)| {
83            total
84                .checked_add(8)?
85                .checked_add(k.len())?
86                .checked_add(v.len())
87        })
88        .ok_or("protected state exceeds bounds")?;
89    if size > MAX_PLAIN {
90        return Err("protected state exceeds bounds");
91    }
92    let additional = size - prefix.len();
93    prefix.reserve(additional);
94    prefix.extend((state.len() as u32).to_be_bytes());
95    let mut entries: Vec<_> = state.iter().collect();
96    entries.sort_by(|a, b| a.0.cmp(b.0));
97    for (k, v) in entries {
98        prefix.extend((k.len() as u32).to_be_bytes());
99        prefix.extend((v.len() as u32).to_be_bytes());
100        prefix.extend(k);
101        prefix.extend(v);
102    }
103    Ok(prefix)
104}
105
106/// Copy an in-memory owner without routing it through a legacy file-size budget.
107pub(super) fn copy_provider(
108    provider: &OpenMlsRustCrypto,
109) -> Result<OpenMlsRustCrypto, &'static str> {
110    let records = provider
111        .storage()
112        .values
113        .read()
114        .map_err(|_| "storage unavailable")?
115        .clone();
116    let copy = OpenMlsRustCrypto::default();
117    *copy
118        .storage()
119        .values
120        .write()
121        .map_err(|_| "storage unavailable")? = records;
122    Ok(copy)
123}
124pub(super) fn decode_provider(bytes: &mut &[u8]) -> Result<OpenMlsRustCrypto, &'static str> {
125    let count = number(bytes)?;
126    if count > MAX_RECORDS {
127        return Err("protected state exceeds bounds");
128    }
129    let provider = OpenMlsRustCrypto::default();
130    {
131        let mut state = provider
132            .storage()
133            .values
134            .write()
135            .map_err(|_| "storage unavailable")?;
136        for _ in 0..count {
137            let klen = number(bytes)?;
138            let vlen = number(bytes)?;
139            let k = take(bytes, klen)?.to_vec();
140            let v = take(bytes, vlen)?.to_vec();
141            if state.insert(k, v).is_some() {
142                return Err("duplicate protected record");
143            }
144        }
145    }
146    if !bytes.is_empty() {
147        return Err("trailing protected state");
148    }
149    Ok(provider)
150}
151impl StorageKey {
152    pub(super) fn protect(
153        &self,
154        provider: &OpenMlsRustCrypto,
155        magic: &[u8; 5],
156        id: [u8; 32],
157        endpoint: [u8; 32],
158        plain: &[u8],
159    ) -> Result<Vec<u8>, &'static str> {
160        if plain.len() > MAX_PLAIN {
161            return Err("protected state exceeds bounds");
162        }
163        self.protect_record(provider, magic, id, endpoint, plain)
164    }
165    // Callers enforce their record-family bounds before encrypting.
166    fn protect_record(
167        &self,
168        provider: &OpenMlsRustCrypto,
169        magic: &[u8; 5],
170        id: [u8; 32],
171        endpoint: [u8; 32],
172        plain: &[u8],
173    ) -> Result<Vec<u8>, &'static str> {
174        let nonce = provider
175            .rand()
176            .random_array::<12>()
177            .map_err(|_| "snapshot randomness failed")?;
178        let mut result = magic.to_vec();
179        result.extend(id);
180        result.extend(nonce);
181        let mut aad = result.clone();
182        aad.extend(endpoint);
183        let cipher =
184            Aes256Gcm::new_from_slice(self.0.as_ref()).map_err(|_| "invalid storage key")?;
185        let encrypted = cipher
186            .encrypt(
187                (&nonce).into(),
188                Payload {
189                    msg: plain,
190                    aad: &aad,
191                },
192            )
193            .map_err(|_| "snapshot protection failed")?;
194        result.extend(encrypted);
195        Ok(result)
196    }
197    pub(super) fn unprotect(
198        &self,
199        magic: &[u8; 5],
200        id: [u8; 32],
201        endpoint: [u8; 32],
202        sealed: &[u8],
203    ) -> Result<Zeroizing<Vec<u8>>, &'static str> {
204        self.unprotect_record(magic, id, endpoint, sealed, MAX_SEALED_WORKSPACE)
205    }
206    fn unprotect_record(
207        &self,
208        magic: &[u8; 5],
209        id: [u8; 32],
210        endpoint: [u8; 32],
211        sealed: &[u8],
212        max_bytes: usize,
213    ) -> Result<Zeroizing<Vec<u8>>, &'static str> {
214        if sealed.len() < HEADER + 16
215            || sealed.len() > max_bytes
216            || !sealed.starts_with(magic)
217            || sealed[5..37] != id
218        {
219            return Err("invalid protected snapshot");
220        }
221        let mut aad = sealed[..HEADER].to_vec();
222        aad.extend(endpoint);
223        let nonce: &[u8; 12] = sealed[37..HEADER].try_into().unwrap();
224        let cipher =
225            Aes256Gcm::new_from_slice(self.0.as_ref()).map_err(|_| "invalid storage key")?;
226        Ok(Zeroizing::new(
227            cipher
228                .decrypt(
229                    nonce.into(),
230                    Payload {
231                        msg: &sealed[HEADER..],
232                        aad: &aad,
233                    },
234                )
235                .map_err(|_| "snapshot authentication failed")?,
236        ))
237    }
238}
239impl Workspace {
240    /// One authenticated host record for security state and opaque local state.
241    /// Host must atomically replace it before adopting state or releasing packets.
242    /// This binds the bytes together; it does not validate the attachment's meaning
243    /// or prevent rollback to an older authentic record.
244    pub fn seal_with_attachment(
245        &self,
246        key: &StorageKey,
247        attachment: &[u8],
248    ) -> Result<Vec<u8>, &'static str> {
249        if attachment.len() > MAX_WORKSPACE_ATTACHMENT {
250            return Err("workspace attachment exceeds bounds");
251        }
252        let security = self.seal(key)?;
253        let mut plain = Zeroizing::new(Vec::with_capacity(8 + security.len() + attachment.len()));
254        plain.extend((security.len() as u32).to_be_bytes());
255        plain.extend(security);
256        plain.extend((attachment.len() as u32).to_be_bytes());
257        plain.extend(attachment);
258        key.protect_record(&self.provider, BUNDLE, self.id, self.endpoint, &plain)
259    }
260
261    /// Authenticate the whole record before exposing either component. The caller
262    /// must validate the attachment against the restored owner before adoption.
263    pub fn restore_with_attachment(
264        key: &StorageKey,
265        endpoint: [u8; 32],
266        id: [u8; 32],
267        sealed: &[u8],
268    ) -> Result<(Self, Zeroizing<Vec<u8>>), &'static str> {
269        let plain = key.unprotect_record(BUNDLE, id, endpoint, sealed, MAX_SEALED_BUNDLE)?;
270        let mut bytes = plain.as_slice();
271        let length = number(&mut bytes)?;
272        if length > MAX_SEALED_WORKSPACE {
273            return Err("bundled security state exceeds bounds");
274        }
275        let security = take(&mut bytes, length)?;
276        let length = number(&mut bytes)?;
277        if length > MAX_WORKSPACE_ATTACHMENT || bytes.len() != length {
278            return Err("invalid workspace attachment length");
279        }
280        let workspace = Self::restore(key, endpoint, id, security)?;
281        Ok((workspace, Zeroizing::new(bytes.to_vec())))
282    }
283
284    pub fn seal(&self, key: &StorageKey) -> Result<Vec<u8>, &'static str> {
285        let mut prefix = Zeroizing::new(self.epoch().to_be_bytes().to_vec());
286        if let Some(member) = &self.member {
287            write_profile(&mut prefix, member);
288        }
289        if !self.invitation_checkpoints.is_empty() {
290            prefix.push(u8::from(self.join_history.is_some()));
291        }
292        if let Some(history) = &self.join_history {
293            let history = history.inline(self.id)?;
294            if history.len() > MAX_PLAIN {
295                return Err("join history exceeds snapshot bounds");
296            }
297            prefix.extend((history.len() as u32).to_be_bytes());
298            prefix.extend(&history);
299        }
300        if !self.admissions.is_empty()
301            || self.join_history.is_some()
302            || !self.invitation_checkpoints.is_empty()
303        {
304            if self.member.is_none() || self.admissions.len() > super::invitation::MAX_ADMISSIONS {
305                return Err("invalid admission retention");
306            }
307            prefix.extend((self.admissions.len() as u32).to_be_bytes());
308            for entry in &self.admissions {
309                prefix.extend(entry.digest);
310                prefix.extend(entry.endpoint);
311                prefix.extend(entry.issuer);
312                prefix.extend(entry.reply.epoch.to_be_bytes());
313                prefix.extend(entry.reply.authorization.invitation_key);
314                prefix.extend(entry.reply.authorization.grant_signature);
315                prefix.extend(entry.reply.authorization.redemption_signature);
316                for value in [&entry.reply.commit, &entry.reply.welcome] {
317                    if value.is_empty() || value.len() > MAX_PLAIN {
318                        return Err("admission response exceeds bounds");
319                    }
320                    prefix.extend((value.len() as u32).to_be_bytes());
321                    prefix.extend_from_slice(value);
322                }
323            }
324        }
325        if !self.invitation_checkpoints.is_empty() {
326            prefix.extend((self.invitation_checkpoints.len() as u32).to_be_bytes());
327            for saved in &self.invitation_checkpoints {
328                prefix.extend(saved.grant);
329                prefix.extend((saved.checkpoint.len() as u32).to_be_bytes());
330                prefix.extend(&saved.checkpoint);
331            }
332        }
333        let plain = encode_provider(&self.provider, prefix)?;
334        key.protect(
335            &self.provider,
336            if !self.invitation_checkpoints.is_empty() {
337                WITH_INVITATION_CHECKPOINTS
338            } else if self.join_history.is_some() {
339                WITH_HISTORY
340            } else if !self.admissions.is_empty() {
341                WITH_ADMISSIONS
342            } else if self.member.is_some() {
343                MAGIC
344            } else {
345                LEGACY
346            },
347            self.id,
348            self.endpoint,
349            &plain,
350        )
351    }
352    pub fn restore(
353        key: &StorageKey,
354        endpoint: [u8; 32],
355        id: [u8; 32],
356        sealed: &[u8],
357    ) -> Result<Self, &'static str> {
358        let magic = if sealed.starts_with(LEGACY) {
359            LEGACY
360        } else if sealed.starts_with(WITH_INVITATION_CHECKPOINTS) {
361            WITH_INVITATION_CHECKPOINTS
362        } else if sealed.starts_with(WITH_HISTORY) {
363            WITH_HISTORY
364        } else if sealed.starts_with(WITH_ADMISSIONS) {
365            WITH_ADMISSIONS
366        } else {
367            MAGIC
368        };
369        let plain = key.unprotect(magic, id, endpoint, sealed)?;
370        let mut bytes = plain.as_slice();
371        let epoch = u64::from_be_bytes(take(&mut bytes, 8)?.try_into().unwrap());
372        let member = if magic != LEGACY {
373            Some(read_profile(&mut bytes)?)
374        } else {
375            None
376        };
377        let has_history = if magic == WITH_INVITATION_CHECKPOINTS {
378            match take(&mut bytes, 1)?[0] {
379                0 => false,
380                1 => true,
381                _ => return Err("invalid stored history flag"),
382            }
383        } else {
384            magic == WITH_HISTORY
385        };
386        let join_history = if has_history {
387            let length = number(&mut bytes)?;
388            Some(super::history::MembershipHistory::from_inline(take(
389                &mut bytes, length,
390            )?)?)
391        } else {
392            None
393        };
394        let mut admissions = Vec::new();
395        let mut shared = super::invitation::SharedReplies::default();
396        if magic == WITH_ADMISSIONS || magic == WITH_HISTORY || magic == WITH_INVITATION_CHECKPOINTS
397        {
398            let count = number(&mut bytes)?;
399            if (count == 0 && magic == WITH_ADMISSIONS) || count > super::invitation::MAX_ADMISSIONS
400            {
401                return Err("invalid admission retention count");
402            }
403            let mut digests = std::collections::BTreeSet::new();
404            let mut prior_epoch = 0;
405            for _ in 0..count {
406                let digest = take(&mut bytes, 32)?.try_into().unwrap();
407                let remote = take(&mut bytes, 32)?.try_into().unwrap();
408                let issuer = take(&mut bytes, 32)?.try_into().unwrap();
409                let admitted_epoch = u64::from_be_bytes(take(&mut bytes, 8)?.try_into().unwrap());
410                if !digests.insert(digest)
411                    || admitted_epoch <= prior_epoch
412                    || admitted_epoch > epoch
413                {
414                    return Err("invalid admission history");
415                }
416                prior_epoch = admitted_epoch;
417                let authorization = super::AdmissionAuthorization {
418                    invitation_key: take(&mut bytes, 32)?.try_into().unwrap(),
419                    grant_signature: take(&mut bytes, 64)?.try_into().unwrap(),
420                    redemption_signature: take(&mut bytes, 64)?.try_into().unwrap(),
421                };
422                let mut read_blob = || -> Result<Vec<u8>, &'static str> {
423                    let length = number(&mut bytes)?;
424                    if length == 0 || length > MAX_PLAIN {
425                        return Err("admission response exceeds bounds");
426                    }
427                    Ok(take(&mut bytes, length)?.to_vec())
428                };
429                let commit = read_blob()?;
430                let welcome = read_blob()?;
431                admissions.push(super::invitation::RetainedAdmission {
432                    digest,
433                    endpoint: remote,
434                    issuer,
435                    reply: shared.reply(admitted_epoch, commit, welcome, authorization),
436                });
437            }
438        }
439        let mut invitation_checkpoints = Vec::new();
440        if magic == WITH_INVITATION_CHECKPOINTS {
441            let count = number(&mut bytes)?;
442            if count == 0 || count > super::invitation::MAX_RETAINED_CHECKPOINTS {
443                return Err("invalid invitation checkpoint count");
444            }
445            for _ in 0..count {
446                let grant = take(&mut bytes, super::invitation::PUBLIC)?
447                    .try_into()
448                    .unwrap();
449                let length = number(&mut bytes)?;
450                if length == 0 || length > 64 * 1024 {
451                    return Err("invalid retained invitation checkpoint");
452                }
453                invitation_checkpoints.push(super::invitation::RetainedInvitationCheckpoint {
454                    grant,
455                    checkpoint: take(&mut bytes, length)?.to_vec(),
456                });
457            }
458        }
459        let provider = decode_provider(&mut bytes)?;
460        Self::restore_owner(
461            provider,
462            endpoint,
463            id,
464            epoch,
465            member,
466            admissions,
467            join_history,
468            invitation_checkpoints,
469        )
470    }
471
472    #[allow(clippy::too_many_arguments)]
473    pub(super) fn restore_owner(
474        provider: OpenMlsRustCrypto,
475        endpoint: [u8; 32],
476        id: [u8; 32],
477        epoch: u64,
478        member: Option<MemberProfile>,
479        admissions: Vec<super::invitation::RetainedAdmission>,
480        join_history: Option<super::history::MembershipHistory>,
481        invitation_checkpoints: Vec<super::invitation::RetainedInvitationCheckpoint>,
482    ) -> Result<Self, &'static str> {
483        let group = MlsGroup::load(provider.storage(), &GroupId::from_slice(&id))
484            .map_err(|_| "invalid stored group")?
485            .ok_or("missing stored group")?;
486        if group.group_id().as_slice() != id
487            || group.epoch().as_u64() != epoch
488            || group.ciphersuite() != SUITE
489            || !group.is_active()
490            || group.pending_commit().is_some()
491        {
492            return Err("workspace state mismatch");
493        }
494        let own = group
495            .members()
496            .find(|m| m.index == group.own_leaf_index())
497            .ok_or("missing own credential")?;
498        let credential = BasicCredential::try_from(own.credential.clone())
499            .map_err(|_| "invalid own credential")?;
500        if credential.identity() != credential_identity(endpoint, member.as_ref()) {
501            return Err("workspace endpoint mismatch");
502        }
503        let signer = SignatureKeyPair::read(
504            provider.storage(),
505            &own.signature_key,
506            SUITE.signature_algorithm(),
507        )
508        .ok_or("missing workspace signer")?;
509        let workspace = Self {
510            provider,
511            _signer: signer,
512            group,
513            id,
514            endpoint,
515            member,
516            admissions,
517            join_history,
518            invitation_checkpoints,
519        };
520        if let Some(history) = &workspace.join_history {
521            history.verify(&workspace)?;
522        }
523        workspace.verify_retained_invitation_checkpoints()?;
524        workspace.object_counter()?;
525        workspace.name_state()?;
526        Ok(workspace)
527    }
528}
529
530#[test]
531fn protected_snapshot_restores_and_rejects_wrong_context() {
532    let key = StorageKey::derive(&[7; 32]).unwrap();
533    let workspace = Workspace::create([1; 32], "Alex Morgan").unwrap();
534    let id = workspace.id();
535    let profile = workspace.member().unwrap().clone();
536    let sealed = workspace.seal(&key).unwrap();
537    assert_ne!(sealed, workspace.seal(&key).unwrap());
538    drop(workspace);
539    let mut restored = Workspace::restore(&key, [1; 32], id, &sealed).unwrap();
540    assert_eq!(restored.id(), id);
541    assert_eq!(restored.member(), Some(&profile));
542    assert_eq!(restored.epoch(), 0);
543    assert_eq!(restored.member_count(), 1);
544    restored
545        .group
546        .create_message(&restored.provider, &restored._signer, b"after restore")
547        .unwrap();
548    let sealed_again = restored.seal(&key).unwrap();
549    assert!(Workspace::restore(&key, [1; 32], id, &sealed_again).is_ok());
550    assert!(
551        Workspace::restore(&StorageKey::derive(&[8; 32]).unwrap(), [1; 32], id, &sealed).is_err()
552    );
553    assert!(Workspace::restore(&key, [2; 32], id, &sealed).is_err());
554    assert!(Workspace::restore(&key, [1; 32], [9; 32], &sealed).is_err());
555    for index in [0, 5, 37, HEADER, sealed.len() - 1] {
556        let mut bad = sealed.clone();
557        bad[index] ^= 1;
558        assert!(Workspace::restore(&key, [1; 32], id, &bad).is_err());
559    }
560    assert!(Workspace::restore(&key, [1; 32], id, &sealed[..sealed.len() - 1]).is_err());
561    let mut trailing = sealed.clone();
562    trailing.push(0);
563    assert!(Workspace::restore(&key, [1; 32], id, &trailing).is_err());
564    assert!(Workspace::restore(&key, [1; 32], id, &vec![0; MAX_SEALED_WORKSPACE + 1]).is_err());
565}
566
567#[test]
568fn legacy_snapshot_keeps_credential_and_has_no_invented_profile() {
569    let provider = OpenMlsRustCrypto::default();
570    let signer = SignatureKeyPair::new(SUITE.signature_algorithm()).unwrap();
571    signer.store(provider.storage()).unwrap();
572    let id = [4; 32];
573    let endpoint = [5; 32];
574    let credential = CredentialWithKey {
575        credential: BasicCredential::new(credential_identity(endpoint, None)).into(),
576        signature_key: signer.to_public_vec().into(),
577    };
578    let group = MlsGroup::new_with_group_id(
579        &provider,
580        &signer,
581        &MlsGroupCreateConfig::builder().ciphersuite(SUITE).build(),
582        GroupId::from_slice(&id),
583        credential,
584    )
585    .unwrap();
586    let workspace = Workspace {
587        provider,
588        _signer: signer,
589        group,
590        id,
591        endpoint,
592        member: None,
593        admissions: Vec::new(),
594        join_history: None,
595        invitation_checkpoints: Vec::new(),
596    };
597    let key = StorageKey::derive(&[6; 32]).unwrap();
598    let sealed = workspace.seal(&key).unwrap();
599    assert!(sealed.starts_with(LEGACY));
600    let restored = Workspace::restore(&key, endpoint, id, &sealed).unwrap();
601    assert_eq!(restored.member(), None);
602    assert_eq!(restored._signer.public(), workspace._signer.public());
603    assert!(restored.seal(&key).unwrap().starts_with(LEGACY));
604}
605
606#[test]
607fn profile_must_match_the_stored_mls_credential() {
608    let key = StorageKey::derive(&[7; 32]).unwrap();
609    let mut workspace = Workspace::create([1; 32], "Alex").unwrap();
610    workspace.member.as_mut().unwrap().id = [99; 32];
611    // Even a correctly encrypted snapshot cannot substitute a different member
612    // ID for the ID bound into the stored MLS credential.
613    let sealed = workspace.seal(&key).unwrap();
614    assert!(Workspace::restore(&key, [1; 32], workspace.id(), &sealed).is_err());
615}
616
617#[test]
618fn combined_record_authenticates_both_parts_and_preserves_legacy_bounds() {
619    let key = StorageKey::derive(&[7; 32]).unwrap();
620    let owner = Workspace::create([1; 32], "Alex").unwrap();
621    let id = owner.id();
622    let attachment = vec![42; MAX_WORKSPACE_ATTACHMENT];
623    let sealed = owner.seal_with_attachment(&key, &attachment).unwrap();
624    assert!(sealed.len() <= MAX_SEALED_BUNDLE);
625    assert!(sealed.len() > MAX_SEALED_WORKSPACE);
626    let (restored, actual) =
627        Workspace::restore_with_attachment(&key, [1; 32], id, &sealed).unwrap();
628    assert_eq!(restored.member(), owner.member());
629    assert_eq!(actual.as_slice(), attachment);
630    assert!(Workspace::restore(&key, [1; 32], id, &sealed).is_err());
631    assert!(Workspace::restore_with_attachment(&key, [2; 32], id, &sealed).is_err());
632    assert!(Workspace::restore_with_attachment(&key, [1; 32], [9; 32], &sealed).is_err());
633    assert!(
634        Workspace::restore_with_attachment(
635            &StorageKey::derive(&[8; 32]).unwrap(),
636            [1; 32],
637            id,
638            &sealed
639        )
640        .is_err()
641    );
642    for offset in [0, 5, 37, HEADER, sealed.len() - 1] {
643        let mut bad = sealed.clone();
644        bad[offset] ^= 1;
645        assert!(Workspace::restore_with_attachment(&key, [1; 32], id, &bad).is_err());
646    }
647    assert!(
648        Workspace::restore_with_attachment(&key, [1; 32], id, &sealed[..sealed.len() - 1]).is_err()
649    );
650    let mut trailing = sealed.clone();
651    trailing.push(0);
652    assert!(Workspace::restore_with_attachment(&key, [1; 32], id, &trailing).is_err());
653    assert!(
654        owner
655            .seal_with_attachment(&key, &vec![0; MAX_WORKSPACE_ATTACHMENT + 1])
656            .is_err()
657    );
658    assert!(
659        Workspace::restore_with_attachment(&key, [1; 32], id, &vec![0; MAX_SEALED_BUNDLE + 1])
660            .is_err()
661    );
662    let legacy = owner.seal(&key).unwrap();
663    assert!(Workspace::restore(&key, [1; 32], id, &legacy).is_ok());
664    assert!(Workspace::restore_with_attachment(&key, [1; 32], id, &legacy).is_err());
665    // Valid encryption does not make malformed inner framing acceptable.
666    for (security, length, tail) in [
667        (legacy.as_slice(), 2u32, vec![1]),
668        (legacy.as_slice(), 0, vec![1]),
669        (
670            legacy.as_slice(),
671            (MAX_WORKSPACE_ATTACHMENT + 1) as u32,
672            vec![],
673        ),
674        (&[][..], 0, vec![]),
675    ] {
676        let mut plain = (security.len() as u32).to_be_bytes().to_vec();
677        plain.extend(security);
678        plain.extend(length.to_be_bytes());
679        plain.extend(tail);
680        let bad = key
681            .protect_record(&owner.provider, BUNDLE, id, [1; 32], &plain)
682            .unwrap();
683        assert!(Workspace::restore_with_attachment(&key, [1; 32], id, &bad).is_err());
684    }
685}
686
687/// Explicit capacity gate: diagnostics report sizes only, never keys or payloads.
688#[test]
689fn twelve_member_snapshot_capacity() {
690    let key = StorageKey::derive(&[201; 32]).unwrap();
691    let mut owner = Workspace::create([200; 32], "Capacity publisher").unwrap();
692    for member in 1..12u8 {
693        let (invite, checkpoint) = owner.issue_invitation().unwrap();
694        let pending = super::PendingJoin::from_invitation(
695            &invite,
696            &checkpoint,
697            [member; 32],
698            "Capacity member",
699        )
700        .unwrap();
701        let next = owner
702            .prepare_admission([member; 32], pending.admission_request().unwrap())
703            .unwrap()
704            .workspace;
705        let state = next.provider.storage().values.read().unwrap();
706        let provider_bytes: usize = 4 + state
707            .iter()
708            .map(|(k, v)| 8 + k.len() + v.len())
709            .sum::<usize>();
710        let reply_bytes: usize = next
711            .admissions
712            .iter()
713            .map(|a| 96 + 8 + 32 + 64 + 64 + 8 + a.reply.commit.len() + a.reply.welcome.len())
714            .sum();
715        let history_bytes = next
716            .join_history
717            .as_ref()
718            .map_or(0, |h| 4 + h.inline(next.id()).unwrap().len());
719        println!(
720            "members={} provider_records={} provider_bytes={} retained_reply_bytes={} history_bytes={} snapshot_limit={}",
721            next.member_count(),
722            state.len(),
723            provider_bytes,
724            reply_bytes,
725            history_bytes,
726            MAX_PLAIN
727        );
728        drop(state);
729        let sealed = next.seal(&key).expect("12-member durable snapshot gate");
730        owner = Workspace::restore(&key, [200; 32], next.id(), &sealed).unwrap();
731    }
732    assert_eq!(owner.member_count(), 12);
733}