Skip to content

feat(cli): decdn gateway serves decdn: URIs to a browser with scoped, in-memory delegates - #2456

Merged
alpergundogdu merged 10 commits into
mainfrom
feat/decdn-gateway
Oct 14, 2026
Merged

alpergundogdu merged 10 commits into
mainfrom
feat/decdn-gateway

Conversation

@alpergundogdu

@alpergundogdu alpergundogdu commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

Builds on the DecdnUri parser from #2455 (merged).

Summary

decdn gateway is a loopback HTTP gateway that lets a browser open decdn: URIs, following the local-gateway pattern from iroh's global content discovery post: the browser stays an HTTP client and the gateway does native QUIC to nodes. It holds no sponsor or onramp knowledge: capabilities arrive through its own small API.

Content

GET /<hash>[/<path>][?ns=<id>] serves decdn:<hash>[/<path>][?ns=<id>]. A blob or bundle entry streams its verified bytes in order (entry Content-Type by extension via mime_guess, Content-Length from the manifest; HTML, SVG, XML and scripts served as text). A pull that fails before its first byte answers with its error status (402 for a funding stop, 502 otherwise); a later failure aborts the body. A bundle (/<hash>/) gets an HTML index. Parsed manifests sit in an LRU cache (16 entries, 64 MiB), and concurrent requests for a missing one pull and pay once. HEAD answers 405, since answering it would cost a paid pull.

