//! The secret check (P2): our own short list of high-confidence rules, run before a change becomes history. use anyhow::Result; use regex::Regex; use std::collections::HashSet; use std::path::Path; use std::sync::LazyLock; struct Rule { name: &'static str, re: Regex, /// Extra test on the matched secret, for rules that would otherwise catch ordinary words. looks_random: bool, } static RULES: LazyLock> = LazyLock::new(|| { let r = |name, pattern: &str, looks_random| Rule { name, re: Regex::new(pattern).unwrap(), looks_random }; vec![ r("private key", r"(?s)-----BEGIN [A-Z0-9 ]*PRIVATE KEY(?: BLOCK)?-----(?:.*?-----END [A-Z0-9 ]*PRIVATE KEY(?: BLOCK)?-----|.*)", false), r("AWS access key", r"\b((?:AKIA|ASIA|ABIA|ACCA)[0-9A-Z]{16})\b", false), r("AWS secret key", r#"(?i)aws.{0,20}(?:secret|key).{0,20}?[:=]\s*["']?([A-Za-z0-9/+=]{40})(?:[^A-Za-z0-9/+=]|$)"#, false), r("GitHub token", r"\b((?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{36,}|github_pat_[A-Za-z0-9_]{60,})", false), r("GitLab token", r"\b(glpat-[A-Za-z0-9_\-]{20,})", false), r("Slack token", r"\b(xox[baprs]-[A-Za-z0-9-]{10,})", false), r("Slack webhook", r"(https://hooks\.slack\.com/services/[A-Za-z0-9/]{20,})", false), r("Stripe key", r"\b((?:sk|rk)_live_[A-Za-z0-9]{20,})", false), r("Google API key", r"\b(AIza[0-9A-Za-z_\-]{35})", false), r("Google client secret", r"\b(GOCSPX-[A-Za-z0-9_\-]{28})", false), r("Anthropic key", r"\b(sk-ant-[A-Za-z0-9_\-]{32,})", false), r("OpenAI key", r"\b(sk-(?:proj-|svcacct-)?[A-Za-z0-9_\-]{32,})", false), r("npm token", r"\b(npm_[A-Za-z0-9]{36})\b", false), r("DigitalOcean token", r"\b(do[opr]_v1_[a-f0-9]{64})\b", false), r("SendGrid key", r"\b(SG\.[A-Za-z0-9_\-]{22}\.[A-Za-z0-9_\-]{43})", false), r("Telegram bot token", r"\b(\d{8,10}:AA[A-Za-z0-9_\-]{33})", false), r("Vault token", r"\b(hv[sb]\.[A-Za-z0-9_\-]{90,})", false), r("JSON web token", r"\b(eyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,})", false), r("password in a URL", r"\b[a-z][a-z0-9+.\-]*://[^\s:/@]+:([^\s@/]{3,})@", true), r( "password or token", r#"(?i)(?:password|passwd|pwd|secret|token|api[_\-]?key|access[_\-]?key|client[_\-]?secret|private[_\-]?key)["']?\s*[:=]\s*["'`]?([^\s"'`,;]{12,})"#, true, ), ] }); /// One suspected secret in a note. #[derive(Debug, Clone)] pub struct Hit { pub rule: &'static str, /// Byte span of the secret itself. pub start: usize, pub end: usize, /// 1-based line where it starts. pub line: usize, /// Fingerprint of the exact line(s) it sits on, for "not a secret". pub line_hash: String, /// Masked preview, never the full secret. pub hint: String, } /// Secrets on lines of `text` that aren't in `old` (already shared) and aren't allowed. pub fn scan(text: &str, old: Option<&str>, allowed: &HashSet) -> Vec { let old_lines: HashSet<&str> = old.map(|o| o.lines().collect()).unwrap_or_default(); let mut hits: Vec = vec![]; for rule in RULES.iter() { for caps in rule.re.captures_iter(text) { let m = caps.get(1).unwrap_or_else(|| caps.get(0).unwrap()); if hits.iter().any(|h| m.start() < h.end && h.start < m.end()) { continue; } if rule.looks_random && !looks_random(m.as_str()) { continue; } let ls = text[..m.start()].rfind('\n').map_or(0, |i| i + 1); let le = text[m.end()..].find('\n').map_or(text.len(), |i| m.end() + i); let lines = &text[ls..le]; if lines.lines().all(|l| old_lines.contains(l)) { continue; } let line_hash = fingerprint(lines); if allowed.contains(&line_hash) { continue; } hits.push(Hit { rule: rule.name, start: m.start(), end: m.end(), line: text[..m.start()].matches('\n').count() + 1, line_hash, hint: mask(m.as_str()), }); } } hits.sort_by_key(|h| h.start); hits } /// Scans a file's bytes; binary files are skipped. pub fn scan_bytes(new: &[u8], old: Option<&[u8]>, allowed: &HashSet) -> Vec { if new.iter().take(8000).any(|&b| b == 0) { return vec![]; } let Ok(text) = std::str::from_utf8(new) else { return vec![] }; let old = old.and_then(|o| std::str::from_utf8(o).ok()); scan(text, old, allowed) } /// Replaces every hit (or only the one on `line`) with `pointer`. pub fn replace_with_pointer(text: &str, hits: &[Hit], line: Option, pointer: &str) -> String { let mut out = text.to_string(); for h in hits.iter().rev().filter(|h| line.is_none_or(|l| h.line == l)) { out.replace_range(h.start..h.end, pointer); } out } fn fingerprint(s: &str) -> String { git2::Oid::hash_object(git2::ObjectType::Blob, s.as_bytes()).map(|o| o.to_string()).unwrap_or_default() } fn mask(s: &str) -> String { let first_line = s.lines().next().unwrap_or(""); let shown: String = first_line.chars().take(4).collect(); format!("{shown}… ({} characters)", s.chars().count()) } /// Long, mixed and not a placeholder: what real generated secrets look like. fn looks_random(s: &str) -> bool { let lower = s.to_lowercase(); let placeholder = ["<", ">", "${", "{{", "xxx", "changeme", "example", "your", "redacted", "placeholder", "****"] .iter() .any(|p| lower.contains(p)); if placeholder || s.len() < 8 { return false; } let classes = [s.bytes().any(|b| b.is_ascii_lowercase()), s.bytes().any(|b| b.is_ascii_uppercase()), s.bytes().any(|b| b.is_ascii_digit()), s.bytes().any(|b| !b.is_ascii_alphanumeric())]; let mut counts = std::collections::HashMap::new(); for c in s.chars() { *counts.entry(c).or_insert(0usize) += 1; } let n = s.chars().count() as f64; let entropy: f64 = counts.values().map(|&c| { let p = c as f64 / n; -p * p.log2() }).sum(); classes.iter().filter(|&&c| c).count() >= 2 && entropy >= 3.0 } /// Lines this device was told are not secrets, as fingerprints. Lives in `.git/lune/`. pub fn load_allowed(git_dir: &Path) -> HashSet { std::fs::read_to_string(crate::state::lune_dir(git_dir).join("not-secrets")) .unwrap_or_default() .lines() .filter_map(|l| l.split_whitespace().next().map(String::from)) .collect() } pub fn allow(git_dir: &Path, hit: &Hit, file: &str) -> Result<()> { use std::io::Write; let dir = crate::state::lune_dir(git_dir); std::fs::create_dir_all(&dir)?; let mut f = std::fs::OpenOptions::new().create(true).append(true).open(dir.join("not-secrets"))?; writeln!(f, "{} {} line {} · {}", hit.line_hash, file, hit.line, hit.rule)?; Ok(()) } /// Lines this history entry adds (relative to all its parents) that look like secrets. The hub refuses any /// entry with one (P3); devices use it to know beforehand. pub fn check_commit(repo: &git2::Repository, commit: &git2::Commit, allowed: &HashSet) -> Result> { let parents: Vec = commit.parents().map(|p| p.tree()).collect::>()?; let tree = commit.tree()?; let first = parents.first(); let diff = repo.diff_tree_to_tree(first, Some(&tree), None)?; let mut out = vec![]; for delta in diff.deltas() { if !matches!(delta.status(), git2::Delta::Added | git2::Delta::Modified) { continue; } let Some(path) = delta.new_file().path() else { continue }; let new = repo.find_blob(delta.new_file().id())?; // A line already present in any parent isn't new here. let mut old = Vec::new(); for p in &parents { if let Ok(e) = p.get_path(path) && let Ok(b) = repo.find_blob(e.id()) { old.extend_from_slice(b.content()); old.push(b'\n'); } } let old = if old.is_empty() { None } else { Some(old.as_slice()) }; for hit in scan_bytes(new.content(), old, allowed) { out.push(format!("{} line {}: possible {}", path.display(), hit.line, hit.rule)); } } Ok(out) } #[cfg(test)] mod tests { use super::*; fn rules_hit(text: &str) -> Vec<&'static str> { scan(text, None, &HashSet::new()).into_iter().map(|h| h.rule).collect() } #[test] fn catches_real_looking_secrets() { assert_eq!(rules_hit("key: AKIAIOSFODNN7EXAMPLE\n"), ["AWS access key"]); assert_eq!(rules_hit("aws_secret_access_key = wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY\n"), ["AWS secret key"]); assert_eq!(rules_hit("-----BEGIN OPENSSH PRIVATE KEY-----\nb3Blbn\n-----END OPENSSH PRIVATE KEY-----\n"), ["private key"]); assert_eq!(rules_hit("token ghp_0123456789abcdefghijABCDEFGHIJ012345\n"), ["GitHub token"]); assert_eq!(rules_hit("sk-ant-api03-abcdefghijklmnopqrstuvwxyz0123456789\n"), ["Anthropic key"]); assert_eq!(rules_hit("db: postgres://app:S3cr3t-Pa55w0rd@db.internal/app\n"), ["password in a URL"]); assert_eq!(rules_hit("DB_PASSWORD=Xq7#pL9!vR2@mK4z\n"), ["password or token"]); } #[test] fn leaves_pointers_and_prose_alone() { for ok in [ "Get the DB password from 1Password: search prod-db\n", "password: \n", "token = ${GITHUB_TOKEN}\n", "secret: see Secrets Manager prod/deploy\n", "use tsh login --proxy=teleport.internal\n", "postgres://app@db.internal/app\n", "api_key = changeme_changeme\n", ] { assert!(rules_hit(ok).is_empty(), "{ok}"); } } #[test] fn only_new_lines_count_and_allowed_lines_are_remembered() { let old = "AKIAIOSFODNN7EXAMPLE\n"; assert!(scan("AKIAIOSFODNN7EXAMPLE\nmore\n", Some(old), &HashSet::new()).is_empty()); let hits = scan("x\nkey AKIAIOSFODNN7EXAMPLE\n", None, &HashSet::new()); assert_eq!(hits[0].line, 2); let allowed = HashSet::from([hits[0].line_hash.clone()]); assert!(scan("x\nkey AKIAIOSFODNN7EXAMPLE\n", None, &allowed).is_empty()); assert!(!hits[0].hint.contains("IOSFODNN7EXAMPLE")); } #[test] fn pointer_replaces_only_the_secret() { let text = "aws_access_key_id = AKIAIOSFODNN7EXAMPLE\n"; let hits = scan(text, None, &HashSet::new()); let out = replace_with_pointer(text, &hits, None, "(search prod-deploy in Secrets Manager)"); assert_eq!(out, "aws_access_key_id = (search prod-deploy in Secrets Manager)\n"); assert!(scan(&out, None, &HashSet::new()).is_empty()); } }