keyhog 0.5.37

keyhog: detects leaked credentials in source trees, git history, and cloud storage
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
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
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
//! End-to-end tests that drive the real `keyhog` binary.
//!
//! Per the per-rule contract (CLAUDE.md test type 10), "the product
//! is the binary." These tests:
//!
//! * use `env!("CARGO_BIN_EXE_keyhog")` - cargo points this at the
//!   freshly built `keyhog` binary in `target/<profile>/keyhog`, so we
//!   exercise the same executable users get;
//! * write a planted-credential fixture to `tempfile::TempDir` (out of
//!   the workspace, so `.gitignore` skip rules don't interfere - keyhog
//!   walks `.internal/` etc. as gitignored, which this test would
//!   otherwise trip);
//! * parse `--format json` stdout, verify shape + counts;
//! * verify the documented exit codes.
//!
//! The fixture is small and self-contained so the test is fast
//! enough to live in the normal `cargo test` flow.

use std::path::PathBuf;
use std::process::Command;

use tempfile::TempDir;

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

/// One-line helper: write a temp file with given content, scan it
/// with `--format json`, return (stdout, stderr, exit-code).
fn scan_text_file(content: &str, extra_args: &[&str]) -> (String, String, Option<i32>) {
    let dir = TempDir::new().expect("tempdir");
    let path = dir.path().join("planted.txt");
    std::fs::write(&path, content).expect("write fixture");

    let output = Command::new(binary())
        .arg("scan")
        .args(extra_args)
        .arg("--format")
        .arg("json")
        .arg(&path)
        .output()
        .expect("spawn keyhog scan");

    (
        String::from_utf8_lossy(&output.stdout).into_owned(),
        String::from_utf8_lossy(&output.stderr).into_owned(),
        output.status.code(),
    )
}

#[test]
fn scan_finds_planted_aws_key_and_returns_exit_1() {
    let fixture = concat!("AWS_ACCESS_KEY_ID = \"AKIA", "QYLPMN5HFIQR7XYA\"\n");
    let (stdout, _stderr, code) = scan_text_file(fixture, &[]);

    // Documented exit codes: 0 = clean, 1 = unverified findings.
    // Planted key with no `--verify` should land us at 1.
    assert_eq!(
        code,
        Some(1),
        "expected exit 1 (unverified findings); got {code:?}"
    );

    let findings: serde_json::Value = serde_json::from_str(&stdout).expect("stdout is valid JSON");
    let arr = findings.as_array().expect("findings JSON is an array");
    assert!(!arr.is_empty(), "expected at least one finding");
    // An AKIA key is caught by the simdsieve fast path (`hot-aws_key`) when it
    // engages, otherwise by the named `aws-access-key` detector. Both are a
    // correct AWS detection - assert on either so the test does not break on a
    // backend/size-dependent fast-path engagement decision.
    let aws = arr.iter().find(|f| {
        matches!(
            f.get("detector_id").and_then(|v| v.as_str()),
            Some("aws-access-key" | "hot-aws_key")
        )
    });
    assert!(aws.is_some(), "expected an AWS key finding; got: {arr:?}");
}

#[test]
fn scan_returns_exit_0_on_clean_file() {
    let fixture = "fn main() { println!(\"hello\"); }\n";
    let (stdout, _stderr, code) = scan_text_file(fixture, &[]);

    assert_eq!(code, Some(0), "expected exit 0 on clean file; got {code:?}");
    let findings: serde_json::Value = serde_json::from_str(&stdout).expect("stdout is valid JSON");
    let arr = findings.as_array().expect("findings JSON is an array");
    assert!(arr.is_empty(), "expected zero findings; got: {arr:?}");
}

