yah-cloud 0.8.29

Declarative cloud substrate for yah-managed camps: .yah/cloud/ config schema, MachineProvider drivers (Hetzner + local containerd), cloud-init rendering, and the pond/mesofact reconcilers.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
//! Domain-level reconciler — `.yah/domains/*.toml` → live Cloudflare state.
//!
//! Today's only shape is the **R2 custom-domain** binding: a domain that
//! declares `front_door = "bucket-direct"` (R594-F12) and names an R2 bucket
//! in `cdn_bucket`. Cloudflare's R2 Custom Domains API binds the hostname to
//! the bucket and writes the CNAME into the parent zone automatically when
//! the zone lives on the same account — no DNS-side call is needed here.
//!
//! Domains with `front_door = "worker"` (e.g. `yah-dev.toml`,
//! `app-yah-dev.toml`) are out of scope for this shape; they get DNS + route
//! management through the Worker reconciler below. `front_door = "passway"`
//! is the sovereign-ingress path (W267) and has no reconciler here yet.
//!
//! Before R594-F12 the shape was *inferred* from the absence of `[[routes]]`,
//! which meant a route-carrying manifest bound straight to R2 was accepted
//! and silently skipped by this pass. The discriminator is now declared and
//! validated at load.

use std::path::Path;

use anyhow::{Context, Result};
use tracing::{debug, info};

use crate::CloudflareClient;

/// Bind `domain` as a custom domain on `bucket_name`. Idempotent — does
/// nothing when the binding is already present, regardless of `enabled`
/// state (CF reflects newly-added bindings as `enabled: true` immediately;
/// disabling is an explicit dashboard action we don't undo here).
///
/// Resolves account_id + the Cloudflare API token from the named provider
/// (`.yah/infra/providers/<provider_id>.toml`, see
/// [`super::cf_creds::CfProvider`]). Mirrors the list-first pattern of
/// `static_asset::ensure_r2_bucket` so the apply loop is safe to re-run.
///
/// Required token scopes: `Workers R2 Storage: Edit` and `Zone: Read`
/// (the latter because the API requires the zone id of the parent zone —
/// CF writes the CNAME there). The caller does NOT need `DNS: Edit`; CF
/// provisions the record itself when the binding is created.
pub async fn ensure_r2_custom_domain(
    workspace_root: &Path,
    provider_id: &str,
    bucket_name: &str,
    domain: &str,
) -> Result<()> {
    let cf_provider = super::cf_creds::CfProvider::resolve(workspace_root, provider_id)?;
    let account_id = cf_provider.account_id.clone();
    let cf = CloudflareClient::new(cf_provider.api_token()?);
    let existing = cf
        .list_r2_custom_domains(&account_id, bucket_name)
        .await
        .with_context(|| format!("listing R2 custom domains on bucket {bucket_name:?}"))?;
    if existing.iter().any(|d| d.domain == domain) {
        debug!(
            domain,
            bucket_name, "R2 custom domain already bound — skipping"
        );
        return Ok(());
    }
    let zone_name = parent_zone_name(domain);
    let zone_id = cf
        .zone_id_for_name(zone_name)
        .await
        .with_context(|| format!("resolving zone id for {zone_name:?}"))?;
    cf.add_r2_custom_domain(&account_id, bucket_name, domain, &zone_id)
        .await
        .with_context(|| format!("binding R2 custom domain {domain:?} → bucket {bucket_name:?}"))?;
    info!(domain, bucket_name, zone_name, "R2 custom domain bound");
    Ok(())
}

/// Heuristic: the parent CF zone of `domain` is its last two labels.
///
/// `cdn.yah.dev` → `yah.dev`; `yah.dev` → `yah.dev` (already apex). This is
/// correct for every yah-owned zone today (all are two-label apexes). If a
/// future workspace registers a three-label zone (e.g. `staging.yah.dev`
/// as its own CF zone) and binds a subdomain under it, this will resolve
/// to the wrong zone — swap in a longest-suffix match against
/// `list_zones()` when that day arrives.
fn parent_zone_name(domain: &str) -> &str {
    let last_dot = domain.rfind('.');
    let Some(last_dot) = last_dot else {
        return domain; // single-label — let CF surface the bad input
    };
    if let Some(prev_dot) = domain[..last_dot].rfind('.') {
        &domain[prev_dot + 1..]
    } else {
        domain // already a two-label apex
    }
}

