keyhog-core 0.5.44

keyhog-core: shared data model and detector specifications for the KeyHog secret scanner
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
//! Regression lock for the `RawMatch` total ordering (`impl Ord for RawMatch`
//! in `keyhog_core::finding`), the sort keyed used by reporters and by the
//! capped per-chunk match heap to pick a deterministic survivor set.
//!
//! The ordering is a fixed key precedence, read directly off the source:
//!   1. confidence, DESCENDING (`other_conf.total_cmp(&self_conf)`), with an
//!      absent confidence treated as `0.0` (LAW10 recall-safe: `None` sorts as
//!      the lowest priority, never dropped);
//!   2. severity, DESCENDING (`other.severity.cmp(&self.severity)`: Critical
//!      before Info, the OPPOSITE direction of `Severity`'s own ascending Ord);
//!   3. detector_id, ASCENDING;
//!   4. credential, ASCENDING;
//!   5. location.offset ASCENDING, then location.line ASCENDING.
//!
//! `Vec::sort` places the cmp-"smallest" element first, so the highest-priority
//! finding (highest confidence, then highest severity, ...) lands at index 0.
//! The remaining fields are identity-only tiebreakers so `cmp == Equal` is
//! exactly equivalent to field-wise equality.
//!
//! Every assertion pins a CONCRETE value: an exact tag sequence, an exact
//! `Ordering` variant, or an exact index. No `is_empty()`/`len()>0`-only checks.
//! Host-independent: pure in-process API, no scanner engine, no accelerator.

use std::cmp::Ordering;
use std::collections::HashMap;
use std::sync::Arc;

use keyhog_core::{CredentialHash, MatchLocation, RawMatch, SensitiveString, Severity};

fn sha256(s: &str) -> CredentialHash {
    use sha2::{Digest, Sha256};
    let mut h = Sha256::new();
    h.update(s.as_bytes());
    CredentialHash::from_bytes(h.finalize().into())
}

fn loc(offset: usize, line: usize) -> MatchLocation {
    MatchLocation {
        source: Arc::from("filesystem"),
        file_path: Some(Arc::from("creds.env")),
        line: Some(line),
        offset,
        commit: None,
        author: None,
        date: None,
    }
}

/// Build a `RawMatch`. `tag` is stored in the (non-cmp-key) `detector_name`
/// field so a sorted vec can be identified position-by-position.
#[allow(clippy::too_many_arguments)]
fn rm(
    det_id: &str,
    tag: &str,
    sev: Severity,
    cred: &str,
    conf: Option<f64>,
    offset: usize,
    line: usize,
) -> RawMatch {
    RawMatch {
        detector_id: Arc::from(det_id),
        detector_name: Arc::from(tag),
        service: Arc::from("svc"),
        severity: sev,
        credential: SensitiveString::from(cred),
        credential_hash: sha256(cred),
        companions: HashMap::new(),
        location: loc(offset, line),
        entropy: None,
        confidence: conf,
    }
}

/// Collect the `detector_name` tags of a slice in current order.
fn tags(v: &[RawMatch]) -> Vec<&str> {
    v.iter().map(|m| &*m.detector_name).collect()
}

// ---------------------------------------------------------------------------
// Key 1: confidence dominates everything below it.
// ---------------------------------------------------------------------------

#[test]
fn higher_confidence_sorts_before_higher_severity() {
    // A: high confidence but only Low severity. B: low confidence but Critical.
    // Confidence is the primary key, so A (0.9) MUST precede B (0.5) even though
    // B outranks A on severity.
    let mut v = vec![
        rm(
            "d",
            "critical_lowconf",
            Severity::Critical,
            "cb",
            Some(0.5),
            0,
            1,
        ),
        rm("d", "low_highconf", Severity::Low, "ca", Some(0.9), 0, 1),
    ];
    v.sort();
    assert_eq!(tags(&v), vec!["low_highconf", "critical_lowconf"]);
}

// ---------------------------------------------------------------------------
// Key 2: severity breaks a confidence tie, DESCENDING.
// ---------------------------------------------------------------------------

