1use std::fs::{self, File, OpenOptions};
18use std::io::Write as _;
19use std::path::{Path, PathBuf};
20
21use anyhow::{Context, Result};
22
23pub const MAX_ACCOUNT_LABEL_LEN: usize = 63;
25
26pub 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 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#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
61pub struct AccountLabel(String);
62
63impl AccountLabel {
64 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#[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 pub fn path(&self) -> &Path {
134 &self.path
135 }
136}
137
138#[derive(Clone, Debug)]
140pub struct AccountLabelRegistry {
141 root: PathBuf,
142}
143
144impl AccountLabelRegistry {
145 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 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 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 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 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", "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}