Skip to main content

greengate_runtime/hooks/
secrets.rs

1//! Secrets never leave the machine — caught at commit, and again at push.
2//!
3//! The severity-matches-irreversibility argument at its most extreme. A
4//! staged credential is a ten-second fix: unstage it. A PUSHED credential
5//! is not a history problem, it is an incident — the secret is compromised
6//! the moment it leaves the machine, and the remedy stops being `git
7//! commit --amend` and becomes rotation. So this check has two halves:
8//!
9//! - **pre-commit** scans the STAGED content (which, under the staged-only
10//!   hold, is exactly what the working tree holds) and blocks;
11//! - **pre-push** scans the content every pushed commit ADDS — including
12//!   commits made with `--no-verify`, from other tools, or three commits
13//!   ago — because the push is the boundary that cannot be taken back.
14//!
15//! Detection is a curated set of literal token shapes, not entropy: private
16//! key headers, cloud access key ids, the well-known API token prefixes.
17//! Entropy heuristics are where secret scanners get noisy, and a noisy
18//! blocker is a blocker people learn to delete. A line that is a KNOWN
19//! false positive (a test fixture, documentation) opts out with the pragma
20//! `amont:allow-secret` on the same line — visible in review, greppable,
21//! and narrower than skipping the whole check.
22//!
23//! Findings are REDACTED: the report names the kind and the place, never
24//! the matched text. A hook that echoes a secret into scrollback (and into
25//! CI logs, and into anything recording the terminal) has widened the leak
26//! it exists to prevent.
27//!
28//! The token shapes below are assembled with `concat!` so this source file
29//! never contains a contiguous matchable pattern — the check must survive
30//! scanning its own repository (see `the_scanner_does_not_flag_its_own_source`).
31
32use crate::check::{Outcome, Severity};
33use crate::finding::Finding;
34use crate::pushrefs::PushRef;
35
36use super::common;
37
38/// Skip lines carrying this pragma — the surgical opt-out for fixtures.
39const ALLOW: &str = "amont:allow-secret";
40
41/// Per-file ceiling: a secret in the first two megabytes is a secret found,
42/// and a generated bundle beyond it is noise this check has no business in.
43const MAX_BYTES: usize = 2 * 1024 * 1024;
44
45/// What was found — the KIND is all the report ever says about it.
46#[derive(Debug, Clone, Copy, PartialEq, Eq)]
47pub(crate) enum Kind {
48    PrivateKey,
49    AwsAccessKeyId,
50    GithubToken,
51    SlackToken,
52    GoogleApiKey,
53    StripeLiveKey,
54    NpmToken,
55    ApiKey,
56    VaultToken,
57}
58
59impl Kind {
60    fn name(self) -> &'static str {
61        match self {
62            Kind::PrivateKey => "a private key",
63            Kind::AwsAccessKeyId => "an AWS access key id",
64            Kind::GithubToken => "a GitHub token",
65            Kind::SlackToken => "a Slack token",
66            Kind::GoogleApiKey => "a Google API key",
67            Kind::StripeLiveKey => "a Stripe live key",
68            Kind::NpmToken => "an npm token",
69            Kind::ApiKey => "an API key",
70            Kind::VaultToken => "a Vault token",
71        }
72    }
73}
74
75fn is_token_char(b: u8) -> bool {
76    b.is_ascii_alphanumeric() || b == b'_' || b == b'-'
77}
78
79/// At least `n` token characters follow `text[at..]`.
80fn token_run(text: &str, at: usize, n: usize) -> bool {
81    text.as_bytes()[at..]
82        .iter()
83        .take_while(|b| is_token_char(**b))
84        .count()
85        >= n
86}
87
88/// The byte before a match must not itself be a token character — `XAKIA…`
89/// is part of some longer word, not a key id.
90fn boundary_before(text: &str, at: usize) -> bool {
91    at == 0 || !is_token_char(text.as_bytes()[at - 1])
92}
93
94/// Every occurrence of `prefix` followed by ≥ `min` token characters.
95fn has_prefixed_token(line: &str, prefix: &str, min: usize) -> bool {
96    let mut from = 0;
97    while let Some(i) = line[from..].find(prefix) {
98        let at = from + i;
99        if boundary_before(line, at) && token_run(line, at + prefix.len(), min) {
100            return true;
101        }
102        from = at + prefix.len();
103    }
104    false
105}
106
107/// What this line carries, if anything. Pure — the whole detector is this
108/// function, and the tests drive it directly.
109pub(crate) fn sniff(line: &str) -> Option<Kind> {
110    if line.contains(ALLOW) {
111        return None;
112    }
113    // The PEM header: a BEGIN marker and the private-key tail on one
114    // line. RSA, EC, DSA, OPENSSH, PGP, and the bare form all share it.
115    // (Spelled via concat! so this file cannot flag itself — comments
116    // included, since a secret in a comment is still a secret.)
117    if line.contains(concat!("-----", "BEGIN ")) && line.contains(concat!("PRIVATE", " KEY-----")) {
118        return Some(Kind::PrivateKey);
119    }
120    // AWS access key ids: AKIA (long-term) / ASIA (temporary) + 16 more.
121    for p in [concat!("AK", "IA"), concat!("AS", "IA")] {
122        let mut from = 0;
123        while let Some(i) = line[from..].find(p) {
124            let at = from + i;
125            let rest = &line.as_bytes()[at + 4..];
126            if boundary_before(line, at)
127                && rest.len() >= 16
128                && rest[..16]
129                    .iter()
130                    .all(|b| b.is_ascii_uppercase() || b.is_ascii_digit())
131            {
132                return Some(Kind::AwsAccessKeyId);
133            }
134            from = at + 4;
135        }
136    }
137    // GitHub: classic ghp_/gho_/ghu_/ghs_/ghr_ + 36, fine-grained
138    // github_pat_ + a long tail.
139    for p in [
140        concat!("gh", "p_"),
141        concat!("gh", "o_"),
142        concat!("gh", "u_"),
143        concat!("gh", "s_"),
144        concat!("gh", "r_"),
145    ] {
146        if has_prefixed_token(line, p, 36) {
147            return Some(Kind::GithubToken);
148        }
149    }
150    if has_prefixed_token(line, concat!("github_", "pat_"), 60) {
151        return Some(Kind::GithubToken);
152    }
153    // Slack: xoxb-/xoxp-/xoxa-/xoxr-/xoxs- + a real tail.
154    for p in [
155        concat!("xox", "b-"),
156        concat!("xox", "p-"),
157        concat!("xox", "a-"),
158        concat!("xox", "r-"),
159        concat!("xox", "s-"),
160    ] {
161        if has_prefixed_token(line, p, 10) {
162            return Some(Kind::SlackToken);
163        }
164    }
165    // Google API keys are AIza + exactly 35 more; ≥ 30 keeps rotated
166    // variants without matching prose.
167    if has_prefixed_token(line, concat!("AI", "za"), 30) {
168        return Some(Kind::GoogleApiKey);
169    }
170    // Stripe LIVE keys only — sk_test_ is designed to be committed.
171    for p in [concat!("sk_", "live_"), concat!("rk_", "live_")] {
172        if has_prefixed_token(line, p, 20) {
173            return Some(Kind::StripeLiveKey);
174        }
175    }
176    if has_prefixed_token(line, concat!("np", "m_"), 36) {
177        return Some(Kind::NpmToken);
178    }
179    // OpenAI / Anthropic project and API keys. The bare `sk-` prefix is
180    // too common in ordinary identifiers to gate on; the vendored forms
181    // are unambiguous.
182    for p in [concat!("sk-", "proj-"), concat!("sk-", "ant-")] {
183        if has_prefixed_token(line, p, 20) {
184            return Some(Kind::ApiKey);
185        }
186    }
187    // Vault 1.10+: hvs. service, hvb. batch, hvr. recovery. Real tokens run
188    // ~90 characters; 40 is the floor because a repository that TALKS about
189    // Vault is full of shorter lookalikes — placeholders, prefix constants,
190    // `strings.HasPrefix(t, "hvs.")`, and test fixtures. The longest such
191    // run measured across a live homelab was 29.
192    //
193    // The legacy bare `s.` / `b.` / `r.` forms are deliberately NOT gated:
194    // `s.` matches a method call on any receiver named `s`, which is most
195    // Go files ever written.
196    for p in [
197        concat!("hv", "s."),
198        concat!("hv", "b."),
199        concat!("hv", "r."),
200    ] {
201        if has_prefixed_token(line, p, 40) {
202            return Some(Kind::VaultToken);
203        }
204    }
205    None
206}
207
208/// git's own binary heuristic: a NUL in the first 8000 bytes.
209fn looks_binary(bytes: &[u8]) -> bool {
210    bytes.iter().take(8000).any(|b| *b == 0)
211}
212
213/// Scan one text, collecting redacted findings as `(line-number, kind)`.
214fn scan(text: &str) -> Vec<(usize, Kind)> {
215    text.lines()
216        .enumerate()
217        .filter_map(|(i, line)| sniff(line).map(|k| (i + 1, k)))
218        .collect()
219}
220
221/// The check's own short name, and the `check` field of every finding it makes.
222pub const NAME: &str = "secrets";
223
224/// Findings for one file's text. PURE — no git, no filesystem.
225///
226/// The message names the KIND and nothing else. A report that echoed the
227/// matched text would be the leak this check exists to prevent, and would
228/// copy it into terminal scrollback, CI logs and editor diagnostics on the
229/// way. `Finding::message` is printed verbatim by everything downstream, so
230/// this is the boundary where that rule has to hold.
231pub fn findings(file: &str, text: &str) -> Vec<Finding> {
232    scan(text)
233        .into_iter()
234        .map(|(line, kind)| {
235            Finding::new(
236                NAME,
237                crate::ui::sanitize(file),
238                Severity::Block,
239                format!(
240                    "{} — unstage it; once pushed it is not history, it is an incident",
241                    kind.name()
242                ),
243            )
244            .at_line(line)
245        })
246        .collect()
247}
248
249/// Is this worth reading as text at all? git's own binary heuristic, plus the
250/// per-file ceiling. Shared so `amont check` skips exactly what the hook skips.
251pub fn is_scannable(bytes: &[u8]) -> bool {
252    !looks_binary(bytes) && bytes.len() <= MAX_BYTES
253}
254
255/// pre-commit: the staged content. Under the staged-only hold the working
256/// tree IS the commit's content, so reading the files is reading the stage.
257pub fn staged(settings: &crate::config::Settings) -> Outcome {
258    let files = common::staged_files(&[]);
259    let root = common::repo_root();
260    let mut found = false;
261    for f in &files {
262        let path = std::path::Path::new(&root).join(f);
263        let Ok(bytes) = std::fs::read(&path) else {
264            continue; // deleted or unreadable: nothing staged to leak
265        };
266        if !is_scannable(&bytes) {
267            continue;
268        }
269        let text = String::from_utf8_lossy(&bytes);
270        for finding in findings(f, &text) {
271            found = true;
272            common::fail(&format!(
273                "secrets: {} — {}",
274                finding.location(),
275                finding.message
276            ));
277        }
278    }
279    if found {
280        return Outcome::Failed;
281    }
282    common::ok(settings, "No secrets staged");
283    Outcome::Passed
284}
285
286/// pre-push: every line every pushed commit ADDS — the last moment a
287/// secret is recoverable at all. `--no-verify` skipped the commit half;
288/// it does not skip this one.
289pub fn pushed(settings: &crate::config::Settings, refs: &[PushRef]) -> Outcome {
290    let zero = crate::git::stdout(&["hash-object", "--stdin"])
291        .map(|h| "0".repeat(h.len()))
292        .unwrap_or_else(|| "0".repeat(40));
293    let mut found = false;
294    let mut checked_any_ref = false;
295    for r in refs {
296        if r.local_oid == zero {
297            continue; // deleting a ref pushes no content
298        }
299        let commits: Vec<String> = crate::pushrefs::commits_and_files_for(r, &zero)
300            .into_iter()
301            .map(|(c, _)| c)
302            .collect();
303        if commits.is_empty() && r.remote_oid != zero {
304            // An up-to-date or forced-same push; nothing new leaves.
305            continue;
306        }
307        checked_any_ref = true;
308        for commit in &commits {
309            let Some(diff) = crate::git::stdout(&["show", "--no-color", "--format=", commit])
310            else {
311                common::warn(
312                    "secrets: git would not show a pushed commit — the push was \
313                     NOT fully scanned",
314                );
315                return Outcome::Unavailable;
316            };
317            let mut file = String::from("?");
318            for line in diff.lines() {
319                if let Some(rest) = line.strip_prefix("+++ b/") {
320                    file = rest.to_string();
321                    continue;
322                }
323                let Some(added) = line.strip_prefix('+') else {
324                    continue;
325                };
326                if let Some(kind) = sniff(added) {
327                    found = true;
328                    common::fail(&format!(
329                        "secrets: {} added by commit {} in {} — this push would \
330                         publish it; rewrite the history first (the secret may \
331                         already need rotating)",
332                        kind.name(),
333                        &commit[..commit.len().min(12)],
334                        crate::ui::sanitize(&file),
335                    ));
336                }
337            }
338        }
339    }
340    if found {
341        return Outcome::Failed;
342    }
343    let _ = checked_any_ref; // a push of nothing is a clean push
344    common::ok(settings, "No secrets in the pushed commits");
345    Outcome::Passed
346}
347
348#[cfg(test)]
349mod tests {
350    use super::*;
351
352    /// Fixtures are ASSEMBLED so this file never contains a contiguous
353    /// secret shape — the same trick the shipped patterns use.
354    fn pem() -> String {
355        format!("{}{} RSA {}{}", "-----", "BEGIN", "PRIVATE", " KEY-----")
356    }
357    fn aws() -> String {
358        format!("{}{}{}", "AK", "IA", "IOSFODNN7EXAMPLE")
359    }
360    fn gh() -> String {
361        format!("{}{}{}", "gh", "p_", "a".repeat(36))
362    }
363    /// A Vault service token at its real length — ~90 characters of base62.
364    fn vault() -> String {
365        format!("{}{}{}", "hv", "s.", "CAESI".to_owned() + &"x".repeat(90))
366    }
367
368    #[test]
369    fn the_known_shapes_are_recognised() {
370        assert_eq!(sniff(&pem()), Some(Kind::PrivateKey));
371        assert_eq!(
372            sniff(&format!("key = {}", aws())),
373            Some(Kind::AwsAccessKeyId)
374        );
375        assert_eq!(sniff(&format!("token: {}", gh())), Some(Kind::GithubToken));
376        assert_eq!(
377            sniff(&format!("SLACK={}{}", "xox", "b-1234567890-abc")),
378            Some(Kind::SlackToken)
379        );
380        assert_eq!(
381            sniff(&format!("{}{}", "AI", "za".to_owned() + &"D".repeat(35))),
382            Some(Kind::GoogleApiKey)
383        );
384        assert_eq!(
385            sniff(&format!("{}{}{}", "sk_", "live_", "a".repeat(24))),
386            Some(Kind::StripeLiveKey)
387        );
388        assert_eq!(
389            sniff(&format!(
390                "{}{}{}",
391                "sk-",
392                "ant-",
393                "api03-".to_owned() + &"x".repeat(20)
394            )),
395            Some(Kind::ApiKey)
396        );
397        assert_eq!(
398            sniff(&format!("VAULT_TOKEN={}", vault())),
399            Some(Kind::VaultToken)
400        );
401        // Batch and recovery tokens share the shape and the sensitivity.
402        for p in ["hv", "hv"].iter().zip(["b.", "r."]) {
403            assert_eq!(
404                sniff(&format!("{}{}{}", p.0, p.1, "y".repeat(80))),
405                Some(Kind::VaultToken)
406            );
407        }
408    }
409
410    /// The shapes are shapes, not prefixes: too short, wrong charset, or
411    /// glued to a longer word is prose, not a credential.
412    #[test]
413    fn lookalikes_are_left_alone() {
414        assert_eq!(sniff("AKIAI is the prefix"), None); // too short
415        assert_eq!(sniff(&format!("X{}", aws())), None); // no boundary before
416        assert_eq!(sniff("ghp_short"), None);
417        assert_eq!(sniff("the sk-1234 identifier"), None); // bare sk- is not gated
418                                                           // Stripe TEST keys are designed to be committed — and assembled
419                                                           // here, because GitHub's own push protection flags the contiguous
420                                                           // spelling even inside the test that proves we ignore it.
421        assert_eq!(
422            sniff(&format!("{}{}{}", "sk_", "test_", "a".repeat(24))),
423            None
424        );
425        assert_eq!(sniff("xoxb- alone"), None);
426        assert_eq!(sniff(""), None);
427        // Vault lookalikes, every one of them lifted from a real homelab
428        // rather than invented: a prefix constant, a placeholder, a doc
429        // string, and the longest test fixture found anywhere (29 chars of
430        // token run, against a floor of 40).
431        assert_eq!(
432            sniff(&format!(
433                r#"validPrefixes := []string{{"{}{}"}}"#,
434                "hv", "s."
435            )),
436            None
437        );
438        assert_eq!(
439            sniff(&format!("echo {}{}XXXXX | bootstrap recover", "hv", "s.")),
440            None
441        );
442        assert_eq!(
443            sniff(&format!(
444                "expected {}{}* / {}{}* prefix",
445                "hv", "s.", "hv", "b."
446            )),
447            None
448        );
449        assert_eq!(
450            sniff(&format!(
451                "{}{}{}",
452                "hv", "s.", "CAESID8u5XM-oKyEbaXCUXmzQxWmb"
453            )),
454            None
455        );
456        // The legacy bare forms must never gate — this is a method call.
457        assert_eq!(
458            sniff("return s.Validate(ctx, token, opts, logger, cfg)"),
459            None
460        );
461    }
462
463    /// The pragma is the surgical opt-out — same line, visible in review.
464    #[test]
465    fn the_allow_pragma_skips_the_line() {
466        let line = format!("{} // {}", aws(), ALLOW);
467        assert_eq!(sniff(&line), None);
468    }
469
470    /// The check must survive its own repository: the shipped source
471    /// assembles every pattern, so scanning this very file finds nothing.
472    #[test]
473    fn the_scanner_does_not_flag_its_own_source() {
474        let own = include_str!("secrets.rs");
475        assert!(
476            scan(own).is_empty(),
477            "the scanner flagged its own source: {:?}",
478            scan(own)
479        );
480    }
481
482    /// A NUL says binary, and binary is out of scope.
483    #[test]
484    fn binary_content_is_skipped() {
485        assert!(looks_binary(b"\x00PNG"));
486        assert!(!looks_binary(b"just text"));
487    }
488
489    /// Line numbers are 1-based and every finding is kept.
490    #[test]
491    fn scan_reports_each_line_once() {
492        let text = format!("clean\n{}\nclean\n{}\n", pem(), aws());
493        let hits = scan(&text);
494        assert_eq!(hits.len(), 2);
495        assert_eq!(hits[0], (2, Kind::PrivateKey));
496        assert_eq!(hits[1], (4, Kind::AwsAccessKeyId));
497    }
498}