Skip to main content

tilo_action_policy/
person.rs

1//! A person, by their root public key: the one id every resource, roster and
2//! grant spells the same way.
3//!
4//! A person's id is the lowercase hex of their root public key and nothing
5//! else (the empty id is the nobody the action model carries for software
6//! holding no person's authority). Kinds of member that are not people carry a
7//! prefix that says so (`agent:<id>`, `bot:<id>`, `automation:<id>`), so a
8//! person needs none: a bare id is a person's, and an id carrying a prefix
9//! names software. Storing `person:<root>` beside the bare root made one
10//! person two strings, and every comparison, roster row and presence entry had
11//! to guess which spelling it was looking at. [`PersonId`] refuses that
12//! spelling when it is parsed.
13
14use serde::de::Error as _;
15use serde::{Deserialize, Deserializer, Serialize, Serializer};
16
17/// A person's id: the lowercase hex of their root public key, bare.
18///
19/// Built from a root key ([`PersonId::from_root`]) or parsed from a stored id
20/// ([`PersonId::parse`], which is also what its serde reader uses). A string
21/// carrying a member prefix names software, never a person.
22#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
23pub struct PersonId(String);
24
25/// Why an id is not a person's.
26#[derive(Clone, Copy, Debug, PartialEq, Eq)]
27pub enum PersonIdError {
28    /// An id that carries a prefix names software: `person:<root>` is the
29    /// prefixed spelling of a person, and is refused like any other.
30    Prefixed,
31}
32
33impl std::fmt::Display for PersonIdError {
34    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
35        f.write_str("a person's id is their bare root key, with no prefix")
36    }
37}
38
39impl std::error::Error for PersonIdError {}
40
41impl PersonId {
42    /// `id` as a person's, when it is their bare root key. Empty is nobody:
43    /// the action model carries it for software holding no person's authority.
44    ///
45    /// # Errors
46    /// An id carrying a `:` (the prefix a member's kind is written with)
47    /// names software, never a person.
48    pub fn parse(id: &str) -> Result<Self, PersonIdError> {
49        if id.contains(':') {
50            return Err(PersonIdError::Prefixed);
51        }
52        Ok(Self(id.to_owned()))
53    }
54
55    /// The root public key `root`, as the id every resource spells.
56    #[must_use]
57    pub fn from_root(root: [u8; 32]) -> Self {
58        Self(hex::encode(root))
59    }
60
61    #[must_use]
62    pub fn as_str(&self) -> &str {
63        &self.0
64    }
65
66    /// The root public key, when the id is one: 32 bytes of hex.
67    #[must_use]
68    pub fn root(&self) -> Option<[u8; 32]> {
69        let mut root = [0; 32];
70        hex::decode_to_slice(&self.0, &mut root).ok()?;
71        Some(root)
72    }
73
74    /// `id` as a person's, for an id this device minted or a fixture names:
75    /// a prefixed id is a mistake in this program, not in data.
76    ///
77    /// # Panics
78    /// When `id` is not a person's id ([`PersonId::parse`] refuses it).
79    #[must_use]
80    #[track_caller]
81    #[allow(
82        clippy::expect_used,
83        reason = "an id this program mints or a fixture names: a prefixed one is a mistake here, not in data"
84    )]
85    pub fn expect(id: impl AsRef<str>) -> Self {
86        Self::parse(id.as_ref()).expect("a person's id is their bare root key")
87    }
88}
89
90impl From<String> for PersonId {
91    #[track_caller]
92    fn from(id: String) -> Self {
93        Self::expect(id)
94    }
95}
96
97impl From<&str> for PersonId {
98    #[track_caller]
99    fn from(id: &str) -> Self {
100        Self::expect(id)
101    }
102}
103
104impl From<&String> for PersonId {
105    #[track_caller]
106    fn from(id: &String) -> Self {
107        Self::expect(id)
108    }
109}
110
111impl From<&PersonId> for PersonId {
112    fn from(id: &PersonId) -> Self {
113        id.clone()
114    }
115}
116
117impl std::ops::Deref for PersonId {
118    type Target = str;
119
120    fn deref(&self) -> &str {
121        &self.0
122    }
123}
124
125impl AsRef<str> for PersonId {
126    fn as_ref(&self) -> &str {
127        &self.0
128    }
129}
130
131impl std::borrow::Borrow<str> for PersonId {
132    fn borrow(&self) -> &str {
133        &self.0
134    }
135}
136
137impl std::fmt::Display for PersonId {
138    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
139        f.write_str(&self.0)
140    }
141}
142
143/// A person's id compares as the string it is, so a caller holding a stored id
144/// reads a roster or a grant without unwrapping one.
145impl PartialEq<str> for PersonId {
146    fn eq(&self, other: &str) -> bool {
147        self.0 == other
148    }
149}
150
151impl PartialEq<&str> for PersonId {
152    fn eq(&self, other: &&str) -> bool {
153        self.0 == *other
154    }
155}
156
157impl PartialEq<String> for PersonId {
158    fn eq(&self, other: &String) -> bool {
159        &self.0 == other
160    }
161}
162
163/// Written and read as the bare root key: an id that carries a prefix fails to
164/// read as a person.
165impl Serialize for PersonId {
166    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
167        serializer.serialize_str(&self.0)
168    }
169}
170
171impl<'de> Deserialize<'de> for PersonId {
172    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
173        let id = String::deserialize(deserializer)?;
174        Self::parse(&id).map_err(D::Error::custom)
175    }
176}
177
178#[cfg(test)]
179mod tests {
180    use super::*;
181
182    tilo_test_env::scenario! {
183        /// A person's id is their bare root key, and a prefixed one is no person.
184        fn a_person_id_is_its_bare_root_key;
185
186        phase a_bare_root_reads_back_as_the_same_person;
187        {
188            let id = PersonId::from_root([7; 32]);
189            assert_eq!(id.as_str().len(), 64);
190            assert_eq!(id.root(), Some([7; 32]));
191            assert_eq!(PersonId::parse(id.as_str()).unwrap(), id);
192            let json = serde_json::to_string(&id).unwrap();
193            assert_eq!(json, format!("\"{id}\""), "written bare");
194            assert_eq!(serde_json::from_str::<PersonId>(&json).unwrap(), id);
195        }
196
197        phase a_prefixed_id_names_no_person;
198        {
199            assert_eq!(
200                PersonId::parse("person:7a7a"),
201                Err(PersonIdError::Prefixed),
202                "the prefixed spelling is not a person"
203            );
204            assert_eq!(PersonId::parse("agent:helper"), Err(PersonIdError::Prefixed));
205            assert!(
206                serde_json::from_str::<PersonId>("\"person:7a\"").is_err(),
207                "a resource carrying the prefixed spelling does not read as a person"
208            );
209        }
210    }
211}