#[test]
fn scan_json_schema_carries_required_fields() {
    let fixture = "GH_TOKEN = \"ghp_aBcD1234EFgh5678ijkl9012MNop3456qrST\"\n";
    let (stdout, _stderr, _code) = scan_text_file(fixture, &[]);

    let findings: serde_json::Value = serde_json::from_str(&stdout).expect("stdout is valid JSON");
    let arr = findings.as_array().expect("findings JSON is an array");
    assert!(!arr.is_empty(), "expected the GH token to fire");

    // Every finding MUST carry the contract fields downstream
    // consumers (CI gates, SARIF converters, IDE plugins) depend on.
    for f in arr {
        for required in [
            "detector_id",
            "detector_name",
            "service",
            "severity",
            "credential_redacted",
            "credential_hash",
            "location",
            "verification",
        ] {
            assert!(
                f.get(required).is_some(),
                "finding is missing required field `{required}`: {f}",
            );
        }
        let loc = f.get("location").unwrap();
        for required in ["source", "file_path", "line", "offset"] {
            assert!(
                loc.get(required).is_some(),
                "location is missing required field `{required}`: {loc}",
            );
        }
    }
}

/// README binding test: the banner advertises an exact detector +
/// pattern count. If we add detectors or rewrite a regex pair, the
/// banner becomes a lie unless updated. This test surfaces drift
/// before it ships.
///
/// README line under audit (root README.md):
///   `KeyHog vX.Y.Z | ... | 889 detectors (1665 patterns)`
///
/// When you legitimately change the counts:
///   1. Update README.md banner.
///   2. Update these two constants.
///   3. CI stays green.
#[test]
fn readme_banner_counts_match_loaded_corpus() {
    const README_DETECTOR_COUNT: usize = 891;
    const README_PATTERN_COUNT: usize = 1645;

    let output = Command::new(binary())
        .arg("detectors")
        .arg("--json")
        .output()
        .expect("spawn keyhog detectors --json");
    assert_eq!(output.status.code(), Some(0));
    let arr: Vec<serde_json::Value> =
        serde_json::from_slice(&output.stdout).expect("detectors JSON parse");
    let actual_patterns: usize = arr
        .iter()
        .map(|d| {
            d.get("patterns")
                .and_then(|v| v.as_array())
                .map(|a| a.len())
                .unwrap_or(0)
        })
        .sum();

    assert_eq!(
        arr.len(),
        README_DETECTOR_COUNT,
        "README banner says {README_DETECTOR_COUNT} detectors; actual={}. \
         Update README and the constant in this test together.",
        arr.len(),
    );
    assert_eq!(
        actual_patterns, README_PATTERN_COUNT,
        "README banner says {README_PATTERN_COUNT} patterns; actual={actual_patterns}. \
         Update README and the constant in this test together.",
    );
}

#[test]
fn detectors_subcommand_emits_json_array() {
    let output = Command::new(binary())
        .arg("detectors")
        .arg("--json")
        .output()
        .expect("spawn keyhog detectors --json");
    assert_eq!(
        output.status.code(),
        Some(0),
        "detectors --json should exit 0; stderr={}",
        String::from_utf8_lossy(&output.stderr)
    );
    let stdout = String::from_utf8_lossy(&output.stdout);
    let parsed: serde_json::Value =
        serde_json::from_str(&stdout).expect("detectors --json stdout is valid JSON");
    let arr = parsed.as_array().expect("--json output is a JSON array");
    assert!(
        arr.len() > 100,
        "expected hundreds of detectors; got {}",
        arr.len()
    );
    // Spot-check one well-known detector.
    let aws = arr
        .iter()
        .find(|d| d.get("id").and_then(|v| v.as_str()) == Some("aws-access-key"));
    assert!(
        aws.is_some(),
        "aws-access-key should appear in --json output"
    );
    let aws = aws.unwrap();
    assert_eq!(
        aws.get("service").and_then(|v| v.as_str()),
        Some("aws"),
        "aws-access-key should have service=aws",
    );
}

