synapse
A component of the AienOS ecosystem.
Brought by drakestapleton
GitHub aien-dev/synapse#99 (code only)
Apply it
git checkout -b patch-d8628e3eab6197e7 3d78efe83d5d08b67848e4b32a83112a95dd2a9d curl -fsSL https://interplane.io/drakestapleton/synapse/patches/d8628e3eab6197e7.patch | git am
Provenance
github-import 1
aien-dev/synapse
99
04ea9040447867312f603b2c9f2bc3249c52c3dc
{"kind":"github-import","owner":"aien-dev","repo":"synapse","number":99,"url":"https://github.com/aien-dev/synapse/pull/99","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:39:20Z","metadata":"unavailable","state_derived":true}
Changes
diff --git a/.crumb b/.crumb index 495a32d..4e2a4af 100644 --- a/.crumb +++ b/.crumb @@ -45,14 +45,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-16T09:12:08Z", + "compiled_at": "2026-10-17T04:07:37Z", "compiler": "crumb-compile/1", - "digest": "sha256:279410a8da95ac0a5c9e9cf32a56684e2ca85469ad52267efcce5e6dbbbef821", - "evidence_files": 241, - "evidence_root": "sha256:f103bd6c7728e5a399cede51d9c64e4d42afc97e0d48dd424536b6cc72e48314", - "files": 411, - "generated_at_commit": "5d287e0e4ab4439f79711243518c0a83cce56eff", - "source_tree": "sha256:07947598e29d8d8fca9b546541ebe7e575c954cf18901eeb74304d2a9f594e2b" + "digest": "sha256:c4d06c37f13491b0557bff87397838e0b6e452af30e69669d8d1cac87b73eda8", + "evidence_files": 244, + "evidence_root": "sha256:f315c6bd537c64571a2e69e3f7a39ec2ab2a84af8d6f6a3ce7a34085b9e92629", + "files": 422, + "generated_at_commit": "98b6debd65e0bb08b490119a9d8c47bbb434f3dd", + "source_tree": "sha256:b4d270454c3c5d90bea670ec647884567c81d275bfcfca7ffedba5706071f026" }, "synapse": { "component_paths": { diff --git a/crates/synapse-api/tests/payload_digest_parity.rs b/crates/synapse-api/tests/payload_digest_parity.rs new file mode 100644 index 0000000..78ae59a --- /dev/null +++ b/crates/synapse-api/tests/payload_digest_parity.rs @@ -0,0 +1,613 @@ +//! Issue #92 parity proof: `synapse_auth::payload_digest` (compact JSON streamed into SHA-256) +//! returns exactly what the old code computed, `(SHA-256(serde_json::to_vec(p)), its length)`, +//! and every refusal code of `PolicyEnforcer::authorize` is unchanged. +//! +//! Corpus: +//! * the A1 malformed corpus, regenerated here the same way +//! `crates/synapse-store/tests/a1_malformed_corpus.rs` builds it (one binary-v2 WAL frame per +//! record kind from the `a1-v1` fixture, every truncation, every bit flip, oversized frame and +//! inner lengths, and every truncation and bit flip of the v2 checkpoint), with each damaged +//! byte string carried both as a blob in a `SubmitChangesetPayload` and as a lossy UTF-8 +//! string, so JSON number arrays and string escaping are both exercised; +//! * recorded requests: every record of the `a1-v1` WAL fixtures (v1 JSON log and v2 binary +//! log), each `ChangesetIngest` rebuilt into the `SubmitChangesetPayload` that produced it +//! (envelope plus the recorded blob bytes), and one payload of every query type built from +//! the recorded ids; +//! * edge values: escapes, control characters, non-ASCII text, empty and maximal numbers. + +use ed25519_dalek::SigningKey; +use serde::Serialize; +use sha2::{Digest, Sha256}; +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; +use synapse_api::{ + ChangesetAdvisoryPayload, ConflictQueryPayload, CrumbContextQueryPayload, DiffQueryPayload, + EvidenceBaseQueryPayload, HistoryQueryPayload, PageRequest, SubmitChangesetPayload, + TreeQueryPayload, TreeTarget, VerifyEvidenceReceiptPayload, WatchQueryPayload, +}; +use synapse_auth::{ + payload_digest, AgentCapabilityGrant, AuthenticatedRequest, BoundaryKind, Capability, + PolicyEnforcer, +}; +use synapse_core::{ + encode_did_key_ed25519, BlobDigest, ChangesetEnvelope, ChangesetId, RefusalCode, RepoId, WalSeq, +}; +use synapse_store::codec::{ + decode_record_with, encode_checkpoint_v2, encode_record, CheckpointState, WAL_FLAG_CODEC_V2, +}; +use synapse_store::wal2::{WAL_V2_ALIGN, WAL_V2_BATCH_HEADER_LEN, WAL_V2_BATCH_MAGIC}; +use synapse_store::{ + encode_wal_frame, wal_frame_from_payload, CheckpointManifest, RecordCodec, WalRecord, + WAL_HEADER_LEN, +}; + +/// Same record cap as the A1 corpus. +const CAP: u64 = 1 << 20; + +fn fixtures() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("../synapse-store/tests/fixtures/a1-v1") +} + +fn fixture(rel: &str) -> Vec<u8> { + std::fs::read(fixtures().join(rel)).unwrap_or_else(|e| panic!("fixture {rel}: {e}")) +} + +fn derived(label: &str, counter: u64) -> [u8; 32] { + let mut h = Sha256::new(); + h.update(b"SYNAPSE_API_PAYLOAD_DIGEST_PARITY_V1\0"); + h.update(label.as_bytes()); + h.update(counter.to_le_bytes()); + h.finalize().into() +} + +/// The digest exactly as `check_request_inner` and `sign_new` computed it before #92. +fn old_digest<T: Serialize + ?Sized>(p: &T) -> Result<([u8; 32], u64), String> { + let json = serde_json::to_vec(p).map_err(|e| format!("serialize payload: {e}"))?; + Ok((Sha256::digest(&json).into(), json.len() as u64)) +} + +#[derive(Default)] +struct Parity { + cases: usize, + json_bytes: u64, +} + +impl Parity { + fn check<T: Serialize + ?Sized>(&mut self, what: &str, p: &T) { + let old = old_digest(p).unwrap_or_else(|e| panic!("{what}: old digest failed: {e}")); + let new = payload_digest(p).unwrap_or_else(|e| panic!("{what}: new digest failed: {e}")); + assert_eq!(new, old, "{what}: digest or length differs"); + self.cases += 1; + self.json_bytes += old.1; + } + + /// One damaged byte string, as a blob and as a lossy string. + fn bytes(&mut self, what: &str, envelope: &ChangesetEnvelope, b: &[u8]) { + self.check( + what, + &SubmitChangesetPayload { + envelope: envelope.clone(), + blobs: vec![(BlobDigest::compute(b), b.to_vec())], + }, + ); + self.check(what, &String::from_utf8_lossy(b)); + } +} + +/// Every record of the v1 JSON WAL fixture, in log order. +fn v1_records() -> Vec<WalRecord> { + let log = fixture("v1-wal-log/wal.log"); + let mut out = Vec::new(); + let mut at = 0; + while at < log.len() { + let len = u32::from_le_bytes(log[at + 48..at + 52].try_into().unwrap()) as usize; + let payload = &log[at + WAL_HEADER_LEN..at + WAL_HEADER_LEN + len]; + out.push(serde_json::from_slice(payload).unwrap()); + at += WAL_HEADER_LEN + len; + } + out +} + +type Blobs = BTreeMap<BlobDigest, Vec<u8>>; + +/// Every record of the WAL v2 fixture (`wal.v2.log`: 4 KiB-aligned `SWB2` batches; each frame +/// payload is `u32 meta_len | meta | u32 blob_count | (digest[32] | u32 len | bytes)*`), with +/// its inline blobs. +fn v2_records() -> (Vec<WalRecord>, Blobs) { + let log = fixture("v1-wal-v2-log/wal.v2.log"); + let u32_at = |b: &[u8], o: usize| u32::from_le_bytes(b[o..o + 4].try_into().unwrap()) as usize; + let mut records = Vec::new(); + let mut blobs = Blobs::new(); + let mut off = 0usize; + while off + WAL_V2_BATCH_HEADER_LEN <= log.len() && log[off..off + 4] == WAL_V2_BATCH_MAGIC { + let count = u32_at(&log, off + 8); + let body = u64::from_le_bytes(log[off + 16..off + 24].try_into().unwrap()) as usize; + let mut at = off + WAL_V2_BATCH_HEADER_LEN; + for _ in 0..count { + let h = &log[at..at + WAL_HEADER_LEN]; + let len = u32_at(h, 48); + let p = &log[at + WAL_HEADER_LEN..at + WAL_HEADER_LEN + len]; + let codec = if h[7] == WAL_FLAG_CODEC_V2 { + RecordCodec::BinaryV2 + } else { + RecordCodec::JsonV1 + }; + let meta_len = u32_at(p, 0); + records.push(decode_record_with(&p[4..4 + meta_len], codec, CAP).unwrap()); + let mut b = 4 + meta_len; + let n = u32_at(p, b); + b += 4; + for _ in 0..n { + let digest = BlobDigest(p[b..b + 32].try_into().unwrap()); + let blen = u32_at(p, b + 32); + let bytes = p[b + 36..b + 36 + blen].to_vec(); + assert_eq!(BlobDigest::compute(&bytes), digest, "inline blob"); + blobs.insert(digest, bytes); + b += 36 + blen; + } + at += WAL_HEADER_LEN + len; + } + let end = (off + WAL_V2_BATCH_HEADER_LEN + body) as u64; + off = end.div_ceil(WAL_V2_ALIGN) as usize * WAL_V2_ALIGN as usize; + } + (records, blobs) +} + +/// The blobs recorded in the v1 fixture's blob store (`blobs/<2 hex>/<64 hex>`). +fn v1_blobs() -> Blobs { + let mut out = Blobs::new(); + for dir in std::fs::read_dir(fixtures().join("v1-wal-log/blobs")).unwrap() { + for file in std::fs::read_dir(dir.unwrap().path()).unwrap() { + let file = file.unwrap(); + let digest = BlobDigest::from_hex(file.file_name().to_str().unwrap()).unwrap(); + let bytes = std::fs::read(file.path()).unwrap(); + assert_eq!(BlobDigest::compute(&bytes), digest, "stored blob"); + out.insert(digest, bytes); + } + } + out +} + +fn one_record_per_kind(records: &[WalRecord]) -> Vec<WalRecord> { + let mut by_kind = BTreeMap::new(); + for r in records { + by_kind.entry(r.kind_byte()).or_insert_with(|| r.clone()); + } + assert_eq!(by_kind.len(), 6, "fixture must hold all six record kinds"); + by_kind.into_values().collect() +} + +fn first_envelope(records: &[WalRecord]) -> ChangesetEnvelope { + records + .iter() + .find_map(|r| match r { + WalRecord::ChangesetIngest { envelope, .. } => Some(envelope.clone()), + _ => None, + }) + .expect("fixture holds a changeset") +} + +/// The `SubmitChangesetPayload` each recorded `ChangesetIngest` was admitted from: its +/// envelope and the bytes of every blob it introduced. +fn recorded_submits( + records: &[WalRecord], + blobs: &Blobs, +) -> Vec<(ChangesetId, SubmitChangesetPayload)> { + records + .iter() + .filter_map(|r| match r { + WalRecord::ChangesetIngest { + envelope, + changeset_id, + new_blobs, + } => Some(( + *changeset_id, + SubmitChangesetPayload { + envelope: envelope.clone(), + blobs: new_blobs + .iter() + .map(|d| { + let b = blobs.get(d).unwrap_or_else(|| panic!("blob {d} recorded")); + (*d, b.clone()) + }) + .collect(), + }, + )), + _ => None, + }) + .collect() +} + +/// Every recorded submit of both fixtures. +fn all_recorded_submits() -> Vec<(ChangesetId, SubmitChangesetPayload)> { + let (v2, v2_blobs) = v2_records(); + let mut out = recorded_submits(&v1_records(), &v1_blobs()); + out.extend(recorded_submits(&v2, &v2_blobs)); + out +} + +#[test] +fn new_digest_equals_old_over_the_a1_malformed_corpus() { + let records = v1_records(); + let envelope = first_envelope(&records); + let mut p = Parity::default(); + let mut classes: BTreeMap<&str, usize> = BTreeMap::new(); + let prev = derived("prev-frame", 0); + for r in one_record_per_kind(&records) { + let kind = r.kind_byte(); + let (frame, _) = encode_wal_frame(WalSeq(1), prev, &r, RecordCodec::BinaryV2, CAP).unwrap(); + p.bytes(&format!("kind {kind} frame"), &envelope, &frame); + for n in 0..frame.len() { + p.bytes( + &format!("kind {kind} truncated to {n}"), + &envelope, + &frame[..n], + ); + *classes.entry("truncated").or_default() += 1; + } + for bit in 0..frame.len() * 8 { + let mut f = frame.clone(); + f[bit / 8] ^= 1 << (bit % 8); + p.bytes(&format!("kind {kind} bit {bit}"), &envelope, &f); + *classes.entry("bit_flipped").or_default() += 1; + } + for declared in [CAP + 1, 2 * CAP, u64::from(u32::MAX)] { + let mut f = frame.clone(); + f[48..52].copy_from_slice(&(declared as u32).to_le_bytes()); + p.bytes(&format!("kind {kind} declares {declared}"), &envelope, &f); + *classes.entry("oversized_frame_length").or_default() += 1; + } + let bin = encode_record(&r).unwrap(); + for off in 0..bin.len().saturating_sub(4) { + let mut b = bin.clone(); + b[off..off + 4].copy_from_slice(&u32::MAX.to_le_bytes()); + let (f, _) = wal_frame_from_payload(WalSeq(1), prev, kind, frame[7], &b); + p.bytes(&format!("kind {kind} inner length at {off}"), &envelope, &f); + *classes.entry("oversized_inner_length").or_default() += 1; + } + } + let manifest: CheckpointManifest = + serde_json::from_slice(&fixture("v1-wal-log/checkpoint.v1")).unwrap(); + let state = CheckpointState::from_v1_manifest(manifest).unwrap(); + let (ckpt, _) = + encode_checkpoint_v2(&state, derived("v1-root", 0), derived("prev-ckpt", 0)).unwrap(); + for n in 0..ckpt.len() { + p.bytes( + &format!("checkpoint truncated to {n}"), + &envelope, + &ckpt[..n], + ); + *classes.entry("checkpoint_truncated").or_default() += 1; + } + for bit in 0..ckpt.len() * 8 { + let mut c = ckpt.clone(); + c[bit / 8] ^= 1 << (bit % 8); + p.bytes(&format!("checkpoint bit {bit}"), &envelope, &c); + *classes.entry("checkpoint_bit_flipped").or_default() += 1; + } + println!( + "A1 corpus parity: {} payloads, {} JSON bytes, classes {classes:?}", + p.cases, p.json_bytes + ); + for class in [ + "truncated", + "bit_flipped", + "oversized_frame_length", + "oversized_inner_length", + "checkpoint_truncated", + "checkpoint_bit_flipped", + ] { + assert!( + classes.get(class).copied().unwrap_or(0) > 0, + "{class} empty" + ); + } +} + +#[test] +fn new_digest_equals_old_for_every_recorded_request() { + let v1 = v1_records(); + let (v2, _) = v2_records(); + assert!(!v2.is_empty(), "v2 fixture decodes"); + let mut p = Parity::default(); + let mut submits = 0; + let mut blob_bytes = 0; + for (i, r) in v1.iter().chain(v2.iter()).enumerate() { + p.check(&format!("record {i}"), r); + } + for (id, s) in all_recorded_submits() { + blob_bytes += s.blobs.iter().map(|(_, b)| b.len()).sum::<usize>(); + p.check(&format!("submit {}", id.to_hex()), &s); + // The same submit carrying bench-sized blobs (the write benches submit about 12 KiB). + for size in [12 * 1024, 1 << 20] { + let mut big = s.clone(); + let blob: Vec<u8> = (0..size) + .map(|i| derived("bench-blob", (i / 32) as u64)[i % 32]) + .collect(); + big.blobs.push((BlobDigest::compute(&blob), blob)); + p.check(&format!("submit {} + {size} B blob", id.to_hex()), &big); + } + submits += 1; + let page = PageRequest { + cursor: Some(id.to_hex()), + limit: 100, + min_visible_seq: Some(WalSeq(1)), + snapshot_seq: None, + }; + let base = TreeTarget::BaseGitCommit(s.envelope.base_git_oid); + let target = TreeTarget::Changeset(id); + p.check( + "tree", + &TreeQueryPayload { + target, + path_prefix: Some("src/".into()), + page: page.clone(), + }, + ); + p.check( + "diff", + &DiffQueryPayload { + base, + target, + page: page.clone(), + }, + ); + p.check( + "history", + &HistoryQueryPayload { + ancestor_of: Some(id), + path_filter: None, + page: page.clone(), + }, + ); + p.check( + "conflicts", + &ConflictQueryPayload { + candidate: id, + against: Some(s.envelope.parent_changesets.clone()), + page: page.clone(), + }, + ); + p.check( + "watch", + &WatchQueryPayload { + subscriber_id: s.envelope.author_did.clone(), + after_seq: Some(WalSeq(u64::MAX)), + page, + }, + ); + p.check( + "advisory", + &ChangesetAdvisoryPayload { + base, + latest: Some(target), + paths: s + .envelope + .mutations + .iter() + .map(|m| format!("{m:?}")) + .collect(), + agent: s.envelope.author_did.clone(), + snapshot_seq: None, + }, + ); + p.check( + "crumb", + &CrumbContextQueryPayload { + target, + path: ".".into(), + snapshot_seq: Some(WalSeq(0)), + }, + ); + p.check( + "evidence base", + &EvidenceBaseQueryPayload { + changeset_id: id, + snapshot_seq: None, + }, + ); + p.check( + "verify receipt", + &VerifyEvidenceReceiptPayload { + receipt: s.envelope.signature.clone(), + snapshot_seq: Some(WalSeq(3)), + }, + ); + p.check("status", &(id, Some(WalSeq(1)), None::<WalSeq>)); + p.check("file", &(target, "README.md".to_string(), Some(WalSeq(2)))); + p.check("receipt", &(id, None::<WalSeq>)); + p.check("snapshot", &Some(WalSeq(7))); + } + assert!( + submits >= 2 && blob_bytes > 0, + "{submits} submits, {blob_bytes} blob bytes" + ); + println!( + "recorded parity: {} records, {submits} submits ({blob_bytes} blob bytes), {} payloads, {} JSON bytes", + v1.len() + v2.len(), + p.cases, + p.json_bytes + ); +} + +#[test] +fn new_digest_equals_old_on_edge_values() { + let mut p = Parity::default(); + let all_bytes: Vec<u8> = (0..=255u8).collect(); + let all_chars: String = (0u32..0x800).filter_map(char::from_u32).collect(); + p.check("empty", &()); + p.check("empty string", ""); + p.check("empty blob", &Vec::<u8>::new()); + p.check("every byte value", &all_bytes); + p.check("every char below U+0800", &all_chars); + p.check( + "escapes", + "quote \" backslash \\ slash / \u{0} \u{1f} \u{7f} \n\r\t\u{8}\u{c}", + ); + p.check("astral", "\u{1F600}\u{10FFFF}"); + p.check( + "numbers", + &(u64::MAX, i64::MIN, 0u8, u16::MAX, u32::MAX, i8::MIN), + ); + p.check("nested", &vec![vec![Some(vec![0u8; 0]), None], vec![]]); + let mut map = BTreeMap::new(); + map.insert("k\u{0}ey".to_string(), all_bytes.clone()); + map.insert(String::new(), Vec::new()); + p.check("map", &map); + // A payload just over, at, and under the 8 KiB staging buffer, in every alignment. + for len in 2_700..2_760usize { + p.check(&format!("blob {len}"), &vec![b'7'; len]); + p.check(&format!("string {len}"), &"x".repeat(len * 3)); + } + // One write larger than the staging buffer (a long string is written in one piece). + p.check("long string", &"\u{e9}".repeat(20_000)); +} + +#[test] +fn a_payload_that_cannot_serialize_is_refused_with_the_same_code_and_message() { + let mut bad: BTreeMap<(u8, u8), u8> = BTreeMap::new(); + bad.insert((1, 2), 3); + let old = old_digest(&bad).unwrap_err(); + let new = payload_digest(&bad).unwrap_err(); + assert_eq!(new.code, RefusalCode::IoFailure); + assert_eq!(new.message, old); +} + +struct Authority { + repo: RepoId, + authority: SigningKey, + agent: SigningKey, +} + +impl Authority { + fn new() -> Self { + Self { + repo: RepoId::new("payload-digest-parity").unwrap(), + authority: SigningKey::from_bytes(&derived("authority", 0)), + agent: SigningKey::from_bytes(&derived("agent", 0)), + } + } + + fn enforcer(&self) -> PolicyEnforcer { + let mut e = PolicyEnforcer::new(); + e.register_repo_authority( + self.repo.clone(), + encode_did_key_ed25519(&self.authority.verifying_key().to_bytes()), + ); + e + } + + fn request( + &self, + n: u64, + max_bytes_per_op: u64, + p: SubmitChangesetPayload, + ) -> AuthenticatedRequest<SubmitChangesetPayload> { + let grant = AgentCapabilityGrant::issue( + &self.authority, + derived("grant", n), + self.repo.clone(), + encode_did_key_ed25519(&self.agent.verifying_key().to_bytes()), + vec![Capability::Propose], + max_bytes_per_op, + 1_000, + 60_000, + 1_000, + 1_000_000, + ); + AuthenticatedRequest::sign_new( + &self.agent, + grant, + self.repo.clone(), + Capability::Propose, + derived("nonce", n), + 2_000, + 0, + p, + ) + .unwrap() + } + + fn authorize( + &self, + req: &AuthenticatedRequest<SubmitChangesetPayload>, + ) -> Result<(), RefusalCode> { + self.enforcer() + .authorize( + BoundaryKind::Api, + "submit", + &self.repo, + Capability::Propose, + req, + 2_000, + ) + .map_err(|e| e.code) + } +} + +#[test] +fn refusal_codes_are_unchanged_for_every_recorded_submit() { + let a = Authority::new(); + let mut checked = 0; + for (n, (id, s)) in all_recorded_submits().into_iter().enumerate() { + let n = n as u64 * 8; + let what = id.to_hex(); + let (old_sha, json_len) = old_digest(&s).unwrap(); + + // Admitted, and the signed digest and length are the old ones. + let req = a.request(n, u64::MAX, s.clone()); + assert_eq!(req.payload_sha256, old_sha, "{what}"); + assert_eq!(req.payload_bytes_len, json_len, "{what}"); + assert_eq!(a.authorize(&req), Ok(()), "{what}"); + + // Quota boundary: the counted length is exactly the old JSON length. + assert_eq!( + a.authorize(&a.request(n + 1, json_len, s.clone())), + Ok(()), + "{what}" + ); + assert_eq!( + a.authorize(&a.request(n + 2, json_len - 1, s.clone())), + Err(RefusalCode::QuotaPayloadTooLarge), + "{what}" + ); + + // A payload changed after signing is refused at the digest check. + let mut tampered = req.clone(); + tampered.payload.envelope.intent_summary.push('!'); + assert_eq!( + a.authorize(&tampered), + Err(RefusalCode::AuthSignatureInvalid), + "{what}" + ); + if !req.payload.blobs.is_empty() { + let mut t = req.clone(); + t.payload.blobs[0].1.push(0); + assert_eq!( + a.authorize(&t), + Err(RefusalCode::AuthSignatureInvalid), + "{what}" + ); + } + + // A digest changed after signing is refused (the signature binds it). + let mut t = req.clone(); + t.payload_sha256[0] ^= 1; + assert_eq!( + a.authorize(&t), + Err(RefusalCode::AuthSignatureInvalid), + "{what}" + ); + + // A declared length lowered after signing is refused by the signature, not the quota. + let mut t = req.clone(); + t.payload_bytes_len -= 1; + assert_eq!( + a.authorize(&t), + Err(RefusalCode::AuthSignatureInvalid), + "{what}" + ); + checked += 1; + } + assert!(checked >= 2, "{checked} recorded submits"); +} diff --git a/crates/synapse-auth/src/digest.rs b/crates/synapse-auth/src/digest.rs new file mode 100644 index 0000000..9e16b81 --- /dev/null +++ b/crates/synapse-auth/src/digest.rs @@ -0,0 +1,204 @@ +//! Request payload digest (issue #92). +//! +//! `payload_sha256` is defined as SHA-256 over the payload's compact `serde_json` encoding, and +//! `payload_bytes_len` is at least that encoding's length. The agent signs both through +//! `AuthenticatedRequest::canonical_signable_bytes`, so the definition is part of the protocol +//! and does not change here. What changes is only how the bytes reach the hash: the serializer +//! writes them through a small fixed staging buffer straight into SHA-256 instead of first +//! collecting the whole JSON text in one growing `Vec` (`serde_json::to_vec`) and hashing that. +//! +//! Equivalence with `SHA-256(serde_json::to_vec(payload))`: +//! * `serde_json::to_vec(v)` is `v.serialize(&mut Serializer::new(Vec::with_capacity(128)))`, +//! and `Serializer::new` is `Serializer::with_formatter(_, CompactFormatter)`, where +//! `CompactFormatter` overrides nothing (`impl Formatter for CompactFormatter {}`): every +//! byte comes from the `Formatter` trait's default methods. +//! * [`DigestFormatter`] also takes every default method except `write_u8`, which it answers +//! from a table instead of `itoa`. The table's 256 entries are checked against +//! `serde_json::to_vec(&v)` for every `u8` value in the unit tests below. +//! * The serializer drives the formatter the same way whatever the writer is, so the byte +//! sequence is identical; the writer only decides where the bytes go. SHA-256 depends only +//! on that sequence, not on how it is split across `update` calls, and the counted length is +//! the number of bytes written. Writes never fail, so a serialization error comes only from +//! the payload's `Serialize` impl, the same error with the same message as before. +//! +//! The parity tests in `crates/synapse-api/tests/payload_digest_parity.rs` check the result +//! against the old computation over the A1 malformed corpus and recorded requests. + +use serde::Serialize; +use serde_json::ser::Formatter; +use sha2::{Digest, Sha256}; +use std::io; +use synapse_core::{RefusalCode, SynapseError, SynapseResult}; + +/// Size of the staging buffer between the JSON serializer and SHA-256. +pub(crate) const DIGEST_STAGING_BYTES: usize = 8 * 1024; + +/// `io::Write` sink that hashes everything written to it and counts the bytes. +struct DigestWriter { + staged: Vec<u8>, + hasher: Sha256, + hashed: u64, +} + +impl DigestWriter { + fn new() -> Self { + Self { + staged: Vec::with_capacity(DIGEST_STAGING_BYTES), + hasher: Sha256::new(), + hashed: 0, + } + } + + fn drain(&mut self) { + self.hasher.update(&self.staged); + self.hashed += self.staged.len() as u64; + self.staged.clear(); + } + + /// The staging buffer cannot take `data`: hash what is staged, then stage `data`, or hash + /// it directly when it is at least a buffer long. + #[cold] + #[inline(never)] + fn spill(&mut self, data: &[u8]) { + self.drain(); + if data.len() >= DIGEST_STAGING_BYTES { + self.hasher.update(data); + self.hashed += data.len() as u64; + } else { + self.staged.extend_from_slice(data); + } + } + + fn finish(mut self) -> ([u8; 32], u64) { + self.drain(); + (self.hasher.finalize().into(), self.hashed) + } +} + +impl io::Write for DigestWriter { + #[inline] + fn write(&mut self, data: &[u8]) -> io::Result<usize> { + self.write_all(data)?; + Ok(data.len()) + } + + #[inline(always)] + fn write_all(&mut self, data: &[u8]) -> io::Result<()> { + // The buffer never grows past its initial capacity: what does not fit spills. + if self.staged.capacity() - self.staged.len() >= data.len() { + self.staged.extend_from_slice(data); + } else { + self.spill(data); + } + Ok(()) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +/// Decimal text of every `u8` (`[digits.., len]`), built at compile time. +const fn decimal_u8_table() -> [[u8; 4]; 256] { + let mut table = [[0u8; 4]; 256]; + let mut i = 0; + while i < 256 { + let v = i as u8; + table[i] = if v >= 100 { + [b'0' + v / 100, b'0' + v / 10 % 10, b'0' + v % 10, 3] + } else if v >= 10 { + [b'0' + v / 10, b'0' + v % 10, 0, 2] + } else { + [b'0' + v, 0, 0, 1] + }; + i += 1; + } + table +} + +static DECIMAL_U8: [[u8; 4]; 256] = decimal_u8_table(); + +/// `CompactFormatter` with a table lookup for `u8` (blob bytes are `Vec<u8>`, one JSON number +/// per byte, so this is the hot path). Every other method is the trait default, exactly as in +/// `CompactFormatter`. +struct DigestFormatter; + +impl Formatter for DigestFormatter { + #[inline] + fn write_u8<W>(&mut self, writer: &mut W, value: u8) -> io::Result<()> + where + W: ?Sized + io::Write, + { + let entry = &DECIMAL_U8[value as usize]; + writer.write_all(&entry[..entry[3] as usize]) + } +} + +/// SHA-256 of `payload`'s compact `serde_json` encoding, and that encoding's length in bytes. +/// +/// Byte-for-byte the same result as hashing `serde_json::to_vec(payload)` and taking its +/// length, without ever holding the encoding in memory. A serialization failure is refused with +/// `IoFailure` and the same message the old code used. +pub fn payload_digest<T: Serialize + ?Sized>(payload: &T) -> SynapseResult<([u8; 32], u64)> { + let mut sink = DigestWriter::new(); + payload + .serialize(&mut serde_json::Serializer::with_formatter( + &mut sink, + DigestFormatter, + )) + .map_err(|e| { + SynapseError::new(RefusalCode::IoFailure, format!("serialize payload: {e}")) + })?; + Ok(sink.finish()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn decimal_table_matches_serde_json_for_every_u8() { + for v in 0..=u8::MAX { + let entry = &DECIMAL_U8[v as usize]; + assert_eq!( + &entry[..entry[3] as usize], + serde_json::to_vec(&v).unwrap().as_slice(), + "{v}" + ); + // Also as a map key, where serde_json quotes the number. + let key = std::collections::BTreeMap::from([(v, ())]); + let mut out = Vec::new(); + key.serialize(&mut serde_json::Serializer::with_formatter( + &mut out, + DigestFormatter, + )) + .unwrap(); + assert_eq!(out, serde_json::to_vec(&key).unwrap(), "key {v}"); + } + } + + #[test] + fn every_write_size_around_the_staging_buffer_hashes_the_same_bytes() { + use std::io::Write; + // Byte strings written in pieces of every size from 1 to past two buffers. + let data: Vec<u8> = (0..3 * DIGEST_STAGING_BYTES) + .map(|i| (i * 31 % 251) as u8) + .collect(); + for piece in [ + 1, + 7, + DIGEST_STAGING_BYTES - 1, + DIGEST_STAGING_BYTES, + DIGEST_STAGING_BYTES + 1, + 2 * DIGEST_STAGING_BYTES + 3, + ] { + let mut w = DigestWriter::new(); + for chunk in data.chunks(piece) { + w.write_all(chunk).unwrap(); + } + assert!(w.staged.capacity() <= DIGEST_STAGING_BYTES, "piece {piece}"); + let want: [u8; 32] = Sha256::digest(&data).into(); + assert_eq!(w.finish(), (want, data.len() as u64), "piece {piece}"); + } + } +} diff --git a/crates/synapse-auth/src/lib.rs b/crates/synapse-auth/src/lib.rs index 8fc4cbc..ccd40cf 100644 --- a/crates/synapse-auth/src/lib.rs +++ b/crates/synapse-auth/src/lib.rs @@ -12,6 +12,8 @@ use synapse_core::{ mod chain; pub use chain::*; +mod digest; +pub use digest::payload_digest; /// Current capability grant schema version. pub const CAPABILITY_GRANT_VERSION: u16 = 1; @@ -205,11 +207,8 @@ impl<T: Serialize> AuthenticatedRequest<T> { declared_payload_bytes_len: u64, payload: T, ) -> SynapseResult<Self> { - let serialized = serde_json::to_vec(&payload).map_err(|e| { - SynapseError::new(RefusalCode::IoFailure, format!("serialize payload: {e}")) - })?; - let payload_sha256: [u8; 32] = Sha256::digest(&serialized).into(); - let effective_len = declared_payload_bytes_len.max(serialized.len() as u64); + let (payload_sha256, serialized_len) = payload_digest(&payload)?; + let effective_len = declared_payload_bytes_len.max(serialized_len); let mut req = Self { grant, @@ -526,10 +525,7 @@ impl PolicyEnforcer { } // 6. Verify payload digest and agent's Ed25519 signature over the request - let serialized_payload = serde_json::to_vec(&req.payload).map_err(|e| { - SynapseError::new(RefusalCode::IoFailure, format!("serialize payload: {e}")) - })?; - let actual_payload_sha256: [u8; 32] = Sha256::digest(&serialized_payload).into(); + let (actual_payload_sha256, serialized_payload_len) = payload_digest(&req.payload)?; if actual_payload_sha256 != req.payload_sha256 { return Err(SynapseError::new( RefusalCode::AuthSignatureInvalid, @@ -558,7 +554,7 @@ impl PolicyEnforcer { })?; // 7. Enforce payload byte quota - let effective_bytes = req.payload_bytes_len.max(serialized_payload.len() as u64); + let effective_bytes = req.payload_bytes_len.max(serialized_payload_len); if effective_bytes > req.grant.max_bytes_per_op { return Err(SynapseError::new( RefusalCode::QuotaPayloadTooLarge, diff --git a/crates/synapse-auth/tests/payload_digest_streaming.rs b/crates/synapse-auth/tests/payload_digest_streaming.rs new file mode 100644 index 0000000..1c944b1 --- /dev/null +++ b/crates/synapse-auth/tests/payload_digest_streaming.rs @@ -0,0 +1,213 @@ +//! Issue #92: the request payload digest is computed by streaming the payload's compact JSON +//! straight into SHA-256, without first materializing the whole JSON text in memory. +//! +//! The digest definition does not change (SHA-256 of the compact `serde_json` encoding, which +//! the agent signs through `payload_sha256`); this file proves the memory shape of the check: +//! the largest single heap allocation made while signing or authorizing a large payload stays a +//! small fixed size, far below the payload's JSON length. Before #92 both paths built the JSON +//! text in one growing `Vec`, so the largest allocation was at least the JSON length. +//! +//! Byte-for-byte parity of the new digest with the old one is proven separately, over the A1 +//! malformed corpus and recorded requests, in `crates/synapse-api/tests/payload_digest_parity.rs`. + +use ed25519_dalek::SigningKey; +use sha2::{Digest, Sha256}; +use std::alloc::{GlobalAlloc, Layout, System}; +use std::cell::Cell; +use synapse_auth::{ + payload_digest, AgentCapabilityGrant, AuthenticatedRequest, BoundaryKind, Capability, + PolicyEnforcer, +}; +use synapse_core::{encode_did_key_ed25519, RepoId}; + +/// Records the largest single allocation made on the measuring thread while a window is open. +struct PeakAlloc; + +thread_local! { + static MEASURING: Cell<bool> = const { Cell::new(false) }; + static PEAK: Cell<usize> = const { Cell::new(0) }; +} + +fn note(size: usize) { + let _ = MEASURING.try_with(|m| { + if m.get() { + let _ = PEAK.try_with(|p| p.set(p.get().max(size))); + } + }); +} + +unsafe impl GlobalAlloc for PeakAlloc { + unsafe fn alloc(&self, layout: Layout) -> *mut u8 { + note(layout.size()); + unsafe { System.alloc(layout) } + } + unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { + unsafe { System.dealloc(ptr, layout) } + } + unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 { + note(layout.size()); + unsafe { System.alloc_zeroed(layout) } + } + unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 { + note(new_size); + unsafe { System.realloc(ptr, layout, new_size) } + } +} + +#[global_allocator] +static GLOBAL: PeakAlloc = PeakAlloc; + +/// Largest single allocation made by `f` on this thread. +fn peak_alloc<R>(f: impl FnOnce() -> R) -> (R, usize) { + PEAK.with(|p| p.set(0)); + MEASURING.with(|m| m.set(true)); + let r = f(); + MEASURING.with(|m| m.set(false)); + (r, PEAK.with(|p| p.get())) +} + +/// Ceiling for any single allocation during digesting: a fixed staging buffer plus slack. +const SMALL_ALLOC_CEILING: usize = 64 * 1024; +/// Blob size: its compact JSON (decimal byte values with commas) is several times larger. +const BLOB_LEN: usize = 256 * 1024; + +fn derived(label: &str, counter: u64) -> [u8; 32] { + let mut h = Sha256::new(); + h.update(b"SYNAPSE_AUTH_PAYLOAD_DIGEST_TEST_V1\0"); + h.update(label.as_bytes()); + h.update(counter.to_le_bytes()); + h.finalize().into() +} + +fn key(label: &str) -> SigningKey { + SigningKey::from_bytes(&derived(label, 0)) +} + +/// A blob whose bytes cover every value, so the JSON mixes one-, two- and three-digit numbers. +fn blob() -> Vec<u8> { + (0..BLOB_LEN) + .map(|i| derived("blob", (i / 32) as u64)[i % 32]) + .collect() +} + +type Payload = (String, Vec<(String, Vec<u8>)>); + +fn payload() -> Payload { + ("submit".to_string(), vec![("blob-0".to_string(), blob())]) +} + +struct Fixture { + repo: RepoId, + authority: SigningKey, + agent: SigningKey, +} + +fn fixture() -> Fixture { + Fixture { + repo: RepoId::new("payload-digest-repo").unwrap(), + authority: key("authority"), + agent: key("agent"), + } +} + +fn grant(f: &Fixture, max_bytes_per_op: u64) -> AgentCapabilityGrant { + AgentCapabilityGrant::issue( + &f.authority, + derived("grant", 0), + f.repo.clone(), + encode_did_key_ed25519(&f.agent.verifying_key().to_bytes()), + vec![Capability::Propose], + max_bytes_per_op, + 100, + 60_000, + 1_000, + 1_000_000, + ) +} + +fn enforcer(f: &Fixture) -> PolicyEnforcer { + let mut e = PolicyEnforcer::new(); + e.register_repo_authority( + f.repo.clone(), + encode_did_key_ed25519(&f.authority.verifying_key().to_bytes()), + ); + e +} + +#[test] +fn signing_a_large_payload_never_materializes_its_json() { + let f = fixture(); + let p = payload(); + let json_len = serde_json::to_vec(&p).unwrap().len(); + assert!( + json_len > 3 * BLOB_LEN, + "JSON must dwarf the blob: {json_len}" + ); + let g = grant(&f, u64::MAX); + let (req, peak) = peak_alloc(|| { + AuthenticatedRequest::sign_new( + &f.agent, + g, + f.repo.clone(), + Capability::Propose, + derived("nonce", 0), + 2_000, + 0, + p, + ) + }); + let req = req.unwrap(); + assert_eq!(req.payload_bytes_len, json_len as u64); + assert!( + peak <= SMALL_ALLOC_CEILING, + "sign_new made a {peak} byte allocation for a {json_len} byte JSON payload" + ); +} + +#[test] +fn authorizing_a_large_payload_never_materializes_its_json() { + let f = fixture(); + let p = payload(); + let json_len = serde_json::to_vec(&p).unwrap().len(); + let req = AuthenticatedRequest::sign_new( + &f.agent, + grant(&f, u64::MAX), + f.repo.clone(), + Capability::Propose, + derived("nonce", 1), + 2_000, + 0, + p, + ) + .unwrap(); + let mut e = enforcer(&f); + let (r, peak) = peak_alloc(|| { + e.authorize( + BoundaryKind::Api, + "submit", + &f.repo, + Capability::Propose, + &req, + 2_000, + ) + }); + r.unwrap(); + assert!( + peak <= SMALL_ALLOC_CEILING, + "authorize made a {peak} byte allocation for a {json_len} byte JSON payload" + ); +} + +#[test] +fn payload_digest_streams_and_matches_the_materialized_json() { + let p = payload(); + let json = serde_json::to_vec(&p).unwrap(); + let want: [u8; 32] = Sha256::digest(&json).into(); + let (got, peak) = peak_alloc(|| payload_digest(&p).unwrap()); + assert_eq!(got, (want, json.len() as u64)); + assert!( + peak <= SMALL_ALLOC_CEILING, + "payload_digest made a {peak} byte allocation for a {} byte JSON payload", + json.len() + ); +} diff --git a/crates/synapse-bench/src/floor.rs b/crates/synapse-bench/src/floor.rs index 778ece5..bbef78c 100644 --- a/crates/synapse-bench/src/floor.rs +++ b/crates/synapse-bench/src/floor.rs @@ -681,11 +681,12 @@ fn cpu_probes(n: usize, idle: &EnergyReading) -> (Vec<Probe>, usize) { ); push( "auth_payload_digest", - "synapse-auth payload digest: serde_json encode of the payload plus SHA-256", + "synapse-auth payload digest as authorize computes it: compact JSON streamed into SHA-256 (synapse_auth::payload_digest)", n, &mut || { - let bytes = serde_json::to_vec(&req.payload).unwrap_or_default(); - std::hint::black_box(Sha256::digest(&bytes)); + std::hint::black_box( + synapse_auth::payload_digest(std::hint::black_box(&req.payload)).ok(), + ); }, ); push(