Repository navigation
feat(cli): decdn gateway serves decdn: URIs to a browser with scoped, in-memory delegates - #2456
Conversation
decdn gateway serves decdn: URIs to a browser over loopback HTTPdecdn gateway serves decdn: URIs to a browser with scoped, in-memory delegates
…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]>
891f408 to
dcb139a
Compare
There was a problem hiding this comment.
🔵 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/bytesdeps): HTTP server, delegate/capability management, scope matching, manifest LRU cache, per-pull thread. fetch.rsrefactor:Sink,Credential,fetch_into,fetch_over/stream_outthreading the sink through;copy_verifiedmade?Sized.uri.rsparser and public-API snapshot (belongs to stacked #2455) plusCLAUDE.md/CLI-enum doc updates addinggateway.
| 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
left a comment
There was a problem hiding this comment.
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.
classifycan't seeFundingNeeded(context isn't downcastable fromchain()) → no 402, nomark_spent- A pull that fails before the first byte returns an empty
200 OK(EOF beats the error in the biased select) - Unverified capabilities can shadow legitimate ones (no signature/deployment check + earliest-expiry tie-break)
- A page can register
*/ public-suffix wildcards and become the payer for other sites - Unauthenticated
GET /_delegatelets any page exhaust the globalMAX_PENDING - A valid token bypasses
may_registereven when a browserOriginis present - One global pull slot with no wait timeout: a paused
<video>blocks all other content - Full endpoint/store/config bring-up per request
HEADstarts a paid pullDECDN_KEYSTORE_PASSWORD_FILEin the env blocksdecdn gatewaystartup
Details inline. Finding 1 was reproduced with a scratch program; the rest come from reading the code.
🤖 Generated with Claude Code
Code Coverage OverviewLanguages: Rust Rust / code-coverage/cargo-llvm-covThe overall line coverage in commit a82668b in the Show a line coverage summary of the most impacted files.
Updated |
…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]>
|
Re-checked at ed57c56. Fixed as described: 1, 2, 6, 9, 10. Moved to #2458: 7, 8. A few gaps remain in the fixes:
🤖 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]>
|
Addressed in 8d262ec:
Tests. 🤖 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]>
|
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 ( 🤖 Addressed by Claude Code |
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
Builds on the
DecdnUriparser from #2455 (merged).Summary
decdn gatewayis a loopback HTTP gateway that lets a browser opendecdn: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>]servesdecdn:<hash>[/<path>][?ns=<id>]. A blob or bundle entry streams its verified bytes in order (entryContent-Typeby extension viamime_guess,Content-Lengthfrom 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.HEADanswers 405, since answering it would cost a paid pull.Every content request needs
x-decdn-token(the gateway token) andx-decdn-host(the page's host). The browser extension (decdn/browser-demo) adds both throughdeclarativeNetRequest, 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 (noOrigin, or an extension's).Origin: nullis refused.GET /_delegatePUT /_capability{capability, scope}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.commay registerexample.com,*.example.comor*, 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 /_capabilityDelegate keys live in memory only; a restart drops them and every capability issued to them. A capability a pull reports as
FundingNeededis retired: a page's is dropped, the token holder's stays listed as spent.Security boundaries
Hostcheck against DNS rebinding.<data-dir>/token(default~/.decdn/gateway, owner-only), compared in constant time./_delegateand/_capabilityanswer cross-origin (preflight allowsGET, 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.--keystore,--capabilityand--capability-fileare refused: the gateway holds its own keys. A keystore password file (for example fromDECDN_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.
fetchrefactorfetchgains aSink(Output= today's--output,Writer= a caller'sAsyncWrite) andfetch_intotakes an optional in-memoryCredential { 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 notSend) and pipes into the response; pulls run one at a time.Tested against Arbitrum Sepolia
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; twoGET /_delegatecalls → different addresses.GET /_delegatewith noOriginor token → 403; a mint past a page's bound → 429 (unit tests cover the per-site bound across subdomains);decdn.orgregisteringnetflix.com→ 403, with or without the token;HEAD→ 405; startup withDECDN_KEYSTORE_PASSWORD_FILEset.*, and a request labelledexample.comstreamed a 4.6 MB PNG bundle entry (valid 2432×1440) in 4.7 s.<img src="decdn:…">and links rendered through the gateway.Not in this PR
decdn:OS URL-handler registration.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 forHEAD, minting and page registration, token match, token file, pruning, content types)cargo clippy -p decdn-cli --all-targets --all-features🤖 Generated with Claude Code