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
#[cfg(feature = "simdsieve")]
use super::*;
#[cfg(feature = "simdsieve")]
use crate::context;
#[cfg(feature = "simdsieve")]
use keyhog_core::{MatchLocation, RawMatch, Severity};
#[cfg(feature = "simdsieve")]
use std::collections::HashMap;
#[cfg(feature = "simdsieve")]
impl CompiledScanner {
pub(crate) fn scan_hot_patterns_fast(
&self,
text: &str,
line_offsets: &[usize],
chunk: &Chunk,
scan_state: &mut ScanState,
) {
use crate::simdsieve_prefilter::{
HOT_PATTERNS, HOT_PATTERN_DETECTOR_IDS, HOT_PATTERN_DISPLAY_NAMES, HOT_PATTERN_NAMES,
};
use simdsieve::SimdSieve;
let text_bytes = text.as_bytes();
// SimdSieve takes `&[&[u8]]`; HOT_PATTERNS is already exactly
// that, so pass it through. The previous flow built a fresh
// `Vec<&[u8]>` per chunk via `.to_vec()` - wasted on every
// file in a 100k-file scan.
let Ok(sieve) = SimdSieve::new(text_bytes, HOT_PATTERNS) else {
return;
};
for offset in sieve {
if scan_state.matches.len() >= self.config.max_matches_per_chunk {
break;
}
for (pattern_idx, pattern) in HOT_PATTERNS.iter().enumerate() {
let end = offset + pattern.len();
if end > text_bytes.len() || &text_bytes[offset..end] != *pattern {
continue;
}
let lookahead_end = (offset + 100).min(text_bytes.len());
let candidate = &text_bytes[offset..lookahead_end];
let cred_end = candidate
.iter()
.position(|&byte| {
byte == b' '
|| byte == b'\n'
|| byte == b'\r'
|| byte == b'"'
|| byte == b'\''
|| byte == b'\\'
|| byte == b';'
|| byte == b','
|| byte == b'('
|| byte == b')'
|| byte == b'['
|| byte == b']'
|| byte == b'{'
|| byte == b'}'
|| byte < 0x20
})
.unwrap_or(candidate.len());
let credential = std::str::from_utf8(&candidate[..cred_end]).unwrap_or("");
// Precise-regex gate. The literal-prefix hit + length floor
// below is a fast prefilter, NOT proof of a real token: a
// length floor admits wrong-character-class strings the
// detector's own regex rejects (`ghp_THIS_HAS_UNDERSCORES…`
// is 43 ≥ 40 but `_` is not in `[A-Za-z0-9]`;
// `xoxp-123-456-789-abc` is 20 ≥ 16 but the segments are far
// short of the 10-13-digit Slack shape). Validate the
// candidate against the detector's regex (anchored at the
// candidate start) and emit the PRECISE matched span, so the
// fast path can never surface a finding the AC+regex path
// would not. Slots with no canonical detector (square) carry
// a `None` validator and keep the length-floor as their gate.
let credential = match self.hot_pattern_validators.get(pattern_idx) {
Some(Some(validator)) => match validator.find(credential) {
// `^`-anchored, so any match starts at 0; trim the
// delimiter-bounded capture down to the real token.
Some(m) => &credential[..m.end()],
None => continue,
},
// No validator for this slot (square, or out of range):
// fall back to the length-floor-only behavior below.
_ => credential,
};
// Per-pattern minimum credential length, in bytes.
// The 8-byte blanket floor would let `AKIA12345`
// (9 bytes, only 5 after the 4-byte `AKIA` prefix)
// through as a "real" AWS access key. Real AKIA
// tokens are AKIA + 16 = 20 bytes minimum - tighten
// the floor per-pattern so the fast-path never emits
// a credential the matching detector's regex would
// reject. See
// tests/adversarial/engine_cases/scanner_stress.rs::
// stress_minified_js_finds_real_pat_not_truncated_aws.
//
// The other hot patterns keep the loose 8-byte floor
// because tightening them speculatively breaks the
// base64 / hex / multi-line-split evasion-corpus
// tests that exercise SHORT decoded fragments. Each
// additional tightening needs its own per-pattern
// regression gate first.
//
// Per-pattern minimum credential length, in bytes.
// Each pattern's floor matches the actual minimum length
// a valid token of that shape can have - fast-path
// findings are emitted as Critical severity without
// re-running the full detector regex, so a too-loose
// floor turns every `SG.length` / `ghp_xxxx` / `xoxb-abc`
// substring into a hard finding.
//
// Index aligns with simdsieve_prefilter::HOT_PATTERNS:
// 0 ghp_ 40 (ghp_ + 36 base62 = real GitHub PAT)
// 1 sk-proj- 20 (sk-proj- + 12 - anthropic/openai newer keys)
// 2 AKIA 20 (AKIA + 16 - already tightened, scanner_stress)
// 3 ASIA 20 (ASIA + 16 - temporary AWS sts session creds)
// 4 SG. 26 (SG. + 22 first-segment base64 minimum;
// full SG.X22+.Y43+ is 69+ chars total)
// 5 xoxb- 16 (xoxb- + 11 alnum minimum slack bot token)
// 6 xoxp- 16 (xoxp- + 11 alnum minimum slack user token)
// 7 sq0csp- 16 (sq0csp- + 9 alnum minimum square secret)
//
// Dogfood: pre-tightening the v0.5.19 binary fired
// `SG.length` in claude-code's OAuthFlowStep.tsx
// (PASTE_HERE_MSG.length substring) as Critical
// sendgrid_key. SG. floor of 8 meant `SG.length` (9
// chars) cleared. 26-floor leaves the first-segment
// shape intact while killing the JS-property FP.
const PER_PATTERN_MIN_LEN: &[usize] = &[40, 20, 20, 20, 26, 16, 16, 16];
let min_len = PER_PATTERN_MIN_LEN.get(pattern_idx).copied().unwrap_or(8);
if credential.len() < min_len
|| crate::pipeline::should_suppress_known_example_credential_with_source(
credential,
chunk.metadata.path.as_deref(),
context::CodeContext::Unknown,
Some(chunk.metadata.source_type.as_str()),
)
{
continue;
}
// Regex-literal suppression for the hot-pattern fast-path.
// Source files that ship secret-scanner code (claude-code's
// teamMemorySync/secretScanner.ts, components/Feedback.tsx,
// every trufflehog / gitleaks competitor) emit hot findings
// on their own regex DEFINITIONS - `AKIA[A-Z0-9]{16,17})/g`,
// `ASIA[A-Z0-9]{16})\b`, `xoxb-[0-9-]*`. Real tokens never
// end in regex sigils. The tail-suffix check is O(1).
if crate::pipeline::looks_like_regex_literal_tail(credential) {
continue;
}
// Vendored 3rd-party minified bundle: same rationale as
// the named-detector path. Random byte sequences in
// minified codemirror/pdfjs/jquery/wp-includes bundles
// routinely hit `AKIA…`/`ASIA…` literal-prefix patterns.
if crate::pipeline::looks_like_vendored_minified_path(
chunk.metadata.path.as_deref(),
) {
continue;
}
// Native-binary string extraction: skip hot-pattern hits
// on the strings-fallback source - same coverage rationale
// as `should_suppress_named_detector_finding`.
if chunk.metadata.source_type.contains("binary-strings")
|| chunk.metadata.source_type.contains("archive-binary")
{
continue;
}
// Secret-scanner source files (the dogfooded file IS itself
// a secret scanner - claude-code's teamMemorySync/
// secretScanner.ts, trufflehog/, gitleaks/, etc.) emit
// hot-pattern findings on their own detector regex
// DEFINITIONS. The `looks_like_regex_literal_tail` check
// catches the common forms; decoder-mangled trailing
// sigils slip past - this filter closes the gap.
if crate::pipeline::looks_like_secret_scanner_source(chunk.metadata.path.as_deref())
{
continue;
}
// Raw base64 / pure-alphabet files: alphabet-coincidence
// matches inside the base64 stream (AKIA/ASIA/etc.) are
// not credentials. Skim raw path bytes case-insensitively
// so a per-match `.to_ascii_lowercase()` allocation never
// lands on the hot-pattern path (this branch fires for
// every AKIA/ASIA literal in every chunk).
if chunk.metadata.path.as_deref().is_some_and(|p| {
let bytes = p.as_bytes();
if crate::ascii_ci::ends_with_ignore_ascii_case(bytes, b".b64")
|| crate::ascii_ci::ends_with_ignore_ascii_case(bytes, b".base64")
{
return true;
}
// `/` AND `\\` for Windows paths - keeps the
// hot-pattern base64 filename gate working when
// the scanner runs against a Windows checkout.
let basename = bytes
.iter()
.rposition(|&b| b == b'/' || b == b'\\')
.map(|i| &bytes[i + 1..])
.unwrap_or(bytes);
(crate::ascii_ci::starts_with_ignore_ascii_case(basename, b"base64_")
|| crate::ascii_ci::ci_find(basename, b"base64_string"))
&& !crate::ascii_ci::ends_with_ignore_ascii_case(basename, b".json")
&& !crate::ascii_ci::ends_with_ignore_ascii_case(basename, b".yml")
&& !crate::ascii_ci::ends_with_ignore_ascii_case(basename, b".yaml")
}) {
continue;
}
// Same partition_point binary-search idiom as
// `match_line_number` - `line_offsets` is sorted
// ascending, so the first offset > `offset` IS the
// 1-based line number directly.
let line = line_offsets.partition_point(|&lo| lo <= offset).max(1);
// Use the pre-formatted static tables - eliminates the
// two `format!()` heap allocations the perf kimi audit
// flagged at this site (one per match, 16 bytes each).
// Index-parallel with HOT_PATTERN_NAMES; the parallel-
// array invariant is locked by unit tests in the parent
// module.
let detector_id = scan_state.intern_metadata(HOT_PATTERN_DETECTOR_IDS[pattern_idx]);
let detector_name =
scan_state.intern_metadata(HOT_PATTERN_DISPLAY_NAMES[pattern_idx]);
let service = scan_state.intern_metadata(HOT_PATTERN_NAMES[pattern_idx]);
let credential_shared = scan_state.intern_credential(credential);
let source = scan_state.intern_metadata(&chunk.metadata.source_type);
let file_path = chunk
.metadata
.path
.as_ref()
.map(|path| scan_state.intern_metadata(path));
let commit = chunk
.metadata
.commit
.as_ref()
.map(|commit| scan_state.intern_metadata(commit));
let author = chunk
.metadata
.author
.as_ref()
.map(|author| scan_state.intern_metadata(author));
let date = chunk
.metadata
.date
.as_ref()
.map(|date| scan_state.intern_metadata(date));
scan_state.push_match(
RawMatch {
credential_hash: crate::sha256_hash(credential),
detector_id,
detector_name,
service,
severity: Severity::Critical,
credential: credential_shared,
companions: HashMap::new(),
location: MatchLocation {
source,
file_path,
line: Some(line),
offset,
commit,
author,
date,
},
entropy: None,
confidence: Some(
crate::confidence::known_prefix_confidence_floor(credential)
.unwrap_or(0.7), // Hot patterns are high-confidence by definition
),
},
self.config.max_matches_per_chunk,
);
break;
}
}
}
}