1use 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
30pub const CS1: Ciphersuite = Ciphersuite::MLS_128_DHKEMX25519_AES128GCM_SHA256_Ed25519;
32
33pub 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
46pub(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
61pub(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 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 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#[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 pub fn new(identity: DeviceIdentity, trust: TrustAnchors) -> E2eeClient {
168 E2eeClient {
169 identity,
170 trust,
171 cfg: E2eeConfig::default(),
172 }
173 }
174
175 pub fn with_config(mut self, cfg: E2eeConfig) -> E2eeClient {
177 self.cfg = cfg;
178 self
179 }
180
181 pub fn set_config(&mut self, cfg: E2eeConfig) {
183 self.cfg = cfg;
184 }
185
186 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 pub fn trust_mut(&mut self) -> &mut TrustAnchors {
210 &mut self.trust
211 }
212
213 pub fn trust(&self) -> &TrustAnchors {
215 &self.trust
216 }
217
218 pub fn identity(&self) -> &DeviceIdentity {
220 &self.identity
221 }
222
223 pub fn config(&self) -> &E2eeConfig {
225 &self.cfg
226 }
227}
228
229pub 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 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
267pub 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 pub fn upload_body(&self) -> KeyPackageUploadRequest {
290 KeyPackageUploadRequest {
291 key_packages: vec![B64::new(self.bytes.clone())],
292 }
293 }
294
295 pub fn key_package_ref(&self) -> [u8; 32] {
297 self.leaf.kp_ref
298 }
299
300 pub fn key_package_bytes(&self) -> &[u8] {
302 &self.bytes
303 }
304
305 pub fn scope(&self) -> CallScope {
307 self.scope
308 }
309
310 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 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 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 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 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
377pub 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}