keyhog 0.5.85

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
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
//! WHY THIS TEST EXISTS:
//! Row 7 / Host independence contract:
//! Install scripts across Unix (`install.sh`) and Windows (`install.ps1`) must
//! maintain exact functional parity for every public mode, parameter, and
//! security verification step.
//!
//! WHAT IT DOES NOT CATCH:
//! Live PowerShell execution on Linux without pwsh installed (covered on Windows
//! runners in CI / action-e2e).

use std::collections::BTreeSet;
use std::path::Path;

fn repo_root() -> &'static Path {
    Path::new(env!("CARGO_MANIFEST_DIR"))
        .parent()
        .expect("crates/")
        .parent()
        .expect("repo root")
}

fn parse_sh_modes(content: &str) -> BTreeSet<String> {
    let mut modes = BTreeSet::new();
    let mut in_modes = false;

    for line in content.lines() {
        let trimmed = line.trim();
        if trimmed.starts_with("# Modes:") {
            in_modes = true;
            continue;
        }
        if in_modes {
            if trimmed.starts_with("# Common flags:")
                || trimmed.starts_with("# Env overrides:")
                || trimmed.is_empty()
            {
                break;
            }
            if let Some(rest) = trimmed.strip_prefix("#") {
                let text = rest.trim();
                if text.starts_with("--") {
                    let mode = text
                        .split_whitespace()
                        .next()
                        .unwrap()
                        .trim_start_matches("--");
                    modes.insert(mode.to_string());
                } else if text.starts_with("(default)") {
                    modes.insert("default".to_string());
                }
            }
        }
    }
    modes
}

fn parse_ps1_modes(content: &str) -> BTreeSet<String> {
    let mut modes = BTreeSet::new();
    let mut in_modes = false;

    for line in content.lines() {
        let trimmed = line.trim();
        if trimmed.starts_with("# Modes:") {
            in_modes = true;
            continue;
        }
        if in_modes {
            if trimmed.starts_with("# Common flags:")
                || trimmed.starts_with("# Env overrides:")
                || trimmed.is_empty()
            {
                break;
            }
            if let Some(rest) = trimmed.strip_prefix("#") {
                let text = rest.trim();
                if text.starts_with("-") {
                    let mode = text
                        .split_whitespace()
                        .next()
                        .unwrap()
                        .trim_start_matches("-")
                        .to_lowercase();
                    modes.insert(mode);
                } else if text.starts_with("(default)") {
                    modes.insert("default".to_string());
                }
            }
        }
    }
    modes
}

fn parse_sh_flags(content: &str) -> BTreeSet<String> {
    let mut flags = BTreeSet::new();
    let mut in_flags = false;

    for line in content.lines() {
        let trimmed = line.trim();
        if trimmed.starts_with("# Common flags:") {
            in_flags = true;
            continue;
        }
        if in_flags {
            if trimmed.starts_with("# Env overrides:") || trimmed.is_empty() {
                break;
            }
            if let Some(rest) = trimmed.strip_prefix("#") {
                let text = rest.trim();
                if text.starts_with("--") {
                    let flag = text
                        .split_whitespace()
                        .next()
                        .unwrap()
                        .split('=')
                        .next()
                        .unwrap()
                        .trim_start_matches("--")
                        .to_string();
                    flags.insert(flag);
                }
            }
        }
    }
    flags
}

/// PowerShell switches are PascalCase (`-NoCalibrate`); the shell spells the
/// same flag `--no-calibrate`. Fold the PowerShell name to the shell one so the
/// two documented sets are comparable as sets.
fn kebab_case(name: &str) -> String {
    let mut out = String::with_capacity(name.len() + 2);
    for (index, ch) in name.chars().enumerate() {
        if ch.is_ascii_uppercase() && index > 0 {
            out.push('-');
        }
        out.extend(ch.to_lowercase());
    }
    out
}

fn parse_ps1_flags(content: &str) -> BTreeSet<String> {
    let mut flags = BTreeSet::new();
    let mut in_flags = false;

    for line in content.lines() {
        let trimmed = line.trim();
        if trimmed.starts_with("# Common flags:") {
            in_flags = true;
            continue;
        }
        if in_flags {
            if trimmed.starts_with("# Env overrides:") || trimmed.is_empty() {
                break;
            }
            if let Some(rest) = trimmed.strip_prefix("#") {
                let text = rest.trim();
                if text.starts_with('-') {
                    let flag = text.split_whitespace().next().unwrap();
                    flags.insert(kebab_case(flag.trim_start_matches('-')));
                }
            }
        }
    }
    flags
}

