Skip to main content

fritz_core/
identity.rs

1//! Which device is which: an identity that stays the same across addresses
2//! and firmware updates, and the lists of devices that may and may never be
3//! changed.
4//!
5//! The identity is the SHA-256 hash of the unique device name (UDN) in the
6//! device description and the serial number `DeviceInfo:GetInfo` returns.
7//! The hash names a device without revealing either of them.
8//!
9//! ```toml
10//! [write]
11//! allow = ["<identity of a test device>"]
12//! deny = ["<identity of the device at home>"]
13//! ```
14
15use std::fmt;
16use std::str::FromStr;
17
18use serde::{Deserialize, Serialize};
19use sha2::{Digest as _, Sha256};
20
21use crate::session::to_hex;
22
23/// The identity of a device.
24#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
25#[serde(try_from = "String", into = "String")]
26pub struct Identity(String);
27
28/// A text is not an identity.
29#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
30#[error("{0} is not a device identity of 64 hex digits")]
31pub struct InvalidIdentity(String);
32
33impl Identity {
34    /// The identity of the device with the unique device name `udn` and the
35    /// serial number `serial`.
36    pub fn of(udn: &str, serial: &str) -> Self {
37        let hash = Sha256::digest(format!("{udn}\n{serial}"));
38        Self(to_hex(&hash))
39    }
40}
41
42impl fmt::Display for Identity {
43    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
44        f.write_str(&self.0)
45    }
46}
47
48impl FromStr for Identity {
49    type Err = InvalidIdentity;
50
51    /// Parses 64 hex digits, in any case.
52    fn from_str(s: &str) -> Result<Self, Self::Err> {
53        if s.len() == 64 && s.bytes().all(|b| b.is_ascii_hexdigit()) {
54            Ok(Self(s.to_ascii_lowercase()))
55        } else {
56            Err(InvalidIdentity(s.to_owned()))
57        }
58    }
59}
60
61impl TryFrom<String> for Identity {
62    type Error = InvalidIdentity;
63
64    fn try_from(value: String) -> Result<Self, Self::Error> {
65        value.parse()
66    }
67}
68
69impl From<Identity> for String {
70    fn from(identity: Identity) -> Self {
71        identity.0
72    }
73}
74
75/// The devices that may be changed, and those that may never be.
76#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
77#[serde(deny_unknown_fields)]
78pub struct Targets {
79    /// The devices that may be changed.
80    #[serde(default, skip_serializing_if = "Vec::is_empty")]
81    pub allow: Vec<Identity>,
82    /// The devices that may never be changed, even if they are allowed.
83    #[serde(default, skip_serializing_if = "Vec::is_empty")]
84    pub deny: Vec<Identity>,
85}
86
87/// Whether a device may be changed.
88#[derive(Debug, Clone, Copy, PartialEq, Eq)]
89pub enum Verdict {
90    /// The device is allowed and not denied.
91    Allowed,
92    /// The device is denied.
93    Denied,
94    /// The device is not allowed.
95    Unknown,
96}
97
98impl Targets {
99    /// Whether there are no devices in either list.
100    pub fn is_empty(&self) -> bool {
101        self.allow.is_empty() && self.deny.is_empty()
102    }
103
104    /// Whether the device may be changed. The deny list wins.
105    pub fn verdict(&self, identity: &Identity) -> Verdict {
106        if self.deny.contains(identity) {
107            Verdict::Denied
108        } else if self.allow.contains(identity) {
109            Verdict::Allowed
110        } else {
111            Verdict::Unknown
112        }
113    }
114}
115
116#[cfg(test)]
117mod tests {
118    use super::*;
119
120    #[test]
121    fn hashes_the_udn_and_the_serial_number() {
122        let identity = Identity::of("uuid:1", "AABBCC");
123        assert_eq!(identity.to_string().len(), 64);
124        assert_eq!(identity, Identity::of("uuid:1", "AABBCC"));
125        assert_ne!(identity, Identity::of("uuid:1", "AABBCD"));
126        assert_ne!(identity, Identity::of("uuid:1A", "ABBCC"));
127    }
128
129    #[test]
130    fn parses_hex_digits() {
131        let identity = Identity::of("uuid:1", "AABBCC");
132        let upper = identity.to_string().to_ascii_uppercase();
133        assert_eq!(upper.parse::<Identity>(), Ok(identity.clone()));
134        assert_eq!(
135            "xyz".parse::<Identity>().unwrap_err().to_string(),
136            "xyz is not a device identity of 64 hex digits"
137        );
138        assert!("g".repeat(64).parse::<Identity>().is_err());
139        assert_eq!(String::from(identity.clone()), identity.to_string());
140    }
141
142    #[test]
143    fn denies_before_it_allows() {
144        let home = Identity::of("uuid:home", "1");
145        let test = Identity::of("uuid:test", "2");
146        let targets = Targets {
147            allow: vec![home.clone(), test.clone()],
148            deny: vec![home.clone()],
149        };
150        assert_eq!(targets.verdict(&home), Verdict::Denied);
151        assert_eq!(targets.verdict(&test), Verdict::Allowed);
152        assert_eq!(
153            targets.verdict(&Identity::of("uuid:other", "3")),
154            Verdict::Unknown
155        );
156        assert!(!targets.is_empty());
157        assert!(Targets::default().is_empty());
158    }
159}