1use action_gate_types::{ActionContext, Check, Decision};
38
39#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
42pub struct DetectorId(&'static str);
43
44impl DetectorId {
45 #[must_use]
47 pub const fn new(name: &'static str) -> Self {
48 Self(name)
49 }
50
51 #[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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
73pub enum Charset {
74 Alphanumeric,
76 Base64Url,
78 Token,
80}
81
82impl Charset {
83 #[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 #[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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
111pub struct PrefixRule {
112 pub detector: DetectorId,
114 pub prefix: &'static str,
116 pub min_tail: usize,
120 pub charset: Charset,
122}
123
124#[derive(Clone, Copy, Debug, PartialEq, Eq)]
126pub struct PemRule {
127 pub detector: DetectorId,
129 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
155pub 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
204pub 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
218pub const URL_CREDENTIAL: DetectorId = DetectorId::new("url-embedded-credential");
220
221pub const JWT: DetectorId = DetectorId::new("json-web-token");
223
224pub const HIGH_ENTROPY: DetectorId = DetectorId::new("high-entropy-token");
226
227pub const CREDENTIAL_ASSIGNMENT: DetectorId = DetectorId::new("credential-assignment");
230
231const ASSIGNMENT_KEYS: [&str; 5] = ["api_key", "api-key", "apikey", "secret", "token"];
234
235const ASSIGNMENT_MIN_VALUE: usize = 24;
237
238pub const ENTROPY_FRACTION_BITS: u32 = 16;
244
245pub const ENTROPY_ONE: u64 = 1 << ENTROPY_FRACTION_BITS;
247
248#[must_use]
250pub const fn bits(whole: u64, hundredths: u64) -> u64 {
251 whole * ENTROPY_ONE + (hundredths * ENTROPY_ONE) / 100
252}
253
254#[derive(Clone, Copy, Debug, PartialEq, Eq)]
257pub struct EntropyRule {
258 pub min_len: usize,
261 pub threshold: u64,
263 pub require_mixed_case_and_digit: bool,
267}
268
269impl EntropyRule {
270 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#[derive(Clone, Debug, PartialEq, Eq)]
291#[non_exhaustive]
292pub struct SecretRules {
293 pub prefixes: &'static [PrefixRule],
295 pub pem: &'static [PemRule],
297 pub url_credentials: bool,
299 pub json_web_tokens: bool,
301 pub assignments: bool,
303 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#[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#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize)]
333#[non_exhaustive]
334pub struct Finding {
335 pub detector: DetectorId,
337 pub offset: usize,
339}
340
341const DELIMITERS: [char; 16] = [
343 '"', '\'', '`', ',', ';', '(', ')', '[', ']', '{', '}', '<', '>', '|', '\\', '\u{feff}',
344];
345
346fn is_boundary(character: char) -> bool {
347 character.is_whitespace() || DELIMITERS.contains(&character)
348}
349
350fn 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#[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 [armour, token, assignment]
413 .into_iter()
414 .flatten()
415 .min_by_key(|finding| finding.offset)
416}
417
418fn 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
427fn 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
438fn 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
464fn 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
489fn 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 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#[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
550fn 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
573fn 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 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#[cfg(feature = "golden-vectors")]
606pub const GOLDEN_VECTORS: &str = include_str!("../testdata/secret-vectors.json");
607
608#[derive(Clone, Debug, Default, PartialEq, Eq)]
614pub struct SecretScanCheck {
615 rules: SecretRules,
616}
617
618impl SecretScanCheck {
619 pub const ID: &'static str = "secret-scan";
621
622 #[must_use]
624 pub fn new(rules: SecretRules) -> Self {
625 Self { rules }
626 }
627
628 #[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}