// ─── R561-F3: domain-manifest-driven static Worker ──────────────────────────
//
// A per-tenant alias-tier manifest (e.g. scrabcake.net.yah.dev) carries a
// `static` route → `<service>/<component>`. Serving it means deploying the
// shared router bundle (`WORKER_SCRIPT`) configured to fetch the tenant's
// assets from its R2 prefix, then binding the subdomain to that Worker via the
// Workers Custom Domains API. This is the routed-domain shape the apply loop
// currently Skips.

use crate::config::{DomainConfig, DomainRoute, FrontDoor, RouteMode};
use crate::provider::cloudflare::WorkerBinding;
use crate::reconciler::mesofact_static::WORKER_SCRIPT;
use std::collections::BTreeMap;

/// The plan for deploying one subdomain's static Worker — everything decided
/// before any Cloudflare call. Pure output of [`plan_domain_worker`], so the
/// decision logic is unit-testable offline; [`deploy_domain_worker`] performs
/// the I/O.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DomainWorkerPlan {
    /// Worker script name (the domain manifest's file stem / `name`).
    pub worker_name: String,
    /// Hostname to bind via Workers Custom Domains, e.g. `scrabcake.net.yah.dev`.
    pub custom_domain: String,
    /// `ASSET_ORIGIN` the Worker fetches from: `<cdn_base>/<service>/<env>`.
    pub asset_origin: String,
    /// `plain_text` Worker bindings (mirrors the Static-mode shape of
    /// mesofact_static's `worker_config_bindings`).
    pub bindings: Vec<(String, String)>,
}

/// Static-mode Worker bindings for an alias-tier subdomain. Kept in lockstep
/// with `mesofact_static::worker_config_bindings(WorkerMode::Static, …)`.
///
/// `route_headers` is the manifest's own `DomainConfig::route_headers_json` —
/// this planner already holds the domain, so unlike the mirror-driven path it
/// needs no lookup to find it (R746).
fn static_worker_bindings(asset_origin: &str, route_headers: String) -> Vec<(String, String)> {
    vec![
        ("ASSET_ORIGIN".to_string(), asset_origin.to_string()),
        ("UPLOAD_ORIGIN".to_string(), String::new()),
        ("WORKER_MODE".to_string(), "static".to_string()),
        ("SSR_ORIGIN".to_string(), String::new()),
        ("SSR_PREFIXES".to_string(), "[]".to_string()),
        ("ROUTE_HEADERS".to_string(), route_headers),
    ]
}

/// Build the [`DomainWorkerPlan`] for a per-tenant alias-tier manifest.
///
/// `cdn_base` is the tier's CDN origin (an R2 custom domain bound to the
/// tier bucket, e.g. `https://cdn.net.yah.dev`); `env` is the mirror env the
/// publisher wrote under (e.g. `cloud`). The publisher lays assets down at
/// `<bucket>/<service>/<env>/<key>` and the Worker fetches
/// `${ASSET_ORIGIN}/<key>`, so `ASSET_ORIGIN = <cdn_base>/<service>/<env>`.
///
/// Fails fast (before any network call) when the manifest has no `static`
/// route or its component ref is malformed.
pub fn plan_domain_worker(
    domain: &DomainConfig,
    cdn_base: &str,
    env: &str,
) -> Result<DomainWorkerPlan> {
    // R594-F12: refuse to synthesize a Worker for a domain that declared a
    // different front door. Without this the plan succeeds and deploys a
    // Worker that never receives traffic (bucket-direct) or that duplicates
    // the sovereign ingress (passway).
    if domain.front_door != FrontDoor::Worker {
        anyhow::bail!(
            "domain {} ({}) declares front_door = \"{}\" — only \"worker\" \
             domains get a generated Cloudflare Worker",
            domain.name,
            domain.domain,
            domain.front_door.as_str()
        );
    }

    // First static route wins (v1 alias tier serves one site per subdomain).
    let component = domain
        .routes
        .iter()
        .find_map(|r| match &r.mode {
            RouteMode::Static { component } => Some(component.as_str()),
            _ => None,
        })
        .with_context(|| {
            format!(
                "domain {} ({}) has no `static` route — nothing for a static Worker to serve",
                domain.name, domain.domain
            )
        })?;

    let service = component
        .split_once('/')
        .map(|(svc, _)| svc)
        .with_context(|| {
            format!(
                "domain {}: route component {component:?} — expected \"<service>/<component-id>\"",
                domain.name
            )
        })?;

    let asset_origin = format!("{}/{}/{}", cdn_base.trim_end_matches('/'), service, env);

    Ok(DomainWorkerPlan {
        worker_name: domain.name.clone(),
        custom_domain: domain.domain.clone(),
        bindings: static_worker_bindings(&asset_origin, domain.route_headers_json()),
        asset_origin,
    })
}

