simple-module-oidc 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.
Files changed (70) hide show
  1. {simple_module_oidc-0.0.49 → simple_module_oidc-0.0.51}/PKG-INFO +14 -11
  2. {simple_module_oidc-0.0.49 → simple_module_oidc-0.0.51}/README.md +9 -6
  3. simple_module_oidc-0.0.51/oidc/contracts/__init__.py +5 -0
  4. simple_module_oidc-0.0.51/oidc/contracts/user_cache.py +101 -0
  5. {simple_module_oidc-0.0.49 → simple_module_oidc-0.0.51}/oidc/core/settings.py +6 -7
  6. {simple_module_oidc-0.0.49 → simple_module_oidc-0.0.51}/oidc/identity/provider.py +10 -16
  7. simple_module_oidc-0.0.51/oidc/locales/de.json +84 -0
  8. simple_module_oidc-0.0.51/oidc/locales/en.json +84 -0
  9. {simple_module_oidc-0.0.49 → simple_module_oidc-0.0.51}/oidc/models.py +2 -2
  10. {simple_module_oidc-0.0.49 → simple_module_oidc-0.0.51}/oidc/module.py +5 -5
  11. simple_module_oidc-0.0.51/oidc/pages/i18n.generated.ts +138 -0
  12. {simple_module_oidc-0.0.49 → simple_module_oidc-0.0.51}/oidc/web/endpoints/api.py +1 -1
  13. {simple_module_oidc-0.0.49 → simple_module_oidc-0.0.51}/oidc/web/endpoints/views.py +20 -7
  14. {simple_module_oidc-0.0.49 → simple_module_oidc-0.0.51}/pyproject.toml +5 -5
  15. {simple_module_oidc-0.0.49 → simple_module_oidc-0.0.51}/tests/conftest.py +7 -6
  16. simple_module_oidc-0.0.51/tests/contracts/test_ensure_oidc_user.py +222 -0
  17. {simple_module_oidc-0.0.49 → simple_module_oidc-0.0.51}/tests/core/module/test_oidc_module.py +1 -1
  18. {simple_module_oidc-0.0.49 → simple_module_oidc-0.0.51}/tests/core/runtime/test_oidc_settings_runtime.py +1 -1
  19. {simple_module_oidc-0.0.49 → simple_module_oidc-0.0.51}/tests/identity/directory/test_oidc_directory.py +2 -2
  20. {simple_module_oidc-0.0.49 → simple_module_oidc-0.0.51}/tests/identity/provider/test_oidc_provider.py +14 -0
  21. {simple_module_oidc-0.0.49 → simple_module_oidc-0.0.51}/tests/identity/renewal/test_oidc_session_transaction.py +3 -3
  22. {simple_module_oidc-0.0.49 → simple_module_oidc-0.0.51}/tests/web/endpoints/test_oidc_keycloak_flow.py +1 -1
  23. {simple_module_oidc-0.0.49 → simple_module_oidc-0.0.51}/tests/web/endpoints/test_oidc_logout.py +35 -1
  24. simple_module_oidc-0.0.51/tests/web/endpoints/test_oidc_logout_event_identity.py +253 -0
  25. simple_module_oidc-0.0.49/oidc/contracts/__init__.py +0 -1
  26. simple_module_oidc-0.0.49/oidc/locales/de.json +0 -14
  27. simple_module_oidc-0.0.49/oidc/locales/en.json +0 -14
  28. simple_module_oidc-0.0.49/oidc/pages/i18n.generated.ts +0 -34
  29. {simple_module_oidc-0.0.49 → simple_module_oidc-0.0.51}/.gitignore +0 -0
  30. {simple_module_oidc-0.0.49 → simple_module_oidc-0.0.51}/oidc/__init__.py +0 -0
  31. {simple_module_oidc-0.0.49 → simple_module_oidc-0.0.51}/oidc/core/__init__.py +0 -0
  32. {simple_module_oidc-0.0.49 → simple_module_oidc-0.0.51}/oidc/core/constants.py +0 -0
  33. {simple_module_oidc-0.0.49 → simple_module_oidc-0.0.51}/oidc/core/presets.py +0 -0
  34. {simple_module_oidc-0.0.49 → simple_module_oidc-0.0.51}/oidc/core/runtime.py +0 -0
  35. {simple_module_oidc-0.0.49 → simple_module_oidc-0.0.51}/oidc/core/state.py +0 -0
  36. {simple_module_oidc-0.0.49 → simple_module_oidc-0.0.51}/oidc/identity/__init__.py +0 -0
  37. {simple_module_oidc-0.0.49 → simple_module_oidc-0.0.51}/oidc/identity/client.py +0 -0
  38. {simple_module_oidc-0.0.49 → simple_module_oidc-0.0.51}/oidc/identity/directory.py +0 -0
  39. {simple_module_oidc-0.0.49 → simple_module_oidc-0.0.51}/oidc/identity/discovery.py +0 -0
  40. {simple_module_oidc-0.0.49 → simple_module_oidc-0.0.51}/oidc/identity/jwks.py +0 -0
  41. {simple_module_oidc-0.0.49 → simple_module_oidc-0.0.51}/oidc/identity/persistence.py +0 -0
  42. {simple_module_oidc-0.0.49 → simple_module_oidc-0.0.51}/oidc/identity/renewal.py +0 -0
  43. {simple_module_oidc-0.0.49 → simple_module_oidc-0.0.51}/oidc/identity/tokens.py +0 -0
  44. {simple_module_oidc-0.0.49 → simple_module_oidc-0.0.51}/oidc/pages/LoggedOut.tsx +0 -0
  45. {simple_module_oidc-0.0.49 → simple_module_oidc-0.0.51}/oidc/pages/Login.tsx +0 -0
  46. {simple_module_oidc-0.0.49 → simple_module_oidc-0.0.51}/oidc/py.typed +0 -0
  47. {simple_module_oidc-0.0.49 → simple_module_oidc-0.0.51}/oidc/web/__init__.py +0 -0
  48. {simple_module_oidc-0.0.49 → simple_module_oidc-0.0.51}/oidc/web/endpoints/__init__.py +0 -0
  49. {simple_module_oidc-0.0.49 → simple_module_oidc-0.0.51}/package.json +0 -0
  50. {simple_module_oidc-0.0.49 → simple_module_oidc-0.0.51}/tests/core/module/test_oidc_boot.py +0 -0
  51. {simple_module_oidc-0.0.49 → simple_module_oidc-0.0.51}/tests/core/module/test_oidc_migration.py +0 -0
  52. {simple_module_oidc-0.0.49 → simple_module_oidc-0.0.51}/tests/core/settings/test_oidc_settings_presets.py +0 -0
  53. {simple_module_oidc-0.0.49 → simple_module_oidc-0.0.51}/tests/identity/client/test_oidc_client.py +0 -0
  54. {simple_module_oidc-0.0.49 → simple_module_oidc-0.0.51}/tests/identity/discovery/test_oidc_discovery.py +0 -0
  55. {simple_module_oidc-0.0.49 → simple_module_oidc-0.0.51}/tests/identity/jwks/test_oidc_jwks.py +0 -0
  56. {simple_module_oidc-0.0.49 → simple_module_oidc-0.0.51}/tests/identity/jwks/test_oidc_jwks_resilience.py +0 -0
  57. {simple_module_oidc-0.0.49 → simple_module_oidc-0.0.51}/tests/identity/persistence/test_oidc_cache_persistence.py +0 -0
  58. {simple_module_oidc-0.0.49 → simple_module_oidc-0.0.51}/tests/identity/provider/test_oidc_bearer_policy.py +0 -0
  59. {simple_module_oidc-0.0.49 → simple_module_oidc-0.0.51}/tests/identity/provider/test_oidc_jwt_policy.py +0 -0
  60. {simple_module_oidc-0.0.49 → simple_module_oidc-0.0.51}/tests/identity/provider/test_oidc_legacy_authority.py +0 -0
  61. {simple_module_oidc-0.0.49 → simple_module_oidc-0.0.51}/tests/identity/provider/test_oidc_sign_in_from_claims.py +0 -0
  62. {simple_module_oidc-0.0.49 → simple_module_oidc-0.0.51}/tests/identity/provider/test_oidc_tenant_resolver.py +0 -0
  63. {simple_module_oidc-0.0.49 → simple_module_oidc-0.0.51}/tests/identity/renewal/test_oidc_refresh.py +0 -0
  64. {simple_module_oidc-0.0.49 → simple_module_oidc-0.0.51}/tests/oidc_flow_helpers.py +0 -0
  65. {simple_module_oidc-0.0.49 → simple_module_oidc-0.0.51}/tests/web/endpoints/test_oidc_authorization.py +0 -0
  66. {simple_module_oidc-0.0.49 → simple_module_oidc-0.0.51}/tests/web/endpoints/test_oidc_authorization_query.py +0 -0
  67. {simple_module_oidc-0.0.49 → simple_module_oidc-0.0.51}/tests/web/endpoints/test_oidc_endpoint_auth.py +0 -0
  68. {simple_module_oidc-0.0.49 → simple_module_oidc-0.0.51}/tests/web/endpoints/test_oidc_flow.py +0 -0
  69. {simple_module_oidc-0.0.49 → simple_module_oidc-0.0.51}/tests-js/oidc-login.test.tsx +0 -0
  70. {simple_module_oidc-0.0.49 → simple_module_oidc-0.0.51}/tests-js/oidc-translations.test.tsx +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: simple_module_oidc
