Skip to main content

s2_kit/connect/server/
store.rs

1//! Where an endpoint keeps what it knows.
2
3use alloc::collections::BTreeMap;
4use alloc::string::String;
5use alloc::sync::Arc;
6use alloc::vec::Vec;
7
8use crate::connect::proto::{
9    AccessToken, ConnectionDetails, NodeDescription, NodeId, NodeIdAlias, PairingToken, TokenStore,
10};
11use crate::types::{Duration, Timestamp};
12
13/// Which pairing: one of this endpoint's nodes, and the remote node it is paired with.
14///
15/// Both halves, because neither is unique on its own. `S2C §Pairing process`: "A CEM can
16/// be paired with multiple RMs at the same time" — so a CEM endpoint holds several
17/// pairings with the same `local`, and a WAN endpoint hosting a household's battery and
18/// heat pump holds two pairings with the same `remote` CEM. A store keyed by either half
19/// alone silently overwrites one of them.
20#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
21pub struct PairingKey {
22    /// One of this endpoint's nodes.
23    pub local: NodeId,
24    /// The node it is paired with.
25    pub remote: NodeId,
26}
27
28/// One node this endpoint is paired with.
29#[derive(Debug, Clone)]
30pub struct PairedNode {
31    /// Which of our nodes.
32    pub local: NodeId,
33    /// Who they are.
34    pub remote: NodeDescription,
35    /// The access tokens that open the door, newest first.
36    pub tokens: TokenStore,
37    /// The connection details exchanged during pairing: the ones we handed out (7A), or
38    /// the ones the client posted when it is the communication server (7B) — in which
39    /// case [`ConnectionDetails::ca_fingerprint`] is what to pin when connecting to it.
40    pub details: Option<ConnectionDetails>,
41    /// Unpaired by this endpoint, and kept only so the next `initiateSession` can be told
42    /// so: `S2C §Unpairing by the communication server` — "The next
43    /// `/[version]/initiateSession` HTTPS API request **must** fail with the
44    /// `No longer paired` response" (the operation is `initiateSession`, erratum E27).
45    pub revoked: bool,
46}
47
48impl PairedNode {
49    /// The key this pairing is stored under.
50    #[must_use]
51    pub fn key(&self) -> PairingKey {
52        PairingKey {
53            local: self.local,
54            remote: self.remote.id,
55        }
56    }
57
58    /// The certificate to pin when *this* endpoint connects to the peer — a 6B pairing,
59    /// where the peer is the communication server.
60    #[must_use]
61    pub fn pin(&self) -> Option<crate::connect::tls::Fingerprint> {
62        self.details
63            .as_ref()
64            .and_then(ConnectionDetails::ca_fingerprint)
65            .map(crate::connect::tls::Fingerprint::from_bytes)
66    }
67}
68
69/// Everything an endpoint must remember across a restart.
70///
71/// Pairings that live only in memory are pairings a power cut destroys, and the recovery
72/// from that is a person walking to the device with a pairing code. Implement this over
73/// whatever the host actually persists to.
74pub trait Store: Send + Sync + 'static {
75    /// The pairing token currently accepting a pairing for one of our nodes, if any.
76    ///
77    /// `None` means `NoValidPairingTokenOnPairingServer`: the node exists but is not
78    /// accepting pairings — the normal state of a device nobody has just pressed the
79    /// button on, and the state a dynamic token returns to when it expires
80    /// (`S2C §pairing token`: "Dynamically generated pairing tokens **must** expire").
81    fn pairing_token(&self, node: NodeId, now: Timestamp) -> Option<PairingToken>;
82
83    /// Which of our nodes an alias names.
84    fn resolve_alias(&self, alias: &NodeIdAlias) -> Option<NodeId>;
85
86    /// Our node, when the endpoint hosts exactly one and the client named none.
87    fn sole_node(&self) -> Option<NodeId>;
88
89    /// Everything about one of our nodes.
90    fn node(&self, node: NodeId) -> Option<NodeDescription>;
91
92    /// Every node this endpoint hosts, for `GET /v1/nodes`.
93    fn nodes(&self) -> Vec<(NodeDescription, Option<NodeIdAlias>)>;
94
95    /// Record a completed pairing, replacing any earlier one under the same key, and
96    /// consume the pairing token that opened it.
97    fn pair(&self, paired: PairedNode);
98
99    /// One pairing.
100    fn paired(&self, key: PairingKey) -> Option<PairedNode>;
101
102    /// Every pairing one of our own nodes has, revoked ones excluded.
103    ///
104    /// `S2C §Pairing process`: "A RM can only be paired with one CEM at a time." Applying
105    /// that needs this question answered.
106    fn pairings_of(&self, local: NodeId) -> Vec<PairingKey>;
107
108    /// Replace a pairing's tokens after a rotation.
109    fn set_tokens(&self, key: PairingKey, tokens: TokenStore);
110
111    /// Mark a pairing unpaired by this endpoint, keeping it until the peer has been told.
112    fn revoke(&self, key: PairingKey);
113
114    /// Forget a pairing.
115    fn unpair(&self, key: PairingKey);
116
117    /// Which pairing a presented access token belongs to, revoked pairings excluded.
118    fn pairing_for_token(&self, token: &AccessToken) -> Option<PairingKey>;
119}
120
121/// How long a dynamic pairing token stays valid when nothing else is said.
122///
123/// `S2C §pairing token`: "five minutes is the recommended duration".
124pub const DYNAMIC_TOKEN_LIFETIME: Duration = Duration::from_secs(5 * 60);
125
126/// A [`Store`] that keeps everything in memory.
127///
128/// Correct, and suitable for a test or a device that re-pairs on every boot. Anything
129/// that must survive a power cut needs a real one.
130#[derive(Debug, Default)]
131pub struct Memory {
132    inner: std::sync::RwLock<Inner>,
133}
134
135#[derive(Debug, Default)]
136struct Inner {
137    /// Our own nodes, by identifier.
138    nodes: BTreeMap<NodeId, NodeDescription>,
139    /// Aliases onto them.
140    aliases: BTreeMap<String, NodeId>,
141    /// Pairing tokens currently accepting a pairing, and when each stops (`None`: a
142    /// static token, valid until closed).
143    tokens: BTreeMap<NodeId, (PairingToken, Option<Timestamp>)>,
144    /// Completed pairings.
145    pairings: BTreeMap<PairingKey, PairedNode>,
146}
147
148impl Memory {
149    /// An empty store.
150    #[must_use]
151    pub fn new() -> Arc<Self> {
152        Arc::new(Self::default())
153    }
154
155    /// Add one of our own nodes.
156    pub fn add_node(&self, node: NodeDescription, alias: Option<NodeIdAlias>) {
157        let Ok(mut inner) = self.inner.write() else {
158            return;
159        };
160        if let Some(alias) = alias {
161            inner.aliases.insert(alias.0, node.id);
162        }
163        inner.nodes.insert(node.id, node);
164    }
165
166    /// Open one of our nodes for pairing with a **static** token — the one printed on the
167    /// device, valid until [`close_pairing`](Self::close_pairing) or a completed pairing.
168    pub fn open_for_pairing(&self, node: NodeId, token: PairingToken) {
169        if let Ok(mut inner) = self.inner.write() {
170            inner.tokens.insert(node, (token, None));
171        }
172    }
173
174    /// Open one of our nodes for pairing with a **dynamic** token, valid for
175    /// [`DYNAMIC_TOKEN_LIFETIME`] from `now` — what pressing the button on a device with
176    /// a display does.
177    pub fn open_for_pairing_until(&self, node: NodeId, token: PairingToken, expires: Timestamp) {
178        if let Ok(mut inner) = self.inner.write() {
179            inner.tokens.insert(node, (token, Some(expires)));
180        }
181    }
182
183    /// [`open_for_pairing_until`](Self::open_for_pairing_until) `now` plus the
184    /// recommended five minutes.
185    pub fn open_for_pairing_dynamic(&self, node: NodeId, token: PairingToken, now: Timestamp) {
186        let expires = now.checked_add(DYNAMIC_TOKEN_LIFETIME).unwrap_or(now);
187        self.open_for_pairing_until(node, token, expires);
188    }
189
190    /// Stop accepting pairings for a node.
191    pub fn close_pairing(&self, node: NodeId) {
192        if let Ok(mut inner) = self.inner.write() {
193            inner.tokens.remove(&node);
194        }
195    }
196}
197
198impl Store for Memory {
199    fn pairing_token(&self, node: NodeId, now: Timestamp) -> Option<PairingToken> {
200        let inner = self.inner.read().ok()?;
201        let (token, expires) = inner.tokens.get(&node)?;
202        match expires {
203            Some(expires) if *expires <= now => None,
204            _ => Some(token.clone()),
205        }
206    }
207
208    fn resolve_alias(&self, alias: &NodeIdAlias) -> Option<NodeId> {
209        self.inner.read().ok()?.aliases.get(&alias.0).copied()
210    }
211
212    fn sole_node(&self) -> Option<NodeId> {
213        let inner = self.inner.read().ok()?;
214        // "If it doesn't know any, but expects the endpoint to represent only one node
215        // … it doesn't provide a value for nodeId and nodeIdAlias." Only answer when
216        // there really is exactly one; guessing would pair the wrong device.
217        if inner.nodes.len() == 1 {
218            inner.nodes.keys().next().copied()
219        } else {
220            None
221        }
222    }
223
224    fn node(&self, node: NodeId) -> Option<NodeDescription> {
225        self.inner.read().ok()?.nodes.get(&node).cloned()
226    }
227
228    fn nodes(&self) -> Vec<(NodeDescription, Option<NodeIdAlias>)> {
229        let Ok(inner) = self.inner.read() else {
230            return Vec::new();
231        };
232        inner
233            .nodes
234            .values()
235            .map(|node| {
236                let alias = inner
237                    .aliases
238                    .iter()
239                    .find(|(_, id)| **id == node.id)
240                    .map(|(alias, _)| NodeIdAlias(alias.clone()));
241                (node.clone(), alias)
242            })
243            .collect()
244    }
245
246    fn pair(&self, paired: PairedNode) {
247        if let Ok(mut inner) = self.inner.write() {
248            // A completed pairing consumes the token: `S2C` makes a dynamic one expire and
249            // leaving a static one open would let the next caller pair as well.
250            inner.tokens.remove(&paired.local);
251            inner.pairings.insert(paired.key(), paired);
252        }
253    }
254
255    fn paired(&self, key: PairingKey) -> Option<PairedNode> {
256        self.inner.read().ok()?.pairings.get(&key).cloned()
257    }
258
259    fn pairings_of(&self, local: NodeId) -> Vec<PairingKey> {
260        let Ok(inner) = self.inner.read() else {
261            return Vec::new();
262        };
263        inner
264            .pairings
265            .iter()
266            .filter(|(key, paired)| key.local == local && !paired.revoked)
267            .map(|(key, _)| *key)
268            .collect()
269    }
270
271    fn set_tokens(&self, key: PairingKey, tokens: TokenStore) {
272        if let Ok(mut inner) = self.inner.write()
273            && let Some(paired) = inner.pairings.get_mut(&key)
274        {
275            paired.tokens = tokens;
276        }
277    }
278
279    fn revoke(&self, key: PairingKey) {
280        if let Ok(mut inner) = self.inner.write()
281            && let Some(paired) = inner.pairings.get_mut(&key)
282        {
283            paired.revoked = true;
284        }
285    }
286
287    fn unpair(&self, key: PairingKey) {
288        if let Ok(mut inner) = self.inner.write() {
289            inner.pairings.remove(&key);
290        }
291    }
292
293    fn pairing_for_token(&self, token: &AccessToken) -> Option<PairingKey> {
294        let inner = self.inner.read().ok()?;
295        // Every pairing is examined, so how long this takes does not say which matched.
296        let mut found = None;
297        for (key, paired) in &inner.pairings {
298            if paired.tokens.accepts(token) && !paired.revoked {
299                found = Some(*key);
300            }
301        }
302        found
303    }
304}
305
306#[cfg(test)]
307mod tests {
308    use super::*;
309    use crate::connect::proto::{Role, TokenKind};
310
311    fn id(s: &str) -> NodeId {
312        NodeId::parse(s).expect("a legal id")
313    }
314
315    fn node(s: &str, role: Role) -> NodeDescription {
316        NodeDescription {
317            id: id(s),
318            brand: "Test".into(),
319            logo_url: None,
320            kind: "test".into(),
321            model_name: "test".into(),
322            user_defined_name: None,
323            role,
324        }
325    }
326
327    fn paired(local: &str, remote: &str, token: &str) -> PairedNode {
328        PairedNode {
329            local: id(local),
330            remote: node(remote, Role::Cem),
331            tokens: TokenStore::new(AccessToken::new(token)),
332            details: None,
333            revoked: false,
334        }
335    }
336
337    #[test]
338    fn one_cem_paired_with_two_nodes_of_one_endpoint_keeps_both() {
339        // A WAN endpoint hosting a battery and a heat pump, both paired with one CEM. Keyed
340        // by the remote node alone, the second pairing would overwrite the first, and the
341        // CEM's next session to the battery would be refused as `NoLongerPaired`.
342        let store = Memory::new();
343        store.pair(paired("battery", "cem", "token-battery"));
344        store.pair(paired("heat-pump", "cem", "token-heat-pump"));
345        let battery = PairingKey {
346            local: id("battery"),
347            remote: id("cem"),
348        };
349        let heat_pump = PairingKey {
350            local: id("heat-pump"),
351            remote: id("cem"),
352        };
353        assert!(store.paired(battery).is_some());
354        assert!(store.paired(heat_pump).is_some());
355        assert_eq!(
356            store.pairing_for_token(&AccessToken::new("token-battery")),
357            Some(battery)
358        );
359        store.unpair(battery);
360        assert!(
361            store.paired(heat_pump).is_some(),
362            "unpairing one keeps the other"
363        );
364    }
365
366    #[test]
367    fn a_dynamic_token_expires_and_a_static_one_does_not() {
368        let store = Memory::new();
369        let now = Timestamp::from_unix(1_700_000_000, 0);
370        let token = || PairingToken::parse("A1b2C3d4", TokenKind::Dynamic).expect("a token");
371        store.open_for_pairing_dynamic(id("rm"), token(), now);
372        assert!(store.pairing_token(id("rm"), now).is_some());
373        let later = now.checked_add(DYNAMIC_TOKEN_LIFETIME).expect("in range");
374        assert!(
375            store.pairing_token(id("rm"), later).is_none(),
376            "five minutes and it is gone"
377        );
378
379        store.open_for_pairing(id("rm"), token());
380        assert!(store.pairing_token(id("rm"), later).is_some());
381    }
382
383    #[test]
384    fn a_revoked_pairing_opens_nothing_but_is_still_there_to_be_told_about() {
385        let store = Memory::new();
386        let entry = paired("rm", "cem", "token");
387        let key = entry.key();
388        store.pair(entry);
389        store.revoke(key);
390        assert!(
391            store
392                .pairing_for_token(&AccessToken::new("token"))
393                .is_none()
394        );
395        assert!(store.pairings_of(id("rm")).is_empty());
396        assert!(store.paired(key).is_some_and(|p| p.revoked));
397    }
398}