1use std::fmt;
16use std::str::FromStr;
17
18use serde::{Deserialize, Serialize};
19use sha2::{Digest as _, Sha256};
20
21use crate::session::to_hex;
22
23#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
25#[serde(try_from = "String", into = "String")]
26pub struct Identity(String);
27
28#[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 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 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#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
77#[serde(deny_unknown_fields)]
78pub struct Targets {
79 #[serde(default, skip_serializing_if = "Vec::is_empty")]
81 pub allow: Vec<Identity>,
82 #[serde(default, skip_serializing_if = "Vec::is_empty")]
84 pub deny: Vec<Identity>,
85}
86
87#[derive(Debug, Clone, Copy, PartialEq, Eq)]
89pub enum Verdict {
90 Allowed,
92 Denied,
94 Unknown,
96}
97
98impl Targets {
99 pub fn is_empty(&self) -> bool {
101 self.allow.is_empty() && self.deny.is_empty()
102 }
103
104 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}