#[test]
fn equal_confidence_orders_by_severity_descending() {
    // Same confidence (0.7); severity decides. Critical before Info.
    let mut v = vec![
        rm("d", "info", Severity::Info, "cb", Some(0.7), 0, 1),
        rm("d", "critical", Severity::Critical, "ca", Some(0.7), 0, 1),
        rm("d", "medium", Severity::Medium, "cc", Some(0.7), 0, 1),
    ];
    v.sort();
    assert_eq!(tags(&v), vec!["critical", "medium", "info"]);
}

#[test]
fn rawmatch_severity_direction_is_flipped_vs_native_severity_ord() {
    // Native Severity Ord ranks Critical ABOVE Info (Greater). RawMatch's cmp
    // deliberately inverts it so the higher-severity finding sorts FIRST (Less).
    let crit = rm("d", "c", Severity::Critical, "x", Some(0.5), 0, 1);
    let info = rm("d", "i", Severity::Info, "y", Some(0.5), 0, 1);
    assert_eq!(Severity::Critical.cmp(&Severity::Info), Ordering::Greater);
    assert_eq!(crit.cmp(&info), Ordering::Less);
    assert_eq!(info.cmp(&crit), Ordering::Greater);
}

// ---------------------------------------------------------------------------
// Key 3: detector_id ASCENDING breaks a conf+severity tie.
// ---------------------------------------------------------------------------

#[test]
fn equal_conf_and_severity_orders_by_detector_id_ascending() {
    let mut v = vec![
        rm("zzz-det", "z", Severity::High, "cb", Some(0.4), 0, 1),
        rm("aaa-det", "a", Severity::High, "ca", Some(0.4), 0, 1),
        rm("mmm-det", "m", Severity::High, "cc", Some(0.4), 0, 1),
    ];
    v.sort();
    assert_eq!(tags(&v), vec!["a", "m", "z"]);
}

// ---------------------------------------------------------------------------
// Key 4: credential ASCENDING breaks a conf+severity+detector tie.
// ---------------------------------------------------------------------------

#[test]
fn equal_conf_severity_detector_orders_by_credential_ascending() {
    // Same detector_id, same conf/severity; credential lexicographic order wins.
    let mut v = vec![
        rm(
            "det",
            "beta",
            Severity::Medium,
            "beta-secret",
            Some(0.5),
            0,
            1,
        ),
        rm(
            "det",
            "alpha",
            Severity::Medium,
            "alpha-secret",
            Some(0.5),
            0,
            1,
        ),
    ];
    v.sort();
    assert_eq!(tags(&v), vec!["alpha", "beta"]);
}

// ---------------------------------------------------------------------------
// Key 5: offset ASCENDING, then line ASCENDING.
// ---------------------------------------------------------------------------

#[test]
fn final_tiebreak_is_offset_then_line_ascending() {
    // All keys equal except location. offset dominates line.
    let mut v = vec![
        rm("det", "off100", Severity::High, "c", Some(0.5), 100, 1),
        rm("det", "off5", Severity::High, "c", Some(0.5), 5, 9),
        rm("det", "off5_line2", Severity::High, "c", Some(0.5), 5, 2),
    ];
    v.sort();
    // offset 5 group first; within it line 2 before line 9. offset 100 last.
    assert_eq!(tags(&v), vec!["off5_line2", "off5", "off100"]);
}

// ---------------------------------------------------------------------------
// LAW10: absent confidence is treated as 0.0 (lowest), never dropped.
// ---------------------------------------------------------------------------

#[test]
fn none_confidence_sorts_last_but_is_retained() {
    let mut v = vec![
        rm("d", "none", Severity::Critical, "cb", None, 0, 1),
        rm("d", "tiny", Severity::Info, "ca", Some(0.01), 0, 1),
    ];
    v.sort();
    // Even a 0.01 confidence outranks a None (0.0), regardless of severity.
    assert_eq!(tags(&v), vec!["tiny", "none"]);
    // Retained: both findings survive the sort (recall-safe).
    assert_eq!(v.len(), 2);
}

