lean-ctx-cloud 3.12.13

The LeanCTX connector: enrollment, bus, knowledge sync, tasks and policy on top of LeanCTX | OSS.
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
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
// SPDX-License-Identifier: Apache-2.0
//! Bus v2 shapes against the C0 2.0 `bus/` fixtures and control vectors.

use super::*;

const PUBLISH_FIELDS: [&str; 14] = [
    "schema",
    "client_msg_id",
    "to",
    "type",
    "worker_id",
    "thread_id",
    "reply_to",
    "refs",
    "body",
    "ck_wrapped",
    "epoch",
    "about",
    "counts",
    "window",
];

fn fixture(name: &str) -> Value {
    let path = format!(
        "{}/crates/lean-ctx-protocol/tests/fixtures/cloud-v2/{name}",
        concat!(env!("CARGO_MANIFEST_DIR"), "/../..")
    );
    serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap()
}

/// The `replace`, `remove` and `add` ops the invalid cases use.
fn patched(base: &Value, ops: &[Value]) -> Value {
    let mut doc = base.clone();
    for op in ops {
        let path = op["path"].as_str().unwrap();
        let (parent, last) = path.rsplit_once('/').unwrap();
        let target = doc.pointer_mut(parent).unwrap().as_object_mut().unwrap();
        match op["op"].as_str().unwrap() {
            "remove" => {
                target.remove(last);
            }
            "replace" | "add" => {
                target.insert(last.to_string(), op["value"].clone());
            }
            other => panic!("op {other}"),
        }
    }
    doc
}

/// A stored message reduced to what its engine published.
fn as_publish(message: &Value) -> Value {
    let mut out = Map::new();
    for field in PUBLISH_FIELDS {
        if let Some(v) = message.get(field) {
            out.insert(field.to_string(), v.clone());
        }
    }
    Value::Object(out)
}

fn publish_ok(doc: &Value) -> Result<(), Invalid> {
    serde_json::from_value::<Publish>(doc.clone())
        .map_err(|e| Invalid(e.to_string()))?
        .validate()
}

fn control_keys() -> ControlKeys {
    let keys = fixture("vectors/signing.vectors.json");
    let control = &keys["keys"]["cloud_control"];
    let mut public = [0u8; 32];
    hex::decode_to_slice(control["public_key_hex"].as_str().unwrap(), &mut public).unwrap();
    BTreeMap::from([(
        control["key_id"].as_str().unwrap().to_string(),
        VerifyingKey::from_bytes(&public).unwrap(),
    )])
}

#[test]
fn collaboration_findings_carry_counts_and_a_window_without_refs() {
    let message = fixture("bus/message.finding.collaboration.json");
    let publish: Publish = serde_json::from_value(as_publish(&message)).unwrap();
    publish.validate().unwrap();
    assert_eq!(publish.about, Some(About::Collaboration));
    let counts = publish.counts.unwrap();
    assert_eq!(
        (counts.agent_seconds, counts.merge_conflict),
        (Some(5400), None)
    );
    assert_eq!(
        publish.window.unwrap().to_ms - publish.window.unwrap().from_ms,
        3_600_000
    );
    // The same finding without `about` needs refs and may not carry counts.
    let mut plain = publish.clone();
    plain.about = None;
    assert!(plain.validate().is_err());
    plain.counts = None;
    plain.window = None;
    assert!(plain.validate().is_err(), "a plain finding needs refs");
    let mut question = publish;
    question.kind = MessageType::Question;
    assert!(question.validate().is_err(), "findings only");
}

#[test]
fn engine_publishes_match_the_fixtures() {
    for name in ["publish.question", "publish.answer"] {
        let doc = fixture(&format!("bus/{name}.json"));
        publish_ok(&doc).unwrap_or_else(|e| panic!("{name}: {e}"));
        let back = serde_json::to_value(serde_json::from_value::<Publish>(doc.clone()).unwrap());
        assert_eq!(back.unwrap(), doc, "{name} round-trips");
    }
    // The frame form is the same body plus `t`.
    let frame = fixture("bus/frame.place_publish.json");
    let mut body = frame.clone();
    body.as_object_mut().unwrap().remove("t");
    publish_ok(&body).unwrap();
}