3
- Version: 0.0.49
3
+ Version: 0.0.51
4
4
  Summary: Generic OIDC authentication provider for simple_module — native Microsoft Entra ID, Auth0, Okta, Keycloak, and any OpenID Connect identity provider
5
5
  Project-URL: Homepage, https://github.com/antosubash/simple_module_python
6
6
  Project-URL: Repository, https://github.com/antosubash/simple_module_python
@@ -21,10 +21,10 @@ Requires-Python: >=3.12
21
21
  Requires-Dist: cryptography>=42
22
22
  Requires-Dist: httpx<0.29,>=0.27
23
23
  Requires-Dist: pyjwt[crypto]<3,>=2.8
24
- Requires-Dist: simple-module-auth==0.0.49
25
- Requires-Dist: simple-module-core==0.0.49
26
- Requires-Dist: simple-module-db==0.0.49
27
- Requires-Dist: simple-module-hosting==0.0.49
24
+ Requires-Dist: simple-module-auth==0.0.51
25
+ Requires-Dist: simple-module-core==0.0.51
26
+ Requires-Dist: simple-module-db==0.0.51
27
+ Requires-Dist: simple-module-hosting==0.0.51
28
28
  Description-Content-Type: text/markdown
29
29
 
30
30
  # simple_module_oidc
@@ -94,9 +94,12 @@ SM_OIDC_CLIENT_SECRET=<client-secret>
94
94
  SM_OIDC_ROLES_CLAIM_PATH=realm_access.roles
