tatara_process/hostname.rs
1//! Hostname helpers — typed FQDN formatting matching `nix/lib/fleet-
2//! domains.nix`'s `mkHostname` pattern.
3//!
4//! The substrate move: every FQDN this codebase emits is computed
5//! here. Two functions ([`fmt_fqdn`] for the per-instance form +
6//! [`fmt_fqdn_stable`] for the unprefixed stable-claim form) and one
7//! deterministic ephemeral-id derivation ([`ephemeral_id_from_spec`])
8//! are the single source of truth — no string `format!()` of DNS
9//! syntax anywhere else in the tree.
10//!
11//! Forms:
12//!
13//! ```text
14//! Per-instance: ${app}.${ephemeral_id}.${cluster}.${location}.${domain}
15//! Stable: ${app}.${cluster}.${location}.${domain}
16//! ```
17//!
18//! Where `${ephemeral_id}` is:
19//!
20//! * `RoutingHostname.instance` when set — a named slot like
21//! `demo-prod` or `pr-1234`.
22//! * `EPHEMERAL_ID_HASH_LEN` (= 8) hex chars of
23//! `BLAKE3(canonical_spec_json)` when unset — a content-hash slot
24//! that changes only when the Process's spec changes.
25//!
26//! All four FQDN segments are validated as RFC 1123 DNS labels at
27//! the boundary — lowercase alphanumeric + hyphen, 1–63 chars, no
28//! leading/trailing hyphen. Validation errors surface as typed
29//! [`HostnameError`] variants so callers can render targeted
30//! operator messages.
31
32use serde::Serialize;
33
34use crate::routing::RoutingHostname;
35
36/// Number of hex chars from BLAKE3 to use as the content-hash form
37/// of `ephemeral_id`. 8 = 32 bits of entropy; collision probability
38/// at 1k concurrent Processes ≈ 1 in 8.5 million. Comfortable for
39/// any single cluster's working set, room to grow.
40pub const EPHEMERAL_ID_HASH_LEN: usize = 8;
41
42/// Reserved 2-part forms forbidden as `app` values (saguão control
43/// plane — see pleme-io CLAUDE.md §Fleet hostname pattern).
44const RESERVED_APP_LABELS: &[&str] = &["auth", "cracha"];
45
46/// Why a hostname can't be formatted. Typed so callers can branch.
47#[derive(Clone, Debug, thiserror::Error, PartialEq, Eq)]
48pub enum HostnameError {
49 #[error("invalid DNS label {label:?} for segment {segment}: {reason}")]
50 InvalidLabel {
51 segment: &'static str,
52 label: String,
53 reason: &'static str,
54 },
55 #[error("app label {0:?} is reserved for the saguão control plane")]
56 ReservedApp(String),
57}
58
59impl HostnameError {
60 /// Construct an [`HostnameError::InvalidLabel`] variant — the ONE
61 /// substrate primitive owning the three-slot
62 /// `HostnameError::InvalidLabel { segment, label: <str>.to_string(),
63 /// reason: <static> }` construction shape every RFC 1123 DNS-label
64 /// rejection site in this module walks BEFORE returning through the
65 /// `?` short-circuit.
66 ///
67 /// Pre-lift the shape was hand-authored at FOUR module-private
68 /// validation sites past the ★★ PRIME-DIRECTIVE ≥ 2 duplication
69 /// threshold, each restating the SAME three-field struct-literal
70 /// verbatim modulo the per-site `reason` slot:
71 ///
72 /// * [`validate_label`] × 3 — the length gate
73 /// (`"must be 1–63 characters"`), the leading/trailing-hyphen gate
74 /// (`"must not start or end with a hyphen"`), and the character-
75 /// set gate (`"must contain only [a-z0-9-]"`); each walked
76 /// `HostnameError::InvalidLabel { segment, label: label.to_string
77 /// (), reason: <per-gate literal> }` with the same
78 /// `segment: &'static str` slot threaded through from the caller
79 /// and the same `label.to_string()` projection on the borrowed
80 /// `&str` label slot.
81 /// * [`validate_domain`] × 1 — the empty-domain early-return
82 /// (`"must not be empty"`); same three-slot struct literal shape,
83 /// same `<str>.to_string()` projection on the borrowed `domain`
84 /// argument, sibling to the three sites in [`validate_label`] on
85 /// the RFC 1123 rejection axis.
86 ///
87 /// All four sites walked the SAME struct-literal three-slot shape
88 /// verbatim, differing only in the `reason: &'static str` slot they
89 /// bound. Post-lift each callsite reads `HostnameError::invalid_label
90 /// (segment, label, "<reason>")` and the construction shape lives at
91 /// ONE substrate owner here.
92 ///
93 /// Peer to the two-step composer [`validate_app`] on the same
94 /// hostname-validation axis, split by ABSTRACTION LEVEL:
95 /// [`validate_app`] owns the ordered check chain callers CONSUME
96 /// (RFC 1123 → reserved-name); this constructor owns the typed-
97 /// variant PRODUCTION callers of those checks EMIT. Together the
98 /// two primitives partition the module's rejection surface — the
99 /// composer says WHEN to reject, the constructor says WHAT the
100 /// rejection variant looks like on the wire.
101 ///
102 /// The `label` slot accepts `impl Into<String>` so a caller with a
103 /// borrowed `&str` label (the four pre-lift sites) reaches
104 /// `invalid_label(segment, label, reason)` without a per-site
105 /// `.to_string()` — the projection lives at the substrate. A caller
106 /// with an owned [`String`] (a future consumer stamping a
107 /// dynamically-composed label into the rejection variant) reaches
108 /// the SAME constructor without a per-site conversion either — the
109 /// `impl Into<String>` bound admits both slot shapes identically.
110 /// A future extension to the variant (a byte-offset slot into the
111 /// source label pinpointing the failing character, a
112 /// [`tracing::Span`] correlation slot, a normalization of the
113 /// label's casing at the substrate before it reaches the operator's
114 /// log stream) lands at THIS ONE constructor and every rejection
115 /// site inherits the upgrade mechanically — no per-site edit at any
116 /// of the four `validate_*` primitives, no drift risk for a fifth
117 /// future validation site that plugs into the same rejection
118 /// policy.
119 ///
120 /// Theory anchor: THEORY.md §VI.1 (generation over composition —
121 /// the three-slot struct-literal recurred at four hand-authored
122 /// sites past the ★★ PRIME-DIRECTIVE ≥ 2 duplication trigger and
123 /// lifts to ONE substrate owner here, matching the discipline
124 /// [`validate_app`] and [`validate_fqdn_suffix`] already carry on
125 /// the peer composer axes). THEORY.md §II.1 invariant 5
126 /// (composition preserves proofs — post-lift every rejection site
127 /// surfaces the byte-identical `HostnameError::InvalidLabel` variant
128 /// by CONSTRUCTION rather than by four independent struct-literal
129 /// restatements kept in sync by convention; a regression that re-
130 /// open-coded a site would surface at the pin block below rather
131 /// than as silent operator-facing skew across every downstream
132 /// rejection consumer).
133 #[inline]
134 fn invalid_label(
135 segment: &'static str,
136 label: impl Into<String>,
137 reason: &'static str,
138 ) -> Self {
139 HostnameError::InvalidLabel {
140 segment,
141 label: label.into(),
142 reason,
143 }
144 }
145}
146
147/// Substrate extension trait over `Result<T, HostnameError>` — the ONE
148/// substrate owner of the `.map_err(|e| anyhow::anyhow!("<ctx>: {e}"))`
149/// wrap-shape every reconciler consumer restated by hand at the
150/// hostname-formatter → anyhow error boundary. Peer of
151/// [`crate::kube_error::KubeResultExt`] on the wrap-shape axis; the two
152/// traits partition the flatten-wrap space by underlying error type
153/// (`kube::Error` on that peer, [`HostnameError`] on this one).
154///
155/// Pre-lift the shape was hand-authored at THREE sites in
156/// `tatara-reconciler::render::render_routing` — each of the three
157/// `HostnameError`-returning hostname primitives ([`ephemeral_id_from_spec`],
158/// [`fmt_fqdn`], [`fmt_fqdn_stable`]) had ITS consumer restate the
159/// SAME closure at the R9 routing-edge render — capture the
160/// [`HostnameError`], prepend a static context slug identifying which
161/// hostname primitive faulted, delegate the tail to [`HostnameError`]'s
162/// `Display` impl via the `{e}` slot — differing only in the context
163/// slug prefix each callsite stamped (`"ephemeral_id_from_spec"` /
164/// `"fmt_fqdn (per-instance)"` / `"fmt_fqdn_stable"`). Three
165/// hand-authored callsites past the ★★ PRIME-DIRECTIVE ≥ 2 duplication
166/// threshold.
167///
168/// Post-lift each callsite reads
169/// `<hostname-primitive>().hostname_ctx("<slug>")?` and the wrap-shape
170/// lives at ONE substrate owner here. The composed [`anyhow::Error`]'s
171/// `Display` is byte-identical to the pre-lift chain
172/// (`format!("{ctx}: {e}")`, threading the [`HostnameError`]'s own
173/// `Display` verbatim into the `{e}` slot), so operator-facing log
174/// output and any error-chain greps still match bytewise. A regression
175/// that drifts the separator, swaps the two slots, or wraps the
176/// [`HostnameError`] with a chain-form `source` (which would change
177/// `Display` output on the `err` slot) surfaces at
178/// [`tests::hostname_ctx_static_str_context_matches_pre_lift_format_bytewise`]
179/// rather than as silent operator-facing drift across the three
180/// pre-lift consumers.
181///
182/// ### Naming — `hostname_ctx`, not `anyhow::Context::context`
183///
184/// Same discipline as [`crate::kube_error::KubeResultExt::kube_ctx`] —
185/// `anyhow::Context::context` wraps the source in a chain (so `Display`
186/// emits only the context slug and callers reach the [`HostnameError`]
187/// via [`std::error::Error::source`] traversal), while this trait's
188/// `hostname_ctx` FLATTENS to a display-prefix shape (`"<ctx>: <HostnameError
189/// display>"`) — the pre-lift wire format every consumer's log output
190/// already encoded. Sharing the name would let a caller who has
191/// `anyhow::Context` in scope resolve to the WRONG method (a chain-wrap
192/// instead of the display-prefix flatten) and silently change every
193/// operator log message.
194///
195/// ### Static-slug only (no `_with` peer yet)
196///
197/// Every current callsite composes its slug at compile time
198/// (`"ephemeral_id_from_spec"`, `"fmt_fqdn (per-instance)"`,
199/// `"fmt_fqdn_stable"`); no consumer needs a `format!`-composed
200/// runtime slug. The static-`&'static str` binding keeps the substrate
201/// contract minimal — a future dynamic-slug consumer would add a
202/// `hostname_ctx_with` peer here matching the `kube_ctx_with` shape,
203/// but until then this trait exposes only the static peer.
204///
205/// ### `#[must_use]`
206///
207/// Every consumer threads the `?` short-circuit onto its handler's
208/// `Result<_, anyhow::Error>` return — dropping the wrap swallows the
209/// hostname-format failure entirely, which is never the intended
210/// semantic (a rejected DNS label at emit time silently produces a
211/// resource with a `""` FQDN slot that the K8s API server accepts and
212/// then no downstream Ingress / DNSEndpoint dispatcher can route to).
213/// The attribute surfaces that as a warning at every call site.
214///
215/// Theory anchor: THEORY.md §VI.1 (generation over composition — the
216/// [`HostnameError`] → anyhow-with-display-prefix wrap-shape recurred
217/// at three hand-authored sites past the ★★ PRIME-DIRECTIVE ≥ 2
218/// duplication trigger, and is lifted to ONE substrate owner here).
219/// THEORY.md §II.1 invariant 5 (composition preserves proofs — a
220/// regression that drifts the display-prefix separator or the byte-
221/// shape at ONE site surfaces here at the substrate pin rather than
222/// as silent operator-facing skew across every render_routing tick).
223pub trait HostnameResultExt<T>: Sized {
224 /// Wrap the [`HostnameError`] (if any) with a static context
225 /// prefix, producing an [`anyhow::Result`] whose error `Display`
226 /// reads exactly `"<context>: <HostnameError display>"`.
227 #[must_use = "an error wrap that isn't threaded via `?` swallows the hostname-format failure"]
228 fn hostname_ctx(self, context: &'static str) -> anyhow::Result<T>;
229}
230
231impl<T> HostnameResultExt<T> for Result<T, HostnameError> {
232 // Delegates the display-prefix wrap-shape body to the generic
233 // substrate owner [`crate::err_ctx::ErrCtxExt`]. Pre-lift the body
234 // restated the `.map_err(|e| anyhow::anyhow!("{context}: {e}"))`
235 // closure by hand, byte-identical to the three sibling specialized
236 // peers ([`crate::kube_error::KubeResultExt`],
237 // [`crate::anyhow_flatten::FlattenCtxExt`],
238 // [`crate::err_ctx::ErrCtxExt`] itself). Post-lift the byte-shape
239 // body lives at ONE substrate owner + this impl is a naming-layer
240 // delegate — [`HostnameError`] impls `Display` via `thiserror` so
241 // the generic [`crate::err_ctx::ErrCtxExt`] impl applies to
242 // `Result<T, HostnameError>` directly. Pinned by
243 // [`crate::err_ctx::tests::err_ctx_agrees_with_hostname_ctx_on_hostname_error_result`]
244 // so a regression that re-open-coded the body would surface there
245 // rather than as silent operator-facing skew between the
246 // hostname-side consumer (`render_routing`) and the sibling peer
247 // families.
248
249 #[inline]
250 fn hostname_ctx(self, context: &'static str) -> anyhow::Result<T> {
251 use crate::err_ctx::ErrCtxExt;
252 self.err_ctx(context)
253 }
254}
255
256/// Format the per-instance FQDN.
257///
258/// ```
259/// use tatara_process::hostname::fmt_fqdn;
260/// let fqdn = fmt_fqdn("api", "demo-prod", "pleme-dev", "use1", "quero.lol").unwrap();
261/// assert_eq!(fqdn, "api.demo-prod.pleme-dev.use1.quero.lol");
262/// ```
263pub fn fmt_fqdn(
264 app: &str,
265 ephemeral_id: &str,
266 cluster: &str,
267 location: &str,
268 domain: &str,
269) -> Result<String, HostnameError> {
270 validate_app(app)?;
271 validate_label("ephemeral_id", ephemeral_id)?;
272 validate_fqdn_suffix(cluster, location, domain)?;
273 Ok(format!(
274 "{app}.{ephemeral_id}.{cluster}.{location}.{domain}"
275 ))
276}
277
278/// Format the stable-claim FQDN (no `ephemeral_id` segment).
279///
280/// ```
281/// use tatara_process::hostname::fmt_fqdn_stable;
282/// let fqdn = fmt_fqdn_stable("api", "pleme-dev", "use1", "quero.lol").unwrap();
283/// assert_eq!(fqdn, "api.pleme-dev.use1.quero.lol");
284/// ```
285pub fn fmt_fqdn_stable(
286 app: &str,
287 cluster: &str,
288 location: &str,
289 domain: &str,
290) -> Result<String, HostnameError> {
291 validate_app(app)?;
292 validate_fqdn_suffix(cluster, location, domain)?;
293 Ok(format!("{app}.{cluster}.{location}.{domain}"))
294}
295
296/// Compute the content-hash form of `ephemeral_id` for a given
297/// `ProcessSpec`. Stable across reconciles of the same spec; new
298/// spec content ⇒ new hash ⇒ new DNS slot.
299///
300/// Uses [`EPHEMERAL_ID_HASH_LEN`] hex chars of BLAKE3 over the
301/// canonical JSON of the spec.
302pub fn ephemeral_id_from_spec<T: Serialize>(spec: &T) -> Result<String, HostnameError> {
303 // Canonical-bytes projection rides through the ONE substrate
304 // primitive [`crate::three_pillar::canonical_bytes`] — the
305 // strict, error-propagating peer of `three_pillar::pillar_bytes`
306 // that owns the 2-link `serde_json::to_value → serde_json::to_vec`
307 // canonicalization chain. Pre-lift this site read through a
308 // module-private `canonical_json` helper (removed) that restated
309 // the same 2-link chain byte-for-byte alongside the peer at
310 // `tatara-export-worker::canonical_json` — two hand-authored
311 // sites past the ★★ PRIME-DIRECTIVE ≥ 2 duplication threshold.
312 // Post-lift both consumers name the payload ONCE and route
313 // through the ONE substrate owner; the discard of the concrete
314 // `serde_json::Error` diagnostic rides through the local
315 // `HostnameError::InvalidLabel` projection at this callsite so
316 // the operator-facing wording stays byte-identical to the
317 // pre-lift shape.
318 let bytes = crate::three_pillar::canonical_bytes(spec).map_err(|_| {
319 HostnameError::invalid_label("spec", "<unserializable>", "spec failed to canonicalize")
320 })?;
321 Ok(short_hex_blake3(&bytes, EPHEMERAL_ID_HASH_LEN))
322}
323
324/// Resolve the `ephemeral_id` for a single [`RoutingHostname`]
325/// entry. Named slot wins if set; otherwise the content-hash form
326/// is computed from the surrounding `ProcessSpec` (caller passes
327/// in via `fallback_hash`).
328///
329/// The split-arg design keeps this pure — the spec hash is computed
330/// once by the caller (via [`ephemeral_id_from_spec`]) and reused
331/// across every hostname on the same Process.
332pub fn resolve_ephemeral_id<'a>(hostname: &'a RoutingHostname, fallback_hash: &'a str) -> &'a str {
333 match &hostname.instance {
334 Some(s) if !s.is_empty() => s.as_str(),
335 _ => fallback_hash,
336 }
337}
338
339// ─── Validation ────────────────────────────────────────────────────
340
341fn validate_label(segment: &'static str, label: &str) -> Result<(), HostnameError> {
342 if label.is_empty() || label.len() > 63 {
343 return Err(HostnameError::invalid_label(
344 segment,
345 label,
346 "must be 1–63 characters",
347 ));
348 }
349 if label.starts_with('-') || label.ends_with('-') {
350 return Err(HostnameError::invalid_label(
351 segment,
352 label,
353 "must not start or end with a hyphen",
354 ));
355 }
356 if !label
357 .chars()
358 .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
359 {
360 return Err(HostnameError::invalid_label(
361 segment,
362 label,
363 "must contain only [a-z0-9-]",
364 ));
365 }
366 Ok(())
367}
368
369/// Validate a caller-supplied `app` label at the fleet-hostname
370/// boundary — the ONE substrate primitive owning the two-step (RFC 1123
371/// DNS label + saguão-reservation reject) check every hostname composer
372/// runs on its `app` slot BEFORE stamping it into an emitted FQDN.
373///
374/// Pre-lift the two-step check was hand-authored at TWO adjacent public
375/// FQDN composers in this module past the ★★ PRIME-DIRECTIVE ≥ 2
376/// duplication threshold:
377///
378/// * [`fmt_fqdn`] — the per-instance form; the 4-line prelude
379/// preceded the sibling `validate_label("ephemeral_id", …)` +
380/// cluster / location / domain checks.
381/// * [`fmt_fqdn_stable`] — the unprefixed stable-claim form; the same
382/// 4-line prelude preceded the cluster / location / domain checks
383/// with no `ephemeral_id` slot in between.
384///
385/// Both restated the SAME 4-line prelude verbatim: (1)
386/// `validate_label("app", app)?` to enforce the RFC 1123 shape (1–63
387/// chars, lowercase alphanumeric + hyphen, no leading / trailing
388/// hyphen), then (2) an early-return
389/// `HostnameError::ReservedApp(app.to_string())` when the label
390/// appears in the module-private [`RESERVED_APP_LABELS`] set
391/// (currently `"auth"` / `"cracha"` — the saguão control-plane
392/// reservations declared in pleme-io CLAUDE.md § Fleet hostname
393/// pattern).
394///
395/// Post-lift each callsite reads `validate_app(app)?` and the ordered
396/// two-step check lives at ONE substrate owner. The step ORDER is
397/// load-bearing: `validate_label` runs first so a reserved label whose
398/// spelling ALSO violates RFC 1123 (an operator who typed `"AUTH"`
399/// instead of `"auth"`) surfaces as
400/// [`HostnameError::InvalidLabel`] (the underlying shape defect),
401/// not as [`HostnameError::ReservedApp`] (the higher-level policy
402/// gate) — matching the pre-lift order both composers hand-authored.
403/// A regression that swapped the two steps would silently re-classify
404/// every such input and callers pattern-matching on the two variants
405/// would branch differently.
406///
407/// A future extension to the reserved set (adding a third saguão name,
408/// a per-cluster reservation surface, a normalized-form lookup that
409/// treats `"Auth"` and `"auth"` as the same reservation) lands at THIS
410/// ONE substrate primitive and both [`fmt_fqdn`] + [`fmt_fqdn_stable`]
411/// inherit the upgrade mechanically — no per-composer edit at either
412/// call site, no drift risk for a third future FQDN-shape composer
413/// that plugs into the same reservation policy.
414///
415/// Theory anchor: THEORY.md §VI.1 (generation over composition — the
416/// 4-line two-step check recurred at two hand-authored composer
417/// preludes past the ★★ PRIME-DIRECTIVE ≥ 2 duplication trigger and
418/// lifts to ONE substrate owner here). THEORY.md §II.1 invariant 5
419/// (composition preserves proofs — the pin block below binds the
420/// primitive at fail-before-pass-after granularity so a regression
421/// that reorders the two steps, drops one, or drifts the typed error
422/// variant surfaces at THESE pins rather than as silent fleet-
423/// hostname skew across every downstream FQDN emit).
424fn validate_app(app: &str) -> Result<(), HostnameError> {
425 validate_label("app", app)?;
426 if RESERVED_APP_LABELS.contains(&app) {
427 return Err(HostnameError::ReservedApp(app.to_string()));
428 }
429 Ok(())
430}
431
432fn validate_domain(segment: &'static str, domain: &str) -> Result<(), HostnameError> {
433 if domain.is_empty() {
434 return Err(HostnameError::invalid_label(
435 segment,
436 domain,
437 "must not be empty",
438 ));
439 }
440 // Multi-label domain — every dot-separated piece must be a valid label.
441 for piece in domain.split('.') {
442 validate_label(segment, piece)?;
443 }
444 Ok(())
445}
446
447/// Validate the shared 3-segment `${cluster}.${location}.${domain}` FQDN
448/// suffix — the ONE substrate primitive owning the ordered
449/// `validate_label("cluster", …) → validate_label("location", …) →
450/// validate_domain("domain", …)` prelude every fleet-hostname composer
451/// runs on the trailing suffix common to BOTH forms
452/// (`${app}.${ephemeral_id}.<suffix>` per-instance and `${app}.<suffix>`
453/// stable) BEFORE stamping it into an emitted FQDN.
454///
455/// Pre-lift the 3-line ordered check was hand-authored at TWO adjacent
456/// public FQDN composers in this module past the ★★ PRIME-DIRECTIVE
457/// ≥ 2 duplication threshold:
458///
459/// * [`fmt_fqdn`] — the per-instance form; the 3-line suffix prelude
460/// followed the sibling `validate_app(app)?` +
461/// `validate_label("ephemeral_id", …)?` head checks and preceded the
462/// `format!("{app}.{ephemeral_id}.{cluster}.{location}.{domain}")`
463/// emission.
464/// * [`fmt_fqdn_stable`] — the unprefixed stable-claim form; the same
465/// 3-line suffix prelude followed the sibling `validate_app(app)?`
466/// check with no `ephemeral_id` slot in between and preceded the
467/// `format!("{app}.{cluster}.{location}.{domain}")` emission.
468///
469/// Both restated the SAME 3-line prelude verbatim: (1)
470/// `validate_label("cluster", cluster)?` to enforce the RFC 1123 shape
471/// on the cluster segment, then (2)
472/// `validate_label("location", location)?` for the location segment,
473/// then (3) `validate_domain("domain", domain)?` to enforce the
474/// multi-label domain shape (non-empty AND every dot-split piece a
475/// valid RFC 1123 label).
476///
477/// Post-lift each callsite reads `validate_fqdn_suffix(cluster,
478/// location, domain)?` and the ordered 3-step suffix check lives at
479/// ONE substrate owner. The step ORDER is load-bearing on the typed-
480/// variant surface: `cluster` is checked first so a bad-cluster-and-
481/// bad-location input surfaces as `InvalidLabel { segment: "cluster", .. }`
482/// (matching the pre-lift order both composers hand-authored) rather
483/// than `InvalidLabel { segment: "location", .. }` — callers pattern-
484/// matching on the `segment` slot to render targeted operator messages
485/// branch differently, so a swap of the two steps would silently
486/// re-classify every such input.
487///
488/// Peer to [`validate_app`] on the "ordered validation prelude" axis —
489/// `validate_app` owns the 2-step head check for the `app` segment,
490/// `validate_fqdn_suffix` owns the 3-step trailing suffix check for the
491/// `cluster` / `location` / `domain` segments; together they cover the
492/// full validation surface both FQDN composers walk BEFORE the terminal
493/// `format!(...)` emission.
494///
495/// A future extension to the suffix check (a per-cluster reserved-name
496/// gate mirroring [`RESERVED_APP_LABELS`], a stricter per-location DNS
497/// label check, a per-domain TLD allowlist gate, a per-fleet
498/// normalization of the cluster segment) lands at THIS ONE substrate
499/// primitive and both [`fmt_fqdn`] + [`fmt_fqdn_stable`] inherit the
500/// upgrade mechanically — no per-composer edit at either callsite, no
501/// drift risk for a third future FQDN-shape composer (a per-region
502/// gateway form, a wildcard-cert-issuer probe form) that plugs into the
503/// same suffix policy.
504///
505/// Theory anchor: THEORY.md §VI.1 (generation over composition — the
506/// 3-line three-step check recurred at two hand-authored composer
507/// preludes past the ★★ PRIME-DIRECTIVE ≥ 2 duplication trigger and
508/// lifts to ONE substrate owner here, matching the discipline
509/// [`validate_app`] already carries on the peer head-check axis).
510/// THEORY.md §II.1 invariant 5 (composition preserves proofs — the
511/// pin block below binds the primitive at fail-before-pass-after
512/// granularity so a regression that reorders the three steps, drops
513/// one, or drifts the typed `segment` slot surfaces at THESE pins
514/// rather than as silent fleet-hostname skew across every downstream
515/// FQDN emit).
516fn validate_fqdn_suffix(cluster: &str, location: &str, domain: &str) -> Result<(), HostnameError> {
517 validate_label("cluster", cluster)?;
518 validate_label("location", location)?;
519 validate_domain("domain", domain)?;
520 Ok(())
521}
522
523fn short_hex_blake3(bytes: &[u8], len: usize) -> String {
524 // Delegate the 2-link `blake3::hash → hex` step to the substrate
525 // primitive so the ephemeral-id prefix stays byte-identical to
526 // every receipt/attestation hex-digest workspace-wide; take a
527 // stable prefix of the shared full-length hex.
528 crate::hash::hex_blake3(bytes).chars().take(len).collect()
529}
530
531#[cfg(test)]
532mod tests {
533 use super::*;
534 use serde::Deserialize;
535
536 #[test]
537 fn fmt_fqdn_per_instance() {
538 let f = fmt_fqdn("api", "demo-prod", "pleme-dev", "use1", "quero.lol").unwrap();
539 assert_eq!(f, "api.demo-prod.pleme-dev.use1.quero.lol");
540 }
541
542 #[test]
543 fn fmt_fqdn_stable_form() {
544 let f = fmt_fqdn_stable("api", "pleme-dev", "use1", "quero.lol").unwrap();
545 assert_eq!(f, "api.pleme-dev.use1.quero.lol");
546 }
547
548 #[test]
549 fn fmt_fqdn_with_multilevel_domain() {
550 let f = fmt_fqdn("api", "env-a", "rio", "us", "internal.example.com").unwrap();
551 assert_eq!(f, "api.env-a.rio.us.internal.example.com");
552 }
553
554 #[test]
555 fn reserved_app_rejected() {
556 let r = fmt_fqdn("auth", "x", "y", "z", "example.com");
557 assert!(matches!(r, Err(HostnameError::ReservedApp(_))));
558 let r = fmt_fqdn_stable("cracha", "y", "z", "example.com");
559 assert!(matches!(r, Err(HostnameError::ReservedApp(_))));
560 }
561
562 #[test]
563 fn empty_label_rejected() {
564 let r = fmt_fqdn("", "x", "y", "z", "example.com");
565 assert!(matches!(
566 r,
567 Err(HostnameError::InvalidLabel { segment: "app", .. })
568 ));
569 }
570
571 #[test]
572 fn too_long_label_rejected() {
573 let long = "a".repeat(64);
574 let r = fmt_fqdn(&long, "x", "y", "z", "example.com");
575 assert!(matches!(r, Err(HostnameError::InvalidLabel { .. })));
576 }
577
578 #[test]
579 fn uppercase_label_rejected() {
580 let r = fmt_fqdn("API", "x", "y", "z", "example.com");
581 assert!(matches!(r, Err(HostnameError::InvalidLabel { .. })));
582 }
583
584 #[test]
585 fn leading_hyphen_label_rejected() {
586 let r = fmt_fqdn("api", "-bad", "y", "z", "example.com");
587 assert!(matches!(r, Err(HostnameError::InvalidLabel { .. })));
588 }
589
590 #[test]
591 fn underscore_label_rejected() {
592 let r = fmt_fqdn("api", "x_y", "z", "w", "example.com");
593 assert!(matches!(r, Err(HostnameError::InvalidLabel { .. })));
594 }
595
596 #[test]
597 fn empty_domain_rejected() {
598 let r = fmt_fqdn("api", "x", "y", "z", "");
599 assert!(matches!(r, Err(HostnameError::InvalidLabel { .. })));
600 }
601
602 // ─── Content-hash derivation ─────────────────────────────────
603
604 #[derive(Serialize, Deserialize)]
605 struct TestSpec {
606 a: u32,
607 b: String,
608 }
609
610 #[test]
611 fn ephemeral_id_is_8_hex_chars() {
612 let spec = TestSpec {
613 a: 1,
614 b: "x".into(),
615 };
616 let id = ephemeral_id_from_spec(&spec).unwrap();
617 assert_eq!(id.len(), EPHEMERAL_ID_HASH_LEN);
618 assert!(id.chars().all(|c| c.is_ascii_hexdigit()));
619 }
620
621 #[test]
622 fn ephemeral_id_is_deterministic() {
623 let s1 = TestSpec {
624 a: 1,
625 b: "x".into(),
626 };
627 let s2 = TestSpec {
628 a: 1,
629 b: "x".into(),
630 };
631 assert_eq!(
632 ephemeral_id_from_spec(&s1).unwrap(),
633 ephemeral_id_from_spec(&s2).unwrap()
634 );
635 }
636
637 #[test]
638 fn ephemeral_id_changes_with_spec() {
639 let s1 = TestSpec {
640 a: 1,
641 b: "x".into(),
642 };
643 let s2 = TestSpec {
644 a: 2,
645 b: "x".into(),
646 };
647 let s3 = TestSpec {
648 a: 1,
649 b: "y".into(),
650 };
651 let id1 = ephemeral_id_from_spec(&s1).unwrap();
652 let id2 = ephemeral_id_from_spec(&s2).unwrap();
653 let id3 = ephemeral_id_from_spec(&s3).unwrap();
654 assert_ne!(id1, id2);
655 assert_ne!(id1, id3);
656 assert_ne!(id2, id3);
657 }
658
659 #[test]
660 fn ephemeral_id_lowercase_valid_dns_label() {
661 // BLAKE3 hex is lowercase by design; the validator must
662 // accept the output as a valid DNS label.
663 let spec = TestSpec {
664 a: 42,
665 b: "anything".into(),
666 };
667 let id = ephemeral_id_from_spec(&spec).unwrap();
668 validate_label("ephemeral_id", &id).unwrap();
669 }
670
671 // ─── resolve_ephemeral_id ────────────────────────────────────
672
673 #[test]
674 fn resolve_named_slot_wins() {
675 let h = RoutingHostname::instanced("api", "demo-prod");
676 assert_eq!(resolve_ephemeral_id(&h, "fallback"), "demo-prod");
677 }
678
679 #[test]
680 fn resolve_empty_named_falls_back() {
681 let h = RoutingHostname {
682 app: "api".into(),
683 instance: Some(String::new()),
684 cluster: None,
685 };
686 assert_eq!(resolve_ephemeral_id(&h, "abc123de"), "abc123de");
687 }
688
689 #[test]
690 fn resolve_unset_named_falls_back() {
691 let h = RoutingHostname::content_hashed("api");
692 assert_eq!(resolve_ephemeral_id(&h, "abc123de"), "abc123de");
693 }
694
695 // ─── End-to-end ──────────────────────────────────────────────
696
697 // ─── HostnameResultExt::hostname_ctx substrate pins ──────────
698 //
699 // Fail-before-pass-after granularity: the `HostnameResultExt::
700 // hostname_ctx` trait method did not exist before this commit,
701 // so each test below fails to compile pre-lift. Post-lift they
702 // collectively pin the display-prefix wrap-shape at ONE substrate
703 // owner — a regression that drifts the separator, swaps the two
704 // slots, wraps the `HostnameError` with a chain-form `source`, or
705 // promotes the pass-through arm to a synthesis (an empty `Ok(())`,
706 // a mutated context slug) surfaces HERE rather than as silent
707 // operator-facing skew across the three pre-lift consumers whose
708 // log output already encoded the flat `"<ctx>: <HostnameError
709 // display>"` shape.
710
711 fn sample_err() -> HostnameError {
712 HostnameError::InvalidLabel {
713 segment: "app",
714 label: "BAD".into(),
715 reason: "must contain only [a-z0-9-]",
716 }
717 }
718
719 #[test]
720 fn hostname_ctx_static_str_context_matches_pre_lift_format_bytewise() {
721 // Byte-shape parity pin: the wrap output of `hostname_ctx
722 // ("<slug>")` MUST be `Display`-identical to the pre-lift
723 // hand-authored `.map_err(|e| anyhow!("<slug>: {e}"))` chain.
724 // A regression that inserted a separator character (`"<slug>::
725 // <hostname>"`), dropped the space after the colon, or swapped
726 // the two slots (`"<hostname>: <slug>"`) surfaces HERE rather
727 // than as silent drift at every downstream log-output consumer.
728 let raw: Result<(), HostnameError> = Err(sample_err());
729 let via_trait = raw.hostname_ctx("fmt_fqdn (per-instance)").unwrap_err();
730 let pre_lift = anyhow::anyhow!("fmt_fqdn (per-instance): {}", sample_err());
731 assert_eq!(
732 format!("{via_trait}"),
733 format!("{pre_lift}"),
734 "hostname_ctx wrap must be Display-identical to pre-lift anyhow! chain"
735 );
736 }
737
738 #[test]
739 fn hostname_ctx_ok_arm_is_a_pure_passthrough() {
740 // Ok-arm invariant: `hostname_ctx` on `Ok(t)` MUST return
741 // `Ok(t)` verbatim — no side-effect on the payload, no
742 // synthesis of a context-tagged error, no allocation. Peer to
743 // the Err-arm byte-shape pin; a regression that promoted the
744 // Ok arm to ALWAYS produce a synthesis Error would silently
745 // break every successful hostname-format call in the pre-lift
746 // consumer set.
747 let raw: Result<&'static str, HostnameError> = Ok("api.demo-prod.pleme-dev.use1.quero.lol");
748 assert_eq!(
749 raw.hostname_ctx("noop").unwrap(),
750 "api.demo-prod.pleme-dev.use1.quero.lol"
751 );
752 }
753
754 #[test]
755 fn hostname_ctx_threads_the_underlying_hostname_error_display_verbatim() {
756 // Display-tail invariant: the wrapped `anyhow::Error`'s
757 // `Display` output MUST contain the `HostnameError`'s own
758 // `Display` output verbatim as the tail past `"<ctx>: "`. A
759 // regression that inserted a normalization (uppercase, JSON
760 // encoding, truncation) between the composed `{e}` slot and
761 // the underlying thiserror-derived Display impl would surface
762 // HERE rather than as silent operator-facing skew across the
763 // three consumers whose grep patterns already encoded the
764 // canonical `HostnameError` variant wordings ("invalid DNS
765 // label ...", "app label ... is reserved").
766 let raw: Result<(), HostnameError> = Err(HostnameError::ReservedApp("auth".into()));
767 let wrapped = raw.hostname_ctx("fmt_fqdn_stable").unwrap_err();
768 let expected_tail = format!("{}", HostnameError::ReservedApp("auth".into()));
769 let expected = format!("fmt_fqdn_stable: {expected_tail}");
770 assert_eq!(format!("{wrapped}"), expected);
771 // Also assert the tail appears verbatim as a suffix — a change
772 // in the thiserror-derived Display for ReservedApp would fail
773 // both this assertion and the RECEIPT_VERSION-in-tail invariant
774 // its docstring pins.
775 assert!(
776 format!("{wrapped}").ends_with(&expected_tail),
777 "wrap must end with the HostnameError Display verbatim"
778 );
779 }
780
781 #[test]
782 fn hostname_ctx_composes_over_ephemeral_id_from_spec_call_shape() {
783 // End-to-end composition pin: the substrate trait method
784 // composes cleanly over the `ephemeral_id_from_spec` return
785 // shape at a real callsite (the `render_routing` R9 seed).
786 // A regression that specialized the trait bound to only one
787 // hostname primitive's Result shape would surface HERE.
788 #[derive(Serialize)]
789 struct NoSuchThingAsAnUnserializableStruct {
790 a: u32,
791 }
792 let v = NoSuchThingAsAnUnserializableStruct { a: 1 };
793 let composed: anyhow::Result<String> =
794 ephemeral_id_from_spec(&v).hostname_ctx("ephemeral_id_from_spec");
795 assert!(composed.is_ok());
796 assert_eq!(composed.unwrap().len(), EPHEMERAL_ID_HASH_LEN);
797 }
798
799 // ─── validate_app substrate pins ─────────────────────────────
800 //
801 // Fail-before-pass-after granularity: the `validate_app` helper
802 // did not exist pre-lift — both [`fmt_fqdn`] and [`fmt_fqdn_stable`]
803 // hand-authored the two-step (RFC 1123 label + reserved-name reject)
804 // check inline. Post-lift the two composers thread the same
805 // primitive, so the pins below pin the primitive's SHAPE + STEP
806 // ORDER + typed-variant surface at the substrate — a regression
807 // that (a) reorders the two steps, (b) drops the reserved-name
808 // gate silently, or (c) promotes the `HostnameError::ReservedApp`
809 // arm to a generic `InvalidLabel` surfaces HERE rather than as
810 // silent skew at every downstream FQDN emit.
811
812 #[test]
813 fn validate_app_accepts_valid_lowercase_alphanumeric_label() {
814 // Happy-path pin: a valid `app` label passes the two-step
815 // check with `Ok(())`. A regression that inverted the return
816 // arm (rejected everything, matched no reserved) surfaces
817 // HERE rather than as every FQDN emit refusing every input.
818 validate_app("api").unwrap();
819 validate_app("gateway").unwrap();
820 validate_app("demo-app").unwrap();
821 validate_app("a").unwrap();
822 }
823
824 #[test]
825 fn validate_app_rejects_empty_label_with_invalid_label_variant() {
826 // Step-1 delegation pin: an empty `app` MUST surface as
827 // `HostnameError::InvalidLabel { segment: "app", .. }` from
828 // the underlying `validate_label("app", app)?` call — NOT as
829 // `ReservedApp` (which would silently reclassify the shape
830 // defect as a policy rejection).
831 assert!(matches!(
832 validate_app(""),
833 Err(HostnameError::InvalidLabel { segment: "app", .. })
834 ));
835 }
836
837 #[test]
838 fn validate_app_rejects_uppercase_label_with_invalid_label_variant() {
839 // Step-1 delegation pin: casing-invalid labels reach through
840 // to `validate_label`'s [a-z0-9-] check. A regression that
841 // short-circuited the reserved-check on a case-insensitive
842 // match ("AUTH" reads as reserved without going through the
843 // RFC 1123 gate first) would surface HERE.
844 assert!(matches!(
845 validate_app("API"),
846 Err(HostnameError::InvalidLabel { segment: "app", .. })
847 ));
848 }
849
850 #[test]
851 fn validate_app_rejects_too_long_label_with_invalid_label_variant() {
852 // Step-1 delegation pin: 64-char labels violate the RFC 1123
853 // upper bound and surface at the `validate_label` gate.
854 let long = "a".repeat(64);
855 assert!(matches!(
856 validate_app(&long),
857 Err(HostnameError::InvalidLabel { segment: "app", .. })
858 ));
859 }
860
861 #[test]
862 fn validate_app_rejects_reserved_auth_label_with_reserved_app_variant() {
863 // Step-2 pin: the currently-reserved `"auth"` slot surfaces
864 // as `HostnameError::ReservedApp("auth")` — the typed
865 // control-plane rejection callers pattern-match on. A
866 // regression that dropped this variant would silently
867 // accept the reservation and let a tenant deploy under the
868 // saguão namespace.
869 assert!(matches!(
870 validate_app("auth"),
871 Err(HostnameError::ReservedApp(ref s)) if s == "auth"
872 ));
873 }
874
875 #[test]
876 fn validate_app_rejects_reserved_cracha_label_with_reserved_app_variant() {
877 // Sibling pin to the `"auth"` reservation — pins the second
878 // currently-reserved label. A regression that dropped one
879 // reservation but not the other would surface HERE.
880 assert!(matches!(
881 validate_app("cracha"),
882 Err(HostnameError::ReservedApp(ref s)) if s == "cracha"
883 ));
884 }
885
886 #[test]
887 fn validate_app_step_order_puts_rfc_1123_check_before_reserved_check() {
888 // Load-bearing order pin: `validate_label` runs FIRST so a
889 // reserved label whose spelling ALSO violates RFC 1123
890 // (uppercase, hyphen at end, etc.) surfaces as
891 // `InvalidLabel` — the underlying SHAPE defect — not as
892 // `ReservedApp` (the higher-level POLICY gate). Callers who
893 // pattern-match on the two variants branch DIFFERENTLY on
894 // shape defects vs policy rejections, so a swap of the two
895 // steps would silently re-route every uppercase-reserved
896 // input into the wrong error arm.
897 assert!(matches!(
898 validate_app("AUTH"),
899 Err(HostnameError::InvalidLabel { segment: "app", .. })
900 ));
901 assert!(matches!(
902 validate_app("Cracha"),
903 Err(HostnameError::InvalidLabel { segment: "app", .. })
904 ));
905 }
906
907 #[test]
908 fn validate_app_matches_pre_lift_two_step_chain_bytewise_across_every_variant_shape() {
909 // Byte-shape parity pin: the substrate primitive's return
910 // MUST equal the pre-lift 4-line hand-authored chain for
911 // every representative input shape. A regression that
912 // drifted the primitive's semantics away from the pre-lift
913 // composer preludes surfaces HERE rather than as silent
914 // skew at either `fmt_fqdn` / `fmt_fqdn_stable` consumer.
915 fn pre_lift(app: &str) -> Result<(), HostnameError> {
916 validate_label("app", app)?;
917 if RESERVED_APP_LABELS.contains(&app) {
918 return Err(HostnameError::ReservedApp(app.to_string()));
919 }
920 Ok(())
921 }
922 for input in [
923 // Happy path.
924 "api",
925 "gateway",
926 "demo-app",
927 "a",
928 // Step-1 rejections.
929 "",
930 "API",
931 "-bad",
932 "bad-",
933 "with_underscore",
934 // Step-2 rejections.
935 "auth",
936 "cracha",
937 // Step-1 wins over step-2 (uppercase reserved).
938 "AUTH",
939 "Cracha",
940 ] {
941 let via_primitive = validate_app(input);
942 let via_pre_lift = pre_lift(input);
943 match (via_primitive, via_pre_lift) {
944 (Ok(()), Ok(())) => {}
945 (Err(a), Err(b)) => assert_eq!(a, b, "variant mismatch for {input:?}"),
946 (a, b) => panic!("arm mismatch for {input:?}: primitive={a:?} pre_lift={b:?}"),
947 }
948 }
949 }
950
951 #[test]
952 fn validate_app_covers_every_currently_reserved_label_at_the_primitive() {
953 // Coherence sweep: iterate the RESERVED_APP_LABELS set and
954 // verify each element rejects at the substrate. A future
955 // addition to the reserved set that forgets to update the
956 // primitive would surface HERE rather than as silent
957 // acceptance at every FQDN emit.
958 for reserved in RESERVED_APP_LABELS {
959 assert!(
960 matches!(validate_app(reserved), Err(HostnameError::ReservedApp(ref s)) if s == reserved),
961 "RESERVED_APP_LABELS entry {reserved:?} must surface as ReservedApp at the substrate"
962 );
963 }
964 }
965
966 // ─── validate_fqdn_suffix substrate pins ─────────────────────
967 //
968 // Fail-before-pass-after granularity: the `validate_fqdn_suffix`
969 // helper did not exist pre-lift — both [`fmt_fqdn`] and
970 // [`fmt_fqdn_stable`] hand-authored the three-step (`validate_label
971 // ("cluster") → validate_label("location") → validate_domain
972 // ("domain")`) suffix check inline. Post-lift the two composers
973 // thread the same primitive, so the pins below pin the primitive's
974 // SHAPE + STEP ORDER + typed-`segment` slot at the substrate — a
975 // regression that (a) reorders the three steps (silently re-
976 // classifying every multi-slot rejection into the wrong `segment`
977 // arm), (b) drops one of the three checks, or (c) swaps the
978 // `validate_domain` primitive for a `validate_label` on the domain
979 // slot (silently accepting a single-label `example` in place of
980 // the multi-label `example.com` shape) surfaces HERE rather than
981 // as silent skew at every downstream FQDN emit.
982
983 #[test]
984 fn validate_fqdn_suffix_accepts_valid_three_segment_suffix() {
985 // Happy-path pin: a valid `cluster.location.domain` triple
986 // passes the three-step check with `Ok(())`. A regression that
987 // inverted the return arm (rejected everything) surfaces HERE
988 // rather than as every FQDN emit refusing every input.
989 validate_fqdn_suffix("pleme-dev", "use1", "quero.lol").unwrap();
990 validate_fqdn_suffix("prod", "eu-west-1", "example.com").unwrap();
991 validate_fqdn_suffix("a", "b", "c.d.e").unwrap();
992 }
993
994 #[test]
995 fn validate_fqdn_suffix_rejects_empty_cluster_with_cluster_segment_slot() {
996 // Step-1 delegation pin: an empty `cluster` MUST surface as
997 // `HostnameError::InvalidLabel { segment: "cluster", .. }`
998 // from the underlying `validate_label("cluster", cluster)?`
999 // call — NOT as `segment: "location"` or `segment: "domain"`
1000 // (which would silently re-classify the shape defect into a
1001 // trailing-slot rejection and route callers who pattern-match
1002 // on the `segment` slot to render targeted operator messages
1003 // to the wrong branch).
1004 assert!(matches!(
1005 validate_fqdn_suffix("", "use1", "quero.lol"),
1006 Err(HostnameError::InvalidLabel {
1007 segment: "cluster",
1008 ..
1009 })
1010 ));
1011 }
1012
1013 #[test]
1014 fn validate_fqdn_suffix_rejects_empty_location_with_location_segment_slot() {
1015 // Step-2 delegation pin — sibling to the cluster-slot pin. A
1016 // valid cluster + empty location MUST surface as `segment:
1017 // "location"` (step 2 fired), NOT as `segment: "domain"`
1018 // (which would mean step 3 short-circuited past step 2).
1019 assert!(matches!(
1020 validate_fqdn_suffix("pleme-dev", "", "quero.lol"),
1021 Err(HostnameError::InvalidLabel {
1022 segment: "location",
1023 ..
1024 })
1025 ));
1026 }
1027
1028 #[test]
1029 fn validate_fqdn_suffix_rejects_empty_domain_with_domain_segment_slot() {
1030 // Step-3 delegation pin — the terminal step. A valid cluster
1031 // + valid location + empty domain MUST surface as `segment:
1032 // "domain"` (from `validate_domain`'s empty-domain gate). A
1033 // regression that swapped `validate_domain` for
1034 // `validate_label` on the domain slot would silently accept
1035 // an empty string with a DIFFERENT `reason` slot or reject a
1036 // multi-label domain (`example.com`) that `validate_label`
1037 // alone forbids (dots).
1038 assert!(matches!(
1039 validate_fqdn_suffix("pleme-dev", "use1", ""),
1040 Err(HostnameError::InvalidLabel {
1041 segment: "domain",
1042 ..
1043 })
1044 ));
1045 }
1046
1047 #[test]
1048 fn validate_fqdn_suffix_rejects_multilabel_cluster_with_invalid_label_variant() {
1049 // Cluster-shape pin: `cluster` reaches through `validate_label`
1050 // (single-label check), NOT `validate_domain` (multi-label
1051 // check). A dot-containing cluster MUST reject at the RFC 1123
1052 // gate. A regression that widened the cluster gate to
1053 // `validate_domain` would silently accept a multi-label
1054 // cluster like `pleme.dev` (folding two segments into one
1055 // slot at emit time and drifting every downstream Ingress /
1056 // DNSEndpoint dispatcher).
1057 assert!(matches!(
1058 validate_fqdn_suffix("pleme.dev", "use1", "quero.lol"),
1059 Err(HostnameError::InvalidLabel {
1060 segment: "cluster",
1061 ..
1062 })
1063 ));
1064 }
1065
1066 #[test]
1067 fn validate_fqdn_suffix_accepts_multilabel_domain_via_validate_domain_split() {
1068 // Domain-shape pin: `domain` reaches through `validate_domain`
1069 // (multi-label check via `domain.split('.')`), NOT
1070 // `validate_label` (single-label check that would reject any
1071 // dot). A regression that narrowed the domain gate to
1072 // `validate_label` would surface HERE — every real-world
1073 // domain (`quero.lol`, `example.com`, `internal.example.com`)
1074 // contains at least one dot and would fail at the RFC 1123
1075 // single-label check.
1076 validate_fqdn_suffix("pleme-dev", "use1", "internal.example.com").unwrap();
1077 validate_fqdn_suffix("pleme-dev", "use1", "a.b.c.d.e.f").unwrap();
1078 }
1079
1080 #[test]
1081 fn validate_fqdn_suffix_step_order_puts_cluster_before_location_before_domain() {
1082 // Load-bearing order pin: the three steps fire in the SAME
1083 // order the pre-lift composer preludes hand-authored (cluster
1084 // → location → domain), so an input that violates MULTIPLE
1085 // slots surfaces at the FIRST violated slot on the ordered
1086 // walk. Callers who pattern-match on the `segment` slot to
1087 // render targeted operator messages branch differently, so a
1088 // swap of the three steps would silently re-classify every
1089 // multi-slot-invalid input.
1090 //
1091 // All three slots invalid → surfaces at `cluster` (step 1).
1092 assert!(matches!(
1093 validate_fqdn_suffix("", "", ""),
1094 Err(HostnameError::InvalidLabel {
1095 segment: "cluster",
1096 ..
1097 })
1098 ));
1099 // Valid cluster + invalid location + invalid domain → surfaces
1100 // at `location` (step 2), NOT `domain` (step 3).
1101 assert!(matches!(
1102 validate_fqdn_suffix("pleme-dev", "", ""),
1103 Err(HostnameError::InvalidLabel {
1104 segment: "location",
1105 ..
1106 })
1107 ));
1108 }
1109
1110 #[test]
1111 fn validate_fqdn_suffix_matches_pre_lift_three_step_chain_bytewise_across_every_variant_shape()
1112 {
1113 // Byte-shape parity pin: the substrate primitive's return
1114 // MUST equal the pre-lift 3-line hand-authored chain for
1115 // every representative input shape. A regression that
1116 // drifted the primitive's semantics away from the pre-lift
1117 // composer preludes surfaces HERE rather than as silent skew
1118 // at either `fmt_fqdn` / `fmt_fqdn_stable` consumer.
1119 fn pre_lift(cluster: &str, location: &str, domain: &str) -> Result<(), HostnameError> {
1120 validate_label("cluster", cluster)?;
1121 validate_label("location", location)?;
1122 validate_domain("domain", domain)?;
1123 Ok(())
1124 }
1125 for (cluster, location, domain) in [
1126 // Happy path — every corner both composers walk in
1127 // production.
1128 ("pleme-dev", "use1", "quero.lol"),
1129 ("prod", "eu-west-1", "example.com"),
1130 ("a", "b", "c.d.e"),
1131 ("cluster-1", "loc-2", "internal.example.com"),
1132 // Step-1 rejections — cluster slot fails.
1133 ("", "use1", "quero.lol"),
1134 ("BAD", "use1", "quero.lol"),
1135 ("-lead", "use1", "quero.lol"),
1136 ("with_underscore", "use1", "quero.lol"),
1137 ("pleme.dev", "use1", "quero.lol"),
1138 // Step-2 rejections — cluster ok, location fails.
1139 ("pleme-dev", "", "quero.lol"),
1140 ("pleme-dev", "USE1", "quero.lol"),
1141 ("pleme-dev", "loc_1", "quero.lol"),
1142 // Step-3 rejections — cluster + location ok, domain fails.
1143 ("pleme-dev", "use1", ""),
1144 ("pleme-dev", "use1", "-bad.com"),
1145 ("pleme-dev", "use1", "BAD.com"),
1146 // Multi-slot rejection — step 1 wins over 2 and 3.
1147 ("", "", ""),
1148 ("BAD", "USE1", ""),
1149 ] {
1150 let via_primitive = validate_fqdn_suffix(cluster, location, domain);
1151 let via_pre_lift = pre_lift(cluster, location, domain);
1152 match (via_primitive, via_pre_lift) {
1153 (Ok(()), Ok(())) => {}
1154 (Err(a), Err(b)) => assert_eq!(
1155 a, b,
1156 "variant mismatch for ({cluster:?}, {location:?}, {domain:?})"
1157 ),
1158 (a, b) => panic!(
1159 "arm mismatch for ({cluster:?}, {location:?}, {domain:?}): primitive={a:?} pre_lift={b:?}"
1160 ),
1161 }
1162 }
1163 }
1164
1165 #[test]
1166 fn fmt_fqdn_routes_suffix_slots_through_validate_fqdn_suffix_primitive() {
1167 // Delegation pin: the per-instance composer routes its
1168 // trailing suffix check through `validate_fqdn_suffix`, NOT
1169 // through a re-open-coded restatement of the three-step
1170 // chain. A regression that re-inlined the pre-lift check at
1171 // the composer prelude would reintroduce the duplication the
1172 // lift removed; this pin catches it by asserting the composer
1173 // surfaces the SAME typed `segment` slot the primitive would
1174 // for a representative rejection in each of the three suffix
1175 // slots (cluster, location, domain).
1176 assert!(matches!(
1177 fmt_fqdn("api", "x", "BAD", "use1", "quero.lol"),
1178 Err(HostnameError::InvalidLabel {
1179 segment: "cluster",
1180 ..
1181 })
1182 ));
1183 assert!(matches!(
1184 fmt_fqdn("api", "x", "pleme-dev", "", "quero.lol"),
1185 Err(HostnameError::InvalidLabel {
1186 segment: "location",
1187 ..
1188 })
1189 ));
1190 assert!(matches!(
1191 fmt_fqdn("api", "x", "pleme-dev", "use1", ""),
1192 Err(HostnameError::InvalidLabel {
1193 segment: "domain",
1194 ..
1195 })
1196 ));
1197 }
1198
1199 #[test]
1200 fn fmt_fqdn_stable_routes_suffix_slots_through_validate_fqdn_suffix_primitive() {
1201 // Sibling delegation pin — same shape as the per-instance pin
1202 // above but for the stable-claim composer. Both composers now
1203 // share the primitive; a regression that re-inlined the chain
1204 // at either site surfaces at ONE of the two pins rather than
1205 // at every downstream FQDN emit.
1206 assert!(matches!(
1207 fmt_fqdn_stable("api", "BAD", "use1", "quero.lol"),
1208 Err(HostnameError::InvalidLabel {
1209 segment: "cluster",
1210 ..
1211 })
1212 ));
1213 assert!(matches!(
1214 fmt_fqdn_stable("api", "pleme-dev", "", "quero.lol"),
1215 Err(HostnameError::InvalidLabel {
1216 segment: "location",
1217 ..
1218 })
1219 ));
1220 assert!(matches!(
1221 fmt_fqdn_stable("api", "pleme-dev", "use1", ""),
1222 Err(HostnameError::InvalidLabel {
1223 segment: "domain",
1224 ..
1225 })
1226 ));
1227 }
1228
1229 #[test]
1230 fn fmt_fqdn_and_fmt_fqdn_stable_agree_on_suffix_rejection_bytewise() {
1231 // Cross-composer coherence pin: post-lift both composers route
1232 // their suffix check through the ONE substrate primitive, so
1233 // the SAME suffix-slot violation surfaces byte-identically at
1234 // BOTH composers (differing only in the `ephemeral_id` arg
1235 // presence). A regression that re-inlined the chain at one
1236 // composer but not the other would silently drift the two
1237 // consumers' typed-`segment` slot; this pin binds them to the
1238 // ONE substrate primitive so any such drift surfaces HERE.
1239 for (cluster, location, domain, expected_segment) in [
1240 ("BAD", "use1", "quero.lol", "cluster"),
1241 ("pleme-dev", "", "quero.lol", "location"),
1242 ("pleme-dev", "use1", "", "domain"),
1243 ("pleme.dev", "use1", "quero.lol", "cluster"),
1244 ] {
1245 let via_per_instance = fmt_fqdn("api", "x", cluster, location, domain);
1246 let via_stable = fmt_fqdn_stable("api", cluster, location, domain);
1247 assert!(
1248 matches!(
1249 &via_per_instance,
1250 Err(HostnameError::InvalidLabel { segment, .. }) if *segment == expected_segment
1251 ),
1252 "fmt_fqdn must surface segment={expected_segment:?} for ({cluster:?}, {location:?}, {domain:?}); got {via_per_instance:?}"
1253 );
1254 assert!(
1255 matches!(
1256 &via_stable,
1257 Err(HostnameError::InvalidLabel { segment, .. }) if *segment == expected_segment
1258 ),
1259 "fmt_fqdn_stable must surface segment={expected_segment:?} for ({cluster:?}, {location:?}, {domain:?}); got {via_stable:?}"
1260 );
1261 // And the two composers' error variants agree bytewise on
1262 // the suffix rejection — they should, since both route
1263 // through the SAME primitive.
1264 match (via_per_instance, via_stable) {
1265 (Err(a), Err(b)) => assert_eq!(
1266 a, b,
1267 "fmt_fqdn and fmt_fqdn_stable must agree on suffix rejection for ({cluster:?}, {location:?}, {domain:?})"
1268 ),
1269 pair => panic!(
1270 "expected both composers to reject ({cluster:?}, {location:?}, {domain:?}) with the SAME variant; got {pair:?}"
1271 ),
1272 }
1273 }
1274 }
1275
1276 #[test]
1277 fn fmt_fqdn_routes_app_slot_through_validate_app_primitive() {
1278 // Delegation pin: the per-instance composer routes its `app`
1279 // slot check through `validate_app`, NOT through a re-open-
1280 // coded restatement of the two-step chain. A regression that
1281 // inlined the pre-lift check at the composer prelude would
1282 // reintroduce the duplication the lift removed; this pin
1283 // catches it by asserting the composer surfaces the SAME
1284 // typed error the primitive would for a representative
1285 // input in each of the two rejection arms.
1286 assert!(matches!(
1287 fmt_fqdn("AUTH", "x", "y", "z", "example.com"),
1288 Err(HostnameError::InvalidLabel { segment: "app", .. })
1289 ));
1290 assert!(matches!(
1291 fmt_fqdn("auth", "x", "y", "z", "example.com"),
1292 Err(HostnameError::ReservedApp(ref s)) if s == "auth"
1293 ));
1294 }
1295
1296 #[test]
1297 fn fmt_fqdn_stable_routes_app_slot_through_validate_app_primitive() {
1298 // Sibling delegation pin — same shape as the per-instance
1299 // pin above but for the stable-claim composer. Both
1300 // composers now share the primitive; a regression that
1301 // re-inlined the chain at either site surfaces at ONE of
1302 // the two pins rather than at every downstream FQDN emit.
1303 assert!(matches!(
1304 fmt_fqdn_stable("Cracha", "y", "z", "example.com"),
1305 Err(HostnameError::InvalidLabel { segment: "app", .. })
1306 ));
1307 assert!(matches!(
1308 fmt_fqdn_stable("cracha", "y", "z", "example.com"),
1309 Err(HostnameError::ReservedApp(ref s)) if s == "cracha"
1310 ));
1311 }
1312
1313 #[test]
1314 fn end_to_end_named_and_unnamed_for_same_process() {
1315 let spec = TestSpec {
1316 a: 1,
1317 b: "x".into(),
1318 };
1319 let hash = ephemeral_id_from_spec(&spec).unwrap();
1320
1321 let h_named = RoutingHostname::instanced("api", "demo-prod");
1322 let h_anon = RoutingHostname::content_hashed("gateway");
1323
1324 let id_named = resolve_ephemeral_id(&h_named, &hash);
1325 let id_anon = resolve_ephemeral_id(&h_anon, &hash);
1326
1327 let fqdn_named =
1328 fmt_fqdn(&h_named.app, id_named, "pleme-dev", "use1", "quero.lol").unwrap();
1329 let fqdn_anon = fmt_fqdn(&h_anon.app, id_anon, "pleme-dev", "use1", "quero.lol").unwrap();
1330
1331 assert_eq!(fqdn_named, "api.demo-prod.pleme-dev.use1.quero.lol");
1332 assert!(fqdn_anon.starts_with("gateway."));
1333 assert!(fqdn_anon.ends_with(".pleme-dev.use1.quero.lol"));
1334 // 5 named segments (app + eph_id + cluster + location + domain),
1335 // but `domain` itself splits as `quero.lol` ⇒ 6 dot-delimited
1336 // pieces. The shape, not the count, is the invariant.
1337 assert_eq!(fqdn_anon.matches('.').count(), 5);
1338 }
1339
1340 // ─── HostnameError::invalid_label substrate pins ─────────────
1341 //
1342 // Fail-before-pass-after granularity: the `HostnameError::
1343 // invalid_label` constructor did not exist pre-lift — the four
1344 // `validate_*` rejection sites hand-authored the three-slot
1345 // `HostnameError::InvalidLabel { segment, label: <str>.to_string
1346 // (), reason: <static> }` struct literal inline. Post-lift the
1347 // four rejection sites thread the same constructor, so the pins
1348 // below pin the constructor's SHAPE + typed-variant surface +
1349 // slot-projection discipline at the substrate — a regression that
1350 // (a) drifts the `label.into()` projection at the substrate (e.g.
1351 // narrows the `impl Into<String>` bound to `&str`, ruling out a
1352 // future consumer stamping a dynamically-composed label), (b)
1353 // promotes the constructor to a different `HostnameError` variant
1354 // (a `ReservedApp` misfire) silently, or (c) swaps two of the
1355 // three slots at the substrate (e.g. binds `reason` in the
1356 // `segment` slot) surfaces HERE rather than as silent skew across
1357 // every downstream FQDN emit whose rejection pattern-matches on
1358 // the typed variant.
1359
1360 #[test]
1361 fn invalid_label_constructor_produces_invalid_label_variant_with_all_three_slots_bound() {
1362 // Byte-shape parity pin: the constructor's return MUST equal
1363 // the pre-lift hand-authored `HostnameError::InvalidLabel {
1364 // segment, label: label.to_string(), reason }` struct literal
1365 // for every slot. A regression that swapped two slots (e.g.
1366 // bound the reason-string into the segment slot) would
1367 // surface HERE rather than as silent operator-facing skew
1368 // across the four `validate_*` rejection sites whose log
1369 // output already encoded the flat "invalid DNS label
1370 // <label:?> for segment <segment>: <reason>" shape.
1371 let via_constructor =
1372 HostnameError::invalid_label("app", "BAD", "must contain only [a-z0-9-]");
1373 let via_pre_lift = HostnameError::InvalidLabel {
1374 segment: "app",
1375 label: "BAD".to_string(),
1376 reason: "must contain only [a-z0-9-]",
1377 };
1378 assert_eq!(via_constructor, via_pre_lift);
1379 }
1380
1381 #[test]
1382 fn invalid_label_constructor_accepts_borrowed_str_label_via_into_string() {
1383 // Borrowed-slot invariant: the `label` slot must accept the
1384 // borrowed `&str` shape (via `String::from`), matching the
1385 // four pre-lift rejection sites whose `label` parameter is a
1386 // borrowed `&str`. A regression that narrowed the bound to
1387 // owned `String` only would reject the four production
1388 // callsites at rustc time; a regression that narrowed it to
1389 // `&'static str` would reject dynamically-composed labels.
1390 let borrowed: &str = "dynamic-label";
1391 let err = HostnameError::invalid_label("app", borrowed, "must be 1–63 characters");
1392 match err {
1393 HostnameError::InvalidLabel {
1394 segment,
1395 label,
1396 reason,
1397 } => {
1398 assert_eq!(segment, "app");
1399 assert_eq!(label, "dynamic-label");
1400 assert_eq!(reason, "must be 1–63 characters");
1401 }
1402 other => panic!("expected InvalidLabel, got {other:?}"),
1403 }
1404 }
1405
1406 #[test]
1407 fn invalid_label_constructor_accepts_owned_string_label_via_into_string() {
1408 // Owned-slot peer of the borrowed-slot pin above — the
1409 // `impl Into<String>` bound must admit an owned [`String`]
1410 // (identity `Into` impl) verbatim. A future consumer that
1411 // composes the label dynamically (via `format!`, from another
1412 // typed source) reaches the SAME constructor without a
1413 // per-callsite borrow detour. A regression that narrowed
1414 // either arm silently would surface HERE.
1415 let owned: String = "owned-label".to_string();
1416 let err = HostnameError::invalid_label("cluster", owned, "must not be empty");
1417 match err {
1418 HostnameError::InvalidLabel {
1419 segment,
1420 label,
1421 reason,
1422 } => {
1423 assert_eq!(segment, "cluster");
1424 assert_eq!(label, "owned-label");
1425 assert_eq!(reason, "must not be empty");
1426 }
1427 other => panic!("expected InvalidLabel, got {other:?}"),
1428 }
1429 }
1430
1431 #[test]
1432 fn invalid_label_constructor_display_matches_thiserror_derived_shape_bytewise() {
1433 // Display-shape invariant: the constructor's produced variant
1434 // MUST render bytewise-identically to the pre-lift
1435 // thiserror-derived Display output — the shape every
1436 // reconciler consumer's log stream and every operator's grep
1437 // pattern already encodes. A regression that added a slot to
1438 // the variant without updating the `#[error]` attribute (or
1439 // vice versa) would surface as a Display drift here, upstream
1440 // of every downstream log consumer.
1441 let via_constructor =
1442 HostnameError::invalid_label("location", "USE1", "must contain only [a-z0-9-]");
1443 assert_eq!(
1444 format!("{via_constructor}"),
1445 "invalid DNS label \"USE1\" for segment location: must contain only [a-z0-9-]",
1446 );
1447 }
1448
1449 #[test]
1450 fn validate_label_length_gate_routes_through_invalid_label_constructor_bytewise() {
1451 // Delegation pin — the length gate at [`validate_label`] MUST
1452 // surface the byte-identical `HostnameError::InvalidLabel`
1453 // variant the constructor produces for the same
1454 // (segment, label, "must be 1–63 characters") triple. A
1455 // regression that re-inlined the pre-lift struct literal at
1456 // the length gate — dropping the delegation and re-open-
1457 // coding the three slots — would reintroduce the duplication
1458 // this lift removed; this pin catches it by asserting the
1459 // rejection site's error equals the constructor's error
1460 // bytewise across two representative shapes (an empty label
1461 // and a 64-char label past the 63-char upper bound).
1462 let long = "a".repeat(64);
1463 for label in ["", long.as_str()] {
1464 let via_validate = validate_label("app", label).unwrap_err();
1465 let via_constructor =
1466 HostnameError::invalid_label("app", label, "must be 1–63 characters");
1467 assert_eq!(
1468 via_validate, via_constructor,
1469 "validate_label length gate must delegate to invalid_label constructor for label {label:?}"
1470 );
1471 }
1472 }
1473
1474 #[test]
1475 fn validate_label_hyphen_gate_routes_through_invalid_label_constructor_bytewise() {
1476 // Sibling delegation pin — the leading/trailing-hyphen gate
1477 // at [`validate_label`] MUST surface the byte-identical
1478 // variant the constructor produces for the same triple.
1479 // Sibling to the length-gate pin above; three representative
1480 // shapes (leading hyphen, trailing hyphen, both).
1481 for label in ["-lead", "trail-", "-both-"] {
1482 let via_validate = validate_label("cluster", label).unwrap_err();
1483 let via_constructor = HostnameError::invalid_label(
1484 "cluster",
1485 label,
1486 "must not start or end with a hyphen",
1487 );
1488 assert_eq!(
1489 via_validate, via_constructor,
1490 "validate_label hyphen gate must delegate to invalid_label constructor for label {label:?}"
1491 );
1492 }
1493 }
1494
1495 #[test]
1496 fn validate_label_charset_gate_routes_through_invalid_label_constructor_bytewise() {
1497 // Sibling delegation pin — the character-set gate at
1498 // [`validate_label`] MUST surface the byte-identical variant
1499 // the constructor produces for the same triple. Sibling to
1500 // the length + hyphen pins above; three representative shapes
1501 // (uppercase, underscore, non-ASCII).
1502 for label in ["BAD", "with_underscore", "café"] {
1503 let via_validate = validate_label("location", label).unwrap_err();
1504 let via_constructor =
1505 HostnameError::invalid_label("location", label, "must contain only [a-z0-9-]");
1506 assert_eq!(
1507 via_validate, via_constructor,
1508 "validate_label charset gate must delegate to invalid_label constructor for label {label:?}"
1509 );
1510 }
1511 }
1512
1513 #[test]
1514 fn validate_domain_empty_gate_routes_through_invalid_label_constructor_bytewise() {
1515 // Sibling delegation pin — the empty-domain early-return at
1516 // [`validate_domain`] MUST surface the byte-identical variant
1517 // the constructor produces for `("<segment>", "", "must not
1518 // be empty")`. Sibling to the three [`validate_label`] gate
1519 // pins above; the fourth pre-lift rejection site closes the
1520 // sweep. A regression that re-inlined the empty-domain struct
1521 // literal would surface HERE and NOT at any of the three
1522 // sibling `validate_label` pins (each covers a different
1523 // gate), so the four pins together bind each pre-lift
1524 // rejection site to the ONE substrate constructor.
1525 let via_validate = validate_domain("domain", "").unwrap_err();
1526 let via_constructor = HostnameError::invalid_label("domain", "", "must not be empty");
1527 assert_eq!(via_validate, via_constructor);
1528 }
1529}