/// A sealed body never leaves, with or without its key material.
#[test]
fn a_sealed_publish_is_refused() {
    let mut doc = fixture("bus/publish.question.json");
    doc["body"] = serde_json::json!({"sealed": {"ct": "AAAA", "nonce": "AAAA"}});
    let refused = publish_ok(&doc).unwrap_err();
    assert!(
        refused.0.contains("sealed bodies are not supported"),
        "{refused:?}"
    );
    doc["ck_wrapped"] = Value::from("A".repeat(96));
    doc["epoch"] = Value::from(1);
    assert!(publish_ok(&doc).is_err());
}

#[test]
fn the_invalid_cases_are_refused_before_they_leave() {
    let keys = control_keys();
    let dir = format!(
        "{}/crates/lean-ctx-protocol/tests/fixtures/cloud-v2/bus/invalid",
        concat!(env!("CARGO_MANIFEST_DIR"), "/../..")
    );
    let mut checked = 0;
    for entry in std::fs::read_dir(dir).unwrap() {
        let case: Value =
            serde_json::from_str(&std::fs::read_to_string(entry.unwrap().path()).unwrap()).unwrap();
        let base_name = case["base"].as_str().unwrap();
        let base = fixture(base_name);
        let doc = patched(&base, case["patch"].as_array().unwrap());
        let name = case["case"].as_str().unwrap_or_default();
        let refused = match base_name.trim_start_matches("bus/") {
            b if b.starts_with("publish.") => publish_ok(&doc).is_err(),
            b if b.starts_with("message.") => {
                publish_ok(&as_publish(&doc)).is_err() || sender_of(&doc).is_err()
            }
            b if b.starts_with("control.") => serde_json::from_value::<Control>(doc.clone())
                .map_or(true, |c| c.verify(c.lifted_at.is_some(), &keys).is_err()),
            b if b.starts_with("frame.control") => match parse_frame(&doc.to_string()) {
                Ok(Inbound::Control { lifted, control }) => control.verify(lifted, &keys).is_err(),
                _ => true,
            },
            // Unknown frames and extra frame members are the server's to
            // refuse; the engine ignores what it does not read.
            _ => continue,
        };
        assert!(refused, "{name} must be refused");
        checked += 1;
    }
    assert!(checked >= 11, "{checked}");
}

/// C0 b000ffd: `issued_by.label` is read (a control carrying it is not
/// dropped as malformed) and is covered by the signature (C0 f5f72158
/// signs the fixture's own label).
#[test]
fn an_issuer_label_is_read_and_signed() {
    let keys = control_keys();
    let doc = fixture("bus/control.hold.json");
    let signed: Control = serde_json::from_value(doc.clone()).unwrap();
    let label = signed
        .issued_by
        .label
        .clone()
        .expect("the fixture is labelled");
    signed.verify(false, &keys).unwrap();
    let mut changed = doc.clone();
    changed["issued_by"]["label"] = format!("{label}-x").into();
    let mut removed = doc;
    removed["issued_by"]
        .as_object_mut()
        .unwrap()
        .remove("label");
    for (what, tampered) in [("changed", changed), ("removed", removed)] {
        let control: Control = serde_json::from_value(tampered).unwrap();
        assert_eq!(
            control.verify(false, &keys),
            Err(ControlRejection::SigInvalid),
            "a {what} label breaks the signature"
        );
    }
}

#[test]
fn a_web_only_place_role_on_a_stored_sender_is_refused() {
    let message = fixture("bus/message.question.json");
    assert!(matches!(sender_of(&message), Ok(Sender::Worker { .. })));
    let mut with_role = message;
    with_role["sender"]["place_role"] = "owner".into();
    assert!(sender_of(&with_role).is_err());
}

#[test]
fn controls_verify_against_the_vectors_and_tampering_fails() {
    let keys = control_keys();
    let vectors = fixture("vectors/control.vectors.json");
    for case in vectors["cases"].as_array().unwrap() {
        let control: Control =
            serde_json::from_value(fixture(case["fixture"].as_str().unwrap())).unwrap();
        let mut unsigned = serde_json::to_value(&control).unwrap();
        unsigned.as_object_mut().unwrap().remove("signature");
        let input = lean_ctx_protocol::cloud::signing_input(CONTROL_DOMAIN, &unsigned).unwrap();
        assert_eq!(
            String::from_utf8(input).unwrap(),
            case["signing_input"].as_str().unwrap()
        );
        control.verify(control.lifted_at.is_some(), &keys).unwrap();
        // A key without purpose `control` (here: unknown) is refused.
        assert_eq!(
            control.verify(control.lifted_at.is_some(), &ControlKeys::new()),
            Err(ControlRejection::SigInvalid)
        );
    }
}

