api-key-manager 0.3.0

Use macOS Keychain secrets in commands without copying their values.
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
547
548
//! End-to-end integration tests.
//!
//! Tests use unique random prefixes so reruns don't step on each other. Run
//! single-threaded (`-- --test-threads=1`) because the macOS Keychain itself
//! has eventual-consistency edge cases when many writers churn concurrently —
//! even with v0.1.3's `ItemSearchOptions`-based enumeration (which is far
//! more robust than the v0.1.2 `security dump-keychain` text parser, but not
//! perfectly atomic under cargo's default thread fan-out).

#![cfg(target_os = "macos")]

use assert_cmd::Command;
use std::process::Command as StdCommand;

fn akm() -> Command {
    Command::cargo_bin("akm").expect("akm binary built")
}

fn unique_key(prefix: &str) -> String {
    use std::time::{SystemTime, UNIX_EPOCH};
    let nanos = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_nanos())
        .unwrap_or(0);
    format!("AKM_IT_{}_{}", prefix, nanos)
}

fn cleanup(name: &str) {
    let _ = StdCommand::new(env!("CARGO_BIN_EXE_akm"))
        .args(["rm", name])
        .output();
}

// ----- baseline tests -----

#[test]
fn version_and_help() {
    akm().arg("--version").assert().success();
    akm().arg("--help").assert().success();
}

#[test]
fn agent_info_json() {
    let out = akm().args(["agent-info", "--json"]).output().unwrap();
    assert!(out.status.success());
    let s = String::from_utf8_lossy(&out.stdout);
    assert!(s.contains("\"name\":\"akm\""));
    assert!(s.contains("\"commands\""));
    assert!(s.contains("\"threat_model\""));
}

#[test]
fn add_get_rm_roundtrip() {
    let name = unique_key("ROUNDTRIP");
    let value = "sk-test-roundtrip-value-1234567890";

    akm()
        .args(["add", &name])
        .write_stdin(value)
        .assert()
        .success();

    let out = akm().args(["get", &name, "--raw"]).output().unwrap();
    assert!(out.status.success());
    let body = String::from_utf8_lossy(&out.stdout);
    assert!(body.contains(value));

    let out = akm().args(["get", &name]).output().unwrap();
    let body = String::from_utf8_lossy(&out.stdout);
    assert!(
        !body.contains(value),
        "masked get must not contain raw value"
    );

    akm().args(["rm", &name]).assert().success();

    let out = akm().args(["get", &name]).output().unwrap();
    assert!(!out.status.success());

    cleanup(&name);
}

#[test]
fn get_missing_returns_not_found() {
    let name = unique_key("MISSING");
    let out = akm().args(["get", &name]).output().unwrap();
    let code = out.status.code().unwrap();
    assert_eq!(code, 6, "missing key should exit 6 (not_found)");
}

#[test]
fn list_includes_added_key() {
    let name = unique_key("LIST");
    akm()
        .args(["add", &name])
        .write_stdin("list-test-value-1234567890")
        .assert()
        .success();

    let out = akm().args(["list", "--json"]).output().unwrap();
    assert!(out.status.success());
    let body = String::from_utf8_lossy(&out.stdout);
    assert!(body.contains(&name));

    cleanup(&name);
}

#[test]
fn add_via_argv_works() {
    let name = unique_key("ARGV");
    let value = "argv-test-value-1234567890";
    akm().args(["add", &name, value]).assert().success();
    let out = akm().args(["get", &name, "--raw"]).output().unwrap();
    let body = String::from_utf8_lossy(&out.stdout);
    assert!(body.contains(value));
    cleanup(&name);
}

#[test]
fn run_requires_only_or_all() {
    let out = akm().args(["run", "--", "true"]).output().unwrap();
    let code = out.status.code().unwrap();
    assert_eq!(code, 3, "missing --only/--all should exit 3 (bad_input)");
}