Every content request needs x-decdn-token (the gateway token) and x-decdn-host (the page's host). The browser extension (decdn/browser-demo) adds both through declarativeNetRequest, so page scripts never see the token. The gateway pays with the registered capability whose scope covers the host: exact host, then *.<domain>, then *; between equal scopes, the token holder's own registration before a page's, then the earlier registration. A funding stop before the first byte retires the capability and the next covering one takes the request, so an empty pool costs a retry, not a failed load; a stop mid-body retires it too.

Capabilities

A caller is a page, by its http(s) Origin (still a page when the request also carries the token), or the token holder, from outside any page (no Origin, or an extension's). Origin: null is refused.

Endpoint Who Does
GET /_delegate a page (CORS) or the token holder Mints a fresh in-memory delegate key and returns its address. Every call returns a new address, so no site can follow the user across sites. The pages of one site (registrable domain by the Public Suffix List, so subdomains share it) hold at most 8 keys, pending or registered, and pages share a bound of 1024; the token holder mints outside both. Unclaimed keys drop after 15 min.
PUT /_capability {capability, scope} a page (CORS) or the token holder Registers a dcap1: capability issued to a minted delegate. Its owner signature must recover the on-chain owner of its pool on the gateway's deployment. A page's scope must cover its own host (example.com may register example.com, *.example.com or *, never another site) and may not be a wildcard over a public suffix (*.io, *.co.uk, *.github.io); the token holder registers any scope. One capability per delegate.
GET /_capability token only Lists registrations (no tokens).

Delegate keys live in memory only; a restart drops them and every capability issued to them. A capability a pull reports as FundingNeeded is retired: a page's is dropped, the token holder's stays listed as spent.

Security boundaries

  • Loopback-only listen (refuses anything else) and a Host check against DNS rebinding.
  • The token is 32 random bytes in <data-dir>/token (default ~/.decdn/gateway, owner-only), compared in constant time.
  • Only /_delegate and /_capability answer cross-origin (preflight allows GET, PUT, content-type, Chrome's private-network header); content and listing never do, so a page cannot read content responses or set the headers itself.
  • 64 KiB body limit on registration, 10 s header-read timeout. RPC errors returned to a page are redacted.
  • The buyer store lives in a temp dir under the data dir, removed when the gateway stops.
  • --keystore, --capability and --capability-file are refused: the gateway holds its own keys. A keystore password file (for example from DECDN_KEYSTORE_PASSWORD_FILE) is ignored.

The design follows the review: no onramp contract in decdn; the extension or a publisher's page does the sponsor handshake.

fetch refactor

fetch gains a Sink (Output = today's --output, Writer = a caller's AsyncWrite) and fetch_into takes an optional in-memory Credential { signer, grant } in place of the keystore and capability flags. Stdout and file behavior are unchanged. Each gateway pull runs on its own thread (the fetch future is not Send) and pipes into the response; pulls run one at a time.

Tested against Arbitrum Sepolia

  • Boundaries: no token / no host / wrong token → 401; no covering capability → 402; content preflight → 403; foreign Host → 403; listing without token → 401; malformed capability → 422; a capability for a delegate the gateway did not mint → 409; second capability on one delegate → 409; two GET /_delegate calls → different addresses.
  • Review fixes: a real sponsored capability passes the on-chain owner check and the same token with a tampered signature gets 422; GET /_delegate with no Origin or token → 403; a mint past a page's bound → 429 (unit tests cover the per-site bound across subdomains); decdn.org registering netflix.com → 403, with or without the token; HEAD → 405; startup with DECDN_KEYSTORE_PASSWORD_FILE set.
  • End to end: minted a delegate, the onramp issued a capability to it, registered it with scope *, and a request labelled example.com streamed a 4.6 MB PNG bundle entry (valid 2432×1440) in 4.7 s.
  • With the extension loaded in Chrome: the demo page's <img src="decdn:…"> and links rendered through the gateway.

Not in this PR

Checks

  • cargo nextest run -p decdn-cli gateway:: fetch::: 62 tests (manifest cache eviction, scope parsing and matching, upward registration, public-suffix wildcard refusal, caller rules, site derivation, per-site and page-wide delegate bounds, capability preference, on-chain owner match, funding classification, early pull errors, key-flag refusal, in-process HTTP routing for HEAD, minting and page registration, token match, token file, pruning, content types)
  • cargo clippy -p decdn-cli --all-targets --all-features

🤖 Generated with Claude Code

Comment thread crates/common/src/cli/gateway.rs Resolved
@alpergundogdu
alpergundogdu marked this pull request as draft October 13, 2026 19:02
@alpergundogdu alpergundogdu changed the title feat(cli): decdn gateway serves decdn: URIs to a browser over loopback HTTP feat(cli): decdn gateway serves decdn: URIs to a browser with scoped, in-memory delegates Oct 14, 2026
Base automatically changed from feat/decdn-uri to main October 14, 2026 09:31
alpergundogdu and others added 3 commits October 14, 2026 10:31
…pback HTTP

`GET /<hash>[/<path>][?ns=<id>]` serves the matching `decdn:` URI
(#2449): a blob or bundle entry streams its verified bytes in order, a
bundle gets an HTML index, and `/` shows the allowance. By default the
gateway pays like the onramp's decdn.sh: a throwaway key under
`<data-dir>/key` and the capability up.decdn.org issues to it after the
browser check; `--capability` pays from a held one instead.

Each request runs the `decdn fetch` streaming path into the HTTP
response through a new `fetch::Sink::Writer`, one pull at a time. It
listens on loopback only and checks `Host` against DNS rebinding.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The gateway no longer talks to any onramp. It mints a fresh in-memory
delegate key per `GET /_delegate`, so no two callers see the same
address, and drops one no capability claims within 15 minutes.
`PUT /_capability` registers a `dcap1:` capability for a minted
delegate with a scope: a page registers through CORS and its scope must
cover its own origin's host (`example.com` may register `example.com`,
`*.example.com` or `*`); the gateway token registers any scope.

Content requests need the gateway token and the page host
(`x-decdn-token`, `x-decdn-host`, which the browser extension adds) and
pay with the most specific covering capability. Only `/_delegate` and
`/_capability` answer cross-origin. The token lives owner-only in
`<data-dir>/token`; the buyer store lives in a directory removed when
the gateway stops. `fetch_into` takes an in-memory `Credential` in
place of the keystore and capability flags.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…est once

The manifest cache is an LRU of at most 16 parsed manifests within a
64 MiB budget (the newest entry stays even alone over it), holding each
behind an Arc so a hit no longer deep-copies it. A miss takes a fill
lock and checks again before pulling, so concurrent requests for one
manifest pull and pay once; hits never wait on the lock.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alpergundogdu
alpergundogdu marked this pull request as ready for review October 14, 2026 09:32
Copilot AI balanced review requested due to automatic review settings October 14, 2026 09:32

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

It introduces a large, network-facing HTTP gateway spanning payment delegation, delegate key custody, CORS/DNS-rebinding security boundaries, and custom thread/runtime management, which warrants human security review despite no concrete defect being found.

0 open findings

What changed in this PR

decdn gateway adds a loopback HTTP gateway so a browser (via the companion extension) can open decdn: URIs: it serves GET /<hash>[/<path>][?ns=<id>] by running the existing paid decdn fetch path and streaming verified bytes back as the HTTP body. It holds its own in-memory delegate keys and the capabilities registered to them (GET /_delegate, PUT /_capability, GET /_capability), paying with the capability whose scope best covers the page host. Security boundaries (loopback-only listen, DNS-rebinding Host check, constant-time token auth, CORS limited to the two capability endpoints, HTML/SVG served as text/plain) are implemented as described. To support this, fetch is refactored to expose fetch_into with a Sink (file/stdout vs. caller AsyncWrite) and an optional in-memory Credential, replacing the keystore/capability flags for programmatic callers.

Changes:

  • New commands/gateway.rs (+ GatewayArgs, CLI wiring, hyper/http-body-util/bytes deps): HTTP server, delegate/capability management, scope matching, manifest LRU cache, per-pull thread.
  • fetch.rs refactor: Sink, Credential, fetch_into, fetch_over/stream_out threading the sink through; copy_verified made ?Sized.
  • uri.rs parser and public-API snapshot (belongs to stacked #2455) plus CLAUDE.md/CLI-enum doc updates adding gateway.
File Description
crates/​cli/​src/​commands/​gateway.rs Main new gateway: HTTP handlers, delegate minting, capability registration/scoping, manifest cache, streaming pulls on dedicated threads
crates/​cli/​src/​commands/​gateway/​tests.rs Unit tests for cache eviction, scope parse/match, token file/compare, pruning, content types
crates/​cli/​src/​commands/​fetch.rs Extracts fetch_into/Sink/Credential; routes verified bytes to stdout or a caller writer
crates/​common/​src/​cli/​gateway.rs, mod.rs GatewayArgs and Command::Gateway wiring
crates/​cli/​src/​main.rs, commands/​mod.rs Dispatch and module registration
crates/​cli/​Cargo.toml, Cargo.lock Add hyper, hyper-util, http-body-util, bytes
crates/​client/​src/​uri.rs, uri/​tests.rs, lib.rs, snapshot DecdnUri parser (stacked #2455)
CLAUDE.md Adds gateway to the CLI command list

🧠 Review effort: Balanced


💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

The hand-kept extension table becomes mime_guess's. On top of the
guess, every text/* type and every type a browser runs or renders as a
document (XHTML, SVG, XML, JavaScript, ECMAScript) is served as
text/plain, so fetched content never runs on the gateway's origin.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@thiras thiras left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Requesting changes. The first two are correctness bugs that together disable the funding/fallback path (402 + mark_spent). Next come four security issues in capability registration that need a design decision on allowed scopes and what gets verified at registration. The last four are perf/UX.

  1. classify can't see FundingNeeded (context isn't downcastable from chain()) → no 402, no mark_spent
  2. A pull that fails before the first byte returns an empty 200 OK (EOF beats the error in the biased select)
  3. Unverified capabilities can shadow legitimate ones (no signature/deployment check + earliest-expiry tie-break)
  4. A page can register * / public-suffix wildcards and become the payer for other sites
  5. Unauthenticated GET /_delegate lets any page exhaust the global MAX_PENDING
  6. A valid token bypasses may_register even when a browser Origin is present
  7. One global pull slot with no wait timeout: a paused <video> blocks all other content
  8. Full endpoint/store/config bring-up per request
  9. HEAD starts a paid pull
  10. DECDN_KEYSTORE_PASSWORD_FILE in the env blocks decdn gateway startup

Details inline. Finding 1 was reproduced with a scratch program; the rest come from reading the code.

🤖 Generated with Claude Code

Comment thread crates/cli/src/commands/gateway.rs Resolved
Comment thread crates/cli/src/commands/gateway.rs Resolved
Comment thread crates/cli/src/commands/gateway.rs Resolved
Comment thread crates/cli/src/commands/gateway.rs Resolved
Comment thread crates/cli/src/commands/gateway.rs Resolved
Comment thread crates/cli/src/commands/gateway.rs Resolved
Comment thread crates/cli/src/commands/gateway.rs Resolved
Comment thread crates/cli/src/commands/gateway.rs Resolved
Comment thread crates/cli/src/commands/gateway.rs Resolved
Comment thread crates/cli/src/commands/gateway.rs Resolved
@github-code-quality

github-code-quality Bot commented Oct 14, 2026 •

Copy link
Copy Markdown

Code Coverage Overview

Languages: Rust

Rust / code-coverage/cargo-llvm-cov

The overall line coverage in commit a82668b in the feat/decdn-gateway branch remains at 75%, unchanged from commit 76d14e8 in the main branch.

Show a line coverage summary of the most impacted files.
File main 76d14e8 feat/decdn-gateway a82668b +/-
crates/node/src...s/client/mod.rs 90% 89% -1%
crates/cli/src/main.rs 77% 76% -1%
crates/client/src/lib.rs 88% 88% 0%
crates/cache/src/engine.rs 91% 91% 0%
crates/cli/src/...mmands/fetch.rs 50% 51% +1%
crates/cli/src/...ands/gateway.rs 0% 43% +43%

Updated October 14, 2026 12:38 UTC

alpergundogdu and others added 2 commits October 14, 2026 11:13
…ounds minting per caller

- A funding stop is found with `downcast_ref`, so a spent capability answers
  402 and the next covering scope takes over.
- A pull that fails before its first byte answers with its error status.
- `PUT /_capability` checks the owner signature against the pool's on-chain
  owner on the gateway's deployment.
- A web page's Origin always applies the page scope rule, token or not.
- `GET /_delegate` needs a page Origin or the token, and each caller keeps at
  most 4 delegates waiting.
- `HEAD` answers 405 instead of starting a paid pull.
- A keystore password file in the environment no longer blocks startup.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… at equal scope

A page that registers `*` no longer takes over the user's own `*` pass by
naming an earlier expiry.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@thiras

thiras commented Oct 14, 2026

Copy link
Copy Markdown
Contributor

Re-checked at ed57c56. Fixed as described: 1, 2, 6, 9, 10. Moved to #2458: 7, 8. A few gaps remain in the fixes:

  1. Shadowing (docs: convert ASCII art schemas to Mermaid diagrams #3) is narrowed, not closed. verify_owner proves the signer owns the pool on this deployment. It does not prove the pool can pay, and ties still go to the earliest expiry (Registered::preference). A page on x.example.com can open its own empty pool, sign a capability over it with an earlier expiry, and register *.example.com. That capability wins over example.com's funded one until it fails and is marked spent: one 402 per bogus capability. "A capability that can pay no longer loses a tie to one that cannot" holds only if "signed by the pool owner" meant "funded", and it doesn't.
  2. Registered delegates have no per-minter bound. may_mint counts only delegates with capability.is_none(), so registering one frees its pending room. A page can loop GET /_delegate → PUT /_capability against one pool and keep as many registrations as it likes until they expire. That grows memory without bound, and combined with (1) it gives the page a stock of shadowing capabilities.
  3. The global pending bound (ADR 001: Specify on-chain node registry contract interface #5) can still be filled. 4 per origin × 256 origins = MAX_PENDING. Wildcard DNS plus iframes on distinct subdomains, each doing a CORS fetch('/_delegate'), fills it.
  4. Minor: a funding stop after the first byte never calls mark_spent. The body stream runs after content() has returned, so only a stop before the first byte marks the capability spent. It self-heals on the next request, which fails before its first byte.
  5. Nit: finished() treats a dropped done_tx as Ok. If the pull thread panics, the browser gets an empty 200 from first_chunk, or a body that ends cleanly but short.

verify_owner has no test, and neither do the HEAD 405 and the password-file change.

🤖 Generated with Claude Code

…ates

- A funding stop before the first byte retires the capability and retries
  with the next covering one; a stop mid-body retires it too.
- Equal scopes prefer the earlier registration, so a newcomer never shadows
  a capability in use.
- Each page origin holds at most 8 delegates, pending or registered, and
  pages share a bound of 1024; the token holder mints outside both.
- A pull thread that ends without a result is an error, not a clean end.
- The handler is generic over the request body so routing is unit tested.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alpergundogdu

Copy link
Copy Markdown
Contributor Author

Addressed in 8d262ec:

  1. Shadowing. Two changes. Equal scopes now prefer the earlier registration instead of the earlier expiry, so a capability registered later can't shadow one that is already in use, whatever expiry it names. And a funding stop before the first byte retires the capability and retries the request with the next covering one, so a capability over an empty pool costs one retry, not a failed load (no 402 reaches the page while another capability covers it). Fixed the verify_owner doc so it no longer claims "can pay": it proves ownership, and funding shows when a pull draws on the pool.
  2. Registered delegates. The per-origin bound now counts every live delegate an origin holds, pending or registered (8), and pages share a bound of 1024. A page's capability retired by a funding stop is dropped, freeing its room; the token holder's stays listed as spent.
  3. Global bound. Only page origins count toward it now, and the token holder mints outside it, so the extension's own handshake can't be blocked. A page using wildcard DNS can still fill the page-wide bound (128 subdomains × 8) and block other pages' publisher handshakes while it stays open. Grouping by registrable domain would need the PSL, which we chose not to add, so this is the remaining limit.
  4. Mid-body funding stop. The body stream now retires the capability when the pull ends with FundingNeeded after the first byte.
  5. Dropped done_tx. finished() now treats it as an error ("the pull ended without a result"), so a panicked pull aborts the body instead of ending it cleanly.

Tests. owner_matches (the on-chain owner comparison, split out of verify_owner). keyless covers the password-file drop and the key-flag refusals. The handler is now generic over the request body, so routing is tested in-process: HEAD → 405, minting needs an Origin or the token and stops at an origin's bound, and a page with the token still can't register another host's scope. Also covered: preference ordering and registered delegates counting toward the bound. 60 tests in gateway:: + fetch::.

🤖 Addressed by Claude Code

… List

Pages of one registrable domain share one bound of 8 delegates, so serving
pages from many subdomains (wildcard DNS) no longer multiplies a site's room
or fills the bound all pages share. The list is compiled in through `psl`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alpergundogdu

Copy link
Copy Markdown
Contributor Author

Follow-up on point 3, in 310e312: the delegate bound is now per site, not per origin. A site is the registrable domain by the Public Suffix List (psl, list compiled in), so p1.evil.com … pN.evil.com share one bound of 8. Wildcard DNS no longer multiplies a site's room; filling the 1024 page-wide bound now takes 128 registrable domains. Private suffixes like github.io keep each user site separate (alice.github.io is its own site). IP hosts and names with no registrable domain (localhost) count as their own site. Covered by a_site_is_the_registrable_domain and an in-process test that mints from 9 subdomains of one site and gets 429 on the 9th.

🤖 Addressed by Claude Code

alpergundogdu and others added 2 commits October 14, 2026 13:18
A page may no longer register `*.io`, `*.co.uk` or `*.github.io` and pay
for, and see, the user's loads across every site under that suffix. Its own
site's wildcard and `*` stay open; the token holder registers any scope.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts:
#	CLAUDE.md
#	crates/cli/src/commands/mod.rs
#	crates/cli/src/main.rs
#	crates/common/src/cli/mod.rs
@alpergundogdu
alpergundogdu merged commit e260c3d into main Oct 14, 2026
33 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants