simple-module-auth 0.0.48__tar.gz → 0.0.50__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. {simple_module_auth-0.0.48 → simple_module_auth-0.0.50}/PKG-INFO +5 -5
  2. {simple_module_auth-0.0.48 → simple_module_auth-0.0.50}/README.md +1 -1
  3. simple_module_auth-0.0.50/auth/contracts/events.py +47 -0
  4. {simple_module_auth-0.0.48 → simple_module_auth-0.0.50}/auth/contracts/schemas.py +22 -19
  5. {simple_module_auth-0.0.48 → simple_module_auth-0.0.50}/auth/models.py +1 -1
  6. {simple_module_auth-0.0.48 → simple_module_auth-0.0.50}/auth/module.py +1 -1
  7. {simple_module_auth-0.0.48 → simple_module_auth-0.0.50}/auth/oidc_common/directory.py +8 -4
  8. simple_module_auth-0.0.50/auth/oidc_common/logout.py +26 -0
  9. {simple_module_auth-0.0.48 → simple_module_auth-0.0.50}/auth/oidc_common/renewal.py +1 -1
  10. {simple_module_auth-0.0.48 → simple_module_auth-0.0.50}/auth/oidc_common/renewal_outcomes.py +2 -2
  11. {simple_module_auth-0.0.48 → simple_module_auth-0.0.50}/auth/oidc_common/session.py +46 -4
  12. {simple_module_auth-0.0.48 → simple_module_auth-0.0.50}/auth/oidc_common/tenant.py +1 -1
  13. {simple_module_auth-0.0.48 → simple_module_auth-0.0.50}/auth/oidc_common/tokens.py +1 -1
  14. {simple_module_auth-0.0.48 → simple_module_auth-0.0.50}/auth/web/deps.py +1 -1
  15. {simple_module_auth-0.0.48 → simple_module_auth-0.0.50}/auth/web/middleware.py +11 -6
  16. {simple_module_auth-0.0.48 → simple_module_auth-0.0.50}/pyproject.toml +4 -4
  17. {simple_module_auth-0.0.48 → simple_module_auth-0.0.50}/tests/conftest.py +4 -4
  18. simple_module_auth-0.0.50/tests/contracts/events/test_auth_session_logout_events.py +74 -0
  19. {simple_module_auth-0.0.48 → simple_module_auth-0.0.50}/tests/contracts/schemas/test_auth_user_context.py +63 -7
  20. {simple_module_auth-0.0.48 → simple_module_auth-0.0.50}/tests/core/audit/test_auth_audit_redaction.py +1 -1
  21. {simple_module_auth-0.0.48 → simple_module_auth-0.0.50}/tests/core/module/test_auth_module.py +1 -1
  22. {simple_module_auth-0.0.48 → simple_module_auth-0.0.50}/tests/oidc_common/authority/test_auth_oidc_authority.py +1 -1
  23. {simple_module_auth-0.0.48 → simple_module_auth-0.0.50}/tests/oidc_common/renewal/test_auth_oidc_concurrent_renewal.py +1 -1
  24. simple_module_auth-0.0.50/tests/oidc_common/session/test_auth_oidc_session_resolution.py +68 -0
  25. {simple_module_auth-0.0.48 → simple_module_auth-0.0.50}/tests/oidc_common/session/test_auth_oidc_sign_in.py +2 -2
  26. {simple_module_auth-0.0.48 → simple_module_auth-0.0.50}/tests/web/deps/test_auth_deps.py +3 -3
  27. simple_module_auth-0.0.50/tests/web/middleware/test_auth_duck_typed_principal.py +52 -0
  28. {simple_module_auth-0.0.48 → simple_module_auth-0.0.50}/tests/web/middleware/test_auth_middleware.py +4 -4
  29. {simple_module_auth-0.0.48 → simple_module_auth-0.0.50}/tests/web/middleware/test_auth_next_target.py +2 -2
  30. {simple_module_auth-0.0.48 → simple_module_auth-0.0.50}/tests/web/middleware/test_auth_unknown_paths.py +2 -2
  31. {simple_module_auth-0.0.48 → simple_module_auth-0.0.50}/.gitignore +0 -0
  32. {simple_module_auth-0.0.48 → simple_module_auth-0.0.50}/LICENSE +0 -0
  33. {simple_module_auth-0.0.48 → simple_module_auth-0.0.50}/auth/__init__.py +0 -0
  34. {simple_module_auth-0.0.48 → simple_module_auth-0.0.50}/auth/contracts/__init__.py +0 -0
  35. {simple_module_auth-0.0.48 → simple_module_auth-0.0.50}/auth/contracts/provider.py +0 -0
  36. {simple_module_auth-0.0.48 → simple_module_auth-0.0.50}/auth/contracts/resolver.py +0 -0
  37. {simple_module_auth-0.0.48 → simple_module_auth-0.0.50}/auth/contracts/tokens.py +0 -0
  38. {simple_module_auth-0.0.48 → simple_module_auth-0.0.50}/auth/core/__init__.py +0 -0
  39. {simple_module_auth-0.0.48 → simple_module_auth-0.0.50}/auth/core/constants.py +0 -0
  40. {simple_module_auth-0.0.48 → simple_module_auth-0.0.50}/auth/core/state.py +0 -0
  41. {simple_module_auth-0.0.48 → simple_module_auth-0.0.50}/auth/locales/de.json +0 -0
  42. {simple_module_auth-0.0.48 → simple_module_auth-0.0.50}/auth/locales/en.json +0 -0
  43. {simple_module_auth-0.0.48 → simple_module_auth-0.0.50}/auth/locales/es.json +0 -0
  44. {simple_module_auth-0.0.48 → simple_module_auth-0.0.50}/auth/oidc_common/__init__.py +0 -0
  45. {simple_module_auth-0.0.48 → simple_module_auth-0.0.50}/auth/oidc_common/claims.py +0 -0
  46. {simple_module_auth-0.0.48 → simple_module_auth-0.0.50}/auth/oidc_common/jwks.py +0 -0
  47. {simple_module_auth-0.0.48 → simple_module_auth-0.0.50}/auth/oidc_common/persistence.py +0 -0
  48. {simple_module_auth-0.0.48 → simple_module_auth-0.0.50}/auth/py.typed +0 -0
  49. {simple_module_auth-0.0.48 → simple_module_auth-0.0.50}/auth/web/__init__.py +0 -0
  50. {simple_module_auth-0.0.48 → simple_module_auth-0.0.50}/auth/web/_route_match.py +0 -0
  51. {simple_module_auth-0.0.48 → simple_module_auth-0.0.50}/tests/contracts/provider/test_auth_provider_protocol.py +0 -0
  52. {simple_module_auth-0.0.48 → simple_module_auth-0.0.50}/tests/contracts/resolver/test_auth_resolver_registry.py +0 -0
  53. {simple_module_auth-0.0.48 → simple_module_auth-0.0.50}/tests/contracts/tokens/test_auth_parse_bearer.py +0 -0
  54. {simple_module_auth-0.0.48 → simple_module_auth-0.0.50}/tests/oidc_common/jwks/test_auth_oidc_jwks_cache.py +0 -0
  55. {simple_module_auth-0.0.48 → simple_module_auth-0.0.50}/tests/oidc_common/jwks/test_auth_oidc_jwt_hardening.py +0 -0
  56. {simple_module_auth-0.0.48 → simple_module_auth-0.0.50}/tests/oidc_common/renewal/test_auth_oidc_authority_outcomes.py +0 -0
  57. {simple_module_auth-0.0.48 → simple_module_auth-0.0.50}/tests/oidc_common/renewal/test_auth_oidc_outcome_logout.py +0 -0
  58. {simple_module_auth-0.0.48 → simple_module_auth-0.0.50}/tests/oidc_common/renewal/test_auth_oidc_outcome_migration.py +0 -0
  59. {simple_module_auth-0.0.48 → simple_module_auth-0.0.50}/tests/oidc_common/session/test_auth_oidc_shared_helpers.py +0 -0
  60. {simple_module_auth-0.0.48 → simple_module_auth-0.0.50}/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.48
