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//! `greengate: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 = crate::names::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            // A line still carrying the old pragma gets its fix in the same
236            // message. It names the pragma, never the line.
237            let hint = if line
238                .checked_sub(1)
239                .and_then(|i| text.lines().nth(i))
240                .is_some_and(|l| l.contains(crate::names::old::ALLOW_SECRET))
241            {
242                format!(
243                    "; `{}` no longer waives, use `{ALLOW}`",
244                    crate::names::old::ALLOW_SECRET
245                )
246            } else {
247                String::new()
248            };
249            Finding::new(
250                NAME,
251                crate::ui::sanitize(file),
252                Severity::Block,
253                format!(
254                    "{} — unstage it; once pushed it is not history, it is an incident{hint}",
255                    kind.name()
256                ),
257            )
258            .at_line(line)
259        })
260        .collect()
261}
262
263/// Is this worth reading as text at all? git's own binary heuristic, plus the
264/// per-file ceiling. Shared so `greengate check` skips exactly what the hook skips.
265pub fn is_scannable(bytes: &[u8]) -> bool {
266    !looks_binary(bytes) && bytes.len() <= MAX_BYTES
267}
268
269/// pre-commit: the staged content. Under the staged-only hold the working
270/// tree IS the commit's content, so reading the files is reading the stage.
271pub fn staged(settings: &crate::config::Settings) -> Outcome {
272    let files = common::staged_files(&[]);
273    let root = common::repo_root();
274    let mut found = false;
275    for f in &files {
276        let path = std::path::Path::new(&root).join(f);
277        let Ok(bytes) = std::fs::read(&path) else {
278            continue; // deleted or unreadable: nothing staged to leak
279        };
280        if !is_scannable(&bytes) {
281            continue;
282        }
283        let text = String::from_utf8_lossy(&bytes);
284        for finding in findings(f, &text) {
285            found = true;
286            common::fail(&format!(
287                "secrets: {} — {}",
288                finding.location(),
289                finding.message
290            ));
291        }
292    }
293    if found {
294        return Outcome::Failed;
295    }
296    common::ok(settings, "No secrets staged");
297    Outcome::Passed
298}
299
300/// pre-push: every line every pushed commit ADDS — the last moment a
301/// secret is recoverable at all. `--no-verify` skipped the commit half;
302/// it does not skip this one.
303pub fn pushed(settings: &crate::config::Settings, refs: &[PushRef]) -> Outcome {
304    let zero = crate::git::stdout(&["hash-object", "--stdin"])
305        .map(|h| "0".repeat(h.len()))
306        .unwrap_or_else(|| "0".repeat(40));
307    let mut found = false;
308    let mut checked_any_ref = false;
309    for r in refs {
310        if r.local_oid == zero {
311            continue; // deleting a ref pushes no content
312        }
313        let commits: Vec<String> = crate::pushrefs::commits_and_files_for(r, &zero)
314            .into_iter()
315            .map(|(c, _)| c)
316            .collect();
317        if commits.is_empty() && r.remote_oid != zero {
318            // An up-to-date or forced-same push; nothing new leaves.
319            continue;
320        }
321        checked_any_ref = true;
322        for commit in &commits {
323            let Some(diff) = crate::git::stdout(&["show", "--no-color", "--format=", commit])
324            else {
325                common::warn(
326                    "secrets: git would not show a pushed commit — the push was \
327                     NOT fully scanned",
328                );
329                return Outcome::Unavailable;
330            };
331            let mut file = String::from("?");
332            for line in diff.lines() {
333                if let Some(rest) = line.strip_prefix("+++ b/") {
334                    file = rest.to_string();
335                    continue;
336                }
337                let Some(added) = line.strip_prefix('+') else {
338                    continue;
339                };
340                if let Some(kind) = sniff(added) {
341                    found = true;
342                    common::fail(&format!(
343                        "secrets: {} added by commit {} in {} — this push would \
344                         publish it; rewrite the history first (the secret may \
345                         already need rotating)",
346                        kind.name(),
347                        &commit[..commit.len().min(12)],
348                        crate::ui::sanitize(&file),
349                    ));
350                }
351            }
352        }
353    }
354    if found {
355        return Outcome::Failed;
356    }
357    let _ = checked_any_ref; // a push of nothing is a clean push
358    common::ok(settings, "No secrets in the pushed commits");
359    Outcome::Passed
360}
361
362#[cfg(test)]
363mod tests {
364    use super::*;
365
366    /// Fixtures are ASSEMBLED so this file never contains a contiguous
367    /// secret shape — the same trick the shipped patterns use.
368    fn pem() -> String {
369        format!("{}{} RSA {}{}", "-----", "BEGIN", "PRIVATE", " KEY-----")
370    }
371    fn aws() -> String {
372        format!("{}{}{}", "AK", "IA", "IOSFODNN7EXAMPLE")
373    }
374    fn gh() -> String {
375        format!("{}{}{}", "gh", "p_", "a".repeat(36))
376    }
377    /// A Vault service token at its real length — ~90 characters of base62.
378    fn vault() -> String {
379        format!("{}{}{}", "hv", "s.", "CAESI".to_owned() + &"x".repeat(90))
380    }
381
382    #[test]
383    fn the_known_shapes_are_recognised() {
384        assert_eq!(sniff(&pem()), Some(Kind::PrivateKey));
385        assert_eq!(
386            sniff(&format!("key = {}", aws())),
387            Some(Kind::AwsAccessKeyId)
388        );
389        assert_eq!(sniff(&format!("token: {}", gh())), Some(Kind::GithubToken));
390        assert_eq!(
391            sniff(&format!("SLACK={}{}", "xox", "b-1234567890-abc")),
392            Some(Kind::SlackToken)
393        );
394        assert_eq!(
395            sniff(&format!("{}{}", "AI", "za".to_owned() + &"D".repeat(35))),
396            Some(Kind::GoogleApiKey)
397        );
398        assert_eq!(
399            sniff(&format!("{}{}{}", "sk_", "live_", "a".repeat(24))),
400            Some(Kind::StripeLiveKey)
401        );
402        assert_eq!(
403            sniff(&format!(
404                "{}{}{}",
405                "sk-",
406                "ant-",
407                "api03-".to_owned() + &"x".repeat(20)
408            )),
409            Some(Kind::ApiKey)
410        );
411        assert_eq!(
412            sniff(&format!("VAULT_TOKEN={}", vault())),
413            Some(Kind::VaultToken)
414        );
415        // Batch and recovery tokens share the shape and the sensitivity.
416        for p in ["hv", "hv"].iter().zip(["b.", "r."]) {
417            assert_eq!(
418                sniff(&format!("{}{}{}", p.0, p.1, "y".repeat(80))),
419                Some(Kind::VaultToken)
420            );
421        }
422    }
423
424    /// The shapes are shapes, not prefixes: too short, wrong charset, or
425    /// glued to a longer word is prose, not a credential.
426    #[test]
427    fn lookalikes_are_left_alone() {
428        assert_eq!(sniff("AKIAI is the prefix"), None); // too short
429        assert_eq!(sniff(&format!("X{}", aws())), None); // no boundary before
430        assert_eq!(sniff("ghp_short"), None);
431        assert_eq!(sniff("the sk-1234 identifier"), None); // bare sk- is not gated
432                                                           // Stripe TEST keys are designed to be committed — and assembled
433                                                           // here, because GitHub's own push protection flags the contiguous
434                                                           // spelling even inside the test that proves we ignore it.
435        assert_eq!(
436            sniff(&format!("{}{}{}", "sk_", "test_", "a".repeat(24))),
437            None
438        );
439        assert_eq!(sniff("xoxb- alone"), None);
440        assert_eq!(sniff(""), None);
441        // Vault lookalikes, every one of them lifted from a real homelab
442        // rather than invented: a prefix constant, a placeholder, a doc
443        // string, and the longest test fixture found anywhere (29 chars of
444        // token run, against a floor of 40).
445        assert_eq!(
446            sniff(&format!(
447                r#"validPrefixes := []string{{"{}{}"}}"#,
448                "hv", "s."
449            )),
450            None
451        );
452        assert_eq!(
453            sniff(&format!("echo {}{}XXXXX | bootstrap recover", "hv", "s.")),
454            None
455        );
456        assert_eq!(
457            sniff(&format!(
458                "expected {}{}* / {}{}* prefix",
459                "hv", "s.", "hv", "b."
460            )),
461            None
462        );
463        assert_eq!(
464            sniff(&format!(
465                "{}{}{}",
466                "hv", "s.", "CAESID8u5XM-oKyEbaXCUXmzQxWmb"
467            )),
468            None
469        );
470        // The legacy bare forms must never gate — this is a method call.
471        assert_eq!(
472            sniff("return s.Validate(ctx, token, opts, logger, cfg)"),
473            None
474        );
475    }
476
477    /// The pragma is the surgical opt-out — same line, visible in review.
478    #[test]
479    fn the_allow_pragma_skips_the_line() {
480        let line = format!("{} // {}", aws(), ALLOW);
481        assert_eq!(sniff(&line), None);
482    }
483
484    /// The check must survive its own repository: the shipped source
485    /// assembles every pattern, so scanning this very file finds nothing.
486    #[test]
487    fn the_scanner_does_not_flag_its_own_source() {
488        let own = include_str!("secrets.rs");
489        assert!(
490            scan(own).is_empty(),
491            "the scanner flagged its own source: {:?}",
492            scan(own)
493        );
494    }
495
496    /// A NUL says binary, and binary is out of scope.
497    #[test]
498    fn binary_content_is_skipped() {
499        assert!(looks_binary(b"\x00PNG"));
500        assert!(!looks_binary(b"just text"));
501    }
502
503    /// Line numbers are 1-based and every finding is kept.
504    #[test]
505    fn scan_reports_each_line_once() {
506        let text = format!("clean\n{}\nclean\n{}\n", pem(), aws());
507        let hits = scan(&text);
508        assert_eq!(hits.len(), 2);
509        assert_eq!(hits[0], (2, Kind::PrivateKey));
510        assert_eq!(hits[1], (4, Kind::AwsAccessKeyId));
511    }
512}