acdp-cli 0.1.2

Command-line client (`acdp` binary) for the Agent Context Distribution Protocol (ACDP)
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
//! Subprocess integration tests for the `acdp` CLI binary.
//!
//! Gated on the `cli` feature; the binary path is provided by Cargo via
//! the `CARGO_BIN_EXE_acdp` env var. The tests drive the binary as a
//! black box (stdin / stdout / exit code) so they catch UX regressions
//! that unit tests would miss.

use std::io::Write;
use std::process::{Command, Stdio};

use serde_json::json;
use wiremock::{
    matchers::{method, path},
    Mock, MockServer, ResponseTemplate,
};

fn acdp_bin() -> Command {
    let mut cmd = Command::new(env!("CARGO_BIN_EXE_acdp"));
    // The CLI applies the full SSRF / HTTPS-only posture by default
    // (P0-1). These tests drive an in-process `wiremock` registry over
    // plain HTTP on loopback, so opt into the documented test-only
    // permissive transport.
    cmd.env("ACDP_INSECURE_TRANSPORT", "1");
    cmd
}

/// Run the CLI with the given args + stdin, return `(exit_code, stdout, stderr)`.
fn run_cli(args: &[&str], stdin_payload: Option<&str>) -> (i32, String, String) {
    let mut child = acdp_bin()
        .args(args)
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .expect("spawn acdp binary");
    if let Some(payload) = stdin_payload {
        child
            .stdin
            .as_mut()
            .expect("stdin pipe")
            .write_all(payload.as_bytes())
            .expect("write stdin");
    }
    let out = child.wait_with_output().expect("wait acdp");
    (
        out.status.code().unwrap_or(-1),
        String::from_utf8_lossy(&out.stdout).into_owned(),
        String::from_utf8_lossy(&out.stderr).into_owned(),
    )
}

// ── publish ───────────────────────────────────────────────────────────────────

/// FEAT-04 — `acdp publish` posts to `POST /contexts` and prints the
/// registry's PublishResponse. Mocks the registry with wiremock over
/// plain HTTP (reqwest's rustls TLS backend handles both schemes).
#[tokio::test]
async fn cli_publish_against_mocked_registry() {
    let registry = MockServer::start().await;
    let response_body = json!({
        "ctx_id": "acdp://r.example.com/12345678-1234-4321-8123-123456781234",
        "lineage_id": "lin:sha256:b14ccd2a8b34530309255db68c151a10689b6a82feb30aff9222d54fdd871720",
        "version": 1,
        "created_at": "2026-05-10T00:00:00.000Z",
        "status": "active",
    });

    Mock::given(method("POST"))
        .and(path("/contexts"))
        .respond_with(ResponseTemplate::new(201).set_body_json(response_body.clone()))
        .mount(&registry)
        .await;

    let seed_hex = "0".repeat(64); // all-zeros — test seed only
    let url = registry.uri();

    let (code, stdout, stderr) = run_cli(
        &[
            "publish",
            &url,
            "--key-seed",
            &seed_hex,
            "--agent-id",
            "did:web:agents.example.com:test",
            "--key-id",
            "did:web:agents.example.com:test#key-1",
            "--title",
            "cli test",
            "--type",
            "data_snapshot",
            "--visibility",
            "public",
        ],
        Some(""), // empty stdin
    );

    assert_eq!(
        code, 0,
        "publish must exit 0 on success; stderr={stderr}, stdout={stdout}"
    );
    let parsed: serde_json::Value =
        serde_json::from_str(&stdout).expect("publish stdout must be JSON");
    assert_eq!(parsed["ctx_id"], response_body["ctx_id"]);
    assert_eq!(parsed["version"], 1);

    // Verify the request body wiremock recorded matches what we asked
    // the CLI to publish. Catches regressions where flag values fail
    // to plumb through to the producer builder.
    let requests = registry
        .received_requests()
        .await
        .expect("recorded requests");
    let last = requests
        .last()
        .expect("publish MUST have made at least one request");
    let sent: acdp::types::PublishRequest =
        serde_json::from_slice(&last.body).expect("posted body MUST deserialize as PublishRequest");
    assert_eq!(sent.title, "cli test");
    assert!(
        matches!(sent.context_type, acdp::types::ContextType::DataSnapshot),
        "type flag did not propagate"
    );
    assert_eq!(sent.agent_id.as_str(), "did:web:agents.example.com:test");
    assert_eq!(sent.signature.algorithm, "ed25519");
    assert_eq!(
        sent.signature.value.len(),
        88,
        "ed25519 signature MUST be 88 base64 chars"
    );
    // Hash matches what the producer would have computed locally for
    // exactly this ProducerContent — confirms the CLI didn't drop or
    // mangle a producer-controlled field.
    let req_value = serde_json::to_value(&sent).expect("re-serialize");
    let recomputed =
        acdp::crypto::compute_content_hash(&req_value).expect("recompute content_hash");
    assert_eq!(
        sent.content_hash, recomputed,
        "posted content_hash MUST match recomputation over the body the CLI built"
    );
}

