1#[derive(Debug, Clone, PartialEq, Eq)]
13pub struct Finding {
14 pub file: String,
15 pub line: u32,
16 pub category: &'static str,
17}
18
19const MAX_FINDINGS: usize = 20;
21
22fn is_alnum(c: char) -> bool {
23 c.is_ascii_alphanumeric()
24}
25
26fn is_key_char(c: char) -> bool {
27 c.is_ascii_alphanumeric() || c == '_' || c == '-'
28}
29
30fn has_run(text: &str, prefix: &str, min: usize, class: fn(char) -> bool) -> bool {
33 let mut from = 0;
34 while let Some(at) = text[from..].find(prefix) {
35 let start = from + at;
36 let after = start + prefix.len();
37 let word_tail = text[..start].chars().next_back().is_some_and(is_alnum);
38 if !word_tail && text[after..].chars().take_while(|c| class(*c)).count() >= min {
39 return true;
40 }
41 from = start + prefix.len().max(1);
42 }
43 false
44}
45
46pub fn credential_in(text: &str) -> Option<&'static str> {
48 if text.contains(&["-----BE", "GIN "].concat()) && text.contains(&["PRIVATE", " KEY-----"].concat()) {
50 return Some("private key");
51 }
52 if ["ghp_", "gho_", "ghu_", "ghs_", "ghr_"].iter().any(|p| has_run(text, p, 36, is_alnum)) || has_run(text, "github_pat_", 22, is_key_char) {
53 return Some("GitHub token");
54 }
55 if ["AKIA", "ASIA"].iter().any(|p| has_run(text, p, 16, |c| c.is_ascii_uppercase() || c.is_ascii_digit())) {
58 return Some("AWS access key id");
59 }
60 if has_run(text, "sk-ant-", 20, is_key_char) {
61 return Some("Anthropic API key");
62 }
63 if has_run(text, "sk-", 40, is_key_char) {
64 return Some("OpenAI API key");
65 }
66 if ["xoxb-", "xoxp-", "xoxa-", "xoxr-", "xoxs-"].iter().any(|p| has_run(text, p, 20, |c| c.is_ascii_alphanumeric() || c == '-')) {
67 return Some("Slack token");
68 }
69 if has_run(text, "AIza", 35, is_key_char) {
70 return Some("Google API key");
71 }
72 if has_run(text, "sk_live_", 20, is_alnum) {
73 return Some("Stripe live key");
74 }
75 None
76}
77
78pub fn scan_diff(diff: &str) -> Vec<Finding> {
80 let mut found = Vec::new();
81 let mut file = String::new();
82 let mut line_no: u32 = 0;
83 let (mut old_left, mut new_left) = (0u32, 0u32);
86 let mut cols = 0usize;
90 for line in diff.lines() {
91 let in_hunk = old_left > 0 || new_left > 0;
92 let in_hunk = if line.starts_with("diff ") {
93 (cols, old_left, new_left) = (0, 0, 0);
95 false
96 } else {
97 in_hunk
98 };
99 if !in_hunk {
100 if let Some(path) = line.strip_prefix("+++ ") {
101 file = path.strip_prefix("b/").unwrap_or(path).trim_matches('"').to_string();
102 continue;
103 }
104 }
105 if line.starts_with("@@@") {
106 cols = line.chars().take_while(|c| *c == '@').count() - 1;
107 let (start, count) = combined_new_range(line);
108 (old_left, new_left, line_no) = (0, count, start);
109 } else if cols > 0
110 && line.get(..cols).is_some_and(|p| p.chars().all(|c| matches!(c, ' ' | '+' | '-')) && (new_left > 0 || p.contains('-')))
111 {
112 let (prefix, text) = line.split_at(cols);
113 if prefix.contains('-') {
114 } else if prefix.chars().all(|c| c == '+') {
116 if let Some(category) = credential_in(text) {
118 found.push(Finding { file: file.clone(), line: line_no, category });
119 if found.len() >= MAX_FINDINGS {
120 return found;
121 }
122 }
123 line_no += 1;
124 new_left = new_left.saturating_sub(1);
125 } else {
126 line_no += 1;
128 new_left = new_left.saturating_sub(1);
129 }
130 } else if let Some(hunk) = line.strip_prefix("@@") {
131 cols = 0;
132 let (old, new) = hunk_counts(hunk);
134 (old_left, new_left) = (old.1, new.1);
135 line_no = new.0;
136 } else if let Some(added) = line.strip_prefix('+') {
137 if let Some(category) = credential_in(added) {
138 found.push(Finding { file: file.clone(), line: line_no, category });
139 if found.len() >= MAX_FINDINGS {
140 return found;
141 }
142 }
143 line_no += 1;
144 new_left = new_left.saturating_sub(1);
145 } else if line.starts_with('-') {
146 old_left = old_left.saturating_sub(1);
147 } else if line.starts_with(' ') {
148 line_no += 1;
149 old_left = old_left.saturating_sub(1);
150 new_left = new_left.saturating_sub(1);
151 }
152 }
153 found
154}
155
156fn combined_new_range(header: &str) -> (u32, u32) {
159 let Some((_, after)) = header.rsplit_once(" +") else { return (0, 0) };
160 let mut n = after.split(' ').next().unwrap_or("").split(',');
161 let start = n.next().and_then(|v| v.parse().ok()).unwrap_or(0);
162 let count = n.next().and_then(|v| v.parse().ok()).unwrap_or(1);
163 (start, count)
164}
165
166fn hunk_counts(header: &str) -> ((u32, u32), (u32, u32)) {
169 let side = |part: &str| {
170 let mut n = part.trim_start_matches(['-', '+', ' ']).split(',');
171 let start = n.next().and_then(|v| v.trim().parse().ok()).unwrap_or(0);
172 let count = n.next().and_then(|v| v.trim().parse().ok()).unwrap_or(1);
173 (start, count)
174 };
175 let ranges = header.split("@@").next().unwrap_or(header).trim();
176 let mut parts = ranges.split(" +");
177 let old = side(parts.next().unwrap_or(""));
178 let new = side(parts.next().unwrap_or(""));
179 (old, new)
180}
181
182pub fn refusal_text(findings: &[Finding]) -> String {
184 let mut out = String::from("agentmux: this push is refused: it adds what looks like a credential.\n");
185 for f in findings {
186 out.push_str(&format!(" {}:{} {}\n", f.file, f.line, f.category));
187 }
188 out.push_str("The text is not shown here. Take it out of the commits (and rotate it if it was real), then push again.\n");
189 out
190}
191
192#[cfg(test)]
193mod tests {
194 use super::*;
195
196 fn gh() -> String {
198 format!("{}{}", "ghp_", "a1B2c3D4e5F6g7H8i9J0k1L2m3N4o5P6q7R8")
199 }
200 fn aws() -> String {
201 format!("{}{}", "AKIA", "ABCDEFGHIJKLMNOP")
202 }
203 fn anthropic() -> String {
204 format!("{}{}", "sk-ant-", "api03-abcdefghijklmnopqrstuvwxyz0123456789")
205 }
206
207 #[test]
208 fn the_formats_with_a_certain_shape_are_found_and_named() {
209 assert_eq!(credential_in(&format!("token = \"{}\"", gh())), Some("GitHub token"));
210 assert_eq!(credential_in(&format!("AWS_KEY={}", aws())), Some("AWS access key id"));
211 assert_eq!(credential_in(&format!("k: {}", anthropic())), Some("Anthropic API key"));
212 assert_eq!(credential_in(&["-----BE", "GIN RSA PRIV", "ATE KEY-----"].concat()), Some("private key"));
213 assert_eq!(credential_in(&format!("{}{}", "github_pat_", "11ABCDEFG0abcdefghijkl_mnopqrstuvwxyz")), Some("GitHub token"));
214 assert_eq!(credential_in(&format!("{}{}", "xoxb-", "1234567890-abcdefghijklmnop")), Some("Slack token"));
215 }
216
217 #[test]
218 fn ordinary_text_and_short_lookalikes_are_not() {
219 for text in [
220 "let key = format!(\"ghp_{}\", n);",
221 "AKIA is the prefix of an access key id",
222 "ask-for-the-thing-that-you-want-to-have-no-longer-than-this-one",
223 "risk-averse-and-long-enough-to-look-like-a-key-0123456789abcdef",
224 "sk-short",
225 "// -----BEGIN is where it starts",
226 ] {
227 assert_eq!(credential_in(text), None, "{text}");
228 }
229 assert_eq!(credential_in(&["\"RoleId\": \"", "AROA", "KSCDLFT9R5DQP782U\""].concat()), None);
231 }
232
233 #[test]
234 fn a_diff_names_the_file_and_the_line_of_each_added_credential() {
235 let diff = format!(
236 "diff --git a/src/a.rs b/src/a.rs\n--- a/src/a.rs\n+++ b/src/a.rs\n@@ -3,0 +4,3 @@\n+fn ok() {{}}\n+let k = \"{}\";\n+let n = 1;\n\
237 diff --git a/b.env b/b.env\n--- /dev/null\n+++ b/b.env\n@@ -0,0 +1,2 @@\n+A=1\n+KEY={}\n-OLD={}\n",
238 gh(),
239 aws(),
240 anthropic()
241 );
242 assert_eq!(
243 scan_diff(&diff),
244 vec![
245 Finding { file: "src/a.rs".into(), line: 5, category: "GitHub token" },
246 Finding { file: "b.env".into(), line: 2, category: "AWS access key id" },
247 ],
248 "a removed line is not a finding"
249 );
250 }
251
252 #[test]
253 fn an_added_line_that_looks_like_a_file_header_is_still_scanned() {
254 let diff = format!(
256 "--- a/x\n+++ b/x\n@@ -0,0 +1,2 @@\n+first\n+++ {}\n@@ -5,1 +5,0 @@\n-gone\n+++ b/next\n@@ -0,0 +1,1 @@\n+{}\n",
257 gh(),
258 aws()
259 );
260 assert_eq!(
261 scan_diff(&diff),
262 vec![
263 Finding { file: "x".into(), line: 2, category: "GitHub token" },
264 Finding { file: "next".into(), line: 1, category: "AWS access key id" },
265 ]
266 );
267 assert_eq!(hunk_counts(" -3,2 +4 @@ fn x"), ((3, 2), (4, 1)));
268 }
269
270 #[test]
271 fn a_merge_is_scanned_for_what_no_parent_had() {
272 let diff = format!(
275 "diff --cc a.txt\nindex 111,222..333\n--- a/a.txt\n+++ b/a.txt\n@@@ -1,2 -1,2 +1,3 @@@\n base\n++key = {}\n +from_main = {}\n- gone\ndiff --git a/b b/b\n--- a/b\n+++ b/b\n@@ -0,0 +1 @@\n+{}\n",
276 gh(),
277 aws(),
278 aws()
279 );
280 assert_eq!(
281 scan_diff(&diff),
282 vec![
283 Finding { file: "a.txt".into(), line: 2, category: "GitHub token" },
284 Finding { file: "b".into(), line: 1, category: "AWS access key id" },
285 ]
286 );
287 assert_eq!(combined_new_range("@@@ -1,2 -1 +4,3 @@@ fn x"), (4, 3));
288 }
289
290 #[test]
291 fn a_refusal_never_contains_the_matched_text() {
292 let text = refusal_text(&[Finding { file: "x".into(), line: 1, category: "GitHub token" }]);
293 assert!(text.contains("x:1 GitHub token"));
294 assert!(!text.contains("ghp_"));
295 }
296}