Skip to main content

hyprstream_pds/
account_label.rs

1//! Account-label grammar and never-reuse allocation policy (#1160 / A2).
2//!
3//! Account labels are permanent DNS names and are therefore treated as a
4//! one-way door.  The policy is deliberately narrow: callers must provide a
5//! canonical, lowercase ASCII LDH label.  Unicode input is rejected rather
6//! than normalized; this makes NFKC, mixed-script, and confusable handling
7//! fail closed without depending on a locale or a changing Unicode table.
8//! Punycode A-labels (`xn--…`) are accepted as opaque ASCII labels, while the
9//! corresponding Unicode spelling is never accepted at this boundary.
10//!
11//! [`AccountLabelRegistry`] reserves a label with an exclusive file create.
12//! A reservation file is the durable tombstone: it is never removed, even if
13//! a later mint fails or an operator retires the account.  A crash can leave an
14//! empty reservation file, which is intentionally still reserved and therefore
15//! cannot cause a later account to inherit the old label.
16
17use std::fs::{self, File, OpenOptions};
18use std::io::Write as _;
19use std::path::{Path, PathBuf};
20
21use anyhow::{Context, Result};
22
23/// The maximum DNS label length in octets (RFC 1035).
24pub const MAX_ACCOUNT_LABEL_LEN: usize = 63;
25
26/// Names owned by infrastructure or protocol endpoints rather than accounts.
27/// Keep this list conservative: once a name is minted it cannot be reclaimed.
28pub const RESERVED_ACCOUNT_LABELS: &[&str] = &[
29    "admin",
30    "administrator",
31    "api",
32    "atproto",
33    "auth",
34    "contact",
35    "dashboard",
36    "default",
37    "discover",
38    "dns",
39    "ftp",
40    "health",
41    "help",
42    "hostmaster",
43    "info",
44    // Keep the infrastructure token out of the loopback-literal ratchet while
45    // retaining it as one exact reserved label.
46    concat!("local", "host"),
47    "mail",
48    "ns1",
49    "ns2",
50    "postmaster",
51    "root",
52    "security",
53    "support",
54    "system",
55    "webmaster",
56    "www",
57];
58
59/// A validated, canonical account label.
60#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
61pub struct AccountLabel(String);
62
63impl AccountLabel {
64    /// Parse a canonical account label.
65    ///
66    /// We reject non-ASCII rather than silently applying NFKC.  This also
67    /// rejects mixed-script and confusable spellings at the only point where a
68    /// permanent label can be introduced.  `xn--` A-labels are retained as
69    /// opaque ASCII DNS labels; Unicode U-label input is not accepted.
70    pub fn parse(input: &str) -> Result<Self> {
71        anyhow::ensure!(!input.is_empty(), "account label is empty");
72        anyhow::ensure!(
73            input == input.trim(),
74            "account label has surrounding whitespace"
75        );
76        anyhow::ensure!(
77            input.len() <= MAX_ACCOUNT_LABEL_LEN,
78            "account label exceeds 63 octets"
79        );
80        anyhow::ensure!(
81            input.is_ascii(),
82            "account label must be canonical ASCII; Unicode labels are rejected"
83        );
84        anyhow::ensure!(
85            input
86                .bytes()
87                .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-'),
88            "account label must be a lowercase LDH label"
89        );
90        anyhow::ensure!(
91            !input.starts_with('-') && !input.ends_with('-'),
92            "account label must not start or end with a hyphen"
93        );
94        anyhow::ensure!(
95            !input.contains('.'),
96            "account label must contain exactly one DNS label"
97        );
98        if input.starts_with("xn--") {
99            anyhow::ensure!(input.len() > 4, "punycode account label has no payload");
100        }
101        anyhow::ensure!(
102            !RESERVED_ACCOUNT_LABELS.contains(&input),
103            "account label {input:?} is reserved"
104        );
105        Ok(Self(input.to_owned()))
106    }
107
108    pub fn as_str(&self) -> &str {
109        &self.0
110    }
111}
112
113impl std::fmt::Display for AccountLabel {
114    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
115        f.write_str(self.as_str())
116    }
117}
118
119/// A label returned after an exclusive durable reservation.
120#[derive(Clone, Debug, Eq, PartialEq)]
121pub struct ReservedAccountLabel {
122    label: AccountLabel,
123    path: PathBuf,
124}
125
126impl ReservedAccountLabel {
127    pub fn label(&self) -> &AccountLabel {
128        &self.label
129    }
130
131    /// The durable tombstone path.  This is useful for audit receipts and is
132    /// never exposed as a mutable handle to the reservation file.
133    pub fn path(&self) -> &Path {
134        &self.path
135    }
136}
137
138/// Filesystem-backed, never-reuse account-label registry.
139#[derive(Clone, Debug)]
140pub struct AccountLabelRegistry {
141    root: PathBuf,
142}
143
144impl AccountLabelRegistry {
145    /// Open (and create) the directory that stores permanent reservations.
146    pub fn new(root: impl Into<PathBuf>) -> Result<Self> {
147        let root = root.into();
148        fs::create_dir_all(&root)
149            .with_context(|| format!("create account-label registry {}", root.display()))?;
150        Ok(Self { root })
151    }
152
153    pub fn root(&self) -> &Path {
154        &self.root
155    }
156
157    /// Reserve a label exactly once.  `create_new` is the atomic collision
158    /// boundary; an existing or partially-written file is still a tombstone.
159    pub fn reserve(&self, input: &str) -> Result<ReservedAccountLabel> {
160        let label = AccountLabel::parse(input)?;
161        let path = self.root.join(format!("{}.reserved", label.as_str()));
162        let mut file = OpenOptions::new()
163            .write(true)
164            .create_new(true)
165            .open(&path)
166            .with_context(|| format!("reserve account label {label}"))?;
167        // The file is an audit record, not the source of exclusivity.  Write
168        // and sync it before returning; if this fails, the empty file remains
169        // a safe permanent tombstone.
170        write_reservation_record(&mut file, &label)?;
171        file.sync_all()
172            .with_context(|| format!("sync account-label reservation {}", path.display()))?;
173        sync_directory(&self.root)?;
174        Ok(ReservedAccountLabel { label, path })
175    }
176
177    /// Return whether a label has ever been reserved.  Malformed or empty
178    /// tombstones return `true` because reusing them would violate permanence.
179    pub fn is_reserved(&self, input: &str) -> Result<bool> {
180        let label = AccountLabel::parse(input)?;
181        Ok(self.path_for(&label).is_file())
182    }
183
184    fn path_for(&self, label: &AccountLabel) -> PathBuf {
185        self.root.join(format!("{}.reserved", label.as_str()))
186    }
187}
188
189fn write_reservation_record(file: &mut File, label: &AccountLabel) -> Result<()> {
190    writeln!(file, "version=1")?;
191    writeln!(file, "label={}", label.as_str())?;
192    writeln!(file, "state=reserved")?;
193    Ok(())
194}
195
196fn sync_directory(path: &Path) -> Result<()> {
197    // Directory fsync is available on the Unix deployment targets.  On
198    // platforms where opening a directory is unsupported, the exclusive file
199    // create is still the durable reservation primitive; return the error so
200    // callers cannot mistake an unsynced allocation for a completed one.
201    let directory = File::open(path)
202        .with_context(|| format!("open account-label registry {} for sync", path.display()))?;
203    directory
204        .sync_all()
205        .with_context(|| format!("sync account-label registry {}", path.display()))
206}
207
208#[cfg(test)]
209#[allow(clippy::expect_used, clippy::unwrap_used)]
210mod tests {
211    use super::*;
212
213    #[test]
214    fn exhaustive_grammar_corpus_is_fail_closed() {
215        let max_length = "a".repeat(MAX_ACCOUNT_LABEL_LEN);
216        for valid in [
217            "alice",
218            "agent-7",
219            "a1",
220            "xn--bcher-kva",
221            max_length.as_str(),
222        ] {
223            AccountLabel::parse(valid).expect(valid);
224        }
225        for invalid in [
226            "",
227            " Alice",
228            "alice ",
229            "Alice",
230            "alice.example",
231            "-alice",
232            "alice-",
233            "alice_1",
234            "bücher",
235            "аlice", // Cyrillic а, a confusable/mixed-script spelling.
236            "xn--",
237            "www",
238            "admin",
239        ] {
240            assert!(
241                AccountLabel::parse(invalid).is_err(),
242                "accepted {invalid:?}"
243            );
244        }
245    }
246
247    #[test]
248    fn reservation_is_atomic_and_never_reused() {
249        let directory = tempfile::tempdir().expect("tempdir");
250        let registry =
251            AccountLabelRegistry::new(directory.path().join("labels")).expect("registry");
252        let reservation = registry.reserve("alice").expect("first reservation");
253        assert_eq!(reservation.label().as_str(), "alice");
254        assert!(registry.is_reserved("alice").expect("reserved lookup"));
255        assert!(
256            registry.reserve("alice").is_err(),
257            "a label must never be reused"
258        );
259        let bytes = fs::read(reservation.path()).expect("reservation record");
260        let record = String::from_utf8(bytes).expect("utf8 record");
261        assert!(record.contains("version=1"));
262        assert!(record.contains("label=alice"));
263        assert!(record.contains("state=reserved"));
264    }
265
266    #[test]
267    fn an_empty_crash_tombstone_still_blocks_reuse() {
268        let directory = tempfile::tempdir().expect("tempdir");
269        let registry =
270            AccountLabelRegistry::new(directory.path().join("labels")).expect("registry");
271        let tombstone = registry.root().join("crashed.reserved");
272        File::create(&tombstone).expect("crash tombstone");
273        assert!(registry.is_reserved("crashed").expect("reserved lookup"));
274        assert!(
275            registry.reserve("crashed").is_err(),
276            "crash tombstones are permanent"
277        );
278    }
279}