Skip to main content

sew_e2ee/
keypackage.rs

1//! Key packages: made offline when the channel view opens
2//! or a ring arrives, signed by the device key, uploaded for a single-use
3//! `key_package_ref`, then claimed by the voice join or the key join (a move).
4
5use std::fmt;
6
7use openmls::prelude::{
8    BasicCredential, Capabilities, Ciphersuite, Credential, CredentialType, CredentialWithKey,
9    ExtensionType, KeyPackage, Lifetime, MlsMessageOut, ProtocolVersion,
10};
11use openmls_traits::OpenMlsProvider;
12use openmls_traits::types::SignatureScheme;
13use sew_mls_crypto::SignatureKeyPair;
14use sew_proto::e2ee::{
15    B64, CallKeysInit, CallScope, E2eeJoin, KeyJoinRequest, KeyPackageRefItem,
16    KeyPackageUploadRequest,
17};
18
19use crate::bridge::Caps;
20use crate::config::E2eeConfig;
21use crate::error::{IdentityError, JoinError, SessionError};
22use crate::identity::cert::verify_p256;
23use crate::identity::credential::{device_sig_message, identity_bytes};
24use crate::identity::{DeviceIdentity, SignRequest};
25use crate::ids::{JoinId, UnixMs};
26use crate::provider::CallProvider;
27use crate::session::CallSession;
28use crate::trust::TrustAnchors;
29
30/// The call ciphersuite.
31pub const CS1: Ciphersuite = Ciphersuite::MLS_128_DHKEMX25519_AES128GCM_SHA256_Ed25519;
32
33/// The capabilities every member leaf advertises: ciphersuite 1 and Basic credentials. Default
34/// extension types such as `external_senders` are **not** listed (RFC 9420 §7.2; Sew's
35/// choice where the server's checks and the RFC disagree: other implementations refuse a leaf
36/// that lists one).
37pub fn member_capabilities() -> Capabilities {
38    Capabilities::builder()
39        .versions(vec![ProtocolVersion::Mls10])
40        .ciphersuites(vec![CS1])
41        .extensions(Vec::<ExtensionType>::new())
42        .credentials(vec![CredentialType::Basic])
43        .build()
44}
45
46/// A leaf's MLS signing key and credential (in memory only, zeroized on drop by
47/// `sew_mls_crypto::SignatureKeyPair`).
48pub(crate) struct LeafSecret {
49    pub(crate) signer: SignatureKeyPair,
50    pub(crate) credential: Credential,
51    pub(crate) lifetime: (u64, u64),
52    pub(crate) kp_ref: [u8; 32],
53}
54
55impl fmt::Debug for LeafSecret {
56    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
57        f.write_str("LeafSecret(***)")
58    }
59}
60
61/// A fresh leaf key waiting for the device signature over its credential binding.
62pub(crate) struct LeafDraft {
63    signer: SignatureKeyPair,
64    scope: CallScope,
65    message: Vec<u8>,
66}
67
68impl fmt::Debug for LeafDraft {
69    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
70        f.write_str("LeafDraft(***)")
71    }
72}
73
74impl LeafDraft {
75    /// A fresh Ed25519 leaf key and the bytes the device must sign.
76    pub(crate) fn new(
77        device: &DeviceIdentity,
78        scope: CallScope,
79    ) -> Result<LeafDraft, IdentityError> {
80        let signer = SignatureKeyPair::new(SignatureScheme::ED25519)
81            .map_err(|_| IdentityError::Mls("leaf key"))?;
82        let message = device_sig_message(
83            device.install_id(),
84            device.member_id(),
85            device.device_id(),
86            scope,
87            signer.public(),
88        );
89        Ok(LeafDraft {
90            signer,
91            scope,
92            message,
93        })
94    }
95
96    pub(crate) fn message(&self) -> &[u8] {
97        &self.message
98    }
99
100    /// Verifies the device signature and builds the KeyPackage in `provider` (its private keys
101    /// stay there for the Welcome). Returns the leaf secret and the `MLSMessage(KeyPackage)`
102    /// bytes.
103    pub(crate) fn finish(
104        self,
105        device: &DeviceIdentity,
106        provider: &CallProvider,
107        device_sig: &[u8; 64],
108        now: UnixMs,
109        cfg: &E2eeConfig,
110    ) -> Result<(LeafSecret, Vec<u8>), IdentityError> {
111        if !verify_p256(device.pubkey(), &self.message, device_sig) {
112            return Err(IdentityError::BadSignature);
113        }
114        let identity = identity_bytes(self.scope, device.cert_bytes(), device_sig);
115        let credential: Credential = BasicCredential::new(identity).into();
116        let now_s = now / 1000;
117        let lifetime = (
118            now_s.saturating_sub(cfg.key_package_lifetime_back_s),
119            now_s.saturating_add(cfg.key_package_lifetime_fwd_s),
120        );
121        let bundle = KeyPackage::builder()
122            .key_package_lifetime(Lifetime::init(lifetime.0, lifetime.1))
123            .leaf_node_capabilities(member_capabilities())
124            .build(
125                CS1,
126                provider,
127                &self.signer,
128                CredentialWithKey {
129                    credential: credential.clone(),
130                    signature_key: self.signer.public().into(),
131                },
132            )
133            .map_err(|_| IdentityError::Mls("key package"))?;
134        let kp = bundle.key_package().clone();
135        let r = kp
136            .hash_ref(provider.crypto())
137            .map_err(|_| IdentityError::Mls("hash_ref"))?;
138        let kp_ref: [u8; 32] = r
139            .as_slice()
140            .try_into()
141            .map_err(|_| IdentityError::Mls("hash_ref length"))?;
142        let bytes = MlsMessageOut::from(kp)
143            .to_bytes()
144            .map_err(|_| IdentityError::Mls("encode key package"))?;
145        Ok((
146            LeafSecret {
147                signer: self.signer,
148                credential,
149                lifetime,
150                kp_ref,
151            },
152            bytes,
153        ))
154    }
155}
156
157/// The `E2eeClient`: one device's identity and trust, for preparing joins.
158#[derive(Debug)]
159pub struct E2eeClient {
160    pub(crate) identity: DeviceIdentity,
161    pub(crate) trust: TrustAnchors,
162    pub(crate) cfg: E2eeConfig,
163}
164
165impl E2eeClient {
166    /// A client for an enrolled device.
167    pub fn new(identity: DeviceIdentity, trust: TrustAnchors) -> E2eeClient {
168        E2eeClient {
169            identity,
170            trust,
171            cfg: E2eeConfig::default(),
172        }
173    }
174
175    /// With local configuration (tests).
176    pub fn with_config(mut self, cfg: E2eeConfig) -> E2eeClient {
177        self.cfg = cfg;
178        self
179    }
180
181    /// Replaces the local configuration.
182    pub fn set_config(&mut self, cfg: E2eeConfig) {
183        self.cfg = cfg;
184    }
185
186    /// Offline (~1 ms native): a fresh leaf key and the device-signature request. Call when the
187    /// channel view opens or a ring arrives. `Scope` has no empty form.
188    pub fn prepare_key_package(
189        &mut self,
190        scope: CallScope,
191        now: UnixMs,
192    ) -> Result<(PendingKp, SignRequest), IdentityError> {
193        let draft = LeafDraft::new(&self.identity, scope)?;
194        let req = SignRequest {
195            message: draft.message().to_vec(),
196        };
197        Ok((
198            PendingKp {
199                draft,
200                identity: self.identity.clone(),
201                cfg: self.cfg.clone(),
202                created: now,
203            },
204            req,
205        ))
206    }
207
208    /// The trust anchors (a `revoked` dispatch extends the CRL; a fresh READY refreshes them).
209    pub fn trust_mut(&mut self) -> &mut TrustAnchors {
210        &mut self.trust
211    }
212
213    /// The trust anchors.
214    pub fn trust(&self) -> &TrustAnchors {
215        &self.trust
216    }
217
218    /// The device identity.
219    pub fn identity(&self) -> &DeviceIdentity {
220        &self.identity
221    }
222
223    /// The local configuration.
224    pub fn config(&self) -> &E2eeConfig {
225        &self.cfg
226    }
227}
228
229/// A key package waiting for its device signature. Not `Debug`-printable beyond its type.
230pub struct PendingKp {
231    draft: LeafDraft,
232    identity: DeviceIdentity,
233    cfg: E2eeConfig,
234    created: UnixMs,
235}
236
237impl fmt::Debug for PendingKp {
238    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
239        f.write_str("PendingKp(***)")
240    }
241}
242
243impl PendingKp {
244    /// Verifies the signature and builds the KeyPackage.
245    pub fn finish(self, device_sig: [u8; 64]) -> Result<PreparedKp, IdentityError> {
246        let provider = CallProvider::new();
247        let scope = self.draft.scope;
248        let (leaf, bytes) = self.draft.finish(
249            &self.identity,
250            &provider,
251            &device_sig,
252            self.created,
253            &self.cfg,
254        )?;
255        Ok(PreparedKp {
256            provider,
257            leaf,
258            bytes,
259            scope,
260            created: self.created,
261            uploaded: None,
262            cfg: self.cfg,
263        })
264    }
265}
266
267/// A signed key package (single use; moved into the session).
268pub struct PreparedKp {
269    pub(crate) provider: CallProvider,
270    pub(crate) leaf: LeafSecret,
271    pub(crate) bytes: Vec<u8>,
272    pub(crate) scope: CallScope,
273    created: UnixMs,
274    uploaded: Option<(Vec<u8>, u64)>,
275    cfg: E2eeConfig,
276}
277
278impl fmt::Debug for PreparedKp {
279    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
280        f.debug_struct("PreparedKp")
281            .field("scope", &self.scope)
282            .field("uploaded", &self.uploaded.is_some())
283            .finish_non_exhaustive()
284    }
285}
286
287impl PreparedKp {
288    /// The KeyPackage upload body (one package per upload here).
289    pub fn upload_body(&self) -> KeyPackageUploadRequest {
290        KeyPackageUploadRequest {
291            key_packages: vec![B64::new(self.bytes.clone())],
292        }
293    }
294
295    /// The package's own `hash_ref` (RFC 9420 §5.2).
296    pub fn key_package_ref(&self) -> [u8; 32] {
297        self.leaf.kp_ref
298    }
299
300    /// The `MLSMessage(KeyPackage)` bytes.
301    pub fn key_package_bytes(&self) -> &[u8] {
302        &self.bytes
303    }
304
305    /// The scope.
306    pub fn scope(&self) -> CallScope {
307        self.scope
308    }
309
310    /// Takes the upload's answer for this package; refuses a ref other than the package's
311    /// `hash_ref`.
312    pub fn set_ref(&mut self, r: &KeyPackageRefItem) -> Result<(), IdentityError> {
313        if r.key_package_ref.as_bytes() != self.leaf.kp_ref.as_slice() {
314            return Err(IdentityError::RefMismatch);
315        }
316        self.uploaded = Some((r.key_package_ref.as_bytes().to_vec(), r.expires_at_ms));
317        Ok(())
318    }
319
320    /// Over 60 min old, or past the server TTL: prepare again.
321    pub fn is_stale(&self, now: UnixMs) -> bool {
322        let age_ms = now.saturating_sub(self.created);
323        if age_ms > self.cfg.prepared_kp_max_age_s.saturating_mul(1000) {
324            return true;
325        }
326        self.uploaded.as_ref().is_some_and(|(_, exp)| now >= *exp)
327    }
328
329    fn uploaded_ref(&self) -> Result<B64, IdentityError> {
330        self.uploaded
331            .as_ref()
332            .map(|(r, _)| B64::new(r.clone()))
333            .ok_or(IdentityError::NoRef)
334    }
335
336    /// The `e2ee` object of the voice join: `{key_package_ref, gateway_session, caps}`.
337    pub fn join_field(
338        &self,
339        caps: &Caps,
340        gateway_session: &str,
341    ) -> Result<E2eeJoin, IdentityError> {
342        Ok(E2eeJoin {
343            key_package_ref: self.uploaded_ref()?,
344            gateway_session: gateway_session.to_owned(),
345            caps: caps.to_wire(),
346        })
347    }
348
349    /// The key join body for a move, with the server-minted `join_id` from `voice_server_updated`.
350    pub fn key_join_request(
351        &self,
352        join_id: JoinId,
353        caps: &Caps,
354        gateway_session: &str,
355    ) -> Result<KeyJoinRequest, IdentityError> {
356        Ok(KeyJoinRequest {
357            join_id,
358            gateway_session: gateway_session.to_owned(),
359            key_package_ref: self.uploaded_ref()?,
360            caps: caps.to_wire(),
361        })
362    }
363
364    /// Starts the session from the server's answer (`CallKeysInit`: `join_id`, `lk_identity`,
365    /// `scope`, group, params). Checks `lk_identity == "p_" + base32(join_id)`.
366    pub fn into_session(
367        self,
368        client: &E2eeClient,
369        init: CallKeysInit,
370        gateway_session: &str,
371        now: UnixMs,
372    ) -> Result<CallSession, SessionError> {
373        CallSession::start(client, self, init, gateway_session, now)
374    }
375}
376
377/// What to do when the voice join or the key join refused the join: `Ok(())` means prepare and
378/// upload a fresh package and retry **once** (`422 e2ee_key_package_ref_unknown`, `409
379/// e2ee_key_package_ref_used`); a second ref failure is `JoinError::KeyPackage`; `422
380/// e2ee_unsupported_client` is `JoinError::Unsupported{unsupported}`.
381pub fn on_join_failure(
382    f: &crate::wire::ApiFailure,
383    already_retried: bool,
384) -> Result<(), JoinError> {
385    use sew_proto::e2ee::reasons;
386    let ref_failure = (f.status == 422 && f.is(reasons::E2EE_KEY_PACKAGE_REF_UNKNOWN))
387        || (f.status == 409 && f.is(reasons::E2EE_KEY_PACKAGE_REF_USED));
388    if ref_failure {
389        return if already_retried {
390            Err(JoinError::KeyPackage)
391        } else {
392            Ok(())
393        };
394    }
395    if f.status == 422 && f.is(reasons::E2EE_UNSUPPORTED_CLIENT) {
396        return Err(JoinError::Unsupported {
397            unsupported: f.detail.clone().unwrap_or_default(),
398        });
399    }
400    Err(JoinError::Session(SessionError::Refused("join refused")))
401}