treeship-core 0.24.0

Portable trust receipts for agent workflows - core library
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
//! Integration tests for v0.9.9 PR 6: Hub-signed checkpoint verification
//! against an embedded `.treeship` package's approval evidence.
//!
//! These tests exercise the full path:
//!   - build a fixture `.treeship` package with one ApprovalUse
//!   - sign a `JournalCheckpoint { kind: HubOrg, ... }` with a real
//!     Ed25519 key
//!   - drop the signed checkpoint into the package's approvals/checkpoints/
//!   - re-read the package via `read_approvals_bundle`
//!   - run `verify_package` and inspect the synthesized
//!     `replay-hub-org` row
//!
//! The release rule "PASS only when signature verifies AND covers
//! every use" is what every test pins.

use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
use ed25519_dalek::{Signer, SigningKey};
use serde_json::Value;

use treeship_core::session::{
    build_package_with_approvals, read_approvals_bundle, verify_package, verify_package_with_trust,
    ApprovalsBundle, VerifyStatus,
};
use treeship_core::statements::{
    approval_use_record_digest, journal_checkpoint_record_digest, ApprovalUse, CheckpointKind,
    JournalCheckpoint, ReplayCheckLevel, TYPE_APPROVAL_USE, TYPE_JOURNAL_CHECKPOINT,
};
use treeship_core::trust::{encode_ed25519_pubkey, TrustRoot, TrustRootKind, TrustRootStore};

/// Build a trust store that pins `pk` for hub-org-checkpoint verification.
/// Every hub-org test below uses this -- post-pin, `verify_package` reads
/// the operator's default trust roots from disk, but in-process tests need
/// to thread an explicit store via `verify_package_with_trust`.
fn trust_for_hub(pk: &ed25519_dalek::VerifyingKey) -> TrustRootStore {
    TrustRootStore::with_roots(vec![TrustRoot {
        key_id: "hub_test".into(),
        public_key: encode_ed25519_pubkey(pk),
        // Batch 5: hub-org checkpoint promotion is scoped to HubOrg.
        kind: TrustRootKind::HubOrg,
        label: "test hub".into(),
        added_at: "2026-05-15T00:00:00Z".into(),
    }])
}

// ---------------------------------------------------------------------------
// Fixture builders
// ---------------------------------------------------------------------------

fn make_use(use_id: &str, grant_id: &str, max_uses: u32) -> ApprovalUse {
    let mut u = ApprovalUse {
        type_: TYPE_APPROVAL_USE.into(),
        use_id: use_id.into(),
        grant_id: grant_id.into(),
        grant_digest: "sha256:00".into(),
        nonce_digest: "sha256:nn".into(),
        actor: "agent://deployer".into(),
        action: "deploy.production".into(),
        subject: "env://production".into(),
        session_id: None,
        action_artifact_id: None,
        receipt_digest: None,
        use_number: 1,
        max_uses: Some(max_uses),
        idempotency_key: None,
        created_at: "2026-04-30T08:00:00Z".into(),
        expires_at: None,
        previous_record_digest: String::new(),
        record_digest: String::new(),
        signature: None,
        signature_alg: None,
        signing_key_id: None,
    };
    u.record_digest = approval_use_record_digest(&u);
    u
}

fn sign_hub_checkpoint(sk: &SigningKey, use_ids: Vec<String>) -> JournalCheckpoint {
    let pk = sk.verifying_key();
    let mut cp = JournalCheckpoint {
        type_: TYPE_JOURNAL_CHECKPOINT.into(),
        checkpoint_id: "cp_hub_test".into(),
        checkpoint_kind: CheckpointKind::HubOrg,
        from_record_index: 1,
        to_record_index: use_ids.len() as u64,
        merkle_root: "sha256:demo".into(),
        leaf_count: use_ids.len() as u64,
        journal_id: "test-journal".into(),
        created_at: "2026-04-30T08:00:00Z".into(),
        hub_id: "hub://zerker-test".into(),
        hub_public_key: URL_SAFE_NO_PAD.encode(pk.to_bytes()),
        hub_signature: String::new(),
        signed_at: "2026-04-30T08:00:00Z".into(),
        covered_use_ids: use_ids,
        covered_grant_ids: Vec::new(),
        previous_record_digest: String::new(),
        record_digest: String::new(),
        signature: None,
        signature_alg: None,
        signing_key_id: None,
    };
    let payload = cp.canonical_hub_signing_bytes();
    let sig = sk.sign(&payload);
    cp.hub_signature = URL_SAFE_NO_PAD.encode(sig.to_bytes());
    cp.record_digest = journal_checkpoint_record_digest(&cp);
    cp
}

