spoolframe_protocol/
server_id.rs1use std::fmt;
17use std::str::FromStr;
18
19pub use spoolframe_types::APP_RP_DOMAIN;
20
21const ALPHABET: &[u8; 32] = b"abcdefghijklmnopqrstuvwxyz234567";
23
24pub const SERVER_ID_BYTES: usize = 10;
26
27pub const SERVER_ID_LEN: usize = 16;
29
30#[derive(Debug, Clone, PartialEq, Eq, Hash)]
32pub struct ServerId(String);
33
34#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
36#[error("{0:?} is not a server id: 16 characters of a-z and 2-7")]
37pub struct InvalidServerId(pub String);
38
39impl ServerId {
40 pub fn from_bytes(bytes: [u8; SERVER_ID_BYTES]) -> Self {
42 let mut id = String::with_capacity(SERVER_ID_LEN);
43 for group in bytes.as_chunks::<5>().0 {
45 let bits = group
46 .iter()
47 .fold(0u64, |bits, &byte| (bits << 8) | u64::from(byte));
48 for at in (0..8).rev() {
49 id.push(char::from(ALPHABET[((bits >> (at * 5)) & 31) as usize]));
50 }
51 }
52 Self(id)
53 }
54
55 pub fn parse(id: &str) -> Result<Self, InvalidServerId> {
60 if id.len() == SERVER_ID_LEN && id.bytes().all(|c| ALPHABET.contains(&c)) {
61 Ok(Self(id.to_owned()))
62 } else {
63 Err(InvalidServerId(id.to_owned()))
64 }
65 }
66
67 pub fn as_str(&self) -> &str {
68 &self.0
69 }
70
71 pub fn rp_id(&self) -> String {
76 format!("{}.{APP_RP_DOMAIN}", self.0)
77 }
78
79 pub fn origin(&self) -> String {
84 format!("https://{}", self.rp_id())
85 }
86}
87
88impl fmt::Display for ServerId {
89 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
90 f.write_str(&self.0)
91 }
92}
93
94impl FromStr for ServerId {
95 type Err = InvalidServerId;
96
97 fn from_str(id: &str) -> Result<Self, Self::Err> {
98 Self::parse(id)
99 }
100}
101
102#[cfg(test)]
103mod tests {
104 use super::*;
105
106 #[test]
109 fn the_id_is_lowercase_base32_of_the_bytes() {
110 assert_eq!(
111 ServerId::from_bytes(*b"foobarfoob").as_str(),
112 "mzxw6ytbojtg633c"
113 );
114 assert_eq!(ServerId::from_bytes([0; 10]).as_str(), "aaaaaaaaaaaaaaaa");
115 assert_eq!(
116 ServerId::from_bytes([0xff; 10]).as_str(),
117 "7777777777777777"
118 );
119 }
120
121 fn is_dns_label(label: &str) -> bool {
124 (1..=63).contains(&label.len())
125 && label
126 .bytes()
127 .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'-')
128 && !label.starts_with('-')
129 && !label.ends_with('-')
130 }
131
132 #[test]
133 fn every_id_is_a_dns_label_of_16_characters() {
134 for seed in 0..=255u8 {
135 let bytes = std::array::from_fn(|i| seed.wrapping_mul(31) ^ (i as u8).wrapping_mul(97));
136 let id = ServerId::from_bytes(bytes);
137 assert_eq!(id.as_str().len(), SERVER_ID_LEN, "{id}");
138 assert!(is_dns_label(id.as_str()), "{id}");
139 assert_eq!(ServerId::parse(id.as_str()), Ok(id));
140 }
141 }
142
143 #[test]
144 fn the_relying_party_and_origin_are_under_spoolframe_app() {
145 let id = ServerId::parse("mzxw6ytbojtg633c").unwrap();
146 assert_eq!(id.rp_id(), "mzxw6ytbojtg633c.spoolframe.app");
147 assert_eq!(id.origin(), "https://mzxw6ytbojtg633c.spoolframe.app");
148 }
149
150 #[test]
151 fn what_is_not_an_id_as_written_is_refused() {
152 for bad in [
153 "",
154 "mzxw6ytboj",
155 "mzxw6ytbojtg633ca",
156 "MZXW6YTBOJTG633C",
157 "mzxw6ytboj1g633c",
158 "mzxw6ytboj.g633c",
159 "mzxw6ytboj-g633c",
160 ] {
161 assert_eq!(
162 ServerId::parse(bad),
163 Err(InvalidServerId(bad.into())),
164 "{bad}"
165 );
166 }
167 }
168}