synapse
A component of the AienOS ecosystem.
Brought by drakestapleton
GitHub aien-dev/synapse#100 (code only)
Apply it
git checkout -b patch-717b26761d5a31a3 d760aa90b28ced718b884e326440c7bd8657a204 curl -fsSL https://interplane.io/drakestapleton/synapse/patches/717b26761d5a31a3.patch | git am
Provenance
github-import 1
aien-dev/synapse
100
2485c6c424b6583b06844fa9f2e1d8cad46d8495
{"kind":"github-import","owner":"aien-dev","repo":"synapse","number":100,"url":"https://github.com/aien-dev/synapse/pull/100","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:39:10Z","metadata":"unavailable","state_derived":true}
Changes
diff --git a/.crumb b/.crumb index ef0139c..19d9da6 100644 --- a/.crumb +++ b/.crumb @@ -45,14 +45,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-17T02:05:18Z", + "compiled_at": "2026-10-17T04:54:09Z", "compiler": "crumb-compile/1", - "digest": "sha256:dc4cd7bcbb783b35f9006c41f7a7e626fb2a92b8fae48f4098484f96df4f9748", - "evidence_files": 249, - "evidence_root": "sha256:915dd8763ee08d5800437ffd2dd6a59720c9481436ec63a8f4b82effe81ced16", - "files": 428, - "generated_at_commit": "157f1c83674df84a0fe9f4a6205a9f891a7b2ce3", - "source_tree": "sha256:f72e4965b6aa26c5ce6ebdab8a641969bdf4fedc3e10a31d9da58a881db5f13c" + "digest": "sha256:4cdb9ae207a7ab122fee1ff2da5beeab2aa1265c5a977f58a5ddfb0cad1da526", + "evidence_files": 253, + "evidence_root": "sha256:0a7ffcf9d421b890714f5f8e6a2435cf0d12dca3eaaa9bb1d8e1b9d93656d8b0", + "files": 434, + "generated_at_commit": "0fe7af04c3f15ead80d40ad5dd392ed61ffa9ee1", + "source_tree": "sha256:d7b353d77232c692c35174265114f21eaf6dc31cda7823203c39e5deafcde0e2" }, "synapse": { "component_paths": { diff --git a/Cargo.lock b/Cargo.lock index 8fb6001..8bbeb95 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -498,6 +498,7 @@ dependencies = [ "serde", "serde_json", "sha2", + "synapse-auth", "synapse-core", ] diff --git a/crates/synapse-api/src/lib.rs b/crates/synapse-api/src/lib.rs index e702ab7..c30f69b 100644 --- a/crates/synapse-api/src/lib.rs +++ b/crates/synapse-api/src/lib.rs @@ -2,6 +2,7 @@ //! store with a bounded cache (`tree`, ADR 0003 step C1), exact `PathIndex` invalidation, and //! durable subscription cursors (`synapse-api`, Gate 2b). +use ed25519_dalek::SigningKey; use serde::{Deserialize, Serialize}; use std::collections::{BTreeMap, BTreeSet}; use std::fs::{self, File}; @@ -9,7 +10,8 @@ use std::io::Write; use std::path::{Path, PathBuf}; use std::process::Command; use synapse_auth::{ - AuditEntry, AuthenticatedRequest, BoundaryKind, Capability, ChainedRequest, PolicyEnforcer, + AuditEntry, AuthenticatedRequest, BoundaryKind, Capability, CapabilityChain, ChainedRequest, + PolicyEnforcer, SignedStateMove, }; use synapse_core::{ validate_repo_relative_path, BlobDigest, ChangesetEnvelope, ChangesetId, EvidenceAttachment, @@ -239,37 +241,77 @@ pub struct WatchQueryPayload { pub page: PageRequest, } -/// Request payload for `advance_revision_state` (ADR 0003 B4), in its one binary encoding: -/// `changeset_id [32] | state u8` (the `RevisionState` tag, 1..=5). +/// Request payload for `advance_revision_state` (ADR 0003 B4, issue #89), in its one binary +/// encoding: `changeset_id [32] | state u8 | signed_at_ms u64 | signature [64]` (105 bytes). +/// `signature` is the request agent's Ed25519 signature over +/// [`SignedStateMove::statement_bytes`] for the service's repository, this revision and +/// state, the request's chain, and `signed_at_ms`; the store records it with the move. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct RevisionStateMovePayload { pub changeset_id: ChangesetId, pub to: RevisionState, + pub signed_at_ms: u64, + pub signature: [u8; 64], } impl RevisionStateMovePayload { + /// Encoded size. + pub const LEN: usize = 32 + 1 + 8 + 64; + + /// Sign a move of `changeset_id` of `repo_id` to `to` as `agent`, the leaf audience of + /// `chain`, at the agent's time `signed_at_ms`. + pub fn sign_new( + agent: &SigningKey, + repo_id: &RepoId, + chain: &CapabilityChain, + changeset_id: ChangesetId, + to: RevisionState, + signed_at_ms: u64, + ) -> SynapseResult<Self> { + let path = ChainPath::new(chain.link_digests().iter().map(|d| d.0).collect())?; + Ok(Self { + changeset_id, + to, + signed_at_ms, + signature: SignedStateMove::sign_statement( + agent, + repo_id, + changeset_id, + to, + &path, + signed_at_ms, + ), + }) + } + pub fn encode(&self) -> Vec<u8> { - let mut buf = Vec::with_capacity(33); + let mut buf = Vec::with_capacity(Self::LEN); buf.extend_from_slice(&self.changeset_id.0); buf.push(self.to.tag_byte()); + buf.extend_from_slice(&self.signed_at_ms.to_le_bytes()); + buf.extend_from_slice(&self.signature); buf } - /// Exactly 33 bytes with a known state tag; anything else is `EnvelopeMalformed`. + /// Exactly 105 bytes with a known state tag; anything else is `EnvelopeMalformed`. pub fn decode(bytes: &[u8]) -> SynapseResult<Self> { let malformed = || { SynapseError::new( RefusalCode::EnvelopeMalformed, - "state move payload must be changeset_id [32] | state u8 (1..=5)", + "state move payload must be changeset_id [32] | state u8 (1..=5) | signed_at_ms u64 | signature [64]", ) }; - let (id, tag) = match bytes { - [id @ .., tag] if id.len() == 32 => (id, *tag), - _ => return Err(malformed()), - }; + if bytes.len() != Self::LEN { + return Err(malformed()); + } + let (id, rest) = bytes.split_at(32); + let (tag, rest) = rest.split_at(1); + let (at, sig) = rest.split_at(8); Ok(Self { changeset_id: ChangesetId(id.try_into().map_err(|_| malformed())?), - to: RevisionState::from_tag_byte(tag).ok_or_else(malformed)?, + to: RevisionState::from_tag_byte(tag[0]).ok_or_else(malformed)?, + signed_at_ms: u64::from_le_bytes(at.try_into().map_err(|_| malformed())?), + signature: sig.try_into().map_err(|_| malformed())?, }) } } @@ -666,8 +708,11 @@ impl SynapseService { } /// Move a revision's state (ADR 0003 B4) under an F1 delegation chain granting - /// `Propose`. `req.payload` is a [`RevisionStateMovePayload`]. The store applies the - /// owner-chain and state-machine rules: any move to `Canonical` is refused + /// `Propose`. `req.payload` is a [`RevisionStateMovePayload`]: the request agent (the + /// chain's leaf audience) must sign the move itself (issue #89), and the store records + /// that signature with the chain's leaf link, so replay can check the mover. A signature + /// that does not verify is `AuthSignatureInvalid`. The store applies the owner-chain and + /// state-machine rules: any move to `Canonical` is refused /// (`CanonicalOutsidePromotionQueue`; canonical moves only through the promotion queue, /// step E2), another owner's `Private` revision is `ChangesetNotFound`, a chain that does /// not own the revision is `AuthChainNotDominant`, and a move to `Verified` or any move @@ -687,9 +732,20 @@ impl SynapseService { self.store.committed_seq().next(), now_ms, )?; - let chain = admission_authority(req)?.chain; - self.store - .advance_revision_state(&self.repo_id, mv.changeset_id, mv.to, chain, now_ms) + let leaf_link = req.chain.leaf().cloned().ok_or_else(|| { + SynapseError::new(RefusalCode::AuthChainBroken, "state move: empty chain") + })?; + let state_move = SignedStateMove { + repo_id: self.repo_id.clone(), + changeset_id: mv.changeset_id, + to: mv.to, + chain: admission_authority(req)?.chain, + signed_at_ms: mv.signed_at_ms, + leaf_link, + mover_key: req.agent_key, + signature: mv.signature, + }; + self.store.advance_revision_state(state_move, now_ms) } /// Read an envelope v2 revision (ADR 0003 B4) under an F1 delegation chain granting diff --git a/crates/synapse-api/tests/b1_chained_revisions.rs b/crates/synapse-api/tests/b1_chained_revisions.rs index 1bba5e8..1240c45 100644 --- a/crates/synapse-api/tests/b1_chained_revisions.rs +++ b/crates/synapse-api/tests/b1_chained_revisions.rs @@ -205,10 +205,15 @@ impl Fx { /// The owner shares a revision (ADR 0003 B4): `Private` -> `Draft`, so chains outside /// its owner chain see it and are refused for dominance rather than as unknown. fn share(&mut self, who: &(SigningKey, CapabilityChain), rev: ChangesetId) { - let payload = RevisionStateMovePayload { - changeset_id: rev, - to: RevisionState::Draft, - } + let payload = RevisionStateMovePayload::sign_new( + &who.0, + &repo(), + &who.1, + rev, + RevisionState::Draft, + NOW, + ) + .unwrap() .encode(); let req = self.request(who, vec![], payload); self.svc.advance_revision_state(&req, NOW).unwrap(); diff --git a/crates/synapse-api/tests/b4_revision_states.rs b/crates/synapse-api/tests/b4_revision_states.rs index 8bc7c1b..7ea75a5 100644 --- a/crates/synapse-api/tests/b4_revision_states.rs +++ b/crates/synapse-api/tests/b4_revision_states.rs @@ -248,11 +248,9 @@ impl Fx { id: ChangesetId, to: RevisionState, ) -> Result<WalSeq, RefusalCode> { - let payload = RevisionStateMovePayload { - changeset_id: id, - to, - } - .encode(); + let payload = RevisionStateMovePayload::sign_new(&who.0, &repo(), &who.1, id, to, NOW) + .unwrap() + .encode(); let req = self.request(who, Capability::Propose, RequestScope::default(), payload); self.svc .advance_revision_state(&req, NOW) @@ -340,11 +338,10 @@ fn b4_api_move_to_canonical_outside_the_promotion_queue_is_refused() { } } // Asking with the canonical reference in the request scope changes nothing. - let payload = RevisionStateMovePayload { - changeset_id: rev, - to: RevisionState::Canonical, - } - .encode(); + let payload = + RevisionStateMovePayload::sign_new(&p.0, &repo(), &p.1, rev, RevisionState::Canonical, NOW) + .unwrap() + .encode(); let scope = RequestScope { paths: vec![], reference: Some(ReferenceKind::CanonicalViaPromotionQueue), @@ -364,10 +361,18 @@ fn b4_api_move_to_canonical_outside_the_promotion_queue_is_refused() { fx.svc.store().get_revision(&repo(), rev).unwrap().state, RevisionState::Proposed ); - // Payloads: exactly changeset_id [32] | state 1..=5. - let mut bad_tag = rev.0.to_vec(); - bad_tag.push(6); - for payload in [vec![], rev.0.to_vec(), bad_tag, vec![0; 34]] { + // Payloads: exactly changeset_id [32] | state 1..=5 | signed_at_ms u64 | signature [64]. + let good = + RevisionStateMovePayload::sign_new(&w.0, &repo(), &w.1, rev, RevisionState::Draft, NOW) + .unwrap() + .encode(); + assert_eq!(good.len(), RevisionStateMovePayload::LEN); + let mut bad_tag = good.clone(); + bad_tag[32] = 6; + let mut longer = good.clone(); + longer.push(0); + let v1_layout = good[..33].to_vec(); + for payload in [vec![], v1_layout, bad_tag, good[..104].to_vec(), longer] { let req = fx.request(&w, Capability::Propose, RequestScope::default(), payload); assert_eq!( fx.svc.advance_revision_state(&req, NOW).unwrap_err().code, @@ -414,3 +419,57 @@ fn b4_api_joining_identical_content_grants_no_ownership_of_a_private_revision() RefusalCode::AuthChainNotDominant ); } + +/// Issue #89: the request agent must sign the move itself. A payload signed by another key +/// (even the owner's ancestor `O`), or whose signature covers another state, chain, or time, +/// is `AuthSignatureInvalid` and writes nothing. The agent's own signed move is recorded with +/// its signature and the chain's leaf link, and still applies after a reopen (strict recovery). +#[test] +fn b89_api_state_moves_must_be_signed_by_the_request_agent() { + let mut fx = Fx::new("signed"); + let (o, w) = (fx.o.clone(), fx.w.clone()); + let rev = fx.submit(&w, b"worker attempt", 1); + let before = fx.svc.store().committed_seq(); + let signed = |by: &Agent, chain_of: &Agent, to: RevisionState| { + RevisionStateMovePayload::sign_new(&by.0, &repo(), &chain_of.1, rev, to, NOW).unwrap() + }; + let mut other_state = signed(&w, &w, RevisionState::Proposed); + other_state.to = RevisionState::Draft; + let mut other_time = signed(&w, &w, RevisionState::Draft); + other_time.signed_at_ms += 1; + let mut flipped = signed(&w, &w, RevisionState::Draft); + flipped.signature[0] ^= 1; + for payload in [ + signed(&o, &w, RevisionState::Draft), + signed(&w, &o, RevisionState::Draft), + other_state, + other_time, + flipped, + ] { + let req = fx.request( + &w, + Capability::Propose, + RequestScope::default(), + payload.encode(), + ); + assert_eq!( + fx.svc.advance_revision_state(&req, NOW).unwrap_err().code, + RefusalCode::AuthSignatureInvalid + ); + } + assert_eq!(fx.svc.store().committed_seq(), before, "nothing written"); + assert_eq!( + fx.svc.store().get_revision(&repo(), rev).unwrap().state, + RevisionState::Private + ); + fx.mv(&w, rev, RevisionState::Draft).unwrap(); + assert_eq!( + fx.svc.store().get_revision(&repo(), rev).unwrap().state, + RevisionState::Draft + ); + assert_eq!( + fx.svc.store().state_move_replay_report(), + Default::default(), + "a store's own writes are never counted" + ); +} diff --git a/crates/synapse-auth/src/lib.rs b/crates/synapse-auth/src/lib.rs index 8fc4cbc..ccf6e99 100644 --- a/crates/synapse-auth/src/lib.rs +++ b/crates/synapse-auth/src/lib.rs @@ -11,7 +11,9 @@ use synapse_core::{ }; mod chain; +mod state_move; pub use chain::*; +pub use state_move::*; /// Current capability grant schema version. pub const CAPABILITY_GRANT_VERSION: u16 = 1; diff --git a/crates/synapse-auth/src/state_move.rs b/crates/synapse-auth/src/state_move.rs new file mode 100644 index 0000000..ee1eefe --- /dev/null +++ b/crates/synapse-auth/src/state_move.rs @@ -0,0 +1,371 @@ +//! Signed revision state moves (ADR 0003 sections 5.3 and 5.4, step B4; issue #89). +//! +//! Section 5.4: every operation records the actor and the capability chain used. A state +//! move (WAL kind 9) therefore carries the mover's key and its strict Ed25519 signature over +//! the move under [`DOMAIN_STATE_MOVE_SIGN_V1`], as an obsolescence marker does, and the +//! leaf link of the chain it was made under. The chain is a list of link digests, so the +//! leaf link is what ties the mover key to the chain: its digest must be the chain's last +//! digest, its parent the digest before it (or [`ROOT_PARENT`] for a one-link chain), its +//! repository the move's repository, and its audience the mover key. Replay checks all of +//! this from the record alone, so a record written into the WAL without the private key of +//! the chain's leaf never verifies. See `docs/B4_REVISION_STATES.md`. + +use crate::{CapabilityChain, CapabilityLink, ROOT_PARENT}; +use ed25519_dalek::{Signature, Signer, SigningKey, VerifyingKey}; +use synapse_core::{ + ChainPath, ChangesetId, RefusalCode, RepoId, RevisionState, SynapseError, SynapseResult, +}; + +/// Domain tag of the mover's Ed25519 signature over a revision state move. +pub const DOMAIN_STATE_MOVE_SIGN_V1: &[u8] = b"SYNAPSE_STATE_MOVE_SIGN_V1\0"; + +/// Why a signed state move does not verify. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum StateMoveFault { + /// The mover key is not an Ed25519 key, or the signature does not verify strictly over + /// [`SignedStateMove::signable_bytes`]. + SignatureInvalid, + /// The leaf link is not the leaf of the move's chain (its digest, parent, or repository + /// differ), or the mover key is not the leaf link's audience. + SignerNotChainLeaf, +} + +impl StateMoveFault { + /// The refusal of a live request carrying this fault (`AuthSignatureInvalid`, as for an + /// envelope whose author is not the chain's leaf audience). + pub fn into_error(self) -> SynapseError { + let msg = match self { + Self::SignatureInvalid => "state move: mover signature does not verify", + Self::SignerNotChainLeaf => { + "state move: the mover key is not the audience of the chain's leaf link" + } + }; + SynapseError::new(RefusalCode::AuthSignatureInvalid, msg) + } +} + +/// A revision state move signed by its mover: revision `changeset_id` of `repo_id` moves to +/// `to` under `chain`, signed at the mover's time `signed_at_ms` by `mover_key`, the +/// audience of `leaf_link` (the chain's leaf link). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SignedStateMove { + pub repo_id: RepoId, + pub changeset_id: ChangesetId, + pub to: RevisionState, + pub chain: ChainPath, + pub signed_at_ms: u64, + pub leaf_link: CapabilityLink, + pub mover_key: [u8; 32], + pub signature: [u8; 64], +} + +impl SignedStateMove { + /// `DOMAIN_STATE_MOVE_SIGN_V1 || u32 len | repo_id || changeset_id [32] || to u8 || + /// chain (u8 count | link digest [32]*) || signed_at_ms u64`: what the mover signs. + pub fn statement_bytes( + repo_id: &RepoId, + changeset_id: ChangesetId, + to: RevisionState, + chain: &ChainPath, + signed_at_ms: u64, + ) -> Vec<u8> { + let repo = repo_id.as_str().as_bytes(); + let mut buf = Vec::with_capacity( + DOMAIN_STATE_MOVE_SIGN_V1.len() + 4 + repo.len() + 32 + 1 + 1 + 32 * 16 + 8, + ); + buf.extend_from_slice(DOMAIN_STATE_MOVE_SIGN_V1); + buf.extend_from_slice(&(repo.len() as u32).to_le_bytes()); + buf.extend_from_slice(repo); + buf.extend_from_slice(&changeset_id.0); + buf.push(to.tag_byte()); + chain.encode_into(&mut buf); + buf.extend_from_slice(&signed_at_ms.to_le_bytes()); + buf + } + + /// The mover's signature over [`Self::statement_bytes`]. + pub fn sign_statement( + mover: &SigningKey, + repo_id: &RepoId, + changeset_id: ChangesetId, + to: RevisionState, + chain: &ChainPath, + signed_at_ms: u64, + ) -> [u8; 64] { + mover + .sign(&Self::statement_bytes( + repo_id, + changeset_id, + to, + chain, + signed_at_ms, + )) + .to_bytes() + } + + /// Build and sign a move under the F1 chain `chain` (its link digests and its leaf link). + /// An empty chain is `AuthChainBroken`. + pub fn sign_new( + mover: &SigningKey, + repo_id: RepoId, + changeset_id: ChangesetId, + to: RevisionState, + chain: &CapabilityChain, + signed_at_ms: u64, + ) -> SynapseResult<Self> { + let leaf_link = chain.leaf().cloned().ok_or_else(|| { + SynapseError::new(RefusalCode::AuthChainBroken, "state move: empty chain") + })?; + let path = ChainPath::new(chain.link_digests().iter().map(|d| d.0).collect())?; + let signature = + Self::sign_statement(mover, &repo_id, changeset_id, to, &path, signed_at_ms); + Ok(Self { + repo_id, + changeset_id, + to, + chain: path, + signed_at_ms, + leaf_link, + mover_key: mover.verifying_key().to_bytes(), + signature, + }) + } + + /// [`Self::statement_bytes`] of this move. + pub fn signable_bytes(&self) -> Vec<u8> { + Self::statement_bytes( + &self.repo_id, + self.changeset_id, + self.to, + &self.chain, + self.signed_at_ms, + ) + } + + /// The signature verifies strictly under `mover_key`, and `mover_key` is the audience + /// of the chain's leaf link: `leaf_link` hashes to the chain's last digest, names the + /// digest before it as its parent (`ROOT_PARENT` for a one-link chain), and belongs to + /// the move's repository. A pure function of the move, so replay gives the same verdict + /// as the live store. + /// + /// **This binds the signer to the chain; it does not authorize the move.** It never + /// checks who issued `leaf_link`, nor its caveats, so anyone can mint a root link of + /// their own, or append a link of their own under someone else's chain, and sign a + /// move that verifies. Precondition for every caller: the chain must also be, or + /// dominate, the chain of the revision's first admission (`ChainPath::dominates`, as + /// the store's owner rule does). Dominance pins every digest of the chain, the leaf + /// included, to links that were really admitted. A descendant chain (`descends_from`) + /// is not enough: its extra links are unchecked. + pub fn verify(&self) -> Result<(), StateMoveFault> { + let key = VerifyingKey::from_bytes(&self.mover_key) + .map_err(|_| StateMoveFault::SignatureInvalid)?; + key.verify_strict( + &self.signable_bytes(), + &Signature::from_bytes(&self.signature), + ) + .map_err(|_| StateMoveFault::SignatureInvalid)?; + let links = self.chain.links(); + let (leaf, ancestors) = links + .split_last() + .ok_or(StateMoveFault::SignerNotChainLeaf)?; + let parent = ancestors.last().copied().unwrap_or(ROOT_PARENT.0); + let link = &self.leaf_link; + if link.digest().0 != *leaf + || link.parent.0 != parent + || link.repo_id != self.repo_id + || link.audience_key != self.mover_key + { + return Err(StateMoveFault::SignerNotChainLeaf); + } + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{ + Capability, ChainQuotas, ChangeScope, LinkCaveats, LinkDigest, OperationSet, PathScope, + ReferenceScope, + }; + use sha2::{Digest, Sha256}; + + /// Keys and nonces are SHA-256 of a label, never fixed byte values. + fn derived(label: &str) -> [u8; 32] { + Sha256::digest(label.as_bytes()).into() + } + + fn key(label: &str) -> SigningKey { + SigningKey::from_bytes(&derived(label)) + } + + fn repo() -> RepoId { + RepoId::new("aien-spark/synapse").unwrap() + } + + fn caveats() -> LinkCaveats { + 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: 100, + window_duration_ms: 60_000, + storage_bytes: 1 << 20, + footprint_paths: 64, + max_bytes_per_op: 1 << 20, + }, + issued_at_ms: 0, + expires_at_ms: u64::MAX, + } + } + + fn link( + issuer: &SigningKey, + parent: LinkDigest, + to: &SigningKey, + label: &str, + ) -> CapabilityLink { + CapabilityLink::issue( + issuer, + parent, + derived(label), + repo(), + to.verifying_key().to_bytes(), + caveats(), + ) + } + + /// Authority -> orchestrator -> worker. + fn chains() -> (SigningKey, SigningKey, CapabilityChain, CapabilityChain) { + let authority = key("state-move authority"); + let orchestrator = key("state-move orchestrator"); + let worker = key("state-move worker"); + let root = link( + &authority, + ROOT_PARENT, + &orchestrator, + "state-move root link", + ); + let child = link( + &orchestrator, + root.digest(), + &worker, + "state-move child link", + ); + let co = CapabilityChain::new(vec![root]); + let cw = co.extended(child); + (orchestrator, worker, co, cw) + } + + fn id() -> ChangesetId { + ChangesetId(derived("state-move changeset")) + } + + #[test] + fn a_move_signed_by_the_chain_leaf_verifies_for_root_and_derived_chains() { + let (o, w, co, cw) = chains(); + for (k, c) in [(&o, &co), (&w, &cw)] { + let m = SignedStateMove::sign_new(k, repo(), id(), RevisionState::Draft, c, 7).unwrap(); + assert_eq!(m.verify(), Ok(())); + } + } + + #[test] + fn a_bad_signature_or_a_signer_that_is_not_the_leaf_is_refused_typed() { + let (o, w, co, cw) = chains(); + let good = + SignedStateMove::sign_new(&w, repo(), id(), RevisionState::Draft, &cw, 7).unwrap(); + + // Any change to a signed field breaks the signature. + let mut m = good.clone(); + m.to = RevisionState::Proposed; + assert_eq!(m.verify(), Err(StateMoveFault::SignatureInvalid)); + let mut m = good.clone(); + m.signed_at_ms += 1; + assert_eq!(m.verify(), Err(StateMoveFault::SignatureInvalid)); + let mut m = good.clone(); + m.signature[0] ^= 1; + assert_eq!(m.verify(), Err(StateMoveFault::SignatureInvalid)); + let mut m = good.clone(); + m.mover_key = derived("state-move not the mover"); + assert_eq!(m.verify(), Err(StateMoveFault::SignatureInvalid)); + + // A valid signature by the orchestrator over the worker's chain: the orchestrator is + // an ancestor, not the leaf, so it must sign under its own chain instead. + let m = SignedStateMove { + mover_key: o.verifying_key().to_bytes(), + signature: SignedStateMove::sign_statement( + &o, + &repo(), + id(), + RevisionState::Draft, + &good.chain, + 7, + ), + ..good.clone() + }; + assert_eq!(m.verify(), Err(StateMoveFault::SignerNotChainLeaf)); + + // A leaf link that is not the chain's leaf (the root link under the worker's chain). + let m = SignedStateMove { + leaf_link: co.leaf().unwrap().clone(), + ..good.clone() + }; + assert_eq!(m.verify(), Err(StateMoveFault::SignerNotChainLeaf)); + + // A self-issued link whose audience is the signer, named as a one-link chain whose + // digest is that link: the parent is not the root, so it is not this chain's leaf + // unless it really is a root link. A forger can mint such a root link, but then the + // chain is its own and never dominates another owner's chain (section 5.3). + let forger = key("state-move forger"); + let fake = link( + &forger, + LinkDigest(*good.chain.links().first().unwrap()), + &forger, + "fake", + ); + let path = ChainPath::new(vec![good.chain.links()[0], fake.digest().0]).unwrap(); + let m = SignedStateMove { + chain: path.clone(), + leaf_link: fake, + mover_key: forger.verifying_key().to_bytes(), + signature: SignedStateMove::sign_statement( + &forger, + &repo(), + id(), + RevisionState::Draft, + &path, + 7, + ), + ..good.clone() + }; + assert_eq!( + m.verify(), + Ok(()), + "the record alone binds key to chain digests" + ); + assert_ne!(m.chain, good.chain, "but never to another chain's digests"); + } + + #[test] + fn a_leaf_link_of_another_repository_is_refused() { + let (_, w, _, cw) = chains(); + let mut m = + SignedStateMove::sign_new(&w, repo(), id(), RevisionState::Draft, &cw, 7).unwrap(); + m.repo_id = RepoId::new("aien-spark/other").unwrap(); + m.signature = SignedStateMove::sign_statement(&w, &m.repo_id, id(), m.to, &m.chain, 7); + assert_eq!(m.verify(), Err(StateMoveFault::SignerNotChainLeaf)); + } + + #[test] + fn faults_map_to_auth_signature_invalid() { + for f in [ + StateMoveFault::SignatureInvalid, + StateMoveFault::SignerNotChainLeaf, + ] { + assert_eq!(f.into_error().code, RefusalCode::AuthSignatureInvalid); + } + } +} diff --git a/crates/synapse-core/src/lib.rs b/crates/synapse-core/src/lib.rs index ccd494c..cc43a11 100644 --- a/crates/synapse-core/src/lib.rs +++ b/crates/synapse-core/src/lib.rs @@ -139,6 +139,10 @@ pub enum RefusalCode { /// A move of a revision to `Canonical` that does not come from the promotion queue /// (ADR 0003 sections 5.3 and 5.5, step B4). CanonicalOutsidePromotionQueue, + /// Strict recovery found a WAL kind 9 state move whose mover signature does not verify + /// 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, // Git and Radicle canonicality refusals GitObjectCorrupt, diff --git a/crates/synapse-store/Cargo.toml b/crates/synapse-store/Cargo.toml index 34588f6..5119311 100644 --- a/crates/synapse-store/Cargo.toml +++ b/crates/synapse-store/Cargo.toml @@ -13,4 +13,5 @@ hex.workspace = true serde.workspace = true serde_json.workspace = true sha2.workspace = true +synapse-auth.workspace = true synapse-core.workspace = true diff --git a/crates/synapse-store/src/codec.rs b/crates/synapse-store/src/codec.rs index 4344c46..c63e2dd 100644 --- a/crates/synapse-store/src/codec.rs +++ b/crates/synapse-store/src/codec.rs @@ -18,6 +18,7 @@ //! huge length is refused without allocating it. use super::*; +use synapse_auth::CapabilityLink; use synapse_core::{FileMode, GitOid, PathMutation}; /// Codec version byte that starts every binary record and checkpoint content. @@ -341,17 +342,18 @@ pub fn encode_record(record: &WalRecord) -> SynapseResult<Vec<u8>> { w.u64(*recorded_at_ms); } WalRecord::RevisionStateMoved { - repo_id, - changeset_id, - to, - chain, + state_move: m, moved_at_ms, } => { - w.repo(repo_id)?; - w.raw(&changeset_id.0); - w.u8(to.tag_byte()); - put_chain(&mut w, chain)?; + w.repo(&m.repo_id)?; + w.raw(&m.changeset_id.0); + w.u8(m.to.tag_byte()); + put_chain(&mut w, &m.chain)?; w.u64(*moved_at_ms); + w.u64(m.signed_at_ms); + w.bytes(&m.leaf_link.encode(), "leaf link")?; + w.raw(&m.mover_key); + w.raw(&m.signature); } } Ok(w.0) @@ -754,12 +756,20 @@ pub fn decode_record(bytes: &[u8], cap: u64) -> Result<WalRecord, CodecRefusal> field: "revision state", tag, })?; + let chain = r.embedded("chain path", ChainPath::decode)?; + let moved_at_ms = r.u64()?; WalRecord::RevisionStateMoved { - repo_id, - changeset_id, - to, - chain: r.embedded("chain path", ChainPath::decode)?, - moved_at_ms: r.u64()?, + state_move: SignedStateMove { + repo_id, + changeset_id, + to, + chain, + signed_at_ms: r.u64()?, + leaf_link: r.embedded("leaf link", CapabilityLink::decode)?, + mover_key: r.array()?, + signature: r.array()?, + }, + moved_at_ms, } } tag => { diff --git a/crates/synapse-store/src/lib.rs b/crates/synapse-store/src/lib.rs index 590340a..2f2cdf6 100644 --- a/crates/synapse-store/src/lib.rs +++ b/crates/synapse-store/src/lib.rs @@ -19,6 +19,7 @@ use std::collections::{BTreeMap, BTreeSet}; use std::fs::{self, File, OpenOptions}; 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, @@ -39,8 +40,8 @@ pub mod wal2; pub use codec::{CheckpointChain, CheckpointState, CodecRefusal, RecordCodec}; pub use revision::{ - AdmissionAuthority, ChangeStatus, RecordedMarker, RevisionOutcome, StoredRevision, - DOMAIN_STATE_ROOT_REVISIONS_V1, + AdmissionAuthority, ChangeStatus, RecordedMarker, RevisionOutcome, StateMoveReplayReport, + StoredRevision, DOMAIN_STATE_ROOT_REVISIONS_V1, }; pub use shared::{GroupCommitStats, SharedStore}; @@ -323,14 +324,12 @@ pub enum WalRecord { chain: ChainPath, recorded_at_ms: u64, }, - /// A move of revision `changeset_id` of `repo_id` to state `to`, asked for under `chain` at - /// server time `moved_at_ms` (ADR 0003 B4). Binary codec only. + /// A move of a revision to another state, signed by its mover (the audience of the + /// chain's leaf link) and recorded at server time `moved_at_ms` (ADR 0003 B4, issue + /// #89). Binary codec only. #[serde(skip)] RevisionStateMoved { - repo_id: RepoId, - changeset_id: ChangesetId, - to: RevisionState, - chain: ChainPath, + state_move: SignedStateMove, moved_at_ms: u64, }, } @@ -1679,7 +1678,12 @@ impl SynapseStore { // The first binary checkpoint records the last v1 state root (or the empty // root for a store that never wrote v1) and chains its own root to it; every // later one chains to the previous checkpoint root. + // Unverified kind 9 records (kept as no-ops only under `TruncateTornTail`) are left + // out (review of PR #100): they change no state, and carrying them would make + // strict recovery refuse the store forever. The ledger is rebuilt without them + // only once the checkpoint is durable; the replay report counts them. self.sync_wal()?; + let (revision_log, dropped_moves) = self.revisions.log_without_unverified_moves(); let (v1_state_root, prev_checkpoint_root) = match self.checkpoint_chain { Some(c) => (c.v1_state_root, c.checkpoint_root), None if self.v1_history => (v1_state_root_at_entry, v1_state_root_at_entry), @@ -1693,7 +1697,7 @@ impl SynapseStore { blob_first_visible_seq: std::mem::take(&mut self.blob_first_visible_seq), github_projections: std::mem::take(&mut self.github_projections), canonical_heads: std::mem::take(&mut self.canonical_heads), - revision_log: self.revisions.log().to_vec(), + revision_log, }; let encoded = codec::encode_checkpoint_v2(&state, v1_state_root, prev_checkpoint_root); self.changesets = state.changesets; @@ -1701,10 +1705,14 @@ impl SynapseStore { self.blob_first_visible_seq = state.blob_first_visible_seq; self.github_projections = state.github_projections; self.canonical_heads = state.canonical_heads; + let revision_log = state.revision_log; let (bytes, chain) = encoded?; - // Read back what will be written: it must decode to the same chain and root. + // Read back what will be written: it must decode to the same chain and root (the + // live state, less any unverified kind 9 records left out above). + let snap = self.resolve_snapshot_seq(None, None)?; + let expected_root = codec::state_root_of(&self.changesets, &revision_log, snap); let (_, check) = codec::decode_checkpoint_v2(&bytes)?; - if check != chain || chain.state_root != self.state_root_digest(None)? { + if check != chain || chain.state_root != expected_root { return Err(SynapseError::new( RefusalCode::CheckpointCorrupt, "checkpoint.v2 does not decode back to the state it was written from", @@ -1743,6 +1751,10 @@ impl SynapseStore { &bytes, )?; self.checkpoint_chain = Some(chain); + if dropped_moves > 0 { + self.revisions + .rebuild_after_compaction(revision_log, dropped_moves); + } self.codec = RecordCodec::BinaryV2; self.binary_seen = true; // checkpoint.v1 becomes the tombstone only after checkpoint.v2 is durable. @@ -2209,7 +2221,24 @@ impl SynapseStore { self.recover_v2(recovery_policy, &mut overlap)?; overlap.close(self.committed_seq, self.last_frame_sha256)?; - // 3. A store with v1 history keeps writing v1 JSON until its first binary + // 3. A state move that does not verify was written without the mover's key: the + // unkeyed seal cannot tell a forgery from a store's write, so strict recovery + // refuses the store instead of hiding it as a no-op (issue #89). It checks the + // records themselves, so a forgery inside a resealed checkpoint is refused too. + if recovery_policy == RecoveryPolicy::StrictFailClosed { + let report = self.revisions.state_move_report(); + if let Some((seq, fault)) = report.first_unverified { + return Err(SynapseError::new( + RefusalCode::RevisionStateMoveUnverified, + format!( + "{} WAL kind 9 state move(s) do not verify (first at {seq}: {fault:?}); strict recovery refuses the store (open it with TruncateTornTail and run checkpoint_and_compact to drop them)", + report.unverified() + ), + )); + } + } + + // 4. A store with v1 history keeps writing v1 JSON until its first binary // checkpoint (the migration checkpoint); every other store writes binary v2. self.codec = if self.checkpoint_chain.is_some() || !self.v1_history { RecordCodec::BinaryV2 diff --git a/crates/synapse-store/src/revision.rs b/crates/synapse-store/src/revision.rs index 87dd68f..7ca15bd 100644 --- a/crates/synapse-store/src/revision.rs +++ b/crates/synapse-store/src/revision.rs @@ -9,7 +9,7 @@ //! same ledger. v1 changesets stay in their own map with their own IDs; the two ID domains //! never meet. -use crate::WalRecord; +use crate::{SignedStateMove, StateMoveFault, WalRecord}; use sha2::{Digest, Sha256}; use std::collections::{BTreeMap, BTreeSet}; use synapse_core::{ @@ -100,6 +100,36 @@ struct ChangeEntry { markers: Vec<RecordedMarker>, } +/// What replay did with WAL kind 9 state moves that changed nothing (ADR 0003 B4, issue +/// #89). A live store writes only moves that verify and are owner moves, so every count here +/// is a record written without the store: a forgery or a bug, never a normal event. +/// `StrictFailClosed` recovery refuses a store with any unverified move +/// (`RevisionStateMoveUnverified`); `TruncateTornTail` opens it with the moves applied as +/// no-ops and reports them here. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct StateMoveReplayReport { + /// Moves whose mover signature does not verify strictly. + pub signature_invalid: u64, + /// Moves whose mover key is not the audience of their chain's leaf link. + pub signer_not_chain_leaf: u64, + /// Verified moves that are not owner moves: not by an owner chain, not an edge the owner + /// may take, or naming an unknown revision (#88's replay rule; kept, change nothing). + pub not_owner_move: u64, + /// Sequence of the first unverified move (signature or leaf), for the refusal message. + pub first_unverified: Option<(WalSeq, StateMoveFault)>, + /// Unverified moves this process left out of a checkpoint (`checkpoint_and_compact` + /// under `TruncateTornTail`), so they are gone from the store and strict recovery + /// accepts it again. Not persisted: a reopened store reports zero. + pub dropped_by_compaction: u64, +} + +impl StateMoveReplayReport { + /// Moves that do not verify (signature or leaf). + pub fn unverified(&self) -> u64 { + self.signature_invalid + self.signer_not_chain_leaf + } +} + /// In-memory revision state, rebuilt from revision records. #[derive(Debug, Clone, Default)] pub(crate) struct RevisionLedger { @@ -109,6 +139,8 @@ pub(crate) struct RevisionLedger { changes: BTreeMap<(RepoId, ChangeId), ChangeEntry>, /// (repository, signer key, idempotency key) to the first admission. idempotency: BTreeMap<(RepoId, [u8; 32], IdempotencyKey), (WalSeq, ChangesetId)>, + /// Kind 9 records that changed nothing, by reason. + state_moves: StateMoveReplayReport, } /// Digest of one revision record over its canonical core encodings. @@ -147,19 +179,22 @@ fn record_digest(record: &WalRecord) -> [u8; 32] { h.update(recorded_at_ms.to_le_bytes()); } WalRecord::RevisionStateMoved { - repo_id, - changeset_id, - to, - chain: c, + state_move: m, moved_at_ms, } => { - h.update((repo_id.as_str().len() as u64).to_le_bytes()); - h.update(repo_id.as_str().as_bytes()); - h.update(changeset_id.0); - h.update([to.tag_byte()]); - c.encode_into(&mut chain); + h.update((m.repo_id.as_str().len() as u64).to_le_bytes()); + h.update(m.repo_id.as_str().as_bytes()); + h.update(m.changeset_id.0); + h.update([m.to.tag_byte()]); + m.chain.encode_into(&mut chain); h.update(&chain); h.update(moved_at_ms.to_le_bytes()); + h.update(m.signed_at_ms.to_le_bytes()); + let link = m.leaf_link.encode(); + h.update((link.len() as u64).to_le_bytes()); + h.update(&link); + h.update(m.mover_key); + h.update(m.signature); } _ => {} } @@ -192,6 +227,42 @@ impl RevisionLedger { &self.log } + /// Kind 9 records that changed nothing, by reason (issue #89). + pub(crate) fn state_move_report(&self) -> StateMoveReplayReport { + self.state_moves + } + + /// The log without kind 9 records that do not verify, and how many were left out + /// (review of PR #100): what a checkpoint keeps. Verified moves that changed nothing stay. + pub(crate) fn log_without_unverified_moves(&self) -> (Vec<(WalSeq, WalRecord)>, u64) { + if self.state_moves.unverified() == 0 { + return (self.log.clone(), 0); + } + let mut dropped = 0; + let log = self + .log + .iter() + .filter(|(_, record)| match record { + WalRecord::RevisionStateMoved { state_move, .. } + if state_move.verify().is_err() => + { + dropped += 1; + false + } + _ => true, + }) + .cloned() + .collect(); + (log, dropped) + } + + /// Rebuild from the log a checkpoint kept, recording the `dropped` unverified moves. + pub(crate) fn rebuild_after_compaction(&mut self, log: Vec<(WalSeq, WalRecord)>, dropped: u64) { + let carried = self.state_moves.dropped_by_compaction + dropped; + *self = Self::from_log(log); + self.state_moves.dropped_by_compaction = carried; + } + /// Rebuild a ledger from checkpointed records. pub(crate) fn from_log(log: Vec<(WalSeq, WalRecord)>) -> Self { let mut l = Self::default(); @@ -275,24 +346,38 @@ impl RevisionLedger { recorded_at_ms: *recorded_at_ms, }); } - WalRecord::RevisionStateMoved { - repo_id, - changeset_id, - to, - chain, - .. - } => { + WalRecord::RevisionStateMoved { state_move: m, .. } => { // Kind 9 is permanently the owner-move record: `Verified` and `Canonical` come - // only from the evidence-bearing records of B3, E1, and E2. Kind 9 records are - // unsigned and the WAL seal is unkeyed, so replay accepts one only when it is - // an owner move (`Private -> Draft`, `Private -> Proposed`, `Draft -> Proposed`, - // by a chain that is or dominates the first admission's chain). Both rules are - // pure functions of the log that never change, so an old log keeps its - // meaning. Any other record stays in the log but changes nothing: no record - // sequence, forged or not, moves a revision backwards or past `Proposed`. - if let Some(rev) = self.revisions.get_mut(&(repo_id.clone(), *changeset_id)) { - if owned_by(rev, chain) && rev.state.check_owner_move(*to).is_ok() { - rev.state = *to; + // only from the evidence-bearing records of B3, E1, and E2. The WAL seal is + // unkeyed (CRC32C and an unkeyed hash chain detect corruption, not forgery), + // so replay applies a move only when (1) its mover signature verifies strictly + // and the mover key is the audience of the chain's leaf link (issue #89), and + // (2) it is an owner move (`Private -> Draft`, `Private -> Proposed`, + // `Draft -> Proposed`, by a chain that is or dominates the first admission's + // chain; #88). Both are pure functions of the record and the log that never + // change, so an old log keeps its meaning. Any other record stays in the log + // and the state root but changes nothing; it is counted in the replay report, + // and strict recovery refuses a store with an unverified one. + match m.verify() { + Err(fault) => { + let r = &mut self.state_moves; + match fault { + StateMoveFault::SignatureInvalid => r.signature_invalid += 1, + StateMoveFault::SignerNotChainLeaf => r.signer_not_chain_leaf += 1, + } + r.first_unverified.get_or_insert((seq, fault)); + } + Ok(()) => { + let rev = self.revisions.get_mut(&(m.repo_id.clone(), m.changeset_id)); + match rev { + Some(rev) + if owned_by(rev, &m.chain) + && rev.state.check_owner_move(m.to).is_ok() => + { + rev.state = m.to; + } + _ => self.state_moves.not_owner_move += 1, + } } } } @@ -317,17 +402,14 @@ impl RevisionLedger { .filter(|rev| visible_to(rev, viewer)) } - /// Checks of a state move asked for under `chain` (step B4). A move to `Canonical` is - /// refused first, whatever the revision (`CanonicalOutsidePromotionQueue`); a revision - /// the chain cannot see is `ChangesetNotFound`; a chain that is not the owner chain is - /// `AuthChainNotDominant`; then the owner-move rule of `RevisionState`. - pub(crate) fn plan_move( - &self, - repo: &RepoId, - id: ChangesetId, - to: RevisionState, - chain: &ChainPath, - ) -> SynapseResult<()> { + /// Checks of a signed state move (steps B4 and issue #89). A move to `Canonical` is + /// refused first, whatever the revision (`CanonicalOutsidePromotionQueue`); then a + /// signature that does not verify, or a mover key that is not the audience of the + /// chain's leaf link, is `AuthSignatureInvalid`; a revision the chain cannot see is + /// `ChangesetNotFound`; a chain that is not the owner chain is `AuthChainNotDominant`; + /// then the owner-move rule of `RevisionState`. + pub(crate) fn plan_move(&self, m: &SignedStateMove) -> SynapseResult<()> { + let (id, to, chain) = (m.changeset_id, m.to, &m.chain); if to == RevisionState::Canonical { return Err(SynapseError::new( RefusalCode::CanonicalOutsidePromotionQueue, @@ -336,8 +418,9 @@ impl RevisionLedger { ), )); } + m.verify().map_err(StateMoveFault::into_error)?; let rev = self - .get_visible(repo, id, chain) + .get_visible(&m.repo_id, id, chain) .ok_or_else(|| not_found(format!("revision {id} not found")))?; if !owned_by(rev, chain) { return Err(SynapseError::new( @@ -693,37 +776,38 @@ impl crate::SynapseStore { self.append_revision_record(record, &[]) } - /// Move revision `changeset_id` of `repo_id` to state `to`, asked for under `chain` at - /// server time `now_ms` (ADR 0003 step B4). Refused, with nothing written: any move to - /// `Canonical` (`CanonicalOutsidePromotionQueue`: canonical moves only through the - /// promotion queue, step E2); a revision the chain cannot see (`ChangesetNotFound`, the - /// same as an unknown one); a chain that is not, and does not dominate, the chain of - /// the revision's first admission (`AuthChainNotDominant`); a move to `Verified`, or any - /// move that is backwards, in place, or skips a state (`RevisionStateMoveInvalid`). - /// The owner chain may move `Private -> Draft`, `Private -> Proposed`, and - /// `Draft -> Proposed`. + /// Record the signed state move `state_move` at server time `now_ms` (ADR 0003 step B4, + /// issue #89). Refused, with nothing written: any move to `Canonical` + /// (`CanonicalOutsidePromotionQueue`: canonical moves only through the promotion queue, + /// step E2); a mover signature that does not verify strictly, or a mover key that is not + /// the audience of the chain's leaf link (`AuthSignatureInvalid`); a revision the chain + /// cannot see (`ChangesetNotFound`, the same as an unknown one); a chain that is not, and + /// does not dominate, the chain of the revision's first admission + /// (`AuthChainNotDominant`); a move to `Verified`, or any move that is backwards, in + /// place, or skips a state (`RevisionStateMoveInvalid`). The owner chain may move + /// `Private -> Draft`, `Private -> Proposed`, and `Draft -> Proposed`. pub fn advance_revision_state( &mut self, - repo_id: &RepoId, - changeset_id: ChangesetId, - to: RevisionState, - chain: ChainPath, + state_move: SignedStateMove, now_ms: u64, ) -> SynapseResult<WalSeq> { self.check_writable()?; self.check_binary_codec()?; - self.revisions - .plan_move(repo_id, changeset_id, to, &chain)?; + self.revisions.plan_move(&state_move)?; let record = WalRecord::RevisionStateMoved { - repo_id: repo_id.clone(), - changeset_id, - to, - chain, + state_move, moved_at_ms: now_ms, }; self.append_revision_record(record, &[]) } + /// Kind 9 records replay kept as no-ops, by reason (issue #89): unverified moves (only + /// under `TruncateTornTail`; strict recovery refuses them) and verified moves that are + /// not owner moves. All zero for a log written only by stores. + pub fn state_move_replay_report(&self) -> StateMoveReplayReport { + self.revisions.state_move_report() + } + /// An admitted revision of `repo_id` as `viewer` may see it (step B4): another owner's /// `Private` revision is `ChangesetNotFound`, exactly like an unknown one. pub fn get_revision_visible_to( @@ -815,7 +899,13 @@ impl crate::SynapseStore { #[cfg(test)] mod b4_tests { use super::*; + use crate::{AdmissionAuthority, FsyncPolicy, RecoveryPolicy, StoreLimits, SynapseStore}; use ed25519_dalek::SigningKey; + use std::path::PathBuf; + use synapse_auth::{ + Capability, CapabilityChain, CapabilityLink, ChainQuotas, ChangeScope, LinkCaveats, + OperationSet, PathScope, ReferenceScope, ROOT_PARENT, + }; use synapse_core::{FileMode, PathMutation, TreeDigest}; struct SplitMix64(u64); @@ -838,13 +928,121 @@ mod b4_tests { RepoId::new("aien-spark/synapse").unwrap() } - fn chain(rng: &mut SplitMix64) -> ChainPath { + /// SHA-256 of a purpose and a label path: keys and nonces of these tests are derived, + /// never fixed byte values. + fn derived(what: &str, labels: &[u8]) -> [u8; 32] { + let mut h = Sha256::new(); + h.update(b"synapse-store revision unit fixture\0"); + h.update(what.as_bytes()); + h.update([0]); + h.update(labels); + h.finalize().into() + } + + /// The key presenting the chain with label path `labels`. + fn key_of(labels: &[u8]) -> SigningKey { + SigningKey::from_bytes(&derived("key", labels)) + } + + fn caveats() -> LinkCaveats { + 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, + } + } + + /// The last F1 link of the chain with label path `labels`: issued by the key of the + /// parent path (a fixture authority for a root link), delegating to the key of `labels`. + fn link_of(labels: &[u8]) -> CapabilityLink { + let (issuer, parent) = match labels.split_last() { + Some((_, [])) | None => ( + SigningKey::from_bytes(&derived("authority", &[])), + ROOT_PARENT, + ), + Some((_, up)) => (key_of(up), link_of(up).digest()), + }; + CapabilityLink::issue( + &issuer, + parent, + derived("nonce", labels), + repo(), + key_of(labels).verifying_key().to_bytes(), + caveats(), + ) + } + + fn chain_of(labels: &[u8]) -> CapabilityChain { + CapabilityChain::new((1..=labels.len()).map(|n| link_of(&labels[..n])).collect()) + } + + /// Link digests of the chain with label path `labels`; label prefixes are ancestors. + fn path(labels: &[u8]) -> ChainPath { + ChainPath::new( + chain_of(labels) + .link_digests() + .iter() + .map(|d| d.0) + .collect(), + ) + .unwrap() + } + + fn random_labels(rng: &mut SplitMix64) -> Vec<u8> { let len = 1 + rng.below(3) as usize; - ChainPath::new((0..len).map(|_| [1 + rng.below(3) as u8; 32]).collect()).unwrap() + (0..len).map(|_| 1 + rng.below(3) as u8).collect() + } + + /// A move of `id` to `to` signed by the leaf key of the chain with label path `labels`. + fn signed(labels: &[u8], id: ChangesetId, to: RevisionState) -> SignedStateMove { + SignedStateMove::sign_new(&key_of(labels), repo(), id, to, &chain_of(labels), 6_000) + .unwrap() + } + + /// The same move with one signature bit flipped (a resealed edit of a signed record). + fn bad_signature(mut m: SignedStateMove) -> SignedStateMove { + m.signature[17] ^= 0x01; + m + } + + /// The same move re-signed, validly, by a key that is not the chain leaf's audience. + fn non_leaf_signer(mut m: SignedStateMove, signer: &[u8]) -> SignedStateMove { + let k = key_of(signer); + m.mover_key = k.verifying_key().to_bytes(); + m.signature = SignedStateMove::sign_statement( + &k, + &m.repo_id, + m.changeset_id, + m.to, + &m.chain, + m.signed_at_ms, + ); + m + } + + fn moved(state_move: SignedStateMove) -> WalRecord { + WalRecord::RevisionStateMoved { + state_move, + moved_at_ms: 6_000, + } + } + + fn body(n: u32) -> [u8; 4] { + n.to_le_bytes() } - fn admission(rng: &mut SplitMix64, n: u32) -> WalRecord { - let body = n.to_le_bytes(); + fn admission(chain: ChainPath, author: &[u8], n: u32) -> WalRecord { + let body = body(n); let content = RevisionContent { change_id: ChangeId([(n % 7) as u8; 16]), base_tree: TreeDigest([0x7E; 32]), @@ -859,39 +1057,45 @@ mod b4_tests { }], intent_summary: "implement the task".into(), }; - let key = SigningKey::from_bytes(&[1 + rng.below(4) as u8; 32]); + let mut idem = derived("idempotency", &n.to_le_bytes()); + idem[0] ^= author.len() as u8; let envelope = ChangesetEnvelopeV2::sign_new( - &key, + &key_of(author), repo(), content, - IdempotencyKey([n as u8; 32]), + IdempotencyKey(idem), 1_000, ); WalRecord::RevisionAdmitted { envelope, - chain: chain(rng), + chain, admitted_at_ms: 5_000, new_blobs: vec![], } } - /// Property (acceptance 1, replay side): the ledger applies any sequence of revision - /// records, including forged moves no store call would write (backwards, in place, - /// skipping, to `Verified` or `Canonical`, by chains that do not own the revision). - /// Only owner moves apply, so no revision ever moves backwards or past `Proposed`, every - /// owner-move record moves its revision, and rebuilding from the log gives the same states. + /// Property (acceptance 1 of B4 and of issue #89, replay side): the ledger applies any + /// sequence of revision records, including forged moves no store call would write + /// (backwards, in place, skipping, to `Verified` or `Canonical`, by chains that do not + /// own the revision, with a broken signature, or signed by a key that is not the chain + /// leaf's audience). Only verified owner moves apply, so no revision ever moves + /// backwards or past `Proposed`, every verified owner move moves its revision, the + /// replay report counts every no-op by reason, and rebuilding from the log gives the + /// same states and the same report. #[test] fn b4_property_forged_record_sequences_never_move_a_revision_backwards() { let mut rng = SplitMix64(0xB4_0003); - let mut forged_refused = 0u32; + let (mut forged_refused, mut unverified_refused) = (0u32, 0u32); for _case in 0..200 { let mut ledger = RevisionLedger::default(); let mut ids: Vec<ChangesetId> = Vec::new(); let mut last: BTreeMap<ChangesetId, RevisionState> = BTreeMap::new(); + let mut want = StateMoveReplayReport::default(); for seq in 1..=60u64 { let record = if ids.is_empty() || rng.below(4) == 0 { let n = rng.below(12) as u32; - let r = admission(&mut rng, n); + let author = random_labels(&mut rng); + let r = admission(path(&random_labels(&mut rng)), &author, n); if let WalRecord::RevisionAdmitted { envelope, .. } = &r { let id = envelope.changeset_id(); if !ids.contains(&id) { @@ -900,33 +1104,45 @@ mod b4_tests { } r } else { - WalRecord::RevisionStateMoved { - repo_id: repo(), - changeset_id: ids[rng.below(ids.len() as u64) as usize], - to: RevisionState::ALL[rng.below(5) as usize], - chain: chain(&mut rng), - moved_at_ms: 6_000, - } + let id = ids[rng.below(ids.len() as u64) as usize]; + let to = RevisionState::ALL[rng.below(5) as usize]; + let m = signed(&random_labels(&mut rng), id, to); + moved(match rng.below(6) { + 0 => bad_signature(m), + 1 => non_leaf_signer(m, &random_labels(&mut rng)), + _ => m, + }) }; - let target = match &record { - WalRecord::RevisionStateMoved { - changeset_id, - to, - chain, - .. - } => Some((*changeset_id, *to, chain.clone())), + let before = match &record { + WalRecord::RevisionStateMoved { state_move: m, .. } => { + let rev = ledger.get_revision(&repo(), m.changeset_id).unwrap(); + let verified = m.verify(); + let owner = + owned_by(rev, &m.chain) && rev.state.check_owner_move(m.to).is_ok(); + match verified { + Err(StateMoveFault::SignatureInvalid) => want.signature_invalid += 1, + Err(StateMoveFault::SignerNotChainLeaf) => { + want.signer_not_chain_leaf += 1 + } + Ok(()) if !owner => want.not_owner_move += 1, + Ok(()) => {} + } + if let Err(fault) = verified { + want.first_unverified.get_or_insert((WalSeq(seq), fault)); + unverified_refused += 1; + } + Some((m.changeset_id, m.to, rev.state, verified.is_ok() && owner)) + } _ => None, }; - let before = target.as_ref().map(|(id, to, chain)| { - let rev = ledger.get_revision(&repo(), *id).unwrap(); - let legal = owned_by(rev, chain) && rev.state.check_owner_move(*to).is_ok(); - (rev.state, legal) - }); ledger.apply(WalSeq(seq), record); - if let (Some((id, to, _)), Some((from, legal))) = (target, before) { + if let Some((id, to, from, legal)) = before { let now = ledger.get_revision(&repo(), id).unwrap().state; - let want = if legal { to } else { from }; - assert_eq!(now, want, "{id}: {from:?} -> {to:?}"); + assert_eq!( + now, + if legal { to } else { from }, + "{id}: {from:?} -> {to:?}" + ); if !legal { forged_refused += 1; } @@ -938,7 +1154,9 @@ mod b4_tests { assert!(now <= RevisionState::Proposed, "{id} reached {now:?}"); } } + assert_eq!(ledger.state_move_report(), want); let rebuilt = RevisionLedger::from_log(ledger.log().to_vec()); + assert_eq!(rebuilt.state_move_report(), want); for id in &ids { assert_eq!( rebuilt.get_revision(&repo(), *id).unwrap().state, @@ -947,52 +1165,333 @@ mod b4_tests { } } assert!(forged_refused > 0, "the sequences included forged moves"); + assert!( + unverified_refused > 0, + "the sequences included unverified moves" + ); } - /// Kind 9 records carry no signature and the WAL seal is unkeyed, so replay accepts a - /// state move only when it is an owner move (`Private -> Draft`, `Private -> Proposed`, - /// `Draft -> Proposed`, by a chain that is or dominates the first admission's chain). - /// A forged `Proposed -> Verified` record, even naming the owner's chain, is refused on - /// replay: `Verified` comes only from B3/E1 evidence records, never from kind 9. + /// Replay applies a state move only when its mover signature verifies, its mover key is + /// the chain leaf's audience, and it is an owner move (`Private -> Draft`, + /// `Private -> Proposed`, `Draft -> Proposed`, by a chain that is or dominates the first + /// admission's chain). A signed `Proposed -> Verified` record, even by the owner, is + /// refused on replay: `Verified` comes only from B3/E1 evidence records, never kind 9. #[test] fn b4_replay_refuses_a_forged_move_to_verified() { - let mut rng = SplitMix64(0xB4_0004); - let mut record = admission(&mut rng, 1); - let owner = ChainPath::new(vec![[1; 32], [2; 32]]).unwrap(); - let id = match &mut record { - WalRecord::RevisionAdmitted { - envelope, chain, .. - } => { - *chain = owner.clone(); - envelope.changeset_id() - } + let owner: &[u8] = &[1, 2]; + let record = admission(path(owner), owner, 1); + let id = match &record { + WalRecord::RevisionAdmitted { envelope, .. } => envelope.changeset_id(), _ => unreachable!(), }; - let mv = |to: RevisionState, chain: &ChainPath| WalRecord::RevisionStateMoved { - repo_id: repo(), - changeset_id: id, - to, - chain: chain.clone(), - moved_at_ms: 6_000, - }; - let outsider = ChainPath::new(vec![[1; 32], [9; 32]]).unwrap(); + let mv = |to: RevisionState, labels: &[u8]| moved(signed(labels, id, to)); let log = vec![ (WalSeq(1), record), - (WalSeq(2), mv(RevisionState::Proposed, &owner)), - (WalSeq(3), mv(RevisionState::Verified, &owner)), - (WalSeq(4), mv(RevisionState::Verified, &outsider)), - (WalSeq(5), mv(RevisionState::Canonical, &owner)), + (WalSeq(2), mv(RevisionState::Proposed, owner)), + (WalSeq(3), mv(RevisionState::Verified, owner)), + (WalSeq(4), mv(RevisionState::Verified, &[1, 9])), + (WalSeq(5), mv(RevisionState::Canonical, owner)), ]; let replayed = RevisionLedger::from_log(log); assert_eq!( replayed.get_revision(&repo(), id).unwrap().state, RevisionState::Proposed, - "a forged move to Verified or Canonical changes nothing on replay" + "a move to Verified or Canonical changes nothing on replay" ); assert_eq!( replayed.log().len(), 5, "kept in the log, applied as no-ops" ); + let report = replayed.state_move_report(); + assert_eq!(report.not_owner_move, 3); + assert_eq!(report.unverified(), 0); + } + + fn temp_dir(name: &str) -> PathBuf { + let nanos = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos(); + let dir = + std::env::temp_dir().join(format!("synapse-b89-{name}-{}-{nanos}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + dir + } + + fn open(dir: &PathBuf, policy: RecoveryPolicy) -> SynapseResult<SynapseStore> { + let limits = StoreLimits { + wal_prealloc_bytes: 64 * 1024, + ..Default::default() + }; + SynapseStore::open(dir, FsyncPolicy::EveryCommit, policy, limits) + } + + /// Admit revision 1 under the chain with label path `owner`; its changeset id. + fn admit(s: &mut SynapseStore, owner: &[u8]) -> ChangesetId { + let WalRecord::RevisionAdmitted { envelope, .. } = admission(path(owner), owner, 1) else { + unreachable!() + }; + let id = envelope.changeset_id(); + let body = body(1); + let blobs = vec![(BlobDigest::compute(&body), body.to_vec())]; + let authority = AdmissionAuthority { + chain: path(owner), + change_scope: Vec::new(), + }; + s.admit_revision(envelope, &blobs, authority, 5_000) + .unwrap(); + id + } + + /// Issue #89 acceptance 1 (red on the #88 head, where kind 9 carried no signature): an + /// owner move written straight into the WAL through the store's own framing (valid + /// CRC32C and hash chain, so a resealed forgery) without the owner's key changes nothing + /// on replay, whether its signature is broken or it is validly signed by a key that is + /// not the chain leaf's audience. Torn-tail recovery keeps both as counted no-ops + /// and strict recovery refuses the store (until a torn-tail compaction drops them: see + /// `b89_torn_tail_compaction_drops_unverified_moves_so_strict_recovery_accepts_the_store`). + #[test] + fn b89_forged_owner_move_resealed_in_the_wal_changes_nothing_on_replay() { + const TORN: RecoveryPolicy = RecoveryPolicy::TruncateTornTail; + let owner: &[u8] = &[1, 2]; + let dir = temp_dir("forged"); + let mut s = open(&dir, TORN).unwrap(); + let id = admit(&mut s, owner); + let honest = signed(owner, id, RevisionState::Draft); + let broken = bad_signature(honest.clone()); + 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(); + assert_eq!( + s.get_revision(&repo(), id).unwrap().state, + RevisionState::Private + ); + drop(s); + + let check = |s: &SynapseStore| { + assert_eq!( + s.get_revision(&repo(), id).unwrap().state, + RevisionState::Private, + "a forged, resealed owner move must change nothing on replay" + ); + let report = s.state_move_replay_report(); + assert_eq!(report.signature_invalid, 1); + assert_eq!(report.signer_not_chain_leaf, 1); + assert_eq!(report.not_owner_move, 0); + assert_eq!( + report.first_unverified, + Some((first, StateMoveFault::SignatureInvalid)) + ); + }; + let strict_refuses = || { + let err = open(&dir, RecoveryPolicy::StrictFailClosed).err().unwrap(); + assert_eq!( + err.code, + RefusalCode::RevisionStateMoveUnverified, + "{err:?}" + ); + }; + check(&open(&dir, TORN).unwrap()); + strict_refuses(); + check(&open(&dir, TORN).unwrap()); + strict_refuses(); + let _ = std::fs::remove_dir_all(&dir); + } + + /// Review of PR #100 (note 1): torn-tail recovery keeps unverified kind 9 records as + /// no-ops, but compaction must not carry them into the checkpoint, or strict recovery + /// refuses the store forever. A torn-tail open followed by `checkpoint_and_compact` + /// drops them (and only them), keeps every applied move, and leaves a store strict + /// recovery accepts with the same revision states. + #[test] + fn b89_torn_tail_compaction_drops_unverified_moves_so_strict_recovery_accepts_the_store() { + const TORN: RecoveryPolicy = RecoveryPolicy::TruncateTornTail; + const STRICT: RecoveryPolicy = RecoveryPolicy::StrictFailClosed; + let owner: &[u8] = &[1, 2]; + let dir = temp_dir("compact-forged"); + 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())), &[]) + .unwrap(); + s.append_revision_record(moved(non_leaf_signer(honest.clone(), &[1, 9])), &[]) + .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(); + drop(s); + assert!( + open(&dir, STRICT).is_err(), + "strict refuses before compaction" + ); + + let mut s = open(&dir, TORN).unwrap(); + assert_eq!(s.state_move_replay_report().unverified(), 2); + s.checkpoint_and_compact(7_000).unwrap(); + let check = |s: &SynapseStore| { + assert_eq!( + s.get_revision(&repo(), id).unwrap().state, + RevisionState::Draft + ); + let report = s.state_move_replay_report(); + assert_eq!(report.unverified(), 0, "{report:?}"); + assert_eq!(report.first_unverified, None); + assert_eq!(report.not_owner_move, 1, "verified no-ops are kept"); + }; + check(&s); + assert_eq!(s.state_move_replay_report().dropped_by_compaction, 2); + let root = s.state_root_digest(None).unwrap(); + drop(s); + let s = open(&dir, STRICT).expect("strict recovery accepts the compacted store"); + check(&s); + assert_eq!( + s.state_move_replay_report().dropped_by_compaction, + 0, + "not persisted" + ); + assert_eq!(s.state_root_digest(None).unwrap(), root); + let _ = std::fs::remove_dir_all(&dir); + } + + /// Review of PR #100 (note 2): `SignedStateMove::verify` checks only that the mover key + /// is the audience of a link whose digest ends the chain; it does not check who issued + /// that link. A forger can mint a root link of its own, or append a link of its own + /// under the owner's chain, and sign a move that verifies. The store is safe because it + /// also requires the chain to be, or dominate, the first admission's chain; this test + /// fails if replay or the store call skips that check. + #[test] + fn b89_a_forger_minted_leaf_link_verifies_but_never_owns_a_revision() { + let owner: &[u8] = &[1, 2]; + let record = admission(path(owner), owner, 1); + let id = match &record { + WalRecord::RevisionAdmitted { envelope, .. } => envelope.changeset_id(), + _ => unreachable!(), + }; + let forger = key_of(&[7]); + let forged = |parent: Option<&[u8]>| { + let (parent_digest, mut digests) = match parent { + None => (ROOT_PARENT, Vec::new()), + Some(labels) => (link_of(labels).digest(), path(labels).links().to_vec()), + }; + let link = CapabilityLink::issue( + &forger, + parent_digest, + derived("forged nonce", parent.unwrap_or(&[])), + repo(), + forger.verifying_key().to_bytes(), + caveats(), + ); + digests.push(link.digest().0); + let chain = ChainPath::new(digests).unwrap(); + let to = RevisionState::Proposed; + SignedStateMove { + repo_id: repo(), + changeset_id: id, + to, + signature: SignedStateMove::sign_statement(&forger, &repo(), id, to, &chain, 6_000), + chain, + signed_at_ms: 6_000, + leaf_link: link, + mover_key: forger.verifying_key().to_bytes(), + } + }; + let moves = [forged(None), forged(Some(owner))]; + for m in &moves { + assert_eq!( + m.verify(), + Ok(()), + "verify alone accepts a forger-minted leaf" + ); + } + let mut log = vec![ + (WalSeq(1), record), + (WalSeq(2), moved(signed(owner, id, RevisionState::Draft))), + ]; + // The revision is `Draft`, so every chain sees it: only ownership can refuse. + let shared = RevisionLedger::from_log(log.clone()); + for m in &moves { + let err = shared.plan_move(m).unwrap_err(); + assert_eq!(err.code, RefusalCode::AuthChainNotDominant); + } + log.extend( + moves + .into_iter() + .zip(3..) + .map(|(m, n)| (WalSeq(n), moved(m))), + ); + let replayed = RevisionLedger::from_log(log); + assert_eq!( + replayed.get_revision(&repo(), id).unwrap().state, + RevisionState::Draft + ); + assert_eq!(replayed.state_move_report().not_owner_move, 2); + } + + /// Issue #89 acceptance 2: a legitimate signed owner move round-trips write, strict + /// replay, checkpoint, and compaction, and the state root covers it. + #[test] + fn b89_signed_owner_move_round_trips_replay_checkpoint_and_compaction() { + const STRICT: RecoveryPolicy = RecoveryPolicy::StrictFailClosed; + let owner: &[u8] = &[1, 2]; + let dir = temp_dir("legit"); + let mut s = open(&dir, STRICT).unwrap(); + let id = admit(&mut s, owner); + let before = s.state_root_digest(None).unwrap(); + s.advance_revision_state(signed(owner, id, RevisionState::Draft), 6_000) + .unwrap(); + let root = s.state_root_digest(None).unwrap(); + assert_ne!(root, before, "the state root covers the move"); + drop(s); + let check = |s: &SynapseStore| { + assert_eq!( + s.get_revision(&repo(), id).unwrap().state, + RevisionState::Draft + ); + assert_eq!( + s.state_move_replay_report(), + StateMoveReplayReport::default() + ); + assert_eq!(s.state_root_digest(None).unwrap(), root); + }; + let mut s = open(&dir, STRICT).unwrap(); + check(&s); + s.checkpoint_and_compact(7_000).unwrap(); + check(&s); + drop(s); + check(&open(&dir, STRICT).unwrap()); + let _ = std::fs::remove_dir_all(&dir); + } + + /// The kind 9 record digest (an input of the state root) covers every signed and + /// unsigned field, so two logs that differ only in a signature, a mover key, or a leaf + /// link have different state roots. + #[test] + fn b89_state_root_record_digest_covers_the_signature_fields() { + let id = ChangesetId(derived("changeset", &[1])); + let m = signed(&[1, 2], id, RevisionState::Draft); + let base = record_digest(&moved(m.clone())); + let mut other_leaf = m.clone(); + other_leaf.leaf_link = link_of(&[1, 9]); + let variants = [ + bad_signature(m.clone()), + non_leaf_signer(m.clone(), &[1, 9]), + other_leaf, + SignedStateMove { + signed_at_ms: 6_001, + ..m.clone() + }, + ]; + for v in variants { + assert_ne!(record_digest(&moved(v)), base); + } + let later = WalRecord::RevisionStateMoved { + state_move: m, + moved_at_ms: 6_001, + }; + assert_ne!(record_digest(&later), base); } } diff --git a/crates/synapse-store/tests/b1_change_identity.rs b/crates/synapse-store/tests/b1_change_identity.rs index c060b7e..c216e7d 100644 --- a/crates/synapse-store/tests/b1_change_identity.rs +++ b/crates/synapse-store/tests/b1_change_identity.rs @@ -1,7 +1,7 @@ //! ADR 0003 step B1 acceptance tests (issue #27): change identity bound to its creating //! chain, admission witnesses, obsolescence markers, envelope v2 with a native base, and v1 -//! identities unchanged. Chains here are plain link-digest paths; `synapse-api` tests the -//! same rules with real signed F1 capability chains. +//! identities unchanged. Chains here are digests of real F1 links from the shared fixture +//! (`common`); `synapse-api` tests the same rules end to end through the request path. use ed25519_dalek::SigningKey; use std::path::{Path, PathBuf}; @@ -11,6 +11,7 @@ use synapse_core::{ ObsolescenceMarker, PathMutation, RefusalCode, RepoId, RevisionContent, RevisionState, TreeDigest, WalSeq, }; +mod common; use synapse_store::codec::{decode_record, encode_record}; use synapse_store::{ AdmissionAuthority, FsyncPolicy, IngestOutcome, RecordCodec, RecoveryPolicy, RevisionOutcome, @@ -57,7 +58,7 @@ struct Chains { } fn chains() -> Chains { - let p = |v: &[u8]| ChainPath::new(v.iter().map(|b| [*b; 32]).collect()).unwrap(); + let p = common::path; Chains { r: p(&[1]), o: p(&[1, 2]), @@ -314,8 +315,7 @@ fn b1_prune_by_chain_not_dominating_creating_chain_is_refused() { let b = admit(&mut s, &key(3), &c.w1, b"worker attempt", 1); // The owner shares it (ADR 0003 B4), so the other chains see it and are refused for // dominance rather than as an unknown revision. - s.advance_revision_state(&repo(), a, RevisionState::Draft, c.o.clone(), 5_500) - .unwrap(); + common::mv(&mut s, &[1, 2], a, RevisionState::Draft, 5_500).unwrap(); let before = s.committed_seq(); for (signer, chain) in [(key(3), &c.w1), (key(9), &c.x), (key(4), &c.w2)] { let err = s diff --git a/crates/synapse-store/tests/b4_revision_states.rs b/crates/synapse-store/tests/b4_revision_states.rs index 09a4cf5..90bf3be 100644 --- a/crates/synapse-store/tests/b4_revision_states.rs +++ b/crates/synapse-store/tests/b4_revision_states.rs @@ -1,8 +1,9 @@ //! ADR 0003 step B4 acceptance tests (issue #28): the revision state machine (`Private`, //! `Draft`, `Proposed`, `Verified`, `Canonical`). Over random operation sequences no revision //! moves backwards; a `Private` revision is invisible to every key outside its owner chain; -//! any move to `Canonical` outside the promotion queue is refused. Chains here are plain -//! link-digest paths; `synapse-api` tests the same rules with real signed F1 chains. +//! any move to `Canonical` outside the promotion queue is refused. Chains here are digests of +//! real F1 links from the shared fixture (`common`), and every state move carries its leaf +//! link and the leaf key's signature (issue #89). //! //! The property tests use a seeded SplitMix64 generator (no new dependency, as in F1); the //! seed and case counts are fixed so every run checks the same sequences. @@ -12,9 +13,11 @@ use std::collections::BTreeMap; use std::path::{Path, PathBuf}; use synapse_core::{ BlobDigest, ChainPath, ChangeId, ChangesetEnvelopeV2, ChangesetId, FileMode, IdempotencyKey, - MutationOp, ObsolescenceMarker, PathMutation, RefusalCode, RepoId, RevisionContent, - RevisionState, TreeDigest, + MutationOp, ObsolescenceMarker, PathMutation, RefusalCode, RevisionContent, RevisionState, + TreeDigest, }; +mod common; +use common::{key_of, mv, path, repo, signed}; use synapse_store::codec::{decode_record, encode_record}; use synapse_store::{ AdmissionAuthority, FsyncPolicy, RecoveryPolicy, RevisionOutcome, StoreLimits, SynapseStore, @@ -59,14 +62,6 @@ fn open(dir: &Path, policy: FsyncPolicy) -> SynapseStore { SynapseStore::open(dir, policy, STRICT, limits).unwrap() } -fn repo() -> RepoId { - RepoId::new("aien-spark/synapse").unwrap() -} - -fn path(links: &[u8]) -> ChainPath { - ChainPath::new(links.iter().map(|b| [*b; 32]).collect()).unwrap() -} - /// The delegation tree: root `R` = [1]; orchestrator `O` = [1,2] under it; workers /// `W1` = [1,2,3] and `W2` = [1,2,4] under `O`; `W1s` = [1,2,3,5], a sub-delegate of `W1`; /// outsider `X` = [1,9] beside `O`. Each chain presents its own key. @@ -79,10 +74,6 @@ const TREE: [&[u8]; 6] = [ &[1, 9], ]; -fn key_of(links: &[u8]) -> SigningKey { - SigningKey::from_bytes(&[*links.last().unwrap(); 32]) -} - fn auth(chain: &ChainPath) -> AdmissionAuthority { AdmissionAuthority { chain: chain.clone(), @@ -238,15 +229,14 @@ fn b4_property_random_operation_sequences_never_move_a_revision_backwards() { known[i].0 }; let to = RevisionState::ALL[rng.below(5) as usize]; - let chain = path(TREE[rng.below(TREE.len() as u64) as usize]); + let labels = TREE[rng.below(TREE.len() as u64) as usize]; + let chain = path(labels); let (cur, owners) = (known[i].4, &known[i].3); let owner = !unknown && chain.dominates(&owners[0]); let visible = !unknown && (cur != RevisionState::Private || owner); let expected = model_move(cur, to, owner, visible); let before = s.committed_seq(); - let got = s - .advance_revision_state(&repo(), id, to, chain, 6_000) - .map_err(|e| e.code); + let got = mv(&mut s, labels, id, to, 6_000).map_err(|e| e.code); match (&expected, &got) { (Ok(want), Ok(_)) => { known[i].4 = *want; @@ -311,8 +301,7 @@ fn b4_private_revision_is_invisible_to_every_key_outside_its_owner_chain() { let o: &[u8] = &[1, 2]; // O creates the change (Draft, so the change itself is visible); W1 adds a Private one. let shared = admit(&mut s, o, b"orchestrator draft", 1); - s.advance_revision_state(&repo(), shared, RevisionState::Draft, path(o), 5_100) - .unwrap(); + mv(&mut s, o, shared, RevisionState::Draft, 5_100).unwrap(); let p = admit(&mut s, w1, b"worker private attempt", 1); assert_eq!(state(&s, p), RevisionState::Private); let unknown = ChangesetId([0xEE; 32]); @@ -320,7 +309,8 @@ fn b4_private_revision_is_invisible_to_every_key_outside_its_owner_chain() { .get_revision_visible_to(&repo(), unknown, &path(o)) .unwrap_err(); - let check = |s: &mut SynapseStore, viewer: &ChainPath| { + let check = |s: &mut SynapseStore, labels: &[u8]| { + let viewer = &path(labels); let owner = viewer.dominates(&path(w1)); let read = s.get_revision_visible_to(&repo(), p, viewer); let listed = s @@ -343,10 +333,15 @@ fn b4_private_revision_is_invisible_to_every_key_outside_its_owner_chain() { ); assert!(!listed, "{viewer:?} must not see it in the change"); let before = s.committed_seq(); - let leaf = viewer.links().last().unwrap()[0]; - let signer = SigningKey::from_bytes(&[leaf; 32]); + let signer = key_of(labels); // Not nameable as a parent. - let (env, blobs) = revision(&signer, ChangeId([0x77; 16]), b"child", [leaf; 32], vec![p]); + let (env, blobs) = revision( + &signer, + ChangeId([0x77; 16]), + b"child", + common::derived("idempotency", labels), + vec![p], + ); assert_eq!( s.admit_revision(env, &blobs, auth(viewer), 5_200) .unwrap_err() @@ -367,7 +362,7 @@ fn b4_private_revision_is_invisible_to_every_key_outside_its_owner_chain() { } // Not movable. assert_eq!( - s.advance_revision_state(&repo(), p, RevisionState::Draft, viewer.clone(), 6_000) + mv(s, labels, p, RevisionState::Draft, 6_000) .unwrap_err() .code, RefusalCode::ChangesetNotFound, @@ -378,7 +373,7 @@ fn b4_private_revision_is_invisible_to_every_key_outside_its_owner_chain() { // The fixed tree: R, O, W1 own it; W2, the sub-delegate W1s, and X do not. for links in TREE { - check(&mut s, &path(links)); + check(&mut s, links); } // Random chains over the same link alphabet. let mut rng = SplitMix64(0xB4_0002); @@ -387,23 +382,22 @@ fn b4_private_revision_is_invisible_to_every_key_outside_its_owner_chain() { let links: Vec<u8> = (0..len) .map(|_| [1u8, 2, 3, 4, 5, 9][rng.below(6) as usize]) .collect(); - check(&mut s, &path(&links)); + check(&mut s, &links); } // The same after replay and after a checkpoint. drop(s); let mut s = open(&dir, FsyncPolicy::EveryCommit); for links in TREE { - check(&mut s, &path(links)); + check(&mut s, links); } s.checkpoint_and_compact(9_000).unwrap(); drop(s); let mut s = open(&dir, FsyncPolicy::EveryCommit); for links in TREE { - check(&mut s, &path(links)); + check(&mut s, links); } // Once its owner moves it to Draft, it is visible to every chain. - s.advance_revision_state(&repo(), p, RevisionState::Draft, path(w1), 9_100) - .unwrap(); + mv(&mut s, w1, p, RevisionState::Draft, 9_100).unwrap(); for links in TREE { let viewer = path(links); assert_eq!( @@ -430,22 +424,18 @@ fn b4_any_move_to_canonical_outside_the_promotion_queue_is_refused() { let private = admit(&mut s, w1, b"private", 1); let draft = admit(&mut s, w1, b"draft", 2); let proposed = admit(&mut s, w1, b"proposed", 3); - s.advance_revision_state(&repo(), draft, RevisionState::Draft, path(w1), 5_100) - .unwrap(); - s.advance_revision_state(&repo(), proposed, RevisionState::Proposed, path(w1), 5_101) - .unwrap(); + mv(&mut s, w1, draft, RevisionState::Draft, 5_100).unwrap(); + mv(&mut s, w1, proposed, RevisionState::Proposed, 5_101).unwrap(); let before = s.committed_seq(); for id in [private, draft, proposed, ChangesetId([0xEE; 32])] { for links in TREE { - let err = s - .advance_revision_state(&repo(), id, RevisionState::Canonical, path(links), 6_000) - .unwrap_err(); + let err = mv(&mut s, links, id, RevisionState::Canonical, 6_000).unwrap_err(); assert_eq!(err.code, RefusalCode::CanonicalOutsidePromotionQueue); } } for id in [private, draft, proposed] { assert_eq!( - s.advance_revision_state(&repo(), id, RevisionState::Verified, path(w1), 6_000) + mv(&mut s, w1, id, RevisionState::Verified, 6_000) .unwrap_err() .code, RefusalCode::RevisionStateMoveInvalid @@ -462,9 +452,7 @@ fn b4_any_move_to_canonical_outside_the_promotion_queue_is_refused() { RevisionState::Proposed, ] { assert_eq!( - s.advance_revision_state(&repo(), proposed, to, path(w1), 6_000) - .unwrap_err() - .code, + mv(&mut s, w1, proposed, to, 6_000).unwrap_err().code, RefusalCode::RevisionStateMoveInvalid ); } @@ -509,8 +497,8 @@ fn b4_joining_identical_content_grants_no_ownership_of_a_private_revision() { assert_eq!(s.get_revision(&repo(), p).unwrap().witnesses.len(), 2); let check = |s: &mut SynapseStore| { assert_eq!(state(s, p), RevisionState::Private); - for viewer in [w1, x] { - let viewer = path(viewer); + for labels in [w1, x] { + let viewer = path(labels); assert_eq!( s.get_revision_visible_to(&repo(), p, &viewer) .unwrap_err() @@ -524,9 +512,7 @@ fn b4_joining_identical_content_grants_no_ownership_of_a_private_revision() { let before = s.committed_seq(); for to in [RevisionState::Draft, RevisionState::Proposed] { assert_eq!( - s.advance_revision_state(&repo(), p, to, viewer.clone(), 6_000) - .unwrap_err() - .code, + mv(s, labels, p, to, 6_000).unwrap_err().code, RefusalCode::ChangesetNotFound, "{viewer:?}" ); @@ -550,8 +536,7 @@ fn b4_joining_identical_content_grants_no_ownership_of_a_private_revision() { let mut s = open(&dir, FsyncPolicy::EveryCommit); check(&mut s); // The owner shares it: the joiner reads it now, but moving it stays the owner's. - s.advance_revision_state(&repo(), p, RevisionState::Draft, path(o), 9_100) - .unwrap(); + mv(&mut s, o, p, RevisionState::Draft, 9_100).unwrap(); assert_eq!( s.get_revision_visible_to(&repo(), p, &path(w1)) .unwrap() @@ -559,47 +544,75 @@ fn b4_joining_identical_content_grants_no_ownership_of_a_private_revision() { RevisionState::Draft ); assert_eq!( - s.advance_revision_state(&repo(), p, RevisionState::Proposed, path(w1), 9_200) + mv(&mut s, w1, p, RevisionState::Proposed, 9_200) .unwrap_err() .code, RefusalCode::AuthChainNotDominant ); - s.advance_revision_state(&repo(), p, RevisionState::Proposed, path(o), 9_300) - .unwrap(); + mv(&mut s, o, p, RevisionState::Proposed, 9_300).unwrap(); } -/// The kind 9 record round-trips byte for byte; truncated, extended, and unknown-state bytes -/// are refused typed, never a panic. +/// The kind 9 v2 record (issue #89) round-trips byte for byte and its move verifies after +/// decoding; truncated, extended, unknown-state, and malformed-leaf-link bytes are refused +/// typed, never a panic; the unsigned layout of #88 is refused (truncated). #[test] fn b4_state_move_records_round_trip_and_malformed_bytes_are_refused_typed() { + let w1: &[u8] = &[1, 2, 3]; + let id = ChangesetId(common::derived("codec revision", &[])); let record = WalRecord::RevisionStateMoved { - repo_id: repo(), - changeset_id: ChangesetId([3; 32]), - to: RevisionState::Proposed, - chain: path(&[1, 2, 3]), - moved_at_ms: 7, + state_move: signed(w1, id, RevisionState::Proposed, 7), + moved_at_ms: 8, }; let bytes = encode_record(&record).unwrap(); assert_eq!(record.kind_byte(), 9); - assert_eq!(decode_record(&bytes, 1 << 20).unwrap(), record); - assert_eq!( - encode_record(&decode_record(&bytes, 1 << 20).unwrap()).unwrap(), - bytes - ); + let decoded = decode_record(&bytes, 1 << 20).unwrap(); + assert_eq!(decoded, record); + assert_eq!(encode_record(&decoded).unwrap(), bytes); + match &decoded { + WalRecord::RevisionStateMoved { state_move, .. } => { + assert_eq!(state_move.verify(), Ok(())) + } + other => panic!("decoded {other:?}"), + } for cut in 0..bytes.len() { - assert!(decode_record(&bytes[..cut], 1 << 20).is_err(), "cut {cut}"); + let err = decode_record(&bytes[..cut], 1 << 20).unwrap_err(); + assert!( + matches!(err.kind(), "Truncated" | "EmbeddedMalformed"), + "cut {cut}: {err:?}" + ); } let mut longer = bytes.clone(); longer.push(0); - assert!(decode_record(&longer, 1 << 20).is_err()); + assert_eq!( + decode_record(&longer, 1 << 20).unwrap_err().kind(), + "TrailingBytes" + ); // The state tag sits after the codec byte, kind, repo string, and changeset ID. let tag_at = 2 + 4 + repo().as_str().len() + 32; assert_eq!(bytes[tag_at], RevisionState::Proposed.tag_byte()); for bad in [0u8, 6, 0xFF] { let mut b = bytes.clone(); b[tag_at] = bad; - assert!(decode_record(&b, 1 << 20).is_err(), "state tag {bad}"); + assert_eq!( + decode_record(&b, 1 << 20).unwrap_err().kind(), + "UnknownTag", + "state tag {bad}" + ); } + // #88's unsigned layout ends after `moved_at_ms`: `repo | id | to | chain | moved_at_ms`. + let v1_len = tag_at + 1 + 4 + (1 + 32 * w1.len()) + 8; + assert_eq!( + decode_record(&bytes[..v1_len], 1 << 20).unwrap_err().kind(), + "Truncated" + ); + // The leaf link is decoded strictly by `CapabilityLink::decode` (its version first). + let link_at = v1_len + 8 + 4; + let mut b = bytes.clone(); + b[link_at] ^= 0x02; + assert_eq!( + decode_record(&b, 1 << 20).unwrap_err().kind(), + "EmbeddedMalformed" + ); for i in 2..bytes.len() { let mut b = bytes.clone(); b[i] ^= 0x41; diff --git a/crates/synapse-store/tests/common/mod.rs b/crates/synapse-store/tests/common/mod.rs new file mode 100644 index 0000000..9528013 --- /dev/null +++ b/crates/synapse-store/tests/common/mod.rs @@ -0,0 +1,108 @@ +//! Shared fixture of the store's revision tests: real F1 capability links for byte-labelled +//! chains. A state move carries its chain's leaf link and the leaf audience's signature +//! (ADR 0003 B4, issue #89), so the chains here are digests of real signed links, not +//! arbitrary bytes. The link of label path `L` is issued by the key of `L` without its last +//! label (a fixture authority for a root link), names that parent link's digest, and +//! delegates to the key of `L`. Keys and nonces are SHA-256 of the labels, never fixed byte +//! values. + +#![allow(dead_code)] + +use ed25519_dalek::SigningKey; +use sha2::{Digest, Sha256}; +use synapse_auth::{ + Capability, CapabilityChain, CapabilityLink, ChainQuotas, ChangeScope, LinkCaveats, + OperationSet, PathScope, ReferenceScope, SignedStateMove, ROOT_PARENT, +}; +use synapse_core::{ChainPath, ChangesetId, RepoId, RevisionState, SynapseResult, WalSeq}; +use synapse_store::SynapseStore; + +pub fn repo() -> RepoId { + RepoId::new("aien-spark/synapse").unwrap() +} + +/// SHA-256 of a purpose and a label path. +pub fn derived(what: &str, labels: &[u8]) -> [u8; 32] { + let mut h = Sha256::new(); + h.update(b"synapse-store revision fixture\0"); + h.update(what.as_bytes()); + h.update([0]); + h.update(labels); + h.finalize().into() +} + +/// The key presenting the chain with label path `labels`. +pub fn key_of(labels: &[u8]) -> SigningKey { + SigningKey::from_bytes(&derived("key", labels)) +} + +fn caveats() -> LinkCaveats { + 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, + } +} + +/// The last link of the chain with label path `labels` (non-empty). +pub fn link_of(labels: &[u8]) -> CapabilityLink { + let (issuer, parent) = match labels.split_last() { + Some((_, [])) | None => ( + SigningKey::from_bytes(&derived("authority", &[])), + ROOT_PARENT, + ), + Some((_, up)) => (key_of(up), link_of(up).digest()), + }; + CapabilityLink::issue( + &issuer, + parent, + derived("nonce", labels), + repo(), + key_of(labels).verifying_key().to_bytes(), + caveats(), + ) +} + +/// The chain with label path `labels`, root first. +pub fn chain_of(labels: &[u8]) -> CapabilityChain { + CapabilityChain::new((1..=labels.len()).map(|n| link_of(&labels[..n])).collect()) +} + +/// Link digests of the chain with label path `labels`: prefixes of a label path are its +/// ancestors, so dominance follows the labels. +pub fn path(labels: &[u8]) -> ChainPath { + ChainPath::new( + chain_of(labels) + .link_digests() + .iter() + .map(|d| d.0) + .collect(), + ) + .unwrap() +} + +/// A move of `id` to `to` signed by the leaf of the chain with label path `labels`. +pub fn signed(labels: &[u8], id: ChangesetId, to: RevisionState, at: u64) -> SignedStateMove { + SignedStateMove::sign_new(&key_of(labels), repo(), id, to, &chain_of(labels), at).unwrap() +} + +/// Record a signed move by the chain with label path `labels` at server time `at`. +pub fn mv( + s: &mut SynapseStore, + labels: &[u8], + id: ChangesetId, + to: RevisionState, + at: u64, +) -> SynapseResult<WalSeq> { + s.advance_revision_state(signed(labels, id, to, at), at) +} diff --git a/docs/B4_REVISION_STATES.md b/docs/B4_REVISION_STATES.md index f686c75..ffd1d6c 100644 --- a/docs/B4_REVISION_STATES.md +++ b/docs/B4_REVISION_STATES.md @@ -2,7 +2,7 @@ ADR 0003 section 9 step B4 (issue aien-dev/synapse#28). Section 5.3 ("States") and need N14: a revision is `Private` (visible only to its owner's delegation chain) or `Draft` (visible within `Read` scope), then `Proposed`, then `Verified` (every claim and required action discharged on its exact tree), then `Canonical` (promoted by quorum, immutable). Revisions never change state backwards; replacing one creates a new revision and an obsolescence marker (B1). Builds on B1 (revisions, admission witnesses, chain dominance) and F1 (capability chains). -Code: `crates/synapse-core/src/revision_state.rs` (`RevisionState`, the order rule, the owner-move rule), `crates/synapse-store/src/revision.rs` (state in the ledger, visibility, moves), `crates/synapse-store/src/{lib,codec}.rs` (WAL kind 9, replay, checkpoint), `crates/synapse-api/src/lib.rs` (`advance_revision_state`, `read_revision`). Tests: unit tests in `crates/synapse-core/src/revision_state.rs` and `crates/synapse-store/src/revision.rs` (`b4_tests`), `crates/synapse-store/tests/b4_revision_states.rs`, `crates/synapse-api/tests/b4_revision_states.rs`. Evidence: `evidence/b4-revision-states/`. +Code: `crates/synapse-core/src/revision_state.rs` (`RevisionState`, the order rule, the owner-move rule), `crates/synapse-auth/src/state_move.rs` (`SignedStateMove`: the mover's signed statement and its check against the chain leaf, issue #89), `crates/synapse-store/src/revision.rs` (state in the ledger, visibility, moves), `crates/synapse-store/src/{lib,codec}.rs` (WAL kind 9, replay, checkpoint), `crates/synapse-api/src/lib.rs` (`advance_revision_state`, `read_revision`). Tests: unit tests in `crates/synapse-core/src/revision_state.rs`, `crates/synapse-auth/src/state_move.rs`, and `crates/synapse-store/src/revision.rs` (`b4_tests`, including the `b89_` tests), `crates/synapse-store/tests/b4_revision_states.rs` (with the shared real-F1-link fixture `tests/common/mod.rs`), `crates/synapse-api/tests/b4_revision_states.rs`. Evidence: `evidence/b4-revision-states/`. ## 1. Model and invariants @@ -11,27 +11,29 @@ Code: `crates/synapse-core/src/revision_state.rs` (`RevisionState`, the order ru * **Initial state.** Every admission starts `Private` (fails closed; see section 5 on the grant default). A second admission of identical content (B1 join) adds a witness and leaves the state and the owner chain unchanged: a joiner outside the owner chain cannot read the revision (so not the owner's witness or attestation), cannot find it in the change, and cannot move it; once the owner shares it, the joiner may read it but still not move it. * **Visibility.** A `Private` revision is visible only to its owner chains; any other state is visible to every chain the caller's `Read` scope allows. A revision a chain may not see behaves exactly like one that does not exist: reads, moves, parent references, and obsolescence markers naming it are refused with `ChangesetNotFound` and the same message as for an unknown revision. Change status seen by a chain lists only the revisions and markers it may see, and recomputes live, obsolete, and divergent from them. * **Who may move.** The owner chain may move its revision to `Draft` or `Proposed`. A move to `Verified` is refused to the owner (`RevisionStateMoveInvalid`): it needs claims (B3) and required-action receipts (E1) discharged on the exact tree, which no chain can assert by itself. Any move to `Canonical` is refused with `CanonicalOutsidePromotionQueue`, checked first, whatever the revision or chain: `Canonical` is reached only through the promotion queue's compare-and-swap (E2). -* **Determinism and replay.** The ledger is a pure function of the kind 7, 8, and 9 records in sequence order. Kind 9 is permanently the owner-move record: `Verified` and `Canonical` come only from the evidence-bearing records of B3, E1, and E2, never from kind 9. Kind 9 records are unsigned and the WAL seal is unkeyed (CRC32C and an unkeyed hash chain detect corruption, not forgery), so replay accepts a kind 9 record only when it is an owner move: `Private -> Draft`, `Private -> Proposed`, or `Draft -> Proposed`, by a chain that is or dominates the first admission's chain. Both rules are pure functions of the log that never change, so an old log keeps its meaning. Any other record (forged or corrupt) is kept in the log and in the state root but changes nothing, so replay, a checkpoint, and a live store rebuild the same states and no record sequence moves a revision backwards or past `Proposed`. +* **Determinism and replay.** The ledger is a pure function of the kind 7, 8, and 9 records in sequence order. Kind 9 is permanently the owner-move record: `Verified` and `Canonical` come only from the evidence-bearing records of B3, E1, and E2, never from kind 9. The WAL seal is unkeyed (CRC32C and an unkeyed hash chain detect corruption, not forgery), so each kind 9 record carries the mover's signature (issue #89) and replay applies it only when (1) the Ed25519 signature verifies strictly over the signed statement under the record's `mover_key`, and `mover_key` is the audience of the chain's leaf link (the record carries that link; its digest must be the chain's last digest, its parent the previous digest or the root parent, its repository the record's), and (2) it is an owner move: `Private -> Draft`, `Private -> Proposed`, or `Draft -> Proposed`, by a chain that is or dominates the first admission's chain (#88). Both rules are pure functions of the record and the log that never change, so an old log keeps its meaning. Any other record (forged or corrupt) is kept in the log and in the state root but changes nothing, so replay, a checkpoint, and a live store rebuild the same states and no record sequence moves a revision backwards or past `Proposed`. +* **Unverified moves on recovery (issue #89).** A kind 9 record whose signature does not verify or whose signer is not the chain leaf's audience cannot come from a store call (the store refuses such a move before writing), so it is evidence of tampering. `StrictFailClosed` recovery refuses the store with `RevisionStateMoveUnverified`, naming the count and the first such record; `TruncateTornTail` opens it, keeps the record as a no-op, and counts it. `SynapseStore::state_move_replay_report()` returns `StateMoveReplayReport { signature_invalid, signer_not_chain_leaf, not_owner_move, first_unverified, dropped_by_compaction }`; all zero for a log written only by stores. Way out (review of PR #100): `checkpoint_and_compact` leaves unverified kind 9 records out of the checkpoint (they change no state), so an operator who opens the store with `TruncateTornTail` and compacts gets a store strict recovery accepts again, with the same revision states; the compacting process reports the count in `dropped_by_compaction` (not persisted). Verified no-ops are kept. The strict refusal message says so. A verified move that fails the owner rule stays an ordinary counted no-op in both policies (as on #88): it depends on ledger state, while the signature check depends only on the record. ## 2. Operations | Operation | Store | API (F1 chained request) | |---|---|---| -| Move | `advance_revision_state(repo, changeset_id, to, chain, now_ms) -> WalSeq` | `advance_revision_state(req, now_ms)`: capability `Propose`; payload = `RevisionStateMovePayload`; chain = the request's chain | +| Move | `advance_revision_state(state_move: SignedStateMove, now_ms) -> WalSeq` | `advance_revision_state(req, now_ms)`: capability `Propose`; payload = `RevisionStateMovePayload` (built with `RevisionStateMovePayload::sign_new`); chain = the request's chain; mover key = the request's agent key; leaf link = the request chain's leaf | | Read | `get_revision_visible_to(repo, id, viewer)`, `change_status_visible_to(repo, change_id, viewer)` | `read_revision(req, now_ms)`: capability `Read`; payload = the 32-byte `ChangesetId`; every mutation path of the revision must be in the leaf's path scope, otherwise `ChangesetNotFound` | | Server-side read | `get_revision(repo, id)`, `change_status(repo, change_id)` (unfiltered) | through `store()` | -Move check order: `to == Canonical` (`CanonicalOutsidePromotionQueue`), then visibility (`ChangesetNotFound`), then owner chain (`AuthChainNotDominant`), then the owner-move rule (`RevisionStateMoveInvalid`). A store still writing v1 JSON records refuses moves with `EnvelopeVersionUnsupported`, as for B1 records. Nothing is written on a refusal. +Move check order: `to == Canonical` (`CanonicalOutsidePromotionQueue`), then the mover signature and leaf binding (`AuthSignatureInvalid`: a payload signed by another key, over another chain, state, or time, or with a flipped bit), then visibility (`ChangesetNotFound`), then owner chain (`AuthChainNotDominant`), then the owner-move rule (`RevisionStateMoveInvalid`). A store still writing v1 JSON records refuses moves with `EnvelopeVersionUnsupported`, as for B1 records. Nothing is written on a refusal. ## 3. Canonical binary layout (principle P5) All integers little-endian; `str` = `u32 len | UTF-8`; trailing bytes refused. * State tag: `Private` = 1, `Draft` = 2, `Proposed` = 3, `Verified` = 4, `Canonical` = 5; 0 and 6..=255 are not states. -* WAL kind 9 `RevisionStateMoved`: `repo str | changeset_id [32] | to u8 | u32 len | chain | moved_at_ms u64`. Binary only (no v1 JSON form); an unknown state tag is `CodecRefusal::UnknownTag { field: "revision state" }`. -* `RevisionStateMovePayload`: exactly `changeset_id [32] | to u8` (33 bytes); anything else, or an unknown tag, is `EnvelopeMalformed`. +* Signed statement (issue #89): `"SYNAPSE_STATE_MOVE_SIGN_V1\0" | str repo | changeset_id [32] | to u8 | chain (u8 count | link digest [32]*) | signed_at_ms u64`, signed with Ed25519 and checked with `verify_strict` (`ed25519-dalek`, as for every other signature here). +* WAL kind 9 `RevisionStateMoved` (signed layout, issue #89): `repo str | changeset_id [32] | to u8 | u32 len | chain | moved_at_ms u64 | signed_at_ms u64 | u32 len | leaf_link | mover_key [32] | signature [64]`; `leaf_link` is the F1 link encoding. Binary only (no v1 JSON form); an unknown state tag is `CodecRefusal::UnknownTag { field: "revision state" }`, a malformed leaf link is `EmbeddedMalformed`, a cut record is `Truncated`, extra bytes are `TrailingBytes`. The unsigned layout of #88 (ending at `moved_at_ms`) is not accepted: it decodes as `Truncated`. #88 was never merged, so no store holds it, and a second kind 9 layout would keep forgeable records readable. +* `RevisionStateMovePayload`: exactly `changeset_id [32] | to u8 | signed_at_ms u64 | signature [64]` (105 bytes); anything else (including the 33-byte #88 payload), or an unknown tag, is `EnvelopeMalformed`. * Checkpoint v2: the revision section of B1 now holds kind 7, 8, or 9 records. -* State root: kind 9 records join the revision part of the root (B1) with digest input `u64 repo len | repo | changeset_id | tag | chain | moved_at_ms`; stores without revision records keep every existing root. +* State root: kind 9 records join the revision part of the root (B1) with digest input `u64 repo len | repo | changeset_id | tag | chain | moved_at_ms | signed_at_ms | u64 leaf link len | leaf_link | mover_key | signature`; stores without revision records keep every existing root. ## 4. Acceptance @@ -41,9 +43,17 @@ All integers little-endian; `str` = `u32 len | UTF-8`; trailing bytes refused. | A `Private` revision is invisible to every key outside its owner chain | `b4_private_revision_is_invisible_to_every_key_outside_its_owner_chain` (read, change status, parent, marker, and move, for the delegation tree and 200 random chains, after replay and a checkpoint); `b4_api_private_revision_is_invisible_outside_its_owner_chain_with_real_f1_chains`; joins: `b4_joining_identical_content_grants_no_ownership_of_a_private_revision` (also after replay and a checkpoint), `b4_api_joining_identical_content_grants_no_ownership_of_a_private_revision` | | Any move to `Canonical` outside the promotion queue is refused | `b4_any_move_to_canonical_outside_the_promotion_queue_is_refused`; `b4_api_move_to_canonical_outside_the_promotion_queue_is_refused` (including a grant with `Publish` and `CanonicalViaPromotionQueue`); `b4_owner_moves_never_reach_verified_or_canonical` | +| Acceptance (issue #89) | Test | +|---|---| +| A forged or resealed kind 9 record with a bad signature or a non-leaf signer changes nothing on replay | `b89_forged_owner_move_resealed_in_the_wal_changes_nothing_on_replay` (a broken-signature and a validly-signed-by-another-key owner move written through the store's own framing: torn-tail recovery keeps both as counted no-ops, strict recovery refuses the store with `RevisionStateMoveUnverified`, both before and after checkpoint and compaction); the ledger property test now mixes both forgeries into its 200 cases and checks the replay report; `b89_api_state_moves_must_be_signed_by_the_request_agent` (API: a payload signed by another key, over another chain, state, or time, or with a flipped bit, is `AuthSignatureInvalid` and writes nothing) | +| A legitimate signed move round-trips write, replay, checkpoint, and compaction, and the state root covers it | `b89_signed_owner_move_round_trips_replay_checkpoint_and_compaction`; `b89_state_root_record_digest_covers_the_signature_fields` | +| Review of PR #100: a torn-tail store can be compacted back into one strict recovery accepts | `b89_torn_tail_compaction_drops_unverified_moves_so_strict_recovery_accepts_the_store` (red on `30353d6`: `red-green/b89-red-compaction.txt`) | +| Review of PR #100: `verify()` alone accepts a forger-minted leaf link; the owner rule refuses it | `b89_a_forger_minted_leaf_link_verifies_but_never_owns_a_revision` (a self-minted root link and a self-appended link under the owner chain both verify; `plan_move` refuses both with `AuthChainNotDominant` and replay keeps them as no-ops; fails if ownership is widened to descendant chains) | +| Strict codec: malformed or truncated records refused typed | `b4_state_move_records_round_trip_and_malformed_bytes_are_refused_typed` (signed layout: every cut, trailing bytes, unknown tag, the #88 layout, a malformed leaf link); the API payload loop in `b4_api_*` (empty, 33-byte #88 payload, bad tag, 104 and 106 bytes); `crates/synapse-auth/src/state_move.rs` unit tests (a move signed by the leaf verifies for root and derived chains; a flipped bit, another signer, a link that is not the chain leaf, and a link of another repository are refused) | + Also: `b4_state_move_records_round_trip_and_malformed_bytes_are_refused_typed`, `b4_state_tags_round_trip_and_unknown_tags_are_not_states`, `b4_every_allowed_move_raises_the_rank_and_every_other_pair_is_refused`. The B1 prune tests now share the orchestrator's revision (`Private -> Draft`) before checking that other chains are refused for dominance, since a `Private` revision is now unknown to them. -Red before green: each acceptance test was run against the B4 commit with one mutation that removes the behaviour it proves (`evidence/b4-revision-states/red-green/red.txt`), and fails; `green.txt` holds the passing runs. The join tests (review of PR #88) were committed before their fix and fail on the earlier implementation (`red-join.txt`); so was the replay test `b4_replay_refuses_a_forged_move_to_verified` (`red-replay.txt`). +Red before green: each acceptance test was run against the B4 commit with one mutation that removes the behaviour it proves (`evidence/b4-revision-states/red-green/red.txt`), and fails; `green.txt` holds the passing runs. The join tests (review of PR #88) were committed before their fix and fail on the earlier implementation (`red-join.txt`); so was the replay test `b4_replay_refuses_a_forged_move_to_verified` (`red-replay.txt`). Issue #89: `b89_forged_owner_move_resealed_in_the_wal_changes_nothing_on_replay` fails on the #88 head `cf3879f`, where a resealed unsigned owner move publishes a `Private` revision on replay (`red-green/b89-red.txt`); `b89-green.txt` holds the passing runs on this branch; the review fixes have `b89-red-compaction.txt` and `b89-green-review.txt`. ## 5. Limits and deviations @@ -51,7 +61,14 @@ Red before green: each acceptance test was run against the B4 commit with one mu * `Verified` is not reachable yet: it is recorded when claims (B3) and required-action receipts (E1) are discharged on the exact tree. `Canonical` is reached only by the promotion queue (E2), which does not exist yet; `CanonicalPromoted` (the canonical reference head) is unchanged and does not consult revision states. * An identical-content admission from a chain that may not see the existing `Private` revision joins it (B1 identity covers content only) and reports `joined_existing_revision`. That reveals only that the same content already exists under the change (which the joiner already holds); the joiner gains no ownership, cannot read the owner's witnesses or attestations, and cannot publish the revision. * The cost of that restrictive reading: a joiner outside the owner chain cannot read, name as a parent, or mark the revision it submitted itself until the owner shares it. The reverse exposure remains: when the owner publishes, every joiner's attestation (its authorship) becomes visible with the revision without that joiner's consent; this matters only for a joiner the owner could not already see (a change-scope joiner outside the owner's subtree). Low. -* Kind 9 records are not signed, so a forged owner move (for example publishing a `Private` revision to `Draft`) written straight into the WAL and resealed would apply on replay; it can never reach `Verified` or `Canonical` or move backwards. Signing state moves and verifying the mover at replay is issue #89. Replay does not re-verify kind 7 and 8 signatures either. +* **Signed moves (issue #89), what they do not cover.** Replay binds a move to the key the chain's leaf link names, but the chain digests themselves come from the unkeyed log. An attacker who can rewrite and reseal the whole WAL can still change a kind 7 admission's chain field to links of their own making and then sign moves under those links; that needs edits to kind 7 records, not only appended kind 9 records. Closing it needs kind 7 and 8 records that carry their leaf link too, or a keyed seal or chain anchor; that is a follow-up. +* **Kinds 7 and 8 are not re-verified at replay.** Their envelope and marker signatures were checked on admission; re-checking only the signature on replay would not bind the unsigned `chain` field next to it (see the bullet above), so it is left for the same follow-up as that binding. +* **Mover time.** The issue asks for `moved_at_ms` under the signature. The agent cannot sign the server's clock, so the mover signs its own `signed_at_ms` (the precedent of obsolescence markers: signed `signed_at_ms`, server `recorded_at_ms`); the record keeps both, and the state root covers both. +* **`signed_at_ms` is self-reported.** It is never checked against the server clock or the leaf link's `issued_at_ms`/`expires_at_ms` window, on the API path or at replay, so it is not evidence of when the mover acted. Replay does not re-check revocation or expiry of the leaf link either: a stolen leaf key whose link was later revoked, together with write access to the WAL, yields a move that verifies. That needs both at once; low. +* **`verify()` binds, it does not authorize.** `SignedStateMove::verify` never checks the leaf link's issuer or caveats; it is safe only together with the owner rule (the chain is or dominates the first admission's chain), which pins the leaf to an admitted link. Its doc comment states this precondition for any future caller; a descendant chain is not enough. +* **No from-state or nonce under the signature.** The signed statement names the target state, not the state moved from, and carries no nonce or sequence number. That is harmless while owner moves only go forward (a replayed signature is an in-place or backward move, both refused). A later step that adds a downward transition (for example a rejection back to `Draft`) makes old signed moves replayable by anyone who can append to the WAL, and must bind the from-state or a nonce. +* **Merge order.** The kind 9 layout changed in place, without a version marker, because #88 never shipped. #88 must not be merged and deployed on its own and then written to: such a store would not open under this change (`Truncated`). Merge #88 and this PR together. +* **Server-originated moves.** No server path moves revision states on this base (`Verified` is not reachable; `Canonical` waits for E2). Server-signed `Verified` and `Canonical` moves need the server machine key of B5 (PR #95) and are a follow-up there; kind 9 stays the owner-move record. * Change-existence oracle (B1, low): when every revision of a change is another owner's `Private` revision, a chain that neither descends from the creating chain nor names the change gets `AuthChangeOutOfScope` where an unknown change would admit it as creator. `ChangeId`s are 16 random bytes, so this needs the ID. * Upgrade: revisions admitted before B4 replay as `Private` (no kind 9 record), so after the upgrade they are invisible to non-owners until an owner moves them. This fails closed. * Store-level `get_revision` and `change_status`, and `SynapseService::store()`, are unfiltered server-side reads; callers acting for an agent use the `_visible_to` reads or `read_revision`. Subscriptions, search, and predictions (section 5.7) do not exist yet and must filter the same way when they are built. diff --git a/evidence/b4-revision-states/SHA256SUMS b/evidence/b4-revision-states/SHA256SUMS index 1be38bf..03f70ba 100644 --- a/evidence/b4-revision-states/SHA256SUMS +++ b/evidence/b4-revision-states/SHA256SUMS @@ -1,3 +1,7 @@ +fdc60f94f908127c28c8dbc322d34dc0ae63028d2b40fa917047828338affbbd red-green/b89-green-review.txt +f542b6bc30a981f71a146607a5314a2349f4018376d61b41bef06578102b52bd red-green/b89-green.txt +bec795c5b0135f5f11d4ee8b3be9b2bed551dc3cc4d20ef7047c0ceb9576224e red-green/b89-red-compaction.txt +712d20025b36c0a853b5e599e26b5ceed217cb5ccbf28cc65f1735d61c849e18 red-green/b89-red.txt 9b646db93b9478d40270919e05242bbd57ba88a3d1eb1b366f20fd47d9aa2548 red-green/green.txt c4d1614b0fc4b83436bedf21ebaf3a6bf04a07f3364d3dc21d3e7d9371bcb30b red-green/red-join.txt 9893d4c58160b80959da78d600a95e8e32fda910fa16f0ed1fb88aa69e0db92b red-green/red-replay.txt diff --git a/evidence/b4-revision-states/red-green/b89-green-review.txt b/evidence/b4-revision-states/red-green/b89-green-review.txt new file mode 100644 index 0000000..039e7f2 --- /dev/null +++ b/evidence/b4-revision-states/red-green/b89-green-review.txt @@ -0,0 +1,11 @@ +# PR #100 review fixes green (2026-10-17, commit deffaec on fix/89-signed-state-moves, stacked on PR #88 head cf3879f; +# workspace 351 passed, 0 failed, 1 ignored; clippy -D warnings and fmt clean) +# Mutation check: owned_by widened to descendant chains -> b89_a_forger_minted_leaf_link_verifies_but_never_owns_a_revision FAILED (restored). + +# Command: nice -n 19 cargo test --locked -j 4 -p synapse-store --lib b89_ -- --test-threads=1 +test revision::b4_tests::b89_a_forger_minted_leaf_link_verifies_but_never_owns_a_revision ... ok +test revision::b4_tests::b89_forged_owner_move_resealed_in_the_wal_changes_nothing_on_replay ... ok +test revision::b4_tests::b89_signed_owner_move_round_trips_replay_checkpoint_and_compaction ... ok +test revision::b4_tests::b89_state_root_record_digest_covers_the_signature_fields ... ok +test revision::b4_tests::b89_torn_tail_compaction_drops_unverified_moves_so_strict_recovery_accepts_the_store ... ok +test result: ok. 5 passed; 0 failed; 0 ignored; 0 measured; 55 filtered out; finished diff --git a/evidence/b4-revision-states/red-green/b89-green.txt b/evidence/b4-revision-states/red-green/b89-green.txt new file mode 100644 index 0000000..9b671ee --- /dev/null +++ b/evidence/b4-revision-states/red-green/b89-green.txt @@ -0,0 +1,49 @@ +# Issue #89 green (2026-10-17, commit 90b2835 on fix/89-signed-state-moves, stacked on PR #88 head cf3879f; +# workspace 349 passed, 0 failed, 1 ignored; clippy -D warnings and fmt clean) + +# Command: nice -n 19 cargo test --locked -j 4 -p synapse-store --lib b89_ -- --test-threads=1 +test revision::b4_tests::b89_forged_owner_move_resealed_in_the_wal_changes_nothing_on_replay ... ok +test revision::b4_tests::b89_signed_owner_move_round_trips_replay_checkpoint_and_compaction ... ok +test revision::b4_tests::b89_state_root_record_digest_covers_the_signature_fields ... ok +test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 55 filtered out; finished + +# Command: nice -n 19 cargo test --locked -j 4 -p synapse-store --lib b4_ -- --test-threads=1 +test revision::b4_tests::b4_property_forged_record_sequences_never_move_a_revision_backwards ... ok +test revision::b4_tests::b4_replay_refuses_a_forged_move_to_verified ... ok +test revision::b4_tests::b89_forged_owner_move_resealed_in_the_wal_changes_nothing_on_replay ... ok +test revision::b4_tests::b89_signed_owner_move_round_trips_replay_checkpoint_and_compaction ... ok +test revision::b4_tests::b89_state_root_record_digest_covers_the_signature_fields ... ok +test result: ok. 5 passed; 0 failed; 0 ignored; 0 measured; 53 filtered out; finished + +# Command: nice -n 19 cargo test --locked -j 4 -p synapse-store --test b4_revision_states -- --test-threads=1 +test b4_any_move_to_canonical_outside_the_promotion_queue_is_refused ... ok +test b4_joining_identical_content_grants_no_ownership_of_a_private_revision ... ok +test b4_private_revision_is_invisible_to_every_key_outside_its_owner_chain ... ok +test b4_property_random_operation_sequences_never_move_a_revision_backwards ... ok +test b4_state_move_records_round_trip_and_malformed_bytes_are_refused_typed ... ok +test result: ok. 5 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished + +# Command: nice -n 19 cargo test --locked -j 4 -p synapse-store --test b1_change_identity -- --test-threads=1 +test b1_divergence_two_live_successors_is_detected ... ok +test b1_every_v1_changeset_id_still_resolves_to_its_record ... ok +test b1_identical_content_two_agents_one_chain_one_change_is_one_revision_two_attestations_two_witnesses ... ok +test b1_join_from_key_outside_creating_chain_without_change_scope_is_refused ... ok +test b1_prune_by_chain_not_dominating_creating_chain_is_refused ... ok +test b1_repeat_same_repo_did_idempotency_key_returns_first_wal_seq ... ok +test b1_revision_records_round_trip_and_malformed_bytes_are_refused_typed ... ok +test b1_rewrite_keeps_change_id_and_gets_new_changeset_id ... ok +test result: ok. 8 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished + +# Command: nice -n 19 cargo test --locked -j 4 -p synapse-auth --lib state_move -- --test-threads=1 +test state_move::tests::a_bad_signature_or_a_signer_that_is_not_the_leaf_is_refused_typed ... ok +test state_move::tests::a_leaf_link_of_another_repository_is_refused ... ok +test state_move::tests::a_move_signed_by_the_chain_leaf_verifies_for_root_and_derived_chains ... ok +test state_move::tests::faults_map_to_auth_signature_invalid ... ok +test result: ok. 4 passed; 0 failed; 0 ignored; 0 measured; 1 filtered out; finished + +# Command: nice -n 19 cargo test --locked -j 4 -p synapse-api --test b4_revision_states -- --test-threads=1 +test b4_api_joining_identical_content_grants_no_ownership_of_a_private_revision ... ok +test b4_api_move_to_canonical_outside_the_promotion_queue_is_refused ... ok +test b4_api_private_revision_is_invisible_outside_its_owner_chain_with_real_f1_chains ... ok +test b89_api_state_moves_must_be_signed_by_the_request_agent ... ok +test result: ok. 4 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished diff --git a/evidence/b4-revision-states/red-green/b89-red-compaction.txt b/evidence/b4-revision-states/red-green/b89-red-compaction.txt new file mode 100644 index 0000000..dcddc4d --- /dev/null +++ b/evidence/b4-revision-states/red-green/b89-red-compaction.txt @@ -0,0 +1,13 @@ +# PR #100 review note 1 red: head 30353d6 plus only the test changes of the next commit, run with +# nice -n 19 cargo test --locked -p synapse-store -j 4 --lib b89_ + +test revision::b4_tests::b89_state_root_record_digest_covers_the_signature_fields ... ok +test revision::b4_tests::b89_a_forger_minted_leaf_link_verifies_but_never_owns_a_revision ... ok +test revision::b4_tests::b89_forged_owner_move_resealed_in_the_wal_changes_nothing_on_replay ... ok +test revision::b4_tests::b89_signed_owner_move_round_trips_replay_checkpoint_and_compaction ... ok +test revision::b4_tests::b89_torn_tail_compaction_drops_unverified_moves_so_strict_recovery_accepts_the_store ... FAILED +thread 'revision::b4_tests::b89_torn_tail_compaction_drops_unverified_moves_so_strict_recovery_accepts_the_store' panicked at crates/synapse-store/src/revision.rs:1306:13: +assertion `left == right` failed: StateMoveReplayReport { signature_invalid: 1, signer_not_chain_leaf: 1, not_owner_move: 1, first_unverified: Some((WalSeq(2), SignatureInvalid)) } + left: 2 + right: 0 +test result: FAILED. 4 passed; 1 failed; 0 ignored; 0 measured; 55 filtered out; finished diff --git a/evidence/b4-revision-states/red-green/b89-red.txt b/evidence/b4-revision-states/red-green/b89-red.txt new file mode 100644 index 0000000..5aec551 --- /dev/null +++ b/evidence/b4-revision-states/red-green/b89-red.txt @@ -0,0 +1,89 @@ +# Issue #89 red: PR #88 head cf3879f plus only the test below (git diff), run with +# nice -n 19 cargo test --locked -p synapse-store -j 4 --lib b89_ + +diff --git a/crates/synapse-store/src/revision.rs b/crates/synapse-store/src/revision.rs +index 87dd68f..73cfb60 100644 +--- a/crates/synapse-store/src/revision.rs ++++ b/crates/synapse-store/src/revision.rs +@@ -995,4 +995,59 @@ mod b4_tests { + "kept in the log, applied as no-ops" + ); + } ++ ++ /// Issue #89 red test on the #88 head: a forged owner move (`Private -> Draft` under the ++ /// owner's chain), written straight into the WAL through the store's own framing (valid ++ /// CRC32C and hash chain, so a resealed forgery) without the owner's key, must change ++ /// nothing on replay. ++ #[test] ++ fn b89_forged_owner_move_resealed_in_the_wal_changes_nothing_on_replay() { ++ use crate::{FsyncPolicy, RecoveryPolicy, StoreLimits, SynapseStore}; ++ let dir = std::env::temp_dir().join(format!("synapse-b89-red-{}", std::process::id())); ++ let _ = std::fs::remove_dir_all(&dir); ++ let open = || { ++ SynapseStore::open( ++ &dir, ++ FsyncPolicy::EveryCommit, ++ RecoveryPolicy::TruncateTornTail, ++ StoreLimits::default(), ++ ) ++ .unwrap() ++ }; ++ let mut s = open(); ++ let mut rng = SplitMix64(0xB89); ++ let (envelope, owner) = match admission(&mut rng, 1) { ++ WalRecord::RevisionAdmitted { envelope, chain, .. } => (envelope, chain), ++ _ => unreachable!(), ++ }; ++ let body = 1u32.to_le_bytes(); ++ let blobs = vec![(BlobDigest::compute(&body), body.to_vec())]; ++ let id = envelope.changeset_id(); ++ s.admit_revision( ++ envelope, ++ &blobs, ++ crate::AdmissionAuthority { ++ chain: owner.clone(), ++ change_scope: Vec::new(), ++ }, ++ 5_000, ++ ) ++ .unwrap(); ++ let forged = WalRecord::RevisionStateMoved { ++ repo_id: repo(), ++ changeset_id: id, ++ to: RevisionState::Draft, ++ chain: owner, ++ moved_at_ms: 6_000, ++ }; ++ s.append_revision_record(forged, &[]).unwrap(); ++ drop(s); ++ let s = open(); ++ assert_eq!( ++ s.get_revision(&repo(), id).unwrap().state, ++ RevisionState::Private, ++ "a forged, resealed owner move must change nothing on replay" ++ ); ++ let _ = std::fs::remove_dir_all(&dir); ++ } + } + + +running 1 test +test revision::b4_tests::b89_forged_owner_move_resealed_in_the_wal_changes_nothing_on_replay ... FAILED + +failures: + +---- revision::b4_tests::b89_forged_owner_move_resealed_in_the_wal_changes_nothing_on_replay stdout ---- + +thread 'revision::b4_tests::b89_forged_owner_move_resealed_in_the_wal_changes_nothing_on_replay' (571453) panicked at crates/synapse-store/src/revision.rs:1046:9: +assertion `left == right` failed: a forged, resealed owner move must change nothing on replay + left: Draft + right: Private +note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace + + +failures: + revision::b4_tests::b89_forged_owner_move_resealed_in_the_wal_changes_nothing_on_replay + +test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 55 filtered out; finished in 0.02s + +error: test failed, to rerun pass `-p synapse-store --lib`