1use crate::check::{Outcome, Severity};
33use crate::finding::Finding;
34use crate::pushrefs::PushRef;
35
36use super::common;
37
38const ALLOW: &str = "amont:allow-secret";
40
41const MAX_BYTES: usize = 2 * 1024 * 1024;
44
45#[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
79fn 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
88fn boundary_before(text: &str, at: usize) -> bool {
91 at == 0 || !is_token_char(text.as_bytes()[at - 1])
92}
93
94fn 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
107pub(crate) fn sniff(line: &str) -> Option<Kind> {
110 if line.contains(ALLOW) {
111 return None;
112 }
113 if line.contains(concat!("-----", "BEGIN ")) && line.contains(concat!("PRIVATE", " KEY-----")) {
118 return Some(Kind::PrivateKey);
119 }
120 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 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 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 if has_prefixed_token(line, concat!("AI", "za"), 30) {
168 return Some(Kind::GoogleApiKey);
169 }
170 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 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 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
208fn looks_binary(bytes: &[u8]) -> bool {
210 bytes.iter().take(8000).any(|b| *b == 0)
211}
212
213fn 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
221pub const NAME: &str = "secrets";
223
224pub 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
249pub fn is_scannable(bytes: &[u8]) -> bool {
252 !looks_binary(bytes) && bytes.len() <= MAX_BYTES
253}
254
255pub 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; };
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
286pub 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; }
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 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; common::ok(settings, "No secrets in the pushed commits");
345 Outcome::Passed
346}
347
348#[cfg(test)]
349mod tests {
350 use super::*;
351
352 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 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 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 #[test]
413 fn lookalikes_are_left_alone() {
414 assert_eq!(sniff("AKIAI is the prefix"), None); assert_eq!(sniff(&format!("X{}", aws())), None); assert_eq!(sniff("ghp_short"), None);
417 assert_eq!(sniff("the sk-1234 identifier"), None); 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 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 assert_eq!(
458 sniff("return s.Validate(ctx, token, opts, logger, cfg)"),
459 None
460 );
461 }
462
463 #[test]
465 fn the_allow_pragma_skips_the_line() {
466 let line = format!("{} // {}", aws(), ALLOW);
467 assert_eq!(sniff(&line), None);
468 }
469
470 #[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 #[test]
484 fn binary_content_is_skipped() {
485 assert!(looks_binary(b"\x00PNG"));
486 assert!(!looks_binary(b"just text"));
487 }
488
489 #[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}