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/__init__.py
CHANGED
|
@@ -15,6 +15,7 @@ from regent_httpsig.budget import (
|
|
|
15
15
|
from regent_httpsig.config import HttpsigConfig
|
|
16
16
|
from regent_httpsig.jwk import b64url, jwk_thumbprint, load_ed25519_jwk
|
|
17
17
|
from regent_httpsig.netguard import NotPublicURL, assert_public_url
|
|
18
|
+
from regent_httpsig.replay import InMemoryReplayGuard, ReplayGuard, ReplayGuardFull
|
|
18
19
|
from regent_httpsig.sfv import (
|
|
19
20
|
build_aauth_budget_header,
|
|
20
21
|
build_aauth_requirement,
|
|
@@ -47,7 +48,7 @@ from regent_httpsig.verify import (
|
|
|
47
48
|
VerifiedSignature,
|
|
48
49
|
)
|
|
49
50
|
|
|
50
|
-
__version__ = "0.
|
|
51
|
+
__version__ = "0.8.0"
|
|
51
52
|
|
|
52
53
|
__all__ = [
|
|
53
54
|
"DIRECTORY_MEDIA_TYPE",
|
|
@@ -56,7 +57,10 @@ __all__ = [
|
|
|
56
57
|
"HttpsigConfig",
|
|
57
58
|
"HttpsigVerifier",
|
|
58
59
|
"InMemoryMeter",
|
|
60
|
+
"InMemoryReplayGuard",
|
|
59
61
|
"InsufficientBudget",
|
|
62
|
+
"ReplayGuard",
|
|
63
|
+
"ReplayGuardFull",
|
|
60
64
|
"TokenRevoked",
|
|
61
65
|
"InvalidBudgetClaim",
|
|
62
66
|
"NotPublicURL",
|
regent_httpsig/config.py
CHANGED
|
@@ -5,13 +5,19 @@ from __future__ import annotations
|
|
|
5
5
|
from collections.abc import Mapping
|
|
6
6
|
from dataclasses import dataclass, field
|
|
7
7
|
|
|
8
|
-
__all__ = ["AAUTH_REQUIRED_COMPONENTS", "HttpsigConfig"]
|
|
8
|
+
__all__ = ["AAUTH_REQUIRED_COMPONENTS", "WBA_REQUIRED_COMPONENTS", "HttpsigConfig"]
|
|
9
9
|
|
|
10
10
|
# AAuth -11 §11.3.3.1: what every agent signature MUST cover. A request with a
|
|
11
11
|
# body to a PS/AS/revocation endpoint additionally covers content-digest and
|
|
12
12
|
# content-type; the verifier adds those when it is handed the body.
|
|
13
13
|
AAUTH_REQUIRED_COMPONENTS: tuple[str, ...] = ("@method", "@authority", "@path", "signature-key")
|
|
14
14
|
|
|
15
|
+
# draft-ietf-webbotauth-httpsig-protocol-01 §5.2: what every Web Bot Auth
|
|
16
|
+
# signature MUST cover — @authority (or @target-uri, which contains it) and the
|
|
17
|
+
# Signature-Agent member the signature is attributed to. Nothing more is
|
|
18
|
+
# required by the draft; @method/@path are SHOULD-level "narrowing" components.
|
|
19
|
+
WBA_REQUIRED_COMPONENTS: tuple[str, ...] = ("@authority", "signature-agent")
|
|
20
|
+
|
|
15
21
|
|
|
16
22
|
@dataclass(frozen=True)
|
|
17
23
|
class HttpsigConfig:
|
|
@@ -19,14 +25,43 @@ class HttpsigConfig:
|
|
|
19
25
|
|
|
20
26
|
Defaults are production-safe and, on the AAuth path, follow -11 as
|
|
21
27
|
published: a 60-second ``created`` window, fully-specified algorithms only,
|
|
22
|
-
no clock-skew tolerance on ``exp``. Web Bot Auth
|
|
23
|
-
|
|
28
|
+
no clock-skew tolerance on ``exp``. On the Web Bot Auth path they are what
|
|
29
|
+
draft-ietf-webbotauth-httpsig-protocol-01 requires and no more: a relying
|
|
30
|
+
party that moves money tightens ``wba_required_components`` and
|
|
31
|
+
``wba_max_validity_seconds`` itself (see the README)."""
|
|
24
32
|
|
|
25
33
|
# Origins/issuers you additionally mark as trusted (``VerifiedSignature.trusted``).
|
|
26
34
|
# Verification itself never depends on this — it only annotates the result.
|
|
27
35
|
trusted_agents: frozenset[str] = field(default_factory=frozenset)
|
|
28
|
-
# Web Bot Auth only: reject signatures created earlier than this many hours ago
|
|
36
|
+
# Web Bot Auth only: reject signatures created earlier than this many hours ago,
|
|
37
|
+
# whatever their `expires` says. Stricter than -01, which sets no upper bound
|
|
38
|
+
# (it RECOMMENDS expires ≤ 24 h after created): kept so that a signature with a
|
|
39
|
+
# far `expires` (the draft's own vectors expire in 2124) is not a long-lived
|
|
40
|
+
# credential (-01 §6.9). Raise it to accept signatures meant to live longer.
|
|
29
41
|
max_age_hours: int = 25
|
|
42
|
+
# Web Bot Auth: covered components every signature must include. "@authority",
|
|
43
|
+
# "@path", "@query" and "@scheme" are also satisfied by "@target-uri" (which
|
|
44
|
+
# contains them; -01 §5.2 accepts either). "signature-agent" means the member
|
|
45
|
+
# the signature is attributed to and is required whether listed or not
|
|
46
|
+
# (-01 §5.2.2: never attribute a signature to a member it does not cover).
|
|
47
|
+
# "content-digest" / "content-type" apply only to a request with a body and
|
|
48
|
+
# need the body passed to verify(); the digest is then checked. For money:
|
|
49
|
+
# ("@method", "@authority", "@path", "signature-agent", "content-digest").
|
|
50
|
+
wba_required_components: tuple[str, ...] = WBA_REQUIRED_COMPONENTS
|
|
51
|
+
# Web Bot Auth: -01 §5.2 makes `expires` a MUST. False accepts signatures
|
|
52
|
+
# without it (their age is then bounded by max_age_hours only).
|
|
53
|
+
wba_require_expires: bool = True
|
|
54
|
+
# Web Bot Auth: the longest `expires - created` accepted, in seconds (without
|
|
55
|
+
# `expires`: the longest age of `created`). None = no bound beyond
|
|
56
|
+
# max_age_hours; -01 only RECOMMENDS at most 24 hours. For money: 300.
|
|
57
|
+
wba_max_validity_seconds: int | None = None
|
|
58
|
+
# Web Bot Auth directories only (-01 §6.10): when a refetch fails, the last
|
|
59
|
+
# good copy keeps being served for at most this many seconds after it went
|
|
60
|
+
# stale (cache_ttl after it was fetched); then a failed refetch is a failure.
|
|
61
|
+
# Bounds how long a key the operator removed can verify while whoever can
|
|
62
|
+
# make the refetch fail (an outage, a DoS of the directory host) keeps it so.
|
|
63
|
+
# AAuth issuer and server JWKS are not served stale.
|
|
64
|
+
wba_max_stale_seconds: float = 600.0
|
|
30
65
|
# AAuth -11 §11.3.4 step 3: the signature validity window for `created`, in
|
|
31
66
|
# seconds. Older than the window → invalid_signature; further ahead of our
|
|
32
67
|
# clock → clock_skew. The same window bounds a token's `iat` (§11.5.2).
|
|
@@ -34,6 +69,12 @@ class HttpsigConfig:
|
|
|
34
69
|
signature_window_seconds: int = 60
|
|
35
70
|
# AAuth -11 §11.3.3.1: covered components every agent signature must include.
|
|
36
71
|
required_components: tuple[str, ...] = AAUTH_REQUIRED_COMPONENTS
|
|
72
|
+
# Only with a replay guard (HttpsigVerifier(replay_guard=...)): a signature is
|
|
73
|
+
# admitted at most this many seconds after its `created`, on both paths, and
|
|
74
|
+
# the guard remembers it until min(expires, created + window + 1). This
|
|
75
|
+
# bounds how long anyone's signatures occupy the guard (-01 Appendix C.6:
|
|
76
|
+
# bound retention and admission). Without a guard it has no effect.
|
|
77
|
+
replay_window_seconds: int = 300
|
|
37
78
|
# Key-directory cache TTL (seconds); failures are cached for negative_cache_ttl.
|
|
38
79
|
cache_ttl: float = 600.0
|
|
39
80
|
negative_cache_ttl: float = 120.0
|
|
@@ -44,6 +85,19 @@ class HttpsigConfig:
|
|
|
44
85
|
# Hosts exempt from the https-only + public-IP SSRF guard (local dev only —
|
|
45
86
|
# e.g. frozenset({"localhost"})). Leave empty in production.
|
|
46
87
|
insecure_hosts: frozenset[str] = field(default_factory=frozenset)
|
|
88
|
+
# FastAPI layer only: this service's public origin(s), e.g.
|
|
89
|
+
# frozenset({"https://api.example"}). When set, the URL a signature is
|
|
90
|
+
# verified against is built from the configured origin that matches the
|
|
91
|
+
# request's Host (scheme included), and a signed request whose Host matches
|
|
92
|
+
# none of them is refused before verification. A host listed under both
|
|
93
|
+
# http:// and https://: X-Forwarded-Proto decides, else https:// (never the
|
|
94
|
+
# connection's own scheme), so a plain-http client with no proxy whose
|
|
95
|
+
# signature covers @target-uri or @scheme is refused. Unset, the URL is rebuilt
|
|
96
|
+
# from the client's Host and X-Forwarded-Proto, so a signature made for
|
|
97
|
+
# another site verifies when replayed with that site's Host unless the
|
|
98
|
+
# proxy in front passes only this service's names. Framework-free callers
|
|
99
|
+
# pass verify() the URL of their own public origin themselves.
|
|
100
|
+
public_origins: frozenset[str] = field(default_factory=frozenset)
|
|
47
101
|
# AAuth -11 §11.3.1: JOSE algs must be fully-specified (RFC 9864); the
|
|
48
102
|
# polymorphic "EdDSA" and keys without `alg` are refused. False is the
|
|
49
103
|
# pre-cut-over behaviour kept only for private test rigs; -11 forbids it.
|
|
@@ -58,5 +112,14 @@ class HttpsigConfig:
|
|
|
58
112
|
# an established relationship with its PS, so trust is pinned by
|
|
59
113
|
# configuration. The value may be "" to discover the JWKS through the
|
|
60
114
|
# issuer's metadata document ({id}/.well-known/{dwk}) instead of a fixed URL.
|
|
61
|
-
# Empty (the default)
|
|
115
|
+
# Empty (the default): auth tokens are refused, and verify()/verify_detailed()
|
|
116
|
+
# refuse every jwks_uri server signature (invalid_key). verify_server() — the
|
|
117
|
+
# explicit entry point for usage and revocation endpoints — still verifies a
|
|
118
|
+
# server that is not listed here and reports it with trusted=False; the
|
|
119
|
+
# endpoint decides whether to accept it.
|
|
62
120
|
trusted_ps: Mapping[str, str] = field(default_factory=dict)
|
|
121
|
+
# Let verify()/verify_detailed() accept a jwks_uri server signature from an
|
|
122
|
+
# `id` that is not in trusted_ps (reported with trusted=False). Off by
|
|
123
|
+
# default: a server names its own key, so an unpinned server signature
|
|
124
|
+
# proves only that someone controls that https origin.
|
|
125
|
+
allow_unpinned_servers: bool = False
|
regent_httpsig/fastapi.py
CHANGED
|
@@ -20,10 +20,14 @@ authentication: a signed request that fails is answered ``401`` with the
|
|
|
20
20
|
AAuth -11 §11.3.4 assigns), an unsigned one with ``AAuth-Requirement:
|
|
21
21
|
requirement=agent-token`` (-11 §6.1).
|
|
22
22
|
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
23
|
+
The signer signed the PUBLIC url. Set ``HttpsigConfig.public_origins`` to
|
|
24
|
+
this service's origin(s): the URL is then built from the configured origin
|
|
25
|
+
that matches ``Host``, and a signed request with any other ``Host`` is refused
|
|
26
|
+
before verification. Without it this layer rebuilds the URL from the client's
|
|
27
|
+
``X-Forwarded-Proto`` + ``Host`` (as 0.7 did), so a signature made for another
|
|
28
|
+
site verifies when replayed with that site's Host unless the proxy in front
|
|
29
|
+
passes only this service's names — and the proxy must set
|
|
30
|
+
``X-Forwarded-Proto`` (nginx: ``proxy_set_header X-Forwarded-Proto $scheme;``).
|
|
27
31
|
"""
|
|
28
32
|
|
|
29
33
|
from __future__ import annotations
|
|
@@ -55,9 +59,11 @@ from regent_httpsig.sfv import (
|
|
|
55
59
|
from regent_httpsig.verify import (
|
|
56
60
|
AAUTH_AUTH_TYP,
|
|
57
61
|
AAUTH_PERSON_TYP,
|
|
62
|
+
SERVER_DWKS,
|
|
58
63
|
HttpsigVerifier,
|
|
59
64
|
VerificationError,
|
|
60
65
|
VerifiedSignature,
|
|
66
|
+
_split_agent_url,
|
|
61
67
|
)
|
|
62
68
|
|
|
63
69
|
__all__ = [
|
|
@@ -71,6 +77,7 @@ __all__ = [
|
|
|
71
77
|
"get_signature",
|
|
72
78
|
"get_signature_error",
|
|
73
79
|
"require_server_signature",
|
|
80
|
+
"verify_server_request",
|
|
74
81
|
"signature_error_response",
|
|
75
82
|
]
|
|
76
83
|
|
|
@@ -83,14 +90,43 @@ def attach(app: FastAPI, verifier: HttpsigVerifier) -> None:
|
|
|
83
90
|
setattr(app.state, _STATE_ATTR, verifier)
|
|
84
91
|
|
|
85
92
|
|
|
86
|
-
def _public_url(request: Request) -> str:
|
|
87
|
-
"""
|
|
88
|
-
|
|
93
|
+
def _public_url(request: Request, origins: frozenset[str] = frozenset()) -> str | None:
|
|
94
|
+
"""The URL the signature is verified against.
|
|
95
|
+
|
|
96
|
+
With ``HttpsigConfig.public_origins`` set: the configured origin whose host
|
|
97
|
+
(and port) is the request's ``Host``, plus the path — or ``None`` when the
|
|
98
|
+
Host is none of them, so a signature made for another site cannot be
|
|
99
|
+
replayed here under that site's name. Without it: rebuilt from
|
|
100
|
+
``X-Forwarded-Proto`` and ``Host`` as in 0.7 — the client's Host decides
|
|
101
|
+
``@authority``, so the proxy in front must pass only this service's names."""
|
|
89
102
|
host = request.headers.get("host") or request.url.netloc
|
|
90
103
|
scheme = request.headers.get("x-forwarded-proto") or request.url.scheme
|
|
91
104
|
path = request.url.path
|
|
92
105
|
query = f"?{request.url.query}" if request.url.query else ""
|
|
93
|
-
|
|
106
|
+
if not origins:
|
|
107
|
+
return f"{scheme}://{host}{path}{query}"
|
|
108
|
+
matches = []
|
|
109
|
+
for configured in origins:
|
|
110
|
+
mine = _split_agent_url(configured)
|
|
111
|
+
if mine is None:
|
|
112
|
+
continue
|
|
113
|
+
theirs = _split_agent_url(f"{mine[0]}://{host}")
|
|
114
|
+
if theirs is not None and theirs[2] == mine[2]:
|
|
115
|
+
matches.append(mine)
|
|
116
|
+
if not matches:
|
|
117
|
+
return None
|
|
118
|
+
# The same host under http and https: X-Forwarded-Proto picks, else https —
|
|
119
|
+
# never the connection's own scheme, which behind a TLS-terminating proxy
|
|
120
|
+
# is plain http whatever the client used.
|
|
121
|
+
forwarded = (request.headers.get("x-forwarded-proto") or "").strip().lower()
|
|
122
|
+
matches.sort(key=lambda m: (m[0] != forwarded, m[0] != "https", m[2]))
|
|
123
|
+
return f"{matches[0][2]}{path}{query}"
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _not_our_origin() -> VerificationError:
|
|
127
|
+
return VerificationError(
|
|
128
|
+
"invalid_signature", "the request's Host is not one of this service's public "
|
|
129
|
+
"origins (HttpsigConfig.public_origins); refused before verification")
|
|
94
130
|
|
|
95
131
|
|
|
96
132
|
def _verifier_of(request: Request) -> HttpsigVerifier:
|
|
@@ -112,12 +148,21 @@ async def _run_verifier(
|
|
|
112
148
|
return cached if isinstance(cached, VerifiedSignature | VerificationError) else None
|
|
113
149
|
outcome: VerifiedSignature | VerificationError | None = None
|
|
114
150
|
if "signature" in request.headers:
|
|
115
|
-
# The
|
|
116
|
-
# Signature-Key path; Web Bot Auth
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
151
|
+
# The body is read only when a rule needs it: the -11 body rule on the
|
|
152
|
+
# Signature-Key path; on the Web Bot Auth path a Content-Digest to check,
|
|
153
|
+
# or a configuration that requires one (-01 itself requires no body
|
|
154
|
+
# coverage, so a plain Web Bot Auth request is never buffered here).
|
|
155
|
+
needs_body = ("signature-key" in request.headers
|
|
156
|
+
or "content-digest" in request.headers
|
|
157
|
+
or "content-digest" in verifier.config.wba_required_components)
|
|
158
|
+
url = _public_url(request, verifier.config.public_origins)
|
|
159
|
+
if url is None:
|
|
160
|
+
outcome = _not_our_origin()
|
|
161
|
+
else:
|
|
162
|
+
body = await request.body() if needs_body else None
|
|
163
|
+
outcome = await verifier.verify_detailed(
|
|
164
|
+
request.method, url, dict(request.headers), body,
|
|
165
|
+
)
|
|
121
166
|
request.state.regent_httpsig_outcome = outcome
|
|
122
167
|
request.state.regent_httpsig_result = (
|
|
123
168
|
outcome if isinstance(outcome, VerifiedSignature) else None)
|
|
@@ -196,15 +241,32 @@ async def require_signature(request: Request) -> VerifiedSignature:
|
|
|
196
241
|
)
|
|
197
242
|
|
|
198
243
|
|
|
244
|
+
async def verify_server_request(
|
|
245
|
+
request: Request, *, allowed_dwk: tuple[str, ...] = SERVER_DWKS,
|
|
246
|
+
) -> VerifiedSignature | VerificationError:
|
|
247
|
+
"""Verify a server's (PS/AS) ``jwks_uri`` signature on ``request`` with the
|
|
248
|
+
attached verifier, against the same URL the other dependencies use
|
|
249
|
+
(``HttpsigConfig.public_origins`` when set), body covered. ``allowed_dwk``
|
|
250
|
+
has the meaning it has in :meth:`HttpsigVerifier.verify_server` (the
|
|
251
|
+
metadata documents a caller may sign under; others are ``invalid_key``).
|
|
252
|
+
Never raises: pass it (or a ``functools.partial`` of it) as
|
|
253
|
+
``authenticate_ps=`` to :func:`make_usage_endpoint` or
|
|
254
|
+
:func:`make_revocation_endpoint` instead of building the URL from
|
|
255
|
+
``request.url``, which is the client's Host."""
|
|
256
|
+
verifier = _verifier_of(request)
|
|
257
|
+
body = await request.body()
|
|
258
|
+
url = _public_url(request, verifier.config.public_origins)
|
|
259
|
+
if url is None:
|
|
260
|
+
return _not_our_origin()
|
|
261
|
+
return await verifier.verify_server(request.method, url, dict(request.headers), body,
|
|
262
|
+
allowed_dwk=allowed_dwk)
|
|
263
|
+
|
|
264
|
+
|
|
199
265
|
async def require_server_signature(request: Request) -> VerifiedSignature:
|
|
200
266
|
"""For endpoints servers call (usage, revocation): the caller must sign
|
|
201
267
|
under the ``jwks_uri`` scheme (-11 §11.3.2); the body is covered. A
|
|
202
268
|
failure is ``401`` + ``Signature-Error``."""
|
|
203
|
-
|
|
204
|
-
body = await request.body()
|
|
205
|
-
outcome = await verifier.verify_server(
|
|
206
|
-
request.method, _public_url(request), dict(request.headers), body,
|
|
207
|
-
)
|
|
269
|
+
outcome = await verify_server_request(request)
|
|
208
270
|
if isinstance(outcome, VerifiedSignature):
|
|
209
271
|
return outcome
|
|
210
272
|
raise HTTPException(status_code=401, headers=outcome.headers(),
|
regent_httpsig/jwk.py
CHANGED
|
@@ -1,15 +1,43 @@
|
|
|
1
|
-
"""JWK helpers — RFC 7638 thumbprints (RFC 8037 A.3 for Ed25519) and key loading.
|
|
1
|
+
"""JWK helpers — RFC 7638 thumbprints (RFC 8037 A.3 for Ed25519) and key loading.
|
|
2
|
+
|
|
3
|
+
Key material is read only from canonical base64url (RFC 7515 §2: the URL-safe
|
|
4
|
+
alphabet, no padding; RFC 4648 §3.5: the unused bits of the last character are
|
|
5
|
+
zero) of the exact length the key type needs. A lenient decoder lets one key
|
|
6
|
+
be written many ways, and a thumbprint over the member as written then gives
|
|
7
|
+
that one key many keyids. The thumbprint is therefore computed over the
|
|
8
|
+
canonical re-encoding of the key material, so every spelling of the same
|
|
9
|
+
bytes has the same thumbprint, and loading refuses all but the canonical one.
|
|
10
|
+
"""
|
|
2
11
|
|
|
3
12
|
from __future__ import annotations
|
|
4
13
|
|
|
5
14
|
import base64
|
|
6
15
|
import hashlib
|
|
7
16
|
import json
|
|
17
|
+
import re
|
|
8
18
|
from typing import Any
|
|
9
19
|
|
|
10
20
|
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
|
|
11
21
|
|
|
12
|
-
__all__ = [
|
|
22
|
+
__all__ = [
|
|
23
|
+
"b64url",
|
|
24
|
+
"b64url_decode",
|
|
25
|
+
"b64url_decode_strict",
|
|
26
|
+
"check_jwk_members",
|
|
27
|
+
"jwk_thumbprint",
|
|
28
|
+
"load_ed25519_jwk",
|
|
29
|
+
]
|
|
30
|
+
|
|
31
|
+
_B64URL = re.compile(r"[A-Za-z0-9_-]*")
|
|
32
|
+
_ANY_B64_SPELLING = re.compile(r"[A-Za-z0-9_+/-]*=*")
|
|
33
|
+
_REQUIRED_BY_KTY = { # RFC 7638 §3.2, RFC 8037 §2
|
|
34
|
+
"OKP": ("crv", "kty", "x"),
|
|
35
|
+
"EC": ("crv", "kty", "x", "y"),
|
|
36
|
+
"RSA": ("e", "kty", "n"),
|
|
37
|
+
}
|
|
38
|
+
_KEY_MATERIAL = {"OKP": ("x",), "EC": ("x", "y"), "RSA": ("e", "n")}
|
|
39
|
+
_OKP_SIZES = {"Ed25519": 32, "Ed448": 57, "X25519": 32, "X448": 56}
|
|
40
|
+
_EC_SIZES = {"P-256": 32, "P-384": 48, "P-521": 66}
|
|
13
41
|
|
|
14
42
|
|
|
15
43
|
def b64url(data: bytes) -> str:
|
|
@@ -17,30 +45,86 @@ def b64url(data: bytes) -> str:
|
|
|
17
45
|
|
|
18
46
|
|
|
19
47
|
def b64url_decode(data: str) -> bytes:
|
|
48
|
+
"""Lenient decoding, for this library's own secrets (seeds). Never use it on
|
|
49
|
+
key material that came from someone else: see :func:`b64url_decode_strict`."""
|
|
20
50
|
return base64.urlsafe_b64decode(data + "=" * (-len(data) % 4))
|
|
21
51
|
|
|
22
52
|
|
|
53
|
+
def b64url_decode_strict(data: Any, *, size: int | None = None) -> bytes:
|
|
54
|
+
"""Decode canonical base64url only: the URL-safe alphabet, no padding, zero
|
|
55
|
+
pad bits (re-encoding gives back exactly ``data``), and ``size`` bytes if
|
|
56
|
+
given. Anything else raises :class:`ValueError`."""
|
|
57
|
+
if not isinstance(data, str) or not _B64URL.fullmatch(data) or len(data) % 4 == 1:
|
|
58
|
+
raise ValueError("not base64url (URL-safe alphabet, no padding)")
|
|
59
|
+
raw = base64.urlsafe_b64decode(data + "=" * (-len(data) % 4))
|
|
60
|
+
if b64url(raw) != data:
|
|
61
|
+
raise ValueError("non-canonical base64url (unused bits must be zero)")
|
|
62
|
+
if size is not None and len(raw) != size:
|
|
63
|
+
raise ValueError(f"expected {size} bytes, got {len(raw)}")
|
|
64
|
+
return raw
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _canonical(value: Any) -> str:
|
|
68
|
+
"""The canonical base64url of whatever bytes ``value`` spells (padding, the
|
|
69
|
+
standard alphabet and non-zero unused bits are tolerated here, and only
|
|
70
|
+
here); characters outside both alphabets raise."""
|
|
71
|
+
if not isinstance(value, str) or not _ANY_B64_SPELLING.fullmatch(value):
|
|
72
|
+
raise ValueError("key member is not base64url")
|
|
73
|
+
body = value.rstrip("=").replace("+", "-").replace("/", "_")
|
|
74
|
+
if len(body) % 4 == 1:
|
|
75
|
+
raise ValueError("key member has an impossible base64url length")
|
|
76
|
+
return b64url(base64.urlsafe_b64decode(body + "=" * (-len(body) % 4)))
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _canonical_uint(value: Any) -> str:
|
|
80
|
+
"""An RSA integer member (``n``, ``e``) in its minimum octets (RFC 7518
|
|
81
|
+
§6.3.1): leading zero octets spell the same integer, so they are dropped."""
|
|
82
|
+
raw = b64url_decode(_canonical(value))
|
|
83
|
+
return b64url(raw.lstrip(b"\x00") or b"\x00")
|
|
84
|
+
|
|
85
|
+
|
|
23
86
|
def jwk_thumbprint(jwk: dict[str, Any]) -> str:
|
|
24
87
|
"""RFC 7638 JWK thumbprint (RFC 8037 A.3 for OKP): sha256 over the canonical
|
|
25
|
-
JSON of the required members, base64url without padding.
|
|
88
|
+
JSON of the required members, base64url without padding. Key material
|
|
89
|
+
(OKP ``x``, EC ``x``/``y``, RSA ``n``/``e``) enters as its canonical
|
|
90
|
+
re-encoding — for RSA the integer in its minimum octets — so one key has
|
|
91
|
+
one thumbprint however its JWK spells it.
|
|
26
92
|
|
|
27
93
|
This is the keyid form Web Bot Auth uses — e.g. the RFC test key's thumbprint
|
|
28
94
|
is ``poqkLGiymh_W0uP6PZFw-dvez3QJT5SolqXBCW38r0U``."""
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
"EC": ("crv", "kty", "x", "y"),
|
|
32
|
-
"RSA": ("e", "kty", "n"),
|
|
33
|
-
}
|
|
34
|
-
members = required_by_kty.get(str(jwk.get("kty", "")))
|
|
95
|
+
kty = str(jwk.get("kty", ""))
|
|
96
|
+
members = _REQUIRED_BY_KTY.get(kty)
|
|
35
97
|
if not members:
|
|
36
98
|
raise ValueError(f"unsupported kty {jwk.get('kty')!r}")
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
99
|
+
values = {m: jwk[m] for m in members}
|
|
100
|
+
for m in _KEY_MATERIAL[kty]:
|
|
101
|
+
values[m] = _canonical_uint(values[m]) if kty == "RSA" else _canonical(values[m])
|
|
102
|
+
canonical = json.dumps(values, separators=(",", ":"), sort_keys=True)
|
|
40
103
|
return b64url(hashlib.sha256(canonical.encode()).digest())
|
|
41
104
|
|
|
42
105
|
|
|
106
|
+
def check_jwk_members(jwk: dict[str, Any]) -> None:
|
|
107
|
+
"""Raise :class:`ValueError` unless every key-material member is canonical
|
|
108
|
+
base64url of the right size: OKP ``x`` and EC ``x``/``y`` exactly the
|
|
109
|
+
curve's size, RSA ``n``/``e`` in the minimum number of octets (RFC 7518
|
|
110
|
+
§6.3.1)."""
|
|
111
|
+
kty, crv = jwk.get("kty"), jwk.get("crv")
|
|
112
|
+
if kty == "OKP":
|
|
113
|
+
b64url_decode_strict(jwk.get("x"), size=_OKP_SIZES.get(str(crv)))
|
|
114
|
+
elif kty == "EC":
|
|
115
|
+
size = _EC_SIZES.get(str(crv))
|
|
116
|
+
b64url_decode_strict(jwk.get("x"), size=size)
|
|
117
|
+
b64url_decode_strict(jwk.get("y"), size=size)
|
|
118
|
+
elif kty == "RSA":
|
|
119
|
+
for m in ("n", "e"):
|
|
120
|
+
raw = b64url_decode_strict(jwk.get(m))
|
|
121
|
+
if not raw or raw[0] == 0:
|
|
122
|
+
raise ValueError(f"RSA {m} is empty or not in minimal octets")
|
|
123
|
+
else:
|
|
124
|
+
raise ValueError(f"unsupported kty {kty!r}")
|
|
125
|
+
|
|
126
|
+
|
|
43
127
|
def load_ed25519_jwk(jwk: dict[str, Any]) -> Ed25519PublicKey:
|
|
44
128
|
if jwk.get("kty") != "OKP" or jwk.get("crv") != "Ed25519" or "x" not in jwk:
|
|
45
129
|
raise ValueError("only OKP/Ed25519 JWKs are supported")
|
|
46
|
-
return Ed25519PublicKey.from_public_bytes(
|
|
130
|
+
return Ed25519PublicKey.from_public_bytes(b64url_decode_strict(jwk["x"], size=32))
|
regent_httpsig/netguard.py
CHANGED
|
@@ -16,6 +16,8 @@ import ipaddress
|
|
|
16
16
|
import socket
|
|
17
17
|
from urllib.parse import urlparse
|
|
18
18
|
|
|
19
|
+
import httpx
|
|
20
|
+
|
|
19
21
|
__all__ = ["NotPublicURL", "assert_public_url"]
|
|
20
22
|
|
|
21
23
|
|
|
@@ -49,9 +51,16 @@ async def assert_public_url(url: str, allow_hosts: frozenset[str] = frozenset())
|
|
|
49
51
|
raise NotPublicURL("URL has no host")
|
|
50
52
|
if host in allow_hosts:
|
|
51
53
|
return
|
|
54
|
+
# Resolve exactly the name httpx will connect to (IDNA 2008, as httpx
|
|
55
|
+
# encodes it). socket.getaddrinfo would encode a Unicode name with Python's
|
|
56
|
+
# IDNA 2003 codec (ß -> ss) — another host — and approve the wrong one.
|
|
57
|
+
try:
|
|
58
|
+
connect_host = httpx.URL(url).raw_host.decode("ascii")
|
|
59
|
+
except Exception as exc: # noqa: BLE001 — httpx would not connect either
|
|
60
|
+
raise NotPublicURL(f"host {host!r} is not a valid hostname") from exc
|
|
52
61
|
try:
|
|
53
62
|
infos = await asyncio.to_thread(
|
|
54
|
-
socket.getaddrinfo,
|
|
63
|
+
socket.getaddrinfo, connect_host, parsed.port or None, 0, socket.SOCK_STREAM
|
|
55
64
|
)
|
|
56
65
|
except socket.gaierror as exc:
|
|
57
66
|
raise NotPublicURL(f"cannot resolve host {host!r}") from exc
|
regent_httpsig/replay.py
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
"""Replay guard — refuse a valid signature presented a second time.
|
|
2
|
+
|
|
3
|
+
A verified signature proves that the key holder signed the covered message;
|
|
4
|
+
it does not prove the message is new. Until it expires anyone who saw it can
|
|
5
|
+
present it again (RFC 9421 §7.2.2; draft-ietf-webbotauth-httpsig-protocol-01
|
|
6
|
+
§4.1 and Appendix C.6). The verifier asks a :class:`ReplayGuard` one question
|
|
7
|
+
after everything else has passed: *is this the first use of this key, which
|
|
8
|
+
stays valid until this time, from this partition?*
|
|
9
|
+
|
|
10
|
+
What counts as "the same" is decided by the verifier, not the guard: the
|
|
11
|
+
scheme, the keyid and the whole signature base (every covered component value
|
|
12
|
+
plus ``@signature-params``, so ``created``, ``expires`` and any ``nonce``).
|
|
13
|
+
Not the ``Signature`` bytes — an ECDSA signature has a twin that verifies too,
|
|
14
|
+
so a guard keyed on the bytes is walked around by rewriting them — and not the
|
|
15
|
+
label, which RFC 9421 lets intermediaries change.
|
|
16
|
+
|
|
17
|
+
The guard holds state on behalf of unauthenticated signers, so -01 Appendix
|
|
18
|
+
C.6 asks for both retention and admission to be bounded:
|
|
19
|
+
|
|
20
|
+
- **Retention**: with a guard configured the verifier admits a signature only
|
|
21
|
+
``replay_window_seconds`` (300 by default) after its ``created`` and asks
|
|
22
|
+
the guard to remember it until ``min(expires, created + window + 1)``.
|
|
23
|
+
- **Admission**: every call names a *partition* — the host that vouches for
|
|
24
|
+
the key (the Web Bot Auth directory's host, the AAuth issuer's, the AAuth
|
|
25
|
+
server's), as the ASCII name httpx connects to (IDNA 2008), lowercase,
|
|
26
|
+
without a trailing dot; scheme and port
|
|
27
|
+
ignored. Anyone can mint keys, keyids, JWK Set URLs and ports on their own
|
|
28
|
+
host, but they all land in one partition, and :class:`InMemoryReplayGuard`
|
|
29
|
+
lets one partition hold only ``max_share`` of its capacity. A partition
|
|
30
|
+
that overflows is refused; the others are not.
|
|
31
|
+
|
|
32
|
+
What remains:
|
|
33
|
+
|
|
34
|
+
- A signer controlling many hosts (subdomains count: each is a host, and no
|
|
35
|
+
public-suffix list is consulted) takes one share per host. ``1 / max_share``
|
|
36
|
+
of them, each at its cap and all within one window, fill the whole guard,
|
|
37
|
+
which then refuses everybody new until entries expire. That takes
|
|
38
|
+
``max_entries`` verified signatures per window — a volumetric attack for a
|
|
39
|
+
rate limit in front of the service, not something a per-request check stops.
|
|
40
|
+
- Co-tenants of one shared host (object storage, a platform serving per-agent
|
|
41
|
+
JWK Sets) share one partition, so one tenant can exhaust it for the others.
|
|
42
|
+
|
|
43
|
+
The knobs are ``max_share`` and ``max_entries`` here, and a rate limit in front.
|
|
44
|
+
|
|
45
|
+
:class:`InMemoryReplayGuard` is **per process**: two workers or two hosts each
|
|
46
|
+
accept a signature once. For more than one process implement the protocol over
|
|
47
|
+
a shared store (e.g. Redis ``SET key 1 NX EXAT until`` plus a per-partition
|
|
48
|
+
counter that expires with the window).
|
|
49
|
+
"""
|
|
50
|
+
|
|
51
|
+
from __future__ import annotations
|
|
52
|
+
|
|
53
|
+
import heapq
|
|
54
|
+
import threading
|
|
55
|
+
import time
|
|
56
|
+
from collections.abc import Callable
|
|
57
|
+
from typing import Protocol, runtime_checkable
|
|
58
|
+
|
|
59
|
+
__all__ = ["InMemoryReplayGuard", "ReplayGuard", "ReplayGuardFull"]
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
@runtime_checkable
|
|
63
|
+
class ReplayGuard(Protocol):
|
|
64
|
+
async def first_use(self, key: str, *, until: int, partition: str) -> bool:
|
|
65
|
+
"""Atomically: ``True`` and remember ``key`` until the unix time
|
|
66
|
+
``until`` if it has not been seen (or its entry has lapsed); ``False``
|
|
67
|
+
if it has. ``partition`` names who vouches for the key; a guard should
|
|
68
|
+
bound how much of its state one partition can hold. Raise
|
|
69
|
+
:class:`ReplayGuardFull` when it cannot remember the key (that
|
|
70
|
+
partition, or the whole guard, is full), or any other exception when
|
|
71
|
+
the answer is unknown: the verifier then refuses the request rather
|
|
72
|
+
than accept it unchecked."""
|
|
73
|
+
...
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
class ReplayGuardFull(RuntimeError):
|
|
77
|
+
"""The guard cannot remember another signature without forgetting one that
|
|
78
|
+
is still valid (which would let it be replayed), so it refuses. ``partition``
|
|
79
|
+
is the partition that is full, or ``None`` when the whole guard is."""
|
|
80
|
+
|
|
81
|
+
def __init__(self, message: str, partition: str | None = None) -> None:
|
|
82
|
+
super().__init__(message)
|
|
83
|
+
self.partition = partition
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
class InMemoryReplayGuard:
|
|
87
|
+
"""A bounded, single-process :class:`ReplayGuard`.
|
|
88
|
+
|
|
89
|
+
Entries live until their ``until`` and are purged as time passes. One
|
|
90
|
+
partition may hold at most ``max_share`` of ``max_entries`` live entries;
|
|
91
|
+
beyond that its new signatures raise :class:`ReplayGuardFull` and other
|
|
92
|
+
partitions are unaffected. When all ``max_entries`` are live it raises for
|
|
93
|
+
everybody (fail closed) — never evicting a live entry early. Size it so
|
|
94
|
+
that ``max_entries * max_share`` exceeds your busiest legitimate host's
|
|
95
|
+
verified requests per ``replay_window_seconds``."""
|
|
96
|
+
|
|
97
|
+
def __init__(self, max_entries: int = 100_000, *, max_share: float = 0.1,
|
|
98
|
+
clock: Callable[[], float] = time.time) -> None:
|
|
99
|
+
if max_entries < 1:
|
|
100
|
+
raise ValueError("max_entries must be at least 1")
|
|
101
|
+
if not 0 < max_share <= 1:
|
|
102
|
+
raise ValueError("max_share must be in (0, 1]")
|
|
103
|
+
self._max = max_entries
|
|
104
|
+
self._per_partition = max(1, int(max_entries * max_share))
|
|
105
|
+
self._clock = clock
|
|
106
|
+
self._seen: dict[str, tuple[int, str]] = {} # key -> (until, partition)
|
|
107
|
+
self._expiry: list[tuple[int, str]] = []
|
|
108
|
+
self._counts: dict[str, int] = {}
|
|
109
|
+
self._lock = threading.Lock() # first_use may be called from several threads
|
|
110
|
+
|
|
111
|
+
def __len__(self) -> int:
|
|
112
|
+
return len(self._seen)
|
|
113
|
+
|
|
114
|
+
def _purge(self, now: int) -> None:
|
|
115
|
+
while self._expiry and self._expiry[0][0] <= now:
|
|
116
|
+
until, key = heapq.heappop(self._expiry)
|
|
117
|
+
entry = self._seen.get(key)
|
|
118
|
+
if entry is not None and entry[0] == until:
|
|
119
|
+
del self._seen[key]
|
|
120
|
+
left = self._counts[entry[1]] - 1
|
|
121
|
+
if left:
|
|
122
|
+
self._counts[entry[1]] = left
|
|
123
|
+
else:
|
|
124
|
+
del self._counts[entry[1]]
|
|
125
|
+
|
|
126
|
+
async def first_use(self, key: str, *, until: int, partition: str) -> bool:
|
|
127
|
+
with self._lock:
|
|
128
|
+
now = int(self._clock())
|
|
129
|
+
self._purge(now)
|
|
130
|
+
if key in self._seen:
|
|
131
|
+
return False
|
|
132
|
+
if self._counts.get(partition, 0) >= self._per_partition:
|
|
133
|
+
raise ReplayGuardFull(
|
|
134
|
+
f"{self._per_partition} signatures from this partition are still valid",
|
|
135
|
+
partition)
|
|
136
|
+
if len(self._seen) >= self._max:
|
|
137
|
+
raise ReplayGuardFull(f"{self._max} signatures are still valid")
|
|
138
|
+
self._seen[key] = (int(until), partition)
|
|
139
|
+
self._counts[partition] = self._counts.get(partition, 0) + 1
|
|
140
|
+
heapq.heappush(self._expiry, (int(until), key))
|
|
141
|
+
return True
|