//! The receptor and the provider on directories: plans, applies, refusals, views, //! reactions, packing, materializing, and the command line. Validators and renderers //! are shell scripts. mod common; use std::process::Command; use common::Host; use enstate::submission::Submission; use enstate::view::Change; use serde_json::{Value, json}; /// 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-or-restart other.service\n" ); // With the lock released: a unit restarted may want the one that runs --migrate. assert_eq!(host.locks(), "free\nfree\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(), &Default::default(), 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 = enstate::migrate::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 = enstate::migrate::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}"] } }, // A placeholder in parentheses, as a whole value: text, its trailing line // breaks removed. "extra": { "source": format!("$(cmd: {lister} show extra)") }, } }); let path = host.root.join("sources.json"); std::fs::write(&path, list.to_string()).unwrap(); let out = host.root.join("packed"); let warnings = enstate::pack::pack(&path, &out, Some(&schema.0)).unwrap(); assert_eq!(warnings.len(), 1, "{warnings:?}"); assert!(warnings[0].starts_with("item secrets/extra: its source is text with placeholders")); // 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" ); assert_eq!( std::fs::read(out.join("channels/secrets/extra")).unwrap(), b"pub-of-extra" ); // 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)); // With the unit that runs --migrate named: started again if it failed (the fake // systemctl says it did). assert!(!host.reactions().contains("is-failed")); let (code, _, stderr) = enstate(&["--apply", good.to_str().unwrap(), "--unit=enstate.service"]); assert_eq!(code, Some(0), "{stderr}"); assert!( host.reactions() .contains("is-failed --quiet enstate.service\nstart --no-block enstate.service\n"), "{}", host.reactions() ); 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}"); }