/// Deploy the planned Worker and bind the subdomain (R561-F3, live I/O).
///
/// Reuses the shared `WORKER_SCRIPT` bundle + the existing CloudflareClient
/// deploy/custom-domain methods. Gated on `cloudflare-api-token`. The decision
/// logic is covered by `plan_domain_worker`'s tests; this I/O path has NOT been
/// exercised against a live account yet (no creds in CI) — treat as untested
/// until a live `yah cloud apply` confirms it.
///
/// CAVEAT (zone resolution): `parent_zone_name` uses a two-label heuristic, so
/// for `scrabcake.net.yah.dev` it returns `yah.dev`. But the alias tiers
/// `net.yah.dev` / `com.yah.dev` are their own Cloudflare zones — the binding
/// must target `net.yah.dev`, not `yah.dev`. Before this goes live, swap in a
/// longest-suffix match against the account's zones (the upgrade path
/// `parent_zone_name`'s doc already names). Tracked on R561-F3.
pub async fn deploy_domain_worker(
    workspace_root: &Path,
    provider_id: &str,
    plan: &DomainWorkerPlan,
) -> Result<()> {
    let cf_provider = super::cf_creds::CfProvider::resolve(workspace_root, provider_id)?;
    let account_id = cf_provider.account_id.clone();
    let cf = CloudflareClient::new(cf_provider.api_token()?);

    let worker_bindings: Vec<WorkerBinding<'_>> = plan
        .bindings
        .iter()
        .map(|(k, v)| WorkerBinding::PlainText {
            name: k.as_str(),
            text: v.as_str(),
        })
        .collect();

    cf.deploy_worker_script(
        &account_id,
        &plan.worker_name,
        WORKER_SCRIPT,
        &worker_bindings,
    )
    .await
    .with_context(|| format!("deploying static Worker {}", plan.worker_name))?;
    info!(worker = %plan.worker_name, "alias-tier Worker deployed");

    let zone = parent_zone_name(&plan.custom_domain);
    let zone_id = cf
        .zone_id_for_name(zone)
        .await
        .with_context(|| format!("resolving zone id for {zone:?}"))?;
    cf.upsert_worker_custom_domain(
        &account_id,
        &zone_id,
        &plan.custom_domain,
        &plan.worker_name,
    )
    .await
    .with_context(|| {
        format!(
            "binding {} to Worker {}",
            plan.custom_domain, plan.worker_name
        )
    })?;
    info!(domain = %plan.custom_domain, worker = %plan.worker_name, "alias-tier custom domain bound");
    Ok(())
}

// ─── R561-F4: alias-tier registration ───────────────────────────────────────
//
// "Claim <name>.{com,net}.yah.dev": validate the label, check it's free, and
// produce the per-tenant DomainConfig (the F2 manifest) the registration flow
// writes. Pure + offline — the SaaS "sign up, get a subdomain" moment.

/// The two wildcard alias tiers. `Com` = managed/commercial, `Net` = community.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AliasTier {
    Com,
    Net,
}

impl AliasTier {
    /// The tier's Cloudflare zone, e.g. `net.yah.dev`.
    pub fn zone(self) -> &'static str {
        match self {
            AliasTier::Com => "com.yah.dev",
            AliasTier::Net => "net.yah.dev",
        }
    }

    /// The tier's shared R2 bucket (per-tenant `<svc>/<env>` prefixes within).
    pub fn bucket(self) -> &'static str {
        match self {
            AliasTier::Com => "com-yah-dev",
            AliasTier::Net => "net-yah-dev",
        }
    }

    /// Manifest-name infix, e.g. `net` → `<name>-net-yah-dev` file stem.
    fn slug(self) -> &'static str {
        match self {
            AliasTier::Com => "com",
            AliasTier::Net => "net",
        }
    }
}

/// A valid DNS label: 1–63 chars, lowercase alphanumeric or hyphen, no
/// leading/trailing hyphen. (Subdomain names a tenant can claim.)
pub fn valid_subdomain_label(name: &str) -> bool {
    !name.is_empty()
        && name.len() <= 63
        && !name.starts_with('-')
        && !name.ends_with('-')
        && name
            .bytes()
            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
}

