stratum-node-config 0.1.0-alpha.4

Versioned stratum.toml schema, comment-preserving editor, semantic validator, change preview and public-config hash for Stratum nodes
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
//! Preview: comment-preserving edits, diffs, change lists and error paths.

mod common;

use common::pq;
use stratum_node_config::{
    preview, schema, ApplyClass, Change, PreviewError, ValidationErrorKind, Value, REDACTED,
};

const COMMENTED: &str = "\
# Operator notes: do not remove.
#   indented comment line

schema_version = 1   # pinned


# --- identity ---
[node]
# The label members see.
name = \"before\"    # trailing comment survives

canonical_origin = \"\"

[limits]   # table header comment
# keep this
max_outstanding_challenges = 16
max_body_bytes   =   262144   # odd spacing


# tail comment
";

#[test]
fn edit_preserves_comments_blank_lines_and_order_exactly() {
    let p = preview(
        COMMENTED,
        &[
            Change::new("limits.max_body_bytes", 65_536),
            Change::new("node.name", "after"),
        ],
    )
    .expect("preview");
    let expected = COMMENTED
        .replace("name = \"before\"    #", "name = \"after\"    #")
        .replace("=   262144   # odd", "=   65536   # odd");
    assert_eq!(p.text(), expected, "only the edited values change");
    assert!(p.is_valid(), "valid: {:?}", p.errors());
}

#[test]
fn edit_of_the_commented_seed_changes_only_the_value() {
    let seed = schema().seed_text();
    let p = preview(&seed, &[Change::new("node.name", "alpha")]).expect("preview");
    assert_eq!(
        p.text(),
        seed.replacen("\nname = \"stratum\"\n", "\nname = \"alpha\"\n", 1),
        "seed round-trip keeps every comment, blank line and key order"
    );
    assert!(p.is_valid(), "valid: {:?}", p.errors());
}

#[test]
fn absent_key_is_appended_to_its_table_and_absent_table_to_the_document() {
    let base = "schema_version = 1\n\n# limits\n[limits]\nmax_body_bytes = 2048\n";
    let p = preview(
        base,
        &[
            Change::new("limits.max_outstanding_challenges", 8),
            Change::new("federation.egress_enabled", true),
        ],
    )
    .expect("preview");
    assert_eq!(
        p.text(),
        "schema_version = 1\n\n# limits\n[limits]\nmax_body_bytes = 2048\n\
         max_outstanding_challenges = 8\n\n[federation]\negress_enabled = true\n",
        "insertions"
    );
    assert!(p.is_valid(), "valid: {:?}", p.errors());
}

#[test]
fn edits_inside_dotted_and_inline_tables() {
    let p = preview(
        "schema_version = 1\nnode.name = \"a\"\nlimits = { max_body_bytes = 2048 }\n",
        &[
            Change::new("node.name", "b"),
            Change::new("limits.max_body_bytes", 4096),
        ],
    )
    .expect("preview");
    assert_eq!(
        p.text(),
        "schema_version = 1\nnode.name = \"b\"\nlimits = { max_body_bytes = 4096 }\n",
        "dotted and inline edits"
    );
}

#[test]
fn list_values_are_written_as_toml_arrays() {
    let seed = schema().seed_text();
    let p = preview(
        &seed,
        &[Change::new(
            "backup.age_recipients",
            Value::from(&[pq(0), pq(1)][..]),
        )],
    )
    .expect("preview");
    assert!(
        p.text().contains(&format!(
            "\nage_recipients = [\"{}\", \"{}\"]\n",
            pq(0),
            pq(1)
        )),
        "array written"
    );
    let doc = p.document().expect("valid");
    assert_eq!(doc.config().age_recipients(), [pq(0), pq(1)], "read back");
}

