keyhog 0.5.73

GPU-accelerated secret scanner for code, Git history, cloud, containers, browser assets, and live credential verification
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
//! Multi-root scanning (`keyhog scan a/ b/ c/`).
//!
//! keyhog scans several filesystem roots per invocation: each becomes its own
//! filesystem source (the scan engine already merges the multi-source `Vec`),
//! overlapping/nested roots fold into their covering parent, and the modes that
//! have no unambiguous meaning over more than one root fail closed. These tests
//! pin three layers:
//!   * the parse + [`ScanArgs::scan_roots`] accessor (pure),
//!   * the [`resolve_scan_roots`] overlap/validation resolver (via the
//!     `CliTestApi` facade, on real temp directories), and
//!   * the shipped binary end to end (every root is actually scanned and no
//!     finding is silently dropped, the recall contract this feature exists
//!     for).

use clap::Parser;
use keyhog::args::ScanArgs;
use keyhog::testing::{CliTestApi, API};
use std::path::PathBuf;
use std::process::Command;
use tempfile::TempDir;

fn binary() -> PathBuf {
    PathBuf::from(env!("CARGO_BIN_EXE_keyhog"))
}

/// A planted AWS access-key id, a deterministic high-confidence positive used
/// across the e2e suite, so a finding is guaranteed on any host/backend.
const PLANTED_SECRET: &str = "AWS_ACCESS_KEY_ID = \"AKIAQYLPMN5HFIQR7XYA\"\n";

fn parse(argv: &[&str]) -> ScanArgs {
    ScanArgs::try_parse_from(argv).expect("scan args must parse")
}

// ---------------------------------------------------------------------------
// Layer 1: `ScanArgs::scan_roots` accessor (pure)
// ---------------------------------------------------------------------------

#[test]
fn single_positional_is_one_root() {
    assert_eq!(parse(&["scan", "a"]).scan_roots(), vec![PathBuf::from("a")]);
}

#[test]
fn three_positionals_are_three_ordered_roots() {
    assert_eq!(
        parse(&["scan", "a", "b", "c"]).scan_roots(),
        vec![PathBuf::from("a"), PathBuf::from("b"), PathBuf::from("c")],
    );
}

#[test]
fn explicit_path_flag_is_one_root() {
    assert_eq!(
        parse(&["scan", "--path", "p"]).scan_roots(),
        vec![PathBuf::from("p")],
    );
}

#[test]
fn no_path_is_zero_roots() {
    assert!(parse(&["scan"]).scan_roots().is_empty());
}

#[test]
fn all_positionals_land_in_one_ordered_vector() {
    let args = parse(&["scan", "a", "b", "c"]);
    assert_eq!(
        args.input,
        vec![PathBuf::from("a"), PathBuf::from("b"), PathBuf::from("c")]
    );
}

#[test]
fn scan_roots_survives_orchestrator_input_to_path_promotion() {
    // `ScanOrchestrator::new` copies the first positional root into `path` for
    // config discovery. The positional vector remains the source of truth.
    let mut args = parse(&["scan", "a", "b", "c"]);
    args.path = args.input.first().cloned();
    assert_eq!(
        args.scan_roots(),
        vec![PathBuf::from("a"), PathBuf::from("b"), PathBuf::from("c")],
        "promotion must not collapse a multi-root request to its first root",
    );
}

#[test]
fn shipped_help_advertises_the_real_variadic_positional() {
    let output = Command::new(binary())
        .args(["scan", "--help"])
        .output()
        .expect("run scan help");
    assert!(output.status.success());
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        stdout.contains("Usage: keyhog scan [OPTIONS] [PATH]..."),
        "generated usage must expose the real multi-root contract: {stdout}"
    );
    assert!(
        !stdout.contains("EXTRA_PATH"),
        "the removed hidden positional shim must not leak into help: {stdout}"
    );
}

#[test]
fn stdin_shorthand_cannot_hide_inside_a_multi_root_request() {
    let tmp = TempDir::new().expect("tempdir");
    let output = Command::new(binary())
        .args(["scan", "-", tmp.path().to_str().expect("utf8 temp path")])
        .output()
        .expect("run mixed stdin/filesystem scan");
    assert_eq!(output.status.code(), Some(2));
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("stdin shorthand `-` cannot be combined with other positional scan roots"),
        "mixed-source refusal must name the conflicting shorthand and fix: {stderr}"
    );
}

// ---------------------------------------------------------------------------
// Layer 2: `resolve_scan_roots` validation + overlap fold (real dirs)
// ---------------------------------------------------------------------------

#[test]
fn distinct_roots_are_kept_in_order() {
    let tmp = TempDir::new().expect("tempdir");
    let a = tmp.path().join("a");
    let b = tmp.path().join("b");
    std::fs::create_dir(&a).unwrap();
    std::fs::create_dir(&b).unwrap();

    let kept = API
        .resolve_scan_roots(&[a.clone(), b.clone()])
        .expect("two distinct roots resolve");
    assert_eq!(kept, vec![a, b]);
}

