Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@ All notable changes to this project are documented in this file. The format is b

- `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).

### Changed

- `users`: Microsoft sign-in is OpenID Connect. It runs authorization-code + PKCE (S256) + nonce on the tenant's v2.0 endpoints and takes the identity from the validated ID token (RS256 against Entra's JWKS, exact issuer, `aud`/`azp`, `exp`/`iat`, nonce) instead of Graph `/me`. A tenant GUID also requires the token's `tid` to match, `organizations` refuses personal accounts and `consumers` accepts only them. The linked account id keeps the value Graph returned, so existing links keep matching; the email is the optional `upn` claim when present, else `preferred_username` (the UPN for members; add the `upn` optional claim if email is an alternate login ID). The trusted-tenant policy (#873) now also treats an `idp` claim naming another issuer as a guest, besides `#EXT#`. The OAuth callback passes the whole token response to `OAuthProvider.get_identity(token, login)` and keeps a per-login PKCE verifier and nonce in the session for providers that use them. **Behaviour change:** the Entra app registration needs the `openid`, `profile` and `email` delegated permissions (usually present by default); Graph `User.Read` is no longer requested. Code that calls `OAuthProvider.get_identity` with an access-token string must pass the token response dict (#876).

## [0.0.45] — 2026-11-11

### Fixed
Expand Down
16 changes: 12 additions & 4 deletions docs/modules/users.md
Original file line number Diff line number Diff line change
Expand Up @@ -224,7 +224,7 @@ Everything else is DB-backed (initial values are pydantic defaults; edit under U
| `oauth_google_client_id` / `oauth_google_client_secret` | `""` — Google OAuth |
| `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_microsoft_trust_tenant_upn` | `False` — treat a member's UPN (the `upn` claim, else `preferred_username`) 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 |

Expand Down Expand Up @@ -527,18 +527,26 @@ Built-in provider keys (the `{provider}` URL segment):
|---|---|---|
| Google | `google` | |
| GitHub | `github` | |
| Microsoft (Entra ID) | `microsoft` | `oauth_microsoft_tenant`: `"common"` (any account), `"organizations"` (work/school), or a tenant GUID |
| Microsoft (Entra ID) | `microsoft` | OpenID Connect with PKCE and a nonce; identity from the validated ID token (see below). `oauth_microsoft_tenant`: `"common"` (any account), `"organizations"` (work/school), `"consumers"` (personal), or a tenant GUID |
| Generic OIDC | `oidc` | any provider exposing a discovery URL (Keycloak, Authentik, Auth0, Zitadel, …); discovery failure logs + disables rather than breaking boot |

A single dispatcher pair (`/api/users/auth/{provider}/login` + `/callback`) serves every provider; the client is resolved per request from the cache. The `/callback` returns a 303 redirect (not the stock fastapi-users 204) so Inertia lands on a real page, with the auth cookie attached. Find-or-create + email association goes through `UserManager.oauth_callback` (`associate_by_email` and `is_verified_by_default` both follow whether the provider proved the email; Microsoft never does unless the opt-in below is on); state CSRF uses the signed session cookie. Linked accounts are stored in `users_oauth_account`. A **newly provisioned** OAuth account is marked external (see below); an existing password account linked by email keeps its password and is left unchanged.

### Microsoft sign-in

Microsoft uses OpenID Connect on the tenant's v2.0 endpoints (`https://login.microsoftonline.com/<tenant>/oauth2/v2.0/…`), built from `oauth_microsoft_tenant` with no discovery fetch at boot. Each login stores a PKCE verifier (S256) and a nonce in the session next to the state; the callback sends the verifier to the token endpoint and validates the returned ID token: RS256 signature against Entra's JWKS, the exact issuer `https://login.microsoftonline.com/<tid>/v2.0`, `aud` (and `azp`) equal to the client id, `exp`/`iat`, and the nonce. A tenant GUID also requires `tid` to equal it; `organizations` refuses personal accounts and `consumers` accepts only them. A failed check refuses the sign-in with `OAUTH_PROVIDER_ERROR`.

- The app registration needs the `openid`, `profile` and `email` delegated permissions; Graph `User.Read` is no longer requested.
- The linked account id is the value Graph `/me` returned before: the `oid` claim for work and school accounts, and for a personal account the 16 hex digits `oid` carries after its zero prefix. Links made before this change keep matching.
- The email is the optional `upn` claim when the app registration adds it, else `preferred_username`: the UPN for a tenant member, the home address for a guest. With email as an alternate login ID turned on, `preferred_username` is the address the user typed, so add the `upn` optional claim (Token configuration → Add optional claim → ID → `upn`) to keep matching invites by UPN. The optional `email` claim is not used, and a phone-number username counts as no email.

### Signing in pre-approved staff with Microsoft

Microsoft email claims are tenant-controlled, so by default a Microsoft sign-in never proves an email ("nOAuth"). That keeps `common`/`organizations` safe, but it also means that with self-signup closed nobody can sign in with Microsoft: a verified local account or pending invite with the same address is refused with `OAUTH_USER_ALREADY_EXISTS`.

For a site that admits one Entra directory, set `oauth_microsoft_tenant` to that tenant's GUID and turn on `oauth_microsoft_trust_tenant_upn`. A **member** account's `userPrincipalName` is on a domain the tenant verified, so it then counts as a verified email: it links to an invited or verified local account with that address, and an account it creates starts verified. The account id stays the Graph `id`; the `mail` attribute is never used.
For a site that admits one Entra directory, set `oauth_microsoft_tenant` to that tenant's GUID and turn on `oauth_microsoft_trust_tenant_upn`. A **member** account's UPN (the ID token's `upn` claim, else `preferred_username`) is on a domain the tenant verified, so it then counts as a verified email: it links to an invited or verified local account with that address, and an account it creates starts verified. The `mail` attribute and the `email` claim are never used.

- Guest accounts (a UPN containing `#EXT#`) and an empty id or UPN stay unverified.
- Guest and other external accounts (an `idp` claim naming another issuer, or a UPN containing `#EXT#`) and an empty username 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 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.
Expand Down
15 changes: 15 additions & 0 deletions docs/superpowers/plans/2026-11-11-microsoft-oidc-provider.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# Plan: Microsoft sign-in over OIDC (#876)

Design: `docs/superpowers/specs/2026-11-11-microsoft-oidc-provider-design.md`. Sequential.

1. `users/oauth/microsoft.py`: `MicrosoftOidc` (Graph client subclass on v2.0 endpoints,
scopes `openid profile email`), ID-token validation with per-`tid` `JWKSCache`,
tenant acceptance, `graph_account_id`, trust rule. Tests:
`tests/oauth/providers/test_users_oauth_microsoft_id_token.py` with a local RSA key.
2. `OAuthProvider`: `uses_pkce`, `authorization_url`, `exchange_code`,
`get_identity(token, login)`; `build_clients` builds `MicrosoftOidc` lazily.
3. `users/oauth/api.py`: per-login verifier + nonce in the session, spent with the state;
missing secrets refused. Tests: `tests/oauth/flow/test_users_oauth_microsoft_pkce.py`;
existing Microsoft flow tests move to the signed-token helper
(`tests/_users_microsoft_support.py`).
4. Docs + CHANGELOG (behaviour change). 5. `make lint`, users tests; suites in `/vf`.
106 changes: 106 additions & 0 deletions docs/superpowers/specs/2026-11-11-microsoft-oidc-provider-design.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
# Microsoft sign-in over OpenID Connect, with PKCE and nonce (#876)

## Goal & scope

The `users` Microsoft provider signs in with OAuth2 + Graph `/me` (`id`,
`userPrincipalName`). It never sees an ID token, never checks the signed-in
account's tenant, and the generic callback hands providers only the access
token, with no session-bound place for a PKCE verifier or nonce.

In scope:
1. The generic callback passes the **whole token response** to
`OAuthProvider.get_identity`, and keeps a per-login PKCE verifier and OIDC
nonce in the session next to the state (generic plumbing; a provider opts in).
2. Microsoft becomes OIDC: authorization-code + PKCE (S256) + nonce, scopes
`openid profile email`, and a validated ID token (RS256 against Entra's JWKS,
exact issuer, `aud` = client id, `azp`, `exp`/`iat`, `nonce`), reusing
`auth.oidc_common.jwks.JWKSCache`. A GUID tenant requires `tid` to equal it.
3. Graph is no longer used for sign-in (no `User.Read` scope).

Out of scope: the generic `oidc` provider keeps its current userinfo flow (it
can opt in to the new plumbing later); storing the profile (#877), trusted
email domains (#878), a development discovery override for a local IdP (#879).

## Approach

Microsoft's v2.0 endpoints are fixed per tenant segment
(`https://login.microsoftonline.com/<tenant>/oauth2/v2.0/{authorize,token}`,
JWKS `…/discovery/v2.0/keys`, issuer `…/<tid>/v2.0`), so the provider builds
them from `oauth_microsoft_tenant` with no network call at boot. They sit in
one small endpoints object that #879 can later fill from a discovery document.

Rejected:
- Discovery at client construction (`httpx_oauth`'s `OpenID`, as the generic
provider does): a synchronous fetch on every boot and settings reload, and a
Microsoft outage would disable the provider until the next reload.
- Keeping Graph and adding the ID token on top: two identity sources that can
disagree; the issue asks for Graph to be optional.

## Design

- `users/oauth/providers.py`: `OAuthProvider` gains
`authorization_url(callback, state, login) -> str` and
`get_identity(token, login) -> tuple[str, str | None, bool]`, where `login`
carries the per-login `code_verifier` and `nonce` (both `None` for providers
that do not use them). Google/GitHub/OIDC behave exactly as today, reading
`token["access_token"]`.
- `users/oauth/microsoft.py` (new): the OIDC client (a `BaseOAuth2` on the
tenant's endpoints) and ID-token validation.
- **Issuer.** GUID tenant: one `JWKSCache` with issuer
`https://login.microsoftonline.com/<GUID>/v2.0`, and `tid` must equal the
GUID. `common` / `organizations` / `consumers`: the issuer is built from the
token's `tid` and validated exactly; one `JWKSCache` per `tid` in a small
bounded LRU. `organizations` refuses the consumer tenant
(`9188040d-…`); `consumers` accepts only it.
- **Account id** (`OAuthAccount.account_id`): unchanged in value so existing
links keep working. For work/school accounts the Graph `id` *is* the `oid`
claim. For personal accounts Graph returns a 16-hex id, which the ID token
carries as the last 16 hex digits of `oid` (`00000000-0000-0000-xxxx-xxxxxxxxxxxx`).
- **Email** = `preferred_username` (for a member, the UPN Graph returned
before; for a guest, their home address). Proof stays #873's policy:
verified only with `oauth_microsoft_trust_tenant_upn` and a GUID tenant, a
`tid` equal to it, no `idp` claim (Entra sets `idp` for guests and other
external identities) and no `#EXT#` in the value.
- `users/oauth/api.py`: `begin()` asks the provider whether it uses PKCE/nonce;
if so it generates both and stores them in the session under
`oauth_login:<provider>` next to the state. The callback compares the state
first, then pops the state and login data together (a forged reply cannot
consume a pending login), passes the verifier to the token exchange and the
login data to `get_identity`. A failed ID-token check is `OAUTH_PROVIDER_ERROR`.
- Docs: users README, `docs/modules/users.md` (provider table, redirect URI
unchanged, Entra app registration needs the `openid profile email` delegated
permissions instead of Graph `User.Read`), CHANGELOG with a **behaviour
change** note.

## Decisions made

- Fixed Entra endpoints, not discovery (see Approach).
- Account id kept Graph-compatible rather than switching to raw `oid` or `sub`,
so no data migration and no broken links.
- `preferred_username` as the email, matching what Graph's UPN gave members;
the optional `email` claim is ignored for now (#877/#878 revisit the profile).
- Guest detection by the `idp` claim, keeping the `#EXT#` check as well.
- PKCE + nonce only for Microsoft in this PR; the plumbing is generic.

## Testing

- Unit (`tests/oauth/providers/`): ID-token validation with a locally generated
RSA key and JWKS (respx or a fake fetch): good token; wrong `aud`, `iss`,
`nonce`, expired, bad signature, missing `tid`/`oid`; GUID tenant with another
`tid`; `organizations` + consumer `tid`; `common` per-`tid` issuer; account-id
mapping for work and personal `oid`; trust rule with and without `idp`.
- Flow (`tests/oauth/flow/`): `begin()` puts `code_challenge` (S256) and
`nonce` in the authorize URL and the session; callback passes the verifier to
the token exchange; a reply with a wrong state leaves the pending login
intact; existing provider flows unchanged.
- No browser QA: no Entra tenant locally (#879 adds a local-IdP path).

## Risks

- The personal-account id mapping is from Microsoft's published `oid` format,
not tested against a live personal account here. If it were wrong, an
existing personal-account link would not be found and that user would be
refused (`OAUTH_USER_ALREADY_EXISTS`) instead of silently linked elsewhere.
- **Behaviour change** for operators: the Entra app registration must allow
the `openid`, `profile`, `email` delegated permissions (usually granted by
default). Graph `User.Read` is no longer requested.
25 changes: 14 additions & 11 deletions modules/users/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,17 +86,20 @@ OAuth providers are configured in the admin UI at **/settings/modules → Users*
secret are set; the secret is masked in the UI. Changes apply live — no restart.

**Microsoft (Entra ID).** Register an app in the Entra admin center and set the
redirect URI to `<base-url>/api/users/auth/microsoft/callback`. Configure under
the **Microsoft OAuth** group:
redirect URI to `<base-url>/api/users/auth/microsoft/callback`; it needs the
`openid`, `profile` and `email` delegated permissions (Graph `User.Read` is not
used). Sign-in is OpenID Connect with PKCE and a nonce, and the identity comes
from the validated ID token. Configure under the **Microsoft OAuth** group:

- `oauth_microsoft_client_id`, `oauth_microsoft_client_secret`
- `oauth_microsoft_tenant` — `common` (any work/school or personal account,
the default), `organizations` (work/school only), or your tenant GUID to
restrict sign-in to one tenant.
the default), `organizations` (work/school only), `consumers` (personal
only), or your tenant GUID to restrict sign-in to one tenant.
- `oauth_microsoft_trust_tenant_upn` — off by default. With a tenant GUID,
a member account's `userPrincipalName` counts as a verified email, so it
links to an invited or verified local account on first sign-in. Guests
(`#EXT#`) stay unverified; with any other tenant value it has no effect.
a member account's UPN (`upn` claim, else `preferred_username`) counts as a verified
email, so it links to an invited or verified local account on first
sign-in. Guests (an `idp` claim naming another issuer, or `#EXT#`) stay unverified; with any other
tenant value it has no effect.
It trusts the tenant's admins: whoever can set a member's UPN can sign in
as the local account with that address.

Expand All @@ -110,10 +113,10 @@ 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`).

> **Note:** for Microsoft *guest/external* accounts the identity email comes
> from the Graph `userPrincipalName`, which may not be a plain email
> (e.g. `user_ext.com#EXT#@tenant.onmicrosoft.com`). For tenant members it is
> the user's email.
> **Note:** the Microsoft identity email is the ID token's optional `upn`
> claim when the app registration adds it, else `preferred_username`: the UPN
> for tenant members, the home address for a guest. A pinned tenant GUID also
> requires the token's `tid` to match it.

### Migrating from `SM_USERS_OAUTH_*` env vars

Expand Down
Loading
Loading