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/commands/serve.rs b/pkgs/id/crates/id-cli/src/commands/serve.rs index dfdd33c4cd..7a05a8d451 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, +) -> 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, @@ -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,65 @@ 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(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" + ); + } + + // 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(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 +2317,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 +2328,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 +2378,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/lib.rs b/pkgs/id/crates/id-cli/src/lib.rs index d8319ec05e..1399b5ccbb 100644 --- a/pkgs/id/crates/id-cli/src/lib.rs +++ b/pkgs/id/crates/id-cli/src/lib.rs @@ -14,6 +14,30 @@ use anyhow::Result; use std::path::PathBuf; pub mod aliases; + +/// The blob gate, at its historical in-crate path: a facade over the +/// split gate crates (`id_groups::blob_gate` for the verdicts and +/// provider wiring, `id_worlds::blob_gate` for the folded worlds). +pub mod blob_gate { + pub use id_groups::blob_gate::{ + BlobPolicy, Request, blob_events, blob_events_with_blocks, decide, decide_with_blocks, + decide_with_local, + }; + pub use id_worlds::blob_gate::{ + FoldedWorlds, RefreshingWorlds, build_reference_index, fold_group_events, hashseq_children, + world_key, + }; +} + +/// The groups bridge, at its historical in-crate path. +pub mod groups { + pub use id_worlds::groups::worlds; +} + +/// The node's local event store, at its historical in-crate path. +pub mod local_events { + pub use id_events::local_events::LocalEvents; +} pub mod app_manifest; pub mod chat_presence; pub mod cli; diff --git a/pkgs/id/crates/id-cli/src/local.rs b/pkgs/id/crates/id-cli/src/local.rs index 0a3e969454..0cdd69e4da 100644 --- a/pkgs/id/crates/id-cli/src/local.rs +++ b/pkgs/id/crates/id-cli/src/local.rs @@ -30,6 +30,7 @@ use iroh_blobs::{ALPN as BLOBS_ALPN, BlobsProtocol, api::Store}; use iroh_docs::protocol::Docs; use iroh_gossip::net::Gossip; +use crate::blob_gate::{BlobPolicy, RefreshingWorlds}; use crate::protocol::{MetaProtocol, MetaRequest, MetaResponse}; use id_core::access::AccessPolicy; use id_core::access::blobs_events; @@ -52,6 +53,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 { @@ -145,9 +148,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() @@ -205,7 +220,20 @@ impl LocalNode { 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, + std::collections::BTreeSet::from([self.node_id]), + )), + ), + 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-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..18c74a355f 100644 --- a/pkgs/id/crates/id-groups/src/blob_gate.rs +++ b/pkgs/id/crates/id-groups/src/blob_gate.rs @@ -15,15 +15,24 @@ //! 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`. +//! 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, + sync::{Arc, RwLock}, }; use iroh_base::EndpointId; @@ -142,6 +151,24 @@ 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 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 +183,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 +194,36 @@ 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) +} + +/// The serving verdict with every rule composed: an operator block +/// (a definite `Blocked` lookup) refuses everyone, local readers +/// included; a local reader not blocked is admitted for any hash; +/// everyone else is decided by [`decide_with_blocks`]. +fn decide_gated( + access: &A, + policy: &BlobPolicy, + blocks: Option<&dyn BlockList>, + local_readers: &BTreeSet, + requester: &EndpointId, + hash: &Hash, + request: Request, +) -> bool { + if let Some(blocks) = blocks { + if matches!( + blocks.peer_lookup(requester.as_bytes()), + BlockLookup::Blocked + ) { + return false; + } + } + if local_readers.contains(requester) { + return true; + } + decide_with_blocks(access, policy, blocks, requester, hash, request) } /// [`blob_events`], with the operator block list composed into every @@ -181,6 +237,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,10 +262,11 @@ pub fn blob_events_with_blocks( } ProviderMessage::GetRequestReceived(m) => { let verdict = admit(peers.get(&m.connection_id), |id| { - decide_with_blocks( + decide_gated( &*access, &policy, blocks.as_deref(), + &local_readers, id, &m.request.hash, Request::Fetch, @@ -219,10 +277,11 @@ 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( + decide_gated( &*access, &policy, blocks.as_deref(), + &local_readers, id, hash, Request::Fetch, @@ -233,10 +292,11 @@ pub fn blob_events_with_blocks( } ProviderMessage::ObserveRequestReceived(m) => { let verdict = admit(peers.get(&m.connection_id), |id| { - decide_with_blocks( + decide_gated( &*access, &policy, blocks.as_deref(), + &local_readers, id, &m.request.hash, Request::Observe, @@ -338,6 +398,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)); @@ -500,3 +597,24 @@ mod tests { } } } + +#[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]) + } +} diff --git a/pkgs/id/crates/id-worlds/src/blob_gate.rs b/pkgs/id/crates/id-worlds/src/blob_gate.rs index 85b2aaa6f8..cda9d4fd8c 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 +/// [`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,163 @@ 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 + }) +} + +/// 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() + } +} + #[cfg(test)] #[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] mod tests { @@ -172,4 +362,177 @@ mod tests { let p = BlobPolicy::default().with_observe(); assert!(decide(&g, &p, &id(2), &blob(9), 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))); + } + + use p2panda_core::Hash as PandaHash; + + #[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, + mode: crate::groups::RemoveMode::Revoke, + }), + }); + } + (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 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" + ); + let _ = BTreeMap::::new(); + } } 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..be7ee94d86 100644 --- a/pkgs/id/src/blob_gate.rs +++ b/pkgs/id/src/blob_gate.rs @@ -22,6 +22,7 @@ pub use id_groups::blob_gate::{ BlobPolicy, Request, blob_events, blob_events_with_blocks, decide, decide_with_blocks, + decide_with_local, }; /// The two questions the gate asks of the world graph, re-exported at @@ -30,4 +31,7 @@ pub use id_events::world_access::WorldAccess; /// [`WorldAccess`] over the folded worlds; the implementation lives /// in `id_worlds::blob_gate`. -pub use id_worlds::blob_gate::FoldedWorlds; +pub use id_worlds::blob_gate::{ + FoldedWorlds, RefreshingWorlds, build_reference_index, fold_group_events, hashseq_children, + world_key, +}; diff --git a/pkgs/id/tests/blob_gate.rs b/pkgs/id/tests/blob_gate.rs index c2ccea3d7d..b4cb19c2ae 100644 --- a/pkgs/id/tests/blob_gate.rs +++ b/pkgs/id/tests/blob_gate.rs @@ -92,6 +92,48 @@ 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])) + .bind() + .await + .unwrap(); + let addr = endpoint.addr(); + 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])) @@ -99,7 +141,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([]), local); let router = Router::builder(endpoint) .accept(iroh_blobs::ALPN, BlobsProtocol::new(store, Some(events))) .spawn(); @@ -177,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(); @@ -196,6 +270,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(); 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)))