hyprstream_core/account/zone.rs
1//! The deployment-configured account zone (epic #1158, ticket #1162 / Phase A3).
2//!
3//! The account zone is the DNS apex under which every host-form `did:web` this
4//! deployment mints lives — e.g. `did:web:alice.acct.example.com`. It is
5//! **deployment-relative configuration**: the operator picks it, in the metal
6//! repo, when deploying hyprstream. hyprstream never bakes a zone name in.
7//!
8//! # No default — ever
9//!
10//! A deployment that configures no account zone must **degrade sanely**: account
11//! minting is disabled with a clear error. It must not panic, and above all it
12//! must not synthesize a default zone name — a default would silently mint
13//! permanent DIDs under a domain the operator never chose (one-way door #1 in
14//! the epic). `AccountZone` therefore has no `Default` impl and no constructor
15//! that invents a name; the only way to obtain one is
16//! [`AccountZoneConfig::resolve_zone`](super::config::AccountZoneConfig::resolve_zone),
17//! which returns `Err` when the zone is unset.
18//!
19//! # Label depth — the A2 seam (#1160)
20//!
21//! A wildcard certificate matches **exactly one** DNS label: `*.acct.example.com`
22//! covers `alice.acct.example.com` and *never* `a.b.acct.example.com`. This
23//! module fixes the *wildcard* shape (one label below the apex). The grammar a
24//! single account label must satisfy (LDH, ≤63 chars, NFKC, no mixed-script,
25//! reserved list, never-reuse) is owned by A2 (`#1160`); B1 enforces it at
26//! mint time. A3 only guarantees the wildcard covers exactly one label, which
27//! [`AccountZone::wildcard_domain`] does structurally.
28
29use std::fmt;
30use std::str::FromStr;
31
32use serde::{Deserialize, Serialize};
33use thiserror::Error;
34
35/// An error raised while resolving or parsing an account zone.
36#[derive(Debug, Error)]
37pub enum AccountZoneError {
38 /// The deployment configured no account zone. **This is the sane-degrade
39 /// path**, not a panic and not a synthesized default. Account minting is
40 /// disabled; callers surface this to the operator.
41 #[error("no account zone configured — account minting is disabled. Set [account] zone (e.g. \"acct.example.com\") to enable did:web minting under a deployment-chosen apex.")]
42 Unset,
43 /// The configured zone name was not a syntactically valid DNS name.
44 #[error("invalid account zone name {name:?}: {reason}")]
45 Invalid { name: String, reason: String },
46}
47
48/// A deployment-configured, validated account-zone apex.
49///
50/// Constructed only via [`AccountZone::new`] / [`FromStr`], both of which
51/// reject anything that is not a normalized, lowercase, fully-qualified DNS
52/// name with at least one delegation label below a public suffix (so an
53/// operator cannot accidentally configure a bare TLD). There is intentionally
54/// **no `Default`**: see the module docs on sane-degrade.
55///
56/// The apex is the zone NS-delegated to hyprstream — e.g. `acct.example.com`,
57/// NOT `*.acct.example.com` and NOT a per-account host. Wildcard and
58/// per-account hostnames are derived from it.
59#[derive(Debug, Clone, PartialEq, Eq, Hash)]
60pub struct AccountZone {
61 // Normalized lowercase ASCII DNS name without a trailing dot.
62 apex: String,
63 // Precomputed `*.apex` — the wildcard that covers exactly one label.
64 wildcard: String,
65}
66
67impl AccountZone {
68 /// Validate and wrap a zone apex like `acct.example.com`.
69 ///
70 /// Rejects empty input, trailing dots, uppercase (use the normalized form),
71 /// underscores, leading digits-in-TLD-style oddities, labels over 63 octets,
72 /// total length over 253, consecutive dots, and bare public suffixes
73 /// (`com`, `co.uk`) which an operator almost certainly did not intend to
74 /// delegate whole to hyprstream.
75 pub fn new(apex: impl Into<String>) -> Result<Self, AccountZoneError> {
76 let apex = apex.into();
77 validate_zone_apex(&apex)?;
78 // `validate_zone_apex` guarantees lowercase + no trailing dot, so this
79 // wildcard is the exact one-label form a CA will issue for DNS-01.
80 let wildcard = format!("*.{apex}");
81 Ok(Self { apex, wildcard })
82 }
83
84 /// The bare apex, e.g. `acct.example.com`. Lowercase, no trailing dot.
85 pub fn apex(&self) -> &str {
86 &self.apex
87 }
88
89 /// The wildcard that covers **exactly one** label below the apex, e.g.
90 /// `*.acct.example.com`. This is the name the DNS-01 wildcard TLS
91 /// certificate is issued for, and the name wildcard A/AAAA records are
92 /// published under.
93 pub fn wildcard_domain(&self) -> &str {
94 &self.wildcard
95 }
96
97 /// The DNS-01 `_acme-challenge` validation owner name for the wildcard
98 /// certificate. Per RFC 8555, a `*.` identifier is validated by publishing
99 /// the TXT record at `_acme-challenge.<apex>` (the apex, not the wildcard).
100 pub fn dns01_validation_name(&self) -> String {
101 format!("_acme-challenge.{}", self.apex)
102 }
103
104 /// Build a per-account host label under this zone, asserting the label is a
105 /// **single** DNS label (the depth the wildcard covers).
106 ///
107 /// This is the A3 side of the A2 seam: A2 (`#1160`) owns the *grammar* of
108 /// the label; A3 owns the *depth*. We reject any label that contains a `.`
109 /// or is empty, because a multi-label label would escape the wildcard's
110 /// single-label coverage and produce a hostname that does not resolve under
111 /// the issued certificate.
112 pub fn host_for_label(&self, label: &str) -> Result<String, AccountZoneError> {
113 if label.is_empty() {
114 return Err(AccountZoneError::Invalid {
115 name: label.to_owned(),
116 reason: "account label is empty".to_owned(),
117 });
118 }
119 if label.contains('.') {
120 return Err(AccountZoneError::Invalid {
121 name: label.to_owned(),
122 reason: "account label must be a single DNS label (the wildcard covers exactly one label below the zone); multi-label labels are not representable".to_owned(),
123 });
124 }
125 Ok(format!("{label}.{}", self.apex))
126 }
127}
128
129impl FromStr for AccountZone {
130 type Err = AccountZoneError;
131 fn from_str(s: &str) -> Result<Self, Self::Err> {
132 Self::new(s)
133 }
134}
135
136impl fmt::Display for AccountZone {
137 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
138 f.write_str(&self.apex)
139 }
140}
141
142impl Serialize for AccountZone {
143 fn serialize<S: serde::Serializer>(&self, ser: S) -> Result<S::Ok, S::Error> {
144 ser.serialize_str(&self.apex)
145 }
146}
147
148impl<'de> Deserialize<'de> for AccountZone {
149 fn deserialize<D: serde::Deserializer<'de>>(de: D) -> Result<Self, D::Error> {
150 let s = String::deserialize(de)?;
151 Self::new(s).map_err(serde::de::Error::custom)
152 }
153}
154
155/// Maximum DNS name length in text form (no trailing dot). The wire-format
156/// limit is 255 octets (RFC 1035 §3.1); a name with N labels encodes as the
157/// sum of (label-len + label) octets plus a terminating zero, so the text
158/// form is at most 253 characters.
159const MAX_DNS_NAME_LEN: usize = 253;
160
161/// Validate a zone apex. See [`AccountZone::new`] for the rules.
162fn validate_zone_apex(apex: &str) -> Result<(), AccountZoneError> {
163 let bad = |reason: &str| AccountZoneError::Invalid {
164 name: apex.to_owned(),
165 reason: reason.to_owned(),
166 };
167
168 if apex.is_empty() {
169 return Err(bad("zone name is empty"));
170 }
171 if apex != apex.trim() {
172 return Err(bad("zone name has surrounding whitespace"));
173 }
174 if apex.ends_with('.') {
175 return Err(bad("zone name must not have a trailing dot"));
176 }
177 if apex.to_ascii_lowercase() != apex {
178 return Err(bad(
179 "zone name must be lowercase (use the NFKC/ASCII-normalized form)",
180 ));
181 }
182 if apex.len() > MAX_DNS_NAME_LEN {
183 return Err(bad("zone name exceeds the 253-octet DNS text limit"));
184 }
185 // Reserve room for derived names. `host_for_label` produces
186 // `<account-label>.<apex>` and account labels are up to 63 octets (A2's
187 // grammar). The wire-format DNS name limit is 255 octets (RFC 1035),
188 // represented as up to 253 text chars. Reject an apex so long that a
189 // maximum-length label would overflow the limit, instead of producing an
190 // oversized host name later.
191 const MAX_ACCOUNT_LABEL_LEN: usize = 63;
192 let max_apex_for_hosts = MAX_DNS_NAME_LEN - 1 - MAX_ACCOUNT_LABEL_LEN; // 189
193 if apex.len() > max_apex_for_hosts {
194 return Err(bad(
195 "zone name leaves no room for a maximum-length (63-octet) account label \
196 under the 253-octet DNS text limit",
197 ));
198 }
199 if apex.starts_with('.') || apex.ends_with('.') {
200 return Err(bad("zone name has an empty label"));
201 }
202
203 let labels: Vec<&str> = apex.split('.').collect();
204 for label in &labels {
205 if label.is_empty() {
206 return Err(bad("zone name has a consecutive dot / empty label"));
207 }
208 if label.len() > 63 {
209 return Err(bad("a label exceeds 63 octets"));
210 }
211 if !label
212 .bytes()
213 .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
214 {
215 return Err(bad(
216 "labels must be LDH (lowercase letters, digits, hyphens) only",
217 ));
218 }
219 if label.starts_with('-') || label.ends_with('-') {
220 return Err(bad("labels must not start or end with a hyphen"));
221 }
222 }
223
224 // A label-count check cannot distinguish a registrable name from a
225 // multi-label public suffix (`example.co.uk` vs. `co.uk`). `psl` embeds the
226 // Mozilla Public Suffix List, so this check is deterministic and does not
227 // require network access at configuration time. Unknown/internal suffixes
228 // still follow the prevailing `*` rule and remain usable below one label.
229 if psl::domain(apex.as_bytes()).is_none() {
230 return Err(bad(
231 "zone name must include at least one registrable label below its public suffix",
232 ));
233 }
234
235 Ok(())
236}
237
238#[cfg(test)]
239#[allow(clippy::unwrap_used)]
240mod tests {
241 use super::*;
242
243 #[test]
244 fn valid_zone_normalizes_derived_names() {
245 let z = AccountZone::new("acct.example.com").unwrap();
246 assert_eq!(z.apex(), "acct.example.com");
247 assert_eq!(z.wildcard_domain(), "*.acct.example.com");
248 assert_eq!(
249 z.dns01_validation_name(),
250 "_acme-challenge.acct.example.com"
251 );
252 }
253
254 #[test]
255 fn host_label_is_single_depth() {
256 let z = AccountZone::new("acct.example.com").unwrap();
257 assert_eq!(z.host_for_label("alice").unwrap(), "alice.acct.example.com");
258 // Multi-label labels escape the wildcard — rejected.
259 let err = z.host_for_label("a.b").unwrap_err();
260 assert!(matches!(err, AccountZoneError::Invalid { .. }));
261 assert!(z.host_for_label("").is_err());
262 }
263
264 #[test]
265 fn rejects_public_suffixes_and_bad_forms() {
266 for public_suffix in ["com", "co.uk", "com.au", "ac.uk"] {
267 assert!(
268 matches!(
269 AccountZone::new(public_suffix).unwrap_err(),
270 AccountZoneError::Invalid { .. }
271 ),
272 "expected public suffix {public_suffix:?} to be rejected"
273 );
274 }
275 assert!(
276 AccountZone::new("acct.example.co.uk").is_ok(),
277 "a delegated zone below a multi-label public suffix must be accepted"
278 );
279 for bad in [
280 "",
281 "Acct.Example.com",
282 "acct..example.com",
283 "acct.example.com.",
284 "-acct.example.com",
285 &format!("{}.example.com", "a".repeat(64)),
286 ]
287 .into_iter()
288 {
289 let err = AccountZone::new(bad);
290 assert!(err.is_err(), "expected {bad:?} to be rejected, got {err:?}");
291 }
292 }
293
294 #[test]
295 fn rejects_apex_that_overflows_derived_host_names() {
296 // `host_for_label` prepends a `<label>.` (label up to 63) to the apex;
297 // RFC 1035 caps wire-format names at 255 octets (≤253 text chars). The
298 // cap leaves room: 253 - 1 - 63 = 189. Build apexes of valid (≤63-char)
299 // labels at exact total lengths.
300 let apex_190 = format!("{}.{}.{}", "a".repeat(63), "b".repeat(63), "c".repeat(62));
301 assert_eq!(apex_190.len(), 190); // 63+1+63+1+62
302 assert!(
303 AccountZone::new(&apex_190).is_err(),
304 "190-char apex must be rejected"
305 );
306
307 // An apex at the 189-char limit is accepted, and a max-length label
308 // still fits: 63 + '.' + 189 = 253.
309 let apex_189 = format!("{}.{}.{}", "a".repeat(63), "b".repeat(63), "c".repeat(61));
310 assert_eq!(apex_189.len(), 189);
311 let z = AccountZone::new(&apex_189).unwrap();
312 let label = "x".repeat(63);
313 let host = z.host_for_label(&label).unwrap();
314 assert_eq!(host.len(), 253);
315 assert_eq!(host, format!("{label}.{apex_189}"));
316 }
317
318 #[test]
319 fn serde_roundtrips() {
320 let z = AccountZone::new("acct.example.com").unwrap();
321 let json = serde_json::to_string(&z).unwrap();
322 assert_eq!(json, "\"acct.example.com\"");
323 let back: AccountZone = serde_json::from_str(&json).unwrap();
324 assert_eq!(z, back);
325 // Deserializing a bad zone fails (no silent default).
326 assert!(serde_json::from_str::<AccountZone>("\"\"").is_err());
327 }
328
329 #[test]
330 fn from_str_matches_new() {
331 let z: AccountZone = "acct.example.com".parse().unwrap();
332 assert_eq!(z.apex(), "acct.example.com");
333 }
334}