/// FEAT-02 — `--key-algorithm ecdsa-p256` builds a P256 producer.
/// The posted body MUST carry `signature.algorithm = "ecdsa-p256"`
/// and an 88-char IEEE-1363 base64 signature.
#[tokio::test]
async fn cli_publish_with_ecdsa_p256_key() {
    let registry = MockServer::start().await;
    let response_body = json!({
        "ctx_id": "acdp://r.example.com/12345678-1234-4321-8123-123456781234",
        "lineage_id": "lin:sha256:b14ccd2a8b34530309255db68c151a10689b6a82feb30aff9222d54fdd871720",
        "version": 1,
        "created_at": "2026-05-18T00:00:00.000Z",
        "status": "active",
    });
    Mock::given(method("POST"))
        .and(path("/contexts"))
        .respond_with(ResponseTemplate::new(201).set_body_json(response_body))
        .mount(&registry)
        .await;

    // Use scalar=1 (the sig-002 golden seed) — guaranteed valid.
    let seed_hex = format!("{:0>64}", "1");
    let (code, stdout, stderr) = run_cli(
        &[
            "publish",
            &registry.uri(),
            "--key-seed",
            &seed_hex,
            "--key-algorithm",
            "ecdsa-p256",
            "--agent-id",
            "did:web:agents.example.com:test",
            "--key-id",
            "did:web:agents.example.com:test#key-1",
            "--title",
            "p256 cli test",
            "--type",
            "data_snapshot",
        ],
        None,
    );
    assert_eq!(
        code, 0,
        "p256 publish MUST succeed; stderr={stderr}, stdout={stdout}"
    );

    let requests = registry
        .received_requests()
        .await
        .expect("recorded requests");
    let last = requests.last().expect("at least one request");
    let sent: acdp::types::PublishRequest =
        serde_json::from_slice(&last.body).expect("posted body parses as PublishRequest");
    assert_eq!(
        sent.signature.algorithm, "ecdsa-p256",
        "CLI MUST emit `ecdsa-p256` algorithm string when --key-algorithm requests it"
    );
    assert_eq!(
        sent.signature.value.len(),
        88,
        "p256 wire signature MUST be 88 base64 chars (IEEE 1363 r‖s)"
    );
}

/// FEAT-02 — unknown `--key-algorithm` is a usage error.
#[test]
fn cli_publish_rejects_unknown_key_algorithm() {
    let seed_hex = "0".repeat(64);
    let (code, _stdout, stderr) = run_cli(
        &[
            "publish",
            "http://unused.example.com",
            "--key-seed",
            &seed_hex,
            "--key-algorithm",
            "rsa-2048",
            "--agent-id",
            "did:web:agents.example.com:test",
            "--key-id",
            "did:web:agents.example.com:test#key-1",
            "--title",
            "x",
            "--type",
            "data_snapshot",
        ],
        None,
    );
    assert_eq!(
        code, 1,
        "unknown --key-algorithm MUST exit 1; stderr={stderr}"
    );
    assert!(
        stderr.contains("rsa-2048") || stderr.contains("--key-algorithm"),
        "stderr MUST mention the bad algorithm, got: {stderr}"
    );
}

/// FEAT-04 — `--idempotency-key` is forwarded as a request header. We
/// match the request having the header set.
#[tokio::test]
async fn cli_publish_forwards_idempotency_key() {
    let registry = MockServer::start().await;
    let response_body = json!({
        "ctx_id": "acdp://r.example.com/12345678-1234-4321-8123-123456781234",
        "lineage_id": "lin:sha256:b14ccd2a8b34530309255db68c151a10689b6a82feb30aff9222d54fdd871720",
        "version": 1,
        "created_at": "2026-05-10T00:00:00.000Z",
        "status": "active",
    });

    Mock::given(method("POST"))
        .and(path("/contexts"))
        .and(wiremock::matchers::header(
            "Idempotency-Key",
            "11111111-2222-3333-4444-555555555555",
        ))
        .respond_with(ResponseTemplate::new(201).set_body_json(response_body))
        .mount(&registry)
        .await;

    let seed_hex = "0".repeat(64);
    let url = registry.uri();
    let (code, stdout, stderr) = run_cli(
        &[
            "publish",
            &url,
            "--key-seed",
            &seed_hex,
            "--agent-id",
            "did:web:agents.example.com:test",
            "--key-id",
            "did:web:agents.example.com:test#key-1",
            "--title",
            "idem test",
            "--type",
            "data_snapshot",
            "--idempotency-key",
            "11111111-2222-3333-4444-555555555555",
        ],
        None,
    );
    assert_eq!(
        code, 0,
        "idem publish must succeed; stderr={stderr}, stdout={stdout}"
    );
}