#[test]
fn team_presence_names_are_read_from_a_presence_update() {
    let frame = serde_json::json!({"t": "presence.update", "address": "#acme/app", "worker_id": "wkr_a",
        "role": "coder", "state": "active", "at": 1,
        "person_name": "  Yves Gugger ", "machine_name": "yves-mac",
        "working_on": "Fix the login page", "display_name": "Coder"});
    let Inbound::Presence { names, .. } = parse_frame(&frame.to_string()).unwrap() else {
        panic!("a presence frame");
    };
    assert_eq!(names.person_name.as_deref(), Some("Yves Gugger"));
    assert_eq!(names.machine_name.as_deref(), Some("yves-mac"));
    assert_eq!(names.working_on.as_deref(), Some("Fix the login page"));
    // No bounded single line: dropped, the rest kept.
    let bad = presence_names(
        &serde_json::json!({"person_name": "a\nb", "machine_name": "x".repeat(129),
        "working_on": ""}),
    );
    assert_eq!(bad.person_name, None);
    assert_eq!(bad.machine_name, None);
    assert_eq!(bad.working_on, None);
}

#[test]
fn the_machine_name_never_carries_a_domain() {
    assert_eq!(
        machine_name("build-01.corp.example.com").as_deref(),
        Some("build-01")
    );
    assert_eq!(machine_name("yves-mac.local").as_deref(), Some("yves-mac"));
    assert_eq!(
        machine_name("DESKTOP-4F2K").as_deref(),
        Some("DESKTOP-4F2K")
    );
    // A label that reads like a name stays as the person set it.
    assert_eq!(
        machine_name(" Yves's laptop ").as_deref(),
        Some("Yves's laptop")
    );
    assert_eq!(machine_name(""), None);
    assert_eq!(machine_name(".local"), None);
    assert_eq!(
        working_on("\n  Review !42\nmore").as_deref(),
        Some("Review !42")
    );
    assert_eq!(
        working_on(&"y".repeat(300)).map(|s| s.chars().count()),
        Some(128)
    );
    assert_eq!(working_on("  \n "), None);
}

/// h7b blocking 1: what a worker is working on leaves the machine without
/// secrets and without absolute paths (only their last part stays).
#[test]
fn h7b_working_on_redacts_secrets_and_paths() {
    // Built at run time so no token-shaped literal sits in the source.
    let secret = ["gh", "p_", "aB3dE6gH9jK2mN5pQ8sT1vW4yZ7bC0eF3hJ6"].concat();
    let line = working_on(&format!(
        "fix /Users/ada/src/acme-bank/login.rs with token={secret} (see C:\\Users\\ada\\acme-bank\\notes.md)"
    ))
    .expect("a line");
    assert!(!line.contains(&secret), "{line}");
    assert!(line.contains("[REDACTED"), "{line}");
    assert!(!line.contains("/Users"), "{line}");
    assert!(!line.contains("acme-bank"), "{line}");
    assert!(line.starts_with("fix login.rs with "), "{line}");
    assert!(line.ends_with("(see notes.md)"), "{line}");
    assert_eq!(
        working_on("open file:///home/ada/acme/plan.txt and ~/acme/x.rs").as_deref(),
        Some("open plan.txt and x.rs")
    );
    // Relative paths, ratios and a lone slash stay as written.
    assert_eq!(
        working_on("edit src/main.rs, 1/2 done / next").as_deref(),
        Some("edit src/main.rs, 1/2 done / next")
    );
    // A secret past the cut is redacted before the cut, never sent half.
    let long = format!("{} token={secret}", "w".repeat(100));
    let cut = working_on(&long).expect("a line");
    assert!(!cut.contains("ghp_aB3"), "{cut}");
    assert!(cut.chars().count() <= 128, "{cut}");
}

