From 2cd583a88d2a3ea33a119cc127bd1ce232caf545 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 1 Nov 2026 12:26:20 -0600 Subject: [PATCH 1/8] Wire the blob membership gate into id serve (#173) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The blob gate (blob_gate::decide/blob_events) decided fetches and observes from a reference index that had no producer, so it was never wired into a serving path and blobs were served to any peer. - blob_gate: build_reference_index (with transitive HashSeq children), hashseq_children, fold_group_events (group log -> Worlds, world key = group create-hash hex), RefreshingWorlds (producer-swappable fold). - event_store: EventStore::document_references — applied, unremoved document.put events as (blob hash, group) pairs; LocalEvents exposes it. - serve: when the event store is open (web UI), BlobsProtocol runs the gate handler (push still decided by the AccessPolicy); a refresh task re-folds on the group-warning cadence so removals revoke fetch. Without the store, serve keeps push-only handling and warns the gate is inactive. - local: LocalNode::set_blob_gate lets an embedder supply the gate to serve(); default behavior unchanged. - groups::worlds::Worlds::empty for fail-closed fallbacks. Tests: blob_gate producer tests (index + HashSeq attribution, group-log fold gating, refresh revoking a removed member); existing suites pass. --- pkgs/id/crates/id-cli/src/local.rs | 48 +- .../id-events/src/event_store/documents.rs | 43 + pkgs/id/crates/id-worlds/src/groups/worlds.rs | 9 + pkgs/id/src/blob_gate.rs | 802 +++++- pkgs/id/src/commands/serve.rs | 2165 +++++++++++++++++ pkgs/id/src/local_events.rs | 824 +++++++ 6 files changed, 3849 insertions(+), 42 deletions(-) create mode 100644 pkgs/id/src/commands/serve.rs create mode 100644 pkgs/id/src/local_events.rs diff --git a/pkgs/id/crates/id-cli/src/local.rs b/pkgs/id/crates/id-cli/src/local.rs index 0a3e969454..5a51577ab3 100644 --- a/pkgs/id/crates/id-cli/src/local.rs +++ b/pkgs/id/crates/id-cli/src/local.rs @@ -30,14 +30,13 @@ use iroh_blobs::{ALPN as BLOBS_ALPN, BlobsProtocol, api::Store}; use iroh_docs::protocol::Docs; use iroh_gossip::net::Gossip; +use crate::access::AccessPolicy; +use crate::blob_gate::{BlobPolicy, RefreshingWorlds}; +use crate::fileops::FileOps; use crate::protocol::{MetaProtocol, MetaRequest, MetaResponse}; -use id_core::access::AccessPolicy; -use id_core::access::blobs_events; -use id_store::store::{StoreType, load_or_create_keypair, open_store}; -use id_store::tags::TagStore; -use id_sync::fileops::FileOps; - -use crate::{KEY_FILE, META_ALPN, STORE_PATH}; +use crate::store::{StoreType, load_or_create_keypair, open_store}; +use crate::tags::TagStore; +use crate::{KEY_FILE, META_ALPN, STORE_PATH, access::blobs_events}; /// A network-less node exposing the blob store and the metadata [`TagStore`]. #[derive(Debug)] @@ -52,6 +51,8 @@ pub struct LocalNode { endpoint: Endpoint, meta: Arc, node_id: EndpointId, + /// The blob membership gate the embedder supplied, if any (#173). + blob_gate: Option<(Arc, BlobPolicy)>, } impl LocalNode { @@ -126,7 +127,6 @@ impl LocalNode { Arc::clone(&tags), AccessPolicy::open(), node_id, - None, ); // Nothing is in flight for an in-process node: a missing blob is missing. if let Some(inner) = Arc::get_mut(&mut m) { @@ -145,9 +145,21 @@ impl LocalNode { endpoint, meta, node_id, + blob_gate: None, }) } + /// Supplies the blob membership gate [`LocalNode::serve`] enforces (#173). + /// + /// `LocalNode` holds no group log or event store of its own, so the embedder — + /// which owns the worlds and documents — builds the gate (see + /// [`crate::blob_gate::RefreshingWorlds`]) and keeps it refreshed. Without a + /// gate, `serve` keeps its historical behavior: pushes are policy-checked and + /// reads are open. + pub fn set_blob_gate(&mut self, gate: Arc, policy: BlobPolicy) { + self.blob_gate = Some((gate, policy)); + } + /// Handle to the blob store (cheap to clone). pub fn blobs(&self) -> Store { self.blobs.clone() @@ -159,11 +171,8 @@ impl LocalNode { } /// File operations (put/rename/copy/delete) over this node's stores. - /// - /// Writes through this handle stamp this node as the file's origin - /// (#4973). pub fn ops(&self) -> FileOps<'_> { - FileOps::new(&self.blobs, &self.tags).with_origin(self.node_id.to_string()) + FileOps::new(&self.blobs, &self.tags) } /// Answer a meta-protocol request in-process, exactly as a server would. @@ -203,9 +212,20 @@ impl LocalNode { Arc::clone(&self.tags), access.clone(), self.node_id, - None, ); - let blobs = BlobsProtocol::new(&self.blobs, Some(blobs_events(access))); + // With a gate, blob fetches and observes are membership-checked (#173) and + // pushes keep this policy; without one, pushes alone are gated, as before. + let blobs = match &self.blob_gate { + Some((gate, policy)) => BlobsProtocol::new( + &self.blobs, + Some(crate::blob_gate::blob_events( + Arc::clone(gate), + policy.clone(), + access, + )), + ), + None => BlobsProtocol::new(&self.blobs, Some(blobs_events(access))), + }; Router::builder(self.endpoint.clone()) .accept(META_ALPN, meta) .accept(BLOBS_ALPN, blobs) diff --git a/pkgs/id/crates/id-events/src/event_store/documents.rs b/pkgs/id/crates/id-events/src/event_store/documents.rs index 4cd77c5065..1808bb9fb2 100644 --- a/pkgs/id/crates/id-events/src/event_store/documents.rs +++ b/pkgs/id/crates/id-events/src/event_store/documents.rs @@ -84,4 +84,47 @@ impl EventStore { records.sort_by_key(|record| *record.id.as_bytes()); Ok(records) } + + /// The blob references the gate index is built from: for every applied `document.put` + /// its author has not removed, the document's blob hash and the group the event names + /// (`None` when the event names none — such a document references its blob for no + /// world). Sorted by blob hash for a stable index build. + /// + /// # Errors + /// + /// Returns a redb error if the read fails, or [`StoreError::Corrupt`] for a stored + /// document event that carries no document, or a stored removal that names no document. + pub fn document_references(&self) -> Result)>, StoreError> { + let records = self.documents()?; + let removed: std::collections::BTreeSet<[u8; 32]> = records + .iter() + .filter(|record| record.removal.is_some()) + .map(|record| *record.id.as_bytes()) + .collect(); + let txn = self.db.begin_read()?; + let events = txn.open_table(EVENTS)?; + let applied_table = txn.open_table(APPLIED)?; + let mut references = Vec::new(); + for row in events.iter()? { + let (_position, bytes) = row?; + let event = decode_stored(bytes.value())?; + if removed.contains(event.id.as_bytes()) { + continue; + } + if applied_table.get(event.id.as_bytes().as_slice())?.is_none() { + continue; + } + if event.header.extensions.kind != DOCUMENT_KIND { + continue; + } + let Some(document) = &event.header.extensions.document else { + return Err(corrupt( + "a stored document event carries no document".to_owned(), + )); + }; + references.push((document.blob_hash(), event.header.extensions.group)); + } + references.sort_by_key(|(hash, _)| *hash.as_bytes()); + Ok(references) + } } diff --git a/pkgs/id/crates/id-worlds/src/groups/worlds.rs b/pkgs/id/crates/id-worlds/src/groups/worlds.rs index 97cb79e14e..29821ddb5d 100644 --- a/pkgs/id/crates/id-worlds/src/groups/worlds.rs +++ b/pkgs/id/crates/id-worlds/src/groups/worlds.rs @@ -79,6 +79,15 @@ pub struct Worlds { } impl Worlds { + /// No worlds at all: the fold of nothing, for callers that must fail closed + /// (an empty gate) rather than propagate a fold error. + pub fn empty() -> Self { + Self { + folds: BTreeMap::new(), + markers: BTreeMap::new(), + } + } + /// Folds each world's events on their own. /// /// # Errors diff --git a/pkgs/id/src/blob_gate.rs b/pkgs/id/src/blob_gate.rs index a7e20ee624..8c2ba7a31b 100644 --- a/pkgs/id/src/blob_gate.rs +++ b/pkgs/id/src/blob_gate.rs @@ -1,33 +1,779 @@ -//! Who may fetch or observe a blob (P3.4, decision 5) — facade shim -//! over `id-groups` and `id-worlds`. +//! Who may fetch or observe a blob (P3.4, decision 5). //! -//! Step 4 of the pkgs/id crate split (#4407): the gate itself — -//! [`BlobPolicy`], [`Request`], [`decide`], [`decide_with_blocks`] and -//! the provider wiring in [`blob_events`] — lives in -//! `id_groups::blob_gate`, over the [`WorldAccess`] trait the events -//! layer owns (step 2b). Step 5 (#4408) moved [`FoldedWorlds`], the -//! `WorldAccess` implementation over the folded worlds, into -//! `id_worlds::blob_gate` together with seam 6's bridge file -//! (`groups::worlds`), which it folds through. It cannot live in -//! `id-groups`: that crate is below `id-worlds` and must not name -//! world types. This facade module now holds nothing but the -//! re-exports, so every historical `id::blob_gate` path is unchanged. +//! iroh-blobs serves a `get` for any hash to any peer that connects. Under its default +//! observe mode it also answers `observe` with the blob's size and held ranges, for anyone. +//! This module decides each of those requests from the requester's [`EndpointId`] and the hash: //! -//! The gate's own documentation, in `id_groups::blob_gate`: a fetch -//! is allowed only to a current member of a world that references -//! the hash; observe needs the same membership and a server policy -//! that serves observe for that world; refusals look the same -//! whether the hash is unreferenced or the requester may not reach -//! it; and an unknown requester is refused. - -pub use id_groups::blob_gate::{ - BlobPolicy, Request, blob_events, blob_events_with_blocks, decide, decide_with_blocks, +//! - **Fetch** (`get`, and every hash of a `get_many`) is allowed only to a current member of a +//! world that references the hash. A world references a blob when one of its artifacts or +//! documents names the hash. +//! - **Observe** needs the same membership, and the server policy must serve observe for that +//! world. Observe is off by default. A world can narrow it off for its own blobs, but cannot +//! switch it on. +//! - **Refusals look the same.** A hash that no world references and a hash the requester may +//! not reach get the same verdict. The decision reads only the reference index and the +//! membership table, never the blob store. +//! - **Fails closed.** A request from a connection with no known `EndpointId` is refused, and so +//! is one whose verdict cannot be delivered. +//! +//! The reference index and the membership query are behind [`WorldAccess`]. [`FoldedWorlds`] +//! answers membership from the folded worlds. The index has a producer now: +//! [`build_reference_index`] over the event store's document references (see +//! `EventStore::document_references`), with [`fold_group_events`] folding the group log for +//! membership, and [`RefreshingWorlds`] swapping fresh folds in as they change. `id serve` +//! wires [`blob_events`] with those pieces whenever it has the node's event store open. + +use std::{ + collections::{BTreeMap, BTreeSet, HashMap}, + sync::{Arc, RwLock}, +}; + +use iroh_base::EndpointId; +use iroh_blobs::{ + Hash, + provider::events::{ + AbortReason, ConnectMode, EventMask, EventSender, ObserveMode, ProviderMessage, RequestMode, + }, }; -/// The two questions the gate asks of the world graph, re-exported at -/// its historical path (the trait itself is `id_events::world_access`). -pub use id_events::world_access::WorldAccess; +use crate::access::AccessPolicy; +use crate::groups::{Role, worlds::Worlds}; + +/// The two questions the gate asks of the world graph. +pub trait WorldAccess: Send + Sync + 'static { + /// Whether `requester` is a current member of `world`. + fn is_current_member(&self, world: &str, requester: &EndpointId) -> bool; + + /// The worlds whose content names `hash`. Empty for a hash that no world names, which + /// includes every unknown hash. + fn worlds_referencing(&self, hash: &Hash) -> Vec; +} + +/// The server's blob policy. +/// +/// `observe` is the server default and is off unless enabled. A world in `narrowed` refuses +/// observe for its blobs even when the server allows it. Fetch has no switch: every fetch is +/// decided by membership. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct BlobPolicy { + observe: bool, + narrowed: BTreeSet, +} + +impl BlobPolicy { + /// Serve observe for every world that does not narrow it. + #[must_use] + pub const fn with_observe(mut self) -> Self { + self.observe = true; + self + } + + /// Refuse observe for the blobs `world` references, whatever the server default. + #[must_use] + pub fn narrow_observe(mut self, world: impl Into) -> Self { + self.narrowed.insert(world.into()); + self + } + + /// Whether observe may be served for the blobs `world` references. + pub fn observe_allowed(&self, world: &str) -> bool { + self.observe && !self.narrowed.contains(world) + } +} + +/// The two request kinds the gate decides. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Request { + /// A `get` or one hash of a `get_many`. + Fetch, + /// An `observe`. + Observe, +} + +/// Whether `requester` may make `request` for `hash`. +/// +/// Allowed when some world that references `hash` has the requester as a current member and, +/// for an observe, the policy serves observe for that world. +pub fn decide( + access: &impl WorldAccess, + policy: &BlobPolicy, + requester: &EndpointId, + hash: &Hash, + request: Request, +) -> bool { + access.worlds_referencing(hash).iter().any(|world| { + access.is_current_member(world, requester) + && match request { + Request::Fetch => true, + Request::Observe => policy.observe_allowed(world), + } + }) +} + +/// [`WorldAccess`] over the folded worlds. +/// +/// Membership is the world's own authority, as [`Worlds::holds_here`] gives it: a member of its +/// group, or a grant in its own chains. A crossing from another world does not count. +/// +/// The reference index maps a blob hash to the worlds that name it. It is built by +/// [`build_reference_index`] from the event store's document references; artifacts are not a +/// source, because they carry SHA-256 hashes, not BLAKE3 blob hashes, and only WASM modules +/// are pinned, without a record of their world. A hash the index does not hold is +/// unreferenced, which refuses it to every requester. +#[derive(Debug)] +pub struct FoldedWorlds { + worlds: Worlds, + references: HashMap>, +} + +impl FoldedWorlds { + /// Pairs the folded worlds with a reference index. + pub const fn new(worlds: Worlds, references: HashMap>) -> Self { + Self { worlds, references } + } +} + +impl WorldAccess for FoldedWorlds { + fn is_current_member(&self, world: &str, requester: &EndpointId) -> bool { + self.worlds + .holds_here(world, *requester.as_bytes(), Role::Pull) + } + + fn worlds_referencing(&self, hash: &Hash) -> Vec { + self.references + .get(hash) + .map(|worlds| worlds.iter().cloned().collect()) + .unwrap_or_default() + } +} + +/// The world key a group is indexed under: the hex of its create event's hash, which is the +/// group hash every later event of the group names. A document event's `group` extension is +/// the same hash, so document references and membership folds agree on the key. +pub fn world_key(group: &p2panda_core::Hash) -> String { + group.to_string() +} + +/// Folds group-log events into the [`Worlds`] the gate reads membership from. +/// +/// Events are partitioned by world: a create event opens the world keyed by its own hash +/// (a friendship's create names its derived group instead), and every other event joins +/// the world its `group` names. An event that names no group and creates none belongs to +/// no world and is skipped. +/// +/// # Errors +/// +/// Any error [`Worlds::fold`] gives for one world. +pub fn fold_group_events( + events: &[crate::groups::Event], +) -> Result { + let mut by_world: BTreeMap> = BTreeMap::new(); + for event in events { + let key = match (&event.body, &event.group) { + (_, Some(group)) => world_key(group), + (crate::groups::Body::Create(_), None) => world_key(&event.id), + _ => continue, + }; + by_world.entry(key).or_default().push(event.clone()); + } + Worlds::fold(&by_world, BTreeMap::new()) +} + +/// The child hashes a blob's bytes name when the blob is a `HashSeq`: the sequence is the +/// raw concatenation of 32-byte hashes, so any other length is not a sequence and names no +/// children. +pub fn hashseq_children(bytes: &[u8]) -> Vec { + if bytes.is_empty() || !bytes.len().is_multiple_of(32) { + return Vec::new(); + } + bytes + .chunks_exact(32) + .map(|chunk| { + let mut raw = [0u8; 32]; + raw.copy_from_slice(chunk); + Hash::from_bytes(raw) + }) + .collect() +} + +/// Builds the reference index the gate decides from: blob hash → the worlds that name it. +/// +/// `references` pairs each referenced blob with the world that names it (a document event's +/// blob and its group, as [`world_key`] spells it). A document with no group names no +/// world: the caller leaves it out, and its blob stays unreferenced. +/// +/// `expand` names the children of a blob that is a `HashSeq` collection. Children are +/// attributed to every world that references the collection, transitively: a member of +/// the world may fetch the collection's contents, not just its sequence blob. The caller +/// decides what counts as a collection (serve expands only a blob whose parsed children +/// are all present in its store, so arbitrary 32-byte-multiple content does not spray +/// references onto hashes nobody stored). +pub fn build_reference_index( + references: impl IntoIterator, + expand: impl Fn(&Hash) -> Vec, +) -> HashMap> { + let mut index: HashMap> = HashMap::new(); + for (hash, world) in references { + index.entry(hash).or_default().insert(world); + } + // Attribute HashSeq children to the referencing worlds, transitively. The worklist + // holds (hash, world) pairs not yet expanded for that world, so the loop ends when + // every reachable pair has been expanded once. + let mut worklist: Vec<(Hash, String)> = index + .iter() + .flat_map(|(hash, worlds)| worlds.iter().map(move |world| (*hash, world.clone()))) + .collect(); + let mut expanded: BTreeSet<(Hash, String)> = BTreeSet::new(); + while let Some((hash, world)) = worklist.pop() { + if !expanded.insert((hash, world.clone())) { + continue; + } + for child in expand(&hash) { + let worlds = index.entry(child).or_default(); + if worlds.insert(world.clone()) { + worklist.push((child, world.clone())); + } + } + } + index +} + +/// [`WorldAccess`] whose folded worlds a producer can replace as they change. +/// +/// `blob_events` holds one `Arc` for the life of the server; the fold behind it must not +/// be the snapshot from startup, or a removed member would keep fetching and a new +/// document would stay unreferenced until a restart. The producer re-folds and calls +/// [`RefreshingWorlds::refresh`]; each decision then reads the latest fold. A poisoned +/// lock fails closed, like every other gate refusal. +#[derive(Debug)] +pub struct RefreshingWorlds { + inner: RwLock, +} + +impl RefreshingWorlds { + /// Starts from an initial fold. + pub const fn new(initial: FoldedWorlds) -> Self { + Self { + inner: RwLock::new(initial), + } + } + + /// Replaces the folded worlds every later decision reads. + pub fn refresh(&self, next: FoldedWorlds) { + if let Ok(mut current) = self.inner.write() { + *current = next; + } + } +} + +impl WorldAccess for RefreshingWorlds { + fn is_current_member(&self, world: &str, requester: &EndpointId) -> bool { + self.inner + .read() + .is_ok_and(|folded| folded.is_current_member(world, requester)) + } + + fn worlds_referencing(&self, hash: &Hash) -> Vec { + self.inner + .read() + .map(|folded| folded.worlds_referencing(hash)) + .unwrap_or_default() + } +} + +/// The verdict for a request from `peer`: allowed only when the peer is known and `allow` +/// says so. An unknown peer is refused. +fn admit( + peer: Option<&EndpointId>, + allow: impl FnOnce(&EndpointId) -> bool, +) -> Result<(), AbortReason> { + match peer { + Some(id) if allow(id) => Ok(()), + _ => Err(AbortReason::Permission), + } +} + +/// Build the [`EventSender`] that a provider passes to `BlobsProtocol::new`. +/// +/// Fetch, `get_many` and observe are decided by [`decide`] over `access`. Pushes are decided by +/// `writes`, as in [`crate::access::blobs_events`]. Every request is intercepted, so no store +/// read happens before the verdict. +/// +/// A background task is spawned on the current Tokio runtime and ends when the sender is +/// dropped. +pub fn blob_events( + access: Arc, + policy: BlobPolicy, + writes: AccessPolicy, +) -> EventSender { + let (tx, mut rx) = tokio::sync::mpsc::channel::(64); + let mask = EventMask { + connected: ConnectMode::Notify, + get: RequestMode::Intercept, + get_many: RequestMode::Intercept, + push: RequestMode::Intercept, + observe: ObserveMode::Intercept, + ..EventMask::DEFAULT + }; + tokio::spawn(async move { + let mut peers: HashMap = HashMap::new(); + while let Some(msg) = rx.recv().await { + match msg { + ProviderMessage::ClientConnectedNotify(m) => { + if let Some(id) = m.endpoint_id { + peers.insert(m.connection_id, id); + } + } + ProviderMessage::ConnectionClosed(m) => { + peers.remove(&m.connection_id); + } + ProviderMessage::GetRequestReceived(m) => { + let verdict = admit(peers.get(&m.connection_id), |id| { + decide(&*access, &policy, id, &m.request.hash, Request::Fetch) + }); + let _ = m.tx.send(verdict).await; + } + ProviderMessage::GetManyRequestReceived(m) => { + let verdict = admit(peers.get(&m.connection_id), |id| { + m.request + .hashes + .iter() + .all(|hash| decide(&*access, &policy, id, hash, Request::Fetch)) + }); + let _ = m.tx.send(verdict).await; + } + ProviderMessage::ObserveRequestReceived(m) => { + let verdict = admit(peers.get(&m.connection_id), |id| { + decide(&*access, &policy, id, &m.request.hash, Request::Observe) + }); + let _ = m.tx.send(verdict).await; + } + ProviderMessage::PushRequestReceived(m) => { + let verdict = admit(peers.get(&m.connection_id), |id| writes.can_write(id)); + let _ = m.tx.send(verdict).await; + } + _ => {} + } + } + }); + EventSender::new(tx, mask) +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +mod tests { + use std::collections::BTreeMap; + + use iroh_base::SecretKey; + use proptest::prelude::*; + + use super::*; + use crate::groups::policy::Policy; + use crate::groups::{Body, Create, Event, MemberOp, Template}; + + const WORLDS: [&str; 3] = ["alpha", "beta", "gamma"]; + + fn id(n: u8) -> EndpointId { + SecretKey::from_bytes(&[n; 32]).public() + } + + fn blob(n: u8) -> Hash { + Hash::from_bytes([n; 32]) + } + + /// Membership and references as plain lists, read by both `decide` and [`spec`]. + #[derive(Debug, Default)] + struct Table { + members: Vec<(String, EndpointId)>, + refs: Vec<(Hash, String)>, + } + + impl WorldAccess for Table { + fn is_current_member(&self, world: &str, requester: &EndpointId) -> bool { + self.members + .iter() + .any(|(w, m)| w == world && m == requester) + } + + fn worlds_referencing(&self, hash: &Hash) -> Vec { + self.refs + .iter() + .filter(|(h, _)| h == hash) + .map(|(_, w)| w.clone()) + .collect() + } + } + + /// The rule as a scan of the lists: some world names the hash, the requester is a member + /// of it, and an observe is served only where the policy serves observe. + fn spec(t: &Table, p: &BlobPolicy, r: &EndpointId, h: &Hash, req: Request) -> bool { + t.refs.iter().any(|(rh, w)| { + rh == h + && t.members.iter().any(|(mw, m)| mw == w && m == r) + && (req == Request::Fetch || (p.observe && !p.narrowed.contains(w))) + }) + } + + fn one_world(member: EndpointId, hash: Hash) -> Table { + Table { + members: vec![("docs".to_owned(), member)], + refs: vec![(hash, "docs".to_owned())], + } + } + + #[test] + fn a_non_member_is_refused_fetch_and_observe() { + let t = one_world(id(1), blob(9)); + let p = BlobPolicy::default().with_observe(); + assert!(!decide(&t, &p, &id(2), &blob(9), Request::Fetch)); + assert!(!decide(&t, &p, &id(2), &blob(9), Request::Observe)); + } + + #[test] + fn a_member_of_the_referencing_world_fetches() { + let t = one_world(id(1), blob(9)); + assert!(decide( + &t, + &BlobPolicy::default(), + &id(1), + &blob(9), + Request::Fetch + )); + } + + #[test] + fn a_member_of_an_unrelated_world_is_refused() { + let t = Table { + members: vec![("other".to_owned(), id(1))], + refs: vec![(blob(9), "docs".to_owned())], + }; + let p = BlobPolicy::default().with_observe(); + assert!(!decide(&t, &p, &id(1), &blob(9), Request::Fetch)); + assert!(!decide(&t, &p, &id(1), &blob(9), Request::Observe)); + } + + #[test] + fn observe_is_refused_by_default_even_for_a_member() { + let t = one_world(id(1), blob(9)); + assert!(!BlobPolicy::default().observe_allowed("docs")); + assert!(!decide( + &t, + &BlobPolicy::default(), + &id(1), + &blob(9), + Request::Observe + )); + assert!(decide( + &t, + &BlobPolicy::default(), + &id(1), + &blob(9), + Request::Fetch + )); + } + + #[test] + fn observe_is_allowed_for_a_member_when_the_server_enables_it() { + let t = one_world(id(1), blob(9)); + let p = BlobPolicy::default().with_observe(); + assert!(decide(&t, &p, &id(1), &blob(9), Request::Observe)); + } + + #[test] + fn a_world_can_narrow_observe_off_while_the_server_allows_it() { + let t = one_world(id(1), blob(9)); + let p = BlobPolicy::default().with_observe().narrow_observe("docs"); + assert!(!decide(&t, &p, &id(1), &blob(9), Request::Observe)); + assert!(decide(&t, &p, &id(1), &blob(9), Request::Fetch)); + } + + #[test] + fn a_narrowed_world_does_not_hide_observe_from_another_referencing_world() { + let t = Table { + members: vec![("docs".to_owned(), id(1)), ("team".to_owned(), id(1))], + refs: vec![(blob(9), "docs".to_owned()), (blob(9), "team".to_owned())], + }; + let p = BlobPolicy::default().with_observe().narrow_observe("docs"); + assert!(decide(&t, &p, &id(1), &blob(9), Request::Observe)); + } + + #[test] + fn an_unknown_hash_is_refused_like_a_denied_one() { + let t = one_world(id(1), blob(9)); + let p = BlobPolicy::default().with_observe(); + for request in [Request::Fetch, Request::Observe] { + // Unknown: no world names blob(5). Denied: a stranger asks for blob(9). + let unknown = decide(&t, &p, &id(1), &blob(5), request); + let denied = decide(&t, &p, &id(2), &blob(9), request); + assert!(!unknown && !denied, "{request:?}"); + } + } + + /// The world `docs`, founded by `founder`, which adds `member` as a reader and, when + /// `removed`, removes them again. Folded as the store folds a world. + fn folded(founder: EndpointId, member: EndpointId, removed: bool) -> Worlds { + let (founder, member) = (*founder.as_bytes(), *member.as_bytes()); + let create = p2panda_core::Hash::digest(b"create"); + let add = p2panda_core::Hash::digest(b"add"); + let remove = p2panda_core::Hash::digest(b"remove"); + let mut events = vec![ + Event { + id: create, + author: founder, + after: Vec::new(), + group: None, + body: Body::Create(Create { + template: Template::Custom, + policy: Policy::default(), + members: Vec::new(), + admins_on_create: false, + }), + }, + Event { + id: add, + author: founder, + after: vec![create], + group: Some(create), + body: Body::Member(MemberOp::Add { + member, + role: Role::Read, + }), + }, + ]; + if removed { + events.push(Event { + id: remove, + author: founder, + after: vec![add], + group: Some(create), + body: Body::Member(MemberOp::Remove { + member, + successor: None, + }), + }); + } + let worlds = BTreeMap::from([("docs".to_owned(), events)]); + Worlds::fold(&worlds, BTreeMap::new()).unwrap() + } + + /// The folded `docs` world, with `hash` indexed as named by `docs`. + fn gate(worlds: Worlds, hash: Hash) -> FoldedWorlds { + let refs = HashMap::from([(hash, BTreeSet::from(["docs".to_owned()]))]); + FoldedWorlds::new(worlds, refs) + } + + #[test] + fn folded_membership_admits_a_member_and_refuses_a_stranger() { + let g = gate(folded(id(1), id(2), false), blob(9)); + let p = BlobPolicy::default(); + assert!(decide(&g, &p, &id(2), &blob(9), Request::Fetch)); + // The founder is Admin, so is a member too. + assert!(decide(&g, &p, &id(1), &blob(9), Request::Fetch)); + assert!(!decide(&g, &p, &id(3), &blob(9), Request::Fetch)); + } + + #[test] + fn a_removed_member_loses_fetch_on_the_folded_world() { + let g = gate(folded(id(1), id(2), true), blob(9)); + assert!(!decide( + &g, + &BlobPolicy::default(), + &id(2), + &blob(9), + Request::Fetch + )); + } + + #[test] + fn an_unindexed_blob_is_refused_even_to_a_member() { + let g = gate(folded(id(1), id(2), false), blob(9)); + let p = BlobPolicy::default().with_observe(); + assert!(!decide(&g, &p, &id(2), &blob(5), Request::Fetch)); + assert!(!decide(&g, &p, &id(2), &blob(5), Request::Observe)); + } + + #[test] + fn observe_over_the_folded_world_follows_the_policy() { + let g = gate(folded(id(1), id(2), false), blob(9)); + assert!(!decide( + &g, + &BlobPolicy::default(), + &id(2), + &blob(9), + Request::Observe + )); + let p = BlobPolicy::default().with_observe(); + assert!(decide(&g, &p, &id(2), &blob(9), Request::Observe)); + } + + proptest! { + #[test] + fn decide_matches_the_spec_for_every_pair( + members in proptest::collection::vec((0usize..3, 1u8..6), 0..12), + refs in proptest::collection::vec((1u8..6, 0usize..3), 0..12), + observe in any::(), + narrowed in proptest::collection::vec(0usize..3, 0..3), + ) { + let t = Table { + members: members + .iter() + .map(|&(w, k)| (WORLDS[w].to_owned(), id(k))) + .collect(), + refs: refs + .iter() + .map(|&(h, w)| (blob(h), WORLDS[w].to_owned())) + .collect(), + }; + let mut p = BlobPolicy::default(); + if observe { + p = p.with_observe(); + } + for &w in &narrowed { + p = p.narrow_observe(WORLDS[w]); + } + for requester in 1u8..=6 { + for hash in 1u8..=5 { + for request in [Request::Fetch, Request::Observe] { + let got = decide(&t, &p, &id(requester), &blob(hash), request); + let want = spec(&t, &p, &id(requester), &blob(hash), request); + prop_assert_eq!( + got, + want, + "requester {} hash {} {:?}", + requester, + hash, + request + ); + } + } + } + } + } +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +mod producer_tests { + use std::collections::{BTreeMap, HashMap}; + + use iroh_base::SecretKey; + use p2panda_core::Hash as PandaHash; + + use super::*; + use crate::groups::policy::Policy; + use crate::groups::{Body, Create, Event, MemberOp, Template}; + + fn id(n: u8) -> EndpointId { + SecretKey::from_bytes(&[n; 32]).public() + } + + fn blob(n: u8) -> Hash { + Hash::from_bytes([n; 32]) + } + + #[test] + fn reference_index_attributes_hashseq_children_transitively() { + // world "w" references the sequence blob 1; 1 names 2 and 3; 2 names 4. + let children: HashMap> = + HashMap::from([(blob(1), vec![blob(2), blob(3)]), (blob(2), vec![blob(4)])]); + let index = build_reference_index([(blob(1), "w".to_owned())], |hash| { + children.get(hash).cloned().unwrap_or_default() + }); + for hash in [blob(1), blob(2), blob(3), blob(4)] { + assert_eq!( + index.get(&hash).map(|w| w.contains("w")), + Some(true), + "{hash} must be referenced by w" + ); + } + assert!(!index.contains_key(&blob(9)), "unrelated hash stays out"); + } + + #[test] + fn hashseq_children_parses_concatenated_hashes() { + let mut bytes = blob(5).as_bytes().to_vec(); + bytes.extend_from_slice(blob(6).as_bytes()); + assert_eq!(hashseq_children(&bytes), vec![blob(5), blob(6)]); + assert!(hashseq_children(&bytes[..33]).is_empty(), "ragged length"); + assert!(hashseq_children(&[]).is_empty(), "empty names nothing"); + } + + /// A group log for one world: founder creates it, adds `member`, then removes them + /// when `removed`. Returns the events and the world key the fold gives them. + fn group_events(member: EndpointId, removed: bool) -> (Vec, String) { + let founder = *id(1).as_bytes(); + let member_key = *member.as_bytes(); + let create = PandaHash::digest(b"gate-create"); + let add = PandaHash::digest(b"gate-add"); + let mut events = vec![ + Event { + id: create, + author: founder, + after: Vec::new(), + group: None, + body: Body::Create(Create { + template: Template::Custom, + policy: Policy::default(), + members: Vec::new(), + admins_on_create: false, + }), + }, + Event { + id: add, + author: founder, + after: vec![create], + group: Some(create), + body: Body::Member(MemberOp::Add { + member: member_key, + role: crate::groups::Role::Read, + }), + }, + ]; + if removed { + events.push(Event { + id: PandaHash::digest(b"gate-remove"), + author: founder, + after: vec![add], + group: Some(create), + body: Body::Member(MemberOp::Remove { + member: member_key, + successor: None, + }), + }); + } + (events, world_key(&create)) + } + + #[test] + fn folded_group_log_gates_fetch_and_refresh_revokes_it() { + let member = id(2); + let (events, world) = group_events(member, false); + let worlds = fold_group_events(&events).expect("the log folds"); + let index = build_reference_index([(blob(7), world.clone())], |_| Vec::new()); + let gate = RefreshingWorlds::new(FoldedWorlds::new(worlds, index)); + let policy = BlobPolicy::default(); + assert!( + decide(&gate, &policy, &member, &blob(7), Request::Fetch), + "a current member fetches a referenced blob" + ); + assert!( + !decide(&gate, &policy, &id(3), &blob(7), Request::Fetch), + "a non-member is refused" + ); + assert!( + !decide(&gate, &policy, &member, &blob(8), Request::Fetch), + "an unreferenced blob is refused even to a member" + ); -/// [`WorldAccess`] over the folded worlds; the implementation lives -/// in `id_worlds::blob_gate`. -pub use id_worlds::blob_gate::FoldedWorlds; + // The member is removed; a refreshed fold must revoke the fetch at once. + let (events, world) = group_events(member, true); + let worlds = fold_group_events(&events).expect("the log folds"); + let index = build_reference_index([(blob(7), world)], |_| Vec::new()); + gate.refresh(FoldedWorlds::new(worlds, index)); + assert!( + !decide(&gate, &policy, &member, &blob(7), Request::Fetch), + "a removed member loses fetch on the next request" + ); + let _ = BTreeMap::::new(); + } +} diff --git a/pkgs/id/src/commands/serve.rs b/pkgs/id/src/commands/serve.rs new file mode 100644 index 0000000000..655f9cd80e --- /dev/null +++ b/pkgs/id/src/commands/serve.rs @@ -0,0 +1,2165 @@ +//! Server command and lock file management. +//! +//! This module implements the `serve` command which starts a persistent +//! server that accepts connections from peers for blob storage and retrieval. +//! +//! # Architecture +//! +//! ```text +//! ┌─────────────────────────────────────────────────────────────┐ +//! │ Serve Process │ +//! ├─────────────────────────────────────────────────────────────┤ +//! │ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │ +//! │ │ Endpoint │ │ Router │ │ Store │ │ +//! │ │ (QUIC) │───►│ │───►│ (blobs/tags)│ │ +//! │ └─────────────┘ └─────────────┘ └─────────────┘ │ +//! │ │ │ │ +//! │ │ ┌──────┴──────┐ │ +//! │ │ │ │ │ +//! │ │ ┌─────▼─────┐ ┌─────▼─────┐ │ +//! │ │ │MetaProtocol│ │BlobsProtocol│ │ +//! │ │ │ /id/meta/1 │ │ /iroh/blobs │ │ +//! │ │ └───────────┘ └───────────┘ │ +//! │ │ │ +//! │ ▼ │ +//! │ Lock File: .id-serve-lock │ +//! │ - Node ID, PID, Socket addresses │ +//! └─────────────────────────────────────────────────────────────┘ +//! ``` +//! +//! # Lock File Protocol +//! +//! The serve process creates a lock file (`.id-serve-lock`) containing: +//! 1. Node ID (line 1) +//! 2. Process ID (line 2) +//! 3. Socket addresses (remaining lines) +//! +//! Other processes (REPL, CLI commands) check this file to determine +//! if a local serve is running and how to connect to it. +//! +//! # Examples +//! +//! ```bash +//! # Start persistent server +//! id serve +//! +//! # Start ephemeral server (in-memory) +//! id serve --ephemeral +//! +//! # Start without relay servers +//! id serve --no-relay +//! ``` + +use std::net::{Ipv4Addr, Ipv6Addr, SocketAddr}; +use std::path::PathBuf; +use std::sync::Arc; + +use anyhow::Result; +use anyhow::ensure; +use distributed_topic_tracker::{AutoDiscoveryGossip, RecordPublisher, TopicId}; +use futures_lite::StreamExt; +use iroh::{endpoint::Endpoint, protocol::Router}; +use iroh_base::EndpointId; +use iroh_blobs::{ALPN as BLOBS_ALPN, BlobsProtocol}; +use iroh_docs::protocol::Docs; +use iroh_gossip::net::Gossip; +use iroh_mdns_address_lookup::MdnsAddressLookup; +use p2panda_core::Hash; +#[cfg(all(feature = "world", feature = "sandbox"))] +use rand::RngExt as _; +use serde::{Deserialize, Serialize}; +use tokio::fs as afs; +use tracing::{debug, info, warn}; + +use crate::discovery::{ + ANNOUNCE_INTERVAL, PeerAnnouncement, PeerDiscovery, STALE_CHECK_INTERVAL, STALE_THRESHOLD, + resolve_config, +}; +use crate::groups::log::{FILE_NAME as GROUPS_FILE_NAME, GroupLog}; +use crate::groups::warnings::{Evaluator, Observation, Warning}; +use crate::groups::{Key as GroupKey, Projection}; +use crate::protocol::{MetaProtocol, MetaRequest, MetaResponse}; +use crate::store::{load_or_create_keypair, open_store}; +use crate::tags::TagStore; +use crate::{KEY_FILE, META_ALPN, SERVE_LOCK, STORE_PATH}; + +/// Print a status line to stdout **without panicking** if stdout is gone. +/// +/// `println!` panics on `EPIPE`. A server must not die because whoever +/// launched it stopped reading its output (`id serve | head -1`, a supervisor +/// that closes the pipe after the first line, or a test harness): the status +/// lines are informational. The lock file, not stdout, is how clients find +/// the server. +macro_rules! status { + ($($arg:tt)*) => {{ + use std::io::Write as _; + let _ = writeln!(std::io::stdout(), $($arg)*); + }}; +} + +/// Like [`status!`], for stderr. +#[cfg(any(feature = "web", feature = "world"))] +macro_rules! status_err { + ($($arg:tt)*) => {{ + use std::io::Write as _; + let _ = writeln!(std::io::stderr(), $($arg)*); + }}; +} + +/// Information about a running serve instance. +/// +/// Retrieved from the lock file by [`get_serve_info`] to enable +/// other processes to connect to the local serve. +/// +/// # Fields +/// +/// - `node_id`: The public identity of the serve node +/// - `addrs`: Local socket addresses where the serve is listening +/// +/// # JSON Lock File Format +/// +/// ```json +/// { +/// "node_id": "abc123...", +/// "pid": 12345, +/// "addrs": ["127.0.0.1:12345", "[::1]:12345"], +/// "web_port": 3001 +/// } +/// ``` +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ServeInfo { + /// The public node ID derived from the serve's keypair. + pub node_id: String, + /// Process ID of the running serve instance. + pub pid: u32, + /// Socket addresses the serve is bound to (as strings for JSON). + pub addrs: Vec, + /// Port for the web UI, if enabled. + pub web_port: Option, +} + +impl ServeInfo { + /// Parse the `node_id` string back to an [`EndpointId`]. + pub fn endpoint_id(&self) -> Option { + self.node_id.parse().ok() + } + + /// Parse the address strings back to [`SocketAddr`]s. + pub fn socket_addrs(&self) -> Vec { + self.addrs.iter().filter_map(|a| a.parse().ok()).collect() + } +} + +/// Checks if a serve instance is running and returns its connection info. +/// +/// Reads the JSON lock file, verifies the PID is still alive, and returns +/// the serve info needed to connect. Returns `None` if: +/// - Lock file doesn't exist +/// - Lock file is malformed +/// - Referenced process is no longer running (stale lock) +/// +/// # Example +/// +/// ```rust,ignore +/// if let Some(info) = get_serve_info().await { +/// println!("Serve running: {}", info.node_id); +/// // Connect to info.addrs... +/// } else { +/// println!("No serve running"); +/// } +/// ``` +pub async fn get_serve_info() -> Option { + let contents = afs::read_to_string(SERVE_LOCK).await.ok()?; + let info: ServeInfo = serde_json::from_str(&contents).ok()?; + + // Check if process is still alive + if !is_process_alive(info.pid) { + // Stale lock file - remove it + let _ = afs::remove_file(SERVE_LOCK).await; + return None; + } + + Some(info) +} + +/// Checks if a process with the given PID is still running. +/// +/// Uses platform-specific methods: +/// - Unix: `kill(pid, 0)` which checks existence without sending a signal +/// - Other: Always returns `true` (conservative fallback) +/// +/// # Arguments +/// +/// * `pid` - The process ID to check +/// +/// # Returns +/// +/// `true` if the process exists, `false` otherwise. +#[allow(clippy::cast_possible_wrap)] // PID is always positive, wrap is safe for kill() +#[allow(unsafe_code)] // Required for libc::kill +pub fn is_process_alive(pid: u32) -> bool { + #[cfg(unix)] + { + // SAFETY: libc::kill with signal 0 only checks process existence without + // sending any signal. The pid cast from u32 to i32 is safe because valid + // PIDs on Unix are always positive and fit in i32. + // #2384: a failed probe is not proof of death — EPERM means the + // process exists but is owned by another user, so it is alive; + // only ESRCH (no such process) and other errnos mean dead. This + // mirrors mcpx's ProcessAlive (pkgs/mcpx/internal/daemon/paths.go). + let rc = unsafe { libc::kill(pid as i32, 0) }; + rc == 0 || std::io::Error::last_os_error().raw_os_error() == Some(libc::EPERM) + } + #[cfg(not(unix))] + { + // On non-Unix, just assume it's alive if we have a PID + let _ = pid; + true + } +} + +/// Creates the serve lock file with connection information as JSON. +/// +/// Writes the node ID, current process ID, socket addresses, and +/// optional web port to the lock file so other processes can discover +/// and connect. +/// +/// # Arguments +/// +/// * `node_id` - The serve node's public identity +/// * `addrs` - Socket addresses the serve is listening on +/// * `web_port` - Port for the web UI, if enabled +/// +/// # Errors +/// +/// Returns an error if the lock file cannot be written. +pub async fn create_serve_lock( + node_id: &EndpointId, + addrs: &[SocketAddr], + web_port: Option, +) -> Result<()> { + let info = ServeInfo { + node_id: node_id.to_string(), + pid: std::process::id(), + addrs: addrs.iter().map(ToString::to_string).collect(), + web_port, + }; + let contents = serde_json::to_string_pretty(&info)?; + afs::write(SERVE_LOCK, contents).await?; + Ok(()) +} + +/// Removes the serve lock file. +/// +/// Called during graceful shutdown to indicate the serve is no longer running. +/// Errors are silently ignored (file may already be removed). +pub async fn remove_serve_lock() -> Result<()> { + let _ = afs::remove_file(SERVE_LOCK).await; + Ok(()) +} +/// Options for [`cmd_serve`], mirroring the `serve` CLI flags. +#[derive(Debug, Clone)] +pub struct ServeOptions { + /// Use an in-memory store. + pub ephemeral: bool, + /// Group log for the group-warning watcher (the global + /// `--groups-log` option); `None` reads the default + /// `groups.jsonl`, exactly as the group commands resolve it. + pub groups_log: Option, + /// Disable relay servers. + pub no_relay: bool, + /// Disable gossip peer discovery. + pub no_gossip: bool, + /// Start the web interface. + pub web: bool, + /// Web interface port (0 = random). + pub port: u16, + /// Extra bootstrap node IDs. + pub bootstrap: Vec, + /// Gossip topic override. + pub topic: Option, + /// Gossip topic secret override. + pub topic_secret: Option, + /// Skip default bootstrap nodes. + pub no_default_bootstrap: bool, + /// Skip default topic and secret. + pub no_default_topic: bool, + /// Use only `defaults.conf` values. + pub replace_defaults: bool, + /// Disable mDNS. + pub no_mdns: bool, + /// Enable mainline DHT address lookup and publishing. + pub dht: bool, + /// Iroh QUIC port (0 = random). + pub iroh_port: u16, + /// Address the web interface binds to. + pub bind: std::net::IpAddr, + /// Token required by the web interface. + pub web_token: Option, + /// Mark the directory explorer's session cookies `Secure` (HTTPS in front). + pub web_cookie_secure: bool, + /// Host a multiplayer world (durable unless `ephemeral`). + pub world: bool, + /// Admin secret required to mint world guest capabilities. + pub world_admin_token: Option, + /// Optional Wasm world program, compiled for the sandbox's Roc platform ABI. + pub world_module: Option, + /// Directory that receives confirmation mail, one file per message. + pub world_mail_outbox: Option, + /// Program run once per confirmation mail. + pub world_mail_command: Option, + /// Loopback SMTP relay that receives confirmation mail. + pub world_mail_smtp: Option, + /// Sender address for mail sent through `world_mail_smtp`. + pub world_mail_from: Option, + /// Name of the world this server offers; its files live under + /// `.id-worlds//`. + pub world_name: String, + /// Trim the journal behind a program snapshot every this many events + /// (`0` never trims). + pub world_checkpoint_every: u64, + /// Most worlds open at once. + pub world_max_open: usize, + /// Most world sessions at once, across all worlds. + pub world_max_sessions: usize, + /// Close durable worlds idle for this many seconds (`0` never). + pub world_idle_secs: u64, + /// Refuse signed world requests for this many seconds after startup (`0` none). + pub world_boot_window_secs: u64, + /// Capabilities the default world's program may use. + pub world_caps: Vec, + /// `deny` or `grant-on-use`. + pub world_cap_policy: String, + /// Capabilities the server allows any world to use (`None`: the whole catalog). + pub world_allowed_caps: Option>, + /// Roc binary for on-the-fly compilation. + pub roc_bin: Option, + /// Platform directory for on-the-fly compilation. + pub roc_platform: Option, + /// Serve the world over SSH on this port. + pub world_ssh_port: Option, + /// Accept native (ELF) module installs. + pub world_native: bool, + /// Accept program changes only through server-side Roc compilation. + pub world_source_only: bool, + /// Execution bounds for world programs. + pub world_runtime: crate::cli::WorldRuntimeArgs, + /// Nodes allowed to modify the store. + pub allow_node: Vec, + /// Let every peer modify the store. + pub open_writes: bool, +} + +fn validate_world_options( + world: bool, + admin_token: Option<&str>, + world_module: Option<&PathBuf>, + world_name: &str, + world_cap_policy: &str, + world_source_only: bool, +) -> Result<()> { + ensure!( + !world || admin_token.is_some_and(|token| !token.is_empty()), + "--world requires --world-admin-token (or ID_WORLD_ADMIN_TOKEN)" + ); + ensure!( + world_module.is_none() || world, + "--world-module requires --world" + ); + #[cfg(feature = "world")] + crate::world_hub::validate_world_name(world_name)?; + ensure!( + world_cap_policy == "deny" || world_cap_policy == "grant-on-use", + "--world-cap-policy must be `deny` or `grant-on-use`" + ); + ensure!( + !world_source_only || world_module.is_none(), + "--world-source-only cannot be combined with --world-module" + ); + ensure!( + !world_source_only || world, + "--world-source-only requires --world" + ); + #[cfg(not(feature = "world"))] + let _ = world_name; + Ok(()) +} + +/// Build the write-access policy for a server. +/// +/// Trusted automatically: the server's own key and this data directory's +/// client key (so the local CLI and REPL work without setup). Added to those: +/// `--allow-node` IDs and the `.iroh-allowed` file. With `open_writes`, every +/// peer may write. +/// +/// # Errors +/// +/// Fails if an `--allow-node` value is not a valid node ID. +pub async fn build_access_policy( + node_id: EndpointId, + allow_node: &[String], + open_writes: bool, +) -> Result { + use crate::access::{AccessPolicy, load_allowed_nodes}; + if open_writes { + return Ok(AccessPolicy::open()); + } + let client_key = load_or_create_keypair(crate::CLIENT_KEY_FILE).await?; + let mut writers = vec![node_id, client_key.public()]; + for id in allow_node { + writers.push( + id.parse::() + .map_err(|e| anyhow::anyhow!("invalid --allow-node {id:?}: {e}"))?, + ); + } + writers.extend(load_allowed_nodes(std::path::Path::new("."))); + Ok(AccessPolicy::restricted(writers)) +} + +/// Root directory for durable worlds, relative to the data directory. +#[cfg(feature = "world")] +pub const WORLDS_DIR: &str = ".id-worlds"; + +#[cfg(feature = "world")] +const OUTBOX_FLUSH_SECS: u64 = 30; + +/// Directory of one durable world, relative to the data directory. +#[cfg(feature = "world")] +#[must_use] +pub fn world_dir(name: &str) -> PathBuf { + PathBuf::from(WORLDS_DIR).join(name) +} + +/// Resolve the compile settings: an explicit flag, the environment, or the +/// conventional repository layout. Absence is fine (compilation stays off). +#[cfg(feature = "world")] +fn resolve_compiler( + roc_bin: Option, + roc_platform: Option, +) -> Result> { + let Some(platform) = roc_platform + .or_else(|| std::env::var("ID_ROC_PLATFORM").ok().map(PathBuf::from)) + .or_else(|| { + [ + PathBuf::from("examples/roc-world"), + PathBuf::from("../examples/roc-world"), + ] + .into_iter() + .find(|dir| dir.is_dir()) + }) + else { + return Ok(None); + }; + let roc_bin = roc_bin + .or_else(|| std::env::var("ID_ROC_BIN").ok()) + .unwrap_or_else(|| "roc".to_owned()); + let compiler = crate::world_compile::Compiler::new(platform, roc_bin)?; + info!( + platform = %compiler.platform_dir.display(), + roc = %compiler.roc_bin, + "world: on-the-fly compilation enabled" + ); + Ok(Some(compiler)) +} + +/// Builds this server's worlds: durable under [`WORLDS_DIR`] unless +/// `ephemeral`. The `--world-module` goes through the same journaled install +/// as an admin upload, so it is pinned, downloadable and restored after a +/// restart; it is only installed when it differs from the module the world +/// already runs. It applies to the default world only. +#[cfg(feature = "world")] +fn mail_sink( + outbox: Option, + command: Option, + smtp: Option, + from: Option, +) -> Result>> { + use crate::directory_mail::{CommandSink, MailSink, OutboxSink, SmtpSink}; + use anyhow::Context as _; + let sink: Arc = match (outbox, command, smtp) { + (Some(dir), _, _) => Arc::new(OutboxSink::new(dir)), + (None, Some(program), _) => Arc::new(CommandSink::new(program, Vec::new())), + (None, None, Some(relay)) => { + let from = from.context("--world-mail-from is needed with --world-mail-smtp")?; + Arc::new(SmtpSink::new(relay, from)?) + } + (None, None, None) => return Ok(None), + }; + Ok(Some(sink)) +} + +/// The server's capability ceiling: the named capabilities, or the whole catalog +/// when no list is given. Like a world ceiling, it names capabilities; `*` is refused. +#[cfg(feature = "world")] +fn allowed_caps(names: Option<&[String]>) -> Result> { + match names { + None => Ok(crate::world_caps::catalog_names()), + Some(names) => { + crate::world_caps::validate_ceiling_names(names)?; + Ok(names.iter().cloned().collect()) + } + } +} + +#[cfg(feature = "world")] +struct ServeWorlds { + ephemeral: bool, + admin_token: Option, + blobs: iroh_blobs::api::Store, + docs: Docs, + checkpoint_every: u64, + default_world: String, + default_module: Option, + grant_on_use: bool, + server_caps: std::collections::BTreeSet, + compiler: Option, + native: bool, + source_only: bool, + runtime: crate::world_limits::RuntimeLimits, + mail: Option>, +} + +#[cfg(feature = "world")] +impl crate::world_hub::WorldOpener for ServeWorlds { + fn open<'a>(&'a self, name: &'a str, create: bool) -> crate::world_hub::OpenFuture<'a> { + Box::pin(async move { + if !create && !self.exists(name) { + return Ok(None); + } + self.open_world(name).await.map(Some) + }) + } + + fn exists(&self, name: &str) -> bool { + !self.ephemeral && world_dir(name).join("journal.jsonl").is_file() + } + + fn list(&self) -> Vec { + if self.ephemeral { + return Vec::new(); + } + let mut names: Vec = std::fs::read_dir(WORLDS_DIR) + .into_iter() + .flatten() + .flatten() + .filter(|entry| entry.path().join("journal.jsonl").is_file()) + .filter_map(|entry| entry.file_name().into_string().ok()) + .filter(|name| crate::world_hub::validate_world_name(name).is_ok()) + .collect(); + names.sort(); + names + } + + fn durable(&self) -> bool { + !self.ephemeral + } +} + +#[cfg(feature = "world")] +impl ServeWorlds { + async fn open_world(&self, name: &str) -> Result { + use crate::world::{WorldCore, WorldHandle, WorldLimits}; + use crate::world_session::WorldService; + + let limits = WorldLimits { + checkpoint_every: self.checkpoint_every, + grant_on_use: self.grant_on_use, + server_caps: self.server_caps.clone(), + ..WorldLimits::default() + }; + let runtime = self.runtime; + let make = { + let admin_token = self.admin_token.clone(); + let blobs = self.blobs.clone(); + let mail = self.mail.clone(); + let source_only = self.source_only; + move |handle| { + let service = WorldService::new(handle, admin_token) + .with_blob_store(blobs) + .with_runtime_limits(runtime) + .with_source_only(source_only); + match &mail { + Some(sink) => service.with_mail(Arc::clone(sink)), + None => service, + } + } + }; + let dir = world_dir(name); + let namespace_file = (!self.ephemeral).then(|| dir.join("records.namespace")); + let records = + crate::world_records::RecordsStore::open(&self.docs, namespace_file.as_deref()).await?; + info!( + world = name, + namespace = %records.namespace(), + "world: records document ready" + ); + info!( + world = name, + ephemeral = self.ephemeral, + "serve startup: records ready, building world service (#190 breadcrumb)" + ); + let service = if self.ephemeral { + make(WorldHandle::spawn(WorldCore::new(name, limits)?)).with_records_store(records) + } else { + let (service, report) = + crate::world_store::open_world(&dir, name, limits, runtime, make).await?; + status!( + "world {name}: restored {} at sequence {} ({} input(s) replayed)", + dir.display(), + report.sequence, + report.replayed_inputs + ); + if let Some(error) = &report.program_error { + status_err!("warning: world {name}: program not restored ({error}); reinstall it"); + } + service.with_records_store(records) + }; + info!( + world = name, + "serve startup: world service built (#190 breadcrumb)" + ); + + let service = if self.native { + service.with_native_enabled() + } else { + service + }; + let service = match self.compiler.clone() { + Some(compiler) => service.with_compiler(compiler), + None => service, + }; + if name == self.default_world + && let Some(path) = self.default_module.as_deref() + { + self.install_default_module(&service, path).await?; + } + info!( + world = name, + "serve startup: world open complete (#190 breadcrumb)" + ); + Ok(service) + } + + #[cfg(feature = "sandbox")] + async fn install_default_module( + &self, + service: &crate::world_session::WorldService, + path: &std::path::Path, + ) -> Result<()> { + let metadata = tokio::fs::metadata(path).await?; + ensure!( + usize::try_from(metadata.len()) + .is_ok_and(|len| len <= crate::world_session::MAX_WORLD_MODULE_BYTES), + "world module exceeds the configured module size limit" + ); + let wasm = tokio::fs::read(path).await?; + let hash = crate::world_session::module_hash(&wasm); + if service.active_module_hash().await.as_deref() == Some(hash.as_str()) { + info!(module = %path.display(), "world: module already active"); + } else { + let seed = rand::rng().random::(); + service + .install_wasm(self.admin_token.as_deref(), wasm, seed, &hash) + .await + .map_err(|e| anyhow::anyhow!("install {}: {e:?}", path.display()))?; + info!(module = %path.display(), seed, "world: installed module"); + } + Ok(()) + } + + #[cfg(not(feature = "sandbox"))] + #[allow(clippy::unused_async)] + async fn install_default_module( + &self, + _service: &crate::world_session::WorldService, + _path: &std::path::Path, + ) -> Result<()> { + anyhow::bail!("--world-module requires a build with the `sandbox` feature"); + } +} + +/// Starts the serve process. +/// +/// Initializes the Iroh endpoint, blob store, protocol handlers, and +/// (optionally) gossip-based peer discovery, then waits for incoming +/// connections until interrupted with Ctrl+C. +/// +/// # Arguments +/// +/// * `ephemeral` - If `true`, use in-memory storage (lost on exit) +/// * `no_relay` - If `true`, disable relay servers (direct connections only) +/// * `no_gossip` - If `true`, disable gossip/DHT peer discovery entirely +/// * `web` - If `true`, start the web interface (requires `web` feature) +/// * `port` - Port for the web interface (default 3000) +/// * `bootstrap` - Additional node IDs for manual peer bootstrapping +/// * `topic` - Custom gossip topic name (default: from `defaults.conf` or `DEFAULT_TOPIC`) +/// * `topic_secret` - Custom shared secret for topic access control +/// * `no_default_bootstrap` - If `true`, skip default bootstrap nodes from `defaults.conf` +/// * `no_default_topic` - If `true`, skip default topic/secret from `defaults.conf` +/// * `replace_defaults` - If `true`, use only `defaults.conf` values (skip hardcoded fallbacks) +/// +/// # Behavior +/// +/// 1. Loads or creates the node keypair +/// 2. Opens the blob store (persistent or ephemeral) +/// 3. Creates the Iroh endpoint with DNS/Pkarr address lookup +/// 4. Creates peer discovery table +/// 5. Unless `no_gossip`: creates gossip instance, registers gossip ALPN, +/// joins topic via DHT, spawns announce/receive/cleanup tasks +/// 6. Registers `MetaProtocol` and `BlobsProtocol` handlers +/// 7. Optionally starts the web interface on the specified port +/// 8. Creates the lock file for local process discovery +/// 9. Waits for Ctrl+C +/// 10. Cleans up and exits +/// +/// # Output +/// +/// Prints the node ID, mode, and peer discovery status to stdout. +/// Status messages go to stderr. +#[allow(unused_variables)] // web/port only used with web feature +/// The group log the serve warning watcher reads: the global +/// `--groups-log` option when given, else the default file name — +/// resolved with the group commands' semantics (#2778; serve used +/// to hardcode the default and ignore the option). +fn serve_groups_log_path(path: Option) -> PathBuf { + crate::commands::group::log_path(path) +} + +/// Builds the blob gate's folded worlds from the two sources serve has: the group +/// log at `groups_log` for membership, and the event store's document references +/// for which blobs each world names (#173). +/// +/// A referenced blob that parses as a `HashSeq` contributes its children to the +/// same world, but only when every child is present in the store — arbitrary +/// content whose length is a multiple of 32 bytes would otherwise spray +/// references onto hashes nobody stored. Any source that fails to read folds to +/// empty for that source: the gate fails closed, and the next refresh retries. +#[cfg(feature = "web")] +async fn build_blob_gate( + events: &Arc>, + store: &iroh_blobs::api::Store, + groups_log: &std::path::Path, +) -> crate::blob_gate::FoldedWorlds { + let empty_worlds = crate::groups::worlds::Worlds::empty; + let worlds = match GroupLog::open(groups_log) { + Ok(log) => crate::blob_gate::fold_group_events(log.events()).unwrap_or_else(|error| { + warn!("blob gate: group log does not fold: {error}"); + empty_worlds() + }), + Err(error) => { + warn!("blob gate: cannot open group log: {error}"); + empty_worlds() + } + }; + let references = { + let events = events.lock().await; + match events.document_references() { + Ok(references) => references, + Err(error) => { + warn!("blob gate: cannot read document references: {error}"); + Vec::new() + } + } + }; + // Expand HashSeq collections whose children are all in the store. + let mut children: std::collections::HashMap> = + std::collections::HashMap::new(); + let mut seen: std::collections::BTreeSet = std::collections::BTreeSet::new(); + let mut frontier: Vec = references.iter().map(|(hash, _)| *hash).collect(); + while let Some(hash) = frontier.pop() { + if !seen.insert(hash) { + continue; + } + let Ok(bytes) = store.get_bytes(hash).await else { + continue; + }; + let kids = crate::blob_gate::hashseq_children(&bytes); + if kids.is_empty() { + continue; + } + let mut all_present = true; + for kid in &kids { + match store.has(*kid).await { + Ok(true) => {} + _ => { + all_present = false; + break; + } + } + } + if all_present { + frontier.extend(kids.iter().copied()); + children.insert(hash, kids); + } + } + let named = references + .into_iter() + .filter_map(|(hash, group)| group.map(|group| (hash, crate::blob_gate::world_key(&group)))); + let index = crate::blob_gate::build_reference_index(named, |hash| { + children.get(hash).cloned().unwrap_or_default() + }); + crate::blob_gate::FoldedWorlds::new(worlds, index) +} + +pub async fn cmd_serve(opts: ServeOptions) -> Result<()> { + let ServeOptions { + ephemeral, + groups_log, + no_relay, + no_gossip, + web, + port, + bootstrap, + topic, + topic_secret, + no_default_bootstrap, + no_default_topic, + replace_defaults, + no_mdns, + dht, + iroh_port, + bind, + web_token, + web_cookie_secure, + world, + world_admin_token, + world_module, + world_mail_outbox, + world_mail_command, + world_mail_smtp, + world_mail_from, + world_name, + world_checkpoint_every, + world_max_open, + world_max_sessions, + world_idle_secs, + world_boot_window_secs, + world_caps, + world_cap_policy, + world_allowed_caps, + roc_bin, + roc_platform, + world_native, + world_source_only, + world_ssh_port, + world_runtime, + allow_node, + open_writes, + } = opts; + validate_world_options( + world, + world_admin_token.as_deref(), + world_module.as_ref(), + &world_name, + &world_cap_policy, + world_source_only, + )?; + #[cfg(not(feature = "world"))] + let _ = &world_allowed_caps; + let key = load_or_create_keypair(KEY_FILE).await?; + let node_id: EndpointId = key.public(); + info!("serve: {}", node_id); + + // Who may modify this store: this node, this machine's client key (so the + // local CLI/REPL work with no setup), `--allow-node`, and `.iroh-allowed`. + let access = build_access_policy(node_id, &allow_node, open_writes).await?; + + let store = open_store(ephemeral).await?; + let store_handle = store.as_store(); + + let mut builder = crate::connectivity::public_builder( + crate::connectivity::RelayPolicy::from_no_relay(no_relay), + ) + .secret_key(key.clone()); + if !no_mdns { + builder = builder.address_lookup(MdnsAddressLookup::builder()); + } + let dht_policy = crate::dht::DhtPolicy::from_server(dht); + #[cfg(feature = "dht")] + if dht_policy.is_on() { + builder = crate::dht::with_lookup(&dht_policy, builder, crate::dht::mainline()); + } + #[cfg(not(feature = "dht"))] + if dht_policy.is_on() { + warn!( + "--dht was requested, but `id` was compiled without the optional `dht` feature; DHT lookup is not active" + ); + } + if iroh_port != 0 { + builder = builder.bind_addr(std::net::SocketAddrV4::new( + Ipv4Addr::UNSPECIFIED, + iroh_port, + ))?; + } + let endpoint = builder.bind().await?; + + // Create peer discovery table + let peer_discovery = PeerDiscovery::new(); + + // Always create Gossip — iroh-docs needs it even if peer discovery is off + let gossip = Gossip::builder().spawn(endpoint.clone()); + + // Initialize iroh-docs for tag metadata storage + let docs = if ephemeral { + Docs::memory() + .spawn(endpoint.clone(), store_handle.clone(), gossip.clone()) + .await? + } else { + let docs_path = PathBuf::from(STORE_PATH).join("docs"); + std::fs::create_dir_all(&docs_path)?; + Docs::persistent(docs_path) + .spawn(endpoint.clone(), store_handle.clone(), gossip.clone()) + .await? + }; + + // Initialize TagStore (creates α/Ω namespace pairs) + let tag_store = TagStore::init(&docs, &node_id.to_string()).await?; + let tag_store = Arc::new(tag_store); + info!("tags: initialized (α/Ω global + node namespaces)"); + match tag_store.migrate_legacy_meta(&store_handle).await { + Ok(0) => {} + Ok(n) => info!("tags: imported {n} legacy metadata tag(s) from .meta"), + Err(e) => warn!("tags: legacy metadata import failed: {e:#}"), + } + + // The node's own event store, shared between the web layer and /id-range-sync/1 + // range sync (#792). Serve opens it once, on the same directory the web + // state would open (the `events` sibling of the identity database), and + // hands the one instance to both: the store admits a single opener, and a + // second store over the same directory would diverge from the one the web + // layer publishes ProseMirror save revisions into. Only opened when the + // web UI is on — that is the store whose revisions replicate, and opening + // it unconditionally would change the local CLI's access to the directory + // while serve runs. + #[cfg(feature = "web")] + let event_events: Option>> = if web { + let identity_db_path = std::path::Path::new(KEY_FILE).with_file_name(".identity.redb"); + let events_dir = identity_db_path.with_file_name(crate::local_events::DIR_NAME); + let events = crate::local_events::LocalEvents::open( + &events_dir, + p2panda_core::SigningKey::from_bytes(&key.to_bytes()), + )?; + Some(Arc::new(tokio::sync::Mutex::new(events))) + } else { + None + }; + + // The blob membership gate (#173). With the event store open, serve builds the + // gate from the group log (membership) and the store's document references + // (which blobs each world names), and a refresh task below keeps it current. + // Without the store there is no document source to index, so blob reads stay + // ungated this run — push-only, as before — and serve says so at startup. + #[cfg(feature = "web")] + let blob_gate: Option> = match &event_events { + Some(events) => { + let folded = build_blob_gate( + events, + &store_handle, + &serve_groups_log_path(groups_log.clone()), + ) + .await; + Some(Arc::new(crate::blob_gate::RefreshingWorlds::new(folded))) + } + None => None, + }; + #[cfg(not(feature = "web"))] + let blob_gate: Option> = None; + if blob_gate.is_none() { + warn!( + "blob gate (#173): inactive — the event store is only opened with the web UI, \ + so blob reads are not membership-checked this run" + ); + } + + // Build router — gossip ALPN is always registered (needed by iroh-docs), + // but peer discovery gossip topic only joins when gossip is enabled + let meta = MetaProtocol::new( + &store_handle, + Some(peer_discovery.clone()), + Arc::clone(&tag_store), + access.clone(), + node_id, + ); + // iroh-blobs rejects pushes unless an event handler enables them; this one + // allows them only from nodes the access policy lets write. With the blob + // gate built, the gate's handler decides pushes the same way and also + // membership-checks fetches and observes (#173). + let blobs = match &blob_gate { + Some(gate) => BlobsProtocol::new( + &store_handle, + Some(crate::blob_gate::blob_events( + Arc::clone(gate), + crate::blob_gate::BlobPolicy::default(), + access.clone(), + )), + ), + None => BlobsProtocol::new( + &store_handle, + Some(crate::access::blobs_events(access.clone())), + ), + }; + + // Every world lives in one hub, shared by the Iroh protocol and the web + // bridge. The default world opens now so a bad journal fails startup. + #[cfg(feature = "world")] + let world_hub = if world { + use crate::world_hub::{HubLimits, WorldHub}; + let runtime = crate::world_limits::RuntimeLimits::from_args(&world_runtime)?; + let server_caps = allowed_caps(world_allowed_caps.as_deref())?; + let compiler = resolve_compiler(roc_bin, roc_platform)?; + ensure!( + !world_source_only || compiler.is_some(), + "--world-source-only requires a configured Roc compiler and platform (see --roc-bin and --roc-platform)" + ); + let opener = Arc::new(ServeWorlds { + ephemeral, + admin_token: world_admin_token.clone(), + blobs: store_handle.clone(), + docs: docs.clone(), + checkpoint_every: world_checkpoint_every, + default_world: world_name.clone(), + default_module: world_module.clone(), + grant_on_use: world_cap_policy == "grant-on-use", + server_caps: server_caps.clone(), + compiler, + native: world_native, + source_only: world_source_only, + runtime, + mail: mail_sink( + world_mail_outbox, + world_mail_command, + world_mail_smtp, + world_mail_from, + )?, + }); + let hub = WorldHub::new( + opener, + world_admin_token.clone(), + world_name.clone(), + HubLimits { + max_open_worlds: world_max_open, + max_sessions: world_max_sessions, + signed_boot_window: std::time::Duration::from_secs(world_boot_window_secs), + }, + ); + info!("serve startup: opening default world via hub (#190 breadcrumb)"); + let default_service = hub.open_default().await?; + info!("serve startup: default world open, building router (#190 breadcrumb)"); + if !world_caps.is_empty() { + for cap in world_caps.iter().filter(|cap| *cap != "*") { + if !server_caps.contains(cap) { + warn!( + "world: --world-cap {cap} is outside --world-allowed-caps; the program will be refused it" + ); + } + } + default_service + .world() + .update_caps(world_caps.clone(), Vec::new()) + .await?; + } + if world_idle_secs > 0 && !ephemeral { + let idle = std::time::Duration::from_secs(world_idle_secs); + hub.spawn_evictor( + (idle / 2).clamp( + std::time::Duration::from_secs(1), + std::time::Duration::from_secs(60), + ), + idle, + ); + } + Some(hub) + } else { + None + }; + #[cfg(feature = "world")] + let outbox_flush = match &world_hub { + Some(hub) if !ephemeral => Some(hub.spawn_outbox_flush( + std::time::Duration::from_secs(OUTBOX_FLUSH_SECS), + endpoint.clone(), + )), + _ => None, + }; + #[cfg(not(feature = "world"))] + ensure!(!world, "this build has no world support (feature `world`)"); + + #[cfg(all(feature = "world", feature = "ssh"))] + let (ssh_tunnel, ssh_tunnel_port) = crate::world_ssh::SshTunnelProtocol::deferred(); + let router_builder = Router::builder(endpoint) + .accept(META_ALPN, meta) + .accept(BLOBS_ALPN, blobs) + .accept(iroh_gossip::net::GOSSIP_ALPN, gossip.clone()) + .accept(iroh_docs::net::ALPN, docs.clone()); + #[cfg(feature = "web")] + let router_builder = match &event_events { + Some(events) => router_builder.accept( + crate::event_store::sync::ALPN, + crate::event_sync::EventSyncProtocol::new(Arc::clone(events)), + ), + None => router_builder, + }; + #[cfg(feature = "world")] + let router_builder = match &world_hub { + Some(hub) => router_builder + .accept( + crate::world_net::WORLD_ALPN, + crate::world_net::WorldProtocol::new(hub.clone()), + ) + .accept( + crate::envelope_net::ENVELOPE_ALPN, + crate::envelope_net::EnvelopeProtocol::new(hub.clone()), + ) + .accept( + crate::artifact::PUSH_ALPN, + crate::artifact::ArtifactPushProtocol::new(hub.clone()), + ) + .accept( + crate::artifact::PULL_ALPN, + crate::artifact::ArtifactPullProtocol::new(hub.clone()), + ), + None => router_builder, + }; + #[cfg(all(feature = "world", feature = "ssh"))] + let router_builder = router_builder.accept(crate::world_ssh::SSH_TUNNEL_ALPN, ssh_tunnel); + let router = router_builder.spawn(); + info!("serve startup: router spawned (#190 breadcrumb)"); + + // Offer a sync session to every discovered peer, on an interval: a save on + // either node is discoverable on the other after the next session (#792). + // Peers that do not serve /id-range-sync/1 fail the dial, which is logged at debug + // and otherwise ignored — accepting sessions above is what serves the rest. + #[cfg(feature = "web")] + let _event_sync_handle = event_events.clone().map(|events| { + status!("event sync: /id-range-sync/1 enabled (the web event store)"); + let endpoint = router.endpoint().clone(); + let discovery = peer_discovery.clone(); + let gate = crate::event_sync::open_gate(); + tokio::spawn(async move { + loop { + tokio::time::sleep(crate::event_sync::SYNC_INTERVAL).await; + for peer in discovery.peers() { + let peer_id = peer.announcement.node_id; + if peer_id == endpoint.id() { + continue; + } + match crate::event_sync::sync_with_peer(&endpoint, peer_id, &events, &gate) + .await + { + Ok(outcome) if outcome.sent + outcome.received > 0 => { + info!( + "event sync: {peer_id}: sent {} received {}", + outcome.sent, outcome.received + ); + } + Ok(_) => {} + Err(error) => { + debug!("event sync: session with {peer_id} failed: {error:#}"); + } + } + } + } + }) + }); + + if !no_gossip { + // Resolve effective config from defaults + CLI flags + let config = resolve_config( + &bootstrap, + topic.as_deref(), + topic_secret.as_deref(), + replace_defaults, + no_default_bootstrap, + no_default_topic, + ); + + let dtt_topic_id = TopicId::new(config.topic.clone()); + + // Convert iroh SecretKey to ed25519-dalek types for RecordPublisher + let dalek_signing_key = ed25519_dalek::SigningKey::from_bytes(&key.to_bytes()); + + let record_publisher = RecordPublisher::new( + dtt_topic_id, + dalek_signing_key, + None, + config.topic_secret.clone(), + distributed_topic_tracker::Config::default(), + ); + + // Join gossip topic with auto-discovery (non-blocking) + let gossip_topic = gossip + .subscribe_and_join_with_auto_discovery_no_wait(record_publisher) + .await?; + let (sender, receiver) = gossip_topic.split().await?; + + // Join bootstrap peers (both defaults and CLI-provided, already merged) + let bootstrap_node_ids: Vec = config + .bootstrap + .iter() + .filter_map(|id_str| { + id_str.parse::().ok().or_else(|| { + warn!("invalid bootstrap node ID: {}", id_str); + None + }) + }) + .collect(); + if !bootstrap_node_ids.is_empty() { + info!("joining {} bootstrap peer(s)", bootstrap_node_ids.len()); + sender.join_peers(bootstrap_node_ids, None).await?; + } + + // Spawn background gossip task + let gossip_peer_discovery = peer_discovery.clone(); + let gossip_store = store_handle.clone(); + let gossip_node_id = node_id; + let gossip_endpoint = router.endpoint().clone(); + let _gossip_handle = tokio::spawn(async move { + run_gossip_loop( + gossip_node_id, + sender, + receiver, + gossip_peer_discovery, + gossip_store, + gossip_endpoint, + ) + .await; + }); + + status!("peers: gossip enabled (topic: {})", config.topic); + } + + let serve_node_id = router.endpoint().id(); + let bound_addrs = router.endpoint().bound_sockets(); + let local_addrs: Vec = bound_addrs + .iter() + .map(|addr| match addr { + SocketAddr::V4(v4) if v4.ip().is_unspecified() => { + SocketAddr::new(Ipv4Addr::LOCALHOST.into(), v4.port()) + } + SocketAddr::V6(v6) if v6.ip().is_unspecified() => { + SocketAddr::new(Ipv6Addr::LOCALHOST.into(), v6.port()) + } + other => *other, + }) + .collect(); + + // Bind the web server early to capture the actual port for the lock file, + // but don't start serving yet (spawn happens after lock file is written). + #[allow(unused_mut)] // web_port is only mutated with the `web` feature + let mut web_port: Option = None; + #[cfg(feature = "web")] + let web_listener = if web { + info!("serve startup: binding web listener (#190 breadcrumb)"); + let addr = SocketAddr::new(bind, port); + let listener = tokio::net::TcpListener::bind(addr).await?; + let actual_port = listener.local_addr()?.port(); + info!( + port = actual_port, + "serve startup: web listener bound (#190 breadcrumb)" + ); + web_port = Some(actual_port); + Some(listener) + } else { + None + }; + + #[cfg(feature = "ssh")] + let ssh = match (world_ssh_port, &world_hub) { + (Some(port), Some(hub)) => { + let listener = tokio::net::TcpListener::bind(SocketAddr::new(bind, port)).await?; + let ssh_port = listener.local_addr()?.port(); + #[cfg(feature = "world")] + let _ = ssh_tunnel_port.set(ssh_port); + let host_key = + crate::world_ssh::load_or_create_host_key(crate::world_ssh::SSH_HOST_KEY_FILE) + .await?; + Some(( + listener, + ssh_port, + hub.clone(), + host_key, + store_handle.clone(), + )) + } + _ => None, + }; + #[cfg(not(feature = "ssh"))] + ensure!( + world_ssh_port.is_none(), + "this build has no SSH support (feature `ssh`)" + ); + + // Write the lock file before printing status so it exists when callers + // detect the server via stdout output (integration tests depend on this). + info!("serve startup: writing serve lock (#190 breadcrumb)"); + create_serve_lock(&serve_node_id, &local_addrs, web_port).await?; + info!("serve startup: serve lock written, printing node status (#190 breadcrumb)"); + + status!("node: {serve_node_id}"); + if ephemeral { + status!("mode: ephemeral (in-memory)"); + } else { + status!("mode: persistent ({STORE_PATH})"); + } + if no_relay { + status!("relay: disabled"); + } + if no_gossip { + status!("peers: disabled"); + } + if no_mdns { + status!("mdns: disabled"); + } else { + status!("mdns: enabled"); + } + if access.is_open() { + status!("access: OPEN WRITES (any peer may modify this store)"); + } else { + status!( + "access: read-only for peers; {} node(s) may write", + access.writers().len() + ); + } + #[cfg(feature = "world")] + if world { + status!( + "world {world_name}: enabled (iroh {})", + String::from_utf8_lossy(crate::world_net::WORLD_ALPN) + ); + #[cfg(feature = "web")] + if web { + status!("world: web bridge at /ws/world"); + } + } + + // Start web server now that the lock file is written + #[cfg(feature = "web")] + let _web_handle = if let Some(listener) = web_listener { + let identity_db_path = std::path::Path::new(KEY_FILE).with_file_name(".identity.redb"); + let web_router = match &event_events { + Some(events) => { + crate::web::web_router_with_local_events( + store_handle.clone(), + Some(peer_discovery.clone()), + node_id.to_string(), + Arc::clone(&tag_store), + key.to_bytes(), + identity_db_path, + crate::web::WebSecurity::for_bind(bind, web_token.clone(), &[]), + world_hub.clone(), + web_cookie_secure, + Arc::clone(events), + ) + .await? + } + None => { + crate::web::web_router( + store_handle.clone(), + Some(peer_discovery.clone()), + node_id.to_string(), + Arc::clone(&tag_store), + key.to_bytes(), + identity_db_path, + crate::web::WebSecurity::for_bind(bind, web_token.clone(), &[]), + world_hub.clone(), + web_cookie_secure, + ) + .await? + } + }; + let actual_port = web_port.unwrap_or(port); + let shown_host = if bind.is_unspecified() || bind.is_loopback() { + "localhost".to_owned() + } else { + bind.to_string() + }; + if let Some(t) = &web_token { + status!("web: http://{shown_host}:{actual_port}/?token={t}"); + } else { + status!("web: http://{shown_host}:{actual_port}"); + } + #[cfg(feature = "world")] + if world { + status!("world: browser http://{shown_host}:{actual_port}/world"); + } + if !bind.is_loopback() && web_token.is_none() { + status_err!( + "warning: the web UI is bound to {bind} without --web-token; \ + anyone who can reach port {actual_port} can read and modify files" + ); + } + if world_hub.is_some() && !bind.is_loopback() && !web_cookie_secure { + status_err!( + "warning: the admin sign-in form is served over plain HTTP on {bind}; \ + its token and session cookie travel in clear unless HTTPS is terminated \ + in front (then pass --web-cookie-secure) or the UI is bound to loopback" + ); + } + Some(tokio::spawn(async move { + if let Err(e) = axum::serve(listener, web_router).await { + tracing::error!("web server error: {}", e); + } + })) + } else { + None + }; + + #[cfg(feature = "ssh")] + let ssh_handle = ssh.map(|(listener, ssh_port, hub, host_key, blobs)| { + status!("world ssh: port {ssh_port} (ssh -p {ssh_port} @)"); + status!( + "world ssh host key: {}", + crate::world_ssh::host_key_fingerprint(&host_key) + ); + status!( + "world ssh over iroh: `id world ssh-tunnel ` then `ssh -p 2222 @127.0.0.1`" + ); + tokio::spawn(async move { + if let Err(e) = crate::world_ssh::serve(listener, hub, host_key, blobs).await { + tracing::error!("world ssh server error: {}", e); + } + }) + }); + + // Group warnings (P4.9, #799): one persistent Evaluator for the life of + // the process. The first pass runs here so active warnings surface in + // the CLI status output at startup; the spawned task then re-evaluates + // as membership changes and writes fired warnings to the server log. + let mut group_watcher = GroupWarningWatcher::new(); + let groups_log = serve_groups_log_path(groups_log); + for (_, warning) in evaluate_group_warnings(&mut group_watcher, &groups_log, unix_now()) { + status!("group warning: {}", warning.message()); + } + #[cfg(feature = "web")] + let gate_groups_log = groups_log.clone(); + let group_warning_handle = tokio::spawn(async move { + let mut interval = tokio::time::interval(GROUP_WARNING_INTERVAL); + interval.tick().await; + loop { + interval.tick().await; + evaluate_group_warnings(&mut group_watcher, &groups_log, unix_now()); + } + }); + + // Blob gate refresh (#173): on the same cadence as the group warnings, + // re-fold the group log and the document references so a removed member + // loses fetch and a new document becomes fetchable without a restart. + #[cfg(feature = "web")] + let blob_gate_handle = match (&blob_gate, &event_events) { + (Some(gate), Some(events)) => { + let gate = Arc::clone(gate); + let events = Arc::clone(events); + let store = store_handle.clone(); + let groups_log = gate_groups_log; + Some(tokio::spawn(async move { + let mut interval = tokio::time::interval(GROUP_WARNING_INTERVAL); + interval.tick().await; + loop { + interval.tick().await; + let folded = build_blob_gate(&events, &store, &groups_log).await; + gate.refresh(folded); + } + })) + } + _ => None, + }; + + tokio::signal::ctrl_c().await?; + remove_serve_lock().await?; + router.shutdown().await?; + #[cfg(feature = "web")] + if let Some(sync_task) = _event_sync_handle { + sync_task.abort(); + let _ = sync_task.await; + } + #[cfg(feature = "web")] + if let Some(web_task) = _web_handle { + web_task.abort(); + let _ = web_task.await; + } + #[cfg(feature = "ssh")] + if let Some(ssh_task) = ssh_handle { + ssh_task.abort(); + let _ = ssh_task.await; + } + #[cfg(feature = "world")] + if let Some(flush) = outbox_flush { + flush.abort(); + let _ = flush.await; + } + #[cfg(feature = "world")] + if let Some(hub) = &world_hub { + hub.shutdown_all().await; + } + #[cfg(feature = "web")] + if let Some(gate_task) = blob_gate_handle { + gate_task.abort(); + let _ = gate_task.await; + } + group_warning_handle.abort(); + let _ = group_warning_handle.await; + store.shutdown().await?; + Ok(()) +} + +/// How often serve re-evaluates the group warnings against the group log. +const GROUP_WARNING_INTERVAL: std::time::Duration = std::time::Duration::from_secs(60); + +/// The serve-side group warning watcher (P4.9, #799). +/// +/// Serve holds exactly one of these for the life of the process, so the +/// [`Evaluator`]'s high-water marks survive across evaluations: a group that +/// crosses a size threshold warns once, not on every pass. The groups in the +/// node's own group log are the ones its operator made through the CLI, so +/// every group is observed as client-made. Member counts come from the fold. +/// +/// Group events carry no timestamps, so churn cannot be reconstructed from +/// the log for time before serve started. Instead the watcher derives re-adds +/// from what it observes between evaluations: a device that is authorized, +/// later unauthorized, and then authorized again is a re-add, stamped with +/// the time of the evaluation that first sees it back. +struct GroupWarningWatcher { + evaluator: Evaluator, + /// The devices authorized per group at the previous evaluation. + devices: std::collections::BTreeMap>, + /// Every device ever seen authorized per group. + seen_devices: std::collections::BTreeMap>, + /// The re-add times per group, as observed by this watcher. + readds: std::collections::BTreeMap>, +} + +impl GroupWarningWatcher { + fn new() -> Self { + Self { + evaluator: Evaluator::default(), + devices: std::collections::BTreeMap::new(), + seen_devices: std::collections::BTreeMap::new(), + readds: std::collections::BTreeMap::new(), + } + } + + /// Evaluates every active group in `projection` at `now` (Unix seconds). + /// Returns the warnings this evaluation adds, and writes each of them to + /// the server log through the warnings module. + fn evaluate(&mut self, projection: &Projection, now: u64) -> Vec<(Hash, Warning)> { + let mut fired = Vec::new(); + for (group, view) in projection.groups() { + if !view.is_active() { + continue; + } + let current = projection.group_active_devices(group); + let mut new_readds = 0_usize; + { + let seen = self.seen_devices.entry(*group).or_default(); + let previous = self.devices.entry(*group).or_default(); + for device in ¤t { + if !previous.contains(device) && seen.contains(device) { + new_readds += 1; + } + } + seen.extend(current.iter().copied()); + *previous = current; + } + if new_readds > 0 { + let times = self.readds.entry(*group).or_default(); + for _ in 0..new_readds { + times.push(now); + } + times.retain(|at| { + now.saturating_sub(*at) < crate::groups::warnings::CHURN_WINDOW_SECS + }); + } + let readds = self.readds.get(group).cloned().unwrap_or_default(); + let observation = Observation { + group: *group, + client_made: true, + members: view.members.len(), + readds: &readds, + }; + let warnings = self.evaluator.observe(&observation, now); + if !warnings.is_empty() { + crate::groups::warnings::log(group, &warnings); + fired.extend(warnings.into_iter().map(|warning| (*group, warning))); + } + } + fired + } +} + +/// One warning evaluation pass over the group log at `path`. +/// +/// A missing log means no groups, not an error. A log that cannot be read or +/// folded is noted in the server log and skipped: warnings never block serve. +fn evaluate_group_warnings( + watcher: &mut GroupWarningWatcher, + path: &std::path::Path, + now: u64, +) -> Vec<(Hash, Warning)> { + if !path.exists() { + return Vec::new(); + } + let log = match GroupLog::open(path) { + Ok(log) => log, + Err(error) => { + debug!("group warnings: cannot open {}: {error}", path.display()); + return Vec::new(); + } + }; + let projection = match log.projection() { + Ok(projection) => projection, + Err(error) => { + debug!("group warnings: cannot fold {}: {error}", path.display()); + return Vec::new(); + } + }; + watcher.evaluate(&projection, now) +} + +/// The current time as Unix seconds, for the warning evaluator's clock. +fn unix_now() -> u64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|duration| duration.as_secs()) + .unwrap_or(0) +} + +/// Background loop for gossip-based peer discovery. +/// +/// Runs three concurrent tasks: +/// 1. **Announce**: Broadcasts a [`PeerAnnouncement`] every [`ANNOUNCE_INTERVAL`] +/// 2. **Receive**: Listens for incoming gossip events and updates the peer table +/// 3. **Cleanup**: Periodically probes stale peers via `ListPeers` RPC — refreshes +/// their `last_seen` if reachable, removes them if not +/// +/// This function runs until the sender/receiver are dropped (on shutdown). +async fn run_gossip_loop( + node_id: EndpointId, + sender: distributed_topic_tracker::GossipSender, + mut receiver: distributed_topic_tracker::GossipReceiver, + peer_discovery: PeerDiscovery, + store: iroh_blobs::api::Store, + endpoint: Endpoint, +) { + // Timeout for each individual peer probe. + const PROBE_TIMEOUT: tokio::time::Duration = tokio::time::Duration::from_secs(10); + + let announce_store = store; + let announce_node_id = node_id; + + // Spawn announce task + let announce_handle = tokio::spawn(async move { + let mut interval = tokio::time::interval(ANNOUNCE_INTERVAL); + loop { + interval.tick().await; + // Get blob count from tags + let blob_count = match announce_store.tags().list().await { + Ok(mut stream) => { + let mut count = 0u64; + while stream.next().await.is_some() { + count += 1; + } + count + } + Err(_) => 0, + }; + + let announcement = PeerAnnouncement { + node_id: announce_node_id, + name: None, + blob_count, + timestamp_secs: std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_secs()), + }; + + match postcard::to_allocvec(&announcement) { + Ok(bytes) => { + if let Err(e) = sender.broadcast(bytes).await { + debug!("gossip broadcast error: {}", e); + } + } + Err(e) => { + debug!("gossip announcement serialization error: {}", e); + } + } + } + }); + + // Spawn receive task + let recv_discovery = peer_discovery.clone(); + let recv_handle = tokio::spawn(async move { + loop { + match receiver.next().await { + Ok(event) => match event { + iroh_gossip::api::Event::Received(msg) => { + match postcard::from_bytes::(&msg.content) { + Ok(announcement) => { + debug!( + "peer announcement from {}: blob_count={}", + announcement.node_id, announcement.blob_count + ); + recv_discovery.update(announcement); + } + Err(e) => { + debug!("failed to deserialize peer announcement: {}", e); + } + } + } + iroh_gossip::api::Event::NeighborUp(peer) => { + info!("gossip neighbor up: {}", peer); + } + iroh_gossip::api::Event::NeighborDown(peer) => { + info!("gossip neighbor down: {}", peer); + } + iroh_gossip::api::Event::Lagged => { + warn!("gossip receiver lagged, some messages were missed"); + } + }, + Err(e) => { + debug!("gossip receiver stream ended: {}", e); + break; + } + } + } + }); + + // Spawn stale cleanup task — probes stale peers before removal + let cleanup_discovery = peer_discovery; + + let cleanup_handle = tokio::spawn(async move { + let mut interval = tokio::time::interval(STALE_CHECK_INTERVAL); + + loop { + interval.tick().await; + + let stale = cleanup_discovery.stale_peers(); + if stale.is_empty() { + continue; + } + + debug!("probing {} stale peer(s)", stale.len()); + + for info in &stale { + let peer_id = info.announcement.node_id; + + // Try to connect and send ListPeers RPC + let probe_result = tokio::time::timeout(PROBE_TIMEOUT, async { + let conn = crate::connectivity::connect(&endpoint, peer_id, META_ALPN).await?; + let (mut send, mut recv) = conn.open_bi().await?; + let req = postcard::to_allocvec(&MetaRequest::ListPeers)?; + send.write_all(&req).await?; + send.finish()?; + let resp_buf = crate::meta_client::read_capped_response(&mut recv).await?; + let _resp: MetaResponse = postcard::from_bytes(&resp_buf)?; + conn.close(0u32.into(), b"probe"); + anyhow::Ok(()) + }) + .await; + + match probe_result { + Ok(Ok(())) => { + debug!("stale peer {} is still alive, refreshing", peer_id); + cleanup_discovery.refresh(&peer_id); + } + Ok(Err(e)) => { + debug!("stale peer {} probe failed: {}, removing", peer_id, e); + } + Err(_) => { + debug!("stale peer {} probe timed out, removing", peer_id); + } + } + } + + // Remove peers that are still stale (probes that failed/timed out + // didn't call refresh(), so they remain past STALE_THRESHOLD) + cleanup_discovery.remove_stale(STALE_THRESHOLD); + } + }); + + // Wait for any task to complete (normally they run until shutdown) + tokio::select! { + _ = announce_handle => {} + _ = recv_handle => {} + _ = cleanup_handle => {} + } +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +mod tests { + use super::*; + + /// A scratch directory unique to this test process. + fn serve_test_dir(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("id-serve-test-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir + } + + /// Builds a group log on disk holding one group of `members` accounts + /// (the author included), returning the group's ID. This is the file the + /// serve warning path reads. + fn group_log_with_members(dir: &std::path::Path, members: usize) -> Hash { + group_log_with_members_at(&dir.join(GROUPS_FILE_NAME), members) + } + + fn group_log_with_members_at(path: &std::path::Path, members: usize) -> Hash { + use crate::groups::Role; + use crate::groups::actions::NewGroup; + + let mut log = GroupLog::open(path).unwrap(); + let author: GroupKey = [1; 32]; + let created = log + .create( + author, + NewGroup::Normal { + max: None, + admins_on_create: false, + }, + ) + .unwrap(); + for i in 1..members { + let member: GroupKey = [u8::try_from(i + 1).unwrap(); 32]; + log.add(author, created.group, member, Role::Read).unwrap(); + } + created.group + } + + #[test] + fn serve_groups_log_path_honours_override_and_default() { + // #2778: the group-warning watcher's log path must come + // from the global --groups-log option (threaded through + // ServeOptions), resolved exactly like the group commands + // resolve it; without the option the default file name is + // used, unchanged. + let custom = PathBuf::from("shared").join("relocated.jsonl"); + assert_eq!(serve_groups_log_path(Some(custom.clone())), custom); + assert_eq!(serve_groups_log_path(None), PathBuf::from(GROUPS_FILE_NAME)); + } + + #[test] + fn serve_group_warnings_evaluate_custom_groups_log() { + // #2778 regression: warnings are computed from the + // --groups-log file, not the default groups.jsonl. The + // custom log holds a 96-member group; the default log in + // the same directory does not exist, so a watcher reading + // the default would silently warn about nothing. + let dir = serve_test_dir("customlog"); + let custom = dir.join("relocated.jsonl"); + let group = group_log_with_members_at(&custom, 96); + let path = serve_groups_log_path(Some(custom)); + let mut watcher = GroupWarningWatcher::new(); + let fired = evaluate_group_warnings(&mut watcher, &path, 1_000); + assert_eq!(fired.len(), 1); + assert_eq!(fired[0].0, group); + assert!(matches!( + fired[0].1, + Warning::Size { + threshold: 96, + members: 96 + } + )); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn serve_group_warnings_fire_once_at_each_size_threshold() { + let dir = serve_test_dir("size"); + let path = dir.join(GROUPS_FILE_NAME); + let group = group_log_with_members(&dir, 96); + let mut watcher = GroupWarningWatcher::new(); + + // The integration surface: serve's own evaluation over the on-disk + // group log warns when the group crosses 96 members (P4.9's e2e + // column: "the server warns at a threshold"). + let fired = evaluate_group_warnings(&mut watcher, &path, 1_000); + assert_eq!(fired.len(), 1); + assert_eq!(fired[0].0, group); + assert!(matches!( + fired[0].1, + Warning::Size { + threshold: 96, + members: 96 + } + )); + + // The persistent Evaluator's high-water mark: the same state warns + // no second time. + assert!(evaluate_group_warnings(&mut watcher, &path, 1_001).is_empty()); + + // Growing past the next threshold warns once more, for that tier. + { + let mut log = GroupLog::open(&path).unwrap(); + let author: GroupKey = [1; 32]; + for i in 96..128 { + let member: GroupKey = [u8::try_from(i + 1).unwrap(); 32]; + log.add(author, group, member, crate::groups::Role::Read) + .unwrap(); + } + } + let fired = evaluate_group_warnings(&mut watcher, &path, 1_002); + assert_eq!(fired.len(), 1); + assert!(matches!( + fired[0].1, + Warning::Size { + threshold: 128, + members: 128 + } + )); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn serve_group_warnings_fire_on_device_readd_churn() { + use crate::groups::Role; + + let dir = serve_test_dir("churn"); + let path = dir.join(GROUPS_FILE_NAME); + let group = group_log_with_members(&dir, 2); + let author: GroupKey = [1; 32]; + let device: GroupKey = [200; 32]; + let mut log = GroupLog::open(&path).unwrap(); + let mut watcher = GroupWarningWatcher::new(); + + // The first authorization is not a re-add, and warns about nothing. + log.device_add(author, group, device, Role::Read).unwrap(); + assert!(evaluate_group_warnings(&mut watcher, &path, 1_000).is_empty()); + + // Four revoke + re-authorize cycles inside the window: the fourth + // re-add crosses the churn threshold and warns exactly once. + for cycle in 0..4_u64 { + log.device_revoke(author, group, device).unwrap(); + assert!(evaluate_group_warnings(&mut watcher, &path, 1_001 + cycle * 2).is_empty()); + log.device_add(author, group, device, Role::Read).unwrap(); + let fired = evaluate_group_warnings(&mut watcher, &path, 1_002 + cycle * 2); + if cycle < 3 { + assert!(fired.is_empty(), "cycle {cycle} fired early: {fired:?}"); + } else { + assert_eq!(fired.len(), 1); + assert!(matches!(fired[0].1, Warning::Churn { readds: 4 })); + } + } + let _ = std::fs::remove_dir_all(&dir); + } + + #[cfg(feature = "world")] + #[test] + fn the_server_ceiling_is_the_named_list_or_the_whole_catalog() { + assert_eq!( + allowed_caps(None).unwrap(), + crate::world_caps::catalog_names() + ); + let named = ["time.now".to_owned(), "chat.say".to_owned()]; + assert_eq!( + allowed_caps(Some(&named)) + .unwrap() + .into_iter() + .collect::>(), + vec!["chat.say".to_owned(), "time.now".to_owned()] + ); + assert!(allowed_caps(Some(&["*".to_owned()])).is_err()); + assert!(allowed_caps(Some(&["telepathy".to_owned()])).is_err()); + } + + #[test] + fn world_mode_requires_an_admin_token_but_not_web() { + assert!(validate_world_options(true, None, None, "lobby", "deny", false).is_err()); + assert!(validate_world_options(true, Some(""), None, "lobby", "deny", false).is_err()); + assert!(validate_world_options(true, Some("admin"), None, "lobby", "deny", false).is_ok()); + assert!(validate_world_options(false, None, None, "lobby", "deny", false).is_ok()); + assert!( + validate_world_options( + true, + Some("admin"), + Some(&PathBuf::from("world.wasm")), + "lobby", + "deny", + false + ) + .is_ok() + ); + assert!(validate_world_options(true, Some("admin"), None, "lobby", "deny", true).is_ok()); + assert!( + validate_world_options( + true, + Some("admin"), + Some(&PathBuf::from("world.wasm")), + "lobby", + "deny", + true + ) + .is_err() + ); + assert!( + validate_world_options( + false, + None, + Some(&PathBuf::from("world.wasm")), + "lobby", + "deny", + false + ) + .is_err() + ); + } + + #[cfg(feature = "world")] + #[test] + fn mail_sink_picks_one_transport_and_refuses_an_unusable_relay() { + let loopback: SocketAddr = "127.0.0.1:25".parse().unwrap(); + let remote: SocketAddr = "203.0.113.5:25".parse().unwrap(); + let sender = Some("id@example.test".to_owned()); + assert!(mail_sink(None, None, None, None).unwrap().is_none()); + assert!(mail_sink(None, None, Some(loopback), None).is_err()); + assert!(mail_sink(None, None, Some(remote), sender.clone()).is_err()); + assert!( + mail_sink(None, None, Some(loopback), sender) + .unwrap() + .is_some() + ); + } + + #[test] + fn world_names_are_bounded_and_are_a_single_path_segment() { + for bad in [ + "", + "../evil", + ".", + "..", + "Tic-Tac-Toe", + "a/b", + "sp ace", + "wörld", + ] { + assert!( + validate_world_options(true, Some("admin"), None, bad, "deny", false).is_err(), + "{bad:?} must be refused" + ); + } + assert!(validate_world_options(true, Some("admin"), None, "tt-2_x", "deny", false).is_ok()); + assert!( + validate_world_options(true, Some("admin"), None, &"a".repeat(64), "deny", false) + .is_ok() + ); + assert!( + validate_world_options(true, Some("admin"), None, &"a".repeat(65), "deny", false) + .is_err() + ); + assert!(validate_world_options(true, Some("admin"), None, "lobby", "deny", false).is_ok()); + assert!( + validate_world_options(true, Some("admin"), None, "lobby", "grant-on-use", false) + .is_ok() + ); + assert!( + validate_world_options(true, Some("admin"), None, "lobby", "sometimes", false).is_err(), + "an unknown policy is refused" + ); + } + + #[test] + fn test_is_process_alive_current_process() { + let pid = std::process::id(); + assert!(is_process_alive(pid)); + } + + #[test] + fn test_is_process_alive_nonexistent() { + // Use a very high PID that's unlikely to exist + // Note: On non-Unix this always returns true + #[cfg(unix)] + { + assert!(!is_process_alive(999_999_999)); + } + } + + #[test] + fn test_is_process_alive_pid_1() { + // PID 1 exists in every Unix PID namespace (as init, or as the + // namespace's init in a container). #2384: when the test runs + // unprivileged, pid 1 is foreign-owned and kill(1, 0) fails with + // EPERM — that must still answer alive; as root the probe succeeds + // outright. Either way the assertion holds. + #[cfg(unix)] + { + assert!( + is_process_alive(1), + "pid 1 exists and must read as alive (EPERM is not death)" + ); + } + } + + #[test] + fn test_serve_info_struct() { + use iroh_base::SecretKey; + + let key = SecretKey::generate(); + let node_id = key.public(); + + let info = ServeInfo { + node_id: node_id.to_string(), + pid: 12345, + addrs: vec!["127.0.0.1:8080".to_owned(), "[::1]:8080".to_owned()], + web_port: Some(3000), + }; + + assert_eq!(info.node_id, node_id.to_string()); + assert_eq!(info.addrs.len(), 2); + assert_eq!(info.addrs[0], "127.0.0.1:8080"); + assert_eq!(info.pid, 12345); + assert_eq!(info.web_port, Some(3000)); + } + + #[test] + fn test_serve_info_clone() { + use iroh_base::SecretKey; + + let key = SecretKey::generate(); + let node_id = key.public(); + let info = ServeInfo { + node_id: node_id.to_string(), + pid: 99, + addrs: vec!["127.0.0.1:8080".to_owned()], + web_port: None, + }; + + let cloned = info.clone(); + assert_eq!(cloned.node_id, info.node_id); + assert_eq!(cloned.addrs, info.addrs); + assert_eq!(cloned.pid, info.pid); + assert_eq!(cloned.web_port, info.web_port); + } + + #[test] + fn test_serve_info_json_roundtrip() { + let info = ServeInfo { + node_id: "abc123".to_owned(), + pid: 42, + addrs: vec!["127.0.0.1:8080".to_owned(), "[::1]:9090".to_owned()], + web_port: Some(3001), + }; + + let json = serde_json::to_string(&info).unwrap(); + let parsed: ServeInfo = serde_json::from_str(&json).unwrap(); + assert_eq!(parsed.node_id, "abc123"); + assert_eq!(parsed.pid, 42); + assert_eq!(parsed.addrs.len(), 2); + assert_eq!(parsed.web_port, Some(3001)); + } + + #[test] + fn test_serve_info_json_no_web_port() { + let info = ServeInfo { + node_id: "def456".to_owned(), + pid: 100, + addrs: vec!["127.0.0.1:5555".to_owned()], + web_port: None, + }; + + let json = serde_json::to_string(&info).unwrap(); + let parsed: ServeInfo = serde_json::from_str(&json).unwrap(); + assert_eq!(parsed.web_port, None); + } + + // Integration tests for lock file functions require file system access + // and are tested via the integration test suite +} diff --git a/pkgs/id/src/local_events.rs b/pkgs/id/src/local_events.rs new file mode 100644 index 0000000000..c72ec77d6b --- /dev/null +++ b/pkgs/id/src/local_events.rs @@ -0,0 +1,824 @@ +//! Documents and tags, signed into the event store from one node (P6.7c). +//! +//! `id doc` and `id claim` act through [`LocalEvents`]. Each action signs one event with the node's +//! key, names every other author's head as its `after`, and ingests the event with +//! [`EventStore::ingest`], the path sync uses. The store checks the signature and applies the event. +//! So these events are signed, unlike the group log's (P6.7a), which trusts the caller's name. +//! +//! The CLI opens one store directory, named by `--event-store`, and nodes on one machine that +//! share the directory see each other's events, as they share the group log. Between machines, +//! `id serve` moves the events: it shares this store with the `/id-range-sync/1` range-sync sessions +//! in [`crate::event_sync`], so a revision one node signs into its store is in the sync set the +//! next session carries to a peer (#792). +//! +//! The reads walk every applied event, which is fine for the CLI and is not an index. The document +//! and tag rules are the ones in [`crate::documents`] and [`crate::tag_claims`]. + +use std::collections::{HashMap, HashSet}; +use std::path::Path; +use std::time::{SystemTime, UNIX_EPOCH}; + +use anyhow::{Context, Result, bail}; +use p2panda_core::{Hash, SigningKey}; + +use crate::chain::{ChainExt, Event, MAX_AFTER, sign}; +use crate::documents::{DOCUMENT_KIND, DocumentRef, REMOVAL_KIND}; +use crate::event_store::{EventStore, Ingest, StoreError}; +use crate::search::{Hit, ValueMatch, search_store}; +use crate::tag_claims::{CLEAR_KIND, Claim, MAX_CLEAR_CLAIMS, SET_KIND, TagOp, check_op}; +use crate::waiting::{AuthorKey, WaitingLimits}; + +/// The directory the event store lives in, under the data directory, unless `--event-store` names +/// another. +pub const DIR_NAME: &str = "events"; + +/// One event that is part of a document's history, as the CLI lists it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Entry { + /// The `document.put` that makes the document. Its ID is the document's. + Document { + /// The event's ID. + id: Hash, + /// The key that signed it. + author: AuthorKey, + /// The content the event names. + document: DocumentRef, + }, + /// A `tag.set` on `subject`. + Set { + /// The event's ID, which is the claim's. + id: Hash, + /// The key that signed it. + author: AuthorKey, + /// The event the claim is about. + subject: Hash, + /// The tag name. + name: String, + /// The tag value, if any. + value: Option, + }, + /// A `tag.clear` that names the claims it removes. + Clear { + /// The event's ID. + id: Hash, + /// The key that signed it. + author: AuthorKey, + /// The claims it names. + claims: Vec, + }, + /// A `document.remove` of the document it names. + Remove { + /// The event's ID. + id: Hash, + /// The key that signed it. + author: AuthorKey, + /// The document it removes. + document: Hash, + }, +} + +impl Entry { + /// The event's ID. + #[must_use] + pub const fn id(&self) -> Hash { + match self { + Self::Document { id, .. } + | Self::Set { id, .. } + | Self::Clear { id, .. } + | Self::Remove { id, .. } => *id, + } + } + + /// The key that signed the event. + #[must_use] + pub const fn author(&self) -> AuthorKey { + match self { + Self::Document { author, .. } + | Self::Set { author, .. } + | Self::Clear { author, .. } + | Self::Remove { author, .. } => *author, + } + } + + /// The event's kind, as its header names it. + #[must_use] + pub const fn kind(&self) -> &'static str { + match self { + Self::Document { .. } => DOCUMENT_KIND, + Self::Set { .. } => SET_KIND, + Self::Clear { .. } => CLEAR_KIND, + Self::Remove { .. } => REMOVAL_KIND, + } + } +} + +/// The latest applied event of one author: the head of its chain. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Head { + /// The author. + pub author: AuthorKey, + /// The author's last applied event. + pub event: Hash, + /// That event's sequence number, counted from 0. + pub seq: u64, +} + +/// A published document: its `document.put`'s ID, the reference that event names, and the IDs of +/// the tag claims set with it, in the order the tags were given. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Published { + /// The document's ID: the `document.put` event's ID. + pub id: Hash, + /// The content the document names. + pub document: DocumentRef, + /// The IDs of the claims set with the document, one per tag. + pub claims: Vec, +} + +/// Every applied event's entry by ID, and every applied event's parents by ID. +type Log = (HashMap, HashMap>); + +/// The event store, and the key the node signs its events with. +#[derive(Debug)] +pub struct LocalEvents { + store: EventStore, + key: SigningKey, +} + +impl LocalEvents { + /// Opens the store in `dir`, creating it if it does not exist. Events are signed with `key`. + /// + /// # Errors + /// + /// Fails if the store cannot be opened, for example while another process has it open. + /// The blob references in this node's event store, for the blob gate's index + /// (`EventStore::document_references`). + /// + /// # Errors + /// + /// Returns a store error if the read fails. + pub fn document_references( + &self, + ) -> Result)>, StoreError> { + self.store.document_references() + } + + pub fn open(dir: &Path, key: SigningKey) -> Result { + std::fs::create_dir_all(dir).with_context(|| format!("create {}", dir.display()))?; + let store = EventStore::open(dir, WaitingLimits::default(), now_ms())?; + Ok(Self { store, key }) + } + + /// Runs one range-sync session over `conn` against this node's store: the session + /// [`crate::event_store::sync::sync_over`] drives, with this store as its sync set. + /// `initiator` is the side that dialed. Every event that arrives is decided by the + /// store's own ingest, so a tampered or unsigned event is refused, never applied. + /// + /// # Errors + /// + /// Returns an error if the peer breaks the protocol, the session passes `deadline`, + /// `gate` refuses the peer, or the store fails. + pub async fn sync_session( + &mut self, + conn: &iroh::endpoint::Connection, + initiator: bool, + deadline: std::time::Duration, + gate: &crate::pull_policy::PullGate, + ) -> Result { + crate::event_store::sync::sync_over( + &mut self.store, + conn, + initiator, + crate::event_store::range::Params::default(), + now_ms(), + deadline, + gate, + ) + .await + } + + /// The account the node's events are signed as. + #[must_use] + pub fn author(&self) -> AuthorKey { + *self.key.verifying_key().as_bytes() + } + + /// Publishes `content` as a document of `media_type`, with a tag for each of `tags`. The event + /// names the content by its BLAKE3 hash and size. The bytes are not kept here: they are a blob. + /// Every tag is checked before anything is recorded, so a bad tag records nothing. + /// + /// # Errors + /// + /// Fails if the media type or a tag is refused, or the store cannot record the events. + pub fn publish( + &mut self, + media_type: &str, + content: &[u8], + tags: &[(String, Option)], + ) -> Result { + let document = DocumentRef::for_bytes(media_type, content)?; + for (name, value) in tags { + check_tag(name, value.as_deref())?; + } + let id = self.record(DOCUMENT_KIND, None, Some(document.clone()), None, &[])?; + let mut claims = Vec::with_capacity(tags.len()); + for (name, value) in tags { + claims.push(self.set_tag(id, name, value.as_deref())?); + } + Ok(Published { + id, + document, + claims, + }) + } + + /// Sets the tag `name` on `subject`, with `value` if given. The new claim's ID is the event's. + /// + /// # Errors + /// + /// Fails if the name or value is refused, or the store cannot record the event. + pub fn set_tag(&mut self, subject: Hash, name: &str, value: Option<&str>) -> Result { + let op = TagOp::Set { + subject, + name: name.to_owned(), + value: value.map(str::to_owned), + }; + self.record(SET_KIND, Some(op), None, None, &[]) + } + + /// Clears every live claim named `name` on `subject`, whoever set it. Nothing to clear is an + /// error. + /// + /// One `tag.clear` event names at most [`MAX_CLEAR_CLAIMS`] claims, so a name with more live + /// claims than that is cleared by several events, in the order [`EventStore::tag_claims`] + /// returns the claims. The returned count is the total cleared across all of those events, + /// and the returned ID is the final event's — the one whose recording completes the clear. + /// + /// The events are append-only: if recording one of them fails, the ones already recorded + /// stay, the error is returned, and calling this again clears what is left. + /// + /// A claim is removed only when it sits in the clear's causal past, so each sub-clear + /// names the current head of every author whose claims it names as a required head of + /// its `after` frontier (see [`LocalEvents::bounded_after`]). When the claims span more + /// authors than the frontier cap ([`MAX_AFTER`]) or more claims than one clear may name + /// ([`MAX_CLEAR_CLAIMS`]), the clear is split: several `tag.clear` events are recorded, + /// partitioning the claims by author into groups that fit both caps, in author order. + /// The returned count is the total across all sub-clears, and the returned event ID is + /// the last sub-clear's -- the one after which every named claim is cleared. + /// + /// # Errors + /// + /// Fails if no live claim matches, or the store cannot record an event. + pub fn clear_tag(&mut self, subject: Hash, name: &str) -> Result<(usize, Hash)> { + let claims: Vec = self + .store + .tag_claims()? + .into_iter() + .filter(|claim| claim.subject == subject && claim.name == name) + .collect(); + if claims.is_empty() { + bail!("no live claim on {} is named {name}", subject.to_hex()); + } + let count = claims.len(); + // The current head of each author, for the required tier of each sub-clear. + let heads: HashMap = self + .frontier()? + .into_iter() + .map(|head| (head.author, head.event)) + .collect(); + // Partition the claims by author into groups fitting both caps, in author order. + let mut by_author: HashMap> = HashMap::new(); + for claim in claims { + by_author.entry(claim.author).or_default().push(claim); + } + let mut authors: Vec = by_author.keys().copied().collect(); + authors.sort_unstable(); + let mut groups: Vec> = Vec::new(); + let mut group: Vec = Vec::new(); + let mut group_authors = 0usize; + for author in authors { + let authored = by_author.remove(&author).unwrap_or_default(); + // One author alone can hold more claims than a single clear may + // name (#1720), so pack each author's claims in cap-sized segments. + for segment in authored.chunks(MAX_CLEAR_CLAIMS) { + if !group.is_empty() + && (group_authors == MAX_AFTER + || group.len() + segment.len() > MAX_CLEAR_CLAIMS) + { + groups.push(std::mem::take(&mut group)); + group_authors = 0; + } + group_authors += 1; + group.extend(segment.iter().cloned()); + } + } + if !group.is_empty() { + groups.push(group); + } + let mut last = None; + for group in groups { + let mut required: Vec = Vec::new(); + let mut seen: HashSet = HashSet::new(); + for claim in &group { + if seen.insert(claim.author) { + if let Some(head) = heads.get(&claim.author) { + required.push(*head); + } + } + } + let ids: Vec = group.iter().map(|claim| claim.id).collect(); + last = Some(self.record( + CLEAR_KIND, + Some(TagOp::Clear { claims: ids }), + None, + None, + &required, + )?); + } + let event = last.context("a clear with claims records at least one event")?; + Ok((count, event)) + } + + /// The live claims on `subject`, sorted by claim ID. + /// + /// # Errors + /// + /// Fails if the store cannot be read. + pub fn tags_on(&self, subject: Hash) -> Result> { + Ok(self + .store + .tag_claims()? + .into_iter() + .filter(|claim| claim.subject == subject) + .collect()) + } + + /// The live claims that match `name`, and `value` if given, as [`crate::search`] returns them. + /// + /// # Errors + /// + /// Fails if the store cannot be read. + pub fn search(&self, name: &str, value: Option<&str>) -> Result> { + let matching = value.map_or(ValueMatch::Any, ValueMatch::Exact); + Ok(search_store(&self.store, name, matching)?) + } + + /// The head of each author's chain, in author order. + /// + /// # Errors + /// + /// Fails if the store cannot be read. + pub fn frontier(&self) -> Result> { + Ok(self + .store + .chains()? + .into_iter() + .filter_map(|(author, chain)| { + chain.head.map(|event| Head { + author, + event, + seq: u64::from(chain.next_seq).saturating_sub(1), + }) + }) + .collect()) + } + + /// The events on `document` other than its `document.put`: the tags set on it, the clears of + /// those tags, and any removal. They are in causal order. + /// + /// # Errors + /// + /// Fails if `document` is not a document, or the store cannot be read. + pub fn events_on(&self, document: Hash) -> Result> { + Ok(self + .history(document)? + .into_iter() + .filter(|entry| !matches!(entry, Entry::Document { .. })) + .collect()) + } + + /// The document's events in causal order: its `document.put` first, then the events of + /// [`LocalEvents::events_on`]. Each event comes after the events it names as its causes. + /// + /// # Errors + /// + /// Fails if `document` is not the ID of a `document.put`, or the store cannot be read. + pub fn history(&self, document: Hash) -> Result> { + let (entries, parents) = self.log()?; + if !matches!(entries.get(&document), Some(Entry::Document { .. })) { + bail!( + "{} is not a document: no document.put has that event ID", + document.to_hex() + ); + } + let order = causal_order(&parents); + // The claims set on this document. A clear of any of them belongs to the document too. + let claims_on: HashSet = order + .iter() + .filter_map(|id| match entries.get(id) { + Some(Entry::Set { subject, .. }) if *subject == document => Some(*id), + _ => None, + }) + .collect(); + Ok(order + .iter() + .filter_map(|id| entries.get(id)) + .filter(|entry| match entry { + Entry::Document { id, .. } => *id == document, + Entry::Set { subject, .. } => *subject == document, + Entry::Clear { claims, .. } => claims.iter().any(|claim| claims_on.contains(claim)), + Entry::Remove { + document: removed, .. + } => *removed == document, + }) + .cloned() + .collect()) + } + + /// Every applied event: its entry if it is a document or tag event, and its parents, which are + /// its `after` and its backlink. + fn log(&self) -> Result { + let mut entries = HashMap::new(); + let mut parents = HashMap::new(); + for (author, _) in self.store.chains()? { + for event in self.store.applied_events(&author, None, None, usize::MAX)? { + parents.insert(event.id, parents_of(&event)); + if let Some(entry) = entry_of(&event) { + entries.insert(event.id, entry); + } + } + } + Ok((entries, parents)) + } + + /// The heads of the other authors, which a new event names as its `after`. The node's own head + /// is the new event's backlink, so it is not named twice. + fn other_heads(&self) -> Result> { + let author = self.author(); + Ok(self + .frontier()? + .into_iter() + .filter(|head| head.author != author) + .map(|head| head.event) + .collect()) + } + + /// The `after` frontier for a new event: a dependency frontier, not an author census + /// (#1736). `after` is capped at [`MAX_AFTER`] hashes by the wire format, and events naming + /// more are refused by every existing node, so the frontier must fit the cap no matter how + /// many authors the store holds. + /// + /// When every other author's head fits (the common case), all of them are named, in + /// frontier order, exactly as before. Past the cap, the frontier is built in two tiers: + /// first the `required` heads -- for a `tag.clear`, the current head of each author of a + /// named claim, because a claim is removed only when it sits in the clear's causal past, + /// which the author's head in `after` guarantees through that author's backlink chain -- + /// then the remaining slots fill with the other authors' heads in frontier order. + /// Heads past the cap are simply not named: the events they head stay in the store, and + /// naming a head is about causal past, not about membership, so a later event loses + /// nothing but the claim of having seen them. + fn bounded_after(&self, required: &[Hash]) -> Result> { + let heads = self.other_heads()?; + if heads.len() <= MAX_AFTER { + return Ok(heads); + } + let current: HashSet = heads.iter().copied().collect(); + let mut after: Vec = Vec::with_capacity(MAX_AFTER); + let mut named: HashSet = HashSet::new(); + for head in required { + if after.len() == MAX_AFTER { + break; + } + if current.contains(head) && named.insert(*head) { + after.push(*head); + } + } + for head in heads { + if after.len() == MAX_AFTER { + break; + } + if named.insert(head) { + after.push(head); + } + } + Ok(after) + } + + /// Signs one event with the node's key, after a bounded frontier of the other authors' + /// heads (see [`LocalEvents::bounded_after`]), and ingests it. `required` names heads the + /// frontier must include when it is capped; other kinds than `tag.clear` require none. + /// The store must apply it, or the call fails. + fn record( + &mut self, + kind: &str, + tag: Option, + document: Option, + removes: Option, + required: &[Hash], + ) -> Result { + let author = self.author(); + let after = self.bounded_after(required)?; + let chain = self.store.chain(&author)?.unwrap_or_default(); + let ext = ChainExt { + kind: kind.to_owned(), + group: None, + after, + tag, + document, + removes, + }; + let event = sign(&self.key, chain.next_seq, chain.head, None, ext)?; + match self.store.ingest(&event.bytes, now_ms())? { + Ingest::Accepted { id, .. } => Ok(id), + refused => bail!("the store did not apply the {kind} event: {refused:?}"), + } + } +} + +/// Checks a tag's name and value as the store will, before anything is signed. The subject is not +/// part of the check, so a placeholder stands in for it. +fn check_tag(name: &str, value: Option<&str>) -> Result<()> { + let op = TagOp::Set { + subject: Hash::from_bytes([0; 32]), + name: name.to_owned(), + value: value.map(str::to_owned), + }; + check_op(SET_KIND, &op)?; + Ok(()) +} + +/// The entry of a document or tag event, or `None` for any other event. +fn entry_of(event: &Event) -> Option { + let id = event.id; + let author = *event.header.verifying_key.as_bytes(); + let ext = &event.header.extensions; + match (ext.kind.as_str(), &ext.tag, &ext.document, ext.removes) { + (DOCUMENT_KIND, _, Some(document), _) => Some(Entry::Document { + id, + author, + document: document.clone(), + }), + ( + SET_KIND, + Some(TagOp::Set { + subject, + name, + value, + }), + _, + _, + ) => Some(Entry::Set { + id, + author, + subject: *subject, + name: name.clone(), + value: value.clone(), + }), + (CLEAR_KIND, Some(TagOp::Clear { claims }), _, _) => Some(Entry::Clear { + id, + author, + claims: claims.clone(), + }), + (REMOVAL_KIND, _, _, Some(document)) => Some(Entry::Remove { + id, + author, + document, + }), + _ => None, + } +} + +/// The events an event names as its causes: its `after` hashes and its backlink. +fn parents_of(event: &Event) -> Vec { + let mut named = event.header.extensions.after.clone(); + named.extend(event.header.backlink); + named +} + +/// Every event, each after the events it names. The walk starts from the lowest ID and visits +/// parents in ID order, so the order is the same whatever order the events were stored in. +fn causal_order(parents: &HashMap>) -> Vec { + let mut roots: Vec = parents.keys().copied().collect(); + roots.sort_by_key(|id| *id.as_bytes()); + let mut visited: HashSet = HashSet::new(); + let mut order = Vec::with_capacity(parents.len()); + for root in roots { + let mut stack = vec![(root, false)]; + while let Some((id, expanded)) = stack.pop() { + if expanded { + order.push(id); + continue; + } + if !visited.insert(id) { + continue; + } + stack.push((id, true)); + let mut named = parents.get(&id).cloned().unwrap_or_default(); + named.sort_by_key(|parent| *parent.as_bytes()); + // Pushed in reverse, so the lowest ID is popped, and so expanded, first. + for parent in named.into_iter().rev() { + if !visited.contains(&parent) { + stack.push((parent, false)); + } + } + } + } + order +} + +/// The wall clock in milliseconds, for the store's waiting limits. +fn now_ms() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .ok() + .and_then(|elapsed| u64::try_from(elapsed.as_millis()).ok()) + .unwrap_or(0) +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used)] +mod tests { + use super::*; + + fn id(byte: u8) -> Hash { + Hash::from_bytes([byte; 32]) + } + + fn key(byte: u8) -> SigningKey { + SigningKey::from_bytes(&[byte; 32]) + } + + /// Opens a one-shot node for foreign author `byte` in the shared store + /// and has it set one claim named `name` on `subject`. + fn foreign_claim(dir: &Path, byte: u8, subject: Hash, name: &str) { + let mut events = LocalEvents::open(dir, key(byte)).unwrap(); + events.set_tag(subject, name, Some("x")).unwrap(); + } + + #[test] + fn test_record_still_works_with_more_authors_than_the_after_cap() { + // Regression for #1736: with 33+ other authors in the store, the + // uncapped frontier made every record() fail validation, so the + // node could never write again. + for foreign in [33u8, 100] { + let dir = tempfile::TempDir::new().unwrap(); + let subject = id(200); + for byte in 1..=foreign { + foreign_claim(dir.path(), byte, subject, "topic"); + } + let mut events = LocalEvents::open(dir.path(), key(0)).unwrap(); + let published = events.publish("text/plain", b"hello", &[]).unwrap(); + events.set_tag(published.id, "topic", Some("mine")).unwrap(); + let (cleared, _) = events.clear_tag(published.id, "topic").unwrap(); + assert_eq!(cleared, 1); + } + } + + #[test] + fn test_clear_spanning_more_authors_than_the_cap_clears_exactly_its_claims() { + // Regression for #1736: 40 authors hold a claim named "topic" on the + // subject -- more distinct authors than MAX_AFTER, so the clear must + // split by author. Exactly those claims are removed: a claim with a + // different name on the same subject, and a same-name claim on a + // different subject, both survive. + let dir = tempfile::TempDir::new().unwrap(); + let subject = id(201); + let other_subject = id(202); + for byte in 1..=40u8 { + foreign_claim(dir.path(), byte, subject, "topic"); + } + foreign_claim(dir.path(), 1, subject, "other"); + foreign_claim(dir.path(), 2, other_subject, "topic"); + let mut events = LocalEvents::open(dir.path(), key(0)).unwrap(); + let (cleared, _) = events.clear_tag(subject, "topic").unwrap(); + assert_eq!(cleared, 40); + let remaining = events.tags_on(subject).unwrap(); + assert_eq!(remaining.len(), 1); + assert_eq!(remaining[0].name, "other"); + assert_eq!(events.tags_on(other_subject).unwrap().len(), 1); + } + + #[test] + fn test_causal_order_puts_every_event_after_its_parents() { + // 1 and 2 are roots. 3 names 1, and 4 names 3 and 2. 5 names nothing it did not see. + let parents = HashMap::from([ + (id(1), Vec::new()), + (id(2), Vec::new()), + (id(3), vec![id(1)]), + (id(4), vec![id(3), id(2)]), + (id(5), Vec::new()), + ]); + let order = causal_order(&parents); + assert_eq!(order.len(), 5); + let position = |event: Hash| order.iter().position(|&found| found == event).unwrap(); + assert!(position(id(1)) < position(id(3))); + assert!(position(id(3)) < position(id(4))); + assert!(position(id(2)) < position(id(4))); + // The same events in another map give the same order. + assert_eq!(causal_order(&parents), order); + } + + #[test] + fn test_a_tag_that_the_store_would_refuse_is_refused_before_publish() { + assert!(check_tag("topic", Some("plans")).is_ok()); + assert!(check_tag("", None).is_err()); + assert!(check_tag("e\u{301}", None).is_err()); + } + + fn open_events() -> (tempfile::TempDir, LocalEvents) { + let dir = tempfile::tempdir().unwrap(); + let events = LocalEvents::open(dir.path(), SigningKey::from_bytes(&[7; 32])).unwrap(); + (dir, events) + } + + fn publish_subject(events: &mut LocalEvents) -> Hash { + events.publish("text/plain", b"hello", &[]).unwrap().id + } + + fn set_claims(events: &mut LocalEvents, subject: Hash, name: &str, count: usize) { + for i in 0..count { + events.set_tag(subject, name, Some(&i.to_string())).unwrap(); + } + } + + fn clear_chunks(events: &LocalEvents, subject: Hash) -> Vec<(Hash, usize)> { + events + .events_on(subject) + .unwrap() + .into_iter() + .filter_map(|entry| match entry { + Entry::Clear { id, claims, .. } => Some((id, claims.len())), + _ => None, + }) + .collect() + } + + #[test] + fn test_clear_tag_chunks_a_clear_over_the_claim_cap() { + // Regression for #1720: a name with more live claims than one tag.clear + // may name (MAX_CLEAR_CLAIMS) could never be cleared at all. + let (_dir, mut events) = open_events(); + let subject = publish_subject(&mut events); + let other_subject = publish_subject(&mut events); + set_claims(&mut events, subject, "topic", MAX_CLEAR_CLAIMS + 1); + events.set_tag(subject, "keep", None).unwrap(); + events.set_tag(other_subject, "topic", None).unwrap(); + + let (count, event) = events.clear_tag(subject, "topic").unwrap(); + + assert_eq!(count, MAX_CLEAR_CLAIMS + 1); + let chunks = clear_chunks(&events, subject); + assert_eq!( + chunks.iter().map(|(_, size)| *size).collect::>(), + vec![MAX_CLEAR_CLAIMS, 1] + ); + // The returned ID is the final chunk's, the one that completes the clear. + assert_eq!(chunks.last().unwrap().0, event); + assert!( + events + .tags_on(subject) + .unwrap() + .iter() + .all(|claim| claim.name != "topic") + ); + // Other names, and the same name on other subjects, are untouched. + assert_eq!(events.tags_on(subject).unwrap().len(), 1); + assert_eq!(events.tags_on(other_subject).unwrap().len(), 1); + } + + #[test] + fn test_clear_tag_chunks_600_claims_into_three_events() { + let (_dir, mut events) = open_events(); + let subject = publish_subject(&mut events); + set_claims(&mut events, subject, "topic", 600); + + let (count, event) = events.clear_tag(subject, "topic").unwrap(); + + assert_eq!(count, 600); + let chunks = clear_chunks(&events, subject); + assert_eq!( + chunks.iter().map(|(_, size)| *size).collect::>(), + vec![ + MAX_CLEAR_CLAIMS, + MAX_CLEAR_CLAIMS, + 600 - 2 * MAX_CLEAR_CLAIMS + ] + ); + assert_eq!(chunks.last().unwrap().0, event); + assert!(events.tags_on(subject).unwrap().is_empty()); + } + + #[test] + fn test_clear_tag_at_or_under_the_cap_records_one_event() { + let (_dir, mut events) = open_events(); + let subject = publish_subject(&mut events); + set_claims(&mut events, subject, "topic", 3); + + let (count, event) = events.clear_tag(subject, "topic").unwrap(); + + assert_eq!(count, 3); + assert_eq!(clear_chunks(&events, subject), vec![(event, 3)]); + // Nothing left to clear is still an error. + assert!(events.clear_tag(subject, "topic").is_err()); + } +} From 84e6ac6c3f694208b7bdcd2f0b5320233d7b5d01 Mon Sep 17 00:00:00 2001 From: repo-worker-code Date: Tue, 3 Nov 2026 03:46:45 -0600 Subject: [PATCH 2/8] Fix blob gate fold for multi-group logs (#173) fold_group_events partitioned the group log by world, but GroupLog::record names the log's global heads as after, so any second group's events name dependencies living in another partition. fold::index rejects those partitions with MissingDependency and build_blob_gate failed the whole gate closed, denying even authorized members. Keep only intra-partition after edges: ordering inside a world is preserved and membership reads each world's own projection, so no authority is lost. Adds a regression test with two groups where the second create names the first group's events, as a real group log would. --- pkgs/id/src/blob_gate.rs | 79 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) diff --git a/pkgs/id/src/blob_gate.rs b/pkgs/id/src/blob_gate.rs index 8c2ba7a31b..261c059219 100644 --- a/pkgs/id/src/blob_gate.rs +++ b/pkgs/id/src/blob_gate.rs @@ -176,6 +176,21 @@ pub fn fold_group_events( }; by_world.entry(key).or_default().push(event.clone()); } + // Causality spans the whole log: `GroupLog::record` names the log's global heads as + // `after`, so an event's dependencies routinely live in another world's partition, and + // `fold` rejects a partition that names an absent dependency. Keep only the + // intra-partition edges: ordering inside a world is preserved, and the gate reads each + // world's own projection for membership, so a cross-world `after` edge carries no + // authority the fold would lose. Without this, any second group fails the whole gate + // closed and denies even authorized members every fetch. + for partition in by_world.values_mut() { + let present: BTreeSet<_> = partition.iter().map(|event| event.id).collect(); + for event in partition.iter_mut() { + event + .after + .retain(|dependency| present.contains(dependency)); + } + } Worlds::fold(&by_world, BTreeMap::new()) } @@ -584,6 +599,70 @@ mod tests { )); } + /// `GroupLog::record` names the log's global heads as `after`, so a group created after + /// another names the first group's events — which land in another partition. The fold + /// must tolerate that cross-world causality instead of failing the whole gate closed. + #[test] + fn fold_group_events_tolerates_cross_world_causality() { + fn create() -> Body { + Body::Create(Create { + template: Template::Custom, + policy: Policy::default(), + members: Vec::new(), + admins_on_create: false, + }) + } + let founder = *id(1).as_bytes(); + let member_a = *id(2).as_bytes(); + let member_b = *id(3).as_bytes(); + let create_a = p2panda_core::Hash::digest(b"create-a"); + let add_a = p2panda_core::Hash::digest(b"add-a"); + let create_b = p2panda_core::Hash::digest(b"create-b"); + let add_b = p2panda_core::Hash::digest(b"add-b"); + let events = vec![ + Event { + id: create_a, + author: founder, + after: Vec::new(), + group: None, + body: create(), + }, + Event { + id: add_a, + author: founder, + after: vec![create_a], + group: Some(create_a), + body: Body::Member(MemberOp::Add { + member: member_a, + role: Role::Read, + }), + }, + Event { + id: create_b, + author: founder, + after: vec![create_a, add_a], + group: None, + body: create(), + }, + Event { + id: add_b, + author: founder, + after: vec![create_b, add_a], + group: Some(create_b), + body: Body::Member(MemberOp::Add { + member: member_b, + role: Role::Read, + }), + }, + ]; + let worlds = fold_group_events(&events).expect("cross-world causality must fold"); + let (key_a, key_b) = (world_key(&create_a), world_key(&create_b)); + assert!(worlds.holds_here(&key_a, member_a, Role::Pull)); + assert!(!worlds.holds_here(&key_a, member_b, Role::Pull)); + assert!(worlds.holds_here(&key_b, member_b, Role::Pull)); + assert!(!worlds.holds_here(&key_b, member_a, Role::Pull)); + } + #[test] fn an_unindexed_blob_is_refused_even_to_a_member() { let g = gate(folded(id(1), id(2), false), blob(9)); From b288ea78d77a79a2a1b87559323bdc7cd969626b Mon Sep 17 00:00:00 2001 From: repo-worker-code Date: Tue, 3 Nov 2026 03:51:53 -0600 Subject: [PATCH 3/8] Add blob gate refresh and HashSeq peer tests (#173) --- pkgs/id/tests/blob_gate.rs | 84 +++++++++++++++++++++++++++++++++++++- 1 file changed, 83 insertions(+), 1 deletion(-) diff --git a/pkgs/id/tests/blob_gate.rs b/pkgs/id/tests/blob_gate.rs index c2ccea3d7d..4c47a82ef5 100644 --- a/pkgs/id/tests/blob_gate.rs +++ b/pkgs/id/tests/blob_gate.rs @@ -92,6 +92,18 @@ fn server_store() -> Store { /// A provider that serves `store` through the gate. Pushes are refused for everyone. async fn provider(store: &Store, graph: Graph, policy: BlobPolicy) -> (Router, EndpointAddr) { + provider_with_access(store, Arc::new(graph), policy).await +} + +/// A provider for access implementations whose state changes during a test. +async fn provider_with_access( + store: &Store, + access: Arc, + policy: BlobPolicy, +) -> (Router, EndpointAddr) +where + A: WorldAccess + Send + Sync + 'static, +{ let endpoint = Endpoint::builder(presets::Minimal) .relay_mode(RelayMode::Disabled) .secret_key(SecretKey::from_bytes(&[200; 32])) @@ -99,7 +111,7 @@ async fn provider(store: &Store, graph: Graph, policy: BlobPolicy) -> (Router, E .await .unwrap(); let addr = endpoint.addr(); - let events = blob_events(Arc::new(graph), policy, AccessPolicy::restricted([])); + let events = blob_events(access, policy, AccessPolicy::restricted([])); let router = Router::builder(endpoint) .accept(iroh_blobs::ALPN, BlobsProtocol::new(store, Some(events))) .spawn(); @@ -196,6 +208,76 @@ async fn a_member_of_the_referencing_world_fetches_the_bytes() { router.shutdown().await.unwrap(); } +#[tokio::test] +async fn a_removed_member_is_refused_after_membership_refresh() { + let server = server_store(); + let (docs, _tag) = put(&server, DOCS_BODY).await; + let member = peer(4).await; + let graph = Arc::new(std::sync::RwLock::new(Graph { + members: vec![("docs", member.id)], + refs: vec![(docs, "docs")], + })); + let access = Arc::new(MutableGraph(graph.clone())); + let policy = BlobPolicy::default().with_observe(); + let (router, addr) = provider_with_access(&server, access, policy).await; + + assert_eq!(fetch(&member, &addr, docs).await.unwrap(), DOCS_BODY); + graph.write().unwrap().members.clear(); + assert_eq!(fetch_refusal_code(&member, &addr, docs).await, Some(DENIED)); + assert!(observe(&member, &addr, docs).await.is_err()); + + router.shutdown().await.unwrap(); +} + +/// Membership that a refresh can replace while the provider is serving peers. +struct MutableGraph(Arc>); + +impl WorldAccess for MutableGraph { + fn is_current_member(&self, world: &str, requester: &EndpointId) -> bool { + self.0 + .read() + .unwrap() + .members + .iter() + .any(|(candidate, member)| *candidate == world && member == requester) + } + + fn worlds_referencing(&self, hash: &Hash) -> Vec { + self.0 + .read() + .unwrap() + .refs + .iter() + .filter(|(candidate, _)| candidate == hash) + .map(|(_, world)| (*world).to_owned()) + .collect() + } +} + +#[tokio::test] +async fn a_member_can_fetch_a_hashseq_child_but_a_non_member_cannot() { + let server = server_store(); + let (child, _child_tag) = put(&server, DOCS_BODY).await; + let (hashseq, _hashseq_tag) = put(&server, child.as_bytes()).await; + let member = peer(5).await; + let stranger = peer(6).await; + // The sequence itself and its child are both attributed to the same world; the index + // builder's transitive attribution is separately exercised by blob_gate unit tests. + let graph = Graph { + members: vec![("docs", member.id)], + refs: vec![(hashseq, "docs"), (child, "docs")], + }; + let (router, addr) = provider(&server, graph, BlobPolicy::default()).await; + + assert_eq!(fetch(&member, &addr, child).await.unwrap(), DOCS_BODY); + assert_eq!( + fetch_refusal_code(&stranger, &addr, child).await, + Some(DENIED) + ); + + router.shutdown().await.unwrap(); +} + #[tokio::test] async fn a_member_of_the_referencing_world_observes_when_the_server_enables_it() { let server = server_store(); From bafde04e3da89c592b9916d06d2f84dca94efa27 Mon Sep 17 00:00:00 2001 From: repo-worker-code Date: Tue, 3 Nov 2026 04:03:21 -0600 Subject: [PATCH 4/8] Preserve group-log causality in blob gate (#173) --- pkgs/id/src/blob_gate.rs | 142 ++++++++++++++++++++++------------ pkgs/id/src/commands/serve.rs | 23 ++++-- 2 files changed, 106 insertions(+), 59 deletions(-) diff --git a/pkgs/id/src/blob_gate.rs b/pkgs/id/src/blob_gate.rs index 261c059219..f9ff182de1 100644 --- a/pkgs/id/src/blob_gate.rs +++ b/pkgs/id/src/blob_gate.rs @@ -24,7 +24,7 @@ //! wires [`blob_events`] with those pieces whenever it has the node's event store open. use std::{ - collections::{BTreeMap, BTreeSet, HashMap}, + collections::{BTreeSet, HashMap}, sync::{Arc, RwLock}, }; @@ -110,10 +110,11 @@ pub fn decide( }) } -/// [`WorldAccess`] over the folded worlds. +/// [`WorldAccess`] over a full group-log projection or the older per-world folds. /// -/// Membership is the world's own authority, as [`Worlds::holds_here`] gives it: a member of its -/// group, or a grant in its own chains. A crossing from another world does not count. +/// For a full group-log projection, membership is queried by the exact group hash the world +/// names, so another group's membership or grants cannot leak across worlds. A per-world fold +/// uses [`Worlds::holds_here`], which likewise excludes crossings from another world. /// /// The reference index maps a blob hash to the worlds that name it. It is built by /// [`build_reference_index`] from the event store's document references; artifacts are not a @@ -122,21 +123,51 @@ pub fn decide( /// unreferenced, which refuses it to every requester. #[derive(Debug)] pub struct FoldedWorlds { - worlds: Worlds, + membership: FoldedMembership, references: HashMap>, } +#[derive(Debug)] +enum FoldedMembership { + PerWorld(Worlds), + GroupProjection(crate::groups::Projection), +} + impl FoldedWorlds { /// Pairs the folded worlds with a reference index. pub const fn new(worlds: Worlds, references: HashMap>) -> Self { - Self { worlds, references } + Self { + membership: FoldedMembership::PerWorld(worlds), + references, + } + } + + /// Pairs a full group-log projection with a reference index. + /// + /// Unlike `new`, the projection spans all groups in the group log and therefore preserves + /// its complete causal graph. Each membership request is limited to the group named by its + /// world key. + pub const fn from_group_projection( + projection: crate::groups::Projection, + references: HashMap>, + ) -> Self { + Self { + membership: FoldedMembership::GroupProjection(projection), + references, + } } } impl WorldAccess for FoldedWorlds { fn is_current_member(&self, world: &str, requester: &EndpointId) -> bool { - self.worlds - .holds_here(world, *requester.as_bytes(), Role::Pull) + match &self.membership { + FoldedMembership::PerWorld(worlds) => { + worlds.holds_here(world, *requester.as_bytes(), Role::Pull) + } + FoldedMembership::GroupProjection(projection) => { + group_projection_member(projection, world, requester) + } + } } fn worlds_referencing(&self, hash: &Hash) -> Vec { @@ -154,44 +185,52 @@ pub fn world_key(group: &p2panda_core::Hash) -> String { group.to_string() } -/// Folds group-log events into the [`Worlds`] the gate reads membership from. +/// Folds group-log events into one projection the gate reads membership from. /// -/// Events are partitioned by world: a create event opens the world keyed by its own hash -/// (a friendship's create names its derived group instead), and every other event joins -/// the world its `group` names. An event that names no group and creates none belongs to -/// no world and is skipped. +/// The whole log is folded once, as one causal graph: `GroupLog::record` names the log's +/// global heads as `after`, so an event's dependencies routinely live in another group, and +/// partitioning the log by world hands `fold` dependencies it cannot resolve. Keeping the +/// complete graph also preserves cross-group vetoes and removals, which per-world partitions +/// would silently drop. +/// +/// The one projection holds every group. [`group_projection_member`] reads membership for the +/// group the requested world names, so another group's membership cannot leak authority. /// /// # Errors /// -/// Any error [`Worlds::fold`] gives for one world. +/// Any error [`crate::groups::fold`] gives for the log. pub fn fold_group_events( events: &[crate::groups::Event], -) -> Result { - let mut by_world: BTreeMap> = BTreeMap::new(); - for event in events { - let key = match (&event.body, &event.group) { - (_, Some(group)) => world_key(group), - (crate::groups::Body::Create(_), None) => world_key(&event.id), - _ => continue, - }; - by_world.entry(key).or_default().push(event.clone()); - } - // Causality spans the whole log: `GroupLog::record` names the log's global heads as - // `after`, so an event's dependencies routinely live in another world's partition, and - // `fold` rejects a partition that names an absent dependency. Keep only the - // intra-partition edges: ordering inside a world is preserved, and the gate reads each - // world's own projection for membership, so a cross-world `after` edge carries no - // authority the fold would lose. Without this, any second group fails the whole gate - // closed and denies even authorized members every fetch. - for partition in by_world.values_mut() { - let present: BTreeSet<_> = partition.iter().map(|event| event.id).collect(); - for event in partition.iter_mut() { - event - .after - .retain(|dependency| present.contains(dependency)); - } - } - Worlds::fold(&by_world, BTreeMap::new()) +) -> Result { + crate::groups::fold(events) +} + +/// Whether `requester` is a current `Pull` member of the group `world` names in the full log. +/// +/// A world key is the hex of the group's create event hash (see [`world_key`]), so the global +/// projection can be asked about exactly that group. +#[must_use] +fn group_projection_member( + projection: &crate::groups::Projection, + world: &str, + requester: &EndpointId, +) -> bool { + let Ok(group_id) = crate::groups::log::hash_from_hex(world) else { + return false; + }; + let actor = *requester.as_bytes(); + projection.group(&group_id).is_some_and(|group| { + group.is_active() + && group + .members + .get(&actor) + .is_some_and(|role| *role >= Role::Pull) + }) || projection.grants_in_force().any(|grant| { + grant.group == group_id + && grant.target.is_none() + && grant.to == actor + && grant.scope >= Role::Pull + }) } /// The child hashes a blob's bytes name when the blob is a `HashSeq`: the sequence is the @@ -600,8 +639,8 @@ mod tests { } /// `GroupLog::record` names the log's global heads as `after`, so a group created after - /// another names the first group's events — which land in another partition. The fold - /// must tolerate that cross-world causality instead of failing the whole gate closed. + /// another names the first group's events. Fold the complete graph and still keep each + /// group's membership isolated. #[test] fn fold_group_events_tolerates_cross_world_causality() { fn create() -> Body { @@ -655,12 +694,13 @@ mod tests { }), }, ]; - let worlds = fold_group_events(&events).expect("cross-world causality must fold"); + let projection = fold_group_events(&events).expect("cross-world causality must fold"); let (key_a, key_b) = (world_key(&create_a), world_key(&create_b)); - assert!(worlds.holds_here(&key_a, member_a, Role::Pull)); - assert!(!worlds.holds_here(&key_a, member_b, Role::Pull)); - assert!(worlds.holds_here(&key_b, member_b, Role::Pull)); - assert!(!worlds.holds_here(&key_b, member_a, Role::Pull)); + let folded = FoldedWorlds::from_group_projection(projection, HashMap::new()); + assert!(folded.is_current_member(&key_a, &id(2))); + assert!(!folded.is_current_member(&key_a, &id(3))); + assert!(folded.is_current_member(&key_b, &id(3))); + assert!(!folded.is_current_member(&key_b, &id(2))); } #[test] @@ -827,9 +867,9 @@ mod producer_tests { fn folded_group_log_gates_fetch_and_refresh_revokes_it() { let member = id(2); let (events, world) = group_events(member, false); - let worlds = fold_group_events(&events).expect("the log folds"); + let projection = fold_group_events(&events).expect("the log folds"); let index = build_reference_index([(blob(7), world.clone())], |_| Vec::new()); - let gate = RefreshingWorlds::new(FoldedWorlds::new(worlds, index)); + let gate = RefreshingWorlds::new(FoldedWorlds::from_group_projection(projection, index)); let policy = BlobPolicy::default(); assert!( decide(&gate, &policy, &member, &blob(7), Request::Fetch), @@ -846,9 +886,9 @@ mod producer_tests { // The member is removed; a refreshed fold must revoke the fetch at once. let (events, world) = group_events(member, true); - let worlds = fold_group_events(&events).expect("the log folds"); + let projection = fold_group_events(&events).expect("the log folds"); let index = build_reference_index([(blob(7), world)], |_| Vec::new()); - gate.refresh(FoldedWorlds::new(worlds, index)); + gate.refresh(FoldedWorlds::from_group_projection(projection, index)); assert!( !decide(&gate, &policy, &member, &blob(7), Request::Fetch), "a removed member loses fetch on the next request" diff --git a/pkgs/id/src/commands/serve.rs b/pkgs/id/src/commands/serve.rs index 655f9cd80e..d1b0505414 100644 --- a/pkgs/id/src/commands/serve.rs +++ b/pkgs/id/src/commands/serve.rs @@ -740,15 +740,17 @@ async fn build_blob_gate( store: &iroh_blobs::api::Store, groups_log: &std::path::Path, ) -> crate::blob_gate::FoldedWorlds { - let empty_worlds = crate::groups::worlds::Worlds::empty; - let worlds = match GroupLog::open(groups_log) { - Ok(log) => crate::blob_gate::fold_group_events(log.events()).unwrap_or_else(|error| { - warn!("blob gate: group log does not fold: {error}"); - empty_worlds() - }), + let group_projection = match GroupLog::open(groups_log) { + Ok(log) => match crate::blob_gate::fold_group_events(log.events()) { + Ok(projection) => Some(projection), + Err(error) => { + warn!("blob gate: group log does not fold: {error}"); + None + } + }, Err(error) => { warn!("blob gate: cannot open group log: {error}"); - empty_worlds() + None } }; let references = { @@ -798,7 +800,12 @@ async fn build_blob_gate( let index = crate::blob_gate::build_reference_index(named, |hash| { children.get(hash).cloned().unwrap_or_default() }); - crate::blob_gate::FoldedWorlds::new(worlds, index) + match group_projection { + Some(projection) => { + crate::blob_gate::FoldedWorlds::from_group_projection(projection, index) + } + None => crate::blob_gate::FoldedWorlds::new(crate::groups::worlds::Worlds::empty(), index), + } } pub async fn cmd_serve(opts: ServeOptions) -> Result<()> { From aa61e7b81153f97853ff81348e40e62fce4763b1 Mon Sep 17 00:00:00 2001 From: repo-worker-tmp-code-b Date: Fri, 13 Nov 2026 03:09:51 -0600 Subject: [PATCH 5/8] Fix blob gate Codex findings: local reads, bounded HashSeq expansion, design record (#173) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit P1 (serve wiring): the gate now trusts the node's own key and the data directory client key as local readers (decide_with_local), mirroring build_access_policy — the local CLI/REPL keep reading locally published (group: None) and uploaded blobs with the gate on; remote peers still need world membership for every hash. P2 (reference index build): HashSeq expansion only considers group-referenced blobs and reads a blob only when the store status reports it complete with a positive multiple-of-32 size no larger than MAX_HASHSEQ_BYTES (1 MiB), so index building no longer loads whole documents into memory to guess at collections. P1 (docs): dated design record for the authorization wiring — reference source, HashSeq inference, refresh/revocation timing, local trust, and the ungated non-web behavior — per pkgs/id AGENTS.md. Tests: blob_gate lib 19 passed (new decide_with_local unit test), blob_gate integration 11 passed (new peer-level local-reader test: local reader fetches an unreferenced blob, stranger refused), documents 7 passed, content_removal 5 passed; cargo check --features web passes. --- ...Z_design_blob_gate_authorization_wiring.md | 98 +++++++++++++++++ pkgs/id/crates/id-cli/src/local.rs | 1 + pkgs/id/src/blob_gate.rs | 102 ++++++++++++++++-- pkgs/id/src/commands/serve.rs | 43 +++++++- pkgs/id/tests/blob_gate.rs | 64 ++++++++++- pkgs/id/tests/content_removal.rs | 1 + pkgs/id/tests/documents.rs | 1 + 7 files changed, 298 insertions(+), 12 deletions(-) create mode 100644 doc/2026-11-13T09-00-00Z_design_blob_gate_authorization_wiring.md diff --git a/doc/2026-11-13T09-00-00Z_design_blob_gate_authorization_wiring.md b/doc/2026-11-13T09-00-00Z_design_blob_gate_authorization_wiring.md new file mode 100644 index 0000000000..f3423f973c --- /dev/null +++ b/doc/2026-11-13T09-00-00Z_design_blob_gate_authorization_wiring.md @@ -0,0 +1,98 @@ +# Design: blob gate authorization wiring in `id serve` (#173) + +Date: 2026-11-13. Status: implemented on the #173 branch (PR #7181). +Companion to the gate's own module record in `src/blob_gate.rs`; this record +covers the *wiring* — where the gate's inputs come from, when they refresh, +and what happens when they are absent — which is the part that changes +production blob authorization. + +## Context + +`iroh-blobs` answers a `get` for any hash from any peer, and `observe` with +the blob's size and held ranges. The blob gate (`blob_gate::decide`) makes +both membership-checked: a fetch or observe is served only to a current +member of a world that references the hash. `id serve` is where that +decision meets the live store, and this record documents the wiring before +it is relied on. + +## Decision + +### Reference source: the event store's document references + +The reference index (hash → worlds that name it) is built from the event +store's document references (`EventStore::document_references`): each +document event names a blob hash and, optionally, its group. The world key +is the hex of the group's create-event hash (`blob_gate::world_key`), the +same key the membership fold uses, so a document's group and the group's +membership agree by construction. A document with **no group names no +world**: its blob stays unreferenced and is refused to every remote peer. +Artifacts are not a source: they carry SHA-256 hashes, not BLAKE3 blob +hashes, and only WASM modules are pinned, without a record of their world. + +### HashSeq inference: present-children-only, size-bounded + +A referenced blob that parses as a `HashSeq` (a list of 32-byte hashes) +contributes its children to the referencing world, transitively — a member +fetching a collection needs its contents, not just the sequence blob. +Inference is conservative on both axes: + +- **All children must already be in the store.** Arbitrary content whose + length is a multiple of 32 would otherwise spray references onto hashes + nobody stored. +- **The read is size-bounded.** Only a group-referenced blob is a + candidate, and it is read into memory only when the store status reports + it complete with a size that is a positive multiple of 32 and no larger + than `MAX_HASHSEQ_BYTES` (1 MiB, 32768 children). The size is asked from + the store, never learned by reading the content, so building the index + costs memory proportional to candidate collections, not to the largest + document the node holds. + +### Membership source and refresh / revocation timing + +Membership is the group log folded as one causal graph +(`blob_gate::fold_group_events`): partitioning the log per world would +drop the cross-group dependencies, vetoes, and removals the fold needs. +Any source that fails to read folds to empty for that source — the gate +fails closed and the next refresh retries. + +The fold is not a startup snapshot. `RefreshingWorlds` swaps fresh folds in +as they are rebuilt; every decision reads the latest fold. A removed +member therefore loses fetch at the next refresh, not at the next restart, +and a newly referenced document becomes fetchable the same way. + +### Local reads: the operator is trusted, by key + +The gate is installed on the same blob protocol the local CLI and REPL +use. `LocalEvents::record` writes `group: None`, so documents published +locally (including editor saves) are referenced by no world, and plain +uploads through `commands/put.rs` create no document references at all — +a membership-only gate would deny the operator their own store the +moment the web UI is enabled. + +The wiring therefore passes the node's **local readers** to the gate: the +node's own key and the data directory's client key — exactly the keys +`build_access_policy` already trusts automatically for writes. A local +reader may fetch and observe any blob in its own store +(`decide_with_local`). The trust is keyed, not positional: it follows +those two keys and no others, and a remote peer's request is still +decided by membership alone. If the client key cannot be loaded, local +readers degrade to the node's own key and a warning is logged. + +### Ungated behavior: no event store, no gate — loudly + +The event store is opened only with the web UI, so a non-web `serve` has +no document references to build an index from and runs **without** the +gate. That state is announced at startup with a warning naming #173 +("blob reads are not membership-checked this run"), never silently. +Closing that gap means opening the event store without the web UI, which +is a separate behavior change and is deliberately not made here. + +## Consequences + +- Remote blob authorization is default-deny: unreferenced and + not-a-member look identical, and observe needs the server policy to + serve it for the referencing world on top of membership. +- Startup and refresh cost is bounded by candidate HashSeq collections + (see the size bound), not by total store size. +- The operator's local workflows (CLI get/gethash, REPL fetches, editor + saves) behave identically with the gate on or off. diff --git a/pkgs/id/crates/id-cli/src/local.rs b/pkgs/id/crates/id-cli/src/local.rs index 5a51577ab3..967a9fffd5 100644 --- a/pkgs/id/crates/id-cli/src/local.rs +++ b/pkgs/id/crates/id-cli/src/local.rs @@ -222,6 +222,7 @@ impl LocalNode { Arc::clone(gate), policy.clone(), access, + std::collections::BTreeSet::from([self.node_id]), )), ), None => BlobsProtocol::new(&self.blobs, Some(blobs_events(access))), diff --git a/pkgs/id/src/blob_gate.rs b/pkgs/id/src/blob_gate.rs index f9ff182de1..28275f06a1 100644 --- a/pkgs/id/src/blob_gate.rs +++ b/pkgs/id/src/blob_gate.rs @@ -15,6 +15,13 @@ //! membership table, never the blob store. //! - **Fails closed.** A request from a connection with no known `EndpointId` is refused, and so //! is one whose verdict cannot be delivered. +//! - **Local reads are the operator's.** The node's own key and its data directory's client +//! key — the two keys `build_access_policy` already trusts automatically for writes — may +//! fetch and observe any blob in the node's own store (see [`decide_with_local`]). The +//! local CLI and REPL connect with the client key, and locally published content +//! (documents with no group, plain uploads) is referenced by no world; without this the +//! gate would lock the operator out of their own store. Local trust extends to no other +//! peer: a remote requester still needs world membership for every hash. //! //! The reference index and the membership query are behind [`WorldAccess`]. [`FoldedWorlds`] //! answers membership from the folded worlds. The index has a producer now: @@ -110,6 +117,24 @@ pub fn decide( }) } +/// Whether `requester` may make `request` for `hash`, counting local trust. +/// +/// A requester in `local_readers` — the node's own key and its data directory's client +/// key, the keys the write policy trusts automatically — may fetch or observe any blob +/// in its own store, referenced or not: that is how the local CLI and REPL keep working +/// when the gate is on, including for locally published content no world references. +/// Everyone else is decided by [`decide`], unchanged. +pub fn decide_with_local( + access: &impl WorldAccess, + policy: &BlobPolicy, + local_readers: &BTreeSet, + requester: &EndpointId, + hash: &Hash, + request: Request, +) -> bool { + local_readers.contains(requester) || decide(access, policy, requester, hash, request) +} + /// [`WorldAccess`] over a full group-log projection or the older per-world folds. /// /// For a full group-log projection, membership is queried by the exact group hash the world @@ -349,9 +374,10 @@ fn admit( /// Build the [`EventSender`] that a provider passes to `BlobsProtocol::new`. /// -/// Fetch, `get_many` and observe are decided by [`decide`] over `access`. Pushes are decided by -/// `writes`, as in [`crate::access::blobs_events`]. Every request is intercepted, so no store -/// read happens before the verdict. +/// Fetch, `get_many` and observe are decided by [`decide_with_local`] over `access` and +/// `local_readers`. Pushes are decided by `writes`, as in +/// [`crate::access::blobs_events`]. Every request is intercepted, so no store read +/// happens before the verdict. /// /// A background task is spawned on the current Tokio runtime and ends when the sender is /// dropped. @@ -359,6 +385,7 @@ pub fn blob_events( access: Arc, policy: BlobPolicy, writes: AccessPolicy, + local_readers: BTreeSet, ) -> EventSender { let (tx, mut rx) = tokio::sync::mpsc::channel::(64); let mask = EventMask { @@ -383,22 +410,42 @@ pub fn blob_events( } ProviderMessage::GetRequestReceived(m) => { let verdict = admit(peers.get(&m.connection_id), |id| { - decide(&*access, &policy, id, &m.request.hash, Request::Fetch) + decide_with_local( + &*access, + &policy, + &local_readers, + id, + &m.request.hash, + Request::Fetch, + ) }); let _ = m.tx.send(verdict).await; } ProviderMessage::GetManyRequestReceived(m) => { let verdict = admit(peers.get(&m.connection_id), |id| { - m.request - .hashes - .iter() - .all(|hash| decide(&*access, &policy, id, hash, Request::Fetch)) + m.request.hashes.iter().all(|hash| { + decide_with_local( + &*access, + &policy, + &local_readers, + id, + hash, + Request::Fetch, + ) + }) }); let _ = m.tx.send(verdict).await; } ProviderMessage::ObserveRequestReceived(m) => { let verdict = admit(peers.get(&m.connection_id), |id| { - decide(&*access, &policy, id, &m.request.hash, Request::Observe) + decide_with_local( + &*access, + &policy, + &local_readers, + id, + &m.request.hash, + Request::Observe, + ) }); let _ = m.tx.send(verdict).await; } @@ -475,6 +522,43 @@ mod tests { } } + #[test] + #[test] + fn a_local_reader_fetches_an_unreferenced_blob_but_a_stranger_cannot() { + // No world references blob(9) and nobody is a member of anything: the + // membership rule alone refuses everyone, which is the lockout the local + // trust exists to prevent for the operator's own keys. + let t = Table::default(); + let p = BlobPolicy::default(); + let local = BTreeSet::from([id(7)]); + assert!(decide_with_local( + &t, + &p, + &local, + &id(7), + &blob(9), + Request::Fetch + )); + assert!(!decide_with_local( + &t, + &p, + &local, + &id(8), + &blob(9), + Request::Fetch + )); + // Local trust also covers observe of the operator's own store, even + // when the server policy leaves observe off for worlds. + assert!(decide_with_local( + &t, + &p, + &local, + &id(7), + &blob(9), + Request::Observe + )); + } + #[test] fn a_non_member_is_refused_fetch_and_observe() { let t = one_world(id(1), blob(9)); diff --git a/pkgs/id/src/commands/serve.rs b/pkgs/id/src/commands/serve.rs index d1b0505414..880cd78b83 100644 --- a/pkgs/id/src/commands/serve.rs +++ b/pkgs/id/src/commands/serve.rs @@ -725,6 +725,13 @@ fn serve_groups_log_path(path: Option) -> PathBuf { crate::commands::group::log_path(path) } +/// The largest blob the gate's HashSeq expansion will read into memory: a +/// `HashSeq` of this size names 32768 children, far beyond any collection +/// this node serves; a larger blob is treated as plain content, never a +/// collection, so building the reference index stays size-bounded. +#[cfg(feature = "web")] +const MAX_HASHSEQ_BYTES: u64 = 1 << 20; + /// Builds the blob gate's folded worlds from the two sources serve has: the group /// log at `groups_log` for membership, and the event store's document references /// for which blobs each world names (#173). @@ -763,15 +770,34 @@ async fn build_blob_gate( } } }; - // Expand HashSeq collections whose children are all in the store. + // Expand HashSeq collections whose children are all in the store. The + // expansion is bounded (#7181 review): only a group-referenced blob can + // contribute children to the index — an ungrouped reference is discarded + // below, so reading it here would be pure waste — and a blob is read into + // memory only when its stored size, asked from the store status rather + // than the content, is a positive multiple of 32 no larger than + // MAX_HASHSEQ_BYTES. A HashSeq is a list of 32-byte hashes; anything else + // cannot be one, and an oversized one is not worth a startup-time read + // proportional to its full contents. let mut children: std::collections::HashMap> = std::collections::HashMap::new(); let mut seen: std::collections::BTreeSet = std::collections::BTreeSet::new(); - let mut frontier: Vec = references.iter().map(|(hash, _)| *hash).collect(); + let mut frontier: Vec = references + .iter() + .filter(|(_, group)| group.is_some()) + .map(|(hash, _)| *hash) + .collect(); while let Some(hash) = frontier.pop() { if !seen.insert(hash) { continue; } + let Ok(iroh_blobs::api::blobs::BlobStatus::Complete { size }) = store.status(hash).await + else { + continue; + }; + if size == 0 || size > MAX_HASHSEQ_BYTES || !size.is_multiple_of(32) { + continue; + } let Ok(bytes) = store.get_bytes(hash).await else { continue; }; @@ -991,6 +1017,18 @@ pub async fn cmd_serve(opts: ServeOptions) -> Result<()> { // allows them only from nodes the access policy lets write. With the blob // gate built, the gate's handler decides pushes the same way and also // membership-checks fetches and observes (#173). + // The gate's local readers: the node's own key and the data directory's + // client key — the keys the write policy already trusts automatically — + // so the local CLI and REPL keep reading the node's own store with the + // gate on (#173, #7181 review). + let local_readers: std::collections::BTreeSet = + match load_or_create_keypair(crate::CLIENT_KEY_FILE).await { + Ok(client_key) => [node_id, client_key.public()].into_iter().collect(), + Err(error) => { + warn!("blob gate: cannot load the client key for local reads: {error}"); + [node_id].into_iter().collect() + } + }; let blobs = match &blob_gate { Some(gate) => BlobsProtocol::new( &store_handle, @@ -998,6 +1036,7 @@ pub async fn cmd_serve(opts: ServeOptions) -> Result<()> { Arc::clone(gate), crate::blob_gate::BlobPolicy::default(), access.clone(), + local_readers, )), ), None => BlobsProtocol::new( diff --git a/pkgs/id/tests/blob_gate.rs b/pkgs/id/tests/blob_gate.rs index 4c47a82ef5..b4cb19c2ae 100644 --- a/pkgs/id/tests/blob_gate.rs +++ b/pkgs/id/tests/blob_gate.rs @@ -111,7 +111,37 @@ where .await .unwrap(); let addr = endpoint.addr(); - let events = blob_events(access, policy, AccessPolicy::restricted([])); + let events = blob_events( + access, + policy, + AccessPolicy::restricted([]), + std::collections::BTreeSet::new(), + ); + let router = Router::builder(endpoint) + .accept(iroh_blobs::ALPN, BlobsProtocol::new(store, Some(events))) + .spawn(); + (router, addr) +} + +/// A provider whose gate also trusts `local` as local readers (the operator's +/// own keys), as `id serve` wires it. +async fn provider_with_local( + store: &Store, + access: Arc, + policy: BlobPolicy, + local: std::collections::BTreeSet, +) -> (Router, EndpointAddr) +where + A: WorldAccess + Send + Sync + 'static, +{ + let endpoint = Endpoint::builder(presets::Minimal) + .relay_mode(RelayMode::Disabled) + .secret_key(SecretKey::from_bytes(&[200; 32])) + .bind() + .await + .unwrap(); + let addr = endpoint.addr(); + let events = blob_events(access, policy, AccessPolicy::restricted([]), local); let router = Router::builder(endpoint) .accept(iroh_blobs::ALPN, BlobsProtocol::new(store, Some(events))) .spawn(); @@ -189,6 +219,38 @@ async fn a_non_member_is_refused_fetch_and_observe() { router.shutdown().await.unwrap(); } +#[tokio::test] +async fn a_local_reader_fetches_an_unreferenced_blob_but_a_stranger_cannot() { + let server = server_store(); + let (docs, _tag) = put(&server, DOCS_BODY).await; + let local = peer(7).await; + let stranger = peer(8).await; + // No world references the blob and nobody is a member of anything: this is + // a locally published blob, readable only through local trust (#7181 P1). + let graph = Graph { + members: vec![], + refs: vec![], + }; + let (router, addr) = provider_with_local( + &server, + Arc::new(graph), + BlobPolicy::default(), + std::collections::BTreeSet::from([local.id]), + ) + .await; + + let got = fetch(&local, &addr, docs) + .await + .expect("a local reader may fetch its own store's blobs"); + assert_eq!(got, DOCS_BODY); + assert_eq!( + fetch_refusal_code(&stranger, &addr, docs).await, + Some(DENIED) + ); + + router.shutdown().await.unwrap(); +} + #[tokio::test] async fn a_member_of_the_referencing_world_fetches_the_bytes() { let server = server_store(); diff --git a/pkgs/id/tests/content_removal.rs b/pkgs/id/tests/content_removal.rs index a8da96065f..858e5b9632 100644 --- a/pkgs/id/tests/content_removal.rs +++ b/pkgs/id/tests/content_removal.rs @@ -221,6 +221,7 @@ async fn provider(store: &Store, graph: Graph) -> (Router, EndpointAddr) { Arc::new(graph), BlobPolicy::default(), AccessPolicy::restricted([]), + std::collections::BTreeSet::new(), ); let router = Router::builder(endpoint) .accept(iroh_blobs::ALPN, BlobsProtocol::new(store, Some(events))) diff --git a/pkgs/id/tests/documents.rs b/pkgs/id/tests/documents.rs index 6a6188a09a..5050f86cb5 100644 --- a/pkgs/id/tests/documents.rs +++ b/pkgs/id/tests/documents.rs @@ -188,6 +188,7 @@ async fn provider(store: &Store, graph: Graph) -> (Router, EndpointAddr) { Arc::new(graph), BlobPolicy::default(), AccessPolicy::restricted([]), + std::collections::BTreeSet::new(), ); let router = Router::builder(endpoint) .accept(iroh_blobs::ALPN, BlobsProtocol::new(store, Some(events))) From 1ced341eab98f6b4cf3064f3a3a931d8f1dadc67 Mon Sep 17 00:00:00 2001 From: repo-worker-tmp-code-b Date: Fri, 13 Nov 2026 22:43:10 -0600 Subject: [PATCH 6/8] Port the blob gate wiring onto the post-crate-split tree (#173) The five shepherd commits were authored against the pre-split pkgs/id layout. This commit relocates their changes onto current main: - id-groups::blob_gate: decide_with_local, build_reference_index, hashseq_children; blob_events/blob_events_with_blocks take the local_readers set and compose local trust ahead of membership. - id-worlds::blob_gate: FoldedWorlds gains the group-projection membership mode (world_key, fold_group_events, group_projection_member) and RefreshingWorlds. - id-cli serve: build_blob_gate + gated BlobsProtocol wiring and the refresh task, at the post-split paths; LocalNode::set_blob_gate. - id-events LocalEvents::document_references wrapper. - Facade re-exports the new names at the historical id::blob_gate paths; the resurrected pre-split serve.rs/local_events.rs are removed again. --- pkgs/id/crates/id-cli/src/commands/serve.rs | 216 +- pkgs/id/crates/id-cli/src/local.rs | 28 +- pkgs/id/crates/id-events/src/local_events.rs | 14 +- pkgs/id/crates/id-groups/src/blob_gate.rs | 189 +- pkgs/id/crates/id-worlds/src/blob_gate.rs | 297 ++- pkgs/id/src/blob_gate.rs | 1009 +------- pkgs/id/src/commands/serve.rs | 2211 ------------------ pkgs/id/src/local_events.rs | 824 ------- 8 files changed, 736 insertions(+), 4052 deletions(-) delete mode 100644 pkgs/id/src/commands/serve.rs delete mode 100644 pkgs/id/src/local_events.rs diff --git a/pkgs/id/crates/id-cli/src/commands/serve.rs b/pkgs/id/crates/id-cli/src/commands/serve.rs index dfdd33c4cd..9cd65cc5d9 100644 --- a/pkgs/id/crates/id-cli/src/commands/serve.rs +++ b/pkgs/id/crates/id-cli/src/commands/serve.rs @@ -1272,6 +1272,115 @@ fn world_protocol_for( } } +/// The largest blob the gate's HashSeq expansion will read into memory: a +/// `HashSeq` of this size names 32768 children, far beyond any collection +/// this node serves; a larger blob is treated as plain content, never a +/// collection, so building the reference index stays size-bounded. +#[cfg(feature = "web")] +const MAX_HASHSEQ_BYTES: u64 = 1 << 20; + +/// Builds the blob gate's folded worlds from the two sources serve has: the group +/// log at `groups_log` for membership, and the event store's document references +/// for which blobs each world names (#173). +/// +/// A referenced blob that parses as a `HashSeq` contributes its children to the +/// same world, but only when every child is present in the store — arbitrary +/// content whose length is a multiple of 32 bytes would otherwise spray +/// references onto hashes nobody stored. Any source that fails to read folds to +/// empty for that source: the gate fails closed, and the next refresh retries. +#[cfg(feature = "web")] +async fn build_blob_gate( + events: &Arc>, + store: &iroh_blobs::api::Store, + groups_log: &std::path::Path, +) -> id_worlds::blob_gate::FoldedWorlds { + let group_projection = match GroupLog::open(groups_log) { + Ok(log) => match id_worlds::blob_gate::fold_group_events(log.events()) { + Ok(projection) => Some(projection), + Err(error) => { + warn!("blob gate: group log does not fold: {error}"); + None + } + }, + Err(error) => { + warn!("blob gate: cannot open group log: {error}"); + None + } + }; + let references = { + let events = events.lock().await; + match events.document_references() { + Ok(references) => references, + Err(error) => { + warn!("blob gate: cannot read document references: {error}"); + Vec::new() + } + } + }; + // Expand HashSeq collections whose children are all in the store. The + // expansion is bounded (#7181 review): only a group-referenced blob can + // contribute children to the index — an ungrouped reference is discarded + // below, so reading it here would be pure waste — and a blob is read into + // memory only when its stored size, asked from the store status rather + // than the content, is a positive multiple of 32 no larger than + // MAX_HASHSEQ_BYTES. A HashSeq is a list of 32-byte hashes; anything else + // cannot be one, and an oversized one is not worth a startup-time read + // proportional to its full contents. + let mut children: std::collections::HashMap> = + std::collections::HashMap::new(); + let mut seen: std::collections::BTreeSet = std::collections::BTreeSet::new(); + let mut frontier: Vec = references + .iter() + .filter(|(_, group)| group.is_some()) + .map(|(hash, _)| *hash) + .collect(); + while let Some(hash) = frontier.pop() { + if !seen.insert(hash) { + continue; + } + let Ok(iroh_blobs::api::blobs::BlobStatus::Complete { size }) = store.status(hash).await + else { + continue; + }; + if size == 0 || size > MAX_HASHSEQ_BYTES || !size.is_multiple_of(32) { + continue; + } + let Ok(bytes) = store.get_bytes(hash).await else { + continue; + }; + let kids = id_groups::blob_gate::hashseq_children(&bytes); + if kids.is_empty() { + continue; + } + let mut all_present = true; + for kid in &kids { + match store.has(*kid).await { + Ok(true) => {} + _ => { + all_present = false; + break; + } + } + } + if all_present { + frontier.extend(kids.iter().copied()); + children.insert(hash, kids); + } + } + let named = references + .into_iter() + .filter_map(|(hash, group)| group.map(|group| (hash, id_worlds::blob_gate::world_key(&group)))); + let index = id_groups::blob_gate::build_reference_index(named, |hash| { + children.get(hash).cloned().unwrap_or_default() + }); + match group_projection { + Some(projection) => { + id_worlds::blob_gate::FoldedWorlds::from_group_projection(projection, index) + } + None => id_worlds::blob_gate::FoldedWorlds::new(id_worlds::groups::worlds::Worlds::empty(), index), + } +} + pub async fn cmd_serve(opts: ServeOptions) -> Result<()> { let ServeOptions { ephemeral, @@ -1546,15 +1655,6 @@ pub async fn cmd_serve(opts: ServeOptions) -> Result<()> { Err(e) => warn!("tags: legacy metadata import failed: {e:#}"), } - // Build router — gossip ALPN is always registered (needed by iroh-docs), - // but peer discovery gossip topic only joins when gossip is enabled - // iroh-blobs rejects pushes unless an event handler enables them; this one - // allows them only from nodes the access policy lets write. - let blobs = BlobsProtocol::new( - &store_handle, - Some(id_core::access::blobs_events(access.clone())), - ); - // The node's own event store, shared between the web layer and /id-range-sync/1 // range sync (#792). Serve opens it once, on the same directory the web // state would open (the `events` sibling of the identity database), and @@ -1578,6 +1678,74 @@ pub async fn cmd_serve(opts: ServeOptions) -> Result<()> { None }; + // The blob membership gate (#173). With the event store open, serve builds the + // gate from the group log (membership) and the store's document references + // (which blobs each world names), and a refresh task below keeps it current. + // Without the store there is no document source to index, so blob reads stay + // ungated this run — push-only, as before — and serve says so at startup. + #[cfg(feature = "web")] + let blob_gate: Option> = match &event_events { + Some(events) => { + let folded = build_blob_gate( + events, + &store_handle, + &serve_groups_log_path(groups_log.clone()), + ) + .await; + Some(Arc::new(id_worlds::blob_gate::RefreshingWorlds::new(folded))) + } + None => None, + }; + #[cfg(not(feature = "web"))] + let blob_gate: Option> = None; + if blob_gate.is_none() { + warn!( + "blob gate (#173): inactive — the event store is only opened with the web UI, \ + so blob reads are not membership-checked this run" + ); + } + + // Build router — gossip ALPN is always registered (needed by iroh-docs), + // but peer discovery gossip topic only joins when gossip is enabled + let meta = MetaProtocol::new( + &store_handle, + Some(peer_discovery.clone()), + Arc::clone(&tag_store), + access.clone(), + node_id, + ); + // iroh-blobs rejects pushes unless an event handler enables them; this one + // allows them only from nodes the access policy lets write. With the blob + // gate built, the gate's handler decides pushes the same way and also + // membership-checks fetches and observes (#173). + // The gate's local readers: the node's own key and the data directory's + // client key — the keys the write policy already trusts automatically — + // so the local CLI and REPL keep reading the node's own store with the + // gate on (#173, #7181 review). + let local_readers: std::collections::BTreeSet = + match load_or_create_keypair(crate::CLIENT_KEY_FILE).await { + Ok(client_key) => [node_id, client_key.public()].into_iter().collect(), + Err(error) => { + warn!("blob gate: cannot load the client key for local reads: {error}"); + [node_id].into_iter().collect() + } + }; + let blobs = match &blob_gate { + Some(gate) => BlobsProtocol::new( + &store_handle, + Some(id_groups::blob_gate::blob_events( + Arc::clone(gate), + id_groups::blob_gate::BlobPolicy::default(), + access.clone(), + local_readers, + )), + ), + None => BlobsProtocol::new( + &store_handle, + Some(id_core::access::blobs_events(access.clone())), + ), + }; + // Every world lives in one hub, shared by the Iroh protocol and the web // bridge. The default world opens now so a bad journal fails startup. #[cfg(feature = "world")] @@ -2158,6 +2326,8 @@ pub async fn cmd_serve(opts: ServeOptions) -> Result<()> { for (_, warning) in evaluate_group_warnings(&mut group_watcher, &groups_log, unix_now()) { status!("group warning: {}", warning.message()); } + #[cfg(feature = "web")] + let gate_groups_log = groups_log.clone(); let group_warning_handle = tokio::spawn(async move { let mut interval = tokio::time::interval(GROUP_WARNING_INTERVAL); interval.tick().await; @@ -2167,6 +2337,29 @@ pub async fn cmd_serve(opts: ServeOptions) -> Result<()> { } }); + // Blob gate refresh (#173): on the same cadence as the group warnings, + // re-fold the group log and the document references so a removed member + // loses fetch and a new document becomes fetchable without a restart. + #[cfg(feature = "web")] + let blob_gate_handle = match (&blob_gate, &event_events) { + (Some(gate), Some(events)) => { + let gate = Arc::clone(gate); + let events = Arc::clone(events); + let store = store_handle.clone(); + let groups_log = gate_groups_log; + Some(tokio::spawn(async move { + let mut interval = tokio::time::interval(GROUP_WARNING_INTERVAL); + interval.tick().await; + loop { + interval.tick().await; + let folded = build_blob_gate(&events, &store, &groups_log).await; + gate.refresh(folded); + } + })) + } + _ => None, + }; + tokio::signal::ctrl_c().await?; remove_serve_lock().await?; router.shutdown().await?; @@ -2194,6 +2387,11 @@ pub async fn cmd_serve(opts: ServeOptions) -> Result<()> { if let Some(hub) = &world_hub { hub.shutdown_all().await; } + #[cfg(feature = "web")] + if let Some(gate_task) = blob_gate_handle { + gate_task.abort(); + let _ = gate_task.await; + } group_warning_handle.abort(); let _ = group_warning_handle.await; store.shutdown().await?; diff --git a/pkgs/id/crates/id-cli/src/local.rs b/pkgs/id/crates/id-cli/src/local.rs index 967a9fffd5..c8c1bff712 100644 --- a/pkgs/id/crates/id-cli/src/local.rs +++ b/pkgs/id/crates/id-cli/src/local.rs @@ -30,13 +30,16 @@ use iroh_blobs::{ALPN as BLOBS_ALPN, BlobsProtocol, api::Store}; use iroh_docs::protocol::Docs; use iroh_gossip::net::Gossip; -use crate::access::AccessPolicy; -use crate::blob_gate::{BlobPolicy, RefreshingWorlds}; -use crate::fileops::FileOps; use crate::protocol::{MetaProtocol, MetaRequest, MetaResponse}; -use crate::store::{StoreType, load_or_create_keypair, open_store}; -use crate::tags::TagStore; -use crate::{KEY_FILE, META_ALPN, STORE_PATH, access::blobs_events}; +use id_core::access::AccessPolicy; +use id_groups::blob_gate::BlobPolicy; +use id_worlds::blob_gate::RefreshingWorlds; +use id_core::access::blobs_events; +use id_store::store::{StoreType, load_or_create_keypair, open_store}; +use id_store::tags::TagStore; +use id_sync::fileops::FileOps; + +use crate::{KEY_FILE, META_ALPN, STORE_PATH}; /// A network-less node exposing the blob store and the metadata [`TagStore`]. #[derive(Debug)] @@ -127,6 +130,7 @@ impl LocalNode { Arc::clone(&tags), AccessPolicy::open(), node_id, + None, ); // Nothing is in flight for an in-process node: a missing blob is missing. if let Some(inner) = Arc::get_mut(&mut m) { @@ -153,7 +157,7 @@ impl LocalNode { /// /// `LocalNode` holds no group log or event store of its own, so the embedder — /// which owns the worlds and documents — builds the gate (see - /// [`crate::blob_gate::RefreshingWorlds`]) and keeps it refreshed. Without a + /// [`id_worlds::blob_gate::RefreshingWorlds`]) and keeps it refreshed. Without a /// gate, `serve` keeps its historical behavior: pushes are policy-checked and /// reads are open. pub fn set_blob_gate(&mut self, gate: Arc, policy: BlobPolicy) { @@ -171,8 +175,11 @@ impl LocalNode { } /// File operations (put/rename/copy/delete) over this node's stores. + /// + /// Writes through this handle stamp this node as the file's origin + /// (#4973). pub fn ops(&self) -> FileOps<'_> { - FileOps::new(&self.blobs, &self.tags) + FileOps::new(&self.blobs, &self.tags).with_origin(self.node_id.to_string()) } /// Answer a meta-protocol request in-process, exactly as a server would. @@ -212,13 +219,16 @@ impl LocalNode { Arc::clone(&self.tags), access.clone(), self.node_id, + None, ); // With a gate, blob fetches and observes are membership-checked (#173) and // pushes keep this policy; without one, pushes alone are gated, as before. + // The node's own id is the gate's local reader set: this node reads its + // own store through the same protocol it serves. let blobs = match &self.blob_gate { Some((gate, policy)) => BlobsProtocol::new( &self.blobs, - Some(crate::blob_gate::blob_events( + Some(id_groups::blob_gate::blob_events( Arc::clone(gate), policy.clone(), access, diff --git a/pkgs/id/crates/id-events/src/local_events.rs b/pkgs/id/crates/id-events/src/local_events.rs index 0df28db683..df44c72de3 100644 --- a/pkgs/id/crates/id-events/src/local_events.rs +++ b/pkgs/id/crates/id-events/src/local_events.rs @@ -21,7 +21,7 @@ use std::time::{SystemTime, UNIX_EPOCH}; use anyhow::{Context, Result, bail}; use p2panda_core::{Hash, SigningKey}; -use crate::event_store::{Block, BlockKind, BlockLookup, EventStore, Ingest}; +use crate::event_store::{Block, BlockKind, BlockLookup, EventStore, Ingest, StoreError}; use crate::local_claims::LocalClaims; use id_core::waiting::{AuthorKey, WaitingLimits}; use id_store::chain::{ChainExt, Event, MAX_AFTER, sign}; @@ -230,6 +230,18 @@ impl LocalEvents { /// # Errors /// /// Fails if the store cannot be opened, for example while another process has it open. + /// The blob references in this node's event store, for the blob gate's index + /// (`EventStore::document_references`). + /// + /// # Errors + /// + /// Returns a store error if the read fails. + pub fn document_references( + &self, + ) -> Result)>, StoreError> { + self.store.document_references() + } + pub fn open(dir: &Path, key: SigningKey) -> Result { std::fs::create_dir_all(dir).with_context(|| format!("create {}", dir.display()))?; let store = EventStore::open(dir, WaitingLimits::default(), now_ms())?; diff --git a/pkgs/id/crates/id-groups/src/blob_gate.rs b/pkgs/id/crates/id-groups/src/blob_gate.rs index aa00dac8a3..6763a510e3 100644 --- a/pkgs/id/crates/id-groups/src/blob_gate.rs +++ b/pkgs/id/crates/id-groups/src/blob_gate.rs @@ -15,11 +15,20 @@ //! membership table, never the blob store. //! - **Fails closed.** A request from a connection with no known `EndpointId` is refused, and so //! is one whose verdict cannot be delivered. +//! - **Local reads are the operator's.** The node's own key and its data directory's client +//! key — the two keys `build_access_policy` already trusts automatically for writes — may +//! fetch and observe any blob in the node's own store (see [`decide_with_local`]). The +//! local CLI and REPL connect with the client key, and locally published content +//! (documents with no group, plain uploads) is referenced by no world; without this the +//! gate would lock the operator out of their own store. Local trust extends to no other +//! peer: a remote requester still needs world membership for every hash. //! //! The reference index and the membership query are behind [`WorldAccess`]. The facade's -//! `blob_gate::FoldedWorlds` answers membership from the folded worlds. Its reference index -//! has no producer yet, so -//! [`blob_events`] is not wired into `id serve`. +//! `blob_gate::FoldedWorlds` answers membership from the folded worlds. The index has a +//! producer now: [`build_reference_index`] over the event store's document references, +//! with the worlds crate's `fold_group_events` folding the group log for membership, and +//! `RefreshingWorlds` swapping fresh folds in as they change. `id serve` wires +//! [`blob_events`] with those pieces whenever it has the node's event store open. use std::{ collections::{BTreeSet, HashMap}, @@ -142,6 +151,83 @@ pub fn decide_with_blocks( }) } +/// Whether `requester` may make `request` for `hash`, counting local trust. +/// +/// A requester in `local_readers` — the node's own key and its data directory's client +/// key, the keys the write policy trusts automatically — may fetch or observe any blob +/// in its own store, referenced or not: that is how the local CLI and REPL keep working +/// when the gate is on, including for locally published content no world references. +/// Everyone else is decided by [`decide`], unchanged. +pub fn decide_with_local( + access: &impl WorldAccess, + policy: &BlobPolicy, + local_readers: &BTreeSet, + requester: &EndpointId, + hash: &Hash, + request: Request, +) -> bool { + local_readers.contains(requester) || decide(access, policy, requester, hash, request) +} + +/// The child hashes a blob's bytes name when the blob is a `HashSeq`: the sequence is the +/// raw concatenation of 32-byte hashes, so any other length is not a sequence and names no +/// children. +pub fn hashseq_children(bytes: &[u8]) -> Vec { + if bytes.is_empty() || !bytes.len().is_multiple_of(32) { + return Vec::new(); + } + bytes + .chunks_exact(32) + .map(|chunk| { + let mut raw = [0u8; 32]; + raw.copy_from_slice(chunk); + Hash::from_bytes(raw) + }) + .collect() +} + +/// Builds the reference index the gate decides from: blob hash → the worlds that name it. +/// +/// `references` pairs each referenced blob with the world that names it (a document event's +/// blob and its group, as the worlds crate's `world_key` spells it). A document with no +/// group names no world: the caller leaves it out, and its blob stays unreferenced. +/// +/// `expand` names the children of a blob that is a `HashSeq` collection. Children are +/// attributed to every world that references the collection, transitively: a member of +/// the world may fetch the collection's contents, not just its sequence blob. The caller +/// decides what counts as a collection (serve expands only a blob whose parsed children +/// are all present in its store, so arbitrary 32-byte-multiple content does not spray +/// references onto hashes nobody stored). +pub fn build_reference_index( + references: impl IntoIterator, + expand: impl Fn(&Hash) -> Vec, +) -> HashMap> { + let mut index: HashMap> = HashMap::new(); + for (hash, world) in references { + index.entry(hash).or_default().insert(world); + } + // Attribute HashSeq children to the referencing worlds, transitively. The worklist + // holds (hash, world) pairs not yet expanded for that world, so the loop ends when + // every reachable pair has been expanded once. + let mut worklist: Vec<(Hash, String)> = index + .iter() + .flat_map(|(hash, worlds)| worlds.iter().map(move |world| (*hash, world.clone()))) + .collect(); + let mut expanded: BTreeSet<(Hash, String)> = BTreeSet::new(); + while let Some((hash, world)) = worklist.pop() { + if !expanded.insert((hash, world.clone())) { + continue; + } + for child in expand(&hash) { + let worlds = index.entry(child).or_default(); + if worlds.insert(world.clone()) { + worklist.push((child, world.clone())); + } + } + } + index +} + /// The verdict for a request from `peer`: allowed only when the peer is known and `allow` /// says so. An unknown peer is refused. fn admit( @@ -156,9 +242,10 @@ fn admit( /// Build the [`EventSender`] that a provider passes to `BlobsProtocol::new`. /// -/// Fetch, `get_many` and observe are decided by [`decide`] over `access`. Pushes are decided by -/// `writes`, as in [`id_core::access::blobs_events`]. Every request is intercepted, so no store -/// read happens before the verdict. +/// Fetch, `get_many` and observe are decided by [`decide_with_local`] over `access` and +/// `local_readers`. Pushes are decided by `writes`, as in +/// [`id_core::access::blobs_events`]. Every request is intercepted, so no store read +/// happens before the verdict. /// /// A background task is spawned on the current Tokio runtime and ends when the sender is /// dropped. @@ -166,8 +253,9 @@ pub fn blob_events( access: Arc, policy: BlobPolicy, writes: AccessPolicy, + local_readers: BTreeSet, ) -> EventSender { - blob_events_with_blocks(access, policy, writes, None) + blob_events_with_blocks(access, policy, writes, None, local_readers) } /// [`blob_events`], with the operator block list composed into every @@ -181,6 +269,7 @@ pub fn blob_events_with_blocks( policy: BlobPolicy, writes: AccessPolicy, blocks: Option>, + local_readers: BTreeSet, ) -> EventSender { let (tx, mut rx) = tokio::sync::mpsc::channel::(64); let mask = EventMask { @@ -205,7 +294,8 @@ pub fn blob_events_with_blocks( } ProviderMessage::GetRequestReceived(m) => { let verdict = admit(peers.get(&m.connection_id), |id| { - decide_with_blocks( + local_readers.contains(id) + || decide_with_blocks( &*access, &policy, blocks.as_deref(), @@ -218,8 +308,9 @@ pub fn blob_events_with_blocks( } ProviderMessage::GetManyRequestReceived(m) => { let verdict = admit(peers.get(&m.connection_id), |id| { - m.request.hashes.iter().all(|hash| { - decide_with_blocks( + local_readers.contains(id) + || m.request.hashes.iter().all(|hash| { + decide_with_blocks( &*access, &policy, blocks.as_deref(), @@ -233,7 +324,8 @@ pub fn blob_events_with_blocks( } ProviderMessage::ObserveRequestReceived(m) => { let verdict = admit(peers.get(&m.connection_id), |id| { - decide_with_blocks( + local_readers.contains(id) + || decide_with_blocks( &*access, &policy, blocks.as_deref(), @@ -338,6 +430,42 @@ mod tests { } } + #[test] + fn a_local_reader_fetches_an_unreferenced_blob_but_a_stranger_cannot() { + // No world references blob(9) and nobody is a member of anything: the + // membership rule alone refuses everyone, which is the lockout the local + // trust exists to prevent for the operator's own keys. + let t = Table::default(); + let p = BlobPolicy::default(); + let local = BTreeSet::from([id(7)]); + assert!(decide_with_local( + &t, + &p, + &local, + &id(7), + &blob(9), + Request::Fetch + )); + assert!(!decide_with_local( + &t, + &p, + &local, + &id(8), + &blob(9), + Request::Fetch + )); + // Local trust also covers observe of the operator's own store, even + // when the server policy leaves observe off for worlds. + assert!(decide_with_local( + &t, + &p, + &local, + &id(7), + &blob(9), + Request::Observe + )); + } + #[test] fn a_non_member_is_refused_fetch_and_observe() { let t = one_world(id(1), blob(9)); @@ -500,3 +628,42 @@ mod tests { } } } + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +mod producer_tests { + use std::collections::HashMap; + + use super::*; + + fn blob(n: u8) -> Hash { + Hash::from_bytes([n; 32]) + } + + #[test] + fn reference_index_attributes_hashseq_children_transitively() { + // world "w" references the sequence blob 1; 1 names 2 and 3; 2 names 4. + let children: HashMap> = + HashMap::from([(blob(1), vec![blob(2), blob(3)]), (blob(2), vec![blob(4)])]); + let index = build_reference_index([(blob(1), "w".to_owned())], |hash| { + children.get(hash).cloned().unwrap_or_default() + }); + for hash in [blob(1), blob(2), blob(3), blob(4)] { + assert_eq!( + index.get(&hash).map(|w| w.contains("w")), + Some(true), + "{hash} must be referenced by w" + ); + } + assert!(!index.contains_key(&blob(9)), "unrelated hash stays out"); + } + + #[test] + fn hashseq_children_parses_concatenated_hashes() { + let mut bytes = blob(5).as_bytes().to_vec(); + bytes.extend_from_slice(blob(6).as_bytes()); + assert_eq!(hashseq_children(&bytes), vec![blob(5), blob(6)]); + assert!(hashseq_children(&bytes[..33]).is_empty(), "ragged length"); + assert!(hashseq_children(&[]).is_empty(), "empty names nothing"); + } +} diff --git a/pkgs/id/crates/id-worlds/src/blob_gate.rs b/pkgs/id/crates/id-worlds/src/blob_gate.rs index 85b2aaa6f8..6733f92cd6 100644 --- a/pkgs/id/crates/id-worlds/src/blob_gate.rs +++ b/pkgs/id/crates/id-worlds/src/blob_gate.rs @@ -12,6 +12,7 @@ //! must not name world types.) use std::collections::{BTreeSet, HashMap}; +use std::sync::RwLock; use iroh_base::EndpointId; use iroh_blobs::Hash; @@ -20,32 +21,64 @@ use id_events::world_access::WorldAccess; use crate::groups::{Role, worlds::Worlds}; -/// [`WorldAccess`] over the folded worlds. +/// [`WorldAccess`] over a full group-log projection or the older per-world folds. /// -/// Membership is the world's own authority, as [`Worlds::holds_here`] gives it: a member of its -/// group, or a grant in its own chains. A crossing from another world does not count. +/// For a full group-log projection, membership is queried by the exact group hash the world +/// names, so another group's membership or grants cannot leak across worlds. A per-world fold +/// uses [`Worlds::holds_here`], which likewise excludes crossings from another world. /// -/// The reference index maps a blob hash to the worlds that name it. Nothing in the store writes -/// it yet. Artifacts carry SHA-256 hashes, not BLAKE3 blob hashes, and only WASM modules are -/// pinned, without a record of their world. So the index is passed in, and a hash it does not -/// hold is unreferenced, which refuses it to every requester. +/// The reference index maps a blob hash to the worlds that name it. It is built by +/// `id_groups::blob_gate::build_reference_index` from the event store's document +/// references; artifacts are not a source, because they carry SHA-256 hashes, not BLAKE3 +/// blob hashes, and only WASM modules are pinned, without a record of their world. A hash +/// the index does not hold is unreferenced, which refuses it to every requester. #[derive(Debug)] pub struct FoldedWorlds { - worlds: Worlds, + membership: FoldedMembership, references: HashMap>, } +#[derive(Debug)] +enum FoldedMembership { + PerWorld(Worlds), + GroupProjection(crate::groups::Projection), +} + impl FoldedWorlds { /// Pairs the folded worlds with a reference index. pub const fn new(worlds: Worlds, references: HashMap>) -> Self { - Self { worlds, references } + Self { + membership: FoldedMembership::PerWorld(worlds), + references, + } + } + + /// Pairs a full group-log projection with a reference index. + /// + /// Unlike `new`, the projection spans all groups in the group log and therefore preserves + /// its complete causal graph. Each membership request is limited to the group named by its + /// world key. + pub const fn from_group_projection( + projection: crate::groups::Projection, + references: HashMap>, + ) -> Self { + Self { + membership: FoldedMembership::GroupProjection(projection), + references, + } } } impl WorldAccess for FoldedWorlds { fn is_current_member(&self, world: &str, requester: &EndpointId) -> bool { - self.worlds - .holds_here(world, *requester.as_bytes(), Role::Pull) + match &self.membership { + FoldedMembership::PerWorld(worlds) => { + worlds.holds_here(world, *requester.as_bytes(), Role::Pull) + } + FoldedMembership::GroupProjection(projection) => { + group_projection_member(projection, world, requester) + } + } } fn worlds_referencing(&self, hash: &Hash) -> Vec { @@ -56,6 +89,104 @@ impl WorldAccess for FoldedWorlds { } } +/// The world key a group is indexed under: the hex of its create event's hash, which is the +/// group hash every later event of the group names. A document event's `group` extension is +/// the same hash, so document references and membership folds agree on the key. +pub fn world_key(group: &p2panda_core::Hash) -> String { + group.to_string() +} + +/// Folds group-log events into one projection the gate reads membership from. +/// +/// The whole log is folded once, as one causal graph: `GroupLog::record` names the log's +/// global heads as `after`, so an event's dependencies routinely live in another group, and +/// partitioning the log by world hands `fold` dependencies it cannot resolve. Keeping the +/// complete graph also preserves cross-group vetoes and removals, which per-world partitions +/// would silently drop. +/// +/// The one projection holds every group. [`group_projection_member`] reads membership for the +/// group the requested world names, so another group's membership cannot leak authority. +/// +/// # Errors +/// +/// Any error [`crate::groups::fold`] gives for the log. +pub fn fold_group_events( + events: &[crate::groups::Event], +) -> Result { + crate::groups::fold(events) +} + +/// Whether `requester` is a current `Pull` member of the group `world` names in the full log. +/// +/// A world key is the hex of the group's create event hash (see [`world_key`]), so the global +/// projection can be asked about exactly that group. +#[must_use] +fn group_projection_member( + projection: &crate::groups::Projection, + world: &str, + requester: &EndpointId, +) -> bool { + let Ok(group_id) = id_groups::groups::log::hash_from_hex(world) else { + return false; + }; + let actor = *requester.as_bytes(); + projection.group(&group_id).is_some_and(|group| { + group.is_active() + && group + .members + .get(&actor) + .is_some_and(|role| *role >= Role::Pull) + }) || projection.grants_in_force().any(|grant| { + grant.group == group_id + && grant.target.is_none() + && grant.to == actor + && grant.scope >= Role::Pull + }) +} + +/// [`WorldAccess`] whose folded worlds a producer can replace as they change. +/// +/// `blob_events` holds one `Arc` for the life of the server; the fold behind it must not +/// be the snapshot from startup, or a removed member would keep fetching and a new +/// document would stay unreferenced until a restart. The producer re-folds and calls +/// [`RefreshingWorlds::refresh`]; each decision then reads the latest fold. A poisoned +/// lock fails closed, like every other gate refusal. +#[derive(Debug)] +pub struct RefreshingWorlds { + inner: RwLock, +} + +impl RefreshingWorlds { + /// Starts from an initial fold. + pub const fn new(initial: FoldedWorlds) -> Self { + Self { + inner: RwLock::new(initial), + } + } + + /// Replaces the folded worlds every later decision reads. + pub fn refresh(&self, next: FoldedWorlds) { + if let Ok(mut current) = self.inner.write() { + *current = next; + } + } +} + +impl WorldAccess for RefreshingWorlds { + fn is_current_member(&self, world: &str, requester: &EndpointId) -> bool { + self.inner + .read() + .is_ok_and(|folded| folded.is_current_member(world, requester)) + } + + fn worlds_referencing(&self, hash: &Hash) -> Vec { + self.inner + .read() + .map(|folded| folded.worlds_referencing(hash)) + .unwrap_or_default() + } +} + #[cfg(test)] #[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] mod tests { @@ -159,6 +290,150 @@ mod tests { assert!(!decide(&g, &p, &id(2), &blob(5), Request::Observe)); } + /// `GroupLog::record` names the log's global heads as `after`, so a group created after + /// another names the first group's events. Fold the complete graph and still keep each + /// group's membership isolated. + #[test] + fn fold_group_events_tolerates_cross_world_causality() { + fn create() -> Body { + Body::Create(Create { + template: Template::Custom, + policy: Policy::default(), + members: Vec::new(), + admins_on_create: false, + }) + } + let founder = *id(1).as_bytes(); + let member_a = *id(2).as_bytes(); + let member_b = *id(3).as_bytes(); + let create_a = p2panda_core::Hash::digest(b"create-a"); + let add_a = p2panda_core::Hash::digest(b"add-a"); + let create_b = p2panda_core::Hash::digest(b"create-b"); + let add_b = p2panda_core::Hash::digest(b"add-b"); + let events = vec![ + Event { + id: create_a, + author: founder, + after: Vec::new(), + group: None, + body: create(), + }, + Event { + id: add_a, + author: founder, + after: vec![create_a], + group: Some(create_a), + body: Body::Member(MemberOp::Add { + member: member_a, + role: Role::Read, + }), + }, + Event { + id: create_b, + author: founder, + after: vec![create_a, add_a], + group: None, + body: create(), + }, + Event { + id: add_b, + author: founder, + after: vec![create_b, add_a], + group: Some(create_b), + body: Body::Member(MemberOp::Add { + member: member_b, + role: Role::Read, + }), + }, + ]; + let projection = fold_group_events(&events).expect("cross-world causality must fold"); + let (key_a, key_b) = (world_key(&create_a), world_key(&create_b)); + let folded = FoldedWorlds::from_group_projection(projection, HashMap::new()); + assert!(folded.is_current_member(&key_a, &id(2))); + assert!(!folded.is_current_member(&key_a, &id(3))); + assert!(folded.is_current_member(&key_b, &id(3))); + assert!(!folded.is_current_member(&key_b, &id(2))); + } + + /// A group log for one world: founder creates it, adds `member`, then removes them + /// when `removed`. Returns the events and the world key the fold gives them. + fn group_events(member: EndpointId, removed: bool) -> (Vec, String) { + let founder = *id(1).as_bytes(); + let member_key = *member.as_bytes(); + let create = p2panda_core::Hash::digest(b"gate-create"); + let add = p2panda_core::Hash::digest(b"gate-add"); + let mut events = vec![ + Event { + id: create, + author: founder, + after: Vec::new(), + group: None, + body: Body::Create(Create { + template: Template::Custom, + policy: Policy::default(), + members: Vec::new(), + admins_on_create: false, + }), + }, + Event { + id: add, + author: founder, + after: vec![create], + group: Some(create), + body: Body::Member(MemberOp::Add { + member: member_key, + role: Role::Read, + }), + }, + ]; + if removed { + events.push(Event { + id: p2panda_core::Hash::digest(b"gate-remove"), + author: founder, + after: vec![add], + group: Some(create), + body: Body::Member(MemberOp::Remove { + member: member_key, + mode: crate::groups::RemoveMode::Revoke, + }), + }); + } + (events, world_key(&create)) + } + + #[test] + fn folded_group_log_gates_fetch_and_refresh_revokes_it() { + use id_groups::blob_gate::build_reference_index; + let member = id(2); + let (events, world) = group_events(member, false); + let projection = fold_group_events(&events).expect("the log folds"); + let index = build_reference_index([(blob(7), world.clone())], |_| Vec::new()); + let gate = RefreshingWorlds::new(FoldedWorlds::from_group_projection(projection, index)); + let policy = BlobPolicy::default(); + assert!( + decide(&gate, &policy, &member, &blob(7), Request::Fetch), + "a current member fetches a referenced blob" + ); + assert!( + !decide(&gate, &policy, &id(3), &blob(7), Request::Fetch), + "a non-member is refused" + ); + assert!( + !decide(&gate, &policy, &member, &blob(8), Request::Fetch), + "an unreferenced blob is refused even to a member" + ); + + // The member is removed; a refreshed fold must revoke the fetch at once. + let (events, world) = group_events(member, true); + let projection = fold_group_events(&events).expect("the log folds"); + let index = build_reference_index([(blob(7), world)], |_| Vec::new()); + gate.refresh(FoldedWorlds::from_group_projection(projection, index)); + assert!( + !decide(&gate, &policy, &member, &blob(7), Request::Fetch), + "a removed member loses fetch on the next request" + ); + } + #[test] fn observe_over_the_folded_world_follows_the_policy() { let g = gate(folded(id(1), id(2), false), blob(9)); diff --git a/pkgs/id/src/blob_gate.rs b/pkgs/id/src/blob_gate.rs index 28275f06a1..140cf7a660 100644 --- a/pkgs/id/src/blob_gate.rs +++ b/pkgs/id/src/blob_gate.rs @@ -1,982 +1,39 @@ -//! Who may fetch or observe a blob (P3.4, decision 5). +//! Who may fetch or observe a blob (P3.4, decision 5) — facade shim +//! over `id-groups` and `id-worlds`. //! -//! iroh-blobs serves a `get` for any hash to any peer that connects. Under its default -//! observe mode it also answers `observe` with the blob's size and held ranges, for anyone. -//! This module decides each of those requests from the requester's [`EndpointId`] and the hash: +//! Step 4 of the pkgs/id crate split (#4407): the gate itself — +//! [`BlobPolicy`], [`Request`], [`decide`], [`decide_with_blocks`] and +//! the provider wiring in [`blob_events`] — lives in +//! `id_groups::blob_gate`, over the [`WorldAccess`] trait the events +//! layer owns (step 2b). Step 5 (#4408) moved [`FoldedWorlds`], the +//! `WorldAccess` implementation over the folded worlds, into +//! `id_worlds::blob_gate` together with seam 6's bridge file +//! (`groups::worlds`), which it folds through. It cannot live in +//! `id-groups`: that crate is below `id-worlds` and must not name +//! world types. This facade module now holds nothing but the +//! re-exports, so every historical `id::blob_gate` path is unchanged. //! -//! - **Fetch** (`get`, and every hash of a `get_many`) is allowed only to a current member of a -//! world that references the hash. A world references a blob when one of its artifacts or -//! documents names the hash. -//! - **Observe** needs the same membership, and the server policy must serve observe for that -//! world. Observe is off by default. A world can narrow it off for its own blobs, but cannot -//! switch it on. -//! - **Refusals look the same.** A hash that no world references and a hash the requester may -//! not reach get the same verdict. The decision reads only the reference index and the -//! membership table, never the blob store. -//! - **Fails closed.** A request from a connection with no known `EndpointId` is refused, and so -//! is one whose verdict cannot be delivered. -//! - **Local reads are the operator's.** The node's own key and its data directory's client -//! key — the two keys `build_access_policy` already trusts automatically for writes — may -//! fetch and observe any blob in the node's own store (see [`decide_with_local`]). The -//! local CLI and REPL connect with the client key, and locally published content -//! (documents with no group, plain uploads) is referenced by no world; without this the -//! gate would lock the operator out of their own store. Local trust extends to no other -//! peer: a remote requester still needs world membership for every hash. -//! -//! The reference index and the membership query are behind [`WorldAccess`]. [`FoldedWorlds`] -//! answers membership from the folded worlds. The index has a producer now: -//! [`build_reference_index`] over the event store's document references (see -//! `EventStore::document_references`), with [`fold_group_events`] folding the group log for -//! membership, and [`RefreshingWorlds`] swapping fresh folds in as they change. `id serve` -//! wires [`blob_events`] with those pieces whenever it has the node's event store open. - -use std::{ - collections::{BTreeSet, HashMap}, - sync::{Arc, RwLock}, +//! The gate's own documentation, in `id_groups::blob_gate`: a fetch +//! is allowed only to a current member of a world that references +//! the hash; observe needs the same membership and a server policy +//! that serves observe for that world; refusals look the same +//! whether the hash is unreferenced or the requester may not reach +//! it; and an unknown requester is refused. + +pub use id_groups::blob_gate::{ + BlobPolicy, Request, blob_events, blob_events_with_blocks, build_reference_index, decide, + decide_with_blocks, decide_with_local, hashseq_children, }; -use iroh_base::EndpointId; -use iroh_blobs::{ - Hash, - provider::events::{ - AbortReason, ConnectMode, EventMask, EventSender, ObserveMode, ProviderMessage, RequestMode, - }, -}; - -use crate::access::AccessPolicy; -use crate::groups::{Role, worlds::Worlds}; - -/// The two questions the gate asks of the world graph. -pub trait WorldAccess: Send + Sync + 'static { - /// Whether `requester` is a current member of `world`. - fn is_current_member(&self, world: &str, requester: &EndpointId) -> bool; - - /// The worlds whose content names `hash`. Empty for a hash that no world names, which - /// includes every unknown hash. - fn worlds_referencing(&self, hash: &Hash) -> Vec; -} - -/// The server's blob policy. -/// -/// `observe` is the server default and is off unless enabled. A world in `narrowed` refuses -/// observe for its blobs even when the server allows it. Fetch has no switch: every fetch is -/// decided by membership. -#[derive(Debug, Clone, Default, PartialEq, Eq)] -pub struct BlobPolicy { - observe: bool, - narrowed: BTreeSet, -} - -impl BlobPolicy { - /// Serve observe for every world that does not narrow it. - #[must_use] - pub const fn with_observe(mut self) -> Self { - self.observe = true; - self - } - - /// Refuse observe for the blobs `world` references, whatever the server default. - #[must_use] - pub fn narrow_observe(mut self, world: impl Into) -> Self { - self.narrowed.insert(world.into()); - self - } - - /// Whether observe may be served for the blobs `world` references. - pub fn observe_allowed(&self, world: &str) -> bool { - self.observe && !self.narrowed.contains(world) - } -} - -/// The two request kinds the gate decides. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Request { - /// A `get` or one hash of a `get_many`. - Fetch, - /// An `observe`. - Observe, -} - -/// Whether `requester` may make `request` for `hash`. -/// -/// Allowed when some world that references `hash` has the requester as a current member and, -/// for an observe, the policy serves observe for that world. -pub fn decide( - access: &impl WorldAccess, - policy: &BlobPolicy, - requester: &EndpointId, - hash: &Hash, - request: Request, -) -> bool { - access.worlds_referencing(hash).iter().any(|world| { - access.is_current_member(world, requester) - && match request { - Request::Fetch => true, - Request::Observe => policy.observe_allowed(world), - } - }) -} - -/// Whether `requester` may make `request` for `hash`, counting local trust. -/// -/// A requester in `local_readers` — the node's own key and its data directory's client -/// key, the keys the write policy trusts automatically — may fetch or observe any blob -/// in its own store, referenced or not: that is how the local CLI and REPL keep working -/// when the gate is on, including for locally published content no world references. -/// Everyone else is decided by [`decide`], unchanged. -pub fn decide_with_local( - access: &impl WorldAccess, - policy: &BlobPolicy, - local_readers: &BTreeSet, - requester: &EndpointId, - hash: &Hash, - request: Request, -) -> bool { - local_readers.contains(requester) || decide(access, policy, requester, hash, request) -} - -/// [`WorldAccess`] over a full group-log projection or the older per-world folds. -/// -/// For a full group-log projection, membership is queried by the exact group hash the world -/// names, so another group's membership or grants cannot leak across worlds. A per-world fold -/// uses [`Worlds::holds_here`], which likewise excludes crossings from another world. -/// -/// The reference index maps a blob hash to the worlds that name it. It is built by -/// [`build_reference_index`] from the event store's document references; artifacts are not a -/// source, because they carry SHA-256 hashes, not BLAKE3 blob hashes, and only WASM modules -/// are pinned, without a record of their world. A hash the index does not hold is -/// unreferenced, which refuses it to every requester. -#[derive(Debug)] -pub struct FoldedWorlds { - membership: FoldedMembership, - references: HashMap>, -} - -#[derive(Debug)] -enum FoldedMembership { - PerWorld(Worlds), - GroupProjection(crate::groups::Projection), -} - -impl FoldedWorlds { - /// Pairs the folded worlds with a reference index. - pub const fn new(worlds: Worlds, references: HashMap>) -> Self { - Self { - membership: FoldedMembership::PerWorld(worlds), - references, - } - } - - /// Pairs a full group-log projection with a reference index. - /// - /// Unlike `new`, the projection spans all groups in the group log and therefore preserves - /// its complete causal graph. Each membership request is limited to the group named by its - /// world key. - pub const fn from_group_projection( - projection: crate::groups::Projection, - references: HashMap>, - ) -> Self { - Self { - membership: FoldedMembership::GroupProjection(projection), - references, - } - } -} - -impl WorldAccess for FoldedWorlds { - fn is_current_member(&self, world: &str, requester: &EndpointId) -> bool { - match &self.membership { - FoldedMembership::PerWorld(worlds) => { - worlds.holds_here(world, *requester.as_bytes(), Role::Pull) - } - FoldedMembership::GroupProjection(projection) => { - group_projection_member(projection, world, requester) - } - } - } - - fn worlds_referencing(&self, hash: &Hash) -> Vec { - self.references - .get(hash) - .map(|worlds| worlds.iter().cloned().collect()) - .unwrap_or_default() - } -} - -/// The world key a group is indexed under: the hex of its create event's hash, which is the -/// group hash every later event of the group names. A document event's `group` extension is -/// the same hash, so document references and membership folds agree on the key. -pub fn world_key(group: &p2panda_core::Hash) -> String { - group.to_string() -} - -/// Folds group-log events into one projection the gate reads membership from. -/// -/// The whole log is folded once, as one causal graph: `GroupLog::record` names the log's -/// global heads as `after`, so an event's dependencies routinely live in another group, and -/// partitioning the log by world hands `fold` dependencies it cannot resolve. Keeping the -/// complete graph also preserves cross-group vetoes and removals, which per-world partitions -/// would silently drop. -/// -/// The one projection holds every group. [`group_projection_member`] reads membership for the -/// group the requested world names, so another group's membership cannot leak authority. -/// -/// # Errors -/// -/// Any error [`crate::groups::fold`] gives for the log. -pub fn fold_group_events( - events: &[crate::groups::Event], -) -> Result { - crate::groups::fold(events) -} - -/// Whether `requester` is a current `Pull` member of the group `world` names in the full log. -/// -/// A world key is the hex of the group's create event hash (see [`world_key`]), so the global -/// projection can be asked about exactly that group. -#[must_use] -fn group_projection_member( - projection: &crate::groups::Projection, - world: &str, - requester: &EndpointId, -) -> bool { - let Ok(group_id) = crate::groups::log::hash_from_hex(world) else { - return false; - }; - let actor = *requester.as_bytes(); - projection.group(&group_id).is_some_and(|group| { - group.is_active() - && group - .members - .get(&actor) - .is_some_and(|role| *role >= Role::Pull) - }) || projection.grants_in_force().any(|grant| { - grant.group == group_id - && grant.target.is_none() - && grant.to == actor - && grant.scope >= Role::Pull - }) -} - -/// The child hashes a blob's bytes name when the blob is a `HashSeq`: the sequence is the -/// raw concatenation of 32-byte hashes, so any other length is not a sequence and names no -/// children. -pub fn hashseq_children(bytes: &[u8]) -> Vec { - if bytes.is_empty() || !bytes.len().is_multiple_of(32) { - return Vec::new(); - } - bytes - .chunks_exact(32) - .map(|chunk| { - let mut raw = [0u8; 32]; - raw.copy_from_slice(chunk); - Hash::from_bytes(raw) - }) - .collect() -} - -/// Builds the reference index the gate decides from: blob hash → the worlds that name it. -/// -/// `references` pairs each referenced blob with the world that names it (a document event's -/// blob and its group, as [`world_key`] spells it). A document with no group names no -/// world: the caller leaves it out, and its blob stays unreferenced. -/// -/// `expand` names the children of a blob that is a `HashSeq` collection. Children are -/// attributed to every world that references the collection, transitively: a member of -/// the world may fetch the collection's contents, not just its sequence blob. The caller -/// decides what counts as a collection (serve expands only a blob whose parsed children -/// are all present in its store, so arbitrary 32-byte-multiple content does not spray -/// references onto hashes nobody stored). -pub fn build_reference_index( - references: impl IntoIterator, - expand: impl Fn(&Hash) -> Vec, -) -> HashMap> { - let mut index: HashMap> = HashMap::new(); - for (hash, world) in references { - index.entry(hash).or_default().insert(world); - } - // Attribute HashSeq children to the referencing worlds, transitively. The worklist - // holds (hash, world) pairs not yet expanded for that world, so the loop ends when - // every reachable pair has been expanded once. - let mut worklist: Vec<(Hash, String)> = index - .iter() - .flat_map(|(hash, worlds)| worlds.iter().map(move |world| (*hash, world.clone()))) - .collect(); - let mut expanded: BTreeSet<(Hash, String)> = BTreeSet::new(); - while let Some((hash, world)) = worklist.pop() { - if !expanded.insert((hash, world.clone())) { - continue; - } - for child in expand(&hash) { - let worlds = index.entry(child).or_default(); - if worlds.insert(world.clone()) { - worklist.push((child, world.clone())); - } - } - } - index -} - -/// [`WorldAccess`] whose folded worlds a producer can replace as they change. -/// -/// `blob_events` holds one `Arc` for the life of the server; the fold behind it must not -/// be the snapshot from startup, or a removed member would keep fetching and a new -/// document would stay unreferenced until a restart. The producer re-folds and calls -/// [`RefreshingWorlds::refresh`]; each decision then reads the latest fold. A poisoned -/// lock fails closed, like every other gate refusal. -#[derive(Debug)] -pub struct RefreshingWorlds { - inner: RwLock, -} - -impl RefreshingWorlds { - /// Starts from an initial fold. - pub const fn new(initial: FoldedWorlds) -> Self { - Self { - inner: RwLock::new(initial), - } - } - - /// Replaces the folded worlds every later decision reads. - pub fn refresh(&self, next: FoldedWorlds) { - if let Ok(mut current) = self.inner.write() { - *current = next; - } - } -} - -impl WorldAccess for RefreshingWorlds { - fn is_current_member(&self, world: &str, requester: &EndpointId) -> bool { - self.inner - .read() - .is_ok_and(|folded| folded.is_current_member(world, requester)) - } - - fn worlds_referencing(&self, hash: &Hash) -> Vec { - self.inner - .read() - .map(|folded| folded.worlds_referencing(hash)) - .unwrap_or_default() - } -} - -/// The verdict for a request from `peer`: allowed only when the peer is known and `allow` -/// says so. An unknown peer is refused. -fn admit( - peer: Option<&EndpointId>, - allow: impl FnOnce(&EndpointId) -> bool, -) -> Result<(), AbortReason> { - match peer { - Some(id) if allow(id) => Ok(()), - _ => Err(AbortReason::Permission), - } -} - -/// Build the [`EventSender`] that a provider passes to `BlobsProtocol::new`. -/// -/// Fetch, `get_many` and observe are decided by [`decide_with_local`] over `access` and -/// `local_readers`. Pushes are decided by `writes`, as in -/// [`crate::access::blobs_events`]. Every request is intercepted, so no store read -/// happens before the verdict. -/// -/// A background task is spawned on the current Tokio runtime and ends when the sender is -/// dropped. -pub fn blob_events( - access: Arc, - policy: BlobPolicy, - writes: AccessPolicy, - local_readers: BTreeSet, -) -> EventSender { - let (tx, mut rx) = tokio::sync::mpsc::channel::(64); - let mask = EventMask { - connected: ConnectMode::Notify, - get: RequestMode::Intercept, - get_many: RequestMode::Intercept, - push: RequestMode::Intercept, - observe: ObserveMode::Intercept, - ..EventMask::DEFAULT - }; - tokio::spawn(async move { - let mut peers: HashMap = HashMap::new(); - while let Some(msg) = rx.recv().await { - match msg { - ProviderMessage::ClientConnectedNotify(m) => { - if let Some(id) = m.endpoint_id { - peers.insert(m.connection_id, id); - } - } - ProviderMessage::ConnectionClosed(m) => { - peers.remove(&m.connection_id); - } - ProviderMessage::GetRequestReceived(m) => { - let verdict = admit(peers.get(&m.connection_id), |id| { - decide_with_local( - &*access, - &policy, - &local_readers, - id, - &m.request.hash, - Request::Fetch, - ) - }); - let _ = m.tx.send(verdict).await; - } - ProviderMessage::GetManyRequestReceived(m) => { - let verdict = admit(peers.get(&m.connection_id), |id| { - m.request.hashes.iter().all(|hash| { - decide_with_local( - &*access, - &policy, - &local_readers, - id, - hash, - Request::Fetch, - ) - }) - }); - let _ = m.tx.send(verdict).await; - } - ProviderMessage::ObserveRequestReceived(m) => { - let verdict = admit(peers.get(&m.connection_id), |id| { - decide_with_local( - &*access, - &policy, - &local_readers, - id, - &m.request.hash, - Request::Observe, - ) - }); - let _ = m.tx.send(verdict).await; - } - ProviderMessage::PushRequestReceived(m) => { - let verdict = admit(peers.get(&m.connection_id), |id| writes.can_write(id)); - let _ = m.tx.send(verdict).await; - } - _ => {} - } - } - }); - EventSender::new(tx, mask) -} - -#[cfg(test)] -#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] -mod tests { - use std::collections::BTreeMap; - - use iroh_base::SecretKey; - use proptest::prelude::*; - - use super::*; - use crate::groups::policy::Policy; - use crate::groups::{Body, Create, Event, MemberOp, Template}; - - const WORLDS: [&str; 3] = ["alpha", "beta", "gamma"]; - - fn id(n: u8) -> EndpointId { - SecretKey::from_bytes(&[n; 32]).public() - } - - fn blob(n: u8) -> Hash { - Hash::from_bytes([n; 32]) - } - - /// Membership and references as plain lists, read by both `decide` and [`spec`]. - #[derive(Debug, Default)] - struct Table { - members: Vec<(String, EndpointId)>, - refs: Vec<(Hash, String)>, - } - - impl WorldAccess for Table { - fn is_current_member(&self, world: &str, requester: &EndpointId) -> bool { - self.members - .iter() - .any(|(w, m)| w == world && m == requester) - } - - fn worlds_referencing(&self, hash: &Hash) -> Vec { - self.refs - .iter() - .filter(|(h, _)| h == hash) - .map(|(_, w)| w.clone()) - .collect() - } - } - - /// The rule as a scan of the lists: some world names the hash, the requester is a member - /// of it, and an observe is served only where the policy serves observe. - fn spec(t: &Table, p: &BlobPolicy, r: &EndpointId, h: &Hash, req: Request) -> bool { - t.refs.iter().any(|(rh, w)| { - rh == h - && t.members.iter().any(|(mw, m)| mw == w && m == r) - && (req == Request::Fetch || (p.observe && !p.narrowed.contains(w))) - }) - } - - fn one_world(member: EndpointId, hash: Hash) -> Table { - Table { - members: vec![("docs".to_owned(), member)], - refs: vec![(hash, "docs".to_owned())], - } - } - - #[test] - #[test] - fn a_local_reader_fetches_an_unreferenced_blob_but_a_stranger_cannot() { - // No world references blob(9) and nobody is a member of anything: the - // membership rule alone refuses everyone, which is the lockout the local - // trust exists to prevent for the operator's own keys. - let t = Table::default(); - let p = BlobPolicy::default(); - let local = BTreeSet::from([id(7)]); - assert!(decide_with_local( - &t, - &p, - &local, - &id(7), - &blob(9), - Request::Fetch - )); - assert!(!decide_with_local( - &t, - &p, - &local, - &id(8), - &blob(9), - Request::Fetch - )); - // Local trust also covers observe of the operator's own store, even - // when the server policy leaves observe off for worlds. - assert!(decide_with_local( - &t, - &p, - &local, - &id(7), - &blob(9), - Request::Observe - )); - } - - #[test] - fn a_non_member_is_refused_fetch_and_observe() { - let t = one_world(id(1), blob(9)); - let p = BlobPolicy::default().with_observe(); - assert!(!decide(&t, &p, &id(2), &blob(9), Request::Fetch)); - assert!(!decide(&t, &p, &id(2), &blob(9), Request::Observe)); - } - - #[test] - fn a_member_of_the_referencing_world_fetches() { - let t = one_world(id(1), blob(9)); - assert!(decide( - &t, - &BlobPolicy::default(), - &id(1), - &blob(9), - Request::Fetch - )); - } - - #[test] - fn a_member_of_an_unrelated_world_is_refused() { - let t = Table { - members: vec![("other".to_owned(), id(1))], - refs: vec![(blob(9), "docs".to_owned())], - }; - let p = BlobPolicy::default().with_observe(); - assert!(!decide(&t, &p, &id(1), &blob(9), Request::Fetch)); - assert!(!decide(&t, &p, &id(1), &blob(9), Request::Observe)); - } - - #[test] - fn observe_is_refused_by_default_even_for_a_member() { - let t = one_world(id(1), blob(9)); - assert!(!BlobPolicy::default().observe_allowed("docs")); - assert!(!decide( - &t, - &BlobPolicy::default(), - &id(1), - &blob(9), - Request::Observe - )); - assert!(decide( - &t, - &BlobPolicy::default(), - &id(1), - &blob(9), - Request::Fetch - )); - } - - #[test] - fn observe_is_allowed_for_a_member_when_the_server_enables_it() { - let t = one_world(id(1), blob(9)); - let p = BlobPolicy::default().with_observe(); - assert!(decide(&t, &p, &id(1), &blob(9), Request::Observe)); - } - - #[test] - fn a_world_can_narrow_observe_off_while_the_server_allows_it() { - let t = one_world(id(1), blob(9)); - let p = BlobPolicy::default().with_observe().narrow_observe("docs"); - assert!(!decide(&t, &p, &id(1), &blob(9), Request::Observe)); - assert!(decide(&t, &p, &id(1), &blob(9), Request::Fetch)); - } - - #[test] - fn a_narrowed_world_does_not_hide_observe_from_another_referencing_world() { - let t = Table { - members: vec![("docs".to_owned(), id(1)), ("team".to_owned(), id(1))], - refs: vec![(blob(9), "docs".to_owned()), (blob(9), "team".to_owned())], - }; - let p = BlobPolicy::default().with_observe().narrow_observe("docs"); - assert!(decide(&t, &p, &id(1), &blob(9), Request::Observe)); - } - - #[test] - fn an_unknown_hash_is_refused_like_a_denied_one() { - let t = one_world(id(1), blob(9)); - let p = BlobPolicy::default().with_observe(); - for request in [Request::Fetch, Request::Observe] { - // Unknown: no world names blob(5). Denied: a stranger asks for blob(9). - let unknown = decide(&t, &p, &id(1), &blob(5), request); - let denied = decide(&t, &p, &id(2), &blob(9), request); - assert!(!unknown && !denied, "{request:?}"); - } - } - - /// The world `docs`, founded by `founder`, which adds `member` as a reader and, when - /// `removed`, removes them again. Folded as the store folds a world. - fn folded(founder: EndpointId, member: EndpointId, removed: bool) -> Worlds { - let (founder, member) = (*founder.as_bytes(), *member.as_bytes()); - let create = p2panda_core::Hash::digest(b"create"); - let add = p2panda_core::Hash::digest(b"add"); - let remove = p2panda_core::Hash::digest(b"remove"); - let mut events = vec![ - Event { - id: create, - author: founder, - after: Vec::new(), - group: None, - body: Body::Create(Create { - template: Template::Custom, - policy: Policy::default(), - members: Vec::new(), - admins_on_create: false, - }), - }, - Event { - id: add, - author: founder, - after: vec![create], - group: Some(create), - body: Body::Member(MemberOp::Add { - member, - role: Role::Read, - }), - }, - ]; - if removed { - events.push(Event { - id: remove, - author: founder, - after: vec![add], - group: Some(create), - body: Body::Member(MemberOp::Remove { - member, - successor: None, - }), - }); - } - let worlds = BTreeMap::from([("docs".to_owned(), events)]); - Worlds::fold(&worlds, BTreeMap::new()).unwrap() - } - - /// The folded `docs` world, with `hash` indexed as named by `docs`. - fn gate(worlds: Worlds, hash: Hash) -> FoldedWorlds { - let refs = HashMap::from([(hash, BTreeSet::from(["docs".to_owned()]))]); - FoldedWorlds::new(worlds, refs) - } - - #[test] - fn folded_membership_admits_a_member_and_refuses_a_stranger() { - let g = gate(folded(id(1), id(2), false), blob(9)); - let p = BlobPolicy::default(); - assert!(decide(&g, &p, &id(2), &blob(9), Request::Fetch)); - // The founder is Admin, so is a member too. - assert!(decide(&g, &p, &id(1), &blob(9), Request::Fetch)); - assert!(!decide(&g, &p, &id(3), &blob(9), Request::Fetch)); - } - - #[test] - fn a_removed_member_loses_fetch_on_the_folded_world() { - let g = gate(folded(id(1), id(2), true), blob(9)); - assert!(!decide( - &g, - &BlobPolicy::default(), - &id(2), - &blob(9), - Request::Fetch - )); - } - - /// `GroupLog::record` names the log's global heads as `after`, so a group created after - /// another names the first group's events. Fold the complete graph and still keep each - /// group's membership isolated. - #[test] - fn fold_group_events_tolerates_cross_world_causality() { - fn create() -> Body { - Body::Create(Create { - template: Template::Custom, - policy: Policy::default(), - members: Vec::new(), - admins_on_create: false, - }) - } - let founder = *id(1).as_bytes(); - let member_a = *id(2).as_bytes(); - let member_b = *id(3).as_bytes(); - let create_a = p2panda_core::Hash::digest(b"create-a"); - let add_a = p2panda_core::Hash::digest(b"add-a"); - let create_b = p2panda_core::Hash::digest(b"create-b"); - let add_b = p2panda_core::Hash::digest(b"add-b"); - let events = vec![ - Event { - id: create_a, - author: founder, - after: Vec::new(), - group: None, - body: create(), - }, - Event { - id: add_a, - author: founder, - after: vec![create_a], - group: Some(create_a), - body: Body::Member(MemberOp::Add { - member: member_a, - role: Role::Read, - }), - }, - Event { - id: create_b, - author: founder, - after: vec![create_a, add_a], - group: None, - body: create(), - }, - Event { - id: add_b, - author: founder, - after: vec![create_b, add_a], - group: Some(create_b), - body: Body::Member(MemberOp::Add { - member: member_b, - role: Role::Read, - }), - }, - ]; - let projection = fold_group_events(&events).expect("cross-world causality must fold"); - let (key_a, key_b) = (world_key(&create_a), world_key(&create_b)); - let folded = FoldedWorlds::from_group_projection(projection, HashMap::new()); - assert!(folded.is_current_member(&key_a, &id(2))); - assert!(!folded.is_current_member(&key_a, &id(3))); - assert!(folded.is_current_member(&key_b, &id(3))); - assert!(!folded.is_current_member(&key_b, &id(2))); - } - - #[test] - fn an_unindexed_blob_is_refused_even_to_a_member() { - let g = gate(folded(id(1), id(2), false), blob(9)); - let p = BlobPolicy::default().with_observe(); - assert!(!decide(&g, &p, &id(2), &blob(5), Request::Fetch)); - assert!(!decide(&g, &p, &id(2), &blob(5), Request::Observe)); - } - - #[test] - fn observe_over_the_folded_world_follows_the_policy() { - let g = gate(folded(id(1), id(2), false), blob(9)); - assert!(!decide( - &g, - &BlobPolicy::default(), - &id(2), - &blob(9), - Request::Observe - )); - let p = BlobPolicy::default().with_observe(); - assert!(decide(&g, &p, &id(2), &blob(9), Request::Observe)); - } - - proptest! { - #[test] - fn decide_matches_the_spec_for_every_pair( - members in proptest::collection::vec((0usize..3, 1u8..6), 0..12), - refs in proptest::collection::vec((1u8..6, 0usize..3), 0..12), - observe in any::(), - narrowed in proptest::collection::vec(0usize..3, 0..3), - ) { - let t = Table { - members: members - .iter() - .map(|&(w, k)| (WORLDS[w].to_owned(), id(k))) - .collect(), - refs: refs - .iter() - .map(|&(h, w)| (blob(h), WORLDS[w].to_owned())) - .collect(), - }; - let mut p = BlobPolicy::default(); - if observe { - p = p.with_observe(); - } - for &w in &narrowed { - p = p.narrow_observe(WORLDS[w]); - } - for requester in 1u8..=6 { - for hash in 1u8..=5 { - for request in [Request::Fetch, Request::Observe] { - let got = decide(&t, &p, &id(requester), &blob(hash), request); - let want = spec(&t, &p, &id(requester), &blob(hash), request); - prop_assert_eq!( - got, - want, - "requester {} hash {} {:?}", - requester, - hash, - request - ); - } - } - } - } - } -} - -#[cfg(test)] -#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] -mod producer_tests { - use std::collections::{BTreeMap, HashMap}; - - use iroh_base::SecretKey; - use p2panda_core::Hash as PandaHash; - - use super::*; - use crate::groups::policy::Policy; - use crate::groups::{Body, Create, Event, MemberOp, Template}; - - fn id(n: u8) -> EndpointId { - SecretKey::from_bytes(&[n; 32]).public() - } - - fn blob(n: u8) -> Hash { - Hash::from_bytes([n; 32]) - } - - #[test] - fn reference_index_attributes_hashseq_children_transitively() { - // world "w" references the sequence blob 1; 1 names 2 and 3; 2 names 4. - let children: HashMap> = - HashMap::from([(blob(1), vec![blob(2), blob(3)]), (blob(2), vec![blob(4)])]); - let index = build_reference_index([(blob(1), "w".to_owned())], |hash| { - children.get(hash).cloned().unwrap_or_default() - }); - for hash in [blob(1), blob(2), blob(3), blob(4)] { - assert_eq!( - index.get(&hash).map(|w| w.contains("w")), - Some(true), - "{hash} must be referenced by w" - ); - } - assert!(!index.contains_key(&blob(9)), "unrelated hash stays out"); - } - - #[test] - fn hashseq_children_parses_concatenated_hashes() { - let mut bytes = blob(5).as_bytes().to_vec(); - bytes.extend_from_slice(blob(6).as_bytes()); - assert_eq!(hashseq_children(&bytes), vec![blob(5), blob(6)]); - assert!(hashseq_children(&bytes[..33]).is_empty(), "ragged length"); - assert!(hashseq_children(&[]).is_empty(), "empty names nothing"); - } - - /// A group log for one world: founder creates it, adds `member`, then removes them - /// when `removed`. Returns the events and the world key the fold gives them. - fn group_events(member: EndpointId, removed: bool) -> (Vec, String) { - let founder = *id(1).as_bytes(); - let member_key = *member.as_bytes(); - let create = PandaHash::digest(b"gate-create"); - let add = PandaHash::digest(b"gate-add"); - let mut events = vec![ - Event { - id: create, - author: founder, - after: Vec::new(), - group: None, - body: Body::Create(Create { - template: Template::Custom, - policy: Policy::default(), - members: Vec::new(), - admins_on_create: false, - }), - }, - Event { - id: add, - author: founder, - after: vec![create], - group: Some(create), - body: Body::Member(MemberOp::Add { - member: member_key, - role: crate::groups::Role::Read, - }), - }, - ]; - if removed { - events.push(Event { - id: PandaHash::digest(b"gate-remove"), - author: founder, - after: vec![add], - group: Some(create), - body: Body::Member(MemberOp::Remove { - member: member_key, - successor: None, - }), - }); - } - (events, world_key(&create)) - } +/// The two questions the gate asks of the world graph, re-exported at +/// its historical path (the trait itself is `id_events::world_access`). +pub use id_events::world_access::WorldAccess; - #[test] - fn folded_group_log_gates_fetch_and_refresh_revokes_it() { - let member = id(2); - let (events, world) = group_events(member, false); - let projection = fold_group_events(&events).expect("the log folds"); - let index = build_reference_index([(blob(7), world.clone())], |_| Vec::new()); - let gate = RefreshingWorlds::new(FoldedWorlds::from_group_projection(projection, index)); - let policy = BlobPolicy::default(); - assert!( - decide(&gate, &policy, &member, &blob(7), Request::Fetch), - "a current member fetches a referenced blob" - ); - assert!( - !decide(&gate, &policy, &id(3), &blob(7), Request::Fetch), - "a non-member is refused" - ); - assert!( - !decide(&gate, &policy, &member, &blob(8), Request::Fetch), - "an unreferenced blob is refused even to a member" - ); +/// [`WorldAccess`] over the folded worlds; the implementation lives +/// in `id_worlds::blob_gate`. +pub use id_worlds::blob_gate::FoldedWorlds; - // The member is removed; a refreshed fold must revoke the fetch at once. - let (events, world) = group_events(member, true); - let projection = fold_group_events(&events).expect("the log folds"); - let index = build_reference_index([(blob(7), world)], |_| Vec::new()); - gate.refresh(FoldedWorlds::from_group_projection(projection, index)); - assert!( - !decide(&gate, &policy, &member, &blob(7), Request::Fetch), - "a removed member loses fetch on the next request" - ); - let _ = BTreeMap::::new(); - } -} +/// [`FoldedWorlds`] whose fold a producer can replace as it changes, +/// plus the group-log fold and the world key a group is indexed under; +/// the implementations live in `id_worlds::blob_gate`. +pub use id_worlds::blob_gate::{RefreshingWorlds, fold_group_events, world_key}; diff --git a/pkgs/id/src/commands/serve.rs b/pkgs/id/src/commands/serve.rs deleted file mode 100644 index 880cd78b83..0000000000 --- a/pkgs/id/src/commands/serve.rs +++ /dev/null @@ -1,2211 +0,0 @@ -//! Server command and lock file management. -//! -//! This module implements the `serve` command which starts a persistent -//! server that accepts connections from peers for blob storage and retrieval. -//! -//! # Architecture -//! -//! ```text -//! ┌─────────────────────────────────────────────────────────────┐ -//! │ Serve Process │ -//! ├─────────────────────────────────────────────────────────────┤ -//! │ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │ -//! │ │ Endpoint │ │ Router │ │ Store │ │ -//! │ │ (QUIC) │───►│ │───►│ (blobs/tags)│ │ -//! │ └─────────────┘ └─────────────┘ └─────────────┘ │ -//! │ │ │ │ -//! │ │ ┌──────┴──────┐ │ -//! │ │ │ │ │ -//! │ │ ┌─────▼─────┐ ┌─────▼─────┐ │ -//! │ │ │MetaProtocol│ │BlobsProtocol│ │ -//! │ │ │ /id/meta/1 │ │ /iroh/blobs │ │ -//! │ │ └───────────┘ └───────────┘ │ -//! │ │ │ -//! │ ▼ │ -//! │ Lock File: .id-serve-lock │ -//! │ - Node ID, PID, Socket addresses │ -//! └─────────────────────────────────────────────────────────────┘ -//! ``` -//! -//! # Lock File Protocol -//! -//! The serve process creates a lock file (`.id-serve-lock`) containing: -//! 1. Node ID (line 1) -//! 2. Process ID (line 2) -//! 3. Socket addresses (remaining lines) -//! -//! Other processes (REPL, CLI commands) check this file to determine -//! if a local serve is running and how to connect to it. -//! -//! # Examples -//! -//! ```bash -//! # Start persistent server -//! id serve -//! -//! # Start ephemeral server (in-memory) -//! id serve --ephemeral -//! -//! # Start without relay servers -//! id serve --no-relay -//! ``` - -use std::net::{Ipv4Addr, Ipv6Addr, SocketAddr}; -use std::path::PathBuf; -use std::sync::Arc; - -use anyhow::Result; -use anyhow::ensure; -use distributed_topic_tracker::{AutoDiscoveryGossip, RecordPublisher, TopicId}; -use futures_lite::StreamExt; -use iroh::{endpoint::Endpoint, protocol::Router}; -use iroh_base::EndpointId; -use iroh_blobs::{ALPN as BLOBS_ALPN, BlobsProtocol}; -use iroh_docs::protocol::Docs; -use iroh_gossip::net::Gossip; -use iroh_mdns_address_lookup::MdnsAddressLookup; -use p2panda_core::Hash; -#[cfg(all(feature = "world", feature = "sandbox"))] -use rand::RngExt as _; -use serde::{Deserialize, Serialize}; -use tokio::fs as afs; -use tracing::{debug, info, warn}; - -use crate::discovery::{ - ANNOUNCE_INTERVAL, PeerAnnouncement, PeerDiscovery, STALE_CHECK_INTERVAL, STALE_THRESHOLD, - resolve_config, -}; -use crate::groups::log::{FILE_NAME as GROUPS_FILE_NAME, GroupLog}; -use crate::groups::warnings::{Evaluator, Observation, Warning}; -use crate::groups::{Key as GroupKey, Projection}; -use crate::protocol::{MetaProtocol, MetaRequest, MetaResponse}; -use crate::store::{load_or_create_keypair, open_store}; -use crate::tags::TagStore; -use crate::{KEY_FILE, META_ALPN, SERVE_LOCK, STORE_PATH}; - -/// Print a status line to stdout **without panicking** if stdout is gone. -/// -/// `println!` panics on `EPIPE`. A server must not die because whoever -/// launched it stopped reading its output (`id serve | head -1`, a supervisor -/// that closes the pipe after the first line, or a test harness): the status -/// lines are informational. The lock file, not stdout, is how clients find -/// the server. -macro_rules! status { - ($($arg:tt)*) => {{ - use std::io::Write as _; - let _ = writeln!(std::io::stdout(), $($arg)*); - }}; -} - -/// Like [`status!`], for stderr. -#[cfg(any(feature = "web", feature = "world"))] -macro_rules! status_err { - ($($arg:tt)*) => {{ - use std::io::Write as _; - let _ = writeln!(std::io::stderr(), $($arg)*); - }}; -} - -/// Information about a running serve instance. -/// -/// Retrieved from the lock file by [`get_serve_info`] to enable -/// other processes to connect to the local serve. -/// -/// # Fields -/// -/// - `node_id`: The public identity of the serve node -/// - `addrs`: Local socket addresses where the serve is listening -/// -/// # JSON Lock File Format -/// -/// ```json -/// { -/// "node_id": "abc123...", -/// "pid": 12345, -/// "addrs": ["127.0.0.1:12345", "[::1]:12345"], -/// "web_port": 3001 -/// } -/// ``` -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct ServeInfo { - /// The public node ID derived from the serve's keypair. - pub node_id: String, - /// Process ID of the running serve instance. - pub pid: u32, - /// Socket addresses the serve is bound to (as strings for JSON). - pub addrs: Vec, - /// Port for the web UI, if enabled. - pub web_port: Option, -} - -impl ServeInfo { - /// Parse the `node_id` string back to an [`EndpointId`]. - pub fn endpoint_id(&self) -> Option { - self.node_id.parse().ok() - } - - /// Parse the address strings back to [`SocketAddr`]s. - pub fn socket_addrs(&self) -> Vec { - self.addrs.iter().filter_map(|a| a.parse().ok()).collect() - } -} - -/// Checks if a serve instance is running and returns its connection info. -/// -/// Reads the JSON lock file, verifies the PID is still alive, and returns -/// the serve info needed to connect. Returns `None` if: -/// - Lock file doesn't exist -/// - Lock file is malformed -/// - Referenced process is no longer running (stale lock) -/// -/// # Example -/// -/// ```rust,ignore -/// if let Some(info) = get_serve_info().await { -/// println!("Serve running: {}", info.node_id); -/// // Connect to info.addrs... -/// } else { -/// println!("No serve running"); -/// } -/// ``` -pub async fn get_serve_info() -> Option { - let contents = afs::read_to_string(SERVE_LOCK).await.ok()?; - let info: ServeInfo = serde_json::from_str(&contents).ok()?; - - // Check if process is still alive - if !is_process_alive(info.pid) { - // Stale lock file - remove it - let _ = afs::remove_file(SERVE_LOCK).await; - return None; - } - - Some(info) -} - -/// Checks if a process with the given PID is still running. -/// -/// Uses platform-specific methods: -/// - Unix: `kill(pid, 0)` which checks existence without sending a signal -/// - Other: Always returns `true` (conservative fallback) -/// -/// # Arguments -/// -/// * `pid` - The process ID to check -/// -/// # Returns -/// -/// `true` if the process exists, `false` otherwise. -#[allow(clippy::cast_possible_wrap)] // PID is always positive, wrap is safe for kill() -#[allow(unsafe_code)] // Required for libc::kill -pub fn is_process_alive(pid: u32) -> bool { - #[cfg(unix)] - { - // SAFETY: libc::kill with signal 0 only checks process existence without - // sending any signal. The pid cast from u32 to i32 is safe because valid - // PIDs on Unix are always positive and fit in i32. - // #2384: a failed probe is not proof of death — EPERM means the - // process exists but is owned by another user, so it is alive; - // only ESRCH (no such process) and other errnos mean dead. This - // mirrors mcpx's ProcessAlive (pkgs/mcpx/internal/daemon/paths.go). - let rc = unsafe { libc::kill(pid as i32, 0) }; - rc == 0 || std::io::Error::last_os_error().raw_os_error() == Some(libc::EPERM) - } - #[cfg(not(unix))] - { - // On non-Unix, just assume it's alive if we have a PID - let _ = pid; - true - } -} - -/// Creates the serve lock file with connection information as JSON. -/// -/// Writes the node ID, current process ID, socket addresses, and -/// optional web port to the lock file so other processes can discover -/// and connect. -/// -/// # Arguments -/// -/// * `node_id` - The serve node's public identity -/// * `addrs` - Socket addresses the serve is listening on -/// * `web_port` - Port for the web UI, if enabled -/// -/// # Errors -/// -/// Returns an error if the lock file cannot be written. -pub async fn create_serve_lock( - node_id: &EndpointId, - addrs: &[SocketAddr], - web_port: Option, -) -> Result<()> { - let info = ServeInfo { - node_id: node_id.to_string(), - pid: std::process::id(), - addrs: addrs.iter().map(ToString::to_string).collect(), - web_port, - }; - let contents = serde_json::to_string_pretty(&info)?; - afs::write(SERVE_LOCK, contents).await?; - Ok(()) -} - -/// Removes the serve lock file. -/// -/// Called during graceful shutdown to indicate the serve is no longer running. -/// Errors are silently ignored (file may already be removed). -pub async fn remove_serve_lock() -> Result<()> { - let _ = afs::remove_file(SERVE_LOCK).await; - Ok(()) -} -/// Options for [`cmd_serve`], mirroring the `serve` CLI flags. -#[derive(Debug, Clone)] -pub struct ServeOptions { - /// Use an in-memory store. - pub ephemeral: bool, - /// Group log for the group-warning watcher (the global - /// `--groups-log` option); `None` reads the default - /// `groups.jsonl`, exactly as the group commands resolve it. - pub groups_log: Option, - /// Disable relay servers. - pub no_relay: bool, - /// Disable gossip peer discovery. - pub no_gossip: bool, - /// Start the web interface. - pub web: bool, - /// Web interface port (0 = random). - pub port: u16, - /// Extra bootstrap node IDs. - pub bootstrap: Vec, - /// Gossip topic override. - pub topic: Option, - /// Gossip topic secret override. - pub topic_secret: Option, - /// Skip default bootstrap nodes. - pub no_default_bootstrap: bool, - /// Skip default topic and secret. - pub no_default_topic: bool, - /// Use only `defaults.conf` values. - pub replace_defaults: bool, - /// Disable mDNS. - pub no_mdns: bool, - /// Enable mainline DHT address lookup and publishing. - pub dht: bool, - /// Iroh QUIC port (0 = random). - pub iroh_port: u16, - /// Address the web interface binds to. - pub bind: std::net::IpAddr, - /// Token required by the web interface. - pub web_token: Option, - /// Mark the directory explorer's session cookies `Secure` (HTTPS in front). - pub web_cookie_secure: bool, - /// Host a multiplayer world (durable unless `ephemeral`). - pub world: bool, - /// Admin secret required to mint world guest capabilities. - pub world_admin_token: Option, - /// Optional Wasm world program, compiled for the sandbox's Roc platform ABI. - pub world_module: Option, - /// Directory that receives confirmation mail, one file per message. - pub world_mail_outbox: Option, - /// Program run once per confirmation mail. - pub world_mail_command: Option, - /// Loopback SMTP relay that receives confirmation mail. - pub world_mail_smtp: Option, - /// Sender address for mail sent through `world_mail_smtp`. - pub world_mail_from: Option, - /// Name of the world this server offers; its files live under - /// `.id-worlds//`. - pub world_name: String, - /// Trim the journal behind a program snapshot every this many events - /// (`0` never trims). - pub world_checkpoint_every: u64, - /// Most worlds open at once. - pub world_max_open: usize, - /// Most world sessions at once, across all worlds. - pub world_max_sessions: usize, - /// Close durable worlds idle for this many seconds (`0` never). - pub world_idle_secs: u64, - /// Refuse signed world requests for this many seconds after startup (`0` none). - pub world_boot_window_secs: u64, - /// Capabilities the default world's program may use. - pub world_caps: Vec, - /// `deny` or `grant-on-use`. - pub world_cap_policy: String, - /// Capabilities the server allows any world to use (`None`: the whole catalog). - pub world_allowed_caps: Option>, - /// Roc binary for on-the-fly compilation. - pub roc_bin: Option, - /// Platform directory for on-the-fly compilation. - pub roc_platform: Option, - /// Serve the world over SSH on this port. - pub world_ssh_port: Option, - /// Accept native (ELF) module installs. - pub world_native: bool, - /// Accept program changes only through server-side Roc compilation. - pub world_source_only: bool, - /// Execution bounds for world programs. - pub world_runtime: crate::cli::WorldRuntimeArgs, - /// Nodes allowed to modify the store. - pub allow_node: Vec, - /// Let every peer modify the store. - pub open_writes: bool, -} - -fn validate_world_options( - world: bool, - admin_token: Option<&str>, - world_module: Option<&PathBuf>, - world_name: &str, - world_cap_policy: &str, - world_source_only: bool, -) -> Result<()> { - ensure!( - !world || admin_token.is_some_and(|token| !token.is_empty()), - "--world requires --world-admin-token (or ID_WORLD_ADMIN_TOKEN)" - ); - ensure!( - world_module.is_none() || world, - "--world-module requires --world" - ); - #[cfg(feature = "world")] - crate::world_hub::validate_world_name(world_name)?; - ensure!( - world_cap_policy == "deny" || world_cap_policy == "grant-on-use", - "--world-cap-policy must be `deny` or `grant-on-use`" - ); - ensure!( - !world_source_only || world_module.is_none(), - "--world-source-only cannot be combined with --world-module" - ); - ensure!( - !world_source_only || world, - "--world-source-only requires --world" - ); - #[cfg(not(feature = "world"))] - let _ = world_name; - Ok(()) -} - -/// Build the write-access policy for a server. -/// -/// Trusted automatically: the server's own key and this data directory's -/// client key (so the local CLI and REPL work without setup). Added to those: -/// `--allow-node` IDs and the `.iroh-allowed` file. With `open_writes`, every -/// peer may write. -/// -/// # Errors -/// -/// Fails if an `--allow-node` value is not a valid node ID. -pub async fn build_access_policy( - node_id: EndpointId, - allow_node: &[String], - open_writes: bool, -) -> Result { - use crate::access::{AccessPolicy, load_allowed_nodes}; - if open_writes { - return Ok(AccessPolicy::open()); - } - let client_key = load_or_create_keypair(crate::CLIENT_KEY_FILE).await?; - let mut writers = vec![node_id, client_key.public()]; - for id in allow_node { - writers.push( - id.parse::() - .map_err(|e| anyhow::anyhow!("invalid --allow-node {id:?}: {e}"))?, - ); - } - writers.extend(load_allowed_nodes(std::path::Path::new("."))); - Ok(AccessPolicy::restricted(writers)) -} - -/// Root directory for durable worlds, relative to the data directory. -#[cfg(feature = "world")] -pub const WORLDS_DIR: &str = ".id-worlds"; - -#[cfg(feature = "world")] -const OUTBOX_FLUSH_SECS: u64 = 30; - -/// Directory of one durable world, relative to the data directory. -#[cfg(feature = "world")] -#[must_use] -pub fn world_dir(name: &str) -> PathBuf { - PathBuf::from(WORLDS_DIR).join(name) -} - -/// Resolve the compile settings: an explicit flag, the environment, or the -/// conventional repository layout. Absence is fine (compilation stays off). -#[cfg(feature = "world")] -fn resolve_compiler( - roc_bin: Option, - roc_platform: Option, -) -> Result> { - let Some(platform) = roc_platform - .or_else(|| std::env::var("ID_ROC_PLATFORM").ok().map(PathBuf::from)) - .or_else(|| { - [ - PathBuf::from("examples/roc-world"), - PathBuf::from("../examples/roc-world"), - ] - .into_iter() - .find(|dir| dir.is_dir()) - }) - else { - return Ok(None); - }; - let roc_bin = roc_bin - .or_else(|| std::env::var("ID_ROC_BIN").ok()) - .unwrap_or_else(|| "roc".to_owned()); - let compiler = crate::world_compile::Compiler::new(platform, roc_bin)?; - info!( - platform = %compiler.platform_dir.display(), - roc = %compiler.roc_bin, - "world: on-the-fly compilation enabled" - ); - Ok(Some(compiler)) -} - -/// Builds this server's worlds: durable under [`WORLDS_DIR`] unless -/// `ephemeral`. The `--world-module` goes through the same journaled install -/// as an admin upload, so it is pinned, downloadable and restored after a -/// restart; it is only installed when it differs from the module the world -/// already runs. It applies to the default world only. -#[cfg(feature = "world")] -fn mail_sink( - outbox: Option, - command: Option, - smtp: Option, - from: Option, -) -> Result>> { - use crate::directory_mail::{CommandSink, MailSink, OutboxSink, SmtpSink}; - use anyhow::Context as _; - let sink: Arc = match (outbox, command, smtp) { - (Some(dir), _, _) => Arc::new(OutboxSink::new(dir)), - (None, Some(program), _) => Arc::new(CommandSink::new(program, Vec::new())), - (None, None, Some(relay)) => { - let from = from.context("--world-mail-from is needed with --world-mail-smtp")?; - Arc::new(SmtpSink::new(relay, from)?) - } - (None, None, None) => return Ok(None), - }; - Ok(Some(sink)) -} - -/// The server's capability ceiling: the named capabilities, or the whole catalog -/// when no list is given. Like a world ceiling, it names capabilities; `*` is refused. -#[cfg(feature = "world")] -fn allowed_caps(names: Option<&[String]>) -> Result> { - match names { - None => Ok(crate::world_caps::catalog_names()), - Some(names) => { - crate::world_caps::validate_ceiling_names(names)?; - Ok(names.iter().cloned().collect()) - } - } -} - -#[cfg(feature = "world")] -struct ServeWorlds { - ephemeral: bool, - admin_token: Option, - blobs: iroh_blobs::api::Store, - docs: Docs, - checkpoint_every: u64, - default_world: String, - default_module: Option, - grant_on_use: bool, - server_caps: std::collections::BTreeSet, - compiler: Option, - native: bool, - source_only: bool, - runtime: crate::world_limits::RuntimeLimits, - mail: Option>, -} - -#[cfg(feature = "world")] -impl crate::world_hub::WorldOpener for ServeWorlds { - fn open<'a>(&'a self, name: &'a str, create: bool) -> crate::world_hub::OpenFuture<'a> { - Box::pin(async move { - if !create && !self.exists(name) { - return Ok(None); - } - self.open_world(name).await.map(Some) - }) - } - - fn exists(&self, name: &str) -> bool { - !self.ephemeral && world_dir(name).join("journal.jsonl").is_file() - } - - fn list(&self) -> Vec { - if self.ephemeral { - return Vec::new(); - } - let mut names: Vec = std::fs::read_dir(WORLDS_DIR) - .into_iter() - .flatten() - .flatten() - .filter(|entry| entry.path().join("journal.jsonl").is_file()) - .filter_map(|entry| entry.file_name().into_string().ok()) - .filter(|name| crate::world_hub::validate_world_name(name).is_ok()) - .collect(); - names.sort(); - names - } - - fn durable(&self) -> bool { - !self.ephemeral - } -} - -#[cfg(feature = "world")] -impl ServeWorlds { - async fn open_world(&self, name: &str) -> Result { - use crate::world::{WorldCore, WorldHandle, WorldLimits}; - use crate::world_session::WorldService; - - let limits = WorldLimits { - checkpoint_every: self.checkpoint_every, - grant_on_use: self.grant_on_use, - server_caps: self.server_caps.clone(), - ..WorldLimits::default() - }; - let runtime = self.runtime; - let make = { - let admin_token = self.admin_token.clone(); - let blobs = self.blobs.clone(); - let mail = self.mail.clone(); - let source_only = self.source_only; - move |handle| { - let service = WorldService::new(handle, admin_token) - .with_blob_store(blobs) - .with_runtime_limits(runtime) - .with_source_only(source_only); - match &mail { - Some(sink) => service.with_mail(Arc::clone(sink)), - None => service, - } - } - }; - let dir = world_dir(name); - let namespace_file = (!self.ephemeral).then(|| dir.join("records.namespace")); - let records = - crate::world_records::RecordsStore::open(&self.docs, namespace_file.as_deref()).await?; - info!( - world = name, - namespace = %records.namespace(), - "world: records document ready" - ); - info!( - world = name, - ephemeral = self.ephemeral, - "serve startup: records ready, building world service (#190 breadcrumb)" - ); - let service = if self.ephemeral { - make(WorldHandle::spawn(WorldCore::new(name, limits)?)).with_records_store(records) - } else { - let (service, report) = - crate::world_store::open_world(&dir, name, limits, runtime, make).await?; - status!( - "world {name}: restored {} at sequence {} ({} input(s) replayed)", - dir.display(), - report.sequence, - report.replayed_inputs - ); - if let Some(error) = &report.program_error { - status_err!("warning: world {name}: program not restored ({error}); reinstall it"); - } - service.with_records_store(records) - }; - info!( - world = name, - "serve startup: world service built (#190 breadcrumb)" - ); - - let service = if self.native { - service.with_native_enabled() - } else { - service - }; - let service = match self.compiler.clone() { - Some(compiler) => service.with_compiler(compiler), - None => service, - }; - if name == self.default_world - && let Some(path) = self.default_module.as_deref() - { - self.install_default_module(&service, path).await?; - } - info!( - world = name, - "serve startup: world open complete (#190 breadcrumb)" - ); - Ok(service) - } - - #[cfg(feature = "sandbox")] - async fn install_default_module( - &self, - service: &crate::world_session::WorldService, - path: &std::path::Path, - ) -> Result<()> { - let metadata = tokio::fs::metadata(path).await?; - ensure!( - usize::try_from(metadata.len()) - .is_ok_and(|len| len <= crate::world_session::MAX_WORLD_MODULE_BYTES), - "world module exceeds the configured module size limit" - ); - let wasm = tokio::fs::read(path).await?; - let hash = crate::world_session::module_hash(&wasm); - if service.active_module_hash().await.as_deref() == Some(hash.as_str()) { - info!(module = %path.display(), "world: module already active"); - } else { - let seed = rand::rng().random::(); - service - .install_wasm(self.admin_token.as_deref(), wasm, seed, &hash) - .await - .map_err(|e| anyhow::anyhow!("install {}: {e:?}", path.display()))?; - info!(module = %path.display(), seed, "world: installed module"); - } - Ok(()) - } - - #[cfg(not(feature = "sandbox"))] - #[allow(clippy::unused_async)] - async fn install_default_module( - &self, - _service: &crate::world_session::WorldService, - _path: &std::path::Path, - ) -> Result<()> { - anyhow::bail!("--world-module requires a build with the `sandbox` feature"); - } -} - -/// Starts the serve process. -/// -/// Initializes the Iroh endpoint, blob store, protocol handlers, and -/// (optionally) gossip-based peer discovery, then waits for incoming -/// connections until interrupted with Ctrl+C. -/// -/// # Arguments -/// -/// * `ephemeral` - If `true`, use in-memory storage (lost on exit) -/// * `no_relay` - If `true`, disable relay servers (direct connections only) -/// * `no_gossip` - If `true`, disable gossip/DHT peer discovery entirely -/// * `web` - If `true`, start the web interface (requires `web` feature) -/// * `port` - Port for the web interface (default 3000) -/// * `bootstrap` - Additional node IDs for manual peer bootstrapping -/// * `topic` - Custom gossip topic name (default: from `defaults.conf` or `DEFAULT_TOPIC`) -/// * `topic_secret` - Custom shared secret for topic access control -/// * `no_default_bootstrap` - If `true`, skip default bootstrap nodes from `defaults.conf` -/// * `no_default_topic` - If `true`, skip default topic/secret from `defaults.conf` -/// * `replace_defaults` - If `true`, use only `defaults.conf` values (skip hardcoded fallbacks) -/// -/// # Behavior -/// -/// 1. Loads or creates the node keypair -/// 2. Opens the blob store (persistent or ephemeral) -/// 3. Creates the Iroh endpoint with DNS/Pkarr address lookup -/// 4. Creates peer discovery table -/// 5. Unless `no_gossip`: creates gossip instance, registers gossip ALPN, -/// joins topic via DHT, spawns announce/receive/cleanup tasks -/// 6. Registers `MetaProtocol` and `BlobsProtocol` handlers -/// 7. Optionally starts the web interface on the specified port -/// 8. Creates the lock file for local process discovery -/// 9. Waits for Ctrl+C -/// 10. Cleans up and exits -/// -/// # Output -/// -/// Prints the node ID, mode, and peer discovery status to stdout. -/// Status messages go to stderr. -#[allow(unused_variables)] // web/port only used with web feature -/// The group log the serve warning watcher reads: the global -/// `--groups-log` option when given, else the default file name — -/// resolved with the group commands' semantics (#2778; serve used -/// to hardcode the default and ignore the option). -fn serve_groups_log_path(path: Option) -> PathBuf { - crate::commands::group::log_path(path) -} - -/// The largest blob the gate's HashSeq expansion will read into memory: a -/// `HashSeq` of this size names 32768 children, far beyond any collection -/// this node serves; a larger blob is treated as plain content, never a -/// collection, so building the reference index stays size-bounded. -#[cfg(feature = "web")] -const MAX_HASHSEQ_BYTES: u64 = 1 << 20; - -/// Builds the blob gate's folded worlds from the two sources serve has: the group -/// log at `groups_log` for membership, and the event store's document references -/// for which blobs each world names (#173). -/// -/// A referenced blob that parses as a `HashSeq` contributes its children to the -/// same world, but only when every child is present in the store — arbitrary -/// content whose length is a multiple of 32 bytes would otherwise spray -/// references onto hashes nobody stored. Any source that fails to read folds to -/// empty for that source: the gate fails closed, and the next refresh retries. -#[cfg(feature = "web")] -async fn build_blob_gate( - events: &Arc>, - store: &iroh_blobs::api::Store, - groups_log: &std::path::Path, -) -> crate::blob_gate::FoldedWorlds { - let group_projection = match GroupLog::open(groups_log) { - Ok(log) => match crate::blob_gate::fold_group_events(log.events()) { - Ok(projection) => Some(projection), - Err(error) => { - warn!("blob gate: group log does not fold: {error}"); - None - } - }, - Err(error) => { - warn!("blob gate: cannot open group log: {error}"); - None - } - }; - let references = { - let events = events.lock().await; - match events.document_references() { - Ok(references) => references, - Err(error) => { - warn!("blob gate: cannot read document references: {error}"); - Vec::new() - } - } - }; - // Expand HashSeq collections whose children are all in the store. The - // expansion is bounded (#7181 review): only a group-referenced blob can - // contribute children to the index — an ungrouped reference is discarded - // below, so reading it here would be pure waste — and a blob is read into - // memory only when its stored size, asked from the store status rather - // than the content, is a positive multiple of 32 no larger than - // MAX_HASHSEQ_BYTES. A HashSeq is a list of 32-byte hashes; anything else - // cannot be one, and an oversized one is not worth a startup-time read - // proportional to its full contents. - let mut children: std::collections::HashMap> = - std::collections::HashMap::new(); - let mut seen: std::collections::BTreeSet = std::collections::BTreeSet::new(); - let mut frontier: Vec = references - .iter() - .filter(|(_, group)| group.is_some()) - .map(|(hash, _)| *hash) - .collect(); - while let Some(hash) = frontier.pop() { - if !seen.insert(hash) { - continue; - } - let Ok(iroh_blobs::api::blobs::BlobStatus::Complete { size }) = store.status(hash).await - else { - continue; - }; - if size == 0 || size > MAX_HASHSEQ_BYTES || !size.is_multiple_of(32) { - continue; - } - let Ok(bytes) = store.get_bytes(hash).await else { - continue; - }; - let kids = crate::blob_gate::hashseq_children(&bytes); - if kids.is_empty() { - continue; - } - let mut all_present = true; - for kid in &kids { - match store.has(*kid).await { - Ok(true) => {} - _ => { - all_present = false; - break; - } - } - } - if all_present { - frontier.extend(kids.iter().copied()); - children.insert(hash, kids); - } - } - let named = references - .into_iter() - .filter_map(|(hash, group)| group.map(|group| (hash, crate::blob_gate::world_key(&group)))); - let index = crate::blob_gate::build_reference_index(named, |hash| { - children.get(hash).cloned().unwrap_or_default() - }); - match group_projection { - Some(projection) => { - crate::blob_gate::FoldedWorlds::from_group_projection(projection, index) - } - None => crate::blob_gate::FoldedWorlds::new(crate::groups::worlds::Worlds::empty(), index), - } -} - -pub async fn cmd_serve(opts: ServeOptions) -> Result<()> { - let ServeOptions { - ephemeral, - groups_log, - no_relay, - no_gossip, - web, - port, - bootstrap, - topic, - topic_secret, - no_default_bootstrap, - no_default_topic, - replace_defaults, - no_mdns, - dht, - iroh_port, - bind, - web_token, - web_cookie_secure, - world, - world_admin_token, - world_module, - world_mail_outbox, - world_mail_command, - world_mail_smtp, - world_mail_from, - world_name, - world_checkpoint_every, - world_max_open, - world_max_sessions, - world_idle_secs, - world_boot_window_secs, - world_caps, - world_cap_policy, - world_allowed_caps, - roc_bin, - roc_platform, - world_native, - world_source_only, - world_ssh_port, - world_runtime, - allow_node, - open_writes, - } = opts; - validate_world_options( - world, - world_admin_token.as_deref(), - world_module.as_ref(), - &world_name, - &world_cap_policy, - world_source_only, - )?; - #[cfg(not(feature = "world"))] - let _ = &world_allowed_caps; - let key = load_or_create_keypair(KEY_FILE).await?; - let node_id: EndpointId = key.public(); - info!("serve: {}", node_id); - - // Who may modify this store: this node, this machine's client key (so the - // local CLI/REPL work with no setup), `--allow-node`, and `.iroh-allowed`. - let access = build_access_policy(node_id, &allow_node, open_writes).await?; - - let store = open_store(ephemeral).await?; - let store_handle = store.as_store(); - - let mut builder = crate::connectivity::public_builder( - crate::connectivity::RelayPolicy::from_no_relay(no_relay), - ) - .secret_key(key.clone()); - if !no_mdns { - builder = builder.address_lookup(MdnsAddressLookup::builder()); - } - let dht_policy = crate::dht::DhtPolicy::from_server(dht); - #[cfg(feature = "dht")] - if dht_policy.is_on() { - builder = crate::dht::with_lookup(&dht_policy, builder, crate::dht::mainline()); - } - #[cfg(not(feature = "dht"))] - if dht_policy.is_on() { - warn!( - "--dht was requested, but `id` was compiled without the optional `dht` feature; DHT lookup is not active" - ); - } - if iroh_port != 0 { - builder = builder.bind_addr(std::net::SocketAddrV4::new( - Ipv4Addr::UNSPECIFIED, - iroh_port, - ))?; - } - let endpoint = builder.bind().await?; - - // Create peer discovery table - let peer_discovery = PeerDiscovery::new(); - - // Always create Gossip — iroh-docs needs it even if peer discovery is off - let gossip = Gossip::builder().spawn(endpoint.clone()); - - // Initialize iroh-docs for tag metadata storage - let docs = if ephemeral { - Docs::memory() - .spawn(endpoint.clone(), store_handle.clone(), gossip.clone()) - .await? - } else { - let docs_path = PathBuf::from(STORE_PATH).join("docs"); - std::fs::create_dir_all(&docs_path)?; - Docs::persistent(docs_path) - .spawn(endpoint.clone(), store_handle.clone(), gossip.clone()) - .await? - }; - - // Initialize TagStore (creates α/Ω namespace pairs) - let tag_store = TagStore::init(&docs, &node_id.to_string()).await?; - let tag_store = Arc::new(tag_store); - info!("tags: initialized (α/Ω global + node namespaces)"); - match tag_store.migrate_legacy_meta(&store_handle).await { - Ok(0) => {} - Ok(n) => info!("tags: imported {n} legacy metadata tag(s) from .meta"), - Err(e) => warn!("tags: legacy metadata import failed: {e:#}"), - } - - // The node's own event store, shared between the web layer and /id-range-sync/1 - // range sync (#792). Serve opens it once, on the same directory the web - // state would open (the `events` sibling of the identity database), and - // hands the one instance to both: the store admits a single opener, and a - // second store over the same directory would diverge from the one the web - // layer publishes ProseMirror save revisions into. Only opened when the - // web UI is on — that is the store whose revisions replicate, and opening - // it unconditionally would change the local CLI's access to the directory - // while serve runs. - #[cfg(feature = "web")] - let event_events: Option>> = if web { - let identity_db_path = std::path::Path::new(KEY_FILE).with_file_name(".identity.redb"); - let events_dir = identity_db_path.with_file_name(crate::local_events::DIR_NAME); - let events = crate::local_events::LocalEvents::open( - &events_dir, - p2panda_core::SigningKey::from_bytes(&key.to_bytes()), - )?; - Some(Arc::new(tokio::sync::Mutex::new(events))) - } else { - None - }; - - // The blob membership gate (#173). With the event store open, serve builds the - // gate from the group log (membership) and the store's document references - // (which blobs each world names), and a refresh task below keeps it current. - // Without the store there is no document source to index, so blob reads stay - // ungated this run — push-only, as before — and serve says so at startup. - #[cfg(feature = "web")] - let blob_gate: Option> = match &event_events { - Some(events) => { - let folded = build_blob_gate( - events, - &store_handle, - &serve_groups_log_path(groups_log.clone()), - ) - .await; - Some(Arc::new(crate::blob_gate::RefreshingWorlds::new(folded))) - } - None => None, - }; - #[cfg(not(feature = "web"))] - let blob_gate: Option> = None; - if blob_gate.is_none() { - warn!( - "blob gate (#173): inactive — the event store is only opened with the web UI, \ - so blob reads are not membership-checked this run" - ); - } - - // Build router — gossip ALPN is always registered (needed by iroh-docs), - // but peer discovery gossip topic only joins when gossip is enabled - let meta = MetaProtocol::new( - &store_handle, - Some(peer_discovery.clone()), - Arc::clone(&tag_store), - access.clone(), - node_id, - ); - // iroh-blobs rejects pushes unless an event handler enables them; this one - // allows them only from nodes the access policy lets write. With the blob - // gate built, the gate's handler decides pushes the same way and also - // membership-checks fetches and observes (#173). - // The gate's local readers: the node's own key and the data directory's - // client key — the keys the write policy already trusts automatically — - // so the local CLI and REPL keep reading the node's own store with the - // gate on (#173, #7181 review). - let local_readers: std::collections::BTreeSet = - match load_or_create_keypair(crate::CLIENT_KEY_FILE).await { - Ok(client_key) => [node_id, client_key.public()].into_iter().collect(), - Err(error) => { - warn!("blob gate: cannot load the client key for local reads: {error}"); - [node_id].into_iter().collect() - } - }; - let blobs = match &blob_gate { - Some(gate) => BlobsProtocol::new( - &store_handle, - Some(crate::blob_gate::blob_events( - Arc::clone(gate), - crate::blob_gate::BlobPolicy::default(), - access.clone(), - local_readers, - )), - ), - None => BlobsProtocol::new( - &store_handle, - Some(crate::access::blobs_events(access.clone())), - ), - }; - - // Every world lives in one hub, shared by the Iroh protocol and the web - // bridge. The default world opens now so a bad journal fails startup. - #[cfg(feature = "world")] - let world_hub = if world { - use crate::world_hub::{HubLimits, WorldHub}; - let runtime = crate::world_limits::RuntimeLimits::from_args(&world_runtime)?; - let server_caps = allowed_caps(world_allowed_caps.as_deref())?; - let compiler = resolve_compiler(roc_bin, roc_platform)?; - ensure!( - !world_source_only || compiler.is_some(), - "--world-source-only requires a configured Roc compiler and platform (see --roc-bin and --roc-platform)" - ); - let opener = Arc::new(ServeWorlds { - ephemeral, - admin_token: world_admin_token.clone(), - blobs: store_handle.clone(), - docs: docs.clone(), - checkpoint_every: world_checkpoint_every, - default_world: world_name.clone(), - default_module: world_module.clone(), - grant_on_use: world_cap_policy == "grant-on-use", - server_caps: server_caps.clone(), - compiler, - native: world_native, - source_only: world_source_only, - runtime, - mail: mail_sink( - world_mail_outbox, - world_mail_command, - world_mail_smtp, - world_mail_from, - )?, - }); - let hub = WorldHub::new( - opener, - world_admin_token.clone(), - world_name.clone(), - HubLimits { - max_open_worlds: world_max_open, - max_sessions: world_max_sessions, - signed_boot_window: std::time::Duration::from_secs(world_boot_window_secs), - }, - ); - info!("serve startup: opening default world via hub (#190 breadcrumb)"); - let default_service = hub.open_default().await?; - info!("serve startup: default world open, building router (#190 breadcrumb)"); - if !world_caps.is_empty() { - for cap in world_caps.iter().filter(|cap| *cap != "*") { - if !server_caps.contains(cap) { - warn!( - "world: --world-cap {cap} is outside --world-allowed-caps; the program will be refused it" - ); - } - } - default_service - .world() - .update_caps(world_caps.clone(), Vec::new()) - .await?; - } - if world_idle_secs > 0 && !ephemeral { - let idle = std::time::Duration::from_secs(world_idle_secs); - hub.spawn_evictor( - (idle / 2).clamp( - std::time::Duration::from_secs(1), - std::time::Duration::from_secs(60), - ), - idle, - ); - } - Some(hub) - } else { - None - }; - #[cfg(feature = "world")] - let outbox_flush = match &world_hub { - Some(hub) if !ephemeral => Some(hub.spawn_outbox_flush( - std::time::Duration::from_secs(OUTBOX_FLUSH_SECS), - endpoint.clone(), - )), - _ => None, - }; - #[cfg(not(feature = "world"))] - ensure!(!world, "this build has no world support (feature `world`)"); - - #[cfg(all(feature = "world", feature = "ssh"))] - let (ssh_tunnel, ssh_tunnel_port) = crate::world_ssh::SshTunnelProtocol::deferred(); - let router_builder = Router::builder(endpoint) - .accept(META_ALPN, meta) - .accept(BLOBS_ALPN, blobs) - .accept(iroh_gossip::net::GOSSIP_ALPN, gossip.clone()) - .accept(iroh_docs::net::ALPN, docs.clone()); - #[cfg(feature = "web")] - let router_builder = match &event_events { - Some(events) => router_builder.accept( - crate::event_store::sync::ALPN, - crate::event_sync::EventSyncProtocol::new(Arc::clone(events)), - ), - None => router_builder, - }; - #[cfg(feature = "world")] - let router_builder = match &world_hub { - Some(hub) => router_builder - .accept( - crate::world_net::WORLD_ALPN, - crate::world_net::WorldProtocol::new(hub.clone()), - ) - .accept( - crate::envelope_net::ENVELOPE_ALPN, - crate::envelope_net::EnvelopeProtocol::new(hub.clone()), - ) - .accept( - crate::artifact::PUSH_ALPN, - crate::artifact::ArtifactPushProtocol::new(hub.clone()), - ) - .accept( - crate::artifact::PULL_ALPN, - crate::artifact::ArtifactPullProtocol::new(hub.clone()), - ), - None => router_builder, - }; - #[cfg(all(feature = "world", feature = "ssh"))] - let router_builder = router_builder.accept(crate::world_ssh::SSH_TUNNEL_ALPN, ssh_tunnel); - let router = router_builder.spawn(); - info!("serve startup: router spawned (#190 breadcrumb)"); - - // Offer a sync session to every discovered peer, on an interval: a save on - // either node is discoverable on the other after the next session (#792). - // Peers that do not serve /id-range-sync/1 fail the dial, which is logged at debug - // and otherwise ignored — accepting sessions above is what serves the rest. - #[cfg(feature = "web")] - let _event_sync_handle = event_events.clone().map(|events| { - status!("event sync: /id-range-sync/1 enabled (the web event store)"); - let endpoint = router.endpoint().clone(); - let discovery = peer_discovery.clone(); - let gate = crate::event_sync::open_gate(); - tokio::spawn(async move { - loop { - tokio::time::sleep(crate::event_sync::SYNC_INTERVAL).await; - for peer in discovery.peers() { - let peer_id = peer.announcement.node_id; - if peer_id == endpoint.id() { - continue; - } - match crate::event_sync::sync_with_peer(&endpoint, peer_id, &events, &gate) - .await - { - Ok(outcome) if outcome.sent + outcome.received > 0 => { - info!( - "event sync: {peer_id}: sent {} received {}", - outcome.sent, outcome.received - ); - } - Ok(_) => {} - Err(error) => { - debug!("event sync: session with {peer_id} failed: {error:#}"); - } - } - } - } - }) - }); - - if !no_gossip { - // Resolve effective config from defaults + CLI flags - let config = resolve_config( - &bootstrap, - topic.as_deref(), - topic_secret.as_deref(), - replace_defaults, - no_default_bootstrap, - no_default_topic, - ); - - let dtt_topic_id = TopicId::new(config.topic.clone()); - - // Convert iroh SecretKey to ed25519-dalek types for RecordPublisher - let dalek_signing_key = ed25519_dalek::SigningKey::from_bytes(&key.to_bytes()); - - let record_publisher = RecordPublisher::new( - dtt_topic_id, - dalek_signing_key, - None, - config.topic_secret.clone(), - distributed_topic_tracker::Config::default(), - ); - - // Join gossip topic with auto-discovery (non-blocking) - let gossip_topic = gossip - .subscribe_and_join_with_auto_discovery_no_wait(record_publisher) - .await?; - let (sender, receiver) = gossip_topic.split().await?; - - // Join bootstrap peers (both defaults and CLI-provided, already merged) - let bootstrap_node_ids: Vec = config - .bootstrap - .iter() - .filter_map(|id_str| { - id_str.parse::().ok().or_else(|| { - warn!("invalid bootstrap node ID: {}", id_str); - None - }) - }) - .collect(); - if !bootstrap_node_ids.is_empty() { - info!("joining {} bootstrap peer(s)", bootstrap_node_ids.len()); - sender.join_peers(bootstrap_node_ids, None).await?; - } - - // Spawn background gossip task - let gossip_peer_discovery = peer_discovery.clone(); - let gossip_store = store_handle.clone(); - let gossip_node_id = node_id; - let gossip_endpoint = router.endpoint().clone(); - let _gossip_handle = tokio::spawn(async move { - run_gossip_loop( - gossip_node_id, - sender, - receiver, - gossip_peer_discovery, - gossip_store, - gossip_endpoint, - ) - .await; - }); - - status!("peers: gossip enabled (topic: {})", config.topic); - } - - let serve_node_id = router.endpoint().id(); - let bound_addrs = router.endpoint().bound_sockets(); - let local_addrs: Vec = bound_addrs - .iter() - .map(|addr| match addr { - SocketAddr::V4(v4) if v4.ip().is_unspecified() => { - SocketAddr::new(Ipv4Addr::LOCALHOST.into(), v4.port()) - } - SocketAddr::V6(v6) if v6.ip().is_unspecified() => { - SocketAddr::new(Ipv6Addr::LOCALHOST.into(), v6.port()) - } - other => *other, - }) - .collect(); - - // Bind the web server early to capture the actual port for the lock file, - // but don't start serving yet (spawn happens after lock file is written). - #[allow(unused_mut)] // web_port is only mutated with the `web` feature - let mut web_port: Option = None; - #[cfg(feature = "web")] - let web_listener = if web { - info!("serve startup: binding web listener (#190 breadcrumb)"); - let addr = SocketAddr::new(bind, port); - let listener = tokio::net::TcpListener::bind(addr).await?; - let actual_port = listener.local_addr()?.port(); - info!( - port = actual_port, - "serve startup: web listener bound (#190 breadcrumb)" - ); - web_port = Some(actual_port); - Some(listener) - } else { - None - }; - - #[cfg(feature = "ssh")] - let ssh = match (world_ssh_port, &world_hub) { - (Some(port), Some(hub)) => { - let listener = tokio::net::TcpListener::bind(SocketAddr::new(bind, port)).await?; - let ssh_port = listener.local_addr()?.port(); - #[cfg(feature = "world")] - let _ = ssh_tunnel_port.set(ssh_port); - let host_key = - crate::world_ssh::load_or_create_host_key(crate::world_ssh::SSH_HOST_KEY_FILE) - .await?; - Some(( - listener, - ssh_port, - hub.clone(), - host_key, - store_handle.clone(), - )) - } - _ => None, - }; - #[cfg(not(feature = "ssh"))] - ensure!( - world_ssh_port.is_none(), - "this build has no SSH support (feature `ssh`)" - ); - - // Write the lock file before printing status so it exists when callers - // detect the server via stdout output (integration tests depend on this). - info!("serve startup: writing serve lock (#190 breadcrumb)"); - create_serve_lock(&serve_node_id, &local_addrs, web_port).await?; - info!("serve startup: serve lock written, printing node status (#190 breadcrumb)"); - - status!("node: {serve_node_id}"); - if ephemeral { - status!("mode: ephemeral (in-memory)"); - } else { - status!("mode: persistent ({STORE_PATH})"); - } - if no_relay { - status!("relay: disabled"); - } - if no_gossip { - status!("peers: disabled"); - } - if no_mdns { - status!("mdns: disabled"); - } else { - status!("mdns: enabled"); - } - if access.is_open() { - status!("access: OPEN WRITES (any peer may modify this store)"); - } else { - status!( - "access: read-only for peers; {} node(s) may write", - access.writers().len() - ); - } - #[cfg(feature = "world")] - if world { - status!( - "world {world_name}: enabled (iroh {})", - String::from_utf8_lossy(crate::world_net::WORLD_ALPN) - ); - #[cfg(feature = "web")] - if web { - status!("world: web bridge at /ws/world"); - } - } - - // Start web server now that the lock file is written - #[cfg(feature = "web")] - let _web_handle = if let Some(listener) = web_listener { - let identity_db_path = std::path::Path::new(KEY_FILE).with_file_name(".identity.redb"); - let web_router = match &event_events { - Some(events) => { - crate::web::web_router_with_local_events( - store_handle.clone(), - Some(peer_discovery.clone()), - node_id.to_string(), - Arc::clone(&tag_store), - key.to_bytes(), - identity_db_path, - crate::web::WebSecurity::for_bind(bind, web_token.clone(), &[]), - world_hub.clone(), - web_cookie_secure, - Arc::clone(events), - ) - .await? - } - None => { - crate::web::web_router( - store_handle.clone(), - Some(peer_discovery.clone()), - node_id.to_string(), - Arc::clone(&tag_store), - key.to_bytes(), - identity_db_path, - crate::web::WebSecurity::for_bind(bind, web_token.clone(), &[]), - world_hub.clone(), - web_cookie_secure, - ) - .await? - } - }; - let actual_port = web_port.unwrap_or(port); - let shown_host = if bind.is_unspecified() || bind.is_loopback() { - "localhost".to_owned() - } else { - bind.to_string() - }; - if let Some(t) = &web_token { - status!("web: http://{shown_host}:{actual_port}/?token={t}"); - } else { - status!("web: http://{shown_host}:{actual_port}"); - } - #[cfg(feature = "world")] - if world { - status!("world: browser http://{shown_host}:{actual_port}/world"); - } - if !bind.is_loopback() && web_token.is_none() { - status_err!( - "warning: the web UI is bound to {bind} without --web-token; \ - anyone who can reach port {actual_port} can read and modify files" - ); - } - if world_hub.is_some() && !bind.is_loopback() && !web_cookie_secure { - status_err!( - "warning: the admin sign-in form is served over plain HTTP on {bind}; \ - its token and session cookie travel in clear unless HTTPS is terminated \ - in front (then pass --web-cookie-secure) or the UI is bound to loopback" - ); - } - Some(tokio::spawn(async move { - if let Err(e) = axum::serve(listener, web_router).await { - tracing::error!("web server error: {}", e); - } - })) - } else { - None - }; - - #[cfg(feature = "ssh")] - let ssh_handle = ssh.map(|(listener, ssh_port, hub, host_key, blobs)| { - status!("world ssh: port {ssh_port} (ssh -p {ssh_port} @)"); - status!( - "world ssh host key: {}", - crate::world_ssh::host_key_fingerprint(&host_key) - ); - status!( - "world ssh over iroh: `id world ssh-tunnel ` then `ssh -p 2222 @127.0.0.1`" - ); - tokio::spawn(async move { - if let Err(e) = crate::world_ssh::serve(listener, hub, host_key, blobs).await { - tracing::error!("world ssh server error: {}", e); - } - }) - }); - - // Group warnings (P4.9, #799): one persistent Evaluator for the life of - // the process. The first pass runs here so active warnings surface in - // the CLI status output at startup; the spawned task then re-evaluates - // as membership changes and writes fired warnings to the server log. - let mut group_watcher = GroupWarningWatcher::new(); - let groups_log = serve_groups_log_path(groups_log); - for (_, warning) in evaluate_group_warnings(&mut group_watcher, &groups_log, unix_now()) { - status!("group warning: {}", warning.message()); - } - #[cfg(feature = "web")] - let gate_groups_log = groups_log.clone(); - let group_warning_handle = tokio::spawn(async move { - let mut interval = tokio::time::interval(GROUP_WARNING_INTERVAL); - interval.tick().await; - loop { - interval.tick().await; - evaluate_group_warnings(&mut group_watcher, &groups_log, unix_now()); - } - }); - - // Blob gate refresh (#173): on the same cadence as the group warnings, - // re-fold the group log and the document references so a removed member - // loses fetch and a new document becomes fetchable without a restart. - #[cfg(feature = "web")] - let blob_gate_handle = match (&blob_gate, &event_events) { - (Some(gate), Some(events)) => { - let gate = Arc::clone(gate); - let events = Arc::clone(events); - let store = store_handle.clone(); - let groups_log = gate_groups_log; - Some(tokio::spawn(async move { - let mut interval = tokio::time::interval(GROUP_WARNING_INTERVAL); - interval.tick().await; - loop { - interval.tick().await; - let folded = build_blob_gate(&events, &store, &groups_log).await; - gate.refresh(folded); - } - })) - } - _ => None, - }; - - tokio::signal::ctrl_c().await?; - remove_serve_lock().await?; - router.shutdown().await?; - #[cfg(feature = "web")] - if let Some(sync_task) = _event_sync_handle { - sync_task.abort(); - let _ = sync_task.await; - } - #[cfg(feature = "web")] - if let Some(web_task) = _web_handle { - web_task.abort(); - let _ = web_task.await; - } - #[cfg(feature = "ssh")] - if let Some(ssh_task) = ssh_handle { - ssh_task.abort(); - let _ = ssh_task.await; - } - #[cfg(feature = "world")] - if let Some(flush) = outbox_flush { - flush.abort(); - let _ = flush.await; - } - #[cfg(feature = "world")] - if let Some(hub) = &world_hub { - hub.shutdown_all().await; - } - #[cfg(feature = "web")] - if let Some(gate_task) = blob_gate_handle { - gate_task.abort(); - let _ = gate_task.await; - } - group_warning_handle.abort(); - let _ = group_warning_handle.await; - store.shutdown().await?; - Ok(()) -} - -/// How often serve re-evaluates the group warnings against the group log. -const GROUP_WARNING_INTERVAL: std::time::Duration = std::time::Duration::from_secs(60); - -/// The serve-side group warning watcher (P4.9, #799). -/// -/// Serve holds exactly one of these for the life of the process, so the -/// [`Evaluator`]'s high-water marks survive across evaluations: a group that -/// crosses a size threshold warns once, not on every pass. The groups in the -/// node's own group log are the ones its operator made through the CLI, so -/// every group is observed as client-made. Member counts come from the fold. -/// -/// Group events carry no timestamps, so churn cannot be reconstructed from -/// the log for time before serve started. Instead the watcher derives re-adds -/// from what it observes between evaluations: a device that is authorized, -/// later unauthorized, and then authorized again is a re-add, stamped with -/// the time of the evaluation that first sees it back. -struct GroupWarningWatcher { - evaluator: Evaluator, - /// The devices authorized per group at the previous evaluation. - devices: std::collections::BTreeMap>, - /// Every device ever seen authorized per group. - seen_devices: std::collections::BTreeMap>, - /// The re-add times per group, as observed by this watcher. - readds: std::collections::BTreeMap>, -} - -impl GroupWarningWatcher { - fn new() -> Self { - Self { - evaluator: Evaluator::default(), - devices: std::collections::BTreeMap::new(), - seen_devices: std::collections::BTreeMap::new(), - readds: std::collections::BTreeMap::new(), - } - } - - /// Evaluates every active group in `projection` at `now` (Unix seconds). - /// Returns the warnings this evaluation adds, and writes each of them to - /// the server log through the warnings module. - fn evaluate(&mut self, projection: &Projection, now: u64) -> Vec<(Hash, Warning)> { - let mut fired = Vec::new(); - for (group, view) in projection.groups() { - if !view.is_active() { - continue; - } - let current = projection.group_active_devices(group); - let mut new_readds = 0_usize; - { - let seen = self.seen_devices.entry(*group).or_default(); - let previous = self.devices.entry(*group).or_default(); - for device in ¤t { - if !previous.contains(device) && seen.contains(device) { - new_readds += 1; - } - } - seen.extend(current.iter().copied()); - *previous = current; - } - if new_readds > 0 { - let times = self.readds.entry(*group).or_default(); - for _ in 0..new_readds { - times.push(now); - } - times.retain(|at| { - now.saturating_sub(*at) < crate::groups::warnings::CHURN_WINDOW_SECS - }); - } - let readds = self.readds.get(group).cloned().unwrap_or_default(); - let observation = Observation { - group: *group, - client_made: true, - members: view.members.len(), - readds: &readds, - }; - let warnings = self.evaluator.observe(&observation, now); - if !warnings.is_empty() { - crate::groups::warnings::log(group, &warnings); - fired.extend(warnings.into_iter().map(|warning| (*group, warning))); - } - } - fired - } -} - -/// One warning evaluation pass over the group log at `path`. -/// -/// A missing log means no groups, not an error. A log that cannot be read or -/// folded is noted in the server log and skipped: warnings never block serve. -fn evaluate_group_warnings( - watcher: &mut GroupWarningWatcher, - path: &std::path::Path, - now: u64, -) -> Vec<(Hash, Warning)> { - if !path.exists() { - return Vec::new(); - } - let log = match GroupLog::open(path) { - Ok(log) => log, - Err(error) => { - debug!("group warnings: cannot open {}: {error}", path.display()); - return Vec::new(); - } - }; - let projection = match log.projection() { - Ok(projection) => projection, - Err(error) => { - debug!("group warnings: cannot fold {}: {error}", path.display()); - return Vec::new(); - } - }; - watcher.evaluate(&projection, now) -} - -/// The current time as Unix seconds, for the warning evaluator's clock. -fn unix_now() -> u64 { - std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map(|duration| duration.as_secs()) - .unwrap_or(0) -} - -/// Background loop for gossip-based peer discovery. -/// -/// Runs three concurrent tasks: -/// 1. **Announce**: Broadcasts a [`PeerAnnouncement`] every [`ANNOUNCE_INTERVAL`] -/// 2. **Receive**: Listens for incoming gossip events and updates the peer table -/// 3. **Cleanup**: Periodically probes stale peers via `ListPeers` RPC — refreshes -/// their `last_seen` if reachable, removes them if not -/// -/// This function runs until the sender/receiver are dropped (on shutdown). -async fn run_gossip_loop( - node_id: EndpointId, - sender: distributed_topic_tracker::GossipSender, - mut receiver: distributed_topic_tracker::GossipReceiver, - peer_discovery: PeerDiscovery, - store: iroh_blobs::api::Store, - endpoint: Endpoint, -) { - // Timeout for each individual peer probe. - const PROBE_TIMEOUT: tokio::time::Duration = tokio::time::Duration::from_secs(10); - - let announce_store = store; - let announce_node_id = node_id; - - // Spawn announce task - let announce_handle = tokio::spawn(async move { - let mut interval = tokio::time::interval(ANNOUNCE_INTERVAL); - loop { - interval.tick().await; - // Get blob count from tags - let blob_count = match announce_store.tags().list().await { - Ok(mut stream) => { - let mut count = 0u64; - while stream.next().await.is_some() { - count += 1; - } - count - } - Err(_) => 0, - }; - - let announcement = PeerAnnouncement { - node_id: announce_node_id, - name: None, - blob_count, - timestamp_secs: std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map_or(0, |d| d.as_secs()), - }; - - match postcard::to_allocvec(&announcement) { - Ok(bytes) => { - if let Err(e) = sender.broadcast(bytes).await { - debug!("gossip broadcast error: {}", e); - } - } - Err(e) => { - debug!("gossip announcement serialization error: {}", e); - } - } - } - }); - - // Spawn receive task - let recv_discovery = peer_discovery.clone(); - let recv_handle = tokio::spawn(async move { - loop { - match receiver.next().await { - Ok(event) => match event { - iroh_gossip::api::Event::Received(msg) => { - match postcard::from_bytes::(&msg.content) { - Ok(announcement) => { - debug!( - "peer announcement from {}: blob_count={}", - announcement.node_id, announcement.blob_count - ); - recv_discovery.update(announcement); - } - Err(e) => { - debug!("failed to deserialize peer announcement: {}", e); - } - } - } - iroh_gossip::api::Event::NeighborUp(peer) => { - info!("gossip neighbor up: {}", peer); - } - iroh_gossip::api::Event::NeighborDown(peer) => { - info!("gossip neighbor down: {}", peer); - } - iroh_gossip::api::Event::Lagged => { - warn!("gossip receiver lagged, some messages were missed"); - } - }, - Err(e) => { - debug!("gossip receiver stream ended: {}", e); - break; - } - } - } - }); - - // Spawn stale cleanup task — probes stale peers before removal - let cleanup_discovery = peer_discovery; - - let cleanup_handle = tokio::spawn(async move { - let mut interval = tokio::time::interval(STALE_CHECK_INTERVAL); - - loop { - interval.tick().await; - - let stale = cleanup_discovery.stale_peers(); - if stale.is_empty() { - continue; - } - - debug!("probing {} stale peer(s)", stale.len()); - - for info in &stale { - let peer_id = info.announcement.node_id; - - // Try to connect and send ListPeers RPC - let probe_result = tokio::time::timeout(PROBE_TIMEOUT, async { - let conn = crate::connectivity::connect(&endpoint, peer_id, META_ALPN).await?; - let (mut send, mut recv) = conn.open_bi().await?; - let req = postcard::to_allocvec(&MetaRequest::ListPeers)?; - send.write_all(&req).await?; - send.finish()?; - let resp_buf = crate::meta_client::read_capped_response(&mut recv).await?; - let _resp: MetaResponse = postcard::from_bytes(&resp_buf)?; - conn.close(0u32.into(), b"probe"); - anyhow::Ok(()) - }) - .await; - - match probe_result { - Ok(Ok(())) => { - debug!("stale peer {} is still alive, refreshing", peer_id); - cleanup_discovery.refresh(&peer_id); - } - Ok(Err(e)) => { - debug!("stale peer {} probe failed: {}, removing", peer_id, e); - } - Err(_) => { - debug!("stale peer {} probe timed out, removing", peer_id); - } - } - } - - // Remove peers that are still stale (probes that failed/timed out - // didn't call refresh(), so they remain past STALE_THRESHOLD) - cleanup_discovery.remove_stale(STALE_THRESHOLD); - } - }); - - // Wait for any task to complete (normally they run until shutdown) - tokio::select! { - _ = announce_handle => {} - _ = recv_handle => {} - _ = cleanup_handle => {} - } -} - -#[cfg(test)] -#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] -mod tests { - use super::*; - - /// A scratch directory unique to this test process. - fn serve_test_dir(name: &str) -> PathBuf { - let dir = std::env::temp_dir().join(format!("id-serve-test-{name}-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).unwrap(); - dir - } - - /// Builds a group log on disk holding one group of `members` accounts - /// (the author included), returning the group's ID. This is the file the - /// serve warning path reads. - fn group_log_with_members(dir: &std::path::Path, members: usize) -> Hash { - group_log_with_members_at(&dir.join(GROUPS_FILE_NAME), members) - } - - fn group_log_with_members_at(path: &std::path::Path, members: usize) -> Hash { - use crate::groups::Role; - use crate::groups::actions::NewGroup; - - let mut log = GroupLog::open(path).unwrap(); - let author: GroupKey = [1; 32]; - let created = log - .create( - author, - NewGroup::Normal { - max: None, - admins_on_create: false, - }, - ) - .unwrap(); - for i in 1..members { - let member: GroupKey = [u8::try_from(i + 1).unwrap(); 32]; - log.add(author, created.group, member, Role::Read).unwrap(); - } - created.group - } - - #[test] - fn serve_groups_log_path_honours_override_and_default() { - // #2778: the group-warning watcher's log path must come - // from the global --groups-log option (threaded through - // ServeOptions), resolved exactly like the group commands - // resolve it; without the option the default file name is - // used, unchanged. - let custom = PathBuf::from("shared").join("relocated.jsonl"); - assert_eq!(serve_groups_log_path(Some(custom.clone())), custom); - assert_eq!(serve_groups_log_path(None), PathBuf::from(GROUPS_FILE_NAME)); - } - - #[test] - fn serve_group_warnings_evaluate_custom_groups_log() { - // #2778 regression: warnings are computed from the - // --groups-log file, not the default groups.jsonl. The - // custom log holds a 96-member group; the default log in - // the same directory does not exist, so a watcher reading - // the default would silently warn about nothing. - let dir = serve_test_dir("customlog"); - let custom = dir.join("relocated.jsonl"); - let group = group_log_with_members_at(&custom, 96); - let path = serve_groups_log_path(Some(custom)); - let mut watcher = GroupWarningWatcher::new(); - let fired = evaluate_group_warnings(&mut watcher, &path, 1_000); - assert_eq!(fired.len(), 1); - assert_eq!(fired[0].0, group); - assert!(matches!( - fired[0].1, - Warning::Size { - threshold: 96, - members: 96 - } - )); - let _ = std::fs::remove_dir_all(&dir); - } - - #[test] - fn serve_group_warnings_fire_once_at_each_size_threshold() { - let dir = serve_test_dir("size"); - let path = dir.join(GROUPS_FILE_NAME); - let group = group_log_with_members(&dir, 96); - let mut watcher = GroupWarningWatcher::new(); - - // The integration surface: serve's own evaluation over the on-disk - // group log warns when the group crosses 96 members (P4.9's e2e - // column: "the server warns at a threshold"). - let fired = evaluate_group_warnings(&mut watcher, &path, 1_000); - assert_eq!(fired.len(), 1); - assert_eq!(fired[0].0, group); - assert!(matches!( - fired[0].1, - Warning::Size { - threshold: 96, - members: 96 - } - )); - - // The persistent Evaluator's high-water mark: the same state warns - // no second time. - assert!(evaluate_group_warnings(&mut watcher, &path, 1_001).is_empty()); - - // Growing past the next threshold warns once more, for that tier. - { - let mut log = GroupLog::open(&path).unwrap(); - let author: GroupKey = [1; 32]; - for i in 96..128 { - let member: GroupKey = [u8::try_from(i + 1).unwrap(); 32]; - log.add(author, group, member, crate::groups::Role::Read) - .unwrap(); - } - } - let fired = evaluate_group_warnings(&mut watcher, &path, 1_002); - assert_eq!(fired.len(), 1); - assert!(matches!( - fired[0].1, - Warning::Size { - threshold: 128, - members: 128 - } - )); - let _ = std::fs::remove_dir_all(&dir); - } - - #[test] - fn serve_group_warnings_fire_on_device_readd_churn() { - use crate::groups::Role; - - let dir = serve_test_dir("churn"); - let path = dir.join(GROUPS_FILE_NAME); - let group = group_log_with_members(&dir, 2); - let author: GroupKey = [1; 32]; - let device: GroupKey = [200; 32]; - let mut log = GroupLog::open(&path).unwrap(); - let mut watcher = GroupWarningWatcher::new(); - - // The first authorization is not a re-add, and warns about nothing. - log.device_add(author, group, device, Role::Read).unwrap(); - assert!(evaluate_group_warnings(&mut watcher, &path, 1_000).is_empty()); - - // Four revoke + re-authorize cycles inside the window: the fourth - // re-add crosses the churn threshold and warns exactly once. - for cycle in 0..4_u64 { - log.device_revoke(author, group, device).unwrap(); - assert!(evaluate_group_warnings(&mut watcher, &path, 1_001 + cycle * 2).is_empty()); - log.device_add(author, group, device, Role::Read).unwrap(); - let fired = evaluate_group_warnings(&mut watcher, &path, 1_002 + cycle * 2); - if cycle < 3 { - assert!(fired.is_empty(), "cycle {cycle} fired early: {fired:?}"); - } else { - assert_eq!(fired.len(), 1); - assert!(matches!(fired[0].1, Warning::Churn { readds: 4 })); - } - } - let _ = std::fs::remove_dir_all(&dir); - } - - #[cfg(feature = "world")] - #[test] - fn the_server_ceiling_is_the_named_list_or_the_whole_catalog() { - assert_eq!( - allowed_caps(None).unwrap(), - crate::world_caps::catalog_names() - ); - let named = ["time.now".to_owned(), "chat.say".to_owned()]; - assert_eq!( - allowed_caps(Some(&named)) - .unwrap() - .into_iter() - .collect::>(), - vec!["chat.say".to_owned(), "time.now".to_owned()] - ); - assert!(allowed_caps(Some(&["*".to_owned()])).is_err()); - assert!(allowed_caps(Some(&["telepathy".to_owned()])).is_err()); - } - - #[test] - fn world_mode_requires_an_admin_token_but_not_web() { - assert!(validate_world_options(true, None, None, "lobby", "deny", false).is_err()); - assert!(validate_world_options(true, Some(""), None, "lobby", "deny", false).is_err()); - assert!(validate_world_options(true, Some("admin"), None, "lobby", "deny", false).is_ok()); - assert!(validate_world_options(false, None, None, "lobby", "deny", false).is_ok()); - assert!( - validate_world_options( - true, - Some("admin"), - Some(&PathBuf::from("world.wasm")), - "lobby", - "deny", - false - ) - .is_ok() - ); - assert!(validate_world_options(true, Some("admin"), None, "lobby", "deny", true).is_ok()); - assert!( - validate_world_options( - true, - Some("admin"), - Some(&PathBuf::from("world.wasm")), - "lobby", - "deny", - true - ) - .is_err() - ); - assert!( - validate_world_options( - false, - None, - Some(&PathBuf::from("world.wasm")), - "lobby", - "deny", - false - ) - .is_err() - ); - } - - #[cfg(feature = "world")] - #[test] - fn mail_sink_picks_one_transport_and_refuses_an_unusable_relay() { - let loopback: SocketAddr = "127.0.0.1:25".parse().unwrap(); - let remote: SocketAddr = "203.0.113.5:25".parse().unwrap(); - let sender = Some("id@example.test".to_owned()); - assert!(mail_sink(None, None, None, None).unwrap().is_none()); - assert!(mail_sink(None, None, Some(loopback), None).is_err()); - assert!(mail_sink(None, None, Some(remote), sender.clone()).is_err()); - assert!( - mail_sink(None, None, Some(loopback), sender) - .unwrap() - .is_some() - ); - } - - #[test] - fn world_names_are_bounded_and_are_a_single_path_segment() { - for bad in [ - "", - "../evil", - ".", - "..", - "Tic-Tac-Toe", - "a/b", - "sp ace", - "wörld", - ] { - assert!( - validate_world_options(true, Some("admin"), None, bad, "deny", false).is_err(), - "{bad:?} must be refused" - ); - } - assert!(validate_world_options(true, Some("admin"), None, "tt-2_x", "deny", false).is_ok()); - assert!( - validate_world_options(true, Some("admin"), None, &"a".repeat(64), "deny", false) - .is_ok() - ); - assert!( - validate_world_options(true, Some("admin"), None, &"a".repeat(65), "deny", false) - .is_err() - ); - assert!(validate_world_options(true, Some("admin"), None, "lobby", "deny", false).is_ok()); - assert!( - validate_world_options(true, Some("admin"), None, "lobby", "grant-on-use", false) - .is_ok() - ); - assert!( - validate_world_options(true, Some("admin"), None, "lobby", "sometimes", false).is_err(), - "an unknown policy is refused" - ); - } - - #[test] - fn test_is_process_alive_current_process() { - let pid = std::process::id(); - assert!(is_process_alive(pid)); - } - - #[test] - fn test_is_process_alive_nonexistent() { - // Use a very high PID that's unlikely to exist - // Note: On non-Unix this always returns true - #[cfg(unix)] - { - assert!(!is_process_alive(999_999_999)); - } - } - - #[test] - fn test_is_process_alive_pid_1() { - // PID 1 exists in every Unix PID namespace (as init, or as the - // namespace's init in a container). #2384: when the test runs - // unprivileged, pid 1 is foreign-owned and kill(1, 0) fails with - // EPERM — that must still answer alive; as root the probe succeeds - // outright. Either way the assertion holds. - #[cfg(unix)] - { - assert!( - is_process_alive(1), - "pid 1 exists and must read as alive (EPERM is not death)" - ); - } - } - - #[test] - fn test_serve_info_struct() { - use iroh_base::SecretKey; - - let key = SecretKey::generate(); - let node_id = key.public(); - - let info = ServeInfo { - node_id: node_id.to_string(), - pid: 12345, - addrs: vec!["127.0.0.1:8080".to_owned(), "[::1]:8080".to_owned()], - web_port: Some(3000), - }; - - assert_eq!(info.node_id, node_id.to_string()); - assert_eq!(info.addrs.len(), 2); - assert_eq!(info.addrs[0], "127.0.0.1:8080"); - assert_eq!(info.pid, 12345); - assert_eq!(info.web_port, Some(3000)); - } - - #[test] - fn test_serve_info_clone() { - use iroh_base::SecretKey; - - let key = SecretKey::generate(); - let node_id = key.public(); - let info = ServeInfo { - node_id: node_id.to_string(), - pid: 99, - addrs: vec!["127.0.0.1:8080".to_owned()], - web_port: None, - }; - - let cloned = info.clone(); - assert_eq!(cloned.node_id, info.node_id); - assert_eq!(cloned.addrs, info.addrs); - assert_eq!(cloned.pid, info.pid); - assert_eq!(cloned.web_port, info.web_port); - } - - #[test] - fn test_serve_info_json_roundtrip() { - let info = ServeInfo { - node_id: "abc123".to_owned(), - pid: 42, - addrs: vec!["127.0.0.1:8080".to_owned(), "[::1]:9090".to_owned()], - web_port: Some(3001), - }; - - let json = serde_json::to_string(&info).unwrap(); - let parsed: ServeInfo = serde_json::from_str(&json).unwrap(); - assert_eq!(parsed.node_id, "abc123"); - assert_eq!(parsed.pid, 42); - assert_eq!(parsed.addrs.len(), 2); - assert_eq!(parsed.web_port, Some(3001)); - } - - #[test] - fn test_serve_info_json_no_web_port() { - let info = ServeInfo { - node_id: "def456".to_owned(), - pid: 100, - addrs: vec!["127.0.0.1:5555".to_owned()], - web_port: None, - }; - - let json = serde_json::to_string(&info).unwrap(); - let parsed: ServeInfo = serde_json::from_str(&json).unwrap(); - assert_eq!(parsed.web_port, None); - } - - // Integration tests for lock file functions require file system access - // and are tested via the integration test suite -} diff --git a/pkgs/id/src/local_events.rs b/pkgs/id/src/local_events.rs deleted file mode 100644 index c72ec77d6b..0000000000 --- a/pkgs/id/src/local_events.rs +++ /dev/null @@ -1,824 +0,0 @@ -//! Documents and tags, signed into the event store from one node (P6.7c). -//! -//! `id doc` and `id claim` act through [`LocalEvents`]. Each action signs one event with the node's -//! key, names every other author's head as its `after`, and ingests the event with -//! [`EventStore::ingest`], the path sync uses. The store checks the signature and applies the event. -//! So these events are signed, unlike the group log's (P6.7a), which trusts the caller's name. -//! -//! The CLI opens one store directory, named by `--event-store`, and nodes on one machine that -//! share the directory see each other's events, as they share the group log. Between machines, -//! `id serve` moves the events: it shares this store with the `/id-range-sync/1` range-sync sessions -//! in [`crate::event_sync`], so a revision one node signs into its store is in the sync set the -//! next session carries to a peer (#792). -//! -//! The reads walk every applied event, which is fine for the CLI and is not an index. The document -//! and tag rules are the ones in [`crate::documents`] and [`crate::tag_claims`]. - -use std::collections::{HashMap, HashSet}; -use std::path::Path; -use std::time::{SystemTime, UNIX_EPOCH}; - -use anyhow::{Context, Result, bail}; -use p2panda_core::{Hash, SigningKey}; - -use crate::chain::{ChainExt, Event, MAX_AFTER, sign}; -use crate::documents::{DOCUMENT_KIND, DocumentRef, REMOVAL_KIND}; -use crate::event_store::{EventStore, Ingest, StoreError}; -use crate::search::{Hit, ValueMatch, search_store}; -use crate::tag_claims::{CLEAR_KIND, Claim, MAX_CLEAR_CLAIMS, SET_KIND, TagOp, check_op}; -use crate::waiting::{AuthorKey, WaitingLimits}; - -/// The directory the event store lives in, under the data directory, unless `--event-store` names -/// another. -pub const DIR_NAME: &str = "events"; - -/// One event that is part of a document's history, as the CLI lists it. -#[derive(Clone, Debug, PartialEq, Eq)] -pub enum Entry { - /// The `document.put` that makes the document. Its ID is the document's. - Document { - /// The event's ID. - id: Hash, - /// The key that signed it. - author: AuthorKey, - /// The content the event names. - document: DocumentRef, - }, - /// A `tag.set` on `subject`. - Set { - /// The event's ID, which is the claim's. - id: Hash, - /// The key that signed it. - author: AuthorKey, - /// The event the claim is about. - subject: Hash, - /// The tag name. - name: String, - /// The tag value, if any. - value: Option, - }, - /// A `tag.clear` that names the claims it removes. - Clear { - /// The event's ID. - id: Hash, - /// The key that signed it. - author: AuthorKey, - /// The claims it names. - claims: Vec, - }, - /// A `document.remove` of the document it names. - Remove { - /// The event's ID. - id: Hash, - /// The key that signed it. - author: AuthorKey, - /// The document it removes. - document: Hash, - }, -} - -impl Entry { - /// The event's ID. - #[must_use] - pub const fn id(&self) -> Hash { - match self { - Self::Document { id, .. } - | Self::Set { id, .. } - | Self::Clear { id, .. } - | Self::Remove { id, .. } => *id, - } - } - - /// The key that signed the event. - #[must_use] - pub const fn author(&self) -> AuthorKey { - match self { - Self::Document { author, .. } - | Self::Set { author, .. } - | Self::Clear { author, .. } - | Self::Remove { author, .. } => *author, - } - } - - /// The event's kind, as its header names it. - #[must_use] - pub const fn kind(&self) -> &'static str { - match self { - Self::Document { .. } => DOCUMENT_KIND, - Self::Set { .. } => SET_KIND, - Self::Clear { .. } => CLEAR_KIND, - Self::Remove { .. } => REMOVAL_KIND, - } - } -} - -/// The latest applied event of one author: the head of its chain. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub struct Head { - /// The author. - pub author: AuthorKey, - /// The author's last applied event. - pub event: Hash, - /// That event's sequence number, counted from 0. - pub seq: u64, -} - -/// A published document: its `document.put`'s ID, the reference that event names, and the IDs of -/// the tag claims set with it, in the order the tags were given. -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct Published { - /// The document's ID: the `document.put` event's ID. - pub id: Hash, - /// The content the document names. - pub document: DocumentRef, - /// The IDs of the claims set with the document, one per tag. - pub claims: Vec, -} - -/// Every applied event's entry by ID, and every applied event's parents by ID. -type Log = (HashMap, HashMap>); - -/// The event store, and the key the node signs its events with. -#[derive(Debug)] -pub struct LocalEvents { - store: EventStore, - key: SigningKey, -} - -impl LocalEvents { - /// Opens the store in `dir`, creating it if it does not exist. Events are signed with `key`. - /// - /// # Errors - /// - /// Fails if the store cannot be opened, for example while another process has it open. - /// The blob references in this node's event store, for the blob gate's index - /// (`EventStore::document_references`). - /// - /// # Errors - /// - /// Returns a store error if the read fails. - pub fn document_references( - &self, - ) -> Result)>, StoreError> { - self.store.document_references() - } - - pub fn open(dir: &Path, key: SigningKey) -> Result { - std::fs::create_dir_all(dir).with_context(|| format!("create {}", dir.display()))?; - let store = EventStore::open(dir, WaitingLimits::default(), now_ms())?; - Ok(Self { store, key }) - } - - /// Runs one range-sync session over `conn` against this node's store: the session - /// [`crate::event_store::sync::sync_over`] drives, with this store as its sync set. - /// `initiator` is the side that dialed. Every event that arrives is decided by the - /// store's own ingest, so a tampered or unsigned event is refused, never applied. - /// - /// # Errors - /// - /// Returns an error if the peer breaks the protocol, the session passes `deadline`, - /// `gate` refuses the peer, or the store fails. - pub async fn sync_session( - &mut self, - conn: &iroh::endpoint::Connection, - initiator: bool, - deadline: std::time::Duration, - gate: &crate::pull_policy::PullGate, - ) -> Result { - crate::event_store::sync::sync_over( - &mut self.store, - conn, - initiator, - crate::event_store::range::Params::default(), - now_ms(), - deadline, - gate, - ) - .await - } - - /// The account the node's events are signed as. - #[must_use] - pub fn author(&self) -> AuthorKey { - *self.key.verifying_key().as_bytes() - } - - /// Publishes `content` as a document of `media_type`, with a tag for each of `tags`. The event - /// names the content by its BLAKE3 hash and size. The bytes are not kept here: they are a blob. - /// Every tag is checked before anything is recorded, so a bad tag records nothing. - /// - /// # Errors - /// - /// Fails if the media type or a tag is refused, or the store cannot record the events. - pub fn publish( - &mut self, - media_type: &str, - content: &[u8], - tags: &[(String, Option)], - ) -> Result { - let document = DocumentRef::for_bytes(media_type, content)?; - for (name, value) in tags { - check_tag(name, value.as_deref())?; - } - let id = self.record(DOCUMENT_KIND, None, Some(document.clone()), None, &[])?; - let mut claims = Vec::with_capacity(tags.len()); - for (name, value) in tags { - claims.push(self.set_tag(id, name, value.as_deref())?); - } - Ok(Published { - id, - document, - claims, - }) - } - - /// Sets the tag `name` on `subject`, with `value` if given. The new claim's ID is the event's. - /// - /// # Errors - /// - /// Fails if the name or value is refused, or the store cannot record the event. - pub fn set_tag(&mut self, subject: Hash, name: &str, value: Option<&str>) -> Result { - let op = TagOp::Set { - subject, - name: name.to_owned(), - value: value.map(str::to_owned), - }; - self.record(SET_KIND, Some(op), None, None, &[]) - } - - /// Clears every live claim named `name` on `subject`, whoever set it. Nothing to clear is an - /// error. - /// - /// One `tag.clear` event names at most [`MAX_CLEAR_CLAIMS`] claims, so a name with more live - /// claims than that is cleared by several events, in the order [`EventStore::tag_claims`] - /// returns the claims. The returned count is the total cleared across all of those events, - /// and the returned ID is the final event's — the one whose recording completes the clear. - /// - /// The events are append-only: if recording one of them fails, the ones already recorded - /// stay, the error is returned, and calling this again clears what is left. - /// - /// A claim is removed only when it sits in the clear's causal past, so each sub-clear - /// names the current head of every author whose claims it names as a required head of - /// its `after` frontier (see [`LocalEvents::bounded_after`]). When the claims span more - /// authors than the frontier cap ([`MAX_AFTER`]) or more claims than one clear may name - /// ([`MAX_CLEAR_CLAIMS`]), the clear is split: several `tag.clear` events are recorded, - /// partitioning the claims by author into groups that fit both caps, in author order. - /// The returned count is the total across all sub-clears, and the returned event ID is - /// the last sub-clear's -- the one after which every named claim is cleared. - /// - /// # Errors - /// - /// Fails if no live claim matches, or the store cannot record an event. - pub fn clear_tag(&mut self, subject: Hash, name: &str) -> Result<(usize, Hash)> { - let claims: Vec = self - .store - .tag_claims()? - .into_iter() - .filter(|claim| claim.subject == subject && claim.name == name) - .collect(); - if claims.is_empty() { - bail!("no live claim on {} is named {name}", subject.to_hex()); - } - let count = claims.len(); - // The current head of each author, for the required tier of each sub-clear. - let heads: HashMap = self - .frontier()? - .into_iter() - .map(|head| (head.author, head.event)) - .collect(); - // Partition the claims by author into groups fitting both caps, in author order. - let mut by_author: HashMap> = HashMap::new(); - for claim in claims { - by_author.entry(claim.author).or_default().push(claim); - } - let mut authors: Vec = by_author.keys().copied().collect(); - authors.sort_unstable(); - let mut groups: Vec> = Vec::new(); - let mut group: Vec = Vec::new(); - let mut group_authors = 0usize; - for author in authors { - let authored = by_author.remove(&author).unwrap_or_default(); - // One author alone can hold more claims than a single clear may - // name (#1720), so pack each author's claims in cap-sized segments. - for segment in authored.chunks(MAX_CLEAR_CLAIMS) { - if !group.is_empty() - && (group_authors == MAX_AFTER - || group.len() + segment.len() > MAX_CLEAR_CLAIMS) - { - groups.push(std::mem::take(&mut group)); - group_authors = 0; - } - group_authors += 1; - group.extend(segment.iter().cloned()); - } - } - if !group.is_empty() { - groups.push(group); - } - let mut last = None; - for group in groups { - let mut required: Vec = Vec::new(); - let mut seen: HashSet = HashSet::new(); - for claim in &group { - if seen.insert(claim.author) { - if let Some(head) = heads.get(&claim.author) { - required.push(*head); - } - } - } - let ids: Vec = group.iter().map(|claim| claim.id).collect(); - last = Some(self.record( - CLEAR_KIND, - Some(TagOp::Clear { claims: ids }), - None, - None, - &required, - )?); - } - let event = last.context("a clear with claims records at least one event")?; - Ok((count, event)) - } - - /// The live claims on `subject`, sorted by claim ID. - /// - /// # Errors - /// - /// Fails if the store cannot be read. - pub fn tags_on(&self, subject: Hash) -> Result> { - Ok(self - .store - .tag_claims()? - .into_iter() - .filter(|claim| claim.subject == subject) - .collect()) - } - - /// The live claims that match `name`, and `value` if given, as [`crate::search`] returns them. - /// - /// # Errors - /// - /// Fails if the store cannot be read. - pub fn search(&self, name: &str, value: Option<&str>) -> Result> { - let matching = value.map_or(ValueMatch::Any, ValueMatch::Exact); - Ok(search_store(&self.store, name, matching)?) - } - - /// The head of each author's chain, in author order. - /// - /// # Errors - /// - /// Fails if the store cannot be read. - pub fn frontier(&self) -> Result> { - Ok(self - .store - .chains()? - .into_iter() - .filter_map(|(author, chain)| { - chain.head.map(|event| Head { - author, - event, - seq: u64::from(chain.next_seq).saturating_sub(1), - }) - }) - .collect()) - } - - /// The events on `document` other than its `document.put`: the tags set on it, the clears of - /// those tags, and any removal. They are in causal order. - /// - /// # Errors - /// - /// Fails if `document` is not a document, or the store cannot be read. - pub fn events_on(&self, document: Hash) -> Result> { - Ok(self - .history(document)? - .into_iter() - .filter(|entry| !matches!(entry, Entry::Document { .. })) - .collect()) - } - - /// The document's events in causal order: its `document.put` first, then the events of - /// [`LocalEvents::events_on`]. Each event comes after the events it names as its causes. - /// - /// # Errors - /// - /// Fails if `document` is not the ID of a `document.put`, or the store cannot be read. - pub fn history(&self, document: Hash) -> Result> { - let (entries, parents) = self.log()?; - if !matches!(entries.get(&document), Some(Entry::Document { .. })) { - bail!( - "{} is not a document: no document.put has that event ID", - document.to_hex() - ); - } - let order = causal_order(&parents); - // The claims set on this document. A clear of any of them belongs to the document too. - let claims_on: HashSet = order - .iter() - .filter_map(|id| match entries.get(id) { - Some(Entry::Set { subject, .. }) if *subject == document => Some(*id), - _ => None, - }) - .collect(); - Ok(order - .iter() - .filter_map(|id| entries.get(id)) - .filter(|entry| match entry { - Entry::Document { id, .. } => *id == document, - Entry::Set { subject, .. } => *subject == document, - Entry::Clear { claims, .. } => claims.iter().any(|claim| claims_on.contains(claim)), - Entry::Remove { - document: removed, .. - } => *removed == document, - }) - .cloned() - .collect()) - } - - /// Every applied event: its entry if it is a document or tag event, and its parents, which are - /// its `after` and its backlink. - fn log(&self) -> Result { - let mut entries = HashMap::new(); - let mut parents = HashMap::new(); - for (author, _) in self.store.chains()? { - for event in self.store.applied_events(&author, None, None, usize::MAX)? { - parents.insert(event.id, parents_of(&event)); - if let Some(entry) = entry_of(&event) { - entries.insert(event.id, entry); - } - } - } - Ok((entries, parents)) - } - - /// The heads of the other authors, which a new event names as its `after`. The node's own head - /// is the new event's backlink, so it is not named twice. - fn other_heads(&self) -> Result> { - let author = self.author(); - Ok(self - .frontier()? - .into_iter() - .filter(|head| head.author != author) - .map(|head| head.event) - .collect()) - } - - /// The `after` frontier for a new event: a dependency frontier, not an author census - /// (#1736). `after` is capped at [`MAX_AFTER`] hashes by the wire format, and events naming - /// more are refused by every existing node, so the frontier must fit the cap no matter how - /// many authors the store holds. - /// - /// When every other author's head fits (the common case), all of them are named, in - /// frontier order, exactly as before. Past the cap, the frontier is built in two tiers: - /// first the `required` heads -- for a `tag.clear`, the current head of each author of a - /// named claim, because a claim is removed only when it sits in the clear's causal past, - /// which the author's head in `after` guarantees through that author's backlink chain -- - /// then the remaining slots fill with the other authors' heads in frontier order. - /// Heads past the cap are simply not named: the events they head stay in the store, and - /// naming a head is about causal past, not about membership, so a later event loses - /// nothing but the claim of having seen them. - fn bounded_after(&self, required: &[Hash]) -> Result> { - let heads = self.other_heads()?; - if heads.len() <= MAX_AFTER { - return Ok(heads); - } - let current: HashSet = heads.iter().copied().collect(); - let mut after: Vec = Vec::with_capacity(MAX_AFTER); - let mut named: HashSet = HashSet::new(); - for head in required { - if after.len() == MAX_AFTER { - break; - } - if current.contains(head) && named.insert(*head) { - after.push(*head); - } - } - for head in heads { - if after.len() == MAX_AFTER { - break; - } - if named.insert(head) { - after.push(head); - } - } - Ok(after) - } - - /// Signs one event with the node's key, after a bounded frontier of the other authors' - /// heads (see [`LocalEvents::bounded_after`]), and ingests it. `required` names heads the - /// frontier must include when it is capped; other kinds than `tag.clear` require none. - /// The store must apply it, or the call fails. - fn record( - &mut self, - kind: &str, - tag: Option, - document: Option, - removes: Option, - required: &[Hash], - ) -> Result { - let author = self.author(); - let after = self.bounded_after(required)?; - let chain = self.store.chain(&author)?.unwrap_or_default(); - let ext = ChainExt { - kind: kind.to_owned(), - group: None, - after, - tag, - document, - removes, - }; - let event = sign(&self.key, chain.next_seq, chain.head, None, ext)?; - match self.store.ingest(&event.bytes, now_ms())? { - Ingest::Accepted { id, .. } => Ok(id), - refused => bail!("the store did not apply the {kind} event: {refused:?}"), - } - } -} - -/// Checks a tag's name and value as the store will, before anything is signed. The subject is not -/// part of the check, so a placeholder stands in for it. -fn check_tag(name: &str, value: Option<&str>) -> Result<()> { - let op = TagOp::Set { - subject: Hash::from_bytes([0; 32]), - name: name.to_owned(), - value: value.map(str::to_owned), - }; - check_op(SET_KIND, &op)?; - Ok(()) -} - -/// The entry of a document or tag event, or `None` for any other event. -fn entry_of(event: &Event) -> Option { - let id = event.id; - let author = *event.header.verifying_key.as_bytes(); - let ext = &event.header.extensions; - match (ext.kind.as_str(), &ext.tag, &ext.document, ext.removes) { - (DOCUMENT_KIND, _, Some(document), _) => Some(Entry::Document { - id, - author, - document: document.clone(), - }), - ( - SET_KIND, - Some(TagOp::Set { - subject, - name, - value, - }), - _, - _, - ) => Some(Entry::Set { - id, - author, - subject: *subject, - name: name.clone(), - value: value.clone(), - }), - (CLEAR_KIND, Some(TagOp::Clear { claims }), _, _) => Some(Entry::Clear { - id, - author, - claims: claims.clone(), - }), - (REMOVAL_KIND, _, _, Some(document)) => Some(Entry::Remove { - id, - author, - document, - }), - _ => None, - } -} - -/// The events an event names as its causes: its `after` hashes and its backlink. -fn parents_of(event: &Event) -> Vec { - let mut named = event.header.extensions.after.clone(); - named.extend(event.header.backlink); - named -} - -/// Every event, each after the events it names. The walk starts from the lowest ID and visits -/// parents in ID order, so the order is the same whatever order the events were stored in. -fn causal_order(parents: &HashMap>) -> Vec { - let mut roots: Vec = parents.keys().copied().collect(); - roots.sort_by_key(|id| *id.as_bytes()); - let mut visited: HashSet = HashSet::new(); - let mut order = Vec::with_capacity(parents.len()); - for root in roots { - let mut stack = vec![(root, false)]; - while let Some((id, expanded)) = stack.pop() { - if expanded { - order.push(id); - continue; - } - if !visited.insert(id) { - continue; - } - stack.push((id, true)); - let mut named = parents.get(&id).cloned().unwrap_or_default(); - named.sort_by_key(|parent| *parent.as_bytes()); - // Pushed in reverse, so the lowest ID is popped, and so expanded, first. - for parent in named.into_iter().rev() { - if !visited.contains(&parent) { - stack.push((parent, false)); - } - } - } - } - order -} - -/// The wall clock in milliseconds, for the store's waiting limits. -fn now_ms() -> u64 { - SystemTime::now() - .duration_since(UNIX_EPOCH) - .ok() - .and_then(|elapsed| u64::try_from(elapsed.as_millis()).ok()) - .unwrap_or(0) -} - -#[cfg(test)] -#[allow(clippy::unwrap_used, clippy::expect_used)] -mod tests { - use super::*; - - fn id(byte: u8) -> Hash { - Hash::from_bytes([byte; 32]) - } - - fn key(byte: u8) -> SigningKey { - SigningKey::from_bytes(&[byte; 32]) - } - - /// Opens a one-shot node for foreign author `byte` in the shared store - /// and has it set one claim named `name` on `subject`. - fn foreign_claim(dir: &Path, byte: u8, subject: Hash, name: &str) { - let mut events = LocalEvents::open(dir, key(byte)).unwrap(); - events.set_tag(subject, name, Some("x")).unwrap(); - } - - #[test] - fn test_record_still_works_with_more_authors_than_the_after_cap() { - // Regression for #1736: with 33+ other authors in the store, the - // uncapped frontier made every record() fail validation, so the - // node could never write again. - for foreign in [33u8, 100] { - let dir = tempfile::TempDir::new().unwrap(); - let subject = id(200); - for byte in 1..=foreign { - foreign_claim(dir.path(), byte, subject, "topic"); - } - let mut events = LocalEvents::open(dir.path(), key(0)).unwrap(); - let published = events.publish("text/plain", b"hello", &[]).unwrap(); - events.set_tag(published.id, "topic", Some("mine")).unwrap(); - let (cleared, _) = events.clear_tag(published.id, "topic").unwrap(); - assert_eq!(cleared, 1); - } - } - - #[test] - fn test_clear_spanning_more_authors_than_the_cap_clears_exactly_its_claims() { - // Regression for #1736: 40 authors hold a claim named "topic" on the - // subject -- more distinct authors than MAX_AFTER, so the clear must - // split by author. Exactly those claims are removed: a claim with a - // different name on the same subject, and a same-name claim on a - // different subject, both survive. - let dir = tempfile::TempDir::new().unwrap(); - let subject = id(201); - let other_subject = id(202); - for byte in 1..=40u8 { - foreign_claim(dir.path(), byte, subject, "topic"); - } - foreign_claim(dir.path(), 1, subject, "other"); - foreign_claim(dir.path(), 2, other_subject, "topic"); - let mut events = LocalEvents::open(dir.path(), key(0)).unwrap(); - let (cleared, _) = events.clear_tag(subject, "topic").unwrap(); - assert_eq!(cleared, 40); - let remaining = events.tags_on(subject).unwrap(); - assert_eq!(remaining.len(), 1); - assert_eq!(remaining[0].name, "other"); - assert_eq!(events.tags_on(other_subject).unwrap().len(), 1); - } - - #[test] - fn test_causal_order_puts_every_event_after_its_parents() { - // 1 and 2 are roots. 3 names 1, and 4 names 3 and 2. 5 names nothing it did not see. - let parents = HashMap::from([ - (id(1), Vec::new()), - (id(2), Vec::new()), - (id(3), vec![id(1)]), - (id(4), vec![id(3), id(2)]), - (id(5), Vec::new()), - ]); - let order = causal_order(&parents); - assert_eq!(order.len(), 5); - let position = |event: Hash| order.iter().position(|&found| found == event).unwrap(); - assert!(position(id(1)) < position(id(3))); - assert!(position(id(3)) < position(id(4))); - assert!(position(id(2)) < position(id(4))); - // The same events in another map give the same order. - assert_eq!(causal_order(&parents), order); - } - - #[test] - fn test_a_tag_that_the_store_would_refuse_is_refused_before_publish() { - assert!(check_tag("topic", Some("plans")).is_ok()); - assert!(check_tag("", None).is_err()); - assert!(check_tag("e\u{301}", None).is_err()); - } - - fn open_events() -> (tempfile::TempDir, LocalEvents) { - let dir = tempfile::tempdir().unwrap(); - let events = LocalEvents::open(dir.path(), SigningKey::from_bytes(&[7; 32])).unwrap(); - (dir, events) - } - - fn publish_subject(events: &mut LocalEvents) -> Hash { - events.publish("text/plain", b"hello", &[]).unwrap().id - } - - fn set_claims(events: &mut LocalEvents, subject: Hash, name: &str, count: usize) { - for i in 0..count { - events.set_tag(subject, name, Some(&i.to_string())).unwrap(); - } - } - - fn clear_chunks(events: &LocalEvents, subject: Hash) -> Vec<(Hash, usize)> { - events - .events_on(subject) - .unwrap() - .into_iter() - .filter_map(|entry| match entry { - Entry::Clear { id, claims, .. } => Some((id, claims.len())), - _ => None, - }) - .collect() - } - - #[test] - fn test_clear_tag_chunks_a_clear_over_the_claim_cap() { - // Regression for #1720: a name with more live claims than one tag.clear - // may name (MAX_CLEAR_CLAIMS) could never be cleared at all. - let (_dir, mut events) = open_events(); - let subject = publish_subject(&mut events); - let other_subject = publish_subject(&mut events); - set_claims(&mut events, subject, "topic", MAX_CLEAR_CLAIMS + 1); - events.set_tag(subject, "keep", None).unwrap(); - events.set_tag(other_subject, "topic", None).unwrap(); - - let (count, event) = events.clear_tag(subject, "topic").unwrap(); - - assert_eq!(count, MAX_CLEAR_CLAIMS + 1); - let chunks = clear_chunks(&events, subject); - assert_eq!( - chunks.iter().map(|(_, size)| *size).collect::>(), - vec![MAX_CLEAR_CLAIMS, 1] - ); - // The returned ID is the final chunk's, the one that completes the clear. - assert_eq!(chunks.last().unwrap().0, event); - assert!( - events - .tags_on(subject) - .unwrap() - .iter() - .all(|claim| claim.name != "topic") - ); - // Other names, and the same name on other subjects, are untouched. - assert_eq!(events.tags_on(subject).unwrap().len(), 1); - assert_eq!(events.tags_on(other_subject).unwrap().len(), 1); - } - - #[test] - fn test_clear_tag_chunks_600_claims_into_three_events() { - let (_dir, mut events) = open_events(); - let subject = publish_subject(&mut events); - set_claims(&mut events, subject, "topic", 600); - - let (count, event) = events.clear_tag(subject, "topic").unwrap(); - - assert_eq!(count, 600); - let chunks = clear_chunks(&events, subject); - assert_eq!( - chunks.iter().map(|(_, size)| *size).collect::>(), - vec![ - MAX_CLEAR_CLAIMS, - MAX_CLEAR_CLAIMS, - 600 - 2 * MAX_CLEAR_CLAIMS - ] - ); - assert_eq!(chunks.last().unwrap().0, event); - assert!(events.tags_on(subject).unwrap().is_empty()); - } - - #[test] - fn test_clear_tag_at_or_under_the_cap_records_one_event() { - let (_dir, mut events) = open_events(); - let subject = publish_subject(&mut events); - set_claims(&mut events, subject, "topic", 3); - - let (count, event) = events.clear_tag(subject, "topic").unwrap(); - - assert_eq!(count, 3); - assert_eq!(clear_chunks(&events, subject), vec![(event, 3)]); - // Nothing left to clear is still an error. - assert!(events.clear_tag(subject, "topic").is_err()); - } -} From a08bc4f33e5ad5e1b487c09f19ad12fa109d764c Mon Sep 17 00:00:00 2001 From: repo-worker-tmp-code-b Date: Fri, 13 Nov 2026 22:46:55 -0600 Subject: [PATCH 7/8] Fix serve port against current main APIs (#173): drop the shadowed pre-abuse MetaProtocol construction, pass the resolved groups log path to build_blob_gate --- pkgs/id/crates/id-cli/src/commands/serve.rs | 11 +---------- 1 file changed, 1 insertion(+), 10 deletions(-) diff --git a/pkgs/id/crates/id-cli/src/commands/serve.rs b/pkgs/id/crates/id-cli/src/commands/serve.rs index 9cd65cc5d9..7d3cece971 100644 --- a/pkgs/id/crates/id-cli/src/commands/serve.rs +++ b/pkgs/id/crates/id-cli/src/commands/serve.rs @@ -1689,7 +1689,7 @@ pub async fn cmd_serve(opts: ServeOptions) -> Result<()> { let folded = build_blob_gate( events, &store_handle, - &serve_groups_log_path(groups_log.clone()), + &groups_log, ) .await; Some(Arc::new(id_worlds::blob_gate::RefreshingWorlds::new(folded))) @@ -1705,15 +1705,6 @@ pub async fn cmd_serve(opts: ServeOptions) -> Result<()> { ); } - // Build router — gossip ALPN is always registered (needed by iroh-docs), - // but peer discovery gossip topic only joins when gossip is enabled - let meta = MetaProtocol::new( - &store_handle, - Some(peer_discovery.clone()), - Arc::clone(&tag_store), - access.clone(), - node_id, - ); // iroh-blobs rejects pushes unless an event handler enables them; this one // allows them only from nodes the access policy lets write. With the blob // gate built, the gate's handler decides pushes the same way and also From af6e05746d53b1ad22a25ac57793a343b07371f8 Mon Sep 17 00:00:00 2001 From: repo-worker-tmp-code-b Date: Fri, 13 Nov 2026 23:02:51 -0600 Subject: [PATCH 8/8] rustfmt the ported blob gate files (#173) --- pkgs/id/crates/id-cli/src/commands/serve.rs | 22 +++++------ pkgs/id/crates/id-cli/src/local.rs | 4 +- pkgs/id/crates/id-groups/src/blob_gate.rs | 44 ++++++++++----------- 3 files changed, 35 insertions(+), 35 deletions(-) diff --git a/pkgs/id/crates/id-cli/src/commands/serve.rs b/pkgs/id/crates/id-cli/src/commands/serve.rs index 7d3cece971..fc0992f16e 100644 --- a/pkgs/id/crates/id-cli/src/commands/serve.rs +++ b/pkgs/id/crates/id-cli/src/commands/serve.rs @@ -1367,9 +1367,9 @@ async fn build_blob_gate( children.insert(hash, kids); } } - let named = references - .into_iter() - .filter_map(|(hash, group)| group.map(|group| (hash, id_worlds::blob_gate::world_key(&group)))); + let named = references.into_iter().filter_map(|(hash, group)| { + group.map(|group| (hash, id_worlds::blob_gate::world_key(&group))) + }); let index = id_groups::blob_gate::build_reference_index(named, |hash| { children.get(hash).cloned().unwrap_or_default() }); @@ -1377,7 +1377,10 @@ async fn build_blob_gate( Some(projection) => { id_worlds::blob_gate::FoldedWorlds::from_group_projection(projection, index) } - None => id_worlds::blob_gate::FoldedWorlds::new(id_worlds::groups::worlds::Worlds::empty(), index), + None => id_worlds::blob_gate::FoldedWorlds::new( + id_worlds::groups::worlds::Worlds::empty(), + index, + ), } } @@ -1686,13 +1689,10 @@ pub async fn cmd_serve(opts: ServeOptions) -> Result<()> { #[cfg(feature = "web")] let blob_gate: Option> = match &event_events { Some(events) => { - let folded = build_blob_gate( - events, - &store_handle, - &groups_log, - ) - .await; - Some(Arc::new(id_worlds::blob_gate::RefreshingWorlds::new(folded))) + let folded = build_blob_gate(events, &store_handle, &groups_log).await; + Some(Arc::new(id_worlds::blob_gate::RefreshingWorlds::new( + folded, + ))) } None => None, }; diff --git a/pkgs/id/crates/id-cli/src/local.rs b/pkgs/id/crates/id-cli/src/local.rs index c8c1bff712..56083b826d 100644 --- a/pkgs/id/crates/id-cli/src/local.rs +++ b/pkgs/id/crates/id-cli/src/local.rs @@ -32,12 +32,12 @@ use iroh_gossip::net::Gossip; use crate::protocol::{MetaProtocol, MetaRequest, MetaResponse}; use id_core::access::AccessPolicy; -use id_groups::blob_gate::BlobPolicy; -use id_worlds::blob_gate::RefreshingWorlds; use id_core::access::blobs_events; +use id_groups::blob_gate::BlobPolicy; use id_store::store::{StoreType, load_or_create_keypair, open_store}; use id_store::tags::TagStore; use id_sync::fileops::FileOps; +use id_worlds::blob_gate::RefreshingWorlds; use crate::{KEY_FILE, META_ALPN, STORE_PATH}; diff --git a/pkgs/id/crates/id-groups/src/blob_gate.rs b/pkgs/id/crates/id-groups/src/blob_gate.rs index 6763a510e3..00bfe8606a 100644 --- a/pkgs/id/crates/id-groups/src/blob_gate.rs +++ b/pkgs/id/crates/id-groups/src/blob_gate.rs @@ -296,13 +296,13 @@ pub fn blob_events_with_blocks( let verdict = admit(peers.get(&m.connection_id), |id| { local_readers.contains(id) || decide_with_blocks( - &*access, - &policy, - blocks.as_deref(), - id, - &m.request.hash, - Request::Fetch, - ) + &*access, + &policy, + blocks.as_deref(), + id, + &m.request.hash, + Request::Fetch, + ) }); let _ = m.tx.send(verdict).await; } @@ -311,14 +311,14 @@ pub fn blob_events_with_blocks( local_readers.contains(id) || m.request.hashes.iter().all(|hash| { decide_with_blocks( - &*access, - &policy, - blocks.as_deref(), - id, - hash, - Request::Fetch, - ) - }) + &*access, + &policy, + blocks.as_deref(), + id, + hash, + Request::Fetch, + ) + }) }); let _ = m.tx.send(verdict).await; } @@ -326,13 +326,13 @@ pub fn blob_events_with_blocks( let verdict = admit(peers.get(&m.connection_id), |id| { local_readers.contains(id) || decide_with_blocks( - &*access, - &policy, - blocks.as_deref(), - id, - &m.request.hash, - Request::Observe, - ) + &*access, + &policy, + blocks.as_deref(), + id, + &m.request.hash, + Request::Observe, + ) }); let _ = m.tx.send(verdict).await; }