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};
11
12/// One node this endpoint is paired with.
13#[derive(Debug, Clone)]
14pub struct PairedNode {
15    /// Which of our nodes.
16    pub local: NodeId,
17    /// Who they are.
18    pub remote: NodeDescription,
19    /// The access tokens that open the door, newest first.
20    pub tokens: TokenStore,
21    /// What we told them about where to connect, if we are the communication server.
22    pub details: Option<ConnectionDetails>,
23}
24
25/// Everything an endpoint must remember across a restart.
26///
27/// Pairings that live only in memory are pairings a power cut destroys, and the recovery
28/// from that is a person walking to the device with a pairing code. Implement this over
29/// whatever the host actually persists to.
30pub trait Store: Send + Sync + 'static {
31    /// The pairing token currently active for one of our nodes, if any.
32    ///
33    /// `None` means `NoValidPairingTokenOnPairingServer`: the node exists but is not
34    /// accepting pairings, which is the normal state of a device nobody has just pressed
35    /// the button on.
36    fn pairing_token(&self, node: NodeId) -> Option<PairingToken>;
37
38    /// Which of our nodes an alias names.
39    fn resolve_alias(&self, alias: &NodeIdAlias) -> Option<NodeId>;
40
41    /// Our node, when the endpoint hosts exactly one and the client named none.
42    fn sole_node(&self) -> Option<NodeId>;
43
44    /// Everything about one of our nodes.
45    fn node(&self, node: NodeId) -> Option<NodeDescription>;
46
47    /// Every node this endpoint hosts, for `GET /v1/nodes`.
48    fn nodes(&self) -> Vec<(NodeDescription, Option<NodeIdAlias>)>;
49
50    /// Record a completed pairing.
51    fn pair(&self, paired: PairedNode);
52
53    /// A pairing, by the remote node's identifier.
54    fn paired(&self, remote: NodeId) -> Option<PairedNode>;
55
56    /// Every remote node one of our own nodes is currently paired with.
57    ///
58    /// `S2C §Pairing process`: "A CEM can be paired with multiple RMs at the same time. A
59    /// RM can only be paired with one CEM at a time." The second half is a rule somebody
60    /// has to apply, and applying it needs this question answered — the pairings are
61    /// keyed by the *remote* node, so there is otherwise no way to ask which of them
62    /// belong to one of ours.
63    fn paired_with(&self, local: NodeId) -> Vec<NodeId>;
64
65    /// Replace a pairing's tokens after a rotation.
66    fn set_tokens(&self, remote: NodeId, tokens: TokenStore);
67
68    /// Forget a pairing.
69    fn unpair(&self, remote: NodeId);
70
71    /// Which of our nodes a presented access token belongs to, if any.
72    fn node_for_token(&self, token: &AccessToken) -> Option<NodeId>;
73}
74
75/// A [`Store`] that keeps everything in memory.
76///
77/// Correct, and suitable for a test or a device that re-pairs on every boot. Anything
78/// that must survive a power cut needs a real one.
79#[derive(Debug, Default)]
80pub struct Memory {
81    inner: std::sync::RwLock<Inner>,
82}
83
84#[derive(Debug, Default)]
85struct Inner {
86    /// Our own nodes, by identifier.
87    nodes: BTreeMap<NodeId, NodeDescription>,
88    /// Aliases onto them.
89    aliases: BTreeMap<String, NodeId>,
90    /// Pairing tokens currently accepting a pairing.
91    tokens: BTreeMap<NodeId, PairingToken>,
92    /// Completed pairings, by the *remote* node's identifier.
93    pairings: BTreeMap<NodeId, PairedNode>,
94}
95
96impl Memory {
97    /// An empty store.
98    #[must_use]
99    pub fn new() -> Arc<Self> {
100        Arc::new(Self::default())
101    }
102
103    /// Add one of our own nodes.
104    pub fn add_node(&self, node: NodeDescription, alias: Option<NodeIdAlias>) {
105        let Ok(mut inner) = self.inner.write() else {
106            return;
107        };
108        if let Some(alias) = alias {
109            inner.aliases.insert(alias.0, node.id);
110        }
111        inner.nodes.insert(node.id, node);
112    }
113
114    /// Open one of our nodes for pairing, with this token.
115    ///
116    /// What `preparePairing` does, and what pressing the button on a device does.
117    pub fn open_for_pairing(&self, node: NodeId, token: PairingToken) {
118        if let Ok(mut inner) = self.inner.write() {
119            inner.tokens.insert(node, token);
120        }
121    }
122
123    /// Stop accepting pairings for a node.
124    pub fn close_pairing(&self, node: NodeId) {
125        if let Ok(mut inner) = self.inner.write() {
126            inner.tokens.remove(&node);
127        }
128    }
129}
130
131impl Store for Memory {
132    fn pairing_token(&self, node: NodeId) -> Option<PairingToken> {
133        self.inner.read().ok()?.tokens.get(&node).cloned()
134    }
135
136    fn resolve_alias(&self, alias: &NodeIdAlias) -> Option<NodeId> {
137        self.inner.read().ok()?.aliases.get(&alias.0).copied()
138    }
139
140    fn sole_node(&self) -> Option<NodeId> {
141        let inner = self.inner.read().ok()?;
142        // "If it doesn't know any, but expects the endpoint to represent only one node
143        // … it doesn't provide a value for nodeId and nodeIdAlias." Only answer when
144        // there really is exactly one; guessing would pair the wrong device.
145        if inner.nodes.len() == 1 {
146            inner.nodes.keys().next().copied()
147        } else {
148            None
149        }
150    }
151
152    fn node(&self, node: NodeId) -> Option<NodeDescription> {
153        self.inner.read().ok()?.nodes.get(&node).cloned()
154    }
155
156    fn nodes(&self) -> Vec<(NodeDescription, Option<NodeIdAlias>)> {
157        let Ok(inner) = self.inner.read() else {
158            return Vec::new();
159        };
160        inner
161            .nodes
162            .values()
163            .map(|node| {
164                let alias = inner
165                    .aliases
166                    .iter()
167                    .find(|(_, id)| **id == node.id)
168                    .map(|(alias, _)| NodeIdAlias(alias.clone()));
169                (node.clone(), alias)
170            })
171            .collect()
172    }
173
174    fn pair(&self, paired: PairedNode) {
175        if let Ok(mut inner) = self.inner.write() {
176            // A completed pairing consumes the token: `S2C` makes a dynamic one expire and
177            // leaving a static one open would let the next caller pair as well.
178            inner.tokens.remove(&paired.local);
179            inner.pairings.insert(paired.remote.id, paired);
180        }
181    }
182
183    fn paired(&self, remote: NodeId) -> Option<PairedNode> {
184        self.inner.read().ok()?.pairings.get(&remote).cloned()
185    }
186
187    fn paired_with(&self, local: NodeId) -> Vec<NodeId> {
188        let Ok(inner) = self.inner.read() else {
189            return Vec::new();
190        };
191        inner
192            .pairings
193            .values()
194            .filter(|paired| paired.local == local)
195            .map(|paired| paired.remote.id)
196            .collect()
197    }
198
199    fn set_tokens(&self, remote: NodeId, tokens: TokenStore) {
200        if let Ok(mut inner) = self.inner.write()
201            && let Some(paired) = inner.pairings.get_mut(&remote)
202        {
203            paired.tokens = tokens;
204        }
205    }
206
207    fn unpair(&self, remote: NodeId) {
208        if let Ok(mut inner) = self.inner.write() {
209            inner.pairings.remove(&remote);
210        }
211    }
212
213    fn node_for_token(&self, token: &AccessToken) -> Option<NodeId> {
214        let inner = self.inner.read().ok()?;
215        inner
216            .pairings
217            .values()
218            .find(|p| p.tokens.accepts(token))
219            .map(|p| p.remote.id)
220    }
221}