/// h7b follow-up: a path behind a flag (`--root=`) or with spaces in a
/// folder name leaves only its last part, on Unix and Windows alike.
#[test]
fn h7b_working_on_cuts_flag_values_and_paths_with_spaces() {
    let cases = [
        (
            "serve --root=/Users/ada/acme-bank",
            "serve --root=acme-bank",
        ),
        (
            "index --root=C:\\Users\\ada\\acme-bank\\ now",
            "index --root=acme-bank now",
        ),
        ("graph root=~/acme-bank/api done", "graph root=api done"),
        (
            "edit /Users/ada/My Projects/acme-bank/login.rs next",
            "edit login.rs next",
        ),
        (
            "edit C:\\Users\\Ada Lovelace\\acme-bank\\notes.md now",
            "edit notes.md now",
        ),
        (
            "share \\\\nas\\team share\\acme-bank\\q3.xlsx",
            "share q3.xlsx",
        ),
        (
            "open \"/home/ada/acme bank/plan one.txt\" now",
            "open \"plan one.txt\" now",
        ),
        (
            "run --root=\"/Users/ada/My Projects/acme-bank\" ok",
            "run --root=\"acme-bank\" ok",
        ),
        ("diff /srv/ada/x.rs /srv/ada/y.rs", "diff x.rs y.rs"),
    ];
    for (input, want) in cases {
        let got = working_on(input).expect("a line");
        assert_eq!(got, want, "{input}");
        for private in ["Users", "home", "Projects", "Lovelace", "nas", "srv"] {
            assert!(!got.contains(private), "{input} -> {got}");
        }
    }
    // Relative paths, flags without a path and a lone slash stay as written.
    for kept in [
        "keep src/main.rs and --mode=fast",
        "token=abc and 1/2 done / next",
        "see https://example.com/a/b",
    ] {
        assert_eq!(working_on(kept).as_deref(), Some(kept));
    }
}

/// h7b review: a path starts after any prefix (a nested `key=`, a short flag,
/// `path:`, a non-ASCII key, `~user/`), and everything through the last
/// separator of its segment goes, so folder names with several spaces and a
/// quote inside a quoted path leak nothing.
#[test]
fn h7b_working_on_cuts_paths_after_any_prefix_through_the_last_separator() {
    let cases = [
        (
            "edit C:\\Users\\ada\\OneDrive - Acme Bank\\secret-proj\\x.rs now",
            "edit x.rs now",
        ),
        (
            "edit /Users/ada/My Big Projects/acme/login.rs next",
            "edit login.rs next",
        ),
        ("run --set=a=/Users/ada/acme-bank/x", "run --set=a=x"),
        ("docker -v/Users/ada/acme-bank:/app up", "docker -vapp up"),
        ("cc -I/Users/ada/acme-bank/include x.c", "cc -Iinclude x.c"),
        ("open path:/Users/ada/acme-bank/x.rs", "open path:x.rs"),
        ("grün=/Users/ada/x/y.rs", "grün=y.rs"),
        ("cd ~ada/acme-bank/api", "cd api"),
        ("open '/home/ada/it's here/acme/x' now", "open 'x' now"),
        ("read /repo/a.md src/main.rs", "read main.rs"),
        (
            "open \"C:\\Users\\ada\\My Big Projects\\acme\\\" now",
            "open \"acme\" now",
        ),
    ];
    for (input, want) in cases {
        let got = working_on(input).expect("a line");
        assert_eq!(got, want, "{input}");
        for private in [
            "Users",
            "home",
            "ada",
            "Acme",
            "acme-bank",
            "secret-proj",
            "Big",
            "Projects",
            "here",
            "repo",
        ] {
            assert!(!got.contains(private), "{input} -> {got}");
        }
    }
    // Relative paths, ratios, a lone slash and URLs still stay as written.
    for kept in [
        "keep src/main.rs and ./x and ../y",
        "token=abc and 1/2 done / next",
        "see https://example.com/a/b and -v",
    ] {
        assert_eq!(working_on(kept).as_deref(), Some(kept));
    }
}

/// h7b re-review: a host-form `file:` URL (UNC as a URL) and a home
/// written as `$NAME/` are cut like `\\nas\share\…` and `~/…`.
#[test]
fn h7b_working_on_cuts_host_file_urls_and_env_homes() {
    for (input, want) in [
        ("open file://nas/share/acme-bank/q3.xlsx", "open q3.xlsx"),
        ("cd $HOME/acme-bank/api", "cd api"),
        ("edit $USERPROFILE\\acme-bank\\x.rs now", "edit x.rs now"),
    ] {
        let got = working_on(input).expect("a line");
        assert_eq!(got, want, "{input}");
        for private in ["nas", "share", "acme-bank", "HOME", "USERPROFILE"] {
            assert!(!got.contains(private), "{input} -> {got}");
        }
    }
    // An amount or a variable without a path stays.
    assert_eq!(
        working_on("costs $5 and $HOME").as_deref(),
        Some("costs $5 and $HOME")
    );
}

