From 53069a06482791940a834028b1b1ea0120fd0655 Mon Sep 17 00:00:00 2001 From: Drake Stapleton Date: Fri, 16 Oct 2026 21:18:12 -0500 Subject: [PATCH 1/5] feat(b5): DerivationAttestation for server-derived revisions (#29) Server-derived revisions (path-level rebase, merge tier T0) carry a DerivationAttestation signed by the identity document's server_key. Admission and replica replay recompute the rule over the tree store and refuse wrong keys, unregistered keys, mismatched inputs or rule, disagreeing recomputation, replayed attestations, and borrowed agent signatures with stable refusal codes. New WAL record kind 11 (DerivedRevisionAdmitted). Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 1 + crates/synapse-api/Cargo.toml | 3 + crates/synapse-api/src/derivation.rs | 191 +++++ crates/synapse-api/src/lib.rs | 2 + .../tests/b5_derivation_attestation.rs | 681 ++++++++++++++++ crates/synapse-core/src/derivation.rs | 755 ++++++++++++++++++ crates/synapse-core/src/lib.rs | 24 + crates/synapse-core/src/revision.rs | 74 +- crates/synapse-radicle/src/identity.rs | 9 + crates/synapse-store/src/codec.rs | 16 +- crates/synapse-store/src/lib.rs | 28 +- crates/synapse-store/src/revision.rs | 314 +++++++- .../tests/a1_malformed_corpus.rs | 6 +- .../synapse-store/tests/b5_derived_record.rs | 102 +++ 14 files changed, 2149 insertions(+), 57 deletions(-) create mode 100644 crates/synapse-api/src/derivation.rs create mode 100644 crates/synapse-api/tests/b5_derivation_attestation.rs create mode 100644 crates/synapse-core/src/derivation.rs create mode 100644 crates/synapse-store/tests/b5_derived_record.rs diff --git a/Cargo.lock b/Cargo.lock index 8bbeb95..10ac157 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -380,6 +380,7 @@ dependencies = [ "synapse-core", "synapse-crumb", "synapse-evidence", + "synapse-radicle", "synapse-store", ] diff --git a/crates/synapse-api/Cargo.toml b/crates/synapse-api/Cargo.toml index 7ec9498..96467de 100644 --- a/crates/synapse-api/Cargo.toml +++ b/crates/synapse-api/Cargo.toml @@ -19,3 +19,6 @@ synapse-coord.workspace = true synapse-crumb.workspace = true synapse-evidence.workspace = true synapse-store.workspace = true + +[dev-dependencies] +synapse-radicle.workspace = true diff --git a/crates/synapse-api/src/derivation.rs b/crates/synapse-api/src/derivation.rs new file mode 100644 index 0000000..f75a93e --- /dev/null +++ b/crates/synapse-api/src/derivation.rs @@ -0,0 +1,191 @@ +//! Server-derived revisions through the service (ADR 0003 step B5): the C1 tree store as the +//! [`DerivationTrees`] every rule is recomputed on, derivation by the server, admission, and +//! replica verification of the revision log. See `docs/B5_DERIVATION_ATTESTATION.md`. + +use crate::tree::{TreeEdit, TreeFile, TreeStore}; +use crate::SynapseService; +use ed25519_dalek::SigningKey; +use std::collections::BTreeMap; +use synapse_core::{ + BlobDigest, ChangesetId, DerivationInput, DerivationRule, DerivationTrees, DerivedRevision, + GitOid, MutationOp, PathMutation, RefusalCode, RevisionContent, ServerKeyRegistry, + SynapseError, SynapseResult, TreeDigest, +}; +use synapse_store::{AdmissionAuthority, RevisionOutcome, WalRecord}; + +/// The tree store seen as [`DerivationTrees`]. `git_oids` carries the Git blob OID of every +/// blob a rule may upsert: a bridge attribute of tree files that never affects a `TreeDigest`. +pub struct ServiceDerivationTrees<'a> { + trees: &'a mut TreeStore, + git_oids: BTreeMap, +} + +impl DerivationTrees for ServiceDerivationTrees<'_> { + fn holds_tree(&mut self, tree: TreeDigest) -> bool { + self.trees.contains(tree) + } + + fn apply_mutations( + &mut self, + base: TreeDigest, + mutations: &[PathMutation], + ) -> SynapseResult { + let mut edit = TreeEdit::new(self.trees, base)?; + for m in mutations { + match &m.op { + MutationOp::Upsert { + mode, + blob_digest, + size_bytes, + } => { + let git_blob_oid = *self.git_oids.get(blob_digest).ok_or_else(|| { + SynapseError::new( + RefusalCode::BlobNotFound, + format!("blob {blob_digest} of path {} is not readable", m.path), + ) + })?; + let file = TreeFile { + mode: *mode, + blob_digest: *blob_digest, + size_bytes: *size_bytes, + git_blob_oid, + }; + edit.upsert(self.trees, &m.path, file)?; + } + MutationOp::Delete => edit.delete(self.trees, &m.path)?, + } + } + edit.finish(self.trees) + } + + fn changed_paths(&mut self, from: TreeDigest, to: TreeDigest) -> SynapseResult> { + Ok(self + .trees + .diff(from, to)? + .into_iter() + .map(|e| e.path) + .collect()) + } +} + +impl SynapseService { + /// Git blob OIDs of every readable upserted blob of `contents` (unreadable blobs are left + /// out; a rule that needs one then fails with `BlobNotFound`). + fn git_oids_of<'c>( + &self, + contents: impl IntoIterator, + ) -> BTreeMap { + let mut out = BTreeMap::new(); + for c in contents { + for m in &c.mutations { + if let MutationOp::Upsert { blob_digest, .. } = &m.op { + if out.contains_key(blob_digest) { + continue; + } + if let Ok(raw) = self.read_blob_bytes(*blob_digest, None) { + out.insert(*blob_digest, GitOid::compute_blob(&raw)); + } + } + } + } + out + } + + /// Contents of the input revisions `inputs` names that this repository has admitted. + fn input_contents(&self, inputs: &[DerivationInput]) -> Vec { + inputs + .iter() + .filter_map(|i| match i { + DerivationInput::Revision(id) => self + .store + .get_revision(&self.repo_id, *id) + .ok() + .map(|r| r.content), + DerivationInput::Tree(_) => None, + }) + .collect() + } + + /// Derive a revision as the server: recompute `rule` on `inputs` over the tree store and + /// sign the attestation with the server's machine key `server`. Nothing is admitted. + pub fn derive_revision( + &mut self, + server: &SigningKey, + rule: DerivationRule, + inputs: Vec, + ) -> SynapseResult { + let sources = self.input_contents(&inputs); + let git_oids = self.git_oids_of(&sources); + let store = &self.store; + let repo = self.repo_id.clone(); + let lookup = |id: ChangesetId| store.get_revision(&repo, id).ok().map(|r| r.content); + let mut trees = ServiceDerivationTrees { + trees: &mut self.trees, + git_oids, + }; + DerivedRevision::derive( + server, + self.repo_id.clone(), + rule, + inputs, + &lookup, + &mut trees, + ) + } + + /// Admit a server-derived revision (ADR 0003 B5) under `authority` (the chain that asked + /// for it or proposed it, already authorized by the caller). `keys` is the repository + /// identity log (`synapse_radicle::IdentityLog`). The attestation must name this service's + /// repository (`AuthCrossRepoDenied`); the store then checks the derivation and recomputes + /// it over the tree store. + pub fn admit_derived_revision( + &mut self, + derived: DerivedRevision, + authority: AdmissionAuthority, + keys: &dyn ServerKeyRegistry, + now_ms: u64, + ) -> SynapseResult { + if derived.attestation.repo_id != self.repo_id { + return Err(SynapseError::new( + RefusalCode::AuthCrossRepoDenied, + "derivation attestation repo_id does not match service repo_id", + )); + } + let mut sources = self.input_contents(&derived.attestation.inputs); + sources.push(derived.content.clone()); + let git_oids = self.git_oids_of(&sources); + let mut trees = ServiceDerivationTrees { + trees: &mut self.trees, + git_oids, + }; + self.store + .admit_derived_revision(derived, authority, keys, &mut trees, now_ms) + } + + /// Verify `records` as a replica (see `synapse_store::verify_revision_log`), recomputing + /// every derived revision over this service's tree store. Returns the number of records + /// verified. + pub fn verify_revision_records( + &mut self, + records: &[(synapse_core::WalSeq, WalRecord)], + keys: &dyn ServerKeyRegistry, + ) -> SynapseResult { + let contents = records.iter().filter_map(|(_, r)| match r { + WalRecord::RevisionAdmitted { envelope, .. } => Some(&envelope.content), + WalRecord::DerivedRevisionAdmitted { derived, .. } => Some(&derived.content), + _ => None, + }); + let git_oids = self.git_oids_of(contents); + let mut trees = ServiceDerivationTrees { + trees: &mut self.trees, + git_oids, + }; + synapse_store::verify_revision_log(records, keys, &mut trees) + } + + /// Verify this service's own revision log as a replica would after replay. + pub fn verify_revision_log(&mut self, keys: &dyn ServerKeyRegistry) -> SynapseResult { + let records = self.store.revision_records().to_vec(); + self.verify_revision_records(&records, keys) + } +} diff --git a/crates/synapse-api/src/lib.rs b/crates/synapse-api/src/lib.rs index c30f69b..f41f7de 100644 --- a/crates/synapse-api/src/lib.rs +++ b/crates/synapse-api/src/lib.rs @@ -26,6 +26,8 @@ use synapse_store::{ mod advisory; mod crumb; +mod derivation; +pub use derivation::ServiceDerivationTrees; mod evidence; pub mod tree; pub use advisory::{ diff --git a/crates/synapse-api/tests/b5_derivation_attestation.rs b/crates/synapse-api/tests/b5_derivation_attestation.rs new file mode 100644 index 0000000..83a06d2 --- /dev/null +++ b/crates/synapse-api/tests/b5_derivation_attestation.rs @@ -0,0 +1,681 @@ +//! ADR 0003 step B5: `DerivationAttestation` for server-derived revisions, through the service +//! with the C1 tree store and the E0 identity log. +//! +//! Acceptance (ADR 0003 section 9, row 9): +//! * a replica recomputes every derived revision from the inputs and rule its attestation names +//! and gets the same digests +//! (`b5_replica_recomputes_every_derived_revision_and_gets_the_same_digests`); +//! * an attestation naming different inputs, a different rule, or an unregistered server key is +//! refused at admission and at replay +//! (`b5_attestation_naming_different_inputs_is_refused_at_admission_and_replay`, +//! `b5_attestation_naming_a_different_rule_is_refused_at_admission_and_replay`, +//! `b5_unregistered_server_key_is_refused_at_admission_and_replay`); +//! * a derived revision presented with an agent signature it does not have is refused +//! (`b5_derived_revision_presented_with_an_agent_signature_it_does_not_have_is_refused`). +//! +//! Also: a signature by another key, a replayed attestation, and a recomputation that disagrees. +//! +//! Keys, idempotency keys, change ids and chain digests are derived from labels (`label`), so +//! no literal value is used as key material. + +use ed25519_dalek::SigningKey; +use sha2::{Digest, Sha256}; +use std::path::{Path, PathBuf}; +use synapse_api::{SynapseService, TreeTarget}; +use synapse_core::{ + BlobDigest, ChainPath, ChangeId, ChangesetEnvelopeV2, ChangesetId, DerivationAttestation, + DerivationInput, DerivationRule, DerivedRevision, FileMode, GitOid, IdempotencyKey, MergeTier, + MutationOp, PathMutation, RefusalCode, RepoId, RevisionContent, TreeDigest, WalSeq, + WitnessSigner, +}; +use synapse_radicle::{ + IdentityDocumentDigest, IdentityEdit, IdentityLog, RepositoryIdentityDocument, +}; +use synapse_store::{ + AdmissionAuthority, FsyncPolicy, RecoveryPolicy, RevisionOutcome, StoreLimits, WalRecord, +}; + +const NOW: u64 = 5_000; +const T0: DerivationRule = DerivationRule::Merge { + tier: MergeTier::T0Path, +}; + +/// Base `B0`: README.md, docs/x.md, src/a.rs. `B1`: `B0` with docs/x.md changed. +const B0: GitOid = GitOid([0xB0; 20]); +const B1: GitOid = GitOid([0xB1; 20]); +/// Independent expectations: `B1` with src/a.rs = "a1" (the rebase of `ra` onto `B1`) and `B0` +/// with src/a.rs = "a1" and src/b.rs = "b1" (the T0 merge of `ra` and `rb`). +const B1_REBASED_A: GitOid = GitOid([0xE1; 20]); +const B0_MERGED_AB: GitOid = GitOid([0xE2; 20]); + +fn repo() -> RepoId { + RepoId::new("aien-spark/synapse").unwrap() +} + +/// 32 bytes derived from a label. +fn label(s: &str) -> [u8; 32] { + Sha256::digest(format!("synapse b5 test: {s}").as_bytes()).into() +} + +fn key(s: &str) -> SigningKey { + SigningKey::from_bytes(&label(&format!("key {s}"))) +} + +fn change(s: &str) -> ChangeId { + let mut id = [0u8; 16]; + id.copy_from_slice(&label(&format!("change {s}"))[..16]); + ChangeId(id) +} + +fn authority(s: &str) -> AdmissionAuthority { + AdmissionAuthority { + chain: ChainPath::new(vec![label(&format!("chain {s}"))]).unwrap(), + change_scope: vec![], + } +} + +fn pk(k: &SigningKey) -> [u8; 32] { + k.verifying_key().to_bytes() +} + +fn files(x: &[u8], a: &[u8], b: Option<&[u8]>) -> Vec<(String, FileMode, Vec)> { + let mut f = vec![ + ( + "README.md".to_string(), + FileMode::Regular644, + b"base".to_vec(), + ), + ("docs/x.md".to_string(), FileMode::Regular644, x.to_vec()), + ("src/a.rs".to_string(), FileMode::Regular644, a.to_vec()), + ]; + if let Some(b) = b { + f.push(("src/b.rs".to_string(), FileMode::Regular644, b.to_vec())); + } + f +} + +fn open(dir: &Path) -> SynapseService { + let mut svc = SynapseService::open( + dir, + repo(), + FsyncPolicy::EveryCommit, + RecoveryPolicy::StrictFailClosed, + StoreLimits { + wal_prealloc_bytes: 64 * 1024, + ..Default::default() + }, + ) + .unwrap(); + svc.register_base_tree(B0, files(b"x0", b"a0", None)) + .unwrap(); + svc.register_base_tree(B1, files(b"x1", b"a0", None)) + .unwrap(); + svc.register_base_tree(B1_REBASED_A, files(b"x1", b"a1", None)) + .unwrap(); + svc.register_base_tree(B0_MERGED_AB, files(b"x0", b"a1", Some(b"b1"))) + .unwrap(); + svc +} + +fn upsert(path: &str, body: &[u8]) -> PathMutation { + PathMutation { + path: path.into(), + op: MutationOp::Upsert { + mode: FileMode::Regular644, + blob_digest: BlobDigest::compute(body), + size_bytes: body.len() as u64, + }, + } +} + +fn agent_revision(s: &str, base: TreeDigest, path: &str, body: &[u8]) -> ChangesetEnvelopeV2 { + let content = RevisionContent { + change_id: change(s), + base_tree: base, + parents: vec![], + mutations: vec![upsert(path, body)], + intent_summary: format!("agent revision {s}"), + }; + ChangesetEnvelopeV2::sign_new( + &key(&format!("agent {s}")), + repo(), + content, + IdempotencyKey(label(&format!("idempotency {s}"))), + NOW, + ) +} + +/// Re-sign `content` as `signer`, naming `rule`, `inputs` and `tree`. +fn forge( + signer: &SigningKey, + content: RevisionContent, + rule: DerivationRule, + inputs: Vec, + tree: TreeDigest, +) -> DerivedRevision { + let attestation = + DerivationAttestation::sign(signer, repo(), rule, inputs, content.changeset_id(), tree); + DerivedRevision { + content, + attestation, + } +} + +/// A derived record holding `derived`, as a lying server would have written it. +fn derived_record(derived: DerivedRevision) -> WalRecord { + WalRecord::DerivedRevisionAdmitted { + derived, + chain: authority("a").chain, + admitted_at_ms: NOW, + } +} + +struct Fx { + dir: PathBuf, + svc: SynapseService, + server: SigningKey, + keys: IdentityLog, + delegates: [SigningKey; 2], + b0: TreeDigest, + b1: TreeDigest, + /// `ra` upserts src/a.rs, `rb` adds src/b.rs, `rc` upserts docs/x.md; all on `B0`. + ra: ChangesetEnvelopeV2, + rb: ChangesetEnvelopeV2, + rc: ChangesetEnvelopeV2, +} + +impl Fx { + fn new(name: &str) -> Self { + let dir: PathBuf = std::env::temp_dir().join(format!( + "synapse-b5-{name}-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + let mut svc = open(&dir); + let b0 = svc + .tree_digest(TreeTarget::BaseGitCommit(B0), None) + .unwrap(); + let b1 = svc + .tree_digest(TreeTarget::BaseGitCommit(B1), None) + .unwrap(); + let server = key("server"); + let delegates = [key("delegate 1"), key("delegate 2")]; + let mut ds = vec![pk(&delegates[0]), pk(&delegates[1])]; + ds.sort(); + let genesis = RepositoryIdentityDocument { + repo_id: repo(), + revision: 0, + prev: IdentityDocumentDigest::ZERO, + threshold: 2, + delegates: ds, + executors: vec![], + server_key: pk(&server), + }; + let edit = IdentityEdit::sign(genesis, &[&delegates[0], &delegates[1]]); + let keys = IdentityLog::genesis(&edit, WalSeq(0)).unwrap(); + let ra = agent_revision("a", b0, "src/a.rs", b"a1"); + let rb = agent_revision("b", b0, "src/b.rs", b"b1"); + let rc = agent_revision("c", b0, "docs/x.md", b"xc"); + for (env, who, body) in [ + (&ra, "a", b"a1".as_slice()), + (&rb, "b", b"b1".as_slice()), + (&rc, "c", b"xc".as_slice()), + ] { + let out = svc + .store_mut() + .admit_revision( + env.clone(), + &[(BlobDigest::compute(body), body.to_vec())], + authority(who), + NOW, + ) + .unwrap(); + assert!(matches!(out, RevisionOutcome::Admitted { .. })); + } + Self { + dir, + svc, + server, + keys, + delegates, + b0, + b1, + ra, + rb, + rc, + } + } + + fn derive(&mut self, rule: DerivationRule, inputs: Vec) -> DerivedRevision { + let server = self.server.clone(); + self.svc.derive_revision(&server, rule, inputs).unwrap() + } + + fn rebase_inputs(&self, of: &ChangesetEnvelopeV2) -> Vec { + vec![ + DerivationInput::Revision(of.changeset_id()), + DerivationInput::Tree(self.b1), + ] + } + + /// The honest rebase of `ra` onto `B1`. + fn rebase_a(&mut self) -> DerivedRevision { + let inputs = self.rebase_inputs(&self.ra); + self.derive(DerivationRule::Rebase, inputs) + } + + /// The honest T0 merge of `ra` and `rb` on `B0`, inputs in the canonical merge order. + fn merge_ab(&mut self) -> DerivedRevision { + let mut ids = vec![self.ra.changeset_id(), self.rb.changeset_id()]; + ids.sort(); + let mut inputs = vec![DerivationInput::Tree(self.b0)]; + inputs.extend(ids.into_iter().map(DerivationInput::Revision)); + self.derive(T0, inputs) + } + + fn admit(&mut self, derived: DerivedRevision, who: &str) -> Result { + let keys = self.keys.clone(); + match self + .svc + .admit_derived_revision(derived, authority(who), &keys, NOW) + { + Ok(RevisionOutcome::Admitted { wal_seq, .. }) => Ok(wal_seq), + Ok(other) => panic!("unexpected outcome {other:?}"), + Err(e) => Err(e.code), + } + } + + /// Admit `derived` and expect `code`, with nothing written. + fn refused_at_admission(&mut self, derived: DerivedRevision, code: RefusalCode) { + let before = self.svc.store().committed_seq(); + assert_eq!(self.admit(derived, "a"), Err(code), "refused at admission"); + assert_eq!(self.svc.store().committed_seq(), before, "nothing written"); + } + + fn records(&self) -> Vec<(WalSeq, WalRecord)> { + self.svc.store().revision_records().to_vec() + } + + /// The store's revision records with the record at `seq` replaced by `record`. + fn records_with(&self, seq: WalSeq, record: WalRecord) -> Vec<(WalSeq, WalRecord)> { + let mut records = self.records(); + let slot = records.iter_mut().find(|(s, _)| *s == seq).unwrap(); + slot.1 = record; + records + } + + fn verify(&mut self, records: &[(WalSeq, WalRecord)]) -> Result { + let keys = self.keys.clone(); + self.svc + .verify_revision_records(records, &keys) + .map_err(|e| e.code) + } + + /// Refused at admission, and refused at replay when a record carrying `forged` replaces + /// the honest derived record at `honest_seq`. + fn refused_at_admission_and_replay( + &mut self, + honest_seq: WalSeq, + forged: DerivedRevision, + code: RefusalCode, + ) { + self.refused_at_admission(forged.clone(), code); + let records = self.records_with(honest_seq, derived_record(forged)); + assert_eq!(self.verify(&records), Err(code), "refused at replay"); + } +} + +#[test] +fn b5_replica_recomputes_every_derived_revision_and_gets_the_same_digests() { + let mut fx = Fx::new("recompute"); + let rebase = fx.rebase_a(); + let merge = fx.merge_ab(); + // The derived trees equal independently built trees. + let rebased_tree = fx + .svc + .tree_digest(TreeTarget::BaseGitCommit(B1_REBASED_A), None) + .unwrap(); + let merged_tree = fx + .svc + .tree_digest(TreeTarget::BaseGitCommit(B0_MERGED_AB), None) + .unwrap(); + assert_eq!(rebase.attestation.output_tree, rebased_tree); + assert_eq!(merge.attestation.output_tree, merged_tree); + // A rebase keeps the change, parents, mutations and intent; only the base moves. + assert_eq!(rebase.content.change_id, fx.ra.content.change_id); + assert_eq!(rebase.content.base_tree, fx.b1); + assert_eq!(rebase.content.mutations, fx.ra.content.mutations); + assert_eq!(rebase.content.intent_summary, fx.ra.content.intent_summary); + // A merge's parents are the merged revisions in the canonical order. + let mut parents = vec![fx.ra.changeset_id(), fx.rb.changeset_id()]; + parents.sort(); + assert_eq!(merge.content.parents, parents); + assert_eq!(merge.content.base_tree, fx.b0); + assert_eq!(merge.content.mutations.len(), 2); + + let s_rebase = fx.admit(rebase.clone(), "a").unwrap(); + let s_merge = fx.admit(merge.clone(), "merge").unwrap(); + assert!(s_rebase < s_merge); + // The witness names the server key and the attestation; no agent signature is claimed. + for d in [&rebase, &merge] { + let stored = fx + .svc + .store() + .get_revision(&repo(), d.changeset_id()) + .unwrap(); + assert!(stored.attestations.is_empty(), "no authorship attestation"); + assert_eq!(stored.derivations, vec![d.attestation.clone()]); + assert_eq!(stored.witnesses.len(), 1); + assert_eq!( + stored.witnesses[0].signer, + WitnessSigner::Server { + server_key: pk(&fx.server), + signature: d.attestation.signature, + attestation_digest: d.attestation.digest(), + } + ); + } + let live = fx.records(); + assert_eq!(fx.verify(&live), Ok(5), "3 agent and 2 derived revisions"); + + // A replica: reopen from the WAL (base trees registered again), recompute everything. + let Fx { + dir, + svc, + keys, + server, + .. + } = fx; + drop(svc); + let mut replica = open(&dir); + assert_eq!(replica.store().revision_records(), live.as_slice()); + assert_eq!(replica.verify_revision_log(&keys).unwrap(), 5); + // Recomputing on the replica gives byte-identical revisions and attestations. + let again = replica + .derive_revision( + &server, + DerivationRule::Rebase, + rebase.attestation.inputs.clone(), + ) + .unwrap(); + assert_eq!(again, rebase); + let again = replica + .derive_revision(&server, T0, merge.attestation.inputs.clone()) + .unwrap(); + assert_eq!(again, merge); + // Through a checkpoint (which keeps revision records) and another reopen. + replica.store_mut().checkpoint_and_compact(NOW).unwrap(); + drop(replica); + let mut replica = open(&dir); + assert_eq!(replica.store().revision_records(), live.as_slice()); + assert_eq!(replica.verify_revision_log(&keys).unwrap(), 5); +} + +#[test] +fn b5_attestation_naming_different_inputs_is_refused_at_admission_and_replay() { + let mut fx = Fx::new("inputs"); + let honest = fx.rebase_a(); + let at = fx.admit(honest.clone(), "a").unwrap(); + let rule = DerivationRule::Rebase; + let tree = honest.attestation.output_tree; + // The same output, attributed to another real revision (`rb` rebased onto `B1` is not it). + let other = fx.rebase_inputs(&fx.rb); + let forged = forge(&fx.server, honest.content.clone(), rule, other, tree); + fx.refused_at_admission_and_replay(at, forged, RefusalCode::DerivationRecomputeMismatch); + // Attributed to a revision nobody admitted. + let unknown = vec![ + DerivationInput::Revision(ChangesetId(label("unknown revision"))), + DerivationInput::Tree(fx.b1), + ]; + let forged = forge(&fx.server, honest.content.clone(), rule, unknown, tree); + fx.refused_at_admission_and_replay(at, forged, RefusalCode::DerivationInputMismatch); + // Onto a tree nobody holds. + let nowhere = vec![ + DerivationInput::Revision(fx.ra.changeset_id()), + DerivationInput::Tree(TreeDigest(label("unknown tree"))), + ]; + let forged = forge(&fx.server, honest.content.clone(), rule, nowhere, tree); + fx.refused_at_admission_and_replay(at, forged, RefusalCode::DerivationInputMismatch); + // The honest record still verifies. + let live = fx.records(); + assert_eq!(fx.verify(&live), Ok(4)); +} + +#[test] +fn b5_attestation_naming_a_different_rule_is_refused_at_admission_and_replay() { + let mut fx = Fx::new("rule"); + let merge = fx.merge_ab(); + let at = fx.admit(merge.clone(), "merge").unwrap(); + let tree = merge.attestation.output_tree; + // The merge's own inputs under the rebase rule. + let forged = forge( + &fx.server, + merge.content.clone(), + DerivationRule::Rebase, + merge.attestation.inputs.clone(), + tree, + ); + fx.refused_at_admission_and_replay(at, forged, RefusalCode::DerivationInputMismatch); + // The merge's output claimed as a rebase of its first input onto its own base (no move). + let as_rebase = vec![ + DerivationInput::Revision(merge.content.parents[0]), + DerivationInput::Tree(fx.b0), + ]; + let forged = forge( + &fx.server, + merge.content.clone(), + DerivationRule::Rebase, + as_rebase, + tree, + ); + fx.refused_at_admission_and_replay(at, forged, RefusalCode::DerivationRecomputeMismatch); + // A rebase's output and inputs claimed as a T0 merge. + let rebase = fx.rebase_a(); + let forged = forge( + &fx.server, + rebase.content.clone(), + T0, + rebase.attestation.inputs.clone(), + rebase.attestation.output_tree, + ); + fx.refused_at_admission(forged, RefusalCode::DerivationInputMismatch); + let live = fx.records(); + assert_eq!(fx.verify(&live), Ok(4)); +} + +#[test] +fn b5_unregistered_server_key_is_refused_at_admission_and_replay() { + let mut fx = Fx::new("unregistered"); + let honest = fx.rebase_a(); + let at = fx.admit(honest.clone(), "a").unwrap(); + // A correctly computed and validly signed derivation by a key the identity document does + // not register as `server_key` (a delegate's key is not a server key either). + for signer in [key("rogue server"), fx.delegates[0].clone()] { + let a = &honest.attestation; + let forged = forge( + &signer, + honest.content.clone(), + a.rule, + a.inputs.clone(), + a.output_tree, + ); + assert_eq!(forged.attestation.server_key, pk(&signer)); + fx.refused_at_admission_and_replay( + at, + forged, + RefusalCode::DerivationServerKeyUnregistered, + ); + } + + // Rotation: from the next sequence the document names `s2`. The derivation admitted + // before still verifies at its own sequence; the old key is refused after it. + let s2 = key("server 2"); + let rotate_at = fx.svc.store().committed_seq().next(); + let mut next = fx.keys.current().successor(); + next.server_key = pk(&s2); + let edit = IdentityEdit::sign(next, &[&fx.delegates[0], &fx.delegates[1]]); + fx.keys.apply(&edit, rotate_at).unwrap(); + let merge = fx.merge_ab(); + assert_eq!(merge.attestation.server_key, pk(&fx.server)); + fx.refused_at_admission(merge.clone(), RefusalCode::DerivationServerKeyUnregistered); + let a = &merge.attestation; + let by_s2 = forge( + &s2, + merge.content.clone(), + a.rule, + a.inputs.clone(), + a.output_tree, + ); + let s_merge = fx.admit(by_s2, "merge").unwrap(); + assert!(s_merge >= rotate_at); + let live = fx.records(); + assert_eq!(fx.verify(&live), Ok(5), "each verifies at its own sequence"); + // At replay, the old key's merge in place of the new key's is refused. + let records = fx.records_with(s_merge, derived_record(merge)); + assert_eq!( + fx.verify(&records), + Err(RefusalCode::DerivationServerKeyUnregistered) + ); +} + +#[test] +fn b5_attestation_signed_by_another_key_is_refused_at_admission_and_replay() { + let mut fx = Fx::new("signature"); + let honest = fx.rebase_a(); + let at = fx.admit(honest.clone(), "a").unwrap(); + // Signed by a rogue key while naming the registered server key. + let a = &honest.attestation; + let mut forged = forge( + &key("rogue server"), + honest.content.clone(), + a.rule, + a.inputs.clone(), + a.output_tree, + ); + forged.attestation.server_key = pk(&fx.server); + fx.refused_at_admission_and_replay(at, forged, RefusalCode::DerivationSignatureInvalid); + // The registered key's attestation presented with content it does not name. + let mut swapped = honest.clone(); + swapped.content.intent_summary = "a different intent".into(); + fx.refused_at_admission_and_replay(at, swapped, RefusalCode::DerivationSignatureInvalid); + // A field changed after signing. + let mut tampered = honest.clone(); + tampered.attestation.output_tree = fx.b0; + fx.refused_at_admission_and_replay(at, tampered, RefusalCode::DerivationSignatureInvalid); +} + +#[test] +fn b5_derived_revision_presented_with_an_agent_signature_it_does_not_have_is_refused() { + let mut fx = Fx::new("agent-signature"); + let derived = fx.rebase_a(); + // `ra`'s author never signed the rebased content: its attestation as is, or re-pointed at + // the derived revision, is refused. + let mut repointed = fx.ra.attestation.clone(); + repointed.changeset_id = derived.changeset_id(); + let borrowed: Vec = [fx.ra.attestation.clone(), repointed] + .into_iter() + .map(|attestation| ChangesetEnvelopeV2 { + content: derived.content.clone(), + attestation, + }) + .collect(); + let body = b"a1"; + for env in &borrowed { + let before = fx.svc.store().committed_seq(); + let err = fx + .svc + .store_mut() + .admit_revision( + env.clone(), + &[(BlobDigest::compute(body), body.to_vec())], + authority("a"), + NOW, + ) + .unwrap_err(); + assert_eq!(err.code, RefusalCode::AuthSignatureInvalid); + assert_eq!(fx.svc.store().committed_seq(), before, "nothing written"); + } + // At replay: a revision record carrying a borrowed signature in place of the derived + // record is refused. + let at = fx.admit(derived.clone(), "a").unwrap(); + for env in borrowed { + let record = WalRecord::RevisionAdmitted { + envelope: env, + chain: authority("a").chain, + admitted_at_ms: NOW, + new_blobs: vec![], + }; + let records = fx.records_with(at, record); + assert_eq!(fx.verify(&records), Err(RefusalCode::AuthSignatureInvalid)); + } + // The stored revision claims no agent signature. + let stored = fx + .svc + .store() + .get_revision(&repo(), derived.changeset_id()) + .unwrap(); + assert!(stored.attestations.is_empty()); +} + +#[test] +fn b5_replayed_attestation_is_refused_at_admission_and_replay() { + let mut fx = Fx::new("replayed"); + let honest = fx.rebase_a(); + let at = fx.admit(honest.clone(), "a").unwrap(); + // The same attestation presented again, under the same or another chain. + fx.refused_at_admission(honest.clone(), RefusalCode::DerivationAttestationReplayed); + let before = fx.svc.store().committed_seq(); + assert_eq!( + fx.admit(honest.clone(), "b"), + Err(RefusalCode::DerivationAttestationReplayed) + ); + assert_eq!(fx.svc.store().committed_seq(), before); + // At replay: the record duplicated at a later sequence is refused. + let mut records = fx.records(); + let dup = records.iter().find(|(s, _)| *s == at).unwrap().1.clone(); + records.push((before.next(), dup)); + assert_eq!( + fx.verify(&records), + Err(RefusalCode::DerivationAttestationReplayed) + ); +} + +#[test] +fn b5_recomputation_that_disagrees_is_refused_at_admission_and_replay() { + let mut fx = Fx::new("disagree"); + let honest = fx.rebase_a(); + let at = fx.admit(honest.clone(), "a").unwrap(); + let a = honest.attestation.clone(); + // The right inputs and rule with a wrong output tree (the independently built merge tree). + let wrong_tree = fx + .svc + .tree_digest(TreeTarget::BaseGitCommit(B0_MERGED_AB), None) + .unwrap(); + let forged = forge( + &fx.server, + honest.content.clone(), + a.rule, + a.inputs.clone(), + wrong_tree, + ); + fx.refused_at_admission_and_replay(at, forged, RefusalCode::DerivationRecomputeMismatch); + // The right inputs and rule with other content (an extra mutation the rule never makes). + let mut content = honest.content.clone(); + content.mutations.push(upsert("src/z.rs", b"a1")); + let forged = forge(&fx.server, content, a.rule, a.inputs.clone(), a.output_tree); + fx.refused_at_admission_and_replay(at, forged, RefusalCode::DerivationRecomputeMismatch); + // `rc` changed docs/x.md, which `B1` also changed: the rebase conflicts and cannot be + // derived, so no attestation of it is produced. + let inputs = fx.rebase_inputs(&fx.rc); + let server = fx.server.clone(); + let err = fx + .svc + .derive_revision(&server, DerivationRule::Rebase, inputs) + .unwrap_err(); + assert_eq!(err.code, RefusalCode::DerivationRecomputeMismatch); + let live = fx.records(); + assert_eq!(fx.verify(&live), Ok(4)); +} diff --git a/crates/synapse-core/src/derivation.rs b/crates/synapse-core/src/derivation.rs new file mode 100644 index 0000000..0e12036 --- /dev/null +++ b/crates/synapse-core/src/derivation.rs @@ -0,0 +1,755 @@ +//! Server-derived revisions and their `DerivationAttestation` (ADR 0003 sections 5.1, 5.3, 5.6 +//! and 5.8, section 9 step B5). See `docs/B5_DERIVATION_ATTESTATION.md`. +//! +//! * A **derived revision** is one the server produced rather than an agent: a rebase of an +//! admitted revision onto another tree, or a merge of admitted revisions. It carries no agent +//! signature. A [`DerivedRevision`] is its content plus one [`DerivationAttestation`]. +//! * A [`DerivationAttestation`] is signed by the server's machine key (the `server_key` of the +//! repository identity document, step E0). It names the inputs (revisions and trees), the +//! deterministic [`DerivationRule`], and the output `ChangesetId` and `TreeDigest`. +//! * [`derive_revision_output`] is the one definition of every rule. The server uses it to +//! produce a derived revision and every replica uses it to recompute one; an attestation whose +//! recomputation differs is refused. +//! +//! The encodings follow `docs/B1_CHANGE_IDENTITY.md` section 3 (principle P5): little-endian, +//! length-prefixed, every count bounded before allocation, trailing bytes refused, and every +//! decode refusal `EnvelopeMalformed`. + +use crate::revision::{malformed, put_str, Reader}; +use crate::{ + encode_did_key_ed25519, AdmissionWitness, ChainPath, ChangeId, ChangesetId, IdempotencyKey, + PathMutation, RefusalCode, RepoId, RevisionContent, SynapseError, SynapseResult, TreeDigest, + WalSeq, WitnessSigner, +}; +use ed25519_dalek::{Signature, Signer, SigningKey, VerifyingKey}; +use sha2::{Digest, Sha256}; + +/// Domain tag of the server's Ed25519 signature over a [`DerivationAttestation`]. +pub const DOMAIN_DERIVATION_SIGN_V1: &[u8] = b"SYNAPSE_DERIVATION_SIGN_V1\0"; +/// Domain tag of [`DerivationAttestation::digest`]. +pub const DOMAIN_DERIVATION_ATTESTATION_V1: &[u8] = b"SYNAPSE_DERIVATION_ATTESTATION_V1\0"; +/// Domain tag of the `ChangeId` of a merge output (a merge starts a new unit of work whose +/// identity must be recomputable from its inputs). +pub const DOMAIN_DERIVED_MERGE_CHANGE_V1: &[u8] = b"SYNAPSE_DERIVED_MERGE_CHANGE_V1\0"; +/// Most inputs one attestation names. +pub const MAX_DERIVATION_INPUTS: usize = 256; + +const RULE_TAG_REBASE: u8 = 1; +const RULE_TAG_MERGE: u8 = 2; +// Tag 3 is reserved for the derived-file action (the `ActionDigest` of the declared action, +// ADR 0003 section 5.3); it needs registered executors and is not decodable yet. +const TIER_TAG_T0: u8 = 0; +const INPUT_TAG_REVISION: u8 = 1; +const INPUT_TAG_TREE: u8 = 2; +/// Encoded size of the smallest input (tag and a 32-byte digest). +const MIN_INPUT_BYTES: usize = 1 + 32; + +fn input_mismatch(msg: impl Into) -> SynapseError { + SynapseError::new(RefusalCode::DerivationInputMismatch, msg) +} + +fn recompute_mismatch(msg: impl Into) -> SynapseError { + SynapseError::new(RefusalCode::DerivationRecomputeMismatch, msg) +} + +// --------------------------------------------------------------------------------------- +// Rules and inputs +// --------------------------------------------------------------------------------------- + +/// The level a merge works at (`MergeTier` in `CONTEXT.md`). Only T0 exists before step D1. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum MergeTier { + /// Path level: the merged revisions touch disjoint paths (no path of one equals, contains, + /// or lies inside a path of another). + T0Path, +} + +/// The deterministic rule a derivation applied. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum DerivationRule { + /// Rebase one admitted revision onto another tree, at path level. Inputs: exactly + /// `[Revision(r), Tree(onto)]`. The output keeps `r`'s `ChangeId`, parents, mutations and + /// intent and takes `onto` as its base. Refused when `onto` is already `r`'s base, or when + /// a path `r` mutates collides with a path that differs between `r`'s base and `onto` + /// (that is a conflict, recorded by later steps as a conflict term, never overwritten). + Rebase, + /// Merge admitted revisions that share one base. Inputs: `[Tree(base), Revision(a1), ..., + /// Revision(an)]` with `n >= 2` and the revisions in the canonical merge order (strictly + /// ascending `ChangesetId`). The output's base is `base`, its parents are the merged + /// revisions, its mutations are their union (paths must be disjoint at tier T0), its + /// `ChangeId` is the first 16 bytes of `SHA-256(DOMAIN_DERIVED_MERGE_CHANGE_V1 || base || + /// u32 n || id*)`, and its intent summary is `merge tier T0 of revisions`. + Merge { tier: MergeTier }, +} + +impl DerivationRule { + fn encode_into(&self, buf: &mut Vec) { + match self { + DerivationRule::Rebase => buf.push(RULE_TAG_REBASE), + DerivationRule::Merge { tier } => { + buf.push(RULE_TAG_MERGE); + buf.push(match tier { + MergeTier::T0Path => TIER_TAG_T0, + }); + } + } + } + + fn decode_from(r: &mut Reader) -> SynapseResult { + match r.u8()? { + RULE_TAG_REBASE => Ok(DerivationRule::Rebase), + RULE_TAG_MERGE => match r.u8()? { + TIER_TAG_T0 => Ok(DerivationRule::Merge { + tier: MergeTier::T0Path, + }), + tag => Err(malformed(format!("unknown merge tier tag {tag}"))), + }, + tag => Err(malformed(format!("unknown derivation rule tag {tag}"))), + } + } +} + +/// One input a derivation names: an admitted revision or a tree. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum DerivationInput { + Revision(ChangesetId), + Tree(TreeDigest), +} + +impl DerivationInput { + fn encode_into(&self, buf: &mut Vec) { + match self { + DerivationInput::Revision(id) => { + buf.push(INPUT_TAG_REVISION); + buf.extend_from_slice(&id.0); + } + DerivationInput::Tree(t) => { + buf.push(INPUT_TAG_TREE); + buf.extend_from_slice(&t.0); + } + } + } + + fn decode_from(r: &mut Reader) -> SynapseResult { + match r.u8()? { + INPUT_TAG_REVISION => Ok(DerivationInput::Revision(ChangesetId(r.array()?))), + INPUT_TAG_TREE => Ok(DerivationInput::Tree(TreeDigest(r.array()?))), + tag => Err(malformed(format!("unknown derivation input tag {tag}"))), + } + } +} + +// --------------------------------------------------------------------------------------- +// Attestation and derived revision +// --------------------------------------------------------------------------------------- + +/// The server's signed statement that revision `output_changeset`, whose tree is +/// `output_tree`, is what `rule` gives on `inputs` in repository `repo_id` (ADR 0003 section +/// 5.1). Deterministic: the same derivation always gives the same attestation bytes, so a +/// second presentation of one derivation is a replay. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct DerivationAttestation { + pub repo_id: RepoId, + pub rule: DerivationRule, + pub inputs: Vec, + pub output_changeset: ChangesetId, + pub output_tree: TreeDigest, + /// The server machine key that signed (must be the identity document's `server_key` in + /// effect at the admission `WalSeq`). + pub server_key: [u8; 32], + pub signature: [u8; 64], +} + +impl DerivationAttestation { + /// Sign an attestation with the server's machine key. + pub fn sign( + server: &SigningKey, + repo_id: RepoId, + rule: DerivationRule, + inputs: Vec, + output_changeset: ChangesetId, + output_tree: TreeDigest, + ) -> Self { + let mut att = Self { + repo_id, + rule, + inputs, + output_changeset, + output_tree, + server_key: server.verifying_key().to_bytes(), + signature: [0u8; 64], + }; + att.signature = server.sign(&att.signable_bytes()).to_bytes(); + att + } + + /// The server key's `did:key`. + pub fn server_did(&self) -> String { + encode_did_key_ed25519(&self.server_key) + } + + fn encode_body(&self, buf: &mut Vec) { + put_str(buf, self.repo_id.as_str()); + self.rule.encode_into(buf); + buf.extend_from_slice(&(self.inputs.len() as u32).to_le_bytes()); + for i in &self.inputs { + i.encode_into(buf); + } + buf.extend_from_slice(&self.output_changeset.0); + buf.extend_from_slice(&self.output_tree.0); + buf.extend_from_slice(&self.server_key); + } + + /// `DOMAIN_DERIVATION_SIGN_V1 || repo_id str || rule || u32 count || input* || + /// output_changeset [32] || output_tree [32] || server_key [32]`. + pub fn signable_bytes(&self) -> Vec { + let mut buf = Vec::with_capacity(192 + 33 * self.inputs.len()); + buf.extend_from_slice(DOMAIN_DERIVATION_SIGN_V1); + self.encode_body(&mut buf); + buf + } + + /// 1..=`MAX_DERIVATION_INPUTS` inputs and a strict Ed25519 signature by `server_key`. + /// Both a key that is not an Ed25519 point and a signature that does not verify are + /// `DerivationSignatureInvalid`. + pub fn verify(&self) -> SynapseResult<()> { + if self.inputs.is_empty() || self.inputs.len() > MAX_DERIVATION_INPUTS { + return Err(input_mismatch(format!( + "derivation names {} inputs, outside 1..={MAX_DERIVATION_INPUTS}", + self.inputs.len() + ))); + } + let invalid = |what: &str| { + SynapseError::new( + RefusalCode::DerivationSignatureInvalid, + format!("derivation attestation: {what}"), + ) + }; + let vk = VerifyingKey::from_bytes(&self.server_key) + .map_err(|_| invalid("server key is not an Ed25519 public key"))?; + vk.verify_strict( + &self.signable_bytes(), + &Signature::from_bytes(&self.signature), + ) + .map_err(|_| invalid("signature does not verify under the named server key")) + } + + /// Body (as signed, without the domain tag) then the 64-byte signature. + pub fn encode(&self) -> Vec { + let mut buf = Vec::with_capacity(256 + 33 * self.inputs.len()); + self.encode_into(&mut buf); + buf + } + + fn encode_into(&self, buf: &mut Vec) { + self.encode_body(buf); + buf.extend_from_slice(&self.signature); + } + + /// Decode exactly one canonical attestation (structure only; see [`Self::verify`]). + pub fn decode(bytes: &[u8]) -> SynapseResult { + let mut r = Reader::new(bytes); + let att = Self::decode_from(&mut r)?; + r.finish()?; + Ok(att) + } + + fn decode_from(r: &mut Reader) -> SynapseResult { + let repo_id = r.repo()?; + let rule = DerivationRule::decode_from(r)?; + let n = r.count(MAX_DERIVATION_INPUTS, MIN_INPUT_BYTES)?; + if n == 0 { + return Err(malformed("derivation names no inputs")); + } + let mut inputs = Vec::with_capacity(n); + for _ in 0..n { + inputs.push(DerivationInput::decode_from(r)?); + } + Ok(Self { + repo_id, + rule, + inputs, + output_changeset: ChangesetId(r.array()?), + output_tree: TreeDigest(r.array()?), + server_key: r.array()?, + signature: r.array()?, + }) + } + + /// `SHA-256(DOMAIN_DERIVATION_ATTESTATION_V1 || encode())`: the identity of one signed + /// attestation, recorded in the admission witness and used to refuse replays. + pub fn digest(&self) -> [u8; 32] { + let mut h = Sha256::new(); + h.update(DOMAIN_DERIVATION_ATTESTATION_V1); + h.update(self.encode()); + h.finalize().into() + } +} + +/// A server-derived revision: its content and the attestation over it. It has no agent +/// signature and never claims one. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct DerivedRevision { + pub content: RevisionContent, + pub attestation: DerivationAttestation, +} + +impl DerivedRevision { + /// Produce a derived revision: recompute `rule` on `inputs` (the same function every + /// replica runs) and sign the attestation with the server's machine key. + pub fn derive( + server: &SigningKey, + repo_id: RepoId, + rule: DerivationRule, + inputs: Vec, + revision: &dyn Fn(ChangesetId) -> Option, + trees: &mut dyn DerivationTrees, + ) -> SynapseResult { + let (content, tree) = derive_revision_output(rule, &inputs, revision, trees)?; + let attestation = DerivationAttestation::sign( + server, + repo_id, + rule, + inputs, + content.changeset_id(), + tree, + ); + Ok(Self { + content, + attestation, + }) + } + + /// The content-only v2 `ChangesetId`. + pub fn changeset_id(&self) -> ChangesetId { + self.content.changeset_id() + } + + /// Validate the content (the B1 rules), check that the attestation names this content + /// (`DerivationSignatureInvalid` otherwise), and verify the attestation. This needs no + /// state; registration of the server key, replay, and recomputation are checked against + /// the ledger, the identity document, and the tree store. + pub fn validate(&self) -> SynapseResult { + self.content.validate()?; + let id = self.content.changeset_id(); + if self.attestation.output_changeset != id { + return Err(SynapseError::new( + RefusalCode::DerivationSignatureInvalid, + format!( + "derivation attestation names revision {} but the content is revision {id}", + self.attestation.output_changeset + ), + )); + } + self.attestation.verify()?; + Ok(id) + } + + /// `u32 content_len | content | attestation`. + pub fn encode(&self) -> Vec { + let content = self.content.encode(); + let mut buf = Vec::with_capacity(content.len() + 256); + buf.extend_from_slice(&(content.len() as u32).to_le_bytes()); + buf.extend_from_slice(&content); + self.attestation.encode_into(&mut buf); + buf + } + + /// Decode exactly one canonical derived revision (structure only; see [`Self::validate`]). + pub fn decode(bytes: &[u8]) -> SynapseResult { + let mut r = Reader::new(bytes); + let len = r.u32()? as usize; + let mut inner = Reader::new(r.take(len)?); + let content = RevisionContent::decode_from(&mut inner)?; + inner.finish()?; + let attestation = DerivationAttestation::decode_from(&mut r)?; + r.finish()?; + Ok(Self { + content, + attestation, + }) + } +} + +impl AdmissionWitness { + /// The witness of admitting `derived` at `admission_seq` under `chain`: the server key, + /// its signature, and the attestation digest instead of an agent signature. The + /// idempotency key is the attestation digest (a derivation has no client key; a second + /// presentation of one attestation is refused as a replay). + pub fn of_derivation( + derived: &DerivedRevision, + chain: ChainPath, + admission_seq: WalSeq, + admitted_at_ms: u64, + ) -> Self { + let att = &derived.attestation; + let digest = att.digest(); + Self { + repo_id: att.repo_id.clone(), + changeset_id: att.output_changeset, + signer: WitnessSigner::Server { + server_key: att.server_key, + signature: att.signature, + attestation_digest: digest, + }, + idempotency_key: IdempotencyKey(digest), + admission_seq, + admitted_at_ms, + chain, + } + } +} + +// --------------------------------------------------------------------------------------- +// What a replica needs to check and recompute +// --------------------------------------------------------------------------------------- + +/// Which server machine key the repository identity document registered at a `WalSeq` +/// (`synapse_radicle::IdentityLog` implements it from the E0 document chain). +pub trait ServerKeyRegistry { + /// The `server_key` of the document in effect at `at`; `None` before genesis. + fn registered_server_key(&self, at: WalSeq) -> Option<[u8; 32]>; +} + +/// The tree operations a derivation rule needs (the C1 tree store implements them). +pub trait DerivationTrees { + /// Whether the tree `tree` can be read (its root node is held). + fn holds_tree(&mut self, tree: TreeDigest) -> bool; + /// The root of `base` with `mutations` applied in order. + fn apply_mutations( + &mut self, + base: TreeDigest, + mutations: &[PathMutation], + ) -> SynapseResult; + /// Every file path whose entry differs between `from` and `to`. + fn changed_paths(&mut self, from: TreeDigest, to: TreeDigest) -> SynapseResult>; +} + +/// `true` when `inner` lies strictly below directory `dir`. +fn is_below(inner: &str, dir: &str) -> bool { + inner.len() > dir.len() && inner.starts_with(dir) && inner.as_bytes()[dir.len()] == b'/' +} + +/// Two paths collide at path level when they are equal or one lies below the other. +fn paths_collide(a: &str, b: &str) -> bool { + a == b || is_below(a, b) || is_below(b, a) +} + +/// Any pair of paths, one from each sorted list, that collides. +fn first_collision<'a>(a: &'a [&'a str], b: &'a [&'a str]) -> Option<(&'a str, &'a str)> { + for x in a { + for y in b { + if paths_collide(x, y) { + return Some((x, y)); + } + } + } + None +} + +/// The `ChangeId` of a T0 merge of `ids` (canonical order) on `base`. +fn require_tree(trees: &mut dyn DerivationTrees, t: TreeDigest, what: &str) -> SynapseResult<()> { + if trees.holds_tree(t) { + Ok(()) + } else { + Err(input_mismatch(format!( + "{what} {t} is not held by this replica" + ))) + } +} + +fn merge_change_id(base: TreeDigest, ids: &[ChangesetId]) -> ChangeId { + let mut h = Sha256::new(); + h.update(DOMAIN_DERIVED_MERGE_CHANGE_V1); + h.update(base.0); + h.update((ids.len() as u32).to_le_bytes()); + for id in ids { + h.update(id.0); + } + let d: [u8; 32] = h.finalize().into(); + let mut out = [0u8; 16]; + out.copy_from_slice(&d[..16]); + ChangeId(out) +} + +/// The output content and tree of `rule` on `inputs`: the one definition of every rule, run +/// by the server to derive and by every replica to recompute. `revision` resolves an admitted +/// revision of the attestation's repository (admitted before the derivation). +/// +/// Refusals: inputs that do not fit the rule (kind, count, order, duplicates) or that are not +/// held (`revision` returns `None`, or the tree is not held) are `DerivationInputMismatch`; a +/// rule that does not apply to the inputs (a rebase onto its own base or with a path conflict, +/// a merge of revisions on another base or with colliding paths) is +/// `DerivationRecomputeMismatch`. Tree store failures propagate unchanged. +pub fn derive_revision_output( + rule: DerivationRule, + inputs: &[DerivationInput], + revision: &dyn Fn(ChangesetId) -> Option, + trees: &mut dyn DerivationTrees, +) -> SynapseResult<(RevisionContent, TreeDigest)> { + if inputs.is_empty() || inputs.len() > MAX_DERIVATION_INPUTS { + return Err(input_mismatch(format!( + "derivation names {} inputs, outside 1..={MAX_DERIVATION_INPUTS}", + inputs.len() + ))); + } + let resolve = |id: ChangesetId| { + revision(id).ok_or_else(|| { + input_mismatch(format!( + "input revision {id} is not an admitted revision of this repository" + )) + }) + }; + match rule { + DerivationRule::Rebase => { + let [DerivationInput::Revision(r), DerivationInput::Tree(onto)] = inputs else { + return Err(input_mismatch( + "a rebase names exactly [Revision(r), Tree(onto)]", + )); + }; + let source = resolve(*r)?; + require_tree(trees, *onto, "rebase target tree")?; + require_tree(trees, source.base_tree, "base tree of the rebased revision")?; + if source.base_tree == *onto { + return Err(recompute_mismatch(format!( + "revision {r} is already based on {onto}: nothing to rebase" + ))); + } + let changed = trees.changed_paths(source.base_tree, *onto)?; + let changed: Vec<&str> = changed.iter().map(String::as_str).collect(); + let mutated: Vec<&str> = source.mutations.iter().map(|m| m.path.as_str()).collect(); + if let Some((m, c)) = first_collision(&mutated, &changed) { + return Err(recompute_mismatch(format!( + "path-level rebase of {r} conflicts: {m} collides with {c}, which differs between its base and {onto}" + ))); + } + let content = RevisionContent { + base_tree: *onto, + ..source + }; + content.validate()?; + let tree = trees.apply_mutations(*onto, &content.mutations)?; + Ok((content, tree)) + } + DerivationRule::Merge { + tier: MergeTier::T0Path, + } => { + let Some((DerivationInput::Tree(base), rest)) = inputs.split_first() else { + return Err(input_mismatch( + "a merge names [Tree(base), Revision(a1), ..., Revision(an)]", + )); + }; + let mut ids = Vec::with_capacity(rest.len()); + for i in rest { + match i { + DerivationInput::Revision(id) => ids.push(*id), + DerivationInput::Tree(_) => { + return Err(input_mismatch("a merge names exactly one tree, first")) + } + } + } + if ids.len() < 2 { + return Err(input_mismatch("a merge names at least two revisions")); + } + if ids.windows(2).any(|w| w[0] >= w[1]) { + return Err(input_mismatch( + "merge revisions must be in the canonical merge order (strictly ascending ChangesetId)", + )); + } + require_tree(trees, *base, "merge base tree")?; + let mut sources = Vec::with_capacity(ids.len()); + for id in &ids { + sources.push(resolve(*id)?); + } + for (id, s) in ids.iter().zip(&sources) { + if s.base_tree != *base { + return Err(recompute_mismatch(format!( + "revision {id} is based on {}, not on the merge base {base}", + s.base_tree + ))); + } + } + for i in 0..sources.len() { + let a: Vec<&str> = sources[i] + .mutations + .iter() + .map(|m| m.path.as_str()) + .collect(); + for s in &sources[i + 1..] { + let b: Vec<&str> = s.mutations.iter().map(|m| m.path.as_str()).collect(); + if let Some((x, y)) = first_collision(&a, &b) { + return Err(recompute_mismatch(format!( + "tier T0 merge conflicts: {x} collides with {y}" + ))); + } + } + } + let mut mutations: Vec = sources + .iter() + .flat_map(|s| s.mutations.iter().cloned()) + .collect(); + mutations.sort_by(|a, b| a.path.cmp(&b.path)); + let content = RevisionContent { + change_id: merge_change_id(*base, &ids), + base_tree: *base, + parents: ids.clone(), + mutations, + intent_summary: format!("merge tier T0 of {} revisions", ids.len()), + }; + content.validate()?; + let tree = trees.apply_mutations(*base, &content.mutations)?; + Ok((content, tree)) + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{BlobDigest, FileMode, MutationOp}; + + fn repo() -> RepoId { + RepoId::new("aien-spark/synapse").unwrap() + } + + fn server() -> SigningKey { + let seed: [u8; 32] = Sha256::digest(b"b5 unit server key").into(); + SigningKey::from_bytes(&seed) + } + + fn attestation() -> DerivationAttestation { + DerivationAttestation::sign( + &server(), + repo(), + DerivationRule::Merge { + tier: MergeTier::T0Path, + }, + vec![ + DerivationInput::Tree(TreeDigest([0x5A; 32])), + DerivationInput::Revision(ChangesetId([1; 32])), + DerivationInput::Revision(ChangesetId([2; 32])), + ], + ChangesetId([3; 32]), + TreeDigest([4; 32]), + ) + } + + #[test] + fn b5_attestation_round_trips_and_refuses_malformed_bytes() { + let att = attestation(); + att.verify().unwrap(); + let bytes = att.encode(); + assert_eq!(DerivationAttestation::decode(&bytes).unwrap(), att); + for cut in 0..bytes.len() { + assert_eq!( + DerivationAttestation::decode(&bytes[..cut]) + .unwrap_err() + .code, + RefusalCode::EnvelopeMalformed, + "cut {cut}" + ); + } + let mut trailing = bytes.clone(); + trailing.push(0); + assert!(DerivationAttestation::decode(&trailing).is_err()); + // The rule tag follows `u32 len | repo`; tag 3 (derived-file action) is reserved. + let rule_at = 4 + repo().as_str().len(); + let mut reserved = bytes.clone(); + reserved[rule_at] = 3; + assert_eq!( + DerivationAttestation::decode(&reserved).unwrap_err().code, + RefusalCode::EnvelopeMalformed + ); + let mut tier = bytes.clone(); + tier[rule_at + 1] = 1; + assert!(DerivationAttestation::decode(&tier).is_err()); + let mut zero = bytes.clone(); + zero[rule_at + 2..rule_at + 6].copy_from_slice(&0u32.to_le_bytes()); + assert!(DerivationAttestation::decode(&zero).is_err()); + let mut huge = bytes; + huge[rule_at + 2..rule_at + 6].copy_from_slice(&u32::MAX.to_le_bytes()); + assert!(DerivationAttestation::decode(&huge).is_err()); + } + + #[test] + fn b5_attestation_signature_binds_every_field() { + let att = attestation(); + let mut t = att.clone(); + t.output_tree = TreeDigest([9; 32]); + assert_eq!( + t.verify().unwrap_err().code, + RefusalCode::DerivationSignatureInvalid + ); + let mut t = att.clone(); + t.rule = DerivationRule::Rebase; + assert_eq!( + t.verify().unwrap_err().code, + RefusalCode::DerivationSignatureInvalid + ); + let mut t = att.clone(); + t.inputs.pop(); + assert_eq!( + t.verify().unwrap_err().code, + RefusalCode::DerivationSignatureInvalid + ); + let mut t = att.clone(); + t.repo_id = RepoId::new("aien-spark/other").unwrap(); + assert_eq!( + t.verify().unwrap_err().code, + RefusalCode::DerivationSignatureInvalid + ); + assert_ne!(att.digest(), t.digest()); + } + + #[test] + fn b5_server_witness_round_trips_and_is_not_an_agent() { + let content = RevisionContent { + change_id: ChangeId([7; 16]), + base_tree: TreeDigest([0x5A; 32]), + parents: vec![], + mutations: vec![PathMutation { + path: "src/lib.rs".into(), + op: MutationOp::Upsert { + mode: FileMode::Regular644, + blob_digest: BlobDigest::compute(b"x"), + size_bytes: 1, + }, + }], + intent_summary: "derived".into(), + }; + let attestation = DerivationAttestation::sign( + &server(), + repo(), + DerivationRule::Rebase, + vec![ + DerivationInput::Revision(ChangesetId([1; 32])), + DerivationInput::Tree(TreeDigest([0x5A; 32])), + ], + content.changeset_id(), + TreeDigest([4; 32]), + ); + let derived = DerivedRevision { + content, + attestation, + }; + derived.validate().unwrap(); + assert_eq!(DerivedRevision::decode(&derived.encode()).unwrap(), derived); + let chain = ChainPath::new(vec![[1; 32]]).unwrap(); + let w = AdmissionWitness::of_derivation(&derived, chain, WalSeq(3), 9); + assert_eq!(AdmissionWitness::decode(&w.encode()).unwrap(), w); + assert_eq!(w.signer_did(), derived.attestation.server_did()); + assert!( + matches!(w.signer, WitnessSigner::Server { attestation_digest, .. } + if attestation_digest == derived.attestation.digest()) + ); + } + + #[test] + fn b5_path_collision_is_equal_or_below() { + assert!(paths_collide("a", "a")); + assert!(paths_collide("a", "a/b")); + assert!(paths_collide("a/b/c", "a/b")); + assert!(!paths_collide("a", "ab")); + assert!(!paths_collide("a/b", "a/c")); + } +} diff --git a/crates/synapse-core/src/lib.rs b/crates/synapse-core/src/lib.rs index cc43a11..6a6d8f7 100644 --- a/crates/synapse-core/src/lib.rs +++ b/crates/synapse-core/src/lib.rs @@ -8,9 +8,16 @@ use sha1::Sha1; use sha2::{Digest, Sha256}; use std::fmt; +mod derivation; mod revision; mod revision_state; mod tree; +pub use derivation::{ + derive_revision_output, DerivationAttestation, DerivationInput, DerivationRule, + DerivationTrees, DerivedRevision, MergeTier, ServerKeyRegistry, + DOMAIN_DERIVATION_ATTESTATION_V1, DOMAIN_DERIVATION_SIGN_V1, DOMAIN_DERIVED_MERGE_CHANGE_V1, + MAX_DERIVATION_INPUTS, +}; pub use revision::{ AdmissionWitness, AuthorshipAttestation, ChainPath, ChangesetEnvelopeV2, ObsolescenceKind, ObsolescenceMarker, RevisionContent, WitnessSigner, DOMAIN_ADMISSION_WITNESS_V1, @@ -143,6 +150,23 @@ pub enum RefusalCode { /// or whose mover key is not the audience of its chain's leaf link: the log was written /// without the mover's private key (ADR 0003 sections 5.3 and 5.4, step B4, issue #89). RevisionStateMoveUnverified, + /// A `DerivationAttestation` does not name the revision it is presented with, or its + /// signature does not verify under the server key it names (ADR 0003 section 5.1, step B5). + DerivationSignatureInvalid, + /// The server key a `DerivationAttestation` names is not the server key of the repository + /// identity document in effect at the admission `WalSeq`, or no document is in effect + /// (step B5). + DerivationServerKeyUnregistered, + /// A `DerivationAttestation` names inputs that do not fit its rule (kind, count, order, + /// duplicates) or that the replica does not hold: a revision not admitted in this + /// repository before the derivation, or a tree not in the tree store (step B5). + DerivationInputMismatch, + /// Recomputing the rule a `DerivationAttestation` names from the inputs it names fails, or + /// gives a `ChangesetId` or `TreeDigest` other than the ones it attests (step B5). + DerivationRecomputeMismatch, + /// A `DerivationAttestation` already admitted (the same attestation digest) is presented + /// again (step B5). + DerivationAttestationReplayed, // Git and Radicle canonicality refusals GitObjectCorrupt, diff --git a/crates/synapse-core/src/revision.rs b/crates/synapse-core/src/revision.rs index b223201..0e257a6 100644 --- a/crates/synapse-core/src/revision.rs +++ b/crates/synapse-core/src/revision.rs @@ -54,21 +54,28 @@ const MAX_PATH_BYTES: usize = 2048; const MAX_REPO_ID_BYTES: usize = 128; /// Encoded size of the smallest mutation (`u32` empty path and a delete tag). const MIN_MUTATION_BYTES: usize = 4 + 1; -/// Witness signer tag of an agent admission (B5 adds the server-derived signer as tag 2). +/// Witness signer tag of an agent admission. const SIGNER_TAG_AGENT: u8 = 1; +/// Witness signer tag of a server-derived admission (step B5). +const SIGNER_TAG_SERVER: u8 = 2; const OP_TAG_UPSERT: u8 = 1; const OP_TAG_DELETE: u8 = 2; -fn malformed(msg: impl Into) -> SynapseError { +pub(crate) fn malformed(msg: impl Into) -> SynapseError { SynapseError::new(RefusalCode::EnvelopeMalformed, msg) } -fn put_str(buf: &mut Vec, s: &str) { +pub(crate) fn put_str(buf: &mut Vec, s: &str) { buf.extend_from_slice(&(s.len() as u32).to_le_bytes()); buf.extend_from_slice(s.as_bytes()); } -fn verify_ed25519(key: &[u8; 32], msg: &[u8], sig: &[u8; 64], what: &str) -> SynapseResult<()> { +pub(crate) fn verify_ed25519( + key: &[u8; 32], + msg: &[u8], + sig: &[u8; 64], + what: &str, +) -> SynapseResult<()> { let vk = VerifyingKey::from_bytes(key).map_err(|_| { SynapseError::new( RefusalCode::DidKeyInvalid, @@ -155,7 +162,7 @@ impl RevisionContent { Ok(content) } - fn decode_from(r: &mut Reader) -> SynapseResult { + pub(crate) fn decode_from(r: &mut Reader) -> SynapseResult { let version = r.u16()?; if version != ENVELOPE_V2_VERSION { return Err(SynapseError::new( @@ -461,8 +468,8 @@ impl ChainPath { } } -/// Who signed an admitted revision. Step B5 adds the server-derived signer (the server's -/// machine-key signature and its `DerivationAttestation` digest) under tag 2. +/// Who signed an admitted revision: an agent (tag 1, step B1) or, for a server-derived +/// revision, the server's machine key with its `DerivationAttestation` (tag 2, step B5). #[derive(Debug, Clone, PartialEq, Eq)] pub enum WitnessSigner { /// An agent's key and its signature over the envelope (its authorship attestation). @@ -470,6 +477,14 @@ pub enum WitnessSigner { author_key: [u8; 32], signature: [u8; 64], }, + /// The server's machine key, its signature over the revision's + /// [`crate::DerivationAttestation`], and that attestation's digest. A server-derived + /// revision never carries an agent signature (ADR 0003 sections 5.1 and 5.6). + Server { + server_key: [u8; 32], + signature: [u8; 64], + attestation_digest: [u8; 32], + }, } /// The immutable record of one admission of a revision (ADR 0003 section 5.1). Idempotency @@ -514,11 +529,13 @@ impl AdmissionWitness { pub fn signer_did(&self) -> String { match &self.signer { WitnessSigner::Agent { author_key, .. } => encode_did_key_ed25519(author_key), + WitnessSigner::Server { server_key, .. } => encode_did_key_ed25519(server_key), } } /// `repo_id str | changeset_id [32] | signer | idempotency_key [32] | admission_seq u64 | - /// admitted_at_ms u64 | chain`, with `signer` = `1 | author_key [32] | signature [64]`. + /// admitted_at_ms u64 | chain`, with `signer` = `1 | author_key [32] | signature [64]` + /// (agent) or `2 | server_key [32] | signature [64] | attestation_digest [32]` (server). pub fn encode(&self) -> Vec { let mut buf = Vec::with_capacity(256); put_str(&mut buf, self.repo_id.as_str()); @@ -532,6 +549,16 @@ impl AdmissionWitness { buf.extend_from_slice(author_key); buf.extend_from_slice(signature); } + WitnessSigner::Server { + server_key, + signature, + attestation_digest, + } => { + buf.push(SIGNER_TAG_SERVER); + buf.extend_from_slice(server_key); + buf.extend_from_slice(signature); + buf.extend_from_slice(attestation_digest); + } } buf.extend_from_slice(&self.idempotency_key.0); buf.extend_from_slice(&self.admission_seq.0.to_le_bytes()); @@ -550,6 +577,11 @@ impl AdmissionWitness { author_key: r.array()?, signature: r.array()?, }, + SIGNER_TAG_SERVER => WitnessSigner::Server { + server_key: r.array()?, + signature: r.array()?, + attestation_digest: r.array()?, + }, tag => return Err(malformed(format!("unknown witness signer tag {tag}"))), }; let w = Self { @@ -735,21 +767,21 @@ impl ObsolescenceMarker { // --------------------------------------------------------------------------------------- /// Bounds-checked little-endian reader; every failure is `EnvelopeMalformed`. -struct Reader<'a> { +pub(crate) struct Reader<'a> { buf: &'a [u8], pos: usize, } impl<'a> Reader<'a> { - fn new(buf: &'a [u8]) -> Self { + pub(crate) fn new(buf: &'a [u8]) -> Self { Self { buf, pos: 0 } } - fn remaining(&self) -> usize { + pub(crate) fn remaining(&self) -> usize { self.buf.len() - self.pos } - fn take(&mut self, n: usize) -> SynapseResult<&'a [u8]> { + pub(crate) fn take(&mut self, n: usize) -> SynapseResult<&'a [u8]> { if n > self.remaining() { return Err(malformed(format!( "truncated: need {n} bytes at offset {}, {} remain", @@ -762,29 +794,29 @@ impl<'a> Reader<'a> { Ok(out) } - fn array(&mut self) -> SynapseResult<[u8; N]> { + pub(crate) fn array(&mut self) -> SynapseResult<[u8; N]> { Ok(self.take(N)?.try_into().expect("N bytes")) } - fn u8(&mut self) -> SynapseResult { + pub(crate) fn u8(&mut self) -> SynapseResult { Ok(self.take(1)?[0]) } - fn u16(&mut self) -> SynapseResult { + pub(crate) fn u16(&mut self) -> SynapseResult { Ok(u16::from_le_bytes(self.array()?)) } - fn u32(&mut self) -> SynapseResult { + pub(crate) fn u32(&mut self) -> SynapseResult { Ok(u32::from_le_bytes(self.array()?)) } - fn u64(&mut self) -> SynapseResult { + pub(crate) fn u64(&mut self) -> SynapseResult { Ok(u64::from_le_bytes(self.array()?)) } /// A `u32` count, refused above `cap` or above what `min_item_bytes` per item could fit /// in the bytes that remain (so nothing is reserved beyond the input). - fn count(&mut self, cap: usize, min_item_bytes: usize) -> SynapseResult { + pub(crate) fn count(&mut self, cap: usize, min_item_bytes: usize) -> SynapseResult { let n = self.u32()? as usize; if n > cap || n.saturating_mul(min_item_bytes) > self.remaining() { return Err(malformed(format!( @@ -795,7 +827,7 @@ impl<'a> Reader<'a> { Ok(n) } - fn string(&mut self, cap: usize) -> SynapseResult { + pub(crate) fn string(&mut self, cap: usize) -> SynapseResult { let len = self.u32()? as usize; if len > cap { return Err(malformed(format!("string length {len} above cap {cap}"))); @@ -804,12 +836,12 @@ impl<'a> Reader<'a> { String::from_utf8(bytes.to_vec()).map_err(|_| malformed("string is not UTF-8")) } - fn repo(&mut self) -> SynapseResult { + pub(crate) fn repo(&mut self) -> SynapseResult { let s = self.string(MAX_REPO_ID_BYTES)?; RepoId::new(s).map_err(|e| malformed(format!("repository id: {}", e.message))) } - fn finish(&self) -> SynapseResult<()> { + pub(crate) fn finish(&self) -> SynapseResult<()> { if self.pos != self.buf.len() { return Err(malformed(format!("{} trailing bytes", self.remaining()))); } diff --git a/crates/synapse-radicle/src/identity.rs b/crates/synapse-radicle/src/identity.rs index baa9037..9ab868d 100644 --- a/crates/synapse-radicle/src/identity.rs +++ b/crates/synapse-radicle/src/identity.rs @@ -621,3 +621,12 @@ impl<'a> Reader<'a> { Ok(()) } } + +/// The server key a derivation attestation must name is the `server_key` of the document in +/// effect at the admission `WalSeq` (ADR 0003 step B5): a later rotation never invalidates a +/// derivation admitted before it, and a key rotated out refuses every later one. +impl synapse_core::ServerKeyRegistry for IdentityLog { + fn registered_server_key(&self, at: WalSeq) -> Option<[u8; 32]> { + self.server_key_at(at) + } +} diff --git a/crates/synapse-store/src/codec.rs b/crates/synapse-store/src/codec.rs index c63e2dd..74247ca 100644 --- a/crates/synapse-store/src/codec.rs +++ b/crates/synapse-store/src/codec.rs @@ -355,6 +355,15 @@ pub fn encode_record(record: &WalRecord) -> SynapseResult> { w.raw(&m.mover_key); w.raw(&m.signature); } + WalRecord::DerivedRevisionAdmitted { + derived, + chain, + admitted_at_ms, + } => { + w.bytes(&derived.encode(), "derived revision")?; + put_chain(&mut w, chain)?; + w.u64(*admitted_at_ms); + } } Ok(w.0) } @@ -772,6 +781,11 @@ pub fn decode_record(bytes: &[u8], cap: u64) -> Result moved_at_ms, } } + 11 => WalRecord::DerivedRevisionAdmitted { + derived: r.embedded("derived revision", DerivedRevision::decode)?, + chain: r.embedded("chain path", ChainPath::decode)?, + admitted_at_ms: r.u64()?, + }, tag => { return Err(CodecRefusal::UnknownTag { at, @@ -1130,7 +1144,7 @@ impl CheckpointState { let tag_at = r.pos + 4 + 1; let bytes = r.bytes()?; let record = decode_record(&bytes, r.cap)?; - if !matches!(record.kind_byte(), 7..=9) { + if !matches!(record.kind_byte(), 7..=9 | 11) { return Err(CodecRefusal::UnknownTag { at: tag_at, field: "revision record kind", diff --git a/crates/synapse-store/src/lib.rs b/crates/synapse-store/src/lib.rs index 2f2cdf6..08411db 100644 --- a/crates/synapse-store/src/lib.rs +++ b/crates/synapse-store/src/lib.rs @@ -21,9 +21,10 @@ use std::io::{Read, Seek, SeekFrom, Write}; use std::path::{Path, PathBuf}; pub use synapse_auth::{SignedStateMove, StateMoveFault}; use synapse_core::{ - BlobDigest, ChainPath, ChangesetEnvelope, ChangesetEnvelopeV2, ChangesetId, EvidenceAttachment, - GitHubPullRequestProjection, IdempotencyKey, MutationOp, ObsolescenceMarker, - RadicleCanonicalHead, RefusalCode, RepoId, RevisionState, SynapseError, SynapseResult, WalSeq, + BlobDigest, ChainPath, ChangesetEnvelope, ChangesetEnvelopeV2, ChangesetId, DerivedRevision, + EvidenceAttachment, GitHubPullRequestProjection, IdempotencyKey, MutationOp, + ObsolescenceMarker, RadicleCanonicalHead, RefusalCode, RepoId, RevisionState, SynapseError, + SynapseResult, WalSeq, }; #[cfg(test)] @@ -40,8 +41,8 @@ pub mod wal2; pub use codec::{CheckpointChain, CheckpointState, CodecRefusal, RecordCodec}; pub use revision::{ - AdmissionAuthority, ChangeStatus, RecordedMarker, RevisionOutcome, StateMoveReplayReport, - StoredRevision, DOMAIN_STATE_ROOT_REVISIONS_V1, + verify_revision_log, AdmissionAuthority, ChangeStatus, RecordedMarker, RevisionOutcome, + StateMoveReplayReport, StoredRevision, DOMAIN_STATE_ROOT_REVISIONS_V1, }; pub use shared::{GroupCommitStats, SharedStore}; @@ -332,6 +333,15 @@ pub enum WalRecord { state_move: SignedStateMove, moved_at_ms: u64, }, + /// Admission of a server-derived revision under `chain` at server time `admitted_at_ms` + /// (ADR 0003 B5). It references only blobs already visible, so it carries none. Binary + /// codec only. + #[serde(skip)] + DerivedRevisionAdmitted { + derived: DerivedRevision, + chain: ChainPath, + admitted_at_ms: u64, + }, } impl WalRecord { @@ -346,6 +356,7 @@ impl WalRecord { Self::RevisionAdmitted { .. } => 7, Self::ObsolescenceRecorded { .. } => 8, Self::RevisionStateMoved { .. } => 9, + Self::DerivedRevisionAdmitted { .. } => 11, } } @@ -354,6 +365,7 @@ impl WalRecord { let mutations = match self { Self::ChangesetIngest { envelope, .. } => &envelope.mutations, Self::RevisionAdmitted { envelope, .. } => &envelope.content.mutations, + Self::DerivedRevisionAdmitted { derived, .. } => &derived.content.mutations, _ => return Vec::new(), }; mutations @@ -2156,6 +2168,12 @@ impl SynapseStore { } record @ (WalRecord::ObsolescenceRecorded { .. } | WalRecord::RevisionStateMoved { .. }) => self.revisions.apply(seq, record), + record @ WalRecord::DerivedRevisionAdmitted { .. } => { + for digest in record.upsert_blobs() { + self.blob_first_visible_seq.entry(digest).or_insert(seq); + } + self.revisions.apply(seq, record); + } } } diff --git a/crates/synapse-store/src/revision.rs b/crates/synapse-store/src/revision.rs index 7ca15bd..3dcb3cc 100644 --- a/crates/synapse-store/src/revision.rs +++ b/crates/synapse-store/src/revision.rs @@ -13,9 +13,10 @@ use crate::{SignedStateMove, StateMoveFault, WalRecord}; use sha2::{Digest, Sha256}; use std::collections::{BTreeMap, BTreeSet}; use synapse_core::{ - AdmissionWitness, AuthorshipAttestation, BlobDigest, ChainPath, ChangeId, ChangesetEnvelopeV2, - ChangesetId, IdempotencyKey, MutationOp, ObsolescenceKind, ObsolescenceMarker, RefusalCode, - RepoId, RevisionContent, RevisionState, SynapseError, SynapseResult, WalSeq, + derive_revision_output, AdmissionWitness, AuthorshipAttestation, BlobDigest, ChainPath, + ChangeId, ChangesetEnvelopeV2, ChangesetId, DerivationAttestation, DerivationTrees, + DerivedRevision, IdempotencyKey, MutationOp, ObsolescenceKind, ObsolescenceMarker, RefusalCode, + RepoId, RevisionContent, RevisionState, ServerKeyRegistry, SynapseError, SynapseResult, WalSeq, }; /// Domain tag of the revision part of the state root (only hashed when revisions exist). @@ -32,8 +33,9 @@ pub struct AdmissionAuthority { pub change_scope: Vec, } -/// One admitted revision: its content, every authorship attestation, and every admission -/// witness, in admission order. +/// One admitted revision: its content, every authorship attestation (agents), every +/// derivation attestation (the server, step B5), and every admission witness, in admission +/// order. A revision only the server derived has no authorship attestation. #[derive(Debug, Clone, PartialEq, Eq)] pub struct StoredRevision { pub repo_id: RepoId, @@ -42,6 +44,7 @@ pub struct StoredRevision { /// Sequence of the first admission. pub first_seq: WalSeq, pub attestations: Vec, + pub derivations: Vec, pub witnesses: Vec, /// Current state (step B4): `Private` from the first admission; it only moves forward. pub state: RevisionState, @@ -141,6 +144,8 @@ pub(crate) struct RevisionLedger { idempotency: BTreeMap<(RepoId, [u8; 32], IdempotencyKey), (WalSeq, ChangesetId)>, /// Kind 9 records that changed nothing, by reason. state_moves: StateMoveReplayReport, + /// (repository, derivation attestation digest) to its admission (replay refusal, B5). + derivations: BTreeMap<(RepoId, [u8; 32]), WalSeq>, } /// Digest of one revision record over its canonical core encodings. @@ -196,6 +201,18 @@ fn record_digest(record: &WalRecord) -> [u8; 32] { h.update(m.mover_key); h.update(m.signature); } + WalRecord::DerivedRevisionAdmitted { + derived, + chain: c, + admitted_at_ms, + } => { + let d = derived.encode(); + h.update((d.len() as u64).to_le_bytes()); + h.update(&d); + c.encode_into(&mut chain); + h.update(&chain); + h.update(admitted_at_ms.to_le_bytes()); + } _ => {} } h.finalize().into() @@ -324,12 +341,52 @@ impl RevisionLedger { content: envelope.content.clone(), first_seq: seq, attestations: Vec::new(), + derivations: Vec::new(), witnesses: Vec::new(), state: RevisionState::Private, }); rev.attestations.push(att.clone()); rev.witnesses.push(witness); } + WalRecord::DerivedRevisionAdmitted { + derived, + chain, + admitted_at_ms, + } => { + let att = &derived.attestation; + let id = att.output_changeset; + let repo = att.repo_id.clone(); + let witness = + AdmissionWitness::of_derivation(derived, chain.clone(), seq, *admitted_at_ms); + let entry = self + .changes + .entry((repo.clone(), derived.content.change_id)) + .or_default(); + if entry.creating_chain.is_none() { + entry.creating_chain = Some(chain.clone()); + } + if !entry.revisions.contains(&id) { + entry.revisions.push(id); + } + self.derivations + .entry((repo.clone(), att.digest())) + .or_insert(seq); + let rev = + self.revisions + .entry((repo.clone(), id)) + .or_insert_with(|| StoredRevision { + repo_id: repo, + changeset_id: id, + content: derived.content.clone(), + first_seq: seq, + attestations: Vec::new(), + derivations: Vec::new(), + witnesses: Vec::new(), + state: RevisionState::Private, + }); + rev.derivations.push(att.clone()); + rev.witnesses.push(witness); + } WalRecord::ObsolescenceRecorded { marker, chain, @@ -474,6 +531,63 @@ impl RevisionLedger { )) } + /// Checks of a derived revision at admission `WalSeq` `at` (ADR 0003 B5), shared by + /// admission and replay verification so both refuse exactly the same records. In order: + /// content rules, the attestation names this content and its signature verifies under the + /// server key it names (`DerivationSignatureInvalid`); that key is the identity document's + /// server key in effect at `at` (`DerivationServerKeyUnregistered`); the attestation was + /// not admitted before (`DerivationAttestationReplayed`); the inputs fit the rule and are + /// held (`DerivationInputMismatch`); recomputing the rule on them gives the attested + /// `ChangesetId` and `TreeDigest` (`DerivationRecomputeMismatch`). + pub(crate) fn check_derivation( + &self, + derived: &DerivedRevision, + at: WalSeq, + keys: &dyn ServerKeyRegistry, + trees: &mut dyn DerivationTrees, + ) -> SynapseResult { + let id = derived.validate()?; + let att = &derived.attestation; + let registered = keys.registered_server_key(at); + if registered != Some(att.server_key) { + return Err(SynapseError::new( + RefusalCode::DerivationServerKeyUnregistered, + match registered { + Some(_) => format!( + "server key {} is not the server key of the identity document in effect at {at}", + att.server_did() + ), + None => format!("no identity document is in effect at {at}"), + }, + )); + } + let repo = att.repo_id.clone(); + let digest = att.digest(); + if let Some(first) = self.derivations.get(&(repo.clone(), digest)) { + return Err(SynapseError::new( + RefusalCode::DerivationAttestationReplayed, + format!( + "derivation attestation {} was already admitted at {first}", + hex::encode(digest) + ), + )); + } + let lookup = + |input: ChangesetId| self.get_revision(&repo, input).map(|r| r.content.clone()); + let (content, tree) = derive_revision_output(att.rule, &att.inputs, &lookup, trees)?; + let recomputed = content.changeset_id(); + if recomputed != att.output_changeset || tree != att.output_tree { + return Err(SynapseError::new( + RefusalCode::DerivationRecomputeMismatch, + format!( + "recomputed {:?} on the named inputs gives revision {recomputed} tree {tree}, the attestation names revision {} tree {}", + att.rule, att.output_changeset, att.output_tree + ), + )); + } + Ok(id) + } + /// Checks of an obsolescence marker against the ledger. `Ok(Some(seq))` when the same /// predecessor and successors are already recorded (the first marker's sequence). pub(crate) fn plan_marker( @@ -606,6 +720,61 @@ impl RevisionLedger { } } +/// Replica verification of revision records (ADR 0003 B5): replay `records` in `WalSeq` +/// order into a fresh ledger and refuse the first record that could not have been admitted +/// on its own evidence. An agent revision (kind 7) must carry a strictly verifying agent +/// signature over its own content: a derived revision presented with an agent signature it +/// does not have is refused (`AuthSignatureInvalid`). A marker (kind 8) must verify. A derived +/// revision (kind 11) must pass the admission checks of its derivation at its own `WalSeq` +/// (signature, server key registered then, not a replay, inputs admitted before it, the same +/// digests on recomputation). The refusal keeps its code and names the record's `WalSeq`. +/// Returns the number of records verified. Authorization (chains, join rule) and blobs are +/// not re-checked here. +pub fn verify_revision_log( + records: &[(WalSeq, WalRecord)], + keys: &dyn ServerKeyRegistry, + trees: &mut dyn DerivationTrees, +) -> SynapseResult { + let mut ledger = RevisionLedger::default(); + let mut prev: Option = None; + for (seq, record) in records { + let at_seq = |e: SynapseError| { + SynapseError::new(e.code, format!("revision record at {seq}: {}", e.message)) + }; + if prev.is_some_and(|p| p >= *seq) { + return Err(SynapseError::new( + RefusalCode::WalSequenceGap, + format!("revision record at {seq} does not follow the previous record"), + )); + } + prev = Some(*seq); + match record { + WalRecord::RevisionAdmitted { envelope, .. } => { + envelope.validate().map_err(at_seq)?; + } + WalRecord::ObsolescenceRecorded { marker, .. } => { + marker.validate().map_err(at_seq)?; + } + WalRecord::DerivedRevisionAdmitted { derived, .. } => { + ledger + .check_derivation(derived, *seq, keys, trees) + .map_err(at_seq)?; + } + other => { + return Err(SynapseError::new( + RefusalCode::WalRecordMalformed, + format!( + "record of kind {} at {seq} is not a revision record", + other.kind_byte() + ), + )) + } + } + ledger.apply(*seq, record.clone()); + } + Ok(records.len()) +} + impl crate::SynapseStore { /// Admit an envelope v2 revision under `authority` at server time `now_ms` (ADR 0003 /// B1). Checks, in order: the envelope (content rules, attestation names this content, @@ -659,29 +828,7 @@ impl crate::SynapseStore { } self.revisions .check_join(&repo, content.change_id, &authority)?; - for parent in &content.parents { - // Another owner's `Private` revision is not a parent this chain can name (B4). - let parent_repo = if self - .revisions - .get_visible(&repo, *parent, &authority.chain) - .is_some() - { - &repo - } else if let Some(cs) = self.changesets.get(parent) { - &cs.envelope.repo_id - } else { - return Err(SynapseError::new( - RefusalCode::ParentChangesetNotFound, - format!("parent {parent} not found"), - )); - }; - if parent_repo != &repo { - return Err(SynapseError::new( - RefusalCode::AuthCrossRepoDenied, - "parent changeset belongs to a different repository", - )); - } - } + self.check_revision_parents(&repo, content, &authority.chain)?; let mut provided: BTreeMap = BTreeMap::new(); let mut total = 0u64; for (declared, bytes) in blobs { @@ -750,6 +897,117 @@ impl crate::SynapseStore { }) } + /// Parents of a revision: each an admitted revision or a v1 changeset of `repo`. + fn check_revision_parents( + &self, + repo: &RepoId, + content: &RevisionContent, + viewer: &ChainPath, + ) -> SynapseResult<()> { + for parent in &content.parents { + // Another owner's `Private` revision is not a parent this chain can name (B4). + let parent_repo = if self.revisions.get_visible(repo, *parent, viewer).is_some() { + repo + } else if let Some(cs) = self.changesets.get(parent) { + &cs.envelope.repo_id + } else { + return Err(SynapseError::new( + RefusalCode::ParentChangesetNotFound, + format!("parent {parent} not found"), + )); + }; + if parent_repo != repo { + return Err(SynapseError::new( + RefusalCode::AuthCrossRepoDenied, + "parent changeset belongs to a different repository", + )); + } + } + Ok(()) + } + + /// Admit a server-derived revision (ADR 0003 B5) under `authority` at server time + /// `now_ms`. `keys` answers which server key the repository identity document registered + /// at the admission `WalSeq`; `trees` is the tree store the rule is recomputed on. Checks, + /// in order: the derivation (see `RevisionLedger::check_derivation`: signature, registered + /// key, replay, inputs, recomputation); the path-count limit; the join rule against the + /// change's creating chain (`AuthChangeOutOfScope`); parents; every upserted blob already + /// visible (`BlobNotFound`: a derived revision brings no new content). Nothing is written + /// on a refusal. The witness records the server key, its signature, and the attestation + /// digest; no agent signature is recorded or claimed. + pub fn admit_derived_revision( + &mut self, + derived: DerivedRevision, + authority: AdmissionAuthority, + keys: &dyn ServerKeyRegistry, + trees: &mut dyn DerivationTrees, + now_ms: u64, + ) -> SynapseResult { + self.check_writable()?; + self.check_binary_codec()?; + let at = self.committed_seq().next(); + let id = self.revisions.check_derivation(&derived, at, keys, trees)?; + let content = &derived.content; + let repo = derived.attestation.repo_id.clone(); + if content.mutations.len() > self.limits.max_paths_per_changeset { + return Err(SynapseError::new( + RefusalCode::QuotaTooManyPaths, + format!( + "revision touches {} paths, exceeding limit {}", + content.mutations.len(), + self.limits.max_paths_per_changeset + ), + )); + } + self.revisions + .check_join(&repo, content.change_id, &authority)?; + self.check_revision_parents(&repo, content, &authority.chain)?; + for m in &content.mutations { + if let MutationOp::Upsert { blob_digest, .. } = &m.op { + if !self.blob_first_visible_seq.contains_key(blob_digest) { + return Err(SynapseError::new( + RefusalCode::BlobNotFound, + format!( + "derived mutation path {} references blob {blob_digest}, which is not visible", + m.path + ), + )); + } + } + } + let joined_existing_revision = self.revisions.get_revision(&repo, id).is_some(); + let record = WalRecord::DerivedRevisionAdmitted { + derived, + chain: authority.chain, + admitted_at_ms: now_ms, + }; + let wal_seq = self.append_revision_record(record, &[])?; + debug_assert_eq!( + wal_seq, at, + "derivation checked at the sequence it was written at" + ); + Ok(RevisionOutcome::Admitted { + wal_seq, + changeset_id: id, + joined_existing_revision, + }) + } + + /// Every revision record (kinds 7, 8 and 11) this store holds, in `WalSeq` order: what a + /// replica replays and verifies with [`verify_revision_log`]. + pub fn revision_records(&self) -> &[(WalSeq, WalRecord)] { + self.revisions.log() + } + + /// [`verify_revision_log`] over this store's revision records. + pub fn verify_revisions( + &self, + keys: &dyn ServerKeyRegistry, + trees: &mut dyn DerivationTrees, + ) -> SynapseResult { + verify_revision_log(self.revisions.log(), keys, trees) + } + /// Record an obsolescence marker authorized under `chain` at server time `now_ms`. A /// prune needs a chain that is or dominates the change's creating chain; a rewrite or a /// split needs that, or a chain that is or dominates the chain of the predecessor's first diff --git a/crates/synapse-store/tests/a1_malformed_corpus.rs b/crates/synapse-store/tests/a1_malformed_corpus.rs index 3cb1154..c90fbcd 100644 --- a/crates/synapse-store/tests/a1_malformed_corpus.rs +++ b/crates/synapse-store/tests/a1_malformed_corpus.rs @@ -156,8 +156,10 @@ fn length_fields(record: &WalRecord, bin: &[u8]) -> Vec { // repo_id length first. WalRecord::GitProjected { .. } | WalRecord::CanonicalPromoted { .. } => vec![2], WalRecord::LeaseUpdated { .. } => vec![], - // Embedded envelope v2 or marker length first (ADR 0003 B1). - WalRecord::RevisionAdmitted { .. } | WalRecord::ObsolescenceRecorded { .. } => vec![2], + // Embedded envelope v2, marker, or derived revision length first (ADR 0003 B1, B5). + WalRecord::RevisionAdmitted { .. } + | WalRecord::ObsolescenceRecorded { .. } + | WalRecord::DerivedRevisionAdmitted { .. } => vec![2], // repo_id length first (ADR 0003 B4). WalRecord::RevisionStateMoved { .. } => vec![2], } diff --git a/crates/synapse-store/tests/b5_derived_record.rs b/crates/synapse-store/tests/b5_derived_record.rs new file mode 100644 index 0000000..fb8bc24 --- /dev/null +++ b/crates/synapse-store/tests/b5_derived_record.rs @@ -0,0 +1,102 @@ +//! ADR 0003 step B5 (issue #29): the `DerivedRevisionAdmitted` WAL record (kind 11) round +//! trips through the binary codec and malformed bytes are refused typed. Admission, replay +//! verification and recomputation are tested through `synapse-api` +//! (`tests/b5_derivation_attestation.rs`), which holds the tree store. + +use ed25519_dalek::SigningKey; +use sha2::{Digest, Sha256}; +use synapse_core::{ + BlobDigest, ChainPath, ChangeId, ChangesetId, DerivationAttestation, DerivationInput, + DerivationRule, DerivedRevision, FileMode, MergeTier, MutationOp, PathMutation, RepoId, + RevisionContent, TreeDigest, +}; +use synapse_store::codec::{decode_record, encode_record}; +use synapse_store::WalRecord; + +/// 32 bytes derived from a label (no literal key material). +fn label(s: &str) -> [u8; 32] { + Sha256::digest(format!("synapse b5 store test: {s}").as_bytes()).into() +} + +fn derived(rule: DerivationRule, inputs: Vec) -> DerivedRevision { + let mut change = [0u8; 16]; + change.copy_from_slice(&label("change")[..16]); + let content = RevisionContent { + change_id: ChangeId(change), + base_tree: TreeDigest(label("base")), + parents: vec![], + mutations: vec![PathMutation { + path: "src/lib.rs".into(), + op: MutationOp::Upsert { + mode: FileMode::Regular644, + blob_digest: BlobDigest::compute(b"x"), + size_bytes: 1, + }, + }], + intent_summary: "derived".into(), + }; + let attestation = DerivationAttestation::sign( + &SigningKey::from_bytes(&label("server")), + RepoId::new("aien-spark/synapse").unwrap(), + rule, + inputs, + content.changeset_id(), + TreeDigest(label("output")), + ); + DerivedRevision { + content, + attestation, + } +} + +#[test] +fn b5_derived_revision_records_round_trip_and_malformed_bytes_are_refused_typed() { + let a = ChangesetId(label("a")); + let b = ChangesetId(label("b")); + let records = [ + derived( + DerivationRule::Rebase, + vec![ + DerivationInput::Revision(a), + DerivationInput::Tree(TreeDigest(label("onto"))), + ], + ), + derived( + DerivationRule::Merge { + tier: MergeTier::T0Path, + }, + vec![ + DerivationInput::Tree(TreeDigest(label("base"))), + DerivationInput::Revision(a), + DerivationInput::Revision(b), + ], + ), + ] + .map(|derived| WalRecord::DerivedRevisionAdmitted { + derived, + chain: ChainPath::new(vec![label("chain")]).unwrap(), + admitted_at_ms: 7, + }); + for record in records { + assert_eq!(record.kind_byte(), 11); + let bytes = encode_record(&record).unwrap(); + assert_eq!(decode_record(&bytes, 1 << 20).unwrap(), record); + for cut in 0..bytes.len() { + assert!(decode_record(&bytes[..cut], 1 << 20).is_err(), "cut {cut}"); + } + let mut longer = bytes.clone(); + longer.push(0); + assert!(decode_record(&longer, 1 << 20).is_err()); + // Flip each byte after the header: refused or decodes to a different record, never a + // panic. + for i in 2..bytes.len() { + let mut b = bytes.clone(); + b[i] ^= 0x41; + if let Ok(r) = decode_record(&b, 1 << 20) { + assert_ne!(r, record); + } + } + // No v1 JSON form. + assert!(serde_json::to_vec(&record).is_err()); + } +} From f4bdd195663d83713400e3c1479784adb94ce298 Mon Sep 17 00:00:00 2001 From: Drake Stapleton Date: Fri, 16 Oct 2026 21:22:35 -0500 Subject: [PATCH 2/5] docs(b5): derivation attestation doc and red/green evidence (#29) Co-Authored-By: Claude Opus 5.5 --- crates/synapse-core/src/lib.rs | 5 +- docs/B5_DERIVATION_ATTESTATION.md | 68 ++++++++++ evidence/b5-derivation-attestation/SHA256SUMS | 2 + .../red-green/green.txt | 23 ++++ .../red-green/red.txt | 126 ++++++++++++++++++ 5 files changed, 222 insertions(+), 2 deletions(-) create mode 100644 docs/B5_DERIVATION_ATTESTATION.md create mode 100644 evidence/b5-derivation-attestation/SHA256SUMS create mode 100644 evidence/b5-derivation-attestation/red-green/green.txt create mode 100644 evidence/b5-derivation-attestation/red-green/red.txt diff --git a/crates/synapse-core/src/lib.rs b/crates/synapse-core/src/lib.rs index 6a6d8f7..90c5544 100644 --- a/crates/synapse-core/src/lib.rs +++ b/crates/synapse-core/src/lib.rs @@ -80,8 +80,9 @@ pub enum RefusalCode { // Schema, path, and consistency refusals EnvelopeVersionUnsupported, - /// A changeset envelope v2, authorship attestation, admission witness, or obsolescence - /// marker is not in its one canonical binary encoding (ADR 0003 section 5.1, step B1). + /// A changeset envelope v2, authorship attestation, admission witness, obsolescence + /// marker, derivation attestation, or derived revision is not in its one canonical binary + /// encoding (ADR 0003 section 5.1, steps B1 and B5). EnvelopeMalformed, RepoIdInvalid, PathInvalid, diff --git a/docs/B5_DERIVATION_ATTESTATION.md b/docs/B5_DERIVATION_ATTESTATION.md new file mode 100644 index 0000000..ec9692f --- /dev/null +++ b/docs/B5_DERIVATION_ATTESTATION.md @@ -0,0 +1,68 @@ +# B5: DerivationAttestation for Server-Derived Revisions + +ADR 0003 section 9 step B5 (issue aien-dev/synapse#29), row 9. Sections 5.1 (`AdmissionWitness`, `DerivationAttestation`), 5.3 (lazy rebase), 5.5 (promotion merges) and 5.8 (every admitted mutation is signed): a revision the server produces rather than an agent carries a `DerivationAttestation` signed by the server machine key that the repository identity document (E0) registers as `server_key`. It names the inputs and the rule; every rule is deterministic, so a replica recomputes the output and refuses an attestation that does not match. No derived revision claims an agent signature it does not have. + +Code: `crates/synapse-core/src/derivation.rs` (types, codecs, the one recomputation `derive_revision_output`), `crates/synapse-core/src/revision.rs` (witness signer tag 2), `crates/synapse-store/src/revision.rs` (`check_derivation`, `admit_derived_revision`, `verify_revision_log`), `crates/synapse-store/src/{lib,codec}.rs` (WAL kind 11, replay, checkpoint, state root), `crates/synapse-radicle/src/identity.rs` (`IdentityLog` as `ServerKeyRegistry`), `crates/synapse-api/src/derivation.rs` (tree store as `DerivationTrees`, `derive_revision`, `admit_derived_revision`, `verify_revision_records`, `verify_revision_log`). Tests: `crates/synapse-api/tests/b5_derivation_attestation.rs`, `crates/synapse-store/tests/b5_derived_record.rs`, unit tests in `crates/synapse-core/src/derivation.rs`. Evidence: `evidence/b5-derivation-attestation/`. + +## 1. Model and invariants + +* **Rules.** `DerivationRule::Rebase` (path level) and `DerivationRule::Merge { tier: MergeTier::T0Path }` (the path-level merge tier; D1 adds T1). The derived-file action rule (`ActionDigest`) is reserved and not decodable yet (section 5). +* **Rebase.** Inputs exactly `[Revision(r), Tree(onto)]`. The output keeps `r`'s `ChangeId`, parents, mutations and intent, takes `onto` as base, and its tree is `r`'s mutations applied to `onto`. Refused when `onto` is already `r`'s base, or when a path `r` mutates is equal to, or an ancestor or descendant of, a path that differs between `r`'s base and `onto`. +* **Merge tier T0.** Inputs `[Tree(base), Revision(a1), ..., Revision(an)]`, n >= 2, revisions strictly ascending by `ChangesetId` (the canonical merge order). Every `ai` must be based on `base`, and no two may touch colliding paths (equal or one below the other). The output's parents are the `ai` in that order, its mutations are their union sorted by path, its intent is `merge tier T0 of {n} revisions`, and its `ChangeId` is the first 16 bytes of `SHA-256("SYNAPSE_DERIVED_MERGE_CHANGE_V1\0" || base || u32 n || a1 || ... || an)`, so the same merge always gets the same identity. +* **Attestation.** `DerivationAttestation` = repository, rule, inputs (1..=256), output `ChangesetId`, output `TreeDigest`, server key, Ed25519 signature (strict) over `"SYNAPSE_DERIVATION_SIGN_V1\0" || body`. Its digest is `SHA-256("SYNAPSE_DERIVATION_ATTESTATION_V1\0" || encoding)`. It carries no time, so a derivation is a pure function of its inputs and key, and a second presentation of one attestation is a replay. +* **Derived revision** = `RevisionContent` + `DerivationAttestation`; the attestation must name the content's `ChangesetId`. It carries no `AuthorshipAttestation`. The input revisions keep their own agent signatures. +* **Witness.** Admission records an `AdmissionWitness` with signer tag 2 (`WitnessSigner::Server`: server key, the attestation's signature, the attestation digest) instead of an agent signature; its idempotency key is the attestation digest. `StoredRevision.derivations` lists the attestations; `attestations` (agent) stays empty for a revision only the server produced. +* **One recomputation.** `derive_revision_output` is the only implementation of the rules. The server uses it to derive, admission uses it to check, and replay verification uses it to recompute, so the three cannot drift apart. +* **Server key registration.** `ServerKeyRegistry::registered_server_key(at)` returns the identity document's `server_key` in effect at `WalSeq` `at`; `IdentityLog` implements it with E0's `server_key_at`. An attestation is checked at the sequence of its own admission, so a rotation does not invalidate earlier derivations and an old key is refused after the rotation. + +## 2. Checks, in order + +At admission (`SynapseStore::admit_derived_revision`, sequence `at` = the next `WalSeq`) and at replay (`verify_revision_log`, sequence = the record's own): + +| Check | Refusal | +|---|---| +| Content rules; attestation names this content; input count 1..=256; server key is a valid Ed25519 point and the strict signature verifies | `DerivationSignatureInvalid` (count: `DerivationInputMismatch`) | +| Server key equals the identity document's `server_key` at the sequence | `DerivationServerKeyUnregistered` | +| Attestation digest not already admitted in this repository | `DerivationAttestationReplayed` | +| Inputs fit the rule's shape and order; every named revision is admitted; every named tree is held | `DerivationInputMismatch` | +| The rule applies (rebase target differs from the base, no path conflict, merge revisions share the base) and the recomputed `ChangesetId` and `TreeDigest` equal the attested ones | `DerivationRecomputeMismatch` | + +Admission then applies B1's checks: path-count limit, join rule under the asking or proposing chain (`AuthChangeOutOfScope`), parents (`ParentChangesetNotFound`), and every upserted blob already visible (`BlobNotFound`); nothing is written on any refusal. The API also refuses an attestation for another repository (`AuthCrossRepoDenied`). + +Replay verification walks the revision records in sequence order with a fresh ledger: kind 7 records are checked with `ChangesetEnvelopeV2::validate` (so a derived revision dressed in a borrowed agent attestation is `AuthSignatureInvalid`), kind 8 with `ObsolescenceMarker::validate`, kind 11 with the checks above; sequences must strictly ascend (`WalSequenceGap`) and any other kind is `WalRecordMalformed`. Refusals keep their code and prefix the message with the record's sequence. + +## 3. Canonical binary layout (principle P5) + +Conventions as in B1 (little-endian, `str` = `u32 len | UTF-8`, lengths checked before allocation, trailing bytes refused, core decoders refuse with `EnvelopeMalformed`). + +* Rule: `1` (rebase) or `2 | tier u8` (merge; tier `0` = T0). Tag 3 is reserved for the derived-file action. +* Input: `1 | changeset_id [32]` (revision) or `2 | tree_digest [32]` (tree). +* Attestation: `repo str | rule | u32 n (1..=256) | input*n | output_changeset [32] | output_tree [32] | server_key [32] | signature [64]` (signed bytes = domain tag + all but the signature). +* Derived revision: `u32 content_len | content | attestation`. +* Witness signer tag 2: `2 | server_key [32] | signature [64] | attestation_digest [32]`, in the B1 witness layout. +* WAL kind 11 `DerivedRevisionAdmitted`: `u32 len | derived revision | u32 len | chain | admitted_at_ms u64`. Binary only (no v1 JSON form), no inline blobs (every blob is already visible). Kinds 9 and 10 are taken by open PRs (B4 #88 and the Git bridge cut 2 of #48). +* Checkpoint v2 revision section and state root: as in B1, now holding kind 7, 8 and 11 records. The state root's record digest covers kind 11 records, so a checkpoint that lost one is `CheckpointCorrupt` on load (red case in the evidence). + +## 4. Acceptance + +| Acceptance (issue #29) | Test | +|---|---| +| A replica recomputes every derived revision from the inputs and rule its attestation names and gets the same digests | `b5_replica_recomputes_every_derived_revision_and_gets_the_same_digests` (rebase and T0 merge equal independently built trees; reopen from the WAL and after a checkpoint; recomputation on the replica is byte-identical) | +| An attestation naming different inputs is refused at admission and at replay | `b5_attestation_naming_different_inputs_is_refused_at_admission_and_replay` (another real revision, an unknown revision, an unknown tree) | +| An attestation naming a different rule is refused at admission and at replay | `b5_attestation_naming_a_different_rule_is_refused_at_admission_and_replay` | +| An attestation by an unregistered server key is refused at admission and at replay | `b5_unregistered_server_key_is_refused_at_admission_and_replay` (a rogue key, a delegate's key, the old key after a rotation; the earlier derivation still verifies) | +| A derived revision presented with an agent signature it does not have is refused | `b5_derived_revision_presented_with_an_agent_signature_it_does_not_have_is_refused` (the input's attestation as is and re-pointed, at admission and as a replayed kind 7 record) | + +Also: `b5_attestation_signed_by_another_key_is_refused_at_admission_and_replay`, `b5_replayed_attestation_is_refused_at_admission_and_replay`, `b5_recomputation_that_disagrees_is_refused_at_admission_and_replay`, `b5_derived_revision_records_round_trip_and_malformed_bytes_are_refused_typed`, and the core unit tests (codec, signature binding, server witness, path collision). Test keys and identifiers are derived from labels by SHA-256; no literal is used as key material. + +Red before green: each acceptance test was run against the B5 commit with one mutation that removes the behaviour it proves (`evidence/b5-derivation-attestation/red-green/red.txt`, 11 cases), and fails; `green.txt` holds the passing runs. + +## 5. Limits and deviations + +* **Derived-file rule not implemented.** The `ActionDigest` rule for derived files (lockfiles) needs registered executors and action receipts (E1, E3); rule tag 3 is reserved and refused by the decoder. Rebase and merge tier T0 are implemented. +* **When the server derives is not decided here.** B5 provides derivation, admission and verification. Lazy rebase policy (who may ask, the obsolescence marker that accompanies an admitted rebase, quota charging: D4) and the promotion queue (E2) are later steps. +* **Identity log in memory.** E0's identity log is not persisted yet, so the caller passes it to admission and to replay verification. Replay verification is an explicit call (`verify_revision_log`) after reopening: the store's own replay rebuilds state from the records without the identity log or the tree store. +* **Replay verification checks signatures and recomputation, not authority.** It does not recheck the join rule, quotas or blob visibility, which depend on F1 grants and blob state at admission time. +* **Conservative T0.** Two revisions that touch the same path, even identically, do not merge at T0. +* **B4 interaction.** Built against main. B4 (#88, open) adds revision states and WAL kind 9 to the same store files (`revision.rs`, `codec.rs`, `lib.rs`); whichever merges second needs a rebase, and the checkpoint kind list and state-root digest must then cover 7, 8, 9 and 11. A derived revision's initial B4 state is not defined here. +* **No performance figures:** B5 has no hot-path acceptance, and none were measured. diff --git a/evidence/b5-derivation-attestation/SHA256SUMS b/evidence/b5-derivation-attestation/SHA256SUMS new file mode 100644 index 0000000..64ae04e --- /dev/null +++ b/evidence/b5-derivation-attestation/SHA256SUMS @@ -0,0 +1,2 @@ +2fbd4dd8c5ee861b53856ce8c8569dc5d627c02a5a0aa0961043864489cfc4e2 red-green/green.txt +28f1eb8a5f641aa239f46331ca4661502a2a8bbd0ba4ebd3f1a09c47c0e6e8ba red-green/red.txt diff --git a/evidence/b5-derivation-attestation/red-green/green.txt b/evidence/b5-derivation-attestation/red-green/green.txt new file mode 100644 index 0000000..37e6349 --- /dev/null +++ b/evidence/b5-derivation-attestation/red-green/green.txt @@ -0,0 +1,23 @@ +# Green (2026-10-17, B5 commit bbe1734 on main 3d78efe; workspace 340 passed, 0 failed, 1 ignored; clippy -D warnings and fmt clean) + +# Command: cargo test --locked -p synapse-core --lib b5_ -- --test-threads=1 +test derivation::tests::b5_attestation_round_trips_and_refuses_malformed_bytes ... ok +test derivation::tests::b5_attestation_signature_binds_every_field ... ok +test derivation::tests::b5_path_collision_is_equal_or_below ... ok +test derivation::tests::b5_server_witness_round_trips_and_is_not_an_agent ... ok +test result: ok. 4 passed; 0 failed; 0 ignored; 0 measured; 13 filtered out; finished in 0.01s + +# Command: cargo test --locked -p synapse-store --test b5_derived_record -- --test-threads=1 +test b5_derived_revision_records_round_trip_and_malformed_bytes_are_refused_typed ... ok +test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.01s + +# Command: cargo test --locked -p synapse-api --test b5_derivation_attestation -- --test-threads=1 +test b5_attestation_naming_a_different_rule_is_refused_at_admission_and_replay ... ok +test b5_attestation_naming_different_inputs_is_refused_at_admission_and_replay ... ok +test b5_attestation_signed_by_another_key_is_refused_at_admission_and_replay ... ok +test b5_derived_revision_presented_with_an_agent_signature_it_does_not_have_is_refused ... ok +test b5_recomputation_that_disagrees_is_refused_at_admission_and_replay ... ok +test b5_replayed_attestation_is_refused_at_admission_and_replay ... ok +test b5_replica_recomputes_every_derived_revision_and_gets_the_same_digests ... ok +test b5_unregistered_server_key_is_refused_at_admission_and_replay ... ok +test result: ok. 8 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.78s diff --git a/evidence/b5-derivation-attestation/red-green/red.txt b/evidence/b5-derivation-attestation/red-green/red.txt new file mode 100644 index 0000000..a938ffb --- /dev/null +++ b/evidence/b5-derivation-attestation/red-green/red.txt @@ -0,0 +1,126 @@ +# Red (2026-10-17): each acceptance test run against the B5 commit bbe1734 with one mutation +# that removes the behaviour it proves; every mutation is reverted after its run. +# Command per case: cargo test --locked -p synapse-api --test b5_derivation_attestation -- --exact + +## server key not checked against the identity document +# mutation in crates/synapse-store/src/revision.rs: +# - if registered != Some(att.server_key) { +# + if false && registered != Some(att.server_key) { +thread 'b5_unregistered_server_key_is_refused_at_admission_and_replay' panicked at crates/synapse-api/tests/b5_derivation_attestation.rs:294:9: +assertion `left == right` failed: refused at admission + left: Ok(WalSeq(5)) + right: Err(DerivationServerKeyUnregistered) +test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 7 filtered out; finished in 0.10s +error: test failed, to rerun pass `-p synapse-api --test b5_derivation_attestation` + +## attestation signature not verified +# mutation in crates/synapse-core/src/derivation.rs: +# + .or(Ok(())) +thread 'b5_attestation_signed_by_another_key_is_refused_at_admission_and_replay' panicked at crates/synapse-api/tests/b5_derivation_attestation.rs:294:9: +assertion `left == right` failed: refused at admission + left: Ok(WalSeq(5)) + right: Err(DerivationSignatureInvalid) +test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 7 filtered out; finished in 0.10s +error: test failed, to rerun pass `-p synapse-api --test b5_derivation_attestation` + +## replayed attestation not detected +# mutation in crates/synapse-store/src/revision.rs: +# - if let Some(first) = self.derivations.get(&(repo.clone(), digest)) { +# + if let Some(first) = self.derivations.get(&(repo.clone(), digest)).filter(|_| false) { +thread 'b5_replayed_attestation_is_refused_at_admission_and_replay' panicked at crates/synapse-api/tests/b5_derivation_attestation.rs:294:9: +assertion `left == right` failed: refused at admission + left: Ok(WalSeq(5)) + right: Err(DerivationAttestationReplayed) +test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 7 filtered out; finished in 0.10s +error: test failed, to rerun pass `-p synapse-api --test b5_derivation_attestation` + +## derivation not recomputed (the attestation's output is trusted) +# mutation in crates/synapse-store/src/revision.rs: +# - let (content, tree) = derive_revision_output(att.rule, &att.inputs, &lookup, trees)?; +# + let _ = (&lookup, &trees); +# + let (content, tree) = (derived.content.clone(), att.output_tree); +thread 'b5_attestation_naming_different_inputs_is_refused_at_admission_and_replay' panicked at crates/synapse-api/tests/b5_derivation_attestation.rs:294:9: +assertion `left == right` failed: refused at admission + left: Ok(WalSeq(5)) + right: Err(DerivationRecomputeMismatch) +test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 7 filtered out; finished in 0.09s +error: test failed, to rerun pass `-p synapse-api --test b5_derivation_attestation` + +## recomputed tree not compared with the attested tree +# mutation in crates/synapse-store/src/revision.rs: +# - if recomputed != att.output_changeset || tree != att.output_tree { +# + if recomputed != att.output_changeset { +thread 'b5_recomputation_that_disagrees_is_refused_at_admission_and_replay' panicked at crates/synapse-api/tests/b5_derivation_attestation.rs:294:9: +assertion `left == right` failed: refused at admission + left: Ok(WalSeq(5)) + right: Err(DerivationRecomputeMismatch) +test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 7 filtered out; finished in 0.10s +error: test failed, to rerun pass `-p synapse-api --test b5_derivation_attestation` + +## attested rule ignored (rule inferred from the input count) +# mutation in crates/synapse-store/src/revision.rs: +# - let (content, tree) = derive_revision_output(att.rule, &att.inputs, &lookup, trees)?; +# + let (content, tree) = derive_revision_output(if att.inputs.len() == 2 { synapse_core::DerivationRule::Rebase } else { synapse_core::DerivationRule::Merge { tier: synapse_core::MergeTier::T0Path } }, &att.inputs, &lookup, trees)?; +thread 'b5_attestation_naming_a_different_rule_is_refused_at_admission_and_replay' panicked at crates/synapse-api/tests/b5_derivation_attestation.rs:294:9: +assertion `left == right` failed: refused at admission + left: Err(AuthChangeOutOfScope) + right: Err(DerivationInputMismatch) +test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 7 filtered out; finished in 0.09s +error: test failed, to rerun pass `-p synapse-api --test b5_derivation_attestation` + +## replay verifier does not check agent signatures of revision records +# mutation in crates/synapse-store/src/revision.rs: +# - envelope.validate().map_err(at_seq)?; +# + let _ = envelope; +thread 'b5_derived_revision_presented_with_an_agent_signature_it_does_not_have_is_refused' panicked at crates/synapse-api/tests/b5_derivation_attestation.rs:612:9: +assertion `left == right` failed + left: Ok(4) + right: Err(AuthSignatureInvalid) +test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 7 filtered out; finished in 0.09s +error: test failed, to rerun pass `-p synapse-api --test b5_derivation_attestation` + +## replay verifier does not recompute derived records +# mutation in crates/synapse-store/src/revision.rs: +# - ledger +# - .check_derivation(derived, *seq, keys, trees) +# - .map_err(at_seq)?; +# + let _ = (derived, &keys, &trees); +thread 'b5_attestation_naming_different_inputs_is_refused_at_admission_and_replay' panicked at crates/synapse-api/tests/b5_derivation_attestation.rs:327:9: +assertion `left == right` failed: refused at replay + left: Ok(4) + right: Err(DerivationRecomputeMismatch) +test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 7 filtered out; finished in 0.09s +error: test failed, to rerun pass `-p synapse-api --test b5_derivation_attestation` + +## replay verifier checks the server key at the latest identity document, not at the record's sequence +# mutation in crates/synapse-store/src/revision.rs: +# - .check_derivation(derived, *seq, keys, trees) +# + .check_derivation(derived, WalSeq(u64::MAX), keys, trees) +thread 'b5_unregistered_server_key_is_refused_at_admission_and_replay' panicked at crates/synapse-api/tests/b5_derivation_attestation.rs:535:5: +assertion `left == right` failed: each verifies at its own sequence + left: Err(DerivationServerKeyUnregistered) + right: Ok(5) +test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 7 filtered out; finished in 0.11s +error: test failed, to rerun pass `-p synapse-api --test b5_derivation_attestation` + +## rebase applies the mutations on the source base instead of the target tree +# mutation in crates/synapse-core/src/derivation.rs: +# - let tree = trees.apply_mutations(*onto, &content.mutations)?; +# + let tree = trees.apply_mutations(source.base_tree, &content.mutations)?; +thread 'b5_replica_recomputes_every_derived_revision_and_gets_the_same_digests' panicked at crates/synapse-api/tests/b5_derivation_attestation.rs:345:5: +assertion `left == right` failed + left: TreeDigest(8e50e3ff7af1ce28124e0bf045b39f205959a647714c58c9784f7dccfe44a0dd) + right: TreeDigest(4db0df3d43b078a9cf2e6883d8ac0a98306492e68a34b3d824078747bb606fd4) +test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 7 filtered out; finished in 0.08s +error: test failed, to rerun pass `-p synapse-api --test b5_derivation_attestation` + +## checkpoint load drops derived revision records +# mutation in crates/synapse-store/src/codec.rs: +# - s.revision_log.push((seq, record)); +# + if record.kind_byte() != 11 { +# + s.revision_log.push((seq, record)); +# + } +thread 'b5_replica_recomputes_every_derived_revision_and_gets_the_same_digests' panicked at crates/synapse-api/tests/b5_derivation_attestation.rs:410:53: +called `Result::unwrap()` on an `Err` value: SynapseError { code: CheckpointCorrupt, message: "checkpoint: checkpoint.v2 state root does not match its content" } +test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 7 filtered out; finished in 0.08s +error: test failed, to rerun pass `-p synapse-api --test b5_derivation_attestation` From aef369ee09d63b874ecc42b4a8f478198230935e Mon Sep 17 00:00:00 2001 From: Drake Stapleton Date: Fri, 16 Oct 2026 21:39:04 -0500 Subject: [PATCH 3/5] fix(b5): bind server key lookup to the repository; release-mode write sequence check (#29) Review of #95, findings 1 and 5. 1. ServerKeyRegistry::registered_server_key now takes the repository and answers ServerKeyLookup (Registered / NoDocument / OtherRepository). IdentityLog answers only for its own repository. check_derivation refuses another repository's identity documents with the new stable code DerivationIdentityRepoMismatch, at admission and at replay, even when both repositories register the same server machine key. 2. The admission-to-write sequence agreement was a debug_assert_eq!. It is now a real check in every build profile: a writer whose next sequence differs from the checked one is refused before writing, and a frame that lands at another sequence is not applied and poisons the store (WalSequenceGap), instead of a panic (debug) or a silent admission (release). Red before green: evidence/b5-derivation-attestation/red-green/review-fixes.txt (fix 1 red: other repo's log accepted; fix 2 red: debug panic, release admits seq 4-checked record at seq 5). Workspace: 342 passed, 0 failed, 1 ignored. Co-Authored-By: Claude Opus 5.5 --- .../tests/b5_derivation_attestation.rs | 85 +++++++++++- crates/synapse-core/src/derivation.rs | 22 ++- crates/synapse-core/src/lib.rs | 6 +- crates/synapse-radicle/src/identity.rs | 16 ++- crates/synapse-store/src/revision.rs | 128 +++++++++++++----- docs/B5_DERIVATION_ATTESTATION.md | 12 +- evidence/b5-derivation-attestation/SHA256SUMS | 1 + .../red-green/review-fixes.txt | 63 +++++++++ 8 files changed, 289 insertions(+), 44 deletions(-) create mode 100644 evidence/b5-derivation-attestation/red-green/review-fixes.txt diff --git a/crates/synapse-api/tests/b5_derivation_attestation.rs b/crates/synapse-api/tests/b5_derivation_attestation.rs index 83a06d2..8d0e442 100644 --- a/crates/synapse-api/tests/b5_derivation_attestation.rs +++ b/crates/synapse-api/tests/b5_derivation_attestation.rs @@ -32,7 +32,8 @@ use synapse_radicle::{ IdentityDocumentDigest, IdentityEdit, IdentityLog, RepositoryIdentityDocument, }; use synapse_store::{ - AdmissionAuthority, FsyncPolicy, RecoveryPolicy, RevisionOutcome, StoreLimits, WalRecord, + AdmissionAuthority, FaultInjection, FsyncPolicy, RecoveryPolicy, RevisionOutcome, StoreLimits, + WalRecord, }; const NOW: u64 = 5_000; @@ -541,6 +542,59 @@ fn b5_unregistered_server_key_is_refused_at_admission_and_replay() { ); } +#[test] +fn b5_identity_log_of_another_repository_is_refused_at_admission_and_replay() { + let mut fx = Fx::new("other-repo-identity"); + let honest = fx.rebase_a(); + let at = fx.admit(honest.clone(), "a").unwrap(); + // Another repository's identity log that registers the same server machine key, with the + // same delegates, from the same sequence: its `server_key` matches the attestation's, but + // it says nothing about this repository. + let mut ds = vec![pk(&fx.delegates[0]), pk(&fx.delegates[1])]; + ds.sort(); + let other_genesis = RepositoryIdentityDocument { + repo_id: RepoId::new("aien-spark/other").unwrap(), + revision: 0, + prev: IdentityDocumentDigest::ZERO, + threshold: 2, + delegates: ds, + executors: vec![], + server_key: pk(&fx.server), + }; + let edit = IdentityEdit::sign(other_genesis, &[&fx.delegates[0], &fx.delegates[1]]); + let other = IdentityLog::genesis(&edit, WalSeq(0)).unwrap(); + assert_eq!(fx.keys.server_key_at(at), other.server_key_at(at)); + + // Admission against the other repository's log is refused, and nothing is written. + let merge = fx.merge_ab(); + let before = fx.svc.store().committed_seq(); + let refused = fx + .svc + .admit_derived_revision(merge.clone(), authority("merge"), &other, NOW) + .map(|_| ()) + .map_err(|e| e.code); + assert_eq!( + refused, + Err(RefusalCode::DerivationIdentityRepoMismatch), + "refused at admission" + ); + assert_eq!(fx.svc.store().committed_seq(), before, "nothing written"); + + // Replay of the honest log against the other repository's log is refused; against this + // repository's own log it verifies. + let live = fx.records(); + assert_eq!( + fx.svc + .verify_revision_records(&live, &other) + .map_err(|e| e.code), + Err(RefusalCode::DerivationIdentityRepoMismatch), + "refused at replay" + ); + assert_eq!(fx.verify(&live), Ok(4)); + // The same derivation is admitted against this repository's own log. + fx.admit(merge, "merge").unwrap(); +} + #[test] fn b5_attestation_signed_by_another_key_is_refused_at_admission_and_replay() { let mut fx = Fx::new("signature"); @@ -679,3 +733,32 @@ fn b5_recomputation_that_disagrees_is_refused_at_admission_and_replay() { let live = fx.records(); assert_eq!(fx.verify(&live), Ok(4)); } + +#[test] +fn b5_derivation_written_at_another_sequence_than_it_was_checked_at_is_refused() { + let mut fx = Fx::new("sequence-mismatch"); + let honest = fx.rebase_a(); + let checked_at = fx.svc.store().committed_seq().next(); + // Test hook standing in for a writer that places the frame elsewhere: the next frame is + // written at `checked_at + 1`, so the derivation was checked against the identity document + // of a sequence it is not stored at. + fx.svc + .store_mut() + .set_fault_injection(FaultInjection::InjectNextWalSequenceGap); + assert_eq!( + fx.admit(honest.clone(), "a"), + Err(RefusalCode::WalSequenceGap), + "refused with a typed error, not admitted and not a panic" + ); + // Not applied: no derived record is visible, and the store refuses further writes until + // it is reopened (recovery then decides on the frame on disk). + assert!( + fx.records() + .iter() + .all(|(_, r)| !matches!(r, WalRecord::DerivedRevisionAdmitted { .. })), + "the derived revision is not applied" + ); + assert!(fx.svc.store().poisoned().is_some(), "store is poisoned"); + assert_eq!(fx.admit(honest, "a"), Err(RefusalCode::IoFailure)); + assert!(fx.svc.store().committed_seq() > checked_at); +} diff --git a/crates/synapse-core/src/derivation.rs b/crates/synapse-core/src/derivation.rs index 0e12036..7f334d3 100644 --- a/crates/synapse-core/src/derivation.rs +++ b/crates/synapse-core/src/derivation.rs @@ -404,11 +404,25 @@ impl AdmissionWitness { // What a replica needs to check and recompute // --------------------------------------------------------------------------------------- -/// Which server machine key the repository identity document registered at a `WalSeq` -/// (`synapse_radicle::IdentityLog` implements it from the E0 document chain). +/// What a [`ServerKeyRegistry`] answers for one repository at one `WalSeq`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ServerKeyLookup { + /// The `server_key` of the repository's identity document in effect at the sequence. + Registered([u8; 32]), + /// No identity document of the repository is in effect at the sequence (before genesis). + NoDocument, + /// The registry holds the identity documents of another repository (named here), so it + /// says nothing about the one asked for. + OtherRepository(RepoId), +} + +/// Which server machine key a repository identity document registered at a `WalSeq` +/// (`synapse_radicle::IdentityLog` implements it from the E0 document chain). The repository +/// is part of the question, so one repository's documents can never vouch for another's +/// derivations, even when both register the same server machine key. pub trait ServerKeyRegistry { - /// The `server_key` of the document in effect at `at`; `None` before genesis. - fn registered_server_key(&self, at: WalSeq) -> Option<[u8; 32]>; + /// The `server_key` of `repo`'s document in effect at `at`. + fn registered_server_key(&self, repo: &RepoId, at: WalSeq) -> ServerKeyLookup; } /// The tree operations a derivation rule needs (the C1 tree store implements them). diff --git a/crates/synapse-core/src/lib.rs b/crates/synapse-core/src/lib.rs index 90c5544..9966ad3 100644 --- a/crates/synapse-core/src/lib.rs +++ b/crates/synapse-core/src/lib.rs @@ -14,7 +14,7 @@ mod revision_state; mod tree; pub use derivation::{ derive_revision_output, DerivationAttestation, DerivationInput, DerivationRule, - DerivationTrees, DerivedRevision, MergeTier, ServerKeyRegistry, + DerivationTrees, DerivedRevision, MergeTier, ServerKeyLookup, ServerKeyRegistry, DOMAIN_DERIVATION_ATTESTATION_V1, DOMAIN_DERIVATION_SIGN_V1, DOMAIN_DERIVED_MERGE_CHANGE_V1, MAX_DERIVATION_INPUTS, }; @@ -158,6 +158,10 @@ pub enum RefusalCode { /// identity document in effect at the admission `WalSeq`, or no document is in effect /// (step B5). DerivationServerKeyUnregistered, + /// The identity documents a derivation is checked against belong to another repository + /// than the one its `DerivationAttestation` names, so their `server_key` says nothing + /// about this derivation (step B5). + DerivationIdentityRepoMismatch, /// A `DerivationAttestation` names inputs that do not fit its rule (kind, count, order, /// duplicates) or that the replica does not hold: a revision not admitted in this /// repository before the derivation, or a tree not in the tree store (step B5). diff --git a/crates/synapse-radicle/src/identity.rs b/crates/synapse-radicle/src/identity.rs index 9ab868d..8f0bbf4 100644 --- a/crates/synapse-radicle/src/identity.rs +++ b/crates/synapse-radicle/src/identity.rs @@ -624,9 +624,19 @@ impl<'a> Reader<'a> { /// The server key a derivation attestation must name is the `server_key` of the document in /// effect at the admission `WalSeq` (ADR 0003 step B5): a later rotation never invalidates a -/// derivation admitted before it, and a key rotated out refuses every later one. +/// derivation admitted before it, and a key rotated out refuses every later one. The log holds +/// one repository's documents (`apply` refuses an edit for another), so it answers only for +/// that repository and names it as `OtherRepository` for any other. impl synapse_core::ServerKeyRegistry for IdentityLog { - fn registered_server_key(&self, at: WalSeq) -> Option<[u8; 32]> { - self.server_key_at(at) + fn registered_server_key(&self, repo: &RepoId, at: WalSeq) -> synapse_core::ServerKeyLookup { + use synapse_core::ServerKeyLookup; + let own = &self.current().repo_id; + if own != repo { + return ServerKeyLookup::OtherRepository(own.clone()); + } + match self.server_key_at(at) { + Some(key) => ServerKeyLookup::Registered(key), + None => ServerKeyLookup::NoDocument, + } } } diff --git a/crates/synapse-store/src/revision.rs b/crates/synapse-store/src/revision.rs index 3dcb3cc..8fcc088 100644 --- a/crates/synapse-store/src/revision.rs +++ b/crates/synapse-store/src/revision.rs @@ -16,7 +16,8 @@ use synapse_core::{ derive_revision_output, AdmissionWitness, AuthorshipAttestation, BlobDigest, ChainPath, ChangeId, ChangesetEnvelopeV2, ChangesetId, DerivationAttestation, DerivationTrees, DerivedRevision, IdempotencyKey, MutationOp, ObsolescenceKind, ObsolescenceMarker, RefusalCode, - RepoId, RevisionContent, RevisionState, ServerKeyRegistry, SynapseError, SynapseResult, WalSeq, + RepoId, RevisionContent, RevisionState, ServerKeyLookup, ServerKeyRegistry, SynapseError, + SynapseResult, WalSeq, }; /// Domain tag of the revision part of the state root (only hashed when revisions exist). @@ -534,11 +535,12 @@ impl RevisionLedger { /// Checks of a derived revision at admission `WalSeq` `at` (ADR 0003 B5), shared by /// admission and replay verification so both refuse exactly the same records. In order: /// content rules, the attestation names this content and its signature verifies under the - /// server key it names (`DerivationSignatureInvalid`); that key is the identity document's - /// server key in effect at `at` (`DerivationServerKeyUnregistered`); the attestation was - /// not admitted before (`DerivationAttestationReplayed`); the inputs fit the rule and are - /// held (`DerivationInputMismatch`); recomputing the rule on them gives the attested - /// `ChangesetId` and `TreeDigest` (`DerivationRecomputeMismatch`). + /// server key it names (`DerivationSignatureInvalid`); the identity documents `keys` holds + /// belong to the attestation's repository (`DerivationIdentityRepoMismatch`); that key is + /// the identity document's server key in effect at `at` (`DerivationServerKeyUnregistered`); + /// the attestation was not admitted before (`DerivationAttestationReplayed`); the inputs fit + /// the rule and are held (`DerivationInputMismatch`); recomputing the rule on them gives the + /// attested `ChangesetId` and `TreeDigest` (`DerivationRecomputeMismatch`). pub(crate) fn check_derivation( &self, derived: &DerivedRevision, @@ -548,20 +550,33 @@ impl RevisionLedger { ) -> SynapseResult { let id = derived.validate()?; let att = &derived.attestation; - let registered = keys.registered_server_key(at); - if registered != Some(att.server_key) { - return Err(SynapseError::new( - RefusalCode::DerivationServerKeyUnregistered, - match registered { - Some(_) => format!( + let repo = att.repo_id.clone(); + match keys.registered_server_key(&repo, at) { + ServerKeyLookup::Registered(key) if key == att.server_key => {} + ServerKeyLookup::Registered(_) => { + return Err(SynapseError::new( + RefusalCode::DerivationServerKeyUnregistered, + format!( "server key {} is not the server key of the identity document in effect at {at}", att.server_did() ), - None => format!("no identity document is in effect at {at}"), - }, - )); + )) + } + ServerKeyLookup::NoDocument => { + return Err(SynapseError::new( + RefusalCode::DerivationServerKeyUnregistered, + format!("no identity document of {repo} is in effect at {at}"), + )) + } + ServerKeyLookup::OtherRepository(other) => { + return Err(SynapseError::new( + RefusalCode::DerivationIdentityRepoMismatch, + format!( + "the identity documents checked belong to {other}, the derivation attestation names {repo}" + ), + )) + } } - let repo = att.repo_id.clone(); let digest = att.digest(); if let Some(first) = self.derivations.get(&(repo.clone(), digest)) { return Err(SynapseError::new( @@ -889,7 +904,7 @@ impl crate::SynapseStore { admitted_at_ms: now_ms, new_blobs: inline.iter().map(|(d, _)| *d).collect(), }; - let wal_seq = self.append_revision_record(record, &inline)?; + let wal_seq = self.append_revision_record(record, &inline, None)?; Ok(RevisionOutcome::Admitted { wal_seq, changeset_id: id, @@ -981,11 +996,7 @@ impl crate::SynapseStore { chain: authority.chain, admitted_at_ms: now_ms, }; - let wal_seq = self.append_revision_record(record, &[])?; - debug_assert_eq!( - wal_seq, at, - "derivation checked at the sequence it was written at" - ); + let wal_seq = self.append_revision_record(record, &[], Some(at))?; Ok(RevisionOutcome::Admitted { wal_seq, changeset_id: id, @@ -1031,7 +1042,7 @@ impl crate::SynapseStore { chain, recorded_at_ms: now_ms, }; - self.append_revision_record(record, &[]) + self.append_revision_record(record, &[], None) } /// Record the signed state move `state_move` at server time `now_ms` (ADR 0003 step B4, @@ -1056,7 +1067,7 @@ impl crate::SynapseStore { state_move, moved_at_ms: now_ms, }; - self.append_revision_record(record, &[]) + self.append_revision_record(record, &[], None) } /// Kind 9 records replay kept as no-ops, by reason (issue #89): unverified moves (only @@ -1128,30 +1139,80 @@ impl crate::SynapseStore { } /// Append one revision record (blobs inline in the segment store, blob files first in - /// the `wal.log` layout) and apply it. + /// the `wal.log` layout) and apply it. With `checked_at`, the record was checked against + /// that `WalSeq` (a derivation against the identity document in effect there) and must be + /// written at exactly that sequence: a writer whose next sequence differs is refused + /// before anything is written, and a frame that lands at another sequence anyway is not + /// applied and poisons the store (`WalSequenceGap` in both cases), so a record is never + /// admitted at a sequence it was not checked at. Real checks in every build profile. fn append_revision_record( &mut self, record: WalRecord, blobs: &[(BlobDigest, &[u8])], + checked_at: Option, ) -> SynapseResult { if self.v2_mode { let encoded = crate::wal2::encode_record(&record, blobs, self.codec)?; self.check_frame_cap(encoded.payload.len())?; let mut ticket = self.v2_begin()?; + if let Some(err) = + checked_at.and_then(|at| sequence_mismatch(at, ticket.base_seq.next(), false)) + { + // Hand the writer back untouched; the refusal is the result. + let refused = self.v2_finish( + ticket, + Err(crate::wal2::BatchFailure::RolledBack(err.clone())), + ); + return Err(refused.err().unwrap_or(err)); + } let result = Self::v2_write(&mut ticket, &[&encoded]); let placed = self.v2_finish(ticket, result)?; let seq = placed[0].seq; + self.refuse_misplaced(checked_at, seq)?; self.apply_v2_ingest(&placed[0], record, &encoded.inline); return Ok(seq); } + if let Some(err) = + checked_at.and_then(|at| sequence_mismatch(at, self.committed_seq.next(), false)) + { + return Err(err); + } let payload = self.encode_v1_payload(&record)?; for (digest, bytes) in blobs { self.write_blob_file(*digest, bytes)?; } let (seq, _, _) = self.append_v1_payload(record.kind_byte(), &payload)?; + self.refuse_misplaced(checked_at, seq)?; self.apply_record(seq, record); Ok(seq) } + + /// After a durable write: a record checked at `checked_at` that landed at `seq` instead + /// is not applied, and the store refuses writes until it is reopened. + fn refuse_misplaced(&mut self, checked_at: Option, seq: WalSeq) -> SynapseResult<()> { + match checked_at.and_then(|at| sequence_mismatch(at, seq, true)) { + Some(err) => { + self.poisoned = Some(err.message.clone()); + Err(err) + } + None => Ok(()), + } + } +} + +/// `WalSequenceGap` when a record checked at `checked_at` would be (`written == false`) or was +/// (`written == true`) placed at `seq`. +fn sequence_mismatch(checked_at: WalSeq, seq: WalSeq, written: bool) -> Option { + (checked_at != seq).then(|| { + SynapseError::new( + RefusalCode::WalSequenceGap, + if written { + format!("record checked at {checked_at} was written at {seq}; it is not applied and the store refuses writes until it is reopened") + } else { + format!("record checked at {checked_at} would be written at {seq}; nothing was written") + }, + ) + }) } #[cfg(test)] @@ -1521,8 +1582,9 @@ mod b4_tests { assert_eq!(broken.verify(), Err(StateMoveFault::SignatureInvalid)); let impostor = non_leaf_signer(honest, &[1, 9]); assert_eq!(impostor.verify(), Err(StateMoveFault::SignerNotChainLeaf)); - let first = s.append_revision_record(moved(broken), &[]).unwrap(); - s.append_revision_record(moved(impostor), &[]).unwrap(); + let first = s.append_revision_record(moved(broken), &[], None).unwrap(); + s.append_revision_record(moved(impostor), &[], None) + .unwrap(); assert_eq!( s.get_revision(&repo(), id).unwrap().state, RevisionState::Private @@ -1573,14 +1635,18 @@ mod b4_tests { let mut s = open(&dir, TORN).unwrap(); let id = admit(&mut s, owner); let honest = signed(owner, id, RevisionState::Draft); - s.append_revision_record(moved(bad_signature(honest.clone())), &[]) + s.append_revision_record(moved(bad_signature(honest.clone())), &[], None) .unwrap(); - s.append_revision_record(moved(non_leaf_signer(honest.clone(), &[1, 9])), &[]) + s.append_revision_record(moved(non_leaf_signer(honest.clone(), &[1, 9])), &[], None) .unwrap(); s.advance_revision_state(honest, 6_500).unwrap(); // A verified move that is not an owner move is an ordinary no-op and stays. - s.append_revision_record(moved(signed(&[1, 9], id, RevisionState::Proposed)), &[]) - .unwrap(); + s.append_revision_record( + moved(signed(&[1, 9], id, RevisionState::Proposed)), + &[], + None, + ) + .unwrap(); drop(s); assert!( open(&dir, STRICT).is_err(), diff --git a/docs/B5_DERIVATION_ATTESTATION.md b/docs/B5_DERIVATION_ATTESTATION.md index ec9692f..a3bd0ba 100644 --- a/docs/B5_DERIVATION_ATTESTATION.md +++ b/docs/B5_DERIVATION_ATTESTATION.md @@ -13,7 +13,7 @@ Code: `crates/synapse-core/src/derivation.rs` (types, codecs, the one recomputat * **Derived revision** = `RevisionContent` + `DerivationAttestation`; the attestation must name the content's `ChangesetId`. It carries no `AuthorshipAttestation`. The input revisions keep their own agent signatures. * **Witness.** Admission records an `AdmissionWitness` with signer tag 2 (`WitnessSigner::Server`: server key, the attestation's signature, the attestation digest) instead of an agent signature; its idempotency key is the attestation digest. `StoredRevision.derivations` lists the attestations; `attestations` (agent) stays empty for a revision only the server produced. * **One recomputation.** `derive_revision_output` is the only implementation of the rules. The server uses it to derive, admission uses it to check, and replay verification uses it to recompute, so the three cannot drift apart. -* **Server key registration.** `ServerKeyRegistry::registered_server_key(at)` returns the identity document's `server_key` in effect at `WalSeq` `at`; `IdentityLog` implements it with E0's `server_key_at`. An attestation is checked at the sequence of its own admission, so a rotation does not invalidate earlier derivations and an old key is refused after the rotation. +* **Server key registration.** `ServerKeyRegistry::registered_server_key(repo, at)` returns the `server_key` of `repo`'s identity document in effect at `WalSeq` `at` (`ServerKeyLookup::Registered`), `NoDocument` before genesis, or `OtherRepository` when the registry holds another repository's documents; `IdentityLog` implements it with E0's `server_key_at` and answers only for its own repository. The repository is part of the question, so one repository's identity log never vouches for another repository's derivations, even when both register the same server machine key. An attestation is checked at the sequence of its own admission, so a rotation does not invalidate earlier derivations and an old key is refused after the rotation. ## 2. Checks, in order @@ -22,12 +22,13 @@ At admission (`SynapseStore::admit_derived_revision`, sequence `at` = the next ` | Check | Refusal | |---|---| | Content rules; attestation names this content; input count 1..=256; server key is a valid Ed25519 point and the strict signature verifies | `DerivationSignatureInvalid` (count: `DerivationInputMismatch`) | +| The identity documents checked belong to the attestation's repository | `DerivationIdentityRepoMismatch` | | Server key equals the identity document's `server_key` at the sequence | `DerivationServerKeyUnregistered` | | Attestation digest not already admitted in this repository | `DerivationAttestationReplayed` | | Inputs fit the rule's shape and order; every named revision is admitted; every named tree is held | `DerivationInputMismatch` | | The rule applies (rebase target differs from the base, no path conflict, merge revisions share the base) and the recomputed `ChangesetId` and `TreeDigest` equal the attested ones | `DerivationRecomputeMismatch` | -Admission then applies B1's checks: path-count limit, join rule under the asking or proposing chain (`AuthChangeOutOfScope`), parents (`ParentChangesetNotFound`), and every upserted blob already visible (`BlobNotFound`); nothing is written on any refusal. The API also refuses an attestation for another repository (`AuthCrossRepoDenied`). +Admission then applies B1's checks: path-count limit, join rule under the asking or proposing chain (`AuthChangeOutOfScope`), parents (`ParentChangesetNotFound`), and every upserted blob already visible (`BlobNotFound`); nothing is written on any refusal. The record must then be written at exactly the sequence `at` it was checked at: a writer whose next sequence differs is refused before anything is written, and a frame that lands at another sequence anyway is not applied and poisons the store until it is reopened (`WalSequenceGap` in both cases, a real check in every build profile). The API also refuses an attestation for another repository (`AuthCrossRepoDenied`). Replay verification walks the revision records in sequence order with a fresh ledger: kind 7 records are checked with `ChangesetEnvelopeV2::validate` (so a derived revision dressed in a borrowed agent attestation is `AuthSignatureInvalid`), kind 8 with `ObsolescenceMarker::validate`, kind 11 with the checks above; sequences must strictly ascend (`WalSequenceGap`) and any other kind is `WalRecordMalformed`. Refusals keep their code and prefix the message with the record's sequence. @@ -53,15 +54,18 @@ Conventions as in B1 (little-endian, `str` = `u32 len | UTF-8`, lengths checked | An attestation by an unregistered server key is refused at admission and at replay | `b5_unregistered_server_key_is_refused_at_admission_and_replay` (a rogue key, a delegate's key, the old key after a rotation; the earlier derivation still verifies) | | A derived revision presented with an agent signature it does not have is refused | `b5_derived_revision_presented_with_an_agent_signature_it_does_not_have_is_refused` (the input's attestation as is and re-pointed, at admission and as a replayed kind 7 record) | -Also: `b5_attestation_signed_by_another_key_is_refused_at_admission_and_replay`, `b5_replayed_attestation_is_refused_at_admission_and_replay`, `b5_recomputation_that_disagrees_is_refused_at_admission_and_replay`, `b5_derived_revision_records_round_trip_and_malformed_bytes_are_refused_typed`, and the core unit tests (codec, signature binding, server witness, path collision). Test keys and identifiers are derived from labels by SHA-256; no literal is used as key material. +Also: `b5_attestation_signed_by_another_key_is_refused_at_admission_and_replay`, `b5_identity_log_of_another_repository_is_refused_at_admission_and_replay` (same server key, same delegates, other repository: refused at admission and at replay), `b5_derivation_written_at_another_sequence_than_it_was_checked_at_is_refused` (typed refusal, not applied, store poisoned), `b5_replayed_attestation_is_refused_at_admission_and_replay`, `b5_recomputation_that_disagrees_is_refused_at_admission_and_replay`, `b5_derived_revision_records_round_trip_and_malformed_bytes_are_refused_typed`, and the core unit tests (codec, signature binding, server witness, path collision). Test keys and identifiers are derived from labels by SHA-256; no literal is used as key material. -Red before green: each acceptance test was run against the B5 commit with one mutation that removes the behaviour it proves (`evidence/b5-derivation-attestation/red-green/red.txt`, 11 cases), and fails; `green.txt` holds the passing runs. +Red before green: each acceptance test was run against the B5 commit with one mutation that removes the behaviour it proves (`evidence/b5-derivation-attestation/red-green/red.txt`, 11 cases), and fails; `green.txt` holds the passing runs. The two review fixes (repository-bound key lookup, release-mode sequence check) were written test first: `review-fixes.txt` holds their red runs (the other repository's log was accepted; the misplaced record panicked in a debug build and was admitted in a release build) and green runs. ## 5. Limits and deviations * **Derived-file rule not implemented.** The `ActionDigest` rule for derived files (lockfiles) needs registered executors and action receipts (E1, E3); rule tag 3 is reserved and refused by the decoder. Rebase and merge tier T0 are implemented. * **When the server derives is not decided here.** B5 provides derivation, admission and verification. Lazy rebase policy (who may ask, the obsolescence marker that accompanies an admitted rebase, quota charging: D4) and the promotion queue (E2) are later steps. * **Identity log in memory.** E0's identity log is not persisted yet, so the caller passes it to admission and to replay verification. Replay verification is an explicit call (`verify_revision_log`) after reopening: the store's own replay rebuilds state from the records without the identity log or the tree store. +* **Open and checkpoint load do not verify kind 11 records.** They trust the store's own WAL, as for kind 7; a caller that skips `verify_revision_log` gets no error. A later step could make `open` take a `ServerKeyRegistry` or record "verified up to seq N". +* **Rotation sequence not authenticated (E0 scope).** `applied_at` is supplied by the caller and is not covered by the edit signatures or written to the store WAL, so a replica must learn rotation sequences from the server, which limits what replica verification proves today. +* **Re-signing after rotation.** After a rotation the new key can re-sign a derivation the old key already attested; the digest differs, so it is admitted again as a second witness on the same revision. Each admission is a valid server statement at its own sequence. * **Replay verification checks signatures and recomputation, not authority.** It does not recheck the join rule, quotas or blob visibility, which depend on F1 grants and blob state at admission time. * **Conservative T0.** Two revisions that touch the same path, even identically, do not merge at T0. * **B4 interaction.** Built against main. B4 (#88, open) adds revision states and WAL kind 9 to the same store files (`revision.rs`, `codec.rs`, `lib.rs`); whichever merges second needs a rebase, and the checkpoint kind list and state-root digest must then cover 7, 8, 9 and 11. A derived revision's initial B4 state is not defined here. diff --git a/evidence/b5-derivation-attestation/SHA256SUMS b/evidence/b5-derivation-attestation/SHA256SUMS index 64ae04e..184e866 100644 --- a/evidence/b5-derivation-attestation/SHA256SUMS +++ b/evidence/b5-derivation-attestation/SHA256SUMS @@ -1,2 +1,3 @@ 2fbd4dd8c5ee861b53856ce8c8569dc5d627c02a5a0aa0961043864489cfc4e2 red-green/green.txt 28f1eb8a5f641aa239f46331ca4661502a2a8bbd0ba4ebd3f1a09c47c0e6e8ba red-green/red.txt +482aaf388eb8058a9e73376e6d4cc79d8f0b7bee1f0b787ef48465e405474d28 red-green/review-fixes.txt diff --git a/evidence/b5-derivation-attestation/red-green/review-fixes.txt b/evidence/b5-derivation-attestation/red-green/review-fixes.txt new file mode 100644 index 0000000..e50af3e --- /dev/null +++ b/evidence/b5-derivation-attestation/red-green/review-fixes.txt @@ -0,0 +1,63 @@ +# Review fixes for PR #95 (2026-10-17, on B5 head 50295c3): red before green +# Review comment: aien-dev/synapse#95 issuecomment-6228539788, findings 1 and 5. + +## Fix 1: server key lookup bound to the repository (DerivationIdentityRepoMismatch) +# Red: test written with only the new refusal code added; check_derivation unchanged. +# Command: cargo test --locked -p synapse-api --test b5_derivation_attestation b5_identity_log_of_another_repository +test b5_identity_log_of_another_repository_is_refused_at_admission_and_replay ... FAILED +thread 'b5_identity_log_of_another_repository_is_refused_at_admission_and_replay' panicked at crates/synapse-api/tests/b5_derivation_attestation.rs:575:5: +assertion `left == right` failed: refused at admission + left: Ok(()) + right: Err(DerivationIdentityRepoMismatch) +test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 8 filtered out; finished in 0.06s + +## Fix 2: admission-to-write sequence check in every build profile (WalSequenceGap) +# Red (debug build): the debug_assert_eq! panics. +# Command: cargo test --locked -p synapse-api --test b5_derivation_attestation b5_derivation_written_at +test b5_derivation_written_at_another_sequence_than_it_was_checked_at_is_refused ... FAILED +thread 'b5_derivation_written_at_another_sequence_than_it_was_checked_at_is_refused' panicked at crates/synapse-store/src/revision.rs:769:9: +assertion `left == right` failed: derivation checked at the sequence it was written at + left: WalSeq(5) + right: WalSeq(4) +test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 9 filtered out; finished in 0.05s + +# Red (release build): the record checked at seq 4 is admitted at seq 5. +# Command: cargo test --release --locked -p synapse-api --test b5_derivation_attestation b5_derivation_written_at +test b5_derivation_written_at_another_sequence_than_it_was_checked_at_is_refused ... FAILED +thread 'b5_derivation_written_at_another_sequence_than_it_was_checked_at_is_refused' panicked at crates/synapse-api/tests/b5_derivation_attestation.rs:748:5: +assertion `left == right` failed: refused with a typed error, not admitted and not a panic + left: Ok(WalSeq(5)) + right: Err(WalSequenceGap) +test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 9 filtered out; finished in 0.05s + +## Green, both fixes (debug build) +# Command: cargo test --locked -p synapse-api --test b5_derivation_attestation +test b5_attestation_naming_a_different_rule_is_refused_at_admission_and_replay ... ok +test b5_attestation_naming_different_inputs_is_refused_at_admission_and_replay ... ok +test b5_attestation_signed_by_another_key_is_refused_at_admission_and_replay ... ok +test b5_derivation_written_at_another_sequence_than_it_was_checked_at_is_refused ... ok +test b5_derived_revision_presented_with_an_agent_signature_it_does_not_have_is_refused ... ok +test b5_identity_log_of_another_repository_is_refused_at_admission_and_replay ... ok +test b5_recomputation_that_disagrees_is_refused_at_admission_and_replay ... ok +test b5_replayed_attestation_is_refused_at_admission_and_replay ... ok +test b5_replica_recomputes_every_derived_revision_and_gets_the_same_digests ... ok +test b5_unregistered_server_key_is_refused_at_admission_and_replay ... ok +test result: ok. 10 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.12s + +## Green, both fixes (release build) +# Command: cargo test --release --locked -p synapse-api --test b5_derivation_attestation +test b5_attestation_naming_a_different_rule_is_refused_at_admission_and_replay ... ok +test b5_attestation_naming_different_inputs_is_refused_at_admission_and_replay ... ok +test b5_attestation_signed_by_another_key_is_refused_at_admission_and_replay ... ok +test b5_derivation_written_at_another_sequence_than_it_was_checked_at_is_refused ... ok +test b5_derived_revision_presented_with_an_agent_signature_it_does_not_have_is_refused ... ok +test b5_identity_log_of_another_repository_is_refused_at_admission_and_replay ... ok +test b5_recomputation_that_disagrees_is_refused_at_admission_and_replay ... ok +test b5_replayed_attestation_is_refused_at_admission_and_replay ... ok +test b5_replica_recomputes_every_derived_revision_and_gets_the_same_digests ... ok +test b5_unregistered_server_key_is_refused_at_admission_and_replay ... ok +test result: ok. 10 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.10s + +## Workspace +# Command: nice -n 19 cargo test --locked --workspace -j 4 +45 test binaries: 342 passed, 0 failed, 1 ignored From 1cf99e0f4c57a6e07158f92f113664b695a8e004 Mon Sep 17 00:00:00 2001 From: Drake Stapleton Date: Sat, 17 Oct 2026 06:53:44 -0500 Subject: [PATCH 4/5] fix(b5): compose with B4 private visibility and signed state moves (#29, #89) Derivation inputs are looked up as the admitting chain may see them, so another owner's Private revision cannot be rebased or merged by a third chain (refused like an input that is not held, at admission and replay). The replica verifier accepts kind 9 state moves that verify and refuses unverified ones (RevisionStateMoveUnverified), the rule strict recovery applies. The B5 fixture now uses real one-link F1 chains and publishes its inputs (Private -> Proposed) before a third chain merges them. Co-Authored-By: Claude Opus 5.5 --- .../tests/b5_derivation_attestation.rs | 165 ++++++++++++++++-- crates/synapse-store/src/revision.rs | 40 +++-- 2 files changed, 183 insertions(+), 22 deletions(-) diff --git a/crates/synapse-api/tests/b5_derivation_attestation.rs b/crates/synapse-api/tests/b5_derivation_attestation.rs index 8d0e442..a03f518 100644 --- a/crates/synapse-api/tests/b5_derivation_attestation.rs +++ b/crates/synapse-api/tests/b5_derivation_attestation.rs @@ -22,11 +22,15 @@ use ed25519_dalek::SigningKey; use sha2::{Digest, Sha256}; use std::path::{Path, PathBuf}; use synapse_api::{SynapseService, TreeTarget}; +use synapse_auth::{ + Capability, CapabilityChain, CapabilityLink, ChainQuotas, ChangeScope, LinkCaveats, + OperationSet, PathScope, ReferenceScope, SignedStateMove, ROOT_PARENT, +}; use synapse_core::{ BlobDigest, ChainPath, ChangeId, ChangesetEnvelopeV2, ChangesetId, DerivationAttestation, DerivationInput, DerivationRule, DerivedRevision, FileMode, GitOid, IdempotencyKey, MergeTier, - MutationOp, PathMutation, RefusalCode, RepoId, RevisionContent, TreeDigest, WalSeq, - WitnessSigner, + MutationOp, PathMutation, RefusalCode, RepoId, RevisionContent, RevisionState, TreeDigest, + WalSeq, WitnessSigner, }; use synapse_radicle::{ IdentityDocumentDigest, IdentityEdit, IdentityLog, RepositoryIdentityDocument, @@ -68,13 +72,47 @@ fn change(s: &str) -> ChangeId { ChangeId(id) } +/// The one-link F1 chain held by `s`: issued by the fixture authority to `key("chain {s}")`. +fn chain(s: &str) -> CapabilityChain { + let caveats = LinkCaveats { + operations: OperationSet::from_capabilities(&[Capability::Read, Capability::Propose]), + paths: PathScope::whole_repository(), + references: ReferenceScope::from_kinds(&[]), + 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: 0, + expires_at_ms: u64::MAX, + }; + CapabilityChain::new(vec![CapabilityLink::issue( + &key("authority"), + ROOT_PARENT, + label(&format!("nonce {s}")), + repo(), + pk(&key(&format!("chain {s}"))), + caveats, + )]) +} + fn authority(s: &str) -> AdmissionAuthority { + let links = chain(s).link_digests().iter().map(|d| d.0).collect(); AdmissionAuthority { - chain: ChainPath::new(vec![label(&format!("chain {s}"))]).unwrap(), + chain: ChainPath::new(links).unwrap(), change_scope: vec![], } } +/// The owner `s` moves its revision `id` to `to` (step B4: a `Private` revision is invisible +/// outside its owner chain until its owner moves it). +fn owner_move(s: &str, id: ChangesetId, to: RevisionState) -> SignedStateMove { + SignedStateMove::sign_new(&key(&format!("chain {s}")), repo(), id, to, &chain(s), NOW).unwrap() +} + fn pk(k: &SigningKey) -> [u8; 32] { k.verifying_key().to_bytes() } @@ -235,6 +273,13 @@ impl Fx { ) .unwrap(); assert!(matches!(out, RevisionOutcome::Admitted { .. })); + // Published, so other chains may name it as a derivation input (step B4). + svc.store_mut() + .advance_revision_state( + owner_move(who, env.changeset_id(), RevisionState::Proposed), + NOW, + ) + .unwrap(); } Self { dir, @@ -380,7 +425,11 @@ fn b5_replica_recomputes_every_derived_revision_and_gets_the_same_digests() { ); } let live = fx.records(); - assert_eq!(fx.verify(&live), Ok(5), "3 agent and 2 derived revisions"); + assert_eq!( + fx.verify(&live), + Ok(8), + "3 agent revisions, their 3 publishing moves and 2 derived revisions" + ); // A replica: reopen from the WAL (base trees registered again), recompute everything. let Fx { @@ -393,7 +442,7 @@ fn b5_replica_recomputes_every_derived_revision_and_gets_the_same_digests() { drop(svc); let mut replica = open(&dir); assert_eq!(replica.store().revision_records(), live.as_slice()); - assert_eq!(replica.verify_revision_log(&keys).unwrap(), 5); + assert_eq!(replica.verify_revision_log(&keys).unwrap(), 8); // Recomputing on the replica gives byte-identical revisions and attestations. let again = replica .derive_revision( @@ -412,7 +461,7 @@ fn b5_replica_recomputes_every_derived_revision_and_gets_the_same_digests() { drop(replica); let mut replica = open(&dir); assert_eq!(replica.store().revision_records(), live.as_slice()); - assert_eq!(replica.verify_revision_log(&keys).unwrap(), 5); + assert_eq!(replica.verify_revision_log(&keys).unwrap(), 8); } #[test] @@ -442,7 +491,7 @@ fn b5_attestation_naming_different_inputs_is_refused_at_admission_and_replay() { fx.refused_at_admission_and_replay(at, forged, RefusalCode::DerivationInputMismatch); // The honest record still verifies. let live = fx.records(); - assert_eq!(fx.verify(&live), Ok(4)); + assert_eq!(fx.verify(&live), Ok(7)); } #[test] @@ -484,7 +533,7 @@ fn b5_attestation_naming_a_different_rule_is_refused_at_admission_and_replay() { ); fx.refused_at_admission(forged, RefusalCode::DerivationInputMismatch); let live = fx.records(); - assert_eq!(fx.verify(&live), Ok(4)); + assert_eq!(fx.verify(&live), Ok(7)); } #[test] @@ -533,7 +582,7 @@ fn b5_unregistered_server_key_is_refused_at_admission_and_replay() { let s_merge = fx.admit(by_s2, "merge").unwrap(); assert!(s_merge >= rotate_at); let live = fx.records(); - assert_eq!(fx.verify(&live), Ok(5), "each verifies at its own sequence"); + assert_eq!(fx.verify(&live), Ok(8), "each verifies at its own sequence"); // At replay, the old key's merge in place of the new key's is refused. let records = fx.records_with(s_merge, derived_record(merge)); assert_eq!( @@ -590,7 +639,7 @@ fn b5_identity_log_of_another_repository_is_refused_at_admission_and_replay() { Err(RefusalCode::DerivationIdentityRepoMismatch), "refused at replay" ); - assert_eq!(fx.verify(&live), Ok(4)); + assert_eq!(fx.verify(&live), Ok(7)); // The same derivation is admitted against this repository's own log. fx.admit(merge, "merge").unwrap(); } @@ -731,7 +780,7 @@ fn b5_recomputation_that_disagrees_is_refused_at_admission_and_replay() { .unwrap_err(); assert_eq!(err.code, RefusalCode::DerivationRecomputeMismatch); let live = fx.records(); - assert_eq!(fx.verify(&live), Ok(4)); + assert_eq!(fx.verify(&live), Ok(7)); } #[test] @@ -762,3 +811,97 @@ fn b5_derivation_written_at_another_sequence_than_it_was_checked_at_is_refused() assert_eq!(fx.admit(honest, "a"), Err(RefusalCode::IoFailure)); assert!(fx.svc.store().committed_seq() > checked_at); } + +/// Step B4 composed with B5: another owner's `Private` revision is not a derivation input. A +/// rebase or merge naming it is refused at admission for any other chain with the code of an +/// input that is not held (`DerivationInputMismatch`), exactly like an unknown revision, and +/// refused at replay when the record carries such a chain; its owner may still admit the rebase. +#[test] +fn b5_another_owners_private_revision_is_not_a_derivation_input() { + let mut fx = Fx::new("private-input"); + // `rd` stays `Private` to its owner "d". + let rd = agent_revision("d", fx.b0, "src/a.rs", b"a1"); + fx.svc + .store_mut() + .admit_revision(rd.clone(), &[], authority("d"), NOW) + .unwrap(); + let rebase = { + let inputs = fx.rebase_inputs(&rd); + fx.derive(DerivationRule::Rebase, inputs) + }; + let merge = { + let mut ids = vec![rd.changeset_id(), fx.rb.changeset_id()]; + ids.sort(); + let mut inputs = vec![DerivationInput::Tree(fx.b0)]; + inputs.extend(ids.into_iter().map(DerivationInput::Revision)); + fx.derive(T0, inputs) + }; + let before = fx.svc.store().committed_seq(); + for (derived, who) in [(&rebase, "b"), (&merge, "merge"), (&merge, "b")] { + assert_eq!( + fx.admit(derived.clone(), who), + Err(RefusalCode::DerivationInputMismatch), + "chain {who} names another owner's private revision" + ); + } + assert_eq!(fx.svc.store().committed_seq(), before, "nothing written"); + + // At replay: the same rebase written under chain "b" is refused. + let mut records = fx.records(); + let honest = records.len(); + records.push(( + before.next(), + WalRecord::DerivedRevisionAdmitted { + derived: rebase.clone(), + chain: authority("b").chain, + admitted_at_ms: NOW, + }, + )); + assert_eq!( + fx.verify(&records), + Err(RefusalCode::DerivationInputMismatch), + "refused at replay" + ); + + // The owner may rebase its own private revision, and the log verifies. + fx.admit(rebase, "d").unwrap(); + let live = fx.records(); + assert_eq!(fx.verify(&live), Ok(honest + 1)); +} + +/// A replica verifies kind 9 state moves like strict recovery does (issue #89): a move whose +/// signature does not verify is refused, not skipped. +#[test] +fn b5_replica_refuses_a_state_move_that_does_not_verify() { + let mut fx = Fx::new("unverified-move"); + let live = fx.records(); + assert_eq!( + fx.verify(&live), + Ok(6), + "3 agent revisions and 3 publishing moves" + ); + let (seq, record) = live + .iter() + .find(|(_, r)| matches!(r, WalRecord::RevisionStateMoved { .. })) + .cloned() + .unwrap(); + let WalRecord::RevisionStateMoved { + mut state_move, + moved_at_ms, + } = record + else { + unreachable!() + }; + state_move.signature[17] ^= 0x01; + let forged = fx.records_with( + seq, + WalRecord::RevisionStateMoved { + state_move, + moved_at_ms, + }, + ); + assert_eq!( + fx.verify(&forged), + Err(RefusalCode::RevisionStateMoveUnverified) + ); +} diff --git a/crates/synapse-store/src/revision.rs b/crates/synapse-store/src/revision.rs index 8fcc088..ad5305b 100644 --- a/crates/synapse-store/src/revision.rs +++ b/crates/synapse-store/src/revision.rs @@ -539,12 +539,14 @@ impl RevisionLedger { /// belong to the attestation's repository (`DerivationIdentityRepoMismatch`); that key is /// the identity document's server key in effect at `at` (`DerivationServerKeyUnregistered`); /// the attestation was not admitted before (`DerivationAttestationReplayed`); the inputs fit - /// the rule and are held (`DerivationInputMismatch`); recomputing the rule on them gives the - /// attested `ChangesetId` and `TreeDigest` (`DerivationRecomputeMismatch`). + /// the rule and are held where `viewer` may see them, so another owner's `Private` revision + /// counts as not held (step B4, `DerivationInputMismatch`); recomputing the rule on them + /// gives the attested `ChangesetId` and `TreeDigest` (`DerivationRecomputeMismatch`). pub(crate) fn check_derivation( &self, derived: &DerivedRevision, at: WalSeq, + viewer: &ChainPath, keys: &dyn ServerKeyRegistry, trees: &mut dyn DerivationTrees, ) -> SynapseResult { @@ -587,8 +589,11 @@ impl RevisionLedger { ), )); } - let lookup = - |input: ChangesetId| self.get_revision(&repo, input).map(|r| r.content.clone()); + // Another owner's `Private` revision is not an input this chain can name (B4). + let lookup = |input: ChangesetId| { + self.get_visible(&repo, input, viewer) + .map(|r| r.content.clone()) + }; let (content, tree) = derive_revision_output(att.rule, &att.inputs, &lookup, trees)?; let recomputed = content.changeset_id(); if recomputed != att.output_changeset || tree != att.output_tree { @@ -741,10 +746,11 @@ impl RevisionLedger { /// signature over its own content: a derived revision presented with an agent signature it /// does not have is refused (`AuthSignatureInvalid`). A marker (kind 8) must verify. A derived /// revision (kind 11) must pass the admission checks of its derivation at its own `WalSeq` -/// (signature, server key registered then, not a replay, inputs admitted before it, the same -/// digests on recomputation). The refusal keeps its code and names the record's `WalSeq`. -/// Returns the number of records verified. Authorization (chains, join rule) and blobs are -/// not re-checked here. +/// (signature, server key registered then, not a replay, inputs admitted before it and +/// visible to the record's chain, the same digests on recomputation). A state move (kind 9) +/// must verify (`RevisionStateMoveUnverified`), the rule strict recovery applies (issue #89). +/// The refusal keeps its code and names the record's `WalSeq`. Returns the number of records +/// verified. Authorization (chains, join rule) and blobs are not re-checked here. pub fn verify_revision_log( records: &[(WalSeq, WalRecord)], keys: &dyn ServerKeyRegistry, @@ -770,11 +776,21 @@ pub fn verify_revision_log( WalRecord::ObsolescenceRecorded { marker, .. } => { marker.validate().map_err(at_seq)?; } - WalRecord::DerivedRevisionAdmitted { derived, .. } => { + WalRecord::DerivedRevisionAdmitted { derived, chain, .. } => { ledger - .check_derivation(derived, *seq, keys, trees) + .check_derivation(derived, *seq, chain, keys, trees) .map_err(at_seq)?; } + WalRecord::RevisionStateMoved { state_move, .. } => { + // The same rule as strict recovery (issue #89): a move that does not verify + // was not written with the mover's key. + state_move.verify().map_err(|fault| { + SynapseError::new( + RefusalCode::RevisionStateMoveUnverified, + format!("state move at {seq} does not verify: {fault:?}"), + ) + })?; + } other => { return Err(SynapseError::new( RefusalCode::WalRecordMalformed, @@ -961,7 +977,9 @@ impl crate::SynapseStore { self.check_writable()?; self.check_binary_codec()?; let at = self.committed_seq().next(); - let id = self.revisions.check_derivation(&derived, at, keys, trees)?; + let id = self + .revisions + .check_derivation(&derived, at, &authority.chain, keys, trees)?; let content = &derived.content; let repo = derived.attestation.repo_id.clone(); if content.mutations.len() > self.limits.max_paths_per_changeset { From 68f1fd413f0ff6bc96d8b6b6cfa541ec8727726a Mon Sep 17 00:00:00 2001 From: Drake Stapleton Date: Sat, 17 Oct 2026 06:54:04 -0500 Subject: [PATCH 5/5] crumb: recompile for B5 rebased on B4 (#29) Co-Authored-By: Claude Opus 5.5 --- .crumb | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/.crumb b/.crumb index 19d9da6..b241b63 100644 --- a/.crumb +++ b/.crumb @@ -45,14 +45,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-17T04:54:09Z", + "compiled_at": "2026-10-17T11:53:58Z", "compiler": "crumb-compile/1", - "digest": "sha256:4cdb9ae207a7ab122fee1ff2da5beeab2aa1265c5a977f58a5ddfb0cad1da526", - "evidence_files": 253, - "evidence_root": "sha256:0a7ffcf9d421b890714f5f8e6a2435cf0d12dca3eaaa9bb1d8e1b9d93656d8b0", - "files": 434, - "generated_at_commit": "0fe7af04c3f15ead80d40ad5dd392ed61ffa9ee1", - "source_tree": "sha256:d7b353d77232c692c35174265114f21eaf6dc31cda7823203c39e5deafcde0e2" + "digest": "sha256:02c07846431e14591967857e7fa02a5123c36d0b7ee1637234a816c911981ce0", + "evidence_files": 257, + "evidence_root": "sha256:209cf73b94ce79f2c68b46628b4936c950ceb96ebc3d93c0575d7510b3bcf2d6", + "files": 443, + "generated_at_commit": "1cf99e0f4c57a6e07158f92f113664b695a8e004", + "source_tree": "sha256:876e335d9234ad209f8621813a3040ec5cbe0a3a2f705f2857245151fd6bfd8f" }, "synapse": { "component_paths": {