regent-httpsig 0.5.0__py3-none-any.whl → 0.5.1__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.
regent_httpsig/fastapi.py CHANGED
@@ -191,6 +191,13 @@ class BudgetMiddleware(BaseHTTPMiddleware):
191
191
  return await call_next(request)
192
192
 
193
193
  sig = await self._verified(request)
194
+ if sig is not None and sig.expired:
195
+ # §Budget Exhaustion, "auth token expired": the base protocol's plain
196
+ # 401 — and the resource token we attach carries the presented
197
+ # token's FINAL consumption record (stated at/after its exp), which
198
+ # is what lets its issuer settle the allocation exactly. Without
199
+ # this challenge an issuer never sees a final figure at all.
200
+ return await self._expired_challenge(sig)
194
201
  envelope: BudgetClaim | None = None
195
202
  if sig is not None:
196
203
  try:
@@ -307,11 +314,42 @@ class BudgetMiddleware(BaseHTTPMiddleware):
307
314
  result = None
308
315
  if "signature" in request.headers:
309
316
  result = await self._verifier.verify(
310
- request.method, _public_url(request), dict(request.headers)
317
+ request.method, _public_url(request), dict(request.headers),
318
+ allow_expired_auth_token=True,
311
319
  )
312
- request.state.regent_httpsig_result = result
320
+ # An expired token is never handed to the app: the middleware answers
321
+ # it with the final-record challenge and nothing downstream runs. The
322
+ # per-request cache still must not carry it — a later dependency
323
+ # reading the cache would otherwise see a token that is not valid.
324
+ request.state.regent_httpsig_result = (
325
+ None if result is not None and result.expired else result)
313
326
  return result
314
327
 
