tba-protocol-oidc 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 (36) hide show
  1. tba_protocol_oidc/__init__.py +92 -0
  2. tba_protocol_oidc/bindings.py +37 -0
  3. tba_protocol_oidc/capability_requirements.py +5 -0
  4. tba_protocol_oidc/claim_sets.py +119 -0
  5. tba_protocol_oidc/claims.py +19 -0
  6. tba_protocol_oidc/compatibility.py +37 -0
  7. tba_protocol_oidc/discovery.py +23 -0
  8. tba_protocol_oidc/eap_acr_values.py +27 -0
  9. tba_protocol_oidc/errors.py +16 -0
  10. tba_protocol_oidc/features.py +26 -0
  11. tba_protocol_oidc/id_token.py +26 -0
  12. tba_protocol_oidc/id_token_profile.py +55 -0
  13. tba_protocol_oidc/jwks_service.py +12 -0
  14. tba_protocol_oidc/migrations.py +14 -0
  15. tba_protocol_oidc/provider.py +223 -0
  16. tba_protocol_oidc/py.typed +0 -0
  17. tba_protocol_oidc/reusable_components.py +23 -0
  18. tba_protocol_oidc/schemas.py +31 -0
  19. tba_protocol_oidc/standards/__init__.py +8 -0
  20. tba_protocol_oidc/standards/_rp_logout_validation.py +113 -0
  21. tba_protocol_oidc/standards/backchannel_logout.py +236 -0
  22. tba_protocol_oidc/standards/core.py +35 -0
  23. tba_protocol_oidc/standards/discovery.py +53 -0
  24. tba_protocol_oidc/standards/discovery_metadata.py +148 -0
  25. tba_protocol_oidc/standards/frontchannel_logout.py +107 -0
  26. tba_protocol_oidc/standards/id_token.py +134 -0
  27. tba_protocol_oidc/standards/openid4vc.py +80 -0
  28. tba_protocol_oidc/standards/rp_initiated_logout.py +279 -0
  29. tba_protocol_oidc/standards/session_mgmt.py +222 -0
  30. tba_protocol_oidc/standards/set_delivery.py +31 -0
  31. tba_protocol_oidc/standards/userinfo.py +54 -0
  32. tba_protocol_oidc/tenant_discovery.py +226 -0
  33. tba_protocol_oidc/versions.py +25 -0
  34. tba_protocol_oidc-0.4.0.dev2.dist-info/METADATA +139 -0
  35. tba_protocol_oidc-0.4.0.dev2.dist-info/RECORD +36 -0
  36. tba_protocol_oidc-0.4.0.dev2.dist-info/WHEEL +4 -0
