keyhog-core 0.2.0

Core types, traits, and detector specs for the 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
//! Scanner findings: the output type for detected secrets with location,
//! confidence, detector metadata, and optional verification status.

use serde::Serialize;
use std::collections::HashMap;

use crate::Severity;

/// A credential match found by the scanner, before verification.
///
/// # Examples
///
/// ```rust
/// use keyhog_core::{MatchLocation, RawMatch, Severity};
///
/// let finding = RawMatch {
///     detector_id: "demo-token".into(),
///     detector_name: "Demo Token".into(),
///     service: "demo".into(),
///     severity: Severity::High,
///     credential: "demo_ABC12345".into(),
///     companion: None,
///     location: MatchLocation {
///         source: "filesystem".into(),
///         file_path: Some(".env".into()),
///         line: Some(1),
///         offset: 0,
///         commit: None,
///         author: None,
///         date: None,
///     },
///     entropy: None,
///     confidence: Some(0.9),
/// };
///
/// assert_eq!(finding.detector_id, "demo-token");
/// ```
#[derive(Debug, Clone, Serialize)]
pub struct RawMatch {
    /// Stable detector identifier.
    pub detector_id: String,
    /// Human-readable detector name.
    pub detector_name: String,
    /// Service namespace associated with the detector.
    pub service: String,
    /// Detector severity level.
    pub severity: Severity,
    /// Matched credential bytes before redaction.
    pub credential: String,
    /// Companion credential or context value extracted nearby.
    pub companion: Option<String>,
    /// Source location for the match.
    pub location: MatchLocation,
    /// Shannon entropy of the matched credential (0.0 - 8.0).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub entropy: Option<f64>,
    /// Confidence score (0.0 - 1.0) combining entropy, keyword proximity, file type, etc.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub confidence: Option<f64>,
}

/// Where a credential was found: file path, line number, commit, and author.
///
/// # Examples
///
/// ```rust
/// use keyhog_core::MatchLocation;
///
/// let location = MatchLocation {
///     source: "stdin".into(),
///     file_path: None,
///     line: Some(3),
///     offset: 20,
///     commit: None,
///     author: None,
///     date: None,
/// };
///
/// assert_eq!(location.line, Some(3));
/// ```
#[derive(Debug, Clone, Serialize)]
pub struct MatchLocation {
    /// Logical source backend, such as `filesystem` or `git`.
    pub source: String,
    /// File path, object key, or logical path when available.
    pub file_path: Option<String>,
    /// One-based line number when known.
    pub line: Option<usize>,
    /// Byte offset from the start of the source chunk.
    pub offset: usize,
    /// Commit identifier for history-derived matches.
    pub commit: Option<String>,
    /// Commit author when available.
    pub author: Option<String>,
    /// Commit timestamp when available.
    pub date: Option<String>,
}

/// A finding after verification — the final output.
///
/// # Examples
///
/// ```rust
/// use keyhog_core::{MatchLocation, Severity, VerificationResult, VerifiedFinding};
/// use std::collections::HashMap;
///
/// let finding = VerifiedFinding {
///     detector_id: "demo-token".into(),
///     detector_name: "Demo Token".into(),
///     service: "demo".into(),
///     severity: Severity::High,
///     credential_redacted: "demo_...2345".into(),
///     location: MatchLocation {
///         source: "filesystem".into(),
///         file_path: Some(".env".into()),
///         line: Some(1),
///         offset: 0,
///         commit: None,
///         author: None,
///         date: None,
///     },
///     verification: VerificationResult::Skipped,
///     metadata: HashMap::new(),
///     additional_locations: Vec::new(),
///     confidence: Some(0.9),
/// };
///
/// assert_eq!(finding.service, "demo");
/// ```
#[derive(Debug, Clone, Serialize)]
pub struct VerifiedFinding {
    /// Stable detector identifier.
    pub detector_id: String,
    /// Human-readable detector name.
    pub detector_name: String,
    /// Service namespace associated with the detector.
    pub service: String,
    /// Detector severity level.
    pub severity: Severity,
    /// Redacted credential string suitable for output.
    pub credential_redacted: String,
    /// Primary source location for the finding.
    pub location: MatchLocation,
    /// Verification outcome for the credential.
    pub verification: VerificationResult,
    /// Extra metadata extracted from verification responses.
    #[serde(skip_serializing_if = "HashMap::is_empty")]
    pub metadata: HashMap<String, String>,
    /// Additional duplicate locations that resolved into the same finding.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub additional_locations: Vec<MatchLocation>,
    /// Confidence score (0.0 - 1.0) combining entropy, keyword proximity, file type, etc.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub confidence: Option<f64>,
}

