Skip to content

Commit 3b502a9

Browse files
alpergundogduclaude
andcommitted
feat!: register a capability with a scope; PAYMENT_REQUIRED replaces POOL_UNFUNDED
`register_capability(capability, scope)` takes a required scope: "any", or a `NamespaceScope(namespaces, signature)` the pool's owner signed, which the SDK passes through. `Registration` and `RegisteredCapability` carry the optional `namespaces` the gateway echoes. A 503 from a public gateway maps to `PAYMENT_REQUIRED`, as a 402 does; the `POOL_UNFUNDED` code is gone. The fake gateway requires `scope`, checks a namespace scope's shape and echoes its namespaces in the 201 and the listing. The loopback contract suite registers with scope "any" and checks a registration without a scope is 422. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 6500b2a commit 3b502a9

15 files changed

Lines changed: 256 additions & 81 deletions

‎README.md‎

Lines changed: 20 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -139,7 +139,7 @@ async with AsyncClient("https://decdn.link") as client:
139139

140140
A public gateway pays with the capabilities its operator registered on it, in
141141
the order they were registered. When none can pay, a request the gateway must
142-
pull fails with `POOL_UNFUNDED`, carrying `retry_after_secs` and the
142+
pull fails with `PAYMENT_REQUIRED`, carrying `retry_after_secs` and the
143143
`fallback_uri` to fetch with a paying client of your own; a response its cache
144144
holds whole still comes, at no cost.
145145

@@ -151,23 +151,35 @@ too; leaving the block closes the connection if the body was not read.
151151
A loopback gateway pays with capabilities a pool owner issued to its delegate
152152
keys. The gateway holds one pending key: `delegate()` returns the same address
153153
until a capability claims it, and a fresh key after that. Have the owner
154-
assign the pending key, then register the capability:
154+
assign the pending key, then register the capability with the scope it pays
155+
for:
155156

156157
```python
157-
from decdn import AsyncClient, Client
158+
from decdn import AsyncClient, Client, NamespaceScope
158159

159160
with Client("http://127.0.0.1:8484") as client:
160161
delegate = client.loopback.delegate()
161162
# The pool owner: decdn pool assign --pool <id> --signer <delegate.address> ...
162-
client.loopback.register_capability("dcap1:...")
163+
client.loopback.register_capability("dcap1:...", "any")
163164
r = client.get("decdn:<64 hex>")
164165

165166
async with AsyncClient("http://127.0.0.1:8484") as client:
166167
delegate = await client.loopback.delegate()
167-
await client.loopback.register_capability("dcap1:...")
168-
r = await client.get("decdn:<64 hex>")
168+
scope = NamespaceScope(namespaces=[7, 9], signature="0x...")
169+
await client.loopback.register_capability("dcap1:...", scope)
170+
r = await client.get("decdn:<64 hex>?ns=7")
169171
```
170172

173+
The scope is required. `"any"` pays for any content. A `NamespaceScope` pays
174+
only for requests that name one of its namespaces (`?ns=<id>` in the `decdn:`
175+
URI, or a site host `<ns>.<label>.localhost`), and carries the pool owner's
176+
EIP-712 signature over `CapabilityScope(address signer,bytes32 poolId,uint256[] namespaces)`
177+
(domain `decdn-capability-scope`, version `1`, the chain id, and the
178+
PaymentPool as the verifying contract). The SDK sends the signature as given;
179+
the gateway checks it and refuses a malformed scope or a signature that does
180+
not recover the pool's owner with `UNPROCESSABLE`. A request that names no
181+
namespace is paid only by `"any"` capabilities.
182+
171183
A key holds one capability per pool, and capabilities from several pools.
172184
`client.loopback.capabilities()` lists what the gateway holds in the order it
173185
pays with them: a request goes to the first one that is not spent and not
@@ -215,8 +227,7 @@ Every failure is a `DecdnError` with a stable `code`:
215227