/// Tier-B suppression flag: by default keyhog suppresses Stripe's
/// public docs demo key (and other documented test fixtures), so
/// scanning a fixture containing it surfaces 0 findings. Passing
/// `--no-suppress-test-fixtures` flips that - the same fixture
/// produces the finding gitleaks and trufflehog also report.
///
/// This is the binding test for the Tier-B move (task #60). If
/// someone deletes the bundled `test-fixtures.toml` entry for
/// Stripe, the default-mode assertion below catches it; if someone
/// drops the `--no-suppress-test-fixtures` arg, the opt-out branch
/// catches it.
#[test]
fn no_suppress_test_fixtures_surfaces_stripe_demo_key() {
    // The canonical Stripe public-docs demo key. Split via `concat!`
    // so GitHub Push Protection doesn't scan this source file as a
    // live secret leak.
    let stripe_key = concat!("sk_", "live_", "4eC39HqLyjWDarjtT1zdp7dc");
    let fixture = format!("STRIPE_KEY = \"{stripe_key}\"\n");

    let dir = TempDir::new().expect("tempdir");
    let path = dir.path().join("planted.txt");
    std::fs::write(&path, &fixture).expect("write fixture");

    // ----- default: suppressed -----------------------------------
    let default_out = Command::new(binary())
        .arg("scan")
        .arg("--format")
        .arg("json")
        .arg(&path)
        .output()
        .expect("spawn keyhog scan (default)");
    let default_json = String::from_utf8_lossy(&default_out.stdout);
    let default_findings: serde_json::Value =
        serde_json::from_str(&default_json).expect("default-mode stdout is JSON");
    let default_arr = default_findings.as_array().expect("array");
    let has_stripe = default_arr
        .iter()
        .any(|f| f.get("service").and_then(|v| v.as_str()) == Some("stripe"));
    assert!(
        !has_stripe,
        "default mode MUST suppress the Stripe demo key; got findings: {default_arr:?}"
    );

    // ----- --no-suppress-test-fixtures: surfaced -----------------
    let optout_out = Command::new(binary())
        .arg("scan")
        .arg("--no-suppress-test-fixtures")
        .arg("--format")
        .arg("json")
        .arg(&path)
        .output()
        .expect("spawn keyhog scan (opt-out)");
    let optout_json = String::from_utf8_lossy(&optout_out.stdout);
    let optout_findings: serde_json::Value =
        serde_json::from_str(&optout_json).expect("opt-out stdout is JSON");
    let optout_arr = optout_findings.as_array().expect("array");
    let has_stripe_now = optout_arr
        .iter()
        .any(|f| f.get("service").and_then(|v| v.as_str()) == Some("stripe"));
    assert!(
        has_stripe_now,
        "--no-suppress-test-fixtures MUST surface the Stripe demo key; \
         got findings: {optout_arr:?}"
    );
}

/// Regression for the demo-secret.env UX bug originally flagged
/// in TODO.md (2026-05-17): scanning a file that holds an
/// AWS-published EXAMPLE credential (AKIAIOSFODNN7EXAMPLE) used to
/// print "No secrets found. Your code is clean." - identical to a
/// genuinely clean repo - because the test-fixture suppression
/// filtered the match BEFORE the example-suppression telemetry
/// counter saw it. The reporter then read counter=0 and chose the
/// clean-repo summary.
///
/// v0.5.6 wired `record_example_suppression` for the engine-side
/// EXAMPLE token check, but missed this orchestrator-level
/// test-fixture filter, so the bug came back as soon as the AWS
/// fixture went through the substring suppression instead of the
/// engine path. This test pins the right behaviour:
///
/// * Default mode → output contains "example/test key" and does
///   NOT contain the all-clean summary.
/// * The bundled AWS-EXAMPLE entry must still suppress (no
///   finding shown in the matches list).
#[test]
fn demo_secret_aws_example_summary_distinguishes_suppression_from_clean() {
    let fixture = "AWS_ACCESS_KEY_ID=AKIAIOSFODNN7EXAMPLE\n";
    let dir = TempDir::new().expect("tempdir");
    let path = dir.path().join("demo-secret.env");
    std::fs::write(&path, fixture).expect("write fixture");

    // --no-daemon to guarantee the in-process orchestrator path is
    // exercised (the daemon path lives in `subcommands/scan.rs` and
    // is locked by `daemon_route_test_fixture_suppression_records_telemetry`
    // below).
    let out = Command::new(binary())
        .arg("scan")
        .arg("--no-daemon")
        .arg("--format")
        .arg("text")
        .arg(&path)
        .output()
        .expect("spawn keyhog scan demo-secret.env");
    let stdout = String::from_utf8_lossy(&out.stdout);

    assert!(
        stdout.contains("example/test key") && stdout.contains("suppressed"),
        "demo-secret.env summary must distinguish suppressed-example from a \
         clean repo. Got stdout: {stdout}"
    );
    assert!(
        !stdout.contains("Your code is clean."),
        "the clean-repo summary must NOT fire when an example credential was \
         suppressed. Got stdout: {stdout}"
    );
}

