diff --git a/pkgs/id/Cargo.lock b/pkgs/id/Cargo.lock index eebe1db9df..69a73e8078 100644 --- a/pkgs/id/Cargo.lock +++ b/pkgs/id/Cargo.lock @@ -4074,6 +4074,7 @@ name = "id-sync" version = "0.1.0" dependencies = [ "anyhow", + "ed25519-dalek 3.0.0", "futures-lite", "futures-util", "id-core", @@ -4083,18 +4084,22 @@ dependencies = [ "iroh-base", "iroh-blobs", "iroh-mainline-address-lookup", + "iroh-tickets", "p2panda-auth", "p2panda-core", "p2panda-store", "p2panda-sync", "postcard", "proptest", + "rand 0.10.3", "serde", "serde_json", + "sha2 0.11.0", "tempfile", "thiserror 2.0.21", "tokio", "tracing", + "unicode-normalization", ] [[package]] diff --git a/pkgs/id/Cargo.toml b/pkgs/id/Cargo.toml index da325388ca..74f3530226 100644 --- a/pkgs/id/Cargo.toml +++ b/pkgs/id/Cargo.toml @@ -195,6 +195,10 @@ id-core = { path = "crates/id-core", default-features = false, features = [ id-caps = { path = "crates/id-caps", default-features = false, features = [ "test-provider", ] } +# The artifact/envelope test seams live in id-sync since step 3c (#4406). +id-sync = { path = "crates/id-sync", default-features = false, features = [ + "test-utils", +] } # SQLite for the bridge PoC's DO-shaped hosted store (#2276). Bundled, so no system SQLite is needed. rusqlite = { version = "0.32", features = ["bundled"] } wat = "=1.261.0" diff --git a/pkgs/id/crates/id-sync/Cargo.toml b/pkgs/id/crates/id-sync/Cargo.toml index 63f8597076..5ec267aa37 100644 --- a/pkgs/id/crates/id-sync/Cargo.toml +++ b/pkgs/id/crates/id-sync/Cargo.toml @@ -22,11 +22,17 @@ default = [] # Mainline DHT address lookup (P7.3). Off in the default build; the # facade forwards its `dht` feature here. dht = ["dep:iroh-mainline-address-lookup"] +test-utils = [] [dependencies] anyhow = "1" futures-lite = "2" futures-util = { version = "0.3", features = ["sink"] } +ed25519-dalek = { version = "3", features = ["rand_core"] } +iroh-tickets = "1" +rand = "0.10" +sha2 = "0.11" +unicode-normalization = "0.1" id-core = { path = "../id-core", default-features = false } id-events = { path = "../id-events", default-features = false } id-store = { path = "../id-store", default-features = false } diff --git a/pkgs/id/crates/id-sync/src/artifact.rs b/pkgs/id/crates/id-sync/src/artifact.rs new file mode 100644 index 0000000000..7a975bb820 --- /dev/null +++ b/pkgs/id/crates/id-sync/src/artifact.rs @@ -0,0 +1,2387 @@ +//! Signed artifacts: each account's own signed statements, kept as one +//! append-only chain per author. +//! +//! An artifact names its author's Ed25519 key, a per-author sequence number and +//! the hash of the artifact before it, and is signed by that key. Any server +//! can check one without trusting the server that sent it. [`ArtifactLog`] +//! holds only chains that verify, and takes neither a gap nor a fork. A kind +//! this server does not know is stored but never applied, so a newer peer +//! cannot break an older server. Applying a known kind is the directory's job. +//! +//! Receipt contract (#3231): a known-kind artifact is acceptable on receipt +//! only when it satisfies the same rules its in-tree builder must satisfy — +//! enforced in [`SignedArtifact::parsed`] before [`ArtifactLog`] stores or +//! replays it, and at the producer seams that build each kind. The generic +//! builders mirror receipt (#5623): [`SignedArtifact::sign`] and +//! [`SignedArtifact::sign_after`] run the same `parsed` check before +//! returning, so an in-tree caller can no longer mint a signed known-kind +//! artifact that receipt would refuse. A structural +//! rule failure is [`Refusal::Forbidden`] naming the rule; only hash and +//! signature failures are [`Refusal::Unauthenticated`]. Receipt never +//! rewrites signed bytes: duplicates and noncanonical values are refused, +//! not deduplicated or normalized. Unknown kinds keep the forward-compatible +//! rule above: envelope only, stored, never applied. A rule added after an +//! artifact was legitimately stored does not brick replay of its log — the +//! replay path (`parsed_for_replay`) carries each such grandfathered rule. +//! +//! 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. +//! +//! Generic kinds carry data rather than directory changes: a `document` holds +//! structured JSON, and a `tag` labels another artifact by its hash. An author +//! tags their own document with `name` `author` and `value` their key. +//! +//! Artifacts travel over iroh only: pushed to a home server on +//! [`PUSH_ALPN`], and pulled by account from the same endpoint on [`PULL_ALPN`]. + +use std::collections::{BTreeMap, HashSet}; +use std::fs::{self, OpenOptions}; +use std::io::{self, Write}; +use std::path::Path; +use std::time::Duration; + +use anyhow::{Context, Result, bail, ensure}; +use ed25519_dalek::{Signature, Signer as _, SigningKey, VerifyingKey}; +use iroh::{ + Endpoint, EndpointAddr, + endpoint::Connection, + protocol::{AcceptError, ProtocolHandler}, +}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use unicode_normalization::is_nfc; + +use id_core::connectivity::{DIAL_TIMEOUT, connect, within}; +use id_core::Refusal; + +use crate::hex::{hex_encode, hex_to_array, normalize_key}; +use crate::host::{Availability, SessionHost}; +use crate::envelope_net::{Reply, answer_frames, send}; +use crate::envelope_outbox::{Outcome, check_target}; +use id_events::event_sync::{CLOSE_WAIT, SESSION_DEADLINE}; +use id_core::frames::{read_frame, write_frame}; +use id_core::frames::MAX_FRAME_BYTES; + +/// The file, beside `directory.jsonl`, that holds a world's artifacts. +pub const FILE: &str = "artifacts.jsonl"; +/// Bytes one page may take on the wire, counting its JSON framing. +/// +/// A page always carries at least one artifact, so one larger than this is sent +/// alone. The budget keeps a page of maximum-size documents far under the frame limit. +pub const PAGE_BYTES: usize = 256 * 1024; +/// Home servers one declaration may name. +pub const MAX_HOME_SERVERS: usize = 8; +/// The largest world ID one home server may carry, in bytes. +pub const MAX_WORLD_ID_BYTES: usize = 64; +/// Hashes one artifact may name in `after`. +pub const MAX_AFTER: usize = 32; +/// The largest content a document may carry, as serialized JSON. +pub const MAX_DOCUMENT_BYTES: usize = 64 * 1024; +/// The kind of a friend removal. +pub const FRIEND_REMOVE: &str = "friend_remove"; +/// Pending friendship requests a single friend removal can void. +pub const MAX_FRIEND_REMOVE_REQUESTS: usize = 3; +/// The kind of a home-server declaration. +pub const HOME_DECLARED: &str = "home_declared"; +/// The kind of a generic structured document. +pub const DOCUMENT: &str = "document"; +/// The kind of a label on another artifact. +pub const TAG: &str = "tag"; + +/// ALPN on which a server accepts pushed artifacts, one per stream. +pub const PUSH_ALPN: &[u8] = b"/id-artifact-push/1"; +/// ALPN on which a server answers pulls of an account's artifacts. +pub const PULL_ALPN: &[u8] = b"/id-artifact-pull/1"; + +/// One signed statement by an account. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct SignedArtifact { + /// Hex Ed25519 public key of the account that signed it. + pub author: String, + /// One-based position in the author's chain. + pub seq: u64, + /// Hash of the author's artifact at `seq - 1`, empty for `seq` 1. + pub prev: String, + /// What the body says. An unknown kind is kept but not applied. + pub kind: String, + /// The kind-specific fields. + pub body: serde_json::Value, + /// Hashes of artifacts the author had applied before this one. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub after: Vec, + /// Hex SHA-256 over the signed body. + pub hash: String, + /// Hex Ed25519 signature over the signed body. + pub signature: String, +} + +#[derive(Serialize)] +struct SignedBody<'a> { + author: &'a str, + seq: u64, + prev: &'a str, + kind: &'a str, + body: &'a serde_json::Value, + #[serde(skip_serializing_if = "Vec::is_empty")] + after: Vec, +} + +/// The canonical bytes an artifact's hash and signature cover: the +/// author's key, sequence, predecessor, kind, body and `after` frontier, +/// length-prefixed and domain-separated. +pub fn signed_bytes( + author: &str, + seq: u64, + prev: &str, + kind: &str, + body: &serde_json::Value, + after: &[String], +) -> Result> { + Ok(serde_json::to_vec(&SignedBody { + author, + seq, + prev, + kind, + body, + after: after.to_vec(), + })?) +} + +fn is_hash(text: &str) -> bool { + text.len() == 64 + && text + .bytes() + .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)) +} + +/// The canonical friend-request ID shape: 16 bytes as 32 lowercase +/// hexadecimal characters. This is the shape the envelope producer mints +/// (`Envelope::signed` in directory.rs) and the shape the `friend_remove` +/// receipt contract (#3146) requires; directory.rs reuses this predicate +/// at friend-request admission (#5624) so the two never drift. +pub fn is_friend_request_id(text: &str) -> bool { + text.len() == 32 + && text + .bytes() + .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)) +} + +/// A friendship ends, and the request IDs it covers are void. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct FriendRemove { + /// One account. + pub a: String, + /// The other account. + pub b: String, + /// At most three lowercase 32-character hex request IDs covered by this removal. + #[serde(default)] + pub requests: Vec, +} + +/// Where an account's artifacts are held: an endpoint ticket or a bare node ID. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct HomeServer { + /// The Iroh endpoint that takes pushes and serves pulls of the account's artifacts. + pub endpoint: String, + /// The world the server holds the account in. + pub world_id: String, +} + +/// The servers an account publishes its artifacts to. A newer declaration replaces an older one. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct HomeDeclared { + /// The declaring account. + pub account: String, + /// Where its artifacts are held. + pub servers: Vec, +} + +/// Structured data an account publishes as its own statement. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Document { + /// What the content is, such as `application/json`. + pub media_type: String, + /// The content itself. + pub content: serde_json::Value, +} + +/// A label on another artifact, which the subject names by its hash. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Tag { + /// The hash of the artifact labelled. + pub subject: String, + /// The label, such as `author`. + pub name: String, + /// The label's value, such as an account key. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub value: Option, +} + +/// A known kind, with its body decoded. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Kind { + /// A friendship ends. + FriendRemove(FriendRemove), + /// An account names its home servers. + HomeDeclared(HomeDeclared), + /// An account publishes structured data. + Document(Document), + /// An account labels an artifact. + Tag(Tag), +} + +impl Kind { + /// The kind's wire name and JSON body. + pub fn encode(&self) -> Result<(&'static str, serde_json::Value)> { + Ok(match self { + Self::FriendRemove(body) => (FRIEND_REMOVE, serde_json::to_value(body)?), + Self::HomeDeclared(body) => (HOME_DECLARED, serde_json::to_value(body)?), + Self::Document(body) => (DOCUMENT, serde_json::to_value(body)?), + Self::Tag(body) => (TAG, serde_json::to_value(body)?), + }) + } +} + +fn forbidden(message: impl Into) -> anyhow::Error { + Refusal::Forbidden(message.into()).into() +} + +fn check_key(key: &str) -> Result<()> { + match normalize_key(key) { + Ok(canonical) if canonical == key => Ok(()), + _ => Err(forbidden(format!("{key} is not an account key"))), + } +} + +/// 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<()> { + check_key(&body.account)?; + if author != body.account { + return Err(forbidden( + "a home declaration must be signed by its own account", + )); + } + if body.servers.len() > MAX_HOME_SERVERS { + return Err(forbidden(format!( + "a declaration names at most {MAX_HOME_SERVERS} servers" + ))); + } + // Duplicate refusal compares the validated endpoint + // identities, not the raw strings: one node can be named + // by its bare ID or by an endpoint ticket for that ID. + let mut targets: Vec = Vec::with_capacity(body.servers.len()); + 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) { + return Err(forbidden("a declaration names each endpoint at most once")); + } + targets.push(target); + } + for server in &body.servers { + if server.world_id.is_empty() { + return Err(forbidden("a home server needs a world ID")); + } + if replay { + continue; + } + if 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" + ))); + } + if server.world_id.trim().is_empty() { + return Err(forbidden( + "a home server's world ID must not be whitespace only", + )); + } + if server.world_id.chars().any(char::is_control) { + return Err(forbidden( + "a home server's world ID must not contain control characters", + )); + } + if server.world_id.chars().any(id_core::is_format_char) { + return Err(forbidden( + "a home server's world ID must not contain format characters", + )); + } + } + Ok(()) +} + +impl SignedArtifact { + /// Sign a body of `kind` as the author holding `key`, at `seq` after `prev`. + /// + /// # Errors + /// + /// Fails if `seq` is zero or the body cannot be serialized, or if `kind` + /// is a known kind and its body breaks a rule receipt enforces — a + /// [`Refusal::Forbidden`] naming the rule, exactly as + /// [`SignedArtifact::parsed`] would refuse the signed artifact (#5623). + /// Unknown kinds stay envelope-only and always sign. + pub fn sign( + key: &SigningKey, + seq: u64, + prev: &str, + kind: &str, + body: serde_json::Value, + ) -> Result { + Self::sign_after(key, seq, prev, kind, body, Vec::new()) + } + + /// Like [`Self::sign`], also naming `after`, the artifacts the author had applied before this one. + /// + /// # Errors + /// + /// Fails if `seq` is zero, if `after` breaks the frontier rules (see + /// [`Self::check_after`]), if the body cannot be serialized, or if + /// `kind` is a known kind and its body breaks a rule receipt enforces + /// (see [`Self::sign`]). + pub fn sign_after( + key: &SigningKey, + seq: u64, + prev: &str, + kind: &str, + body: serde_json::Value, + after: Vec, + ) -> Result { + let artifact = Self::build_signed(key, seq, prev, kind, body, after)?; + // Construction-vs-receipt symmetry (#5623): a known kind is signed + // only when receipt would accept its body, so the check is the + // receipt check itself, run on the artifact about to go out. + // Unknown kinds parse to `None` and stay signable envelope-only. + artifact.parsed()?; + Ok(artifact) + } + + /// Sign without the known-kind body check in [`Self::sign_after`]: + /// sequence, `after`-frontier, hash, and signature rules all still + /// apply. Test-only, so tests can still craft the signed-but-refusable + /// artifacts that receipt-side tests exist to refuse. + #[cfg(any(test, feature = "test-utils"))] + pub fn sign_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, + prev: &str, + kind: &str, + body: serde_json::Value, + after: Vec, + ) -> Result { + ensure!(seq >= 1, "an artifact's sequence number starts at 1"); + Self::check_after(&after)?; + let author = hex_encode(&key.verifying_key().to_bytes()); + let bytes = signed_bytes(&author, seq, prev, kind, &body, &after)?; + Ok(Self { + hash: hex_encode(&Sha256::digest(&bytes)), + signature: hex_encode(&key.sign(&bytes).to_bytes()), + author, + seq, + prev: prev.to_owned(), + kind: kind.to_owned(), + body, + after, + }) + } + + /// Check the hash against the content and the signature against the author key. + /// + /// # Errors + /// + /// Fails with [`Refusal::Forbidden`] when the `after` frontier breaks a + /// frontier rule — a structural policy refusal, not an authenticity + /// failure (#3196) — and with [`Refusal::Unauthenticated`] if the hash + /// or signature does not check out. + pub fn verify(&self) -> Result<()> { + self.verify_mode(false) + } + + /// [`Self::verify`] for history a log already holds (trusted local + /// replay only): the duplicate-`after` rule (#3196) postdates logs + /// the producer path legitimately wrote, so replay does not apply + /// it - mirroring how replay skips the duplicate-request rule in + /// `parsed_for_replay`. Authenticity (hash, signature, canonical + /// author) and the other frontier rules (count, well-formed hashes) + /// stay strict in both modes: a corrupt or forged line still fails + /// to reopen. Fresh receipt and remote receipt always use + /// [`Self::verify`]; this leniency is never a remote policy (#5625, + /// coordinating with the #4459 format cutoff). + pub(crate) fn verify_for_replay(&self) -> Result<()> { + self.verify_mode(true) + } + + fn verify_mode(&self, replay: bool) -> Result<()> { + Self::check_after_mode(&self.after, replay)?; + self.check_authenticity() + .map_err(|error| Refusal::Unauthenticated(format!("{error:#}")).into()) + } + + /// The `after` frontier rules, shared by construction + /// ([`Self::sign_after`]) and receipt ([`Self::verify`]): at most + /// [`MAX_AFTER`] hashes, each one a well-formed hash, and none named + /// twice. Receipt refuses a duplicate rather than deduplicating it, so + /// what the signer supplied stays visible (#3231). + fn check_after(after: &[String]) -> Result<()> { + Self::check_after_mode(after, false) + } + + fn check_after_mode(after: &[String], replay: bool) -> Result<()> { + if after.len() > MAX_AFTER { + return Err(forbidden(format!( + "an artifact names at most {MAX_AFTER} artifacts before it" + ))); + } + if after.iter().any(|hash| !is_hash(hash)) { + return Err(forbidden("an artifact names a malformed hash in after")); + } + // The duplicate rule is the #3196 addition: in replay mode a + // frontier stored before it is grandfathered (see + // [`Self::verify_for_replay`]); construction and fresh receipt + // refuse a duplicate rather than deduplicating it. + if !replay { + let mut seen = HashSet::with_capacity(after.len()); + for hash in after { + if !seen.insert(hash) { + return Err(forbidden(format!( + "an artifact names {hash} twice in after" + ))); + } + } + } + Ok(()) + } + + fn check_authenticity(&self) -> Result<()> { + ensure!( + normalize_key(&self.author)? == self.author, + "author is not a canonical key" + ); + let bytes = signed_bytes( + &self.author, + self.seq, + &self.prev, + &self.kind, + &self.body, + &self.after, + )?; + ensure!( + hex_encode(&Sha256::digest(&bytes)) == self.hash, + "artifact hash does not match its content" + ); + let key = VerifyingKey::from_bytes( + &hex_to_array::<32>(&self.author).context("malformed author key")?, + ) + .context("author is not an Ed25519 key")?; + let signature = Signature::from_bytes( + &hex_to_array::<64>(&self.signature).context("malformed artifact signature")?, + ); + key.verify_strict(&bytes, &signature) + .context("signature does not verify against the author key") + } + + /// The known kind this artifact carries, checked. `None` for a kind this + /// server does not know: it is stored but never applied. + /// + /// # Errors + /// + /// 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) + } + + /// [`SignedArtifact::parsed`] for history a log already holds: the + /// `home_declared` bounds added for #3187 do not apply, so a declaration + /// 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) + } + + fn parsed_mode(&self, replay: bool) -> Result> { + match self.kind.as_str() { + FRIEND_REMOVE => { + let body: FriendRemove = self.decode()?; + check_key(&body.a)?; + check_key(&body.b)?; + if body.requests.len() > MAX_FRIEND_REMOVE_REQUESTS { + return Err(forbidden(format!( + "a friend removal names at most {MAX_FRIEND_REMOVE_REQUESTS} requests" + ))); + } + if body + .requests + .iter() + .any(|request| !is_friend_request_id(request)) + { + return Err(forbidden( + "a friend removal request ID is not 32 lowercase hexadecimal characters", + )); + } + // The producer sorts and deduplicates its request IDs + // (directory.rs `friendship_requests`); a receipt naming + // the same request twice is refused rather than + // deduplicated (#3146). Replay stays lenient, mirroring + // the #3187 grandfathering below: a removal stored before + // this rule still replays, and its effect on the + // removed-request set is idempotent. + if !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")); + } + } + if body.a == body.b { + return Err(forbidden("no one befriends themselves")); + } + if self.author != body.a && self.author != body.b { + return Err(forbidden( + "a friend removal must be signed by one of its two accounts", + )); + } + Ok(Some(Kind::FriendRemove(body))) + } + HOME_DECLARED => { + let body: HomeDeclared = self.decode()?; + check_home_declared(&self.author, &body, replay)?; + Ok(Some(Kind::HomeDeclared(body))) + } + DOCUMENT => { + let body: Document = self.decode()?; + if body.media_type.is_empty() || body.media_type.len() > 128 { + return Err(forbidden("a document names its media type")); + } + // 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) { + return Err(forbidden("a document's media type is not NFC")); + } + let size = serde_json::to_vec(&body.content) + .map_err(|error| forbidden(format!("{error}")))? + .len(); + if size > MAX_DOCUMENT_BYTES { + return Err(forbidden(format!( + "a document holds at most {MAX_DOCUMENT_BYTES} bytes of content" + ))); + } + Ok(Some(Kind::Document(body))) + } + TAG => { + let body: Tag = self.decode()?; + if !is_hash(&body.subject) { + return Err(forbidden("a tag names its subject by hash")); + } + 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) { + 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)) { + return Err(forbidden("a tag's value is not NFC")); + } + Ok(Some(Kind::Tag(body))) + } + _ => Ok(None), + } + } + + fn decode(&self) -> Result { + serde_json::from_value(self.body.clone()) + .map_err(|error| forbidden(format!("{} body is malformed: {error}", self.kind))) + } +} + +/// Whether an insert stored a new artifact or matched one already held. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Stored { + /// The artifact extends its author's chain. + New, + /// The same artifact is already held. + Duplicate, +} + +/// Every author's chain of verified artifacts, in sequence order. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct ArtifactLog { + chains: BTreeMap>, +} + +impl ArtifactLog { + /// Add an artifact to its author's chain, if it verifies and extends the chain. + /// + /// # Errors + /// + /// Fails with [`Refusal::Unauthenticated`] for a bad signature or hash, and + /// with [`Refusal::Conflict`] for a gap, a fork, or a `prev` that does not + /// match. An artifact that one frame cannot carry is [`Refusal::Forbidden`], + /// since no page could ever send it. The log is unchanged on error. + pub fn insert(&mut self, artifact: SignedArtifact) -> Result { + self.store(artifact, true) + } + + /// [`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()?; + } 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()?; + } + let size = encoded_len(&artifact); + if frame_check && page_frame_bytes().saturating_add(size) > MAX_FRAME_BYTES { + return Err(forbidden(format!( + "an artifact of {size} bytes cannot be sent in one frame of {MAX_FRAME_BYTES} bytes" + ))); + } + if artifact.seq < 1 { + return Err(forbidden("sequence numbers start at 1")); + } + let held = self + .chains + .get(&artifact.author) + .map_or(&[][..], Vec::as_slice); + let have = u64::try_from(held.len())?; + if artifact.seq <= have { + let same = held + .get(usize::try_from(artifact.seq - 1)?) + .is_some_and(|at| at.hash == artifact.hash); + return if same { + Ok(Stored::Duplicate) + } else { + Err(Refusal::Conflict(format!( + "artifact {} of this account is already held as a different one", + artifact.seq + )) + .into()) + }; + } + if artifact.seq > have + 1 { + return Err(Refusal::Conflict(format!( + "artifact {} is missing; it must be pulled before artifact {}", + have + 1, + artifact.seq + )) + .into()); + } + let expected = held + .last() + .map_or_else(String::new, |last| last.hash.clone()); + if artifact.prev != expected { + return Err(Refusal::Conflict(format!( + "artifact {} does not follow the one held before it", + artifact.seq + )) + .into()); + } + self.chains + .entry(artifact.author.clone()) + .or_default() + .push(artifact); + Ok(Stored::New) + } + + /// Every held artifact, author by author, each in sequence order. + pub fn all(&self) -> impl Iterator { + self.chains.values().flatten() + } + + /// The number of artifacts held for an author, which is the last sequence number. + #[must_use] + pub fn head_seq(&self, author: &str) -> u64 { + self.chains + .get(author) + .map_or(0, |chain| u64::try_from(chain.len()).unwrap_or(u64::MAX)) + } + + /// The author's artifacts with a sequence number after `after`, in order, up to + /// [`PAGE_BYTES`]. A page always holds at least one artifact if any remain. + #[must_use] + pub fn page(&self, author: &str, after: u64) -> Vec { + let mut page: Vec = Vec::new(); + let mut used = page_frame_bytes(); + for artifact in self + .chains + .get(author) + .into_iter() + .flatten() + .filter(|artifact| artifact.seq > after) + { + let size = encoded_len(artifact).saturating_add(usize::from(!page.is_empty())); + if !page.is_empty() && used.saturating_add(size) > PAGE_BYTES { + break; + } + used = used.saturating_add(size); + page.push(artifact.clone()); + } + page + } + + /// The latest home-server declaration an account has made. + #[must_use] + pub fn declared(&self, account: &str) -> Option { + self.chains.get(account)?.iter().rev().find_map(|artifact| { + match artifact.parsed_for_replay() { + Ok(Some(Kind::HomeDeclared(declared))) => Some(declared), + _ => None, + } + }) + } + + /// Sign `kind` as the author holding `key`, at the position after its chain's head. + /// The result is not added to the log. + /// + /// # Errors + /// + /// Fails if the body cannot be serialized, or if the kind's body breaks + /// a rule receipt enforces (see [`SignedArtifact::sign`]). + pub fn sign(&self, key: &SigningKey, kind: &Kind) -> Result { + self.sign_after(key, kind, Vec::new()) + } + + /// Like [`Self::sign`], also naming `after`, the artifacts the author had applied before this one. + /// + /// # Errors + /// + /// Fails if the body cannot be serialized, or if the kind's body breaks + /// a rule receipt enforces (see [`SignedArtifact::sign`]). + pub fn sign_after( + &self, + key: &SigningKey, + kind: &Kind, + after: Vec, + ) -> Result { + let author = hex_encode(&key.verifying_key().to_bytes()); + let (seq, prev) = self.chains.get(&author).map_or_else( + || (1, String::new()), + |chain| { + let last = chain.last(); + ( + last.map_or(1, |last| last.seq + 1), + last.map_or_else(String::new, |last| last.hash.clone()), + ) + }, + ); + let (name, body) = kind.encode()?; + SignedArtifact::sign_after(key, seq, &prev, name, body, after) + } + + /// Load the log at `path`, which is empty if the file does not exist. A + /// final line cut short by a crash was never synced, so it is dropped and + /// the file is truncated to the last complete line, with a warning. Blank + /// lines are skipped, as `Directory::replay` skips them (#2128). + /// + /// # Errors + /// + /// Fails if a complete line is corrupt or does not verify. + pub fn open(path: &Path) -> Result { + let bytes = match fs::read(path) { + Ok(bytes) => bytes, + Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(Self::default()), + Err(error) => return Err(error).context("reading the artifact file"), + }; + let kept = bytes + .iter() + .rposition(|&byte| byte == b'\n') + .map_or(0, |index| index + 1); + if kept < bytes.len() { + // #2128: mirror Directory::replay / FileJournal::open - a torn + // final entry is dropped loudly, not silently. + tracing::warn!( + "artifact journal {}: dropping torn final entry at byte {kept}", + path.display() + ); + OpenOptions::new() + .write(true) + .open(path)? + .set_len(u64::try_from(kept)?)?; + } + let text = std::str::from_utf8(&bytes[..kept]).context("artifact file is not UTF-8")?; + let mut log = Self::default(); + for (number, line) in text.lines().enumerate() { + // #2128: blank lines are cosmetic (Directory::replay skips them + // in its own journal); enumerate() keeps the physical line + // number, so a corrupt non-blank line still reports its true + // position below. + if line.trim().is_empty() { + continue; + } + let artifact: SignedArtifact = serde_json::from_str(line) + .with_context(|| format!("artifact line {} is corrupt", number + 1))?; + log.store(artifact, false) + .with_context(|| format!("artifact line {} is refused", number + 1))?; + } + Ok(log) + } + + /// Load and verify an artifact log without truncating a torn final + /// fragment. Used by read-only replicas, whose startup must never + /// rewrite local state. + pub fn open_read_only(path: &Path) -> Result { + let bytes = match fs::read(path) { + Ok(bytes) => bytes, + Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(Self::default()), + Err(error) => return Err(error).context("reading the artifact file"), + }; + let kept = bytes + .iter() + .rposition(|&byte| byte == b'\n') + .map_or(0, |index| index + 1); + let text = std::str::from_utf8(&bytes[..kept]).context("artifact file is not UTF-8")?; + let mut log = Self::default(); + for (number, line) in text.lines().enumerate() { + if line.trim().is_empty() { + continue; + } + let artifact: SignedArtifact = serde_json::from_str(line) + .with_context(|| format!("artifact line {} is corrupt", number + 1))?; + log.store(artifact, false) + .with_context(|| format!("artifact line {} is refused", number + 1))?; + } + Ok(log) + } +} + +/// Durably append one artifact to the file at `path`. +/// +/// # Errors +/// +/// Fails if the file cannot be written or synced. +pub fn append(path: &Path, artifact: &SignedArtifact) -> Result<()> { + let mut line = serde_json::to_vec(artifact)?; + line.push(b'\n'); + let mut file = OpenOptions::new().create(true).append(true).open(path)?; + file.write_all(&line)?; + file.sync_data()?; + Ok(()) +} + +/// A page of an account's artifacts, the answer to one [`PullRequest`]. +#[derive(Debug, Serialize, Deserialize)] +pub struct Page { + /// The account's artifacts after the sequence number asked for, in order. + pub artifacts: Vec, +} + +/// The bytes of a page with no artifacts in it, which is `{"artifacts":[]}`. +fn page_frame_bytes() -> usize { + serde_json::to_vec(&Page { + artifacts: Vec::new(), + }) + .map_or(0, |bytes| bytes.len()) +} + +/// The bytes one artifact takes inside a page. An artifact that does not encode +/// counts as unbounded, so it can only ever be sent alone. +fn encoded_len(artifact: &SignedArtifact) -> usize { + serde_json::to_vec(artifact).map_or(usize::MAX, |bytes| bytes.len()) +} + +/// The bytes a page of `artifacts` takes on the wire, with one comma between artifacts. +fn page_bytes(artifacts: &[SignedArtifact]) -> usize { + artifacts + .iter() + .enumerate() + .fold(page_frame_bytes(), |used, (index, artifact)| { + used.saturating_add(encoded_len(artifact)) + .saturating_add(usize::from(index > 0)) + }) +} + +/// Whether a page is within [`PAGE_BYTES`], or holds one artifact that is larger alone. +fn within_budget(artifacts: &[SignedArtifact]) -> bool { + artifacts.len() <= 1 || page_bytes(artifacts) <= PAGE_BYTES +} + +/// What applying a page did. +#[derive(Debug, Default, PartialEq, Eq)] +pub struct PageOutcome { + /// Artifacts newly stored. + pub stored: usize, + /// Artifacts already held. + pub duplicates: usize, + /// The first artifact refused. Nothing after it is applied, since later + /// artifacts in a chain depend on it. + pub refused: Option, +} + +/// The artifact a page stopped at, and why. +#[derive(Debug, PartialEq, Eq)] +pub struct PageRefusal { + /// The refused artifact's sequence number. + pub seq: u64, + /// Why it was refused. + pub reason: String, +} + +/// The artifact store [`apply_page`] and [`pull`] write to: the seam +/// between transfer and the directory that owns the log (seam 9 of the +/// crate split, #4406). The facade implements it for its `Directory`. +pub trait ArtifactSink { + /// Store one verified artifact, as `Directory::receive_artifact` does. + fn receive_artifact(&mut self, artifact: &SignedArtifact) -> Result; + + /// The sequence number of `account`'s newest artifact, or 0 for none. + fn artifact_head_seq(&self, account: &str) -> u64; +} + +/// Apply a page of `account`'s artifacts to `directory`. Each artifact is +/// checked on its own, so the server that served the page is not trusted. +pub fn apply_page( + directory: &mut D, + account: &str, + page: &[SignedArtifact], +) -> PageOutcome { + let mut outcome = PageOutcome::default(); + for artifact in page { + let refusal = if artifact.author == account { + match directory.receive_artifact(artifact) { + Ok(Stored::New) => { + outcome.stored += 1; + None + } + Ok(Stored::Duplicate) => { + outcome.duplicates += 1; + None + } + Err(error) => Some(format!("{error:#}")), + } + } else { + Some("artifact is not from the requested account".to_owned()) + }; + if let Some(reason) = refusal { + outcome.refused = Some(PageRefusal { + seq: artifact.seq, + reason, + }); + break; + } + } + outcome +} + +/// One pull on [`PULL_ALPN`]: the artifacts of `account` after sequence `after`. +#[derive(Debug, Serialize, Deserialize)] +pub struct PullRequest { + /// The account whose chain is wanted. + pub account: String, + /// The last sequence number the puller already holds. + pub after: u64, +} + +/// Answers [`PULL_ALPN`] pulls from the worlds a hub holds. +#[derive(Clone, Debug)] +pub struct ArtifactPullProtocol { + /// The host the pulls are served from. + pub hub: H, + /// Deadline for the request frame to arrive (see `accept`). + pub frame_deadline: Duration, + /// Bound on the post-answer wait for the dialer to close. + pub close_wait: Duration, +} + +impl ArtifactPullProtocol { + /// Serve the artifacts of the worlds in `hub` to Iroh peers. + #[must_use] + pub const fn new(hub: H) -> Self { + Self { + hub, + frame_deadline: SESSION_DEADLINE, + close_wait: CLOSE_WAIT, + } + } + + async fn page(&self, request: &PullRequest) -> Result { + check_key(&request.account)?; + let page = match self + .hub + .read_artifacts(request.account.clone(), request.after) + .await + { + Ok(Availability::Available(page)) => page, + Ok(Availability::Busy) => bail!("the server is busy; try again"), + Err(error) => return Err(error), + }; + Ok(Page { artifacts: page }) + } +} + +fn refused(error: anyhow::Error) -> AcceptError { + AcceptError::from_boxed(error.into()) +} + +impl ProtocolHandler for ArtifactPullProtocol { + async fn accept(&self, conn: Connection) -> Result<(), AcceptError> { + let (mut send, mut recv) = conn.accept_bi().await?; + // A peer that connects and never sends its request frame + // must not hold this handler forever (#2087): bound the + // read by the same session deadline event sync uses for a + // silent peer. + let frame = tokio::time::timeout(self.frame_deadline, read_frame(&mut recv)).await; + let frame = match frame { + Ok(frame) => frame.map_err(refused)?, + Err(_elapsed) => return Ok(()), + }; + let Some(frame) = frame else { + return Ok(()); + }; + let request: PullRequest = + serde_json::from_slice(&frame).map_err(|error| refused(error.into()))?; + let page = self.page(&request).await.map_err(refused)?; + let bytes = serde_json::to_vec(&page).map_err(|error| refused(error.into()))?; + write_frame(&mut send, &bytes).await.map_err(refused)?; + send.finish()?; + // Bound the wait for the dialer to close, as event sync + // does (#2087): a peer that never closes must not pin the + // handler after its answer is sent. + let _ = tokio::time::timeout(self.close_wait, conn.closed()).await; + Ok(()) + } +} + +/// Accepts pushed artifacts on [`PUSH_ALPN`] and stores them in the worlds a hub holds. +#[derive(Clone, Debug)] +pub struct ArtifactPushProtocol { + hub: H, +} + +impl ArtifactPushProtocol { + /// Take pushed artifacts for the worlds in `hub`. + #[must_use] + pub const fn new(hub: H) -> Self { + Self { hub } + } +} + +impl ProtocolHandler for ArtifactPushProtocol { + async fn accept(&self, conn: Connection) -> Result<(), AcceptError> { + let hub = self.hub.clone(); + answer_frames(&conn, move |body| { + let hub = hub.clone(); + async move { receive_pushed(&hub, &body).await } + }) + .await + } +} + +/// Push `artifact` to the home server at `target`, and say whether it is done. +pub async fn push(endpoint: &Endpoint, target: EndpointAddr, artifact: &SignedArtifact) -> Outcome { + match serde_json::to_vec(artifact) { + Ok(json) => send(endpoint, PUSH_ALPN, target, &json).await, + Err(error) => Outcome::Refused(format!("artifact does not encode: {error}")), + } +} + +async fn receive_pushed(hub: &H, body: &[u8]) -> Reply { + let artifact: SignedArtifact = match serde_json::from_slice(body) { + Ok(artifact) => artifact, + Err(error) => { + return Reply::Refused { + message: format!("not an artifact: {error}"), + }; + } + }; + match hub.receive_artifact(artifact).await { + Ok(Availability::Busy) => Reply::Retry { + message: "the server is busy; try again".to_owned(), + }, + Ok(Availability::Available(Some(Stored::New))) => Reply::Applied, + Ok(Availability::Available(Some(Stored::Duplicate))) => Reply::Duplicate, + Ok(Availability::Available(None)) => Reply::Retry { + message: "artifact was not stored".to_owned(), + }, + Err(error) if error.downcast_ref::().is_some() => Reply::Refused { + message: format!("{error:#}"), + }, + Err(error) => Reply::Retry { + message: format!("{error:#}"), + }, + } +} + +/// Fetch one page of `account`'s artifacts after `after` from the home server at `peer`. +/// The dial and the answer share one [`DIAL_TIMEOUT`]. +/// +/// # Errors +/// +/// Fails if the deadline passes, the peer is unreachable, does not speak +/// [`PULL_ALPN`], or answers with something other than a page. +pub async fn fetch_page( + endpoint: &Endpoint, + peer: EndpointAddr, + account: &str, + after: u64, +) -> Result> { + fetch_page_within(endpoint, peer, account, after, DIAL_TIMEOUT).await +} + +/// [`fetch_page`] with its own deadline, which covers the address lookup, the +/// dial and the answer. +/// +/// # Errors +/// +/// As [`fetch_page`], and fails if `limit` passes first. +pub async fn fetch_page_within( + endpoint: &Endpoint, + peer: EndpointAddr, + account: &str, + after: u64, + limit: Duration, +) -> Result> { + check_key(account)?; + within(limit, "pulling artifacts from the home server", async { + let connection = connect(endpoint, peer, PULL_ALPN) + .await + .context("connecting to the home server")?; + let (mut send, mut recv) = connection + .open_bi() + .await + .context("opening a pull stream")?; + let request = PullRequest { + account: account.to_owned(), + after, + }; + write_frame(&mut send, &serde_json::to_vec(&request)?).await?; + send.finish().context("finishing the pull request")?; + let frame = read_frame(&mut recv) + .await? + .context("home server closed without a page")?; + let page: Page = serde_json::from_slice(&frame).context("artifact page is malformed")?; + ensure!( + within_budget(&page.artifacts), + "artifact page is over its byte budget" + ); + connection.close(0_u32.into(), b"pulled"); + Ok(page.artifacts) + }) + .await +} + +/// Pull `account`'s new artifacts from the home server at `peer`, page by page, +/// applying each page to `directory` as it arrives. Stops at the first refusal, +/// an empty page, or a page that stores nothing. +/// +/// A page is cut by bytes, so a short page does not mean the chain has ended. +/// The pull asks again after every page that stored something, which costs one +/// empty answer at the end. Each page fetch has [`DIAL_TIMEOUT`]. +/// +/// # Errors +/// +/// Fails if a page cannot be fetched. +pub async fn pull( + endpoint: &Endpoint, + peer: EndpointAddr, + account: &str, + directory: &mut D, +) -> Result { + pull_within(endpoint, peer, account, directory, DIAL_TIMEOUT).await +} + +/// [`pull`] with `limit` on each page fetch, see [`fetch_page_within`]. +/// +/// # Errors +/// +/// Fails if a page cannot be fetched within `limit`. +pub async fn pull_within( + endpoint: &Endpoint, + peer: EndpointAddr, + account: &str, + directory: &mut D, + limit: Duration, +) -> Result { + check_key(account)?; + let mut total = PageOutcome::default(); + loop { + let after = directory.artifact_head_seq(account); + let page = fetch_page_within(endpoint, peer.clone(), account, after, limit).await?; + let outcome = apply_page(directory, account, &page); + total.stored += outcome.stored; + total.duplicates += outcome.duplicates; + if outcome.refused.is_some() { + total.refused = outcome.refused; + break; + } + if page.is_empty() || outcome.stored == 0 { + break; + } + } + Ok(total) +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +mod tests { + use super::*; + use serde_json::json; + use std::net::{Ipv4Addr, SocketAddr}; + use std::time::Instant; + use tempfile::TempDir; + + use id_core::connectivity::silent::{ + endpoint_with_silent_lookup, unanswered_addr, unanswered_id, + }; + use iroh::{ + TransportAddr, + endpoint::{RelayMode, presets}, + protocol::Router, + }; + use iroh_base::SecretKey; + use proptest::prelude::*; + fn key(seed: u8) -> SigningKey { + SigningKey::from_bytes(&[seed; 32]) + } + #[test] + fn read_only_artifact_open_ignores_a_torn_non_utf8_tail_without_writing() { + let dir = TempDir::new().unwrap(); + let path = dir.path().join(FILE); + std::fs::write(&path, [0xff, 0xfe]).unwrap(); + let before = std::fs::read(&path).unwrap(); + let log = ArtifactLog::open_read_only(&path).unwrap(); + assert_eq!(log.all().count(), 0); + assert_eq!(std::fs::read(&path).unwrap(), before); + } + fn public(seed: u8) -> String { + hex_encode(&key(seed).verifying_key().to_bytes()) + } + fn removal(a: u8, b: u8, requests: &[&str]) -> Kind { + Kind::FriendRemove(FriendRemove { + a: public(a), + b: public(b), + requests: requests + .iter() + .map(|request| format!("{:0>32}", request.trim_start_matches('r'))) + .collect(), + }) + } + fn endpoint_of(seed: u8) -> String { + SecretKey::from_bytes(&[seed; 32]).public().to_string() + } + fn declared(seed: u8, home: u8) -> Kind { + Kind::HomeDeclared(HomeDeclared { + account: public(seed), + servers: vec![HomeServer { + endpoint: endpoint_of(home), + world_id: "home".to_owned(), + }], + }) + } + fn document(text: &str) -> Kind { + Kind::Document(Document { + media_type: "application/json".to_owned(), + content: json!({ "text": text }), + }) + } + /// Sign with full control of the `after` frontier, bypassing the + /// builder-side frontier check in [`SignedArtifact::sign_after`], so + /// receipt-side refusal of invalid frontiers stays testable. + fn sign_raw_after( + key: &SigningKey, + seq: u64, + prev: &str, + kind: &Kind, + after: Vec, + ) -> SignedArtifact { + let (name, body) = kind.encode().unwrap(); + let author = hex_encode(&key.verifying_key().to_bytes()); + let bytes = signed_bytes(&author, seq, prev, name, &body, &after).unwrap(); + SignedArtifact { + hash: hex_encode(&Sha256::digest(&bytes)), + signature: hex_encode(&key.sign(&bytes).to_bytes()), + author, + seq, + prev: prev.to_owned(), + kind: name.to_owned(), + body, + after, + } + } + /// Sign a typed kind without the construction-side body check in + /// [`SignedArtifact::sign_after`], so receipt-side refusal of that + /// body stays testable (the typed twin of [`SignedArtifact::sign_unchecked`]). + fn sign_kind_unchecked(key: &SigningKey, kind: &Kind) -> SignedArtifact { + let (name, body) = kind.encode().unwrap(); + SignedArtifact::sign_unchecked(key, 1, "", name, body).unwrap() + } + fn author_tag(subject: &str, author: u8) -> Kind { + Kind::Tag(Tag { + subject: subject.to_owned(), + name: "author".to_owned(), + value: Some(public(author)), + }) + } + #[test] + fn a_replayed_artifact_is_a_duplicate_and_a_gap_names_what_is_missing() { + let mut log = ArtifactLog::default(); + let first = log.sign(&key(1), &removal(1, 2, &["r1"])).unwrap(); + assert_eq!(first.seq, 1); + assert_eq!(log.insert(first.clone()).unwrap(), Stored::New); + assert_eq!(log.insert(first).unwrap(), Stored::Duplicate); + assert_eq!(log.head_seq(&public(1)), 1); + + let second = log.sign(&key(1), &removal(1, 3, &[])).unwrap(); + let third = SignedArtifact::sign( + &key(1), + 3, + &second.hash, + FRIEND_REMOVE, + json!({"a": public(1), "b": public(3), "requests": []}), + ) + .unwrap(); + let gap = log.insert(third).unwrap_err(); + assert!( + matches!(gap.downcast_ref::(), Some(Refusal::Conflict(m)) if m.contains("artifact 2 is missing")), + "{gap:#}" + ); + assert_eq!(log.head_seq(&public(1)), 1); + } + #[test] + fn a_fork_at_a_held_sequence_number_is_refused() { + let mut log = ArtifactLog::default(); + let held = log.sign(&key(1), &removal(1, 2, &["r1"])).unwrap(); + log.insert(held).unwrap(); + let other = SignedArtifact::sign( + &key(1), + 1, + "", + FRIEND_REMOVE, + json!({ + "a": public(1), + "b": public(2), + "requests": [format!("{:032x}", 2)] + }), + ) + .unwrap(); + let fork = log.insert(other).unwrap_err(); + assert!( + matches!(fork.downcast_ref::(), Some(Refusal::Conflict(_))), + "{fork:#}" + ); + } + #[test] + fn a_forged_or_tampered_artifact_is_refused_and_changes_nothing() { + let mut log = ArtifactLog::default(); + let good = log.sign(&key(1), &removal(1, 2, &["r1"])).unwrap(); + log.insert(good.clone()).unwrap(); + let before = log.clone(); + + let mut tampered = SignedArtifact::sign( + &key(1), + 2, + &good.hash, + FRIEND_REMOVE, + json!({"a": public(1), "b": public(2), "requests": []}), + ) + .unwrap(); + tampered.body = json!({ + "a": public(1), + "b": public(2), + "requests": [format!("{:032x}", 9)] + }); + let error = log.insert(tampered).unwrap_err(); + assert!( + matches!( + error.downcast_ref::(), + Some(Refusal::Unauthenticated(_)) + ), + "{error:#}" + ); + + let mut forged = SignedArtifact::sign_unchecked( + &key(3), + 2, + &good.hash, + FRIEND_REMOVE, + json!({"a": public(1), "b": public(2), "requests": []}), + ) + .unwrap(); + forged.author = public(1); + let error = log.insert(forged).unwrap_err(); + assert!( + matches!( + error.downcast_ref::(), + Some(Refusal::Unauthenticated(_)) + ), + "{error:#}" + ); + assert_eq!(log, before); + } + #[test] + fn a_removal_must_be_signed_by_one_of_its_accounts() { + let mut log = ArtifactLog::default(); + let stranger = SignedArtifact::sign_unchecked( + &key(3), + 1, + "", + FRIEND_REMOVE, + json!({"a": public(1), "b": public(2), "requests": []}), + ) + .unwrap(); + let error = log.insert(stranger).unwrap_err(); + assert!( + matches!(error.downcast_ref::(), Some(Refusal::Forbidden(_))), + "{error:#}" + ); + } + #[test] + fn friend_removal_refuses_too_many_or_malformed_request_ids_before_storage() { + let valid_id = |n: u8| format!("{n:032x}"); + let valid_three = SignedArtifact::sign( + &key(1), + 1, + "", + FRIEND_REMOVE, + json!({ + "a": public(1), + "b": public(2), + "requests": [valid_id(1), valid_id(2), valid_id(3)] + }), + ) + .unwrap(); + assert!(matches!( + valid_three.parsed(), + Ok(Some(Kind::FriendRemove(_))) + )); + + let cases = [ + vec![valid_id(1), valid_id(2), valid_id(3), valid_id(4)], + vec![valid_id(1), valid_id(1)], + vec!["g".repeat(32)], + vec!["a".repeat(31)], + vec!["a".repeat(33)], + vec!["A".repeat(32)], + ]; + + for requests in cases { + let artifact = SignedArtifact::sign_unchecked( + &key(1), + 1, + "", + FRIEND_REMOVE, + json!({"a": public(1), "b": public(2), "requests": requests}), + ) + .unwrap(); + let parsed = artifact.parsed().unwrap_err(); + assert!( + matches!( + parsed.downcast_ref::(), + Some(Refusal::Forbidden(_)) + ), + "{parsed:#}" + ); + + let mut log = ArtifactLog::default(); + let inserted = log.insert(artifact).unwrap_err(); + assert!( + matches!( + inserted.downcast_ref::(), + Some(Refusal::Forbidden(_)) + ), + "{inserted:#}" + ); + assert_eq!(log.head_seq(&public(1)), 0); + } + } + #[test] + fn a_legacy_removal_naming_a_request_twice_still_replays() { + // Stored before the uniqueness rule (#3146): fresh receipt refuses + // it, but replay does not brick the log that already holds it. + let dir = TempDir::new().unwrap(); + let path = dir.path().join(FILE); + let legacy = SignedArtifact::sign_unchecked( + &key(1), + 1, + "", + FRIEND_REMOVE, + json!({ + "a": public(1), + "b": public(2), + "requests": [format!("{:032x}", 7), format!("{:032x}", 7)] + }), + ) + .unwrap(); + assert!(legacy.parsed().is_err()); + assert!(ArtifactLog::default().insert(legacy.clone()).is_err()); + append(&path, &legacy).unwrap(); + + let reopened = ArtifactLog::open(&path).unwrap(); + assert_eq!(reopened.head_seq(&public(1)), 1); + } + #[test] + fn a_legacy_log_with_a_duplicate_after_frontier_still_replays() { + // #5625: stored before the duplicate-after rule (#3196), when + // sign_after accepted a repeated frontier hash. Fresh receipt + // (verify / insert) still refuses it; trusted local replay + // (open / open_read_only) reopens the log that already holds it. + let dir = TempDir::new().unwrap(); + let path = dir.path().join(FILE); + let mut log = ArtifactLog::default(); + let first = log.sign(&key(1), &document("first")).unwrap(); + log.insert(first.clone()).unwrap(); + let legacy = sign_raw_after( + &key(1), + 2, + &first.hash, + &document("second"), + vec![first.hash.clone(), first.hash.clone()], + ); + assert!(legacy.verify().is_err()); + assert!(ArtifactLog::default().insert(legacy.clone()).is_err()); + append(&path, &first).unwrap(); + append(&path, &legacy).unwrap(); + + let reopened = ArtifactLog::open(&path).unwrap(); + assert_eq!(reopened.head_seq(&public(1)), 2); + let read_only = ArtifactLog::open_read_only(&path).unwrap(); + assert_eq!(read_only.head_seq(&public(1)), 2); + + // Authenticity stays strict in replay: the same log with a + // forged hash line does not reopen. + let mut forged = legacy.clone(); + forged.hash = format!("{:064x}", 9_u64); + let bad_path = dir.path().join("forged.jsonl"); + append(&bad_path, &first).unwrap(); + append(&bad_path, &forged).unwrap(); + assert!(ArtifactLog::open(&bad_path).is_err()); + assert!(ArtifactLog::open_read_only(&bad_path).is_err()); + } + #[test] + fn a_legacy_log_with_non_nfc_document_and_tag_fields_still_replays() { + // #5625: stored before the NFC rules (#3192), when the producer + // path passed media_type / tag text through the then-lenient + // parser. Fresh receipt still refuses each shape; replay + // grandfathers exactly those three fields. + let dir = TempDir::new().unwrap(); + let cases: Vec = vec![ + Kind::Document(Document { + media_type: "application/jso\u{301}n".to_owned(), + content: json!({ "text": "ok" }), + }), + Kind::Tag(Tag { + subject: public(2), + name: "e\u{301}".to_owned(), + value: None, + }), + Kind::Tag(Tag { + subject: public(2), + name: "author".to_owned(), + value: Some("e\u{301}".to_owned()), + }), + ]; + for (index, kind) in cases.into_iter().enumerate() { + let legacy = sign_kind_unchecked(&key(1), &kind); + assert!(legacy.parsed().is_err(), "case {index}"); + assert!( + ArtifactLog::default().insert(legacy.clone()).is_err(), + "case {index}" + ); + assert!( + matches!(legacy.parsed_for_replay(), Ok(Some(_))), + "case {index}" + ); + let path = dir.path().join(format!("legacy-{index}.jsonl")); + append(&path, &legacy).unwrap(); + let reopened = ArtifactLog::open(&path).unwrap(); + assert_eq!(reopened.head_seq(&public(1)), 1, "case {index}"); + let read_only = ArtifactLog::open_read_only(&path).unwrap(); + assert_eq!(read_only.head_seq(&public(1)), 1, "case {index}"); + } + } + #[test] + fn signing_a_known_kind_refuses_the_bodies_receipt_refuses() { + // Construction-vs-receipt symmetry (#5623), with `parsed` on a + // raw-signed copy as the oracle: for every known kind, a body + // receipt refuses is refused at signing time with the same + // Refusal::Forbidden class, and a body receipt accepts still signs. + let valid_id = |n: u8| format!("{n:032x}"); + let refused: Vec<(&str, serde_json::Value)> = vec![ + // A removal signed by an account that is not one of its two. + ( + FRIEND_REMOVE, + json!({"a": public(1), "b": public(2), "requests": []}), + ), + // A document with no media type. + ( + DOCUMENT, + json!({"media_type": "", "content": {"text": "x"}}), + ), + // A tag whose subject is not a hash. + ( + TAG, + json!({"subject": "not a hash", "name": "author", "value": null}), + ), + ]; + // The friend_remove case must be signed by the stranger, key(3). + let stranger_error = + SignedArtifact::sign(&key(3), 1, "", refused[0].0, refused[0].1.clone()).unwrap_err(); + assert!( + matches!( + stranger_error.downcast_ref::(), + Some(Refusal::Forbidden(_)) + ), + "{stranger_error:#}" + ); + for (kind, body) in &refused[1..] { + let error = SignedArtifact::sign(&key(1), 1, "", kind, body.clone()).unwrap_err(); + assert!( + matches!(error.downcast_ref::(), Some(Refusal::Forbidden(_))), + "{kind}: {error:#}" + ); + let raw = SignedArtifact::sign_unchecked(&key(1), 1, "", kind, body.clone()).unwrap(); + assert!(raw.parsed().is_err(), "{kind} body accepted by parsed"); + } + // Too many friend-removal requests, signed by a party to the removal. + let too_many = SignedArtifact::sign( + &key(1), + 1, + "", + FRIEND_REMOVE, + json!({ + "a": public(1), + "b": public(2), + "requests": [valid_id(1), valid_id(2), valid_id(3), valid_id(4)] + }), + ) + .unwrap_err(); + assert!( + matches!( + too_many.downcast_ref::(), + Some(Refusal::Forbidden(_)) + ), + "{too_many:#}" + ); + // A home declaration naming another account. + let other_account = SignedArtifact::sign( + &key(2), + 1, + "", + HOME_DECLARED, + json!({"account": public(1), "servers": []}), + ) + .unwrap_err(); + assert!( + matches!( + other_account.downcast_ref::(), + Some(Refusal::Forbidden(_)) + ), + "{other_account:#}" + ); + // The accepted side of the symmetry: valid bodies of every known + // kind still sign, and an unknown kind stays signable envelope-only. + for (kind, body) in [ + ( + FRIEND_REMOVE, + json!({"a": public(1), "b": public(2), "requests": [valid_id(1)]}), + ), + (HOME_DECLARED, json!({"account": public(1), "servers": []})), + ( + DOCUMENT, + json!({"media_type": "application/json", "content": {"text": "x"}}), + ), + ( + TAG, + json!({"subject": public(2), "name": "author", "value": null}), + ), + ] { + let signed = SignedArtifact::sign(&key(1), 1, "", kind, body).unwrap(); + assert!( + matches!(signed.parsed(), Ok(Some(_))), + "{kind} valid body refused" + ); + } + let future = + SignedArtifact::sign(&key(1), 1, "", "future_kind", json!({"anything": true})).unwrap(); + assert_eq!(future.parsed().unwrap(), None); + } + #[test] + fn an_unknown_kind_is_stored_and_has_no_meaning_here() { + let mut log = ArtifactLog::default(); + let future = + SignedArtifact::sign(&key(1), 1, "", "future_kind", json!({"anything": [1, 2]})) + .unwrap(); + assert_eq!(log.insert(future.clone()).unwrap(), Stored::New); + assert_eq!(future.parsed().unwrap(), None); + assert_eq!(log.head_seq(&public(1)), 1); + } + #[test] + fn a_home_declaration_is_checked_and_the_latest_one_wins() { + let mut log = ArtifactLog::default(); + let first = log.sign(&key(1), &declared(1, 7)).unwrap(); + log.insert(first.clone()).unwrap(); + let second = log.sign(&key(1), &declared(1, 8)).unwrap(); + log.insert(second).unwrap(); + assert_eq!( + log.declared(&public(1)).unwrap().servers[0].endpoint, + endpoint_of(8) + ); + assert_eq!(log.insert(first).unwrap(), Stored::Duplicate); + assert_eq!( + log.declared(&public(1)).unwrap().servers[0].endpoint, + endpoint_of(8) + ); + + let plain = SignedArtifact::sign_unchecked( + &key(1), + 3, + &log.page(&public(1), 0)[1].hash, + HOME_DECLARED, + json!({"account": public(1), "servers": [{"endpoint": "not a node", "world_id": "w"}]}), + ) + .unwrap(); + let refused = log.insert(plain).unwrap_err(); + assert!( + matches!( + refused.downcast_ref::(), + Some(Refusal::Forbidden(_)) + ), + "{refused:#}" + ); + let other_account = SignedArtifact::sign_unchecked( + &key(2), + 1, + "", + HOME_DECLARED, + json!({"account": public(1), "servers": []}), + ) + .unwrap(); + assert!(log.insert(other_account).is_err()); + } + #[test] + fn artifacts_survive_a_restart_and_a_torn_tail_is_dropped() { + let dir = TempDir::new().unwrap(); + let path = dir.path().join(FILE); + let mut log = ArtifactLog::default(); + let first = log.sign(&key(1), &removal(1, 2, &["r1"])).unwrap(); + log.insert(first.clone()).unwrap(); + append(&path, &first).unwrap(); + let second = log.sign(&key(1), &declared(1, 7)).unwrap(); + log.insert(second.clone()).unwrap(); + append(&path, &second).unwrap(); + let complete = fs::read(&path).unwrap(); + let mut torn = complete.clone(); + torn.extend_from_slice(b"{\"name\":\"Jos"); + torn.push(0xc3); // First byte of "é". + fs::write(&path, torn).unwrap(); + + let mut reopened = ArtifactLog::open(&path).unwrap(); + assert_eq!(reopened, log); + assert_eq!(fs::read(&path).unwrap(), complete); + assert_eq!(reopened.head_seq(&public(1)), 2); + let third = reopened.sign(&key(1), &declared(1, 9)).unwrap(); + reopened.insert(third.clone()).unwrap(); + append(&path, &third).unwrap(); + assert_eq!(ArtifactLog::open(&path).unwrap(), reopened); + } + #[test] + fn blank_lines_in_the_journal_are_skipped() { + // #2128: a blank line must not brick the open - Directory::replay + // skips them in its own journal. Middle (incl. whitespace-only), + // trailing, and blank-only states all open with artifacts intact. + let dir = TempDir::new().unwrap(); + let path = dir.path().join(FILE); + let mut log = ArtifactLog::default(); + let first = log.sign(&key(1), &removal(1, 2, &["r1"])).unwrap(); + log.insert(first.clone()).unwrap(); + append(&path, &first).unwrap(); + let second = log.sign(&key(1), &declared(1, 7)).unwrap(); + log.insert(second.clone()).unwrap(); + append(&path, &second).unwrap(); + + let text = fs::read_to_string(&path).unwrap(); + let first_nl = text.find('\n').unwrap(); + let mut mangled = text.clone(); + mangled.insert_str(first_nl + 1, "\n \n"); + mangled.push('\n'); + fs::write(&path, mangled).unwrap(); + assert_eq!(ArtifactLog::open(&path).unwrap(), log); + + let blank_only = dir.path().join("blank.artifacts"); + fs::write(&blank_only, "\n\n").unwrap(); + assert_eq!( + ArtifactLog::open(&blank_only).unwrap(), + ArtifactLog::default() + ); + } + #[test] + fn a_corrupt_line_after_a_blank_line_reports_its_physical_line() { + // #2128: skipping blanks must not renumber - the corrupt line is + // physically line 3 and the refusal must say so. + let dir = TempDir::new().unwrap(); + let path = dir.path().join(FILE); + let mut log = ArtifactLog::default(); + let first = log.sign(&key(1), &removal(1, 2, &["r1"])).unwrap(); + log.insert(first.clone()).unwrap(); + append(&path, &first).unwrap(); + let mut text = fs::read_to_string(&path).unwrap(); + text.push_str("\nnot json\n"); + fs::write(&path, text).unwrap(); + + let refused = ArtifactLog::open(&path).unwrap_err(); + assert!( + format!("{refused:#}").contains("artifact line 3 is corrupt"), + "{refused:#}" + ); + } + /// The bytes a page takes on the wire, as the server sends it. + fn wire_len(page: &[SignedArtifact]) -> usize { + serde_json::to_vec(&Page { + artifacts: page.to_vec(), + }) + .unwrap() + .len() + } + /// Pages through `author`'s chain from the start, checking each page as it comes. + fn every_page(log: &ArtifactLog, author: &str) -> Vec> { + let total = log.head_seq(author); + let mut pages = Vec::new(); + let mut after = 0; + while after < total { + let page = log.page(author, after); + assert!(!page.is_empty(), "no progress after sequence {after}"); + assert!( + fills_the_budget(log, author, &page), + "a page of {} artifacts leaves room for the next", + page.len() + ); + after = page.last().unwrap().seq; + pages.push(page); + } + pages + } + /// Whether `page` is as full as the budget allows: the artifact after its last + /// one would not fit in it. A page cut short by a count, not by bytes, fails. + fn fills_the_budget(log: &ArtifactLog, author: &str, page: &[SignedArtifact]) -> bool { + let Some(last) = page.last() else { + return true; + }; + let Some(next) = log.page(author, last.seq).into_iter().next() else { + return true; + }; + let mut bigger = page.to_vec(); + bigger.push(next); + wire_len(&bigger) > PAGE_BYTES + } + #[test] + fn a_page_is_in_order_and_within_the_byte_budget() { + let mut log = ArtifactLog::default(); + for _ in 0..12 { + let next = log + .sign(&key(1), &document(&"x".repeat(MAX_DOCUMENT_BYTES - 32))) + .unwrap(); + log.insert(next).unwrap(); + } + let first = log.page(&public(1), 0); + assert_eq!(first[0].seq, 1); + assert!(first.len() > 1 && first.len() < 12, "{}", first.len()); + assert!(wire_len(&first) <= PAGE_BYTES, "{}", wire_len(&first)); + + let pages = every_page(&log, &public(1)); + assert!(pages.len() >= 3, "12 documents of 64 KiB take three pages"); + let seqs: Vec = pages.iter().flatten().map(|a| a.seq).collect(); + assert_eq!(seqs, (1..=12).collect::>()); + } + #[test] + fn a_lone_oversized_artifact_is_a_page_of_its_own() { + let mut log = ArtifactLog::default(); + let big = SignedArtifact::sign( + &key(1), + 1, + "", + "future_kind", + json!({"blob": "x".repeat(PAGE_BYTES * 2)}), + ) + .unwrap(); + log.insert(big).unwrap(); + for _ in 0..3 { + let next = log.sign(&key(1), &document("small")).unwrap(); + log.insert(next).unwrap(); + } + let first = log.page(&public(1), 0); + assert_eq!(first.len(), 1, "the oversized artifact goes alone"); + assert!(wire_len(&first) > PAGE_BYTES); + let pages = every_page(&log, &public(1)); + assert_eq!(pages.len(), 2, "then the three small ones together"); + assert_eq!( + pages[1].iter().map(|a| a.seq).collect::>(), + [2, 3, 4] + ); + } + /// An artifact whose JSON is `bytes` long. Its kind is unknown, so no parser + /// limits its size, and its body is padding. + fn unknown_kind_of_size(bytes: usize) -> SignedArtifact { + let signed = |pad: usize| { + SignedArtifact::sign( + &key(1), + 1, + "", + "future_kind", + json!({ "pad": "x".repeat(pad) }), + ) + .unwrap() + }; + let base = serde_json::to_vec(&signed(0)).unwrap().len(); + signed(bytes.saturating_sub(base)) + } + /// An artifact is stored exactly when one page can carry it in a frame. A + /// pull then never meets an artifact that the server cannot send. + #[test] + fn an_artifact_is_stored_exactly_when_one_frame_can_carry_it() { + let mut wrong = Vec::new(); + for slack in [0_usize, 1, 15, 16, 17, 40, 4096] { + let artifact = unknown_kind_of_size(MAX_FRAME_BYTES - slack); + let fits = wire_len(std::slice::from_ref(&artifact)) <= MAX_FRAME_BYTES; + let stored = ArtifactLog::default().insert(artifact).is_ok(); + if stored != fits { + wrong.push(format!( + "{slack} bytes under the cap: stored {stored}, fits {fits}" + )); + } + } + assert!(wrong.is_empty(), "{}", wrong.join("\n")); + } + /// A log file written before the frame check can hold an artifact that one + /// frame cannot carry. Opening the file must keep it: the directory loads its + /// log at start-up, so refusing the line would stop the server from starting. + #[test] + fn a_stored_artifact_too_large_for_one_frame_still_opens() { + for bytes in [MAX_FRAME_BYTES - 5, MAX_FRAME_BYTES + 1024] { + let dir = TempDir::new().unwrap(); + let path = dir.path().join(FILE); + let line = serde_json::to_string(&unknown_kind_of_size(bytes)).unwrap(); + fs::write(&path, format!("{line}\n")).unwrap(); + let log = ArtifactLog::open(&path) + .unwrap_or_else(|error| panic!("a {bytes}-byte line: {error:#}")); + assert_eq!(log.head_seq(&public(1)), 1, "a {bytes}-byte line"); + } + } + + proptest! { + #![proptest_config(ProptestConfig::with_cases(24))] + + /// Random record sizes, mostly small with some near the limit: every page + /// fits the byte budget unless it holds one artifact, and paging returns + /// each artifact exactly once, in order. Debug-mode hashing is slow, so the + /// sizes skew small to keep the case count useful. + #[test] + fn pages_fit_the_budget_and_neither_lose_nor_repeat_an_artifact( + sizes in proptest::collection::vec( + prop_oneof![ + 3 => 0..4096_usize, + 1 => 0..(MAX_DOCUMENT_BYTES - 32), + ], + 1..40, + ), + ) { + let mut log = ArtifactLog::default(); + for size in &sizes { + let next = log.sign(&key(1), &document(&"x".repeat(*size))).unwrap(); + log.insert(next).unwrap(); + } + let total = sizes.len() as u64; + let mut after = 0; + let mut paged = Vec::new(); + while after < total { + let page = log.page(&public(1), after); + prop_assert!(!page.is_empty(), "no progress after sequence {after}"); + prop_assert!( + page.len() == 1 || wire_len(&page) <= PAGE_BYTES, + "a page of {} artifacts takes {} bytes", + page.len(), + wire_len(&page) + ); + prop_assert!( + fills_the_budget(&log, &public(1), &page), + "a page of {} artifacts leaves room for the next", + page.len() + ); + after = page.last().map_or(after, |last| last.seq); + paged.extend(page); + } + prop_assert_eq!( + paged.iter().map(|a| a.seq).collect::>(), + (1..=total).collect::>() + ); + } + } + async fn endpoint() -> Endpoint { + Endpoint::builder(presets::Minimal) + .relay_mode(RelayMode::Disabled) + .bind() + .await + .unwrap() + } + fn loopback(endpoint: &Endpoint) -> EndpointAddr { + EndpointAddr::from_parts( + endpoint.id(), + endpoint.bound_sockets().iter().map(|a| { + let ip = if a.ip().is_unspecified() { + Ipv4Addr::LOCALHOST.into() + } else { + a.ip() + }; + TransportAddr::Ip(SocketAddr::new(ip, a.port())) + }), + ) + } + #[test] + fn causal_references_are_signed_and_bounded() { + let mut log = ArtifactLog::default(); + let first = log.sign(&key(1), &document("first")).unwrap(); + log.insert(first.clone()).unwrap(); + let second = log + .sign_after(&key(1), &document("second"), vec![first.hash.clone()]) + .unwrap(); + assert_eq!(second.after, vec![first.hash.clone()]); + log.insert(second.clone()).unwrap(); + + let second_hash = second.hash.clone(); + let mut stripped = second; + stripped.after.clear(); + let error = ArtifactLog::default().insert(stripped).unwrap_err(); + assert!( + matches!( + error.downcast_ref::(), + Some(Refusal::Unauthenticated(_)) + ), + "{error:#}" + ); + + let malformed = sign_raw_after( + &key(1), + 3, + &second_hash, + &document("third"), + vec!["not a hash".to_owned()], + ); + assert!(log.insert(malformed).is_err()); + let crowded = sign_raw_after( + &key(1), + 3, + &second_hash, + &document("fourth"), + vec![first.hash; MAX_AFTER + 1], + ); + assert!(log.insert(crowded).is_err()); + assert_eq!(log.head_seq(&public(1)), 2); + } + #[test] + fn test_duplicate_after_hashes_are_refused() { + let mut log = ArtifactLog::default(); + let first = log.sign(&key(1), &document("first")).unwrap(); + log.insert(first.clone()).unwrap(); + + let doubled = sign_raw_after( + &key(1), + 2, + &first.hash, + &document("second"), + vec![first.hash.clone(), first.hash.clone()], + ); + // A validly signed duplicate frontier is a policy refusal, not an + // authenticity failure (#3196). + let refused = doubled.verify().unwrap_err(); + assert!( + matches!( + refused.downcast_ref::(), + Some(Refusal::Forbidden(_)) + ), + "{refused:#}" + ); + assert!(log.insert(doubled).is_err()); + + // The builder refuses the same frontier before receipt sees it. + assert!( + log.sign_after( + &key(1), + &document("second"), + vec![first.hash.clone(), first.hash.clone()], + ) + .is_err() + ); + + let repeated = sign_raw_after( + &key(1), + 2, + &first.hash, + &document("third"), + vec![first.hash.clone(); MAX_AFTER], + ); + assert!(repeated.verify().is_err()); + assert!(log.insert(repeated).is_err()); + assert_eq!(log.head_seq(&public(1)), 1); + + let distinct: Vec = (0..MAX_AFTER).map(|i| format!("{i:064x}")).collect(); + let frontier = log + .sign_after(&key(1), &document("fourth"), distinct) + .unwrap(); + assert!(frontier.verify().is_ok()); + assert_eq!(log.insert(frontier).unwrap(), Stored::New); + } + fn home_declared_with(servers: Vec) -> SignedArtifact { + sign_kind_unchecked( + &key(1), + &Kind::HomeDeclared(HomeDeclared { + account: public(1), + servers, + }), + ) + } + fn home_server(endpoint: String, world_id: &str) -> HomeServer { + HomeServer { + endpoint, + world_id: world_id.to_owned(), + } + } + #[test] + fn parsed_home_world_id_is_bounded_and_clean() { + let control = home_declared_with(vec![home_server(endpoint_of(7), "home")]); + assert!(matches!(control.parsed(), Ok(Some(Kind::HomeDeclared(_))))); + + let at_bound = home_declared_with(vec![home_server(endpoint_of(7), &"w".repeat(64))]); + assert!(matches!(at_bound.parsed(), Ok(Some(Kind::HomeDeclared(_))))); + + for world_id in [ + "w".repeat(65), + " ".to_owned(), + "home\nFORGED".to_owned(), + "ho\u{1}me".to_owned(), + "home\u{202e}".to_owned(), + ] { + let refused = home_declared_with(vec![home_server(endpoint_of(7), &world_id)]); + assert!(refused.parsed().is_err(), "world_id {world_id:?} accepted"); + } + } + #[test] + fn parsed_home_declaration_refuses_duplicate_endpoints() { + let distinct = home_declared_with(vec![ + home_server(endpoint_of(7), "home"), + home_server(endpoint_of(8), "lobby"), + ]); + assert!(matches!(distinct.parsed(), Ok(Some(Kind::HomeDeclared(_))))); + + let duplicate = home_declared_with(vec![ + home_server(endpoint_of(7), "home"), + home_server(endpoint_of(7), "lobby"), + ]); + assert!(duplicate.parsed().is_err()); + + // The same node named once by bare ID and once by an endpoint + // ticket for that ID is still a duplicate. + let ticket = iroh_tickets::endpoint::EndpointTicket::new(EndpointAddr::from( + SecretKey::from_bytes(&[7; 32]).public(), + )) + .to_string(); + let aliased = home_declared_with(vec![ + home_server(endpoint_of(7), "home"), + home_server(ticket, "lobby"), + ]); + assert!(aliased.parsed().is_err()); + } + #[test] + fn a_legacy_home_declaration_still_replays() { + // A declaration accepted before the #3187 bounds (here: a world ID + // past MAX_WORLD_ID_BYTES) must not brick reopening its log: replay + // is lenient, while a fresh receipt of the same artifact is refused. + let dir = TempDir::new().unwrap(); + let path = dir.path().join(FILE); + let legacy = home_declared_with(vec![home_server(endpoint_of(7), &"w".repeat(65))]); + assert!(legacy.parsed().is_err()); + assert!(ArtifactLog::default().insert(legacy.clone()).is_err()); + append(&path, &legacy).unwrap(); + + let reopened = ArtifactLog::open(&path).unwrap(); + assert_eq!( + reopened.declared(&public(1)).unwrap().servers[0].world_id, + "w".repeat(65) + ); + } + #[test] + fn parsed_document_media_type_must_be_nfc() { + let nfc = ArtifactLog::default() + .sign( + &key(1), + &Kind::Document(Document { + media_type: "application/json".to_owned(), + content: json!({ "text": "ok" }), + }), + ) + .unwrap(); + assert!(matches!(nfc.parsed(), Ok(Some(Kind::Document(_))))); + + let decomposed = sign_kind_unchecked( + &key(1), + &Kind::Document(Document { + media_type: "application/jso\u{301}n".to_owned(), + content: json!({ "text": "ok" }), + }), + ); + assert!(decomposed.parsed().is_err()); + } + #[test] + fn parsed_tag_name_must_be_nfc() { + let control = ArtifactLog::default() + .sign(&key(1), &author_tag(&public(2), 1)) + .unwrap(); + assert!(matches!(control.parsed(), Ok(Some(Kind::Tag(_))))); + + let decomposed = sign_kind_unchecked( + &key(1), + &Kind::Tag(Tag { + subject: public(2), + name: "e\u{301}".to_owned(), + value: None, + }), + ); + assert!(decomposed.parsed().is_err()); + } + #[test] + fn parsed_tag_value_must_be_nfc() { + let control = ArtifactLog::default() + .sign(&key(1), &author_tag(&public(2), 1)) + .unwrap(); + assert!(matches!(control.parsed(), Ok(Some(Kind::Tag(_))))); + + let decomposed = sign_kind_unchecked( + &key(1), + &Kind::Tag(Tag { + subject: public(2), + name: "author".to_owned(), + value: Some("e\u{301}".to_owned()), + }), + ); + assert!(decomposed.parsed().is_err()); + } + /// A home server that answers every pull with `0` as one page, whatever the budget. + #[derive(Debug)] + struct OverfullPage(Vec); + impl ProtocolHandler for OverfullPage { + async fn accept(&self, conn: Connection) -> Result<(), AcceptError> { + let (mut send, mut recv) = conn.accept_bi().await?; + let _request = read_frame(&mut recv).await.map_err(refused)?; + let bytes = serde_json::to_vec(&Page { + artifacts: self.0.clone(), + }) + .map_err(|error| refused(error.into()))?; + write_frame(&mut send, &bytes).await.map_err(refused)?; + send.finish()?; + conn.closed().await; + Ok(()) + } + } + /// What a pull of `public(1)` gets from a server that sends `artifacts` as one page. + async fn pulled_from_overfull(artifacts: Vec) -> Result> { + let server = endpoint().await; + let _router = Router::builder(server.clone()) + .accept(PULL_ALPN, OverfullPage(artifacts)) + .spawn(); + let client = endpoint().await; + fetch_page(&client, loopback(&server), &public(1), 0).await + } + /// The client checks the budget of each page it is sent. A page of several + /// artifacts over the budget is refused, and one oversized artifact alone is not. + #[tokio::test] + async fn a_page_over_the_byte_budget_is_refused_and_a_lone_oversized_artifact_is_not() { + let mut log = ArtifactLog::default(); + let mut documents = Vec::new(); + for _ in 0..5 { + let next = log + .sign(&key(1), &document(&"x".repeat(MAX_DOCUMENT_BYTES - 32))) + .unwrap(); + log.insert(next.clone()).unwrap(); + documents.push(next); + } + let error = pulled_from_overfull(documents).await.unwrap_err(); + assert!( + format!("{error:#}").contains("over its byte budget"), + "{error:#}" + ); + + let lone = unknown_kind_of_size(PAGE_BYTES + 1024); + let pulled = pulled_from_overfull(vec![lone]).await.unwrap(); + assert_eq!(pulled.len(), 1); + } + /// A pull to an address nothing answers must end at its deadline, not wait out + /// the handshake. + #[tokio::test] + async fn a_pull_from_an_unanswered_address_ends_at_its_deadline() { + let client = endpoint().await; + let mut directory = LogSink::default(); + let started = Instant::now(); + let error = pull_within( + &client, + unanswered_addr(), + &public(1), + &mut directory, + Duration::from_millis(500), + ) + .await + .unwrap_err(); + assert!( + started.elapsed() < Duration::from_secs(5), + "{:?}", + started.elapsed() + ); + assert!(format!("{error:#}").contains("timed out"), "{error:#}"); + } + /// A pull by node ID whose address lookup never answers must end at its deadline. + #[tokio::test] + async fn a_pull_whose_lookup_never_answers_ends_at_its_deadline() { + let client = endpoint_with_silent_lookup().await; + let mut directory = LogSink::default(); + let started = Instant::now(); + let error = pull_within( + &client, + unanswered_id(), + &public(1), + &mut directory, + Duration::from_millis(500), + ) + .await + .unwrap_err(); + assert!( + started.elapsed() < Duration::from_secs(5), + "{:?}", + started.elapsed() + ); + assert!(format!("{error:#}").contains("timed out"), "{error:#}"); + } + /// An [`ArtifactSink`] over a bare log, for the pull tests that run + /// without a directory. + #[derive(Default)] + struct LogSink(ArtifactLog); + + impl ArtifactSink for LogSink { + fn receive_artifact(&mut self, artifact: &SignedArtifact) -> Result { + self.0.insert(artifact.clone()) + } + + fn artifact_head_seq(&self, account: &str) -> u64 { + self.0.head_seq(account) + } + } +} diff --git a/pkgs/id/crates/id-sync/src/envelope.rs b/pkgs/id/crates/id-sync/src/envelope.rs new file mode 100644 index 0000000000..022f43e5aa --- /dev/null +++ b/pkgs/id/crates/id-sync/src/envelope.rs @@ -0,0 +1,122 @@ +//! Friend envelopes: a request or acceptance, signed by its sender's +//! account key (moved out of the facade's `directory` module in step 3c of +//! the crate split, #4406). The directory's acceptance policy (time-to-live, +//! pending-request caps) stays with the directory; this is the wire type +//! and its signature. + +use anyhow::{Context, Result}; +use ed25519_dalek::{Signature, Signer as _, SigningKey, VerifyingKey}; +use rand::RngExt as _; +use serde::{Deserialize, Serialize}; + +use crate::hex::{hex_encode, hex_to_array}; + +/// What a friend envelope says. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum EnvelopeKind { + /// A request to become friends. + FriendRequest, + /// Acceptance of a request. + FriendAccept, +} + +/// A friend request or acceptance, signed by its sender's account key. Anyone +/// holding it can check the signature without asking the server. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Envelope { + /// What the envelope says. + pub kind: EnvelopeKind, + /// The sender's account ID. + pub from: String, + /// The recipient's account ID. + pub to: String, + /// The world ID of the server the envelope is for. + pub audience: String, + /// A random ID unique to this envelope. A request's ID names the request. + pub id: String, + /// For an acceptance, the ID of the request it accepts. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub request: Option, + /// When it was made, in Unix milliseconds. + pub at: u64, + /// Hex Ed25519 signature over the canonical body. + pub signature: String, +} + +/// The canonical envelope body the signature covers. +#[derive(Serialize)] +pub struct SignedBody<'a> { + kind: EnvelopeKind, + from: &'a str, + to: &'a str, + audience: &'a str, + id: &'a str, + request: Option<&'a str>, + at: u64, +} + +impl Envelope { + pub fn body(&self) -> SignedBody<'_> { + SignedBody { + kind: self.kind, + from: &self.from, + to: &self.to, + audience: &self.audience, + id: &self.id, + request: self.request.as_deref(), + at: self.at, + } + } + + /// Sign an envelope with `key`, giving it a fresh random ID. + /// + /// # Errors + /// + /// Fails if the canonical body does not encode. + pub fn signed( + key: &SigningKey, + kind: EnvelopeKind, + from: &str, + to: &str, + audience: &str, + request: Option<&str>, + at: u64, + ) -> Result { + let mut nonce = [0_u8; 16]; + rand::rng().fill(&mut nonce); + let mut envelope = Self { + kind, + from: from.to_owned(), + to: to.to_owned(), + audience: audience.to_owned(), + id: hex_encode(&nonce), + request: request.map(str::to_owned), + at, + signature: String::new(), + }; + let signature = key.sign(&serde_json::to_vec(&envelope.body())?); + envelope.signature = hex_encode(&signature.to_bytes()); + Ok(envelope) + } + + /// Check the signature against the sender's account key. + /// + /// # Errors + /// + /// Fails if the sender is not a key, the signature is malformed, or it + /// does not match the body. + pub fn verify(&self) -> Result<()> { + let key = VerifyingKey::from_bytes( + &hex_to_array::<32>(&self.from).context("malformed envelope sender")?, + ) + .context("envelope sender is not a key")?; + let signature = Signature::from_bytes( + &hex_to_array::<64>(&self.signature).context("malformed envelope signature")?, + ); + let body = serde_json::to_vec(&self.body())?; + key.verify_strict(&body, &signature) + .context("envelope signature does not verify") + } +} + diff --git a/pkgs/id/crates/id-sync/src/envelope_net.rs b/pkgs/id/crates/id-sync/src/envelope_net.rs new file mode 100644 index 0000000000..1f7071276c --- /dev/null +++ b/pkgs/id/crates/id-sync/src/envelope_net.rs @@ -0,0 +1,545 @@ +//! Iroh transport for friend envelopes (`/id-envelope/1`) and signed artifacts +//! (`/id-artifact-push/1`). +//! +//! One bidirectional stream carries one payload: the sender writes a frame +//! holding the payload's JSON, and the receiver answers with a frame holding a +//! [`Reply`]. The payload's signature is what makes it trusted, not the iroh +//! node that delivered it. + +use std::time::Duration; + +use anyhow::{Context, Result}; +use iroh::{ + Endpoint, EndpointAddr, + endpoint::Connection, + protocol::{AcceptError, ProtocolHandler}, +}; +use serde::{Deserialize, Serialize}; + +use id_core::connectivity::connect; +use id_core::Refusal; + +use crate::envelope::Envelope; +use crate::host::{Availability, EnvelopeReceived, SessionHost}; +use crate::envelope_outbox::Outcome; +use id_core::frames::{read_frame, write_frame}; + +/// ALPN for friend envelopes. Within version 1 fields may be added; removing or +/// changing one needs `/id-envelope/2`. +pub const ENVELOPE_ALPN: &[u8] = b"/id-envelope/1"; + +const TIMEOUT: Duration = Duration::from_secs(30); + +/// The answer to one frame. `Refused` will never succeed; `Retry` may. +#[derive(Debug, Serialize, Deserialize)] +#[serde(tag = "status", rename_all = "snake_case")] +pub enum Reply { + /// The frame was applied. + Applied, + /// The frame was already applied. + Duplicate, + /// The frame is invalid and must not be sent again. + Refused { + /// Why it was refused. + message: String, + }, + /// The frame could not be applied now but may be later. + Retry { + /// Why it could not be applied now. + message: String, + }, +} + +/// Sends `envelope` to the node at `target`, and says whether it is done. +pub async fn deliver( + endpoint: &Endpoint, + target: impl Into, + envelope: &Envelope, +) -> Outcome { + let json = match serde_json::to_vec(envelope) { + Ok(json) => json, + Err(error) => return Outcome::Refused(format!("envelope does not encode: {error}")), + }; + send(endpoint, ENVELOPE_ALPN, target.into(), &json).await +} + +/// Sends one frame on `alpn` to `target`, and says whether the peer took it. +/// The whole delivery, address lookup included, must finish within [`TIMEOUT`]. +pub async fn send(endpoint: &Endpoint, alpn: &[u8], target: EndpointAddr, json: &[u8]) -> Outcome { + send_within(endpoint, alpn, target, json, TIMEOUT).await +} + +/// [`send`] with `limit` on the whole delivery. +pub async fn send_within( + endpoint: &Endpoint, + alpn: &[u8], + target: EndpointAddr, + json: &[u8], + limit: Duration, +) -> Outcome { + match tokio::time::timeout(limit, exchange(endpoint, alpn, target, json)).await { + Ok(Ok(Reply::Applied | Reply::Duplicate)) => Outcome::Delivered, + Ok(Ok(Reply::Refused { message })) => Outcome::Refused(message), + Ok(Ok(Reply::Retry { message })) => Outcome::Retry(message), + Ok(Err(error)) => Outcome::Retry(format!("{error:#}")), + Err(_) => Outcome::Retry("delivery timed out".to_owned()), + } +} + +async fn exchange( + endpoint: &Endpoint, + alpn: &[u8], + target: EndpointAddr, + json: &[u8], +) -> Result { + let conn = connect(endpoint, target, alpn) + .await + .context("connecting to the recipient's server")?; + let reply = async { + let (mut send, mut recv) = conn.open_bi().await.context("opening a stream")?; + write_frame(&mut send, json).await?; + send.finish().context("finishing the request")?; + let frame = read_frame(&mut recv).await?.context("no reply")?; + serde_json::from_slice::(&frame).context("malformed reply") + } + .await; + conn.close(0_u32.into(), b"done"); + reply +} + +/// Accepts friend envelopes over Iroh. Register with +/// `Router::builder(..).accept(ENVELOPE_ALPN, EnvelopeProtocol::new(hub))`. +#[derive(Clone, Debug)] +pub struct EnvelopeProtocol { + hub: H, +} + +impl EnvelopeProtocol { + /// Serve the friend envelopes of every world in `hub`. + #[must_use] + pub const fn new(hub: H) -> Self { + Self { hub } + } +} + +impl ProtocolHandler for EnvelopeProtocol { + async fn accept(&self, conn: Connection) -> Result<(), AcceptError> { + let hub = self.hub.clone(); + answer_frames(&conn, move |body| { + let hub = hub.clone(); + async move { receive(&hub, &body).await } + }) + .await + } +} + +/// Answers frames sequentially on `conn` with the [`Reply`] `receive` gives it. +/// Each stream is bounded by [`TIMEOUT`]; a timed-out stream is reset and the +/// accept loop advances to the next stream. +pub async fn answer_frames(conn: &Connection, receive: F) -> Result<(), AcceptError> +where + F: Fn(Vec) -> Fut, + Fut: Future + Send, +{ + answer_frames_within(conn, receive, TIMEOUT).await +} + +async fn answer_frames_within( + conn: &Connection, + receive: F, + deadline: Duration, +) -> Result<(), AcceptError> +where + F: Fn(Vec) -> Fut, + Fut: Future + Send, +{ + while let Ok((mut send, mut recv)) = conn.accept_bi().await { + let timed_out = tokio::time::timeout(deadline, async { + let reply = match read_frame(&mut recv).await { + Ok(Some(body)) => receive(body).await, + Ok(None) => return, + Err(error) => Reply::Refused { + message: format!("{error:#}"), + }, + }; + let Ok(json) = serde_json::to_vec(&reply) else { + return; + }; + if write_frame(&mut send, &json).await.is_ok() { + let _ = send.finish(); + } + }) + .await + .is_err(); + if timed_out { + // `read_frame` is not cancel-safe. Abandon both halves rather + // than attempting to reuse a partially consumed stream. + let _ = send.reset(0_u32.into()); + let _ = recv.stop(0_u32.into()); + } + } + Ok(()) +} + +async fn receive(hub: &H, body: &[u8]) -> Reply { + let envelope: Envelope = match serde_json::from_slice(body) { + Ok(envelope) => envelope, + Err(error) => { + return Reply::Refused { + message: format!("not an envelope: {error}"), + }; + } + }; + match hub.receive_envelope(envelope).await { + Ok(Availability::Busy) => Reply::Retry { + message: "the server is busy; try again".to_owned(), + }, + Ok(Availability::Available(Some(EnvelopeReceived::Applied))) => Reply::Applied, + Ok(Availability::Available(Some(EnvelopeReceived::Duplicate))) => Reply::Duplicate, + Ok(Availability::Available(None)) => Reply::Retry { + message: "envelope was not received".to_owned(), + }, + Err(error) if error.downcast_ref::().is_some() => Reply::Refused { + message: format!("{error:#}"), + }, + Err(error) => Reply::Retry { + message: format!("{error:#}"), + }, + } +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +mod tests { + use std::sync::Arc; + use std::time::Instant; + + use ed25519_dalek::SigningKey; + use iroh::{ + address_lookup::MemoryLookup, + endpoint::{RelayMode, presets}, + protocol::Router, + }; + use iroh_blobs::{ + BlobFormat, Hash, api::blobs::AddBytesOptions, store::mem::MemStore, + }; + use tokio::sync::Mutex; + + use super::*; + use id_core::connectivity::silent::{ + endpoint_with_silent_lookup, unanswered_addr, unanswered_id, + }; + + use crate::envelope::EnvelopeKind; + const NOW: u64 = 1_000_000_000; + async fn endpoint() -> Endpoint { + Endpoint::builder(presets::Minimal) + .relay_mode(RelayMode::Disabled) + .bind() + .await + .unwrap() + } + async fn endpoint_with(lookup: &MemoryLookup) -> Endpoint { + Endpoint::builder(presets::Minimal) + .relay_mode(RelayMode::Disabled) + .address_lookup(lookup.clone()) + .bind() + .await + .unwrap() + } + fn loopback_addr(ep: &Endpoint) -> EndpointAddr { + EndpointAddr::from_parts( + ep.id(), + ep.bound_sockets().iter().map(|addr| { + let ip = if addr.ip().is_unspecified() { + std::net::Ipv4Addr::LOCALHOST.into() + } else { + addr.ip() + }; + iroh::TransportAddr::Ip(std::net::SocketAddr::new(ip, addr.port())) + }), + ) + } + /// Test-only receiver for exercising the raw frame transport. This is not + /// the production [`EnvelopeProtocol`], which accepts directory envelopes + /// and deliberately refuses chat-frame JSON. + #[derive(Clone, Debug)] + struct CaptureFrames(Arc>>>); + impl ProtocolHandler for CaptureFrames { + async fn accept(&self, conn: Connection) -> Result<(), AcceptError> { + let frames = self.0.clone(); + answer_frames(&conn, move |body| { + let frames = frames.clone(); + async move { + frames.lock().await.push(body); + Reply::Applied + } + }) + .await + } + } + #[derive(Clone, Debug)] + struct DeadlineCaptureFrames { + frames: Arc>>>, + deadline: Duration, + } + impl ProtocolHandler for DeadlineCaptureFrames { + async fn accept(&self, conn: Connection) -> Result<(), AcceptError> { + let frames = self.frames.clone(); + answer_frames_within( + &conn, + move |body| { + let frames = frames.clone(); + async move { + frames.lock().await.push(body); + Reply::Applied + } + }, + self.deadline, + ) + .await + } + } + /// A throwaway transport fixture for the proposed chat frame. It proves + /// byte-preserving exchange on the existing ALPN and a local content-hash + /// hit; it does not test CLI routing, production envelope acceptance, or + /// chat signature verification. + #[tokio::test] + async fn test_review_gated_chat_frame_round_trips_and_resolves_local_blob() { + let alice = endpoint().await; + let bob = endpoint().await; + let alice_frames = Arc::new(Mutex::new(Vec::new())); + let bob_frames = Arc::new(Mutex::new(Vec::new())); + let alice_router = Router::builder(alice.clone()) + .accept(ENVELOPE_ALPN, CaptureFrames(alice_frames.clone())) + .spawn(); + let bob_router = Router::builder(bob.clone()) + .accept(ENVELOPE_ALPN, CaptureFrames(bob_frames.clone())) + .spawn(); + + let receiver_store: iroh_blobs::api::Store = MemStore::new().into(); + let blob_bytes = b"review-gated chat PoC local blob"; + let _keep = receiver_store + .add_bytes_with_opts(AddBytesOptions { + data: blob_bytes.to_vec().into(), + format: BlobFormat::Raw, + }) + .temp_tag() + .await + .unwrap(); + let blob_hash = _keep.hash(); + + let frame_alice_to_bob = serde_json::to_vec(&serde_json::json!({ + "v": 1, + "channel": "group:local-poc", + "author": alice.id().to_string(), + "seq": 1, + "after": [], + "text": "blob link fixture", + "links": [{ + "kind": "blob", + "hash": blob_hash.to_string(), + "author": alice.id().to_string() + }], + "sig": "test-only; no signature verification" + })) + .unwrap(); + let frame_bob_to_alice = serde_json::to_vec(&serde_json::json!({ + "v": 1, + "channel": "group:local-poc", + "author": bob.id().to_string(), + "seq": 1, + "after": [], + "text": "acknowledged", + "links": [], + "sig": "test-only; no signature verification" + })) + .unwrap(); + + println!( + "Alice -> Bob /id-envelope/1 frame bytes (UTF-8): {}", + String::from_utf8(frame_alice_to_bob.clone()).unwrap() + ); + println!( + "Bob -> Alice /id-envelope/1 frame bytes (UTF-8): {}", + String::from_utf8(frame_bob_to_alice.clone()).unwrap() + ); + + assert_eq!( + send_within( + &alice, + ENVELOPE_ALPN, + loopback_addr(&bob), + &frame_alice_to_bob, + Duration::from_secs(5), + ) + .await, + Outcome::Delivered + ); + assert_eq!( + send_within( + &bob, + ENVELOPE_ALPN, + loopback_addr(&alice), + &frame_bob_to_alice, + Duration::from_secs(5), + ) + .await, + Outcome::Delivered + ); + + assert_eq!( + bob_frames.lock().await.as_slice(), + &[frame_alice_to_bob.clone()] + ); + assert_eq!( + alice_frames.lock().await.as_slice(), + &[frame_bob_to_alice.clone()] + ); + + let received_alice_to_bob = bob_frames.lock().await[0].clone(); + let received_frame: serde_json::Value = + serde_json::from_slice(&received_alice_to_bob).unwrap(); + let linked_hash: Hash = received_frame["links"][0]["hash"] + .as_str() + .unwrap() + .parse() + .unwrap(); + assert_eq!(linked_hash, blob_hash); + assert!(receiver_store.blobs().has(linked_hash).await.unwrap()); + let resolved = receiver_store.blobs().get_bytes(linked_hash).await.unwrap(); + assert_eq!(&*resolved, blob_bytes); + assert_eq!(Hash::new(&*resolved), blob_hash); + println!( + "Bob local blob resolution: hash={blob_hash} bytes={} hash_verified=true", + resolved.len() + ); + + alice.close().await; + bob.close().await; + alice_router.shutdown().await.unwrap(); + bob_router.shutdown().await.unwrap(); + } + #[tokio::test] + async fn an_unreachable_recipient_is_retried() { + let client = endpoint().await; + let gone = endpoint().await; + let gone_id = gone.id(); + gone.close().await; + let envelope = test_envelope(); + assert!(matches!( + deliver(&client, gone_id, &envelope).await, + Outcome::Retry(_) + )); + } + #[tokio::test] + async fn a_partial_frame_times_out_before_the_next_stream_is_answered() { + let server = endpoint().await; + let client = endpoint().await; + let frames = Arc::new(Mutex::new(Vec::new())); + let router = Router::builder(server.clone()) + .accept( + ENVELOPE_ALPN, + DeadlineCaptureFrames { + frames: frames.clone(), + deadline: Duration::from_millis(100), + }, + ) + .spawn(); + let conn = connect(&client, loopback_addr(&server), ENVELOPE_ALPN) + .await + .unwrap(); + + let (mut first_send, mut first_recv) = conn.open_bi().await.unwrap(); + first_send.write_all(&[0, 0]).await.unwrap(); + + let (mut second_send, mut second_recv) = conn.open_bi().await.unwrap(); + write_frame(&mut second_send, b"valid second frame") + .await + .unwrap(); + second_send.finish().unwrap(); + + let second_reply = tokio::time::timeout(Duration::from_secs(2), async { + let frame = read_frame(&mut second_recv).await.unwrap().unwrap(); + serde_json::from_slice::(&frame).unwrap() + }) + .await + .expect("second stream should be answered after the first times out"); + assert!(matches!(second_reply, Reply::Applied)); + assert_eq!( + frames.lock().await.as_slice(), + &[b"valid second frame".to_vec()] + ); + + let first_reply = + tokio::time::timeout(Duration::from_secs(1), first_recv.read_to_end(16)).await; + assert!( + matches!(first_reply, Ok(Err(_))), + "first stream should be reset" + ); + + drop(first_send); + conn.close(0_u32.into(), b"done"); + client.close().await; + server.close().await; + router.shutdown().await.unwrap(); + } + /// A delivery to an address nothing answers must give up at its deadline. + #[tokio::test] + async fn a_delivery_to_an_unanswered_address_gives_up_at_its_deadline() { + let client = endpoint().await; + let started = Instant::now(); + let outcome = send_within( + &client, + ENVELOPE_ALPN, + unanswered_addr(), + b"{}", + Duration::from_millis(500), + ) + .await; + assert!( + started.elapsed() < Duration::from_secs(5), + "{:?}", + started.elapsed() + ); + assert_eq!(outcome, Outcome::Retry("delivery timed out".to_owned())); + } + /// A delivery by node ID whose address lookup never answers gives up at its + /// deadline. The lookup is inside the deadline, so this is the step that hung. + #[tokio::test] + async fn a_delivery_whose_lookup_never_answers_gives_up_at_its_deadline() { + let client = endpoint_with_silent_lookup().await; + let started = Instant::now(); + let outcome = send_within( + &client, + ENVELOPE_ALPN, + unanswered_id(), + b"{}", + Duration::from_millis(500), + ) + .await; + assert!( + started.elapsed() < Duration::from_secs(5), + "{:?}", + started.elapsed() + ); + assert_eq!(outcome, Outcome::Retry("delivery timed out".to_owned())); + } + /// A signed envelope from a throwaway account, for the delivery tests + /// that never reach a server which would check it. + fn test_envelope() -> Envelope { + let key = SigningKey::from_bytes(&[7_u8; 32]); + Envelope::signed( + &key, + EnvelopeKind::FriendRequest, + &crate::hex::hex_encode(&key.verifying_key().to_bytes()), + &"ab".repeat(32), + "lobby", + None, + NOW, + ) + .unwrap() + } +} diff --git a/pkgs/id/crates/id-sync/src/envelope_outbox.rs b/pkgs/id/crates/id-sync/src/envelope_outbox.rs new file mode 100644 index 0000000000..596908f85b --- /dev/null +++ b/pkgs/id/crates/id-sync/src/envelope_outbox.rs @@ -0,0 +1,1150 @@ +//! A durable queue of what this server sends to other servers: friend envelopes +//! and signed artifacts, each to a target endpoint. +//! +//! Each change is one JSON line, synced before it counts. The file is replayed +//! on open, so an entry that was not finished survives a restart. A line cut +//! short by a crash was never acknowledged, so it is dropped on open. + +use std::collections::{BTreeMap, VecDeque}; +#[cfg(unix)] +use std::fs::File; +use std::fs::{self, OpenOptions}; +use std::io::{self, Write}; +use std::path::{Path, PathBuf}; + +use anyhow::{Context, Result, anyhow, ensure}; +use serde::{Deserialize, Serialize}; +use tokio::sync::Mutex; + +use iroh::{Endpoint, EndpointAddr, EndpointId}; +use iroh_tickets::endpoint::EndpointTicket; + +use crate::artifact::{self, SignedArtifact}; +use crate::envelope::Envelope; +use crate::envelope_net::deliver; + +/// Deliveries attempted before an envelope is given up. +pub const MAX_ATTEMPTS: u32 = 12; +/// The maximum number of newest finished entries retained by the outbox. +pub const MAX_FINISHED_ENTRIES: usize = 100; +const BASE_DELAY_MS: u64 = 60_000; +const MAX_DELAY_MS: u64 = 6 * 60 * 60 * 1000; + +/// How a queued envelope ended. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Finish { + /// The recipient's server accepted it. + Delivered, + /// The recipient's server refused it, so it is not retried. + Refused, + /// Every attempt failed. + GaveUp, +} + +/// The result of one delivery attempt. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Outcome { + /// The envelope was delivered or was already applied there. + Delivered, + /// The envelope will not be accepted, and retrying cannot change that. + Refused(String), + /// The attempt failed in a way a later attempt may fix. + Retry(String), +} + +/// What the outbox carries to another server. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Payload { + /// A friend envelope, for the recipient's server. + Envelope(Envelope), + /// A signed artifact, for a home server that holds the account's chain. + Artifact(SignedArtifact), +} + +impl Payload { + /// The key the queue files this payload under, so one payload is queued once. + #[must_use] + pub fn key(&self, target: &str) -> String { + match self { + Self::Envelope(envelope) => envelope.id.clone(), + Self::Artifact(artifact) => format!("artifact {target} {}", artifact.hash), + } + } +} + +/// One queued payload and what has happened to it so far. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Entry { + /// The recipient: an endpoint ticket or a bare node ID. + pub target: String, + /// What to deliver. + pub payload: Payload, + /// Attempts made so far. + pub attempts: u32, + /// The earliest time the next attempt may run, in Unix milliseconds. + pub next_at: u64, + /// The reason for the last failed attempt or the final outcome. + pub last_error: Option, + /// Set once the payload is no longer queued. + pub finish: Option, +} + +#[derive(Serialize, Deserialize)] +#[serde(tag = "op", rename_all = "snake_case")] +enum Record { + Queued { + target: String, + envelope: Envelope, + }, + QueuedArtifact { + target: String, + artifact: SignedArtifact, + }, + Attempted { + id: String, + attempts: u32, + next_at: u64, + error: String, + }, + Finished { + id: String, + attempts: u32, + outcome: Finish, + detail: Option, + }, + Withdrawn { + id: String, + }, +} + +/// The queue, keyed by envelope ID. +/// +/// It retains the newest [`MAX_FINISHED_ENTRIES`] finished entries by finish +/// order, along with every unfinished entry. When replay drops older finished +/// entries, the journal is compacted on open. +#[derive(Debug)] +pub struct Outbox { + path: PathBuf, + entries: BTreeMap, + finished_order: VecDeque, +} + +impl Outbox { + /// Opens the queue at `path`, replaying every record already in it. + /// + /// # Errors + /// + /// Fails if the file cannot be read, a complete line is corrupt, or a + /// journal record violates the outbox state machine. + pub fn open(path: impl Into) -> Result { + let mut outbox = Self { + path: path.into(), + entries: BTreeMap::new(), + finished_order: VecDeque::new(), + }; + let bytes = match fs::read(&outbox.path) { + Ok(bytes) => bytes, + Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(outbox), + Err(error) => return Err(error).context("reading the envelope outbox"), + }; + let mut kept = 0; + let mut dropped_finished = false; + for (number, line) in bytes.split_inclusive(|byte| *byte == b'\n').enumerate() { + if !line.ends_with(b"\n") { + // The final line has no newline: a crash cut the append + // short. Parseable or not, it was never completely + // written, so it is torn and dropped — the same rule + // ArtifactLog::open and Directory::replay apply. Keeping + // a parseable torn line would let the next append merge + // two records onto one line and brick the queue (#1620). + // `kept` stays at the last complete line, so the file is + // truncated to it below. + break; + } + let text = std::str::from_utf8(line) + .with_context(|| format!("envelope outbox line {} is corrupt", number + 1))?; + if text.trim().is_empty() { + // Blank lines carry no records, but they are complete bytes in + // the journal and must remain before any later torn tail. + kept += line.len(); + continue; + } + match serde_json::from_str::(text.trim_end()) { + Ok(record) => { + dropped_finished |= outbox.apply(record).with_context(|| { + format!("envelope outbox line {} is refused", number + 1) + })?; + kept += line.len(); + } + Err(error) => { + return Err(error).with_context(|| { + format!("envelope outbox line {} is corrupt", number + 1) + }); + } + } + } + if kept < bytes.len() { + OpenOptions::new() + .write(true) + .open(&outbox.path)? + .set_len(kept as u64)?; + } + if dropped_finished { + outbox.compact_journal()?; + } + Ok(outbox) + } + + /// Queues `envelope` for delivery to the node `target`, due immediately. + /// + /// # Errors + /// + /// Fails if the node ID is malformed, the envelope is already queued, or the + /// record cannot be written. + pub fn enqueue(&mut self, target: &str, envelope: Envelope) -> Result<()> { + check_target(target)?; + self.enqueue_payload(&Payload::Envelope(envelope), target) + } + + /// Queues `artifact` for a home server at `target`, due immediately. + /// + /// # Errors + /// + /// Fails if the target is malformed, the artifact is already queued for it, + /// or the record cannot be written. + pub fn enqueue_artifact(&mut self, target: &str, artifact: SignedArtifact) -> Result<()> { + check_target(target)?; + self.enqueue_payload(&Payload::Artifact(artifact), target) + } + + fn enqueue_payload(&mut self, payload: &Payload, target: &str) -> Result<()> { + let key = payload.key(target); + ensure!(!self.entries.contains_key(&key), "{key} is already queued"); + let record = match payload { + Payload::Envelope(envelope) => Record::Queued { + target: target.to_owned(), + envelope: envelope.clone(), + }, + Payload::Artifact(artifact) => Record::QueuedArtifact { + target: target.to_owned(), + artifact: artifact.clone(), + }, + }; + self.commit(record) + } + + /// The IDs of envelopes that are queued and due at `now`. + #[must_use] + pub fn due(&self, now: u64) -> Vec { + self.entries + .iter() + .filter(|(_, entry)| entry.finish.is_none() && entry.next_at <= now) + .map(|(id, _)| id.clone()) + .collect() + } + + /// The queued envelope with `id`, finished or not. + #[must_use] + pub fn entry(&self, id: &str) -> Option<&Entry> { + self.entries.get(id) + } + + /// Removes an envelope that was queued but never attempted, as if it had + /// never been queued. + /// + /// # Errors + /// + /// Fails if `id` is not queued, has been attempted, or the record cannot be + /// written. + pub fn withdraw(&mut self, id: &str) -> Result<()> { + let entry = self.entries.get(id).context("envelope is not queued")?; + ensure!( + entry.attempts == 0 && entry.finish.is_none(), + "envelope {id} was already attempted" + ); + self.commit(Record::Withdrawn { id: id.to_owned() }) + } + + /// Records the outcome of an attempt made at `now`. + /// + /// # Errors + /// + /// Fails if `id` is not queued, or the record cannot be written. + pub fn record(&mut self, id: &str, now: u64, outcome: Outcome) -> Result<()> { + let entry = self.entries.get(id).context("envelope is not queued")?; + ensure!(entry.finish.is_none(), "envelope {id} already finished"); + let attempts = entry.attempts + 1; + let record = match outcome { + Outcome::Delivered => Record::Finished { + id: id.to_owned(), + attempts, + outcome: Finish::Delivered, + detail: None, + }, + Outcome::Refused(error) => Record::Finished { + id: id.to_owned(), + attempts, + outcome: Finish::Refused, + detail: Some(error), + }, + Outcome::Retry(error) if attempts >= MAX_ATTEMPTS => Record::Finished { + id: id.to_owned(), + attempts, + outcome: Finish::GaveUp, + detail: Some(error), + }, + Outcome::Retry(error) => Record::Attempted { + id: id.to_owned(), + attempts, + next_at: now.saturating_add(backoff_ms(attempts)), + error, + }, + }; + self.commit(record) + } + + /// Every queued envelope, finished or not, in ID order. + pub fn entries(&self) -> impl Iterator { + self.entries.values() + } + + fn commit(&mut self, record: Record) -> Result<()> { + let mut line = serde_json::to_string(&record)?; + line.push('\n'); + let mut file = OpenOptions::new() + .create(true) + .append(true) + .open(&self.path)?; + file.write_all(line.as_bytes())?; + file.sync_data()?; + self.apply(record)?; + Ok(()) + } + + /// Applies a record and reports whether it evicted a finished entry. + fn apply(&mut self, record: Record) -> Result { + let mut dropped_finished = false; + match record { + Record::Queued { target, envelope } => { + self.insert_queued(target, Payload::Envelope(envelope))?; + } + Record::QueuedArtifact { target, artifact } => { + self.insert_queued(target, Payload::Artifact(artifact))?; + } + Record::Attempted { + id, + attempts, + next_at, + error, + } => { + let entry = self.entry_mut(&id)?; + ensure!(entry.finish.is_none(), "envelope {id} already finished"); + let expected_attempts = entry.attempts + 1; + ensure!( + attempts == expected_attempts, + "outbox record for envelope {id} expected {expected_attempts} attempts, got {attempts}" + ); + ensure!( + attempts < MAX_ATTEMPTS, + "outbox record attempts envelope {id} at the retry limit" + ); + entry.attempts = attempts; + entry.next_at = next_at; + entry.last_error = Some(error); + } + Record::Finished { + id, + attempts, + outcome, + detail, + } => { + let entry = self.entry_mut(&id)?; + ensure!(entry.finish.is_none(), "envelope {id} already finished"); + let expected_attempts = entry.attempts + 1; + ensure!( + attempts == expected_attempts, + "outbox record for envelope {id} expected {expected_attempts} attempts, got {attempts}" + ); + ensure!( + attempts <= MAX_ATTEMPTS, + "outbox record exceeds the retry limit for envelope {id}" + ); + match outcome { + Finish::Delivered => ensure!( + detail.is_none(), + "delivered outbox record for envelope {id} has refusal detail" + ), + Finish::Refused => ensure!( + detail.is_some(), + "refused outbox record for envelope {id} is missing detail" + ), + Finish::GaveUp => { + ensure!( + attempts == MAX_ATTEMPTS, + "gave-up outbox record for envelope {id} is not at the retry limit" + ); + ensure!( + detail.is_some(), + "gave-up outbox record for envelope {id} is missing detail" + ); + } + } + entry.attempts = attempts; + entry.finish = Some(outcome); + entry.last_error = detail; + self.finished_order.retain(|finished_id| finished_id != &id); + self.finished_order.push_back(id); + if self.finished_order.len() > MAX_FINISHED_ENTRIES { + if let Some(oldest) = self.finished_order.pop_front() { + self.entries.remove(&oldest); + dropped_finished = true; + } + } + } + Record::Withdrawn { id } => { + let entry = self + .entries + .get(&id) + .with_context(|| format!("outbox record withdraws unknown envelope {id}"))?; + ensure!( + entry.attempts == 0 && entry.finish.is_none(), + "envelope {id} was already attempted" + ); + self.finished_order.retain(|finished_id| finished_id != &id); + self.entries.remove(&id); + } + } + Ok(dropped_finished) + } + + /// Rewrites the journal as a snapshot of the retained entries. + fn compact_journal(&self) -> Result<()> { + let mut temporary_path = self.path.as_os_str().to_owned(); + temporary_path.push(".compact.tmp"); + let temporary_path = PathBuf::from(temporary_path); + let permissions = fs::metadata(&self.path)?.permissions(); + let mut file = OpenOptions::new() + .create(true) + .truncate(true) + .write(true) + .open(&temporary_path) + .context("creating the compacted envelope outbox")?; + + for record in self.compact_records()? { + serde_json::to_writer(&mut file, &record)?; + file.write_all(b"\n")?; + } + fs::set_permissions(&temporary_path, permissions)?; + file.sync_all()?; + drop(file); + replace_journal(&temporary_path, &self.path) + .context("replacing the envelope outbox with its compacted journal")?; + + #[cfg(unix)] + { + let parent = self + .path + .parent() + .filter(|parent| !parent.as_os_str().is_empty()) + .unwrap_or_else(|| Path::new(".")); + File::open(parent)?.sync_all()?; + } + Ok(()) + } + + /// Builds a replayable snapshot while preserving the finish-order queue. + fn compact_records(&self) -> Result> { + // NOTE: the snapshot must satisfy the same replay validation as a + // live journal (see `apply`): every `Attempted` record increments + // the attempt count by exactly one, and a `Finished` record carries + // the count after its final attempt. A snapshot therefore replays + // an entry's attempt count incrementally (`push_attempt_history`) + // instead of jumping straight to the final count. + let mut records = Vec::with_capacity(self.entries.len() * 2); + for entry in self.entries.values() { + records.push(match &entry.payload { + Payload::Envelope(envelope) => Record::Queued { + target: entry.target.clone(), + envelope: envelope.clone(), + }, + Payload::Artifact(artifact) => Record::QueuedArtifact { + target: entry.target.clone(), + artifact: artifact.clone(), + }, + }); + } + + // Pending entries have no finish-order significance, so their retry + // state can be replayed before the finished entries. + for (id, entry) in &self.entries { + if entry.finish.is_none() + && (entry.attempts > 0 || entry.next_at != 0 || entry.last_error.is_some()) + { + push_attempt_increments(&mut records, id, entry.attempts); + if entry.attempts > 0 { + records.push(Record::Attempted { + id: id.clone(), + attempts: entry.attempts, + next_at: entry.next_at, + error: entry.last_error.clone().unwrap_or_default(), + }); + } + } + } + + for id in &self.finished_order { + let entry = self + .entries + .get(id) + .with_context(|| format!("finished entry {id} is missing during compaction"))?; + // The `Finished` record itself carries the final attempt count, + // so only the increments below it are replayed as `Attempted`. + // A finished entry's `next_at` is inert (`due` skips finished + // entries), so the increments use a placeholder. + push_attempt_increments(&mut records, id, entry.attempts); + records.push(Record::Finished { + id: id.clone(), + attempts: entry.attempts, + outcome: entry + .finish + .context("finished-order entry has no finish during compaction")?, + detail: entry.last_error.clone(), + }); + } + Ok(records) + } + + fn insert_queued(&mut self, target: String, payload: Payload) -> Result<()> { + // The live path checks the target in the enqueue verbs + // before committing; replay must hold the same line, or a journal + // record the live API could never produce loads as a due entry and + // only fails at flush time as a spurious refusal (#5635). + check_target(&target)?; + let key = payload.key(&target); + ensure!(!self.entries.contains_key(&key), "{key} is queued twice"); + self.entries.insert( + key, + Entry { + target, + payload, + attempts: 0, + next_at: 0, + last_error: None, + finish: None, + }, + ); + Ok(()) + } + + fn entry_mut(&mut self, id: &str) -> Result<&mut Entry> { + self.entries + .get_mut(id) + .with_context(|| format!("outbox record names unknown envelope {id}")) + } +} + +/// Pushes placeholder `Attempted` records for the counts `1..below`, so a +/// compacted snapshot replays an entry's attempt count one increment at a +/// time, as replay validation requires. The caller pushes the final record +/// (the real `Attempted` for a pending entry, or the `Finished` record) +/// itself; placeholders carry no retry state. +fn push_attempt_increments(records: &mut Vec, id: &str, below: u32) { + for attempts in 1..below { + records.push(Record::Attempted { + id: id.to_owned(), + attempts, + next_at: 0, + error: String::new(), + }); + } +} + +/// Replaces the journal at `destination` with the compacted file at +/// `temporary`, as atomically as the platform allows. +#[cfg(not(windows))] +fn replace_journal(temporary: &Path, destination: &Path) -> io::Result<()> { + // rename(2) replaces an existing destination atomically. + fs::rename(temporary, destination) +} + +/// Replaces the journal at `destination` with the compacted file at +/// `temporary`, as atomically as the platform allows. +#[cfg(windows)] +fn replace_journal(temporary: &Path, destination: &Path) -> io::Result<()> { + // `fs::rename` cannot replace an existing file on Windows, and the + // journal always exists by the time compaction runs, so a plain rename + // would fail every compaction there (Copilot review on PR #4710). + // Remove-then-rename is the fallback: it is NOT atomic — a crash + // between the two calls leaves the journal missing and only the + // `.compact.tmp` file behind — but compaction only runs after a full + // successful replay, and the alternative on Windows is that + // compaction (and with it `Outbox::open`) never succeeds at all. + if destination.exists() { + fs::remove_file(destination)?; + } + fs::rename(temporary, destination) +} + +/// Delivers every envelope due at `now`, recording each outcome as it happens. +/// +/// The lock is released while a delivery is in flight, so enqueueing is not +/// held up by a slow recipient. Returns how many attempts were made. +/// +/// # Errors +/// +/// Fails if an outcome cannot be written. Envelopes already recorded stay +/// recorded. +pub async fn flush(outbox: &Mutex, endpoint: &Endpoint, now: u64) -> Result { + let due: Vec<(String, String, Payload)> = { + let queue = outbox.lock().await; + queue + .due(now) + .into_iter() + .filter_map(|id| { + let entry = queue.entry(&id)?; + Some((id.clone(), entry.target.clone(), entry.payload.clone())) + }) + .collect() + }; + for (id, target, payload) in &due { + let outcome = match check_target(target) { + Ok(addr) => match payload { + Payload::Envelope(envelope) => deliver(endpoint, addr, envelope).await, + Payload::Artifact(artifact) => artifact::push(endpoint, addr, artifact).await, + }, + Err(error) => Outcome::Refused(format!("{error:#}")), + }; + outbox.lock().await.record(id, now, outcome)?; + } + Ok(due.len()) +} + +/// Reads a recipient: an endpoint ticket, or a bare node ID that resolves +/// through the discovery services the endpoint uses. +/// +/// # Errors +/// +/// Fails if `target` is neither, so nothing is queued for it. +pub fn check_target(target: &str) -> Result { + if let Ok(ticket) = target.parse::() { + return Ok(ticket.endpoint_addr().clone()); + } + target + .parse::() + .map(EndpointAddr::from) + .map_err(|error| anyhow!("{target} is neither an endpoint ticket nor a node ID: {error}")) +} + +fn backoff_ms(attempts: u32) -> u64 { + let shift = attempts.saturating_sub(1).min(20); + (BASE_DELAY_MS << shift).min(MAX_DELAY_MS) +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +mod tests { + use super::*; + use crate::envelope::EnvelopeKind; + + const NOW: u64 = 1_000_000_000; + const MINUTE: u64 = 60_000; + + fn envelope(id: &str) -> Envelope { + Envelope { + kind: EnvelopeKind::FriendRequest, + from: "ann".to_owned(), + to: "bo".to_owned(), + audience: "club".to_owned(), + id: id.to_owned(), + request: None, + at: NOW, + signature: "00".to_owned(), + } + } + + fn target() -> String { + iroh::SecretKey::from_bytes(&[7; 32]).public().to_string() + } + + fn path(dir: &tempfile::TempDir) -> PathBuf { + dir.path().join("outbox.jsonl") + } + + fn queued_line(id: &str) -> String { + let dir = tempfile::tempdir().unwrap(); + let mut outbox = Outbox::open(path(&dir)).unwrap(); + outbox.enqueue(&target(), envelope(id)).unwrap(); + fs::read_to_string(path(&dir)) + .unwrap() + .trim_end_matches('\n') + .to_owned() + } + + fn queued_record(id: &str) -> Record { + Record::Queued { + target: target(), + envelope: envelope(id), + } + } + + fn write_records(dir: &tempfile::TempDir, records: impl IntoIterator) { + let text = records + .into_iter() + .map(|record| format!("{}\n", serde_json::to_string(&record).unwrap())) + .collect::(); + fs::write(path(dir), text).unwrap(); + } + + fn assert_replay_error(records: impl IntoIterator, line: usize, reason: &str) { + let dir = tempfile::tempdir().unwrap(); + write_records(&dir, records); + let error = Outbox::open(path(&dir)) + .err() + .expect("invalid replay should fail"); + let message = format!("{error:#}"); + assert!(message.contains(&format!("line {line}")), "{message}"); + assert!(message.contains(reason), "{message}"); + } + + #[test] + fn a_target_is_a_ticket_or_a_bare_node_id() { + let id = iroh::SecretKey::from_bytes(&[7; 32]).public(); + let addr = EndpointAddr::from(id); + let ticket = EndpointTicket::new(addr.clone()).to_string(); + assert_eq!(check_target(&ticket).unwrap(), addr); + assert_eq!(check_target(&id.to_string()).unwrap(), addr); + assert!(check_target("not a target").is_err()); + } + + #[test] + fn queued_envelopes_survive_a_restart() { + let dir = tempfile::tempdir().unwrap(); + let mut outbox = Outbox::open(path(&dir)).unwrap(); + outbox.enqueue(&target(), envelope("e1")).unwrap(); + drop(outbox); + + let reopened = Outbox::open(path(&dir)).unwrap(); + assert_eq!(reopened.due(NOW), vec!["e1".to_owned()]); + assert_eq!( + reopened.entry("e1").unwrap().payload, + Payload::Envelope(envelope("e1")) + ); + } + + #[test] + fn a_retry_waits_for_its_backoff_and_then_gives_up() { + let dir = tempfile::tempdir().unwrap(); + let mut outbox = Outbox::open(path(&dir)).unwrap(); + outbox.enqueue(&target(), envelope("e1")).unwrap(); + + outbox + .record("e1", NOW, Outcome::Retry("down".to_owned())) + .unwrap(); + let entry = outbox.entry("e1").unwrap(); + assert_eq!((entry.attempts, entry.next_at), (1, NOW + MINUTE)); + assert!(outbox.due(NOW + MINUTE - 1).is_empty()); + assert_eq!(outbox.due(NOW + MINUTE), vec!["e1".to_owned()]); + + for attempt in 2..=MAX_ATTEMPTS { + outbox + .record("e1", NOW, Outcome::Retry("down".to_owned())) + .unwrap(); + assert_eq!(outbox.entry("e1").unwrap().attempts, attempt); + } + let entry = outbox.entry("e1").unwrap(); + assert_eq!(entry.finish, Some(Finish::GaveUp)); + assert!(outbox.due(u64::MAX).is_empty()); + + let reopened = Outbox::open(path(&dir)).unwrap(); + assert_eq!(reopened.entry("e1").unwrap().finish, Some(Finish::GaveUp)); + } + + #[test] + fn a_refusal_is_final() { + let dir = tempfile::tempdir().unwrap(); + let mut outbox = Outbox::open(path(&dir)).unwrap(); + outbox.enqueue(&target(), envelope("e1")).unwrap(); + outbox + .record("e1", NOW, Outcome::Refused("bad signature".to_owned())) + .unwrap(); + let entry = outbox.entry("e1").unwrap(); + assert_eq!(entry.finish, Some(Finish::Refused)); + assert_eq!(entry.last_error.as_deref(), Some("bad signature")); + assert!(outbox.due(u64::MAX).is_empty()); + assert!(outbox.record("e1", NOW, Outcome::Delivered).is_err()); + drop(outbox); + + let reopened = Outbox::open(path(&dir)).unwrap(); + assert_eq!(reopened.entry("e1").unwrap().finish, Some(Finish::Refused)); + assert_eq!( + reopened.entry("e1").unwrap().last_error.as_deref(), + Some("bad signature") + ); + } + + #[test] + fn a_delivery_survives_a_restart() { + let dir = tempfile::tempdir().unwrap(); + let mut outbox = Outbox::open(path(&dir)).unwrap(); + outbox.enqueue(&target(), envelope("e1")).unwrap(); + outbox.record("e1", NOW, Outcome::Delivered).unwrap(); + drop(outbox); + + let reopened = Outbox::open(path(&dir)).unwrap(); + assert_eq!( + reopened.entry("e1").unwrap().finish, + Some(Finish::Delivered) + ); + assert!(reopened.entry("e1").unwrap().last_error.is_none()); + } + + #[test] + fn runtime_retains_the_newest_finished_entries_in_finish_order() { + let dir = tempfile::tempdir().unwrap(); + let mut outbox = Outbox::open(path(&dir)).unwrap(); + let total = MAX_FINISHED_ENTRIES + 5; + + for index in 0..total { + let id = format!("e{index:03}"); + outbox.enqueue(&target(), envelope(&id)).unwrap(); + } + for index in (0..total).step_by(2).chain((1..total).step_by(2)) { + let id = format!("e{index:03}"); + outbox.record(&id, NOW, Outcome::Delivered).unwrap(); + } + + assert_eq!( + outbox + .entries() + .filter(|entry| entry.finish.is_some()) + .count(), + MAX_FINISHED_ENTRIES + ); + for oldest in [0, 2, 4, 6, 8] { + assert!(outbox.entry(&format!("e{oldest:03}")).is_none()); + } + assert!(outbox.entry("e001").is_some()); + assert!(outbox.entry("e104").is_some()); + + outbox.enqueue(&target(), envelope("pending")).unwrap(); + assert_eq!(outbox.entries().count(), MAX_FINISHED_ENTRIES + 1); + assert_eq!(outbox.due(NOW), vec!["pending".to_owned()]); + } + + #[test] + fn replay_compacts_finished_history_and_preserves_state_and_finish_order() { + let dir = tempfile::tempdir().unwrap(); + let journal = path(&dir); + let mut outbox = Outbox::open(&journal).unwrap(); + let total = MAX_FINISHED_ENTRIES + 5; + + for index in 0..total { + let id = format!("e{index:03}"); + outbox.enqueue(&target(), envelope(&id)).unwrap(); + } + for index in (0..total).step_by(2).chain((1..total).step_by(2)) { + let id = format!("e{index:03}"); + outbox.record(&id, NOW, Outcome::Delivered).unwrap(); + } + outbox.enqueue(&target(), envelope("pending-now")).unwrap(); + outbox + .enqueue(&target(), envelope("pending-later")) + .unwrap(); + outbox + .record("pending-later", NOW, Outcome::Retry("down".to_owned())) + .unwrap(); + + let expected_entries = outbox.entries.clone(); + let expected_due_now = outbox.due(NOW); + let expected_due_later = outbox.due(NOW + MINUTE); + drop(outbox); + + // A parseable record without its trailing newline is still a torn tail; + // open must truncate it before compacting the completed history. + let mut file = OpenOptions::new().append(true).open(&journal).unwrap(); + file.write_all(queued_line("torn").as_bytes()).unwrap(); + drop(file); + + let reopened = Outbox::open(&journal).unwrap(); + assert_eq!(reopened.entries, expected_entries); + assert_eq!(reopened.due(NOW), expected_due_now); + assert_eq!(reopened.due(NOW + MINUTE), expected_due_later); + assert!(reopened.entry("torn").is_none()); + + let compacted = fs::read_to_string(&journal).unwrap(); + assert!(compacted.ends_with('\n')); + assert!(!compacted.contains("e000")); + assert!(!compacted.contains("e002")); + assert!(compacted.contains("e001")); + assert!(compacted.contains("pending-later")); + drop(reopened); + + let mut reopened_again = Outbox::open(&journal).unwrap(); + assert_eq!(reopened_again.entries, expected_entries); + assert_eq!(reopened_again.due(NOW), expected_due_now); + assert_eq!(reopened_again.due(NOW + MINUTE), expected_due_later); + assert_eq!(fs::read_to_string(&journal).unwrap(), compacted); + + // Compaction must keep the relative finish order so the next finish + // evicts the oldest entry that survived the first cap. + reopened_again + .enqueue(&target(), envelope("next-finish")) + .unwrap(); + reopened_again + .record("next-finish", NOW, Outcome::Delivered) + .unwrap(); + assert!(reopened_again.entry("e010").is_none()); + assert!(reopened_again.entry("e001").is_some()); + } + + #[test] + fn a_withdrawn_envelope_is_gone_and_stays_gone() { + let dir = tempfile::tempdir().unwrap(); + let mut outbox = Outbox::open(path(&dir)).unwrap(); + outbox.enqueue(&target(), envelope("e1")).unwrap(); + outbox.withdraw("e1").unwrap(); + assert!(outbox.entry("e1").is_none()); + assert!(outbox.due(u64::MAX).is_empty()); + assert!(outbox.withdraw("e1").is_err()); + drop(outbox); + + let reopened = Outbox::open(path(&dir)).unwrap(); + assert!(reopened.entry("e1").is_none()); + } + + #[test] + fn test_blank_and_whitespace_lines_are_skipped_and_kept() { + let dir = tempfile::tempdir().unwrap(); + let contents = format!("{}\n\n \t\r\n{}\n\n", queued_line("e1"), queued_line("e2")); + fs::write(path(&dir), &contents).unwrap(); + + let outbox = Outbox::open(path(&dir)).unwrap(); + assert!(outbox.entry("e1").is_some()); + assert!(outbox.entry("e2").is_some()); + assert_eq!(fs::read_to_string(path(&dir)).unwrap(), contents); + } + + #[test] + fn test_blank_lines_before_a_torn_tail_are_kept_when_the_tail_is_truncated() { + let dir = tempfile::tempdir().unwrap(); + let kept = format!("{}\n \t\n", queued_line("e1")); + fs::write(path(&dir), format!("{kept}{{\"op\":\"queued\"")).unwrap(); + + let outbox = Outbox::open(path(&dir)).unwrap(); + assert!(outbox.entry("e1").is_some()); + assert_eq!(fs::read_to_string(path(&dir)).unwrap(), kept); + } + + #[test] + fn a_torn_last_line_is_dropped_and_not_mixed_into_the_next_record() { + let dir = tempfile::tempdir().unwrap(); + let mut outbox = Outbox::open(path(&dir)).unwrap(); + outbox.enqueue(&target(), envelope("e1")).unwrap(); + drop(outbox); + let mut file = OpenOptions::new().append(true).open(path(&dir)).unwrap(); + // The tail is cut after the first byte of a multibyte name. + file.write_all(b"{\"name\":\"Jos\xc3").unwrap(); + drop(file); + + let mut outbox = Outbox::open(path(&dir)).unwrap(); + assert!(outbox.entry("e1").is_some()); + outbox.enqueue(&target(), envelope("e2")).unwrap(); + drop(outbox); + + let reopened = Outbox::open(path(&dir)).unwrap(); + assert!(reopened.entry("e1").is_some() && reopened.entry("e2").is_some()); + } + + #[test] + fn a_parseable_torn_last_line_is_also_dropped() { + // #1620: the torn tail here is a complete JSON record missing + // only its trailing newline. Before the fix, open accepted it, + // and the next append merged two records onto one line. + let dir = tempfile::tempdir().unwrap(); + let mut outbox = Outbox::open(path(&dir)).unwrap(); + outbox.enqueue(&target(), envelope("e1")).unwrap(); + drop(outbox); + // A whole record line for e2, written by a healthy outbox, with + // its newline stripped to simulate the crash cut. + let scratch = tempfile::tempdir().unwrap(); + let mut other = Outbox::open(path(&scratch)).unwrap(); + other.enqueue(&target(), envelope("e2")).unwrap(); + drop(other); + let line = fs::read_to_string(path(&scratch)).unwrap(); + let mut file = OpenOptions::new().append(true).open(path(&dir)).unwrap(); + file.write_all(line.trim_end_matches('\n').as_bytes()) + .unwrap(); + drop(file); + + let mut outbox = Outbox::open(path(&dir)).unwrap(); + assert!(outbox.entry("e1").is_some()); + assert!( + outbox.entry("e2").is_none(), + "the parseable torn record must be dropped, not accepted" + ); + // The file was truncated to the last complete line, so the next + // append starts on its own line and round-trips. + outbox.enqueue(&target(), envelope("e2")).unwrap(); + drop(outbox); + + let reopened = Outbox::open(path(&dir)).unwrap(); + assert!(reopened.entry("e1").is_some() && reopened.entry("e2").is_some()); + } + + #[test] + fn a_corrupt_complete_line_stops_the_load() { + let dir = tempfile::tempdir().unwrap(); + fs::write(path(&dir), "\nnot json\n").unwrap(); + let error = Outbox::open(path(&dir)).err().unwrap(); + assert!(format!("{error:#}").contains("envelope outbox line 2 is corrupt")); + } + + #[test] + fn replay_rejects_attempt_after_finish() { + assert_replay_error( + [ + queued_record("e1"), + Record::Finished { + id: "e1".to_owned(), + attempts: 1, + outcome: Finish::Delivered, + detail: None, + }, + Record::Attempted { + id: "e1".to_owned(), + attempts: 2, + next_at: NOW + MINUTE, + error: "down".to_owned(), + }, + ], + 3, + "already finished", + ); + } + + #[test] + fn replay_rejects_a_second_finish() { + assert_replay_error( + [ + queued_record("e1"), + Record::Finished { + id: "e1".to_owned(), + attempts: 1, + outcome: Finish::Delivered, + detail: None, + }, + Record::Finished { + id: "e1".to_owned(), + attempts: 2, + outcome: Finish::Refused, + detail: Some("bad signature".to_owned()), + }, + ], + 3, + "already finished", + ); + } + + #[test] + fn replay_rejects_attempt_count_regression() { + let mut records = vec![queued_record("e1")]; + for attempts in 1..=5 { + records.push(Record::Attempted { + id: "e1".to_owned(), + attempts, + next_at: NOW + u64::from(attempts) * MINUTE, + error: "down".to_owned(), + }); + } + records.push(Record::Attempted { + id: "e1".to_owned(), + attempts: 2, + next_at: NOW + 2 * MINUTE, + error: "down".to_owned(), + }); + + assert_replay_error(records, 7, "expected 6 attempts, got 2"); + } + + #[test] + fn replay_rejects_withdrawal_after_an_attempt() { + assert_replay_error( + [ + queued_record("e1"), + Record::Attempted { + id: "e1".to_owned(), + attempts: 1, + next_at: NOW + MINUTE, + error: "down".to_owned(), + }, + Record::Withdrawn { + id: "e1".to_owned(), + }, + ], + 3, + "already attempted", + ); + } + + #[test] + fn replay_rejects_withdrawal_after_finish() { + assert_replay_error( + [ + queued_record("e1"), + Record::Finished { + id: "e1".to_owned(), + attempts: 1, + outcome: Finish::Delivered, + detail: None, + }, + Record::Withdrawn { + id: "e1".to_owned(), + }, + ], + 3, + "already attempted", + ); + } + + #[test] + fn replay_rejects_a_queued_record_with_a_malformed_target() { + assert_replay_error( + [Record::Queued { + target: "not a target".to_owned(), + envelope: envelope("e1"), + }], + 1, + "is neither an endpoint ticket nor a node ID", + ); + } + + #[test] + fn replay_rejects_a_queued_artifact_record_with_a_malformed_target() { + let artifact = SignedArtifact { + author: "00".to_owned(), + seq: 1, + prev: String::new(), + kind: "note".to_owned(), + body: serde_json::Value::Null, + after: Vec::new(), + hash: "00".to_owned(), + signature: "00".to_owned(), + }; + assert_replay_error( + [Record::QueuedArtifact { + target: "not a target".to_owned(), + artifact, + }], + 1, + "is neither an endpoint ticket nor a node ID", + ); + } + + #[test] + fn a_node_id_is_required() { + assert!(check_target(&target()).is_ok()); + assert!(check_target("https://bo.example/envelope").is_err()); + assert!(check_target("not a node").is_err()); + } +} diff --git a/pkgs/id/crates/id-sync/src/hex.rs b/pkgs/id/crates/id-sync/src/hex.rs new file mode 100644 index 0000000000..49c59207b9 --- /dev/null +++ b/pkgs/id/crates/id-sync/src/hex.rs @@ -0,0 +1,44 @@ +//! Hex and key-text helpers for the wire layer. The facade's directory +//! keeps its own copies for the code that stayed behind (step 3c, #4406); +//! these serve the envelope and artifact modules here. + +use anyhow::{Context, Result}; +use ed25519_dalek::VerifyingKey; + +/// Lower-case hex encoding of a byte slice, two characters per byte. +pub(crate) fn hex_encode(bytes: &[u8]) -> String { + const HEX: &[u8; 16] = b"0123456789abcdef"; + let mut encoded = String::with_capacity(bytes.len() * 2); + for byte in bytes { + encoded.push(char::from(HEX[usize::from(byte >> 4)])); + encoded.push(char::from(HEX[usize::from(byte & 0x0f)])); + } + encoded +} + +pub(crate) fn hex_to_array(text: &str) -> Option<[u8; N]> { + // Every byte must be an ASCII hex digit (#2517): u8::from_str_radix + // also accepts a leading '+', so without this gate a byte 0x00-0x0f + // has two accepted spellings ('0x' and '+x') and key strings stop + // being canonical. + if text.len() != N * 2 || !text.bytes().all(|b| b.is_ascii_hexdigit()) { + return None; + } + let mut out = [0_u8; N]; + for (index, byte) in out.iter_mut().enumerate() { + *byte = u8::from_str_radix(&text[index * 2..index * 2 + 2], 16).ok()?; + } + Some(out) +} + +/// A public key as lower-case hex, if it is an Ed25519 public key. +/// +/// # Errors +/// +/// Fails if the text is not 64 hex characters or not a valid key. +pub(crate) fn normalize_key(key: &str) -> Result { + let key = key.trim().to_ascii_lowercase(); + let bytes = hex_to_array::<32>(&key).context("a public key is 64 hex characters")?; + VerifyingKey::from_bytes(&bytes).context("not an Ed25519 public key")?; + Ok(key) +} diff --git a/pkgs/id/crates/id-sync/src/host.rs b/pkgs/id/crates/id-sync/src/host.rs new file mode 100644 index 0000000000..270e0dc46c --- /dev/null +++ b/pkgs/id/crates/id-sync/src/host.rs @@ -0,0 +1,59 @@ +//! The seam between the wire protocols and the world host (seam 9 of the +//! crate-split design, #4406): the host publishes whether it can take a +//! request; the transfer protocols in this crate consume that and nothing +//! else. The facade implements [`SessionHost`] for its world hub, running +//! each request as a directory action under the hub's lease; the errors it +//! returns keep the directory's `Refusal` in their chain, so the wire +//! layer's refused-vs-retry mapping is unchanged. + +use std::future::Future; + +use anyhow::Error; + +use crate::artifact::{SignedArtifact, Stored}; +use crate::envelope::Envelope; + +/// Whether the host could take a request at all. +#[derive(Debug)] +pub enum Availability { + /// The host took the request and produced this outcome. + Available(T), + /// The host is busy (its world lease is contended); trying again later + /// may succeed. + Busy, +} + +/// What receiving an envelope did, as the wire answer needs it. The +/// directory's own `Received` also carries the journal entry it appended, +/// which the wire never sees. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum EnvelopeReceived { + /// The envelope changed the directory. + Applied, + /// The envelope was already applied, so nothing changed. + Duplicate, +} + +/// The directory operations the envelope and artifact protocols need from +/// the world host. `Ok(Available(None))` means the action ran but had +/// nothing to report (the envelope or artifact was not received/stored). +pub trait SessionHost: Clone + std::fmt::Debug + Send + Sync + 'static { + /// Receive one friend envelope into the hosted world. + fn receive_envelope( + &self, + envelope: Envelope, + ) -> impl Future>, Error>> + Send; + + /// Store one pushed artifact in the hosted world. + fn receive_artifact( + &self, + artifact: SignedArtifact, + ) -> impl Future>, Error>> + Send; + + /// Read one page of `account`'s artifacts after sequence `after`. + fn read_artifacts( + &self, + account: String, + after: u64, + ) -> impl Future>, Error>> + Send; +} diff --git a/pkgs/id/crates/id-sync/src/lib.rs b/pkgs/id/crates/id-sync/src/lib.rs index 317e42b93f..248919fab3 100644 --- a/pkgs/id/crates/id-sync/src/lib.rs +++ b/pkgs/id/crates/id-sync/src/lib.rs @@ -7,14 +7,28 @@ //! [`dht`], the opt-in mainline lookup policy) and the wire half of //! [`meta_client`] (request/response plumbing over an open connection). //! +//! Step 3c added the friend-envelope and artifact transfer family: +//! [`envelope`] (the signed wire type, out of the facade's directory), +//! [`envelope_net`] and [`envelope_outbox`] (their transport and durable +//! queue) and [`artifact`] (signed artifacts and their push/pull +//! transfer). Their seam to the worlds and directory that still live in +//! the facade is [`host::SessionHost`] plus +//! [`artifact::ArtifactSink`], both implemented facade-side. +//! //! The facade re-exports each module at its historical `id::` path, so //! no call site outside the moved modules changed. Composition stays //! in the facade until step 7: the `MetaClient` enum that chooses //! between a running server and the in-process local node is defined //! there, over this crate's [`meta_client`] plumbing. +pub mod artifact; pub mod dht; +pub mod envelope; +pub mod envelope_net; +pub mod envelope_outbox; pub mod fileops; +pub(crate) mod hex; +pub mod host; pub mod log_sync; pub mod meta_client; pub mod protocol; diff --git a/pkgs/id/src/artifact.rs b/pkgs/id/src/artifact.rs index 8377b855f1..bfc32987ca 100644 --- a/pkgs/id/src/artifact.rs +++ b/pkgs/id/src/artifact.rs @@ -1,2073 +1,85 @@ -//! Signed artifacts: each account's own signed statements, kept as one -//! append-only chain per author. -//! -//! An artifact names its author's Ed25519 key, a per-author sequence number and -//! the hash of the artifact before it, and is signed by that key. Any server -//! can check one without trusting the server that sent it. [`ArtifactLog`] -//! holds only chains that verify, and takes neither a gap nor a fork. A kind -//! this server does not know is stored but never applied, so a newer peer -//! cannot break an older server. Applying a known kind is the directory's job. -//! -//! Receipt contract (#3231): a known-kind artifact is acceptable on receipt -//! only when it satisfies the same rules its in-tree builder must satisfy — -//! enforced in [`SignedArtifact::parsed`] before [`ArtifactLog`] stores or -//! replays it, and at the producer seams that build each kind. The generic -//! builders mirror receipt (#5623): [`SignedArtifact::sign`] and -//! [`SignedArtifact::sign_after`] run the same `parsed` check before -//! returning, so an in-tree caller can no longer mint a signed known-kind -//! artifact that receipt would refuse. A structural -//! rule failure is [`Refusal::Forbidden`] naming the rule; only hash and -//! signature failures are [`Refusal::Unauthenticated`]. Receipt never -//! rewrites signed bytes: duplicates and noncanonical values are refused, -//! not deduplicated or normalized. Unknown kinds keep the forward-compatible -//! rule above: envelope only, stored, never applied. A rule added after an -//! artifact was legitimately stored does not brick replay of its log — the -//! replay path (`parsed_for_replay`) carries each such grandfathered rule. -//! -//! 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. -//! -//! Generic kinds carry data rather than directory changes: a `document` holds -//! structured JSON, and a `tag` labels another artifact by its hash. An author -//! tags their own document with `name` `author` and `value` their key. -//! -//! Artifacts travel over iroh only: pushed to a home server on -//! [`PUSH_ALPN`], and pulled by account from the same endpoint on [`PULL_ALPN`]. +//! Facade re-export of the artifact wire layer (moved to `id-sync` in +//! step 3c of the crate split, #4406). The tests below stay here: they +//! run the protocols against a real `Directory` and world hub, which +//! live in the facade until steps 5-6. -use std::collections::{BTreeMap, HashSet}; -use std::fs::{self, OpenOptions}; -use std::io::{self, Write}; -use std::path::Path; -use std::time::Duration; +pub use id_sync::artifact::*; -use anyhow::{Context, Result, bail, ensure}; -use ed25519_dalek::{Signature, Signer as _, SigningKey, VerifyingKey}; -use iroh::{ - Endpoint, EndpointAddr, - endpoint::Connection, - protocol::{AcceptError, ProtocolHandler}, -}; -use serde::{Deserialize, Serialize}; -use sha2::{Digest, Sha256}; -use unicode_normalization::is_nfc; - -use crate::connectivity::{DIAL_TIMEOUT, connect, within}; -use crate::directory::{Directory, Refusal, hex_to_array, normalize_key}; -use crate::directory_auth::Caller; -use crate::directory_view::{DirectoryAction, DirectoryOutcome}; -use crate::envelope_net::{Reply, answer_frames, send}; -use crate::envelope_outbox::{Outcome, check_target}; -use crate::event_sync::{CLOSE_WAIT, SESSION_DEADLINE}; -use crate::frames::{read_frame, write_frame}; -use crate::world::hex_encode; -use crate::world_hub::WorldHub; -use crate::world_session::MAX_FRAME_BYTES; - -/// The file, beside `directory.jsonl`, that holds a world's artifacts. -pub const FILE: &str = "artifacts.jsonl"; -/// Bytes one page may take on the wire, counting its JSON framing. -/// -/// A page always carries at least one artifact, so one larger than this is sent -/// alone. The budget keeps a page of maximum-size documents far under the frame limit. -pub const PAGE_BYTES: usize = 256 * 1024; -/// Home servers one declaration may name. -pub const MAX_HOME_SERVERS: usize = 8; -/// The largest world ID one home server may carry, in bytes. -pub const MAX_WORLD_ID_BYTES: usize = 64; -/// Hashes one artifact may name in `after`. -pub const MAX_AFTER: usize = 32; -/// The largest content a document may carry, as serialized JSON. -pub const MAX_DOCUMENT_BYTES: usize = 64 * 1024; -/// The kind of a friend removal. -pub const FRIEND_REMOVE: &str = "friend_remove"; -/// Pending friendship requests a single friend removal can void. -pub const MAX_FRIEND_REMOVE_REQUESTS: usize = 3; -/// The kind of a home-server declaration. -pub const HOME_DECLARED: &str = "home_declared"; -/// The kind of a generic structured document. -pub const DOCUMENT: &str = "document"; -/// The kind of a label on another artifact. -pub const TAG: &str = "tag"; - -/// ALPN on which a server accepts pushed artifacts, one per stream. -pub const PUSH_ALPN: &[u8] = b"/id-artifact-push/1"; -/// ALPN on which a server answers pulls of an account's artifacts. -pub const PULL_ALPN: &[u8] = b"/id-artifact-pull/1"; - -/// One signed statement by an account. -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub struct SignedArtifact { - /// Hex Ed25519 public key of the account that signed it. - pub author: String, - /// One-based position in the author's chain. - pub seq: u64, - /// Hash of the author's artifact at `seq - 1`, empty for `seq` 1. - pub prev: String, - /// What the body says. An unknown kind is kept but not applied. - pub kind: String, - /// The kind-specific fields. - pub body: serde_json::Value, - /// Hashes of artifacts the author had applied before this one. - #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub after: Vec, - /// Hex SHA-256 over the signed body. - pub hash: String, - /// Hex Ed25519 signature over the signed body. - pub signature: String, -} - -#[derive(Serialize)] -struct SignedBody<'a> { - author: &'a str, - seq: u64, - prev: &'a str, - kind: &'a str, - body: &'a serde_json::Value, - #[serde(skip_serializing_if = "Vec::is_empty")] - after: Vec, -} - -fn signed_bytes( - author: &str, - seq: u64, - prev: &str, - kind: &str, - body: &serde_json::Value, - after: &[String], -) -> Result> { - Ok(serde_json::to_vec(&SignedBody { - author, - seq, - prev, - kind, - body, - after: after.to_vec(), - })?) -} - -fn is_hash(text: &str) -> bool { - text.len() == 64 - && text - .bytes() - .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)) -} - -/// The canonical friend-request ID shape: 16 bytes as 32 lowercase -/// hexadecimal characters. This is the shape the envelope producer mints -/// (`Envelope::signed` in directory.rs) and the shape the `friend_remove` -/// receipt contract (#3146) requires; directory.rs reuses this predicate -/// at friend-request admission (#5624) so the two never drift. -pub(crate) fn is_friend_request_id(text: &str) -> bool { - text.len() == 32 - && text - .bytes() - .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)) -} - -/// A friendship ends, and the request IDs it covers are void. -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub struct FriendRemove { - /// One account. - pub a: String, - /// The other account. - pub b: String, - /// At most three lowercase 32-character hex request IDs covered by this removal. - #[serde(default)] - pub requests: Vec, -} - -/// Where an account's artifacts are held: an endpoint ticket or a bare node ID. -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub struct HomeServer { - /// The Iroh endpoint that takes pushes and serves pulls of the account's artifacts. - pub endpoint: String, - /// The world the server holds the account in. - pub world_id: String, -} - -/// The servers an account publishes its artifacts to. A newer declaration replaces an older one. -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub struct HomeDeclared { - /// The declaring account. - pub account: String, - /// Where its artifacts are held. - pub servers: Vec, -} - -/// Structured data an account publishes as its own statement. -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub struct Document { - /// What the content is, such as `application/json`. - pub media_type: String, - /// The content itself. - pub content: serde_json::Value, -} - -/// A label on another artifact, which the subject names by its hash. -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub struct Tag { - /// The hash of the artifact labelled. - pub subject: String, - /// The label, such as `author`. - pub name: String, - /// The label's value, such as an account key. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub value: Option, -} - -/// A known kind, with its body decoded. -#[derive(Clone, Debug, PartialEq, Eq)] -pub enum Kind { - /// A friendship ends. - FriendRemove(FriendRemove), - /// An account names its home servers. - HomeDeclared(HomeDeclared), - /// An account publishes structured data. - Document(Document), - /// An account labels an artifact. - Tag(Tag), -} - -impl Kind { - fn encode(&self) -> Result<(&'static str, serde_json::Value)> { - Ok(match self { - Self::FriendRemove(body) => (FRIEND_REMOVE, serde_json::to_value(body)?), - Self::HomeDeclared(body) => (HOME_DECLARED, serde_json::to_value(body)?), - Self::Document(body) => (DOCUMENT, serde_json::to_value(body)?), - Self::Tag(body) => (TAG, serde_json::to_value(body)?), - }) - } -} - -fn forbidden(message: impl Into) -> anyhow::Error { - Refusal::Forbidden(message.into()).into() -} - -fn check_key(key: &str) -> Result<()> { - match normalize_key(key) { - Ok(canonical) if canonical == key => Ok(()), - _ => Err(forbidden(format!("{key} is not an account key"))), - } -} - -/// 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(crate) fn check_home_declared(author: &str, body: &HomeDeclared, replay: bool) -> Result<()> { - check_key(&body.account)?; - if author != body.account { - return Err(forbidden( - "a home declaration must be signed by its own account", - )); - } - if body.servers.len() > MAX_HOME_SERVERS { - return Err(forbidden(format!( - "a declaration names at most {MAX_HOME_SERVERS} servers" - ))); - } - // Duplicate refusal compares the validated endpoint - // identities, not the raw strings: one node can be named - // by its bare ID or by an endpoint ticket for that ID. - let mut targets: Vec = Vec::with_capacity(body.servers.len()); - 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) { - return Err(forbidden("a declaration names each endpoint at most once")); - } - targets.push(target); - } - for server in &body.servers { - if server.world_id.is_empty() { - return Err(forbidden("a home server needs a world ID")); - } - if replay { - continue; - } - if 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" - ))); - } - if server.world_id.trim().is_empty() { - return Err(forbidden( - "a home server's world ID must not be whitespace only", - )); - } - if server.world_id.chars().any(char::is_control) { - return Err(forbidden( - "a home server's world ID must not contain control characters", - )); - } - if server.world_id.chars().any(crate::is_format_char) { - return Err(forbidden( - "a home server's world ID must not contain format characters", - )); - } - } - Ok(()) -} - -impl SignedArtifact { - /// Sign a body of `kind` as the author holding `key`, at `seq` after `prev`. - /// - /// # Errors - /// - /// Fails if `seq` is zero or the body cannot be serialized, or if `kind` - /// is a known kind and its body breaks a rule receipt enforces — a - /// [`Refusal::Forbidden`] naming the rule, exactly as - /// [`SignedArtifact::parsed`] would refuse the signed artifact (#5623). - /// Unknown kinds stay envelope-only and always sign. - pub fn sign( - key: &SigningKey, - seq: u64, - prev: &str, - kind: &str, - body: serde_json::Value, - ) -> Result { - Self::sign_after(key, seq, prev, kind, body, Vec::new()) - } - - /// Like [`Self::sign`], also naming `after`, the artifacts the author had applied before this one. - /// - /// # Errors - /// - /// Fails if `seq` is zero, if `after` breaks the frontier rules (see - /// [`Self::check_after`]), if the body cannot be serialized, or if - /// `kind` is a known kind and its body breaks a rule receipt enforces - /// (see [`Self::sign`]). - pub fn sign_after( - key: &SigningKey, - seq: u64, - prev: &str, - kind: &str, - body: serde_json::Value, - after: Vec, - ) -> Result { - let artifact = Self::build_signed(key, seq, prev, kind, body, after)?; - // Construction-vs-receipt symmetry (#5623): a known kind is signed - // only when receipt would accept its body, so the check is the - // receipt check itself, run on the artifact about to go out. - // Unknown kinds parse to `None` and stay signable envelope-only. - artifact.parsed()?; - Ok(artifact) - } - - /// Sign without the known-kind body check in [`Self::sign_after`]: - /// sequence, `after`-frontier, hash, and signature rules all still - /// apply. Test-only, so tests can still craft the signed-but-refusable - /// artifacts that receipt-side tests exist to refuse. - #[cfg(test)] - pub(crate) fn sign_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, - prev: &str, - kind: &str, - body: serde_json::Value, - after: Vec, - ) -> Result { - ensure!(seq >= 1, "an artifact's sequence number starts at 1"); - Self::check_after(&after)?; - let author = hex_encode(&key.verifying_key().to_bytes()); - let bytes = signed_bytes(&author, seq, prev, kind, &body, &after)?; - Ok(Self { - hash: hex_encode(&Sha256::digest(&bytes)), - signature: hex_encode(&key.sign(&bytes).to_bytes()), - author, - seq, - prev: prev.to_owned(), - kind: kind.to_owned(), - body, - after, - }) - } - - /// Check the hash against the content and the signature against the author key. - /// - /// # Errors - /// - /// Fails with [`Refusal::Forbidden`] when the `after` frontier breaks a - /// frontier rule — a structural policy refusal, not an authenticity - /// failure (#3196) — and with [`Refusal::Unauthenticated`] if the hash - /// or signature does not check out. - pub fn verify(&self) -> Result<()> { - self.verify_mode(false) - } - - /// [`Self::verify`] for history a log already holds (trusted local - /// replay only): the duplicate-`after` rule (#3196) postdates logs - /// the producer path legitimately wrote, so replay does not apply - /// it - mirroring how replay skips the duplicate-request rule in - /// `parsed_for_replay`. Authenticity (hash, signature, canonical - /// author) and the other frontier rules (count, well-formed hashes) - /// stay strict in both modes: a corrupt or forged line still fails - /// to reopen. Fresh receipt and remote receipt always use - /// [`Self::verify`]; this leniency is never a remote policy (#5625, - /// coordinating with the #4459 format cutoff). - pub(crate) fn verify_for_replay(&self) -> Result<()> { - self.verify_mode(true) - } - - fn verify_mode(&self, replay: bool) -> Result<()> { - Self::check_after_mode(&self.after, replay)?; - self.check_authenticity() - .map_err(|error| Refusal::Unauthenticated(format!("{error:#}")).into()) - } - - /// The `after` frontier rules, shared by construction - /// ([`Self::sign_after`]) and receipt ([`Self::verify`]): at most - /// [`MAX_AFTER`] hashes, each one a well-formed hash, and none named - /// twice. Receipt refuses a duplicate rather than deduplicating it, so - /// what the signer supplied stays visible (#3231). - fn check_after(after: &[String]) -> Result<()> { - Self::check_after_mode(after, false) - } - - fn check_after_mode(after: &[String], replay: bool) -> Result<()> { - if after.len() > MAX_AFTER { - return Err(forbidden(format!( - "an artifact names at most {MAX_AFTER} artifacts before it" - ))); - } - if after.iter().any(|hash| !is_hash(hash)) { - return Err(forbidden("an artifact names a malformed hash in after")); - } - // The duplicate rule is the #3196 addition: in replay mode a - // frontier stored before it is grandfathered (see - // [`Self::verify_for_replay`]); construction and fresh receipt - // refuse a duplicate rather than deduplicating it. - if !replay { - let mut seen = HashSet::with_capacity(after.len()); - for hash in after { - if !seen.insert(hash) { - return Err(forbidden(format!( - "an artifact names {hash} twice in after" - ))); - } - } - } - Ok(()) - } - - fn check_authenticity(&self) -> Result<()> { - ensure!( - normalize_key(&self.author)? == self.author, - "author is not a canonical key" - ); - let bytes = signed_bytes( - &self.author, - self.seq, - &self.prev, - &self.kind, - &self.body, - &self.after, - )?; - ensure!( - hex_encode(&Sha256::digest(&bytes)) == self.hash, - "artifact hash does not match its content" - ); - let key = VerifyingKey::from_bytes( - &hex_to_array::<32>(&self.author).context("malformed author key")?, - ) - .context("author is not an Ed25519 key")?; - let signature = Signature::from_bytes( - &hex_to_array::<64>(&self.signature).context("malformed artifact signature")?, - ); - key.verify_strict(&bytes, &signature) - .context("signature does not verify against the author key") - } - - /// The known kind this artifact carries, checked. `None` for a kind this - /// server does not know: it is stored but never applied. - /// - /// # Errors - /// - /// 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) - } - - /// [`SignedArtifact::parsed`] for history a log already holds: the - /// `home_declared` bounds added for #3187 do not apply, so a declaration - /// accepted before them still replays (mirroring how replay skips the - /// frame check in `store`). New receipts always go through `parsed`. - pub(crate) fn parsed_for_replay(&self) -> Result> { - self.parsed_mode(true) - } - - fn parsed_mode(&self, replay: bool) -> Result> { - match self.kind.as_str() { - FRIEND_REMOVE => { - let body: FriendRemove = self.decode()?; - check_key(&body.a)?; - check_key(&body.b)?; - if body.requests.len() > MAX_FRIEND_REMOVE_REQUESTS { - return Err(forbidden(format!( - "a friend removal names at most {MAX_FRIEND_REMOVE_REQUESTS} requests" - ))); - } - if body - .requests - .iter() - .any(|request| !is_friend_request_id(request)) - { - return Err(forbidden( - "a friend removal request ID is not 32 lowercase hexadecimal characters", - )); - } - // The producer sorts and deduplicates its request IDs - // (directory.rs `friendship_requests`); a receipt naming - // the same request twice is refused rather than - // deduplicated (#3146). Replay stays lenient, mirroring - // the #3187 grandfathering below: a removal stored before - // this rule still replays, and its effect on the - // removed-request set is idempotent. - if !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")); - } - } - if body.a == body.b { - return Err(forbidden("no one befriends themselves")); - } - if self.author != body.a && self.author != body.b { - return Err(forbidden( - "a friend removal must be signed by one of its two accounts", - )); - } - Ok(Some(Kind::FriendRemove(body))) - } - HOME_DECLARED => { - let body: HomeDeclared = self.decode()?; - check_home_declared(&self.author, &body, replay)?; - Ok(Some(Kind::HomeDeclared(body))) - } - DOCUMENT => { - let body: Document = self.decode()?; - if body.media_type.is_empty() || body.media_type.len() > 128 { - return Err(forbidden("a document names its media type")); - } - // 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) { - return Err(forbidden("a document's media type is not NFC")); - } - let size = serde_json::to_vec(&body.content) - .map_err(|error| forbidden(format!("{error}")))? - .len(); - if size > MAX_DOCUMENT_BYTES { - return Err(forbidden(format!( - "a document holds at most {MAX_DOCUMENT_BYTES} bytes of content" - ))); - } - Ok(Some(Kind::Document(body))) - } - TAG => { - let body: Tag = self.decode()?; - if !is_hash(&body.subject) { - return Err(forbidden("a tag names its subject by hash")); - } - 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) { - 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)) { - return Err(forbidden("a tag's value is not NFC")); - } - Ok(Some(Kind::Tag(body))) - } - _ => Ok(None), - } - } - - fn decode(&self) -> Result { - serde_json::from_value(self.body.clone()) - .map_err(|error| forbidden(format!("{} body is malformed: {error}", self.kind))) - } -} - -/// Whether an insert stored a new artifact or matched one already held. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum Stored { - /// The artifact extends its author's chain. - New, - /// The same artifact is already held. - Duplicate, -} - -/// Every author's chain of verified artifacts, in sequence order. -#[derive(Clone, Debug, Default, PartialEq, Eq)] -pub struct ArtifactLog { - chains: BTreeMap>, -} - -impl ArtifactLog { - /// Add an artifact to its author's chain, if it verifies and extends the chain. - /// - /// # Errors - /// - /// Fails with [`Refusal::Unauthenticated`] for a bad signature or hash, and - /// with [`Refusal::Conflict`] for a gap, a fork, or a `prev` that does not - /// match. An artifact that one frame cannot carry is [`Refusal::Forbidden`], - /// since no page could ever send it. The log is unchanged on error. - pub fn insert(&mut self, artifact: SignedArtifact) -> Result { - self.store(artifact, true) - } - - /// [`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()?; - } 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()?; - } - let size = encoded_len(&artifact); - if frame_check && page_frame_bytes().saturating_add(size) > MAX_FRAME_BYTES { - return Err(forbidden(format!( - "an artifact of {size} bytes cannot be sent in one frame of {MAX_FRAME_BYTES} bytes" - ))); - } - if artifact.seq < 1 { - return Err(forbidden("sequence numbers start at 1")); - } - let held = self - .chains - .get(&artifact.author) - .map_or(&[][..], Vec::as_slice); - let have = u64::try_from(held.len())?; - if artifact.seq <= have { - let same = held - .get(usize::try_from(artifact.seq - 1)?) - .is_some_and(|at| at.hash == artifact.hash); - return if same { - Ok(Stored::Duplicate) - } else { - Err(Refusal::Conflict(format!( - "artifact {} of this account is already held as a different one", - artifact.seq - )) - .into()) - }; - } - if artifact.seq > have + 1 { - return Err(Refusal::Conflict(format!( - "artifact {} is missing; it must be pulled before artifact {}", - have + 1, - artifact.seq - )) - .into()); - } - let expected = held - .last() - .map_or_else(String::new, |last| last.hash.clone()); - if artifact.prev != expected { - return Err(Refusal::Conflict(format!( - "artifact {} does not follow the one held before it", - artifact.seq - )) - .into()); - } - self.chains - .entry(artifact.author.clone()) - .or_default() - .push(artifact); - Ok(Stored::New) - } - - /// Every held artifact, author by author, each in sequence order. - pub fn all(&self) -> impl Iterator { - self.chains.values().flatten() - } - - /// The number of artifacts held for an author, which is the last sequence number. - #[must_use] - pub fn head_seq(&self, author: &str) -> u64 { - self.chains - .get(author) - .map_or(0, |chain| u64::try_from(chain.len()).unwrap_or(u64::MAX)) - } - - /// The author's artifacts with a sequence number after `after`, in order, up to - /// [`PAGE_BYTES`]. A page always holds at least one artifact if any remain. - #[must_use] - pub fn page(&self, author: &str, after: u64) -> Vec { - let mut page: Vec = Vec::new(); - let mut used = page_frame_bytes(); - for artifact in self - .chains - .get(author) - .into_iter() - .flatten() - .filter(|artifact| artifact.seq > after) - { - let size = encoded_len(artifact).saturating_add(usize::from(!page.is_empty())); - if !page.is_empty() && used.saturating_add(size) > PAGE_BYTES { - break; - } - used = used.saturating_add(size); - page.push(artifact.clone()); - } - page - } - - /// The latest home-server declaration an account has made. - #[must_use] - pub fn declared(&self, account: &str) -> Option { - self.chains.get(account)?.iter().rev().find_map(|artifact| { - match artifact.parsed_for_replay() { - Ok(Some(Kind::HomeDeclared(declared))) => Some(declared), - _ => None, - } - }) - } - - /// Sign `kind` as the author holding `key`, at the position after its chain's head. - /// The result is not added to the log. - /// - /// # Errors - /// - /// Fails if the body cannot be serialized, or if the kind's body breaks - /// a rule receipt enforces (see [`SignedArtifact::sign`]). - pub fn sign(&self, key: &SigningKey, kind: &Kind) -> Result { - self.sign_after(key, kind, Vec::new()) - } - - /// Like [`Self::sign`], also naming `after`, the artifacts the author had applied before this one. - /// - /// # Errors - /// - /// Fails if the body cannot be serialized, or if the kind's body breaks - /// a rule receipt enforces (see [`SignedArtifact::sign`]). - pub fn sign_after( - &self, - key: &SigningKey, - kind: &Kind, - after: Vec, - ) -> Result { - let author = hex_encode(&key.verifying_key().to_bytes()); - let (seq, prev) = self.chains.get(&author).map_or_else( - || (1, String::new()), - |chain| { - let last = chain.last(); - ( - last.map_or(1, |last| last.seq + 1), - last.map_or_else(String::new, |last| last.hash.clone()), - ) - }, - ); - let (name, body) = kind.encode()?; - SignedArtifact::sign_after(key, seq, &prev, name, body, after) - } - - /// Load the log at `path`, which is empty if the file does not exist. A - /// final line cut short by a crash was never synced, so it is dropped and - /// the file is truncated to the last complete line, with a warning. Blank - /// lines are skipped, as `Directory::replay` skips them (#2128). - /// - /// # Errors - /// - /// Fails if a complete line is corrupt or does not verify. - pub fn open(path: &Path) -> Result { - let bytes = match fs::read(path) { - Ok(bytes) => bytes, - Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(Self::default()), - Err(error) => return Err(error).context("reading the artifact file"), - }; - let kept = bytes - .iter() - .rposition(|&byte| byte == b'\n') - .map_or(0, |index| index + 1); - if kept < bytes.len() { - // #2128: mirror Directory::replay / FileJournal::open - a torn - // final entry is dropped loudly, not silently. - tracing::warn!( - "artifact journal {}: dropping torn final entry at byte {kept}", - path.display() - ); - OpenOptions::new() - .write(true) - .open(path)? - .set_len(u64::try_from(kept)?)?; - } - let text = std::str::from_utf8(&bytes[..kept]).context("artifact file is not UTF-8")?; - let mut log = Self::default(); - for (number, line) in text.lines().enumerate() { - // #2128: blank lines are cosmetic (Directory::replay skips them - // in its own journal); enumerate() keeps the physical line - // number, so a corrupt non-blank line still reports its true - // position below. - if line.trim().is_empty() { - continue; - } - let artifact: SignedArtifact = serde_json::from_str(line) - .with_context(|| format!("artifact line {} is corrupt", number + 1))?; - log.store(artifact, false) - .with_context(|| format!("artifact line {} is refused", number + 1))?; - } - Ok(log) - } - - /// Load and verify an artifact log without truncating a torn final - /// fragment. Used by read-only replicas, whose startup must never - /// rewrite local state. - pub fn open_read_only(path: &Path) -> Result { - let bytes = match fs::read(path) { - Ok(bytes) => bytes, - Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(Self::default()), - Err(error) => return Err(error).context("reading the artifact file"), - }; - let kept = bytes - .iter() - .rposition(|&byte| byte == b'\n') - .map_or(0, |index| index + 1); - let text = std::str::from_utf8(&bytes[..kept]).context("artifact file is not UTF-8")?; - let mut log = Self::default(); - for (number, line) in text.lines().enumerate() { - if line.trim().is_empty() { - continue; - } - let artifact: SignedArtifact = serde_json::from_str(line) - .with_context(|| format!("artifact line {} is corrupt", number + 1))?; - log.store(artifact, false) - .with_context(|| format!("artifact line {} is refused", number + 1))?; - } - Ok(log) - } -} - -/// Durably append one artifact to the file at `path`. -/// -/// # Errors -/// -/// Fails if the file cannot be written or synced. -pub fn append(path: &Path, artifact: &SignedArtifact) -> Result<()> { - let mut line = serde_json::to_vec(artifact)?; - line.push(b'\n'); - let mut file = OpenOptions::new().create(true).append(true).open(path)?; - file.write_all(&line)?; - file.sync_data()?; - Ok(()) -} - -/// A page of an account's artifacts, the answer to one [`PullRequest`]. -#[derive(Debug, Serialize, Deserialize)] -pub struct Page { - /// The account's artifacts after the sequence number asked for, in order. - pub artifacts: Vec, -} - -/// The bytes of a page with no artifacts in it, which is `{"artifacts":[]}`. -fn page_frame_bytes() -> usize { - serde_json::to_vec(&Page { - artifacts: Vec::new(), - }) - .map_or(0, |bytes| bytes.len()) -} - -/// The bytes one artifact takes inside a page. An artifact that does not encode -/// counts as unbounded, so it can only ever be sent alone. -fn encoded_len(artifact: &SignedArtifact) -> usize { - serde_json::to_vec(artifact).map_or(usize::MAX, |bytes| bytes.len()) -} - -/// The bytes a page of `artifacts` takes on the wire, with one comma between artifacts. -fn page_bytes(artifacts: &[SignedArtifact]) -> usize { - artifacts - .iter() - .enumerate() - .fold(page_frame_bytes(), |used, (index, artifact)| { - used.saturating_add(encoded_len(artifact)) - .saturating_add(usize::from(index > 0)) - }) -} - -/// Whether a page is within [`PAGE_BYTES`], or holds one artifact that is larger alone. -fn within_budget(artifacts: &[SignedArtifact]) -> bool { - artifacts.len() <= 1 || page_bytes(artifacts) <= PAGE_BYTES -} - -/// What applying a page did. -#[derive(Debug, Default, PartialEq, Eq)] -pub struct PageOutcome { - /// Artifacts newly stored. - pub stored: usize, - /// Artifacts already held. - pub duplicates: usize, - /// The first artifact refused. Nothing after it is applied, since later - /// artifacts in a chain depend on it. - pub refused: Option, -} - -/// The artifact a page stopped at, and why. -#[derive(Debug, PartialEq, Eq)] -pub struct PageRefusal { - /// The refused artifact's sequence number. - pub seq: u64, - /// Why it was refused. - pub reason: String, -} - -/// Apply a page of `account`'s artifacts to `directory`. Each artifact is -/// checked on its own, so the server that served the page is not trusted. -pub fn apply_page( - directory: &mut Directory, - account: &str, - page: &[SignedArtifact], -) -> PageOutcome { - let mut outcome = PageOutcome::default(); - for artifact in page { - let refusal = if artifact.author == account { - match directory.receive_artifact(artifact) { - Ok(Stored::New) => { - outcome.stored += 1; - None - } - Ok(Stored::Duplicate) => { - outcome.duplicates += 1; - None - } - Err(error) => Some(format!("{error:#}")), - } - } else { - Some("artifact is not from the requested account".to_owned()) - }; - if let Some(reason) = refusal { - outcome.refused = Some(PageRefusal { - seq: artifact.seq, - reason, - }); - break; - } - } - outcome -} - -/// One pull on [`PULL_ALPN`]: the artifacts of `account` after sequence `after`. -#[derive(Debug, Serialize, Deserialize)] -pub struct PullRequest { - /// The account whose chain is wanted. - pub account: String, - /// The last sequence number the puller already holds. - pub after: u64, -} - -/// Answers [`PULL_ALPN`] pulls from the worlds a hub holds. -#[derive(Clone, Debug)] -pub struct ArtifactPullProtocol { - hub: WorldHub, - /// Deadline for the request frame to arrive (see `accept`). - frame_deadline: Duration, - /// Bound on the post-answer wait for the dialer to close. - close_wait: Duration, -} - -impl ArtifactPullProtocol { - /// Serve the artifacts of the worlds in `hub` to Iroh peers. - #[must_use] - pub const fn new(hub: WorldHub) -> Self { - Self { - hub, - frame_deadline: SESSION_DEADLINE, - close_wait: CLOSE_WAIT, - } - } - - async fn page(&self, request: &PullRequest) -> Result { - check_key(&request.account)?; - let Ok(lease) = self.hub.lease(None, None).await else { - bail!("the server is busy; try again"); - }; - let action = DirectoryAction::ReadArtifacts { - account: request.account.clone(), - after: request.after, - }; - let outcome = lease.service().directory(Caller::default(), action).await?; - Ok(Page { - artifacts: outcome.artifact_page.unwrap_or_default(), - }) - } -} - -fn refused(error: anyhow::Error) -> AcceptError { - AcceptError::from_boxed(error.into()) -} - -impl ProtocolHandler for ArtifactPullProtocol { - async fn accept(&self, conn: Connection) -> Result<(), AcceptError> { - let (mut send, mut recv) = conn.accept_bi().await?; - // A peer that connects and never sends its request frame - // must not hold this handler forever (#2087): bound the - // read by the same session deadline event sync uses for a - // silent peer. - let frame = tokio::time::timeout(self.frame_deadline, read_frame(&mut recv)).await; - let frame = match frame { - Ok(frame) => frame.map_err(refused)?, - Err(_elapsed) => return Ok(()), - }; - let Some(frame) = frame else { - return Ok(()); - }; - let request: PullRequest = - serde_json::from_slice(&frame).map_err(|error| refused(error.into()))?; - let page = self.page(&request).await.map_err(refused)?; - let bytes = serde_json::to_vec(&page).map_err(|error| refused(error.into()))?; - write_frame(&mut send, &bytes).await.map_err(refused)?; - send.finish()?; - // Bound the wait for the dialer to close, as event sync - // does (#2087): a peer that never closes must not pin the - // handler after its answer is sent. - let _ = tokio::time::timeout(self.close_wait, conn.closed()).await; - Ok(()) - } -} - -/// Accepts pushed artifacts on [`PUSH_ALPN`] and stores them in the worlds a hub holds. -#[derive(Clone, Debug)] -pub struct ArtifactPushProtocol { - hub: WorldHub, -} - -impl ArtifactPushProtocol { - /// Take pushed artifacts for the worlds in `hub`. - #[must_use] - pub const fn new(hub: WorldHub) -> Self { - Self { hub } - } -} - -impl ProtocolHandler for ArtifactPushProtocol { - async fn accept(&self, conn: Connection) -> Result<(), AcceptError> { - let hub = self.hub.clone(); - answer_frames(&conn, move |body| { - let hub = hub.clone(); - async move { receive_pushed(&hub, &body).await } - }) - .await - } -} - -/// Push `artifact` to the home server at `target`, and say whether it is done. -pub async fn push(endpoint: &Endpoint, target: EndpointAddr, artifact: &SignedArtifact) -> Outcome { - match serde_json::to_vec(artifact) { - Ok(json) => send(endpoint, PUSH_ALPN, target, &json).await, - Err(error) => Outcome::Refused(format!("artifact does not encode: {error}")), - } -} - -async fn receive_pushed(hub: &WorldHub, body: &[u8]) -> Reply { - let artifact: SignedArtifact = match serde_json::from_slice(body) { - Ok(artifact) => artifact, - Err(error) => { - return Reply::Refused { - message: format!("not an artifact: {error}"), - }; - } - }; - let Ok(lease) = hub.lease(None, None).await else { - return Reply::Retry { - message: "the server is busy; try again".to_owned(), - }; - }; - let action = DirectoryAction::ReceiveArtifact { artifact }; - match lease.service().directory(Caller::default(), action).await { - Ok(DirectoryOutcome { - stored: Some(Stored::New), - .. - }) => Reply::Applied, - Ok(DirectoryOutcome { - stored: Some(Stored::Duplicate), - .. - }) => Reply::Duplicate, - Ok(_) => Reply::Retry { - message: "artifact was not stored".to_owned(), - }, - Err(error) if error.downcast_ref::().is_some() => Reply::Refused { - message: format!("{error:#}"), - }, - Err(error) => Reply::Retry { - message: format!("{error:#}"), - }, - } -} - -/// Fetch one page of `account`'s artifacts after `after` from the home server at `peer`. -/// The dial and the answer share one [`DIAL_TIMEOUT`]. -/// -/// # Errors -/// -/// Fails if the deadline passes, the peer is unreachable, does not speak -/// [`PULL_ALPN`], or answers with something other than a page. -pub async fn fetch_page( - endpoint: &Endpoint, - peer: EndpointAddr, - account: &str, - after: u64, -) -> Result> { - fetch_page_within(endpoint, peer, account, after, DIAL_TIMEOUT).await -} - -/// [`fetch_page`] with its own deadline, which covers the address lookup, the -/// dial and the answer. -/// -/// # Errors -/// -/// As [`fetch_page`], and fails if `limit` passes first. -pub async fn fetch_page_within( - endpoint: &Endpoint, - peer: EndpointAddr, - account: &str, - after: u64, - limit: Duration, -) -> Result> { - check_key(account)?; - within(limit, "pulling artifacts from the home server", async { - let connection = connect(endpoint, peer, PULL_ALPN) - .await - .context("connecting to the home server")?; - let (mut send, mut recv) = connection - .open_bi() - .await - .context("opening a pull stream")?; - let request = PullRequest { - account: account.to_owned(), - after, - }; - write_frame(&mut send, &serde_json::to_vec(&request)?).await?; - send.finish().context("finishing the pull request")?; - let frame = read_frame(&mut recv) - .await? - .context("home server closed without a page")?; - let page: Page = serde_json::from_slice(&frame).context("artifact page is malformed")?; - ensure!( - within_budget(&page.artifacts), - "artifact page is over its byte budget" - ); - connection.close(0_u32.into(), b"pulled"); - Ok(page.artifacts) - }) - .await -} - -/// Pull `account`'s new artifacts from the home server at `peer`, page by page, -/// applying each page to `directory` as it arrives. Stops at the first refusal, -/// an empty page, or a page that stores nothing. -/// -/// A page is cut by bytes, so a short page does not mean the chain has ended. -/// The pull asks again after every page that stored something, which costs one -/// empty answer at the end. Each page fetch has [`DIAL_TIMEOUT`]. -/// -/// # Errors -/// -/// Fails if a page cannot be fetched. -pub async fn pull( - endpoint: &Endpoint, - peer: EndpointAddr, - account: &str, - directory: &mut Directory, -) -> Result { - pull_within(endpoint, peer, account, directory, DIAL_TIMEOUT).await -} - -/// [`pull`] with `limit` on each page fetch, see [`fetch_page_within`]. -/// -/// # Errors -/// -/// Fails if a page cannot be fetched within `limit`. -pub async fn pull_within( - endpoint: &Endpoint, - peer: EndpointAddr, - account: &str, - directory: &mut Directory, - limit: Duration, -) -> Result { - check_key(account)?; - let mut total = PageOutcome::default(); - loop { - let after = directory.artifacts().head_seq(account); - let page = fetch_page_within(endpoint, peer.clone(), account, after, limit).await?; - let outcome = apply_page(directory, account, &page); - total.stored += outcome.stored; - total.duplicates += outcome.duplicates; - if outcome.refused.is_some() { - total.refused = outcome.refused; - break; - } - if page.is_empty() || outcome.stored == 0 { - break; - } - } - Ok(total) -} - -#[cfg(test)] -#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] -mod tests { - use super::*; - use crate::test_forgeries::{IDENTITY_KEY, identity_forgery, with_non_canonical_s}; - use iroh::{ - TransportAddr, - endpoint::{RelayMode, presets}, - protocol::Router, - }; - use iroh_base::SecretKey; - use proptest::prelude::*; - use serde_json::json; - use std::net::{Ipv4Addr, SocketAddr}; - use std::time::Instant; - use tempfile::TempDir; - - use crate::connectivity::silent::{ - endpoint_with_silent_lookup, unanswered_addr, unanswered_id, - }; - use crate::world::{WorldCore, WorldHandle, WorldLimits}; - use crate::world_session::WorldService; - - fn key(seed: u8) -> SigningKey { - SigningKey::from_bytes(&[seed; 32]) - } - - #[test] - fn read_only_artifact_open_ignores_a_torn_non_utf8_tail_without_writing() { - let dir = TempDir::new().unwrap(); - let path = dir.path().join(FILE); - std::fs::write(&path, [0xff, 0xfe]).unwrap(); - let before = std::fs::read(&path).unwrap(); - let log = ArtifactLog::open_read_only(&path).unwrap(); - assert_eq!(log.all().count(), 0); - assert_eq!(std::fs::read(&path).unwrap(), before); - } - - fn public(seed: u8) -> String { - hex_encode(&key(seed).verifying_key().to_bytes()) - } - - fn removal(a: u8, b: u8, requests: &[&str]) -> Kind { - Kind::FriendRemove(FriendRemove { - a: public(a), - b: public(b), - requests: requests - .iter() - .map(|request| format!("{:0>32}", request.trim_start_matches('r'))) - .collect(), - }) - } - - fn endpoint_of(seed: u8) -> String { - SecretKey::from_bytes(&[seed; 32]).public().to_string() - } - - fn declared(seed: u8, home: u8) -> Kind { - Kind::HomeDeclared(HomeDeclared { - account: public(seed), - servers: vec![HomeServer { - endpoint: endpoint_of(home), - world_id: "home".to_owned(), - }], - }) - } - - fn document(text: &str) -> Kind { - Kind::Document(Document { - media_type: "application/json".to_owned(), - content: json!({ "text": text }), - }) - } - - /// Sign with full control of the `after` frontier, bypassing the - /// builder-side frontier check in [`SignedArtifact::sign_after`], so - /// receipt-side refusal of invalid frontiers stays testable. - fn sign_raw_after( - key: &SigningKey, - seq: u64, - prev: &str, - kind: &Kind, - after: Vec, - ) -> SignedArtifact { - let (name, body) = kind.encode().unwrap(); - let author = hex_encode(&key.verifying_key().to_bytes()); - let bytes = signed_bytes(&author, seq, prev, name, &body, &after).unwrap(); - SignedArtifact { - hash: hex_encode(&Sha256::digest(&bytes)), - signature: hex_encode(&key.sign(&bytes).to_bytes()), - author, - seq, - prev: prev.to_owned(), - kind: name.to_owned(), - body, - after, - } - } - - /// Sign a typed kind without the construction-side body check in - /// [`SignedArtifact::sign_after`], so receipt-side refusal of that - /// body stays testable (the typed twin of [`SignedArtifact::sign_unchecked`]). - fn sign_kind_unchecked(key: &SigningKey, kind: &Kind) -> SignedArtifact { - let (name, body) = kind.encode().unwrap(); - SignedArtifact::sign_unchecked(key, 1, "", name, body).unwrap() - } - - fn author_tag(subject: &str, author: u8) -> Kind { - Kind::Tag(Tag { - subject: subject.to_owned(), - name: "author".to_owned(), - value: Some(public(author)), - }) - } - - #[test] - fn a_replayed_artifact_is_a_duplicate_and_a_gap_names_what_is_missing() { - let mut log = ArtifactLog::default(); - let first = log.sign(&key(1), &removal(1, 2, &["r1"])).unwrap(); - assert_eq!(first.seq, 1); - assert_eq!(log.insert(first.clone()).unwrap(), Stored::New); - assert_eq!(log.insert(first).unwrap(), Stored::Duplicate); - assert_eq!(log.head_seq(&public(1)), 1); - - let second = log.sign(&key(1), &removal(1, 3, &[])).unwrap(); - let third = SignedArtifact::sign( - &key(1), - 3, - &second.hash, - FRIEND_REMOVE, - json!({"a": public(1), "b": public(3), "requests": []}), - ) - .unwrap(); - let gap = log.insert(third).unwrap_err(); - assert!( - matches!(gap.downcast_ref::(), Some(Refusal::Conflict(m)) if m.contains("artifact 2 is missing")), - "{gap:#}" - ); - assert_eq!(log.head_seq(&public(1)), 1); - } - - #[test] - fn a_fork_at_a_held_sequence_number_is_refused() { - let mut log = ArtifactLog::default(); - let held = log.sign(&key(1), &removal(1, 2, &["r1"])).unwrap(); - log.insert(held).unwrap(); - let other = SignedArtifact::sign( - &key(1), - 1, - "", - FRIEND_REMOVE, - json!({ - "a": public(1), - "b": public(2), - "requests": [format!("{:032x}", 2)] - }), - ) - .unwrap(); - let fork = log.insert(other).unwrap_err(); - assert!( - matches!(fork.downcast_ref::(), Some(Refusal::Conflict(_))), - "{fork:#}" - ); - } - - #[test] - fn a_forged_or_tampered_artifact_is_refused_and_changes_nothing() { - let mut log = ArtifactLog::default(); - let good = log.sign(&key(1), &removal(1, 2, &["r1"])).unwrap(); - log.insert(good.clone()).unwrap(); - let before = log.clone(); - - let mut tampered = SignedArtifact::sign( - &key(1), - 2, - &good.hash, - FRIEND_REMOVE, - json!({"a": public(1), "b": public(2), "requests": []}), - ) - .unwrap(); - tampered.body = json!({ - "a": public(1), - "b": public(2), - "requests": [format!("{:032x}", 9)] - }); - let error = log.insert(tampered).unwrap_err(); - assert!( - matches!( - error.downcast_ref::(), - Some(Refusal::Unauthenticated(_)) - ), - "{error:#}" - ); - - let mut forged = SignedArtifact::sign_unchecked( - &key(3), - 2, - &good.hash, - FRIEND_REMOVE, - json!({"a": public(1), "b": public(2), "requests": []}), - ) - .unwrap(); - forged.author = public(1); - let error = log.insert(forged).unwrap_err(); - assert!( - matches!( - error.downcast_ref::(), - Some(Refusal::Unauthenticated(_)) - ), - "{error:#}" - ); - assert_eq!(log, before); - } - - #[test] - fn a_removal_must_be_signed_by_one_of_its_accounts() { - let mut log = ArtifactLog::default(); - let stranger = SignedArtifact::sign_unchecked( - &key(3), - 1, - "", - FRIEND_REMOVE, - json!({"a": public(1), "b": public(2), "requests": []}), - ) - .unwrap(); - let error = log.insert(stranger).unwrap_err(); - assert!( - matches!(error.downcast_ref::(), Some(Refusal::Forbidden(_))), - "{error:#}" - ); - } - - #[test] - fn friend_removal_refuses_too_many_or_malformed_request_ids_before_storage() { - let valid_id = |n: u8| format!("{n:032x}"); - let valid_three = SignedArtifact::sign( - &key(1), - 1, - "", - FRIEND_REMOVE, - json!({ - "a": public(1), - "b": public(2), - "requests": [valid_id(1), valid_id(2), valid_id(3)] - }), - ) - .unwrap(); - assert!(matches!( - valid_three.parsed(), - Ok(Some(Kind::FriendRemove(_))) - )); - - let cases = [ - vec![valid_id(1), valid_id(2), valid_id(3), valid_id(4)], - vec![valid_id(1), valid_id(1)], - vec!["g".repeat(32)], - vec!["a".repeat(31)], - vec!["a".repeat(33)], - vec!["A".repeat(32)], - ]; - - for requests in cases { - let artifact = SignedArtifact::sign_unchecked( - &key(1), - 1, - "", - FRIEND_REMOVE, - json!({"a": public(1), "b": public(2), "requests": requests}), - ) - .unwrap(); - let parsed = artifact.parsed().unwrap_err(); - assert!( - matches!( - parsed.downcast_ref::(), - Some(Refusal::Forbidden(_)) - ), - "{parsed:#}" - ); - - let mut log = ArtifactLog::default(); - let inserted = log.insert(artifact).unwrap_err(); - assert!( - matches!( - inserted.downcast_ref::(), - Some(Refusal::Forbidden(_)) - ), - "{inserted:#}" - ); - assert_eq!(log.head_seq(&public(1)), 0); - } - } - - #[test] - fn a_legacy_removal_naming_a_request_twice_still_replays() { - // Stored before the uniqueness rule (#3146): fresh receipt refuses - // it, but replay does not brick the log that already holds it. - let dir = TempDir::new().unwrap(); - let path = dir.path().join(FILE); - let legacy = SignedArtifact::sign_unchecked( - &key(1), - 1, - "", - FRIEND_REMOVE, - json!({ - "a": public(1), - "b": public(2), - "requests": [format!("{:032x}", 7), format!("{:032x}", 7)] - }), - ) - .unwrap(); - assert!(legacy.parsed().is_err()); - assert!(ArtifactLog::default().insert(legacy.clone()).is_err()); - append(&path, &legacy).unwrap(); - - let reopened = ArtifactLog::open(&path).unwrap(); - assert_eq!(reopened.head_seq(&public(1)), 1); - } - - #[test] - fn a_legacy_log_with_a_duplicate_after_frontier_still_replays() { - // #5625: stored before the duplicate-after rule (#3196), when - // sign_after accepted a repeated frontier hash. Fresh receipt - // (verify / insert) still refuses it; trusted local replay - // (open / open_read_only) reopens the log that already holds it. - let dir = TempDir::new().unwrap(); - let path = dir.path().join(FILE); - let mut log = ArtifactLog::default(); - let first = log.sign(&key(1), &document("first")).unwrap(); - log.insert(first.clone()).unwrap(); - let legacy = sign_raw_after( - &key(1), - 2, - &first.hash, - &document("second"), - vec![first.hash.clone(), first.hash.clone()], - ); - assert!(legacy.verify().is_err()); - assert!(ArtifactLog::default().insert(legacy.clone()).is_err()); - append(&path, &first).unwrap(); - append(&path, &legacy).unwrap(); - - let reopened = ArtifactLog::open(&path).unwrap(); - assert_eq!(reopened.head_seq(&public(1)), 2); - let read_only = ArtifactLog::open_read_only(&path).unwrap(); - assert_eq!(read_only.head_seq(&public(1)), 2); - - // Authenticity stays strict in replay: the same log with a - // forged hash line does not reopen. - let mut forged = legacy.clone(); - forged.hash = format!("{:064x}", 9_u64); - let bad_path = dir.path().join("forged.jsonl"); - append(&bad_path, &first).unwrap(); - append(&bad_path, &forged).unwrap(); - assert!(ArtifactLog::open(&bad_path).is_err()); - assert!(ArtifactLog::open_read_only(&bad_path).is_err()); - } - - #[test] - fn a_legacy_log_with_non_nfc_document_and_tag_fields_still_replays() { - // #5625: stored before the NFC rules (#3192), when the producer - // path passed media_type / tag text through the then-lenient - // parser. Fresh receipt still refuses each shape; replay - // grandfathers exactly those three fields. - let dir = TempDir::new().unwrap(); - let cases: Vec = vec![ - Kind::Document(Document { - media_type: "application/jso\u{301}n".to_owned(), - content: json!({ "text": "ok" }), - }), - Kind::Tag(Tag { - subject: public(2), - name: "e\u{301}".to_owned(), - value: None, - }), - Kind::Tag(Tag { - subject: public(2), - name: "author".to_owned(), - value: Some("e\u{301}".to_owned()), - }), - ]; - for (index, kind) in cases.into_iter().enumerate() { - let legacy = sign_kind_unchecked(&key(1), &kind); - assert!(legacy.parsed().is_err(), "case {index}"); - assert!( - ArtifactLog::default().insert(legacy.clone()).is_err(), - "case {index}" - ); - assert!( - matches!(legacy.parsed_for_replay(), Ok(Some(_))), - "case {index}" - ); - let path = dir.path().join(format!("legacy-{index}.jsonl")); - append(&path, &legacy).unwrap(); - let reopened = ArtifactLog::open(&path).unwrap(); - assert_eq!(reopened.head_seq(&public(1)), 1, "case {index}"); - let read_only = ArtifactLog::open_read_only(&path).unwrap(); - assert_eq!(read_only.head_seq(&public(1)), 1, "case {index}"); - } - } - - #[test] - fn signing_a_known_kind_refuses_the_bodies_receipt_refuses() { - // Construction-vs-receipt symmetry (#5623), with `parsed` on a - // raw-signed copy as the oracle: for every known kind, a body - // receipt refuses is refused at signing time with the same - // Refusal::Forbidden class, and a body receipt accepts still signs. - let valid_id = |n: u8| format!("{n:032x}"); - let refused: Vec<(&str, serde_json::Value)> = vec![ - // A removal signed by an account that is not one of its two. - ( - FRIEND_REMOVE, - json!({"a": public(1), "b": public(2), "requests": []}), - ), - // A document with no media type. - ( - DOCUMENT, - json!({"media_type": "", "content": {"text": "x"}}), - ), - // A tag whose subject is not a hash. - ( - TAG, - json!({"subject": "not a hash", "name": "author", "value": null}), - ), - ]; - // The friend_remove case must be signed by the stranger, key(3). - let stranger_error = - SignedArtifact::sign(&key(3), 1, "", refused[0].0, refused[0].1.clone()).unwrap_err(); - assert!( - matches!( - stranger_error.downcast_ref::(), - Some(Refusal::Forbidden(_)) - ), - "{stranger_error:#}" - ); - for (kind, body) in &refused[1..] { - let error = SignedArtifact::sign(&key(1), 1, "", kind, body.clone()).unwrap_err(); - assert!( - matches!(error.downcast_ref::(), Some(Refusal::Forbidden(_))), - "{kind}: {error:#}" - ); - let raw = SignedArtifact::sign_unchecked(&key(1), 1, "", kind, body.clone()).unwrap(); - assert!(raw.parsed().is_err(), "{kind} body accepted by parsed"); - } - // Too many friend-removal requests, signed by a party to the removal. - let too_many = SignedArtifact::sign( - &key(1), - 1, - "", - FRIEND_REMOVE, - json!({ - "a": public(1), - "b": public(2), - "requests": [valid_id(1), valid_id(2), valid_id(3), valid_id(4)] - }), - ) - .unwrap_err(); - assert!( - matches!( - too_many.downcast_ref::(), - Some(Refusal::Forbidden(_)) - ), - "{too_many:#}" - ); - // A home declaration naming another account. - let other_account = SignedArtifact::sign( - &key(2), - 1, - "", - HOME_DECLARED, - json!({"account": public(1), "servers": []}), - ) - .unwrap_err(); - assert!( - matches!( - other_account.downcast_ref::(), - Some(Refusal::Forbidden(_)) - ), - "{other_account:#}" - ); - // The accepted side of the symmetry: valid bodies of every known - // kind still sign, and an unknown kind stays signable envelope-only. - for (kind, body) in [ - ( - FRIEND_REMOVE, - json!({"a": public(1), "b": public(2), "requests": [valid_id(1)]}), - ), - (HOME_DECLARED, json!({"account": public(1), "servers": []})), - ( - DOCUMENT, - json!({"media_type": "application/json", "content": {"text": "x"}}), - ), - ( - TAG, - json!({"subject": public(2), "name": "author", "value": null}), - ), - ] { - let signed = SignedArtifact::sign(&key(1), 1, "", kind, body).unwrap(); - assert!( - matches!(signed.parsed(), Ok(Some(_))), - "{kind} valid body refused" - ); - } - let future = - SignedArtifact::sign(&key(1), 1, "", "future_kind", json!({"anything": true})).unwrap(); - assert_eq!(future.parsed().unwrap(), None); - } +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +mod tests { + use super::*; + use serde_json::json; + use std::net::{Ipv4Addr, SocketAddr}; + use std::time::Instant; - #[test] - fn an_unknown_kind_is_stored_and_has_no_meaning_here() { - let mut log = ArtifactLog::default(); - let future = - SignedArtifact::sign(&key(1), 1, "", "future_kind", json!({"anything": [1, 2]})) - .unwrap(); - assert_eq!(log.insert(future.clone()).unwrap(), Stored::New); - assert_eq!(future.parsed().unwrap(), None); - assert_eq!(log.head_seq(&public(1)), 1); - } + use iroh::{ + TransportAddr, + endpoint::{RelayMode, presets}, + protocol::Router, + }; + use iroh_base::SecretKey; - #[test] - fn a_home_declaration_is_checked_and_the_latest_one_wins() { - let mut log = ArtifactLog::default(); - let first = log.sign(&key(1), &declared(1, 7)).unwrap(); - log.insert(first.clone()).unwrap(); - let second = log.sign(&key(1), &declared(1, 8)).unwrap(); - log.insert(second).unwrap(); - assert_eq!( - log.declared(&public(1)).unwrap().servers[0].endpoint, - endpoint_of(8) - ); - assert_eq!(log.insert(first).unwrap(), Stored::Duplicate); - assert_eq!( - log.declared(&public(1)).unwrap().servers[0].endpoint, - endpoint_of(8) - ); + use std::time::Duration; - let plain = SignedArtifact::sign_unchecked( - &key(1), - 3, - &log.page(&public(1), 0)[1].hash, - HOME_DECLARED, - json!({"account": public(1), "servers": [{"endpoint": "not a node", "world_id": "w"}]}), - ) - .unwrap(); - let refused = log.insert(plain).unwrap_err(); - assert!( - matches!( - refused.downcast_ref::(), - Some(Refusal::Forbidden(_)) - ), - "{refused:#}" - ); - let other_account = SignedArtifact::sign_unchecked( - &key(2), - 1, - "", - HOME_DECLARED, - json!({"account": public(1), "servers": []}), - ) - .unwrap(); - assert!(log.insert(other_account).is_err()); - } + use anyhow::Result; + use ed25519_dalek::SigningKey; + use iroh::{ + Endpoint, EndpointAddr, + endpoint::Connection, + protocol::{AcceptError, ProtocolHandler}, + }; + use sha2::{Digest, Sha256}; - #[test] - fn artifacts_survive_a_restart_and_a_torn_tail_is_dropped() { - let dir = TempDir::new().unwrap(); - let path = dir.path().join(FILE); - let mut log = ArtifactLog::default(); - let first = log.sign(&key(1), &removal(1, 2, &["r1"])).unwrap(); - log.insert(first.clone()).unwrap(); - append(&path, &first).unwrap(); - let second = log.sign(&key(1), &declared(1, 7)).unwrap(); - log.insert(second.clone()).unwrap(); - append(&path, &second).unwrap(); - let complete = fs::read(&path).unwrap(); - let mut torn = complete.clone(); - torn.extend_from_slice(b"{\"name\":\"Jos"); - torn.push(0xc3); // First byte of "é". - fs::write(&path, torn).unwrap(); + use id_core::frames::{read_frame, write_frame}; - let mut reopened = ArtifactLog::open(&path).unwrap(); - assert_eq!(reopened, log); - assert_eq!(fs::read(&path).unwrap(), complete); - assert_eq!(reopened.head_seq(&public(1)), 2); - let third = reopened.sign(&key(1), &declared(1, 9)).unwrap(); - reopened.insert(third.clone()).unwrap(); - append(&path, &third).unwrap(); - assert_eq!(ArtifactLog::open(&path).unwrap(), reopened); + use crate::directory::{Directory, Refusal, hex_to_array}; + use crate::directory_auth::Caller; + use crate::directory_view::DirectoryAction; + use crate::envelope_outbox::Outcome; + use crate::world::hex_encode; + use crate::world_hub::WorldHub; + use crate::test_forgeries::{IDENTITY_KEY, identity_forgery, with_non_canonical_s}; + use crate::world::{WorldCore, WorldHandle, WorldLimits}; + use crate::world_session::WorldService; + fn key(seed: u8) -> SigningKey { + SigningKey::from_bytes(&[seed; 32]) } - - #[test] - fn blank_lines_in_the_journal_are_skipped() { - // #2128: a blank line must not brick the open - Directory::replay - // skips them in its own journal. Middle (incl. whitespace-only), - // trailing, and blank-only states all open with artifacts intact. - let dir = TempDir::new().unwrap(); - let path = dir.path().join(FILE); - let mut log = ArtifactLog::default(); - let first = log.sign(&key(1), &removal(1, 2, &["r1"])).unwrap(); - log.insert(first.clone()).unwrap(); - append(&path, &first).unwrap(); - let second = log.sign(&key(1), &declared(1, 7)).unwrap(); - log.insert(second.clone()).unwrap(); - append(&path, &second).unwrap(); - - let text = fs::read_to_string(&path).unwrap(); - let first_nl = text.find('\n').unwrap(); - let mut mangled = text.clone(); - mangled.insert_str(first_nl + 1, "\n \n"); - mangled.push('\n'); - fs::write(&path, mangled).unwrap(); - assert_eq!(ArtifactLog::open(&path).unwrap(), log); - - let blank_only = dir.path().join("blank.artifacts"); - fs::write(&blank_only, "\n\n").unwrap(); - assert_eq!( - ArtifactLog::open(&blank_only).unwrap(), - ArtifactLog::default() - ); + fn public(seed: u8) -> String { + hex_encode(&key(seed).verifying_key().to_bytes()) } - - #[test] - fn a_corrupt_line_after_a_blank_line_reports_its_physical_line() { - // #2128: skipping blanks must not renumber - the corrupt line is - // physically line 3 and the refusal must say so. - let dir = TempDir::new().unwrap(); - let path = dir.path().join(FILE); - let mut log = ArtifactLog::default(); - let first = log.sign(&key(1), &removal(1, 2, &["r1"])).unwrap(); - log.insert(first.clone()).unwrap(); - append(&path, &first).unwrap(); - let mut text = fs::read_to_string(&path).unwrap(); - text.push_str("\nnot json\n"); - fs::write(&path, text).unwrap(); - - let refused = ArtifactLog::open(&path).unwrap_err(); - assert!( - format!("{refused:#}").contains("artifact line 3 is corrupt"), - "{refused:#}" - ); + fn endpoint_of(seed: u8) -> String { + SecretKey::from_bytes(&[seed; 32]).public().to_string() } - - /// The bytes a page takes on the wire, as the server sends it. - fn wire_len(page: &[SignedArtifact]) -> usize { - serde_json::to_vec(&Page { - artifacts: page.to_vec(), + fn document(text: &str) -> Kind { + Kind::Document(Document { + media_type: "application/json".to_owned(), + content: json!({ "text": text }), }) - .unwrap() - .len() - } - - /// Pages through `author`'s chain from the start, checking each page as it comes. - fn every_page(log: &ArtifactLog, author: &str) -> Vec> { - let total = log.head_seq(author); - let mut pages = Vec::new(); - let mut after = 0; - while after < total { - let page = log.page(author, after); - assert!(!page.is_empty(), "no progress after sequence {after}"); - assert!( - fills_the_budget(log, author, &page), - "a page of {} artifacts leaves room for the next", - page.len() - ); - after = page.last().unwrap().seq; - pages.push(page); - } - pages - } - - /// Whether `page` is as full as the budget allows: the artifact after its last - /// one would not fit in it. A page cut short by a count, not by bytes, fails. - fn fills_the_budget(log: &ArtifactLog, author: &str, page: &[SignedArtifact]) -> bool { - let Some(last) = page.last() else { - return true; - }; - let Some(next) = log.page(author, last.seq).into_iter().next() else { - return true; - }; - let mut bigger = page.to_vec(); - bigger.push(next); - wire_len(&bigger) > PAGE_BYTES - } - - #[test] - fn a_page_is_in_order_and_within_the_byte_budget() { - let mut log = ArtifactLog::default(); - for _ in 0..12 { - let next = log - .sign(&key(1), &document(&"x".repeat(MAX_DOCUMENT_BYTES - 32))) - .unwrap(); - log.insert(next).unwrap(); - } - let first = log.page(&public(1), 0); - assert_eq!(first[0].seq, 1); - assert!(first.len() > 1 && first.len() < 12, "{}", first.len()); - assert!(wire_len(&first) <= PAGE_BYTES, "{}", wire_len(&first)); - - let pages = every_page(&log, &public(1)); - assert!(pages.len() >= 3, "12 documents of 64 KiB take three pages"); - let seqs: Vec = pages.iter().flatten().map(|a| a.seq).collect(); - assert_eq!(seqs, (1..=12).collect::>()); - } - - #[test] - fn a_lone_oversized_artifact_is_a_page_of_its_own() { - let mut log = ArtifactLog::default(); - let big = SignedArtifact::sign( - &key(1), - 1, - "", - "future_kind", - json!({"blob": "x".repeat(PAGE_BYTES * 2)}), - ) - .unwrap(); - log.insert(big).unwrap(); - for _ in 0..3 { - let next = log.sign(&key(1), &document("small")).unwrap(); - log.insert(next).unwrap(); - } - let first = log.page(&public(1), 0); - assert_eq!(first.len(), 1, "the oversized artifact goes alone"); - assert!(wire_len(&first) > PAGE_BYTES); - let pages = every_page(&log, &public(1)); - assert_eq!(pages.len(), 2, "then the three small ones together"); - assert_eq!( - pages[1].iter().map(|a| a.seq).collect::>(), - [2, 3, 4] - ); - } - - /// An artifact whose JSON is `bytes` long. Its kind is unknown, so no parser - /// limits its size, and its body is padding. - fn unknown_kind_of_size(bytes: usize) -> SignedArtifact { - let signed = |pad: usize| { - SignedArtifact::sign( - &key(1), - 1, - "", - "future_kind", - json!({ "pad": "x".repeat(pad) }), - ) - .unwrap() - }; - let base = serde_json::to_vec(&signed(0)).unwrap().len(); - signed(bytes.saturating_sub(base)) - } - - /// An artifact is stored exactly when one page can carry it in a frame. A - /// pull then never meets an artifact that the server cannot send. - #[test] - fn an_artifact_is_stored_exactly_when_one_frame_can_carry_it() { - let mut wrong = Vec::new(); - for slack in [0_usize, 1, 15, 16, 17, 40, 4096] { - let artifact = unknown_kind_of_size(MAX_FRAME_BYTES - slack); - let fits = wire_len(std::slice::from_ref(&artifact)) <= MAX_FRAME_BYTES; - let stored = ArtifactLog::default().insert(artifact).is_ok(); - if stored != fits { - wrong.push(format!( - "{slack} bytes under the cap: stored {stored}, fits {fits}" - )); - } - } - assert!(wrong.is_empty(), "{}", wrong.join("\n")); } - - /// A log file written before the frame check can hold an artifact that one - /// frame cannot carry. Opening the file must keep it: the directory loads its - /// log at start-up, so refusing the line would stop the server from starting. - #[test] - fn a_stored_artifact_too_large_for_one_frame_still_opens() { - for bytes in [MAX_FRAME_BYTES - 5, MAX_FRAME_BYTES + 1024] { - let dir = TempDir::new().unwrap(); - let path = dir.path().join(FILE); - let line = serde_json::to_string(&unknown_kind_of_size(bytes)).unwrap(); - fs::write(&path, format!("{line}\n")).unwrap(); - let log = ArtifactLog::open(&path) - .unwrap_or_else(|error| panic!("a {bytes}-byte line: {error:#}")); - assert_eq!(log.head_seq(&public(1)), 1, "a {bytes}-byte line"); - } + /// Sign a typed kind without the construction-side body check in + /// [`SignedArtifact::sign_after`], so receipt-side refusal of that + /// body stays testable (the typed twin of [`SignedArtifact::sign_unchecked`]). + fn sign_kind_unchecked(key: &SigningKey, kind: &Kind) -> SignedArtifact { + let (name, body) = kind.encode().unwrap(); + SignedArtifact::sign_unchecked(key, 1, "", name, body).unwrap() } - - proptest! { - #![proptest_config(ProptestConfig::with_cases(24))] - - /// Random record sizes, mostly small with some near the limit: every page - /// fits the byte budget unless it holds one artifact, and paging returns - /// each artifact exactly once, in order. Debug-mode hashing is slow, so the - /// sizes skew small to keep the case count useful. - #[test] - fn pages_fit_the_budget_and_neither_lose_nor_repeat_an_artifact( - sizes in proptest::collection::vec( - prop_oneof![ - 3 => 0..4096_usize, - 1 => 0..(MAX_DOCUMENT_BYTES - 32), - ], - 1..40, - ), - ) { - let mut log = ArtifactLog::default(); - for size in &sizes { - let next = log.sign(&key(1), &document(&"x".repeat(*size))).unwrap(); - log.insert(next).unwrap(); - } - let total = sizes.len() as u64; - let mut after = 0; - let mut paged = Vec::new(); - while after < total { - let page = log.page(&public(1), after); - prop_assert!(!page.is_empty(), "no progress after sequence {after}"); - prop_assert!( - page.len() == 1 || wire_len(&page) <= PAGE_BYTES, - "a page of {} artifacts takes {} bytes", - page.len(), - wire_len(&page) - ); - prop_assert!( - fills_the_budget(&log, &public(1), &page), - "a page of {} artifacts leaves room for the next", - page.len() - ); - after = page.last().map_or(after, |last| last.seq); - paged.extend(page); - } - prop_assert_eq!( - paged.iter().map(|a| a.seq).collect::>(), - (1..=total).collect::>() - ); - } + fn author_tag(subject: &str, author: u8) -> Kind { + Kind::Tag(Tag { + subject: subject.to_owned(), + name: "author".to_owned(), + value: Some(public(author)), + }) } - fn account(directory: &mut Directory, name: &str) -> (String, String) { let (credential, _) = directory.sign_up(name).unwrap(); let id = directory.account_for(&credential).unwrap(); (id, credential) } - fn key_of(credential: &str) -> SigningKey { let secret = hex_to_array::<32>(credential.rsplit('.').next().unwrap()).unwrap(); SigningKey::from_bytes(&secret) } - async fn endpoint() -> Endpoint { Endpoint::builder(presets::Minimal) .relay_mode(RelayMode::Disabled) @@ -2075,7 +87,6 @@ mod tests { .await .unwrap() } - fn loopback(endpoint: &Endpoint) -> EndpointAddr { EndpointAddr::from_parts( endpoint.id(), @@ -2089,7 +100,6 @@ mod tests { }), ) } - #[test] fn a_page_applies_what_verifies_and_stops_at_a_forgery() { let mut home = Directory::new(); @@ -2123,7 +133,6 @@ mod tests { assert!(!away.are_friends(&ann, &bo), "the verified removal applied"); assert_eq!(away.artifacts().head_seq(&ann), 1); } - #[tokio::test] async fn a_pull_over_iroh_applies_the_removal_a_home_server_holds() { let mut home = Directory::new(); @@ -2165,7 +174,6 @@ mod tests { assert!(!away.are_friends(&ann, &bo)); assert_eq!(away.artifacts().head_seq(&ann), 1); } - #[tokio::test(flavor = "multi_thread")] async fn a_silent_or_never_closing_pull_peer_does_not_pin_the_handler() { // #2087 regression: accept waited forever for the request @@ -2253,7 +261,6 @@ mod tests { "the answered accept ends cleanly: {released:?}" ); } - #[test] fn a_pulled_artifact_from_another_account_is_refused() { let mut directory = Directory::new(); @@ -2269,103 +276,6 @@ mod tests { assert_eq!(outcome.stored, 0); assert!(outcome.refused.is_some()); } - - #[test] - fn causal_references_are_signed_and_bounded() { - let mut log = ArtifactLog::default(); - let first = log.sign(&key(1), &document("first")).unwrap(); - log.insert(first.clone()).unwrap(); - let second = log - .sign_after(&key(1), &document("second"), vec![first.hash.clone()]) - .unwrap(); - assert_eq!(second.after, vec![first.hash.clone()]); - log.insert(second.clone()).unwrap(); - - let second_hash = second.hash.clone(); - let mut stripped = second; - stripped.after.clear(); - let error = ArtifactLog::default().insert(stripped).unwrap_err(); - assert!( - matches!( - error.downcast_ref::(), - Some(Refusal::Unauthenticated(_)) - ), - "{error:#}" - ); - - let malformed = sign_raw_after( - &key(1), - 3, - &second_hash, - &document("third"), - vec!["not a hash".to_owned()], - ); - assert!(log.insert(malformed).is_err()); - let crowded = sign_raw_after( - &key(1), - 3, - &second_hash, - &document("fourth"), - vec![first.hash; MAX_AFTER + 1], - ); - assert!(log.insert(crowded).is_err()); - assert_eq!(log.head_seq(&public(1)), 2); - } - - #[test] - fn test_duplicate_after_hashes_are_refused() { - let mut log = ArtifactLog::default(); - let first = log.sign(&key(1), &document("first")).unwrap(); - log.insert(first.clone()).unwrap(); - - let doubled = sign_raw_after( - &key(1), - 2, - &first.hash, - &document("second"), - vec![first.hash.clone(), first.hash.clone()], - ); - // A validly signed duplicate frontier is a policy refusal, not an - // authenticity failure (#3196). - let refused = doubled.verify().unwrap_err(); - assert!( - matches!( - refused.downcast_ref::(), - Some(Refusal::Forbidden(_)) - ), - "{refused:#}" - ); - assert!(log.insert(doubled).is_err()); - - // The builder refuses the same frontier before receipt sees it. - assert!( - log.sign_after( - &key(1), - &document("second"), - vec![first.hash.clone(), first.hash.clone()], - ) - .is_err() - ); - - let repeated = sign_raw_after( - &key(1), - 2, - &first.hash, - &document("third"), - vec![first.hash.clone(); MAX_AFTER], - ); - assert!(repeated.verify().is_err()); - assert!(log.insert(repeated).is_err()); - assert_eq!(log.head_seq(&public(1)), 1); - - let distinct: Vec = (0..MAX_AFTER).map(|i| format!("{i:064x}")).collect(); - let frontier = log - .sign_after(&key(1), &document("fourth"), distinct) - .unwrap(); - assert!(frontier.verify().is_ok()); - assert_eq!(log.insert(frontier).unwrap(), Stored::New); - } - #[test] fn documents_and_tags_are_checked_and_never_applied_as_directory_changes() { // Construction refuses these bodies itself now (#5623), with the @@ -2420,149 +330,6 @@ mod tests { assert_eq!(stored, Stored::New); assert_eq!(directory.artifacts().head_seq(&public(1)), 1); } - - fn home_declared_with(servers: Vec) -> SignedArtifact { - sign_kind_unchecked( - &key(1), - &Kind::HomeDeclared(HomeDeclared { - account: public(1), - servers, - }), - ) - } - - fn home_server(endpoint: String, world_id: &str) -> HomeServer { - HomeServer { - endpoint, - world_id: world_id.to_owned(), - } - } - - #[test] - fn parsed_home_world_id_is_bounded_and_clean() { - let control = home_declared_with(vec![home_server(endpoint_of(7), "home")]); - assert!(matches!(control.parsed(), Ok(Some(Kind::HomeDeclared(_))))); - - let at_bound = home_declared_with(vec![home_server(endpoint_of(7), &"w".repeat(64))]); - assert!(matches!(at_bound.parsed(), Ok(Some(Kind::HomeDeclared(_))))); - - for world_id in [ - "w".repeat(65), - " ".to_owned(), - "home\nFORGED".to_owned(), - "ho\u{1}me".to_owned(), - "home\u{202e}".to_owned(), - ] { - let refused = home_declared_with(vec![home_server(endpoint_of(7), &world_id)]); - assert!(refused.parsed().is_err(), "world_id {world_id:?} accepted"); - } - } - - #[test] - fn parsed_home_declaration_refuses_duplicate_endpoints() { - let distinct = home_declared_with(vec![ - home_server(endpoint_of(7), "home"), - home_server(endpoint_of(8), "lobby"), - ]); - assert!(matches!(distinct.parsed(), Ok(Some(Kind::HomeDeclared(_))))); - - let duplicate = home_declared_with(vec![ - home_server(endpoint_of(7), "home"), - home_server(endpoint_of(7), "lobby"), - ]); - assert!(duplicate.parsed().is_err()); - - // The same node named once by bare ID and once by an endpoint - // ticket for that ID is still a duplicate. - let ticket = iroh_tickets::endpoint::EndpointTicket::new(EndpointAddr::from( - SecretKey::from_bytes(&[7; 32]).public(), - )) - .to_string(); - let aliased = home_declared_with(vec![ - home_server(endpoint_of(7), "home"), - home_server(ticket, "lobby"), - ]); - assert!(aliased.parsed().is_err()); - } - - #[test] - fn a_legacy_home_declaration_still_replays() { - // A declaration accepted before the #3187 bounds (here: a world ID - // past MAX_WORLD_ID_BYTES) must not brick reopening its log: replay - // is lenient, while a fresh receipt of the same artifact is refused. - let dir = TempDir::new().unwrap(); - let path = dir.path().join(FILE); - let legacy = home_declared_with(vec![home_server(endpoint_of(7), &"w".repeat(65))]); - assert!(legacy.parsed().is_err()); - assert!(ArtifactLog::default().insert(legacy.clone()).is_err()); - append(&path, &legacy).unwrap(); - - let reopened = ArtifactLog::open(&path).unwrap(); - assert_eq!( - reopened.declared(&public(1)).unwrap().servers[0].world_id, - "w".repeat(65) - ); - } - - #[test] - fn parsed_document_media_type_must_be_nfc() { - let nfc = ArtifactLog::default() - .sign( - &key(1), - &Kind::Document(Document { - media_type: "application/json".to_owned(), - content: json!({ "text": "ok" }), - }), - ) - .unwrap(); - assert!(matches!(nfc.parsed(), Ok(Some(Kind::Document(_))))); - - let decomposed = sign_kind_unchecked( - &key(1), - &Kind::Document(Document { - media_type: "application/jso\u{301}n".to_owned(), - content: json!({ "text": "ok" }), - }), - ); - assert!(decomposed.parsed().is_err()); - } - - #[test] - fn parsed_tag_name_must_be_nfc() { - let control = ArtifactLog::default() - .sign(&key(1), &author_tag(&public(2), 1)) - .unwrap(); - assert!(matches!(control.parsed(), Ok(Some(Kind::Tag(_))))); - - let decomposed = sign_kind_unchecked( - &key(1), - &Kind::Tag(Tag { - subject: public(2), - name: "e\u{301}".to_owned(), - value: None, - }), - ); - assert!(decomposed.parsed().is_err()); - } - - #[test] - fn parsed_tag_value_must_be_nfc() { - let control = ArtifactLog::default() - .sign(&key(1), &author_tag(&public(2), 1)) - .unwrap(); - assert!(matches!(control.parsed(), Ok(Some(Kind::Tag(_))))); - - let decomposed = sign_kind_unchecked( - &key(1), - &Kind::Tag(Tag { - subject: public(2), - name: "author".to_owned(), - value: Some("e\u{301}".to_owned()), - }), - ); - assert!(decomposed.parsed().is_err()); - } - #[tokio::test] async fn a_document_and_its_author_tag_travel_over_iroh() { let mut author = Directory::new(); @@ -2613,7 +380,6 @@ mod tests { other => panic!("expected a tag, got {other:?}"), } } - #[test] fn an_artifact_with_a_non_canonical_s_is_refused() { let key = SigningKey::from_bytes(&[7; 32]); @@ -2624,7 +390,6 @@ mod tests { artifact.signature = hex_encode(&with_non_canonical_s(raw)); assert!(artifact.verify().is_err()); } - #[test] fn an_artifact_under_a_small_order_key_is_refused() { let author = hex_encode(&IDENTITY_KEY); @@ -2642,7 +407,6 @@ mod tests { }; assert!(artifact.verify().is_err()); } - /// A hundred documents at the size limit would be about 6.4 MB in one page, /// far over the 1 MiB frame. The pull must take several pages. #[tokio::test] @@ -2686,104 +450,4 @@ mod tests { assert!(outcome.refused.is_none()); assert_eq!(reader.artifacts().head_seq(&ann), 100); } - - /// A home server that answers every pull with `0` as one page, whatever the budget. - #[derive(Debug)] - struct OverfullPage(Vec); - - impl ProtocolHandler for OverfullPage { - async fn accept(&self, conn: Connection) -> Result<(), AcceptError> { - let (mut send, mut recv) = conn.accept_bi().await?; - let _request = read_frame(&mut recv).await.map_err(refused)?; - let bytes = serde_json::to_vec(&Page { - artifacts: self.0.clone(), - }) - .map_err(|error| refused(error.into()))?; - write_frame(&mut send, &bytes).await.map_err(refused)?; - send.finish()?; - conn.closed().await; - Ok(()) - } - } - - /// What a pull of `public(1)` gets from a server that sends `artifacts` as one page. - async fn pulled_from_overfull(artifacts: Vec) -> Result> { - let server = endpoint().await; - let _router = Router::builder(server.clone()) - .accept(PULL_ALPN, OverfullPage(artifacts)) - .spawn(); - let client = endpoint().await; - fetch_page(&client, loopback(&server), &public(1), 0).await - } - - /// The client checks the budget of each page it is sent. A page of several - /// artifacts over the budget is refused, and one oversized artifact alone is not. - #[tokio::test] - async fn a_page_over_the_byte_budget_is_refused_and_a_lone_oversized_artifact_is_not() { - let mut log = ArtifactLog::default(); - let mut documents = Vec::new(); - for _ in 0..5 { - let next = log - .sign(&key(1), &document(&"x".repeat(MAX_DOCUMENT_BYTES - 32))) - .unwrap(); - log.insert(next.clone()).unwrap(); - documents.push(next); - } - let error = pulled_from_overfull(documents).await.unwrap_err(); - assert!( - format!("{error:#}").contains("over its byte budget"), - "{error:#}" - ); - - let lone = unknown_kind_of_size(PAGE_BYTES + 1024); - let pulled = pulled_from_overfull(vec![lone]).await.unwrap(); - assert_eq!(pulled.len(), 1); - } - - /// A pull to an address nothing answers must end at its deadline, not wait out - /// the handshake. - #[tokio::test] - async fn a_pull_from_an_unanswered_address_ends_at_its_deadline() { - let client = endpoint().await; - let mut directory = Directory::new(); - let started = Instant::now(); - let error = pull_within( - &client, - unanswered_addr(), - &public(1), - &mut directory, - Duration::from_millis(500), - ) - .await - .unwrap_err(); - assert!( - started.elapsed() < Duration::from_secs(5), - "{:?}", - started.elapsed() - ); - assert!(format!("{error:#}").contains("timed out"), "{error:#}"); - } - - /// A pull by node ID whose address lookup never answers must end at its deadline. - #[tokio::test] - async fn a_pull_whose_lookup_never_answers_ends_at_its_deadline() { - let client = endpoint_with_silent_lookup().await; - let mut directory = Directory::new(); - let started = Instant::now(); - let error = pull_within( - &client, - unanswered_id(), - &public(1), - &mut directory, - Duration::from_millis(500), - ) - .await - .unwrap_err(); - assert!( - started.elapsed() < Duration::from_secs(5), - "{:?}", - started.elapsed() - ); - assert!(format!("{error:#}").contains("timed out"), "{error:#}"); - } } diff --git a/pkgs/id/src/directory.rs b/pkgs/id/src/directory.rs index a810b46c62..1ce91a041c 100644 --- a/pkgs/id/src/directory.rs +++ b/pkgs/id/src/directory.rs @@ -96,6 +96,10 @@ pub struct Account { /// re-exported here at its historical path. pub use id_core::Refusal; +/// The envelope wire types live in `id-sync` (step 3c); this path is +/// the historical one callers use. +pub use id_sync::envelope::{Envelope, EnvelopeKind}; + macro_rules! refuse { ($kind:ident, $($arg:tt)*) => { return Err(Refusal::$kind(format!($($arg)*)).into()) @@ -295,16 +299,6 @@ pub enum Actor<'a> { Account(&'a str), } -/// What a friend envelope says. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub enum EnvelopeKind { - /// A request to become friends. - FriendRequest, - /// Acceptance of a request. - FriendAccept, -} - /// Longest time after it is made that an envelope is accepted. const ENVELOPE_TTL_MS: u64 = 30 * 24 * 60 * 60 * 1000; /// How far ahead of the receiving clock an envelope may be dated. @@ -313,99 +307,6 @@ const ENVELOPE_SKEW_MS: u64 = 5 * 60 * 1000; /// Friend requests one sender account may have pending on a server at once. pub const MAX_PENDING_FRIEND_REQUESTS: usize = 20; -/// A friend request or acceptance, signed by its sender's account key. Anyone -/// holding it can check the signature without asking the server. -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub struct Envelope { - /// What the envelope says. - pub kind: EnvelopeKind, - /// The sender's account ID. - pub from: String, - /// The recipient's account ID. - pub to: String, - /// The world ID of the server the envelope is for. - pub audience: String, - /// A random ID unique to this envelope. A request's ID names the request. - pub id: String, - /// For an acceptance, the ID of the request it accepts. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub request: Option, - /// When it was made, in Unix milliseconds. - pub at: u64, - /// Hex Ed25519 signature over the canonical body. - pub signature: String, -} - -#[derive(Serialize)] -struct SignedBody<'a> { - kind: EnvelopeKind, - from: &'a str, - to: &'a str, - audience: &'a str, - id: &'a str, - request: Option<&'a str>, - at: u64, -} - -impl Envelope { - fn body(&self) -> SignedBody<'_> { - SignedBody { - kind: self.kind, - from: &self.from, - to: &self.to, - audience: &self.audience, - id: &self.id, - request: self.request.as_deref(), - at: self.at, - } - } - - fn signed( - key: &SigningKey, - kind: EnvelopeKind, - from: &str, - to: &str, - audience: &str, - request: Option<&str>, - at: u64, - ) -> Result { - let mut nonce = [0_u8; 16]; - rand::rng().fill(&mut nonce); - let mut envelope = Self { - kind, - from: from.to_owned(), - to: to.to_owned(), - audience: audience.to_owned(), - id: hex_encode(&nonce), - request: request.map(str::to_owned), - at, - signature: String::new(), - }; - let signature = key.sign(&serde_json::to_vec(&envelope.body())?); - envelope.signature = hex_encode(&signature.to_bytes()); - Ok(envelope) - } - - /// Check the signature against the sender's account key. - /// - /// # Errors - /// - /// Fails if the sender is not a key, the signature is malformed, or it - /// does not match the body. - pub fn verify(&self) -> Result<()> { - let key = VerifyingKey::from_bytes( - &hex_to_array::<32>(&self.from).context("malformed envelope sender")?, - ) - .context("envelope sender is not a key")?; - let signature = Signature::from_bytes( - &hex_to_array::<64>(&self.signature).context("malformed envelope signature")?, - ); - let body = serde_json::to_vec(&self.body())?; - key.verify_strict(&body, &signature) - .context("envelope signature does not verify") - } -} - /// What receiving an envelope did to the directory. #[derive(Clone, Debug, PartialEq, Eq)] pub enum Received { diff --git a/pkgs/id/src/envelope_net.rs b/pkgs/id/src/envelope_net.rs index ade727d26c..8d74d5cc51 100644 --- a/pkgs/id/src/envelope_net.rs +++ b/pkgs/id/src/envelope_net.rs @@ -1,224 +1,9 @@ -//! Iroh transport for friend envelopes (`/id-envelope/1`) and signed artifacts -//! (`/id-artifact-push/1`). -//! -//! One bidirectional stream carries one payload: the sender writes a frame -//! holding the payload's JSON, and the receiver answers with a frame holding a -//! [`Reply`]. The payload's signature is what makes it trusted, not the iroh -//! node that delivered it. +//! Facade re-export of the envelope transport (moved to `id-sync` in +//! step 3c of the crate split, #4406). The tests below stay here: they +//! serve envelopes from a real world hub and directory, which live in +//! the facade until steps 5-6. -use std::time::Duration; - -use anyhow::{Context, Result}; -use iroh::{ - Endpoint, EndpointAddr, - endpoint::Connection, - protocol::{AcceptError, ProtocolHandler}, -}; -use serde::{Deserialize, Serialize}; - -use crate::connectivity::connect; -use crate::directory::{Envelope, Received, Refusal}; -use crate::directory_auth::Caller; -use crate::directory_view::{DirectoryAction, DirectoryOutcome}; -use crate::envelope_outbox::Outcome; -use crate::frames::{read_frame, write_frame}; -use crate::world_hub::WorldHub; - -/// ALPN for friend envelopes. Within version 1 fields may be added; removing or -/// changing one needs `/id-envelope/2`. -pub const ENVELOPE_ALPN: &[u8] = b"/id-envelope/1"; - -const TIMEOUT: Duration = Duration::from_secs(30); - -/// The answer to one frame. `Refused` will never succeed; `Retry` may. -#[derive(Debug, Serialize, Deserialize)] -#[serde(tag = "status", rename_all = "snake_case")] -pub enum Reply { - /// The frame was applied. - Applied, - /// The frame was already applied. - Duplicate, - /// The frame is invalid and must not be sent again. - Refused { - /// Why it was refused. - message: String, - }, - /// The frame could not be applied now but may be later. - Retry { - /// Why it could not be applied now. - message: String, - }, -} - -/// Sends `envelope` to the node at `target`, and says whether it is done. -pub async fn deliver( - endpoint: &Endpoint, - target: impl Into, - envelope: &Envelope, -) -> Outcome { - let json = match serde_json::to_vec(envelope) { - Ok(json) => json, - Err(error) => return Outcome::Refused(format!("envelope does not encode: {error}")), - }; - send(endpoint, ENVELOPE_ALPN, target.into(), &json).await -} - -/// Sends one frame on `alpn` to `target`, and says whether the peer took it. -/// The whole delivery, address lookup included, must finish within [`TIMEOUT`]. -pub async fn send(endpoint: &Endpoint, alpn: &[u8], target: EndpointAddr, json: &[u8]) -> Outcome { - send_within(endpoint, alpn, target, json, TIMEOUT).await -} - -/// [`send`] with `limit` on the whole delivery. -pub async fn send_within( - endpoint: &Endpoint, - alpn: &[u8], - target: EndpointAddr, - json: &[u8], - limit: Duration, -) -> Outcome { - match tokio::time::timeout(limit, exchange(endpoint, alpn, target, json)).await { - Ok(Ok(Reply::Applied | Reply::Duplicate)) => Outcome::Delivered, - Ok(Ok(Reply::Refused { message })) => Outcome::Refused(message), - Ok(Ok(Reply::Retry { message })) => Outcome::Retry(message), - Ok(Err(error)) => Outcome::Retry(format!("{error:#}")), - Err(_) => Outcome::Retry("delivery timed out".to_owned()), - } -} - -async fn exchange( - endpoint: &Endpoint, - alpn: &[u8], - target: EndpointAddr, - json: &[u8], -) -> Result { - let conn = connect(endpoint, target, alpn) - .await - .context("connecting to the recipient's server")?; - let reply = async { - let (mut send, mut recv) = conn.open_bi().await.context("opening a stream")?; - write_frame(&mut send, json).await?; - send.finish().context("finishing the request")?; - let frame = read_frame(&mut recv).await?.context("no reply")?; - serde_json::from_slice::(&frame).context("malformed reply") - } - .await; - conn.close(0_u32.into(), b"done"); - reply -} - -/// Accepts friend envelopes over Iroh. Register with -/// `Router::builder(..).accept(ENVELOPE_ALPN, EnvelopeProtocol::new(hub))`. -#[derive(Clone, Debug)] -pub struct EnvelopeProtocol { - hub: WorldHub, -} - -impl EnvelopeProtocol { - /// Serve the friend envelopes of every world in `hub`. - #[must_use] - pub const fn new(hub: WorldHub) -> Self { - Self { hub } - } -} - -impl ProtocolHandler for EnvelopeProtocol { - async fn accept(&self, conn: Connection) -> Result<(), AcceptError> { - let hub = self.hub.clone(); - answer_frames(&conn, move |body| { - let hub = hub.clone(); - async move { receive(&hub, &body).await } - }) - .await - } -} - -/// Answers frames sequentially on `conn` with the [`Reply`] `receive` gives it. -/// Each stream is bounded by [`TIMEOUT`]; a timed-out stream is reset and the -/// accept loop advances to the next stream. -pub async fn answer_frames(conn: &Connection, receive: F) -> Result<(), AcceptError> -where - F: Fn(Vec) -> Fut, - Fut: Future + Send, -{ - answer_frames_within(conn, receive, TIMEOUT).await -} - -async fn answer_frames_within( - conn: &Connection, - receive: F, - deadline: Duration, -) -> Result<(), AcceptError> -where - F: Fn(Vec) -> Fut, - Fut: Future + Send, -{ - while let Ok((mut send, mut recv)) = conn.accept_bi().await { - let timed_out = tokio::time::timeout(deadline, async { - let reply = match read_frame(&mut recv).await { - Ok(Some(body)) => receive(body).await, - Ok(None) => return, - Err(error) => Reply::Refused { - message: format!("{error:#}"), - }, - }; - let Ok(json) = serde_json::to_vec(&reply) else { - return; - }; - if write_frame(&mut send, &json).await.is_ok() { - let _ = send.finish(); - } - }) - .await - .is_err(); - if timed_out { - // `read_frame` is not cancel-safe. Abandon both halves rather - // than attempting to reuse a partially consumed stream. - let _ = send.reset(0_u32.into()); - let _ = recv.stop(0_u32.into()); - } - } - Ok(()) -} - -async fn receive(hub: &WorldHub, body: &[u8]) -> Reply { - let envelope: Envelope = match serde_json::from_slice(body) { - Ok(envelope) => envelope, - Err(error) => { - return Reply::Refused { - message: format!("not an envelope: {error}"), - }; - } - }; - let Ok(lease) = hub.lease(None, None).await else { - return Reply::Retry { - message: "the server is busy; try again".to_owned(), - }; - }; - match lease - .service() - .directory(Caller::default(), DirectoryAction::Receive { envelope }) - .await - { - Ok(DirectoryOutcome { - received: Some(Received::Applied(_)), - .. - }) => Reply::Applied, - Ok(DirectoryOutcome { - received: Some(Received::Duplicate), - .. - }) => Reply::Duplicate, - Ok(_) => Reply::Retry { - message: "envelope was not received".to_owned(), - }, - Err(error) if error.downcast_ref::().is_some() => Reply::Refused { - message: format!("{error:#}"), - }, - Err(error) => Reply::Retry { - message: format!("{error:#}"), - }, - } -} +pub use id_sync::envelope_net::*; #[cfg(test)] #[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] @@ -235,17 +20,17 @@ mod tests { use tokio::sync::Mutex; use super::*; - use crate::commands::put::add_raw; - use crate::connectivity::silent::{ - endpoint_with_silent_lookup, unanswered_addr, unanswered_id, - }; - use crate::directory::Directory; + use iroh::{Endpoint, EndpointAddr}; + + use crate::directory::{Directory, Envelope}; + use crate::envelope_outbox::Outcome; + use crate::world_hub::WorldHub; + use crate::directory_auth::Caller; + use crate::directory_view::DirectoryAction; use crate::envelope_outbox::{Finish, Outbox, flush}; use crate::world::{WorldCore, WorldHandle, WorldLimits}; use crate::world_session::WorldService; - const NOW: u64 = 1_000_000_000; - async fn endpoint() -> Endpoint { Endpoint::builder(presets::Minimal) .relay_mode(RelayMode::Disabled) @@ -253,7 +38,6 @@ mod tests { .await .unwrap() } - async fn endpoint_with(lookup: &MemoryLookup) -> Endpoint { Endpoint::builder(presets::Minimal) .relay_mode(RelayMode::Disabled) @@ -262,65 +46,6 @@ mod tests { .await .unwrap() } - - fn loopback_addr(ep: &Endpoint) -> EndpointAddr { - EndpointAddr::from_parts( - ep.id(), - ep.bound_sockets().iter().map(|addr| { - let ip = if addr.ip().is_unspecified() { - std::net::Ipv4Addr::LOCALHOST.into() - } else { - addr.ip() - }; - iroh::TransportAddr::Ip(std::net::SocketAddr::new(ip, addr.port())) - }), - ) - } - - /// Test-only receiver for exercising the raw frame transport. This is not - /// the production [`EnvelopeProtocol`], which accepts directory envelopes - /// and deliberately refuses chat-frame JSON. - #[derive(Clone, Debug)] - struct CaptureFrames(Arc>>>); - - impl ProtocolHandler for CaptureFrames { - async fn accept(&self, conn: Connection) -> Result<(), AcceptError> { - let frames = self.0.clone(); - answer_frames(&conn, move |body| { - let frames = frames.clone(); - async move { - frames.lock().await.push(body); - Reply::Applied - } - }) - .await - } - } - - #[derive(Clone, Debug)] - struct DeadlineCaptureFrames { - frames: Arc>>>, - deadline: Duration, - } - - impl ProtocolHandler for DeadlineCaptureFrames { - async fn accept(&self, conn: Connection) -> Result<(), AcceptError> { - let frames = self.frames.clone(); - answer_frames_within( - &conn, - move |body| { - let frames = frames.clone(); - async move { - frames.lock().await.push(body); - Reply::Applied - } - }, - self.deadline, - ) - .await - } - } - /// A lobby on a node that is reachable only over loopback. async fn lobby(ep: &Endpoint) -> (Router, EndpointAddr, String) { let world = WorldHandle::spawn(WorldCore::new("lobby", WorldLimits::default()).unwrap()); @@ -355,7 +80,6 @@ mod tests { ); (router, addr, bo) } - fn sent_from_home(to: &str, audience: &str, at: u64) -> Envelope { let mut home = Directory::new(); let (credential, _) = home.sign_up("Ann").unwrap(); @@ -363,7 +87,6 @@ mod tests { .unwrap() .0 } - #[tokio::test] async fn an_envelope_is_applied_once_and_refusals_are_permanent() { let server = endpoint().await; @@ -401,186 +124,6 @@ mod tests { Outcome::Refused(_) )); } - - /// A throwaway transport fixture for the proposed chat frame. It proves - /// byte-preserving exchange on the existing ALPN and a local content-hash - /// hit; it does not test CLI routing, production envelope acceptance, or - /// chat signature verification. - #[tokio::test] - async fn test_review_gated_chat_frame_round_trips_and_resolves_local_blob() { - let alice = endpoint().await; - let bob = endpoint().await; - let alice_frames = Arc::new(Mutex::new(Vec::new())); - let bob_frames = Arc::new(Mutex::new(Vec::new())); - let alice_router = Router::builder(alice.clone()) - .accept(ENVELOPE_ALPN, CaptureFrames(alice_frames.clone())) - .spawn(); - let bob_router = Router::builder(bob.clone()) - .accept(ENVELOPE_ALPN, CaptureFrames(bob_frames.clone())) - .spawn(); - - let receiver_store: iroh_blobs::api::Store = MemStore::new().into(); - let blob_bytes = b"review-gated chat PoC local blob"; - let (blob_hash, _keep) = add_raw(&receiver_store, blob_bytes.to_vec()).await.unwrap(); - - let frame_alice_to_bob = serde_json::to_vec(&serde_json::json!({ - "v": 1, - "channel": "group:local-poc", - "author": alice.id().to_string(), - "seq": 1, - "after": [], - "text": "blob link fixture", - "links": [{ - "kind": "blob", - "hash": blob_hash.to_string(), - "author": alice.id().to_string() - }], - "sig": "test-only; no signature verification" - })) - .unwrap(); - let frame_bob_to_alice = serde_json::to_vec(&serde_json::json!({ - "v": 1, - "channel": "group:local-poc", - "author": bob.id().to_string(), - "seq": 1, - "after": [], - "text": "acknowledged", - "links": [], - "sig": "test-only; no signature verification" - })) - .unwrap(); - - println!( - "Alice -> Bob /id-envelope/1 frame bytes (UTF-8): {}", - String::from_utf8(frame_alice_to_bob.clone()).unwrap() - ); - println!( - "Bob -> Alice /id-envelope/1 frame bytes (UTF-8): {}", - String::from_utf8(frame_bob_to_alice.clone()).unwrap() - ); - - assert_eq!( - send_within( - &alice, - ENVELOPE_ALPN, - loopback_addr(&bob), - &frame_alice_to_bob, - Duration::from_secs(5), - ) - .await, - Outcome::Delivered - ); - assert_eq!( - send_within( - &bob, - ENVELOPE_ALPN, - loopback_addr(&alice), - &frame_bob_to_alice, - Duration::from_secs(5), - ) - .await, - Outcome::Delivered - ); - - assert_eq!( - bob_frames.lock().await.as_slice(), - &[frame_alice_to_bob.clone()] - ); - assert_eq!( - alice_frames.lock().await.as_slice(), - &[frame_bob_to_alice.clone()] - ); - - let received_alice_to_bob = bob_frames.lock().await[0].clone(); - let received_frame: serde_json::Value = - serde_json::from_slice(&received_alice_to_bob).unwrap(); - let linked_hash: Hash = received_frame["links"][0]["hash"] - .as_str() - .unwrap() - .parse() - .unwrap(); - assert_eq!(linked_hash, blob_hash); - assert!(receiver_store.blobs().has(linked_hash).await.unwrap()); - let resolved = receiver_store.blobs().get_bytes(linked_hash).await.unwrap(); - assert_eq!(&*resolved, blob_bytes); - assert_eq!(Hash::new(&*resolved), blob_hash); - println!( - "Bob local blob resolution: hash={blob_hash} bytes={} hash_verified=true", - resolved.len() - ); - - alice.close().await; - bob.close().await; - alice_router.shutdown().await.unwrap(); - bob_router.shutdown().await.unwrap(); - } - - #[tokio::test] - async fn an_unreachable_recipient_is_retried() { - let client = endpoint().await; - let gone = endpoint().await; - let gone_id = gone.id(); - gone.close().await; - let envelope = sent_from_home(&"ab".repeat(32), "lobby", crate::time::unix_ms()); - assert!(matches!( - deliver(&client, gone_id, &envelope).await, - Outcome::Retry(_) - )); - } - - #[tokio::test] - async fn a_partial_frame_times_out_before_the_next_stream_is_answered() { - let server = endpoint().await; - let client = endpoint().await; - let frames = Arc::new(Mutex::new(Vec::new())); - let router = Router::builder(server.clone()) - .accept( - ENVELOPE_ALPN, - DeadlineCaptureFrames { - frames: frames.clone(), - deadline: Duration::from_millis(100), - }, - ) - .spawn(); - let conn = connect(&client, loopback_addr(&server), ENVELOPE_ALPN) - .await - .unwrap(); - - let (mut first_send, mut first_recv) = conn.open_bi().await.unwrap(); - first_send.write_all(&[0, 0]).await.unwrap(); - - let (mut second_send, mut second_recv) = conn.open_bi().await.unwrap(); - write_frame(&mut second_send, b"valid second frame") - .await - .unwrap(); - second_send.finish().unwrap(); - - let second_reply = tokio::time::timeout(Duration::from_secs(2), async { - let frame = read_frame(&mut second_recv).await.unwrap().unwrap(); - serde_json::from_slice::(&frame).unwrap() - }) - .await - .expect("second stream should be answered after the first times out"); - assert!(matches!(second_reply, Reply::Applied)); - assert_eq!( - frames.lock().await.as_slice(), - &[b"valid second frame".to_vec()] - ); - - let first_reply = - tokio::time::timeout(Duration::from_secs(1), first_recv.read_to_end(16)).await; - assert!( - matches!(first_reply, Ok(Err(_))), - "first stream should be reset" - ); - - drop(first_send); - conn.close(0_u32.into(), b"done"); - client.close().await; - server.close().await; - router.shutdown().await.unwrap(); - } - #[tokio::test] async fn flush_delivers_due_envelopes_and_records_each_outcome() { let dir = tempfile::tempdir().unwrap(); @@ -613,47 +156,4 @@ mod tests { .count(); assert_eq!((delivered, refused), (1, 1)); } - - /// A delivery to an address nothing answers must give up at its deadline. - #[tokio::test] - async fn a_delivery_to_an_unanswered_address_gives_up_at_its_deadline() { - let client = endpoint().await; - let started = Instant::now(); - let outcome = send_within( - &client, - ENVELOPE_ALPN, - unanswered_addr(), - b"{}", - Duration::from_millis(500), - ) - .await; - assert!( - started.elapsed() < Duration::from_secs(5), - "{:?}", - started.elapsed() - ); - assert_eq!(outcome, Outcome::Retry("delivery timed out".to_owned())); - } - - /// A delivery by node ID whose address lookup never answers gives up at its - /// deadline. The lookup is inside the deadline, so this is the step that hung. - #[tokio::test] - async fn a_delivery_whose_lookup_never_answers_gives_up_at_its_deadline() { - let client = endpoint_with_silent_lookup().await; - let started = Instant::now(); - let outcome = send_within( - &client, - ENVELOPE_ALPN, - unanswered_id(), - b"{}", - Duration::from_millis(500), - ) - .await; - assert!( - started.elapsed() < Duration::from_secs(5), - "{:?}", - started.elapsed() - ); - assert_eq!(outcome, Outcome::Retry("delivery timed out".to_owned())); - } } diff --git a/pkgs/id/src/envelope_outbox.rs b/pkgs/id/src/envelope_outbox.rs index 8a769703bd..59daa65f42 100644 --- a/pkgs/id/src/envelope_outbox.rs +++ b/pkgs/id/src/envelope_outbox.rs @@ -1,1150 +1,4 @@ -//! A durable queue of what this server sends to other servers: friend envelopes -//! and signed artifacts, each to a target endpoint. -//! -//! Each change is one JSON line, synced before it counts. The file is replayed -//! on open, so an entry that was not finished survives a restart. A line cut -//! short by a crash was never acknowledged, so it is dropped on open. +//! Facade re-export of the durable outbox (moved to `id-sync` in step +//! 3c of the crate split, #4406). -use std::collections::{BTreeMap, VecDeque}; -#[cfg(unix)] -use std::fs::File; -use std::fs::{self, OpenOptions}; -use std::io::{self, Write}; -use std::path::{Path, PathBuf}; - -use anyhow::{Context, Result, anyhow, ensure}; -use serde::{Deserialize, Serialize}; -use tokio::sync::Mutex; - -use iroh::{Endpoint, EndpointAddr, EndpointId}; -use iroh_tickets::endpoint::EndpointTicket; - -use crate::artifact::{self, SignedArtifact}; -use crate::directory::Envelope; -use crate::envelope_net::deliver; - -/// Deliveries attempted before an envelope is given up. -pub const MAX_ATTEMPTS: u32 = 12; -/// The maximum number of newest finished entries retained by the outbox. -pub const MAX_FINISHED_ENTRIES: usize = 100; -const BASE_DELAY_MS: u64 = 60_000; -const MAX_DELAY_MS: u64 = 6 * 60 * 60 * 1000; - -/// How a queued envelope ended. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub enum Finish { - /// The recipient's server accepted it. - Delivered, - /// The recipient's server refused it, so it is not retried. - Refused, - /// Every attempt failed. - GaveUp, -} - -/// The result of one delivery attempt. -#[derive(Clone, Debug, PartialEq, Eq)] -pub enum Outcome { - /// The envelope was delivered or was already applied there. - Delivered, - /// The envelope will not be accepted, and retrying cannot change that. - Refused(String), - /// The attempt failed in a way a later attempt may fix. - Retry(String), -} - -/// What the outbox carries to another server. -#[derive(Clone, Debug, PartialEq, Eq)] -pub enum Payload { - /// A friend envelope, for the recipient's server. - Envelope(Envelope), - /// A signed artifact, for a home server that holds the account's chain. - Artifact(SignedArtifact), -} - -impl Payload { - /// The key the queue files this payload under, so one payload is queued once. - #[must_use] - pub fn key(&self, target: &str) -> String { - match self { - Self::Envelope(envelope) => envelope.id.clone(), - Self::Artifact(artifact) => format!("artifact {target} {}", artifact.hash), - } - } -} - -/// One queued payload and what has happened to it so far. -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct Entry { - /// The recipient: an endpoint ticket or a bare node ID. - pub target: String, - /// What to deliver. - pub payload: Payload, - /// Attempts made so far. - pub attempts: u32, - /// The earliest time the next attempt may run, in Unix milliseconds. - pub next_at: u64, - /// The reason for the last failed attempt or the final outcome. - pub last_error: Option, - /// Set once the payload is no longer queued. - pub finish: Option, -} - -#[derive(Serialize, Deserialize)] -#[serde(tag = "op", rename_all = "snake_case")] -enum Record { - Queued { - target: String, - envelope: Envelope, - }, - QueuedArtifact { - target: String, - artifact: SignedArtifact, - }, - Attempted { - id: String, - attempts: u32, - next_at: u64, - error: String, - }, - Finished { - id: String, - attempts: u32, - outcome: Finish, - detail: Option, - }, - Withdrawn { - id: String, - }, -} - -/// The queue, keyed by envelope ID. -/// -/// It retains the newest [`MAX_FINISHED_ENTRIES`] finished entries by finish -/// order, along with every unfinished entry. When replay drops older finished -/// entries, the journal is compacted on open. -#[derive(Debug)] -pub struct Outbox { - path: PathBuf, - entries: BTreeMap, - finished_order: VecDeque, -} - -impl Outbox { - /// Opens the queue at `path`, replaying every record already in it. - /// - /// # Errors - /// - /// Fails if the file cannot be read, a complete line is corrupt, or a - /// journal record violates the outbox state machine. - pub fn open(path: impl Into) -> Result { - let mut outbox = Self { - path: path.into(), - entries: BTreeMap::new(), - finished_order: VecDeque::new(), - }; - let bytes = match fs::read(&outbox.path) { - Ok(bytes) => bytes, - Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(outbox), - Err(error) => return Err(error).context("reading the envelope outbox"), - }; - let mut kept = 0; - let mut dropped_finished = false; - for (number, line) in bytes.split_inclusive(|byte| *byte == b'\n').enumerate() { - if !line.ends_with(b"\n") { - // The final line has no newline: a crash cut the append - // short. Parseable or not, it was never completely - // written, so it is torn and dropped — the same rule - // ArtifactLog::open and Directory::replay apply. Keeping - // a parseable torn line would let the next append merge - // two records onto one line and brick the queue (#1620). - // `kept` stays at the last complete line, so the file is - // truncated to it below. - break; - } - let text = std::str::from_utf8(line) - .with_context(|| format!("envelope outbox line {} is corrupt", number + 1))?; - if text.trim().is_empty() { - // Blank lines carry no records, but they are complete bytes in - // the journal and must remain before any later torn tail. - kept += line.len(); - continue; - } - match serde_json::from_str::(text.trim_end()) { - Ok(record) => { - dropped_finished |= outbox.apply(record).with_context(|| { - format!("envelope outbox line {} is refused", number + 1) - })?; - kept += line.len(); - } - Err(error) => { - return Err(error).with_context(|| { - format!("envelope outbox line {} is corrupt", number + 1) - }); - } - } - } - if kept < bytes.len() { - OpenOptions::new() - .write(true) - .open(&outbox.path)? - .set_len(kept as u64)?; - } - if dropped_finished { - outbox.compact_journal()?; - } - Ok(outbox) - } - - /// Queues `envelope` for delivery to the node `target`, due immediately. - /// - /// # Errors - /// - /// Fails if the node ID is malformed, the envelope is already queued, or the - /// record cannot be written. - pub fn enqueue(&mut self, target: &str, envelope: Envelope) -> Result<()> { - check_target(target)?; - self.enqueue_payload(&Payload::Envelope(envelope), target) - } - - /// Queues `artifact` for a home server at `target`, due immediately. - /// - /// # Errors - /// - /// Fails if the target is malformed, the artifact is already queued for it, - /// or the record cannot be written. - pub fn enqueue_artifact(&mut self, target: &str, artifact: SignedArtifact) -> Result<()> { - check_target(target)?; - self.enqueue_payload(&Payload::Artifact(artifact), target) - } - - fn enqueue_payload(&mut self, payload: &Payload, target: &str) -> Result<()> { - let key = payload.key(target); - ensure!(!self.entries.contains_key(&key), "{key} is already queued"); - let record = match payload { - Payload::Envelope(envelope) => Record::Queued { - target: target.to_owned(), - envelope: envelope.clone(), - }, - Payload::Artifact(artifact) => Record::QueuedArtifact { - target: target.to_owned(), - artifact: artifact.clone(), - }, - }; - self.commit(record) - } - - /// The IDs of envelopes that are queued and due at `now`. - #[must_use] - pub fn due(&self, now: u64) -> Vec { - self.entries - .iter() - .filter(|(_, entry)| entry.finish.is_none() && entry.next_at <= now) - .map(|(id, _)| id.clone()) - .collect() - } - - /// The queued envelope with `id`, finished or not. - #[must_use] - pub fn entry(&self, id: &str) -> Option<&Entry> { - self.entries.get(id) - } - - /// Removes an envelope that was queued but never attempted, as if it had - /// never been queued. - /// - /// # Errors - /// - /// Fails if `id` is not queued, has been attempted, or the record cannot be - /// written. - pub fn withdraw(&mut self, id: &str) -> Result<()> { - let entry = self.entries.get(id).context("envelope is not queued")?; - ensure!( - entry.attempts == 0 && entry.finish.is_none(), - "envelope {id} was already attempted" - ); - self.commit(Record::Withdrawn { id: id.to_owned() }) - } - - /// Records the outcome of an attempt made at `now`. - /// - /// # Errors - /// - /// Fails if `id` is not queued, or the record cannot be written. - pub fn record(&mut self, id: &str, now: u64, outcome: Outcome) -> Result<()> { - let entry = self.entries.get(id).context("envelope is not queued")?; - ensure!(entry.finish.is_none(), "envelope {id} already finished"); - let attempts = entry.attempts + 1; - let record = match outcome { - Outcome::Delivered => Record::Finished { - id: id.to_owned(), - attempts, - outcome: Finish::Delivered, - detail: None, - }, - Outcome::Refused(error) => Record::Finished { - id: id.to_owned(), - attempts, - outcome: Finish::Refused, - detail: Some(error), - }, - Outcome::Retry(error) if attempts >= MAX_ATTEMPTS => Record::Finished { - id: id.to_owned(), - attempts, - outcome: Finish::GaveUp, - detail: Some(error), - }, - Outcome::Retry(error) => Record::Attempted { - id: id.to_owned(), - attempts, - next_at: now.saturating_add(backoff_ms(attempts)), - error, - }, - }; - self.commit(record) - } - - /// Every queued envelope, finished or not, in ID order. - pub fn entries(&self) -> impl Iterator { - self.entries.values() - } - - fn commit(&mut self, record: Record) -> Result<()> { - let mut line = serde_json::to_string(&record)?; - line.push('\n'); - let mut file = OpenOptions::new() - .create(true) - .append(true) - .open(&self.path)?; - file.write_all(line.as_bytes())?; - file.sync_data()?; - self.apply(record)?; - Ok(()) - } - - /// Applies a record and reports whether it evicted a finished entry. - fn apply(&mut self, record: Record) -> Result { - let mut dropped_finished = false; - match record { - Record::Queued { target, envelope } => { - self.insert_queued(target, Payload::Envelope(envelope))?; - } - Record::QueuedArtifact { target, artifact } => { - self.insert_queued(target, Payload::Artifact(artifact))?; - } - Record::Attempted { - id, - attempts, - next_at, - error, - } => { - let entry = self.entry_mut(&id)?; - ensure!(entry.finish.is_none(), "envelope {id} already finished"); - let expected_attempts = entry.attempts + 1; - ensure!( - attempts == expected_attempts, - "outbox record for envelope {id} expected {expected_attempts} attempts, got {attempts}" - ); - ensure!( - attempts < MAX_ATTEMPTS, - "outbox record attempts envelope {id} at the retry limit" - ); - entry.attempts = attempts; - entry.next_at = next_at; - entry.last_error = Some(error); - } - Record::Finished { - id, - attempts, - outcome, - detail, - } => { - let entry = self.entry_mut(&id)?; - ensure!(entry.finish.is_none(), "envelope {id} already finished"); - let expected_attempts = entry.attempts + 1; - ensure!( - attempts == expected_attempts, - "outbox record for envelope {id} expected {expected_attempts} attempts, got {attempts}" - ); - ensure!( - attempts <= MAX_ATTEMPTS, - "outbox record exceeds the retry limit for envelope {id}" - ); - match outcome { - Finish::Delivered => ensure!( - detail.is_none(), - "delivered outbox record for envelope {id} has refusal detail" - ), - Finish::Refused => ensure!( - detail.is_some(), - "refused outbox record for envelope {id} is missing detail" - ), - Finish::GaveUp => { - ensure!( - attempts == MAX_ATTEMPTS, - "gave-up outbox record for envelope {id} is not at the retry limit" - ); - ensure!( - detail.is_some(), - "gave-up outbox record for envelope {id} is missing detail" - ); - } - } - entry.attempts = attempts; - entry.finish = Some(outcome); - entry.last_error = detail; - self.finished_order.retain(|finished_id| finished_id != &id); - self.finished_order.push_back(id); - if self.finished_order.len() > MAX_FINISHED_ENTRIES { - if let Some(oldest) = self.finished_order.pop_front() { - self.entries.remove(&oldest); - dropped_finished = true; - } - } - } - Record::Withdrawn { id } => { - let entry = self - .entries - .get(&id) - .with_context(|| format!("outbox record withdraws unknown envelope {id}"))?; - ensure!( - entry.attempts == 0 && entry.finish.is_none(), - "envelope {id} was already attempted" - ); - self.finished_order.retain(|finished_id| finished_id != &id); - self.entries.remove(&id); - } - } - Ok(dropped_finished) - } - - /// Rewrites the journal as a snapshot of the retained entries. - fn compact_journal(&self) -> Result<()> { - let mut temporary_path = self.path.as_os_str().to_owned(); - temporary_path.push(".compact.tmp"); - let temporary_path = PathBuf::from(temporary_path); - let permissions = fs::metadata(&self.path)?.permissions(); - let mut file = OpenOptions::new() - .create(true) - .truncate(true) - .write(true) - .open(&temporary_path) - .context("creating the compacted envelope outbox")?; - - for record in self.compact_records()? { - serde_json::to_writer(&mut file, &record)?; - file.write_all(b"\n")?; - } - fs::set_permissions(&temporary_path, permissions)?; - file.sync_all()?; - drop(file); - replace_journal(&temporary_path, &self.path) - .context("replacing the envelope outbox with its compacted journal")?; - - #[cfg(unix)] - { - let parent = self - .path - .parent() - .filter(|parent| !parent.as_os_str().is_empty()) - .unwrap_or_else(|| Path::new(".")); - File::open(parent)?.sync_all()?; - } - Ok(()) - } - - /// Builds a replayable snapshot while preserving the finish-order queue. - fn compact_records(&self) -> Result> { - // NOTE: the snapshot must satisfy the same replay validation as a - // live journal (see `apply`): every `Attempted` record increments - // the attempt count by exactly one, and a `Finished` record carries - // the count after its final attempt. A snapshot therefore replays - // an entry's attempt count incrementally (`push_attempt_history`) - // instead of jumping straight to the final count. - let mut records = Vec::with_capacity(self.entries.len() * 2); - for entry in self.entries.values() { - records.push(match &entry.payload { - Payload::Envelope(envelope) => Record::Queued { - target: entry.target.clone(), - envelope: envelope.clone(), - }, - Payload::Artifact(artifact) => Record::QueuedArtifact { - target: entry.target.clone(), - artifact: artifact.clone(), - }, - }); - } - - // Pending entries have no finish-order significance, so their retry - // state can be replayed before the finished entries. - for (id, entry) in &self.entries { - if entry.finish.is_none() - && (entry.attempts > 0 || entry.next_at != 0 || entry.last_error.is_some()) - { - push_attempt_increments(&mut records, id, entry.attempts); - if entry.attempts > 0 { - records.push(Record::Attempted { - id: id.clone(), - attempts: entry.attempts, - next_at: entry.next_at, - error: entry.last_error.clone().unwrap_or_default(), - }); - } - } - } - - for id in &self.finished_order { - let entry = self - .entries - .get(id) - .with_context(|| format!("finished entry {id} is missing during compaction"))?; - // The `Finished` record itself carries the final attempt count, - // so only the increments below it are replayed as `Attempted`. - // A finished entry's `next_at` is inert (`due` skips finished - // entries), so the increments use a placeholder. - push_attempt_increments(&mut records, id, entry.attempts); - records.push(Record::Finished { - id: id.clone(), - attempts: entry.attempts, - outcome: entry - .finish - .context("finished-order entry has no finish during compaction")?, - detail: entry.last_error.clone(), - }); - } - Ok(records) - } - - fn insert_queued(&mut self, target: String, payload: Payload) -> Result<()> { - // The live path checks the target in the enqueue verbs - // before committing; replay must hold the same line, or a journal - // record the live API could never produce loads as a due entry and - // only fails at flush time as a spurious refusal (#5635). - check_target(&target)?; - let key = payload.key(&target); - ensure!(!self.entries.contains_key(&key), "{key} is queued twice"); - self.entries.insert( - key, - Entry { - target, - payload, - attempts: 0, - next_at: 0, - last_error: None, - finish: None, - }, - ); - Ok(()) - } - - fn entry_mut(&mut self, id: &str) -> Result<&mut Entry> { - self.entries - .get_mut(id) - .with_context(|| format!("outbox record names unknown envelope {id}")) - } -} - -/// Pushes placeholder `Attempted` records for the counts `1..below`, so a -/// compacted snapshot replays an entry's attempt count one increment at a -/// time, as replay validation requires. The caller pushes the final record -/// (the real `Attempted` for a pending entry, or the `Finished` record) -/// itself; placeholders carry no retry state. -fn push_attempt_increments(records: &mut Vec, id: &str, below: u32) { - for attempts in 1..below { - records.push(Record::Attempted { - id: id.to_owned(), - attempts, - next_at: 0, - error: String::new(), - }); - } -} - -/// Replaces the journal at `destination` with the compacted file at -/// `temporary`, as atomically as the platform allows. -#[cfg(not(windows))] -fn replace_journal(temporary: &Path, destination: &Path) -> io::Result<()> { - // rename(2) replaces an existing destination atomically. - fs::rename(temporary, destination) -} - -/// Replaces the journal at `destination` with the compacted file at -/// `temporary`, as atomically as the platform allows. -#[cfg(windows)] -fn replace_journal(temporary: &Path, destination: &Path) -> io::Result<()> { - // `fs::rename` cannot replace an existing file on Windows, and the - // journal always exists by the time compaction runs, so a plain rename - // would fail every compaction there (Copilot review on PR #4710). - // Remove-then-rename is the fallback: it is NOT atomic — a crash - // between the two calls leaves the journal missing and only the - // `.compact.tmp` file behind — but compaction only runs after a full - // successful replay, and the alternative on Windows is that - // compaction (and with it `Outbox::open`) never succeeds at all. - if destination.exists() { - fs::remove_file(destination)?; - } - fs::rename(temporary, destination) -} - -/// Delivers every envelope due at `now`, recording each outcome as it happens. -/// -/// The lock is released while a delivery is in flight, so enqueueing is not -/// held up by a slow recipient. Returns how many attempts were made. -/// -/// # Errors -/// -/// Fails if an outcome cannot be written. Envelopes already recorded stay -/// recorded. -pub async fn flush(outbox: &Mutex, endpoint: &Endpoint, now: u64) -> Result { - let due: Vec<(String, String, Payload)> = { - let queue = outbox.lock().await; - queue - .due(now) - .into_iter() - .filter_map(|id| { - let entry = queue.entry(&id)?; - Some((id.clone(), entry.target.clone(), entry.payload.clone())) - }) - .collect() - }; - for (id, target, payload) in &due { - let outcome = match check_target(target) { - Ok(addr) => match payload { - Payload::Envelope(envelope) => deliver(endpoint, addr, envelope).await, - Payload::Artifact(artifact) => artifact::push(endpoint, addr, artifact).await, - }, - Err(error) => Outcome::Refused(format!("{error:#}")), - }; - outbox.lock().await.record(id, now, outcome)?; - } - Ok(due.len()) -} - -/// Reads a recipient: an endpoint ticket, or a bare node ID that resolves -/// through the discovery services the endpoint uses. -/// -/// # Errors -/// -/// Fails if `target` is neither, so nothing is queued for it. -pub fn check_target(target: &str) -> Result { - if let Ok(ticket) = target.parse::() { - return Ok(ticket.endpoint_addr().clone()); - } - target - .parse::() - .map(EndpointAddr::from) - .map_err(|error| anyhow!("{target} is neither an endpoint ticket nor a node ID: {error}")) -} - -fn backoff_ms(attempts: u32) -> u64 { - let shift = attempts.saturating_sub(1).min(20); - (BASE_DELAY_MS << shift).min(MAX_DELAY_MS) -} - -#[cfg(test)] -#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] -mod tests { - use super::*; - use crate::directory::EnvelopeKind; - - const NOW: u64 = 1_000_000_000; - const MINUTE: u64 = 60_000; - - fn envelope(id: &str) -> Envelope { - Envelope { - kind: EnvelopeKind::FriendRequest, - from: "ann".to_owned(), - to: "bo".to_owned(), - audience: "club".to_owned(), - id: id.to_owned(), - request: None, - at: NOW, - signature: "00".to_owned(), - } - } - - fn target() -> String { - iroh::SecretKey::from_bytes(&[7; 32]).public().to_string() - } - - fn path(dir: &tempfile::TempDir) -> PathBuf { - dir.path().join("outbox.jsonl") - } - - fn queued_line(id: &str) -> String { - let dir = tempfile::tempdir().unwrap(); - let mut outbox = Outbox::open(path(&dir)).unwrap(); - outbox.enqueue(&target(), envelope(id)).unwrap(); - fs::read_to_string(path(&dir)) - .unwrap() - .trim_end_matches('\n') - .to_owned() - } - - fn queued_record(id: &str) -> Record { - Record::Queued { - target: target(), - envelope: envelope(id), - } - } - - fn write_records(dir: &tempfile::TempDir, records: impl IntoIterator) { - let text = records - .into_iter() - .map(|record| format!("{}\n", serde_json::to_string(&record).unwrap())) - .collect::(); - fs::write(path(dir), text).unwrap(); - } - - fn assert_replay_error(records: impl IntoIterator, line: usize, reason: &str) { - let dir = tempfile::tempdir().unwrap(); - write_records(&dir, records); - let error = Outbox::open(path(&dir)) - .err() - .expect("invalid replay should fail"); - let message = format!("{error:#}"); - assert!(message.contains(&format!("line {line}")), "{message}"); - assert!(message.contains(reason), "{message}"); - } - - #[test] - fn a_target_is_a_ticket_or_a_bare_node_id() { - let id = iroh::SecretKey::from_bytes(&[7; 32]).public(); - let addr = EndpointAddr::from(id); - let ticket = EndpointTicket::new(addr.clone()).to_string(); - assert_eq!(check_target(&ticket).unwrap(), addr); - assert_eq!(check_target(&id.to_string()).unwrap(), addr); - assert!(check_target("not a target").is_err()); - } - - #[test] - fn queued_envelopes_survive_a_restart() { - let dir = tempfile::tempdir().unwrap(); - let mut outbox = Outbox::open(path(&dir)).unwrap(); - outbox.enqueue(&target(), envelope("e1")).unwrap(); - drop(outbox); - - let reopened = Outbox::open(path(&dir)).unwrap(); - assert_eq!(reopened.due(NOW), vec!["e1".to_owned()]); - assert_eq!( - reopened.entry("e1").unwrap().payload, - Payload::Envelope(envelope("e1")) - ); - } - - #[test] - fn a_retry_waits_for_its_backoff_and_then_gives_up() { - let dir = tempfile::tempdir().unwrap(); - let mut outbox = Outbox::open(path(&dir)).unwrap(); - outbox.enqueue(&target(), envelope("e1")).unwrap(); - - outbox - .record("e1", NOW, Outcome::Retry("down".to_owned())) - .unwrap(); - let entry = outbox.entry("e1").unwrap(); - assert_eq!((entry.attempts, entry.next_at), (1, NOW + MINUTE)); - assert!(outbox.due(NOW + MINUTE - 1).is_empty()); - assert_eq!(outbox.due(NOW + MINUTE), vec!["e1".to_owned()]); - - for attempt in 2..=MAX_ATTEMPTS { - outbox - .record("e1", NOW, Outcome::Retry("down".to_owned())) - .unwrap(); - assert_eq!(outbox.entry("e1").unwrap().attempts, attempt); - } - let entry = outbox.entry("e1").unwrap(); - assert_eq!(entry.finish, Some(Finish::GaveUp)); - assert!(outbox.due(u64::MAX).is_empty()); - - let reopened = Outbox::open(path(&dir)).unwrap(); - assert_eq!(reopened.entry("e1").unwrap().finish, Some(Finish::GaveUp)); - } - - #[test] - fn a_refusal_is_final() { - let dir = tempfile::tempdir().unwrap(); - let mut outbox = Outbox::open(path(&dir)).unwrap(); - outbox.enqueue(&target(), envelope("e1")).unwrap(); - outbox - .record("e1", NOW, Outcome::Refused("bad signature".to_owned())) - .unwrap(); - let entry = outbox.entry("e1").unwrap(); - assert_eq!(entry.finish, Some(Finish::Refused)); - assert_eq!(entry.last_error.as_deref(), Some("bad signature")); - assert!(outbox.due(u64::MAX).is_empty()); - assert!(outbox.record("e1", NOW, Outcome::Delivered).is_err()); - drop(outbox); - - let reopened = Outbox::open(path(&dir)).unwrap(); - assert_eq!(reopened.entry("e1").unwrap().finish, Some(Finish::Refused)); - assert_eq!( - reopened.entry("e1").unwrap().last_error.as_deref(), - Some("bad signature") - ); - } - - #[test] - fn a_delivery_survives_a_restart() { - let dir = tempfile::tempdir().unwrap(); - let mut outbox = Outbox::open(path(&dir)).unwrap(); - outbox.enqueue(&target(), envelope("e1")).unwrap(); - outbox.record("e1", NOW, Outcome::Delivered).unwrap(); - drop(outbox); - - let reopened = Outbox::open(path(&dir)).unwrap(); - assert_eq!( - reopened.entry("e1").unwrap().finish, - Some(Finish::Delivered) - ); - assert!(reopened.entry("e1").unwrap().last_error.is_none()); - } - - #[test] - fn runtime_retains_the_newest_finished_entries_in_finish_order() { - let dir = tempfile::tempdir().unwrap(); - let mut outbox = Outbox::open(path(&dir)).unwrap(); - let total = MAX_FINISHED_ENTRIES + 5; - - for index in 0..total { - let id = format!("e{index:03}"); - outbox.enqueue(&target(), envelope(&id)).unwrap(); - } - for index in (0..total).step_by(2).chain((1..total).step_by(2)) { - let id = format!("e{index:03}"); - outbox.record(&id, NOW, Outcome::Delivered).unwrap(); - } - - assert_eq!( - outbox - .entries() - .filter(|entry| entry.finish.is_some()) - .count(), - MAX_FINISHED_ENTRIES - ); - for oldest in [0, 2, 4, 6, 8] { - assert!(outbox.entry(&format!("e{oldest:03}")).is_none()); - } - assert!(outbox.entry("e001").is_some()); - assert!(outbox.entry("e104").is_some()); - - outbox.enqueue(&target(), envelope("pending")).unwrap(); - assert_eq!(outbox.entries().count(), MAX_FINISHED_ENTRIES + 1); - assert_eq!(outbox.due(NOW), vec!["pending".to_owned()]); - } - - #[test] - fn replay_compacts_finished_history_and_preserves_state_and_finish_order() { - let dir = tempfile::tempdir().unwrap(); - let journal = path(&dir); - let mut outbox = Outbox::open(&journal).unwrap(); - let total = MAX_FINISHED_ENTRIES + 5; - - for index in 0..total { - let id = format!("e{index:03}"); - outbox.enqueue(&target(), envelope(&id)).unwrap(); - } - for index in (0..total).step_by(2).chain((1..total).step_by(2)) { - let id = format!("e{index:03}"); - outbox.record(&id, NOW, Outcome::Delivered).unwrap(); - } - outbox.enqueue(&target(), envelope("pending-now")).unwrap(); - outbox - .enqueue(&target(), envelope("pending-later")) - .unwrap(); - outbox - .record("pending-later", NOW, Outcome::Retry("down".to_owned())) - .unwrap(); - - let expected_entries = outbox.entries.clone(); - let expected_due_now = outbox.due(NOW); - let expected_due_later = outbox.due(NOW + MINUTE); - drop(outbox); - - // A parseable record without its trailing newline is still a torn tail; - // open must truncate it before compacting the completed history. - let mut file = OpenOptions::new().append(true).open(&journal).unwrap(); - file.write_all(queued_line("torn").as_bytes()).unwrap(); - drop(file); - - let reopened = Outbox::open(&journal).unwrap(); - assert_eq!(reopened.entries, expected_entries); - assert_eq!(reopened.due(NOW), expected_due_now); - assert_eq!(reopened.due(NOW + MINUTE), expected_due_later); - assert!(reopened.entry("torn").is_none()); - - let compacted = fs::read_to_string(&journal).unwrap(); - assert!(compacted.ends_with('\n')); - assert!(!compacted.contains("e000")); - assert!(!compacted.contains("e002")); - assert!(compacted.contains("e001")); - assert!(compacted.contains("pending-later")); - drop(reopened); - - let mut reopened_again = Outbox::open(&journal).unwrap(); - assert_eq!(reopened_again.entries, expected_entries); - assert_eq!(reopened_again.due(NOW), expected_due_now); - assert_eq!(reopened_again.due(NOW + MINUTE), expected_due_later); - assert_eq!(fs::read_to_string(&journal).unwrap(), compacted); - - // Compaction must keep the relative finish order so the next finish - // evicts the oldest entry that survived the first cap. - reopened_again - .enqueue(&target(), envelope("next-finish")) - .unwrap(); - reopened_again - .record("next-finish", NOW, Outcome::Delivered) - .unwrap(); - assert!(reopened_again.entry("e010").is_none()); - assert!(reopened_again.entry("e001").is_some()); - } - - #[test] - fn a_withdrawn_envelope_is_gone_and_stays_gone() { - let dir = tempfile::tempdir().unwrap(); - let mut outbox = Outbox::open(path(&dir)).unwrap(); - outbox.enqueue(&target(), envelope("e1")).unwrap(); - outbox.withdraw("e1").unwrap(); - assert!(outbox.entry("e1").is_none()); - assert!(outbox.due(u64::MAX).is_empty()); - assert!(outbox.withdraw("e1").is_err()); - drop(outbox); - - let reopened = Outbox::open(path(&dir)).unwrap(); - assert!(reopened.entry("e1").is_none()); - } - - #[test] - fn test_blank_and_whitespace_lines_are_skipped_and_kept() { - let dir = tempfile::tempdir().unwrap(); - let contents = format!("{}\n\n \t\r\n{}\n\n", queued_line("e1"), queued_line("e2")); - fs::write(path(&dir), &contents).unwrap(); - - let outbox = Outbox::open(path(&dir)).unwrap(); - assert!(outbox.entry("e1").is_some()); - assert!(outbox.entry("e2").is_some()); - assert_eq!(fs::read_to_string(path(&dir)).unwrap(), contents); - } - - #[test] - fn test_blank_lines_before_a_torn_tail_are_kept_when_the_tail_is_truncated() { - let dir = tempfile::tempdir().unwrap(); - let kept = format!("{}\n \t\n", queued_line("e1")); - fs::write(path(&dir), format!("{kept}{{\"op\":\"queued\"")).unwrap(); - - let outbox = Outbox::open(path(&dir)).unwrap(); - assert!(outbox.entry("e1").is_some()); - assert_eq!(fs::read_to_string(path(&dir)).unwrap(), kept); - } - - #[test] - fn a_torn_last_line_is_dropped_and_not_mixed_into_the_next_record() { - let dir = tempfile::tempdir().unwrap(); - let mut outbox = Outbox::open(path(&dir)).unwrap(); - outbox.enqueue(&target(), envelope("e1")).unwrap(); - drop(outbox); - let mut file = OpenOptions::new().append(true).open(path(&dir)).unwrap(); - // The tail is cut after the first byte of a multibyte name. - file.write_all(b"{\"name\":\"Jos\xc3").unwrap(); - drop(file); - - let mut outbox = Outbox::open(path(&dir)).unwrap(); - assert!(outbox.entry("e1").is_some()); - outbox.enqueue(&target(), envelope("e2")).unwrap(); - drop(outbox); - - let reopened = Outbox::open(path(&dir)).unwrap(); - assert!(reopened.entry("e1").is_some() && reopened.entry("e2").is_some()); - } - - #[test] - fn a_parseable_torn_last_line_is_also_dropped() { - // #1620: the torn tail here is a complete JSON record missing - // only its trailing newline. Before the fix, open accepted it, - // and the next append merged two records onto one line. - let dir = tempfile::tempdir().unwrap(); - let mut outbox = Outbox::open(path(&dir)).unwrap(); - outbox.enqueue(&target(), envelope("e1")).unwrap(); - drop(outbox); - // A whole record line for e2, written by a healthy outbox, with - // its newline stripped to simulate the crash cut. - let scratch = tempfile::tempdir().unwrap(); - let mut other = Outbox::open(path(&scratch)).unwrap(); - other.enqueue(&target(), envelope("e2")).unwrap(); - drop(other); - let line = fs::read_to_string(path(&scratch)).unwrap(); - let mut file = OpenOptions::new().append(true).open(path(&dir)).unwrap(); - file.write_all(line.trim_end_matches('\n').as_bytes()) - .unwrap(); - drop(file); - - let mut outbox = Outbox::open(path(&dir)).unwrap(); - assert!(outbox.entry("e1").is_some()); - assert!( - outbox.entry("e2").is_none(), - "the parseable torn record must be dropped, not accepted" - ); - // The file was truncated to the last complete line, so the next - // append starts on its own line and round-trips. - outbox.enqueue(&target(), envelope("e2")).unwrap(); - drop(outbox); - - let reopened = Outbox::open(path(&dir)).unwrap(); - assert!(reopened.entry("e1").is_some() && reopened.entry("e2").is_some()); - } - - #[test] - fn a_corrupt_complete_line_stops_the_load() { - let dir = tempfile::tempdir().unwrap(); - fs::write(path(&dir), "\nnot json\n").unwrap(); - let error = Outbox::open(path(&dir)).err().unwrap(); - assert!(format!("{error:#}").contains("envelope outbox line 2 is corrupt")); - } - - #[test] - fn replay_rejects_attempt_after_finish() { - assert_replay_error( - [ - queued_record("e1"), - Record::Finished { - id: "e1".to_owned(), - attempts: 1, - outcome: Finish::Delivered, - detail: None, - }, - Record::Attempted { - id: "e1".to_owned(), - attempts: 2, - next_at: NOW + MINUTE, - error: "down".to_owned(), - }, - ], - 3, - "already finished", - ); - } - - #[test] - fn replay_rejects_a_second_finish() { - assert_replay_error( - [ - queued_record("e1"), - Record::Finished { - id: "e1".to_owned(), - attempts: 1, - outcome: Finish::Delivered, - detail: None, - }, - Record::Finished { - id: "e1".to_owned(), - attempts: 2, - outcome: Finish::Refused, - detail: Some("bad signature".to_owned()), - }, - ], - 3, - "already finished", - ); - } - - #[test] - fn replay_rejects_attempt_count_regression() { - let mut records = vec![queued_record("e1")]; - for attempts in 1..=5 { - records.push(Record::Attempted { - id: "e1".to_owned(), - attempts, - next_at: NOW + u64::from(attempts) * MINUTE, - error: "down".to_owned(), - }); - } - records.push(Record::Attempted { - id: "e1".to_owned(), - attempts: 2, - next_at: NOW + 2 * MINUTE, - error: "down".to_owned(), - }); - - assert_replay_error(records, 7, "expected 6 attempts, got 2"); - } - - #[test] - fn replay_rejects_withdrawal_after_an_attempt() { - assert_replay_error( - [ - queued_record("e1"), - Record::Attempted { - id: "e1".to_owned(), - attempts: 1, - next_at: NOW + MINUTE, - error: "down".to_owned(), - }, - Record::Withdrawn { - id: "e1".to_owned(), - }, - ], - 3, - "already attempted", - ); - } - - #[test] - fn replay_rejects_withdrawal_after_finish() { - assert_replay_error( - [ - queued_record("e1"), - Record::Finished { - id: "e1".to_owned(), - attempts: 1, - outcome: Finish::Delivered, - detail: None, - }, - Record::Withdrawn { - id: "e1".to_owned(), - }, - ], - 3, - "already attempted", - ); - } - - #[test] - fn replay_rejects_a_queued_record_with_a_malformed_target() { - assert_replay_error( - [Record::Queued { - target: "not a target".to_owned(), - envelope: envelope("e1"), - }], - 1, - "is neither an endpoint ticket nor a node ID", - ); - } - - #[test] - fn replay_rejects_a_queued_artifact_record_with_a_malformed_target() { - let artifact = SignedArtifact { - author: "00".to_owned(), - seq: 1, - prev: String::new(), - kind: "note".to_owned(), - body: serde_json::Value::Null, - after: Vec::new(), - hash: "00".to_owned(), - signature: "00".to_owned(), - }; - assert_replay_error( - [Record::QueuedArtifact { - target: "not a target".to_owned(), - artifact, - }], - 1, - "is neither an endpoint ticket nor a node ID", - ); - } - - #[test] - fn a_node_id_is_required() { - assert!(check_target(&target()).is_ok()); - assert!(check_target("https://bo.example/envelope").is_err()); - assert!(check_target("not a node").is_err()); - } -} +pub use id_sync::envelope_outbox::*; diff --git a/pkgs/id/src/lib.rs b/pkgs/id/src/lib.rs index d9ff87834c..8378bdf829 100644 --- a/pkgs/id/src/lib.rs +++ b/pkgs/id/src/lib.rs @@ -267,6 +267,8 @@ pub mod world_doctor; #[cfg(feature = "world")] pub mod world_fixture; #[cfg(feature = "world")] +mod session_host; + pub mod world_hub; #[cfg(feature = "world")] pub use id_caps::world_limits; diff --git a/pkgs/id/src/session_host.rs b/pkgs/id/src/session_host.rs new file mode 100644 index 0000000000..e873ea022c --- /dev/null +++ b/pkgs/id/src/session_host.rs @@ -0,0 +1,83 @@ +//! The facade's side of the `id-sync` host seam (seam 9 of the crate +//! split, #4406): the world hub runs each wire request as a directory +//! action under its lease, and the directory itself is the artifact +//! sink the pull/apply transfer writes to. The protocols live in +//! `id_sync`; this is their composition with the hub and directory, +//! which stay in the facade until steps 5-6. + +use anyhow::Result; +use id_sync::artifact::{ArtifactSink, SignedArtifact, Stored}; +use id_sync::envelope::Envelope; +use id_sync::host::{Availability, EnvelopeReceived, SessionHost}; + +use crate::directory::{Directory, Received}; +use crate::directory_auth::Caller; +use crate::directory_view::DirectoryAction; +use crate::world_hub::WorldHub; + +impl SessionHost for WorldHub { + async fn receive_envelope( + &self, + envelope: Envelope, + ) -> Result>> { + let Ok(lease) = self.lease(None, None).await else { + return Ok(Availability::Busy); + }; + let outcome = lease + .service() + .directory(Caller::default(), DirectoryAction::Receive { envelope }) + .await?; + Ok(Availability::Available(match outcome.received { + Some(Received::Applied(_)) => Some(EnvelopeReceived::Applied), + Some(Received::Duplicate) => Some(EnvelopeReceived::Duplicate), + None => None, + })) + } + + async fn receive_artifact( + &self, + artifact: SignedArtifact, + ) -> Result>> { + let Ok(lease) = self.lease(None, None).await else { + return Ok(Availability::Busy); + }; + let outcome = lease + .service() + .directory( + Caller::default(), + DirectoryAction::ReceiveArtifact { artifact }, + ) + .await?; + Ok(Availability::Available(outcome.stored)) + } + + async fn read_artifacts( + &self, + account: String, + after: u64, + ) -> Result>> { + let Ok(lease) = self.lease(None, None).await else { + return Ok(Availability::Busy); + }; + let outcome = lease + .service() + .directory( + Caller::default(), + DirectoryAction::ReadArtifacts { account, after }, + ) + .await?; + Ok(Availability::Available( + outcome.artifact_page.unwrap_or_default(), + )) + } +} + +impl ArtifactSink for Directory { + fn receive_artifact(&mut self, artifact: &SignedArtifact) -> Result { + Directory::receive_artifact(self, artifact) + } + + fn artifact_head_seq(&self, account: &str) -> u64 { + self.artifacts().head_seq(account) + } +}