Skip to main content

umbera_core/
lib.rs

1// umbera_core — anonymous group crypto core (MLS, RFC 9420).
2//
3// Shared Rust core: ONE implementation powers Android (uniffi→Kotlin) now and iOS
4// (uniffi→Swift) later. It does ONLY cryptography (no network): create groups, add/
5// remove members (producing Commit+Welcome), process incoming handshake/application
6// messages, encrypt/decrypt application payloads, export per-call media secrets, and
7// serialize/restore the whole group state for our SQLCipher store.
8//
9// The transport (anonymous pairwise-rendezvous fan-out) lives in Kotlin/Swift; this
10// crate is transport-agnostic — it hands back opaque bytes to send and consumes opaque
11// bytes received.
12
13use std::sync::Mutex;
14
15use openmls::prelude::*;
16use openmls_basic_credential::SignatureKeyPair;
17use serde::{Deserialize, Serialize};
18use tls_codec::{Deserialize as TlsDeserialize, Serialize as TlsSerialize};
19
20uniffi::setup_scaffolding!();
21
22// AMF message-franking crypto (verifiable abuse reports; server stays blind). See amf.rs.
23// pub so an offline moderation tool can call amf_judge/amf_commit (that tool holds the judge private key).
24pub mod amf;
25
26// audit C-7: metadata scrubbing for outgoing PDFs. Not cryptography — it lives here
27// because neither platform ships a PDF writer, and one copy cannot drift. See pdf.rs.
28pub mod pdf;
29
30// KMP-prep phase 6: 1:1 crypto primitives (Argon2id, AES-GCM, X25519, secp256k1,
31// Ed25519, HKDF, SHA-256/PBKDF2, ML-KEM, ML-DSA). See primitives.rs.
32pub mod primitives;
33
34// Linked devices: QR linking, device certificate, transfer bundle,
35// Communities vault root, desktop joining MLS groups as a separate leaf. See devlink/mod.rs.
36pub mod devlink;
37
38// Provider with X-Wing for new groups; the legacy suite stays on plain RustCrypto.
39pub mod provider;
40
41// Hybrid call-frame key (X25519 + ML-KEM-1024) delivered over the message channel.
42pub mod callkey;
43// Reference implementation of the v3 / v3s envelope and the v2 file key (tests only, not part of the library).
44mod sealv3;
45use provider::{UmberaProvider, LEGACY_SUITE, XWING_SUITE};
46
47/// Default suite wherever no suite is chosen explicitly (legacy FFI calls): X25519 + AES-128-GCM +
48/// SHA-256 + Ed25519 — what all store builds use. New groups and key packages for X-Wing
49/// are created via explicit `*_for(suite)` calls; the app picks the suite from members' capabilities.
50const CIPHERSUITE: Ciphersuite = LEGACY_SUITE;
51
52/// Legacy suite code (0x0001), exposed to the app.
53#[uniffi::export]
54pub fn mls_suite_legacy() -> u16 {
55    LEGACY_SUITE as u16
56}
57
58/// X-Wing suite code (0x004D, X25519 + ML-KEM-768), exposed to the app.
59#[uniffi::export]
60pub fn mls_suite_xwing() -> u16 {
61    XWING_SUITE as u16
62}
63
64fn suite_from(code: u16) -> R<Ciphersuite> {
65    match code {
66        c if c == LEGACY_SUITE as u16 => Ok(LEGACY_SUITE),
67        c if c == XWING_SUITE as u16 => Ok(XWING_SUITE),
68        c => Err(MlsError::Generic(format!("unsupported ciphersuite 0x{c:04x}"))),
69    }
70}
71
72/// What is known about a key package before adding it: suite and its leaf's memberId (signature verified).
73#[derive(uniffi::Record)]
74pub struct KeyPackageInfo {
75    pub ciphersuite: u16,
76    pub identity: Vec<u8>,
77    /// The core supports X-Wing (the leaf advertised the suite in its capabilities).
78    pub supports_xwing: bool,
79}
80
81/// Parse and validate a key package (signature, lifetime, suite) without a group.
82#[uniffi::export]
83pub fn key_package_info(key_package: Vec<u8>) -> R<KeyPackageInfo> {
84    let provider = UmberaProvider::default();
85    let kp = KeyPackageIn::tls_deserialize_exact(&key_package)
86        .mls()?
87        .validate(provider.crypto(), ProtocolVersion::Mls10)
88        .mls()?;
89    let leaf = kp.leaf_node();
90    Ok(KeyPackageInfo {
91        ciphersuite: kp.ciphersuite() as u16,
92        identity: leaf.credential().serialized_content().to_vec(),
93        supports_xwing: supports_suite(leaf.capabilities(), XWING_SUITE),
94    })
95}
96
97/// Hard cap on group membership, enforced at the CRYPTO layer (audit finding #1).
98///
99/// The blind relay has no notion of a "group" — it only forwards opaque pairwise
100/// rendezvous entries — so it physically cannot enforce a member cap without learning
101/// which rendezvous belong to one group, which would break anonymity (Law 0). Instead
102/// every honest client enforces the cap on its own MLS state: it REFUSES to merge any
103/// Commit that would push the group past this size (the epoch does not advance), so a
104/// malicious admin cannot force the (cap+1)-th member onto honest devices. The server
105/// learns nothing — anonymity is untouched.
106///
107/// Linked devices: a person now has up to 5 leaves (phone + 4 desktops), so
108/// the core limit counts LEAVES: up to [MAX_GROUP_LEAVES]; the app counts the "20 people" limit per person
109/// (leaves of one account are tied by sibling signatures, devlink::mlsjoin). But phones on the old
110/// core (20-leaf limit) reject a Commit that takes the group above 20 leaves: their epoch
111/// diverges and the group breaks for them. Hence more than [LEGACY_LEAF_CAP] leaves
112/// are allowed only if ALL leaves of the group (and those being added) advertise the
113/// [MULTI_DEVICE_CAPABILITY] extension in capabilities, i.e. run the new core. Otherwise the old limit of 20 applies. The rule
114/// is the same on the sender (add_members) and the receiver (process_incoming).
115pub const MAX_GROUP_MEMBERS: usize = LEGACY_LEAF_CAP;
116
117/// Leaf limit while any member lacks the new-core marker (= the old limit).
118pub const LEGACY_LEAF_CAP: usize = 20;
119
120/// Leaf limit when all leaves run the new core: 20 people × (phone + 4 desktops).
121pub const MAX_GROUP_LEAVES: usize = 100;
122
123/// "Core supports linked devices" marker in a leaf's capabilities: an extension type from the
124/// private-use range (RFC 9420 §17.3, 0xF000–0xFFFF). Old clients parse it
125/// as an unknown type and ignore it.
126pub const MULTI_DEVICE_CAPABILITY: u16 = 0xF0D1;
127
128/// "Core supports X-Wing groups" marker in a leaf's capabilities, RFC 9420 private range.
129///
130/// Advertising the X-Wing suite (0x004D) in capabilities does NOT prove support: the store-build core
131/// (OpenMLS 0.6) lists it by default even though its provider cannot do X-Wing
132/// (`openmls_rust_crypto` 0.3: "XWing is not supported"). So only this marker counts — it is set
133/// only by a core with an X-Wing provider (src/provider.rs). Old cores skip the unknown extension.
134pub const XWING_CAPABILITY: u16 = 0xF0D2;
135
136/// Suites a leaf advertises: exactly the openmls default list of the store-build core (without this,
137/// openmls 0.9 with the PQ feature would advertise a dozen draft suites we do not implement).
138const OUR_SUITES: [Ciphersuite; 4] = [
139    LEGACY_SUITE,
140    Ciphersuite::MLS_128_DHKEMP256_AES128GCM_SHA256_P256,
141    Ciphersuite::MLS_128_DHKEMX25519_CHACHA20POLY1305_SHA256_Ed25519,
142    XWING_SUITE,
143];
144
145fn our_capabilities() -> Capabilities {
146    Capabilities::new(
147        None,
148        Some(&OUR_SUITES),
149        Some(&[ExtensionType::Unknown(MULTI_DEVICE_CAPABILITY), ExtensionType::Unknown(XWING_CAPABILITY)]),
150        None,
151        None,
152    )
153}
154
155fn has_xwing_marker(caps: &Capabilities) -> bool {
156    caps.extensions().contains(&ExtensionType::Unknown(XWING_CAPABILITY))
157}
158
159/// Whether a leaf actually supports [suite]: legacy — all leaves; X-Wing — only with the [XWING_CAPABILITY] marker.
160fn supports_suite(caps: &Capabilities, suite: Ciphersuite) -> bool {
161    match suite {
162        XWING_SUITE => has_xwing_marker(caps) && caps.ciphersuites().iter().any(|c| *c == VerifiableCiphersuite::from(suite)),
163        _ => caps.ciphersuites().iter().any(|c| *c == VerifiableCiphersuite::from(suite)),
164    }
165}
166
167/// Whether all current leaves of the group support [suite].
168fn all_leaves_support(group: &MlsGroup, suite: Ciphersuite) -> R<bool> {
169    let v = serde_json::to_value(group.export_ratchet_tree()).mls()?;
170    let nodes: Vec<Option<Node>> = serde_json::from_value(v).mls()?;
171    Ok(nodes.iter().all(|n| match n {
172        Some(Node::LeafNode(l)) => supports_suite(l.capabilities(), suite),
173        _ => true,
174    }))
175}
176
177fn has_marker(caps: &Capabilities) -> bool {
178    caps.extensions().contains(&ExtensionType::Unknown(MULTI_DEVICE_CAPABILITY))
179}
180
181/// Whether all current leaves of the group advertise the new-core marker.
182fn all_leaves_marked(group: &MlsGroup) -> R<bool> {
183    // MlsGroup has no public access to other members' leaves; the tree is exported
184    // as a public type and parsed back into public Node/LeafNode (serde of the same openmls).
185    let v = serde_json::to_value(group.export_ratchet_tree()).mls()?;
186    let nodes: Vec<Option<Node>> = serde_json::from_value(v).mls()?;
187    Ok(nodes.iter().all(|n| match n {
188        Some(Node::LeafNode(l)) => has_marker(l.capabilities()),
189        _ => true,
190    }))
191}
192
193/// How many leaves are allowed after a Commit.
194fn leaf_limit(group: &MlsGroup, added_all_marked: bool) -> R<usize> {
195    Ok(if added_all_marked && all_leaves_marked(group)? { MAX_GROUP_LEAVES } else { LEGACY_LEAF_CAP })
196}
197
198#[derive(Debug, thiserror::Error, uniffi::Error)]
199pub enum MlsError {
200    #[error("mls: {0}")]
201    Generic(String),
202}
203type R<T> = Result<T, MlsError>;
204
205/// `.mls()?` turns any error into [MlsError] without the reflexive-From conflict a
206/// blanket `impl From` would cause.
207trait IntoMls<T> {
208    fn mls(self) -> R<T>;
209}
210impl<T, E: std::fmt::Display> IntoMls<T> for Result<T, E> {
211    fn mls(self) -> R<T> {
212        self.map_err(|e| MlsError::Generic(e.to_string()))
213    }
214}
215
216/// What `add_members` hands back: the Commit to fan out to EXISTING members, and the
217/// Welcome to send to the NEW members (both already MLS-encrypted).
218/// Anti-equivocation: recompute the public "quant address" from a peer's classical
219/// (secp256k1) + Dilithium public keys, EXACTLY as the server computes it, so a client can check
220/// resolved keys against an address it got out of band: raw = BLAKE3(classical || dilithium); checksum = BLAKE3(raw)[:4];
221/// address = "quant" + base58(raw || checksum).
222///
223/// The client uses this to verify, with ZERO trust in any server, that the keys a (possibly malicious)
224/// peer-home-server returned actually hash to the address the user obtained out-of-band. A mismatch ⇒ the
225/// server tried to substitute keys ⇒ reject. Inputs are hex (as the server returns them).
226#[uniffi::export]
227pub fn quant_address(classical_hex: String, dilithium_hex: String) -> Result<String, MlsError> {
228    let cb = unhex(classical_hex.trim())?;
229    let db = unhex(dilithium_hex.trim())?;
230    let mut h = blake3::Hasher::new();
231    h.update(&cb);
232    h.update(&db);
233    let raw = h.finalize();
234    let raw = raw.as_bytes(); // 32 bytes
235    let cs = blake3::hash(raw);
236    let mut payload = Vec::with_capacity(36);
237    payload.extend_from_slice(raw);
238    payload.extend_from_slice(&cs.as_bytes()[..4]);
239    Ok(format!("quant{}", bs58::encode(payload).into_string()))
240}
241
242#[derive(uniffi::Record)]
243pub struct CommitBundle {
244    pub commit: Vec<u8>,
245    pub welcome: Vec<u8>,
246}
247
248/// Classified result of feeding an inbound MLS message to the group.
249#[derive(uniffi::Enum)]
250pub enum Incoming {
251    /// A decrypted application payload (a real chat message/control).
252    ///
253    /// `sender_identity` is the AUTHENTICATED sender: the credential OpenMLS verified
254    /// while decrypting, whose serialized content is that member's leaf id (the same
255    /// bytes `members()` returns as `identity`, i.e. the app's memberId).
256    ///
257    /// It exists because MLS on its own only proves "SOME member of this epoch sent
258    /// this". The application layer used to take the sender from a field inside the
259    /// decrypted payload — a value the sender picks freely — and gate admin actions on
260    /// it, so any member could claim to be an admin (audit K-1). Handing the verified
261    /// identity out lets the caller reject a payload whose claimed sender isn't the one
262    /// MLS authenticated.
263    Application {
264        plaintext: Vec<u8>,
265        sender_identity: Vec<u8>,
266    },
267    /// A membership change (Commit) was applied; the epoch advanced.
268    CommitApplied,
269    /// A Commit was REFUSED because it would push the group past MAX_GROUP_MEMBERS
270    /// (audit finding #1). It was NOT merged — the epoch did not advance — so a hostile
271    /// admin cannot force an over-cap member onto this honest client.
272    CommitRejected,
273    /// A proposal was stored (awaiting a Commit). Nothing to show yet.
274    Proposal,
275    /// Our own message echoed back / not for us / stale epoch — ignore.
276    Ignored,
277}
278
279#[derive(uniffi::Record)]
280pub struct MemberInfo {
281    pub leaf_index: u32,
282    pub identity: Vec<u8>,
283}
284
285/// Persisted identity+groups blob (everything needed to resume on a fresh device).
286#[derive(Serialize, Deserialize)]
287struct PersistState {
288    identity: Vec<u8>,
289    signer: Vec<u8>, // SignatureKeyPair tls-serialized
290    storage: Vec<(String, String)>, // MemoryStorage key→value (hex)
291}
292
293/// One MLS identity + its groups. uniffi Object (Arc on the Kotlin/Swift side).
294#[derive(uniffi::Object)]
295pub struct MlsClient {
296    inner: Mutex<Inner>,
297}
298
299struct Inner {
300    provider: UmberaProvider,
301    signer: SignatureKeyPair,
302    identity: Vec<u8>,
303}
304
305fn hex(b: &[u8]) -> String {
306    b.iter().map(|x| format!("{:02x}", x)).collect()
307}
308/// Panic-free hex parsing: odd length and any non-hex character (including non-ASCII) is an error, not a slice
309/// through the middle of a character (`&s[i..i + 2]` used to panic on `from_state` / `quant_address`).
310fn unhex(s: &str) -> R<Vec<u8>> {
311    fn nib(c: u8) -> Option<u8> {
312        match c {
313            b'0'..=b'9' => Some(c - b'0'),
314            b'a'..=b'f' => Some(c - b'a' + 10),
315            b'A'..=b'F' => Some(c - b'A' + 10),
316            _ => None,
317        }
318    }
319    let b = s.as_bytes();
320    if b.len() % 2 != 0 {
321        return Err(MlsError::Generic("hex: odd length".into()));
322    }
323    b.chunks_exact(2)
324        .map(|p| match (nib(p[0]), nib(p[1])) {
325            (Some(h), Some(l)) => Ok(h << 4 | l),
326            _ => Err(MlsError::Generic("hex: invalid digit".into())),
327        })
328        .collect()
329}
330
331// Private helpers (NOT exported over FFI).
332impl MlsClient {
333    /// Core lock that never fails permanently. uniffi turns a Rust panic into an FFI error, but
334    /// a panic under `lock().unwrap()` poisoned the Mutex, and EVERY subsequent call (all groups) failed until the
335    /// process restarted: one panic while parsing a foreign frame = remote denial of service of the group core.
336    ///
337    /// Deliberate: after a panic we clear the poison and continue. The state is the in-memory openmls store; a group
338    /// is reloaded from it on every call (`load_group`) rather than kept between calls, so an interrupted
339    /// call loses only its own unwritten `MlsGroup`. Store writes are per key (one insert into a HashMap under its own
340    /// RwLock), so a half-written key cannot occur; if a panic hits between writes of one operation, only that
341    /// group fails (its `load_group` returns an error), the rest keep working. Persisting to disk (export_state) —
342    /// always from this same store.
343    fn lock(&self) -> std::sync::MutexGuard<'_, Inner> {
344        self.inner.lock().unwrap_or_else(|poisoned| {
345            self.inner.clear_poison();
346            poisoned.into_inner()
347        })
348    }
349
350    fn cwk(g: &Inner) -> CredentialWithKey {
351        let credential = BasicCredential::new(g.identity.clone());
352        CredentialWithKey {
353            credential: credential.into(),
354            signature_key: g.signer.public().into(),
355        }
356    }
357
358    fn load_group(g: &Inner, gid: &[u8]) -> R<MlsGroup> {
359        let mut group = MlsGroup::load(g.provider.storage(), &GroupId::from_slice(gid))
360            .mls()?
361            .ok_or_else(|| MlsError::Generic("group not found".into()))?;
362        // Groups created before OpenMLS 0.9 (and by the store-build core) keep the default window —
363        // 5 messages. Apply our window on first load; leave the rest of the config untouched.
364        if *group.configuration().sender_ratchet_configuration() != sender_ratchet_config() {
365            let cfg = with_our_ratchet(group.configuration())?;
366            group.set_configuration(g.provider.storage(), &cfg).mls()?;
367        }
368        Ok(group)
369    }
370}
371
372/// Sender ratchet window (SenderRatchetConfiguration) for all our groups.
373///
374/// OpenMLS 0.7.1 fixed GHSA-qr9h-x63w-vqfm: after decryption the secret tree is persisted and
375/// the used key is erased (replaying the same ciphertext no longer decrypts — that is
376/// the fix). Side effect: a late message from a sender decrypts only if
377/// it lags the newest one received from that sender by at most `out_of_order_tolerance`.
378/// The default is 5. On 0.6 keys were not persisted and any order worked. Our transport
379/// does not guarantee ordering (multiple delivery paths, offline queue), so the window is 1000, same as
380/// the forward distance: anything the receiver could decrypt "ahead" it can also decrypt late.
381/// Cost: up to 1000 keys per sender in the state, and only for messages actually skipped;
382/// received ones are kept as an empty marker.
383pub const OUT_OF_ORDER_TOLERANCE: u32 = 1000;
384/// Forward distance — the OpenMLS default (as on 0.6).
385pub const MAXIMUM_FORWARD_DISTANCE: u32 = 1000;
386
387fn sender_ratchet_config() -> SenderRatchetConfiguration {
388    SenderRatchetConfiguration::new(OUT_OF_ORDER_TOLERANCE, MAXIMUM_FORWARD_DISTANCE)
389}
390
391/// The same group config, but with our ratchet window. Via serde: MlsGroupJoinConfig has no
392/// "from existing" constructor, and this way all fields (wire format, padding, past epochs…) carry over
393/// as is, even if OpenMLS adds new ones.
394fn with_our_ratchet(c: &MlsGroupJoinConfig) -> R<MlsGroupJoinConfig> {
395    let mut v = serde_json::to_value(c).mls()?;
396    let obj = v
397        .as_object_mut()
398        .ok_or_else(|| MlsError::Generic("join config: not an object".into()))?;
399    obj.insert(
400        "sender_ratchet_configuration".into(),
401        serde_json::to_value(sender_ratchet_config()).mls()?,
402    );
403    serde_json::from_value(v).mls()
404}
405
406#[uniffi::export]
407impl MlsClient {
408    /// Brand-new identity. `identity` = our stable per-group leaf id bytes (memberId).
409    #[uniffi::constructor]
410    pub fn new(identity: Vec<u8>) -> R<std::sync::Arc<MlsClient>> {
411        let provider = UmberaProvider::default();
412        let signer = SignatureKeyPair::new(CIPHERSUITE.signature_algorithm()).mls()?;
413        signer.store(provider.storage()).mls()?;
414        Ok(std::sync::Arc::new(MlsClient {
415            inner: Mutex::new(Inner {
416                provider,
417                signer,
418                identity,
419            }),
420        }))
421    }
422
423    /// Restore from a previously exported state blob (see [export_state]).
424    #[uniffi::constructor]
425    pub fn from_state(blob: Vec<u8>) -> R<std::sync::Arc<MlsClient>> {
426        let st: PersistState = serde_json::from_slice(&blob).mls()?;
427        let provider = UmberaProvider::default();
428        {
429            let store = provider.storage();
430            let mut map = store
431                .values
432                .write()
433                .map_err(|_| MlsError::Generic("storage lock".into()))?;
434            for (k, v) in &st.storage {
435                map.insert(unhex(k)?, unhex(v)?);
436            }
437        }
438        let signer = SignatureKeyPair::tls_deserialize_exact(&st.signer).mls()?;
439        Ok(std::sync::Arc::new(MlsClient {
440            inner: Mutex::new(Inner {
441                provider,
442                signer,
443                identity: st.identity,
444            }),
445        }))
446    }
447
448    /// Same leaf (memberId and Ed25519 signing key), but without groups or packages: for moving a group to another
449    /// suite. The signing key is unchanged, so device-link (sibling) signatures still verify
450    /// against the leaf keys of the new tree.
451    pub fn spawn_same_identity(&self) -> R<std::sync::Arc<MlsClient>> {
452        let g = self.lock();
453        let provider = UmberaProvider::default();
454        let signer = SignatureKeyPair::tls_deserialize_exact(&g.signer.tls_serialize_detached().mls()?).mls()?;
455        signer.store(provider.storage()).mls()?;
456        Ok(std::sync::Arc::new(MlsClient {
457            inner: Mutex::new(Inner {
458                provider,
459                signer,
460                identity: g.identity.clone(),
461            }),
462        }))
463    }
464
465    /// Serialize the whole identity+groups for our SQLCipher store.
466    pub fn export_state(&self) -> R<Vec<u8>> {
467        let g = self.lock();
468        let storage: Vec<(String, String)> = {
469            let map = g
470                .provider
471                .storage()
472                .values
473                .read()
474                .map_err(|_| MlsError::Generic("storage lock".into()))?;
475            map.iter().map(|(k, v)| (hex(k), hex(v))).collect()
476        };
477        let st = PersistState {
478            identity: g.identity.clone(),
479            signer: g.signer.tls_serialize_detached().mls()?,
480            storage,
481        };
482        serde_json::to_vec(&st).mls()
483    }
484
485    /// Our Ed25519 signature public key (identifies our leaf to peers).
486    pub fn signature_public_key(&self) -> Vec<u8> {
487        self.lock().signer.public().to_vec()
488    }
489
490    /// Produce a fresh KeyPackage (serialized) to hand to whoever will add us to a group.
491    pub fn generate_key_package(&self) -> R<Vec<u8>> {
492        self.generate_key_package_for(CIPHERSUITE as u16)
493    }
494
495    /// Key package in suite [suite] ([mls_suite_legacy] or [mls_suite_xwing]). The same leaf (memberId and
496    /// signing key) can issue packages in both suites: the inviter picks the one that fits the group.
497    pub fn generate_key_package_for(&self, suite: u16) -> R<Vec<u8>> {
498        let suite = suite_from(suite)?;
499        let g = self.lock();
500        let bundle = KeyPackage::builder()
501            .leaf_node_capabilities(our_capabilities())
502            .build(suite, &g.provider, &g.signer, Self::cwk(&g))
503            .mls()?;
504        bundle.key_package().tls_serialize_detached().mls()
505    }
506
507    /// Group suite (RFC 9420 code).
508    pub fn group_ciphersuite(&self, gid: Vec<u8>) -> R<u16> {
509        let g = self.lock();
510        let group = Self::load_group(&g, &gid)?;
511        Ok(group.ciphersuite() as u16)
512    }
513
514    /// Whether all leaves of the group advertise support for [suite] (i.e. every member runs a core that
515    /// supports it). The app uses this to decide whether the group can be moved to X-Wing.
516    pub fn members_support(&self, gid: Vec<u8>, suite: u16) -> R<bool> {
517        let suite = suite_from(suite)?;
518        let g = self.lock();
519        let group = Self::load_group(&g, &gid)?;
520        all_leaves_support(&group, suite)
521    }
522
523    /// Create a new group with our chosen 32-byte group id (`gid`). We become the
524    /// single initial member (admin handled at the app layer, not by MLS).
525    pub fn create_group(&self, gid: Vec<u8>) -> R<()> {
526        self.create_group_for(gid, CIPHERSUITE as u16)
527    }
528
529    /// New group in suite [suite]. No state may exist under the same gid in this client.
530    pub fn create_group_for(&self, gid: Vec<u8>, suite: u16) -> R<()> {
531        let suite = suite_from(suite)?;
532        let g = self.lock();
533        let cfg = MlsGroupCreateConfig::builder()
534            .ciphersuite(suite)
535            .capabilities(our_capabilities())
536            .use_ratchet_tree_extension(true)
537            .sender_ratchet_configuration(sender_ratchet_config())
538            .build();
539        MlsGroup::new_with_group_id(
540            &g.provider,
541            &g.signer,
542            &cfg,
543            GroupId::from_slice(&gid),
544            Self::cwk(&g),
545        )
546        .mls()?;
547        Ok(())
548    }
549
550    /// Add members by their serialized KeyPackages → returns Commit (for existing
551    /// members) + Welcome (for the new ones). We merge our own commit immediately.
552    pub fn add_members(&self, gid: Vec<u8>, key_packages: Vec<Vec<u8>>) -> R<CommitBundle> {
553        let g = self.lock();
554        let mut group = Self::load_group(&g, &gid)?;
555        // CRYPTO-LEVEL MEMBERSHIP CAP (audit finding #1): an honest admin fails CLOSED —
556        // it will not even produce a Commit that takes the group past the cap, so it can
557        // never create the over-cap fork honest members would reject anyway.
558        let current = group.members().count();
559        if current + key_packages.len() > MAX_GROUP_LEAVES {
560            return Err(MlsError::Generic(format!(
561                "group member cap ({}) exceeded: {} + {}",
562                MAX_GROUP_LEAVES,
563                current,
564                key_packages.len()
565            )));
566        }
567        let mut kps = Vec::with_capacity(key_packages.len());
568        for raw in &key_packages {
569            let kp_in = KeyPackageIn::tls_deserialize_exact(raw).mls()?;
570            let kp = kp_in
571                .validate(g.provider.crypto(), ProtocolVersion::Mls10)
572                .mls()?;
573            if kp.ciphersuite() != group.ciphersuite() {
574                return Err(MlsError::Generic(format!(
575                    "key package ciphersuite 0x{:04x} does not match the group (0x{:04x})",
576                    kp.ciphersuite() as u16,
577                    group.ciphersuite() as u16
578                )));
579            }
580            kps.push(kp);
581        }
582        let added_marked = kps.iter().all(|k| has_marker(k.leaf_node().capabilities()));
583        let limit = leaf_limit(&group, added_marked)?;
584        if current + kps.len() > limit {
585            return Err(MlsError::Generic(format!(
586                "group member cap ({}) exceeded: {} + {} (members on an old app version keep the cap at {})",
587                limit,
588                current,
589                kps.len(),
590                LEGACY_LEAF_CAP
591            )));
592        }
593        let (commit, welcome, _info) = group.add_members(&g.provider, &g.signer, &kps).mls()?;
594        group.merge_pending_commit(&g.provider).mls()?;
595        Ok(CommitBundle {
596            commit: commit.tls_serialize_detached().mls()?,
597            welcome: welcome.tls_serialize_detached().mls()?,
598        })
599    }
600
601    /// Remove members by leaf index → Commit to fan out. We merge our own commit.
602    pub fn remove_members(&self, gid: Vec<u8>, leaf_indices: Vec<u32>) -> R<Vec<u8>> {
603        let g = self.lock();
604        let mut group = Self::load_group(&g, &gid)?;
605        let idx: Vec<LeafNodeIndex> = leaf_indices.iter().map(|i| LeafNodeIndex::new(*i)).collect();
606        let (commit, _welcome, _info) = group.remove_members(&g.provider, &g.signer, &idx).mls()?;
607        group.merge_pending_commit(&g.provider).mls()?;
608        commit.tls_serialize_detached().mls()
609    }
610
611    /// Plain rekey (post-compromise security) with no membership change → Commit.
612    pub fn update_keys(&self, gid: Vec<u8>) -> R<Vec<u8>> {
613        let g = self.lock();
614        let mut group = Self::load_group(&g, &gid)?;
615        // OpenMLS 0.7+: self_update returns a CommitMessageBundle instead of a (commit, welcome, info) tuple.
616        let bundle = group
617            // Rekey also advertises the new-core marker in our leaf (a leaf created by the old
618            // core before the upgrade gets it here).
619            .self_update(&g.provider, &g.signer, LeafNodeParameters::builder().with_capabilities(our_capabilities()).build())
620            .mls()?;
621        let commit = bundle.commit().tls_serialize_detached().mls()?;
622        group.merge_pending_commit(&g.provider).mls()?;
623        Ok(commit)
624    }
625
626    /// Join a group from a Welcome we received → returns the group id we joined.
627    pub fn process_welcome(&self, welcome_bytes: Vec<u8>) -> R<Vec<u8>> {
628        let g = self.lock();
629        let msg = MlsMessageIn::tls_deserialize_exact(&welcome_bytes).mls()?;
630        let welcome = match msg.extract() {
631            MlsMessageBodyIn::Welcome(w) => w,
632            _ => return Err(MlsError::Generic("not a welcome".into())),
633        };
634        let cfg = MlsGroupJoinConfig::builder()
635            .use_ratchet_tree_extension(true)
636            .sender_ratchet_configuration(sender_ratchet_config())
637            .build();
638        // OpenMLS 0.7+ on join checks the lifetime of tree leaves that have never been
639        // updated since being added — by default 84 days from KeyPackage issuance. 0.6 had no such
640        // check. A member who has not committed for a long time (the app does not call update_keys
641        // on its own) would otherwise permanently block every newcomer on the new core. KeyPackage lifetime
642        // is still checked when adding (KeyPackageIn::validate in add_members), and signatures and
643        // everything else in the tree as well; only this check is skipped, as before the upgrade.
644        let staged = StagedWelcome::build_from_welcome(&g.provider, &cfg, welcome)
645            .mls()?
646            .skip_lifetime_validation()
647            .build()
648            .mls()?;
649        let group = staged.into_group(&g.provider).mls()?;
650        Ok(group.group_id().as_slice().to_vec())
651    }
652
653    /// Encrypt an application payload (chat message / control) for the group.
654    pub fn encrypt(&self, gid: Vec<u8>, plaintext: Vec<u8>) -> R<Vec<u8>> {
655        let g = self.lock();
656        let mut group = Self::load_group(&g, &gid)?;
657        let out = group.create_message(&g.provider, &g.signer, &plaintext).mls()?;
658        out.tls_serialize_detached().mls()
659    }
660
661    /// Feed an inbound MLS message to a group: decrypts application payloads and
662    /// applies membership Commits. Classifies the outcome.
663    pub fn process_incoming(&self, gid: Vec<u8>, message: Vec<u8>) -> R<Incoming> {
664        self.process_incoming_inner(gid, message, None).map(|(inc, _)| inc)
665    }
666
667    /// Same as `process_incoming`, plus the sender's leaf (Application, Commit, Proposal
668    /// from a member; `None` — external sender or the frame was not processed).
669    ///
670    /// `allowed_handshake_senders`: if set, a Commit/Proposal is accepted only when the credential of the sender's
671    /// leaf (verified by OpenMLS) is in this list. Otherwise the Commit is NOT merged (the epoch does not advance) —
672    /// `CommitRejected`, a Proposal — `Ignored`. This lets the app bind a Commit to the ML-DSA signer of the envelope:
673    /// a member with a valid PQ signature of their own cannot push through another leaf's Commit. `None` — no check, as before.
674    /// Application messages are not restricted by this list (their leaf is checked by the app).
675    pub fn process_incoming_with_sender(
676        &self,
677        gid: Vec<u8>,
678        message: Vec<u8>,
679        allowed_handshake_senders: Option<Vec<Vec<u8>>>,
680    ) -> R<IncomingWithSender> {
681        self.process_incoming_inner(gid, message, allowed_handshake_senders.as_deref())
682            .map(|(incoming, sender)| IncomingWithSender { incoming, sender })
683    }
684
685    /// Derive a fresh symmetric secret bound to the current epoch (e.g. a conference
686    /// media key). Rotates automatically every time the group rekeys.
687    pub fn export_secret(&self, gid: Vec<u8>, label: String, length: u32) -> R<Vec<u8>> {
688        let g = self.lock();
689        let group = Self::load_group(&g, &gid)?;
690        group
691            // OpenMLS 0.7+: the exporter needs only the crypto provider (#1786), the secret is the same.
692            .export_secret(g.provider.crypto(), &label, &[], length as usize)
693            .mls()
694    }
695
696    /// Current epoch number (advances on every membership change / rekey).
697    pub fn epoch(&self, gid: Vec<u8>) -> R<u64> {
698        let g = self.lock();
699        let group = Self::load_group(&g, &gid)?;
700        Ok(group.epoch().as_u64())
701    }
702
703    /// Member identities (leaf credential bytes = memberIds) + their leaf indices.
704    pub fn members(&self, gid: Vec<u8>) -> R<Vec<MemberInfo>> {
705        let g = self.lock();
706        let group = Self::load_group(&g, &gid)?;
707        let mut out = Vec::new();
708        for m in group.members() {
709            out.push(MemberInfo {
710                leaf_index: m.index.u32(),
711                identity: m.credential.serialized_content().to_vec(),
712            });
713        }
714        Ok(out)
715    }
716
717    /// How many leaves the group may have right now: 100 if all leaves run the new core (the
718    /// MULTI_DEVICE_CAPABILITY marker), otherwise 20. The app uses this to decide whether
719    /// desktops can be added: if they do not fit into 20 leaves and someone is still on an old version, wait.
720    pub fn leaf_limit(&self, gid: Vec<u8>) -> R<u32> {
721        let g = self.lock();
722        let group = Self::load_group(&g, &gid)?;
723        Ok(leaf_limit(&group, true)? as u32)
724    }
725
726    /// Whether our leaf carries the new-core marker. If not, run update_keys (rekey) and send the
727    /// Commit: after it the leaf advertises the marker.
728    pub fn own_leaf_marked(&self, gid: Vec<u8>) -> R<bool> {
729        let g = self.lock();
730        let group = Self::load_group(&g, &gid)?;
731        // The "new-core marker" now means both the linked-devices marker and advertised X-Wing: a leaf lacking
732        // either (issued by an old core) advertises both after a rekey.
733        Ok(group
734            .own_leaf_node()
735            .map(|l| has_marker(l.capabilities()) && supports_suite(l.capabilities(), XWING_SUITE))
736            .unwrap_or(false))
737    }
738}
739
740#[cfg(test)]
741impl MlsClient {
742    /// KeyPackage as the old core makes it (without the new marker) — for compatibility tests.
743    pub(crate) fn legacy_key_package(&self) -> R<Vec<u8>> {
744        let g = self.lock();
745        // As in the store-build core: default suites (X-Wing is in the list!), no new-core markers.
746        let store_caps = Capabilities::new(None, Some(&OUR_SUITES), None, None, None);
747        let bundle = KeyPackage::builder()
748            .leaf_node_capabilities(store_caps)
749            .build(CIPHERSUITE, &g.provider, &g.signer, Self::cwk(&g))
750            .mls()?;
751        bundle.key_package().tls_serialize_detached().mls()
752    }
753}
754
755
756/// Sender leaf of an incoming frame: tree index and credential (identity), verified
757/// by OpenMLS (leaf signature).
758#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
759pub struct SenderLeaf {
760    pub leaf_index: u32,
761    pub identity: Vec<u8>,
762}
763
764/// Result of `process_incoming_with_sender`.
765#[derive(uniffi::Record)]
766pub struct IncomingWithSender {
767    pub incoming: Incoming,
768    pub sender: Option<SenderLeaf>,
769}
770
771impl MlsClient {
772    fn process_incoming_inner(
773        &self,
774        gid: Vec<u8>,
775        message: Vec<u8>,
776        allowed_handshake_senders: Option<&[Vec<u8>]>,
777    ) -> R<(Incoming, Option<SenderLeaf>)> {
778        let g = self.lock();
779
780        let mut group = Self::load_group(&g, &gid)?;
781        let msg = MlsMessageIn::tls_deserialize_exact(&message).mls()?;
782        let protocol = match msg.try_into_protocol_message() {
783            Ok(p) => p,
784            Err(_) => return Ok((Incoming::Ignored, None)),
785        };
786        let processed = match group.process_message(&g.provider, protocol) {
787            Ok(p) => p,
788            Err(_) => return Ok((Incoming::Ignored, None)),
789        };
790        // Capture the authenticated sender BEFORE consuming the message: into_content()
791        // drops everything except the payload, which is exactly how the sender identity
792        // came to be taken from attacker-chosen JSON instead (audit K-1).
793        let sender_identity = processed.credential().serialized_content().to_vec();
794        // Sender leaf for Commit/Proposal too (the "leaf ↔ ML-DSA signer" check in Kotlin).
795        let sender = match processed.sender() {
796            Sender::Member(leaf) => Some(SenderLeaf { leaf_index: leaf.u32(), identity: sender_identity.clone() }),
797            _ => None,
798        };
799        // Commit/Proposal only from a leaf in the list (if set). Checked BEFORE merging.
800        let handshake_ok = match allowed_handshake_senders {
801            None => true,
802            Some(list) => sender.as_ref().map(|s| list.iter().any(|a| a == &s.identity)).unwrap_or(false),
803        };
804        match processed.into_content() {
805            ProcessedMessageContent::StagedCommitMessage(_) if !handshake_ok => Ok((Incoming::CommitRejected, sender)),
806            ProcessedMessageContent::ProposalMessage(_) | ProcessedMessageContent::ExternalJoinProposalMessage(_)
807                if !handshake_ok => Ok((Incoming::Ignored, sender)),
808            ProcessedMessageContent::ApplicationMessage(app) => Ok((Incoming::Application {
809                plaintext: app.into_bytes(),
810                sender_identity,
811            }, sender)),
812            ProcessedMessageContent::StagedCommitMessage(staged) => {
813                // CRYPTO-LEVEL MEMBERSHIP CAP (audit finding #1): inspect the staged
814                // commit's NET membership effect BEFORE merging. If it would push the
815                // group past MAX_GROUP_MEMBERS, refuse it — do NOT merge, so the epoch
816                // does not advance on this honest client. A malicious admin therefore
817                // cannot force the (cap+1)-th member onto honest devices; the blind
818                // server never sees the group, so anonymity is untouched.
819                let current = group.members().count();
820                let adds = staged.add_proposals().count();
821                let removes = staged.remove_proposals().count();
822                let resulting = current.saturating_add(adds).saturating_sub(removes);
823                // Same rule as on the sender: more than 20 leaves only if all leaves
824                // and all added ones run the new core; more than 100 — never.
825                let added_marked = staged
826                    .add_proposals()
827                    .all(|p| has_marker(p.add_proposal().key_package().leaf_node().capabilities()));
828                let limit = if resulting > LEGACY_LEAF_CAP { leaf_limit(&group, added_marked)? } else { LEGACY_LEAF_CAP };
829                if resulting > limit {
830                    // Drop the staged commit unmerged; epoch stays put.
831                    return Ok((Incoming::CommitRejected, sender));
832                }
833                group.merge_staged_commit(&g.provider, *staged).mls()?;
834                Ok((Incoming::CommitApplied, sender))
835            }
836            ProcessedMessageContent::ProposalMessage(_)
837            | ProcessedMessageContent::ExternalJoinProposalMessage(_) => Ok((Incoming::Proposal, sender)),
838            // OpenMLS 0.9 no longer returns an error for our own echo but yields these two
839            // variants. On 0.6 both were a process_message error → Ignored; we keep that:
840            //  • OwnPrivateMessage — our own encrypted message came back from the relay;
841            //    it cannot be decrypted and its sender is not verified (#2099) — just skip it;
842            //  • OwnPendingCommit — our Commit matching a pending one. We merge our Commits right
843            //    on creation (add/remove/update_keys), so we never have a pending one; if one does
844            //    exist (a Commit built bypassing our methods), its fate is up to whoever built it.
845            ProcessedMessageContent::OwnPrivateMessage | ProcessedMessageContent::OwnPendingCommit => {
846                Ok((Incoming::Ignored, None))
847            }
848        }
849    }
850}
851
852#[cfg(test)]
853mod tests {
854    use super::*;
855
856    /// A panic under the lock (as while parsing a foreign frame) does not disable the core until restart —
857    /// the next call clears the poison; groups and signing keep working.
858    #[test]
859    fn panic_under_lock_does_not_disable_the_core() {
860        let gid = b"poison-recovery-group-0001".to_vec();
861        let alice = MlsClient::new(b"alice".to_vec()).unwrap();
862        alice.create_group(gid.clone()).unwrap();
863        let pk = alice.signature_public_key();
864        let a = alice.clone();
865        let r = std::thread::spawn(move || {
866            let _g = a.lock();
867            panic!("panic while parsing a foreign frame");
868        })
869        .join();
870        assert!(r.is_err());
871        assert!(alice.inner.is_poisoned(), "the check must start with a poisoned lock");
872        assert_eq!(alice.signature_public_key(), pk);
873        assert!(!alice.inner.is_poisoned());
874        assert_eq!(alice.members(gid.clone()).unwrap().len(), 1);
875        assert!(!alice.encrypt(gid.clone(), b"hello".to_vec()).unwrap().is_empty());
876        assert!(!alice.export_state().unwrap().is_empty());
877    }
878
879    /// Corrupted hex is an error, not a panic (odd length, non-ASCII, garbage).
880    #[test]
881    fn unhex_rejects_malformed_without_panic() {
882        assert_eq!(unhex("00ff7A").unwrap(), vec![0x00, 0xff, 0x7a]);
883        assert!(unhex("").unwrap().is_empty());
884        for bad in ["0", "abc", "zz", "a\u{e9}b", "\u{e9}\u{e9}", "\u{1F600}", "0g", " 0"] {
885            assert!(unhex(bad).is_err(), "{bad:?}");
886        }
887        assert!(quant_address("abc".into(), "00".into()).is_err());
888        assert!(quant_address("a\u{e9}b".into(), "00".into()).is_err());
889        let blob = br#"{"identity":[1],"signer":[],"storage":[["abc","00"]]}"#.to_vec();
890        assert!(MlsClient::from_state(blob).is_err());
891        let blob = br#"{"identity":[1],"signer":[],"storage":[["a\u00e9b","00"]]}"#.to_vec();
892        assert!(MlsClient::from_state(blob).is_err());
893        assert!(MlsClient::from_state(vec![0xff, 0xff, 0xff, 0xff]).is_err());
894    }
895
896    /// With a member on the old core the limit is 20 leaves (otherwise their epoch falls behind);
897    /// when everyone is on the new core — up to 100 leaves; the receiver applies the same rule.
898    #[test]
899    fn leaf_cap_depends_on_every_member_running_the_new_core() {
900        let gid = b"cap-multidevice-group-0001".to_vec();
901        let alice = MlsClient::new(b"alice".to_vec()).unwrap();
902        alice.create_group(gid.clone()).unwrap();
903        assert!(alice.own_leaf_marked(gid.clone()).unwrap());
904        // Bob is on the old core (leaf without the marker).
905        let bob = MlsClient::new(b"bob".to_vec()).unwrap();
906        let b = alice.add_members(gid.clone(), vec![bob.legacy_key_package().unwrap()]).unwrap();
907        bob.process_welcome(b.welcome).unwrap();
908        assert!(!bob.own_leaf_marked(gid.clone()).unwrap());
909        assert_eq!(alice.leaf_limit(gid.clone()).unwrap(), LEGACY_LEAF_CAP as u32);
910        let carol = MlsClient::new(b"carol".to_vec()).unwrap();
911        let c = alice.add_members(gid.clone(), vec![carol.generate_key_package().unwrap()]).unwrap();
912        carol.process_welcome(c.welcome).unwrap();
913        assert!(matches!(bob.process_incoming(gid.clone(), c.commit).unwrap(), Incoming::CommitApplied));
914        for i in 4..=LEGACY_LEAF_CAP {
915            let m = MlsClient::new(format!("m{i}").into_bytes()).unwrap();
916            let cb = alice.add_members(gid.clone(), vec![m.generate_key_package().unwrap()]).unwrap();
917            for peer in [&bob, &carol] {
918                assert!(matches!(peer.process_incoming(gid.clone(), cb.commit.clone()).unwrap(), Incoming::CommitApplied));
919            }
920        }
921        // 21st leaf while a member is on the old core — rejected by the sender.
922        let pc = MlsClient::new(b"pc".to_vec()).unwrap();
923        let pc_kp = pc.generate_key_package().unwrap();
924        assert!(alice.add_members(gid.clone(), vec![pc_kp.clone()]).is_err());
925        // Bob updated the app and did a rekey: now all leaves run the new core.
926        let up = bob.update_keys(gid.clone()).unwrap();
927        assert!(bob.own_leaf_marked(gid.clone()).unwrap());
928        assert!(matches!(alice.process_incoming(gid.clone(), up.clone()).unwrap(), Incoming::CommitApplied));
929        assert!(matches!(carol.process_incoming(gid.clone(), up).unwrap(), Incoming::CommitApplied));
930        assert_eq!(alice.leaf_limit(gid.clone()).unwrap(), MAX_GROUP_LEAVES as u32);
931        let cb = alice.add_members(gid.clone(), vec![pc_kp]).unwrap();
932        for peer in [&bob, &carol] {
933            assert!(matches!(peer.process_incoming(gid.clone(), cb.commit.clone()).unwrap(), Incoming::CommitApplied));
934        }
935        pc.process_welcome(cb.welcome).unwrap();
936        assert_eq!(bob.members(gid.clone()).unwrap().len(), LEGACY_LEAF_CAP + 1);
937        // A new member on the old core is not added to a 21-leaf group…
938        let old = MlsClient::new(b"old".to_vec()).unwrap();
939        assert!(alice.add_members(gid.clone(), vec![old.legacy_key_package().unwrap()]).is_err());
940        // …and a malicious Commit with such an add is rejected by honest members.
941        let evil = {
942            let g = alice.inner.lock().unwrap();
943            let mut group = MlsClient::load_group(&g, &gid).unwrap();
944            let kp = KeyPackageIn::tls_deserialize_exact(&old.legacy_key_package().unwrap())
945                .unwrap()
946                .validate(g.provider.crypto(), ProtocolVersion::Mls10)
947                .unwrap();
948            let (commit, _w, _i) = group.add_members(&g.provider, &g.signer, &[kp]).unwrap();
949            commit.tls_serialize_detached().unwrap()
950        };
951        assert!(matches!(bob.process_incoming(gid.clone(), evil).unwrap(), Incoming::CommitRejected));
952    }
953
954    /// Up to 100 leaves when everyone is on the new core; the 101st is rejected.
955    #[test]
956    fn hundred_leaves_when_all_members_are_new() {
957        let gid = b"cap-multidevice-group-0100".to_vec();
958        let alice = MlsClient::new(b"alice".to_vec()).unwrap();
959        alice.create_group(gid.clone()).unwrap();
960        let kps: Vec<Vec<u8>> = (2..=MAX_GROUP_LEAVES)
961            .map(|i| MlsClient::new(format!("d{i}").into_bytes()).unwrap().generate_key_package().unwrap())
962            .collect();
963        alice.add_members(gid.clone(), kps).unwrap();
964        assert_eq!(alice.members(gid.clone()).unwrap().len(), MAX_GROUP_LEAVES);
965        let extra = MlsClient::new(b"d101".to_vec()).unwrap().generate_key_package().unwrap();
966        assert!(alice.add_members(gid, vec![extra]).is_err());
967    }
968
969    fn app_bytes(inc: Incoming) -> Vec<u8> {
970        app_parts(inc).0
971    }
972
973    fn app_parts(inc: Incoming) -> (Vec<u8>, Vec<u8>) {
974        match inc {
975            Incoming::Application {
976                plaintext,
977                sender_identity,
978            } => (plaintext, sender_identity),
979            _ => panic!("expected application message"),
980        }
981    }
982
983    #[test]
984    fn full_group_roundtrip() {
985        let gid = b"group-id-0123456789-abcdef-0001".to_vec();
986        let alice = MlsClient::new(b"alice".to_vec()).unwrap();
987        let bob = MlsClient::new(b"bob".to_vec()).unwrap();
988        let carol = MlsClient::new(b"carol".to_vec()).unwrap();
989
990        // Alice creates the group, adds Bob.
991        alice.create_group(gid.clone()).unwrap();
992        let bob_kp = bob.generate_key_package().unwrap();
993        let bundle = alice.add_members(gid.clone(), vec![bob_kp]).unwrap();
994        let joined = bob.process_welcome(bundle.welcome).unwrap();
995        assert_eq!(joined, gid, "bob joined the right group");
996
997        // Alice → Bob application message decrypts correctly.
998        let ct = alice.encrypt(gid.clone(), b"hello bob".to_vec()).unwrap();
999        let got = app_bytes(bob.process_incoming(gid.clone(), ct).unwrap());
1000        assert_eq!(got, b"hello bob");
1001
1002        // Bob → Alice the other direction.
1003        let ct2 = bob.encrypt(gid.clone(), b"hi alice".to_vec()).unwrap();
1004        let got2 = app_bytes(alice.process_incoming(gid.clone(), ct2).unwrap());
1005        assert_eq!(got2, b"hi alice");
1006
1007        // Add Carol: Alice commits, Bob applies the commit, Carol joins via welcome.
1008        let carol_kp = carol.generate_key_package().unwrap();
1009        let bundle2 = alice.add_members(gid.clone(), vec![carol_kp]).unwrap();
1010        matches!(
1011            bob.process_incoming(gid.clone(), bundle2.commit).unwrap(),
1012            Incoming::CommitApplied
1013        );
1014        carol.process_welcome(bundle2.welcome).unwrap();
1015        assert_eq!(alice.members(gid.clone()).unwrap().len(), 3);
1016
1017        // After the membership change (new epoch), Alice→{Bob,Carol} still decrypts.
1018        let ct3 = alice.encrypt(gid.clone(), b"welcome carol".to_vec()).unwrap();
1019        let to_bob = app_bytes(bob.process_incoming(gid.clone(), ct3.clone()).unwrap());
1020        let to_carol = app_bytes(carol.process_incoming(gid.clone(), ct3).unwrap());
1021        assert_eq!(to_bob, b"welcome carol");
1022        assert_eq!(to_carol, b"welcome carol");
1023
1024        // Persistence round-trip: export Alice's state, restore, keep talking.
1025        let blob = alice.export_state().unwrap();
1026        let alice2 = MlsClient::from_state(blob).unwrap();
1027        let ct4 = alice2.encrypt(gid.clone(), b"after reload".to_vec()).unwrap();
1028        let got4 = app_bytes(bob.process_incoming(gid.clone(), ct4).unwrap());
1029        assert_eq!(got4, b"after reload");
1030    }
1031
1032    /// AUTHENTICATED SENDER (audit K-1). The application layer decides admin rights from a
1033    /// `sender` field the sender itself writes into the plaintext, so it can only be trusted
1034    /// once it is checked against the identity MLS itself authenticated. This proves the FFI
1035    /// hands that identity out, and that it is the *real* sender rather than any peer the
1036    /// attacker might want to impersonate.
1037    /// Commit and Proposal also return the sender leaf (index + credential), and it is the real sender.
1038    #[test]
1039    fn commits_and_proposals_carry_the_sender_leaf() {
1040        let gid = b"sender-leaf-group-id-0123456789ab".to_vec();
1041        let alice = MlsClient::new(b"alice".to_vec()).unwrap();
1042        let bob = MlsClient::new(b"bob".to_vec()).unwrap();
1043        let carol = MlsClient::new(b"carol".to_vec()).unwrap();
1044        alice.create_group(gid.clone()).unwrap();
1045        let b1 = alice.add_members(gid.clone(), vec![bob.generate_key_package().unwrap()]).unwrap();
1046        bob.process_welcome(b1.welcome).unwrap();
1047        let b2 = alice.add_members(gid.clone(), vec![carol.generate_key_package().unwrap()]).unwrap();
1048        let r = bob.process_incoming_with_sender(gid.clone(), b2.commit, None).unwrap();
1049        let (inc, sender) = (r.incoming, r.sender);
1050        assert!(matches!(inc, Incoming::CommitApplied));
1051        let s = sender.expect("commit sender leaf");
1052        assert_eq!(s.identity, b"alice".to_vec());
1053        assert_eq!(s.leaf_index, 0, "alice created the group: leaf 0");
1054        carol.process_welcome(b2.welcome).unwrap();
1055
1056        // Commit from Bob (updating his leaf): for Carol the sender is Bob, not Alice.
1057        let up = bob.update_keys(gid.clone()).unwrap();
1058        let r2 = carol.process_incoming_with_sender(gid.clone(), up.clone(), None).unwrap();
1059        let (inc2, s2) = (r2.incoming, r2.sender);
1060        assert!(matches!(alice.process_incoming(gid.clone(), up).unwrap(), Incoming::CommitApplied));
1061        assert!(matches!(inc2, Incoming::CommitApplied));
1062        let s2 = s2.expect("bob commit sender");
1063        assert_eq!(s2.identity, b"bob".to_vec());
1064        assert_eq!(s2.leaf_index, 1);
1065
1066        // Application message — the same leaf as in Incoming::Application.
1067        let ct = carol.encrypt(gid.clone(), b"hi".to_vec()).unwrap();
1068        let r3 = alice.process_incoming_with_sender(gid.clone(), ct, None).unwrap();
1069        let (inc3, s3) = (r3.incoming, r3.sender);
1070        let (_, id) = app_parts(inc3);
1071        let s3 = s3.unwrap();
1072        assert_eq!(s3.identity, id);
1073        assert_eq!(s3.identity, b"carol".to_vec());
1074        assert_eq!(s3.leaf_index, 2);
1075
1076        // Garbage — no sender.
1077        let (inc4, s4) = alice
1078            .process_incoming_with_sender(gid.clone(), vec![0u8; 8], None)
1079            .map_or((Incoming::Ignored, None), |x| (x.incoming, x.sender));
1080        assert!(matches!(inc4, Incoming::Ignored));
1081        assert!(s4.is_none());
1082    }
1083
1084    /// Another leaf's Commit under "own" PQ signature is not merged (epoch unchanged); a Commit from a leaf in the
1085    /// list is merged; application messages are not restricted by the list.
1086    #[test]
1087    fn handshake_sender_guard_rejects_commit_of_other_leaf() {
1088        let gid = b"sender-guard-group-id-0123456789a".to_vec();
1089        let alice = MlsClient::new(b"alice".to_vec()).unwrap();
1090        let bob = MlsClient::new(b"bob".to_vec()).unwrap();
1091        let carol = MlsClient::new(b"carol".to_vec()).unwrap();
1092        alice.create_group(gid.clone()).unwrap();
1093        let b1 = alice.add_members(gid.clone(), vec![bob.generate_key_package().unwrap()]).unwrap();
1094        bob.process_welcome(b1.welcome).unwrap();
1095        let b2 = alice.add_members(gid.clone(), vec![carol.generate_key_package().unwrap()]).unwrap();
1096        carol.process_welcome(b2.welcome).unwrap();
1097        bob.process_incoming(gid.clone(), b2.commit).unwrap();
1098
1099        // Alice's Commit, but the envelope signer (by PQ) is Bob: Carol's list = Bob's leaves.
1100        let up = alice.update_keys(gid.clone()).unwrap();
1101        let e0 = carol.epoch(gid.clone()).unwrap();
1102        let r = carol.process_incoming_with_sender(gid.clone(), up.clone(), Some(vec![b"bob".to_vec()])).unwrap();
1103        assert!(matches!(r.incoming, Incoming::CommitRejected));
1104        assert_eq!(r.sender.unwrap().identity, b"alice".to_vec());
1105        assert_eq!(carol.epoch(gid.clone()).unwrap(), e0, "rejected commit must not advance the epoch");
1106        // An empty list is also a rejection.
1107        let r0 = bob.process_incoming_with_sender(gid.clone(), up.clone(), Some(vec![])).unwrap();
1108        assert!(matches!(r0.incoming, Incoming::CommitRejected));
1109        assert_eq!(bob.epoch(gid.clone()).unwrap(), e0);
1110
1111        // The same leaf in the list — the Commit is applied.
1112        let up2 = bob.update_keys(gid.clone()).unwrap();
1113        let r2 = carol.process_incoming_with_sender(gid.clone(), up2, Some(vec![b"bob".to_vec()])).unwrap();
1114        // Bob and Carol both rejected Alice's Commit and stayed on e0 — Bob's Commit applies at Carol's epoch.
1115        assert!(matches!(r2.incoming, Incoming::CommitApplied));
1116        assert_eq!(carol.epoch(gid.clone()).unwrap(), e0 + 1);
1117
1118        // Application message from Bob with the list "alice only" decrypts (the list is not for application messages).
1119        let ct = bob.encrypt(gid.clone(), b"hi".to_vec()).unwrap();
1120        let r3 = carol.process_incoming_with_sender(gid.clone(), ct, Some(vec![b"alice".to_vec()])).unwrap();
1121        let (pt, id) = app_parts(r3.incoming);
1122        assert_eq!(pt, b"hi".to_vec());
1123        assert_eq!(id, b"bob".to_vec());
1124    }
1125
1126    #[test]
1127    fn application_messages_carry_the_authenticated_sender() {
1128        let gid = b"sender-auth-group-id-01234567890".to_vec();
1129        let alice = MlsClient::new(b"alice".to_vec()).unwrap();
1130        let bob = MlsClient::new(b"bob".to_vec()).unwrap();
1131        let carol = MlsClient::new(b"carol".to_vec()).unwrap();
1132
1133        alice.create_group(gid.clone()).unwrap();
1134        let bundle = alice
1135            .add_members(gid.clone(), vec![bob.generate_key_package().unwrap()])
1136            .unwrap();
1137        bob.process_welcome(bundle.welcome).unwrap();
1138        let bundle2 = alice
1139            .add_members(gid.clone(), vec![carol.generate_key_package().unwrap()])
1140            .unwrap();
1141        assert!(matches!(
1142            bob.process_incoming(gid.clone(), bundle2.commit).unwrap(),
1143            Incoming::CommitApplied
1144        ));
1145        carol.process_welcome(bundle2.welcome).unwrap();
1146
1147        // Bob is a plain member. Whatever he claims inside the plaintext, the identity the
1148        // receiver gets back is Bob's own credential — never Alice's.
1149        let forged = br#"{"sender":"alice","t":"role","content":"bob|ADMIN"}"#.to_vec();
1150        let ct = bob.encrypt(gid.clone(), forged.clone()).unwrap();
1151        let (plaintext, sender) = app_parts(carol.process_incoming(gid.clone(), ct).unwrap());
1152        assert_eq!(plaintext, forged, "payload still decrypts verbatim");
1153        assert_eq!(sender, b"bob".to_vec(), "identity is the authenticated sender");
1154        assert_ne!(sender, b"alice".to_vec(), "impersonation must not be possible");
1155
1156        // And the honest case still reports the honest sender.
1157        let ct2 = alice.encrypt(gid.clone(), b"hi".to_vec()).unwrap();
1158        let (_, sender2) = app_parts(carol.process_incoming(gid.clone(), ct2).unwrap());
1159        assert_eq!(sender2, b"alice".to_vec());
1160    }
1161
1162    /// CRYPTO-LEVEL MEMBERSHIP CAP (audit finding #1). Proves the cap is enforced by the
1163    /// MLS layer on EVERY honest client, not by the blind server:
1164    ///   (1) an honest admin fails closed — it will not produce an over-cap Commit; and
1165    ///   (2) when a MALICIOUS admin crafts an over-cap Commit anyway (driving openmls
1166    ///       directly, bypassing our add guard), an honest member REFUSES to merge it and
1167    ///       its epoch does not advance — so the (cap+1)-th member can never be forced on.
1168    #[test]
1169    fn member_cap_enforced_at_crypto_layer() {
1170        let gid = b"cap-test-group-id-0123456789-001".to_vec();
1171        let alice = MlsClient::new(b"alice".to_vec()).unwrap();
1172        alice.create_group(gid.clone()).unwrap();
1173
1174        // Bob is a real existing member (#2) who will judge the over-cap Commit.
1175        let bob = MlsClient::new(b"bob".to_vec()).unwrap();
1176        // Bob on the old core: the group limit stays at 20 leaves.
1177        let bob_kp = bob.legacy_key_package().unwrap();
1178        let b = alice.add_members(gid.clone(), vec![bob_kp]).unwrap();
1179        bob.process_welcome(b.welcome).unwrap();
1180
1181        // Fill the group up to exactly the cap (members 3..=MAX). Bob applies each Commit
1182        // so he stays at the same epoch as Alice.
1183        for i in 3..=MAX_GROUP_MEMBERS {
1184            let m = MlsClient::new(format!("m{}", i).into_bytes()).unwrap();
1185            let kp = m.generate_key_package().unwrap();
1186            let cb = alice.add_members(gid.clone(), vec![kp]).unwrap();
1187            assert!(matches!(
1188                bob.process_incoming(gid.clone(), cb.commit).unwrap(),
1189                Incoming::CommitApplied
1190            ));
1191        }
1192        assert_eq!(alice.members(gid.clone()).unwrap().len(), MAX_GROUP_MEMBERS);
1193        assert_eq!(bob.members(gid.clone()).unwrap().len(), MAX_GROUP_MEMBERS);
1194
1195        // The (cap+1)-th candidate.
1196        let evil = MlsClient::new(b"member-21".to_vec()).unwrap();
1197        let evil_kp = evil.generate_key_package().unwrap();
1198
1199        // (1) HONEST ADMIN fails closed: it won't even produce an over-cap Commit.
1200        assert!(
1201            alice.add_members(gid.clone(), vec![evil_kp.clone()]).is_err(),
1202            "honest admin must refuse to add the (cap+1)-th member"
1203        );
1204
1205        // (2) MALICIOUS ADMIN: craft an over-cap Commit by driving openmls directly,
1206        // bypassing our add_members guard, then feed it to honest member Bob.
1207        let evil_commit = {
1208            let g = alice.inner.lock().unwrap();
1209            let mut group = MlsClient::load_group(&g, &gid).unwrap();
1210            let kp_in = KeyPackageIn::tls_deserialize_exact(&evil_kp).unwrap();
1211            let kp = kp_in
1212                .validate(g.provider.crypto(), ProtocolVersion::Mls10)
1213                .unwrap();
1214            let (commit, _welcome, _info) =
1215                group.add_members(&g.provider, &g.signer, &[kp]).unwrap();
1216            commit.tls_serialize_detached().unwrap()
1217        };
1218
1219        let epoch_before = bob.epoch(gid.clone()).unwrap();
1220        // Honest Bob REFUSES the over-cap Commit.
1221        assert!(
1222            matches!(
1223                bob.process_incoming(gid.clone(), evil_commit).unwrap(),
1224                Incoming::CommitRejected
1225            ),
1226            "honest member must reject an over-cap Commit"
1227        );
1228        // Its epoch did NOT advance and its roster stays at the cap.
1229        assert_eq!(bob.epoch(gid.clone()).unwrap(), epoch_before);
1230        assert_eq!(bob.members(gid.clone()).unwrap().len(), MAX_GROUP_MEMBERS);
1231    }
1232
1233    /// X-Wing: a group in the X25519 + ML-KEM-768 suite behaves like a legacy one — add,
1234    /// messaging both ways, remove, rekey, save and restore, epoch secret.
1235    #[test]
1236    fn xwing_group_full_life() {
1237        let x = mls_suite_xwing();
1238        let gid = b"xwing-group-0123456789abcdef0001".to_vec();
1239        let alice = MlsClient::new(b"alice".to_vec()).unwrap();
1240        let bob = MlsClient::new(b"bob".to_vec()).unwrap();
1241        let carol = MlsClient::new(b"carol".to_vec()).unwrap();
1242        alice.create_group_for(gid.clone(), x).unwrap();
1243        assert_eq!(alice.group_ciphersuite(gid.clone()).unwrap(), x);
1244        let kp = bob.generate_key_package_for(x).unwrap();
1245        let info = key_package_info(kp.clone()).unwrap();
1246        assert_eq!(info.ciphersuite, x);
1247        assert_eq!(info.identity, b"bob".to_vec());
1248        assert!(info.supports_xwing);
1249        let b = alice.add_members(gid.clone(), vec![kp]).unwrap();
1250        assert_eq!(bob.process_welcome(b.welcome).unwrap(), gid);
1251        assert_eq!(bob.group_ciphersuite(gid.clone()).unwrap(), x);
1252        let ct = alice.encrypt(gid.clone(), b"pq hello".to_vec()).unwrap();
1253        assert_eq!(app_bytes(bob.process_incoming(gid.clone(), ct).unwrap()), b"pq hello");
1254        let ct = bob.encrypt(gid.clone(), b"pq back".to_vec()).unwrap();
1255        assert_eq!(app_bytes(alice.process_incoming(gid.clone(), ct).unwrap()), b"pq back");
1256        let c = alice.add_members(gid.clone(), vec![carol.generate_key_package_for(x).unwrap()]).unwrap();
1257        assert!(matches!(bob.process_incoming(gid.clone(), c.commit).unwrap(), Incoming::CommitApplied));
1258        carol.process_welcome(c.welcome).unwrap();
1259        let up = carol.update_keys(gid.clone()).unwrap();
1260        for p in [&alice, &bob] {
1261            assert!(matches!(p.process_incoming(gid.clone(), up.clone()).unwrap(), Incoming::CommitApplied));
1262        }
1263        let s = [&alice, &bob, &carol].map(|p| p.export_secret(gid.clone(), "conf".into(), 32).unwrap());
1264        assert!(s[0] == s[1] && s[1] == s[2]);
1265        assert!(alice.members_support(gid.clone(), x).unwrap());
1266        let bob_leaf = alice.members(gid.clone()).unwrap().into_iter().find(|m| m.identity == b"bob").unwrap().leaf_index;
1267        let rm = alice.remove_members(gid.clone(), vec![bob_leaf]).unwrap();
1268        assert!(matches!(carol.process_incoming(gid.clone(), rm).unwrap(), Incoming::CommitApplied));
1269        let carol2 = MlsClient::from_state(carol.export_state().unwrap()).unwrap();
1270        let ct = carol2.encrypt(gid.clone(), b"after reload".to_vec()).unwrap();
1271        assert_eq!(app_bytes(alice.process_incoming(gid.clone(), ct).unwrap()), b"after reload");
1272        assert_eq!(carol2.group_ciphersuite(gid.clone()).unwrap(), x);
1273    }
1274
1275    /// Moving a group to X-Wing with the same leaf: a new group with the same gid and signing keys; links still verify.
1276    #[test]
1277    fn regroup_to_xwing_keeps_leaf_signature_keys() {
1278        let (l, x) = (mls_suite_legacy(), mls_suite_xwing());
1279        let gid = b"regroup-group-0123456789abcdef01".to_vec();
1280        let alice = MlsClient::new(b"alice".to_vec()).unwrap();
1281        let bob = MlsClient::new(b"bob".to_vec()).unwrap();
1282        alice.create_group(gid.clone()).unwrap();
1283        let b = alice.add_members(gid.clone(), vec![bob.generate_key_package_for(l).unwrap()]).unwrap();
1284        bob.process_welcome(b.welcome).unwrap();
1285        let sig = bob.sibling_sign(gid.clone(), b"bob".to_vec(), b"alice".to_vec()).unwrap();
1286        // Bob publishes an X-Wing package from a "twin" of his leaf in advance.
1287        let bob2 = bob.spawn_same_identity().unwrap();
1288        assert_eq!(bob2.signature_public_key(), bob.signature_public_key());
1289        let kp = bob2.generate_key_package_for(x).unwrap();
1290        let alice2 = alice.spawn_same_identity().unwrap();
1291        alice2.create_group_for(gid.clone(), x).unwrap();
1292        let w = alice2.add_members(gid.clone(), vec![kp]).unwrap().welcome;
1293        assert_eq!(bob2.process_welcome(w).unwrap(), gid);
1294        assert_eq!(bob2.group_ciphersuite(gid.clone()).unwrap(), x);
1295        let ct = bob2.encrypt(gid.clone(), b"after regroup".to_vec()).unwrap();
1296        assert_eq!(app_bytes(alice2.process_incoming(gid.clone(), ct).unwrap()), b"after regroup");
1297        // A signature made by the previous leaf verifies against the new tree.
1298        let sig2 = alice2.sibling_sign(gid.clone(), b"bob".to_vec(), b"alice".to_vec()).unwrap();
1299        assert!(alice2.sibling_verify(gid.clone(), b"bob".to_vec(), b"alice".to_vec(), sig, sig2).unwrap());
1300    }
1301
1302    /// A package of the wrong suite is not added to the group (an error, not group corruption); legacy and X-Wing
1303    /// packages of one client are different packages of the same leaf.
1304    #[test]
1305    fn suites_do_not_mix() {
1306        let (l, x) = (mls_suite_legacy(), mls_suite_xwing());
1307        let gid = b"suite-mix-group-0123456789abcd01".to_vec();
1308        let alice = MlsClient::new(b"alice".to_vec()).unwrap();
1309        let bob = MlsClient::new(b"bob".to_vec()).unwrap();
1310        alice.create_group_for(gid.clone(), x).unwrap();
1311        let legacy = bob.generate_key_package_for(l).unwrap();
1312        assert_eq!(key_package_info(legacy.clone()).unwrap().ciphersuite, l);
1313        assert!(key_package_info(legacy.clone()).unwrap().supports_xwing);
1314        assert!(alice.add_members(gid.clone(), vec![legacy]).is_err());
1315        assert_eq!(alice.epoch(gid.clone()).unwrap(), 0);
1316        let gid2 = b"suite-mix-group-0123456789abcd02".to_vec();
1317        alice.create_group(gid2.clone()).unwrap();
1318        assert_eq!(alice.group_ciphersuite(gid2.clone()).unwrap(), l);
1319        assert!(alice.add_members(gid2.clone(), vec![bob.generate_key_package_for(x).unwrap()]).is_err());
1320        assert!(alice.generate_key_package_for(0x0002).is_err());
1321        // An old-core leaf does not advertise X-Wing: a group with it cannot be moved.
1322        let old = MlsClient::new(b"old".to_vec()).unwrap();
1323        let b = alice.add_members(gid2.clone(), vec![old.legacy_key_package().unwrap()]).unwrap();
1324        old.process_welcome(b.welcome).unwrap();
1325        assert!(!alice.members_support(gid2.clone(), x).unwrap());
1326        assert!(!old.own_leaf_marked(gid2.clone()).unwrap());
1327        // Upgraded and did a rekey — now advertises it.
1328        let up = old.update_keys(gid2.clone()).unwrap();
1329        assert!(matches!(alice.process_incoming(gid2.clone(), up).unwrap(), Incoming::CommitApplied));
1330        assert!(alice.members_support(gid2.clone(), x).unwrap());
1331        assert!(old.own_leaf_marked(gid2).unwrap());
1332    }
1333
1334    /// The leaf limit also holds in X-Wing groups (100 when everyone is on the new core).
1335    #[test]
1336    fn xwing_hundred_leaves_and_sizes() {
1337        let x = mls_suite_xwing();
1338        let gid = b"xwing-cap-group-0123456789abcd01".to_vec();
1339        let alice = MlsClient::new(b"alice".to_vec()).unwrap();
1340        alice.create_group_for(gid.clone(), x).unwrap();
1341        let peers: Vec<_> = (2..=MAX_GROUP_LEAVES).map(|i| MlsClient::new(format!("d{i}").into_bytes()).unwrap()).collect();
1342        let kps: Vec<Vec<u8>> = peers.iter().map(|p| p.generate_key_package_for(x).unwrap()).collect();
1343        let kp_len = kps[0].len();
1344        let b = alice.add_members(gid.clone(), kps).unwrap();
1345        assert_eq!(alice.members(gid.clone()).unwrap().len(), MAX_GROUP_LEAVES);
1346        peers[0].process_welcome(b.welcome.clone()).unwrap();
1347        let up = peers[0].update_keys(gid.clone()).unwrap();
1348        eprintln!("X-Wing: KeyPackage {kp_len} B, Welcome for {} leaves {} B, Commit with path {} B", MAX_GROUP_LEAVES, b.welcome.len(), up.len());
1349        // The relay envelope is up to 1 MiB after double base64; a Welcome with the whole tree must fit.
1350        assert!(b.welcome.len() * 16 / 9 < 1024 * 1024);
1351        let extra = MlsClient::new(b"d101".to_vec()).unwrap().generate_key_package_for(x).unwrap();
1352        assert!(alice.add_members(gid, vec![extra]).is_err());
1353    }
1354
1355    /// The Rust quant_address must match the server's output BYTE-FOR-BYTE, else the
1356    /// client's zero-trust address↔keys check would falsely accept/reject. Reference computed from
1357    /// the server's reference implementation.
1358    #[test]
1359    fn quant_address_matches_backend() {
1360        let got = quant_address(
1361            "0374e364c795619762574ae2f1fb5b75".to_string(),
1362            "cafebabedeadbeef00112233".to_string(),
1363        )
1364        .unwrap();
1365        assert_eq!(got, "quant2dcE7nu1UsMEi4wqzzsj92SUDGbMJaYCyEhwxBpcPbcHNRbU4X");
1366    }
1367}