#[test]
fn none_confidence_equals_explicit_zero_for_the_confidence_key() {
    // Some(0.0) and None both map to 0.0, so the confidence key TIES and the
    // severity key decides: the Critical finding (with None) beats the Low
    // finding (with Some(0.0)).
    let some_zero_low = rm("d", "some0_low", Severity::Low, "ca", Some(0.0), 0, 1);
    let none_crit = rm("d", "none_crit", Severity::Critical, "cb", None, 0, 1);
    assert_eq!(none_crit.cmp(&some_zero_low), Ordering::Less);
    let mut v = vec![some_zero_low, none_crit];
    v.sort();
    assert_eq!(tags(&v), vec!["none_crit", "some0_low"]);
}

// ---------------------------------------------------------------------------
// Full mixed batch: exact ordered positions across all key tiers.
// ---------------------------------------------------------------------------

#[test]
fn full_mixed_batch_sorts_to_exact_order() {
    let f1 = rm("d1", "crit_hi", Severity::Critical, "c1", Some(0.95), 0, 1);
    let f2 = rm("d2", "low_hi", Severity::Low, "c2", Some(0.95), 0, 1);
    let f3 = rm("d3", "crit_mid", Severity::Critical, "c3", Some(0.60), 0, 1);
    let f4 = rm("d4", "info_mid", Severity::Info, "c4", Some(0.60), 0, 1);
    let f5 = rm("d5", "none_crit", Severity::Critical, "c5", None, 0, 1);
    let f6 = rm("d6", "high_lo", Severity::High, "c6", Some(0.10), 0, 1);

    let mut v = vec![f1, f2, f3, f4, f5, f6];
    v.sort();
    // Primary descending confidence groups: {0.95}, {0.60}, {0.10}, {0.0=None}.
    // Within a confidence group, severity descending decides.
    assert_eq!(
        tags(&v),
        vec![
            "crit_hi",
            "low_hi",
            "crit_mid",
            "info_mid",
            "high_lo",
            "none_crit"
        ]
    );
    // Pin two individual positions explicitly.
    assert_eq!(&*v[0].detector_name, "crit_hi");
    assert_eq!(&*v[5].detector_name, "none_crit");
}

// ---------------------------------------------------------------------------
// Determinism: total order => any input permutation yields identical output.
// ---------------------------------------------------------------------------

#[test]
fn two_input_permutations_sort_identically() {
    let build = || {
        vec![
            rm("d1", "crit_hi", Severity::Critical, "c1", Some(0.95), 0, 1),
            rm("d2", "low_hi", Severity::Low, "c2", Some(0.95), 0, 1),
            rm("d3", "crit_mid", Severity::Critical, "c3", Some(0.60), 0, 1),
            rm("d6", "high_lo", Severity::High, "c6", Some(0.10), 0, 1),
        ]
    };
    let mut forward = build();
    forward.sort();

    let mut reversed = build();
    reversed.reverse();
    reversed.sort();

    let expected = vec!["crit_hi", "low_hi", "crit_mid", "high_lo"];
    assert_eq!(tags(&forward), expected);
    assert_eq!(tags(&reversed), expected);
}

// ---------------------------------------------------------------------------
// Reflexivity, antisymmetry, and PartialOrd agreement.
// ---------------------------------------------------------------------------

#[test]
fn cmp_is_reflexive_and_partial_cmp_agrees() {
    let a = rm("d", "a", Severity::High, "cred", Some(0.5), 3, 7);
    assert_eq!(a.cmp(&a), Ordering::Equal);
    assert_eq!(a.partial_cmp(&a), Some(Ordering::Equal));
}

#[test]
fn cmp_is_antisymmetric_for_ordered_pair() {
    // Higher confidence => Less (sorts first); the reverse is Greater.
    let hi = rm("d", "hi", Severity::Low, "ca", Some(0.9), 0, 1);
    let lo = rm("d", "lo", Severity::Critical, "cb", Some(0.2), 0, 1);
    assert_eq!(hi.cmp(&lo), Ordering::Less);
    assert_eq!(lo.cmp(&hi), Ordering::Greater);
    assert_eq!(hi.partial_cmp(&lo), Some(Ordering::Less));
}

// ---------------------------------------------------------------------------
// min() selects the highest-priority finding (the cmp-smallest).
// ---------------------------------------------------------------------------

