tigrbl-identity-rp 0.4.0.dev2__tar.gz

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.
@@ -0,0 +1,20 @@
1
+ Metadata-Version: 2.4
2
+ Name: tigrbl-identity-rp
3
+ Version: 0.4.0.dev2
4
+ Summary: Relying-party SDK for the Tigrbl identity package suite.
5
+ License-Expression: Apache-2.0
6
+ Requires-Python: >=3.10,<3.15
7
+ Classifier: Programming Language :: Python :: 3
8
+ Classifier: Programming Language :: Python :: 3.10
9
+ Classifier: Programming Language :: Python :: 3.11
10
+ Classifier: Programming Language :: Python :: 3.12
11
+ Classifier: Programming Language :: Python :: 3.13
12
+ Classifier: Programming Language :: Python :: 3.14
13
+ Description-Content-Type: text/markdown
14
+
15
+ # tigrbl-identity-rp
16
+
17
+ Relying-party SDK for the Tigrbl identity package suite.
18
+
19
+ This package uses the independent import root `tigrbl_identity_rp`.
20
+
@@ -0,0 +1,5 @@
1
+ # tigrbl-identity-rp
2
+
3
+ Relying-party SDK for the Tigrbl identity package suite.
4
+
5
+ This package uses the independent import root `tigrbl_identity_rp`.
@@ -0,0 +1,14 @@
1
+ [project]
2
+ name = "tigrbl-identity-rp"
3
+ version = "0.4.0.dev2"
4
+ description = "Relying-party SDK for the Tigrbl identity package suite."
5
+ readme = "README.md"
6
+ requires-python = ">=3.10,<3.15"
7
+ license = "Apache-2.0"
8
+
9
+ [build-system]
10
+ requires = ["poetry-core>=1.0.0"]
11
+ build-backend = "poetry.core.masonry.api"
12
+
13
+ [tool.poetry]
14
+ packages = [{ include = "tigrbl_identity_rp", from = "src" }]
@@ -0,0 +1,5 @@
1
+ """Relying-party SDK for the Tigrbl identity package suite."""
2
+
3
+ from __future__ import annotations
4
+
5
+ __all__: list[str] = []
@@ -0,0 +1,73 @@
1
+ """Compatibility facade for OIDC discovery.
2
+
3
+ When the full runtime stack is importable, this module re-exports the canonical
4
+ router-backed implementation. In dependency-light checkpoint environments, it
5
+ falls back to pure metadata helpers so discovery snapshots and unit tests can be
6
+ exercised without Tigrbl/SQLAlchemy.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ try: # pragma: no cover - exercised when runtime dependencies are installed
12
+ from tigrbl_auth.standards.oidc.discovery import (
13
+ ISSUER,
14
+ JWKS_PATH,
15
+ _build_openid_config,
16
+ _cached_openid_config,
17
+ _settings_signature,
18
+ api,
19
+ include_oidc_discovery,
20
+ refresh_discovery_cache,
21
+ router,
22
+ )
23
+ except Exception: # pragma: no cover - dependency-light fallback
24
+ import json
25
+ from functools import lru_cache
26
+ from typing import Any
27
+
28
+ from tigrbl_auth.config.deployment import resolve_deployment
29
+ from tigrbl_auth.config.settings import settings
30
+ from tigrbl_auth.standards.oidc.discovery_metadata import build_openid_config
31
+ from tigrbl_auth.standards.oauth2.rfc8414_metadata import ISSUER, JWKS_PATH
32
+
33
+ api = None
34
+ router = None
35
+
36
+ def _settings_signature(
37
+ settings_obj: object | None = None,
38
+ *,
39
+ profile: str | None = None,
40
+ flag_overrides: dict[str, Any] | None = None,
41
+ ) -> str:
42
+ deployment = resolve_deployment(settings_obj or settings, profile=profile, flag_overrides=flag_overrides)
43
+ return json.dumps(deployment.to_manifest(), sort_keys=True)
44
+
45
+ def _build_openid_config(
46
+ settings_obj: object | None = None,
47
+ *,
48
+ profile: str | None = None,
49
+ flag_overrides: dict[str, Any] | None = None,
50
+ ) -> dict[str, Any]:
51
+ return build_openid_config(settings_obj or settings, profile=profile, flag_overrides=flag_overrides)
52
+
53
+ @lru_cache(maxsize=8)
54
+ def _cached_openid_config(sig: str) -> dict[str, Any]:
55
+ return _build_openid_config()
56
+
57
+ def refresh_discovery_cache() -> None:
58
+ _cached_openid_config.cache_clear()
59
+
60
+ def include_oidc_discovery(app) -> None:
61
+ return None
62
+
63
+ __all__ = [
64
+ "api",
65
+ "router",
66
+ "JWKS_PATH",
67
+ "ISSUER",
68
+ "include_oidc_discovery",
69
+ "refresh_discovery_cache",
70
+ "_build_openid_config",
71
+ "_cached_openid_config",
72
+ "_settings_signature",
73
+ ]
@@ -0,0 +1,357 @@
1
+ from __future__ import annotations
2
+
3
+ """OpenID Connect RP-Initiated Logout with durable fanout planning and replay protection."""
4
+
5
+ from dataclasses import dataclass
6
+ from datetime import datetime, timezone
7
+ import base64
8
+ import json
9
+ from typing import Any, Final
10
+ from urllib.parse import urlparse
11
+ from uuid import UUID
12
+
13
+ from tigrbl_auth.config.deployment import deployment_from_request, resolve_deployment
14
+ from tigrbl_auth.config.settings import settings
15
+
16
+ try: # dependency-light import path for checkpoint evidence generation
17
+ from tigrbl_auth.framework import HTTPException, status
18
+ except Exception: # pragma: no cover - exercised in dependency-light tests
19
+ class _FallbackStatus:
20
+ HTTP_400_BAD_REQUEST = 400
21
+ HTTP_401_UNAUTHORIZED = 401
22
+ HTTP_404_NOT_FOUND = 404
23
+
24
+ class HTTPException(Exception):
25
+ def __init__(self, status_code: int, detail: Any):
26
+ super().__init__(detail)
27
+ self.status_code = status_code
28
+ self.detail = detail
29
+
30
+ status = _FallbackStatus()
31
+
32
+ STATUS: Final[str] = "rp-initiated-logout-runtime"
33
+
34
+
35
+ @dataclass(frozen=True, slots=True)
36
+ class StandardOwner:
37
+ label: str
38
+ title: str
39
+ runtime_status: str
40
+ public_surface: tuple[str, ...]
41
+ notes: str
42
+
43
+
44
+ @dataclass(frozen=True, slots=True)
45
+ class LogoutRequestContext:
46
+ client_id: UUID | None
47
+ post_logout_redirect_uri: str | None
48
+ id_token_hint_claims: dict[str, Any] | None
49
+
50
+
51
+ OWNER = StandardOwner(
52
+ label="OIDC RP-Initiated Logout",
53
+ title="OpenID Connect RP-Initiated Logout",
54
+ runtime_status=STATUS,
55
+ public_surface=("/logout",),
56
+ notes=(
57
+ "The canonical /logout route validates registered post-logout redirect URIs, validates id_token_hint "
58
+ "claims against issuer/audience/session policy, persists logout fanout plans, and reuses an existing "
59
+ "logout_state record to provide replay-safe idempotence when logout is retried."
60
+ ),
61
+ )
62
+
63
+
64
+ def _persistence():
65
+ from tigrbl_auth.services import persistence as persistence_module
66
+
67
+ return persistence_module
68
+
69
+
70
+ def _frontchannel_builder():
71
+ from tigrbl_auth.standards.oidc.frontchannel_logout import build_frontchannel_descriptor
72
+
73
+ return build_frontchannel_descriptor
74
+
75
+
76
+ def _backchannel_builder():
77
+ from tigrbl_auth.standards.oidc.backchannel_logout import build_backchannel_descriptor
78
+
79
+ return build_backchannel_descriptor
80
+
81
+
82
+ async def _verify_id_token_hint(token: str, *, issuer: str, audience: str):
83
+ from tigrbl_auth.standards.oidc.id_token import verify_id_token
84
+
85
+ return await verify_id_token(token, issuer=issuer, audience=audience)
86
+
87
+
88
+ def _normalized_uris(value: Any) -> list[str]:
89
+ if value is None:
90
+ return []
91
+ if isinstance(value, list):
92
+ return [str(item) for item in value if item]
93
+ if isinstance(value, str):
94
+ return [item for item in value.split() if item]
95
+ return [str(value)]
96
+
97
+
98
+ def _normalize_uuid(value: Any) -> UUID | None:
99
+ if value in {None, '', False}:
100
+ return None
101
+ if isinstance(value, UUID):
102
+ return value
103
+ try:
104
+ return UUID(str(value))
105
+ except Exception:
106
+ return None
107
+
108
+
109
+ def _audiences(claims: dict[str, Any] | None) -> list[str]:
110
+ if not claims:
111
+ return []
112
+ aud = claims.get('aud')
113
+ if aud is None:
114
+ return []
115
+ if isinstance(aud, (list, tuple, set)):
116
+ return [str(item) for item in aud if item not in {None, ''}]
117
+ return [str(aud)] if aud not in {None, ''} else []
118
+
119
+
120
+ def _unsafe_decode_jwt_claims(token: str) -> dict[str, Any]:
121
+ try:
122
+ parts = str(token).split('.')
123
+ if len(parts) != 3:
124
+ return {}
125
+ padded = parts[1] + '=' * (-len(parts[1]) % 4)
126
+ return dict(json.loads(base64.urlsafe_b64decode(padded).decode('utf-8')))
127
+ except Exception:
128
+ return {}
129
+
130
+
131
+ def _require_https_if_present(uri: str) -> None:
132
+ parsed = urlparse(uri)
133
+ if parsed.scheme != 'https':
134
+ raise HTTPException(status.HTTP_400_BAD_REQUEST, 'post_logout_redirect_uri must use https')
135
+
136
+
137
+ def assert_logout_session_active(session_row) -> None:
138
+ if session_row is None:
139
+ return None
140
+ state = str(getattr(session_row, 'session_state', 'active') or 'active').lower()
141
+ if getattr(session_row, 'ended_at', None) is not None or state in {'terminated', 'expired', 'ended', 'revoked'}:
142
+ raise HTTPException(status.HTTP_400_BAD_REQUEST, {'error': 'expired_session'})
143
+
144
+
145
+ async def validate_post_logout_redirect_uri(*, client_id: UUID | None, post_logout_redirect_uri: str | None) -> str | None:
146
+ if not post_logout_redirect_uri:
147
+ return None
148
+ _require_https_if_present(post_logout_redirect_uri)
149
+ if client_id is None:
150
+ raise HTTPException(status.HTTP_400_BAD_REQUEST, {'error': 'invalid_client', 'error_description': 'client_id required when post_logout_redirect_uri is supplied'})
151
+ registration = await _persistence().get_client_registration_async(client_id)
152
+ metadata = dict(getattr(registration, 'registration_metadata', {}) or {})
153
+ allowed = _normalized_uris(metadata.get('post_logout_redirect_uris'))
154
+ if post_logout_redirect_uri not in allowed:
155
+ raise HTTPException(status.HTTP_400_BAD_REQUEST, {'error': 'invalid_request', 'error_description': 'unregistered post_logout_redirect_uri'})
156
+ return post_logout_redirect_uri
157
+
158
+
159
+ async def validate_id_token_hint(
160
+ *,
161
+ id_token_hint: str | None,
162
+ client_id: UUID | str | None = None,
163
+ session_id: UUID | str | None = None,
164
+ issuer: str | None = None,
165
+ ) -> dict[str, Any] | None:
166
+ if not id_token_hint:
167
+ return None
168
+ effective_issuer = issuer or settings.issuer
169
+ effective_client_id = _normalize_uuid(client_id)
170
+ if effective_client_id is None:
171
+ unverified = _unsafe_decode_jwt_claims(id_token_hint)
172
+ for audience in _audiences(unverified):
173
+ parsed = _normalize_uuid(audience)
174
+ if parsed is not None:
175
+ effective_client_id = parsed
176
+ break
177
+ if effective_client_id is None:
178
+ raise HTTPException(status.HTTP_400_BAD_REQUEST, {'error': 'invalid_id_token_hint', 'error_description': 'unable to derive client_id from id_token_hint'})
179
+ try:
180
+ claims = dict(await _verify_id_token_hint(id_token_hint, issuer=effective_issuer, audience=str(effective_client_id)))
181
+ except Exception as exc:
182
+ raise HTTPException(status.HTTP_400_BAD_REQUEST, {'error': 'invalid_id_token_hint'}) from exc
183
+ if str(claims.get('iss') or '') != effective_issuer:
184
+ raise HTTPException(status.HTTP_400_BAD_REQUEST, {'error': 'invalid_id_token_hint', 'error_description': 'issuer mismatch'})
185
+ audiences = _audiences(claims)
186
+ if str(effective_client_id) not in audiences:
187
+ raise HTTPException(status.HTTP_400_BAD_REQUEST, {'error': 'invalid_id_token_hint', 'error_description': 'audience mismatch'})
188
+ expected_session_id = _normalize_uuid(session_id)
189
+ if expected_session_id is not None:
190
+ sid = _normalize_uuid(claims.get('sid'))
191
+ if sid is not None and sid != expected_session_id:
192
+ raise HTTPException(status.HTTP_400_BAD_REQUEST, {'error': 'invalid_id_token_hint', 'error_description': 'sid mismatch'})
193
+ return claims
194
+
195
+
196
+ def resolve_logout_client_id(*, requested_client_id: UUID | str | None, session_row=None, hint_claims: dict[str, Any] | None = None) -> UUID | None:
197
+ requested = _normalize_uuid(requested_client_id)
198
+ session_client = _normalize_uuid(getattr(session_row, 'client_id', None)) if session_row is not None else None
199
+ hint_candidates = {_normalize_uuid(audience) for audience in _audiences(hint_claims)}
200
+ hint_candidates.discard(None)
201
+
202
+ if requested is not None and session_client is not None and requested != session_client:
203
+ raise HTTPException(status.HTTP_400_BAD_REQUEST, {'error': 'invalid_client', 'error_description': 'requested client does not own the session'})
204
+ if requested is not None and hint_candidates and requested not in hint_candidates:
205
+ raise HTTPException(status.HTTP_400_BAD_REQUEST, {'error': 'invalid_client', 'error_description': 'requested client does not match id_token_hint'})
206
+ if session_client is not None and hint_candidates and session_client not in hint_candidates:
207
+ raise HTTPException(status.HTTP_400_BAD_REQUEST, {'error': 'invalid_client', 'error_description': 'session client does not match id_token_hint'})
208
+
209
+ if requested is not None:
210
+ return requested
211
+ if session_client is not None:
212
+ return session_client
213
+ for candidate in hint_candidates:
214
+ return candidate
215
+ return None
216
+
217
+
218
+ async def validate_logout_request(
219
+ *,
220
+ requested_client_id: UUID | str | None,
221
+ post_logout_redirect_uri: str | None,
222
+ id_token_hint: str | None,
223
+ session_row=None,
224
+ issuer: str | None = None,
225
+ ) -> LogoutRequestContext:
226
+ assert_logout_session_active(session_row)
227
+ prevalidated_client_id = _normalize_uuid(requested_client_id) or _normalize_uuid(getattr(session_row, 'client_id', None))
228
+ hint_claims = await validate_id_token_hint(
229
+ id_token_hint=id_token_hint,
230
+ client_id=prevalidated_client_id,
231
+ session_id=getattr(session_row, 'id', None),
232
+ issuer=issuer,
233
+ )
234
+ client_id = resolve_logout_client_id(requested_client_id=requested_client_id, session_row=session_row, hint_claims=hint_claims)
235
+ redirect_uri = await validate_post_logout_redirect_uri(
236
+ client_id=client_id,
237
+ post_logout_redirect_uri=post_logout_redirect_uri,
238
+ )
239
+ return LogoutRequestContext(
240
+ client_id=client_id,
241
+ post_logout_redirect_uri=redirect_uri,
242
+ id_token_hint_claims=hint_claims,
243
+ )
244
+
245
+
246
+ async def build_logout_plan(
247
+ *,
248
+ session_row,
249
+ client_id: UUID | None,
250
+ post_logout_redirect_uri: str | None,
251
+ state: str | None,
252
+ reason: str = 'logout',
253
+ metadata: dict[str, Any] | None = None,
254
+ deployment=None,
255
+ ):
256
+ deployment = deployment if deployment is not None else resolve_deployment(settings)
257
+ persistence = _persistence()
258
+ now = datetime.now(timezone.utc).replace(microsecond=0)
259
+ existing = await persistence.get_latest_logout_for_session_async(session_row.id)
260
+ if existing is not None:
261
+ existing_meta = dict(getattr(existing, 'logout_metadata', {}) or {})
262
+ if post_logout_redirect_uri and 'post_logout_redirect_uri' not in existing_meta:
263
+ existing_meta['post_logout_redirect_uri'] = post_logout_redirect_uri
264
+ if state and 'state' not in existing_meta:
265
+ existing_meta['state'] = state
266
+ existing_meta['replay_count'] = int(existing_meta.get('replay_count', 0)) + 1
267
+ existing_meta['replayed_at'] = now.isoformat()
268
+ if metadata:
269
+ existing_meta.update(metadata)
270
+ if existing_meta != dict(getattr(existing, 'logout_metadata', {}) or {}):
271
+ existing = await persistence.update_logout_metadata_async(existing.id, metadata=existing_meta) or existing
272
+ return existing
273
+
274
+ front_required = bool(client_id and deployment.flag_enabled('enable_oidc_frontchannel_logout'))
275
+ back_required = bool(client_id and deployment.flag_enabled('enable_oidc_backchannel_logout'))
276
+ combined_meta = {
277
+ 'post_logout_redirect_uri': post_logout_redirect_uri,
278
+ 'state': state,
279
+ 'client_id': str(client_id) if client_id is not None else None,
280
+ 'request_validated_at': now.isoformat(),
281
+ 'replay_count': 0,
282
+ 'frontchannel_delivery': {'status': 'pending' if front_required else 'not_configured', 'attempts': 0, 'max_retries': 3},
283
+ 'backchannel_delivery': {'status': 'pending' if back_required else 'not_configured', 'attempts': 0, 'max_retries': 3},
284
+ }
285
+ if metadata:
286
+ combined_meta.update(metadata)
287
+ logout = await persistence.terminate_session_async(
288
+ session_row.id,
289
+ initiated_by='rp_logout',
290
+ reason=reason,
291
+ frontchannel_required=front_required,
292
+ backchannel_required=back_required,
293
+ metadata=combined_meta,
294
+ )
295
+ if logout is None:
296
+ return None
297
+
298
+ frontchannel = None
299
+ backchannel = None
300
+ if client_id is not None:
301
+ frontchannel = await _frontchannel_builder()(
302
+ client_id=client_id,
303
+ sid=str(session_row.id),
304
+ iss=str(deployment.issuer or settings.issuer),
305
+ logout_id=logout.id,
306
+ )
307
+ backchannel = await _backchannel_builder()(
308
+ client_id=client_id,
309
+ sid=str(session_row.id),
310
+ sub=str(session_row.user_id),
311
+ iss=str(deployment.issuer or settings.issuer),
312
+ logout_id=logout.id,
313
+ )
314
+ plan_meta = dict(logout.logout_metadata or {})
315
+ plan_meta.update({
316
+ 'post_logout_redirect_uri': post_logout_redirect_uri,
317
+ 'state': state,
318
+ 'frontchannel': frontchannel,
319
+ 'backchannel': backchannel,
320
+ 'frontchannel_delivery': (frontchannel or {}).get('delivery') if isinstance(frontchannel, dict) else {'status': 'not_configured', 'attempts': 0, 'max_retries': 3},
321
+ 'backchannel_delivery': (backchannel or {}).get('delivery') if isinstance(backchannel, dict) else {'status': 'not_configured', 'attempts': 0, 'max_retries': 3},
322
+ 'idempotent_replay_protection': True,
323
+ 'replay_count': 0,
324
+ })
325
+ return await persistence.update_logout_metadata_async(logout.id, metadata=plan_meta) or logout
326
+
327
+
328
+ def describe(*, request=None, deployment=None) -> dict[str, object]:
329
+ if deployment is None and request is not None:
330
+ deployment = deployment_from_request(request, settings)
331
+ return {
332
+ 'label': OWNER.label,
333
+ 'title': OWNER.title,
334
+ 'runtime_status': OWNER.runtime_status,
335
+ 'public_surface': list(OWNER.public_surface),
336
+ 'id_token_hint_validation_supported': True,
337
+ 'post_logout_redirect_uri_validation_supported': True,
338
+ 'idempotent_replay_protection': True,
339
+ 'frontchannel_logout_supported': bool(getattr(deployment, "flag_enabled", lambda *_: True)("enable_oidc_frontchannel_logout")) if deployment is not None else True,
340
+ 'backchannel_logout_supported': bool(getattr(deployment, "flag_enabled", lambda *_: True)("enable_oidc_backchannel_logout")) if deployment is not None else True,
341
+ 'notes': OWNER.notes,
342
+ }
343
+
344
+
345
+ __all__ = [
346
+ 'STATUS',
347
+ 'LogoutRequestContext',
348
+ 'StandardOwner',
349
+ 'OWNER',
350
+ 'assert_logout_session_active',
351
+ 'build_logout_plan',
352
+ 'describe',
353
+ 'resolve_logout_client_id',
354
+ 'validate_id_token_hint',
355
+ 'validate_logout_request',
356
+ 'validate_post_logout_redirect_uri',
357
+ ]
@@ -0,0 +1,124 @@
1
+ """UserInfo endpoint for OpenID Connect 1.0.
2
+
3
+ This module implements the `/userinfo` endpoint as described in the
4
+ OpenID Connect Core specification. It is **not** tied to an RFC so it
5
+ lives in the OIDC namespace instead of an `rfcXXXX` module.
6
+
7
+ The endpoint returns a set of claims about the authenticated user based
8
+ on the scopes granted to the access token. Unrequested claim groups are
9
+ omitted from the response.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import inspect
15
+
16
+ from tigrbl_auth.framework import (
17
+ TigrblRouter,
18
+ TigrblApp,
19
+ HTTPException,
20
+ Request,
21
+ Response,
22
+ status,
23
+ )
24
+
25
+ from tigrbl_auth.security import auth as security_auth
26
+ from tigrbl_auth.security import deps as security_deps
27
+ from tigrbl_auth.services.token_service import JWTCoder, InvalidTokenError, _svc
28
+ from tigrbl_auth.tables import User
29
+ from tigrbl_auth.standards.oauth2.rfc6750 import extract_bearer_token
30
+ from tigrbl_auth.framework import JWAAlg
31
+
32
+ api = TigrblRouter()
33
+ router = api
34
+
35
+
36
+ async def _resolve_current_user(request: Request) -> User:
37
+ """Resolve the current principal, honoring app/router dependency overrides."""
38
+
39
+ app = getattr(request, "app", None)
40
+ router = getattr(app, "router", None)
41
+ overrides = dict(getattr(app, "dependency_overrides", {}) or {})
42
+ router_overrides = getattr(router, "dependency_overrides", {})
43
+ if router_overrides:
44
+ overrides.update(router_overrides)
45
+
46
+ for dependency in (
47
+ security_deps.get_current_principal,
48
+ security_auth.get_current_principal,
49
+ ):
50
+ override = overrides.get(dependency)
51
+ if override is None:
52
+ continue
53
+ try:
54
+ resolved = override(request)
55
+ except TypeError:
56
+ resolved = override()
57
+ return await resolved if inspect.isawaitable(resolved) else resolved
58
+
59
+ return await security_deps.get_current_principal(request)
60
+
61
+
62
+ @api.route("/userinfo", methods=["GET"], response_model=None)
63
+ async def userinfo(request: Request) -> Response | dict[str, str]:
64
+ """Return claims about the authenticated user.
65
+
66
+ The caller must present a valid access token in the ``Authorization``
67
+ header. Returned claims are filtered based on scopes granted in that
68
+ token. If the request ``Accept`` header includes ``application/jwt`` the
69
+ response will be JWS signed.
70
+ """
71
+
72
+ token = await extract_bearer_token(
73
+ request,
74
+ request.headers.get("Authorization")
75
+ or request.headers.get("authorization", ""),
76
+ )
77
+ if not token:
78
+ raise HTTPException(status.HTTP_401_UNAUTHORIZED, "missing access token")
79
+ try:
80
+ payload = await JWTCoder.default().async_decode(token)
81
+ except InvalidTokenError as exc:
82
+ raise HTTPException(
83
+ status.HTTP_401_UNAUTHORIZED, "invalid access token"
84
+ ) from exc
85
+ scopes: set[str] = set(payload.get("scope", "").split())
86
+ user = await _resolve_current_user(request)
87
+
88
+ claims: dict[str, str] = {"sub": str(user.id)}
89
+ if "profile" in scopes:
90
+ claims["name"] = user.username
91
+ if "email" in scopes:
92
+ claims["email"] = user.email
93
+ if "address" in scopes and getattr(user, "address", None):
94
+ claims["address"] = getattr(user, "address")
95
+ if "phone" in scopes and getattr(user, "phone", None):
96
+ claims["phone_number"] = getattr(user, "phone")
97
+
98
+ if "application/jwt" in (
99
+ request.headers.get("Accept") or request.headers.get("accept", "")
100
+ ):
101
+ svc, kid = _svc()
102
+ token = await svc.mint(claims, alg=JWAAlg.EDDSA, kid=kid)
103
+ return Response(body=str(token).encode("utf-8"), headers={"content-type": "application/jwt"}, media_type="application/jwt")
104
+
105
+ return claims
106
+
107
+
108
+ # ---------------------------------------------------------------------------
109
+ # Tigrbl integration
110
+ # ---------------------------------------------------------------------------
111
+
112
+
113
+ def include_oidc_userinfo(app: TigrblApp) -> None:
114
+ """Attach the UserInfo endpoint to *app* if not already present."""
115
+
116
+ if not any(
117
+ (getattr(route, "path", None) or getattr(route, "path_template", None))
118
+ == "/userinfo"
119
+ for route in app.router.routes
120
+ ):
121
+ app.include_router(api)
122
+
123
+
124
+ __all__ = ["api", "router", "include_oidc_userinfo"]