diff options
Diffstat (limited to 'tests')
| -rw-r--r-- | tests/common/mod.rs | 121 | ||||
| -rw-r--r-- | tests/migrations.rs | 247 | ||||
| -rw-r--r-- | tests/receptor.rs | 103 |
3 files changed, 374 insertions, 97 deletions
diff --git a/tests/common/mod.rs b/tests/common/mod.rs new file mode 100644 index 0000000..751d809 --- /dev/null +++ b/tests/common/mod.rs @@ -0,0 +1,121 @@ +//! A host on directories, for the tests: its store, programs as shell scripts, +//! schemas, submissions, and what its views and reactions are. + +#![allow(dead_code)] + +use std::os::unix::fs::PermissionsExt; +use std::path::{Path, PathBuf}; + +use enstate::migrate::Migration; +use enstate::plan::{self, Plan}; +use enstate::schema::Schema; +use enstate::store::Store; +use enstate::submission::Submission; +use serde_json::{Value, json}; + +pub struct Host { + pub root: PathBuf, +} + +impl Host { + pub 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 } + } + + pub 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). + pub 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() + } + + pub fn schema(&self, schema: Value) -> (Schema, Vec<u8>) { + 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/`. + pub 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 + } + + pub fn plan(&self, schema: &Schema, dir: &Path) -> Plan { + let submission = Submission::load(dir).unwrap(); + plan::plan(schema, &self.store(), &submission).unwrap().plan + } + + pub fn apply(&self, schema: &(Schema, Vec<u8>), 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. + pub fn systemctl(&self) -> PathBuf { + let log = self.root.join("systemctl.log"); + PathBuf::from(self.program("systemctl", &format!("echo \"$*\" >> {}", log.display()))) + } + + pub fn reactions(&self) -> String { + std::fs::read_to_string(self.root.join("systemctl.log")).unwrap_or_default() + } + + pub fn view(&self, view: &str, file: &str) -> Option<Vec<u8>> { + std::fs::read(self.root.join("run/views").join(view).join(file)).ok() + } + + pub fn mode(&self, view: &str, file: &str) -> u32 { + std::fs::metadata(self.root.join("run/views").join(view).join(file)) + .unwrap() + .permissions() + .mode() + & 0o777 + } +} + +impl Host { + /// Serves the generation of `schema` from the snapshots, or says what that would do. + pub fn migrate(&self, schema: &(Schema, Vec<u8>), dry_run: bool) -> Migration { + let store = self.store(); + let _lock = store.lock().unwrap(); + enstate::migrate::migrate(&schema.0, &store, dry_run, &self.systemctl()).unwrap() + } + + /// The current snapshot's id of `channel`. + pub fn snapshot(&self, channel: &str) -> Option<String> { + self.store() + .current(channel) + .unwrap() + .map(|snapshot| snapshot.id) + } +} diff --git a/tests/migrations.rs b/tests/migrations.rs new file mode 100644 index 0000000..7b78b8e --- /dev/null +++ b/tests/migrations.rs @@ -0,0 +1,247 @@ +//! The cases of docs/migrations.md, as far as the first version goes: a renamed slot +//! and a rollback across it, a type that changes without a converter, and what is +//! kept. G1 and G2 are generations, S1 and S2 their schemas. + +mod common; + +use common::Host; +use enstate::view::Change; +use serde_json::{Value, json}; + +fn secrets(slots: Value, views: Value) -> Value { + json!({ "schema": 1, "channels": { "secrets": { "slots": slots } }, "views": views }) +} + +fn rotate(host: &Host, name: &str, slot: &str, bytes: &[u8]) -> std::path::PathBuf { + let address = format!("secrets/{slot}"); + host.submission( + name, + json!({ "channel": "secrets", "items": [{ "address": address, "op": "set" }] }), + &[(address.as_str(), bytes)], + ) +} + +/// Case 1: S2 renames `tinc.key` to `retiolum.key`. Switching to G2 needs no +/// submission; a rotation under G2 stores the state under S2; rolling back to G1 +/// gives it the rotated key, by S2's rename read backwards. +#[test] +fn a_renamed_slot_and_a_rollback() { + let host = Host::new("rename"); + let s1 = host.schema(secrets( + json!({ "tinc.key": { "type": "application/octet-stream", "secret": true } }), + json!({ "tinc.key": { "from": ["secrets/tinc.key"], "reactions": { "restart": ["tinc.service"] } } }), + )); + let s2_value = secrets( + json!({ "retiolum.key": { "type": "application/octet-stream", "secret": true, "renamedFrom": "tinc.key" } }), + json!({ "retiolum.key": { "from": ["secrets/retiolum.key"], "reactions": { "restart": ["tincr.service"] } } }), + ); + // G1 runs, K submitted. + assert!( + host.apply(&s1, &rotate(&host, "k", "tinc.key", b"K")) + .accepted + ); + let first = host.snapshot("secrets").unwrap(); + + // Before switching to G2: it would see K, under its new name. + let s2 = host.schema(s2_value.clone()); + let migration = host.migrate(&s2, true); + assert!(migration.accepted, "{migration:?}"); + assert!( + migration.channels["secrets"].seen.notes[0] + .contains("secrets/retiolum.key: from secrets/tinc.key, renamed"), + "{migration:?}" + ); + assert!(host.view("tinc.key", "tinc.key").is_some()); + + // Switching: the views follow, the snapshot isn't rewritten. + let migration = host.migrate(&s2, false); + assert!( + migration.accepted && migration.failed.is_empty(), + "{migration:?}" + ); + assert_eq!(host.view("retiolum.key", "retiolum.key").unwrap(), b"K"); + assert!(host.view("tinc.key", "tinc.key").is_none()); + assert!(host.reactions().contains("restart tincr.service")); + let stored = host.store().current("secrets").unwrap().unwrap(); + assert_eq!(stored.id, first); + assert_eq!(stored.schema, s1.1); + + // Rotating under G2 stores the state under S2, and nothing is kept: tinc.key went + // into retiolum.key. + let plan = host.apply(&s2, &rotate(&host, "k2", "retiolum.key", b"K'")); + assert!(plan.accepted && plan.warnings.is_empty(), "{plan:?}"); + let stored = host.store().current("secrets").unwrap().unwrap(); + assert_eq!(stored.schema, s2.1); + assert_eq!(stored.content.keys().collect::<Vec<_>>(), ["retiolum.key"]); + assert!(stored.kept.is_empty()); + + // Rolling back to G1: tinc.key is the rotated key, from S2's rename. + let s1 = host.schema(serde_json::from_slice(&s1.1).unwrap()); + let migration = host.migrate(&s1, false); + assert!(migration.accepted, "{migration:?}"); + assert!( + migration.channels["secrets"].seen.notes[0].contains( + "secrets/tinc.key: from secrets/retiolum.key, which the schema it was accepted under renamed from it" + ), + "{migration:?}" + ); + assert_eq!(host.view("tinc.key", "tinc.key").unwrap(), b"K'"); + assert!(host.view("retiolum.key", "retiolum.key").is_none()); +} + +/// Trying an older generation and back costs nothing: the snapshot stays as it was. +#[test] +fn switching_back_and_forth_rewrites_nothing() { + let host = Host::new("back-and-forth"); + let s1 = host.schema(secrets( + json!({ "a": { "type": "application/octet-stream" } }), + json!({ "a": { "from": ["secrets/a"] } }), + )); + assert!(host.apply(&s1, &rotate(&host, "a", "a", b"A")).accepted); + let id = host.snapshot("secrets").unwrap(); + let s2 = host.schema(secrets( + json!({ "b": { "type": "application/octet-stream", "renamedFrom": "a" } }), + json!({ "b": { "from": ["secrets/b"] } }), + )); + assert!(host.migrate(&s2, false).accepted); + let s1 = host.schema(serde_json::from_slice(&s1.1).unwrap()); + assert!(host.migrate(&s1, false).accepted); + assert!(host.migrate(&s2, false).accepted); + assert_eq!(host.snapshot("secrets").unwrap(), id); + assert_eq!(host.view("b", "b").unwrap(), b"A"); +} + +/// Case 2, without converters (not in the first version): a slot whose type changes +/// can't be filled, so the switch is refused before switching, naming the slot; after +/// a switch anyway (a boot), the views made from it aren't there. +#[test] +fn a_type_without_a_converter() { + let host = Host::new("type"); + let fleet = |media_type: &str| { + json!({ + "schema": 1, + "channels": { "fleet": { "slots": { "hosts": { "type": media_type } } } }, + "views": { "hosts": { "from": ["fleet/hosts"] } } + }) + }; + let s1 = host.schema(fleet("application/x-hosts1+json")); + let first = host.submission( + "first", + json!({ "channel": "fleet", "items": [{ "address": "fleet/hosts/ne", "op": "set" }] }), + &[("fleet/hosts", br#"{"ne": {"addr": "a"}}"#)], + ); + assert!(host.apply(&s1, &first).accepted); + let s2 = host.schema(fleet("application/x-hosts2+json")); + let migration = host.migrate(&s2, true); + assert!(!migration.accepted); + assert_eq!( + migration.refused, + ["required slot fleet/hosts can't be filled"] + ); + assert!( + migration.channels["fleet"].seen.notes[0].contains( + "fleet/hosts: type application/x-hosts1+json is now application/x-hosts2+json, and there is no converter" + ), + "{migration:?}" + ); + // The dry run changed nothing; a switch anyway takes the view away. + assert!(host.view("hosts", "hosts").is_some()); + let migration = host.migrate(&s2, false); + assert!(!migration.accepted); + assert!( + migration + .views + .iter() + .any(|view| view.name == "hosts" && view.change == Change::Removed) + ); + assert!(host.view("hosts", "hosts").is_none()); + // A submission made for S2 fills it, and the old entry goes: it is older. + let fresh = host.submission( + "fresh", + json!({ "channel": "fleet", "items": [{ "address": "fleet/hosts/ne", "op": "set" }] }), + &[("fleet/hosts", br#"{"ne": {"addrs": ["a", "b"]}}"#)], + ); + let plan = host.apply(&s2, &fresh); + assert!(plan.accepted, "{plan:?}"); + assert_eq!( + plan.warnings, + [ + "goes, as fleet/hosts is filled anew: the entry of type application/x-hosts1+json kept from before" + ] + ); + assert!(host.view("hosts", "hosts").is_some()); + // Back to G1 is refused before switching: nothing in S2 makes S1's type. + let s1 = host.schema(serde_json::from_slice(&s1.1).unwrap()); + let migration = host.migrate(&s1, true); + assert_eq!( + migration.refused, + ["required slot fleet/hosts can't be filled"] + ); + assert!(migration.channels["fleet"].seen.notes[0].contains("is now application/x-hosts1+json")); +} + +/// What no slot wants is kept, and fills its slot again after a rollback; a complete +/// submission lets it go. +#[test] +fn what_is_kept() { + let host = Host::new("kept"); + let both = secrets( + json!({ + "a": { "type": "application/octet-stream" }, + "extra": { "type": "application/octet-stream", "required": false } + }), + json!({ "extra": { "from": ["secrets/extra"] } }), + ); + let s1 = host.schema(both.clone()); + let first = host.submission( + "first", + json!({ "channel": "secrets", "complete": true, "items": [ + { "address": "secrets/a", "op": "set" }, + { "address": "secrets/extra", "op": "set" } + ] }), + &[("secrets/a", b"A"), ("secrets/extra", b"E")], + ); + assert!(host.apply(&s1, &first).accepted); + let s2 = host.schema(secrets( + json!({ "a": { "type": "application/octet-stream" } }), + json!({}), + )); + let migration = host.migrate(&s2, false); + assert_eq!(migration.channels["secrets"].kept, ["extra"]); + assert!(host.view("extra", "extra").is_none()); + let plan = host.apply(&s2, &rotate(&host, "a2", "a", b"A2")); + assert_eq!( + plan.warnings, + ["kept, in no slot of the schema: secrets/extra"] + ); + let stored = host.store().current("secrets").unwrap().unwrap(); + assert_eq!(stored.kept["extra"].1, b"E"); + // Back to G1: extra is there again. + let s1 = host.schema(both); + let migration = host.migrate(&s1, false); + assert!(migration.channels["secrets"].seen.notes[0].contains("from what was kept")); + assert_eq!(host.view("extra", "extra").unwrap(), b"E"); + // Under G2 again, a complete submission lets it go. + let s2 = host.schema(secrets( + json!({ "a": { "type": "application/octet-stream" } }), + json!({}), + )); + let complete = host.submission( + "complete", + json!({ "channel": "secrets", "complete": true, "items": [{ "address": "secrets/a", "op": "set" }] }), + &[("secrets/a", b"A3")], + ); + let plan = host.apply(&s2, &complete); + assert_eq!( + plan.warnings, + ["goes, as the submission is complete: secrets/extra, which was kept"] + ); + assert!( + host.store() + .current("secrets") + .unwrap() + .unwrap() + .kept + .is_empty() + ); +} diff --git a/tests/receptor.rs b/tests/receptor.rs index 496140b..034e2a8 100644 --- a/tests/receptor.rs +++ b/tests/receptor.rs @@ -2,107 +2,15 @@ //! reactions, packing, materializing, and the command line. Validators and renderers //! are shell scripts. -use std::os::unix::fs::PermissionsExt; -use std::path::{Path, PathBuf}; +mod common; + use std::process::Command; -use enstate::plan::{self, Plan}; -use enstate::schema::Schema; -use enstate::store::Store; +use common::Host; 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<u8>) { - 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<u8>), 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<Vec<u8>> { - 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 { @@ -338,6 +246,7 @@ fn refusals_and_what_is_left_out() { ("extra".to_owned(), b"broken".to_vec()), ] .into(), + &Default::default(), None, &schema2.1, ) @@ -483,7 +392,7 @@ fn materialize_after_boot_and_switch() { 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(); + let views = enstate::migrate::materialize(&schema.0, &host.store()).unwrap(); assert!( views.iter().all(|view| view.change == Change::Added), "{views:?}" @@ -493,7 +402,7 @@ fn materialize_after_boot_and_switch() { 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(); + let views = enstate::migrate::materialize(&fewer.0, &host.store()).unwrap(); assert!( views .iter() |
