use alloc::collections::BTreeMap;
use alloc::string::String;
use alloc::sync::Arc;
use alloc::vec::Vec;
use crate::connect::proto::{
AccessToken, ConnectionDetails, NodeDescription, NodeId, NodeIdAlias, PairingToken, TokenStore,
};
use crate::types::{Duration, Timestamp};
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct PairingKey {
pub local: NodeId,
pub remote: NodeId,
}
#[derive(Debug, Clone)]
pub struct PairedNode {
pub local: NodeId,
pub remote: NodeDescription,
pub tokens: TokenStore,
pub details: Option<ConnectionDetails>,
pub revoked: bool,
}
impl PairedNode {
#[must_use]
pub fn key(&self) -> PairingKey {
PairingKey {
local: self.local,
remote: self.remote.id,
}
}
#[must_use]
pub fn pin(&self) -> Option<crate::connect::tls::Fingerprint> {
self.details
.as_ref()
.and_then(ConnectionDetails::ca_fingerprint)
.map(crate::connect::tls::Fingerprint::from_bytes)
}
}
pub trait Store: Send + Sync + 'static {
fn pairing_token(&self, node: NodeId, now: Timestamp) -> Option<PairingToken>;
fn resolve_alias(&self, alias: &NodeIdAlias) -> Option<NodeId>;
fn sole_node(&self) -> Option<NodeId>;
fn node(&self, node: NodeId) -> Option<NodeDescription>;
fn nodes(&self) -> Vec<(NodeDescription, Option<NodeIdAlias>)>;
fn pair(&self, paired: PairedNode);
fn paired(&self, key: PairingKey) -> Option<PairedNode>;
fn pairings_of(&self, local: NodeId) -> Vec<PairingKey>;
fn set_tokens(&self, key: PairingKey, tokens: TokenStore);
fn revoke(&self, key: PairingKey);
fn unpair(&self, key: PairingKey);
fn pairing_for_token(&self, token: &AccessToken) -> Option<PairingKey>;
}
pub const DYNAMIC_TOKEN_LIFETIME: Duration = Duration::from_secs(5 * 60);
#[derive(Debug, Default)]
pub struct Memory {
inner: std::sync::RwLock<Inner>,
}
#[derive(Debug, Default)]
struct Inner {
nodes: BTreeMap<NodeId, NodeDescription>,
aliases: BTreeMap<String, NodeId>,
tokens: BTreeMap<NodeId, (PairingToken, Option<Timestamp>)>,
pairings: BTreeMap<PairingKey, PairedNode>,
}
impl Memory {
#[must_use]
pub fn new() -> Arc<Self> {
Arc::new(Self::default())
}
pub fn add_node(&self, node: NodeDescription, alias: Option<NodeIdAlias>) {
let Ok(mut inner) = self.inner.write() else {
return;
};
if let Some(alias) = alias {
inner.aliases.insert(alias.0, node.id);
}
inner.nodes.insert(node.id, node);
}
pub fn open_for_pairing(&self, node: NodeId, token: PairingToken) {
if let Ok(mut inner) = self.inner.write() {
inner.tokens.insert(node, (token, None));
}
}
pub fn open_for_pairing_until(&self, node: NodeId, token: PairingToken, expires: Timestamp) {
if let Ok(mut inner) = self.inner.write() {
inner.tokens.insert(node, (token, Some(expires)));
}
}
pub fn open_for_pairing_dynamic(&self, node: NodeId, token: PairingToken, now: Timestamp) {
let expires = now.checked_add(DYNAMIC_TOKEN_LIFETIME).unwrap_or(now);
self.open_for_pairing_until(node, token, expires);
}
pub fn close_pairing(&self, node: NodeId) {
if let Ok(mut inner) = self.inner.write() {
inner.tokens.remove(&node);
}
}
}
impl Store for Memory {
fn pairing_token(&self, node: NodeId, now: Timestamp) -> Option<PairingToken> {
let inner = self.inner.read().ok()?;
let (token, expires) = inner.tokens.get(&node)?;
match expires {
Some(expires) if *expires <= now => None,
_ => Some(token.clone()),
}
}
fn resolve_alias(&self, alias: &NodeIdAlias) -> Option<NodeId> {
self.inner.read().ok()?.aliases.get(&alias.0).copied()
}
fn sole_node(&self) -> Option<NodeId> {
let inner = self.inner.read().ok()?;
if inner.nodes.len() == 1 {
inner.nodes.keys().next().copied()
} else {
None
}
}
fn node(&self, node: NodeId) -> Option<NodeDescription> {
self.inner.read().ok()?.nodes.get(&node).cloned()
}
fn nodes(&self) -> Vec<(NodeDescription, Option<NodeIdAlias>)> {
let Ok(inner) = self.inner.read() else {
return Vec::new();
};
inner
.nodes
.values()
.map(|node| {
let alias = inner
.aliases
.iter()
.find(|(_, id)| **id == node.id)
.map(|(alias, _)| NodeIdAlias(alias.clone()));
(node.clone(), alias)
})
.collect()
}
fn pair(&self, paired: PairedNode) {
if let Ok(mut inner) = self.inner.write() {
inner.tokens.remove(&paired.local);
inner.pairings.insert(paired.key(), paired);
}
}
fn paired(&self, key: PairingKey) -> Option<PairedNode> {
self.inner.read().ok()?.pairings.get(&key).cloned()
}
fn pairings_of(&self, local: NodeId) -> Vec<PairingKey> {
let Ok(inner) = self.inner.read() else {
return Vec::new();
};
inner
.pairings
.iter()
.filter(|(key, paired)| key.local == local && !paired.revoked)
.map(|(key, _)| *key)
.collect()
}
fn set_tokens(&self, key: PairingKey, tokens: TokenStore) {
if let Ok(mut inner) = self.inner.write()
&& let Some(paired) = inner.pairings.get_mut(&key)
{
paired.tokens = tokens;
}
}
fn revoke(&self, key: PairingKey) {
if let Ok(mut inner) = self.inner.write()
&& let Some(paired) = inner.pairings.get_mut(&key)
{
paired.revoked = true;
}
}
fn unpair(&self, key: PairingKey) {
if let Ok(mut inner) = self.inner.write() {
inner.pairings.remove(&key);
}
}
fn pairing_for_token(&self, token: &AccessToken) -> Option<PairingKey> {
let inner = self.inner.read().ok()?;
let mut found = None;
for (key, paired) in &inner.pairings {
if paired.tokens.accepts(token) && !paired.revoked {
found = Some(*key);
}
}
found
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::connect::proto::{Role, TokenKind};
fn id(s: &str) -> NodeId {
NodeId::parse(s).expect("a legal id")
}
fn node(s: &str, role: Role) -> NodeDescription {
NodeDescription {
id: id(s),
brand: "Test".into(),
logo_url: None,
kind: "test".into(),
model_name: "test".into(),
user_defined_name: None,
role,
}
}
fn paired(local: &str, remote: &str, token: &str) -> PairedNode {
PairedNode {
local: id(local),
remote: node(remote, Role::Cem),
tokens: TokenStore::new(AccessToken::new(token)),
details: None,
revoked: false,
}
}
#[test]
fn one_cem_paired_with_two_nodes_of_one_endpoint_keeps_both() {
let store = Memory::new();
store.pair(paired("battery", "cem", "token-battery"));
store.pair(paired("heat-pump", "cem", "token-heat-pump"));
let battery = PairingKey {
local: id("battery"),
remote: id("cem"),
};
let heat_pump = PairingKey {
local: id("heat-pump"),
remote: id("cem"),
};
assert!(store.paired(battery).is_some());
assert!(store.paired(heat_pump).is_some());
assert_eq!(
store.pairing_for_token(&AccessToken::new("token-battery")),
Some(battery)
);
store.unpair(battery);
assert!(
store.paired(heat_pump).is_some(),
"unpairing one keeps the other"
);
}
#[test]
fn a_dynamic_token_expires_and_a_static_one_does_not() {
let store = Memory::new();
let now = Timestamp::from_unix(1_700_000_000, 0);
let token = || PairingToken::parse("A1b2C3d4", TokenKind::Dynamic).expect("a token");
store.open_for_pairing_dynamic(id("rm"), token(), now);
assert!(store.pairing_token(id("rm"), now).is_some());
let later = now.checked_add(DYNAMIC_TOKEN_LIFETIME).expect("in range");
assert!(
store.pairing_token(id("rm"), later).is_none(),
"five minutes and it is gone"
);
store.open_for_pairing(id("rm"), token());
assert!(store.pairing_token(id("rm"), later).is_some());
}
#[test]
fn a_revoked_pairing_opens_nothing_but_is_still_there_to_be_told_about() {
let store = Memory::new();
let entry = paired("rm", "cem", "token");
let key = entry.key();
store.pair(entry);
store.revoke(key);
assert!(
store
.pairing_for_token(&AccessToken::new("token"))
.is_none()
);
assert!(store.pairings_of(id("rm")).is_empty());
assert!(store.paired(key).is_some_and(|p| p.revoked));
}
}