216228
| Code | When |
217229
| ----------------------- | --------------------------------------------------------------------------------------------------- |
218-
| `PAYMENT_REQUIRED` | 402: no capability the loopback gateway holds can pay |
219-
| `POOL_UNFUNDED` | 503: no capability the public gateway holds can pay |
230+
| `PAYMENT_REQUIRED` | 402 (loopback) or 503 (public): no capability the gateway holds can pay |
220231
| `NOT_FOUND` | 404 |
221232
| `RANGE_NOT_SATISFIABLE` | 416: the range starts past the end; `size` holds the entry's size |
222233
| `FORBIDDEN` | 403 |
@@ -298,7 +309,7 @@ are the deployment the gateway verifies against.
298309
| `client.manifest(hash_or_uri)` | A bundle's verified manifest, cached per client |
299310
| `client.site_url(uri)`, `client.namespace_url(ns)` | The site URL of a bundle or entry; the URL a namespace's pointer serves at (`https://<ns>.<host>/`). Neither makes a request |
300311
| `client.loopback.delegate()` | The loopback gateway's pending delegate key: the same address until a capability claims it |
301-
| `client.loopback.register_capability(capability)`, `.capabilities()` | Registers a `dcap1:` capability issued to a key the gateway holds; lists the capabilities the gateway holds, in the order it pays with them |
312+
| `client.loopback.register_capability(capability, scope)`, `.capabilities()` | Registers a `dcap1:` capability issued to a key the gateway holds, for scope `"any"` or a `NamespaceScope`; lists the capabilities the gateway holds, in the order it pays with them, with the `namespaces` of a scoped one |
302313
| `client.pointer.set(namespace=, root=, seq=, signer=)` | Signs and publishes a namespace pointer on a public gateway |
303314
| `pointer_typed_data`, `pointer_signing_hash`, `sign_pointer`, `recover_pointer_signer` | The pointer's EIP-712 typed data and signing hash, its signature, and the signer a signature recovers to |
304315
| `parse_uri`, `format_uri` | Parse and canonically format a `decdn:` URI, following the Rust client's grammar exactly (`BAD_URI` on anything it refuses) |

‎src/decdn/__init__.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,8 +29,10 @@
2929
)
3030
from decdn.loopback import (
3131
AsyncLoopbackApi,
32+
CapabilityScope,
3233
Delegate,
3334
LoopbackApi,
35+
NamespaceScope,
3436
RegisteredCapability,
3537
Registration,
3638
)
@@ -93,8 +95,10 @@
9395
"create_blake3",
9496
# loopback
9597
"AsyncLoopbackApi",
98+
"CapabilityScope",
9699
"Delegate",
97100
"LoopbackApi",
101+
"NamespaceScope",
98102
"RegisteredCapability",
99103
"Registration",
100104
# manifest

‎src/decdn/_core.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@
3333
_DIGITS = re.compile(r"[0-9]+")
3434
_ETAG = re.compile(r'"?([0-9a-fA-F]{64})"?')
3535
_LOOPBACK_HOSTS = frozenset({"127.0.0.1", "localhost", "::1", "[::1]"})
36-
_RETRYABLE = frozenset({"PAYMENT_REQUIRED", "POOL_UNFUNDED", "RATE_LIMITED"})
36+
_RETRYABLE = frozenset({"PAYMENT_REQUIRED", "RATE_LIMITED"})
3737

3838

3939
@dataclass(frozen=True)

‎src/decdn/_http.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121
422: "UNPROCESSABLE",
2222
429: "RATE_LIMITED",
2323
502: "UPSTREAM",
24-
503: "POOL_UNFUNDED",
24+
503: "PAYMENT_REQUIRED",
2525
}
2626

2727
_LINK = re.compile(r'<(decdn:[^>]+)>\s*;\s*rel="?alternate"?')

‎src/decdn/errors.py‎

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,8 @@
33
from typing import Literal
44

