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.
Files changed (62) hide show
  1. tba_protocol_oauth/__init__.py +122 -0
  2. tba_protocol_oauth/bindings.py +116 -0
  3. tba_protocol_oauth/capability_requirements.py +5 -0
  4. tba_protocol_oauth/claim_sets.py +19 -0
  5. tba_protocol_oauth/claims.py +79 -0
  6. tba_protocol_oauth/compatibility.py +39 -0
  7. tba_protocol_oauth/errors.py +25 -0
  8. tba_protocol_oauth/features.py +36 -0
  9. tba_protocol_oauth/jwtoken.py +16 -0
  10. tba_protocol_oauth/migrations.py +37 -0
  11. tba_protocol_oauth/protocol.py +282 -0
  12. tba_protocol_oauth/py.typed +0 -0
  13. tba_protocol_oauth/reusable_components.py +5 -0
  14. tba_protocol_oauth/schemas.py +198 -0
  15. tba_protocol_oauth/standards/__init__.py +9 -0
  16. tba_protocol_oauth/standards/_dpop/__init__.py +57 -0
  17. tba_protocol_oauth/standards/_dpop/metadata.py +18 -0
  18. tba_protocol_oauth/standards/_dpop/primitives.py +194 -0
  19. tba_protocol_oauth/standards/_dpop/proofs.py +393 -0
  20. tba_protocol_oauth/standards/_dpop/state.py +74 -0
  21. tba_protocol_oauth/standards/_introspection_activity.py +32 -0
  22. tba_protocol_oauth/standards/_mtls_identity.py +98 -0
  23. tba_protocol_oauth/standards/_rfc8693/__init__.py +26 -0
  24. tba_protocol_oauth/standards/_rfc8693/endpoint.py +56 -0
  25. tba_protocol_oauth/standards/_rfc8693/runtime.py +289 -0
  26. tba_protocol_oauth/standards/_rfc9700/__init__.py +45 -0
  27. tba_protocol_oauth/standards/_rfc9700/security_profile.py +265 -0
  28. tba_protocol_oauth/standards/_rfc9700/sender_constraints.py +397 -0
  29. tba_protocol_oauth/standards/assertion_framework.py +173 -0
  30. tba_protocol_oauth/standards/authorization_framework.py +102 -0
  31. tba_protocol_oauth/standards/authorization_server_metadata.py +43 -0
  32. tba_protocol_oauth/standards/authorization_server_metadata_endpoint.py +21 -0
  33. tba_protocol_oauth/standards/bearer_token_usage.py +86 -0
  34. tba_protocol_oauth/standards/client_registration_management.py +89 -0
  35. tba_protocol_oauth/standards/device_authorization.py +140 -0
  36. tba_protocol_oauth/standards/dpop.py +59 -0
  37. tba_protocol_oauth/standards/dynamic_client_registration.py +68 -0
  38. tba_protocol_oauth/standards/gnap.py +6 -0
  39. tba_protocol_oauth/standards/introspection.py +56 -0
  40. tba_protocol_oauth/standards/issuer_identification.py +130 -0
  41. tba_protocol_oauth/standards/json_web_token.py +159 -0
  42. tba_protocol_oauth/standards/jwt_access_tokens.py +44 -0
  43. tba_protocol_oauth/standards/jwt_best_practices.py +44 -0
  44. tba_protocol_oauth/standards/jwt_client_auth.py +208 -0
  45. tba_protocol_oauth/standards/jwt_secured_authorization_requests.py +421 -0
  46. tba_protocol_oauth/standards/legacy_jwt_client_assertions.py +113 -0
  47. tba_protocol_oauth/standards/mutual_tls_client_authentication.py +394 -0
  48. tba_protocol_oauth/standards/native_apps.py +132 -0
  49. tba_protocol_oauth/standards/oauth_security_bcp.py +47 -0
  50. tba_protocol_oauth/standards/proof_key_for_code_exchange.py +82 -0
  51. tba_protocol_oauth/standards/protected_resource_metadata.py +103 -0
  52. tba_protocol_oauth/standards/pushed_authorization_requests.py +198 -0
  53. tba_protocol_oauth/standards/resource_indicators.py +127 -0
  54. tba_protocol_oauth/standards/resource_verifier_contract.py +91 -0
  55. tba_protocol_oauth/standards/revocation.py +59 -0
  56. tba_protocol_oauth/standards/rich_authorization_requests.py +221 -0
  57. tba_protocol_oauth/standards/token_endpoint.py +76 -0
  58. tba_protocol_oauth/standards/token_exchange.py +60 -0
  59. tba_protocol_oauth/versions.py +110 -0
  60. tba_protocol_oauth-0.4.0.dev2.dist-info/METADATA +114 -0
  61. tba_protocol_oauth-0.4.0.dev2.dist-info/RECORD +62 -0
  62. tba_protocol_oauth-0.4.0.dev2.dist-info/WHEEL +4 -0
