From eaac60ba88728bb582778c726e5798156dddfc45 Mon Sep 17 00:00:00 2001 From: tv Date: Sun, 29 Nov 2026 14:21:34 +0000 Subject: enstate: the receptor and the provider, a first version One program on a library: --plan and --apply of submissions (complete and partial, items required and optional, groups, removal, the chain as order), validators of types and across slots, views put in place by replacing a link, their reactions by systemctl; --status, --materialize; and --pack, a submission from a source list in JSON or TOML, by the config crate's sources. Programs by the protocol of design.md 5.2; tests with shell scripts as validators and renderers. --- Cargo.lock | 334 ++++++++++++++++++++++++++++ Cargo.toml | 20 ++ README.md | 23 +- docs/design.md | 10 +- rustfmt.toml | 1 + src/content.rs | 105 +++++++++ src/lib.rs | 42 ++++ src/main.rs | 505 ++++++++++++++++++++++++++++++++++++++++++ src/media.rs | 92 ++++++++ src/name.rs | 140 ++++++++++++ src/pack.rs | 233 +++++++++++++++++++ src/plan.rs | 566 +++++++++++++++++++++++++++++++++++++++++++++++ src/program.rs | 201 +++++++++++++++++ src/schema.rs | 292 ++++++++++++++++++++++++ src/scratch.rs | 74 +++++++ src/store.rs | 225 +++++++++++++++++++ src/submission.rs | 219 ++++++++++++++++++ src/view.rs | 181 +++++++++++++++ tests/receptor.rs | 651 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 19 files changed, 3908 insertions(+), 6 deletions(-) create mode 100644 Cargo.lock create mode 100644 Cargo.toml create mode 100644 rustfmt.toml create mode 100644 src/content.rs create mode 100644 src/lib.rs create mode 100644 src/main.rs create mode 100644 src/media.rs create mode 100644 src/name.rs create mode 100644 src/pack.rs create mode 100644 src/plan.rs create mode 100644 src/program.rs create mode 100644 src/schema.rs create mode 100644 src/scratch.rs create mode 100644 src/store.rs create mode 100644 src/submission.rs create mode 100644 src/view.rs create mode 100644 tests/receptor.rs diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..545f276 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,334 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "anstream" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "anstyle-parse" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys", +] + +[[package]] +name = "anyhow" +version = "1.0.105" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2cb931c189b85683d69a5cfad41d4d418671e1ac413dd209f3f2fc31e3cfd902" + +[[package]] +name = "clap" +version = "4.6.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50066ca966813ca8957ee15361752f19424a8ff620dbe9c8993d9f99d99b04b3" +dependencies = [ + "clap_builder", +] + +[[package]] +name = "clap_builder" +version = "4.6.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0ed97c96ef4efb3cc84e09fa388df4463e7cc3224ec38d7b1d9e45749333590" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_lex" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e0921b3876b3a1df8a1c9f912e7f94342458022c2e84288015893d83c4d62a79" + +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + +[[package]] +name = "config" +version = "0.1.0" +source = "git+https://cgit.krebsco.de/continuum#bcb729ce0cae2cd8bbd8f60f8e98a81674bcd4fb" +dependencies = [ + "anyhow", + "clap", + "serde", + "serde_json", + "toml", +] + +[[package]] +name = "enstate" +version = "0.0.1" +dependencies = [ + "anyhow", + "clap", + "config", + "serde", + "serde_json", + "similar", + "toml", +] + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "hashbrown" +version = "0.17.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc" + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", +] + +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_spanned" +version = "1.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c187e0a369471c550af028cba56d4f4fa2a489ad28151ae95a4d340a2a8b782" +dependencies = [ + "serde_core", +] + +[[package]] +name = "similar" +version = "2.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbbb5d9659141646ae647b42fe094daf6c6192d1620870b449d9557f748b2daa" + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "toml" +version = "1.2.3+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26b1f26e9485c1fa43ee89fe76e9f3fb9e2e52bb227f8594b4d687496b83d073" +dependencies = [ + "indexmap", + "serde_core", + "serde_spanned", + "toml_datetime", + "toml_parser", + "toml_writer", + "winnow", +] + +[[package]] +name = "toml_datetime" +version = "1.1.3+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "173f25c883cd2176a2d8212155638c0a60d484a9d84546d270866f40f56b6e49" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_parser" +version = "1.1.7+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bb28d6e049a9766c3bd91a8326e6179f5b132dec87906bb97018ef7a2f3431a" +dependencies = [ + "winnow", +] + +[[package]] +name = "toml_writer" +version = "1.2.0+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "009dbb7700f11c55ef83aebbe4c0e9cf1f1ac0844bd8d6f00dc38f302026e13a" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "winnow" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..b49d28b --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,20 @@ +# The receptor, which plans and applies submissions on a host, and the provider +# that makes them (`enstate --pack`): one program (`src/main.rs`) on a library +# (`src/lib.rs`). docs/design.md says what they are for. +[package] +name = "enstate" +version = "0.0.1" +edition = "2024" + +# Its doc comments are prose, not examples to test. +[lib] +doctest = false + +[dependencies] +anyhow = "1.0" +clap = { version = "4.6", features = ["color"] } +config = { git = "https://cgit.krebsco.de/continuum", features = ["clap", "serde", "toml"] } +serde = { version = "1.0", features = ["derive"] } +serde_json = "1.0" +similar = "2" +toml = "1.1" diff --git a/README.md b/README.md index 2eb368a..71ae7e2 100644 --- a/README.md +++ b/README.md @@ -6,5 +6,26 @@ system declares what state it can consume; a receptor on the host accepts a snapshot that fits, puts it in place and reloads what uses it, or rejects it. -Nothing is built yet. The design is in [docs/design.md](docs/design.md); +The design is in [docs/design.md](docs/design.md); [docs/migrations.md](docs/migrations.md) walks through its migration model. + +## What there is + +`enstate`, one program for the receptor and the provider: + +- `--plan PATH`, `--apply PATH`: what the submission in PATH would do, and + doing it: complete and partial submissions, items required and optional, + groups, removal, the chain as order, validators (a type's and across + slots), views and their reactions; +- `--status`, `--materialize`: the snapshots, and putting every view in + place from them; +- `--pack PATH --out DIR`: a submission from a source list, JSON or TOML. + +Not yet: migrations (`--migrate`), the NixOS module, a NixOS VM test, +shell completion, a sandbox for programs. + +```sh +cargo build +cargo test +enstate --help +``` diff --git a/docs/design.md b/docs/design.md index b20323e..fdc5e1e 100644 --- a/docs/design.md +++ b/docs/design.md @@ -1,10 +1,10 @@ # enstate: state next to the store, a design draft -Draft 4, 2026-11-29. Nothing is built yet. Section 12 lists what is open. -The name, enstate, may change. An older model of state objects is in -[state-object.md](state-object.md); section 9 says how it fits in. -[migrations.md](migrations.md) walks through the migration model with -three made-up cases. +Draft 4, 2026-11-29. What is built of it, [README.md](../README.md) says. +Section 12 lists what is open. The name, enstate, may change. An older +model of state objects is in [state-object.md](state-object.md); section +9 says how it fits in. [migrations.md](migrations.md) walks through the +migration model with three made-up cases. ## 1. The problem diff --git a/rustfmt.toml b/rustfmt.toml new file mode 100644 index 0000000..3501136 --- /dev/null +++ b/rustfmt.toml @@ -0,0 +1 @@ +style_edition = "2024" diff --git a/src/content.rs b/src/content.rs new file mode 100644 index 0000000..4dce0e7 --- /dev/null +++ b/src/content.rs @@ -0,0 +1,105 @@ +//! The entries of one channel, by slot, and the records in keyed ones. + +use std::collections::BTreeMap; +use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt}; +use std::path::Path; + +use anyhow::{Context, Result, bail}; +use serde_json::{Map, Value}; + +use crate::name; + +/// Entries by slot name, each exactly as stored. +pub type Content = BTreeMap>; + +/// The entries in `dir`: one file per slot. A missing directory holds none. +pub fn read_dir(dir: &Path) -> Result { + let mut content = Content::new(); + let entries = match std::fs::read_dir(dir) { + Ok(entries) => entries, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(content), + Err(error) => return Err(error).with_context(|| format!("reading {}", dir.display())), + }; + for entry in entries { + let entry = entry?; + let slot = entry + .file_name() + .into_string() + .ok() + .filter(|slot| name::is_name(slot)); + let Some(slot) = slot else { + bail!("{}: not a slot's name", entry.path().display()); + }; + if !entry.file_type()?.is_file() { + bail!("{}: not a regular file", entry.path().display()); + } + let bytes = std::fs::read(entry.path()) + .with_context(|| format!("reading {}", entry.path().display()))?; + content.insert(slot, bytes); + } + Ok(content) +} + +/// Writes `content` into `dir`, which is created, with files of `mode` (and +/// directories that can be entered where the files can be read). +pub fn write_dir(content: &Content, dir: &Path, mode: u32) -> Result<()> { + std::fs::DirBuilder::new() + .recursive(true) + .mode(directory_mode(mode)) + .create(dir) + .with_context(|| format!("creating {}", dir.display()))?; + for (slot, bytes) in content { + write_file(&dir.join(slot), bytes, mode)?; + } + Ok(()) +} + +pub fn write_file(path: &Path, bytes: &[u8], mode: u32) -> Result<()> { + use std::io::Write; + let mut file = std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .mode(mode) + .open(path) + .with_context(|| format!("creating {}", path.display()))?; + file.write_all(bytes) + .with_context(|| format!("writing {}", path.display())) +} + +/// The mode of a directory holding files of `mode`: searchable by whoever can read. +pub fn directory_mode(mode: u32) -> u32 { + mode | ((mode & 0o444) >> 2) +} + +/// The records of a keyed entry. +pub fn records(bytes: &[u8]) -> Result> { + match serde_json::from_slice(bytes).context("not JSON")? { + Value::Object(records) => Ok(records), + _ => bail!("not a JSON object, whose keys would be records"), + } +} + +/// A keyed entry holding `records`, in a normal form: keys sorted, indented, a line +/// break at the end. +pub fn from_records(records: &Map) -> Vec { + let mut bytes = serde_json::to_vec_pretty(records).expect("JSON values serialize"); + bytes.push(b'\n'); + bytes +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn records_in_normal_form() { + let records = records(br#"{"b": 1, "a": {"x": [1]}}"#).unwrap(); + assert_eq!( + String::from_utf8(from_records(&records)).unwrap(), + "{\n \"a\": {\n \"x\": [\n 1\n ]\n },\n \"b\": 1\n}\n" + ); + assert!(super::records(b"[1]").is_err()); + assert_eq!(directory_mode(0o600), 0o700); + assert_eq!(directory_mode(0o644), 0o755); + } +} diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..af7de7e --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,42 @@ +//! enstate: state next to the store (docs/design.md). +//! +//! * [`name`]: names of channels and slots, and addresses; +//! * [`media`]: types, as media types; +//! * [`schema`]: what a generation accepts; +//! * [`content`]: the entries of one channel, and records in them; +//! * [`submission`]: what gets handed to the host; +//! * [`program`]: the protocol of validators, renderers, converters and steps; +//! * [`view`]: rendering views, comparing them, installing them; +//! * [`store`]: snapshots on disk, and the views in place; +//! * [`plan`]: what a submission would do, and applying it; +//! * [`pack`]: making a submission from a source list. + +pub mod content; +pub mod media; +pub mod name; +pub mod pack; +pub mod plan; +pub mod program; +pub mod schema; +pub mod scratch; +pub mod store; +pub mod submission; +pub mod view; + +/// A new identifier for a snapshot: a random UUID (version 4). +pub fn new_id() -> anyhow::Result { + use std::io::Read; + let mut bytes = [0u8; 16]; + std::fs::File::open("/dev/urandom")?.read_exact(&mut bytes)?; + bytes[6] = (bytes[6] & 0x0f) | 0x40; + bytes[8] = (bytes[8] & 0x3f) | 0x80; + let hex: String = bytes.iter().map(|byte| format!("{byte:02x}")).collect(); + Ok(format!( + "{}-{}-{}-{}-{}", + &hex[0..8], + &hex[8..12], + &hex[12..16], + &hex[16..20], + &hex[20..32] + )) +} diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..16c553d --- /dev/null +++ b/src/main.rs @@ -0,0 +1,505 @@ +//! `enstate`: the receptor's commands on a host (`--plan`, `--apply`, `--status`, +//! `--materialize`), and the provider's (`--pack`). Commands are options, like every +//! other, in any order. + +use std::io::{IsTerminal, Write}; +use std::path::{Path, PathBuf}; +use std::process::ExitCode; + +use anyhow::{Context, Result, bail}; +use clap::{Arg, ArgAction, ArgGroup, Command}; +use config::option::{Kind, OptionSpec, option}; +use serde::Deserialize; + +use enstate::plan::{self, Plan, ViewOutcome}; +use enstate::schema::Schema; +use enstate::store::Store; +use enstate::submission::Submission; +use enstate::view; + +const OPTIONS: &[OptionSpec] = &[ + option( + "state-dir", + Kind::Text, + "DIR", + Some("/var/lib/enstate"), + "Where snapshots are kept", + ), + option( + "run-dir", + Kind::Text, + "DIR", + Some("/run/enstate"), + "Where views are put", + ), + option( + "schema", + Kind::Text, + "PATH", + Some("/etc/enstate/schema.json"), + "The schema of the running generation; for --pack, one to check the source list against", + ), + OptionSpec { + hidden: true, + ..option( + "systemctl", + Kind::Text, + "PATH", + Some("systemctl"), + "What runs reactions", + ) + }, +]; + +const SETTINGS: config::option::Schema = config::option::Schema { + options: OPTIONS, + conflicts: &[], + gone: &[], +}; + +#[derive(Deserialize)] +#[serde(rename_all = "kebab-case")] +struct Settings { + state_dir: Option, + run_dir: Option, + schema: Option, + systemctl: Option, +} + +const COMMANDS: &[(&str, &str)] = &[ + ( + "plan", + "Say what the submission in PATH would do, changing nothing", + ), + ( + "apply", + "Apply the submission in PATH, if its plan is accepted", + ), + ("status", "Show the channels' snapshots and the views"), + ( + "materialize", + "Put every view in place from the snapshots (at boot, after a switch)", + ), + ( + "pack", + "Make a submission in --out from the source list in PATH", + ), +]; + +fn command() -> Command { + let mut command = Command::new("enstate") + .about("State next to the Nix store: plan, apply, and make submissions") + .disable_version_flag(true) + .disable_help_flag(true) + .next_help_heading("Commands"); + for (name, help) in COMMANDS { + command = command.arg( + Arg::new(*name) + .long(*name) + .action(ArgAction::SetTrue) + .help(*help), + ); + } + command = command + .group( + ArgGroup::new("command") + .args(COMMANDS.iter().map(|(name, _)| *name)) + .required(true) + .multiple(false), + ) + .next_help_heading("Options") + .arg( + Arg::new("help") + .long("help") + .short('h') + .action(ArgAction::Help) + .help("Print this help"), + ) + .arg( + Arg::new("json") + .long("json") + .action(ArgAction::SetTrue) + .help("Print JSON (--plan, --apply, --status, --materialize)"), + ) + .arg( + Arg::new("out") + .long("out") + .value_name("DIR") + .help("Where --pack writes the submission"), + ) + .arg( + Arg::new("path") + .value_name("PATH") + .help("The submission (--plan, --apply) or source list (--pack)"), + ) + .next_help_heading("Settings"); + config::arguments::with_print_config(config::arguments::with_options(command, OPTIONS)) +} + +fn main() -> ExitCode { + match run() { + Ok(code) => code, + Err(error) => { + eprintln!("enstate: {error:#}"); + ExitCode::from(2) + } + } +} + +fn run() -> Result { + config::arguments::refuse_gone(std::env::args().skip(1), &SETTINGS)?; + let matches = command().get_matches(); + let (layer, files) = config::arguments::merged(&matches, &SETTINGS, &[])?; + if config::arguments::prints_config(&matches) { + let settings = layer + .iter() + .map(|(name, entry)| (name.clone(), entry.value.clone())) + .collect(); + let origins = layer + .iter() + .map(|(name, entry)| (name.clone(), entry.origin.clone())) + .collect(); + let report = config::report::report( + &SETTINGS, + &settings, + &origins, + &files, + config::report::Values::Interpolated, + ); + println!("{}", serde_json::to_string_pretty(&report)?); + return Ok(ExitCode::SUCCESS); + } + let settings: Settings = config::layer::read(&layer)?; + let command = COMMANDS + .iter() + .map(|(name, _)| *name) + .find(|name| matches.get_flag(name)) + .expect("clap requires one command"); + let json = matches.get_flag("json"); + let path = matches.get_one::("path").map(PathBuf::from); + let out = matches.get_one::("out").map(PathBuf::from); + // An option that isn't for the command is an error. + let takes_path = matches!(command, "plan" | "apply" | "pack"); + match (&path, takes_path) { + (None, true) => bail!("--{command} needs a PATH"), + (Some(path), false) => bail!("--{command} takes no PATH ({})", path.display()), + _ => {} + } + if out.is_some() && command != "pack" { + bail!("--out is for --pack only"); + } + if json && command == "pack" { + bail!("--json is not for --pack"); + } + if command == "pack" { + let out = out.context("--pack needs --out DIR")?; + let schema = settings.schema.as_deref().map(Schema::load).transpose()?; + enstate::pack::pack(path.as_deref().unwrap(), &out, schema.as_ref())?; + return Ok(ExitCode::SUCCESS); + } + let store = Store::new( + settings + .state_dir + .as_deref() + .unwrap_or(Path::new("/var/lib/enstate")), + settings + .run_dir + .as_deref() + .unwrap_or(Path::new("/run/enstate")), + ); + let schema_path = settings + .schema + .unwrap_or_else(|| PathBuf::from("/etc/enstate/schema.json")); + let schema_bytes = std::fs::read(&schema_path) + .with_context(|| format!("reading {}", schema_path.display()))?; + let schema = Schema::from_slice(&schema_bytes) + .with_context(|| format!("schema {}", schema_path.display()))?; + let systemctl = settings + .systemctl + .unwrap_or_else(|| PathBuf::from("systemctl")); + let _lock = store.lock()?; + match command { + "plan" | "apply" => { + let submission = Submission::load(path.as_deref().unwrap())?; + let planned = plan::plan(&schema, &store, &submission)?; + let plan = if command == "apply" { + planned.apply(&store, &schema_bytes, &systemctl)? + } else { + planned.plan + }; + if json { + println!("{}", serde_json::to_string_pretty(&plan)?); + } else { + print_plan(&plan, command == "apply")?; + } + Ok(if !plan.accepted { + ExitCode::from(1) + } else if !plan.failed.is_empty() { + ExitCode::from(3) + } else { + ExitCode::SUCCESS + }) + } + "materialize" => { + let views = plan::materialize(&schema, &store)?; + if json { + println!("{}", serde_json::to_string_pretty(&views)?); + } else { + print_views(&mut std::io::stdout().lock(), &views, false)?; + } + Ok(ExitCode::SUCCESS) + } + "status" => { + let status = status(&schema, &store)?; + if json { + println!("{}", serde_json::to_string_pretty(&status)?); + } else { + print_status(&status)?; + } + Ok(ExitCode::SUCCESS) + } + _ => unreachable!(), + } +} + +/// Colors, on a terminal, and without `NO_COLOR`. +struct Style { + on: bool, +} + +impl Style { + fn new() -> Self { + Self { + on: std::io::stdout().is_terminal() + && std::env::var_os("NO_COLOR").is_none_or(|value| value.is_empty()), + } + } + + fn paint(&self, code: &str, text: &str) -> String { + if self.on { + format!("\x1b[{code}m{text}\x1b[0m") + } else { + text.to_owned() + } + } +} + +fn print_plan(plan: &Plan, applying: bool) -> Result<()> { + let style = Style::new(); + let mut out = std::io::stdout().lock(); + let verdict = if plan.accepted { + style.paint("32", "accepted") + } else { + style.paint("31", "refused") + }; + writeln!(out, "channel {}: {verdict}", plan.channel)?; + writeln!( + out, + " current snapshot: {}", + plan.current.as_deref().unwrap_or("none") + )?; + if let Some(base) = &plan.base { + writeln!(out, " builds on: {base}")?; + } + for reason in &plan.refused { + writeln!(out, " {} {reason}", style.paint("31", "refused:"))?; + } + if !plan.items.is_empty() { + writeln!(out, "items:")?; + } + for item in &plan.items { + let mark = if item.goes_in { + style.paint("32", "+") + } else { + style.paint("33", "-") + }; + let mut what = format!( + "{}, {}", + item.op, + if item.required { + "required" + } else { + "optional" + } + ); + if let Some(group) = &item.group { + what.push_str(&format!(", group {group}")); + } + writeln!(out, " {mark} {} ({what})", item.address)?; + for reason in &item.reasons { + writeln!(out, " {reason}")?; + } + } + for warning in &plan.warnings { + writeln!(out, "{} {warning}", style.paint("33", "warning:"))?; + } + print_views(&mut out, &plan.views, true)?; + if !plan.reactions.restart.is_empty() { + writeln!(out, "restart: {}", plan.reactions.restart.join(" "))?; + } + if !plan.reactions.reload.is_empty() { + writeln!(out, "reload: {}", plan.reactions.reload.join(" "))?; + } + if plan.accepted && !plan.changes { + writeln!(out, "nothing changes")?; + } + if applying && plan.accepted { + match &plan.snapshot { + Some(id) => writeln!(out, "applied: snapshot {id}")?, + None if plan.changes => writeln!(out, "applied: the snapshot is unchanged")?, + None => {} + } + for failed in &plan.failed { + writeln!(out, "{} {failed}", style.paint("31", "failed:"))?; + } + } + Ok(()) +} + +fn print_views(out: &mut impl Write, views: &[ViewOutcome], only_changes: bool) -> Result<()> { + let style = Style::new(); + let changing: Vec<_> = views + .iter() + .filter(|view| !only_changes || view.change != view::Change::Unchanged) + .collect(); + if changing.is_empty() { + return Ok(()); + } + writeln!(out, "views:")?; + for view in changing { + let change = match view.change { + view::Change::Unchanged => "unchanged", + view::Change::Added => "added", + view::Change::Removed => "removed", + view::Change::Changed => "changed", + }; + let secret = if view.secret { " (secret)" } else { "" }; + writeln!(out, " {}{secret}: {change}", view.name)?; + for file in &view.files { + for line in file.diff.lines() { + let painted = match line.chars().next() { + Some('+') if !line.starts_with("+++") => style.paint("32", line), + Some('-') if !line.starts_with("---") => style.paint("31", line), + _ => line.to_owned(), + }; + writeln!(out, " {painted}")?; + } + } + } + Ok(()) +} + +#[derive(serde::Serialize)] +struct Status { + channels: Vec, + views: Vec, +} + +#[derive(serde::Serialize)] +struct ChannelStatus { + channel: String, + snapshot: Option, + filled: Vec, + unfilled: Vec, + /// Required, and unfilled. + missing: Vec, + /// Kept, but in no slot of the schema. + kept: Vec, +} + +#[derive(serde::Serialize)] +struct ViewStatus { + view: String, + installed: bool, +} + +fn status(schema: &Schema, store: &Store) -> Result { + let mut channels = Vec::new(); + let mut names: Vec = schema.channels.keys().cloned().collect(); + for channel in store.channels()? { + if !names.contains(&channel) { + names.push(channel); + } + } + for channel in names { + let snapshot = store.current(&channel)?; + let content = snapshot + .as_ref() + .map(|snapshot| snapshot.content.clone()) + .unwrap_or_default(); + let slots = schema + .channel(&channel) + .map(|spec| spec.slots.clone()) + .unwrap_or_default(); + channels.push(ChannelStatus { + channel: channel.clone(), + snapshot: snapshot.map(|snapshot| snapshot.id), + filled: slots + .keys() + .filter(|slot| content.contains_key(*slot)) + .cloned() + .collect(), + unfilled: slots + .keys() + .filter(|slot| !content.contains_key(*slot)) + .cloned() + .collect(), + missing: slots + .iter() + .filter(|(slot, spec)| spec.required && !content.contains_key(*slot)) + .map(|(slot, _)| slot.clone()) + .collect(), + kept: content + .keys() + .filter(|slot| !slots.contains_key(*slot)) + .cloned() + .collect(), + }); + } + let views = schema + .views + .keys() + .map(|view| ViewStatus { + view: view.clone(), + installed: store.installed_view(view).is_some(), + }) + .collect(); + Ok(Status { channels, views }) +} + +fn print_status(status: &Status) -> Result<()> { + let style = Style::new(); + let mut out = std::io::stdout().lock(); + for channel in &status.channels { + writeln!( + out, + "channel {}: snapshot {}", + channel.channel, + channel.snapshot.as_deref().unwrap_or("none") + )?; + for slot in &channel.filled { + writeln!(out, " {} {slot}", style.paint("32", "filled"))?; + } + for slot in &channel.unfilled { + let missing = channel.missing.contains(slot); + let label = if missing { + style.paint("31", "missing") + } else { + "unfilled".to_owned() + }; + writeln!(out, " {label} {slot}")?; + } + for slot in &channel.kept { + writeln!(out, " {} {slot}", style.paint("33", "kept"))?; + } + } + for view in &status.views { + let state = if view.installed { + style.paint("32", "in place") + } else { + style.paint("33", "not in place") + }; + writeln!(out, "view {}: {state}", view.view)?; + } + Ok(()) +} diff --git a/src/media.rs b/src/media.rs new file mode 100644 index 0000000..c6b1c22 --- /dev/null +++ b/src/media.rs @@ -0,0 +1,92 @@ +//! Types, as media types (docs/design.md, 5.1): compared in a normal form, and keyed +//! (holding records) where their top level is an object, which to start with means +//! JSON. + +use anyhow::{Result, bail}; + +/// `media_type` in its normal form: type and subtype and parameter names in lower +/// case, parameters sorted by name, `; ` between them. Parameter values stay as they +/// are, but for the quotes around a quoted one that needs none. +pub fn normalize(media_type: &str) -> Result { + let mut parts = media_type.split(';'); + let essence = parts.next().unwrap_or_default().trim().to_ascii_lowercase(); + let Some((kind, subtype)) = essence.split_once('/') else { + bail!("type {media_type:?} is not a media type (TYPE/SUBTYPE)"); + }; + if !is_token(kind) || !is_token(subtype) { + bail!("type {media_type:?} is not a media type (TYPE/SUBTYPE)"); + } + let mut parameters = Vec::new(); + for parameter in parts { + let Some((name, value)) = parameter.split_once('=') else { + bail!("type {media_type:?}: parameter {parameter:?} is not NAME=VALUE"); + }; + let name = name.trim().to_ascii_lowercase(); + let mut value = value.trim().to_owned(); + if value.len() >= 2 && value.starts_with('"') && value.ends_with('"') { + let inner = &value[1..value.len() - 1]; + if is_token(inner) { + value = inner.to_owned(); + } + } + if !is_token(&name) || value.is_empty() { + bail!("type {media_type:?}: parameter {parameter:?} is not NAME=VALUE"); + } + if parameters.iter().any(|(other, _)| *other == name) { + bail!("type {media_type:?}: parameter {name} is given twice"); + } + parameters.push((name, value)); + } + parameters.sort(); + let mut normal = essence; + for (name, value) in parameters { + normal.push_str(&format!("; {name}={value}")); + } + Ok(normal) +} + +/// Whether entries of `media_type` (normalized) are keyed: JSON objects, whose keys are +/// records. +pub fn keyed(media_type: &str) -> bool { + let essence = media_type.split(';').next().unwrap_or_default(); + let subtype = essence + .split_once('/') + .map(|(_, subtype)| subtype) + .unwrap_or_default(); + subtype == "json" || subtype.ends_with("+json") +} + +fn is_token(text: &str) -> bool { + !text.is_empty() + && text + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || b"!#$&-^_.+".contains(&byte)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn normal_forms() { + assert_eq!( + normalize("Application/X-OpenSSH-Private-Key;Algorithm=\"ed25519\"").unwrap(), + "application/x-openssh-private-key; algorithm=ed25519" + ); + assert_eq!( + normalize("text/plain; b=2; a=1").unwrap(), + "text/plain; a=1; b=2" + ); + assert!(normalize("text").is_err()); + assert!(normalize("text/plain; a").is_err()); + assert!(normalize("text/plain; a=1; A=2").is_err()); + } + + #[test] + fn keyed_types() { + assert!(keyed("application/x-enstate-hosts+json")); + assert!(keyed("application/json")); + assert!(!keyed("application/octet-stream")); + assert!(!keyed("application/x-pem-file; x=json")); + } +} diff --git a/src/name.rs b/src/name.rs new file mode 100644 index 0000000..a1ed0e4 --- /dev/null +++ b/src/name.rs @@ -0,0 +1,140 @@ +//! Names of channels and slots, and addresses (docs/design.md, 5.1). + +use std::fmt; +use std::str::FromStr; + +use anyhow::{Result, anyhow, bail}; + +/// Whether `name` is a portable filename (POSIX.1-2017, 3.281) not starting with a +/// hyphen, and neither `.` nor `..`: `[0-9A-Za-z._][0-9A-Za-z._-]*`. +pub fn is_name(name: &str) -> bool { + let mut chars = name.chars(); + let portable = |c: char| c.is_ascii_alphanumeric() || c == '.' || c == '_'; + match chars.next() { + Some(first) if portable(first) => {} + _ => return false, + } + chars.all(|c| portable(c) || c == '-') && name != "." && name != ".." +} + +/// `name`, if it is one, else an error saying what it was meant to name. +pub fn check(what: &str, name: &str) -> Result<()> { + if is_name(name) { + Ok(()) + } else { + bail!( + "{what} {name:?} is not a portable filename ([0-9A-Za-z._][0-9A-Za-z._-]*, not . or ..)" + ) + } +} + +/// `CHANNEL/SLOT` for an entry, `CHANNEL/SLOT/KEY` for a record. A record's key is +/// everything after the second `/`, so it may hold `/` itself. +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct Address { + pub channel: String, + pub slot: String, + pub key: Option, +} + +impl Address { + pub fn entry(channel: &str, slot: &str) -> Self { + Self { + channel: channel.to_owned(), + slot: slot.to_owned(), + key: None, + } + } + + /// The address of the entry this is, or holds this record. + pub fn of_entry(&self) -> Self { + Self::entry(&self.channel, &self.slot) + } + + /// Whether one of the two is within the other: the same entry, or an entry and one + /// of its records, or the same record. + pub fn overlaps(&self, other: &Address) -> bool { + self.channel == other.channel + && self.slot == other.slot + && match (&self.key, &other.key) { + (Some(one), Some(other)) => one == other, + _ => true, + } + } +} + +impl FromStr for Address { + type Err = anyhow::Error; + + fn from_str(text: &str) -> Result { + let mut parts = text.splitn(3, '/'); + let channel = parts.next().unwrap_or_default(); + let slot = parts + .next() + .ok_or_else(|| anyhow!("address {text:?} is not CHANNEL/SLOT or CHANNEL/SLOT/KEY"))?; + check("channel", channel)?; + check("slot", slot)?; + let key = match parts.next() { + None => None, + Some("") => bail!("address {text:?} has an empty key"), + Some(key) => Some(key.to_owned()), + }; + Ok(Self { + channel: channel.to_owned(), + slot: slot.to_owned(), + key, + }) + } +} + +impl fmt::Display for Address { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}/{}", self.channel, self.slot)?; + if let Some(key) = &self.key { + write!(f, "/{key}")?; + } + Ok(()) + } +} + +impl serde::Serialize for Address { + fn serialize(&self, serializer: S) -> Result { + serializer.collect_str(self) + } +} + +impl<'de> serde::Deserialize<'de> for Address { + fn deserialize>(deserializer: D) -> Result { + let text = String::deserialize(deserializer)?; + text.parse().map_err(serde::de::Error::custom) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn names() { + for good in ["a", "retiolum.key", "_x", ".hidden", "a-b", "0"] { + assert!(is_name(good), "{good}"); + } + for bad in ["", ".", "..", "-a", "a/b", "a b", "ä"] { + assert!(!is_name(bad), "{bad}"); + } + } + + #[test] + fn addresses() { + let record: Address = "fleet/hosts/a/b".parse().unwrap(); + assert_eq!(record.key.as_deref(), Some("a/b")); + assert_eq!(record.to_string(), "fleet/hosts/a/b"); + let entry: Address = "fleet/hosts".parse().unwrap(); + assert!(entry.overlaps(&record) && record.overlaps(&entry)); + let other: Address = "fleet/hosts/c".parse().unwrap(); + assert!(!other.overlaps(&record)); + assert!("fleet".parse::
().is_err()); + assert!("fleet/hosts/".parse::
().is_err()); + assert!("fleet/../x".parse::
().is_err()); + } +} diff --git a/src/pack.rs b/src/pack.rs new file mode 100644 index 0000000..67603d6 --- /dev/null +++ b/src/pack.rs @@ -0,0 +1,233 @@ +//! Making a submission from a source list (docs/design.md, section 10). +//! +//! ```json +//! { +//! "channel": "secrets", +//! "complete": true, +//! "items": { +//! "retiolum.key": { "source": "cmd:secrets ${env:HOST} show retiolum.ed25519_key.priv" }, +//! "tls.pem": { "source": { "file": "/etc/ssl/some.pem" }, "required": false }, +//! "hosts/ne": { "source": { "file": "ne.json" }, "group": "ne" }, +//! "hosts/wu": { "remove": true } +//! }, +//! "groups": { "ne": { "required": false } } +//! } +//! ``` +//! +//! An item is named `SLOT` (an entry) or `SLOT/KEY` (a record). Sources are those of +//! continuum's `config` crate: `env:`, `file:`, `cmd:`, the tables `{ "env": … }`, +//! `{ "file": … }`, `{ "command": … }`, and text with placeholders. An entry is taken +//! byte-exact (as `+raw`), a record as JSON. Relative paths are relative to the +//! source list, and commands run in its directory. JSON, or TOML by the extension +//! `.toml`. + +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; + +use anyhow::{Context, Result, anyhow, bail}; +use config::import::{self, Format, Imported, Importer, Raw, Source}; +use serde::Deserialize; +use serde_json::{Map, Value}; + +use crate::content; +use crate::name::{self, Address}; +use crate::schema::Schema; +use crate::submission::{self, GroupSpec, ItemSpec, Manifest, Op}; + +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct SourceList { + pub channel: String, + #[serde(default)] + pub complete: bool, + #[serde(default)] + pub base: Option, + pub items: BTreeMap, + #[serde(default)] + pub groups: BTreeMap, +} + +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ItemSource { + #[serde(default)] + pub source: Option, + #[serde(default)] + pub remove: bool, + #[serde(default)] + pub required: Option, + #[serde(default)] + pub group: Option, +} + +impl SourceList { + pub fn load(path: &Path) -> Result { + let text = + std::fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?; + let value: Value = if path + .extension() + .is_some_and(|extension| extension == "toml") + { + toml::from_str(&text).with_context(|| format!("source list {}", path.display()))? + } else { + serde_json::from_str(&text) + .with_context(|| format!("source list {}", path.display()))? + }; + serde_json::from_value(value).with_context(|| format!("source list {}", path.display())) + } +} + +/// Packs the source list at `path` into a submission in `out` (which must not exist, +/// or be empty), checked against `schema` if one is given. +pub fn pack(path: &Path, out: &Path, schema: Option<&Schema>) -> Result<()> { + let list = SourceList::load(path)?; + let dir = path + .parent() + .map(Path::to_owned) + .filter(|dir| !dir.as_os_str().is_empty()) + .unwrap_or_else(|| PathBuf::from(".")); + name::check("channel", &list.channel)?; + let mut items = Vec::new(); + for (key, item) in &list.items { + let address: Address = format!("{}/{key}", list.channel) + .parse() + .with_context(|| format!("item {key}"))?; + if item.remove == item.source.is_some() { + bail!("item {key}: give either a source or \"remove\": true"); + } + items.push((address, item)); + } + if let Some(schema) = schema { + check(schema, &list, &items)?; + } + // Read every source before writing anything. + let mut entries: BTreeMap> = BTreeMap::new(); + let mut records: BTreeMap> = BTreeMap::new(); + let mut specs = Vec::new(); + for (address, item) in &items { + if let Some(source) = &item.source { + let importer = importer(source, &dir, address.key.is_none()) + .with_context(|| format!("item {address}"))?; + let imported = importer + .fetch() + .with_context(|| format!("item {address}: {}", importer.describe()))?; + match &address.key { + None => { + entries.insert(address.slot.clone(), bytes(imported)); + } + Some(key) => { + let value = match imported { + Imported::Json(value) => value, + other => serde_json::from_slice(&bytes(other)) + .with_context(|| format!("item {address}: not JSON"))?, + }; + records + .entry(address.slot.clone()) + .or_default() + .insert(key.clone(), value); + } + } + } + specs.push(ItemSpec { + address: address.clone(), + op: if item.remove { Op::Remove } else { Op::Set }, + required: item.required, + group: item.group.clone(), + }); + } + if let Some(slot) = records.keys().find(|slot| entries.contains_key(*slot)) { + bail!("slot {slot} is given both as a whole and by records"); + } + let manifest = Manifest { + submission: submission::VERSION, + channel: list.channel.clone(), + complete: list.complete, + base: list.base.clone(), + items: specs, + groups: list.groups, + }; + match std::fs::read_dir(out) { + Ok(mut existing) => { + if existing.next().is_some() { + bail!("{} is not empty", out.display()); + } + } + Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} + Err(error) => return Err(error).with_context(|| format!("reading {}", out.display())), + } + let channel_dir = out.join(submission::CHANNELS).join(&list.channel); + content::write_dir(&entries, &channel_dir, 0o600)?; + for (slot, records) in &records { + content::write_file( + &channel_dir.join(slot), + &content::from_records(records), + 0o600, + )?; + } + let mut manifest_bytes = serde_json::to_vec_pretty(&manifest)?; + manifest_bytes.push(b'\n'); + content::write_file(&out.join(submission::MANIFEST), &manifest_bytes, 0o600)?; + // What was written is a submission the receptor reads. + submission::Submission::load(out)?; + Ok(()) +} + +/// The importer `source` describes, in `dir`: raw for an entry, JSON for a record. +fn importer(source: &Value, dir: &Path, entry: bool) -> Result { + let mut importer = match source { + Value::String(text) => match import::parse_argument(text) { + Raw::Import(mut importer) => { + importer.dir = Some(dir.to_owned()); + importer + } + Raw::Literal(_) => { + bail!("source {text:?} is neither env:, file:, cmd: nor text with placeholders") + } + }, + Value::Object(table) => import::parse_table(table, dir)? + .ok_or_else(|| anyhow!("source is not a table of env, file or command"))?, + other => bail!("source {other} is neither a text nor a table"), + }; + if !matches!(importer.source, Source::Template(_)) { + importer.format = if entry { Format::Raw } else { Format::Json }; + } + Ok(importer) +} + +fn bytes(imported: Imported) -> Vec { + match imported { + Imported::Raw(bytes) => bytes, + Imported::Text(text) => text.into_bytes(), + Imported::Json(value) => value.to_string().into_bytes(), + } +} + +/// The source list against the schema: the channel, the slots, records only in keyed +/// types, and for a complete submission every required slot given. +fn check(schema: &Schema, list: &SourceList, items: &[(Address, &ItemSource)]) -> Result<()> { + let Some(channel) = schema.channel(&list.channel) else { + bail!("the schema has no channel {}", list.channel); + }; + for (address, _) in items { + let Some(slot) = channel.slots.get(&address.slot) else { + bail!("the schema has no slot {}", address.of_entry()); + }; + if address.key.is_some() && !crate::media::keyed(&slot.media_type) { + bail!("item {address}: type {} holds no records", slot.media_type); + } + } + if list.complete { + for (slot, spec) in &channel.slots { + let given = items + .iter() + .any(|(address, item)| address.slot == *slot && !item.remove); + if spec.required && !given { + bail!( + "required slot {}/{slot} has no source, and the submission is complete", + list.channel + ); + } + } + } + Ok(()) +} diff --git a/src/plan.rs b/src/plan.rs new file mode 100644 index 0000000..952f3aa --- /dev/null +++ b/src/plan.rs @@ -0,0 +1,566 @@ +//! What a submission would do, and doing it (docs/design.md, 5.5). +//! +//! The plan: check the channel and the base; apply the items to a copy of the current +//! snapshot; run the validators on it, leaving out optional items an objection names, +//! with their groups, and refusing for a required one or for what is in place; check +//! that every required slot is filled; render the views into scratch and compare. +//! Applying: the same, then the new snapshot becomes current, the views that changed +//! are put in place, and their reactions run, each unit once. + +use std::collections::{BTreeMap, BTreeSet}; +use std::path::Path; +use std::process::Command; + +use anyhow::{Context, Result, anyhow}; +use serde::Serialize; + +use crate::content::{self, Content}; +use crate::media; +use crate::name::Address; +use crate::program::{self, Given, ProgramFailed, Role}; +use crate::schema::{Reactions, Schema}; +use crate::scratch::Scratch; +use crate::store::Store; +use crate::submission::{Change, Item, Submission}; +use crate::view::{self, FileChange}; + +#[derive(Debug, Clone, Serialize)] +pub struct Plan { + pub channel: String, + /// The current snapshot's id. + pub current: Option, + /// The snapshot the submission builds on, if it names one. + pub base: Option, + pub accepted: bool, + /// Why not, if not. + pub refused: Vec, + pub items: Vec, + pub warnings: Vec, + pub views: Vec, + pub reactions: Reactions, + /// Whether the snapshot or a view would change. + pub changes: bool, + /// The new snapshot's id, once applied. + #[serde(skip_serializing_if = "Option::is_none")] + pub snapshot: Option, + /// Reactions that failed, once applied. + #[serde(skip_serializing_if = "Vec::is_empty")] + pub failed: Vec, +} + +#[derive(Debug, Clone, Serialize)] +pub struct ItemOutcome { + pub address: Address, + pub op: &'static str, + pub required: bool, + #[serde(skip_serializing_if = "Option::is_none")] + pub group: Option, + pub goes_in: bool, + #[serde(skip_serializing_if = "Vec::is_empty")] + pub reasons: Vec, +} + +#[derive(Debug, Clone, Serialize)] +pub struct ViewOutcome { + pub name: String, + pub secret: bool, + pub change: view::Change, + pub files: Vec, +} + +/// A plan, and what applying it needs. +pub struct Planned { + pub plan: Plan, + content: Content, + content_changes: bool, + rendered: Vec<(String, Option, bool)>, +} + +/// A plan refused: nothing to apply. +fn refused(plan: Plan) -> Result { + Ok(Planned { + plan, + content: Content::new(), + content_changes: false, + rendered: Vec::new(), + }) +} + +/// Plans `submission` against `schema` and what `store` holds. +pub fn plan(schema: &Schema, store: &Store, submission: &Submission) -> Result { + let channel = submission.channel.as_str(); + let current = store.current(channel)?; + let mut plan = Plan { + channel: channel.to_owned(), + current: current.as_ref().map(|snapshot| snapshot.id.clone()), + base: submission.base.clone(), + accepted: false, + refused: Vec::new(), + items: submission + .items + .iter() + .map(|item| ItemOutcome { + address: item.address.clone(), + op: match item.change { + Change::Remove => "remove", + _ => "set", + }, + required: item.required, + group: item.group.clone(), + goes_in: true, + reasons: Vec::new(), + }) + .collect(), + warnings: Vec::new(), + views: Vec::new(), + reactions: Reactions::default(), + changes: false, + snapshot: None, + failed: Vec::new(), + }; + let Some(channel_spec) = schema.channel(channel) else { + plan.refused + .push(format!("the schema has no channel {channel}")); + return refused(plan); + }; + if let Some(base) = &submission.base { + let current_id = current.as_ref().map(|snapshot| snapshot.id.as_str()); + if current_id != Some(base.as_str()) { + plan.refused.push(format!( + "the submission builds on {base}, but the current snapshot is {}", + current_id.unwrap_or("none") + )); + return refused(plan); + } + } + let empty = Content::new(); + let base_content = match (¤t, submission.complete) { + (Some(snapshot), false) => &snapshot.content, + _ => &empty, + }; + // Other channels, for validators and views given their slots. + let mut others: BTreeMap = BTreeMap::new(); + let mut other_channels: BTreeSet<&str> = BTreeSet::new(); + for validator in schema.validators_of(channel) { + for address in validator.slots { + if address.channel != channel { + other_channels.insert(schema.channels.get_key_value(&address.channel).unwrap().0); + } + } + } + for (_, view) in schema.views_of(Some(channel)) { + for address in &view.from { + if address.channel != channel { + other_channels.insert(schema.channels.get_key_value(&address.channel).unwrap().0); + } + } + } + for other in other_channels { + let content = store + .current(other)? + .map(|snapshot| snapshot.content) + .unwrap_or_default(); + others.insert(other.to_owned(), content); + } + + let items = &submission.items; + // Items that can't go in, whatever the validators say. + let mut cannot: BTreeMap = BTreeMap::new(); + for (index, item) in items.iter().enumerate() { + if let Some(reason) = unfit(schema, item, base_content) { + cannot.insert(index, reason); + } + } + let mut excluded: BTreeSet = BTreeSet::new(); + let leave_out = + |plan: &mut Plan, excluded: &mut BTreeSet, index: usize, reason: String| -> bool { + // Whether it may be left out: else the submission is refused. + let item = &items[index]; + if item.required { + plan.refused + .push(format!("required item {}: {reason}", item.address)); + return false; + } + for (other, other_item) in items.iter().enumerate() { + let together = + other == index || (item.group.is_some() && other_item.group == item.group); + if together && excluded.insert(other) { + plan.items[other].goes_in = false; + let reason = if other == index { + reason.clone() + } else { + format!( + "its group {} can't go in", + item.group.as_deref().unwrap_or_default() + ) + }; + plan.warnings + .push(format!("left out: {}: {reason}", other_item.address)); + plan.items[other].reasons.push(reason); + } + } + true + }; + for (index, reason) in &cannot { + if !excluded.contains(index) && !leave_out(&mut plan, &mut excluded, *index, reason.clone()) + { + return refused(plan); + } + } + + let candidate = loop { + let candidate = apply_items(base_content, items, &excluded); + let mut blame: Vec<(usize, String)> = Vec::new(); + // Required slots first: validators are given filled slots. + for (slot, spec) in &channel_spec.slots { + if !spec.required || candidate.contains_key(slot) { + continue; + } + let address = Address::entry(channel, slot); + let removals: Vec = (0..items.len()) + .filter(|index| !excluded.contains(index)) + .filter(|index| { + items[*index].address == address && items[*index].change == Change::Remove + }) + .collect(); + if removals.is_empty() { + plan.refused + .push(format!("required slot {address} is unfilled")); + } + blame.extend( + removals + .into_iter() + .map(|index| (index, format!("required slot {address} would be unfilled"))), + ); + } + if !plan.refused.is_empty() { + return refused(plan); + } + if blame.is_empty() { + // Validators. + for validator in schema.validators_of(channel) { + let entry = |address: &Address| -> Option<&[u8]> { + if address.channel == channel { + candidate.get(&address.slot).map(Vec::as_slice) + } else { + others + .get(&address.channel)? + .get(&address.slot) + .map(Vec::as_slice) + } + }; + if validator.of_type && entry(&validator.slots[0]).is_none() { + continue; + } + let given = Given { + slots: validator + .slots + .iter() + .map(|address| { + let media_type = schema + .slot(address) + .map(|slot| slot.media_type.as_str()) + .unwrap_or_default(); + (address.clone(), (media_type, entry(address))) + }) + .collect(), + }; + let outcome = match program::run( + &validator.program, + Role::Validator, + &validator.name, + &given, + &store.scratch(), + ) { + Ok(outcome) => outcome, + Err(error) => match error.downcast::() { + Ok(failed) => { + plan.refused.push(failed.to_string()); + return refused(plan); + } + Err(error) => return Err(error), + }, + }; + for objection in outcome.objections { + let said = format!( + "{}: {} (validator {})", + objection.address, objection.message, validator.name + ); + let blamed: Vec = (0..items.len()) + .filter(|index| !excluded.contains(index)) + .filter(|index| items[*index].address.overlaps(&objection.address)) + .collect(); + if blamed.is_empty() { + plan.refused + .push(format!("objection to what is in place: {said}")); + } + blame.extend(blamed.into_iter().map(|index| (index, said.clone()))); + } + } + if !plan.refused.is_empty() { + return refused(plan); + } + } + if blame.is_empty() { + break candidate; + } + for (index, reason) in blame { + if !excluded.contains(&index) && !leave_out(&mut plan, &mut excluded, index, reason) { + return refused(plan); + } + } + }; + for slot in candidate.keys() { + if !channel_spec.slots.contains_key(slot) { + plan.warnings.push(format!( + "kept, but in no slot of the schema: {channel}/{slot}" + )); + } + } + + // Views. + let mut rendered_views = Vec::new(); + let mut entries: view::Entries = others + .iter() + .map(|(name, content)| (name.as_str(), content)) + .collect(); + entries.insert(channel, &candidate); + for (name, view_spec) in schema.views_of(Some(channel)) { + let secret = schema.view_is_secret(view_spec); + let rendered = match view::render(schema, name, view_spec, &entries, &store.scratch()) { + Ok(rendered) => rendered, + Err(error) => match error.downcast::() { + Ok(failed) => { + plan.refused.push(failed.to_string()); + return refused(plan); + } + Err(error) => return Err(error), + }, + }; + let installed = store.installed_view(name); + let (change, files) = view::compare( + installed.as_deref(), + rendered.as_ref().map(Scratch::path), + secret, + )?; + if change != view::Change::Unchanged { + plan.reactions + .restart + .extend(view_spec.reactions.restart.iter().cloned()); + plan.reactions + .reload + .extend(view_spec.reactions.reload.iter().cloned()); + } + plan.views.push(ViewOutcome { + name: name.clone(), + secret, + change, + files, + }); + rendered_views.push((name.clone(), rendered, secret)); + } + let restart: BTreeSet = std::mem::take(&mut plan.reactions.restart) + .into_iter() + .collect(); + let reload: BTreeSet = std::mem::take(&mut plan.reactions.reload) + .into_iter() + .filter(|unit| !restart.contains(unit)) + .collect(); + plan.reactions = Reactions { + restart: restart.into_iter().collect(), + reload: reload.into_iter().collect(), + }; + let content_changes = current.as_ref().map(|snapshot| &snapshot.content) != Some(&candidate); + plan.changes = content_changes + || plan + .views + .iter() + .any(|view| view.change != view::Change::Unchanged); + plan.accepted = true; + Ok(Planned { + plan, + content: candidate, + content_changes, + rendered: rendered_views, + }) +} + +/// Why `item` can't go in, whatever the validators say: no such slot, a record in an +/// entry that holds none. +fn unfit(schema: &Schema, item: &Item, base: &Content) -> Option { + let Some(slot) = schema.slot(&item.address) else { + return Some(format!( + "the schema has no slot {}", + item.address.of_entry() + )); + }; + if item.address.key.is_some() { + if !media::keyed(&slot.media_type) { + return Some(format!("type {} holds no records", slot.media_type)); + } + if let Some(bytes) = base.get(&item.address.slot) + && let Err(error) = content::records(bytes) + { + return Some(format!("the entry in place holds no records: {error}")); + } + } + None +} + +/// `base` with the items not `excluded` applied. +fn apply_items(base: &Content, items: &[Item], excluded: &BTreeSet) -> Content { + let mut content = base.clone(); + for (index, item) in items.iter().enumerate() { + if excluded.contains(&index) { + continue; + } + let slot = &item.address.slot; + match (&item.address.key, &item.change) { + (None, Change::Entry(bytes)) => { + content.insert(slot.clone(), bytes.clone()); + } + (None, Change::Remove) => { + content.remove(slot); + } + (Some(key), change) => { + // `unfit` made sure an entry in place holds records. + let mut records = content + .get(slot) + .and_then(|bytes| content::records(bytes).ok()) + .unwrap_or_default(); + match change { + Change::Record(value) => { + records.insert(key.clone(), value.clone()); + } + Change::Remove => { + records.remove(key); + } + Change::Entry(_) => unreachable!("an entry's item has no key"), + } + content.insert(slot.clone(), content::from_records(&records)); + } + (None, Change::Record(_)) => unreachable!("a record's item has a key"), + } + } + content +} + +impl Planned { + /// Applies the plan, if it was accepted: the new snapshot, the views that change, + /// and their reactions, by `systemctl`. + pub fn apply(self, store: &Store, schema_bytes: &[u8], systemctl: &Path) -> Result { + let mut plan = self.plan; + if !plan.accepted { + return Ok(plan); + } + if self.content_changes { + plan.snapshot = Some(store.commit( + &plan.channel, + &self.content, + plan.current.as_deref(), + schema_bytes, + )?); + } + for ((name, rendered, secret), outcome) in self.rendered.into_iter().zip(&plan.views) { + if outcome.change != view::Change::Unchanged { + store + .install_view(&name, rendered, secret) + .with_context(|| format!("view {name}"))?; + } + } + plan.failed = react(&plan.reactions, systemctl); + Ok(plan) + } +} + +/// Runs `reactions`; what failed. +pub fn react(reactions: &Reactions, systemctl: &Path) -> Vec { + let mut failed = Vec::new(); + for (verb, units) in [ + ("restart", &reactions.restart), + ("reload", &reactions.reload), + ] { + if units.is_empty() { + continue; + } + let result = Command::new(systemctl) + .arg(verb) + .args(units) + .status() + .map_err(|error| anyhow!("{error}")) + .and_then(|status| { + if status.success() { + Ok(()) + } else { + Err(anyhow!("{status}")) + } + }); + if let Err(error) = result { + failed.push(format!( + "{} {verb} {}: {error}", + systemctl.display(), + units.join(" ") + )); + } + } + failed +} + +/// Renders every view of `schema` from the current snapshots, puts those that differ +/// from what is in place there, and takes away views the schema doesn't have: at boot, +/// and after a generation change. Runs no reactions. Returns how each view changed. +pub fn materialize(schema: &Schema, store: &Store) -> Result> { + let mut contents: BTreeMap = BTreeMap::new(); + for channel in schema.channels.keys() { + if let Some(snapshot) = store.current(channel)? { + contents.insert(channel.clone(), snapshot.content); + } + } + let entries: view::Entries = contents + .iter() + .map(|(name, content)| (name.as_str(), content)) + .collect(); + let mut outcomes = Vec::new(); + for (name, view_spec) in schema.views_of(None) { + let secret = schema.view_is_secret(view_spec); + let rendered = view::render(schema, name, view_spec, &entries, &store.scratch()) + .with_context(|| format!("view {name}"))?; + let installed = store.installed_view(name); + let (change, files) = view::compare( + installed.as_deref(), + rendered.as_ref().map(Scratch::path), + secret, + )?; + if change != view::Change::Unchanged { + store.install_view(name, rendered, secret)?; + } + outcomes.push(ViewOutcome { + name: name.clone(), + secret, + change, + files, + }); + } + let views = store.run.join("views"); + if let Ok(entries) = std::fs::read_dir(&views) { + for entry in entries { + let name = entry?.file_name().to_string_lossy().into_owned(); + if name == ".generations" + || name.ends_with(".new-link") + || schema.views.contains_key(&name) + { + continue; + } + if store.installed_view(&name).is_some() { + store.install_view(&name, None, false)?; + outcomes.push(ViewOutcome { + name, + secret: false, + change: view::Change::Removed, + files: Vec::new(), + }); + } + } + } + Ok(outcomes) +} diff --git a/src/program.rs b/src/program.rs new file mode 100644 index 0000000..8c4a565 --- /dev/null +++ b/src/program.rs @@ -0,0 +1,201 @@ +//! The protocol of validators, renderers, converters and steps (docs/design.md, 5.2). +//! +//! `PROGRAM IN OUT`, standard input `/dev/null`, an empty environment, in `IN`. `IN` +//! holds `invocation.json` and the slots given at `channels/CHANNEL/SLOT`; `OUT` is +//! empty. Objections are JSON lines on standard output; an exit status but 0 is a +//! failure. +//! +//! `IN` is read-only (for its owner, as root ignores modes). Not yet: a sandbox (no +//! network, nothing writable but `OUT`). + +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; + +use anyhow::{Context, Result, anyhow, bail}; +use serde::{Deserialize, Serialize}; + +use crate::content; +use crate::name::Address; +use crate::scratch::Scratch; + +pub const PROTOCOL: u32 = 1; +pub const INVOCATION: &str = "invocation.json"; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "lowercase")] +pub enum Role { + Validator, + Renderer, + Converter, + Step, +} + +/// What a program is given: slots, by address, with their types and entries (none for +/// an unfilled one). +pub struct Given<'a> { + pub slots: BTreeMap)>, +} + +#[derive(Serialize)] +struct Invocation<'a> { + protocol: u32, + program: Role, + #[serde(skip_serializing_if = "Option::is_none")] + view: Option<&'a str>, + #[serde(skip_serializing_if = "Option::is_none")] + validator: Option<&'a str>, + slots: BTreeMap>, + produces: BTreeMap>, +} + +#[derive(Serialize)] +struct SlotType<'a> { + #[serde(rename = "type")] + media_type: &'a str, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Objection { + pub address: Address, + pub message: String, +} + +/// What a program did: its objections, and what it wrote, in `OUT`. +pub struct Outcome { + pub objections: Vec, + pub out: Scratch, +} + +/// Runs `program` as `role`, named `name` (a view's or validator's), on `given`, in a +/// scratch directory below `scratch`. +pub fn run( + program: &Path, + role: Role, + name: &str, + given: &Given, + scratch: &Path, +) -> Result { + let what = format!("{} {name} ({})", role_name(role), program.display()); + let input = Scratch::new(scratch, "in-")?; + let out = Scratch::new(scratch, "out-")?; + let invocation = Invocation { + protocol: PROTOCOL, + program: role, + view: (role == Role::Renderer).then_some(name), + validator: (role == Role::Validator).then_some(name), + slots: given + .slots + .iter() + .map(|(address, (media_type, _))| (address.to_string(), SlotType { media_type })) + .collect(), + produces: BTreeMap::new(), + }; + content::write_file( + &input.path().join(INVOCATION), + &serde_json::to_vec_pretty(&invocation)?, + 0o600, + )?; + for (address, (_, bytes)) in &given.slots { + let Some(bytes) = bytes else { continue }; + let dir = input.path().join("channels").join(&address.channel); + std::fs::create_dir_all(&dir)?; + content::write_file(&dir.join(&address.slot), bytes, 0o600)?; + } + input.set_modes(0o400)?; + let program = std::path::absolute(program).unwrap_or_else(|_| program.to_owned()); + let output = Command::new(&program) + .arg(input.path()) + .arg(out.path()) + .current_dir(input.path()) + .env_clear() + .stdin(Stdio::null()) + .output() + .with_context(|| format!("running {what}"))?; + let stderr = String::from_utf8_lossy(&output.stderr); + if !output.status.success() { + return Err(ProgramFailed { + what, + status: output.status.to_string(), + stderr: stderr.trim_end().to_owned(), + } + .into()); + } + let mut objections = Vec::new(); + let stdout = String::from_utf8(output.stdout) + .map_err(|_| anyhow!("{what}: its standard output is not UTF-8"))?; + for line in stdout.lines().filter(|line| !line.trim().is_empty()) { + let objection: Objection = serde_json::from_str(line) + .with_context(|| format!("{what}: not an objection: {line}"))?; + if !given + .slots + .keys() + .any(|address| address.overlaps(&objection.address)) + { + bail!( + "{what} objects to {}, which it wasn't given", + objection.address + ); + } + objections.push(objection); + } + Ok(Outcome { objections, out }) +} + +fn role_name(role: Role) -> &'static str { + match role { + Role::Validator => "validator", + Role::Renderer => "renderer", + Role::Converter => "converter", + Role::Step => "step", + } +} + +/// A program that didn't exit with 0: no item is to blame. +#[derive(Debug)] +pub struct ProgramFailed { + pub what: String, + pub status: String, + pub stderr: String, +} + +impl std::fmt::Display for ProgramFailed { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{} failed ({})", self.what, self.status)?; + if !self.stderr.is_empty() { + write!(f, ":\n{}", self.stderr)?; + } + Ok(()) + } +} + +impl std::error::Error for ProgramFailed {} + +/// The regular files below `dir`, by path relative to it; anything but regular files +/// and directories is an error. +pub fn files_below(dir: &Path) -> Result>> { + let mut files = BTreeMap::new(); + let mut pending = vec![PathBuf::new()]; + while let Some(relative) = pending.pop() { + let path = dir.join(&relative); + for entry in + std::fs::read_dir(&path).with_context(|| format!("reading {}", path.display()))? + { + let entry = entry?; + let kind = entry.file_type()?; + let relative = relative.join(entry.file_name()); + if kind.is_dir() { + pending.push(relative); + } else if kind.is_file() { + files.insert(relative, std::fs::read(entry.path())?); + } else { + bail!( + "{}: neither a regular file nor a directory", + entry.path().display() + ); + } + } + } + Ok(files) +} diff --git a/src/schema.rs b/src/schema.rs new file mode 100644 index 0000000..a44f6f8 --- /dev/null +++ b/src/schema.rs @@ -0,0 +1,292 @@ +//! What a generation accepts (docs/design.md, 5.1 to 5.3): its channels and their +//! slots, the types' validators and the schema's own, and the views. A JSON file in +//! the system, which the NixOS module writes. +//! +//! ```json +//! { +//! "schema": 1, +//! "types": { "application/x-enstate-hosts+json": { "validator": "/nix/store/…" } }, +//! "channels": { +//! "secrets": { "slots": { "retiolum.key": { "type": "…", "secret": true } } } +//! }, +//! "validators": { "key-pair": { "slots": ["secrets/a.key", "secrets/a.pub"], "program": "…" } }, +//! "views": { +//! "known-hosts": { "from": ["fleet/hosts"], "renderer": "…", "reactions": { "reload": [] } }, +//! "retiolum.key": { "from": ["secrets/retiolum.key"] } +//! } +//! } +//! ``` +//! +//! Slots are required unless they say otherwise. A view without a renderer is the one +//! entry it is from. A view is secret if one of the slots it is from is, unless it +//! says it isn't. + +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; + +use anyhow::{Context, Result, bail}; +use serde::{Deserialize, Serialize}; + +use crate::media; +use crate::name::{self, Address}; + +pub const VERSION: u32 = 1; + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Schema { + pub schema: u32, + #[serde(default)] + pub types: BTreeMap, + pub channels: BTreeMap, + #[serde(default)] + pub validators: BTreeMap, + #[serde(default)] + pub views: BTreeMap, +} + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct TypeSpec { + pub validator: Option, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ChannelSpec { + pub slots: BTreeMap, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields, rename_all = "camelCase")] +pub struct SlotSpec { + #[serde(rename = "type")] + pub media_type: String, + #[serde(default = "yes")] + pub required: bool, + #[serde(default)] + pub secret: bool, +} + +fn yes() -> bool { + true +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ValidatorSpec { + pub slots: Vec
, + pub program: PathBuf, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ViewSpec { + pub from: Vec
, + pub renderer: Option, + pub secret: Option, + #[serde(default)] + pub reactions: Reactions, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Reactions { + #[serde(default)] + pub restart: Vec, + #[serde(default)] + pub reload: Vec, +} + +impl Schema { + /// The schema in `path`, checked, its types normalized. + pub fn load(path: &Path) -> Result { + let bytes = std::fs::read(path).with_context(|| format!("reading {}", path.display()))?; + Self::from_slice(&bytes).with_context(|| format!("schema {}", path.display())) + } + + pub fn from_slice(bytes: &[u8]) -> Result { + let mut schema: Schema = serde_json::from_slice(bytes)?; + schema.check()?; + Ok(schema) + } + + fn check(&mut self) -> Result<()> { + if self.schema != VERSION { + bail!("schema version {} is not {VERSION}", self.schema); + } + self.types = std::mem::take(&mut self.types) + .into_iter() + .map(|(media_type, spec)| Ok((media::normalize(&media_type)?, spec))) + .collect::>()?; + for (channel, spec) in &mut self.channels { + name::check("channel", channel)?; + for (slot, spec) in &mut spec.slots { + name::check("slot", slot)?; + spec.media_type = media::normalize(&spec.media_type) + .with_context(|| format!("slot {channel}/{slot}"))?; + } + } + for (name, validator) in &self.validators { + if validator.slots.is_empty() { + bail!("validator {name} is given no slots"); + } + for address in &validator.slots { + self.entry_slot(address) + .with_context(|| format!("validator {name}"))?; + } + } + for (name, view) in &self.views { + name::check("view", name)?; + if view.from.is_empty() { + bail!("view {name} is made from no slots"); + } + for address in &view.from { + self.entry_slot(address) + .with_context(|| format!("view {name}"))?; + } + if view.renderer.is_none() && view.from.len() != 1 { + bail!("view {name} has no renderer, so it must be made from one slot"); + } + } + Ok(()) + } + + /// The slot `address` names, which must be an entry's address. + fn entry_slot(&self, address: &Address) -> Result<&SlotSpec> { + if address.key.is_some() { + bail!("{address} is a record's address, not a slot's"); + } + self.slot(address) + .with_context(|| format!("no slot {address}")) + } + + /// The slot of the entry `address` is, or is in. + pub fn slot(&self, address: &Address) -> Option<&SlotSpec> { + self.channels + .get(&address.channel)? + .slots + .get(&address.slot) + } + + pub fn channel(&self, channel: &str) -> Option<&ChannelSpec> { + self.channels.get(channel) + } + + /// The validators that see `channel`: each slot's type's own, for that slot, and + /// the schema's that are given one of its slots. + pub fn validators_of(&self, channel: &str) -> Vec { + let mut validators = Vec::new(); + if let Some(spec) = self.channels.get(channel) { + for (slot, slot_spec) in &spec.slots { + if let Some(program) = self + .types + .get(&slot_spec.media_type) + .and_then(|spec| spec.validator.as_ref()) + { + validators.push(Validator { + name: format!("type {}", slot_spec.media_type), + slots: vec![Address::entry(channel, slot)], + program: program.clone(), + of_type: true, + }); + } + } + } + for (name, spec) in &self.validators { + if spec.slots.iter().any(|address| address.channel == channel) { + validators.push(Validator { + name: name.clone(), + slots: spec.slots.clone(), + program: spec.program.clone(), + of_type: false, + }); + } + } + validators + } + + /// The views made from one of `channel`'s slots, or all views. + pub fn views_of(&self, channel: Option<&str>) -> impl Iterator { + self.views.iter().filter(move |(_, view)| match channel { + None => true, + Some(channel) => view.from.iter().any(|address| address.channel == channel), + }) + } + + pub fn view_is_secret(&self, view: &ViewSpec) -> bool { + view.secret.unwrap_or_else(|| { + view.from + .iter() + .any(|address| self.slot(address).is_some_and(|slot| slot.secret)) + }) + } +} + +/// A validator to run: a type's, for one slot, or the schema's. +#[derive(Debug, Clone)] +pub struct Validator { + pub name: String, + pub slots: Vec
, + pub program: PathBuf, + /// A type's own: an unfilled slot isn't checked. + pub of_type: bool, +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_schema() { + let schema = Schema::from_slice( + br#"{ + "schema": 1, + "types": { "Application/X-Hosts+JSON": { "validator": "/bin/check" } }, + "channels": { + "fleet": { "slots": { "hosts": { "type": "application/x-hosts+json" } } }, + "secrets": { "slots": { "a.key": { "type": "application/octet-stream", "secret": true, "required": false } } } + }, + "validators": { "both": { "slots": ["fleet/hosts", "secrets/a.key"], "program": "/bin/both" } }, + "views": { + "hosts": { "from": ["fleet/hosts"], "renderer": "/bin/render" }, + "a.key": { "from": ["secrets/a.key"] } + } + }"#, + ) + .unwrap(); + let validators = schema.validators_of("fleet"); + assert_eq!(validators.len(), 2); + assert_eq!(validators[0].name, "type application/x-hosts+json"); + assert!(schema.view_is_secret(&schema.views["a.key"])); + assert!(!schema.view_is_secret(&schema.views["hosts"])); + assert!(schema.channels["fleet"].slots["hosts"].required); + } + + #[test] + fn mistakes() { + for (bad, said) in [ + (r#"{"schema": 2, "channels": {}}"#, "version"), + ( + r#"{"schema": 1, "channels": {"-x": {"slots": {}}}}"#, + "portable", + ), + ( + r#"{"schema": 1, "channels": {"c": {"slots": {"s": {"type": "text"}}}}}"#, + "media type", + ), + ( + r#"{"schema": 1, "channels": {}, "views": {"v": {"from": ["c/s"]}}}"#, + "no slot c/s", + ), + ( + r#"{"schema": 1, "channels": {"c": {"slots": {"s": {"type": "a/b"}, "t": {"type": "a/b"}}}}, + "views": {"v": {"from": ["c/s", "c/t"]}}}"#, + "no renderer", + ), + ] { + let error = format!("{:#}", Schema::from_slice(bad.as_bytes()).unwrap_err()); + assert!(error.contains(said), "{bad}: {error}"); + } + } +} diff --git a/src/scratch.rs b/src/scratch.rs new file mode 100644 index 0000000..dddd91b --- /dev/null +++ b/src/scratch.rs @@ -0,0 +1,74 @@ +//! Scratch directories, removed when dropped. + +use std::os::unix::fs::PermissionsExt; +use std::path::{Path, PathBuf}; + +use anyhow::{Context, Result}; + +#[derive(Debug)] +pub struct Scratch { + path: PathBuf, + keep: bool, +} + +impl Scratch { + /// A new directory below `parent`, readable by its owner only. + pub fn new(parent: &Path, prefix: &str) -> Result { + use std::os::unix::fs::DirBuilderExt; + std::fs::DirBuilder::new() + .recursive(true) + .mode(0o700) + .create(parent) + .with_context(|| format!("creating {}", parent.display()))?; + let path = parent.join(format!("{prefix}{}", crate::new_id()?)); + std::fs::DirBuilder::new() + .mode(0o700) + .create(&path) + .with_context(|| format!("creating {}", path.display()))?; + Ok(Self { path, keep: false }) + } + + pub fn path(&self) -> &Path { + &self.path + } + + /// Its path, no longer removed when dropped: it has been moved, or is kept. + pub fn keep(mut self) -> PathBuf { + self.keep = true; + self.path.clone() + } + + /// Gives the files below it `mode`, and the directories (it too) the mode to reach + /// them: `0o400` makes it read-only, `0o644` readable by all. + pub fn set_modes(&self, mode: u32) -> Result<()> { + set_modes(&self.path, mode) + } +} + +impl Drop for Scratch { + fn drop(&mut self) { + if !self.keep { + // A read-only directory's entries can't be removed: writable first. + let _ = set_modes(&self.path, 0o600); + let _ = std::fs::remove_dir_all(&self.path); + } + } +} + +/// Files below `dir` get `mode`, directories (`dir` too) the mode to reach them, set +/// on the way down so each can still be entered. +pub fn set_modes(dir: &Path, mode: u32) -> Result<()> { + let directory = crate::content::directory_mode(mode) | 0o100; + let reach = std::fs::Permissions::from_mode(directory | 0o700); + std::fs::set_permissions(dir, reach).with_context(|| format!("chmod {}", dir.display()))?; + for entry in std::fs::read_dir(dir)? { + let entry = entry?; + if entry.file_type()?.is_dir() { + set_modes(&entry.path(), mode)?; + } else { + std::fs::set_permissions(entry.path(), std::fs::Permissions::from_mode(mode))?; + } + } + std::fs::set_permissions(dir, std::fs::Permissions::from_mode(directory))?; + Ok(()) +} diff --git a/src/store.rs b/src/store.rs new file mode 100644 index 0000000..b25495e --- /dev/null +++ b/src/store.rs @@ -0,0 +1,225 @@ +//! Snapshots on disk, and the views in place (docs/design.md, 5.8). +//! +//! ```text +//! STATE/lock +//! STATE/channels/CHANNEL/current -> snapshots/ID +//! STATE/channels/CHANNEL/snapshots/ID/snapshot.json id, and the id it was built on +//! STATE/channels/CHANNEL/snapshots/ID/schema.json the schema it was accepted under +//! STATE/channels/CHANNEL/snapshots/ID/entries/SLOT +//! RUN/views/VIEW -> .generations/VIEW.ID +//! RUN/tmp/ scratch +//! ``` +//! +//! Entries are root's (mode 0600). A new snapshot or view generation is written +//! next to the old one and put in place by replacing a symbolic link, so a reader +//! sees one or the other, never a mix. + +use std::fs::File; +use std::os::unix::fs::DirBuilderExt; +use std::path::{Path, PathBuf}; + +use anyhow::{Context, Result, bail}; +use serde::{Deserialize, Serialize}; + +use crate::content::{self, Content}; +use crate::scratch::Scratch; + +pub struct Store { + pub state: PathBuf, + pub run: PathBuf, +} + +#[derive(Debug, Clone)] +pub struct Snapshot { + pub id: String, + pub base: Option, + pub content: Content, + /// The schema it was accepted under, as it was. + pub schema: Vec, +} + +#[derive(Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct SnapshotFile { + id: String, + channel: String, + base: Option, +} + +/// Held while the store is used; released when dropped. +pub struct Lock(#[allow(dead_code)] File); + +impl Store { + /// The store in `state` and `run`, made absolute: programs run in a directory of + /// their own. + pub fn new(state: &Path, run: &Path) -> Self { + let absolute = |path: &Path| std::path::absolute(path).unwrap_or_else(|_| path.to_owned()); + Self { + state: absolute(state), + run: absolute(run), + } + } + + /// Waits for, and takes, the store's lock: one receptor at a time. + pub fn lock(&self) -> Result { + create_dir(&self.state, 0o700)?; + let path = self.state.join("lock"); + let file = File::options() + .create(true) + .truncate(false) + .write(true) + .open(&path) + .with_context(|| format!("opening {}", path.display()))?; + file.lock() + .with_context(|| format!("locking {}", path.display()))?; + Ok(Lock(file)) + } + + /// Where programs get their scratch directories. + pub fn scratch(&self) -> PathBuf { + self.run.join("tmp") + } + + fn channel_dir(&self, channel: &str) -> PathBuf { + self.state.join("channels").join(channel) + } + + /// The channels that have a snapshot. + pub fn channels(&self) -> Result> { + let dir = self.state.join("channels"); + let mut channels = Vec::new(); + match std::fs::read_dir(&dir) { + Ok(entries) => { + for entry in entries { + if let Ok(name) = entry?.file_name().into_string() { + channels.push(name); + } + } + } + Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} + Err(error) => return Err(error).with_context(|| format!("reading {}", dir.display())), + } + channels.sort(); + Ok(channels) + } + + /// The current snapshot of `channel`, if there is one. + pub fn current(&self, channel: &str) -> Result> { + let link = self.channel_dir(channel).join("current"); + let target = match std::fs::read_link(&link) { + Ok(target) => target, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None), + Err(error) => return Err(error).with_context(|| format!("reading {}", link.display())), + }; + let dir = self.channel_dir(channel).join(target); + let path = dir.join("snapshot.json"); + let file: SnapshotFile = serde_json::from_slice( + &std::fs::read(&path).with_context(|| format!("reading {}", path.display()))?, + ) + .with_context(|| format!("reading {}", path.display()))?; + if file.channel != channel { + bail!("{} is of channel {}", path.display(), file.channel); + } + let schema = std::fs::read(dir.join("schema.json")) + .with_context(|| format!("reading {}", dir.join("schema.json").display()))?; + Ok(Some(Snapshot { + id: file.id, + base: file.base, + content: content::read_dir(&dir.join("entries"))?, + schema, + })) + } + + /// Makes `content` the current snapshot of `channel`, accepted under `schema`, + /// built on `base`; returns its id. The snapshot it replaces is removed. + pub fn commit( + &self, + channel: &str, + content: &Content, + base: Option<&str>, + schema: &[u8], + ) -> Result { + let id = crate::new_id()?; + let snapshots = self.channel_dir(channel).join("snapshots"); + create_dir(&snapshots, 0o700)?; + let new = snapshots.join(format!(".{id}.new")); + create_dir(&new, 0o700)?; + let file = SnapshotFile { + id: id.clone(), + channel: channel.to_owned(), + base: base.map(str::to_owned), + }; + content::write_file( + &new.join("snapshot.json"), + &serde_json::to_vec_pretty(&file)?, + 0o600, + )?; + content::write_file(&new.join("schema.json"), schema, 0o600)?; + content::write_dir(content, &new.join("entries"), 0o600)?; + std::fs::rename(&new, snapshots.join(&id))?; + let old = std::fs::read_link(self.channel_dir(channel).join("current")).ok(); + replace_link( + &self.channel_dir(channel).join("current"), + &Path::new("snapshots").join(&id), + )?; + if let Some(old) = old { + std::fs::remove_dir_all(self.channel_dir(channel).join(old))?; + } + Ok(id) + } + + /// The directory the view `name` is in place at, if it is. + pub fn installed_view(&self, name: &str) -> Option { + let link = self.run.join("views").join(name); + std::fs::read_link(&link).ok()?; + Some(link) + } + + /// Puts what was rendered for the view `name` in place (or, if nothing was, takes + /// it away), readable by root only if it is secret. + pub fn install_view(&self, name: &str, rendered: Option, secret: bool) -> Result<()> { + let views = self.run.join("views"); + create_dir(&views, 0o755)?; + let link = views.join(name); + let old = std::fs::read_link(&link).ok(); + match rendered { + Some(rendered) => { + let generations = views.join(".generations"); + create_dir(&generations, 0o755)?; + let mode = if secret { 0o600 } else { 0o644 }; + rendered.set_modes(mode)?; + let target = Path::new(".generations").join(format!("{name}.{}", crate::new_id()?)); + std::fs::rename(rendered.path(), views.join(&target)) + .with_context(|| format!("moving view {name} in place"))?; + rendered.keep(); + replace_link(&link, &target)?; + } + None => { + if old.is_some() { + std::fs::remove_file(&link)?; + } + } + } + if let Some(old) = old { + std::fs::remove_dir_all(views.join(old))?; + } + Ok(()) + } +} + +fn create_dir(path: &Path, mode: u32) -> Result<()> { + std::fs::DirBuilder::new() + .recursive(true) + .mode(mode) + .create(path) + .with_context(|| format!("creating {}", path.display())) +} + +/// Points the symbolic link `link` at `target`, atomically. +fn replace_link(link: &Path, target: &Path) -> Result<()> { + let name = link.file_name().unwrap_or_default().to_string_lossy(); + let new = link.with_file_name(format!(".{name}.new-link")); + let _ = std::fs::remove_file(&new); + std::os::unix::fs::symlink(target, &new)?; + std::fs::rename(&new, link).with_context(|| format!("replacing {}", link.display())) +} diff --git a/src/submission.rs b/src/submission.rs new file mode 100644 index 0000000..1958909 --- /dev/null +++ b/src/submission.rs @@ -0,0 +1,219 @@ +//! What gets handed to the host (docs/design.md, 5.4): a directory with a manifest, +//! and the entries and records its items set at `channels/CHANNEL/SLOT`. +//! +//! ```json +//! { +//! "submission": 1, +//! "channel": "fleet", +//! "complete": false, +//! "base": "4f0c…", +//! "items": [ +//! { "address": "fleet/hosts/ne", "op": "set", "group": "ne" }, +//! { "address": "fleet/users/tv", "op": "set", "required": false }, +//! { "address": "fleet/hosts/wu", "op": "remove" } +//! ], +//! "groups": { "ne": { "required": true } } +//! } +//! ``` +//! +//! Items and groups are required unless they say otherwise; an item in a group is as +//! required as its group, and says nothing of its own. An item setting records has +//! them in its entry's file, as an object holding just the records set. + +use std::collections::{BTreeMap, BTreeSet}; +use std::path::{Path, PathBuf}; + +use anyhow::{Context, Result, bail}; +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +use crate::content; +use crate::name::Address; + +pub const VERSION: u32 = 1; +pub const MANIFEST: &str = "manifest.json"; +pub const CHANNELS: &str = "channels"; + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Manifest { + pub submission: u32, + pub channel: String, + #[serde(default)] + pub complete: bool, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub base: Option, + pub items: Vec, + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub groups: BTreeMap, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ItemSpec { + pub address: Address, + pub op: Op, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub required: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub group: Option, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum Op { + Set, + Remove, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct GroupSpec { + #[serde(default = "yes")] + pub required: bool, +} + +fn yes() -> bool { + true +} + +/// A submission, read. +#[derive(Debug, Clone)] +pub struct Submission { + pub dir: PathBuf, + pub channel: String, + pub complete: bool, + pub base: Option, + pub items: Vec, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct Item { + pub address: Address, + pub required: bool, + pub group: Option, + pub change: Change, +} + +#[derive(Debug, Clone, PartialEq)] +pub enum Change { + Entry(Vec), + Record(Value), + Remove, +} + +impl Submission { + pub fn load(dir: &Path) -> Result { + let path = dir.join(MANIFEST); + let bytes = std::fs::read(&path).with_context(|| format!("reading {}", path.display()))?; + let manifest: Manifest = serde_json::from_slice(&bytes) + .with_context(|| format!("manifest {}", path.display()))?; + Self::from_manifest(dir, manifest).with_context(|| format!("submission {}", dir.display())) + } + + fn from_manifest(dir: &Path, manifest: Manifest) -> Result { + if manifest.submission != VERSION { + bail!( + "submission version {} is not {VERSION}", + manifest.submission + ); + } + crate::name::check("channel", &manifest.channel)?; + let files = dir.join(CHANNELS).join(&manifest.channel); + let mut seen: Vec<&Address> = Vec::new(); + let mut used = BTreeSet::new(); + let mut items = Vec::new(); + for spec in &manifest.items { + let address = &spec.address; + if address.channel != manifest.channel { + bail!("item {address} is not of channel {}", manifest.channel); + } + if let Some(other) = seen.iter().find(|other| other.overlaps(address)) { + bail!("items {other} and {address} overlap"); + } + seen.push(address); + let required = match (&spec.group, spec.required) { + (Some(group), None) => match manifest.groups.get(group) { + Some(group) => group.required, + None => bail!("item {address}: no group {group}"), + }, + (Some(_), Some(_)) => { + bail!("item {address} is in a group, which says whether it is required") + } + (None, required) => required.unwrap_or(true), + }; + let change = match (spec.op, &address.key) { + (Op::Remove, _) => Change::Remove, + (Op::Set, None) => { + used.insert(address.slot.clone()); + let path = files.join(&address.slot); + Change::Entry( + std::fs::read(&path).with_context(|| { + format!("item {address}: reading {}", path.display()) + })?, + ) + } + (Op::Set, Some(key)) => { + used.insert(address.slot.clone()); + let path = files.join(&address.slot); + let bytes = std::fs::read(&path) + .with_context(|| format!("item {address}: reading {}", path.display()))?; + let records = content::records(&bytes) + .with_context(|| format!("item {address}: {}", path.display()))?; + match records.get(key) { + Some(value) => Change::Record(value.clone()), + None => bail!("item {address}: no record {key:?} in {}", path.display()), + } + } + }; + items.push(Item { + address: address.clone(), + required, + group: spec.group.clone(), + change, + }); + } + // Records a file holds that no item sets, and files no item reads, would be + // handed over and silently ignored. + for slot in &used { + let records_set: BTreeSet<&str> = items + .iter() + .filter(|item| item.address.slot == *slot) + .filter_map(|item| item.address.key.as_deref()) + .collect(); + if records_set.is_empty() { + continue; + } + let path = files.join(slot); + let records = content::records(&std::fs::read(&path)?)?; + if let Some(key) = records + .keys() + .find(|key| !records_set.contains(key.as_str())) + { + bail!( + "{} holds record {key:?}, which no item sets", + path.display() + ); + } + } + for (slot, _) in content::read_dir(&files)? { + if !used.contains(&slot) { + bail!("{} is set by no item", files.join(slot).display()); + } + } + if let Some(group) = manifest + .groups + .keys() + .find(|group| !items.iter().any(|item| item.group.as_ref() == Some(*group))) + { + bail!("group {group} has no items"); + } + Ok(Self { + dir: dir.to_owned(), + channel: manifest.channel, + complete: manifest.complete, + base: manifest.base, + items, + }) + } +} diff --git a/src/view.rs b/src/view.rs new file mode 100644 index 0000000..b7bab6c --- /dev/null +++ b/src/view.rs @@ -0,0 +1,181 @@ +//! Views (docs/design.md, 5.3): rendered into scratch, compared with what is in +//! place, and how they changed. + +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; + +use anyhow::Result; +use serde::Serialize; + +use crate::content::Content; +use crate::name::Address; +use crate::program::{self, Given, Role}; +use crate::schema::{Schema, ViewSpec}; +use crate::scratch::Scratch; + +/// The entries of every channel a view may be made from: the one being planned as it +/// would be, the others as they are. +pub type Entries<'a> = BTreeMap<&'a str, &'a Content>; + +/// Renders the view `name` from `entries` into scratch below `scratch`; nothing if it +/// is an entry's own and that entry isn't there. +pub fn render( + schema: &Schema, + name: &str, + view: &ViewSpec, + entries: &Entries, + scratch: &Path, +) -> Result> { + let entry = |address: &Address| { + entries + .get(address.channel.as_str()) + .and_then(|content| content.get(&address.slot)) + }; + match &view.renderer { + None => { + let address = &view.from[0]; + let Some(bytes) = entry(address) else { + return Ok(None); + }; + let out = Scratch::new(scratch, "view-")?; + crate::content::write_file(&out.path().join(&address.slot), bytes, 0o600)?; + Ok(Some(out)) + } + Some(renderer) => { + let given = Given { + slots: view + .from + .iter() + .map(|address| { + let media_type = schema + .slot(address) + .map(|slot| slot.media_type.as_str()) + .unwrap_or_default(); + ( + address.clone(), + (media_type, entry(address).map(Vec::as_slice)), + ) + }) + .collect(), + }; + let outcome = program::run(renderer, Role::Renderer, name, &given, scratch)?; + // What it can't render, it fails on; and it may write regular files and + // directories only. + program::files_below(outcome.out.path())?; + Ok(Some(outcome.out)) + } + } +} + +/// How a view changes. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +#[serde(rename_all = "lowercase")] +pub enum Change { + Unchanged, + Added, + Removed, + Changed, +} + +/// One file of a view that changes. +#[derive(Debug, Clone, Serialize)] +pub struct FileChange { + pub path: PathBuf, + pub change: Change, + /// As diffutils says it (`diff`). + pub diff: String, +} + +/// How what is in place (`old`) would become what was rendered (`new`): the view as a +/// whole, and its files. A secret view's files are named, but no diff is made. +pub fn compare( + old: Option<&Path>, + new: Option<&Path>, + secret: bool, +) -> Result<(Change, Vec)> { + let read = |dir: Option<&Path>| -> Result>> { + match dir { + Some(dir) => program::files_below(dir), + None => Ok(BTreeMap::new()), + } + }; + let (old_files, new_files) = (read(old)?, read(new)?); + let mut files = Vec::new(); + for (path, bytes) in &new_files { + match old_files.get(path) { + Some(old) if old == bytes => {} + Some(old) => files.push(FileChange { + path: path.clone(), + change: Change::Changed, + diff: diff(path, Some(old), Some(bytes), secret), + }), + None => files.push(FileChange { + path: path.clone(), + change: Change::Added, + diff: diff(path, None, Some(bytes), secret), + }), + } + } + for (path, bytes) in &old_files { + if !new_files.contains_key(path) { + files.push(FileChange { + path: path.clone(), + change: Change::Removed, + diff: diff(path, Some(bytes), None, secret), + }); + } + } + let change = match (old, new) { + (None, None) => Change::Unchanged, + (None, Some(_)) => Change::Added, + (Some(_), None) => Change::Removed, + (Some(_), Some(_)) if files.is_empty() => Change::Unchanged, + (Some(_), Some(_)) => Change::Changed, + }; + Ok((change, files)) +} + +/// How a file changes, as diffutils' `diff -ru a b` says it: a unified diff for text in +/// a public view; for a secret view, or bytes that aren't text, only that the file +/// differs, or is only on one side. +fn diff(path: &Path, old: Option<&[u8]>, new: Option<&[u8]>, secret: bool) -> String { + let name = path.display().to_string(); + let text = |bytes: Option<&[u8]>| match bytes { + None => Some(String::new()), + Some(bytes) => std::str::from_utf8(bytes).ok().map(str::to_owned), + }; + let (old_text, new_text) = (text(old), text(new)); + match (old_text, new_text) { + (Some(old), Some(new)) if !secret => similar::TextDiff::from_lines(&old, &new) + .unified_diff() + .header(&format!("a/{name}"), &format!("b/{name}")) + .to_string(), + _ => match (old, new) { + (None, _) => format!("Only in b: {name}\n"), + (_, None) => format!("Only in a: {name}\n"), + _ if secret => format!("Files a/{name} and b/{name} differ\n"), + _ => format!("Binary files a/{name} and b/{name} differ\n"), + }, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn diffs_as_diffutils_says_them() { + let path = Path::new("f"); + assert_eq!( + diff(path, Some(b"a\n"), Some(b"b\n"), true), + "Files a/f and b/f differ\n" + ); + assert_eq!( + diff(path, Some(b"\xff"), Some(b"\xfe"), false), + "Binary files a/f and b/f differ\n" + ); + assert_eq!(diff(path, None, Some(b"k"), true), "Only in b: f\n"); + assert_eq!(diff(path, Some(b"\xff"), None, false), "Only in a: f\n"); + assert!(diff(path, Some(b"a\n"), Some(b"b\n"), false).contains("-a\n+b\n")); + } +} diff --git a/tests/receptor.rs b/tests/receptor.rs new file mode 100644 index 0000000..496140b --- /dev/null +++ b/tests/receptor.rs @@ -0,0 +1,651 @@ +//! The receptor and the provider on directories: plans, applies, refusals, views, +//! reactions, packing, materializing, and the command line. Validators and renderers +//! are shell scripts. + +use std::os::unix::fs::PermissionsExt; +use std::path::{Path, PathBuf}; +use std::process::Command; + +use enstate::plan::{self, Plan}; +use enstate::schema::Schema; +use enstate::store::Store; +use enstate::submission::Submission; +use enstate::view::Change; +use serde_json::{Value, json}; + +struct Host { + root: PathBuf, +} + +impl Host { + fn new(name: &str) -> Self { + let root = Path::new(env!("CARGO_TARGET_TMPDIR")) + .join("receptor") + .join(name); + let _ = std::fs::remove_dir_all(&root); + std::fs::create_dir_all(root.join("programs")).unwrap(); + Self { root } + } + + fn store(&self) -> Store { + Store::new(&self.root.join("state"), &self.root.join("run")) + } + + /// A shell script, with the tests' PATH (programs get an empty environment). + fn program(&self, name: &str, body: &str) -> String { + let path = self.root.join("programs").join(name); + let script = format!( + "#!/bin/sh\nPATH={}\nset -eu\n{body}\n", + std::env::var("PATH").unwrap() + ); + std::fs::write(&path, script).unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap(); + path.display().to_string() + } + + fn schema(&self, schema: Value) -> (Schema, Vec) { + let bytes = serde_json::to_vec_pretty(&schema).unwrap(); + std::fs::write(self.root.join("schema.json"), &bytes).unwrap(); + (Schema::from_slice(&bytes).unwrap(), bytes) + } + + /// A submission named `name`: its manifest, and files below `channels/`. + fn submission(&self, name: &str, manifest: Value, files: &[(&str, &[u8])]) -> PathBuf { + let dir = self.root.join("submissions").join(name); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let mut manifest = manifest; + manifest["submission"] = json!(1); + std::fs::write(dir.join("manifest.json"), manifest.to_string()).unwrap(); + for (path, bytes) in files { + let path = dir.join("channels").join(path); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, bytes).unwrap(); + } + dir + } + + fn plan(&self, schema: &Schema, dir: &Path) -> Plan { + let submission = Submission::load(dir).unwrap(); + plan::plan(schema, &self.store(), &submission).unwrap().plan + } + + fn apply(&self, schema: &(Schema, Vec), dir: &Path) -> Plan { + let submission = Submission::load(dir).unwrap(); + let store = self.store(); + let _lock = store.lock().unwrap(); + plan::plan(&schema.0, &store, &submission) + .unwrap() + .apply(&store, &schema.1, &self.systemctl()) + .unwrap() + } + + /// A systemctl that writes down what it was asked. + fn systemctl(&self) -> PathBuf { + let log = self.root.join("systemctl.log"); + PathBuf::from(self.program("systemctl", &format!("echo \"$*\" >> {}", log.display()))) + } + + fn reactions(&self) -> String { + std::fs::read_to_string(self.root.join("systemctl.log")).unwrap_or_default() + } + + fn view(&self, view: &str, file: &str) -> Option> { + std::fs::read(self.root.join("run/views").join(view).join(file)).ok() + } + + fn mode(&self, view: &str, file: &str) -> u32 { + std::fs::metadata(self.root.join("run/views").join(view).join(file)) + .unwrap() + .permissions() + .mode() + & 0o777 + } +} + +/// A host's secrets: a key, its public half, an optional extra; a validator across +/// the key pair; each entry its own view, the key restarting a service. +fn secrets_schema(host: &Host) -> Value { + let pair = host.program( + "pair", + r#"key=$(cat "$1/channels/secrets/a.key") +pub=$(cat "$1/channels/secrets/a.pub") +if [ "$pub" != "pub-of-$key" ]; then + echo '{"address": "secrets/a.pub", "message": "does not belong to secrets/a.key"}' +fi"#, + ); + let opaque = host.program( + "opaque", + r#"if grep -q broken "$1/channels/secrets/extra"; then + echo '{"address": "secrets/extra", "message": "broken"}' +fi"#, + ); + json!({ + "schema": 1, + "types": { "application/x-test-extra": { "validator": opaque } }, + "channels": { "secrets": { "slots": { + "a.key": { "type": "application/octet-stream", "secret": true }, + "a.pub": { "type": "application/octet-stream" }, + "extra": { "type": "application/x-test-extra", "required": false } + } } }, + "validators": { "pair": { "slots": ["secrets/a.key", "secrets/a.pub"], "program": pair } }, + "views": { + "a.key": { "from": ["secrets/a.key"], "reactions": { "restart": ["svc.service"] } }, + "a.pub": { "from": ["secrets/a.pub"], "reactions": { "reload": ["svc.service", "other.service"] } } + } + }) +} + +fn complete(items: &[(&str, &str)]) -> Value { + json!({ + "channel": "secrets", + "complete": true, + "items": items.iter().map(|(address, op)| json!({"address": address, "op": op})).collect::>() + }) +} + +#[test] +fn apply_rotate_and_nothing_to_change() { + let host = Host::new("rotate"); + let schema = host.schema(secrets_schema(&host)); + let first = host.submission( + "first", + complete(&[("secrets/a.key", "set"), ("secrets/a.pub", "set")]), + &[("secrets/a.key", b"K\n"), ("secrets/a.pub", b"pub-of-K\n")], + ); + let plan = host.apply(&schema, &first); + assert!(plan.accepted, "{plan:?}"); + let id = plan.snapshot.clone().unwrap(); + assert_eq!(host.view("a.key", "a.key").unwrap(), b"K\n"); + assert_eq!(host.mode("a.key", "a.key"), 0o600); + assert_eq!(host.mode("a.pub", "a.pub"), 0o644); + // A unit both restarted and reloaded is restarted. + assert_eq!( + host.reactions(), + "restart svc.service\nreload other.service\n" + ); + + // The same again changes nothing: no new snapshot, no reactions. + let again = host.submission( + "again", + complete(&[("secrets/a.key", "set"), ("secrets/a.pub", "set")]), + &[("secrets/a.key", b"K\n"), ("secrets/a.pub", b"pub-of-K\n")], + ); + let plan = host.apply(&schema, &again); + assert!( + plan.accepted && !plan.changes && plan.snapshot.is_none(), + "{plan:?}" + ); + assert_eq!(host.store().current("secrets").unwrap().unwrap().id, id); + + // Rotating, building on the current snapshot: the views change, the secret one + // saying only that it differs. + let rotate = host.submission( + "rotate", + json!({ + "channel": "secrets", + "base": id, + "items": [ + { "address": "secrets/a.key", "op": "set", "group": "pair" }, + { "address": "secrets/a.pub", "op": "set", "group": "pair" } + ], + "groups": { "pair": {} } + }), + &[("secrets/a.key", b"L\n"), ("secrets/a.pub", b"pub-of-L\n")], + ); + let plan = host.plan(&schema.0, &rotate); + assert!(plan.accepted && plan.changes); + let key = plan.views.iter().find(|view| view.name == "a.key").unwrap(); + assert!(key.secret && key.change == Change::Changed); + assert_eq!(key.files[0].diff, "Files a/a.key and b/a.key differ\n"); + let public = plan.views.iter().find(|view| view.name == "a.pub").unwrap(); + assert!(public.files[0].diff.contains("+pub-of-L")); + // A plan changes nothing. + assert_eq!(host.view("a.key", "a.key").unwrap(), b"K\n"); + let plan = host.apply(&schema, &rotate); + assert_eq!(plan.current.as_deref(), Some(id.as_str())); + assert_eq!(host.view("a.key", "a.key").unwrap(), b"L\n"); + let snapshot = host.store().current("secrets").unwrap().unwrap(); + assert_eq!(snapshot.base.as_deref(), Some(id.as_str())); + assert_eq!(snapshot.schema, schema.1); + + // Building on a snapshot that is no longer current is refused. + let stale = host.apply(&schema, &rotate); + assert!(!stale.accepted); + assert!(stale.refused[0].contains("builds on"), "{stale:?}"); +} + +#[test] +fn refusals_and_what_is_left_out() { + let host = Host::new("refusals"); + let schema = host.schema(secrets_schema(&host)); + // A required slot unfilled. + let missing = host.submission( + "missing", + complete(&[("secrets/a.key", "set")]), + &[("secrets/a.key", b"K")], + ); + let plan = host.apply(&schema, &missing); + assert!(!plan.accepted); + assert!( + plan.refused + .iter() + .any(|reason| reason.contains("required slot secrets/a.pub is unfilled")), + "{plan:?}" + ); + assert!(host.store().current("secrets").unwrap().is_none()); + assert!(host.view("a.key", "a.key").is_none()); + + // The validator across slots objects to a required item. + let mismatch = host.submission( + "mismatch", + complete(&[("secrets/a.key", "set"), ("secrets/a.pub", "set")]), + &[("secrets/a.key", b"K"), ("secrets/a.pub", b"pub-of-X")], + ); + let plan = host.apply(&schema, &mismatch); + assert!(!plan.accepted); + assert!(plan.refused[0].contains("does not belong"), "{plan:?}"); + + // An optional item the type's validator objects to is left out, with a warning. + let manifest = json!({ + "channel": "secrets", + "complete": true, + "items": [ + { "address": "secrets/a.key", "op": "set" }, + { "address": "secrets/a.pub", "op": "set" }, + { "address": "secrets/extra", "op": "set", "required": false } + ] + }); + let optional = host.submission( + "optional", + manifest.clone(), + &[ + ("secrets/a.key", b"K"), + ("secrets/a.pub", b"pub-of-K"), + ("secrets/extra", b"broken"), + ], + ); + let plan = host.apply(&schema, &optional); + assert!(plan.accepted, "{plan:?}"); + assert!(!plan.items[2].goes_in && plan.items[0].goes_in); + assert!( + plan.warnings[0].contains("left out: secrets/extra: secrets/extra: broken"), + "{plan:?}" + ); + assert!( + !host + .store() + .current("secrets") + .unwrap() + .unwrap() + .content + .contains_key("extra") + ); + + // In an optional group, neither goes in. + let grouped = host.submission( + "grouped", + json!({ + "channel": "secrets", + "items": [ + { "address": "secrets/a.pub", "op": "set", "group": "g" }, + { "address": "secrets/extra", "op": "set", "group": "g" } + ], + "groups": { "g": { "required": false } } + }), + &[ + ("secrets/a.pub", b"pub-of-K2"), + ("secrets/extra", b"broken"), + ], + ); + let plan = host.plan(&schema.0, &grouped); + assert!(plan.accepted && !plan.changes, "{plan:?}"); + assert!(plan.items.iter().all(|item| !item.goes_in)); + assert!(plan.items[0].reasons[0].contains("its group g"), "{plan:?}"); + + // A required removal of a required entry is refused; an optional one left out. + let remove = |required: bool| { + host.submission( + &format!("remove-{required}"), + json!({ + "channel": "secrets", + "items": [{ "address": "secrets/a.pub", "op": "remove", "required": required }] + }), + &[], + ) + }; + let plan = host.plan(&schema.0, &remove(true)); + assert!( + !plan.accepted && plan.refused[0].contains("would be unfilled"), + "{plan:?}" + ); + let plan = host.plan(&schema.0, &remove(false)); + assert!( + plan.accepted && !plan.changes && !plan.items[0].goes_in, + "{plan:?}" + ); + + // An objection to what is in place, which no item touches, refuses. + let host2 = Host::new("in-place"); + let schema2 = host2.schema(secrets_schema(&host2)); + let store = host2.store(); + store + .commit( + "secrets", + &[ + ("a.key".to_owned(), b"K".to_vec()), + ("a.pub".to_owned(), b"pub-of-K".to_vec()), + ("extra".to_owned(), b"broken".to_vec()), + ] + .into(), + None, + &schema2.1, + ) + .unwrap(); + let rotate = host2.submission( + "rotate", + json!({ "channel": "secrets", "items": [ + { "address": "secrets/a.key", "op": "set" }, + { "address": "secrets/a.pub", "op": "set" } + ] }), + &[("secrets/a.key", b"L"), ("secrets/a.pub", b"pub-of-L")], + ); + let plan = host2.plan(&schema2.0, &rotate); + assert!( + !plan.accepted && plan.refused[0].contains("objection to what is in place"), + "{plan:?}" + ); + + // A validator that fails refuses, naming it, blaming no item. + let host3 = Host::new("failing"); + let mut failing = secrets_schema(&host3); + failing["validators"]["pair"]["program"] = + json!(host3.program("fail", "echo oops >&2; exit 3")); + let schema3 = host3.schema(failing); + let first = host3.submission( + "first", + complete(&[("secrets/a.key", "set"), ("secrets/a.pub", "set")]), + &[("secrets/a.key", b"K"), ("secrets/a.pub", b"pub-of-K")], + ); + let plan = host3.plan(&schema3.0, &first); + assert!(!plan.accepted); + assert!( + plan.refused[0].contains("validator pair") && plan.refused[0].contains("oops"), + "{plan:?}" + ); +} + +/// The fleet's hosts, records in one keyed entry: a validator naming records, a +/// renderer making known hosts. +fn fleet_schema(host: &Host) -> Value { + let hosts = host.program( + "hosts", + r#"awk ' + /^ "[^"]+": \{/ { key = $1; gsub(/[":]/, "", key) } + /"addr": "10\.0\.0\.99"/ { printf "{\"address\": \"fleet/hosts/%s\", \"message\": \"address is taken\"}\n", key } +' "$1/channels/fleet/hosts""#, + ); + let render = host.program( + "known-hosts", + r#"awk ' + /^ "[^"]+": \{/ { key = $1; gsub(/[":]/, "", key) } + /"key": / { k = $2; gsub(/[",]/, "", k); print key " ssh-ed25519 " k } +' "$1/channels/fleet/hosts" > "$2/known_hosts" +grep -q '"type": "application/x-hosts+json"' "$1/invocation.json""#, + ); + json!({ + "schema": 1, + "types": { "application/x-hosts+json": { "validator": hosts } }, + "channels": { "fleet": { "slots": { + "hosts": { "type": "application/x-hosts+json" } + } } }, + "views": { "known-hosts": { "from": ["fleet/hosts"], "renderer": render } } + }) +} + +#[test] +fn records_set_removed_rendered() { + let host = Host::new("records"); + let schema = host.schema(fleet_schema(&host)); + let add = |name: &str, records: Value, items: Value| { + host.submission( + name, + json!({ "channel": "fleet", "items": items }), + &[("fleet/hosts", records.to_string().as_bytes())], + ) + }; + let first = add( + "first", + json!({ "ne": { "addr": "10.0.0.1", "key": "AAA" }, "xu": { "addr": "10.0.0.2", "key": "BBB" } }), + json!([ + { "address": "fleet/hosts/ne", "op": "set" }, + { "address": "fleet/hosts/xu", "op": "set" } + ]), + ); + let plan = host.apply(&schema, &first); + assert!(plan.accepted, "{plan:?}"); + assert_eq!( + String::from_utf8(host.view("known-hosts", "known_hosts").unwrap()).unwrap(), + "ne ssh-ed25519 AAA\nxu ssh-ed25519 BBB\n" + ); + // A taken address, optional: left out; the other record goes in. + let second = add( + "second", + json!({ "wu": { "addr": "10.0.0.99", "key": "CCC" }, "ni": { "addr": "10.0.0.4", "key": "DDD" } }), + json!([ + { "address": "fleet/hosts/wu", "op": "set", "required": false }, + { "address": "fleet/hosts/ni", "op": "set" } + ]), + ); + let plan = host.apply(&schema, &second); + assert!(plan.accepted, "{plan:?}"); + assert!( + plan.warnings[0].contains("fleet/hosts/wu: address is taken"), + "{plan:?}" + ); + let diff = plan.views[0].files[0].diff.clone(); + assert!( + diff.contains("+ni ssh-ed25519 DDD") && !diff.contains("wu"), + "{diff}" + ); + // Removing a record. + let remove = host.submission( + "remove", + json!({ "channel": "fleet", "items": [{ "address": "fleet/hosts/xu", "op": "remove" }] }), + &[], + ); + let plan = host.apply(&schema, &remove); + assert!(plan.accepted, "{plan:?}"); + assert_eq!( + String::from_utf8(host.view("known-hosts", "known_hosts").unwrap()).unwrap(), + "ne ssh-ed25519 AAA\nni ssh-ed25519 DDD\n" + ); + // A record in a slot whose type holds none can't go in; a record the file holds + // but no item sets is a mistake. + let stray = host.submission( + "stray", + json!({ "channel": "fleet", "items": [{ "address": "fleet/hosts/ne", "op": "set" }] }), + &[("fleet/hosts", br#"{"ne": {}, "xx": {}}"#)], + ); + let error = Submission::load(&stray).unwrap_err(); + assert!(format!("{error:#}").contains("no item sets"), "{error:#}"); +} + +#[test] +fn materialize_after_boot_and_switch() { + let host = Host::new("materialize"); + let schema = host.schema(secrets_schema(&host)); + let first = host.submission( + "first", + complete(&[("secrets/a.key", "set"), ("secrets/a.pub", "set")]), + &[("secrets/a.key", b"K"), ("secrets/a.pub", b"pub-of-K")], + ); + assert!(host.apply(&schema, &first).accepted); + // Boot: /run is empty. + std::fs::remove_dir_all(host.root.join("run")).unwrap(); + let views = plan::materialize(&schema.0, &host.store()).unwrap(); + assert!( + views.iter().all(|view| view.change == Change::Added), + "{views:?}" + ); + assert_eq!(host.view("a.key", "a.key").unwrap(), b"K"); + // A generation without the view a.pub: it goes. + let mut fewer = secrets_schema(&host); + fewer["views"].as_object_mut().unwrap().remove("a.pub"); + let fewer = host.schema(fewer); + let views = plan::materialize(&fewer.0, &host.store()).unwrap(); + assert!( + views + .iter() + .any(|view| view.name == "a.pub" && view.change == Change::Removed) + ); + assert!(host.view("a.pub", "a.pub").is_none()); + assert!(host.view("a.key", "a.key").is_some()); +} + +#[test] +fn pack_from_sources() { + let host = Host::new("pack"); + let schema = host.schema(secrets_schema(&host)); + std::fs::write(host.root.join("key"), b"K\n\n").unwrap(); + std::fs::write(host.root.join("ne.json"), br#"{"addr": "10.0.0.1"}"#).unwrap(); + let lister = host.program("secrets", r#"printf 'pub-of-%s\n\n' "$2""#); + let list = json!({ + "channel": "secrets", + "complete": true, + "items": { + "a.key": { "source": { "file": "key" } }, + "a.pub": { "source": { "command": [lister, "show", "${file:key}"] } }, + } + }); + let path = host.root.join("sources.json"); + std::fs::write(&path, list.to_string()).unwrap(); + let out = host.root.join("packed"); + enstate::pack::pack(&path, &out, Some(&schema.0)).unwrap(); + // Byte-exact entries: trailing line breaks stay. + assert_eq!( + std::fs::read(out.join("channels/secrets/a.key")).unwrap(), + b"K\n\n" + ); + assert_eq!( + std::fs::read(out.join("channels/secrets/a.pub")).unwrap(), + b"pub-of-K\n\n" + ); + // The pair validator compares without trailing line breaks ($(cat)). + let plan = host.apply(&schema, &out); + assert!(plan.accepted, "{plan:?}"); + // Not into a directory that holds something. + assert!(enstate::pack::pack(&path, &out, None).is_err()); + + // TOML, records, a shell command with a nested placeholder, removal; checked + // against a schema. + let fleet = host.schema(fleet_schema(&host)); + let toml = r#"channel = "fleet" +[items."hosts/ne"] +source = { file = "ne.json" } +[items."hosts/xu"] +source = 'cmd:printf "%s" "{\"addr\": \"${env:ADDR}\"}"' +[items."hosts/wu"] +remove = true +"#; + let path = host.root.join("fleet.toml"); + std::fs::write(&path, toml).unwrap(); + // SAFETY: the tests here don't read the environment concurrently. + unsafe { std::env::set_var("ADDR", "10.0.0.2; touch injected") }; + let out = host.root.join("fleet-packed"); + enstate::pack::pack(&path, &out, Some(&fleet.0)).unwrap(); + assert!(!host.root.join("injected").exists()); + let submission = Submission::load(&out).unwrap(); + assert_eq!(submission.items.len(), 3); + let records: Value = + serde_json::from_slice(&std::fs::read(out.join("channels/fleet/hosts")).unwrap()).unwrap(); + assert_eq!(records["xu"]["addr"], json!("10.0.0.2; touch injected")); + assert_eq!(records["ne"]["addr"], json!("10.0.0.1")); + // A slot the schema doesn't have. + let bad = host.root.join("bad.json"); + std::fs::write( + &bad, + json!({"channel": "fleet", "items": {"nope": {"source": "env:ADDR"}}}).to_string(), + ) + .unwrap(); + let error = enstate::pack::pack(&bad, &host.root.join("bad-out"), Some(&fleet.0)).unwrap_err(); + assert!( + error.to_string().contains("no slot fleet/nope"), + "{error:#}" + ); +} + +#[test] +fn command_line() { + let host = Host::new("cli"); + let _ = host.schema(secrets_schema(&host)); + let enstate = |arguments: &[&str]| { + let output = Command::new(env!("CARGO_BIN_EXE_enstate")) + .args(arguments) + .arg(format!("--state-dir={}", host.root.join("state").display())) + .arg(format!("--run-dir={}", host.root.join("run").display())) + .arg(format!( + "--schema={}", + host.root.join("schema.json").display() + )) + .arg(format!("--systemctl={}", host.systemctl().display())) + .output() + .unwrap(); + ( + output.status.code(), + String::from_utf8_lossy(&output.stdout).into_owned(), + String::from_utf8_lossy(&output.stderr).into_owned(), + ) + }; + let missing = host.submission( + "missing", + complete(&[("secrets/a.key", "set")]), + &[("secrets/a.key", b"K")], + ); + let missing = missing.to_str().unwrap(); + let (code, stdout, _) = enstate(&[missing, "--plan"]); + assert_eq!(code, Some(1)); + assert!( + stdout.contains("refused") && stdout.contains("secrets/a.pub"), + "{stdout}" + ); + let good = host.submission( + "good", + complete(&[("secrets/a.key", "set"), ("secrets/a.pub", "set")]), + &[("secrets/a.key", b"K"), ("secrets/a.pub", b"pub-of-K")], + ); + let (code, stdout, stderr) = enstate(&["--apply", "--json", good.to_str().unwrap()]); + assert_eq!(code, Some(0), "{stderr}"); + let plan: Value = serde_json::from_str(&stdout).unwrap(); + assert_eq!(plan["accepted"], json!(true)); + let (code, stdout, _) = enstate(&["--status"]); + assert_eq!(code, Some(0)); + assert!( + stdout.contains("filled a.key") && stdout.contains("view a.key: in place"), + "{stdout}" + ); + // Options not for the command, and two commands. + let (code, _, stderr) = enstate(&["--status", "--out", "x"]); + assert_eq!(code, Some(2)); + assert!(stderr.contains("--out is for --pack only"), "{stderr}"); + let (code, _, _) = enstate(&["--status", "--plan"]); + assert_eq!(code, Some(2)); + let (code, _, stderr) = enstate(&["--status", missing]); + assert_eq!(code, Some(2)); + assert!(stderr.contains("takes no PATH"), "{stderr}"); + // Relative paths: programs run in a directory of their own, and still find theirs. + let output = Command::new(env!("CARGO_BIN_EXE_enstate")) + .current_dir(&host.root) + .args([ + "--plan", + "submissions/good", + "--state-dir=state", + "--run-dir=run", + "--schema=schema.json", + ]) + .output() + .unwrap(); + let stdout = String::from_utf8_lossy(&output.stdout); + assert_eq!(output.status.code(), Some(0), "{stdout}"); + assert!(stdout.contains("nothing changes"), "{stdout}"); +} -- cgit v1.3.1