keyhog-scanner 0.5.85

keyhog-scanner: high-performance SIMD-accelerated secret detection engine
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
//! Candidate-bounded roles for documentation, roff, and shell sources.

use keyhog_core::SemanticSourceRole;

use crate::source_semantics::{SourceSemanticEvidence, SourceSpan};

pub(crate) const MAX_DOCUMENT_SOURCE_BYTES: usize = 64 * 1024;
pub(crate) const STRUCTURED_MARKDOWN_FENCES: &[(&str, &str)] = &[
    ("env", ".env"),
    ("dotenv", ".env"),
    ("json", "snippet.json"),
    ("jsonl", "snippet.jsonl"),
    ("ndjson", "snippet.ndjson"),
    ("toml", "snippet.toml"),
    ("yaml", "snippet.yaml"),
    ("yml", "snippet.yml"),
    ("ini", "snippet.ini"),
    ("cfg", "snippet.cfg"),
    ("conf", "snippet.conf"),
    ("properties", "snippet.properties"),
];

#[derive(Debug, Clone, Copy)]
struct DocumentValue {
    span: SourceSpan,
    role: SemanticSourceRole,
}

#[derive(Debug)]
pub(crate) struct DocumentSourceIndex {
    values: Vec<DocumentValue>,
}

impl DocumentSourceIndex {
    fn new(text_len: usize, default_role: SemanticSourceRole) -> Self {
        let mut values = Vec::new();
        if text_len != 0 {
            values.push(DocumentValue {
                span: SourceSpan::new(0, text_len),
                role: default_role,
            });
        }
        Self { values }
    }

    fn push(&mut self, span: SourceSpan, role: SemanticSourceRole) {
        if span.start < span.end {
            self.values.push(DocumentValue { span, role });
        }
    }

    pub(crate) fn classify(&self, target: SourceSpan) -> Option<SourceSemanticEvidence> {
        let value = self
            .values
            .iter()
            .filter(|value| value.span.contains(target))
            .min_by_key(|value| value.span.end.saturating_sub(value.span.start))?;
        Some(SourceSemanticEvidence::parsed(
            value.role, target, value.span,
        ))
    }
}

pub(crate) fn build_document_source_index(text: &str, path: &str) -> Option<DocumentSourceIndex> {
    if text.len() > MAX_DOCUMENT_SOURCE_BYTES {
        return None;
    }
    match document_kind(path)? {
        DocumentKind::Markdown => index_markdown(text),
        DocumentKind::Roff => index_roff(text),
        DocumentKind::Shell => index_shell(text, 0),
    }
}

#[derive(Clone, Copy)]
enum DocumentKind {
    Markdown,
    Roff,
    Shell,
}

fn document_kind(path: &str) -> Option<DocumentKind> {
    let name = path
        .rsplit(['/', '\\', '!'])
        .next()
        .unwrap_or(path)
        .split('?')
        .next()
        .unwrap_or(path);
    let extension = name.rsplit_once('.').map(|(_, extension)| extension);
    if extension.is_some_and(|extension| {
        ["md", "markdown", "mdown"]
            .iter()
            .any(|candidate| extension.eq_ignore_ascii_case(candidate))
    }) {
        Some(DocumentKind::Markdown)
    } else if extension.is_some_and(|extension| {
        ["1", "2", "3", "4", "5", "6", "7", "8", "9", "man", "roff"]
            .iter()
            .any(|candidate| extension.eq_ignore_ascii_case(candidate))
    }) {
        Some(DocumentKind::Roff)
    } else if extension.is_some_and(|extension| {
        ["sh", "bash", "zsh", "ksh"]
            .iter()
            .any(|candidate| extension.eq_ignore_ascii_case(candidate))
    }) || ["Dockerfile", "Containerfile"]
        .iter()
        .any(|candidate| name.eq_ignore_ascii_case(candidate))
    {
        Some(DocumentKind::Shell)
    } else {
        None
    }
}

