keyhog-core 0.5.42

keyhog-core: shared data model and detector specifications for the KeyHog 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
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
//! Auto-fix suggestions: turn each finding into "replace this credential
//! with `${ENV_VAR_NAME}`" advice.
//!
//! Tier-B moat innovation #15 + #17 from the internal design notes:
//! moves keyhog from "find" to "fix." We surface the suggestion in SARIF
//! `result.fixes[]` per the v2.2.0 spec; CLI consumers can apply the edit
//! interactively or in a pre-commit hook.
//!
//! This module provides only the SUGGESTION step (deterministic env-var
//! name from service + the `${VAR}` replacement string). Actually rewriting
//! files belongs in the CLI, where we can prompt the user before clobbering
//! their working tree.
//!
//! The curated `service -> env var` mappings are **Tier-B data**, compiled in
//! from `data/service-env-vars.toml`. They are NOT a hardcoded `match` arm and
//! are not extended by ambient process environment; changing the shipped map is
//! a data-file edit, reviewable in the same diff as the detector corpus.

use std::collections::BTreeSet;
use std::sync::LazyLock;

use crate::Severity;

/// One curated `service -> env var` mapping, deserialized from the Tier-B
/// `[[service]]` tables in `data/service-env-vars.toml`.
#[derive(serde::Deserialize)]
#[serde(deny_unknown_fields)]
struct ServiceEnvEntry {
    /// ASCII-case-insensitive needle tested against the service string.
    #[serde(rename = "match")]
    needle: String,
    /// The environment-variable name emitted verbatim when the needle matches.
    env: String,
    /// When `true`, require the service to START with `needle`; otherwise it is
    /// a substring test.
    #[serde(default)]
    prefix: bool,
}

#[derive(serde::Deserialize, Default)]
#[serde(deny_unknown_fields)]
struct ServiceEnvFile {
    #[serde(default)]
    service: Vec<ServiceEnvEntry>,
}

/// The compiled-in service map. Ordering within the file is preserved; because
/// matching takes the first hit, the data file must list more-specific needles
/// before broader substrings they could otherwise shadow.
///
/// The map is `include_str!`d at compile time, so an invalid document is a BUILD
/// bug, never a runtime/user condition, identical to `REMEDIATION_MAP`. Failing
/// loud (panic in the initializer) is the fail-closed response; degrading to the
/// screaming-snake derivation would silently ship wrong fix advice (Law 10).
#[allow(clippy::panic)]
static SERVICE_ENV_MAP: LazyLock<Vec<ServiceEnvEntry>> = LazyLock::new(|| {
    match parse_service_env_file(
        include_str!("../data/service-env-vars.toml"),
        "<embedded data/service-env-vars.toml>",
    ) {
        Ok(entries) => entries,
        Err(error) => panic!(
            "keyhog: service-env map '<embedded data/service-env-vars.toml>' is invalid: {error}. \
             Fix: correct crates/core/data/service-env-vars.toml and rebuild"
        ),
    }
});

/// Provider-specific remediation advice emitted by text, JSON, SARIF, and HTML
/// reporters. The values come from Tier-B data, never reporter-side match arms.
#[derive(Debug, Clone, serde::Serialize)]
pub(crate) struct Remediation {
    pub(crate) action: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(crate) revoke_url: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(crate) docs_url: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(crate) revoke_command: Option<String>,
}

impl Remediation {
    pub(crate) fn markdown(&self) -> String {
        let mut out = self.action.clone();
        if let Some(command) = &self.revoke_command {
            out.push_str("\n\nRevoke command:\n\n```sh\n");
            out.push_str(command);
            out.push_str("\n```");
        }
        if let Some(url) = self.revoke_url.as_ref().or(self.docs_url.as_ref()) {
            out.push_str("\n\nReference: ");
            out.push_str(url);
        }
        out
    }
}

#[derive(Clone, serde::Deserialize)]
struct RemediationFields {
    action: String,
    #[serde(default)]
    revoke_url: Option<String>,
    #[serde(default)]
    docs_url: Option<String>,
    #[serde(default)]
    revoke_command: Option<String>,
}

impl From<&RemediationFields> for Remediation {
    fn from(fields: &RemediationFields) -> Self {
        Self {
            action: fields.action.clone(),
            revoke_url: fields.revoke_url.clone(),
            docs_url: fields.docs_url.clone(),
            revoke_command: fields.revoke_command.clone(),
        }
    }
}

#[derive(serde::Deserialize)]
struct DetectorRemediationEntry {
    id: String,
    #[serde(flatten)]
    fields: RemediationFields,
}

#[derive(serde::Deserialize)]
struct ServiceRemediationEntry {
    #[serde(rename = "match")]
    needle: String,
    #[serde(default)]
    prefix: bool,
    #[serde(flatten)]
    fields: RemediationFields,
}

#[derive(serde::Deserialize)]
struct SeverityRemediationEntry {
    severity: String,
    #[serde(flatten)]
    fields: RemediationFields,
}

#[derive(Default, serde::Deserialize)]
#[serde(deny_unknown_fields)]
struct RemediationFile {
    #[serde(default)]
    detector: Vec<DetectorRemediationEntry>,
    #[serde(default)]
    service: Vec<ServiceRemediationEntry>,
    #[serde(default)]
    severity: Vec<SeverityRemediationEntry>,
}

// The embedded remediation map is `include_str!`d at compile time, so an invalid
// document is a BUILD bug, never a runtime/user condition. Failing loud (panic in
// the initializer) is the correct, recall-safe response: a runtime fallback to an
// empty map would silently strip remediation advice (Law 10). `clippy::panic`
// targets genuine runtime panics; this compile-time invariant is the exception.
#[allow(clippy::panic)]
static REMEDIATION_MAP: LazyLock<RemediationFile> =
    LazyLock::new(|| {
        match parse_remediation_file(
            include_str!("../data/remediation.toml"),
            "<embedded data/remediation.toml>",
        ) {
            Ok(parsed) => parsed,
            Err(error) => {
                panic!(
            "keyhog: remediation map '<embedded data/remediation.toml>' is invalid: {error}. \
                 Fix: correct crates/core/data/remediation.toml and rebuild"
        );
            }
        }
    });

/// The per-severity remediation fallback, resolved once into a rank-indexed total
/// array. `REMEDIATION_MAP`'s initializer runs `validate_severity_remediation`,
/// which fails the (compile-time-embedded) load unless every `Severity::ORDERED`
/// carries a `[[severity]]` entry, so every slot is populated. Resolving it here
/// lets `remediation_for` do an infallible `[rank]` index instead of a fallible
/// `find(...).expect(...)` on a value the load-time invariant already guarantees.
static SEVERITY_FALLBACKS: LazyLock<[RemediationFields; Severity::ORDERED.len()]> =
    LazyLock::new(|| {
        let file = &*REMEDIATION_MAP;
        std::array::from_fn(|rank| {
            let severity = Severity::ORDERED[rank];
            match file
                .severity
                .iter()
                .find(|entry| entry.severity == severity.as_str())
            {
                Some(entry) => entry.fields.clone(),
                // Unreachable: REMEDIATION_MAP's initializer enforces the
                // completeness invariant (it panics on a missing severity). A loud
                // sentinel, never a silent/empty value, keeps a hypothetical
                // invariant break visible rather than fail-silent (Law 10).
                None => RemediationFields {
                    action: format!(
                        "(internal) remediation map is missing a {} fallback, rebuild keyhog",
                        severity.as_str()
                    ),
                    revoke_url: None,
                    docs_url: None,
                    revoke_command: None,
                },
            }
        })
    });

/// Parse one `service-env-vars.toml` document into its entries. A parse error is
/// returned (fail-closed) so the caller can refuse rather than silently ship
/// wrong fix advice (Law 10).
fn parse_service_env_file(raw: &str, origin: &str) -> Result<Vec<ServiceEnvEntry>, String> {
    let entries = toml::from_str::<ServiceEnvFile>(raw)
        .map(|parsed| parsed.service)
        .map_err(|error| format!("failed to parse {origin}: {error}"))?;
    // Fail closed on malformed Tier-B rows: an empty needle would match EVERY
    // service (shadowing every later entry) and an empty env would emit the
    // nonsense replacement `${}`; a duplicate (needle, prefix) is a dead row
    // the first-hit lookup can never reach. Reject rather than silently ship
    // wrong fix advice (Law 10).
    let mut seen = BTreeSet::new();
    for (index, entry) in entries.iter().enumerate() {
        if entry.needle.trim().is_empty() {
            return Err(format!("{origin} [[service]] row {index} has empty match"));
        }
        if entry.env.trim().is_empty() {
            return Err(format!("{origin} [[service]] row {index} has empty env"));
        }
        if !seen.insert((entry.needle.as_str(), entry.prefix)) {
            return Err(format!(
                "{origin} [[service]] contains duplicate match {:?} with prefix={}",
                entry.needle, entry.prefix
            ));
        }
    }
    Ok(entries)
}

pub(crate) fn validate_remediation_file_for_test(raw: &str) -> Result<(), String> {
    parse_remediation_file(raw, "<test remediation.toml>").map(|_| ())
}

fn parse_remediation_file(raw: &str, origin: &str) -> Result<RemediationFile, String> {
    validate_remediation_keys(raw, origin)?;
    let parsed = toml::from_str::<RemediationFile>(raw)
        .map_err(|error| format!("failed to parse {origin}: {error}"))?;
    validate_remediation_file(&parsed, origin)?;
    Ok(parsed)
}

fn validate_remediation_keys(raw: &str, origin: &str) -> Result<(), String> {
    let value = toml::from_str::<toml::Value>(raw)
        .map_err(|error| format!("failed to parse {origin}: {error}"))?;
    let table = value
        .as_table()
        .ok_or_else(|| format!("{origin} must be a TOML table"))?;

    for key in table.keys() {
        if !matches!(key.as_str(), "detector" | "service" | "severity") {
            return Err(format!("{origin} contains unknown top-level table {key:?}"));
        }
    }

    validate_array_table_keys(
        table,
        "detector",
        &["id", "action", "revoke_url", "docs_url", "revoke_command"],
        origin,
    )?;
    validate_array_table_keys(
        table,
        "service",
        &[
            "match",
            "prefix",
            "action",
            "revoke_url",
            "docs_url",
            "revoke_command",
        ],
        origin,
    )?;
    validate_array_table_keys(
        table,
        "severity",
        &[
            "severity",
            "action",
            "revoke_url",
            "docs_url",
            "revoke_command",
        ],
        origin,
    )?;
    Ok(())
}

fn validate_array_table_keys(
    table: &toml::map::Map<String, toml::Value>,
    section: &str,
    allowed: &[&str],
    origin: &str,
) -> Result<(), String> {
    let Some(value) = table.get(section) else {
        return Ok(());
    };
    let rows = value
        .as_array()
        .ok_or_else(|| format!("{origin} [{section}] must be an array of tables"))?;
    for (index, row) in rows.iter().enumerate() {
        let row = row
            .as_table()
            .ok_or_else(|| format!("{origin} [[{section}]] row {index} must be a table"))?;
        for key in row.keys() {
            if !allowed.contains(&key.as_str()) {
                return Err(format!(
                    "{origin} [[{section}]] row {index} contains unknown field {key:?}"
                ));
            }
        }
    }
    Ok(())
}

fn validate_remediation_file(file: &RemediationFile, origin: &str) -> Result<(), String> {
    validate_detector_remediation(file, origin)?;
    validate_service_remediation(file, origin)?;
    validate_severity_remediation(file, origin)?;
    Ok(())
}

fn validate_detector_remediation(file: &RemediationFile, origin: &str) -> Result<(), String> {
    let detectors = crate::load_embedded_detectors_or_fail()
        .map_err(|error| format!("{origin} could not validate detector ids: {error}"))?;
    let detector_ids = detectors
        .iter()
        .map(|detector| detector.id.as_str())
        .collect::<BTreeSet<_>>();
    let mut seen = BTreeSet::new();
    for (index, entry) in file.detector.iter().enumerate() {
        validate_non_empty("detector", index, "id", &entry.id, origin)?;
        validate_fields("detector", index, &entry.fields, origin)?;
        if !detector_ids.contains(entry.id.as_str()) {
            return Err(format!(
                "{origin} [[detector]] row {index} references unknown detector id {:?}",
                entry.id
            ));
        }
        if !seen.insert(entry.id.as_str()) {
            return Err(format!(
                "{origin} [[detector]] contains duplicate detector id {:?}",
                entry.id
            ));
        }
    }
    Ok(())
}

fn validate_service_remediation(file: &RemediationFile, origin: &str) -> Result<(), String> {
    let mut seen = BTreeSet::new();
    for (index, entry) in file.service.iter().enumerate() {
        validate_non_empty("service", index, "match", &entry.needle, origin)?;
        validate_fields("service", index, &entry.fields, origin)?;
        let key = (entry.needle.as_str(), entry.prefix);
        if !seen.insert(key) {
            return Err(format!(
                "{origin} [[service]] contains duplicate match {:?} with prefix={}",
                entry.needle, entry.prefix
            ));
        }
    }
    Ok(())
}

