Skip to main content

arachne_security/
lib.rs

1//! Portable workspace security owner. No ATAK, transport or payload types.
2//! Legacy hosts persist encrypted snapshots; trusted native adapters can persist
3//! separate secret-bearing records in an authenticated encrypted store.
4mod bootstrap;
5mod history;
6mod records;
7pub use records::SecurityRecords;
8mod admission;
9pub use admission::{
10    AdmissionAttempt, AdmissionEnqueue, AdmissionQueue, AdmissionQueueError,
11    MAX_ADMISSION_QUEUE_BYTES, MAX_ADMISSION_QUEUE_ITEMS,
12};
13mod management;
14mod name;
15pub use name::{
16    MAX_WORKSPACE_NAME_CHECKPOINT, MAX_WORKSPACE_NAME_RECORD, PreparedWorkspaceName,
17    PreparedWorkspaceNameCheckpoint, validate_workspace_name,
18};
19mod profile;
20pub use profile::{MAX_MEMBER_PROFILE, MemberIdentity};
21mod removed;
22pub use management::{ManagementAction, PreparedManagement, PreparedManagementUpdate};
23pub use removed::{MAX_SEALED_REMOVAL, RemovedMembership};
24mod message;
25mod object;
26pub use object::AuthenticatedObject;
27mod recovery;
28pub use message::{
29    ApplicationMessage, MAX_APPLICATION_CIPHERTEXT, MAX_APPLICATION_CONTEXT,
30    MAX_APPLICATION_PAYLOAD,
31};
32pub use recovery::{
33    MAX_RECOVERY_PACKETS, RecoveryCutoffRequest, RecoveryRequest, VerifiedRecoveryOffer,
34};
35mod invitation;
36mod invitation_controls;
37pub use invitation_controls::{
38    INVITATION_APPROVAL_REQUIRED, INVITATION_AUTOMATIC_APPROVAL_REQUIRED, INVITATION_DISABLED,
39    INVITATION_EXPIRED, InvitationControl,
40};
41mod pending;
42pub use invitation::{
43    AdmissionAssessment, AdmissionReply, Invitation, PreparedAdmission, PreparedAdmissionBatch,
44    ValidatedAdmission,
45};
46mod storage;
47pub use bootstrap::{
48    AdmissionAuthorization, HISTORY_CHUNK_STEPS, JoinProof, MAX_JOIN_HISTORY_BYTES,
49    MAX_JOIN_HISTORY_STEPS, MembershipAuthorization, MembershipVerifier,
50};
51use openmls::prelude::*;
52use openmls_basic_credential::SignatureKeyPair;
53use openmls_rust_crypto::OpenMlsRustCrypto;
54use openmls_traits::{OpenMlsProvider, random::OpenMlsRand};
55pub use pending::{MAX_WELCOME, PendingJoin};
56pub use storage::{MAX_SEALED_BUNDLE, MAX_SEALED_WORKSPACE, MAX_WORKSPACE_ATTACHMENT, StorageKey};
57
58const SUITE: Ciphersuite = Ciphersuite::MLS_128_DHKEMX25519_AES128GCM_SHA256_Ed25519;
59const AUTHORITY: u16 = 0xff00; // Candidate encoding shared with admission experiment.
60pub const MAX_ADMISSION_BATCH: usize = 128;
61
62/// Workspace-scoped identity and chosen local display name. Names are not credentials.
63#[derive(Clone, Debug, PartialEq, Eq)]
64pub struct MemberProfile {
65    id: [u8; 32],
66    display_name: String,
67    service: bool,
68}
69impl MemberProfile {
70    fn new(id: [u8; 32], name: &str) -> Result<Self, &'static str> {
71        Self::new_kind(id, name, false)
72    }
73    fn new_kind(id: [u8; 32], name: &str, service: bool) -> Result<Self, &'static str> {
74        let name = name.trim();
75        if name.is_empty() || name.len() > 256 || name.chars().count() > 80
76            || name.chars().any(|c| c.is_control() || matches!(c,
77                '\u{061c}' | '\u{200e}' | '\u{200f}' | '\u{202a}'..='\u{202e}' | '\u{2066}'..='\u{2069}'))
78        {
79            return Err("member name must be 1–80 characters without control characters");
80        }
81        Ok(Self {
82            id,
83            display_name: name.to_owned(),
84            service,
85        })
86    }
87    pub fn id(&self) -> [u8; 32] {
88        self.id
89    }
90    pub fn display_name(&self) -> &str {
91        &self.display_name
92    }
93    pub fn is_service(&self) -> bool {
94        self.service
95    }
96}
97
98fn credential_identity(endpoint: [u8; 32], member: Option<&MemberProfile>) -> Vec<u8> {
99    let mut identity = if let Some(member) = member {
100        let mut bytes = b"data-fabric/candidate-member/v2/".to_vec();
101        bytes.extend(member.id);
102        bytes
103    } else {
104        b"data-fabric/candidate-endpoint/v1/".to_vec()
105    };
106    identity.extend(endpoint);
107    identity
108}
109
110/// Owns cryptographic state without exposing OpenMLS objects. Secret-bearing
111/// storage records are restricted to the trusted native persistence seam.
112pub struct Workspace {
113    provider: OpenMlsRustCrypto,
114    _signer: SignatureKeyPair,
115    group: MlsGroup,
116    id: [u8; 32],
117    endpoint: [u8; 32],
118    member: Option<MemberProfile>,
119    admissions: Vec<invitation::RetainedAdmission>,
120    join_history: Option<history::MembershipHistory>,
121    invitation_checkpoints: Vec<invitation::RetainedInvitationCheckpoint>,
122}
123
124/// Bytes held by one workspace's state, by part. Diagnostic only: it counts
125/// payload bytes, not allocator overhead.
126#[derive(Debug, Default, Clone, Copy)]
127pub struct MemoryReport {
128    pub records: usize,
129    pub record_bytes: usize,
130    pub history_steps: usize,
131    pub history_bytes: usize,
132    pub admissions: usize,
133    pub admission_bytes: usize,
134    pub checkpoint_bytes: usize,
135}
136
137impl Workspace {
138    pub fn memory_report(&self) -> MemoryReport {
139        let mut report = MemoryReport::default();
140        if let Ok(values) = self.provider.storage().values.read() {
141            report.records = values.len();
142            report.record_bytes = values.iter().map(|(key, value)| key.len() + value.len()).sum();
143        }
144        if let Some(history) = &self.join_history {
145            report.history_steps = history.steps.len();
146            report.history_bytes = history.checkpoint.len() + history.steps.iter().map(|(_, commit)| commit.len()).sum::<usize>();
147        }
148        report.admissions = self.admissions.len();
149        // Shared batch bytes count once: the number is the memory held.
150        let mut seen = std::collections::HashSet::new();
151        for admission in &self.admissions {
152            for bytes in [&admission.reply.commit, &admission.reply.welcome] {
153                if seen.insert(bytes.as_ptr()) {
154                    report.admission_bytes += bytes.len();
155                }
156            }
157        }
158        report.checkpoint_bytes = self.invitation_checkpoints.iter().map(|checkpoint| checkpoint.checkpoint.len()).sum();
159        report
160    }
161
162    pub fn create_named(
163        endpoint: [u8; 32],
164        display_name: &str,
165        workspace_name: Option<&str>,
166    ) -> Result<Self, &'static str> {
167        let owner = Self::create(endpoint, display_name)?;
168        match workspace_name {
169            Some(name) => Ok(owner.prepare_workspace_name(name)?.workspace),
170            None => Ok(owner),
171        }
172    }
173    pub fn create(endpoint: [u8; 32], display_name: &str) -> Result<Self, &'static str> {
174        if endpoint == [0; 32] {
175            return Err("invalid workspace-facing endpoint");
176        }
177        let provider = OpenMlsRustCrypto::default();
178        let member = MemberProfile::new(
179            provider
180                .rand()
181                .random_array::<32>()
182                .map_err(|_| "member randomness failed")?,
183            display_name,
184        )?;
185        let id = provider
186            .rand()
187            .random_array::<32>()
188            .map_err(|_| "workspace randomness failed")?;
189        let signer = SignatureKeyPair::new(SUITE.signature_algorithm())
190            .map_err(|_| "credential creation failed")?;
191        signer
192            .store(provider.storage())
193            .map_err(|_| "credential storage failed")?;
194        let identity = credential_identity(endpoint, Some(&member));
195        let credential = CredentialWithKey {
196            credential: BasicCredential::new(identity).into(),
197            signature_key: signer.to_public_vec().into(),
198        };
199        let mut authority = vec![1, 1];
200        authority.extend(signer.public());
201        let extensions = Extensions::from_vec(vec![
202            Extension::Unknown(AUTHORITY, UnknownExtension(authority)),
203            Extension::RequiredCapabilities(RequiredCapabilitiesExtension::new(
204                &[ExtensionType::Unknown(AUTHORITY)],
205                &[],
206                &[],
207            )),
208        ])
209        .map_err(|_| "invalid workspace extensions")?;
210        let config = MlsGroupCreateConfig::builder()
211            .ciphersuite(SUITE)
212            // Public MLS handshakes permit invitation checkpoint replay. They
213            // contain roster metadata and require an authorized outer channel.
214            // MLS application messages remain PrivateMessage ciphertext.
215            .wire_format_policy(PURE_PLAINTEXT_WIRE_FORMAT_POLICY)
216            .use_ratchet_tree_extension(true)
217            .capabilities(Capabilities::new(
218                None,
219                None,
220                Some(&[ExtensionType::Unknown(AUTHORITY)]),
221                None,
222                None,
223            ))
224            .with_group_context_extensions(extensions)
225            .build();
226        let group = MlsGroup::new_with_group_id(
227            &provider,
228            &signer,
229            &config,
230            GroupId::from_slice(&id),
231            credential,
232        )
233        .map_err(|_| "workspace creation failed")?;
234        Ok(Self {
235            provider,
236            _signer: signer,
237            group,
238            id,
239            endpoint,
240            member: Some(member),
241            admissions: Vec::new(),
242            join_history: None,
243            invitation_checkpoints: Vec::new(),
244        })
245    }
246
247    /// None identifies a legacy snapshot without a chosen member profile.
248    pub fn member(&self) -> Option<&MemberProfile> {
249        self.member.as_ref()
250    }
251    pub fn id(&self) -> [u8; 32] {
252        self.id
253    }
254    /// This owner's workspace-scoped transport identity, not a device-global ID.
255    pub fn endpoint(&self) -> [u8; 32] {
256        self.endpoint
257    }
258    pub fn epoch(&self) -> u64 {
259        self.group.epoch().as_u64()
260    }
261    /// Compare accepted epochs between already authenticated workspace members.
262    /// Equality is not authority, global finality, or a branch-merge decision.
263    pub fn epoch_fingerprint(&self) -> [u8; 32] {
264        use sha2::{Digest, Sha256};
265        let mut hash = Sha256::new();
266        hash.update(b"data-fabric/epoch-fingerprint/v1\0");
267        hash.update(self.id);
268        hash.update(self.epoch().to_be_bytes());
269        hash.update(self.group.epoch_authenticator().as_slice());
270        hash.finalize().into()
271    }
272    /// Verified workspace-facing transport endpoints for a routing projection.
273    /// This is membership, not topic permission or a global device directory.
274    pub fn member_endpoints(&self) -> Result<Vec<[u8; 32]>, &'static str> {
275        self.group
276            .members()
277            .map(|member| {
278                let credential = BasicCredential::try_from(member.credential)
279                    .map_err(|_| "unsupported member credential")?;
280                let identity = credential
281                    .identity()
282                    .strip_prefix(b"data-fabric/candidate-member/v2/")
283                    .filter(|identity| identity.len() == 64)
284                    .ok_or("member identity binding required")?;
285                Ok(identity[32..].try_into().unwrap())
286            })
287            .collect()
288    }
289
290    /// Resolve a canonical direct recipient scope through the accepted roster.
291    /// Endpoint keys are a transport result, never caller supplied authority.
292    pub fn endpoints_for_members(
293        &self,
294        members: &[[u8; 32]],
295    ) -> Result<Vec<[u8; 32]>, &'static str> {
296        if members.is_empty()
297            || members.len() > 64
298            || members.windows(2).any(|pair| pair[0] >= pair[1])
299        {
300            return Err("invalid direct recipient scope");
301        }
302        let bindings: Vec<_> = self
303            .group
304            .members()
305            .map(|member| bootstrap::binding(&member.credential))
306            .collect::<Result<_, _>>()?;
307        members
308            .iter()
309            .map(|member| {
310                bindings
311                    .iter()
312                    .find_map(|(id, endpoint)| (id == member).then_some(*endpoint))
313                    .ok_or("direct recipient is not a current member")
314            })
315            .collect()
316    }
317
318    pub fn member_count(&self) -> usize {
319        self.group.members().count()
320    }
321}
322
323#[test]
324fn creation_owns_distinct_groups_and_initial_authority() {
325    assert!(Workspace::create([0; 32], "Alex").is_err());
326    let a = Workspace::create([1; 32], "Alex").unwrap();
327    let b = Workspace::create([2; 32], "Alex").unwrap();
328    assert_ne!(a.id(), b.id());
329    assert_ne!(a.member().unwrap().id(), b.member().unwrap().id());
330    assert_ne!(a.member().unwrap().id(), a.id());
331    assert_ne!(a.member().unwrap().id(), a.endpoint);
332    assert_eq!(
333        a.member().unwrap().display_name(),
334        b.member().unwrap().display_name()
335    );
336    assert_eq!(
337        MemberProfile::new([1; 32], "  Álex Morgan  ")
338            .unwrap()
339            .display_name(),
340        "Álex Morgan"
341    );
342    for name in [
343        "",
344        "  ",
345        "Alex\nMorgan",
346        "Alex\u{202e}Morgan",
347        &"a".repeat(81),
348        &"😀".repeat(65),
349    ] {
350        assert!(Workspace::create([1; 32], name).is_err());
351    }
352    assert_eq!(a.epoch(), 0);
353    assert_eq!(a.member_count(), 1);
354    let admins = &a.group.extensions().unknown(AUTHORITY).unwrap().0;
355    assert_eq!(&admins[..2], &[1, 1]);
356    assert_eq!(&admins[2..], a._signer.public());
357}