zenkey-model 0.24.0

zk2 keys and contracts without a Zenoh session: the key grammar, the contract authoring format, canonical form, fingerprints and bundles
Documentation
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
//! The `zk2` binary's exit contract (#618): 0 asked and clean, 1 a finding,
//! 2 no verdict.

use std::path::{Path, PathBuf};
use std::process::Command;

fn spec() -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR")).join("../spec/conformance")
}

fn zk2(args: &[&str]) -> i32 {
    Command::new(env!("CARGO_BIN_EXE_zk2"))
        .args(args)
        .output()
        .expect("runs")
        .status
        .code()
        .expect("exits")
}

fn p(rel: &str) -> String {
    spec().join(rel).display().to_string()
}

#[test]
fn exit_codes() {
    assert_eq!(
        zk2(&["contract", "lint", &p("contracts/ok-minimal.toml")]),
        0
    );
    assert_eq!(
        zk2(&["contract", "lint", &p("contracts/e015-event.toml")]),
        1
    );
    assert_eq!(
        zk2(&["contract", "fingerprint", &p("contracts/ok-kinds.toml")]),
        0
    );
    let c = |case: &str, side: &str| p(&format!("compat/contract/{case}/{side}.toml"));
    assert_eq!(
        zk2(&[
            "contract",
            "compat",
            &c("optional-role-added", "old"),
            &c("optional-role-added", "new")
        ]),
        0
    );
    assert_eq!(
        zk2(&[
            "contract",
            "compat",
            &c("priority-changed", "old"),
            &c("priority-changed", "new")
        ]),
        1
    );
    assert_eq!(
        zk2(&[
            "contract",
            "compat",
            &c("resource-removed", "old"),
            &c("resource-removed", "new")
        ]),
        1
    );
    assert_eq!(zk2(&["contract", "check-history", &p("history/ok")]), 0);
    assert_eq!(
        zk2(&["contract", "check-history", &p("history/tampered")]),
        1
    );
    assert_eq!(
        zk2(&[
            "contract",
            "compat",
            &p("bundles/valid.bundle.json"),
            &p("bundles/valid.bundle.json")
        ]),
        0
    );
    assert_eq!(zk2(&["contract", "nope"]), 2);
    assert_eq!(zk2(&["contract", "fingerprint", "/nonexistent.toml"]), 1);
}

/// What `zk2` prints and how it exits, for one run.
fn run(args: &[&str]) -> (i32, String) {
    let out = Command::new(env!("CARGO_BIN_EXE_zk2"))
        .args(args)
        .output()
        .expect("runs");
    (
        out.status.code().expect("exits"),
        String::from_utf8(out.stdout).expect("UTF-8"),
    )
}

