sew_e2ee/session/io.rs
1//! The session's inputs and outputs.
2
3use std::fmt;
4
5use sew_proto::e2ee::{CallKeysMessage, ReadyCallKeys};
6
7use crate::bridge::KeyEvent;
8use crate::ids::{
9 Consent, Epoch, FenceId, LkIdentity, MemberId, Millis, RecordingId, RequestId, SignId, Slot,
10};
11use crate::wire::{ApiFailure, KeyReply, KeyRequest};
12
13/// Everything a `CallSession` reacts to. The driver or the TS wrapper feeds them.
14#[non_exhaustive]
15pub enum Input {
16 /// A `call_keys_delivered` body.
17 Server(CallKeysMessage),
18 /// The answer to an `Output::Send` (the server's responses, or the failure).
19 Reply(RequestId, Result<KeyReply, ApiFailure>),
20 /// The bridge applied everything up to `fence`.
21 Installed {
22 /// The fence.
23 fence: FenceId,
24 },
25 /// The platform signed a `NeedDeviceSignature` message (raw r‖s, 64 bytes).
26 DeviceSignature {
27 /// The request.
28 request: SignId,
29 /// The signature.
30 sig: [u8; 64],
31 },
32 /// The gateway resumed (a replay follows; nothing to do).
33 GatewayResumed,
34 /// A new gateway session (not a resume): the `state` route.
35 GatewayReidentified {
36 /// READY's `session_id`.
37 gateway_session: String,
38 },
39 /// A fresh READY: pins, CRL, params.
40 Ready(ReadyCallKeys),
41 /// The app's recording state: the live recording and this member's consent.
42 Recording {
43 /// The live recording, if any.
44 recording_id: Option<RecordingId>,
45 /// This member's consent for it.
46 my_consent: Consent,
47 },
48 /// The SDK reports a missing key for `identity` since `since` (bridge telemetry).
49 SdkMissingKey {
50 /// The remote identity.
51 identity: LkIdentity,
52 /// When the SDK first reported it.
53 since: Millis,
54 },
55 /// The SDK reports undecryptable frames from `identity` (the receiver check).
56 SdkUndecryptable {
57 /// The remote identity.
58 identity: LkIdentity,
59 /// Continuously failing since.
60 since: Millis,
61 /// Failures counted.
62 failures: u32,
63 /// `invalid_key` or `missing_key`.
64 reason: UndecryptReason,
65 /// The key index the frames carried, when known.
66 missing_index: Option<Slot>,
67 },
68 /// The SDK decrypts `identity` again (clears an undecryptable report).
69 SdkDecryptOk {
70 /// The remote identity.
71 identity: LkIdentity,
72 },
73 /// The bridge's sender self-check: the slot the local sender is on.
74 SenderSlotObserved {
75 /// What the SDK reports.
76 observed: Slot,
77 },
78 /// The bridge saw the engine misbehave (the `report` engine kinds).
79 EngineMisbehaviour {
80 /// What.
81 kind: EngineMisbehaviour,
82 /// The identity involved (the publisher), if any.
83 identity: Option<LkIdentity>,
84 },
85 /// The SDK's participant identities (for `report` roster reports).
86 MediaParticipants(Vec<LkIdentity>),
87 /// The members Sew shows in this call (voice states), for `report`.
88 VoiceMembers(Vec<MemberId>),
89}
90
91impl fmt::Debug for Input {
92 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
93 match self {
94 Input::Server(m) => write!(f, "Server({})", m.kind()),
95 Input::Reply(id, r) => write!(
96 f,
97 "Reply({id}, {})",
98 match r {
99 Ok(k) => k.kind(),
100 Err(_) => "failure",
101 }
102 ),
103 Input::Installed { fence } => write!(f, "Installed({fence})"),
104 Input::DeviceSignature { request, .. } => write!(f, "DeviceSignature({request})"),
105 Input::GatewayResumed => f.write_str("GatewayResumed"),
106 Input::GatewayReidentified { .. } => f.write_str("GatewayReidentified"),
107 Input::Ready(_) => f.write_str("Ready"),
108 Input::Recording {
109 recording_id,
110 my_consent,
111 } => write!(f, "Recording({recording_id:?}, {my_consent:?})"),
112 Input::SdkMissingKey { identity, since } => {
113 write!(f, "SdkMissingKey({identity}, {since})")
114 }
115 Input::SdkUndecryptable {
116 identity, reason, ..
117 } => write!(f, "SdkUndecryptable({identity}, {reason:?})"),
118 Input::SdkDecryptOk { identity } => write!(f, "SdkDecryptOk({identity})"),
119 Input::SenderSlotObserved { observed } => write!(f, "SenderSlotObserved({observed})"),
120 Input::EngineMisbehaviour { kind, .. } => write!(f, "EngineMisbehaviour({kind:?})"),
121 Input::MediaParticipants(v) => write!(f, "MediaParticipants({})", v.len()),
122 Input::VoiceMembers(v) => write!(f, "VoiceMembers({})", v.len()),
123 }
124 }
125}
126
127/// Why a receiver cannot decrypt a sender.
128#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
129#[non_exhaustive]
130pub enum UndecryptReason {
131 /// The SDK has a key at the frame's index but the tag fails.
132 InvalidKey,
133 /// No key at the frame's index.
134 MissingKey,
135}
136
137impl UndecryptReason {
138 /// The `report` route's `details.reason`.
139 pub fn as_str(self) -> &'static str {
140 match self {
141 UndecryptReason::InvalidKey => "invalid_key",
142 UndecryptReason::MissingKey => "missing_key",
143 }
144 }
145}
146
147/// Engine misbehaviour a bridge detected.
148#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
149#[non_exhaustive]
150pub enum EngineMisbehaviour {
151 /// A publication announced unencrypted (`enable{false}` filtered, or a NONE track refused).
152 UnencryptedTrack,
153 /// A non-empty SIF trailer (dropped).
154 SifTrailer,
155 /// A published track's encryption was downgraded (publish refused).
156 EncryptionDowngrade,
157}
158
159/// What a `CallSession` asks its driver to do.
160#[non_exhaustive]
161pub enum Output {
162 /// POST a key route; feed the answer back as `Input::Reply(id, …)`.
163 Send(RequestId, KeyRequest),
164 /// Apply a key event to the bridge, in order.
165 Key(KeyEvent),
166 /// Have the device key sign `message` (a fresh KeyPackage for a re-add or a reset).
167 NeedDeviceSignature {
168 /// The request.
169 request: SignId,
170 /// The bytes to sign (raw r‖s answer).
171 message: Vec<u8>,
172 },
173 /// Ask the bridge for the local sender's slot (the sender self-check); answer with
174 /// `Input::SenderSlotObserved`.
175 CheckSenderSlot {
176 /// The slot it should be on.
177 expected: Slot,
178 },
179 /// The status changed.
180 Status(E2eeStatus),
181 /// `roster()` changed.
182 Roster,
183}
184
185impl fmt::Debug for Output {
186 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
187 match self {
188 Output::Send(id, r) => write!(f, "Send({id}, {})", r.kind()),
189 Output::Key(ev) => write!(f, "Key({} {:?} {:?})", ev.kind(), ev.identity(), ev.slot()),
190 Output::NeedDeviceSignature { request, .. } => {
191 write!(f, "NeedDeviceSignature({request})")
192 }
193 Output::CheckSenderSlot { expected } => write!(f, "CheckSenderSlot({expected})"),
194 Output::Status(s) => write!(f, "Status({s:?})"),
195 Output::Roster => f.write_str("Roster"),
196 }
197 }
198}
199
200/// The UI status. Every change is an `Output::Status`, carrying its timestamp.
201#[derive(Debug, Clone, PartialEq, Eq)]
202#[non_exhaustive]
203pub enum E2eeStatus {
204 /// Preparing the key package.
205 Preparing,
206 /// Join sent; waiting for `init` / `welcome`.
207 Joining {
208 /// Since.
209 since: Millis,
210 },
211 /// Keys active.
212 Active {
213 /// The active epoch.
214 epoch: Epoch,
215 /// Since.
216 since: Millis,
217 },
218 /// Media may be connected but keys are not active yet; the UI shows "Securing…" only
219 /// `show_after_ms` after `since` (from `params.securing_indicator_after_ms`).
220 Securing {
221 /// Since.
222 since: Millis,
223 /// The UI threshold.
224 show_after_ms: u64,
225 },
226 /// Re-adding or resetting; old keys still in use.
227 Recovering {
228 /// Why.
229 reason: &'static str,
230 /// Since.
231 since: Millis,
232 },
233 /// No usable device certificate.
234 DeviceNotEnrolled,
235 /// A pinned server key changed: no joins until the store is cleared.
236 ServerIdentityChanged,
237 /// This client cannot join encrypted calls.
238 Unsupported {
239 /// Why.
240 reason: String,
241 },
242 /// Failed for good (`recovery_timeout`, `sender_index_stuck`, `create_failed`, …).
243 Failed {
244 /// Why.
245 reason: &'static str,
246 },
247 /// Left.
248 Left {
249 /// Why.
250 reason: LeftReason,
251 },
252}
253
254/// Why a session ended (`SessionState::Left`).
255#[derive(Debug, Clone, Copy, PartialEq, Eq)]
256#[non_exhaustive]
257pub enum LeftReason {
258 /// `leave()`.
259 Left,
260 /// A `removed` dispatch (or a commit that removed this leaf).
261 Removed(sew_proto::e2ee::RemoveReason),
262 /// Failed hard (`create_failed`, `recovery_timeout`, …).
263 Failed(&'static str),
264}
265
266/// The per-call state.
267#[derive(Debug, Clone, PartialEq, Eq)]
268#[non_exhaustive]
269pub enum SessionState {
270 /// Join sent; waiting for `init` / `welcome`.
271 Joining,
272 /// A member.
273 Active {
274 /// The MLS epoch.
275 epoch: Epoch,
276 /// The transition in progress.
277 transition: Transition,
278 },
279 /// Sent `invalid`; waiting for the re-add Welcome. Old SDK keys stay in place.
280 Resyncing {
281 /// Why.
282 reason: &'static str,
283 /// Since.
284 since: Millis,
285 },
286 /// A `reset` is collecting; the old group's keys stay in use until the new group activates.
287 Resetting {
288 /// The new group.
289 new_group_id: Vec<u8>,
290 /// Since.
291 since: Millis,
292 },
293 /// Left, removed or failed hard. Terminal; all secrets are zeroized.
294 Left {
295 /// Why.
296 reason: LeftReason,
297 },
298}
299
300/// A transition in progress.
301#[derive(Debug, Clone, PartialEq, Eq)]
302#[non_exhaustive]
303pub enum Transition {
304 /// Nothing in flight.
305 Idle,
306 /// This leaf posted a commit.
307 Committing {
308 /// The epoch it leaves.
309 epoch_from: Epoch,
310 },
311 /// The new epoch's remote keys went to the bridge; waiting for the fence.
312 Installed {
313 /// The pending epoch.
314 epoch: Epoch,
315 /// The fence.
316 fence: FenceId,
317 },
318 /// `ready` sent; waiting for `activate`.
319 Ready {
320 /// The pending epoch.
321 epoch: Epoch,
322 /// When `ready` was sent.
323 since: Millis,
324 },
325}