95
95
  ```
96
96
 
97
- `SM_OIDC_ROLES_CLAIM_PATH` seeds the roles path so the first Keycloak admin is
98
- mapped to `admin` on first sign-in (the Settings UI that edits it needs an
99
- admin). A value saved in the UI later wins.
97
+ `SM_OIDC_ROLES_CLAIM_PATH` seeds the roles claim path. Because `role_mapping`
98
+ defaults to `{}` so no shared-IdP role grants app privileges until mapped,
99
+ seed `oidc.role_mapping` after `make migrate` and before the first admin signs in
100
+ (with `simple_module_settings` installed:
101
+ `SM_OIDC_ROLE_MAPPING='{"admin":"admin","user":"user"}' uv run smpy settings import-from-env --prefix SM_OIDC_ROLE_MAPPING`).
102
+ A value saved in the Settings UI later wins.
100
103
 
101
104
  Here `<app>` includes the application's scheme and host, and `<server>` is the
102
105
  Keycloak server (including any deployment prefix). Discovery is exactly
@@ -139,7 +142,7 @@ The `entra` preset derives the discovery URL
139
142
  (`https://login.microsoftonline.com/{tenant_id}/v2.0/.well-known/openid-configuration`),
140
143
  validates the **id_token**, keys the user cache on **(issuer, `oid`)**, and
141
144
  maps Entra **app roles** (the `roles` claim) to application roles via
142
- `role_mapping` (default: `admin` and `user` map 1:1). Assign app roles in
145
+ `role_mapping` (default: `{}` — configure explicit mappings before the first admin signs in). Assign app roles in
143
146
  *Entra → App registrations → App roles* and *Enterprise applications → Users and groups*.
144
147
 
145
148
  ## Any other OIDC provider
@@ -163,7 +166,7 @@ SM_OIDC_CLIENT_SECRET=<client-secret>
163
166
  | `SM_OIDC_TENANT_ID` | — | Used by templated presets (Entra) to derive the discovery URL. |
164
167
  | `SM_OIDC_CLIENT_ID` | — | OAuth client id. |
165
168
  | `SM_OIDC_CLIENT_SECRET` | — | OAuth client secret. |
166
- | `SM_OIDC_ROLES_CLAIM_PATH` | preset | Seeds `roles_claim_path`, so the first admin can sign in before the Settings UI is reachable. |
169
+ | `SM_OIDC_ROLES_CLAIM_PATH` | preset | Seeds `roles_claim_path`; combine with seeding `oidc.role_mapping` via `smpy settings import-from-env` before the first admin signs in. |
167
170
 
168
171
  Only the six environment variables above bootstrap process wiring, secrets and the first admin's roles path.
169
172
  These variables seed defaults; explicit DB values can override them.
@@ -182,7 +185,7 @@ and tenant-claim trust read the live settings state.
182
185
  | `username_claim` / `name_claim` | `preferred_username` / `name` | Display name with fallback. |
183
186
  | `email_claim` | `email` | Display email; only generic OIDC literal `email_verified=true` attests ownership. Entra never attests it. |
184
187
  | `roles_claim_path` | `roles` for Entra, otherwise empty | Dotted claim path to role list. |
185
- | `role_mapping` | admin/user map to themselves | External roles to application roles; `tenant:*` roles are filtered on login and restored sessions. |
188
+ | `role_mapping` | `{}` (empty) | External roles to application roles; no IdP role grants app privileges until mapped, and `tenant:*` roles are filtered on login and restored sessions. |
186
189
  | `jwks_cache_ttl_seconds` | 3600 | Last-good signing keys retained on outage; unknown keys share a 30-second fetch cooldown. |
187
190
 
188
191
  ## Login, sessions and logout
@@ -65,9 +65,12 @@ SM_OIDC_CLIENT_SECRET=<client-secret>
65
65
  SM_OIDC_ROLES_CLAIM_PATH=realm_access.roles
66
66
  ```
67
67
 
68
- `SM_OIDC_ROLES_CLAIM_PATH` seeds the roles path so the first Keycloak admin is
69
- mapped to `admin` on first sign-in (the Settings UI that edits it needs an
70
- admin). A value saved in the UI later wins.
68
+ `SM_OIDC_ROLES_CLAIM_PATH` seeds the roles claim path. Because `role_mapping`
69
+ defaults to `{}` so no shared-IdP role grants app privileges until mapped,
70
+ seed `oidc.role_mapping` after `make migrate` and before the first admin signs in
71
+ (with `simple_module_settings` installed:
72
+ `SM_OIDC_ROLE_MAPPING='{"admin":"admin","user":"user"}' uv run smpy settings import-from-env --prefix SM_OIDC_ROLE_MAPPING`).
73
+ A value saved in the Settings UI later wins.
71
74
 
72
75
  Here `<app>` includes the application's scheme and host, and `<server>` is the
73
76
  Keycloak server (including any deployment prefix). Discovery is exactly
@@ -110,7 +113,7 @@ The `entra` preset derives the discovery URL
110
113
  (`https://login.microsoftonline.com/{tenant_id}/v2.0/.well-known/openid-configuration`),
111
114
  validates the **id_token**, keys the user cache on **(issuer, `oid`)**, and
112
115
  maps Entra **app roles** (the `roles` claim) to application roles via
113
- `role_mapping` (default: `admin` and `user` map 1:1). Assign app roles in
116
+ `role_mapping` (default: `{}` — configure explicit mappings before the first admin signs in). Assign app roles in
114
117
  *Entra → App registrations → App roles* and *Enterprise applications → Users and groups*.
115
118
 
116
119
  ## Any other OIDC provider
@@ -134,7 +137,7 @@ SM_OIDC_CLIENT_SECRET=<client-secret>
134
137
  | `SM_OIDC_TENANT_ID` | — | Used by templated presets (Entra) to derive the discovery URL. |