#[test]
fn explicit_format_text_does_not_emit_json() {
    let fixture = concat!("AWS_ACCESS_KEY_ID = \"AKIA", "QYLPMN5HFIQR7XYA\"\n");
    let dir = TempDir::new().expect("tempdir");
    let path = dir.path().join("planted.txt");
    std::fs::write(&path, fixture).expect("write fixture");

    // Don't share the json-format helper here - text-format is the
    // contrast case we're asserting.
    let output = Command::new(binary())
        .arg("scan")
        .arg("--format")
        .arg("text")
        .arg(&path)
        .output()
        .expect("spawn keyhog scan --format text");

    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);
    let combined = format!("{stdout}\n{stderr}");

    // Text mode is the human-facing default. The hard contract:
    // (1) stdout MUST NOT start with `[` (would mean JSON leaked
    //     through), and (2) the combined stream must reference the
    //     finding somewhere - text reporter writes to stdout or
    //     stderr depending on `--output`; we accept either.
    assert!(
        !stdout.trim_start().starts_with('['),
        "text format must not start with JSON `[`; got: {stdout}",
    );
    assert!(
        combined.to_lowercase().contains("aws") || combined.contains("AKIA"),
        "text format should mention the finding somewhere; \
         stdout={stdout:?}, stderr={stderr:?}, exit={:?}",
        output.status.code(),
    );
}

/// `--scan-comments` end-to-end: a credential pasted inside a
/// `// TODO: rotate this …` comment is suppressed by default (the
/// common case is an EXAMPLE token in a doc comment) but surfaces
/// when the operator opts in. Pins the wiring all the way from the
/// clap flag → ScanArgs → orchestrator_config::scan_comments →
/// ScannerConfig.scan_comments → fallback_generic + engine context-
/// penalty gates.
#[test]
fn scan_comments_flag_surfaces_credentials_in_comments() {
    // A genuine-shape AWS access key inside a `//`-style comment.
    // Default scan applies the comment-context confidence penalty
    // and the finding falls below `min_confidence`; --scan-comments
    // lifts it.
    let aws_key = concat!("AKIA", "ROTATIONNEEDED7777Q");
    let fixture = format!("// TODO: rotate this - {aws_key}\n");

    let dir = TempDir::new().expect("tempdir");
    let path = dir.path().join("comment_planted.go");
    std::fs::write(&path, &fixture).expect("write fixture");

    // Default: comment-context penalty in effect; AWS prefix is
    // strong enough to still fire on this one, so we don't assert
    // the *absence* of the finding (that would be brittle to
    // confidence-floor tuning). What we DO assert is that
    // --scan-comments AT LEAST matches the default - never silently
    // hides findings the default would surface.
    let default_out = Command::new(binary())
        .arg("scan")
        .arg("--format")
        .arg("json")
        .arg(&path)
        .output()
        .expect("spawn keyhog scan (default)");
    let default_json = String::from_utf8_lossy(&default_out.stdout);
    let default_findings: serde_json::Value =
        serde_json::from_str(&default_json).expect("default-mode stdout is JSON");
    let default_count = default_findings.as_array().map(|a| a.len()).unwrap_or(0);

    let opt_in_out = Command::new(binary())
        .arg("scan")
        .arg("--scan-comments")
        .arg("--format")
        .arg("json")
        .arg(&path)
        .output()
        .expect("spawn keyhog scan --scan-comments");
    let opt_in_json = String::from_utf8_lossy(&opt_in_out.stdout);
    let opt_in_findings: serde_json::Value =
        serde_json::from_str(&opt_in_json).expect("opt-in stdout is JSON");
    let opt_in_count = opt_in_findings.as_array().map(|a| a.len()).unwrap_or(0);

    assert!(
        opt_in_count >= default_count,
        "--scan-comments must not LOSE findings vs default; \
         default={default_count}, --scan-comments={opt_in_count}, \
         default_json={default_json}, opt_in_json={opt_in_json}"
    );

    // At minimum --scan-comments fires on this AKIA-prefixed key
    // (the keyhog known-prefix floor keeps it above any penalty).
    assert!(
        opt_in_count >= 1,
        "--scan-comments MUST surface the AKIA-prefixed key in the \
         comment; got {opt_in_count} findings: {opt_in_json}"
    );
}

