Skip to main content

vault_core/
nodes.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright the UnENVerse contributors.
3//! Phase 34 — Nodes: the protocol, the hub's registry and the node's config.
4//!
5//! A **hub** is an `unv-server` holding the vault. A **node** is an agent on
6//! another host that observes, and when told to, applies config files derived
7//! from that vault. This module is everything both ends must agree on; the
8//! filesystem side of an apply is in [`crate::nodes_apply`].
9//!
10//! # What a node is, and is not
11//!
12//! A node never holds a vault key and never holds a scoped read token. Its
13//! identity is an Ed25519 key it generated itself. The hub stores the public
14//! half at enrollment and checks a signature on every request, so the hub
15//! pins the node's key the way the node pins the hub's certificate (ADR-0140
16//! explains why this is request signing and not client certificates).
17//!
18//! # State is not in the vault
19//!
20//! The registry is `nodes.json` beside `pools.json`. Heartbeats arrive every
21//! minute; putting them through `save_vault` would grow the audit chain without
22//! bound (the read-event and pool-cursor mistake, a third time) and turn every
23//! beat into a compare-and-swap that can conflict with a human's edit.
24//!
25//! # Rendered content never touches disk on the hub
26//!
27//! The registry holds hashes, never file content: a rendered `wg0.conf`
28//! contains a private key and `nodes.json` is not encrypted.
29
30use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey};
31use rand::Rng;
32use serde::{Deserialize, Serialize};
33use sha2::{Digest, Sha256};
34use std::collections::HashSet;
35use std::path::{Path, PathBuf};
36
37/// How long an enrollment token lives unless the operator asks otherwise.
38pub const ENROLL_TTL_SECS: i64 = 900;
39/// A signed request whose timestamp is further than this from the hub's clock
40/// is refused. Replays inside the window are stopped by the strictly increasing
41/// timestamp, not by the window.
42pub const MAX_CLOCK_SKEW_SECS: i64 = 60;
43/// Targets one node may declare. A bound, so a hostile beat cannot grow the
44/// registry without limit.
45pub const MAX_TARGETS: usize = 256;
46
47/// The error `record_beat`'s `desired` callback returns when the hub cannot
48/// render at all because the vault is locked. It is not a refusal: the target
49/// is simply `unknown` until the hub is unlocked again.
50pub const LOCKED: &str = "hub-locked";
51
52/// Exporter names a target may use. `compose-env` is the `.env` Compose
53/// substitutes from, which is a separate file and therefore a separate target.
54/// True for a built-in exporter name or a stack adapter's (Phase 38).
55pub fn valid_exporter(name: &str) -> bool {
56    EXPORTERS.contains(&name) || crate::stack::adapter(name).is_some()
57}
58
59pub const EXPORTERS: &[&str] = &[
60    "wireguard",
61    "nginx",
62    "apache",
63    "haproxy",
64    "ansible",
65    "postgres",
66    "k8s",
67    "ssh",
68    "traefik",
69    "compose",
70    "compose-env",
71    "env",
72];
73
74// ── Identity and request signing ──────────────────────────────────────────────
75
76/// A fresh node identity as `(seed_hex, public_key_hex)`.
77pub fn generate_identity() -> (String, String) {
78    let mut seed = [0u8; 32];
79    rand::rng().fill_bytes(&mut seed);
80    let public = SigningKey::from_bytes(&seed).verifying_key().to_bytes();
81    (hex::encode(seed), hex::encode(public))
82}
83
84/// SHA-256 of the raw public key, as hex. What the operator compares.
85pub fn key_fingerprint(public_hex: &str) -> Result<String, String> {
86    let bytes = hex::decode(public_hex).map_err(|_| "public key is not hex".to_string())?;
87    if bytes.len() != 32 {
88        return Err("public key must be 32 bytes".into());
89    }
90    Ok(hex::encode(Sha256::digest(&bytes)))
91}
92
93/// The exact bytes a signature covers. Method and path are inside it so a
94/// signature for one route cannot be replayed against another; the body is
95/// inside it by hash so the hub never has to re-serialise anything.
96fn signing_input(method: &str, path: &str, ts_ms: i64, body: &[u8]) -> Vec<u8> {
97    signing_input_for("envv-node-v1", method, path, ts_ms, body)
98}
99
100/// The same input under another domain. A hub's request to a node and a node's
101/// request to a hub must never be interchangeable, so each direction has its own
102/// first line.
103fn signing_input_for(domain: &str, method: &str, path: &str, ts_ms: i64, body: &[u8]) -> Vec<u8> {
104    format!(
105        "{domain}\n{}\n{}\n{}\n{}",
106        method.to_ascii_uppercase(),
107        path,
108        ts_ms,
109        hex::encode(Sha256::digest(body))
110    )
111    .into_bytes()
112}
113
114/// Signs a request. Returns the signature as hex.
115pub fn sign_request(
116    seed_hex: &str,
117    method: &str,
118    path: &str,
119    ts_ms: i64,
120    body: &[u8],
121) -> Result<String, String> {
122    let seed: [u8; 32] = hex::decode(seed_hex)
123        .map_err(|_| "node key is not hex".to_string())?
124        .try_into()
125        .map_err(|_| "node key must be 32 bytes".to_string())?;
126    let sig = SigningKey::from_bytes(&seed).sign(&signing_input(method, path, ts_ms, body));
127    Ok(hex::encode(sig.to_bytes()))
128}
129
130/// True only for a valid signature by `public_hex` over exactly this request.
131pub fn verify_request(
132    public_hex: &str,
133    method: &str,
134    path: &str,
135    ts_ms: i64,
136    body: &[u8],
137    sig_hex: &str,
138) -> bool {
139    verify_in(
140        "envv-node-v1",
141        public_hex,
142        method,
143        path,
144        ts_ms,
145        body,
146        sig_hex,
147    )
148}
149
150/// As [`sign_request`], for a hub talking to a node that listens (Phase 34.1).
151pub fn sign_hub_request(
152    seed_hex: &str,
153    method: &str,
154    path: &str,
155    ts_ms: i64,
156    body: &[u8],
157) -> Result<String, String> {
158    let seed: [u8; 32] = hex::decode(seed_hex)
159        .map_err(|_| "hub key is not hex".to_string())?
160        .try_into()
161        .map_err(|_| "hub key must be 32 bytes".to_string())?;
162    let sig = SigningKey::from_bytes(&seed).sign(&signing_input_for(
163        "envv-hub-v1",
164        method,
165        path,
166        ts_ms,
167        body,
168    ));
169    Ok(hex::encode(sig.to_bytes()))
170}
171
172/// As [`verify_request`], for the hub's requests.
173pub fn verify_hub_request(
174    public_hex: &str,
175    method: &str,
176    path: &str,
177    ts_ms: i64,
178    body: &[u8],
179    sig_hex: &str,
180) -> bool {
181    verify_in(
182        "envv-hub-v1",
183        public_hex,
184        method,
185        path,
186        ts_ms,
187        body,
188        sig_hex,
189    )
190}
191
192fn verify_in(
193    domain: &str,
194    public_hex: &str,
195    method: &str,
196    path: &str,
197    ts_ms: i64,
198    body: &[u8],
199    sig_hex: &str,
200) -> bool {
201    let Ok(pk) = hex::decode(public_hex) else {
202        return false;
203    };
204    let Ok(pk): Result<[u8; 32], _> = pk.try_into() else {
205        return false;
206    };
207    let Ok(vk) = VerifyingKey::from_bytes(&pk) else {
208        return false;
209    };
210    let Ok(sig) = hex::decode(sig_hex) else {
211        return false;
212    };
213    let Ok(sig): Result<[u8; 64], _> = sig.try_into() else {
214        return false;
215    };
216    vk.verify(
217        &signing_input_for(domain, method, path, ts_ms, body),
218        &Signature::from_bytes(&sig),
219    )
220    .is_ok()
221}
222
223// ── Listening nodes (Phase 34.1) ──────────────────────────────────────────────
224
225/// How a hub reaches a node that listens instead of dialling: its address and
226/// the SHA-256 of the TLS certificate it generated for that. Recorded at
227/// enrollment, over the channel the one-time token already authenticates, and
228/// pinned from then on.
229#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
230pub struct ListenInfo {
231    pub endpoint: String,
232    pub cert_sha256: String,
233}
234
235impl ListenInfo {
236    /// `https://host[:port]` and nothing else: a path, query, userinfo or
237    /// fragment would let an address smuggle something to the hub's client.
238    pub fn validate(&self) -> Result<(), String> {
239        let rest = self
240            .endpoint
241            .strip_prefix("https://")
242            .ok_or("A listening node must be reachable over https")?;
243        let rest = rest.strip_suffix('/').unwrap_or(rest);
244        let ok = !rest.is_empty()
245            && rest.len() <= 255
246            && rest.bytes().all(|b| {
247                b.is_ascii_alphanumeric() || matches!(b, b'.' | b'-' | b':' | b'[' | b']')
248            });
249        if !ok {
250            return Err("endpoint must be https://host or https://host:port".into());
251        }
252        if self.cert_sha256.len() != 64 || !self.cert_sha256.bytes().all(|b| b.is_ascii_hexdigit())
253        {
254            return Err("cert_sha256 must be 64 hex characters".into());
255        }
256        Ok(())
257    }
258
259    /// The endpoint without a trailing slash.
260    pub fn base(&self) -> &str {
261        self.endpoint.strip_suffix('/').unwrap_or(&self.endpoint)
262    }
263}
264
265// ── Wire types ────────────────────────────────────────────────────────────────
266
267/// One target as the node reports it. Hash and state only; never content.
268#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
269pub struct TargetReport {
270    pub id: String,
271    pub project: String,
272    pub exporter: String,
273    /// `push` (vault to file) or `pull` (file to vault).
274    pub mode: String,
275    /// Whether this node will write the file. Declared by the operator in the
276    /// node's own config; the hub cannot change it.
277    pub apply: bool,
278    /// SHA-256 of the file on disk, or `None` when it does not exist.
279    pub sha256: Option<String>,
280    /// `ok`, `missing`, `unreadable`, `applied`, `failed`.
281    pub state: String,
282    pub error: Option<String>,
283    /// Whether the node's own config accepts a rule approval for this target (R12). Declared by the
284    /// operator; the hub only reads it to know which kind of token to send.
285    #[serde(default)]
286    pub accept_rule_approval: bool,
287}
288
289/// A change the node saw between two beats (hub down, or locked).
290#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
291pub struct DriftEvent {
292    pub target: String,
293    pub at: String,
294    pub from: Option<String>,
295    pub to: Option<String>,
296}
297
298/// The outcome of one apply, reported on the next beat. The hub turns each into
299/// an audit row; heartbeats themselves write nothing.
300#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
301pub struct ApplyResult {
302    pub target: String,
303    pub at: String,
304    pub sha256: String,
305    pub ok: bool,
306    pub error: Option<String>,
307    /// The steps that completed, in order (`written`, `validated`, `reloaded`, `checked`). Absent
308    /// from an older node, so a report without it says nothing about the steps.
309    #[serde(default, skip_serializing_if = "Vec::is_empty")]
310    pub phases: Vec<String>,
311}
312
313#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Default)]
314pub struct HostInfo {
315    pub hostname: String,
316    pub os: String,
317    pub kernel: String,
318    pub arch: String,
319    pub version: String,
320    pub uptime_secs: u64,
321}
322
323/// The heartbeat. No IP address: the hub has the socket where it needs one.
324#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Default)]
325pub struct Beat {
326    pub host: HostInfo,
327    pub targets: Vec<TargetReport>,
328    #[serde(default)]
329    pub events: Vec<DriftEvent>,
330    #[serde(default)]
331    pub results: Vec<ApplyResult>,
332    /// Seconds the node is willing to wait for the hub to answer. The hub
333    /// holds the request open this long when it has nothing to say, so a vault
334    /// save reaches the node in about a second instead of one interval.
335    #[serde(default)]
336    pub wait_secs: u32,
337}
338
339/// Something the hub asks a node to do.
340#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
341#[serde(tag = "kind", rename_all = "snake_case")]
342pub enum Action {
343    /// Write these bytes to a push target whose `apply` is true. `sha256` is
344    /// what the node must recompute and compare before it writes anything.
345    Push {
346        target: String,
347        sha256: String,
348        content_b64: String,
349        /// The hub's signed statement that a human approved exactly these bytes
350        /// for this node and target (Phase 37). Absent when the node needs none.
351        #[serde(default, skip_serializing_if = "Option::is_none")]
352        approval: Option<SignedApproval>,
353    },
354    /// Send the content of a pull target once. Requested by a human.
355    Upload { target: String },
356}
357
358#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Default)]
359pub struct BeatReply {
360    pub interval_secs: u32,
361    /// True when the hub could not render (vault locked). Observe goes on; push
362    /// idles.
363    pub hub_locked: bool,
364    /// True when the hub recorded the `results` of this beat. A hub that cannot
365    /// (locked, so the audit chain is closed) says false and the node sends
366    /// them again; clearing them on a reply that did not keep them would lose
367    /// the only record that an apply happened.
368    #[serde(default)]
369    pub results_ack: bool,
370    pub actions: Vec<Action>,
371    /// Pushes the hub is holding for a human (Phase 37). Informational: the
372    /// node shows them, and nothing about them is a command.
373    #[serde(default)]
374    pub pending: Vec<PendingNote>,
375    /// The hub's approval-signing public key (Phase 37). A node pins the first
376    /// one it sees over its pinned TLS channel and refuses a different one.
377    #[serde(default, skip_serializing_if = "Option::is_none")]
378    pub hub_pubkey: Option<String>,
379    /// Which vault this hub serves and which instance of it this is (R19). A node remembers the
380    /// highest epoch it has seen for the vault and refuses a lower one, so a forgotten second hub
381    /// cannot push over the live one. Absent from a hub that predates it; an old node ignores it.
382    #[serde(default, skip_serializing_if = "Option::is_none")]
383    pub hub_epoch: Option<HubEpoch>,
384}
385
386/// A hub's claim about itself: the vault and the instance epoch it speaks for.
387#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
388pub struct HubEpoch {
389    pub vault_id: String,
390    pub epoch: u64,
391}
392
393// ── The node's own config ─────────────────────────────────────────────────────
394
395/// One `[[target]]` in the node's config. Everything executable is here, on
396/// this host, written by the operator. Nothing the hub sends can add to it.
397#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
398#[serde(deny_unknown_fields)]
399pub struct Target {
400    pub id: String,
401    pub path: PathBuf,
402    pub project: String,
403    pub exporter: String,
404    #[serde(default = "default_mode")]
405    pub mode: String,
406    /// Observe until deliberately flipped.
407    #[serde(default)]
408    pub apply: bool,
409    /// A command run after the bytes are written. If it contains `{file}` it runs against a
410    /// temporary file first and the target is replaced only when it passes.
411    pub validate: Option<String>,
412    pub reload: Option<String>,
413    /// A health check run after `reload`: a command, or an `http://host:port/path` URL that must
414    /// answer 2xx. A failure puts the previous file back and reloads it.
415    #[serde(default)]
416    pub check: Option<String>,
417    /// Accept a push that carries a rule approval: a short-lived token signed by this node's
418    /// `automation_approver` key, bound to this node, target, bytes and operation. Needs
419    /// `automation_approver`; cannot be combined with `require_approval`, which asks for a human.
420    #[serde(default)]
421    pub accept_rule_approval: bool,
422    /// Refuse any push that does not carry the hub's signed approval of exactly
423    /// these bytes (Phase 37). Set here, on the host, so a hub bug or a hub
424    /// policy change cannot turn it off.
425    #[serde(default)]
426    pub require_approval: bool,
427    /// Permission bits of the written file, as octal text (`"0400"`). Unix only. A Compose
428    /// target defaults to `0400`; any other target keeps the mode the file already has.
429    #[serde(default)]
430    pub file_mode: Option<String>,
431    /// Owner of the written file as numeric `uid` or `uid:gid` (the user inside the container
432    /// that reads the secret, e.g. `999:999` for the Postgres image). Needs the node to run as
433    /// root or that user. Unix only.
434    #[serde(default)]
435    pub owner: Option<String>,
436    /// Makes this a Docker Compose secret-file target: after the write the node runs
437    /// `docker compose -p <project> -f <compose_file> config -q` and then recreates only
438    /// `services`. Replaces `validate` and `reload`, which it generates.
439    #[serde(default)]
440    pub compose_project: Option<String>,
441    #[serde(default)]
442    pub compose_file: Option<PathBuf>,
443    #[serde(default)]
444    pub services: Vec<String>,
445}
446
447impl Target {
448    /// `file_mode` as bits: `Some` when set, or `0o400` for a Compose target.
449    pub fn file_mode_bits(&self) -> Option<u32> {
450        match &self.file_mode {
451            Some(m) => parse_file_mode(m),
452            None => self.compose_project.as_ref().map(|_| 0o400),
453        }
454    }
455
456    /// `owner` as `(uid, gid)`; a bare uid uses the same number as gid.
457    pub fn owner_ids(&self) -> Option<(u32, u32)> {
458        parse_owner(self.owner.as_deref()?)
459    }
460}
461
462/// `"0400"`, `"640"`: three or four octal digits, no setuid/setgid/sticky bits.
463pub fn parse_file_mode(text: &str) -> Option<u32> {
464    if !(3..=4).contains(&text.len()) || !text.bytes().all(|b| (b'0'..=b'7').contains(&b)) {
465        return None;
466    }
467    u32::from_str_radix(text, 8).ok().filter(|b| *b <= 0o777)
468}
469
470/// `"999"` or `"999:999"`.
471pub fn parse_owner(text: &str) -> Option<(u32, u32)> {
472    fn id(t: &str) -> Option<u32> {
473        if t.is_empty() || !t.bytes().all(|b| b.is_ascii_digit()) {
474            return None;
475        }
476        t.parse().ok()
477    }
478    let (u, g) = text.split_once(':').unwrap_or((text, text));
479    Some((id(u)?, id(g)?))
480}
481
482fn default_mode() -> String {
483    "push".into()
484}
485
486#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Default)]
487#[serde(deny_unknown_fields)]
488pub struct NodeConfig {
489    /// Seconds between beats when the hub has nothing to say. 10 to 3600.
490    pub interval_secs: Option<u32>,
491    #[serde(default, rename = "target")]
492    pub targets: Vec<Target>,
493    /// The public key (hex) of the device whose signature this node accepts as a
494    /// human's approval (Phase 37.1). When set, a push that needs approval must
495    /// carry a token signed by this key; the hub's own key no longer counts, so a
496    /// hub that has been taken over cannot approve its own pushes.
497    #[serde(default)]
498    pub approver: Option<String>,
499    /// The public key (hex) whose signature counts as a rule approval (R12): a token the hub's
500    /// automation key signed for one operation, valid for minutes. It never satisfies
501    /// `require_approval`, which always needs a human or a device.
502    #[serde(default)]
503    pub automation_approver: Option<String>,
504}
505
506/// `^[A-Za-z0-9][A-Za-z0-9_.-]{0,62}$`
507pub fn valid_id(s: &str) -> bool {
508    let b = s.as_bytes();
509    !b.is_empty()
510        && b.len() <= 63
511        && b[0].is_ascii_alphanumeric()
512        && b.iter()
513            .all(|c| c.is_ascii_alphanumeric() || matches!(c, b'_' | b'.' | b'-'))
514}
515
516fn valid_command(s: &str) -> bool {
517    !s.trim().is_empty() && s.len() <= 512 && !s.contains('\0')
518}
519
520impl NodeConfig {
521    pub fn parse(text: &str) -> Result<Self, String> {
522        let cfg: NodeConfig = toml::from_str(text).map_err(|e| format!("node config: {e}"))?;
523        cfg.validate()?;
524        Ok(cfg)
525    }
526
527    pub fn validate(&self) -> Result<(), String> {
528        if let Some(i) = self.interval_secs {
529            if !(10..=3600).contains(&i) {
530                return Err("interval_secs must be between 10 and 3600".into());
531            }
532        }
533        if let Some(a) = &self.approver {
534            let ok = a.len() == 64
535                && hex::decode(a)
536                    .ok()
537                    .and_then(|b| <[u8; 32]>::try_from(b).ok())
538                    .is_some_and(|b| VerifyingKey::from_bytes(&b).is_ok());
539            if !ok {
540                return Err("approver must be a 64-character hex Ed25519 public key".into());
541            }
542        }
543        if let Some(a) = &self.automation_approver {
544            let ok = a.len() == 64
545                && hex::decode(a)
546                    .ok()
547                    .and_then(|b| <[u8; 32]>::try_from(b).ok())
548                    .is_some_and(|b| VerifyingKey::from_bytes(&b).is_ok());
549            if !ok {
550                return Err(
551                    "automation_approver must be a 64-character hex Ed25519 public key".into(),
552                );
553            }
554        }
555        if self.targets.len() > MAX_TARGETS {
556            return Err(format!("at most {MAX_TARGETS} targets"));
557        }
558        let mut seen = HashSet::new();
559        for t in &self.targets {
560            if !valid_id(&t.id) {
561                return Err(format!(
562                    "target id '{}' must be letters, digits, '_', '.' or '-' (max 63)",
563                    t.id
564                ));
565            }
566            if !seen.insert(t.id.clone()) {
567                return Err(format!("target id '{}' is used twice", t.id));
568            }
569            // has_root: "/etc/x" is rooted but not absolute on Windows (no drive), and is still unambiguous on the current drive.
570            if !(t.path.is_absolute() || t.path.has_root()) {
571                return Err(format!("target '{}': path must be absolute", t.id));
572            }
573            if t.path.to_string_lossy().contains('\0') {
574                return Err(format!("target '{}': path contains NUL", t.id));
575            }
576            if t.project.trim().is_empty() {
577                return Err(format!("target '{}': project is empty", t.id));
578            }
579            if !valid_exporter(&t.exporter) {
580                return Err(format!(
581                    "target '{}': unknown exporter '{}'. Supported: {}",
582                    t.id,
583                    t.exporter,
584                    EXPORTERS
585                        .iter()
586                        .copied()
587                        .chain(crate::stack::adapters().iter().map(|a| a.id.as_str()))
588                        .collect::<Vec<_>>()
589                        .join(", ")
590                ));
591            }
592            if t.mode != "push" && t.mode != "pull" {
593                return Err(format!(
594                    "target '{}': mode must be \"push\" or \"pull\"",
595                    t.id
596                ));
597            }
598            // A pull target's file is the source of truth. Letting the hub
599            // write it would make "pull" mean its opposite.
600            if t.mode == "pull"
601                && (t.apply || t.validate.is_some() || t.reload.is_some() || t.require_approval)
602            {
603                return Err(format!(
604                    "target '{}': a pull target is only read, so apply, validate, reload and require_approval do not belong on it",
605                    t.id
606                ));
607            }
608            if t.accept_rule_approval {
609                if t.mode != "push" {
610                    return Err(format!(
611                        "target '{}': accept_rule_approval only applies to a push target",
612                        t.id
613                    ));
614                }
615                if t.require_approval {
616                    return Err(format!(
617                        "target '{}': require_approval asks for a human and accept_rule_approval for an automation rule; choose one",
618                        t.id
619                    ));
620                }
621                if self.automation_approver.is_none() {
622                    return Err(format!(
623                        "target '{}': accept_rule_approval needs automation_approver (the public key shown in Settings)",
624                        t.id
625                    ));
626                }
627            }
628            if let Some(m) = &t.file_mode {
629                if parse_file_mode(m).is_none() {
630                    return Err(format!(
631                        "target '{}': file_mode must be octal like \"0400\" (no setuid bits)",
632                        t.id
633                    ));
634                }
635            }
636            if let Some(o) = &t.owner {
637                if parse_owner(o).is_none() {
638                    return Err(format!(
639                        "target '{}': owner must be a numeric uid or uid:gid",
640                        t.id
641                    ));
642                }
643            }
644            match &t.compose_project {
645                Some(project) => {
646                    if t.mode != "push" {
647                        return Err(format!(
648                            "target '{}': a Compose target is written by the hub, so its mode is \"push\"",
649                            t.id
650                        ));
651                    }
652                    if !valid_id(project) {
653                        return Err(format!(
654                            "target '{}': compose_project must be letters, digits, '_', '.' or '-'",
655                            t.id
656                        ));
657                    }
658                    if !t.compose_file.as_ref().is_some_and(|f| {
659                        (f.is_absolute() || f.has_root()) && !f.to_string_lossy().contains('\0')
660                    }) {
661                        return Err(format!(
662                            "target '{}': compose_project needs compose_file, an absolute path",
663                            t.id
664                        ));
665                    }
666                    if t.services.is_empty() || !t.services.iter().all(|x| valid_id(x)) {
667                        return Err(format!(
668                            "target '{}': compose_project needs services, the names to recreate",
669                            t.id
670                        ));
671                    }
672                    if t.validate.is_some() || t.reload.is_some() {
673                        return Err(format!(
674                            "target '{}': a Compose target generates validate and reload; remove them (use check for a health probe)",
675                            t.id
676                        ));
677                    }
678                }
679                None => {
680                    if t.compose_file.is_some() || !t.services.is_empty() {
681                        return Err(format!(
682                            "target '{}': compose_file and services belong to a target that sets compose_project",
683                            t.id
684                        ));
685                    }
686                }
687            }
688            for (name, v) in [
689                ("validate", &t.validate),
690                ("reload", &t.reload),
691                ("check", &t.check),
692            ] {
693                if let Some(c) = v {
694                    if !valid_command(c) {
695                        return Err(format!("target '{}': {name} is empty or too long", t.id));
696                    }
697                }
698            }
699        }
700        Ok(())
701    }
702}
703
704// ── The hub's registry ────────────────────────────────────────────────────────
705
706/// What the hub knows about one target on one node.
707#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
708pub struct TargetStatus {
709    pub id: String,
710    pub project: String,
711    pub exporter: String,
712    pub mode: String,
713    pub apply: bool,
714    pub reported_sha: Option<String>,
715    /// What the hub would write now. `None` when it could not render (locked,
716    /// unknown project, or the config check failed).
717    pub desired_sha: Option<String>,
718    /// For a pull target: the hash a human last accepted into the vault.
719    pub accepted_sha: Option<String>,
720    pub state: String,
721    pub error: Option<String>,
722    /// `in_sync`, `drift`, `pending`, `missing`, `changed`, `unreviewed`,
723    /// `unknown`, `refused`.
724    pub status: String,
725    /// Why the hub withheld a push, when `status` is `refused`.
726    pub refusal: Option<String>,
727}
728
729#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
730pub struct NodeRecord {
731    pub id: String,
732    pub name: String,
733    pub pubkey: String,
734    pub fingerprint: String,
735    /// Projects this node may be sent. Set by the operator when minting the
736    /// token; a node cannot widen it by declaring a target.
737    pub projects: Vec<String>,
738    pub enrolled_at: String,
739    pub last_seen: Option<String>,
740    /// Highest request timestamp accepted. Persisted so a restart does not
741    /// reopen the replay window.
742    pub last_ts_ms: i64,
743    pub revoked_at: Option<String>,
744    pub host: Option<HostInfo>,
745    pub targets: Vec<TargetStatus>,
746    /// `required` holds every push to this node for a human (Phase 37); empty or
747    /// `none` pushes as soon as a node's own config allows it.
748    #[serde(default)]
749    pub approval: String,
750    /// Set when the node listens and the hub dials it (Phase 34.1). Absent for a
751    /// node that dials the hub.
752    #[serde(default, skip_serializing_if = "Option::is_none")]
753    pub listen: Option<ListenInfo>,
754    /// When the hub last polled this node, for a listening node.
755    #[serde(default, skip_serializing_if = "Option::is_none")]
756    pub last_polled: Option<String>,
757}
758
759#[derive(Clone, Debug, Serialize, Deserialize)]
760struct TokenRecord {
761    /// SHA-256 of the token. The plaintext is shown once and never stored.
762    hash: String,
763    name: String,
764    projects: Vec<String>,
765    expires_at_secs: i64,
766    used: bool,
767}
768
769#[derive(Default, Serialize, Deserialize)]
770struct StoreFile {
771    #[serde(default)]
772    tokens: Vec<TokenRecord>,
773    #[serde(default)]
774    nodes: Vec<NodeRecord>,
775    #[serde(default)]
776    approvals: Vec<ApprovalRecord>,
777    /// The hub's transport signing seed for listening nodes (Phase 34.1), created
778    /// on first use. It lives here, not in the vault, so a locked hub can still
779    /// poll (observation continues); pushes still need the unlocked vault.
780    #[serde(default)]
781    hub_node_seed: String,
782    /// Devices whose signature counts as the owner's approval (Phase 37.1).
783    #[serde(default)]
784    approvers: Vec<Approver>,
785    /// Target leases (R12): a rotation pins a target to the bytes it is deploying.
786    #[serde(default)]
787    leases: Vec<Lease>,
788}
789
790#[derive(Debug, PartialEq)]
791pub enum AuthError {
792    UnknownNode,
793    Revoked,
794    BadSignature,
795    Skew,
796    Replay,
797}
798
799impl AuthError {
800    pub fn message(&self) -> &'static str {
801        match self {
802            AuthError::UnknownNode | AuthError::BadSignature => "Node authentication failed",
803            AuthError::Revoked => "This node has been revoked",
804            AuthError::Skew => "Request timestamp is outside the allowed clock skew",
805            AuthError::Replay => "Request timestamp is not newer than the last one accepted",
806        }
807    }
808}
809
810pub struct NodeStore {
811    path: PathBuf,
812    data: StoreFile,
813}
814
815fn token_hash(token: &str) -> String {
816    hex::encode(Sha256::digest(token.as_bytes()))
817}
818
819/// Writes `bytes` to `path` through a temp file, 0600 on Unix.
820fn write_private(path: &Path, bytes: &[u8]) -> Result<(), String> {
821    use std::io::Write;
822    if let Some(dir) = path.parent() {
823        std::fs::create_dir_all(dir).map_err(|e| e.to_string())?;
824    }
825    let tmp = path.with_extension("json.tmp");
826    let mut opts = std::fs::OpenOptions::new();
827    opts.write(true).create(true).truncate(true);
828    #[cfg(unix)]
829    {
830        use std::os::unix::fs::OpenOptionsExt;
831        opts.mode(0o600);
832    }
833    let mut f = opts.open(&tmp).map_err(|e| e.to_string())?;
834    f.write_all(bytes).map_err(|e| e.to_string())?;
835    f.sync_all().map_err(|e| e.to_string())?;
836    drop(f);
837    crate::platform::replace_file(&tmp, path).map_err(|e| e.to_string())
838}
839
840/// Prefix of the refusal when the file changed after the owner fetched it.
841pub const ACCEPT_CHANGED: &str = "The file changed on the node after you fetched it";
842
843impl NodeStore {
844    /// Opens the registry, empty when the file does not exist. A file that
845    /// exists and does not parse is an error, not an empty registry: silently
846    /// forgetting every enrolled node would re-open every enrollment token.
847    pub fn open(path: &Path) -> Result<Self, String> {
848        let data = match std::fs::read_to_string(path) {
849            Ok(t) => serde_json::from_str(&t)
850                .map_err(|e| format!("{} is not a valid node registry: {e}", path.display()))?,
851            Err(e) if e.kind() == std::io::ErrorKind::NotFound => StoreFile::default(),
852            Err(e) => return Err(format!("{}: {e}", path.display())),
853        };
854        Ok(Self {
855            path: path.to_path_buf(),
856            data,
857        })
858    }
859
860    fn save(&self) -> Result<(), String> {
861        let text = serde_json::to_vec_pretty(&self.data).map_err(|e| e.to_string())?;
862        write_private(&self.path, &text)
863    }
864
865    /// Mints a single-use enrollment token. Returns the plaintext once.
866    pub fn mint_token(
867        &mut self,
868        name: &str,
869        projects: Vec<String>,
870        ttl_secs: i64,
871        now_secs: i64,
872    ) -> Result<(String, i64), String> {
873        if !valid_id(name) {
874            return Err("node name must be letters, digits, '_', '.' or '-' (max 63)".into());
875        }
876        if projects.is_empty() {
877            return Err("name at least one project this node may receive".into());
878        }
879        if self
880            .data
881            .nodes
882            .iter()
883            .any(|n| n.name == name && n.revoked_at.is_none())
884        {
885            return Err(format!("a node named '{name}' is already enrolled"));
886        }
887        // Two open tokens for one name would enrol two nodes with the same name.
888        if self
889            .data
890            .tokens
891            .iter()
892            .any(|t| t.name == name && !t.used && t.expires_at_secs > now_secs)
893        {
894            return Err(format!(
895                "an enrollment token for '{name}' is already open; use it or let it expire"
896            ));
897        }
898        let ttl = ttl_secs.clamp(30, 7 * 86_400);
899        let mut raw = [0u8; 32];
900        rand::rng().fill_bytes(&mut raw);
901        let token = format!("envn_{}", hex::encode(raw));
902        let expires = now_secs + ttl;
903        // Expired and spent tokens are dead weight; dropping them here keeps
904        // the file from growing with every enrollment ever attempted.
905        self.data
906            .tokens
907            .retain(|t| !t.used && t.expires_at_secs > now_secs);
908        self.data.tokens.push(TokenRecord {
909            hash: token_hash(&token),
910            name: name.to_string(),
911            projects,
912            expires_at_secs: expires,
913            used: false,
914        });
915        self.save()?;
916        Ok((token, expires))
917    }
918
919    /// Enrols a listening node from its pairing request, without a token changing hands (R12): the
920    /// owner carries the node's request in and the reply out, which is how a hub that opens no port
921    /// (the desktop) learns a node. The token is minted and spent inside this call, so the usual
922    /// checks (a free name, a real key, a bare https address) apply unchanged. Returns the node and
923    /// the hub's transport key, which the node pins.
924    pub fn pair(
925        &mut self,
926        name: &str,
927        projects: Vec<String>,
928        pubkey_hex: &str,
929        listen: ListenInfo,
930        now_secs: i64,
931        now_iso: &str,
932    ) -> Result<(NodeRecord, String), String> {
933        let (token, _) = self.mint_token(name, projects, 30, now_secs)?;
934        match self.enroll(&token, pubkey_hex, Some(listen), now_secs, now_iso) {
935            Ok(node) => {
936                let hub_key = self.hub_node_key()?.1;
937                Ok((node, hub_key))
938            }
939            Err(e) => {
940                // A refused request must not leave its token open: it would block the name for
941                // a retry until it expired.
942                let h = token_hash(&token);
943                self.data.tokens.retain(|t| t.hash != h);
944                let _ = self.save();
945                Err(e)
946            }
947        }
948    }
949
950    /// Spends a token and registers the node's public key.
951    pub fn enroll(
952        &mut self,
953        token: &str,
954        pubkey_hex: &str,
955        listen: Option<ListenInfo>,
956        now_secs: i64,
957        now_iso: &str,
958    ) -> Result<NodeRecord, String> {
959        if let Some(l) = &listen {
960            l.validate()?;
961        }
962        let fingerprint = key_fingerprint(pubkey_hex)?;
963        // A point that is not on the curve can never verify, and storing it
964        // would make the node permanently unable to authenticate.
965        let raw: [u8; 32] = hex::decode(pubkey_hex)
966            .map_err(|_| "public key is not hex".to_string())?
967            .try_into()
968            .map_err(|_| "public key must be 32 bytes".to_string())?;
969        VerifyingKey::from_bytes(&raw).map_err(|_| "public key is not a valid Ed25519 key")?;
970
971        let h = token_hash(token);
972        let rec = self
973            .data
974            .tokens
975            .iter_mut()
976            .find(|t| t.hash == h)
977            .ok_or("Invalid or expired enrollment token")?;
978        // One message for every way a token can be bad: which one it was is
979        // information for whoever is guessing.
980        if rec.used || rec.expires_at_secs <= now_secs {
981            return Err("Invalid or expired enrollment token".into());
982        }
983        let name = rec.name.clone();
984        if self
985            .data
986            .nodes
987            .iter()
988            .any(|n| n.name == name && n.revoked_at.is_none())
989        {
990            return Err(format!("a node named '{name}' is already enrolled"));
991        }
992        let rec = self
993            .data
994            .tokens
995            .iter_mut()
996            .find(|t| t.hash == h)
997            .expect("found above");
998        rec.used = true;
999        let node = NodeRecord {
1000            id: crate::new_uuid(),
1001            name,
1002            pubkey: pubkey_hex.to_ascii_lowercase(),
1003            fingerprint,
1004            projects: rec.projects.clone(),
1005            enrolled_at: now_iso.to_string(),
1006            last_seen: None,
1007            last_ts_ms: 0,
1008            revoked_at: None,
1009            host: None,
1010            targets: Vec::new(),
1011            approval: String::new(),
1012            listen,
1013            last_polled: None,
1014        };
1015        self.data.nodes.push(node.clone());
1016        if let Err(e) = self.save() {
1017            // Not on disk, so not enrolled: leave memory as the file is, and the
1018            // token usable for a retry.
1019            self.data.nodes.pop();
1020            if let Some(t) = self.data.tokens.iter_mut().find(|t| t.hash == h) {
1021                t.used = false;
1022            }
1023            return Err(e);
1024        }
1025        Ok(node)
1026    }
1027
1028    /// Checks a signed request and, on success, advances the node's replay mark.
1029    pub fn authenticate(
1030        &mut self,
1031        node_id: &str,
1032        method: &str,
1033        path: &str,
1034        ts_ms: i64,
1035        body: &[u8],
1036        sig_hex: &str,
1037        now_ms: i64,
1038    ) -> Result<NodeRecord, AuthError> {
1039        let node = self
1040            .data
1041            .nodes
1042            .iter_mut()
1043            .find(|n| n.id == node_id)
1044            .ok_or(AuthError::UnknownNode)?;
1045        // Signature first: skew, replay and revocation are only worth telling
1046        // to somebody who holds the key.
1047        if !verify_request(&node.pubkey, method, path, ts_ms, body, sig_hex) {
1048            return Err(AuthError::BadSignature);
1049        }
1050        if node.revoked_at.is_some() {
1051            return Err(AuthError::Revoked);
1052        }
1053        if (now_ms - ts_ms).abs() > MAX_CLOCK_SKEW_SECS * 1000 {
1054            return Err(AuthError::Skew);
1055        }
1056        if ts_ms <= node.last_ts_ms {
1057            return Err(AuthError::Replay);
1058        }
1059        node.last_ts_ms = ts_ms;
1060        let out = node.clone();
1061        // Best effort: failing to persist the mark must not drop a beat, but
1062        // the in-memory mark still stops replays until a restart.
1063        let _ = self.save();
1064        Ok(out)
1065    }
1066
1067    /// The hub's transport key for listening nodes as `(seed, public)`, made on
1068    /// first use.
1069    pub fn hub_node_key(&mut self) -> Result<(String, String), String> {
1070        if self.data.hub_node_seed.is_empty() {
1071            self.data.hub_node_seed = generate_hub_seed();
1072            self.save()?;
1073        }
1074        let public = hub_public(&self.data.hub_node_seed)?;
1075        Ok((self.data.hub_node_seed.clone(), public))
1076    }
1077
1078    /// Active nodes the hub has to dial.
1079    pub fn listening(&self) -> Vec<NodeRecord> {
1080        self.data
1081            .nodes
1082            .iter()
1083            .filter(|n| n.listen.is_some() && n.revoked_at.is_none())
1084            .cloned()
1085            .collect()
1086    }
1087
1088    /// Notes that the hub polled `id` just now.
1089    pub fn mark_polled(&mut self, id: &str, now_iso: &str) {
1090        if let Some(n) = self.data.nodes.iter_mut().find(|n| n.id == id) {
1091            n.last_polled = Some(now_iso.to_string());
1092            let _ = self.save();
1093        }
1094    }
1095
1096    pub fn list(&self) -> Vec<NodeRecord> {
1097        self.data.nodes.clone()
1098    }
1099
1100    pub fn get(&self, id: &str) -> Option<NodeRecord> {
1101        self.data.nodes.iter().find(|n| n.id == id).cloned()
1102    }
1103
1104    /// Finds an active node by name or id.
1105    pub fn find(&self, name_or_id: &str) -> Option<NodeRecord> {
1106        self.data
1107            .nodes
1108            .iter()
1109            .find(|n| n.revoked_at.is_none() && (n.id == name_or_id || n.name == name_or_id))
1110            .cloned()
1111    }
1112
1113    pub fn revoke(&mut self, id: &str, now_iso: &str) -> Result<NodeRecord, String> {
1114        let n = self
1115            .data
1116            .nodes
1117            .iter_mut()
1118            .find(|n| n.id == id)
1119            .ok_or("No such node")?;
1120        if n.revoked_at.is_none() {
1121            n.revoked_at = Some(now_iso.to_string());
1122        }
1123        let out = n.clone();
1124        self.save()?;
1125        Ok(out)
1126    }
1127
1128    /// Replaces a node's observed state from a beat. `desired` is what the hub
1129    /// would write for each target id (`Ok(sha)`), or why it will not (`Err`).
1130    pub fn record_beat(
1131        &mut self,
1132        id: &str,
1133        beat: &Beat,
1134        desired: &dyn Fn(&TargetReport) -> Result<String, String>,
1135        now_iso: &str,
1136    ) -> Result<(), String> {
1137        let now_secs = unix_now();
1138        let approvals: Vec<ApprovalRecord> = self.data.approvals.clone();
1139        let node = self
1140            .data
1141            .nodes
1142            .iter_mut()
1143            .find(|n| n.id == id)
1144            .ok_or("No such node")?;
1145        if beat.targets.len() > MAX_TARGETS {
1146            return Err(format!("at most {MAX_TARGETS} targets"));
1147        }
1148        let accepted: Vec<(String, String)> = node
1149            .targets
1150            .iter()
1151            .filter_map(|t| t.accepted_sha.clone().map(|a| (t.id.clone(), a)))
1152            .collect();
1153        let requires_approval = matches!(node.approval.as_str(), "required" | "device");
1154        let mut out = Vec::new();
1155        for r in &beat.targets {
1156            if !valid_id(&r.id) || !valid_exporter(&r.exporter) {
1157                continue;
1158            }
1159            let accepted_sha = accepted
1160                .iter()
1161                .find(|(i, _)| i == &r.id)
1162                .map(|(_, a)| a.clone());
1163            let (desired_sha, refusal) = if r.mode == "push" {
1164                if !node.projects.iter().any(|p| p == &r.project) {
1165                    (
1166                        None,
1167                        Some(format!(
1168                            "node '{}' was not enrolled for project '{}'",
1169                            node.name, r.project
1170                        )),
1171                    )
1172                } else {
1173                    match desired(r) {
1174                        Ok(s) => (Some(s), None),
1175                        Err(e) if e == LOCKED => (None, None),
1176                        Err(e) => (None, Some(e)),
1177                    }
1178                }
1179            } else {
1180                (None, None)
1181            };
1182            let mut status =
1183                derive_status(r, desired_sha.as_deref(), accepted_sha.as_deref(), &refusal);
1184            // A push that is ready to go is held for a human when the node needs one.
1185            if status == "pending" && requires_approval {
1186                if let Some(d) = desired_sha.as_deref() {
1187                    status = approval_status(&approvals, id, &r.id, d, now_secs).into();
1188                }
1189            }
1190            out.push(TargetStatus {
1191                id: r.id.clone(),
1192                project: r.project.clone(),
1193                exporter: r.exporter.clone(),
1194                mode: r.mode.clone(),
1195                apply: r.apply,
1196                reported_sha: r.sha256.clone(),
1197                desired_sha,
1198                accepted_sha,
1199                state: r.state.clone(),
1200                error: r.error.clone(),
1201                status,
1202                refusal,
1203            });
1204        }
1205        node.targets = out;
1206        node.host = Some(beat.host.clone());
1207        node.last_seen = Some(now_iso.to_string());
1208        // An approved push whose bytes the node now reports has done its job; one
1209        // nobody acted on in time, or a request nobody answered, lapses.
1210        for a in self.data.approvals.iter_mut().filter(|a| a.node_id == id) {
1211            // The node reports having the bytes, or reports the write that put them
1212            // there (the file may have been edited again before this beat).
1213            let applied = beat
1214                .targets
1215                .iter()
1216                .any(|r| r.id == a.target && r.sha256.as_deref() == Some(a.sha256.as_str()))
1217                || beat
1218                    .results
1219                    .iter()
1220                    .any(|r| r.ok && r.target == a.target && r.sha256 == a.sha256);
1221            match a.status.as_str() {
1222                "approved" if applied => a.status = "consumed".into(),
1223                "approved" if now_secs >= a.decided_secs.unwrap_or(0) + APPROVAL_TTL_SECS => {
1224                    a.status = "expired".into()
1225                }
1226                "pending" if now_secs >= a.requested_secs + PENDING_TTL_SECS => {
1227                    a.status = "expired".into()
1228                }
1229                _ => {}
1230            }
1231        }
1232        self.save()
1233    }
1234
1235    /// Drops grants for projects that no longer exist. A grant is a project NAME,
1236    /// so without this a deleted project's name would pass to whoever creates a
1237    /// project of that name later. Returns `(node name, project)` for each grant removed.
1238    pub fn prune_projects(&mut self, existing: &[String]) -> Result<Vec<(String, String)>, String> {
1239        let mut removed = Vec::new();
1240        for n in self.data.nodes.iter_mut() {
1241            n.projects.retain(|p| {
1242                let keep = existing.iter().any(|e| e == p);
1243                if !keep {
1244                    removed.push((n.name.clone(), p.clone()));
1245                }
1246                keep
1247            });
1248        }
1249        for t in self.data.tokens.iter_mut().filter(|t| !t.used) {
1250            t.projects.retain(|p| existing.iter().any(|e| e == p));
1251        }
1252        if !removed.is_empty() {
1253            self.save()?;
1254        }
1255        Ok(removed)
1256    }
1257
1258    /// Records the hash a human accepted into the vault for a pull target.
1259    /// Records the node's current file for a pull target as accepted.
1260    ///
1261    /// `expected` is the hash of the bytes the owner actually fetched and reviewed. Without
1262    /// it, accept recorded whatever the node last reported, and a file that changed between
1263    /// the fetch and the accept was accepted as in sync without anyone having seen it.
1264    pub fn accept(
1265        &mut self,
1266        id: &str,
1267        target: &str,
1268        expected: Option<&str>,
1269    ) -> Result<String, String> {
1270        let node = self
1271            .data
1272            .nodes
1273            .iter_mut()
1274            .find(|n| n.id == id)
1275            .ok_or("No such node")?;
1276        let t = node
1277            .targets
1278            .iter_mut()
1279            .find(|t| t.id == target)
1280            .ok_or("No such target on this node")?;
1281        if t.mode != "pull" {
1282            return Err("Only a pull target has something to accept".into());
1283        }
1284        let sha = t
1285            .reported_sha
1286            .clone()
1287            .ok_or("The file does not exist on the node, so there is nothing to accept")?;
1288        if let Some(want) = expected {
1289            if !want.eq_ignore_ascii_case(&sha) {
1290                return Err(format!(
1291                    "{ACCEPT_CHANGED}: you fetched {want} but the node now reports {sha}. Pull it again and review that."
1292                ));
1293            }
1294        }
1295        t.accepted_sha = Some(sha.clone());
1296        t.status = "in_sync".into();
1297        self.save()?;
1298        Ok(sha)
1299    }
1300}
1301
1302/// The one place a target's status word is decided.
1303pub fn derive_status(
1304    r: &TargetReport,
1305    desired: Option<&str>,
1306    accepted: Option<&str>,
1307    refusal: &Option<String>,
1308) -> String {
1309    if r.mode == "pull" {
1310        return match (r.sha256.as_deref(), accepted) {
1311            (None, _) => "missing",
1312            (Some(_), None) => "unreviewed",
1313            (Some(a), Some(b)) if a == b => "in_sync",
1314            _ => "changed",
1315        }
1316        .into();
1317    }
1318    if refusal.is_some() {
1319        return "refused".into();
1320    }
1321    match (r.sha256.as_deref(), desired) {
1322        (_, None) => "unknown",
1323        (None, Some(_)) => {
1324            if r.apply {
1325                "pending"
1326            } else {
1327                "missing"
1328            }
1329        }
1330        (Some(a), Some(d)) if a == d => "in_sync",
1331        (Some(_), Some(_)) => {
1332            if r.apply {
1333                "pending"
1334            } else {
1335                "drift"
1336            }
1337        }
1338    }
1339    .into()
1340}
1341
1342// ── Approval (Phase 37, ADR-0143) ─────────────────────────────────────────────
1343
1344/// How long an approved push stays valid, and so how long its signed token does.
1345pub const APPROVAL_TTL_SECS: i64 = 3600;
1346/// How long a request waits for a human before it lapses.
1347pub const PENDING_TTL_SECS: i64 = 7 * 86_400;
1348
1349fn unix_now() -> i64 {
1350    std::time::SystemTime::now()
1351        .duration_since(std::time::UNIX_EPOCH)
1352        .map_or(0, |d| d.as_secs() as i64)
1353}
1354
1355/// A request for a human to say yes to these exact bytes for this node target.
1356/// Holds hashes and snapshot numbers, never content: the content is in the
1357/// config history, where the human reads it as a diff.
1358#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
1359pub struct ApprovalRecord {
1360    pub id: String,
1361    pub node_id: String,
1362    pub target: String,
1363    pub project: String,
1364    pub exporter: String,
1365    /// SHA-256 of the proposed file. The approval is for this and nothing else.
1366    pub sha256: String,
1367    /// What the node reported having when the request was made.
1368    pub from_sha: Option<String>,
1369    /// History snapshot of the file the node has (when known) and of the proposal.
1370    pub from_seq: Option<i64>,
1371    pub to_seq: Option<i64>,
1372    pub requested_at: String,
1373    pub requested_secs: i64,
1374    /// `pending`, `approved`, `rejected`, `consumed`, `expired`.
1375    pub status: String,
1376    pub decided_at: Option<String>,
1377    pub decided_secs: Option<i64>,
1378    pub decided_by: Option<String>,
1379    /// Set when the yes was signed on the owner's own device (Phase 37.1); the
1380    /// hub then sends exactly this and never signs an approval itself.
1381    #[serde(default, skip_serializing_if = "Option::is_none")]
1382    pub signed: Option<SignedApproval>,
1383}
1384
1385/// A device whose signature counts as the owner's approval (Phase 37.1, ADR-0147).
1386#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
1387pub struct Approver {
1388    pub pubkey: String,
1389    pub fingerprint: String,
1390    pub label: String,
1391    pub added: String,
1392}
1393
1394/// A held push, as told to the node.
1395#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
1396pub struct PendingNote {
1397    pub target: String,
1398    pub sha256: String,
1399    pub status: String,
1400    pub approval_id: String,
1401}
1402
1403/// What the hub signs when a human approves. Canonical JSON is signed as text,
1404/// so there is nothing to re-serialise on the verifying side.
1405#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
1406pub struct ApprovalToken {
1407    pub v: u8,
1408    pub node_id: String,
1409    pub target: String,
1410    pub sha256: String,
1411    pub approval_id: String,
1412    pub approved_by: String,
1413    pub approved_at: String,
1414    pub expires_secs: i64,
1415    pub nonce: String,
1416}
1417
1418/// What may sign an approval and what it means (R12). `human` and `device` are people; `rule` is an
1419/// automation key acting under a written rule, never a person.
1420#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1421pub enum ApprovalKind {
1422    Human,
1423    Device,
1424    Rule,
1425}
1426
1427impl ApprovalKind {
1428    pub fn as_str(self) -> &'static str {
1429        match self {
1430            Self::Human => "human",
1431            Self::Device => "device",
1432            Self::Rule => "rule",
1433        }
1434    }
1435
1436    pub fn is_person(self) -> bool {
1437        !matches!(self, Self::Rule)
1438    }
1439}
1440
1441/// The signing domain of a version 2 token. A signature made for one domain never verifies in the
1442/// other, so a v1 token cannot be replayed as v2 or the reverse.
1443pub const APPROVAL_V2_DOMAIN: &str = "unv-approval-v2";
1444/// A rule approval lives minutes, not an hour: it exists for one automated operation.
1445pub const RULE_APPROVAL_TTL_SECS: i64 = 300;
1446
1447/// Version 2: adds the approval's kind and ties it to one operation and the policy it was made
1448/// under. Signed as `unv-approval-v2\n<json>`; version 1 tokens still verify.
1449#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
1450pub struct ApprovalTokenV2 {
1451    pub v: u8,
1452    /// `human`, `device` or `rule`.
1453    pub kind: String,
1454    pub node_id: String,
1455    pub target: String,
1456    pub sha256: String,
1457    pub approval_id: String,
1458    /// The operation this approval belongs to; an approval for one deployment is not valid for
1459    /// another.
1460    pub operation_id: String,
1461    /// The credential generation the rendered file was made from, when known.
1462    #[serde(default)]
1463    pub credential_generation: Option<u64>,
1464    /// The revision of the policy under which the approval was given.
1465    pub policy_rev: u64,
1466    /// For `rule`: the rule that allowed it.
1467    #[serde(default)]
1468    pub rule_id: Option<String>,
1469    pub approved_by: String,
1470    pub approved_at: String,
1471    pub expires_secs: i64,
1472    pub nonce: String,
1473}
1474
1475/// What a node learns from a verified approval of either version.
1476#[derive(Clone, Debug, PartialEq)]
1477pub struct Verified {
1478    pub version: u8,
1479    pub kind: ApprovalKind,
1480    pub nonce: String,
1481    pub operation_id: Option<String>,
1482    pub rule_id: Option<String>,
1483}
1484
1485fn v2_input(token_json: &str) -> Vec<u8> {
1486    format!("{APPROVAL_V2_DOMAIN}\n{token_json}").into_bytes()
1487}
1488
1489pub fn sign_approval_v2(seed_hex: &str, token: &ApprovalTokenV2) -> Result<SignedApproval, String> {
1490    let seed: [u8; 32] = hex::decode(seed_hex)
1491        .map_err(|_| "signing key is not hex".to_string())?
1492        .try_into()
1493        .map_err(|_| "signing key must be 32 bytes".to_string())?;
1494    let json = serde_json::to_string(token).map_err(|e| e.to_string())?;
1495    let sig = SigningKey::from_bytes(&seed).sign(&v2_input(&json));
1496    Ok(SignedApproval {
1497        token: json,
1498        sig: hex::encode(sig.to_bytes()),
1499    })
1500}
1501
1502/// Checks a version 1 or version 2 approval the way a node does before it writes. `public_hex` is
1503/// the key the caller trusts for this decision: a node passes the human/device key for a target
1504/// that needs a person and the automation key for a rule approval, so a token signed by the wrong
1505/// kind of key fails here before its claims are read.
1506pub fn verify_approval_any(
1507    public_hex: &str,
1508    signed: &SignedApproval,
1509    node_id: &str,
1510    target: &str,
1511    sha256: &str,
1512    now_secs: i64,
1513) -> Result<Verified, String> {
1514    let version = serde_json::from_str::<serde_json::Value>(&signed.token)
1515        .ok()
1516        .and_then(|v| v.get("v").and_then(|v| v.as_u64()))
1517        .ok_or("approval is unreadable")?;
1518    match version {
1519        1 => {
1520            let t = verify_approval(public_hex, signed, node_id, target, sha256, now_secs)?;
1521            Ok(Verified {
1522                version: 1,
1523                kind: if t.approved_by.starts_with("device:") {
1524                    ApprovalKind::Device
1525                } else {
1526                    ApprovalKind::Human
1527                },
1528                nonce: t.nonce,
1529                operation_id: None,
1530                rule_id: None,
1531            })
1532        }
1533        2 => {
1534            let pk: [u8; 32] = hex::decode(public_hex)
1535                .map_err(|_| "approval key is not hex".to_string())?
1536                .try_into()
1537                .map_err(|_| "approval key must be 32 bytes".to_string())?;
1538            let vk = VerifyingKey::from_bytes(&pk)
1539                .map_err(|_| "approval key is not a valid Ed25519 key")?;
1540            let sig: [u8; 64] = hex::decode(&signed.sig)
1541                .map_err(|_| "approval signature is not hex".to_string())?
1542                .try_into()
1543                .map_err(|_| "approval signature has the wrong length".to_string())?;
1544            vk.verify(&v2_input(&signed.token), &Signature::from_bytes(&sig))
1545                .map_err(|_| "approval signature does not verify")?;
1546            let t: ApprovalTokenV2 = serde_json::from_str(&signed.token)
1547                .map_err(|e| format!("approval is unreadable: {e}"))?;
1548            let kind = match t.kind.as_str() {
1549                "human" => ApprovalKind::Human,
1550                "device" => ApprovalKind::Device,
1551                "rule" => ApprovalKind::Rule,
1552                _ => return Err("approval has an unknown kind".into()),
1553            };
1554            if kind == ApprovalKind::Rule && t.rule_id.as_deref().unwrap_or("").is_empty() {
1555                return Err("a rule approval must name its rule".into());
1556            }
1557            if t.operation_id.is_empty() {
1558                return Err("approval names no operation".into());
1559            }
1560            if t.node_id != node_id {
1561                return Err("approval is for a different node".into());
1562            }
1563            if t.target != target {
1564                return Err("approval is for a different target".into());
1565            }
1566            if t.sha256 != sha256 {
1567                return Err("approval is for different bytes than the ones sent".into());
1568            }
1569            if now_secs >= t.expires_secs {
1570                return Err("approval has expired".into());
1571            }
1572            Ok(Verified {
1573                version: 2,
1574                kind,
1575                nonce: t.nonce,
1576                operation_id: Some(t.operation_id),
1577                rule_id: t.rule_id,
1578            })
1579        }
1580        _ => Err("unknown approval version".into()),
1581    }
1582}
1583
1584/// The hub's automation signing seed (R12), created on first use in the vault's own encrypted
1585/// `vault_meta`, separate from the approval key so each can be rotated and pinned on its own. Its
1586/// public half goes into a node's `automation_approver`.
1587pub fn automation_seed(conn: &rusqlite::Connection) -> Result<String, String> {
1588    use rusqlite::OptionalExtension;
1589    let have: Option<String> = conn
1590        .query_row(
1591            "SELECT value FROM vault_meta WHERE key = 'node_automation_seed'",
1592            [],
1593            |r| r.get(0),
1594        )
1595        .optional()
1596        .map_err(|e| e.to_string())?;
1597    if let Some(s) = have {
1598        return Ok(s);
1599    }
1600    let seed = generate_hub_seed();
1601    conn.execute(
1602        "INSERT OR IGNORE INTO vault_meta (key, value) VALUES ('node_automation_seed', ?1)",
1603        [&seed],
1604    )
1605    .map_err(|e| e.to_string())?;
1606    conn.query_row(
1607        "SELECT value FROM vault_meta WHERE key = 'node_automation_seed'",
1608        [],
1609        |r| r.get(0),
1610    )
1611    .map_err(|e| e.to_string())
1612}
1613
1614#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
1615pub struct SignedApproval {
1616    /// The token as JSON text; the signature covers exactly these bytes.
1617    pub token: String,
1618    pub sig: String,
1619}
1620
1621fn approval_input(token_json: &str) -> Vec<u8> {
1622    format!("envv-approval-v1\n{token_json}").into_bytes()
1623}
1624
1625/// The public key for a hub's approval-signing seed.
1626pub fn hub_public(seed_hex: &str) -> Result<String, String> {
1627    let seed: [u8; 32] = hex::decode(seed_hex)
1628        .map_err(|_| "hub key is not hex".to_string())?
1629        .try_into()
1630        .map_err(|_| "hub key must be 32 bytes".to_string())?;
1631    Ok(hex::encode(
1632        SigningKey::from_bytes(&seed).verifying_key().to_bytes(),
1633    ))
1634}
1635
1636/// A fresh hub approval seed, hex.
1637pub fn generate_hub_seed() -> String {
1638    let mut seed = [0u8; 32];
1639    rand::rng().fill_bytes(&mut seed);
1640    hex::encode(seed)
1641}
1642
1643/// The hub's approval-signing seed, created on first use. It lives in the vault's
1644/// own encrypted `vault_meta` (as the unique-ID registry's secrets do), so a
1645/// copy of `nodes.json` is not enough to forge an approval.
1646pub fn hub_seed(conn: &rusqlite::Connection) -> Result<String, String> {
1647    use rusqlite::OptionalExtension;
1648    let have: Option<String> = conn
1649        .query_row(
1650            "SELECT value FROM vault_meta WHERE key = 'node_hub_seed'",
1651            [],
1652            |r| r.get(0),
1653        )
1654        .optional()
1655        .map_err(|e| e.to_string())?;
1656    if let Some(s) = have {
1657        return Ok(s);
1658    }
1659    let seed = generate_hub_seed();
1660    conn.execute(
1661        "INSERT OR IGNORE INTO vault_meta (key, value) VALUES ('node_hub_seed', ?1)",
1662        [&seed],
1663    )
1664    .map_err(|e| e.to_string())?;
1665    // Two first uses can race; whichever insert won is the key.
1666    conn.query_row(
1667        "SELECT value FROM vault_meta WHERE key = 'node_hub_seed'",
1668        [],
1669        |r| r.get(0),
1670    )
1671    .map_err(|e| e.to_string())
1672}
1673
1674pub fn sign_approval(seed_hex: &str, token: &ApprovalToken) -> Result<SignedApproval, String> {
1675    let seed: [u8; 32] = hex::decode(seed_hex)
1676        .map_err(|_| "hub key is not hex".to_string())?
1677        .try_into()
1678        .map_err(|_| "hub key must be 32 bytes".to_string())?;
1679    let json = serde_json::to_string(token).map_err(|e| e.to_string())?;
1680    let sig = SigningKey::from_bytes(&seed).sign(&approval_input(&json));
1681    Ok(SignedApproval {
1682        token: json,
1683        sig: hex::encode(sig.to_bytes()),
1684    })
1685}
1686
1687/// The owner device's approval seed in `dir/approver.key`, made on first use
1688/// (0600). One file per machine, shared by the CLI and the desktop app.
1689pub fn approver_seed(dir: &Path) -> Result<String, String> {
1690    let path = dir.join("approver.key");
1691    if let Ok(t) = std::fs::read_to_string(&path) {
1692        let t = t.trim().to_string();
1693        hub_public(&t).map_err(|e| format!("{}: {e}", path.display()))?;
1694        return Ok(t);
1695    }
1696    std::fs::create_dir_all(dir).map_err(|e| e.to_string())?;
1697    // On Windows the key used to live under the roaming profile; adopt it rather than make a
1698    // second device identity that no node trusts.
1699    let seed = match legacy_approver_dir().and_then(|old| adopt_legacy_key(&old).ok().flatten()) {
1700        Some(adopted) => adopted,
1701        None => generate_hub_seed(),
1702    };
1703    // Written through the same private-file path as the registry.
1704    let tmp = path.with_extension("key.tmp");
1705    {
1706        use std::io::Write;
1707        let mut o = std::fs::OpenOptions::new();
1708        o.write(true).create_new(true);
1709        #[cfg(unix)]
1710        {
1711            use std::os::unix::fs::OpenOptionsExt;
1712            o.mode(0o600);
1713        }
1714        let _ = std::fs::remove_file(&tmp);
1715        let mut f = o.open(&tmp).map_err(|e| e.to_string())?;
1716        f.write_all(seed.as_bytes()).map_err(|e| e.to_string())?;
1717        f.sync_all().map_err(|e| e.to_string())?;
1718    }
1719    // A second process may have won the race; keep whichever landed first.
1720    if path.exists() {
1721        let _ = std::fs::remove_file(&tmp);
1722        return approver_seed(dir);
1723    }
1724    crate::platform::replace_file(&tmp, &path).map_err(|e| e.to_string())?;
1725    Ok(seed)
1726}
1727
1728/// Where the CLI keeps the device key: the directory the desktop app uses too. On Windows that is
1729/// the machine-local profile, not the roaming one, so a device key never follows the user to
1730/// another computer (a roaming copy would make two machines the same approver).
1731pub fn default_approver_dir() -> Option<PathBuf> {
1732    #[cfg(windows)]
1733    let base = dirs::data_local_dir();
1734    #[cfg(not(windows))]
1735    let base = dirs::data_dir();
1736    base.map(|d| d.join("io.unenverse"))
1737}
1738
1739/// The roaming-profile directory an older Windows build kept the device key in, when it differs
1740/// from where the key lives now.
1741fn legacy_approver_dir() -> Option<PathBuf> {
1742    #[cfg(windows)]
1743    let old = dirs::data_dir()
1744        .map(|d| d.join("io.unenverse"))
1745        .filter(|old| Some(old) != default_approver_dir().as_ref());
1746    #[cfg(not(windows))]
1747    let old = None;
1748    old
1749}
1750
1751/// Reads a valid `approver.key` from `legacy` so the caller can write it to the new place. The old
1752/// file is never touched: an interrupted move leaves the old key working. A missing, unreadable or invalid old key adopts nothing.
1753fn adopt_legacy_key(legacy: &Path) -> Result<Option<String>, String> {
1754    let old = legacy.join("approver.key");
1755    let Ok(text) = std::fs::read_to_string(&old) else {
1756        return Ok(None);
1757    };
1758    let seed = text.trim().to_string();
1759    if hub_public(&seed).is_err() {
1760        return Ok(None);
1761    }
1762    Ok(Some(seed))
1763}
1764
1765/// Signs an approval on the owner's device for exactly one request. The lifetime
1766/// is the hub's own ([`APPROVAL_TTL_SECS`]); the nonce is fresh.
1767pub fn sign_device_approval(
1768    seed_hex: &str,
1769    node_id: &str,
1770    target: &str,
1771    sha256: &str,
1772    approval_id: &str,
1773    now_secs: i64,
1774    now_iso: &str,
1775) -> Result<SignedApproval, String> {
1776    let fp = key_fingerprint(&hub_public(seed_hex)?)?;
1777    sign_approval(
1778        seed_hex,
1779        &ApprovalToken {
1780            v: 1,
1781            node_id: node_id.into(),
1782            target: target.into(),
1783            sha256: sha256.into(),
1784            approval_id: approval_id.into(),
1785            approved_by: format!("device:{}", &fp[..12]),
1786            approved_at: now_iso.into(),
1787            expires_secs: now_secs + APPROVAL_TTL_SECS,
1788            nonce: crate::new_uuid(),
1789        },
1790    )
1791}
1792
1793/// Checks a token the way a node does before it writes: the signature is the
1794/// hub's, it names this node, this target and exactly this hash, and it has not
1795/// expired. Returns the token so the caller can remember its nonce.
1796pub fn verify_approval(
1797    hub_public_hex: &str,
1798    signed: &SignedApproval,
1799    node_id: &str,
1800    target: &str,
1801    sha256: &str,
1802    now_secs: i64,
1803) -> Result<ApprovalToken, String> {
1804    let pk: [u8; 32] = hex::decode(hub_public_hex)
1805        .map_err(|_| "hub key is not hex".to_string())?
1806        .try_into()
1807        .map_err(|_| "hub key must be 32 bytes".to_string())?;
1808    let vk = VerifyingKey::from_bytes(&pk).map_err(|_| "hub key is not a valid Ed25519 key")?;
1809    let sig: [u8; 64] = hex::decode(&signed.sig)
1810        .map_err(|_| "approval signature is not hex".to_string())?
1811        .try_into()
1812        .map_err(|_| "approval signature has the wrong length".to_string())?;
1813    vk.verify(&approval_input(&signed.token), &Signature::from_bytes(&sig))
1814        .map_err(|_| "approval signature does not verify")?;
1815    let t: ApprovalToken =
1816        serde_json::from_str(&signed.token).map_err(|e| format!("approval is unreadable: {e}"))?;
1817    if t.v != 1 {
1818        return Err("unknown approval version".into());
1819    }
1820    if t.node_id != node_id {
1821        return Err("approval is for a different node".into());
1822    }
1823    if t.target != target {
1824        return Err("approval is for a different target".into());
1825    }
1826    if t.sha256 != sha256 {
1827        return Err("approval is for different bytes than the ones sent".into());
1828    }
1829    if now_secs >= t.expires_secs {
1830        return Err("approval has expired".into());
1831    }
1832    Ok(t)
1833}
1834
1835/// The status word for a push that is ready but may be held.
1836fn approval_status(
1837    approvals: &[ApprovalRecord],
1838    node_id: &str,
1839    target: &str,
1840    sha: &str,
1841    now_secs: i64,
1842) -> &'static str {
1843    match latest_approval(approvals, node_id, target, sha) {
1844        Some(a)
1845            if a.status == "approved"
1846                && now_secs < a.decided_secs.unwrap_or(0) + APPROVAL_TTL_SECS =>
1847        {
1848            "pending"
1849        }
1850        Some(a) if a.status == "rejected" => "rejected",
1851        _ => "awaiting_approval",
1852    }
1853}
1854
1855fn latest_approval<'a>(
1856    approvals: &'a [ApprovalRecord],
1857    node_id: &str,
1858    target: &str,
1859    sha: &str,
1860) -> Option<&'a ApprovalRecord> {
1861    approvals
1862        .iter()
1863        .rev()
1864        .find(|a| a.node_id == node_id && a.target == target && a.sha256 == sha)
1865}
1866
1867/// The longest a lease may last. A lease that outlived its holder would freeze a target.
1868pub const MAX_LEASE_SECS: i64 = 3600;
1869
1870/// A hold on one target of one node (R12): while it lives, the hub pushes that target only the
1871/// bytes with this hash. A rotation takes a lease on the rendering that carries the new credential,
1872/// so a regular auto-push of an older rendering (a save from a stale window, say) cannot put the
1873/// old credential back on the host half way through.
1874#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
1875pub struct Lease {
1876    pub node_id: String,
1877    pub target: String,
1878    /// The only content hash the hub will push to this target while the lease lives.
1879    pub sha256: String,
1880    /// Who holds it (a rotation run id, say). Only the holder may release or replace it.
1881    pub holder: String,
1882    pub expires_secs: i64,
1883}
1884
1885impl NodeStore {
1886    /// Takes a lease on `target` of `node_id`, or replaces the caller's own. Refused while another
1887    /// holder's lease is alive, and for a lifetime over [`MAX_LEASE_SECS`].
1888    pub fn lease_target(
1889        &mut self,
1890        node_id: &str,
1891        target: &str,
1892        sha256: &str,
1893        holder: &str,
1894        ttl_secs: i64,
1895        now_secs: i64,
1896    ) -> Result<Lease, String> {
1897        if !self
1898            .data
1899            .nodes
1900            .iter()
1901            .any(|n| n.id == node_id && n.revoked_at.is_none())
1902        {
1903            return Err("No such node".into());
1904        }
1905        if !(1..=MAX_LEASE_SECS).contains(&ttl_secs) {
1906            return Err(format!(
1907                "a lease lasts 1 to {MAX_LEASE_SECS} seconds, not {ttl_secs}"
1908            ));
1909        }
1910        if sha256.len() != 64 || !sha256.bytes().all(|b| b.is_ascii_hexdigit()) {
1911            return Err("a lease names the content it allows by its SHA-256".into());
1912        }
1913        if holder.is_empty() || holder.len() > 64 {
1914            return Err("a lease needs a holder of 1 to 64 characters".into());
1915        }
1916        self.data.leases.retain(|l| l.expires_secs > now_secs);
1917        if let Some(other) = self
1918            .data
1919            .leases
1920            .iter()
1921            .find(|l| l.node_id == node_id && l.target == target && l.holder != holder)
1922        {
1923            return Err(format!("{target} is leased by {}", other.holder));
1924        }
1925        self.data
1926            .leases
1927            .retain(|l| !(l.node_id == node_id && l.target == target));
1928        let lease = Lease {
1929            node_id: node_id.to_string(),
1930            target: target.to_string(),
1931            sha256: sha256.to_ascii_lowercase(),
1932            holder: holder.to_string(),
1933            expires_secs: now_secs + ttl_secs,
1934        };
1935        self.data.leases.push(lease.clone());
1936        self.save()?;
1937        Ok(lease)
1938    }
1939
1940    /// Ends the lease on `target`, which only its holder may do. An expired lease is already gone.
1941    pub fn release_lease(
1942        &mut self,
1943        node_id: &str,
1944        target: &str,
1945        holder: &str,
1946        now_secs: i64,
1947    ) -> Result<(), String> {
1948        let live = self
1949            .data
1950            .leases
1951            .iter()
1952            .find(|l| l.node_id == node_id && l.target == target && l.expires_secs > now_secs)
1953            .cloned();
1954        match live {
1955            None => Err("No such lease".into()),
1956            Some(l) if l.holder != holder => Err(format!("{target} is leased by {}", l.holder)),
1957            Some(_) => {
1958                self.data
1959                    .leases
1960                    .retain(|l| !(l.node_id == node_id && l.target == target));
1961                self.save()
1962            }
1963        }
1964    }
1965
1966    /// The live lease on `target`, if any.
1967    pub fn lease_for(&self, node_id: &str, target: &str, now_secs: i64) -> Option<Lease> {
1968        self.data
1969            .leases
1970            .iter()
1971            .find(|l| l.node_id == node_id && l.target == target && l.expires_secs > now_secs)
1972            .cloned()
1973    }
1974
1975    /// Every live lease.
1976    pub fn leases(&self, now_secs: i64) -> Vec<Lease> {
1977        self.data
1978            .leases
1979            .iter()
1980            .filter(|l| l.expires_secs > now_secs)
1981            .cloned()
1982            .collect()
1983    }
1984}
1985
1986impl NodeStore {
1987    /// Sets whether every push to a node is held for a human.
1988    pub fn set_approval_policy(&mut self, id: &str, policy: &str) -> Result<NodeRecord, String> {
1989        if !matches!(policy, "required" | "none" | "device") {
1990            return Err("approval must be \"required\", \"device\" or \"none\"".into());
1991        }
1992        if policy == "device" && self.data.approvers.is_empty() {
1993            return Err(
1994                "Register an approver device first (`unv node approver register`); \
1995                 otherwise nothing could ever approve this node's pushes."
1996                    .into(),
1997            );
1998        }
1999        let n = self
2000            .data
2001            .nodes
2002            .iter_mut()
2003            .find(|n| n.id == id && n.revoked_at.is_none())
2004            .ok_or("No such node")?;
2005        n.approval = if policy == "none" {
2006            String::new()
2007        } else {
2008            policy.to_string()
2009        };
2010        let out = n.clone();
2011        self.save()?;
2012        Ok(out)
2013    }
2014
2015    /// The approval for exactly these bytes, if there is one and it can still be
2016    /// used: approved, within its lifetime, for an active node.
2017    pub fn usable_approval(
2018        &self,
2019        node_id: &str,
2020        target: &str,
2021        sha: &str,
2022        now_secs: i64,
2023    ) -> Option<ApprovalRecord> {
2024        let node_ok = self
2025            .data
2026            .nodes
2027            .iter()
2028            .any(|n| n.id == node_id && n.revoked_at.is_none());
2029        latest_approval(&self.data.approvals, node_id, target, sha)
2030            .filter(|a| {
2031                node_ok
2032                    && a.status == "approved"
2033                    && now_secs < a.decided_secs.unwrap_or(0) + APPROVAL_TTL_SECS
2034            })
2035            .cloned()
2036    }
2037
2038    /// The newest request for these bytes in any state.
2039    pub fn approval_for(&self, node_id: &str, target: &str, sha: &str) -> Option<ApprovalRecord> {
2040        latest_approval(&self.data.approvals, node_id, target, sha).cloned()
2041    }
2042
2043    /// Opens a request for a human, unless one for the same bytes is already
2044    /// open, decided, or spent. A consumed or expired request for the same bytes
2045    /// (a revert) opens a fresh one: an old yes does not cover a later push.
2046    #[allow(clippy::too_many_arguments)]
2047    pub fn request_approval(
2048        &mut self,
2049        node_id: &str,
2050        target: &TargetReport,
2051        sha: &str,
2052        from_seq: Option<i64>,
2053        to_seq: Option<i64>,
2054        now_secs: i64,
2055        now_iso: &str,
2056    ) -> Result<ApprovalRecord, String> {
2057        if let Some(a) = latest_approval(&self.data.approvals, node_id, &target.id, sha) {
2058            if matches!(a.status.as_str(), "pending" | "approved" | "rejected") {
2059                return Ok(a.clone());
2060            }
2061        }
2062        // Bound the table: spent requests are history the audit chain keeps.
2063        self.data.approvals.retain(|a| {
2064            matches!(a.status.as_str(), "pending" | "approved")
2065                || now_secs - a.requested_secs < 7 * 86_400
2066        });
2067        let rec = ApprovalRecord {
2068            id: crate::new_uuid(),
2069            node_id: node_id.to_string(),
2070            target: target.id.clone(),
2071            project: target.project.clone(),
2072            exporter: target.exporter.clone(),
2073            sha256: sha.to_string(),
2074            from_sha: target.sha256.clone(),
2075            from_seq,
2076            to_seq,
2077            requested_at: now_iso.to_string(),
2078            requested_secs: now_secs,
2079            status: "pending".into(),
2080            decided_at: None,
2081            decided_secs: None,
2082            decided_by: None,
2083            signed: None,
2084        };
2085        self.data.approvals.push(rec.clone());
2086        self.save()?;
2087        Ok(rec)
2088    }
2089
2090    /// A human's answer. Only a pending request can be decided: an approval is
2091    /// never revived, and a decision on stale bytes is a decision on a request
2092    /// the hub no longer asks for.
2093    pub fn decide(
2094        &mut self,
2095        approval_id: &str,
2096        approve: bool,
2097        by: &str,
2098        now_secs: i64,
2099        now_iso: &str,
2100    ) -> Result<ApprovalRecord, String> {
2101        let a = self
2102            .data
2103            .approvals
2104            .iter_mut()
2105            .find(|a| a.id == approval_id)
2106            .ok_or("No such approval request")?;
2107        if a.status != "pending" {
2108            return Err(format!("That request is already {}", a.status));
2109        }
2110        if now_secs >= a.requested_secs + PENDING_TTL_SECS {
2111            a.status = "expired".into();
2112            let _ = self.save();
2113            return Err("That request has expired; the next beat opens a new one".into());
2114        }
2115        a.status = if approve { "approved" } else { "rejected" }.into();
2116        a.decided_at = Some(now_iso.to_string());
2117        a.decided_secs = Some(now_secs);
2118        a.decided_by = Some(by.to_string());
2119        let out = a.clone();
2120        self.save()?;
2121        Ok(out)
2122    }
2123
2124    /// Registers a device whose signature counts as the owner's approval.
2125    pub fn add_approver(
2126        &mut self,
2127        pubkey_hex: &str,
2128        label: &str,
2129        now_iso: &str,
2130    ) -> Result<Approver, String> {
2131        let raw: [u8; 32] = hex::decode(pubkey_hex)
2132            .map_err(|_| "public key is not hex".to_string())?
2133            .try_into()
2134            .map_err(|_| "public key must be 32 bytes".to_string())?;
2135        VerifyingKey::from_bytes(&raw).map_err(|_| "public key is not a valid Ed25519 key")?;
2136        let label = label.trim();
2137        if label.is_empty() || label.len() > 64 || label.chars().any(char::is_control) {
2138            return Err("give the device a short label (up to 64 characters)".into());
2139        }
2140        let pubkey = pubkey_hex.to_ascii_lowercase();
2141        if let Some(a) = self.data.approvers.iter().find(|a| a.pubkey == pubkey) {
2142            return Ok(a.clone());
2143        }
2144        if self.data.approvers.len() >= 16 {
2145            return Err("at most 16 approver devices".into());
2146        }
2147        let a = Approver {
2148            fingerprint: key_fingerprint(&pubkey)?,
2149            pubkey,
2150            label: label.to_string(),
2151            added: now_iso.to_string(),
2152        };
2153        self.data.approvers.push(a.clone());
2154        self.save()?;
2155        Ok(a)
2156    }
2157
2158    /// Removes a device by (a prefix of at least 8 characters of) its fingerprint.
2159    /// Nodes set to `device` approval lose their only approver if this was the
2160    /// last one: they fall back to `required`, so nothing is left unapprovable and
2161    /// nothing silently becomes approvable by the hub alone.
2162    pub fn remove_approver(&mut self, fp_prefix: &str) -> Result<Approver, String> {
2163        if fp_prefix.len() < 8 {
2164            return Err("name at least 8 characters of the fingerprint".into());
2165        }
2166        let hits: Vec<usize> = self
2167            .data
2168            .approvers
2169            .iter()
2170            .enumerate()
2171            .filter(|(_, a)| a.fingerprint.starts_with(fp_prefix))
2172            .map(|(i, _)| i)
2173            .collect();
2174        let [i] = hits[..] else {
2175            return Err(if hits.is_empty() {
2176                "No such approver".into()
2177            } else {
2178                "That prefix fits more than one approver".into()
2179            });
2180        };
2181        let gone = self.data.approvers.remove(i);
2182        if self.data.approvers.is_empty() {
2183            for n in self
2184                .data
2185                .nodes
2186                .iter_mut()
2187                .filter(|n| n.approval == "device")
2188            {
2189                n.approval = "required".into();
2190            }
2191        }
2192        self.save()?;
2193        Ok(gone)
2194    }
2195
2196    pub fn approvers(&self) -> Vec<Approver> {
2197        self.data.approvers.clone()
2198    }
2199
2200    /// A human's yes, signed on their own device. The hub holds no key that could
2201    /// have made it: it checks the signature against the registered devices, that
2202    /// the token names exactly this request (node, target, bytes, request id), and
2203    /// that its lifetime is no longer than the hub's own.
2204    pub fn decide_signed(
2205        &mut self,
2206        approval_id: &str,
2207        signed: SignedApproval,
2208        now_secs: i64,
2209        now_iso: &str,
2210    ) -> Result<ApprovalRecord, String> {
2211        let keys: Vec<(String, String)> = self
2212            .data
2213            .approvers
2214            .iter()
2215            .map(|a| (a.pubkey.clone(), a.fingerprint.clone()))
2216            .collect();
2217        let rec = self
2218            .data
2219            .approvals
2220            .iter_mut()
2221            .find(|a| a.id == approval_id)
2222            .ok_or("No such approval request")?;
2223        if rec.status != "pending" {
2224            return Err(format!("That request is already {}", rec.status));
2225        }
2226        if now_secs >= rec.requested_secs + PENDING_TTL_SECS {
2227            rec.status = "expired".into();
2228            let _ = self.save();
2229            return Err("That request has expired; the next beat opens a new one".into());
2230        }
2231        let mut by = None;
2232        let mut last_err = "no approver device is registered".to_string();
2233        for (pk, fp) in &keys {
2234            match verify_approval(
2235                pk,
2236                &signed,
2237                &rec.node_id,
2238                &rec.target,
2239                &rec.sha256,
2240                now_secs,
2241            ) {
2242                Ok(t) => {
2243                    if t.approval_id != rec.id {
2244                        last_err = "approval is for a different request".into();
2245                        continue;
2246                    }
2247                    if t.expires_secs > now_secs + APPROVAL_TTL_SECS + 60 {
2248                        last_err = "approval lasts longer than the hub allows".into();
2249                        continue;
2250                    }
2251                    if t.nonce.is_empty() {
2252                        last_err = "approval has no nonce".into();
2253                        continue;
2254                    }
2255                    by = Some(format!("device:{}", &fp[..12]));
2256                    break;
2257                }
2258                Err(e) => last_err = e,
2259            }
2260        }
2261        let Some(by) = by else {
2262            return Err(format!("Not accepted: {last_err}"));
2263        };
2264        rec.status = "approved".into();
2265        rec.decided_at = Some(now_iso.to_string());
2266        rec.decided_secs = Some(now_secs);
2267        rec.decided_by = Some(by);
2268        rec.signed = Some(signed);
2269        let out = rec.clone();
2270        self.save()?;
2271        Ok(out)
2272    }
2273
2274    /// Requests, newest first; for one node or all.
2275    pub fn approvals(&self, node_id: Option<&str>) -> Vec<ApprovalRecord> {
2276        let mut v: Vec<ApprovalRecord> = self
2277            .data
2278            .approvals
2279            .iter()
2280            .filter(|a| node_id.is_none_or(|n| a.node_id == n))
2281            .cloned()
2282            .collect();
2283        v.reverse();
2284        v
2285    }
2286}
2287
2288#[cfg(test)]
2289mod tests {
2290    use super::*;
2291
2292    fn scratch(tag: &str) -> PathBuf {
2293        // A counter beside the process id, not the clock: two tests starting within one clock tick
2294        // (macOS has a coarse one) shared a directory and failed with "database is locked".
2295        let n = {
2296            use std::sync::atomic::{AtomicU64, Ordering};
2297            static SEQ: AtomicU64 = AtomicU64::new(0);
2298            format!(
2299                "{}-{}",
2300                std::process::id(),
2301                SEQ.fetch_add(1, Ordering::SeqCst)
2302            )
2303        };
2304        let d = std::env::temp_dir().join(format!("unv-nodes-{tag}-{n}"));
2305        std::fs::create_dir_all(&d).unwrap();
2306        d
2307    }
2308
2309    fn enrolled() -> (NodeStore, NodeRecord, String, PathBuf) {
2310        let dir = scratch("store");
2311        let mut s = NodeStore::open(&dir.join("nodes.json")).unwrap();
2312        let (seed, public) = generate_identity();
2313        let (tok, _) = s
2314            .mint_token("vps-01", vec!["edge".into()], 900, 1_000)
2315            .unwrap();
2316        let n = s
2317            .enroll(&tok, &public, None, 1_001, "2026-10-08T00:00:00Z")
2318            .unwrap();
2319        (s, n, seed, dir)
2320    }
2321
2322    fn report(mode: &str, apply: bool, sha: Option<&str>) -> TargetReport {
2323        TargetReport {
2324            id: "nginx-main".into(),
2325            project: "edge".into(),
2326            exporter: "nginx".into(),
2327            mode: mode.into(),
2328            apply,
2329            sha256: sha.map(String::from),
2330            state: "ok".into(),
2331            error: None,
2332            accept_rule_approval: false,
2333        }
2334    }
2335
2336    #[test]
2337    fn a_signature_covers_method_path_time_and_body() {
2338        let (seed, public) = generate_identity();
2339        let sig = sign_request(&seed, "POST", "/api/nodes/beat", 5, b"{}").unwrap();
2340        assert!(verify_request(
2341            &public,
2342            "post",
2343            "/api/nodes/beat",
2344            5,
2345            b"{}",
2346            &sig
2347        ));
2348        assert!(!verify_request(
2349            &public,
2350            "POST",
2351            "/api/nodes/upload",
2352            5,
2353            b"{}",
2354            &sig
2355        ));
2356        assert!(!verify_request(
2357            &public,
2358            "POST",
2359            "/api/nodes/beat",
2360            6,
2361            b"{}",
2362            &sig
2363        ));
2364        assert!(!verify_request(
2365            &public,
2366            "POST",
2367            "/api/nodes/beat",
2368            5,
2369            b"{ }",
2370            &sig
2371        ));
2372        let (_, other) = generate_identity();
2373        assert!(!verify_request(
2374            &other,
2375            "POST",
2376            "/api/nodes/beat",
2377            5,
2378            b"{}",
2379            &sig
2380        ));
2381        assert!(!verify_request("zz", "POST", "/", 5, b"", "00"));
2382    }
2383
2384    #[test]
2385    fn a_token_enrolls_exactly_one_node_and_only_once() {
2386        let dir = scratch("once");
2387        let mut s = NodeStore::open(&dir.join("nodes.json")).unwrap();
2388        let (tok, _) = s.mint_token("a", vec!["p".into()], 900, 100).unwrap();
2389        let (_, pk) = generate_identity();
2390        s.enroll(&tok, &pk, None, 101, "t").unwrap();
2391        let (_, pk2) = generate_identity();
2392        let again = s.enroll(&tok, &pk2, None, 102, "t").unwrap_err();
2393        assert_eq!(again, "Invalid or expired enrollment token");
2394        assert_eq!(s.list().len(), 1);
2395    }
2396
2397    #[test]
2398    fn an_expired_or_unknown_token_gets_the_same_answer() {
2399        let dir = scratch("exp");
2400        let mut s = NodeStore::open(&dir.join("nodes.json")).unwrap();
2401        let (tok, exp) = s.mint_token("a", vec!["p".into()], 60, 100).unwrap();
2402        let (_, pk) = generate_identity();
2403        let late = s.enroll(&tok, &pk, None, exp, "t").unwrap_err();
2404        let unknown = s.enroll("envn_nope", &pk, None, 101, "t").unwrap_err();
2405        assert_eq!(late, unknown);
2406    }
2407
2408    #[test]
2409    fn the_token_is_stored_as_a_hash() {
2410        let dir = scratch("hash");
2411        let mut s = NodeStore::open(&dir.join("nodes.json")).unwrap();
2412        let (tok, _) = s.mint_token("a", vec!["p".into()], 900, 100).unwrap();
2413        let on_disk = std::fs::read_to_string(dir.join("nodes.json")).unwrap();
2414        assert!(
2415            !on_disk.contains(&tok),
2416            "plaintext token reached nodes.json"
2417        );
2418        assert!(on_disk.contains(&token_hash(&tok)));
2419    }
2420
2421    #[test]
2422    fn a_key_that_is_not_a_curve_point_is_refused_and_does_not_spend_the_token() {
2423        let dir = scratch("badkey");
2424        let mut s = NodeStore::open(&dir.join("nodes.json")).unwrap();
2425        let (tok, _) = s.mint_token("a", vec!["p".into()], 900, 100).unwrap();
2426        // About half of all 32-byte strings do not decompress to a point.
2427        let bad = (0u8..=255)
2428            .map(|b| hex::encode([b; 32]))
2429            .find(|k| {
2430                VerifyingKey::from_bytes(&hex::decode(k).unwrap().try_into().unwrap()).is_err()
2431            })
2432            .expect("some repeated byte is not a point");
2433        assert!(s
2434            .enroll(&tok, &bad, None, 101, "t")
2435            .unwrap_err()
2436            .contains("valid Ed25519"));
2437        let (_, ok) = generate_identity();
2438        assert!(
2439            s.enroll(&tok, &ok, None, 102, "t").is_ok(),
2440            "a refused key spent the token"
2441        );
2442    }
2443
2444    #[test]
2445    fn authentication_refuses_replay_skew_revocation_and_forgery() {
2446        let (mut s, n, seed, _d) = enrolled();
2447        let now = 1_700_000_000_000i64;
2448        let sig = |ts: i64| sign_request(&seed, "POST", "/api/nodes/beat", ts, b"x").unwrap();
2449        let auth = |s: &mut NodeStore, ts: i64, sg: &str| {
2450            s.authenticate(&n.id, "POST", "/api/nodes/beat", ts, b"x", sg, now)
2451        };
2452        assert!(auth(&mut s, now, &sig(now)).is_ok());
2453        // The same request again is a replay, not a second beat.
2454        assert_eq!(auth(&mut s, now, &sig(now)).unwrap_err(), AuthError::Replay);
2455        assert_eq!(
2456            auth(&mut s, now - 1, &sig(now - 1)).unwrap_err(),
2457            AuthError::Replay
2458        );
2459        assert!(auth(&mut s, now + 1, &sig(now + 1)).is_ok());
2460        let far = now + 61_000;
2461        assert_eq!(auth(&mut s, far, &sig(far)).unwrap_err(), AuthError::Skew);
2462        assert_eq!(
2463            auth(&mut s, now + 2, "00").unwrap_err(),
2464            AuthError::BadSignature
2465        );
2466        s.revoke(&n.id, "t").unwrap();
2467        assert_eq!(
2468            auth(&mut s, now + 3, &sig(now + 3)).unwrap_err(),
2469            AuthError::Revoked
2470        );
2471    }
2472
2473    #[test]
2474    fn the_replay_mark_survives_a_restart() {
2475        let (mut s, n, seed, dir) = enrolled();
2476        let now = 1_700_000_000_000i64;
2477        let sig = sign_request(&seed, "POST", "/p", now, b"").unwrap();
2478        s.authenticate(&n.id, "POST", "/p", now, b"", &sig, now)
2479            .unwrap();
2480        let mut reopened = NodeStore::open(&dir.join("nodes.json")).unwrap();
2481        assert_eq!(
2482            reopened
2483                .authenticate(&n.id, "POST", "/p", now, b"", &sig, now)
2484                .unwrap_err(),
2485            AuthError::Replay
2486        );
2487    }
2488
2489    #[test]
2490    fn a_corrupt_registry_is_an_error_not_an_empty_one() {
2491        let dir = scratch("corrupt");
2492        std::fs::write(dir.join("nodes.json"), "{ not json").unwrap();
2493        assert!(NodeStore::open(&dir.join("nodes.json")).is_err());
2494    }
2495
2496    #[cfg(unix)]
2497    #[test]
2498    fn the_registry_is_private() {
2499        use std::os::unix::fs::PermissionsExt;
2500        let (_s, _n, _seed, dir) = enrolled();
2501        let mode = std::fs::metadata(dir.join("nodes.json"))
2502            .unwrap()
2503            .permissions()
2504            .mode();
2505        assert_eq!(mode & 0o777, 0o600);
2506    }
2507
2508    #[test]
2509    fn status_words() {
2510        let none = None;
2511        let d = Some("aa");
2512        assert_eq!(
2513            derive_status(&report("push", false, Some("aa")), d, None, &none),
2514            "in_sync"
2515        );
2516        assert_eq!(
2517            derive_status(&report("push", false, Some("bb")), d, None, &none),
2518            "drift"
2519        );
2520        assert_eq!(
2521            derive_status(&report("push", true, Some("bb")), d, None, &none),
2522            "pending"
2523        );
2524        assert_eq!(
2525            derive_status(&report("push", false, None), d, None, &none),
2526            "missing"
2527        );
2528        assert_eq!(
2529            derive_status(&report("push", false, Some("aa")), None, None, &none),
2530            "unknown"
2531        );
2532        assert_eq!(
2533            derive_status(
2534                &report("push", true, Some("aa")),
2535                d,
2536                None,
2537                &Some("no".into())
2538            ),
2539            "refused"
2540        );
2541        assert_eq!(
2542            derive_status(&report("pull", false, Some("aa")), None, None, &none),
2543            "unreviewed"
2544        );
2545        assert_eq!(
2546            derive_status(&report("pull", false, Some("aa")), None, Some("aa"), &none),
2547            "in_sync"
2548        );
2549        assert_eq!(
2550            derive_status(&report("pull", false, Some("bb")), None, Some("aa"), &none),
2551            "changed"
2552        );
2553        assert_eq!(
2554            derive_status(&report("pull", false, None), None, Some("aa"), &none),
2555            "missing"
2556        );
2557    }
2558
2559    #[test]
2560    fn a_node_cannot_be_sent_a_project_it_was_not_enrolled_for() {
2561        let (mut s, n, _seed, _d) = enrolled();
2562        let mut r = report("push", true, Some("bb"));
2563        r.project = "payroll".into();
2564        let beat = Beat {
2565            targets: vec![r],
2566            ..Default::default()
2567        };
2568        s.record_beat(&n.id, &beat, &|_| Ok("aa".into()), "t")
2569            .unwrap();
2570        let t = &s.get(&n.id).unwrap().targets[0];
2571        assert_eq!(t.status, "refused");
2572        assert!(t.desired_sha.is_none());
2573    }
2574
2575    #[test]
2576    fn accepting_a_pull_target_records_its_current_hash() {
2577        let (mut s, n, _seed, _d) = enrolled();
2578        let beat = Beat {
2579            targets: vec![report("pull", false, Some("cc"))],
2580            ..Default::default()
2581        };
2582        s.record_beat(&n.id, &beat, &|_| Err("x".into()), "t")
2583            .unwrap();
2584        assert_eq!(s.get(&n.id).unwrap().targets[0].status, "unreviewed");
2585        s.accept(&n.id, "nginx-main", None).unwrap();
2586        // The next beat still sees the accepted hash.
2587        s.record_beat(&n.id, &beat, &|_| Err("x".into()), "t")
2588            .unwrap();
2589        assert_eq!(s.get(&n.id).unwrap().targets[0].status, "in_sync");
2590    }
2591
2592    #[test]
2593    fn config_parses_and_every_mistake_is_named() {
2594        let ok = r#"
2595interval_secs = 30
2596[[target]]
2597id = "nginx-main"
2598path = "/etc/nginx/sites-enabled/x.conf"
2599project = "edge"
2600exporter = "nginx"
2601apply = true
2602validate = "nginx -t"
2603reload = "systemctl reload nginx"
2604"#;
2605        let c = NodeConfig::parse(ok).unwrap();
2606        assert_eq!(c.targets[0].mode, "push");
2607        let bad = |t: &str| NodeConfig::parse(t).unwrap_err();
2608        let base = |extra: &str| {
2609            format!(
2610                "[[target]]\nid=\"a\"\npath=\"/etc/a\"\nproject=\"p\"\nexporter=\"nginx\"\n{extra}"
2611            )
2612        };
2613        assert!(bad(&base("aply = true")).contains("unknown field"));
2614        assert!(bad(&base("mode = \"sideways\"")).contains("mode must be"));
2615        assert!(bad(&base("mode = \"pull\"\napply = true")).contains("only read"));
2616        assert!(bad(&base("mode = \"pull\"\nreload = \"x\"")).contains("only read"));
2617        assert!(bad(&base("reload = \"\"")).contains("reload"));
2618        assert!(bad(&base("").replace("/etc/a", "etc/a")).contains("absolute"));
2619        assert!(bad(&base("").replace("nginx", "emacs")).contains("unknown exporter"));
2620        assert!(bad(&base("").replace("id=\"a\"", "id=\"../a\"")).contains("id"));
2621        assert!(bad(&format!("{}\n{}", base(""), base(""))).contains("twice"));
2622        assert!(bad("interval_secs = 1").contains("interval_secs"));
2623    }
2624    // ── Approval (Phase 37) ───────────────────────────────────────────────────
2625
2626    fn token(node: &str, target: &str, sha: &str, exp: i64) -> ApprovalToken {
2627        ApprovalToken {
2628            v: 1,
2629            node_id: node.into(),
2630            target: target.into(),
2631            sha256: sha.into(),
2632            approval_id: "a1".into(),
2633            approved_by: "owner".into(),
2634            approved_at: "t".into(),
2635            expires_secs: exp,
2636            nonce: "n1".into(),
2637        }
2638    }
2639
2640    // N3: the node wrote the approved bytes, then somebody edited the file before the
2641    // next beat. The beat reports the edited hash plus the ok result of the write. The
2642    // approval stayed "approved", so the hub pushed the same bytes again over the edit.
2643    // N6: grants are project names. A deleted project's name stayed on the node, so a
2644    // project created later under that name was pushed to the node without the owner
2645    // ever granting it.
2646    #[test]
2647    fn a_grant_for_a_deleted_project_is_dropped() {
2648        let (mut s, n, _seed, _d) = enrolled();
2649        assert_eq!(s.get(&n.id).unwrap().projects, vec!["edge".to_string()]);
2650        assert!(s.prune_projects(&["edge".into()]).unwrap().is_empty());
2651        let gone = s.prune_projects(&["other".into()]).unwrap();
2652        assert_eq!(gone, vec![("vps-01".to_string(), "edge".to_string())]);
2653        assert!(s.get(&n.id).unwrap().projects.is_empty());
2654    }
2655
2656    // N12: two open tokens for one name enrolled two nodes with that name, and a
2657    // failed save left the node live in memory with its token spent.
2658    #[test]
2659    fn a_name_has_one_open_token_and_a_failed_enrol_save_is_rolled_back() {
2660        let dir = scratch("dup");
2661        let mut s = NodeStore::open(&dir.join("nodes.json")).unwrap();
2662        let (tok, _) = s
2663            .mint_token("vps-01", vec!["edge".into()], 900, 1_000)
2664            .unwrap();
2665        assert!(s
2666            .mint_token("vps-01", vec!["edge".into()], 900, 1_001)
2667            .unwrap_err()
2668            .contains("already open"));
2669        // The file's directory vanishes: save fails.
2670        let (_seed, public) = generate_identity();
2671        std::fs::remove_dir_all(&dir).unwrap();
2672        std::fs::write(&dir, b"not a directory").unwrap();
2673        assert!(s.enroll(&tok, &public, None, 1_002, "t").is_err());
2674        assert!(
2675            s.list().is_empty(),
2676            "a node that is not on disk is not enrolled"
2677        );
2678        std::fs::remove_file(&dir).unwrap();
2679        std::fs::create_dir_all(&dir).unwrap();
2680        let n = s.enroll(&tok, &public, None, 1_003, "t").unwrap();
2681        assert_eq!(n.name, "vps-01", "the token still works for a retry");
2682    }
2683
2684    #[test]
2685    fn a_reported_write_spends_the_approval_even_if_the_file_was_edited_since() {
2686        let (mut s, n, _seed, _d) = enrolled();
2687        let a = request(&mut s, &n.id, "v1", 1_000);
2688        s.decide(&a.id, true, "owner", 1_001, "t").unwrap();
2689        let beat = Beat {
2690            targets: vec![report("push", true, Some("edited-locally"))],
2691            results: vec![ApplyResult {
2692                target: "nginx-main".into(),
2693                at: "t".into(),
2694                sha256: "v1".into(),
2695                ok: true,
2696                error: None,
2697                phases: Vec::new(),
2698            }],
2699            ..Default::default()
2700        };
2701        s.record_beat(&n.id, &beat, &|_| Ok("v1".into()), "t")
2702            .unwrap();
2703        assert_eq!(
2704            s.approval_for(&n.id, "nginx-main", "v1").unwrap().status,
2705            "consumed"
2706        );
2707        assert!(s
2708            .usable_approval(&n.id, "nginx-main", "v1", 1_002)
2709            .is_none());
2710    }
2711
2712    fn v2(kind: &str, node: &str, target: &str, sha: &str, expires: i64) -> ApprovalTokenV2 {
2713        ApprovalTokenV2 {
2714            v: 2,
2715            kind: kind.into(),
2716            node_id: node.into(),
2717            target: target.into(),
2718            sha256: sha.into(),
2719            approval_id: "a1".into(),
2720            operation_id: "op1".into(),
2721            credential_generation: Some(4),
2722            policy_rev: 7,
2723            rule_id: (kind == "rule").then(|| "node-push".into()),
2724            approved_by: "someone".into(),
2725            approved_at: "t".into(),
2726            expires_secs: expires,
2727            nonce: "n-1".into(),
2728        }
2729    }
2730
2731    /// Version 2 carries its kind and the operation it belongs to, and each kind verifies only
2732    /// for the node, target and bytes it names, before its expiry.
2733    #[test]
2734    fn a_version_2_approval_names_its_kind_operation_and_the_bytes_and_lapses() {
2735        let seed = generate_hub_seed();
2736        let public = hub_public(&seed).unwrap();
2737        for kind in ["human", "device", "rule"] {
2738            let signed = sign_approval_v2(&seed, &v2(kind, "n1", "nginx", "abc", 2_000)).unwrap();
2739            let v = verify_approval_any(&public, &signed, "n1", "nginx", "abc", 1_000).unwrap();
2740            assert_eq!(v.version, 2);
2741            assert_eq!(v.kind.as_str(), kind);
2742            assert_eq!(v.operation_id.as_deref(), Some("op1"));
2743            assert_eq!(v.rule_id.is_some(), kind == "rule");
2744            let err = |node, target, sha, now| {
2745                verify_approval_any(&public, &signed, node, target, sha, now).unwrap_err()
2746            };
2747            assert!(err("other", "nginx", "abc", 1_000).contains("different node"));
2748            assert!(err("n1", "wg", "abc", 1_000).contains("different target"));
2749            assert!(err("n1", "nginx", "abd", 1_000).contains("different bytes"));
2750            assert!(err("n1", "nginx", "abc", 2_000).contains("expired"));
2751        }
2752    }
2753
2754    #[test]
2755    fn a_rule_approval_must_name_its_rule_and_an_operation_and_cannot_be_forged() {
2756        let seed = generate_hub_seed();
2757        let public = hub_public(&seed).unwrap();
2758        let mut no_rule = v2("rule", "n1", "nginx", "abc", 2_000);
2759        no_rule.rule_id = None;
2760        let signed = sign_approval_v2(&seed, &no_rule).unwrap();
2761        assert!(
2762            verify_approval_any(&public, &signed, "n1", "nginx", "abc", 1)
2763                .unwrap_err()
2764                .contains("name its rule")
2765        );
2766        let mut no_op = v2("human", "n1", "nginx", "abc", 2_000);
2767        no_op.operation_id.clear();
2768        let signed = sign_approval_v2(&seed, &no_op).unwrap();
2769        assert!(
2770            verify_approval_any(&public, &signed, "n1", "nginx", "abc", 1)
2771                .unwrap_err()
2772                .contains("no operation")
2773        );
2774        let mut bad_kind = v2("human", "n1", "nginx", "abc", 2_000);
2775        bad_kind.kind = "root".into();
2776        let signed = sign_approval_v2(&seed, &bad_kind).unwrap();
2777        assert!(
2778            verify_approval_any(&public, &signed, "n1", "nginx", "abc", 1)
2779                .unwrap_err()
2780                .contains("unknown kind")
2781        );
2782        // A different key's signature, and a tampered token, do not verify.
2783        let other = hub_public(&generate_hub_seed()).unwrap();
2784        let ok = sign_approval_v2(&seed, &v2("rule", "n1", "nginx", "abc", 2_000)).unwrap();
2785        assert!(verify_approval_any(&other, &ok, "n1", "nginx", "abc", 1).is_err());
2786        let tampered = SignedApproval {
2787            token: ok.token.replace("\"rule\"", "\"human\""),
2788            sig: ok.sig.clone(),
2789        };
2790        assert!(verify_approval_any(&public, &tampered, "n1", "nginx", "abc", 1).is_err());
2791    }
2792
2793    /// The two versions sign under different domains, so a version 1 signature cannot be passed off
2794    /// as version 2 (or the reverse), and version 1 tokens still verify through the shared path.
2795    #[test]
2796    fn the_two_versions_cannot_be_swapped_and_version_1_still_verifies() {
2797        let seed = generate_hub_seed();
2798        let public = hub_public(&seed).unwrap();
2799        let v1 = sign_approval(&seed, &token("n1", "nginx", "abc", 2_000)).unwrap();
2800        let verified = verify_approval_any(&public, &v1, "n1", "nginx", "abc", 1_000).unwrap();
2801        assert_eq!(verified.version, 1);
2802        assert_eq!(verified.kind, ApprovalKind::Human);
2803        assert!(verified.operation_id.is_none());
2804        let device = sign_approval(
2805            &seed,
2806            &ApprovalToken {
2807                approved_by: "device:abcdef012345".into(),
2808                ..token("n1", "nginx", "abc", 2_000)
2809            },
2810        )
2811        .unwrap();
2812        assert_eq!(
2813            verify_approval_any(&public, &device, "n1", "nginx", "abc", 1_000)
2814                .unwrap()
2815                .kind,
2816            ApprovalKind::Device
2817        );
2818        // A v2 token body under a v1 signature (and the reverse) fails.
2819        let v2_signed = sign_approval_v2(&seed, &v2("human", "n1", "nginx", "abc", 2_000)).unwrap();
2820        let cross = SignedApproval {
2821            token: v2_signed.token.clone(),
2822            sig: sign_approval(&seed, &token("n1", "nginx", "abc", 2_000))
2823                .unwrap()
2824                .sig,
2825        };
2826        assert!(verify_approval_any(&public, &cross, "n1", "nginx", "abc", 1).is_err());
2827        let cross2 = SignedApproval {
2828            token: v1.token.clone(),
2829            sig: v2_signed.sig,
2830        };
2831        assert!(verify_approval_any(&public, &cross2, "n1", "nginx", "abc", 1).is_err());
2832        let unknown = SignedApproval {
2833            token: r#"{"v":3}"#.into(),
2834            sig: v1.sig,
2835        };
2836        assert!(
2837            verify_approval_any(&public, &unknown, "n1", "nginx", "abc", 1)
2838                .unwrap_err()
2839                .contains("unknown approval version")
2840        );
2841    }
2842
2843    #[test]
2844    fn rule_approval_config_needs_an_automation_key_and_cannot_stand_in_for_a_human() {
2845        let key = hub_public(&generate_hub_seed()).unwrap();
2846        let target = |extra: &str| {
2847            format!(
2848                "[[target]]\nid=\"t\"\npath=\"/etc/x\"\nproject=\"p\"\nexporter=\"env\"\napply=true\n{extra}\n"
2849            )
2850        };
2851        let ok = format!(
2852            "automation_approver = \"{key}\"\n{}",
2853            target("accept_rule_approval = true")
2854        );
2855        assert!(NodeConfig::parse(&ok).is_ok());
2856        assert!(NodeConfig::parse(&target("accept_rule_approval = true"))
2857            .unwrap_err()
2858            .contains("needs automation_approver"));
2859        let both = format!(
2860            "automation_approver = \"{key}\"\n{}",
2861            target("accept_rule_approval = true\nrequire_approval = true")
2862        );
2863        assert!(NodeConfig::parse(&both).unwrap_err().contains("choose one"));
2864        assert!(NodeConfig::parse("automation_approver = \"zz\"\n")
2865            .unwrap_err()
2866            .contains("automation_approver"));
2867        let pull = format!(
2868            "automation_approver = \"{key}\"\n[[target]]\nid=\"t\"\npath=\"/etc/x\"\nproject=\"p\"\nexporter=\"env\"\nmode=\"pull\"\naccept_rule_approval = true\n"
2869        );
2870        assert!(NodeConfig::parse(&pull).is_err());
2871    }
2872
2873    #[test]
2874    fn an_approval_verifies_only_for_the_node_target_and_bytes_it_names() {
2875        let seed = generate_hub_seed();
2876        let public = hub_public(&seed).unwrap();
2877        let signed = sign_approval(&seed, &token("n1", "nginx", "abc", 2_000)).unwrap();
2878        assert!(verify_approval(&public, &signed, "n1", "nginx", "abc", 1_000).is_ok());
2879        let err = |node, target, sha, now| {
2880            verify_approval(&public, &signed, node, target, sha, now).unwrap_err()
2881        };
2882        assert!(err("other", "nginx", "abc", 1_000).contains("different node"));
2883        assert!(err("n1", "wg", "abc", 1_000).contains("different target"));
2884        assert!(err("n1", "nginx", "abd", 1_000).contains("different bytes"));
2885        assert!(err("n1", "nginx", "abc", 2_000).contains("expired"));
2886        // Edited token text, another hub's key, a mangled signature.
2887        let mut forged = signed.clone();
2888        forged.token = forged.token.replace("\"abc\"", "\"abd\"");
2889        assert!(
2890            verify_approval(&public, &forged, "n1", "nginx", "abd", 1_000)
2891                .unwrap_err()
2892                .contains("does not verify")
2893        );
2894        let other = hub_public(&generate_hub_seed()).unwrap();
2895        assert!(verify_approval(&other, &signed, "n1", "nginx", "abc", 1_000).is_err());
2896        let mut bad = signed.clone();
2897        bad.sig = "00".into();
2898        assert!(verify_approval(&public, &bad, "n1", "nginx", "abc", 1_000).is_err());
2899    }
2900
2901    fn request(s: &mut NodeStore, node: &str, sha: &str, now: i64) -> ApprovalRecord {
2902        s.request_approval(
2903            node,
2904            &report("push", true, Some("old")),
2905            sha,
2906            Some(1),
2907            Some(2),
2908            now,
2909            "t",
2910        )
2911        .unwrap()
2912    }
2913
2914    #[test]
2915    fn a_request_is_opened_once_per_set_of_bytes_and_decided_once() {
2916        let (mut s, n, _seed, _d) = enrolled();
2917        let a = request(&mut s, &n.id, "new", 1_000);
2918        assert_eq!(a.status, "pending");
2919        assert_eq!(
2920            request(&mut s, &n.id, "new", 1_001).id,
2921            a.id,
2922            "asking again must not open a second request"
2923        );
2924        assert_ne!(request(&mut s, &n.id, "other", 1_002).id, a.id);
2925        assert!(
2926            s.usable_approval(&n.id, "nginx-main", "new", 1_003)
2927                .is_none(),
2928            "pending is not approved"
2929        );
2930        let done = s.decide(&a.id, true, "owner", 1_010, "t").unwrap();
2931        assert_eq!(
2932            (done.status.as_str(), done.decided_by.as_deref()),
2933            ("approved", Some("owner"))
2934        );
2935        assert!(s
2936            .decide(&a.id, false, "owner", 1_011, "t")
2937            .unwrap_err()
2938            .contains("already approved"));
2939        assert!(s
2940            .usable_approval(&n.id, "nginx-main", "new", 1_020)
2941            .is_some());
2942        // An approval is for those bytes only.
2943        assert!(s
2944            .usable_approval(&n.id, "nginx-main", "other", 1_020)
2945            .is_none());
2946        assert!(s.usable_approval(&n.id, "wg", "new", 1_020).is_none());
2947    }
2948
2949    #[test]
2950    fn an_approval_lapses_and_a_revoked_node_cannot_use_one() {
2951        let (mut s, n, _seed, _d) = enrolled();
2952        let a = request(&mut s, &n.id, "new", 1_000);
2953        s.decide(&a.id, true, "owner", 1_000, "t").unwrap();
2954        assert!(s
2955            .usable_approval(&n.id, "nginx-main", "new", 1_000 + APPROVAL_TTL_SECS - 1)
2956            .is_some());
2957        assert!(s
2958            .usable_approval(&n.id, "nginx-main", "new", 1_000 + APPROVAL_TTL_SECS)
2959            .is_none());
2960        s.revoke(&n.id, "t").unwrap();
2961        assert!(s
2962            .usable_approval(&n.id, "nginx-main", "new", 1_001)
2963            .is_none());
2964    }
2965
2966    #[test]
2967    fn a_rejected_request_stays_rejected_for_those_bytes_and_an_old_request_cannot_be_decided() {
2968        let (mut s, n, _seed, _d) = enrolled();
2969        let a = request(&mut s, &n.id, "new", 1_000);
2970        s.decide(&a.id, false, "owner", 1_001, "t").unwrap();
2971        assert_eq!(
2972            request(&mut s, &n.id, "new", 1_002).status,
2973            "rejected",
2974            "asking again must not reopen it"
2975        );
2976        let b = request(&mut s, &n.id, "newer", 2_000);
2977        let late = 2_000 + PENDING_TTL_SECS;
2978        assert!(s
2979            .decide(&b.id, true, "owner", late, "t")
2980            .unwrap_err()
2981            .contains("expired"));
2982        assert!(s
2983            .decide("nope", true, "owner", 1, "t")
2984            .unwrap_err()
2985            .contains("No such"));
2986    }
2987
2988    #[test]
2989    fn a_spent_request_for_the_same_bytes_does_not_cover_a_later_push() {
2990        let (mut s, n, _seed, _d) = enrolled();
2991        let a = request(&mut s, &n.id, "v1", 1_000);
2992        s.decide(&a.id, true, "owner", 1_001, "t").unwrap();
2993        // The node reports having the approved bytes: the approval is consumed.
2994        let beat = Beat {
2995            targets: vec![report("push", true, Some("v1"))],
2996            ..Default::default()
2997        };
2998        s.record_beat(&n.id, &beat, &|_| Ok("v1".into()), "t")
2999            .unwrap();
3000        assert_eq!(
3001            s.approval_for(&n.id, "nginx-main", "v1").unwrap().status,
3002            "consumed"
3003        );
3004        assert!(s
3005            .usable_approval(&n.id, "nginx-main", "v1", 1_002)
3006            .is_none());
3007        // The same bytes wanted again later (a revert) need a new yes.
3008        let again = request(&mut s, &n.id, "v1", 5_000);
3009        assert_ne!(again.id, a.id);
3010        assert_eq!(again.status, "pending");
3011    }
3012
3013    #[test]
3014    fn status_follows_the_policy_and_the_decision() {
3015        let (mut s, n, _seed, _d) = enrolled();
3016        let beat = Beat {
3017            targets: vec![report("push", true, Some("old"))],
3018            ..Default::default()
3019        };
3020        let status = |s: &NodeStore| s.get(&n.id).unwrap().targets[0].status.clone();
3021        // No policy: ready to go.
3022        s.record_beat(&n.id, &beat, &|_| Ok("new".into()), "t")
3023            .unwrap();
3024        assert_eq!(status(&s), "pending");
3025        // Policy required, nothing asked yet: held.
3026        s.set_approval_policy(&n.id, "required").unwrap();
3027        s.record_beat(&n.id, &beat, &|_| Ok("new".into()), "t")
3028            .unwrap();
3029        assert_eq!(status(&s), "awaiting_approval");
3030        let now = unix_now();
3031        let a = s
3032            .request_approval(&n.id, &beat.targets[0], "new", None, None, now, "t")
3033            .unwrap();
3034        s.record_beat(&n.id, &beat, &|_| Ok("new".into()), "t")
3035            .unwrap();
3036        assert_eq!(status(&s), "awaiting_approval");
3037        s.decide(&a.id, true, "owner", now, "t").unwrap();
3038        s.record_beat(&n.id, &beat, &|_| Ok("new".into()), "t")
3039            .unwrap();
3040        assert_eq!(status(&s), "pending", "approved: the hub will push it");
3041        // The vault moved on: the old yes does not cover the new bytes.
3042        s.record_beat(&n.id, &beat, &|_| Ok("newer".into()), "t")
3043            .unwrap();
3044        assert_eq!(status(&s), "awaiting_approval");
3045        // A rejection is shown as one.
3046        let b = s
3047            .request_approval(&n.id, &beat.targets[0], "newer", None, None, now, "t")
3048            .unwrap();
3049        s.decide(&b.id, false, "owner", now, "t").unwrap();
3050        s.record_beat(&n.id, &beat, &|_| Ok("newer".into()), "t")
3051            .unwrap();
3052        assert_eq!(status(&s), "rejected");
3053        // Policy off again.
3054        s.set_approval_policy(&n.id, "none").unwrap();
3055        s.record_beat(&n.id, &beat, &|_| Ok("newer".into()), "t")
3056            .unwrap();
3057        assert_eq!(status(&s), "pending");
3058        assert!(s.set_approval_policy(&n.id, "sometimes").is_err());
3059    }
3060
3061    #[test]
3062    fn a_pull_target_cannot_require_approval() {
3063        let t = "[[target]]\nid=\"a\"\npath=\"/etc/a\"\nproject=\"p\"\nexporter=\"nginx\"\nmode=\"pull\"\nrequire_approval=true\n";
3064        assert!(NodeConfig::parse(t).unwrap_err().contains("only read"));
3065        let ok = "[[target]]\nid=\"a\"\npath=\"/etc/a\"\nproject=\"p\"\nexporter=\"nginx\"\napply=true\nrequire_approval=true\n";
3066        assert!(NodeConfig::parse(ok).unwrap().targets[0].require_approval);
3067    }
3068
3069    #[test]
3070    fn file_mode_and_owner_are_checked_text_not_free_form() {
3071        for (text, bits) in [("0400", 0o400), ("640", 0o640), ("0000", 0)] {
3072            assert_eq!(parse_file_mode(text), Some(bits), "{text}");
3073        }
3074        // No setuid bit, no non-octal digit, no wrong length, no sign.
3075        for bad in ["4755", "0o400", "89", "12", "07777", "", "+400", "40 0"] {
3076            assert_eq!(parse_file_mode(bad), None, "{bad:?}");
3077        }
3078        assert_eq!(parse_owner("999"), Some((999, 999)));
3079        assert_eq!(parse_owner("70:71"), Some((70, 71)));
3080        for bad in ["", "root", "1:", ":1", "1:2:3", "-1", "99999999999"] {
3081            assert_eq!(parse_owner(bad), None, "{bad:?}");
3082        }
3083    }
3084
3085    fn compose_target(extra: &str) -> String {
3086        format!(
3087            "[[target]]\nid=\"pw\"\npath=\"/srv/secrets/db_password\"\nproject=\"p\"\nexporter=\"compose-secret\"\napply=true\n{extra}"
3088        )
3089    }
3090
3091    #[test]
3092    fn a_compose_target_needs_its_file_and_services_and_generates_the_commands() {
3093        let ok = compose_target(
3094            "compose_project=\"demo\"\ncompose_file=\"/srv/compose.yaml\"\nservices=[\"db\"]\nowner=\"999:999\"\n",
3095        );
3096        let t = NodeConfig::parse(&ok).unwrap().targets.remove(0);
3097        // 0400 unless the operator says otherwise; the owner is the container user.
3098        assert_eq!(t.file_mode_bits(), Some(0o400));
3099        assert_eq!(t.owner_ids(), Some((999, 999)));
3100        let ok = compose_target(
3101            "file_mode=\"0440\"\ncompose_project=\"demo\"\ncompose_file=\"/srv/compose.yaml\"\nservices=[\"db\"]\n",
3102        );
3103        assert_eq!(
3104            NodeConfig::parse(&ok).unwrap().targets[0].file_mode_bits(),
3105            Some(0o440)
3106        );
3107        // A plain target keeps the file's own mode.
3108        let plain = "[[target]]\nid=\"a\"\npath=\"/etc/a\"\nproject=\"p\"\nexporter=\"nginx\"\n";
3109        assert_eq!(
3110            NodeConfig::parse(plain).unwrap().targets[0].file_mode_bits(),
3111            None
3112        );
3113        for (extra, needle) in [
3114            ("compose_project=\"demo\"\nservices=[\"db\"]\n", "needs compose_file"),
3115            (
3116                "compose_project=\"demo\"\ncompose_file=\"rel.yaml\"\nservices=[\"db\"]\n",
3117                "needs compose_file",
3118            ),
3119            (
3120                "compose_project=\"demo\"\ncompose_file=\"/srv/c.yaml\"\n",
3121                "needs services",
3122            ),
3123            (
3124                "compose_project=\"demo\"\ncompose_file=\"/srv/c.yaml\"\nservices=[\"db; rm\"]\n",
3125                "needs services",
3126            ),
3127            (
3128                "compose_project=\"de mo\"\ncompose_file=\"/srv/c.yaml\"\nservices=[\"db\"]\n",
3129                "compose_project must be",
3130            ),
3131            (
3132                "compose_project=\"demo\"\ncompose_file=\"/srv/c.yaml\"\nservices=[\"db\"]\nreload=\"true\"\n",
3133                "generates validate and reload",
3134            ),
3135            (
3136                "compose_project=\"demo\"\ncompose_file=\"/srv/c.yaml\"\nservices=[\"db\"]\nmode=\"pull\"\n",
3137                "a pull target is only read",
3138            ),
3139            ("services=[\"db\"]\n", "belong to a target that sets compose_project"),
3140            ("compose_file=\"/srv/c.yaml\"\n", "belong to a target that sets compose_project"),
3141            ("file_mode=\"4755\"\n", "file_mode must be octal"),
3142            ("owner=\"root\"\n", "owner must be a numeric"),
3143        ] {
3144            let err = NodeConfig::parse(&compose_target(extra)).unwrap_err();
3145            assert!(err.contains(needle), "{extra:?} -> {err}");
3146        }
3147    }
3148
3149    /// The target examples in the Compose and Home Assistant guides are the config a reader
3150    /// copies, so they must be accepted by the parser that will read them.
3151    #[test]
3152    fn the_guides_node_examples_parse_and_mean_what_the_text_says() {
3153        fn toml_blocks(page: &str) -> Vec<String> {
3154            page.split("```toml\n")
3155                .skip(1)
3156                .map(|b| b.split("```").next().unwrap_or("").to_string())
3157                .collect()
3158        }
3159        let compose = toml_blocks(include_str!("../../book/src/compose-secrets.md"));
3160        assert_eq!(compose.len(), 1);
3161        let t = NodeConfig::parse(&compose[0]).unwrap().targets.remove(0);
3162        assert_eq!(t.exporter, "compose-secret");
3163        assert_eq!(t.compose_project.as_deref(), Some("stack"));
3164        assert_eq!(t.services, vec!["db".to_string()]);
3165        assert_eq!(t.file_mode_bits(), Some(0o400));
3166        assert_eq!(t.owner_ids(), Some((999, 999)));
3167
3168        let ha = toml_blocks(include_str!("../../book/src/home-assistant.md"));
3169        assert_eq!(ha.len(), 1);
3170        let t = NodeConfig::parse(&ha[0]).unwrap().targets.remove(0);
3171        assert_eq!(t.exporter, "homeassistant");
3172        assert!(t.validate.as_deref().unwrap().contains("check_config"));
3173        assert!(t.check.as_deref().unwrap().starts_with("http://"));
3174    }
3175
3176    #[test]
3177    fn a_compose_target_that_only_reads_is_refused_for_its_mode() {
3178        // Without `apply` the pull rule has nothing to say, so the Compose rule does.
3179        let t = "[[target]]\nid=\"pw\"\npath=\"/srv/s\"\nproject=\"p\"\nexporter=\"compose-secret\"\nmode=\"pull\"\ncompose_project=\"demo\"\ncompose_file=\"/srv/c.yaml\"\nservices=[\"db\"]\n";
3180        assert!(NodeConfig::parse(t).unwrap_err().contains("its mode is"));
3181    }
3182
3183    fn listen(endpoint: &str) -> ListenInfo {
3184        ListenInfo {
3185            endpoint: endpoint.into(),
3186            cert_sha256: "ab".repeat(32),
3187        }
3188    }
3189
3190    #[test]
3191    fn pairing_enrols_a_listening_node_and_hands_back_the_hub_key() {
3192        let dir = scratch("pair");
3193        let mut s = NodeStore::open(&dir.join("nodes.json")).unwrap();
3194        let (_, pk) = generate_identity();
3195        let (node, hub_key) = s
3196            .pair(
3197                "edge",
3198                vec!["p".into()],
3199                &pk,
3200                listen("https://10.0.0.5:9443"),
3201                100,
3202                "t",
3203            )
3204            .unwrap();
3205        assert_eq!(node.name, "edge");
3206        assert_eq!(
3207            node.listen.as_ref().unwrap().endpoint,
3208            "https://10.0.0.5:9443"
3209        );
3210        assert_eq!(hub_key.len(), 64);
3211        assert_eq!(s.hub_node_key().unwrap().1, hub_key);
3212        assert_eq!(s.listening().len(), 1);
3213        // The name is taken now, and nothing is left open.
3214        let (_, pk2) = generate_identity();
3215        let taken = s
3216            .pair(
3217                "edge",
3218                vec!["p".into()],
3219                &pk2,
3220                listen("https://10.0.0.6:9443"),
3221                101,
3222                "t",
3223            )
3224            .unwrap_err();
3225        assert!(taken.contains("already enrolled"));
3226    }
3227
3228    #[test]
3229    fn a_refused_pairing_leaves_no_token_that_blocks_a_retry() {
3230        // The bug this pins: minting before validating left an open token for the name, so the
3231        // corrected request was refused with "a token is already open" until it expired.
3232        let dir = scratch("pair-retry");
3233        let mut s = NodeStore::open(&dir.join("nodes.json")).unwrap();
3234        let (_, pk) = generate_identity();
3235        let bad = s
3236            .pair(
3237                "edge",
3238                vec!["p".into()],
3239                "zz",
3240                listen("https://10.0.0.5:9443"),
3241                100,
3242                "t",
3243            )
3244            .unwrap_err();
3245        assert!(bad.contains("hex"), "{bad}");
3246        let bad_addr = s
3247            .pair(
3248                "edge",
3249                vec!["p".into()],
3250                &pk,
3251                listen("http://10.0.0.5"),
3252                100,
3253                "t",
3254            )
3255            .unwrap_err();
3256        assert!(bad_addr.contains("https"), "{bad_addr}");
3257        s.pair(
3258            "edge",
3259            vec!["p".into()],
3260            &pk,
3261            listen("https://10.0.0.5:9443"),
3262            101,
3263            "t",
3264        )
3265        .unwrap();
3266        assert!(s
3267            .pair(
3268                "bad name",
3269                vec!["p".into()],
3270                &pk,
3271                listen("https://h"),
3272                102,
3273                "t"
3274            )
3275            .is_err());
3276    }
3277
3278    #[test]
3279    fn a_listening_address_is_a_bare_https_origin() {
3280        for ok in [
3281            "https://node.example",
3282            "https://10.0.0.5:9443",
3283            "https://[::1]:9443/",
3284            "https://n-1.lan",
3285        ] {
3286            assert!(listen(ok).validate().is_ok(), "{ok}");
3287        }
3288        for bad in [
3289            "http://node.example",
3290            "https://user@node.example",
3291            "https://node.example/path",
3292            "https://node.example?x=1",
3293            "https://node.example#f",
3294            "https://",
3295            "ftp://node.example",
3296            "",
3297        ] {
3298            assert!(listen(bad).validate().is_err(), "{bad}");
3299        }
3300        let mut l = listen("https://n.example");
3301        l.cert_sha256 = "xyz".into();
3302        assert!(l.validate().is_err());
3303        assert_eq!(listen("https://n.example/").base(), "https://n.example");
3304    }
3305
3306    #[test]
3307    fn a_node_signature_is_not_a_hub_signature_and_the_reverse() {
3308        let (node_seed, node_pub) = generate_identity();
3309        let hub_seed = generate_hub_seed();
3310        let hub_pub = hub_public(&hub_seed).unwrap();
3311        let body = b"{}";
3312        let n = sign_request(&node_seed, "POST", "/p", 5, body).unwrap();
3313        let h = sign_hub_request(&hub_seed, "POST", "/p", 5, body).unwrap();
3314        assert!(verify_request(&node_pub, "POST", "/p", 5, body, &n));
3315        assert!(verify_hub_request(&hub_pub, "POST", "/p", 5, body, &h));
3316        // Same input, other direction: refused. Without the domain line a node
3317        // could replay what the hub told it, or the reverse.
3318        assert!(!verify_hub_request(&node_pub, "POST", "/p", 5, body, &n));
3319        assert!(!verify_request(&hub_pub, "POST", "/p", 5, body, &h));
3320        // And a hub signature is bound to its path, time and body.
3321        assert!(!verify_hub_request(&hub_pub, "POST", "/other", 5, body, &h));
3322        assert!(!verify_hub_request(&hub_pub, "POST", "/p", 6, body, &h));
3323        assert!(!verify_hub_request(&hub_pub, "POST", "/p", 5, b"{ }", &h));
3324    }
3325
3326    #[test]
3327    fn enrollment_records_where_a_listening_node_is_and_refuses_a_bad_address() {
3328        let dir = scratch("listen");
3329        let path = dir.join("nodes.json");
3330        let mut s = NodeStore::open(&path).unwrap();
3331        let (_, pk) = generate_identity();
3332        let (tok, _) = s.mint_token("edge", vec!["web".into()], 900, 100).unwrap();
3333        let bad = s
3334            .enroll(&tok, &pk, Some(listen("http://plain.example")), 101, "t")
3335            .unwrap_err();
3336        assert!(bad.contains("https"), "{bad}");
3337        // A refused address does not spend the token.
3338        let n = s
3339            .enroll(
3340                &tok,
3341                &pk,
3342                Some(listen("https://edge.example:9443")),
3343                102,
3344                "t",
3345            )
3346            .unwrap();
3347        assert_eq!(
3348            n.listen.as_ref().unwrap().base(),
3349            "https://edge.example:9443"
3350        );
3351        assert_eq!(s.listening().len(), 1);
3352        // A dialling node is not in the list the hub dials.
3353        let (_, pk2) = generate_identity();
3354        let (tok2, _) = s
3355            .mint_token("dialer", vec!["web".into()], 900, 100)
3356            .unwrap();
3357        s.enroll(&tok2, &pk2, None, 103, "t").unwrap();
3358        assert_eq!(s.listening().len(), 1);
3359        s.revoke(&n.id, "t").unwrap();
3360        assert!(s.listening().is_empty(), "a revoked node is not dialled");
3361        // Survives a reopen.
3362        let again = NodeStore::open(&path).unwrap();
3363        assert!(again.get(&n.id).unwrap().listen.is_some());
3364    }
3365
3366    #[test]
3367    fn the_hub_transport_key_is_made_once_and_kept() {
3368        let dir = scratch("hubkey");
3369        let path = dir.join("nodes.json");
3370        let mut s = NodeStore::open(&path).unwrap();
3371        let (seed, public) = s.hub_node_key().unwrap();
3372        assert_eq!(hub_public(&seed).unwrap(), public);
3373        assert_eq!(s.hub_node_key().unwrap().0, seed);
3374        let mut reopened = NodeStore::open(&path).unwrap();
3375        assert_eq!(reopened.hub_node_key().unwrap(), (seed, public));
3376    }
3377
3378    fn device() -> (String, String) {
3379        let seed = generate_hub_seed();
3380        let public = hub_public(&seed).unwrap();
3381        (seed, public)
3382    }
3383
3384    #[test]
3385    fn device_approval_is_accepted_only_for_the_request_it_names_and_only_from_a_registered_device()
3386    {
3387        let (mut s, n, _seed, _dir) = enrolled();
3388        let (dev_seed, dev_pub) = device();
3389        // `device` is not a policy until a device exists.
3390        assert!(s.set_approval_policy(&n.id, "device").is_err());
3391        s.add_approver(&dev_pub, "laptop", "t").unwrap();
3392        s.set_approval_policy(&n.id, "device").unwrap();
3393
3394        let rec = s
3395            .request_approval(
3396                &n.id,
3397                &report("push", true, Some("old")),
3398                "newsha",
3399                None,
3400                None,
3401                2_000,
3402                "t",
3403            )
3404            .unwrap();
3405        let sign = |seed: &str, node: &str, target: &str, sha: &str, id: &str, now: i64| {
3406            sign_device_approval(seed, node, target, sha, id, now, "t").unwrap()
3407        };
3408        // Not registered: refused.
3409        let (other_seed, _) = device();
3410        let bad = sign(&other_seed, &n.id, "nginx-main", "newsha", &rec.id, 2_010);
3411        assert!(s
3412            .decide_signed(&rec.id, bad, 2_010, "t")
3413            .unwrap_err()
3414            .contains("Not accepted"));
3415        // Registered, but for other bytes / target / node / request: refused.
3416        for (node, target, sha, id) in [
3417            (n.id.as_str(), "nginx-main", "othersha", rec.id.as_str()),
3418            (n.id.as_str(), "other", "newsha", rec.id.as_str()),
3419            ("someone", "nginx-main", "newsha", rec.id.as_str()),
3420            (n.id.as_str(), "nginx-main", "newsha", "another-request"),
3421        ] {
3422            let t = sign(&dev_seed, node, target, sha, id, 2_010);
3423            assert!(
3424                s.decide_signed(&rec.id, t, 2_010, "t").is_err(),
3425                "{node} {target} {sha} {id}"
3426            );
3427        }
3428        // A lifetime longer than the hub's own is refused.
3429        let long = sign_approval(
3430            &dev_seed,
3431            &ApprovalToken {
3432                v: 1,
3433                node_id: n.id.clone(),
3434                target: "nginx-main".into(),
3435                sha256: "newsha".into(),
3436                approval_id: rec.id.clone(),
3437                approved_by: "x".into(),
3438                approved_at: "t".into(),
3439                expires_secs: 2_010 + APPROVAL_TTL_SECS * 10,
3440                nonce: "n".into(),
3441            },
3442        )
3443        .unwrap();
3444        assert!(s
3445            .decide_signed(&rec.id, long, 2_010, "t")
3446            .unwrap_err()
3447            .contains("longer"));
3448        // The right one is accepted, recorded, and cannot be decided twice.
3449        let good = sign(&dev_seed, &n.id, "nginx-main", "newsha", &rec.id, 2_010);
3450        let a = s.decide_signed(&rec.id, good.clone(), 2_010, "t").unwrap();
3451        assert_eq!(a.status, "approved");
3452        assert!(a.decided_by.as_deref().unwrap().starts_with("device:"));
3453        assert_eq!(a.signed, Some(good.clone()));
3454        assert!(s
3455            .decide_signed(&rec.id, good, 2_011, "t")
3456            .unwrap_err()
3457            .contains("already"));
3458        assert!(s
3459            .usable_approval(&n.id, "nginx-main", "newsha", 2_020)
3460            .is_some());
3461    }
3462
3463    #[test]
3464    fn removing_the_last_approver_returns_device_nodes_to_hub_approval() {
3465        let (mut s, n, _seed, _dir) = enrolled();
3466        let (_, p1) = device();
3467        let a = s.add_approver(&p1, "laptop", "t").unwrap();
3468        assert_eq!(
3469            s.add_approver(&p1, "again", "t").unwrap(),
3470            a,
3471            "adding twice is one device"
3472        );
3473        s.set_approval_policy(&n.id, "device").unwrap();
3474        assert!(
3475            s.remove_approver("abc").is_err(),
3476            "a short prefix is a guess"
3477        );
3478        s.remove_approver(&a.fingerprint[..10]).unwrap();
3479        assert_eq!(s.get(&n.id).unwrap().approval, "required");
3480        assert!(s.approvers().is_empty());
3481        assert!(s.add_approver("zz", "x", "t").is_err());
3482        assert!(s.add_approver(&p1, "", "t").is_err());
3483    }
3484
3485    #[test]
3486    fn the_device_seed_is_made_once_private_and_stable() {
3487        let dir = scratch("approver");
3488        let a = approver_seed(&dir).unwrap();
3489        assert_eq!(approver_seed(&dir).unwrap(), a);
3490        assert_eq!(hub_public(&a).unwrap().len(), 64);
3491        #[cfg(unix)]
3492        {
3493            use std::os::unix::fs::PermissionsExt;
3494            let m = std::fs::metadata(dir.join("approver.key"))
3495                .unwrap()
3496                .permissions()
3497                .mode();
3498            assert_eq!(m & 0o077, 0, "the key is readable by others: {m:o}");
3499        }
3500        std::fs::write(dir.join("approver.key"), "not a key").unwrap();
3501        assert!(
3502            approver_seed(&dir).is_err(),
3503            "a damaged key is an error, not a new identity"
3504        );
3505    }
3506
3507    #[test]
3508    fn a_node_config_names_its_approver_as_a_real_public_key_or_not_at_all() {
3509        let (_, p) = device();
3510        assert!(NodeConfig::parse(&format!("approver = \"{p}\"")).is_ok());
3511        assert!(NodeConfig::parse("approver = \"zz\"").is_err());
3512        assert!(NodeConfig::parse("").unwrap().approver.is_none());
3513    }
3514
3515    #[test]
3516    fn device_approver_path_stays_under_the_platform_data_directory() {
3517        // Windows keeps a device key in the machine-local profile; the others use the data directory.
3518        #[cfg(windows)]
3519        let base = dirs::data_local_dir();
3520        #[cfg(not(windows))]
3521        let base = dirs::data_dir();
3522        let expected = base.map(|dir| dir.join("io.unenverse"));
3523        assert_eq!(default_approver_dir(), expected);
3524
3525        #[cfg(target_os = "linux")]
3526        if let Some(data_home) = std::env::var_os("XDG_DATA_HOME") {
3527            assert_eq!(
3528                default_approver_dir(),
3529                Some(PathBuf::from(data_home).join("io.unenverse"))
3530            );
3531        }
3532        #[cfg(windows)]
3533        if let Some(appdata) = std::env::var_os("LOCALAPPDATA") {
3534            assert_eq!(
3535                default_approver_dir(),
3536                Some(PathBuf::from(appdata).join("io.unenverse"))
3537            );
3538        }
3539    }
3540    const SHA_A: &str = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
3541    const SHA_B: &str = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb";
3542
3543    #[test]
3544    fn a_lease_pins_a_target_until_it_expires_or_its_holder_releases_it() {
3545        let (mut s, n, _, _) = enrolled();
3546        let l = s
3547            .lease_target(&n.id, "nginx-main", SHA_A, "rot-1", 60, 1_000)
3548            .unwrap();
3549        assert_eq!(l.expires_secs, 1_060);
3550        assert_eq!(
3551            s.lease_for(&n.id, "nginx-main", 1_059).unwrap().sha256,
3552            SHA_A
3553        );
3554        assert!(
3555            s.lease_for(&n.id, "nginx-main", 1_060).is_none(),
3556            "gone at its expiry"
3557        );
3558        assert!(s.lease_for(&n.id, "other-target", 1_001).is_none());
3559        assert_eq!(s.leases(1_001).len(), 1);
3560        s.release_lease(&n.id, "nginx-main", "rot-1", 1_001)
3561            .unwrap();
3562        assert!(s.lease_for(&n.id, "nginx-main", 1_002).is_none());
3563    }
3564
3565    #[test]
3566    fn another_holder_cannot_take_or_release_a_live_lease_but_can_after_it_expires() {
3567        let (mut s, n, _, _) = enrolled();
3568        s.lease_target(&n.id, "nginx-main", SHA_A, "rot-1", 60, 1_000)
3569            .unwrap();
3570        let e = s
3571            .lease_target(&n.id, "nginx-main", SHA_B, "rot-2", 60, 1_010)
3572            .unwrap_err();
3573        assert!(e.contains("rot-1"), "{e}");
3574        assert!(s
3575            .release_lease(&n.id, "nginx-main", "rot-2", 1_010)
3576            .is_err());
3577        // The holder may replace its own lease with new content.
3578        s.lease_target(&n.id, "nginx-main", SHA_B, "rot-1", 60, 1_020)
3579            .unwrap();
3580        assert_eq!(
3581            s.lease_for(&n.id, "nginx-main", 1_021).unwrap().sha256,
3582            SHA_B
3583        );
3584        // Once it has expired, anyone may lease.
3585        s.lease_target(&n.id, "nginx-main", SHA_A, "rot-2", 60, 5_000)
3586            .unwrap();
3587    }
3588
3589    #[test]
3590    fn a_lease_is_refused_for_a_bad_lifetime_hash_holder_or_node_and_survives_a_reopen() {
3591        let (mut s, n, _, dir) = enrolled();
3592        for (ttl, sha, holder, node) in [
3593            (0, SHA_A, "h", n.id.as_str()),
3594            (MAX_LEASE_SECS + 1, SHA_A, "h", n.id.as_str()),
3595            (60, "short", "h", n.id.as_str()),
3596            (60, SHA_A, "", n.id.as_str()),
3597            (60, SHA_A, "h", "no-such-node"),
3598        ] {
3599            assert!(s.lease_target(node, "t", sha, holder, ttl, 1_000).is_err());
3600        }
3601        assert!(
3602            s.release_lease(&n.id, "t", "h", 1_000).is_err(),
3603            "nothing to release"
3604        );
3605        s.lease_target(&n.id, "t", SHA_A, "rot-1", 60, 1_000)
3606            .unwrap();
3607        let again = NodeStore::open(&dir.join("nodes.json")).unwrap();
3608        assert!(again.lease_for(&n.id, "t", 1_001).is_some());
3609    }
3610}
3611
3612#[cfg(test)]
3613mod legacy_key_tests {
3614    use super::*;
3615
3616    fn dir(tag: &str) -> PathBuf {
3617        let d = std::env::temp_dir().join(format!("vc-key-{tag}-{}", crate::new_uuid()));
3618        std::fs::create_dir_all(&d).unwrap();
3619        d
3620    }
3621
3622    #[test]
3623    fn a_valid_old_key_is_adopted_and_the_old_file_stays() {
3624        let old = dir("old");
3625        let seed = generate_hub_seed();
3626        std::fs::write(old.join("approver.key"), &seed).unwrap();
3627        assert_eq!(
3628            adopt_legacy_key(&old).unwrap().as_deref(),
3629            Some(seed.as_str())
3630        );
3631        assert!(old.join("approver.key").exists(), "the old key is kept");
3632    }
3633
3634    #[test]
3635    fn a_missing_or_damaged_old_key_adopts_nothing() {
3636        let old = dir("o2");
3637        assert_eq!(adopt_legacy_key(&old).unwrap(), None);
3638        std::fs::write(old.join("approver.key"), "not a key").unwrap();
3639        assert_eq!(adopt_legacy_key(&old).unwrap(), None);
3640    }
3641
3642    #[test]
3643    fn on_this_platform_the_old_directory_is_only_set_where_it_differs() {
3644        if cfg!(windows) {
3645            assert_ne!(legacy_approver_dir(), default_approver_dir());
3646        } else {
3647            assert_eq!(legacy_approver_dir(), None);
3648        }
3649    }
3650}