tigrbl-identity-oauth 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.
Files changed (57) hide show
  1. tigrbl_identity_oauth-0.4.0.dev2/PKG-INFO +20 -0
  2. tigrbl_identity_oauth-0.4.0.dev2/README.md +5 -0
  3. tigrbl_identity_oauth-0.4.0.dev2/pyproject.toml +14 -0
  4. tigrbl_identity_oauth-0.4.0.dev2/src/tigrbl_identity_oauth/__init__.py +5 -0
  5. tigrbl_identity_oauth-0.4.0.dev2/src/tigrbl_identity_oauth/ops/__init__.py +8 -0
  6. tigrbl_identity_oauth-0.4.0.dev2/src/tigrbl_identity_oauth/ops/authorize.py +328 -0
  7. tigrbl_identity_oauth-0.4.0.dev2/src/tigrbl_identity_oauth/ops/device_authorization.py +148 -0
  8. tigrbl_identity_oauth-0.4.0.dev2/src/tigrbl_identity_oauth/ops/par.py +278 -0
  9. tigrbl_identity_oauth-0.4.0.dev2/src/tigrbl_identity_oauth/ops/register.py +439 -0
  10. tigrbl_identity_oauth-0.4.0.dev2/src/tigrbl_identity_oauth/ops/revoke.py +27 -0
  11. tigrbl_identity_oauth-0.4.0.dev2/src/tigrbl_identity_oauth/ops/token.py +663 -0
  12. tigrbl_identity_oauth-0.4.0.dev2/src/tigrbl_identity_oauth/standards/__init__.py +9 -0
  13. tigrbl_identity_oauth-0.4.0.dev2/src/tigrbl_identity_oauth/standards/assertion_framework.py +187 -0
  14. tigrbl_identity_oauth-0.4.0.dev2/src/tigrbl_identity_oauth/standards/client_registration_management.py +41 -0
  15. tigrbl_identity_oauth-0.4.0.dev2/src/tigrbl_identity_oauth/standards/device_authorization.py +214 -0
  16. tigrbl_identity_oauth-0.4.0.dev2/src/tigrbl_identity_oauth/standards/dpop.py +602 -0
  17. tigrbl_identity_oauth-0.4.0.dev2/src/tigrbl_identity_oauth/standards/dynamic_client_registration.py +41 -0
  18. tigrbl_identity_oauth-0.4.0.dev2/src/tigrbl_identity_oauth/standards/introspection.py +347 -0
  19. tigrbl_identity_oauth-0.4.0.dev2/src/tigrbl_identity_oauth/standards/issuer_identification.py +127 -0
  20. tigrbl_identity_oauth-0.4.0.dev2/src/tigrbl_identity_oauth/standards/jar.py +389 -0
  21. tigrbl_identity_oauth-0.4.0.dev2/src/tigrbl_identity_oauth/standards/jwt_access_tokens.py +36 -0
  22. tigrbl_identity_oauth-0.4.0.dev2/src/tigrbl_identity_oauth/standards/jwt_client_auth.py +213 -0
  23. tigrbl_identity_oauth-0.4.0.dev2/src/tigrbl_identity_oauth/standards/mtls.py +293 -0
  24. tigrbl_identity_oauth-0.4.0.dev2/src/tigrbl_identity_oauth/standards/native_apps.py +138 -0
  25. tigrbl_identity_oauth-0.4.0.dev2/src/tigrbl_identity_oauth/standards/par.py +152 -0
  26. tigrbl_identity_oauth-0.4.0.dev2/src/tigrbl_identity_oauth/standards/rar.py +211 -0
  27. tigrbl_identity_oauth-0.4.0.dev2/src/tigrbl_identity_oauth/standards/resource_indicators.py +134 -0
  28. tigrbl_identity_oauth-0.4.0.dev2/src/tigrbl_identity_oauth/standards/resource_verifier_contract.py +87 -0
  29. tigrbl_identity_oauth-0.4.0.dev2/src/tigrbl_identity_oauth/standards/revocation.py +93 -0
  30. tigrbl_identity_oauth-0.4.0.dev2/src/tigrbl_identity_oauth/standards/rfc6749.py +100 -0
  31. tigrbl_identity_oauth-0.4.0.dev2/src/tigrbl_identity_oauth/standards/rfc6749_token.py +5 -0
  32. tigrbl_identity_oauth-0.4.0.dev2/src/tigrbl_identity_oauth/standards/rfc6750.py +82 -0
  33. tigrbl_identity_oauth-0.4.0.dev2/src/tigrbl_identity_oauth/standards/rfc7009.py +25 -0
  34. tigrbl_identity_oauth-0.4.0.dev2/src/tigrbl_identity_oauth/standards/rfc7521.py +33 -0
  35. tigrbl_identity_oauth-0.4.0.dev2/src/tigrbl_identity_oauth/standards/rfc7523.py +43 -0
  36. tigrbl_identity_oauth-0.4.0.dev2/src/tigrbl_identity_oauth/standards/rfc7591.py +11 -0
  37. tigrbl_identity_oauth-0.4.0.dev2/src/tigrbl_identity_oauth/standards/rfc7592.py +11 -0
  38. tigrbl_identity_oauth-0.4.0.dev2/src/tigrbl_identity_oauth/standards/rfc7636_pkce.py +107 -0
  39. tigrbl_identity_oauth-0.4.0.dev2/src/tigrbl_identity_oauth/standards/rfc7662.py +27 -0
  40. tigrbl_identity_oauth-0.4.0.dev2/src/tigrbl_identity_oauth/standards/rfc7662_introspection.py +27 -0
  41. tigrbl_identity_oauth-0.4.0.dev2/src/tigrbl_identity_oauth/standards/rfc8252.py +23 -0
  42. tigrbl_identity_oauth-0.4.0.dev2/src/tigrbl_identity_oauth/standards/rfc8414.py +36 -0
  43. tigrbl_identity_oauth-0.4.0.dev2/src/tigrbl_identity_oauth/standards/rfc8414_metadata.py +15 -0
  44. tigrbl_identity_oauth-0.4.0.dev2/src/tigrbl_identity_oauth/standards/rfc8523.py +107 -0
  45. tigrbl_identity_oauth-0.4.0.dev2/src/tigrbl_identity_oauth/standards/rfc8628.py +98 -0
  46. tigrbl_identity_oauth-0.4.0.dev2/src/tigrbl_identity_oauth/standards/rfc8693.py +36 -0
  47. tigrbl_identity_oauth-0.4.0.dev2/src/tigrbl_identity_oauth/standards/rfc8705.py +31 -0
  48. tigrbl_identity_oauth-0.4.0.dev2/src/tigrbl_identity_oauth/standards/rfc8707.py +12 -0
  49. tigrbl_identity_oauth-0.4.0.dev2/src/tigrbl_identity_oauth/standards/rfc9068.py +18 -0
  50. tigrbl_identity_oauth-0.4.0.dev2/src/tigrbl_identity_oauth/standards/rfc9101.py +25 -0
  51. tigrbl_identity_oauth-0.4.0.dev2/src/tigrbl_identity_oauth/standards/rfc9126.py +11 -0
  52. tigrbl_identity_oauth-0.4.0.dev2/src/tigrbl_identity_oauth/standards/rfc9207.py +12 -0
  53. tigrbl_identity_oauth-0.4.0.dev2/src/tigrbl_identity_oauth/standards/rfc9396.py +21 -0
  54. tigrbl_identity_oauth-0.4.0.dev2/src/tigrbl_identity_oauth/standards/rfc9449_dpop.py +34 -0
  55. tigrbl_identity_oauth-0.4.0.dev2/src/tigrbl_identity_oauth/standards/rfc9700.py +482 -0
  56. tigrbl_identity_oauth-0.4.0.dev2/src/tigrbl_identity_oauth/standards/rfc9728.py +72 -0
  57. tigrbl_identity_oauth-0.4.0.dev2/src/tigrbl_identity_oauth/standards/token_exchange.py +359 -0