/// `zk2 catalog` (core §8.6; #980 C1a): `new` writes a first catalog, `add`
/// its successor, `id` and `check` read one; 1 for a refused catalog, one
/// that does not succeed its predecessor or lacks a contract, 2 for usage
/// and unreadable files.
#[test]
fn catalog_exit_codes() {
    let dir = std::env::temp_dir().join(format!("zk2-catalog-cli-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    let at = |name: &str| dir.join(name).display().to_string();
    let modem = Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("../examples/zk2/zenoh-modem/modem.v3.toml")
        .display()
        .to_string();
    // The history's first file by name, so the pick never hangs on the
    // file system's order.
    let mut revisions: Vec<_> = Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("../spec/profiles/.history/health.v1")
        .read_dir()
        .unwrap()
        .map(|e| e.unwrap().path())
        .collect();
    revisions.sort();
    let health = revisions[0].display().to_string();

    let (code, first) = run(&["catalog", "new", "--epoch", "1767225600", &modem]);
    assert_eq!(code, 0);
    std::fs::write(at("a.json"), &first).unwrap();
    let (code, id_a) = run(&["catalog", "id", &at("a.json")]);
    assert_eq!(code, 0);
    assert_eq!(id_a.trim().len(), 8);

    // A bundle from a history is a revision too; the successor names `a`.
    let (code, second) = run(&["catalog", "add", &at("a.json"), &health, &modem]);
    assert_eq!(code, 0);
    assert!(second.contains(id_a.trim()), "{second}");
    std::fs::write(at("b.json"), &second).unwrap();
    assert_eq!(
        zk2(&[
            "catalog",
            "check",
            &at("b.json"),
            "--previous",
            &at("a.json"),
            &modem,
            &health
        ]),
        0
    );
    // Succession is one way, and adding nothing writes the input unchanged.
    assert_eq!(
        zk2(&[
            "catalog",
            "check",
            &at("a.json"),
            "--previous",
            &at("b.json")
        ]),
        1
    );
    assert_eq!(run(&["catalog", "add", &at("b.json"), &modem]), (0, second));
    // A contract the catalog does not hold is a finding.
    assert_eq!(zk2(&["catalog", "check", &at("a.json"), &health]), 1);
    // The smallest catalog, and its default epoch of 0.
    let (code, empty) = run(&["catalog", "new"]);
    assert_eq!(code, 0);
    assert_eq!(
        empty.trim(),
        r#"{"entries":[],"epoch":0,"format":"zk2-catalog/1"}"#
    );

    std::fs::write(
        at("refused.json"),
        r#"{"format": "zk2-catalog/1", "epoch": -0, "entries": []}"#,
    )
    .unwrap();
    assert_eq!(zk2(&["catalog", "id", &at("refused.json")]), 1);
    assert_eq!(zk2(&["catalog", "check", &at("refused.json")]), 1);
    assert_eq!(zk2(&["catalog", "add", &at("refused.json"), &modem]), 1);

    assert_eq!(zk2(&["catalog", "id", &at("missing.json")]), 2);
    assert_eq!(zk2(&["catalog", "new", "--epoch", "-1"]), 2);
    assert_eq!(zk2(&["catalog", "new", "--epoch", "01"]), 2);
    assert_eq!(zk2(&["catalog", "new", "--epoch", "9007199254740992"]), 2);
    assert_eq!(zk2(&["catalog", "new", &at("missing.toml")]), 2);
    assert_eq!(zk2(&["catalog", "add", &at("a.json")]), 2);
    assert_eq!(
        zk2(&["catalog", "check", &at("a.json"), "--previus", "x"]),
        2
    );
    let invalid = p("contracts/e015-event.toml");
    assert_eq!(zk2(&["catalog", "new", &invalid]), 1);
    std::fs::remove_dir_all(&dir).unwrap();
}

/// `zk2 contract compat --history` of a revision the history root holds
/// (core §9.7, zk2py round 97's F-456): it passed its review when it was
/// published, so its review is reported as accepted and the exit is 0.
/// The same revision against a root that holds only its predecessor is a
/// review not yet accepted, exit 1. `health.v1`'s revision 1.1 uses
/// `freshness.v2` where 1.0 used `freshness.v1` (`uses_changed`).
#[test]
fn a_published_review_is_accepted() {
    let profiles = Path::new(env!("CARGO_MANIFEST_DIR")).join("../spec/profiles");
    let contract = profiles.join("health/health.v1.toml").display().to_string();
    let history = profiles.join(".history").display().to_string();
    let (code, out) = run(&["contract", "compat", "--history", &history, &contract]);
    assert_eq!(code, 0, "{out}");
    assert!(out.contains("same revision as a published one"), "{out}");
    assert!(out.contains("review [uses_changed]"), "{out}");
    assert!(out.contains("accepted: the revision is published"), "{out}");

    let dir = std::env::temp_dir().join(format!("zk2-accepted-cli-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(dir.join("health.v1")).unwrap();
    // Revision 1.0 alone.
    let first = "e9dbcdcb2fc325ca3121fdcacf7badd0091f62d97ab4c7d7a5f022dd8d6671df.bundle.json";
    std::fs::copy(
        profiles.join(".history/health.v1").join(first),
        dir.join("health.v1").join(first),
    )
    .unwrap();
    let root = dir.display().to_string();
    let (code, out) = run(&["contract", "compat", "--history", &root, &contract]);
    assert_eq!(code, 1, "{out}");
    assert!(out.contains("review [uses_changed]"), "{out}");
    assert!(!out.contains("accepted"), "{out}");
    std::fs::remove_dir_all(&dir).unwrap();
}

/// `zk2 config derive` on zenoh-modem's `sx1262_config.v1` (#985 G4)
/// prints exactly the five derived types its packed file holds after its
/// three group types, and `contract lint` finds nothing in it.
#[test]
fn config_derive_reproduces_the_sx1262s_derived_types() {
    let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("../examples/zk2/zenoh-modem/config");
    let contract = dir.join("sx1262_config.v1.toml").display().to_string();
    let out = Command::new(env!("CARGO_BIN_EXE_zk2"))
        .args(["config", "derive", &contract])
        .output()
        .expect("runs");
    assert_eq!(
        out.status.code(),
        Some(0),
        "{}",
        String::from_utf8_lossy(&out.stderr)
    );
    let printed: serde_json::Value = serde_json::from_slice(&out.stdout).expect("JSON");
    let packed: serde_json::Value = serde_json::from_str(
        &std::fs::read_to_string(dir.join("schemas/sx1262_config.json")).expect("the packed file"),
    )
    .expect("JSON");
    let names = |v: &serde_json::Value| {
        let mut n: Vec<String> = v["types"]
            .as_object()
            .expect("types")
            .keys()
            .cloned()
            .collect();
        n.sort_unstable();
        n
    };
    let derived = names(&printed);
    assert_eq!(
        derived,
        ["Control", "Error", "Record", "SetDuty", "SetRadio"],
        "Record, a Set<T> per hot or reach group, Control and Error"
    );
    assert_eq!(
        names(&packed),
        [
            "Control",
            "Duty",
            "Error",
            "Modulation",
            "Radio",
            "Record",
            "SetDuty",
            "SetRadio"
        ],
        "the three group types and the five derived ones"
    );
    for n in &derived {
        assert_eq!(printed["types"][n], packed["types"][n], "{n}");
    }
    assert_eq!(zk2(&["contract", "lint", &contract]), 0);
}

/// `zk2 config derive` prints the types config.v2 derives from a contract's
/// declaration (config.v2 §3): for the test contract `rfcfg.v1`, exactly
/// the eight derived types its packed file holds.
#[test]
fn config_derive_writes_the_derived_types() {
    let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("../spec/profiles/config/conformance");
    let contract = dir.join("contracts/rfcfg.v1.toml");
    let out = Command::new(env!("CARGO_BIN_EXE_zk2"))
        .args(["config", "derive", &contract.display().to_string()])
        .output()
        .expect("runs");
    assert_eq!(
        out.status.code(),
        Some(0),
        "{}",
        String::from_utf8_lossy(&out.stderr)
    );
    let printed: serde_json::Value = serde_json::from_slice(&out.stdout).expect("JSON");
    let packed: serde_json::Value = serde_json::from_str(
        &std::fs::read_to_string(dir.join("contracts/rfcfg.json")).expect("rfcfg.json"),
    )
    .expect("JSON");
    let types = printed["types"].as_object().expect("types");
    let names: Vec<&str> = types.keys().map(String::as_str).collect();
    let mut want = vec![
        "Control", "Error", "Record", "SetDuty", "SetLink", "SetQueue", "SetRadio", "SetSim",
    ];
    want.sort_unstable();
    let mut got = names.clone();
    got.sort_unstable();
    assert_eq!(got, want);
    for n in names {
        assert_eq!(printed["types"][n], packed["types"][n], "{n}");
    }
    // `contract lint` runs config.v2's lint: the test contract has no finding.
    assert_eq!(
        zk2(&["contract", "lint", &contract.display().to_string()]),
        0
    );
    assert_eq!(
        zk2(&["config", "derive", &p("contracts/ok-minimal.toml")]),
        1
    );
    assert_eq!(
        zk2(&["config", "derive", &p("contracts/no-such-file.toml")]),
        2
    );
}

/// `zk2 contract lint` runs desired.v2's lint (desired.v2 §2.2, §2.10): the
/// scenarios' two contracts have no finding, and a horizon above 0 under
/// `freshness.v1` is a finding, exit 1, named by its token.
#[test]
fn contract_lint_reads_desired_v2s_declarations() {
    let contracts = Path::new(env!("CARGO_MANIFEST_DIR")).join("../zenkey/tests/contracts");
    for file in ["tasking.v2.toml", "worker.v2.toml"] {
        let out = Command::new(env!("CARGO_BIN_EXE_zk2"))
            .args([
                "contract",
                "lint",
                &contracts.join(file).display().to_string(),
            ])
            .output()
            .expect("runs");
        assert_eq!(out.status.code(), Some(0), "{file}");
        assert!(out.stderr.is_empty(), "{file}: no finding at all");
    }
    let text = std::fs::read_to_string(contracts.join("tasking.v2.toml"))
        .expect("tasking.v2")
        .replace("\"freshness.v2\"", "\"freshness.v1\"")
        .replace("\"freshness.ttl_s\" = 0", "\"freshness.ttl_s\" = 600")
        .replace("jsonschema = [\"tasking.json\"]", "");
    let text = text.replace(
        "type        = \"json:Task\"",
        "type        = { raw = \"text/plain\" }",
    );
    let dir = std::env::temp_dir().join(format!("zk2-cli-desired-v2-{}", std::process::id()));
    std::fs::create_dir_all(&dir).expect("a directory");
    let file = dir.join("tasking.v2.toml");
    std::fs::write(&file, text).expect("the contract");
    let out = Command::new(env!("CARGO_BIN_EXE_zk2"))
        .args(["contract", "lint", &file.display().to_string()])
        .output()
        .expect("runs");
    let _ = std::fs::remove_dir_all(&dir);
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert_eq!(out.status.code(), Some(1), "{stderr}");
    assert!(
        stderr.contains("error[desired.v2 horizon_v1] state/tasks/{system}/{service}"),
        "{stderr}"
    );
    // The contract still loads, with its fingerprint (desired.v2 0.2 §2.2,
    // F-583): printed after the errors, as for any contract that loads.
    let stdout = String::from_utf8_lossy(&out.stdout);
    let printed = format!("{}: tasking.v2 ", file.display());
    assert!(
        stdout.starts_with(&format!("{printed}sha256:"))
            && stdout.trim_end().len() == printed.len() + "sha256:".len() + 64,
        "{stdout}"
    );
}

/// `zk2 contract lint` reads a service's own word tables (health.v2 §2.10,
/// §4): a contract that lists `health.v2` and writes its three keys once,
/// on `[defaults]`, has no finding; one whose table is no list of names, or
/// whose resources carry two lists, exits 1 and names the resource, the key
/// and the reason.
#[test]
fn contract_lint_reads_health_v2s_tables() {
    let dir = std::env::temp_dir().join(format!("zk2-cli-health-v2-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    let contract = |name: &str, defaults: &str, own: &str| {
        let path = dir.join(format!("{name}.toml"));
        let text = format!(
            "[interface]\nname = \"tc\"\nmajor = 1\nminor = 0\nuses = [\"health.v2\"]\n\n\
             [defaults]\nannotations = {{ {defaults} }}\n\n\
             [resources.rates]\nkind = \"stream\"\ntype = {{ raw = \"text/plain\" }}\n\n\
             [resources.loss]\nkind = \"stream\"\ntype = {{ raw = \"text/plain\" }}\n{own}"
        );
        std::fs::write(&path, text).unwrap();
        path.display().to_string()
    };
    let lint = |file: &str| {
        let out = Command::new(env!("CARGO_BIN_EXE_zk2"))
            .args(["contract", "lint", file])
            .output()
            .expect("runs");
        (
            out.status.code().expect("exits"),
            String::from_utf8(out.stderr).expect("UTF-8"),
        )
    };
    let ok = contract(
        "ok",
        r#""health.reasons" = ["tc_netns_gone", "tc_probe_stale"], "health.details" = ["tc_no_route"], "health.codes" = ["tc_netns_restarted"]"#,
        "",
    );
    let (code, stderr) = lint(&ok);
    assert_eq!(code, 0, "{stderr}");
    assert!(!stderr.contains("health.v2"), "{stderr}");
    let value = contract("value", r#""health.reasons" = ["Bad Name"]"#, "");
    let (code, stderr) = lint(&value);
    assert_eq!(code, 1, "{stderr}");
    assert!(
        stderr.contains("error[health.v2 value] stream/loss: health.reasons: "),
        "{stderr}"
    );
    let disagrees = contract(
        "disagrees",
        r#""health.codes" = ["tc_a", "tc_b"]"#,
        "annotations = { \"health.codes\" = [\"tc_a\"] }\n",
    );
    let (code, stderr) = lint(&disagrees);
    assert_eq!(code, 1, "{stderr}");
    assert!(
        stderr.contains("error[health.v2 disagrees] stream/rates: health.codes: "),
        "{stderr}"
    );
    let _ = std::fs::remove_dir_all(&dir);
}

/// `zk2 contract lint` warns of a governed interface's invalid declaration
/// (redundancy.v1 §2.2, redundancy.v2 §2.2; #987's N1): an explicit stream
/// under `redundancy.v2` (`explicit_stream`), and an election outside the
/// vocabulary under either major (`value`). Its runtime refuses to start
/// it, and the core has no code for either, so they are warnings: the
/// contract loads, its fingerprint is printed, and the exit is 0.
#[test]
fn contract_lint_warns_of_a_governed_declaration() {
    let dir = std::env::temp_dir().join(format!("zk2-cli-redundancy-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    let contract = |name: &str, uses: &str, election: &str, explicit: bool| {
        let path = dir.join(format!("{name}.toml"));
        let text = format!(
            "[interface]\nname = \"ledger\"\nmajor = 1\nminor = 0\nuses = [\"{uses}\"]\n\n\
             [defaults]\nannotations = {{ \"redundancy.election\" = \"{election}\" }}\n\n\
             [resources.balance]\nkind = \"state\"\ntype = {{ raw = \"text/plain\" }}\n\n\
             [resources.feed]\nkind = \"stream\"\nexplicit = {explicit}\ntype = {{ raw = \"text/plain\" }}\n"
        );
        std::fs::write(&path, text).unwrap();
        path.display().to_string()
    };
    let lint = |file: &str| {
        let out = Command::new(env!("CARGO_BIN_EXE_zk2"))
            .args(["contract", "lint", file])
            .output()
            .expect("runs");
        (
            out.status.code().expect("exits"),
            String::from_utf8(out.stdout).expect("UTF-8"),
            String::from_utf8(out.stderr).expect("UTF-8"),
        )
    };
    let clean = contract("clean", "redundancy.v2", "claim", false);
    let (code, stdout, stderr) = lint(&clean);
    assert_eq!(code, 0, "{stderr}");
    assert!(!stderr.contains("redundancy."), "{stderr}");
    assert!(stdout.contains("ledger.v1 sha256:"), "{stdout}");
    let explicit = contract("explicit", "redundancy.v2", "claim", true);
    let (code, stdout, stderr) = lint(&explicit);
    assert_eq!(code, 0, "a warning moves no exit: {stderr}");
    assert!(
        stderr.contains("  warning[redundancy.v2 explicit_stream] @stream/feed: "),
        "{stderr}"
    );
    assert!(stdout.contains("ledger.v1 sha256:"), "{stdout}");
    let v1 = contract("v1-explicit", "redundancy.v1", "claim", true);
    let (code, _, stderr) = lint(&v1);
    assert_eq!(code, 0, "{stderr}");
    assert!(
        !stderr.contains("redundancy."),
        "v1 fences an explicit stream: {stderr}"
    );
    for uses in ["redundancy.v1", "redundancy.v2"] {
        let value = contract(&format!("value-{uses}"), uses, "quorum", false);
        let (code, _, stderr) = lint(&value);
        assert_eq!(code, 0, "{stderr}");
        assert!(
            stderr.contains(&format!("  warning[{uses} value] state/balance: ")),
            "{stderr}"
        );
    }
    let _ = std::fs::remove_dir_all(&dir);
}