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.
- tba_protocol_oidc/__init__.py +92 -0
- tba_protocol_oidc/bindings.py +37 -0
- tba_protocol_oidc/capability_requirements.py +5 -0
- tba_protocol_oidc/claim_sets.py +119 -0
- tba_protocol_oidc/claims.py +19 -0
- tba_protocol_oidc/compatibility.py +37 -0
- tba_protocol_oidc/discovery.py +23 -0
- tba_protocol_oidc/eap_acr_values.py +27 -0
- tba_protocol_oidc/errors.py +16 -0
- tba_protocol_oidc/features.py +26 -0
- tba_protocol_oidc/id_token.py +26 -0
- tba_protocol_oidc/id_token_profile.py +55 -0
- tba_protocol_oidc/jwks_service.py +12 -0
- tba_protocol_oidc/migrations.py +14 -0
- tba_protocol_oidc/provider.py +223 -0
- tba_protocol_oidc/py.typed +0 -0
- tba_protocol_oidc/reusable_components.py +23 -0
- tba_protocol_oidc/schemas.py +31 -0
- tba_protocol_oidc/standards/__init__.py +8 -0
- tba_protocol_oidc/standards/_rp_logout_validation.py +113 -0
- tba_protocol_oidc/standards/backchannel_logout.py +236 -0
- tba_protocol_oidc/standards/core.py +35 -0
- tba_protocol_oidc/standards/discovery.py +53 -0
- tba_protocol_oidc/standards/discovery_metadata.py +148 -0
- tba_protocol_oidc/standards/frontchannel_logout.py +107 -0
- tba_protocol_oidc/standards/id_token.py +134 -0
- tba_protocol_oidc/standards/openid4vc.py +80 -0
- tba_protocol_oidc/standards/rp_initiated_logout.py +279 -0
- tba_protocol_oidc/standards/session_mgmt.py +222 -0
- tba_protocol_oidc/standards/set_delivery.py +31 -0
- tba_protocol_oidc/standards/userinfo.py +54 -0
- tba_protocol_oidc/tenant_discovery.py +226 -0
- tba_protocol_oidc/versions.py +25 -0
- tba_protocol_oidc-0.4.0.dev2.dist-info/METADATA +139 -0
- tba_protocol_oidc-0.4.0.dev2.dist-info/RECORD +36 -0
- tba_protocol_oidc-0.4.0.dev2.dist-info/WHEEL +4 -0
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import html
|
|
4
|
+
import secrets
|
|
5
|
+
from dataclasses import replace
|
|
6
|
+
from datetime import datetime, timedelta, timezone
|
|
7
|
+
from typing import Callable, Iterable, Mapping
|
|
8
|
+
|
|
9
|
+
from tba_contracts_identity.oidc import (
|
|
10
|
+
HostedLoginPage,
|
|
11
|
+
HostedLoginRequest,
|
|
12
|
+
LoginThemeAssetPolicy,
|
|
13
|
+
LogoutPlan,
|
|
14
|
+
LogoutRequest,
|
|
15
|
+
OidcContractError,
|
|
16
|
+
OidcSession,
|
|
17
|
+
TenantBranding,
|
|
18
|
+
)
|
|
19
|
+
from tba_contracts_identity.protocols import OidcSessionStatus
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
OidcProviderError = OidcContractError
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _utc_now() -> datetime:
|
|
26
|
+
return datetime.now(tz=timezone.utc)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _token(prefix: str) -> str:
|
|
30
|
+
return f"{prefix}_{secrets.token_urlsafe(20)}"
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class TenantBrandingRegistry:
|
|
34
|
+
def __init__(
|
|
35
|
+
self,
|
|
36
|
+
asset_policy: LoginThemeAssetPolicy | None = None,
|
|
37
|
+
) -> None:
|
|
38
|
+
self.asset_policy = asset_policy or LoginThemeAssetPolicy()
|
|
39
|
+
self._items: dict[str, TenantBranding] = {}
|
|
40
|
+
|
|
41
|
+
def set(self, branding: TenantBranding) -> TenantBranding:
|
|
42
|
+
self.asset_policy.validate_asset_uri(branding.logo_uri)
|
|
43
|
+
branding.sanitized_display_name()
|
|
44
|
+
branding.sanitized_primary_color()
|
|
45
|
+
self._items[branding.tenant_id] = branding
|
|
46
|
+
return branding
|
|
47
|
+
|
|
48
|
+
def get(self, tenant_id: str) -> TenantBranding:
|
|
49
|
+
try:
|
|
50
|
+
return self._items[tenant_id]
|
|
51
|
+
except KeyError as exc:
|
|
52
|
+
raise OidcProviderError("tenant branding is not configured") from exc
|
|
53
|
+
|
|
54
|
+
def snapshot(self) -> Mapping[str, TenantBranding]:
|
|
55
|
+
return dict(self._items)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class OidcProviderRuntime:
|
|
59
|
+
def __init__(
|
|
60
|
+
self,
|
|
61
|
+
allowed_redirect_uris: Mapping[str, tuple[str, ...]],
|
|
62
|
+
frontchannel_logout_uris: Mapping[str, tuple[str, ...]] | None = None,
|
|
63
|
+
backchannel_logout_uris: Mapping[str, tuple[str, ...]] | None = None,
|
|
64
|
+
now: Callable[[], datetime] = _utc_now,
|
|
65
|
+
) -> None:
|
|
66
|
+
self.allowed_redirect_uris = allowed_redirect_uris
|
|
67
|
+
self.frontchannel_logout_uris = frontchannel_logout_uris or {}
|
|
68
|
+
self.backchannel_logout_uris = backchannel_logout_uris or {}
|
|
69
|
+
self.now = now
|
|
70
|
+
self._sessions = {}
|
|
71
|
+
|
|
72
|
+
@property
|
|
73
|
+
def sessions(self) -> Mapping[str, OidcSession]:
|
|
74
|
+
return dict(self._sessions)
|
|
75
|
+
|
|
76
|
+
def render_hosted_login(
|
|
77
|
+
self, request: HostedLoginRequest, branding: TenantBranding
|
|
78
|
+
) -> HostedLoginPage:
|
|
79
|
+
self._require_redirect_uri(request.client_id, request.redirect_uri)
|
|
80
|
+
if request.tenant_id != branding.tenant_id:
|
|
81
|
+
raise OidcProviderError("tenant branding mismatch")
|
|
82
|
+
if "openid" not in request.scope:
|
|
83
|
+
raise OidcProviderError("OIDC hosted login requires openid scope")
|
|
84
|
+
rendered = render_login_template(request, branding)
|
|
85
|
+
return HostedLoginPage(
|
|
86
|
+
tenant_id=request.tenant_id,
|
|
87
|
+
client_id=request.client_id,
|
|
88
|
+
html=rendered,
|
|
89
|
+
state=request.state,
|
|
90
|
+
nonce=request.nonce,
|
|
91
|
+
)
|
|
92
|
+
|
|
93
|
+
def render_hosted_login_for_tenant(
|
|
94
|
+
self,
|
|
95
|
+
request: HostedLoginRequest,
|
|
96
|
+
registry: TenantBrandingRegistry,
|
|
97
|
+
) -> HostedLoginPage:
|
|
98
|
+
return self.render_hosted_login(request, registry.get(request.tenant_id))
|
|
99
|
+
|
|
100
|
+
def create_session(
|
|
101
|
+
self,
|
|
102
|
+
*,
|
|
103
|
+
tenant_id: str,
|
|
104
|
+
subject: str,
|
|
105
|
+
client_id: str,
|
|
106
|
+
nonce: str,
|
|
107
|
+
ttl_seconds: int = 3600,
|
|
108
|
+
) -> OidcSession:
|
|
109
|
+
if ttl_seconds <= 0:
|
|
110
|
+
raise OidcProviderError("session ttl must be positive")
|
|
111
|
+
session = OidcSession(
|
|
112
|
+
session_id=_token("sid"),
|
|
113
|
+
tenant_id=tenant_id,
|
|
114
|
+
subject=subject,
|
|
115
|
+
client_id=client_id,
|
|
116
|
+
nonce=nonce,
|
|
117
|
+
created_at=self.now(),
|
|
118
|
+
expires_at=self.now() + timedelta(seconds=ttl_seconds),
|
|
119
|
+
)
|
|
120
|
+
self._sessions[session.session_id] = session
|
|
121
|
+
return session
|
|
122
|
+
|
|
123
|
+
def require_active_session(self, session_id: str) -> OidcSession:
|
|
124
|
+
session = self._sessions.get(session_id)
|
|
125
|
+
if session is None:
|
|
126
|
+
raise OidcProviderError("unknown OIDC session")
|
|
127
|
+
if session.status != OidcSessionStatus.ACTIVE:
|
|
128
|
+
raise OidcProviderError("OIDC session is not active")
|
|
129
|
+
if self.now() >= session.expires_at:
|
|
130
|
+
expired = replace(session, status=OidcSessionStatus.EXPIRED)
|
|
131
|
+
self._sessions[session_id] = expired
|
|
132
|
+
raise OidcProviderError("OIDC session expired")
|
|
133
|
+
return session
|
|
134
|
+
|
|
135
|
+
def build_logout_plan(self, request: LogoutRequest) -> LogoutPlan:
|
|
136
|
+
session = self.require_active_session(request.session_id)
|
|
137
|
+
if (
|
|
138
|
+
session.tenant_id != request.tenant_id
|
|
139
|
+
or session.client_id != request.client_id
|
|
140
|
+
):
|
|
141
|
+
raise OidcProviderError("logout request does not match OIDC session")
|
|
142
|
+
if request.post_logout_redirect_uri is not None:
|
|
143
|
+
self._require_redirect_uri(
|
|
144
|
+
request.client_id, request.post_logout_redirect_uri
|
|
145
|
+
)
|
|
146
|
+
logged_out = replace(session, status=OidcSessionStatus.LOGGED_OUT)
|
|
147
|
+
self._sessions[session.session_id] = logged_out
|
|
148
|
+
return LogoutPlan(
|
|
149
|
+
session_id=session.session_id,
|
|
150
|
+
status=logged_out.status,
|
|
151
|
+
frontchannel_notifications=tuple(
|
|
152
|
+
self.frontchannel_logout_uris.get(request.client_id, ())
|
|
153
|
+
),
|
|
154
|
+
backchannel_notifications=tuple(
|
|
155
|
+
self.backchannel_logout_uris.get(request.client_id, ())
|
|
156
|
+
),
|
|
157
|
+
redirect_uri=request.post_logout_redirect_uri,
|
|
158
|
+
state=request.state,
|
|
159
|
+
)
|
|
160
|
+
|
|
161
|
+
def _require_redirect_uri(self, client_id: str, redirect_uri: str) -> None:
|
|
162
|
+
allowed = self.allowed_redirect_uris.get(client_id, ())
|
|
163
|
+
if redirect_uri not in allowed:
|
|
164
|
+
raise OidcProviderError("redirect URI is not registered for client")
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def new_login_request(
|
|
168
|
+
*,
|
|
169
|
+
tenant_id: str,
|
|
170
|
+
client_id: str,
|
|
171
|
+
redirect_uri: str,
|
|
172
|
+
scopes: Iterable[str],
|
|
173
|
+
) -> HostedLoginRequest:
|
|
174
|
+
return HostedLoginRequest(
|
|
175
|
+
tenant_id=tenant_id,
|
|
176
|
+
client_id=client_id,
|
|
177
|
+
redirect_uri=redirect_uri,
|
|
178
|
+
scope=tuple(sorted(set(scopes))),
|
|
179
|
+
state=_token("state"),
|
|
180
|
+
nonce=_token("nonce"),
|
|
181
|
+
)
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def render_login_template(request: HostedLoginRequest, branding: TenantBranding) -> str:
|
|
185
|
+
if request.tenant_id != branding.tenant_id:
|
|
186
|
+
raise OidcProviderError("tenant branding mismatch")
|
|
187
|
+
logo = branding.sanitized_logo_uri()
|
|
188
|
+
escaped_name = branding.sanitized_display_name()
|
|
189
|
+
escaped_tenant = html.escape(request.tenant_id, quote=True)
|
|
190
|
+
escaped_client = html.escape(request.client_id, quote=True)
|
|
191
|
+
escaped_redirect = html.escape(request.redirect_uri, quote=True)
|
|
192
|
+
escaped_color = branding.sanitized_primary_color()
|
|
193
|
+
escaped_scope = html.escape(" ".join(request.scope), quote=True)
|
|
194
|
+
logo_markup = f'<img src="{logo}" alt="{escaped_name}">' if logo else ""
|
|
195
|
+
return (
|
|
196
|
+
f'<main data-tenant="{escaped_tenant}" data-client="{escaped_client}" '
|
|
197
|
+
f'data-redirect-uri="{escaped_redirect}" style="--brand-color:{escaped_color}">'
|
|
198
|
+
f"{logo_markup}<h1>{escaped_name}</h1>"
|
|
199
|
+
'<form method="post" action="/login/complete" autocomplete="on">'
|
|
200
|
+
f'<input type="hidden" name="state" value="{html.escape(request.state, quote=True)}">'
|
|
201
|
+
f'<input type="hidden" name="nonce" value="{html.escape(request.nonce, quote=True)}">'
|
|
202
|
+
f'<input type="hidden" name="scope" value="{escaped_scope}">'
|
|
203
|
+
'<input name="identifier" autocomplete="username">'
|
|
204
|
+
'<input name="password" type="password" autocomplete="current-password">'
|
|
205
|
+
"</form></main>"
|
|
206
|
+
)
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
__all__ = [
|
|
210
|
+
"HostedLoginPage",
|
|
211
|
+
"HostedLoginRequest",
|
|
212
|
+
"LoginThemeAssetPolicy",
|
|
213
|
+
"LogoutPlan",
|
|
214
|
+
"LogoutRequest",
|
|
215
|
+
"OidcProviderError",
|
|
216
|
+
"OidcProviderRuntime",
|
|
217
|
+
"OidcSession",
|
|
218
|
+
"OidcSessionStatus",
|
|
219
|
+
"TenantBranding",
|
|
220
|
+
"TenantBrandingRegistry",
|
|
221
|
+
"new_login_request",
|
|
222
|
+
"render_login_template",
|
|
223
|
+
]
|
|
File without changes
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"""OIDC composition exports from protocol-neutral concrete owners."""
|
|
2
|
+
|
|
3
|
+
from .eap_acr_values import EapAcrValue, EapAmrValue, satisfies_eap_acr
|
|
4
|
+
from tba_concrete_identity_assurance import (
|
|
5
|
+
parse_verified_claims,
|
|
6
|
+
serialize_verified_claims,
|
|
7
|
+
)
|
|
8
|
+
from tba_provider_claims_local import LocalClaimsProvider
|
|
9
|
+
from tba_concrete_pairwise_subject_identifier import (
|
|
10
|
+
PairwiseSubjectIdentifierStrategy,
|
|
11
|
+
)
|
|
12
|
+
from tba_concrete_public_subject_identifier import PublicSubjectIdentifierStrategy
|
|
13
|
+
|
|
14
|
+
__all__ = [
|
|
15
|
+
"EapAcrValue",
|
|
16
|
+
"EapAmrValue",
|
|
17
|
+
"LocalClaimsProvider",
|
|
18
|
+
"PairwiseSubjectIdentifierStrategy",
|
|
19
|
+
"PublicSubjectIdentifierStrategy",
|
|
20
|
+
"parse_verified_claims",
|
|
21
|
+
"serialize_verified_claims",
|
|
22
|
+
"satisfies_eap_acr",
|
|
23
|
+
]
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"""OpenID Connect wire schemas owned by the versioned protocol package."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from pydantic import BaseModel
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class LogoutIn(BaseModel):
|
|
11
|
+
id_token_hint: str | None = None
|
|
12
|
+
post_logout_redirect_uri: str | None = None
|
|
13
|
+
state: str | None = None
|
|
14
|
+
sid: str | None = None
|
|
15
|
+
client_id: str | None = None
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class LogoutOut(BaseModel):
|
|
19
|
+
status: str
|
|
20
|
+
session_id: str | None = None
|
|
21
|
+
logout_id: str | None = None
|
|
22
|
+
post_logout_redirect_uri: str | None = None
|
|
23
|
+
state: str | None = None
|
|
24
|
+
cookie_cleared: bool = True
|
|
25
|
+
cookie_policy: dict[str, Any] | None = None
|
|
26
|
+
frontchannel_logout: dict[str, Any] | None = None
|
|
27
|
+
backchannel_logout: dict[str, Any] | None = None
|
|
28
|
+
replay_protected: bool = True
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
__all__ = ["LogoutIn", "LogoutOut"]
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
"""OpenID Connect RP-Initiated Logout with durable fanout planning and replay protection."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import base64
|
|
6
|
+
import json
|
|
7
|
+
from typing import Any, Final
|
|
8
|
+
from tba_primitives_identity.standards import StandardOwner
|
|
9
|
+
from urllib.parse import urlparse
|
|
10
|
+
from uuid import UUID
|
|
11
|
+
|
|
12
|
+
try: # dependency-light import path for checkpoint evidence generation
|
|
13
|
+
from http import HTTPStatus as status
|
|
14
|
+
from tigrbl.runtime.status import HTTPException
|
|
15
|
+
except Exception: # pragma: no cover - exercised in dependency-light tests
|
|
16
|
+
|
|
17
|
+
class _FallbackStatus:
|
|
18
|
+
HTTP_400_BAD_REQUEST = 400
|
|
19
|
+
HTTP_401_UNAUTHORIZED = 401
|
|
20
|
+
HTTP_404_NOT_FOUND = 404
|
|
21
|
+
|
|
22
|
+
class HTTPException(Exception):
|
|
23
|
+
def __init__(self, status_code: int, detail: Any):
|
|
24
|
+
super().__init__(detail)
|
|
25
|
+
self.status_code = status_code
|
|
26
|
+
self.detail = detail
|
|
27
|
+
|
|
28
|
+
status = _FallbackStatus()
|
|
29
|
+
|
|
30
|
+
STATUS: Final[str] = "rp-initiated-logout-runtime"
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
OWNER = StandardOwner(
|
|
34
|
+
label="OIDC RP-Initiated Logout",
|
|
35
|
+
title="OpenID Connect RP-Initiated Logout",
|
|
36
|
+
runtime_status=STATUS,
|
|
37
|
+
public_surface=("/logout",),
|
|
38
|
+
notes=(
|
|
39
|
+
"The canonical /logout route validates registered post-logout redirect URIs, validates id_token_hint "
|
|
40
|
+
"claims against issuer/audience/session policy, persists logout fanout plans, and reuses an existing "
|
|
41
|
+
"logout_state record to provide replay-safe idempotence when logout is retried."
|
|
42
|
+
),
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
async def _verify_id_token_hint(token: str, *, issuer: str, audience: str):
|
|
47
|
+
from tba_protocol_oidc.standards.id_token import verify_id_token
|
|
48
|
+
|
|
49
|
+
return await verify_id_token(token, issuer=issuer, audience=audience)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _normalized_uris(value: Any) -> list[str]:
|
|
53
|
+
if value is None:
|
|
54
|
+
return []
|
|
55
|
+
if isinstance(value, list):
|
|
56
|
+
return [str(item) for item in value if item]
|
|
57
|
+
if isinstance(value, str):
|
|
58
|
+
return [item for item in value.split() if item]
|
|
59
|
+
return [str(value)]
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _normalize_uuid(value: Any) -> UUID | None:
|
|
63
|
+
if value in {None, "", False}:
|
|
64
|
+
return None
|
|
65
|
+
if isinstance(value, UUID):
|
|
66
|
+
return value
|
|
67
|
+
try:
|
|
68
|
+
return UUID(str(value))
|
|
69
|
+
except Exception:
|
|
70
|
+
return None
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _audiences(claims: dict[str, Any] | None) -> list[str]:
|
|
74
|
+
if not claims:
|
|
75
|
+
return []
|
|
76
|
+
aud = claims.get("aud")
|
|
77
|
+
if aud is None:
|
|
78
|
+
return []
|
|
79
|
+
if isinstance(aud, (list, tuple, set)):
|
|
80
|
+
return [str(item) for item in aud if item not in {None, ""}]
|
|
81
|
+
return [str(aud)] if aud not in {None, ""} else []
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _unsafe_decode_jwt_claims(token: str) -> dict[str, Any]:
|
|
85
|
+
try:
|
|
86
|
+
parts = str(token).split(".")
|
|
87
|
+
if len(parts) != 3:
|
|
88
|
+
return {}
|
|
89
|
+
padded = parts[1] + "=" * (-len(parts[1]) % 4)
|
|
90
|
+
return dict(json.loads(base64.urlsafe_b64decode(padded).decode("utf-8")))
|
|
91
|
+
except Exception:
|
|
92
|
+
return {}
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _require_https_if_present(uri: str) -> None:
|
|
96
|
+
parsed = urlparse(uri)
|
|
97
|
+
if parsed.scheme != "https":
|
|
98
|
+
raise HTTPException(
|
|
99
|
+
status.HTTP_400_BAD_REQUEST, "post_logout_redirect_uri must use https"
|
|
100
|
+
)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def assert_logout_session_active(session_row) -> None:
|
|
104
|
+
if session_row is None:
|
|
105
|
+
return None
|
|
106
|
+
state = str(getattr(session_row, "session_state", "active") or "active").lower()
|
|
107
|
+
if getattr(session_row, "ended_at", None) is not None or state in {
|
|
108
|
+
"terminated",
|
|
109
|
+
"expired",
|
|
110
|
+
"ended",
|
|
111
|
+
"revoked",
|
|
112
|
+
}:
|
|
113
|
+
raise HTTPException(status.HTTP_400_BAD_REQUEST, {"error": "expired_session"})
|
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
"""OpenID Connect Back-Channel Logout planning and durable completion tracking."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import base64
|
|
6
|
+
import hashlib
|
|
7
|
+
import hmac
|
|
8
|
+
import json
|
|
9
|
+
from datetime import datetime, timedelta, timezone
|
|
10
|
+
from typing import Any, Awaitable, Callable, Final, Mapping
|
|
11
|
+
from uuid import UUID, uuid4
|
|
12
|
+
|
|
13
|
+
from tba_primitives_identity.standards import StandardOwner, describe_owner
|
|
14
|
+
from tba_contracts_identity.protocol_configuration import (
|
|
15
|
+
protocol_settings as settings,
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
STATUS: Final[str] = "backchannel-logout-fanout-runtime"
|
|
19
|
+
_BACKCHANNEL_EVENT: Final[str] = "http://schemas.openid.net/event/backchannel-logout"
|
|
20
|
+
_DEFAULT_MAX_RETRIES: Final[int] = 3
|
|
21
|
+
_ALLOWED_CLOCK_SKEW: Final[int] = 300
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
OWNER = StandardOwner(
|
|
25
|
+
label="OIDC Back-Channel Logout",
|
|
26
|
+
title="OpenID Connect Back-Channel Logout",
|
|
27
|
+
runtime_status=STATUS,
|
|
28
|
+
public_surface=("/logout",),
|
|
29
|
+
notes=(
|
|
30
|
+
"Back-channel logout planning is implementation-backed. Client registration metadata can declare "
|
|
31
|
+
"backchannel_logout_uri and the module mints repository-owned logout tokens with replay protection, durable delivery state, and bounded retry metadata."
|
|
32
|
+
),
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _jwt_coder_cls():
|
|
37
|
+
from tba_provider_identity_jose.jwt_coder import JWTCoder
|
|
38
|
+
|
|
39
|
+
return JWTCoder
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _b64url(data: bytes) -> str:
|
|
43
|
+
return base64.urlsafe_b64encode(data).rstrip(b"=").decode("ascii")
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _b64url_decode(value: str) -> bytes:
|
|
47
|
+
return base64.urlsafe_b64decode(value + "=" * (-len(value) % 4))
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _encode_checkpoint_logout_token(claims: dict[str, Any]) -> str:
|
|
51
|
+
header = {"alg": "HS256", "typ": "logout+jwt"}
|
|
52
|
+
signing_input = ".".join(
|
|
53
|
+
(
|
|
54
|
+
_b64url(
|
|
55
|
+
json.dumps(header, separators=(",", ":"), sort_keys=True).encode(
|
|
56
|
+
"utf-8"
|
|
57
|
+
)
|
|
58
|
+
),
|
|
59
|
+
_b64url(
|
|
60
|
+
json.dumps(claims, separators=(",", ":"), sort_keys=True).encode(
|
|
61
|
+
"utf-8"
|
|
62
|
+
)
|
|
63
|
+
),
|
|
64
|
+
)
|
|
65
|
+
)
|
|
66
|
+
secret = str(
|
|
67
|
+
getattr(settings, "jwt_secret", "capability-backchannel-secret")
|
|
68
|
+
).encode("utf-8")
|
|
69
|
+
signature = hmac.new(secret, signing_input.encode("ascii"), hashlib.sha256).digest()
|
|
70
|
+
return f"{signing_input}.{_b64url(signature)}"
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _decode_checkpoint_logout_token(token: str) -> dict[str, Any]:
|
|
74
|
+
parts = str(token).split(".")
|
|
75
|
+
if len(parts) != 3:
|
|
76
|
+
raise ValueError("malformed logout token")
|
|
77
|
+
signing_input = f"{parts[0]}.{parts[1]}"
|
|
78
|
+
secret = str(
|
|
79
|
+
getattr(settings, "jwt_secret", "capability-backchannel-secret")
|
|
80
|
+
).encode("utf-8")
|
|
81
|
+
expected = hmac.new(secret, signing_input.encode("ascii"), hashlib.sha256).digest()
|
|
82
|
+
if not hmac.compare_digest(expected, _b64url_decode(parts[2])):
|
|
83
|
+
raise ValueError("logout token signature mismatch")
|
|
84
|
+
payload = json.loads(_b64url_decode(parts[1]).decode("utf-8"))
|
|
85
|
+
if not isinstance(payload, dict):
|
|
86
|
+
raise ValueError("logout token payload malformed")
|
|
87
|
+
return payload
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
async def _mint_logout_token(
|
|
91
|
+
*, claims: dict[str, Any], issuer: str, audience: str
|
|
92
|
+
) -> str:
|
|
93
|
+
"""Mint a self-contained logout token.
|
|
94
|
+
|
|
95
|
+
Back-channel logout validation must remain functional in dependency-complete
|
|
96
|
+
checkpoint environments even when the durable token-record tables are not
|
|
97
|
+
initialized. The repository-owned checkpoint format is therefore the primary
|
|
98
|
+
path for logout-token minting, with local HMAC signing plus replay tracking.
|
|
99
|
+
"""
|
|
100
|
+
|
|
101
|
+
return _encode_checkpoint_logout_token(claims)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
async def build_backchannel_descriptor(
|
|
105
|
+
*,
|
|
106
|
+
client_id: UUID,
|
|
107
|
+
sid: str,
|
|
108
|
+
sub: str,
|
|
109
|
+
iss: str | None = None,
|
|
110
|
+
logout_id: UUID | None = None,
|
|
111
|
+
registration_metadata: Mapping[str, Any],
|
|
112
|
+
) -> dict[str, object] | None:
|
|
113
|
+
metadata = dict(registration_metadata)
|
|
114
|
+
logout_uri = metadata.get("backchannel_logout_uri")
|
|
115
|
+
if not logout_uri:
|
|
116
|
+
return None
|
|
117
|
+
include_sid = bool(metadata.get("backchannel_logout_session_required", True))
|
|
118
|
+
issuer = iss or settings.issuer
|
|
119
|
+
claims: dict[str, Any] = {
|
|
120
|
+
"events": {_BACKCHANNEL_EVENT: {}},
|
|
121
|
+
"jti": str(uuid4()),
|
|
122
|
+
"iat": int(datetime.now(timezone.utc).timestamp()),
|
|
123
|
+
"iss": issuer,
|
|
124
|
+
"aud": [str(client_id)],
|
|
125
|
+
"sub": sub,
|
|
126
|
+
}
|
|
127
|
+
if include_sid:
|
|
128
|
+
claims["sid"] = sid
|
|
129
|
+
logout_token = await _mint_logout_token(
|
|
130
|
+
claims=claims, issuer=issuer, audience=str(client_id)
|
|
131
|
+
)
|
|
132
|
+
return {
|
|
133
|
+
"client_id": str(client_id),
|
|
134
|
+
"logout_uri": str(logout_uri),
|
|
135
|
+
"logout_token": logout_token,
|
|
136
|
+
"iss": issuer,
|
|
137
|
+
"sid_included": include_sid,
|
|
138
|
+
"sid": sid if include_sid else None,
|
|
139
|
+
"logout_id": str(logout_id) if logout_id is not None else None,
|
|
140
|
+
"delivery": {
|
|
141
|
+
"channel": "backchannel",
|
|
142
|
+
"status": "pending",
|
|
143
|
+
"attempts": 0,
|
|
144
|
+
"max_retries": _DEFAULT_MAX_RETRIES,
|
|
145
|
+
"replay_protected": True,
|
|
146
|
+
},
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
async def validate_backchannel_logout_token(
|
|
151
|
+
logout_token: str,
|
|
152
|
+
*,
|
|
153
|
+
client_id: UUID | str,
|
|
154
|
+
issuer: str | None = None,
|
|
155
|
+
now: datetime | None = None,
|
|
156
|
+
register_replay: Callable[..., Awaitable[Any]],
|
|
157
|
+
) -> dict[str, Any]:
|
|
158
|
+
effective_issuer = issuer or settings.issuer
|
|
159
|
+
current = now or datetime.now(timezone.utc)
|
|
160
|
+
try:
|
|
161
|
+
claims = _decode_checkpoint_logout_token(logout_token)
|
|
162
|
+
except Exception:
|
|
163
|
+
jwt_coder = _jwt_coder_cls().default()
|
|
164
|
+
claims = await jwt_coder.async_decode(
|
|
165
|
+
logout_token,
|
|
166
|
+
verify_exp=True,
|
|
167
|
+
audience=str(client_id),
|
|
168
|
+
issuer=effective_issuer,
|
|
169
|
+
)
|
|
170
|
+
claims = dict(claims)
|
|
171
|
+
if claims.get("iss") not in {None, effective_issuer}:
|
|
172
|
+
raise ValueError("logout token issuer mismatch")
|
|
173
|
+
events = claims.get("events")
|
|
174
|
+
if not isinstance(events, dict) or _BACKCHANNEL_EVENT not in events:
|
|
175
|
+
raise ValueError("logout token missing backchannel event")
|
|
176
|
+
if "nonce" in claims:
|
|
177
|
+
raise ValueError("logout token must not contain nonce")
|
|
178
|
+
if not claims.get("sid") and not claims.get("sub"):
|
|
179
|
+
raise ValueError("logout token requires sid or sub")
|
|
180
|
+
audiences = claims.get("aud")
|
|
181
|
+
if isinstance(audiences, str):
|
|
182
|
+
audiences = [audiences]
|
|
183
|
+
if str(client_id) not in [str(item) for item in list(audiences or [])]:
|
|
184
|
+
raise ValueError("logout token audience mismatch")
|
|
185
|
+
exp = claims.get("exp")
|
|
186
|
+
if exp is not None:
|
|
187
|
+
exp_dt = datetime.fromtimestamp(int(exp), tz=timezone.utc)
|
|
188
|
+
if exp_dt <= current:
|
|
189
|
+
raise ValueError("logout token expired")
|
|
190
|
+
iat = claims.get("iat")
|
|
191
|
+
if (
|
|
192
|
+
iat is not None
|
|
193
|
+
and abs(int(current.timestamp()) - int(iat)) > _ALLOWED_CLOCK_SKEW + 300
|
|
194
|
+
):
|
|
195
|
+
raise ValueError("logout token stale")
|
|
196
|
+
jti = str(claims.get("jti") or "").strip()
|
|
197
|
+
if not jti:
|
|
198
|
+
raise ValueError("logout token missing jti")
|
|
199
|
+
expiry = (
|
|
200
|
+
datetime.fromtimestamp(int(exp), tz=timezone.utc)
|
|
201
|
+
if exp is not None
|
|
202
|
+
else current + timedelta(minutes=5)
|
|
203
|
+
)
|
|
204
|
+
await register_replay(
|
|
205
|
+
jti=jti,
|
|
206
|
+
issuer=effective_issuer,
|
|
207
|
+
client_id=str(client_id),
|
|
208
|
+
expires_at=expiry,
|
|
209
|
+
now=current,
|
|
210
|
+
)
|
|
211
|
+
return claims
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def replay_store_snapshot() -> dict[str, str]:
|
|
215
|
+
return {"replay_store": "table:BackchannelLogoutReplay"}
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def describe() -> dict[str, object]:
|
|
219
|
+
return describe_owner(
|
|
220
|
+
OWNER,
|
|
221
|
+
logout_token_validation_supported=True,
|
|
222
|
+
replay_protection=True,
|
|
223
|
+
delivery_state_persisted=True,
|
|
224
|
+
retry_semantics_supported=True,
|
|
225
|
+
)
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
__all__ = [
|
|
229
|
+
"STATUS",
|
|
230
|
+
"StandardOwner",
|
|
231
|
+
"OWNER",
|
|
232
|
+
"build_backchannel_descriptor",
|
|
233
|
+
"replay_store_snapshot",
|
|
234
|
+
"validate_backchannel_logout_token",
|
|
235
|
+
"describe",
|
|
236
|
+
]
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
"""OIDC Core certified-core aggregator.
|
|
2
|
+
|
|
3
|
+
This module provides a named, non-wrapper aggregation point for the OIDC Core
|
|
4
|
+
release path. It intentionally re-exports selected discovery and ID Token
|
|
5
|
+
helpers plus descriptive UserInfo protocol ownership.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from tba_protocol_oidc.standards.id_token import (
|
|
11
|
+
mint_id_token,
|
|
12
|
+
oidc_hash,
|
|
13
|
+
rotate_rsa_jwt_key,
|
|
14
|
+
verify_id_token,
|
|
15
|
+
)
|
|
16
|
+
from tba_protocol_oidc.standards.userinfo import (
|
|
17
|
+
OWNER as USERINFO_OWNER,
|
|
18
|
+
describe as describe_userinfo,
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
OIDC_CORE_COMPONENTS = (
|
|
22
|
+
"discovery",
|
|
23
|
+
"id_token",
|
|
24
|
+
"userinfo",
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
__all__ = [
|
|
28
|
+
"OIDC_CORE_COMPONENTS",
|
|
29
|
+
"USERINFO_OWNER",
|
|
30
|
+
"describe_userinfo",
|
|
31
|
+
"mint_id_token",
|
|
32
|
+
"oidc_hash",
|
|
33
|
+
"rotate_rsa_jwt_key",
|
|
34
|
+
"verify_id_token",
|
|
35
|
+
]
|