simple-module-auth 0.0.41__tar.gz → 0.0.43__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 (54) hide show
  1. {simple_module_auth-0.0.41 → simple_module_auth-0.0.43}/.gitignore +3 -0
  2. {simple_module_auth-0.0.41 → simple_module_auth-0.0.43}/PKG-INFO +21 -9
  3. {simple_module_auth-0.0.41 → simple_module_auth-0.0.43}/README.md +14 -5
  4. simple_module_auth-0.0.43/auth/constants.py +6 -0
  5. {simple_module_auth-0.0.41 → simple_module_auth-0.0.43}/auth/deps.py +8 -9
  6. {simple_module_auth-0.0.41 → simple_module_auth-0.0.43}/auth/middleware.py +35 -12
  7. simple_module_auth-0.0.43/auth/models.py +21 -0
  8. simple_module_auth-0.0.43/auth/oidc_common/__init__.py +1 -0
  9. simple_module_auth-0.0.43/auth/oidc_common/claims.py +20 -0
  10. simple_module_auth-0.0.43/auth/oidc_common/directory.py +95 -0
  11. simple_module_auth-0.0.43/auth/oidc_common/jwks.py +195 -0
  12. simple_module_auth-0.0.43/auth/oidc_common/persistence.py +82 -0
  13. simple_module_auth-0.0.43/auth/oidc_common/renewal.py +116 -0
  14. simple_module_auth-0.0.43/auth/oidc_common/renewal_outcomes.py +181 -0
  15. simple_module_auth-0.0.43/auth/oidc_common/session.py +126 -0
  16. simple_module_auth-0.0.43/auth/oidc_common/tenant.py +46 -0
  17. simple_module_auth-0.0.43/auth/oidc_common/tokens.py +81 -0
  18. {simple_module_auth-0.0.41 → simple_module_auth-0.0.43}/package.json +5 -6
  19. {simple_module_auth-0.0.41 → simple_module_auth-0.0.43}/pyproject.toml +7 -4
  20. simple_module_auth-0.0.43/tests/conftest.py +97 -0
  21. {simple_module_auth-0.0.41 → simple_module_auth-0.0.43}/tests/test_auth_middleware.py +23 -0
  22. {simple_module_auth-0.0.41 → simple_module_auth-0.0.43}/tests/test_auth_next_target.py +27 -1
  23. simple_module_auth-0.0.43/tests/test_auth_oidc_authority.py +183 -0
  24. simple_module_auth-0.0.43/tests/test_auth_oidc_authority_outcomes.py +49 -0
  25. simple_module_auth-0.0.43/tests/test_auth_oidc_concurrent_renewal.py +180 -0
  26. simple_module_auth-0.0.43/tests/test_auth_oidc_jwks_cache.py +87 -0
  27. simple_module_auth-0.0.43/tests/test_auth_oidc_jwt_hardening.py +49 -0
  28. simple_module_auth-0.0.43/tests/test_auth_oidc_outcome_logout.py +119 -0
  29. simple_module_auth-0.0.43/tests/test_auth_oidc_outcome_migration.py +30 -0
  30. simple_module_auth-0.0.43/tests/test_auth_oidc_shared_helpers.py +46 -0
  31. simple_module_auth-0.0.43/tests/test_auth_oidc_sign_in.py +50 -0
  32. simple_module_auth-0.0.43/tests/test_auth_oidc_tokens.py +48 -0
  33. simple_module_auth-0.0.43/tests/test_auth_permission_deprecation.py +13 -0
  34. {simple_module_auth-0.0.41 → simple_module_auth-0.0.43}/LICENSE +0 -0
  35. {simple_module_auth-0.0.41 → simple_module_auth-0.0.43}/auth/__init__.py +0 -0
  36. {simple_module_auth-0.0.41 → simple_module_auth-0.0.43}/auth/_route_match.py +0 -0
  37. {simple_module_auth-0.0.41 → simple_module_auth-0.0.43}/auth/contracts/__init__.py +0 -0
  38. {simple_module_auth-0.0.41 → simple_module_auth-0.0.43}/auth/contracts/provider.py +0 -0
  39. {simple_module_auth-0.0.41 → simple_module_auth-0.0.43}/auth/contracts/resolver.py +0 -0
  40. {simple_module_auth-0.0.41 → simple_module_auth-0.0.43}/auth/contracts/schemas.py +0 -0
  41. {simple_module_auth-0.0.41 → simple_module_auth-0.0.43}/auth/contracts/tokens.py +0 -0
  42. {simple_module_auth-0.0.41 → simple_module_auth-0.0.43}/auth/locales/de.json +0 -0
  43. {simple_module_auth-0.0.41 → simple_module_auth-0.0.43}/auth/locales/en.json +0 -0
  44. {simple_module_auth-0.0.41 → simple_module_auth-0.0.43}/auth/locales/es.json +0 -0
  45. {simple_module_auth-0.0.41 → simple_module_auth-0.0.43}/auth/module.py +0 -0
  46. {simple_module_auth-0.0.41 → simple_module_auth-0.0.43}/auth/py.typed +0 -0
  47. {simple_module_auth-0.0.41 → simple_module_auth-0.0.43}/auth/state.py +0 -0
  48. {simple_module_auth-0.0.41 → simple_module_auth-0.0.43}/tests/test_auth_parse_bearer.py +0 -0
  49. {simple_module_auth-0.0.41 → simple_module_auth-0.0.43}/tests/test_auth_provider_protocol.py +0 -0
  50. {simple_module_auth-0.0.41 → simple_module_auth-0.0.43}/tests/test_auth_unknown_paths.py +0 -0
  51. {simple_module_auth-0.0.41 → simple_module_auth-0.0.43}/tests/test_deps.py +0 -0
  52. {simple_module_auth-0.0.41 → simple_module_auth-0.0.43}/tests/test_module.py +0 -0
  53. {simple_module_auth-0.0.41 → simple_module_auth-0.0.43}/tests/test_resolver_registry.py +0 -0
  54. {simple_module_auth-0.0.41 → simple_module_auth-0.0.43}/tests/test_user_context.py +0 -0
