use action_gate_types::{ActionContext, Check, Decision};
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct DetectorId(&'static str);
impl DetectorId {
#[must_use]
pub const fn new(name: &'static str) -> Self {
Self(name)
}
#[must_use]
pub const fn as_str(self) -> &'static str {
self.0
}
}
impl core::fmt::Display for DetectorId {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str(self.0)
}
}
impl serde::Serialize for DetectorId {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(self.0)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Charset {
Alphanumeric,
Base64Url,
Token,
}
impl Charset {
#[must_use]
pub const fn admits(self, character: char) -> bool {
match self {
Self::Alphanumeric => character.is_ascii_alphanumeric(),
Self::Base64Url => {
character.is_ascii_alphanumeric() || character == '-' || character == '_'
}
Self::Token => {
character.is_ascii_alphanumeric()
|| matches!(character, '+' | '/' | '=' | '-' | '_' | '.')
}
}
}
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Alphanumeric => "alphanumeric",
Self::Base64Url => "base64url",
Self::Token => "token",
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PrefixRule {
pub detector: DetectorId,
pub prefix: &'static str,
pub min_tail: usize,
pub charset: Charset,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PemRule {
pub detector: DetectorId,
pub marker: &'static str,
}
const fn prefix(
detector: &'static str,
prefix: &'static str,
min_tail: usize,
charset: Charset,
) -> PrefixRule {
PrefixRule {
detector: DetectorId::new(detector),
prefix,
min_tail,
charset,
}
}
const fn pem(detector: &'static str, marker: &'static str) -> PemRule {
PemRule {
detector: DetectorId::new(detector),
marker,
}
}
pub const PREFIX_RULES: &[PrefixRule] = &[
prefix("anthropic-api-key", "sk-ant-", 24, Charset::Base64Url),
prefix("openai-api-key", "sk-", 20, Charset::Base64Url),
prefix("stripe-secret-key", "sk_live_", 16, Charset::Alphanumeric),
prefix(
"stripe-restricted-key",
"rk_live_",
16,
Charset::Alphanumeric,
),
prefix("github-token", "ghp_", 36, Charset::Alphanumeric),
prefix("github-oauth-token", "gho_", 36, Charset::Alphanumeric),
prefix("github-user-token", "ghu_", 36, Charset::Alphanumeric),
prefix("github-server-token", "ghs_", 36, Charset::Alphanumeric),
prefix("github-refresh-token", "ghr_", 36, Charset::Alphanumeric),
prefix(
"github-fine-grained-token",
"github_pat_",
40,
Charset::Base64Url,
),
prefix("gitlab-personal-token", "glpat-", 20, Charset::Base64Url),
prefix("slack-bot-token", "xoxb-", 24, Charset::Token),
prefix("slack-user-token", "xoxp-", 24, Charset::Token),
prefix("slack-app-token", "xapp-", 24, Charset::Token),
prefix("aws-access-key-id", "AKIA", 16, Charset::Alphanumeric),
prefix(
"aws-temporary-access-key-id",
"ASIA",
16,
Charset::Alphanumeric,
),
prefix("google-api-key", "AIza", 35, Charset::Base64Url),
prefix("google-oauth-token", "ya29.", 32, Charset::Token),
prefix("npm-token", "npm_", 36, Charset::Alphanumeric),
prefix("digitalocean-token", "dop_v1_", 60, Charset::Alphanumeric),
prefix("sendgrid-api-key", "SG.", 32, Charset::Token),
prefix("huggingface-token", "hf_", 32, Charset::Alphanumeric),
prefix("shopify-access-token", "shpat_", 32, Charset::Alphanumeric),
prefix("supabase-service-key", "sbp_", 36, Charset::Alphanumeric),
];
pub const PEM_RULES: &[PemRule] = &[
pem("pem-private-key", "-----BEGIN PRIVATE KEY-----"),
pem("pem-rsa-private-key", "-----BEGIN RSA PRIVATE KEY-----"),
pem("pem-ec-private-key", "-----BEGIN EC PRIVATE KEY-----"),
pem("pem-dsa-private-key", "-----BEGIN DSA PRIVATE KEY-----"),
pem(
"pem-encrypted-private-key",
"-----BEGIN ENCRYPTED PRIVATE KEY-----",
),
pem("openssh-private-key", "-----BEGIN OPENSSH PRIVATE KEY-----"),
pem("pgp-private-key", "-----BEGIN PGP PRIVATE KEY BLOCK-----"),
];
pub const URL_CREDENTIAL: DetectorId = DetectorId::new("url-embedded-credential");
pub const JWT: DetectorId = DetectorId::new("json-web-token");
pub const HIGH_ENTROPY: DetectorId = DetectorId::new("high-entropy-token");
pub const CREDENTIAL_ASSIGNMENT: DetectorId = DetectorId::new("credential-assignment");
const ASSIGNMENT_KEYS: [&str; 5] = ["api_key", "api-key", "apikey", "secret", "token"];
const ASSIGNMENT_MIN_VALUE: usize = 24;
pub const ENTROPY_FRACTION_BITS: u32 = 16;
pub const ENTROPY_ONE: u64 = 1 << ENTROPY_FRACTION_BITS;
#[must_use]
pub const fn bits(whole: u64, hundredths: u64) -> u64 {
whole * ENTROPY_ONE + (hundredths * ENTROPY_ONE) / 100
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct EntropyRule {
pub min_len: usize,
pub threshold: u64,
pub require_mixed_case_and_digit: bool,
}
impl EntropyRule {
pub const STANDARD: Self = Self {
min_len: 24,
threshold: bits(4, 50),
require_mixed_case_and_digit: true,
};
}
impl Default for EntropyRule {
fn default() -> Self {
Self::STANDARD
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct SecretRules {
pub prefixes: &'static [PrefixRule],
pub pem: &'static [PemRule],
pub url_credentials: bool,
pub json_web_tokens: bool,
pub assignments: bool,
pub entropy: Option<EntropyRule>,
}
impl Default for SecretRules {
fn default() -> Self {
Self {
prefixes: PREFIX_RULES,
pem: PEM_RULES,
url_credentials: true,
json_web_tokens: true,
assignments: true,
entropy: Some(EntropyRule::STANDARD),
}
}
}
#[must_use]
pub fn detector_ids() -> Vec<DetectorId> {
PREFIX_RULES
.iter()
.map(|rule| rule.detector)
.chain(PEM_RULES.iter().map(|rule| rule.detector))
.chain([URL_CREDENTIAL, JWT, HIGH_ENTROPY, CREDENTIAL_ASSIGNMENT])
.collect()
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize)]
#[non_exhaustive]
pub struct Finding {
pub detector: DetectorId,
pub offset: usize,
}
const DELIMITERS: [char; 16] = [
'"', '\'', '`', ',', ';', '(', ')', '[', ']', '{', '}', '<', '>', '|', '\\', '\u{feff}',
];
fn is_boundary(character: char) -> bool {
character.is_whitespace() || DELIMITERS.contains(&character)
}
fn tokens(text: &str) -> impl Iterator<Item = (usize, &str)> {
let mut offset = 0usize;
core::iter::from_fn(move || {
let rest = text.get(offset..)?;
let start = offset + rest.find(|c: char| !is_boundary(c))?;
let tail = text.get(start..)?;
let len = tail.find(is_boundary).unwrap_or(tail.len());
offset = start + len;
tail.get(..len).map(|token| (start, token))
})
}
#[must_use]
pub fn scan(text: &str, rules: &SecretRules) -> Option<Finding> {
let armour = rules
.pem
.iter()
.filter_map(|rule| {
text.find(rule.marker).map(|offset| Finding {
detector: rule.detector,
offset,
})
})
.min_by_key(|finding| finding.offset);
let token = tokens(text).find_map(|(offset, token)| {
prefix_match(token, rules.prefixes)
.or_else(|| {
rules
.url_credentials
.then(|| url_credential(token))
.flatten()
})
.or_else(|| {
rules
.json_web_tokens
.then(|| json_web_token(token))
.flatten()
})
.map(|detector| (detector, 0usize))
.or_else(|| rules.entropy.and_then(|rule| high_entropy(token, &rule)))
.map(|(detector, within)| Finding {
detector,
offset: offset.saturating_add(within),
})
});
let assignment = rules
.assignments
.then(|| assignment(text))
.flatten()
.map(|offset| Finding {
detector: CREDENTIAL_ASSIGNMENT,
offset,
});
[armour, token, assignment]
.into_iter()
.flatten()
.min_by_key(|finding| finding.offset)
}
fn prefix_match(token: &str, rules: &[PrefixRule]) -> Option<DetectorId> {
rules.iter().find_map(|rule| {
let tail = token.strip_prefix(rule.prefix)?;
let body: usize = tail.chars().take_while(|c| rule.charset.admits(*c)).count();
(body >= rule.min_tail).then_some(rule.detector)
})
}
fn url_credential(token: &str) -> Option<DetectorId> {
let after_scheme = token.split_once("://")?.1;
let authority = after_scheme.split('/').next()?;
let (userinfo, host) = authority.rsplit_once('@')?;
let (_, password) = userinfo.split_once(':')?;
let credible = !password.is_empty() && !host.is_empty() && !password.contains('@');
credible.then_some(URL_CREDENTIAL)
}
fn json_web_token(token: &str) -> Option<DetectorId> {
let mut parts = token.split('.');
let header = parts.next()?;
let payload = parts.next()?;
let signature = parts.next()?;
if parts.next().is_some() || header.is_empty() || payload.is_empty() {
return None;
}
let base64url =
|part: &str| !part.is_empty() && part.chars().all(|c| Charset::Base64Url.admits(c));
if !base64url(header) || !base64url(payload) || (!signature.is_empty() && !base64url(signature))
{
return None;
}
let decoded = base64url_decode(header)?;
let text = String::from_utf8(decoded).ok()?;
let object: serde_json::Value = serde_json::from_str(&text).ok()?;
let names_a_header = object
.as_object()
.is_some_and(|map| map.contains_key("alg") || map.contains_key("typ"));
names_a_header.then_some(JWT)
}
fn base64url_decode(part: &str) -> Option<Vec<u8>> {
let mut out = Vec::with_capacity(part.len() * 3 / 4);
let mut accumulator: u32 = 0;
let mut bits: u32 = 0;
for character in part.chars() {
let value = match character {
'A'..='Z' => u32::from(character as u8 - b'A'),
'a'..='z' => u32::from(character as u8 - b'a') + 26,
'0'..='9' => u32::from(character as u8 - b'0') + 52,
'-' => 62,
'_' => 63,
_ => return None,
};
accumulator = (accumulator << 6) | value;
bits += 6;
if bits >= 8 {
bits -= 8;
let byte = u8::try_from((accumulator >> bits) & 0xff).ok()?;
out.push(byte);
}
}
Some(out)
}
fn high_entropy(token: &str, rule: &EntropyRule) -> Option<(DetectorId, usize)> {
let mut start = 0usize;
for run in token.split(|c: char| !Charset::Token.admits(c)) {
if is_high_entropy(run, rule) {
return Some((HIGH_ENTROPY, start));
}
let after_run = start.saturating_add(run.len());
start = token
.get(after_run..)
.and_then(|rest| rest.chars().next())
.map_or(after_run, |sep| after_run.saturating_add(sep.len_utf8()));
}
None
}
fn is_high_entropy(run: &str, rule: &EntropyRule) -> bool {
if run.len() < rule.min_len {
return false;
}
if rule.require_mixed_case_and_digit {
let mixed = run.chars().any(|c| c.is_ascii_uppercase())
&& run.chars().any(|c| c.is_ascii_lowercase())
&& run.chars().any(|c| c.is_ascii_digit());
if !mixed {
return false;
}
}
shannon_bits(run) >= rule.threshold
}
#[must_use]
pub fn shannon_bits(token: &str) -> u64 {
let mut counts = [0u32; 256];
let mut total: u64 = 0;
for byte in token.bytes() {
if let Some(slot) = counts.get_mut(usize::from(byte)) {
*slot = slot.saturating_add(1);
total = total.saturating_add(1);
}
}
if total < 2 {
return 0;
}
let weighted: u64 = counts
.iter()
.filter(|count| **count > 0)
.map(|count| u64::from(*count).saturating_mul(log2_q16(u64::from(*count))))
.sum();
log2_q16(total).saturating_sub(weighted / total)
}
fn log2_q16(x: u64) -> u64 {
if x == 0 {
return 0;
}
let integer = u64::from(63 - x.leading_zeros());
let mut mantissa: u128 = if integer >= 32 {
u128::from(x) >> (integer - 32)
} else {
u128::from(x) << (32 - integer)
};
let mut fraction: u64 = 0;
for bit in 0..ENTROPY_FRACTION_BITS {
mantissa = (mantissa * mantissa) >> 32;
if mantissa >= (2u128 << 32) {
fraction |= 1 << (ENTROPY_FRACTION_BITS - 1 - bit);
mantissa >>= 1;
}
}
(integer << ENTROPY_FRACTION_BITS) | fraction
}
fn assignment(text: &str) -> Option<usize> {
let bytes = text.as_bytes();
(0..bytes.len()).find_map(|start| {
ASSIGNMENT_KEYS.iter().find_map(|key| {
let end = start.checked_add(key.len())?;
let candidate = bytes.get(start..end)?;
if !candidate.eq_ignore_ascii_case(key.as_bytes()) {
return None;
}
assigned_value(text, end)
})
})
}
fn assigned_value(text: &str, after_key: usize) -> Option<usize> {
let rest = text.get(after_key..)?.trim_start();
let rest = rest.strip_prefix([':', '='])?.trim_start();
let value = rest.strip_prefix(['\'', '"']).unwrap_or(rest);
let len = value
.bytes()
.take_while(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-'))
.count();
(len >= ASSIGNMENT_MIN_VALUE).then(|| text.len() - value.len())
}
#[cfg(feature = "golden-vectors")]
pub const GOLDEN_VECTORS: &str = include_str!("../testdata/secret-vectors.json");
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct SecretScanCheck {
rules: SecretRules,
}
impl SecretScanCheck {
pub const ID: &'static str = "secret-scan";
#[must_use]
pub fn new(rules: SecretRules) -> Self {
Self { rules }
}
#[must_use]
pub fn rules(&self) -> &SecretRules {
&self.rules
}
}
impl Check for SecretScanCheck {
fn id(&self) -> &str {
Self::ID
}
fn evaluate(&self, ctx: &ActionContext) -> Option<Decision> {
let fields = [
("summary", Some(ctx.payload_summary.as_str())),
("body", ctx.payload_body.as_deref()),
];
fields.into_iter().find_map(|(field, text)| {
let finding = scan(text?, &self.rules)?;
Some(
Decision::deny(
format!(
"gate:deny:secrets:{}:{field}:{}",
finding.detector, finding.offset
),
vec![Self::ID.into()],
)
.blocking(),
)
})
}
fn config_fingerprint(&self) -> String {
let prefixes: Vec<String> = self
.rules
.prefixes
.iter()
.map(|r| {
format!(
"{}|{}|{}|{}",
r.detector,
r.prefix,
r.min_tail,
r.charset.as_str()
)
})
.collect();
let pem: Vec<String> = self
.rules
.pem
.iter()
.map(|r| format!("{}|{}", r.detector, r.marker))
.collect();
let entropy = self.rules.entropy.map_or_else(
|| "none".to_owned(),
|e| {
format!(
"{}|{}|{}",
e.min_len, e.threshold, e.require_mixed_case_and_digit
)
},
);
format!(
"{}:v1;prefix=[{}];pem=[{}];url={};jwt={};assignment={};entropy={}",
Self::ID,
prefixes.join(","),
pem.join(","),
self.rules.url_credentials,
self.rules.json_web_tokens,
self.rules.assignments,
entropy
)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn detect(text: &str) -> Option<(&'static str, usize)> {
scan(text, &SecretRules::default()).map(|f| (f.detector.as_str(), f.offset))
}
#[test]
fn detector_ids_are_unique_and_complete() {
let ids = detector_ids();
let unique: std::collections::BTreeSet<_> = ids.iter().collect();
assert_eq!(unique.len(), ids.len(), "duplicate detector id");
assert_eq!(ids.len(), 24 + 7 + 4);
}
#[test]
fn assignment_reports_the_value_offset() {
let text = "config: api_key = 'abcdefghijklmnopqrstuvwxyz0123'";
assert_eq!(detect(text), Some(("credential-assignment", 19)));
assert_eq!(
detect("TOKEN:abcdefghijklmnopqrstuvwxyz"),
Some(("credential-assignment", 6))
);
}
#[test]
fn assignment_needs_a_long_value_and_an_operator() {
assert_eq!(detect("the token is abcdefghijklmnopqrstuvwxyz"), None);
assert_eq!(detect("secret = short"), None);
assert_eq!(detect("api key = abcdefghijklmnopqrstuvwxyz"), None);
}
#[test]
fn token_detector_wins_a_tie_with_assignment() {
let text = "token = ghp_RyIdydJp2Ys2SJ2jXUBATskPzpR6QTFGlbDtQ57k";
assert_eq!(detect(text), Some(("github-token", 8)));
}
#[test]
fn armour_wins_a_tie_and_earliest_offset_wins() {
let text = "x -----BEGIN PGP PRIVATE KEY BLOCK----- AKIA4QD7XZLM2VNBKTRW";
assert_eq!(detect(text), Some(("pgp-private-key", 2)));
let text = "AKIA4QD7XZLM2VNBKTRW -----BEGIN PRIVATE KEY-----";
assert_eq!(detect(text), Some(("aws-access-key-id", 0)));
}
#[test]
fn toggles_disable_their_detector() {
let rules = SecretRules {
assignments: false,
entropy: None,
..SecretRules::default()
};
assert!(scan("secret=abcdefghijklmnopqrstuvwxyz", &rules).is_none());
}
#[test]
fn shannon_bits_matches_known_values() {
assert_eq!(shannon_bits(""), 0);
assert_eq!(shannon_bits("aaaa"), 0);
assert_eq!(shannon_bits("ab"), ENTROPY_ONE);
assert_eq!(shannon_bits("abcd"), 2 * ENTROPY_ONE);
}
#[test]
fn check_reason_names_detector_field_and_offset() {
let check = SecretScanCheck::default();
let ctx = ActionContext::new("write")
.with_summary("clean")
.with_body("key AKIA4QD7XZLM2VNBKTRW");
let d = check.evaluate(&ctx).expect("secret in body");
assert_eq!(d.reason, "gate:deny:secrets:aws-access-key-id:body:4");
assert_eq!(d.check_ids, vec!["secret-scan"]);
assert!(d.blocking);
assert!(check.evaluate(&ActionContext::new("write")).is_none());
}
#[test]
fn fingerprint_changes_with_the_rules() {
let rules = SecretRules {
json_web_tokens: false,
..SecretRules::default()
};
assert_ne!(
SecretScanCheck::default().config_fingerprint(),
SecretScanCheck::new(rules).config_fingerprint()
);
}
}