Skip to main content

sew_e2ee/
wire.rs

1//! The key routes a session drives: this crate's enums over
2//! `sew_proto::e2ee` request and response types, and the failure shape the driver feeds back.
3
4use serde::Serialize;
5use sew_proto::e2ee::reasons;
6use sew_proto::e2ee::{
7    CallId, KeyCommitAccepted, KeyCommitRequest, KeyInvalidRequest, KeyReadyRequest,
8    KeyRekeyRequest, KeyReleaseRequest, KeyReportRequest, KeyResetPackageRequest, KeyStateRequest,
9    KeyStateResponse,
10};
11use sew_proto::routes;
12
13/// A key route request for one call. The driver POSTs `body()` to `path()`; every body carries the
14/// Sew-minted `join_id` and is idempotent per the server's key, so a failed POST is retried
15/// unchanged.
16#[derive(Debug, Clone, PartialEq, Eq)]
17pub enum KeyRequest {
18    /// `state`.
19    State(CallId, KeyStateRequest),
20    /// `commit`.
21    Commit(CallId, KeyCommitRequest),
22    /// `ready`.
23    Ready(CallId, KeyReadyRequest),
24    /// `invalid` (a re-add).
25    Invalid(CallId, KeyInvalidRequest),
26    /// `key_package` (a reset).
27    ResetPackage(CallId, KeyResetPackageRequest),
28    /// `release`.
29    Release(CallId, KeyReleaseRequest),
30    /// `rekey`.
31    Rekey(CallId, KeyRekeyRequest),
32    /// `report`.
33    Report(CallId, KeyReportRequest),
34}
35
36impl KeyRequest {
37    /// `state`, `commit`, `ready`, `invalid`, `key_package`, `release`, `rekey`, `report`.
38    pub fn kind(&self) -> &'static str {
39        match self {
40            KeyRequest::State(..) => "state",
41            KeyRequest::Commit(..) => "commit",
42            KeyRequest::Ready(..) => "ready",
43            KeyRequest::Invalid(..) => "invalid",
44            KeyRequest::ResetPackage(..) => "key_package",
45            KeyRequest::Release(..) => "release",
46            KeyRequest::Rekey(..) => "rekey",
47            KeyRequest::Report(..) => "report",
48        }
49    }
50
51    /// The call.
52    pub fn call_id(&self) -> &CallId {
53        match self {
54            KeyRequest::State(c, _)
55            | KeyRequest::Commit(c, _)
56            | KeyRequest::Ready(c, _)
57            | KeyRequest::Invalid(c, _)
58            | KeyRequest::ResetPackage(c, _)
59            | KeyRequest::Release(c, _)
60            | KeyRequest::Rekey(c, _)
61            | KeyRequest::Report(c, _) => c,
62        }
63    }
64
65    /// The route path (`/api/v1/calls/{call_id}/keys/<kind>`).
66    pub fn path(&self) -> String {
67        let t = match self {
68            KeyRequest::State(..) => routes::CALL_KEYS_STATE,
69            KeyRequest::Commit(..) => routes::CALL_KEYS_COMMIT,
70            KeyRequest::Ready(..) => routes::CALL_KEYS_READY,
71            KeyRequest::Invalid(..) => routes::CALL_KEYS_INVALID,
72            KeyRequest::ResetPackage(..) => routes::CALL_KEYS_KEY_PACKAGE,
73            KeyRequest::Release(..) => routes::CALL_KEYS_RELEASE,
74            KeyRequest::Rekey(..) => routes::CALL_KEYS_REKEY,
75            KeyRequest::Report(..) => routes::CALL_KEYS_REPORT,
76        };
77        routes::with_call_id(t, self.call_id().as_str())
78    }
79
80    /// The JSON body.
81    pub fn body(&self) -> serde_json::Value {
82        fn j<T: Serialize>(t: &T) -> serde_json::Value {
83            serde_json::to_value(t).unwrap_or(serde_json::Value::Null)
84        }
85        match self {
86            KeyRequest::State(_, b) => j(b),
87            KeyRequest::Commit(_, b) => j(b),
88            KeyRequest::Ready(_, b) => j(b),
89            KeyRequest::Invalid(_, b) => j(b),
90            KeyRequest::ResetPackage(_, b) => j(b),
91            KeyRequest::Release(_, b) => j(b),
92            KeyRequest::Rekey(_, b) => j(b),
93            KeyRequest::Report(_, b) => j(b),
94        }
95    }
96}
97
98/// A successful answer (the server's `KeyStateResponse`, `KeyCommitAccepted`, or `202 {}`).
99#[derive(Debug, Clone, PartialEq, Eq)]
100pub enum KeyReply {
101    /// `state`.
102    State(KeyStateResponse),
103    /// `commit` `200`.
104    CommitAccepted(KeyCommitAccepted),
105    /// Any other `2xx`.
106    Accepted,
107}
108
109impl KeyReply {
110    /// For logs.
111    pub fn kind(&self) -> &'static str {
112        match self {
113            KeyReply::State(_) => "state",
114            KeyReply::CommitAccepted(_) => "commit_accepted",
115            KeyReply::Accepted => "accepted",
116        }
117    }
118}
119
120/// A failed key route: the HTTP status and `details.reason`, or a transport failure
121/// (`status = 0`). The driver retries transport failures and `503 voice_unavailable` itself
122/// (with backoff, unchanged content); what reaches the session is final.
123#[derive(Debug, Clone, PartialEq, Eq)]
124#[non_exhaustive]
125pub struct ApiFailure {
126    /// HTTP status (`0` = transport).
127    pub status: u16,
128    /// `details.reason`, when the envelope has one.
129    pub reason: Option<String>,
130    /// `details.check` / `details.unsupported`, when present.
131    pub detail: Option<String>,
132    /// `retry_after_ms` / `Retry-After`, when present.
133    pub retry_after_ms: Option<u64>,
134}
135
136impl ApiFailure {
137    /// A failure with a status and reason.
138    pub fn new(status: u16, reason: &str) -> ApiFailure {
139        ApiFailure {
140            status,
141            reason: Some(reason.to_owned()),
142            detail: None,
143            retry_after_ms: None,
144        }
145    }
146
147    /// A transport failure.
148    pub fn transport() -> ApiFailure {
149        ApiFailure::from_status(0)
150    }
151
152    /// A failure with a status only: no `reason`, `detail` or `retry_after_ms` (set them with
153    /// the `with_*` setters).
154    pub fn from_status(status: u16) -> ApiFailure {
155        ApiFailure {
156            status,
157            reason: None,
158            detail: None,
159            retry_after_ms: None,
160        }
161    }
162
163    /// Sets `reason` (`details.reason`).
164    pub fn with_reason(mut self, reason: Option<String>) -> ApiFailure {
165        self.reason = reason;
166        self
167    }
168
169    /// Sets `detail` (`details.check` / `details.unsupported`).
170    pub fn with_detail(mut self, detail: Option<String>) -> ApiFailure {
171        self.detail = detail;
172        self
173    }
174
175    /// Sets `retry_after_ms`.
176    pub fn with_retry_after_ms(mut self, retry_after_ms: Option<u64>) -> ApiFailure {
177        self.retry_after_ms = retry_after_ms;
178        self
179    }
180
181    /// Whether `details.reason` is `r`.
182    pub fn is(&self, r: &str) -> bool {
183        self.reason.as_deref() == Some(r)
184    }
185
186    /// A failure the driver retries (transport, `503`).
187    pub fn is_retryable(&self) -> bool {
188        self.status == 0 || self.status == 503
189    }
190
191    /// `state`'s three `409`s that mean "re-add with reason `behind`".
192    pub fn is_behind(&self) -> bool {
193        self.status == 409
194            && (self.is(reasons::E2EE_EPOCH_BEHIND)
195                || self.is(reasons::E2EE_GROUP_MISMATCH)
196                || self.is(reasons::E2EE_NOT_IN_GROUP))
197    }
198}