jacs-cli 0.11.3

JACS CLI: command-line interface for JSON AI Communication Standard
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
//! CLI integration tests for `jacs sign-image`, `jacs verify-image`,
//! `jacs extract-media-signature`. PRD §3.2 / §4.2.
//!
//! Generates fixtures in-process via the `image` crate (PNG + JPEG only;
//! WebP is built byte-by-byte as a minimal RIFF container — same approach
//! as `jacs/tests/image_signature_tests.rs`).

use assert_cmd::Command;
use predicates::prelude::*;
use std::path::{Path, PathBuf};
use tempfile::TempDir;

const TEST_PASSWORD: &str = "TestSignImage!2026";

fn cmd() -> Command {
    let mut c = Command::cargo_bin("jacs").expect("jacs binary should exist");
    c.env("JACS_PRIVATE_KEY_PASSWORD", TEST_PASSWORD);
    c
}

fn fresh_tmpdir() -> TempDir {
    TempDir::new().expect("tmpdir")
}

/// Bootstrap a persistent agent in `dir` via `jacs quickstart`. Required for
/// sign + verify across multiple CLI invocations to use the same agent key.
fn bootstrap_agent(dir: &TempDir, algorithm: &str) {
    cmd()
        .current_dir(dir.path())
        .args([
            "quickstart",
            "--algorithm",
            algorithm,
            "--name",
            "test-agent",
            "--domain",
            "localhost",
        ])
        .assert()
        .success();
}

// ============================================================================
// Fixtures
// ============================================================================

fn make_png(width: u32, height: u32) -> Vec<u8> {
    let img = image::RgbaImage::from_pixel(width, height, image::Rgba([32, 64, 128, 255]));
    let mut buf = Vec::new();
    let mut cur = std::io::Cursor::new(&mut buf);
    img.write_to(&mut cur, image::ImageFormat::Png)
        .expect("png encode");
    buf
}

fn make_jpeg(width: u32, height: u32) -> Vec<u8> {
    let img = image::RgbImage::from_pixel(width, height, image::Rgb([200, 150, 100]));
    let mut buf = Vec::new();
    let mut cur = std::io::Cursor::new(&mut buf);
    let encoder = image::codecs::jpeg::JpegEncoder::new_with_quality(&mut cur, 95);
    img.write_with_encoder(encoder).expect("jpeg encode");
    buf
}

/// Minimal valid WebP RIFF container — chunk-level only, no decodable
/// pixels. Matches the fixture pattern in jacs/tests/image_signature_tests.rs.
fn make_webp() -> Vec<u8> {
    fn build_chunk(fourcc: &[u8; 4], body: &[u8]) -> Vec<u8> {
        let mut out = Vec::with_capacity(8 + body.len() + 1);
        out.extend_from_slice(fourcc);
        out.extend_from_slice(&(body.len() as u32).to_le_bytes());
        out.extend_from_slice(body);
        if body.len() % 2 == 1 {
            out.push(0);
        }
        out
    }
    let body = vec![0u8; 4];
    let mut chunks = Vec::new();
    chunks.extend_from_slice(b"WEBP");
    chunks.extend_from_slice(&build_chunk(b"VP8L", &body));
    let riff_size = chunks.len() as u32;
    let mut out = Vec::new();
    out.extend_from_slice(b"RIFF");
    out.extend_from_slice(&riff_size.to_le_bytes());
    out.extend_from_slice(&chunks);
    out
}

fn write_fixture(dir: &TempDir, name: &str, bytes: &[u8]) -> PathBuf {
    let path = dir.path().join(name);
    std::fs::write(&path, bytes).expect("write fixture");
    path
}

fn signed_size(path: &Path) -> u64 {
    std::fs::metadata(path).map(|m| m.len()).unwrap_or(0)
}

// ============================================================================
// sign-image — formats + flags
// ============================================================================

#[test]
fn sign_image_png_exit_zero() {
    let dir = fresh_tmpdir();
    bootstrap_agent(&dir, "ed25519");
    let in_path = write_fixture(&dir, "in.png", &make_png(32, 32));
    let out_path = dir.path().join("out.png");

    cmd()
        .current_dir(dir.path())
        .args(["sign-image"])
        .arg(in_path.to_str().unwrap())
        .args(["--out"])
        .arg(out_path.to_str().unwrap())
        .assert()
        .success();
    assert!(out_path.exists(), "signed PNG must be written");
    assert!(signed_size(&out_path) > 0);
}