#[test]
fn run_injects_only_named_keys() {
    let name = unique_key("RUN");
    let value = "value-for-run-injection-test-abc123";

    akm()
        .args(["add", &name])
        .write_stdin(value)
        .assert()
        .success();

    let out = akm()
        .args([
            "run",
            "--only",
            &name,
            "--no-redact",
            "--",
            "/bin/sh",
            "-c",
            &format!("echo ${}", name),
        ])
        .output()
        .unwrap();
    assert!(out.status.success());
    let body = String::from_utf8_lossy(&out.stdout);
    assert!(body.contains(value));

    cleanup(&name);
}

#[test]
fn run_redaction_replaces_value() {
    let name = unique_key("REDACT");
    let value = "secret-to-redact-not-in-output-xyz789";

    akm()
        .args(["add", &name])
        .write_stdin(value)
        .assert()
        .success();

    let out = akm()
        .args([
            "run",
            "--only",
            &name,
            "--",
            "/bin/sh",
            "-c",
            &format!("echo ${}", name),
        ])
        .output()
        .unwrap();
    assert!(out.status.success());
    let body = String::from_utf8_lossy(&out.stdout);
    assert!(!body.contains(value));
    assert!(body.contains("[REDACTED:"));

    cleanup(&name);
}

// ----- new tests for Codex 0.1.1 fixes -----

/// Fix #9: `akm run --json` must NOT pollute child stdout with the akm
/// envelope. Envelope goes to stderr.
#[test]
fn run_json_envelope_does_not_pollute_child_stdout() {
    let name = unique_key("RUN_JSON");
    let value = "run-json-stdout-test-value-abc1234567890";

    akm()
        .args(["add", &name])
        .write_stdin(value)
        .assert()
        .success();

    let out = akm()
        .args([
            "run",
            "--json",
            "--only",
            &name,
            "--no-redact",
            "--",
            "/bin/sh",
            "-c",
            "echo CHILD_OUTPUT_LINE",
        ])
        .output()
        .unwrap();
    assert!(out.status.success());
    let stdout = String::from_utf8_lossy(&out.stdout);
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stdout.trim() == "CHILD_OUTPUT_LINE",
        "child stdout should be exactly CHILD_OUTPUT_LINE, got: {:?}",
        stdout
    );
    assert!(
        stderr.contains("\"command\":\"run\""),
        "envelope should be on stderr in --json mode, got: {:?}",
        stderr
    );
    cleanup(&name);
}

/// v0.1.3: `akm stdin NAME -- <cmd>` writes the value to the child's stdin.
#[test]
fn stdin_writes_value_to_child_stdin() {
    let name = unique_key("STDIN_PIPE");
    let value = "stdin-pipe-test-value-abc1234567890";
    akm()
        .args(["add", &name])
        .write_stdin(value)
        .assert()
        .success();

    // /bin/cat echoes stdin to stdout. With --no-redact we get the raw value;
    // assert we see exactly what we put in.
    let out = akm()
        .args(["stdin", &name, "--no-redact", "--", "/bin/cat"])
        .output()
        .unwrap();
    assert!(out.status.success());
    let body = String::from_utf8_lossy(&out.stdout);
    assert!(
        body.contains(value),
        "child should receive the value on stdin, got: {:?}",
        body
    );
    cleanup(&name);
}

/// v0.1.3: stdin command redacts the value from child stdout by default.
#[test]
fn stdin_redacts_value_in_child_output() {
    let name = unique_key("STDIN_REDACT");
    let value = "stdin-redact-test-value-xyz9876543210";
    akm()
        .args(["add", &name])
        .write_stdin(value)
        .assert()
        .success();

    // Child reads value from stdin, then prints it back. Default mode should
    // replace the value with [REDACTED:NAME].
    let out = akm()
        .args(["stdin", &name, "--", "/bin/cat"])
        .output()
        .unwrap();
    assert!(out.status.success());
    let body = String::from_utf8_lossy(&out.stdout);
    assert!(
        !body.contains(value),
        "raw value must not appear in redacted stdout, got: {:?}",
        body
    );
    assert!(
        body.contains(&format!("[REDACTED:{}]", name)),
        "redaction token should appear, got: {:?}",
        body
    );
    cleanup(&name);
}