@@ -0,0 +1,279 @@
1
+ """OpenID Connect RP-Initiated Logout with durable fanout planning and replay protection."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Awaitable, Callable, Final, Mapping
6
+ from tba_contracts_identity.oidc import LogoutRequestContext
7
+ from tba_primitives_identity.standards import StandardOwner, describe_owner
8
+ from uuid import UUID
9
+
10
+ from ._rp_logout_validation import (
11
+ OWNER,
12
+ _audiences,
13
+ _normalize_uuid,
14
+ _normalized_uris,
15
+ _require_https_if_present,
16
+ _unsafe_decode_jwt_claims,
17
+ _verify_id_token_hint,
18
+ assert_logout_session_active,
19
+ )
20
+
21
+ try: # dependency-light import path for checkpoint evidence generation
22
+ from http import HTTPStatus as status
23
+ from tigrbl.runtime.status import HTTPException
24
+ except Exception: # pragma: no cover - exercised in dependency-light tests
25
+
26
+ class _FallbackStatus:
27
+ HTTP_400_BAD_REQUEST = 400
28
+ HTTP_401_UNAUTHORIZED = 401
29
+ HTTP_404_NOT_FOUND = 404
30
+
31
+ class HTTPException(Exception):
32
+ def __init__(self, status_code: int, detail: Any):
33
+ super().__init__(detail)
34
+ self.status_code = status_code
35
+ self.detail = detail
36
+
37
+ status = _FallbackStatus()
38
+
39
+ STATUS: Final[str] = "rp-initiated-logout-runtime"
40
+
41
+
42
+ async def validate_post_logout_redirect_uri(
43
+ *,
44
+ client_id: UUID | None,
45
+ post_logout_redirect_uri: str | None,
46
+ registration_metadata: Mapping[str, Any] | None,
47
+ ) -> str | None:
48
+ if not post_logout_redirect_uri:
49
+ return None
50
+ _require_https_if_present(post_logout_redirect_uri)
51
+ if client_id is None:
52
+ raise HTTPException(
53
+ status.HTTP_400_BAD_REQUEST,
54
+ {
55
+ "error": "invalid_client",
56
+ "error_description": "client_id required when post_logout_redirect_uri is supplied",
57
+ },
58
+ )
59
+ metadata = dict(registration_metadata or {})
60
+ allowed = _normalized_uris(metadata.get("post_logout_redirect_uris"))
61
+ if post_logout_redirect_uri not in allowed:
62
+ raise HTTPException(
63
+ status.HTTP_400_BAD_REQUEST,
64
+ {
65
+ "error": "invalid_request",
66
+ "error_description": "unregistered post_logout_redirect_uri",
67
+ },
68
+ )
69
+ return post_logout_redirect_uri
70
+
71
+
72
+ async def validate_id_token_hint(
73
+ *,
74
+ id_token_hint: str | None,
75
+ client_id: UUID | str | None = None,
76
+ session_id: UUID | str | None = None,
77
+ issuer: str | None = None,
78
+ ) -> dict[str, Any] | None:
79
+ if not id_token_hint:
80
+ return None
81
+ effective_issuer = str(issuer or "").strip()
82
+ if not effective_issuer:
83
+ raise HTTPException(
84
+ status.HTTP_400_BAD_REQUEST,
85
+ {"error": "invalid_id_token_hint", "error_description": "issuer required"},
86
+ )
87
+ effective_client_id = _normalize_uuid(client_id)
88
+ if effective_client_id is None:
89
+ unverified = _unsafe_decode_jwt_claims(id_token_hint)
90
+ for audience in _audiences(unverified):
91
+ parsed = _normalize_uuid(audience)
92
+ if parsed is not None:
93
+ effective_client_id = parsed
94
+ break
95
+ if effective_client_id is None:
96
+ raise HTTPException(
97
+ status.HTTP_400_BAD_REQUEST,
98
+ {
99
+ "error": "invalid_id_token_hint",
100
+ "error_description": "unable to derive client_id from id_token_hint",
101
+ },
102
+ )
103
+ try:
104
+ claims = dict(
105
+ await _verify_id_token_hint(
106
+ id_token_hint,
107
+ issuer=effective_issuer,
108
+ audience=str(effective_client_id),
109
+ )
110
+ )
111
+ except Exception as exc:
112
+ raise HTTPException(
113
+ status.HTTP_400_BAD_REQUEST, {"error": "invalid_id_token_hint"}
114
+ ) from exc
115
+ if str(claims.get("iss") or "") != effective_issuer:
116
+ raise HTTPException(
117
+ status.HTTP_400_BAD_REQUEST,
118
+ {"error": "invalid_id_token_hint", "error_description": "issuer mismatch"},
119
+ )
120
+ audiences = _audiences(claims)
121
+ if str(effective_client_id) not in audiences:
122
+ raise HTTPException(
123
+ status.HTTP_400_BAD_REQUEST,
124
+ {
125
+ "error": "invalid_id_token_hint",
126
+ "error_description": "audience mismatch",
127
+ },
128
+ )
129
+ expected_session_id = _normalize_uuid(session_id)
130
+ if expected_session_id is not None:
131
+ sid = _normalize_uuid(claims.get("sid"))
132
+ if sid is not None and sid != expected_session_id:
133
+ raise HTTPException(
134
+ status.HTTP_400_BAD_REQUEST,
135
+ {"error": "invalid_id_token_hint", "error_description": "sid mismatch"},
136
+ )
137
+ return claims
138
+
139
+
140
+ def resolve_logout_client_id(
141
+ *,
142
+ requested_client_id: UUID | str | None,
143
+ session_row=None,
144
+ hint_claims: dict[str, Any] | None = None,
145
+ ) -> UUID | None:
146
+ requested = _normalize_uuid(requested_client_id)
147
+ session_client = (
148
+ _normalize_uuid(getattr(session_row, "client_id", None))
149
+ if session_row is not None
150
+ else None
151
+ )
152
+ hint_candidates = {
153
+ _normalize_uuid(audience) for audience in _audiences(hint_claims)
154
+ }
155
+ hint_candidates.discard(None)
156
+
157
+ if (
158
+ requested is not None
159
+ and session_client is not None
160
+ and requested != session_client
161
+ ):
162
+ raise HTTPException(
163
+ status.HTTP_400_BAD_REQUEST,
164
+ {
165
+ "error": "invalid_client",
166
+ "error_description": "requested client does not own the session",
167
+ },
168
+ )
169
+ if requested is not None and hint_candidates and requested not in hint_candidates:
170
+ raise HTTPException(
171
+ status.HTTP_400_BAD_REQUEST,
172
+ {
173
+ "error": "invalid_client",
174
+ "error_description": "requested client does not match id_token_hint",
175
+ },
176
+ )
177
+ if (
178
+ session_client is not None
179
+ and hint_candidates
180
+ and session_client not in hint_candidates
181
+ ):
182
+ raise HTTPException(
183
+ status.HTTP_400_BAD_REQUEST,
184
+ {
185
+ "error": "invalid_client",
186
+ "error_description": "session client does not match id_token_hint",
187
+ },
188
+ )
189
+
190
+ if requested is not None:
191
+ return requested
192
+ if session_client is not None:
193
+ return session_client
194
+ for candidate in hint_candidates:
195
+ return candidate
196
+ return None
197
+
198
+
199
+ async def validate_logout_request(
200
+ *,
201
+ requested_client_id: UUID | str | None,
202
+ post_logout_redirect_uri: str | None,
203
+ id_token_hint: str | None,
204
+ session_row=None,
205
+ issuer: str | None = None,
206
+ registration_resolver: Callable[[UUID], Awaitable[Any]] | None = None,
207
+ ) -> LogoutRequestContext:
208
+ assert_logout_session_active(session_row)
209
+ prevalidated_client_id = _normalize_uuid(requested_client_id) or _normalize_uuid(
210
+ getattr(session_row, "client_id", None)
211
+ )
212
+ hint_claims = await validate_id_token_hint(
213
+ id_token_hint=id_token_hint,
214
+ client_id=prevalidated_client_id,
215
+ session_id=getattr(session_row, "id", None),
216
+ issuer=issuer,
217
+ )
218
+ client_id = resolve_logout_client_id(
219
+ requested_client_id=requested_client_id,
220
+ session_row=session_row,
221
+ hint_claims=hint_claims,
222
+ )
223
+ registration_metadata: Mapping[str, Any] | None = None
224
+ if post_logout_redirect_uri and client_id is not None:
225
+ if registration_resolver is None:
226
+ raise RuntimeError(
227
+ "logout validation requires an injected registration resolver"
228
+ )
229
+ registration = await registration_resolver(client_id)
230
+ registration_metadata = dict(
231
+ getattr(registration, "registration_metadata", {}) or {}
232
+ )
233
+ redirect_uri = await validate_post_logout_redirect_uri(
234
+ client_id=client_id,
235
+ post_logout_redirect_uri=post_logout_redirect_uri,
236
+ registration_metadata=registration_metadata,
237
+ )
238
+ return LogoutRequestContext(
239
+ client_id=client_id,
240
+ post_logout_redirect_uri=redirect_uri,
241
+ id_token_hint_claims=hint_claims,
242
+ )
243
+
244
+
245
+ def describe(*, deployment=None) -> dict[str, object]:
246
+ return describe_owner(
247
+ OWNER,
248
+ id_token_hint_validation_supported=True,
249
+ post_logout_redirect_uri_validation_supported=True,
250
+ idempotent_replay_protection=True,
251
+ frontchannel_logout_supported=bool(
252
+ getattr(deployment, "flag_enabled", lambda *_: True)(
253
+ "enable_oidc_frontchannel_logout"
254
+ )
255
+ )
256
+ if deployment is not None
257
+ else True,
258
+ backchannel_logout_supported=bool(
259
+ getattr(deployment, "flag_enabled", lambda *_: True)(
260
+ "enable_oidc_backchannel_logout"
261
+ )
262
+ )
263
+ if deployment is not None
264
+ else True,
265
+ )
266
+
267
+
268
+ __all__ = [
269
+ "STATUS",
270
+ "LogoutRequestContext",
271
+ "StandardOwner",
272
+ "OWNER",
273
+ "assert_logout_session_active",
274
+ "describe",
275
+ "resolve_logout_client_id",
276
+ "validate_id_token_hint",
277
+ "validate_logout_request",
278
+ "validate_post_logout_redirect_uri",
279
+ ]
@@ -0,0 +1,222 @@
1
+ """OpenID Connect Session Management with durable browser-session handling.
2
+
3
+ This module deliberately keeps the session-management claim boundary truthful:
4
+ - durable browser sessions are persisted server-side
5
+ - ``session_state`` values are emitted and can be validated against client origins
6
+ - auth-code issuance is bound to the durable browser session
7
+ - cookie rotation / renewal / invalidation semantics are repository-owned
8
+ - a dedicated mounted ``check_session_iframe`` route is *not* currently claimed
9
+ by discovery or contracts in this checkpoint
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from hashlib import sha256
15
+ from typing import Final
16
+
17
+ from tba_contracts_identity.oidc import SessionStateValidation
18
+ from tba_primitives_identity.standards import StandardOwner, describe_owner
19
+ from urllib.parse import urlparse
20
+ from uuid import UUID
21
+
22
+ from tba_protocol_oauth.standards.authorization_server_metadata import ISSUER
23
+
24
+ STATUS: Final[str] = "browser-session-runtime"
25
+
26
+
27
+ OWNER = StandardOwner(
28
+ label="OIDC Session Management",
29
+ title="OpenID Connect Session Management",
30
+ runtime_status=STATUS,
31
+ public_surface=("/login", "/authorize", "/logout"),
32
+ notes=(
33
+ "Durable browser sessions own opaque session-cookie secrets, cookie rotation, "
34
+ "client binding, auth-code linkage, and OIDC session_state generation + validation across "
35
+ "client origins. This release path does not claim a mounted check_session_iframe endpoint, "
36
+ "and discovery/contracts remain truthful about that omission."
37
+ ),
38
+ )
39
+
40
+
41
+ def _origin(uri: str | None) -> str:
42
+ if not uri:
43
+ return ""
44
+ parsed = urlparse(uri)
45
+ host = parsed.hostname or ""
46
+ port = f":{parsed.port}" if parsed.port else ""
47
+ return f"{parsed.scheme}://{host}{port}" if parsed.scheme and host else uri
48
+
49
+
50
+ def session_client_origin(redirect_uri: str | None) -> str:
51
+ return _origin(redirect_uri)
52
+
53
+
54
+ def compute_session_state(
55
+ *,
56
+ client_id: str,
57
+ redirect_uri: str,
58
+ session_id: UUID | str,
59
+ salt: str,
60
+ issuer: str | None = None,
61
+ ) -> str:
62
+ origin = _origin(redirect_uri)
63
+ payload = f"{client_id} {origin} {session_id} {salt} {issuer or ISSUER}"
64
+ return f"{sha256(payload.encode('utf-8')).hexdigest()}.{salt}"
65
+
66
+
67
+ def parse_session_state(value: str | None) -> tuple[str, str] | None:
68
+ if not value or not isinstance(value, str):
69
+ return None
70
+ if "." not in value:
71
+ return None
72
+ digest, salt = value.rsplit(".", 1)
73
+ if len(digest) != 64 or not salt:
74
+ return None
75
+ try:
76
+ int(digest, 16)
77
+ except Exception:
78
+ return None
79
+ return digest, salt
80
+
81
+
82
+ def validate_session_state(
83
+ *,
84
+ presented_session_state: str | None,
85
+ client_id: str,
86
+ redirect_uri: str,
87
+ session_id: UUID | str,
88
+ salt: str | None = None,
89
+ expected_session_state: str | None = None,
90
+ issuer: str | None = None,
91
+ ) -> SessionStateValidation:
92
+ origin = _origin(redirect_uri)
93
+ parsed_presented = parse_session_state(presented_session_state)
94
+ if parsed_presented is None:
95
+ return SessionStateValidation(
96
+ valid=False,
97
+ reason="malformed_session_state",
98
+ origin=origin,
99
+ presented_session_state=presented_session_state,
100
+ expected_session_state=expected_session_state,
101
+ )
102
+ presented_digest, presented_salt = parsed_presented
103
+ effective_salt = salt or presented_salt
104
+ effective_expected = expected_session_state or compute_session_state(
105
+ client_id=client_id,
106
+ redirect_uri=redirect_uri,
107
+ session_id=session_id,
108
+ salt=effective_salt,
109
+ issuer=issuer,
110
+ )
111
+ parsed_expected = parse_session_state(effective_expected)
112
+ if parsed_expected is None:
113
+ return SessionStateValidation(
114
+ valid=False,
115
+ reason="invalid_expected_session_state",
116
+ origin=origin,
117
+ presented_session_state=presented_session_state,
118
+ expected_session_state=effective_expected,
119
+ )
120
+ expected_digest, expected_salt = parsed_expected
121
+ if presented_salt != expected_salt:
122
+ return SessionStateValidation(
123
+ valid=False,
124
+ reason="salt_mismatch",
125
+ origin=origin,
126
+ presented_session_state=presented_session_state,
127
+ expected_session_state=effective_expected,
128
+ )
129
+ if presented_digest != expected_digest:
130
+ return SessionStateValidation(
131
+ valid=False,
132
+ reason="hash_mismatch",
133
+ origin=origin,
134
+ presented_session_state=presented_session_state,
135
+ expected_session_state=effective_expected,
136
+ )
137
+ return SessionStateValidation(
138
+ valid=True,
139
+ reason="validated",
140
+ origin=origin,
141
+ presented_session_state=presented_session_state,
142
+ expected_session_state=effective_expected,
143
+ )
144
+
145
+
146
+ def session_state_for_client(
147
+ session_row,
148
+ *,
149
+ client_id: str,
150
+ redirect_uri: str,
151
+ deployment=None,
152
+ issuer: str | None = None,
153
+ ) -> str | None:
154
+ if session_row is None:
155
+ return None
156
+ if deployment is None:
157
+ raise TypeError("session_state_for_client requires an injected deployment")
158
+ if not deployment.flag_enabled("enable_oidc_session_management"):
159
+ return None
160
+ salt = getattr(session_row, "session_state_salt", None)
161
+ if not salt:
162
+ return None
163
+ return compute_session_state(
164
+ client_id=client_id,
165
+ redirect_uri=redirect_uri,
166
+ session_id=session_row.id,
167
+ salt=salt,
168
+ issuer=issuer or getattr(deployment, "issuer", None),
169
+ )
170
+
171
+
172
+ def validate_session_state_for_client(
173
+ session_row,
174
+ *,
175
+ presented_session_state: str | None,
176
+ client_id: str,
177
+ redirect_uri: str,
178
+ deployment=None,
179
+ issuer: str | None = None,
180
+ ) -> SessionStateValidation:
181
+ if session_row is None:
182
+ return SessionStateValidation(
183
+ valid=False,
184
+ reason="no_session",
185
+ origin=_origin(redirect_uri),
186
+ presented_session_state=presented_session_state,
187
+ expected_session_state=None,
188
+ )
189
+ return validate_session_state(
190
+ presented_session_state=presented_session_state,
191
+ client_id=client_id,
192
+ redirect_uri=redirect_uri,
193
+ session_id=session_row.id,
194
+ salt=getattr(session_row, "session_state_salt", None),
195
+ issuer=issuer or getattr(deployment, "issuer", None),
196
+ )
197
+
198
+
199
+ def describe(*, cross_site_logout_enabled: bool = True) -> dict[str, object]:
200
+ return describe_owner(
201
+ OWNER,
202
+ session_state_validation_supported=True,
203
+ session_state_origin_bound=True,
204
+ auth_code_linkage_supported=True,
205
+ check_session_iframe_claimed=False,
206
+ cross_site_logout_enabled=cross_site_logout_enabled,
207
+ )
208
+
209
+
210
+ __all__ = [
211
+ "STATUS",
212
+ "SessionStateValidation",
213
+ "StandardOwner",
214
+ "OWNER",
215
+ "compute_session_state",
216
+ "describe",
217
+ "parse_session_state",
218
+ "session_client_origin",
219
+ "session_state_for_client",
220
+ "validate_session_state",
221
+ "validate_session_state_for_client",
222
+ ]
@@ -0,0 +1,31 @@
1
+ """RFC 8935 push and RFC 8936 poll delivery contracts for RFC 8417 SETs."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from typing import Mapping
7
+
8
+
9
+ @dataclass(frozen=True, slots=True)
10
+ class SetPushRequest:
11
+ set_token: str
12
+
13
+ def form(self) -> Mapping[str, str]:
14
+ if self.set_token.count(".") != 2:
15
+ raise ValueError("SET push payload must be a compact JWT")
16
+ return {"SET": self.set_token}
17
+
18
+
19
+ @dataclass(frozen=True, slots=True)
20
+ class SetPollRequest:
21
+ max_events: int | None = None
22
+ return_immediately: bool | None = None
23
+ acks: tuple[str, ...] = ()
24
+ set_errs: Mapping[str, str] | None = None
25
+
26
+ def __post_init__(self) -> None:
27
+ if self.max_events is not None and self.max_events <= 0:
28
+ raise ValueError("max_events must be positive")
29
+
30
+
31
+ __all__ = ["SetPollRequest", "SetPushRequest"]
@@ -0,0 +1,54 @@
1
+ """OIDC Core UserInfo specification ownership without runtime mounting."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Final
6
+
7
+ from tba_primitives_identity.standards import StandardOwner, describe_owner
8
+
9
+
10
+ OIDC_USERINFO_SPEC_URL: Final[str] = (
11
+ "https://openid.net/specs/openid-connect-core-1_0.html#UserInfo"
12
+ )
13
+ USERINFO_SCOPE_CLAIMS: Final[dict[str, tuple[str, ...]]] = {
14
+ "openid": ("sub",),
15
+ "profile": ("name",),
16
+ "email": ("email",),
17
+ "address": ("address",),
18
+ "phone": ("phone_number",),
19
+ }
20
+
21
+ OWNER = StandardOwner(
22
+ label="OIDC Core UserInfo",
23
+ title="OpenID Connect Core 1.0 UserInfo Endpoint",
24
+ runtime_status="runtime-composed",
25
+ public_surface=("/userinfo",),
26
+ notes=(
27
+ "Layer 50 owns the OIDC UserInfo version, scope-to-claim mapping, and "
28
+ "wire semantics. Layer 60 composes verification and claim resolution; "
29
+ "layer 80 owns the HTTP carrier.",
30
+ ),
31
+ )
32
+
33
+
34
+ def describe() -> dict[str, object]:
35
+ """Describe the selected OIDC Core UserInfo protocol feature."""
36
+
37
+ return describe_owner(
38
+ OWNER,
39
+ specification_uri=OIDC_USERINFO_SPEC_URL,
40
+ methods=("GET",),
41
+ bearer_token_required=True,
42
+ signed_response_media_type="application/jwt",
43
+ scope_claims={
44
+ scope: list(claims) for scope, claims in USERINFO_SCOPE_CLAIMS.items()
45
+ },
46
+ )
47
+
48
+
49
+ __all__ = [
50
+ "OIDC_USERINFO_SPEC_URL",
51
+ "OWNER",
52
+ "USERINFO_SCOPE_CLAIMS",
53
+ "describe",
54
+ ]