agentmux_srv_core/backend/reactive/
post_secrets.rs1pub const KNOWN_SECRET: &str = "a known secret value";
10
11pub const WORD_THEN_VALUE: &str = "a credential word followed by a value";
13
14pub fn help(rule: &str) -> &'static str {
16 match rule {
17 KNOWN_SECRET => " Leave the value out of the text (name what it is, do not paste it).",
18 WORD_THEN_VALUE => " If it is not a secret, rephrase it: leave out the long value-like string (say what it is called instead of pasting it), or drop the word that names a credential.",
19 _ => "",
20 }
21}
22
23static REFUSALS: std::sync::Mutex<Vec<(&'static str, u64)>> = std::sync::Mutex::new(Vec::new());
25
26pub fn count_refusal(rule: &'static str) {
28 let mut counts = REFUSALS.lock().unwrap_or_else(|e| e.into_inner());
29 match counts.iter_mut().find(|(r, _)| *r == rule) {
30 Some((_, n)) => *n += 1,
31 None => counts.push((rule, 1)),
32 }
33 tracing::info!(rule, "a post was refused");
34}
35
36pub fn refusal_counts() -> Vec<(&'static str, u64)> {
38 REFUSALS.lock().unwrap_or_else(|e| e.into_inner()).clone()
39}
40
41const CREDENTIAL_NOUNS: &[&str] = &["token", "tokens", "secret", "secrets", "key", "keys", "password", "passwords", "credential", "credentials", "pat", "apikey", "passphrase", "passphrases", "passwd", "pwd", "bearer"];
44
45const VALUE_PREFIXES: &[&str] = &["ghp_", "gho_", "ghs_", "ghu_", "ghr_", "github_pat_", "xox", "sk-", "sk_", "akia", "asia", "aiza", "ya29.", "eyj", "glpat-", "npm_", "pypi-"];
47
48const REACH: usize = 3;
50
51fn value_shaped(word: &str) -> bool {
54 let lower = word.to_ascii_lowercase();
55 if word.len() >= 12 && VALUE_PREFIXES.iter().any(|p| lower.starts_with(p)) {
56 return true;
57 }
58 let run = word.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '+' | '/' | '=' | '.'));
59 run && word.len() >= 20 && word.chars().any(|c| c.is_ascii_digit()) && word.chars().any(|c| c.is_ascii_alphabetic())
60}
61
62fn parts(word: &str) -> Vec<String> {
64 let mut out = Vec::new();
65 let mut part = String::new();
66 let mut prev_lower = false;
67 for c in word.chars() {
68 if c == '_' || c == '-' {
69 if !part.is_empty() {
70 out.push(std::mem::take(&mut part));
71 }
72 prev_lower = false;
73 continue;
74 }
75 if c.is_ascii_uppercase() && prev_lower && !part.is_empty() {
76 out.push(std::mem::take(&mut part));
77 }
78 prev_lower = c.is_ascii_lowercase();
79 part.push(c.to_ascii_lowercase());
80 }
81 if !part.is_empty() {
82 out.push(part);
83 }
84 out
85}
86
87fn names_a_credential(word: &str) -> bool {
89 parts(word).iter().any(|p| CREDENTIAL_NOUNS.contains(&p.as_str()))
90}
91
92pub(super) fn letter_lookalike(c: char) -> char {
94 match c {
95 'а' => 'a', 'е' | 'є' => 'e', 'о' | 'ο' => 'o', 'р' | 'ρ' => 'p', 'с' | 'ϲ' => 'c', 'у' => 'y', 'х' | 'χ' => 'x',
96 'і' | 'ї' | 'ι' => 'i', 'ѕ' => 's', 'ј' => 'j', 'ԁ' => 'd', 'α' => 'a', 'ν' => 'v', 'τ' => 't', 'κ' => 'k',
97 'А' | 'Α' => 'A', 'В' | 'Β' => 'B', 'Е' | 'Ε' => 'E', 'К' | 'Κ' => 'K', 'М' | 'Μ' => 'M', 'Н' | 'Η' => 'H',
98 'О' | 'Ο' => 'O', 'Р' | 'Ρ' => 'P', 'С' => 'C', 'Т' | 'Τ' => 'T', 'Х' | 'Χ' => 'X', 'І' | 'Ι' => 'I', 'Ѕ' => 'S',
99 'Ј' => 'J', 'Ү' => 'Y', 'Ζ' => 'Z',
100 other => other,
101 }
102}
103
104fn as_read(text: &str) -> String {
107 text.chars()
108 .filter(|c| !matches!(*c, '\u{200B}'..='\u{200F}' | '\u{2060}'..='\u{2064}' | '\u{FEFF}' | '\u{00AD}' | '\u{180E}' | '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}' | '\u{E0000}'..='\u{E007F}'))
109 .map(|c| match c as u32 {
110 0xFF01..=0xFF5E => char::from_u32(c as u32 - 0xFEE0).unwrap_or(c),
111 _ => letter_lookalike(c),
112 })
113 .collect()
114}
115
116pub fn refusal_rule(text: &str) -> Option<&'static str> {
120 let read = as_read(text);
121 if crate::backend::transcript::withhold::holds(text) || crate::backend::transcript::withhold::holds(&read) {
122 return Some(KNOWN_SECRET);
123 }
124 let words: Vec<&str> = read
125 .split(|c: char| c.is_whitespace() || matches!(c, '=' | ':' | '"' | '\'' | ',' | ';' | '{' | '}' | '(' | ')' | '[' | ']' | '`' | '<' | '>'))
126 .filter(|w| !w.is_empty())
127 .collect();
128 for (i, word) in words.iter().enumerate() {
129 if !value_shaped(word) {
130 continue;
131 }
132 let from = i.saturating_sub(REACH);
133 let to = (i + 1 + REACH).min(words.len());
134 if words[from..i].iter().chain(words[i + 1..to].iter()).any(|near| names_a_credential(near)) {
135 return Some(WORD_THEN_VALUE);
136 }
137 }
138 None
139}
140
141#[cfg(test)]
142mod tests {
143 use super::*;
144 use crate::backend::transcript::withhold;
145
146 #[test]
147 fn a_value_the_registry_holds_is_refused_in_every_spelling_and_never_named() {
148 let canary = "canary-Value_7731xQ-post";
149 withhold::register(canary);
150 for form in crate::backend::vault::scrub::forms(canary) {
151 let text = format!("please note that {form} is what you need");
152 assert_eq!(refusal_rule(&text), Some(KNOWN_SECRET), "{form}");
153 }
154 assert!(!KNOWN_SECRET.contains("canary") && !WORD_THEN_VALUE.contains("canary"));
155 assert_eq!(refusal_rule("a value that is not registered, and ordinary text"), None);
156 }
157
158 #[test]
159 fn joined_credential_names_are_refused_when_a_value_follows() {
160 let value = ["ghp", "_aB3dE5fG7hI9jK1lM3nO5pQ7rS9tU1vW3xY5"].concat();
162 let slack = ["xo", "xb-1234567890-abcdefghijkl"].concat();
163 for text in [
164 format!("access_token={value}"),
165 format!("refresh_token: {value}"),
166 format!("api-key {value}"),
167 format!("client_secret = \"{value}\""),
168 format!("apiKey: {value}"),
169 format!("AccessToken {value}"),
170 format!("a slack token {slack}"),
171 format!("the discord token is {value}"),
172 ] {
173 assert_eq!(refusal_rule(&text), Some(WORD_THEN_VALUE), "{text}");
174 }
175 }
176
177 #[test]
178 fn ordinary_text_about_usage_units_and_names_without_a_value_is_let_through() {
179 for text in [
180 "Record ways to save tokens: a kind named security is for gaps.",
181 "the access_token field is renamed to accessToken in the new release",
182 "rotate the api-key every quarter; the key name stays the same",
183 "It cost 40k tokens and seven turns on 2026-11-21T19:59:07Z",
184 "the secret store is in the private repo (a5af/shared-infrastructure)",
185 ] {
186 assert_eq!(refusal_rule(text), None, "{text}");
187 }
188 }
189
190 #[test]
191 fn a_registered_value_is_still_found_with_an_invisible_character_or_a_look_alike_letter_in_it() {
192 let canary = "Canary-Pass7731xQ-fold";
193 withhold::register(canary);
194 let with_zero_width = canary.replacen("Pass", "Pa\u{200B}ss", 1);
195 let with_cyrillic_a = canary.replacen("Canary", "C\u{0430}nary", 1);
196 let fullwidth: String = canary.chars().map(|c| if c.is_ascii_alphanumeric() { char::from_u32(c as u32 + 0xFEE0).unwrap() } else { c }).collect();
197 for text in [with_zero_width, with_cyrillic_a, fullwidth] {
198 assert_eq!(refusal_rule(&format!("note: {text} ok")), Some(KNOWN_SECRET), "{text}");
199 }
200 }
201
202 #[test]
203 fn a_value_first_and_the_newer_nouns_are_refused() {
204 let value = ["ghp", "_aB3dE5fG7hI9jK1lM3nO5pQ7rS9tU1vW3xY5"].concat();
205 for text in [
206 format!("{value} is my token"),
207 format!("{value} <- the key"),
208 format!("passphrase: {value}"),
209 format!("pwd={value}"),
210 format!("Bearer {value}"),
211 format!("the passwd is {value}"),
212 ] {
213 assert_eq!(refusal_rule(&text), Some(WORD_THEN_VALUE), "{text}");
214 }
215 assert_eq!(refusal_rule(&format!("the build id is {} and nothing else follows here", ["d3b0", "7384d9a04c9b8a6d1f2e3c4b5a697881"].concat())), None);
217 }
218
219 #[test]
220 fn a_refusal_says_how_to_post_the_text_anyway_and_is_counted_by_rule() {
221 assert!(help(WORD_THEN_VALUE).contains("rephrase") && help(KNOWN_SECRET).contains("Leave the value out"));
222 assert_eq!(help("password"), "");
223 let before = refusal_counts().into_iter().find(|(r, _)| *r == WORD_THEN_VALUE).map_or(0, |(_, n)| n);
224 count_refusal(WORD_THEN_VALUE);
225 let after = refusal_counts().into_iter().find(|(r, _)| *r == WORD_THEN_VALUE).map_or(0, |(_, n)| n);
226 assert_eq!(after, before + 1);
227 }
228}