simple-module-auth 0.0.42__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.
- {simple_module_auth-0.0.42 → simple_module_auth-0.0.43}/.gitignore +3 -0
- {simple_module_auth-0.0.42 → simple_module_auth-0.0.43}/PKG-INFO +8 -4
- {simple_module_auth-0.0.42 → simple_module_auth-0.0.43}/README.md +1 -0
- simple_module_auth-0.0.43/auth/constants.py +6 -0
- {simple_module_auth-0.0.42 → simple_module_auth-0.0.43}/auth/middleware.py +35 -12
- simple_module_auth-0.0.43/auth/models.py +21 -0
- simple_module_auth-0.0.43/auth/oidc_common/__init__.py +1 -0
- simple_module_auth-0.0.43/auth/oidc_common/claims.py +20 -0
- simple_module_auth-0.0.43/auth/oidc_common/directory.py +95 -0
- simple_module_auth-0.0.43/auth/oidc_common/jwks.py +195 -0
- simple_module_auth-0.0.43/auth/oidc_common/persistence.py +82 -0
- simple_module_auth-0.0.43/auth/oidc_common/renewal.py +116 -0
- simple_module_auth-0.0.43/auth/oidc_common/renewal_outcomes.py +181 -0
- simple_module_auth-0.0.43/auth/oidc_common/session.py +126 -0
- simple_module_auth-0.0.43/auth/oidc_common/tenant.py +46 -0
- simple_module_auth-0.0.43/auth/oidc_common/tokens.py +81 -0
- {simple_module_auth-0.0.42 → simple_module_auth-0.0.43}/package.json +1 -1
- {simple_module_auth-0.0.42 → simple_module_auth-0.0.43}/pyproject.toml +7 -4
- simple_module_auth-0.0.43/tests/conftest.py +97 -0
- {simple_module_auth-0.0.42 → simple_module_auth-0.0.43}/tests/test_auth_middleware.py +23 -0
- {simple_module_auth-0.0.42 → simple_module_auth-0.0.43}/tests/test_auth_next_target.py +27 -1
- simple_module_auth-0.0.43/tests/test_auth_oidc_authority.py +183 -0
- simple_module_auth-0.0.43/tests/test_auth_oidc_authority_outcomes.py +49 -0
- simple_module_auth-0.0.43/tests/test_auth_oidc_concurrent_renewal.py +180 -0
- simple_module_auth-0.0.43/tests/test_auth_oidc_jwks_cache.py +87 -0
- simple_module_auth-0.0.43/tests/test_auth_oidc_jwt_hardening.py +49 -0
- simple_module_auth-0.0.43/tests/test_auth_oidc_outcome_logout.py +119 -0
- simple_module_auth-0.0.43/tests/test_auth_oidc_outcome_migration.py +30 -0
- simple_module_auth-0.0.43/tests/test_auth_oidc_shared_helpers.py +46 -0
- simple_module_auth-0.0.43/tests/test_auth_oidc_sign_in.py +50 -0
- simple_module_auth-0.0.43/tests/test_auth_oidc_tokens.py +48 -0
- {simple_module_auth-0.0.42 → simple_module_auth-0.0.43}/LICENSE +0 -0
- {simple_module_auth-0.0.42 → simple_module_auth-0.0.43}/auth/__init__.py +0 -0
- {simple_module_auth-0.0.42 → simple_module_auth-0.0.43}/auth/_route_match.py +0 -0
- {simple_module_auth-0.0.42 → simple_module_auth-0.0.43}/auth/contracts/__init__.py +0 -0
- {simple_module_auth-0.0.42 → simple_module_auth-0.0.43}/auth/contracts/provider.py +0 -0
- {simple_module_auth-0.0.42 → simple_module_auth-0.0.43}/auth/contracts/resolver.py +0 -0
- {simple_module_auth-0.0.42 → simple_module_auth-0.0.43}/auth/contracts/schemas.py +0 -0
- {simple_module_auth-0.0.42 → simple_module_auth-0.0.43}/auth/contracts/tokens.py +0 -0
- {simple_module_auth-0.0.42 → simple_module_auth-0.0.43}/auth/deps.py +0 -0
- {simple_module_auth-0.0.42 → simple_module_auth-0.0.43}/auth/locales/de.json +0 -0
- {simple_module_auth-0.0.42 → simple_module_auth-0.0.43}/auth/locales/en.json +0 -0
- {simple_module_auth-0.0.42 → simple_module_auth-0.0.43}/auth/locales/es.json +0 -0
- {simple_module_auth-0.0.42 → simple_module_auth-0.0.43}/auth/module.py +0 -0
- {simple_module_auth-0.0.42 → simple_module_auth-0.0.43}/auth/py.typed +0 -0
- {simple_module_auth-0.0.42 → simple_module_auth-0.0.43}/auth/state.py +0 -0
- {simple_module_auth-0.0.42 → simple_module_auth-0.0.43}/tests/test_auth_parse_bearer.py +0 -0
- {simple_module_auth-0.0.42 → simple_module_auth-0.0.43}/tests/test_auth_permission_deprecation.py +0 -0
- {simple_module_auth-0.0.42 → simple_module_auth-0.0.43}/tests/test_auth_provider_protocol.py +0 -0
- {simple_module_auth-0.0.42 → simple_module_auth-0.0.43}/tests/test_auth_unknown_paths.py +0 -0
- {simple_module_auth-0.0.42 → simple_module_auth-0.0.43}/tests/test_deps.py +0 -0
- {simple_module_auth-0.0.42 → simple_module_auth-0.0.43}/tests/test_module.py +0 -0
- {simple_module_auth-0.0.42 → simple_module_auth-0.0.43}/tests/test_resolver_registry.py +0 -0
- {simple_module_auth-0.0.42 → simple_module_auth-0.0.43}/tests/test_user_context.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: simple_module_auth
|
|
3
|
-
Version: 0.0.
|
|
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,10 +21,13 @@ 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:
|
|
26
|
-
Requires-Dist: simple-module-
|
|
27
|
-
Requires-Dist: simple-module-
|
|
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
|
|
@@ -46,6 +49,7 @@ pip install simple_module_auth
|
|
|
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
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
|
|
@@ -17,6 +17,7 @@ pip install simple_module_auth
|
|
|
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
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
|
|
@@ -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
|
|
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
|
-
|
|
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)
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
"""Durable provider-scoped UUIDs, with race recovery and throttled activity writes."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import logging
|
|
7
|
+
from datetime import UTC, datetime, timedelta
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
from simple_module_db import independent_session
|
|
11
|
+
from sqlmodel import col
|
|
12
|
+
from starlette.requests import Request
|
|
13
|
+
|
|
14
|
+
logger = logging.getLogger(__name__)
|
|
15
|
+
_LAST_LOGIN_WRITE_INTERVAL = timedelta(minutes=5)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
async def upsert_user_cache(
|
|
19
|
+
request: Request,
|
|
20
|
+
*,
|
|
21
|
+
model: Any,
|
|
22
|
+
identity: dict[str, str],
|
|
23
|
+
email: str | None,
|
|
24
|
+
name: str | None,
|
|
25
|
+
update_name: bool = True,
|
|
26
|
+
throttle_login: bool = False,
|
|
27
|
+
session_factory: Any = independent_session,
|
|
28
|
+
) -> str | None:
|
|
29
|
+
try:
|
|
30
|
+
from sqlalchemy import or_, select, update
|
|
31
|
+
from sqlalchemy.exc import IntegrityError
|
|
32
|
+
|
|
33
|
+
now = datetime.now(UTC)
|
|
34
|
+
async with session_factory(request.app) as db:
|
|
35
|
+
stmt = select(model).where(
|
|
36
|
+
*(getattr(model, key) == value for key, value in identity.items())
|
|
37
|
+
)
|
|
38
|
+
row = (await db.execute(stmt)).scalar_one_or_none()
|
|
39
|
+
if row is None:
|
|
40
|
+
try:
|
|
41
|
+
async with db.begin_nested():
|
|
42
|
+
row = model(
|
|
43
|
+
**identity,
|
|
44
|
+
email=email if isinstance(email, str) else "",
|
|
45
|
+
full_name=name,
|
|
46
|
+
last_login_at=now,
|
|
47
|
+
)
|
|
48
|
+
db.add(row)
|
|
49
|
+
await db.flush()
|
|
50
|
+
except IntegrityError:
|
|
51
|
+
# Another request inserted this sub after our SELECT.
|
|
52
|
+
row = (await db.execute(stmt)).scalar_one()
|
|
53
|
+
|
|
54
|
+
if isinstance(email, str):
|
|
55
|
+
row.email = email # an absent or malformed claim keeps the last known address
|
|
56
|
+
if update_name or row.full_name is None:
|
|
57
|
+
row.full_name = name # an absent claim keeps the last known name
|
|
58
|
+
if not throttle_login:
|
|
59
|
+
row.last_login_at = now
|
|
60
|
+
else:
|
|
61
|
+
cutoff = now - _LAST_LOGIN_WRITE_INTERVAL
|
|
62
|
+
if row.last_login_at is None or row.last_login_at <= cutoff:
|
|
63
|
+
# Recheck in SQL so concurrent bearer requests share one touch.
|
|
64
|
+
await db.execute(
|
|
65
|
+
update(model)
|
|
66
|
+
.where(
|
|
67
|
+
col(model.id) == row.id,
|
|
68
|
+
or_(
|
|
69
|
+
col(model.last_login_at).is_(None),
|
|
70
|
+
col(model.last_login_at) <= cutoff,
|
|
71
|
+
),
|
|
72
|
+
)
|
|
73
|
+
.values(last_login_at=now)
|
|
74
|
+
)
|
|
75
|
+
return str(row.id)
|
|
76
|
+
except Exception as exc:
|
|
77
|
+
# Diagnosable without personal data: the error class and a short hash
|
|
78
|
+
# of the identity, never the identity itself or a traceback whose SQL
|
|
79
|
+
# parameters can carry the email.
|
|
80
|
+
digest = hashlib.sha256(repr(sorted(identity.items())).encode()).hexdigest()[:12]
|
|
81
|
+
logger.warning("Failed to persist OIDC identity %s (%s)", digest, type(exc).__name__)
|
|
82
|
+
return None
|