tba-protocol-oauth 0.4.0.dev2__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.
- tba_protocol_oauth/__init__.py +122 -0
- tba_protocol_oauth/bindings.py +116 -0
- tba_protocol_oauth/capability_requirements.py +5 -0
- tba_protocol_oauth/claim_sets.py +19 -0
- tba_protocol_oauth/claims.py +79 -0
- tba_protocol_oauth/compatibility.py +39 -0
- tba_protocol_oauth/errors.py +25 -0
- tba_protocol_oauth/features.py +36 -0
- tba_protocol_oauth/jwtoken.py +16 -0
- tba_protocol_oauth/migrations.py +37 -0
- tba_protocol_oauth/protocol.py +282 -0
- tba_protocol_oauth/py.typed +0 -0
- tba_protocol_oauth/reusable_components.py +5 -0
- tba_protocol_oauth/schemas.py +198 -0
- tba_protocol_oauth/standards/__init__.py +9 -0
- tba_protocol_oauth/standards/_dpop/__init__.py +57 -0
- tba_protocol_oauth/standards/_dpop/metadata.py +18 -0
- tba_protocol_oauth/standards/_dpop/primitives.py +194 -0
- tba_protocol_oauth/standards/_dpop/proofs.py +393 -0
- tba_protocol_oauth/standards/_dpop/state.py +74 -0
- tba_protocol_oauth/standards/_introspection_activity.py +32 -0
- tba_protocol_oauth/standards/_mtls_identity.py +98 -0
- tba_protocol_oauth/standards/_rfc8693/__init__.py +26 -0
- tba_protocol_oauth/standards/_rfc8693/endpoint.py +56 -0
- tba_protocol_oauth/standards/_rfc8693/runtime.py +289 -0
- tba_protocol_oauth/standards/_rfc9700/__init__.py +45 -0
- tba_protocol_oauth/standards/_rfc9700/security_profile.py +265 -0
- tba_protocol_oauth/standards/_rfc9700/sender_constraints.py +397 -0
- tba_protocol_oauth/standards/assertion_framework.py +173 -0
- tba_protocol_oauth/standards/authorization_framework.py +102 -0
- tba_protocol_oauth/standards/authorization_server_metadata.py +43 -0
- tba_protocol_oauth/standards/authorization_server_metadata_endpoint.py +21 -0
- tba_protocol_oauth/standards/bearer_token_usage.py +86 -0
- tba_protocol_oauth/standards/client_registration_management.py +89 -0
- tba_protocol_oauth/standards/device_authorization.py +140 -0
- tba_protocol_oauth/standards/dpop.py +59 -0
- tba_protocol_oauth/standards/dynamic_client_registration.py +68 -0
- tba_protocol_oauth/standards/gnap.py +6 -0
- tba_protocol_oauth/standards/introspection.py +56 -0
- tba_protocol_oauth/standards/issuer_identification.py +130 -0
- tba_protocol_oauth/standards/json_web_token.py +159 -0
- tba_protocol_oauth/standards/jwt_access_tokens.py +44 -0
- tba_protocol_oauth/standards/jwt_best_practices.py +44 -0
- tba_protocol_oauth/standards/jwt_client_auth.py +208 -0
- tba_protocol_oauth/standards/jwt_secured_authorization_requests.py +421 -0
- tba_protocol_oauth/standards/legacy_jwt_client_assertions.py +113 -0
- tba_protocol_oauth/standards/mutual_tls_client_authentication.py +394 -0
- tba_protocol_oauth/standards/native_apps.py +132 -0
- tba_protocol_oauth/standards/oauth_security_bcp.py +47 -0
- tba_protocol_oauth/standards/proof_key_for_code_exchange.py +82 -0
- tba_protocol_oauth/standards/protected_resource_metadata.py +103 -0
- tba_protocol_oauth/standards/pushed_authorization_requests.py +198 -0
- tba_protocol_oauth/standards/resource_indicators.py +127 -0
- tba_protocol_oauth/standards/resource_verifier_contract.py +91 -0
- tba_protocol_oauth/standards/revocation.py +59 -0
- tba_protocol_oauth/standards/rich_authorization_requests.py +221 -0
- tba_protocol_oauth/standards/token_endpoint.py +76 -0
- tba_protocol_oauth/standards/token_exchange.py +60 -0
- tba_protocol_oauth/versions.py +110 -0
- tba_protocol_oauth-0.4.0.dev2.dist-info/METADATA +114 -0
- tba_protocol_oauth-0.4.0.dev2.dist-info/RECORD +62 -0
- tba_protocol_oauth-0.4.0.dev2.dist-info/WHEEL +4 -0
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
"""Domain-organized RFC 9449 DPoP helpers.
|
|
2
|
+
|
|
3
|
+
The release/runtime path uses the dedicated Swarmauri DPoP signer when it is
|
|
4
|
+
available, but this module also exposes a dependency-light Ed25519 fallback so
|
|
5
|
+
checkpoint evidence and low-dependency tests can execute without the full
|
|
6
|
+
runtime stack.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import asyncio
|
|
12
|
+
import base64
|
|
13
|
+
import hashlib
|
|
14
|
+
import json
|
|
15
|
+
from typing import Any, Dict, Final
|
|
16
|
+
from tba_primitives_identity.standards import StandardOwner
|
|
17
|
+
|
|
18
|
+
try:
|
|
19
|
+
from cryptography.hazmat.primitives import serialization
|
|
20
|
+
from cryptography.hazmat.primitives.asymmetric.ed25519 import (
|
|
21
|
+
Ed25519PrivateKey,
|
|
22
|
+
Ed25519PublicKey,
|
|
23
|
+
)
|
|
24
|
+
from cryptography.hazmat.primitives.serialization import (
|
|
25
|
+
Encoding,
|
|
26
|
+
NoEncryption,
|
|
27
|
+
PrivateFormat,
|
|
28
|
+
PublicFormat,
|
|
29
|
+
load_pem_private_key,
|
|
30
|
+
load_pem_public_key,
|
|
31
|
+
)
|
|
32
|
+
except (
|
|
33
|
+
Exception
|
|
34
|
+
): # pragma: no cover - cryptography is expected in release/runtime installs
|
|
35
|
+
serialization = None # type: ignore[assignment]
|
|
36
|
+
Ed25519PrivateKey = None # type: ignore[assignment]
|
|
37
|
+
Ed25519PublicKey = None # type: ignore[assignment]
|
|
38
|
+
Encoding = None # type: ignore[assignment]
|
|
39
|
+
NoEncryption = None # type: ignore[assignment]
|
|
40
|
+
PrivateFormat = None # type: ignore[assignment]
|
|
41
|
+
PublicFormat = None # type: ignore[assignment]
|
|
42
|
+
load_pem_private_key = None # type: ignore[assignment]
|
|
43
|
+
load_pem_public_key = None # type: ignore[assignment]
|
|
44
|
+
|
|
45
|
+
RFC9449_SPEC_URL: Final[str] = "https://www.rfc-editor.org/rfc/rfc9449"
|
|
46
|
+
_ALG_VALUE: Final[str] = "EdDSA"
|
|
47
|
+
_TYP_VALUE: Final[str] = "dpop+jwt"
|
|
48
|
+
_ALLOWED_SKEW: Final[int] = 300
|
|
49
|
+
_SIGNER = None # The cryptography-backed implementation in proofs.py is canonical.
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
OWNER = StandardOwner(
|
|
53
|
+
label="RFC 9449",
|
|
54
|
+
title="OAuth 2.0 Demonstrating Proof-of-Possession at the Application Layer",
|
|
55
|
+
runtime_status="dpop-runtime-integrated",
|
|
56
|
+
public_surface=("/token", "/token/exchange", "/userinfo", "/introspect", "/revoke"),
|
|
57
|
+
notes=(
|
|
58
|
+
"DPoP proof verification is runtime-integrated with jkt binding, ath binding, optional nonce validation, "
|
|
59
|
+
"iat freshness checks, and replay-safe jti tracking."
|
|
60
|
+
),
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _run_async(coro: Any) -> Any:
|
|
65
|
+
try:
|
|
66
|
+
asyncio.get_running_loop()
|
|
67
|
+
except RuntimeError:
|
|
68
|
+
return asyncio.run(coro)
|
|
69
|
+
coro.close()
|
|
70
|
+
raise RuntimeError("sync DPoP helpers cannot run inside an active event loop")
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _b64url(data: bytes) -> str:
|
|
74
|
+
return base64.urlsafe_b64encode(data).rstrip(b"=").decode("ascii")
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _b64url_decode(data: str) -> bytes:
|
|
78
|
+
padded = str(data) + ("=" * (-len(str(data)) % 4))
|
|
79
|
+
return base64.urlsafe_b64decode(padded)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _json_segment(payload: dict[str, Any]) -> str:
|
|
83
|
+
return _b64url(
|
|
84
|
+
json.dumps(payload, separators=(",", ":"), sort_keys=True).encode("utf-8")
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _compact_signing_input(header: dict[str, Any], payload: dict[str, Any]) -> str:
|
|
89
|
+
return f"{_json_segment(header)}.{_json_segment(payload)}"
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _raw_public_bytes(public_key: Any) -> bytes:
|
|
93
|
+
if isinstance(public_key, bytes):
|
|
94
|
+
raw = public_key
|
|
95
|
+
elif isinstance(public_key, str):
|
|
96
|
+
raw = public_key.encode("utf-8")
|
|
97
|
+
elif Ed25519PublicKey is not None and isinstance(public_key, Ed25519PublicKey):
|
|
98
|
+
return public_key.public_bytes(Encoding.Raw, PublicFormat.Raw)
|
|
99
|
+
elif (
|
|
100
|
+
hasattr(public_key, "public_bytes")
|
|
101
|
+
and Encoding is not None
|
|
102
|
+
and PublicFormat is not None
|
|
103
|
+
):
|
|
104
|
+
try:
|
|
105
|
+
return public_key.public_bytes(Encoding.Raw, PublicFormat.Raw)
|
|
106
|
+
except Exception:
|
|
107
|
+
raw = b""
|
|
108
|
+
else:
|
|
109
|
+
raw = b""
|
|
110
|
+
if raw.startswith(b"-----BEGIN"):
|
|
111
|
+
if load_pem_public_key is None or Encoding is None or PublicFormat is None:
|
|
112
|
+
raise RuntimeError(
|
|
113
|
+
"PEM public-key conversion requires cryptography serialization support"
|
|
114
|
+
)
|
|
115
|
+
pub_obj = load_pem_public_key(raw)
|
|
116
|
+
return pub_obj.public_bytes(Encoding.Raw, PublicFormat.Raw)
|
|
117
|
+
if raw:
|
|
118
|
+
return raw
|
|
119
|
+
raise ValueError("public key material required for DPoP proof handling")
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _raw_private_bytes(keyref: Any) -> bytes:
|
|
123
|
+
material = getattr(keyref, "material", keyref)
|
|
124
|
+
if isinstance(material, str):
|
|
125
|
+
return material.encode("utf-8")
|
|
126
|
+
if isinstance(material, bytes):
|
|
127
|
+
return material
|
|
128
|
+
if Ed25519PrivateKey is not None and isinstance(material, Ed25519PrivateKey):
|
|
129
|
+
return material.private_bytes(Encoding.Raw, PrivateFormat.Raw, NoEncryption())
|
|
130
|
+
if (
|
|
131
|
+
hasattr(material, "private_bytes")
|
|
132
|
+
and Encoding is not None
|
|
133
|
+
and PrivateFormat is not None
|
|
134
|
+
and NoEncryption is not None
|
|
135
|
+
):
|
|
136
|
+
try:
|
|
137
|
+
return material.private_bytes(
|
|
138
|
+
Encoding.Raw, PrivateFormat.Raw, NoEncryption()
|
|
139
|
+
)
|
|
140
|
+
except Exception:
|
|
141
|
+
pass
|
|
142
|
+
raise ValueError("private key material required for DPoP proof generation")
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def _load_private_key(keyref: Any) -> Any:
|
|
146
|
+
if Ed25519PrivateKey is None:
|
|
147
|
+
raise RuntimeError("cryptography Ed25519 support is unavailable")
|
|
148
|
+
material = getattr(keyref, "material", keyref)
|
|
149
|
+
if isinstance(material, Ed25519PrivateKey):
|
|
150
|
+
return material
|
|
151
|
+
if hasattr(material, "sign") and hasattr(material, "public_key"):
|
|
152
|
+
return material
|
|
153
|
+
raw = _raw_private_bytes(keyref)
|
|
154
|
+
if raw.startswith(b"-----BEGIN"):
|
|
155
|
+
if load_pem_private_key is None:
|
|
156
|
+
raise RuntimeError(
|
|
157
|
+
"PEM private-key conversion requires cryptography serialization support"
|
|
158
|
+
)
|
|
159
|
+
private_key = load_pem_private_key(raw, password=None)
|
|
160
|
+
if not isinstance(private_key, Ed25519PrivateKey):
|
|
161
|
+
raise ValueError("DPoP fallback only supports Ed25519 private keys")
|
|
162
|
+
return private_key
|
|
163
|
+
if len(raw) != 32:
|
|
164
|
+
raise ValueError("DPoP fallback expects Ed25519 raw private key bytes")
|
|
165
|
+
return Ed25519PrivateKey.from_private_bytes(raw)
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
# ---------------------------------------------------------------------------
|
|
169
|
+
# JWK helpers
|
|
170
|
+
# ---------------------------------------------------------------------------
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def jwk_from_public_key(public_key: Any) -> Dict[str, str]:
|
|
174
|
+
x = _b64url(_raw_public_bytes(public_key))
|
|
175
|
+
return {"kty": "OKP", "crv": "Ed25519", "x": x}
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def jwk_thumbprint(jwk: Dict[str, str]) -> str:
|
|
179
|
+
data = json.dumps({k: jwk[k] for k in sorted(jwk)}, separators=(",", ":")).encode()
|
|
180
|
+
digest = hashlib.sha256(data).digest()
|
|
181
|
+
return _b64url(digest)
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
# ---------------------------------------------------------------------------
|
|
185
|
+
# Proof helpers
|
|
186
|
+
# ---------------------------------------------------------------------------
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def ath_for_access_token(access_token: str) -> str:
|
|
190
|
+
digest = hashlib.sha256(str(access_token).encode("utf-8")).digest()
|
|
191
|
+
return _b64url(digest)
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
access_token_hash = ath_for_access_token
|
|
@@ -0,0 +1,393 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import secrets
|
|
5
|
+
import time
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from tba_contracts_identity.protocol_configuration import (
|
|
9
|
+
protocol_settings as settings,
|
|
10
|
+
)
|
|
11
|
+
from tba_contracts_security_trust import DPoPNonceRecord, DPoPProofClaims
|
|
12
|
+
|
|
13
|
+
from .metadata import describe
|
|
14
|
+
from .primitives import (
|
|
15
|
+
OWNER,
|
|
16
|
+
RFC9449_SPEC_URL,
|
|
17
|
+
Ed25519PublicKey,
|
|
18
|
+
StandardOwner,
|
|
19
|
+
_ALG_VALUE,
|
|
20
|
+
_ALLOWED_SKEW,
|
|
21
|
+
_SIGNER,
|
|
22
|
+
_TYP_VALUE,
|
|
23
|
+
_b64url,
|
|
24
|
+
_b64url_decode,
|
|
25
|
+
_compact_signing_input,
|
|
26
|
+
_load_private_key,
|
|
27
|
+
_run_async,
|
|
28
|
+
access_token_hash,
|
|
29
|
+
ath_for_access_token,
|
|
30
|
+
jwk_from_public_key,
|
|
31
|
+
jwk_thumbprint,
|
|
32
|
+
)
|
|
33
|
+
from .state import (
|
|
34
|
+
_maybe_await,
|
|
35
|
+
_require_callable,
|
|
36
|
+
consume_nonce,
|
|
37
|
+
consume_nonce_async,
|
|
38
|
+
issue_nonce,
|
|
39
|
+
issue_nonce_async,
|
|
40
|
+
register_nonce,
|
|
41
|
+
register_nonce_async,
|
|
42
|
+
replay_table_snapshot,
|
|
43
|
+
replay_table_snapshot_async,
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _segments(proof: str) -> tuple[dict[str, Any], dict[str, Any]]:
|
|
48
|
+
parts = str(proof).split(".")
|
|
49
|
+
if len(parts) != 3:
|
|
50
|
+
raise ValueError(f"malformed DPoP proof: {RFC9449_SPEC_URL}")
|
|
51
|
+
try:
|
|
52
|
+
header = json.loads(_b64url_decode(parts[0]).decode("utf-8"))
|
|
53
|
+
payload = json.loads(_b64url_decode(parts[1]).decode("utf-8"))
|
|
54
|
+
except Exception as exc:
|
|
55
|
+
raise ValueError(f"invalid DPoP proof encoding: {RFC9449_SPEC_URL}") from exc
|
|
56
|
+
if not isinstance(header, dict) or not isinstance(payload, dict):
|
|
57
|
+
raise ValueError(f"invalid DPoP proof payload: {RFC9449_SPEC_URL}")
|
|
58
|
+
return header, payload
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def proof_claims(proof: str) -> DPoPProofClaims:
|
|
62
|
+
header, payload = _segments(proof)
|
|
63
|
+
jwk = header.get("jwk")
|
|
64
|
+
if not isinstance(jwk, dict) or not jwk:
|
|
65
|
+
raise ValueError(f"missing jwk in DPoP header: {RFC9449_SPEC_URL}")
|
|
66
|
+
jti = str(payload.get("jti") or "").strip()
|
|
67
|
+
if not jti:
|
|
68
|
+
raise ValueError(f"missing jti in DPoP proof: {RFC9449_SPEC_URL}")
|
|
69
|
+
htm = str(payload.get("htm") or "").upper().strip()
|
|
70
|
+
htu = str(payload.get("htu") or "").strip()
|
|
71
|
+
if not htm or not htu:
|
|
72
|
+
raise ValueError(f"missing htm/htu in DPoP proof: {RFC9449_SPEC_URL}")
|
|
73
|
+
iat_raw = payload.get("iat")
|
|
74
|
+
if iat_raw is not None and not isinstance(iat_raw, int):
|
|
75
|
+
raise ValueError(f"invalid iat in DPoP proof: {RFC9449_SPEC_URL}")
|
|
76
|
+
nonce = payload.get("nonce")
|
|
77
|
+
if nonce is not None and not isinstance(nonce, str):
|
|
78
|
+
raise ValueError(f"invalid nonce in DPoP proof: {RFC9449_SPEC_URL}")
|
|
79
|
+
ath = payload.get("ath")
|
|
80
|
+
if ath is not None and not isinstance(ath, str):
|
|
81
|
+
raise ValueError(f"invalid ath in DPoP proof: {RFC9449_SPEC_URL}")
|
|
82
|
+
normalized_jwk = {str(key): str(value) for key, value in jwk.items()}
|
|
83
|
+
return DPoPProofClaims(
|
|
84
|
+
jti=jti,
|
|
85
|
+
htm=htm,
|
|
86
|
+
htu=htu,
|
|
87
|
+
iat=iat_raw,
|
|
88
|
+
nonce=nonce,
|
|
89
|
+
ath=ath,
|
|
90
|
+
jkt=jwk_thumbprint(normalized_jwk),
|
|
91
|
+
)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def decode_proof(proof: str) -> dict[str, object]:
|
|
95
|
+
return proof_claims(proof).as_dict()
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _verify_fallback_signature(
|
|
99
|
+
proof: str, method: str, url: str, *, max_skew_s: int = _ALLOWED_SKEW
|
|
100
|
+
) -> bool:
|
|
101
|
+
if Ed25519PublicKey is None:
|
|
102
|
+
raise RuntimeError("cryptography Ed25519 support is unavailable")
|
|
103
|
+
header, payload = _segments(proof)
|
|
104
|
+
alg = str(header.get("alg") or "")
|
|
105
|
+
if alg != _ALG_VALUE:
|
|
106
|
+
raise ValueError(f"unsupported DPoP alg: {RFC9449_SPEC_URL}")
|
|
107
|
+
typ = str(header.get("typ") or "").lower().strip()
|
|
108
|
+
if typ and typ != _TYP_VALUE:
|
|
109
|
+
raise ValueError(f"invalid DPoP typ: {RFC9449_SPEC_URL}")
|
|
110
|
+
jwk = header.get("jwk")
|
|
111
|
+
if (
|
|
112
|
+
not isinstance(jwk, dict)
|
|
113
|
+
or str(jwk.get("kty") or "") != "OKP"
|
|
114
|
+
or str(jwk.get("crv") or "") != "Ed25519"
|
|
115
|
+
):
|
|
116
|
+
raise ValueError(f"unsupported DPoP jwk: {RFC9449_SPEC_URL}")
|
|
117
|
+
x = str(jwk.get("x") or "").strip()
|
|
118
|
+
if not x:
|
|
119
|
+
raise ValueError(f"missing DPoP jwk x: {RFC9449_SPEC_URL}")
|
|
120
|
+
htm = str(payload.get("htm") or "").upper().strip()
|
|
121
|
+
htu = str(payload.get("htu") or "").strip()
|
|
122
|
+
if htm != method.upper() or htu != url:
|
|
123
|
+
return False
|
|
124
|
+
iat = payload.get("iat")
|
|
125
|
+
if not isinstance(iat, int):
|
|
126
|
+
raise ValueError(f"missing iat in DPoP proof: {RFC9449_SPEC_URL}")
|
|
127
|
+
if abs(int(time.time()) - int(iat)) > max_skew_s:
|
|
128
|
+
raise ValueError(f"stale DPoP proof: {RFC9449_SPEC_URL}")
|
|
129
|
+
parts = str(proof).split(".")
|
|
130
|
+
if len(parts) != 3:
|
|
131
|
+
raise ValueError(f"malformed DPoP proof: {RFC9449_SPEC_URL}")
|
|
132
|
+
public_key = Ed25519PublicKey.from_public_bytes(_b64url_decode(x))
|
|
133
|
+
try:
|
|
134
|
+
public_key.verify(
|
|
135
|
+
_b64url_decode(parts[2]), f"{parts[0]}.{parts[1]}".encode("ascii")
|
|
136
|
+
)
|
|
137
|
+
except Exception:
|
|
138
|
+
return False
|
|
139
|
+
return True
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _verify_signature_requirements(
|
|
143
|
+
proof: str, method: str, url: str, *, max_skew_s: int = _ALLOWED_SKEW
|
|
144
|
+
) -> bool:
|
|
145
|
+
if _SIGNER is not None:
|
|
146
|
+
try:
|
|
147
|
+
verified = bool(
|
|
148
|
+
_run_async(
|
|
149
|
+
_SIGNER.verify_bytes(
|
|
150
|
+
b"",
|
|
151
|
+
[{"sig": proof}],
|
|
152
|
+
require={
|
|
153
|
+
"htm": method.upper(),
|
|
154
|
+
"htu": url,
|
|
155
|
+
"algs": [_ALG_VALUE],
|
|
156
|
+
"max_skew_s": max_skew_s,
|
|
157
|
+
},
|
|
158
|
+
)
|
|
159
|
+
)
|
|
160
|
+
)
|
|
161
|
+
if verified:
|
|
162
|
+
return True
|
|
163
|
+
except Exception:
|
|
164
|
+
pass
|
|
165
|
+
return _verify_fallback_signature(proof, method, url, max_skew_s=max_skew_s)
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
async def _verify_signature_requirements_async(
|
|
169
|
+
proof: str,
|
|
170
|
+
method: str,
|
|
171
|
+
url: str,
|
|
172
|
+
*,
|
|
173
|
+
max_skew_s: int = _ALLOWED_SKEW,
|
|
174
|
+
) -> bool:
|
|
175
|
+
if _SIGNER is not None:
|
|
176
|
+
try:
|
|
177
|
+
verified = bool(
|
|
178
|
+
await _SIGNER.verify_bytes(
|
|
179
|
+
b"",
|
|
180
|
+
[{"sig": proof}],
|
|
181
|
+
require={
|
|
182
|
+
"htm": method.upper(),
|
|
183
|
+
"htu": url,
|
|
184
|
+
"algs": [_ALG_VALUE],
|
|
185
|
+
"max_skew_s": max_skew_s,
|
|
186
|
+
},
|
|
187
|
+
)
|
|
188
|
+
)
|
|
189
|
+
if verified:
|
|
190
|
+
return True
|
|
191
|
+
except Exception:
|
|
192
|
+
pass
|
|
193
|
+
return _verify_fallback_signature(proof, method, url, max_skew_s=max_skew_s)
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def make_proof(
|
|
197
|
+
keyref: Any,
|
|
198
|
+
method: str,
|
|
199
|
+
url: str,
|
|
200
|
+
*,
|
|
201
|
+
access_token: str | None = None,
|
|
202
|
+
nonce: str | None = None,
|
|
203
|
+
enabled: bool | None = None,
|
|
204
|
+
) -> str:
|
|
205
|
+
if enabled is None:
|
|
206
|
+
enabled = settings.enable_rfc9449
|
|
207
|
+
if not enabled:
|
|
208
|
+
return ""
|
|
209
|
+
if _SIGNER is not None:
|
|
210
|
+
priv = getattr(keyref, "material", b"") or b""
|
|
211
|
+
if isinstance(priv, str):
|
|
212
|
+
priv = priv.encode()
|
|
213
|
+
opts: dict[str, Any] = {"htm": method.upper(), "htu": url}
|
|
214
|
+
if access_token:
|
|
215
|
+
opts["ath"] = ath_for_access_token(access_token)
|
|
216
|
+
if nonce:
|
|
217
|
+
opts["nonce"] = str(nonce)
|
|
218
|
+
sigs = _run_async(
|
|
219
|
+
_SIGNER.sign_bytes(
|
|
220
|
+
{"kind": "pem", "priv": priv},
|
|
221
|
+
b"",
|
|
222
|
+
alg=_ALG_VALUE,
|
|
223
|
+
opts=opts,
|
|
224
|
+
)
|
|
225
|
+
)
|
|
226
|
+
proof = sigs[0]["sig"]
|
|
227
|
+
try:
|
|
228
|
+
claims = proof_claims(proof)
|
|
229
|
+
expected_ath = (
|
|
230
|
+
ath_for_access_token(access_token) if access_token is not None else None
|
|
231
|
+
)
|
|
232
|
+
if expected_ath is not None and claims.ath != expected_ath:
|
|
233
|
+
raise ValueError("ath mismatch")
|
|
234
|
+
if nonce is not None and claims.nonce != str(nonce):
|
|
235
|
+
raise ValueError("nonce mismatch")
|
|
236
|
+
return proof
|
|
237
|
+
except Exception:
|
|
238
|
+
# Fallback to local Ed25519 compact-JWT signer when the runtime signer
|
|
239
|
+
# omits required claims (ath/nonce) in dependency-light environments.
|
|
240
|
+
pass
|
|
241
|
+
|
|
242
|
+
private_key = _load_private_key(keyref)
|
|
243
|
+
public_material = getattr(keyref, "public", None)
|
|
244
|
+
if public_material in {None, b"", ""}:
|
|
245
|
+
public_material = private_key.public_key()
|
|
246
|
+
jwk = jwk_from_public_key(public_material)
|
|
247
|
+
header = {"typ": _TYP_VALUE, "alg": _ALG_VALUE, "jwk": jwk}
|
|
248
|
+
payload: dict[str, Any] = {
|
|
249
|
+
"jti": secrets.token_urlsafe(24),
|
|
250
|
+
"htm": method.upper(),
|
|
251
|
+
"htu": url,
|
|
252
|
+
"iat": int(time.time()),
|
|
253
|
+
}
|
|
254
|
+
if access_token is not None:
|
|
255
|
+
payload["ath"] = ath_for_access_token(access_token)
|
|
256
|
+
if nonce is not None:
|
|
257
|
+
payload["nonce"] = str(nonce)
|
|
258
|
+
signing_input = _compact_signing_input(header, payload)
|
|
259
|
+
signature = private_key.sign(signing_input.encode("ascii"))
|
|
260
|
+
return f"{signing_input}.{_b64url(signature)}"
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
makeProof = make_proof
|
|
264
|
+
create_proof = make_proof
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def verify_proof(
|
|
268
|
+
proof: str,
|
|
269
|
+
method: str,
|
|
270
|
+
url: str,
|
|
271
|
+
*,
|
|
272
|
+
jkt: str | None = None,
|
|
273
|
+
access_token: str | None = None,
|
|
274
|
+
expected_nonce: str | None = None,
|
|
275
|
+
require_nonce: bool = False,
|
|
276
|
+
enabled: bool | None = None,
|
|
277
|
+
replay_checker: Any | None = None,
|
|
278
|
+
nonce_consumer: Any | None = None,
|
|
279
|
+
) -> str:
|
|
280
|
+
if enabled is None:
|
|
281
|
+
enabled = settings.enable_rfc9449
|
|
282
|
+
if not enabled:
|
|
283
|
+
return ""
|
|
284
|
+
claims = proof_claims(proof)
|
|
285
|
+
if claims.htm != method.upper():
|
|
286
|
+
raise ValueError(f"htm mismatch: {RFC9449_SPEC_URL}")
|
|
287
|
+
if claims.htu != url:
|
|
288
|
+
raise ValueError(f"htu mismatch: {RFC9449_SPEC_URL}")
|
|
289
|
+
if claims.iat is None:
|
|
290
|
+
raise ValueError(f"missing iat in DPoP proof: {RFC9449_SPEC_URL}")
|
|
291
|
+
if abs(int(time.time()) - int(claims.iat)) > _ALLOWED_SKEW:
|
|
292
|
+
raise ValueError(f"stale DPoP proof: {RFC9449_SPEC_URL}")
|
|
293
|
+
valid = _verify_signature_requirements(proof, method, url)
|
|
294
|
+
if not valid:
|
|
295
|
+
raise ValueError(f"invalid DPoP proof: {RFC9449_SPEC_URL}")
|
|
296
|
+
if jkt and claims.jkt != jkt:
|
|
297
|
+
raise ValueError(f"jkt mismatch: {RFC9449_SPEC_URL}")
|
|
298
|
+
if access_token is not None:
|
|
299
|
+
expected_ath = ath_for_access_token(access_token)
|
|
300
|
+
if claims.ath != expected_ath:
|
|
301
|
+
raise ValueError(f"ath mismatch: {RFC9449_SPEC_URL}")
|
|
302
|
+
if expected_nonce is not None:
|
|
303
|
+
if claims.nonce != expected_nonce:
|
|
304
|
+
raise ValueError(f"nonce mismatch: {RFC9449_SPEC_URL}")
|
|
305
|
+
consumer = _require_callable(nonce_consumer, "expected_nonce validation")
|
|
306
|
+
if not consumer(expected_nonce):
|
|
307
|
+
raise ValueError(f"invalid or expired nonce: {RFC9449_SPEC_URL}")
|
|
308
|
+
elif require_nonce and not claims.nonce:
|
|
309
|
+
raise ValueError(f"nonce required: {RFC9449_SPEC_URL}")
|
|
310
|
+
checker = _require_callable(replay_checker, "verify_proof")
|
|
311
|
+
if checker(claims, ttl_s=_ALLOWED_SKEW):
|
|
312
|
+
raise ValueError(f"replayed DPoP proof: {RFC9449_SPEC_URL}")
|
|
313
|
+
return claims.jkt
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
async def verify_proof_async(
|
|
317
|
+
proof: str,
|
|
318
|
+
method: str,
|
|
319
|
+
url: str,
|
|
320
|
+
*,
|
|
321
|
+
jkt: str | None = None,
|
|
322
|
+
access_token: str | None = None,
|
|
323
|
+
expected_nonce: str | None = None,
|
|
324
|
+
require_nonce: bool = False,
|
|
325
|
+
enabled: bool | None = None,
|
|
326
|
+
replay_checker: Any | None = None,
|
|
327
|
+
nonce_consumer: Any | None = None,
|
|
328
|
+
) -> str:
|
|
329
|
+
if enabled is None:
|
|
330
|
+
enabled = settings.enable_rfc9449
|
|
331
|
+
if not enabled:
|
|
332
|
+
return ""
|
|
333
|
+
claims = proof_claims(proof)
|
|
334
|
+
if claims.htm != method.upper():
|
|
335
|
+
raise ValueError(f"htm mismatch: {RFC9449_SPEC_URL}")
|
|
336
|
+
if claims.htu != url:
|
|
337
|
+
raise ValueError(f"htu mismatch: {RFC9449_SPEC_URL}")
|
|
338
|
+
if claims.iat is None:
|
|
339
|
+
raise ValueError(f"missing iat in DPoP proof: {RFC9449_SPEC_URL}")
|
|
340
|
+
if abs(int(time.time()) - int(claims.iat)) > _ALLOWED_SKEW:
|
|
341
|
+
raise ValueError(f"stale DPoP proof: {RFC9449_SPEC_URL}")
|
|
342
|
+
valid = await _verify_signature_requirements_async(proof, method, url)
|
|
343
|
+
if not valid:
|
|
344
|
+
raise ValueError(f"invalid DPoP proof: {RFC9449_SPEC_URL}")
|
|
345
|
+
if jkt and claims.jkt != jkt:
|
|
346
|
+
raise ValueError(f"jkt mismatch: {RFC9449_SPEC_URL}")
|
|
347
|
+
if access_token is not None:
|
|
348
|
+
expected_ath = ath_for_access_token(access_token)
|
|
349
|
+
if claims.ath != expected_ath:
|
|
350
|
+
raise ValueError(f"ath mismatch: {RFC9449_SPEC_URL}")
|
|
351
|
+
if expected_nonce is not None:
|
|
352
|
+
if claims.nonce != expected_nonce:
|
|
353
|
+
raise ValueError(f"nonce mismatch: {RFC9449_SPEC_URL}")
|
|
354
|
+
consumer = _require_callable(nonce_consumer, "expected_nonce validation")
|
|
355
|
+
if not await _maybe_await(consumer(expected_nonce)):
|
|
356
|
+
raise ValueError(f"invalid or expired nonce: {RFC9449_SPEC_URL}")
|
|
357
|
+
elif require_nonce and not claims.nonce:
|
|
358
|
+
raise ValueError(f"nonce required: {RFC9449_SPEC_URL}")
|
|
359
|
+
|
|
360
|
+
checker = _require_callable(replay_checker, "verify_proof_async")
|
|
361
|
+
replayed = await _maybe_await(checker(claims, ttl_s=_ALLOWED_SKEW))
|
|
362
|
+
if replayed:
|
|
363
|
+
raise ValueError(f"replayed DPoP proof: {RFC9449_SPEC_URL}")
|
|
364
|
+
return claims.jkt
|
|
365
|
+
|
|
366
|
+
|
|
367
|
+
__all__ = [
|
|
368
|
+
"RFC9449_SPEC_URL",
|
|
369
|
+
"DPoPNonceRecord",
|
|
370
|
+
"DPoPProofClaims",
|
|
371
|
+
"StandardOwner",
|
|
372
|
+
"OWNER",
|
|
373
|
+
"access_token_hash",
|
|
374
|
+
"ath_for_access_token",
|
|
375
|
+
"consume_nonce",
|
|
376
|
+
"consume_nonce_async",
|
|
377
|
+
"create_proof",
|
|
378
|
+
"decode_proof",
|
|
379
|
+
"describe",
|
|
380
|
+
"issue_nonce",
|
|
381
|
+
"issue_nonce_async",
|
|
382
|
+
"jwk_from_public_key",
|
|
383
|
+
"jwk_thumbprint",
|
|
384
|
+
"makeProof",
|
|
385
|
+
"make_proof",
|
|
386
|
+
"proof_claims",
|
|
387
|
+
"register_nonce",
|
|
388
|
+
"register_nonce_async",
|
|
389
|
+
"replay_table_snapshot",
|
|
390
|
+
"replay_table_snapshot_async",
|
|
391
|
+
"verify_proof_async",
|
|
392
|
+
"verify_proof",
|
|
393
|
+
]
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
"""Injected durable-state adapters for DPoP nonce and replay operations."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import inspect
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from .primitives import _ALLOWED_SKEW
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def _require_callable(fn: Any | None, purpose: str) -> Any:
|
|
12
|
+
if not callable(fn):
|
|
13
|
+
raise RuntimeError(
|
|
14
|
+
f"{purpose} requires an injected DPoP table-backed operation"
|
|
15
|
+
)
|
|
16
|
+
return fn
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
async def _maybe_await(value: Any) -> Any:
|
|
20
|
+
if inspect.isawaitable(value):
|
|
21
|
+
return await value
|
|
22
|
+
return value
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def issue_nonce(*, ttl_s: int = _ALLOWED_SKEW, issuer: Any | None = None) -> str:
|
|
26
|
+
return _require_callable(issuer, "issue_nonce")(ttl_s=ttl_s)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
async def issue_nonce_async(
|
|
30
|
+
*, ttl_s: int = _ALLOWED_SKEW, issuer: Any | None = None
|
|
31
|
+
) -> str:
|
|
32
|
+
return await _maybe_await(
|
|
33
|
+
_require_callable(issuer, "issue_nonce_async")(ttl_s=ttl_s)
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def register_nonce(
|
|
38
|
+
nonce: str, *, ttl_s: int = _ALLOWED_SKEW, registrar: Any | None = None
|
|
39
|
+
) -> str:
|
|
40
|
+
return _require_callable(registrar, "register_nonce")(nonce, ttl_s=ttl_s)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
async def register_nonce_async(
|
|
44
|
+
nonce: str, *, ttl_s: int = _ALLOWED_SKEW, registrar: Any | None = None
|
|
45
|
+
) -> str:
|
|
46
|
+
return await _maybe_await(
|
|
47
|
+
_require_callable(registrar, "register_nonce_async")(nonce, ttl_s=ttl_s)
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def consume_nonce(
|
|
52
|
+
nonce: str, *, consumer: Any | None = None, now: int | None = None
|
|
53
|
+
) -> bool:
|
|
54
|
+
return _require_callable(consumer, "consume_nonce")(nonce, now=now)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
async def consume_nonce_async(
|
|
58
|
+
nonce: str, *, consumer: Any | None = None, now: int | None = None
|
|
59
|
+
) -> bool:
|
|
60
|
+
return await _maybe_await(
|
|
61
|
+
_require_callable(consumer, "consume_nonce_async")(nonce, now=now)
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def replay_table_snapshot(snapshotter: Any | None = None) -> dict[str, int]:
|
|
66
|
+
return _require_callable(snapshotter, "replay_table_snapshot")()
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
async def replay_table_snapshot_async(
|
|
70
|
+
snapshotter: Any | None = None,
|
|
71
|
+
) -> dict[str, int]:
|
|
72
|
+
return await _maybe_await(
|
|
73
|
+
_require_callable(snapshotter, "replay_table_snapshot_async")()
|
|
74
|
+
)
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import Any, Dict
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def header(request: Any, name: str) -> str | None:
|
|
7
|
+
headers = getattr(request, "headers", {}) or {}
|
|
8
|
+
if hasattr(headers, "get"):
|
|
9
|
+
return headers.get(name) or headers.get(name.lower())
|
|
10
|
+
return None
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def authorization_snapshot_stale(payload: Dict[str, Any]) -> bool:
|
|
14
|
+
issued_version = payload.get("authz_version")
|
|
15
|
+
current_version = payload.get("current_authz_version")
|
|
16
|
+
if issued_version is None or current_version is None:
|
|
17
|
+
return False
|
|
18
|
+
try:
|
|
19
|
+
return int(issued_version) != int(current_version)
|
|
20
|
+
except (TypeError, ValueError):
|
|
21
|
+
return str(issued_version) != str(current_version)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def apply_introspection_activity_constraints(payload: Dict[str, Any]) -> Dict[str, Any]:
|
|
25
|
+
if payload.get("active") is False:
|
|
26
|
+
return payload
|
|
27
|
+
if not authorization_snapshot_stale(payload):
|
|
28
|
+
return payload
|
|
29
|
+
inactive = dict(payload)
|
|
30
|
+
inactive["active"] = False
|
|
31
|
+
inactive["inactive_reason"] = "authorization_snapshot_stale"
|
|
32
|
+
return inactive
|