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
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
//! Micro gate for `cli/daemon/frame.rs` and `cli/daemon/protocol.rs`.

use crate::daemon::frame;
use crate::daemon::protocol::{
    BackendRecoveryStatus, RecoveredInputRangeStatus, Request, RequiredOption, Response,
    SourceCoverageGaps, WarmBackendIdentity, WarmBackendStatus, WIRE_VERSION,
};
use keyhog_scanner::telemetry::StaticRecoveryStatus;
use std::collections::BTreeMap;
use tokio::io::AsyncWriteExt;

fn ready_warm_backend() -> WarmBackendStatus {
    WarmBackendStatus {
        ready: true,
        daemon_generation: "test-generation".into(),
        identity: WarmBackendIdentity {
            engine: "test-engine".into(),
            gpu_artifact: None,
            binary_sha256: "test-binary".into(),
            detector_rules_digest: "rules123".into(),
            config_digest: "test-config".into(),
        },
        required_backends: vec!["cpu-fallback".into()],
        initialized_backends: vec!["cpu-fallback".into()],
        reason: None,
        repair_command: None,
    }
}

#[tokio::test]
async fn daemon_wire_v10_hello_roundtrip_carries_mass_gpu_contract() {
    let (mut client, mut server) = tokio::io::duplex(64 * 1024);

    frame::write_request(&mut client, &Request::Hello)
        .await
        .expect("write Hello");
    let req = frame::read_request(&mut server)
        .await
        .expect("read request")
        .expect("Hello frame");
    assert!(matches!(req, Request::Hello));

    frame::write_response(
        &mut server,
        &Response::Hello {
            wire_version: WIRE_VERSION,
            keyhog_version: "test".into(),
            git_hash: "abc123".into(),
            detector_rules_digest: "rules123".into(),
            backend_policy: "cpu-fallback".into(),
            detector_count: 1,
            uptime_secs: 0,
            warm_backend: ready_warm_backend(),
            mass_service: true,
            mass_gpu_primary_required: true,
        },
    )
    .await
    .expect("write Hello response");
    let resp = frame::read_response(&mut client)
        .await
        .expect("read response")
        .expect("Hello response frame");
    match resp {
        Response::Hello {
            wire_version,
            mass_gpu_primary_required,
            ..
        } => {
            assert_eq!(wire_version, WIRE_VERSION);
            assert!(mass_gpu_primary_required);
        }
        other => panic!("expected Hello response, got {other:?}"),
    }
}

#[tokio::test]
async fn daemon_scan_text_roundtrip_carries_matches() {
    use keyhog_core::{MatchLocation, RawMatch, Severity};
    use std::sync::Arc;

    let (mut client, mut server) = tokio::io::duplex(256 * 1024);
    let sample = RawMatch {
        detector_id: Arc::from("aws-access-key"),
        detector_name: Arc::from("AWS Access Key"),
        service: Arc::from("aws"),
        severity: Severity::Critical,
        credential: keyhog_core::SensitiveString::from(concat!("AK", "IAQYLPMN5HFIQR7XYA")),
        credential_hash: [7u8; 32].into(),
        companions: Default::default(),
        location: MatchLocation {
            source: Arc::from("daemon"),
            file_path: Some(Arc::from("test.txt")),
            line: Some(1),
            offset: 0,
            commit: None,
            author: None,
            date: None,
        },
        entropy: None,
        confidence: None,
    };

    frame::write_request(
        &mut client,
        &Request::ScanText {
            path: Some("test.txt".into()),
            text: concat!("AK", "IAQYLPMN5HFIQR7XYA").into(),
            dogfood: false,
            profile: false,
        },
    )
    .await
    .unwrap();
    let req = frame::read_request(&mut server).await.unwrap().unwrap();
    assert!(matches!(req, Request::ScanText { .. }));

    frame::write_response(
        &mut server,
        &Response::ScanResults {
            path: Some("test.txt".into()),
            matches: vec![sample],
            engine_example_suppressions: 0,
            dogfood_events: vec![],
            static_recovery_rejections: BTreeMap::new(),
            static_recovery_status: StaticRecoveryStatus::default(),
            dogfood_detail_events_dropped: 0,
            source_coverage_gaps: Default::default(),
            backend_recovery: RequiredOption::None,
            profile: RequiredOption::None,
        },
    )
    .await
    .unwrap();
    let resp = frame::read_response(&mut client).await.unwrap().unwrap();
    match resp {
        Response::ScanResults { matches, .. } => {
            assert_eq!(matches.len(), 1);
            assert_eq!(matches[0].detector_id.as_ref(), "aws-access-key");
        }
        other => panic!("expected ScanResults, got {other:?}"),
    }
}

