Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/synapse/blob/main/crates/synapse-api/src/secret_scan.rs # synapse A component of the AienOS ecosystem. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `synapse / crates / synapse-api / src / secret_scan.rs` 518 lines ยท 17693 bytes Raw Blame History 1 //! Secret scanning at admission (ADR 0003 section 5.13, step M1). 2 //! 3 //! Every blob an agent submits is scanned before the store sees it, so a refused secret never 4 //! reaches the WAL, the content store, an index, or a cache. A hit refuses the whole admission 5 //! with [`RefusalCode::SecretDetected`]. The refusal names the blob digest, the rule, the rule 6 //! set version, and the byte offset; it never contains the matched bytes, and this module keeps 7 //! no copy of them. 8 //! 9 //! The scanner is a hand-written single pass over raw bytes (binary safe, no UTF-8 10 //! assumption, no regular expressions). Each position does a bounded amount of work, and the 11 //! windows that longer checks walk cannot overlap without bound, so time is linear in the input 12 //! length and memory is constant. The rule set is versioned data ([`SECRET_RULESET_VERSION`]). 13 //! 14 //! Policy (refuse by default): there is no allowlist and no override. Clearly fake 15 //! documentation values (`EXAMPLE`, `fake`, `your`, `xxxxxxxx`, very low character variety) are not 16 //! secrets and are admitted. 17 18 use synapse_core::{BlobDigest, RefusalCode, SynapseError, SynapseResult}; 19 20 /// Version of the rule set below. Bump it whenever a rule is added, removed, or changed. 21 pub const SECRET_RULESET_VERSION: u16 = 1; 22 23 /// One rule of the secret-scanning rule set. 24 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] 25 pub enum SecretRule { 26 /// A PEM or OpenSSH private key block (`BEGIN ... PRIVATE KEY`) with a key body. 27 PrivateKeyBlock, 28 /// An AWS access key id (`AKIA` or `ASIA` plus 16 characters). 29 AwsAccessKeyId, 30 /// A GitHub classic token (`ghp_`, `gho_`, `ghu_`, `ghs_`, `ghr_`). 31 GithubToken, 32 /// A GitHub fine-grained personal access token (`github_pat_`). 33 GithubFineGrainedToken, 34 /// A Slack token (`xoxb-`, `xoxp-`, ...). 35 SlackToken, 36 /// A Slack incoming webhook URL. 37 SlackWebhook, 38 /// A Stripe live secret or restricted key. 39 StripeLiveKey, 40 /// An Anthropic API key (`sk-ant-`). 41 AnthropicKey, 42 /// An OpenAI API key (project, service account, admin, or legacy format). 43 OpenAiKey, 44 /// A high-entropy value assigned to a secret-like name (`token = "..."`). 45 SecretAssignment, 46 } 47 48 impl SecretRule { 49 /// Stable identifier of the rule, used in refusal text. 50 pub fn id(self) -> &'static str { 51 match self { 52 SecretRule::PrivateKeyBlock => "private-key-block", 53 SecretRule::AwsAccessKeyId => "aws-access-key-id", 54 SecretRule::GithubToken => "github-token", 55 SecretRule::GithubFineGrainedToken => "github-fine-grained-token", 56 SecretRule::SlackToken => "slack-token", 57 SecretRule::SlackWebhook => "slack-webhook", 58 SecretRule::StripeLiveKey => "stripe-live-key", 59 SecretRule::AnthropicKey => "anthropic-key", 60 SecretRule::OpenAiKey => "openai-key", 61 SecretRule::SecretAssignment => "secret-assignment", 62 } 63 } 64 } 65 66 /// Where a rule matched. Carries no matched bytes. 67 #[derive(Debug, Clone, Copy, PartialEq, Eq)] 68 pub struct SecretFinding { 69 pub rule: SecretRule, 70 /// Byte offset of the start of the match inside the scanned input. 71 pub offset: usize, 72 } 73 74 /// Scan `bytes` and return the first finding, if any. 75 pub fn scan(bytes: &[u8]) -> Option { 76 Scanner::new(bytes).scan_all() 77 } 78 79 /// Scan and also return the number of byte inspections made, for the linear-time bound tests. 80 #[doc(hidden)] 81 pub fn scan_with_steps(bytes: &[u8]) -> (Option, u64) { 82 let mut s = Scanner::new(bytes); 83 let found = s.scan_all(); 84 (found, s.steps) 85 } 86 87 /// Refuse the admission if any blob matches a rule. The error never contains blob bytes. 88 pub fn check_blobs(blobs: &[(BlobDigest, Vec)]) -> SynapseResult<()> { 89 for (digest, bytes) in blobs { 90 if let Some(f) = scan(bytes) { 91 return Err(refusal(*digest, f)); 92 } 93 } 94 Ok(()) 95 } 96 97 fn refusal(digest: BlobDigest, f: SecretFinding) -> SynapseError { 98 SynapseError::new( 99 RefusalCode::SecretDetected, 100 format!( 101 "blob {digest} refused: matched secret rule {} (rule set v{}) at byte offset {}", 102 f.rule.id(), 103 SECRET_RULESET_VERSION, 104 f.offset 105 ), 106 ) 107 } 108 109 // Bounds on every window a rule walks. Each is a constant, so the work per position is bounded. 110 const PEM_LABEL_MAX: usize = 48; 111 const PEM_BODY_WINDOW: usize = 512; 112 const PEM_BODY_MIN: usize = 64; 113 const TOKEN_MAX: usize = 255; 114 const IDENT_MAX: usize = 64; 115 const SPACE_MAX: usize = 4; 116 const VALUE_MIN: usize = 20; 117 const VALUE_MAX: usize = 128; 118 119 const SECRET_NAMES: &[&[u8]] = &[ 120 b"secret", 121 b"token", 122 b"password", 123 b"passwd", 124 b"passphrase", 125 b"pwd", 126 b"apikey", 127 b"api_key", 128 b"api-key", 129 b"accesskey", 130 b"access_key", 131 b"access-key", 132 b"privatekey", 133 b"private_key", 134 b"private-key", 135 b"credential", 136 b"authkey", 137 b"auth_key", 138 ]; 139 140 const FAKE_MARKERS: &[&[u8]] = &[ 141 b"example", 142 b"fake", 143 b"dummy", 144 b"placeholder", 145 b"redacted", 146 b"changeme", 147 b"your", 148 b"xxxxxxxx", 149 ]; 150 151 fn is_tok(b: u8) -> bool { 152 b.is_ascii_alphanumeric() || b == b'_' || b == b'-' 153 } 154 fn is_upper_digit(b: u8) -> bool { 155 b.is_ascii_uppercase() || b.is_ascii_digit() 156 } 157 fn is_alnum_us(b: u8) -> bool { 158 b.is_ascii_alphanumeric() || b == b'_' 159 } 160 fn is_alnum_dash(b: u8) -> bool { 161 b.is_ascii_alphanumeric() || b == b'-' 162 } 163 fn is_b64(b: u8) -> bool { 164 b.is_ascii_alphanumeric() || b == b'+' || b == b'/' || b == b'=' 165 } 166 fn is_ident(b: u8) -> bool { 167 b.is_ascii_alphanumeric() || b == b'_' || b == b'-' || b == b'.' 168 } 169 fn is_value(b: u8) -> bool { 170 b.is_ascii_alphanumeric() || matches!(b, b'+' | b'/' | b'_' | b'-' | b'.') 171 } 172 fn is_space(b: u8) -> bool { 173 b == b' ' || b == b'\t' 174 } 175 fn is_quote(b: u8) -> bool { 176 b == b'"' || b == b'\'' || b == b'`' 177 } 178 179 fn contains_ci(hay: &[u8], needle: &[u8]) -> bool { 180 hay.len() >= needle.len() 181 && hay 182 .windows(needle.len()) 183 .any(|w| w.eq_ignore_ascii_case(needle)) 184 } 185 186 fn distinct_bytes(s: &[u8]) -> usize { 187 let mut seen = [false; 256]; 188 let mut n = 0; 189 for &b in s { 190 if !seen[b as usize] { 191 seen[b as usize] = true; 192 n += 1; 193 } 194 } 195 n 196 } 197 198 /// A clearly fake documentation value: a fake marker or too little character variety. 199 fn looks_fake(body: &[u8]) -> bool { 200 distinct_bytes(body) < 8 || FAKE_MARKERS.iter().any(|m| contains_ci(body, m)) 201 } 202 203 /// Shannon entropy in bits per byte. 204 fn entropy(s: &[u8]) -> f64 { 205 let mut counts = [0u32; 256]; 206 for &b in s { 207 counts[b as usize] += 1; 208 } 209 let n = s.len() as f64; 210 counts 211 .iter() 212 .filter(|&&c| c > 0) 213 .map(|&c| { 214 let p = f64::from(c) / n; 215 -p * p.log2() 216 }) 217 .sum() 218 } 219 220 struct Scanner<'a> { 221 b: &'a [u8], 222 steps: u64, 223 } 224 225 impl<'a> Scanner<'a> { 226 fn new(b: &'a [u8]) -> Self { 227 Self { b, steps: 0 } 228 } 229 230 fn at(&self, i: usize) -> Option { 231 self.b.get(i).copied() 232 } 233 234 fn lit(&mut self, i: usize, lit: &[u8]) -> bool { 235 self.steps += lit.len() as u64; 236 self.b.get(i..i + lit.len()) == Some(lit) 237 } 238 239 /// Length of the run of `pred` bytes from `i`, counting at most `cap + 1` bytes so callers 240 /// can tell a run longer than `cap`. 241 fn run(&mut self, i: usize, pred: fn(u8) -> bool, cap: usize) -> usize { 242 let end = self.b.len().min(i.saturating_add(cap + 1)); 243 let n = self 244 .b 245 .get(i..end) 246 .map_or(0, |w| w.iter().position(|&c| !pred(c)).unwrap_or(w.len())); 247 self.steps += n as u64 + 1; 248 n 249 } 250 251 fn left_boundary(&self, i: usize) -> bool { 252 i == 0 || !is_tok(self.b[i - 1]) 253 } 254 255 fn scan_all(&mut self) -> Option { 256 for i in 0..self.b.len() { 257 self.steps += 1; 258 let rule = match self.b[i] { 259 b'-' => self.pem(i), 260 b'A' => self.aws(i), 261 b'g' => self.github(i), 262 b'x' => self.slack(i), 263 b'h' => self.slack_webhook(i), 264 b's' | b'r' => self.sk(i), 265 b'=' | b':' => self.assignment(i), 266 _ => None, 267 }; 268 if let Some(rule) = rule { 269 return Some(SecretFinding { rule, offset: i }); 270 } 271 } 272 None 273 } 274 275 fn pem(&mut self, i: usize) -> Option { 276 if !self.lit(i, b"-----BEGIN ") { 277 return None; 278 } 279 let label_start = i + 11; 280 let label_len = self.run( 281 label_start, 282 |c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == b' ', 283 PEM_LABEL_MAX, 284 ); 285 if label_len > PEM_LABEL_MAX { 286 return None; 287 } 288 let label = &self.b[label_start..label_start + label_len]; 289 if !(label.ends_with(b"PRIVATE KEY") || label == b"PGP PRIVATE KEY BLOCK") { 290 return None; 291 } 292 let body_start = label_start + label_len; 293 if !self.lit(body_start, b"-----") { 294 return None; 295 } 296 let start = body_start + 5; 297 let end = self.b.len().min(start + PEM_BODY_WINDOW); 298 let window = &self.b[start..end]; 299 self.steps += window.len() as u64; 300 let mut b64 = 0usize; 301 let mut other = 0usize; 302 for &c in window { 303 match c { 304 b'-' => break, 305 b'\r' | b'\n' | b' ' | b'\t' => {} 306 c if is_b64(c) => b64 += 1, 307 _ => other += 1, 308 } 309 } 310 let body_ok = b64 >= PEM_BODY_MIN && other * 4 <= b64; 311 body_ok.then_some(SecretRule::PrivateKeyBlock) 312 } 313 314 fn aws(&mut self, i: usize) -> Option { 315 if !self.left_boundary(i) || !(self.lit(i, b"AKIA") || self.lit(i, b"ASIA")) { 316 return None; 317 } 318 let n = self.run(i + 4, is_upper_digit, 16); 319 if n != 16 || self.at(i + 20).is_some_and(|c| c.is_ascii_alphanumeric()) { 320 return None; 321 } 322 let body = &self.b[i + 4..i + 20]; 323 (!looks_fake(body)).then_some(SecretRule::AwsAccessKeyId) 324 } 325 326 fn github(&mut self, i: usize) -> Option { 327 if !self.left_boundary(i) { 328 return None; 329 } 330 if self.lit(i, b"github_pat_") { 331 let n = self.run(i + 11, is_alnum_us, TOKEN_MAX); 332 let body = &self.b[i + 11..i + 11 + n.min(TOKEN_MAX)]; 333 return ((80..=TOKEN_MAX).contains(&n) && !looks_fake(body)) 334 .then_some(SecretRule::GithubFineGrainedToken); 335 } 336 let prefix_ok = self.lit(i, b"gh") 337 && matches!(self.at(i + 2), Some(b'p' | b'o' | b'u' | b's' | b'r')) 338 && self.at(i + 3) == Some(b'_'); 339 if !prefix_ok { 340 return None; 341 } 342 let n = self.run(i + 4, |c| c.is_ascii_alphanumeric(), 36); 343 if n != 36 || self.at(i + 40).is_some_and(is_tok) { 344 return None; 345 } 346 (!looks_fake(&self.b[i + 4..i + 40])).then_some(SecretRule::GithubToken) 347 } 348 349 fn slack(&mut self, i: usize) -> Option { 350 let prefix_ok = self.left_boundary(i) 351 && self.lit(i, b"xox") 352 && matches!( 353 self.at(i + 3), 354 Some(b'b' | b'p' | b'a' | b'r' | b's' | b'o') 355 ) 356 && self.at(i + 4) == Some(b'-'); 357 if !prefix_ok { 358 return None; 359 } 360 let n = self.run(i + 5, is_alnum_dash, TOKEN_MAX); 361 if !(20..=TOKEN_MAX).contains(&n) { 362 return None; 363 } 364 let body = &self.b[i + 5..i + 5 + n]; 365 let dashes = body.iter().filter(|&&c| c == b'-').count(); 366 let digits = body.iter().filter(|c| c.is_ascii_digit()).count(); 367 (dashes >= 2 && digits >= 10 && !looks_fake(body)).then_some(SecretRule::SlackToken) 368 } 369 370 fn slack_webhook(&mut self, i: usize) -> Option { 371 const PREFIX: &[u8] = b"hooks.slack.com/services/"; 372 if !self.lit(i, PREFIX) { 373 return None; 374 } 375 let start = i + PREFIX.len(); 376 let n = self.run(start, |c| c.is_ascii_alphanumeric() || c == b'/', TOKEN_MAX); 377 if !(40..=TOKEN_MAX).contains(&n) { 378 return None; 379 } 380 let body = &self.b[start..start + n]; 381 let slashes = body.iter().filter(|&&c| c == b'/').count(); 382 (slashes >= 2 && !looks_fake(body)).then_some(SecretRule::SlackWebhook) 383 } 384 385 fn sk(&mut self, i: usize) -> Option { 386 if !self.left_boundary(i) { 387 return None; 388 } 389 if self.lit(i, b"sk_live_") || self.lit(i, b"rk_live_") { 390 let n = self.run(i + 8, |c| c.is_ascii_alphanumeric(), TOKEN_MAX); 391 let body = &self.b[i + 8..i + 8 + n.min(TOKEN_MAX)]; 392 return ((24..=TOKEN_MAX).contains(&n) && !looks_fake(body)) 393 .then_some(SecretRule::StripeLiveKey); 394 } 395 if !self.lit(i, b"sk-") { 396 return None; 397 } 398 let (rule, start, min) = if self.lit(i, b"sk-ant-") { 399 (SecretRule::AnthropicKey, i + 7, 32) 400 } else if self.lit(i, b"sk-proj-") || self.lit(i, b"sk-admin-") { 401 let len = if self.at(i + 3) == Some(b'p') { 8 } else { 9 }; 402 (SecretRule::OpenAiKey, i + len, 40) 403 } else if self.lit(i, b"sk-svcacct-") { 404 (SecretRule::OpenAiKey, i + 11, 40) 405 } else { 406 // Legacy OpenAI key: 48 alphanumerics with the base64 "OpenAI" marker inside. 407 let n = self.run(i + 3, |c| c.is_ascii_alphanumeric(), 48); 408 if n != 48 || self.at(i + 51).is_some_and(is_tok) { 409 return None; 410 } 411 let body = &self.b[i + 3..i + 51]; 412 return body 413 .windows(8) 414 .any(|w| w == b"T3BlbkFJ") 415 .then_some(SecretRule::OpenAiKey); 416 }; 417 let n = self.run(start, is_tok, TOKEN_MAX); 418 let body = &self.b[start..start + n.min(TOKEN_MAX)]; 419 ((min..=TOKEN_MAX).contains(&n) && !looks_fake(body)).then_some(rule) 420 } 421 422 /// `name = value`, `name: value`, `name := value`, `name => value`, with the name holding 423 /// a secret-like word and the value a high-entropy literal. 424 fn assignment(&mut self, i: usize) -> Option { 425 let op = self.b[i]; 426 let prev = if i > 0 { Some(self.b[i - 1]) } else { None }; 427 let next = self.at(i + 1); 428 self.steps += 2; 429 let mut name_end = i; 430 let mut value_from = i + 1; 431 if op == b':' { 432 // `:=` is handled at the `=`; `::` is a path separator. 433 if matches!(next, Some(b'=' | b':')) || prev == Some(b':') { 434 return None; 435 } 436 } else { 437 if next == Some(b'=') 438 || matches!( 439 prev, 440 Some( 441 b'=' | b'!' 442 | b'<' 443 | b'>' 444 | b'+' 445 | b'-' 446 | b'*' 447 | b'/' 448 | b'|' 449 | b'&' 450 | b'^' 451 | b'%' 452 ) 453 ) 454 { 455 return None; 456 } 457 if prev == Some(b':') { 458 name_end = i - 1; 459 } 460 if next == Some(b'>') { 461 value_from = i + 2; 462 } 463 } 464 465 // Name, walking back over a few spaces and one closing quote. 466 let mut j = name_end; 467 let mut k = 0; 468 while k < SPACE_MAX && j > 0 && is_space(self.b[j - 1]) { 469 j -= 1; 470 k += 1; 471 } 472 if j > 0 && is_quote(self.b[j - 1]) { 473 j -= 1; 474 } 475 let mut name_len = 0; 476 while name_len < IDENT_MAX && j > name_len && is_ident(self.b[j - 1 - name_len]) { 477 name_len += 1; 478 } 479 self.steps += (k + name_len + 1) as u64; 480 if name_len == 0 { 481 return None; 482 } 483 let name = &self.b[j - name_len..j]; 484 if !SECRET_NAMES.iter().any(|w| contains_ci(name, w)) { 485 return None; 486 } 487 488 // Value, after a few spaces and an optional opening quote. 489 let mut v = value_from + self.run(value_from, is_space, SPACE_MAX).min(SPACE_MAX); 490 let quote = self.at(v).filter(|&c| is_quote(c)); 491 if quote.is_some() { 492 v += 1; 493 } 494 let n = self.run(v, is_value, VALUE_MAX); 495 if !(VALUE_MIN..=VALUE_MAX).contains(&n) { 496 return None; 497 } 498 let value = &self.b[v..v + n]; 499 let mut after = v + n; 500 let pad = self.run(after, |c| c == b'=', 2).min(2); 501 after += pad; 502 match quote { 503 Some(q) if self.at(after) != Some(q) => return None, 504 None if matches!(self.at(after), Some(b'(' | b'[' | b'{' | b'<')) => return None, 505 _ => {} 506 } 507 self.steps += n as u64; 508 let has_digit = value.iter().any(|c| c.is_ascii_digit()); 509 let has_alpha = value.iter().any(|c| c.is_ascii_alphabetic()); 510 if !has_digit || !has_alpha || looks_fake(value) { 511 return None; 512 } 513 let h = entropy(value); 514 let hex = value.iter().all(|c| c.is_ascii_hexdigit()); 515 let strong = if hex { n >= 32 && h >= 3.0 } else { h >= 3.5 }; 516 strong.then_some(SecretRule::SecretAssignment) 517 } 518 }