diff --git a/CHANGELOG.md b/CHANGELOG.md index d43376b5..ee60e7c8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,8 @@ All notable changes to this project are documented in this file. The format is b ### Added +- `users`: `oauth_signup_providers` and `oauth_signup_default_role` provision accounts through SSO while local signup stays closed. A first sign-in through a listed provider creates the account when the provider proved the email, whatever `allow_signup` says; the account gets `oauth_signup_default_role`, or no role when it is blank (the default), even with signup open (not the self-signup `user` role), and `admin` is refused. A listed provider without email proof is refused even with signup open. Local registration and its links still follow `allow_signup`, and unlisted providers keep the old rule. The OAuth provider fields moved to `users.core.oauth_settings.OAuthSettings`, which `UsersSettings` inherits (#874). + - `users`: `oauth_microsoft_trust_tenant_upn` (off by default) lets a site that pins `oauth_microsoft_tenant` to one tenant GUID sign in pre-approved staff with Microsoft while self-signup stays closed. A member account's `userPrincipalName` then counts as a verified email, so the first Microsoft sign-in links to an invited or verified local account with that address instead of failing with `OAUTH_USER_ALREADY_EXISTS`. Guest UPNs (`#EXT#`) and empty identities stay unverified, the `mail` attribute is never used, and with `common`, `organizations`, `consumers` or a domain-name tenant the setting has no effect and logs `users.oauth.microsoft_trust_ignored`. Turning it on trusts the tenant's admins, who can set a member's UPN to any address in the tenant's domains (#873). ## [0.0.45] — 2026-11-11 diff --git a/docs/modules/users.md b/docs/modules/users.md index a87c898c..ab70d512 100644 --- a/docs/modules/users.md +++ b/docs/modules/users.md @@ -225,6 +225,7 @@ Everything else is DB-backed (initial values are pydantic defaults; edit under U | `oauth_github_client_id` / `oauth_github_client_secret` | `""` — GitHub OAuth | | `oauth_microsoft_client_id` / `oauth_microsoft_client_secret` / `oauth_microsoft_tenant` | `""` / `""` / `"common"` — Microsoft (Entra ID) | | `oauth_microsoft_trust_tenant_upn` | `False` — treat a member's `userPrincipalName` as a verified email; only with a tenant GUID (see [Signing in pre-approved staff with Microsoft](#signing-in-pre-approved-staff-with-microsoft)) | +| `oauth_signup_providers` / `oauth_signup_default_role` | `[]` / `""` — providers that create accounts on first sign-in with `allow_signup` off, and the role those accounts get (see [Provisioning accounts through SSO](#provisioning-accounts-through-sso)) | | `oauth_oidc_client_id` / `oauth_oidc_client_secret` / `oauth_oidc_discovery_url` / `oauth_oidc_display_name` | `""` / `""` / `""` / `"OIDC"` — generic OIDC | ## Permissions @@ -539,10 +540,18 @@ For a site that admits one Entra directory, set `oauth_microsoft_tenant` to that - Guest accounts (a UPN containing `#EXT#`) and an empty id or UPN stay unverified. - With `common`, `organizations`, `consumers` (or its fixed GUID) or a domain-name tenant the setting has no effect, and the settings load logs a `users.oauth.microsoft_trust_ignored` warning. -- An unverified, un-invited local account with the same address is still refused (`OAUTH_ACCOUNT_NOT_VERIFIED`), and `allow_signup=False` still refuses a Microsoft user who has no account. +- An unverified, un-invited local account with the same address is still refused (`OAUTH_ACCOUNT_NOT_VERIFIED`), and with `allow_signup=False` a Microsoft user who has no account is refused unless `microsoft` is in `oauth_signup_providers` (see below). - A user whose UPN differs from the address they were invited with does not match the invite; invite them by their UPN. - The policy trusts whoever administers the tenant: an Entra admin who sets a member's UPN to an address that matches a verified local account (an administrator's, say) signs that member in as that account. Turn it on only for a directory whose admins you already trust with your users' identities. +### Provisioning accounts through SSO + +With `allow_signup` off, an OAuth sign-in for an identity nobody holds is refused (`OAUTH_SIGNUP_DISABLED`), so opening local signup used to be the only way to let staff get an account on their first SSO sign-in. List the providers that may provision instead: + +- `oauth_signup_providers` (for example `["microsoft"]`): a first sign-in through a listed provider creates the account, as an external (SSO-only) user, when the provider proved the email. An unproven email is refused even with `allow_signup` on, so listing a provider never widens what it can do. For Microsoft that means turning on the trusted-tenant policy above; GitHub needs a verified primary email; generic OIDC needs `email_verified: true`. +- `oauth_signup_default_role`: the role those accounts get, with `allow_signup` on too: a listed provider's accounts never get the `user` role that self-signup grants. Blank (the default) means none: the account signs in but holds no permissions until an admin grants a role. Every account the provider creates gets this role, so name one whose permissions you would give to anyone in that directory; `admin` is refused, and a name with no matching role is logged and grants nothing. +- Local registration (`POST /api/users/auth/register`, `/users/register`, the "Sign up" links) still follows `allow_signup` alone. Providers that are not listed keep the old rule: they create accounts only with `allow_signup` on, and those accounts get the `user` role. + ## Importing users from another system `users` stores passwords through fastapi-users' default `PasswordHelper`, so you can import `hashed_password` values from another system and users keep their existing passwords (no reset needed). Accepted formats: diff --git a/docs/superpowers/plans/2026-11-11-oauth-provisioning.md b/docs/superpowers/plans/2026-11-11-oauth-provisioning.md new file mode 100644 index 00000000..a47bcc11 --- /dev/null +++ b/docs/superpowers/plans/2026-11-11-oauth-provisioning.md @@ -0,0 +1,22 @@ +# Plan: provider-scoped SSO provisioning (#874) + +Design: `docs/superpowers/specs/2026-11-11-oauth-provisioning-design.md`. Sequential tasks. + +1. **Split OAuth settings** — move every `oauth_*` field, `is_tenant_guid` and the + Microsoft-trust validator from `users/core/settings.py` into + `users/core/oauth_settings.py` (`OAuthSettings(DbBackedSettings)`); `UsersSettings` + inherits it; `users/oauth/providers.py` imports from the new module. Done: users + tests green with no behaviour change. +2. **New settings** — `oauth_signup_providers`, `oauth_signup_default_role` with field + validators (known provider names; not `admin`). Test first: + `tests/oauth/providers/test_users_oauth_signup_settings.py`. +3. **Create gate** — `users/oauth/api.py`: listed + verified provider may create with + `allow_signup` off; registration flag carries the provider name. Test first: + `tests/oauth/flow/test_users_oauth_provider_signup.py`. +4. **Role** — `attach_default_role(..., role_name)` and a helper choosing the role for an + OAuth-provisioned account; `on_after_register` uses it. Tests in the same flow file + (configured role, blank, missing role, unlisted + `allow_signup=True` → `user`). +5. **Local registration stays closed** — test `/api/users/auth/register` and + `/users/register` refuse with a provider listed and `allow_signup=False`. +6. **Docs** — users README, `docs/modules/users.md`, CHANGELOG. +7. **Full check** — `make lint`, users tests; full suites in `/vf`. diff --git a/docs/superpowers/specs/2026-11-11-oauth-provisioning-design.md b/docs/superpowers/specs/2026-11-11-oauth-provisioning-design.md new file mode 100644 index 00000000..0c592b6f --- /dev/null +++ b/docs/superpowers/specs/2026-11-11-oauth-provisioning-design.md @@ -0,0 +1,87 @@ +# Provider-scoped SSO provisioning, independent of `allow_signup` (#874) + +## Goal & scope + +Let a site provision accounts on first sign-in through chosen OAuth providers +("staff sign in with the organisation's IdP and get an account") while local +email/password registration stays closed. Today the OAuth callback creates an +account only when `allow_signup` is on, and that switch also opens +`POST /api/users/auth/register`, `/users/register`, the "Sign up" links and the +`user` role for provisioned accounts. + +In scope: two `UsersSettings` fields, the callback's create gate, the role a +provisioned account gets, docs. Out of scope: everything local registration +does (it keeps following `allow_signup` alone), #876–#879. + +## Approach + +```python +oauth_signup_providers: list[str] = [] # e.g. ["microsoft"] +oauth_signup_default_role: str = "" # "" = no role; an admin grants one +``` + +- **Create gate** (`users/oauth/api.py`): a sign-in with no existing account + proceeds when `allow_signup` is on (unchanged) **or** the provider is in + `oauth_signup_providers` **and** it proved the email (`email_verified`). + Otherwise `OAUTH_SIGNUP_DISABLED` as today. A listed provider that did not + prove the email (Microsoft without #873's trust policy, GitHub with an + unverified primary) is refused with the same code. +- **Role** (`UserManager.on_after_register`): the callback already marks the + request as an OAuth registration; it now records the provider name. An + account created through a listed provider gets `oauth_signup_default_role` + (none when blank); any other OAuth-provisioned account keeps today's rule + (`user` role only with `allow_signup` on). Local self-signup unchanged. +- **Validation**: unknown provider names (not `google`, `github`, + `microsoft`, `oidc`) and `oauth_signup_default_role = "admin"` are rejected + as field errors; a role name that does not exist at sign-in is logged and the + account gets no role (same as the missing-`user`-role path today). + +Rejected: +- A single boolean "SSO signup on": would provision through every configured + provider, including ones that never prove email; the issue asks for + provider scope. +- Giving listed-provider accounts the `user` role by default: the safe default + with signup closed is "wait for an admin", as today (#543's second line). + +## Design + +- `users/core/settings.py`: the two fields (group "OAuth provisioning") and a + validator. The file is at the 300-line cap, so the OAuth provider fields, + `is_tenant_guid` and their validators move to a new + `users/core/oauth_settings.py` (`OAuthSettings(DbBackedSettings)` base, + `UsersSettings` inherits it); public names stay importable from + `users.core.settings`. +- `users/oauth/api.py`: gate as above; set the registration flag to the + provider name instead of `True`. +- `users/accounts/registration.py`: `attach_default_role(session, user, + role_name=USER_ROLE_NAME)`; a helper picks the role for a provisioned + account so `manager.py` (297 lines) stays under the cap. +- Docs: users README, `docs/modules/users.md`, CHANGELOG. + +## Decisions made + +- Field names from the issue; `oauth_signup_default_role` is `str` with `""` + meaning none (the settings store handles `str` fields; `None` adds nothing). +- `admin` is refused as the default role: auto-granting full admin to a + provider's users is never what an operator means. +- When `allow_signup` is on **and** the provider is listed, the listed-provider + rule wins (verified email required, `oauth_signup_default_role`), so listing + a provider never widens what it can do. +- Provider names are validated against the four built-in keys. + +## Testing + +- Settings: defaults, unknown provider rejected, `admin` role rejected. +- Flow (fake provider, `allow_signup=False`): listed + verified → account + created, external, gets the configured role / no role when blank; listed + + unverified → `OAUTH_SIGNUP_DISABLED`; unlisted → refused; `allow_signup=True` + + unlisted → `user` role as today; listed with a missing role → no role, warning. +- Local `/api/users/auth/register` and `/users/register` still 404/refuse with + `allow_signup=False` while a provider is listed. +- No browser QA (backend-only). + +## Risks + +- Moving the OAuth fields to a base class changes field order in the settings + editor; groups keep their names, so the form still groups them. If the + editor orders by declaration, the OAuth groups move up — acceptable. diff --git a/modules/users/README.md b/modules/users/README.md index 8941d8e9..81c69b69 100644 --- a/modules/users/README.md +++ b/modules/users/README.md @@ -100,6 +100,13 @@ the **Microsoft OAuth** group: It trusts the tenant's admins: whoever can set a member's UPN can sign in as the local account with that address. +**Provisioning through SSO with signup closed.** `oauth_signup_providers` +(e.g. `["microsoft"]`) lets those providers create an account on first sign-in +when they proved the email, while local registration keeps following +`allow_signup`. `oauth_signup_default_role` is the role those accounts get, +with signup open too (never the self-signup `user` role); blank (the default) +means none until an admin grants one, and `admin` is refused. + Each provider's callback URL is `/api/users/auth//callback` (`google`, `github`, `microsoft`, `oidc`). diff --git a/modules/users/tests/accounts/manager/test_users_default_role.py b/modules/users/tests/accounts/manager/test_users_default_role.py index 9f51f990..2a9f90bc 100644 --- a/modules/users/tests/accounts/manager/test_users_default_role.py +++ b/modules/users/tests/accounts/manager/test_users_default_role.py @@ -12,8 +12,8 @@ from users.models import OAuthAccount, Role, User, UserRole -def _manager(app, session, *, allow_signup: bool) -> UserManager: - settings = app.state.users.settings.model_copy(update={"allow_signup": allow_signup}) +def _manager(app, session, *, allow_signup: bool, **update) -> UserManager: + settings = app.state.users.settings.model_copy(update={"allow_signup": allow_signup, **update}) return UserManager( UserDatabaseWithRoles(session, User, OAuthAccount), MagicMock(send_verification=AsyncMock()), @@ -21,10 +21,12 @@ def _manager(app, session, *, allow_signup: bool) -> UserManager: ) -def _request(*, oauth: bool) -> MagicMock: +def _request(*, oauth: bool, provider: str = "oidc") -> MagicMock: request = MagicMock() request.app.state.sm.event_bus = MagicMock(publish=AsyncMock()) - request.state = SimpleNamespace(**({OAUTH_REGISTRATION_REQUEST_FLAG: True} if oauth else {})) + request.state = SimpleNamespace( + **({OAUTH_REGISTRATION_REQUEST_FLAG: provider} if oauth else {}) + ) return request @@ -73,3 +75,53 @@ async def test_a_deleted_user_role_is_not_recreated(users_app, users_db): await manager.on_after_register(user, _request(oauth=False)) assert await _roles(users_db, user) == [] assert await users_db.get(Role, USER_ROLE_ID) is None + + +async def _role_named(session, name: str) -> Role: + role = Role(name=name) + session.add(role) + await session.commit() + return role + + +async def test_listed_provider_gets_the_configured_role(users_app, users_db): + staff = await _role_named(users_db, "staff") + manager = _manager( + users_app, + users_db, + allow_signup=False, + oauth_signup_providers=["oidc"], + oauth_signup_default_role="staff", + ) + user = await _user(users_db) + await manager.on_after_register(user, _request(oauth=True)) + assert await _roles(users_db, user) == [staff.id] + + +async def test_listed_provider_with_a_blank_role_gets_none(users_app, users_db): + """Even with signup open: the listed rule wins, so no ``user`` role.""" + manager = _manager(users_app, users_db, allow_signup=True, oauth_signup_providers=["oidc"]) + user = await _user(users_db) + await manager.on_after_register(user, _request(oauth=True)) + assert await _roles(users_db, user) == [] + + +async def test_listed_provider_with_a_missing_role_gets_none(users_app, users_db, caplog): + manager = _manager( + users_app, + users_db, + allow_signup=False, + oauth_signup_providers=["oidc"], + oauth_signup_default_role="ghost", + ) + user = await _user(users_db) + await manager.on_after_register(user, _request(oauth=True)) + assert await _roles(users_db, user) == [] + assert "ghost" in caplog.text + + +async def test_unlisted_provider_with_signup_open_keeps_the_user_role(users_app, users_db): + manager = _manager(users_app, users_db, allow_signup=True, oauth_signup_providers=["microsoft"]) + user = await _user(users_db) + await manager.on_after_register(user, _request(oauth=True, provider="oidc")) + assert await _roles(users_db, user) == [USER_ROLE_ID] diff --git a/modules/users/tests/core/settings/test_users_oauth_signup_settings.py b/modules/users/tests/core/settings/test_users_oauth_signup_settings.py new file mode 100644 index 00000000..182582f7 --- /dev/null +++ b/modules/users/tests/core/settings/test_users_oauth_signup_settings.py @@ -0,0 +1,57 @@ +"""Provider-scoped SSO provisioning settings (#874).""" + +import pytest +from pydantic import ValidationError +from users.core.settings import UsersSettings + + +def test_provisioning_is_off_by_default(): + settings = UsersSettings() + assert settings.oauth_signup_providers == [] + assert settings.oauth_signup_default_role == "" + + +def test_known_providers_are_accepted(): + settings = UsersSettings(oauth_signup_providers=["microsoft", "oidc"]) + assert settings.oauth_signup_providers == ["microsoft", "oidc"] + + +def test_unknown_provider_is_rejected(): + with pytest.raises(ValidationError) as exc: + UsersSettings(oauth_signup_providers=["microsoft", "facebook"]) + assert exc.value.errors()[0]["loc"] == ("oauth_signup_providers",) + + +@pytest.mark.parametrize("role", ["admin", " Admin "]) +def test_admin_is_never_the_provisioning_role(role): + with pytest.raises(ValidationError) as exc: + UsersSettings(oauth_signup_default_role=role) + assert exc.value.errors()[0]["loc"] == ("oauth_signup_default_role",) + + +def test_a_role_name_is_stored_trimmed(): + assert UsersSettings(oauth_signup_default_role=" staff ").oauth_signup_default_role == "staff" + + +def test_signup_provider_names_match_the_buildable_providers(): + from users.core.oauth_settings import OAUTH_PROVIDER_NAMES + from users.oauth.providers import build_client_map + + configured = UsersSettings( + oauth_google_client_id="g", + oauth_google_client_secret="g", + oauth_github_client_id="h", + oauth_github_client_secret="h", + oauth_microsoft_client_id="m", + oauth_microsoft_client_secret="m", + ) + # OIDC needs a reachable discovery URL to build, so it is checked by name. + assert set(build_client_map(configured)) | {"oidc"} == OAUTH_PROVIDER_NAMES + + +def test_oauth_fields_follow_the_core_fields(): + """The settings editor groups by first appearance; the split keeps the old order.""" + fields = list(UsersSettings.model_fields) + assert fields[0] == "allow_signup" + assert fields.index("bootstrap_user_password") < fields.index("oauth_google_client_id") + assert fields[-2:] == ["oauth_signup_providers", "oauth_signup_default_role"] diff --git a/modules/users/tests/oauth/flow/test_users_oauth_error_responses.py b/modules/users/tests/oauth/flow/test_users_oauth_error_responses.py index af8a1c60..2ef34d10 100644 --- a/modules/users/tests/oauth/flow/test_users_oauth_error_responses.py +++ b/modules/users/tests/oauth/flow/test_users_oauth_error_responses.py @@ -43,7 +43,7 @@ async def test_oauth_callback_error_response(failure, detail, public_code, statu provider_client.get_profile.side_effect = GetProfileError("private provider details") app.state.users = SimpleNamespace( oauth_clients={"oidc": OAuthProvider("oidc", "OIDC", provider_client)}, - settings=SimpleNamespace(allow_signup=False), + settings=SimpleNamespace(allow_signup=False, oauth_signup_providers=[]), ) manager = AsyncMock() manager.get_by_oauth_account.side_effect = UserNotExists() diff --git a/modules/users/tests/oauth/flow/test_users_oauth_provider_signup.py b/modules/users/tests/oauth/flow/test_users_oauth_provider_signup.py new file mode 100644 index 00000000..0c29f0b9 --- /dev/null +++ b/modules/users/tests/oauth/flow/test_users_oauth_provider_signup.py @@ -0,0 +1,57 @@ +"""Listed providers provision accounts with local signup closed (#874).""" + +from __future__ import annotations + +import pytest +from _users_oauth_support import ( + find_user, + install_fake_provider, + oauth_callback, + set_users_settings, +) + + +@pytest.mark.anyio +async def test_listed_provider_with_proven_email_creates_the_account(users_app, anon_client): + set_users_settings(users_app, allow_signup=False, oauth_signup_providers=["oidc"]) + install_fake_provider(users_app, "staff-1", "staff@example.com") + + assert (await oauth_callback(anon_client)).status_code == 303 + user = await find_user(users_app, "staff@example.com") + assert user is not None and user.is_external and user.is_verified + + +@pytest.mark.anyio +@pytest.mark.parametrize("allow_signup", [False, True]) +async def test_listed_provider_without_email_proof_is_refused(users_app, anon_client, allow_signup): + """Listing a provider never widens it: an unproven email creates nothing.""" + set_users_settings(users_app, allow_signup=allow_signup, oauth_signup_providers=["microsoft"]) + install_fake_provider(users_app, "ms-1", "who@example.com", provider="microsoft") + + resp = await oauth_callback(anon_client, "microsoft") + assert resp.status_code == 403 + assert resp.json()["detail"] == "OAUTH_SIGNUP_DISABLED" + assert await find_user(users_app, "who@example.com") is None + + +@pytest.mark.anyio +async def test_unlisted_provider_still_follows_allow_signup(users_app, anon_client): + set_users_settings(users_app, allow_signup=False, oauth_signup_providers=["microsoft"]) + install_fake_provider(users_app, "oidc-1", "other@example.com") + + resp = await oauth_callback(anon_client) + assert resp.json()["detail"] == "OAUTH_SIGNUP_DISABLED" + + +@pytest.mark.anyio +async def test_local_registration_stays_closed(users_app, anon_client): + set_users_settings(users_app, allow_signup=False, oauth_signup_providers=["oidc"]) + + page = await anon_client.get("/users/register") + api = await anon_client.post( + "/api/users/auth/register", + json={"email": "local@example.com", "password": "SecurePass1!"}, + ) + assert page.status_code == 404 + assert api.status_code == 404 + assert await find_user(users_app, "local@example.com") is None diff --git a/modules/users/users/accounts/manager.py b/modules/users/users/accounts/manager.py index 1c99ebd3..2d8f6cb0 100644 --- a/modules/users/users/accounts/manager.py +++ b/modules/users/users/accounts/manager.py @@ -17,7 +17,7 @@ from simple_module_hosting.session import sign_in_preserved_keys, stamp_session_expiry from users.accounts.db_adapter import UserDatabaseWithRoles, get_user_db -from users.accounts.registration import attach_default_role +from users.accounts.registration import attach_default_role, registration_role from users.accounts.reset_revocation import ResetRevocationMixin from users.contracts.events import UserRegistered from users.core.constants import ( @@ -59,6 +59,7 @@ def __init__( self.cookie_max_age_seconds = settings.cookie_max_age_seconds # Read per request: ``get_user_manager`` builds a manager per request # from the live settings, so an admin toggling signup takes effect. + self.settings = settings self.allow_signup = settings.allow_signup self.require_verification = settings.require_verification @@ -128,20 +129,19 @@ async def on_after_register(self, user: User, request: Request | None = None) -> # find-or-create) is external: drop the random password fastapi-users # assigned and mark the account SSO-only. Fires only for *new* users — # OAuth logins that link to an existing account don't reach here. - oauth_provisioned = request is not None and getattr( - request.state, OAUTH_REGISTRATION_REQUEST_FLAG, False + oauth_provider = ( + getattr(request.state, OAUTH_REGISTRATION_REQUEST_FLAG, None) if request else None ) + oauth_provisioned = oauth_provider is not None if oauth_provisioned: user.hashed_password = None user.is_external = True await self.user_db.update(user, {"hashed_password": None, "is_external": True}) - # The OAuth callback refuses to create accounts with signups closed - # (#543); this is the second line: should one be provisioned anyway, - # it must not get the ``user`` role (file read/write, API tokens) — - # a provider's whole user base would hold it. Signups closed means - # an OAuth-provisioned account waits for an admin to grant a role. - if request is not None and (self.allow_signup or not oauth_provisioned): - await attach_default_role(self.user_db.session, user) + # Signups closed means an OAuth-provisioned account waits for an admin, + # unless its provider is listed for provisioning (#543, #874). + role = registration_role(self.settings, oauth_provider) if request else None + if role is not None: + await attach_default_role(self.user_db.session, user, role) await self._publish_user_registered(user, request) if user.is_verified: return diff --git a/modules/users/users/accounts/registration.py b/modules/users/users/accounts/registration.py index 49134028..55aac1e7 100644 --- a/modules/users/users/accounts/registration.py +++ b/modules/users/users/accounts/registration.py @@ -3,6 +3,7 @@ from __future__ import annotations import logging +from typing import TYPE_CHECKING from simple_module_db import independent_session from sqlalchemy import select @@ -12,11 +13,32 @@ from users.core.constants import USER_ROLE_NAME from users.models import Role, User, UserRole +if TYPE_CHECKING: + from users.core.settings import UsersSettings + logger = logging.getLogger(__name__) -async def attach_default_role(session: AsyncSession, user: User) -> None: - """Give a self-registered (or OAuth-provisioned) user the ``user`` role. +def registration_role(settings: UsersSettings, oauth_provider: str | None) -> str | None: + """The role a request-bound registration gets, or ``None`` for no role. + + Local self-signup gets ``user``. An account created through a provider in + ``oauth_signup_providers`` gets ``oauth_signup_default_role`` (none when + blank), even with signup open, so listing a provider never widens it (#874). + Any other OAuth-provisioned account gets ``user`` only with signup open: + with signups closed it waits for an admin (#543). + """ + if oauth_provider is None: + return USER_ROLE_NAME + if oauth_provider in settings.oauth_signup_providers: + return settings.oauth_signup_default_role or None + return USER_ROLE_NAME if settings.allow_signup else None + + +async def attach_default_role( + session: AsyncSession, user: User, role_name: str = USER_ROLE_NAME +) -> None: + """Give a self-registered (or OAuth-provisioned) user ``role_name``. Without it a fresh signup holds no permissions at all — not even ``api_tokens.use`` — until an admin assigns a role by hand (GH #488). @@ -35,12 +57,10 @@ async def attach_default_role(session: AsyncSession, user: User) -> None: await session.commit() async with independent_session(session) as checkpoint: role = ( - await checkpoint.execute(select(Role).where(col(Role.name) == USER_ROLE_NAME)) + await checkpoint.execute(select(Role).where(col(Role.name) == role_name)) ).scalar_one_or_none() if role is None: - logger.warning( - "No '%s' role exists; %s registered with no role", USER_ROLE_NAME, user_id - ) + logger.warning("No '%s' role exists; %s registered with no role", role_name, user_id) return # fastapi-users already committed the account. Keep its default role # even if a later registration hook or verification email fails. diff --git a/modules/users/users/core/oauth_settings.py b/modules/users/users/core/oauth_settings.py new file mode 100644 index 00000000..295ce7b1 --- /dev/null +++ b/modules/users/users/core/oauth_settings.py @@ -0,0 +1,122 @@ +"""OAuth / OIDC provider settings, the base of :class:`UsersSettings`. + +Split out of ``settings.py`` so the provider fields and their checks sit +together; ``UsersSettings`` inherits every field here, so callers keep reading +them from ``app.state.users.settings``. +""" + +from __future__ import annotations + +import logging +import uuid + +from pydantic import Field, field_validator, model_validator +from simple_module_core.settings_base import DbBackedSettings + +from users.core.constants import ADMIN_ROLE_NAME + +logger = logging.getLogger("users.settings") + +# The ``{provider}`` URL segments ``users.oauth.providers.build_clients`` can serve. +OAUTH_PROVIDER_NAMES = frozenset({"google", "github", "microsoft", "oidc"}) +OAUTH_PROVISIONING_GROUP = "OAuth provisioning" + +# Microsoft's fixed "consumers" tenant (personal accounts): a GUID, but not one directory. +_MICROSOFT_CONSUMERS_TENANT = uuid.UUID("9188040d-6c67-4c5b-b112-36a304b66dad") + + +def is_tenant_guid(tenant: str) -> bool: + """Whether a Microsoft ``tenant`` pins one work/school directory (a canonical GUID). + + ``common`` & co, non-canonical spellings and the personal-account ``consumers`` + tenant GUID do not qualify. + """ + try: + parsed = uuid.UUID(tenant) + except ValueError: + return False + return str(parsed) == tenant.lower() and parsed != _MICROSOFT_CONSUMERS_TENANT + + +class OAuthSettings(DbBackedSettings): + """Provider credentials and SSO policy for the ``users`` module.""" + + # OAuth / OIDC providers — configured via the admin settings UI + # (/settings/modules → Users). Credentials live in the DB-backed settings + # store and hydrate after boot; secret fields are masked in the UI (the + # same treatment the SMTP password gets). Provider changes apply live via + # the SettingsReloaded event — no restart (see users/module.py). + oauth_google_client_id: str = Field(default="", json_schema_extra={"group": "Google OAuth"}) + oauth_google_client_secret: str = Field(default="", json_schema_extra={"group": "Google OAuth"}) + oauth_github_client_id: str = Field(default="", json_schema_extra={"group": "GitHub OAuth"}) + oauth_github_client_secret: str = Field(default="", json_schema_extra={"group": "GitHub OAuth"}) + # Generic OIDC — any provider that exposes a discovery URL + # (Keycloak, Authentik, Auth0, Zitadel, ...). + oauth_oidc_client_id: str = Field(default="", json_schema_extra={"group": "OIDC"}) + oauth_oidc_client_secret: str = Field(default="", json_schema_extra={"group": "OIDC"}) + oauth_oidc_discovery_url: str = Field(default="", json_schema_extra={"group": "OIDC"}) + oauth_oidc_display_name: str = Field(default="OIDC", json_schema_extra={"group": "OIDC"}) + # Microsoft Entra ID / Microsoft accounts. tenant: "common" (any work/school + # or personal account), "organizations" (work/school only), or a tenant GUID + # to restrict sign-in to a single Entra tenant. + oauth_microsoft_client_id: str = Field( + default="", json_schema_extra={"group": "Microsoft OAuth"} + ) + oauth_microsoft_client_secret: str = Field( + default="", json_schema_extra={"group": "Microsoft OAuth"} + ) + oauth_microsoft_tenant: str = Field( + default="common", json_schema_extra={"group": "Microsoft OAuth"} + ) + # Treat a member account's userPrincipalName as a verified email, so it + # links to an invited or verified local account (#873). Only effective when + # the tenant is a GUID: that tenant verified the UPN's domain. Guest UPNs + # (``#EXT#``) stay unverified. + oauth_microsoft_trust_tenant_upn: bool = Field( + default=False, json_schema_extra={"group": "Microsoft OAuth"} + ) + + @model_validator(mode="after") + def _warn_on_ignored_microsoft_trust(self) -> OAuthSettings: + """The UPN trust policy is inert unless one tenant is pinned by GUID.""" + if self.oauth_microsoft_trust_tenant_upn and not is_tenant_guid( + self.oauth_microsoft_tenant + ): + logger.warning( + "users.oauth.microsoft_trust_ignored — oauth_microsoft_trust_tenant_upn is on " + "but oauth_microsoft_tenant=%r is not one work/school tenant GUID; Microsoft " + "emails stay unverified. Set it to your directory's GUID to trust member UPNs.", + self.oauth_microsoft_tenant, + ) + return self + + # Providers that may create an account on first sign-in with ``allow_signup`` + # off (#874), and only when the provider proved the email. Local email and + # password registration keeps following ``allow_signup`` alone. + oauth_signup_providers: list[str] = Field( + default_factory=list, json_schema_extra={"group": OAUTH_PROVISIONING_GROUP} + ) + # Role for accounts those providers create. Blank: no role until an admin + # grants one. A name with no matching role is logged and grants nothing. + oauth_signup_default_role: str = Field( + default="", json_schema_extra={"group": OAUTH_PROVISIONING_GROUP} + ) + + @field_validator("oauth_signup_providers") + @classmethod + def _known_signup_providers(cls, value: list[str]) -> list[str]: + value = [name.strip().lower() for name in value] + unknown = sorted(set(value) - OAUTH_PROVIDER_NAMES) + if unknown: + known = sorted(OAUTH_PROVIDER_NAMES) + raise ValueError(f"unknown OAuth provider(s) {unknown}; expected any of {known}") + return value + + @field_validator("oauth_signup_default_role") + @classmethod + def _no_admin_provisioning(cls, value: str) -> str: + """Auto-granting admin to a provider's whole user base is never the intent.""" + value = value.strip() + if value.lower() == ADMIN_ROLE_NAME: + raise ValueError("SSO-provisioned accounts cannot get the admin role automatically") + return value diff --git a/modules/users/users/core/settings.py b/modules/users/users/core/settings.py index 701cf855..a60e393c 100644 --- a/modules/users/users/core/settings.py +++ b/modules/users/users/core/settings.py @@ -12,7 +12,6 @@ import logging import os -import uuid from typing import Literal from pydantic import Field, field_validator, model_validator @@ -24,6 +23,7 @@ from simple_module_core.stored_settings import field_error from users.accounts.session_version_cache import SESSION_VERSION_TTL_SECONDS +from users.core.oauth_settings import OAuthSettings logger = logging.getLogger("users.settings") @@ -38,25 +38,8 @@ DEMO_SETTINGS_GROUP = "Demo account" -# Microsoft's fixed "consumers" tenant (personal accounts): a GUID, but not one directory. -_MICROSOFT_CONSUMERS_TENANT = uuid.UUID("9188040d-6c67-4c5b-b112-36a304b66dad") - - -def is_tenant_guid(tenant: str) -> bool: - """Whether a Microsoft ``tenant`` pins one work/school directory (a canonical GUID). - - ``common`` & co, non-canonical spellings and the personal-account ``consumers`` - tenant GUID do not qualify. - """ - try: - parsed = uuid.UUID(tenant) - except ValueError: - return False - return str(parsed) == tenant.lower() and parsed != _MICROSOFT_CONSUMERS_TENANT - - -class UsersSettings(DbBackedSettings): - """Local user management configuration.""" +class _UsersCoreSettings(DbBackedSettings): + """Local user management configuration; the OAuth fields come from ``OAuthSettings``.""" # ``DbBackedSettings`` (not ``BaseSettings``) so the DB is genuinely the # only source: omitting ``env_prefix`` would leave pydantic-settings @@ -196,57 +179,8 @@ def _lowercase_samesite(cls, value: object) -> object: bootstrap_user_email: str = "" bootstrap_user_password: str = "" - # OAuth / OIDC providers — configured via the admin settings UI - # (/settings/modules → Users). Credentials live in the DB-backed settings - # store and hydrate after boot; secret fields are masked in the UI (the - # same treatment the SMTP password gets). Provider changes apply live via - # the SettingsReloaded event — no restart (see users/module.py). - oauth_google_client_id: str = Field(default="", json_schema_extra={"group": "Google OAuth"}) - oauth_google_client_secret: str = Field(default="", json_schema_extra={"group": "Google OAuth"}) - oauth_github_client_id: str = Field(default="", json_schema_extra={"group": "GitHub OAuth"}) - oauth_github_client_secret: str = Field(default="", json_schema_extra={"group": "GitHub OAuth"}) - # Generic OIDC — any provider that exposes a discovery URL - # (Keycloak, Authentik, Auth0, Zitadel, ...). - oauth_oidc_client_id: str = Field(default="", json_schema_extra={"group": "OIDC"}) - oauth_oidc_client_secret: str = Field(default="", json_schema_extra={"group": "OIDC"}) - oauth_oidc_discovery_url: str = Field(default="", json_schema_extra={"group": "OIDC"}) - oauth_oidc_display_name: str = Field(default="OIDC", json_schema_extra={"group": "OIDC"}) - # Microsoft Entra ID / Microsoft accounts. tenant: "common" (any work/school - # or personal account), "organizations" (work/school only), or a tenant GUID - # to restrict sign-in to a single Entra tenant. - oauth_microsoft_client_id: str = Field( - default="", json_schema_extra={"group": "Microsoft OAuth"} - ) - oauth_microsoft_client_secret: str = Field( - default="", json_schema_extra={"group": "Microsoft OAuth"} - ) - oauth_microsoft_tenant: str = Field( - default="common", json_schema_extra={"group": "Microsoft OAuth"} - ) - # Treat a member account's userPrincipalName as a verified email, so it - # links to an invited or verified local account (#873). Only effective when - # the tenant is a GUID: that tenant verified the UPN's domain. Guest UPNs - # (``#EXT#``) stay unverified. - oauth_microsoft_trust_tenant_upn: bool = Field( - default=False, json_schema_extra={"group": "Microsoft OAuth"} - ) - @model_validator(mode="after") - def _warn_on_ignored_microsoft_trust(self) -> UsersSettings: - """The UPN trust policy is inert unless one tenant is pinned by GUID.""" - if self.oauth_microsoft_trust_tenant_upn and not is_tenant_guid( - self.oauth_microsoft_tenant - ): - logger.warning( - "users.oauth.microsoft_trust_ignored — oauth_microsoft_trust_tenant_upn is on " - "but oauth_microsoft_tenant=%r is not one work/school tenant GUID; Microsoft " - "emails stay unverified. Set it to your directory's GUID to trust member UPNs.", - self.oauth_microsoft_tenant, - ) - return self - - @model_validator(mode="after") - def _warn_on_writable_admin_demo(self) -> UsersSettings: + def _warn_on_writable_admin_demo(self) -> _UsersCoreSettings: """A writable admin demo is a public superuser — say so, loudly. Not an error: an operator who resets the demo database on a timer has @@ -266,7 +200,7 @@ def _warn_on_writable_admin_demo(self) -> UsersSettings: return self @model_validator(mode="after") - def _forbid_placeholder_token_secrets_in_production(self) -> UsersSettings: + def _forbid_placeholder_token_secrets_in_production(self) -> _UsersCoreSettings: """Fail boot if the reset/verify token secrets are still placeholders. Both are HMAC keys for fastapi-users JWTs. A well-known default lets @@ -298,3 +232,14 @@ def _forbid_placeholder_token_secrets_in_production(self) -> UsersSettings: related=["reset_password_token_secret", "verification_token_secret"], ) return self + + +class UsersSettings(OAuthSettings, _UsersCoreSettings): + """Local user management configuration. + + Bases in this order because pydantic lists fields in reverse MRO order: the + core fields first, then the OAuth ones, as the settings editor showed them + before the split (it groups fields by first appearance). + """ + + model_config = SettingsConfigDict(extra="ignore") diff --git a/modules/users/users/oauth/api.py b/modules/users/users/oauth/api.py index dd843604..854a5ebc 100644 --- a/modules/users/users/oauth/api.py +++ b/modules/users/users/oauth/api.py @@ -34,6 +34,7 @@ if TYPE_CHECKING: from users.accounts.manager import UserManager + from users.core.settings import UsersSettings from users.models import User from users.oauth.providers import OAuthProvider @@ -84,6 +85,19 @@ def _unproven_account(user: User) -> bool: return not user.is_verified and user.invited_at is None +def _may_create_account(settings: UsersSettings, provider: str, email_verified: bool) -> bool: + """Whether a first sign-in through ``provider`` may create an account. + + A provider listed in ``oauth_signup_providers`` provisions with signup + closed, but only when it proved the email; the listing applies with signup + open too, so it never widens what the provider can do (#874). Any other + provider follows ``allow_signup``. + """ + if provider in settings.oauth_signup_providers: + return email_verified + return settings.allow_signup + + def register_oauth_routes(api_router: APIRouter) -> None: """Mount the provider-agnostic OAuth dispatcher under ``/auth``.""" router = APIRouter(prefix="/auth", tags=["users-auth"]) @@ -136,15 +150,16 @@ async def callback( # with ``allow_signup`` off it must not be one: an operator enabling # SSO for staff would otherwise open signup to the provider's whole # user base (GH #543). Existing accounts still link and sign in. - if existing is None and not request.app.state.users.settings.allow_signup: + settings = request.app.state.users.settings + if existing is None and not _may_create_account(settings, provider, email_verified): return refuse_login(request, "OAUTH_SIGNUP_DISABLED", status.HTTP_403_FORBIDDEN) if existing is not None and not linked and _unproven_account(existing): return refuse_login(request, "OAUTH_ACCOUNT_NOT_VERIFIED", status.HTTP_403_FORBIDDEN) - # Mark this request so the manager's on_after_register provisions a - # *new* OAuth user as external (null password). Ignored when the login - # links to an existing account (on_after_register won't fire). - setattr(request.state, OAUTH_REGISTRATION_REQUEST_FLAG, True) + # Mark this request with the provider so the manager's on_after_register + # provisions a *new* OAuth user as external (null password) and picks its + # role. Ignored when the login links to an existing account. + setattr(request.state, OAUTH_REGISTRATION_REQUEST_FLAG, provider) try: user = await user_manager.oauth_callback( provider, diff --git a/modules/users/users/oauth/providers.py b/modules/users/users/oauth/providers.py index f4f21197..7d68bd9e 100644 --- a/modules/users/users/oauth/providers.py +++ b/modules/users/users/oauth/providers.py @@ -14,7 +14,7 @@ import logging from typing import TYPE_CHECKING, Any, NamedTuple -from users.core.settings import is_tenant_guid +from users.core.oauth_settings import is_tenant_guid if TYPE_CHECKING: from httpx_oauth.oauth2 import BaseOAuth2