Skip to main content

action_gate_core/
secrets.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Bartek Kus
3//
4// The detector tables, token scan and entropy arithmetic are carried from
5// aicortex (crates/aicortex-gate/src/rules.rs and secrets.rs, commit a927f85,
6// aicortex spec 013), Apache-2.0, same copyright holder. See spec 001.
7
8//! The secret detector registry (spec 001).
9//!
10//! A pure, regex-free scan that answers *which* detector fired and *where*,
11//! never *what*: a [`Finding`] is a [`DetectorId`] and a byte offset, and
12//! nothing that reports one carries any part of the matched value (B-9).
13//!
14//! The prefix and armour detectors are data ([`PREFIX_RULES`],
15//! [`PEM_RULES`]): adding a credential shape is a table row and a golden
16//! vector, not a code path. The URL, JWT, entropy and assignment detectors are
17//! named constants with fixed logic.
18//!
19//! ```
20//! use action_gate_core::secrets::{self, SecretRules};
21//!
22//! let text = "the key is AKIA4QD7XZLM2VNBKTRW, rotate it";
23//! let finding = secrets::scan(text, &SecretRules::default()).expect("a credential");
24//! assert_eq!(finding.detector.as_str(), "aws-access-key-id");
25//! assert_eq!(finding.offset, 11);
26//! ```
27//!
28//! # What is scanned
29//!
30//! Exactly the text given: normalization (Unicode forms, bidirectional
31//! controls) is the consumer's, and offsets index the text as passed. Armour
32//! markers and the assignment rule read the whole text, because a PEM block
33//! spans lines and an assignment spans whitespace. Everything else reads
34//! *tokens*: maximal runs of characters that are neither whitespace nor one of
35//! the delimiters prose puts around a pasted value (B-4).
36
37use action_gate_types::{ActionContext, Check, Decision};
38
39/// The stable name of a detector, as a finding reports it and a vector records
40/// it (B-1). Once shipped, an id is never renamed or reused.
41#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
42pub struct DetectorId(&'static str);
43
44impl DetectorId {
45    /// Name a detector.
46    #[must_use]
47    pub const fn new(name: &'static str) -> Self {
48        Self(name)
49    }
50
51    /// The name, as it is reported and recorded.
52    #[must_use]
53    pub const fn as_str(self) -> &'static str {
54        self.0
55    }
56}
57
58impl core::fmt::Display for DetectorId {
59    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
60        f.write_str(self.0)
61    }
62}
63
64impl serde::Serialize for DetectorId {
65    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
66        serializer.serialize_str(self.0)
67    }
68}
69
70/// Which characters a credential's body is made of, so that a prefix match is
71/// not a match on prose that happens to start with the same letters.
72#[derive(Clone, Copy, Debug, PartialEq, Eq)]
73pub enum Charset {
74    /// `A-Z a-z 0-9`.
75    Alphanumeric,
76    /// `A-Z a-z 0-9 - _`, the base64url alphabet without padding.
77    Base64Url,
78    /// `A-Z a-z 0-9 + / = - _ .`, which is every token alphabet in use.
79    Token,
80}
81
82impl Charset {
83    /// Whether `character` belongs to this alphabet.
84    #[must_use]
85    pub const fn admits(self, character: char) -> bool {
86        match self {
87            Self::Alphanumeric => character.is_ascii_alphanumeric(),
88            Self::Base64Url => {
89                character.is_ascii_alphanumeric() || character == '-' || character == '_'
90            }
91            Self::Token => {
92                character.is_ascii_alphanumeric()
93                    || matches!(character, '+' | '/' | '=' | '-' | '_' | '.')
94            }
95        }
96    }
97
98    /// A stable name, used in [`SecretScanCheck`]'s config fingerprint.
99    #[must_use]
100    pub const fn as_str(self) -> &'static str {
101        match self {
102            Self::Alphanumeric => "alphanumeric",
103            Self::Base64Url => "base64url",
104            Self::Token => "token",
105        }
106    }
107}
108
109/// A credential recognised by the way it starts.
110#[derive(Clone, Copy, Debug, PartialEq, Eq)]
111pub struct PrefixRule {
112    /// What a finding names.
113    pub detector: DetectorId,
114    /// The literal the token begins with (case-sensitive).
115    pub prefix: &'static str,
116    /// How many characters of [`Self::charset`] must follow it. A prefix with
117    /// no length requirement matches the word "sky" and every sentence that
118    /// contains it.
119    pub min_tail: usize,
120    /// What those characters may be.
121    pub charset: Charset,
122}
123
124/// A private key recognised by its armour.
125#[derive(Clone, Copy, Debug, PartialEq, Eq)]
126pub struct PemRule {
127    /// What a finding names.
128    pub detector: DetectorId,
129    /// The armour line, matched as a substring anywhere in the text. A PEM
130    /// header is unambiguous: no prose contains one by accident.
131    pub marker: &'static str,
132}
133
134const fn prefix(
135    detector: &'static str,
136    prefix: &'static str,
137    min_tail: usize,
138    charset: Charset,
139) -> PrefixRule {
140    PrefixRule {
141        detector: DetectorId::new(detector),
142        prefix,
143        min_tail,
144        charset,
145    }
146}
147
148const fn pem(detector: &'static str, marker: &'static str) -> PemRule {
149    PemRule {
150        detector: DetectorId::new(detector),
151        marker,
152    }
153}
154
155/// The token shapes published by the systems whose credentials people paste.
156///
157/// Each row is a prefix, a minimum body length, and the alphabet that body is
158/// written in. The lengths are the published ones where a system publishes
159/// them and a conservative floor where it does not; they lean low, because a
160/// floor that is too high costs a leaked credential. Order matters where one
161/// prefix extends another: `sk-ant-` precedes `sk-`.
162pub const PREFIX_RULES: &[PrefixRule] = &[
163    prefix("anthropic-api-key", "sk-ant-", 24, Charset::Base64Url),
164    prefix("openai-api-key", "sk-", 20, Charset::Base64Url),
165    prefix("stripe-secret-key", "sk_live_", 16, Charset::Alphanumeric),
166    prefix(
167        "stripe-restricted-key",
168        "rk_live_",
169        16,
170        Charset::Alphanumeric,
171    ),
172    prefix("github-token", "ghp_", 36, Charset::Alphanumeric),
173    prefix("github-oauth-token", "gho_", 36, Charset::Alphanumeric),
174    prefix("github-user-token", "ghu_", 36, Charset::Alphanumeric),
175    prefix("github-server-token", "ghs_", 36, Charset::Alphanumeric),
176    prefix("github-refresh-token", "ghr_", 36, Charset::Alphanumeric),
177    prefix(
178        "github-fine-grained-token",
179        "github_pat_",
180        40,
181        Charset::Base64Url,
182    ),
183    prefix("gitlab-personal-token", "glpat-", 20, Charset::Base64Url),
184    prefix("slack-bot-token", "xoxb-", 24, Charset::Token),
185    prefix("slack-user-token", "xoxp-", 24, Charset::Token),
186    prefix("slack-app-token", "xapp-", 24, Charset::Token),
187    prefix("aws-access-key-id", "AKIA", 16, Charset::Alphanumeric),
188    prefix(
189        "aws-temporary-access-key-id",
190        "ASIA",
191        16,
192        Charset::Alphanumeric,
193    ),
194    prefix("google-api-key", "AIza", 35, Charset::Base64Url),
195    prefix("google-oauth-token", "ya29.", 32, Charset::Token),
196    prefix("npm-token", "npm_", 36, Charset::Alphanumeric),
197    prefix("digitalocean-token", "dop_v1_", 60, Charset::Alphanumeric),
198    prefix("sendgrid-api-key", "SG.", 32, Charset::Token),
199    prefix("huggingface-token", "hf_", 32, Charset::Alphanumeric),
200    prefix("shopify-access-token", "shpat_", 32, Charset::Alphanumeric),
201    prefix("supabase-service-key", "sbp_", 36, Charset::Alphanumeric),
202];
203
204/// The armour lines of the private-key formats.
205pub const PEM_RULES: &[PemRule] = &[
206    pem("pem-private-key", "-----BEGIN PRIVATE KEY-----"),
207    pem("pem-rsa-private-key", "-----BEGIN RSA PRIVATE KEY-----"),
208    pem("pem-ec-private-key", "-----BEGIN EC PRIVATE KEY-----"),
209    pem("pem-dsa-private-key", "-----BEGIN DSA PRIVATE KEY-----"),
210    pem(
211        "pem-encrypted-private-key",
212        "-----BEGIN ENCRYPTED PRIVATE KEY-----",
213    ),
214    pem("openssh-private-key", "-----BEGIN OPENSSH PRIVATE KEY-----"),
215    pem("pgp-private-key", "-----BEGIN PGP PRIVATE KEY BLOCK-----"),
216];
217
218/// The detector that reports a credential embedded in a URL's userinfo.
219pub const URL_CREDENTIAL: DetectorId = DetectorId::new("url-embedded-credential");
220
221/// The detector that reports a JSON Web Token.
222pub const JWT: DetectorId = DetectorId::new("json-web-token");
223
224/// The detector that reports an unbroken run of high entropy.
225pub const HIGH_ENTROPY: DetectorId = DetectorId::new("high-entropy-token");
226
227/// The detector that reports `api_key = <value>` style assignments (the rule
228/// action-gate 0.1.0's `SecretsCheck` carried as a regex).
229pub const CREDENTIAL_ASSIGNMENT: DetectorId = DetectorId::new("credential-assignment");
230
231/// The key names the assignment rule recognises, matched ASCII
232/// case-insensitively and without a word boundary, as 0.1.0's regex did.
233const ASSIGNMENT_KEYS: [&str; 5] = ["api_key", "api-key", "apikey", "secret", "token"];
234
235/// How many value characters an assignment needs to be a credential.
236const ASSIGNMENT_MIN_VALUE: usize = 24;
237
238/// How many fractional bits the entropy arithmetic carries.
239///
240/// Integer arithmetic in Q16 fixed point rather than floating point, so the
241/// same text yields the same finding on every target without an argument
242/// about rounding (B-8).
243pub const ENTROPY_FRACTION_BITS: u32 = 16;
244
245/// One whole bit, in the fixed point [`ENTROPY_FRACTION_BITS`] defines.
246pub const ENTROPY_ONE: u64 = 1 << ENTROPY_FRACTION_BITS;
247
248/// `whole.hundredths` bits per character, in Q16.
249#[must_use]
250pub const fn bits(whole: u64, hundredths: u64) -> u64 {
251    whole * ENTROPY_ONE + (hundredths * ENTROPY_ONE) / 100
252}
253
254/// The threshold detector: a long unbroken run whose Shannon entropy is above
255/// a configurable bound. All three fields are false-positive control.
256#[derive(Clone, Copy, Debug, PartialEq, Eq)]
257pub struct EntropyRule {
258    /// The shortest run considered at all. Below this, entropy per character
259    /// is noise.
260    pub min_len: usize,
261    /// Bits per character, in Q16, at or above which a run is a credential.
262    pub threshold: u64,
263    /// Whether a run must mix upper case, lower case and digits to be
264    /// considered. A hex digest, a ULID and a UUID each fail this and so are
265    /// never measured.
266    pub require_mixed_case_and_digit: bool,
267}
268
269impl EntropyRule {
270    /// The shipped threshold: 4.50 bits per character over at least 24
271    /// characters. A 40-character hex digest measures at most 4.00 by
272    /// construction; a random 32-byte secret in base64 measures about 5.50.
273    pub const STANDARD: Self = Self {
274        min_len: 24,
275        threshold: bits(4, 50),
276        require_mixed_case_and_digit: true,
277    };
278}
279
280impl Default for EntropyRule {
281    fn default() -> Self {
282        Self::STANDARD
283    }
284}
285
286/// Which detectors run, and how the threshold one is tuned (B-5).
287///
288/// `non_exhaustive` so a later detector toggle is not a breaking change: start
289/// from [`SecretRules::default`] and narrow field by field.
290#[derive(Clone, Debug, PartialEq, Eq)]
291#[non_exhaustive]
292pub struct SecretRules {
293    /// The prefix table. Defaults to [`PREFIX_RULES`].
294    pub prefixes: &'static [PrefixRule],
295    /// The armour table. Defaults to [`PEM_RULES`].
296    pub pem: &'static [PemRule],
297    /// Whether a credential in a URL's userinfo is a finding.
298    pub url_credentials: bool,
299    /// Whether a JSON Web Token is a finding.
300    pub json_web_tokens: bool,
301    /// Whether an `api_key = <value>` style assignment is a finding.
302    pub assignments: bool,
303    /// The threshold detector, or `None` to run only the patterns.
304    pub entropy: Option<EntropyRule>,
305}
306
307impl Default for SecretRules {
308    fn default() -> Self {
309        Self {
310            prefixes: PREFIX_RULES,
311            pem: PEM_RULES,
312            url_credentials: true,
313            json_web_tokens: true,
314            assignments: true,
315            entropy: Some(EntropyRule::STANDARD),
316        }
317    }
318}
319
320/// Every detector id the default rules can report, in table order (B-1).
321#[must_use]
322pub fn detector_ids() -> Vec<DetectorId> {
323    PREFIX_RULES
324        .iter()
325        .map(|rule| rule.detector)
326        .chain(PEM_RULES.iter().map(|rule| rule.detector))
327        .chain([URL_CREDENTIAL, JWT, HIGH_ENTROPY, CREDENTIAL_ASSIGNMENT])
328        .collect()
329}
330
331/// A detector's hit: which one, and where. Never the value (B-9).
332#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize)]
333#[non_exhaustive]
334pub struct Finding {
335    /// The detector that fired.
336    pub detector: DetectorId,
337    /// The byte offset into the scanned text, on a character boundary (B-7).
338    pub offset: usize,
339}
340
341/// The characters that end a token even though they are not whitespace.
342const DELIMITERS: [char; 16] = [
343    '"', '\'', '`', ',', ';', '(', ')', '[', ']', '{', '}', '<', '>', '|', '\\', '\u{feff}',
344];
345
346fn is_boundary(character: char) -> bool {
347    character.is_whitespace() || DELIMITERS.contains(&character)
348}
349
350/// The tokens of `text`, each with its byte offset.
351fn tokens(text: &str) -> impl Iterator<Item = (usize, &str)> {
352    let mut offset = 0usize;
353    core::iter::from_fn(move || {
354        let rest = text.get(offset..)?;
355        let start = offset + rest.find(|c: char| !is_boundary(c))?;
356        let tail = text.get(start..)?;
357        let len = tail.find(is_boundary).unwrap_or(tail.len());
358        offset = start + len;
359        tail.get(..len).map(|token| (start, token))
360    })
361}
362
363/// The first detector to fire on `text`, or `None` when nothing does (B-6).
364///
365/// The finding with the smallest offset wins; at equal offsets an armour
366/// marker beats a token detector, which beats the assignment rule.
367#[must_use]
368pub fn scan(text: &str, rules: &SecretRules) -> Option<Finding> {
369    let armour = rules
370        .pem
371        .iter()
372        .filter_map(|rule| {
373            text.find(rule.marker).map(|offset| Finding {
374                detector: rule.detector,
375                offset,
376            })
377        })
378        .min_by_key(|finding| finding.offset);
379
380    let token = tokens(text).find_map(|(offset, token)| {
381        prefix_match(token, rules.prefixes)
382            .or_else(|| {
383                rules
384                    .url_credentials
385                    .then(|| url_credential(token))
386                    .flatten()
387            })
388            .or_else(|| {
389                rules
390                    .json_web_tokens
391                    .then(|| json_web_token(token))
392                    .flatten()
393            })
394            .map(|detector| (detector, 0usize))
395            .or_else(|| rules.entropy.and_then(|rule| high_entropy(token, &rule)))
396            .map(|(detector, within)| Finding {
397                detector,
398                offset: offset.saturating_add(within),
399            })
400    });
401
402    let assignment = rules
403        .assignments
404        .then(|| assignment(text))
405        .flatten()
406        .map(|offset| Finding {
407            detector: CREDENTIAL_ASSIGNMENT,
408            offset,
409        });
410
411    // `min_by_key` keeps the first of equal minima, which is the precedence.
412    [armour, token, assignment]
413        .into_iter()
414        .flatten()
415        .min_by_key(|finding| finding.offset)
416}
417
418/// The prefix rule `token` satisfies, if any.
419fn prefix_match(token: &str, rules: &[PrefixRule]) -> Option<DetectorId> {
420    rules.iter().find_map(|rule| {
421        let tail = token.strip_prefix(rule.prefix)?;
422        let body: usize = tail.chars().take_while(|c| rule.charset.admits(*c)).count();
423        (body >= rule.min_tail).then_some(rule.detector)
424    })
425}
426
427/// Whether `token` is a URL whose userinfo carries a password:
428/// `scheme://user:secret@host`, with a non-empty password and host.
429fn url_credential(token: &str) -> Option<DetectorId> {
430    let after_scheme = token.split_once("://")?.1;
431    let authority = after_scheme.split('/').next()?;
432    let (userinfo, host) = authority.rsplit_once('@')?;
433    let (_, password) = userinfo.split_once(':')?;
434    let credible = !password.is_empty() && !host.is_empty() && !password.contains('@');
435    credible.then_some(URL_CREDENTIAL)
436}
437
438/// Whether `token` is a JSON Web Token: three base64url segments whose first
439/// decodes to a JSON object naming an algorithm or a type. The header decode
440/// is what separates a JWT from a dotted identifier.
441fn json_web_token(token: &str) -> Option<DetectorId> {
442    let mut parts = token.split('.');
443    let header = parts.next()?;
444    let payload = parts.next()?;
445    let signature = parts.next()?;
446    if parts.next().is_some() || header.is_empty() || payload.is_empty() {
447        return None;
448    }
449    let base64url =
450        |part: &str| !part.is_empty() && part.chars().all(|c| Charset::Base64Url.admits(c));
451    if !base64url(header) || !base64url(payload) || (!signature.is_empty() && !base64url(signature))
452    {
453        return None;
454    }
455    let decoded = base64url_decode(header)?;
456    let text = String::from_utf8(decoded).ok()?;
457    let object: serde_json::Value = serde_json::from_str(&text).ok()?;
458    let names_a_header = object
459        .as_object()
460        .is_some_and(|map| map.contains_key("alg") || map.contains_key("typ"));
461    names_a_header.then_some(JWT)
462}
463
464/// Decode unpadded base64url, or `None` when `part` is not base64url.
465fn base64url_decode(part: &str) -> Option<Vec<u8>> {
466    let mut out = Vec::with_capacity(part.len() * 3 / 4);
467    let mut accumulator: u32 = 0;
468    let mut bits: u32 = 0;
469    for character in part.chars() {
470        let value = match character {
471            'A'..='Z' => u32::from(character as u8 - b'A'),
472            'a'..='z' => u32::from(character as u8 - b'a') + 26,
473            '0'..='9' => u32::from(character as u8 - b'0') + 52,
474            '-' => 62,
475            '_' => 63,
476            _ => return None,
477        };
478        accumulator = (accumulator << 6) | value;
479        bits += 6;
480        if bits >= 8 {
481            bits -= 8;
482            let byte = u8::try_from((accumulator >> bits) & 0xff).ok()?;
483            out.push(byte);
484        }
485    }
486    Some(out)
487}
488
489/// The first high-entropy run inside `token`, and where it starts.
490///
491/// A *run* of token-alphabet characters rather than the whole token, so that
492/// punctuation glued onto a secret (`label:<secret>`, `token~<secret>`) cannot
493/// hide it (aicortex 013 D-12).
494fn high_entropy(token: &str, rule: &EntropyRule) -> Option<(DetectorId, usize)> {
495    let mut start = 0usize;
496    for run in token.split(|c: char| !Charset::Token.admits(c)) {
497        if is_high_entropy(run, rule) {
498            return Some((HIGH_ENTROPY, start));
499        }
500        // Past this run, then past the (possibly multi-byte) separator.
501        let after_run = start.saturating_add(run.len());
502        start = token
503            .get(after_run..)
504            .and_then(|rest| rest.chars().next())
505            .map_or(after_run, |sep| after_run.saturating_add(sep.len_utf8()));
506    }
507    None
508}
509
510fn is_high_entropy(run: &str, rule: &EntropyRule) -> bool {
511    if run.len() < rule.min_len {
512        return false;
513    }
514    if rule.require_mixed_case_and_digit {
515        let mixed = run.chars().any(|c| c.is_ascii_uppercase())
516            && run.chars().any(|c| c.is_ascii_lowercase())
517            && run.chars().any(|c| c.is_ascii_digit());
518        if !mixed {
519            return false;
520        }
521    }
522    shannon_bits(run) >= rule.threshold
523}
524
525/// The Shannon entropy of `token` in bits per character, in Q16 fixed point.
526///
527/// `H = log2(n) - (1/n) * sum(c_i * log2(c_i))`, written so that only one
528/// division is needed and every term is a non-negative integer.
529#[must_use]
530pub fn shannon_bits(token: &str) -> u64 {
531    let mut counts = [0u32; 256];
532    let mut total: u64 = 0;
533    for byte in token.bytes() {
534        if let Some(slot) = counts.get_mut(usize::from(byte)) {
535            *slot = slot.saturating_add(1);
536            total = total.saturating_add(1);
537        }
538    }
539    if total < 2 {
540        return 0;
541    }
542    let weighted: u64 = counts
543        .iter()
544        .filter(|count| **count > 0)
545        .map(|count| u64::from(*count).saturating_mul(log2_q16(u64::from(*count))))
546        .sum();
547    log2_q16(total).saturating_sub(weighted / total)
548}
549
550/// `log2(x)` in Q16 fixed point, for `x >= 1`, by repeated squaring of the
551/// mantissa.
552fn log2_q16(x: u64) -> u64 {
553    if x == 0 {
554        return 0;
555    }
556    let integer = u64::from(63 - x.leading_zeros());
557    let mut mantissa: u128 = if integer >= 32 {
558        u128::from(x) >> (integer - 32)
559    } else {
560        u128::from(x) << (32 - integer)
561    };
562    let mut fraction: u64 = 0;
563    for bit in 0..ENTROPY_FRACTION_BITS {
564        mantissa = (mantissa * mantissa) >> 32;
565        if mantissa >= (2u128 << 32) {
566            fraction |= 1 << (ENTROPY_FRACTION_BITS - 1 - bit);
567            mantissa >>= 1;
568        }
569    }
570    (integer << ENTROPY_FRACTION_BITS) | fraction
571}
572
573/// The offset of the first assigned value, if any: a key from
574/// [`ASSIGNMENT_KEYS`], optional whitespace, `:` or `=`, optional whitespace,
575/// an optional quote, then [`ASSIGNMENT_MIN_VALUE`] or more of
576/// `A-Z a-z 0-9 _ -`.
577fn assignment(text: &str) -> Option<usize> {
578    let bytes = text.as_bytes();
579    (0..bytes.len()).find_map(|start| {
580        ASSIGNMENT_KEYS.iter().find_map(|key| {
581            let end = start.checked_add(key.len())?;
582            // An ASCII-only match, so `start` and `end` are char boundaries.
583            let candidate = bytes.get(start..end)?;
584            if !candidate.eq_ignore_ascii_case(key.as_bytes()) {
585                return None;
586            }
587            assigned_value(text, end)
588        })
589    })
590}
591
592fn assigned_value(text: &str, after_key: usize) -> Option<usize> {
593    let rest = text.get(after_key..)?.trim_start();
594    let rest = rest.strip_prefix([':', '='])?.trim_start();
595    let value = rest.strip_prefix(['\'', '"']).unwrap_or(rest);
596    let len = value
597        .bytes()
598        .take_while(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-'))
599        .count();
600    (len >= ASSIGNMENT_MIN_VALUE).then(|| text.len() - value.len())
601}
602
603/// The golden vectors of spec 001 B-15, as JSON, for consumers asserting
604/// parity by vector id (feature `golden-vectors`).
605#[cfg(feature = "golden-vectors")]
606pub const GOLDEN_VECTORS: &str = include_str!("../testdata/secret-vectors.json");
607
608/// Denies when [`scan`] finds a credential in the payload, naming the detector,
609/// the field and the offset, never the value (B-9, B-10).
610///
611/// Blocking: a secret in the payload must stop the action regardless of any
612/// trust level. Needs no optional feature and no `regex`.
613#[derive(Clone, Debug, Default, PartialEq, Eq)]
614pub struct SecretScanCheck {
615    rules: SecretRules,
616}
617
618impl SecretScanCheck {
619    /// The check id, as it appears in a decision's `check_ids`.
620    pub const ID: &'static str = "secret-scan";
621
622    /// A scan check with custom rules.
623    #[must_use]
624    pub fn new(rules: SecretRules) -> Self {
625        Self { rules }
626    }
627
628    /// The rules this check scans with.
629    #[must_use]
630    pub fn rules(&self) -> &SecretRules {
631        &self.rules
632    }
633}
634
635impl Check for SecretScanCheck {
636    fn id(&self) -> &str {
637        Self::ID
638    }
639
640    fn evaluate(&self, ctx: &ActionContext) -> Option<Decision> {
641        let fields = [
642            ("summary", Some(ctx.payload_summary.as_str())),
643            ("body", ctx.payload_body.as_deref()),
644        ];
645        fields.into_iter().find_map(|(field, text)| {
646            let finding = scan(text?, &self.rules)?;
647            Some(
648                Decision::deny(
649                    format!(
650                        "gate:deny:secrets:{}:{field}:{}",
651                        finding.detector, finding.offset
652                    ),
653                    vec![Self::ID.into()],
654                )
655                .blocking(),
656            )
657        })
658    }
659
660    fn config_fingerprint(&self) -> String {
661        let prefixes: Vec<String> = self
662            .rules
663            .prefixes
664            .iter()
665            .map(|r| {
666                format!(
667                    "{}|{}|{}|{}",
668                    r.detector,
669                    r.prefix,
670                    r.min_tail,
671                    r.charset.as_str()
672                )
673            })
674            .collect();
675        let pem: Vec<String> = self
676            .rules
677            .pem
678            .iter()
679            .map(|r| format!("{}|{}", r.detector, r.marker))
680            .collect();
681        let entropy = self.rules.entropy.map_or_else(
682            || "none".to_owned(),
683            |e| {
684                format!(
685                    "{}|{}|{}",
686                    e.min_len, e.threshold, e.require_mixed_case_and_digit
687                )
688            },
689        );
690        format!(
691            "{}:v1;prefix=[{}];pem=[{}];url={};jwt={};assignment={};entropy={}",
692            Self::ID,
693            prefixes.join(","),
694            pem.join(","),
695            self.rules.url_credentials,
696            self.rules.json_web_tokens,
697            self.rules.assignments,
698            entropy
699        )
700    }
701}
702
703#[cfg(test)]
704mod tests {
705    use super::*;
706
707    fn detect(text: &str) -> Option<(&'static str, usize)> {
708        scan(text, &SecretRules::default()).map(|f| (f.detector.as_str(), f.offset))
709    }
710
711    #[test]
712    fn detector_ids_are_unique_and_complete() {
713        let ids = detector_ids();
714        let unique: std::collections::BTreeSet<_> = ids.iter().collect();
715        assert_eq!(unique.len(), ids.len(), "duplicate detector id");
716        assert_eq!(ids.len(), 24 + 7 + 4);
717    }
718
719    #[test]
720    fn assignment_reports_the_value_offset() {
721        let text = "config: api_key = 'abcdefghijklmnopqrstuvwxyz0123'";
722        assert_eq!(detect(text), Some(("credential-assignment", 19)));
723        assert_eq!(
724            detect("TOKEN:abcdefghijklmnopqrstuvwxyz"),
725            Some(("credential-assignment", 6))
726        );
727    }
728
729    #[test]
730    fn assignment_needs_a_long_value_and_an_operator() {
731        assert_eq!(detect("the token is abcdefghijklmnopqrstuvwxyz"), None);
732        assert_eq!(detect("secret = short"), None);
733        assert_eq!(detect("api key = abcdefghijklmnopqrstuvwxyz"), None);
734    }
735
736    #[test]
737    fn token_detector_wins_a_tie_with_assignment() {
738        let text = "token = ghp_RyIdydJp2Ys2SJ2jXUBATskPzpR6QTFGlbDtQ57k";
739        assert_eq!(detect(text), Some(("github-token", 8)));
740    }
741
742    #[test]
743    fn armour_wins_a_tie_and_earliest_offset_wins() {
744        let text = "x -----BEGIN PGP PRIVATE KEY BLOCK----- AKIA4QD7XZLM2VNBKTRW";
745        assert_eq!(detect(text), Some(("pgp-private-key", 2)));
746        let text = "AKIA4QD7XZLM2VNBKTRW -----BEGIN PRIVATE KEY-----";
747        assert_eq!(detect(text), Some(("aws-access-key-id", 0)));
748    }
749
750    #[test]
751    fn toggles_disable_their_detector() {
752        let rules = SecretRules {
753            assignments: false,
754            entropy: None,
755            ..SecretRules::default()
756        };
757        assert!(scan("secret=abcdefghijklmnopqrstuvwxyz", &rules).is_none());
758    }
759
760    #[test]
761    fn shannon_bits_matches_known_values() {
762        assert_eq!(shannon_bits(""), 0);
763        assert_eq!(shannon_bits("aaaa"), 0);
764        assert_eq!(shannon_bits("ab"), ENTROPY_ONE);
765        assert_eq!(shannon_bits("abcd"), 2 * ENTROPY_ONE);
766    }
767
768    #[test]
769    fn check_reason_names_detector_field_and_offset() {
770        let check = SecretScanCheck::default();
771        let ctx = ActionContext::new("write")
772            .with_summary("clean")
773            .with_body("key AKIA4QD7XZLM2VNBKTRW");
774        let d = check.evaluate(&ctx).expect("secret in body");
775        assert_eq!(d.reason, "gate:deny:secrets:aws-access-key-id:body:4");
776        assert_eq!(d.check_ids, vec!["secret-scan"]);
777        assert!(d.blocking);
778        assert!(check.evaluate(&ActionContext::new("write")).is_none());
779    }
780
781    #[test]
782    fn fingerprint_changes_with_the_rules() {
783        let rules = SecretRules {
784            json_web_tokens: false,
785            ..SecretRules::default()
786        };
787        assert_ne!(
788            SecretScanCheck::default().config_fingerprint(),
789            SecretScanCheck::new(rules).config_fingerprint()
790        );
791    }
792}