Skip to main content

spoolframe_protocol/
server_id.rs

1//! A server's id: its name for app passkeys, apart from its key.
2//!
3//! The endpoint key is what a client pins and proves on every connect, and
4//! it may be replaced (a lost state directory, a rotated key). A passkey
5//! is made for a relying party and synced with it to the user's other
6//! devices, so the server needs a name that outlives its key: the server
7//! id. It is made once, from 80 random bits, and kept in the state
8//! directory beside the key.
9//!
10//! It is written as lowercase RFC 4648 base32: 16 characters of `a`-`z`
11//! and `2`-`7`, with no padding (80 bits are 16 characters exactly), a DNS
12//! label as it is. It is short because a password manager shows it in
13//! the passkey's domain, and it says nothing about the server: it goes
14//! wherever its passkeys go.
15
16use std::fmt;
17use std::str::FromStr;
18
19pub use spoolframe_types::APP_RP_DOMAIN;
20
21/// RFC 4648's base32 alphabet, lowercase.
22const ALPHABET: &[u8; 32] = b"abcdefghijklmnopqrstuvwxyz234567";
23
24/// Random bytes in a server id.
25pub const SERVER_ID_BYTES: usize = 10;
26
27/// Characters in a server id: 80 bits in 5-bit characters.
28pub const SERVER_ID_LEN: usize = 16;
29
30/// A server's id, as [`ServerId::parse`] checked it.
31#[derive(Debug, Clone, PartialEq, Eq, Hash)]
32pub struct ServerId(String);
33
34/// Why a string is not a server id.
35#[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    /// The id written for `bytes`: the server makes them at random.
41    pub fn from_bytes(bytes: [u8; SERVER_ID_BYTES]) -> Self {
42        let mut id = String::with_capacity(SERVER_ID_LEN);
43        // 5 bytes are 8 characters, with no bits left over.
44        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    /// `id` if it is a server id as [`ServerId::from_bytes`] writes one:
56    /// 16 characters of the alphabet. Anything else, uppercase too, is
57    /// refused: a server id names a relying party, and one id has one
58    /// spelling.
59    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    /// The relying party of this server's app passkeys:
72    /// `<id>.`[`APP_RP_DOMAIN`]. A security key keeps passkeys apart by
73    /// relying party, so one with passkeys for two servers offers only
74    /// this server's.
75    pub fn rp_id(&self) -> String {
76        format!("{}.{APP_RP_DOMAIN}", self.0)
77    }
78
79    /// The origin the platform writes into `clientDataJSON` for
80    /// [`ServerId::rp_id`]: `https://<id>.spoolframe.app`. WebAuthn wants
81    /// the origin's host to be the relying party or under it, so it is
82    /// never `https://spoolframe.app`.
83    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    /// RFC 4648 base32, lowercase, of 10 bytes: the known answer, from
107    /// Python's `base64.b32encode`.
108    #[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    /// A DNS label: 1 to 63 letters, digits and hyphens, not starting or
122    /// ending with a hyphen. A relying party's host is made of them.
123    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}