diff --git a/pkgs/id/src/world/mod.rs b/pkgs/id/src/world/mod.rs index ad8229b9f8..4b6b6a4f99 100644 --- a/pkgs/id/src/world/mod.rs +++ b/pkgs/id/src/world/mod.rs @@ -35,6 +35,7 @@ mod clock; mod core; mod handle; mod metrics; +mod replication; pub mod signed; mod util; @@ -46,6 +47,13 @@ pub use clock::{Clock, ManualClock, SystemClock}; pub use core::WorldCore; pub use handle::WorldHandle; pub use metrics::{HistogramSnapshot, MetricsSnapshot, WorldMetrics}; +pub use replication::{ + AcceptedFrame, MAX_REPLICATION_FRAME_BYTES, MAX_REPLICATION_PAYLOAD_BYTES, REPLICATION_DOMAIN, + REPLICATION_ENVELOPE_VERSION, REPLICATION_FRAME_MAGIC, ReplicationCursor, ReplicationEnvelope, + ReplicationError, ReplicationKind, ReplicationTracker, SESSION_NONCE_BYTES, + SignedReplicationEnvelope, advance_cursor, chain_base_cursor, chain_payload, frame_digest, + journal_entry_line, payload_digest, split_entry_payload, +}; pub use util::{EventPage, hex_encode, publish_records}; pub(crate) use util::{ constant_time_eq, hex_decode_32, legacy_sanitize_display_name, sanitize_chat, diff --git a/pkgs/id/src/world/replication.rs b/pkgs/id/src/world/replication.rs new file mode 100644 index 0000000000..2a1ee7ba0f --- /dev/null +++ b/pkgs/id/src/world/replication.rs @@ -0,0 +1,1214 @@ +//! F12.13 journal replication: wire contract and crypto primitives (#806). +//! +//! Phase 1 of the phased plan in `doc/2026-11-01_design_id806.md` (design +//! record on #806, merged in PR #3822). This module defines only the +//! contract every later phase builds on — the signed replication envelope, +//! the cursor/hash-chain rules, bounded payload behavior, and the +//! receiver-side verification state machine. It contains no network +//! serving, no journal I/O, and no replica storage: the writer feed +//! (phase 2), the durable receiver (phase 3), and spectator serving +//! (phases 4–5) consume these types. +//! +//! ## F12.6 seam disposition +//! +//! Design §4.6/§7 gate phase 1 on #1063 slice 1 (task 4885) settling the +//! shared F12.6 framing seam, with an explicit fallback: "If #1063 does not +//! define reusable wire framing, record that explicitly and have F12.13 own +//! its versioned envelope." As of 2026-11-02, #1063 slice 1 (PR #4017) is an +//! audit-log feature — it records audit facts at call sites and defines no +//! reusable wire-framing contract — so the fallback applies and this module +//! is the explicitly versioned, F12.13-owned envelope the design calls for. +//! The envelope is carried as the payload of the existing length-prefixed +//! transport framing ([`crate::frames`]); if F12.6 later defines a reusable +//! outer framing, only that carriage changes, not the envelope, the cursor +//! rules, or the signature contract below. +//! +//! ## Contract summary +//! +//! - One writer. A frame is a [`SignedReplicationEnvelope`]: an +//! [`ReplicationEnvelope`] plus an Ed25519 signature over the +//! domain-separated canonical encoding of every envelope field and the +//! exact payload bytes. Verification uses `verify_strict` and requires +//! the signer to be the frame's claimed `source`, which the receiver +//! must additionally pin out of band ([`ReplicationTracker`] is built +//! with the pinned source). A key supplied only by the stream is never +//! trusted on its own. +//! - The cursor is `(entry ordinal, rolling digest)` over the exact +//! journal-entry bytes (the JSONL lines the journal stores, newline +//! included). The chain base is seeded with the replication domain, the +//! world ID, the source node ID, and the journal header version, so a +//! compaction or header bump changes the base and forces a reset +//! snapshot. The cursor can be recomputed from the current journal file +//! after a restart with [`chain_base_cursor`] and [`advance_cursor`]. +//! - Every signature binds a fresh per-session nonce, so captured frames +//! cannot be replayed into another sync session. Within a session, +//! frames also chain by digest: each frame names the digest of the +//! previous frame's exact encoded bytes. +//! - Payloads carry exact serialized journal-entry bytes, never a lossy +//! projection. A frame payload is bounded by +//! [`MAX_REPLICATION_PAYLOAD_BYTES`]; larger batches are split at entry +//! boundaries with [`split_entry_payload`]. A signed +//! [`ReplicationKind::Terminal`] frame commits the completed +//! snapshot/batch cursor; a batch without its terminal frame is not +//! complete and must not replace replica state. + +use ed25519_dalek::{Signature, Signer, SigningKey, VerifyingKey}; +use serde::{Deserialize, Serialize}; + +use super::{JournalEntry, MAX_JOURNAL_VERSION}; + +/// Domain separator bound into every signature and hash-chain step, so a +/// replication signature or digest can never be reinterpreted by another +/// protocol in this crate (design §4.3: replication-specific domain tag). +pub const REPLICATION_DOMAIN: &[u8] = b"developing-today/id/world-replication/v1\0"; + +/// Frame marker prefixing the postcard-encoded signed envelope, separating +/// replication frames from any other payload on a shared transport. +pub const REPLICATION_FRAME_MAGIC: &[u8] = b"id-world-replication/v1\n"; + +/// Version of the envelope defined by this module. A receiver refuses any +/// other version; a future incompatible contract bumps this (and the +/// domain/magic version tags with it). +pub const REPLICATION_ENVELOPE_VERSION: u8 = 1; + +/// Largest payload one replication frame may carry, in bytes. Bounded well +/// below the transport frame bound ([`crate::frames::MAX_FRAME_BYTES`]) so +/// a signed envelope plus its encoding overhead always fits one transport +/// frame; larger batches are split at entry boundaries +/// ([`split_entry_payload`]). +pub const MAX_REPLICATION_PAYLOAD_BYTES: usize = 256 * 1024; + +/// Largest accepted encoded replication frame, in bytes. Matches the +/// transport framing bound ([`crate::frames::MAX_FRAME_BYTES`]). +pub const MAX_REPLICATION_FRAME_BYTES: usize = 1024 * 1024; + +/// Length of the per-session nonce every signature binds, in bytes. +pub const SESSION_NONCE_BYTES: usize = 16; + +/// A position in a world's replicated journal: how many entries the chain +/// has absorbed, and the rolling digest over their exact bytes. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct ReplicationCursor { + /// Number of journal entries absorbed into the chain so far. + pub ordinal: u64, + /// Rolling BLAKE3 digest over the absorbed entry bytes, seeded by + /// [`chain_base_cursor`]. + pub digest: [u8; 32], +} + +/// The chain base for one world's journal under one source and header +/// version: ordinal 0 and a digest seeded with the replication domain, +/// world ID, source node ID, and header version. Compaction or a header +/// bump changes the inputs, so a replica whose cursor is not in the new +/// chain is detected immediately and must take a reset snapshot. +#[must_use] +pub fn chain_base_cursor( + world_id: &str, + source: &[u8; 32], + header_version: u32, +) -> ReplicationCursor { + let seed = postcard::to_allocvec(&(REPLICATION_DOMAIN, world_id, source, header_version)) + .unwrap_or_default(); + ReplicationCursor { + ordinal: 0, + digest: *blake3::hash(&seed).as_bytes(), + } +} + +/// Advance the chain by one journal entry's exact bytes (the stored JSONL +/// line, newline included). Domain-separated and length-prefixed, so two +/// different entry splits of the same byte stream chain differently. +#[must_use] +pub fn advance_cursor(cursor: ReplicationCursor, entry_bytes: &[u8]) -> ReplicationCursor { + let mut hasher = blake3::Hasher::new(); + hasher.update(REPLICATION_DOMAIN); + hasher.update(&cursor.digest); + hasher.update(&u64::try_from(entry_bytes.len()).unwrap_or(u64::MAX).to_le_bytes()); + hasher.update(entry_bytes); + ReplicationCursor { + ordinal: cursor.ordinal + 1, + digest: *hasher.finalize().as_bytes(), + } +} + +/// The exact replicated bytes of one journal entry: its JSON encoding plus +/// the newline the journal file stores, matching `world_store`'s on-disk +/// line format. +#[must_use] +pub fn journal_entry_line(entry: &JournalEntry) -> Vec { + let mut line = serde_json::to_vec(entry).unwrap_or_default(); + line.push(b'\n'); + line +} + +/// Digest of a frame's exact encoded bytes (magic included), as named by +/// the next frame's `prev_frame_digest`. +#[must_use] +pub fn frame_digest(frame_bytes: &[u8]) -> [u8; 32] { + let mut hasher = blake3::Hasher::new(); + hasher.update(REPLICATION_DOMAIN); + hasher.update(frame_bytes); + *hasher.finalize().as_bytes() +} + +/// Split a concatenated journal-entry payload into chunks of at most +/// [`MAX_REPLICATION_PAYLOAD_BYTES`], breaking only at entry (newline) +/// boundaries so every chunk is itself a valid frame payload. +/// +/// # Errors +/// +/// [`ReplicationError::MalformedPayload`] if a non-empty payload does not +/// end at an entry boundary, or +/// [`ReplicationError::PayloadTooLarge`] if one entry alone exceeds the +/// per-frame bound (such an entry can never be replicated in v1). +pub fn split_entry_payload(payload: &[u8]) -> Result>, ReplicationError> { + if payload.is_empty() { + return Ok(Vec::new()); + } + if !payload.ends_with(b"\n") { + return Err(ReplicationError::MalformedPayload); + } + let mut chunks = Vec::new(); + let mut start = 0; + let mut chunk_end = 0; + for (idx, byte) in payload.iter().enumerate() { + if *byte != b'\n' { + continue; + } + let entry_end = idx + 1; + if entry_end - start > MAX_REPLICATION_PAYLOAD_BYTES { + return Err(ReplicationError::PayloadTooLarge); + } + if entry_end - chunk_end > MAX_REPLICATION_PAYLOAD_BYTES { + chunks.push(payload[chunk_end..start].to_vec()); + chunk_end = start; + } + start = entry_end; + } + if chunk_end < payload.len() { + chunks.push(payload[chunk_end..].to_vec()); + } + Ok(chunks) +} + +/// What a replication frame carries (design §4.1/§4.4). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub enum ReplicationKind { + /// A complete signed reset snapshot: the full journal from the chain + /// base, sent on first sync, after compaction, and after a header + /// bump. Replaces the receiver's chain wholesale. + Snapshot, + /// An ordered batch of journal entries continuing the current chain. + Tail, + /// Commits the snapshot/batch whose cursor the receiver has already + /// reached. Carries no payload; a batch without its terminal frame is + /// incomplete and must not replace replica state. + Terminal, +} + +/// The unsigned replication envelope. Every field is bound by the +/// signature in [`SignedReplicationEnvelope`]. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct ReplicationEnvelope { + /// Envelope contract version; must equal + /// [`REPLICATION_ENVELOPE_VERSION`]. + pub version: u8, + /// World the journal belongs to. + pub world_id: String, + /// Ed25519 public key bytes of the single writer; the only key whose + /// signature a receiver may accept, and only when it matches the + /// receiver's pinned source. + pub source: [u8; 32], + /// Journal header version the payload's entries belong to. A receiver + /// refuses a version newer than it supports before applying any entry + /// (the F11.12 header-boundary rule). + pub header_version: u32, + /// What this frame carries. + pub kind: ReplicationKind, + /// Fresh random nonce of the sync session; bound by the signature so + /// captured frames cannot be replayed into another session. + pub session_nonce: [u8; SESSION_NONCE_BYTES], + /// Chain position before this frame's payload. + pub cursor_before: ReplicationCursor, + /// Chain position after this frame's payload. For + /// [`ReplicationKind::Terminal`], equal to `cursor_before`: the + /// terminal frame commits the cursor the batch already reached. + pub cursor_after: ReplicationCursor, + /// [`frame_digest`] of the previous frame in this session, or all + /// zeroes for the first frame. + pub prev_frame_digest: [u8; 32], + /// BLAKE3 digest of `payload`, domain-separated. + pub payload_digest: [u8; 32], + /// Exact journal-entry bytes (JSONL lines), or empty for + /// [`ReplicationKind::Terminal`]. + pub payload: Vec, +} + +impl ReplicationEnvelope { + /// Number of journal entries this frame's payload carries, derived + /// from the cursors so it cannot disagree with them. + #[must_use] + pub fn entry_count(&self) -> u64 { + self.cursor_after.ordinal.saturating_sub(self.cursor_before.ordinal) + } + + /// Build a tail frame continuing `cursor_before`, computing the + /// after-cursor and payload digest from the exact entry bytes. + /// + /// # Errors + /// + /// Returns the chain errors of [`chain_payload`]: + /// [`ReplicationError::PayloadTooLarge`] or + /// [`ReplicationError::MalformedPayload`]. + pub fn tail( + world_id: &str, + source: [u8; 32], + header_version: u32, + session_nonce: [u8; SESSION_NONCE_BYTES], + cursor_before: ReplicationCursor, + prev_frame_digest: [u8; 32], + payload: Vec, + ) -> Result { + let cursor_after = chain_payload(cursor_before, &payload)?; + Ok(Self { + version: REPLICATION_ENVELOPE_VERSION, + world_id: world_id.to_string(), + source, + header_version, + kind: ReplicationKind::Tail, + session_nonce, + cursor_before, + cursor_after, + prev_frame_digest, + payload_digest: payload_digest(&payload), + payload, + }) + } + + /// Build a snapshot frame: a complete journal from the chain base for + /// `header_version`, computing the after-cursor and payload digest. + /// + /// # Errors + /// + /// Returns the chain errors of [`chain_payload`]: + /// [`ReplicationError::PayloadTooLarge`] or + /// [`ReplicationError::MalformedPayload`]. + pub fn snapshot( + world_id: &str, + source: [u8; 32], + header_version: u32, + session_nonce: [u8; SESSION_NONCE_BYTES], + prev_frame_digest: [u8; 32], + payload: Vec, + ) -> Result { + let cursor_before = chain_base_cursor(world_id, &source, header_version); + let cursor_after = chain_payload(cursor_before, &payload)?; + Ok(Self { + version: REPLICATION_ENVELOPE_VERSION, + world_id: world_id.to_string(), + source, + header_version, + kind: ReplicationKind::Snapshot, + session_nonce, + cursor_before, + cursor_after, + prev_frame_digest, + payload_digest: payload_digest(&payload), + payload, + }) + } + + /// Build the terminal frame committing `cursor` — the position the + /// preceding snapshot/tail frames of this batch already reached. + #[must_use] + pub fn terminal( + world_id: &str, + source: [u8; 32], + header_version: u32, + session_nonce: [u8; SESSION_NONCE_BYTES], + cursor: ReplicationCursor, + prev_frame_digest: [u8; 32], + ) -> Self { + Self { + version: REPLICATION_ENVELOPE_VERSION, + world_id: world_id.to_string(), + source, + header_version, + kind: ReplicationKind::Terminal, + session_nonce, + cursor_before: cursor, + cursor_after: cursor, + prev_frame_digest, + payload_digest: payload_digest(&[]), + payload: Vec::new(), + } + } +} + +/// Domain-separated BLAKE3 digest of a frame payload. +#[must_use] +pub fn payload_digest(payload: &[u8]) -> [u8; 32] { + let mut hasher = blake3::Hasher::new(); + hasher.update(REPLICATION_DOMAIN); + hasher.update(payload); + *hasher.finalize().as_bytes() +} + +/// Chain a whole payload (zero or more complete entry lines) from +/// `cursor`, refusing anything that is not a sequence of complete entries +/// within the per-frame payload bound. +/// +/// # Errors +/// +/// [`ReplicationError::PayloadTooLarge`] if the payload exceeds +/// [`MAX_REPLICATION_PAYLOAD_BYTES`]; +/// [`ReplicationError::MalformedPayload`] if it does not end at an entry +/// boundary. +pub fn chain_payload( + mut cursor: ReplicationCursor, + payload: &[u8], +) -> Result { + if payload.len() > MAX_REPLICATION_PAYLOAD_BYTES { + return Err(ReplicationError::PayloadTooLarge); + } + if payload.is_empty() { + return Ok(cursor); + } + if !payload.ends_with(b"\n") { + return Err(ReplicationError::MalformedPayload); + } + for entry in payload.split_inclusive(|byte| *byte == b'\n') { + // A line that does not decode as a journal entry is not an entry, + // however the chain arithmetic treats its bytes: refuse it here so + // a verified cursor never covers data the restore path cannot read. + serde_json::from_slice::(entry) + .map_err(|_| ReplicationError::MalformedPayload)?; + cursor = advance_cursor(cursor, entry); + } + Ok(cursor) +} + +/// A replication envelope plus its Ed25519 signature — the frame a +/// replication stream actually carries (as the payload of the transport +/// framing, see [`crate::frames`]). +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct SignedReplicationEnvelope { + /// The envelope; every field is signed. + pub envelope: ReplicationEnvelope, + /// Ed25519 signature over [`Self::signing_bytes`], by the key whose + /// public half is `envelope.source`. + pub signature: Vec, +} + +impl SignedReplicationEnvelope { + /// Sign an envelope, refusing to sign for a key that is not the + /// envelope's claimed source, and refusing an over-bound payload. + pub fn sign(envelope: ReplicationEnvelope, key: &SigningKey) -> Option { + if envelope.source != *key.verifying_key().as_bytes() + || envelope.payload.len() > MAX_REPLICATION_PAYLOAD_BYTES + { + return None; + } + let mut signed = Self { + envelope, + signature: Vec::new(), + }; + signed.signature = key.sign(&signed.signing_bytes().ok()?).to_bytes().to_vec(); + Some(signed) + } + + /// Encode this frame: the replication magic, then the postcard + /// encoding of the signed envelope. + pub fn encode_frame(&self) -> Result, postcard::Error> { + let payload = postcard::to_allocvec(self)?; + let mut frame = Vec::with_capacity(REPLICATION_FRAME_MAGIC.len() + payload.len()); + frame.extend_from_slice(REPLICATION_FRAME_MAGIC); + frame.extend_from_slice(&payload); + Ok(frame) + } + + /// Decode a frame's bytes. This checks only shape (magic, size bound, + /// decodability); authentication and chain validation are + /// [`ReplicationTracker::accept`]'s job — never apply a payload from a + /// frame that has not passed it. + pub fn decode_frame(frame: &[u8]) -> Option { + if frame.len() > MAX_REPLICATION_FRAME_BYTES { + return None; + } + let payload = frame.strip_prefix(REPLICATION_FRAME_MAGIC)?; + // `take_from_bytes`, not `from_bytes`: trailing bytes after the + // envelope must refuse the frame, not be silently ignored — the + // frame digest covers the whole received buffer, so an unsigned + // suffix would otherwise desynchronize the frame chain. + let (signed, rest) = postcard::take_from_bytes::(payload).ok()?; + if !rest.is_empty() { + return None; + } + Some(signed) + } + + /// Verify the signature against the envelope's claimed source key, + /// with `verify_strict`. Does not check that the source is the + /// receiver's pinned source — [`ReplicationTracker::accept`] does. + /// + /// # Errors + /// + /// [`ReplicationError::BadSignature`] if the signature is malformed or + /// does not verify. + pub fn verify_signature(&self) -> Result<(), ReplicationError> { + let verifying_key = VerifyingKey::from_bytes(&self.envelope.source) + .map_err(|_| ReplicationError::BadSignature)?; + let signature = + Signature::from_slice(&self.signature).map_err(|_| ReplicationError::BadSignature)?; + verifying_key + .verify_strict(&self.signing_bytes().map_err(|_| ReplicationError::BadSignature)?, &signature) + .map_err(|_| ReplicationError::BadSignature) + } + + /// Domain-separated canonical encoding of every envelope field and the + /// exact payload bytes: what the signature binds. + fn signing_bytes(&self) -> Result, postcard::Error> { + postcard::to_allocvec(&( + REPLICATION_DOMAIN, + self.envelope.version, + &self.envelope.world_id, + &self.envelope.source, + self.envelope.header_version, + self.envelope.kind, + &self.envelope.session_nonce, + self.envelope.cursor_before, + self.envelope.cursor_after, + &self.envelope.prev_frame_digest, + &self.envelope.payload_digest, + &self.envelope.payload, + )) + } +} + +/// Why a replication frame was refused. Every refusal leaves the +/// receiver's verified state untouched (design §5.3/§5.4). +#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)] +pub enum ReplicationError { + /// The frame bytes do not decode as a replication frame at all. + #[error("malformed replication frame")] + MalformedFrame, + /// The frame's envelope version is not the one this module defines. + #[error("unsupported replication envelope version {0}")] + UnsupportedEnvelopeVersion(u8), + /// The frame's journal header version is newer than this binary reads; + /// refused at the header boundary, before any entry is applied. + #[error("unsupported journal header version {0}")] + UnsupportedJournalVersion(u32), + /// A tail/terminal frame's header version differs from the chain's. + #[error("journal header version changed without a reset snapshot")] + HeaderVersionChanged, + /// The frame names a different world than the receiver replicates. + #[error("replication frame is for a different world")] + WorldMismatch, + /// The frame's source is not the receiver's pinned source. + #[error("replication frame source is not the pinned source")] + UntrustedSource, + /// The signature does not verify against the frame's source key. + #[error("replication frame signature does not verify")] + BadSignature, + /// The frame belongs to a different sync session (nonce mismatch): + /// a replay of captured frames into a new session. + #[error("replication frame belongs to a different session")] + NonceMismatch, + /// The frame does not name the previous frame's digest: a gap or a + /// reordered/forked frame stream. + #[error("replication frame does not continue the frame chain")] + FrameChainMismatch, + /// The frame starts after the receiver's cursor: entries are missing. + #[error("replication frame starts after the verified cursor (gap)")] + CursorGap, + /// The frame starts before the receiver's cursor: a replay of + /// already-applied entries. + #[error("replication frame starts before the verified cursor (replay)")] + StaleCursor, + /// The frame starts at the receiver's ordinal but on a different + /// digest chain: a fork. + #[error("replication frame continues a different chain (fork)")] + CursorFork, + /// The payload does not chain to the frame's claimed after-cursor. + #[error("replication payload does not chain to the claimed cursor")] + EntryChainMismatch, + /// The payload's digest differs from the signed payload digest. + #[error("replication payload digest mismatch")] + PayloadDigestMismatch, + /// The payload exceeds the per-frame bound. + #[error("replication payload exceeds the per-frame bound")] + PayloadTooLarge, + /// The payload is not a sequence of complete entry lines, or a line + /// does not decode as a journal entry. + #[error("replication payload is not complete journal entries")] + MalformedPayload, + /// A terminal frame names a cursor the batch has not reached — the + /// batch is truncated or the terminal belongs to another batch. + #[error("terminal frame does not match the reached cursor")] + TerminalCursorMismatch, +} + +/// A frame that passed [`ReplicationTracker::accept`]: its payload (the +/// exact entry bytes) may now be applied, in accept order. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct AcceptedFrame { + /// What the frame carried. + pub kind: ReplicationKind, + /// The verified chain position after this frame. + pub cursor_after: ReplicationCursor, + /// Exact journal-entry bytes to append (empty for a terminal frame). + pub payload: Vec, +} + +/// Receiver-side verification state for one sync session with one pinned +/// source (design §4.5): checks the signature, trusted signer, domain, +/// world, session nonce, frame chain, cursor continuity, previous digest, +/// entry decoding, and header version before any batch is made visible. +/// State advances only on a fully verified frame, so a refused frame +/// leaves the last complete replica state intact. +#[derive(Clone, Debug)] +pub struct ReplicationTracker { + world_id: String, + pinned_source: [u8; 32], + session_nonce: [u8; SESSION_NONCE_BYTES], + header_version: u32, + cursor: ReplicationCursor, + last_frame_digest: [u8; 32], +} + +impl ReplicationTracker { + /// Start a session: the chain sits at the base for `header_version` + /// and no frame has been accepted yet. + #[must_use] + pub fn new( + world_id: &str, + pinned_source: [u8; 32], + header_version: u32, + session_nonce: [u8; SESSION_NONCE_BYTES], + ) -> Self { + Self { + world_id: world_id.to_string(), + pinned_source, + session_nonce, + header_version, + cursor: chain_base_cursor(world_id, &pinned_source, header_version), + last_frame_digest: [0; 32], + } + } + + /// The current verified chain position. + #[must_use] + pub fn cursor(&self) -> ReplicationCursor { + self.cursor + } + + /// The journal header version of the current chain. + #[must_use] + pub fn header_version(&self) -> u32 { + self.header_version + } + + /// Verify one encoded frame and, if it passes every check, advance + /// the session state and return the payload to apply. + /// + /// # Errors + /// + /// The [`ReplicationError`] naming the first failed check; the + /// tracker's state is unchanged on any error. + pub fn accept(&mut self, frame_bytes: &[u8]) -> Result { + let signed = SignedReplicationEnvelope::decode_frame(frame_bytes) + .ok_or(ReplicationError::MalformedFrame)?; + let envelope = &signed.envelope; + if envelope.version != REPLICATION_ENVELOPE_VERSION { + return Err(ReplicationError::UnsupportedEnvelopeVersion(envelope.version)); + } + if envelope.header_version > MAX_JOURNAL_VERSION { + return Err(ReplicationError::UnsupportedJournalVersion( + envelope.header_version, + )); + } + if envelope.world_id != self.world_id { + return Err(ReplicationError::WorldMismatch); + } + if envelope.source != self.pinned_source { + return Err(ReplicationError::UntrustedSource); + } + signed.verify_signature()?; + if envelope.session_nonce != self.session_nonce { + return Err(ReplicationError::NonceMismatch); + } + if envelope.prev_frame_digest != self.last_frame_digest { + return Err(ReplicationError::FrameChainMismatch); + } + if envelope.payload.len() > MAX_REPLICATION_PAYLOAD_BYTES { + return Err(ReplicationError::PayloadTooLarge); + } + if envelope.payload_digest != payload_digest(&envelope.payload) { + return Err(ReplicationError::PayloadDigestMismatch); + } + match envelope.kind { + ReplicationKind::Snapshot => { + // A snapshot rebases the chain: its before-cursor must be + // the base for its own header version, whatever the + // current chain is (first sync, compaction, header bump). + let base = + chain_base_cursor(&envelope.world_id, &envelope.source, envelope.header_version); + if envelope.cursor_before != base { + return Err(ReplicationError::CursorFork); + } + let chained = chain_payload(envelope.cursor_before, &envelope.payload)?; + if chained != envelope.cursor_after { + return Err(ReplicationError::EntryChainMismatch); + } + self.cursor = envelope.cursor_after; + self.header_version = envelope.header_version; + } + ReplicationKind::Tail => { + if envelope.header_version != self.header_version { + return Err(ReplicationError::HeaderVersionChanged); + } + if envelope.cursor_before.ordinal > self.cursor.ordinal { + return Err(ReplicationError::CursorGap); + } + if envelope.cursor_before.ordinal < self.cursor.ordinal { + return Err(ReplicationError::StaleCursor); + } + if envelope.cursor_before != self.cursor { + return Err(ReplicationError::CursorFork); + } + let chained = chain_payload(envelope.cursor_before, &envelope.payload)?; + if chained != envelope.cursor_after { + return Err(ReplicationError::EntryChainMismatch); + } + self.cursor = envelope.cursor_after; + } + ReplicationKind::Terminal => { + if envelope.header_version != self.header_version { + return Err(ReplicationError::HeaderVersionChanged); + } + if !envelope.payload.is_empty() + || envelope.cursor_before != envelope.cursor_after + || envelope.cursor_after != self.cursor + { + return Err(ReplicationError::TerminalCursorMismatch); + } + } + } + self.last_frame_digest = frame_digest(frame_bytes); + Ok(AcceptedFrame { + kind: envelope.kind, + cursor_after: envelope.cursor_after, + payload: envelope.payload.clone(), + }) + } +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +mod tests { + use super::*; + use crate::world::JournalEntry; + + const WORLD: &str = "world-replication-test"; + const NONCE: [u8; SESSION_NONCE_BYTES] = [7; SESSION_NONCE_BYTES]; + + fn signing_key(seed: u8) -> SigningKey { + SigningKey::from_bytes(&[seed; 32]) + } + + fn source_of(key: &SigningKey) -> [u8; 32] { + *key.verifying_key().as_bytes() + } + + fn hex(bytes: &[u8]) -> String { + bytes.iter().map(|byte| format!("{byte:02x}")).collect() + } + + /// Three real journal entries as their exact replicated line bytes. + fn entry_payload() -> Vec { + let entries = [ + JournalEntry::Created { + world_id: WORLD.to_string(), + version: 1, + }, + JournalEntry::CapsGranted { + granted: vec!["chat".to_string()], + }, + JournalEntry::CapsCeiling { + ceiling: vec!["chat".to_string(), "input".to_string()], + }, + ]; + entries.iter().flat_map(journal_entry_line).collect() + } + + fn tracker(key: &SigningKey) -> ReplicationTracker { + ReplicationTracker::new(WORLD, source_of(key), 1, NONCE) + } + + /// A signed tail frame over `payload`, chained from `cursor` with + /// frame-chain digest `prev`. + fn signed_tail( + key: &SigningKey, + cursor: ReplicationCursor, + prev: [u8; 32], + payload: Vec, + ) -> Vec { + let envelope = ReplicationEnvelope::tail( + WORLD, + source_of(key), + 1, + NONCE, + cursor, + prev, + payload, + ) + .unwrap(); + SignedReplicationEnvelope::sign(envelope, key) + .unwrap() + .encode_frame() + .unwrap() + } + + #[test] + fn chain_base_is_a_pinned_deterministic_test_vector() { + let source = [3u8; 32]; + let base = chain_base_cursor(WORLD, &source, 1); + assert_eq!(base.ordinal, 0); + // Pinned vector: any change to the domain tag, seed fields, or + // seed encoding changes this digest and must be a deliberate, + // version-bumped contract change. + assert_eq!(hex(&base.digest), "d32092e6f4f8a8e813644b4e8a14ad2439d50c320c41fcb2aa9d24e6c0d1d291"); + // Domain separation: another world, source, or header version is + // a different chain. + assert_ne!(base, chain_base_cursor("other-world", &source, 1)); + assert_ne!(base, chain_base_cursor(WORLD, &[4u8; 32], 1)); + assert_ne!(base, chain_base_cursor(WORLD, &source, 2)); + // The chain is reproducible from the entry bytes alone (restart). + let payload = entry_payload(); + let mut cursor = base; + for line in payload.split_inclusive(|byte| *byte == b'\n') { + cursor = advance_cursor(cursor, line); + } + assert_eq!(cursor, chain_payload(base, &payload).unwrap()); + assert_eq!(cursor.ordinal, 3); + } + + #[test] + fn tail_round_trip_verifies_and_advances_the_cursor() { + let key = signing_key(1); + let mut receiver = tracker(&key); + let payload = entry_payload(); + let frame = signed_tail( + &key, + chain_base_cursor(WORLD, &source_of(&key), 1), + [0; 32], + payload.clone(), + ); + let decoded = SignedReplicationEnvelope::decode_frame(&frame).unwrap(); + assert_eq!(decoded.envelope.entry_count(), 3); + let accepted = receiver.accept(&frame).unwrap(); + assert_eq!(accepted.kind, ReplicationKind::Tail); + assert_eq!(accepted.payload, payload); + assert_eq!(accepted.cursor_after.ordinal, 3); + assert_eq!(receiver.cursor(), accepted.cursor_after); + // The terminal frame then commits the reached cursor. + let terminal = ReplicationEnvelope::terminal( + WORLD, + source_of(&key), + 1, + NONCE, + receiver.cursor(), + frame_digest(&frame), + ); + let terminal_bytes = SignedReplicationEnvelope::sign(terminal, &key) + .unwrap() + .encode_frame() + .unwrap(); + let committed = receiver.accept(&terminal_bytes).unwrap(); + assert_eq!(committed.kind, ReplicationKind::Terminal); + assert!(committed.payload.is_empty()); + } + + #[test] + fn tampered_frames_are_refused() { + let key = signing_key(1); + let payload = entry_payload(); + let frame = signed_tail( + &key, + chain_base_cursor(WORLD, &source_of(&key), 1), + [0; 32], + payload, + ); + // Mutating a payload byte after signing breaks the signature. + let mut tampered = SignedReplicationEnvelope::decode_frame(&frame).unwrap(); + tampered.envelope.payload[0] ^= 0xff; + let tampered_bytes = tampered.encode_frame().unwrap(); + assert_eq!( + tracker(&key).accept(&tampered_bytes), + Err(ReplicationError::BadSignature) + ); + // Mutating the claimed cursor after signing also breaks it. + let mut tampered = SignedReplicationEnvelope::decode_frame(&frame).unwrap(); + tampered.envelope.cursor_after.ordinal += 1; + let tampered_bytes = tampered.encode_frame().unwrap(); + assert_eq!( + tracker(&key).accept(&tampered_bytes), + Err(ReplicationError::BadSignature) + ); + // A correctly signed frame whose payload digest lies is refused + // on the digest check, past the signature check. + let mut lying = ReplicationEnvelope::tail( + WORLD, + source_of(&key), + 1, + NONCE, + chain_base_cursor(WORLD, &source_of(&key), 1), + [0; 32], + entry_payload(), + ) + .unwrap(); + lying.payload_digest = payload_digest(b"not the payload"); + let lying_bytes = SignedReplicationEnvelope::sign(lying, &key) + .unwrap() + .encode_frame() + .unwrap(); + assert_eq!( + tracker(&key).accept(&lying_bytes), + Err(ReplicationError::PayloadDigestMismatch) + ); + } + + #[test] + fn truncated_frames_and_unfinished_batches_are_refused() { + let key = signing_key(1); + let frame = signed_tail( + &key, + chain_base_cursor(WORLD, &source_of(&key), 1), + [0; 32], + entry_payload(), + ); + // A truncated frame does not decode, and does not advance state. + let cut = &frame[..frame.len() - 5]; + assert!(SignedReplicationEnvelope::decode_frame(cut).is_none()); + let mut receiver = tracker(&key); + assert_eq!(receiver.accept(cut), Err(ReplicationError::MalformedFrame)); + assert_eq!(receiver.cursor().ordinal, 0); + // A terminal frame for a cursor the batch never reached (the + // batch was truncated before its last entry) does not commit. + let wrong_terminal = ReplicationEnvelope::terminal( + WORLD, + source_of(&key), + 1, + NONCE, + ReplicationCursor { + ordinal: 99, + digest: [9; 32], + }, + [0; 32], + ); + let wrong_bytes = SignedReplicationEnvelope::sign(wrong_terminal, &key) + .unwrap() + .encode_frame() + .unwrap(); + assert_eq!( + tracker(&key).accept(&wrong_bytes), + Err(ReplicationError::TerminalCursorMismatch) + ); + } + + #[test] + fn gap_fork_and_replay_are_refused() { + let key = signing_key(1); + let base = chain_base_cursor(WORLD, &source_of(&key), 1); + let payload = entry_payload(); + let first_line_end = payload.iter().position(|byte| *byte == b'\n').unwrap() + 1; + + // Gap: a frame that starts at entry 1 while the receiver is at 0. + let gap_frame = signed_tail( + &key, + advance_cursor(base, &payload[..first_line_end]), + [0; 32], + payload[first_line_end..].to_vec(), + ); + assert_eq!( + tracker(&key).accept(&gap_frame), + Err(ReplicationError::CursorGap) + ); + + // Fork: two different first frames; after accepting one, the + // other no longer continues the verified chain. + let frame_a = signed_tail(&key, base, [0; 32], payload.clone()); + let mut other_payload = payload.clone(); + other_payload.extend_from_slice(&journal_entry_line(&JournalEntry::CapsGranted { + granted: vec!["builder".to_string()], + })); + let frame_b = signed_tail(&key, base, [0; 32], other_payload); + let mut receiver = tracker(&key); + receiver.accept(&frame_a).unwrap(); + assert_eq!( + receiver.accept(&frame_b), + Err(ReplicationError::FrameChainMismatch) + ); + // Replay: the already-accepted frame itself is stale now. + assert_eq!( + receiver.accept(&frame_a), + Err(ReplicationError::FrameChainMismatch) + ); + // A frame naming a bogus previous-frame digest is refused before + // its cursor is even considered. + let bad_prev = signed_tail(&key, receiver.cursor(), [8; 32], payload.clone()); + assert_eq!( + receiver.accept(&bad_prev), + Err(ReplicationError::FrameChainMismatch) + ); + } + + #[test] + fn unsupported_versions_are_refused_at_the_boundary() { + let key = signing_key(1); + let base = chain_base_cursor(WORLD, &source_of(&key), 1); + // Envelope version from the future. + let mut future = ReplicationEnvelope::tail( + WORLD, + source_of(&key), + 1, + NONCE, + base, + [0; 32], + entry_payload(), + ) + .unwrap(); + future.version = REPLICATION_ENVELOPE_VERSION + 1; + let future_bytes = SignedReplicationEnvelope::sign(future, &key) + .unwrap() + .encode_frame() + .unwrap(); + assert_eq!( + tracker(&key).accept(&future_bytes), + Err(ReplicationError::UnsupportedEnvelopeVersion(2)) + ); + // Journal header version newer than this binary reads: refused + // before any entry is applied (F11.12 header-boundary rule). + let future_journal = ReplicationEnvelope::tail( + WORLD, + source_of(&key), + MAX_JOURNAL_VERSION + 1, + NONCE, + base, + [0; 32], + entry_payload(), + ) + .unwrap(); + let future_journal_bytes = SignedReplicationEnvelope::sign(future_journal, &key) + .unwrap() + .encode_frame() + .unwrap(); + assert_eq!( + tracker(&key).accept(&future_journal_bytes), + Err(ReplicationError::UnsupportedJournalVersion( + MAX_JOURNAL_VERSION + 1 + )) + ); + } + + #[test] + fn untrusted_sources_and_cross_session_replays_are_refused() { + let key = signing_key(1); + let stranger = signing_key(2); + let base = chain_base_cursor(WORLD, &source_of(&key), 1); + let frame = signed_tail(&key, base, [0; 32], entry_payload()); + // A receiver pinned to a different source refuses the frame. + let mut pinned_elsewhere = + ReplicationTracker::new(WORLD, source_of(&stranger), 1, NONCE); + assert_eq!( + pinned_elsewhere.accept(&frame), + Err(ReplicationError::UntrustedSource) + ); + // Signing for another key's source claim is refused at sign time. + let claim = ReplicationEnvelope::tail( + WORLD, + source_of(&stranger), + 1, + NONCE, + chain_base_cursor(WORLD, &source_of(&stranger), 1), + [0; 32], + entry_payload(), + ) + .unwrap(); + assert!(SignedReplicationEnvelope::sign(claim, &key).is_none()); + // The same frame replayed into a session with a fresh nonce is + // refused: the signature binds the session nonce. + let mut other_session = + ReplicationTracker::new(WORLD, source_of(&key), 1, [8; SESSION_NONCE_BYTES]); + assert_eq!( + other_session.accept(&frame), + Err(ReplicationError::NonceMismatch) + ); + } + + #[test] + fn payload_bounds_are_enforced() { + let key = signing_key(1); + // An over-bound payload cannot even be signed into a frame. + let oversized = vec![b'x'; MAX_REPLICATION_PAYLOAD_BYTES + 1]; + let mut envelope = ReplicationEnvelope::terminal( + WORLD, + source_of(&key), + 1, + NONCE, + chain_base_cursor(WORLD, &source_of(&key), 1), + [0; 32], + ); + envelope.payload = oversized; + assert!(SignedReplicationEnvelope::sign(envelope, &key).is_none()); + // Chaining refuses an over-bound or boundary-less payload. + let base = chain_base_cursor(WORLD, &source_of(&key), 1); + assert_eq!( + chain_payload(base, &vec![b'x'; MAX_REPLICATION_PAYLOAD_BYTES + 1]), + Err(ReplicationError::PayloadTooLarge) + ); + assert_eq!( + chain_payload(base, b"no newline at the end"), + Err(ReplicationError::MalformedPayload) + ); + // Splitting respects the bound and entry boundaries, and the + // chunks reassemble to the original payload. + let line = journal_entry_line(&JournalEntry::CapsGranted { + granted: vec!["chat".to_string()], + }); + let mut big = Vec::new(); + while big.len() <= MAX_REPLICATION_PAYLOAD_BYTES { + big.extend_from_slice(&line); + } + let chunks = split_entry_payload(&big).unwrap(); + assert!(chunks.len() >= 2); + assert!( + chunks + .iter() + .all(|chunk| chunk.len() <= MAX_REPLICATION_PAYLOAD_BYTES) + ); + assert!( + chunks + .iter() + .all(|chunk| chunk.ends_with(b"\n") && !chunk.is_empty()) + ); + assert_eq!(chunks.concat(), big); + // One entry larger than the bound can never be replicated. + let giant_line = vec![b'y'; MAX_REPLICATION_PAYLOAD_BYTES + 1]; + let mut giant = giant_line; + giant.push(b'\n'); + assert_eq!( + split_entry_payload(&giant), + Err(ReplicationError::PayloadTooLarge) + ); + assert_eq!( + split_entry_payload(b"unterminated"), + Err(ReplicationError::MalformedPayload) + ); + assert_eq!(split_entry_payload(&[]), Ok(Vec::new())); + } + + #[test] + fn snapshot_rebases_the_chain_on_a_header_bump() { + let key = signing_key(1); + let mut receiver = tracker(&key); + let first = signed_tail( + &key, + chain_base_cursor(WORLD, &source_of(&key), 1), + [0; 32], + entry_payload(), + ); + receiver.accept(&first).unwrap(); + // After a header bump the writer sends a snapshot on the new + // chain base; the receiver rebases instead of demanding + // continuity with the old chain. + let snapshot = ReplicationEnvelope::snapshot( + WORLD, + source_of(&key), + 2, + NONCE, + frame_digest(&first), + entry_payload(), + ) + .unwrap(); + let snapshot_bytes = SignedReplicationEnvelope::sign(snapshot, &key) + .unwrap() + .encode_frame() + .unwrap(); + let accepted = receiver.accept(&snapshot_bytes).unwrap(); + assert_eq!(accepted.kind, ReplicationKind::Snapshot); + assert_eq!(receiver.header_version(), 2); + assert_eq!(accepted.cursor_after.ordinal, 3); + assert_eq!( + accepted.cursor_after, + chain_payload(chain_base_cursor(WORLD, &source_of(&key), 2), &entry_payload()) + .unwrap() + ); + // A tail on the old header version is now refused. + let stale_tail = ReplicationEnvelope::tail( + WORLD, + source_of(&key), + 1, + NONCE, + receiver.cursor(), + frame_digest(&snapshot_bytes), + entry_payload(), + ) + .unwrap(); + let stale_bytes = SignedReplicationEnvelope::sign(stale_tail, &key) + .unwrap() + .encode_frame() + .unwrap(); + assert_eq!( + receiver.accept(&stale_bytes), + Err(ReplicationError::HeaderVersionChanged) + ); + } + + #[test] + fn trailing_bytes_and_undecodable_entries_are_refused() { + // Regression tests for the Codex review findings on PR #4447. + let key = signing_key(1); + let base = chain_base_cursor(WORLD, &source_of(&key), 1); + let frame = signed_tail(&key, base, [0; 32], entry_payload()); + // Bytes appended to an otherwise valid frame refuse it outright: + // the envelope decode must not ignore a trailing suffix. + let mut extended = frame.clone(); + extended.extend_from_slice(b"unsigned suffix"); + assert!(SignedReplicationEnvelope::decode_frame(&extended).is_none()); + let mut receiver = tracker(&key); + assert_eq!( + receiver.accept(&extended), + Err(ReplicationError::MalformedFrame) + ); + assert_eq!(receiver.cursor(), base); + // A payload whose lines do not decode as journal entries is + // refused before the verified cursor advances, even when the + // pinned source signed it. + let mut bogus = ReplicationEnvelope::terminal( + WORLD, + source_of(&key), + 1, + NONCE, + base, + [0; 32], + ); + bogus.kind = ReplicationKind::Tail; + bogus.payload = b"not-json\n".to_vec(); + bogus.payload_digest = payload_digest(&bogus.payload); + bogus.cursor_after = ReplicationCursor { + ordinal: base.ordinal + 1, + digest: [5; 32], + }; + let bogus_bytes = SignedReplicationEnvelope::sign(bogus, &key) + .unwrap() + .encode_frame() + .unwrap(); + assert_eq!( + receiver.accept(&bogus_bytes), + Err(ReplicationError::MalformedPayload) + ); + assert_eq!(receiver.cursor(), base); + } +}