fn workspace_detectors() -> PathBuf {
    PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .join("../../detectors")
        .canonicalize()
        .expect("workspace detectors dir")
}

#[cfg(feature = "git")]
fn init_git_repo(repo_path: &std::path::Path) {
    use std::process::Command;
    for args in [
        ["init", "-b", "main"],
        ["config", "user.email", "test@example.com"],
        ["config", "user.name", "Test User"],
    ] {
        let output = Command::new("git")
            .args(args)
            .current_dir(repo_path)
            .output()
            .expect("git setup");
        assert!(output.status.success(), "git setup failed: {output:?}");
    }
}

#[cfg(feature = "git")]
#[test]
fn git_staged_scan_finds_only_staged_secret() {
    use std::process::Command;

    let repo = TempDir::new().expect("tempdir");
    let repo_path = repo.path();
    init_git_repo(repo_path);

    std::fs::write(
        repo_path.join("staged.env"),
        concat!("AWS_ACCESS_KEY_ID = \"AKIA", "QYLPMN5HFIQR7XYA\"\n"),
    )
    .unwrap();
    std::fs::write(
        repo_path.join("unstaged.env"),
        "AWS_ACCESS_KEY_ID = \"AKIAQYLPMN5HUNSTAGEDKEY000000000000\"\n",
    )
    .unwrap();
    Command::new("git")
        .args(["add", "staged.env"])
        .current_dir(repo_path)
        .output()
        .unwrap();

    let output = Command::new(binary())
        .current_dir(repo_path)
        .args([
            "scan",
            "--git-staged",
            "--no-daemon",
            "--format",
            "json",
            "--path",
            ".",
        ])
        .output()
        .expect("git-staged scan");

    assert_eq!(
        output.status.code(),
        Some(1),
        "staged secret must exit 1; stderr={}",
        String::from_utf8_lossy(&output.stderr)
    );
    let findings: serde_json::Value =
        serde_json::from_slice(&output.stdout).expect("stdout is JSON");
    let arr = findings.as_array().expect("array");
    assert!(
        arr.iter().any(|f| {
            f.get("location")
                .and_then(|l| l.get("file_path"))
                .and_then(|p| p.as_str())
                .is_some_and(|p| p.ends_with("staged.env"))
        }),
        "must find staged file secret; got {arr:?}"
    );
    assert!(
        !arr.iter().any(|f| {
            f.get("location")
                .and_then(|l| l.get("file_path"))
                .and_then(|p| p.as_str())
                .is_some_and(|p| p.contains("unstaged.env"))
        }),
        "unstaged file must not be scanned; got {arr:?}"
    );
}