#[test]
fn sign_image_jpeg_exit_zero() {
    let dir = fresh_tmpdir();
    bootstrap_agent(&dir, "ed25519");
    let in_path = write_fixture(&dir, "in.jpg", &make_jpeg(32, 32));
    let out_path = dir.path().join("out.jpg");

    cmd()
        .current_dir(dir.path())
        .args(["sign-image"])
        .arg(in_path.to_str().unwrap())
        .args(["--out"])
        .arg(out_path.to_str().unwrap())
        .assert()
        .success();
    assert!(out_path.exists());
}

#[test]
fn sign_image_webp_exit_zero() {
    let dir = fresh_tmpdir();
    bootstrap_agent(&dir, "ed25519");
    let in_path = write_fixture(&dir, "in.webp", &make_webp());
    let out_path = dir.path().join("out.webp");

    cmd()
        .current_dir(dir.path())
        .args(["sign-image"])
        .arg(in_path.to_str().unwrap())
        .args(["--out"])
        .arg(out_path.to_str().unwrap())
        .assert()
        .success();
    assert!(out_path.exists());
}

#[test]
fn sign_image_robust_flag_round_trip() {
    let dir = fresh_tmpdir();
    bootstrap_agent(&dir, "ed25519");
    // Robust mode embeds the JACS signed-document JSON via LSB. Need a
    // sufficiently large image — 256x256 RGBA = 65536 pixels = ~32 KiB
    // theoretical capacity (4 bits per pixel after LSB), enough for the
    // ~2 KiB JACS signed-document payload.
    let in_path = write_fixture(&dir, "in.png", &make_png(256, 256));
    let out_path = dir.path().join("out.png");

    cmd()
        .current_dir(dir.path())
        .args(["sign-image", "--robust"])
        .arg(in_path.to_str().unwrap())
        .args(["--out"])
        .arg(out_path.to_str().unwrap())
        .assert()
        .success();

    // Robust mode writes LSB-only (no metadata chunk) per Wave 2a handoff —
    // verify must use --robust to find the payload.
    cmd()
        .current_dir(dir.path())
        .args(["verify-image", "--robust"])
        .arg(out_path.to_str().unwrap())
        .assert()
        .success();
}

#[test]
fn sign_image_format_override() {
    // --format png on a renamed file (extension doesn't match) still works
    // because the actual magic bytes match the explicit hint.
    let dir = fresh_tmpdir();
    bootstrap_agent(&dir, "ed25519");
    let in_path = write_fixture(&dir, "in.bin", &make_png(32, 32));
    let out_path = dir.path().join("out.png");

    cmd()
        .current_dir(dir.path())
        .args(["sign-image", "--format", "png"])
        .arg(in_path.to_str().unwrap())
        .args(["--out"])
        .arg(out_path.to_str().unwrap())
        .assert()
        .success();
    assert!(out_path.exists());
}

// ============================================================================
// verify-image — strict / permissive
// ============================================================================

#[test]
fn verify_image_permissive_missing_signature_exit_two() {
    let dir = fresh_tmpdir();
    let path = write_fixture(&dir, "unsigned.png", &make_png(32, 32));

    cmd()
        .current_dir(dir.path())
        .args(["verify-image"])
        .arg(path.to_str().unwrap())
        .assert()
        .code(2)
        .stderr(predicate::str::contains("no JACS signature found"));
}

#[test]
fn verify_image_strict_missing_signature_exit_one() {
    let dir = fresh_tmpdir();
    let path = write_fixture(&dir, "unsigned.png", &make_png(32, 32));

    cmd()
        .current_dir(dir.path())
        .args(["verify-image", "--strict"])
        .arg(path.to_str().unwrap())
        .assert()
        .code(1)
        .stderr(predicate::str::contains("no JACS signature found"));
}