135
138
  | `SM_OIDC_CLIENT_ID` | — | OAuth client id. |
136
139
  | `SM_OIDC_CLIENT_SECRET` | — | OAuth client secret. |
137
- | `SM_OIDC_ROLES_CLAIM_PATH` | preset | Seeds `roles_claim_path`, so the first admin can sign in before the Settings UI is reachable. |
140
+ | `SM_OIDC_ROLES_CLAIM_PATH` | preset | Seeds `roles_claim_path`; combine with seeding `oidc.role_mapping` via `smpy settings import-from-env` before the first admin signs in. |
138
141
 
139
142
  Only the six environment variables above bootstrap process wiring, secrets and the first admin's roles path.
140
143
  These variables seed defaults; explicit DB values can override them.
@@ -153,7 +156,7 @@ and tenant-claim trust read the live settings state.
153
156
  | `username_claim` / `name_claim` | `preferred_username` / `name` | Display name with fallback. |
154
157
  | `email_claim` | `email` | Display email; only generic OIDC literal `email_verified=true` attests ownership. Entra never attests it. |
155
158
  | `roles_claim_path` | `roles` for Entra, otherwise empty | Dotted claim path to role list. |
156
- | `role_mapping` | admin/user map to themselves | External roles to application roles; `tenant:*` roles are filtered on login and restored sessions. |
159
+ | `role_mapping` | `{}` (empty) | External roles to application roles; no IdP role grants app privileges until mapped, and `tenant:*` roles are filtered on login and restored sessions. |
157
160
  | `jwks_cache_ttl_seconds` | 3600 | Last-good signing keys retained on outage; unknown keys share a 30-second fetch cooldown. |
158
161
 
159
162
  ## Login, sessions and logout
