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