1use 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#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
21pub struct PairingKey {
22 pub local: NodeId,
24 pub remote: NodeId,
26}
27
28#[derive(Debug, Clone)]
30pub struct PairedNode {
31 pub local: NodeId,
33 pub remote: NodeDescription,
35 pub tokens: TokenStore,
37 pub details: Option<ConnectionDetails>,
41 pub revoked: bool,
46}
47
48impl PairedNode {
49 #[must_use]
51 pub fn key(&self) -> PairingKey {
52 PairingKey {
53 local: self.local,
54 remote: self.remote.id,
55 }
56 }
57
58 #[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
69pub trait Store: Send + Sync + 'static {
75 fn pairing_token(&self, node: NodeId, now: Timestamp) -> Option<PairingToken>;
82
83 fn resolve_alias(&self, alias: &NodeIdAlias) -> Option<NodeId>;
85
86 fn sole_node(&self) -> Option<NodeId>;
88
89 fn node(&self, node: NodeId) -> Option<NodeDescription>;
91
92 fn nodes(&self) -> Vec<(NodeDescription, Option<NodeIdAlias>)>;
94
95 fn pair(&self, paired: PairedNode);
98
99 fn paired(&self, key: PairingKey) -> Option<PairedNode>;
101
102 fn pairings_of(&self, local: NodeId) -> Vec<PairingKey>;
107
108 fn set_tokens(&self, key: PairingKey, tokens: TokenStore);
110
111 fn revoke(&self, key: PairingKey);
113
114 fn unpair(&self, key: PairingKey);
116
117 fn pairing_for_token(&self, token: &AccessToken) -> Option<PairingKey>;
119}
120
121pub const DYNAMIC_TOKEN_LIFETIME: Duration = Duration::from_secs(5 * 60);
125
126#[derive(Debug, Default)]
131pub struct Memory {
132 inner: std::sync::RwLock<Inner>,
133}
134
135#[derive(Debug, Default)]
136struct Inner {
137 nodes: BTreeMap<NodeId, NodeDescription>,
139 aliases: BTreeMap<String, NodeId>,
141 tokens: BTreeMap<NodeId, (PairingToken, Option<Timestamp>)>,
144 pairings: BTreeMap<PairingKey, PairedNode>,
146}
147
148impl Memory {
149 #[must_use]
151 pub fn new() -> Arc<Self> {
152 Arc::new(Self::default())
153 }
154
155 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 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 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 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 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 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 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 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 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}