regent-httpsig 0.7.3__py3-none-any.whl → 0.8.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.
- regent_httpsig/__init__.py +5 -1
- regent_httpsig/config.py +68 -5
- regent_httpsig/fastapi.py +81 -19
- regent_httpsig/jwk.py +97 -13
- regent_httpsig/netguard.py +10 -1
- regent_httpsig/replay.py +141 -0
- regent_httpsig/sfv.py +74 -8
- regent_httpsig/verify.py +495 -115
- regent_httpsig-0.8.0.dist-info/METADATA +549 -0
- regent_httpsig-0.8.0.dist-info/RECORD +18 -0
- {regent_httpsig-0.7.3.dist-info → regent_httpsig-0.8.0.dist-info}/WHEEL +1 -1
- regent_httpsig-0.7.3.dist-info/METADATA +0 -309
- regent_httpsig-0.7.3.dist-info/RECORD +0 -17
- {regent_httpsig-0.7.3.dist-info → regent_httpsig-0.8.0.dist-info}/entry_points.txt +0 -0
- {regent_httpsig-0.7.3.dist-info → regent_httpsig-0.8.0.dist-info}/licenses/LICENSE +0 -0
regent_httpsig/verify.py
CHANGED
|
@@ -3,13 +3,17 @@
|
|
|
3
3
|
Two schemes are accepted side by side (both ride the same ``Signature`` /
|
|
4
4
|
``Signature-Input`` headers; the difference is where the public key comes from):
|
|
5
5
|
|
|
6
|
-
- **Web Bot Auth** (draft-
|
|
7
|
-
|
|
8
|
-
``
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
6
|
+
- **Web Bot Auth** (draft-ietf-webbotauth-httpsig-protocol-01): the agent
|
|
7
|
+
signs with ``tag="web-bot-auth"`` and names, in ``Signature-Agent``, where
|
|
8
|
+
its Ed25519 JWK Set is published. Both wire forms of ``Signature-Agent`` are
|
|
9
|
+
accepted: the sf-dictionary (a member covered with ``;key=``) and the legacy
|
|
10
|
+
bare sf-string OpenAI's Cloud browser sends. A bare origin
|
|
11
|
+
(``"https://chatgpt.com"``) resolves to
|
|
12
|
+
``{origin}/.well-known/http-message-signatures-directory`` as in every draft
|
|
13
|
+
before -01; any other URL is fetched directly as the JWK Set (-01 §5.5).
|
|
14
|
+
The signature must cover ``@authority`` (or ``@target-uri``) and the member
|
|
15
|
+
it is attributed to, and carry ``expires`` (-01 §5.2); ``expires`` has no
|
|
16
|
+
grace.
|
|
13
17
|
- **AAuth** (draft-hardt-oauth-aauth-protocol-11): the agent carries a JWT in
|
|
14
18
|
the ``Signature-Key`` header under the ``jwt`` scheme — an agent token
|
|
15
19
|
(``typ: aa-agent+jwt``), a person token (``aa-person+jwt``) or an auth token
|
|
@@ -17,7 +21,12 @@ Two schemes are accepted side by side (both ride the same ``Signature`` /
|
|
|
17
21
|
``{iss}/.well-known/{dwk}``, verifies the token; the token's ``cnf.jwk``
|
|
18
22
|
verifies the request signature (proof of possession). Servers (a PS or AS
|
|
19
23
|
calling a resource's usage or revocation endpoint) sign under the ``jwks_uri``
|
|
20
|
-
scheme with ``id``, ``dwk`` and ``kid
|
|
24
|
+
scheme with ``id``, ``dwk`` and ``kid``; :meth:`HttpsigVerifier.verify` accepts
|
|
25
|
+
that scheme only from a server pinned in ``trusted_ps``. Requires the
|
|
26
|
+
``[aauth]`` extra.
|
|
27
|
+
|
|
28
|
+
``VerifiedSignature.keyid`` is always the RFC 7638 thumbprint of the key that
|
|
29
|
+
verified the signature. It is an identity only together with ``scheme``.
|
|
21
30
|
|
|
22
31
|
Failures are typed, not silent: :meth:`HttpsigVerifier.verify_detailed` returns
|
|
23
32
|
a :class:`VerificationError` carrying the ``Signature-Error`` code of
|
|
@@ -37,6 +46,7 @@ import asyncio
|
|
|
37
46
|
import base64
|
|
38
47
|
import hashlib
|
|
39
48
|
import logging
|
|
49
|
+
import re
|
|
40
50
|
import time
|
|
41
51
|
from collections.abc import Awaitable, Callable, Mapping
|
|
42
52
|
from dataclasses import dataclass, field
|
|
@@ -49,16 +59,18 @@ from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
|
|
|
49
59
|
from http_message_signatures import HTTPMessageVerifier # type: ignore[attr-defined]
|
|
50
60
|
|
|
51
61
|
from regent_httpsig.config import HttpsigConfig
|
|
52
|
-
from regent_httpsig.jwk import jwk_thumbprint, load_ed25519_jwk
|
|
62
|
+
from regent_httpsig.jwk import b64url, check_jwk_members, jwk_thumbprint, load_ed25519_jwk
|
|
53
63
|
from regent_httpsig.netguard import NotPublicURL, assert_public_url
|
|
64
|
+
from regent_httpsig.replay import ReplayGuard, ReplayGuardFull
|
|
54
65
|
from regent_httpsig.sfv import (
|
|
55
66
|
ED25519,
|
|
56
67
|
DictKeyComponentResolver,
|
|
57
68
|
Message,
|
|
58
69
|
StaticKeyResolver,
|
|
59
|
-
|
|
70
|
+
parse_covered_components,
|
|
60
71
|
parse_signature_input,
|
|
61
72
|
parse_signature_key,
|
|
73
|
+
signature_agent_member,
|
|
62
74
|
)
|
|
63
75
|
|
|
64
76
|
__all__ = [
|
|
@@ -74,6 +86,12 @@ logger = logging.getLogger("regent_httpsig")
|
|
|
74
86
|
|
|
75
87
|
WBA_TAG = "web-bot-auth"
|
|
76
88
|
WBA_DIRECTORY_PATH = "/.well-known/http-message-signatures-directory"
|
|
89
|
+
# Web Bot Auth: how far `created` may be ahead of our clock (the upstream
|
|
90
|
+
# library's tolerance, kept). `expires` gets none.
|
|
91
|
+
WBA_CLOCK_SKEW_SECONDS = 5
|
|
92
|
+
# Components @target-uri contains, so covering it covers them (-01 §5.2).
|
|
93
|
+
_TARGET_URI_PARTS = frozenset({"@scheme", "@authority", "@path", "@query"})
|
|
94
|
+
_BODY_COMPONENTS = ("content-digest", "content-type")
|
|
77
95
|
AAUTH_METADATA_PATH = "/.well-known/aauth-agent.json"
|
|
78
96
|
AAUTH_PERSON_METADATA_PATH = "/.well-known/aauth-person.json"
|
|
79
97
|
AAUTH_JWT_TYP = "aa-agent+jwt"
|
|
@@ -97,6 +115,85 @@ _ALG_TABLE: dict[str, tuple[str, str, str | None]] = {
|
|
|
97
115
|
RevocationCheck = Callable[[str, str], Awaitable[bool]]
|
|
98
116
|
|
|
99
117
|
|
|
118
|
+
def _now() -> int:
|
|
119
|
+
"""The verifier's clock in whole seconds — the one place time is read, so
|
|
120
|
+
every `created`/`expires`/`exp` decision uses the same instant."""
|
|
121
|
+
return int(time.time())
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _monotonic() -> float:
|
|
125
|
+
"""The directory cache's clock (one place, so its expiry can be tested)."""
|
|
126
|
+
return time.monotonic()
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _covers(covered: list[str], component: str, *, target_uri: bool = False) -> bool:
|
|
130
|
+
if component in covered:
|
|
131
|
+
return True
|
|
132
|
+
return target_uri and component in _TARGET_URI_PARTS and "@target-uri" in covered
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def _split_agent_url(value: str) -> tuple[str, str, str] | None:
|
|
136
|
+
"""A ``Signature-Agent`` URL → ``(scheme, fetch URL, identifier)``, or None
|
|
137
|
+
when it is not an absolute http(s) URL with a host and no userinfo.
|
|
138
|
+
|
|
139
|
+
A bare origin (empty path or ``/``) and the well-known directory URL itself
|
|
140
|
+
both resolve to ``{origin}/.well-known/http-message-signatures-directory``
|
|
141
|
+
and are identified by the origin — what every Web Bot Auth signer sends
|
|
142
|
+
today, and the identifier 0.7 reported. Any other URL is the JWK Set itself
|
|
143
|
+
(-01 §5.5), identified by the URL without its query. Identifiers are
|
|
144
|
+
normalized as -01 §5.5 asks (RFC 3986 §6.2.2 and §6.2.3: scheme and host
|
|
145
|
+
lowercase, default port dropped, percent-encoded unreserved characters
|
|
146
|
+
decoded and other escapes uppercased, dot segments removed) so one key set
|
|
147
|
+
is not reported under several spellings; the normalized URL is fetched."""
|
|
148
|
+
try:
|
|
149
|
+
parts = urlsplit(value.strip())
|
|
150
|
+
scheme = parts.scheme.lower()
|
|
151
|
+
host = parts.hostname or ""
|
|
152
|
+
port = parts.port
|
|
153
|
+
except ValueError:
|
|
154
|
+
return None
|
|
155
|
+
if scheme not in ("https", "http") or not host or "@" in parts.netloc:
|
|
156
|
+
return None
|
|
157
|
+
default = 443 if scheme == "https" else 80
|
|
158
|
+
hostport = f"[{host}]" if ":" in host else host
|
|
159
|
+
if port is not None and port != default:
|
|
160
|
+
hostport += f":{port}"
|
|
161
|
+
origin = f"{scheme}://{hostport}"
|
|
162
|
+
path = _normalize_path(parts.path)
|
|
163
|
+
if path in ("", "/", WBA_DIRECTORY_PATH):
|
|
164
|
+
return scheme, origin + WBA_DIRECTORY_PATH, origin
|
|
165
|
+
fetch = origin + path + (f"?{parts.query}" if parts.query else "")
|
|
166
|
+
return scheme, fetch, origin + path
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
_UNRESERVED = frozenset("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~")
|
|
170
|
+
_PERCENT = re.compile(r"%([0-9A-Fa-f]{2})")
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def _normalize_path(path: str) -> str:
|
|
174
|
+
"""RFC 3986 §6.2.2 for a path: percent-encoding (unreserved characters
|
|
175
|
+
decoded, other escapes in uppercase hex), then §5.2.4 dot-segment removal."""
|
|
176
|
+
def escape(match: re.Match[str]) -> str:
|
|
177
|
+
char = chr(int(match.group(1), 16))
|
|
178
|
+
return char if char in _UNRESERVED else "%" + match.group(1).upper()
|
|
179
|
+
|
|
180
|
+
path = _PERCENT.sub(escape, path)
|
|
181
|
+
if not path.startswith("/"):
|
|
182
|
+
return path
|
|
183
|
+
segments = path.split("/")[1:]
|
|
184
|
+
out: list[str] = []
|
|
185
|
+
for i, segment in enumerate(segments):
|
|
186
|
+
last = i == len(segments) - 1
|
|
187
|
+
if segment in (".", ".."):
|
|
188
|
+
if segment == ".." and out:
|
|
189
|
+
out.pop()
|
|
190
|
+
if last:
|
|
191
|
+
out.append("")
|
|
192
|
+
continue
|
|
193
|
+
out.append(segment)
|
|
194
|
+
return "/" + "/".join(out)
|
|
195
|
+
|
|
196
|
+
|
|
100
197
|
def _register_fully_specified_algs() -> None:
|
|
101
198
|
"""Register 'Ed25519' (RFC 9864 fully-specified) with PyJWT — same math as
|
|
102
199
|
the polymorphic 'EdDSA', which AAuth -11 forbids implementations to accept."""
|
|
@@ -115,11 +212,17 @@ class VerifiedSignature:
|
|
|
115
212
|
|
|
116
213
|
scheme: str # "web-bot-auth" | "aauth" | "aauth-person" | "aauth-auth" | "aauth-server"
|
|
117
214
|
agent: str # WBA: Signature-Agent origin; AAuth: the token issuer / the server id
|
|
118
|
-
|
|
215
|
+
# RFC 7638 / RFC 8037 A.3 thumbprint of the key that verified the signature,
|
|
216
|
+
# in every scheme. It names a key, not who holds it: treat it as an identity
|
|
217
|
+
# only together with `scheme` (and `agent`) — a Web Bot Auth key, an AAuth
|
|
218
|
+
# cnf key and a server key are different things even when one party holds all.
|
|
219
|
+
keyid: str
|
|
119
220
|
trusted: bool # agent/issuer is on the configured trust list
|
|
120
221
|
sub: str | None = None # AAuth agent id (token `sub`)
|
|
121
222
|
label: str = ""
|
|
122
|
-
|
|
223
|
+
# AAuth: token claims (redacted). Web Bot Auth: "directory" (the URL the key
|
|
224
|
+
# was fetched from, query included) and "jwk" (the key, RFC 7638 members).
|
|
225
|
+
claims: dict[str, Any] = field(default_factory=dict)
|
|
123
226
|
|
|
124
227
|
def context(self) -> dict[str, Any]:
|
|
125
228
|
"""A flat dict suitable for logging / policy engines / audit trails."""
|
|
@@ -186,9 +289,10 @@ class _KeyidOptionalParams(dict): # type: ignore[type-arg]
|
|
|
186
289
|
|
|
187
290
|
class _KeyidOptionalVerifier(HTTPMessageVerifier):
|
|
188
291
|
def validate_created_and_expires(self, sig_input: Any, max_age: Any = None) -> None:
|
|
189
|
-
"""No-op:
|
|
190
|
-
|
|
191
|
-
the
|
|
292
|
+
"""No-op: `created` and `expires` were judged in ``_check_signature_input``
|
|
293
|
+
(the -11 window on the AAuth path, the -01 rules on the Web Bot Auth
|
|
294
|
+
path) with the drafts' own error codes. The upstream rule — 5 seconds
|
|
295
|
+
of skew applied to `expires` too — must not pre-empt or loosen them."""
|
|
192
296
|
|
|
193
297
|
def _verify_one(self, *, label: Any, sig_input: Any, signature: Any,
|
|
194
298
|
message: Any, max_age: Any) -> Any:
|
|
@@ -200,6 +304,23 @@ class _KeyidOptionalVerifier(HTTPMessageVerifier):
|
|
|
200
304
|
)
|
|
201
305
|
|
|
202
306
|
|
|
307
|
+
def _partition(url: str) -> str:
|
|
308
|
+
"""The replay guard's partition: the host alone — the ASCII host httpx
|
|
309
|
+
actually connects to (IDNA 2008, as httpx encodes it), lowercase, trailing
|
|
310
|
+
dot stripped; scheme and port ignored, so one host does not become several
|
|
311
|
+
partitions by serving on several ports or spellings. Python's own ``idna``
|
|
312
|
+
codec (IDNA 2003) is not used: it folds ß into ss and so merges hosts
|
|
313
|
+
httpx keeps apart."""
|
|
314
|
+
try:
|
|
315
|
+
host = httpx.URL(url.strip()).raw_host.decode("ascii")
|
|
316
|
+
except Exception: # noqa: BLE001 — not a URL httpx would connect to
|
|
317
|
+
try:
|
|
318
|
+
host = urlsplit(url.strip()).hostname or ""
|
|
319
|
+
except ValueError:
|
|
320
|
+
host = ""
|
|
321
|
+
return host.rstrip(".").lower() or url
|
|
322
|
+
|
|
323
|
+
|
|
203
324
|
def _keys_from_jwks(doc: dict[str, Any]) -> dict[str, Ed25519PublicKey]:
|
|
204
325
|
keys: dict[str, Ed25519PublicKey] = {}
|
|
205
326
|
for jwk in list(doc.get("keys") or [])[:10]:
|
|
@@ -210,6 +331,28 @@ def _keys_from_jwks(doc: dict[str, Any]) -> dict[str, Ed25519PublicKey]:
|
|
|
210
331
|
return keys
|
|
211
332
|
|
|
212
333
|
|
|
334
|
+
def _wba_select(doc: dict[str, Any], keyid: str) -> tuple[str, Ed25519PublicKey] | None:
|
|
335
|
+
"""The directory key a Web Bot Auth ``keyid`` names → ``(thumbprint, key)``.
|
|
336
|
+
|
|
337
|
+
-01 §5.2 makes keyid the key's thumbprint, and §5.5 has the verifier match
|
|
338
|
+
it against ``kid``, which at the well-known URI MUST be that thumbprint.
|
|
339
|
+
Deployed directories do not all follow that (Google-Agent's kids are short
|
|
340
|
+
labels), so a thumbprint match comes first and a ``kid`` match second. The
|
|
341
|
+
lookup stays within this one directory, and the thumbprint — never the
|
|
342
|
+
label — is what the caller reports."""
|
|
343
|
+
keys = _keys_from_jwks(doc)
|
|
344
|
+
if keyid in keys:
|
|
345
|
+
return keyid, keys[keyid]
|
|
346
|
+
for jwk in list(doc.get("keys") or [])[:10]:
|
|
347
|
+
if isinstance(jwk, dict) and jwk.get("kid") == keyid:
|
|
348
|
+
try:
|
|
349
|
+
thumbprint = jwk_thumbprint(jwk)
|
|
350
|
+
except Exception: # noqa: BLE001
|
|
351
|
+
return None
|
|
352
|
+
return (thumbprint, keys[thumbprint]) if thumbprint in keys else None
|
|
353
|
+
return None
|
|
354
|
+
|
|
355
|
+
|
|
213
356
|
class _Refused(Exception):
|
|
214
357
|
"""Internal: carries a VerificationError out of the AAuth path."""
|
|
215
358
|
|
|
@@ -236,6 +379,7 @@ def _load_public_key(jwk: dict[str, Any]) -> tuple[Any, Any]:
|
|
|
236
379
|
if jwk.get("kty") != kty or (crv is not None and jwk.get("crv") != crv):
|
|
237
380
|
raise _refuse("invalid_key", f"key type disagrees with alg {alg}")
|
|
238
381
|
try:
|
|
382
|
+
check_jwk_members(jwk) # canonical base64url only: one key, one keyid
|
|
239
383
|
if alg == "Ed25519":
|
|
240
384
|
key: Any = load_ed25519_jwk(jwk)
|
|
241
385
|
else:
|
|
@@ -255,6 +399,9 @@ class HttpsigVerifier:
|
|
|
255
399
|
shared :class:`httpx.AsyncClient` to reuse its pool. ``is_revoked(iss,
|
|
256
400
|
jti)`` is how the application tells the verifier about revocations it has
|
|
257
401
|
received (§11.12.5): a token it says yes for is answered ``revoked_jwt``.
|
|
402
|
+
``replay_guard`` (opt-in, see :mod:`regent_httpsig.replay`) refuses a
|
|
403
|
+
signature presented a second time within its validity, on every path;
|
|
404
|
+
without one a valid signature can be replayed until it expires.
|
|
258
405
|
|
|
259
406
|
Usage::
|
|
260
407
|
|
|
@@ -270,13 +417,20 @@ class HttpsigVerifier:
|
|
|
270
417
|
*,
|
|
271
418
|
http_client: httpx.AsyncClient | None = None,
|
|
272
419
|
is_revoked: RevocationCheck | None = None,
|
|
420
|
+
replay_guard: ReplayGuard | None = None,
|
|
273
421
|
) -> None:
|
|
274
422
|
self.config = config or HttpsigConfig()
|
|
423
|
+
self._replay_guard = replay_guard
|
|
275
424
|
self._http = http_client
|
|
276
425
|
self._owns_client = http_client is None
|
|
277
426
|
self._is_revoked = is_revoked
|
|
278
|
-
# url -> (expires_monotonic, parsed JSON | None for negative entries
|
|
279
|
-
|
|
427
|
+
# url -> (expires_monotonic, parsed JSON | None for negative entries,
|
|
428
|
+
# monotonic time until which a Web Bot Auth reader may be served
|
|
429
|
+
# the last good copy, that last good copy). A failed refetch is
|
|
430
|
+
# always stored as a negative entry: the stale copy is handed out
|
|
431
|
+
# only to stale_ok readers, never to the AAuth path.
|
|
432
|
+
self._cache: dict[
|
|
433
|
+
str, tuple[float, dict[str, Any] | None, float, dict[str, Any] | None]] = {}
|
|
280
434
|
|
|
281
435
|
async def verify(
|
|
282
436
|
self, method: str, url: str, headers: Mapping[str, str],
|
|
@@ -295,19 +449,18 @@ class HttpsigVerifier:
|
|
|
295
449
|
) -> VerifiedSignature | VerificationError | None:
|
|
296
450
|
"""Like :meth:`verify`, but a failure comes back as a
|
|
297
451
|
:class:`VerificationError` (``None`` only when no ``Signature`` header is
|
|
298
|
-
present at all). ``body`` enables the
|
|
299
|
-
given and non-empty, ``content-digest`` and ``content-type`` must be
|
|
300
|
-
covered
|
|
301
|
-
|
|
302
|
-
|
|
452
|
+
present at all). ``body`` enables the body rules: on the AAuth path,
|
|
453
|
+
when given and non-empty, ``content-digest`` and ``content-type`` must be
|
|
454
|
+
covered (-11); on the Web Bot Auth path ``content-digest`` must be
|
|
455
|
+
covered when ``wba_required_components`` lists it. Whenever a covered
|
|
456
|
+
``Content-Digest`` and the body are both present, the digest must match."""
|
|
457
|
+
if not any(str(k).lower() == "signature" for k in headers):
|
|
303
458
|
return None
|
|
304
459
|
try:
|
|
305
|
-
|
|
460
|
+
hdrs = _normalize_headers(headers)
|
|
461
|
+
if "signature-key" in hdrs:
|
|
306
462
|
return await self._verify_signature_key(method, url, hdrs, body)
|
|
307
|
-
result = await self._verify_web_bot_auth(method, url, hdrs)
|
|
308
|
-
if result is None:
|
|
309
|
-
return VerificationError("invalid_signature",
|
|
310
|
-
"Web Bot Auth signature did not verify")
|
|
463
|
+
result = await self._verify_web_bot_auth(method, url, hdrs, body)
|
|
311
464
|
logger.info("httpsig verified scheme=%s agent=%s keyid=%s trusted=%s",
|
|
312
465
|
result.scheme, result.agent, result.keyid[:16], result.trusted)
|
|
313
466
|
return result
|
|
@@ -324,9 +477,11 @@ class HttpsigVerifier:
|
|
|
324
477
|
) -> VerifiedSignature | VerificationError:
|
|
325
478
|
"""Verify a request a *server* signed under the ``jwks_uri`` scheme
|
|
326
479
|
(§11.3.2): a PS or AS at a revocation or usage endpoint. The caller is
|
|
327
|
-
identified by ``id``; ``trusted`` says whether it is a configured PS.
|
|
328
|
-
|
|
480
|
+
identified by ``id``; ``trusted`` says whether it is a configured PS.
|
|
481
|
+
Unlike :meth:`verify`, a server missing from ``trusted_ps`` is verified
|
|
482
|
+
too (``trusted=False``) — the endpoint decides whether to accept it."""
|
|
329
483
|
try:
|
|
484
|
+
hdrs = _normalize_headers(headers)
|
|
330
485
|
members = parse_signature_key(_header(hdrs, "signature-key"))
|
|
331
486
|
if not members:
|
|
332
487
|
raise _refuse("invalid_signature", "Signature-Key header missing or malformed")
|
|
@@ -355,26 +510,46 @@ class HttpsigVerifier:
|
|
|
355
510
|
|
|
356
511
|
def _cache_get(self, url: str) -> tuple[bool, dict[str, Any] | None]:
|
|
357
512
|
entry = self._cache.get(url)
|
|
358
|
-
if entry and entry[0] >
|
|
513
|
+
if entry and entry[0] > _monotonic():
|
|
359
514
|
return True, entry[1]
|
|
360
515
|
return False, None
|
|
361
516
|
|
|
362
|
-
def _cache_put(self, url: str, doc: dict[str, Any] | None, ttl: float
|
|
363
|
-
|
|
517
|
+
def _cache_put(self, url: str, doc: dict[str, Any] | None, ttl: float,
|
|
518
|
+
stale_until: float = 0.0, last_good: dict[str, Any] | None = None) -> None:
|
|
519
|
+
if url not in self._cache and len(self._cache) >= self.config.cache_max_entries:
|
|
364
520
|
# Evict the soonest-to-expire entry; bounds memory against keyid spam.
|
|
365
521
|
self._cache.pop(min(self._cache, key=lambda k: self._cache[k][0]), None)
|
|
366
|
-
self._cache[url] = (
|
|
522
|
+
self._cache[url] = (_monotonic() + ttl, doc, stale_until, last_good)
|
|
367
523
|
|
|
368
524
|
def _cache_forget(self, url: str) -> None:
|
|
369
|
-
|
|
525
|
+
"""Force the next read to refetch ``url`` (AAuth key rotation). The
|
|
526
|
+
entry is expired, not deleted: the last good copy and its allowance
|
|
527
|
+
stay for Web Bot Auth readers of the same URL, so a stranger's token
|
|
528
|
+
with an unknown kid cannot take a directory's stale copy away."""
|
|
529
|
+
entry = self._cache.get(url)
|
|
530
|
+
if entry is not None:
|
|
531
|
+
self._cache[url] = (0.0, None, entry[2], entry[3])
|
|
370
532
|
|
|
371
|
-
async def _fetch_json(self, url: str) -> dict[str, Any] | None:
|
|
533
|
+
async def _fetch_json(self, url: str, *, stale_ok: bool = False) -> dict[str, Any] | None:
|
|
372
534
|
"""Fetch an attacker-nameable identity document safely: https-only
|
|
373
|
-
(except allow-listed dev hosts), public-IP-only, size-capped, cached.
|
|
535
|
+
(except allow-listed dev hosts), public-IP-only, size-capped, cached.
|
|
536
|
+
|
|
537
|
+
``stale_ok`` (Web Bot Auth directories, -01 §6.10): a failed refetch is
|
|
538
|
+
not evidence, so the last good copy keeps being served — for at most
|
|
539
|
+
``wba_max_stale_seconds`` after it went stale, after which a failed
|
|
540
|
+
refetch is a failure. Only a successful fetch replaces the copy,
|
|
541
|
+
including one that no longer lists a key, which is how a removed key
|
|
542
|
+
stops verifying. Without it (AAuth issuer and server JWKS) a failure
|
|
543
|
+
is a failure, as in 0.7: a failed refetch is stored as a negative
|
|
544
|
+
entry for every reader, and the stale copy is decided per read, so it
|
|
545
|
+
never reaches a reader that did not ask for it."""
|
|
374
546
|
cfg = self.config
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
547
|
+
now = _monotonic()
|
|
548
|
+
entry = self._cache.get(url)
|
|
549
|
+
stale_until, last_good = (entry[2], entry[3]) if entry else (0.0, None)
|
|
550
|
+
stale = last_good if stale_ok and now < stale_until else None
|
|
551
|
+
if entry and entry[0] > now:
|
|
552
|
+
return entry[1] if entry[1] is not None else stale
|
|
378
553
|
try:
|
|
379
554
|
parsed = urlsplit(url)
|
|
380
555
|
if parsed.scheme != "https" and parsed.hostname not in cfg.insecure_hosts:
|
|
@@ -388,7 +563,8 @@ class HttpsigVerifier:
|
|
|
388
563
|
follow_redirects=False,
|
|
389
564
|
headers={"accept": "application/json"},
|
|
390
565
|
)
|
|
391
|
-
resp.
|
|
566
|
+
if resp.status_code != 200: # -01 §5.5: anything else is a discovery failure
|
|
567
|
+
raise ValueError(f"status {resp.status_code}, not 200")
|
|
392
568
|
if len(resp.content) > cfg.max_directory_bytes:
|
|
393
569
|
raise ValueError("directory too large")
|
|
394
570
|
doc = resp.json()
|
|
@@ -396,9 +572,12 @@ class HttpsigVerifier:
|
|
|
396
572
|
raise ValueError("directory is not a JSON object")
|
|
397
573
|
except Exception as exc: # noqa: BLE001 — any failure = unverifiable, not fatal
|
|
398
574
|
logger.info("directory fetch failed url=%s: %s", url, str(exc)[:200])
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
575
|
+
# Negative for everyone; the last good copy rides along for
|
|
576
|
+
# stale_ok readers, each read checking its allowance.
|
|
577
|
+
self._cache_put(url, None, cfg.negative_cache_ttl, stale_until, last_good)
|
|
578
|
+
return stale
|
|
579
|
+
self._cache_put(url, doc, cfg.cache_ttl,
|
|
580
|
+
now + cfg.cache_ttl + cfg.wba_max_stale_seconds, doc)
|
|
402
581
|
return doc
|
|
403
582
|
|
|
404
583
|
async def _jwks_key(self, jwks_url: str, kid: str | None) -> dict[str, Any]:
|
|
@@ -440,47 +619,71 @@ class HttpsigVerifier:
|
|
|
440
619
|
# ── Web Bot Auth ─────────────────────────────────────────────────────────
|
|
441
620
|
|
|
442
621
|
async def _verify_web_bot_auth(
|
|
443
|
-
self, method: str, url: str, headers: dict[str, str]
|
|
444
|
-
) -> VerifiedSignature
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
622
|
+
self, method: str, url: str, headers: dict[str, str], body: bytes | None,
|
|
623
|
+
) -> VerifiedSignature:
|
|
624
|
+
"""draft-ietf-webbotauth-httpsig-protocol-01 §5.4: the first signature
|
|
625
|
+
tagged ``web-bot-auth`` is checked on its own — components and times
|
|
626
|
+
first (no fetch for a signature that would be refused anyway), then
|
|
627
|
+
the covered ``Signature-Agent`` member is resolved, then the math."""
|
|
628
|
+
inputs = parse_signature_input(_header(headers, "signature-input"))
|
|
629
|
+
label = next((lbl for lbl, (_, p) in inputs.items() if p.get("tag") == WBA_TAG), None)
|
|
630
|
+
if label is None:
|
|
631
|
+
raise _refuse("invalid_signature", f'no signature is tagged "{WBA_TAG}"')
|
|
632
|
+
params = self._check_signature_input(headers, label, body, wba=True)
|
|
633
|
+
keyid = params.get("keyid")
|
|
634
|
+
if not isinstance(keyid, str) or not keyid:
|
|
635
|
+
raise _refuse("invalid_signature", "keyid parameter is required")
|
|
636
|
+
fetch_url, agent = self._wba_directory(headers, label)
|
|
637
|
+
directory = await self._fetch_json(fetch_url, stale_ok=True)
|
|
453
638
|
if not directory:
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
if
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
)
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
)
|
|
639
|
+
raise _refuse("invalid_signature", f"key directory {fetch_url} is unavailable")
|
|
640
|
+
selected = _wba_select(directory, keyid)
|
|
641
|
+
if selected is None:
|
|
642
|
+
raise _refuse("invalid_signature", f"keyid {keyid[:16]}… is not in {fetch_url}")
|
|
643
|
+
keyid, key = selected # from here on keyid is the thumbprint of the key
|
|
644
|
+
base = await self._verify_pop(method, url, headers, label, key, ED25519,
|
|
645
|
+
"Web Bot Auth signature failed", tag=WBA_TAG)
|
|
646
|
+
await self._check_replay(WBA_TAG, keyid, base, self._valid_until(params, wba=True),
|
|
647
|
+
agent)
|
|
648
|
+
trusted = any((_split_agent_url(t) or ("", "", t))[2] == agent
|
|
649
|
+
for t in self.config.trusted_agents)
|
|
650
|
+
# Where the key came from, exactly: `agent` is the identifier (query
|
|
651
|
+
# dropped, -01 §5.5); the URL fetched and the key it gave are kept here
|
|
652
|
+
# so a relying party can record both.
|
|
653
|
+
jwk = {"kty": "OKP", "crv": "Ed25519", "x": b64url(key.public_bytes_raw())}
|
|
654
|
+
return VerifiedSignature(scheme=WBA_TAG, agent=agent, keyid=keyid,
|
|
655
|
+
trusted=trusted, label=label,
|
|
656
|
+
claims={"directory": fetch_url, "jwk": jwk})
|
|
657
|
+
|
|
658
|
+
def _wba_directory(self, headers: dict[str, str], label: str) -> tuple[str, str]:
|
|
659
|
+
"""-01 §5.2.1/§5.2.2: the ``Signature-Agent`` member this signature
|
|
660
|
+
covers → ``(fetch URL, identifier)``. Never "the first member": a
|
|
661
|
+
signature is attributed only to a member it covers. The member keyed
|
|
662
|
+
by the signature's own label wins; the legacy bare String counts as one
|
|
663
|
+
member covered by ``"signature-agent"`` without ``;key=``."""
|
|
664
|
+
field_value = _header(headers, "signature-agent")
|
|
665
|
+
covered = [p for name, p in parse_covered_components(
|
|
666
|
+
_header(headers, "signature-input")).get(label, []) if name == "signature-agent"]
|
|
667
|
+
keys = [str(p["key"]) for p in covered if "key" in p]
|
|
668
|
+
candidates: list[str | None] = sorted(keys, key=lambda k: k != label)
|
|
669
|
+
if any("key" not in p for p in covered): # the whole field is covered
|
|
670
|
+
candidates += [None, label]
|
|
671
|
+
member = next((m for k in candidates
|
|
672
|
+
if (m := signature_agent_member(field_value, k)) is not None), None)
|
|
673
|
+
if member is None:
|
|
674
|
+
raise _refuse("invalid_input",
|
|
675
|
+
"signature covers no usable Signature-Agent member (an https URL "
|
|
676
|
+
"string, no parameters)", required_input=self._wba_required())
|
|
677
|
+
located = _split_agent_url(member)
|
|
678
|
+
host = urlsplit(member.strip()).hostname
|
|
679
|
+
if located is None or (located[0] != "https" and host not in self.config.insecure_hosts):
|
|
680
|
+
raise _refuse("invalid_key", "Signature-Agent is not an https URL with a host "
|
|
681
|
+
"and no userinfo")
|
|
682
|
+
return located[1], located[2]
|
|
683
|
+
|
|
684
|
+
def _wba_required(self) -> tuple[str, ...]:
|
|
685
|
+
required = tuple(self.config.wba_required_components)
|
|
686
|
+
return required if "signature-agent" in required else (*required, "signature-agent")
|
|
484
687
|
|
|
485
688
|
# ── AAuth: the Signature-Key header (§11.3) ──────────────────────────────
|
|
486
689
|
|
|
@@ -494,65 +697,178 @@ class HttpsigVerifier:
|
|
|
494
697
|
if scheme == "jwt":
|
|
495
698
|
return await self._verify_jwt_scheme(method, url, headers, body, label, params)
|
|
496
699
|
if scheme == "jwks_uri":
|
|
700
|
+
# A server names its own kid: on the generic path only a pinned
|
|
701
|
+
# server is an identity (verify_server() is the explicit entry).
|
|
702
|
+
server_id = str(params.get("id") or "")
|
|
703
|
+
cfg = self.config
|
|
704
|
+
if server_id not in cfg.trusted_ps and not cfg.allow_unpinned_servers:
|
|
705
|
+
raise _refuse("invalid_key", f"server {server_id or '(no id)'} is not a "
|
|
706
|
+
"configured PS/AS (trusted_ps)")
|
|
497
707
|
return await self._verify_server_scheme(method, url, headers, body, label, params)
|
|
498
708
|
raise _refuse("unsupported_scheme", f"scheme {scheme!r} is not accepted",
|
|
499
709
|
accept_schemes=AAUTH_ACCEPT_SCHEMES)
|
|
500
710
|
|
|
501
711
|
def _check_signature_input(
|
|
502
|
-
self, headers: dict[str, str], label: str, body: bytes | None,
|
|
503
|
-
) ->
|
|
504
|
-
"""
|
|
712
|
+
self, headers: dict[str, str], label: str, body: bytes | None, *, wba: bool = False,
|
|
713
|
+
) -> dict[str, Any]:
|
|
714
|
+
"""Covered components and times of signature ``label``; returns its params.
|
|
715
|
+
|
|
716
|
+
One check, two profiles. AAuth -11: §11.3.3.1 components (+ the body
|
|
717
|
+
components when there is a body), §11.3.4 step 3 ``created`` window.
|
|
718
|
+
Web Bot Auth -01 §5.2: ``wba_required_components`` (``@target-uri``
|
|
719
|
+
standing in for the parts it contains), ``created`` at most
|
|
720
|
+
``WBA_CLOCK_SKEW_SECONDS`` ahead and at most ``max_age_hours`` old,
|
|
721
|
+
``expires`` required by default, ``wba_max_validity_seconds``. Both:
|
|
722
|
+
no grace on ``expires`` (refused at or after it), and a covered
|
|
723
|
+
``Content-Digest`` is checked against the body when the body is given."""
|
|
505
724
|
inputs = parse_signature_input(_header(headers, "signature-input"))
|
|
506
725
|
if label not in inputs:
|
|
507
726
|
raise _refuse("invalid_signature", f"Signature-Input has no member {label!r}")
|
|
508
727
|
covered, params = inputs[label]
|
|
509
|
-
|
|
510
|
-
has_body =
|
|
511
|
-
if
|
|
512
|
-
required
|
|
513
|
-
|
|
728
|
+
cfg = self.config
|
|
729
|
+
has_body = _has_body(headers, body)
|
|
730
|
+
if wba:
|
|
731
|
+
required = [c for c in self._wba_required() if c not in _BODY_COMPONENTS or has_body]
|
|
732
|
+
else:
|
|
733
|
+
required = list(cfg.required_components)
|
|
734
|
+
if has_body:
|
|
735
|
+
required += list(_BODY_COMPONENTS)
|
|
736
|
+
missing = [c for c in required if not _covers(covered, c, target_uri=wba)]
|
|
514
737
|
if missing:
|
|
515
738
|
raise _refuse("invalid_input", f"signature does not cover {', '.join(missing)}",
|
|
516
739
|
required_input=tuple(required))
|
|
517
|
-
now =
|
|
518
|
-
|
|
519
|
-
created = params.get("created")
|
|
740
|
+
now = _now()
|
|
741
|
+
created, expires = params.get("created"), params.get("expires")
|
|
520
742
|
if not isinstance(created, int):
|
|
521
743
|
raise _refuse("invalid_signature", "created parameter is required")
|
|
522
|
-
if
|
|
523
|
-
raise _refuse("
|
|
524
|
-
if
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
744
|
+
if expires is not None and not isinstance(expires, int):
|
|
745
|
+
raise _refuse("invalid_signature", "expires parameter is not an integer")
|
|
746
|
+
if wba:
|
|
747
|
+
self._check_wba_times(created, expires, now)
|
|
748
|
+
else:
|
|
749
|
+
window = int(cfg.signature_window_seconds)
|
|
750
|
+
if created > now + window:
|
|
751
|
+
raise _refuse("clock_skew", "signature created ahead of the server's clock")
|
|
752
|
+
if created < now - window:
|
|
753
|
+
raise _refuse("invalid_signature",
|
|
754
|
+
"signature created outside the validity window")
|
|
755
|
+
if expires is not None and expires <= now:
|
|
528
756
|
raise _refuse("invalid_signature", "signature has expired")
|
|
529
|
-
if
|
|
757
|
+
if self._replay_guard is not None and created < now - int(cfg.replay_window_seconds):
|
|
758
|
+
# With a guard, admission is bounded too (-01 Appendix C.6): the guard
|
|
759
|
+
# never has to remember anyone's signature longer than the window.
|
|
760
|
+
raise _refuse("invalid_signature", f"signature created more than "
|
|
761
|
+
f"{cfg.replay_window_seconds} s ago (replay window)")
|
|
762
|
+
if "content-digest" in required and body is None:
|
|
763
|
+
# Required and covered, but nothing to check it against: a digest
|
|
764
|
+
# nobody compares with the body binds nothing.
|
|
765
|
+
raise _refuse("invalid_signature", "the request has a body that was not passed "
|
|
766
|
+
"to the verifier, so its Content-Digest cannot be checked")
|
|
767
|
+
if body is not None and "content-digest" in covered:
|
|
530
768
|
digest = _header(headers, "content-digest")
|
|
531
769
|
expected = "sha-256=:" + base64.b64encode(hashlib.sha256(body).digest()).decode() + ":"
|
|
532
770
|
if digest.replace(" ", "") != expected:
|
|
533
771
|
raise _refuse("invalid_signature", "Content-Digest does not match the body")
|
|
772
|
+
return params
|
|
773
|
+
|
|
774
|
+
def _check_wba_times(self, created: int, expires: int | None, now: int) -> None:
|
|
775
|
+
cfg = self.config
|
|
776
|
+
if created > now + WBA_CLOCK_SKEW_SECONDS:
|
|
777
|
+
raise _refuse("clock_skew", "signature created ahead of the server's clock")
|
|
778
|
+
if created < now - int(cfg.max_age_hours) * 3600:
|
|
779
|
+
raise _refuse("invalid_signature",
|
|
780
|
+
f"signature created more than {cfg.max_age_hours} hours ago")
|
|
781
|
+
limit = cfg.wba_max_validity_seconds
|
|
782
|
+
if expires is None:
|
|
783
|
+
if cfg.wba_require_expires:
|
|
784
|
+
raise _refuse("invalid_signature", "expires parameter is required")
|
|
785
|
+
if limit is not None and now - created > limit:
|
|
786
|
+
raise _refuse("invalid_signature", f"signature is older than {limit} s")
|
|
787
|
+
elif limit is not None and expires - created > limit:
|
|
788
|
+
raise _refuse("invalid_signature",
|
|
789
|
+
f"signature validity {expires - created} s exceeds {limit} s")
|
|
534
790
|
|
|
535
791
|
async def _verify_pop(
|
|
536
792
|
self, method: str, url: str, headers: dict[str, str], label: str,
|
|
537
|
-
key: Any, algorithm: Any, detail: str,
|
|
538
|
-
) ->
|
|
539
|
-
"""Verify the HTTP Message Signature labelled ``label`` with ``key
|
|
793
|
+
key: Any, algorithm: Any, detail: str, *, tag: str | None = None,
|
|
794
|
+
) -> str:
|
|
795
|
+
"""Verify the HTTP Message Signature labelled ``label`` with ``key``
|
|
796
|
+
(with ``tag``: only that signature, which must carry the tag). Returns
|
|
797
|
+
the signature base that verified — what the replay guard keys on."""
|
|
540
798
|
message = Message(method, url, headers)
|
|
541
799
|
verifier = _KeyidOptionalVerifier(
|
|
542
800
|
signature_algorithm=algorithm,
|
|
543
801
|
key_resolver=StaticKeyResolver({}, default=key),
|
|
544
802
|
component_resolver_class=DictKeyComponentResolver,
|
|
545
803
|
)
|
|
804
|
+
selection: dict[str, Any] = {"expect_tag": tag, "expect_label": label} if tag else {}
|
|
546
805
|
try:
|
|
547
|
-
# created/expires were judged
|
|
548
|
-
# library's
|
|
806
|
+
# created/expires were judged in _check_signature_input with our own
|
|
807
|
+
# codes; the library's max_age is set wide so it cannot pre-empt them.
|
|
549
808
|
results = await asyncio.to_thread(
|
|
550
|
-
verifier.verify, message, max_age=timedelta(days=365),
|
|
809
|
+
verifier.verify, message, max_age=timedelta(days=365), **selection,
|
|
551
810
|
)
|
|
552
811
|
except Exception as exc: # noqa: BLE001
|
|
553
812
|
raise _refuse("invalid_signature", f"{detail}: {str(exc)[:120]}") from exc
|
|
554
|
-
|
|
813
|
+
result = next((r for r in results if str(r.label) == label), None)
|
|
814
|
+
if result is None:
|
|
555
815
|
raise _refuse("invalid_signature", f"no verified signature labelled {label!r}")
|
|
816
|
+
# covered_components is the whole base, "@signature-params" line included.
|
|
817
|
+
return "\n".join(f"{k}: {v}" for k, v in result.covered_components.items())
|
|
818
|
+
|
|
819
|
+
def _valid_until(self, params: dict[str, Any], *, wba: bool) -> int:
|
|
820
|
+
"""The first second at which this signature is refused on time grounds —
|
|
821
|
+
how long the replay guard must remember it."""
|
|
822
|
+
created = int(params["created"])
|
|
823
|
+
cfg = self.config
|
|
824
|
+
bounds = [created + int(cfg.replay_window_seconds) + 1] # the admission window
|
|
825
|
+
if wba:
|
|
826
|
+
bounds.append(created + int(cfg.max_age_hours) * 3600 + 1)
|
|
827
|
+
if params.get("expires") is None and cfg.wba_max_validity_seconds is not None:
|
|
828
|
+
bounds.append(created + int(cfg.wba_max_validity_seconds) + 1)
|
|
829
|
+
else:
|
|
830
|
+
bounds.append(created + int(cfg.signature_window_seconds) + 1)
|
|
831
|
+
if isinstance(params.get("expires"), int):
|
|
832
|
+
bounds.append(int(params["expires"]))
|
|
833
|
+
return min(bounds)
|
|
834
|
+
|
|
835
|
+
async def _check_replay(self, scheme: str, keyid: str, base: str, until: int,
|
|
836
|
+
vouched_by: str) -> None:
|
|
837
|
+
"""Ask the replay guard, last: only a fully verified signature is recorded.
|
|
838
|
+
|
|
839
|
+
The key is the scheme, the keyid and the signature base — not the
|
|
840
|
+
Signature bytes (an ECDSA signature (r, s) has a twin (r, n-s) that
|
|
841
|
+
verifies too) and not the label (not signed). The partition is the
|
|
842
|
+
host of ``vouched_by`` (the directory URL, the issuer, the server):
|
|
843
|
+
however many keys, JWK Set URLs or ports one party uses on its host,
|
|
844
|
+
they share one partition and one cap.
|
|
845
|
+
|
|
846
|
+
A replay is answered ``invalid_signature``: no Signature-Error code
|
|
847
|
+
names replay, and -11 §11.3.4 already uses ``invalid_signature`` for a
|
|
848
|
+
signature that verifies but is no longer acceptable (created outside the
|
|
849
|
+
window) — the agent's remedy, signing the request again, is the same. A
|
|
850
|
+
guard that fails or is full is a refusal too: an unchecked signature is
|
|
851
|
+
not accepted."""
|
|
852
|
+
if self._replay_guard is None:
|
|
853
|
+
return
|
|
854
|
+
digest = hashlib.sha256(f"{scheme}\n{keyid}\n{base}".encode()).hexdigest()
|
|
855
|
+
try:
|
|
856
|
+
fresh = await self._replay_guard.first_use(digest, until=until,
|
|
857
|
+
partition=_partition(vouched_by))
|
|
858
|
+
except ReplayGuardFull as exc:
|
|
859
|
+
scope = "for this host" if exc.partition is not None else "for every host"
|
|
860
|
+
raise _refuse("invalid_signature",
|
|
861
|
+
f"replay guard full {scope} (signatures still valid); refused "
|
|
862
|
+
"rather than accepted unchecked") from exc
|
|
863
|
+
except Exception as exc: # noqa: BLE001
|
|
864
|
+
raise _refuse("invalid_signature",
|
|
865
|
+
f"replay guard unavailable ({type(exc).__name__}); refused rather "
|
|
866
|
+
"than accepted unchecked") from exc
|
|
867
|
+
if not fresh:
|
|
868
|
+
raise _refuse("invalid_signature", "this signature was already used (replay)")
|
|
869
|
+
|
|
870
|
+
def _signature_params(self, headers: dict[str, str], label: str) -> dict[str, Any]:
|
|
871
|
+
return parse_signature_input(_header(headers, "signature-input"))[label][1]
|
|
556
872
|
|
|
557
873
|
async def _verify_jwt_scheme(
|
|
558
874
|
self, method: str, url: str, headers: dict[str, str], body: bytes | None,
|
|
@@ -641,6 +957,7 @@ class HttpsigVerifier:
|
|
|
641
957
|
raise _refuse("unsupported_algorithm", f"issuer key alg {key_alg!r} is not {alg}",
|
|
642
958
|
accept_algs=AAUTH_ACCEPT_ALGS)
|
|
643
959
|
try:
|
|
960
|
+
check_jwk_members(issuer_jwk)
|
|
644
961
|
if key_alg in (None, "EdDSA") or alg == "Ed25519":
|
|
645
962
|
issuer_key: Any = load_ed25519_jwk(issuer_jwk)
|
|
646
963
|
else:
|
|
@@ -658,7 +975,7 @@ class HttpsigVerifier:
|
|
|
658
975
|
)
|
|
659
976
|
except Exception as exc: # noqa: BLE001
|
|
660
977
|
raise _refuse("invalid_jwt", f"token does not verify: {str(exc)[:120]}") from exc
|
|
661
|
-
now =
|
|
978
|
+
now = _now()
|
|
662
979
|
window = int(cfg.signature_window_seconds)
|
|
663
980
|
try:
|
|
664
981
|
exp, iat = int(claims["exp"]), int(claims["iat"])
|
|
@@ -684,13 +1001,16 @@ class HttpsigVerifier:
|
|
|
684
1001
|
if not cfg.require_fully_specified_algs and "alg" not in cnf_jwk:
|
|
685
1002
|
cnf_jwk = {**cnf_jwk, "alg": "Ed25519"}
|
|
686
1003
|
pop_key, algorithm = _load_public_key(cnf_jwk)
|
|
687
|
-
await self._verify_pop(method, url, headers, label, pop_key, algorithm,
|
|
688
|
-
|
|
1004
|
+
base = await self._verify_pop(method, url, headers, label, pop_key, algorithm,
|
|
1005
|
+
"proof of possession failed")
|
|
1006
|
+
keyid = jwk_thumbprint(cnf_jwk)
|
|
1007
|
+
await self._check_replay("aauth", keyid, base, self._valid_until(
|
|
1008
|
+
self._signature_params(headers, label), wba=False), iss)
|
|
689
1009
|
|
|
690
1010
|
return VerifiedSignature(
|
|
691
1011
|
scheme=scheme,
|
|
692
1012
|
agent=iss,
|
|
693
|
-
keyid=
|
|
1013
|
+
keyid=keyid,
|
|
694
1014
|
# An auth-token issuer is by definition a configured, trusted PS/AS.
|
|
695
1015
|
trusted=iss in cfg.trusted_agents or typ == AAUTH_AUTH_TYP,
|
|
696
1016
|
sub=str(claims.get("sub", "")),
|
|
@@ -724,18 +1044,78 @@ class HttpsigVerifier:
|
|
|
724
1044
|
jwks_url = await self._issuer_jwks_url(server_id, dwk, override=override or None)
|
|
725
1045
|
jwk = await self._jwks_key(jwks_url, kid)
|
|
726
1046
|
key, algorithm = _load_public_key(jwk)
|
|
727
|
-
await self._verify_pop(method, url, headers, label, key, algorithm,
|
|
728
|
-
|
|
1047
|
+
base = await self._verify_pop(method, url, headers, label, key, algorithm,
|
|
1048
|
+
"server signature failed")
|
|
1049
|
+
# The thumbprint of the key that verified, never the kid: the kid is a
|
|
1050
|
+
# label the server chose and may copy from anyone (claims["kid"]).
|
|
1051
|
+
keyid = jwk_thumbprint(jwk)
|
|
1052
|
+
await self._check_replay("aauth-server", keyid, base, self._valid_until(
|
|
1053
|
+
self._signature_params(headers, label), wba=False), server_id)
|
|
729
1054
|
return VerifiedSignature(
|
|
730
1055
|
scheme="aauth-server",
|
|
731
1056
|
agent=server_id,
|
|
732
|
-
keyid=
|
|
1057
|
+
keyid=keyid,
|
|
733
1058
|
trusted=server_id in cfg.trusted_ps or server_id in cfg.trusted_agents,
|
|
734
1059
|
label=label,
|
|
735
1060
|
claims={"iss": server_id, "dwk": dwk, "kid": kid},
|
|
736
1061
|
)
|
|
737
1062
|
|
|
738
1063
|
|
|
1064
|
+
# Fields the verification itself reads; any covered field is added per request.
|
|
1065
|
+
_VERIFICATION_FIELDS = frozenset({
|
|
1066
|
+
"signature", "signature-input", "signature-agent", "signature-key",
|
|
1067
|
+
"content-digest", "content-type", "content-length", "transfer-encoding", "host",
|
|
1068
|
+
})
|
|
1069
|
+
|
|
1070
|
+
|
|
1071
|
+
def _normalize_headers(headers: Mapping[str, str]) -> dict[str, str]:
|
|
1072
|
+
"""The request's header mapping as ONE lowercase name per field — built once,
|
|
1073
|
+
before anything reads it, so the verifier's own checks and the RFC 9421
|
|
1074
|
+
library read the same single value.
|
|
1075
|
+
|
|
1076
|
+
A case-preserving mapping can carry ``Signature-Input`` and
|
|
1077
|
+
``signature-input`` side by side; read first-match by one reader and
|
|
1078
|
+
last-match by the other, that let the checks judge one value while the
|
|
1079
|
+
math verified another. A field the verification depends on (the signature
|
|
1080
|
+
fields, the body fields, ``host``, and every field a signature covers) that
|
|
1081
|
+
arrives under two spellings is refused; any other duplicate is harmless."""
|
|
1082
|
+
out: dict[str, str] = {}
|
|
1083
|
+
twice: set[str] = set()
|
|
1084
|
+
for key, value in headers.items():
|
|
1085
|
+
name = str(key).lower()
|
|
1086
|
+
if name in out:
|
|
1087
|
+
twice.add(name)
|
|
1088
|
+
out[name] = str(value)
|
|
1089
|
+
if twice:
|
|
1090
|
+
clash = sorted(twice & _VERIFICATION_FIELDS)
|
|
1091
|
+
if not clash: # Signature-Input itself is single here, so it can be read
|
|
1092
|
+
covered = {c for comps, _ in parse_signature_input(
|
|
1093
|
+
out.get("signature-input", "")).values() for c in comps}
|
|
1094
|
+
clash = sorted(twice & covered)
|
|
1095
|
+
if clash:
|
|
1096
|
+
raise _refuse("invalid_signature",
|
|
1097
|
+
f"header {clash[0]} arrives under two spellings")
|
|
1098
|
+
return out
|
|
1099
|
+
|
|
1100
|
+
|
|
1101
|
+
def _has_body(headers: Mapping[str, str], body: bytes | None) -> bool:
|
|
1102
|
+
"""Whether the request carries a body. When the caller passes the body, the
|
|
1103
|
+
body decides (an empty chunked request is bodiless). Only when it is not
|
|
1104
|
+
passed does the framing count: ``Content-Length`` above zero (or
|
|
1105
|
+
unreadable), ``Transfer-Encoding``, or a ``Content-Digest``."""
|
|
1106
|
+
if body is not None:
|
|
1107
|
+
return len(body) > 0
|
|
1108
|
+
if _header(headers, "transfer-encoding") or _header(headers, "content-digest"):
|
|
1109
|
+
return True
|
|
1110
|
+
length = _header(headers, "content-length").strip()
|
|
1111
|
+
if not length:
|
|
1112
|
+
return False
|
|
1113
|
+
try:
|
|
1114
|
+
return int(length) > 0
|
|
1115
|
+
except ValueError:
|
|
1116
|
+
return True
|
|
1117
|
+
|
|
1118
|
+
|
|
739
1119
|
def _header(headers: Mapping[str, str], name: str) -> str:
|
|
740
1120
|
lname = name.lower()
|
|
741
1121
|
for k, v in headers.items():
|