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
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
use super::limits::apply_limits_section;
use super::schema::{ConfigFile, ScanSection};
use super::sections::config_relative_path;
use crate::args::{DetectorMode, ScanArgs};
use crate::value_parsers::{
    parse_byte_size, parse_dedup_scope, parse_entropy_bpe_max_bytes_per_token,
    parse_entropy_threshold, parse_min_confidence, parse_ml_threshold, parse_ml_weight,
    parse_output_format, parse_severity_filter, value_enum_expected,
};
use std::path::{Path, PathBuf};
const DETECTOR_MODE_ACCEPTED: &str = "expected one of replace, overlay";

fn parse_detector_mode(value: &str) -> Option<DetectorMode> {
    match value {
        "replace" => Some(DetectorMode::Replace),
        "overlay" => Some(DetectorMode::Overlay),
        _ => None,
    }
}

/// Reject a user-supplied keyword list that contains an empty entry.
///
/// An empty keyword is meaningless as a match needle (it would match at every
/// byte offset) and, critically, reaches `slice::windows(0)` in the entropy
/// keyword/placeholder scan (`entropy::keywords::is_keyword_assignment_line`,
/// `entropy::plausibility::is_placeholder_ci`, `entropy::scanner`), which panics
/// with "size is zero" and crashes the whole scan. Fail closed at the config
/// boundary with a message that names the fix, rather than letting a
/// `.keyhog.toml` typo (`placeholder_keywords = [""]`) abort mid-scan with an
/// opaque panic. Returns `true` when the list is safe to apply.
fn keyword_list_is_nonempty(errors: &mut Vec<String>, field: &str, entries: &[String]) -> bool {
    if entries.iter().any(|entry| entry.is_empty()) {
        errors.push(format!(
            "- {field}: entries must not be empty; remove the empty \"\" item"
        ));
        return false;
    }
    true
}

pub(super) fn parse_config_byte_size(
    errors: &mut Vec<String>,
    field: &str,
    value: &str,
) -> Option<usize> {
    match parse_byte_size(value) {
        Ok(size) => Some(size),
        Err(error) => {
            errors.push(super::invalid_config_value(field, value, &error));
            None
        }
    }
}

fn parse_config_decode_depth(errors: &mut Vec<String>, field: &str, depth: usize) -> Option<usize> {
    let limit = keyhog_core::max_decode_depth_limit();
    if (1..=limit).contains(&depth) {
        return Some(depth);
    }
    errors.push(format!(
        "- {field} = {depth}: decode depth must be between 1 and {limit}"
    ));
    None
}

/// Validate a `.keyhog.toml` numeric knob by routing its value through the SAME
/// canonical CLI value_parser the corresponding flag uses (ONE-PLACE: each bound
/// lives in exactly one validator). Renders the TOML f64 to its string form, runs
/// the parser, and on rejection pushes a `field = value: <reason>` config error
/// (returning None so the caller leaves the arg at its default). This is the ONE
/// body for `min_confidence` / `ml_weight` / `ml_threshold`: the numeric knobs
/// settable on BOTH the flag AND the `[scan]`/top-level TOML; each wrapper supplies
/// only its parser. Without this routing, a config value the CLI fails closed on
/// (e.g. `min_confidence = 5.0`) was applied un-validated and silently broke
/// scanning (zero recall / distorted confidence) (a Law-10 silent failure).
fn parse_config_f64(
    errors: &mut Vec<String>,
    field: &str,
    value: f64,
    parse: impl Fn(&str) -> Result<f64, String>,
) -> Option<f64> {
    let rendered = value.to_string();
    match parse(&rendered) {
        Ok(value) => Some(value),
        Err(error) => {
            errors.push(super::invalid_config_value(field, &rendered, &error));
            None
        }
    }
}

fn parse_config_ml_threshold(errors: &mut Vec<String>, field: &str, threshold: f64) -> Option<f64> {
    parse_config_f64(errors, field, threshold, parse_ml_threshold)
}

pub(super) fn parse_config_min_confidence(
    errors: &mut Vec<String>,
    field: &str,
    confidence: f64,
) -> Option<f64> {
    parse_config_f64(errors, field, confidence, parse_min_confidence)
}

fn parse_config_ml_weight(errors: &mut Vec<String>, field: &str, weight: f64) -> Option<f64> {
    parse_config_f64(errors, field, weight, parse_ml_weight)
}

fn parse_config_entropy_bpe_bound(
    errors: &mut Vec<String>,
    field: &str,
    bound: f64,
) -> Option<f64> {
    parse_config_f64(errors, field, bound, parse_entropy_bpe_max_bytes_per_token)
}

fn parse_config_entropy_threshold(
    errors: &mut Vec<String>,
    field: &str,
    threshold: f64,
) -> Option<f64> {
    parse_config_f64(errors, field, threshold, parse_entropy_threshold)
}

pub(super) fn validate_scan_preset_conflicts(
    args: &ScanArgs,
    config_errors: &mut Vec<String>,
    config: &ConfigFile,
) {
    // CLI presets are the highest-precedence layer. A lower-precedence config
    // key shadowed by a CLI preset is not a config-file contradiction; the CLI
    // did exactly what "CLI wins" promises. This validation rejects only same-
    // file TOML contradictions that would otherwise be accepted and then ignored
    // by the effective fast preset.
    if args.fast || args.deep || args.precision {
        return;
    }

    let toml_fast = config.fast == Some(true);
    let toml_deep = config.deep == Some(true);
    let toml_precision = config.precision == Some(true);
    if !(toml_fast || toml_deep || toml_precision) {
        return;
    }

    let presets = [
        ("fast", toml_fast),
        ("deep", toml_deep),
        ("precision", toml_precision),
    ];
    let selected: Vec<_> = presets
        .into_iter()
        .filter_map(|(name, enabled)| enabled.then_some(name))
        .collect();
    if selected.len() > 1 {
        config_errors.push(format!(
            "- {}: choose only one scan preset in .keyhog.toml",
            selected.join("/")
        ));
    }

    if !(toml_fast || toml_precision) {
        return;
    }
    let preset = if toml_fast {
        "fast = true"
    } else {
        "precision = true"
    };
    let mode = if toml_fast {
        "fast mode"
    } else {
        "precision mode"
    };

    for field in config_fast_noop_fields(config) {
        config_errors.push(format!(
            "- {field}: cannot be combined with {preset} because {mode} disables entropy/decode for that knob"
        ));
    }
}

fn config_fast_noop_fields(config: &ConfigFile) -> Vec<&'static str> {
    let mut fields = Vec::new();
    if config.no_decode == Some(true) {
        fields.push("no_decode");
    }
    if config.no_entropy == Some(true) {
        fields.push("no_entropy");
    }
    if config.entropy_source_files == Some(true) {
        fields.push("entropy_source_files");
    }
    if config.generic_keyword_low_entropy == Some(false) {
        fields.push("generic_keyword_low_entropy = false");
    }
    if config
        .scan
        .as_ref()
        .is_some_and(|scan| scan.entropy_threshold.is_some())
    {
        fields.push("[scan].entropy_threshold");
    }
    if config
        .scan
        .as_ref()
        .is_some_and(|scan| scan.min_secret_len.is_some())
    {
        fields.push("[scan].min_secret_len");
    }
    if config
        .scan
        .as_ref()
        .is_some_and(|scan| scan.entropy_bpe_max_bytes_per_token.is_some())
    {
        fields.push("[scan].entropy_bpe_max_bytes_per_token");
    }
    fields
}