/// IMP-01 — the stdin overlay supports `data_period` and `schema_uri`.
/// Both are structural fields with no CLI flag; the overlay MUST plumb
/// them into the posted `PublishRequest`.
#[tokio::test]
async fn cli_publish_overlay_data_period_and_schema_uri() {
    let registry = MockServer::start().await;
    let response_body = json!({
        "ctx_id": "acdp://r.example.com/12345678-1234-4321-8123-123456781234",
        "lineage_id": "lin:sha256:b14ccd2a8b34530309255db68c151a10689b6a82feb30aff9222d54fdd871720",
        "version": 1,
        "created_at": "2026-05-10T00:00:00.000Z",
        "status": "active",
    });
    Mock::given(method("POST"))
        .and(path("/contexts"))
        .respond_with(ResponseTemplate::new(201).set_body_json(response_body))
        .mount(&registry)
        .await;

    let seed_hex = "0".repeat(64);
    let url = registry.uri();
    let overlay = json!({
        "data_period": {
            "start": "2026-01-01T00:00:00.000Z",
            "end": "2026-03-31T00:00:00.000Z"
        },
        "schema_uri": "https://schemas.example.com/snapshot.json"
    })
    .to_string();
    let (code, stdout, stderr) = run_cli(
        &[
            "publish",
            &url,
            "--key-seed",
            &seed_hex,
            "--agent-id",
            "did:web:agents.example.com:test",
            "--key-id",
            "did:web:agents.example.com:test#key-1",
            "--title",
            "overlay test",
            "--type",
            "data_snapshot",
        ],
        Some(&overlay),
    );
    assert_eq!(
        code, 0,
        "overlay publish must succeed; stderr={stderr}, stdout={stdout}"
    );
    let requests = registry.received_requests().await.expect("recorded");
    let last = requests.last().expect("a request");
    let sent: acdp::types::PublishRequest =
        serde_json::from_slice(&last.body).expect("posted body deserializes");
    assert!(sent.data_period.is_some(), "data_period overlay dropped");
    assert_eq!(
        sent.schema_uri.as_deref(),
        Some("https://schemas.example.com/snapshot.json"),
        "schema_uri overlay dropped"
    );
}

/// IMP-01 — an unknown overlay key is a usage error, not silently
/// ignored. Catches the trap where e.g. a misspelled `expires_at`
/// publishes a context with no expiry.
#[test]
fn cli_publish_overlay_rejects_unknown_key() {
    let seed_hex = "0".repeat(64);
    let overlay = json!({ "expirez_at": "2026-12-31T00:00:00Z" }).to_string();
    let (code, _stdout, stderr) = run_cli(
        &[
            "publish",
            "http://unused.example.com",
            "--key-seed",
            &seed_hex,
            "--agent-id",
            "did:web:agents.example.com:test",
            "--key-id",
            "did:web:agents.example.com:test#key-1",
            "--title",
            "x",
            "--type",
            "data_snapshot",
        ],
        Some(&overlay),
    );
    assert_eq!(code, 1, "unknown overlay key MUST exit 1; stderr={stderr}");
    assert!(
        stderr.contains("expirez_at") || stderr.contains("unknown publish overlay field"),
        "stderr MUST name the bad overlay key, got: {stderr}"
    );
}

// ── validate ──────────────────────────────────────────────────────────────────

/// FEAT-05 — `acdp validate` runs offline schema validation and
/// reports both the declared and recomputed content_hash so users can
/// see whether the body is internally consistent.
#[test]
fn cli_validate_accepts_well_formed_request() {
    let req = json!({
        "version": 1,
        "supersedes": null,
        "agent_id": "did:web:agents.example.com:test",
        "contributors": [],
        "title": "validate test",
        "type": "data_snapshot",
        "data_refs": [],
        "derived_from": [],
        "visibility": "public",
        "content_hash": "sha256:0000000000000000000000000000000000000000000000000000000000000000",
        "signature": {
            "algorithm": "ed25519",
            "key_id": "did:web:agents.example.com:test#key-1",
            "value": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=="
        }
    });
    let dir = std::env::temp_dir();
    let path = dir.join(format!("acdp-validate-test-{}.json", std::process::id()));
    std::fs::write(&path, serde_json::to_vec(&req).unwrap()).unwrap();

    let (code, stdout, stderr) = run_cli(&["validate", path.to_str().unwrap()], None);
    let _ = std::fs::remove_file(&path);
    assert_eq!(code, 0, "validate must accept; stderr={stderr}");
    let parsed: serde_json::Value =
        serde_json::from_str(&stdout).expect("validate stdout must be JSON");
    assert_eq!(parsed["ok"], true);
    assert!(parsed.get("content_hash_recomputed").is_some());
}