#[test]
fn exact_duplicate_root_is_folded_to_one() {
    let tmp = TempDir::new().expect("tempdir");
    let a = tmp.path().join("a");
    std::fs::create_dir(&a).unwrap();

    let kept = API
        .resolve_scan_roots(&[a.clone(), a.clone()])
        .expect("duplicate roots resolve");
    assert_eq!(kept, vec![a], "an exact duplicate keeps only the first");
}

#[test]
fn nested_child_after_parent_is_folded_into_parent() {
    let tmp = TempDir::new().expect("tempdir");
    let parent = tmp.path().join("parent");
    let child = parent.join("child");
    std::fs::create_dir_all(&child).unwrap();

    let kept = API
        .resolve_scan_roots(&[parent.clone(), child])
        .expect("nested roots resolve");
    assert_eq!(kept, vec![parent], "the child subtree is already walked");
}

#[test]
fn nested_parent_after_child_still_folds_the_child() {
    let tmp = TempDir::new().expect("tempdir");
    let parent = tmp.path().join("parent");
    let child = parent.join("child");
    std::fs::create_dir_all(&child).unwrap();

    // Order reversed: the ancestor wins regardless of argument position.
    let kept = API
        .resolve_scan_roots(&[child, parent.clone()])
        .expect("nested roots resolve");
    assert_eq!(kept, vec![parent]);
}

#[test]
fn only_the_nested_root_is_dropped_from_three() {
    let tmp = TempDir::new().expect("tempdir");
    let a = tmp.path().join("a");
    let b = tmp.path().join("b");
    let a_sub = a.join("sub");
    std::fs::create_dir_all(&a_sub).unwrap();
    std::fs::create_dir(&b).unwrap();

    let kept = API
        .resolve_scan_roots(&[a.clone(), a_sub, b.clone()])
        .expect("mixed roots resolve");
    assert_eq!(kept, vec![a, b]);
}

#[test]
fn sibling_directories_are_both_kept() {
    let tmp = TempDir::new().expect("tempdir");
    let a = tmp.path().join("shared_a");
    let b = tmp.path().join("shared_b");
    std::fs::create_dir(&a).unwrap();
    std::fs::create_dir(&b).unwrap();

    // `shared_b` is NOT nested in `shared_a` even though the canonical string of
    // one is a textual prefix of the other. `Path::starts_with` is
    // component-wise, so neither is folded.
    let kept = API
        .resolve_scan_roots(&[a.clone(), b.clone()])
        .expect("sibling roots resolve");
    assert_eq!(kept, vec![a, b]);
}

#[test]
fn single_root_resolves_to_itself() {
    let tmp = TempDir::new().expect("tempdir");
    let a = tmp.path().join("a");
    std::fs::create_dir(&a).unwrap();
    assert_eq!(API.resolve_scan_roots(&[a.clone()]).unwrap(), vec![a]);
}

#[test]
fn empty_request_resolves_to_empty() {
    assert!(API.resolve_scan_roots(&[]).unwrap().is_empty());
}

#[test]
fn nonexistent_root_fails_closed() {
    let tmp = TempDir::new().expect("tempdir");
    let real = tmp.path().join("real");
    std::fs::create_dir(&real).unwrap();
    let missing = tmp.path().join("does_not_exist");

    let err = API
        .resolve_scan_roots(&[real, missing])
        .expect_err("a missing root must error, not be silently skipped");
    let msg = format!("{err:#}");
    assert!(
        msg.contains("does_not_exist"),
        "the error names the offending root: {msg}"
    );
}

// ---------------------------------------------------------------------------
// Layer 2b, combination guard (`guard_multi_root_combinations`)
// ---------------------------------------------------------------------------

#[test]
fn single_root_passes_the_combination_guard() {
    API.guard_multi_root_combinations(&parse(&["scan", "a"]))
        .expect("one root has nothing to guard");
}

#[test]
fn plain_multi_root_passes_the_combination_guard() {
    API.guard_multi_root_combinations(&parse(&["scan", "a", "b", "c"]))
        .expect("plain filesystem multi-root is allowed");
}

#[cfg(feature = "git")]
#[test]
fn git_staged_with_multi_root_is_rejected() {
    let err = API
        .guard_multi_root_combinations(&parse(&["scan", "a", "b", "--git-staged"]))
        .expect_err("--git-staged cannot span multiple roots");
    let msg = format!("{err:#}");
    assert!(msg.contains("--git-staged"), "names the flag: {msg}");
    assert!(
        msg.contains('a') && msg.contains('b'),
        "names the offending roots: {msg}"
    );
}

#[cfg(feature = "git")]
#[test]
fn git_staged_with_single_root_is_allowed() {
    API.guard_multi_root_combinations(&parse(&["scan", "repo", "--git-staged"]))
        .expect("--git-staged is fine with exactly one root");
}

// ---------------------------------------------------------------------------
// Layer 3, shipped binary, end to end
// ---------------------------------------------------------------------------

