Skip to main content

sew_e2ee/bridge/
keyring.rs

1//! `KeyRing`: a shadow of what the SDK holds.
2//!
3//! Per remote identity it keeps at most three live keys: `previous` (within the grace),
4//! `current` (the slot every sender uses now) and `pending` (installed, not active yet), plus the
5//! local identity's send slot and key. It is the pull API for Sew's test client key source
6//! (`current`, `get`) and for the JS provider overrides (`getKeys()` returns live keys only,
7//! `getLatestManuallySetKeyIndex()` returns [`KeyRing::local_slot`]).
8//!
9//! Roles follow the local activation: every sender of one call switches to the same slot at
10//! the same epoch, so when the local identity activates slot `s`, every remote key at `s`
11//! becomes `current` and the old `current` becomes `previous`.
12
13use std::collections::BTreeMap;
14
15use super::KeyEvent;
16use crate::ids::{LkIdentity, Slot};
17use crate::keys::FrameIkm;
18
19/// The role of one installed key.
20#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
21pub enum KeyRole {
22    /// Superseded, kept until its retirement (the grace window).
23    Previous,
24    /// The slot senders use now.
25    Current,
26    /// Installed for the next epoch, not active yet.
27    Pending,
28}
29
30#[derive(Debug, Default)]
31struct Remote {
32    keys: BTreeMap<Slot, (FrameIkm, KeyRole)>,
33}
34
35/// The shadow of an SDK's key state.
36#[derive(Debug, Default)]
37pub struct KeyRing {
38    remotes: BTreeMap<LkIdentity, Remote>,
39    local: Option<(LkIdentity, Slot, FrameIkm)>,
40    local_previous: Option<Slot>,
41    reconnect_window: bool,
42}
43
44impl KeyRing {
45    /// An empty ring.
46    pub fn new() -> KeyRing {
47        KeyRing::default()
48    }
49
50    /// Applies one event (the same events the bridge gets, in order).
51    pub fn apply(&mut self, ev: &KeyEvent) {
52        match ev {
53            KeyEvent::Install {
54                identity,
55                slot,
56                ikm,
57            } => {
58                let current = self.local.as_ref().map(|(_, s, _)| *s);
59                let role = if Some(*slot) == current {
60                    KeyRole::Current
61                } else {
62                    KeyRole::Pending
63                };
64                let r = self.remotes.entry(identity.clone()).or_default();
65                r.keys.insert(*slot, (ikm.duplicate(), role));
66            }
67            KeyEvent::Activate {
68                identity,
69                slot,
70                ikm,
71            } => {
72                let old = self.local.as_ref().map(|(_, s, _)| *s);
73                if old != Some(*slot) {
74                    self.local_previous = old;
75                }
76                self.local = Some((identity.clone(), *slot, ikm.duplicate()));
77                for r in self.remotes.values_mut() {
78                    for (s, (_, role)) in r.keys.iter_mut() {
79                        *role = if *s == *slot {
80                            KeyRole::Current
81                        } else if *role == KeyRole::Current {
82                            KeyRole::Previous
83                        } else {
84                            *role
85                        };
86                    }
87                }
88            }
89            KeyEvent::Retire { identity, slot, .. } => {
90                if self.local.as_ref().is_some_and(|(id, _, _)| id == identity) {
91                    if self.local_previous == Some(*slot) {
92                        self.local_previous = None;
93                    }
94                    return;
95                }
96                if let Some(r) = self.remotes.get_mut(identity) {
97                    r.keys.remove(slot);
98                }
99            }
100            KeyEvent::Forget { identity } => {
101                self.remotes.remove(identity);
102            }
103            KeyEvent::Fence { .. } => {}
104            KeyEvent::Clear => {
105                self.remotes.clear();
106            }
107        }
108    }
109
110    /// The local send slot (`getLatestManuallySetKeyIndex()`).
111    pub fn local_slot(&self) -> Option<Slot> {
112        self.local.as_ref().map(|(_, s, _)| *s)
113    }
114
115    /// The local identity, once activated.
116    pub fn local_identity(&self) -> Option<&LkIdentity> {
117        self.local.as_ref().map(|(id, _, _)| id)
118    }
119
120    /// The local identity's current key.
121    pub fn local_key(&self) -> Option<(Slot, &FrameIkm)> {
122        self.local.as_ref().map(|(_, s, k)| (*s, k))
123    }
124
125    /// The slot and key `id` sends on now (the local identity included).
126    pub fn current(&self, id: &LkIdentity) -> Option<(Slot, &FrameIkm)> {
127        if let Some((lid, s, k)) = &self.local
128            && lid == id
129        {
130            return Some((*s, k));
131        }
132        self.remotes.get(id).and_then(|r| {
133            r.keys
134                .iter()
135                .find(|(_, (_, role))| *role == KeyRole::Current)
136                .map(|(s, (k, _))| (*s, k))
137        })
138    }
139
140    /// The key of `id` at `slot`, if live.
141    pub fn get(&self, id: &LkIdentity, slot: Slot) -> Option<&FrameIkm> {
142        if let Some((lid, s, k)) = &self.local
143            && lid == id
144            && *s == slot
145        {
146            return Some(k);
147        }
148        self.remotes
149            .get(id)
150            .and_then(|r| r.keys.get(&slot))
151            .map(|(k, _)| k)
152    }
153
154    /// The role of `id`'s key at `slot`.
155    pub fn role(&self, id: &LkIdentity, slot: Slot) -> Option<KeyRole> {
156        self.remotes
157            .get(id)
158            .and_then(|r| r.keys.get(&slot))
159            .map(|(_, role)| *role)
160    }
161
162    /// Every live key: remote keys of every role, then the local current key.
163    pub fn live(&self) -> impl Iterator<Item = (&LkIdentity, Slot, &FrameIkm)> {
164        self.remotes
165            .iter()
166            .flat_map(|(id, r)| r.keys.iter().map(move |(s, (k, _))| (id, *s, k)))
167            .chain(self.local.iter().map(|(id, s, k)| (id, *s, k)))
168    }
169
170    /// What `getKeys()` returns: the current and pending keys of every
171    /// live remote identity and the local current key; `previous` keys too only inside a
172    /// reconnect window ([`KeyRing::set_reconnect_window`]).
173    pub fn repost_keys(&self) -> Vec<(&LkIdentity, Slot, &FrameIkm)> {
174        let mut out: Vec<(&LkIdentity, Slot, &FrameIkm)> = self
175            .remotes
176            .iter()
177            .flat_map(|(id, r)| {
178                r.keys
179                    .iter()
180                    .filter(|(_, (_, role))| *role != KeyRole::Previous || self.reconnect_window)
181                    .map(move |(s, (k, _))| (id, *s, k))
182            })
183            .collect();
184        if let Some((id, s, k)) = &self.local {
185            out.push((id, *s, k));
186        }
187        out
188    }
189
190    /// Opens or closes the reconnect window (`Reconnecting` → `SignalConnected`, JS bridge).
191    pub fn set_reconnect_window(&mut self, open: bool) {
192        self.reconnect_window = open;
193    }
194
195    /// Remote identities with at least one key.
196    pub fn identities(&self) -> impl Iterator<Item = &LkIdentity> {
197        self.remotes.keys()
198    }
199
200    /// Whether `id` holds any key (local or remote).
201    pub fn holds(&self, id: &LkIdentity) -> bool {
202        self.remotes.get(id).is_some_and(|r| !r.keys.is_empty())
203            || self.local.as_ref().is_some_and(|(lid, _, _)| lid == id)
204    }
205
206    /// Live remote keys (for the `getKeys()` budget: ≤ 3 per live identity + 1).
207    pub fn remote_key_count(&self) -> usize {
208        self.remotes.values().map(|r| r.keys.len()).sum()
209    }
210}