@@ -0,0 +1,208 @@
1
+ """RFC 7523 JWT client-auth helpers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import time
6
+ import uuid
7
+ from typing import Any, Final, Iterable
8
+
9
+ from tba_primitives_identity.standards import StandardOwner, describe_owner
10
+
11
+ from tba_contracts_identity.protocol_configuration import (
12
+ protocol_settings as settings,
13
+ )
14
+ from tba_protocol_oauth.standards.mutual_tls_client_authentication import (
15
+ SUPPORTED_MTLS_AUTH_METHODS,
16
+ )
17
+ from tba_protocol_oauth.standards.json_web_token import decode_jwt, encode_jwt
18
+ from tba_protocol_oauth.standards.assertion_framework import (
19
+ JWT_BEARER_ASSERTION_TYPE,
20
+ validate_temporal_claims,
21
+ )
22
+
23
+ STATUS: Final[str] = "jwt-client-auth-runtime-integrated"
24
+ RFC7523_SPEC_URL: Final[str] = "https://www.rfc-editor.org/rfc/rfc7523"
25
+ REQUIRED_CLAIMS: Final[set[str]] = {"iss", "sub", "aud", "exp"}
26
+ STRICT_CLIENT_ASSERTION_CLAIMS: Final[set[str]] = REQUIRED_CLAIMS | {"iat", "jti"}
27
+ PRIVATE_KEY_JWT_AUTH_METHOD: Final[str] = "private_key_jwt"
28
+ CLIENT_SECRET_JWT_AUTH_METHOD: Final[str] = "client_secret_jwt"
29
+ SUPPORTED_CLIENT_ASSERTION_AUTH_METHODS: Final[tuple[str, ...]] = (
30
+ PRIVATE_KEY_JWT_AUTH_METHOD,
31
+ )
32
+ SUPPORTED_CLIENT_ASSERTION_SIGNING_ALGS: Final[tuple[str, ...]] = ("EdDSA",)
33
+
34
+
35
+ OWNER = StandardOwner(
36
+ label="RFC 7523",
37
+ title="JWT Profile for OAuth 2.0 Client Authentication and Authorization Grants",
38
+ runtime_status=STATUS,
39
+ public_surface=("/token",),
40
+ notes="Runtime-integrated JWT bearer assertion validation for token-endpoint client authentication and authorization grants.",
41
+ )
42
+
43
+
44
+ def _coerce_audiences(audience: str | Iterable[str] | None) -> set[str]:
45
+ if audience is None:
46
+ return set()
47
+ if isinstance(audience, str):
48
+ return {audience}
49
+ return {str(item) for item in audience}
50
+
51
+
52
+ def _coerce_aud_claim(value: object) -> set[str]:
53
+ if isinstance(value, str):
54
+ return {value}
55
+ if isinstance(value, (list, tuple, set)):
56
+ return {str(item) for item in value}
57
+ raise ValueError("invalid aud claim")
58
+
59
+
60
+ def validate_client_jwt_bearer(
61
+ assertion: str,
62
+ *,
63
+ audience: str | Iterable[str] | None = None,
64
+ client_id: str | None = None,
65
+ now: int | None = None,
66
+ leeway_seconds: int = 30,
67
+ require_strict_claims: bool = False,
68
+ decoder=decode_jwt,
69
+ ) -> dict[str, object]:
70
+ """Validate a client assertion per RFC 7523."""
71
+
72
+ if not settings.enable_rfc7523:
73
+ raise RuntimeError(f"RFC 7523 support disabled: {RFC7523_SPEC_URL}")
74
+ claims = dict(decoder(assertion))
75
+ required_claims = (
76
+ STRICT_CLIENT_ASSERTION_CLAIMS if require_strict_claims else REQUIRED_CLAIMS
77
+ )
78
+ missing = required_claims - claims.keys()
79
+ if missing:
80
+ raise ValueError(f"missing claims: {', '.join(sorted(missing))}")
81
+ validate_temporal_claims(claims, now=now, leeway_seconds=leeway_seconds)
82
+ iss = str(claims.get("iss") or "")
83
+ sub = str(claims.get("sub") or "")
84
+ if iss != sub:
85
+ raise ValueError("iss and sub must match for client authentication")
86
+ if client_id is not None and iss != client_id:
87
+ raise ValueError("client assertion subject does not match client_id")
88
+ expected_audiences = _coerce_audiences(audience)
89
+ if expected_audiences:
90
+ aud_values = _coerce_aud_claim(claims["aud"])
91
+ if aud_values.isdisjoint(expected_audiences):
92
+ raise ValueError("invalid audience")
93
+ if require_strict_claims:
94
+ jti = claims.get("jti")
95
+ if not isinstance(jti, str) or not jti.strip():
96
+ raise ValueError("missing claims: jti")
97
+ return claims
98
+
99
+
100
+ def authenticate_client_assertion(
101
+ *,
102
+ client_assertion_type: str,
103
+ client_assertion: str,
104
+ audience: str | Iterable[str] | None,
105
+ client_id: str | None = None,
106
+ token_endpoint_auth_method: str | None = None,
107
+ ) -> dict[str, object]:
108
+ if not settings.enable_rfc7523:
109
+ raise RuntimeError(f"RFC 7523 support disabled: {RFC7523_SPEC_URL}")
110
+ if client_assertion_type != JWT_BEARER_ASSERTION_TYPE:
111
+ raise ValueError("unsupported client_assertion_type")
112
+ if token_endpoint_auth_method not in {
113
+ None,
114
+ PRIVATE_KEY_JWT_AUTH_METHOD,
115
+ CLIENT_SECRET_JWT_AUTH_METHOD,
116
+ }:
117
+ raise ValueError("unsupported token_endpoint_auth_method")
118
+ return validate_client_jwt_bearer(
119
+ client_assertion,
120
+ audience=audience,
121
+ client_id=client_id,
122
+ require_strict_claims=True,
123
+ )
124
+
125
+
126
+ def make_client_assertion_jwt(
127
+ client_id: str,
128
+ audience: str,
129
+ *,
130
+ expires_in: int = 300,
131
+ additional_claims: dict[str, Any] | None = None,
132
+ ) -> str:
133
+ """Mint a client assertion JWT suitable for RFC 7523 flows."""
134
+
135
+ if not settings.enable_rfc7523:
136
+ raise RuntimeError(f"RFC 7523 support disabled: {RFC7523_SPEC_URL}")
137
+ current_time = int(time.time())
138
+ claims: dict[str, Any] = {
139
+ "iss": client_id,
140
+ "sub": client_id,
141
+ "aud": audience,
142
+ "exp": current_time + expires_in,
143
+ "iat": current_time,
144
+ "jti": str(uuid.uuid4()),
145
+ }
146
+ if additional_claims:
147
+ claims.update(additional_claims)
148
+ return encode_jwt(**claims)
149
+
150
+
151
+ def token_endpoint_auth_methods_supported() -> list[str]:
152
+ methods = ["client_secret_basic", "client_secret_post"]
153
+ if settings.enable_rfc7523:
154
+ methods.append(PRIVATE_KEY_JWT_AUTH_METHOD)
155
+ if settings.enable_rfc8705:
156
+ methods.extend(SUPPORTED_MTLS_AUTH_METHODS)
157
+ return list(dict.fromkeys(methods))
158
+
159
+
160
+ def token_endpoint_auth_signing_alg_values_supported() -> list[str]:
161
+ return (
162
+ list(SUPPORTED_CLIENT_ASSERTION_SIGNING_ALGS) if settings.enable_rfc7523 else []
163
+ )
164
+
165
+
166
+ def build_client_assertion_contract_examples(
167
+ token_endpoint_audience: str,
168
+ ) -> list[dict[str, Any]]:
169
+ return [
170
+ {
171
+ "client_id": "<client-id>",
172
+ "client_assertion_type": JWT_BEARER_ASSERTION_TYPE,
173
+ "client_assertion": "<jwt-client-assertion>",
174
+ "token_endpoint_auth_method": PRIVATE_KEY_JWT_AUTH_METHOD,
175
+ "audience": token_endpoint_audience,
176
+ }
177
+ ]
178
+
179
+
180
+ def describe() -> dict[str, object]:
181
+ return describe_owner(
182
+ OWNER,
183
+ spec_url=RFC7523_SPEC_URL,
184
+ token_endpoint_auth_methods_supported=token_endpoint_auth_methods_supported(),
185
+ token_endpoint_auth_signing_alg_values_supported=token_endpoint_auth_signing_alg_values_supported(),
186
+ )
187
+
188
+
189
+ __all__ = [
190
+ "STATUS",
191
+ "RFC7523_SPEC_URL",
192
+ "REQUIRED_CLAIMS",
193
+ "STRICT_CLIENT_ASSERTION_CLAIMS",
194
+ "PRIVATE_KEY_JWT_AUTH_METHOD",
195
+ "CLIENT_SECRET_JWT_AUTH_METHOD",
196
+ "SUPPORTED_CLIENT_ASSERTION_AUTH_METHODS",
197
+ "SUPPORTED_CLIENT_ASSERTION_SIGNING_ALGS",
198
+ "StandardOwner",
199
+ "OWNER",
200
+ "JWT_BEARER_ASSERTION_TYPE",
201
+ "authenticate_client_assertion",
202
+ "build_client_assertion_contract_examples",
203
+ "describe",
204
+ "make_client_assertion_jwt",
205
+ "token_endpoint_auth_methods_supported",
206
+ "token_endpoint_auth_signing_alg_values_supported",
207
+ "validate_client_jwt_bearer",
208
+ ]
@@ -0,0 +1,421 @@
1
+ """OAuth 2.0 JWT-Secured Authorization Request owner and runtime helpers.
2
+
3
+ The active repository profile keeps a deliberately bounded JAR implementation:
4
+
5
+ - compact JWS request objects only
6
+ - signed request objects only (`alg=none` is rejected)
7
+ - HMAC request-object signatures using `HS256` / `HS384` / `HS512`
8
+ - temporal validation for `exp`, `nbf`, and `iat` when present
9
+ - client and audience consistency checks when the caller provides expectations
10
+ - deterministic merge semantics between query/form parameters and request-object claims
11
+
12
+ The helpers stay dependency-light so targeted standards tests and evidence can run
13
+ without importing the full Tigrbl runtime stack.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import base64
19
+ import hashlib
20
+ import hmac
21
+ import json
22
+ from datetime import datetime, timedelta, timezone
23
+ from typing import Any, Final, Iterable, Mapping, Sequence
24
+ from tba_primitives_identity.standards import StandardOwner, describe_owner
25
+ from tba_contracts_identity.oauth import RequestObjectPolicy
26
+
27
+ from tba_contracts_identity.protocol_configuration import (
28
+ protocol_settings as settings,
29
+ )
30
+
31
+ STATUS: Final[str] = "request-object-runtime"
32
+ RFC9101_SPEC_URL: Final[str] = "https://www.rfc-editor.org/rfc/rfc9101"
33
+ SUPPORTED_JAR_ALG_VALUES: Final[tuple[str, ...]] = ("HS256", "HS384", "HS512")
34
+ DEFAULT_REQUEST_OBJECT_LIFETIME_SECONDS: Final[int] = 300
35
+ DEFAULT_CLOCK_SKEW_SECONDS: Final[int] = 60
36
+
37
+
38
+ OWNER = StandardOwner(
39
+ label="RFC 9101",
40
+ title="OAuth 2.0 JWT-Secured Authorization Request (JAR)",
41
+ runtime_status=STATUS,
42
+ public_surface=("/authorize", "/par"),
43
+ notes=(
44
+ "Canonical standards-tree owner module for request-object signing, verification, "
45
+ "temporal validation, and parameter-consistency enforcement wired into the "
46
+ "authorization and PAR release path."
47
+ ),
48
+ )
49
+
50
+ ACTIVE_REQUEST_OBJECT_POLICY: Final[RequestObjectPolicy] = RequestObjectPolicy()
51
+
52
+
53
+ class RequestObjectValidationError(ValueError):
54
+ """Raised when a request object violates the active bounded JAR profile."""
55
+
56
+
57
+ def _b64url_encode(data: bytes) -> str:
58
+ return base64.urlsafe_b64encode(data).decode("ascii").rstrip("=")
59
+
60
+
61
+ def _b64url_decode(value: str) -> bytes:
62
+ padding = "=" * (-len(value) % 4)
63
+ return base64.urlsafe_b64decode(value + padding)
64
+
65
+
66
+ def _json_dumps(payload: Mapping[str, Any]) -> str:
67
+ return json.dumps(payload, separators=(",", ":"), sort_keys=True)
68
+
69
+
70
+ def _normalize_secret(secret: str | bytes | bytearray) -> bytes:
71
+ if isinstance(secret, (bytes, bytearray)):
72
+ return bytes(secret)
73
+ return str(secret).encode("utf-8")
74
+
75
+
76
+ def _validate_algorithm(
77
+ algorithm: str, *, policy: RequestObjectPolicy = ACTIVE_REQUEST_OBJECT_POLICY
78
+ ) -> str:
79
+ alg = str(algorithm or "").upper()
80
+ if not alg:
81
+ raise RequestObjectValidationError(
82
+ f"missing JAR signing algorithm: {RFC9101_SPEC_URL}"
83
+ )
84
+ if alg == "NONE":
85
+ raise RequestObjectValidationError(
86
+ f"unsigned request objects are not accepted: {RFC9101_SPEC_URL}"
87
+ )
88
+ if alg not in policy.allowed_algs:
89
+ raise RequestObjectValidationError(
90
+ f"unsupported request-object signing algorithm {alg!r}; supported values: {', '.join(policy.allowed_algs)}"
91
+ )
92
+ return alg
93
+
94
+
95
+ def _hash_name_for_alg(algorithm: str) -> str:
96
+ alg = _validate_algorithm(algorithm)
97
+ if alg == "HS256":
98
+ return "sha256"
99
+ if alg == "HS384":
100
+ return "sha384"
101
+ return "sha512"
102
+
103
+
104
+ def _sign_compact_jws(
105
+ payload: Mapping[str, Any], *, secret: str | bytes | bytearray, algorithm: str
106
+ ) -> str:
107
+ alg = _validate_algorithm(algorithm)
108
+ header = {"alg": alg, "typ": "JWT"}
109
+ signing_input = ".".join(
110
+ (
111
+ _b64url_encode(_json_dumps(header).encode("utf-8")),
112
+ _b64url_encode(_json_dumps(dict(payload)).encode("utf-8")),
113
+ )
114
+ )
115
+ signature = hmac.new(
116
+ _normalize_secret(secret),
117
+ signing_input.encode("ascii"),
118
+ getattr(hashlib, _hash_name_for_alg(alg)),
119
+ ).digest()
120
+ return f"{signing_input}.{_b64url_encode(signature)}"
121
+
122
+
123
+ def _verify_compact_jws(
124
+ token: str,
125
+ *,
126
+ secret: str | bytes | bytearray,
127
+ algorithms: Iterable[str] | None = None,
128
+ policy: RequestObjectPolicy = ACTIVE_REQUEST_OBJECT_POLICY,
129
+ ) -> tuple[dict[str, Any], dict[str, Any]]:
130
+ try:
131
+ header_segment, payload_segment, signature_segment = token.split(".")
132
+ except ValueError as exc:
133
+ raise RequestObjectValidationError(
134
+ f"invalid compact request object: {RFC9101_SPEC_URL}"
135
+ ) from exc
136
+ try:
137
+ header = json.loads(_b64url_decode(header_segment).decode("utf-8"))
138
+ except Exception as exc:
139
+ raise RequestObjectValidationError(
140
+ f"invalid request-object header encoding: {RFC9101_SPEC_URL}"
141
+ ) from exc
142
+ if not isinstance(header, dict):
143
+ raise RequestObjectValidationError(
144
+ f"invalid request-object header: {RFC9101_SPEC_URL}"
145
+ )
146
+ alg = _validate_algorithm(str(header.get("alg") or ""), policy=policy)
147
+ allowlist = tuple(
148
+ _validate_algorithm(item, policy=policy)
149
+ for item in (algorithms or policy.allowed_algs)
150
+ )
151
+ if alg not in allowlist:
152
+ raise RequestObjectValidationError(
153
+ f"request-object signature algorithm {alg!r} is not permitted: {RFC9101_SPEC_URL}"
154
+ )
155
+ expected_sig = hmac.new(
156
+ _normalize_secret(secret),
157
+ f"{header_segment}.{payload_segment}".encode("ascii"),
158
+ getattr(hashlib, _hash_name_for_alg(alg)),
159
+ ).digest()
160
+ try:
161
+ actual_sig = _b64url_decode(signature_segment)
162
+ except Exception as exc:
163
+ raise RequestObjectValidationError(
164
+ f"invalid request-object signature encoding: {RFC9101_SPEC_URL}"
165
+ ) from exc
166
+ if not hmac.compare_digest(expected_sig, actual_sig):
167
+ raise RequestObjectValidationError(
168
+ f"request-object signature verification failed: {RFC9101_SPEC_URL}"
169
+ )
170
+ try:
171
+ payload = json.loads(_b64url_decode(payload_segment).decode("utf-8"))
172
+ except Exception as exc:
173
+ raise RequestObjectValidationError(
174
+ f"invalid request-object payload encoding: {RFC9101_SPEC_URL}"
175
+ ) from exc
176
+ if not isinstance(payload, dict):
177
+ raise RequestObjectValidationError(
178
+ f"request-object payload must be a JSON object: {RFC9101_SPEC_URL}"
179
+ )
180
+ return header, payload
181
+
182
+
183
+ def _utc_now(now: datetime | None = None) -> datetime:
184
+ value = now or datetime.now(timezone.utc)
185
+ return value if value.tzinfo is not None else value.replace(tzinfo=timezone.utc)
186
+
187
+
188
+ def _as_timestamp(value: Any) -> int | None:
189
+ if value in {None, ""}:
190
+ return None
191
+ if isinstance(value, bool):
192
+ raise RequestObjectValidationError(
193
+ f"invalid temporal claim type in request object: {RFC9101_SPEC_URL}"
194
+ )
195
+ try:
196
+ return int(value)
197
+ except Exception as exc:
198
+ raise RequestObjectValidationError(
199
+ f"invalid temporal claim in request object: {RFC9101_SPEC_URL}"
200
+ ) from exc
201
+
202
+
203
+ def _audience_matches(expected_audience: str, aud_claim: Any) -> bool:
204
+ if isinstance(aud_claim, str):
205
+ return aud_claim == expected_audience
206
+ if isinstance(aud_claim, Sequence) and not isinstance(
207
+ aud_claim, (bytes, bytearray, str)
208
+ ):
209
+ return expected_audience in {str(item) for item in aud_claim}
210
+ return False
211
+
212
+
213
+ def validate_request_object_claims(
214
+ payload: Mapping[str, Any],
215
+ *,
216
+ expected_client_id: str | None = None,
217
+ expected_audience: str | None = None,
218
+ now: datetime | None = None,
219
+ require_expiration: bool = False,
220
+ policy: RequestObjectPolicy = ACTIVE_REQUEST_OBJECT_POLICY,
221
+ ) -> dict[str, Any]:
222
+ normalized = dict(payload)
223
+ current = _utc_now(now)
224
+ skew = timedelta(seconds=policy.max_clock_skew_seconds)
225
+
226
+ exp = _as_timestamp(normalized.get("exp"))
227
+ nbf = _as_timestamp(normalized.get("nbf"))
228
+ iat = _as_timestamp(normalized.get("iat"))
229
+
230
+ if require_expiration and exp is None:
231
+ raise RequestObjectValidationError(
232
+ f"request objects must include exp in the active profile: {RFC9101_SPEC_URL}"
233
+ )
234
+ if (
235
+ exp is not None
236
+ and datetime.fromtimestamp(exp, tz=timezone.utc) <= current - skew
237
+ ):
238
+ raise RequestObjectValidationError(
239
+ f"stale request object rejected by temporal policy: {RFC9101_SPEC_URL}"
240
+ )
241
+ if (
242
+ nbf is not None
243
+ and datetime.fromtimestamp(nbf, tz=timezone.utc) > current + skew
244
+ ):
245
+ raise RequestObjectValidationError(
246
+ f"request object is not yet valid: {RFC9101_SPEC_URL}"
247
+ )
248
+ if (
249
+ iat is not None
250
+ and datetime.fromtimestamp(iat, tz=timezone.utc) > current + skew
251
+ ):
252
+ raise RequestObjectValidationError(
253
+ f"request object iat is in the future: {RFC9101_SPEC_URL}"
254
+ )
255
+ if exp is not None and iat is not None and exp <= iat:
256
+ raise RequestObjectValidationError(
257
+ f"request object exp must be greater than iat: {RFC9101_SPEC_URL}"
258
+ )
259
+ if exp is not None and nbf is not None and exp <= nbf:
260
+ raise RequestObjectValidationError(
261
+ f"request object exp must be greater than nbf: {RFC9101_SPEC_URL}"
262
+ )
263
+
264
+ if expected_client_id:
265
+ claim_client_id = str(normalized.get("client_id") or "").strip() or None
266
+ issuer = str(normalized.get("iss") or "").strip() or None
267
+ subject = str(normalized.get("sub") or "").strip() or None
268
+ if claim_client_id is not None and claim_client_id != expected_client_id:
269
+ raise RequestObjectValidationError(
270
+ f"request object client_id mismatch: {RFC9101_SPEC_URL}"
271
+ )
272
+ if issuer is not None and issuer != expected_client_id:
273
+ raise RequestObjectValidationError(
274
+ f"request object iss/client mismatch: {RFC9101_SPEC_URL}"
275
+ )
276
+ if subject is not None and subject != expected_client_id:
277
+ raise RequestObjectValidationError(
278
+ f"request object sub/client mismatch: {RFC9101_SPEC_URL}"
279
+ )
280
+ if expected_audience:
281
+ aud = normalized.get("aud")
282
+ if aud not in {None, ""} and not _audience_matches(expected_audience, aud):
283
+ raise RequestObjectValidationError(
284
+ f"request object audience mismatch: {RFC9101_SPEC_URL}"
285
+ )
286
+ return normalized
287
+
288
+
289
+ def merge_request_object_params(
290
+ request_object_claims: Mapping[str, Any],
291
+ request_params: Mapping[str, Any],
292
+ *,
293
+ allow_query_overrides: Iterable[str] = (),
294
+ ) -> dict[str, Any]:
295
+ merged = dict(request_object_claims)
296
+ override_keys = {str(item) for item in allow_query_overrides}
297
+ for key, value in request_params.items():
298
+ if key == "request":
299
+ continue
300
+ if value in (None, "", [], (), {}):
301
+ continue
302
+ existing = merged.get(key)
303
+ if key in override_keys:
304
+ merged[key] = value
305
+ continue
306
+ if existing not in (None, "", [], (), {}) and existing != value:
307
+ raise RequestObjectValidationError(
308
+ f"conflicting query/form parameter {key!r} does not match request-object claim: {RFC9101_SPEC_URL}"
309
+ )
310
+ merged[key] = value
311
+ return merged
312
+
313
+
314
+ async def make_request_object(
315
+ params: dict[str, Any],
316
+ *,
317
+ secret: str,
318
+ algorithm: str = "HS256",
319
+ issuer: str | None = None,
320
+ audience: str | None = None,
321
+ lifetime_seconds: int = DEFAULT_REQUEST_OBJECT_LIFETIME_SECONDS,
322
+ ) -> str:
323
+ if not settings.enable_rfc9101:
324
+ raise RuntimeError(f"RFC 9101 support disabled: {RFC9101_SPEC_URL}")
325
+ payload = dict(params)
326
+ now = _utc_now()
327
+ payload.setdefault("iat", int(now.timestamp()))
328
+ payload.setdefault(
329
+ "exp", int((now + timedelta(seconds=max(1, int(lifetime_seconds)))).timestamp())
330
+ )
331
+ if issuer is not None:
332
+ payload.setdefault("iss", issuer)
333
+ payload.setdefault("sub", issuer)
334
+ if audience is not None:
335
+ payload.setdefault("aud", audience)
336
+ return _sign_compact_jws(payload, secret=secret, algorithm=algorithm)
337
+
338
+
339
+ async def makeRequestObject(
340
+ params: dict[str, Any],
341
+ *,
342
+ secret: str,
343
+ algorithm: str = "HS256",
344
+ ) -> str:
345
+ return await make_request_object(params, secret=secret, algorithm=algorithm)
346
+
347
+
348
+ async def create_request_object(
349
+ params: dict[str, Any],
350
+ *,
351
+ secret: str,
352
+ algorithm: str = "HS256",
353
+ ) -> str:
354
+ return await makeRequestObject(params, secret=secret, algorithm=algorithm)
355
+
356
+
357
+ async def parse_request_object(
358
+ token: str,
359
+ *,
360
+ secret: str,
361
+ algorithms: Iterable[str] | None = None,
362
+ expected_client_id: str | None = None,
363
+ expected_audience: str | None = None,
364
+ now: datetime | None = None,
365
+ require_expiration: bool = False,
366
+ ) -> dict[str, Any]:
367
+ if not settings.enable_rfc9101:
368
+ raise RuntimeError(f"RFC 9101 support disabled: {RFC9101_SPEC_URL}")
369
+ _header, payload = _verify_compact_jws(token, secret=secret, algorithms=algorithms)
370
+ return validate_request_object_claims(
371
+ payload,
372
+ expected_client_id=expected_client_id,
373
+ expected_audience=expected_audience,
374
+ now=now,
375
+ require_expiration=require_expiration,
376
+ )
377
+
378
+
379
+ def request_object_summary(payload: Mapping[str, Any]) -> dict[str, Any]:
380
+ claims = dict(payload)
381
+ return {
382
+ "claim_keys": sorted(claims.keys()),
383
+ "client_id": claims.get("client_id"),
384
+ "iss": claims.get("iss"),
385
+ "sub": claims.get("sub"),
386
+ "aud": claims.get("aud"),
387
+ "has_exp": "exp" in claims,
388
+ "has_nbf": "nbf" in claims,
389
+ "has_iat": "iat" in claims,
390
+ }
391
+
392
+
393
+ def describe() -> dict[str, object]:
394
+ return describe_owner(
395
+ OWNER,
396
+ allowed_algs=list(ACTIVE_REQUEST_OBJECT_POLICY.allowed_algs),
397
+ require_signature=ACTIVE_REQUEST_OBJECT_POLICY.require_signature,
398
+ clock_skew_seconds=ACTIVE_REQUEST_OBJECT_POLICY.max_clock_skew_seconds,
399
+ spec_url=RFC9101_SPEC_URL,
400
+ )
401
+
402
+
403
+ __all__ = [
404
+ "STATUS",
405
+ "RFC9101_SPEC_URL",
406
+ "SUPPORTED_JAR_ALG_VALUES",
407
+ "DEFAULT_REQUEST_OBJECT_LIFETIME_SECONDS",
408
+ "StandardOwner",
409
+ "RequestObjectPolicy",
410
+ "RequestObjectValidationError",
411
+ "OWNER",
412
+ "ACTIVE_REQUEST_OBJECT_POLICY",
413
+ "make_request_object",
414
+ "makeRequestObject",
415
+ "create_request_object",
416
+ "parse_request_object",
417
+ "validate_request_object_claims",
418
+ "merge_request_object_params",
419
+ "request_object_summary",
420
+ "describe",
421
+ ]