328
+ async def _expired_challenge(self, sig: VerifiedSignature) -> Response:
329
+ jti = str(sig.claims.get("jti") or "")
330
+ key: MeterKey = (
331
+ str(sig.claims.get("iss", "")),
332
+ str(sig.claims.get("sub", "")),
333
+ str(sig.claims.get("aud", "")),
334
+ )
335
+ token: str | None = None
336
+ if self._resource_token is not None and jti:
337
+ try:
338
+ record = await self._meter.consumed_record(key, jti)
339
+ token = await _maybe_await(self._resource_token(key, record))
340
+ except Exception: # noqa: BLE001 — the challenge must not fail on the extras
341
+ logger.warning("resource_token_provider failed", exc_info=True)
342
+ return JSONResponse(
343
+ status_code=401,
344
+ content={
345
+ "code": "AUTH_TOKEN_EXPIRED",
346
+ "message": "The auth token has expired. Take the resource token in "
347
+ "AAuth-Requirement to your PS for a fresh one.",
348
+ },
349
+ headers={"AAuth-Requirement": build_aauth_requirement(
350
+ reason=None, resource_token=token)},
351
+ )
352
+
315
353
  async def _refusal_with_token(
316
354
  self, *, reason: str, envelope: BudgetClaim,
317
355
  remaining: int, key: MeterKey, jti: str,
regent_httpsig/sfv.py CHANGED
@@ -176,13 +176,18 @@ def build_aauth_budget_header(
176
176
  return ", ".join(members)
177
177
 
178
178
 
179
- def build_aauth_requirement(*, reason: str, resource_token: str | None = None) -> str:
180
- """Serialize ``AAuth-Requirement`` for a budget refusal:
179
+ def build_aauth_requirement(*, reason: str | None,
180
+ resource_token: str | None = None) -> str:
181
+ """Serialize ``AAuth-Requirement`` for a budget challenge:
181
182
  ``requirement=auth-token;resource-token="eyJ…";reason=insufficient-budget``.
182
- ``reason`` is an sf-token (``insufficient-budget`` | ``budget-exhausted``);
183
- the resource token (when the resource issues one) rides as an sf-string."""
183
+ ``reason`` is an sf-token (``insufficient-budget`` | ``budget-exhausted``)
184
+ for an exhaustion refusal, or ``None`` for the base protocol's plain
185
+ challenge (an EXPIRED auth token — the budget did not run out, the token
186
+ did); the resource token (when the resource issues one) rides as an
187
+ sf-string."""
184
188
  out = "requirement=auth-token"
185
189
  if resource_token:
186
190
  out += f";resource-token={_sf_string(resource_token)}"
187
- out += f";reason={reason}"
191
+ if reason:
192
+ out += f";reason={reason}"
188
193
  return out
regent_httpsig/verify.py CHANGED
@@ -61,6 +61,10 @@ AAUTH_PERSON_TYP = "aa-person+jwt"
61
61
  AAUTH_AUTH_TYP = "aa-auth+jwt" # PS-issued auth tokens — the budget carrier
62
62
  # -11: person and auth tokens live at most one hour — enforced with tolerance.
63
63
  PERSON_TOKEN_MAX_LIFETIME = 3600 + 90
64
+ # How long after its exp an auth token still earns the budgets "final record"
65
+ # challenge (opt-in, BudgetMiddleware only): the meter retains consumption for
66
+ # about this long after last activity; beyond it there is no figure to carry.
67
+ EXPIRED_AUTH_TOKEN_GRACE = 7200
64
68
 
65
69
 
66
70
  def _register_fully_specified_algs() -> None:
@@ -86,6 +90,11 @@ class VerifiedSignature:
86
90
  sub: str | None = None # AAuth agent id (token `sub`)
87
91
  label: str = ""
88
92
  claims: dict[str, Any] = field(default_factory=dict) # AAuth token claims (redacted)
93
+ # Set only when ``verify(..., allow_expired_auth_token=True)`` accepted an
94
+ # auth token PAST its exp: genuine (issuer signature + proof of possession
95
+ # verified) but NOT valid for access. BudgetMiddleware uses it to answer
96
+ # with the final-record challenge; nothing else should ever see it True.
97
+ expired: bool = False
89
98
 
90
99
  def context(self) -> dict[str, Any]:
91
100
  """A flat dict suitable for logging / policy engines / audit trails."""
@@ -164,18 +173,28 @@ class HttpsigVerifier:
164
173
  self._cache: dict[str, tuple[float, dict[str, Any] | None]] = {}
165
174
 
166
175
  async def verify(
167
- self, method: str, url: str, headers: Mapping[str, str]
176
+ self, method: str, url: str, headers: Mapping[str, str],
177
+ *, allow_expired_auth_token: bool = False,
168
178
  ) -> VerifiedSignature | None:
169
179
  """Verify the request's agent signature. Returns ``None`` when there is
170
180
  no ``Signature`` header, the signature is invalid, or the signer's keys
171
- cannot be (safely) fetched — never raises on untrusted input."""
181
+ cannot be (safely) fetched — never raises on untrusted input.
182
+
183
+ ``allow_expired_auth_token`` (default False — leave it so for access
184
+ decisions) lets a genuine ``aa-auth+jwt`` past its ``exp`` come back
185
+ with ``expired=True`` instead of ``None``, for up to
186
+ :data:`EXPIRED_AUTH_TOKEN_GRACE` seconds. Budgets need this: the
187
+ resource owes the holder of an expired token a challenge carrying that
188
+ token's final consumption record (draft §Budget Exhaustion), and it
189
+ cannot build one for a token it refused to look at."""
172
190
  hdrs = {str(k): str(v) for k, v in headers.items()}
173
191
  if not any(k.lower() == "signature" for k in hdrs):
174
192
  return None
175
193
  result: VerifiedSignature | None = None
176
194
  try:
177
195
  if any(k.lower() == "signature-key" for k in hdrs):
178
- result = await self._verify_aauth(method, url, hdrs)
196
+ result = await self._verify_aauth(
197
+ method, url, hdrs, allow_expired_auth_token=allow_expired_auth_token)
179
198
  if result is None:
180
199
  result = await self._verify_web_bot_auth(method, url, hdrs)
181
200
  except Exception as exc: # noqa: BLE001 — belt and braces
@@ -288,7 +307,8 @@ class HttpsigVerifier:
288
307
  # ── AAuth (identity-based mode) ──────────────────────────────────────────
289
308
 
290
309
  async def _verify_aauth(
291
- self, method: str, url: str, headers: dict[str, str]
310
+ self, method: str, url: str, headers: dict[str, str],
311
+ *, allow_expired_auth_token: bool = False,
292
312
  ) -> VerifiedSignature | None:
293
313
  try:
294
314
  import jwt as pyjwt # the [aauth] extra
@@ -387,6 +407,7 @@ class HttpsigVerifier:
387
407
  continue
388
408
  if issuer_key is None:
389
409
  return None
410
+ tolerate_exp = allow_expired_auth_token and typ == AAUTH_AUTH_TYP
390
411
  try:
391
412
  claims = pyjwt.decode(
392
413
  token,
@@ -396,11 +417,20 @@ class HttpsigVerifier:
396
417
  options={
397
418
  "require": ["iss", "sub", "exp", "iat"],
398
419
  "verify_aud": audience is not None,
420
+ "verify_exp": not tolerate_exp,
399
421
  },
400
422
  )
401
423
  except Exception as exc: # noqa: BLE001
402
424
  logger.info("aauth token invalid iss=%s: %s", iss, str(exc)[:200])
403
425
  return None
426
+ expired = False
427
+ if tolerate_exp:
428
+ overdue = int(time.time()) - int(claims.get("exp", 0))
429
+ expired = overdue >= 0
430
+ if overdue > EXPIRED_AUTH_TOKEN_GRACE:
431
+ logger.info("aauth auth token expired %ss ago — past grace iss=%s",
432
+ overdue, iss)
433
+ return None
404
434
 
405
435
  # -11: person and auth tokens live at most one hour.
406
436
  if typ in (AAUTH_PERSON_TYP, AAUTH_AUTH_TYP):
@@ -456,4 +486,5 @@ class HttpsigVerifier:
456
486
  "budget") # budgets: the envelope rides in the token
457
487
  if k in claims
458
488
  },
489
+ expired=expired,
459
490
  )
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: regent-httpsig
3
- Version: 0.5.0
3
+ Version: 0.5.1
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
@@ -174,6 +174,11 @@ production on [get4agent.com](https://get4agent.com).
174
174
 
175
175
  - `insufficient-budget` refusals carry **`required`** — the refused request's
176
176
  maximum cost — so the agent lowers its bound and retries instead of guessing.
177
+ - An **expired** auth token gets the base protocol's plain challenge with a
178
+ resource token carrying that token's **final** consumption record — the
179
+ figure its issuer needs to settle the allocation (a record stated at or
180
+ after `exp` is final; one on a live token is a snapshot and releases
181
+ nothing).
177
182
  - **Streaming** responses run in the draft's cost-omitted mode: `reserved` in
178
183
  the header, commit when the stream ends (set `request.state.budget_cost`
179
184
  mid-stream if you learn the actual), and the agent recovers the exact cost
@@ -2,15 +2,15 @@ regent_httpsig/__init__.py,sha256=Ch-PdsMDo_uKG4U5A4xklU3jbCWdJTWXHG86n5VA7dc,17
2
2
  regent_httpsig/budget.py,sha256=sjNJiFyfqLHEdnbh8e4bmqZr2gPveYynZ5eXUYpES_k,16967
3
3
  regent_httpsig/cli.py,sha256=WUSLQ2WuEX4E85L2C2EgoUfu5cWpj6MRSG1UVNHpzcw,2005
4
4
  regent_httpsig/config.py,sha256=_xAIFYAyNbXzKg-famXLAs7eNdYwuvNA7NHQxcno0G4,2439
5
- regent_httpsig/fastapi.py,sha256=IijwDjnDKntRzavFzj2o6HM3XqvCHi2VZOv_xL_MLTA,15660
5
+ regent_httpsig/fastapi.py,sha256=RGkEHsNchEac7fXNYs2CT_MOETDktCxHcgQGwytSCCI,17714
6
6
  regent_httpsig/jwk.py,sha256=h4vgnIgpnyKeWdWpm7g_hEyXZOPVREWn-bD4JN07tT0,1637
7
7
  regent_httpsig/netguard.py,sha256=Sqg08mdC94RWvnQLJaH4weZW0nN2VlTJF5wVF8VYGHY,2121
8
- regent_httpsig/sfv.py,sha256=O8eK3Xyw-lewSepLJQcBKfPZAIBZCYatw4zDNDsxxYo,7407
8
+ regent_httpsig/sfv.py,sha256=-nUUjyqyAMOSGro9Z0AIXiuchqsIAVaJWbKuIIO4fB0,7624
9
9
  regent_httpsig/sign.py,sha256=B5ChxFxuuKL0i10bGrgFImzyh8GMjWIqNDECXehBWTA,4397
10
10
  regent_httpsig/usage.py,sha256=PSIPXCtUZyh5cjn4SzwOgrXuJrwDIWu-kffJ-4NFeS0,9453
11
- regent_httpsig/verify.py,sha256=8z-x3trF5B8P8D1aDYoqzF4R5h8BVv91CKiubFKFIiI,19915
12
- regent_httpsig-0.5.0.dist-info/METADATA,sha256=9_2zaZrS2LBdENWDPnYVWrJhtIh9vgbG_7e7J5f3X_s,12187
13
- regent_httpsig-0.5.0.dist-info/WHEEL,sha256=zOwg4jB6zX2kU910N-cMawjivD6tO8NEWvE12je1bVk,87
14
- regent_httpsig-0.5.0.dist-info/entry_points.txt,sha256=SgZdmc27V14IAmwOjbBoCYLsbrALaqdTUHNHLbil2dU,59
15
- regent_httpsig-0.5.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
16
- regent_httpsig-0.5.0.dist-info/RECORD,,
11
+ regent_httpsig/verify.py,sha256=p9VtHZz9HWHIstDBxNvVrc_xJdubbRA_pN9DjQQDzpk,21716
12
+ regent_httpsig-0.5.1.dist-info/METADATA,sha256=AWYCmTad0KRJFx6ODUZso9fyUcvN6CdU2fbxh0-LTXw,12496
13
+ regent_httpsig-0.5.1.dist-info/WHEEL,sha256=zOwg4jB6zX2kU910N-cMawjivD6tO8NEWvE12je1bVk,87
14
+ regent_httpsig-0.5.1.dist-info/entry_points.txt,sha256=SgZdmc27V14IAmwOjbBoCYLsbrALaqdTUHNHLbil2dU,59
15
+ regent_httpsig-0.5.1.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
16
+ regent_httpsig-0.5.1.dist-info/RECORD,,