fn make_minimal_receipt() -> treeship_core::session::SessionReceipt {
    use treeship_core::session::{
        event::{EventType, SessionEvent},
        manifest::SessionManifest,
        receipt::{ArtifactEntry, ReceiptComposer},
    };
    let manifest = SessionManifest::new(
        "ssn_hub_test".into(),
        "agent://test".into(),
        "2026-04-30T08:00:00Z".into(),
        1745035200000,
    );
    let mk = |seq: u64, et: EventType| -> SessionEvent {
        SessionEvent {
            session_id: "ssn_hub_test".into(),
            event_id: format!("evt_{:016x}", seq),
            timestamp: format!("2026-04-30T08:00:{:02}Z", seq),
            sequence_no: seq,
            trace_id: "tr".into(),
            span_id: format!("sp_{seq}"),
            parent_span_id: None,
            agent_id: "agent://test".into(),
            agent_instance_id: "test".into(),
            agent_name: "test".into(),
            agent_role: None,
            host_id: "host_1".into(),
            tool_runtime_id: None,
            event_type: et,
            artifact_ref: None,
            meta: None,
        }
    };
    let events = vec![
        mk(0, EventType::SessionStarted),
        mk(
            1,
            EventType::AgentStarted {
                parent_agent_instance_id: None,
            },
        ),
        mk(
            2,
            EventType::AgentCompleted {
                termination_reason: None,
            },
        ),
        mk(
            3,
            EventType::SessionClosed {
                summary: None,
                duration_ms: None,
            },
        ),
    ];
    let artifacts = vec![ArtifactEntry {
        artifact_id: "art_use_1".into(),
        payload_type: "action".into(),
        digest: None,
        signed_at: None,
    }];
    ReceiptComposer::compose(&manifest, &events, artifacts)
}

