regent-httpsig 0.3.0__py3-none-any.whl → 0.4.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -14,6 +14,14 @@ from regent_httpsig.budget import (
14
14
  from regent_httpsig.config import HttpsigConfig
15
15
  from regent_httpsig.jwk import b64url, jwk_thumbprint, load_ed25519_jwk
16
16
  from regent_httpsig.netguard import NotPublicURL, assert_public_url
17
+ from regent_httpsig.usage import (
18
+ ResponseSigner,
19
+ UsageQueryError,
20
+ build_usage_response,
21
+ make_usage_endpoint,
22
+ parse_usage_request,
23
+ validate_budget_grant,
24
+ )
17
25
  from regent_httpsig.sfv import (
18
26
  build_aauth_budget_header,
19
27
  build_aauth_requirement,
@@ -40,6 +48,12 @@ __all__ = [
40
48
  "__version__",
41
49
  "assert_public_url",
42
50
  "b64url",
51
+ "ResponseSigner",
52
+ "UsageQueryError",
53
+ "build_usage_response",
54
+ "make_usage_endpoint",
55
+ "parse_usage_request",
56
+ "validate_budget_grant",
43
57
  "build_aauth_budget_header",
44
58
  "build_aauth_requirement",
45
59
  "generate_seed",
regent_httpsig/budget.py CHANGED
@@ -21,6 +21,7 @@ import asyncio
21
21
  import itertools
22
22
  import time
23
23
  from collections.abc import Mapping
24
+ from datetime import UTC, datetime, timedelta
24
25
  from dataclasses import dataclass, field
25
26
  from typing import Any
26
27
 
@@ -109,6 +110,48 @@ class _Pool:
109
110
  last_activity: float = 0.0
110
111
 
111
112
 
113
+ @dataclass
114
+ class _ScopeCounters:
115
+ """Calendar counters for one usage scope (draft §calendar-counters): running
116
+ integers bucketed on UTC boundaries — no per-record history is kept."""
117
+
118
+ all_time: int = 0
119
+ day: int = 0
120
+ week: int = 0
121
+ month: int = 0
122
+ year: int = 0
123
+ day_start: float = 0.0
124
+ week_start: float = 0.0
125
+ month_start: float = 0.0
126
+ year_start: float = 0.0
127
+
128
+ def add(self, amount: int, wall: float) -> None:
129
+ self._roll(wall)
130
+ self.all_time += amount
131
+ self.day += amount
132
+ self.week += amount
133
+ self.month += amount
134
+ self.year += amount
135
+
136
+ def snapshot(self, wall: float) -> dict[str, int]:
137
+ self._roll(wall)
138
+ return {"day": self.day, "week": self.week, "month": self.month,
139
+ "year": self.year, "all_time": self.all_time}
140
+
141
+ def _roll(self, wall: float) -> None:
142
+ dt = datetime.fromtimestamp(wall, tz=UTC)
143
+ day = dt.replace(hour=0, minute=0, second=0, microsecond=0)
144
+ week = day - timedelta(days=dt.weekday()) # Monday 00:00 UTC (ISO 8601)
145
+ month = day.replace(day=1)
146
+ year = month.replace(month=1)
147
+ for name, start in (("day", day), ("week", week),
148
+ ("month", month), ("year", year)):
149
+ ts = start.timestamp()
150
+ if getattr(self, f"{name}_start") < ts:
151
+ setattr(self, name, 0)
152
+ setattr(self, f"{name}_start", ts)
153
+
154
+
112
155
  class InMemoryMeter:
113
156
  """Single-process meter (asyncio-safe). Right for a single-instance service;
114
157
  multi-replica deployments need a shared backend behind the same interface.
@@ -119,12 +162,23 @@ class InMemoryMeter:
119
162
  """
120
163
 
121
164
  def __init__(self, *, reservation_ttl: float = 120.0,
122
- retention_seconds: float = 7200.0) -> None:
165
+ retention_seconds: float = 7200.0,
166
+ usage_key_retention: float = 86400.0) -> None:
123
167
  self._pools: dict[MeterKey, _Pool] = {}
124
168
  self._lock = asyncio.Lock()
125
169
  self._rids = itertools.count(1)
126
170
  self._reservation_ttl = reservation_ttl
127
171
  self._retention = retention_seconds
172
+ # Usage counters (draft §usage-counters) — wall-clock, keyed by the
173
+ # issuing PS so the endpoint only answers the party whose tokens we
174
+ # accepted. Scope counters never expire (all_time reaches as far back
175
+ # as the resource retains); per-key figures are pruned on IDLE time —
176
+ # "SHOULD retain … at least 24 hours after that key's last metered
177
+ # request" — so a key in continuous use is never pruned.
178
+ self._usage_key_retention = usage_key_retention
179
+ self._scope_usage: dict[tuple[str, str], _ScopeCounters] = {} # (iss, sub)
180
+ self._key_usage: dict[tuple[str, str], tuple[int, float]] = {} # (iss, jkt) -> (total, last_wall)
181
+ self._metering_unit: tuple[str, int] | None = None
128
182
 
129
183
  # ── internals (call under lock) ──────────────────────────────────────────
130
184
 
@@ -137,6 +191,7 @@ class InMemoryMeter:
137
191
  if deadline <= now:
138
192
  pool.consumed[jti] = pool.consumed.get(jti, 0) + amount
139
193
  del pool.reservations[rid]
194
+ self._record_usage(key, pool, jti, amount)
140
195
  # Expired grants leave the pool; their consumption records remain for
141
196
  # budget_consumed reporting until the retention window passes.
142
197
  for jti, (_, exp) in list(pool.grants.items()):
@@ -210,6 +265,8 @@ class InMemoryMeter:
210
265
  cost = min(max(actual, 0), held[1] if held else res.amount)
211
266
  pool.consumed[res.jti] = pool.consumed.get(res.jti, 0) + cost
212
267
  pool.last_activity = now
268
+ if cost > 0:
269
+ self._record_usage(res.key, pool, res.jti, cost)
213
270
  return self._remaining(pool)
214
271
 
215
272
  async def release(self, res: Reservation) -> int:
@@ -225,6 +282,46 @@ class InMemoryMeter:
225
282
  pool = self._purge(key, time.monotonic())
226
283
  return 0 if pool is None else self._remaining(pool)
227
284
 
285
+ def _record_usage(self, key: MeterKey, pool: _Pool, jti: str,
286
+ amount: int) -> None:
287
+ """Post a committed cost to the usage counters (call under lock).
288
+ Wall-clock, because calendar boundaries are UTC by definition."""
289
+ if amount <= 0:
290
+ return
291
+ wall = time.time()
292
+ iss, sub, _aud = key
293
+ self._metering_unit = self._metering_unit or (pool.unit, pool.decimals)
294
+ self._scope_usage.setdefault((iss, sub), _ScopeCounters()).add(amount, wall)
295
+ jkt = pool.jkt_of.get(jti)
296
+ if jkt:
297
+ total, _ = self._key_usage.get((iss, jkt), (0, 0.0))
298
+ self._key_usage[(iss, jkt)] = (total + amount, wall)
299
+
300
+ async def usage_scope(self, iss: str, sub: str) -> dict[str, int] | None:
301
+ """Calendar counters for a ``sub`` scope query, or ``None`` when the
302
+ resource holds no figure — the endpoint then omits ``usage``, keeping
303
+ "never seen" indistinguishable from "nothing consumed"."""
304
+ async with self._lock:
305
+ counters = self._scope_usage.get((iss, sub))
306
+ return None if counters is None else counters.snapshot(time.time())
307
+
308
+ async def usage_keys(self, iss: str, jkts: list[str]) -> dict[str, int]:
309
+ """Per-key totals for a ``jkts`` query. Unrecognized or pruned keys are
310
+ OMITTED, never reported as zero — absence means "cannot answer", a
311
+ present zero would be a wrong answer to an allocation decision."""
312
+ async with self._lock:
313
+ wall = time.time()
314
+ for pair, (_, last) in list(self._key_usage.items()):
315
+ if wall - last > self._usage_key_retention:
316
+ del self._key_usage[pair]
317
+ return {jkt: self._key_usage[(iss, jkt)][0]
318
+ for jkt in jkts if (iss, jkt) in self._key_usage}
319
+
320
+ def metering_unit(self) -> tuple[str, int] | None:
321
+ """The one unit every usage figure is denominated in (draft §one-unit),
322
+ or ``None`` before the first commit."""
323
+ return self._metering_unit
324
+
228
325
  async def consumed_records(self, key: MeterKey,
229
326
  jkt: str | None = None) -> list[dict[str, Any]]:
230
327
  """Per-token consumption for the resource token's ``budget_consumed``
regent_httpsig/fastapi.py CHANGED
@@ -224,6 +224,9 @@ class BudgetMiddleware(BaseHTTPMiddleware):
224
224
  return await self._refusal_with_token(
225
225
  reason=reason, envelope=envelope, remaining=outcome.remaining,
226
226
  key=key, jkt=sig.keyid,
227
+ # `required` rides only on insufficient-budget: what THIS
228
+ # request needed, so the agent can lower its bound and retry.
229
+ required=int(max_cost) if reason == "insufficient-budget" else None,
227
230
  )
228
231
 
229
232
  reservation: Reservation = outcome
@@ -237,6 +240,21 @@ class BudgetMiddleware(BaseHTTPMiddleware):
237
240
  # Nothing was served — the envelope is not charged for errors.
238
241
  remaining = await self._meter.release(reservation)
239
242
  cost = 0
243
+ elif self._is_streamed(request, response):
244
+ # Cost-omitted mode (draft §cost-omitted): a streamed response's
245
+ # actual cost is known only when the stream ends, and this runtime
246
+ # sends no trailers. We state what we HOLD — `reserved`, REQUIRED
247
+ # when `cost` is omitted — with `remaining` already net of the
248
+ # hold, and commit when the stream completes. The agent recovers
249
+ # the exact figure from the next response's `remaining`.
250
+ remaining = await self._meter.remaining(key)
251
+ response.headers["AAuth-Budget"] = build_aauth_budget_header(
252
+ remaining=remaining, reserved=int(max_cost),
253
+ unit=envelope.unit, decimals=envelope.decimals,
254
+ )
255
+ self._commit_after_stream(request, response, reservation,
256
+ int(max_cost))
257
+ return response
240
258
  else:
241
259
  actual = getattr(request.state, "budget_cost", None)
242
260
  cost = int(actual) if actual is not None else int(max_cost)
@@ -247,6 +265,36 @@ class BudgetMiddleware(BaseHTTPMiddleware):
247
265
  )
248
266
  return response
249
267
 
268
+ @staticmethod
269
+ def _is_streamed(request: Request, response: Response) -> bool:
270
+ """A handler opts in with ``request.state.budget_streaming = True``;
271
+ SSE responses are recognized on their own."""
272
+ if getattr(request.state, "budget_streaming", False):
273
+ return True
274
+ ctype = response.headers.get("content-type", "")
275
+ return ctype.startswith("text/event-stream")
276
+
277
+ def _commit_after_stream(self, request: Request, response: Response,
278
+ reservation: Reservation, max_cost: int) -> None:
279
+ """Wrap the body iterator: commit when the stream ends (the handler may
280
+ set ``request.state.budget_cost`` while streaming), release the unspent
281
+ remainder; a broken stream commits the full hold — conservative, per
282
+ the reservation-timeout rule."""
283
+ inner = response.body_iterator # type: ignore[attr-defined]
284
+
285
+ async def metered() -> Any:
286
+ ok = False
287
+ try:
288
+ async for chunk in inner:
289
+ yield chunk
290
+ ok = True
291
+ finally:
292
+ actual = getattr(request.state, "budget_cost", None)
293
+ cost = int(actual) if (ok and actual is not None) else max_cost
294
+ await self._meter.commit(reservation, cost)
295
+
296
+ response.body_iterator = metered() # type: ignore[attr-defined]
297
+
250
298
  # ── helpers ──────────────────────────────────────────────────────────────
251
299
 
252
300
  async def _verified(self, request: Request) -> VerifiedSignature | None:
@@ -264,6 +312,7 @@ class BudgetMiddleware(BaseHTTPMiddleware):
264
312
  async def _refusal_with_token(
265
313
  self, *, reason: str, envelope: BudgetClaim,
266
314
  remaining: int, key: MeterKey, jkt: str | None = None,
315
+ required: int | None = None,
267
316
  ) -> Response:
268
317
  token: str | None = None
269
318
  if self._resource_token is not None:
@@ -273,12 +322,13 @@ class BudgetMiddleware(BaseHTTPMiddleware):
273
322
  except Exception: # noqa: BLE001 — refusal must not fail on the extras
274
323
  logger.warning("resource_token_provider failed", exc_info=True)
275
324
  return self._refusal(reason=reason, envelope=envelope,
276
- remaining=remaining, resource_token=token)
325
+ remaining=remaining, resource_token=token,
326
+ required=required)
277
327
 
278
328
  def _refusal(
279
329
  self, *, reason: str | None, envelope: BudgetClaim | None,
280
330
  remaining: int | None, key: MeterKey | None = None,
281
- resource_token: str | None = None,
331
+ resource_token: str | None = None, required: int | None = None,
282
332
  ) -> Response:
283
333
  headers = {
284
334
  "AAuth-Requirement": build_aauth_requirement(
@@ -288,7 +338,8 @@ class BudgetMiddleware(BaseHTTPMiddleware):
288
338
  }
289
339
  if remaining is not None and envelope is not None:
290
340
  headers["AAuth-Budget"] = build_aauth_budget_header(
291
- remaining=remaining, unit=envelope.unit, decimals=envelope.decimals
341
+ remaining=remaining, required=required,
342
+ unit=envelope.unit, decimals=envelope.decimals,
292
343
  )
293
344
  code = "AUTH_TOKEN_REQUIRED" if reason is None else reason.upper().replace("-", "_")
294
345
  return JSONResponse(
regent_httpsig/sfv.py CHANGED
@@ -151,11 +151,15 @@ def build_aauth_budget_header(
151
151
  remaining: int,
152
152
  cost: int | None = None,
153
153
  reserved: int | None = None,
154
+ required: int | None = None,
154
155
  unit: str | None = None,
155
156
  decimals: int | None = None,
156
157
  ) -> str:
157
158
  """Serialize the ``AAuth-Budget`` response header. ``remaining`` is the only
158
- REQUIRED member; ``unit``/``decimals`` must travel together or not at all."""
159
+ REQUIRED member; ``unit``/``decimals`` must travel together or not at all.
160
+ ``required`` is the maximum cost of a request refused ``insufficient-budget``
161
+ — sent only with that refusal, so the agent's retry is a calculation
162
+ (lower the bound to fit ``remaining``) rather than a search."""
159
163
  if (unit is None) != (decimals is None):
160
164
  raise ValueError("unit and decimals must be provided together")
161
165
  members: list[str] = []
@@ -164,6 +168,8 @@ def build_aauth_budget_header(
164
168
  members.append(f"remaining={remaining}")
165
169
  if reserved is not None:
166
170
  members.append(f"reserved={reserved}")
171
+ if required is not None:
172
+ members.append(f"required={required}")
167
173
  if unit is not None and decimals is not None:
168
174
  members.append(f"unit={_sf_string(unit)}")
169
175
  members.append(f"decimals={decimals}")
@@ -0,0 +1,223 @@
1
+ """AAuth Budgets usage endpoint (draft-hardt-aauth-budgets, §Usage Counters).
2
+
3
+ Consumption records reach the PS only when an agent carries a resource token
4
+ home; this endpoint removes the agent from that loop — the PS queries the
5
+ resource directly, on a channel the agent is never on.
6
+
7
+ The library owns the contract: query validation, the response shape, and the
8
+ RECOMMENDED response signature. Caller authentication is the application's
9
+ (``authenticate_ps``) — it already knows which person servers it trusts and
10
+ how it verifies their signatures, exactly as it does for auth tokens.
11
+
12
+ Draft rules encoded here, each load-bearing:
13
+
14
+ - Exactly one scope key (``sub`` | ``tenant`` | ``mission_s256``) or ``jkts``;
15
+ both MAY appear; two scope keys or neither-nor-jkts is an error.
16
+ - An unrecognized scope value returns ``200`` with ``usage`` omitted — "never
17
+ seen" and "nothing consumed" are deliberately indistinguishable, so a query
18
+ cannot discover whether a person holds an account.
19
+ - An unrecognized or pruned thumbprint is OMITTED from ``jkts``, never zero:
20
+ absence means "cannot answer"; a present zero would be a wrong answer to an
21
+ allocation decision.
22
+ - One unit per response, named once at the top level.
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ import base64
28
+ import hashlib
29
+ import json
30
+ import time
31
+ from collections.abc import Awaitable, Callable
32
+ from typing import Any
33
+
34
+ from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
35
+
36
+ from regent_httpsig.jwk import b64url_decode, jwk_thumbprint
37
+
38
+ __all__ = ["UsageQueryError", "ResponseSigner", "build_usage_response",
39
+ "parse_usage_request", "make_usage_endpoint",
40
+ "validate_budget_grant"]
41
+
42
+ _SCOPE_KEYS = ("sub", "tenant", "mission_s256")
43
+ _MAX_JKTS = 100
44
+
45
+
46
+ class UsageQueryError(ValueError):
47
+ """The query violates the request contract (two scope keys, neither a
48
+ scope key nor ``jkts``, or malformed members)."""
49
+
50
+
51
+ def parse_usage_request(body: Any) -> tuple[str | None, str | None, list[str]]:
52
+ """Validate a usage query. Returns ``(scope_key, scope_value, jkts)``."""
53
+ if not isinstance(body, dict):
54
+ raise UsageQueryError("body must be a JSON object")
55
+ present = [k for k in _SCOPE_KEYS if k in body]
56
+ if len(present) > 1:
57
+ raise UsageQueryError("at most one scope key may appear")
58
+ jkts_raw = body.get("jkts", [])
59
+ if not isinstance(jkts_raw, list) or len(jkts_raw) > _MAX_JKTS or not all(
60
+ isinstance(j, str) and 20 <= len(j) <= 100 for j in jkts_raw
61
+ ):
62
+ raise UsageQueryError("jkts must be a short array of JWK thumbprints")
63
+ if not present and not jkts_raw:
64
+ raise UsageQueryError("a scope key or jkts is required")
65
+ scope_key = present[0] if present else None
66
+ scope_value = None
67
+ if scope_key is not None:
68
+ scope_value = body[scope_key]
69
+ if not isinstance(scope_value, str) or not scope_value:
70
+ raise UsageQueryError(f"{scope_key} must be a non-empty string")
71
+ return scope_key, scope_value, [str(j) for j in jkts_raw]
72
+
73
+
74
+ async def build_usage_response(
75
+ meter: Any,
76
+ *,
77
+ iss: str,
78
+ aud: str,
79
+ unit: str,
80
+ decimals: int,
81
+ scope_key: str | None,
82
+ scope_value: str | None,
83
+ jkts: list[str],
84
+ now: float | None = None,
85
+ ) -> dict[str, Any]:
86
+ """Assemble the response body per §Usage Response. ``iss`` scopes every
87
+ figure to tokens the calling PS issued; ``aud`` echoes who the response is
88
+ for (what stops a signed response being shown to a third party)."""
89
+ out: dict[str, Any] = {
90
+ "as_of": int(now if now is not None else time.time()),
91
+ "aud": aud,
92
+ "unit": unit,
93
+ "decimals": decimals,
94
+ }
95
+ if scope_key is not None:
96
+ out[scope_key] = scope_value
97
+ if scope_key == "sub":
98
+ counters = await meter.usage_scope(iss, str(scope_value))
99
+ if counters is not None:
100
+ out["usage"] = counters
101
+ # tenant / mission_s256: this meter holds no figure for them — the
102
+ # scope value is echoed and ``usage`` omitted, per the unrecognized
103
+ # scope rule. A backend that tracks them plugs in here.
104
+ if jkts:
105
+ out["jkts"] = await meter.usage_keys(iss, jkts)
106
+ return out
107
+
108
+
109
+ class ResponseSigner:
110
+ """Signs a usage response per §The Signed Response: an Ed25519 HTTP Sig
111
+ covering ``@status``, ``content-type``, ``content-digest``, bound to the
112
+ request via ``@authority``/``@path`` with the ``req`` parameter.
113
+
114
+ Hand-built base string: response signing with request-bound components is
115
+ beyond the request-oriented helper libraries, the component set is fixed by
116
+ the draft, and the golden tests freeze every byte of it.
117
+ """
118
+
119
+ def __init__(self, *, seed: str, jwks_url: str, label: str = "sig") -> None:
120
+ raw = b64url_decode(seed)
121
+ if len(raw) != 32:
122
+ raise ValueError("seed must be 32 bytes (base64url-encoded)")
123
+ self._key = Ed25519PrivateKey.from_private_bytes(raw)
124
+ self._jwks_url = jwks_url
125
+ self._label = label
126
+ self.public_jwk = {
127
+ "kty": "OKP", "crv": "Ed25519",
128
+ "x": base64.urlsafe_b64encode(
129
+ self._key.public_key().public_bytes_raw()
130
+ ).rstrip(b"=").decode(),
131
+ }
132
+ self.keyid = jwk_thumbprint(self.public_jwk)
133
+
134
+ def sign(self, *, status: int, content_type: str, body: bytes,
135
+ authority: str, path: str,
136
+ created: int | None = None) -> dict[str, str]:
137
+ """Return the four response headers: ``Content-Digest``,
138
+ ``Signature-Input``, ``Signature``, ``Signature-Key``."""
139
+ digest = "sha-256=:" + base64.b64encode(
140
+ hashlib.sha256(body).digest()).decode() + ":"
141
+ created = int(created if created is not None else time.time())
142
+ inner = (
143
+ '("@status" "content-type" "content-digest" '
144
+ '"@authority";req "@path";req)'
145
+ f";created={created}"
146
+ )
147
+ base = "\n".join([
148
+ f'"@status": {status}',
149
+ f'"content-type": {content_type}',
150
+ f'"content-digest": {digest}',
151
+ f'"@authority";req: {authority}',
152
+ f'"@path";req: {path}',
153
+ f'"@signature-params": {inner}',
154
+ ])
155
+ sig = base64.b64encode(self._key.sign(base.encode())).decode()
156
+ return {
157
+ "Content-Digest": digest,
158
+ "Signature-Input": f"{self._label}={inner}",
159
+ "Signature": f"{self._label}=:{sig}:",
160
+ "Signature-Key": f'{self._label}=jwks_uri; jwks_uri="{self._jwks_url}"',
161
+ }
162
+
163
+
164
+ def make_usage_endpoint(
165
+ meter: Any,
166
+ *,
167
+ authenticate_ps: Callable[[Any], Awaitable[str | None]],
168
+ unit: str,
169
+ decimals: int,
170
+ signer: ResponseSigner | None = None,
171
+ ) -> Callable[[Any], Awaitable[Any]]:
172
+ """Build an ASGI-framework-agnostic handler: ``handler(request)`` returns a
173
+ Starlette/FastAPI ``Response``. ``authenticate_ps(request)`` verifies the
174
+ calling person server's signature (jwks_uri scheme, per the AS token
175
+ endpoint rules) and returns its issuer identifier, or ``None`` to refuse —
176
+ the resource MUST only answer for values seen in tokens from that PS,
177
+ which the ``iss``-keyed counters enforce structurally."""
178
+ from starlette.responses import JSONResponse, Response
179
+
180
+ async def handler(request: Any) -> Response:
181
+ iss = await authenticate_ps(request)
182
+ if iss is None:
183
+ return JSONResponse(status_code=401, content={
184
+ "code": "PS_AUTH_REQUIRED",
185
+ "message": "Sign the query as a person server (jwks_uri scheme).",
186
+ })
187
+ try:
188
+ payload = json.loads(await request.body() or b"{}")
189
+ scope_key, scope_value, jkts = parse_usage_request(payload)
190
+ except (UsageQueryError, ValueError) as exc:
191
+ return JSONResponse(status_code=400, content={
192
+ "code": "INVALID_USAGE_QUERY", "message": str(exc)[:200]})
193
+ doc = await build_usage_response(
194
+ meter, iss=iss, aud=iss, unit=unit, decimals=decimals,
195
+ scope_key=scope_key, scope_value=scope_value, jkts=jkts)
196
+ body = json.dumps(doc, separators=(",", ":")).encode()
197
+ headers: dict[str, str] = {}
198
+ if signer is not None:
199
+ headers = signer.sign(
200
+ status=200, content_type="application/json", body=body,
201
+ authority=request.url.netloc, path=request.url.path)
202
+ return Response(content=body, media_type="application/json",
203
+ headers=headers)
204
+
205
+ return handler
206
+
207
+
208
+ def validate_budget_grant(unit: str, decimals: int,
209
+ budget_units: list[dict[str, Any]]) -> None:
210
+ """Enforce the §Resource Metadata MUSTs before minting a resource token:
211
+ a resource that declares ``budget_units`` MUST NOT issue a token whose
212
+ ``budget.unit`` is absent from the array, and MUST set ``budget.decimals``
213
+ to the declared value — the mismatch this stops is the draft's
214
+ "thousandfold error"."""
215
+ for entry in budget_units:
216
+ if entry.get("unit") == unit:
217
+ declared = entry.get("decimals")
218
+ if declared != decimals:
219
+ raise ValueError(
220
+ f"budget.decimals must be {declared} for {unit!r} "
221
+ f"(declared in budget_units), got {decimals}")
222
+ return
223
+ raise ValueError(f"unit {unit!r} is not declared in budget_units")
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: regent-httpsig
3
- Version: 0.3.0
3
+ Version: 0.4.0
4
4
  Summary: Verify and sign AI agent HTTP traffic in Python — RFC 9421 HTTP Message Signatures: Web Bot Auth (what OpenAI ships) and AAuth.
5
5
  Project-URL: Homepage, https://github.com/regent-protocol/regent-httpsig
6
6
  Project-URL: Repository, https://github.com/regent-protocol/regent-httpsig
@@ -168,6 +168,42 @@ The only thing the library cannot do for you is pricing (`price_fn`) — that
168
168
  is your domain. First known implementation of the draft; running in
169
169
  production on [get4agent.com](https://get4agent.com).
170
170
 
171
+ **The August 20 additions** are covered too:
172
+
173
+ - `insufficient-budget` refusals carry **`required`** — the refused request's
174
+ maximum cost — so the agent lowers its bound and retries instead of guessing.
175
+ - **Streaming** responses run in the draft's cost-omitted mode: `reserved` in
176
+ the header, commit when the stream ends (set `request.state.budget_cost`
177
+ mid-stream if you learn the actual), and the agent recovers the exact cost
178
+ from the next response's `remaining`.
179
+ - The **usage endpoint** (§Usage Counters) lets your PS query consumption
180
+ without the agent in the loop — scope counters (`sub`, UTC calendar buckets)
181
+ and per-key `jkts` totals, optionally signed:
182
+
183
+ ```python
184
+ from regent_httpsig import InMemoryMeter, ResponseSigner, make_usage_endpoint
185
+
186
+ handler = make_usage_endpoint(
187
+ meter,
188
+ authenticate_ps=my_ps_authenticator, # verify the PS's jwks_uri signature
189
+ unit="USD", decimals=6,
190
+ signer=ResponseSigner(seed=SEED, jwks_url="https://api.example/jwks.json"),
191
+ )
192
+
193
+ @app.post("/usage")
194
+ async def usage(request: Request):
195
+ return await handler(request)
196
+ ```
197
+
198
+ - `validate_budget_grant(unit, decimals, budget_units)` enforces the resource
199
+ metadata MUSTs before you mint a resource token — the "thousandfold error"
200
+ guard.
201
+
202
+ **Test vectors**: [`vectors/aauth-budgets-vectors.json`](vectors/aauth-budgets-vectors.json) —
203
+ header serializations (including `required` and the cost-omitted streaming
204
+ case), the budget object, consumption records, and a fully worked signed
205
+ usage response with a fixed key, ready for cross-implementation checks.
206
+
171
207
  ## Security model (what a naive implementation gets wrong)
172
208
 
173
209
  The verifier fetches key directories from **attacker-nameable origins** — whoever signs a
@@ -0,0 +1,16 @@
1
+ regent_httpsig/__init__.py,sha256=Ch-PdsMDo_uKG4U5A4xklU3jbCWdJTWXHG86n5VA7dc,1709
2
+ regent_httpsig/budget.py,sha256=RfasLL3HAdLt5kJ2L8DeGoA3FaVXe94LIn1nzboWYKA,15095
3
+ regent_httpsig/cli.py,sha256=WUSLQ2WuEX4E85L2C2EgoUfu5cWpj6MRSG1UVNHpzcw,2005
4
+ regent_httpsig/config.py,sha256=_xAIFYAyNbXzKg-famXLAs7eNdYwuvNA7NHQxcno0G4,2439
5
+ regent_httpsig/fastapi.py,sha256=a2m_azGEoVx9gghJTkKaHFUpUYGrxTmFK8IKW7-9AUQ,15266
6
+ regent_httpsig/jwk.py,sha256=h4vgnIgpnyKeWdWpm7g_hEyXZOPVREWn-bD4JN07tT0,1637
7
+ regent_httpsig/netguard.py,sha256=Sqg08mdC94RWvnQLJaH4weZW0nN2VlTJF5wVF8VYGHY,2121
8
+ regent_httpsig/sfv.py,sha256=O8eK3Xyw-lewSepLJQcBKfPZAIBZCYatw4zDNDsxxYo,7407
9
+ regent_httpsig/sign.py,sha256=B5ChxFxuuKL0i10bGrgFImzyh8GMjWIqNDECXehBWTA,4397
10
+ regent_httpsig/usage.py,sha256=PSIPXCtUZyh5cjn4SzwOgrXuJrwDIWu-kffJ-4NFeS0,9453
11
+ regent_httpsig/verify.py,sha256=8z-x3trF5B8P8D1aDYoqzF4R5h8BVv91CKiubFKFIiI,19915
12
+ regent_httpsig-0.4.0.dist-info/METADATA,sha256=FcXizrgtqWf9JnuL3ui_YtXDQFNgh-b5DG2zHzYJg-4,12023
13
+ regent_httpsig-0.4.0.dist-info/WHEEL,sha256=zOwg4jB6zX2kU910N-cMawjivD6tO8NEWvE12je1bVk,87
14
+ regent_httpsig-0.4.0.dist-info/entry_points.txt,sha256=SgZdmc27V14IAmwOjbBoCYLsbrALaqdTUHNHLbil2dU,59
15
+ regent_httpsig-0.4.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
16
+ regent_httpsig-0.4.0.dist-info/RECORD,,
@@ -1,15 +0,0 @@
1
- regent_httpsig/__init__.py,sha256=TCRliXblszIoUdlNNQzPf41jA2lZ8Pu3OImylFGzaMk,1372
2
- regent_httpsig/budget.py,sha256=8B0Zb5exfjorP1pcvezpuYqHN13ytrwJG3MNOEhnvE4,10563
3
- regent_httpsig/cli.py,sha256=WUSLQ2WuEX4E85L2C2EgoUfu5cWpj6MRSG1UVNHpzcw,2005
4
- regent_httpsig/config.py,sha256=_xAIFYAyNbXzKg-famXLAs7eNdYwuvNA7NHQxcno0G4,2439
5
- regent_httpsig/fastapi.py,sha256=cDOk7qHdz58JO3MlTDLsyDwGEQm6t3ZO3S3hyyo7OyU,12550
6
- regent_httpsig/jwk.py,sha256=h4vgnIgpnyKeWdWpm7g_hEyXZOPVREWn-bD4JN07tT0,1637
7
- regent_httpsig/netguard.py,sha256=Sqg08mdC94RWvnQLJaH4weZW0nN2VlTJF5wVF8VYGHY,2121
8
- regent_httpsig/sfv.py,sha256=zTxPf2f0XdSu3yKl3rw_CV4_Gbpl1ZJzOM_IA9nM7H0,7076
9
- regent_httpsig/sign.py,sha256=B5ChxFxuuKL0i10bGrgFImzyh8GMjWIqNDECXehBWTA,4397
10
- regent_httpsig/verify.py,sha256=8z-x3trF5B8P8D1aDYoqzF4R5h8BVv91CKiubFKFIiI,19915
11
- regent_httpsig-0.3.0.dist-info/METADATA,sha256=T0gBVK2_fZOYuWj_5ZlIYH5WJk7nn9RbmG-uWAFzcqM,10439
12
- regent_httpsig-0.3.0.dist-info/WHEEL,sha256=zOwg4jB6zX2kU910N-cMawjivD6tO8NEWvE12je1bVk,87
13
- regent_httpsig-0.3.0.dist-info/entry_points.txt,sha256=SgZdmc27V14IAmwOjbBoCYLsbrALaqdTUHNHLbil2dU,59
14
- regent_httpsig-0.3.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
15
- regent_httpsig-0.3.0.dist-info/RECORD,,