simple-module-auth 0.0.42__tar.gz → 0.0.44__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.44}/.gitignore +3 -0
- {simple_module_auth-0.0.42 → simple_module_auth-0.0.44}/PKG-INFO +10 -6
- {simple_module_auth-0.0.42 → simple_module_auth-0.0.44}/README.md +3 -2
- simple_module_auth-0.0.44/auth/constants.py +11 -0
- simple_module_auth-0.0.44/auth/core/__init__.py +1 -0
- simple_module_auth-0.0.44/auth/core/constants.py +6 -0
- simple_module_auth-0.0.44/auth/deps.py +11 -0
- simple_module_auth-0.0.44/auth/middleware.py +11 -0
- simple_module_auth-0.0.44/auth/models.py +23 -0
- {simple_module_auth-0.0.42 → simple_module_auth-0.0.44}/auth/module.py +2 -2
- simple_module_auth-0.0.44/auth/oidc_common/__init__.py +1 -0
- simple_module_auth-0.0.44/auth/oidc_common/claims.py +20 -0
- simple_module_auth-0.0.44/auth/oidc_common/directory.py +95 -0
- simple_module_auth-0.0.44/auth/oidc_common/jwks.py +195 -0
- simple_module_auth-0.0.44/auth/oidc_common/persistence.py +82 -0
- simple_module_auth-0.0.44/auth/oidc_common/renewal.py +116 -0
- simple_module_auth-0.0.44/auth/oidc_common/renewal_outcomes.py +181 -0
- simple_module_auth-0.0.44/auth/oidc_common/session.py +126 -0
- simple_module_auth-0.0.44/auth/oidc_common/tenant.py +46 -0
- simple_module_auth-0.0.44/auth/oidc_common/tokens.py +81 -0
- simple_module_auth-0.0.44/auth/state.py +11 -0
- simple_module_auth-0.0.44/auth/web/__init__.py +5 -0
- {simple_module_auth-0.0.42/auth → simple_module_auth-0.0.44/auth/web}/middleware.py +37 -14
- {simple_module_auth-0.0.42 → simple_module_auth-0.0.44}/package.json +1 -1
- {simple_module_auth-0.0.42 → simple_module_auth-0.0.44}/pyproject.toml +7 -4
- simple_module_auth-0.0.44/tests/conftest.py +97 -0
- simple_module_auth-0.0.42/tests/test_resolver_registry.py → simple_module_auth-0.0.44/tests/contracts/resolver/test_auth_resolver_registry.py +5 -5
- simple_module_auth-0.0.44/tests/core/audit/test_auth_audit_redaction.py +16 -0
- simple_module_auth-0.0.44/tests/oidc_common/authority/test_auth_oidc_authority.py +183 -0
- simple_module_auth-0.0.44/tests/oidc_common/jwks/test_auth_oidc_jwks_cache.py +87 -0
- simple_module_auth-0.0.44/tests/oidc_common/jwks/test_auth_oidc_jwt_hardening.py +49 -0
- simple_module_auth-0.0.44/tests/oidc_common/renewal/test_auth_oidc_authority_outcomes.py +49 -0
- simple_module_auth-0.0.44/tests/oidc_common/renewal/test_auth_oidc_concurrent_renewal.py +180 -0
- simple_module_auth-0.0.44/tests/oidc_common/renewal/test_auth_oidc_outcome_logout.py +119 -0
- simple_module_auth-0.0.44/tests/oidc_common/renewal/test_auth_oidc_outcome_migration.py +30 -0
- simple_module_auth-0.0.44/tests/oidc_common/session/test_auth_oidc_shared_helpers.py +46 -0
- simple_module_auth-0.0.44/tests/oidc_common/session/test_auth_oidc_sign_in.py +50 -0
- simple_module_auth-0.0.44/tests/oidc_common/tokens/test_auth_oidc_tokens.py +48 -0
- simple_module_auth-0.0.42/tests/test_deps.py → simple_module_auth-0.0.44/tests/web/deps/test_auth_deps.py +1 -1
- {simple_module_auth-0.0.42/tests → simple_module_auth-0.0.44/tests/web/deps}/test_auth_permission_deprecation.py +4 -2
- {simple_module_auth-0.0.42/tests → simple_module_auth-0.0.44/tests/web/middleware}/test_auth_middleware.py +25 -2
- {simple_module_auth-0.0.42/tests → simple_module_auth-0.0.44/tests/web/middleware}/test_auth_next_target.py +29 -3
- {simple_module_auth-0.0.42/tests → simple_module_auth-0.0.44/tests/web/middleware}/test_auth_unknown_paths.py +3 -3
- {simple_module_auth-0.0.42 → simple_module_auth-0.0.44}/LICENSE +0 -0
- {simple_module_auth-0.0.42 → simple_module_auth-0.0.44}/auth/__init__.py +0 -0
- {simple_module_auth-0.0.42 → simple_module_auth-0.0.44}/auth/contracts/__init__.py +0 -0
- {simple_module_auth-0.0.42 → simple_module_auth-0.0.44}/auth/contracts/provider.py +0 -0
- {simple_module_auth-0.0.42 → simple_module_auth-0.0.44}/auth/contracts/resolver.py +0 -0
- {simple_module_auth-0.0.42 → simple_module_auth-0.0.44}/auth/contracts/schemas.py +0 -0
- {simple_module_auth-0.0.42 → simple_module_auth-0.0.44}/auth/contracts/tokens.py +0 -0
- {simple_module_auth-0.0.42/auth → simple_module_auth-0.0.44/auth/core}/state.py +0 -0
- {simple_module_auth-0.0.42 → simple_module_auth-0.0.44}/auth/locales/de.json +0 -0
- {simple_module_auth-0.0.42 → simple_module_auth-0.0.44}/auth/locales/en.json +0 -0
- {simple_module_auth-0.0.42 → simple_module_auth-0.0.44}/auth/locales/es.json +0 -0
- {simple_module_auth-0.0.42 → simple_module_auth-0.0.44}/auth/py.typed +0 -0
- {simple_module_auth-0.0.42/auth → simple_module_auth-0.0.44/auth/web}/_route_match.py +0 -0
- {simple_module_auth-0.0.42/auth → simple_module_auth-0.0.44/auth/web}/deps.py +0 -0
- {simple_module_auth-0.0.42/tests → simple_module_auth-0.0.44/tests/contracts/provider}/test_auth_provider_protocol.py +0 -0
- /simple_module_auth-0.0.42/tests/test_user_context.py → /simple_module_auth-0.0.44/tests/contracts/schemas/test_auth_user_context.py +0 -0
- {simple_module_auth-0.0.42/tests → simple_module_auth-0.0.44/tests/contracts/tokens}/test_auth_parse_bearer.py +0 -0
- /simple_module_auth-0.0.42/tests/test_module.py → /simple_module_auth-0.0.44/tests/core/module/test_auth_module.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.44
|
|
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.44
|
|
29
|
+
Requires-Dist: simple-module-db==0.0.44
|
|
30
|
+
Requires-Dist: simple-module-hosting==0.0.44
|
|
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
|
|
@@ -53,7 +57,7 @@ pip install simple_module_auth
|
|
|
53
57
|
```python
|
|
54
58
|
from fastapi import APIRouter
|
|
55
59
|
|
|
56
|
-
from auth.deps import CurrentUser
|
|
60
|
+
from auth.web.deps import CurrentUser
|
|
57
61
|
|
|
58
62
|
router = APIRouter()
|
|
59
63
|
|
|
@@ -77,7 +81,7 @@ from .constants import PERM_PRODUCTS_CREATE
|
|
|
77
81
|
async def create_product(): ...
|
|
78
82
|
```
|
|
79
83
|
|
|
80
|
-
`auth.deps.require_permission` is deprecated and will be removed in **0.1.0**
|
|
84
|
+
`auth.web.deps.require_permission` is deprecated and will be removed in **0.1.0**
|
|
81
85
|
(#698). It retains its legacy any-of semantics, role-based admin bypass and cached
|
|
82
86
|
permission check. Migrate to `RequiresPermission(PERM_KEY)`; for several required
|
|
83
87
|
permissions, declare a dependency for each. Unlike the legacy helper,
|
|
@@ -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
|
|
@@ -24,7 +25,7 @@ pip install simple_module_auth
|
|
|
24
25
|
```python
|
|
25
26
|
from fastapi import APIRouter
|
|
26
27
|
|
|
27
|
-
from auth.deps import CurrentUser
|
|
28
|
+
from auth.web.deps import CurrentUser
|
|
28
29
|
|
|
29
30
|
router = APIRouter()
|
|
30
31
|
|
|
@@ -48,7 +49,7 @@ from .constants import PERM_PRODUCTS_CREATE
|
|
|
48
49
|
async def create_product(): ...
|
|
49
50
|
```
|
|
50
51
|
|
|
51
|
-
`auth.deps.require_permission` is deprecated and will be removed in **0.1.0**
|
|
52
|
+
`auth.web.deps.require_permission` is deprecated and will be removed in **0.1.0**
|
|
52
53
|
(#698). It retains its legacy any-of semantics, role-based admin bypass and cached
|
|
53
54
|
permission check. Migrate to `RequiresPermission(PERM_KEY)`; for several required
|
|
54
55
|
permissions, declare a dependency for each. Unlike the legacy helper,
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
"""Moved to :mod:`auth.core.constants`; this alias goes in 0.0.46 (module layout)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import importlib
|
|
6
|
+
import sys
|
|
7
|
+
|
|
8
|
+
from simple_module_core.deprecation import deprecated_module
|
|
9
|
+
|
|
10
|
+
deprecated_module("auth.constants", remove_in="0.0.46", use="auth.core.constants")
|
|
11
|
+
sys.modules[__name__] = importlib.import_module("auth.core.constants")
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""What every auth feature builds on: browser session keys and the app.state.auth container."""
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
"""Moved to :mod:`auth.web.deps`; this alias goes in 0.0.46 (module layout)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import importlib
|
|
6
|
+
import sys
|
|
7
|
+
|
|
8
|
+
from simple_module_core.deprecation import deprecated_module
|
|
9
|
+
|
|
10
|
+
deprecated_module("auth.deps", remove_in="0.0.46", use="auth.web.deps")
|
|
11
|
+
sys.modules[__name__] = importlib.import_module("auth.web.deps")
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
"""Moved to :mod:`auth.web.middleware`; this alias goes in 0.0.46 (module layout)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import importlib
|
|
6
|
+
import sys
|
|
7
|
+
|
|
8
|
+
from simple_module_core.deprecation import deprecated_module
|
|
9
|
+
|
|
10
|
+
deprecated_module("auth.middleware", remove_in="0.0.46", use="auth.web.middleware")
|
|
11
|
+
sys.modules[__name__] = importlib.import_module("auth.web.middleware")
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"""Short-lived cross-worker outcomes for browser token renewal."""
|
|
2
|
+
|
|
3
|
+
from typing import Any, ClassVar
|
|
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
|
+
__audit_redact_fields__: ClassVar[set[str]] = {"outcome_key", "lock_key", "session"}
|
|
14
|
+
|
|
15
|
+
__tablename__ = "auth_refresh_outcome"
|
|
16
|
+
|
|
17
|
+
# sha256(refresh key : identity : spent sealed token); not a session id.
|
|
18
|
+
outcome_key: str = Field(primary_key=True, max_length=128)
|
|
19
|
+
# sha256(refresh key : identity), the per-session lock; logout deletes by it.
|
|
20
|
+
lock_key: str = Field(index=True, max_length=128)
|
|
21
|
+
# BIGINT: a 32-bit Unix time overflows in 2038.
|
|
22
|
+
expires_at: int = Field(sa_type=BigInteger, index=True)
|
|
23
|
+
session: dict[str, Any] = Field(sa_type=JSON)
|
|
@@ -41,13 +41,13 @@ class AuthModule(ModuleBase):
|
|
|
41
41
|
)
|
|
42
42
|
|
|
43
43
|
def register_settings(self, app: FastAPI) -> None:
|
|
44
|
-
from auth.state import AuthState
|
|
44
|
+
from auth.core.state import AuthState
|
|
45
45
|
|
|
46
46
|
app.state.auth = AuthState()
|
|
47
47
|
app.state.principal_serializer = _serialize_principal
|
|
48
48
|
|
|
49
49
|
def register_middleware(self, app: FastAPI) -> None:
|
|
50
|
-
from auth.middleware import AuthMiddleware
|
|
50
|
+
from auth.web.middleware import AuthMiddleware
|
|
51
51
|
|
|
52
52
|
app.add_middleware(AuthMiddleware)
|
|
53
53
|
|
|
@@ -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
|