fn scan(args: &[&std::ffi::OsStr]) -> std::process::Output {
    Command::new(binary())
        .arg("scan")
        .args(["--daemon=off", "--backend", "simd", "--format", "json"])
        .args(args)
        .output()
        .expect("spawn keyhog scan")
}

#[test]
fn two_clean_roots_scan_and_exit_zero() {
    let tmp = TempDir::new().expect("tempdir");
    let a = tmp.path().join("a");
    let b = tmp.path().join("b");
    std::fs::create_dir(&a).unwrap();
    std::fs::create_dir(&b).unwrap();
    std::fs::write(a.join("clean.txt"), "nothing here\n").unwrap();
    std::fs::write(b.join("clean.txt"), "also nothing\n").unwrap();

    let out = scan(&[a.as_os_str(), b.as_os_str()]);
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert_eq!(
        out.status.code(),
        Some(0),
        "two clean roots exit 0; stderr={stderr}"
    );
    assert!(
        !stderr.contains("scans one root path per invocation"),
        "multi-root is accepted, never rejected: {stderr}"
    );
}

#[test]
fn every_root_is_scanned_and_no_finding_is_dropped() {
    // The recall contract: a secret planted in EACH root must surface. Reading
    // only the first root (the pre-feature behavior) would drop `beta`.
    let tmp = TempDir::new().expect("tempdir");
    let a = tmp.path().join("a");
    let b = tmp.path().join("b");
    std::fs::create_dir(&a).unwrap();
    std::fs::create_dir(&b).unwrap();
    std::fs::write(a.join("alpha.env"), PLANTED_SECRET).unwrap();
    std::fs::write(b.join("beta.env"), PLANTED_SECRET).unwrap();

    let out = scan(&[a.as_os_str(), b.as_os_str()]);
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert_eq!(
        out.status.code(),
        Some(1),
        "findings present exit 1; stdout={stdout}"
    );
    assert!(stdout.contains("alpha.env"), "first root scanned: {stdout}");
    assert!(stdout.contains("beta.env"), "second root scanned: {stdout}");
    assert_eq!(
        stdout.matches("\"file_path\"").count(),
        2,
        "exactly one finding per root, none dropped or duplicated: {stdout}"
    );
}

#[test]
fn overlapping_roots_fold_loudly_and_scan_the_subtree_once() {
    let tmp = TempDir::new().expect("tempdir");
    let parent = tmp.path().join("parent");
    let child = parent.join("child");
    std::fs::create_dir_all(&child).unwrap();
    std::fs::write(child.join("planted.env"), PLANTED_SECRET).unwrap();

    let out = scan(&[parent.as_os_str(), child.as_os_str()]);
    let stdout = String::from_utf8_lossy(&out.stdout);
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("folding overlapping scan root"),
        "the fold is announced, never silent (Law 10): {stderr}"
    );
    assert_eq!(
        stdout.matches("\"file_path\"").count(),
        1,
        "the nested subtree is walked once via its parent, not twice: {stdout}"
    );
}

#[cfg(feature = "git")]
#[test]
fn git_staged_multi_root_binary_fails_closed() {
    let tmp = TempDir::new().expect("tempdir");
    let a = tmp.path().join("a");
    let b = tmp.path().join("b");
    std::fs::create_dir(&a).unwrap();
    std::fs::create_dir(&b).unwrap();

    let out = Command::new(binary())
        .arg("scan")
        .args(["--daemon=off", "--backend", "simd", "--git-staged"])
        .args([a.as_os_str(), b.as_os_str()])
        .output()
        .expect("spawn keyhog scan");
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert_eq!(
        out.status.code(),
        Some(2),
        "--git-staged over many roots fails closed with EXIT_USER_ERROR; stderr={stderr}"
    );
    assert!(
        stderr.contains("repository"),
        "explains the single-repository constraint: {stderr}"
    );
}

#[cfg(unix)]
#[test]
fn forced_daemon_with_multi_root_fails_closed_not_silent() {
    // `--daemon=on` over several roots cannot be served by the single-path
    // daemon protocol; it must fail closed rather than silently scan the first
    // root only.
    let tmp = TempDir::new().expect("tempdir");
    let a = tmp.path().join("a.env");
    let b = tmp.path().join("b.env");
    std::fs::write(&a, PLANTED_SECRET).unwrap();
    std::fs::write(&b, PLANTED_SECRET).unwrap();

    let out = Command::new(binary())
        .arg("scan")
        .args(["--daemon=on", "--backend", "simd", "--format", "json"])
        .args([a.as_os_str(), b.as_os_str()])
        .output()
        .expect("spawn keyhog scan");
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert_eq!(
        out.status.code(),
        Some(2),
        "forced daemon + multi-root fails closed; stdout={stdout}"
    );
    assert!(
        !stdout.contains("a.env") || !stdout.contains("\"file_path\""),
        "it must NOT silently produce a single-root daemon result: {stdout}"
    );
}