1use crate::check::{Outcome, Severity};
33use crate::finding::Finding;
34use crate::pushrefs::PushRef;
35
36use super::common;
37
38const ALLOW: &str = crate::names::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 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
263pub fn is_scannable(bytes: &[u8]) -> bool {
266 !looks_binary(bytes) && bytes.len() <= MAX_BYTES
267}
268
269pub 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; };
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
300pub 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; }
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 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; common::ok(settings, "No secrets in the pushed commits");
359 Outcome::Passed
360}
361
362#[cfg(test)]
363mod tests {
364 use super::*;
365
366 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 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 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 #[test]
427 fn lookalikes_are_left_alone() {
428 assert_eq!(sniff("AKIAI is the prefix"), None); assert_eq!(sniff(&format!("X{}", aws())), None); assert_eq!(sniff("ghp_short"), None);
431 assert_eq!(sniff("the sk-1234 identifier"), None); 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 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 assert_eq!(
472 sniff("return s.Validate(ctx, token, opts, logger, cfg)"),
473 None
474 );
475 }
476
477 #[test]
479 fn the_allow_pragma_skips_the_line() {
480 let line = format!("{} // {}", aws(), ALLOW);
481 assert_eq!(sniff(&line), None);
482 }
483
484 #[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 #[test]
498 fn binary_content_is_skipped() {
499 assert!(looks_binary(b"\x00PNG"));
500 assert!(!looks_binary(b"just text"));
501 }
502
503 #[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}