cloud/cloud_init.rs
1//! Cloud-init template renderer for mirror-machine bootstrap (R040-F4).
2//!
3//! Loads the YAML template from `.yah/cloud/cloud-init/mirror.yml` (with a
4//! built-in fallback for portability) and substitutes per-machine values:
5//! machine name, yah-yubaba release-archive URL + sha256, Headscale pre-auth
6//! key, and mesh tags. The output is the `user_data` string passed to
7//! `MachineProvider::create_server`.
8//!
9//! Hetzner caps `user_data` at 32KiB so the yubaba binary cannot be
10//! base64-embedded (R040-F11). The first-boot `runcmd` fetches the release
11//! tar.gz (matching what `.github/workflows/release.yml` publishes), verifies
12//! sha256 against the archive, extracts, and installs `/usr/local/bin/yubaba`
13//! before the systemd hand-off.
14//!
15//! @yah:ticket(R040-F11, "yah-yubaba delivery: fetch from URL instead of base64 (Hetzner 32KiB user_data cap)")
16//! @yah:at(2026-05-05T00:00:42Z)
17//! @yah:status(review)
18//! @yah:assignee(agent:claude)
19//! @yah:parent(R040)
20//! @arch:see(architecture/PHASE_1_MIRROR_BOOTSTRAP.md)
21//! @yah:verify("cargo test -p cloud")
22//! @yah:verify("cargo test -p yah --bin yah cloud::")
23//! @yah:verify("yah cloud machine provision noisetable-pdx-1 --path /Users/user/ss/noisetable --dry-run --yubaba-url https://example.com/yubaba --yubaba /tmp/yubaba — renders curl + sha256sum runcmd lines, computes sha from local file")
24//! @yah:handoff("Cloud-init now fetches yah-yubaba via URL + sha256 verify instead of base64 inline (Hetzner 32KiB user_data cap). RenderInput swapped warden_base64 for warden_url + warden_sha256; template runcmd does curl -o + chmod +x + 'echo SHA bin | sha256sum -c -'. CLI provision flags: --yubaba-url <URL> required for live; --yubaba-sha256 <HEX> and/or --yubaba <PATH> (compute or assert sha); --dry-run falls back to placeholders. New helper resolve_warden_delivery() in app/yah/cli/src/cloud.rs covers all five flag combos with 7 unit tests. Cumulative: 30 cloud-crate tests pass (incl. new render_stays_under_hetzner_user_data_cap which fails the build if rendering ever blows past 32 KiB), 17 yah cloud:: tests pass. PHASE_1_MIRROR_BOOTSTRAP.md updated. Side fix: status.rs FakeProvider needed a one-line delete_bucket stub to compile (R040-F12 has the real impl in review).")
25//! @yah:next("Operator runbook (R040-T6) is now unblocked: publish yah-yubaba Linux musl binary at a stable URL (GitHub release artifact for the workspace.package version), then run `yah cloud machine provision noisetable-$region-1 --yubaba-url <URL> --yubaba <local-copy> --path /Users/user/ss/noisetable` for region in pdx iad fsn.")
26//! @yah:next("Optional polish: derive a default --yubaba-url from workspace.package.version + a hardcoded GitHub repo so operators don't have to retype the URL per region. Skip until release-plz (R038-F3) is wired so the artifact actually exists at a predictable path.")
27//!
28//! @yah:ticket(R040-F15, "Cloudflare Tunnel in cloud-init: cloudflared install + token, no public ports needed")
29//! @yah:at(2026-05-05T00:00:42Z)
30//! @yah:assignee(agent:claude)
31//! @yah:status(review)
32//! @yah:parent(R040)
33//! @yah:handoff("Architecture decision (this session, recorded so future-self doesn't re-litigate): public ingress for yah-cloud nodes is Cloudflare Tunnels — `cloudflared` runs on each origin, makes an OUTBOUND connection to CF edge, CF proxies inbound traffic through the tunnel. Origin needs zero inbound exposure (no port 80/443 open, no stable IPv4, no floating IP plumbing). DNS records point at `<tunnel-id>.cfargotunnel.com` and never churn when boxes are replaced. Inter-node TCP (Postgres replication, gRPC streams, NATS) goes over Headscale mesh — see R040-F16. Combined effect: Hetzner inline IPs are fine forever, IPv6-only is even an option (saves ~€0.50/mo per box; needs validating that tailscale install + apt mirrors work over v6).")
34//! @yah:next("cloud-init template: add `cloudflared service install --token {{CLOUDFLARED_TOKEN}}` + `systemctl enable --now cloudflared` to runcmd, parallel to the existing tailscale install. Token comes from RenderInput.cloudflared_token, sourced from `keys::KeysStore::open().get(\"cloudflare-tunnel-token\")` in cli/src/cloud.rs::handle_provision.")
35//! @yah:next("MachineConfig.cloudflared: Option<String> — tunnel-id this machine joins. Empty/None means \"no tunnel\" (mesh-only nodes that don't need public ingress). When set, the cloud-init renderer wires the right token in.")
36//! @yah:next("Optional: `yah cloud tunnel {create,list,destroy}` subcommand against the CF API. Lower-priority — operators can use cloudflared CLI directly until this matters at fleet scale.")
37//! @yah:next("Caveat to flag in handoff: Free + Pro tier CF Tunnels is HTTP/WebSocket/gRPC only. Raw TCP/UDP ingress (rare for yah, but possible — e.g. a public Postgres for some integration) needs CF Spectrum (paid) OR a primary IP for that one service. Don't pre-build the second path; design records this as a known constraint.")
38//! @arch:see(architecture/PHASE_1_MIRROR_BOOTSTRAP.md)
39//!
40//! @yah:ticket(R441-B3, "cloud_init mirror.yml drift between cloud/templates and .yah/infra/cloud-init")
41//! @yah:assignee(agent:claude)
42//! @yah:at(2026-06-04T22:56:14Z)
43//! @yah:status(review)
44//! @yah:parent(R441)
45//! @yah:next("embedded_template_matches_workspace_canonical at cloud_init.rs:489 panics: the two mirror.yml files diverged. crates/yah/cloud/templates/mirror.yml (canonical, R406-T13/W154) has yubaba + kamaji + yubaba.slice systemd units plus the kamaji.service unit; .yah/infra/cloud-init/mirror.yml still has the older single yah-yubaba.service shape with no kamaji.")
46//! @yah:next("Pick the source of truth (the canonical-template path that the embedded test enforces was meant to be the cloud/templates copy) and sync the other file to match. Re-run the test to confirm.")
47//! @yah:verify("cargo test -p cloud --lib cloud_init::tests::embedded_template_matches_workspace_canonical passes")
48//! @yah:handoff("Overwrote crates/yah/cloud/templates/mirror.yml to match .yah/infra/cloud-init/mirror.yml (W154/R406-T13 yubaba+kamaji+yubaba.slice format). The workspace file was the canonical updated version; the embedded template hadn't been synced. cargo test -p cloud --lib cloud_init::tests::embedded_template_matches_workspace_canonical passes.")
49//!
50//! @yah:ticket(R589-F1, "Rename service/binary emitters warden→yubaba in the provision path so new nodes provision as yubaba")
51//! @yah:status(review)
52//! @yah:at(2026-07-06T06:13:22Z)
53//! @yah:assignee(agent:claude)
54//! @yah:parent(R589)
55//! @yah:handoff("Hard-cut warden→yubaba across the provision-path emitters (no shims/aliases). cloud_init.rs: RenderInput fields warden_url/warden_sha256/warden_channel/warden_cosign_identity_regexp → yubaba_*; placeholders {{YAH_WARDEN_URL}}/{{YAH_WARDEN_SHA256}}/{{WARDEN_CHANNEL}}/{{UFW_WARDEN_RULE}} → {{YAH_YUBABA_URL}}/{{YAH_YUBABA_SHA256}}/{{YUBABA_CHANNEL}}/{{UFW_YUBABA_RULE}}; PLACEHOLDER_WARDEN_URL/SHA256 → PLACEHOLDER_YUBABA_URL/SHA256; DEFAULT_WARDEN_CHANNEL → DEFAULT_YUBABA_CHANNEL; compute_warden_sha256() → compute_yubaba_sha256(). templates/mirror.yml + its workspace-canonical twin .yah/infra/cloud-init/mirror.yml (drift-tested against each other) got matching placeholder/env renames, incl. the systemd drop-in's Environment=WARDEN_CHANNEL→YUBABA_CHANNEL. provision.rs's build_request() params + release_manifest.rs's WardenReleaseManifest→YubabaReleaseManifest / DEFAULT_WARDEN_COSIGN_IDENTITY→DEFAULT_YUBABA_COSIGN_IDENTITY followed (they feed straight into RenderInput). yubaba-test-harness/src/lib.rs: YAH_WARDEN_URL/SHA256 env vars → YAH_YUBABA_URL/SHA256, plus the local build_smoke_cloud_init()/wait_for_warden_health() helpers renamed to match. local_docker.rs's cloud_init_boots_warden_service test renamed + its template placeholders updated. Cross-crate consumers outside oss/yubaba also updated in the same pass (real compile deps, not board-protocol scope creep): app/yah/cli/src/{cloud.rs,cli.rs,yubaba_fetch.rs} + tests/camp_yubaba_fetch.rs. Fenced OFF (belongs to R592-T4, wire-layer type/client renames): WardenHandle, YubabaRaft, YubabaRequest, WardenRoute wire types in yubaba/raft/*, yubaba-test-harness's WardenHandle, and camp.rs's WardenContainerSpec/build_warden_run_spec/DEFAULT_WARDEN_IMAGE/DEFAULT_WARDEN_HTTP_PORT/read_warden_pond_port/WardenDeploy (pond continuous-deploy runtime, not the cloud-init provisioning path). Also left untouched: name-neutral state paths (/var/lib/yah-cloud/identity.json, /run/constable/constable.sock) per this ticket's own scope fence, and stale warden_test_harness/warden_test_macros doc-comment crate names in yubaba-test-macros (pre-existing drift from an earlier, unrelated crate rename — not provision-path env/template residue). Verify: cargo check/test -p cloud -p yubaba-test-harness (oss/yubaba workspace) clean; cargo check -p yah + cargo test -p yah --lib yubaba_fetch:: + --test camp_yubaba_fetch clean from repo root. Zero remaining WARDEN_ env/placeholder refs in the provision path (grep-verified).")
56//!
57//! @yah:relay(R702, "Bounded disk everywhere — no process on a yah box grows without an explicit ceiling")
58//! @yah:at(2026-08-03T01:29:40Z)
59//! @yah:status(open)
60//! @yah:assignee(agent:bundle-anthropic-glimmerstone)
61//! @yah:next("DOCTRINE (operator, 2026-08-02, emphatic): a full disk brings the best software to its knees, and apps - Docker especially - love to eat all the space. Every single process that ever runs on a yah box must be explicitly forbidden from unbounded growth. A default that happens to be a fraction of the disk is NOT a bound. This relay makes that auditable rather than aspirational.")
62//! @yah:next("DONE ALREADY, not part of the remaining children: journald bounded on all three cloud nodes via /etc/systemd/journald.conf.d/10-yah-disk-bounds.conf (SystemMaxUse=500M, SystemKeepFree=1G, SystemMaxFileSize=50M, RuntimeMaxUse=64M) and the same block added to the TOP of runcmd in BOTH twin cloud-init templates (oss/yubaba/crates/cloud/templates/mirror.yml + .yah/infra/cloud-init/mirror.yml) so it lands before anything else on the box starts writing. us-south-001 went 755.5M -> 483M on restart. RuntimeMaxUse matters twice over: /run is tmpfs, so it bounds RAM too.")
63//! @yah:next("Children to file as work begins: (F) kamaji bundle-cache budget - THE live unbounded one, see gotcha; (T) containerd image/snapshot GC policy; (T) apt archive + old-kernel retention; (T) surface per-node disk headroom in yubaba node status so pressure is visible before it is fatal; (D) a W doc carrying the doctrine plus a review checklist item - every new on-disk writer declares its ceiling at the same time it declares the path.")
64//! @yah:gotcha("LIVE UNBOUNDED CACHE IN OUR OWN CODE, RIGHT NOW. kamaji's mesofact bundle cache has working, unit-tested LRU eviction (BundleCache::evict_to_budget, oss/yah-base/crates/mesofact-bundle/src/store.rs:243) that is DISABLED in production: BundleBackend::cache_budget defaults to 0 (oss/kamaji/crates/kamaji-bin/src/server.rs:297) and 0 explicitly means 'unbounded, eviction off' (store.rs:207). There is no --bundle-cache-budget CLI flag in kamaji-bin/src/main.rs, and the live drop-in /etc/systemd/system/kamaji.service.d/20-bundle.conf on us-east-001 passes only --bundle-cache-dir and --bundle-origin. Net effect: every release wave materializes a new digest-keyed tree under /var/lib/yah/kamaji/bundles/ and NOTHING ever removes the old one. Only 6.3M on east today because there have been few waves - it grows monotonically with release count, forever.")
65//! @yah:gotcha("Fix shape for that child: add the flag, and make the DEFAULT non-zero rather than shipping another opt-in bound (an opt-in ceiling is how this happened). If 0-means-unbounded stays as an escape hatch it should require passing 0 explicitly, so the default path is always bounded.")
66//! @yah:gotcha("Measured baseline 2026-08-02 for whoever picks this up. us-south-001 (30G disk, 1 vCPU / 961MB): 7.2G used, /var 1.4G of which journal 755M, /var/lib/apt 295M, /var/cache 177M. us-east-001 (99G): 2.0G used, /usr 1.1G, /var 786M, containerd 154M, kamaji bundles 6.3M. us-west-001 (99G): 1.9G used. Nothing is near full today - this relay is about the derivative, not the current level.")
67//! @yah:verify("cargo test -p yah-cloud --lib cloud_init # 25/25 pass after the template edit, incl. embedded_template_matches_workspace_canonical (twin-drift guard) and rendered_runcmd_entries_are_all_strings (the colon-space YAML footgun guard) - ALREADY GREEN 2026-08-02")
68//! @yah:verify("Audit gate for closing this relay: on a freshly provisioned node, every path under /var that any yah-owned process writes to has a named ceiling, and each ceiling is asserted somewhere (unit test, systemd directive, or config) rather than assumed.")
69//! @yah:verify("journalctl --disk-usage on each cloud node stays under 500M across a week of normal operation.")
70//! @yah:assumes("The LAN/appliance nodes (us-west-011/013/014/015) need the same treatment and probably need it MORE (us-west-014 is the arm64 Pi appliance prototype - SD-card-class storage). They were not touched in the 2026-08-02 pass, which covered only the three cloud VMs.")
71//! @yah:gotcha("us-west-014 (Pi 5) VERIFIED 2026-08-02 and it is a two-filesystem box, which changes what 'bounded' means there. The NVMe design IS implemented and working - /dev/nvme0n1p1 is bind-mounted onto /var/lib/docker, /var/lib/yah-cloud and /srv/build, plus an 8 GB swapfile (enabled, 0 used), 234 G at 4%. But `/` is a 2.5 G SD-backed ext4 at 68% with ~745 M free, and /var itself is NOT on the NVMe - only those three subdirectories are. So /var/log (123 M) and /var/cache apt (170 M) sit on the tightest filesystem in the fleet. journald capped at 200M/400M-keepfree there (deliberately smaller than the cloud nodes' 500M). The general rule for this box: anything new writing under /var lands on the SD unless it gets its own bind, so a per-node ceiling has to be sized to the filesystem it actually lands on, not copied from the cloud nodes.")
72//! @yah:gotcha("Docker on us-west-014 is the ONE docker install in the fleet that is already safe by placement (data-root bind-mounted to a 234 G NVMe at 4%). Do not let that make the containerd/docker GC child look optional - the cloud nodes have containerd on the root filesystem with no GC policy (154 M on us-east-001 today).")
73//! @yah:handoff("PI APPLIANCE IMAGE BOUNDED (2026-08-02), ahead of flashing us-west-011 + us-west-013. Two unbounded growers ship with stock docker and both hit build workers hardest: json-file logging defaults to no max-size/max-file, and the BuildKit cache grows forever without builder.gc. Neither had any config - /etc/docker/daemon.json did not exist on us-west-014 or in the image layer. Added to .yah/infra/pi-image/layer/yah-build-worker.yaml: a mkdir -p hook plus a baked /etc/docker/daemon.json (json-file, max-size 10m, max-file 3, builder.gc enabled with defaultKeepStorage 20GB) and /etc/systemd/journald.conf.d/10-yah-disk-bounds.conf at 200M/400M-keepfree/25M-maxfile/32M-runtime. Layer YAML re-parses (14 hooks) and the emitted JSON body validates.")
74//! @yah:handoff("LOCKSTEP DEBT PAID. mirror.yml's new journald runcmd block obliged a matching change in its documented twin .yah/infra/cloud-init/stand-up-yubaba.sh (the SSH-deliverable transcription used for LAN nodes, W257 step 6). Written WRITE-IF-ABSENT on purpose: the standup default is the cloud-node 500M, but the Pi image bakes a tighter 200M sized to its 2.5 G SD root, and the standup runs AFTER first boot - an unconditional write would have silently regressed every Pi it touched. An existing ceiling always wins and the script echoes what it kept. bash -n clean.")
75//! @yah:handoff("W257 runbook step 5 gained a disk-ceiling verification block. The load-bearing assertion is `systemctl is-active docker`: dockerd refuses to start on a daemon.json it cannot parse, and a docker-less build worker is the entire purpose of the node gone. Runbook names the likely culprit after a docker bump (defaultKeepStorage deprecated in favour of builder.gc.policy in 27+; trixie ships 26.1.5, which honours the old key).")
76//! @yah:handoff("X86 FLEET PROVISIONING LANDED (2026-08-02), and it closes the arch-specific-ceiling gap this relay opened. New .yah/infra/preseed/{yah-x86-worker.cfg, build-iso.sh, .gitignore}. Deliberately the SAME shape as the Pi path rather than a new idiom: a Debian container does the work, the operator key is injected at build time instead of committed, and one artifact provisions every x86 box with per-box identity applied after install. build-iso.sh caches the stock trixie amd64 netinst, renders the preseed with ~/.ssh/yah.pub substituted for @@SSH_PUBKEY@@, injects it into the installer initrd (so the install is hands-off with no boot prompt to type at), regenerates md5sum.txt, and repacks a UEFI hybrid ISO with xorriso. Neither path is a roll-your-own distro - one configures rpi-image-gen, the other configures debian-installer.")
77//! @yah:handoff("PARTITIONING IS THE STRUCTURAL HALF OF THIS RELAY, and the preseed is where it finally gets decided up front instead of discovered. Separate LVs for /, /var and /var/lib/docker on VG `yah`, ~40 GB left unallocated for online lvextend. A runaway BuildKit cache now fills /var/lib/docker and NOTHING else - root stays writable, sshd keeps accepting, journald keeps recording, the box stays reachable to clean up. That is the backstop for a MISSING ceiling; it does not replace the ceilings, which the preseed late_command also writes (journald 500M + docker daemon.json with log rotation and builder.gc at 100GB, sized to the 512 GB disk).")
78//! @yah:handoff("DOCKER CEILING IS NO LONGER A PROPERTY OF ONE IMAGE. stand-up-yubaba.sh now applies /etc/docker/daemon.json write-if-absent on any node where docker is present (it installs containerd, not docker, so this is a conditional), and restarts docker THERE so a parse failure surfaces during standup rather than at the next reboot - dockerd refuses to start on a daemon.json it cannot parse. Three provisioning paths now converge on the same ceilings: Pi image (baked), preseed late_command (baked), standup script (retrofit). bash -n clean on both scripts.")
79//! @yah:handoff("Scaffolded .yah/infra/machines/us-west-012.toml for the GEEKOM A5 (Ryzen 7 5825U 8C/16T, 16 GB, 512 GB NVMe): tier:x86 + os:linux + build-worker/qed, taints copied from us-west-002 for day one. Recorded WHY it is a better tier:x86 host than 002 - 002 is a WSL2 box that sleeps and reboots with Windows, this is dedicated always-on Debian - so dropping no-server/no-appliance later is a deliberate re-decision rather than drift. Stays no-voter regardless: a residential uplink must never be able to stall the raft. allocatable is from the vendor spec with an explicit instruction to re-verify via nproc + free -m on the box, since the OVH nodes shipped wrong for months. Parses: cargo test -p yah-cloud --lib machine 24/24, `yah cloud validate` ok.")
80//! @yah:verify("UNPROVEN, and the one thing to watch: the partman-auto/expert_recipe in yah-x86-worker.cfg has never been run. A malformed recipe fails mid-install with an error that does not always name the offending stanza. Watch the first install of any ISO revision; once it completes cleanly the same ISO is proven for every later box. It also assumes ONE disk (early_command picks `list-devices disk | head -n1`), so a two-disk box needs the target pinned.")
81//! @yah:verify("UNPROVEN: build-iso.sh has not been executed - the initrd inject + xorriso repack path is written but not run, and the ISO URL pins DEBIAN_VERSION=13.1.0 which should be bumped to whatever trixie point release is current at build time (override with the env var).")
82//! @yah:verify("Cheap de-risk available before touching hardware: boot the built ISO in QEMU against a scratch qcow2 and let the unattended install run to completion. That proves the recipe, the initrd inject and the late_command without burning a USB or a trip to the box.")
83//! @yah:handoff("RENUMBERED (operator correction, 2026-08-02): the GEEKOM mini PC is us-west-003, NOT us-west-012 — the 01x block is reserved for the small LAN/appliance class and another Pi is taking 012. The convention is by HARDWARE CLASS, not arrival order: 00x = PC/server (001 OVH VPS, 002 WSL2 gamer box, 003 GEEKOM), 01x = small LAN boxes (011-014 Pis, 015 arm64 Mac). Recorded at the top of us-west-003.toml and in W257, because it is not derivable from the existing files and it is what tells a reader which of the two provisioning paths a node took. The us-west-012.toml scaffold was untracked and never committed, so it was removed rather than renamed; no stale refs remain (grep clean, `yah cloud validate` ok).")
84//! @yah:gotcha("LAN IP for us-west-003 is ASSUMED, not confirmed. W257's convention is us-west-0NN -> 192.168.10.NN and it holds for every 01x node, but the only existing 00x LAN box breaks it: us-west-002 sits at 192.168.10.30, not .2. The scaffold uses .3 with a CONFIRM-BEFORE-BRING-UP note inline. If the 00x block actually lives in the .3x range on the router, .3 is wrong and both [connect].address and [connect].ssh need correcting before step 4.")
85
86use crate::config::MachineConfig;
87use crate::release_manifest::ReleaseTrust;
88use anyhow::{bail, Context, Result};
89use sha2::{Digest, Sha256};
90use std::path::Path;
91
92/// Built-in fallback template, used when `.yah/infra/cloud-init/mirror.yml`
93/// is absent. Keeps the binary self-contained for tests + new workspaces.
94pub const DEFAULT_TEMPLATE: &str = include_str!("../templates/mirror.yml");
95
96/// Inputs needed to render `mirror.yml` for a single machine.
97#[derive(Debug)]
98pub struct RenderInput<'a> {
99 pub machine: &'a MachineConfig,
100 /// HTTPS URL of the yah-yubaba release tar.gz (e.g. a GitHub release
101 /// asset published by `.github/workflows/release.yml`). Cloud-init's
102 /// `runcmd` downloads it, verifies sha256 against [`Self::yubaba_sha256`],
103 /// extracts, and installs `/usr/local/bin/yubaba`. Use
104 /// `PLACEHOLDER_YUBABA_URL` for dry-run previews.
105 pub yubaba_url: String,
106 /// Lowercase hex sha256 of the tar.gz at `yubaba_url`. Cloud-init verifies
107 /// this with `sha256sum -c -` against the downloaded archive and fails
108 /// the boot if it doesn't match.
109 pub yubaba_sha256: String,
110 /// Release channel passed to `yah-yubaba serve --channel`. One of
111 /// `"stable"` or `"beta"`. Use [`DEFAULT_YUBABA_CHANNEL`] for Phase 1.
112 pub yubaba_channel: String,
113 /// Headscale pre-auth key. `Some` ⟺ this machine is joining an existing
114 /// mesh: the renderer emits the tailscaled install + `tailscale up` join
115 /// block (gated on this being `Some`, see [`render`]). `None` ⟺ standalone
116 /// / coordinator-to-be — no mesh to join yet, so no join block is emitted
117 /// (the node becomes the coordinator later via `yah mesh bootstrap`).
118 pub headscale_preauth_key: Option<String>,
119 /// Stable URL of the Headscale coordinator (`https://mesh.<domain>`).
120 /// When set (R040-F18), the rendered cloud-init passes
121 /// `--login-server <url>` to `tailscale up` so the new machine joins
122 /// the camp's Headscale instead of Tailscale SaaS. When `None`, the
123 /// `{{MESH_LOGIN_SERVER_ARG}}` placeholder is replaced with an empty
124 /// string, preserving the existing Tailscale SaaS behaviour.
125 pub mesh_url: Option<String>,
126 /// Cloudflare Tunnel token for `cloudflared service install --token ...`.
127 /// `None` → no cloudflared install (mesh-only node). When `Some`, the
128 /// renderer emits the full cloudflared apt-repo install + service enable
129 /// block into `runcmd` in place of `{{CLOUDFLARED_BLOCK}}`.
130 pub cloudflared_token: Option<String>,
131 /// When `Some`, render the cosign install + `cosign verify-blob` runcmd
132 /// block into `{{COSIGN_VERIFY_BLOCK}}`, gating the yubaba tarball on a
133 /// keyless OIDC signature whose certificate identity matches this regexp
134 /// (e.g. `^https://github\.com/yah-ai/yah/`). The sha256 check stays
135 /// in parallel as belt-and-suspenders (R330-F20, W203 §1.4). When `None`
136 /// the placeholder substitutes to an empty string and the bootstrap stays
137 /// on the sha256-only path.
138 pub yubaba_cosign_identity_regexp: Option<String>,
139}
140
141/// Placeholders used when the user requests a dry-run without supplying real
142/// substitutes. Makes the rendered YAML obviously non-shippable while still
143/// preserving the structure for review.
144pub const PLACEHOLDER_YUBABA_URL: &str = "<YUBABA_URL_PLACEHOLDER>";
145pub const PLACEHOLDER_YUBABA_SHA256: &str = "<YUBABA_SHA256_PLACEHOLDER>";
146pub const PLACEHOLDER_PREAUTH_KEY: &str = "<HEADSCALE_PREAUTH_KEY_PLACEHOLDER>";
147pub const PLACEHOLDER_CLOUDFLARED_TOKEN: &str = "<CLOUDFLARED_TOKEN_PLACEHOLDER>";
148
149/// Phase 1 defaults for new provisioning keys.
150pub const DEFAULT_YUBABA_CHANNEL: &str = "stable";
151/// Pinned cosign release used by the cloud-init verify-blob block. Bump in
152/// lockstep with [`COSIGN_SHA256_AMD64`] / [`COSIGN_SHA256_ARM64`] when
153/// upgrading the verifier — supply-chain hygiene (W203 §1.4, R330-F22).
154pub const COSIGN_VERSION: &str = "v2.4.1";
155/// sha256 of the cosign-linux-amd64 binary at [`COSIGN_VERSION`]. Cloud-init
156/// verifies the downloaded binary against this before chmod+exec. Pinning the
157/// verifier itself closes the bootstrap-trust gap: TLS to github.com proves
158/// origin, sha256 proves bytes, then cosign proves the yubaba tarball.
159pub const COSIGN_SHA256_AMD64: &str =
160 "8b24b946dd5809c6bd93de08033bcf6bc0ed7d336b7785787c080f574b89249b";
161/// sha256 of the cosign-linux-arm64 binary at [`COSIGN_VERSION`].
162pub const COSIGN_SHA256_ARM64: &str =
163 "3b2e2e3854d0356c45fe6607047526ccd04742d20bd44afb5be91fa2a6e7cb4a";
164/// Sigstore Fulcio OIDC issuer for GitHub-Actions-rooted keyless signing.
165/// Re-exported from [`crate::release_manifest`], which owns the canonical
166/// copy — the shell verify path here and the Rust verify path in the yah CLI
167/// must pin the same issuer or one of them silently accepts the other's
168/// rejects (R605-F1).
169pub use crate::release_manifest::COSIGN_OIDC_ISSUER;
170
171/// Load the cloud-init template for a workspace.
172///
173/// Prefers `<workspace_root>/.yah/infra/cloud-init/mirror.yml` if it exists,
174/// otherwise returns the embedded [`DEFAULT_TEMPLATE`].
175pub fn load_template(workspace_root: &Path) -> Result<String> {
176 let custom = crate::paths::cloud_init_template(workspace_root);
177 if custom.exists() {
178 std::fs::read_to_string(&custom).with_context(|| format!("reading {}", custom.display()))
179 } else {
180 Ok(DEFAULT_TEMPLATE.to_string())
181 }
182}
183
184/// Substitute `{{KEY}}` placeholders. Fails loudly if any unsubstituted
185/// placeholder remains — better than silently shipping a broken cloud-init.
186pub fn render(template: &str, input: &RenderInput) -> Result<String> {
187 let tags = if input.machine.mesh_tags.is_empty() {
188 // Tailscale rejects empty `--advertise-tags=`; emit a single tag derived from the machine name.
189 format!("tag:{}", input.machine.name)
190 } else {
191 input.machine.mesh_tags.join(",")
192 };
193
194 let mesh_login_server_arg = match &input.mesh_url {
195 Some(url) => format!(" --login-server {url}"),
196 None => String::new(),
197 };
198
199 let cloudflared_block = match &input.cloudflared_token {
200 Some(token) => build_cloudflared_block(token),
201 None => String::new(),
202 };
203
204 // The tailscale-up/join block is emitted iff we have a preauth key, i.e.
205 // this machine is joining an existing mesh (R330-F28). Standalone /
206 // coordinator-to-be nodes carry no preauth and get no join block — they
207 // come up as bare yubaba and become the coordinator via `yah mesh bootstrap`.
208 let operator_bridge_block = match &input.headscale_preauth_key {
209 Some(key) => build_operator_bridge_block(key, &mesh_login_server_arg, &tags),
210 None => String::new(),
211 };
212
213 // Yubaba RPC (7443) firewall rule keys off the same axis (R330-F28 #13).
214 // JOINING (preauth present): deny public 7443 — the join block above adds
215 // an `allow in on tailscale0` so yubaba is mesh-reachable only. STANDALONE
216 // (no preauth): allow public 7443 so the operator can attach + bootstrap
217 // the coordinator before any mesh exists to reach it over.
218 let ufw_yubaba_rule = match &input.headscale_preauth_key {
219 Some(_) => " - ufw deny 7443".to_string(),
220 None => " - ufw allow 7443".to_string(),
221 };
222
223 // Coordinator pre-stage (standalone only, R330-F28 #15). yubaba runs under
224 // ProtectSystem=strict so it cannot write the headscale systemd unit nor
225 // open the firewall; cloud-init (unsandboxed) lays both down here so a later
226 // `yah mesh bootstrap` only needs to write config + `systemctl enable --now
227 // headscale`. The unit's ExecStart matches DEFAULT_HEADSCALE_DIR. Joining
228 // nodes never self-bootstrap a coordinator, so the block is empty for them.
229 let coordinator_prestage_block = match &input.headscale_preauth_key {
230 Some(_) => String::new(),
231 None => build_coordinator_prestage_block(),
232 };
233
234 let cosign_verify_block = match &input.yubaba_cosign_identity_regexp {
235 Some(regexp) => build_cosign_verify_block(&input.yubaba_url, regexp),
236 None => String::new(),
237 };
238
239 let rendered = template
240 .replace("{{MACHINE_NAME}}", &input.machine.name)
241 .replace("{{YAH_YUBABA_URL}}", &input.yubaba_url)
242 .replace("{{YAH_YUBABA_SHA256}}", &input.yubaba_sha256)
243 .replace("{{YUBABA_CHANNEL}}", &input.yubaba_channel)
244 .replace(
245 "{{HEADSCALE_PREAUTH_KEY}}",
246 input.headscale_preauth_key.as_deref().unwrap_or(""),
247 )
248 .replace("{{MESH_LOGIN_SERVER_ARG}}", &mesh_login_server_arg)
249 .replace("{{TAGS}}", &tags)
250 .replace("{{CLOUDFLARED_BLOCK}}", &cloudflared_block)
251 .replace("{{OPERATOR_BRIDGE_BLOCK}}", &operator_bridge_block)
252 .replace("{{UFW_YUBABA_RULE}}", &ufw_yubaba_rule)
253 .replace(
254 "{{COORDINATOR_PRESTAGE_BLOCK}}",
255 &coordinator_prestage_block,
256 )
257 .replace("{{COSIGN_VERIFY_BLOCK}}", &cosign_verify_block);
258
259 if let Some(remnant) = find_unsubstituted(&rendered) {
260 bail!("cloud-init template has unsubstituted placeholder: {remnant}");
261 }
262 Ok(rendered)
263}
264
265/// Read a yah-yubaba release tar.gz from disk and return its lowercase hex
266/// sha256. Used both as the cloud-init verification digest and for asserting
267/// that a local copy matches an expected `--yubaba-sha256` value. The path
268/// should point to the release archive (matching what cloud-init downloads),
269/// not a bare binary.
270pub fn compute_yubaba_sha256(path: &Path) -> Result<String> {
271 let bytes = std::fs::read(path)
272 .with_context(|| format!("reading yah-yubaba archive at {}", path.display()))?;
273 let mut hasher = Sha256::new();
274 hasher.update(&bytes);
275 Ok(hex::encode(hasher.finalize()))
276}
277
278/// Build the cloudflared apt-repo install + tunnel-connect block for `runcmd`.
279/// Each line is a valid cloud-init sequence entry (two-space indent + `- `).
280/// The block replaces `{{CLOUDFLARED_BLOCK}}` in the template; when empty it
281/// leaves a blank line in the rendered YAML (harmless to the YAML parser).
282fn build_cloudflared_block(token: &str) -> String {
283 [
284 " - mkdir -p --mode=0755 /usr/share/keyrings".to_string(),
285 " - sh -c 'curl -fsSL https://pkg.cloudflare.com/cloudflare-main.gpg | gpg --dearmor > /usr/share/keyrings/cloudflare-main.gpg'".to_string(),
286 " - sh -c 'echo \"deb [signed-by=/usr/share/keyrings/cloudflare-main.gpg] https://pkg.cloudflare.com/cloudflared bookworm main\" > /etc/apt/sources.list.d/cloudflared.list'".to_string(),
287 " - apt-get update -qq".to_string(),
288 " - apt-get install -y cloudflared".to_string(),
289 // The token is a POSITIONAL argument, not a `--token` flag: the
290 // `service install` subcommand has no `--token` option, so
291 // `cloudflared service install --token <tok>` fails arg-parsing with
292 // "flag provided but not defined: -token", prints usage, and NEVER
293 // creates cloudflared.service. The `systemctl enable --now` below then
294 // fails with "Unit file cloudflared.service does not exist", leaving
295 // the tunnel inactive with an empty journal (R330-B29, found on the
296 // us-west-001 from-zero validation). `service install <TOKEN>` already
297 // installs+enables+starts the unit; the explicit enable is redundant
298 // but harmless now that the unit exists.
299 format!(" - cloudflared service install {token}"),
300 " - systemctl enable --now cloudflared".to_string(),
301 ]
302 .join("\n")
303}
304
305/// Build the cosign install + `cosign verify-blob` block for `runcmd`. Each
306/// line is a valid cloud-init sequence entry (two-space indent + `- `). The
307/// `.sig`/`.cert` URLs derive by appending those suffixes to the tarball URL —
308/// matching what `release.yml` publishes alongside the canonical artifact
309/// (R330-F19). Architecture is detected at boot via `dpkg --print-architecture`
310/// so one rendered template serves both x86_64 and aarch64 Hetzner machines.
311///
312/// R605-F1: `identity_spec` is parsed as a [`ReleaseTrust`], so a fleet whose
313/// releases are cut on QED (key-based cosign, no Fulcio) provisions by setting
314/// `key:<pubkey-ref>` — the `.cert` fetch drops out with it, because a
315/// key-based signature has no certificate to download.
316fn build_cosign_verify_block(yubaba_url: &str, identity_spec: &str) -> String {
317 // ARCH + SHA must be set, checked, and consumed inside the same `sh -c`
318 // process — cloud-init runcmd entries are independent shells, so a
319 // multi-step download-then-verify-then-install split would lose the
320 // variables between lines. One `sh -c` keeps the pin atomic.
321 //
322 // NB: runcmd entries are emitted as bare (unquoted) YAML scalars, so a
323 // `: ` (colon-space) anywhere in the command makes the YAML parser read
324 // the entry as a `key: value` MAPPING — cloud-init's shellify then chokes
325 // on the dict and SKIPS THE ENTIRE runcmd block (R330-F28 from-zero
326 // validation, pothole #12). Keep this string colon-space-free: the error
327 // message says "unsupported arch <ARCH>", not "unsupported arch: <ARCH>".
328 let install_and_verify_cosign = format!(
329 " - sh -c 'set -e; ARCH=$(dpkg --print-architecture); \
330 case \"$ARCH\" in \
331 amd64) SHA=\"{amd64}\";; \
332 arm64) SHA=\"{arm64}\";; \
333 *) echo \"unsupported arch $ARCH\" >&2; exit 1;; \
334 esac; \
335 curl -fsSL \"https://github.com/sigstore/cosign/releases/download/{ver}/cosign-linux-${{ARCH}}\" -o /usr/local/bin/cosign; \
336 echo \"${{SHA}} /usr/local/bin/cosign\" | sha256sum -c -; \
337 chmod +x /usr/local/bin/cosign'",
338 amd64 = COSIGN_SHA256_AMD64,
339 arm64 = COSIGN_SHA256_ARM64,
340 ver = COSIGN_VERSION
341 );
342 let trust = ReleaseTrust::parse(identity_spec);
343 // Single-quote each flag value: the regexp arm carries backslashes and `^`
344 // that the boot shell would otherwise eat, and the key arm carries a URI.
345 // Neither may contain a `'` — a spec that does is an operator error, not a
346 // case to escape, since it can't be a valid identity regexp or key ref.
347 let trust_flags = trust
348 .verify_flags()
349 .chunks(2)
350 .map(|kv| format!("{} '{}'", kv[0], kv.get(1).map_or("", |v| v.as_str())))
351 .collect::<Vec<_>>()
352 .join(" ");
353
354 let mut lines = vec![
355 install_and_verify_cosign,
356 format!(" - curl -fsSL -o /tmp/yah-yubaba.tar.gz.sig {yubaba_url}.sig"),
357 ];
358 if trust.needs_certificate() {
359 lines.push(format!(
360 " - curl -fsSL -o /tmp/yah-yubaba.tar.gz.cert {yubaba_url}.cert"
361 ));
362 }
363 let cert_flag = if trust.needs_certificate() {
364 " --certificate /tmp/yah-yubaba.tar.gz.cert"
365 } else {
366 ""
367 };
368 lines.push(format!(
369 " - cosign verify-blob {trust_flags}{cert_flag} --signature /tmp/yah-yubaba.tar.gz.sig /tmp/yah-yubaba.tar.gz"
370 ));
371 lines.join("\n")
372}
373
374/// Build the tailscaled operator-bridge block for `runcmd`.
375/// Each line is a valid cloud-init sequence entry (two-space indent + `- `).
376/// The block replaces `{{OPERATOR_BRIDGE_BLOCK}}` in the template; when the
377/// machine does not host operator-bridge workloads the placeholder is replaced
378/// with an empty string (harmless blank line in the rendered YAML).
379fn build_operator_bridge_block(
380 preauth_key: &str,
381 mesh_login_server_arg: &str,
382 tags: &str,
383) -> String {
384 // `--accept-dns=false` is load-bearing, not a preference (R624-B1).
385 //
386 // With MagicDNS accepted, tailscaled rewrites /etc/resolv.conf to point at
387 // its own resolver (100.100.100.100). If tailscaled is then down — as it is
388 // on every boot before it connects — nothing answers that address, so the
389 // node cannot resolve the control server, so tailscaled can never come up.
390 // The loop is self-sustaining and survives reboots and restarts; it took
391 // us-south-001 (a raft voter) off the mesh for 30+ hours until a human
392 // edited resolv.conf by hand. Ordering the unit After=tailscaled does NOT
393 // help: tailscaled starts fine, it just can never CONNECT.
394 //
395 // Server nodes have nothing to lose here. Nothing on a node resolves a
396 // mesh name: yubaba binds a literal 100.64.0.0/10 address, the machine
397 // TOMLs carry literal IPs, and kamaji reaches its peers over a unix socket.
398 // MagicDNS buys a convenience we never use, at the cost of a node that can
399 // permanently strand itself.
400 [
401 " - curl -fsSL https://tailscale.com/install.sh | sh".to_string(),
402 format!(" - tailscale up{mesh_login_server_arg} --auth-key={preauth_key} --advertise-tags={tags} --accept-dns=false"),
403 " - ufw allow in on tailscale0 to any port 7443".to_string(),
404 ]
405 .join("\n")
406}
407
408/// Build the coordinator pre-stage block for `runcmd` (R330-F28 #15). Emitted
409/// only for STANDALONE nodes (no preauth). cloud-init runs unsandboxed at first
410/// boot, so it lays down the headscale systemd unit + opens ufw 80/443 (the LE
411/// HTTP-01 challenge + the headscale `listen_addr :443`). yubaba runs under
412/// `ProtectSystem=strict` and cannot write `/etc/systemd/system` or `/etc/ufw`,
413/// so `yah mesh bootstrap` only downloads the headscale binary, writes config,
414/// and `systemctl enable --now headscale` against this pre-staged unit.
415///
416/// The unit's `ExecStart` must match yubaba's `DEFAULT_HEADSCALE_DIR`
417/// (`/var/lib/yah-cloud/headscale` — under the systemd StateDirectory, writable
418/// at runtime; see R330-F28 #14). Kept colon-space-free so the bare YAML scalar
419/// stays a string (#12). `enable` (not `--now`) here: the binary + config don't
420/// exist until bootstrap, so we only wire it for boot, not start it now.
421fn build_coordinator_prestage_block() -> String {
422 let unit = "[Unit]\\n\
423 Description=Headscale coordinator (yah-managed)\\n\
424 After=network-online.target\\n\\n\
425 [Service]\\n\
426 ExecStart=/var/lib/yah-cloud/headscale/headscale serve --config /var/lib/yah-cloud/headscale/config.yaml\\n\
427 Restart=on-failure\\n\
428 RestartSec=5\\n\\n\
429 [Install]\\n\
430 WantedBy=multi-user.target\\n";
431 [
432 format!(" - sh -c 'printf \"{unit}\" > /etc/systemd/system/headscale.service'"),
433 " - systemctl enable headscale".to_string(),
434 " - ufw allow 80".to_string(),
435 " - ufw allow 443".to_string(),
436 ]
437 .join("\n")
438}
439
440/// Look for an unsubstituted placeholder of the form `{{NAME}}` (no spaces inside braces).
441/// Documentation comments deliberately use `{{ NAME }}` (with spaces) so they survive rendering.
442fn find_unsubstituted(s: &str) -> Option<&str> {
443 let mut cursor = 0;
444 while let Some(start_off) = s[cursor..].find("{{") {
445 let start = cursor + start_off;
446 let after = &s[start + 2..];
447 let end_off = after.find("}}")?;
448 let inner = &after[..end_off];
449 if !inner.is_empty() && !inner.starts_with(' ') && !inner.ends_with(' ') {
450 return Some(&s[start..start + 2 + end_off + 2]);
451 }
452 cursor = start + 2 + end_off + 2;
453 }
454 None
455}
456
457#[cfg(test)]
458mod tests {
459 use super::*;
460 use crate::config::{BucketSpec, MachineConfig};
461 use std::path::Path;
462
463 fn sample_machine() -> MachineConfig {
464 MachineConfig {
465 name: "noisetable-pdx-1".into(),
466 provider: "hetzner".into(),
467 location: Some("pdx".into()),
468 server_type: Some("cpx22".into()),
469 hosts_mirrors: vec!["noisetable".into(), "yah".into()],
470 mesh_tags: vec!["tag:region-pdx".into(), "tag:tier-t2".into()],
471 region: None,
472 zone: None,
473 arch: None,
474 bucket: Some(BucketSpec {
475 name: "noisetable-assets-pdx-1".into(),
476 public_read: false,
477 }),
478 vendor: None,
479 nickname: None,
480 legacy_hostkey_fingerprint: None,
481 registration: Default::default(),
482 ssh_keys: vec![],
483 cloudflared: None,
484 hosts_operator_bridge: false,
485 connect: None,
486 allocatable: None,
487 taints: vec![],
488 }
489 }
490
491 fn minimal_input(machine: &MachineConfig) -> RenderInput<'_> {
492 RenderInput {
493 machine,
494 yubaba_url: "https://example.com/yah-yubaba".into(),
495 yubaba_sha256: "deadbeef".into(),
496 yubaba_channel: DEFAULT_YUBABA_CHANNEL.into(),
497 // Default: standalone (no join block). Tests that exercise the
498 // mesh-join path set `headscale_preauth_key = Some(...)`.
499 headscale_preauth_key: None,
500 mesh_url: None,
501 cloudflared_token: None,
502 yubaba_cosign_identity_regexp: None,
503 }
504 }
505
506 #[test]
507 fn render_substitutes_all_placeholders() {
508 let machine = sample_machine();
509 // Enable operator bridge so tailscale content (preauth key, tags) is emitted.
510 let mut input = minimal_input(&machine);
511 input.headscale_preauth_key = Some("tskey-test".into());
512 let out = render(DEFAULT_TEMPLATE, &input).unwrap();
513 assert!(out.contains("noisetable-pdx-1"));
514 assert!(out.contains("https://example.com/yah-yubaba"));
515 assert!(out.contains("deadbeef"));
516 assert!(out.contains(DEFAULT_YUBABA_CHANNEL));
517 assert!(out.contains("apt-get install -y containerd"));
518 assert!(out.contains("tskey-test"));
519 assert!(out.contains("tag:region-pdx,tag:tier-t2"));
520 // Real placeholders must all be substituted.
521 // Documentation {{ KEY }} (with inner spaces) is allowed to survive.
522 assert!(find_unsubstituted(&out).is_none());
523 }
524
525 #[test]
526 fn render_with_mesh_url_adds_login_server() {
527 let machine = sample_machine();
528 let mut input = minimal_input(&machine);
529 input.mesh_url = Some("https://mesh.example.com".into());
530 input.headscale_preauth_key = Some("tskey-test".into());
531 let out = render(DEFAULT_TEMPLATE, &input).unwrap();
532 assert!(out.contains("--login-server https://mesh.example.com"));
533 assert!(find_unsubstituted(&out).is_none());
534 }
535
536 #[test]
537 fn render_without_mesh_url_no_login_server() {
538 let machine = sample_machine();
539 let mut input = minimal_input(&machine);
540 input.headscale_preauth_key = Some("tskey-test".into());
541 let out = render(DEFAULT_TEMPLATE, &input).unwrap();
542 // Without a mesh_url the MESH_LOGIN_SERVER_ARG substitutes to empty string,
543 // so the tailscale up line should not contain a --login-server=https:// arg.
544 assert!(!out.contains("--login-server https://"));
545 assert!(find_unsubstituted(&out).is_none());
546 }
547
548 #[test]
549 fn render_with_placeholders_for_dry_run() {
550 let machine = sample_machine();
551 let input = RenderInput {
552 machine: &machine,
553 yubaba_url: PLACEHOLDER_YUBABA_URL.into(),
554 yubaba_sha256: PLACEHOLDER_YUBABA_SHA256.into(),
555 yubaba_channel: DEFAULT_YUBABA_CHANNEL.into(),
556 // A preauth key present → join block emitted, so the placeholder appears in output.
557 headscale_preauth_key: Some(PLACEHOLDER_PREAUTH_KEY.into()),
558 mesh_url: None,
559 cloudflared_token: None,
560 yubaba_cosign_identity_regexp: None,
561 };
562 let out = render(DEFAULT_TEMPLATE, &input).unwrap();
563 assert!(out.contains(PLACEHOLDER_YUBABA_URL));
564 assert!(out.contains(PLACEHOLDER_YUBABA_SHA256));
565 assert!(out.contains(PLACEHOLDER_PREAUTH_KEY));
566 }
567
568 #[test]
569 fn render_stays_under_hetzner_user_data_cap() {
570 // Backward-compat alias — see renders_under_user_data_cap below.
571 renders_under_user_data_cap();
572 }
573
574 #[test]
575 fn renders_under_user_data_cap() {
576 // Hetzner refuses user_data > 32 KiB (R040-F11). Worst-case: all blocks
577 // enabled (cloudflared + operator_bridge), long URL and sha, full tag list.
578 let machine = sample_machine();
579 let input = RenderInput {
580 machine: &machine,
581 yubaba_url: "https://github.com/yah-ai/yah/releases/download/v0.7.0/yah-yubaba-v0.7.0-x86_64-unknown-linux-musl.tar.gz".into(),
582 yubaba_sha256: "0".repeat(64),
583 yubaba_channel: "stable".into(),
584 headscale_preauth_key: Some("tskey-auth-keylongenoughforrealism123456".into()),
585 mesh_url: Some("https://mesh.example.com".into()),
586 cloudflared_token: Some(PLACEHOLDER_CLOUDFLARED_TOKEN.into()),
587 // Worst-case includes the cosign block so the 32 KiB cap test
588 // covers the bootstrap-channel signing path too (W203 §1.4).
589 yubaba_cosign_identity_regexp: Some("^https://github\\.com/yah-ai/yah/".into()),
590 };
591 let out = render(DEFAULT_TEMPLATE, &input).unwrap();
592 assert!(
593 out.len() < 32 * 1024,
594 "rendered cloud-init is {} bytes (Hetzner cap is 32 KiB)",
595 out.len()
596 );
597 }
598
599 #[test]
600 fn render_rejects_unknown_placeholder() {
601 let machine = sample_machine();
602 let input = RenderInput {
603 machine: &machine,
604 yubaba_url: "x".into(),
605 yubaba_sha256: "y".into(),
606 yubaba_channel: "stable".into(),
607 headscale_preauth_key: None,
608 mesh_url: None,
609 cloudflared_token: None,
610 yubaba_cosign_identity_regexp: None,
611 };
612 let bad = "foo: {{NOT_A_KEY}}\n";
613 let err = render(bad, &input).unwrap_err().to_string();
614 assert!(err.contains("{{NOT_A_KEY}}"), "unexpected error: {err}");
615 }
616
617 #[test]
618 fn render_falls_back_to_machine_tag_when_mesh_tags_empty() {
619 let mut machine = sample_machine();
620 machine.mesh_tags = vec![];
621 let mut input = minimal_input(&machine);
622 input.headscale_preauth_key = Some("tskey-test".into());
623 let out = render(DEFAULT_TEMPLATE, &input).unwrap();
624 assert!(out.contains("--advertise-tags=tag:noisetable-pdx-1"));
625 }
626
627 #[test]
628 fn load_template_uses_workspace_override_when_present() {
629 let dir = tempfile::tempdir().unwrap();
630 let custom_dir = crate::paths::cloud_init_dir(dir.path());
631 std::fs::create_dir_all(&custom_dir).unwrap();
632 std::fs::write(
633 custom_dir.join("mirror.yml"),
634 "#cloud-config\ncustom: true\n",
635 )
636 .unwrap();
637 let loaded = load_template(dir.path()).unwrap();
638 assert!(loaded.contains("custom: true"));
639 }
640
641 #[test]
642 fn load_template_falls_back_to_default_when_absent() {
643 let dir = tempfile::tempdir().unwrap();
644 let loaded = load_template(dir.path()).unwrap();
645 assert_eq!(loaded, DEFAULT_TEMPLATE);
646 }
647
648 #[test]
649 fn render_preserves_documentation_comments() {
650 let machine = sample_machine();
651 let input = minimal_input(&machine);
652 let out = render(DEFAULT_TEMPLATE, &input).unwrap();
653 // The header comment uses `{{ KEY }}` (with spaces) so it survives the
654 // `{{KEY}}` (no-spaces) substitution and stays readable.
655 assert!(out.contains("{{ MACHINE_NAME }}"));
656 assert!(out.contains("{{ YAH_YUBABA_URL }}"));
657 assert!(out.contains("{{ YAH_YUBABA_SHA256 }}"));
658 }
659
660 #[test]
661 fn render_with_cloudflared_token_emits_install_block() {
662 let machine = sample_machine();
663 let mut input = minimal_input(&machine);
664 input.cloudflared_token = Some("tok_abc123".into());
665 let out = render(DEFAULT_TEMPLATE, &input).unwrap();
666 // R330-B29: token is a POSITIONAL arg, NOT a `--token` flag. The flag
667 // form fails arg-parsing and never creates cloudflared.service.
668 assert!(
669 out.contains("cloudflared service install tok_abc123"),
670 "install line missing"
671 );
672 assert!(
673 !out.contains("service install --token"),
674 "must not use the bogus --token flag (R330-B29)"
675 );
676 assert!(
677 out.contains("systemctl enable --now cloudflared"),
678 "enable line missing"
679 );
680 assert!(out.contains("pkg.cloudflare.com"), "apt-repo setup missing");
681 assert!(find_unsubstituted(&out).is_none());
682 }
683
684 #[test]
685 fn render_without_cloudflared_token_omits_install_block() {
686 let machine = sample_machine();
687 let input = minimal_input(&machine);
688 let out = render(DEFAULT_TEMPLATE, &input).unwrap();
689 // Template header mentions "cloudflared service install" in prose; check
690 // for the token-bearing form which is only present in the actual runcmd.
691 assert!(
692 !out.contains("cloudflared service install --token"),
693 "install line should be absent"
694 );
695 assert!(
696 !out.contains("pkg.cloudflare.com"),
697 "apt-repo setup should be absent"
698 );
699 assert!(find_unsubstituted(&out).is_none());
700 }
701
702 #[test]
703 fn operator_bridge_block_emitted_when_enabled() {
704 let machine = sample_machine();
705 let mut input = minimal_input(&machine);
706 input.headscale_preauth_key = Some("tskey-test".into());
707 let out = render(DEFAULT_TEMPLATE, &input).unwrap();
708 assert!(
709 out.contains("tailscale.com/install.sh"),
710 "tailscale install missing"
711 );
712 assert!(out.contains("tailscale up"), "tailscale up missing");
713 assert!(
714 out.contains("ufw allow in on tailscale0"),
715 "ufw tailscale rule missing"
716 );
717 assert!(find_unsubstituted(&out).is_none());
718 }
719
720 /// R624-B1: a provisioned node must never let tailscaled own
721 /// `/etc/resolv.conf`.
722 ///
723 /// Accepting MagicDNS points the resolver at 100.100.100.100, which only
724 /// answers while tailscaled is up — so a tailscaled that is down cannot
725 /// resolve its control server and can never come up again. That deadlock
726 /// took a raft voter off the mesh for 30+ hours. This assertion is the
727 /// guard: dropping the flag silently re-arms the trap on every node
728 /// provisioned afterwards, and the damage only shows up at the next reboot.
729 #[test]
730 fn tailscale_join_refuses_magicdns_so_a_node_cannot_strand_itself() {
731 let machine = sample_machine();
732 let mut input = minimal_input(&machine);
733 input.headscale_preauth_key = Some("tskey-test".into());
734 let out = render(DEFAULT_TEMPLATE, &input).unwrap();
735 assert!(
736 out.contains("--accept-dns=false"),
737 "tailscale up MUST pass --accept-dns=false — without it tailscaled \
738 rewrites /etc/resolv.conf to MagicDNS and a node that boots with \
739 tailscaled down can never resolve its control server again \
740 (R624-B1). Rendered:\n{out}"
741 );
742 }
743
744 #[test]
745 fn operator_bridge_block_omitted_when_disabled() {
746 let machine = sample_machine();
747 let input = minimal_input(&machine);
748 let out = render(DEFAULT_TEMPLATE, &input).unwrap();
749 assert!(
750 !out.contains("tailscale.com/install.sh"),
751 "tailscale install should be absent"
752 );
753 // Template header mentions "tailscale up" in prose; check for the auth-key
754 // bearing form which is only present in the actual runcmd block.
755 assert!(
756 !out.contains("tailscale up --auth-key"),
757 "tailscale join should be absent"
758 );
759 assert!(find_unsubstituted(&out).is_none());
760 }
761
762 /// R330-F28 pothole #12: the from-zero validation found that cloud-init's
763 /// `runcmd` is emitted as a sequence of BARE (unquoted) YAML scalars, so a
764 /// `: ` (colon-space) anywhere in a command — e.g. the cosign block's old
765 /// `echo "unsupported arch: $ARCH"` — makes the YAML parser read the entry
766 /// as a `{key: value}` mapping. cloud-init's `shellify` then rejects the
767 /// dict and SKIPS THE ENTIRE runcmd block, so yubaba never installs. This
768 /// test parses the worst-case rendered cloud-init as real YAML and asserts
769 /// every runcmd entry is a string, catching any future colon-space footgun.
770 #[test]
771 fn rendered_runcmd_entries_are_all_strings() {
772 let machine = sample_machine();
773 // Worst case: every conditional block present (cosign + cloudflared +
774 // operator-bridge), since that's where dynamic strings are injected.
775 let input = RenderInput {
776 machine: &machine,
777 yubaba_url: "https://cdn.yah.dev/yubaba/0.8.13/x86_64-unknown-linux-musl/yah-yubaba-x86_64-unknown-linux-musl.tar.gz".into(),
778 yubaba_sha256: "0".repeat(64),
779 yubaba_channel: "stable".into(),
780 headscale_preauth_key: Some("tskey-auth-keylongenoughforrealism123456".into()),
781 mesh_url: Some("https://cloud.mesh.yah.dev".into()),
782 cloudflared_token: Some("tok_abc123".into()),
783 yubaba_cosign_identity_regexp: Some(r"^https://github\.com/yah-ai/yah/".into()),
784 };
785 let out = render(DEFAULT_TEMPLATE, &input).unwrap();
786 let doc: serde_yaml::Value =
787 serde_yaml::from_str(&out).expect("rendered cloud-init must be valid YAML");
788 let runcmd = doc
789 .get("runcmd")
790 .and_then(|v| v.as_sequence())
791 .expect("cloud-init must have a runcmd sequence");
792 assert!(!runcmd.is_empty(), "runcmd should not be empty");
793 for (i, entry) in runcmd.iter().enumerate() {
794 assert!(
795 entry.is_string(),
796 "runcmd[{i}] parsed as {entry:?}, not a string — a `: ` (colon-space) \
797 in a bare YAML scalar turned it into a mapping (pothole #12)"
798 );
799 }
800 }
801
802 /// R330-F28 #13: the yubaba-port firewall rule keys off mesh role. A
803 /// JOINING node (preauth present) denies public 7443 (mesh-only via the
804 /// tailscale0 allow in the join block); a STANDALONE coordinator (no
805 /// preauth) allows public 7443 so the operator can attach + bootstrap it
806 /// before any mesh exists.
807 #[test]
808 fn ufw_yubaba_rule_keys_off_mesh_role() {
809 let machine = sample_machine();
810
811 // Standalone: allow public 7443.
812 let standalone = minimal_input(&machine);
813 let out = render(DEFAULT_TEMPLATE, &standalone).unwrap();
814 assert!(
815 out.contains("ufw allow 7443"),
816 "standalone must allow public 7443"
817 );
818 assert!(
819 !out.contains("ufw deny 7443"),
820 "standalone must not deny 7443"
821 );
822
823 // Joining: deny public 7443 (join block adds the tailscale0 allow).
824 let mut joining = minimal_input(&machine);
825 joining.headscale_preauth_key = Some("tskey-test".into());
826 let out = render(DEFAULT_TEMPLATE, &joining).unwrap();
827 assert!(
828 out.contains("ufw deny 7443"),
829 "joining node must deny public 7443"
830 );
831 assert!(
832 !out.contains("ufw allow 7443"),
833 "joining node must not allow public 7443"
834 );
835 assert!(
836 out.contains("ufw allow in on tailscale0"),
837 "joining node needs the tailscale0 allow"
838 );
839 }
840
841 /// R330-F28 #15: a STANDALONE coordinator pre-stages the headscale unit +
842 /// opens ufw 80/443 via cloud-init (yubaba's sandbox can't). A JOINING node
843 /// must never do this. Both renders must stay valid, parseable YAML.
844 #[test]
845 fn coordinator_prestage_only_for_standalone() {
846 let machine = sample_machine();
847
848 // Standalone: pre-stage present.
849 let standalone = minimal_input(&machine);
850 let out = render(DEFAULT_TEMPLATE, &standalone).unwrap();
851 assert!(
852 out.contains("/etc/systemd/system/headscale.service"),
853 "standalone must stage the headscale unit"
854 );
855 assert!(
856 out.contains("/var/lib/yah-cloud/headscale/headscale serve"),
857 "unit ExecStart must match DEFAULT_HEADSCALE_DIR"
858 );
859 assert!(
860 out.contains("ufw allow 80"),
861 "standalone must open ufw 80 (LE HTTP-01)"
862 );
863 assert!(
864 out.contains("ufw allow 443"),
865 "standalone must open ufw 443 (headscale)"
866 );
867 // Must stay parseable YAML with all-string runcmd entries.
868 let doc: serde_yaml::Value =
869 serde_yaml::from_str(&out).expect("standalone cloud-init must be valid YAML");
870 for entry in doc["runcmd"].as_sequence().expect("runcmd seq") {
871 assert!(
872 entry.is_string(),
873 "standalone runcmd entry parsed as {entry:?}, not a string"
874 );
875 }
876
877 // Joining: no pre-stage.
878 let mut joining = minimal_input(&machine);
879 joining.headscale_preauth_key = Some("tskey-test".into());
880 let out = render(DEFAULT_TEMPLATE, &joining).unwrap();
881 assert!(
882 !out.contains("/etc/systemd/system/headscale.service"),
883 "joining node must not stage a headscale unit"
884 );
885 assert!(
886 !out.contains("ufw allow 443"),
887 "joining node must not open 443"
888 );
889 }
890
891 #[test]
892 fn render_yubaba_channel_in_output() {
893 let machine = sample_machine();
894 let mut input = minimal_input(&machine);
895 input.yubaba_channel = "beta".into();
896 let out = render(DEFAULT_TEMPLATE, &input).unwrap();
897 // Channel rides a systemd drop-in (Environment=YUBABA_CHANNEL=…), not a
898 // --channel flag (the ExecStart bakes defaults; the drop-in tunes it).
899 assert!(
900 out.contains("YUBABA_CHANNEL=beta"),
901 "yubaba channel missing"
902 );
903 // containerd is installed unpinned (R330-T9).
904 assert!(
905 out.contains("apt-get install -y containerd\n"),
906 "containerd install missing"
907 );
908 assert!(find_unsubstituted(&out).is_none());
909 }
910
911 #[test]
912 fn embedded_template_matches_workspace_canonical() {
913 // Drift test: .yah/infra/cloud-init/mirror.yml must stay in sync with
914 // the embedded DEFAULT_TEMPLATE (crates/yah/cloud/templates/mirror.yml).
915 // Edit both files together; this test catches divergence.
916 let workspace_root = Path::new(env!("CARGO_MANIFEST_DIR"))
917 .ancestors()
918 .find(|p| p.join(".yah").is_dir())
919 .expect("workspace root not found from CARGO_MANIFEST_DIR");
920 let canonical_path = crate::paths::cloud_init_template(workspace_root);
921 if canonical_path.exists() {
922 let canonical =
923 std::fs::read_to_string(&canonical_path).expect("reading workspace canonical");
924 assert_eq!(
925 canonical.trim_end(),
926 DEFAULT_TEMPLATE.trim_end(),
927 ".yah/infra/cloud-init/mirror.yml drifted from crates/yah/cloud/templates/mirror.yml — edit both files together"
928 );
929 }
930 // If the file doesn't exist yet, the test passes (bootstrap case).
931 }
932
933 #[test]
934 fn cosign_block_shell_form_well_quoted() {
935 // YAML parsability spot-check: the block uses double-quoted strings inside
936 // a single-quoted `sh -c '...'`. Confirm no apostrophes leak into the
937 // single-quoted body and the case/esac terminators are present.
938 let machine = sample_machine();
939 let mut input = minimal_input(&machine);
940 input.yubaba_cosign_identity_regexp = Some("^https://github\\.com/yah-ai/yah/".into());
941 let out = render(DEFAULT_TEMPLATE, &input).unwrap();
942 let sh_line = out
943 .lines()
944 .find(|l| l.contains("sh -c") && l.contains("cosign"))
945 .expect("cosign install sh -c line missing");
946 // Body of the sh -c is enclosed in a single quoted region; we
947 // intentionally use double-quotes around shell vars inside. If a stray
948 // apostrophe slipped through we'd see an odd count of `'`.
949 let single_quotes = sh_line.matches('\'').count();
950 assert!(
951 single_quotes == 2,
952 "expected exactly 2 enclosing single quotes in sh -c body, found {single_quotes}: {sh_line}"
953 );
954 assert!(sh_line.contains("case \"$ARCH\""), "case opener missing");
955 assert!(sh_line.contains("esac"), "case terminator missing");
956 // The block must be a sequence of valid `runcmd` entries: each line
957 // starts with ` - ` (two-space indent + dash + space) so cloud-init
958 // parses it as a YAML list item.
959 for line in out.lines().filter(|l| l.contains("cosign")) {
960 // Skip the header comment lines (start with `#`).
961 let stripped = line.trim_start();
962 if stripped.starts_with('#') || stripped.is_empty() {
963 continue;
964 }
965 assert!(
966 line.starts_with(" - "),
967 "cosign block line is not a runcmd list entry: {line:?}"
968 );
969 }
970 }
971
972 /// R605-F1: a fleet whose releases are cut on QED verifies against a
973 /// pinned public key, not a Fulcio certificate identity. The `.cert`
974 /// fetch must drop out with it — the release publishes no `.cert`, so
975 /// leaving the curl in place would fail the boot before cosign ever runs.
976 #[test]
977 fn render_with_key_trust_emits_key_verify_and_no_cert_fetch() {
978 let machine = sample_machine();
979 let mut input = minimal_input(&machine);
980 input.yubaba_url = "https://cdn.yah.dev/yubaba/0.9.0/x86_64-unknown-linux-musl/yah-yubaba-x86_64-unknown-linux-musl.tar.gz".into();
981 input.yubaba_cosign_identity_regexp =
982 Some("key:https://cdn.yah.dev/keys/yah-release.pub".into());
983 let out = render(DEFAULT_TEMPLATE, &input).unwrap();
984
985 assert!(
986 out.contains(
987 "cosign verify-blob --key 'https://cdn.yah.dev/keys/yah-release.pub' \
988 --signature /tmp/yah-yubaba.tar.gz.sig"
989 ),
990 "key-based verify-blob line missing:\n{out}"
991 );
992 assert!(
993 !out.contains("--certificate-identity-regexp"),
994 "keyless flags must not survive into a key-trust render"
995 );
996 assert!(
997 !out.contains(&format!("{}.cert", input.yubaba_url)),
998 "key-based signatures have no .cert sibling to fetch"
999 );
1000 // Still a well-formed runcmd sequence.
1001 for line in out.lines().filter(|l| l.contains("cosign")) {
1002 let stripped = line.trim_start();
1003 if stripped.starts_with('#') || stripped.is_empty() {
1004 continue;
1005 }
1006 assert!(
1007 line.starts_with(" - "),
1008 "cosign block line is not a runcmd list entry: {line:?}"
1009 );
1010 // R330-F28 pothole #12: a `: ` anywhere makes cloud-init read the
1011 // entry as a YAML mapping and skip the whole runcmd block.
1012 assert!(
1013 !line.contains(": "),
1014 "colon-space in runcmd entry would break cloud-init parsing: {line:?}"
1015 );
1016 }
1017 }
1018
1019 #[test]
1020 fn render_with_cosign_identity_emits_verify_block() {
1021 let machine = sample_machine();
1022 let mut input = minimal_input(&machine);
1023 input.yubaba_url = "https://cdn.yah.dev/yubaba/0.9.0/x86_64-unknown-linux-musl/yah-yubaba-x86_64-unknown-linux-musl.tar.gz".into();
1024 input.yubaba_cosign_identity_regexp = Some("^https://github\\.com/yah-ai/yah/".into());
1025 let out = render(DEFAULT_TEMPLATE, &input).unwrap();
1026 assert!(
1027 out.contains("cosign verify-blob --certificate-identity-regexp '^https://github\\.com/yah-ai/yah/'"),
1028 "verify-blob line missing or identity-regexp not threaded"
1029 );
1030 assert!(out.contains(COSIGN_OIDC_ISSUER), "oidc-issuer flag missing");
1031 // sig + cert sibling URLs are derived by suffixing the tarball URL.
1032 assert!(
1033 out.contains(&format!("{}.sig", input.yubaba_url)),
1034 ".sig sibling URL missing"
1035 );
1036 assert!(
1037 out.contains(&format!("{}.cert", input.yubaba_url)),
1038 ".cert sibling URL missing"
1039 );
1040 // cosign install is pinned to a specific release version (no `latest`).
1041 assert!(
1042 out.contains(&format!(
1043 "/releases/download/{}/cosign-linux-",
1044 COSIGN_VERSION
1045 )),
1046 "pinned cosign release URL missing"
1047 );
1048 // R330-F22: cosign binary itself is sha256-pinned (both arches).
1049 // Bumping COSIGN_VERSION without bumping the sha256s should break this
1050 // assertion before it breaks a boot.
1051 assert!(
1052 out.contains(COSIGN_SHA256_AMD64),
1053 "cosign amd64 sha256 pin missing from rendered block"
1054 );
1055 assert!(
1056 out.contains(COSIGN_SHA256_ARM64),
1057 "cosign arm64 sha256 pin missing from rendered block"
1058 );
1059 assert!(
1060 out.contains("sha256sum -c -"),
1061 "cosign binary sha256 verify line missing"
1062 );
1063 // sha256 verify still runs in parallel — belt + suspenders during rollout.
1064 assert!(
1065 out.contains("sha256sum -c -"),
1066 "sha256 verify dropped — should run in parallel with cosign"
1067 );
1068 assert!(find_unsubstituted(&out).is_none());
1069 }
1070
1071 #[test]
1072 fn render_without_cosign_identity_omits_verify_block() {
1073 // Byte-equivalence check against today's sha256-only render: when
1074 // yubaba_cosign_identity_regexp is None, no cosign content appears.
1075 let machine = sample_machine();
1076 let input = minimal_input(&machine);
1077 let out = render(DEFAULT_TEMPLATE, &input).unwrap();
1078 // Comment-line in mirror.yml mentions "cosign verify-blob" in prose;
1079 // check for the flag-bearing form which is only emitted when the
1080 // verify-blob runcmd block actually runs.
1081 assert!(
1082 !out.contains("cosign verify-blob --certificate-identity-regexp"),
1083 "cosign block should be absent when identity_regexp is None"
1084 );
1085 assert!(
1086 !out.contains("/sigstore/cosign/releases/download/"),
1087 "cosign install line should be absent when identity_regexp is None"
1088 );
1089 // sha256 verify is the trust gate in this mode.
1090 assert!(
1091 out.contains("sha256sum -c -"),
1092 "sha256 verify must remain in the no-cosign render path"
1093 );
1094 assert!(find_unsubstituted(&out).is_none());
1095 }
1096
1097 #[test]
1098 fn compute_yubaba_sha256_matches_known_value() {
1099 // sha256("hello") = 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824
1100 let dir = tempfile::tempdir().unwrap();
1101 let bin_path = dir.path().join("yah-yubaba");
1102 std::fs::write(&bin_path, b"hello").unwrap();
1103 let sha = compute_yubaba_sha256(&bin_path).unwrap();
1104 assert_eq!(
1105 sha,
1106 "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"
1107 );
1108 }
1109}