/// Validate and build the per-tenant alias manifest for a claim.
///
/// `name` is the requested subdomain label (e.g. `scrabcake`); `component` is
/// the tenant's static component ref (`"<service>/<component-id>"`). `existing`
/// is the current domain map (from `CloudConfig`) — the claim fails if the
/// resulting host or manifest name is already taken. Returns the
/// [`DomainConfig`] to write at `.yah/domains/<stem>.toml`.
pub fn plan_alias_claim(
    tier: AliasTier,
    name: &str,
    component: &str,
    existing: &BTreeMap<String, DomainConfig>,
) -> Result<DomainConfig> {
    if !valid_subdomain_label(name) {
        anyhow::bail!(
            "invalid subdomain {name:?} — must be 1–63 chars, lowercase \
             alphanumeric or hyphen, no leading/trailing hyphen"
        );
    }
    if component.split_once('/').is_none() {
        anyhow::bail!("component {component:?} — expected \"<service>/<component-id>\"");
    }

    let domain = format!("{name}.{}", tier.zone());
    let stem = format!("{name}-{}-yah-dev", tier.slug());

    if existing.values().any(|d| d.domain == domain) {
        anyhow::bail!("{domain} is already claimed");
    }
    if existing.contains_key(&stem) {
        anyhow::bail!("domain manifest {stem:?} already exists");
    }

    Ok(DomainConfig {
        schema_version: 1,
        name: stem,
        domain,
        // R594-F12: every tenant manifest is Worker-served (R561-F3 binds the
        // subdomain as a custom domain on the generated Worker).
        front_door: FrontDoor::Worker,
        cdn_bucket: tier.bucket().to_string(),
        worker_bundle_path: None,
        routes: vec![DomainRoute {
            path: "/*".into(),
            // A claimed alias serves one bundle at the root with no special
            // header needs; a tenant that wants some edits its own manifest.
            headers: BTreeMap::new(),
            mode: RouteMode::Static {
                component: component.to_string(),
            },
        }],
    })
}

#[cfg(test)]
mod tests {
    use super::parent_zone_name;

    #[test]
    fn parent_zone_strips_one_label_off_subdomain() {
        assert_eq!(parent_zone_name("cdn.yah.dev"), "yah.dev");
        assert_eq!(parent_zone_name("app.yah.dev"), "yah.dev");
    }

    #[test]
    fn parent_zone_returns_self_for_apex() {
        assert_eq!(parent_zone_name("yah.dev"), "yah.dev");
    }

    #[test]
    fn parent_zone_strips_only_first_label_for_deeper_subdomain() {
        // Two-label heuristic: yah-side zones are all two-label apexes today.
        assert_eq!(parent_zone_name("a.b.yah.dev"), "yah.dev");
    }

    use super::{plan_domain_worker, DomainWorkerPlan};
    use crate::config::{DomainConfig, DomainRoute, FrontDoor, RouteMode};

    fn net_tier_manifest() -> DomainConfig {
        // Mirrors .yah/domains/scrabcake-net-yah-dev.toml.
        DomainConfig {
            schema_version: 1,
            name: "scrabcake-net-yah-dev".into(),
            domain: "scrabcake.net.yah.dev".into(),
            front_door: FrontDoor::Worker,
            cdn_bucket: "net-yah-dev".into(),
            worker_bundle_path: None,
            routes: vec![DomainRoute {
                headers: Default::default(),
                path: "/*".into(),
                mode: RouteMode::Static {
                    component: "scrabcake/site".into(),
                },
            }],
        }
    }

    #[test]
    fn plan_resolves_worker_name_domain_and_asset_origin() {
        let plan =
            plan_domain_worker(&net_tier_manifest(), "https://cdn.net.yah.dev", "cloud").unwrap();
        assert_eq!(
            plan,
            DomainWorkerPlan {
                worker_name: "scrabcake-net-yah-dev".into(),
                custom_domain: "scrabcake.net.yah.dev".into(),
                asset_origin: "https://cdn.net.yah.dev/scrabcake/cloud".into(),
                bindings: vec![
                    (
                        "ASSET_ORIGIN".into(),
                        "https://cdn.net.yah.dev/scrabcake/cloud".into()
                    ),
                    ("UPLOAD_ORIGIN".into(), String::new()),
                    ("WORKER_MODE".into(), "static".into()),
                    ("SSR_ORIGIN".into(), String::new()),
                    ("SSR_PREFIXES".into(), "[]".into()),
                    ("ROUTE_HEADERS".into(), "[]".into()),
                ],
            }
        );
    }

    /// R746: headers declared on a route reach the deployed Worker as the
    /// ROUTE_HEADERS binding. Without this the manifest could declare them and
    /// the Worker would serve without them — the exact silent gap the primitive
    /// exists to close.
    #[test]
    fn plan_carries_declared_route_headers_into_the_bindings() {
        let mut dom = net_tier_manifest();
        dom.routes[0].headers = [
            ("Cross-Origin-Opener-Policy".to_string(), "same-origin".to_string()),
            (
                "Cross-Origin-Embedder-Policy".to_string(),
                "require-corp".to_string(),
            ),
        ]
        .into_iter()
        .collect();
        let plan = plan_domain_worker(&dom, "https://cdn.net.yah.dev", "cloud").unwrap();
        let binding = plan
            .bindings
            .iter()
            .find(|(k, _)| k == "ROUTE_HEADERS")
            .expect("ROUTE_HEADERS binding");
        assert!(binding.1.contains("same-origin"), "{}", binding.1);
        assert!(binding.1.contains("require-corp"), "{}", binding.1);
        assert!(binding.1.contains("/*"), "{}", binding.1);
    }

    #[test]
    fn plan_trims_trailing_slash_on_cdn_base() {
        let plan =
            plan_domain_worker(&net_tier_manifest(), "https://cdn.net.yah.dev/", "cloud").unwrap();
        assert_eq!(plan.asset_origin, "https://cdn.net.yah.dev/scrabcake/cloud");
    }

    /// R594-F12: a manifest that declares a different front door must not
    /// get a Cloudflare Worker synthesized behind its back — the Worker
    /// would deploy and then never receive traffic.
    #[test]
    fn plan_bails_when_front_door_is_not_worker() {
        for door in [FrontDoor::BucketDirect, FrontDoor::Passway] {
            let mut dom = net_tier_manifest();
            dom.front_door = door;
            let err = plan_domain_worker(&dom, "https://cdn.net.yah.dev", "cloud").unwrap_err();
            let msg = format!("{err:#}");
            assert!(msg.contains("front_door"), "{msg}");
            assert!(msg.contains(door.as_str()), "{msg}");
        }
    }

    #[test]
    fn plan_bails_when_no_static_route() {
        let mut dom = net_tier_manifest();
        dom.routes = vec![DomainRoute {
            headers: Default::default(),
            path: "/old".into(),
            mode: RouteMode::Redirect {
                target: "https://elsewhere".into(),
                status: 308,
            },
        }];
        let err = plan_domain_worker(&dom, "https://cdn.net.yah.dev", "cloud").unwrap_err();
        assert!(
            format!("{err:#}").contains("no `static` route"),
            "got: {err:#}"
        );
    }

    // ── R561-F4: alias-tier registration ──
    use super::{plan_alias_claim, valid_subdomain_label, AliasTier};
    use std::collections::BTreeMap;

    #[test]
    fn label_validation_rules() {
        assert!(valid_subdomain_label("scrabcake"));
        assert!(valid_subdomain_label("my-repo-1"));
        assert!(!valid_subdomain_label("")); // empty
        assert!(!valid_subdomain_label("-lead")); // leading hyphen
        assert!(!valid_subdomain_label("trail-")); // trailing hyphen
        assert!(!valid_subdomain_label("Caps")); // uppercase
        assert!(!valid_subdomain_label("under_score")); // underscore
    }

    #[test]
    fn claim_builds_net_tier_manifest() {
        let dom = plan_alias_claim(
            AliasTier::Net,
            "scrabcake",
            "scrabcake/site",
            &BTreeMap::new(),
        )
        .unwrap();
        assert_eq!(dom.name, "scrabcake-net-yah-dev");
        assert_eq!(dom.domain, "scrabcake.net.yah.dev");
        assert_eq!(dom.cdn_bucket, "net-yah-dev");
        assert_eq!(dom.routes.len(), 1);
        assert!(
            matches!(&dom.routes[0].mode, RouteMode::Static { component } if component == "scrabcake/site")
        );
    }

    #[test]
    fn claim_uses_com_tier_zone_and_bucket() {
        let dom = plan_alias_claim(AliasTier::Com, "acme", "acme/site", &BTreeMap::new()).unwrap();
        assert_eq!(dom.domain, "acme.com.yah.dev");
        assert_eq!(dom.cdn_bucket, "com-yah-dev");
    }

    #[test]
    fn claim_bails_on_duplicate_host() {
        let existing: BTreeMap<String, DomainConfig> =
            [("scrabcake-net-yah-dev".to_string(), net_tier_manifest())]
                .into_iter()
                .collect();
        let err =
            plan_alias_claim(AliasTier::Net, "scrabcake", "scrabcake/site", &existing).unwrap_err();
        assert!(format!("{err:#}").contains("already"), "got: {err:#}");
    }

    #[test]
    fn claim_bails_on_invalid_label() {
        let err =
            plan_alias_claim(AliasTier::Net, "Bad_Name", "x/y", &BTreeMap::new()).unwrap_err();
        assert!(
            format!("{err:#}").contains("invalid subdomain"),
            "got: {err:#}"
        );
    }
}