@@ -22,6 +22,9 @@ node_modules/
22
22
 
23
23
  # Database
24
24
  *.db
25
+ *.db-wal
26
+ *.db-shm
27
+ *.db-journal
25
28
  *.sqlite3
26
29
 
27
30
  # Module-managed runtime state (e.g. uploaded dataset files,
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: simple_module_auth
3
- Version: 0.0.41
3
+ Version: 0.0.43
4
4
  Summary: Session-cookie authentication primitives — middleware, login/logout, redirect helpers for simple_module
5
5
  Project-URL: Homepage, https://github.com/antosubash/simple_module_python
6
6
  Project-URL: Repository, https://github.com/antosubash/simple_module_python
@@ -21,15 +21,18 @@ Classifier: Topic :: Internet :: WWW/HTTP
21
21
  Classifier: Topic :: Software Development :: Libraries :: Application Frameworks
22
22
  Classifier: Typing :: Typed
23
23
  Requires-Python: >=3.12
24
+ Requires-Dist: cryptography>=42
25
+ Requires-Dist: httpx<0.29,>=0.27
24
26
  Requires-Dist: itsdangerous<3,>=2.2
25
- Requires-Dist: simple-module-core==0.0.41
26
- Requires-Dist: simple-module-db==0.0.41
27
- Requires-Dist: simple-module-hosting==0.0.41
27
+ Requires-Dist: pyjwt[crypto]<3,>=2.8
28
+ Requires-Dist: simple-module-core==0.0.43
29
+ Requires-Dist: simple-module-db==0.0.43
30
+ Requires-Dist: simple-module-hosting==0.0.43
28
31
  Description-Content-Type: text/markdown
29
32
 
30
33
  # simple_module_auth
31
34
 
