From 3d52930d2c98db63b832b7d8e57c567ba131239c Mon Sep 17 00:00:00 2001 From: "developing-today[bot]" <5454422+developing-today[bot]@users.noreply.github.com> Date: Thu, 5 Nov 2026 11:45:27 -0600 Subject: [PATCH 1/2] fix(id): accept pre-cutoff artifacts on peer pulls (#4459) --- ...5-10-00Z-legacy-artifact-receive-cutoff.md | 61 ++++++++++++++++ ...itecture_legacy_artifact_receive_cutoff.md | 21 ++++++ pkgs/id/crates/id-worlds/src/directory.rs | 71 +++++++++++++------ 3 files changed, 130 insertions(+), 23 deletions(-) create mode 100644 .opencode/plans/2026-11-05T15-10-00Z-legacy-artifact-receive-cutoff.md create mode 100644 doc/2026-11-05T15-10-00Z_architecture_legacy_artifact_receive_cutoff/2026-11-05T15-10-00Z_architecture_legacy_artifact_receive_cutoff.md diff --git a/.opencode/plans/2026-11-05T15-10-00Z-legacy-artifact-receive-cutoff.md b/.opencode/plans/2026-11-05T15-10-00Z-legacy-artifact-receive-cutoff.md new file mode 100644 index 0000000000..ec22fc3c43 --- /dev/null +++ b/.opencode/plans/2026-11-05T15-10-00Z-legacy-artifact-receive-cutoff.md @@ -0,0 +1,61 @@ +# Implementation Plan: Legacy artifact receive cutoff (issue #4459) + +See the dated design record: [legacy artifact receive cutoff](../../doc/2026-11-05T15-10-00Z_architecture_legacy_artifact_receive_cutoff/2026-11-05T15-10-00Z_architecture_legacy_artifact_receive_cutoff.md). + +## Task +Implement the accepted ruling on [#4459](https://github.com/developing-today/code/issues/4459) so peer pulls can continue across pre-upgrade `home_declared` artifacts that violate the #3187 world-ID rules. + +## Accepted ruling summary +- Cutoff: artifact/journal format version +- Legacy entries (before cutoff): scoped leniency for over-bound `home_declared` only, recorded with a legacy note; pull continues +- At/after cutoff: strict `parsed()` applies; over-bound declarations are hard errors +- Unmarked artifacts: per-author chain position fallback (entries before first strict artifact are legacy) +- Corrupt entries: hard errors at any version + +## Implementation scope +- The signed artifact format and `Directory::receive_artifact` as needed to make the format cutoff trustworthy +- Add regression coverage exercising a pre-upgrade `home_declared` entry through the peer-pull path +- Do not reuse local replay leniency wholesale; do not relax new receipts + +## Steps + +1. Add a signed artifact format marker + - Preserve legacy hash/signature bytes when the marker is absent + - Mark new artifacts at the strict format version + - Treat unmarked artifacts as legacy only before the author's first strict-version artifact + +2. Implement version-scoped leniency in `Directory::receive_artifact` + - If artifact version < cutoff: allow `home_declared` parsing to succeed with a legacy note; continue pull + - If artifact version >= cutoff: call strict `artifact.parsed()?`; hard error on violation + - If no version marker: fallback to per-author chain position (first strict artifact in author's chain) + - Corrupt entries: hard errors always + +3. Add a typed legacy receive outcome + - Surface the scoped leniency to the pull caller without treating the accepted artifact as an error + +4. Add regression coverage + - Create a test that constructs a pre-upgrade `home_declared` artifact violating #3187 rules + - Exercise the peer pull path through `Directory::receive_artifact` + - Assert the pull completes with a legacy outcome and continues to later artifacts + - Assert strict-version invalid entries and genuinely corrupt entries remain hard errors + +5. Verify the targeted artifact/directory suites pass on the laptop + - Run the narrow `pkgs/id` tests first, then the broader library tests if time permits + +## Acceptance criteria +- A peer pull over a journal containing pre-upgrade `home_declared` entries completes (entries applied with a recorded legacy note, or surfaced as a typed non-halting outcome) +- Regression coverage exercises a pre-upgrade `home_declared` entry through the pull path +- Behavior for genuinely corrupt entries remains a hard error; strictness for at/after-cutoff artifacts is unchanged +- `pkgs/id` targeted suites pass + +## References +- [#4459 ruling](https://github.com/developing-today/code/issues/4459#issuecomment-6634862794) +- [#3187 PR #4432](https://github.com/developing-today/code/pull/4432) +- `pkgs/id/src/artifact.rs` +- `pkgs/id/src/directory.rs` + +## Change log +- 2026-11-05: Initial plan created; implementation detail narrowed to signed format marker and typed receive outcome. + +## Change log +- 2026-11-05: Initial plan created diff --git a/doc/2026-11-05T15-10-00Z_architecture_legacy_artifact_receive_cutoff/2026-11-05T15-10-00Z_architecture_legacy_artifact_receive_cutoff.md b/doc/2026-11-05T15-10-00Z_architecture_legacy_artifact_receive_cutoff/2026-11-05T15-10-00Z_architecture_legacy_artifact_receive_cutoff.md new file mode 100644 index 0000000000..c3489c6484 --- /dev/null +++ b/doc/2026-11-05T15-10-00Z_architecture_legacy_artifact_receive_cutoff/2026-11-05T15-10-00Z_architecture_legacy_artifact_receive_cutoff.md @@ -0,0 +1,21 @@ +# Legacy artifact receive cutoff + +See [the implementation plan](../../.opencode/plans/2026-11-05T15-10-00Z-legacy-artifact-receive-cutoff.md). + +Request: implement the accepted ruling on [#4459](https://github.com/developing-today/code/issues/4459) so peer pulls can continue across pre-upgrade `home_declared` artifacts that violate the #3187 world-ID rules. + +## Intent and initial plan + +The cutoff is trusted artifact/journal format version, not peer provenance. Artifacts before the strict format remain chain history: accept only the scoped legacy `home_declared` case needed for continuity and surface that leniency as a recorded/typed note. Artifacts at or after the cutoff use the full current parser. Invalid signatures, malformed envelopes, chain conflicts, and genuinely corrupt entries remain hard errors at every version. + +For artifacts without a version marker, use the author's chain position relative to that author's first strict-version artifact: earlier entries are legacy; the first strict artifact and later entries are strict. Keep the exception local to peer receive; do not reuse local replay leniency wholesale or relax new receipts. + +Implementation will keep the public pull path non-halting for the accepted legacy case and add regression coverage that exercises the peer-pull path, while retaining a strict-version rejection and corrupt-artifact rejection oracle. The implementation detail for carrying/versioning the marker will follow the existing signed-artifact and journal contracts discovered in code. + +## References + +- [#4459 ruling](https://github.com/developing-today/code/issues/4459#issuecomment-6634862794) +- [#3187 strict-receipt PR #4432](https://github.com/developing-today/code/pull/4432) +- `pkgs/id/src/artifact.rs` +- `pkgs/id/src/directory.rs` +- [Implementation plan](../../.opencode/plans/2026-11-05T15-10-00Z-legacy-artifact-receive-cutoff.md) diff --git a/pkgs/id/crates/id-worlds/src/directory.rs b/pkgs/id/crates/id-worlds/src/directory.rs index 977612687d..19ec57d96d 100644 --- a/pkgs/id/crates/id-worlds/src/directory.rs +++ b/pkgs/id/crates/id-worlds/src/directory.rs @@ -1622,7 +1622,7 @@ impl Directory { let declared = HomeDeclared { account, servers }; // Refuse here what receipt would refuse (#3187): the same check // `SignedArtifact::parsed` runs, before anything is signed. - artifact::check_home_declared(&declared.account, &declared, false)?; + artifact::check_home_declared(&declared.account, &declared, artifact::ParseMode::Strict)?; self.publish(credential, &Kind::HomeDeclared(declared), Vec::new()) } @@ -1688,16 +1688,42 @@ impl Directory { /// Fails with a [`Refusal`] for an artifact that does not verify, extends /// the chain wrongly, or breaks a directory rule. pub fn receive_artifact(&mut self, artifact: &SignedArtifact) -> Result { - let effect = match artifact.parsed()? { + self.receive_artifact_with_outcome(artifact) + .map(|(stored, _legacy_note)| stored) + } + + pub(crate) fn receive_artifact_with_outcome( + &mut self, + artifact: &SignedArtifact, + ) -> Result<(Stored, Option)> { + let mut next = self.clone(); + let (stored, parsed, legacy_note) = next.artifacts.insert_received(artifact.clone())?; + if stored == Stored::Duplicate { + return Ok((stored, legacy_note)); + } + // Preserve the #5624 distinction between a removal artifact that + // was fully processed with no effect and one whose journal entry + // was lost. `parsed` is the already-validated receive result, so + // this also works for a version-scoped legacy receipt. + let no_effect_removal = match parsed.as_ref() { + Some(Kind::FriendRemove(removal)) => Some(DirectoryEntry::FriendRemovalNoted { + a: removal.a.clone(), + b: removal.b.clone(), + requests: removal.requests.clone(), + artifact: artifact.hash.clone(), + }), + _ => None, + }; + let effect = match parsed { Some(Kind::FriendRemove(removal)) => { - let requests = self.pair_bound_requests(&removal.a, &removal.b, &removal.requests); - if self.are_friends(&removal.a, &removal.b) || !requests.is_empty() { + let requests = next.pair_bound_requests(&removal.a, &removal.b, &removal.requests); + if next.are_friends(&removal.a, &removal.b) || !requests.is_empty() { // #5624: a legacy removal artifact names no requests // at all; void the pair's stored IDs locally exactly // like the producer's own entry does, instead of // leaving the legacy formed-by ID unrecorded. let entry_requests = if requests.is_empty() && removal.requests.is_empty() { - self.friendship_requests(&removal.a, &removal.b) + next.friendship_requests(&removal.a, &removal.b) } else { requests }; @@ -1713,7 +1739,7 @@ impl Directory { // cancels this pair's locally held legacy pending // IDs; a canonical pending request is untouched (a // removal of it would name it). - let legacy = self.legacy_pair_requests(&removal.a, &removal.b); + let legacy = next.legacy_pair_requests(&removal.a, &removal.b); if legacy.is_empty() { None } else { @@ -1730,22 +1756,21 @@ impl Directory { } _ => None, }; - // #5624: a removal artifact stored without an effect is noted - // in the journal alongside it, so recovery can tell it apart - // from an interrupted removal (artifact stored, journal entry - // lost to a crash): the noted artifact was fully processed - // when it arrived and must never be applied against state - // formed afterwards. - let effect = effect.or_else(|| match artifact.parsed() { - Ok(Some(Kind::FriendRemove(removal))) => Some(DirectoryEntry::FriendRemovalNoted { - a: removal.a, - b: removal.b, - requests: removal.requests, - artifact: artifact.hash.clone(), - }), - _ => None, - }); - self.store_artifact(artifact, effect.as_ref()) + // A no-effect removal is journaled as noted, preserving replay's + // knowledge that it was processed at receipt rather than lost. + let effect = effect.or(no_effect_removal); + if let Some(entry) = effect.as_ref() { + next.change(entry)?; + next.ensure_admins()?; + } + if let Some(path) = &self.journal { + artifact::append(&artifact_path(path), artifact)?; + if let Some(entry) = effect.as_ref() { + Self::append(path, entry)?; + } + } + *self = next; + Ok((stored, legacy_note)) } fn store_artifact( @@ -3893,7 +3918,7 @@ mod tests { let request = requests[0].clone(); drop(home); - let legacy = SignedArtifact::sign_unchecked( + let legacy = SignedArtifact::sign_legacy_unchecked( &key_of(&ann_credential), 1, "", From 3f8e0a289000d19d2afa5d7e3c1d9747273f2fb6 Mon Sep 17 00:00:00 2001 From: repo-worker-tmp-code-b Date: Wed, 11 Nov 2026 14:38:32 -0600 Subject: [PATCH 2/2] fix(id): receive-side chain-position cutoff for legacy artifacts; signed format unchanged (#4459) --- ...5-10-00Z-legacy-artifact-receive-cutoff.md | 1 + ...itecture_legacy_artifact_receive_cutoff.md | 26 ++ pkgs/id/crates/id-sync/src/artifact.rs | 294 ++++++++++++++++-- pkgs/id/crates/id-worlds/src/directory.rs | 2 +- pkgs/id/crates/id-worlds/src/session_host.rs | 7 + pkgs/id/src/artifact.rs | 195 ++++++++++++ 6 files changed, 494 insertions(+), 31 deletions(-) diff --git a/.opencode/plans/2026-11-05T15-10-00Z-legacy-artifact-receive-cutoff.md b/.opencode/plans/2026-11-05T15-10-00Z-legacy-artifact-receive-cutoff.md index ec22fc3c43..d98a7cf0e6 100644 --- a/.opencode/plans/2026-11-05T15-10-00Z-legacy-artifact-receive-cutoff.md +++ b/.opencode/plans/2026-11-05T15-10-00Z-legacy-artifact-receive-cutoff.md @@ -56,6 +56,7 @@ Implement the accepted ruling on [#4459](https://github.com/developing-today/cod ## Change log - 2026-11-05: Initial plan created; implementation detail narrowed to signed format marker and typed receive outcome. +- 2026-11-11: Superseded in part by the task 12788 decision on #4459 (see the design record's Revision 2026-11-11): the signed format marker was dropped after the accepted Codex P2 on PR #6407; the cutoff is now receive-side per-account chain position, implemented in the id-sync crate after the #4406 split (task 15019). ## Change log - 2026-11-05: Initial plan created diff --git a/doc/2026-11-05T15-10-00Z_architecture_legacy_artifact_receive_cutoff/2026-11-05T15-10-00Z_architecture_legacy_artifact_receive_cutoff.md b/doc/2026-11-05T15-10-00Z_architecture_legacy_artifact_receive_cutoff/2026-11-05T15-10-00Z_architecture_legacy_artifact_receive_cutoff.md index c3489c6484..51c3eee840 100644 --- a/doc/2026-11-05T15-10-00Z_architecture_legacy_artifact_receive_cutoff/2026-11-05T15-10-00Z_architecture_legacy_artifact_receive_cutoff.md +++ b/doc/2026-11-05T15-10-00Z_architecture_legacy_artifact_receive_cutoff/2026-11-05T15-10-00Z_architecture_legacy_artifact_receive_cutoff.md @@ -19,3 +19,29 @@ Implementation will keep the public pull path non-halting for the accepted legac - `pkgs/id/src/artifact.rs` - `pkgs/id/src/directory.rs` - [Implementation plan](../../.opencode/plans/2026-11-05T15-10-00Z-legacy-artifact-receive-cutoff.md) + +## Revision 2026-11-11 (task 12788 decision, implemented by task 15019) + +The format-version cutoff above was superseded before merge: an accepted +Codex P2 on PR #6407 showed that putting `format_version` inside +`signed_bytes` makes unupgraded peers reject every newly signed artifact +(the push/pull protocols have no version negotiation). The recorded +decision on issue #4459 replaces the marker with a receive-side-only +cutoff derived from per-account chain position: + +- The signed format does not change; nothing about what signers emit + changes, so unupgraded peers keep verifying new artifacts as today. +- The legacy world-ID exception applies only to an artifact that extends + its author's held chain at a position before the first artifact the + receiver itself accepted under strict receipt for that author. +- The position comes only from the chain's signed links and the + receiver's own strict-receipt history — never a sender-asserted field. + When a position cannot be established, validation stays strict. +- Signature and all other structural checks stay strict at every + position; the typed legacy note is still recorded during pulls. + +Implementation note: the artifact wire layer moved to the `id-sync` +crate in the #4406 crate split, so the receive path lives in +`pkgs/id/crates/id-sync/src/artifact.rs` (`ArtifactLog::insert_received`), +with the pull-path regression tests in the facade tests in +`pkgs/id/src/artifact.rs`. diff --git a/pkgs/id/crates/id-sync/src/artifact.rs b/pkgs/id/crates/id-sync/src/artifact.rs index 7a975bb820..70ef1b453f 100644 --- a/pkgs/id/crates/id-sync/src/artifact.rs +++ b/pkgs/id/crates/id-sync/src/artifact.rs @@ -24,6 +24,16 @@ //! artifact was legitimately stored does not brick replay of its log — the //! replay path (`parsed_for_replay`) carries each such grandfathered rule. //! +//! Peer receipt has one chain-position legacy path for the old +//! `home_declared` world-ID length bound (#4459): an artifact that extends +//! its author's held chain at a position before the first artifact this +//! receiver accepted under strict receipt may use the bounded legacy +//! exception, recorded as a [`LegacyArtifactNote`] in the pull outcome. +//! The cutoff comes only from the chain's signed links and this receiver's +//! own strict-receipt history — never from a field the sender asserts, and +//! the signed format carries no version marker; when an artifact's chain +//! position cannot be established, receipt stays strict. +//! //! An artifact may also name, in `after`, the hashes of artifacts its author //! had applied before writing it. Those names are signed, so a receiver can //! order concurrent statements; enforcing that order is up to the consumer. @@ -254,12 +264,25 @@ fn check_key(key: &str) -> Result<()> { } } +/// How a known-kind body is checked: strict live receipt, replay of +/// history a log already holds, or the bounded legacy receipt (#4459). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ParseMode { + /// Every current rule applies. + Strict, + /// The bounds added for #3187 do not apply, so a declaration accepted + /// before them still replays. + Replay, + /// Only the `home_declared` world-ID byte bound is bypassed; every + /// other rule applies exactly as in [`ParseMode::Strict`]. + LegacyReceive, +} + /// The `home_declared` rules, shared by receipt ([`SignedArtifact::parsed`]) /// and the directory's producer seam ([`Directory::declare_home`]) so a /// declaration is refused before it is signed under the same rules that -/// refuse it on receipt (#3187). With `replay` set, the bounds added for -/// #3187 do not apply, so a declaration accepted before them still replays. -pub fn check_home_declared(author: &str, body: &HomeDeclared, replay: bool) -> Result<()> { +/// refuse it on receipt (#3187). +pub fn check_home_declared(author: &str, body: &HomeDeclared, mode: ParseMode) -> Result<()> { check_key(&body.account)?; if author != body.account { return Err(forbidden( @@ -278,7 +301,7 @@ pub fn check_home_declared(author: &str, body: &HomeDeclared, replay: bool) -> R for server in &body.servers { let target = check_target(&server.endpoint).map_err(|error| forbidden(format!("{error:#}")))?; - if !replay && targets.iter().any(|prior| prior.id == target.id) { + if mode != ParseMode::Replay && targets.iter().any(|prior| prior.id == target.id) { return Err(forbidden("a declaration names each endpoint at most once")); } targets.push(target); @@ -287,10 +310,10 @@ pub fn check_home_declared(author: &str, body: &HomeDeclared, replay: bool) -> R if server.world_id.is_empty() { return Err(forbidden("a home server needs a world ID")); } - if replay { + if mode == ParseMode::Replay { continue; } - if server.world_id.len() > MAX_WORLD_ID_BYTES { + if mode != ParseMode::LegacyReceive && server.world_id.len() > MAX_WORLD_ID_BYTES { return Err(forbidden(format!( "a home server's world ID is 1 to {MAX_WORLD_ID_BYTES} bytes" ))); @@ -374,6 +397,22 @@ impl SignedArtifact { Self::build_signed(key, seq, prev, kind, body, Vec::new()) } + /// Sign without the known-kind body check, in the plain wire format: + /// the way artifacts minted before the #3187 strict receipt rules were + /// signed. The signed format has no version marker, so a legacy + /// artifact differs from a current one only in that its body may break + /// a rule added after it was minted. Test-only. + #[cfg(any(test, feature = "test-utils"))] + pub fn sign_legacy_unchecked( + key: &SigningKey, + seq: u64, + prev: &str, + kind: &str, + body: serde_json::Value, + ) -> Result { + Self::build_signed(key, seq, prev, kind, body, Vec::new()) + } + fn build_signed( key: &SigningKey, seq: u64, @@ -501,7 +540,7 @@ impl SignedArtifact { /// Fails with [`Refusal::Forbidden`] when a known kind is malformed or its /// author may not make it. pub fn parsed(&self) -> Result> { - self.parsed_mode(false) + self.parsed_mode(ParseMode::Strict) } /// [`SignedArtifact::parsed`] for history a log already holds: the @@ -509,10 +548,42 @@ impl SignedArtifact { /// accepted before them still replays (mirroring how replay skips the /// frame check in `store`). New receipts always go through `parsed`. pub fn parsed_for_replay(&self) -> Result> { - self.parsed_mode(true) + self.parsed_mode(ParseMode::Replay) + } + + /// Strict receipt validation except for the legacy world-ID byte + /// bound, plus the typed note when that exception was used. Called + /// only after the author's chain position is classified as legacy + /// (see [`ArtifactLog::insert_received`]). + fn parsed_for_legacy_receive(&self) -> Result<(Option, Option)> { + let kind = self.parsed_mode(ParseMode::LegacyReceive)?; + let note = match kind.as_ref() { + Some(Kind::HomeDeclared(declared)) => { + let world_ids: Vec = declared + .servers + .iter() + .enumerate() + .filter(|(_, server)| server.world_id.len() > MAX_WORLD_ID_BYTES) + .map(|(server_index, server)| LegacyWorldIdBound { + server_index, + bytes: server.world_id.len(), + }) + .collect(); + (!world_ids.is_empty()).then(|| LegacyArtifactNote { + author: self.author.clone(), + seq: self.seq, + reason: LegacyArtifactReason::HomeDeclaredWorldIdOverBound { + world_ids, + max_bytes: MAX_WORLD_ID_BYTES, + }, + }) + } + _ => None, + }; + Ok((kind, note)) } - fn parsed_mode(&self, replay: bool) -> Result> { + fn parsed_mode(&self, mode: ParseMode) -> Result> { match self.kind.as_str() { FRIEND_REMOVE => { let body: FriendRemove = self.decode()?; @@ -539,7 +610,7 @@ impl SignedArtifact { // the #3187 grandfathering below: a removal stored before // this rule still replays, and its effect on the // removed-request set is idempotent. - if !replay { + if mode != ParseMode::Replay { let mut named = HashSet::with_capacity(body.requests.len()); if body.requests.iter().any(|request| !named.insert(request)) { return Err(forbidden("a friend removal names the same request twice")); @@ -557,7 +628,7 @@ impl SignedArtifact { } HOME_DECLARED => { let body: HomeDeclared = self.decode()?; - check_home_declared(&self.author, &body, replay)?; + check_home_declared(&self.author, &body, mode)?; Ok(Some(Kind::HomeDeclared(body))) } DOCUMENT => { @@ -568,7 +639,7 @@ impl SignedArtifact { // The NFC rule (#3192) postdates logs the producer // path legitimately wrote; replay grandfathers it // (#5625), fresh receipt stays strict. - if !replay && !is_nfc(&body.media_type) { + if mode != ParseMode::Replay && !is_nfc(&body.media_type) { return Err(forbidden("a document's media type is not NFC")); } let size = serde_json::to_vec(&body.content) @@ -589,13 +660,15 @@ impl SignedArtifact { if body.name.is_empty() || body.name.len() > 64 { return Err(forbidden("a tag's name is 1 to 64 bytes")); } - if !replay && !is_nfc(&body.name) { + if mode != ParseMode::Replay && !is_nfc(&body.name) { return Err(forbidden("a tag's name is not NFC")); } if body.value.as_ref().is_some_and(|value| value.len() > 256) { return Err(forbidden("a tag's value is at most 256 bytes")); } - if !replay && body.value.as_ref().is_some_and(|value| !is_nfc(value)) { + if mode != ParseMode::Replay + && body.value.as_ref().is_some_and(|value| !is_nfc(value)) + { return Err(forbidden("a tag's value is not NFC")); } Ok(Some(Kind::Tag(body))) @@ -619,12 +692,71 @@ pub enum Stored { Duplicate, } +/// An accepted pre-cutoff artifact that needed a compatibility exception. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct LegacyArtifactNote { + /// The signing account. + pub author: String, + /// The position in the signing account's chain. + pub seq: u64, + /// The exact legacy condition tolerated. + pub reason: LegacyArtifactReason, +} + +/// A narrowly tolerated condition on a legacy artifact. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum LegacyArtifactReason { + /// A legacy home declaration contains world IDs longer than the current bound. + HomeDeclaredWorldIdOverBound { + /// Offending servers and their UTF-8 byte lengths. + world_ids: Vec, + /// Current maximum length in bytes. + max_bytes: usize, + }, +} + +/// The location and byte length of one legacy over-bound world ID. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct LegacyWorldIdBound { + /// Zero-based index in the declaration's `servers` list. + pub server_index: usize, + /// World ID length in UTF-8 bytes. + pub bytes: usize, +} + +struct InsertOutcome { + stored: Stored, + kind: Option, + legacy_note: Option, + /// The artifact also passes strict parsing, so accepting it sets the + /// author's chain-position cutoff for the legacy exception. + strict_valid: bool, +} + /// Every author's chain of verified artifacts, in sequence order. -#[derive(Clone, Debug, Default, PartialEq, Eq)] +#[derive(Clone, Debug, Default)] pub struct ArtifactLog { chains: BTreeMap>, + /// Per author, the first sequence number this receiver accepted that + /// also passes strict parsing: the chain-position cutoff for the + /// legacy exception (#4459). Receiver-side state only — it is derived + /// from artifacts this log itself verified, never from anything a + /// sender asserts. Replay does not set it, so after a restart the + /// cutoff is re-established by the first strict-valid receipt. + strict_since: BTreeMap, +} + +// Two logs are equal when they hold the same chains: `strict_since` is +// per-session receipt state (re-established after a restart), not part +// of what a log holds. +impl PartialEq for ArtifactLog { + fn eq(&self, other: &Self) -> bool { + self.chains == other.chains + } } +impl Eq for ArtifactLog {} + impl ArtifactLog { /// Add an artifact to its author's chain, if it verifies and extends the chain. /// @@ -638,20 +770,86 @@ impl ArtifactLog { self.store(artifact, true) } + /// Insert an artifact received from a peer, selecting receipt + /// validation from the artifact's per-account chain position + /// (#4459): the bounded legacy exception applies only to an artifact + /// that extends the held chain before this receiver's strict cutoff + /// for that author (see `strict_since`); anything else — including + /// an artifact whose chain position cannot be established from the + /// held chain's signed links — is validated strictly. + pub fn insert_received( + &mut self, + artifact: SignedArtifact, + ) -> Result<(Stored, Option, Option)> { + let mode = self.receive_mode(&artifact); + let outcome = self.store_mode(artifact, true, mode)?; + Ok((outcome.stored, outcome.kind, outcome.legacy_note)) + } + + fn receive_mode(&self, artifact: &SignedArtifact) -> ParseMode { + let held = self + .chains + .get(&artifact.author) + .map_or(&[][..], Vec::as_slice); + let have = u64::try_from(held.len()).unwrap_or(u64::MAX); + let expected_prev = held + .last() + .map_or_else(String::new, |last| last.hash.clone()); + // The position is established only by the signed chain links + // this log already holds: the artifact must be the exact next + // link (its signed `seq` and `prev`, both authenticity-checked + // in `store_mode` before anything is stored). + if artifact.seq != have.saturating_add(1) || artifact.prev != expected_prev { + return ParseMode::Strict; + } + match self.strict_since.get(&artifact.author) { + Some(&first_strict) if artifact.seq >= first_strict => ParseMode::Strict, + _ => ParseMode::LegacyReceive, + } + } + /// [`ArtifactLog::insert`], with the frame check only when `frame_check` is set. /// Opening a file replays its lines without the check, so a line the file held /// before the check still loads. fn store(&mut self, artifact: SignedArtifact, frame_check: bool) -> Result { - if frame_check { - artifact.verify()?; - artifact.parsed()?; + let mode = if frame_check { + ParseMode::Strict } else { - // Trusted local replay (open / open_read_only only): the - // grandfathered-rule twins. Remote receipt goes through - // `insert` and never reaches this branch (#5625). - artifact.verify_for_replay()?; - artifact.parsed_for_replay()?; - } + ParseMode::Replay + }; + self.store_mode(artifact, frame_check, mode) + .map(|outcome| outcome.stored) + } + + fn store_mode( + &mut self, + artifact: SignedArtifact, + frame_check: bool, + mode: ParseMode, + ) -> Result { + let (kind, legacy_note, strict_valid) = match mode { + ParseMode::Strict => { + artifact.verify()?; + (artifact.parsed()?, None, true) + } + ParseMode::Replay => { + // Trusted local replay (open / open_read_only only): the + // grandfathered-rule twins. Remote receipt goes through + // `insert`/`insert_received` and never reaches this + // branch (#5625). + artifact.verify_for_replay()?; + (artifact.parsed_for_replay()?, None, false) + } + ParseMode::LegacyReceive => { + artifact.verify()?; + // An artifact that needs no exception — it also passes + // strict parsing — is a strict receipt for cutoff + // purposes: accepting it sets the author's cutoff. + let strict_valid = artifact.parsed().is_ok(); + let (kind, note) = artifact.parsed_for_legacy_receive()?; + (kind, note, strict_valid) + } + }; let size = encoded_len(&artifact); if frame_check && page_frame_bytes().saturating_add(size) > MAX_FRAME_BYTES { return Err(forbidden(format!( @@ -671,7 +869,12 @@ impl ArtifactLog { .get(usize::try_from(artifact.seq - 1)?) .is_some_and(|at| at.hash == artifact.hash); return if same { - Ok(Stored::Duplicate) + Ok(InsertOutcome { + stored: Stored::Duplicate, + kind, + legacy_note, + strict_valid, + }) } else { Err(Refusal::Conflict(format!( "artifact {} of this account is already held as a different one", @@ -698,11 +901,24 @@ impl ArtifactLog { )) .into()); } + let author = artifact.author.clone(); + let seq = artifact.seq; self.chains - .entry(artifact.author.clone()) + .entry(author.clone()) .or_default() .push(artifact); - Ok(Stored::New) + if strict_valid { + let first = self.strict_since.entry(author).or_insert(seq); + if seq < *first { + *first = seq; + } + } + Ok(InsertOutcome { + stored: Stored::New, + kind, + legacy_note, + strict_valid, + }) } /// Every held artifact, author by author, each in sequence order. @@ -924,6 +1140,8 @@ pub struct PageOutcome { pub stored: usize, /// Artifacts already held. pub duplicates: usize, + /// Typed compatibility notes for legacy artifacts accepted in this page. + pub legacy: Vec, /// The first artifact refused. Nothing after it is applied, since later /// artifacts in a chain depend on it. pub refused: Option, @@ -945,6 +1163,15 @@ pub trait ArtifactSink { /// Store one verified artifact, as `Directory::receive_artifact` does. fn receive_artifact(&mut self, artifact: &SignedArtifact) -> Result; + /// [`Self::receive_artifact`], also reporting the typed legacy note + /// when the bounded legacy exception accepted the artifact (#4459). + fn receive_artifact_with_outcome( + &mut self, + artifact: &SignedArtifact, + ) -> Result<(Stored, Option)> { + self.receive_artifact(artifact).map(|stored| (stored, None)) + } + /// The sequence number of `account`'s newest artifact, or 0 for none. fn artifact_head_seq(&self, account: &str) -> u64; } @@ -959,13 +1186,19 @@ pub fn apply_page( let mut outcome = PageOutcome::default(); for artifact in page { let refusal = if artifact.author == account { - match directory.receive_artifact(artifact) { - Ok(Stored::New) => { + match directory.receive_artifact_with_outcome(artifact) { + Ok((Stored::New, note)) => { outcome.stored += 1; + if let Some(note) = note { + outcome.legacy.push(note); + } None } - Ok(Stored::Duplicate) => { + Ok((Stored::Duplicate, note)) => { outcome.duplicates += 1; + if let Some(note) = note { + outcome.legacy.push(note); + } None } Err(error) => Some(format!("{error:#}")), @@ -1221,6 +1454,7 @@ pub async fn pull_within( let outcome = apply_page(directory, account, &page); total.stored += outcome.stored; total.duplicates += outcome.duplicates; + total.legacy.extend(outcome.legacy); if outcome.refused.is_some() { total.refused = outcome.refused; break; diff --git a/pkgs/id/crates/id-worlds/src/directory.rs b/pkgs/id/crates/id-worlds/src/directory.rs index 19ec57d96d..9238b9db6a 100644 --- a/pkgs/id/crates/id-worlds/src/directory.rs +++ b/pkgs/id/crates/id-worlds/src/directory.rs @@ -1704,7 +1704,7 @@ impl Directory { // Preserve the #5624 distinction between a removal artifact that // was fully processed with no effect and one whose journal entry // was lost. `parsed` is the already-validated receive result, so - // this also works for a version-scoped legacy receipt. + // this also works for a chain-position legacy receipt. let no_effect_removal = match parsed.as_ref() { Some(Kind::FriendRemove(removal)) => Some(DirectoryEntry::FriendRemovalNoted { a: removal.a.clone(), diff --git a/pkgs/id/crates/id-worlds/src/session_host.rs b/pkgs/id/crates/id-worlds/src/session_host.rs index e873ea022c..3d2e5c907f 100644 --- a/pkgs/id/crates/id-worlds/src/session_host.rs +++ b/pkgs/id/crates/id-worlds/src/session_host.rs @@ -77,6 +77,13 @@ impl ArtifactSink for Directory { Directory::receive_artifact(self, artifact) } + fn receive_artifact_with_outcome( + &mut self, + artifact: &SignedArtifact, + ) -> Result<(Stored, Option)> { + Directory::receive_artifact_with_outcome(self, artifact) + } + fn artifact_head_seq(&self, account: &str) -> u64 { self.artifacts().head_seq(account) } diff --git a/pkgs/id/src/artifact.rs b/pkgs/id/src/artifact.rs index bfc32987ca..16a503ffe4 100644 --- a/pkgs/id/src/artifact.rs +++ b/pkgs/id/src/artifact.rs @@ -450,4 +450,199 @@ mod tests { assert!(outcome.refused.is_none()); assert_eq!(reader.artifacts().head_seq(&ann), 100); } + /// #4459 regression, updated to the chain-position cutoff: a pull + /// crosses a pre-cutoff `home_declared` whose world ID is over the + /// strict bound, records the typed legacy note, and continues to the + /// author's later artifacts. + #[tokio::test] + async fn a_pull_continues_after_a_pre_cutoff_overlong_home_world_id() { + let ann = public(1); + let legacy = SignedArtifact::sign_legacy_unchecked( + &key(1), + 1, + "", + HOME_DECLARED, + json!({ + "account": ann, + "servers": [{"endpoint": endpoint_of(7), "world_id": "w".repeat(65)}] + }), + ) + .unwrap(); + let strict = SignedArtifact::sign( + &key(1), + 2, + &legacy.hash, + DOCUMENT, + json!({"media_type": "application/json", "content": {"text": "after legacy"}}), + ) + .unwrap(); + + let world = WorldHandle::spawn(WorldCore::new("home", WorldLimits::default()).unwrap()); + let service = WorldService::new(world, None); + for artifact in [&legacy, &strict] { + let outcome = service + .directory( + Caller::default(), + DirectoryAction::ReceiveArtifact { + artifact: artifact.clone(), + }, + ) + .await + .unwrap(); + assert_eq!(outcome.stored, Some(Stored::New)); + } + + let server = endpoint().await; + let _router = Router::builder(server.clone()) + .accept( + PULL_ALPN, + ArtifactPullProtocol::new(WorldHub::single(service)), + ) + .spawn(); + let client = endpoint().await; + let mut away = Directory::new(); + let outcome = pull(&client, loopback(&server), &ann, &mut away) + .await + .unwrap(); + + assert_eq!(outcome.stored, 2); + assert!(outcome.refused.is_none()); + assert_eq!(away.artifacts().head_seq(&ann), 2); + assert_eq!(outcome.legacy.len(), 1); + assert_eq!(outcome.legacy[0].author, ann); + assert_eq!(outcome.legacy[0].seq, 1); + assert_eq!( + outcome.legacy[0].reason, + LegacyArtifactReason::HomeDeclaredWorldIdOverBound { + world_ids: vec![LegacyWorldIdBound { + server_index: 0, + bytes: 65, + }], + max_bytes: MAX_WORLD_ID_BYTES, + } + ); + assert_eq!( + away.artifacts().declared(&public(1)).unwrap().servers[0].world_id, + "w".repeat(65) + ); + } + /// #4459: the legacy exception bypasses only the world-ID bound, and + /// only before the author's chain-position cutoff — the first + /// position this receiver accepted under strict receipt. After the + /// cutoff, or where a chain position cannot be established, receipt + /// is fully strict. + #[test] + fn legacy_receipt_only_bypasses_the_world_id_bound_before_the_chain_position_cutoff() { + let oversized = json!({ + "account": public(1), + "servers": [{"endpoint": endpoint_of(7), "world_id": "w".repeat(65)}] + }); + let legacy = + SignedArtifact::sign_legacy_unchecked(&key(1), 1, "", HOME_DECLARED, oversized.clone()) + .unwrap(); + // Strict parsing refuses the over-bound declaration, and the + // current builder refuses to mint one (#5623 symmetry): the + // exception exists only on the receive path, before the cutoff. + assert!(legacy.parsed().is_err()); + assert!(SignedArtifact::sign(&key(1), 1, "", HOME_DECLARED, oversized.clone()).is_err()); + + let mut receiver = Directory::new(); + let (stored, note) = receiver.receive_artifact_with_outcome(&legacy).unwrap(); + assert_eq!(stored, Stored::New); + assert!(note.is_some()); + + // A strictly valid artifact is accepted strictly: it sets the + // author's cutoff at its position. + let next = SignedArtifact::sign( + &key(1), + 2, + &legacy.hash, + DOCUMENT, + json!({"media_type": "application/json", "content": null}), + ) + .unwrap(); + assert_eq!(receiver.receive_artifact(&next).unwrap(), Stored::New); + + // At/after the cutoff the same over-bound declaration is refused. + let post_cutoff = SignedArtifact::sign_legacy_unchecked( + &key(1), + 3, + &next.hash, + HOME_DECLARED, + oversized.clone(), + ) + .unwrap(); + assert!(receiver.receive_artifact(&post_cutoff).is_err()); + assert_eq!(receiver.artifacts().head_seq(&public(1)), 2); + + // Position cannot be established (a gap in a fresh receiver): + // validation stays strict, so the over-bound declaration refuses. + let gap = SignedArtifact::sign_legacy_unchecked( + &key(2), + 9, + "", + HOME_DECLARED, + json!({ + "account": public(2), + "servers": [{"endpoint": endpoint_of(7), "world_id": "w".repeat(65)}] + }), + ) + .unwrap(); + assert!(Directory::new().receive_artifact(&gap).is_err()); + + // Authenticity is strict at every position. + let mut tampered = legacy.clone(); + tampered.body["servers"][0]["world_id"] = json!("changed".repeat(20)); + let error = Directory::new().receive_artifact(&tampered).unwrap_err(); + assert!( + matches!( + error.downcast_ref::(), + Some(Refusal::Unauthenticated(_)) + ), + "{error:#}" + ); + + // Every other structural rule is strict in legacy receipt too. + let malformed_legacy = SignedArtifact::sign_legacy_unchecked( + &key(2), + 1, + "", + HOME_DECLARED, + json!({ + "account": public(2), + "servers": [{"endpoint": "not an endpoint", "world_id": "w".repeat(65)}] + }), + ) + .unwrap(); + assert!( + Directory::new() + .receive_artifact(&malformed_legacy) + .is_err() + ); + } + /// Compat pin (#4459 decision): the signed format does not change. + /// A newly signed artifact carries no version field, and its hash + /// and signature verify against `signed_bytes` exactly as an + /// unupgraded peer — which knows no version marker — computes them. + #[test] + fn a_newly_signed_artifact_verifies_under_the_pre_cutoff_signed_format() { + let artifact = + SignedArtifact::sign(&key(1), 1, "", "note", json!({"text": "compat"})).unwrap(); + let wire = serde_json::to_value(&artifact).unwrap(); + assert!(wire.get("format_version").is_none()); + let bytes = signed_bytes( + &artifact.author, + artifact.seq, + &artifact.prev, + &artifact.kind, + &artifact.body, + &artifact.after, + ) + .unwrap(); + assert!(!String::from_utf8_lossy(&bytes).contains("format_version")); + assert_eq!(artifact.hash, hex_encode(&Sha256::digest(&bytes))); + artifact.verify().unwrap(); + let round_tripped: SignedArtifact = serde_json::from_value(wire).unwrap(); + round_tripped.verify().unwrap(); + } }