/// FEAT-05 — `acdp validate` exits non-zero and emits an error envelope
/// for schema-invalid input.
#[test]
fn cli_validate_rejects_v1_with_lineage_id() {
    let req = json!({
        "version": 1,
        "supersedes": null,
        "lineage_id": "lin:sha256:1111111111111111111111111111111111111111111111111111111111111111",
        "agent_id": "did:web:agents.example.com:test",
        "contributors": [],
        "title": "v1+lineage rejected",
        "type": "data_snapshot",
        "data_refs": [],
        "derived_from": [],
        "visibility": "public",
        "content_hash": "sha256:0000000000000000000000000000000000000000000000000000000000000000",
        "signature": {
            "algorithm": "ed25519",
            "key_id": "did:web:agents.example.com:test#key-1",
            "value": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=="
        }
    });
    let dir = std::env::temp_dir();
    let path = dir.join(format!("acdp-validate-bad-{}.json", std::process::id()));
    std::fs::write(&path, serde_json::to_vec(&req).unwrap()).unwrap();

    let (code, stdout, _stderr) = run_cli(&["validate", path.to_str().unwrap()], None);
    let _ = std::fs::remove_file(&path);
    assert_eq!(
        code, 2,
        "validate of v1+lineage MUST exit 2 (protocol error)"
    );
    let parsed: serde_json::Value =
        serde_json::from_str(&stdout).expect("validate error stdout must be JSON envelope");
    assert_eq!(parsed["error"]["code"], "schema_violation");
}

// ── usage / unknown subcommand ───────────────────────────────────────────────

/// Plain usage output: invoking `acdp` with no args exits 1 and prints
/// the usage line on stderr. Catches regressions in arg parsing.
#[test]
fn cli_no_args_prints_usage_and_exits_1() {
    let (code, stdout, stderr) = run_cli(&[], None);
    assert_eq!(code, 1, "no-args MUST exit 1");
    assert!(stdout.is_empty());
    assert!(
        stderr.contains("USAGE"),
        "stderr MUST include usage line; got: {stderr}"
    );
}

/// `acdp publish` includes the new command in the usage block.
#[test]
fn cli_help_lists_new_commands() {
    let (code, _stdout, stderr) = run_cli(&["help"], None);
    assert_eq!(code, 0);
    assert!(stderr.contains("acdp publish"));
    assert!(stderr.contains("acdp validate"));
    assert!(stderr.contains("acdp resolve"));
}

// ── resolve ──────────────────────────────────────────────────────────────────

/// FEAT-05 — `acdp resolve` with no args exits 1 (usage error) and
/// prints the usage line on stderr.
#[test]
fn cli_resolve_no_args_exits_usage_error() {
    let (code, stdout, stderr) = run_cli(&["resolve"], None);
    assert_eq!(code, 1, "resolve with no args MUST exit 1 (usage error)");
    assert!(stdout.is_empty());
    assert!(
        stderr.contains("`resolve` requires") || stderr.contains("USAGE"),
        "stderr MUST surface the missing-arg message, got: {stderr}"
    );
}

/// FEAT-05 — `acdp resolve <malformed>` surfaces a protocol error
/// envelope on stdout and exits 2. The malformed ctx_id is caught at
/// parse time inside `CrossRegistryResolver::resolve`; no network is
/// touched.
#[test]
fn cli_resolve_malformed_ctx_id_exits_protocol_error() {
    let (code, stdout, stderr) = run_cli(&["resolve", "not-a-ctx-id"], None);
    assert_eq!(
        code, 2,
        "resolve with malformed ctx_id MUST exit 2 (protocol error); stderr={stderr}"
    );
    let parsed: serde_json::Value =
        serde_json::from_str(&stdout).expect("resolve error envelope MUST be JSON");
    assert!(
        parsed["error"]["code"].is_string(),
        "error envelope MUST carry an `error.code` string, got {parsed}"
    );
}

/// FEAT-05 — `acdp resolve --max-depth bad-int` is a flag-parse error
/// (exit 1), not a protocol error. Catches the easy-to-overlook case
/// where flag-handling errors should surface as user errors, not
/// network errors.
#[test]
fn cli_resolve_bad_max_depth_exits_usage_error() {
    let (code, _stdout, stderr) = run_cli(
        &[
            "resolve",
            "acdp://r.example.com/12345678-1234-4321-8123-123456781234",
            "--max-depth",
            "not-a-number",
        ],
        None,
    );
    assert_eq!(code, 1, "bad --max-depth MUST exit 1 (usage error)");
    assert!(
        stderr.contains("--max-depth") || stderr.contains("invalid"),
        "stderr MUST mention the bad flag, got: {stderr}"
    );
}