/// Result of live verification: whether the credential is active, revoked, or untested.
///
/// # Examples
///
/// ```rust
/// use keyhog_core::VerificationResult;
///
/// let status = VerificationResult::Live;
/// assert!(matches!(status, VerificationResult::Live));
/// ```
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum VerificationResult {
    /// The credential was verified as active.
    Live,
    /// The credential was checked and appears invalid.
    Dead,
    /// Verification was throttled by the upstream service.
    RateLimited,
    /// Verification failed before a conclusive result was produced.
    Error(String),
    /// The detector has no live verification path.
    Unverifiable,
    /// Verification was disabled for this scan.
    Skipped,
}

impl RawMatch {
    /// Deduplication key: same detector + same credential = same finding.
    /// Git history includes commit ID so the same secret in different commits stays distinct.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use keyhog_core::{MatchLocation, RawMatch, Severity};
    ///
    /// let finding = RawMatch {
    ///     detector_id: "demo".into(),
    ///     detector_name: "Demo".into(),
    ///     service: "demo".into(),
    ///     severity: Severity::High,
    ///     credential: "demo_ABC12345".into(),
    ///     companion: None,
    ///     location: MatchLocation {
    ///         source: "filesystem".into(),
    ///         file_path: Some(".env".into()),
    ///         line: Some(1),
    ///         offset: 0,
    ///         commit: None,
    ///         author: None,
    ///         date: None,
    ///     },
    ///     entropy: None,
    ///     confidence: None,
    /// };
    ///
    /// assert_eq!(finding.deduplication_key().0, "demo");
    /// ```
    pub fn deduplication_key(&self) -> (String, String) {
        if self.location.source == "git-history" {
            (
                format!(
                    "{}:{}",
                    self.detector_id,
                    self.location.commit.clone().unwrap_or_default()
                ),
                self.credential.clone(),
            )
        } else {
            (self.detector_id.clone(), self.credential.clone())
        }
    }
}

/// Redact a credential for safe display without leaking type prefixes or exact length.
///
/// # Examples
///
/// ```rust
/// use keyhog_core::redact;
///
/// let key = format!("sk_live_{}", "abcdefghijklmnopqrstuvwxyz1234");
/// assert_eq!(redact(&key), "sk_live_...1234");
/// ```
pub fn redact(credential: &str) -> String {
    if credential.is_empty() {
        return "*".repeat(8);
    }
    if credential.len() <= SHORT_SECRET_MAX_LEN {
        return redact_short_secret(credential);
    }
    redact_with_prefix_preservation(credential)
}

const SHORT_SECRET_MAX_LEN: usize = 8;
const SHORT_SECRET_EDGE_CHARS: usize = 2;
const DEFAULT_REDACTION_EDGE_CHARS: usize = 4;
const MAX_VISIBLE_PREFIX_CHARS: usize = 8;
const REDACTION_SEPARATOR: &str = "...";

fn redact_short_secret(credential: &str) -> String {
    let start = first_chars(credential, SHORT_SECRET_EDGE_CHARS);
    let end = last_chars(credential, SHORT_SECRET_EDGE_CHARS);
    format!("{start}{REDACTION_SEPARATOR}{end}")
}

fn redact_with_prefix_preservation(credential: &str) -> String {
    let prefix_len = visible_prefix_len(credential);
    let suffix_len = last_chars(credential, DEFAULT_REDACTION_EDGE_CHARS).len();
    if prefix_len == 0 || credential.len() <= prefix_len + suffix_len {
        return redact_without_prefix_preservation(credential);
    }
    let prefix = &credential[..prefix_len];
    let suffix = &credential[credential.len() - suffix_len..];
    format!("{prefix}{REDACTION_SEPARATOR}{suffix}")
}

