Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
98 changes: 98 additions & 0 deletions doc/2026-11-13T09-00-00Z_design_blob_gate_authorization_wiring.md
Original file line number Diff line number Diff line change
@@ -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.
207 changes: 198 additions & 9 deletions pkgs/id/crates/id-cli/src/commands/serve.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<tokio::sync::Mutex<crate::local_events::LocalEvents>>,
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<iroh_blobs::Hash, Vec<iroh_blobs::Hash>> =
std::collections::HashMap::new();
let mut seen: std::collections::BTreeSet<iroh_blobs::Hash> = std::collections::BTreeSet::new();
let mut frontier: Vec<iroh_blobs::Hash> = 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,
Expand Down Expand Up @@ -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
Expand All @@ -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<Arc<crate::blob_gate::RefreshingWorlds>> = 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<Arc<crate::blob_gate::RefreshingWorlds>> = 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<EndpointId> =
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")]
Expand Down Expand Up @@ -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;
Expand All @@ -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?;
Expand Down Expand Up @@ -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?;
Expand Down
24 changes: 24 additions & 0 deletions pkgs/id/crates/id-cli/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
Loading