simple-module-auth 0.0.49__tar.gz → 0.0.51__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.49 → simple_module_auth-0.0.51}/PKG-INFO +5 -5
- {simple_module_auth-0.0.49 → simple_module_auth-0.0.51}/README.md +1 -1
- simple_module_auth-0.0.51/auth/contracts/events.py +47 -0
- {simple_module_auth-0.0.49 → simple_module_auth-0.0.51}/auth/contracts/schemas.py +27 -23
- {simple_module_auth-0.0.49 → simple_module_auth-0.0.51}/auth/core/state.py +5 -3
- {simple_module_auth-0.0.49 → simple_module_auth-0.0.51}/auth/models.py +1 -1
- {simple_module_auth-0.0.49 → simple_module_auth-0.0.51}/auth/module.py +1 -1
- {simple_module_auth-0.0.49 → simple_module_auth-0.0.51}/auth/oidc_common/directory.py +8 -4
- simple_module_auth-0.0.51/auth/oidc_common/logout.py +26 -0
- {simple_module_auth-0.0.49 → simple_module_auth-0.0.51}/auth/oidc_common/renewal.py +1 -1
- {simple_module_auth-0.0.49 → simple_module_auth-0.0.51}/auth/oidc_common/renewal_outcomes.py +2 -2
- {simple_module_auth-0.0.49 → simple_module_auth-0.0.51}/auth/oidc_common/session.py +46 -4
- {simple_module_auth-0.0.49 → simple_module_auth-0.0.51}/auth/oidc_common/tenant.py +1 -1
- {simple_module_auth-0.0.49 → simple_module_auth-0.0.51}/auth/oidc_common/tokens.py +1 -1
- {simple_module_auth-0.0.49 → simple_module_auth-0.0.51}/auth/web/deps.py +1 -1
- {simple_module_auth-0.0.49 → simple_module_auth-0.0.51}/auth/web/middleware.py +14 -6
- {simple_module_auth-0.0.49 → simple_module_auth-0.0.51}/pyproject.toml +4 -4
- {simple_module_auth-0.0.49 → simple_module_auth-0.0.51}/tests/conftest.py +4 -4
- simple_module_auth-0.0.51/tests/contracts/events/test_auth_session_logout_events.py +74 -0
- {simple_module_auth-0.0.49 → simple_module_auth-0.0.51}/tests/contracts/schemas/test_auth_user_context.py +63 -7
- {simple_module_auth-0.0.49 → simple_module_auth-0.0.51}/tests/core/audit/test_auth_audit_redaction.py +1 -1
- {simple_module_auth-0.0.49 → simple_module_auth-0.0.51}/tests/core/module/test_auth_module.py +1 -1
- {simple_module_auth-0.0.49 → simple_module_auth-0.0.51}/tests/oidc_common/authority/test_auth_oidc_authority.py +1 -1
- {simple_module_auth-0.0.49 → simple_module_auth-0.0.51}/tests/oidc_common/renewal/test_auth_oidc_concurrent_renewal.py +1 -1
- simple_module_auth-0.0.51/tests/oidc_common/session/test_auth_oidc_session_resolution.py +68 -0
- {simple_module_auth-0.0.49 → simple_module_auth-0.0.51}/tests/oidc_common/session/test_auth_oidc_sign_in.py +2 -2
- {simple_module_auth-0.0.49 → simple_module_auth-0.0.51}/tests/web/deps/test_auth_deps.py +3 -3
- simple_module_auth-0.0.51/tests/web/middleware/test_auth_duck_typed_principal.py +52 -0
- {simple_module_auth-0.0.49 → simple_module_auth-0.0.51}/tests/web/middleware/test_auth_middleware.py +4 -4
- {simple_module_auth-0.0.49 → simple_module_auth-0.0.51}/tests/web/middleware/test_auth_next_target.py +2 -2
- {simple_module_auth-0.0.49 → simple_module_auth-0.0.51}/tests/web/middleware/test_auth_unknown_paths.py +2 -2
- simple_module_auth-0.0.51/tests/web/middleware/test_principal_guards.py +83 -0
- {simple_module_auth-0.0.49 → simple_module_auth-0.0.51}/.gitignore +0 -0
- {simple_module_auth-0.0.49 → simple_module_auth-0.0.51}/LICENSE +0 -0
- {simple_module_auth-0.0.49 → simple_module_auth-0.0.51}/auth/__init__.py +0 -0
- {simple_module_auth-0.0.49 → simple_module_auth-0.0.51}/auth/contracts/__init__.py +0 -0
- {simple_module_auth-0.0.49 → simple_module_auth-0.0.51}/auth/contracts/provider.py +0 -0
- {simple_module_auth-0.0.49 → simple_module_auth-0.0.51}/auth/contracts/resolver.py +0 -0
- {simple_module_auth-0.0.49 → simple_module_auth-0.0.51}/auth/contracts/tokens.py +0 -0
- {simple_module_auth-0.0.49 → simple_module_auth-0.0.51}/auth/core/__init__.py +0 -0
- {simple_module_auth-0.0.49 → simple_module_auth-0.0.51}/auth/core/constants.py +0 -0
- {simple_module_auth-0.0.49 → simple_module_auth-0.0.51}/auth/locales/de.json +0 -0
- {simple_module_auth-0.0.49 → simple_module_auth-0.0.51}/auth/locales/en.json +0 -0
- {simple_module_auth-0.0.49 → simple_module_auth-0.0.51}/auth/locales/es.json +0 -0
- {simple_module_auth-0.0.49 → simple_module_auth-0.0.51}/auth/oidc_common/__init__.py +0 -0
- {simple_module_auth-0.0.49 → simple_module_auth-0.0.51}/auth/oidc_common/claims.py +0 -0
- {simple_module_auth-0.0.49 → simple_module_auth-0.0.51}/auth/oidc_common/jwks.py +0 -0
- {simple_module_auth-0.0.49 → simple_module_auth-0.0.51}/auth/oidc_common/persistence.py +0 -0
- {simple_module_auth-0.0.49 → simple_module_auth-0.0.51}/auth/py.typed +0 -0
- {simple_module_auth-0.0.49 → simple_module_auth-0.0.51}/auth/web/__init__.py +0 -0
- {simple_module_auth-0.0.49 → simple_module_auth-0.0.51}/auth/web/_route_match.py +0 -0
- {simple_module_auth-0.0.49 → simple_module_auth-0.0.51}/tests/contracts/provider/test_auth_provider_protocol.py +0 -0
- {simple_module_auth-0.0.49 → simple_module_auth-0.0.51}/tests/contracts/resolver/test_auth_resolver_registry.py +0 -0
- {simple_module_auth-0.0.49 → simple_module_auth-0.0.51}/tests/contracts/tokens/test_auth_parse_bearer.py +0 -0
- {simple_module_auth-0.0.49 → simple_module_auth-0.0.51}/tests/oidc_common/jwks/test_auth_oidc_jwks_cache.py +0 -0
- {simple_module_auth-0.0.49 → simple_module_auth-0.0.51}/tests/oidc_common/jwks/test_auth_oidc_jwt_hardening.py +0 -0
- {simple_module_auth-0.0.49 → simple_module_auth-0.0.51}/tests/oidc_common/renewal/test_auth_oidc_authority_outcomes.py +0 -0
- {simple_module_auth-0.0.49 → simple_module_auth-0.0.51}/tests/oidc_common/renewal/test_auth_oidc_outcome_logout.py +0 -0
- {simple_module_auth-0.0.49 → simple_module_auth-0.0.51}/tests/oidc_common/renewal/test_auth_oidc_outcome_migration.py +0 -0
- {simple_module_auth-0.0.49 → simple_module_auth-0.0.51}/tests/oidc_common/session/test_auth_oidc_shared_helpers.py +0 -0
- {simple_module_auth-0.0.49 → simple_module_auth-0.0.51}/tests/oidc_common/tokens/test_auth_oidc_tokens.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.51
|
|
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
|
|
@@ -25,9 +25,9 @@ Requires-Dist: cryptography>=42
|
|
|
25
25
|
Requires-Dist: httpx<0.29,>=0.27
|
|
26
26
|
Requires-Dist: itsdangerous<3,>=2.2
|
|
27
27
|
Requires-Dist: pyjwt[crypto]<3,>=2.8
|
|
28
|
-
Requires-Dist: simple-module-core==0.0.
|
|
29
|
-
Requires-Dist: simple-module-db==0.0.
|
|
30
|
-
Requires-Dist: simple-module-hosting==0.0.
|
|
28
|
+
Requires-Dist: simple-module-core==0.0.51
|
|
29
|
+
Requires-Dist: simple-module-db==0.0.51
|
|
30
|
+
Requires-Dist: simple-module-hosting==0.0.51
|
|
31
31
|
Description-Content-Type: text/markdown
|
|
32
32
|
|
|
33
33
|
# simple_module_auth
|
|
@@ -72,7 +72,7 @@ Routes that need a specific permission use `RequiresPermission` from hosting:
|
|
|
72
72
|
```python
|
|
73
73
|
from fastapi import Depends
|
|
74
74
|
|
|
75
|
-
from simple_module_hosting.permissions import RequiresPermission
|
|
75
|
+
from simple_module_hosting.auth.permissions import RequiresPermission
|
|
76
76
|
|
|
77
77
|
from .constants import PERM_PRODUCTS_CREATE
|
|
78
78
|
|
|
@@ -40,7 +40,7 @@ Routes that need a specific permission use `RequiresPermission` from hosting:
|
|
|
40
40
|
```python
|
|
41
41
|
from fastapi import Depends
|
|
42
42
|
|
|
43
|
-
from simple_module_hosting.permissions import RequiresPermission
|
|
43
|
+
from simple_module_hosting.auth.permissions import RequiresPermission
|
|
44
44
|
|
|
45
45
|
from .constants import PERM_PRODUCTS_CREATE
|
|
46
46
|
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"""Build auth lifecycle events from validated session identities."""
|
|
2
|
+
|
|
3
|
+
from contextlib import suppress
|
|
4
|
+
from uuid import UUID
|
|
5
|
+
|
|
6
|
+
from simple_module_core.runtime.deprecation import deprecate
|
|
7
|
+
from simple_module_core.user_events import UserLoggedOut
|
|
8
|
+
from starlette.requests import Request
|
|
9
|
+
|
|
10
|
+
from auth.contracts.schemas import UserContext
|
|
11
|
+
from auth.contracts.tokens import AUTH_KIND_SESSION
|
|
12
|
+
|
|
13
|
+
_LEGACY_REQUEST = deprecate(
|
|
14
|
+
"auth.contracts.events.session_logout_event(request)",
|
|
15
|
+
remove_in="0.0.52",
|
|
16
|
+
use="session_logout_event() with the validated session UserContext",
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def session_logout_event(
|
|
21
|
+
user: UserContext | Request | None = None,
|
|
22
|
+
*,
|
|
23
|
+
local_account: bool,
|
|
24
|
+
request: Request | None = None,
|
|
25
|
+
) -> UserLoggedOut | None:
|
|
26
|
+
"""Capture the identity of the browser session that logout will end.
|
|
27
|
+
|
|
28
|
+
The caller must validate the session independently of any bearer principal.
|
|
29
|
+
Convert Users account IDs to UUIDs. Keep external providers' principal IDs
|
|
30
|
+
as strings, including cache IDs and any case-sensitive subject fallback.
|
|
31
|
+
Passing a Request (positionally or as request=) is supported until 0.0.52.
|
|
32
|
+
"""
|
|
33
|
+
if request is not None:
|
|
34
|
+
if user is not None:
|
|
35
|
+
raise TypeError("Pass either user or request, not both")
|
|
36
|
+
user = request
|
|
37
|
+
if isinstance(user, Request):
|
|
38
|
+
_LEGACY_REQUEST.warn()
|
|
39
|
+
user = getattr(user.state, "user", None)
|
|
40
|
+
if user is None or user.auth_kind != AUTH_KIND_SESSION:
|
|
41
|
+
return None
|
|
42
|
+
user_id: UUID | str = user.id
|
|
43
|
+
if local_account:
|
|
44
|
+
with suppress(ValueError):
|
|
45
|
+
user_id = UUID(user.id)
|
|
46
|
+
email = user.email if isinstance(user.email, str) and user.email != "None" else ""
|
|
47
|
+
return UserLoggedOut(user_id=user_id, email=email)
|
|
@@ -21,7 +21,7 @@ class AccountLike(Protocol):
|
|
|
21
21
|
"""
|
|
22
22
|
|
|
23
23
|
id: Any
|
|
24
|
-
email: str
|
|
24
|
+
email: str | None
|
|
25
25
|
full_name: str | None
|
|
26
26
|
roles: Iterable[NamedRole]
|
|
27
27
|
|
|
@@ -57,6 +57,10 @@ class UserContext:
|
|
|
57
57
|
# permissions; when missing, the request runs as anonymous (401 on gated
|
|
58
58
|
# routes). ``None`` (a session, a service key) requires nothing.
|
|
59
59
|
required_permission: str | None = None
|
|
60
|
+
# The ``api_tokens`` row id of the credential behind a ``"pat"`` /
|
|
61
|
+
# ``"service"`` principal, so audit records can name the token. ``None``
|
|
62
|
+
# for every other kind of sign-in.
|
|
63
|
+
token_id: str | None = None
|
|
60
64
|
|
|
61
65
|
# Providers must explicitly attest ownership of the principal's email.
|
|
62
66
|
email_verified: bool = False
|
|
@@ -83,11 +87,12 @@ class UserContext:
|
|
|
83
87
|
generic provider's claim path sets it).
|
|
84
88
|
The caller is responsible for eager-loading roles (selectinload).
|
|
85
89
|
"""
|
|
90
|
+
email = user.email or ""
|
|
86
91
|
return cls(
|
|
87
92
|
id=str(user.id),
|
|
88
|
-
email=
|
|
89
|
-
email_verified=getattr(user, "is_verified", False) is True,
|
|
90
|
-
name=user.full_name or
|
|
93
|
+
email=email,
|
|
94
|
+
email_verified=bool(email) and getattr(user, "is_verified", False) is True,
|
|
95
|
+
name=user.full_name or email,
|
|
91
96
|
roles=[r.name for r in user.roles],
|
|
92
97
|
auth_kind=auth_kind,
|
|
93
98
|
scopes=list(scopes) if scopes is not None else None,
|
|
@@ -98,7 +103,12 @@ class UserContext:
|
|
|
98
103
|
|
|
99
104
|
The inverse of :meth:`from_session_dict`. Adding a new field to
|
|
100
105
|
``UserContext`` requires updating both methods here — not the
|
|
101
|
-
AuthMiddleware cache helper, which stays schema-agnostic.
|
|
106
|
+
AuthMiddleware cache helper, which stays schema-agnostic.
|
|
107
|
+
|
|
108
|
+
A session is a browser sign-in, never a credential: token identity
|
|
109
|
+
(``auth_kind``, ``scopes``, ``required_permission``, ``token_id``) is
|
|
110
|
+
never written, so whatever principal is cached, the cookie restores a
|
|
111
|
+
plain session principal."""
|
|
102
112
|
return {
|
|
103
113
|
"id": self.id,
|
|
104
114
|
"email": self.email,
|
|
@@ -107,30 +117,33 @@ class UserContext:
|
|
|
107
117
|
"roles": list(self.roles),
|
|
108
118
|
"tenant_id": self.tenant_id,
|
|
109
119
|
"permissions": list(self.permissions),
|
|
110
|
-
"auth_kind": self.auth_kind,
|
|
111
|
-
"scopes": list(self.scopes) if self.scopes is not None else None,
|
|
112
|
-
"required_permission": self.required_permission,
|
|
113
120
|
}
|
|
114
121
|
|
|
115
122
|
@classmethod
|
|
116
123
|
def from_session_dict(cls, payload: Any) -> UserContext | None:
|
|
117
124
|
"""Rebuild from :meth:`to_session_dict` output. Returns ``None`` on any
|
|
118
|
-
shape mismatch so callers can fall through to a fresh DB load.
|
|
125
|
+
shape mismatch so callers can fall through to a fresh DB load.
|
|
126
|
+
|
|
127
|
+
Always a plain session principal: token-identity keys in the payload
|
|
128
|
+
(a cookie written by an older release, or a hand-built dict) are
|
|
129
|
+
ignored, so a session can never restore as a scoped or token principal
|
|
130
|
+
— which would, for instance, earn it the ``RequiresCsrf`` token skip."""
|
|
119
131
|
if not isinstance(payload, dict):
|
|
120
132
|
return None
|
|
121
133
|
try:
|
|
134
|
+
email = payload["email"]
|
|
135
|
+
name = payload["name"]
|
|
122
136
|
return cls(
|
|
123
137
|
id=str(payload["id"]),
|
|
124
|
-
|
|
138
|
+
# Treat the legacy string "None" as a missing email.
|
|
139
|
+
email="" if email is None or email == "None" else str(email),
|
|
125
140
|
email_verified=payload.get("email_verified") is True,
|
|
126
|
-
name=str(
|
|
141
|
+
name="" if name is None else str(name),
|
|
127
142
|
roles=list(payload.get("roles") or []),
|
|
128
143
|
tenant_id=payload.get("tenant_id"),
|
|
129
144
|
# Absent on cookies written before the field existed.
|
|
130
145
|
permissions=list(payload.get("permissions") or []),
|
|
131
|
-
auth_kind=
|
|
132
|
-
scopes=_scopes_from(payload.get("scopes")),
|
|
133
|
-
required_permission=payload.get("required_permission") or None,
|
|
146
|
+
auth_kind=AUTH_KIND_SESSION,
|
|
134
147
|
)
|
|
135
148
|
except (KeyError, TypeError, ValueError):
|
|
136
149
|
return None
|
|
@@ -147,12 +160,3 @@ class UserContext:
|
|
|
147
160
|
|
|
148
161
|
def has_any_role(self, roles: list[str]) -> bool:
|
|
149
162
|
return bool(set(self.roles) & set(roles))
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
def _scopes_from(raw: Any) -> list[str] | None:
|
|
153
|
-
"""``None`` stays ``None`` (uncapped); anything else must be a list."""
|
|
154
|
-
if raw is None:
|
|
155
|
-
return None
|
|
156
|
-
if not isinstance(raw, list):
|
|
157
|
-
raise TypeError("scopes must be a list")
|
|
158
|
-
return [str(s) for s in raw]
|
|
@@ -9,7 +9,7 @@ principal-resolver registry. Apps register additional resolvers from their
|
|
|
9
9
|
|
|
10
10
|
from __future__ import annotations
|
|
11
11
|
|
|
12
|
-
from collections.abc import Callable
|
|
12
|
+
from collections.abc import Awaitable, Callable
|
|
13
13
|
from dataclasses import dataclass, field
|
|
14
14
|
from typing import TYPE_CHECKING
|
|
15
15
|
|
|
@@ -30,9 +30,11 @@ class AuthState:
|
|
|
30
30
|
principal_resolvers: list[PrincipalResolver] = field(default_factory=list)
|
|
31
31
|
# Run once a principal has resolved (any credential source), before downstream
|
|
32
32
|
# middleware; anonymous requests never reach them.
|
|
33
|
-
# A guard is a sync callable returning a refusal response or None to continue.
|
|
33
|
+
# A guard is a sync or async callable returning a refusal response or None to continue.
|
|
34
34
|
# An exception propagates (a 500), so a broken guard fails closed, never open.
|
|
35
|
-
principal_guards: list[Callable[[Request], Response | None]] =
|
|
35
|
+
principal_guards: list[Callable[[Request], Response | Awaitable[Response | None] | None]] = (
|
|
36
|
+
field(default_factory=list)
|
|
37
|
+
)
|
|
36
38
|
|
|
37
39
|
|
|
38
40
|
__all__ = ["AuthState"]
|
|
@@ -15,7 +15,7 @@ from __future__ import annotations
|
|
|
15
15
|
|
|
16
16
|
from typing import TYPE_CHECKING
|
|
17
17
|
|
|
18
|
-
from simple_module_core.module import ModuleBase, ModuleMeta
|
|
18
|
+
from simple_module_core.modules.module import ModuleBase, ModuleMeta
|
|
19
19
|
|
|
20
20
|
if TYPE_CHECKING:
|
|
21
21
|
from fastapi import FastAPI
|
|
@@ -6,13 +6,14 @@ from collections.abc import Collection
|
|
|
6
6
|
from datetime import UTC, datetime, timedelta
|
|
7
7
|
from typing import Any
|
|
8
8
|
|
|
9
|
-
from simple_module_core.user_directory import (
|
|
9
|
+
from simple_module_core.access.user_directory import (
|
|
10
10
|
DirectoryStats,
|
|
11
11
|
DirectoryUser,
|
|
12
|
+
EmailLookupUserDirectory,
|
|
12
13
|
chunked,
|
|
13
14
|
parse_user_ids,
|
|
14
15
|
)
|
|
15
|
-
from simple_module_db.user_directory_sql import (
|
|
16
|
+
from simple_module_db.queries.user_directory_sql import (
|
|
16
17
|
name_or_email_contains,
|
|
17
18
|
search_rows,
|
|
18
19
|
to_directory_user,
|
|
@@ -46,7 +47,7 @@ def _uuid_text_sqlite(element: Any, compiler: Any, **kw: Any) -> str:
|
|
|
46
47
|
return " || '-' || ".join(f"substr({col}, {start}, {length})" for start, length in parts)
|
|
47
48
|
|
|
48
49
|
|
|
49
|
-
class CacheDirectory:
|
|
50
|
+
class CacheDirectory(EmailLookupUserDirectory):
|
|
50
51
|
"""Directory over the supplied provider cache model."""
|
|
51
52
|
|
|
52
53
|
#: Cache rows are not an audited model with a screen of their own, so actor
|
|
@@ -79,6 +80,7 @@ class CacheDirectory:
|
|
|
79
80
|
exclude_ids: Collection[str] = (),
|
|
80
81
|
active_only: bool = False,
|
|
81
82
|
exact_email: bool = False,
|
|
83
|
+
match_email: bool = True,
|
|
82
84
|
) -> list[DirectoryUser]:
|
|
83
85
|
stmt = select(*self._columns).order_by(self.model.email)
|
|
84
86
|
if exclude_ids:
|
|
@@ -88,7 +90,9 @@ class CacheDirectory:
|
|
|
88
90
|
stmt = stmt.where(func.lower(self.model.email) == (term or "").strip().lower())
|
|
89
91
|
elif term and term.strip():
|
|
90
92
|
stmt = stmt.where(
|
|
91
|
-
name_or_email_contains(
|
|
93
|
+
name_or_email_contains(
|
|
94
|
+
self.model.full_name, self.model.email, term.strip(), match_email=match_email
|
|
95
|
+
)
|
|
92
96
|
)
|
|
93
97
|
rows = await search_rows(db, stmt, self.model.id, include_ids=include_ids, limit=limit)
|
|
94
98
|
return [to_directory_user(row, str(row.id)) for row in rows]
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
"""Capture logout events through the native OIDC session validator."""
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
from simple_module_core.user_events import UserLoggedOut
|
|
7
|
+
from starlette.requests import Request
|
|
8
|
+
|
|
9
|
+
from auth.contracts.events import session_logout_event
|
|
10
|
+
|
|
11
|
+
logger = logging.getLogger(__name__)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
async def logout_event_for(request: Request, provider: Any) -> UserLoggedOut | None:
|
|
15
|
+
"""Capture a locally valid session without renewal, tolerating validation failures."""
|
|
16
|
+
try:
|
|
17
|
+
# The host's swappable AuthProvider need not expose session validation.
|
|
18
|
+
state = getattr(request.app.state, provider.name)
|
|
19
|
+
validator = provider(state=state)
|
|
20
|
+
validator.jwks_cache = state.jwks_cache
|
|
21
|
+
session_user = await validator.resolve_session(request, renew=False)
|
|
22
|
+
return session_logout_event(session_user, local_account=False)
|
|
23
|
+
except Exception as exc:
|
|
24
|
+
# Event capture must not stop logout cleanup or expose exception details.
|
|
25
|
+
logger.warning("Logout session validation failed (%s); skipping event", type(exc).__name__)
|
|
26
|
+
return None
|
|
@@ -7,7 +7,7 @@ import time
|
|
|
7
7
|
from typing import Any
|
|
8
8
|
|
|
9
9
|
import httpx
|
|
10
|
-
from simple_module_hosting.session import SESSION_EXPIRES_AT_KEY
|
|
10
|
+
from simple_module_hosting.pipeline.session import SESSION_EXPIRES_AT_KEY
|
|
11
11
|
from starlette.requests import Request
|
|
12
12
|
|
|
13
13
|
from auth.contracts.schemas import UserContext
|
{simple_module_auth-0.0.49 → simple_module_auth-0.0.51}/auth/oidc_common/renewal_outcomes.py
RENAMED
|
@@ -9,9 +9,9 @@ import secrets
|
|
|
9
9
|
import time
|
|
10
10
|
from typing import Any
|
|
11
11
|
|
|
12
|
-
from simple_module_core.leases import lease
|
|
12
|
+
from simple_module_core.runtime.leases import lease
|
|
13
13
|
from simple_module_db import independent_session
|
|
14
|
-
from simple_module_hosting.session import SESSION_EXPIRES_AT_KEY
|
|
14
|
+
from simple_module_hosting.pipeline.session import SESSION_EXPIRES_AT_KEY
|
|
15
15
|
from sqlalchemy import delete, or_
|
|
16
16
|
from sqlmodel import col
|
|
17
17
|
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"""Shared sign-in rotation and callback transaction checks."""
|
|
1
|
+
"""Shared session resolution, sign-in rotation and callback transaction checks."""
|
|
2
2
|
|
|
3
3
|
import base64
|
|
4
4
|
import hashlib
|
|
@@ -6,16 +6,58 @@ import json
|
|
|
6
6
|
import secrets
|
|
7
7
|
from collections.abc import Callable
|
|
8
8
|
from dataclasses import dataclass
|
|
9
|
+
from typing import TYPE_CHECKING, Any
|
|
9
10
|
|
|
10
11
|
from fastapi import HTTPException, Request
|
|
11
|
-
from simple_module_core.redirect_safety import SESSION_NEXT_KEY, safe_next_or_none
|
|
12
|
-
from simple_module_hosting.csrf import rotate_csrf_token
|
|
13
|
-
from simple_module_hosting.session import
|
|
12
|
+
from simple_module_core.web.redirect_safety import SESSION_NEXT_KEY, safe_next_or_none
|
|
13
|
+
from simple_module_hosting.auth.csrf import rotate_csrf_token
|
|
14
|
+
from simple_module_hosting.pipeline.session import (
|
|
15
|
+
SESSION_EXPIRES_AT_KEY,
|
|
16
|
+
session_has_expired,
|
|
17
|
+
sign_in_preserved_keys,
|
|
18
|
+
)
|
|
14
19
|
from starlette.responses import RedirectResponse
|
|
15
20
|
|
|
21
|
+
from auth.contracts.schemas import UserContext
|
|
16
22
|
from auth.core.constants import SESSION_AUTHORITY_KEY, SESSION_ID_KEY
|
|
17
23
|
|
|
18
24
|
|
|
25
|
+
class SessionResolution:
|
|
26
|
+
"""Mixin resolving browser sessions through provider authority, renewal and tenant hooks."""
|
|
27
|
+
|
|
28
|
+
_session_user_key: str
|
|
29
|
+
|
|
30
|
+
if TYPE_CHECKING:
|
|
31
|
+
# Type-only hooks must not shadow implementations in sibling renewal mixins.
|
|
32
|
+
def _accept_session(self, session: dict[str, Any]) -> bool: ...
|
|
33
|
+
async def _refresh_session(self, request: Request) -> UserContext | None: ...
|
|
34
|
+
def _trusted_tenant(self, value: Any) -> str | None: ...
|
|
35
|
+
def _without_tenant_roles(self, roles: list[str]) -> list[str]: ...
|
|
36
|
+
|
|
37
|
+
def _session_needs_renewal(self, session: dict[str, Any]) -> bool:
|
|
38
|
+
return session_has_expired(session)
|
|
39
|
+
|
|
40
|
+
async def resolve_session(self, request: Request, *, renew: bool = True) -> UserContext | None:
|
|
41
|
+
"""Validate the session; ``renew=False`` preserves it and never calls the IdP."""
|
|
42
|
+
session = request.scope.get("session", {})
|
|
43
|
+
if not renew:
|
|
44
|
+
# Authority rejection must leave the original logout credentials available.
|
|
45
|
+
session = dict(session)
|
|
46
|
+
if not self._accept_session(session):
|
|
47
|
+
return None
|
|
48
|
+
# Renew authority from the IdP at expiry, without interrupting the request.
|
|
49
|
+
if self._session_needs_renewal(session):
|
|
50
|
+
return await self._refresh_session(request) if renew else None
|
|
51
|
+
ctx = UserContext.from_session_dict(session.get(self._session_user_key))
|
|
52
|
+
if ctx is not None:
|
|
53
|
+
# The cookie froze what was decided at login; re-decide with the
|
|
54
|
+
# current settings, so turning trust_tenant_claim off takes effect
|
|
55
|
+
# on sessions that already exist.
|
|
56
|
+
ctx.tenant_id = self._trusted_tenant(ctx.tenant_id)
|
|
57
|
+
ctx.roles = self._without_tenant_roles(ctx.roles)
|
|
58
|
+
return ctx
|
|
59
|
+
|
|
60
|
+
|
|
19
61
|
@dataclass(frozen=True)
|
|
20
62
|
class SessionKeys:
|
|
21
63
|
user: str
|
|
@@ -5,7 +5,7 @@ from __future__ import annotations
|
|
|
5
5
|
import logging
|
|
6
6
|
from typing import Any
|
|
7
7
|
|
|
8
|
-
from simple_module_core.tenancy import is_tenant_role
|
|
8
|
+
from simple_module_core.access.tenancy import is_tenant_role
|
|
9
9
|
from simple_module_db import is_valid_tenant_id
|
|
10
10
|
|
|
11
11
|
logger = logging.getLogger(__name__)
|
|
@@ -15,7 +15,7 @@ from types import SimpleNamespace
|
|
|
15
15
|
from typing import Any
|
|
16
16
|
|
|
17
17
|
from cryptography.fernet import Fernet, InvalidToken
|
|
18
|
-
from simple_module_core.crypto import derive_key
|
|
18
|
+
from simple_module_core.runtime.crypto import derive_key
|
|
19
19
|
|
|
20
20
|
logger = logging.getLogger(__name__)
|
|
21
21
|
# Browsers drop a cookie over 4096 bytes, and a dropped session cookie means a
|
|
@@ -5,7 +5,7 @@ from __future__ import annotations
|
|
|
5
5
|
from typing import Annotated
|
|
6
6
|
|
|
7
7
|
from fastapi import Depends, HTTPException, Request
|
|
8
|
-
from simple_module_hosting.i18n_deps import TranslatorDep
|
|
8
|
+
from simple_module_hosting.i18n.i18n_deps import TranslatorDep
|
|
9
9
|
|
|
10
10
|
from auth.contracts.schemas import UserContext
|
|
11
11
|
|
|
@@ -8,15 +8,17 @@ principal-resolver chain. Sets ``request.state.user`` and the
|
|
|
8
8
|
|
|
9
9
|
from __future__ import annotations
|
|
10
10
|
|
|
11
|
+
import inspect
|
|
11
12
|
import logging
|
|
12
13
|
from urllib.parse import urlsplit
|
|
13
14
|
|
|
14
|
-
from simple_module_core.app_state import get_openapi_url
|
|
15
|
-
from simple_module_core.redirect_safety import SESSION_NEXT_KEY, safe_next_or_none
|
|
16
|
-
from simple_module_db.
|
|
17
|
-
from
|
|
18
|
-
from simple_module_hosting.
|
|
19
|
-
from simple_module_hosting.
|
|
15
|
+
from simple_module_core.modules.app_state import get_openapi_url
|
|
16
|
+
from simple_module_core.web.redirect_safety import SESSION_NEXT_KEY, safe_next_or_none
|
|
17
|
+
from simple_module_db.models.credential import current_auth_kind, current_token_id
|
|
18
|
+
from simple_module_db.models.listeners import current_user_id
|
|
19
|
+
from simple_module_hosting.frontend.inertia_deps import is_inertia_request
|
|
20
|
+
from simple_module_hosting.pipeline.path_matching import matches_path, validated_prefixes
|
|
21
|
+
from simple_module_hosting.pipeline.public_access import is_public as route_is_public
|
|
20
22
|
from starlette.requests import Request
|
|
21
23
|
from starlette.responses import JSONResponse, RedirectResponse
|
|
22
24
|
from starlette.types import ASGIApp, Receive, Scope, Send
|
|
@@ -176,13 +178,19 @@ class AuthMiddleware:
|
|
|
176
178
|
request.state.user = user_ctx
|
|
177
179
|
for guard in auth_state.principal_guards:
|
|
178
180
|
refusal = guard(request)
|
|
181
|
+
if inspect.isawaitable(refusal):
|
|
182
|
+
refusal = await refusal
|
|
179
183
|
if refusal is not None:
|
|
180
184
|
await refusal(scope, receive, send)
|
|
181
185
|
return
|
|
182
186
|
token = current_user_id.set(user_ctx.id)
|
|
187
|
+
kind_token = current_auth_kind.set(getattr(user_ctx, "auth_kind", None))
|
|
188
|
+
token_id_token = current_token_id.set(getattr(user_ctx, "token_id", None))
|
|
183
189
|
try:
|
|
184
190
|
await self.app(scope, receive, send)
|
|
185
191
|
finally:
|
|
192
|
+
current_token_id.reset(token_id_token)
|
|
193
|
+
current_auth_kind.reset(kind_token)
|
|
186
194
|
current_user_id.reset(token)
|
|
187
195
|
return
|
|
188
196
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "simple_module_auth"
|
|
3
|
-
version = "0.0.
|
|
3
|
+
version = "0.0.51"
|
|
4
4
|
description = "Session-cookie authentication primitives — middleware, login/logout, redirect helpers for simple_module"
|
|
5
5
|
readme = "README.md"
|
|
6
6
|
license = "MIT"
|
|
@@ -25,9 +25,9 @@ dependencies = [
|
|
|
25
25
|
"PyJWT[crypto]>=2.8,<3",
|
|
26
26
|
"cryptography>=42",
|
|
27
27
|
"httpx>=0.27,<0.29",
|
|
28
|
-
"simple_module_core==0.0.
|
|
29
|
-
"simple_module_db==0.0.
|
|
30
|
-
"simple_module_hosting==0.0.
|
|
28
|
+
"simple_module_core==0.0.51",
|
|
29
|
+
"simple_module_db==0.0.51",
|
|
30
|
+
"simple_module_hosting==0.0.51",
|
|
31
31
|
]
|
|
32
32
|
|
|
33
33
|
[project.entry-points.simple_module]
|
|
@@ -9,8 +9,8 @@ import pytest
|
|
|
9
9
|
from auth.contracts.schemas import UserContext
|
|
10
10
|
from auth.oidc_common.renewal import refresh_session
|
|
11
11
|
from auth.oidc_common.session import SessionKeys
|
|
12
|
-
from simple_module_core.leases import configure_leases, reset_lease_backend
|
|
13
|
-
from simple_module_db.leases import DbLeaseBackend
|
|
12
|
+
from simple_module_core.runtime.leases import configure_leases, reset_lease_backend
|
|
13
|
+
from simple_module_db.engine.leases import DbLeaseBackend
|
|
14
14
|
from starlette.requests import Request
|
|
15
15
|
|
|
16
16
|
|
|
@@ -19,8 +19,8 @@ async def renewal(request, tmp_path):
|
|
|
19
19
|
from importlib import import_module
|
|
20
20
|
|
|
21
21
|
from auth.models import Base
|
|
22
|
-
from simple_module_db.leases import LeaseRow
|
|
23
|
-
from simple_module_db.session import init_db
|
|
22
|
+
from simple_module_db.engine.leases import LeaseRow
|
|
23
|
+
from simple_module_db.engine.session import init_db
|
|
24
24
|
|
|
25
25
|
db_state = init_db(f"sqlite+aiosqlite:///{tmp_path}/refresh.db")
|
|
26
26
|
async with db_state.engine.begin() as conn:
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
"""Session logout events preserve the dated Request calling convention (#1129)."""
|
|
2
|
+
|
|
3
|
+
import warnings
|
|
4
|
+
from uuid import UUID
|
|
5
|
+
|
|
6
|
+
import pytest
|
|
7
|
+
from auth.contracts.events import session_logout_event
|
|
8
|
+
from auth.contracts.schemas import UserContext
|
|
9
|
+
from auth.contracts.tokens import AUTH_KIND_BEARER
|
|
10
|
+
from starlette.requests import Request
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@pytest.mark.parametrize("keyword", [False, True], ids=["positional", "request-keyword"])
|
|
14
|
+
@pytest.mark.parametrize("local_account", [False, True], ids=["external", "local"])
|
|
15
|
+
def test_legacy_request_returns_session_identity_and_warns(keyword, local_account):
|
|
16
|
+
request = Request({"type": "http"})
|
|
17
|
+
request.state.user = UserContext(
|
|
18
|
+
id="74fefc26-66cb-4914-a51f-c88f27e66bb3", email="session@example.com", name="Session"
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
with pytest.warns(DeprecationWarning, match=r"session_logout_event.*0\.0\.52"):
|
|
22
|
+
if keyword:
|
|
23
|
+
event = session_logout_event(request=request, local_account=local_account)
|
|
24
|
+
else:
|
|
25
|
+
event = session_logout_event(request, local_account=local_account)
|
|
26
|
+
|
|
27
|
+
assert event is not None
|
|
28
|
+
assert event.user_id == (
|
|
29
|
+
UUID("74fefc26-66cb-4914-a51f-c88f27e66bb3")
|
|
30
|
+
if local_account
|
|
31
|
+
else "74fefc26-66cb-4914-a51f-c88f27e66bb3"
|
|
32
|
+
)
|
|
33
|
+
assert event.email == "session@example.com"
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@pytest.mark.parametrize("has_bearer", [False, True], ids=["missing-user", "bearer-user"])
|
|
37
|
+
def test_legacy_request_without_session_identity_returns_none_and_warns(has_bearer):
|
|
38
|
+
request = Request({"type": "http"})
|
|
39
|
+
if has_bearer:
|
|
40
|
+
request.state.user = UserContext(
|
|
41
|
+
id="bearer", email="bearer@example.com", name="Bearer", auth_kind=AUTH_KIND_BEARER
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
with pytest.warns(DeprecationWarning, match=r"session_logout_event.*0\.0\.52"):
|
|
45
|
+
assert session_logout_event(request, local_account=False) is None
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def test_validated_session_user_returns_event_without_warning():
|
|
49
|
+
user = UserContext(id="ExternalSubject", email="session@example.com", name="Session")
|
|
50
|
+
|
|
51
|
+
with warnings.catch_warnings(record=True) as caught:
|
|
52
|
+
warnings.simplefilter("always")
|
|
53
|
+
event = session_logout_event(user=user, local_account=False)
|
|
54
|
+
|
|
55
|
+
assert event is not None
|
|
56
|
+
assert event.user_id == "ExternalSubject"
|
|
57
|
+
assert event.email == "session@example.com"
|
|
58
|
+
assert not caught
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def test_none_returns_none_without_warning():
|
|
62
|
+
with warnings.catch_warnings(record=True) as caught:
|
|
63
|
+
warnings.simplefilter("always")
|
|
64
|
+
assert session_logout_event(None, local_account=True) is None
|
|
65
|
+
|
|
66
|
+
assert not caught
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def test_user_and_request_cannot_be_combined():
|
|
70
|
+
user = UserContext(id="session", email="session@example.com", name="Session")
|
|
71
|
+
request = Request({"type": "http"})
|
|
72
|
+
|
|
73
|
+
with pytest.raises(TypeError, match="either user or request"):
|
|
74
|
+
session_logout_event(user, request=request, local_account=False)
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
|
+
import pytest
|
|
5
6
|
from auth.contracts.schemas import UserContext
|
|
6
7
|
|
|
7
8
|
|
|
@@ -149,13 +150,68 @@ class TestUserContextTokenFields:
|
|
|
149
150
|
assert ctx is not None
|
|
150
151
|
assert (ctx.auth_kind, ctx.scopes) == ("session", None)
|
|
151
152
|
|
|
152
|
-
async def
|
|
153
|
+
async def test_token_context_writes_no_token_identity(self):
|
|
154
|
+
"""The session boundary never carries a credential (#1178)."""
|
|
153
155
|
for scopes in (["x.read"], []):
|
|
154
|
-
ctx = UserContext(
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
156
|
+
ctx = UserContext(
|
|
157
|
+
id="1",
|
|
158
|
+
email="",
|
|
159
|
+
name="A",
|
|
160
|
+
auth_kind="pat",
|
|
161
|
+
scopes=scopes,
|
|
162
|
+
required_permission="api_tokens.use",
|
|
163
|
+
token_id="t-1",
|
|
164
|
+
)
|
|
165
|
+
payload = ctx.to_session_dict()
|
|
166
|
+
for key in ("auth_kind", "scopes", "required_permission", "token_id"):
|
|
167
|
+
assert key not in payload
|
|
168
|
+
back = UserContext.from_session_dict(payload)
|
|
169
|
+
assert back is not None
|
|
170
|
+
assert (back.auth_kind, back.scopes, back.required_permission, back.token_id) == (
|
|
171
|
+
"session",
|
|
172
|
+
None,
|
|
173
|
+
None,
|
|
174
|
+
None,
|
|
175
|
+
)
|
|
176
|
+
assert not back.is_scoped
|
|
177
|
+
|
|
178
|
+
@pytest.mark.parametrize("kind", ["pat", "service", "bearer"])
|
|
179
|
+
async def test_token_shaped_payload_restores_as_plain_session(self, kind):
|
|
180
|
+
payload = {
|
|
181
|
+
"id": "svc:1",
|
|
182
|
+
"email": "",
|
|
183
|
+
"name": "A",
|
|
184
|
+
"roles": ["user"],
|
|
185
|
+
"auth_kind": kind,
|
|
186
|
+
"scopes": ["x.read"],
|
|
187
|
+
"required_permission": "api_tokens.use",
|
|
188
|
+
"token_id": "t-1",
|
|
189
|
+
}
|
|
190
|
+
ctx = UserContext.from_session_dict(payload)
|
|
191
|
+
assert ctx is not None
|
|
192
|
+
assert (ctx.auth_kind, ctx.scopes, ctx.required_permission, ctx.token_id) == (
|
|
193
|
+
"session",
|
|
194
|
+
None,
|
|
195
|
+
None,
|
|
196
|
+
None,
|
|
197
|
+
)
|
|
198
|
+
assert ctx.roles == ["user"]
|
|
158
199
|
|
|
159
|
-
async def
|
|
200
|
+
async def test_malformed_scopes_are_ignored(self):
|
|
160
201
|
payload = {"id": "1", "email": "a@b.com", "name": "A", "scopes": "x.read"}
|
|
161
|
-
|
|
202
|
+
ctx = UserContext.from_session_dict(payload)
|
|
203
|
+
assert ctx is not None and ctx.scopes is None
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
class TestUserContextSession:
|
|
207
|
+
def test_null_email_and_name_decode_as_empty_strings(self):
|
|
208
|
+
payload = {"id": "1", "email": None, "name": None}
|
|
209
|
+
assert UserContext.from_session_dict(payload) == UserContext(id="1", email="", name="")
|
|
210
|
+
|
|
211
|
+
def test_legacy_string_none_email_decodes_as_empty(self):
|
|
212
|
+
payload = {"id": "1", "email": "None", "name": "A"}
|
|
213
|
+
assert UserContext.from_session_dict(payload) == UserContext(id="1", email="", name="A")
|
|
214
|
+
|
|
215
|
+
def test_normal_email_and_name_round_trip_unchanged(self):
|
|
216
|
+
ctx = UserContext(id="1", email="a@b.com", name="A")
|
|
217
|
+
assert UserContext.from_session_dict(ctx.to_session_dict()) == ctx
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
"""Refresh-outcome credentials are redacted from audit diffs."""
|
|
2
2
|
|
|
3
3
|
from auth.models import RefreshOutcome
|
|
4
|
-
from simple_module_db.audit import collect_audit_records
|
|
4
|
+
from simple_module_db.auditing.audit import collect_audit_records
|
|
5
5
|
from sqlalchemy.orm import Session
|
|
6
6
|
|
|
7
7
|
|
|
@@ -11,7 +11,7 @@ from keycloak.core.settings import KeycloakSettings
|
|
|
11
11
|
from keycloak.identity.provider import KeycloakAuthProvider
|
|
12
12
|
from oidc.core.settings import OidcSettings
|
|
13
13
|
from oidc.identity.provider import OidcAuthProvider
|
|
14
|
-
from simple_module_hosting.session import SessionMiddleware
|
|
14
|
+
from simple_module_hosting.pipeline.session import SessionMiddleware
|
|
15
15
|
from starlette.requests import Request
|
|
16
16
|
|
|
17
17
|
|
|
@@ -59,7 +59,7 @@ async def test_waiter_timeout_leaves_the_cookie_untouched(renewal, monkeypatch):
|
|
|
59
59
|
import hashlib
|
|
60
60
|
|
|
61
61
|
from auth.oidc_common import renewal_outcomes
|
|
62
|
-
from simple_module_core.leases import lease
|
|
62
|
+
from simple_module_core.runtime.leases import lease
|
|
63
63
|
|
|
64
64
|
r = renewal
|
|
65
65
|
name = hashlib.sha256(f"{r.keys.refresh}:opaque-session".encode()).hexdigest()
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
"""Shared session resolution preserves provider renewal policies (#1169)."""
|
|
2
|
+
|
|
3
|
+
from copy import deepcopy
|
|
4
|
+
from importlib import import_module
|
|
5
|
+
|
|
6
|
+
import pytest
|
|
7
|
+
from auth.contracts.schemas import UserContext
|
|
8
|
+
from auth.core.constants import SESSION_AUTHORITY_KEY
|
|
9
|
+
from starlette.requests import Request
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@pytest.fixture(params=["keycloak", "oidc"])
|
|
13
|
+
def provider(request):
|
|
14
|
+
module = import_module(f"{request.param}.identity.provider")
|
|
15
|
+
cls = module.KeycloakAuthProvider if request.param == "keycloak" else module.OidcAuthProvider
|
|
16
|
+
return cls()
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _request(provider, deadline=4_102_444_800):
|
|
20
|
+
return Request(
|
|
21
|
+
{
|
|
22
|
+
"type": "http",
|
|
23
|
+
"session": {
|
|
24
|
+
SESSION_AUTHORITY_KEY: provider._session_authority,
|
|
25
|
+
"user_ctx": UserContext(
|
|
26
|
+
id="cached", email="user@example.test", name="User"
|
|
27
|
+
).to_session_dict(),
|
|
28
|
+
"expires_at": deadline,
|
|
29
|
+
},
|
|
30
|
+
}
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@pytest.mark.parametrize("renew", [False, True])
|
|
35
|
+
async def test_session_resolution_honours_provider_renewal_hook(provider, monkeypatch, renew):
|
|
36
|
+
request = _request(provider)
|
|
37
|
+
original = deepcopy(request.session)
|
|
38
|
+
refreshed = UserContext(id="renewed", email="user@example.test", name="User")
|
|
39
|
+
|
|
40
|
+
async def refresh(request):
|
|
41
|
+
assert renew, "Local-only validation must never contact the IdP"
|
|
42
|
+
request.session["renewed"] = True
|
|
43
|
+
return refreshed
|
|
44
|
+
|
|
45
|
+
monkeypatch.setattr(provider, "_session_needs_renewal", lambda session: True, raising=False)
|
|
46
|
+
monkeypatch.setattr(provider, "_refresh_session", refresh)
|
|
47
|
+
|
|
48
|
+
result = await provider.resolve_session(request, renew=renew)
|
|
49
|
+
|
|
50
|
+
assert result == (refreshed if renew else None)
|
|
51
|
+
if renew:
|
|
52
|
+
assert request.session["renewed"] is True
|
|
53
|
+
else:
|
|
54
|
+
assert request.session == original
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
@pytest.mark.parametrize("deadline", [4_102_444_800, 4_102_444_800.5, 0, None, True, "future"])
|
|
58
|
+
async def test_session_expiry_keeps_provider_type_policy(provider, deadline):
|
|
59
|
+
request = _request(provider, deadline)
|
|
60
|
+
original = deepcopy(request.session)
|
|
61
|
+
|
|
62
|
+
result = await provider.resolve_session(request, renew=False)
|
|
63
|
+
|
|
64
|
+
accepted = deadline == 4_102_444_800 or (
|
|
65
|
+
provider.name == "keycloak" and deadline == 4_102_444_800.5
|
|
66
|
+
)
|
|
67
|
+
assert (result.id if result else None) == ("cached" if accepted else None)
|
|
68
|
+
assert request.session == original
|
|
@@ -5,8 +5,8 @@ from types import SimpleNamespace
|
|
|
5
5
|
import pytest
|
|
6
6
|
from auth.contracts.schemas import UserContext
|
|
7
7
|
from auth.oidc_common.session import sign_in
|
|
8
|
-
from simple_module_hosting.csrf import get_csrf_token
|
|
9
|
-
from simple_module_hosting.session import preserve_across_sign_in
|
|
8
|
+
from simple_module_hosting.auth.csrf import get_csrf_token
|
|
9
|
+
from simple_module_hosting.pipeline.session import preserve_across_sign_in
|
|
10
10
|
from starlette.requests import Request
|
|
11
11
|
|
|
12
12
|
|
|
@@ -11,8 +11,8 @@ import pytest
|
|
|
11
11
|
from auth.contracts.schemas import UserContext
|
|
12
12
|
from auth.web.deps import get_current_user
|
|
13
13
|
from fastapi import Depends, HTTPException
|
|
14
|
-
from simple_module_core.i18n import I18nRegistry, Translator
|
|
15
|
-
from simple_module_hosting.permissions import RequiresPermission
|
|
14
|
+
from simple_module_core.localization.i18n import I18nRegistry, Translator
|
|
15
|
+
from simple_module_hosting.auth.permissions import RequiresPermission
|
|
16
16
|
|
|
17
17
|
|
|
18
18
|
def _translator() -> Translator:
|
|
@@ -111,7 +111,7 @@ class TestRequirePermissionAdvanced:
|
|
|
111
111
|
def test_requires_permission_is_a_token_gate():
|
|
112
112
|
"""``token_guard`` admits API tokens on a route gated by ``RequiresPermission``."""
|
|
113
113
|
from fastapi import FastAPI
|
|
114
|
-
from simple_module_hosting.token_guard import route_admits_tokens
|
|
114
|
+
from simple_module_hosting.auth.token_guard import route_admits_tokens
|
|
115
115
|
|
|
116
116
|
app = FastAPI()
|
|
117
117
|
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
"""AuthMiddleware tolerates duck-typed principals."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import httpx
|
|
6
|
+
from auth.core.state import AuthState
|
|
7
|
+
from auth.web.middleware import AuthMiddleware
|
|
8
|
+
from fastapi import FastAPI, Request
|
|
9
|
+
from simple_module_core.web.public_routes import PublicRouteRegistry
|
|
10
|
+
from starlette.middleware.sessions import SessionMiddleware
|
|
11
|
+
from starlette.responses import JSONResponse
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class _Provider:
|
|
15
|
+
name = "stub"
|
|
16
|
+
|
|
17
|
+
def __init__(self, user):
|
|
18
|
+
self._user = user
|
|
19
|
+
|
|
20
|
+
async def resolve_user(self, request):
|
|
21
|
+
return self._user
|
|
22
|
+
|
|
23
|
+
def get_login_url(self, request, next_url=None):
|
|
24
|
+
return "/stub/login"
|
|
25
|
+
|
|
26
|
+
def get_logout_url(self, request):
|
|
27
|
+
return "/stub/logout"
|
|
28
|
+
|
|
29
|
+
def is_bearer_request(self, request):
|
|
30
|
+
return False
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
async def test_duck_typed_principal_without_auth_kind_is_tolerated():
|
|
34
|
+
"""A custom provider's principal need not carry ``auth_kind``/``token_id``."""
|
|
35
|
+
from types import SimpleNamespace
|
|
36
|
+
|
|
37
|
+
principal = SimpleNamespace(id="u1", email="d@example.com", roles=[], permissions=[])
|
|
38
|
+
app = FastAPI()
|
|
39
|
+
app.state.auth = AuthState(auth_provider=_Provider(principal), principal_resolvers=[])
|
|
40
|
+
app.state.public_routes = PublicRouteRegistry()
|
|
41
|
+
|
|
42
|
+
async def _ok(request: Request):
|
|
43
|
+
return JSONResponse({"ok": True})
|
|
44
|
+
|
|
45
|
+
app.add_api_route("/ping", _ok, methods=["GET"])
|
|
46
|
+
app.add_middleware(AuthMiddleware)
|
|
47
|
+
app.add_middleware(SessionMiddleware, secret_key="s")
|
|
48
|
+
async with httpx.AsyncClient(
|
|
49
|
+
transport=httpx.ASGITransport(app=app), base_url="http://test"
|
|
50
|
+
) as c:
|
|
51
|
+
resp = await c.get("/ping")
|
|
52
|
+
assert resp.status_code == 200
|
{simple_module_auth-0.0.49 → simple_module_auth-0.0.51}/tests/web/middleware/test_auth_middleware.py
RENAMED
|
@@ -8,7 +8,7 @@ from auth.contracts.schemas import UserContext
|
|
|
8
8
|
from auth.core.state import AuthState
|
|
9
9
|
from auth.web.middleware import AuthMiddleware
|
|
10
10
|
from fastapi import FastAPI, Request
|
|
11
|
-
from simple_module_core.public_routes import PublicRouteRegistry
|
|
11
|
+
from simple_module_core.web.public_routes import PublicRouteRegistry
|
|
12
12
|
from starlette.middleware.sessions import SessionMiddleware
|
|
13
13
|
from starlette.responses import JSONResponse
|
|
14
14
|
|
|
@@ -135,7 +135,7 @@ async def test_root_is_public(unauthenticated_app):
|
|
|
135
135
|
|
|
136
136
|
async def test_registry_public_route_skips_auth():
|
|
137
137
|
"""A module-contributed public route lets an unauthenticated GET through."""
|
|
138
|
-
from simple_module_core.public_routes import PublicRouteRegistry
|
|
138
|
+
from simple_module_core.web.public_routes import PublicRouteRegistry
|
|
139
139
|
|
|
140
140
|
registry = PublicRouteRegistry()
|
|
141
141
|
registry.add_prefix("/api/gis/stac")
|
|
@@ -150,7 +150,7 @@ async def test_registry_public_route_skips_auth():
|
|
|
150
150
|
|
|
151
151
|
async def test_registry_method_scoping_gates_other_verbs():
|
|
152
152
|
"""A GET-scoped public rule exempts GET but still gates PATCH on the same path."""
|
|
153
|
-
from simple_module_core.public_routes import PublicRouteRegistry
|
|
153
|
+
from simple_module_core.web.public_routes import PublicRouteRegistry
|
|
154
154
|
|
|
155
155
|
registry = PublicRouteRegistry()
|
|
156
156
|
registry.add_regex(r"/api/gis/datasets/[^/]+/tilejson$", methods={"GET"})
|
|
@@ -212,7 +212,7 @@ class TestDeepLinkPreservation:
|
|
|
212
212
|
|
|
213
213
|
The value is replayed into a ``Location`` header after login, so it is
|
|
214
214
|
stored relative and sanitised on the way in — see
|
|
215
|
-
``simple_module_core.redirect_safety``.
|
|
215
|
+
``simple_module_core.web.redirect_safety``.
|
|
216
216
|
"""
|
|
217
217
|
|
|
218
218
|
async def _get(self, app, path: str):
|
|
@@ -7,8 +7,8 @@ import pytest
|
|
|
7
7
|
from auth.core.state import AuthState
|
|
8
8
|
from auth.web.middleware import AuthMiddleware
|
|
9
9
|
from fastapi import FastAPI, Request
|
|
10
|
-
from simple_module_core.public_routes import PublicRouteRegistry
|
|
11
|
-
from simple_module_core.redirect_safety import SESSION_NEXT_KEY
|
|
10
|
+
from simple_module_core.web.public_routes import PublicRouteRegistry
|
|
11
|
+
from simple_module_core.web.redirect_safety import SESSION_NEXT_KEY
|
|
12
12
|
from starlette.middleware.sessions import SessionMiddleware
|
|
13
13
|
from starlette.responses import JSONResponse
|
|
14
14
|
|
|
@@ -13,8 +13,8 @@ from auth.contracts.schemas import UserContext
|
|
|
13
13
|
from auth.core.state import AuthState
|
|
14
14
|
from auth.web.middleware import AuthMiddleware
|
|
15
15
|
from fastapi import APIRouter, FastAPI
|
|
16
|
-
from simple_module_core.public_routes import PublicRouteRegistry
|
|
17
|
-
from simple_module_core.redirect_safety import SESSION_NEXT_KEY
|
|
16
|
+
from simple_module_core.web.public_routes import PublicRouteRegistry
|
|
17
|
+
from simple_module_core.web.redirect_safety import SESSION_NEXT_KEY
|
|
18
18
|
from starlette.middleware.sessions import SessionMiddleware
|
|
19
19
|
from starlette.requests import Request
|
|
20
20
|
from starlette.responses import JSONResponse
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
"""Mixed sync and async principal_guards ordering and short-circuiting."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import httpx
|
|
6
|
+
from auth.contracts.schemas import UserContext
|
|
7
|
+
from auth.core.state import AuthState
|
|
8
|
+
from auth.web.middleware import AuthMiddleware
|
|
9
|
+
from fastapi import FastAPI
|
|
10
|
+
from simple_module_core.web.public_routes import PublicRouteRegistry
|
|
11
|
+
from starlette.middleware.sessions import SessionMiddleware
|
|
12
|
+
from starlette.responses import JSONResponse
|
|
13
|
+
|
|
14
|
+
_USER = UserContext(id="u-1", email="u@example.com", name="Test User", roles=["user"])
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class _Provider:
|
|
18
|
+
async def resolve_user(self, request):
|
|
19
|
+
return _USER
|
|
20
|
+
|
|
21
|
+
def get_login_url(self, request, next_url=None):
|
|
22
|
+
return "/login"
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _make_app(guards):
|
|
26
|
+
app = FastAPI()
|
|
27
|
+
app.state.public_routes = PublicRouteRegistry()
|
|
28
|
+
app.state.auth = AuthState(auth_provider=_Provider(), principal_guards=list(guards))
|
|
29
|
+
|
|
30
|
+
@app.post("/api/action")
|
|
31
|
+
async def action():
|
|
32
|
+
return {"ok": True}
|
|
33
|
+
|
|
34
|
+
app.add_middleware(AuthMiddleware)
|
|
35
|
+
app.add_middleware(SessionMiddleware, secret_key="s" * 32)
|
|
36
|
+
return app
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
async def test_principal_guards_run_sync_and_async_in_order_and_short_circuit():
|
|
40
|
+
order: list[str] = []
|
|
41
|
+
|
|
42
|
+
def sync_allow(request):
|
|
43
|
+
order.append("sync_allow")
|
|
44
|
+
return
|
|
45
|
+
|
|
46
|
+
async def async_refuse(request):
|
|
47
|
+
order.append("async_refuse")
|
|
48
|
+
return JSONResponse({"detail": "BLOCKED"}, status_code=403)
|
|
49
|
+
|
|
50
|
+
def never_called(request):
|
|
51
|
+
order.append("never_called")
|
|
52
|
+
return
|
|
53
|
+
|
|
54
|
+
app = _make_app([sync_allow, async_refuse, never_called])
|
|
55
|
+
async with httpx.AsyncClient(
|
|
56
|
+
transport=httpx.ASGITransport(app=app), base_url="http://test"
|
|
57
|
+
) as client:
|
|
58
|
+
res = await client.post("/api/action")
|
|
59
|
+
|
|
60
|
+
assert res.status_code == 403
|
|
61
|
+
assert res.json() == {"detail": "BLOCKED"}
|
|
62
|
+
assert order == ["sync_allow", "async_refuse"]
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
async def test_principal_guards_pass_when_all_sync_and_async_return_none():
|
|
66
|
+
order: list[str] = []
|
|
67
|
+
|
|
68
|
+
async def async_ok(request):
|
|
69
|
+
order.append("async_ok")
|
|
70
|
+
return
|
|
71
|
+
|
|
72
|
+
def sync_ok(request):
|
|
73
|
+
order.append("sync_ok")
|
|
74
|
+
return
|
|
75
|
+
|
|
76
|
+
app = _make_app([async_ok, sync_ok])
|
|
77
|
+
async with httpx.AsyncClient(
|
|
78
|
+
transport=httpx.ASGITransport(app=app), base_url="http://test"
|
|
79
|
+
) as client:
|
|
80
|
+
res = await client.post("/api/action")
|
|
81
|
+
|
|
82
|
+
assert res.status_code == 200
|
|
83
|
+
assert order == ["async_ok", "sync_ok"]
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|