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 { + 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(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(&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 { + 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>; + +/// 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, 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 { + 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::(); + 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 = (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::)); + p.check("file", &(target, "README.md".to_string(), Some(WalSeq(2)))); + p.check("receipt", &(id, None::)); + 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 = (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::::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 { + 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, + ) -> 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/chain.rs b/crates/synapse-auth/src/chain.rs index 920ed8e..b319c86 100644 --- a/crates/synapse-auth/src/chain.rs +++ b/crates/synapse-auth/src/chain.rs @@ -11,7 +11,7 @@ //! encoding of `docs/F1_CAPABILITY_CHAINS.md` (ADR 0003 principle P5); there is no serde form. use crate::{AuditOutcome, BoundaryKind, Capability, PolicyEnforcer}; -use ed25519_dalek::{Signature, Signer, SigningKey, VerifyingKey}; +use ed25519_dalek::{Signature, Signer, SigningKey}; use sha2::{Digest, Sha256}; use std::collections::BTreeMap; use synapse_core::{ @@ -513,7 +513,7 @@ impl CapabilityLink { /// Verify the issuer's Ed25519 signature over `signable_bytes()`. pub fn verify_signature(&self) -> SynapseResult<()> { let invalid = |msg: &str| SynapseError::new(RefusalCode::AuthGrantSignatureInvalid, msg); - let key = VerifyingKey::from_bytes(&self.issuer_key) + let key = crate::key_cache::verifying_key(&self.issuer_key) .map_err(|_| invalid("link issuer key is not a valid Ed25519 key"))?; key.verify_strict( &self.signable_bytes(), @@ -1010,7 +1010,7 @@ impl PolicyEnforcer { ), )); } - let agent_key = VerifyingKey::from_bytes(&req.agent_key).map_err(|_| { + let agent_key = crate::key_cache::verifying_key(&req.agent_key).map_err(|_| { SynapseError::new(RefusalCode::DidKeyInvalid, "invalid agent Ed25519 key") })?; agent_key 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, + 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 { + 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`, 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(&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(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 = (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/key_cache.rs b/crates/synapse-auth/src/key_cache.rs new file mode 100644 index 0000000..7a0d0f1 --- /dev/null +++ b/crates/synapse-auth/src/key_cache.rs @@ -0,0 +1,16 @@ +//! Decoded-key cache for the grant, request and capability-chain checks (issue #93). +//! +//! The cache itself lives in `synapse_core::key_cache` so the changeset envelope check shares +//! it; see that module for the bounds and refusal rules. + +pub(crate) use synapse_core::cached_verifying_key as verifying_key; +pub use synapse_core::KEY_CACHE_CAPACITY; + +/// `(cached keys, point decodes)` for this thread. +#[cfg(test)] +pub(crate) fn stats() -> (usize, u64) { + synapse_core::key_cache_stats() +} + +#[cfg(test)] +mod tests; diff --git a/crates/synapse-auth/src/key_cache/tests.rs b/crates/synapse-auth/src/key_cache/tests.rs new file mode 100644 index 0000000..f669299 --- /dev/null +++ b/crates/synapse-auth/src/key_cache/tests.rs @@ -0,0 +1,332 @@ +//! Issue #93: the decoded-key cache decodes each key once, stays bounded under hostile key +//! churn, and leaves every refusal code for malformed or invalid keys unchanged. +//! +//! Keys, nonces and grant ids are derived from labels and counters (SHA-256), never written +//! as literals. Each `#[test]` runs on its own thread, so it starts with an empty cache; +//! the assertions still use before/after deltas. + +use super::{stats, verifying_key, KEY_CACHE_CAPACITY}; +use crate::{ + AgentCapabilityGrant, AuthenticatedRequest, BoundaryKind, Capability, CapabilityChain, + CapabilityLink, ChainQuotas, ChainedRequest, ChangeScope, LinkCaveats, OperationSet, PathScope, + PolicyEnforcer, ReferenceKind, ReferenceScope, RequestScope, ROOT_PARENT, +}; +use ed25519_dalek::{Signer, SigningKey, VerifyingKey}; +use sha2::{Digest, Sha256}; +use synapse_core::{encode_did_key_ed25519, RefusalCode, RepoId, WalSeq}; + +const NOW: u64 = 1_000_000; + +fn derived(label: &str, n: u64) -> [u8; 32] { + let mut h = Sha256::new(); + h.update(b"SYNAPSE_AUTH_KEY_CACHE_TEST_V1\0"); + h.update(label.as_bytes()); + h.update(n.to_le_bytes()); + h.finalize().into() +} + +fn key(label: &str, n: u64) -> SigningKey { + SigningKey::from_bytes(&derived(label, n)) +} + +fn did(k: &SigningKey) -> String { + encode_did_key_ed25519(&k.verifying_key().to_bytes()) +} + +/// 32 derived bytes that are not the encoding of a curve point (`from_bytes` refuses them). +fn invalid_point(label: &str) -> [u8; 32] { + (0u64..) + .map(|n| derived(label, n)) + .find(|b| VerifyingKey::from_bytes(b).is_err()) + .expect("about half of all encodings are not points") +} + +/// A small-order point encoding (decodes, but `verify_strict` refuses it as weak): +/// y = n for the first small n whose point is weak. +fn weak_point() -> [u8; 32] { + (0u8..=u8::MAX) + .map(|n| std::array::from_fn(|i| if i == 0 { n } else { 0 })) + .find(|b: &[u8; 32]| VerifyingKey::from_bytes(b).is_ok_and(|k| k.is_weak())) + .expect("y = 0 and y = 1 are small-order points") +} + +fn repo() -> RepoId { + RepoId::new("github.com/aien-dev/synapse-key-cache-test").unwrap() +} + +fn caveats() -> LinkCaveats { + 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: NOW - 1, + expires_at_ms: NOW + 60_000, + } +} + +fn grant(authority: &SigningKey, agent_did: String, n: u64) -> AgentCapabilityGrant { + AgentCapabilityGrant::issue( + authority, + derived("grant", n), + repo(), + agent_did, + vec![Capability::Read, Capability::Propose], + 1 << 20, + 1 << 20, + 60_000, + NOW - 1, + NOW + 60_000, + ) +} + +fn request( + agent: &SigningKey, + grant: AgentCapabilityGrant, + n: u64, +) -> AuthenticatedRequest> { + AuthenticatedRequest::sign_new( + agent, + grant, + repo(), + Capability::Propose, + derived("nonce", n), + NOW, + 0, + derived("payload", n).to_vec(), + ) + .unwrap() +} + +fn authorize( + enf: &mut PolicyEnforcer, + req: &AuthenticatedRequest>, +) -> Result<(), RefusalCode> { + enf.authorize( + BoundaryKind::Api, + "submit", + &repo(), + Capability::Propose, + req, + NOW, + ) + .map_err(|e| e.code) +} + +/// The authority and agent keys are decoded once each, however many requests they sign. +#[test] +fn each_key_decodes_once_across_repeated_authorizations() { + let authority = key("authority", 1); + let agent = key("agent", 1); + let mut enf = PolicyEnforcer::new(); + enf.register_repo_authority(repo(), did(&authority)); + let g = grant(&authority, did(&agent), 1); + let (_, before) = stats(); + for n in 0..32 { + assert_eq!(authorize(&mut enf, &request(&agent, g.clone(), n)), Ok(())); + } + let (len, after) = stats(); + assert_eq!( + after - before, + 2, + "authority and agent key decoded once each" + ); + assert!(len >= 2); +} + +/// Hostile churn of valid keys: every new key costs one decode and the cache never holds +/// more than the cap; the oldest keys are the ones evicted. +#[test] +fn hostile_valid_key_churn_stays_at_the_cap() { + let churn = 10 * KEY_CACHE_CAPACITY as u64; + let (_, before) = stats(); + for n in 0..churn { + let bytes = key("churn", n).verifying_key().to_bytes(); + assert_eq!( + verifying_key(&bytes).unwrap(), + VerifyingKey::from_bytes(&bytes).unwrap() + ); + assert!( + stats().0 <= KEY_CACHE_CAPACITY, + "cache above the cap at key {n}" + ); + } + let (len, after) = stats(); + assert_eq!(len, KEY_CACHE_CAPACITY); + assert_eq!(after - before, churn, "every new key is one decode"); + + // Newest key: a hit. Oldest key: evicted, decoded again. + verifying_key(&key("churn", churn - 1).verifying_key().to_bytes()).unwrap(); + assert_eq!(stats().1, after); + verifying_key(&key("churn", 0).verifying_key().to_bytes()).unwrap(); + assert_eq!(stats().1, after + 1); + assert_eq!(stats().0, KEY_CACHE_CAPACITY); +} + +/// Bytes that are not a point are refused on every call and never enter the cache, so +/// churn of invalid keys cannot grow it either. +#[test] +fn invalid_key_bytes_are_refused_every_time_and_never_cached() { + let (len0, d0) = stats(); + for n in 0..(4 * KEY_CACHE_CAPACITY as u64) { + let bad = invalid_point(&format!("invalid-churn-{n}")); + assert!(verifying_key(&bad).is_err()); + assert!(verifying_key(&bad).is_err(), "second call refused too"); + } + let (len1, d1) = stats(); + assert_eq!(len1, len0, "invalid keys are never cached"); + assert_eq!(d1 - d0, 8 * KEY_CACHE_CAPACITY as u64, "every call decodes"); +} + +/// Refusal codes for invalid authority and agent keys on the grant path, unchanged, both +/// before and after the valid keys are cached. +#[test] +fn grant_path_refusal_codes_for_bad_keys_are_unchanged_cold_and_warm() { + let authority = key("authority", 2); + let agent = key("agent", 2); + let mut enf = PolicyEnforcer::new(); + enf.register_repo_authority(repo(), did(&authority)); + + // Invalid authority key: a trusted issuer DID whose 32 bytes are not a point. + let bad_issuer_did = encode_did_key_ed25519(&invalid_point("issuer")); + enf.register_repo_authority(repo(), bad_issuer_did.clone()); + let mut bad_issuer = grant(&authority, did(&agent), 2); + bad_issuer.issuer_did = bad_issuer_did; + + // Invalid agent key in a validly signed grant. + let bad_agent_did = encode_did_key_ed25519(&invalid_point("agent")); + let bad_agent = grant(&authority, bad_agent_did, 3); + + // Malformed DIDs: not multibase z, and the wrong multicodec prefix. + let no_z = grant( + &authority, + did(&agent).replacen("did:key:z", "did:key:m", 1), + 4, + ); + let wrong_codec = grant( + &authority, + did(&agent).replacen("did:key:z6Mk", "did:key:z6Mj", 1), + 5, + ); + + // Valid keys, wrong signatures. + let mut forged_grant = grant(&authority, did(&agent), 6); + forged_grant.signature = key("forger", 0) + .sign(&forged_grant.canonical_signable_bytes()) + .to_bytes() + .to_vec(); + let good = grant(&authority, did(&agent), 7); + + let cases = |enf: &mut PolicyEnforcer, round: u64| { + let n = 100 * round; + assert_eq!( + authorize(enf, &request(&agent, bad_issuer.clone(), n)), + Err(RefusalCode::DidKeyInvalid) + ); + assert_eq!( + authorize(enf, &request(&agent, bad_agent.clone(), n + 1)), + Err(RefusalCode::DidKeyInvalid) + ); + assert_eq!( + authorize(enf, &request(&agent, no_z.clone(), n + 2)), + Err(RefusalCode::DidKeyInvalid) + ); + assert_eq!( + authorize(enf, &request(&agent, wrong_codec.clone(), n + 3)), + Err(RefusalCode::DidKeyInvalid) + ); + assert_eq!( + authorize(enf, &request(&agent, forged_grant.clone(), n + 4)), + Err(RefusalCode::AuthGrantSignatureInvalid) + ); + assert_eq!( + authorize(enf, &request(&key("impostor", round), good.clone(), n + 5)), + Err(RefusalCode::AuthSignatureInvalid) + ); + assert_eq!( + authorize(enf, &request(&agent, good.clone(), n + 6)), + Ok(()) + ); + }; + cases(&mut enf, 1); // cold: nothing cached yet + cases(&mut enf, 2); // warm: authority and agent keys cached +} + +/// Refusal codes on the capability-chain path (`verify_strict`), unchanged cold and warm: +/// a link issuer key that is not a point and a small-order issuer key are both +/// `AuthGrantSignatureInvalid`; an agent key that is not a point is `DidKeyInvalid`. +#[test] +fn chain_path_refusal_codes_for_bad_keys_are_unchanged_cold_and_warm() { + let authority = key("chain-authority", 1); + let link = CapabilityLink::issue( + &authority, + ROOT_PARENT, + derived("link-nonce", 1), + repo(), + key("chain-agent", 1).verifying_key().to_bytes(), + caveats(), + ); + let mut not_a_point = link.clone(); + not_a_point.issuer_key = invalid_point("link-issuer"); + let mut weak = link.clone(); + weak.issuer_key = weak_point(); + for _round in 0..2 { + assert_eq!(link.verify_signature(), Ok(())); + assert_eq!( + not_a_point.verify_signature().map_err(|e| e.code), + Err(RefusalCode::AuthGrantSignatureInvalid) + ); + assert_eq!( + weak.verify_signature().map_err(|e| e.code), + Err(RefusalCode::AuthGrantSignatureInvalid) + ); + } + + // Agent key that is not a point: a granted root link whose audience is those bytes. + let bad_agent = invalid_point("chain-agent-bad"); + let mut enf = PolicyEnforcer::new(); + enf.register_repo_authority(repo(), did(&authority)); + let root = CapabilityLink::issue( + &authority, + ROOT_PARENT, + derived("link-nonce", 2), + repo(), + bad_agent, + caveats(), + ); + let chain = CapabilityChain::new(vec![root]); + enf.grant_link(&chain, WalSeq(1), NOW).unwrap(); + for round in 0..2u64 { + let mut req = ChainedRequest::sign_new( + &key("chain-signer", round), + chain.clone(), + repo(), + Capability::Propose, + RequestScope::default(), + derived("chain-nonce", round), + NOW, + derived("chain-payload", round).to_vec(), + ); + req.agent_key = bad_agent; + assert_eq!( + enf.authorize_chain( + BoundaryKind::Api, + "submit", + &repo(), + Capability::Propose, + &req, + WalSeq(2 + round), + NOW, + ) + .map_err(|e| e.code), + Err(RefusalCode::DidKeyInvalid) + ); + } +} diff --git a/crates/synapse-auth/src/lib.rs b/crates/synapse-auth/src/lib.rs index aefaa47..b717a46 100644 --- a/crates/synapse-auth/src/lib.rs +++ b/crates/synapse-auth/src/lib.rs @@ -1,7 +1,7 @@ //! Capability-scoped Ed25519 authentication, replay protection, quota enforcement, //! and tamper-evident hash-chained security audit logging (`synapse-auth`, Gate 2a). -use ed25519_dalek::{Signature, Signer, SigningKey, VerifyingKey}; +use ed25519_dalek::{Signature, Signer, SigningKey}; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; use std::collections::{BTreeMap, BTreeSet}; @@ -11,8 +11,12 @@ use synapse_core::{ }; mod chain; +mod digest; +mod key_cache; mod state_move; pub use chain::*; +pub use digest::payload_digest; +pub use key_cache::KEY_CACHE_CAPACITY; pub use state_move::*; /// Current capability grant schema version. @@ -155,7 +159,7 @@ impl AgentCapabilityGrant { )); } let pubkey_bytes = decode_did_key_ed25519(&self.issuer_did)?; - let verifying_key = VerifyingKey::from_bytes(&pubkey_bytes).map_err(|_| { + let verifying_key = key_cache::verifying_key(&pubkey_bytes).map_err(|_| { SynapseError::new( RefusalCode::DidKeyInvalid, "invalid authority Ed25519 public key", @@ -207,11 +211,8 @@ impl AuthenticatedRequest { declared_payload_bytes_len: u64, payload: T, ) -> SynapseResult { - 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, @@ -528,10 +529,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, @@ -540,7 +538,7 @@ impl PolicyEnforcer { } let agent_pubkey_bytes = decode_did_key_ed25519(&req.grant.agent_did)?; - let agent_verifying_key = VerifyingKey::from_bytes(&agent_pubkey_bytes).map_err(|_| { + let agent_verifying_key = key_cache::verifying_key(&agent_pubkey_bytes).map_err(|_| { SynapseError::new(RefusalCode::DidKeyInvalid, "invalid agent Ed25519 key") })?; let sig_arr: [u8; 64] = req.agent_signature.as_slice().try_into().map_err(|_| { @@ -560,7 +558,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 = const { Cell::new(false) }; + static PEAK: Cell = 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(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 { + (0..BLOB_LEN) + .map(|i| derived("blob", (i / 32) as u64)[i % 32]) + .collect() +} + +type Payload = (String, Vec<(String, Vec)>); + +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, 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( diff --git a/crates/synapse-core/src/key_cache.rs b/crates/synapse-core/src/key_cache.rs new file mode 100644 index 0000000..5a772be --- /dev/null +++ b/crates/synapse-core/src/key_cache.rs @@ -0,0 +1,76 @@ +//! Bounded per-thread cache of decoded Ed25519 verifying keys (issue #93). +//! +//! `VerifyingKey::from_bytes` decompresses the curve point on every call. One accepted +//! submit verifies the changeset envelope (author key, [`crate::ChangesetEnvelope::validate`]), +//! the grant (authority key) and the request (agent key, both in `synapse-auth`), and these +//! keys repeat across requests, so the decoded key is cached here, keyed by the exact 32 key +//! bytes. The cache lives in this crate so the envelope check and `synapse-auth` share it. +//! Only the decode is cached: every signature is still verified in full, with the same +//! `verify` or `verify_strict` call as before, by the existing `ed25519-dalek` crate. +//! +//! Bounds and refusals: +//! - Only keys that decode are cached. Bytes that do not decode are refused on every call, +//! exactly as before (the caller maps the error to its refusal code), and never enter +//! the cache, so churn of invalid keys cannot grow it. +//! - At most [`KEY_CACHE_CAPACITY`] keys per thread; the oldest insertion is evicted first. +//! Churn of valid keys (each new key one decode) therefore keeps the cache at the cap. +//! - Per thread: no lock on the verify path and nothing shared between threads. + +use ed25519_dalek::{SignatureError, VerifyingKey}; +use std::cell::RefCell; +use std::collections::{HashMap, VecDeque}; + +/// Most decoded keys one thread keeps. +pub const KEY_CACHE_CAPACITY: usize = 64; + +#[derive(Default)] +struct KeyCache { + keys: HashMap<[u8; 32], VerifyingKey>, + /// Insertion order, oldest first; always the same key set as `keys`. + order: VecDeque<[u8; 32]>, + /// Point decodes performed (cache misses that reached `VerifyingKey::from_bytes`). + decodes: u64, +} + +thread_local! { + static CACHE: RefCell = RefCell::new(KeyCache::default()); +} + +/// The decoded verifying key for `bytes`: from this thread's cache, or decoded with +/// `VerifyingKey::from_bytes` (and cached when it decodes). Same result and same error as +/// calling `VerifyingKey::from_bytes(bytes)` directly. +pub fn cached_verifying_key(bytes: &[u8; 32]) -> Result { + CACHE + .try_with(|cell| { + let mut cache = cell.borrow_mut(); + if let Some(key) = cache.keys.get(bytes) { + return Ok(*key); + } + cache.decodes += 1; + let key = VerifyingKey::from_bytes(bytes)?; + if cache.keys.len() >= KEY_CACHE_CAPACITY { + if let Some(oldest) = cache.order.pop_front() { + cache.keys.remove(&oldest); + } + } + cache.keys.insert(*bytes, key); + cache.order.push_back(*bytes); + Ok(key) + }) + // Thread-local storage already torn down (thread exit): decode without caching. + .unwrap_or_else(|_| VerifyingKey::from_bytes(bytes)) +} + +/// `(cached keys, point decodes)` for the calling thread. Diagnostic only: tests use it to +/// count decodes; it changes nothing. +#[doc(hidden)] +pub fn key_cache_stats() -> (usize, u64) { + CACHE.with(|cell| { + let cache = cell.borrow(); + debug_assert_eq!(cache.keys.len(), cache.order.len()); + (cache.keys.len(), cache.decodes) + }) +} + +#[cfg(test)] +mod tests; diff --git a/crates/synapse-core/src/key_cache/tests.rs b/crates/synapse-core/src/key_cache/tests.rs new file mode 100644 index 0000000..fd9e44c --- /dev/null +++ b/crates/synapse-core/src/key_cache/tests.rs @@ -0,0 +1,237 @@ +//! Issue #93, envelope path: `ChangesetEnvelope::validate` decodes each author key once per +//! thread, stays bounded, and gives the same verdict and refusal code as the uncached check +//! (`VerifyingKey::from_bytes` then `verify`) for every bad key, cold and warm. +//! +//! Keys and idempotency keys are derived from labels and counters (SHA-256), never written as +//! literals. Each `#[test]` runs on its own thread, so it starts with an empty cache; the +//! assertions still use before/after deltas. + +use super::{cached_verifying_key, key_cache_stats, KEY_CACHE_CAPACITY}; +use crate::{ + encode_did_key_ed25519, BlobDigest, ChangesetEnvelope, EvidenceAttachment, FileMode, GitOid, + IdempotencyKey, MutationOp, PathMutation, RefusalCode, RepoId, SynapseResult, + SYNAPSE_ENVELOPE_VERSION, +}; +use ed25519_dalek::{Signature, SigningKey, Verifier, VerifyingKey}; +use sha2::{Digest, Sha256}; + +fn derived(label: &str, n: u64) -> [u8; 32] { + let mut h = Sha256::new(); + h.update(b"SYNAPSE_CORE_KEY_CACHE_TEST_V1\0"); + h.update(label.as_bytes()); + h.update(n.to_le_bytes()); + h.finalize().into() +} + +fn key(label: &str, n: u64) -> SigningKey { + SigningKey::from_bytes(&derived(label, n)) +} + +/// 32 derived bytes that are not the encoding of a curve point (`from_bytes` refuses them). +fn invalid_point(label: &str) -> [u8; 32] { + (0u64..) + .map(|n| derived(label, n)) + .find(|b| VerifyingKey::from_bytes(b).is_err()) + .expect("an undecodable encoding exists") +} + +/// The identity point: decodes, but has small order. +fn small_order_point() -> [u8; 32] { + let mut b = [0u8; 32]; + b[0] = 1; + b +} + +fn envelope(n: u64) -> ChangesetEnvelope { + let payload = derived("payload", n); + ChangesetEnvelope { + version: SYNAPSE_ENVELOPE_VERSION, + repo_id: RepoId::new("aien-spark/synapse").unwrap(), + base_git_oid: GitOid::compute_blob(&payload), + parent_changesets: vec![], + author_did: String::new(), + idempotency_key: IdempotencyKey(derived("idem", n)), + created_at_ms: 1_789_800_000_000 + n, + intent_summary: "key cache test".to_string(), + mutations: vec![PathMutation { + path: "src/lib.rs".to_string(), + op: MutationOp::Upsert { + mode: FileMode::Regular644, + blob_digest: BlobDigest::compute(&payload), + size_bytes: payload.len() as u64, + }, + }], + evidence_receipts: vec![EvidenceAttachment { + gate_name: "cargo-test".to_string(), + passed: true, + artifact_digest: derived("artifact", n), + summary: "ok".to_string(), + }], + signature: vec![], + } +} + +fn signed(k: &SigningKey, n: u64) -> ChangesetEnvelope { + let mut env = envelope(n); + env.sign(k); + env +} + +/// The pre-cache check, written out: decode with `from_bytes` on every call, then `verify`. +/// Used as the reference the cached path must agree with. +fn uncached_signature_verdict(env: &ChangesetEnvelope) -> SynapseResult<()> { + let bytes = crate::decode_did_key_ed25519(&env.author_did)?; + let vk = VerifyingKey::from_bytes(&bytes).map_err(|_| { + crate::SynapseError::new(RefusalCode::DidKeyInvalid, "invalid Ed25519 public key") + })?; + let sig: [u8; 64] = env.signature.as_slice().try_into().map_err(|_| { + crate::SynapseError::new( + RefusalCode::AuthSignatureInvalid, + "signature must be 64 bytes", + ) + })?; + vk.verify( + &env.canonical_signable_bytes(), + &Signature::from_bytes(&sig), + ) + .map_err(|_| crate::SynapseError::new(RefusalCode::AuthSignatureInvalid, "verify failed")) +} + +fn code(r: SynapseResult) -> Option { + r.err().map(|e| e.code) +} + +#[test] +fn envelope_author_key_decodes_once_across_repeated_validates() { + let author = key("author", 0); + let (_, before) = key_cache_stats(); + for n in 0..32 { + signed(&author, n).validate().expect("valid envelope"); + } + let (len, after) = key_cache_stats(); + assert_eq!( + after - before, + 1, + "one decode for 32 validates by one author" + ); + assert_eq!(len, 1); +} + +#[test] +fn envelope_refusal_codes_for_bad_keys_are_unchanged_cold_and_warm() { + let author = key("author", 1); + let good = signed(&author, 0); + + let mut undecodable = good.clone(); + undecodable.author_did = encode_did_key_ed25519(&invalid_point("undecodable")); + + let mut no_z = good.clone(); + no_z.author_did = good.author_did.replacen("z", "y", 1); + + let mut wrong_codec = good.clone(); + wrong_codec.author_did = format!("did:key:z{}", "1".repeat(46)); + + let mut forged = good.clone(); + forged.signature = signed(&key("impostor", 0), 0).signature; + + let mut tampered = good.clone(); + tampered.intent_summary = "tampered".to_string(); + + let mut short_sig = good.clone(); + short_sig.signature.truncate(63); + + // Small-order author key with the (R = identity, S = 0) signature. The envelope check uses + // non-strict `verify` (unchanged by this issue); the cached path must give the same verdict. + let mut small_order = good.clone(); + small_order.author_did = encode_did_key_ed25519(&small_order_point()); + small_order.signature = { + let mut s = vec![0u8; 64]; + s[0] = 1; + s + }; + + let cases = [ + ("undecodable", undecodable, Some(RefusalCode::DidKeyInvalid)), + ("no z", no_z, Some(RefusalCode::DidKeyInvalid)), + ( + "wrong multicodec", + wrong_codec, + Some(RefusalCode::DidKeyInvalid), + ), + ("forged", forged, Some(RefusalCode::AuthSignatureInvalid)), + ( + "tampered", + tampered, + Some(RefusalCode::AuthSignatureInvalid), + ), + ( + "short signature", + short_sig, + Some(RefusalCode::AuthSignatureInvalid), + ), + ]; + for round in ["cold", "warm"] { + good.validate().expect("genuine envelope admitted"); + for (name, env, want) in &cases { + assert_eq!(code(env.validate()), *want, "{name} ({round})"); + assert_eq!( + code(uncached_signature_verdict(env)), + *want, + "{name} reference" + ); + } + assert_eq!( + code(small_order.validate().map(|_| ())), + code(uncached_signature_verdict(&small_order)), + "small-order key ({round}) agrees with the uncached check" + ); + } +} + +#[test] +fn invalid_author_keys_are_refused_every_time_and_never_cached() { + let (len0, d0) = key_cache_stats(); + let calls = 4 * KEY_CACHE_CAPACITY as u64; + for n in 0..calls { + let mut env = signed(&key("author", 2), n); + env.author_did = encode_did_key_ed25519(&invalid_point(&format!("bad-{}", n % 8))); + assert_eq!(code(env.validate()), Some(RefusalCode::DidKeyInvalid)); + } + let (len1, d1) = key_cache_stats(); + assert_eq!(len1, len0, "invalid keys never enter the cache"); + assert_eq!(d1 - d0, calls, "every call with an invalid key decodes"); +} + +#[test] +fn hostile_author_churn_stays_at_the_cap() { + let churn = 10 * KEY_CACHE_CAPACITY as u64; + for n in 0..churn { + signed(&key("churn", n), n) + .validate() + .expect("valid envelope"); + assert!(key_cache_stats().0 <= KEY_CACHE_CAPACITY); + } + assert_eq!(key_cache_stats().0, KEY_CACHE_CAPACITY); +} + +/// Negative control: a warm cache holds the genuine author key, and still no envelope the +/// author did not sign is admitted; the cache returns the same key `from_bytes` does. +#[test] +fn warm_cache_admits_nothing_the_author_did_not_sign() { + let author = key("author", 3); + let good = signed(&author, 0); + good.validate().expect("warm the cache"); + for n in 1..16 { + let mut env = signed(&author, n); + env.signature = good.signature.clone(); + assert_eq!( + code(env.validate()), + Some(RefusalCode::AuthSignatureInvalid) + ); + } + let bytes = author.verifying_key().to_bytes(); + assert_eq!( + cached_verifying_key(&bytes).unwrap(), + VerifyingKey::from_bytes(&bytes).unwrap() + ); +} diff --git a/crates/synapse-core/src/lib.rs b/crates/synapse-core/src/lib.rs index 02e4c15..4bceed1 100644 --- a/crates/synapse-core/src/lib.rs +++ b/crates/synapse-core/src/lib.rs @@ -2,13 +2,14 @@ //! [`ChangesetEnvelopeV2`]), `did:key` Ed25519 codec, and deterministic refusal taxonomy for //! Synapse (ADR 0001). -use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey}; +use ed25519_dalek::{Signature, Signer, SigningKey, Verifier}; use serde::{Deserialize, Serialize}; use sha1::Sha1; use sha2::{Digest, Sha256}; use std::fmt; mod derivation; +mod key_cache; mod revision; mod revision_state; mod tree; @@ -18,6 +19,7 @@ pub use derivation::{ DOMAIN_DERIVATION_ATTESTATION_V1, DOMAIN_DERIVATION_SIGN_V1, DOMAIN_DERIVED_MERGE_CHANGE_V1, MAX_DERIVATION_INPUTS, }; +pub use key_cache::{cached_verifying_key, key_cache_stats, KEY_CACHE_CAPACITY}; pub use revision::{ AdmissionWitness, AuthorshipAttestation, ChainPath, ChangesetEnvelopeV2, ObsolescenceKind, ObsolescenceMarker, RevisionContent, WitnessSigner, DOMAIN_ADMISSION_WITNESS_V1, @@ -597,7 +599,7 @@ impl ChangesetEnvelope { // Verify author_did and Ed25519 signature let pubkey_bytes = decode_did_key_ed25519(&self.author_did)?; - let verifying_key = VerifyingKey::from_bytes(&pubkey_bytes).map_err(|_| { + let verifying_key = cached_verifying_key(&pubkey_bytes).map_err(|_| { SynapseError::new(RefusalCode::DidKeyInvalid, "invalid Ed25519 public key") })?; let sig_arr: [u8; 64] = self.signature.as_slice().try_into().map_err(|_| {