fn extract_public_key(content: &str) -> Option<String> {
    for line in content.lines() {
        if line.contains("RWTPnJ/p6xVJ3TJIxr+ZVHMD/MTHWZhsdE38Go/oD3DYBoi4bePR55go") {
            return Some("RWTPnJ/p6xVJ3TJIxr+ZVHMD/MTHWZhsdE38Go/oD3DYBoi4bePR55go".to_string());
        }
    }
    None
}

#[test]
fn install_scripts_expose_matching_modes_and_parity() {
    let root = repo_root();
    let sh_path = root.join("install.sh");
    let ps1_path = root.join("install.ps1");

    assert!(sh_path.exists(), "install.sh must exist at repo root");
    assert!(ps1_path.exists(), "install.ps1 must exist at repo root");

    let sh_content = std::fs::read_to_string(&sh_path).expect("read install.sh");
    let ps1_content = std::fs::read_to_string(&ps1_path).expect("read install.ps1");

    let sh_modes = parse_sh_modes(&sh_content);
    let ps1_modes = parse_ps1_modes(&ps1_content);

    assert!(
        !sh_modes.is_empty(),
        "install.sh must document public execution modes"
    );
    assert_eq!(
        sh_modes, ps1_modes,
        "install.sh and install.ps1 must document identical public modes"
    );

    // Mandatory canonical modes. `repair` went with the retired binary-asset
    // channel: reinstalling now means `cargo install --locked --force keyhog`.
    for required in &["default", "diagnose", "calibrate", "uninstall"] {
        assert!(
            sh_modes.contains(*required),
            "installer modes must contain mandatory '{required}' mode"
        );
    }
}

#[test]
fn install_scripts_share_public_signing_key_and_repo() {
    let root = repo_root();
    let sh_content = std::fs::read_to_string(root.join("install.sh")).expect("read install.sh");
    let ps1_content = std::fs::read_to_string(root.join("install.ps1")).expect("read install.ps1");

    let sh_key = extract_public_key(&sh_content);
    let ps1_key = extract_public_key(&ps1_content);

    assert!(sh_key.is_some(), "install.sh must carry release public key");
    assert_eq!(
        sh_key, ps1_key,
        "install.sh and install.ps1 must use identical release public keys"
    );

    assert!(
        sh_content.contains("santhreal/keyhog"),
        "install.sh must target canonical santhreal/keyhog repository"
    );
    assert!(
        ps1_content.contains("santhreal/keyhog"),
        "install.ps1 must target canonical santhreal/keyhog repository"
    );
}

/// WHY: this file's contract is "exact functional parity for every public mode,
/// parameter, and security verification step", and this test asserted only that
/// each script documents at least one flag. It could not fail on the bug it
/// names. It did not: `install.sh --no-calibrate` had no PowerShell
/// counterpart, so a Windows install had no way to skip the autoroute
/// measurement phase that a POSIX install skips with one flag, and neither did
/// `--no-prompt` or `--help`.
///
/// WHAT IT DOES NOT CATCH: a flag documented on both sides and implemented on
/// one. The behavior half is asserted below against the argument parsers.
#[test]
fn install_scripts_share_common_flags() {
    let root = repo_root();
    let sh_content = std::fs::read_to_string(root.join("install.sh")).expect("read install.sh");
    let ps1_content = std::fs::read_to_string(root.join("install.ps1")).expect("read install.ps1");

    let sh_flags = parse_sh_flags(&sh_content);
    let ps1_flags = parse_ps1_flags(&ps1_content);

    assert!(
        !sh_flags.is_empty(),
        "install.sh must document common flags"
    );
    assert_eq!(
        sh_flags,
        ps1_flags,
        "install.sh and install.ps1 must document identical common flags\n  \
         only in install.sh: {:?}\n  only in install.ps1: {:?}",
        sh_flags.difference(&ps1_flags).collect::<Vec<_>>(),
        ps1_flags.difference(&sh_flags).collect::<Vec<_>>(),
    );

    // Every documented flag must be a real parameter, not prose. The shell
    // parses flags in a `case`; PowerShell declares them in `param()`.
    for flag in &sh_flags {
        assert!(
            sh_content.contains(&format!("--{flag}")),
            "install.sh documents --{flag} but never parses it"
        );
        let switch: String = flag
            .split('-')
            .map(|word| {
                let mut chars = word.chars();
                match chars.next() {
                    Some(first) => first.to_ascii_uppercase().to_string() + chars.as_str(),
                    None => String::new(),
                }
            })
            .collect();
        assert!(
            ps1_content.contains(&format!("${switch},"))
                || ps1_content.contains(&format!("${switch} ")),
            "install.ps1 documents -{switch} but never declares it as a parameter"
        );
    }
}