#[derive(Clone, Copy)]
enum MarkdownFenceLanguage {
    Documentation,
    Shell,
    Structured(&'static str),
}

#[derive(Clone, Copy)]
struct MarkdownFence {
    marker: u8,
    width: usize,
    language: MarkdownFenceLanguage,
    content_start: usize,
}

fn index_markdown(text: &str) -> Option<DocumentSourceIndex> {
    let mut index = DocumentSourceIndex::new(text.len(), SemanticSourceRole::ProseDocumentation);
    let mut line = 0usize;
    let mut fence: Option<MarkdownFence> = None;
    while line < text.len() {
        let inside_fence = fence.is_some();
        let end = line_end(text, line);
        let trimmed_start = skip_spaces(text.as_bytes(), line, end);
        let marker = fence_marker(text.as_bytes(), trimmed_start, end);
        if let Some(active) = fence {
            if marker.is_some_and(|(candidate, candidate_width, _)| {
                candidate == active.marker && candidate_width >= active.width
            }) {
                if let MarkdownFenceLanguage::Structured(path) = active.language {
                    append_structured_fence(&mut index, text, active.content_start, line, path)?;
                }
                fence = None;
            } else if matches!(active.language, MarkdownFenceLanguage::Shell) {
                append_shell_line(&mut index, text, line, end)?;
            }
        } else if let Some((marker, width, language)) = marker {
            fence = Some(MarkdownFence {
                marker,
                width,
                language,
                content_start: next_line(text, line).unwrap_or(end),
            });
        }
        if !inside_fence && marker.is_none() {
            append_inline_code(&mut index, text, line, end)?;
        }
        let Some(next) = next_line(text, line) else {
            break;
        };
        line = next;
    }
    fence.is_none().then_some(index)
}

fn fence_marker(
    bytes: &[u8],
    start: usize,
    end: usize,
) -> Option<(u8, usize, MarkdownFenceLanguage)> {
    let byte @ (b'`' | b'~') = *bytes.get(start)? else {
        return None;
    };
    let width = bytes[start..end]
        .iter()
        .take_while(|candidate| **candidate == byte)
        .count();
    if width < 3 {
        return None;
    }
    let info = std::str::from_utf8(&bytes[start + width..end]).ok()?.trim();
    let language = if ["sh", "shell", "bash", "zsh", "console"]
        .iter()
        .any(|candidate| info.eq_ignore_ascii_case(candidate))
    {
        MarkdownFenceLanguage::Shell
    } else if let Some((_, path)) = STRUCTURED_MARKDOWN_FENCES
        .iter()
        .find(|(candidate, _)| info.eq_ignore_ascii_case(candidate))
    {
        MarkdownFenceLanguage::Structured(path)
    } else {
        MarkdownFenceLanguage::Documentation
    };
    Some((byte, width, language))
}

fn append_structured_fence(
    index: &mut DocumentSourceIndex,
    text: &str,
    start: usize,
    end: usize,
    path: &str,
) -> Option<()> {
    let body = text.get(start..end)?;
    let structured = crate::source_semantics::build_structured_source_index(body, Some(path))?;
    let mut valid = true;
    structured.for_each_value(|role, span| {
        let Some(value_start) = start.checked_add(span.start) else {
            valid = false;
            return;
        };
        let Some(value_end) = start.checked_add(span.end) else {
            valid = false;
            return;
        };
        index.push(SourceSpan::new(value_start, value_end), role);
    });
    valid.then_some(())
}

fn append_inline_code(
    index: &mut DocumentSourceIndex,
    text: &str,
    start: usize,
    end: usize,
) -> Option<()> {
    let bytes = text.as_bytes();
    let mut cursor = start;
    while cursor < end {
        if bytes[cursor] != b'`' {
            cursor += 1;
            continue;
        }
        let width = bytes[cursor..end]
            .iter()
            .take_while(|byte| **byte == b'`')
            .count();
        let content_start = cursor + width;
        let close = find_run(bytes, content_start, end, b'`', width)?;
        index.push(
            SourceSpan::new(content_start, close),
            SemanticSourceRole::ProseDocumentation,
        );
        cursor = close + width;
    }
    Some(())
}

fn index_roff(text: &str) -> Option<DocumentSourceIndex> {
    let mut index = DocumentSourceIndex::new(text.len(), SemanticSourceRole::ProseDocumentation);
    let mut line = 0usize;
    while line < text.len() {
        let end = line_end(text, line);
        let trimmed = skip_spaces(text.as_bytes(), line, end);
        if text.as_bytes().get(trimmed) == Some(&b'.') {
            let tokens = shell_tokens(text, trimmed, end)?;
            if tokens.iter().any(|token| {
                text[token.start..token.end]
                    .trim_matches(['\'', '"'])
                    .starts_with("--")
            }) {
                index.push(
                    SourceSpan::new(trimmed, end),
                    SemanticSourceRole::CommandOptionDeclaration,
                );
            }
        }
        let Some(next) = next_line(text, line) else {
            break;
        };
        line = next;
    }
    Some(index)
}

fn index_shell(text: &str, base: usize) -> Option<DocumentSourceIndex> {
    let mut index = DocumentSourceIndex { values: Vec::new() };
    let mut line = 0usize;
    while line < text.len() {
        let end = line_end(text, line);
        append_shell_line_with_base(&mut index, text, line, end, base)?;
        let Some(next) = next_line(text, line) else {
            break;
        };
        line = next;
    }
    Some(index)
}

fn append_shell_line(
    index: &mut DocumentSourceIndex,
    text: &str,
    start: usize,
    end: usize,
) -> Option<()> {
    append_shell_line_with_base(index, text, start, end, 0)
}

fn append_shell_line_with_base(
    index: &mut DocumentSourceIndex,
    text: &str,
    start: usize,
    end: usize,
    base: usize,
) -> Option<()> {
    let tokens = shell_tokens(text, start, end)?;
    let mut expects_option_value = false;
    let mut command_started = false;
    for token in tokens {
        let raw = &text[token.start..token.end];
        let unquoted = raw.trim_matches(['\'', '"']);
        let unquoted_offset = raw.find(unquoted).unwrap_or(0);
        let span = SourceSpan::new(
            base + token.start + unquoted_offset,
            base + token.start + unquoted_offset + unquoted.len(),
        );
        if expects_option_value {
            index.push(span, SemanticSourceRole::CommandArgumentValue);
            expects_option_value = false;
            continue;
        }
        if unquoted.starts_with('-') {
            command_started = true;
            if let Some(equals) = unquoted.find('=') {
                let value_start = span.start + equals + 1;
                index.push(
                    SourceSpan::new(value_start, span.end),
                    SemanticSourceRole::CommandArgumentValue,
                );
            } else {
                expects_option_value = true;
            }
        } else if !command_started
            && unquoted
                .split_once('=')
                .is_some_and(|(name, _)| is_shell_name(name))
        {
            let equals = unquoted.find('=').expect("split_once proved assignment");
            index.push(
                SourceSpan::new(span.start + equals + 1, span.end),
                SemanticSourceRole::EnvironmentAssignmentValue,
            );
        } else if command_started {
            index.push(span, SemanticSourceRole::CommandArgumentValue);
        } else {
            command_started = true;
        }
    }
    Some(())
}

fn is_shell_name(name: &str) -> bool {
    let mut bytes = name.bytes();
    bytes
        .next()
        .is_some_and(|byte| byte == b'_' || byte.is_ascii_alphabetic())
        && bytes.all(|byte| byte == b'_' || byte.is_ascii_alphanumeric())
}

fn shell_tokens(text: &str, start: usize, end: usize) -> Option<Vec<SourceSpan>> {
    let bytes = text.as_bytes();
    let mut tokens = Vec::new();
    let mut cursor = start;
    while cursor < end {
        cursor = skip_spaces(bytes, cursor, end);
        if cursor == end || bytes[cursor] == b'#' {
            break;
        }
        let token_start = cursor;
        let mut quote = None;
        while cursor < end {
            if let Some(active) = quote {
                if bytes[cursor] == b'\\' && active == b'"' {
                    cursor = cursor.saturating_add(2);
                } else if bytes[cursor] == active {
                    quote = None;
                    cursor += 1;
                } else {
                    cursor += 1;
                }
            } else if matches!(bytes[cursor], b'\'' | b'"') {
                quote = Some(bytes[cursor]);
                cursor += 1;
            } else if bytes[cursor].is_ascii_whitespace() {
                break;
            } else if bytes[cursor] == b'#' && cursor == token_start {
                break;
            } else if bytes[cursor] == b'\\' {
                cursor = cursor.saturating_add(2);
            } else {
                cursor += 1;
            }
        }
        if quote.is_some() || cursor > end {
            return None;
        }
        tokens.push(SourceSpan::new(token_start, cursor));
    }
    Some(tokens)
}

fn find_run(bytes: &[u8], mut cursor: usize, end: usize, byte: u8, width: usize) -> Option<usize> {
    while cursor + width <= end {
        if bytes[cursor..cursor + width]
            .iter()
            .all(|candidate| *candidate == byte)
        {
            return Some(cursor);
        }
        cursor += 1;
    }
    None
}

fn skip_spaces(bytes: &[u8], mut cursor: usize, end: usize) -> usize {
    while cursor < end && matches!(bytes[cursor], b' ' | b'\t') {
        cursor += 1;
    }
    cursor
}

fn line_end(text: &str, start: usize) -> usize {
    text.as_bytes()[start..]
        .iter()
        .position(|byte| matches!(byte, b'\r' | b'\n'))
        .map_or(text.len(), |offset| start + offset)
}

fn next_line(text: &str, start: usize) -> Option<usize> {
    let end = line_end(text, start);
    (end < text.len()).then_some(if text.as_bytes().get(end..end + 2) == Some(b"\r\n") {
        end + 2
    } else {
        end + 1
    })
}