fn build_package_with_bundle(bundle: ApprovalsBundle) -> std::path::PathBuf {
    let receipt = make_minimal_receipt();
    let tmp = std::env::temp_dir().join(format!("treeship-hub-test-{}", rand::random::<u32>()));
    let out = build_package_with_approvals(&receipt, &tmp, Some(&bundle)).unwrap();
    out.path
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

/// Acceptance: no Hub checkpoint embedded -> no replay-hub-org row.
/// The Approval Authority panel renders "- not checked" instead.
#[test]
fn no_hub_checkpoint_no_row() {
    let mut bundle = ApprovalsBundle::default();
    bundle.uses.push(make_use("use_a", "art_g", 1));
    let pkg = build_package_with_bundle(bundle);

    let checks = verify_package(&pkg).unwrap();
    let hub_rows: Vec<_> = checks
        .iter()
        .filter(|c| c.name == "replay-hub-org")
        .collect();
    assert!(
        hub_rows.is_empty(),
        "no hub-org row should be emitted: {:?}",
        hub_rows
    );
}

/// Acceptance: valid signed Hub checkpoint covering every use -> PASS.
#[test]
fn valid_hub_checkpoint_passes() {
    let sk = SigningKey::from_bytes(&[7u8; 32]);
    let trust = trust_for_hub(&sk.verifying_key());

    let mut bundle = ApprovalsBundle::default();
    let u = make_use("use_a", "art_g", 1);
    let cp = sign_hub_checkpoint(&sk, vec!["use_a".into()]);
    bundle.uses.push(u);
    bundle.checkpoints.push(cp);

    let pkg = build_package_with_bundle(bundle);
    let checks = verify_package_with_trust(&pkg, &trust).unwrap();
    let hub = checks
        .iter()
        .find(|c| c.name == "replay-hub-org")
        .expect("replay-hub-org row expected");
    assert_eq!(
        hub.status,
        VerifyStatus::Pass,
        "expected PASS, got: {hub:?}"
    );
    assert!(
        hub.detail.contains("verifies"),
        "detail should mention verification: {}",
        hub.detail
    );
}

/// Acceptance: tampered signature -> FAIL by default (audit lane J
/// fix-up). Previously this was WARN and --strict promoted to FAIL,
/// which let forged signatures exit 0 in default mode.
#[test]
fn tampered_hub_signature_fails_default() {
    let sk = SigningKey::from_bytes(&[8u8; 32]);
    let trust = trust_for_hub(&sk.verifying_key());

    let u = make_use("use_a", "art_g", 1);
    let mut cp = sign_hub_checkpoint(&sk, vec!["use_a".into()]);
    // Tamper: flip a coverage entry. canonical_hub_signing_bytes
    // changes -> stored signature no longer applies.
    cp.covered_use_ids.push("use_smuggled".into());

    let mut bundle = ApprovalsBundle::default();
    bundle.uses.push(u);
    bundle.checkpoints.push(cp);

    let pkg = build_package_with_bundle(bundle);
    let checks = verify_package_with_trust(&pkg, &trust).unwrap();
    let hub = checks
        .iter()
        .find(|c| c.name == "replay-hub-org")
        .expect("replay-hub-org row expected");
    assert_eq!(
        hub.status,
        VerifyStatus::Fail,
        "tampered signature must FAIL by default (not warn): {hub:?}"
    );
    assert!(
        hub.detail.contains("hub signature failed") || hub.detail.contains("tampered"),
        "detail should mention signature failure: {}",
        hub.detail,
    );
}

/// Acceptance: signed checkpoint that DOESN'T cover the package's
/// uses -> WARN. The signature verifies but coverage is incomplete.
#[test]
fn hub_checkpoint_missing_use_coverage_warns() {
    let sk = SigningKey::from_bytes(&[9u8; 32]);
    let trust = trust_for_hub(&sk.verifying_key());

    let u_a = make_use("use_a", "art_g", 1);
    let u_b = make_use("use_b", "art_g", 1);
    // Checkpoint only covers use_a; use_b is uncovered.
    let cp = sign_hub_checkpoint(&sk, vec!["use_a".into()]);

    let mut bundle = ApprovalsBundle::default();
    bundle.uses.push(u_a);
    bundle.uses.push(u_b);
    bundle.checkpoints.push(cp);

    let pkg = build_package_with_bundle(bundle);
    let checks = verify_package_with_trust(&pkg, &trust).unwrap();
    let hub = checks
        .iter()
        .find(|c| c.name == "replay-hub-org")
        .expect("replay-hub-org row expected");
    assert_eq!(
        hub.status,
        VerifyStatus::Warn,
        "expected WARN on missing coverage, got: {hub:?}"
    );
    assert!(
        hub.detail.contains("does not cover") || hub.detail.contains("not cover"),
        "detail should mention coverage gap: {}",
        hub.detail
    );
}

/// Acceptance: missing required Hub field -> WARN with which field
/// is missing.
#[test]
fn hub_checkpoint_missing_field_warns() {
    let sk = SigningKey::from_bytes(&[10u8; 32]);
    let trust = trust_for_hub(&sk.verifying_key());

    let u = make_use("use_a", "art_g", 1);
    let mut cp = sign_hub_checkpoint(&sk, vec!["use_a".into()]);
    cp.hub_id = String::new(); // explicitly clear required field

    let mut bundle = ApprovalsBundle::default();
    bundle.uses.push(u);
    bundle.checkpoints.push(cp);

    let pkg = build_package_with_bundle(bundle);
    let checks = verify_package_with_trust(&pkg, &trust).unwrap();
    let hub = checks
        .iter()
        .find(|c| c.name == "replay-hub-org")
        .expect("replay-hub-org row expected");
    assert_eq!(hub.status, VerifyStatus::Warn);
    assert!(
        hub.detail.contains("hub_id"),
        "detail should name missing field: {}",
        hub.detail
    );
}

/// Trust pin: a checkpoint signed by a key not in the operator's
/// trust store must surface as UntrustedIssuer and FAIL by default
/// (not warn). This is the headline audit fix -- previously a
/// self-signed checkpoint passed silently, then was downgraded to a
/// WARN that exited 0 unless the user remembered `--strict`. Now any
/// untrusted-issuer or tampered hub signature is a hard failure
/// regardless of strict mode.
#[test]
fn hub_checkpoint_with_untrusted_issuer_fails() {
    let attacker_sk = SigningKey::from_bytes(&[42u8; 32]);
    // Operator trusts a DIFFERENT issuer.
    let honest_sk = SigningKey::from_bytes(&[7u8; 32]);
    let trust = trust_for_hub(&honest_sk.verifying_key());

    let mut bundle = ApprovalsBundle::default();
    bundle.uses.push(make_use("use_a", "art_g", 1));
    bundle
        .checkpoints
        .push(sign_hub_checkpoint(&attacker_sk, vec!["use_a".into()]));

    let pkg = build_package_with_bundle(bundle);
    let checks = verify_package_with_trust(&pkg, &trust).unwrap();
    let hub = checks
        .iter()
        .find(|c| c.name == "replay-hub-org")
        .expect("replay-hub-org row expected");
    assert_eq!(
        hub.status,
        VerifyStatus::Fail,
        "untrusted-issuer must FAIL by default (not warn): {hub:?}"
    );
    assert!(
        hub.detail.contains("not a trusted root") || hub.detail.contains("treeship trust add"),
        "detail must reference the trust remediation: {}",
        hub.detail
    );
}

/// Acceptance: a LocalJournal-kind checkpoint must NOT promote
/// replay-hub-org. The discriminator is what makes this safe -- a
/// well-formed local checkpoint without Hub fields shouldn't be
/// confusable for a Hub checkpoint just because it shares the JSON shape.
#[test]
fn local_journal_kind_does_not_promote_hub_org() {
    let mut cp = JournalCheckpoint {
        type_: TYPE_JOURNAL_CHECKPOINT.into(),
        checkpoint_id: "cp_local_only".into(),
        checkpoint_kind: CheckpointKind::LocalJournal,
        from_record_index: 1,
        to_record_index: 1,
        merkle_root: "sha256:00".into(),
        leaf_count: 1,
        journal_id: "journal".into(),
        created_at: "2026-04-30T08:00:00Z".into(),
        hub_id: String::new(),
        hub_public_key: String::new(),
        hub_signature: String::new(),
        signed_at: String::new(),
        covered_use_ids: Vec::new(),
        covered_grant_ids: Vec::new(),
        previous_record_digest: String::new(),
        record_digest: String::new(),
        signature: None,
        signature_alg: None,
        signing_key_id: None,
    };
    cp.record_digest = journal_checkpoint_record_digest(&cp);

    let mut bundle = ApprovalsBundle::default();
    bundle.uses.push(make_use("use_a", "art_g", 1));
    bundle.checkpoints.push(cp);

    let pkg = build_package_with_bundle(bundle);
    let checks = verify_package(&pkg).unwrap();
    let hub = checks.iter().find(|c| c.name == "replay-hub-org");
    assert!(
        hub.is_none(),
        "local-journal-kind checkpoint must not emit replay-hub-org row"
    );

    // included-checkpoint should still pass for the local-kind one.
    let inc = checks
        .iter()
        .find(|c| c.name == "replay-included-checkpoint");
    assert!(
        inc.is_some(),
        "included-checkpoint row should still appear for local kind"
    );
}

/// Smoke: bundle round-trips through write/read; the kind discriminator
/// survives serialization. Pre-PR-6 packages (no checkpoint_kind field)
/// deserialize as LocalJournal.
#[test]
fn checkpoint_kind_round_trip() {
    let sk = SigningKey::from_bytes(&[11u8; 32]);
    let u = make_use("use_a", "art_g", 1);
    let cp = sign_hub_checkpoint(&sk, vec!["use_a".into()]);

    let mut bundle = ApprovalsBundle::default();
    bundle.uses.push(u);
    bundle.checkpoints.push(cp.clone());

    let pkg = build_package_with_bundle(bundle);
    let read = read_approvals_bundle(&pkg).unwrap();
    assert_eq!(read.checkpoints.len(), 1);
    assert_eq!(read.checkpoints[0].checkpoint_kind, CheckpointKind::HubOrg);
    assert_eq!(read.checkpoints[0].hub_id, "hub://zerker-test");

    // Hand-craft a JSON that omits checkpoint_kind (pre-PR-6 shape).
    let json: Value = serde_json::from_value(serde_json::json!({
        "type": TYPE_JOURNAL_CHECKPOINT,
        "checkpoint_id": "cp_legacy",
        "from_record_index": 1,
        "to_record_index": 1,
        "merkle_root": "sha256:0",
        "leaf_count": 1,
        "journal_id": "j",
        "created_at": "2026-04-30T08:00:00Z",
    }))
    .unwrap();
    let cp_legacy: JournalCheckpoint = serde_json::from_value(json).unwrap();
    assert_eq!(cp_legacy.checkpoint_kind, CheckpointKind::LocalJournal);

    // Tag the unused-import warning silenced.
    let _ = ReplayCheckLevel::HubOrg;
}