fn visible_prefix_len(credential: &str) -> usize {
    credential
        .char_indices()
        .take_while(|(_, ch)| ch.is_ascii_alphanumeric() || matches!(ch, '-' | '_' | '.'))
        .take(MAX_VISIBLE_PREFIX_CHARS)
        .last()
        .map(|(idx, ch)| idx + ch.len_utf8())
        .unwrap_or(0)
        .min(
            credential
                .len()
                .saturating_sub(DEFAULT_REDACTION_EDGE_CHARS),
        )
}

fn redact_without_prefix_preservation(credential: &str) -> String {
    let start = first_chars(credential, DEFAULT_REDACTION_EDGE_CHARS);
    let end = last_chars(credential, DEFAULT_REDACTION_EDGE_CHARS);
    if start == end {
        format!("{start}{REDACTION_SEPARATOR}")
    } else {
        format!("{start}{REDACTION_SEPARATOR}{end}")
    }
}

fn first_chars(value: &str, count: usize) -> String {
    value.chars().take(count).collect()
}

fn last_chars(value: &str, count: usize) -> String {
    let total = value.chars().count();
    value.chars().skip(total.saturating_sub(count)).collect()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn redaction() {
        assert_eq!(redact("xoxb-1234567890-abc"), "xoxb-123...-abc");
        assert_eq!(redact("short"), "sh...rt");
        assert_eq!(redact("AKIA1234567890ABCDEF"), "AKIA1234...CDEF");
        assert_eq!(
            redact("sk-proj-abcdefghijklmnopqrstuvwxyz1234"),
            "sk-proj-...1234"
        );
    }

    #[test]
    fn deduplication_key_groups_same_credential() {
        let m1 = RawMatch {
            detector_id: "aws".into(),
            detector_name: "AWS".into(),
            service: "aws".into(),
            severity: Severity::Critical,
            credential: "AKIAIOSFODNN7EXAMPLE".into(),
            companion: None,
            location: MatchLocation {
                source: "fs".into(),
                file_path: Some("file1.py".into()),
                line: Some(10),
                offset: 0,
                commit: None,
                author: None,
                date: None,
            },
            entropy: None,
            confidence: None,
        };
        let m2 = RawMatch {
            location: MatchLocation {
                file_path: Some("file2.py".into()),
                line: Some(20),
                ..m1.location.clone()
            },
            ..m1.clone()
        };
        assert_eq!(m1.deduplication_key(), m2.deduplication_key());
    }

    macro_rules! redaction_case {
        ($name:ident, $input:expr, $expected:expr) => {
            #[test]
            fn $name() {
                assert_eq!(redact($input), $expected);
            }
        };
    }

    redaction_case!(redact_empty_secret, "", "********");
    redaction_case!(redact_single_char_secret, "a", "a...a");
    redaction_case!(redact_two_char_secret, "ab", "ab...ab");
    redaction_case!(redact_eight_char_secret, "12345678", "12...78");
    redaction_case!(
        redact_prefixless_long_secret,
        "@@@@abcdefgh1234",
        "@@@@...1234"
    );
    redaction_case!(redact_unicode_secret, "пароль-супер-длинный", "паро...нный");
    redaction_case!(
        redact_secret_with_preserved_ascii_prefix,
        "token_value_1234567890",
        "token_va...7890"
    );
    redaction_case!(
        redact_repeated_edges_compacts_suffix,
        "aaaaabbbbb",
        "aaaa...bbbb"
    );

    #[test]
    fn git_history_deduplication_includes_commit_id() {
        let matched = RawMatch {
            detector_id: "aws".into(),
            detector_name: "AWS".into(),
            service: "aws".into(),
            severity: Severity::Critical,
            credential: "AKIAIOSFODNN7EXAMPLE".into(),
            companion: None,
            location: MatchLocation {
                source: "git-history".into(),
                file_path: Some("history.env".into()),
                line: Some(1),
                offset: 0,
                commit: Some("abc123".into()),
                author: None,
                date: None,
            },
            entropy: None,
            confidence: None,
        };

        let (detector, credential) = matched.deduplication_key();
        assert_eq!(detector, "aws:abc123");
        assert_eq!(credential, "AKIAIOSFODNN7EXAMPLE");
    }
}