#[test]
fn baseline_suppresses_acknowledged_findings_on_rescan() {
    let dir = TempDir::new().expect("tempdir");
    let fixture = dir.path().join("planted.txt");
    std::fs::write(
        &fixture,
        concat!("AWS_ACCESS_KEY_ID = \"AKIA", "QYLPMN5HFIQR7XYA\"\n"),
    )
    .unwrap();
    let baseline_path = dir.path().join("baseline.json");

    let create = Command::new(binary())
        .args([
            "scan",
            "--no-daemon",
            "--create-baseline",
            baseline_path.to_str().unwrap(),
            "--format",
            "json",
        ])
        .arg(&fixture)
        .output()
        .expect("create baseline");
    assert_eq!(
        create.status.code(),
        Some(0),
        "create-baseline must exit 0; stderr={}",
        String::from_utf8_lossy(&create.stderr)
    );
    assert!(baseline_path.exists(), "baseline file must be written");

    let filtered = Command::new(binary())
        .args([
            "scan",
            "--no-daemon",
            "--baseline",
            baseline_path.to_str().unwrap(),
            "--format",
            "json",
        ])
        .arg(&fixture)
        .output()
        .expect("baseline-filter scan");
    assert_eq!(
        filtered.status.code(),
        Some(0),
        "baseline-filtered rescan must exit 0; stderr={}",
        String::from_utf8_lossy(&filtered.stderr)
    );
    let findings: serde_json::Value =
        serde_json::from_slice(&filtered.stdout).expect("filtered stdout is JSON");
    assert!(
        findings.as_array().is_some_and(|a| a.is_empty()),
        "baseline must suppress known findings; got {findings:?}"
    );
}

#[test]
fn lockdown_bails_on_verify_flag() {
    let dir = TempDir::new().expect("tempdir");
    let fixture = dir.path().join("planted.txt");
    std::fs::write(
        &fixture,
        concat!("AWS_ACCESS_KEY_ID = \"AKIA", "QYLPMN5HFIQR7XYA\"\n"),
    )
    .unwrap();

    // Lockdown requires RLIMIT_CORE=0 on Linux so coredump_filter checks
    // pass; `prlimit --core=0` sets that for the child without touching
    // the test runner's own limits.
    let mut cmd = Command::new("prlimit");
    cmd.args(["--core=0"])
        .arg(binary())
        .args([
            "scan",
            "--no-daemon",
            "--lockdown",
            "--verify",
            "--format",
            "json",
        ])
        .arg(&fixture);
    let output = match cmd.output() {
        Ok(out) => out,
        Err(_) => Command::new(binary())
            .args([
                "scan",
                "--no-daemon",
                "--lockdown",
                "--verify",
                "--format",
                "json",
            ])
            .arg(&fixture)
            .output()
            .expect("lockdown+verify scan"),
    };

    assert_eq!(
        output.status.code(),
        Some(2),
        "lockdown+verify must exit 2 (runtime error); got {:?}",
        output.status.code()
    );
    let combined = format!(
        "{}\n{}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr)
    );
    assert!(
        combined.contains("lockdown mode forbids --verify")
            || combined.contains("protections failed to apply"),
        "must refuse outbound verification in lockdown (or fail closed on \
         hardening); got: {combined}"
    );
    if !combined.contains("protections failed to apply") {
        assert!(
            combined.contains("lockdown mode forbids --verify"),
            "when lockdown protections apply, --verify must be refused; got: {combined}"
        );
    }
}