/// Fix #12: key names must match env-var pattern.
#[test]
fn add_rejects_invalid_name() {
    let out = akm()
        .args(["add", "FOO=BAR"])
        .write_stdin("any-value-12345678")
        .output()
        .unwrap();
    assert_eq!(
        out.status.code().unwrap(),
        3,
        "FOO=BAR should be bad_input (3)"
    );
}

#[test]
fn add_rejects_lowercase_name() {
    let out = akm()
        .args(["add", "lowercase"])
        .write_stdin("any-value-12345678")
        .output()
        .unwrap();
    assert_eq!(out.status.code().unwrap(), 3);
}

/// Fix #7: audit log file is created with mode 0600 (not group/other readable).
#[test]
fn audit_log_perms_are_0600() {
    use std::os::unix::fs::PermissionsExt;
    let name = unique_key("PERM");
    akm()
        .args(["add", &name])
        .write_stdin("perm-test-value-1234567890")
        .assert()
        .success();
    let home = std::env::var("HOME").unwrap();
    let path = format!("{}/.akm/audit.log", home);
    let meta = std::fs::metadata(&path).expect("audit log exists");
    let mode = meta.permissions().mode() & 0o777;
    assert_eq!(mode, 0o600, "expected 0600, got {:o}", mode);
    cleanup(&name);
}

/// Fix #6: `akm run` writes a "started" audit entry BEFORE the child exits,
/// AND a matching `run_id` pairs the started/completed entries.
///
/// Codex flagged the previous version of this test as weak: it used `true`
/// (instant exit) and checked after, so it didn't prove the ordering. This
/// version spawns a long-lived child, checks the audit log while it's still
/// alive, then asserts the paired completion entry exists.
#[test]
fn run_writes_started_audit_entry_before_child_exits() {
    use std::thread;
    use std::time::Duration;
    let name = unique_key("STARTED");
    akm()
        .args(["add", &name])
        .write_stdin("started-audit-test-1234567890")
        .assert()
        .success();

    // Spawn a long-lived child in the background.
    let name_c = name.clone();
    let handle = thread::spawn(move || {
        akm()
            .args([
                "run",
                "--only",
                &name_c,
                "--no-redact",
                "--",
                "/bin/sh",
                "-c",
                "sleep 2",
            ])
            .output()
            .unwrap()
    });

    // Give the started entry time to land.
    thread::sleep(Duration::from_millis(500));

    let out = akm()
        .args(["audit", "--json", "--limit", "50"])
        .output()
        .unwrap();
    let body = String::from_utf8_lossy(&out.stdout);
    assert!(
        body.contains("\"status\":\"started\""),
        "started entry must appear while child is alive, got: {}",
        body
    );

    let result = handle.join().expect("run thread joined");
    assert!(result.status.success(), "run should succeed");

    // After completion, both started and ok entries must be present and
    // share a run_id.
    let out = akm()
        .args(["audit", "--json", "--limit", "50"])
        .output()
        .unwrap();
    let body = String::from_utf8_lossy(&out.stdout);
    assert!(body.contains("\"status\":\"started\""));
    assert!(body.contains("\"status\":\"ok\""));
    cleanup(&name);
}

