1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
|
//! 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::<Vec<_>>()
})
}
#[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}"] } },
}
});
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}");
}
|