/// WHY: `--no-calibrate` is the flag that decides whether an install runs the
/// autoroute measurement ladder, minutes of probes, or finishes immediately.
/// Documenting it is not implementing it: the switch has to reach the finalize
/// step, skip the calibration call, and say so, on both platforms.
///
/// WHAT IT DOES NOT CATCH: that the skipped install is still usable with an
/// explicit `--backend`. The install-from-build fixtures cover that end to end.
#[test]
fn skipping_calibration_is_implemented_on_both_platforms() {
    let root = repo_root();
    let sh_content = std::fs::read_to_string(root.join("install.sh")).expect("read install.sh");
    let ps1_content = std::fs::read_to_string(root.join("install.ps1")).expect("read install.ps1");

    assert!(
        sh_content.contains("--no-calibrate)") && sh_content.contains("SKIP_CALIBRATION=1"),
        "install.sh must bind --no-calibrate to SKIP_CALIBRATION"
    );
    assert!(
        ps1_content.contains("if ($NoCalibrate) {"),
        "install.ps1 must branch on -NoCalibrate before calibrating"
    );

    // The notice and the calibration call must be the two arms of ONE branch.
    // A notice printed anywhere else is an install that says it skipped
    // calibration and then spends the minutes anyway.
    for (name, content, notice, guard, call) in [
        (
            "install.sh",
            &sh_content,
            "Skipped autoroute calibration by explicit --no-calibrate.",
            "SKIP_CALIBRATION",
            "calibrate_and_verify",
        ),
        (
            "install.ps1",
            &ps1_content,
            "Skipped autoroute calibration by explicit -NoCalibrate.",
            "$NoCalibrate",
            "Invoke-CalibrateAndVerify",
        ),
    ] {
        let lines: Vec<&str> = content.lines().collect();
        let notice_at = lines
            .iter()
            .position(|line| line.contains(notice))
            .unwrap_or_else(|| panic!("{name} must say out loud that it skipped calibration"));

        // Backwards: the branch the notice sits in must be the one the flag opens.
        // A notice printed above the branch is an install that reports a skip and
        // then spends the minutes anyway.
        let opener = lines[..notice_at]
            .iter()
            .rev()
            .find(|line| line.contains("if ") || line.contains("if("))
            .unwrap_or_else(|| panic!("{name}: the skip notice is not inside any branch"));
        assert!(
            opener.contains(guard),
            "{name}: the skip notice must be inside the {guard} branch, found: {opener}"
        );

        // Forwards: the opposite arm is the calibration the flag replaces.
        let arm = lines[notice_at + 1..]
            .iter()
            .take(6)
            .position(|line| {
                line.contains("elif") || line.contains("elseif") || line.contains("else")
            })
            .unwrap_or_else(|| {
                panic!("{name}: the skip notice must be one arm of the calibration branch")
            });
        assert!(
            lines[notice_at + 1 + arm..]
                .iter()
                .take(3)
                .any(|line| line.contains(call)),
            "{name}: the arm opposite the skip notice must be the {call} the flag replaces"
        );
    }
}