#[test]
fn daemon_wire_v8_requires_every_scan_result_integrity_field() {
    let complete = Response::ScanResults {
        path: None,
        matches: vec![],
        engine_example_suppressions: 0,
        dogfood_events: vec![],
        static_recovery_rejections: BTreeMap::new(),
        static_recovery_status: StaticRecoveryStatus::default(),
        dogfood_detail_events_dropped: 0,
        source_coverage_gaps: SourceCoverageGaps::default(),
        backend_recovery: RequiredOption::None,
        profile: RequiredOption::None,
    };
    let complete = serde_json::to_value(complete).expect("serialize complete response");

    for missing in [
        "engine_example_suppressions",
        "dogfood_events",
        "source_coverage_gaps",
        "static_recovery_rejections",
        "static_recovery_status",
        "dogfood_detail_events_dropped",
        "backend_recovery",
        "profile",
    ] {
        let mut incomplete = complete.clone();
        incomplete
            .as_object_mut()
            .expect("response object")
            .remove(missing);
        let error = serde_json::from_value::<Response>(incomplete)
            .expect_err("wire-v8 ScanResults must reject omitted integrity fields");
        assert!(
            error.to_string().contains(missing),
            "missing {missing} must be named in the frame error: {error}"
        );
    }

    let mut incomplete = complete;
    incomplete["source_coverage_gaps"]
        .as_object_mut()
        .expect("coverage object")
        .remove("over_max_size");
    let error = serde_json::from_value::<Response>(incomplete)
        .expect_err("wire-v8 must reject incomplete source coverage");
    assert!(error.to_string().contains("over_max_size"));
}

#[test]
fn daemon_scan_results_source_coverage_gaps_roundtrip_exactly() {
    let response = Response::ScanResults {
        path: None,
        matches: vec![],
        engine_example_suppressions: 0,
        dogfood_events: vec![],
        static_recovery_rejections: BTreeMap::from([("json_base64".into(), 3)]),
        static_recovery_status: StaticRecoveryStatus {
            supported: 5,
            unsupported: 0,
            erroneous: 3,
        },
        dogfood_detail_events_dropped: 7,
        source_coverage_gaps: SourceCoverageGaps {
            binary: 1,
            ..Default::default()
        },
        backend_recovery: RequiredOption::Some(BackendRecoveryStatus {
            failed_backend: "gpu-cuda-region-presence".into(),
            recovery_backend: "cpu-fallback".into(),
            recovered_ranges: vec![RecoveredInputRangeStatus {
                chunk_index: 2,
                byte_start: 64,
                byte_end: 96,
            }],
            recovered_chunks: 1,
            recovered_bytes: 32,
            reason: "injected dispatch fault".into(),
        }),
        profile: RequiredOption::None,
    };
    let encoded = serde_json::to_string(&response).expect("serialize scan results");
    let decoded: Response = serde_json::from_str(&encoded).expect("deserialize scan results");
    match decoded {
        Response::ScanResults {
            source_coverage_gaps,
            static_recovery_rejections,
            static_recovery_status,
            dogfood_detail_events_dropped,
            backend_recovery,
            ..
        } => {
            assert_eq!(source_coverage_gaps.binary, 1);
            assert_eq!(source_coverage_gaps.total(), 1);
            // KH-1368: WARN-class binary alone must not trip FAIL incomplete.
            assert!(source_coverage_gaps.fail_class_empty());
            assert_eq!(
                SourceCoverageGaps {
                    unreadable: 2,
                    binary: 9,
                    ..Default::default()
                }
                .fail_class_total(),
                2
            );
            assert_eq!(static_recovery_rejections["json_base64"], 3);
            assert_eq!(
                static_recovery_status,
                StaticRecoveryStatus {
                    supported: 5,
                    unsupported: 0,
                    erroneous: 3,
                }
            );
            assert_eq!(dogfood_detail_events_dropped, 7);
            let recovery = backend_recovery.expect("recovery status");
            assert_eq!(recovery.recovered_bytes, 32);
            assert_eq!(
                recovery.recovered_ranges,
                vec![RecoveredInputRangeStatus {
                    chunk_index: 2,
                    byte_start: 64,
                    byte_end: 96,
                }]
            );
        }
        other => panic!("expected ScanResults, got {other:?}"),
    }
}