#[test]
fn verify_image_strict_valid_exit_zero() {
    let dir = fresh_tmpdir();
    bootstrap_agent(&dir, "ed25519");
    let in_path = write_fixture(&dir, "in.png", &make_png(32, 32));
    let out_path = dir.path().join("out.png");

    cmd()
        .current_dir(dir.path())
        .args(["sign-image"])
        .arg(in_path.to_str().unwrap())
        .args(["--out"])
        .arg(out_path.to_str().unwrap())
        .assert()
        .success();

    cmd()
        .current_dir(dir.path())
        .args(["verify-image", "--strict"])
        .arg(out_path.to_str().unwrap())
        .assert()
        .success();
}

// ============================================================================
// extract-media-signature — decoded vs raw
// ============================================================================

fn sign_format(dir: &TempDir, fmt: &str) -> PathBuf {
    let in_name = format!("in.{}", fmt);
    let out_name = format!("out.{}", fmt);
    let bytes = match fmt {
        "png" => make_png(32, 32),
        "jpg" | "jpeg" => make_jpeg(32, 32),
        "webp" => make_webp(),
        _ => panic!("unsupported fmt"),
    };
    let in_path = write_fixture(dir, &in_name, &bytes);
    let out_path = dir.path().join(out_name);
    cmd()
        .current_dir(dir.path())
        .args(["sign-image"])
        .arg(in_path.to_str().unwrap())
        .args(["--out"])
        .arg(out_path.to_str().unwrap())
        .assert()
        .success();
    out_path
}

#[test]
fn extract_media_signature_prints_decoded_json_by_default() {
    for fmt in ["png", "jpg", "webp"] {
        let dir = fresh_tmpdir();
        bootstrap_agent(&dir, "ed25519");
        let signed = sign_format(&dir, fmt);
        let output = cmd()
            .current_dir(dir.path())
            .args(["extract-media-signature"])
            .arg(signed.to_str().unwrap())
            .assert()
            .success()
            .get_output()
            .stdout
            .clone();
        // Default behaviour: decoded JSON. Must parse, must contain
        // mediaSignatureVersion field.
        let value: serde_json::Value = serde_json::from_slice(&output).unwrap_or_else(|e| {
            panic!(
                "extract-media-signature default must emit parseable JSON for {}: {}",
                fmt, e
            )
        });
        let stdout_str = String::from_utf8_lossy(&output);
        assert!(
            stdout_str.contains("mediaSignatureVersion"),
            "decoded JSON must contain mediaSignatureVersion field for {}: got {}",
            fmt,
            stdout_str
        );
        // Sanity: it's an object/structure (not just a number).
        assert!(
            value.is_object() || value.is_array(),
            "JSON must be a structure for {}",
            fmt
        );
    }
}

#[test]
fn extract_media_signature_raw_payload_prints_base64url() {
    let dir = fresh_tmpdir();
    bootstrap_agent(&dir, "ed25519");
    let signed = sign_format(&dir, "png");
    let output = cmd()
        .current_dir(dir.path())
        .args(["extract-media-signature", "--raw-payload"])
        .arg(signed.to_str().unwrap())
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let s = String::from_utf8_lossy(&output);
    assert!(
        s.chars().all(|c| {
            c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == '=' || c == '\n' || c == '\r'
        }),
        "raw-payload must contain only base64url chars (and newlines); got {:?}",
        s.chars()
            .filter(|c| !(c.is_ascii_alphanumeric()
                || *c == '-'
                || *c == '_'
                || *c == '='
                || *c == '\n'
                || *c == '\r'))
            .collect::<String>()
    );
    // Confirm it really is base64url (would not parse as JSON).
    assert!(
        serde_json::from_slice::<serde_json::Value>(&output).is_err(),
        "raw payload should NOT be valid JSON"
    );
}

