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
//! Allowlist support: `.keyhogignore` file parsing for suppressing known false
//! positives by path glob, detector ID, or credential hash.
/// Allowlist: known false positives and ignored patterns.
///
/// Users can create a `.keyhogignore` file to suppress known FPs.
/// Format (one per line):
/// - `hash:<sha256>` - ignore a specific credential by hash
/// - `detector:<id>` - ignore all findings from a detector
/// - `path:<glob>` - ignore files matching a glob pattern
/// - `# comment` - comments
/// - blank lines are skipped
use std::collections::HashSet;
use std::ops::{Deref, DerefMut};
use std::path::Path;
use std::sync::atomic::{AtomicU64, Ordering};
use crate::merkle_spec_hash::hex_to_array;
use crate::{CredentialHash, VerifiedFinding};
// Submodules live in `allowlist/` (native resolution), matching the
// `foo.rs` + `foo/` layout used across the workspace.
mod metadata;
use metadata::*;
// Path-glob matching (normalization, segment automaton, first-segment bucketed
// index) is its own subsystem; the `Allowlist` holds a precompiled index and
// delegates every path decision to it.
mod glob;
use glob::{normalize_path, PathGlobIndex};
static NEXT_OBSERVED_PATHS_ID: AtomicU64 = AtomicU64::new(1);
/// A Vec-compatible path list that records direct mutable access.
///
/// `Allowlist::ignored_paths` remains a public collection for compatibility,
/// but a plain public `Vec` cannot tell its compiled matcher that an indexed
/// element was replaced. `DerefMut` increments a generation before exposing
/// the underlying Vec, so pushes, clears, assignments, and other mutable
/// operations invalidate the matcher in O(1) on the next lookup.
#[derive(Debug)]
pub struct ObservedPaths {
values: Vec<String>,
instance_id: u64,
mutation_epoch: AtomicU64,
}
impl ObservedPaths {
fn new(values: Vec<String>) -> Self {
Self {
values,
instance_id: NEXT_OBSERVED_PATHS_ID.fetch_add(1, Ordering::Relaxed),
mutation_epoch: AtomicU64::new(0),
}
}
pub(crate) fn instance_id(&self) -> u64 {
self.instance_id
}
pub(crate) fn mutation_epoch(&self) -> u64 {
self.mutation_epoch.load(Ordering::Relaxed)
}
}
impl Default for ObservedPaths {
fn default() -> Self {
Self::new(Vec::new())
}
}
impl Clone for ObservedPaths {
fn clone(&self) -> Self {
Self::new(self.values.clone())
}
}
impl Deref for ObservedPaths {
type Target = Vec<String>;
fn deref(&self) -> &Self::Target {
&self.values
}
}
impl DerefMut for ObservedPaths {
fn deref_mut(&mut self) -> &mut Self::Target {
self.mutation_epoch.fetch_add(1, Ordering::Relaxed);
&mut self.values
}
}
impl AsRef<[String]> for ObservedPaths {
fn as_ref(&self) -> &[String] {
&self.values
}
}
impl serde::Serialize for ObservedPaths {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
self.values.serialize(serializer)
}
}
impl From<Vec<String>> for ObservedPaths {
fn from(values: Vec<String>) -> Self {
Self::new(values)
}
}
impl FromIterator<String> for ObservedPaths {
fn from_iter<T: IntoIterator<Item = String>>(iter: T) -> Self {
Self::new(iter.into_iter().collect())
}
}
impl IntoIterator for ObservedPaths {
type Item = String;
type IntoIter = std::vec::IntoIter<String>;
fn into_iter(self) -> Self::IntoIter {
self.values.into_iter()
}
}
impl<'a> IntoIterator for &'a ObservedPaths {
type Item = &'a String;
type IntoIter = std::slice::Iter<'a, String>;
fn into_iter(self) -> Self::IntoIter {
self.values.iter()
}
}
impl PartialEq for ObservedPaths {
fn eq(&self, other: &Self) -> bool {
self.values == other.values
}
}
impl<T: AsRef<str>> PartialEq<Vec<T>> for ObservedPaths {
fn eq(&self, other: &Vec<T>) -> bool {
self.values.len() == other.len()
&& self
.values
.iter()
.zip(other)
.all(|(left, right)| left == right.as_ref())
}
}
/// User-defined suppressions loaded from `.keyhogignore`: credential hashes, detector IDs, and path globs.
///
/// # Examples
///
/// ```rust
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use keyhog_core::Allowlist;
///
/// let path = std::env::temp_dir().join(format!(
/// "keyhog_allowlist_struct_{}.keyhogignore",
/// std::process::id()
/// ));
/// std::fs::write(&path, "detector:demo-token\npath:**/*.md\n")?;
/// let allowlist = Allowlist::load_with_metadata_policy(&path, false, false, None)?;
/// std::fs::remove_file(&path)?;
/// assert!(allowlist.ignored_detectors.contains("demo-token"));
/// # Ok(()) }
/// ```
#[derive(Debug, serde::Serialize)]
pub struct Allowlist {
/// SHA-256 hashes of credentials to ignore.
pub credential_hashes: HashSet<CredentialHash>,
/// Detector IDs to ignore entirely.
pub ignored_detectors: HashSet<String>,
/// Glob patterns for paths to ignore (raw, as authored). Kept as the public
/// Vec-compatible contract + serialized form; the matcher consumes the
/// precompiled [`PathGlobIndex`] built from these in [`Allowlist::parse`].
pub ignored_paths: ObservedPaths,
/// Precompiled, first-segment-bucketed form of `ignored_paths`. Built once
/// in `parse`/`empty` so per-finding path checks neither re-normalize +
/// re-split each pattern nor sweep every rule. Skipped by `serde` (it is a
/// pure function of `ignored_paths`; rebuilt by the constructors and clone
/// implementation) so the serialized shape is unchanged.
#[serde(skip)]
path_index: PathGlobIndex,
/// Expired policy lines found while parsing. They are never active
/// suppressions; `load` turns them into a user-visible policy error.
#[serde(skip)]
expired_entries: Vec<ExpiredAllowlistEntry>,
/// Governance-policy violations found while parsing. They are never active
/// suppressions; `load_with_policy` turns them into a user-visible policy
/// error.
#[serde(skip)]
policy_violations: Vec<AllowlistPolicyViolation>,
}
#[derive(Debug, Clone)]
struct ExpiredAllowlistEntry {
line_number: usize,
entry: String,
expires: String,
}
#[derive(Debug, Clone, Copy, Default, serde::Serialize)]
struct AllowlistMetadataPolicy {
require_reason: bool,
require_approved_by: bool,
max_expires_days: Option<u64>,
}
impl AllowlistMetadataPolicy {
fn is_enforced(self) -> bool {
self.require_reason || self.require_approved_by || self.max_expires_days.is_some()
}
}
#[derive(Debug, Clone)]
struct AllowlistPolicyViolation {
line_number: usize,
entry: String,
field: &'static str,
detail: String,
}
impl Allowlist {
/// Create an empty allowlist with no suppressed hashes, detectors, or paths.
///
/// # Examples
///
/// ```rust
/// use keyhog_core::Allowlist;
///
/// let allowlist = Allowlist::default();
/// assert!(allowlist.ignored_paths.is_empty());
/// ```
pub(crate) fn empty() -> Self {
let ignored_paths = ObservedPaths::default();
Self {
credential_hashes: HashSet::new(),
ignored_detectors: HashSet::new(),
path_index: PathGlobIndex::build(&ignored_paths),
ignored_paths,
expired_entries: Vec::new(),
policy_violations: Vec::new(),
}
}
/// Load from a `.keyhogignore` file and enforce metadata governance.
pub fn load_with_metadata_policy(
path: &Path,
require_reason: bool,
require_approved_by: bool,
max_expires_days: Option<u64>,
) -> Result<Self, std::io::Error> {
Self::load_with_policy(
path,
AllowlistMetadataPolicy {
require_reason,
require_approved_by,
max_expires_days,
},
)
}
fn load_with_policy(
path: &Path,
policy: AllowlistMetadataPolicy,
) -> Result<Self, std::io::Error> {
let bytes = crate::state_file::read_capped(
path,
crate::state_file::RULE_CONFIG_FILE_BYTES,
"allowlist",
)?;
let contents = String::from_utf8(bytes)
.map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
let allowlist = Self::parse_with_policy(&contents, policy);
if !allowlist.expired_entries.is_empty() {
return Err(allowlist.expired_entries_error(path));
}
if !allowlist.policy_violations.is_empty() {
return Err(allowlist.policy_violations_error(path));
}
Ok(allowlist)
}
/// Parse allowlist from string content.
///
/// # Examples
///
/// ```rust
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use keyhog_core::Allowlist;
///
/// let path = std::env::temp_dir().join(format!(
/// "keyhog_allowlist_parse_{}.keyhogignore",
/// std::process::id()
/// ));
/// std::fs::write(&path, "path:**/.env\ndetector:demo-token\n")?;
/// let allowlist = Allowlist::load_with_metadata_policy(&path, false, false, None)?;
/// std::fs::remove_file(&path)?;
/// assert!(allowlist.is_path_ignored("app/.env"));
/// # Ok(()) }
/// ```
pub(crate) fn parse(content: &str) -> Self {
Self::parse_with_policy(content, AllowlistMetadataPolicy::default())
}
fn parse_with_policy(content: &str, policy: AllowlistMetadataPolicy) -> Self {
let mut al = Self::empty();
let today_days = match try_today_days_since_epoch() {
Ok(days) => days,
Err(detail) => {
al.push_policy_violation(1, "<allowlist>", "system_clock", detail);
return al;
}
};
let today = yyyy_mm_dd_from_days(today_days);
for (line_number, raw_line) in content.lines().enumerate() {
let raw_line = raw_line.trim();
if raw_line.is_empty() || raw_line.starts_with('#') {
continue;
}
// Optional inline metadata: `entry; reason="..."; expires=YYYY-MM-DD; approved_by="..."`
// Each `;`-separated token after the first is a key=value pair.
let mut parts = raw_line.splitn(2, ';');
let entry = parts.next().unwrap_or("").trim(); // LAW10: missing/non-string field => empty/placeholder; recall-safe
let metadata = parts.next().unwrap_or(""); // LAW10: missing/non-string field => empty/placeholder; recall-safe
let parsed_meta = parse_inline_metadata(metadata);
for key in &parsed_meta.unknown_keys {
al.push_policy_violation(
line_number + 1,
entry,
"metadata",
format!("unknown key `{key}`; supported keys are reason, expires, approved_by"),
);
}
for detail in &parsed_meta.malformed_tokens {
al.push_policy_violation(line_number + 1, entry, "metadata", detail.clone());
}
if entry.is_empty() {
al.push_policy_violation(
line_number + 1,
entry,
"entry",
"empty allowlist entry before metadata; add `detector:`, `path:`, `hash:`, or a glob before `;`".to_string(),
);
continue;
}
// Drop entries whose `expires` is past - keeps `.keyhogignore`
// self-cleaning for short-lived approvals (Tier-B #18 governance).
if let Some(exp) = parsed_meta.expires.as_deref() {
match parse_yyyy_mm_dd_days(exp) {
Some(exp_days) if exp_days < today_days => {
al.expired_entries.push(ExpiredAllowlistEntry {
line_number: line_number + 1,
entry: entry.to_string(),
expires: exp.to_string(),
});
tracing::warn!(
"allowlist entry expired on {} (today is {}): '{}'",
exp,
today,
entry
);
continue;
}
Some(_) => {}
None => {
al.push_policy_violation(
line_number + 1,
entry,
"expires",
"must use YYYY-MM-DD".to_string(),
);
continue;
}
}
}
if let Some(hash) = entry.strip_prefix("hash:") {
let trimmed = hash.trim();
if let Some(valid_hash) = parse_sha256_hex(trimmed) {
if !al.metadata_policy_allows(
line_number + 1,
entry,
&parsed_meta,
policy,
today_days,
) {
continue;
}
al.credential_hashes.insert(valid_hash);
log_metadata_audit("hash", trimmed, &parsed_meta);
} else {
al.push_invalid_entry_violation(
line_number + 1,
entry,
"hash",
"must be a 64-character SHA-256 hex digest",
);
tracing::warn!(
"invalid hash allowlist entry at line {}: '{}'",
line_number + 1,
trimmed
);
}
} else if let Some(detector) = entry.strip_prefix("detector:") {
let detector = detector.trim();
if detector.is_empty() {
al.push_invalid_entry_violation(
line_number + 1,
entry,
"detector",
"detector id must not be empty",
);
tracing::warn!(
"invalid detector allowlist entry at line {}: detector id is empty",
line_number + 1
);
} else {
if !al.metadata_policy_allows(
line_number + 1,
entry,
&parsed_meta,
policy,
today_days,
) {
continue;
}
al.ignored_detectors.insert(detector.to_string());
log_metadata_audit("detector", detector, &parsed_meta);
}
} else if let Some(path) = entry.strip_prefix("path:") {
let path = path.trim();
if path.is_empty() {
al.push_invalid_entry_violation(
line_number + 1,
entry,
"path",
"path glob must not be empty",
);
tracing::warn!(
"invalid path allowlist entry at line {}: glob is empty",
line_number + 1
);
} else {
if !al.metadata_policy_allows(
line_number + 1,
entry,
&parsed_meta,
policy,
today_days,
) {
continue;
}
al.ignored_paths.push(path.to_string());
log_metadata_audit("path", path, &parsed_meta);
}
} else if let Some(bytes) = parse_sha256_hex(entry) {
// Bare 64-char hex hash. Lets the obvious
// `keyhog scan ... --format jsonl | jq -r '.credential_hash'
// >> .keyhogignore` workflow Just Work without users
// learning the `hash:` prefix.
if !al.metadata_policy_allows(
line_number + 1,
entry,
&parsed_meta,
policy,
today_days,
) {
continue;
}
al.credential_hashes.insert(bytes);
log_metadata_audit("hash", entry, &parsed_meta);
} else if let Some((field, detail)) = invalid_bare_entry(entry) {
al.push_invalid_entry_violation(line_number + 1, entry, field, detail);
tracing::warn!(
"invalid allowlist entry at line {}: '{}'",
line_number + 1,
entry
);
} else {
// Bare path glob (gitignore-style). Anything that didn't
// match an explicit `hash:` / `detector:` / `path:` prefix
// and isn't a bare hash is interpreted as a path glob,
// matching `.gitignore` UX (`*.log`, `node_modules/`,
// `vendor/**/*.json`). kimi-1 dogfood #129 - the prior
// behavior emitted a warning and silently dropped the
// line, which is the worst of both worlds: every
// `.gitignore` users copied over was dead.
if !al.metadata_policy_allows(
line_number + 1,
entry,
&parsed_meta,
policy,
today_days,
) {
continue;
}
al.ignored_paths.push(entry.to_string());
log_metadata_audit("path", entry, &parsed_meta);
}
}
// Precompile the path globs ONCE: segments + oversize verdict + the
// first-segment bucket index, so per-finding suppression neither
// re-normalizes each pattern nor sweeps every rule.
al.path_index = PathGlobIndex::build(&al.ignored_paths);
al
}
fn metadata_policy_allows(
&mut self,
line_number: usize,
entry: &str,
metadata: &InlineMetadata,
policy: AllowlistMetadataPolicy,
today_days: i64,
) -> bool {
if !policy.is_enforced() {
return true;
}
let mut allowed = true;
if policy.require_reason && metadata.reason.as_deref().is_none_or(str::is_empty) {
self.push_policy_violation(
line_number,
entry,
"reason",
"required by [allowlist].require_reason".to_string(),
);
allowed = false;
}
if policy.require_approved_by && metadata.approved_by.as_deref().is_none_or(str::is_empty) {
self.push_policy_violation(
line_number,
entry,
"approved_by",
"required by [allowlist].require_approved_by".to_string(),
);
allowed = false;
}
if let Some(max_expires_days) = policy.max_expires_days {
match metadata.expires.as_deref() {
Some(expires) if !expires.is_empty() => match parse_yyyy_mm_dd_days(expires) {
Some(expires_days) => {
let max_days = match i64::try_from(max_expires_days) {
Ok(days) => days,
Err(error) => {
self.push_policy_violation(
line_number,
entry,
"expires",
format!(
"max_expires_days={max_expires_days} is too large to enforce ({error})"
),
);
allowed = false;
return allowed;
}
};
if expires_days.saturating_sub(today_days) > max_days {
self.push_policy_violation(
line_number,
entry,
"expires",
format!(
"expires={expires} is more than {max_expires_days} days out"
),
);
allowed = false;
}
}
None => {
self.push_policy_violation(
line_number,
entry,
"expires",
"must use YYYY-MM-DD when [allowlist].max_expires_days is set"
.to_string(),
);
allowed = false;
}
},
_ => {
self.push_policy_violation(
line_number,
entry,
"expires",
"required by [allowlist].max_expires_days".to_string(),
);
allowed = false;
}
}
}
allowed
}
fn push_invalid_entry_violation(
&mut self,
line_number: usize,
entry: &str,
field: &'static str,
detail: &'static str,
) {
self.push_policy_violation(line_number, entry, field, detail.to_string());
}
fn push_policy_violation(
&mut self,
line_number: usize,
entry: &str,
field: &'static str,
detail: String,
) {
self.policy_violations.push(AllowlistPolicyViolation {
line_number,
entry: entry.to_string(),
field,
detail,
});
}
fn expired_entries_error(&self, path: &Path) -> std::io::Error {
let first = &self.expired_entries[0];
let extra = self.expired_entries.len().saturating_sub(1);
let suffix = if extra == 0 {
String::new()
} else if extra == 1 {
" (+1 more expired entry)".to_string()
} else {
format!(" (+{extra} more expired entries)")
};
std::io::Error::new(
std::io::ErrorKind::InvalidData,
format!(
"{} contains expired allowlist policy at line {}: '{}' expired on {}{}. \
Remove the entry or renew its expires metadata; refusing to scan with stale suppressions.",
path.display(),
first.line_number,
first.entry,
first.expires,
suffix
),
)
}
fn policy_violations_error(&self, path: &Path) -> std::io::Error {
let first = &self.policy_violations[0];
let extra = self.policy_violations.len().saturating_sub(1);
let suffix = if extra == 0 {
String::new()
} else if extra == 1 {
" (+1 more policy violation)".to_string()
} else {
format!(" (+{extra} more policy violations)")
};
std::io::Error::new(
std::io::ErrorKind::InvalidData,
format!(
"{} violates allowlist governance at line {}: '{}' missing/invalid {} ({}){}. \
Add inline metadata like `; reason=\"...\"; approved_by=\"...\"; expires=YYYY-MM-DD` \
or relax the [allowlist] policy in .keyhog.toml; refusing to scan with unapproved suppressions.",
path.display(),
first.line_number,
first.entry,
first.field,
first.detail,
suffix
),
)
}
/// Check whether detector or path rules suppress a verified finding.
///
/// Hash-based suppression is evaluated earlier on [`crate::RawMatch`] values
/// because [`VerifiedFinding`] stores only redacted credentials.
///
/// # Examples
///
/// ```rust
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use keyhog_core::Allowlist;
///
/// let path = std::env::temp_dir().join(format!(
/// "keyhog_allowlist_allowed_{}.keyhogignore",
/// std::process::id()
/// ));
/// std::fs::write(&path, "detector:demo-token\npath:src/*.rs\n")?;
/// let allowlist = Allowlist::load_with_metadata_policy(&path, false, false, None)?;
/// std::fs::remove_file(&path)?;
/// assert!(allowlist.ignored_detectors.contains("demo-token"));
/// assert!(allowlist.is_path_ignored("src/main.rs"));
/// # Ok(()) }
/// ```
pub(crate) fn is_allowed(&self, finding: &VerifiedFinding) -> bool {
let detector_ignored = self.ignored_detectors.contains(&*finding.detector_id);
let path_ignored = finding.location.file_path.as_ref().is_some_and(|path| {
let normalized_path = normalize_path(path);
self.path_matches(&normalized_path)
});
let hash_ignored = self.matches_ignored_hash(&finding.credential_hash);
detector_ignored || path_ignored || hash_ignored
}
/// Check if a raw credential hash is allowlisted.
///
/// # Examples
///
/// ```rust
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use keyhog_core::{Allowlist, CredentialHash};
///
/// let path = std::env::temp_dir().join(format!(
/// "keyhog_allowlist_hash_{}.keyhogignore",
/// std::process::id()
/// ));
/// std::fs::write(&path, "hash:0000000000000000000000000000000000000000000000000000000000000000\n")?;
/// let allowlist = Allowlist::load_with_metadata_policy(&path, false, false, None)?;
/// std::fs::remove_file(&path)?;
/// assert!(allowlist.credential_hashes.contains(&CredentialHash::from([0u8; 32])));
/// # Ok(()) }
/// ```
pub(crate) fn is_hash_allowed(&self, credential: &str) -> bool {
self.matches_ignored_hash_hex(credential)
}
/// Check if a hex-encoded SHA-256 hash is allowlisted.
pub(crate) fn is_raw_hash_ignored(&self, hash_hex: &str) -> bool {
self.matches_ignored_hash_hex(hash_hex)
}
/// Check whether a raw path matches an ignored-path glob.
///
/// # Examples
///
/// ```rust
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use keyhog_core::Allowlist;
///
/// let path = std::env::temp_dir().join(format!(
/// "keyhog_allowlist_path_{}.keyhogignore",
/// std::process::id()
/// ));
/// std::fs::write(&path, "path:**/*.md\n")?;
/// let allowlist = Allowlist::load_with_metadata_policy(&path, false, false, None)?;
/// std::fs::remove_file(&path)?;
/// assert!(allowlist.is_path_ignored("docs/README.md"));
/// # Ok(()) }
/// ```
pub fn is_path_ignored(&self, path: &str) -> bool {
let normalized = normalize_path(path);
self.path_matches(&normalized)
}
/// Run the precompiled path-glob index against an already-normalized path,
/// rebuilding the index first iff the public `ignored_paths` field was
/// mutated directly since construction. The construction paths keep the
/// index in sync, so the scanner hot path always takes the fast branch. A
/// hand-mutated allowlist rebuilds on every call (the index cannot be cached
/// behind `&self`), paying for correctness rather than silently skipping it;
/// callers that mutate `ignored_paths` in a loop should re-`parse` instead.
fn path_matches(&self, normalized_path: &str) -> bool {
if self.path_index.matches_sources(&self.ignored_paths) {
self.path_index.matches(normalized_path)
} else {
PathGlobIndex::build(&self.ignored_paths).matches(normalized_path)
}
}
fn matches_ignored_hash(&self, hash: &CredentialHash) -> bool {
// Direct byte-set membership. Suppressing `hash:` entries are parsed
// from 64-hex into this same `[u8; 32]` form at load time
// (`parse_sha256_hex`), and findings carry the raw bytes, so no hex
// round-trip happens here. (Earlier versions also hashed raw input as a
// fallback, which silently encouraged plaintext in `.keyhogignore` - the
// file is often committed by accident; that path is intentionally gone,
// see audit release-2026-04-26.)
self.credential_hashes.contains(hash)
}
fn matches_ignored_hash_hex(&self, hash_hex: &str) -> bool {
parse_sha256_hex(hash_hex).is_some_and(|bytes| self.matches_ignored_hash(&bytes))
}
}
impl Default for Allowlist {
fn default() -> Self {
Self::empty()
}
}
impl Clone for Allowlist {
fn clone(&self) -> Self {
let ignored_paths = self.ignored_paths.clone();
Self {
credential_hashes: self.credential_hashes.clone(),
ignored_detectors: self.ignored_detectors.clone(),
path_index: PathGlobIndex::build(&ignored_paths),
ignored_paths,
expired_entries: self.expired_entries.clone(),
policy_violations: self.policy_violations.clone(),
}
}
}
fn parse_sha256_hex(input: &str) -> Option<CredentialHash> {
hex_to_array(input.trim()).map(CredentialHash::from_bytes)
}
fn invalid_bare_entry(entry: &str) -> Option<(&'static str, &'static str)> {
if entry.contains(':') {
return Some((
"entry",
"entry contains `:` but does not start with a valid prefix (`hash:`, `detector:`, or `path:`); use `path:` for literal path globs containing `:`",
));
}
let bytes = entry.as_bytes();
if bytes.len() == crate::git_lfs::SHA256_HEX_LEN {
return Some((
"hash",
"bare 64-byte entry must be a valid SHA-256 hex digest; use `path:` for a literal 64-byte path glob",
));
}
if bytes.len() >= 32 && bytes.iter().all(u8::is_ascii_hexdigit) {
return Some((
"hash",
"hex-like bare entry must be exactly a 64-character SHA-256 digest; use `path:` for a literal hex path glob",
));
}
None
}
pub(crate) fn allowlist_days_since_epoch_for_test(
now: std::time::SystemTime,
) -> Result<i64, String> {
metadata::days_since_epoch_for_test(now)
}
/// Inline metadata parsed from a `.keyhogignore` line trailer. Used to
/// implement enterprise governance fields (`reason`, `expires`,
/// `approved_by`) per the internal design notes Tier-B #18.
#[derive(Default, Debug)]
struct InlineMetadata {
reason: Option<String>,
expires: Option<String>,
approved_by: Option<String>,
unknown_keys: Vec<String>,
malformed_tokens: Vec<String>,
}