#[cfg(unix)]
#[test]
fn daemon_wire_scan_path_finds_planted_secret() {
    use std::process::{Child, Command, Stdio};
    use std::time::{Duration, Instant};

    let runtime = TempDir::new().expect("runtime dir");
    let dir = TempDir::new().expect("fixture dir");
    let fixture = dir.path().join("daemon_planted.txt");
    std::fs::write(
        &fixture,
        concat!("AWS_ACCESS_KEY_ID = \"AKIA", "QYLPMN5HFIQR7XYA\"\n"),
    )
    .unwrap();

    let detectors = workspace_detectors();
    let mut daemon: Child = Command::new(binary())
        .env("XDG_RUNTIME_DIR", runtime.path())
        .args([
            "daemon",
            "start",
            "--detectors",
            detectors.to_str().unwrap(),
        ])
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()
        .expect("spawn daemon");

    let socket = runtime.path().join("keyhog.sock");
    let deadline = Instant::now() + Duration::from_secs(30);
    while !socket.exists() {
        assert!(
            Instant::now() < deadline,
            "daemon socket did not appear in time"
        );
        std::thread::sleep(Duration::from_millis(50));
    }

    let scan = Command::new(binary())
        .env("XDG_RUNTIME_DIR", runtime.path())
        .args(["scan", "--daemon", "--format", "json"])
        .arg(&fixture)
        .output()
        .expect("daemon scan");

    let _ = Command::new(binary())
        .env("XDG_RUNTIME_DIR", runtime.path())
        .args(["daemon", "stop"])
        .output();
    let _ = daemon.kill();
    let _ = daemon.wait();

    assert_eq!(
        scan.status.code(),
        Some(1),
        "daemon scan must find secret (exit 1); stderr={}",
        String::from_utf8_lossy(&scan.stderr)
    );
    let findings: serde_json::Value =
        serde_json::from_slice(&scan.stdout).expect("daemon stdout is JSON");
    let arr = findings.as_array().expect("array");
    assert!(
        arr.iter().any(|f| matches!(
            f.get("detector_id").and_then(|v| v.as_str()),
            Some("aws-access-key" | "hot-aws_key")
        )),
        "daemon wire path must return an AWS finding; got {arr:?}"
    );
}

#[test]
fn doctor_reports_corpus_and_passes_scan_self_test() {
    // `keyhog doctor` is the install health check. On a healthy host it must
    // exit 0, report the real embedded detector corpus (not 0), and PASS the
    // end-to-end scan self-test (plant -> scan -> match). Asserting the
    // displayed count equals the binary's own embedded count proves the
    // report reflects reality, not a hardcoded banner number.
    let output = Command::new(binary())
        .arg("doctor")
        .env("KEYHOG_NO_GPU", "1")
        .output()
        .expect("run keyhog doctor");
    let stdout = String::from_utf8_lossy(&output.stdout);

    assert_eq!(
        output.status.code(),
        Some(0),
        "doctor must exit 0 on a healthy host (PATH warning is non-fatal); stdout:\n{stdout}"
    );
    assert!(
        stdout.contains("self-test"),
        "doctor must run a self-test section; got:\n{stdout}"
    );
    assert!(
        stdout.contains("PASS"),
        "the scan-engine self-test must PASS; got:\n{stdout}"
    );
    let corpus = keyhog_core::embedded_detector_count();
    assert!(corpus > 0, "binary must embed a detector corpus");
    assert!(
        stdout.contains(&corpus.to_string()),
        "doctor must display the real embedded corpus count ({corpus}); got:\n{stdout}"
    );
}

#[test]
fn update_subcommand_is_wired_with_its_flags() {
    // `keyhog update`'s download/replace path is network-bound (it queries the
    // GitHub releases API), so it can't be a deterministic offline snapshot -
    // its pure logic (asset selection, semver compare, executable-magic guard)
    // is unit-tested in subcommands::update. This e2e confirms the subcommand
    // and its flags are actually registered in the CLI (a wiring regression
    // would otherwise only surface when a user runs it).
    let output = Command::new(binary())
        .arg("update")
        .arg("--help")
        .output()
        .expect("run keyhog update --help");
    assert!(
        output.status.success(),
        "`keyhog update --help` must succeed; stderr:\n{}",
        String::from_utf8_lossy(&output.stderr)
    );
    let help = String::from_utf8_lossy(&output.stdout);
    for flag in ["--check", "--version", "--variant"] {
        assert!(
            help.contains(flag),
            "`keyhog update --help` must document {flag}; got:\n{help}"
        );
    }
}

#[test]
fn repair_subcommand_is_wired_with_its_flags() {
    // Like `update`, `repair`'s download/reinstall path is network-bound; its
    // shared logic is unit-tested in crate::installer. This confirms the
    // subcommand + flags are registered.
    let output = Command::new(binary())
        .arg("repair")
        .arg("--help")
        .output()
        .expect("run keyhog repair --help");
    assert!(
        output.status.success(),
        "`keyhog repair --help` must succeed; stderr:\n{}",
        String::from_utf8_lossy(&output.stderr)
    );
    let help = String::from_utf8_lossy(&output.stdout);
    for flag in ["--force", "--version", "--variant"] {
        assert!(
            help.contains(flag),
            "`keyhog repair --help` must document {flag}; got:\n{help}"
        );
    }
}