#[test]
fn iter_min_selects_highest_priority_finding() {
    let v = vec![
        rm("d5", "none_crit", Severity::Critical, "c5", None, 0, 1),
        rm("d1", "crit_hi", Severity::Critical, "c1", Some(0.95), 0, 1),
        rm("d6", "high_lo", Severity::High, "c6", Some(0.10), 0, 1),
    ];
    let best = v.iter().min().expect("non-empty");
    assert_eq!(&*best.detector_name, "crit_hi");
    let worst = v.iter().max().expect("non-empty");
    assert_eq!(&*worst.detector_name, "none_crit");
}

// ---------------------------------------------------------------------------
// Adversarial: identity-only fields must prevent distinct BTree keys from
// comparing Equal after every priority key ties.
// ---------------------------------------------------------------------------

#[test]
fn detector_name_breaks_a_complete_priority_tie() {
    // Identical on every priority key (conf, severity, detector_id, credential,
    // offset, line) but differing in the detector-name identity tiebreaker.
    let make = |tag: &str| rm("det", tag, Severity::High, "same-cred", Some(0.5), 4, 2);
    let x = make("X");
    let y = make("Y");
    assert_ne!(x.cmp(&y), Ordering::Equal);
    assert_ne!(x, y);

    let mut xy = vec![make("X"), make("Y")];
    xy.sort();
    assert_eq!(tags(&xy), vec!["X", "Y"]);

    let mut yx = vec![make("Y"), make("X")];
    yx.sort();
    assert_eq!(tags(&yx), vec!["X", "Y"]);

    let set = std::collections::BTreeSet::from([make("X"), make("Y")]);
    assert_eq!(
        set.len(),
        2,
        "distinct findings must remain distinct BTree keys"
    );
}

#[test]
fn every_fieldwise_identity_difference_breaks_cmp_equality() {
    let base = rm("det", "name", Severity::High, "same-cred", Some(0.0), 4, 2);
    let mut variants = Vec::new();

    let mut changed = base.clone();
    changed.service = Arc::from("other-service");
    variants.push(("service", changed));

    let mut changed = base.clone();
    changed.credential_hash = sha256("other-hash-input");
    variants.push(("credential_hash", changed));

    let mut changed = base.clone();
    changed
        .companions
        .insert("client_id".into(), "other".into());
    variants.push(("companions", changed));

    let mut changed = base.clone();
    changed.location.source = Arc::from("git");
    variants.push(("location.source", changed));

    let mut changed = base.clone();
    changed.location.file_path = Some(Arc::from("other.env"));
    variants.push(("location.file_path", changed));

    let mut changed = base.clone();
    changed.location.commit = Some(Arc::from("deadbeef"));
    variants.push(("location.commit", changed));

    let mut changed = base.clone();
    changed.location.author = Some(Arc::from("operator"));
    variants.push(("location.author", changed));

    let mut changed = base.clone();
    changed.location.date = Some(Arc::from("2026-07-10"));
    variants.push(("location.date", changed));

    let mut changed = base.clone();
    changed.entropy = Some(3.75);
    variants.push(("entropy", changed));

    let mut changed = base.clone();
    changed.confidence = None;
    variants.push(("confidence identity", changed));

    for (field, changed) in variants {
        assert_ne!(base, changed, "fixture must differ in {field}");
        assert_ne!(
            base.cmp(&changed),
            Ordering::Equal,
            "fieldwise difference in {field} must break cmp equality"
        );
    }
}

#[test]
fn companion_ordering_is_insertion_order_independent() {
    let mut forward = rm("det", "name", Severity::High, "same-cred", Some(0.5), 4, 2);
    forward.companions.insert("alpha".into(), "one".into());
    forward.companions.insert("beta".into(), "two".into());

    let mut reverse = rm("det", "name", Severity::High, "same-cred", Some(0.5), 4, 2);
    reverse.companions.insert("beta".into(), "two".into());
    reverse.companions.insert("alpha".into(), "one".into());

    assert_eq!(forward, reverse);
    assert_eq!(forward.cmp(&reverse), Ordering::Equal);

    reverse.companions.insert("beta".into(), "three".into());
    assert_eq!(
        forward.cmp(&reverse),
        reverse.cmp(&forward).reverse(),
        "different companion maps must retain an antisymmetric lexical order"
    );
    assert_ne!(forward.cmp(&reverse), Ordering::Equal);
}