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,113 @@
1
+ """Legacy migration-history compatibility module for JWT client assertions.
2
+
3
+ Certification claims map JWT client authentication to RFC 7523. This module
4
+ preserves the legacy helper API without relying on the flat ``tba_auth.rfc``
5
+ tree.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import time
11
+ import warnings
12
+ from typing import Any, Iterable
13
+
14
+ from tba_contracts_identity.protocol_configuration import (
15
+ protocol_settings as settings,
16
+ )
17
+ from tba_primitives_identity.errors import InvalidTokenError
18
+ from tba_protocol_oauth.standards.json_web_token import encode_jwt
19
+ from tba_protocol_oauth.standards.jwt_client_auth import (
20
+ validate_client_jwt_bearer,
21
+ )
22
+
23
+ RFC8523_SPEC_URL = "https://www.rfc-editor.org/rfc/rfc8523"
24
+ REQUIRED_CLAIMS: set[str] = {"iss", "sub", "aud", "exp", "iat", "jti"}
25
+
26
+
27
+ def validate_enhanced_jwt_bearer(
28
+ assertion: str,
29
+ *,
30
+ audience: str | Iterable[str] | None = None,
31
+ max_age_seconds: int = 300,
32
+ clock_skew_seconds: int = 30,
33
+ ) -> dict[str, Any]:
34
+ if not settings.enable_rfc8523:
35
+ raise RuntimeError("Legacy RFC 8523 path disabled")
36
+ claims = validate_client_jwt_bearer(assertion, audience=audience)
37
+ missing = REQUIRED_CLAIMS - claims.keys()
38
+ if missing:
39
+ raise ValueError(
40
+ f"Legacy RFC 8523 path missing claims: {', '.join(sorted(missing))}"
41
+ )
42
+ current_time = int(time.time())
43
+ iat = claims.get("iat")
44
+ if not isinstance(iat, int):
45
+ raise InvalidTokenError("'iat' claim must be an integer timestamp")
46
+ token_age = current_time - iat
47
+ if token_age > max_age_seconds + clock_skew_seconds:
48
+ raise ValueError(f"JWT is too old: {token_age} seconds > {max_age_seconds}")
49
+ if iat > current_time + clock_skew_seconds:
50
+ raise InvalidTokenError("JWT 'iat' claim is in the future")
51
+ jti = claims.get("jti")
52
+ if not isinstance(jti, str) or not jti.strip():
53
+ raise ValueError("'jti' claim must be a non-empty string")
54
+ return claims
55
+
56
+
57
+ def makeClientAssertionJwt(
58
+ client_id: str,
59
+ audience: str,
60
+ *,
61
+ expires_in: int = 300,
62
+ additional_claims: dict[str, Any] | None = None,
63
+ ) -> str:
64
+ if not settings.enable_rfc8523:
65
+ raise RuntimeError("Legacy RFC 8523 path disabled")
66
+ import uuid
67
+
68
+ current_time = int(time.time())
69
+ claims = {
70
+ "iss": client_id,
71
+ "sub": client_id,
72
+ "aud": audience,
73
+ "exp": current_time + expires_in,
74
+ "iat": current_time,
75
+ "jti": str(uuid.uuid4()),
76
+ }
77
+ if additional_claims:
78
+ claims.update(additional_claims)
79
+ return encode_jwt(**claims)
80
+
81
+
82
+ def create_client_assertion_jwt(
83
+ client_id: str,
84
+ audience: str,
85
+ *,
86
+ expires_in: int = 300,
87
+ additional_claims: dict[str, Any] | None = None,
88
+ ) -> str:
89
+ warnings.warn(
90
+ "create_client_assertion_jwt is deprecated, use makeClientAssertionJwt",
91
+ DeprecationWarning,
92
+ stacklevel=2,
93
+ )
94
+ return makeClientAssertionJwt(
95
+ client_id,
96
+ audience,
97
+ expires_in=expires_in,
98
+ additional_claims=additional_claims,
99
+ )
100
+
101
+
102
+ def is_jwt_replay(jti: str, iat: int, max_age_seconds: int = 300) -> bool:
103
+ return False
104
+
105
+
106
+ __all__ = [
107
+ "validate_enhanced_jwt_bearer",
108
+ "makeClientAssertionJwt",
109
+ "create_client_assertion_jwt",
110
+ "is_jwt_replay",
111
+ "RFC8523_SPEC_URL",
112
+ "REQUIRED_CLAIMS",
113
+ ]
@@ -0,0 +1,394 @@
1
+ """Mutual-TLS client authentication and certificate-bound token helpers.
2
+
3
+ This module is intentionally dependency-light so Tier 3 evidence checkpoint evidence can execute
4
+ without the full runtime stack. It covers three distinct concerns:
5
+
6
+ - certificate thumbprint extraction and confirmation-claim construction
7
+ - certificate-bound access-token verification on resource paths
8
+ - token-endpoint client authentication for tls_client_auth and
9
+ self_signed_tls_client_auth registrations
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import base64
15
+ import hashlib
16
+ from typing import Any, Final, Mapping
17
+ from tba_primitives_identity.standards import StandardOwner, describe_owner
18
+ from tba_contracts_security_trust import MTLSClientAuthentication
19
+
20
+ from cryptography import x509
21
+ from cryptography.hazmat.primitives import serialization
22
+
23
+ from tba_contracts_identity.protocol_configuration import (
24
+ protocol_settings as settings,
25
+ )
26
+ from tba_primitives_identity.errors import InvalidTokenError
27
+ from tba_protocol_oauth.standards._mtls_identity import (
28
+ certificate_matches_registered_identity,
29
+ certificate_san_values,
30
+ certificate_subject_dn,
31
+ normalize_presented_pem,
32
+ registered_certificate_identity_metadata,
33
+ )
34
+
35
+ RFC8705_SPEC_URL: Final[str] = "https://www.rfc-editor.org/rfc/rfc8705"
36
+ TLS_CLIENT_AUTH_METHOD: Final[str] = "tls_client_auth"
37
+ SELF_SIGNED_TLS_CLIENT_AUTH_METHOD: Final[str] = "self_signed_tls_client_auth"
38
+ SUPPORTED_MTLS_AUTH_METHODS: Final[tuple[str, str]] = (
39
+ TLS_CLIENT_AUTH_METHOD,
40
+ SELF_SIGNED_TLS_CLIENT_AUTH_METHOD,
41
+ )
42
+
43
+ _CERTIFICATE_THUMBPRINT_HEADER_NAMES: Final[tuple[str, ...]] = (
44
+ "X-Client-Cert-SHA256",
45
+ "X-SSL-Client-SHA256",
46
+ "X_SSL_CLIENT_CERT_SHA256",
47
+ "MTLS-Client-Cert-SHA256",
48
+ )
49
+ _CERTIFICATE_PEM_HEADER_NAMES: Final[tuple[str, ...]] = (
50
+ "X-Client-Cert",
51
+ "X-SSL-Client-Cert",
52
+ "MTLS-Client-Cert",
53
+ )
54
+ _SCOPE_CERTIFICATE_KEYS: Final[tuple[str, ...]] = (
55
+ "client_cert_sha256",
56
+ "tls_client_cert_sha256",
57
+ "mtls_client_cert_sha256",
58
+ )
59
+ _SCOPE_CERTIFICATE_PEM_KEYS: Final[tuple[str, ...]] = (
60
+ "client_cert_pem",
61
+ "tls_client_cert_pem",
62
+ "mtls_client_cert_pem",
63
+ )
64
+ _TRUSTED_CERTIFICATE_SCOPE_KEYS: Final[tuple[str, ...]] = (
65
+ "client_cert_trusted",
66
+ "tls_client_cert_trusted",
67
+ "mtls_client_cert_trusted",
68
+ "mtls_trusted_proxy",
69
+ )
70
+ _TLS_CERT_THUMBPRINT_KEYS: Final[tuple[str, ...]] = (
71
+ "tls_client_certificate_thumbprint",
72
+ "tls_client_certificate_thumbprints",
73
+ )
74
+ _SELF_SIGNED_CERT_THUMBPRINT_KEYS: Final[tuple[str, ...]] = (
75
+ "self_signed_tls_client_certificate_thumbprint",
76
+ "self_signed_tls_client_certificate_thumbprints",
77
+ )
78
+ _TLS_CLIENT_AUTH_IDENTITY_KEYS: Final[tuple[str, ...]] = (
79
+ "tls_client_auth_subject_dn",
80
+ "tls_client_auth_san_dns",
81
+ "tls_client_auth_san_uri",
82
+ "tls_client_auth_san_ip",
83
+ "tls_client_auth_san_email",
84
+ )
85
+
86
+
87
+ OWNER = StandardOwner(
88
+ label="RFC 8705",
89
+ title="OAuth 2.0 Mutual-TLS Client Authentication and Certificate-Bound Access Tokens",
90
+ runtime_status="mtls-runtime-integrated",
91
+ public_surface=("/token", "/token/exchange", "/userinfo", "/introspect", "/revoke"),
92
+ notes=(
93
+ "mTLS client authentication, certificate-bound access-token validation, and "
94
+ "runtime registration metadata checks are integrated with dependency-light helpers."
95
+ ),
96
+ )
97
+
98
+
99
+ def thumbprint_from_cert_pem(cert_pem: bytes) -> str:
100
+ cert = x509.load_pem_x509_certificate(cert_pem)
101
+ der = cert.public_bytes(serialization.Encoding.DER)
102
+ digest = hashlib.sha256(der).digest()
103
+ return base64.urlsafe_b64encode(digest).rstrip(b"=").decode("ascii")
104
+
105
+
106
+ def _normalize_presented_thumbprint(value: str | bytes | None) -> str | None:
107
+ if value in {None, b"", ""}:
108
+ return None
109
+ if isinstance(value, bytes):
110
+ if value.startswith(b"-----BEGIN CERTIFICATE-----"):
111
+ return thumbprint_from_cert_pem(value)
112
+ return value.decode("utf-8").strip() or None
113
+ text = str(value).strip()
114
+ if not text:
115
+ return None
116
+ if text.startswith("-----BEGIN CERTIFICATE-----"):
117
+ return thumbprint_from_cert_pem(text.encode("utf-8"))
118
+ return text
119
+
120
+
121
+ def certificate_confirmation_claim(thumbprint: str) -> dict[str, str]:
122
+ return {"x5t#S256": str(thumbprint)}
123
+
124
+
125
+ def token_is_certificate_bound(payload: Mapping[str, Any]) -> bool:
126
+ cnf = payload.get("cnf")
127
+ return isinstance(cnf, Mapping) and bool(cnf.get("x5t#S256"))
128
+
129
+
130
+ is_certificate_bound_token = token_is_certificate_bound
131
+
132
+
133
+ def _headers_from_request(request_or_mapping: Any) -> Any:
134
+ headers = getattr(request_or_mapping, "headers", None)
135
+ if headers is None and isinstance(request_or_mapping, Mapping):
136
+ headers = request_or_mapping
137
+ return headers or {}
138
+
139
+
140
+ def _scope_from_request(request_or_mapping: Any) -> Mapping[str, Any]:
141
+ scope = getattr(request_or_mapping, "scope", None)
142
+ if scope is None and isinstance(request_or_mapping, Mapping):
143
+ scope = request_or_mapping
144
+ return scope if isinstance(scope, Mapping) else {}
145
+
146
+
147
+ def _scope_trusts_certificate_headers(request_or_mapping: Any) -> bool:
148
+ scope = _scope_from_request(request_or_mapping)
149
+ if any(bool(scope.get(key)) for key in _TRUSTED_CERTIFICATE_SCOPE_KEYS):
150
+ return True
151
+ state = getattr(request_or_mapping, "state", None)
152
+ return any(
153
+ bool(getattr(state, key, False)) for key in _TRUSTED_CERTIFICATE_SCOPE_KEYS
154
+ )
155
+
156
+
157
+ def _header_certificate_thumbprint(request_or_mapping: Any) -> str | None:
158
+ headers = _headers_from_request(request_or_mapping)
159
+ if hasattr(headers, "get"):
160
+ for name in _CERTIFICATE_THUMBPRINT_HEADER_NAMES:
161
+ thumb = _normalize_presented_thumbprint(headers.get(name))
162
+ if thumb:
163
+ return thumb
164
+ for name in _CERTIFICATE_PEM_HEADER_NAMES:
165
+ thumb = _normalize_presented_thumbprint(headers.get(name))
166
+ if thumb:
167
+ return thumb
168
+ return None
169
+
170
+
171
+ def _scope_certificate_thumbprint(request_or_mapping: Any) -> str | None:
172
+ scope = _scope_from_request(request_or_mapping)
173
+ for key in _SCOPE_CERTIFICATE_KEYS:
174
+ thumb = _normalize_presented_thumbprint(scope.get(key))
175
+ if thumb:
176
+ return thumb
177
+ for key in _SCOPE_CERTIFICATE_PEM_KEYS:
178
+ thumb = _normalize_presented_thumbprint(scope.get(key))
179
+ if thumb:
180
+ return thumb
181
+ return None
182
+
183
+
184
+ def presented_certificate_pem(
185
+ request_or_mapping: Any, *, trusted_proxy: bool = False
186
+ ) -> bytes | None:
187
+ scope = _scope_from_request(request_or_mapping)
188
+ for key in _SCOPE_CERTIFICATE_PEM_KEYS:
189
+ pem = normalize_presented_pem(scope.get(key))
190
+ if pem:
191
+ return pem
192
+ if trusted_proxy or _scope_trusts_certificate_headers(request_or_mapping):
193
+ headers = _headers_from_request(request_or_mapping)
194
+ if hasattr(headers, "get"):
195
+ for name in _CERTIFICATE_PEM_HEADER_NAMES:
196
+ pem = normalize_presented_pem(headers.get(name))
197
+ if pem:
198
+ return pem
199
+ return None
200
+
201
+
202
+ def presented_trusted_certificate_thumbprint(
203
+ request_or_mapping: Any, *, trusted_proxy: bool = False
204
+ ) -> str | None:
205
+ scope_thumbprint = _scope_certificate_thumbprint(request_or_mapping)
206
+ if scope_thumbprint:
207
+ return scope_thumbprint
208
+ if trusted_proxy or _scope_trusts_certificate_headers(request_or_mapping):
209
+ return _header_certificate_thumbprint(request_or_mapping)
210
+ return None
211
+
212
+
213
+ def presented_certificate_thumbprint(request_or_mapping: Any) -> str | None:
214
+ return _header_certificate_thumbprint(
215
+ request_or_mapping
216
+ ) or _scope_certificate_thumbprint(request_or_mapping)
217
+
218
+
219
+ def _coerce_thumbprints(value: Any) -> tuple[str, ...]:
220
+ if value is None:
221
+ return ()
222
+ if isinstance(value, str) and not value.strip():
223
+ return ()
224
+ if isinstance(value, bytes) and not value.strip():
225
+ return ()
226
+ if isinstance(value, (list, tuple, set)) and not value:
227
+ return ()
228
+ if isinstance(value, (list, tuple, set)):
229
+ result: list[str] = []
230
+ for item in value:
231
+ normalized = _normalize_presented_thumbprint(item)
232
+ if normalized:
233
+ result.append(normalized)
234
+ return tuple(dict.fromkeys(result))
235
+ normalized = _normalize_presented_thumbprint(value)
236
+ return (normalized,) if normalized else ()
237
+
238
+
239
+ def registered_certificate_thumbprints(
240
+ registration_metadata: Mapping[str, Any] | None,
241
+ *,
242
+ token_endpoint_auth_method: str | None = None,
243
+ ) -> tuple[str, ...]:
244
+ metadata = dict(registration_metadata or {})
245
+ auth_method = str(
246
+ token_endpoint_auth_method or metadata.get("token_endpoint_auth_method") or ""
247
+ ).strip()
248
+ thumbprints: list[str] = []
249
+ if auth_method in {"", TLS_CLIENT_AUTH_METHOD}:
250
+ for key in _TLS_CERT_THUMBPRINT_KEYS:
251
+ thumbprints.extend(_coerce_thumbprints(metadata.get(key)))
252
+ if auth_method in {"", SELF_SIGNED_TLS_CLIENT_AUTH_METHOD}:
253
+ for key in _SELF_SIGNED_CERT_THUMBPRINT_KEYS:
254
+ thumbprints.extend(_coerce_thumbprints(metadata.get(key)))
255
+ return tuple(dict.fromkeys(thumbprints))
256
+
257
+
258
+ def authenticate_mtls_client(
259
+ registration_metadata: Mapping[str, Any] | None,
260
+ presented_thumbprint: str | bytes | None,
261
+ *,
262
+ presented_certificate_pem: str | bytes | None = None,
263
+ token_endpoint_auth_method: str | None = None,
264
+ enabled: bool | None = None,
265
+ ) -> MTLSClientAuthentication:
266
+ if enabled is None:
267
+ enabled = settings.enable_rfc8705
268
+ if not enabled:
269
+ raise ValueError(f"RFC 8705 support disabled: {RFC8705_SPEC_URL}")
270
+ auth_method = str(
271
+ token_endpoint_auth_method
272
+ or dict(registration_metadata or {}).get("token_endpoint_auth_method")
273
+ or TLS_CLIENT_AUTH_METHOD
274
+ ).strip()
275
+ if auth_method not in SUPPORTED_MTLS_AUTH_METHODS:
276
+ raise ValueError(
277
+ "unsupported token_endpoint_auth_method for mTLS client authentication"
278
+ )
279
+ pem = normalize_presented_pem(presented_certificate_pem)
280
+ effective_thumbprint = _normalize_presented_thumbprint(presented_thumbprint)
281
+ if not effective_thumbprint and pem:
282
+ effective_thumbprint = thumbprint_from_cert_pem(pem)
283
+ if not effective_thumbprint:
284
+ raise ValueError(
285
+ "client certificate thumbprint required for mTLS client authentication"
286
+ )
287
+ allowed = registered_certificate_thumbprints(
288
+ registration_metadata,
289
+ token_endpoint_auth_method=auth_method,
290
+ )
291
+ if allowed:
292
+ if effective_thumbprint not in set(allowed):
293
+ raise ValueError(
294
+ "presented client certificate thumbprint is not registered for this client"
295
+ )
296
+ return MTLSClientAuthentication(
297
+ auth_method=auth_method, cert_thumbprint=effective_thumbprint
298
+ )
299
+ if (
300
+ auth_method == TLS_CLIENT_AUTH_METHOD
301
+ and pem
302
+ and certificate_matches_registered_identity(pem, registration_metadata)
303
+ ):
304
+ return MTLSClientAuthentication(
305
+ auth_method=auth_method, cert_thumbprint=effective_thumbprint
306
+ )
307
+ if auth_method == TLS_CLIENT_AUTH_METHOD and any(
308
+ registered_certificate_identity_metadata(registration_metadata).values()
309
+ ):
310
+ raise ValueError(
311
+ "presented client certificate identity is not registered for this client"
312
+ )
313
+ raise ValueError(
314
+ "registration metadata does not pin an allowed client certificate thumbprint"
315
+ )
316
+ return MTLSClientAuthentication(
317
+ auth_method=auth_method, cert_thumbprint=effective_thumbprint
318
+ )
319
+
320
+
321
+ def validate_certificate_binding(
322
+ payload: Mapping[str, Any],
323
+ presented_thumbprint: str | bytes | None,
324
+ *,
325
+ enabled: bool | None = None,
326
+ ) -> None:
327
+ if enabled is None:
328
+ enabled = settings.enable_rfc8705
329
+ if not enabled:
330
+ return
331
+ cnf = payload.get("cnf")
332
+ if not isinstance(cnf, Mapping):
333
+ raise InvalidTokenError(f"cnf claim required by RFC 8705: {RFC8705_SPEC_URL}")
334
+ bound = _normalize_presented_thumbprint(cnf.get("x5t#S256"))
335
+ effective_thumbprint = _normalize_presented_thumbprint(presented_thumbprint)
336
+ if not bound:
337
+ raise InvalidTokenError(
338
+ f"x5t#S256 confirmation claim required by RFC 8705: {RFC8705_SPEC_URL}"
339
+ )
340
+ if bound != effective_thumbprint:
341
+ raise InvalidTokenError(
342
+ f"certificate thumbprint mismatch per RFC 8705: {RFC8705_SPEC_URL}"
343
+ )
344
+
345
+
346
+ def validate_request_certificate_binding(
347
+ payload: Mapping[str, Any],
348
+ request_or_mapping: Any,
349
+ *,
350
+ enabled: bool | None = None,
351
+ ) -> str | None:
352
+ thumbprint = presented_certificate_thumbprint(request_or_mapping)
353
+ if token_is_certificate_bound(payload):
354
+ validate_certificate_binding(payload, thumbprint, enabled=enabled)
355
+ return thumbprint
356
+
357
+
358
+ def describe() -> dict[str, object]:
359
+ return describe_owner(
360
+ OWNER,
361
+ spec_url=RFC8705_SPEC_URL,
362
+ confirmation_claim="x5t#S256",
363
+ supported_token_endpoint_auth_methods=list(SUPPORTED_MTLS_AUTH_METHODS),
364
+ certificate_thumbprint_header_names=list(_CERTIFICATE_THUMBPRINT_HEADER_NAMES),
365
+ certificate_pem_header_names=list(_CERTIFICATE_PEM_HEADER_NAMES),
366
+ tls_client_auth_identity_metadata=list(_TLS_CLIENT_AUTH_IDENTITY_KEYS),
367
+ )
368
+
369
+
370
+ __all__ = [
371
+ "RFC8705_SPEC_URL",
372
+ "TLS_CLIENT_AUTH_METHOD",
373
+ "SELF_SIGNED_TLS_CLIENT_AUTH_METHOD",
374
+ "SUPPORTED_MTLS_AUTH_METHODS",
375
+ "MTLSClientAuthentication",
376
+ "StandardOwner",
377
+ "OWNER",
378
+ "authenticate_mtls_client",
379
+ "certificate_matches_registered_identity",
380
+ "certificate_confirmation_claim",
381
+ "certificate_san_values",
382
+ "certificate_subject_dn",
383
+ "describe",
384
+ "is_certificate_bound_token",
385
+ "presented_certificate_pem",
386
+ "presented_certificate_thumbprint",
387
+ "presented_trusted_certificate_thumbprint",
388
+ "registered_certificate_identity_metadata",
389
+ "registered_certificate_thumbprints",
390
+ "thumbprint_from_cert_pem",
391
+ "token_is_certificate_bound",
392
+ "validate_certificate_binding",
393
+ "validate_request_certificate_binding",
394
+ ]
@@ -0,0 +1,132 @@
1
+ """RFC 8252 native-application redirect and PKCE policy helpers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Final, Iterable
6
+ from tba_contracts_identity.oauth import NativeRedirectAssessment
7
+ from urllib.parse import urlparse
8
+
9
+ RFC8252_SPEC_URL: Final[str] = "https://www.rfc-editor.org/rfc/rfc8252"
10
+ _LOOPBACK_HOSTS: Final[set[str]] = {"127.0.0.1", "localhost", "::1"}
11
+
12
+
13
+ def classify_native_redirect_uri(uri: str) -> NativeRedirectAssessment | None:
14
+ parsed = urlparse(uri)
15
+ if parsed.scheme in {"http", "https"}:
16
+ host = parsed.hostname or ""
17
+ if host in _LOOPBACK_HOSTS:
18
+ return NativeRedirectAssessment(
19
+ redirect_uri=uri,
20
+ kind="loopback",
21
+ scheme=parsed.scheme,
22
+ host=host,
23
+ port=parsed.port,
24
+ )
25
+ return None
26
+ if parsed.scheme:
27
+ return NativeRedirectAssessment(
28
+ redirect_uri=uri,
29
+ kind="private-use-scheme",
30
+ scheme=parsed.scheme,
31
+ host=parsed.hostname,
32
+ port=parsed.port,
33
+ )
34
+ return None
35
+
36
+
37
+ def is_native_redirect_uri(uri: str) -> bool:
38
+ return classify_native_redirect_uri(uri) is not None
39
+
40
+
41
+ def validate_native_redirect_uri(uri: str) -> NativeRedirectAssessment:
42
+ assessment = classify_native_redirect_uri(uri)
43
+ if assessment is None:
44
+ raise ValueError(
45
+ f"redirect URI not permitted for native apps per RFC 8252: {RFC8252_SPEC_URL}"
46
+ )
47
+ parsed = urlparse(uri)
48
+ if parsed.fragment:
49
+ raise ValueError("native redirect URIs must not include a URI fragment")
50
+ if assessment.kind == "loopback":
51
+ if assessment.scheme != "http":
52
+ raise ValueError("loopback redirect URIs for native apps must use http")
53
+ if assessment.port is None:
54
+ raise ValueError(
55
+ "loopback redirect URIs for native apps must include an explicit port"
56
+ )
57
+ if parsed.username or parsed.password:
58
+ raise ValueError("loopback redirect URIs must not include userinfo")
59
+ return assessment
60
+ # private-use scheme
61
+ if parsed.netloc:
62
+ raise ValueError(
63
+ "private-use scheme redirect URIs must not include an authority component"
64
+ )
65
+ return assessment
66
+
67
+
68
+ def validate_native_client_metadata(
69
+ *,
70
+ redirect_uris: Iterable[str],
71
+ response_types: Iterable[str] | None = None,
72
+ grant_types: Iterable[str] | None = None,
73
+ ) -> dict[str, object]:
74
+ assessments = [
75
+ validate_native_redirect_uri(uri)
76
+ for uri in redirect_uris
77
+ if is_native_redirect_uri(uri)
78
+ ]
79
+ if not assessments:
80
+ return {"native_application": False}
81
+ response_types_set = {str(value) for value in response_types or [] if str(value)}
82
+ if response_types_set and response_types_set != {"code"}:
83
+ raise ValueError("native apps must use the authorization code response type")
84
+ grant_types_set = {str(value) for value in grant_types or [] if str(value)}
85
+ if grant_types_set and "authorization_code" not in grant_types_set:
86
+ raise ValueError("native apps must enable the authorization_code grant type")
87
+ return {
88
+ "native_application": True,
89
+ "pkce_required": True,
90
+ "redirect_uri_kinds": sorted({assessment.kind for assessment in assessments}),
91
+ }
92
+
93
+
94
+ def validate_native_authorization_request(
95
+ *,
96
+ redirect_uri: str,
97
+ response_type: str,
98
+ code_challenge: str | None,
99
+ code_challenge_method: str | None,
100
+ ) -> NativeRedirectAssessment | None:
101
+ if not is_native_redirect_uri(redirect_uri):
102
+ return None
103
+ assessment = validate_native_redirect_uri(redirect_uri)
104
+ if set(str(response_type).split()) != {"code"}:
105
+ raise ValueError("native apps must use the authorization code flow")
106
+ if not code_challenge:
107
+ raise ValueError("PKCE code_challenge is required for native apps")
108
+ if code_challenge_method != "S256":
109
+ raise ValueError("native apps must use the S256 PKCE code_challenge_method")
110
+ return assessment
111
+
112
+
113
+ def validate_native_token_request(
114
+ *, redirect_uri: str, code_verifier: str | None
115
+ ) -> None:
116
+ if not is_native_redirect_uri(redirect_uri):
117
+ return
118
+ validate_native_redirect_uri(redirect_uri)
119
+ if not code_verifier:
120
+ raise ValueError("PKCE code_verifier is required for native apps")
121
+
122
+
123
+ __all__ = [
124
+ "RFC8252_SPEC_URL",
125
+ "NativeRedirectAssessment",
126
+ "classify_native_redirect_uri",
127
+ "is_native_redirect_uri",
128
+ "validate_native_authorization_request",
129
+ "validate_native_client_metadata",
130
+ "validate_native_redirect_uri",
131
+ "validate_native_token_request",
132
+ ]
@@ -0,0 +1,47 @@
1
+ """OAuth 2.0 Security Best Current Practice public surface."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from ._rfc9700 import (
6
+ DEVICE_CODE_GRANT_TYPE,
7
+ RFC9700_SPEC_URL,
8
+ TOKEN_EXCHANGE_GRANT_TYPE,
9
+ OAuthDeploymentProfile,
10
+ OAuthPolicyViolation,
11
+ RuntimeSecurityProfile,
12
+ SenderConstraintResult,
13
+ assert_authorization_request_allowed,
14
+ assert_token_request_allowed,
15
+ authorization_enforcement_matrix,
16
+ client_certificate_thumbprint_from_request,
17
+ discovery_policy_metadata,
18
+ dpop_proof_from_request,
19
+ runtime_security_profile,
20
+ security_bcp_profile,
21
+ validate_sender_constraint,
22
+ validate_sender_constraint_async,
23
+ verify_access_token_sender_constraint,
24
+ verify_access_token_sender_constraint_async,
25
+ )
26
+
27
+ __all__ = [
28
+ "DEVICE_CODE_GRANT_TYPE",
29
+ "RFC9700_SPEC_URL",
30
+ "TOKEN_EXCHANGE_GRANT_TYPE",
31
+ "OAuthDeploymentProfile",
32
+ "OAuthPolicyViolation",
33
+ "RuntimeSecurityProfile",
34
+ "SenderConstraintResult",
35
+ "assert_authorization_request_allowed",
36
+ "assert_token_request_allowed",
37
+ "authorization_enforcement_matrix",
38
+ "client_certificate_thumbprint_from_request",
39
+ "discovery_policy_metadata",
40
+ "dpop_proof_from_request",
41
+ "runtime_security_profile",
42
+ "security_bcp_profile",
43
+ "validate_sender_constraint",
44
+ "validate_sender_constraint_async",
45
+ "verify_access_token_sender_constraint",
46
+ "verify_access_token_sender_constraint_async",
47
+ ]