/// Fix #8: redactor handles prefix collision (longer secret beats shorter
/// prefix). Tightened per Codex #9: also assert command success AND that the
/// redaction token appears (empty stdout would otherwise satisfy "not contains
/// long_val").
#[test]
fn run_redacts_longer_matching_secret() {
    let short = unique_key("SHORT_PFX");
    let long = unique_key("LONG_PFX");
    let short_val = "prefix-collision-test-xx".to_string();
    let long_val = format!("{}-more-bytes", short_val);

    akm()
        .args(["add", &short])
        .write_stdin(short_val.clone())
        .assert()
        .success();
    akm()
        .args(["add", &long])
        .write_stdin(long_val.clone())
        .assert()
        .success();

    let out = akm()
        .args([
            "run",
            "--only",
            &format!("{},{}", short, long),
            "--",
            "/bin/sh",
            "-c",
            &format!("echo ${}", long),
        ])
        .output()
        .unwrap();

    assert!(out.status.success(), "run should succeed");
    let body = String::from_utf8_lossy(&out.stdout);
    assert!(
        !body.contains(&long_val),
        "long value should be redacted, got: {:?}",
        body
    );
    assert!(
        body.contains(&format!("[REDACTED:{}]", long)),
        "expected [REDACTED:{}] in output, got: {:?}",
        long,
        body
    );

    cleanup(&short);
    cleanup(&long);
}

// ----- v0.2.0: export / import / list --long -----

#[test]
fn export_json_and_env_formats() {
    let name = unique_key("EXPORT");
    let value = "sk-test-export-value-1234567890";

    akm()
        .args(["add", &name])
        .write_stdin(value)
        .assert()
        .success();

    let out = akm().args(["export", "--only", &name]).output().unwrap();
    assert!(out.status.success());
    let s = String::from_utf8_lossy(&out.stdout);
    assert!(
        s.contains(&format!("\"{}\":\"{}\"", name, value)),
        "json export carries raw value: {s}"
    );

    let out = akm()
        .args(["export", "--only", &name, "--format", "env"])
        .output()
        .unwrap();
    assert!(out.status.success());
    let s = String::from_utf8_lossy(&out.stdout);
    assert_eq!(s.trim(), format!("{}={}", name, value));

    cleanup(&name);
}

#[test]
fn export_missing_key_maps_to_not_found() {
    let name = unique_key("EXPORT_MISSING");
    let out = akm().args(["export", "--only", &name]).output().unwrap();
    assert_eq!(out.status.code(), Some(6), "not_found exit code");
}

#[test]
fn import_dotenv_roundtrip_and_skips() {
    let name = unique_key("IMPORT");
    let dotenv = format!(
        "# comment\nexport {}=\"imported-value-123\"\nlowercase=nope\nBROKENLINE\n",
        name
    );

    let out = akm()
        .args(["import", "-"])
        .write_stdin(dotenv.clone())
        .output()
        .unwrap();
    assert!(out.status.success());
    let s = String::from_utf8_lossy(&out.stdout);
    assert!(s.contains("\"count\":1"), "one key stored: {s}");
    assert!(s.contains("\"skipped\""), "skips reported: {s}");

    let out = akm().args(["get", &name, "--raw"]).output().unwrap();
    assert!(out.status.success());
    let s = String::from_utf8_lossy(&out.stdout);
    assert!(s.contains("imported-value-123"), "value roundtrips: {s}");

    // dry-run must not write
    let name2 = unique_key("IMPORT_DRY");
    akm()
        .args(["import", "-", "--dry-run"])
        .write_stdin(format!("{}=would-be-stored", name2))
        .assert()
        .success();
    let out = akm().args(["get", &name2]).output().unwrap();
    assert_eq!(out.status.code(), Some(6), "dry-run stored nothing");

    cleanup(&name);
}

#[test]
fn list_long_reports_age() {
    let name = unique_key("LISTLONG");
    akm()
        .args(["add", &name])
        .write_stdin("list-long-value-123")
        .assert()
        .success();

    let out = akm().args(["list", "--json"]).output().unwrap();
    assert!(out.status.success());
    let s = String::from_utf8_lossy(&out.stdout);
    assert!(s.contains("\"entries\""), "entries present: {s}");
    assert!(
        s.contains(&format!("\"name\":\"{}\"", name)),
        "new key listed with metadata: {s}"
    );
    assert!(s.contains("\"age_days\":0"), "fresh key has age 0: {s}");

    cleanup(&name);
}