synapse
A component of the AienOS ecosystem.
Brought by drakestapleton
synapse / crates / synapse-api / tests / m1_secret_scan.rs
| 1 | //! ADR 0003 step M1: secret scanning at admission (section 5.13). |
| 2 | //! |
| 3 | //! Every planted secret below is assembled at run time from split pieces and a deterministic |
| 4 | //! generator, so this file itself holds no complete token and no real key. Values used as |
| 5 | //! negatives are clearly fake documentation examples. |
| 6 | |
| 7 | use ed25519_dalek::SigningKey; |
| 8 | use sha2::{Digest, Sha256}; |
| 9 | use std::path::{Path, PathBuf}; |
| 10 | use std::time::{Duration, Instant}; |
| 11 | use synapse_api::secret_scan::{ |
| 12 | check_blobs, scan, scan_with_steps, SecretRule, SECRET_RULESET_VERSION, |
| 13 | }; |
| 14 | use synapse_api::{SubmitChangesetPayload, SynapseService, TreeTarget}; |
| 15 | use synapse_auth::{ |
| 16 | AgentCapabilityGrant, AuthenticatedRequest, Capability, CapabilityChain, CapabilityLink, |
| 17 | ChainQuotas, ChainedRequest, ChangeScope, LinkCaveats, OperationSet, PathScope, ReferenceKind, |
| 18 | ReferenceScope, RequestScope, ROOT_PARENT, |
| 19 | }; |
| 20 | use synapse_core::{ |
| 21 | encode_did_key_ed25519, BlobDigest, ChangeId, ChangesetEnvelope, ChangesetEnvelopeV2, FileMode, |
| 22 | GitOid, IdempotencyKey, MutationOp, PathMutation, RefusalCode, RepoId, RevisionContent, WalSeq, |
| 23 | SYNAPSE_ENVELOPE_VERSION, |
| 24 | }; |
| 25 | use synapse_store::{FsyncPolicy, IngestOutcome, RecoveryPolicy, StoreLimits}; |
| 26 | |
| 27 | /// Deterministic xorshift generator for token bodies. |
| 28 | struct Gen(u64); |
| 29 | |
| 30 | impl Gen { |
| 31 | fn next(&mut self) -> u64 { |
| 32 | self.0 ^= self.0 << 13; |
| 33 | self.0 ^= self.0 >> 7; |
| 34 | self.0 ^= self.0 << 17; |
| 35 | self.0 |
| 36 | } |
| 37 | fn from(&mut self, alphabet: &[u8], n: usize) -> String { |
| 38 | (0..n) |
| 39 | .map(|_| alphabet[(self.next() % alphabet.len() as u64) as usize] as char) |
| 40 | .collect() |
| 41 | } |
| 42 | } |
| 43 | |
| 44 | const ALNUM: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; |
| 45 | const UPPER_DIGIT: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; |
| 46 | const DIGITS: &[u8] = b"0123456789"; |
| 47 | const B64: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; |
| 48 | |
| 49 | /// `(rule, secret)` pairs; each secret is the exact sensitive span. |
| 50 | fn planted() -> Vec<(SecretRule, String)> { |
| 51 | let mut g = Gen(0x9E37_79B9_7F4A_7C15); |
| 52 | let dash5 = "-".repeat(5); |
| 53 | let pem = |label: &str, g: &mut Gen| { |
| 54 | let body: Vec<String> = (0..6).map(|_| g.from(B64, 64)).collect(); |
| 55 | format!( |
| 56 | "{dash5}{} {label}{dash5}\n{}\n{dash5}END {label}{dash5}\n", |
| 57 | "BEGIN", |
| 58 | body.join("\n") |
| 59 | ) |
| 60 | }; |
| 61 | let rsa = pem(&["RSA", "PRIVATE", "KEY"].join(" "), &mut g); |
| 62 | let openssh = pem(&["OPENSSH", "PRIVATE", "KEY"].join(" "), &mut g); |
| 63 | let pkcs8 = pem(&["PRIVATE", "KEY"].join(" "), &mut g); |
| 64 | vec![ |
| 65 | (SecretRule::PrivateKeyBlock, rsa), |
| 66 | (SecretRule::PrivateKeyBlock, openssh), |
| 67 | (SecretRule::PrivateKeyBlock, pkcs8), |
| 68 | ( |
| 69 | SecretRule::AwsAccessKeyId, |
| 70 | format!("{}{}", ["AK", "IA"].concat(), g.from(UPPER_DIGIT, 16)), |
| 71 | ), |
| 72 | ( |
| 73 | SecretRule::AwsAccessKeyId, |
| 74 | format!("{}{}", ["AS", "IA"].concat(), g.from(UPPER_DIGIT, 16)), |
| 75 | ), |
| 76 | ( |
| 77 | SecretRule::GithubToken, |
| 78 | format!("{}{}", ["gh", "p_"].concat(), g.from(ALNUM, 36)), |
| 79 | ), |
| 80 | ( |
| 81 | SecretRule::GithubToken, |
| 82 | format!("{}{}", ["gh", "s_"].concat(), g.from(ALNUM, 36)), |
| 83 | ), |
| 84 | ( |
| 85 | SecretRule::GithubFineGrainedToken, |
| 86 | format!( |
| 87 | "{}{}_{}", |
| 88 | ["github", "_pat_"].concat(), |
| 89 | g.from(ALNUM, 22), |
| 90 | g.from(ALNUM, 59) |
| 91 | ), |
| 92 | ), |
| 93 | ( |
| 94 | SecretRule::SlackToken, |
| 95 | format!( |
| 96 | "{}{}-{}-{}", |
| 97 | ["xo", "xb-"].concat(), |
| 98 | g.from(DIGITS, 12), |
| 99 | g.from(DIGITS, 13), |
| 100 | g.from(ALNUM, 24) |
| 101 | ), |
| 102 | ), |
| 103 | ( |
| 104 | SecretRule::SlackWebhook, |
| 105 | format!( |
| 106 | "https://{}T{}/B{}/{}", |
| 107 | ["hooks.", "slack.com/services/"].concat(), |
| 108 | g.from(UPPER_DIGIT, 10), |
| 109 | g.from(UPPER_DIGIT, 10), |
| 110 | g.from(ALNUM, 24) |
| 111 | ), |
| 112 | ), |
| 113 | ( |
| 114 | SecretRule::StripeLiveKey, |
| 115 | format!("{}{}", ["sk_", "live_"].concat(), g.from(ALNUM, 32)), |
| 116 | ), |
| 117 | ( |
| 118 | SecretRule::AnthropicKey, |
| 119 | format!("{}api03-{}", ["sk-", "ant-"].concat(), g.from(ALNUM, 93)), |
| 120 | ), |
| 121 | ( |
| 122 | SecretRule::OpenAiKey, |
| 123 | format!("{}{}", ["sk-", "proj-"].concat(), g.from(ALNUM, 64)), |
| 124 | ), |
| 125 | ( |
| 126 | SecretRule::OpenAiKey, |
| 127 | format!( |
| 128 | "sk-{}{}{}", |
| 129 | g.from(ALNUM, 20), |
| 130 | ["T3Blbk", "FJ"].concat(), |
| 131 | g.from(ALNUM, 20) |
| 132 | ), |
| 133 | ), |
| 134 | (SecretRule::SecretAssignment, g.from(ALNUM, 40)), |
| 135 | ] |
| 136 | } |
| 137 | |
| 138 | /// The planted secret placed in a realistic source context. |
| 139 | fn in_context(rule: SecretRule, secret: &str) -> Vec<u8> { |
| 140 | match rule { |
| 141 | SecretRule::SecretAssignment => { |
| 142 | format!("fn main() {{\n let db_password = \"{secret}\";\n}}\n").into_bytes() |
| 143 | } |
| 144 | SecretRule::PrivateKeyBlock => format!("# deploy key\n{secret}").into_bytes(), |
| 145 | _ => { |
| 146 | format!("config:\n endpoint: https://api.local\n upstream: '{secret}'\n").into_bytes() |
| 147 | } |
| 148 | } |
| 149 | } |
| 150 | |
| 151 | #[test] |
| 152 | fn m1_every_planted_secret_is_found_by_its_rule() { |
| 153 | for (rule, secret) in planted() { |
| 154 | let blob = in_context(rule, &secret); |
| 155 | let f = scan(&blob).unwrap_or_else(|| panic!("{} not found", rule.id())); |
| 156 | if rule != SecretRule::SecretAssignment { |
| 157 | assert_eq!(f.rule, rule, "rule for {}", rule.id()); |
| 158 | } |
| 159 | // Binary context: the secret between non-text bytes is still found. |
| 160 | let mut bin = vec![0u8, 0xFF, 0x80, b'\n']; |
| 161 | bin.extend_from_slice(secret.as_bytes()); |
| 162 | bin.extend_from_slice(&[0u8, 0xFE]); |
| 163 | if rule != SecretRule::SecretAssignment { |
| 164 | assert_eq!( |
| 165 | scan(&bin).map(|f| f.rule), |
| 166 | Some(rule), |
| 167 | "binary {}", |
| 168 | rule.id() |
| 169 | ); |
| 170 | } |
| 171 | } |
| 172 | } |
| 173 | |
| 174 | #[test] |
| 175 | fn m1_assignment_forms_are_found() { |
| 176 | let mut g = Gen(7); |
| 177 | let v = g.from(ALNUM, 32); |
| 178 | let hex = g.from(b"0123456789abcdef", 64); |
| 179 | for text in [ |
| 180 | format!("API_KEY={v}\n"), |
| 181 | format!("export GITHUB_TOKEN={v}\n"), |
| 182 | format!("{{\"client_secret\": \"{v}\"}}"), |
| 183 | format!("password := \"{v}\""), |
| 184 | format!("auth_token => '{v}',"), |
| 185 | format!("secret: {hex}\n"), |
| 186 | ] { |
| 187 | assert_eq!( |
| 188 | scan(text.as_bytes()).map(|f| f.rule), |
| 189 | Some(SecretRule::SecretAssignment), |
| 190 | "{text}" |
| 191 | ); |
| 192 | } |
| 193 | } |
| 194 | |
| 195 | #[test] |
| 196 | fn m1_lookalikes_and_marked_fake_examples_are_admitted() { |
| 197 | let dash5 = "-".repeat(5); |
| 198 | let negatives: Vec<String> = vec![ |
| 199 | // AWS documentation example key id (clearly fake: ends in EXAMPLE). |
| 200 | format!("{}IOSFODNN7EXAMPLE", ["AK", "IA"].concat()), |
| 201 | // Placeholder GitHub token from docs. |
| 202 | format!("{}{}", ["gh", "p_"].concat(), "x".repeat(36)), |
| 203 | // Wrong length and prefix glued to a word. |
| 204 | format!("{}abc123", ["gh", "p_"].concat()), |
| 205 | format!( |
| 206 | "my{}{}", |
| 207 | ["gh", "p_"].concat(), |
| 208 | "A1b2C3d4E5f6G7h8I9j0K1l2M3n4O5p6Q7r8" |
| 209 | ), |
| 210 | // Stripe test keys are not live keys. |
| 211 | format!( |
| 212 | "{}{}", |
| 213 | ["sk_", "test_"].concat(), |
| 214 | "4eC39HqLyjWDarjtT1zdp7dc" |
| 215 | ), |
| 216 | // A PEM header in prose with no key body, and a public key block. |
| 217 | format!("{dash5}BEGIN RSA PRIVATE KEY{dash5}\n...\n{dash5}END RSA PRIVATE KEY{dash5}"), |
| 218 | format!( |
| 219 | "{dash5}BEGIN PUBLIC KEY{dash5}\n{}\n", |
| 220 | "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA".repeat(3) |
| 221 | ), |
| 222 | // Assignments that are not literal secrets. |
| 223 | "let token = generate_token_v2(seed_1234567890abcdef);".into(), |
| 224 | "password = \"${DB_PASSWORD_FROM_ENVIRONMENT_1}\"".into(), |
| 225 | "pub token: String,\n secret: [u8; 32],".into(), |
| 226 | "api_key = \"your-api-key-goes-here-123\"".into(), |
| 227 | "client_secret = \"EXAMPLE0123456789abcdefEXAMPLE\"".into(), |
| 228 | "if token == expected_token_value_1234 {}".into(), |
| 229 | "let tokens = Vec::<Token>::with_capacity(1024);".into(), |
| 230 | // High-entropy values under names that are not secret-like. |
| 231 | "digest = \"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\"".into(), |
| 232 | "commit: 2f06c45a1b2c3d4e5f60718293a4b5c6d7e8f901".into(), |
| 233 | // Rust paths with `::`. |
| 234 | "synapse_api::secret_scan::check_blobs(&blobs)?;".into(), |
| 235 | // A short hex value named token. |
| 236 | "token = \"deadbeef12345678\"".into(), |
| 237 | ]; |
| 238 | for n in &negatives { |
| 239 | assert_eq!(scan(n.as_bytes()), None, "false refusal: {n}"); |
| 240 | } |
| 241 | } |
| 242 | |
| 243 | #[test] |
| 244 | fn m1_refusal_names_rule_and_never_echoes_secret_bytes() { |
| 245 | for (rule, secret) in planted() { |
| 246 | let blob = in_context(rule, &secret); |
| 247 | let digest = BlobDigest::compute(&blob); |
| 248 | let ok = BlobDigest::compute(b"clean"); |
| 249 | let err = check_blobs(&[(ok, b"clean".to_vec()), (digest, blob)]).unwrap_err(); |
| 250 | assert_eq!(err.code, RefusalCode::SecretDetected); |
| 251 | let rendered = format!("{err} {err:?}"); |
| 252 | assert!(rendered.contains(&digest.to_string())); |
| 253 | assert!(rendered.contains(&format!("v{SECRET_RULESET_VERSION}"))); |
| 254 | // No 8-byte window of the secret appears in any rendering of the refusal. |
| 255 | let s = secret.as_bytes(); |
| 256 | for w in s.windows(8) { |
| 257 | let w = String::from_utf8_lossy(w); |
| 258 | if w.contains('-') || w.contains('\n') { |
| 259 | continue; // PEM framing is not secret material. |
| 260 | } |
| 261 | assert!(!rendered.contains(&*w), "{} leaked into refusal", rule.id()); |
| 262 | } |
| 263 | } |
| 264 | } |
| 265 | |
| 266 | /// Inputs built to make naive or backtracking matchers blow up: every trigger byte repeated, |
| 267 | /// near-miss prefixes, and long runs that stop one byte short of a match. |
| 268 | fn adversarial(len: usize) -> Vec<Vec<u8>> { |
| 269 | let dash5 = "-".repeat(5); |
| 270 | let units: Vec<String> = vec![ |
| 271 | format!("{dash5}BEGIN RSA PRIVATE KEY{dash5}\n"), |
| 272 | format!("{dash5}BEGIN "), |
| 273 | "-".into(), |
| 274 | ["AK", "IA"].concat(), |
| 275 | ["gh", "p_"].concat(), |
| 276 | ["github", "_pat_"].concat(), |
| 277 | format!("{}1-", ["xo", "xb-"].concat()), |
| 278 | ["sk-", "ant-"].concat(), |
| 279 | "sk-".into(), |
| 280 | "token=".into(), |
| 281 | "password:".into(), |
| 282 | "a=".into(), |
| 283 | "=".into(), |
| 284 | ":".into(), |
| 285 | format!("secret_token = \"{}\"\n", "Ab1".repeat(50)), |
| 286 | format!("api_key={}", "Z9".repeat(64)), |
| 287 | "hooks.slack.com/services/".into(), |
| 288 | ]; |
| 289 | let mut out: Vec<Vec<u8>> = units |
| 290 | .iter() |
| 291 | .map(|u| u.as_bytes().iter().copied().cycle().take(len).collect()) |
| 292 | .collect(); |
| 293 | out.push(vec![b'a'; len]); |
| 294 | out.push(vec![0u8; len]); |
| 295 | let mut g = Gen(42); |
| 296 | out.push((0..len).map(|_| g.next() as u8).collect()); |
| 297 | out |
| 298 | } |
| 299 | |
| 300 | #[test] |
| 301 | fn m1_adversarial_input_is_linear_in_time_and_steps() { |
| 302 | const LEN: usize = 1 << 22; // 4 MiB per input |
| 303 | const STEPS_PER_BYTE: u64 = 64; |
| 304 | for input in adversarial(LEN) { |
| 305 | let t = Instant::now(); |
| 306 | let (_, steps) = scan_with_steps(&input); |
| 307 | let took = t.elapsed(); |
| 308 | assert!( |
| 309 | steps <= STEPS_PER_BYTE * input.len() as u64, |
| 310 | "{steps} steps for {} bytes", |
| 311 | input.len() |
| 312 | ); |
| 313 | // Generous wall-clock ceiling for an unoptimized test build. |
| 314 | assert!(took < Duration::from_secs(10), "took {took:?}"); |
| 315 | // Doubling the input at most doubles the work (plus a constant). |
| 316 | let half = &input[..LEN / 2]; |
| 317 | let (_, half_steps) = scan_with_steps(half); |
| 318 | assert!(steps <= 2 * half_steps + 65_536, "{steps} vs {half_steps}"); |
| 319 | } |
| 320 | } |
| 321 | |
| 322 | fn source_files(dir: &Path, out: &mut Vec<PathBuf>) { |
| 323 | let Ok(rd) = std::fs::read_dir(dir) else { |
| 324 | return; |
| 325 | }; |
| 326 | for e in rd.flatten() { |
| 327 | let p = e.path(); |
| 328 | let name = e.file_name(); |
| 329 | if name == "target" || name.to_string_lossy().starts_with('.') { |
| 330 | continue; |
| 331 | } |
| 332 | if p.is_dir() { |
| 333 | source_files(&p, out); |
| 334 | } else if matches!( |
| 335 | p.extension().and_then(|x| x.to_str()), |
| 336 | Some("rs" | "md" | "toml" | "sh" | "json") |
| 337 | ) { |
| 338 | out.push(p); |
| 339 | } |
| 340 | } |
| 341 | } |
| 342 | |
| 343 | /// Real AIEN source without secrets: this repository's own crates, docs, and scripts. The |
| 344 | /// false-refusal count is printed and must be zero. |
| 345 | #[test] |
| 346 | fn m1_real_aien_source_is_admitted_with_zero_false_refusals() { |
| 347 | let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../.."); |
| 348 | let mut files = Vec::new(); |
| 349 | for d in ["crates", "docs", "scripts"] { |
| 350 | source_files(&root.join(d), &mut files); |
| 351 | } |
| 352 | files.sort(); |
| 353 | assert!(files.len() > 50, "corpus too small: {}", files.len()); |
| 354 | let mut bytes = 0usize; |
| 355 | let mut refused = Vec::new(); |
| 356 | let t = Instant::now(); |
| 357 | for f in &files { |
| 358 | let data = std::fs::read(f).unwrap(); |
| 359 | bytes += data.len(); |
| 360 | if let Some(found) = scan(&data) { |
| 361 | refused.push(format!( |
| 362 | "{} ({} @ {})", |
| 363 | f.display(), |
| 364 | found.rule.id(), |
| 365 | found.offset |
| 366 | )); |
| 367 | } |
| 368 | } |
| 369 | let secs = t.elapsed().as_secs_f64(); |
| 370 | println!( |
| 371 | "m1 corpus: {} files, {} bytes, {} false refusals, {:.6} s scan (debug build)", |
| 372 | files.len(), |
| 373 | bytes, |
| 374 | refused.len(), |
| 375 | secs |
| 376 | ); |
| 377 | assert!(refused.is_empty(), "false refusals: {refused:#?}"); |
| 378 | } |
| 379 | |
| 380 | fn temp_dir(label: &str) -> PathBuf { |
| 381 | std::env::temp_dir().join(format!( |
| 382 | "synapse-m1-{label}-{}-{}", |
| 383 | std::process::id(), |
| 384 | std::time::SystemTime::now() |
| 385 | .duration_since(std::time::UNIX_EPOCH) |
| 386 | .unwrap() |
| 387 | .as_nanos() |
| 388 | )) |
| 389 | } |
| 390 | |
| 391 | fn repo() -> RepoId { |
| 392 | RepoId::new("aien-spark/synapse").unwrap() |
| 393 | } |
| 394 | |
| 395 | /// Link nonces for one fixture: SHA-256 of the fixture label and a counter, so every link |
| 396 | /// gets a fresh nonce and none is a fixed value (same shape as b4_revision_states). |
| 397 | fn link_nonces(label: &str) -> impl FnMut() -> [u8; 32] { |
| 398 | let seed = label.to_owned(); |
| 399 | let mut issued = 0u32; |
| 400 | move || { |
| 401 | issued += 1; |
| 402 | let mut h = Sha256::new(); |
| 403 | h.update(seed.as_bytes()); |
| 404 | h.update(issued.to_le_bytes()); |
| 405 | h.finalize().into() |
| 406 | } |
| 407 | } |
| 408 | |
| 409 | fn open(label: &str) -> SynapseService { |
| 410 | SynapseService::open( |
| 411 | temp_dir(label), |
| 412 | repo(), |
| 413 | FsyncPolicy::EveryCommit, |
| 414 | RecoveryPolicy::StrictFailClosed, |
| 415 | StoreLimits { |
| 416 | wal_prealloc_bytes: 64 * 1024, |
| 417 | ..Default::default() |
| 418 | }, |
| 419 | ) |
| 420 | .unwrap() |
| 421 | } |
| 422 | |
| 423 | /// Envelope v1 `submit`: a blob with a secret is refused before any WAL write; a clean blob |
| 424 | /// in the same service is then admitted. |
| 425 | #[test] |
| 426 | fn m1_submit_refuses_secret_blob_before_any_wal_write() { |
| 427 | let mut svc = open("submit"); |
| 428 | let auth = SigningKey::from_bytes(&[10; 32]); |
| 429 | svc.register_authority(encode_did_key_ed25519(&auth.verifying_key().to_bytes())); |
| 430 | let agent = SigningKey::from_bytes(&[20; 32]); |
| 431 | let agent_did = encode_did_key_ed25519(&agent.verifying_key().to_bytes()); |
| 432 | let base = GitOid::compute_blob(b"base"); |
| 433 | svc.register_base_tree( |
| 434 | base, |
| 435 | vec![("README.md".into(), FileMode::Regular644, b"base".to_vec())], |
| 436 | ) |
| 437 | .unwrap(); |
| 438 | let grant = AgentCapabilityGrant::issue( |
| 439 | &auth, |
| 440 | [1; 32], |
| 441 | repo(), |
| 442 | agent_did, |
| 443 | vec![Capability::Read, Capability::Propose], |
| 444 | 1 << 20, |
| 445 | 100, |
| 446 | 60_000, |
| 447 | 10, |
| 448 | 100_000, |
| 449 | ); |
| 450 | let request = |body: &[u8], n: u8| { |
| 451 | let digest = BlobDigest::compute(body); |
| 452 | let mut env = ChangesetEnvelope { |
| 453 | version: SYNAPSE_ENVELOPE_VERSION, |
| 454 | repo_id: repo(), |
| 455 | base_git_oid: base, |
| 456 | parent_changesets: vec![], |
| 457 | author_did: String::new(), |
| 458 | idempotency_key: IdempotencyKey([n; 32]), |
| 459 | created_at_ms: 100, |
| 460 | intent_summary: "edit config".into(), |
| 461 | mutations: vec![PathMutation { |
| 462 | path: "src/config.rs".into(), |
| 463 | op: MutationOp::Upsert { |
| 464 | mode: FileMode::Regular644, |
| 465 | blob_digest: digest, |
| 466 | size_bytes: body.len() as u64, |
| 467 | }, |
| 468 | }], |
| 469 | evidence_receipts: vec![], |
| 470 | signature: vec![], |
| 471 | }; |
| 472 | env.sign(&agent); |
| 473 | AuthenticatedRequest::sign_new( |
| 474 | &agent, |
| 475 | grant.clone(), |
| 476 | repo(), |
| 477 | Capability::Propose, |
| 478 | [n; 32], |
| 479 | 100, |
| 480 | 0, |
| 481 | SubmitChangesetPayload { |
| 482 | envelope: env, |
| 483 | blobs: vec![(digest, body.to_vec())], |
| 484 | }, |
| 485 | ) |
| 486 | .unwrap() |
| 487 | }; |
| 488 | let before = svc.store().committed_seq(); |
| 489 | for (i, (rule, secret)) in planted().into_iter().enumerate() { |
| 490 | let body = in_context(rule, &secret); |
| 491 | let err = svc.submit(&request(&body, 100 + i as u8), 100).unwrap_err(); |
| 492 | assert_eq!(err.code, RefusalCode::SecretDetected, "{}", rule.id()); |
| 493 | assert!(!err.message.contains(&secret)); |
| 494 | assert_eq!(svc.store().committed_seq(), before, "WAL advanced"); |
| 495 | assert!(svc |
| 496 | .read_blob_bytes(BlobDigest::compute(&body), None) |
| 497 | .is_err()); |
| 498 | } |
| 499 | let clean = b"pub fn port() -> u16 { 8080 }\n"; |
| 500 | let out = svc.submit(&request(clean, 1), 100).unwrap(); |
| 501 | assert!(matches!(out, IngestOutcome::Committed { .. })); |
| 502 | assert!(svc.store().committed_seq() > before); |
| 503 | } |
| 504 | |
| 505 | /// Envelope v2 `submit_revision` under an F1 chain: the same refusal, no WAL write. |
| 506 | #[test] |
| 507 | fn m1_submit_revision_refuses_secret_blob_before_any_wal_write() { |
| 508 | const NOW: u64 = 2_000; |
| 509 | const C: ChangeId = ChangeId([0xC1; 16]); |
| 510 | let mut svc = open("revision"); |
| 511 | let a = SigningKey::from_bytes(&[1; 32]); |
| 512 | let o = SigningKey::from_bytes(&[2; 32]); |
| 513 | svc.auth_mut().register_repo_authority( |
| 514 | repo(), |
| 515 | encode_did_key_ed25519(&a.verifying_key().to_bytes()), |
| 516 | ); |
| 517 | let caveats = LinkCaveats { |
| 518 | operations: OperationSet::from_capabilities(&[Capability::Read, Capability::Propose]), |
| 519 | paths: PathScope::whole_repository(), |
| 520 | references: ReferenceScope::from_kinds(&[ReferenceKind::OwnDrafts]), |
| 521 | changes: ChangeScope::any(), |
| 522 | quotas: ChainQuotas { |
| 523 | max_ops_per_window: 1_000, |
| 524 | window_duration_ms: 60_000, |
| 525 | storage_bytes: 1 << 30, |
| 526 | footprint_paths: 1 << 20, |
| 527 | max_bytes_per_op: 1 << 20, |
| 528 | }, |
| 529 | issued_at_ms: 1_000, |
| 530 | expires_at_ms: 100_000, |
| 531 | }; |
| 532 | let link = CapabilityLink::issue( |
| 533 | &a, |
| 534 | ROOT_PARENT, |
| 535 | link_nonces("revision")(), |
| 536 | repo(), |
| 537 | o.verifying_key().to_bytes(), |
| 538 | caveats, |
| 539 | ); |
| 540 | let chain = CapabilityChain::new(vec![link]); |
| 541 | svc.auth_mut().grant_link(&chain, WalSeq(0), NOW).unwrap(); |
| 542 | let base_oid = GitOid([0x0B; 20]); |
| 543 | svc.register_base_tree( |
| 544 | base_oid, |
| 545 | vec![("README.md".into(), FileMode::Regular644, b"base".to_vec())], |
| 546 | ) |
| 547 | .unwrap(); |
| 548 | let base = svc |
| 549 | .tree_digest(TreeTarget::BaseGitCommit(base_oid), None) |
| 550 | .unwrap(); |
| 551 | let mut submit = |body: &[u8], n: u8| { |
| 552 | let content = RevisionContent { |
| 553 | change_id: C, |
| 554 | base_tree: base, |
| 555 | parents: vec![], |
| 556 | mutations: vec![PathMutation { |
| 557 | path: "src/lib.rs".into(), |
| 558 | op: MutationOp::Upsert { |
| 559 | mode: FileMode::Regular644, |
| 560 | blob_digest: BlobDigest::compute(body), |
| 561 | size_bytes: body.len() as u64, |
| 562 | }, |
| 563 | }], |
| 564 | intent_summary: "implement the task".into(), |
| 565 | }; |
| 566 | let env = ChangesetEnvelopeV2::sign_new(&o, repo(), content, IdempotencyKey([n; 32]), NOW); |
| 567 | let req = ChainedRequest::sign_new( |
| 568 | &o, |
| 569 | chain.clone(), |
| 570 | repo(), |
| 571 | Capability::Propose, |
| 572 | RequestScope { |
| 573 | paths: vec!["src/lib.rs".into()], |
| 574 | reference: None, |
| 575 | join_change: Some(C), |
| 576 | }, |
| 577 | [n; 32], |
| 578 | NOW, |
| 579 | env.encode(), |
| 580 | ); |
| 581 | let blobs = vec![(BlobDigest::compute(body), body.to_vec())]; |
| 582 | let before = svc.store().committed_seq(); |
| 583 | let r = svc.submit_revision(&req, &blobs, NOW); |
| 584 | (r.map(|_| ()), before, svc.store().committed_seq()) |
| 585 | }; |
| 586 | let (rule, secret) = planted().swap_remove(5); |
| 587 | let body = in_context(rule, &secret); |
| 588 | let (r, before, after) = submit(&body, 7); |
| 589 | let err = r.unwrap_err(); |
| 590 | assert_eq!(err.code, RefusalCode::SecretDetected); |
| 591 | assert!(!err.message.contains(&secret)); |
| 592 | assert_eq!(before, after, "WAL advanced on a refused secret"); |
| 593 | let (r, before, after) = submit(b"pub fn ok() {}\n", 8); |
| 594 | r.unwrap(); |
| 595 | assert!(after > before); |
| 596 | } |