diff --git a/crates/synapse-api/src/lib.rs b/crates/synapse-api/src/lib.rs index 71fa247..6ba8330 100644 --- a/crates/synapse-api/src/lib.rs +++ b/crates/synapse-api/src/lib.rs @@ -29,6 +29,7 @@ mod crumb; mod derivation; pub use derivation::ServiceDerivationTrees; mod evidence; +pub mod secret_scan; pub mod tree; pub use advisory::{ ChangesetAdvisory, ChangesetAdvisoryPayload, CoordinationStatus, GuidanceNote, @@ -632,6 +633,9 @@ impl SynapseService { req, now_ms, )?; + // Secret scanning (ADR 0003 section 5.13, step M1) runs here, before the store and the + // single writer, so a refused secret never reaches the WAL. + secret_scan::check_blobs(&req.payload.blobs)?; if req.payload.envelope.repo_id != self.repo_id { return Err(SynapseError::new( @@ -714,6 +718,7 @@ impl SynapseService { )); } let authority = admission_authority(req)?; + secret_scan::check_blobs(blobs)?; self.store .admit_revision(envelope, blobs, authority, now_ms) } diff --git a/crates/synapse-api/src/secret_scan.rs b/crates/synapse-api/src/secret_scan.rs new file mode 100644 index 0000000..f7e8f51 --- /dev/null +++ b/crates/synapse-api/src/secret_scan.rs @@ -0,0 +1,518 @@ +//! Secret scanning at admission (ADR 0003 section 5.13, step M1). +//! +//! Every blob an agent submits is scanned before the store sees it, so a refused secret never +//! reaches the WAL, the content store, an index, or a cache. A hit refuses the whole admission +//! with [`RefusalCode::SecretDetected`]. The refusal names the blob digest, the rule, the rule +//! set version, and the byte offset; it never contains the matched bytes, and this module keeps +//! no copy of them. +//! +//! The scanner is a hand-written single pass over raw bytes (binary safe, no UTF-8 +//! assumption, no regular expressions). Each position does a bounded amount of work, and the +//! windows that longer checks walk cannot overlap without bound, so time is linear in the input +//! length and memory is constant. The rule set is versioned data ([`SECRET_RULESET_VERSION`]). +//! +//! Policy (refuse by default): there is no allowlist and no override. Clearly fake +//! documentation values (`EXAMPLE`, `fake`, `your`, `xxxxxxxx`, very low character variety) are not +//! secrets and are admitted. + +use synapse_core::{BlobDigest, RefusalCode, SynapseError, SynapseResult}; + +/// Version of the rule set below. Bump it whenever a rule is added, removed, or changed. +pub const SECRET_RULESET_VERSION: u16 = 1; + +/// One rule of the secret-scanning rule set. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum SecretRule { + /// A PEM or OpenSSH private key block (`BEGIN ... PRIVATE KEY`) with a key body. + PrivateKeyBlock, + /// An AWS access key id (`AKIA` or `ASIA` plus 16 characters). + AwsAccessKeyId, + /// A GitHub classic token (`ghp_`, `gho_`, `ghu_`, `ghs_`, `ghr_`). + GithubToken, + /// A GitHub fine-grained personal access token (`github_pat_`). + GithubFineGrainedToken, + /// A Slack token (`xoxb-`, `xoxp-`, ...). + SlackToken, + /// A Slack incoming webhook URL. + SlackWebhook, + /// A Stripe live secret or restricted key. + StripeLiveKey, + /// An Anthropic API key (`sk-ant-`). + AnthropicKey, + /// An OpenAI API key (project, service account, admin, or legacy format). + OpenAiKey, + /// A high-entropy value assigned to a secret-like name (`token = "..."`). + SecretAssignment, +} + +impl SecretRule { + /// Stable identifier of the rule, used in refusal text. + pub fn id(self) -> &'static str { + match self { + SecretRule::PrivateKeyBlock => "private-key-block", + SecretRule::AwsAccessKeyId => "aws-access-key-id", + SecretRule::GithubToken => "github-token", + SecretRule::GithubFineGrainedToken => "github-fine-grained-token", + SecretRule::SlackToken => "slack-token", + SecretRule::SlackWebhook => "slack-webhook", + SecretRule::StripeLiveKey => "stripe-live-key", + SecretRule::AnthropicKey => "anthropic-key", + SecretRule::OpenAiKey => "openai-key", + SecretRule::SecretAssignment => "secret-assignment", + } + } +} + +/// Where a rule matched. Carries no matched bytes. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct SecretFinding { + pub rule: SecretRule, + /// Byte offset of the start of the match inside the scanned input. + pub offset: usize, +} + +/// Scan `bytes` and return the first finding, if any. +pub fn scan(bytes: &[u8]) -> Option { + Scanner::new(bytes).scan_all() +} + +/// Scan and also return the number of byte inspections made, for the linear-time bound tests. +#[doc(hidden)] +pub fn scan_with_steps(bytes: &[u8]) -> (Option, u64) { + let mut s = Scanner::new(bytes); + let found = s.scan_all(); + (found, s.steps) +} + +/// Refuse the admission if any blob matches a rule. The error never contains blob bytes. +pub fn check_blobs(blobs: &[(BlobDigest, Vec)]) -> SynapseResult<()> { + for (digest, bytes) in blobs { + if let Some(f) = scan(bytes) { + return Err(refusal(*digest, f)); + } + } + Ok(()) +} + +fn refusal(digest: BlobDigest, f: SecretFinding) -> SynapseError { + SynapseError::new( + RefusalCode::SecretDetected, + format!( + "blob {digest} refused: matched secret rule {} (rule set v{}) at byte offset {}", + f.rule.id(), + SECRET_RULESET_VERSION, + f.offset + ), + ) +} + +// Bounds on every window a rule walks. Each is a constant, so the work per position is bounded. +const PEM_LABEL_MAX: usize = 48; +const PEM_BODY_WINDOW: usize = 512; +const PEM_BODY_MIN: usize = 64; +const TOKEN_MAX: usize = 255; +const IDENT_MAX: usize = 64; +const SPACE_MAX: usize = 4; +const VALUE_MIN: usize = 20; +const VALUE_MAX: usize = 128; + +const SECRET_NAMES: &[&[u8]] = &[ + b"secret", + b"token", + b"password", + b"passwd", + b"passphrase", + b"pwd", + b"apikey", + b"api_key", + b"api-key", + b"accesskey", + b"access_key", + b"access-key", + b"privatekey", + b"private_key", + b"private-key", + b"credential", + b"authkey", + b"auth_key", +]; + +const FAKE_MARKERS: &[&[u8]] = &[ + b"example", + b"fake", + b"dummy", + b"placeholder", + b"redacted", + b"changeme", + b"your", + b"xxxxxxxx", +]; + +fn is_tok(b: u8) -> bool { + b.is_ascii_alphanumeric() || b == b'_' || b == b'-' +} +fn is_upper_digit(b: u8) -> bool { + b.is_ascii_uppercase() || b.is_ascii_digit() +} +fn is_alnum_us(b: u8) -> bool { + b.is_ascii_alphanumeric() || b == b'_' +} +fn is_alnum_dash(b: u8) -> bool { + b.is_ascii_alphanumeric() || b == b'-' +} +fn is_b64(b: u8) -> bool { + b.is_ascii_alphanumeric() || b == b'+' || b == b'/' || b == b'=' +} +fn is_ident(b: u8) -> bool { + b.is_ascii_alphanumeric() || b == b'_' || b == b'-' || b == b'.' +} +fn is_value(b: u8) -> bool { + b.is_ascii_alphanumeric() || matches!(b, b'+' | b'/' | b'_' | b'-' | b'.') +} +fn is_space(b: u8) -> bool { + b == b' ' || b == b'\t' +} +fn is_quote(b: u8) -> bool { + b == b'"' || b == b'\'' || b == b'`' +} + +fn contains_ci(hay: &[u8], needle: &[u8]) -> bool { + hay.len() >= needle.len() + && hay + .windows(needle.len()) + .any(|w| w.eq_ignore_ascii_case(needle)) +} + +fn distinct_bytes(s: &[u8]) -> usize { + let mut seen = [false; 256]; + let mut n = 0; + for &b in s { + if !seen[b as usize] { + seen[b as usize] = true; + n += 1; + } + } + n +} + +/// A clearly fake documentation value: a fake marker or too little character variety. +fn looks_fake(body: &[u8]) -> bool { + distinct_bytes(body) < 8 || FAKE_MARKERS.iter().any(|m| contains_ci(body, m)) +} + +/// Shannon entropy in bits per byte. +fn entropy(s: &[u8]) -> f64 { + let mut counts = [0u32; 256]; + for &b in s { + counts[b as usize] += 1; + } + let n = s.len() as f64; + counts + .iter() + .filter(|&&c| c > 0) + .map(|&c| { + let p = f64::from(c) / n; + -p * p.log2() + }) + .sum() +} + +struct Scanner<'a> { + b: &'a [u8], + steps: u64, +} + +impl<'a> Scanner<'a> { + fn new(b: &'a [u8]) -> Self { + Self { b, steps: 0 } + } + + fn at(&self, i: usize) -> Option { + self.b.get(i).copied() + } + + fn lit(&mut self, i: usize, lit: &[u8]) -> bool { + self.steps += lit.len() as u64; + self.b.get(i..i + lit.len()) == Some(lit) + } + + /// Length of the run of `pred` bytes from `i`, counting at most `cap + 1` bytes so callers + /// can tell a run longer than `cap`. + fn run(&mut self, i: usize, pred: fn(u8) -> bool, cap: usize) -> usize { + let end = self.b.len().min(i.saturating_add(cap + 1)); + let n = self + .b + .get(i..end) + .map_or(0, |w| w.iter().position(|&c| !pred(c)).unwrap_or(w.len())); + self.steps += n as u64 + 1; + n + } + + fn left_boundary(&self, i: usize) -> bool { + i == 0 || !is_tok(self.b[i - 1]) + } + + fn scan_all(&mut self) -> Option { + for i in 0..self.b.len() { + self.steps += 1; + let rule = match self.b[i] { + b'-' => self.pem(i), + b'A' => self.aws(i), + b'g' => self.github(i), + b'x' => self.slack(i), + b'h' => self.slack_webhook(i), + b's' | b'r' => self.sk(i), + b'=' | b':' => self.assignment(i), + _ => None, + }; + if let Some(rule) = rule { + return Some(SecretFinding { rule, offset: i }); + } + } + None + } + + fn pem(&mut self, i: usize) -> Option { + if !self.lit(i, b"-----BEGIN ") { + return None; + } + let label_start = i + 11; + let label_len = self.run( + label_start, + |c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == b' ', + PEM_LABEL_MAX, + ); + if label_len > PEM_LABEL_MAX { + return None; + } + let label = &self.b[label_start..label_start + label_len]; + if !(label.ends_with(b"PRIVATE KEY") || label == b"PGP PRIVATE KEY BLOCK") { + return None; + } + let body_start = label_start + label_len; + if !self.lit(body_start, b"-----") { + return None; + } + let start = body_start + 5; + let end = self.b.len().min(start + PEM_BODY_WINDOW); + let window = &self.b[start..end]; + self.steps += window.len() as u64; + let mut b64 = 0usize; + let mut other = 0usize; + for &c in window { + match c { + b'-' => break, + b'\r' | b'\n' | b' ' | b'\t' => {} + c if is_b64(c) => b64 += 1, + _ => other += 1, + } + } + let body_ok = b64 >= PEM_BODY_MIN && other * 4 <= b64; + body_ok.then_some(SecretRule::PrivateKeyBlock) + } + + fn aws(&mut self, i: usize) -> Option { + if !self.left_boundary(i) || !(self.lit(i, b"AKIA") || self.lit(i, b"ASIA")) { + return None; + } + let n = self.run(i + 4, is_upper_digit, 16); + if n != 16 || self.at(i + 20).is_some_and(|c| c.is_ascii_alphanumeric()) { + return None; + } + let body = &self.b[i + 4..i + 20]; + (!looks_fake(body)).then_some(SecretRule::AwsAccessKeyId) + } + + fn github(&mut self, i: usize) -> Option { + if !self.left_boundary(i) { + return None; + } + if self.lit(i, b"github_pat_") { + let n = self.run(i + 11, is_alnum_us, TOKEN_MAX); + let body = &self.b[i + 11..i + 11 + n.min(TOKEN_MAX)]; + return ((80..=TOKEN_MAX).contains(&n) && !looks_fake(body)) + .then_some(SecretRule::GithubFineGrainedToken); + } + let prefix_ok = self.lit(i, b"gh") + && matches!(self.at(i + 2), Some(b'p' | b'o' | b'u' | b's' | b'r')) + && self.at(i + 3) == Some(b'_'); + if !prefix_ok { + return None; + } + let n = self.run(i + 4, |c| c.is_ascii_alphanumeric(), 36); + if n != 36 || self.at(i + 40).is_some_and(is_tok) { + return None; + } + (!looks_fake(&self.b[i + 4..i + 40])).then_some(SecretRule::GithubToken) + } + + fn slack(&mut self, i: usize) -> Option { + let prefix_ok = self.left_boundary(i) + && self.lit(i, b"xox") + && matches!( + self.at(i + 3), + Some(b'b' | b'p' | b'a' | b'r' | b's' | b'o') + ) + && self.at(i + 4) == Some(b'-'); + if !prefix_ok { + return None; + } + let n = self.run(i + 5, is_alnum_dash, TOKEN_MAX); + if !(20..=TOKEN_MAX).contains(&n) { + return None; + } + let body = &self.b[i + 5..i + 5 + n]; + let dashes = body.iter().filter(|&&c| c == b'-').count(); + let digits = body.iter().filter(|c| c.is_ascii_digit()).count(); + (dashes >= 2 && digits >= 10 && !looks_fake(body)).then_some(SecretRule::SlackToken) + } + + fn slack_webhook(&mut self, i: usize) -> Option { + const PREFIX: &[u8] = b"hooks.slack.com/services/"; + if !self.lit(i, PREFIX) { + return None; + } + let start = i + PREFIX.len(); + let n = self.run(start, |c| c.is_ascii_alphanumeric() || c == b'/', TOKEN_MAX); + if !(40..=TOKEN_MAX).contains(&n) { + return None; + } + let body = &self.b[start..start + n]; + let slashes = body.iter().filter(|&&c| c == b'/').count(); + (slashes >= 2 && !looks_fake(body)).then_some(SecretRule::SlackWebhook) + } + + fn sk(&mut self, i: usize) -> Option { + if !self.left_boundary(i) { + return None; + } + if self.lit(i, b"sk_live_") || self.lit(i, b"rk_live_") { + let n = self.run(i + 8, |c| c.is_ascii_alphanumeric(), TOKEN_MAX); + let body = &self.b[i + 8..i + 8 + n.min(TOKEN_MAX)]; + return ((24..=TOKEN_MAX).contains(&n) && !looks_fake(body)) + .then_some(SecretRule::StripeLiveKey); + } + if !self.lit(i, b"sk-") { + return None; + } + let (rule, start, min) = if self.lit(i, b"sk-ant-") { + (SecretRule::AnthropicKey, i + 7, 32) + } else if self.lit(i, b"sk-proj-") || self.lit(i, b"sk-admin-") { + let len = if self.at(i + 3) == Some(b'p') { 8 } else { 9 }; + (SecretRule::OpenAiKey, i + len, 40) + } else if self.lit(i, b"sk-svcacct-") { + (SecretRule::OpenAiKey, i + 11, 40) + } else { + // Legacy OpenAI key: 48 alphanumerics with the base64 "OpenAI" marker inside. + let n = self.run(i + 3, |c| c.is_ascii_alphanumeric(), 48); + if n != 48 || self.at(i + 51).is_some_and(is_tok) { + return None; + } + let body = &self.b[i + 3..i + 51]; + return body + .windows(8) + .any(|w| w == b"T3BlbkFJ") + .then_some(SecretRule::OpenAiKey); + }; + let n = self.run(start, is_tok, TOKEN_MAX); + let body = &self.b[start..start + n.min(TOKEN_MAX)]; + ((min..=TOKEN_MAX).contains(&n) && !looks_fake(body)).then_some(rule) + } + + /// `name = value`, `name: value`, `name := value`, `name => value`, with the name holding + /// a secret-like word and the value a high-entropy literal. + fn assignment(&mut self, i: usize) -> Option { + let op = self.b[i]; + let prev = if i > 0 { Some(self.b[i - 1]) } else { None }; + let next = self.at(i + 1); + self.steps += 2; + let mut name_end = i; + let mut value_from = i + 1; + if op == b':' { + // `:=` is handled at the `=`; `::` is a path separator. + if matches!(next, Some(b'=' | b':')) || prev == Some(b':') { + return None; + } + } else { + if next == Some(b'=') + || matches!( + prev, + Some( + b'=' | b'!' + | b'<' + | b'>' + | b'+' + | b'-' + | b'*' + | b'/' + | b'|' + | b'&' + | b'^' + | b'%' + ) + ) + { + return None; + } + if prev == Some(b':') { + name_end = i - 1; + } + if next == Some(b'>') { + value_from = i + 2; + } + } + + // Name, walking back over a few spaces and one closing quote. + let mut j = name_end; + let mut k = 0; + while k < SPACE_MAX && j > 0 && is_space(self.b[j - 1]) { + j -= 1; + k += 1; + } + if j > 0 && is_quote(self.b[j - 1]) { + j -= 1; + } + let mut name_len = 0; + while name_len < IDENT_MAX && j > name_len && is_ident(self.b[j - 1 - name_len]) { + name_len += 1; + } + self.steps += (k + name_len + 1) as u64; + if name_len == 0 { + return None; + } + let name = &self.b[j - name_len..j]; + if !SECRET_NAMES.iter().any(|w| contains_ci(name, w)) { + return None; + } + + // Value, after a few spaces and an optional opening quote. + let mut v = value_from + self.run(value_from, is_space, SPACE_MAX).min(SPACE_MAX); + let quote = self.at(v).filter(|&c| is_quote(c)); + if quote.is_some() { + v += 1; + } + let n = self.run(v, is_value, VALUE_MAX); + if !(VALUE_MIN..=VALUE_MAX).contains(&n) { + return None; + } + let value = &self.b[v..v + n]; + let mut after = v + n; + let pad = self.run(after, |c| c == b'=', 2).min(2); + after += pad; + match quote { + Some(q) if self.at(after) != Some(q) => return None, + None if matches!(self.at(after), Some(b'(' | b'[' | b'{' | b'<')) => return None, + _ => {} + } + self.steps += n as u64; + let has_digit = value.iter().any(|c| c.is_ascii_digit()); + let has_alpha = value.iter().any(|c| c.is_ascii_alphabetic()); + if !has_digit || !has_alpha || looks_fake(value) { + return None; + } + let h = entropy(value); + let hex = value.iter().all(|c| c.is_ascii_hexdigit()); + let strong = if hex { n >= 32 && h >= 3.0 } else { h >= 3.5 }; + strong.then_some(SecretRule::SecretAssignment) + } +} diff --git a/crates/synapse-api/tests/m1_secret_scan.rs b/crates/synapse-api/tests/m1_secret_scan.rs new file mode 100644 index 0000000..e6c58d1 --- /dev/null +++ b/crates/synapse-api/tests/m1_secret_scan.rs @@ -0,0 +1,596 @@ +//! ADR 0003 step M1: secret scanning at admission (section 5.13). +//! +//! Every planted secret below is assembled at run time from split pieces and a deterministic +//! generator, so this file itself holds no complete token and no real key. Values used as +//! negatives are clearly fake documentation examples. + +use ed25519_dalek::SigningKey; +use sha2::{Digest, Sha256}; +use std::path::{Path, PathBuf}; +use std::time::{Duration, Instant}; +use synapse_api::secret_scan::{ + check_blobs, scan, scan_with_steps, SecretRule, SECRET_RULESET_VERSION, +}; +use synapse_api::{SubmitChangesetPayload, SynapseService, TreeTarget}; +use synapse_auth::{ + AgentCapabilityGrant, AuthenticatedRequest, Capability, CapabilityChain, CapabilityLink, + ChainQuotas, ChainedRequest, ChangeScope, LinkCaveats, OperationSet, PathScope, ReferenceKind, + ReferenceScope, RequestScope, ROOT_PARENT, +}; +use synapse_core::{ + encode_did_key_ed25519, BlobDigest, ChangeId, ChangesetEnvelope, ChangesetEnvelopeV2, FileMode, + GitOid, IdempotencyKey, MutationOp, PathMutation, RefusalCode, RepoId, RevisionContent, WalSeq, + SYNAPSE_ENVELOPE_VERSION, +}; +use synapse_store::{FsyncPolicy, IngestOutcome, RecoveryPolicy, StoreLimits}; + +/// Deterministic xorshift generator for token bodies. +struct Gen(u64); + +impl Gen { + fn next(&mut self) -> u64 { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + self.0 + } + fn from(&mut self, alphabet: &[u8], n: usize) -> String { + (0..n) + .map(|_| alphabet[(self.next() % alphabet.len() as u64) as usize] as char) + .collect() + } +} + +const ALNUM: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; +const UPPER_DIGIT: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; +const DIGITS: &[u8] = b"0123456789"; +const B64: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + +/// `(rule, secret)` pairs; each secret is the exact sensitive span. +fn planted() -> Vec<(SecretRule, String)> { + let mut g = Gen(0x9E37_79B9_7F4A_7C15); + let dash5 = "-".repeat(5); + let pem = |label: &str, g: &mut Gen| { + let body: Vec = (0..6).map(|_| g.from(B64, 64)).collect(); + format!( + "{dash5}{} {label}{dash5}\n{}\n{dash5}END {label}{dash5}\n", + "BEGIN", + body.join("\n") + ) + }; + let rsa = pem(&["RSA", "PRIVATE", "KEY"].join(" "), &mut g); + let openssh = pem(&["OPENSSH", "PRIVATE", "KEY"].join(" "), &mut g); + let pkcs8 = pem(&["PRIVATE", "KEY"].join(" "), &mut g); + vec![ + (SecretRule::PrivateKeyBlock, rsa), + (SecretRule::PrivateKeyBlock, openssh), + (SecretRule::PrivateKeyBlock, pkcs8), + ( + SecretRule::AwsAccessKeyId, + format!("{}{}", ["AK", "IA"].concat(), g.from(UPPER_DIGIT, 16)), + ), + ( + SecretRule::AwsAccessKeyId, + format!("{}{}", ["AS", "IA"].concat(), g.from(UPPER_DIGIT, 16)), + ), + ( + SecretRule::GithubToken, + format!("{}{}", ["gh", "p_"].concat(), g.from(ALNUM, 36)), + ), + ( + SecretRule::GithubToken, + format!("{}{}", ["gh", "s_"].concat(), g.from(ALNUM, 36)), + ), + ( + SecretRule::GithubFineGrainedToken, + format!( + "{}{}_{}", + ["github", "_pat_"].concat(), + g.from(ALNUM, 22), + g.from(ALNUM, 59) + ), + ), + ( + SecretRule::SlackToken, + format!( + "{}{}-{}-{}", + ["xo", "xb-"].concat(), + g.from(DIGITS, 12), + g.from(DIGITS, 13), + g.from(ALNUM, 24) + ), + ), + ( + SecretRule::SlackWebhook, + format!( + "https://{}T{}/B{}/{}", + ["hooks.", "slack.com/services/"].concat(), + g.from(UPPER_DIGIT, 10), + g.from(UPPER_DIGIT, 10), + g.from(ALNUM, 24) + ), + ), + ( + SecretRule::StripeLiveKey, + format!("{}{}", ["sk_", "live_"].concat(), g.from(ALNUM, 32)), + ), + ( + SecretRule::AnthropicKey, + format!("{}api03-{}", ["sk-", "ant-"].concat(), g.from(ALNUM, 93)), + ), + ( + SecretRule::OpenAiKey, + format!("{}{}", ["sk-", "proj-"].concat(), g.from(ALNUM, 64)), + ), + ( + SecretRule::OpenAiKey, + format!( + "sk-{}{}{}", + g.from(ALNUM, 20), + ["T3Blbk", "FJ"].concat(), + g.from(ALNUM, 20) + ), + ), + (SecretRule::SecretAssignment, g.from(ALNUM, 40)), + ] +} + +/// The planted secret placed in a realistic source context. +fn in_context(rule: SecretRule, secret: &str) -> Vec { + match rule { + SecretRule::SecretAssignment => { + format!("fn main() {{\n let db_password = \"{secret}\";\n}}\n").into_bytes() + } + SecretRule::PrivateKeyBlock => format!("# deploy key\n{secret}").into_bytes(), + _ => { + format!("config:\n endpoint: https://api.local\n upstream: '{secret}'\n").into_bytes() + } + } +} + +#[test] +fn m1_every_planted_secret_is_found_by_its_rule() { + for (rule, secret) in planted() { + let blob = in_context(rule, &secret); + let f = scan(&blob).unwrap_or_else(|| panic!("{} not found", rule.id())); + if rule != SecretRule::SecretAssignment { + assert_eq!(f.rule, rule, "rule for {}", rule.id()); + } + // Binary context: the secret between non-text bytes is still found. + let mut bin = vec![0u8, 0xFF, 0x80, b'\n']; + bin.extend_from_slice(secret.as_bytes()); + bin.extend_from_slice(&[0u8, 0xFE]); + if rule != SecretRule::SecretAssignment { + assert_eq!( + scan(&bin).map(|f| f.rule), + Some(rule), + "binary {}", + rule.id() + ); + } + } +} + +#[test] +fn m1_assignment_forms_are_found() { + let mut g = Gen(7); + let v = g.from(ALNUM, 32); + let hex = g.from(b"0123456789abcdef", 64); + for text in [ + format!("API_KEY={v}\n"), + format!("export GITHUB_TOKEN={v}\n"), + format!("{{\"client_secret\": \"{v}\"}}"), + format!("password := \"{v}\""), + format!("auth_token => '{v}',"), + format!("secret: {hex}\n"), + ] { + assert_eq!( + scan(text.as_bytes()).map(|f| f.rule), + Some(SecretRule::SecretAssignment), + "{text}" + ); + } +} + +#[test] +fn m1_lookalikes_and_marked_fake_examples_are_admitted() { + let dash5 = "-".repeat(5); + let negatives: Vec = vec![ + // AWS documentation example key id (clearly fake: ends in EXAMPLE). + format!("{}IOSFODNN7EXAMPLE", ["AK", "IA"].concat()), + // Placeholder GitHub token from docs. + format!("{}{}", ["gh", "p_"].concat(), "x".repeat(36)), + // Wrong length and prefix glued to a word. + format!("{}abc123", ["gh", "p_"].concat()), + format!( + "my{}{}", + ["gh", "p_"].concat(), + "A1b2C3d4E5f6G7h8I9j0K1l2M3n4O5p6Q7r8" + ), + // Stripe test keys are not live keys. + format!( + "{}{}", + ["sk_", "test_"].concat(), + "4eC39HqLyjWDarjtT1zdp7dc" + ), + // A PEM header in prose with no key body, and a public key block. + format!("{dash5}BEGIN RSA PRIVATE KEY{dash5}\n...\n{dash5}END RSA PRIVATE KEY{dash5}"), + format!( + "{dash5}BEGIN PUBLIC KEY{dash5}\n{}\n", + "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA".repeat(3) + ), + // Assignments that are not literal secrets. + "let token = generate_token_v2(seed_1234567890abcdef);".into(), + "password = \"${DB_PASSWORD_FROM_ENVIRONMENT_1}\"".into(), + "pub token: String,\n secret: [u8; 32],".into(), + "api_key = \"your-api-key-goes-here-123\"".into(), + "client_secret = \"EXAMPLE0123456789abcdefEXAMPLE\"".into(), + "if token == expected_token_value_1234 {}".into(), + "let tokens = Vec::::with_capacity(1024);".into(), + // High-entropy values under names that are not secret-like. + "digest = \"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\"".into(), + "commit: 2f06c45a1b2c3d4e5f60718293a4b5c6d7e8f901".into(), + // Rust paths with `::`. + "synapse_api::secret_scan::check_blobs(&blobs)?;".into(), + // A short hex value named token. + "token = \"deadbeef12345678\"".into(), + ]; + for n in &negatives { + assert_eq!(scan(n.as_bytes()), None, "false refusal: {n}"); + } +} + +#[test] +fn m1_refusal_names_rule_and_never_echoes_secret_bytes() { + for (rule, secret) in planted() { + let blob = in_context(rule, &secret); + let digest = BlobDigest::compute(&blob); + let ok = BlobDigest::compute(b"clean"); + let err = check_blobs(&[(ok, b"clean".to_vec()), (digest, blob)]).unwrap_err(); + assert_eq!(err.code, RefusalCode::SecretDetected); + let rendered = format!("{err} {err:?}"); + assert!(rendered.contains(&digest.to_string())); + assert!(rendered.contains(&format!("v{SECRET_RULESET_VERSION}"))); + // No 8-byte window of the secret appears in any rendering of the refusal. + let s = secret.as_bytes(); + for w in s.windows(8) { + let w = String::from_utf8_lossy(w); + if w.contains('-') || w.contains('\n') { + continue; // PEM framing is not secret material. + } + assert!(!rendered.contains(&*w), "{} leaked into refusal", rule.id()); + } + } +} + +/// Inputs built to make naive or backtracking matchers blow up: every trigger byte repeated, +/// near-miss prefixes, and long runs that stop one byte short of a match. +fn adversarial(len: usize) -> Vec> { + let dash5 = "-".repeat(5); + let units: Vec = vec![ + format!("{dash5}BEGIN RSA PRIVATE KEY{dash5}\n"), + format!("{dash5}BEGIN "), + "-".into(), + ["AK", "IA"].concat(), + ["gh", "p_"].concat(), + ["github", "_pat_"].concat(), + format!("{}1-", ["xo", "xb-"].concat()), + ["sk-", "ant-"].concat(), + "sk-".into(), + "token=".into(), + "password:".into(), + "a=".into(), + "=".into(), + ":".into(), + format!("secret_token = \"{}\"\n", "Ab1".repeat(50)), + format!("api_key={}", "Z9".repeat(64)), + "hooks.slack.com/services/".into(), + ]; + let mut out: Vec> = units + .iter() + .map(|u| u.as_bytes().iter().copied().cycle().take(len).collect()) + .collect(); + out.push(vec![b'a'; len]); + out.push(vec![0u8; len]); + let mut g = Gen(42); + out.push((0..len).map(|_| g.next() as u8).collect()); + out +} + +#[test] +fn m1_adversarial_input_is_linear_in_time_and_steps() { + const LEN: usize = 1 << 22; // 4 MiB per input + const STEPS_PER_BYTE: u64 = 64; + for input in adversarial(LEN) { + let t = Instant::now(); + let (_, steps) = scan_with_steps(&input); + let took = t.elapsed(); + assert!( + steps <= STEPS_PER_BYTE * input.len() as u64, + "{steps} steps for {} bytes", + input.len() + ); + // Generous wall-clock ceiling for an unoptimized test build. + assert!(took < Duration::from_secs(10), "took {took:?}"); + // Doubling the input at most doubles the work (plus a constant). + let half = &input[..LEN / 2]; + let (_, half_steps) = scan_with_steps(half); + assert!(steps <= 2 * half_steps + 65_536, "{steps} vs {half_steps}"); + } +} + +fn source_files(dir: &Path, out: &mut Vec) { + let Ok(rd) = std::fs::read_dir(dir) else { + return; + }; + for e in rd.flatten() { + let p = e.path(); + let name = e.file_name(); + if name == "target" || name.to_string_lossy().starts_with('.') { + continue; + } + if p.is_dir() { + source_files(&p, out); + } else if matches!( + p.extension().and_then(|x| x.to_str()), + Some("rs" | "md" | "toml" | "sh" | "json") + ) { + out.push(p); + } + } +} + +/// Real AIEN source without secrets: this repository's own crates, docs, and scripts. The +/// false-refusal count is printed and must be zero. +#[test] +fn m1_real_aien_source_is_admitted_with_zero_false_refusals() { + let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../.."); + let mut files = Vec::new(); + for d in ["crates", "docs", "scripts"] { + source_files(&root.join(d), &mut files); + } + files.sort(); + assert!(files.len() > 50, "corpus too small: {}", files.len()); + let mut bytes = 0usize; + let mut refused = Vec::new(); + let t = Instant::now(); + for f in &files { + let data = std::fs::read(f).unwrap(); + bytes += data.len(); + if let Some(found) = scan(&data) { + refused.push(format!( + "{} ({} @ {})", + f.display(), + found.rule.id(), + found.offset + )); + } + } + let secs = t.elapsed().as_secs_f64(); + println!( + "m1 corpus: {} files, {} bytes, {} false refusals, {:.6} s scan (debug build)", + files.len(), + bytes, + refused.len(), + secs + ); + assert!(refused.is_empty(), "false refusals: {refused:#?}"); +} + +fn temp_dir(label: &str) -> PathBuf { + std::env::temp_dir().join(format!( + "synapse-m1-{label}-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )) +} + +fn repo() -> RepoId { + RepoId::new("aien-spark/synapse").unwrap() +} + +/// Link nonces for one fixture: SHA-256 of the fixture label and a counter, so every link +/// gets a fresh nonce and none is a fixed value (same shape as b4_revision_states). +fn link_nonces(label: &str) -> impl FnMut() -> [u8; 32] { + let seed = label.to_owned(); + let mut issued = 0u32; + move || { + issued += 1; + let mut h = Sha256::new(); + h.update(seed.as_bytes()); + h.update(issued.to_le_bytes()); + h.finalize().into() + } +} + +fn open(label: &str) -> SynapseService { + SynapseService::open( + temp_dir(label), + repo(), + FsyncPolicy::EveryCommit, + RecoveryPolicy::StrictFailClosed, + StoreLimits { + wal_prealloc_bytes: 64 * 1024, + ..Default::default() + }, + ) + .unwrap() +} + +/// Envelope v1 `submit`: a blob with a secret is refused before any WAL write; a clean blob +/// in the same service is then admitted. +#[test] +fn m1_submit_refuses_secret_blob_before_any_wal_write() { + let mut svc = open("submit"); + let auth = SigningKey::from_bytes(&[10; 32]); + svc.register_authority(encode_did_key_ed25519(&auth.verifying_key().to_bytes())); + let agent = SigningKey::from_bytes(&[20; 32]); + let agent_did = encode_did_key_ed25519(&agent.verifying_key().to_bytes()); + let base = GitOid::compute_blob(b"base"); + svc.register_base_tree( + base, + vec![("README.md".into(), FileMode::Regular644, b"base".to_vec())], + ) + .unwrap(); + let grant = AgentCapabilityGrant::issue( + &auth, + [1; 32], + repo(), + agent_did, + vec![Capability::Read, Capability::Propose], + 1 << 20, + 100, + 60_000, + 10, + 100_000, + ); + let request = |body: &[u8], n: u8| { + let digest = BlobDigest::compute(body); + let mut env = ChangesetEnvelope { + version: SYNAPSE_ENVELOPE_VERSION, + repo_id: repo(), + base_git_oid: base, + parent_changesets: vec![], + author_did: String::new(), + idempotency_key: IdempotencyKey([n; 32]), + created_at_ms: 100, + intent_summary: "edit config".into(), + mutations: vec![PathMutation { + path: "src/config.rs".into(), + op: MutationOp::Upsert { + mode: FileMode::Regular644, + blob_digest: digest, + size_bytes: body.len() as u64, + }, + }], + evidence_receipts: vec![], + signature: vec![], + }; + env.sign(&agent); + AuthenticatedRequest::sign_new( + &agent, + grant.clone(), + repo(), + Capability::Propose, + [n; 32], + 100, + 0, + SubmitChangesetPayload { + envelope: env, + blobs: vec![(digest, body.to_vec())], + }, + ) + .unwrap() + }; + let before = svc.store().committed_seq(); + for (i, (rule, secret)) in planted().into_iter().enumerate() { + let body = in_context(rule, &secret); + let err = svc.submit(&request(&body, 100 + i as u8), 100).unwrap_err(); + assert_eq!(err.code, RefusalCode::SecretDetected, "{}", rule.id()); + assert!(!err.message.contains(&secret)); + assert_eq!(svc.store().committed_seq(), before, "WAL advanced"); + assert!(svc + .read_blob_bytes(BlobDigest::compute(&body), None) + .is_err()); + } + let clean = b"pub fn port() -> u16 { 8080 }\n"; + let out = svc.submit(&request(clean, 1), 100).unwrap(); + assert!(matches!(out, IngestOutcome::Committed { .. })); + assert!(svc.store().committed_seq() > before); +} + +/// Envelope v2 `submit_revision` under an F1 chain: the same refusal, no WAL write. +#[test] +fn m1_submit_revision_refuses_secret_blob_before_any_wal_write() { + const NOW: u64 = 2_000; + const C: ChangeId = ChangeId([0xC1; 16]); + let mut svc = open("revision"); + let a = SigningKey::from_bytes(&[1; 32]); + let o = SigningKey::from_bytes(&[2; 32]); + svc.auth_mut().register_repo_authority( + repo(), + encode_did_key_ed25519(&a.verifying_key().to_bytes()), + ); + let caveats = LinkCaveats { + operations: OperationSet::from_capabilities(&[Capability::Read, Capability::Propose]), + paths: PathScope::whole_repository(), + references: ReferenceScope::from_kinds(&[ReferenceKind::OwnDrafts]), + changes: ChangeScope::any(), + quotas: ChainQuotas { + max_ops_per_window: 1_000, + window_duration_ms: 60_000, + storage_bytes: 1 << 30, + footprint_paths: 1 << 20, + max_bytes_per_op: 1 << 20, + }, + issued_at_ms: 1_000, + expires_at_ms: 100_000, + }; + let link = CapabilityLink::issue( + &a, + ROOT_PARENT, + link_nonces("revision")(), + repo(), + o.verifying_key().to_bytes(), + caveats, + ); + let chain = CapabilityChain::new(vec![link]); + svc.auth_mut().grant_link(&chain, WalSeq(0), NOW).unwrap(); + let base_oid = GitOid([0x0B; 20]); + svc.register_base_tree( + base_oid, + vec![("README.md".into(), FileMode::Regular644, b"base".to_vec())], + ) + .unwrap(); + let base = svc + .tree_digest(TreeTarget::BaseGitCommit(base_oid), None) + .unwrap(); + let mut submit = |body: &[u8], n: u8| { + let content = RevisionContent { + change_id: C, + base_tree: base, + parents: vec![], + mutations: vec![PathMutation { + path: "src/lib.rs".into(), + op: MutationOp::Upsert { + mode: FileMode::Regular644, + blob_digest: BlobDigest::compute(body), + size_bytes: body.len() as u64, + }, + }], + intent_summary: "implement the task".into(), + }; + let env = ChangesetEnvelopeV2::sign_new(&o, repo(), content, IdempotencyKey([n; 32]), NOW); + let req = ChainedRequest::sign_new( + &o, + chain.clone(), + repo(), + Capability::Propose, + RequestScope { + paths: vec!["src/lib.rs".into()], + reference: None, + join_change: Some(C), + }, + [n; 32], + NOW, + env.encode(), + ); + let blobs = vec![(BlobDigest::compute(body), body.to_vec())]; + let before = svc.store().committed_seq(); + let r = svc.submit_revision(&req, &blobs, NOW); + (r.map(|_| ()), before, svc.store().committed_seq()) + }; + let (rule, secret) = planted().swap_remove(5); + let body = in_context(rule, &secret); + let (r, before, after) = submit(&body, 7); + let err = r.unwrap_err(); + assert_eq!(err.code, RefusalCode::SecretDetected); + assert!(!err.message.contains(&secret)); + assert_eq!(before, after, "WAL advanced on a refused secret"); + let (r, before, after) = submit(b"pub fn ok() {}\n", 8); + r.unwrap(); + assert!(after > before); +} diff --git a/crates/synapse-core/src/lib.rs b/crates/synapse-core/src/lib.rs index 4bceed1..61eb612 100644 --- a/crates/synapse-core/src/lib.rs +++ b/crates/synapse-core/src/lib.rs @@ -188,6 +188,13 @@ pub enum RefusalCode { RadicleQuorumInsufficient, StaleBaseHead, SplitBrainDivergence, + + // Content admission refusals + /// An admitted blob matches a rule of the versioned secret-scanning rule set (a private key + /// block, a provider token format, or a high-entropy value assigned to a secret-like name). + /// The refusal names the rule and byte offset only, never the matched bytes (ADR 0003 + /// section 5.13, step M1). + SecretDetected, } /// Structured error pairing a deterministic `RefusalCode` with diagnostic context.