3
+ Version: 0.0.50
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.48
29
- Requires-Dist: simple-module-db==0.0.48
30
- Requires-Dist: simple-module-hosting==0.0.48
28
+ Requires-Dist: simple-module-core==0.0.50
29
+ Requires-Dist: simple-module-db==0.0.50
30
+ Requires-Dist: simple-module-hosting==0.0.50
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)
@@ -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
@@ -98,7 +102,12 @@ class UserContext:
98
102
 
99
103
  The inverse of :meth:`from_session_dict`. Adding a new field to
100
104
  ``UserContext`` requires updating both methods here — not the
101
- AuthMiddleware cache helper, which stays schema-agnostic."""
105
+ AuthMiddleware cache helper, which stays schema-agnostic.
106
+
107
+ A session is a browser sign-in, never a credential: token identity
108
+ (``auth_kind``, ``scopes``, ``required_permission``, ``token_id``) is
109
+ never written, so whatever principal is cached, the cookie restores a
110
+ plain session principal."""
102
111
  return {
103
112
  "id": self.id,
104
113
  "email": self.email,
@@ -107,30 +116,33 @@ class UserContext:
107
116
  "roles": list(self.roles),
108
117
  "tenant_id": self.tenant_id,
109
118
  "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
119
  }
114
120
 
115
121
  @classmethod
116
122
  def from_session_dict(cls, payload: Any) -> UserContext | None:
117
123
  """Rebuild from :meth:`to_session_dict` output. Returns ``None`` on any
118
- shape mismatch so callers can fall through to a fresh DB load."""
124
+ shape mismatch so callers can fall through to a fresh DB load.
125
+
126
+ Always a plain session principal: token-identity keys in the payload
127
+ (a cookie written by an older release, or a hand-built dict) are
128
+ ignored, so a session can never restore as a scoped or token principal
129
+ — which would, for instance, earn it the ``RequiresCsrf`` token skip."""
119
130
  if not isinstance(payload, dict):
120
131
  return None
121
132
  try:
133
+ email = payload["email"]
134
+ name = payload["name"]
122
135
  return cls(
123
136
  id=str(payload["id"]),
124
- email=str(payload["email"]),
137
+ # Treat the legacy string "None" as a missing email.
138
+ email="" if email is None or email == "None" else str(email),
125
139
  email_verified=payload.get("email_verified") is True,
126
- name=str(payload["name"]),
140
+ name="" if name is None else str(name),
127
141
  roles=list(payload.get("roles") or []),
128
142
  tenant_id=payload.get("tenant_id"),
129
143
  # Absent on cookies written before the field existed.
130
144
  permissions=list(payload.get("permissions") or []),
131
- auth_kind=str(payload.get("auth_kind") or AUTH_KIND_SESSION),
132
- scopes=_scopes_from(payload.get("scopes")),
133
- required_permission=payload.get("required_permission") or None,
145
+ auth_kind=AUTH_KIND_SESSION,
134
146
  )
135
147
  except (KeyError, TypeError, ValueError):
136
148
  return None
@@ -147,12 +159,3 @@ class UserContext:
147
159
 
148
160
  def has_any_role(self, roles: list[str]) -> bool:
149
161
  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]
@@ -2,7 +2,7 @@
2
2
 
3
3
  from typing import Any, ClassVar
4
4
 
5
- from simple_module_db.base import create_module_base
5
+ from simple_module_db.models.base import create_module_base
6
6
  from sqlalchemy import JSON, BigInteger
7
7
  from sqlmodel import Field
8
8
 
@@ -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(self.model.full_name, self.model.email, term.strip())
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
@@ -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 SESSION_EXPIRES_AT_KEY, sign_in_preserved_keys
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
 
@@ -11,12 +11,13 @@ from __future__ import annotations
11
11
  import logging
12
12
  from urllib.parse import urlsplit
13
13
 
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.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, validated_prefixes
19
- from simple_module_hosting.public_access import is_public as route_is_public
14
+ from simple_module_core.modules.app_state import get_openapi_url
15
+ from simple_module_core.web.redirect_safety import SESSION_NEXT_KEY, safe_next_or_none
16
+ from simple_module_db.models.credential import current_auth_kind, current_token_id
17
+ from simple_module_db.models.listeners import current_user_id
18
+ from simple_module_hosting.frontend.inertia_deps import is_inertia_request
19
+ from simple_module_hosting.pipeline.path_matching import matches_path, validated_prefixes
20
+ from simple_module_hosting.pipeline.public_access import is_public as route_is_public
20
21
  from starlette.requests import Request
21
22
  from starlette.responses import JSONResponse, RedirectResponse
22
23
  from starlette.types import ASGIApp, Receive, Scope, Send
@@ -180,9 +181,13 @@ class AuthMiddleware:
180
181
  await refusal(scope, receive, send)
181
182
  return
182
183
  token = current_user_id.set(user_ctx.id)
184
+ kind_token = current_auth_kind.set(getattr(user_ctx, "auth_kind", None))
185
+ token_id_token = current_token_id.set(getattr(user_ctx, "token_id", None))
183
186
  try:
184
187
  await self.app(scope, receive, send)
185
188
  finally:
189
+ current_token_id.reset(token_id_token)
190
+ current_auth_kind.reset(kind_token)
186
191
  current_user_id.reset(token)
187
192
  return
188
193
 
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "simple_module_auth"
3
- version = "0.0.48"
3
+ version = "0.0.50"
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.48",
29
- "simple_module_db==0.0.48",
30
- "simple_module_hosting==0.0.48",
28
+ "simple_module_core==0.0.50",
29
+ "simple_module_db==0.0.50",
30
+ "simple_module_hosting==0.0.50",
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 test_token_fields_round_trip_and_empty_scopes_stay_capped(self):
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(id="1", email="", name="A", auth_kind="pat", scopes=scopes)
155
- back = UserContext.from_session_dict(ctx.to_session_dict())
156
- assert back == ctx
157
- assert back is not None and back.is_scoped
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 test_malformed_scopes_reject_the_payload(self):
200
+ async def test_malformed_scopes_are_ignored(self):
160
201
  payload = {"id": "1", "email": "a@b.com", "name": "A", "scopes": "x.read"}
161
- assert UserContext.from_session_dict(payload) is None
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
 
@@ -3,7 +3,7 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  from auth.module import AuthModule
6
- from simple_module_core.menu import MenuRegistry
6
+ from simple_module_core.web.menu import MenuRegistry
7
7
 
8
8
 
9
9
  class TestAuthModuleRegistration:
@@ -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
@@ -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