/// h7b blocking 3: an IP label is kept whole, never cut to its first octet.
#[test]
fn h7b_machine_name_keeps_an_ip_whole() {
    assert_eq!(machine_name("10.0.0.5").as_deref(), Some("10.0.0.5"));
    assert_eq!(machine_name("fe80::1").as_deref(), Some("fe80::1"));
    assert_eq!(machine_name("ci-7.internal").as_deref(), Some("ci-7"));
}

#[test]
fn frames_the_engine_reads_parse() {
    let text = |name: &str| fixture(&format!("bus/{name}.json")).to_string();
    assert!(matches!(
        parse_frame(&text("frame.message_stored")).unwrap(),
        Inbound::Stored { seq, .. } if seq >= 1
    ));
    assert!(matches!(
        parse_frame(&text("frame.presence_update")).unwrap(),
        Inbound::Presence {
            state: PresenceState::Idle,
            ..
        }
    ));
    assert!(matches!(
        parse_frame(&text("frame.control.lifted")).unwrap(),
        Inbound::Control { lifted: true, .. }
    ));
    assert!(matches!(
        parse_frame(&text("frame.place_denied")).unwrap(),
        Inbound::PlaceDenied { .. }
    ));
    assert!(matches!(
        parse_frame(&text("frame.resync")).unwrap(),
        Inbound::Resync { .. }
    ));
    assert!(matches!(
        parse_frame(&text("frame.error")).unwrap(),
        Inbound::Error { .. }
    ));
    assert!(matches!(
        parse_frame(&text("frame.ping")).unwrap(),
        Inbound::Ping
    ));
    assert!(matches!(
        parse_frame(&text("frame.message_deliver")).unwrap(),
        Inbound::Deliver(_)
    ));
    assert!(matches!(
        parse_frame(&text("frame.lease_granted")).unwrap(),
        Inbound::Other(_)
    ));
    assert!(matches!(
        parse_frame(&text("frame.log_advanced")).unwrap(),
        Inbound::LogAdvanced { purge: false, ref place } if place.starts_with("vault:")
    ));
    assert!(matches!(
        parse_frame(&text("frame.log_advanced.purge")).unwrap(),
        Inbound::LogAdvanced { purge: true, .. }
    ));
    assert!(matches!(
        parse_frame(&text("frame.trust_advanced")).unwrap(),
        Inbound::TrustAdvanced { .. }
    ));
}

/// `policy.advanced` (proposed C0 frame, no fixture yet): a version, and a
/// frame without one is invalid rather than a nudge for nothing.
#[test]
fn policy_advanced_carries_a_version() {
    assert!(matches!(
        parse_frame(r#"{"t":"policy.advanced","version":7,"digest":"ab"}"#).unwrap(),
        Inbound::PolicyAdvanced { version: 7 }
    ));
    assert!(parse_frame(r#"{"t":"policy.advanced"}"#).is_err());
    assert!(parse_frame(r#"{"t":"log.advanced","seq":1}"#).is_err());
}

#[test]
fn ulids_are_well_formed_and_ordered_by_time() {
    let a = new_ulid(1_792_800_000_000);
    let b = new_ulid(1_792_800_000_001);
    assert!(is_ulid(&a) && is_ulid(&b), "{a} {b}");
    assert!(a[..10] < b[..10]);
    assert!(is_ulid("01M5NKA2Z8B000000000000001"));
    assert!(!is_ulid("01m5nka2z8b000000000000001"));
    assert!(!is_ulid("01M5NKA2Z8B00000000000000I"));
}

#[test]
fn the_c0_2_2_bus_types() {
    for t in [
        "question", "answer", "finding", "offer", "handoff", "progress",
    ] {
        assert!(MessageType::parse(t).is_some(), "{t}");
    }
    for t in ["need", "claim", "result", "status"] {
        assert_eq!(MessageType::parse(t), None, "{t}");
    }
}