#[tokio::test]
async fn daemon_frame_rejects_oversized_length_prefix() {
    use keyhog::daemon::protocol::MAX_FRAME_BYTES;

    let (mut client, mut server) = tokio::io::duplex(256);
    let bogus_len = (MAX_FRAME_BYTES + 1).to_be_bytes();
    client.write_all(&bogus_len).await.unwrap();
    let err = frame::read_request(&mut server).await.unwrap_err();
    assert!(
        err.to_string().contains("exceeds"),
        "oversized frame must be rejected; got {err}"
    );
}

/// Locks the v14 bump: daemon-local filesystem scans now carry incremental
/// cache state and stream bounded responses after one drain request. Older
/// peers must fail at Hello instead of disagreeing about frame cardinality.
#[test]
fn daemon_wire_version_is_v14_with_mass_filesystem_protocol() {
    assert_eq!(WIRE_VERSION, 14);
}

#[tokio::test]
async fn daemon_wire_v14_mass_incremental_cache_roundtrips() {
    let request = Request::MassFilesystemBegin {
        root: "/workspace".into(),
        max_file_size: 1024,
        ignore_paths: vec!["target".into()],
        respect_default_excludes: true,
        reader_threads: Some(2),
        incremental_cache: Some("/cache/keyhog/merkle.idx".into()),
    };
    let encoded = serde_json::to_string(&request).expect("serialize request");
    let decoded: Request = serde_json::from_str(&encoded).expect("deserialize request");
    let reencoded = serde_json::to_string(&decoded).expect("re-serialize request");
    assert_eq!(
        reencoded, encoded,
        "the exact incremental cache identity must survive the wire boundary"
    );
}

#[tokio::test]
async fn daemon_wire_v14_mass_filesystem_drain_roundtrips() {
    let (mut client, mut server) = tokio::io::duplex(1024);
    frame::write_request(&mut client, &Request::MassFilesystemDrain)
        .await
        .expect("write mass filesystem drain");
    let request = frame::read_request(&mut server)
        .await
        .expect("read request")
        .expect("mass filesystem drain frame");
    assert!(matches!(request, Request::MassFilesystemDrain));
}

/// The v12 `profile` opt-in must survive the frame round-trip verbatim on
/// every request kind that carries it; a dropped flag would silently turn
/// off per-request profiling on the daemon route.
#[tokio::test]
async fn daemon_wire_v12_profile_flag_roundtrips_on_scan_requests() {
    let requests = [
        Request::ScanText {
            path: Some("stdin".into()),
            text: "payload".into(),
            dogfood: false,
            profile: true,
        },
        Request::ScanPath {
            path: "src/main.rs".into(),
            working_dir: Some("/tmp/project".into()),
            dogfood: false,
            profile: true,
        },
        Request::MassBegin {
            dogfood: true,
            profile: true,
        },
        Request::ScanText {
            path: None,
            text: "unprofiled".into(),
            dogfood: false,
            profile: false,
        },
    ];
    for request in requests {
        let encoded = serde_json::to_string(&request).expect("serialize request");
        let decoded: Request = serde_json::from_str(&encoded).expect("deserialize request");
        let (expected, actual) = match (&request, &decoded) {
            (
                Request::ScanText {
                    profile: expected, ..
                },
                Request::ScanText {
                    profile: actual, ..
                },
            )
            | (
                Request::ScanPath {
                    profile: expected, ..
                },
                Request::ScanPath {
                    profile: actual, ..
                },
            )
            | (
                Request::MassBegin {
                    profile: expected, ..
                },
                Request::MassBegin {
                    profile: actual, ..
                },
            ) => (expected, actual),
            (sent, got) => panic!("request kind changed across the wire: {sent:?} -> {got:?}"),
        };
        assert_eq!(expected, actual, "profile flag must round-trip exactly");
    }
}