32
- Pluggable authentication core for [simple_module](https://github.com/antosubash/simple_module_python) apps. Owns the stable public contracts every other module imports — `UserContext`, the `AuthProvider` protocol, the `PrincipalResolver` chain, and the `get_current_user` / `CurrentUser` / `require_permission` dependencies — plus the `AuthMiddleware` that resolves the current principal on every request.
35
+ Pluggable authentication core for [simple_module](https://github.com/antosubash/simple_module_python) apps. Owns the stable public contracts every other module imports — `UserContext`, the `AuthProvider` protocol, the `PrincipalResolver` chain, and the `get_current_user` / `CurrentUser` dependencies — plus the `AuthMiddleware` that resolves the current principal on every request.
33
36
 
34
37
  **Heads up:** for most apps you don't install this directly — an auth-provider module (`simple_module_users` for email+password, `simple_module_keycloak` for OIDC) pulls it in and registers itself on `app.state.auth.auth_provider`.
35
38
 
@@ -45,7 +48,8 @@ pip install simple_module_auth
45
48
  - `AuthProvider` protocol — the swappable-backend contract (`resolve_user`, `get_login_url`, `get_logout_url`, `is_bearer_request`); exactly one provider module registers an implementation on `app.state.auth.auth_provider`.
46
49
  - `PrincipalResolver` chain — async `(Request) -> UserContext | None` callables apps append to `app.state.auth.principal_resolvers` (e.g. PAT/bearer-token or API-key auth), consulted after the session path.
47
50
  - `AuthMiddleware` — delegates to the provider + resolver chain on every request and populates the request principal.
48
- - `get_current_user` / `CurrentUser` dependency and the `require_permission(*permissions)` dependency factory.
51
+ - `get_current_user` / `CurrentUser` dependency.
52
+ - `auth.oidc_common` — provider-neutral OIDC helpers (JWKS/JWT validation, refresh-token sealing, sign-in rotation, renewal, cache persistence, directory) shared by the `oidc` and `keycloak` modules.
49
53
  - Anonymous-access is declared via the framework's method-aware `register_public_routes` hook (with the `SM_AUTH_PUBLIC_PATHS` host-level escape hatch).
50
54
 
51
55
  ## Usage
@@ -63,18 +67,26 @@ async def me(user: CurrentUser):
63
67
  return {"user_id": user.id, "email": user.email}
64
68
  ```
65
69
 
66
- Routes that need a specific permission use the `require_permission(...)` dependency factory:
70
+ Routes that need a specific permission use `RequiresPermission` from hosting:
67
71
 
68
72
  ```python
69
73
  from fastapi import Depends
70
74
 
71
- from auth.deps import require_permission
75
+ from simple_module_hosting.permissions import RequiresPermission
72
76
 
77
+ from .constants import PERM_PRODUCTS_CREATE
73
78
 
74
- @router.post("/", dependencies=[Depends(require_permission("products.create"))])
79
+
80
+ @router.post("/", dependencies=[Depends(RequiresPermission(PERM_PRODUCTS_CREATE))])
75
81
  async def create_product(): ...
76
82
  ```
77
83
 
84
+ `auth.deps.require_permission` is deprecated and will be removed in **0.1.0**
85
+ (#698). It retains its legacy any-of semantics, role-based admin bypass and cached
86
+ permission check. Migrate to `RequiresPermission(PERM_KEY)`; for several required
87
+ permissions, declare a dependency for each. Unlike the legacy helper,
88
+ `RequiresPermission` rechecks administrators demoted during the request.
89
+
78
90
  ## Depends on
79
91
 
80
92
  - `simple_module_core`, `simple_module_db`
@@ -1,6 +1,6 @@
1
1
  # simple_module_auth
2
2
 
3
- Pluggable authentication core for [simple_module](https://github.com/antosubash/simple_module_python) apps. Owns the stable public contracts every other module imports — `UserContext`, the `AuthProvider` protocol, the `PrincipalResolver` chain, and the `get_current_user` / `CurrentUser` / `require_permission` dependencies — plus the `AuthMiddleware` that resolves the current principal on every request.
3
+ Pluggable authentication core for [simple_module](https://github.com/antosubash/simple_module_python) apps. Owns the stable public contracts every other module imports — `UserContext`, the `AuthProvider` protocol, the `PrincipalResolver` chain, and the `get_current_user` / `CurrentUser` dependencies — plus the `AuthMiddleware` that resolves the current principal on every request.
4
4
 
5
5
  **Heads up:** for most apps you don't install this directly — an auth-provider module (`simple_module_users` for email+password, `simple_module_keycloak` for OIDC) pulls it in and registers itself on `app.state.auth.auth_provider`.
6
6
 
@@ -16,7 +16,8 @@ pip install simple_module_auth
16
16
  - `AuthProvider` protocol — the swappable-backend contract (`resolve_user`, `get_login_url`, `get_logout_url`, `is_bearer_request`); exactly one provider module registers an implementation on `app.state.auth.auth_provider`.
17
17
  - `PrincipalResolver` chain — async `(Request) -> UserContext | None` callables apps append to `app.state.auth.principal_resolvers` (e.g. PAT/bearer-token or API-key auth), consulted after the session path.
18
18
  - `AuthMiddleware` — delegates to the provider + resolver chain on every request and populates the request principal.
19
- - `get_current_user` / `CurrentUser` dependency and the `require_permission(*permissions)` dependency factory.
19
+ - `get_current_user` / `CurrentUser` dependency.
20
+ - `auth.oidc_common` — provider-neutral OIDC helpers (JWKS/JWT validation, refresh-token sealing, sign-in rotation, renewal, cache persistence, directory) shared by the `oidc` and `keycloak` modules.
20
21
  - Anonymous-access is declared via the framework's method-aware `register_public_routes` hook (with the `SM_AUTH_PUBLIC_PATHS` host-level escape hatch).
21
22
 
22
23
  ## Usage
@@ -34,18 +35,26 @@ async def me(user: CurrentUser):
34
35
  return {"user_id": user.id, "email": user.email}
35
36
  ```
36
37
 
37
- Routes that need a specific permission use the `require_permission(...)` dependency factory:
38
+ Routes that need a specific permission use `RequiresPermission` from hosting:
38
39
 
39
40
  ```python
40
41
  from fastapi import Depends
41
42
 
42
- from auth.deps import require_permission
43
+ from simple_module_hosting.permissions import RequiresPermission
43
44
 
45
+ from .constants import PERM_PRODUCTS_CREATE
44
46
 
45
- @router.post("/", dependencies=[Depends(require_permission("products.create"))])
47
+
48
+ @router.post("/", dependencies=[Depends(RequiresPermission(PERM_PRODUCTS_CREATE))])
46
49
  async def create_product(): ...
47
50
  ```
48
51
 
52
+ `auth.deps.require_permission` is deprecated and will be removed in **0.1.0**
53
+ (#698). It retains its legacy any-of semantics, role-based admin bypass and cached
54
+ permission check. Migrate to `RequiresPermission(PERM_KEY)`; for several required
55
+ permissions, declare a dependency for each. Unlike the legacy helper,
56
+ `RequiresPermission` rechecks administrators demoted during the request.
57
+
49
58
  ## Depends on
50
59
 
51
60
  - `simple_module_core`, `simple_module_db`
@@ -0,0 +1,6 @@
1
+ """Shared browser session keys."""
2
+
3
+ SESSION_AUTHORITY_KEY = "oidc_authority"
4
+ SESSION_ID_KEY = "oidc_session_id"
5
+ # Cooldown after a transient refresh failure or skipped coordination.
6
+ REFRESH_RETRY_AFTER_SECONDS = 30
@@ -5,15 +5,14 @@ from __future__ import annotations
5
5
  from typing import Annotated
6
6
 
7
7
  from fastapi import Depends, HTTPException, Request
8
- from simple_module_core.permissions import grants
8
+ from simple_module_core.deprecation import deprecated
9
+ from simple_module_core.permissions import ADMIN_ROLE, grants
9
10
  from simple_module_hosting.i18n_deps import TranslatorDep
10
11
  from simple_module_hosting.permissions import ensure_resolved_permissions
11
12
  from simple_module_hosting.token_guard import GATE_PERMISSION, mark_token_gate
12
13
 
13
14
  from auth.contracts.schemas import UserContext
14
15
 
15
- _ADMIN_ROLE = "admin"
16
-
17
16
 
18
17
  async def get_current_user(request: Request, t: TranslatorDep) -> UserContext:
19
18
  """Extract the authenticated user from request state.
@@ -29,13 +28,13 @@ async def get_current_user(request: Request, t: TranslatorDep) -> UserContext:
29
28
  CurrentUser = Annotated[UserContext, Depends(get_current_user)]
30
29
 
31
30
 
31
+ @deprecated(remove_in="0.1.0", use="simple_module_hosting.permissions.RequiresPermission")
32
32
  def require_permission(*permissions: str):
33
- """Create a dependency that checks if the user has required permissions.
34
-
35
- Usage::
33
+ """Legacy any-of gate, removed in 0.1.0; use ``RequiresPermission`` instead.
36
34
 
37
- @router.post("/", dependencies=[Depends(require_permission("products.create"))])
38
- async def create_product(...): ...
35
+ Retains the role-based admin bypass and cached permission behaviour for
36
+ compatibility. ``RequiresPermission`` rechecks a principal demoted during
37
+ the request; this helper does not.
39
38
  """
40
39
 
41
40
  async def check(
@@ -46,7 +45,7 @@ def require_permission(*permissions: str):
46
45
  # Admin role bypasses permission checks — but not for a token: an
47
46
  # admin's PAT is worth only the scopes it carries, and the resolved
48
47
  # set below already applies that cap.
49
- if _ADMIN_ROLE in user.roles and user.scopes is None:
48
+ if ADMIN_ROLE in user.roles and user.scopes is None:
50
49
  return
51
50
 
52
51
  # The same resolution RequiresPermission reads: the registry's role map
@@ -9,10 +9,13 @@ principal-resolver chain. Sets ``request.state.user`` and the
9
9
  from __future__ import annotations
10
10
 
11
11
  import logging
12
+ from urllib.parse import urlsplit
12
13
 
13
14
  from simple_module_core.app_state import get_openapi_url
14
15
  from simple_module_core.redirect_safety import SESSION_NEXT_KEY, safe_next_or_none
15
16
  from simple_module_db.listeners import current_user_id
17
+ from simple_module_hosting.inertia_deps import is_inertia_request
18
+ from simple_module_hosting.path_matching import matches_path
16
19
  from simple_module_hosting.public_access import is_public as route_is_public
17
20
  from starlette.requests import Request
18
21
  from starlette.responses import JSONResponse, RedirectResponse
@@ -23,13 +26,13 @@ from auth._route_match import route_exists
23
26
  logger = logging.getLogger(__name__)
24
27
 
25
28
  _FRAMEWORK_PUBLIC_PREFIXES = (
26
- "/health",
29
+ "/health/",
27
30
  "/static/",
28
- "/api/docs",
29
- "/api/redoc",
31
+ "/api/docs/",
32
+ "/api/redoc/",
30
33
  "/i18n/",
31
34
  )
32
- _FRAMEWORK_PUBLIC_EXACT = ("/",)
35
+ _FRAMEWORK_PUBLIC_EXACT = ("/", "/health", "/api/docs", "/api/redoc")
33
36
 
34
37
 
35
38
  def _query_suffix(request: Request) -> str:
@@ -46,7 +49,7 @@ def _is_navigation(request: Request) -> bool:
46
49
  clients, scripts) keep the previous behaviour.
47
50
  """
48
51
  headers = request.headers
49
- if headers.get("x-inertia") == "true":
52
+ if is_inertia_request(request.scope):
50
53
  return True
51
54
  dest = headers.get("sec-fetch-dest")
52
55
  if dest is not None:
@@ -57,6 +60,31 @@ def _is_navigation(request: Request) -> bool:
57
60
  return True
58
61
 
59
62
 
63
+ def _post_login_target(request: Request) -> str | None:
64
+ """Where sign-in should return the visitor, or ``None``.
65
+
66
+ A GET/HEAD navigation returns to itself. A mutation (an Inertia DELETE
67
+ whose session expired) must not: replaying its URL as a GET after sign-in
68
+ hits a 405, so it returns to the same-site page it was sent from instead.
69
+ """
70
+ if not _is_navigation(request):
71
+ return None
72
+ if request.method in ("GET", "HEAD"):
73
+ return safe_next_or_none(request.url.path + _query_suffix(request))
74
+ try:
75
+ referer = urlsplit(request.headers.get("referer", ""))
76
+ # Same origin means host *and* port: another port on this host is a
77
+ # different site. A malformed Referer (``http://[``) raises ValueError.
78
+ if referer.netloc and (
79
+ referer.hostname != request.url.hostname or referer.port != request.url.port
80
+ ):
81
+ return None
82
+ except ValueError:
83
+ return None
84
+ query = f"?{referer.query}" if referer.query else ""
85
+ return safe_next_or_none(referer.path + query) if referer.path else None
86
+
87
+
60
88
  class AuthMiddleware:
61
89
  """Authenticate requests via the registered AuthProvider.
62
90
 
@@ -85,8 +113,7 @@ class AuthMiddleware:
85
113
  return
86
114
 
87
115
  is_public = (
88
- any(path.startswith(p) for p in _FRAMEWORK_PUBLIC_PREFIXES)
89
- or path in _FRAMEWORK_PUBLIC_EXACT
116
+ matches_path(path, exact=_FRAMEWORK_PUBLIC_EXACT, prefixes=_FRAMEWORK_PUBLIC_PREFIXES)
90
117
  # Anonymous exactly when the host serves it (dev, or openapi_public).
91
118
  or path == get_openapi_url(scope["app"])
92
119
  )
@@ -136,11 +163,7 @@ class AuthMiddleware:
136
163
  session = scope.get("session", {})
137
164
  # Only a navigation is a target: a subresource (the sign-in
138
165
  # page's own favicon) would overwrite it (#416).
139
- next_url = (
140
- safe_next_or_none(request.url.path + _query_suffix(request))
141
- if _is_navigation(request)
142
- else None
143
- )
166
+ next_url = _post_login_target(request)
144
167
  if next_url is not None:
145
168
  session[SESSION_NEXT_KEY] = next_url
146
169
  response = RedirectResponse(
@@ -0,0 +1,21 @@
1
+ """Short-lived cross-worker outcomes for browser token renewal."""
2
+
3
+ from typing import Any
4
+
5
+ from simple_module_db.base import create_module_base
6
+ from sqlalchemy import JSON, BigInteger
7
+ from sqlmodel import Field
8
+
9
+ Base = create_module_base("auth")
10
+
11
+
12
+ class RefreshOutcome(Base, table=True): # ty: ignore[unsupported-base]
13
+ __tablename__ = "auth_refresh_outcome"
14
+
15
+ # sha256(refresh key : identity : spent sealed token); not a session id.
16
+ outcome_key: str = Field(primary_key=True, max_length=128)
17
+ # sha256(refresh key : identity), the per-session lock; logout deletes by it.
18
+ lock_key: str = Field(index=True, max_length=128)
19
+ # BIGINT: a 32-bit Unix time overflows in 2038.
20
+ expires_at: int = Field(sa_type=BigInteger, index=True)
21
+ session: dict[str, Any] = Field(sa_type=JSON)
@@ -0,0 +1 @@
1
+ """Provider-neutral OIDC protocol helpers shared by authentication providers."""
@@ -0,0 +1,20 @@
1
+ """OIDC role-claim lookup."""
2
+
3
+ from typing import Any
4
+
5
+
6
+ def extract_nested(data: dict, path: str) -> list[str] | None:
7
+ # A claim named exactly ``path`` wins: Auth0/Okta namespace custom claims
8
+ # as URLs (``https://example.com/roles``), which contain dots.
9
+ if path in data:
10
+ value = data[path]
11
+ return value if isinstance(value, list) else None
12
+ parts = path.split(".")
13
+ current: Any = data
14
+ for part in parts:
15
+ if not isinstance(current, dict):
16
+ return None
17
+ current = current.get(part)
18
+ if current is None:
19
+ return None
20
+ return current if isinstance(current, list) else None
@@ -0,0 +1,95 @@
1
+ """Directory for provider-owned UUID cache tables; roles remain at the IdP."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Collection
6
+ from datetime import UTC, datetime, timedelta
7
+ from typing import Any
8
+
9
+ from simple_module_core.user_directory import (
10
+ DirectoryStats,
11
+ DirectoryUser,
12
+ chunked,
13
+ parse_user_ids,
14
+ )
15
+ from simple_module_db.user_directory_sql import name_or_email_contains, to_directory_user
16
+ from sqlalchemy import String, func, select
17
+ from sqlalchemy.ext.compiler import compiles
18
+ from sqlalchemy.sql.expression import FunctionElement
19
+
20
+
21
+ class _UuidText(FunctionElement):
22
+ """A uuid column as the canonical hyphenated text every text id uses.
23
+
24
+ The cache primary key is SQLAlchemy's ``Uuid``: native on Postgres,
25
+ where a plain cast already renders hyphenated, but 32 bare hex characters
26
+ on SQLite — which would never equal the ``str(uuid)`` an audit row stored.
27
+ """
28
+
29
+ type = String()
30
+ inherit_cache = True
31
+
32
+
33
+ @compiles(_UuidText)
34
+ def _uuid_text_default(element: Any, compiler: Any, **kw: Any) -> str:
35
+ return f"CAST({compiler.process(element.clauses, **kw)} AS VARCHAR)"
36
+
37
+
38
+ @compiles(_UuidText, "sqlite")
39
+ def _uuid_text_sqlite(element: Any, compiler: Any, **kw: Any) -> str:
40
+ col = compiler.process(element.clauses, **kw)
41
+ parts = [(1, 8), (9, 4), (13, 4), (17, 4), (21, 12)]
42
+ return " || '-' || ".join(f"substr({col}, {start}, {length})" for start, length in parts)
43
+
44
+
45
+ class CacheDirectory:
46
+ """Directory over the supplied provider cache model."""
47
+
48
+ #: Cache rows are not an audited model with a screen of their own, so actor
49
+ #: cells stay unlinked rather than pointing at a users page that is absent.
50
+ entity_type: str | None = None
51
+
52
+ def __init__(self, model: Any) -> None:
53
+ self.model = model
54
+ self._columns = (model.id, model.email, model.full_name)
55
+
56
+ async def get_many(
57
+ self, db: Any, ids: Collection[str], *, with_roles: bool = False
58
+ ) -> dict[str, DirectoryUser]:
59
+ parsed = parse_user_ids(ids)
60
+ found: dict[str, DirectoryUser] = {}
61
+ for chunk in chunked(list(parsed)):
62
+ stmt = select(*self._columns).where(self.model.id.in_(chunk))
63
+ for row in (await db.execute(stmt)).all():
64
+ for key in parsed[row.id]:
65
+ found[key] = to_directory_user(row, key)
66
+ return found
67
+
68
+ async def search(self, db: Any, term: str | None, *, limit: int) -> list[DirectoryUser]:
69
+ stmt = select(*self._columns).order_by(self.model.email).limit(limit)
70
+ if term and term.strip():
71
+ stmt = stmt.where(
72
+ name_or_email_contains(self.model.full_name, self.model.email, term.strip())
73
+ )
74
+ return [to_directory_user(row, str(row.id)) for row in (await db.execute(stmt)).all()]
75
+
76
+ def match_ids(self, term: str) -> Any | None:
77
+ return select(_UuidText(self.model.id)).where(
78
+ name_or_email_contains(self.model.full_name, self.model.email, term)
79
+ )
80
+
81
+ async def stats(self, db: Any, *, active_window: timedelta) -> DirectoryStats:
82
+ cutoff = datetime.now(UTC) - active_window
83
+ total, active = (
84
+ await db.execute(
85
+ select(
86
+ func.count(),
87
+ func.count().filter(self.model.last_login_at >= cutoff),
88
+ ).select_from(self.model)
89
+ )
90
+ ).one()
91
+ # The cache row is written at first sign-in, not account creation.
92
+ return DirectoryStats(total=total, active_since=active, created_this_month=None)
93
+
94
+
95
+ __all__ = ["CacheDirectory"]
@@ -0,0 +1,195 @@
1
+ """JWKS key cache and JWT validation for OIDC tokens."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import logging
7
+ import time
8
+ from typing import Any
9
+ from urllib.parse import urlsplit
10
+
11
+ import httpx
12
+ import jwt
13
+ from jwt.algorithms import RSAAlgorithm
14
+
15
+ logger = logging.getLogger(__name__)
16
+ _CLOCK_SKEW_SECONDS = 10
17
+ _MIN_REFETCH_INTERVAL_SECONDS = 30
18
+
19
+
20
+ class JWKSCache:
21
+ """Caches OIDC's public signing keys and validates JWTs.
22
+
23
+ Unknown keys trigger a refresh, with a per-cache cooldown and lock to
24
+ bound unauthenticated fetches while still discovering key rotation.
25
+ """
26
+
27
+ def __init__(
28
+ self,
29
+ jwks_url: str,
30
+ ttl_seconds: int = 3600,
31
+ *,
32
+ issuer: str,
33
+ audience: str,
34
+ exclusive_audience: bool = True,
35
+ ) -> None:
36
+ if not issuer:
37
+ raise ValueError("issuer is required for JWT validation")
38
+ if not audience:
39
+ raise ValueError("audience is required for JWT validation")
40
+ self._jwks_url = jwks_url
41
+ self._ttl = ttl_seconds
42
+ self._issuer = issuer
43
+ self._audience = audience
44
+ # True: the token may name only the expected audience and, for this
45
+ # client's own audience, ``azp`` must be this client. False (Keycloak):
46
+ # the audience only has to be among the token's ``aud`` values and
47
+ # ``azp`` is not checked, as Keycloak access tokens carry
48
+ # ``aud: [client, "account"]`` and bearer tokens come from other clients.
49
+ self._exclusive_audience = exclusive_audience
50
+ self._keys: dict[str, Any] = {}
51
+ self._fetched_at: float = 0
52
+ self._last_fetch_attempt: float | None = None
53
+ self._fetch_lock = asyncio.Lock()
54
+
55
+ @staticmethod
56
+ def _now() -> float:
57
+ return time.monotonic()
58
+
59
+ @property
60
+ def issuer(self) -> str:
61
+ """The exact discovered issuer used to validate token claims."""
62
+ return self._issuer
63
+
64
+ async def validate_jwt(
65
+ self,
66
+ token: str,
67
+ *,
68
+ audience: str | None = None,
69
+ ) -> dict[str, Any] | None:
70
+ """Decode and validate a JWT. Returns claims dict or None."""
71
+ try:
72
+ unverified = jwt.get_unverified_header(token)
73
+ except jwt.PyJWTError:
74
+ return None
75
+
76
+ kid = unverified.get("kid")
77
+ if not isinstance(kid, str) or not kid:
78
+ return None
79
+
80
+ key = await self._get_key(kid)
81
+ if key is None:
82
+ return None
83
+
84
+ return self._decode(token, key, audience or self._audience)
85
+
86
+ def _decode(self, token: str, key: Any, audience: str) -> dict[str, Any] | None:
87
+ try:
88
+ claims = jwt.decode(
89
+ token,
90
+ key,
91
+ algorithms=["RS256"],
92
+ issuer=self.issuer,
93
+ audience=audience,
94
+ options={"require": ["iss", "sub", "aud", "exp", "iat"]},
95
+ # An app clock a few seconds behind the IdP would otherwise
96
+ # reject fresh tokens as issued in the future.
97
+ leeway=_CLOCK_SKEW_SECONDS,
98
+ )
99
+ if not isinstance(claims["sub"], str) or not claims["sub"].strip():
100
+ return None
101
+ if any(type(claims[k]) is not int for k in ("exp", "iat")):
102
+ return None
103
+ if not self._exclusive_audience:
104
+ return claims
105
+ audiences = claims["aud"]
106
+ audiences = [audiences] if isinstance(audiences, str) else audiences
107
+ if not isinstance(audiences, list) or any(
108
+ not isinstance(a, str) or not a for a in audiences
109
+ ):
110
+ return None
111
+ if set(audiences) - {audience}:
112
+ return None
113
+ # ``azp`` names the client a token was issued to. For this client's
114
+ # ID token that is us; for an API access token it is the *calling*
115
+ # client (Entra v2 always sets it), which is never ours to pin.
116
+ azp = claims.get("azp")
117
+ if (
118
+ audience == self._audience
119
+ and (len(audiences) > 1 or azp is not None)
120
+ and azp != self._audience
121
+ ):
122
+ return None
123
+ return claims
124
+ except jwt.PyJWTError:
125
+ logger.debug("OIDC JWT validation failed")
126
+ return None
127
+
128
+ async def _get_key(self, kid: str) -> Any | None:
129
+ if self._is_stale() or kid not in self._keys:
130
+ async with self._fetch_lock:
131
+ await self._fetch_keys()
132
+ return self._keys.get(kid)
133
+
134
+ def _is_stale(self) -> bool:
135
+ return self._now() - self._fetched_at > self._ttl
136
+
137
+ async def _fetch_keys(self) -> None:
138
+ now = self._now()
139
+ if (
140
+ self._last_fetch_attempt is not None
141
+ and now - self._last_fetch_attempt < _MIN_REFETCH_INTERVAL_SECONDS
142
+ ):
143
+ return
144
+ # Failed attempts must also cool down; keep the last good keys on failure.
145
+ self._last_fetch_attempt = now
146
+ try:
147
+ async with httpx.AsyncClient() as client:
148
+ resp = await client.get(self._jwks_url, timeout=10)
149
+ resp.raise_for_status()
150
+ jwks_data = resp.json()
151
+ except Exception:
152
+ logger.warning("Failed to fetch OIDC JWKS")
153
+ return
154
+
155
+ new_keys: dict[str, Any] = {}
156
+ if not isinstance(jwks_data, dict) or not isinstance(jwks_data.get("keys"), list):
157
+ return
158
+ for key_data in jwks_data["keys"]:
159
+ if not isinstance(key_data, dict) or not self._is_rsa_signing_key(key_data):
160
+ continue
161
+ key_issuer = key_data.get("issuer", self._issuer)
162
+ if isinstance(key_issuer, str):
163
+ # Entra may template its JWK issuer even on tenant-specific discovery.
164
+ tenant = urlsplit(self._issuer).path.strip("/").split("/")[0]
165
+ key_issuer = key_issuer.replace("{tenantid}", tenant)
166
+ if key_issuer != self._issuer:
167
+ continue
168
+ kid = key_data["kid"] # _is_rsa_signing_key guarantees a non-empty kid
169
+ try:
170
+ new_keys[kid] = RSAAlgorithm.from_jwk(key_data)
171
+ except Exception:
172
+ logger.warning("Failed to parse JWK kid=%s", kid)
173
+ if not new_keys:
174
+ return
175
+ self._keys = new_keys
176
+ self._fetched_at = self._now()
177
+
178
+ @staticmethod
179
+ def _is_rsa_signing_key(key_data: dict[str, Any]) -> bool:
180
+ """Accept RSA signing keys. ``alg``/``use`` are optional in JWKS — Entra
181
+ omits ``alg`` — so only reject when a present value is incompatible."""
182
+ if (
183
+ not isinstance(key_data.get("kid"), str)
184
+ or not key_data["kid"]
185
+ or key_data.get("kty") != "RSA"
186
+ ):
187
+ return False
188
+ alg = key_data.get("alg")
189
+ if alg and alg != "RS256":
190
+ return False
191
+ use = key_data.get("use")
192
+ if use and use != "sig":
193
+ return False
194
+ operations = key_data.get("key_ops")
195
+ return operations is None or (isinstance(operations, list) and "verify" in operations)