/// Apply a `.keyhog.toml` positive-integer scan knob: reject `0` with a "use a
/// positive integer" config error, otherwise fill the CLI arg only when the
/// operator left it unset (CLI overrides TOML). ONE home for the reject-0 +
/// CLI-precedence guard that `threads` / `reader_threads` / `fused_batch` /
/// `fused_depth` / `per_chunk_timeout_ms` / `min_secret_len` all share on BOTH
/// the flat and `[scan]` config forms: `label` carries the `[scan].`-prefix
/// distinction, and the generic `T` covers the `usize` knobs plus the `u64`
/// `per_chunk_timeout_ms`. Before this the guard was pasted 12 times, which is
/// exactly how `threads` silently diverged from `reader_threads` (missing its
/// reject-0 check) until RECONCILE#14 (one owner makes that class impossible).
fn apply_positive_int_field<T: Copy + PartialEq + From<u8>>(
    config_errors: &mut Vec<String>,
    target: &mut Option<T>,
    label: &str,
    value: T,
) {
    if value == T::from(0u8) {
        config_errors.push(format!("- {label} = 0: use a positive integer"));
    } else if target.is_none() {
        *target = Some(value);
    }
}

pub(super) fn apply_scan_section(
    args: &mut ScanArgs,
    config_errors: &mut Vec<String>,
    scan: Option<ScanSection>,
) {
    // `[scan]` layer merge + validation, profiled as preprocessing.
    let _scan_section_span = keyhog_profile::span(keyhog_profile::Stage::Preprocess);
    // `[scan]` nested table - the surface the README documents as canonical.
    // Fills only fields still at their CLI defaults; command-line flags win.
    if let Some(scan) = scan {
        if let Some(ref s) = scan.severity {
            match parse_severity_filter(s) {
                Some(severity) => {
                    if args.severity.is_none() {
                        args.severity = Some(severity);
                    }
                }
                None => config_errors.push(super::invalid_config_value(
                    "[scan].severity",
                    s,
                    &value_enum_expected::<crate::args::SeverityFilter>(),
                )),
            }
        }
        if let Some(confidence) = scan.min_confidence {
            let parsed_confidence =
                parse_config_min_confidence(config_errors, "[scan].min_confidence", confidence);
            if args.min_confidence.is_none() {
                args.min_confidence = parsed_confidence;
            }
        }
        if let Some(threshold) = scan.ml_threshold {
            let parsed_threshold =
                parse_config_ml_threshold(config_errors, "[scan].ml_threshold", threshold);
            if args.ml_threshold.is_none() {
                args.ml_threshold = parsed_threshold;
            }
        }
        if let Some(threshold) = scan.entropy_threshold {
            let parsed_threshold = parse_config_entropy_threshold(
                config_errors,
                "[scan].entropy_threshold",
                threshold,
            );
            if args.entropy_threshold.is_none() {
                args.entropy_threshold = parsed_threshold;
            }
        }
        if let Some(bound) = scan.entropy_bpe_max_bytes_per_token {
            let parsed_bound = parse_config_entropy_bpe_bound(
                config_errors,
                "[scan].entropy_bpe_max_bytes_per_token",
                bound,
            );
            if args.entropy_bpe_max_bytes_per_token.is_none() {
                args.entropy_bpe_max_bytes_per_token = parsed_bound;
            }
        }
        if let Some(depth) = scan.decode_depth {
            let parsed_depth =
                parse_config_decode_depth(config_errors, "[scan].decode_depth", depth);
            if args.decode_depth.is_none() {
                args.decode_depth = parsed_depth;
            }
        }
        if let Some(min_secret_len) = scan.min_secret_len {
            apply_positive_int_field(
                config_errors,
                &mut args.min_secret_len,
                "[scan].min_secret_len",
                min_secret_len,
            );
        }
        if let Some(ref f) = scan.format {
            match parse_output_format(f) {
                Some(fmt) => {
                    if !args.format_cli_explicit
                        && matches!(args.format, crate::args::OutputFormat::Text)
                    {
                        args.format = fmt;
                    }
                }
                None => config_errors.push(super::invalid_config_value(
                    "[scan].format",
                    f,
                    &value_enum_expected::<crate::args::OutputFormat>(),
                )),
            }
        }
        if args.exclude_paths.is_none() {
            args.exclude_paths = scan.exclude;
        }
        if let Some(threads) = scan.threads {
            apply_positive_int_field(config_errors, &mut args.threads, "[scan].threads", threads);
        }
        if let Some(threads) = scan.reader_threads {
            apply_positive_int_field(
                config_errors,
                &mut args.reader_threads,
                "[scan].reader_threads",
                threads,
            );
        }
        if let Some(batch) = scan.fused_batch {
            apply_positive_int_field(
                config_errors,
                &mut args.fused_batch,
                "[scan].fused_batch",
                batch,
            );
        }
        if let Some(depth) = scan.fused_depth {
            apply_positive_int_field(
                config_errors,
                &mut args.fused_depth,
                "[scan].fused_depth",
                depth,
            );
        }
        if let Some(timeout_ms) = scan.per_chunk_timeout_ms {
            apply_positive_int_field(
                config_errors,
                &mut args.per_chunk_timeout_ms,
                "[scan].per_chunk_timeout_ms",
                timeout_ms,
            );
        }
        if let Some(ref d) = scan.dedup {
            match parse_dedup_scope(d) {
                Some(scope) => {
                    if !args.dedup_cli_explicit
                        && matches!(args.dedup, crate::args::CliDedupScope::Credential)
                    {
                        args.dedup = scope;
                    }
                }
                None => config_errors.push(super::invalid_config_value(
                    "[scan].dedup",
                    d,
                    &value_enum_expected::<crate::args::CliDedupScope>(),
                )),
            }
        }
        if let Some(incremental) = scan.incremental {
            if !args.incremental {
                args.incremental = incremental;
            }
        }
        if args.incremental_cache.is_none() {
            args.incremental_cache = scan.incremental_cache;
        }
        if let Some(ref limit) = scan.gpu_batch_input_limit {
            let parsed =
                parse_config_byte_size(config_errors, "[scan].gpu_batch_input_limit", limit);
            if args.gpu_batch_input_limit.is_none() {
                args.gpu_batch_input_limit = parsed;
            }
        }
    }
}