55
ErrorCode = Literal[
6-
# 402: no capability the loopback gateway holds can pay.
6+
# 402 (loopback) or 503 (public): no capability the gateway holds can pay.
77
"PAYMENT_REQUIRED",
8-
# 503: no capability the public gateway holds can pay.
9-
"POOL_UNFUNDED",
108
# 404.
119
"NOT_FOUND",
1210
# 416: the range starts past the end; `size` holds the entry's size.

‎src/decdn/loopback.py‎

Lines changed: 53 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -2,21 +2,41 @@
22
(https://github.com/decdn/decdn/blob/main/crates/cli/src/commands/gateway.rs):
33
44
`GET /_delegate` returns the gateway's pending delegate key, `PUT /_capability` registers a `dcap1:`
5-
capability issued to a key the gateway holds, `GET /_capability` lists the registered ones in the
6-
order the gateway pays with them. Keys and capabilities live in the gateway's memory: a restart
7-
drops every one.
5+
capability issued to a key the gateway holds, with the scope of content it pays for,
6+
`GET /_capability` lists the registered ones in the order the gateway pays with them. Keys and
7+
capabilities live in the gateway's memory: a restart drops every one.
88
"""
99

1010
import json
1111
from dataclasses import dataclass
12-
from typing import TYPE_CHECKING, Any
12+
from typing import TYPE_CHECKING, Any, Literal
1313

1414
from decdn.errors import DecdnError
1515

1616
if TYPE_CHECKING:
1717
from decdn.client import AsyncClient, Client
1818

1919

20+
@dataclass(frozen=True)
21+
class NamespaceScope:
22+
"""A capability scope that pays only for content of `namespaces`.
23+
24+
The pool's on-chain owner signs EIP-712 `CapabilityScope(address signer,bytes32 poolId,
25+
uint256[] namespaces)` (domain `decdn-capability-scope`, version `1`, the chain id, and the
26+
PaymentPool as the verifying contract), with the capability's `signer` and `poolId`. The SDK
27+
sends `signature` as given; the gateway checks it.
28+
"""
29+
30+
# Namespace ids, at least one, each 1 or more.
31+
namespaces: list[int]
32+
# The owner's 65-byte signature, `0x` hex.
33+
signature: str
34+
35+
36+
CapabilityScope = Literal["any"] | NamespaceScope
37+
"""What a capability pays for: `"any"` content, or only the content of a `NamespaceScope`."""
38+
39+
2040
@dataclass(frozen=True)
2141
class Delegate:
2242
"""A delegate key the gateway holds."""
@@ -32,6 +52,8 @@ class Registration:
3252
pool: str
3353
# Unix-seconds expiry.
3454
expiry: int
55+
# The namespaces a namespace-scoped capability pays for; `None` for scope `"any"`.
56+
namespaces: list[int] | None = None
3557

3658

3759
@dataclass(frozen=True)
@@ -46,6 +68,8 @@ class RegisteredCapability:
4668
expiry: int
4769
# Whether a pull stopped for funding on it; the gateway pays with it no more.
4870
spent: bool
71+
# The namespaces a namespace-scoped capability pays for; `None` for scope `"any"`.
72+
namespaces: list[int] | None = None
4973

5074

5175
def _check(context: str) -> None:
@@ -57,8 +81,13 @@ def _headers(has_body: bool) -> dict[str, str]:
5781
return {"content-type": "application/json"} if has_body else {}
5882

5983

60-
def _registration_body(capability: str) -> bytes:
61-
return json.dumps({"capability": capability}).encode()
84+
def _registration_body(capability: str, scope: CapabilityScope) -> bytes:
85+
wire: str | dict[str, Any] = (
86+
scope
87+
if isinstance(scope, str)
88+
else {"namespaces": list(scope.namespaces), "signature": scope.signature}
89+
)
90+
return json.dumps({"capability": capability, "scope": wire}).encode()
6291

6392

6493
def _delegate(data: bytes) -> Delegate:
@@ -67,7 +96,12 @@ def _delegate(data: bytes) -> Delegate:
6796

6897
def _registration(data: bytes) -> Registration:
6998
parsed = json.loads(data)
70-
return Registration(signer=parsed["signer"], pool=parsed["pool"], expiry=parsed["expiry"])
99+
return Registration(
100+
signer=parsed["signer"],
101+
pool=parsed["pool"],
102+
expiry=parsed["expiry"],
103+
namespaces=parsed.get("namespaces"),
104+
)
71105

72106

73107
def _capabilities(data: bytes) -> list[RegisteredCapability]:
@@ -79,6 +113,7 @@ def _capabilities(data: bytes) -> list[RegisteredCapability]:
79113
cap=i["cap"],
80114
expiry=i["expiry"],
81115
spent=i["spent"],
116+
namespaces=i.get("namespaces"),
82117
)
83118
for i in items
84119
]
@@ -107,13 +142,16 @@ def delegate(self) -> Delegate:
107142
"""
108143
return _delegate(self._call("GET", "/_delegate"))
109144

110-
def register_capability(self, capability: str) -> Registration:
111-
"""Register `capability`, a `dcap1:` issued to a key the gateway holds.
145+
def register_capability(self, capability: str, scope: CapabilityScope) -> Registration:
146+
"""Register `capability`, a `dcap1:` issued to a key the gateway holds, to pay for `scope`.
112147
113-
A key holds one capability per pool: a key the gateway does not hold, or a second
114-
capability from the same pool on one key, raises `CONFLICT`.
148+
`scope` is `"any"` (any content) or a `NamespaceScope` the pool's owner signed (only the
149+
content of its namespaces). A key holds one capability per pool: a key the gateway does
150+
not hold, or a second capability from the same pool on one key, raises `CONFLICT`. A
151+
malformed scope, or a scope signature that does not recover the pool's owner, raises
152+
`UNPROCESSABLE`.
115153
"""
116-
return _registration(self._call("PUT", "/_capability", _registration_body(capability)))
154+
return _registration(self._call("PUT", "/_capability", _registration_body(capability, scope)))
117155

118156
def capabilities(self) -> list[RegisteredCapability]:
119157
"""Return the capabilities the gateway holds, in the order it pays with them."""
@@ -139,9 +177,9 @@ async def delegate(self) -> Delegate:
139177
"""Return the gateway's pending delegate key: `LoopbackApi`'s."""
140178
return _delegate(await self._call("GET", "/_delegate"))
141179

142-
async def register_capability(self, capability: str) -> Registration:
143-
"""Register `capability`, a `dcap1:` issued to a key the gateway holds: `LoopbackApi`'s."""
144-
return _registration(await self._call("PUT", "/_capability", _registration_body(capability)))
180+
async def register_capability(self, capability: str, scope: CapabilityScope) -> Registration:
181+
"""Register `capability` to pay for `scope`: `LoopbackApi`'s."""
182+
return _registration(await self._call("PUT", "/_capability", _registration_body(capability, scope)))
145183

146184
async def capabilities(self) -> list[RegisteredCapability]:
147185
"""Return the capabilities the gateway holds, in the order it pays with them."""

‎tests/contract/fixture.py‎

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -129,15 +129,21 @@ def http(self, flavour: Driver) -> httpx.Client | httpx.AsyncClient:
129129
return httpx.AsyncClient(transport=AsyncHostTransport(self.connect), follow_redirects=False)
130130

131131
async def fetch(
132-
self, flavour: Driver, url: str, *, method: str = "GET", headers: dict[str, str] | None = None
132+
self,
133+
flavour: Driver,
134+
url: str,
135+
*,
136+
method: str = "GET",
137+
headers: dict[str, str] | None = None,
138+
content: bytes | None = None,
133139
) -> httpx.Response:
134140
"""Send one raw request through `http(flavour)` and return the answer, read."""
135141
http = self.http(flavour)
136142
if isinstance(http, httpx.Client):
137143
with http:
138-
return http.request(method, url, headers=headers)
144+
return http.request(method, url, headers=headers, content=content)
139145
async with http:
140-
return await http.request(method, url, headers=headers)
146+
return await http.request(method, url, headers=headers, content=content)
141147

142148
def close(self) -> None:
143149
"""Stop the fake's listener; a real gateway is the harness's to stop."""

‎tests/contract/test_loopback.py‎

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
own pool, and each flavour registers its own.
88
"""
99

10+
import json
1011
import re
1112
from collections.abc import Iterator
1213

@@ -41,8 +42,8 @@ async def test_refuses_an_unknown_host(contract: Contract, flavour: Driver) -> N
4142
assert r.status_code == 403
4243

4344

44-
# No token, a browser-header gate on content, the pending delegate key, capabilities without a
45-
# scope, and payment by the held capabilities in registration order: decdn/decdn's gateway after
45+
# No token, a browser-header gate on content, the pending delegate key, capabilities registered
46+
# with a scope, and payment by the held capabilities in registration order: decdn/decdn's gateway after
4647
# release 0.3.1. A released gateway up to 0.3.1 wants a token and a page host, so it never collects
4748
# these tests.
4849
if shipped_after("0.3.1"):
@@ -64,15 +65,29 @@ async def test_returns_the_one_pending_key_until_a_capability_claims_it(
6465
assert again.address == first.address
6566
assert first.address.lower() == parse_capability(contract.capability(client)).signer.lower()
6667

68+
async def test_refuses_a_capability_registered_without_a_scope(
69+
contract: Contract, flavour: Driver
70+
) -> None:
71+
c = contract
72+
r = await c.fetch(
73+
flavour,
74+
f"{c.gateway_url}/_capability",
75+
method="PUT",
76+
headers={"content-type": "application/json"},
77+
content=json.dumps({"capability": c.capability(flavour)}).encode(),
78+
)
79+
assert r.status_code == 422
80+
6781
async def test_registers_a_capability_from_each_pool_on_the_one_key(
6882
contract: Contract, flavour: Driver, client: Driver
6983
) -> None:
7084
capability = contract.capability(flavour)
71-
registered = await client.loopback_register(capability=capability)
85+
registered = await client.loopback_register(capability=capability, scope="any")
7286
grant = parse_capability(capability)
7387
assert registered.signer.lower() == grant.signer.lower()
7488
assert registered.pool.lower() == grant.pool_id.lower()
7589
assert registered.expiry == grant.expiry
90+
assert registered.namespaces is None
7691

7792
async def test_lists_the_capabilities_in_registration_order(
7893
contract: Contract, flavour: Driver, client: Driver
@@ -97,7 +112,9 @@ async def test_lists_the_capabilities_in_registration_order(
97112
async def test_refuses_a_second_capability_from_one_pool_on_one_key(
98113
contract: Contract, flavour: Driver, client: Driver
99114
) -> None:
100-
await rejects(client.loopback_register(capability=contract.capability(flavour)), "CONFLICT")
115+
await rejects(
116+
client.loopback_register(capability=contract.capability(flavour), scope="any"), "CONFLICT"
117+
)
101118

102119
async def test_creates_a_fresh_pending_key_once_a_capability_claims_it(
103120
contract: Contract, flavour: Driver, client: Driver

0 commit comments

Comments
 (0)