#[test]
fn change_list_is_in_schema_order_with_old_and_new_values() {
    let seed = schema().seed_text();
    let p = preview(
        &seed,
        &[
            Change::new("limits.max_outstanding_challenges", 4),
            Change::new("node.canonical_origin", "https://pod.example.org"),
            Change::new("listen.address", "127.0.0.1:8000"),
        ],
    )
    .expect("preview");
    let got: Vec<(&str, ApplyClass, Option<&Value>, &Value)> = p
        .changes()
        .iter()
        .map(|c| (c.path(), c.apply_class(), c.old(), c.new_value()))
        .collect();
    assert_eq!(
        got,
        [
            (
                "node.canonical_origin",
                ApplyClass::Redeploy,
                Some(&Value::from("")),
                &Value::from("https://pod.example.org"),
            ),
            (
                "listen.address",
                ApplyClass::Restart,
                Some(&Value::from("127.0.0.1:7460")),
                &Value::from("127.0.0.1:8000"),
            ),
            (
                "limits.max_outstanding_challenges",
                ApplyClass::Live,
                Some(&Value::Integer(16)),
                &Value::Integer(4),
            ),
        ],
        "change list"
    );
    assert_eq!(
        p.strictest_apply_class(),
        Some(ApplyClass::Redeploy),
        "strictest"
    );
}

#[test]
fn old_value_of_an_absent_field_is_its_default() {
    let p = preview(
        "schema_version = 1\n",
        &[Change::new("limits.max_body_bytes", 2048)],
    )
    .expect("preview");
    assert_eq!(
        p.changes()[0].old(),
        Some(&Value::Integer(262_144)),
        "default as old"
    );
}

#[test]
fn no_op_changes_are_dropped_and_leave_text_untouched() {
    let seed = schema().seed_text();
    let p = preview(
        &seed,
        &[
            Change::new("node.name", "stratum"),
            Change::new("limits.max_body_bytes", 262_144),
        ],
    )
    .expect("preview");
    assert!(p.changes().is_empty(), "no changes");
    assert_eq!(p.strictest_apply_class(), None, "no class");
    assert_eq!(p.text(), seed, "text unchanged");
    assert_eq!(p.diff(), "", "empty diff");
    assert!(p.is_valid(), "still valid");

    // Setting an omitted field to its default is also a no-op.
    let base = "schema_version = 1\n";
    let p = preview(base, &[Change::new("federation.egress_enabled", false)]).expect("preview");
    assert!(p.changes().is_empty(), "default no-op");
    assert_eq!(p.text(), base, "nothing inserted");
}

#[test]
fn mixed_no_op_and_real_changes_keep_only_the_real_one() {
    let seed = schema().seed_text();
    let p = preview(
        &seed,
        &[
            Change::new("node.name", "stratum"),
            Change::new("federation.egress_enabled", true),
        ],
    )
    .expect("preview");
    let paths: Vec<&str> = p
        .changes()
        .iter()
        .map(stratum_node_config::FieldChange::path)
        .collect();
    assert_eq!(paths, ["federation.egress_enabled"], "only the real change");
    assert_eq!(p.strictest_apply_class(), Some(ApplyClass::Live), "class");
}

#[test]
fn unified_diff_has_headers_and_hunks() {
    let base = "schema_version = 1\n\n[node]\nname = \"a\"\n";
    let p = preview(base, &[Change::new("node.name", "b")]).expect("preview");
    assert_eq!(
        p.diff(),
        "--- stratum.toml\n+++ stratum.toml\n@@ -1,4 +1,4 @@\n schema_version = 1\n \n [node]\n-name = \"a\"\n+name = \"b\"\n",
        "unified diff"
    );
}

#[test]
fn secret_reference_values_are_redacted_in_the_change_list() {
    let base = "schema_version = 1\n[secrets]\npod_admin_key_ref = \"keystore:old-MARK\"\n";
    let p = preview(
        base,
        &[Change::new(
            "secrets.pod_admin_key_ref",
            "keystore:new-MARK",
        )],
    )
    .expect("preview");
    let c = &p.changes()[0];
    assert!(c.is_redacted(), "flagged");
    assert_eq!(c.old(), Some(&Value::from(REDACTED)), "old redacted");
    assert_eq!(c.new_value(), &Value::from(REDACTED), "new redacted");
    assert_eq!(c.apply_class(), ApplyClass::Restart, "class");

    let json = serde_json::to_string(p.changes()).expect("serialises");
    assert!(!json.contains("MARK"), "change list json redacted: {json}");
    assert!(json.contains("\"<redacted>\""), "redaction marker present");
    let debug = format!("{p:?}");
    assert!(!debug.contains("MARK"), "preview debug redacted: {debug}");
    let change_debug = format!("{:?}", Change::new("secrets.pod_admin_key_ref", "x-MARK"));
    assert!(!change_debug.contains("MARK"), "change debug redacted");

    // The TOML text itself is the configuration and keeps the reference.
    assert!(
        p.text().contains("keystore:new-MARK"),
        "text holds reference"
    );
    assert!(
        p.document()
            .and_then(|d| d.config().pod_admin_key_ref())
            .is_some_and(|r| r.as_str() == "keystore:new-MARK"),
        "typed accessor sees new reference"
    );
}

#[test]
fn invalid_result_reports_every_error_and_has_no_document() {
    let seed = schema().seed_text();
    let p = preview(
        &seed,
        &[
            Change::new("node.name", ""),
            Change::new("limits.max_body_bytes", 1),
            Change::new("federation.egress_enabled", "yes"),
            Change::new("storage.backup_dir", "/var/lib/stratum/state"),
        ],
    )
    .expect("preview");
    let got: Vec<(Option<&str>, ValidationErrorKind)> =
        p.errors().iter().map(|e| (e.path(), e.kind())).collect();
    assert_eq!(
        got,
        [
            (Some("node.name"), ValidationErrorKind::InvalidValue),
            (
                Some("federation.egress_enabled"),
                ValidationErrorKind::WrongType
            ),
            (
                Some("limits.max_body_bytes"),
                ValidationErrorKind::OutOfRange
            ),
            (Some("storage.backup_dir"), ValidationErrorKind::Conflict),
        ],
        "errors of the result"
    );
    assert!(!p.is_valid(), "invalid");
    assert!(p.document().is_none(), "no document");
    assert_eq!(p.changes().len(), 4, "changes still listed");
}

#[test]
fn an_invalid_base_can_be_repaired() {
    let base = "schema_version = 1\n[limits]\nmax_body_bytes = 5\n";
    let p = preview(base, &[Change::new("limits.max_body_bytes", 4096)]).expect("preview");
    assert!(p.is_valid(), "repaired: {:?}", p.errors());
    assert_eq!(
        p.changes()[0].old(),
        Some(&Value::Integer(5)),
        "old out-of-range value"
    );

    let base = "schema_version = 1\n[limits]\nmax_body_bytes = 5.5\n";
    let p = preview(base, &[Change::new("limits.max_body_bytes", 4096)]).expect("preview");
    assert!(p.is_valid(), "float repaired");
    assert_eq!(p.changes()[0].old(), None, "unrepresentable old value");
}

#[test]
fn unknown_path_is_an_error() {
    let err = preview(&schema().seed_text(), &[Change::new("node.colour", "red")])
        .expect_err("unknown path");
    assert_eq!(
        err,
        PreviewError::UnknownPath {
            path: "node.colour".to_owned()
        },
        "variant"
    );
    assert_eq!(
        err.to_string(),
        "unknown configuration path \"node.colour\"",
        "message"
    );
    let err = preview("schema_version = 1\n", &[Change::new("schema_version", 2)])
        .expect_err("schema_version is not editable");
    assert!(matches!(err, PreviewError::UnknownPath { .. }), "{err}");
}

#[test]
fn duplicate_path_is_an_error() {
    let err = preview(
        &schema().seed_text(),
        &[Change::new("node.name", "a"), Change::new("node.name", "b")],
    )
    .expect_err("duplicate");
    assert_eq!(
        err,
        PreviewError::DuplicatePath {
            path: "node.name".to_owned()
        },
        "variant"
    );
}

#[test]
fn syntactically_broken_base_is_an_error() {
    let err = preview(
        "schema_version = 1\n[node\n",
        &[Change::new("node.name", "a")],
    )
    .expect_err("syntax");
    let PreviewError::Syntax(e) = err else {
        panic!("expected syntax error, got {err:?}");
    };
    assert_eq!(e.kind(), ValidationErrorKind::Syntax, "kind");
}

#[test]
fn obstructed_edits_are_errors() {
    let err = preview(
        "schema_version = 1\nnode = 5\n",
        &[Change::new("node.name", "a")],
    )
    .expect_err("section not a table");
    assert_eq!(
        err,
        PreviewError::NotEditable {
            path: "node".to_owned()
        },
        "section"
    );
    let err = preview(
        "schema_version = 1\n[node.name]\nx = 1\n",
        &[Change::new("node.name", "a")],
    )
    .expect_err("value slot holds a table");
    assert_eq!(
        err,
        PreviewError::NotEditable {
            path: "node.name".to_owned()
        },
        "value"
    );
}

#[test]
fn preview_is_deterministic() {
    let changes = [
        Change::new("node.name", "alpha"),
        Change::new("backup.age_recipients", Value::from(&[pq(0)][..])),
        Change::new("secrets.pod_admin_key_ref", "keystore:k"),
        Change::new("limits.max_body_bytes", 1),
    ];
    let a = preview(COMMENTED, &changes).expect("first");
    let b = preview(COMMENTED, &changes).expect("second");
    assert_eq!(a, b, "equal previews");
    let ja = serde_json::to_vec(&a).expect("json a");
    let jb = serde_json::to_vec(&b).expect("json b");
    assert_eq!(ja, jb, "byte-identical serialisation");
    assert_eq!(
        a.text().as_bytes(),
        b.text().as_bytes(),
        "byte-identical text"
    );
    assert_eq!(
        a.diff().as_bytes(),
        b.diff().as_bytes(),
        "byte-identical diff"
    );

    // Input order does not matter either.
    let mut reversed = changes;
    reversed.reverse();
    let c = preview(COMMENTED, &reversed).expect("reversed");
    assert_eq!(a, c, "order-independent");
}

#[test]
fn preview_serialises_for_the_http_api() {
    let p = preview(&schema().seed_text(), &[Change::new("node.name", "alpha")]).expect("preview");
    let json = serde_json::to_value(&p).expect("serialises");
    assert_eq!(json["valid"], true, "valid");
    assert_eq!(json["strictest_apply_class"], "live", "class");
    assert_eq!(
        json["changes"],
        serde_json::json!([{
            "path": "node.name",
            "apply_class": "live",
            "old": "stratum",
            "new": "alpha",
            "redacted": false,
        }]),
        "changes"
    );
    assert_eq!(json["errors"], serde_json::json!([]), "errors");
    assert_eq!(json["text"], p.text(), "text");
    assert_eq!(json["diff"], p.diff(), "diff");
}

#[test]
fn changes_deserialise_from_the_http_shape() {
    let changes: Vec<Change> = serde_json::from_str(
        r#"[{"path": "node.name", "value": "alpha"},
            {"path": "limits.max_body_bytes", "value": 4096},
            {"path": "federation.egress_enabled", "value": true},
            {"path": "backup.age_recipients", "value": ["age1a"]}]"#,
    )
    .expect("deserialises");
    assert_eq!(
        changes,
        [
            Change::new("node.name", "alpha"),
            Change::new("limits.max_body_bytes", 4096),
            Change::new("federation.egress_enabled", true),
            Change::new("backup.age_recipients", Value::from(&["age1a"][..])),
        ],
        "typed changes"
    );
    let bad: Result<Vec<Change>, _> =
        serde_json::from_str(r#"[{"path": "limits.max_body_bytes", "value": 1.5}]"#);
    assert!(bad.is_err(), "floats are not values");
}