Skip to main content

sew_call_client/e2ee/
session.rs

1//! The key session: everything between a join answer and active call keys.
2//!
3//! The order after a join answer:
4//! 1. open the call socket and read READY's `session_id` (the join's `e2ee.gateway_session`) and
5//!    the trust anchors (TOFU-pinned in the device file);
6//! 2. load or enrol the device ([`crate::device::DeviceVault::ensure_device`]);
7//! 3. upload a KeyPackage for `call:<channel_id>`;
8//! 4. key-join: the key join route with the credential's `join_id` ([`MlsSession::key_join`],
9//!    the deferred key join and every move), or inline in the voice join (the host's join carried
10//!    [`MlsSession::prepare_join`]'s `e2ee`, then [`MlsSession::begin`]);
11//! 5. drive `sew-e2ee`'s `CallSession`: `call_keys_delivered` in, the call key routes out,
12//!    `KeyEvent`s into [`MediaKeys`], the media path's reports back as `report` inputs.
13//!
14//! Recording (Sew 0.7.3): the call socket's own `recording_updated` and READY's
15//! `recording` reach the owner as [`KeySessionEvent::Recording`]; the owner (the engine)
16//! decides which recording is the call's and feeds it back with [`MlsSession::set_recording`],
17//! which `sew-e2ee` turns into the recorder key release (only for `granted`) or a rekey on a
18//! withdrawal. The last state is applied again to every new key session (a move, a re-join), so
19//! a new session never starts from a stale `granted`: it starts `pending` until fed.
20//!
21//! The credential is renewed at half its life and the socket re-authenticated (REAUTH). A device
22//! the server refuses (revoked, or its certificate failed) is forgotten, enrolled once and the
23//! step retried once (Sew 0.7.1's rule); the pins are kept. A pin mismatch ends with
24//! `ca_pin_mismatch` and is never re-pinned.
25//!
26//! The session and the bridge sit behind a short-held mutex; HTTP runs with it released.
27
28use std::collections::{BTreeMap, BTreeSet};
29use std::fmt;
30use std::sync::{Arc, Mutex};
31use std::time::Duration;
32
33use sew_e2ee::keypackage::on_join_failure;
34use sew_e2ee::{
35    ApiFailure, CallSession, E2eeClient, E2eeStatus, Input, JoinId, KeyEvent, KeySink as _,
36    LeftReason, LkIdentity, Output, PreparedKp, SessionState, SinkAck, TrustAnchors,
37    UnknownCallBuffer,
38};
39use sew_proto::e2ee::{CallKeysInit, CallScope, ConsentState, E2eeJoin};
40use sew_proto::id::Id;
41use sew_proto::recording::{Recording, RecordingControls};
42use sew_proto::voice::{MediaPolicy, VoiceServerUpdated, VoiceStateUpdated};
43use tokio::sync::mpsc;
44use url::Url;
45
46use super::credential::{Bearer, CredentialGrant, RenewRefused, SharedBearer, renew_at, unix_ms};
47use super::frame::FrameCrypto;
48use super::keys::{MediaKeys, MediaReport, engine_caps, lock};
49use super::transport::{KeyTransport, TransportError};
50use crate::Clock;
51use crate::device::{
52    DeviceError, DeviceKey, DeviceVault, DeviceWarning, VaultConfig, is_device_refused,
53};
54use crate::gateway::{CallReadyInfo, CallSocket, SocketClosed, SocketError, SocketEvent};
55
56/// How long [`MlsSession::connect`] waits for the call socket's READY.
57pub const READY_TIMEOUT: Duration = Duration::from_secs(15);
58/// The driver wakes at least this often (timers, the media path's reports).
59pub const TICK: Duration = Duration::from_millis(100);
60
61/// What the key session needs.
62#[derive(Clone)]
63#[non_exhaustive]
64pub struct KeySessionConfig {
65    /// The door (`JoinAnswer.api_base`).
66    pub api_base: Url,
67    /// The bearer: the call credential's token (a `sews_` session token only in tests).
68    pub bearer: Bearer,
69    /// When the credential expires (unix ms); `None`: never renewed (a `sews_` test bearer).
70    pub credential_expires_at_ms: Option<u64>,
71    /// The credential's `device_scope` (the stored device is keyed on it).
72    pub device_scope: String,
73    /// Where the device lives.
74    pub vault: VaultConfig,
75    /// The install id when the call socket's READY does not carry one.
76    pub install_id: Option<u64>,
77    /// The clock (unix ms).
78    pub clock: Clock,
79    /// The TLS trust of the key routes and the call socket (`None`: the platform's, as the
80    /// engine's own connections).
81    pub tls: Option<Arc<rustls::ClientConfig>>,
82}
83
84impl fmt::Debug for KeySessionConfig {
85    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
86        f.debug_struct("KeySessionConfig")
87            .field("host", &self.api_base.host_str())
88            .field("bearer", &self.bearer)
89            .field("device_scope", &self.device_scope)
90            .finish_non_exhaustive()
91    }
92}
93
94impl KeySessionConfig {
95    /// A key session config with its required fields: no `credential_expires_at_ms` (never
96    /// renewed), no `install_id` (READY's) and no `tls` (the platform's trust).
97    pub fn new(
98        api_base: Url,
99        bearer: Bearer,
100        device_scope: impl Into<String>,
101        vault: VaultConfig,
102        clock: Clock,
103    ) -> KeySessionConfig {
104        KeySessionConfig {
105            api_base,
106            bearer,
107            credential_expires_at_ms: None,
108            device_scope: device_scope.into(),
109            vault,
110            install_id: None,
111            clock,
112            tls: None,
113        }
114    }
115
116    /// From the join answer's credential.
117    pub fn from_grant(
118        api_base: Url,
119        grant: &CredentialGrant,
120        vault: VaultConfig,
121        clock: Clock,
122    ) -> KeySessionConfig {
123        KeySessionConfig {
124            api_base,
125            bearer: Bearer::new(grant.token.clone()),
126            credential_expires_at_ms: Some(unix_ms(grant.expires_at)),
127            device_scope: grant.device_scope.clone(),
128            vault,
129            install_id: None,
130            clock,
131            tls: None,
132        }
133    }
134}
135
136/// Why the key session failed (the `errors` codes in brackets).
137#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
138#[non_exhaustive]
139pub enum KeyError {
140    /// The door or the client could not be set up.
141    #[error("transport: {0}")]
142    Transport(String),
143    /// The call socket closed before READY, or READY was unreadable.
144    #[error("the call socket did not become ready")]
145    NoReady,
146    /// READY carried no trust anchors (`call_keys`).
147    #[error("the call socket's READY has no call_keys")]
148    NoTrustAnchors,
149    /// No install id (neither READY nor the config).
150    #[error("no install id")]
151    NoInstallId,
152    /// A pinned server key changed (`ca_pin_mismatch`). Only `reset_device` clears the pins.
153    #[error("the server's call identity changed ({0})")]
154    PinMismatch(&'static str),
155    /// READY's trust anchors are malformed.
156    #[error("trust anchors refused: {0}")]
157    Trust(String),
158    /// The device store or enrolment failed.
159    #[error("device: {0}")]
160    Device(#[from] DeviceError),
161    /// The server refused the key join for good (`e2ee_refused`).
162    #[error("key join refused ({status} {reason:?})")]
163    Refused {
164        /// HTTP status.
165        status: u16,
166        /// `details.reason`.
167        reason: Option<String>,
168    },
169    /// The MLS session could not start or failed.
170    #[error("session: {0}")]
171    Session(String),
172    /// The key session is closed.
173    #[error("closed")]
174    Closed,
175}
176
177impl From<TransportError> for KeyError {
178    fn from(e: TransportError) -> Self {
179        KeyError::Transport(e.to_string())
180    }
181}
182
183impl From<SocketError> for KeyError {
184    fn from(e: SocketError) -> Self {
185        KeyError::Transport(e.to_string())
186    }
187}
188
189impl KeyError {
190    /// The plugin's `errors.code` / `ended.reason`.
191    pub fn code(&self) -> &'static str {
192        match self {
193            KeyError::PinMismatch(_) => "ca_pin_mismatch",
194            KeyError::Refused { .. } | KeyError::Session(_) => "e2ee_refused",
195            KeyError::Device(_) => "e2ee_refused",
196            KeyError::Closed => "credential_lost",
197            _ => "network",
198        }
199    }
200}
201
202fn refused(f: &ApiFailure) -> KeyError {
203    KeyError::Refused {
204        status: f.status,
205        reason: f.reason.clone(),
206    }
207}
208
209/// Why the key session ended by itself.
210#[derive(Debug, Clone, PartialEq, Eq)]
211#[non_exhaustive]
212pub enum KeyEnd {
213    /// The credential is gone (`4011`, or a renewal refused): `credential_lost`. `rejoin` is
214    /// true when the engine may re-join through the `JoinProvider` (`expired`).
215    CredentialLost {
216        /// Why.
217        reason: String,
218        /// Whether a re-join may follow.
219        rejoin: bool,
220    },
221    /// Sew ended this join and said why (Sew 0.7.2): the `4011` close of the call socket named
222    /// the reason ([`SocketClosed::Ended`]); `reason` is Sew's voice leave reason as it
223    /// arrived (`replaced`: another device took the call over).
224    Ended {
225        /// Why.
226        reason: String,
227    },
228    /// The call socket ended for good (`4004`, a protocol error).
229    Socket(SocketClosed),
230    /// The MLS session left (removed, or failed for good).
231    Left(LeftReason),
232    /// The device key could not sign in the call (a hardware key's error: `e2ee_refused`; no
233    /// software fallback).
234    Device(DeviceError),
235}
236
237/// What the key session tells the engine.
238#[derive(Debug, Clone)]
239#[non_exhaustive]
240pub enum KeySessionEvent {
241    /// The E2EE status changed (`connected` needs `Active`).
242    Status(E2eeStatus),
243    /// The verified roster changed: re-check tracks that were `SubscribeDecision::Wait`.
244    Roster,
245    /// `voice_server_updated` (a move: reconnect signalling with its token; the key session
246    /// key-joins the new `join_id` by itself).
247    VoiceServerUpdated(Box<VoiceServerUpdated>),
248    /// `voice_state_updated` of the call's channel (the plugin's `participants`).
249    VoiceStateUpdated(Box<VoiceStateUpdated>),
250    /// A recording as this member sees it (the socket's own `recording_updated`, or the call
251    /// socket's READY `recording`); `None`: READY says the call has no active recording. Never
252    /// fed to the keys by the session itself: see [`MlsSession::set_recording`].
253    Recording(Option<Box<Recording>>),
254    /// The member's Record and Stop from a server that computes them: the call socket's READY
255    /// `recording_controls` (`channel_id` `None`: the call's room; `controls` `None`: no value
256    /// yet) or its `recording_controls_updated`.
257    RecordingControls {
258        /// The room's channel, when the server named it.
259        channel_id: Option<Id>,
260        /// The value, when the server has one.
261        controls: Option<RecordingControls>,
262    },
263    /// `media_policy_updated` (new layer hints, video on or off).
264    MediaPolicy(Box<MediaPolicy>),
265    /// A warning for the host (`key_storage_file`, `pins_reset`).
266    Warning(DeviceWarning),
267    /// A move's key join failed.
268    KeyJoinFailed(KeyError),
269    /// The key session ended by itself.
270    Ended(KeyEnd),
271}
272
273struct Core<C: FrameCrypto> {
274    session: Option<CallSession>,
275    sink: MediaKeys<C>,
276    client: E2eeClient,
277    signer: DeviceKey,
278    prepared: BTreeMap<[u8; 32], PreparedKp>,
279    buffer: UnknownCallBuffer,
280    gateway_session: String,
281    voice_members: BTreeSet<Id>,
282    channel: Option<Id>,
283    last_verified: BTreeSet<LkIdentity>,
284    /// The recording state the owner fed last ([`MlsSession::set_recording`]): applied to every
285    /// new `CallSession`.
286    recording: Option<(Option<Id>, ConsentState)>,
287    ended: bool,
288}
289
290struct Shared<C: FrameCrypto> {
291    core: Mutex<Core<C>>,
292    http: KeyTransport,
293    vault: tokio::sync::Mutex<DeviceVault>,
294    clock: Clock,
295    events: mpsc::UnboundedSender<KeySessionEvent>,
296    member: Id,
297    changed: tokio::sync::Notify,
298}
299
300/// One call's key session.
301pub struct MlsSession<C: FrameCrypto> {
302    shared: Arc<Shared<C>>,
303    socket: Arc<CallSocket>,
304    stop: Arc<tokio::sync::Notify>,
305}
306
307impl<C: FrameCrypto> fmt::Debug for MlsSession<C> {
308    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
309        f.debug_struct("MlsSession")
310            .field("member", &self.shared.member)
311            .field("status", &self.status())
312            .finish_non_exhaustive()
313    }
314}
315
316impl<C: FrameCrypto> Drop for MlsSession<C> {
317    fn drop(&mut self) {
318        self.stop.notify_one();
319        self.socket.close();
320    }
321}
322
323/// Builds the trust anchors from READY against the pins (TOFU; a change is refused) and pages
324/// the CRL when READY's is partial.
325async fn trust_from_ready(
326    ready: &CallReadyInfo,
327    install: u64,
328    vault: &mut DeviceVault,
329    http: &KeyTransport,
330) -> Result<TrustAnchors, KeyError> {
331    let ck = ready.call_keys.as_ref().ok_or(KeyError::NoTrustAnchors)?;
332    let mut trust =
333        TrustAnchors::from_ready(ck, install, vault.file_mut()).map_err(|e| match e {
334            sew_e2ee::TrustError::ServerIdentityChanged { what } => KeyError::PinMismatch(what),
335            other => KeyError::Trust(other.to_string()),
336        })?;
337    if trust.crl_partial() {
338        let mut after = None;
339        for _ in 0..64 {
340            let Ok(page) = http.crl_page(after).await else {
341                break;
342            };
343            trust.revoke(&page.items.iter().map(|s| s.get()).collect::<Vec<_>>());
344            after = page.items.last().copied();
345            if !page.has_more || after.is_none() {
346                break;
347            }
348        }
349    }
350    Ok(trust)
351}
352
353impl<C: FrameCrypto> MlsSession<C> {
354    /// Steps 1–2: opens the call socket, reads READY, pins the trust anchors, loads or enrols
355    /// the device, and starts the driver. Events arrive on the returned receiver.
356    pub async fn connect(
357        cfg: KeySessionConfig,
358        keys: MediaKeys<C>,
359    ) -> Result<(MlsSession<C>, mpsc::UnboundedReceiver<KeySessionEvent>), KeyError> {
360        let bearer = SharedBearer::new(cfg.bearer.clone());
361        let tls = match &cfg.tls {
362            Some(t) => t.clone(),
363            None => {
364                crate::config::platform_tls().map_err(|e| KeyError::Transport(e.to_string()))?
365            }
366        };
367        let http = KeyTransport::new(&cfg.api_base, bearer.clone(), &tls)?;
368        let (socket, mut socket_rx) = CallSocket::open(&cfg.api_base, bearer.clone(), tls)?;
369        let ready = match tokio::time::timeout(READY_TIMEOUT, socket_rx.recv()).await {
370            Ok(Some(SocketEvent::Ready(r))) => *r,
371            Ok(Some(SocketEvent::Closed(SocketClosed::Revoked | SocketClosed::Ended { .. }))) => {
372                return Err(KeyError::Closed);
373            }
374            _ => return Err(KeyError::NoReady),
375        };
376        let install = ready
377            .install_id
378            .map(|i| i.get())
379            .or(cfg.install_id)
380            .ok_or(KeyError::NoInstallId)?;
381        let member = ready.member_id.ok_or(KeyError::NoReady)?;
382        tracing::debug!(target: "sew_call_client::keys", member = %member, install, "call socket ready");
383        let mut vault =
384            DeviceVault::open_async(&cfg.vault, install, member, &cfg.device_scope).await?;
385        let (ev_tx, ev_rx) = mpsc::unbounded_channel();
386        for w in vault.take_warnings() {
387            let _ = ev_tx.send(KeySessionEvent::Warning(w));
388        }
389        if let Some(r) = ready.recording.clone() {
390            let _ = ev_tx.send(KeySessionEvent::Recording(r.map(Box::new)));
391        }
392        if let Some(c) = ready.recording_controls.clone() {
393            let _ = ev_tx.send(KeySessionEvent::RecordingControls {
394                channel_id: None,
395                controls: c,
396            });
397        }
398        let trust = trust_from_ready(&ready, install, &mut vault, &http).await?;
399        let now = (cfg.clock)();
400        let (identity, signer) = vault.ensure_device(&http, &trust, member, now).await?;
401        let params = trust.params().map_err(|e| KeyError::Trust(e.to_string()))?;
402        let client = E2eeClient::new(identity, trust);
403        let buffer = UnknownCallBuffer::new(&params, client.config());
404        let shared = Arc::new(Shared {
405            core: Mutex::new(Core {
406                session: None,
407                sink: keys,
408                client,
409                signer,
410                prepared: BTreeMap::new(),
411                buffer,
412                gateway_session: ready.session_id.clone(),
413                voice_members: BTreeSet::new(),
414                channel: None,
415                last_verified: BTreeSet::new(),
416                recording: None,
417                ended: false,
418            }),
419            http,
420            vault: tokio::sync::Mutex::new(vault),
421            clock: cfg.clock.clone(),
422            events: ev_tx,
423            member,
424            changed: tokio::sync::Notify::new(),
425        });
426        let socket = Arc::new(socket);
427        let stop = Arc::new(tokio::sync::Notify::new());
428        let renew = cfg
429            .credential_expires_at_ms
430            .filter(|_| cfg.bearer.is_call_credential())
431            .map(|exp| renew_at(now, exp));
432        tokio::spawn(drive(
433            Arc::downgrade(&shared),
434            socket.clone(),
435            socket_rx,
436            stop.clone(),
437            renew,
438        ));
439        Ok((
440            MlsSession {
441                shared,
442                socket,
443                stop,
444            },
445            ev_rx,
446        ))
447    }
448
449    /// The call socket's `session_id` (the join's `e2ee.gateway_session`).
450    pub fn gateway_session(&self) -> String {
451        lock(&self.shared.core).gateway_session.clone()
452    }
453
454    /// The member.
455    pub fn member_id(&self) -> Id {
456        self.shared.member
457    }
458
459    /// The key state the media path reads.
460    pub fn media_keys(&self) -> MediaKeys<C> {
461        lock(&self.shared.core).sink.clone()
462    }
463
464    /// The device in use (its id).
465    pub fn device_id(&self) -> Id {
466        lock(&self.shared.core).client.identity().device_id()
467    }
468
469    /// The last E2EE status.
470    pub fn status(&self) -> Option<E2eeStatus> {
471        lock(&self.shared.core)
472            .session
473            .as_ref()
474            .and_then(|s| s.status().cloned())
475    }
476
477    /// The MLS session state.
478    pub fn state(&self) -> Option<SessionState> {
479        lock(&self.shared.core).session.as_ref().map(|s| s.state())
480    }
481
482    /// Whether a key epoch is active and the local sender has a key (`connected`).
483    pub fn is_active(&self) -> bool {
484        let c = lock(&self.shared.core);
485        let active = c.session.as_ref().is_some_and(|s| {
486            matches!(s.state(), SessionState::Active { .. }) && s.active_epoch().is_some()
487        });
488        active && c.sink.local_slot().is_some()
489    }
490
491    /// The local engine identity of the current join.
492    pub fn lk_identity(&self) -> Option<LkIdentity> {
493        lock(&self.shared.core)
494            .session
495            .as_ref()
496            .map(|s| s.lk_identity().clone())
497    }
498
499    /// Waits until `pred` holds or `timeout` passes.
500    pub async fn wait_until(&self, timeout: Duration, pred: impl Fn(&Self) -> bool) -> bool {
501        let deadline = tokio::time::Instant::now() + timeout;
502        loop {
503            if pred(self) {
504                return true;
505            }
506            if tokio::time::Instant::now() >= deadline {
507                return false;
508            }
509            let n = self.shared.changed.notified();
510            let _ = tokio::time::timeout(Duration::from_millis(50), n).await;
511        }
512    }
513
514    /// Steps 3 and 4 inline: a KeyPackage for `call:<channel>` uploaded, and the `e2ee` object
515    /// of a voice or DM call join. Hand the join's `CallKeysInit` to [`MlsSession::begin`].
516    pub async fn prepare_join(&self, channel: Id) -> Result<E2eeJoin, KeyError> {
517        let kp = self.prepared_kp(CallScope::call(channel)).await?;
518        let mut guard = lock(&self.shared.core);
519        let c = &mut *guard;
520        let join = kp
521            .join_field(&engine_caps(), &c.gateway_session)
522            .map_err(|e| KeyError::Session(e.to_string()))?;
523        c.channel = Some(channel);
524        c.prepared.insert(kp.key_package_ref(), kp);
525        Ok(join)
526    }
527
528    /// Starts the MLS session from a voice join answer (`VoiceJoinResponse.e2ee`).
529    pub async fn begin(&self, init: CallKeysInit) -> Result<(), KeyError> {
530        start_session(&self.shared, init, None).await
531    }
532
533    /// Steps 3–4 for a deferred key join or a move: a KeyPackage for `call:<channel>`, then the key
534    /// join with `join_id`, then the session. A stale ref is re-uploaded once; a refused device is
535    /// forgotten, enrolled once and the join retried once.
536    pub async fn key_join(&self, channel: Id, join_id: JoinId) -> Result<(), KeyError> {
537        key_join(&self.shared, channel, join_id).await
538    }
539
540    /// Leaves: the session zeroizes its secrets, every remote key is dropped, the socket closes.
541    /// (The voice leave itself is `POST /api/v1/me/voice/leave`, the engine's.)
542    pub async fn leave(&self) {
543        let now = (self.shared.clock)();
544        {
545            let mut guard = lock(&self.shared.core);
546            let c = &mut *guard;
547            if let Some(s) = c.session.as_mut() {
548                s.leave(now);
549            }
550            let _ = c.sink.apply(KeyEvent::Clear);
551            c.ended = true;
552        }
553        pump(&self.shared).await;
554        self.stop.notify_one();
555        self.socket.close();
556    }
557
558    /// The host's explicit `reset_device` (a Rust API, never a webview command): forgets the
559    /// device, its key and the pins.
560    pub async fn reset_device(&self) -> Result<(), KeyError> {
561        let mut v = self.shared.vault.lock().await;
562        v.reset().await?;
563        Ok(())
564    }
565
566    /// The live bearer (renewed in place).
567    pub fn bearer(&self) -> Bearer {
568        self.shared.http.bearer().get()
569    }
570
571    /// The device's network changed: the call socket reconnects at once and resumes.
572    pub fn network_changed(&self) {
573        self.socket.reconnect();
574    }
575
576    /// The engine renewed the call credential: the key routes use the new token from now on,
577    /// and the call socket re-authenticates with it (REAUTH keeps the `session_id`).
578    pub fn renewed(&self, token: Bearer) {
579        self.shared.http.bearer().set(token);
580        self.socket.reauth();
581    }
582
583    /// The call's recording state as Sew said it (never local state): the live recording of
584    /// the call's room (`None`: none) and this member's consent for it. `sew-e2ee` releases this
585    /// device's key to the recorder only while the recording is announced, live and
586    /// `Granted`, and asks for an immediate rekey when `Granted` ends (a withdrawal). Kept and
587    /// applied again to each new key session of this socket.
588    pub async fn set_recording(&self, recording_id: Option<Id>, my_consent: ConsentState) {
589        {
590            let mut guard = lock(&self.shared.core);
591            let c = &mut *guard;
592            if c.recording == Some((recording_id, my_consent)) {
593                return;
594            }
595            c.recording = Some((recording_id, my_consent));
596        }
597        tracing::debug!(target: "sew_call_client::keys", recording = ?recording_id, consent = ?my_consent, "recording state");
598        input(
599            &self.shared,
600            Input::Recording {
601                recording_id,
602                my_consent,
603            },
604        )
605        .await;
606    }
607
608    /// The recording state last given to [`MlsSession::set_recording`].
609    pub fn recording(&self) -> Option<(Option<Id>, ConsentState)> {
610        lock(&self.shared.core).recording
611    }
612
613    /// The key state and the active epoch's security code (`None` before the session has a
614    /// status).
615    pub fn security(&self) -> Option<crate::call::CallSecurity> {
616        let c = lock(&self.shared.core);
617        let s = c.session.as_ref()?;
618        let mut out = security_of(s.status()?);
619        out.code = s.security_code().map(|code| code.display());
620        Some(out)
621    }
622
623    /// The active key epoch, when the session has one.
624    pub fn active_epoch(&self) -> Option<u64> {
625        lock(&self.shared.core)
626            .session
627            .as_ref()
628            .and_then(|s| s.active_epoch())
629    }
630
631    /// The engine identities bound to a leaf of the verified tree and the member each is, the
632    /// local one included (the `participants` event's `member_id`).
633    pub fn members(&self) -> Vec<(String, String)> {
634        lock(&self.shared.core)
635            .session
636            .as_ref()
637            .map(|s| {
638                s.roster()
639                    .iter()
640                    .filter(|e| e.leaf_index.is_some())
641                    .map(|e| (e.lk_identity.as_str().to_owned(), e.member_id.to_string()))
642                    .collect()
643            })
644            .unwrap_or_default()
645    }
646
647    /// For tests: the derived keys are not exposed, but the IKMs the session holds are, so a
648    /// test can grep logs for them.
649    #[doc(hidden)]
650    pub fn live_ikms_for_test(&self) -> Vec<[u8; 32]> {
651        let c = lock(&self.shared.core);
652        let Some(s) = c.session.as_ref() else {
653            return Vec::new();
654        };
655        s.key_ring().live().map(|(_, _, k)| *k.expose()).collect()
656    }
657}
658
659impl<C: FrameCrypto> Shared<C> {
660    fn emit(&self, e: KeySessionEvent) {
661        let _ = self.events.send(e);
662    }
663}
664
665/// Prepares and uploads one KeyPackage for `scope`, recovering a refused device once.
666async fn upload_kp<C: FrameCrypto>(
667    shared: &Arc<Shared<C>>,
668    scope: CallScope,
669) -> Result<PreparedKp, KeyError> {
670    let mut recovered = false;
671    loop {
672        let now = (shared.clock)();
673        let (pending, msg, signer) = {
674            let mut guard = lock(&shared.core);
675            let c = &mut *guard;
676            let (pending, req) = c
677                .client
678                .prepare_key_package(scope, now)
679                .map_err(|e| KeyError::Session(e.to_string()))?;
680            (pending, req.message, c.signer.clone())
681        };
682        let mut kp = pending
683            .finish(signer.sign(&msg).await?)
684            .map_err(|e| KeyError::Session(e.to_string()))?;
685        match shared.http.upload_key_package(&mut kp).await {
686            Ok(()) => return Ok(kp),
687            Err(f) if !recovered && is_device_refused(&f) => {
688                recovered = true;
689                recover_device(shared).await?;
690            }
691            Err(f) => return Err(refused(&f)),
692        }
693    }
694}
695
696/// Sew 0.7.1's recovery: forget the refused device (keep the pins), enrol once.
697async fn recover_device<C: FrameCrypto>(shared: &Arc<Shared<C>>) -> Result<(), KeyError> {
698    tracing::info!(target: "sew_call_client::keys", "the device was refused; enrolling again");
699    let trust = lock(&shared.core).client.trust().clone();
700    let now = (shared.clock)();
701    let (identity, signer) = {
702        let mut v = shared.vault.lock().await;
703        v.forget_device().await?;
704        v.enroll(&shared.http, &trust, shared.member, now).await?
705    };
706    let mut guard = lock(&shared.core);
707    let c = &mut *guard;
708    let cfg = c.client.config().clone();
709    c.client = E2eeClient::new(identity, trust).with_config(cfg);
710    c.signer = signer;
711    // Packages signed by the old device are useless now.
712    c.prepared.clear();
713    Ok(())
714}
715
716impl<C: FrameCrypto> MlsSession<C> {
717    async fn prepared_kp(&self, scope: CallScope) -> Result<PreparedKp, KeyError> {
718        upload_kp(&self.shared, scope).await
719    }
720}
721
722async fn key_join<C: FrameCrypto>(
723    shared: &Arc<Shared<C>>,
724    channel: Id,
725    join_id: JoinId,
726) -> Result<(), KeyError> {
727    let scope = CallScope::call(channel);
728    let mut ref_retried = false;
729    let mut device_retried = false;
730    loop {
731        let kp = upload_kp(shared, scope).await?;
732        let body = {
733            let c = lock(&shared.core);
734            kp.key_join_request(join_id.clone(), &engine_caps(), &c.gateway_session)
735                .map_err(|e| KeyError::Session(e.to_string()))?
736        };
737        match shared.http.key_join(&body).await {
738            Ok(init) => {
739                lock(&shared.core).channel = Some(channel);
740                return start_session(shared, init, Some(kp)).await;
741            }
742            Err(f) if !device_retried && is_device_refused(&f) => {
743                device_retried = true;
744                recover_device(shared).await?;
745            }
746            Err(f) => match on_join_failure(&f, ref_retried) {
747                Ok(()) => ref_retried = true,
748                Err(_) => return Err(refused(&f)),
749            },
750        }
751    }
752}
753
754async fn start_session<C: FrameCrypto>(
755    shared: &Arc<Shared<C>>,
756    init: CallKeysInit,
757    kp: Option<PreparedKp>,
758) -> Result<(), KeyError> {
759    let now = (shared.clock)();
760    {
761        let mut guard = lock(&shared.core);
762        let c = &mut *guard;
763        let kp = match kp {
764            Some(k) => k,
765            None => c
766                .prepared
767                .pop_last()
768                .map(|(_, k)| k)
769                .ok_or_else(|| KeyError::Session("no prepared key package".to_owned()))?,
770        };
771        let call_id = init.call_id.clone();
772        if let Some(old) = c.session.as_mut() {
773            // A move: the old call's keys go (its leave is the server's).
774            old.leave(now);
775        }
776        let _ = c.sink.apply(KeyEvent::Clear);
777        let session = kp
778            .into_session(&c.client, init, &c.gateway_session, now)
779            .map_err(|e| KeyError::Session(e.to_string()))?;
780        tracing::debug!(target: "sew_call_client::keys", call = %call_id.as_str(), "key session started");
781        c.session = Some(session);
782        c.prepared.clear();
783        let held = c.buffer.take(now, &call_id);
784        let recording = c.recording;
785        if let Some(s) = c.session.as_mut() {
786            for m in held {
787                let _ = s.handle(now, Input::Server(m));
788            }
789            // A new session starts `pending`: the recording state as last fed.
790            if let Some((recording_id, my_consent)) = recording {
791                let _ = s.handle(
792                    now,
793                    Input::Recording {
794                        recording_id,
795                        my_consent,
796                    },
797                );
798            }
799        }
800    }
801    pump(shared).await;
802    Ok(())
803}
804
805/// Applies key events, answers signatures and self-checks, and POSTs every request (lock
806/// released), feeding the answers back, until the session is quiet. Signatures are made with
807/// the lock released too: a hardware key's `sign` is async and may take its time.
808async fn pump<C: FrameCrypto>(shared: &Arc<Shared<C>>) {
809    loop {
810        let (sends, roster_changed, ended, signs, key) = {
811            let mut guard = lock(&shared.core);
812            let c = &mut *guard;
813            let now = (shared.clock)();
814            let mut sends = Vec::new();
815            let mut signs = Vec::new();
816            let mut roster = false;
817            let Some(session) = c.session.as_mut() else {
818                return;
819            };
820            while let Some(o) = session.poll_output() {
821                match o {
822                    Output::Send(id, req) => sends.push((id, req)),
823                    Output::Key(ev) => {
824                        let fence = match &ev {
825                            KeyEvent::Fence { id } => Some(*id),
826                            _ => None,
827                        };
828                        match c.sink.apply(ev) {
829                            Ok(SinkAck::Now) => {
830                                if let Some(f) = fence {
831                                    let _ = session.handle(now, Input::Installed { fence: f });
832                                }
833                            }
834                            Ok(SinkAck::Later(_)) => {}
835                            Err(e) => {
836                                tracing::warn!(target: "sew_call_client::keys", error = %e, "the bridge refused a key event");
837                            }
838                        }
839                    }
840                    Output::NeedDeviceSignature { request, message } => {
841                        signs.push((request, message));
842                    }
843                    Output::CheckSenderSlot { .. } => {
844                        if let Some(observed) = c.sink.local_slot() {
845                            let _ = session.handle(now, Input::SenderSlotObserved { observed });
846                        }
847                    }
848                    Output::Status(s) => shared.emit(KeySessionEvent::Status(s)),
849                    Output::Roster => roster = true,
850                    _ => {}
851                }
852            }
853            let me = session.lk_identity().clone();
854            let verified: BTreeSet<LkIdentity> = session
855                .roster()
856                .iter()
857                .filter(|e| e.leaf_index.is_some() && e.lk_identity != me)
858                .map(|e| e.lk_identity.clone())
859                .collect();
860            if verified != c.last_verified {
861                c.sink.set_verified(verified.clone());
862                c.last_verified = verified;
863                roster = true;
864            }
865            let ended = match session.state() {
866                SessionState::Left { reason } if !c.ended => {
867                    c.ended = true;
868                    Some(reason)
869                }
870                _ => None,
871            };
872            (sends, roster, ended, signs, c.signer.clone())
873        };
874        if roster_changed {
875            shared.emit(KeySessionEvent::Roster);
876        }
877        if let Some(r) = ended
878            && !matches!(r, LeftReason::Left)
879        {
880            shared.emit(KeySessionEvent::Ended(KeyEnd::Left(r)));
881        }
882        shared.changed.notify_waiters();
883        if sends.is_empty() && signs.is_empty() {
884            return;
885        }
886        for (request, message) in signs {
887            match key.sign(&message).await {
888                Ok(sig) => {
889                    let now = (shared.clock)();
890                    let mut guard = lock(&shared.core);
891                    if let Some(s) = guard.session.as_mut() {
892                        let _ = s.handle(now, Input::DeviceSignature { request, sig });
893                    }
894                }
895                Err(e) => {
896                    // No software fallback: the hardware key could not sign, so the session
897                    // cannot re-add this device. End it.
898                    tracing::warn!(target: "sew_call_client::keys", error = %e, "the device key could not sign");
899                    let first = {
900                        let mut c = lock(&shared.core);
901                        !std::mem::replace(&mut c.ended, true)
902                    };
903                    if first {
904                        shared.emit(KeySessionEvent::Ended(KeyEnd::Device(e)));
905                    }
906                    return;
907                }
908            }
909        }
910        for (id, req) in sends {
911            let r = shared.http.key_request(&req).await;
912            let now = (shared.clock)();
913            let mut guard = lock(&shared.core);
914            let c = &mut *guard;
915            if let Some(s) = c.session.as_mut() {
916                let _ = s.handle(now, Input::Reply(id, r));
917            }
918        }
919    }
920}
921
922/// Feeds one input to the session (if any), then pumps.
923async fn input<C: FrameCrypto>(shared: &Arc<Shared<C>>, i: Input) {
924    {
925        let now = (shared.clock)();
926        let mut guard = lock(&shared.core);
927        let c = &mut *guard;
928        if let Some(s) = c.session.as_mut()
929            && let Err(e) = s.handle(now, i)
930        {
931            tracing::debug!(target: "sew_call_client::keys", error = %e, "input refused");
932        }
933    }
934    pump(shared).await;
935}
936
937fn report_input(r: MediaReport) -> Input {
938    match r {
939        MediaReport::EngineMisbehaviour { kind, identity } => {
940            Input::EngineMisbehaviour { kind, identity }
941        }
942        MediaReport::Undecryptable {
943            identity,
944            since,
945            failures,
946            reason,
947            slot,
948        } => Input::SdkUndecryptable {
949            identity,
950            since,
951            failures,
952            reason,
953            missing_index: slot,
954        },
955        MediaReport::DecryptOk { identity } => Input::SdkDecryptOk { identity },
956    }
957}
958
959async fn on_socket<C: FrameCrypto>(shared: &Arc<Shared<C>>, ev: SocketEvent) -> Option<KeyEnd> {
960    match ev {
961        SocketEvent::CallKeys(m) => {
962            let m = *m;
963            let now = (shared.clock)();
964            let known = {
965                let mut guard = lock(&shared.core);
966                let c = &mut *guard;
967                let call = sew_e2ee::session::call_id_of(&m).cloned();
968                let current = c.session.as_ref().map(|s| s.call_id().clone());
969                match (call, current) {
970                    (Some(call), Some(cur)) if call != cur => {
971                        let size = serde_json::to_vec(&m).map(|v| v.len()).unwrap_or(1024);
972                        c.buffer.push(now, call, m, size);
973                        None
974                    }
975                    (Some(call), None) => {
976                        let size = serde_json::to_vec(&m).map(|v| v.len()).unwrap_or(1024);
977                        c.buffer.push(now, call, m, size);
978                        None
979                    }
980                    _ => Some(m),
981                }
982            };
983            if let Some(m) = known {
984                input(shared, Input::Server(m)).await;
985            }
986            None
987        }
988        SocketEvent::Ready(r) => {
989            // A new gateway session (RESUME refused): re-bind with the `state` route.
990            if let Some(rec) = r.recording.clone() {
991                shared.emit(KeySessionEvent::Recording(rec.map(Box::new)));
992            }
993            if let Some(c) = r.recording_controls.clone() {
994                shared.emit(KeySessionEvent::RecordingControls {
995                    channel_id: None,
996                    controls: c,
997                });
998            }
999            {
1000                let mut guard = lock(&shared.core);
1001                let c = &mut *guard;
1002                c.gateway_session = r.session_id.clone();
1003                if let Some(ck) = &r.call_keys
1004                    && let Err(e) = c.client.trust_mut().refresh(ck)
1005                {
1006                    tracing::warn!(target: "sew_call_client::keys", error = %e, "READY's trust anchors refused");
1007                }
1008            }
1009            input(
1010                shared,
1011                Input::GatewayReidentified {
1012                    gateway_session: r.session_id,
1013                },
1014            )
1015            .await;
1016            None
1017        }
1018        SocketEvent::Resumed => {
1019            input(shared, Input::GatewayResumed).await;
1020            None
1021        }
1022        SocketEvent::VoiceServerUpdated(u) => {
1023            shared.emit(KeySessionEvent::VoiceServerUpdated(u.clone()));
1024            let s = shared.clone();
1025            let (channel, join) = (u.channel_id, u.e2ee.join_id.clone());
1026            tokio::spawn(async move {
1027                if let Err(e) = key_join(&s, channel, join).await {
1028                    s.emit(KeySessionEvent::KeyJoinFailed(e));
1029                }
1030            });
1031            None
1032        }
1033        SocketEvent::VoiceStateUpdated(u) => {
1034            let members = {
1035                let mut guard = lock(&shared.core);
1036                let c = &mut *guard;
1037                let here = c.channel;
1038                if u.channel_id.is_some() && u.channel_id == here {
1039                    c.voice_members.insert(u.member_id);
1040                } else {
1041                    c.voice_members.remove(&u.member_id);
1042                }
1043                c.voice_members.iter().copied().collect::<Vec<_>>()
1044            };
1045            shared.emit(KeySessionEvent::VoiceStateUpdated(u));
1046            input(shared, Input::VoiceMembers(members)).await;
1047            None
1048        }
1049        SocketEvent::RecordingUpdated(r) => {
1050            shared.emit(KeySessionEvent::Recording(Some(r)));
1051            None
1052        }
1053        SocketEvent::MediaPolicyUpdated(m) => {
1054            shared.emit(KeySessionEvent::MediaPolicy(m));
1055            None
1056        }
1057        SocketEvent::RecordingControls(u) => {
1058            shared.emit(KeySessionEvent::RecordingControls {
1059                channel_id: Some(u.channel_id),
1060                controls: Some(u.controls()),
1061            });
1062            None
1063        }
1064        SocketEvent::Closed(SocketClosed::Revoked) => Some(KeyEnd::CredentialLost {
1065            reason: "session_revoked".to_owned(),
1066            rejoin: false,
1067        }),
1068        SocketEvent::Closed(SocketClosed::Ended { reason }) => Some(KeyEnd::Ended { reason }),
1069        SocketEvent::Closed(SocketClosed::Closed) => None,
1070        SocketEvent::Closed(other) => Some(KeyEnd::Socket(other)),
1071    }
1072}
1073
1074async fn drive<C: FrameCrypto>(
1075    weak: std::sync::Weak<Shared<C>>,
1076    socket: Arc<CallSocket>,
1077    mut rx: mpsc::Receiver<SocketEvent>,
1078    stop: Arc<tokio::sync::Notify>,
1079    mut renew: Option<u64>,
1080) {
1081    loop {
1082        let next = {
1083            let Some(shared) = weak.upgrade() else {
1084                return;
1085            };
1086            let c = lock(&shared.core);
1087            let now = (shared.clock)();
1088            let mut next = now + TICK.as_millis() as u64;
1089            if let Some(t) = c.session.as_ref().and_then(|s| s.poll_timeout()) {
1090                next = next.min(t);
1091            }
1092            if let Some(t) = renew {
1093                next = next.min(t);
1094            }
1095            next.saturating_sub(now)
1096        };
1097        let ev = tokio::select! {
1098            _ = stop.notified() => return,
1099            e = rx.recv() => match e {
1100                Some(e) => Some(e),
1101                None => return,
1102            },
1103            _ = tokio::time::sleep(Duration::from_millis(next)) => None,
1104        };
1105        let Some(shared) = weak.upgrade() else {
1106            return;
1107        };
1108        if let Some(e) = ev
1109            && let Some(end) = on_socket(&shared, e).await
1110        {
1111            shared.emit(KeySessionEvent::Ended(end));
1112            return;
1113        }
1114        // Timers.
1115        let now = (shared.clock)();
1116        {
1117            let mut guard = lock(&shared.core);
1118            let c = &mut *guard;
1119            if let Some(s) = c.session.as_mut()
1120                && s.poll_timeout().is_some_and(|t| t <= now)
1121            {
1122                s.handle_timeout(now);
1123            }
1124            c.buffer.expire(now);
1125        }
1126        // The media path's reports (the `report` route, the receiver check).
1127        let reports = lock(&shared.core).sink.take_reports();
1128        for r in reports {
1129            input(&shared, report_input(r)).await;
1130        }
1131        pump(&shared).await;
1132        // The credential.
1133        if let Some(at) = renew
1134            && now >= at
1135        {
1136            match shared.http.renew_credential().await {
1137                Ok(a) => {
1138                    socket.reauth();
1139                    renew = Some(renew_at(now, unix_ms(a.expires_at)));
1140                }
1141                Err(f) if f.is_retryable() => {
1142                    renew = Some(now + 5_000);
1143                }
1144                Err(f) => {
1145                    let r = RenewRefused::from_failure(&f);
1146                    shared.emit(KeySessionEvent::Ended(KeyEnd::CredentialLost {
1147                        reason: f.reason.clone().unwrap_or_else(|| f.status.to_string()),
1148                        rejoin: r.allows_rejoin(),
1149                    }));
1150                    return;
1151                }
1152            }
1153        }
1154    }
1155}
1156
1157/// A key status as the engine's [`crate::call::CallSecurity`] (without the code).
1158pub(crate) fn security_of(s: &E2eeStatus) -> crate::call::CallSecurity {
1159    let mut out = crate::call::CallSecurity::default();
1160    out.state = match s {
1161        E2eeStatus::Preparing => "preparing",
1162        E2eeStatus::Joining { since } => {
1163            out.since_ms = Some(*since);
1164            "joining"
1165        }
1166        E2eeStatus::Active { epoch, since } => {
1167            out.epoch = Some(*epoch);
1168            out.since_ms = Some(*since);
1169            "active"
1170        }
1171        E2eeStatus::Securing {
1172            since,
1173            show_after_ms,
1174        } => {
1175            out.since_ms = Some(*since);
1176            out.show_after_ms = Some(*show_after_ms);
1177            "securing"
1178        }
1179        E2eeStatus::Recovering { reason, since } => {
1180            out.since_ms = Some(*since);
1181            out.reason = Some((*reason).to_owned());
1182            "recovering"
1183        }
1184        E2eeStatus::DeviceNotEnrolled => "device_not_enrolled",
1185        E2eeStatus::ServerIdentityChanged => "server_identity_changed",
1186        E2eeStatus::Unsupported { reason } => {
1187            out.reason = Some(reason.clone());
1188            "unsupported"
1189        }
1190        E2eeStatus::Failed { reason } => {
1191            out.reason = Some((*reason).to_owned());
1192            "failed"
1193        }
1194        E2eeStatus::Left { reason } => {
1195            out.reason = Some(match reason {
1196                LeftReason::Left => "left".to_owned(),
1197                LeftReason::Removed(r) => format!("removed:{}", r.as_str()),
1198                LeftReason::Failed(r) => format!("failed:{r}"),
1199                _ => "other".to_owned(),
1200            });
1201            "left"
1202        }
1203        _ => "unknown",
1204    }
1205    .to_owned();
1206    out
1207}
1208
1209#[cfg(test)]
1210mod security_tests {
1211    use super::*;
1212    use sew_proto::e2ee::RemoveReason;
1213
1214    #[test]
1215    fn each_key_status_is_its_security_state() {
1216        let s = security_of(&E2eeStatus::Active {
1217            epoch: 7,
1218            since: 1_000,
1219        });
1220        assert_eq!(
1221            (s.state.as_str(), s.epoch, s.since_ms, s.code),
1222            ("active", Some(7), Some(1_000), None)
1223        );
1224        let s = security_of(&E2eeStatus::Securing {
1225            since: 5,
1226            show_after_ms: 1_500,
1227        });
1228        assert_eq!(
1229            (s.state.as_str(), s.since_ms, s.show_after_ms, s.epoch),
1230            ("securing", Some(5), Some(1_500), None)
1231        );
1232        let s = security_of(&E2eeStatus::Recovering {
1233            reason: "readd",
1234            since: 9,
1235        });
1236        assert_eq!(
1237            (s.state.as_str(), s.reason.as_deref()),
1238            ("recovering", Some("readd"))
1239        );
1240        assert_eq!(security_of(&E2eeStatus::Preparing).state, "preparing");
1241        assert_eq!(
1242            security_of(&E2eeStatus::Joining { since: 3 }).since_ms,
1243            Some(3)
1244        );
1245        assert_eq!(
1246            security_of(&E2eeStatus::DeviceNotEnrolled).state,
1247            "device_not_enrolled"
1248        );
1249        assert_eq!(
1250            security_of(&E2eeStatus::ServerIdentityChanged).state,
1251            "server_identity_changed"
1252        );
1253        let s = security_of(&E2eeStatus::Unsupported {
1254            reason: "no_insertable_streams".to_owned(),
1255        });
1256        assert_eq!(
1257            (s.state.as_str(), s.reason.as_deref()),
1258            ("unsupported", Some("no_insertable_streams"))
1259        );
1260        let s = security_of(&E2eeStatus::Failed {
1261            reason: "recovery_timeout",
1262        });
1263        assert_eq!(s.reason.as_deref(), Some("recovery_timeout"));
1264        let s = security_of(&E2eeStatus::Left {
1265            reason: LeftReason::Removed(RemoveReason::PermsLost),
1266        });
1267        assert_eq!(
1268            (s.state.as_str(), s.reason.as_deref()),
1269            ("left", Some("removed:perms_lost"))
1270        );
1271        let s = security_of(&E2eeStatus::Left {
1272            reason: LeftReason::Left,
1273        });
1274        assert_eq!(s.reason.as_deref(), Some("left"));
1275    }
1276
1277    #[test]
1278    fn the_security_json_writes_only_what_it_has() {
1279        let code = "01234 56789 01234 56789 01234 56789";
1280        let s = crate::call::CallSecurity::active(3, Some(code.into()));
1281        assert_eq!(
1282            serde_json::to_value(&s).unwrap_or_default(),
1283            serde_json::json!({"state": "active", "epoch": 3, "code": code})
1284        );
1285        assert_eq!(
1286            serde_json::to_value(crate::call::CallSecurity::new("joining")).unwrap_or_default(),
1287            serde_json::json!({"state": "joining"})
1288        );
1289    }
1290}