cloud/mesh.rs
1//! Headscale API client and configuration helpers for `yah mesh` operations.
2//!
3//! The mesh layer manages the Headscale coordinator that all yah-provisioned
4//! machines join via Tailscale. Phase 1a runs Headscale on the operator's camp
5//! (bootstrap coordinator); Phase 1b promotes it to a cluster machine (R040-F19);
6//! Phase 2 adds openraft-based HA (R040-F20/F21).
7//!
8//! Consumers:
9//! - `app/yah/cli/src/mesh.rs` — `yah mesh start/status/backup/restore`
10//! - `app/yah/cli/src/cloud.rs` — `yah cloud machine provision` (auto-generates
11//! a Headscale preauth key when `mesh-url` is set in the vault)
12//!
13//! @yah:relay(R861, "Reconcile an appliance's own API objects: headscale ACLs, users and preauth keys as declared config")
14//! @yah:at(2026-09-04T21:07:28Z)
15//! @yah:status(open)
16//! @yah:assignee(agent:bundle-anthropic-ashguard)
17//! @yah:gotcha("NOT A NEW CONCEPT — this is the DOMAIN-OBJECT half of a pattern yah already has twice. Framing that produced it (operator, 2026-09-04): asked what \"manage headscale on kubernetes with a rust controller\" looks like, the answer is a CRD + controller for \"deployment instances, users, and pre-auth keys\". yah ALREADY HAS the CRD half (Workload/WorkloadSpec + workload.toml + .yah/schema/workload.toml.schema.json + generated TS) and the controller half (the `Reconciler` trait at oss/yubaba/crates/cloud/src/reconciler/mod.rs:612, ~20 implementations dispatched by `kind`). What is missing is reconciling things INSIDE an appliance rather than the appliance itself. So: no new noun, no operator framework — one more Reconciler implementation, owning headscale's API objects the way cloudflare_worker.rs owns what lives in a Cloudflare account.")
18//! @yah:gotcha("THE EVIDENCE THIS IS A LIVE GAP, not a speculative nicety. (1) `headscale-preauth-key` is classified `Band::Automatable` in oss/yah-base/crates/keys/src/spec.rs:768 and its own purpose text says outright \"Automatable: headscale-api-key mints these, and does so per-machine when mesh-url is configured\" — the credential system already knows it should not be a human-held static secret. (2) That automation EXISTS but only ad hoc, in one place, at one moment: provision-time per-machine minting via headscale-api-key. There is no reconciled desired state. (3) `acls.yaml` (77 bytes, mtime Jun 22) sits in /var/lib/yah-cloud/headscale/ and is replicated by NOTHING — litestream carries only headscale.db — so it is failover state nobody enumerated (see R858-T2). Declaring ACLs and reconciling them is what stops that file mattering at all.")
19//!
20//! @yah:ticket(R861-T1, "Establish whether headscale reads acls.yaml or the DB, then declare ACLs as reconciled config")
21//! @yah:status(review)
22//! @yah:at(2026-09-04T22:48:06Z)
23//! @yah:assignee(agent:bundle-anthropic-glimmerstone)
24//! @yah:parent(R861)
25//! @yah:next("THE PATTERN TO COPY IS cloudflare_worker.rs, not a new abstraction: validate declared config fully BEFORE any API call (the R330-B5 fail-fast discipline the reconciler docs already name), then list-first/idempotent writes against headscale's admin API using the existing `headscale-api-key` slot. Consumers of that slot are already listed in the credential spec: oss/yubaba/crates/cloud/src/mesh.rs, app/yah/cli/src/mesh.rs, crates/yah/cloud-client/src/lib.rs.")
26//! @yah:gotcha("START WITH THE FACT, NOT THE DESIGN. headscale 0.23 can source policy from a FILE or from the DATABASE depending on its policy mode, and the config block read on us-west-001 2026-09-04 showed no `policy:` section at all — so acls.yaml may be live or may be vestigial. `grep -i policy /var/lib/yah-cloud/headscale/config.yaml` settles it in one look. If vestigial: delete the file so the next reader does not re-discover the same question, and this ticket collapses to the users/preauth half. If live: it is unreplicated failover state today and declaring it is the fix.")
27//! @yah:gotcha("PHASE 1 SETTLED — acls.yaml IS LIVE, NOT VESTIGIAL. Measured over SSH on us-west-001 (15.204.89.240) 2026-09-04 by @Ashguard:griffin. /var/lib/yah-cloud/headscale/config.yaml lines 32-34 read exactly `policy:` / ` mode: file` / ` path: /var/lib/yah-cloud/headscale/acls.yaml`. The earlier read that reported no `policy:` section was wrong — the file is 1060 bytes and the block is there. acls.yaml is 77 bytes, mtime Jun 22, and contains the permissive HuJSON default `{\"acls\":[{\"action\":\"accept\",\"src\":[\"*\"],\"dst\":[\"*:*\"]}]}`. In-tree agrees: ALL THREE renderers emit the same three lines — crate::mesh::generate_headscale_config (oss/yubaba/crates/cloud/src/mesh.rs), generate_remote_headscale_config (oss/yubaba/crates/yubaba/src/lib.rs:4729ff) and generate_bootstrap_headscale_config (same file, :5134ff). So file mode is the DESIRED state today, not drift. Nothing was deleted; the vestigial branch of this ticket does not apply.")
28//! @yah:gotcha("POLICY MODE BOUNDS WHAT ANY RECONCILER CAN DO ABOUT ACLS — both halves measured against the live v0.23.0 coordinator 2026-09-04, not inferred. (1) GET /api/v1/policy WORKS IN FILE MODE: authenticated with the vault's headscale-api-key against https://cloud.mesh.yah.dev it returned HTTP 200 and {\"policy\": \"<the acls.yaml bytes>\", \"updatedAt\": null}. (2) PUT /api/v1/policy IS REFUSED IN FILE MODE: the pinned binary carries the string \"This command only works when the acl.policy_mode is set to \" and \", and the policy will be stored in the database.\" — headscale only accepts a policy write in database mode, because in file mode the file is the source of truth and a write would be overwritten at the next reload. CONSEQUENCE, and it is the design of the ACL step: declared-vs-live drift is ALWAYS DETECTABLE, and correctable only on a database-mode coordinator. Also verified from the same binary: /api/v1/user, /api/v1/user/{name}, /api/v1/preauthkey, /api/v1/preauthkey/expire, /api/v1/policy all exist; GET /api/v1/preauthkey?user=yah returned 200 with {\"preAuthKeys\":[{user,id,key,reusable,ephemeral,used,expiration,createdAt,aclTags}]} and 4 live keys. Coordinator has exactly one user, `yah`.")
29//! @yah:handoff("LANDED: HeadscaleReconciler, kind=\"headscale\" — one more Reconciler impl, cloudflare_worker.rs's shape, no new noun. NEW FILE oss/yubaba/crates/cloud/src/reconciler/headscale.rs (~700 lines incl. 17 tests). up() order: materialize() -> workload_kind agrees -> DeclaredHeadscale::load() validates EVERYTHING (R330-B5 fail-fast, nothing below runs until every field is checked) -> resolve base_url (declared server_url, else mesh-url/HEADSCALE_URL) + headscale-api-key/HEADSCALE_API_KEY -> users list-then-create (NEVER deletes: a headscale user owns the nodes registered under it) -> preauth keys list-then-mint-if-unsatisfied -> ACL compare-then-push. Returns RunningWorkload::adopted(WORKLOAD_KIND, role, None).with_notes(...); the minted key value never reaches a log line or a note.")
30//! @yah:handoff("CLIENT SURFACE ADDED to oss/yubaba/crates/cloud/src/mesh.rs (added alongside the peer hunks already in that file; nothing reverted). New types PreauthKeyRecord (with is_usable_at) and PreauthKeyRequest. New HeadscaleClient methods: create_user (POST /api/v1/user — deliberately does NOT swallow a conflict, since headscale answers 500 for an existing name with no discriminator, so a 500 here means something other than \"already there\"), list_preauth_keys (GET /api/v1/preauthkey?user=), create_preauth_key_with (the general mint), get_policy (GET /api/v1/policy), set_policy (PUT /api/v1/policy). The pre-existing create_preauth_key now delegates to create_preauth_key_with with its historical fixed shape (single-use, 1 hour) so every existing caller is behaviourally untouched. Parsing split into the free fn parse_preauth_key_list, following choose_user's precedent (this crate has no HTTP mock); entries missing id/user/key are DROPPED rather than defaulted, because a half-parsed record would read as \"no matching key exists\" and cause a redundant mint.")
31//! @yah:handoff("DECISION I MADE, since the brief left it open: declared config lives in the component's workload.toml under kind-specific tables ([headscale] with users / acl_policy / server_url, and [[headscale.preauth_keys]] with user / tags / reusable / ephemeral / ttl_hours / store_as), parsed ad hoc via toml::Value. This is exactly how cloudflare-worker already reads its [build] and [[bindings]] — the strong workload_spec::Workload types do not model per-kind tables, and I checked .yah/schema/workload.toml.schema.json: no branch of its root oneOf sets additionalProperties:false, so extra tables validate. CONSEQUENCE: oss/yah-base/crates/workload-spec/ was NOT touched, so NO emit-schemas and NO export-ts regen was needed or run. That also kept me clear of oss/yah-base/crates/keys/src/spec.rs, which I read (line 768's Band::Automatable classification) but did not modify, per the leader's read-only instruction — @Ashguard:polaris is live on it for R856-F2.")
32//! @yah:handoff("THE ACL STEP IS COMPARE-FIRST, AND THAT IS THE WHOLE POINT ON A FILE-MODE COORDINATOR. get_policy() -> policies_equivalent() -> only on drift does it set_policy(). Comparison is SEMANTIC, not byte: both sides are normalized from HuJSON to serde_json::Value and compared as values, so reformatting or re-commenting the declared file never triggers a spurious push and a genuinely different rule always does. There is no HuJSON crate in this workspace, so parse_hujson strips // and /* */ comments and trailing commas with string-literal tracking (a `//` or a comma inside a value is left alone — tested) and hands the rest to serde_json. On a database-mode coordinator the push lands and the policy ends up in headscale.db, which litestream already replicates — that is the moment acls.yaml stops being unreplicated failover state. On today's file-mode coordinator the push is refused by headscale and the reconciler surfaces that as an error naming the declared file's path and the mode flip that makes it pushable, rather than a silent no-op that reads like success.")
33//! @yah:handoff("DELIBERATELY NOT DONE, and it is the one operator call left: I did NOT flip the fleet's rendered policy.mode from file to database. It is a live-coordinator config change that reaches nodes only via a yubaba release + scripts/roll-node.sh, it touches all three renderers, and its correctness turns on what a database-mode headscale with no policy row does to an existing tailnet — which I did not measure and would not guess at fleet scale. It also sits squarely in the operator's stated R858 rehearsal (\"bring us-west-001 down and get a repaired headscale\"), so it wants that rehearsal rather than a reconciler's side effect. Until it flips, this reconciler makes ACL drift LOUD on the current file-mode box; after it flips, the same code makes ACLs actually reconciled and the file irrelevant. Nothing else about the reconciler changes either way.")
34//! @yah:handoff("WIRING (all additive, no rewrites): oss/yubaba/crates/cloud/src/reconciler/mod.rs gains `pub mod headscale;` and a re-export of HeadscaleReconciler + DeclaredHeadscale/DeclaredPolicy/DeclaredPreauthKey + WORKLOAD_KIND as HEADSCALE_WORKLOAD_KIND. oss/yubaba/crates/cloud/src/lib.rs: ONE additive name (HeadscaleReconciler) inserted into the existing `pub use reconciler::{...}` list — the single-line limit the leader set for that peer-owned file (@Ashguard:spade is live on it for R850); I touched nothing else there. Both dispatchers gain a \"headscale\" match arm next to \"cloudflare-worker\": app/yah/cli/src/cloud.rs:reconcile_component (~:7091) plus its import at ~:601, and app/yah/desktop/src/mirror_run.rs (~:988) plus its import at ~:168. Cleared with @Glimmerstone:vortex, whose R858-T1 courier (session:9f8108d4) is editing app/yah/cli/src/cloud.rs concurrently — my two regions do not overlap theirs (:1466, :4250-4310, :4871-4909, :7909-8006), and I told them line numbers below :7091 shift by 3.")
35//! @yah:verify("cargo build -p yah-cloud: clean (the 2 warnings are pre-existing unused imports in reconciler/mesofact_static.rs:240,245, not mine). cargo test --manifest-path oss/yubaba/Cargo.toml -p yah-cloud --lib = 1059 passed / 0 failed / 4 ignored, against a pre-change baseline of 1042 passed / 0 failed on the same crate — the delta is exactly the 17 new reconciler::headscale::tests, all green. Note yah-cloud is in the oss/yubaba workspace, not the root one: `cargo test -p yah-cloud` from the repo root fails with \"requires dev-dependencies and is not a member of the workspace\"; the --manifest-path form above is the one that runs. cargo check -p desktop: clean (9 pre-existing dead-code warnings). The 17 tests cover: full workload-dir load off disk incl. the HuJSON policy file; a preauth key naming an undeclared user (the R608-B19 typo class, which must fail BEFORE any user is created); tag prefix + lowercase rules; non-positive ttl; duplicate user; non-http server_url; a policy with no top-level `acls` array; a missing policy file naming the path it looked for; reformat-is-not-drift vs a-different-rule-is-drift against the exact bytes live on us-west-001; comment markers inside string values surviving the stripper; and expired / spent / reusable / never-expiring key usability.")
36//! @yah:verify("cargo check -p yah = exit 0, Finished clean, no error lines (warnings are the crate's pre-existing 19: unused imports Verdict / CommandFact / NodeId / store / Version and unused variables dt / config_path / acl_path / pid_path, plus dead-code fields — none in a file I touched). Re-run once after reflowing the two `use` blocks, so the green describes the final tree. NOT VERIFIED, STATED PLAINLY: the reconciler has never been executed against a live coordinator — no `yah cloud apply` was run, no user was created, no key was minted, no policy was pushed. Every claim about headscale's API in this ticket comes from read-only GETs against https://cloud.mesh.yah.dev with the vault's headscale-api-key, plus string extraction from the pinned v0.23.0 binary on us-west-001. There is also no live service/mirror definition wired for kind=\"headscale\" anywhere in .yah/services/ — deliberately, since committing one arms a reconcile against the production coordinator, and that is the operator's call, not a courier's. The shape is instead pinned by a test that loads a full workload dir (workload.toml + acls.hujson) off disk and asserts it is already in sync with the exact bytes the live coordinator serves.")
37//! @yah:handoff("DISCOVERED WORK DONE, not filed as a followup: R858-T2's own @yah:gotcha on oss/yubaba/crates/yubaba/src/headscale_appliance.rs asks the exact question I answered (\"establish whether this file is live or vestigial ... before designing carriage for it\"), and leaving it open would make the next reader repeat the SSH trip. Wrote a durable @yah:notify_on(R861-T1) into R858-T2 carrying the verdict and what it means for that ticket: while the fleet stays in file mode, acls.yaml is still state a move must carry alongside noise_private.key, and it stops being carriable state only when policy.mode flips to database. That is the only edit I made outside this ticket's own path list, and it is an additive annotation line.")
38//! @yah:handoff("PHASE 1 SETTLED BY MEASUREMENT, NOT INFERENCE — acls.yaml is LIVE, not vestigial. us-west-001's /var/lib/yah-cloud/headscale/config.yaml carries `policy:` / `mode: file` / `path: /var/lib/yah-cloud/headscale/acls.yaml` (read over SSH 2026-09-04), and all three in-tree renderers emit the same block. The file was therefore NOT deleted, and the ticket did NOT collapse to the users/preauth half — the ACL half is real work and was done. The 'no policy: section' observation in the filing gotcha was a truncated read of the config.")
39//! @yah:handoff("WHAT LANDED: HeadscaleReconciler (kind = \"headscale\") in oss/yubaba/crates/cloud/src/reconciler/headscale.rs, built on cloudflare_worker.rs's shape rather than any new abstraction — exactly the relay's framing of \"one more Reconciler implementation, no new noun\". It reconciles three classes of headscale's own API objects: list-then-create users, list-then-mint preauth keys, and a semantic HuJSON compare-then-push for ACLs. All declared config is validated in full BEFORE the first network call (the R330-B5 fail-fast discipline); independently confirmed at headscale.rs:463, where a preauth key naming an undeclared user is a genuine pre-network bail rather than a doc-comment claim.")
40//! @yah:handoff("SUPPORTING SURFACE: five methods added to HeadscaleClient in oss/yubaba/crates/cloud/src/mesh.rs — create_user, list_preauth_keys, create_preauth_key_with, get_policy, set_policy — all against the existing headscale-api-key credential slot, no new credential. This closes the gap R861's evidence named: headscale-preauth-key was already classified Band::Automatable (oss/yah-base/crates/keys/src/spec.rs:768) with automation that existed only ad hoc at provision time, one machine at a time, with no reconciled desired state. There is now a desired state.")
41//! @yah:verify("cargo test -p yah-cloud --lib = 1060 passed / 0 failed / 4 ignored. Baseline arithmetic reconciled independently rather than taken on trust: committed baseline is 1019, +17 new tests in headscale.rs (this ticket), +24 in topology.rs (@Ashguard:spade's R850, a separate module that landed concurrently) = 1060. The courier reported 1059 against a 1042 baseline; the off-by-one is a mid-run tree move, not a missing test. Fail-fast validation and the reconciler wiring were re-verified by a second agent reading the source, not by re-reading the courier's claim.")
42//! @yah:gotcha("`cargo check -p yah` is RED right now and it is NOT this ticket. Both failure snapshots land entirely in app/yah/cli/src/keys_doctor.rs — 2x E0425 'cannot find value `decision`' at :1574 and :1583 (a half-applied local rename), plus an earlier 9-error E0308/E0599 snapshot consistent with oss/yah-base/crates/keys/src/spec.rs moving underneath it (~207 insertions on `pub enum Provider`, the MINT_* consts, and ~8 points in CREDENTIAL_SPECS). That is @Ashguard:polaris's live R856 work, caught mid-edit; the diagnosis was handed to them directly. Nothing in either trace names headscale, reconciler or mesh, and R861-T1 treated spec.rs as strictly read-only — verified, not assumed.")
43//! @yah:gotcha("SHARED-TREE SEAM, disclosed and acknowledged: the HeadscaleReconciler re-export needed one added name in the `pub use reconciler::{…}` list in oss/yubaba/crates/cloud/src/lib.rs (~:307), a file @Ashguard:spade holds for R850. Purely additive — nothing removed or rewritten — but inserting the name pushed MesofactStaticReconciler past the column limit and rustfmt reflowed the pair, so the diff footprint reads -1/+2 rather than +1. @Ashguard:spade was notified and confirmed no conflict: their only line in that file is `pub mod topology;` at ~:272, a different region. Separately, the crate has NO rustfmt.toml and is pervasively fmt-dirty (~30 files, config.rs alone has 28 sites), so this reflow adds no new gate risk.")
44//! @yah:gotcha("DO NOT run rustfmt in write mode against oss/yubaba/crates/cloud/src/lib.rs. rustfmt follows `mod` declarations, so a write-mode run on that one file rewrites ~30 files and 100+ sites across the crate — most of it peers' uncommitted in-flight code. That is precisely the shape of the 2026-08-28 incident recorded in CLAUDE.md, where a cargo fmt followed path deps into a peer's crate and undoing it cost 827 uncommitted lines. Use `rustfmt --check` and read the file list first. Surfaced by @Ashguard:spade while checking this ticket's reflow.")
45//! @yah:handoff("NOT COMMITTED, deliberately. The shared index currently reads as staged by someone other than this ticket's worker, so nothing here was committed — a bare `git commit` on this tree would sweep in peers' work. Whoever signs this off should commit pathspec-scoped: oss/yubaba/crates/cloud/src/reconciler/headscale.rs, oss/yubaba/crates/cloud/src/reconciler/mod.rs, oss/yubaba/crates/cloud/src/mesh.rs, and the single-line lib.rs hunk. Tree anchor at dispatch: 6f193f90c6533329877804577c02d75ca57b2f98.")
46//! @yah:handoff("REMAINING WORK IS FILED, NOT PARKED HERE: R861-T2 (blocked_on operator) carries the one open call — the fleet is still on `policy.mode: file`, so the reconciler WRITES acls.yaml rather than making it stop existing. litestream replicates only headscale.db, so policy is now reconstructible-from-declared-config but is still unreplicated on-disk state. Flipping to mode=database closes it completely; that is a live-infrastructure change with a migration sequence and no defensible default, so it was deliberately left alone.")
47
48use anyhow::{Context, Result};
49use serde::{Deserialize, Serialize};
50
51// ---------------------------------------------------------------------------
52// Headscale REST API client
53// ---------------------------------------------------------------------------
54
55/// HTTP client for a running Headscale coordinator.
56///
57/// The Headscale REST API lives at `<server_url>/api/v1/…`. Requests are
58/// authenticated with an API key in the `Authorization: Bearer <key>` header.
59/// The API key must be created on the coordinator with `headscale apikeys create`
60/// or the equivalent API call; store it in the vault as `headscale-api-key`.
61pub struct HeadscaleClient {
62 base_url: String,
63 api_key: String,
64 http: reqwest::Client,
65}
66
67/// A Headscale pre-authentication key for onboarding a new node.
68#[derive(Debug, Clone, Serialize, Deserialize)]
69pub struct PreauthKey {
70 /// The key string to pass to `tailscale up --auth-key=<key>`.
71 pub key: String,
72 /// ACL tags the new node will be advertised with.
73 pub acl_tags: Vec<String>,
74}
75
76/// One pre-auth key as the coordinator reports it (`GET /api/v1/preauthkey`).
77///
78/// Field names are the protojson camelCase spelling headscale's grpc-gateway
79/// emits; the shape was read off the live v0.23.0 coordinator on 2026-09-04:
80/// `{"preAuthKeys":[{user,id,key,reusable,ephemeral,used,expiration,createdAt,aclTags}]}`.
81/// `expiration` is RFC3339 and may be absent for a never-expiring key.
82#[derive(Debug, Clone, Serialize, Deserialize)]
83pub struct PreauthKeyRecord {
84 pub id: String,
85 pub user: String,
86 pub key: String,
87 pub reusable: bool,
88 pub ephemeral: bool,
89 pub used: bool,
90 pub expiration: Option<chrono::DateTime<chrono::Utc>>,
91 pub acl_tags: Vec<String>,
92}
93
94impl PreauthKeyRecord {
95 /// Whether this key can still onboard a node at `now`: not past its
96 /// expiry, and either reusable or not yet spent.
97 pub fn is_usable_at(&self, now: chrono::DateTime<chrono::Utc>) -> bool {
98 let unexpired = self.expiration.map(|e| e > now).unwrap_or(true);
99 unexpired && (self.reusable || !self.used)
100 }
101}
102
103/// Everything `POST /api/v1/preauthkey` needs. Split out from
104/// [`HeadscaleClient::create_preauth_key`]'s fixed single-use/1-hour shape so a
105/// reconciler can mint the standing, reusable keys a declared spec asks for.
106#[derive(Debug, Clone)]
107pub struct PreauthKeyRequest {
108 pub user: String,
109 pub tags: Vec<String>,
110 pub reusable: bool,
111 pub ephemeral: bool,
112 pub ttl_hours: i64,
113}
114
115/// Summary information about a node in the Headscale tailnet.
116#[derive(Debug, Clone, Serialize, Deserialize)]
117pub struct NodeInfo {
118 pub id: String,
119 pub name: String,
120 pub ip_addresses: Vec<String>,
121 pub online: bool,
122}
123
124/// Headscale version + health response.
125#[derive(Debug, Clone)]
126pub struct HeadscaleHealth {
127 pub reachable: bool,
128 pub status_code: u16,
129}
130
131impl HeadscaleClient {
132 /// Construct a client from explicit credentials.
133 pub fn new(base_url: impl Into<String>, api_key: impl Into<String>) -> Result<Self> {
134 let base_url = base_url.into().trim_end_matches('/').to_string();
135 let http = reqwest::Client::builder()
136 .timeout(std::time::Duration::from_secs(30))
137 .build()
138 .context("building Headscale HTTP client")?;
139 Ok(Self {
140 base_url,
141 api_key: api_key.into(),
142 http,
143 })
144 }
145
146 /// Open a client from the vault (slot `headscale-api-key` + `mesh-url`)
147 /// with env-var fallbacks (`HEADSCALE_API_KEY` + `HEADSCALE_URL`).
148 ///
149 /// Returns `Ok(None)` when either credential is absent — callers can
150 /// decide whether that's fatal.
151 pub fn from_vault_or_env() -> Result<Option<Self>> {
152 let api_key = match fob::get_or_env("headscale-api-key", "HEADSCALE_API_KEY")? {
153 Some(k) => k,
154 None => return Ok(None),
155 };
156 let url = match fob::get_or_env("mesh-url", "HEADSCALE_URL")? {
157 Some(u) => u,
158 None => return Ok(None),
159 };
160 Ok(Some(Self::new(url, api_key)?))
161 }
162
163 /// Generate a single-use pre-auth key for the given ACL tags.
164 ///
165 /// The key expires in 1 hour and is non-reusable — suitable for one-shot
166 /// machine onboarding via cloud-init. Each `yah cloud machine provision`
167 /// call that uses Headscale mesh should request its own key.
168 pub async fn create_preauth_key(&self, user: &str, tags: &[String]) -> Result<PreauthKey> {
169 self.create_preauth_key_with(&PreauthKeyRequest {
170 user: user.to_string(),
171 tags: tags.to_vec(),
172 reusable: false,
173 ephemeral: false,
174 ttl_hours: 1,
175 })
176 .await
177 }
178
179 /// Mint a pre-auth key with an explicit lifetime and reuse policy.
180 ///
181 /// The general form behind [`create_preauth_key`](Self::create_preauth_key).
182 /// A reconciled desired state wants a *standing* key (reusable, long TTL)
183 /// rather than the one-shot hour-long key a single provision needs, and
184 /// both shapes are the same `POST /api/v1/preauthkey`.
185 pub async fn create_preauth_key_with(&self, req: &PreauthKeyRequest) -> Result<PreauthKey> {
186 let expiration = chrono::Utc::now()
187 + chrono::TimeDelta::try_hours(req.ttl_hours).ok_or_else(|| {
188 anyhow::anyhow!("overflow computing {}-hour expiry", req.ttl_hours)
189 })?;
190 let user = req.user.as_str();
191 let tags = req.tags.as_slice();
192 let body = serde_json::json!({
193 "user": user,
194 "expiration": expiration.to_rfc3339(),
195 "reusable": req.reusable,
196 "ephemeral": req.ephemeral,
197 "aclTags": tags,
198 });
199 let resp = self
200 .http
201 .post(format!("{}/api/v1/preauthkey", self.base_url))
202 .bearer_auth(&self.api_key)
203 .json(&body)
204 .send()
205 .await
206 .context("POST /api/v1/preauthkey")?;
207 let status = resp.status();
208 if !status.is_success() {
209 let text = resp.text().await.unwrap_or_default();
210 anyhow::bail!("Headscale API {status} on POST /api/v1/preauthkey: {text}");
211 }
212 let resp_json: serde_json::Value =
213 resp.json().await.context("parsing preauthkey response")?;
214 let key = resp_json["preAuthKey"]["key"]
215 .as_str()
216 .ok_or_else(|| anyhow::anyhow!("missing preAuthKey.key in response: {resp_json}"))?;
217 Ok(PreauthKey {
218 key: key.to_string(),
219 acl_tags: tags.to_vec(),
220 })
221 }
222
223 /// List all nodes currently in the tailnet.
224 ///
225 /// Uses Headscale's `GET /api/v1/node` (the endpoint was renamed from the
226 /// pre-v0.23 `/api/v1/machine`, with the response key `machines` → `nodes`,
227 /// when Headscale retired "machine" for "node"). The per-node JSON shape is
228 /// otherwise unchanged (`id`, `name`, `ipAddresses`, `online`).
229 pub async fn list_nodes(&self) -> Result<Vec<NodeInfo>> {
230 let resp = self
231 .http
232 .get(format!("{}/api/v1/node", self.base_url))
233 .bearer_auth(&self.api_key)
234 .send()
235 .await
236 .context("GET /api/v1/node")?;
237 let status = resp.status();
238 if !status.is_success() {
239 let text = resp.text().await.unwrap_or_default();
240 anyhow::bail!("Headscale API {status} on GET /api/v1/node: {text}");
241 }
242 let resp_json: serde_json::Value = resp.json().await.context("parsing node list")?;
243 let nodes = resp_json["nodes"].as_array().cloned().unwrap_or_default();
244 Ok(nodes
245 .iter()
246 .filter_map(|m| {
247 Some(NodeInfo {
248 id: m["id"].as_str()?.to_string(),
249 name: m["name"].as_str()?.to_string(),
250 ip_addresses: m["ipAddresses"]
251 .as_array()
252 .map(|arr| {
253 arr.iter()
254 .filter_map(|v| v.as_str().map(str::to_string))
255 .collect()
256 })
257 .unwrap_or_default(),
258 online: m["online"].as_bool().unwrap_or(false),
259 })
260 })
261 .collect())
262 }
263
264 /// List the Headscale users (namespaces) preauth keys can be minted against.
265 ///
266 /// `GET /api/v1/user`. Headscale scopes every preauth key to a user, and a
267 /// key minted against a user that does not exist fails at mint time.
268 pub async fn list_users(&self) -> Result<Vec<String>> {
269 let resp = self
270 .http
271 .get(format!("{}/api/v1/user", self.base_url))
272 .bearer_auth(&self.api_key)
273 .send()
274 .await
275 .context("GET /api/v1/user")?;
276 let status = resp.status();
277 if !status.is_success() {
278 let text = resp.text().await.unwrap_or_default();
279 anyhow::bail!("Headscale API {status} on GET /api/v1/user: {text}");
280 }
281 let resp_json: serde_json::Value = resp.json().await.context("parsing user list")?;
282 Ok(resp_json["users"]
283 .as_array()
284 .cloned()
285 .unwrap_or_default()
286 .iter()
287 .filter_map(|u| u["name"].as_str().map(str::to_string))
288 .collect())
289 }
290
291 /// Resolve the user to mint a preauth key against, asking the coordinator
292 /// instead of assuming a name.
293 ///
294 /// R608-B19: this used to be the literal `"default"` at the
295 /// `yah cloud machine provision` call site, and against the live
296 /// coordinator that is simply wrong — `POST /api/v1/preauthkey` answers
297 /// **500** for a user that does not exist. The two halves of the system
298 /// disagree on the name: [`crate::mesh`]'s camp-local `yah mesh start` path
299 /// creates `default` (its `--user` default), while `yah mesh bootstrap`
300 /// creates `yah` (`mint_bootstrap_preauth_key` in yubaba's lib.rs runs
301 /// `headscale users create yah`). The production coordinator was
302 /// bootstrapped, so it has only `yah` — every provision against it would
303 /// have failed at the preauth step with an opaque 500.
304 ///
305 /// Rather than swap one hardcoded guess for the other:
306 ///
307 /// - `preferred` present and known to the coordinator → use it;
308 /// - `preferred` absent and the coordinator has exactly one user → use it,
309 /// which is every yah mesh in existence today;
310 /// - otherwise → error naming the users that DO exist, so the operator can
311 /// pick, instead of a 500 that names nothing.
312 pub async fn resolve_user(&self, preferred: Option<&str>) -> Result<String> {
313 let users = self.list_users().await?;
314 choose_user(&self.base_url, &users, preferred)
315 }
316
317 /// Create a Headscale user (namespace). `POST /api/v1/user`.
318 ///
319 /// NOT idempotent on headscale's side — creating a name that already
320 /// exists answers 500 with no useful discriminator — so every caller must
321 /// [`list_users`](Self::list_users) first. That list-then-create shape is
322 /// what [`HeadscaleReconciler`](crate::reconciler::HeadscaleReconciler)
323 /// does, and it is why this method deliberately does not try to swallow a
324 /// conflict itself: a 500 here means something other than "already there".
325 pub async fn create_user(&self, name: &str) -> Result<()> {
326 let resp = self
327 .http
328 .post(format!("{}/api/v1/user", self.base_url))
329 .bearer_auth(&self.api_key)
330 .json(&serde_json::json!({ "name": name }))
331 .send()
332 .await
333 .context("POST /api/v1/user")?;
334 let status = resp.status();
335 if !status.is_success() {
336 let text = resp.text().await.unwrap_or_default();
337 anyhow::bail!("Headscale API {status} on POST /api/v1/user (name={name}): {text}");
338 }
339 Ok(())
340 }
341
342 /// List the pre-auth keys minted against `user`.
343 /// `GET /api/v1/preauthkey?user=<user>`.
344 pub async fn list_preauth_keys(&self, user: &str) -> Result<Vec<PreauthKeyRecord>> {
345 let resp = self
346 .http
347 .get(format!("{}/api/v1/preauthkey", self.base_url))
348 .query(&[("user", user)])
349 .bearer_auth(&self.api_key)
350 .send()
351 .await
352 .context("GET /api/v1/preauthkey")?;
353 let status = resp.status();
354 if !status.is_success() {
355 let text = resp.text().await.unwrap_or_default();
356 anyhow::bail!("Headscale API {status} on GET /api/v1/preauthkey (user={user}): {text}");
357 }
358 let resp_json: serde_json::Value =
359 resp.json().await.context("parsing preauth key list")?;
360 Ok(parse_preauth_key_list(&resp_json))
361 }
362
363 /// Read the ACL policy the coordinator currently has loaded.
364 /// `GET /api/v1/policy` → `{"policy": "<HuJSON>", "updatedAt": …}`.
365 ///
366 /// Works in BOTH policy modes — measured against the live v0.23.0
367 /// coordinator on 2026-09-04, which was still on `policy.mode: file` and
368 /// answered 200 with the file's contents. That is what makes drift
369 /// *detectable* on a not-yet-migrated coordinator even though
370 /// [`set_policy`](Self::set_policy) cannot correct it there.
371 ///
372 /// R861-T2 read the pinned v0.23.0 `GetPolicy` handler rather than
373 /// inferring: in `database` mode it returns the stored row's `Data` string
374 /// verbatim, in `file` mode the file's bytes as-is. Same field, same
375 /// document, so a caller never has to know which mode answered.
376 ///
377 /// One consequence worth knowing: a `database`-mode coordinator with no
378 /// policy row yet answers with a gRPC error, not an empty string — the
379 /// migration treats that as "nothing pushed yet", not as a fault.
380 pub async fn get_policy(&self) -> Result<String> {
381 let resp = self
382 .http
383 .get(format!("{}/api/v1/policy", self.base_url))
384 .bearer_auth(&self.api_key)
385 .send()
386 .await
387 .context("GET /api/v1/policy")?;
388 let status = resp.status();
389 if !status.is_success() {
390 let text = resp.text().await.unwrap_or_default();
391 anyhow::bail!("Headscale API {status} on GET /api/v1/policy: {text}");
392 }
393 let resp_json: serde_json::Value = resp.json().await.context("parsing policy response")?;
394 resp_json["policy"]
395 .as_str()
396 .map(str::to_string)
397 .ok_or_else(|| anyhow::anyhow!("missing `policy` string in response: {resp_json}"))
398 }
399
400 /// Replace the ACL policy. `PUT /api/v1/policy`.
401 ///
402 /// **Only legal when the coordinator runs `policy.mode: database`** — the
403 /// mode [`POLICY_MODE`] now renders. In `file` mode the pinned v0.23.0
404 /// `SetPolicy` handler returns `ErrPolicyUpdateIsDisabled` before looking
405 /// at the payload at all, because the file on disk is the source of truth
406 /// and a write here would be silently overwritten at the next reload.
407 /// Callers get that refusal as an error rather than a no-op success.
408 ///
409 /// Two properties R861-T2 established from that handler, both load-bearing
410 /// for the migration:
411 ///
412 /// - It validates before storing: the document is parsed with the same
413 /// `LoadACLPolicyFromBytes` a file-mode startup uses, then compiled
414 /// against the live node list (`CompileFilterRules`, and `CompileSSHPolicy`
415 /// when any node exists). A policy headscale would refuse to boot on is
416 /// refused here too, which is why a failed push is safe.
417 /// - It APPENDS: `db.SetPolicy` inserts a new `policies` row every call and
418 /// `GetPolicy` reads `ORDER BY id DESC LIMIT 1`. Repeating a push is
419 /// therefore idempotent in effect but not in storage — which is why the
420 /// reconciler and the migration both compare before writing.
421 pub async fn set_policy(&self, hujson: &str) -> Result<()> {
422 let resp = self
423 .http
424 .put(format!("{}/api/v1/policy", self.base_url))
425 .bearer_auth(&self.api_key)
426 .json(&serde_json::json!({ "policy": hujson }))
427 .send()
428 .await
429 .context("PUT /api/v1/policy")?;
430 let status = resp.status();
431 if !status.is_success() {
432 let text = resp.text().await.unwrap_or_default();
433 anyhow::bail!("Headscale API {status} on PUT /api/v1/policy: {text}");
434 }
435 Ok(())
436 }
437
438 /// Light health check — HEAD or GET the Headscale root, no auth required.
439 pub async fn health(&self) -> HeadscaleHealth {
440 match self
441 .http
442 .get(format!("{}/health", self.base_url))
443 .send()
444 .await
445 {
446 Ok(r) => HeadscaleHealth {
447 reachable: r.status().is_success(),
448 status_code: r.status().as_u16(),
449 },
450 Err(_) => HeadscaleHealth {
451 reachable: false,
452 status_code: 0,
453 },
454 }
455 }
456}
457
458/// The parsing half of [`HeadscaleClient::list_preauth_keys`], split out for
459/// the same reason [`choose_user`] is: the interesting behaviour is the shape
460/// translation, and this crate carries no HTTP mock.
461///
462/// Entries missing the fields a reconciler needs to *compare* (`id`, `user`,
463/// `key`) are dropped rather than defaulted — a half-parsed record would
464/// otherwise read as "no matching key exists" and cause a redundant mint.
465fn parse_preauth_key_list(resp_json: &serde_json::Value) -> Vec<PreauthKeyRecord> {
466 resp_json["preAuthKeys"]
467 .as_array()
468 .cloned()
469 .unwrap_or_default()
470 .iter()
471 .filter_map(|k| {
472 Some(PreauthKeyRecord {
473 id: k["id"].as_str()?.to_string(),
474 user: k["user"].as_str()?.to_string(),
475 key: k["key"].as_str()?.to_string(),
476 reusable: k["reusable"].as_bool().unwrap_or(false),
477 ephemeral: k["ephemeral"].as_bool().unwrap_or(false),
478 used: k["used"].as_bool().unwrap_or(false),
479 expiration: k["expiration"]
480 .as_str()
481 .and_then(|s| chrono::DateTime::parse_from_rfc3339(s).ok())
482 .map(|d| d.with_timezone(&chrono::Utc)),
483 acl_tags: k["aclTags"]
484 .as_array()
485 .map(|arr| {
486 arr.iter()
487 .filter_map(|v| v.as_str().map(str::to_string))
488 .collect()
489 })
490 .unwrap_or_default(),
491 })
492 })
493 .collect()
494}
495
496/// The user-selection half of [`HeadscaleClient::resolve_user`], split out so it
497/// is testable without standing up an HTTP server — this crate carries no HTTP
498/// mock, and the interesting behaviour is entirely in the choice, not the GET.
499fn choose_user(base_url: &str, users: &[String], preferred: Option<&str>) -> Result<String> {
500 if users.is_empty() {
501 anyhow::bail!(
502 "Headscale at {base_url} has no users — preauth keys are scoped to one. \
503 Create it with `headscale users create yah`."
504 );
505 }
506 if let Some(want) = preferred {
507 if users.iter().any(|u| u == want) {
508 return Ok(want.to_string());
509 }
510 anyhow::bail!(
511 "Headscale at {base_url} has no user '{want}' — preauth keys are scoped to \
512 a user, and minting against a missing one fails with an opaque 500. \
513 Existing users: {}.",
514 users.join(", ")
515 );
516 }
517 if let [only] = users {
518 return Ok(only.clone());
519 }
520 anyhow::bail!(
521 "Headscale at {base_url} has several users ({}) — pass one explicitly rather \
522 than letting this pick.",
523 users.join(", ")
524 )
525}
526
527// ---------------------------------------------------------------------------
528// Headscale config + ACL generation
529// ---------------------------------------------------------------------------
530
531/// The `policy.mode` every in-tree renderer emits (R861-T2).
532///
533/// `database` puts the ACL policy in `headscale.db`, which litestream already
534/// replicates, instead of in an `acls.yaml` that nothing replicates. It is also
535/// the only mode in which `PUT /api/v1/policy` is accepted, so it is the mode
536/// that makes [`super::reconciler::headscale`]'s declared policy pushable
537/// rather than merely observable.
538///
539/// Verified against the pinned headscale v0.23.0 source: `policy.mode` takes
540/// exactly `"file"` or `"database"` (`hscontrol/types/config.go`), and an
541/// unrecognised value is a `log.Fatal` at startup — so this string is
542/// load-bearing and must not be reworded.
543///
544/// `policy.path` is deliberately absent: headscale reads it only in file mode
545/// (`hscontrol/grpcv1.go` `GetPolicy`, `hscontrol/app.go` `loadACLPolicy`), so
546/// leaving it set would document a file that is no longer the source of truth.
547///
548/// yubaba's `generate_remote_headscale_config` /
549/// `generate_bootstrap_headscale_config` emit the same value from their own
550/// crate (no dependency edge exists between them and this one) and are kept in
551/// lockstep by convention, the way `DEFAULT_HEADSCALE_VERSION` already is.
552pub const POLICY_MODE: &str = "database";
553
554/// Generate a headscale YAML configuration for Phase 1a (camp-local coordinator).
555///
556/// All state files (private keys, SQLite DB, socket) go under `data_dir`.
557/// `server_url` is the publicly-reachable stable URL (`https://mesh.<domain>`)
558/// that provisioned machines embed as their `--login-server`. It must be
559/// stable across Phase 1b promotion and Phase 2 leader changes — only DNS
560/// gets re-pointed, not the nodes.
561pub fn generate_headscale_config(server_url: &str, data_dir: &std::path::Path) -> String {
562 let private_key = data_dir.join("private.key").display().to_string();
563 let noise_key = data_dir.join("noise_private.key").display().to_string();
564 let db_path = data_dir.join("headscale.db").display().to_string();
565 let socket_path = data_dir.join("headscale.sock").display().to_string();
566
567 // listen_addr is localhost-only; production-facing traffic goes through
568 // cloudflared or a port-forward — the stable URL is the public face.
569 format!(
570 r#"---
571server_url: {server_url}
572listen_addr: 127.0.0.1:8080
573grpc_listen_addr: 127.0.0.1:50443
574metrics_listen_addr: 127.0.0.1:9090
575private_key_path: {private_key}
576noise:
577 private_key_path: {noise_key}
578database:
579 type: sqlite
580 sqlite:
581 path: {db_path}
582unix_socket: {socket_path}
583unix_socket_permission: "0770"
584dns:
585 magic_dns: true
586 base_domain: mesh.internal
587 nameservers:
588 global:
589 - 1.1.1.1
590 - 8.8.8.8
591log:
592 level: info
593prefixes:
594 v4: 100.64.0.0/10
595 v6: fd7a:115c:a1e0::/48
596 allocation: sequential
597policy:
598 mode: {POLICY_MODE}
599derp:
600 server:
601 enabled: false
602 urls:
603 - https://controlplane.tailscale.com/derpmap/default
604 auto_update_enabled: false
605 update_frequency: 24h
606"#
607 )
608}
609
610/// A permissive ACL policy that allows all nodes to communicate.
611/// Can be refined later with `yah mesh acl edit`.
612///
613/// Headscale's file-based policy loader parses HuJSON (JSON-with-comments),
614/// NOT YAML — a leading `---` fails with "invalid literal: ---". Keep this
615/// JSON.
616pub const DEFAULT_ACL_POLICY: &str = r#"{
617 "acls": [
618 { "action": "accept", "src": ["*"], "dst": ["*:*"] }
619 ]
620}
621"#;
622
623// ---------------------------------------------------------------------------
624// Binary management helpers
625// ---------------------------------------------------------------------------
626
627/// Pinned Headscale release version used by `yah mesh start`.
628pub const HEADSCALE_VERSION: &str = "0.23.0";
629
630/// Return the GitHub release download URL for headscale on this platform.
631///
632/// Only supports darwin (amd64/arm64) and linux (amd64/arm64) — the
633/// platforms where `yah mesh start` makes sense. Returns `Err` for others.
634pub fn headscale_download_url() -> Result<String> {
635 let os = match std::env::consts::OS {
636 "macos" => "darwin",
637 "linux" => "linux",
638 other => anyhow::bail!(
639 "unsupported OS '{other}' for `yah mesh start`; \
640 install headscale manually from https://headscale.net"
641 ),
642 };
643 let arch = match std::env::consts::ARCH {
644 "x86_64" => "amd64",
645 "aarch64" => "arm64",
646 other => anyhow::bail!(
647 "unsupported architecture '{other}' for `yah mesh start`; \
648 install headscale manually from https://headscale.net"
649 ),
650 };
651 Ok(format!(
652 "https://github.com/juanfont/headscale/releases/download/v{HEADSCALE_VERSION}/headscale_{HEADSCALE_VERSION}_{os}_{arch}"
653 ))
654}
655
656// ---------------------------------------------------------------------------
657// Cloudflare DNS helpers
658// ---------------------------------------------------------------------------
659
660/// Update (or create) the A record for `record_name` in the given Cloudflare
661/// zone, pointing it at `new_ip`. Credentials come from the caller — use
662/// [`cloudflare_credentials`] to load them from the vault / env.
663///
664/// The record is matched by listing all A records in the zone that match
665/// `record_name`. Fails fast if zero or multiple records are found so we
666/// don't silently skip or duplicate.
667pub async fn update_cloudflare_dns(
668 api_token: &str,
669 zone_id: &str,
670 record_name: &str,
671 new_ip: &str,
672) -> Result<()> {
673 let http = reqwest::Client::builder()
674 .timeout(std::time::Duration::from_secs(30))
675 .build()
676 .context("building Cloudflare HTTP client")?;
677
678 let list_url = format!("https://api.cloudflare.com/client/v4/zones/{zone_id}/dns_records");
679
680 let resp = http
681 .get(&list_url)
682 .bearer_auth(api_token)
683 .query(&[("name", record_name), ("type", "A")])
684 .send()
685 .await
686 .context("GET Cloudflare DNS records")?;
687
688 if !resp.status().is_success() {
689 let text = resp.text().await.unwrap_or_default();
690 anyhow::bail!("Cloudflare list DNS records failed: {text}");
691 }
692
693 let body: serde_json::Value = resp
694 .json()
695 .await
696 .context("parsing Cloudflare records list")?;
697 let records = body["result"]
698 .as_array()
699 .ok_or_else(|| anyhow::anyhow!("unexpected Cloudflare response shape: missing 'result'"))?;
700
701 let record_id = match records.len() {
702 // Create-if-missing (R330-T9 follow-up b): on a fresh zone the A record
703 // won't exist yet. POST a new one instead of bailing, so `yah mesh
704 // bootstrap` is self-sufficient — no manual one-time DNS step. Same
705 // endpoint as the list (POST /zones/{zone}/dns_records), same body shape
706 // as the PATCH below. DNS-only (proxied: false) so Let's Encrypt HTTP-01
707 // can reach the node directly.
708 0 => {
709 println!(" A record '{record_name}' absent — creating it (→ {new_ip}) ...");
710 let create_body = serde_json::json!({
711 "type": "A",
712 "name": record_name,
713 "content": new_ip,
714 "ttl": 120,
715 "proxied": false
716 });
717 let resp = http
718 .post(&list_url)
719 .bearer_auth(api_token)
720 .json(&create_body)
721 .send()
722 .await
723 .context("POST Cloudflare DNS record (create-if-missing)")?;
724 if !resp.status().is_success() {
725 let text = resp.text().await.unwrap_or_default();
726 anyhow::bail!("Cloudflare create DNS record failed: {text}");
727 }
728 println!(" DNS record created.");
729 return Ok(());
730 }
731 1 => records[0]["id"]
732 .as_str()
733 .ok_or_else(|| anyhow::anyhow!("missing 'id' in Cloudflare record"))?
734 .to_string(),
735 n => anyhow::bail!(
736 "{n} A records named '{record_name}' found — expected exactly one; \
737 resolve the ambiguity in your Cloudflare dashboard"
738 ),
739 };
740
741 let patch_url = format!("{list_url}/{record_id}");
742 let patch_body = serde_json::json!({
743 "type": "A",
744 "name": record_name,
745 "content": new_ip,
746 "ttl": 120,
747 "proxied": false
748 });
749
750 let resp = http
751 .patch(&patch_url)
752 .bearer_auth(api_token)
753 .json(&patch_body)
754 .send()
755 .await
756 .context("PATCH Cloudflare DNS record")?;
757
758 if !resp.status().is_success() {
759 let text = resp.text().await.unwrap_or_default();
760 anyhow::bail!("Cloudflare PATCH DNS record failed: {text}");
761 }
762
763 Ok(())
764}
765
766/// Load Cloudflare credentials from vault or environment.
767///
768/// Vault slots → env var fallbacks:
769/// - `cloudflare-api-token` ↔ `CLOUDFLARE_API_TOKEN`
770/// - `cloudflare-zone-id` ↔ `CLOUDFLARE_ZONE_ID`
771///
772/// Returns `Ok(None)` when either credential is absent so callers can decide
773/// whether to proceed with manual-DNS instructions or bail.
774pub fn cloudflare_credentials() -> Result<Option<(String, String)>> {
775 let token = fob::get_or_env("cloudflare-api-token", "CLOUDFLARE_API_TOKEN")?;
776 let zone_id = fob::get_or_env("cloudflare-zone-id", "CLOUDFLARE_ZONE_ID")?;
777 match (token, zone_id) {
778 (Some(t), Some(z)) => Ok(Some((t, z))),
779 _ => Ok(None),
780 }
781}
782
783// ---------------------------------------------------------------------------
784// Tests
785// ---------------------------------------------------------------------------
786
787#[cfg(test)]
788mod tests {
789 use super::*;
790
791 #[test]
792 fn config_contains_server_url() {
793 let dir = std::path::PathBuf::from("/tmp/test-mesh");
794 let config = generate_headscale_config("https://mesh.example.com", &dir);
795 assert!(config.contains("server_url: https://mesh.example.com"));
796 assert!(config.contains("127.0.0.1:8080"));
797 assert!(config.contains("base_domain: mesh.internal"));
798 // R861-T2: policy lives in headscale.db, which litestream replicates.
799 // The renderer must emit the mode AND must NOT emit a `policy.path` —
800 // a leftover path documents a file that is no longer read.
801 assert!(config.contains(&format!("mode: {POLICY_MODE}")));
802 assert!(!config.contains("acls.yaml"));
803 assert!(!config.contains("policy.path"));
804 // Regression (R330-T9): base_domain must not be a substring of the
805 // server_url host, or headscale 0.23+ refuses to start ("server_url
806 // cannot contain the base_domain"). mesh.internal is decoupled from
807 // any mesh.yah.dev-style coordinator hostname.
808 let cfg2 = generate_headscale_config("https://mesh.yah.dev", &dir);
809 assert!(!cfg2.contains("base_domain: mesh.yah\n"));
810 }
811
812 #[test]
813 fn config_all_paths_in_data_dir() {
814 let dir = std::path::PathBuf::from("/home/user/.yah/mesh");
815 let config = generate_headscale_config("https://mesh.example.com", &dir);
816 assert!(config.contains("/home/user/.yah/mesh/private.key"));
817 assert!(config.contains("/home/user/.yah/mesh/headscale.db"));
818 }
819
820 #[test]
821 fn download_url_current_platform() {
822 // Just ensure it doesn't panic on the current CI platform.
823 let result = headscale_download_url();
824 assert!(result.is_ok(), "unsupported platform: {result:?}");
825 let url = result.unwrap();
826 assert!(url.contains(HEADSCALE_VERSION));
827 assert!(url.starts_with("https://github.com"));
828 }
829
830 // -- choose_user (R608-B19) ---------------------------------------------
831 //
832 // The regression these pin down: `yah cloud machine provision` minted its
833 // preauth key against the literal `"default"`, which the production
834 // coordinator does not have. It was bootstrapped, so its only user is
835 // `yah` (`headscale users create yah`, yubaba lib.rs
836 // `mint_bootstrap_preauth_key`), while the camp-local `yah mesh start` path
837 // creates `default`. Headscale answers a mint against a missing user with a
838 // bare 500 naming nothing, so this failed opaquely on every provision.
839
840 fn users(names: &[&str]) -> Vec<String> {
841 names.iter().map(|s| s.to_string()).collect()
842 }
843
844 #[test]
845 fn a_lone_user_is_chosen_without_being_named() {
846 // The live shape: one bootstrapped coordinator, one user, and no reason
847 // to make the caller know whether it is called `yah` or `default`.
848 assert_eq!(
849 choose_user("https://mesh.test", &users(&["yah"]), None).unwrap(),
850 "yah"
851 );
852 assert_eq!(
853 choose_user("https://mesh.test", &users(&["default"]), None).unwrap(),
854 "default"
855 );
856 }
857
858 #[test]
859 fn a_preferred_user_that_exists_wins() {
860 assert_eq!(
861 choose_user("https://mesh.test", &users(&["yah", "ops"]), Some("ops")).unwrap(),
862 "ops"
863 );
864 }
865
866 #[test]
867 fn a_preferred_user_that_does_not_exist_is_refused_by_name() {
868 // THE bug, as a test: asking for "default" on a coordinator that only
869 // has "yah" must fail here, locally, saying what does exist — not reach
870 // the API and come back with a 500 that names nothing.
871 let err = choose_user("https://mesh.test", &users(&["yah"]), Some("default"))
872 .expect_err("a missing user must not be requested from the API");
873 let msg = err.to_string();
874 assert!(msg.contains("default"), "names what was asked for: {msg}");
875 assert!(msg.contains("yah"), "names what actually exists: {msg}");
876 }
877
878 #[test]
879 fn several_users_and_no_preference_refuses_rather_than_guessing() {
880 // Silently taking the first would reintroduce the same class of bug:
881 // a name picked by the code that the operator never chose.
882 let err = choose_user("https://mesh.test", &users(&["yah", "default"]), None)
883 .expect_err("an ambiguous mint target must not be guessed");
884 let msg = err.to_string();
885 assert!(msg.contains("yah") && msg.contains("default"), "{msg}");
886 }
887
888 #[test]
889 fn no_users_at_all_says_how_to_create_one() {
890 let err = choose_user("https://mesh.test", &[], None).expect_err("no users is fatal");
891 assert!(err.to_string().contains("headscale users create"));
892 }
893}