/// REVIEW_005 (3) / R-011: `extract-media-signature --robust` must recover
/// the LSB-embedded payload on a robust-signed image, mirroring the verify
/// surface. Without this the CLI extract verb is silently inconsistent with
/// `verify-image --robust`.
#[test]
fn extract_media_signature_robust_recovers_lsb_payload() {
    let dir = fresh_tmpdir();
    bootstrap_agent(&dir, "ed25519");
    // Robust mode needs a sufficiently large image — 256x256 RGBA is enough
    // for the ~2 KiB JACS signed-document payload.
    let in_path = write_fixture(&dir, "in.png", &make_png(256, 256));
    let signed_path = dir.path().join("signed.png");

    cmd()
        .current_dir(dir.path())
        .args(["sign-image", "--robust"])
        .arg(in_path.to_str().unwrap())
        .args(["--out"])
        .arg(signed_path.to_str().unwrap())
        .assert()
        .success();

    // Without --robust, extract should NOT find the LSB-only payload.
    let no_robust = cmd()
        .current_dir(dir.path())
        .args(["extract-media-signature"])
        .arg(signed_path.to_str().unwrap())
        .assert()
        .code(2);
    let stdout_no_robust = no_robust.get_output().stdout.clone();
    assert!(
        stdout_no_robust.is_empty(),
        "without --robust, extract must not surface the LSB payload (exit 2). got: {:?}",
        String::from_utf8_lossy(&stdout_no_robust)
    );

    // With --robust, extract MUST recover the LSB-embedded payload.
    let with_robust = cmd()
        .current_dir(dir.path())
        .args(["extract-media-signature", "--robust"])
        .arg(signed_path.to_str().unwrap())
        .assert()
        .success();
    let stdout_with_robust = with_robust.get_output().stdout.clone();
    let s = String::from_utf8_lossy(&stdout_with_robust);
    assert!(
        s.contains("mediaSignatureVersion"),
        "extract --robust must surface a decoded JACS signed-document JSON; got: {s}"
    );
}

#[test]
fn extract_media_signature_no_signature_exit_two_all_formats() {
    for fmt in ["png", "jpg", "webp"] {
        let dir = fresh_tmpdir();
        let bytes = match fmt {
            "png" => make_png(16, 16),
            "jpg" => make_jpeg(16, 16),
            "webp" => make_webp(),
            _ => panic!("unsupported"),
        };
        let path = write_fixture(&dir, &format!("unsigned.{}", fmt), &bytes);
        let assert = cmd()
            .current_dir(dir.path())
            .args(["extract-media-signature"])
            .arg(path.to_str().unwrap())
            .assert()
            .code(2);
        let stdout = assert.get_output().stdout.clone();
        assert!(
            stdout.is_empty(),
            "stdout must be empty when no signature ({}); got {:?}",
            fmt,
            String::from_utf8_lossy(&stdout)
        );
    }
}

// ============================================================================
// PRD §4.2.2 refuse-overwrite
// ============================================================================

#[test]
fn sign_image_refuse_overwrite_errors_on_signed_input() {
    let dir = fresh_tmpdir();
    bootstrap_agent(&dir, "ed25519");
    let in_path = write_fixture(&dir, "foo.png", &make_png(32, 32));
    let signed_path = dir.path().join("foo.signed.png");

    cmd()
        .current_dir(dir.path())
        .args(["sign-image"])
        .arg(in_path.to_str().unwrap())
        .args(["--out"])
        .arg(signed_path.to_str().unwrap())
        .assert()
        .success();

    // Re-sign the already-signed file with --refuse-overwrite. Must error.
    let signed2_path = dir.path().join("foo.signed2.png");
    cmd()
        .current_dir(dir.path())
        .args(["sign-image", "--refuse-overwrite"])
        .arg(signed_path.to_str().unwrap())
        .args(["--out"])
        .arg(signed2_path.to_str().unwrap())
        .assert()
        .failure()
        .stderr(predicate::str::contains("already carries a JACS signature"));
}

#[test]
fn sign_image_default_overwrites_existing_signature() {
    let dir = fresh_tmpdir();
    bootstrap_agent(&dir, "ed25519");
    let in_path = write_fixture(&dir, "foo1.png", &make_png(32, 32));
    let signed_path = dir.path().join("signed.png");

    cmd()
        .current_dir(dir.path())
        .args(["sign-image"])
        .arg(in_path.to_str().unwrap())
        .args(["--out"])
        .arg(signed_path.to_str().unwrap())
        .assert()
        .success();

    // Default sign-image (no --refuse-overwrite) replaces the signature.
    // Re-sign signed.png in place.
    cmd()
        .current_dir(dir.path())
        .args(["sign-image"])
        .arg(signed_path.to_str().unwrap())
        .args(["--out"])
        .arg(signed_path.to_str().unwrap())
        .assert()
        .success();

    // Verify still works (one signer, just the latest).
    cmd()
        .current_dir(dir.path())
        .args(["verify-image"])
        .arg(signed_path.to_str().unwrap())
        .assert()
        .success();
}