Skip to main content

sew_e2ee/identity/
binding.rs

1//! The DS-signed `LeafBinding` table.
2//!
3//! The SDKs key everything by the engine identity (`p_…`), so the client must know which leaf is
4//! which identity. [`verify_table`] is the stateless part (what the recorder runs): the DS
5//! signature, every `lk_identity` = `"p_" + base32(join_id)`, one key type, ascending keys, unique
6//! join ids (so unique identities). The checks that need the tree or the session (coverage, a live
7//! leaf's identity never changes, the local entry) live in `CallSession`.
8//!
9//! Keys are derived per **leaf index**, so a swapped table yields decrypt failures, never
10//! one person's media under another's name.
11
12use std::collections::BTreeMap;
13
14use sew_proto::e2ee::tls::BindingKey;
15use sew_proto::e2ee::{LeafBindingTable, wire};
16
17use super::cert::verify_bindings_sig;
18use crate::config::caps;
19use crate::error::{BindingError, DecodeError};
20use crate::ids::{JoinId, LkIdentity, RoomName};
21
22/// One verified entry.
23#[derive(Debug, Clone, PartialEq, Eq)]
24pub struct VerifiedEntry {
25    /// The join id.
26    pub join_id: JoinId,
27    /// Its engine identity (recomputed and compared).
28    pub lk_identity: LkIdentity,
29}
30
31/// A table whose signature and content rules passed.
32#[derive(Debug, Clone, PartialEq, Eq)]
33pub struct VerifiedTable {
34    /// The call.
35    pub call_id: RoomName,
36    /// The group.
37    pub group_id: Vec<u8>,
38    /// The epoch it is for.
39    pub epoch: u64,
40    /// Entries keyed by leaf (key type 1).
41    pub by_leaf: BTreeMap<u32, VerifiedEntry>,
42    /// Entries keyed by `key_package_ref` (key type 2).
43    pub by_ref: BTreeMap<Vec<u8>, VerifiedEntry>,
44}
45
46impl VerifiedTable {
47    /// Whether this is a key-type-1 table (or empty).
48    pub fn is_leaf_table(&self) -> bool {
49        self.by_ref.is_empty()
50    }
51
52    /// Whether this is a key-type-2 table (or empty).
53    pub fn is_ref_table(&self) -> bool {
54        self.by_leaf.is_empty()
55    }
56
57    /// Entries.
58    pub fn len(&self) -> usize {
59        self.by_leaf.len() + self.by_ref.len()
60    }
61
62    /// No entries.
63    pub fn is_empty(&self) -> bool {
64        self.len() == 0
65    }
66}
67
68/// Verifies a signed table statelessly (the DS signature and the identities, plus uniqueness of
69/// leaves, refs, join ids and identities).
70pub fn verify_table(
71    t: &LeafBindingTable,
72    ds_public_key: &[u8; 32],
73) -> Result<VerifiedTable, BindingError> {
74    if t.entries.len() > caps::LEAF_BINDING_ENTRIES {
75        return Err(BindingError::Decode(DecodeError::TooLarge {
76            what: "leaf_binding_table",
77            len: t.entries.len(),
78            cap: caps::LEAF_BINDING_ENTRIES,
79        }));
80    }
81    let tbs = t.tbs().map_err(|e| match e {
82        wire::BindingError::Identity(_) => BindingError::Identity,
83        wire::BindingError::CallId => BindingError::Scope("call_id"),
84        wire::BindingError::EntryKey(_) | wire::BindingError::Table(_) => BindingError::Duplicate,
85    })?;
86    let bytes_len = tbs.to_bytes_len();
87    if bytes_len > caps::LEAF_BINDING_TABLE {
88        return Err(BindingError::Decode(DecodeError::TooLarge {
89            what: "leaf_binding_table",
90            len: bytes_len,
91            cap: caps::LEAF_BINDING_TABLE,
92        }));
93    }
94    if !verify_bindings_sig(ds_public_key, &tbs, t.sig.as_bytes()) {
95        return Err(BindingError::Signature);
96    }
97    let mut by_leaf = BTreeMap::new();
98    let mut by_ref = BTreeMap::new();
99    for (e, json) in tbs.entries.iter().zip(&t.entries) {
100        if json.lk_identity != json.join_id.lk_identity() {
101            return Err(BindingError::Identity);
102        }
103        let v = VerifiedEntry {
104            join_id: json.join_id.clone(),
105            lk_identity: json.lk_identity.clone(),
106        };
107        let dup = match &e.key {
108            BindingKey::Leaf(l) => by_leaf.insert(*l, v).is_some(),
109            BindingKey::KeyPackageRef(r) => by_ref.insert(r.clone(), v).is_some(),
110        };
111        if dup {
112            return Err(BindingError::Duplicate);
113        }
114    }
115    Ok(VerifiedTable {
116        call_id: t.call_id.clone(),
117        group_id: t.group_id.as_bytes().to_vec(),
118        epoch: t.epoch,
119        by_leaf,
120        by_ref,
121    })
122}
123
124trait TbsLen {
125    fn to_bytes_len(&self) -> usize;
126}
127
128impl TbsLen for sew_proto::e2ee::tls::LeafBindingTableTbs {
129    fn to_bytes_len(&self) -> usize {
130        use sew_proto::e2ee::tls::TlsCodec as _;
131        self.to_bytes().map(|b| b.len()).unwrap_or(usize::MAX)
132    }
133}