pub(super) fn apply_top_level_scan_fields(
    args: &mut ScanArgs,
    config_errors: &mut Vec<String>,
    config_path: &Path,
    config: &mut ConfigFile,
) {
    // Apply config values only when no explicit CLI flag was given.
    let cli_preset_selected = args.fast || args.deep || args.precision;
    if let Some(detectors_str) = &config.detectors {
        if !args.detectors_cli_explicit && args.detectors == PathBuf::from("detectors") {
            args.detectors = config_relative_path(config_path, detectors_str);
            // This bit records an explicitly selected corpus, regardless of
            // whether its spelling happens to equal the default sentinel.
            // The daemon owns its startup corpus and cannot honor a per-scan
            // config corpus without proving that identity in the protocol.
            args.detectors_cli_explicit = true;
        }
    }
    if let Some(mode) = &config.detectors_mode {
        match parse_detector_mode(mode) {
            Some(mode) if args.detectors_mode.is_none() => args.detectors_mode = Some(mode),
            Some(_) => {}
            None => config_errors.push(super::invalid_config_value(
                "detectors_mode",
                mode,
                DETECTOR_MODE_ACCEPTED,
            )),
        }
    }

    if let Some(no_decode) = config.no_decode {
        if !args.no_decode && !cli_preset_selected {
            args.no_decode = no_decode;
        }
    }

    if let Some(no_entropy) = config.no_entropy {
        if !args.no_entropy && !cli_preset_selected {
            args.no_entropy = no_entropy;
        }
    }

    if let Some(fast) = config.fast {
        if !args.fast && !args.deep && !args.precision {
            args.fast = fast;
        }
    }

    if let Some(deep) = config.deep {
        if !args.fast && !args.deep && !args.precision {
            args.deep = deep;
        }
    }

    if let Some(precision) = config.precision {
        if !args.fast && !args.deep && !args.precision {
            args.precision = precision;
        }
    }

    #[cfg(feature = "verify")]
    if let Some(verify) = config.verify {
        if !args.verify && !args.no_verify {
            args.verify = verify;
        }
    }
    #[cfg(not(feature = "verify"))]
    if config.verify.is_some() && !args.no_verify {
        config_errors.push(
            "- verify: this key requires the `verify` feature in this keyhog build".to_string(),
        );
    }

    #[cfg(feature = "verify")]
    if let Some(timeout) = config.timeout {
        if args.timeout.is_none() {
            args.timeout = Some(timeout);
        }
    }
    #[cfg(not(feature = "verify"))]
    if config.timeout.is_some() {
        config_errors.push(
            "- timeout: this key requires the `verify` feature in this keyhog build".to_string(),
        );
    }

    #[cfg(feature = "verify")]
    if let Some(concurrency) = config.verify_concurrency {
        if concurrency == 0 {
            config_errors.push("- verify_concurrency = 0: expected an integer >= 1 (maximum in-flight verification requests per service)".to_string());
        } else if args.verify_concurrency.is_none() {
            args.verify_concurrency = Some(concurrency);
        }
    }
    #[cfg(not(feature = "verify"))]
    if config.verify_concurrency.is_some() {
        config_errors.push(
            "- verify_concurrency: this key requires the `verify` feature in this keyhog build"
                .to_string(),
        );
    }

    #[cfg(feature = "git")]
    if let Some(max_commits) = config.max_commits {
        if args.max_commits.is_none() {
            args.max_commits = Some(max_commits);
        }
    }
    #[cfg(not(feature = "git"))]
    if config.max_commits.is_some() {
        config_errors.push(
            "- max_commits: this key requires the `git` feature in this keyhog build".to_string(),
        );
    }

    if let Some(show_secrets) = config.show_secrets {
        if !args.show_secrets {
            args.show_secrets = show_secrets;
        }
    }

    if let Some(ref limit_str) = config.decode_size_limit {
        let parsed_size = parse_config_byte_size(config_errors, "decode_size_limit", limit_str);
        if args.decode_size_limit.is_none() {
            if let Some(size) = parsed_size {
                args.decode_size_limit = Some(size);
            }
        }
    }

    if let Some(entropy_source) = config.entropy_source_files {
        if !args.entropy_source_files {
            args.entropy_source_files = entropy_source;
        }
    }

    if config.generic_keyword_low_entropy == Some(false) && !args.no_keyword_low_entropy {
        args.no_keyword_low_entropy = true;
    }

    if let Some(no_unicode_norm) = config.no_unicode_norm {
        if !args.no_unicode_norm {
            args.no_unicode_norm = no_unicode_norm;
        }
    }

    if let Some(no_ml) = config.no_ml {
        if !args.no_ml {
            args.no_ml = no_ml;
        }
    }

    if let Some(ml_weight) = config.ml_weight {
        let parsed = parse_config_ml_weight(config_errors, "ml_weight", ml_weight);
        if args.ml_weight.is_none() {
            args.ml_weight = parsed;
        }
    }

    if let Some(ref limit_str) = config.max_file_size {
        let parsed_size = parse_config_byte_size(config_errors, "max_file_size", limit_str);
        if args.max_file_size.is_none() {
            if let Some(size) = parsed_size {
                args.max_file_size = Some(size);
            }
        }
    }

    if let Some(ref limit_str) = config.regex_dfa_limit {
        let parsed_size = parse_config_byte_size(config_errors, "regex_dfa_limit", limit_str);
        if args.regex_dfa_limit.is_none() {
            if let Some(size) = parsed_size {
                args.regex_dfa_limit = Some(size);
            }
        }
    }

    if let Some(limits) = config.limits.take() {
        apply_limits_section(args, config_errors, limits);
    }

    if let Some(prefixes) = config.known_prefixes.take() {
        if keyword_list_is_nonempty(config_errors, "known_prefixes", &prefixes) {
            args.known_prefixes = prefixes;
        }
    }
    if let Some(keywords) = config.secret_keywords.take() {
        if keyword_list_is_nonempty(config_errors, "secret_keywords", &keywords) {
            args.secret_keywords = keywords;
        }
    }
    if let Some(keywords) = config.test_keywords.take() {
        if keyword_list_is_nonempty(config_errors, "test_keywords", &keywords) {
            args.test_keywords = keywords;
        }
    }
    if let Some(keywords) = config.placeholder_keywords.take() {
        if keyword_list_is_nonempty(config_errors, "placeholder_keywords", &keywords) {
            args.placeholder_keywords = keywords;
        }
    }
}