/// A profiled v12 `ScanResults` must carry the exact request profile payload
/// (id, wall time, per-stage aggregates, loss counts) across the frame
/// boundary, and an unprofiled response must serialize `profile` as an
/// explicit null that deserializes back to `None`, never to a fabricated
/// zero-valued profile.
#[tokio::test]
async fn daemon_wire_v12_scan_results_roundtrips_request_profile() {
    use crate::daemon::protocol::{ProfileStageMeasurement, RequestProfile};

    let profile = RequestProfile {
        request_id: "4242-after-00000001-00000000-0000000000000000".into(),
        wall_time_ns: 1_523_987,
        stages: vec![
            ProfileStageMeasurement {
                stage: "phase1-triggers".into(),
                calls: 3,
                elapsed_ns: 981_114,
            },
            ProfileStageMeasurement {
                stage: "entropy".into(),
                calls: 1,
                elapsed_ns: 12_500,
            },
        ],
        dropped_span_events: 2,
        dropped_point_events: 0,
        dropped_annotations: 1,
        sampled_out_events: 5,
    };
    let response = Response::ScanResults {
        path: None,
        matches: vec![],
        engine_example_suppressions: 0,
        dogfood_events: vec![],
        static_recovery_rejections: BTreeMap::new(),
        static_recovery_status: StaticRecoveryStatus::default(),
        dogfood_detail_events_dropped: 0,
        source_coverage_gaps: SourceCoverageGaps::default(),
        backend_recovery: RequiredOption::None,
        profile: RequiredOption::Some(profile.clone()),
    };

    let (mut client, mut server) = tokio::io::duplex(64 * 1024);
    frame::write_response(&mut server, &response)
        .await
        .expect("write profiled ScanResults");
    let decoded = frame::read_response(&mut client)
        .await
        .expect("read response")
        .expect("ScanResults frame");
    match decoded {
        Response::ScanResults {
            profile: decoded, ..
        } => {
            let decoded = decoded.expect("request profile");
            assert_eq!(decoded, profile, "profile payload must round-trip exactly");
        }
        other => panic!("expected ScanResults, got {other:?}"),
    }

    let unprofiled = Response::ScanResults {
        path: None,
        matches: vec![],
        engine_example_suppressions: 0,
        dogfood_events: vec![],
        static_recovery_rejections: BTreeMap::new(),
        static_recovery_status: StaticRecoveryStatus::default(),
        dogfood_detail_events_dropped: 0,
        source_coverage_gaps: SourceCoverageGaps::default(),
        backend_recovery: RequiredOption::None,
        profile: RequiredOption::None,
    };
    let encoded = serde_json::to_value(&unprofiled).expect("serialize unprofiled response");
    assert_eq!(
        encoded["profile"],
        serde_json::Value::Null,
        "unprofiled ScanResults must carry an explicit null profile field"
    );
    let decoded: Response = serde_json::from_value(encoded).expect("deserialize unprofiled");
    match decoded {
        Response::ScanResults { profile, .. } => {
            assert!(profile.is_none(), "null profile must decode to None");
        }
        other => panic!("expected ScanResults, got {other:?}"),
    }
}

/// The v13 `GuardList` request and `GuardListResult` response must round-trip
/// through the frame boundary with all root entries preserved.
#[tokio::test]
async fn daemon_wire_v13_guard_list_roundtrips() {
    use crate::daemon::protocol::{GuardListEntry, Request, Response};

    let (mut client, mut server) = tokio::io::duplex(64 * 1024);

    frame::write_request(&mut client, &Request::GuardList)
        .await
        .expect("write GuardList");
    let req = frame::read_request(&mut server)
        .await
        .expect("read request")
        .expect("GuardList frame");
    assert!(matches!(req, Request::GuardList));

    let response = Response::GuardListResult {
        roots: vec![
            GuardListEntry {
                root: "/work/project".to_string(),
                mode: "repo".to_string(),
                state: "current".to_string(),
                terminal_sequence: 42,
            },
            GuardListEntry {
                root: "/srv/data".to_string(),
                mode: "filesystem".to_string(),
                state: "indexing".to_string(),
                terminal_sequence: 0,
            },
        ],
    };
    frame::write_response(&mut server, &response)
        .await
        .expect("write GuardListResult");
    let resp = frame::read_response(&mut client)
        .await
        .expect("read response")
        .expect("GuardListResult frame");
    match resp {
        Response::GuardListResult { roots } => {
            assert_eq!(roots.len(), 2);
            assert_eq!(roots[0].root, "/work/project");
            assert_eq!(roots[0].mode, "repo");
            assert_eq!(roots[0].state, "current");
            assert_eq!(roots[0].terminal_sequence, 42);
            assert_eq!(roots[1].root, "/srv/data");
            assert_eq!(roots[1].mode, "filesystem");
            assert_eq!(roots[1].state, "indexing");
            assert_eq!(roots[1].terminal_sequence, 0);
        }
        other => panic!("expected GuardListResult, got {other:?}"),
    }
}