Skip to main content

zwave_security/
provisioning.rs

1//! The SmartStart provisioning list a controller keeps.
2//!
3//! An entry is a node the user has scanned (usually from its QR code) before
4//! powering it. When a SmartStart node asks for inclusion, its NWI home id is
5//! looked up here; a match is included with the entry's granted keys and the
6//! entry's DSK authenticates the key exchange without a PIN prompt.
7
8use crate::dsk::Dsk;
9use crate::qr::QrCode;
10use crate::SecurityClass;
11
12/// Whether an entry should be included when it asks.
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
14#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
15#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
16pub enum EntryStatus {
17    /// Include the node when it asks.
18    #[default]
19    Active,
20    /// Keep the entry but ignore the node's requests.
21    Inactive,
22}
23
24/// One provisioned node.
25#[derive(Debug, Clone, PartialEq, Eq)]
26#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
27pub struct Entry {
28    /// The node's DSK.
29    pub dsk: Dsk,
30    /// The keys to grant.
31    pub granted: Vec<SecurityClass>,
32    /// Active or inactive.
33    #[cfg_attr(feature = "serde", serde(default))]
34    pub status: EntryStatus,
35    /// The node id once included.
36    #[cfg_attr(feature = "serde", serde(default))]
37    pub node_id: Option<u16>,
38    /// A label for people.
39    #[cfg_attr(feature = "serde", serde(default))]
40    pub name: Option<String>,
41}
42
43impl Entry {
44    /// An active entry from a scanned QR code, granting what the node requests.
45    pub fn from_qr(qr: &QrCode) -> Self {
46        Entry {
47            dsk: qr.dsk,
48            granted: qr.requested_classes.clone(),
49            status: EntryStatus::Active,
50            node_id: None,
51            name: None,
52        }
53    }
54}
55
56/// The provisioning list. Small by nature (a building's worth of devices),
57/// so a vector with linear lookups.
58#[derive(Debug, Clone, Default, PartialEq, Eq)]
59#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
60pub struct ProvisioningList {
61    entries: Vec<Entry>,
62}
63
64/// Upper bound on entries, to keep a misbehaving client from growing the list without end.
65pub const MAX_ENTRIES: usize = 1000;
66
67impl ProvisioningList {
68    /// All entries.
69    pub fn entries(&self) -> &[Entry] {
70        &self.entries
71    }
72
73    /// Adds or replaces the entry with the same DSK. Returns false when the list is full.
74    pub fn upsert(&mut self, entry: Entry) -> bool {
75        if let Some(e) = self.entries.iter_mut().find(|e| e.dsk == entry.dsk) {
76            *e = entry;
77            return true;
78        }
79        if self.entries.len() >= MAX_ENTRIES {
80            return false;
81        }
82        self.entries.push(entry);
83        true
84    }
85
86    /// Removes the entry with this DSK.
87    pub fn remove(&mut self, dsk: &Dsk) -> Option<Entry> {
88        let i = self.entries.iter().position(|e| &e.dsk == dsk)?;
89        Some(self.entries.remove(i))
90    }
91
92    /// The entry for a DSK.
93    pub fn get(&self, dsk: &Dsk) -> Option<&Entry> {
94        self.entries.iter().find(|e| &e.dsk == dsk)
95    }
96
97    /// Mutable entry for a DSK.
98    pub fn get_mut(&mut self, dsk: &Dsk) -> Option<&mut Entry> {
99        self.entries.iter_mut().find(|e| &e.dsk == dsk)
100    }
101
102    /// The active entry whose NWI home id matches a SmartStart inclusion request.
103    pub fn match_nwi_home_id(&self, nwi: &[u8; 4]) -> Option<&Entry> {
104        self.entries
105            .iter()
106            .find(|e| e.status == EntryStatus::Active && &e.dsk.nwi_home_id() == nwi)
107    }
108
109    /// Whether any entry is active (the controller then listens for SmartStart requests).
110    pub fn has_active(&self) -> bool {
111        self.entries
112            .iter()
113            .any(|e| e.status == EntryStatus::Active && e.node_id.is_none())
114    }
115}
116
117#[cfg(test)]
118mod tests {
119    use super::*;
120
121    #[test]
122    fn match_by_nwi() {
123        let mut l = ProvisioningList::default();
124        let dsk: Dsk = "51525-35455-41654-24356-13311-14526-06640-31770"
125            .parse()
126            .unwrap();
127        assert!(l.upsert(Entry {
128            dsk,
129            granted: vec![SecurityClass::S2Authenticated],
130            status: EntryStatus::Active,
131            node_id: None,
132            name: None
133        }));
134        assert!(l.has_active());
135        assert_eq!(l.match_nwi_home_id(&dsk.nwi_home_id()).unwrap().dsk, dsk);
136        assert!(l.match_nwi_home_id(&[0, 0, 0, 0]).is_none());
137        l.get_mut(&dsk).unwrap().status = EntryStatus::Inactive;
138        assert!(l.match_nwi_home_id(&dsk.nwi_home_id()).is_none());
139        assert!(l.remove(&dsk).is_some());
140        assert!(l.entries().is_empty());
141    }
142}