Skip to main content

sew_proto/e2ee/
mod.rs

1//! Call key delivery: the wire contract between the MLS delivery
2//! service in `sew` and the `sew-e2ee` client library.
3//!
4//! - [`b64`]: the `B64` newtype (base64url, no padding) every MLS blob travels as.
5//! - [`tls`]: the binary structures (credentials, certificates, binding tables, release
6//!   `info`), the labels and the slot formula.
7//! - [`CallScope`]: what a KeyPackage may join (`call:<channel_id>`, mandatory).
8//! - [`wire`]: the JSON types of the key routes, the `call_keys_delivered` dispatch and READY.
9//! - [`device`]: device enrolment, renewal, revocation and the CRL.
10//! - [`names`]: the `r_…` call id, the 32-hex join id and the `p_…` engine identity.
11//! - [`reasons`]: every error reason string.
12
13pub mod b64;
14pub mod device;
15pub mod names;
16pub mod reasons;
17pub mod tls;
18pub mod wire;
19
20use std::borrow::Cow;
21use std::fmt;
22
23use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
24use serde::de::{self, Deserializer};
25use serde::{Deserialize, Serialize, Serializer};
26
27use crate::id::Id;
28
29pub use b64::{B64, B64Error};
30pub use device::*;
31pub use names::{CallId, JoinIdHex, LkIdentity, NameError};
32pub use wire::*;
33
34/// Whether a member who **declines** recording consent may still join a recorded call,
35/// unrecorded (`true`), or is refused at join with `409 conflict` reason
36/// `recording_consent_required` while a recording is live (`false`).
37///
38/// **Provisional**: the "Decline" behaviour may change; the default lets a decliner
39/// join unrecorded, since the crypto supports it. With `true`, the server still refuses every
40/// recorder release from that member. The voice join gate reads this one constant.
41pub const RECORDING_DECLINE_JOINS_UNRECORDED: bool = true;
42
43/// `details.reason` of the `409` a declined member gets at join while a recording is live, when
44/// [`RECORDING_DECLINE_JOINS_UNRECORDED`] is `false`.
45pub const RECORDING_CONSENT_REQUIRED: &str = "recording_consent_required";
46
47/// What a KeyPackage may join: always `call:<channel_id>` (the voice channel, or the DM channel
48/// of a DM call), with the channel id in decimal. One
49/// constructor; [`CallScope::parse`] refuses every other form, including the empty scope and
50/// the old `voice:<id>` form.
51#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
52pub struct CallScope {
53    channel_id: Id,
54}
55
56/// The longest scope accepted (ASCII bytes).
57pub const SCOPE_MAX_BYTES: usize = 64;
58
59impl CallScope {
60    /// The scope of a call in `channel_id`.
61    pub fn call(channel_id: Id) -> CallScope {
62        CallScope { channel_id }
63    }
64
65    /// The channel.
66    pub fn channel_id(self) -> Id {
67        self.channel_id
68    }
69
70    /// The wire bytes (`call:<decimal id>`).
71    pub fn to_bytes(self) -> Vec<u8> {
72        self.to_string().into_bytes()
73    }
74
75    /// Parses `call:<decimal id>` exactly (no sign, no leading zero, ≤ 64 bytes).
76    pub fn parse(bytes: &[u8]) -> Option<CallScope> {
77        if bytes.is_empty() || bytes.len() > SCOPE_MAX_BYTES {
78            return None;
79        }
80        let s = std::str::from_utf8(bytes).ok()?;
81        let digits = s.strip_prefix("call:")?;
82        if digits.is_empty()
83            || digits.starts_with('0')
84            || !digits.bytes().all(|b| b.is_ascii_digit())
85        {
86            return None;
87        }
88        let id: Id = digits.parse().ok()?;
89        (id.to_string() == digits).then_some(CallScope { channel_id: id })
90    }
91}
92
93impl fmt::Display for CallScope {
94    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
95        write!(f, "call:{}", self.channel_id)
96    }
97}
98
99impl Serialize for CallScope {
100    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
101        s.collect_str(self)
102    }
103}
104
105impl<'de> Deserialize<'de> for CallScope {
106    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<CallScope, D::Error> {
107        let s = String::deserialize(d)?;
108        CallScope::parse(s.as_bytes())
109            .ok_or_else(|| de::Error::custom("not a call scope (call:<decimal channel id>)"))
110    }
111}
112
113impl JsonSchema for CallScope {
114    fn inline_schema() -> bool {
115        true
116    }
117
118    fn schema_name() -> Cow<'static, str> {
119        "CallScope".into()
120    }
121
122    fn json_schema(_: &mut SchemaGenerator) -> Schema {
123        json_schema!({
124            "type": "string",
125            "pattern": "^call:[1-9][0-9]*$",
126            "description": "What a KeyPackage may join: `call:<channel_id>` (decimal)."
127        })
128    }
129}
130
131#[cfg(test)]
132mod tests {
133    use super::*;
134
135    #[test]
136    fn scope_round_trip_and_refusals() {
137        let id: Id = match "1839000000000000001".parse() {
138            Ok(i) => i,
139            Err(_) => return,
140        };
141        let s = CallScope::call(id);
142        assert_eq!(s.to_string(), "call:1839000000000000001");
143        assert_eq!(CallScope::parse(&s.to_bytes()), Some(s));
144        for bad in [
145            &b""[..],
146            b"call:",
147            b"voice:1839000000000000001",
148            b"call:01",
149            b"call:-1",
150            b"call:1x",
151            b"CALL:1",
152        ] {
153            assert_eq!(CallScope::parse(bad), None, "{bad:?}");
154        }
155    }
156}