zenkey_model/hostid.rs
1//! `hostid.v1`: a system name minted from the machine id
2//! (`spec/profiles/hostid/v1.md`, #719).
3//!
4//! The derivation-only profile of core §10 (0.19): it defines no contract,
5//! annotation or kind, only how an owner derives its system from a machine
6//! id, so that system = host (core §1.5). This module is its session-free
7//! half, the pure derivation of §2.1:
8//!
9//! ```text
10//! norm = lower(trim(input)) 32 hex digits, not all zeros, or refused
11//! system = "h-" ++ hex(sha256(utf8(norm) ++ utf8(salt)))[0..12]
12//! ```
13//!
14//! There is no file I/O here. Reading the inputs in order (§2.4), the
15//! shared file (§2.5), failing closed and the `ephemeral` opt-in (§2.6)
16//! belong to the runtime, which calls [`system`] on what it reads.
17
18use sha2::{Digest, Sha256};
19
20use crate::chunk::is_lower_hex;
21use crate::grammar::Name;
22
23/// The one salt of `hostid.v1` (§2.2; architecture D26). Every system is
24/// derived with it, so a machine is one system across every zk2
25/// application. It is not configurable: [`derive()`] takes a salt only so
26/// that the test vectors and the v1 migration table (Appendix B) can be
27/// computed.
28pub const SALT: &str = "zk2-hostid-v1";
29
30/// The profile's id, as an instance whose system is minted lists it in its
31/// descriptor's `profiles` (§2.8; core §3.3, 0.19).
32pub const PROFILE: &str = "hostid.v1";
33
34/// The prefix of a minted system (§2.1).
35pub const PREFIX: &str = "h-";
36
37/// How many hex digits of the digest a system keeps: 48 bits (§2.1, §2.12).
38pub const DIGITS: usize = 12;
39
40/// Normalises a machine id (§2.1 steps 1–2), or refuses it.
41///
42/// Trims the five ASCII whitespace bytes (TAB, LF, FF, CR, SPACE) from both
43/// ends, and no other character: not 0x0B, as Python's `strip()` would, and
44/// not Unicode spaces, as Rust's `str::trim` would. Then lowercases `A–Z`,
45/// and nothing else (no Unicode case folding). The check is on characters,
46/// never a number parse, which would accept a sign.
47/// The result must be exactly 32 hex digits and not all zeros (an all-zero
48/// id is not a machine id, machine-id(5)). Anything else is refused with
49/// `None`: absent, empty, systemd's `uninitialized`, a UUID with hyphens,
50/// 31 or 33 digits, a non-hex digit (§2.4 then tries the next input).
51#[must_use]
52pub fn normalise(input: &str) -> Option<String> {
53 // `str::trim_ascii` trims exactly `u8::is_ascii_whitespace`: the five
54 // bytes above.
55 let norm = input.trim_ascii().to_ascii_lowercase();
56 (is_lower_hex(&norm, 32) && norm.bytes().any(|b| b != b'0')).then_some(norm)
57}
58
59/// Derives a system from a machine id with `salt` (§2.1), or refuses the
60/// input ([`normalise`]).
61///
62/// The system is `h-` and the first 12 lowercase hex digits of
63/// `sha256(norm ++ salt)`, both UTF-8, with no separator. A deployment
64/// always derives with [`SALT`] ([`system`]); another salt is for the
65/// vectors and the migration table only (§2.2).
66#[must_use]
67pub fn derive(machine_id: &str, salt: &str) -> Option<String> {
68 let norm = normalise(machine_id)?;
69 let digest = Sha256::new()
70 .chain_update(norm.as_bytes())
71 .chain_update(salt.as_bytes())
72 .finalize();
73 let mut system = String::with_capacity(PREFIX.len() + DIGITS);
74 system.push_str(PREFIX);
75 for b in &digest[..DIGITS / 2] {
76 system.push(char::from_digit(u32::from(b >> 4), 16).expect("a nibble"));
77 system.push(char::from_digit(u32::from(b & 0xf), 16).expect("a nibble"));
78 }
79 Some(system)
80}
81
82/// The system `hostid.v1` mints from a machine id, with the one salt
83/// ([`SALT`]), or `None` when the input is refused (§2.1, §2.4).
84///
85/// A minted system is a plain chunk (core §1.2) and its own slug (core
86/// §1.4), so it is a system [`Name`] as it stands.
87#[must_use]
88pub fn system(machine_id: &str) -> Option<Name> {
89 let s = derive(machine_id, SALT)?;
90 Some(Name::new("system", &s).expect("h- and 12 hex digits is a plain chunk"))
91}
92
93/// Whether `s` is in the minted shape: exactly `h-` followed by 12
94/// lowercase hex digits, the whole string (§2.11).
95///
96/// The shape is a hint, never proof: a deployment may name a system in it
97/// literally. Only the descriptor's `profiles` establishes a minted system
98/// (§2.8, §5).
99#[must_use]
100pub fn is_minted_shape(s: &str) -> bool {
101 s.strip_prefix(PREFIX)
102 .is_some_and(|hex| is_lower_hex(hex, DIGITS))
103}
104
105#[cfg(test)]
106mod tests {
107 use super::*;
108 use crate::slug::chunk_slug;
109
110 const MID: &str = "b642b4217b34b1e8d3bd915fc65c4452";
111
112 /// v1's test vector, which the construction keeps (hostid.v1 Appendix A).
113 #[test]
114 fn rfc06_vector() {
115 assert_eq!(
116 derive(MID, "example-salt-v1").as_deref(),
117 Some("h-20609002f7b6")
118 );
119 }
120
121 /// The same machine id under the one salt (§2.2).
122 #[test]
123 fn zk2_vector() {
124 assert_eq!(derive(MID, SALT).as_deref(), Some("h-bbd1aa1db10b"));
125 assert_eq!(system(MID).unwrap().as_str(), "h-bbd1aa1db10b");
126 }
127
128 #[test]
129 fn normalisation_trims_five_bytes_and_lowercases() {
130 for input in [
131 "b642b4217b34b1e8d3bd915fc65c4452\n",
132 "b642b4217b34b1e8d3bd915fc65c4452\r\n",
133 " b642b4217b34b1e8d3bd915fc65c4452\t ",
134 "\x0cb642b4217b34b1e8d3bd915fc65c4452\x0c",
135 "B642B4217B34B1E8D3BD915FC65C4452",
136 ] {
137 assert_eq!(normalise(input).as_deref(), Some(MID), "{input:?}");
138 }
139 }
140
141 #[test]
142 fn refused_inputs_yield_nothing() {
143 for input in [
144 "",
145 "\n",
146 "uninitialized\n",
147 "00000000000000000000000000000000",
148 "b642b4217b34b1e8d3bd915fc65c445",
149 "b642b4217b34b1e8d3bd915fc65c44520",
150 "b642b4217b34b1e8d3bd915fc65c445g",
151 "b642b421-7b34-b1e8-d3bd-915fc65c4452",
152 "b642b4217b34b1e8 d3bd915fc65c4452",
153 "\x0bb642b4217b34b1e8d3bd915fc65c4452\x0b",
154 "\u{a0}b642b4217b34b1e8d3bd915fc65c4452\u{a0}",
155 "+642b4217b34b1e8d3bd915fc65c4452",
156 "b642b4217b34b1e8_3bd915fc65c4452",
157 "b642b4217b34b1e8d3bd915fc65c44\u{fb00}",
158 ] {
159 assert_eq!(normalise(input), None, "{input:?}");
160 assert_eq!(derive(input, SALT), None, "{input:?}");
161 assert_eq!(system(input), None, "{input:?}");
162 }
163 }
164
165 #[test]
166 fn a_minted_system_is_a_plain_chunk_and_its_own_slug() {
167 for input in [MID, "00000000000000000000000000000001"] {
168 let s = system(input).unwrap();
169 assert_eq!(s.as_str().len(), 14);
170 assert!(is_minted_shape(s.as_str()));
171 assert_eq!(chunk_slug(s.as_str()), s.as_str());
172 }
173 }
174
175 #[test]
176 fn the_shape() {
177 for yes in ["h-20609002f7b6", "h-000000000000"] {
178 assert!(is_minted_shape(yes), "{yes}");
179 }
180 for no in [
181 "H-20609002f7b6",
182 "h-20609002F7B6",
183 "h-20609002f7b",
184 "h-20609002f7b6a",
185 "h_20609002f7b6",
186 "20609002f7b6",
187 "h-20609002f7b6\n",
188 "",
189 "vehicle-01",
190 ] {
191 assert!(!is_minted_shape(no), "{no:?}");
192 }
193 }
194}