synapse
A component of the AienOS ecosystem.
Brought by drakestapleton
synapse / crates / synapse-api / tests / payload_digest_parity.rs
| 1 | //! Issue #92 parity proof: `synapse_auth::payload_digest` (compact JSON streamed into SHA-256) |
| 2 | //! returns exactly what the old code computed, `(SHA-256(serde_json::to_vec(p)), its length)`, |
| 3 | //! and every refusal code of `PolicyEnforcer::authorize` is unchanged. |
| 4 | //! |
| 5 | //! Corpus: |
| 6 | //! * the A1 malformed corpus, regenerated here the same way |
| 7 | //! `crates/synapse-store/tests/a1_malformed_corpus.rs` builds it (one binary-v2 WAL frame per |
| 8 | //! record kind from the `a1-v1` fixture, every truncation, every bit flip, oversized frame and |
| 9 | //! inner lengths, and every truncation and bit flip of the v2 checkpoint), with each damaged |
| 10 | //! byte string carried both as a blob in a `SubmitChangesetPayload` and as a lossy UTF-8 |
| 11 | //! string, so JSON number arrays and string escaping are both exercised; |
| 12 | //! * recorded requests: every record of the `a1-v1` WAL fixtures (v1 JSON log and v2 binary |
| 13 | //! log), each `ChangesetIngest` rebuilt into the `SubmitChangesetPayload` that produced it |
| 14 | //! (envelope plus the recorded blob bytes), and one payload of every query type built from |
| 15 | //! the recorded ids; |
| 16 | //! * edge values: escapes, control characters, non-ASCII text, empty and maximal numbers. |
| 17 | |
| 18 | use ed25519_dalek::SigningKey; |
| 19 | use serde::Serialize; |
| 20 | use sha2::{Digest, Sha256}; |
| 21 | use std::collections::BTreeMap; |
| 22 | use std::path::{Path, PathBuf}; |
| 23 | use synapse_api::{ |
| 24 | ChangesetAdvisoryPayload, ConflictQueryPayload, CrumbContextQueryPayload, DiffQueryPayload, |
| 25 | EvidenceBaseQueryPayload, HistoryQueryPayload, PageRequest, SubmitChangesetPayload, |
| 26 | TreeQueryPayload, TreeTarget, VerifyEvidenceReceiptPayload, WatchQueryPayload, |
| 27 | }; |
| 28 | use synapse_auth::{ |
| 29 | payload_digest, AgentCapabilityGrant, AuthenticatedRequest, BoundaryKind, Capability, |
| 30 | PolicyEnforcer, |
| 31 | }; |
| 32 | use synapse_core::{ |
| 33 | encode_did_key_ed25519, BlobDigest, ChangesetEnvelope, ChangesetId, RefusalCode, RepoId, WalSeq, |
| 34 | }; |
| 35 | use synapse_store::codec::{ |
| 36 | decode_record_with, encode_checkpoint_v2, encode_record, CheckpointState, WAL_FLAG_CODEC_V2, |
| 37 | }; |
| 38 | use synapse_store::wal2::{WAL_V2_ALIGN, WAL_V2_BATCH_HEADER_LEN, WAL_V2_BATCH_MAGIC}; |
| 39 | use synapse_store::{ |
| 40 | encode_wal_frame, wal_frame_from_payload, CheckpointManifest, RecordCodec, WalRecord, |
| 41 | WAL_HEADER_LEN, |
| 42 | }; |
| 43 | |
| 44 | /// Same record cap as the A1 corpus. |
| 45 | const CAP: u64 = 1 << 20; |
| 46 | |
| 47 | fn fixtures() -> PathBuf { |
| 48 | Path::new(env!("CARGO_MANIFEST_DIR")).join("../synapse-store/tests/fixtures/a1-v1") |
| 49 | } |
| 50 | |
| 51 | fn fixture(rel: &str) -> Vec<u8> { |
| 52 | std::fs::read(fixtures().join(rel)).unwrap_or_else(|e| panic!("fixture {rel}: {e}")) |
| 53 | } |
| 54 | |
| 55 | fn derived(label: &str, counter: u64) -> [u8; 32] { |
| 56 | let mut h = Sha256::new(); |
| 57 | h.update(b"SYNAPSE_API_PAYLOAD_DIGEST_PARITY_V1\0"); |
| 58 | h.update(label.as_bytes()); |
| 59 | h.update(counter.to_le_bytes()); |
| 60 | h.finalize().into() |
| 61 | } |
| 62 | |
| 63 | /// The digest exactly as `check_request_inner` and `sign_new` computed it before #92. |
| 64 | fn old_digest<T: Serialize + ?Sized>(p: &T) -> Result<([u8; 32], u64), String> { |
| 65 | let json = serde_json::to_vec(p).map_err(|e| format!("serialize payload: {e}"))?; |
| 66 | Ok((Sha256::digest(&json).into(), json.len() as u64)) |
| 67 | } |
| 68 | |
| 69 | #[derive(Default)] |
| 70 | struct Parity { |
| 71 | cases: usize, |
| 72 | json_bytes: u64, |
| 73 | } |
| 74 | |
| 75 | impl Parity { |
| 76 | fn check<T: Serialize + ?Sized>(&mut self, what: &str, p: &T) { |
| 77 | let old = old_digest(p).unwrap_or_else(|e| panic!("{what}: old digest failed: {e}")); |
| 78 | let new = payload_digest(p).unwrap_or_else(|e| panic!("{what}: new digest failed: {e}")); |
| 79 | assert_eq!(new, old, "{what}: digest or length differs"); |
| 80 | self.cases += 1; |
| 81 | self.json_bytes += old.1; |
| 82 | } |
| 83 | |
| 84 | /// One damaged byte string, as a blob and as a lossy string. |
| 85 | fn bytes(&mut self, what: &str, envelope: &ChangesetEnvelope, b: &[u8]) { |
| 86 | self.check( |
| 87 | what, |
| 88 | &SubmitChangesetPayload { |
| 89 | envelope: envelope.clone(), |
| 90 | blobs: vec![(BlobDigest::compute(b), b.to_vec())], |
| 91 | }, |
| 92 | ); |
| 93 | self.check(what, &String::from_utf8_lossy(b)); |
| 94 | } |
| 95 | } |
| 96 | |
| 97 | /// Every record of the v1 JSON WAL fixture, in log order. |
| 98 | fn v1_records() -> Vec<WalRecord> { |
| 99 | let log = fixture("v1-wal-log/wal.log"); |
| 100 | let mut out = Vec::new(); |
| 101 | let mut at = 0; |
| 102 | while at < log.len() { |
| 103 | let len = u32::from_le_bytes(log[at + 48..at + 52].try_into().unwrap()) as usize; |
| 104 | let payload = &log[at + WAL_HEADER_LEN..at + WAL_HEADER_LEN + len]; |
| 105 | out.push(serde_json::from_slice(payload).unwrap()); |
| 106 | at += WAL_HEADER_LEN + len; |
| 107 | } |
| 108 | out |
| 109 | } |
| 110 | |
| 111 | type Blobs = BTreeMap<BlobDigest, Vec<u8>>; |
| 112 | |
| 113 | /// Every record of the WAL v2 fixture (`wal.v2.log`: 4 KiB-aligned `SWB2` batches; each frame |
| 114 | /// payload is `u32 meta_len | meta | u32 blob_count | (digest[32] | u32 len | bytes)*`), with |
| 115 | /// its inline blobs. |
| 116 | fn v2_records() -> (Vec<WalRecord>, Blobs) { |
| 117 | let log = fixture("v1-wal-v2-log/wal.v2.log"); |
| 118 | let u32_at = |b: &[u8], o: usize| u32::from_le_bytes(b[o..o + 4].try_into().unwrap()) as usize; |
| 119 | let mut records = Vec::new(); |
| 120 | let mut blobs = Blobs::new(); |
| 121 | let mut off = 0usize; |
| 122 | while off + WAL_V2_BATCH_HEADER_LEN <= log.len() && log[off..off + 4] == WAL_V2_BATCH_MAGIC { |
| 123 | let count = u32_at(&log, off + 8); |
| 124 | let body = u64::from_le_bytes(log[off + 16..off + 24].try_into().unwrap()) as usize; |
| 125 | let mut at = off + WAL_V2_BATCH_HEADER_LEN; |
| 126 | for _ in 0..count { |
| 127 | let h = &log[at..at + WAL_HEADER_LEN]; |
| 128 | let len = u32_at(h, 48); |
| 129 | let p = &log[at + WAL_HEADER_LEN..at + WAL_HEADER_LEN + len]; |
| 130 | let codec = if h[7] == WAL_FLAG_CODEC_V2 { |
| 131 | RecordCodec::BinaryV2 |
| 132 | } else { |
| 133 | RecordCodec::JsonV1 |
| 134 | }; |
| 135 | let meta_len = u32_at(p, 0); |
| 136 | records.push(decode_record_with(&p[4..4 + meta_len], codec, CAP).unwrap()); |
| 137 | let mut b = 4 + meta_len; |
| 138 | let n = u32_at(p, b); |
| 139 | b += 4; |
| 140 | for _ in 0..n { |
| 141 | let digest = BlobDigest(p[b..b + 32].try_into().unwrap()); |
| 142 | let blen = u32_at(p, b + 32); |
| 143 | let bytes = p[b + 36..b + 36 + blen].to_vec(); |
| 144 | assert_eq!(BlobDigest::compute(&bytes), digest, "inline blob"); |
| 145 | blobs.insert(digest, bytes); |
| 146 | b += 36 + blen; |
| 147 | } |
| 148 | at += WAL_HEADER_LEN + len; |
| 149 | } |
| 150 | let end = (off + WAL_V2_BATCH_HEADER_LEN + body) as u64; |
| 151 | off = end.div_ceil(WAL_V2_ALIGN) as usize * WAL_V2_ALIGN as usize; |
| 152 | } |
| 153 | (records, blobs) |
| 154 | } |
| 155 | |
| 156 | /// The blobs recorded in the v1 fixture's blob store (`blobs/<2 hex>/<64 hex>`). |
| 157 | fn v1_blobs() -> Blobs { |
| 158 | let mut out = Blobs::new(); |
| 159 | for dir in std::fs::read_dir(fixtures().join("v1-wal-log/blobs")).unwrap() { |
| 160 | for file in std::fs::read_dir(dir.unwrap().path()).unwrap() { |
| 161 | let file = file.unwrap(); |
| 162 | let digest = BlobDigest::from_hex(file.file_name().to_str().unwrap()).unwrap(); |
| 163 | let bytes = std::fs::read(file.path()).unwrap(); |
| 164 | assert_eq!(BlobDigest::compute(&bytes), digest, "stored blob"); |
| 165 | out.insert(digest, bytes); |
| 166 | } |
| 167 | } |
| 168 | out |
| 169 | } |
| 170 | |
| 171 | fn one_record_per_kind(records: &[WalRecord]) -> Vec<WalRecord> { |
| 172 | let mut by_kind = BTreeMap::new(); |
| 173 | for r in records { |
| 174 | by_kind.entry(r.kind_byte()).or_insert_with(|| r.clone()); |
| 175 | } |
| 176 | assert_eq!(by_kind.len(), 6, "fixture must hold all six record kinds"); |
| 177 | by_kind.into_values().collect() |
| 178 | } |
| 179 | |
| 180 | fn first_envelope(records: &[WalRecord]) -> ChangesetEnvelope { |
| 181 | records |
| 182 | .iter() |
| 183 | .find_map(|r| match r { |
| 184 | WalRecord::ChangesetIngest { envelope, .. } => Some(envelope.clone()), |
| 185 | _ => None, |
| 186 | }) |
| 187 | .expect("fixture holds a changeset") |
| 188 | } |
| 189 | |
| 190 | /// The `SubmitChangesetPayload` each recorded `ChangesetIngest` was admitted from: its |
| 191 | /// envelope and the bytes of every blob it introduced. |
| 192 | fn recorded_submits( |
| 193 | records: &[WalRecord], |
| 194 | blobs: &Blobs, |
| 195 | ) -> Vec<(ChangesetId, SubmitChangesetPayload)> { |
| 196 | records |
| 197 | .iter() |
| 198 | .filter_map(|r| match r { |
| 199 | WalRecord::ChangesetIngest { |
| 200 | envelope, |
| 201 | changeset_id, |
| 202 | new_blobs, |
| 203 | } => Some(( |
| 204 | *changeset_id, |
| 205 | SubmitChangesetPayload { |
| 206 | envelope: envelope.clone(), |
| 207 | blobs: new_blobs |
| 208 | .iter() |
| 209 | .map(|d| { |
| 210 | let b = blobs.get(d).unwrap_or_else(|| panic!("blob {d} recorded")); |
| 211 | (*d, b.clone()) |
| 212 | }) |
| 213 | .collect(), |
| 214 | }, |
| 215 | )), |
| 216 | _ => None, |
| 217 | }) |
| 218 | .collect() |
| 219 | } |
| 220 | |
| 221 | /// Every recorded submit of both fixtures. |
| 222 | fn all_recorded_submits() -> Vec<(ChangesetId, SubmitChangesetPayload)> { |
| 223 | let (v2, v2_blobs) = v2_records(); |
| 224 | let mut out = recorded_submits(&v1_records(), &v1_blobs()); |
| 225 | out.extend(recorded_submits(&v2, &v2_blobs)); |
| 226 | out |
| 227 | } |
| 228 | |
| 229 | #[test] |
| 230 | fn new_digest_equals_old_over_the_a1_malformed_corpus() { |
| 231 | let records = v1_records(); |
| 232 | let envelope = first_envelope(&records); |
| 233 | let mut p = Parity::default(); |
| 234 | let mut classes: BTreeMap<&str, usize> = BTreeMap::new(); |
| 235 | let prev = derived("prev-frame", 0); |
| 236 | for r in one_record_per_kind(&records) { |
| 237 | let kind = r.kind_byte(); |
| 238 | let (frame, _) = encode_wal_frame(WalSeq(1), prev, &r, RecordCodec::BinaryV2, CAP).unwrap(); |
| 239 | p.bytes(&format!("kind {kind} frame"), &envelope, &frame); |
| 240 | for n in 0..frame.len() { |
| 241 | p.bytes( |
| 242 | &format!("kind {kind} truncated to {n}"), |
| 243 | &envelope, |
| 244 | &frame[..n], |
| 245 | ); |
| 246 | *classes.entry("truncated").or_default() += 1; |
| 247 | } |
| 248 | for bit in 0..frame.len() * 8 { |
| 249 | let mut f = frame.clone(); |
| 250 | f[bit / 8] ^= 1 << (bit % 8); |
| 251 | p.bytes(&format!("kind {kind} bit {bit}"), &envelope, &f); |
| 252 | *classes.entry("bit_flipped").or_default() += 1; |
| 253 | } |
| 254 | for declared in [CAP + 1, 2 * CAP, u64::from(u32::MAX)] { |
| 255 | let mut f = frame.clone(); |
| 256 | f[48..52].copy_from_slice(&(declared as u32).to_le_bytes()); |
| 257 | p.bytes(&format!("kind {kind} declares {declared}"), &envelope, &f); |
| 258 | *classes.entry("oversized_frame_length").or_default() += 1; |
| 259 | } |
| 260 | let bin = encode_record(&r).unwrap(); |
| 261 | for off in 0..bin.len().saturating_sub(4) { |
| 262 | let mut b = bin.clone(); |
| 263 | b[off..off + 4].copy_from_slice(&u32::MAX.to_le_bytes()); |
| 264 | let (f, _) = wal_frame_from_payload(WalSeq(1), prev, kind, frame[7], &b); |
| 265 | p.bytes(&format!("kind {kind} inner length at {off}"), &envelope, &f); |
| 266 | *classes.entry("oversized_inner_length").or_default() += 1; |
| 267 | } |
| 268 | } |
| 269 | let manifest: CheckpointManifest = |
| 270 | serde_json::from_slice(&fixture("v1-wal-log/checkpoint.v1")).unwrap(); |
| 271 | let state = CheckpointState::from_v1_manifest(manifest).unwrap(); |
| 272 | let (ckpt, _) = |
| 273 | encode_checkpoint_v2(&state, derived("v1-root", 0), derived("prev-ckpt", 0)).unwrap(); |
| 274 | for n in 0..ckpt.len() { |
| 275 | p.bytes( |
| 276 | &format!("checkpoint truncated to {n}"), |
| 277 | &envelope, |
| 278 | &ckpt[..n], |
| 279 | ); |
| 280 | *classes.entry("checkpoint_truncated").or_default() += 1; |
| 281 | } |
| 282 | for bit in 0..ckpt.len() * 8 { |
| 283 | let mut c = ckpt.clone(); |
| 284 | c[bit / 8] ^= 1 << (bit % 8); |
| 285 | p.bytes(&format!("checkpoint bit {bit}"), &envelope, &c); |
| 286 | *classes.entry("checkpoint_bit_flipped").or_default() += 1; |
| 287 | } |
| 288 | println!( |
| 289 | "A1 corpus parity: {} payloads, {} JSON bytes, classes {classes:?}", |
| 290 | p.cases, p.json_bytes |
| 291 | ); |
| 292 | for class in [ |
| 293 | "truncated", |
| 294 | "bit_flipped", |
| 295 | "oversized_frame_length", |
| 296 | "oversized_inner_length", |
| 297 | "checkpoint_truncated", |
| 298 | "checkpoint_bit_flipped", |
| 299 | ] { |
| 300 | assert!( |
| 301 | classes.get(class).copied().unwrap_or(0) > 0, |
| 302 | "{class} empty" |
| 303 | ); |
| 304 | } |
| 305 | } |
| 306 | |
| 307 | #[test] |
| 308 | fn new_digest_equals_old_for_every_recorded_request() { |
| 309 | let v1 = v1_records(); |
| 310 | let (v2, _) = v2_records(); |
| 311 | assert!(!v2.is_empty(), "v2 fixture decodes"); |
| 312 | let mut p = Parity::default(); |
| 313 | let mut submits = 0; |
| 314 | let mut blob_bytes = 0; |
| 315 | for (i, r) in v1.iter().chain(v2.iter()).enumerate() { |
| 316 | p.check(&format!("record {i}"), r); |
| 317 | } |
| 318 | for (id, s) in all_recorded_submits() { |
| 319 | blob_bytes += s.blobs.iter().map(|(_, b)| b.len()).sum::<usize>(); |
| 320 | p.check(&format!("submit {}", id.to_hex()), &s); |
| 321 | // The same submit carrying bench-sized blobs (the write benches submit about 12 KiB). |
| 322 | for size in [12 * 1024, 1 << 20] { |
| 323 | let mut big = s.clone(); |
| 324 | let blob: Vec<u8> = (0..size) |
| 325 | .map(|i| derived("bench-blob", (i / 32) as u64)[i % 32]) |
| 326 | .collect(); |
| 327 | big.blobs.push((BlobDigest::compute(&blob), blob)); |
| 328 | p.check(&format!("submit {} + {size} B blob", id.to_hex()), &big); |
| 329 | } |
| 330 | submits += 1; |
| 331 | let page = PageRequest { |
| 332 | cursor: Some(id.to_hex()), |
| 333 | limit: 100, |
| 334 | min_visible_seq: Some(WalSeq(1)), |
| 335 | snapshot_seq: None, |
| 336 | }; |
| 337 | let base = TreeTarget::BaseGitCommit(s.envelope.base_git_oid); |
| 338 | let target = TreeTarget::Changeset(id); |
| 339 | p.check( |
| 340 | "tree", |
| 341 | &TreeQueryPayload { |
| 342 | target, |
| 343 | path_prefix: Some("src/".into()), |
| 344 | page: page.clone(), |
| 345 | }, |
| 346 | ); |
| 347 | p.check( |
| 348 | "diff", |
| 349 | &DiffQueryPayload { |
| 350 | base, |
| 351 | target, |
| 352 | page: page.clone(), |
| 353 | }, |
| 354 | ); |
| 355 | p.check( |
| 356 | "history", |
| 357 | &HistoryQueryPayload { |
| 358 | ancestor_of: Some(id), |
| 359 | path_filter: None, |
| 360 | page: page.clone(), |
| 361 | }, |
| 362 | ); |
| 363 | p.check( |
| 364 | "conflicts", |
| 365 | &ConflictQueryPayload { |
| 366 | candidate: id, |
| 367 | against: Some(s.envelope.parent_changesets.clone()), |
| 368 | page: page.clone(), |
| 369 | }, |
| 370 | ); |
| 371 | p.check( |
| 372 | "watch", |
| 373 | &WatchQueryPayload { |
| 374 | subscriber_id: s.envelope.author_did.clone(), |
| 375 | after_seq: Some(WalSeq(u64::MAX)), |
| 376 | page, |
| 377 | }, |
| 378 | ); |
| 379 | p.check( |
| 380 | "advisory", |
| 381 | &ChangesetAdvisoryPayload { |
| 382 | base, |
| 383 | latest: Some(target), |
| 384 | paths: s |
| 385 | .envelope |
| 386 | .mutations |
| 387 | .iter() |
| 388 | .map(|m| format!("{m:?}")) |
| 389 | .collect(), |
| 390 | agent: s.envelope.author_did.clone(), |
| 391 | snapshot_seq: None, |
| 392 | }, |
| 393 | ); |
| 394 | p.check( |
| 395 | "crumb", |
| 396 | &CrumbContextQueryPayload { |
| 397 | target, |
| 398 | path: ".".into(), |
| 399 | snapshot_seq: Some(WalSeq(0)), |
| 400 | }, |
| 401 | ); |
| 402 | p.check( |
| 403 | "evidence base", |
| 404 | &EvidenceBaseQueryPayload { |
| 405 | changeset_id: id, |
| 406 | snapshot_seq: None, |
| 407 | }, |
| 408 | ); |
| 409 | p.check( |
| 410 | "verify receipt", |
| 411 | &VerifyEvidenceReceiptPayload { |
| 412 | receipt: s.envelope.signature.clone(), |
| 413 | snapshot_seq: Some(WalSeq(3)), |
| 414 | }, |
| 415 | ); |
| 416 | p.check("status", &(id, Some(WalSeq(1)), None::<WalSeq>)); |
| 417 | p.check("file", &(target, "README.md".to_string(), Some(WalSeq(2)))); |
| 418 | p.check("receipt", &(id, None::<WalSeq>)); |
| 419 | p.check("snapshot", &Some(WalSeq(7))); |
| 420 | } |
| 421 | assert!( |
| 422 | submits >= 2 && blob_bytes > 0, |
| 423 | "{submits} submits, {blob_bytes} blob bytes" |
| 424 | ); |
| 425 | println!( |
| 426 | "recorded parity: {} records, {submits} submits ({blob_bytes} blob bytes), {} payloads, {} JSON bytes", |
| 427 | v1.len() + v2.len(), |
| 428 | p.cases, |
| 429 | p.json_bytes |
| 430 | ); |
| 431 | } |
| 432 | |
| 433 | #[test] |
| 434 | fn new_digest_equals_old_on_edge_values() { |
| 435 | let mut p = Parity::default(); |
| 436 | let all_bytes: Vec<u8> = (0..=255u8).collect(); |
| 437 | let all_chars: String = (0u32..0x800).filter_map(char::from_u32).collect(); |
| 438 | p.check("empty", &()); |
| 439 | p.check("empty string", ""); |
| 440 | p.check("empty blob", &Vec::<u8>::new()); |
| 441 | p.check("every byte value", &all_bytes); |
| 442 | p.check("every char below U+0800", &all_chars); |
| 443 | p.check( |
| 444 | "escapes", |
| 445 | "quote \" backslash \\ slash / \u{0} \u{1f} \u{7f} \n\r\t\u{8}\u{c}", |
| 446 | ); |
| 447 | p.check("astral", "\u{1F600}\u{10FFFF}"); |
| 448 | p.check( |
| 449 | "numbers", |
| 450 | &(u64::MAX, i64::MIN, 0u8, u16::MAX, u32::MAX, i8::MIN), |
| 451 | ); |
| 452 | p.check("nested", &vec![vec![Some(vec![0u8; 0]), None], vec![]]); |
| 453 | let mut map = BTreeMap::new(); |
| 454 | map.insert("k\u{0}ey".to_string(), all_bytes.clone()); |
| 455 | map.insert(String::new(), Vec::new()); |
| 456 | p.check("map", &map); |
| 457 | // A payload just over, at, and under the 8 KiB staging buffer, in every alignment. |
| 458 | for len in 2_700..2_760usize { |
| 459 | p.check(&format!("blob {len}"), &vec![b'7'; len]); |
| 460 | p.check(&format!("string {len}"), &"x".repeat(len * 3)); |
| 461 | } |
| 462 | // One write larger than the staging buffer (a long string is written in one piece). |
| 463 | p.check("long string", &"\u{e9}".repeat(20_000)); |
| 464 | } |
| 465 | |
| 466 | #[test] |
| 467 | fn a_payload_that_cannot_serialize_is_refused_with_the_same_code_and_message() { |
| 468 | let mut bad: BTreeMap<(u8, u8), u8> = BTreeMap::new(); |
| 469 | bad.insert((1, 2), 3); |
| 470 | let old = old_digest(&bad).unwrap_err(); |
| 471 | let new = payload_digest(&bad).unwrap_err(); |
| 472 | assert_eq!(new.code, RefusalCode::IoFailure); |
| 473 | assert_eq!(new.message, old); |
| 474 | } |
| 475 | |
| 476 | struct Authority { |
| 477 | repo: RepoId, |
| 478 | authority: SigningKey, |
| 479 | agent: SigningKey, |
| 480 | } |
| 481 | |
| 482 | impl Authority { |
| 483 | fn new() -> Self { |
| 484 | Self { |
| 485 | repo: RepoId::new("payload-digest-parity").unwrap(), |
| 486 | authority: SigningKey::from_bytes(&derived("authority", 0)), |
| 487 | agent: SigningKey::from_bytes(&derived("agent", 0)), |
| 488 | } |
| 489 | } |
| 490 | |
| 491 | fn enforcer(&self) -> PolicyEnforcer { |
| 492 | let mut e = PolicyEnforcer::new(); |
| 493 | e.register_repo_authority( |
| 494 | self.repo.clone(), |
| 495 | encode_did_key_ed25519(&self.authority.verifying_key().to_bytes()), |
| 496 | ); |
| 497 | e |
| 498 | } |
| 499 | |
| 500 | fn request( |
| 501 | &self, |
| 502 | n: u64, |
| 503 | max_bytes_per_op: u64, |
| 504 | p: SubmitChangesetPayload, |
| 505 | ) -> AuthenticatedRequest<SubmitChangesetPayload> { |
| 506 | let grant = AgentCapabilityGrant::issue( |
| 507 | &self.authority, |
| 508 | derived("grant", n), |
| 509 | self.repo.clone(), |
| 510 | encode_did_key_ed25519(&self.agent.verifying_key().to_bytes()), |
| 511 | vec![Capability::Propose], |
| 512 | max_bytes_per_op, |
| 513 | 1_000, |
| 514 | 60_000, |
| 515 | 1_000, |
| 516 | 1_000_000, |
| 517 | ); |
| 518 | AuthenticatedRequest::sign_new( |
| 519 | &self.agent, |
| 520 | grant, |
| 521 | self.repo.clone(), |
| 522 | Capability::Propose, |
| 523 | derived("nonce", n), |
| 524 | 2_000, |
| 525 | 0, |
| 526 | p, |
| 527 | ) |
| 528 | .unwrap() |
| 529 | } |
| 530 | |
| 531 | fn authorize( |
| 532 | &self, |
| 533 | req: &AuthenticatedRequest<SubmitChangesetPayload>, |
| 534 | ) -> Result<(), RefusalCode> { |
| 535 | self.enforcer() |
| 536 | .authorize( |
| 537 | BoundaryKind::Api, |
| 538 | "submit", |
| 539 | &self.repo, |
| 540 | Capability::Propose, |
| 541 | req, |
| 542 | 2_000, |
| 543 | ) |
| 544 | .map_err(|e| e.code) |
| 545 | } |
| 546 | } |
| 547 | |
| 548 | #[test] |
| 549 | fn refusal_codes_are_unchanged_for_every_recorded_submit() { |
| 550 | let a = Authority::new(); |
| 551 | let mut checked = 0; |
| 552 | for (n, (id, s)) in all_recorded_submits().into_iter().enumerate() { |
| 553 | let n = n as u64 * 8; |
| 554 | let what = id.to_hex(); |
| 555 | let (old_sha, json_len) = old_digest(&s).unwrap(); |
| 556 | |
| 557 | // Admitted, and the signed digest and length are the old ones. |
| 558 | let req = a.request(n, u64::MAX, s.clone()); |
| 559 | assert_eq!(req.payload_sha256, old_sha, "{what}"); |
| 560 | assert_eq!(req.payload_bytes_len, json_len, "{what}"); |
| 561 | assert_eq!(a.authorize(&req), Ok(()), "{what}"); |
| 562 | |
| 563 | // Quota boundary: the counted length is exactly the old JSON length. |
| 564 | assert_eq!( |
| 565 | a.authorize(&a.request(n + 1, json_len, s.clone())), |
| 566 | Ok(()), |
| 567 | "{what}" |
| 568 | ); |
| 569 | assert_eq!( |
| 570 | a.authorize(&a.request(n + 2, json_len - 1, s.clone())), |
| 571 | Err(RefusalCode::QuotaPayloadTooLarge), |
| 572 | "{what}" |
| 573 | ); |
| 574 | |
| 575 | // A payload changed after signing is refused at the digest check. |
| 576 | let mut tampered = req.clone(); |
| 577 | tampered.payload.envelope.intent_summary.push('!'); |
| 578 | assert_eq!( |
| 579 | a.authorize(&tampered), |
| 580 | Err(RefusalCode::AuthSignatureInvalid), |
| 581 | "{what}" |
| 582 | ); |
| 583 | if !req.payload.blobs.is_empty() { |
| 584 | let mut t = req.clone(); |
| 585 | t.payload.blobs[0].1.push(0); |
| 586 | assert_eq!( |
| 587 | a.authorize(&t), |
| 588 | Err(RefusalCode::AuthSignatureInvalid), |
| 589 | "{what}" |
| 590 | ); |
| 591 | } |
| 592 | |
| 593 | // A digest changed after signing is refused (the signature binds it). |
| 594 | let mut t = req.clone(); |
| 595 | t.payload_sha256[0] ^= 1; |
| 596 | assert_eq!( |
| 597 | a.authorize(&t), |
| 598 | Err(RefusalCode::AuthSignatureInvalid), |
| 599 | "{what}" |
| 600 | ); |
| 601 | |
| 602 | // A declared length lowered after signing is refused by the signature, not the quota. |
| 603 | let mut t = req.clone(); |
| 604 | t.payload_bytes_len -= 1; |
| 605 | assert_eq!( |
| 606 | a.authorize(&t), |
| 607 | Err(RefusalCode::AuthSignatureInvalid), |
| 608 | "{what}" |
| 609 | ); |
| 610 | checked += 1; |
| 611 | } |
| 612 | assert!(checked >= 2, "{checked} recorded submits"); |
| 613 | } |