@@ -0,0 +1,20 @@
1
+ Metadata-Version: 2.4
2
+ Name: tigrbl-identity-oauth
3
+ Version: 0.4.0.dev2
4
+ Summary: OAuth protocol surfaces 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-oauth
16
+
17
+ OAuth protocol surfaces for the Tigrbl identity package suite.
18
+
19
+ This package uses the independent import root `tigrbl_identity_oauth`.
20
+
@@ -0,0 +1,5 @@
1
+ # tigrbl-identity-oauth
2
+
3
+ OAuth protocol surfaces for the Tigrbl identity package suite.
4
+
5
+ This package uses the independent import root `tigrbl_identity_oauth`.
@@ -0,0 +1,14 @@
1
+ [project]
2
+ name = "tigrbl-identity-oauth"
3
+ version = "0.4.0.dev2"
4
+ description = "OAuth protocol surfaces 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_oauth", from = "src" }]
@@ -0,0 +1,5 @@
1
+ """OAuth protocol surfaces for the Tigrbl identity package suite."""
2
+
3
+ from __future__ import annotations
4
+
5
+ __all__: list[str] = []
@@ -0,0 +1,8 @@
1
+ """Operation modules.
2
+
3
+ The package keeps this namespace import-light so targeted standards tests and
4
+ checkpoint tooling can import individual operation modules without pulling in
5
+ the entire runtime stack as a side effect.
6
+ """
7
+
8
+ __all__: list[str] = []
@@ -0,0 +1,328 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ from datetime import datetime, timedelta, timezone
5
+ from typing import Any
6
+ from urllib.parse import urlencode
7
+ from uuid import UUID, uuid4
8
+
9
+ from tigrbl_auth.framework import HTMLResponse, HTTPException, RedirectResponse, select, status
10
+ from tigrbl_auth.api.rest.shared import _jwt, _require_tls
11
+ from tigrbl_auth.config.deployment import deployment_from_request
12
+ from tigrbl_auth.config.deployment import resolve_deployment
13
+ from tigrbl_auth.config.settings import settings
14
+ from tigrbl_auth.standards.http.cookies import issue_session_cookie
15
+ from tigrbl_auth.oidc_id_token import mint_id_token, oidc_hash
16
+ from tigrbl_auth.standards.oidc.session_mgmt import (
17
+ bind_browser_session_client,
18
+ maybe_rotate_browser_session_cookie,
19
+ resolve_browser_session,
20
+ session_state_for_client,
21
+ )
22
+ from tigrbl_auth.standards.oauth2.native_apps import validate_native_authorization_request
23
+ from tigrbl_auth.standards.oauth2.jar import merge_request_object_params, parse_request_object
24
+ from tigrbl_auth.standards.oauth2.par import RFC9126_SPEC_URL, consume_pushed_authorization_request, validate_pushed_authorization_request_row
25
+ from tigrbl_auth.standards.oauth2.rar import normalize_authorization_details
26
+ from tigrbl_auth.standards.oauth2.resource_indicators import extract_resource
27
+ from tigrbl_auth.standards.oauth2.issuer_identification import authorization_response_issuer
28
+ from tigrbl_auth.standards.oauth2.rfc8414_metadata import ISSUER
29
+ from tigrbl_auth.standards.oauth2.rfc9700 import (
30
+ OAuthPolicyViolation,
31
+ assert_authorization_request_allowed,
32
+ runtime_security_profile,
33
+ )
34
+ from tigrbl_auth.tables import AuthCode, Client, PushedAuthorizationRequest, User
35
+
36
+
37
+ def _coerce_multi_value(value: Any) -> list[str]:
38
+ if value is None:
39
+ return []
40
+ if isinstance(value, (list, tuple, set)):
41
+ return [str(item) for item in value if str(item)]
42
+ return [str(value)] if str(value) else []
43
+
44
+
45
+ async def _resolve_pushed_authorization_request(db, params: dict[str, Any]) -> tuple[dict[str, Any], PushedAuthorizationRequest | None]:
46
+ request_uri = params.get("request_uri")
47
+ if not request_uri:
48
+ return params, None
49
+ row = await db.scalar(select(PushedAuthorizationRequest).where(PushedAuthorizationRequest.request_uri == str(request_uri)))
50
+ if row is None:
51
+ raise HTTPException(status.HTTP_400_BAD_REQUEST, {"error": "invalid_request_uri", "error_description": RFC9126_SPEC_URL})
52
+ try:
53
+ result = validate_pushed_authorization_request_row(
54
+ row,
55
+ client_id=str(params.get("client_id") or '') or None,
56
+ request_uri=str(request_uri),
57
+ )
58
+ except Exception as exc:
59
+ raise HTTPException(status.HTTP_400_BAD_REQUEST, {"error": "invalid_request_uri", "error_description": RFC9126_SPEC_URL}) from exc
60
+
61
+ merged = dict(result.params or {})
62
+ for key, value in params.items():
63
+ if value in (None, "", [], (), {}):
64
+ continue
65
+ if key not in {"request_uri", "client_id"}:
66
+ raise HTTPException(status.HTTP_400_BAD_REQUEST, {"error": "invalid_request", "error_description": RFC9126_SPEC_URL})
67
+ existing = merged.get(key)
68
+ if existing not in (None, "", [], (), {}) and existing != value:
69
+ raise HTTPException(status.HTTP_400_BAD_REQUEST, {"error": "invalid_request_uri", "error_description": RFC9126_SPEC_URL})
70
+ merged[key] = value
71
+ return merged, row
72
+
73
+
74
+ async def _resolve_request_object(params: dict[str, Any], deployment) -> dict[str, Any]:
75
+ request_object = params.get("request")
76
+ if not request_object:
77
+ return params
78
+ if not deployment.flag_enabled("enable_rfc9101"):
79
+ raise HTTPException(status.HTTP_400_BAD_REQUEST, {"error": "invalid_request_object"})
80
+ try:
81
+ parsed = await parse_request_object(
82
+ str(request_object),
83
+ secret=settings.jwt_secret,
84
+ algorithms=("HS256", "HS384", "HS512"),
85
+ expected_client_id=str(params.get("client_id") or '') or None,
86
+ expected_audience=str(deployment.issuer or ISSUER),
87
+ )
88
+ merged = merge_request_object_params(parsed, params)
89
+ except Exception as exc:
90
+ raise HTTPException(status.HTTP_400_BAD_REQUEST, {"error": "invalid_request_object"}) from exc
91
+ return merged
92
+
93
+
94
+ async def authorize_request(*, request, db, params: dict[str, Any]):
95
+ deployment = deployment_from_request(request, settings)
96
+ _require_tls(request, deployment=deployment)
97
+ policy = runtime_security_profile(deployment)
98
+
99
+ params = dict(params)
100
+ params["_frontchannel_request"] = True
101
+ params, par_row = await _resolve_pushed_authorization_request(db, params)
102
+ params = await _resolve_request_object(params, deployment)
103
+
104
+ try:
105
+ assert_authorization_request_allowed(params, deployment)
106
+ except OAuthPolicyViolation as exc:
107
+ raise HTTPException(exc.status_code, {"error": exc.error, "error_description": exc.description}) from exc
108
+
109
+ response_type = params.get("response_type")
110
+ client_id = params.get("client_id")
111
+ redirect_uri = params.get("redirect_uri")
112
+ scope = params.get("scope")
113
+ if not all((response_type, client_id, redirect_uri, scope)):
114
+ raise HTTPException(status.HTTP_400_BAD_REQUEST, {"error": "invalid_request"})
115
+
116
+ response_mode = params.get("response_mode")
117
+ state = params.get("state")
118
+ nonce = params.get("nonce")
119
+ code_challenge = params.get("code_challenge")
120
+ code_challenge_method = params.get("code_challenge_method")
121
+ prompt = params.get("prompt")
122
+ max_age = params.get("max_age")
123
+ login_hint = params.get("login_hint")
124
+ claims = params.get("claims")
125
+ authorization_details = params.get("authorization_details")
126
+ resources = _coerce_multi_value(params.get("resource"))
127
+
128
+ if max_age is not None:
129
+ try:
130
+ max_age = int(max_age)
131
+ except (TypeError, ValueError) as exc:
132
+ raise HTTPException(status.HTTP_400_BAD_REQUEST, {"error": "invalid_request"}) from exc
133
+ if max_age < 0:
134
+ raise HTTPException(status.HTTP_400_BAD_REQUEST, {"error": "invalid_request"})
135
+
136
+ rts = set(str(response_type).split())
137
+ allowed = {"code", "token", "id_token"}
138
+ if not rts or not rts.issubset(allowed):
139
+ raise HTTPException(status.HTTP_400_BAD_REQUEST, {"error": "unsupported_response_type"})
140
+
141
+ scopes = set(str(scope).split())
142
+ if "openid" not in scopes:
143
+ raise HTTPException(status.HTTP_400_BAD_REQUEST, {"error": "invalid_scope"})
144
+ if "id_token" in rts and not nonce:
145
+ raise HTTPException(status.HTTP_400_BAD_REQUEST, {"error": "invalid_request"})
146
+
147
+ try:
148
+ client_uuid = UUID(str(client_id))
149
+ except ValueError as exc:
150
+ raise HTTPException(status.HTTP_400_BAD_REQUEST, {"error": "invalid_request"}) from exc
151
+
152
+ client = await db.scalar(select(Client).where(Client.id == client_uuid))
153
+ if client is None or redirect_uri not in (client.redirect_uris or "").split():
154
+ raise HTTPException(status.HTTP_400_BAD_REQUEST, {"error": "invalid_request"})
155
+
156
+ if par_row is not None and par_row.client_id not in {None, client_uuid}:
157
+ raise HTTPException(status.HTTP_400_BAD_REQUEST, {"error": "invalid_request_uri"})
158
+
159
+ session = await resolve_browser_session(request, deployment=deployment)
160
+ if login_hint and session and session.username != login_hint:
161
+ session = None
162
+ prompts = set(str(prompt).split()) if prompt else set()
163
+ if "login" in prompts:
164
+ session = None
165
+ if session is None:
166
+ raise HTTPException(status.HTTP_401_UNAUTHORIZED, {"error": "login_required"})
167
+ if max_age is not None:
168
+ auth_time = session.auth_time
169
+ if auth_time is not None and auth_time.tzinfo is None:
170
+ auth_time = auth_time.replace(tzinfo=timezone.utc)
171
+ if auth_time is None or datetime.now(timezone.utc) - auth_time > timedelta(seconds=max_age):
172
+ raise HTTPException(status.HTTP_401_UNAUTHORIZED, {"error": "login_required"})
173
+
174
+ try:
175
+ validate_native_authorization_request(
176
+ redirect_uri=str(redirect_uri),
177
+ response_type=str(response_type),
178
+ code_challenge=code_challenge,
179
+ code_challenge_method=code_challenge_method,
180
+ )
181
+ except ValueError as exc:
182
+ raise HTTPException(status.HTTP_400_BAD_REQUEST, {"error": "invalid_request", "error_description": str(exc)}) from exc
183
+ if code_challenge_method and code_challenge_method != "S256":
184
+ raise HTTPException(status.HTTP_400_BAD_REQUEST, {"error": "invalid_request"})
185
+ if policy.pkce_s256_required and (not code_challenge or code_challenge_method != "S256"):
186
+ raise HTTPException(
187
+ status.HTTP_400_BAD_REQUEST,
188
+ {"error": "invalid_request", "error_description": "FAPI authorization requests require PKCE S256"},
189
+ )
190
+
191
+ mode = response_mode or ("fragment" if rts & {"token", "id_token"} else "query")
192
+ if mode not in {"query", "fragment", "form_post"}:
193
+ raise HTTPException(status.HTTP_400_BAD_REQUEST, {"error": "unsupported_response_mode"})
194
+
195
+ requested_claims: dict[str, Any] | None = None
196
+ if claims:
197
+ try:
198
+ if isinstance(claims, dict):
199
+ parsed = claims
200
+ else:
201
+ parsed = json.loads(str(claims))
202
+ if not isinstance(parsed, dict):
203
+ raise ValueError
204
+ requested_claims = parsed
205
+ except Exception as exc:
206
+ raise HTTPException(status.HTTP_400_BAD_REQUEST, {"error": "invalid_request"}) from exc
207
+
208
+ resource_audience: str | None = None
209
+ if resources:
210
+ try:
211
+ resource_audience = extract_resource(resources)
212
+ except ValueError as exc:
213
+ raise HTTPException(status.HTTP_400_BAD_REQUEST, {"error": "invalid_target"}) from exc
214
+
215
+ parsed_authorization_details: list[dict[str, Any]] | None = None
216
+ if authorization_details:
217
+ if not deployment.flag_enabled("enable_rfc9396"):
218
+ raise HTTPException(status.HTTP_400_BAD_REQUEST, {"error": "invalid_request"})
219
+ try:
220
+ binding = normalize_authorization_details(
221
+ authorization_details,
222
+ resource=resource_audience,
223
+ audience=resource_audience,
224
+ )
225
+ parsed_authorization_details = binding.details
226
+ if resource_audience is None and binding.audience is not None:
227
+ resource_audience = binding.audience
228
+ except ValueError as exc:
229
+ raise HTTPException(status.HTTP_400_BAD_REQUEST, {"error": "invalid_request"}) from exc
230
+
231
+ await bind_browser_session_client(session.id, client_id=client_uuid)
232
+ user_sub = str(session.user_id)
233
+ tenant_id = str(session.tenant_id)
234
+ scope_str = " ".join(sorted(scopes))
235
+ params_out: list[tuple[str, str]] = []
236
+ code: str | None = None
237
+ access: str | None = None
238
+
239
+ auth_code_claims: dict[str, Any] | None = dict(requested_claims or {})
240
+ if resource_audience is not None:
241
+ auth_code_claims["_resource"] = resource_audience
242
+ if parsed_authorization_details is not None:
243
+ auth_code_claims["_authorization_details"] = parsed_authorization_details
244
+ if params.get("_dpop_jkt"):
245
+ auth_code_claims["_dpop_jkt"] = str(params["_dpop_jkt"])
246
+ if params.get("_mtls_thumbprint"):
247
+ auth_code_claims["_mtls_thumbprint"] = str(params["_mtls_thumbprint"])
248
+
249
+ if "code" in rts:
250
+ code_uuid = uuid4()
251
+ code_row = AuthCode(
252
+ id=code_uuid,
253
+ user_id=UUID(user_sub),
254
+ tenant_id=UUID(tenant_id),
255
+ client_id=client_uuid,
256
+ session_id=session.id,
257
+ redirect_uri=str(redirect_uri),
258
+ code_challenge=code_challenge,
259
+ nonce=nonce,
260
+ scope=scope_str,
261
+ expires_at=datetime.now(timezone.utc) + timedelta(minutes=10),
262
+ claims=auth_code_claims or None,
263
+ )
264
+ db.add(code_row)
265
+ await db.commit()
266
+ code = str(code_uuid)
267
+ params_out.append(("code", code))
268
+
269
+ if "token" in rts:
270
+ jwt_kwargs: dict[str, Any] = {"scope": scope_str}
271
+ if resource_audience is not None:
272
+ jwt_kwargs["audience"] = resource_audience
273
+ access = await _jwt.async_sign(sub=user_sub, tid=tenant_id, **jwt_kwargs)
274
+ params_out.append(("access_token", access))
275
+ params_out.append(("token_type", "bearer"))
276
+
277
+ if "id_token" in rts:
278
+ extra_claims: dict[str, Any] = {
279
+ "tid": tenant_id,
280
+ "typ": "id",
281
+ "sid": str(session.id),
282
+ "auth_time": int(session.auth_time.timestamp()),
283
+ }
284
+ if requested_claims and "id_token" in requested_claims:
285
+ user_obj = await db.scalar(select(User).where(User.id == UUID(user_sub)))
286
+ idc = requested_claims["id_token"]
287
+ if "email" in idc:
288
+ extra_claims["email"] = user_obj.email if user_obj else ""
289
+ if any(k in idc for k in ("name", "preferred_username")):
290
+ extra_claims["name"] = session.username
291
+ if access:
292
+ extra_claims["at_hash"] = oidc_hash(access)
293
+ if code:
294
+ extra_claims["c_hash"] = oidc_hash(code)
295
+ id_token = await mint_id_token(sub=user_sub, aud=str(client_id), nonce=nonce, issuer=str(deployment.issuer or ISSUER), **extra_claims)
296
+ params_out.append(("id_token", id_token))
297
+
298
+ session_state = session_state_for_client(
299
+ session,
300
+ client_id=str(client_id),
301
+ redirect_uri=str(redirect_uri),
302
+ deployment=deployment,
303
+ )
304
+ if session_state:
305
+ params_out.append(("session_state", session_state))
306
+ if policy.authorization_response_iss_required:
307
+ params_out.append(authorization_response_issuer(str(deployment.issuer or ISSUER)))
308
+ if state:
309
+ params_out.append(("state", str(state)))
310
+
311
+ if par_row is not None and getattr(par_row, "consumed_at", None) is None:
312
+ consume_pushed_authorization_request(par_row)
313
+ await db.commit()
314
+
315
+ rotated_secret = await maybe_rotate_browser_session_cookie(session)
316
+
317
+ if mode == "fragment":
318
+ response = RedirectResponse(f"{redirect_uri}#{urlencode(params_out)}" if params_out else redirect_uri)
319
+ elif mode == "form_post":
320
+ inputs = "".join(f'<input type="hidden" name="{k}" value="{v}" />' for k, v in params_out)
321
+ body = "<!DOCTYPE html><html><body>" + f'<form method="post" action="{redirect_uri}">{inputs}</form>' + "<script>document.forms[0].submit()</script></body></html>"
322
+ response = HTMLResponse(content=body)
323
+ else:
324
+ response = RedirectResponse(f"{redirect_uri}?{urlencode(params_out)}" if params_out else redirect_uri)
325
+
326
+ if rotated_secret:
327
+ issue_session_cookie(response, session_id=session.id, secret=rotated_secret, expires_at=session.expires_at)
328
+ return response
@@ -0,0 +1,148 @@
1
+ from __future__ import annotations
2
+
3
+ from datetime import datetime, timedelta, timezone
4
+ from typing import Any
5
+ from urllib.parse import parse_qs
6
+ from uuid import UUID
7
+
8
+ from tigrbl_auth.config.deployment import deployment_from_request
9
+ from tigrbl_auth.config.settings import settings
10
+
11
+ try: # pragma: no cover - exercised with full runtime deps installed
12
+ from tigrbl_auth.framework import HTTPException, select, status
13
+ except Exception: # pragma: no cover - dependency-light fallback
14
+ class _FallbackStatus:
15
+ HTTP_400_BAD_REQUEST = 400
16
+ HTTP_404_NOT_FOUND = 404
17
+
18
+ class HTTPException(Exception):
19
+ def __init__(self, status_code: int, detail: Any):
20
+ super().__init__(detail)
21
+ self.status_code = status_code
22
+ self.detail = detail
23
+
24
+ class _Select:
25
+ def __init__(self, model: Any):
26
+ self.model = model
27
+ self.criteria: list[Any] = []
28
+
29
+ def where(self, criterion: Any):
30
+ self.criteria.append(criterion)
31
+ return self
32
+
33
+ def select(model: Any):
34
+ return _Select(model)
35
+
36
+ status = _FallbackStatus()
37
+
38
+ from tigrbl_auth.standards.oauth2.device_authorization import (
39
+ DEVICE_CODE_EXPIRES_IN,
40
+ DEVICE_CODE_INTERVAL,
41
+ generate_device_code,
42
+ generate_user_code,
43
+ )
44
+ from tigrbl_auth.standards.oauth2.resource_indicators import select_resource_indicator
45
+
46
+ try: # pragma: no cover
47
+ from tigrbl_auth.services.persistence import append_audit_event_async
48
+ except Exception: # pragma: no cover - dependency-light fallback
49
+ async def append_audit_event_async(**kwargs):
50
+ return None
51
+
52
+ try: # pragma: no cover
53
+ from tigrbl_auth.tables import Client, DeviceCode
54
+ except Exception: # pragma: no cover - placeholders for dependency-light tests
55
+ class Client: # type: ignore[override]
56
+ id = object()
57
+
58
+ class DeviceCode: # type: ignore[override]
59
+ def __init__(self, **kwargs):
60
+ for key, value in kwargs.items():
61
+ setattr(self, key, value)
62
+ self.id = kwargs.get('id') or kwargs.get('device_code')
63
+
64
+
65
+ async def device_authorization_request(*, request, db):
66
+ deployment = deployment_from_request(request, settings)
67
+ if not deployment.flag_enabled('enable_rfc8628'):
68
+ raise HTTPException(status.HTTP_404_NOT_FOUND, 'device authorization disabled')
69
+ body = getattr(request, 'body', b'') or b''
70
+ form_data = parse_qs(body.decode('utf-8'), keep_blank_values=True)
71
+ client_id = (form_data.get('client_id') or [None])[0]
72
+ scope = (form_data.get('scope') or [None])[0]
73
+ audience = (form_data.get('audience') or [None])[0]
74
+ resources = [item for item in form_data.get('resource', []) if item]
75
+
76
+ if not client_id:
77
+ raise HTTPException(status.HTTP_400_BAD_REQUEST, 'client_id parameter required')
78
+ try:
79
+ client_uuid = UUID(str(client_id))
80
+ except Exception as exc:
81
+ raise HTTPException(status.HTTP_400_BAD_REQUEST, 'invalid client_id') from exc
82
+ client = await db.scalar(select(Client).where(Client.id == client_uuid))
83
+ if client is None:
84
+ raise HTTPException(status.HTTP_404_NOT_FOUND, 'client not found')
85
+
86
+ selection = None
87
+ if resources:
88
+ if not deployment.flag_enabled('enable_rfc8707'):
89
+ raise HTTPException(status.HTTP_400_BAD_REQUEST, 'resource indicators disabled')
90
+ try:
91
+ selection = select_resource_indicator(resources, audience=audience)
92
+ except ValueError as exc:
93
+ raise HTTPException(status.HTTP_400_BAD_REQUEST, 'invalid_target') from exc
94
+ effective_resource = selection.resource if selection is not None else None
95
+ effective_audience = selection.audience if selection is not None else audience
96
+
97
+ device_code = generate_device_code()
98
+ user_code = generate_user_code()
99
+ expires_at = datetime.now(timezone.utc) + timedelta(seconds=DEVICE_CODE_EXPIRES_IN)
100
+ row = DeviceCode(
101
+ device_code=device_code,
102
+ user_code=user_code,
103
+ client_id=client.id,
104
+ scope=scope,
105
+ audience=effective_audience,
106
+ resource=effective_resource,
107
+ expires_at=expires_at,
108
+ interval=DEVICE_CODE_INTERVAL,
109
+ poll_count=0,
110
+ slow_down_count=0,
111
+ tenant_id=client.tenant_id,
112
+ )
113
+ db.add(row)
114
+ await db.commit()
115
+ try:
116
+ await db.refresh(row)
117
+ except Exception:
118
+ pass
119
+
120
+ verification_uri = f"{str(deployment.issuer or settings.issuer).rstrip('/')}/device"
121
+ verification_uri_complete = f"{verification_uri}?user_code={user_code}"
122
+
123
+ await append_audit_event_async(
124
+ tenant_id=client.tenant_id,
125
+ actor_client_id=client.id,
126
+ event_type='device.authorization.created',
127
+ target_type='device_code',
128
+ target_id=str(getattr(row, 'id', device_code)),
129
+ details={
130
+ 'audience': effective_audience,
131
+ 'resource': effective_resource,
132
+ 'resources': list(selection.resources) if selection is not None else [],
133
+ 'scope': scope,
134
+ 'interval': DEVICE_CODE_INTERVAL,
135
+ 'expires_in': DEVICE_CODE_EXPIRES_IN,
136
+ 'user_code_length': len(user_code),
137
+ 'user_code_charset': 'A-Z0-9',
138
+ },
139
+ )
140
+
141
+ return {
142
+ 'device_code': device_code,
143
+ 'user_code': user_code,
144
+ 'verification_uri': verification_uri,
145
+ 'verification_uri_complete': verification_uri_complete,
146
+ 'expires_in': DEVICE_CODE_EXPIRES_IN,
147
+ 'interval': DEVICE_CODE_INTERVAL,
148
+ }