#[test]
fn uninstall_dry_run_does_not_remove_the_binary() {
    // Safety contract: `keyhog uninstall` without `--yes` must be a no-op dry
    // run - it must NOT delete the binary. (Running it against the test binary
    // is safe precisely because of this guarantee; a regression here would
    // delete the test runner's own binary.)
    let bin = binary();
    let output = Command::new(&bin)
        .arg("uninstall")
        .output()
        .expect("run keyhog uninstall");
    assert!(
        output.status.success(),
        "dry-run uninstall must exit 0; stderr:\n{}",
        String::from_utf8_lossy(&output.stderr)
    );
    let out = String::from_utf8_lossy(&output.stdout).to_lowercase();
    assert!(
        out.contains("dry run"),
        "uninstall without --yes must announce it's a dry run; got:\n{out}"
    );
    assert!(
        bin.exists(),
        "dry-run uninstall MUST NOT delete the binary at {}",
        bin.display()
    );
}

/// Write `content` + a `.keyhog.toml` of `config` into a temp dir, scan the
/// dir, return (stdout, stderr, exit-code). Exercises the real config-load
/// path (`.keyhog.toml` discovery + `apply_config_file`).
fn scan_dir_with_config(
    content: &str,
    config: &str,
    extra: &[&str],
) -> (String, String, Option<i32>) {
    let dir = TempDir::new().expect("tempdir");
    std::fs::write(dir.path().join("planted.txt"), content).expect("write fixture");
    std::fs::write(dir.path().join(".keyhog.toml"), config).expect("write config");
    let output = Command::new(binary())
        .args(["scan", "--no-daemon", "--format", "json"])
        .args(extra)
        .arg(dir.path())
        .output()
        .expect("spawn keyhog scan");
    (
        String::from_utf8_lossy(&output.stdout).into_owned(),
        String::from_utf8_lossy(&output.stderr).into_owned(),
        output.status.code(),
    )
}

#[test]
fn config_detector_disable_drops_findings() {
    // `[detector.<id>] enabled = false` must actually drop the detector. This
    // README-documented toggle was parsed and SILENTLY IGNORED before being
    // wired, so a user disabling a noisy detector kept seeing it fire. The
    // hot-pattern fast path (`hot-aws_key`) shadows the TOML `aws-access-key`
    // detector, so both must be disabled to fully silence the AWS key.
    let aws = concat!("AWS_ACCESS_KEY_ID = \"AKIA", "QYLPMN5HFIQR7XYA\"\n");
    let (_o, _e, before) = scan_dir_with_config(aws, "", &[]);
    assert_eq!(before, Some(1), "baseline: the AWS key must be found");
    let (out, _e, code) = scan_dir_with_config(
        aws,
        "[detector.hot-aws_key]\nenabled = false\n[detector.aws-access-key]\nenabled = false\n",
        &[],
    );
    assert_eq!(
        code,
        Some(0),
        "disabling the AWS detectors via .keyhog.toml must yield zero findings; stdout={out}"
    );
}

#[test]
fn config_lockdown_require_refuses_without_flag() {
    // `[lockdown] require = true` is a fail-closed security control: refuse to
    // run unless --lockdown is passed (README: "refuse to run without
    // --lockdown"). It was parsed and silently ignored, so a repo that believed
    // it mandated lockdown ran unprotected. The refusal must be explicit.
    let (_o, err, code) =
        scan_dir_with_config("ordinary content\n", "[lockdown]\nrequire = true\n", &[]);
    assert_ne!(
        code,
        Some(0),
        "a repo whose .keyhog.toml requires lockdown must NOT run without --lockdown"
    );
    assert!(
        err.to_lowercase().contains("lockdown"),
        "the refusal must name lockdown so the operator knows why; stderr={err}"
    );
}