fn validate_severity_remediation(file: &RemediationFile, origin: &str) -> Result<(), String> {
    let mut seen = BTreeSet::new();
    for (index, entry) in file.severity.iter().enumerate() {
        validate_non_empty("severity", index, "severity", &entry.severity, origin)?;
        validate_fields("severity", index, &entry.fields, origin)?;
        let severity = Severity::from_filter_label(&entry.severity).ok_or_else(|| {
            format!(
                "{origin} [[severity]] row {index} uses unknown severity {:?}; expected {}",
                entry.severity,
                Severity::FILTER_EXPECTED_LABELS
            )
        })?;
        if entry.severity.as_str() != severity.as_str() {
            return Err(format!(
                "{origin} [[severity]] row {index} must use canonical severity {:?}, got {:?}",
                severity.as_str(),
                entry.severity
            ));
        }
        if !seen.insert(severity) {
            return Err(format!(
                "{origin} [[severity]] contains duplicate severity {:?}",
                severity.as_str()
            ));
        }
    }
    for severity in Severity::ORDERED {
        if !seen.contains(&severity) {
            return Err(format!(
                "{origin} is missing [[severity]] fallback for {:?}",
                severity.as_str()
            ));
        }
    }
    Ok(())
}

fn validate_fields(
    section: &str,
    index: usize,
    fields: &RemediationFields,
    origin: &str,
) -> Result<(), String> {
    validate_non_empty(section, index, "action", &fields.action, origin)?;
    if let Some(url) = &fields.revoke_url {
        validate_non_empty(section, index, "revoke_url", url, origin)?;
    }
    if let Some(url) = &fields.docs_url {
        validate_non_empty(section, index, "docs_url", url, origin)?;
    }
    if let Some(command) = &fields.revoke_command {
        validate_non_empty(section, index, "revoke_command", command, origin)?;
    }
    Ok(())
}

fn validate_non_empty(
    section: &str,
    index: usize,
    field: &str,
    value: &str,
    origin: &str,
) -> Result<(), String> {
    if value.trim().is_empty() {
        return Err(format!(
            "{origin} [[{section}]] row {index} has empty {field}"
        ));
    }
    Ok(())
}

/// Map a detector's `service` string to a conventional environment-variable
/// name. Falls back to `<UPPER_SERVICE>_KEY` when the service isn't in the
/// curated [Tier-B map](../data/service-env-vars.toml).
///
/// The curated mappings follow community conventions (12-factor, common SDKs);
/// see `data/service-env-vars.toml` for the authoritative list.
pub(crate) fn env_var_name_for_service(service: &str) -> String {
    SERVICE_ENV_MAP
        .iter()
        .find(|entry| service_entry_matches(service, &entry.needle, entry.prefix))
        .map(|entry| entry.env.clone())
        // The default below is not an error fallback, it is the documented
        // `<SERVICE>_KEY` mapping for any service the curated Tier-B map does not
        // cover, always producing a deterministic, correct suggestion.
        .unwrap_or_else(|| service_to_screaming_snake(service)) // LAW10: documented default, not a failure path
}

fn service_to_screaming_snake(service: &str) -> String {
    let mut out = String::with_capacity(service.len() + 4);
    for ch in service.chars() {
        if ch.is_ascii_alphanumeric() {
            out.push(ch.to_ascii_uppercase());
        } else if !out.ends_with('_') {
            out.push('_');
        }
    }
    out.trim_matches('_').to_string() + "_KEY"
}

/// Render the `${ENV_VAR_NAME}` shell-interpolation replacement string for
/// a detector. Reporters embed this in their `fixes[]` output.
/// Return the recommended replacement text for a leaked credential (e.g., "${STRIPE_KEY}").
pub(crate) fn fix_replacement_text(service: &str) -> String {
    format!("${{{}}}", env_var_name_for_service(service))
}

pub(crate) fn remediation_for(detector_id: &str, service: &str, severity: Severity) -> Remediation {
    let data = &*REMEDIATION_MAP;
    if let Some(entry) = data
        .detector
        .iter()
        .find(|entry| entry.id.as_str() == detector_id)
    {
        return Remediation::from(&entry.fields);
    }

    if let Some(entry) = data
        .service
        .iter()
        .find(|entry| service_entry_matches(service, &entry.needle, entry.prefix))
    {
        return Remediation::from(&entry.fields);
    }

    // The severity table is the single owner of the no-detector/no-service-match
    // fallback. `SEVERITY_FALLBACKS` resolves it into a rank-indexed total array at
    // load, so this is an infallible index (`rank()` is `0..ORDERED.len()`) rather
    // than a fallible `find(...).expect(...)` on the load-guaranteed invariant.
    Remediation::from(&SEVERITY_FALLBACKS[severity.rank()])
}

fn service_entry_matches(service: &str, needle: &str, prefix: bool) -> bool {
    if prefix {
        crate::starts_with_ignore_ascii_case(service, needle)
    } else {
        crate::contains_ignore_ascii_case(service, needle)
    }
}