diff --git a/CHANGELOG.md b/CHANGELOG.md index ee60e7c8..7def699b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/docs/modules/users.md b/docs/modules/users.md index ab70d512..a087761e 100644 --- a/docs/modules/users.md +++ b/docs/modules/users.md @@ -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 | @@ -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//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//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. diff --git a/docs/superpowers/plans/2026-11-11-microsoft-oidc-provider.md b/docs/superpowers/plans/2026-11-11-microsoft-oidc-provider.md new file mode 100644 index 00000000..433b9d7e --- /dev/null +++ b/docs/superpowers/plans/2026-11-11-microsoft-oidc-provider.md @@ -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`. diff --git a/docs/superpowers/specs/2026-11-11-microsoft-oidc-provider-design.md b/docs/superpowers/specs/2026-11-11-microsoft-oidc-provider-design.md new file mode 100644 index 00000000..0c21532f --- /dev/null +++ b/docs/superpowers/specs/2026-11-11-microsoft-oidc-provider-design.md @@ -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//oauth2/v2.0/{authorize,token}`, +JWKS `…/discovery/v2.0/keys`, issuer `…//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//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:` 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. diff --git a/modules/users/README.md b/modules/users/README.md index 81c69b69..f9431aa0 100644 --- a/modules/users/README.md +++ b/modules/users/README.md @@ -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 `/api/users/auth/microsoft/callback`. Configure under -the **Microsoft OAuth** group: +redirect URI to `/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. @@ -110,10 +113,10 @@ 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`). -> **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 diff --git a/modules/users/tests/_users_microsoft_support.py b/modules/users/tests/_users_microsoft_support.py new file mode 100644 index 00000000..4638e64c --- /dev/null +++ b/modules/users/tests/_users_microsoft_support.py @@ -0,0 +1,85 @@ +"""A Microsoft OIDC client that signs real ID tokens with a local key (no network).""" + +from __future__ import annotations + +import time +from typing import Any + +import jwt +from cryptography.hazmat.primitives.asymmetric import rsa +from users.oauth.microsoft import MicrosoftOidc + +KID = "test-kid" +CLIENT_ID = "ms-client" +TENANT = "6f1c2a3b-4d5e-4f60-8a7b-9c0d1e2f3a4b" +OID = "1b2c3d4e-5f60-4a7b-8c9d-0e1f2a3b4c5d" +_PRIVATE = rsa.generate_private_key(public_exponent=65537, key_size=2048) + + +def sign(claims: dict[str, Any], key: Any = _PRIVATE, kid: str = KID) -> str: + return jwt.encode(claims, key, algorithm="RS256", headers={"kid": kid}) + + +def id_claims(tid: str = TENANT, **overrides: Any) -> dict[str, Any]: + now = int(time.time()) + claims = { + "iss": f"https://login.microsoftonline.com/{tid}/v2.0", + "aud": CLIENT_ID, + "sub": "pairwise-sub", + "iat": now, + "exp": now + 300, + "tid": tid, + "oid": OID, + "preferred_username": "jane@corp.com", + } + claims.update(overrides) + return {k: v for k, v in claims.items() if v is not None} + + +class FakeMicrosoft(MicrosoftOidc): + """Captures the login's challenge/nonce and answers with a signed ID token. + + ``claims`` overrides the defaults; ``nonce=None`` in it keeps the login's nonce. + """ + + def __init__(self, tenant: str = TENANT, **claims: Any) -> None: + super().__init__(CLIENT_ID, "secret", tenant) + self.claims = claims + self.nonce: str | None = None + self.challenge: str | None = None + self.verifier: str | None = None + + async def get_authorization_url( + self, + redirect_uri, + state=None, + scope=None, + code_challenge=None, + code_challenge_method=None, + extras_params=None, + ): + self.challenge = code_challenge + self.challenge_method = code_challenge_method + self.nonce = (extras_params or {}).get("nonce") + return f"https://login.example/authorize?state={state}" + + async def get_access_token(self, code, redirect_uri, code_verifier=None): + self.verifier = code_verifier + claims = id_claims(**{"nonce": self.nonce, **self.claims}) + return {"access_token": "at", "id_token": sign(claims)} + + def _cache(self, tid): + cache = super()._cache(tid) + cache._keys = {KID: _PRIVATE.public_key()} + cache._fetched_at = cache._now() + return cache + + +def install_microsoft(app, *, trust: bool = True, tenant: str = TENANT, **claims) -> FakeMicrosoft: + from users.oauth import OAuthProvider + + client = FakeMicrosoft(tenant, **claims) + app.state.users.oauth_clients["microsoft"] = OAuthProvider( + "microsoft", "Microsoft", client, trust_email=trust + ) + return client diff --git a/modules/users/tests/oauth/flow/test_users_oauth_email_claim.py b/modules/users/tests/oauth/flow/test_users_oauth_email_claim.py index d93970f0..041ba785 100644 --- a/modules/users/tests/oauth/flow/test_users_oauth_email_claim.py +++ b/modules/users/tests/oauth/flow/test_users_oauth_email_claim.py @@ -9,6 +9,7 @@ from users.oauth import OAuthProvider _EMAIL = "victim@example.com" +_TOKEN = {"access_token": "token"} class _ClaimClient: @@ -88,7 +89,7 @@ async def test_oidc_existing_subject_can_sign_in_without_verified_email(users_ap @pytest.mark.anyio # Google proof comes from People API metadata: test_users_oauth_provider_identity.py. -@pytest.mark.parametrize("provider", ["github", "microsoft"]) +@pytest.mark.parametrize("provider", ["github"]) async def test_provider_without_email_proof_cannot_link(users_app, anon_client, provider): await seed_password_user(users_app, _EMAIL, is_verified=True) @@ -111,16 +112,22 @@ async def test_provider_without_email_proof_cannot_link(users_app, anon_client, async def test_oidc_identity_preserves_email_proof(claim, verified): provider = OAuthProvider("oidc", "OIDC", _ClaimClient(claim)) - assert await provider.get_identity("token") == ("idp-attacker", _EMAIL, verified) + assert await provider.get_identity(_TOKEN) == ( + "idp-attacker", + _EMAIL, + verified, + ) @pytest.mark.anyio # Google proof comes from People API metadata: test_users_oauth_provider_identity.py. -@pytest.mark.parametrize("provider", ["github", "microsoft"]) +@pytest.mark.parametrize("provider", ["github"]) async def test_non_oidc_identity_does_not_infer_email_proof(provider): client = _ClaimClient({"email_verified": True}) - assert await OAuthProvider(provider, provider, client).get_identity("token") == ( + assert await OAuthProvider(provider, provider, client).get_identity( + {"access_token": "token"} + ) == ( "idp-attacker", _EMAIL, False, @@ -131,7 +138,7 @@ async def test_non_oidc_identity_does_not_infer_email_proof(provider): async def test_unproven_sso_account_cannot_capture_a_later_verified_login(users_app, anon_client): """Pre-hijack: an unproven provider creates the account, a verified one must not join it.""" set_allow_signup(users_app, True) - assert (await _callback(users_app, anon_client, {}, "microsoft")).status_code == 303 + assert (await _callback(users_app, anon_client, {}, "github")).status_code == 303 assert (await find_user(users_app, _EMAIL)).is_verified is False anon_client.cookies.clear() @@ -141,4 +148,4 @@ async def test_unproven_sso_account_cannot_capture_a_later_verified_login(users_ assert response.json()["detail"] == "OAUTH_ACCOUNT_NOT_VERIFIED" async with users_app.state.sm.db.session_factory() as session: providers = {a.oauth_name for a in (await session.execute(select(OAuthAccount))).scalars()} - assert providers == {"microsoft"} + assert providers == {"github"} diff --git a/modules/users/tests/oauth/flow/test_users_oauth_microsoft_pkce.py b/modules/users/tests/oauth/flow/test_users_oauth_microsoft_pkce.py new file mode 100644 index 00000000..38f1013e --- /dev/null +++ b/modules/users/tests/oauth/flow/test_users_oauth_microsoft_pkce.py @@ -0,0 +1,71 @@ +"""Microsoft logins carry a PKCE verifier and nonce bound to the session (#876).""" + +from __future__ import annotations + +from urllib.parse import parse_qs, urlparse + +import pytest +from _users_microsoft_support import install_microsoft +from _users_oauth_support import install_fake_provider, oauth_callback, set_allow_signup +from auth.oidc_common.session import pkce_challenge + + +@pytest.mark.anyio +async def test_login_sends_an_s256_challenge_and_the_callback_its_verifier(users_app, anon_client): + set_allow_signup(users_app, True) + client = install_microsoft(users_app) + + assert (await oauth_callback(anon_client, "microsoft")).status_code == 303 + assert client.challenge_method == "S256" + assert client.verifier and client.challenge == pkce_challenge(client.verifier) + assert client.nonce + + +@pytest.mark.anyio +async def test_each_login_gets_fresh_secrets(users_app, anon_client): + client = install_microsoft(users_app) + await anon_client.get("/api/users/auth/microsoft/login") + first = (client.challenge, client.nonce) + await anon_client.get("/api/users/auth/microsoft/login") + assert (client.challenge, client.nonce) != first + + +@pytest.mark.anyio +async def test_a_callback_without_stored_login_secrets_is_refused(users_app, anon_client): + """A login begun without a verifier (here: before PKCE applied) cannot finish.""" + install_fake_provider(users_app, "ms-1", "jane@corp.com", provider="microsoft") + login = await anon_client.get("/api/users/auth/microsoft/login", follow_redirects=False) + state = parse_qs(urlparse(login.headers["location"]).query)["state"][0] + client = install_microsoft(users_app) + + resp = await anon_client.get( + f"/api/users/auth/microsoft/callback?code=abc&state={state}", follow_redirects=False + ) + assert resp.json()["detail"] == "OAUTH_INVALID_STATE" + assert client.verifier is None # never reached the token endpoint + + +@pytest.mark.anyio +async def test_a_wrong_nonce_is_a_provider_error(users_app, anon_client): + set_allow_signup(users_app, True) + install_microsoft(users_app, nonce="someone-elses-login") + + resp = await oauth_callback(anon_client, "microsoft") + assert resp.json()["detail"] == "OAUTH_PROVIDER_ERROR" + + +@pytest.mark.anyio +async def test_a_forged_reply_leaves_the_pending_login_intact(users_app, anon_client): + set_allow_signup(users_app, True) + install_microsoft(users_app) + login = await anon_client.get("/api/users/auth/microsoft/login", follow_redirects=False) + state = parse_qs(urlparse(login.headers["location"]).query)["state"][0] + + forged = await anon_client.get( + "/api/users/auth/microsoft/callback?code=evil&state=forged", follow_redirects=False + ) + assert forged.json()["detail"] == "OAUTH_INVALID_STATE" + real = await anon_client.get( + f"/api/users/auth/microsoft/callback?code=abc&state={state}", follow_redirects=False + ) + assert real.status_code == 303 diff --git a/modules/users/tests/oauth/flow/test_users_oauth_provider_identity.py b/modules/users/tests/oauth/flow/test_users_oauth_provider_identity.py index 446a9e68..f555b6c1 100644 --- a/modules/users/tests/oauth/flow/test_users_oauth_provider_identity.py +++ b/modules/users/tests/oauth/flow/test_users_oauth_provider_identity.py @@ -3,6 +3,8 @@ import pytest from users.oauth import OAuthProvider +_TOKEN = {"access_token": "t"} + class _Google: def __init__(self, verified): @@ -31,15 +33,14 @@ async def get_emails(self, token): return self.emails -class _Microsoft: - async def get_id_email(self, token): - return "ms-1", "me@example.com" - - @pytest.mark.parametrize("verified", [True, False, None]) async def test_google_uses_primary_email_verification(verified): provider = OAuthProvider("google", "Google", _Google(verified)) - assert await provider.get_identity("t") == ("people/1", "me@example.com", verified is True) + assert await provider.get_identity(_TOKEN) == ( + "people/1", + "me@example.com", + verified is True, + ) @pytest.mark.parametrize( @@ -52,46 +53,9 @@ async def test_google_uses_primary_email_verification(verified): ) async def test_github_requires_the_chosen_email_to_be_verified(emails, expected): provider = OAuthProvider("github", "GitHub", _GitHub(emails)) - assert await provider.get_identity("t") == ("42", "me@example.com", expected) + assert await provider.get_identity(_TOKEN) == ("42", "me@example.com", expected) async def test_github_unreadable_emails_is_not_proof(): provider = OAuthProvider("github", "GitHub", _GitHub([], fail=True)) - assert (await provider.get_identity("t"))[2] is False - - -async def test_microsoft_email_is_never_proof(): - provider = OAuthProvider("microsoft", "Microsoft", _Microsoft()) - assert await provider.get_identity("t") == ("ms-1", "me@example.com", False) - - -class _MicrosoftUpn: - def __init__(self, account_id, upn): - self.account_id, self.upn = account_id, upn - - async def get_id_email(self, token): - return self.account_id, self.upn - - -async def test_microsoft_trusted_tenant_member_upn_is_proof(): - """#873: a member UPN of the pinned tenant is on a domain that tenant verified.""" - provider = OAuthProvider( - "microsoft", "Microsoft", _MicrosoftUpn("ms-1", "jane@corp.com"), trust_email=True - ) - assert await provider.get_identity("t") == ("ms-1", "jane@corp.com", True) - - -@pytest.mark.parametrize( - "account_id, upn", - [ - ("ms-1", "jane_ext.com#EXT#@corp.onmicrosoft.com"), - ("ms-1", "jane_ext.com#ext#@corp.onmicrosoft.com"), - ("", "jane@corp.com"), - ("ms-1", ""), - ], -) -async def test_microsoft_trust_excludes_guests_and_empty_identities(account_id, upn): - provider = OAuthProvider( - "microsoft", "Microsoft", _MicrosoftUpn(account_id, upn), trust_email=True - ) - assert (await provider.get_identity("t"))[2] is False + assert (await provider.get_identity(_TOKEN))[2] is False 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 index 0c29f0b9..ac089463 100644 --- a/modules/users/tests/oauth/flow/test_users_oauth_provider_signup.py +++ b/modules/users/tests/oauth/flow/test_users_oauth_provider_signup.py @@ -3,6 +3,7 @@ from __future__ import annotations import pytest +from _users_microsoft_support import install_microsoft from _users_oauth_support import ( find_user, install_fake_provider, @@ -26,7 +27,7 @@ async def test_listed_provider_with_proven_email_creates_the_account(users_app, 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") + install_microsoft(users_app, trust=False, preferred_username="who@example.com") resp = await oauth_callback(anon_client, "microsoft") assert resp.status_code == 403 diff --git a/modules/users/tests/oauth/flow/test_users_oauth_tenant_upn_trust.py b/modules/users/tests/oauth/flow/test_users_oauth_tenant_upn_trust.py index e42318dd..77245375 100644 --- a/modules/users/tests/oauth/flow/test_users_oauth_tenant_upn_trust.py +++ b/modules/users/tests/oauth/flow/test_users_oauth_tenant_upn_trust.py @@ -10,8 +10,8 @@ from datetime import UTC, datetime import pytest +from _users_microsoft_support import install_microsoft from _users_oauth_support import ( - install_fake_provider, oauth_callback, seed_password_user, set_allow_signup, @@ -22,8 +22,8 @@ _EMAIL = "jane@corp.com" -def _microsoft(app, upn: str = _EMAIL, *, trust: bool = True) -> None: - install_fake_provider(app, "ms-jane", upn, provider="microsoft", trust_email=trust) +def _microsoft(app, upn: str = _EMAIL, *, trust: bool = True, **claims) -> None: + install_microsoft(app, trust=trust, preferred_username=upn, **claims) @pytest.mark.anyio @@ -70,10 +70,17 @@ async def test_unproven_local_account_is_still_refused(users_app, anon_client): @pytest.mark.anyio -async def test_guest_upn_does_not_link(users_app, anon_client): - guest = "jane_corp.com#EXT#@other.onmicrosoft.com" +@pytest.mark.parametrize( + "guest, claims", + [ + # An ID token names a guest by their home address and sets ``idp``. + ("jane@other.com", {"idp": "https://sts.windows.net/other-tenant/"}), + ("jane_corp.com#EXT#@other.onmicrosoft.com", {}), + ], +) +async def test_guest_does_not_link(users_app, anon_client, guest, claims): await seed_password_user(users_app, guest, is_verified=True) - _microsoft(users_app, guest) + _microsoft(users_app, guest, **claims) resp = await oauth_callback(anon_client, "microsoft") assert resp.json()["detail"] == "OAUTH_USER_ALREADY_EXISTS" diff --git a/modules/users/tests/oauth/providers/test_users_oauth_microsoft_id_token.py b/modules/users/tests/oauth/providers/test_users_oauth_microsoft_id_token.py new file mode 100644 index 00000000..35c7cd0e --- /dev/null +++ b/modules/users/tests/oauth/providers/test_users_oauth_microsoft_id_token.py @@ -0,0 +1,143 @@ +"""Microsoft sign-in validates the ID token itself (#876).""" + +from __future__ import annotations + +import pytest +from _users_microsoft_support import OID, TENANT, FakeMicrosoft, id_claims, sign +from cryptography.hazmat.primitives.asymmetric import rsa +from users.core.oauth_settings import MICROSOFT_CONSUMERS_TENANT +from users.oauth.microsoft import IdTokenError, graph_account_id + +_NONCE = "login-nonce" +_OTHER_TENANT = "0a1b2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c4d" +_CONSUMERS = str(MICROSOFT_CONSUMERS_TENANT) + + +async def _identity(client: FakeMicrosoft, token: str, *, trust: bool = False): + return await client.identity({"id_token": token}, _NONCE, trust_email=trust) + + +async def test_a_valid_token_gives_the_graph_compatible_identity(): + token = sign(id_claims(nonce=_NONCE)) + assert await _identity(FakeMicrosoft(), token) == (OID, "jane@corp.com", False) + + +@pytest.mark.parametrize( + "claims", + [ + {"aud": "another-client"}, + {"iss": "https://login.microsoftonline.com/elsewhere/v2.0"}, + {"nonce": "replayed"}, + {"nonce": None}, + {"exp": 1, "iat": 0}, + {"oid": None}, + {"oid": "not-a-guid"}, + {"tid": None}, + {"azp": "another-client"}, + ], + ids=["aud", "iss", "nonce", "no-nonce", "expired", "no-oid", "bad-oid", "no-tid", "azp"], +) +async def test_a_bad_token_is_refused(claims): + token = sign(id_claims(**{"nonce": _NONCE, **claims})) + with pytest.raises(IdTokenError): + await _identity(FakeMicrosoft(), token) + + +async def test_a_token_signed_by_another_key_is_refused(): + other = rsa.generate_private_key(public_exponent=65537, key_size=2048) + with pytest.raises(IdTokenError): + await _identity(FakeMicrosoft(), sign(id_claims(nonce=_NONCE), key=other)) + + +@pytest.mark.parametrize("token", [None, "", "not.a.jwt"]) +async def test_a_missing_or_garbled_token_is_refused(token): + with pytest.raises(IdTokenError): + await FakeMicrosoft().identity({"id_token": token}, _NONCE, trust_email=False) + + +async def test_a_login_without_a_nonce_is_refused(): + with pytest.raises(IdTokenError): + await FakeMicrosoft().identity({"id_token": sign(id_claims())}, None, trust_email=False) + + +async def test_a_pinned_tenant_refuses_another_tenant(): + token = sign(id_claims(_OTHER_TENANT, nonce=_NONCE)) + with pytest.raises(IdTokenError): + await _identity(FakeMicrosoft(TENANT), token) + + +@pytest.mark.parametrize( + "tenant, tid, accepted", + [ + ("common", _OTHER_TENANT, True), + ("common", _CONSUMERS, True), + ("organizations", _OTHER_TENANT, True), + ("organizations", _CONSUMERS, False), + ("consumers", _CONSUMERS, True), + ("consumers", _OTHER_TENANT, False), + ], +) +async def test_multi_tenant_segments_validate_the_tokens_own_issuer(tenant, tid, accepted): + token = sign(id_claims(tid, nonce=_NONCE)) + if accepted: + assert (await _identity(FakeMicrosoft(tenant), token))[0] == OID + else: + with pytest.raises(IdTokenError): + await _identity(FakeMicrosoft(tenant), token) + + +async def test_the_signed_tid_must_match_the_issuer(): + # Issuer for the other tenant, but ``tid`` claims ours: never accepted. + claims = {**id_claims(_OTHER_TENANT, nonce=_NONCE), "tid": TENANT} + with pytest.raises(IdTokenError): + await _identity(FakeMicrosoft("common"), sign(claims)) + + +@pytest.mark.parametrize( + "tenant, claims, trusted", + [ + (TENANT, {}, True), + (TENANT, {"idp": "https://sts.windows.net/other/"}, False), + (TENANT, {"idp": f"https://sts.windows.net/{TENANT}/"}, True), + (TENANT, {"idp": f"https://login.microsoftonline.com/{TENANT}/v2.0"}, True), + (TENANT, {"preferred_username": "jane_x.com#EXT#@corp.onmicrosoft.com"}, False), + (TENANT, {"preferred_username": None}, False), + (TENANT, {"idp": ["https://sts.windows.net/other/"]}, False), + ("common", {}, False), + ], + ids=[ + "member", + "guest-idp", + "home-idp-v1", + "home-idp-v2", + "guest-ext", + "no-username", + "idp-list", + "common", + ], +) +async def test_trust_needs_a_member_of_the_pinned_tenant(tenant, claims, trusted): + token = sign(id_claims(nonce=_NONCE, **claims)) + assert (await _identity(FakeMicrosoft(tenant), token, trust=True))[2] is trusted + + +@pytest.mark.parametrize( + "oid, graph_id", + [ + (OID, OID), + ("00000000-0000-0000-1a2b-3c4d5e6f7a8b", "1a2b3c4d5e6f7a8b"), + ], + ids=["work-or-school", "personal"], +) +def test_account_ids_match_what_graph_returned(oid, graph_id): + assert graph_account_id(oid) == graph_id + + +async def test_a_non_email_username_is_no_email(): + token = sign(id_claims(nonce=_NONCE, preferred_username="+43 1 234 5678")) + assert (await _identity(FakeMicrosoft(), token))[1] is None + + +async def test_the_upn_claim_wins_over_an_alternate_login_alias(): + claims = id_claims(nonce=_NONCE, preferred_username="alias@corp.com", upn="jane@corp.com") + assert (await _identity(FakeMicrosoft(), sign(claims)))[1] == "jane@corp.com" diff --git a/modules/users/users/core/oauth_settings.py b/modules/users/users/core/oauth_settings.py index 295ce7b1..279eee8a 100644 --- a/modules/users/users/core/oauth_settings.py +++ b/modules/users/users/core/oauth_settings.py @@ -22,7 +22,7 @@ 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") +MICROSOFT_CONSUMERS_TENANT = uuid.UUID("9188040d-6c67-4c5b-b112-36a304b66dad") def is_tenant_guid(tenant: str) -> bool: @@ -35,7 +35,7 @@ def is_tenant_guid(tenant: str) -> bool: parsed = uuid.UUID(tenant) except ValueError: return False - return str(parsed) == tenant.lower() and parsed != _MICROSOFT_CONSUMERS_TENANT + return str(parsed) == tenant.lower() and parsed != MICROSOFT_CONSUMERS_TENANT class OAuthSettings(DbBackedSettings): @@ -68,10 +68,10 @@ class OAuthSettings(DbBackedSettings): 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. + # Treat a member account's UPN (the ID token's ``upn`` claim, else ``preferred_username``) 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. Guests (an ``idp`` claim or ``#EXT#``) stay unverified. oauth_microsoft_trust_tenant_upn: bool = Field( default=False, json_schema_extra={"group": "Microsoft OAuth"} ) diff --git a/modules/users/users/oauth/api.py b/modules/users/users/oauth/api.py index 854a5ebc..94b7a8d7 100644 --- a/modules/users/users/oauth/api.py +++ b/modules/users/users/oauth/api.py @@ -18,6 +18,7 @@ from __future__ import annotations +import logging import secrets from typing import TYPE_CHECKING @@ -36,12 +37,25 @@ from users.accounts.manager import UserManager from users.core.settings import UsersSettings from users.models import User - from users.oauth.providers import OAuthProvider + from users.oauth.providers import LoginSecrets, OAuthProvider + +logger = logging.getLogger(__name__) _SESSION_STATE_KEY_FMT = "oauth_state:{provider}" +_SESSION_LOGIN_KEY_FMT = "oauth_login:{provider}" _CALLBACK_ROUTE_NAME = "users_oauth_callback" +def _login_secrets(value: object) -> LoginSecrets | None: + """The stored PKCE verifier and nonce, or ``None`` if absent or malformed.""" + if not isinstance(value, dict): + return None + verifier, nonce = value.get("verifier"), value.get("nonce") + if not isinstance(verifier, str) or not verifier or not isinstance(nonce, str) or not nonce: + return None + return {"verifier": verifier, "nonce": nonce} + + def _resolve_provider(request: Request, provider: str) -> OAuthProvider: """Return the configured provider by name, or raise 404.""" found = request.app.state.users.oauth_clients.get(provider) @@ -108,8 +122,12 @@ async def begin(request: Request, provider: str) -> RedirectResponse: provider_obj = _resolve_provider(request, provider) state = secrets.token_urlsafe(32) request.session[_SESSION_STATE_KEY_FMT.format(provider=provider)] = state + login: LoginSecrets | None = None + if provider_obj.uses_pkce: + login = {"verifier": secrets.token_urlsafe(64), "nonce": secrets.token_urlsafe(32)} + request.session[_SESSION_LOGIN_KEY_FMT.format(provider=provider)] = login callback_url = str(request.url_for(_CALLBACK_ROUTE_NAME, provider=provider)) - authorization_url = await provider_obj.client.get_authorization_url(callback_url, state) + authorization_url = await provider_obj.authorization_url(callback_url, state, login) return RedirectResponse(authorization_url, status_code=302) @router.get("/{provider}/callback", name=_CALLBACK_ROUTE_NAME) @@ -124,8 +142,21 @@ async def callback( """Verify state, exchange code, find-or-create user, set cookie, redirect.""" provider_obj = _resolve_provider(request, provider) state_key = _SESSION_STATE_KEY_FMT.format(provider=provider) - expected_state = request.session.pop(state_key, None) - if not state or not expected_state or not secrets.compare_digest(state, expected_state): + expected_state = request.session.get(state_key) + # Compared before anything is spent, so a forged or stray reply cannot + # consume the pending login; the matching reply spends the state together + # with that login's PKCE verifier and nonce. + if ( + not state + or not isinstance(expected_state, str) + or not secrets.compare_digest(state, expected_state) + ): + return refuse_login(request, "OAUTH_INVALID_STATE") + request.session.pop(state_key, None) + login = _login_secrets( + request.session.pop(_SESSION_LOGIN_KEY_FMT.format(provider=provider), None) + ) + if provider_obj.uses_pkce and login is None: return refuse_login(request, "OAUTH_INVALID_STATE") if "error" in request.query_params: return refuse_login(request, "OAUTH_PROVIDER_ERROR") @@ -134,11 +165,13 @@ async def callback( callback_url = str(request.url_for(_CALLBACK_ROUTE_NAME, provider=provider)) try: - token = await provider_obj.client.get_access_token(code, callback_url) + token = await provider_obj.exchange_code(code, callback_url, login) account_id, account_email, email_verified = await provider_obj.get_identity( - token["access_token"] + token, login ) - except (HTTPXOAuthError, HTTPError): + except (HTTPXOAuthError, HTTPError) as exc: + # The browser only sees OAUTH_PROVIDER_ERROR; say why for the operator. + logger.warning("OAuth sign-in through %s refused: %s", provider, exc) return refuse_login(request, "OAUTH_PROVIDER_ERROR") if account_email is None: return refuse_login(request, "OAUTH_NO_EMAIL") diff --git a/modules/users/users/oauth/microsoft.py b/modules/users/users/oauth/microsoft.py new file mode 100644 index 00000000..b7fc786f --- /dev/null +++ b/modules/users/users/oauth/microsoft.py @@ -0,0 +1,146 @@ +"""Microsoft (Entra) sign-in over OpenID Connect (#876). + +The authorization-code flow runs on the tenant's v2.0 endpoints with PKCE and +a nonce, and the identity comes from the validated ID token rather than Graph +``/me``. The endpoints, JWKS URL and issuer are fixed per tenant segment, so +nothing is fetched at boot. +""" + +from __future__ import annotations + +import re +import secrets +from collections import OrderedDict +from typing import Any + +import jwt +from auth.oidc_common.jwks import JWKSCache +from httpx_oauth.clients.microsoft import MicrosoftGraphOAuth2 +from httpx_oauth.exceptions import HTTPXOAuthError + +from users.core.oauth_settings import MICROSOFT_CONSUMERS_TENANT, is_tenant_guid + +_LOGIN_HOST = "https://login.microsoftonline.com" +_SCOPES = ["openid", "profile", "email"] +_GUID_RE = re.compile(r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$") +# A personal account's ``oid``: its Graph ``id`` (16 hex digits) behind zeros. +_PERSONAL_OID_PREFIX = "00000000-0000-0000-" +# Issuers seen through ``common``/``organizations``; each keeps its own key cache. +_MAX_ISSUER_CACHES = 32 +_CONSUMERS_TID = str(MICROSOFT_CONSUMERS_TENANT) + + +class IdTokenError(HTTPXOAuthError): + """The token response carried no usable, valid ID token.""" + + +class MicrosoftOidc(MicrosoftGraphOAuth2): + """Entra v2.0 client that signs in from the ID token, not Graph.""" + + uses_pkce = True + + def __init__(self, client_id: str, client_secret: str, tenant: str) -> None: + super().__init__(client_id, client_secret, tenant=tenant, scopes=_SCOPES, name="microsoft") + self.tenant = tenant.lower() + self._jwks_url = f"{_LOGIN_HOST}/{tenant}/discovery/v2.0/keys" + self._caches: OrderedDict[str, JWKSCache] = OrderedDict() + + async def identity( + self, token: dict[str, Any], nonce: str | None, *, trust_email: bool + ) -> tuple[str, str | None, bool]: + """Validate the ID token; return (Graph-compatible id, email, proof). + + Raises :class:`IdTokenError` for a missing, invalid or foreign token. + """ + id_token = token.get("id_token") + if not isinstance(id_token, str) or not nonce: + raise IdTokenError("ID token missing") + tid = _unverified_tid(id_token) + if tid is None or not self._accepts_tenant(tid): + raise IdTokenError("ID token from an unexpected tenant") + claims = await self._cache(tid).validate_jwt(id_token) + if claims is None or claims.get("tid") != tid: + raise IdTokenError("ID token validation failed") + claimed_nonce = claims.get("nonce") + if not isinstance(claimed_nonce, str) or not secrets.compare_digest( + claimed_nonce.encode(), nonce.encode() + ): + raise IdTokenError("ID token nonce mismatch") + oid = claims.get("oid") + if not isinstance(oid, str) or not _GUID_RE.fullmatch(oid): + raise IdTokenError("ID token has no object id") + email = _account_email(claims) + # Proof only for a member of the one tenant the operator pinned: Entra + # names another ``idp`` for guests and other external identities (#873). + idp = claims.get("idp") + trusted = ( + trust_email + and email is not None + and is_tenant_guid(self.tenant) + and tid == self.tenant + and (idp is None or (isinstance(idp, str) and idp in _home_issuers(tid))) + and "#EXT#" not in email.upper() + ) + return graph_account_id(oid), email, trusted + + def _accepts_tenant(self, tid: str) -> bool: + if self.tenant == "consumers": + return tid == _CONSUMERS_TID + if self.tenant == "organizations": + return tid != _CONSUMERS_TID + if _GUID_RE.fullmatch(self.tenant): + return tid == self.tenant + # ``common`` or a verified-domain tenant: the authorize endpoint pins it. + return True + + def _cache(self, tid: str) -> JWKSCache: + cache = self._caches.get(tid) + if cache is None: + cache = JWKSCache( + self._jwks_url, issuer=f"{_LOGIN_HOST}/{tid}/v2.0", audience=self.client_id + ) + self._caches[tid] = cache + if len(self._caches) > _MAX_ISSUER_CACHES: + self._caches.popitem(last=False) + else: + self._caches.move_to_end(tid) + return cache + + +def graph_account_id(oid: str) -> str: + """The Graph ``id`` for an ``oid``, so links made through Graph keep matching. + + Work and school accounts: Graph ``id`` is the ``oid``. Personal accounts: + Graph returns 16 hex digits, which ``oid`` carries after a zero prefix. + """ + if oid.startswith(_PERSONAL_OID_PREFIX): + return oid[len(_PERSONAL_OID_PREFIX) :].replace("-", "") + return oid + + +def _account_email(claims: dict[str, Any]) -> str | None: + """The sign-in address: the optional ``upn`` claim, else ``preferred_username``. + + With email as an alternate login ID, ``preferred_username`` is whatever the + user typed; an app registration that adds the ``upn`` optional claim gets the + UPN Graph used to return. A phone-number username is no email. + """ + for name in ("upn", "preferred_username"): + value = claims.get(name) + if isinstance(value, str) and "@" in value: + return value + return None + + +def _home_issuers(tid: str) -> set[str]: + """``idp`` values that mean the tenant itself authenticated the account (v1 and v2).""" + return {f"{_LOGIN_HOST}/{tid}/v2.0", f"https://sts.windows.net/{tid}/"} + + +def _unverified_tid(id_token: str) -> str | None: + """The token's ``tid``, read only to choose the issuer it must then verify against.""" + try: + tid = jwt.decode(id_token, options={"verify_signature": False}).get("tid") + except jwt.PyJWTError: + return None + return tid if isinstance(tid, str) and _GUID_RE.fullmatch(tid) else None diff --git a/modules/users/users/oauth/providers.py b/modules/users/users/oauth/providers.py index 7d68bd9e..d950b25e 100644 --- a/modules/users/users/oauth/providers.py +++ b/modules/users/users/oauth/providers.py @@ -12,7 +12,9 @@ from __future__ import annotations import logging -from typing import TYPE_CHECKING, Any, NamedTuple +from typing import TYPE_CHECKING, Any, NamedTuple, TypedDict + +from auth.oidc_common.session import pkce_challenge from users.core.oauth_settings import is_tenant_guid @@ -24,6 +26,13 @@ logger = logging.getLogger(__name__) +class LoginSecrets(TypedDict): + """Per-login PKCE verifier and OIDC nonce, kept in the session with the state.""" + + verifier: str + nonce: str + + class OAuthProvider(NamedTuple): """One configured provider — name is the URL segment (``/auth/``).""" @@ -33,30 +42,56 @@ class OAuthProvider(NamedTuple): # Microsoft only: the operator trusts member UPNs of the pinned tenant (#873). trust_email: bool = False - async def get_identity(self, token: str) -> tuple[str, str | None, bool]: + @property + def uses_pkce(self) -> bool: + """Whether a login carries a PKCE verifier and an OIDC nonce (#876).""" + return getattr(self.client, "uses_pkce", False) is True + + async def authorization_url(self, callback: str, state: str, login: LoginSecrets | None) -> str: + """The IdP URL to send the browser to, bound to this login's secrets.""" + if login is None: + return await self.client.get_authorization_url(callback, state) + return await self.client.get_authorization_url( + callback, + state, + code_challenge=pkce_challenge(login["verifier"]), + code_challenge_method="S256", + extras_params={"nonce": login["nonce"]}, + ) + + async def exchange_code( + self, code: str, callback: str, login: LoginSecrets | None + ) -> dict[str, Any]: + """The token endpoint's response for this authorization code.""" + if login is None: + return await self.client.get_access_token(code, callback) + return await self.client.get_access_token(code, callback, code_verifier=login["verifier"]) + + async def get_identity( + self, token: dict[str, Any], login: LoginSecrets | None = None + ) -> tuple[str, str | None, bool]: """Return subject, email, and proof that the provider verified that email. - ``get_id_email`` drops verification metadata, so each provider reads it - from its own profile shape. Only a positive proof links an existing - account or marks a new one verified (#622). + ``token`` is the whole token response, so an OIDC provider can read its + ID token (#876). ``get_id_email`` drops verification metadata, so each + provider reads it from its own profile shape. Only a positive proof + links an existing account or marks a new one verified (#622). """ + if self.uses_pkce: + nonce = login["nonce"] if login else None + return await self.client.identity(token, nonce, trust_email=self.trust_email) + access_token = token["access_token"] if self.name == "oidc": - profile = await self.client.get_profile(token) + profile = await self.client.get_profile(access_token) return str(profile["sub"]), profile.get("email"), profile.get("email_verified") is True if self.name == "google": - return _google_identity(await self.client.get_profile(token)) - account_id, email = await self.client.get_id_email(token) + return _google_identity(await self.client.get_profile(access_token)) + account_id, email = await self.client.get_id_email(access_token) if email is None: return account_id, None, False if self.name == "github": - return account_id, email, await _github_verified(self.client, token, email) - # Microsoft (Entra) email claims are tenant-controlled and unverified - # ("nOAuth"), unless the operator pinned one tenant and trusts its member - # UPNs. A guest's UPN (``#EXT#``) belongs to another directory. - trusted = ( - self.trust_email and bool(account_id) and bool(email) and "#EXT#" not in email.upper() - ) - return account_id, email, trusted + return account_id, email, await _github_verified(self.client, access_token, email) + return account_id, email, False def _google_identity(profile: dict[str, Any]) -> tuple[str, str | None, bool]: @@ -117,17 +152,16 @@ def build_clients(settings: UsersSettings) -> list[OAuthProvider]: ) if settings.oauth_microsoft_client_id and settings.oauth_microsoft_client_secret: - from httpx_oauth.clients.microsoft import MicrosoftGraphOAuth2 + from users.oauth.microsoft import MicrosoftOidc out.append( OAuthProvider( "microsoft", "Microsoft", - MicrosoftGraphOAuth2( + MicrosoftOidc( settings.oauth_microsoft_client_id, settings.oauth_microsoft_client_secret, - tenant=settings.oauth_microsoft_tenant or "common", - name="microsoft", + settings.oauth_microsoft_tenant or "common", ), trust_email=settings.oauth_microsoft_trust_tenant_upn and is_tenant_guid(settings.oauth_microsoft_tenant),