Skip to content
Merged
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
11 changes: 10 additions & 1 deletion docs/modules/users.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down
22 changes: 22 additions & 0 deletions docs/superpowers/plans/2026-11-11-oauth-provisioning.md
Original file line number Diff line number Diff line change
@@ -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`.
87 changes: 87 additions & 0 deletions docs/superpowers/specs/2026-11-11-oauth-provisioning-design.md
Original file line number Diff line number Diff line change
@@ -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.
7 changes: 7 additions & 0 deletions modules/users/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<base-url>/api/users/auth/<provider>/callback`
(`google`, `github`, `microsoft`, `oidc`).

Expand Down
60 changes: 56 additions & 4 deletions modules/users/tests/accounts/manager/test_users_default_role.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,19 +12,21 @@
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()),
settings,
)


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


Expand Down Expand Up @@ -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]
Original file line number Diff line number Diff line change
@@ -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"]
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
Loading
Loading