Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/synapse/patches/5092e22fe86b714e # synapse A component of the AienOS ecosystem. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers ## GitHub aien-dev/synapse#69 (code only) closed derived `5092e22fe86b714e` #69 Imported from GitHub aien-dev/synapse#69 (code only) GitHub's metadata for this pull request is unavailable: its state is DERIVED from the commits (merged: the head is reachable from this project's main; open: GitHub kept a merge ref; else closed). Base `e089f3b3b3fed9fc06e1d3ec54c32ec314cc7dbc` · Head `b769cb10b76c39f2523e56e44dc1b6aca63207ed` ### Fetch it A git bundle of the pull request's head, 22431 bytes. ``` curl -fsSL https://interplane.io/drakestapleton/synapse/patches/5092e22fe86b714e.bundle -o 5092e22fe86b714e.bundle git fetch 5092e22fe86b714e.bundle refs/pull/69/head ``` Raw bundle · Diff ### Provenance This proposal is imported from GitHub; it is not signed by its author. Its import statement and source record: ``` github-import 1 aien-dev/synapse 69 b769cb10b76c39f2523e56e44dc1b6aca63207ed ``` ``` {"kind":"github-import","owner":"aien-dev","repo":"synapse","number":69,"url":"https://github.com/aien-dev/synapse/pull/69","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:39:15Z","metadata":"unavailable","state_derived":true} ``` ### Changes ``` diff --git a/Cargo.lock b/Cargo.lock index 317e3df..29fb32d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -483,6 +483,8 @@ dependencies = [ "sha2", "synapse-auth", "synapse-core", + "synapse-crumb", + "synapse-evidence", "synapse-store", ] diff --git a/crates/synapse-radicle/Cargo.toml b/crates/synapse-radicle/Cargo.toml index dc9d810..f0622af 100644 --- a/crates/synapse-radicle/Cargo.toml +++ b/crates/synapse-radicle/Cargo.toml @@ -15,4 +15,8 @@ serde_json.workspace = true sha2.workspace = true synapse-auth.workspace = true synapse-core.workspace = true +synapse-evidence.workspace = true synapse-store.workspace = true + +[dev-dependencies] +synapse-crumb.workspace = true diff --git a/crates/synapse-radicle/src/identity.rs b/crates/synapse-radicle/src/identity.rs new file mode 100644 index 0000000..baa9037 --- /dev/null +++ b/crates/synapse-radicle/src/identity.rs @@ -0,0 +1,623 @@ +//! Repository identity document (ADR 0003 section 5.5 "Trust root", step E0). +//! +//! The document names who may change a repository's trust settings and which machines it +//! trusts: +//! +//! * `delegates` and `threshold`: the keys whose signatures change the document, and how many +//! distinct delegates must sign. This mirrors Radicle `refs/rad/id` delegates and threshold +//! (ADR 0001 section 2.2 item 3 is unchanged; delegates can be machines); +//! * `executors`: the registered executor machine keys whose evidence receipts may count +//! (section 5.5 "Who may execute"; consumed by E1); +//! * `server_key`: the server's own machine key, which signs derivation attestations +//! (section 5.1 `DerivationAttestation`; consumed by B5). +//! +//! Every revision after genesis is an [`IdentityEdit`]: the full next document plus delegate +//! signatures. An edit applies only if at least the *current* document's threshold of its +//! *current* delegates signed it, as in Radicle. The next document carries the revision +//! number and the digest of the document it replaces, so a signed edit cannot be replayed +//! onto a later revision, applied out of order, or moved to another repository. +//! +//! [`IdentityLog`] records the `WalSeq` from which each revision is in effect, so a question +//! such as "was this executor registered when that receipt was accepted" is answered from the +//! document in effect at that `WalSeq`. A later edit never revokes a receipt already +//! accepted; it refuses only receipts accepted from its own `WalSeq` on. +//! +//! Format (ADR 0003 principle P5): fixed-width, little-endian, length-prefixed binary, no +//! Rust-specific serialization. See `docs/E0_IDENTITY_DOCUMENT.md` for the byte layout. + +use ed25519_dalek::{Signature, Signer, SigningKey, VerifyingKey}; +use sha2::{Digest, Sha256}; +use std::collections::BTreeSet; +use synapse_core::{ + decode_did_key_ed25519, RefusalCode, RepoId, SynapseError, SynapseResult, WalSeq, +}; +use synapse_evidence::{EvidenceReceipt, EvidenceReceiptId, ReceiptError}; + +/// The only identity document record version this module reads or writes. +pub const IDENTITY_DOCUMENT_VERSION_V1: u16 = 1; +/// Domain tag that opens every encoded identity document. +pub const DOMAIN_IDENTITY_DOCUMENT_V1: &[u8] = b"SYNAPSE_IDENTITY_DOCUMENT_V1\0"; +/// Domain tag for [`IdentityDocumentDigest`]. +pub const DOMAIN_IDENTITY_DOCUMENT_DIGEST_V1: &[u8] = b"SYNAPSE_IDENTITY_DOCUMENT_DIGEST_V1\0"; +/// Domain tag for a delegate's Ed25519 signature over an identity document digest. +pub const DOMAIN_IDENTITY_EDIT_SIGN_V1: &[u8] = b"SYNAPSE_IDENTITY_EDIT_SIGN_V1\0"; +/// Domain tag that opens every encoded identity edit. +pub const DOMAIN_IDENTITY_EDIT_V1: &[u8] = b"SYNAPSE_IDENTITY_EDIT_V1\0"; +/// Most delegates one document may list. +pub const MAX_DELEGATES: usize = 256; +/// Most registered executors one document may list. +pub const MAX_EXECUTORS: usize = 4096; +/// Most signatures one edit may carry. +pub const MAX_EDIT_SIGNATURES: usize = MAX_DELEGATES; +/// Longest repository identifier, in bytes, the decoder accepts. +pub const MAX_REPO_ID_BYTES: usize = 4096; +/// Largest encoded document the edit decoder accepts (every list and string at its cap). +pub const MAX_DOCUMENT_BYTES: usize = DOMAIN_IDENTITY_DOCUMENT_V1.len() + + 2 + + 4 + + MAX_REPO_ID_BYTES + + 8 + + 32 + + 4 + + 4 + + MAX_DELEGATES * 32 + + 4 + + MAX_EXECUTORS * 32 + + 32; + +/// Raw 32-byte Ed25519 public key. +pub type Ed25519PublicKey = [u8; 32]; + +/// Domain-separated SHA-256 digest of one encoded identity document. Never a `BlobDigest`, +/// `ChangesetId`, or receipt identity. +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] +pub struct IdentityDocumentDigest(pub [u8; 32]); + +impl IdentityDocumentDigest { + /// The `prev` of a genesis document. + pub const ZERO: Self = Self([0u8; 32]); + + pub fn to_hex(self) -> String { + hex::encode(self.0) + } +} + +/// One revision of a repository's identity document. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct RepositoryIdentityDocument { + pub repo_id: RepoId, + /// 0 for genesis; each edit adds exactly 1. + pub revision: u64, + /// Digest of the document this one replaces; [`IdentityDocumentDigest::ZERO`] for genesis. + pub prev: IdentityDocumentDigest, + /// Distinct delegate signatures an edit of this document needs (1 to delegate count). + pub threshold: u32, + /// Strictly ascending, unique, at most [`MAX_DELEGATES`], at least one. + pub delegates: Vec, + /// Registered executor machine keys. Strictly ascending, unique, at most [`MAX_EXECUTORS`]. + pub executors: Vec, + /// The server's machine key (signs derivation attestations). + pub server_key: Ed25519PublicKey, +} + +fn invalid(message: impl Into) -> SynapseError { + SynapseError::new(RefusalCode::RadicleIdentityInvalid, message) +} + +/// A key is usable only if it decodes to a curve point that is not of small order. +fn check_key(key: &Ed25519PublicKey, what: &str) -> SynapseResult { + let vk = VerifyingKey::from_bytes(key) + .map_err(|_| invalid(format!("{what} is not an Ed25519 public key")))?; + if vk.is_weak() { + return Err(invalid(format!("{what} is a small-order Ed25519 key"))); + } + Ok(vk) +} + +fn check_key_list(keys: &[Ed25519PublicKey], cap: usize, what: &str) -> SynapseResult<()> { + if keys.len() > cap { + return Err(invalid(format!( + "{} {what} keys exceed the cap of {cap}", + keys.len() + ))); + } + if keys.windows(2).any(|w| w[0] >= w[1]) { + return Err(invalid(format!( + "{what} keys must be strictly ascending and unique" + ))); + } + for k in keys { + check_key(k, what)?; + } + Ok(()) +} + +impl RepositoryIdentityDocument { + /// Check every structural rule of record version 1. + pub fn validate(&self) -> SynapseResult<()> { + if self.repo_id.as_str().len() > MAX_REPO_ID_BYTES { + return Err(invalid("repository identifier exceeds its cap")); + } + if (self.revision == 0) != (self.prev == IdentityDocumentDigest::ZERO) { + return Err(invalid( + "revision 0, and only revision 0, has the zero prev digest", + )); + } + if self.delegates.is_empty() { + return Err(invalid("identity document must have at least one delegate")); + } + check_key_list(&self.delegates, MAX_DELEGATES, "delegate")?; + if self.threshold == 0 || self.threshold as usize > self.delegates.len() { + return Err(invalid(format!( + "invalid threshold {} for {} delegates", + self.threshold, + self.delegates.len() + ))); + } + check_key_list(&self.executors, MAX_EXECUTORS, "executor")?; + check_key(&self.server_key, "server key")?; + Ok(()) + } + + /// The next revision's starting point: this document with `revision + 1` and `prev` set to + /// this document's digest. The caller then changes what the edit changes. + pub fn successor(&self) -> Self { + let mut next = self.clone(); + next.revision = self.revision.saturating_add(1); + next.prev = self.digest(); + next + } + + /// Canonical record bytes (see `docs/E0_IDENTITY_DOCUMENT.md`). + pub fn encode(&self) -> Vec { + let repo = self.repo_id.as_str().as_bytes(); + let mut buf = Vec::with_capacity( + DOMAIN_IDENTITY_DOCUMENT_V1.len() + + 90 + + repo.len() + + 32 * (self.delegates.len() + self.executors.len()), + ); + buf.extend_from_slice(DOMAIN_IDENTITY_DOCUMENT_V1); + buf.extend_from_slice(&IDENTITY_DOCUMENT_VERSION_V1.to_le_bytes()); + buf.extend_from_slice(&(repo.len() as u32).to_le_bytes()); + buf.extend_from_slice(repo); + buf.extend_from_slice(&self.revision.to_le_bytes()); + buf.extend_from_slice(&self.prev.0); + buf.extend_from_slice(&self.threshold.to_le_bytes()); + for list in [&self.delegates, &self.executors] { + buf.extend_from_slice(&(list.len() as u32).to_le_bytes()); + for k in list { + buf.extend_from_slice(k); + } + } + buf.extend_from_slice(&self.server_key); + buf + } + + /// Decode and validate one record. Refuses a wrong tag or version, a truncated record, + /// trailing bytes, a count above its cap (before allocating for it), and any document + /// [`validate`](Self::validate) refuses. Every refusal is `RadicleIdentityInvalid`. + pub fn decode(bytes: &[u8]) -> SynapseResult { + let mut r = Reader::new(bytes); + let doc = Self::read(&mut r)?; + r.finish()?; + Ok(doc) + } + + fn read(r: &mut Reader<'_>) -> SynapseResult { + r.tag(DOMAIN_IDENTITY_DOCUMENT_V1, "identity document")?; + let version = r.u16()?; + if version != IDENTITY_DOCUMENT_VERSION_V1 { + return Err(invalid(format!( + "identity document version {version} is not supported" + ))); + } + let repo_len = r.count(MAX_REPO_ID_BYTES, 1, "repo_id")?; + let repo = + std::str::from_utf8(r.take(repo_len)?).map_err(|_| invalid("repo_id is not UTF-8"))?; + let repo_id = RepoId::new(repo).map_err(|e| invalid(e.message))?; + let revision = r.u64()?; + let prev = IdentityDocumentDigest(r.array()?); + let threshold = r.u32()?; + let delegates = r.keys(MAX_DELEGATES, "delegates")?; + let executors = r.keys(MAX_EXECUTORS, "executors")?; + let server_key = r.array()?; + let doc = Self { + repo_id, + revision, + prev, + threshold, + delegates, + executors, + server_key, + }; + doc.validate()?; + Ok(doc) + } + + /// SHA-256 over the digest tag, the record length (u64 LE), and the record. + pub fn digest(&self) -> IdentityDocumentDigest { + let bytes = self.encode(); + let mut h = Sha256::new(); + h.update(DOMAIN_IDENTITY_DOCUMENT_DIGEST_V1); + h.update((bytes.len() as u64).to_le_bytes()); + h.update(&bytes); + IdentityDocumentDigest(h.finalize().into()) + } + + /// Bytes a delegate signs to approve this document: the sign tag, then the digest. + pub fn signable_bytes(&self) -> Vec { + let mut buf = DOMAIN_IDENTITY_EDIT_SIGN_V1.to_vec(); + buf.extend_from_slice(&self.digest().0); + buf + } + + /// One delegate's signature approving this document. + pub fn sign(&self, delegate: &SigningKey) -> IdentitySignature { + IdentitySignature { + key: delegate.verifying_key().to_bytes(), + signature: delegate.sign(&self.signable_bytes()).to_bytes(), + } + } + + pub fn is_delegate(&self, key: &Ed25519PublicKey) -> bool { + self.delegates.contains(key) + } + + pub fn is_executor(&self, key: &Ed25519PublicKey) -> bool { + self.executors.contains(key) + } + + /// Check that at least `threshold` distinct delegates of *this* document signed `message` + /// (strict Ed25519). Fails closed: a signer that is not a delegate is refused with + /// `RadicleIdentityInvalid`, a signature that does not verify with + /// `RadicleSignatureInvalid`, and too few distinct delegates with + /// `RadicleQuorumInsufficient`. A delegate signing twice counts once. Returns the distinct + /// signing delegates, ascending. `message` must carry its own domain tag. + pub fn verify_quorum( + &self, + message: &[u8], + signatures: &[IdentitySignature], + ) -> SynapseResult> { + if signatures.len() > MAX_EDIT_SIGNATURES { + return Err(invalid(format!( + "{} signatures exceed the cap of {MAX_EDIT_SIGNATURES}", + signatures.len() + ))); + } + let mut signed = BTreeSet::new(); + for s in signatures { + if !self.is_delegate(&s.key) { + return Err(invalid(format!( + "signer {} is not a delegate of identity revision {}", + hex::encode(s.key), + self.revision + ))); + } + let vk = check_key(&s.key, "delegate")?; + vk.verify_strict(message, &Signature::from_bytes(&s.signature)) + .map_err(|_| { + SynapseError::new( + RefusalCode::RadicleSignatureInvalid, + format!( + "Ed25519 signature of delegate {} does not verify", + hex::encode(s.key) + ), + ) + })?; + signed.insert(s.key); + } + if signed.len() < self.threshold as usize { + return Err(SynapseError::new( + RefusalCode::RadicleQuorumInsufficient, + format!( + "{} of {} required distinct delegate signatures for identity revision {}", + signed.len(), + self.threshold, + self.revision + ), + )); + } + Ok(signed.into_iter().collect()) + } +} + +/// One delegate's Ed25519 signature. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct IdentitySignature { + pub key: Ed25519PublicKey, + pub signature: [u8; 64], +} + +/// A proposed next identity document with the delegate signatures over it. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct IdentityEdit { + pub document: RepositoryIdentityDocument, + pub signatures: Vec, +} + +impl IdentityEdit { + /// Sign `document` with each of `signers` (in the given order). + pub fn sign(document: RepositoryIdentityDocument, signers: &[&SigningKey]) -> Self { + let signatures = signers.iter().map(|k| document.sign(k)).collect(); + Self { + document, + signatures, + } + } + + /// Canonical record bytes: tag, version, length-prefixed document, signature count, then + /// each 32-byte key and 64-byte signature. + pub fn encode(&self) -> Vec { + let doc = self.document.encode(); + let mut buf = Vec::with_capacity( + DOMAIN_IDENTITY_EDIT_V1.len() + 10 + doc.len() + 96 * self.signatures.len(), + ); + buf.extend_from_slice(DOMAIN_IDENTITY_EDIT_V1); + buf.extend_from_slice(&IDENTITY_DOCUMENT_VERSION_V1.to_le_bytes()); + buf.extend_from_slice(&(doc.len() as u32).to_le_bytes()); + buf.extend_from_slice(&doc); + buf.extend_from_slice(&(self.signatures.len() as u32).to_le_bytes()); + for s in &self.signatures { + buf.extend_from_slice(&s.key); + buf.extend_from_slice(&s.signature); + } + buf + } + + /// Decode one edit record. Structural refusals are `RadicleIdentityInvalid`. Signatures + /// are not verified here; [`IdentityLog::apply`] verifies them against the current + /// document. + pub fn decode(bytes: &[u8]) -> SynapseResult { + let mut r = Reader::new(bytes); + r.tag(DOMAIN_IDENTITY_EDIT_V1, "identity edit")?; + let version = r.u16()?; + if version != IDENTITY_DOCUMENT_VERSION_V1 { + return Err(invalid(format!( + "identity edit version {version} is not supported" + ))); + } + let doc_len = r.count(MAX_DOCUMENT_BYTES, 1, "document")?; + let document = RepositoryIdentityDocument::decode(r.take(doc_len)?)?; + let n = r.count(MAX_EDIT_SIGNATURES, 96, "signatures")?; + let mut signatures = Vec::with_capacity(n); + for _ in 0..n { + signatures.push(IdentitySignature { + key: r.array()?, + signature: r.array()?, + }); + } + r.finish()?; + Ok(Self { + document, + signatures, + }) + } +} + +/// One applied identity document and the `WalSeq` from which it is in effect. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct IdentityLogEntry { + pub applied_at: WalSeq, + pub document: RepositoryIdentityDocument, +} + +/// Why a receipt was refused at admission against the identity log. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ReceiptRefusal { + /// The receipt failed its own verification (`EvidenceReceipt::verify`): structure, + /// executor key, or signature. + Receipt(ReceiptError), + /// No identity document was in effect at the `WalSeq`, or the executor key was not + /// registered in it (`RadicleIdentityInvalid`). + Identity(SynapseError), +} + +/// The chain of applied identity documents of one repository, in `WalSeq` order. Entry 0 is +/// genesis; entry `i` has revision `i` and chains to entry `i - 1` by digest. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct IdentityLog { + entries: Vec, +} + +impl IdentityLog { + /// Start a log from a genesis document (revision 0, zero `prev`) signed by at least its own + /// threshold of its own delegates, in effect from `at`. + pub fn genesis(edit: &IdentityEdit, at: WalSeq) -> SynapseResult { + let doc = &edit.document; + doc.validate()?; + if doc.revision != 0 { + return Err(invalid(format!( + "genesis identity document has revision {}", + doc.revision + ))); + } + doc.verify_quorum(&doc.signable_bytes(), &edit.signatures)?; + Ok(Self { + entries: vec![IdentityLogEntry { + applied_at: at, + document: doc.clone(), + }], + }) + } + + /// Apply `edit` from `at` on. Refused unless `at` is after the current document's + /// `WalSeq`, the next document is valid, names the same repository, has the next revision + /// number and the current document's digest as `prev`, and at least the *current* + /// threshold of *current* delegates signed it. A refused edit changes nothing. + pub fn apply(&mut self, edit: &IdentityEdit, at: WalSeq) -> SynapseResult<()> { + let last = self.last(); + let cur = &last.document; + if at <= last.applied_at { + return Err(invalid(format!( + "identity edit at {at} does not follow the current revision's {}", + last.applied_at + ))); + } + let next = &edit.document; + next.validate()?; + if next.repo_id != cur.repo_id { + return Err(invalid(format!( + "identity edit for {} applied to {}", + next.repo_id, cur.repo_id + ))); + } + if Some(next.revision) != cur.revision.checked_add(1) { + return Err(invalid(format!( + "identity edit revision {} does not follow current revision {}", + next.revision, cur.revision + ))); + } + let cur_digest = cur.digest(); + if next.prev != cur_digest { + return Err(invalid(format!( + "identity edit chains to {}, current document is {}", + next.prev.to_hex(), + cur_digest.to_hex() + ))); + } + cur.verify_quorum(&next.signable_bytes(), &edit.signatures)?; + self.entries.push(IdentityLogEntry { + applied_at: at, + document: next.clone(), + }); + Ok(()) + } + + fn last(&self) -> &IdentityLogEntry { + // Every constructor creates the genesis entry and nothing removes entries. + &self.entries[self.entries.len() - 1] + } + + /// The document in effect now (the last applied). + pub fn current(&self) -> &RepositoryIdentityDocument { + &self.last().document + } + + pub fn entries(&self) -> &[IdentityLogEntry] { + &self.entries + } + + /// The document in effect at `at`: the last one applied at or before `at`. `None` before + /// genesis. + pub fn document_at(&self, at: WalSeq) -> Option<&RepositoryIdentityDocument> { + let n = self.entries.partition_point(|e| e.applied_at <= at); + n.checked_sub(1).map(|i| &self.entries[i].document) + } + + /// Whether `key` was a registered executor in the document in effect at `at`. + pub fn executor_registered_at(&self, key: &Ed25519PublicKey, at: WalSeq) -> bool { + self.document_at(at).is_some_and(|d| d.is_executor(key)) + } + + /// The server machine key in the document in effect at `at`. + pub fn server_key_at(&self, at: WalSeq) -> Option { + self.document_at(at).map(|d| d.server_key) + } + + /// Admit `receipt` as accepted at `accepted_at` only if it verifies and its executor key is + /// registered in the document in effect at `accepted_at`. Checking an earlier receipt at + /// its own acceptance `WalSeq` (replay) gives the same answer after any later edit. This + /// checks executor registration only; what a receipt counts toward (input root, policy, + /// independence) is E1. + pub fn admit_executor_receipt( + &self, + receipt: &EvidenceReceipt, + accepted_at: WalSeq, + ) -> Result { + let id = receipt.verify().map_err(ReceiptRefusal::Receipt)?; + let key = + decode_did_key_ed25519(&receipt.executor_did).map_err(ReceiptRefusal::Identity)?; + let doc = self.document_at(accepted_at).ok_or_else(|| { + ReceiptRefusal::Identity(invalid(format!( + "no identity document in effect at {accepted_at}" + ))) + })?; + if !doc.is_executor(&key) { + return Err(ReceiptRefusal::Identity(invalid(format!( + "executor {} is not registered in identity revision {} in effect at {accepted_at}", + receipt.executor_did, doc.revision + )))); + } + Ok(id) + } +} + +/// Bounded little-endian reader. Every read is checked against the remaining bytes. +struct Reader<'a> { + bytes: &'a [u8], + pos: usize, +} + +impl<'a> Reader<'a> { + fn new(bytes: &'a [u8]) -> Self { + Self { bytes, pos: 0 } + } + + fn take(&mut self, n: usize) -> SynapseResult<&'a [u8]> { + let end = self + .pos + .checked_add(n) + .filter(|&e| e <= self.bytes.len()) + .ok_or_else(|| invalid("identity record is truncated"))?; + let s = &self.bytes[self.pos..end]; + self.pos = end; + Ok(s) + } + + fn array(&mut self) -> SynapseResult<[u8; N]> { + let mut a = [0u8; N]; + a.copy_from_slice(self.take(N)?); + Ok(a) + } + + fn u16(&mut self) -> SynapseResult { + Ok(u16::from_le_bytes(self.array()?)) + } + + fn u32(&mut self) -> SynapseResult { + Ok(u32::from_le_bytes(self.array()?)) + } + + fn u64(&mut self) -> SynapseResult { + Ok(u64::from_le_bytes(self.array()?)) + } + + fn tag(&mut self, tag: &[u8], what: &str) -> SynapseResult<()> { + if self.take(tag.len())? != tag { + return Err(invalid(format!("{what} record has the wrong domain tag"))); + } + Ok(()) + } + + /// A u32 count, refused above `cap` or above what the remaining bytes can hold at + /// `item_bytes` each, before the caller allocates for it. + fn count(&mut self, cap: usize, item_bytes: usize, what: &str) -> SynapseResult { + let n = self.u32()? as usize; + if n > cap { + return Err(invalid(format!( + "{what} count {n} exceeds the cap of {cap}" + ))); + } + if n.saturating_mul(item_bytes) > self.bytes.len() - self.pos { + return Err(invalid(format!("{what} count {n} exceeds the record"))); + } + Ok(n) + } + + fn keys(&mut self, cap: usize, what: &str) -> SynapseResult> { + let n = self.count(cap, 32, what)?; + let mut v = Vec::with_capacity(n); + for _ in 0..n { + v.push(self.array()?); + } + Ok(v) + } + + fn finish(&self) -> SynapseResult<()> { + if self.pos != self.bytes.len() { + return Err(invalid("identity record has trailing bytes")); + } + Ok(()) + } +} diff --git a/crates/synapse-radicle/src/lib.rs b/crates/synapse-radicle/src/lib.rs index b2fac49..152645b 100644 --- a/crates/synapse-radicle/src/lib.rs +++ b/crates/synapse-radicle/src/lib.rs @@ -2,6 +2,13 @@ //! Ed25519 delegate threshold verifier, canonical promotion gate, and split-brain //! reconciliation state machine (`synapse-radicle`, Gate 3). +pub mod identity; + +pub use identity::{ + Ed25519PublicKey, IdentityDocumentDigest, IdentityEdit, IdentityLog, IdentityLogEntry, + IdentitySignature, ReceiptRefusal, RepositoryIdentityDocument, +}; + use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey}; use serde::{Deserialize, Serialize}; use std::collections::BTreeMap; diff --git a/crates/synapse-radicle/tests/e0_identity_document.rs b/crates/synapse-radicle/tests/e0_identity_document.rs new file mode 100644 index 0000000..56a8b73 --- /dev/null +++ b/crates/synapse-radicle/tests/e0_identity_document.rs @@ -0,0 +1,469 @@ +//! ADR 0003 step E0: repository identity document (delegates, threshold, registered executor +//! keys, the server's machine key). +//! +//! Acceptance (ADR 0003 section 9, row 6): +//! * an edit signed by fewer than the threshold is refused +//! (`e0_edit_signed_by_fewer_than_threshold_is_refused`); +//! * an edit signed by the threshold applies (`e0_edit_signed_by_threshold_applies`); +//! * a removed executor's later receipts are refused +//! (`e0_removed_executor_later_receipts_are_refused`); +//! * Radicle conformance stays 11 of 11 (synapse-bench conformance child, evidence directory). + +use ed25519_dalek::{Signer, SigningKey}; +use synapse_core::{encode_did_key_ed25519, ChangesetId, GitOid, RefusalCode, RepoId, WalSeq}; +use synapse_crumb::CrumbContextDigest; +use synapse_evidence::{ + CrumbContextBinding, DeclaredOutput, EvidenceReceipt, ExitStatus, InputRoot, Observation, + Outcome, OutputDigest, ReceiptBody, ReceiptResult, SourceRevision, TestIdentity, +}; +use synapse_radicle::identity::{ + DOMAIN_IDENTITY_DOCUMENT_DIGEST_V1, DOMAIN_IDENTITY_EDIT_SIGN_V1, MAX_DELEGATES, +}; +use synapse_radicle::{ + IdentityDocumentDigest, IdentityEdit, IdentityLog, IdentitySignature, ReceiptRefusal, + RepositoryIdentityDocument, +}; + +fn key(seed: u8) -> SigningKey { + SigningKey::from_bytes(&[seed; 32]) +} + +fn pubkey(k: &SigningKey) -> [u8; 32] { + k.verifying_key().to_bytes() +} + +fn sorted(keys: &[&SigningKey]) -> Vec<[u8; 32]> { + let mut v: Vec<[u8; 32]> = keys.iter().map(|k| pubkey(k)).collect(); + v.sort(); + v +} + +fn repo() -> RepoId { + RepoId::new("aien-spark/synapse").unwrap() +} + +struct Fixture { + d1: SigningKey, + d2: SigningKey, + d3: SigningKey, + e1: SigningKey, + e2: SigningKey, + s1: SigningKey, +} + +fn fixture() -> Fixture { + Fixture { + d1: key(0xd1), + d2: key(0xd2), + d3: key(0xd3), + e1: key(0xe1), + e2: key(0xe2), + s1: key(0x51), + } +} + +/// Genesis: 3 delegates, threshold 2, executors e1 and e2, server key s1. +fn genesis_doc(f: &Fixture) -> RepositoryIdentityDocument { + RepositoryIdentityDocument { + repo_id: repo(), + revision: 0, + prev: IdentityDocumentDigest::ZERO, + threshold: 2, + delegates: sorted(&[&f.d1, &f.d2, &f.d3]), + executors: sorted(&[&f.e1, &f.e2]), + server_key: pubkey(&f.s1), + } +} + +fn genesis_log(f: &Fixture) -> IdentityLog { + let edit = IdentityEdit::sign(genesis_doc(f), &[&f.d1, &f.d2]); + IdentityLog::genesis(&edit, WalSeq(1)).expect("genesis signed by the threshold applies") +} + +fn receipt_by(executor: &SigningKey) -> EvidenceReceipt { + let repo = repo(); + let cs = ChangesetId([3; 32]); + let body = ReceiptBody { + repo_id: repo.clone(), + changeset_id: cs, + source: SourceRevision { + base_git_oid: GitOid([1; 20]), + parent_changesets: vec![], + }, + crumb_contexts: vec![CrumbContextBinding { + dir: ".".into(), + at_base: CrumbContextDigest([0xa1; 32]), + in_changeset: CrumbContextDigest([0xa1; 32]), + }], + input_root: InputRoot::single_repo(repo, cs), + test: TestIdentity { + name: "cargo-test-workspace".into(), + command: vec!["cargo".into(), "test".into(), "--workspace".into()], + toolchain: "rustc 1.89.0".into(), + platform: "aarch64-unknown-linux-gnu".into(), + environment: vec![], + }, + result: ReceiptResult { + exit_status: ExitStatus::Code(0), + outcome: Outcome::Pass, + outputs: vec![DeclaredOutput { + name: "verdicts".into(), + digest: OutputDigest::of_bytes(b"all pass"), + }], + }, + observation: Observation { + started_at_ms: 1, + duration_ms: 2, + log: b"ok".to_vec(), + }, + }; + EvidenceReceipt::sign(body, executor).expect("receipt body is valid") +} + +fn identity_code(r: Result) -> RefusalCode { + match r { + Err(ReceiptRefusal::Identity(e)) => e.code, + other => panic!("expected an identity refusal, got {other:?}"), + } +} + +#[test] +fn e0_edit_signed_by_fewer_than_threshold_is_refused() { + let f = fixture(); + let mut log = genesis_log(&f); + let before = log.current().clone(); + + let mut next = before.successor(); + next.executors = sorted(&[&f.e1]); + + // One of three delegates; the threshold is two. + let one = IdentityEdit::sign(next.clone(), &[&f.d1]); + let err = log.apply(&one, WalSeq(10)).unwrap_err(); + assert_eq!(err.code, RefusalCode::RadicleQuorumInsufficient, "{err}"); + + // The same delegate's signature twice still counts once. + let mut twice = one.clone(); + twice.signatures.push(one.signatures[0]); + let err = log.apply(&twice, WalSeq(10)).unwrap_err(); + assert_eq!(err.code, RefusalCode::RadicleQuorumInsufficient, "{err}"); + + // No signature at all. + let none = IdentityEdit::sign(next.clone(), &[]); + let err = log.apply(&none, WalSeq(10)).unwrap_err(); + assert_eq!(err.code, RefusalCode::RadicleQuorumInsufficient, "{err}"); + + // A key that is not a current delegate cannot make up the count, even one the edit + // itself would add as a delegate. + let d4 = key(0xd4); + let mut adds_d4 = next.clone(); + adds_d4.delegates = sorted(&[&f.d1, &f.d2, &f.d3, &d4]); + let self_added = IdentityEdit::sign(adds_d4, &[&f.d1, &d4]); + let err = log.apply(&self_added, WalSeq(10)).unwrap_err(); + assert_eq!(err.code, RefusalCode::RadicleIdentityInvalid, "{err}"); + + // A forged signature from a real delegate is refused, not counted. + let mut forged = IdentityEdit::sign(next, &[&f.d1, &f.d2]); + forged.signatures[1].signature[0] ^= 0x01; + let err = log.apply(&forged, WalSeq(10)).unwrap_err(); + assert_eq!(err.code, RefusalCode::RadicleSignatureInvalid, "{err}"); + + // Nothing changed. + assert_eq!(log.current(), &before); + assert_eq!(log.entries().len(), 1); +} + +#[test] +fn e0_edit_signed_by_threshold_applies() { + let f = fixture(); + let mut log = genesis_log(&f); + let g = log.current().clone(); + + let s2 = key(0x52); + let mut next = g.successor(); + next.executors = sorted(&[&f.e1]); + next.server_key = pubkey(&s2); + next.threshold = 3; + + let edit = IdentityEdit::sign(next.clone(), &[&f.d2, &f.d3]); + log.apply(&edit, WalSeq(10)) + .expect("2 of 3 delegates meet threshold 2"); + + assert_eq!(log.current(), &next); + assert_eq!(log.current().revision, 1); + assert_eq!(log.current().prev, g.digest()); + assert_eq!(log.entries().len(), 2); + assert_eq!(log.entries()[1].applied_at, WalSeq(10)); + + // The document in effect, and the server's machine key, follow the WalSeq. + assert_eq!(log.document_at(WalSeq(0)), None); + assert_eq!(log.document_at(WalSeq(9)), Some(&g)); + assert_eq!(log.document_at(WalSeq(10)), Some(&next)); + assert_eq!(log.server_key_at(WalSeq(9)), Some(pubkey(&f.s1))); + assert_eq!(log.server_key_at(WalSeq(10)), Some(pubkey(&s2))); + + // The next edit needs the new threshold (3): two signatures no longer apply, three do. + let mut third = next.successor(); + third.executors = sorted(&[&f.e1, &f.e2]); + let two = IdentityEdit::sign(third.clone(), &[&f.d1, &f.d2]); + let err = log.apply(&two, WalSeq(20)).unwrap_err(); + assert_eq!(err.code, RefusalCode::RadicleQuorumInsufficient, "{err}"); + let three = IdentityEdit::sign(third.clone(), &[&f.d1, &f.d2, &f.d3]); + log.apply(&three, WalSeq(20)) + .expect("3 of 3 meet threshold 3"); + assert_eq!(log.current(), &third); +} + +#[test] +fn e0_removed_executor_later_receipts_are_refused() { + let f = fixture(); + let mut log = genesis_log(&f); + let r1 = receipt_by(&f.e1); + let r2 = receipt_by(&f.e2); + let e2 = pubkey(&f.e2); + + // Before removal both registered executors' receipts are admitted. + assert!(log.executor_registered_at(&e2, WalSeq(5))); + assert_eq!(log.admit_executor_receipt(&r2, WalSeq(5)), Ok(r2.id())); + + // Remove e2 at WalSeq 10 under the threshold. + let mut next = log.current().successor(); + next.executors = sorted(&[&f.e1]); + log.apply(&IdentityEdit::sign(next, &[&f.d1, &f.d3]), WalSeq(10)) + .unwrap(); + + // e2's receipts from WalSeq 10 on are refused; e1's are still admitted. + assert!(!log.executor_registered_at(&e2, WalSeq(10))); + assert_eq!( + identity_code(log.admit_executor_receipt(&r2, WalSeq(10))), + RefusalCode::RadicleIdentityInvalid + ); + assert_eq!( + identity_code(log.admit_executor_receipt(&r2, WalSeq(11))), + RefusalCode::RadicleIdentityInvalid + ); + assert_eq!(log.admit_executor_receipt(&r1, WalSeq(11)), Ok(r1.id())); + + // Replay: the receipt accepted at WalSeq 5 is judged against the document in effect then, + // so the later removal never revokes it. + assert_eq!(log.admit_executor_receipt(&r2, WalSeq(5)), Ok(r2.id())); + + // A key never registered, a receipt before any identity document, and a forged receipt. + let stranger = receipt_by(&key(0x99)); + assert_eq!( + identity_code(log.admit_executor_receipt(&stranger, WalSeq(5))), + RefusalCode::RadicleIdentityInvalid + ); + assert_eq!( + identity_code(log.admit_executor_receipt(&r1, WalSeq(0))), + RefusalCode::RadicleIdentityInvalid + ); + let mut forged = r1.clone(); + forged.signature[0] ^= 0x01; + assert!(matches!( + log.admit_executor_receipt(&forged, WalSeq(11)), + Err(ReceiptRefusal::Receipt(_)) + )); +} + +#[test] +fn e0_edits_chain_and_cannot_be_replayed_or_reordered() { + let f = fixture(); + let mut log = genesis_log(&f); + let g = log.current().clone(); + + let mut rev1 = g.successor(); + rev1.executors = sorted(&[&f.e1]); + let mut rev2 = rev1.successor(); + rev2.executors = sorted(&[&f.e2]); + let edit1 = IdentityEdit::sign(rev1.clone(), &[&f.d1, &f.d2]); + let edit2 = IdentityEdit::sign(rev2.clone(), &[&f.d1, &f.d2]); + + // Reorder: revision 2 before revision 1. + let err = log.apply(&edit2, WalSeq(10)).unwrap_err(); + assert_eq!(err.code, RefusalCode::RadicleIdentityInvalid, "{err}"); + + log.apply(&edit1, WalSeq(10)).unwrap(); + + // Replay of an applied edit. + let err = log.apply(&edit1, WalSeq(11)).unwrap_err(); + assert_eq!(err.code, RefusalCode::RadicleIdentityInvalid, "{err}"); + + // A WalSeq that does not move forward. + let err = log.apply(&edit2, WalSeq(10)).unwrap_err(); + assert_eq!(err.code, RefusalCode::RadicleIdentityInvalid, "{err}"); + + // Right revision number but the wrong prev digest (a fork of revision 1). + let mut fork = rev2.clone(); + fork.prev = g.digest(); + let err = log + .apply(&IdentityEdit::sign(fork, &[&f.d1, &f.d2]), WalSeq(20)) + .unwrap_err(); + assert_eq!(err.code, RefusalCode::RadicleIdentityInvalid, "{err}"); + + // Another repository's edit. + let mut other = rev2.clone(); + other.repo_id = RepoId::new("aien-spark/other").unwrap(); + let err = log + .apply(&IdentityEdit::sign(other, &[&f.d1, &f.d2]), WalSeq(20)) + .unwrap_err(); + assert_eq!(err.code, RefusalCode::RadicleIdentityInvalid, "{err}"); + + // A signature over the bare digest, without the domain tag, does not count. + let mut undomained = IdentityEdit::sign(rev2.clone(), &[&f.d1]); + undomained.signatures.push(IdentitySignature { + key: pubkey(&f.d2), + signature: f.d2.sign(&rev2.digest().0).to_bytes(), + }); + let err = log.apply(&undomained, WalSeq(20)).unwrap_err(); + assert_eq!(err.code, RefusalCode::RadicleSignatureInvalid, "{err}"); + + log.apply(&edit2, WalSeq(20)).unwrap(); + assert_eq!(log.current(), &rev2); + assert_eq!(log.entries().len(), 3); +} + +#[test] +fn e0_genesis_needs_its_own_threshold_and_a_valid_document() { + let f = fixture(); + let g = genesis_doc(&f); + + let err = + IdentityLog::genesis(&IdentityEdit::sign(g.clone(), &[&f.d1]), WalSeq(1)).unwrap_err(); + assert_eq!(err.code, RefusalCode::RadicleQuorumInsufficient, "{err}"); + + let mut not_genesis = g.clone(); + not_genesis.revision = 1; + let err = IdentityLog::genesis(&IdentityEdit::sign(not_genesis, &[&f.d1, &f.d2]), WalSeq(1)) + .unwrap_err(); + assert_eq!(err.code, RefusalCode::RadicleIdentityInvalid, "{err}"); + + let invalid: Vec<(&str, RepositoryIdentityDocument)> = vec![ + ("threshold 0", { + let mut d = g.clone(); + d.threshold = 0; + d + }), + ("threshold above delegates", { + let mut d = g.clone(); + d.threshold = 4; + d + }), + ("no delegates", { + let mut d = g.clone(); + d.delegates.clear(); + d + }), + ("delegates unsorted", { + let mut d = g.clone(); + d.delegates.reverse(); + d + }), + ("delegate twice", { + let mut d = g.clone(); + d.delegates[1] = d.delegates[0]; + d + }), + ("executors unsorted", { + let mut d = g.clone(); + d.executors.reverse(); + d + }), + ("delegate key not an Ed25519 point", { + let mut d = g.clone(); + // y = 2 has no x on the curve, so this encoding does not decompress. + let mut bad = [0u8; 32]; + bad[0] = 2; + d.delegates = vec![bad]; + d.threshold = 1; + d + }), + ]; + for (label, d) in invalid { + assert_eq!( + d.validate().map_err(|e| e.code), + Err(RefusalCode::RadicleIdentityInvalid), + "{label}" + ); + } + assert_eq!(g.validate(), Ok(())); +} + +#[test] +fn e0_binary_format_round_trips_and_refuses_malformed_bytes() { + let f = fixture(); + let g = genesis_doc(&f); + let edit = IdentityEdit::sign(g.clone(), &[&f.d1, &f.d2]); + + let doc_bytes = g.encode(); + assert!(doc_bytes.starts_with(b"SYNAPSE_IDENTITY_DOCUMENT_V1\0")); + assert_eq!( + RepositoryIdentityDocument::decode(&doc_bytes), + Ok(g.clone()) + ); + let edit_bytes = edit.encode(); + assert!(edit_bytes.starts_with(b"SYNAPSE_IDENTITY_EDIT_V1\0")); + assert_eq!(IdentityEdit::decode(&edit_bytes), Ok(edit.clone())); + + // Digest and signed bytes are domain separated and bound to the encoding. + let mut h = sha2_digest(DOMAIN_IDENTITY_DOCUMENT_DIGEST_V1, &doc_bytes); + assert_eq!(g.digest().0, h); + let mut signable = DOMAIN_IDENTITY_EDIT_SIGN_V1.to_vec(); + signable.extend_from_slice(&h); + assert_eq!(g.signable_bytes(), signable); + h[0] ^= 1; + assert_ne!(g.digest().0, h); + + // Every truncation and a trailing byte are refused. + for n in 0..doc_bytes.len() { + assert!( + RepositoryIdentityDocument::decode(&doc_bytes[..n]).is_err(), + "doc prefix {n}" + ); + } + for n in 0..edit_bytes.len() { + assert!( + IdentityEdit::decode(&edit_bytes[..n]).is_err(), + "edit prefix {n}" + ); + } + let mut trailing = doc_bytes.clone(); + trailing.push(0); + assert!(RepositoryIdentityDocument::decode(&trailing).is_err()); + let mut trailing = edit_bytes.clone(); + trailing.push(0); + assert!(IdentityEdit::decode(&trailing).is_err()); + + // A wrong version is refused. + let tag = b"SYNAPSE_IDENTITY_DOCUMENT_V1\0".len(); + let mut wrong_version = doc_bytes.clone(); + wrong_version[tag] = 2; + assert!(RepositoryIdentityDocument::decode(&wrong_version).is_err()); + + // A delegate count above the cap is refused before anything is allocated for it. + // Layout: tag, u16 version, u32 repo_id length, repo_id, u64 revision, 32 prev, + // u32 threshold, u32 delegate count. + let count_at = tag + 2 + 4 + repo().as_str().len() + 8 + 32 + 4; + let mut huge = doc_bytes.clone(); + huge[count_at..count_at + 4].copy_from_slice(&((MAX_DELEGATES as u32) + 1).to_le_bytes()); + let err = RepositoryIdentityDocument::decode(&huge).unwrap_err(); + assert_eq!(err.code, RefusalCode::RadicleIdentityInvalid, "{err}"); + huge[count_at..count_at + 4].copy_from_slice(&u32::MAX.to_le_bytes()); + assert!(RepositoryIdentityDocument::decode(&huge).is_err()); + + // A decoded document that breaks a rule is refused at decode. + let mut unsorted = g.clone(); + unsorted.delegates.reverse(); + assert!(RepositoryIdentityDocument::decode(&unsorted.encode()).is_err()); + + // The did:key spelling of every key is the Radicle one. + assert!(encode_did_key_ed25519(&g.delegates[0]).starts_with("did:key:z6Mk")); +} + +fn sha2_digest(domain: &[u8], bytes: &[u8]) -> [u8; 32] { + use sha2::{Digest, Sha256}; + let mut h = Sha256::new(); + h.update(domain); + h.update((bytes.len() as u64).to_le_bytes()); + h.update(bytes); + h.finalize().into() +} diff --git a/docs/E0_IDENTITY_DOCUMENT.md b/docs/E0_IDENTITY_DOCUMENT.md new file mode 100644 index 0000000..9320a4c --- /dev/null +++ b/docs/E0_IDENTITY_DOCUMENT.md @@ -0,0 +1,84 @@ +# E0: Repository Identity Document + +ADR 0003 section 9 step E0 (issue aien-spark/synapse#26). Section 5.5 "Trust root": delegates and threshold live in a Synapse identity document that mirrors the Radicle `refs/rad/id` delegates and threshold; changing it, including registering executors and the server's own machine key, needs the current threshold. + +Code: `crates/synapse-radicle/src/identity.rs`. Tests: `crates/synapse-radicle/tests/e0_identity_document.rs`. Evidence: `evidence/e0-identity-document/`. + +## 1. What the document holds + +| Field | Meaning | Consumed by | +| :--- | :--- | :--- | +| `repo_id` | The repository the document governs | every check | +| `revision` | 0 for genesis, each edit adds exactly 1 | chaining | +| `prev` | Digest of the document this one replaces; zero for genesis (and only for genesis) | chaining | +| `threshold` | Distinct delegate signatures an edit of *this* document needs, 1 to the delegate count | E2 (promotion quorum), M2 (erasure quorum) through `verify_quorum` | +| `delegates` | Ed25519 keys allowed to sign edits; strictly ascending, at most 256, at least 1 | same | +| `executors` | Registered executor machine keys; strictly ascending, at most 4096 | E1 (`executor_registered_at`, `admit_executor_receipt`) | +| `server_key` | The server's machine key, which signs derivation attestations | B5 (`server_key_at`) | + +Every key must decode to an Ed25519 point that is not of small order. All refusals use existing `RefusalCode` variants; no new code was added. + +## 2. Rules + +* **Genesis** (`IdentityLog::genesis`): revision 0, zero `prev`, valid, and signed by at least its own threshold of its own delegates. +* **Edit** (`IdentityLog::apply`): the full next document plus delegate signatures. It applies only if the `WalSeq` moves forward, the next document is valid, names the same repository, has revision `current + 1`, has `prev` equal to the current document's digest, and at least the *current* threshold of *current* delegates signed it. A key the edit itself would add cannot sign it into effect. A refused edit changes nothing. +* **Quorum** (`RepositoryIdentityDocument::verify_quorum`): fails closed. A signer that is not a delegate: `RadicleIdentityInvalid`. A signature that does not verify (strict Ed25519): `RadicleSignatureInvalid`. Fewer distinct delegates than the threshold: `RadicleQuorumInsufficient`. A delegate signing twice counts once. +* **Time** (`IdentityLog::document_at`): each revision is in effect from the `WalSeq` it was applied at. The question "was executor X registered when receipt R was accepted" is answered from the document in effect at R's acceptance `WalSeq`, so a later removal refuses only later receipts and never revokes one already accepted (section 5.1, "an attestation added later never revokes a receipt already accepted"). +* **Receipt admission** (`IdentityLog::admit_executor_receipt`): the existing `synapse_evidence::EvidenceReceipt` is verified with its own `verify` (structure, executor `did:key`, strict signature; refusal `ReceiptRefusal::Receipt`), then its executor key must be registered in the document in effect at the acceptance `WalSeq` (refusal `ReceiptRefusal::Identity` with `RadicleIdentityInvalid`). This checks registration only; what a receipt counts toward (input root, policy, independence) is E1. + +## 3. Byte layout (record version 1, principle P5) + +All integers little-endian, all lengths and counts fixed-width and checked against their caps and against the remaining bytes before anything is allocated. Every decode refusal is `RadicleIdentityInvalid`; a truncated record, trailing bytes, a wrong tag, or a wrong version are each refused. + +Document: + +| Field | Bytes | +| :--- | :--- | +| tag `SYNAPSE_IDENTITY_DOCUMENT_V1\0` | 29 | +| version (`1`) | u16 | +| `repo_id` length, then UTF-8 bytes (at most 4096) | u32 + n | +| `revision` | u64 | +| `prev` | 32 | +| `threshold` | u32 | +| delegate count, then each key | u32 + 32 each | +| executor count, then each key | u32 + 32 each | +| `server_key` | 32 | + +Digest: SHA-256 over `SYNAPSE_IDENTITY_DOCUMENT_DIGEST_V1\0`, the record length as u64, and the record. + +Signed bytes (domain separated): `SYNAPSE_IDENTITY_EDIT_SIGN_V1\0` followed by the 32-byte digest. Because the digest covers `repo_id`, `revision`, and `prev`, a signature cannot be replayed onto another repository, another revision, or a fork. + +Edit: + +| Field | Bytes | +| :--- | :--- | +| tag `SYNAPSE_IDENTITY_EDIT_V1\0` | 25 | +| version (`1`) | u16 | +| document length, then the document record | u32 + n | +| signature count (at most 256), then each 32-byte key and 64-byte signature | u32 + 96 each | + +## 4. Acceptance + +| Acceptance (ADR 0003 section 9, row 6) | Test | Result | +| :--- | :--- | :--- | +| An edit signed by fewer than the threshold is refused | `e0_edit_signed_by_fewer_than_threshold_is_refused` (1 of threshold 2; the same delegate twice; no signature; a key the edit would add; a forged delegate signature) | pass | +| An edit signed by the threshold applies | `e0_edit_signed_by_threshold_applies` (2 of 3 applies, raises the threshold to 3, rotates the server key; the next edit then needs 3) | pass | +| A removed executor's later receipts are refused | `e0_removed_executor_later_receipts_are_refused` (real signed `EvidenceReceipt`s; removal at `WalSeq` 10; refused at 10 and 11, still admitted on replay at 5; unregistered key, pre-genesis, forged receipt refused) | pass | +| Radicle conformance stays 11 of 11 | `synapse-bench child --kind conformance` with the live Radicle repository, before (main 91733a3) and after | 11 of 11 both; case results identical | + +Supporting tests: `e0_edits_chain_and_cannot_be_replayed_or_reordered`, `e0_genesis_needs_its_own_threshold_and_a_valid_document`, `e0_binary_format_round_trips_and_refuses_malformed_bytes`. + +Red then green: `evidence/e0-identity-document/red-green/red.txt` (all 6 tests fail on their assertions against a fail-open stub that accepts every edit and receipt and changes nothing) and `green.txt` (all 6 pass). + +Radicle conformance reproduction: write `{"suites":["radicle"],"work_dir":"","radicle_repo":""}` to a spec file and run `synapse-bench child --kind conformance --spec --result `. Raw results: `evidence/e0-identity-document/radicle-conformance/`. + +## 5. Performance + +E0 is not a hot-path step. No figure is reported, so no bound is needed. + +## 6. Limits and disclosures + +* The document is in memory only; persisting edits in the WAL is not part of E0 (the binary record format is fixed here so that a later step can store it unchanged). +* The mirror between this document's delegates and threshold and Radicle `refs/rad/id` is not checked by E0; while the Git edge exists, E2 keeps the existing Radicle check and refuses disagreement as `SplitBrainDivergence`. +* Small-order key refusal and the `verify_quorum` signature-count cap were added beside the tested rules and have no test of their own. +* `synapse-radicle` now depends on `synapse-evidence` (and on `synapse-crumb` for tests only); `Cargo.lock` was regenerated by cargo. diff --git a/evidence/e0-identity-document/SHA256SUMS b/evidence/e0-identity-document/SHA256SUMS new file mode 100644 index 0000000..ccad936 --- /dev/null +++ b/evidence/e0-identity-document/SHA256SUMS @@ -0,0 +1,4 @@ +eb43c33d14d708bd077c3463ee4f1733dc001384908fdbf69f77828338f21845 radicle-conformance/after-e0.json +eb43c33d14d708bd077c3463ee4f1733dc001384908fdbf69f77828338f21845 radicle-conformance/before-91733a3.json +130fb054cff8a949e66b121c69bbba2378e20bb2b5a713d6f4fb3113f1b5a786 red-green/green.txt +1035d6929b3ce9225289c2933f1c45aad0f10f57d35b7e902a6f47a3a3320fa6 red-green/red.txt diff --git a/evidence/e0-identity-document/radicle-conformance/after-e0.json b/evidence/e0-identity-document/radicle-conformance/after-e0.json new file mode 100644 index 0000000..8d542b9 --- /dev/null +++ b/evidence/e0-identity-document/radicle-conformance/after-e0.json @@ -0,0 +1,87 @@ +[ + { + "suite": "radicle", + "cases": [ + { + "suite": "radicle", + "case": "threshold_met_promotes", + "expected": "2 of 3 delegate signatures on X promote X with 2 verified delegates", + "observed": "result Ok((GitOid(91e22fc06774ec0f5c082b2f82c9ac917ae5a703), 2))", + "outcome": "Pass" + }, + { + "suite": "radicle", + "case": "below_threshold_refused", + "expected": "1 of 3 signatures (threshold 2) is refused with RadicleQuorumInsufficient", + "observed": "result Some(RadicleQuorumInsufficient)", + "outcome": "Pass" + }, + { + "suite": "radicle", + "case": "vote_for_other_oid_not_counted", + "expected": "a delegate signature over Y does not count toward X; promotion of X refused with RadicleQuorumInsufficient", + "observed": "result Some(RadicleQuorumInsufficient)", + "outcome": "Pass" + }, + { + "suite": "radicle", + "case": "tampered_refs_blob_refused", + "expected": "a sigrefs blob edited after signing (OID swapped) is refused with RadicleSignatureInvalid", + "observed": "result Some(RadicleSignatureInvalid)", + "outcome": "Pass" + }, + { + "suite": "radicle", + "case": "non_delegate_signer_refused", + "expected": "a valid signature from a key not listed in the identity document is refused with RadicleIdentityInvalid", + "observed": "result Some(RadicleIdentityInvalid)", + "outcome": "Pass" + }, + { + "suite": "radicle", + "case": "forged_delegate_signature_refused", + "expected": "a sigrefs claiming a delegate DID but signed by another key is refused with RadicleSignatureInvalid", + "observed": "result Some(RadicleSignatureInvalid)", + "outcome": "Pass" + }, + { + "suite": "radicle", + "case": "stale_base_refused", + "expected": "after X is canonical, a candidate whose proposal base is not X is refused with StaleBaseHead", + "observed": "result Some(StaleBaseHead); canonical still X true", + "outcome": "Pass" + }, + { + "suite": "radicle", + "case": "github_merged_without_quorum_refused", + "expected": "a GitHub-merged candidate with 1 of 2 required signatures classifies as SplitBrainGithubMergedWithoutRadicleQuorum and promotion is refused with RadicleQuorumInsufficient", + "observed": "state SplitBrainGithubMergedWithoutRadicleQuorum { candidate_oid: GitOid(91e22fc06774ec0f5c082b2f82c9ac917ae5a703), verified_count: 1, required_threshold: 2 }; result Some(RadicleQuorumInsufficient)", + "outcome": "Pass" + }, + { + "suite": "radicle", + "case": "diverged_quorum_refused", + "expected": "when the delegate quorum signs Y, promoting X is refused with SplitBrainDivergence", + "observed": "result Some(SplitBrainDivergence)", + "outcome": "Pass" + }, + { + "suite": "radicle", + "case": "invalid_threshold_identity_refused", + "expected": "an identity document with threshold 4 of 3 delegates is refused with RadicleIdentityInvalid", + "observed": "result Some(RadicleIdentityInvalid)", + "outcome": "Pass" + }, + { + "suite": "radicle", + "case": "live_repository_load_and_classify", + "expected": "read-only: load refs/rad/id and every delegate's sigrefs from the given bare Radicle storage repository, verify signatures, and classify the delegate-signed default-branch head as CanonicalQuorumSatisfied", + "observed": "project \"openclaw-rs\"; delegates 1; threshold 1; sigrefs loaded 1; default branch refs/heads/main head d491aff96f6a875f5de46db8f5f7c7a98d73a4fa signed by 1; state CanonicalQuorumSatisfied", + "outcome": "Pass" + } + ], + "passed": 11, + "failed": 0, + "skipped": 0 + } +] \ No newline at end of file diff --git a/evidence/e0-identity-document/radicle-conformance/before-91733a3.json b/evidence/e0-identity-document/radicle-conformance/before-91733a3.json new file mode 100644 index 0000000..8d542b9 --- /dev/null +++ b/evidence/e0-identity-document/radicle-conformance/before-91733a3.json @@ -0,0 +1,87 @@ +[ + { + "suite": "radicle", + "cases": [ + { + "suite": "radicle", + "case": "threshold_met_promotes", + "expected": "2 of 3 delegate signatures on X promote X with 2 verified delegates", + "observed": "result Ok((GitOid(91e22fc06774ec0f5c082b2f82c9ac917ae5a703), 2))", + "outcome": "Pass" + }, + { + "suite": "radicle", + "case": "below_threshold_refused", + "expected": "1 of 3 signatures (threshold 2) is refused with RadicleQuorumInsufficient", + "observed": "result Some(RadicleQuorumInsufficient)", + "outcome": "Pass" + }, + { + "suite": "radicle", + "case": "vote_for_other_oid_not_counted", + "expected": "a delegate signature over Y does not count toward X; promotion of X refused with RadicleQuorumInsufficient", + "observed": "result Some(RadicleQuorumInsufficient)", + "outcome": "Pass" + }, + { + "suite": "radicle", + "case": "tampered_refs_blob_refused", + "expected": "a sigrefs blob edited after signing (OID swapped) is refused with RadicleSignatureInvalid", + "observed": "result Some(RadicleSignatureInvalid)", + "outcome": "Pass" + }, + { + "suite": "radicle", + "case": "non_delegate_signer_refused", + "expected": "a valid signature from a key not listed in the identity document is refused with RadicleIdentityInvalid", + "observed": "result Some(RadicleIdentityInvalid)", + "outcome": "Pass" + }, + { + "suite": "radicle", + "case": "forged_delegate_signature_refused", + "expected": "a sigrefs claiming a delegate DID but signed by another key is refused with RadicleSignatureInvalid", + "observed": "result Some(RadicleSignatureInvalid)", + "outcome": "Pass" + }, + { + "suite": "radicle", + "case": "stale_base_refused", + "expected": "after X is canonical, a candidate whose proposal base is not X is refused with StaleBaseHead", + "observed": "result Some(StaleBaseHead); canonical still X true", + "outcome": "Pass" + }, + { + "suite": "radicle", + "case": "github_merged_without_quorum_refused", + "expected": "a GitHub-merged candidate with 1 of 2 required signatures classifies as SplitBrainGithubMergedWithoutRadicleQuorum and promotion is refused with RadicleQuorumInsufficient", + "observed": "state SplitBrainGithubMergedWithoutRadicleQuorum { candidate_oid: GitOid(91e22fc06774ec0f5c082b2f82c9ac917ae5a703), verified_count: 1, required_threshold: 2 }; result Some(RadicleQuorumInsufficient)", + "outcome": "Pass" + }, + { + "suite": "radicle", + "case": "diverged_quorum_refused", + "expected": "when the delegate quorum signs Y, promoting X is refused with SplitBrainDivergence", + "observed": "result Some(SplitBrainDivergence)", + "outcome": "Pass" + }, + { + "suite": "radicle", + "case": "invalid_threshold_identity_refused", + "expected": "an identity document with threshold 4 of 3 delegates is refused with RadicleIdentityInvalid", + "observed": "result Some(RadicleIdentityInvalid)", + "outcome": "Pass" + }, + { + "suite": "radicle", + "case": "live_repository_load_and_classify", + "expected": "read-only: load refs/rad/id and every delegate's sigrefs from the given bare Radicle storage repository, verify signatures, and classify the delegate-signed default-branch head as CanonicalQuorumSatisfied", + "observed": "project \"openclaw-rs\"; delegates 1; threshold 1; sigrefs loaded 1; default branch refs/heads/main head d491aff96f6a875f5de46db8f5f7c7a98d73a4fa signed by 1; state CanonicalQuorumSatisfied", + "outcome": "Pass" + } + ], + "passed": 11, + "failed": 0, + "skipped": 0 + } +] \ No newline at end of file diff --git a/evidence/e0-identity-document/red-green/green.txt b/evidence/e0-identity-document/red-green/green.txt new file mode 100644 index 0000000..ae108c9 --- /dev/null +++ b/evidence/e0-identity-document/red-green/green.txt @@ -0,0 +1,15 @@ +# E0 green: same tests after implementing crates/synapse-radicle/src/identity.rs +# command: cargo test --offline -p synapse-radicle --test e0_identity_document + Finished `test` profile [unoptimized + debuginfo] target(s) in 0.02s + Running tests/e0_identity_document.rs (target/debug/deps/e0_identity_document-41dfe8eff02347de) + +running 6 tests +test e0_genesis_needs_its_own_threshold_and_a_valid_document ... ok +test e0_edit_signed_by_fewer_than_threshold_is_refused ... ok +test e0_edit_signed_by_threshold_applies ... ok +test e0_edits_chain_and_cannot_be_replayed_or_reordered ... ok +test e0_removed_executor_later_receipts_are_refused ... ok +test e0_binary_format_round_trips_and_refuses_malformed_bytes ... ok + +test result: ok. 6 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.04s + diff --git a/evidence/e0-identity-document/red-green/red.txt b/evidence/e0-identity-document/red-green/red.txt new file mode 100644 index 0000000..7015f0b --- /dev/null +++ b/evidence/e0-identity-document/red-green/red.txt @@ -0,0 +1,61 @@ +# E0 red: tests run against stub identity module (fail-open, no state change), before implementation +# command: cargo test --offline -p synapse-radicle --test e0_identity_document +# tests committed in 9c23166 (base 91733a3) + Finished `test` profile [unoptimized + debuginfo] target(s) in 0.32s + Running tests/e0_identity_document.rs (target/debug/deps/e0_identity_document-41dfe8eff02347de) + +running 6 tests +test e0_edit_signed_by_threshold_applies ... FAILED +test e0_edits_chain_and_cannot_be_replayed_or_reordered ... FAILED +test e0_binary_format_round_trips_and_refuses_malformed_bytes ... FAILED +test e0_genesis_needs_its_own_threshold_and_a_valid_document ... FAILED +test e0_edit_signed_by_fewer_than_threshold_is_refused ... FAILED +test e0_removed_executor_later_receipts_are_refused ... FAILED + +failures: + +---- e0_edit_signed_by_threshold_applies stdout ---- + +thread 'e0_edit_signed_by_threshold_applies' (1185232) panicked at crates/synapse-radicle/tests/e0_identity_document.rs:191:5: +assertion `left == right` failed + left: RepositoryIdentityDocument { repo_id: RepoId("aien-spark/synapse"), revision: 0, prev: IdentityDocumentDigest([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]), threshold: 2, delegates: [[65, 232, 253, 225, 50, 173, 103, 14, 83, 76, 216, 178, 117, 210, 205, 126, 236, 119, 115, 60, 102, 248, 219, 72, 161, 202, 218, 127, 171, 252, 69, 85], [110, 224, 145, 253, 40, 10, 155, 104, 85, 79, 167, 60, 88, 129, 37, 212, 125, 52, 37, 198, 138, 38, 186, 35, 107, 77, 173, 144, 249, 10, 143, 146], [180, 116, 11, 164, 224, 247, 224, 87, 111, 17, 232, 20, 157, 187, 178, 82, 156, 33, 34, 19, 219, 103, 152, 49, 251, 93, 27, 34, 30, 132, 85, 45]], executors: [[37, 252, 50, 196, 120, 165, 164, 248, 78, 69, 87, 160, 52, 46, 8, 39, 140, 136, 54, 65, 182, 20, 155, 219, 11, 74, 152, 106, 182, 194, 203, 120], [201, 28, 179, 206, 43, 132, 228, 186, 133, 245, 98, 236, 228, 30, 223, 228, 226, 122, 252, 82, 216, 141, 80, 127, 102, 161, 134, 56, 223, 130, 62, 159]], server_key: [192, 80, 197, 99, 122, 68, 250, 134, 41, 255, 243, 204, 204, 226, 48, 12, 179, 98, 166, 61, 153, 217, 95, 197, 65, 69, 38, 111, 67, 50, 68, 90] } + right: RepositoryIdentityDocument { repo_id: RepoId("aien-spark/synapse"), revision: 0, prev: IdentityDocumentDigest([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]), threshold: 3, delegates: [[65, 232, 253, 225, 50, 173, 103, 14, 83, 76, 216, 178, 117, 210, 205, 126, 236, 119, 115, 60, 102, 248, 219, 72, 161, 202, 218, 127, 171, 252, 69, 85], [110, 224, 145, 253, 40, 10, 155, 104, 85, 79, 167, 60, 88, 129, 37, 212, 125, 52, 37, 198, 138, 38, 186, 35, 107, 77, 173, 144, 249, 10, 143, 146], [180, 116, 11, 164, 224, 247, 224, 87, 111, 17, 232, 20, 157, 187, 178, 82, 156, 33, 34, 19, 219, 103, 152, 49, 251, 93, 27, 34, 30, 132, 85, 45]], executors: [[37, 252, 50, 196, 120, 165, 164, 248, 78, 69, 87, 160, 52, 46, 8, 39, 140, 136, 54, 65, 182, 20, 155, 219, 11, 74, 152, 106, 182, 194, 203, 120]], server_key: [32, 18, 203, 144, 202, 96, 232, 229, 216, 218, 246, 110, 34, 114, 210, 35, 62, 4, 134, 213, 87, 232, 198, 97, 65, 237, 137, 32, 23, 125, 126, 183] } +note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace + +---- e0_edits_chain_and_cannot_be_replayed_or_reordered stdout ---- + +thread 'e0_edits_chain_and_cannot_be_replayed_or_reordered' (1185233) panicked at crates/synapse-radicle/tests/e0_identity_document.rs:282:45: +called `Result::unwrap_err()` on an `Ok` value: () + +---- e0_binary_format_round_trips_and_refuses_malformed_bytes stdout ---- + +thread 'e0_binary_format_round_trips_and_refuses_malformed_bytes' (1185230) panicked at crates/synapse-radicle/tests/e0_identity_document.rs:398:5: +assertion failed: doc_bytes.starts_with(b"SYNAPSE_IDENTITY_DOCUMENT_V1\0") + +---- e0_genesis_needs_its_own_threshold_and_a_valid_document stdout ---- + +thread 'e0_genesis_needs_its_own_threshold_and_a_valid_document' (1185234) panicked at crates/synapse-radicle/tests/e0_identity_document.rs:331:83: +called `Result::unwrap_err()` on an `Ok` value: IdentityLog { entries: [IdentityLogEntry { applied_at: WalSeq(1), document: RepositoryIdentityDocument { repo_id: RepoId("aien-spark/synapse"), revision: 0, prev: IdentityDocumentDigest([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]), threshold: 2, delegates: [[65, 232, 253, 225, 50, 173, 103, 14, 83, 76, 216, 178, 117, 210, 205, 126, 236, 119, 115, 60, 102, 248, 219, 72, 161, 202, 218, 127, 171, 252, 69, 85], [110, 224, 145, 253, 40, 10, 155, 104, 85, 79, 167, 60, 88, 129, 37, 212, 125, 52, 37, 198, 138, 38, 186, 35, 107, 77, 173, 144, 249, 10, 143, 146], [180, 116, 11, 164, 224, 247, 224, 87, 111, 17, 232, 20, 157, 187, 178, 82, 156, 33, 34, 19, 219, 103, 152, 49, 251, 93, 27, 34, 30, 132, 85, 45]], executors: [[37, 252, 50, 196, 120, 165, 164, 248, 78, 69, 87, 160, 52, 46, 8, 39, 140, 136, 54, 65, 182, 20, 155, 219, 11, 74, 152, 106, 182, 194, 203, 120], [201, 28, 179, 206, 43, 132, 228, 186, 133, 245, 98, 236, 228, 30, 223, 228, 226, 122, 252, 82, 216, 141, 80, 127, 102, 161, 134, 56, 223, 130, 62, 159]], server_key: [192, 80, 197, 99, 122, 68, 250, 134, 41, 255, 243, 204, 204, 226, 48, 12, 179, 98, 166, 61, 153, 217, 95, 197, 65, 69, 38, 111, 67, 50, 68, 90] } }] } + +---- e0_edit_signed_by_fewer_than_threshold_is_refused stdout ---- + +thread 'e0_edit_signed_by_fewer_than_threshold_is_refused' (1185231) panicked at crates/synapse-radicle/tests/e0_identity_document.rs:141:43: +called `Result::unwrap_err()` on an `Ok` value: () + +---- e0_removed_executor_later_receipts_are_refused stdout ---- + +thread 'e0_removed_executor_later_receipts_are_refused' (1185235) panicked at crates/synapse-radicle/tests/e0_identity_document.rs:235:5: +assertion failed: !log.executor_registered_at(&e2, WalSeq(10)) + + +failures: + e0_binary_format_round_trips_and_refuses_malformed_bytes + e0_edit_signed_by_fewer_than_threshold_is_refused + e0_edit_signed_by_threshold_applies + e0_edits_chain_and_cannot_be_replayed_or_reordered + e0_genesis_needs_its_own_threshold_and_a_valid_document + e0_removed_executor_later_receipts_are_refused + +test result: FAILED. 0 passed; 6 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s + +error: test failed, to rerun pass `-p synapse-radicle --test e0_identity_document` ```