Skip to main content

sew_e2ee/session/
mod.rs

1//! `CallSession`: the per-call state machine.
2//!
3//! Sans-IO: it takes inputs (server messages, replies, bridge acknowledgements, device
4//! signatures, time) and emits outputs (key routes to POST, key events for the bridge, status).
5//! It never does IO, never reads a clock, never spawns and never blocks. Every method is
6//! synchronous and `&mut self`; there are no threads and no `Send` requirement.
7//!
8//! Invariants (asserted by tests and the session fuzzer):
9//! - **I1** the local identity's key appears only in `Activate`, never in `Install`;
10//! - **I2** `Activate{e}` only after `Ready{e}` was sent, or by the fallback;
11//! - **I3** `Ready{e}` only after `Installed{fence}` for every `Install` of epoch `e`;
12//! - **I4** a `Retire` never targets the slot that is current or pending for that identity;
13//! - **I5** no output contains key bytes except `Key(Install | Activate | Retire)`;
14//! - **I6** for a given `(group, epoch, identity)` the IKM is the same on every member.
15
16mod buffer;
17mod io;
18mod mls;
19mod recorder;
20mod recover;
21mod roster;
22
23use std::collections::{BTreeMap, BTreeSet, VecDeque};
24use std::fmt;
25
26use openmls::prelude::MlsGroup;
27use sew_mls_crypto::SignatureKeyPair;
28use sew_proto::e2ee::{CallKeysInit, CallKeysMessage, KeyResyncReason, VerificationCode};
29
30use crate::bridge::{KeyEvent, KeyRing};
31use crate::code::SecurityCode;
32use crate::config::{E2eeConfig, Params};
33use crate::error::SessionError;
34use crate::identity::{DeviceIdentity, LeafIdentity, VerifiedEntry};
35use crate::ids::{
36    Epoch, FenceId, JoinId, LkIdentity, Millis, RequestId, RoomName, SignId, Slot, identity_matches,
37};
38use crate::keypackage::{E2eeClient, LeafDraft, LeafSecret, PreparedKp};
39use crate::keys::FrameIkm;
40use crate::provider::CallProvider;
41use crate::roster::{MediaLabel, RosterEntry};
42use crate::trust::TrustAnchors;
43use crate::wire::{ApiFailure, KeyReply, KeyRequest};
44
45pub use buffer::{UnknownCallBuffer, call_id_of};
46pub use io::{
47    E2eeStatus, EngineMisbehaviour, Input, LeftReason, Output, SessionState, Transition,
48    UndecryptReason,
49};
50#[cfg(feature = "testing")]
51pub use mls::CraftCommit;
52
53use recorder::RecorderState;
54use recover::SignPurpose;
55use roster::RosterWatch;
56
57/// Counts and ids only, for the app's metrics.
58#[derive(Debug, Clone, Default, PartialEq, Eq)]
59#[non_exhaustive]
60pub struct Counters {
61    /// Epochs activated.
62    pub epochs_activated: u64,
63    /// `Install` events emitted.
64    pub installs: u64,
65    /// `Retire` events emitted.
66    pub retires: u64,
67    /// Local activations by the fallback timer.
68    pub activate_fallback: u64,
69    /// Activations whose fence had not returned yet.
70    pub activate_before_fence: u64,
71    /// Re-adds by reason.
72    pub recoveries: BTreeMap<&'static str, u64>,
73    /// Group resets seen.
74    pub resets: u64,
75    /// Messages for another group or an old epoch, ignored.
76    pub ignored_stale: u64,
77    /// Installs into a slot whose previous key was active less than `retire_after` ago.
78    pub slot_reused_early: u64,
79    /// Unencrypted publications refused by the bridge.
80    pub unencrypted_track_refused: u64,
81    /// Sender self-checks that ended stuck.
82    pub sender_index_stuck: u64,
83    /// Recorder releases sent.
84    pub releases_sent: u64,
85    /// `SdkMissingKey` inputs.
86    pub sdk_missing_key: u64,
87    /// `commit` `409`/`422` answers (superseded, stale, not committer, no transition, invalid).
88    pub commit_refused: u64,
89    /// `report`s sent.
90    pub reports_sent: u64,
91    /// `report`s suppressed by the client limits.
92    pub reports_limited: u64,
93    /// Last commit processing time (ms of the caller's clock; 0 in tests with a fixed clock).
94    pub last_commit_ms: u64,
95}
96
97impl Counters {
98    /// Every count 0 and no recoveries (the same as `Counters::default()`).
99    pub fn new() -> Counters {
100        Counters::default()
101    }
102}
103
104/// The epoch whose keys senders use now.
105#[derive(Debug)]
106struct ActiveEpoch {
107    group_id: Vec<u8>,
108    epoch: Epoch,
109    slot: Slot,
110    leaf: u32,
111    ikm: FrameIkm,
112    code: Option<SecurityCode>,
113    since: Millis,
114}
115
116/// The installed, not yet active epoch.
117#[derive(Debug)]
118struct PendingEpoch {
119    group_id: Vec<u8>,
120    epoch: Epoch,
121    slot: Slot,
122    leaf: u32,
123    ikm: FrameIkm,
124    code: Option<SecurityCode>,
125    fence: FenceId,
126    /// Identities that left in this transition (retired and forgotten after the grace).
127    departed: BTreeSet<LkIdentity>,
128}
129
130/// A retirement due at `at`.
131#[derive(Debug, Clone)]
132struct RetireJob {
133    at: Millis,
134    identity: LkIdentity,
135    slot: Slot,
136    forget: bool,
137}
138
139/// What a request in flight was for.
140#[derive(Debug, Clone)]
141enum Purpose {
142    /// `state` after create (with tree).
143    StateCreate,
144    /// `state` after a re-identify (`with_tree` once `send_tree` asked).
145    StateRebind,
146    /// `state` for the missing-key check.
147    StateMissingKey,
148    /// `state` before a `peer_undecryptable` report about this identity.
149    StatePeer(LkIdentity),
150    /// `state` after a `resync{stale_slot}` whose slot disagreed.
151    StateSlot,
152    /// `commit`.
153    Commit,
154    /// `ready`.
155    Ready,
156    /// `invalid`.
157    Invalid,
158    /// `key_package` (a reset).
159    ResetPackage,
160    /// `release` for `(recording, group, epoch)`.
161    Release(u64, Vec<u8>, Epoch),
162    /// `rekey`.
163    Rekey,
164    /// `report`.
165    Report,
166}
167
168/// The sender self-check in progress.
169#[derive(Debug, Clone, Copy)]
170struct SenderCheck {
171    expected: Slot,
172    attempts: u32,
173}
174
175/// A group reset in progress.
176#[derive(Debug, Clone)]
177struct ResetState {
178    new_group_id: Vec<u8>,
179    slot_base: u8,
180}
181
182/// Recovery in progress (re-add or reset), for the watchdog.
183#[derive(Debug, Clone)]
184struct Recovery {
185    reason: &'static str,
186    since: Millis,
187    tries: u32,
188}
189
190/// One device's key state for one call.
191pub struct CallSession {
192    cfg: E2eeConfig,
193    params: Params,
194    trust: TrustAnchors,
195    device: DeviceIdentity,
196    call_id: RoomName,
197    join_id: JoinId,
198    me: LkIdentity,
199    scope: sew_proto::e2ee::CallScope,
200    gateway_session: String,
201    provider: CallProvider,
202    group: Option<MlsGroup>,
203    signer: Option<SignatureKeyPair>,
204    leaves: BTreeMap<[u8; 32], LeafSecret>,
205    own_commit: Option<Vec<u8>>,
206    init_group: Vec<u8>,
207    known_group: Option<(Vec<u8>, Epoch)>,
208    slot_base: u8,
209    bindings: BTreeMap<u32, VerifiedEntry>,
210    add_bindings: BTreeMap<Vec<u8>, VerifiedEntry>,
211    leaf_ids: BTreeMap<u32, LeafIdentity>,
212    last_proposals: Option<(Epoch, Vec<u8>)>,
213    active: Option<ActiveEpoch>,
214    pending: Option<PendingEpoch>,
215    ring: KeyRing,
216    retires: Vec<RetireJob>,
217    slot_retired_at: BTreeMap<Slot, Millis>,
218    latest_leaf: Option<[u8; 32]>,
219    leaf_keys: BTreeMap<u32, Vec<u8>>,
220    rebind_on_next_invalid: bool,
221    state: SessionState,
222    status: Option<E2eeStatus>,
223    reset: Option<ResetState>,
224    recovery: Option<Recovery>,
225    sign_waits: BTreeMap<SignId, (LeafDraft, SignPurpose)>,
226    next_req: u64,
227    next_fence: u64,
228    next_sign: u64,
229    inflight: BTreeMap<RequestId, Purpose>,
230    retry_state_at: Option<Millis>,
231    missing_check_at: Option<Millis>,
232    missing: BTreeMap<LkIdentity, Millis>,
233    missing_checked_epoch: Option<Epoch>,
234    undecryptable: BTreeMap<LkIdentity, (Millis, u32, UndecryptReason, Option<Slot>)>,
235    peer_reported: BTreeSet<(LkIdentity, Epoch)>,
236    sender_check: Option<SenderCheck>,
237    rec: RecorderState,
238    watch: RosterWatch,
239    roster: Vec<RosterEntry>,
240    outputs: VecDeque<Output>,
241    counters: Counters,
242    verification_code: VerificationCode,
243    #[cfg(feature = "testing")]
244    zeroized_probe: bool,
245}
246
247impl fmt::Debug for CallSession {
248    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
249        f.debug_struct("CallSession")
250            .field("call_id", &self.call_id)
251            .field("join_id", &self.join_id)
252            .field("state", &self.state)
253            .field("active_epoch", &self.active.as_ref().map(|a| a.epoch))
254            .finish_non_exhaustive()
255    }
256}
257
258impl CallSession {
259    // ------------------------------------------------------------------ construction
260
261    pub(crate) fn start(
262        client: &E2eeClient,
263        kp: PreparedKp,
264        init: CallKeysInit,
265        gateway_session: &str,
266        now: Millis,
267    ) -> Result<CallSession, SessionError> {
268        let params = Params::from_wire(&init.params)?;
269        if !identity_matches(&init.join_id, &init.lk_identity) {
270            return Err(SessionError::IdentityMismatch);
271        }
272        if init.external_sender.as_bytes() != client.trust.external_sender() {
273            return Err(SessionError::ExternalSenderMismatch);
274        }
275        if init.scope != kp.scope {
276            return Err(SessionError::Refused("scope"));
277        }
278        let PreparedKp { provider, leaf, .. } = kp;
279        let first_leaf = leaf.kp_ref;
280        let mut leaves = BTreeMap::new();
281        leaves.insert(leaf.kp_ref, leaf);
282        let verification_code = client.trust.verification_code();
283        let mut s = CallSession {
284            cfg: client.cfg.clone(),
285            params,
286            trust: client.trust.clone(),
287            device: client.identity.clone(),
288            call_id: init.call_id.clone(),
289            join_id: init.join_id.clone(),
290            me: init.lk_identity.clone(),
291            scope: init.scope,
292            gateway_session: gateway_session.to_owned(),
293            provider,
294            group: None,
295            signer: None,
296            leaves,
297            own_commit: None,
298            init_group: init.group_id.as_bytes().to_vec(),
299            known_group: Some((init.group_id.as_bytes().to_vec(), init.epoch)),
300            slot_base: init.slot_base,
301            bindings: BTreeMap::new(),
302            add_bindings: BTreeMap::new(),
303            leaf_ids: BTreeMap::new(),
304            last_proposals: None,
305            active: None,
306            pending: None,
307            ring: KeyRing::new(),
308            retires: Vec::new(),
309            slot_retired_at: BTreeMap::new(),
310            latest_leaf: None,
311            leaf_keys: BTreeMap::new(),
312            rebind_on_next_invalid: false,
313            state: SessionState::Joining,
314            status: None,
315            reset: None,
316            recovery: None,
317            sign_waits: BTreeMap::new(),
318            next_req: 1,
319            next_fence: 1,
320            next_sign: 1,
321            inflight: BTreeMap::new(),
322            retry_state_at: None,
323            missing_check_at: None,
324            missing: BTreeMap::new(),
325            missing_checked_epoch: None,
326            undecryptable: BTreeMap::new(),
327            peer_reported: BTreeSet::new(),
328            sender_check: None,
329            rec: RecorderState::default(),
330            watch: RosterWatch::default(),
331            roster: Vec::new(),
332            outputs: VecDeque::new(),
333            counters: Counters::default(),
334            verification_code,
335            #[cfg(feature = "testing")]
336            zeroized_probe: false,
337        };
338        s.latest_leaf = Some(first_leaf);
339        s.set_status(E2eeStatus::Joining { since: now });
340        if init.create {
341            s.create_group(now, &init)?;
342        } else {
343            s.set_status(E2eeStatus::Securing {
344                since: now,
345                show_after_ms: s.params.securing_indicator_after_ms,
346            });
347            // A Welcome that never comes (dropped from the unknown-call buffer, or sent to a
348            // dead socket) heals through a re-add after the watchdog period.
349            s.recovery = Some(Recovery {
350                reason: "joining",
351                since: now,
352                tries: 0,
353            });
354        }
355        Ok(s)
356    }
357
358    // ------------------------------------------------------------------ the API
359
360    /// Applies one input. Never panics. A returned `Err` has already queued any recovery
361    /// output; state changes only on success of the MLS step it guards.
362    pub fn handle(&mut self, now: Millis, input: Input) -> Result<(), SessionError> {
363        if matches!(self.state, SessionState::Left { .. }) {
364            return Err(SessionError::Left);
365        }
366        let r = match input {
367            Input::Server(m) => self.on_server(now, m),
368            Input::Reply(id, r) => self.on_reply(now, id, r),
369            Input::Installed { fence } => self.on_installed(now, fence),
370            Input::DeviceSignature { request, sig } => self.on_signature(now, request, sig),
371            Input::GatewayResumed => Ok(()),
372            Input::GatewayReidentified { gateway_session } => {
373                self.on_reidentified(now, gateway_session)
374            }
375            Input::Ready(r) => self.on_ready(now, &r),
376            Input::Recording {
377                recording_id,
378                my_consent,
379            } => self.on_recording(now, recording_id, my_consent),
380            Input::SdkMissingKey { identity, since } => self.on_missing_key(now, identity, since),
381            Input::SdkUndecryptable {
382                identity,
383                since,
384                failures,
385                reason,
386                missing_index,
387            } => self.on_undecryptable(now, identity, since, failures, reason, missing_index),
388            Input::SdkDecryptOk { identity } => {
389                self.missing.remove(&identity);
390                self.undecryptable.remove(&identity);
391                Ok(())
392            }
393            Input::SenderSlotObserved { observed } => self.on_sender_slot(now, observed),
394            Input::EngineMisbehaviour { kind, identity } => {
395                self.on_engine_misbehaviour(now, kind, identity)
396            }
397            Input::MediaParticipants(ids) => self.on_media_participants(now, ids),
398            Input::VoiceMembers(members) => self.on_voice_members(now, members),
399        };
400        self.after_input(now);
401        r
402    }
403
404    /// Runs every timer due at `now`.
405    pub fn handle_timeout(&mut self, now: Millis) {
406        if matches!(self.state, SessionState::Left { .. }) {
407            return;
408        }
409        self.run_timers(now);
410        self.after_input(now);
411    }
412
413    /// The next time `handle_timeout` must run.
414    pub fn poll_timeout(&self) -> Option<Millis> {
415        if matches!(self.state, SessionState::Left { .. }) {
416            return None;
417        }
418        let mut t: Option<Millis> = None;
419        let mut take = |v: Option<Millis>| {
420            if let Some(v) = v {
421                t = Some(t.map_or(v, |c: Millis| c.min(v)));
422            }
423        };
424        take(self.retires.iter().map(|r| r.at).min());
425        if let SessionState::Active {
426            transition: Transition::Ready { since, .. },
427            ..
428        } = &self.state
429        {
430            take(Some(since + self.params.client_activate_fallback_ms));
431        }
432        if let Some(r) = &self.recovery {
433            take(Some(r.since + self.cfg.recovery_watchdog_ms));
434        }
435        take(self.retry_state_at);
436        take(self.missing_check_at);
437        take(self.watch.next_due(self.cfg.roster_grace_ms));
438        take(self.undecryptable_due());
439        t
440    }
441
442    /// The next output, in order.
443    pub fn poll_output(&mut self) -> Option<Output> {
444        self.outputs.pop_front()
445    }
446
447    /// Teardown: `Key(Clear)`, every secret zeroized, state `Left{Left}`. There is no key
448    /// message; the voice leave has the server remove the leaf.
449    pub fn leave(&mut self, now: Millis) {
450        if matches!(self.state, SessionState::Left { .. }) {
451            return;
452        }
453        self.teardown(now, LeftReason::Left);
454    }
455
456    /// Entries in this call's MLS store (no contents; tests and telemetry: a long call's
457    /// store must not grow with its epochs).
458    pub fn stored_entries(&self) -> usize {
459        self.provider.stored_entries()
460    }
461
462    /// Sizes of what the session holds (telemetry, no contents: a long soak tells a
463    /// growing structure from allocator noise): `(name, entries)` pairs, the MLS store's bytes
464    /// as `store_bytes`.
465    pub fn footprint(&self) -> Vec<(&'static str, usize)> {
466        vec![
467            ("store_entries", self.provider.stored_entries()),
468            ("store_bytes", self.provider.stored_bytes()),
469            ("leaves", self.leaves.len()),
470            ("bindings", self.bindings.len()),
471            ("add_bindings", self.add_bindings.len()),
472            ("leaf_ids", self.leaf_ids.len()),
473            ("leaf_keys", self.leaf_keys.len()),
474            ("retires", self.retires.len()),
475            ("slot_retired_at", self.slot_retired_at.len()),
476            ("sign_waits", self.sign_waits.len()),
477            ("inflight", self.inflight.len()),
478            ("missing", self.missing.len()),
479            ("undecryptable", self.undecryptable.len()),
480            ("peer_reported", self.peer_reported.len()),
481            ("roster", self.roster.len()),
482            ("outputs", self.outputs.len()),
483        ]
484    }
485
486    /// The MLS store's entries by storage label (telemetry).
487    pub fn stored_labels(&self) -> BTreeMap<String, usize> {
488        self.provider.stored_labels()
489    }
490
491    /// The per-call state.
492    pub fn state(&self) -> SessionState {
493        self.state.clone()
494    }
495
496    /// The active epoch.
497    pub fn active_epoch(&self) -> Option<Epoch> {
498        self.active.as_ref().map(|a| a.epoch)
499    }
500
501    /// The local send slot.
502    pub fn local_slot(&self) -> Option<Slot> {
503        self.active.as_ref().map(|a| a.slot)
504    }
505
506    /// The MLS epoch of the group held now.
507    pub fn mls_epoch(&self) -> Option<Epoch> {
508        self.group.as_ref().map(|g| g.epoch().as_u64())
509    }
510
511    /// The slot base of the group held now (`slot(e) = (slot_base + e) mod 64`).
512    pub fn slot_base(&self) -> u8 {
513        self.slot_base
514    }
515
516    /// The group held now.
517    pub fn group_id(&self) -> Option<Vec<u8>> {
518        self.group
519            .as_ref()
520            .map(|g| g.group_id().as_slice().to_vec())
521    }
522
523    /// The own leaf index in the group held now.
524    pub fn own_leaf(&self) -> Option<u32> {
525        self.group.as_ref().map(|g| g.own_leaf_index().u32())
526    }
527
528    /// The roster, from the verified MLS tree only.
529    pub fn roster(&self) -> &[RosterEntry] {
530        &self.roster
531    }
532
533    /// Whether `id` is in the key group now (a media participant with no leaf gets no key).
534    pub fn is_keyed(&self, id: &LkIdentity) -> bool {
535        self.bindings.values().any(|e| &e.lk_identity == id)
536    }
537
538    /// How the app labels a media participant.
539    pub fn media_label(&self, id: &LkIdentity) -> MediaLabel {
540        if let Some((leaf, _)) = self.bindings.iter().find(|(_, e)| &e.lk_identity == id) {
541            return MediaLabel::Member(*leaf);
542        }
543        if self.rec.identity() == Some(id) {
544            return MediaLabel::Recorder;
545        }
546        MediaLabel::NotInEncryptedSession
547    }
548
549    /// The 30-digit code of the active epoch; `None` when the policy hides it.
550    pub fn security_code(&self) -> Option<SecurityCode> {
551        if self.verification_code == VerificationCode::Hidden {
552            return None;
553        }
554        self.active.as_ref().and_then(|a| a.code.clone())
555    }
556
557    /// Ids and counts only.
558    pub fn telemetry(&self) -> &Counters {
559        &self.counters
560    }
561
562    /// The last status emitted.
563    pub fn status(&self) -> Option<&E2eeStatus> {
564        self.status.as_ref()
565    }
566
567    /// The local engine identity.
568    pub fn lk_identity(&self) -> &LkIdentity {
569        &self.me
570    }
571
572    /// The Sew-minted join id.
573    pub fn join_id(&self) -> &JoinId {
574        &self.join_id
575    }
576
577    /// The call.
578    pub fn call_id(&self) -> &RoomName {
579        &self.call_id
580    }
581
582    /// The shadow of the keys this session emitted (what the bridge should hold).
583    pub fn key_ring(&self) -> &KeyRing {
584        &self.ring
585    }
586
587    /// The bound engine identity of a leaf.
588    pub fn identity_of_leaf(&self, leaf: u32) -> Option<&LkIdentity> {
589        self.bindings.get(&leaf).map(|e| &e.lk_identity)
590    }
591
592    /// Test hook: whether teardown zeroized the MLS state (a teardown test).
593    #[cfg(feature = "testing")]
594    pub fn zeroized_for_test(&self) -> bool {
595        self.zeroized_probe
596    }
597
598    /// Test hook: the epoch authenticator of the held group's epoch (secret-adjacent; tests
599    /// search logs for it).
600    #[cfg(feature = "testing")]
601    pub fn epoch_authenticator_for_test(&self) -> Option<Vec<u8>> {
602        self.group
603            .as_ref()
604            .map(|g| g.epoch_authenticator().as_slice().to_vec())
605    }
606
607    /// Test hook: the identities with a live key in the ring.
608    #[cfg(feature = "testing")]
609    pub fn ring_identities_for_test(&self) -> Vec<LkIdentity> {
610        self.ring.identities().cloned().collect()
611    }
612
613    // ------------------------------------------------------------------ plumbing
614
615    fn after_input(&mut self, now: Millis) {
616        self.watch_roster(now);
617    }
618
619    fn set_status(&mut self, s: E2eeStatus) {
620        if self.status.as_ref() != Some(&s) {
621            self.status = Some(s.clone());
622            self.outputs.push_back(Output::Status(s));
623        }
624    }
625
626    fn emit_key(&mut self, ev: KeyEvent) {
627        match &ev {
628            KeyEvent::Install { .. } => self.counters.installs += 1,
629            KeyEvent::Retire { .. } => self.counters.retires += 1,
630            _ => {}
631        }
632        self.ring.apply(&ev);
633        self.outputs.push_back(Output::Key(ev));
634    }
635
636    fn next_fence(&mut self) -> FenceId {
637        let f = FenceId(self.next_fence);
638        self.next_fence += 1;
639        f
640    }
641
642    fn send(&mut self, purpose: Purpose, req: KeyRequest) -> RequestId {
643        let id = RequestId(self.next_req);
644        self.next_req += 1;
645        self.inflight.insert(id, purpose);
646        self.outputs.push_back(Output::Send(id, req));
647        id
648    }
649
650    fn sign(&mut self, draft: LeafDraft, purpose: SignPurpose) {
651        let id = SignId(self.next_sign);
652        self.next_sign += 1;
653        let message = draft.message().to_vec();
654        self.sign_waits.insert(id, (draft, purpose));
655        self.outputs.push_back(Output::NeedDeviceSignature {
656            request: id,
657            message,
658        });
659    }
660
661    fn teardown(&mut self, now: Millis, reason: LeftReason) {
662        self.emit_key(KeyEvent::Clear);
663        self.group = None;
664        self.signer = None;
665        self.leaves.clear();
666        self.sign_waits.clear();
667        self.active = None;
668        self.pending = None;
669        self.retires.clear();
670        self.own_commit = None;
671        self.provider.wipe();
672        #[cfg(feature = "testing")]
673        {
674            self.zeroized_probe = self.provider.stored_entries() == 0;
675        }
676        self.state = SessionState::Left { reason };
677        self.set_status(E2eeStatus::Left { reason });
678        let _ = now;
679    }
680
681    // ------------------------------------------------------------------ dispatch
682
683    fn on_server(&mut self, now: Millis, m: CallKeysMessage) -> Result<(), SessionError> {
684        match m {
685            CallKeysMessage::Init(init) => {
686                if init.call_id != self.call_id || init.join_id != self.join_id {
687                    self.counters.ignored_stale += 1;
688                    return Ok(());
689                }
690                self.on_init_dispatch(now, &init)
691            }
692            CallKeysMessage::Proposals {
693                call_id,
694                group_id,
695                epoch,
696                proposals,
697                committer,
698                reason: _,
699                bindings,
700            } => {
701                if call_id != self.call_id {
702                    self.counters.ignored_stale += 1;
703                    return Ok(());
704                }
705                self.on_proposals(
706                    now,
707                    group_id.as_bytes(),
708                    epoch,
709                    &proposals,
710                    committer,
711                    &bindings,
712                )
713            }
714            CallKeysMessage::CommitRequest {
715                call_id,
716                group_id,
717                epoch,
718                committer,
719                attempt: _,
720            } => {
721                if call_id != self.call_id {
722                    self.counters.ignored_stale += 1;
723                    return Ok(());
724                }
725                self.on_commit_request(now, group_id.as_bytes(), epoch, committer)
726            }
727            CallKeysMessage::Commit {
728                call_id,
729                group_id,
730                epoch_from,
731                commit,
732                slot,
733                bindings,
734            } => {
735                if call_id != self.call_id {
736                    self.counters.ignored_stale += 1;
737                    return Ok(());
738                }
739                self.on_commit(
740                    now,
741                    group_id.as_bytes(),
742                    epoch_from,
743                    commit.as_bytes(),
744                    slot,
745                    &bindings,
746                )
747            }
748            CallKeysMessage::Welcome {
749                call_id,
750                group_id,
751                join_id,
752                epoch,
753                welcome,
754                ratchet_tree,
755                slot_base,
756                slot,
757                bindings,
758            } => {
759                if call_id != self.call_id || join_id != self.join_id {
760                    self.counters.ignored_stale += 1;
761                    return Ok(());
762                }
763                self.on_welcome(
764                    now,
765                    group_id.as_bytes(),
766                    epoch,
767                    welcome.as_bytes(),
768                    ratchet_tree.as_bytes(),
769                    slot_base,
770                    slot,
771                    &bindings,
772                )
773            }
774            CallKeysMessage::Activate {
775                call_id,
776                group_id,
777                epoch,
778                slot,
779            } => {
780                if call_id != self.call_id {
781                    self.counters.ignored_stale += 1;
782                    return Ok(());
783                }
784                self.on_activate(now, group_id.as_bytes(), epoch, slot)
785            }
786            CallKeysMessage::Reset {
787                call_id,
788                new_group_id,
789                reason: _,
790                slot_base,
791                collect_ms: _,
792            } => {
793                if call_id != self.call_id {
794                    self.counters.ignored_stale += 1;
795                    return Ok(());
796                }
797                self.on_reset(now, new_group_id.as_bytes(), slot_base)
798            }
799            CallKeysMessage::Recorder {
800                call_id,
801                recording_id,
802                recorder_cert,
803                hpke_pub,
804                lk_identity,
805                removed,
806            } => {
807                if call_id != self.call_id {
808                    self.counters.ignored_stale += 1;
809                    return Ok(());
810                }
811                self.on_recorder(
812                    now,
813                    recording_id,
814                    recorder_cert.as_ref().map(|b| b.as_bytes()),
815                    hpke_pub.as_ref().map(|b| b.as_bytes()),
816                    lk_identity,
817                    removed,
818                );
819                Ok(())
820            }
821            CallKeysMessage::Revoked { serials } => {
822                let s: Vec<u64> = serials.iter().map(|i| i.get()).collect();
823                self.trust.revoke(&s);
824                Ok(())
825            }
826            CallKeysMessage::Removed {
827                call_id,
828                group_id: _,
829                join_id,
830                reason,
831            } => {
832                if call_id != self.call_id || join_id != self.join_id {
833                    self.counters.ignored_stale += 1;
834                    return Ok(());
835                }
836                self.teardown(now, LeftReason::Removed(reason));
837                Ok(())
838            }
839            CallKeysMessage::Resync {
840                call_id,
841                join_id,
842                reason,
843                expected_slot,
844            } => {
845                if call_id != self.call_id || join_id != self.join_id {
846                    self.counters.ignored_stale += 1;
847                    return Ok(());
848                }
849                match reason {
850                    KeyResyncReason::StaleSlot => self.on_stale_slot(now, expected_slot),
851                    KeyResyncReason::Behind
852                    | KeyResyncReason::GroupMismatch
853                    | KeyResyncReason::Lagging => {
854                        self.start_readd(now, sew_proto::e2ee::InvalidReason::Behind);
855                        Ok(())
856                    }
857                    // Unknown and any value added later.
858                    _ => Ok(()),
859                }
860            }
861            CallKeysMessage::Unknown => Ok(()),
862        }
863    }
864
865    fn on_reply(
866        &mut self,
867        now: Millis,
868        id: RequestId,
869        r: Result<KeyReply, ApiFailure>,
870    ) -> Result<(), SessionError> {
871        let Some(purpose) = self.inflight.remove(&id) else {
872            return Ok(());
873        };
874        match purpose {
875            Purpose::StateCreate
876            | Purpose::StateRebind
877            | Purpose::StateMissingKey
878            | Purpose::StatePeer(_)
879            | Purpose::StateSlot => self.on_state_reply(now, purpose, r),
880            Purpose::Commit => self.on_commit_reply(now, r),
881            Purpose::Ready => {
882                if let Err(f) = r
883                    && f.status == 422
884                    && f.is(sew_proto::e2ee::reasons::E2EE_EPOCH_AHEAD)
885                {
886                    self.start_readd(now, sew_proto::e2ee::InvalidReason::StateLost);
887                }
888                Ok(())
889            }
890            Purpose::ResetPackage => {
891                if let Err(f) = r
892                    && f.status == 409
893                    && f.is(sew_proto::e2ee::reasons::E2EE_NO_RESET)
894                {
895                    self.start_readd(now, sew_proto::e2ee::InvalidReason::Behind);
896                }
897                Ok(())
898            }
899            Purpose::Release(rec, gid, epoch) => {
900                self.on_release_reply(rec, gid, epoch, r);
901                Ok(())
902            }
903            Purpose::Invalid | Purpose::Rekey | Purpose::Report => Ok(()),
904        }
905    }
906
907    fn on_installed(&mut self, now: Millis, fence: FenceId) -> Result<(), SessionError> {
908        let Some(p) = &self.pending else {
909            return Ok(());
910        };
911        if p.fence != fence {
912            return Ok(());
913        }
914        let (gid, epoch) = (p.group_id.clone(), p.epoch);
915        if let SessionState::Active {
916            transition: Transition::Installed { .. },
917            ..
918        } = self.state
919        {
920            self.send(
921                Purpose::Ready,
922                KeyRequest::Ready(
923                    self.call_id.clone(),
924                    sew_proto::e2ee::KeyReadyRequest {
925                        join_id: self.join_id.clone(),
926                        group_id: sew_proto::e2ee::B64::new(gid),
927                        epoch,
928                    },
929                ),
930            );
931            self.state = SessionState::Active {
932                epoch,
933                transition: Transition::Ready { epoch, since: now },
934            };
935        }
936        Ok(())
937    }
938
939    fn on_ready(
940        &mut self,
941        now: Millis,
942        r: &sew_proto::e2ee::ReadyCallKeys,
943    ) -> Result<(), SessionError> {
944        match self.trust.refresh(r) {
945            Ok(()) => {
946                self.verification_code = r.verification_code;
947                Ok(())
948            }
949            Err(crate::error::TrustError::ServerIdentityChanged { what }) => {
950                let kind = if what == "ca" {
951                    sew_proto::e2ee::ReportKind::CaChanged
952                } else {
953                    sew_proto::e2ee::ReportKind::ExternalSenderMismatch
954                };
955                self.report(now, kind, None, None);
956                self.set_status(E2eeStatus::ServerIdentityChanged);
957                Err(SessionError::Refused("server identity changed"))
958            }
959            Err(_) => Err(SessionError::Refused("ready")),
960        }
961    }
962
963    fn run_timers(&mut self, now: Millis) {
964        // Retirements.
965        let mut due: Vec<RetireJob> = Vec::new();
966        self.retires.retain(|r| {
967            if r.at <= now {
968                due.push(r.clone());
969                false
970            } else {
971                true
972            }
973        });
974        due.sort_by_key(|r| r.at);
975        for r in due {
976            self.retire_now(&r);
977        }
978        // Activate fallback.
979        if let SessionState::Active {
980            transition: Transition::Ready { since, epoch },
981            ..
982        } = self.state
983            && now >= since + self.params.client_activate_fallback_ms
984        {
985            if self.pending.as_ref().is_some_and(|p| p.epoch == epoch) {
986                self.counters.activate_fallback += 1;
987                self.activate(now);
988            } else {
989                self.state = SessionState::Active {
990                    epoch,
991                    transition: Transition::Idle,
992                };
993            }
994        }
995        // Recovery watchdog.
996        self.watchdog(now);
997        // `state` retry after `rebuilding`.
998        if let Some(at) = self.retry_state_at
999            && now >= at
1000        {
1001            self.retry_state_at = None;
1002            self.send_state(Purpose::StateRebind, false);
1003        }
1004        // Missing-key check.
1005        if let Some(at) = self.missing_check_at
1006            && now >= at
1007        {
1008            self.missing_check_at = None;
1009            self.check_missing(now);
1010        }
1011        self.check_undecryptable(now);
1012    }
1013
1014    fn retire_now(&mut self, r: &RetireJob) {
1015        // I4: never the slot that is current or pending for that identity.
1016        let current = if r.identity == self.me {
1017            self.active.as_ref().map(|a| a.slot)
1018        } else {
1019            self.ring.current(&r.identity).map(|(s, _)| s)
1020        };
1021        let pending = self.pending.as_ref().map(|p| p.slot);
1022        if current != Some(r.slot) && pending != Some(r.slot) {
1023            let filler = FrameIkm::random_os();
1024            self.emit_key(KeyEvent::Retire {
1025                identity: r.identity.clone(),
1026                slot: r.slot,
1027                filler,
1028            });
1029        }
1030        if r.forget && r.identity != self.me && !self.is_keyed(&r.identity) {
1031            self.emit_key(KeyEvent::Forget {
1032                identity: r.identity.clone(),
1033            });
1034        }
1035    }
1036
1037    fn on_stale_slot(&mut self, now: Millis, expected: Option<u8>) -> Result<(), SessionError> {
1038        let Some(a) = &self.active else {
1039            return Ok(());
1040        };
1041        if expected != Some(a.slot.get()) {
1042            // A state disagreement: ask the DS (`state`), never a re-add here.
1043            self.send_state(Purpose::StateSlot, false);
1044            return Ok(());
1045        }
1046        let slot = a.slot;
1047        self.reapply_local();
1048        self.sender_check = Some(SenderCheck {
1049            expected: slot,
1050            attempts: 1,
1051        });
1052        self.outputs
1053            .push_back(Output::CheckSenderSlot { expected: slot });
1054        let _ = now;
1055        Ok(())
1056    }
1057
1058    fn reapply_local(&mut self) {
1059        if let Some(a) = &self.active {
1060            let ev = KeyEvent::Activate {
1061                identity: self.me.clone(),
1062                slot: a.slot,
1063                ikm: a.ikm.duplicate(),
1064            };
1065            self.emit_key(ev);
1066        }
1067    }
1068
1069    fn on_sender_slot(&mut self, now: Millis, observed: Slot) -> Result<(), SessionError> {
1070        let Some(c) = self.sender_check else {
1071            return Ok(());
1072        };
1073        if observed == c.expected {
1074            self.sender_check = None;
1075            return Ok(());
1076        }
1077        if c.attempts == 0 {
1078            self.reapply_local();
1079            self.sender_check = Some(SenderCheck {
1080                expected: c.expected,
1081                attempts: 1,
1082            });
1083            self.outputs.push_back(Output::CheckSenderSlot {
1084                expected: c.expected,
1085            });
1086            return Ok(());
1087        }
1088        self.sender_check = None;
1089        self.counters.sender_index_stuck += 1;
1090        let leaf = self.own_leaf();
1091        self.report(
1092            now,
1093            sew_proto::e2ee::ReportKind::SenderIndexStuck,
1094            leaf,
1095            Some(sew_proto::e2ee::ReportDetails {
1096                expected_slot: Some(c.expected.get()),
1097                observed_slot: Some(observed.get()),
1098                attempts: Some(2),
1099                ..Default::default()
1100            }),
1101        );
1102        self.set_status(E2eeStatus::Failed {
1103            reason: "sender_index_stuck",
1104        });
1105        Ok(())
1106    }
1107
1108    fn on_engine_misbehaviour(
1109        &mut self,
1110        now: Millis,
1111        kind: EngineMisbehaviour,
1112        _identity: Option<LkIdentity>,
1113    ) -> Result<(), SessionError> {
1114        let k = match kind {
1115            EngineMisbehaviour::UnencryptedTrack => {
1116                self.counters.unencrypted_track_refused += 1;
1117                sew_proto::e2ee::ReportKind::EngineUnencryptedTrack
1118            }
1119            EngineMisbehaviour::SifTrailer => sew_proto::e2ee::ReportKind::EngineSifTrailer,
1120            EngineMisbehaviour::EncryptionDowngrade => {
1121                sew_proto::e2ee::ReportKind::EngineEncryptionDowngrade
1122            }
1123        };
1124        self.report(now, k, None, None);
1125        Ok(())
1126    }
1127}