@@ -0,0 +1,5 @@
1
+ """OIDC module contracts."""
2
+
3
+ from oidc.contracts.user_cache import ensure_oidc_user
4
+
5
+ __all__ = ["ensure_oidc_user"]
@@ -0,0 +1,101 @@
1
+ """Public contract for pre-creating OIDC user cache rows (#1218)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import uuid as uuid_mod
6
+
7
+ from sqlalchemy import or_, select, update
8
+ from sqlalchemy.dialects.postgresql import insert as pg_insert
9
+ from sqlalchemy.dialects.sqlite import insert as sqlite_insert
10
+ from sqlalchemy.ext.asyncio import AsyncSession
11
+ from sqlmodel import col
12
+
13
+ from oidc.models import OidcUserCache
14
+
15
+
16
+ async def ensure_oidc_user(
17
+ session: AsyncSession,
18
+ issuer: str,
19
+ subject: str,
20
+ *,
21
+ email: str | None = None,
22
+ full_name: str | None = None,
23
+ user_id: uuid_mod.UUID | None = None,
24
+ ) -> uuid_mod.UUID:
25
+ """Idempotently reserve a framework UUID for an ``(issuer, subject)`` pair.
26
+
27
+ ``issuer`` must match the token's exact ``iss`` claim and ``subject`` must
28
+ match the configured ``uid_claim`` (``sub`` for ``generic``, ``oid`` for
29
+ ``entra``). Callers must commit ``session`` so subsequent OIDC sign-ins
30
+ attach to the reserved UUID.
31
+
32
+ Raises ``ValueError`` if ``issuer`` or ``subject`` is blank, or if a row
33
+ already exists for ``(issuer, subject)`` with a different ``id`` than an
34
+ explicitly requested ``user_id``.
35
+ """
36
+ if not isinstance(issuer, str) or not issuer.strip():
37
+ raise ValueError("issuer must be a non-empty string")
38
+ if not isinstance(subject, str) or not subject.strip():
39
+ raise ValueError("subject must be a non-empty string")
40
+
41
+ conn = await session.connection()
42
+ insert_fn = pg_insert if conn.dialect.name == "postgresql" else sqlite_insert
43
+ candidate_id = user_id if user_id is not None else uuid_mod.uuid4()
44
+ insert_stmt = (
45
+ insert_fn(OidcUserCache)
46
+ .values(
47
+ id=candidate_id,
48
+ issuer=issuer,
49
+ subject=subject,
50
+ email=email or "",
51
+ full_name=full_name,
52
+ last_login_at=None,
53
+ )
54
+ .on_conflict_do_nothing(index_elements=["issuer", "subject"])
55
+ )
56
+ result = await session.execute(insert_stmt)
57
+ inserted = (result.rowcount or 0) > 0
58
+
59
+ stmt = select(OidcUserCache).where(
60
+ col(OidcUserCache.issuer) == issuer,
61
+ col(OidcUserCache.subject) == subject,
62
+ )
63
+ row = (await session.execute(stmt)).scalar_one()
64
+ row_id = row.id
65
+
66
+ if user_id is not None and row_id != user_id:
67
+ raise ValueError(
68
+ f"OIDC user ({issuer!r}, {subject!r}) already exists with id {row_id}, "
69
+ f"cannot assign {user_id}"
70
+ )
71
+
72
+ if not inserted:
73
+ updated = False
74
+ if email:
75
+ res = await session.execute(
76
+ update(OidcUserCache)
77
+ .where(
78
+ col(OidcUserCache.id) == row_id,
79
+ or_(col(OidcUserCache.email).is_(None), col(OidcUserCache.email) == ""),
80
+ )
81
+ .values(email=email)
82
+ .execution_options(synchronize_session=False)
83
+ )
84
+ updated = updated or (res.rowcount or 0) > 0
85
+ if full_name:
86
+ res = await session.execute(
87
+ update(OidcUserCache)
88
+ .where(
89
+ col(OidcUserCache.id) == row_id,
90
+ or_(
91
+ col(OidcUserCache.full_name).is_(None),
92
+ col(OidcUserCache.full_name) == "",
93
+ ),
94
+ )
95
+ .values(full_name=full_name)
96
+ .execution_options(synchronize_session=False)
97
+ )
98
+ updated = updated or (res.rowcount or 0) > 0
99
+ if updated:
100
+ await session.refresh(row)
101
+ return row_id
@@ -11,10 +11,10 @@ import os
11
11
 
12
12
  from pydantic import Field, model_validator
13
13
  from pydantic_settings import SettingsConfigDict
14
- from simple_module_core.dotenv import env_str
15
- from simple_module_core.environments import NON_PROD_ENVIRONMENTS
16
- from simple_module_core.settings_base import DbBackedSettings
17
- from simple_module_core.stored_settings import field_error
14
+ from simple_module_core.settings.dotenv import env_str
15
+ from simple_module_core.settings.environments import NON_PROD_ENVIRONMENTS
16
+ from simple_module_core.settings.settings_base import DbBackedSettings
17
+ from simple_module_core.settings.stored_settings import field_error
18
18
 
19
19
  from oidc.core.presets import get_preset
20
20
 
@@ -76,9 +76,8 @@ class OidcSettings(DbBackedSettings):
76
76
  default=3600, ge=0, json_schema_extra={"requires_restart": True}
77
77
  )
78
78
 
79
- role_mapping: dict[str, str] = Field(
80
- default_factory=lambda: {"admin": "admin", "user": "user"},
81
- )
79
+ # Secure by default: no IdP role grants app privileges until mapped (#1217).
80
+ role_mapping: dict[str, str] = Field(default_factory=dict)
82
81
 
83
82
  @model_validator(mode="after")
84
83
  def _apply_preset(self) -> OidcSettings:
@@ -8,8 +8,9 @@ from typing import TYPE_CHECKING, Any
8
8
  from auth.contracts.schemas import UserContext
9
9
  from auth.contracts.tokens import AUTH_KIND_BEARER, is_api_token, parse_bearer
10
10
  from auth.oidc_common.claims import extract_nested as _extract_nested
11
+ from auth.oidc_common.session import SessionResolution
11
12
  from auth.oidc_common.tenant import trusted_tenant, without_tenant_roles
12
- from simple_module_hosting.session import SESSION_EXPIRES_AT_KEY, session_has_expired
13
+ from simple_module_hosting.pipeline.session import SESSION_EXPIRES_AT_KEY
13
14
  from starlette.requests import Request
14
15
 
15
16
  from oidc.core.constants import LOGIN_PATH, LOGOUT_PATH, SESSION_USER_KEY
@@ -28,10 +29,11 @@ class IdentityUnavailableError(Exception):
28
29
  """The user cache could not record the signed-in identity."""
29
30
 
30
31
 
31
- class OidcAuthProvider(CachePersistence, SessionRenewal):
32
+ class OidcAuthProvider(SessionResolution, CachePersistence, SessionRenewal):
32
33
  """Generic OIDC authentication with issuer-scoped identities."""
33
34
 
34
35
  name = "oidc"
36
+ _session_user_key = SESSION_USER_KEY
35
37
 
36
38
  def __init__(
37
39
  self, settings: OidcSettings | None = None, *, state: OidcState | None = None
@@ -58,20 +60,12 @@ class OidcAuthProvider(CachePersistence, SessionRenewal):
58
60
  return None
59
61
  return await self._resolve_bearer(request, credential)
60
62
 
61
- session = request.scope.get("session", {})
62
- if not self._accept_session(session):
63
- return None
64
- # Renew authority from the IdP at expiry, without interrupting the request.
65
- if type(session.get(SESSION_EXPIRES_AT_KEY)) is not int or session_has_expired(session):
66
- return await self._refresh_session(request)
67
- ctx = UserContext.from_session_dict(session.get(SESSION_USER_KEY))
68
- if ctx is not None:
69
- # The cookie froze what was decided at login; re-decide with the
70
- # current settings, so turning trust_tenant_claim off takes effect
71
- # on sessions that already exist.
72
- ctx.tenant_id = self._trusted_tenant(ctx.tenant_id)
73
- ctx.roles = self._without_tenant_roles(ctx.roles)
74
- return ctx
63
+ return await self.resolve_session(request)
64
+
65
+ def _session_needs_renewal(self, session: dict[str, Any]) -> bool:
66
+ return type(
67
+ session.get(SESSION_EXPIRES_AT_KEY)
68
+ ) is not int or super()._session_needs_renewal(session)
75
69
 
76
70
  def get_login_url(self, request: Request | None, next_url: str | None = None) -> str:
77
71
  return LOGIN_PATH
@@ -0,0 +1,84 @@
1
+ {
2
+ "login": {
3
+ "redirecting": "Weiterleitung zum Identitätsanbieter…",
4
+ "manual": "Keine Weiterleitung? Manuell fortfahren"
5
+ },
6
+ "logout": {
7
+ "title": "Abgemeldet",
8
+ "message": "Sie wurden erfolgreich von dieser App abgemeldet.",
9
+ "sign_in_again": "Erneut anmelden"
10
+ },
11
+ "nav": {
12
+ "logout": "Abmelden"
13
+ },
14
+ "settings_form": {
15
+ "title": "Anmeldung (OIDC)",
16
+ "description": "Verbindung zu Ihrem OpenID-Connect-Anbieter, Claim-Zuordnung und API-Zugriff.",
17
+ "fields": {
18
+ "provider": {
19
+ "label": "Anbieter",
20
+ "help": "Welche Anbieter-Vorlage verwendet wird, etwa Entra oder ein generischer OIDC-Anbieter. Eine Änderung erfordert einen Neustart."
21
+ },
22
+ "discovery_url": {
23
+ "label": "Discovery-URL",
24
+ "help": "Adresse des Discovery-Dokuments des Anbieters. Leer: wird, wo der Anbieter es unterstützt, aus der Tenant-ID abgeleitet."
25
+ },
26
+ "tenant_id": {
27
+ "label": "Tenant-ID",
28
+ "help": "ID des Verzeichnisses (Tenant) für Anbieter wie Entra. Nur Single-Tenant."
29
+ },
30
+ "client_id": {
31
+ "label": "Client-ID",
32
+ "help": "ID des Clients, der für diese Anwendung beim Anbieter registriert ist."
33
+ },
34
+ "client_secret": {
35
+ "label": "Client-Secret",
36
+ "help": "Geheimnis dieses Clients. Nach dem Speichern wird es ausgeblendet."
37
+ },
38
+ "api_audience": {
39
+ "label": "API-Audience",
40
+ "help": "Audience, die Bearer-Tokens für die API haben müssen. Leer lassen, um die Bearer-Authentifizierung auszuschalten."
41
+ },
42
+ "api_allowed_client_ids": {
43
+ "label": "Erlaubte API-Clients",
44
+ "help": "Client-IDs außer dem der Anwendung selbst, die die API mit einem Bearer-Token aufrufen dürfen. Leer: nur der Client dieser Anwendung."
45
+ },
46
+ "trust_tenant_claim": {
47
+ "label": "Mandanten-Claim in Tokens vertrauen",
48
+ "help": "Den im Token genannten Mandanten verwenden. Nur aktivieren, wenn Benutzer diesen Claim nicht beeinflussen können."
49
+ },
50
+ "scope": {
51
+ "label": "Scopes",
52
+ "help": "Beim Anmelden angeforderte Scopes. Unverändert lassen, um die Vorgabe des Anbieters zu nutzen."
53
+ },
54
+ "uid_claim": {
55
+ "label": "Claim für die Benutzer-ID",
56
+ "help": "Token-Claim, der den Benutzer eindeutig identifiziert."
57
+ },
58
+ "username_claim": {
59
+ "label": "Claim für den Benutzernamen",
60
+ "help": "Token-Claim, der zuerst für den angezeigten Namen geprüft wird."
61
+ },
62
+ "email_claim": {
63
+ "label": "Claim für die E-Mail-Adresse",
64
+ "help": "Token-Claim mit der E-Mail-Adresse."
65
+ },
66
+ "name_claim": {
67
+ "label": "Claim für den Anzeigenamen",
68
+ "help": "Token-Claim für den angezeigten Namen, wenn der Benutzername-Claim fehlt oder leer ist."
69
+ },
70
+ "roles_claim_path": {
71
+ "label": "Pfad des Rollen-Claims",
72
+ "help": "Wo die Rollenliste im Token steht, als Punkt-Pfad angegeben."
73
+ },
74
+ "jwks_cache_ttl_seconds": {
75
+ "label": "Cache-Dauer der Signaturschlüssel (Sekunden)",
76
+ "help": "Wie lange die Signaturschlüssel des Anbieters wiederverwendet werden, bevor sie neu geladen werden. Bei 0 werden sie bei Bedarf neu geladen, höchstens alle 30 Sekunden; schlägt das fehl, bleibt der letzte gültige Satz in Gebrauch."
77
+ },
78
+ "role_mapping": {
79
+ "label": "Rollenzuordnung",
80
+ "help": "Ordnet Rollennamen des Anbieters den anwendungsweiten Rollen dieser App zu. Mandantenrollen kommen aus Mitgliedschaften."
81
+ }
82
+ }
83
+ }
84
+ }
@@ -0,0 +1,84 @@
1
+ {
2
+ "login": {
3
+ "redirecting": "Redirecting to identity provider\u2026",
4
+ "manual": "Not redirected? Continue manually"
5
+ },
6
+ "logout": {
7
+ "title": "Signed Out",
8
+ "message": "You have been signed out successfully.",
9
+ "sign_in_again": "Sign in again"
10
+ },
11
+ "nav": {
12
+ "logout": "Logout"
13
+ },
14
+ "settings_form": {
15
+ "title": "Sign-in (OIDC)",
16
+ "description": "Connection to your OpenID Connect provider, claim mapping and API access.",
17
+ "fields": {
18
+ "provider": {
19
+ "label": "Provider",
20
+ "help": "Which provider preset to use, such as Entra or a generic OIDC provider. Changing it needs a restart."
21
+ },
22
+ "discovery_url": {
23
+ "label": "Discovery URL",
24
+ "help": "Address of the provider's discovery document. If blank, it is derived from the tenant ID where the provider supports that."
25
+ },
26
+ "tenant_id": {
27
+ "label": "Tenant ID",
28
+ "help": "Directory (tenant) ID for providers such as Entra. Single-tenant only."
29
+ },
30
+ "client_id": {
31
+ "label": "Client ID",
32
+ "help": "ID of the client registered for this app at the provider."
33
+ },
34
+ "client_secret": {
35
+ "label": "Client secret",
36
+ "help": "Secret of that client. It is hidden once saved."
37
+ },
38
+ "api_audience": {
39
+ "label": "API audience",
40
+ "help": "Audience that bearer tokens for the API must have. Leave blank to turn off bearer authentication."
41
+ },
42
+ "api_allowed_client_ids": {
43
+ "label": "Allowed API clients",
44
+ "help": "Client IDs besides this app's own that may call the API with a bearer token. Empty: only this app's client."
45
+ },
46
+ "trust_tenant_claim": {
47
+ "label": "Trust tenant claim in tokens",
48
+ "help": "Use the tenant named in the token. Only enable if users cannot influence that claim."
49
+ },
50
+ "scope": {
51
+ "label": "Scopes",
52
+ "help": "Scopes requested at sign-in. Leave as is to use the provider preset."
53
+ },
54
+ "uid_claim": {
55
+ "label": "User ID claim",
56
+ "help": "Token claim that uniquely identifies the user."
57
+ },
58
+ "username_claim": {
59
+ "label": "Username claim",
60
+ "help": "Token claim checked first for the name the app displays."
61
+ },
62
+ "email_claim": {
63
+ "label": "Email claim",
64
+ "help": "Token claim holding the email address."
65
+ },
66
+ "name_claim": {
67
+ "label": "Display name claim",
68
+ "help": "Token claim used for the displayed name when the username claim is missing or empty."
69
+ },
70
+ "roles_claim_path": {
71
+ "label": "Roles claim path",
72
+ "help": "Where the list of roles sits inside the token, written as a dotted path."
73
+ },
74
+ "jwks_cache_ttl_seconds": {
75
+ "label": "Signing key cache lifetime (seconds)",
76
+ "help": "How long the provider's signing keys are reused before being fetched again. With 0 they are refetched on demand, at most every 30 seconds, and the last good set is kept if a fetch fails."
77
+ },
78
+ "role_mapping": {
79
+ "label": "Role mapping",
80
+ "help": "Maps role names from the provider to this app's app-wide roles. Tenant roles come from memberships."
81
+ }
82
+ }
83
+ }
84
+ }
@@ -5,8 +5,8 @@ from __future__ import annotations
5
5
  import uuid as uuid_mod
6
6
  from datetime import datetime
7
7
 
8
- from simple_module_db.base import create_module_base
9
- from simple_module_db.types import AwareDateTime
8
+ from simple_module_db.models.base import create_module_base
9
+ from simple_module_db.models.types import AwareDateTime
10
10
  from sqlalchemy import UniqueConstraint
11
11
  from sqlmodel import Field
12
12
 
@@ -4,11 +4,11 @@ from __future__ import annotations
4
4
 
5
5
  from typing import TYPE_CHECKING
6
6
 
7
- from simple_module_core.menu import MenuItem, MenuRegistry, MenuSection
8
- from simple_module_core.module import ModuleBase, ModuleMeta
9
- from simple_module_core.module_settings import register_module_settings
10
- from simple_module_core.role_directory import MappedRoleDirectory, set_role_directory
11
- from simple_module_core.user_directory import set_user_directory
7
+ from simple_module_core.access.role_directory import MappedRoleDirectory, set_role_directory
8
+ from simple_module_core.access.user_directory import set_user_directory
9
+ from simple_module_core.modules.module import ModuleBase, ModuleMeta
10
+ from simple_module_core.settings.module_settings import register_module_settings
11
+ from simple_module_core.web.menu import MenuItem, MenuRegistry, MenuSection
12
12
 
13
13
  from oidc.core.constants import (
14
14
  _MODULE_AUTH,
@@ -0,0 +1,138 @@
1
+ import '@simple-module-py/i18n';
2
+
3
+ // AUTO-GENERATED by simple_module_hosting.i18n.i18n_manifest — do not edit by hand.
4
+ // Regenerate by booting the host in development mode or `make gen-i18n`.
5
+
6
+ export const keys = {
7
+ oidc: {
8
+ login: {
9
+ manual: 'oidc.login.manual',
10
+ redirecting: 'oidc.login.redirecting',
11
+ },
12
+ logout: {
13
+ message: 'oidc.logout.message',
14
+ sign_in_again: 'oidc.logout.sign_in_again',
15
+ title: 'oidc.logout.title',
16
+ },
17
+ nav: {
18
+ logout: 'oidc.nav.logout',
19
+ },
20
+ settings_form: {
21
+ description: 'oidc.settings_form.description',
22
+ fields: {
23
+ api_allowed_client_ids: {
24
+ help: 'oidc.settings_form.fields.api_allowed_client_ids.help',
25
+ label: 'oidc.settings_form.fields.api_allowed_client_ids.label',
26
+ },
27
+ api_audience: {
28
+ help: 'oidc.settings_form.fields.api_audience.help',
29
+ label: 'oidc.settings_form.fields.api_audience.label',
30
+ },
31
+ client_id: {
32
+ help: 'oidc.settings_form.fields.client_id.help',
33
+ label: 'oidc.settings_form.fields.client_id.label',
34
+ },
35
+ client_secret: {
36
+ help: 'oidc.settings_form.fields.client_secret.help',
37
+ label: 'oidc.settings_form.fields.client_secret.label',
38
+ },
39
+ discovery_url: {
40
+ help: 'oidc.settings_form.fields.discovery_url.help',
41
+ label: 'oidc.settings_form.fields.discovery_url.label',
42
+ },
43
+ email_claim: {
44
+ help: 'oidc.settings_form.fields.email_claim.help',
45
+ label: 'oidc.settings_form.fields.email_claim.label',
46
+ },
47
+ jwks_cache_ttl_seconds: {
48
+ help: 'oidc.settings_form.fields.jwks_cache_ttl_seconds.help',
49
+ label: 'oidc.settings_form.fields.jwks_cache_ttl_seconds.label',
50
+ },
51
+ name_claim: {
52
+ help: 'oidc.settings_form.fields.name_claim.help',
53
+ label: 'oidc.settings_form.fields.name_claim.label',
54
+ },
55
+ provider: {
56
+ help: 'oidc.settings_form.fields.provider.help',
57
+ label: 'oidc.settings_form.fields.provider.label',
58
+ },
59
+ role_mapping: {
60
+ help: 'oidc.settings_form.fields.role_mapping.help',
61
+ label: 'oidc.settings_form.fields.role_mapping.label',
62
+ },
63
+ roles_claim_path: {
64
+ help: 'oidc.settings_form.fields.roles_claim_path.help',
65
+ label: 'oidc.settings_form.fields.roles_claim_path.label',
66
+ },
67
+ scope: {
68
+ help: 'oidc.settings_form.fields.scope.help',
69
+ label: 'oidc.settings_form.fields.scope.label',
70
+ },
71
+ tenant_id: {
72
+ help: 'oidc.settings_form.fields.tenant_id.help',
73
+ label: 'oidc.settings_form.fields.tenant_id.label',
74
+ },
75
+ trust_tenant_claim: {
76
+ help: 'oidc.settings_form.fields.trust_tenant_claim.help',
77
+ label: 'oidc.settings_form.fields.trust_tenant_claim.label',
78
+ },
79
+ uid_claim: {
80
+ help: 'oidc.settings_form.fields.uid_claim.help',
81
+ label: 'oidc.settings_form.fields.uid_claim.label',
82
+ },
83
+ username_claim: {
84
+ help: 'oidc.settings_form.fields.username_claim.help',
85
+ label: 'oidc.settings_form.fields.username_claim.label',
86
+ },
87
+ },
88
+ title: 'oidc.settings_form.title',
89
+ },
90
+ },
91
+ } as const;
92
+
93
+ type ModuleTranslationResources = {
94
+ readonly 'oidc.login.manual': '';
95
+ readonly 'oidc.login.redirecting': '';
96
+ readonly 'oidc.logout.message': '';
97
+ readonly 'oidc.logout.sign_in_again': '';
98
+ readonly 'oidc.logout.title': '';
99
+ readonly 'oidc.nav.logout': '';
100
+ readonly 'oidc.settings_form.description': '';
101
+ readonly 'oidc.settings_form.fields.api_allowed_client_ids.help': '';
102
+ readonly 'oidc.settings_form.fields.api_allowed_client_ids.label': '';
103
+ readonly 'oidc.settings_form.fields.api_audience.help': '';
104
+ readonly 'oidc.settings_form.fields.api_audience.label': '';
105
+ readonly 'oidc.settings_form.fields.client_id.help': '';
106
+ readonly 'oidc.settings_form.fields.client_id.label': '';
107
+ readonly 'oidc.settings_form.fields.client_secret.help': '';
108
+ readonly 'oidc.settings_form.fields.client_secret.label': '';
109
+ readonly 'oidc.settings_form.fields.discovery_url.help': '';
110
+ readonly 'oidc.settings_form.fields.discovery_url.label': '';
111
+ readonly 'oidc.settings_form.fields.email_claim.help': '';
112
+ readonly 'oidc.settings_form.fields.email_claim.label': '';
113
+ readonly 'oidc.settings_form.fields.jwks_cache_ttl_seconds.help': '';
114
+ readonly 'oidc.settings_form.fields.jwks_cache_ttl_seconds.label': '';
115
+ readonly 'oidc.settings_form.fields.name_claim.help': '';
116
+ readonly 'oidc.settings_form.fields.name_claim.label': '';
117
+ readonly 'oidc.settings_form.fields.provider.help': '';
118
+ readonly 'oidc.settings_form.fields.provider.label': '';
119
+ readonly 'oidc.settings_form.fields.role_mapping.help': '';
120
+ readonly 'oidc.settings_form.fields.role_mapping.label': '';
121
+ readonly 'oidc.settings_form.fields.roles_claim_path.help': '';
122
+ readonly 'oidc.settings_form.fields.roles_claim_path.label': '';
123
+ readonly 'oidc.settings_form.fields.scope.help': '';
124
+ readonly 'oidc.settings_form.fields.scope.label': '';
125
+ readonly 'oidc.settings_form.fields.tenant_id.help': '';
126
+ readonly 'oidc.settings_form.fields.tenant_id.label': '';
127
+ readonly 'oidc.settings_form.fields.trust_tenant_claim.help': '';
128
+ readonly 'oidc.settings_form.fields.trust_tenant_claim.label': '';
129
+ readonly 'oidc.settings_form.fields.uid_claim.help': '';
130
+ readonly 'oidc.settings_form.fields.uid_claim.label': '';
131
+ readonly 'oidc.settings_form.fields.username_claim.help': '';
132
+ readonly 'oidc.settings_form.fields.username_claim.label': '';
133
+ readonly 'oidc.settings_form.title': '';
134
+ };
135
+
136
+ declare module '@simple-module-py/i18n' {
137
+ interface TranslationResources extends ModuleTranslationResources {}
138
+ }
@@ -8,7 +8,7 @@ import time
8
8
 
9
9
  from auth.oidc_common.session import sign_in, stale_callback
10
10
  from fastapi import APIRouter, HTTPException, Request
11
- from simple_module_hosting.auth_policy import login_redirect_url
11
+ from simple_module_hosting.auth.auth_policy import login_redirect_url
12
12
  from starlette.responses import RedirectResponse
13
13
 
14
14
  from oidc.core.constants import (