/// WHY: the only automatic execution-pack producer used to live in
/// `crates/cli/src/installer/execution_packs.rs`, reachable solely from the
/// self-install path fed by the retired binary-asset release channel. When that
/// channel was removed the producer went with it, and nothing noticed: with no
/// installed generation every scan silently re-parses and re-compiles the
/// embedded detector corpus. Measured on a 16-core AVX-512 host that is 284 ms
/// wall and 1570 ms CPU of scan setup against 66 ms and 110 ms with packs
/// installed. Both installers must publish a generation, and must do it BEFORE
/// calibration, because packs change the detector and config digests that
/// calibration measures its buckets against.
///
/// WHAT IT DOES NOT CATCH: whether the published generation authenticates on
/// this host. `execution_pack_install.rs` covers that through the real compiler.
#[test]
fn install_scripts_publish_execution_packs_before_calibration() {
    let root = repo_root();
    for (name, compile, calibrate) in [
        (
            "install.sh",
            "publish_execution_packs",
            "prime_autoroute_cache",
        ),
        (
            "install.ps1",
            "Publish-ExecutionPacks",
            "Invoke-AutorouteCalibration",
        ),
    ] {
        let content =
            std::fs::read_to_string(root.join(name)).unwrap_or_else(|e| panic!("read {name}: {e}"));
        assert!(
            content.contains("compile-execution-packs"),
            "{name} must invoke `keyhog compile-execution-packs`; without it every scan \
             recompiles the detector corpus"
        );
        assert!(
            content.contains("signing.key"),
            "{name} must provision the 32-byte execution-pack signing key"
        );

        // Every call to the calibration phase must be preceded by a pack
        // publication call in the same script, so no install mode calibrates
        // against digests the packs are about to change.
        let calls: Vec<usize> = content.match_indices(compile).map(|(i, _)| i).collect();
        assert!(
            calls.len() >= 2,
            "{name} must define {compile} and call it from every install mode; found {} \
             occurrence(s)",
            calls.len()
        );
        let first_publish = calls[0];
        for (index, _) in content.match_indices(calibrate) {
            assert!(
                first_publish < index,
                "{name} calls {calibrate} at byte {index} with no earlier {compile}; \
                 packs must be published before calibration"
            );
        }
    }
}

/// Both installers must probe the SAME decode-heavy size bands.
///
/// `decode_admitted` is a keyed routing dimension, and an unmeasured band is
/// served only from at least two measured bands of the same family. One decode
/// probe therefore leaves every decoding scan on that platform uncalibrated and
/// exiting 2. `install.sh` grew a three-band ladder while `install.ps1` kept a
/// single 256 KiB probe, which is exactly that failure on Windows.
///
/// Bands are read out of both scripts at run time, so adding one to either side
/// alone fails here instead of shipping.
#[test]
fn install_scripts_probe_the_same_decode_heavy_bands() {
    let root = repo_root();
    let sh = std::fs::read_to_string(root.join("install.sh")).expect("read install.sh");
    let ps1 = std::fs::read_to_string(root.join("install.ps1")).expect("read install.ps1");

    let sh_bands: BTreeSet<u32> = sh
        .lines()
        .find_map(|line| {
            line.trim()
                .strip_prefix("decode_heavy_kib_sizes=")
                .map(|value| value.trim_matches('"').to_string())
        })
        .expect("install.sh must declare decode_heavy_kib_sizes")
        .split_whitespace()
        .map(|band| band.parse().expect("a decode-heavy band is a KiB integer"))
        .collect();

    // The band list sits on the `foreach` line above the probe call.
    let ps1_lines: Vec<&str> = ps1.lines().collect();
    let ps1_bands: BTreeSet<u32> = ps1_lines
        .iter()
        .position(|line| line.contains("New-DecodeHeavyCalibrationProbeKiB -Path"))
        .and_then(|probe| {
            ps1_lines[..probe]
                .iter()
                .rev()
                .find(|line| line.contains("foreach ($kib in"))
                .copied()
        })
        .and_then(|line| {
            let open = line.find("@(")? + 2;
            let close = line[open..].find(')')? + open;
            Some(line[open..close].to_string())
        })
        .expect("install.ps1 must sweep decode-heavy bands with a foreach list")
        .split(',')
        .map(|band| {
            band.trim()
                .parse()
                .expect("a decode-heavy band is a KiB integer")
        })
        .collect();

    assert!(
        sh_bands.len() >= 2,
        "a decode family needs at least two measured bands to cover an unmeasured one; \
         install.sh probes {sh_bands:?}"
    );
    assert_eq!(
        sh_bands, ps1_bands,
        "install.sh and install.ps1 must probe the same decode-heavy bands"
    );
}

/// WHY: an install can finish "successfully" and still be unusable. Calibration
/// publishes decisions under the configuration it measured, and `keyhog doctor`
/// cannot detect a mismatch: its self-test compiles one bundled detector and
/// scans with an explicit `ScanBackend::CpuFallback`, so it passes on an install
/// whose very next auto-routed scan exits 2. That shipped: the all-policy sweep
/// spawned isolated policy children without the parent's config mode, so every
/// calibrated decision landed under a digest no plain scan resolves. Both
/// installers must therefore end the calibration phase by running one ordinary
/// scan, with no backend override and no calibration flag, and fail the install
/// when routing refuses it.
///
/// WHAT IT DOES NOT CATCH: whether the check itself resolves the same digest on
/// a host whose `.keyhog.toml` sits above the temporary scan directory. The
/// probe runs in a fresh temp tree and asks for the baseline config explicitly.
#[test]
fn install_scripts_verify_a_plain_scan_after_calibration() {
    struct Wiring {
        script: &'static str,
        open: &'static str,
        findings_exit_is_success: &'static str,
        neutral_runner: &'static str,
        chain: &'static [&'static str],
        runner_call_sites: usize,
    }

    let root = repo_root();
    for wiring in [
        Wiring {
            script: "install.sh",
            open: "verify_autoroute_serves_a_scan() {",
            findings_exit_is_success: "\"$check_status\" = \"1\"",
            neutral_runner: "run_in_neutral_dir",
            // Both entry points end in the calibration and then the check.
            chain: &[
                "calibrate_and_verify \"$bin\"",
                "prime_autoroute_cache \"$bin\"",
                "verify_autoroute_serves_a_scan \"$bin\"",
            ],
            // The install path and the standalone --calibrate mode.
            runner_call_sites: 2,
        },
        Wiring {
            script: "install.ps1",
            open: "function Test-AutorouteServesAScan {",
            findings_exit_is_success: "$scanExit -eq 1",
            neutral_runner: "Invoke-InNeutralDirectory",
            chain: &[
                "Invoke-CalibrateAndVerify -BinPath $BinPath",
                "Invoke-AutorouteCalibration -BinPath $BinPath",
                "Test-AutorouteServesAScan -BinPath $BinPath",
            ],
            runner_call_sites: 2,
        },
    ] {
        let name = wiring.script;
        let content =
            std::fs::read_to_string(root.join(name)).unwrap_or_else(|e| panic!("read {name}: {e}"));
        let start = content
            .find(wiring.open)
            .unwrap_or_else(|| panic!("{name} must define the post-calibration scan check"));
        let body = content[start..]
            .split_once("\n}\n")
            .unwrap_or_else(|| panic!("{name}: post-calibration check has no closing brace"))
            .0;

        for link in wiring.chain {
            assert!(
                content.contains(link),
                "{name}: the calibration chain must reach {link}"
            );
        }
        // Both entry points (the install and the standalone calibrate mode) must
        // hand their phase to the neutral-directory runner: a `detectors`
        // directory or a `.keyhog.toml` in the operator's cwd otherwise decides
        // which corpus and configuration every persisted decision is keyed by.
        let runner_calls = content.matches(wiring.neutral_runner).count();
        assert!(
            runner_calls >= wiring.runner_call_sites + 1,
            "{name}: every calibration entry point must go through {} ({runner_calls} \
             occurrence(s), expected the definition plus {} call site(s))",
            wiring.neutral_runner,
            wiring.runner_call_sites
        );
        assert!(
            body.contains("scan"),
            "{name}: the post-calibration check must run a real scan"
        );
        assert!(
            !body.contains("--backend"),
            "{name}: the post-calibration check must exercise the auto route, not a pinned backend"
        );
        assert!(
            !body.contains("--autoroute-calibrate"),
            "{name}: the post-calibration check must read the primed cache, not extend it"
        );
        assert!(
            body.contains("--no-config"),
            "{name}: the check must resolve the baseline configuration calibration measured"
        );
        assert!(
            body.contains(wiring.findings_exit_is_success),
            "{name}: exit 1 is findings, not a routing failure, and must pass the check"
        );
    }
}