From ac970970dbb84fbc2394d489d1e5c6116af5a2f5 Mon Sep 17 00:00:00 2001 From: Anto Subash Date: Wed, 11 Nov 2026 20:44:28 +0100 Subject: [PATCH 01/12] docs: oauth-profile-trusted-domains design (#877 #878) Claude-Session: https://claude.ai/code/session_01M9neheZZEe3sVpDi2S3zT4 --- ...11-oauth-profile-trusted-domains-design.md | 90 +++++++++++++++++++ 1 file changed, 90 insertions(+) create mode 100644 docs/superpowers/specs/2026-11-11-oauth-profile-trusted-domains-design.md diff --git a/docs/superpowers/specs/2026-11-11-oauth-profile-trusted-domains-design.md b/docs/superpowers/specs/2026-11-11-oauth-profile-trusted-domains-design.md new file mode 100644 index 00000000..eda86e38 --- /dev/null +++ b/docs/superpowers/specs/2026-11-11-oauth-profile-trusted-domains-design.md @@ -0,0 +1,90 @@ +# OAuth identity profile and trusted email domains (#877, #878) + +## Goal & scope + +**#877.** An OAuth sign-in keeps only `oauth_name`, `account_id`, +`account_email` and tokens. Store the IdP's profile so administrators can see +which identity an account belongs to and a provider that changes its key has +something to migrate from, and use the IdP's name for the account. + +**#878.** Email trust is all-or-nothing per provider. Let an operator trust +addresses on domains their organisation owns, per provider, and nothing else. + +Both change what a provider returns from `get_identity`, so they ship together. +Out of scope: changing the account email from the IdP (unique-email +collisions), #879's local IdP. + +## Approach + +`OAuthProvider.get_identity` returns an `OAuthIdentity` (frozen dataclass) +instead of a 3-tuple: `account_id`, `email`, `email_verified`, `subject`, +`username`, `display_name`, `extra` (small dict of provider-specific ids). The +callback applies trusted domains to it, runs the existing find-or-create, then +writes the profile onto the linked `OAuthAccount`. + +Rejected: a separate `users_oauth_identity` table (the link row already is one +per identity), and a single global domain list (a domain trusted for Microsoft +must not become trusted for GitHub). + +## Design + +### Profile (#877) + +- `OAuthAccount` gains nullable `subject` (320), `username` (320), + `display_name` (320), `extra` (JSON), `last_sign_in_at` (`AwareDateTime`). + One migration on the users trunk (`--head users@head`); no backfill. +- Each provider fills the profile from what it already fetches: + OIDC: `sub`, `preferred_username`, `name`; Google: `resourceName`, primary + address, `names[0].displayName`; GitHub: `id`, `login`, `name`; Microsoft: + `sub`, `upn`/`preferred_username`, `name`, `extra = {oid, tid}`. +- After `oauth_callback`, the callback updates the link row (same request + session, committed by the middleware) and stamps `last_sign_in_at`. +- `User.full_name`: set from `display_name` when the callback creates the + account; on later sign-ins only when the new `oauth_sync_profile` setting is + on (default off), and never to an empty value. The email is never changed. +- Admin **Edit user** page: a "Linked sign-ins" section listing provider, + username, subject and last sign-in per link (read-only). New `en.json` keys; + `make gen-i18n` and `make gen-api-types`. + +### Trusted email domains (#878) + +- `oauth_trusted_email_domains: dict[str, list[str]] = {}`, e.g. + `{"microsoft": ["iiasa.ac.at"]}`; keys validated against the provider names, + domains lowercased and IDNA-normalised, no wildcards. +- The email becomes verified only when its domain is listed **exactly** for + that provider (no subdomains) **and** the provider's own identity checks + pass. For Microsoft that means a GUID tenant equal to `tid`, no foreign + `idp`, no `#EXT#` (the #873 member checks without requiring the UPN trust + flag); for Microsoft the address is the `email` claim on a listed domain, + else `upn`/`preferred_username` on a listed domain. Other providers: the + address they returned. +- A domain listed for Microsoft while the tenant is not a GUID logs + `users.oauth.trusted_domains_ignored` and has no effect. + +## Decisions made + +- One PR for both issues (shared `OAuthIdentity`). +- `oauth_sync_profile` default off; `full_name` only, never the email. +- A listed domain is the operator's statement, so for Google, GitHub and OIDC + it makes the returned address verified even when the provider gave no + proof; Microsoft additionally needs the member checks, because its claims + are editable by the tenant. +- `extra` is limited to Microsoft's `oid`/`tid` for now. + +## Testing + +- Unit: each provider's `OAuthIdentity`; domain matching (case, IDNA, + subdomain refused, other provider's list ignored); Microsoft email choice. +- Flow: profile columns written on create and on later sign-in; + `last_sign_in_at` stamped; `full_name` set on create, synced only with the + setting; a listed domain links a verified local account; a guest on a + listed domain does not. +- Migration: `make doctor`, `alembic check` (CI), Postgres round trip (CI). +- Admin page: Vitest for the "Linked sign-ins" section; a browser check of the + Edit page with a seeded link. + +## Risks + +- `oauth_callback` (fastapi-users) owns the link-row write; the profile update + runs after it in the same session. If a future fastapi-users version changes + that, the update still works (it looks the row up by provider and account id). From 158a827241e241779084196882d3d306d60f00f5 Mon Sep 17 00:00:00 2001 From: Anto Subash Date: Wed, 11 Nov 2026 20:47:39 +0100 Subject: [PATCH 02/12] feat(users): OAuthIdentity and trusted-domain settings (#877 #878) Claude-Session: https://claude.ai/code/session_01M9neheZZEe3sVpDi2S3zT4 --- ...026-11-11-oauth-profile-trusted-domains.md | 15 +++++ .../test_users_oauth_signup_settings.py | 3 +- .../test_users_oauth_trusted_domains.py | 42 ++++++++++++++ modules/users/users/core/oauth_settings.py | 56 +++++++++++++++++++ modules/users/users/oauth/identity.py | 43 ++++++++++++++ 5 files changed, 158 insertions(+), 1 deletion(-) create mode 100644 docs/superpowers/plans/2026-11-11-oauth-profile-trusted-domains.md create mode 100644 modules/users/tests/oauth/identity/test_users_oauth_trusted_domains.py create mode 100644 modules/users/users/oauth/identity.py diff --git a/docs/superpowers/plans/2026-11-11-oauth-profile-trusted-domains.md b/docs/superpowers/plans/2026-11-11-oauth-profile-trusted-domains.md new file mode 100644 index 00000000..0ad38745 --- /dev/null +++ b/docs/superpowers/plans/2026-11-11-oauth-profile-trusted-domains.md @@ -0,0 +1,15 @@ +# Plan: OAuth identity profile + trusted email domains (#877, #878) + +Design: `docs/superpowers/specs/2026-11-11-oauth-profile-trusted-domains-design.md`. Sequential. + +1. `users/oauth/identity.py`: `OAuthIdentity`, `normalize_domain`, `email_on_domains`. Unit tests. +2. Settings (`users/core/oauth_settings.py`): `oauth_trusted_email_domains` (validated, normalised), + `oauth_sync_profile`; warning when Microsoft domains are listed without a GUID tenant. +3. Providers return `OAuthIdentity` with subject/username/display_name/extra; generic providers apply + their trusted domains; Microsoft chooses `email` → `upn`/`preferred_username` on a listed domain and + needs the member checks. Update provider/flow tests. +4. `OAuthAccount` columns + migration (`--head users@head`); `users/oauth/profile.py` writes the + profile and `last_sign_in_at` after `oauth_callback`, sets/syncs `full_name`. Flow tests. +5. Admin Edit page: `linked_sign_ins` prop (`admin/queries.py`), `LinkedSignInsCard.tsx`, en.json keys, + gen-i18n; Vitest. +6. Docs (README, docs/modules/users.md), CHANGELOG; `make lint`, `make doctor`, users tests. diff --git a/modules/users/tests/core/settings/test_users_oauth_signup_settings.py b/modules/users/tests/core/settings/test_users_oauth_signup_settings.py index 182582f7..f0108775 100644 --- a/modules/users/tests/core/settings/test_users_oauth_signup_settings.py +++ b/modules/users/tests/core/settings/test_users_oauth_signup_settings.py @@ -54,4 +54,5 @@ def test_oauth_fields_follow_the_core_fields(): 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"] + first_oauth = fields.index("oauth_google_client_id") + assert all(name.startswith("oauth_") for name in fields[first_oauth:]) diff --git a/modules/users/tests/oauth/identity/test_users_oauth_trusted_domains.py b/modules/users/tests/oauth/identity/test_users_oauth_trusted_domains.py new file mode 100644 index 00000000..890caf6a --- /dev/null +++ b/modules/users/tests/oauth/identity/test_users_oauth_trusted_domains.py @@ -0,0 +1,42 @@ +"""Exact, normalised domain matching for trusted OAuth emails (#878).""" + +import pytest +from users.oauth.identity import OAuthIdentity, email_on_domains, normalize_domain + +_DOMAINS = frozenset({"iiasa.ac.at", "xn--bcher-kva.example"}) + + +@pytest.mark.parametrize( + "email, expected", + [ + ("jane@iiasa.ac.at", True), + ("Jane@IIASA.AC.AT", True), + ("jane@bücher.example", True), + ("jane@mail.iiasa.ac.at", False), + ("jane@iiasa.ac.at.evil.com", False), + ("jane@notiiasa.ac.at", False), + ("jane@other.org", False), + ("a@b@iiasa.ac.at", False), + ("", False), + (None, False), + ], +) +def test_email_on_domains_is_exact(email, expected): + assert email_on_domains(email, _DOMAINS) is expected + + +@pytest.mark.parametrize("bad", ["", "*.iiasa.ac.at", ".iiasa.ac.at", "a@iiasa.ac.at", " "]) +def test_normalize_domain_refuses_non_domains(bad): + with pytest.raises(ValueError): + normalize_domain(bad) + + +def test_normalize_domain_lowercases_and_encodes(): + assert normalize_domain(" Bücher.Example. ") == "xn--bcher-kva.example" + + +def test_trusting_marks_only_a_listed_domain_verified(): + identity = OAuthIdentity("1", "jane@iiasa.ac.at", False) + assert identity.trusting(_DOMAINS).email_verified is True + other = OAuthIdentity("1", "jane@other.org", False) + assert other.trusting(_DOMAINS) is other diff --git a/modules/users/users/core/oauth_settings.py b/modules/users/users/core/oauth_settings.py index 279eee8a..b4f5180b 100644 --- a/modules/users/users/core/oauth_settings.py +++ b/modules/users/users/core/oauth_settings.py @@ -25,6 +25,17 @@ MICROSOFT_CONSUMERS_TENANT = uuid.UUID("9188040d-6c67-4c5b-b112-36a304b66dad") +def normalize_domain(domain: str) -> str: + """Lowercase, IDNA-encoded form used for exact domain comparison.""" + value = domain.strip().rstrip(".").lower() + if not value or "@" in value or "*" in value or value.startswith("."): + raise ValueError(f"not a domain: {domain!r}") + try: + return value.encode("idna").decode("ascii") + except UnicodeError as exc: + raise ValueError(f"not a domain: {domain!r}") from exc + + def is_tenant_guid(tenant: str) -> bool: """Whether a Microsoft ``tenant`` pins one work/school directory (a canonical GUID). @@ -120,3 +131,48 @@ def _no_admin_provisioning(cls, value: str) -> str: if value.lower() == ADMIN_ROLE_NAME: raise ValueError("SSO-provisioned accounts cannot get the admin role automatically") return value + + # Addresses on these domains count as verified for that provider only, e.g. + # ``{"microsoft": ["iiasa.ac.at"]}`` (#878). Exact domains, no subdomains. + # Microsoft additionally needs a member of a pinned tenant GUID. + oauth_trusted_email_domains: dict[str, list[str]] = Field( + default_factory=dict, json_schema_extra={"group": OAUTH_PROVISIONING_GROUP} + ) + # Update ``full_name`` from the IdP's display name on every sign-in, not + # only when the account is created (#877). The email is never changed. + oauth_sync_profile: bool = Field( + default=False, json_schema_extra={"group": OAUTH_PROVISIONING_GROUP} + ) + + @field_validator("oauth_trusted_email_domains") + @classmethod + def _normalise_trusted_domains(cls, value: dict[str, list[str]]) -> dict[str, list[str]]: + out: dict[str, list[str]] = {} + for provider, domains in value.items(): + name = provider.strip().lower() + if name not in OAUTH_PROVIDER_NAMES: + known = sorted(OAUTH_PROVIDER_NAMES) + raise ValueError(f"unknown OAuth provider {provider!r}; expected any of {known}") + out[name] = sorted({normalize_domain(domain) for domain in domains}) + return out + + @model_validator(mode="after") + def _warn_on_ignored_microsoft_domains(self) -> OAuthSettings: + """Microsoft emails are tenant-editable: a domain needs one pinned tenant.""" + if self.oauth_trusted_email_domains.get("microsoft") and not is_tenant_guid( + self.oauth_microsoft_tenant + ): + logger.warning( + "users.oauth.trusted_domains_ignored — oauth_trusted_email_domains lists " + "domains for microsoft but oauth_microsoft_tenant=%r is not one work/school " + "tenant GUID; those domains are not trusted.", + self.oauth_microsoft_tenant, + ) + return self + + def trusted_domains(self, provider: str) -> frozenset[str]: + """The domains whose addresses ``provider`` may verify (#878).""" + domains = self.oauth_trusted_email_domains.get(provider, []) + if provider == "microsoft" and not is_tenant_guid(self.oauth_microsoft_tenant): + return frozenset() + return frozenset(domains) diff --git a/modules/users/users/oauth/identity.py b/modules/users/users/oauth/identity.py new file mode 100644 index 00000000..1cec22da --- /dev/null +++ b/modules/users/users/oauth/identity.py @@ -0,0 +1,43 @@ +"""What a provider tells the callback about the person signing in (#877, #878).""" + +from __future__ import annotations + +from collections.abc import Collection +from dataclasses import dataclass, field, replace +from typing import Any + +from users.core.oauth_settings import normalize_domain + + +@dataclass(frozen=True) +class OAuthIdentity: + """One sign-in's identity: the link key, the email and its proof, and the profile. + + ``subject``, ``username``, ``display_name`` and ``extra`` are stored on the + ``OAuthAccount`` link and refreshed on every sign-in; only ``display_name`` + reaches the account itself (``User.full_name``). + """ + + account_id: str + email: str | None + email_verified: bool + subject: str | None = None + username: str | None = None + display_name: str | None = None + extra: dict[str, Any] = field(default_factory=dict) + + def trusting(self, domains: Collection[str]) -> OAuthIdentity: + """This identity with its email verified when it sits on one of ``domains``.""" + if self.email_verified or not email_on_domains(self.email, domains): + return self + return replace(self, email_verified=True) + + +def email_on_domains(email: str | None, domains: Collection[str]) -> bool: + """Whether ``email``'s domain is exactly one of ``domains`` (no subdomains).""" + if not email or not domains or email.count("@") != 1: + return False + try: + return normalize_domain(email.rsplit("@", 1)[1]) in domains + except ValueError: + return False From e0607926e515231c95c980b5f7522b730957895e Mon Sep 17 00:00:00 2001 From: Anto Subash Date: Wed, 11 Nov 2026 20:53:18 +0100 Subject: [PATCH 03/12] feat(users): providers return OAuthIdentity; trusted email domains (#877 #878) get_identity returns an OAuthIdentity with subject, username, display name and (Microsoft) oid/tid. oauth_trusted_email_domains lets microsoft (a member of a pinned tenant: upn/preferred_username, or email only with xms_edov) and oidc vouch for addresses on listed domains. Google and GitHub are refused: anyone can add an unverified address on any domain there. Claude-Session: https://claude.ai/code/session_01M9neheZZEe3sVpDi2S3zT4 --- ...est_users_oauth_trusted_domain_settings.py | 55 ++++++++++++ .../flow/test_users_oauth_email_claim.py | 26 ++++-- .../test_users_oauth_provider_identity.py | 14 ++- .../test_users_oauth_microsoft_id_token.py | 46 ++++++++-- modules/users/users/core/oauth_settings.py | 16 +++- modules/users/users/oauth/api.py | 8 +- modules/users/users/oauth/microsoft.py | 85 ++++++++++++++----- modules/users/users/oauth/providers.py | 78 ++++++++++++----- 8 files changed, 265 insertions(+), 63 deletions(-) create mode 100644 modules/users/tests/core/settings/test_users_oauth_trusted_domain_settings.py diff --git a/modules/users/tests/core/settings/test_users_oauth_trusted_domain_settings.py b/modules/users/tests/core/settings/test_users_oauth_trusted_domain_settings.py new file mode 100644 index 00000000..c23d6d2f --- /dev/null +++ b/modules/users/tests/core/settings/test_users_oauth_trusted_domain_settings.py @@ -0,0 +1,55 @@ +"""``oauth_trusted_email_domains`` and ``oauth_sync_profile`` settings (#877, #878).""" + +import logging + +import pytest +from pydantic import ValidationError +from users.core.settings import UsersSettings + +_GUID = "6f1c2a3b-4d5e-4f60-8a7b-9c0d1e2f3a4b" + + +def test_defaults_trust_nothing_and_do_not_sync(): + settings = UsersSettings() + assert settings.oauth_trusted_email_domains == {} + assert settings.oauth_sync_profile is False + assert settings.trusted_domains("oidc") == frozenset() + + +def test_domains_are_normalised_per_provider(): + settings = UsersSettings( + oauth_trusted_email_domains={" OIDC ": ["IIASA.ac.at", "bücher.example"]} + ) + assert settings.oauth_trusted_email_domains == { + "oidc": ["iiasa.ac.at", "xn--bcher-kva.example"] + } + assert settings.trusted_domains("oidc") == {"iiasa.ac.at", "xn--bcher-kva.example"} + assert settings.trusted_domains("google") == frozenset() + + +@pytest.mark.parametrize( + "value", + [ + {"facebook": ["a.org"]}, + # Anyone can add an unverified address on any domain to these accounts. + {"github": ["a.org"]}, + {"google": ["a.org"]}, + {"oidc": ["*.a.org"]}, + {"oidc": [".a.org"]}, + ], +) +def test_bad_entries_are_rejected(value): + with pytest.raises(ValidationError) as exc: + UsersSettings(oauth_trusted_email_domains=value) + assert exc.value.errors()[0]["loc"][0] == "oauth_trusted_email_domains" + + +def test_microsoft_domains_need_a_pinned_tenant(caplog): + with caplog.at_level(logging.WARNING, logger="users.settings"): + common = UsersSettings(oauth_trusted_email_domains={"microsoft": ["iiasa.ac.at"]}) + assert "users.oauth.trusted_domains_ignored" in caplog.text + assert common.trusted_domains("microsoft") == frozenset() + pinned = UsersSettings( + oauth_microsoft_tenant=_GUID, oauth_trusted_email_domains={"microsoft": ["iiasa.ac.at"]} + ) + assert pinned.trusted_domains("microsoft") == {"iiasa.ac.at"} 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 041ba785..80900db8 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,12 @@ from users.oauth import OAuthProvider _EMAIL = "victim@example.com" + + +def _triple(identity): + return identity.account_id, identity.email, identity.email_verified + + _TOKEN = {"access_token": "token"} @@ -112,7 +118,7 @@ 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) == ( + assert _triple(await provider.get_identity(_TOKEN)) == ( "idp-attacker", _EMAIL, verified, @@ -125,13 +131,8 @@ async def test_oidc_identity_preserves_email_proof(claim, verified): 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( - {"access_token": "token"} - ) == ( - "idp-attacker", - _EMAIL, - False, - ) + identity = await OAuthProvider(provider, provider, client).get_identity(_TOKEN) + assert _triple(identity) == ("idp-attacker", _EMAIL, False) @pytest.mark.anyio @@ -149,3 +150,12 @@ async def test_unproven_sso_account_cannot_capture_a_later_verified_login(users_ 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 == {"github"} + + +@pytest.mark.anyio +async def test_oidc_trusted_domain_counts_as_proof(): + client = _ClaimClient({}) + provider = OAuthProvider("oidc", "OIDC", client, trusted_domains=frozenset({"example.com"})) + assert (await provider.get_identity(_TOKEN)).email_verified is True + other = OAuthProvider("oidc", "OIDC", client, trusted_domains=frozenset({"corp.com"})) + assert (await other.get_identity(_TOKEN)).email_verified is False 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 f555b6c1..c39fc57c 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,11 @@ import pytest from users.oauth import OAuthProvider + +def _triple(identity): + return identity.account_id, identity.email, identity.email_verified + + _TOKEN = {"access_token": "t"} @@ -27,6 +32,9 @@ def __init__(self, emails, fail=False): async def get_id_email(self, token): return "42", "me@example.com" + async def get_profile(self, token): + return {"id": 42, "login": "octo", "name": "Octo Cat"} + async def get_emails(self, token): if self.fail: raise RuntimeError("scope missing") @@ -36,7 +44,7 @@ async def get_emails(self, token): @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(_TOKEN) == ( + assert _triple(await provider.get_identity(_TOKEN)) == ( "people/1", "me@example.com", verified is True, @@ -53,9 +61,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(_TOKEN) == ("42", "me@example.com", expected) + assert _triple(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(_TOKEN))[2] is False + assert (await provider.get_identity(_TOKEN)).email_verified is False 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 index 35c7cd0e..28ae93e1 100644 --- 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 @@ -19,7 +19,14 @@ async def _identity(client: FakeMicrosoft, token: str, *, trust: bool = False): 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) + identity = await _identity(FakeMicrosoft(), token) + assert (identity.account_id, identity.email, identity.email_verified) == ( + OID, + "jane@corp.com", + False, + ) + assert identity.subject == "pairwise-sub" + assert identity.extra == {"oid": OID, "tid": TENANT} @pytest.mark.parametrize( @@ -80,7 +87,7 @@ async def test_a_pinned_tenant_refuses_another_tenant(): 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 + assert (await _identity(FakeMicrosoft(tenant), token)).account_id == OID else: with pytest.raises(IdTokenError): await _identity(FakeMicrosoft(tenant), token) @@ -118,7 +125,7 @@ async def test_the_signed_tid_must_match_the_issuer(): ) 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 + assert (await _identity(FakeMicrosoft(tenant), token, trust=True)).email_verified is trusted @pytest.mark.parametrize( @@ -135,9 +142,38 @@ def test_account_ids_match_what_graph_returned(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 + assert (await _identity(FakeMicrosoft(), token)).email 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" + assert (await _identity(FakeMicrosoft(), sign(claims))).email == "jane@corp.com" + + +_DOMAINS = frozenset({"corp.com"}) + + +@pytest.mark.parametrize( + "tenant, claims, email, verified", + [ + (TENANT, {}, "jane@corp.com", True), + # ``email`` is user-editable: only a domain Entra verified (xms_edov) counts. + (TENANT, {"preferred_username": "j@x.org", "email": "jane@corp.com"}, "j@x.org", False), + ( + TENANT, + {"preferred_username": "j@x.org", "email": "jane@corp.com", "xms_edov": True}, + "jane@corp.com", + True, + ), + (TENANT, {"preferred_username": "jane@mail.corp.com"}, "jane@mail.corp.com", False), + (TENANT, {"idp": "https://sts.windows.net/other/"}, "jane@corp.com", False), + ("common", {}, "jane@corp.com", False), + ], + ids=["upn-on-domain", "email-unverified", "email-xms-edov", "subdomain", "guest", "common"], +) +async def test_trusted_domains_need_a_member(tenant, claims, email, verified): + token = sign(id_claims(nonce=_NONCE, **claims)) + identity = await FakeMicrosoft(tenant).identity( + {"id_token": token}, _NONCE, trust_email=False, trusted_domains=_DOMAINS + ) + assert (identity.email, identity.email_verified) == (email, verified) diff --git a/modules/users/users/core/oauth_settings.py b/modules/users/users/core/oauth_settings.py index b4f5180b..9477678c 100644 --- a/modules/users/users/core/oauth_settings.py +++ b/modules/users/users/core/oauth_settings.py @@ -20,6 +20,9 @@ # The ``{provider}`` URL segments ``users.oauth.providers.build_clients`` can serve. OAUTH_PROVIDER_NAMES = frozenset({"google", "github", "microsoft", "oidc"}) OAUTH_PROVISIONING_GROUP = "OAuth provisioning" +# Providers whose directory the domain's owner controls: a pinned Entra tenant, +# or the operator's own OIDC IdP (#878). Not Google or GitHub. +DOMAIN_TRUST_PROVIDERS = frozenset({"microsoft", "oidc"}) # Microsoft's fixed "consumers" tenant (personal accounts): a GUID, but not one directory. MICROSOFT_CONSUMERS_TENANT = uuid.UUID("9188040d-6c67-4c5b-b112-36a304b66dad") @@ -134,7 +137,8 @@ def _no_admin_provisioning(cls, value: str) -> str: # Addresses on these domains count as verified for that provider only, e.g. # ``{"microsoft": ["iiasa.ac.at"]}`` (#878). Exact domains, no subdomains. - # Microsoft additionally needs a member of a pinned tenant GUID. + # Only ``microsoft`` (a member of a pinned tenant GUID) and ``oidc`` (your + # own IdP) can be listed. oauth_trusted_email_domains: dict[str, list[str]] = Field( default_factory=dict, json_schema_extra={"group": OAUTH_PROVISIONING_GROUP} ) @@ -150,9 +154,13 @@ def _normalise_trusted_domains(cls, value: dict[str, list[str]]) -> dict[str, li out: dict[str, list[str]] = {} for provider, domains in value.items(): name = provider.strip().lower() - if name not in OAUTH_PROVIDER_NAMES: - known = sorted(OAUTH_PROVIDER_NAMES) - raise ValueError(f"unknown OAuth provider {provider!r}; expected any of {known}") + if name not in DOMAIN_TRUST_PROVIDERS: + allowed = sorted(DOMAIN_TRUST_PROVIDERS) + raise ValueError( + f"domain trust is not available for {provider!r}; allowed: {allowed}. " + "Anyone can add an unverified address on any domain to a Google or " + "GitHub account, so a domain cannot vouch for it there." + ) out[name] = sorted({normalize_domain(domain) for domain in domains}) return out diff --git a/modules/users/users/oauth/api.py b/modules/users/users/oauth/api.py index 94b7a8d7..de18c466 100644 --- a/modules/users/users/oauth/api.py +++ b/modules/users/users/oauth/api.py @@ -166,15 +166,15 @@ async def callback( callback_url = str(request.url_for(_CALLBACK_ROUTE_NAME, provider=provider)) try: token = await provider_obj.exchange_code(code, callback_url, login) - account_id, account_email, email_verified = await provider_obj.get_identity( - token, login - ) + identity = await provider_obj.get_identity(token, login) 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: + if identity.email is None: return refuse_login(request, "OAUTH_NO_EMAIL") + account_id, account_email = identity.account_id, identity.email + email_verified = identity.email_verified existing, linked = await _existing_account( user_manager, provider, account_id, account_email diff --git a/modules/users/users/oauth/microsoft.py b/modules/users/users/oauth/microsoft.py index b7fc786f..4343e6ce 100644 --- a/modules/users/users/oauth/microsoft.py +++ b/modules/users/users/oauth/microsoft.py @@ -11,6 +11,7 @@ import re import secrets from collections import OrderedDict +from collections.abc import Collection from typing import Any import jwt @@ -19,6 +20,7 @@ from httpx_oauth.exceptions import HTTPXOAuthError from users.core.oauth_settings import MICROSOFT_CONSUMERS_TENANT, is_tenant_guid +from users.oauth.identity import OAuthIdentity, email_on_domains _LOGIN_HOST = "https://login.microsoftonline.com" _SCOPES = ["openid", "profile", "email"] @@ -46,12 +48,48 @@ def __init__(self, client_id: str, client_secret: str, tenant: str) -> None: 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). + self, + token: dict[str, Any], + nonce: str | None, + *, + trust_email: bool, + trusted_domains: Collection[str] = (), + ) -> OAuthIdentity: + """Validate the ID token; return the Graph-compatible identity and profile. Raises :class:`IdTokenError` for a missing, invalid or foreign token. """ + claims, tid = await self._validated_claims(token, nonce) + 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") + member = ( + is_tenant_guid(self.tenant) + and tid == self.tenant + and (idp is None or (isinstance(idp, str) and idp in _home_issuers(tid))) + ) + trusted = trust_email and member and email is not None and "#EXT#" not in email.upper() + # A member's address on a domain the operator owns is proof too (#878). + on_domain = _domain_email(claims, trusted_domains) if member else None + if on_domain is not None: + email, trusted = on_domain, True + return OAuthIdentity( + account_id=graph_account_id(oid), + email=email, + email_verified=bool(trusted), + subject=claims["sub"], + username=email or _text(claims.get("preferred_username")), + display_name=_text(claims.get("name")), + extra={"oid": oid, "tid": tid}, + ) + + async def _validated_claims( + self, token: dict[str, Any], nonce: str | None + ) -> tuple[dict[str, Any], str]: id_token = token.get("id_token") if not isinstance(id_token, str) or not nonce: raise IdTokenError("ID token missing") @@ -66,22 +104,7 @@ async def identity( 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 + return claims, tid def _accepts_tenant(self, tid: str) -> bool: if self.tenant == "consumers": @@ -132,6 +155,30 @@ def _account_email(claims: dict[str, Any]) -> str | None: return None +def _domain_email(claims: dict[str, Any], domains: Collection[str]) -> str | None: + """The UPN or username on a trusted domain, else a domain-verified ``email``. + + ``email`` is editable by the user and unverified unless Entra marks its + domain as verified with the ``xms_edov`` optional claim. + """ + names = ["upn", "preferred_username"] + if claims.get("xms_edov") is True: + names.append("email") + for name in names: + value = claims.get(name) + if ( + isinstance(value, str) + and "#EXT#" not in value.upper() + and email_on_domains(value, domains) + ): + return value + return None + + +def _text(value: object) -> str | None: + return value if isinstance(value, str) and value.strip() else 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}/"} diff --git a/modules/users/users/oauth/providers.py b/modules/users/users/oauth/providers.py index d950b25e..9e4acdb3 100644 --- a/modules/users/users/oauth/providers.py +++ b/modules/users/users/oauth/providers.py @@ -17,6 +17,7 @@ from auth.oidc_common.session import pkce_challenge from users.core.oauth_settings import is_tenant_guid +from users.oauth.identity import OAuthIdentity if TYPE_CHECKING: from httpx_oauth.oauth2 import BaseOAuth2 @@ -41,6 +42,8 @@ class OAuthProvider(NamedTuple): client: BaseOAuth2 # Microsoft only: the operator trusts member UPNs of the pinned tenant (#873). trust_email: bool = False + # Addresses on these domains count as proof for this provider (#878). + trusted_domains: frozenset[str] = frozenset() @property def uses_pkce(self) -> bool: @@ -69,41 +72,76 @@ async def exchange_code( 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. + ) -> OAuthIdentity: + """Who signed in, the email and whether the provider proved it, and the profile. ``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). + ID token (#876). Each provider reads email proof from its own profile + shape; only a positive proof links an existing account or marks a new + one verified (#622). An address on one of the provider's trusted + domains counts as proof too (#878). """ 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"] + return await self.client.identity( + token, + login["nonce"] if login else None, + trust_email=self.trust_email, + trusted_domains=self.trusted_domains, + ) + identity = await self._profile_identity(token["access_token"]) + return identity.trusting(self.trusted_domains) + + async def _profile_identity(self, access_token: str) -> OAuthIdentity: if self.name == "oidc": profile = await self.client.get_profile(access_token) - return str(profile["sub"]), profile.get("email"), profile.get("email_verified") is True + return OAuthIdentity( + str(profile["sub"]), + profile.get("email"), + profile.get("email_verified") is True, + subject=str(profile["sub"]), + username=_text(profile.get("preferred_username")), + display_name=_text(profile.get("name")), + ) if self.name == "google": 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, access_token, email) - return account_id, email, False + if self.name != "github": + return OAuthIdentity(account_id, email, False) + profile = await self.client.get_profile(access_token) + verified = email is not None and await _github_verified(self.client, access_token, email) + return OAuthIdentity( + account_id, + email, + verified, + subject=account_id, + username=_text(profile.get("login")), + display_name=_text(profile.get("name")), + ) -def _google_identity(profile: dict[str, Any]) -> tuple[str, str | None, bool]: - """People API profile → (resourceName, primary email, its ``metadata.verified``).""" +def _text(value: object) -> str | None: + return value if isinstance(value, str) and value.strip() else None + + +def _google_identity(profile: dict[str, Any]) -> OAuthIdentity: + """People API profile → resourceName, primary email and its ``metadata.verified``.""" + subject = str(profile["resourceName"]) + names = profile.get("names") or [{}] + display_name = _text(names[0].get("displayName")) if isinstance(names[0], dict) else None primary = next( (e for e in profile.get("emailAddresses", []) if e.get("metadata", {}).get("primary")), None, ) if primary is None: - return str(profile["resourceName"]), None, False - verified = primary.get("metadata", {}).get("verified") is True - return str(profile["resourceName"]), primary.get("value"), verified + return OAuthIdentity(subject, None, False, subject=subject, display_name=display_name) + return OAuthIdentity( + subject, + primary.get("value"), + primary.get("metadata", {}).get("verified") is True, + subject=subject, + username=primary.get("value"), + display_name=display_name, + ) async def _github_verified(client: Any, token: str, email: str) -> bool: @@ -196,7 +234,7 @@ def build_clients(settings: UsersSettings) -> list[OAuthProvider]: ) ) - return out + return [p._replace(trusted_domains=settings.trusted_domains(p.name)) for p in out] def build_client_map(settings: UsersSettings) -> dict[str, OAuthProvider]: From 9f30d7cabdd09ae2e1065ed269e0d152b960276e Mon Sep 17 00:00:00 2001 From: Anto Subash Date: Wed, 11 Nov 2026 20:56:14 +0100 Subject: [PATCH 04/12] feat(users): store the IdP profile on the OAuth link (#877) OAuthAccount gains subject, username, display_name, extra and last_sign_in_at (migration e480d7dd348f on the users trunk), refreshed on every sign-in. A new account takes full_name from the IdP's display name; later sign-ins update it only with oauth_sync_profile. Claude-Session: https://claude.ai/code/session_01M9neheZZEe3sVpDi2S3zT4 --- docs/database/migrations.md | 2 +- ...480d7dd348f_users_oauth_account_profile.py | 41 ++++++++++++ host/tests/test_migration_graph.py | 4 +- .../oauth/profile/test_users_oauth_profile.py | 64 +++++++++++++++++++ modules/users/users/models/oauth_account.py | 12 +++- modules/users/users/oauth/api.py | 9 +++ modules/users/users/oauth/profile.py | 58 +++++++++++++++++ 7 files changed, 187 insertions(+), 3 deletions(-) create mode 100644 host/migrations/versions/e480d7dd348f_users_oauth_account_profile.py create mode 100644 modules/users/tests/oauth/profile/test_users_oauth_profile.py create mode 100644 modules/users/users/oauth/profile.py diff --git a/docs/database/migrations.md b/docs/database/migrations.md index e117d7e1..f3dba741 100644 --- a/docs/database/migrations.md +++ b/docs/database/migrations.md @@ -71,7 +71,7 @@ The history is **not** a single linear chain. It has several roots and several h | Head | Owning module | Label Alembic reports | |---|---|---| -| `f6c2d4e8b109` | file_storage (tenant browse index) | `api_tokens`, `background_tasks`, `file_storage`, `users` | +| `e480d7dd348f` | users (OAuth link profile, #877) | `api_tokens`, `background_tasks`, `file_storage`, `users` | | `b8d4f2a6c901` | audit_log | `audit_log` | | `f1a9c3d7b2e4` | tenants | `tenants` | | `d263ea727663` | framework (`sm_lease`) | `leases` | diff --git a/host/migrations/versions/e480d7dd348f_users_oauth_account_profile.py b/host/migrations/versions/e480d7dd348f_users_oauth_account_profile.py new file mode 100644 index 00000000..0f542e8a --- /dev/null +++ b/host/migrations/versions/e480d7dd348f_users_oauth_account_profile.py @@ -0,0 +1,41 @@ +"""users: store the IdP profile on the OAuth link (#877) + +Revision ID: e480d7dd348f +Revises: f6c2d4e8b109 +Create Date: 2026-11-11 20:53:38.720371 +""" + +from collections.abc import Sequence + +import sqlalchemy as sa +from alembic import op +from simple_module_db.types import AwareDateTime + +# revision identifiers, used by Alembic. +revision: str = "e480d7dd348f" +down_revision: str | None = "f6c2d4e8b109" +branch_labels: str | Sequence[str] | None = None +depends_on: str | Sequence[str] | None = None + + +def upgrade() -> None: + op.add_column("users_oauth_account", sa.Column("subject", sa.String(length=320), nullable=True)) + op.add_column( + "users_oauth_account", sa.Column("username", sa.String(length=320), nullable=True) + ) + op.add_column( + "users_oauth_account", sa.Column("display_name", sa.String(length=320), nullable=True) + ) + op.add_column("users_oauth_account", sa.Column("extra", sa.JSON(), nullable=True)) + op.add_column( + "users_oauth_account", + sa.Column("last_sign_in_at", AwareDateTime(), nullable=True), + ) + + +def downgrade() -> None: + op.drop_column("users_oauth_account", "last_sign_in_at") + op.drop_column("users_oauth_account", "extra") + op.drop_column("users_oauth_account", "display_name") + op.drop_column("users_oauth_account", "username") + op.drop_column("users_oauth_account", "subject") diff --git a/host/tests/test_migration_graph.py b/host/tests/test_migration_graph.py index 02178e74..68656cbc 100644 --- a/host/tests/test_migration_graph.py +++ b/host/tests/test_migration_graph.py @@ -47,6 +47,7 @@ "e731a1b2c3d4": "users", # unique lower(email) (#731) "e805a1b2c3d4": "users", # browser session retirement "f6c2d4e8b109": "file_storage", # tenant browse index + "e480d7dd348f": "users", # OAuth link profile (#877) "51b2058d8afd": "api_tokens", "168a2882f443": "keycloak", "f6a3b9d2e8c4": "keycloak", @@ -73,7 +74,7 @@ # head revision -> module owning the tables it creates or alters. _HEADS = { "b8d4f2a6c901": "audit_log", - "f6c2d4e8b109": "file_storage", # also carries ``api_tokens``, ``background_tasks``, ``users`` + "e480d7dd348f": "users", # also carries ``api_tokens``, ``background_tasks``, ``file_storage`` "f1a9c3d7b2e4": "tenants", "f6a3b9d2e8c4": "keycloak", "c9d2e4f6a810": "oidc", @@ -124,6 +125,7 @@ "e805a1b2c3d4": "api_tokens", "c5d8e2f1a903": "api_tokens", "f6c2d4e8b109": "api_tokens", + "e480d7dd348f": "api_tokens", "a626b1c8d023": "api_tokens", # also inherits ``background_tasks`` "51b2058d8afd": "api_tokens", # ancestors of a labelled revision inherit its label too } diff --git a/modules/users/tests/oauth/profile/test_users_oauth_profile.py b/modules/users/tests/oauth/profile/test_users_oauth_profile.py new file mode 100644 index 00000000..308c19ce --- /dev/null +++ b/modules/users/tests/oauth/profile/test_users_oauth_profile.py @@ -0,0 +1,64 @@ +"""OAuth sign-ins store the IdP profile on the link (#877).""" + +from __future__ import annotations + +import pytest +from _users_microsoft_support import OID, TENANT, install_microsoft +from _users_oauth_support import ( + find_user, + oauth_callback, + seed_password_user, + set_allow_signup, + set_users_settings, +) +from sqlalchemy import select +from users.models import OAuthAccount + +_EMAIL = "jane@corp.com" + + +async def _link(app) -> OAuthAccount: + async with app.state.sm.db.session_factory() as session: + return (await session.execute(select(OAuthAccount))).scalar_one() + + +@pytest.mark.anyio +async def test_a_new_account_gets_the_profile_and_the_name(users_app, anon_client): + set_allow_signup(users_app, True) + install_microsoft(users_app, name="Jane Doe") + + assert (await oauth_callback(anon_client, "microsoft")).status_code == 303 + link = await _link(users_app) + assert (link.subject, link.username, link.display_name) == ("pairwise-sub", _EMAIL, "Jane Doe") + assert link.extra == {"oid": OID, "tid": TENANT} + assert link.last_sign_in_at is not None + assert (await find_user(users_app, _EMAIL)).full_name == "Jane Doe" + + +@pytest.mark.anyio +@pytest.mark.parametrize("sync, expected", [(False, "Jane Doe"), (True, "Jane Smith")]) +async def test_later_sign_ins_sync_the_name_only_when_asked(users_app, anon_client, sync, expected): + set_allow_signup(users_app, True) + install_microsoft(users_app, name="Jane Doe") + assert (await oauth_callback(anon_client, "microsoft")).status_code == 303 + first = (await _link(users_app)).last_sign_in_at + anon_client.cookies.clear() + + set_users_settings(users_app, oauth_sync_profile=sync) + install_microsoft(users_app, name="Jane Smith") + assert (await oauth_callback(anon_client, "microsoft")).status_code == 303 + + link = await _link(users_app) + assert link.display_name == "Jane Smith" + assert link.last_sign_in_at >= first + assert (await find_user(users_app, _EMAIL)).full_name == expected + + +@pytest.mark.anyio +async def test_linking_an_existing_account_keeps_its_name(users_app, anon_client): + await seed_password_user(users_app, _EMAIL, is_verified=True, full_name="J. Doe") + install_microsoft(users_app, name="Jane Doe") + + assert (await oauth_callback(anon_client, "microsoft")).status_code == 303 + assert (await _link(users_app)).display_name == "Jane Doe" + assert (await find_user(users_app, _EMAIL)).full_name == "J. Doe" diff --git a/modules/users/users/models/oauth_account.py b/modules/users/users/models/oauth_account.py index 775caa82..d5674ad1 100644 --- a/modules/users/users/models/oauth_account.py +++ b/modules/users/users/models/oauth_account.py @@ -10,9 +10,12 @@ # Relationship resolution requires runtime annotations. import uuid -from typing import ClassVar +from datetime import datetime +from typing import Any, ClassVar +import sqlalchemy as sa from fastapi_users_db_sqlalchemy.generics import GUID +from simple_module_db.types import AwareDateTime from sqlmodel import Field from users.models._base import Base @@ -42,3 +45,10 @@ class OAuthAccount(Base, table=True): # ty: ignore[unsupported-base] refresh_token: str | None = Field(default=None, max_length=1024) account_id: str = Field(max_length=320, index=True) account_email: str = Field(max_length=320) + # The IdP's profile, refreshed on every sign-in (#877): who the identity is + # at the provider, for administrators and for a provider that changes its key. + subject: str | None = Field(default=None, max_length=320) + username: str | None = Field(default=None, max_length=320) + display_name: str | None = Field(default=None, max_length=320) + extra: dict[str, Any] | None = Field(default=None, sa_type=sa.JSON) + last_sign_in_at: datetime | None = Field(default=None, sa_type=AwareDateTime()) diff --git a/modules/users/users/oauth/api.py b/modules/users/users/oauth/api.py index de18c466..dce11dca 100644 --- a/modules/users/users/oauth/api.py +++ b/modules/users/users/oauth/api.py @@ -31,6 +31,7 @@ from users.core.constants import OAUTH_REGISTRATION_REQUEST_FLAG from users.oauth.errors import refuse_login +from users.oauth.profile import record_profile from users.web.deps import auth_backend, get_user_manager if TYPE_CHECKING: @@ -210,6 +211,14 @@ async def callback( if not user.is_active: return refuse_login(request, "LOGIN_BAD_CREDENTIALS") + await record_profile( + user_manager.user_db.session, + user, + provider, + identity, + created=existing is None, + sync_name=settings.oauth_sync_profile, + ) login_response = await auth_backend.login(strategy, user) await user_manager.on_after_login(user, request, login_response) diff --git a/modules/users/users/oauth/profile.py b/modules/users/users/oauth/profile.py new file mode 100644 index 00000000..379e4337 --- /dev/null +++ b/modules/users/users/oauth/profile.py @@ -0,0 +1,58 @@ +"""Write the IdP's profile onto the OAuth link after a sign-in (#877).""" + +from __future__ import annotations + +from datetime import UTC, datetime +from typing import TYPE_CHECKING + +from sqlalchemy import select +from sqlmodel import col + +from users.models import OAuthAccount, User + +if TYPE_CHECKING: + from sqlalchemy.ext.asyncio import AsyncSession + + from users.oauth.identity import OAuthIdentity + +_LINK_TEXT_MAX = 320 +_FULL_NAME_MAX = 255 + + +async def record_profile( + session: AsyncSession, + user: User, + provider: str, + identity: OAuthIdentity, + *, + created: bool, + sync_name: bool, +) -> None: + """Refresh the link's profile and ``last_sign_in_at``; set ``full_name`` if due. + + ``full_name`` comes from the IdP's display name when this sign-in created + the account, and on later sign-ins only with ``sync_name``. It is never + cleared, and the account email is never touched (unique-email collisions). + Flushed, not committed: the request session commits after the response. + """ + stmt = select(OAuthAccount).where( + col(OAuthAccount.user_id) == user.id, + col(OAuthAccount.oauth_name) == provider, + col(OAuthAccount.account_id) == identity.account_id, + ) + link = (await session.execute(stmt)).scalar_one_or_none() + if link is not None: + link.subject = _clip(identity.subject, _LINK_TEXT_MAX) + link.username = _clip(identity.username, _LINK_TEXT_MAX) + link.display_name = _clip(identity.display_name, _LINK_TEXT_MAX) + link.extra = identity.extra or None + link.last_sign_in_at = datetime.now(UTC) + name = _clip(identity.display_name, _FULL_NAME_MAX) + if name and (sync_name or (created and not user.full_name)) and user.full_name != name: + user.full_name = name + await session.flush() + + +def _clip(value: str | None, limit: int) -> str | None: + value = value.strip() if value else None + return value[:limit] if value else None From 4ffafbbc7e146b686a2c86bfdecf42b5416634df Mon Sep 17 00:00:00 2001 From: Anto Subash Date: Wed, 11 Nov 2026 20:56:45 +0100 Subject: [PATCH 05/12] fix(users): a trusted domain never overrules an IdP's explicit email_verified: false (#878) Claude-Session: https://claude.ai/code/session_01M9neheZZEe3sVpDi2S3zT4 --- .../tests/oauth/flow/test_users_oauth_email_claim.py | 11 +++++++++++ modules/users/users/oauth/identity.py | 9 ++++++++- modules/users/users/oauth/providers.py | 1 + 3 files changed, 20 insertions(+), 1 deletion(-) 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 80900db8..a097d513 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 @@ -159,3 +159,14 @@ async def test_oidc_trusted_domain_counts_as_proof(): assert (await provider.get_identity(_TOKEN)).email_verified is True other = OAuthProvider("oidc", "OIDC", client, trusted_domains=frozenset({"corp.com"})) assert (await other.get_identity(_TOKEN)).email_verified is False + + +@pytest.mark.anyio +async def test_a_trusted_domain_never_overrules_an_explicit_unverified(): + provider = OAuthProvider( + "oidc", + "OIDC", + _ClaimClient({"email_verified": False}), + trusted_domains=frozenset({"example.com"}), + ) + assert (await provider.get_identity(_TOKEN)).email_verified is False diff --git a/modules/users/users/oauth/identity.py b/modules/users/users/oauth/identity.py index 1cec22da..2041aeb6 100644 --- a/modules/users/users/oauth/identity.py +++ b/modules/users/users/oauth/identity.py @@ -25,10 +25,17 @@ class OAuthIdentity: username: str | None = None display_name: str | None = None extra: dict[str, Any] = field(default_factory=dict) + # False when the provider explicitly said the email is NOT verified: a + # trusted domain must not overrule the IdP's own verdict (#878). + domain_trust_allowed: bool = field(default=True, compare=False) def trusting(self, domains: Collection[str]) -> OAuthIdentity: """This identity with its email verified when it sits on one of ``domains``.""" - if self.email_verified or not email_on_domains(self.email, domains): + if ( + self.email_verified + or not self.domain_trust_allowed + or not email_on_domains(self.email, domains) + ): return self return replace(self, email_verified=True) diff --git a/modules/users/users/oauth/providers.py b/modules/users/users/oauth/providers.py index 9e4acdb3..460ad335 100644 --- a/modules/users/users/oauth/providers.py +++ b/modules/users/users/oauth/providers.py @@ -101,6 +101,7 @@ async def _profile_identity(self, access_token: str) -> OAuthIdentity: subject=str(profile["sub"]), username=_text(profile.get("preferred_username")), display_name=_text(profile.get("name")), + domain_trust_allowed=profile.get("email_verified") is not False, ) if self.name == "google": return _google_identity(await self.client.get_profile(access_token)) From 71488593fd34beda459190b51f10ecac3d99c4f0 Mon Sep 17 00:00:00 2001 From: Anto Subash Date: Wed, 11 Nov 2026 20:58:51 +0100 Subject: [PATCH 06/12] feat(users): admin Edit page lists linked sign-ins (#877) Claude-Session: https://claude.ai/code/session_01M9neheZZEe3sVpDi2S3zT4 --- .../tests-js/users_linked_sign_ins.test.tsx | 40 ++++++++++++++ .../views/test_users_views_linked_sign_ins.py | 52 ++++++++++++++++++ modules/users/users/admin/linked_sign_ins.py | 39 +++++++++++++ modules/users/users/admin/views.py | 2 + modules/users/users/locales/en.json | 6 ++ modules/users/users/pages/Users/Edit.tsx | 6 ++ .../Users/components/LinkedSignInsCard.tsx | 55 +++++++++++++++++++ packages/i18n/src/generated-resources.ts | 4 ++ packages/i18n/src/keys.generated.ts | 6 ++ 9 files changed, 210 insertions(+) create mode 100644 modules/users/tests-js/users_linked_sign_ins.test.tsx create mode 100644 modules/users/tests/admin/views/test_users_views_linked_sign_ins.py create mode 100644 modules/users/users/admin/linked_sign_ins.py create mode 100644 modules/users/users/pages/Users/components/LinkedSignInsCard.tsx diff --git a/modules/users/tests-js/users_linked_sign_ins.test.tsx b/modules/users/tests-js/users_linked_sign_ins.test.tsx new file mode 100644 index 00000000..b6e97c71 --- /dev/null +++ b/modules/users/tests-js/users_linked_sign_ins.test.tsx @@ -0,0 +1,40 @@ +import '@testing-library/jest-dom/vitest'; +import { configureI18n } from '@simple-module-py/i18n'; +import { render, screen } from '@testing-library/react'; +import { describe, expect, test } from 'vitest'; + +configureI18n({ + locale: 'en', + messages: { + 'users.linked_sign_ins.title': 'Linked sign-ins', + 'users.linked_sign_ins.subject': 'Subject', + 'users.linked_sign_ins.last_sign_in': 'Last signed in {when}', + 'users.linked_sign_ins.never': 'Not signed in through it yet', + }, +}); + +import { LinkedSignInsCard } from '../users/pages/Users/components/LinkedSignInsCard'; + +describe('LinkedSignInsCard', () => { + test('lists each provider with its username, subject and last sign-in', () => { + render( + , + ); + expect(screen.getByText('Linked sign-ins')).toBeInTheDocument(); + expect(screen.getByText('Microsoft')).toBeInTheDocument(); + expect(screen.getByText(/jane@corp\.com/)).toBeInTheDocument(); + expect(screen.getByText('pairwise-sub')).toBeInTheDocument(); + expect(screen.getByText(/^Last signed in/)).toBeInTheDocument(); + expect(screen.getByText('Not signed in through it yet')).toBeInTheDocument(); + }); +}); diff --git a/modules/users/tests/admin/views/test_users_views_linked_sign_ins.py b/modules/users/tests/admin/views/test_users_views_linked_sign_ins.py new file mode 100644 index 00000000..648bae99 --- /dev/null +++ b/modules/users/tests/admin/views/test_users_views_linked_sign_ins.py @@ -0,0 +1,52 @@ +"""The admin Edit page lists an account's linked sign-ins (#877).""" + +from __future__ import annotations + +from datetime import UTC, datetime + +import pytest +from users.models import OAuthAccount + +_INERTIA = {"X-Inertia": "true", "X-Inertia-Version": "1.0"} + + +@pytest.mark.anyio +async def test_edit_page_lists_linked_sign_ins(admin_client, users_db): + from _users_admin_support import _make_user + + user = await _make_user(users_db, email="linked@example.com") + signed_in = datetime(2026, 11, 1, 9, 30, tzinfo=UTC) + users_db.add( + OAuthAccount( + user_id=user.id, + oauth_name="microsoft", + access_token="at", + account_id="oid-1", + account_email="linked@example.com", + subject="pairwise-sub", + username="linked@example.com", + last_sign_in_at=signed_in, + ) + ) + await users_db.commit() + + resp = await admin_client.get(f"/admin/users/{user.id}", headers=_INERTIA) + + assert resp.status_code == 200 + assert resp.json()["props"]["linked_sign_ins"] == [ + { + "provider": "microsoft", + "username": "linked@example.com", + "subject": "pairwise-sub", + "last_sign_in_at": signed_in.isoformat(), + } + ] + + +@pytest.mark.anyio +async def test_a_local_account_has_none(admin_client, users_db): + from _users_admin_support import _make_user + + user = await _make_user(users_db, email="local@example.com") + resp = await admin_client.get(f"/admin/users/{user.id}", headers=_INERTIA) + assert resp.json()["props"]["linked_sign_ins"] == [] diff --git a/modules/users/users/admin/linked_sign_ins.py b/modules/users/users/admin/linked_sign_ins.py new file mode 100644 index 00000000..5234fe3c --- /dev/null +++ b/modules/users/users/admin/linked_sign_ins.py @@ -0,0 +1,39 @@ +"""The external sign-ins linked to an account, for the admin Edit page (#877).""" + +from __future__ import annotations + +import uuid +from typing import Any + +from fastapi import Request +from sqlalchemy import select +from sqlalchemy.ext.asyncio import AsyncSession +from sqlmodel import col + +from users.models import OAuthAccount + + +async def linked_sign_ins_for( + request: Request, user_id: uuid.UUID, db: AsyncSession +) -> list[dict[str, Any]]: + """Provider, IdP username, subject and last sign-in per link, read-only.""" + stmt = ( + select( + OAuthAccount.oauth_name, + OAuthAccount.username, + OAuthAccount.subject, + OAuthAccount.last_sign_in_at, + ) + .where(col(OAuthAccount.user_id) == user_id) + .order_by(col(OAuthAccount.oauth_name)) + ) + clients = request.app.state.users.oauth_clients + return [ + { + "provider": clients[name].display_name if name in clients else name, + "username": username, + "subject": subject, + "last_sign_in_at": last.isoformat() if last else None, + } + for name, username, subject, last in (await db.execute(stmt)).all() + ] diff --git a/modules/users/users/admin/views.py b/modules/users/users/admin/views.py index 688144f1..75334d31 100644 --- a/modules/users/users/admin/views.py +++ b/modules/users/users/admin/views.py @@ -15,6 +15,7 @@ from sqlalchemy.ext.asyncio import AsyncSession from starlette.responses import RedirectResponse +from users.admin.linked_sign_ins import linked_sign_ins_for from users.admin.recent_activity import recent_activity_for from users.admin.service import UserService from users.core.constants import PERM_USERS_MANAGE, sanitize_list_filters @@ -194,5 +195,6 @@ async def admin_edit_page( # is then absent rather than empty, which is the honest rendering # of "this deployment does not record activity". "recent_activity": await recent_activity_for(request, uid, db, t), + "linked_sign_ins": await linked_sign_ins_for(request, uid, db), }, ) diff --git a/modules/users/users/locales/en.json b/modules/users/users/locales/en.json index 99d199e0..c270c041 100644 --- a/modules/users/users/locales/en.json +++ b/modules/users/users/locales/en.json @@ -428,5 +428,11 @@ "email_exists": "A user with this email already exists.", "not_found": "User not found", "external_password": "External (SSO) users have no password to reset" + }, + "linked_sign_ins": { + "title": "Linked sign-ins", + "last_sign_in": "Last signed in {when}", + "never": "Not signed in through it yet", + "subject": "Subject" } } diff --git a/modules/users/users/pages/Users/Edit.tsx b/modules/users/users/pages/Users/Edit.tsx index 68e08d3d..4983fd20 100644 --- a/modules/users/users/pages/Users/Edit.tsx +++ b/modules/users/users/pages/Users/Edit.tsx @@ -10,6 +10,7 @@ import { AccountCard } from './components/AccountCard'; import { DangerZone } from './components/DangerZone'; import { DetailsCard } from './components/DetailsCard'; import { EditHeaderActions } from './components/EditHeaderActions'; +import { type LinkedSignIn, LinkedSignInsCard } from './components/LinkedSignInsCard'; import { type ActivityEntry, RecentActivityCard } from './components/RecentActivityCard'; import type { Role } from './components/RolePicker'; import { useEditUserForm } from './components/useEditUserForm'; @@ -21,6 +22,7 @@ interface Props { has_permissions_module: boolean; /** `null` when the audit_log module is not installed. */ recent_activity: ActivityEntry[] | null; + linked_sign_ins: LinkedSignIn[]; auth?: { user?: { id?: string } }; } @@ -45,6 +47,7 @@ function Edit({ roles, has_permissions_module, recent_activity: recentActivity, + linked_sign_ins: linkedSignIns, auth, }: Props) { const { t } = useT(); @@ -123,6 +126,9 @@ function Edit({ )} + {/* Only accounts that sign in through an identity provider have any. */} + {linkedSignIns.length > 0 && } + diff --git a/modules/users/users/pages/Users/components/LinkedSignInsCard.tsx b/modules/users/users/pages/Users/components/LinkedSignInsCard.tsx new file mode 100644 index 00000000..7315adc6 --- /dev/null +++ b/modules/users/users/pages/Users/components/LinkedSignInsCard.tsx @@ -0,0 +1,55 @@ +import { keys, useT } from '@simple-module-py/i18n'; +import { SectionTitle } from '@simple-module-py/ui/components/SectionTitle'; +import { Card, CardContent } from '@simple-module-py/ui/components/ui/card'; +import { useRelativeTime } from '@simple-module-py/ui/hooks/use-relative-time'; + +export interface LinkedSignIn { + provider: string; + username: string | null; + subject: string | null; + last_sign_in_at: string | null; +} + +interface Props { + links: LinkedSignIn[]; +} + +/** + * Which identity provider accounts sign in as this person (#877). + * + * Read-only: the provider's username and subject say which IdP identity an + * account belongs to, which an administrator otherwise cannot tell. + */ +export function LinkedSignInsCard({ links }: Props) { + const { t } = useT(); + const { ago } = useRelativeTime(); + return ( + + + {t(keys.users.linked_sign_ins.title)} +
    + {links.map((link) => ( +
  • +

    + {link.provider} + {link.username && ( + · {link.username} + )} +

    + {link.subject && ( +

    + {t(keys.users.linked_sign_ins.subject)} {link.subject} +

    + )} +

    + {link.last_sign_in_at + ? t(keys.users.linked_sign_ins.last_sign_in, { when: ago(link.last_sign_in_at) }) + : t(keys.users.linked_sign_ins.never)} +

    +
  • + ))} +
+
+
+ ); +} diff --git a/packages/i18n/src/generated-resources.ts b/packages/i18n/src/generated-resources.ts index bc2a6ef2..aacb8348 100644 --- a/packages/i18n/src/generated-resources.ts +++ b/packages/i18n/src/generated-resources.ts @@ -1300,6 +1300,10 @@ export default { 'users.invite_results.retrying': '', 'users.invite_results.title': '', 'users.invite_results.toast_copied': '', + 'users.linked_sign_ins.last_sign_in': '', + 'users.linked_sign_ins.never': '', + 'users.linked_sign_ins.subject': '', + 'users.linked_sign_ins.title': '', 'users.login.aside_body': '', 'users.login.aside_check_sessions': '', 'users.login.aside_check_sso': '', diff --git a/packages/i18n/src/keys.generated.ts b/packages/i18n/src/keys.generated.ts index e2713d1a..e5bb3c5a 100644 --- a/packages/i18n/src/keys.generated.ts +++ b/packages/i18n/src/keys.generated.ts @@ -1648,6 +1648,12 @@ export const keys = { title: 'users.invite_results.title', toast_copied: 'users.invite_results.toast_copied', }, + linked_sign_ins: { + last_sign_in: 'users.linked_sign_ins.last_sign_in', + never: 'users.linked_sign_ins.never', + subject: 'users.linked_sign_ins.subject', + title: 'users.linked_sign_ins.title', + }, login: { aside_body: 'users.login.aside_body', aside_check_sessions: 'users.login.aside_check_sessions', From af6015b848ee6f824f1dfba0552e6a0c972472dc Mon Sep 17 00:00:00 2001 From: Anto Subash Date: Wed, 11 Nov 2026 20:59:11 +0100 Subject: [PATCH 07/12] docs(users): linked identities and trusted email domains (#877 #878) Claude-Session: https://claude.ai/code/session_01M9neheZZEe3sVpDi2S3zT4 --- CHANGELOG.md | 3 +++ docs/modules/users.md | 14 ++++++++++++++ modules/users/README.md | 7 +++++++ 3 files changed, 24 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7def699b..f80dd7e3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,9 @@ All notable changes to this project are documented in this file. The format is b ### Added +- `users`: OAuth sign-ins store the IdP profile on the link: `users_oauth_account` gains `subject`, `username`, `display_name`, `extra` (Microsoft `oid`/`tid`) and `last_sign_in_at` (migration `e480d7dd348f`, users trunk), refreshed on every sign-in and listed under "Linked sign-ins" on the admin Edit user page. A new account takes `full_name` from the IdP's display name; `oauth_sync_profile` (off by default) updates it on later sign-ins. `OAuthProvider.get_identity` returns an `OAuthIdentity` instead of a tuple (#877). +- `users`: `oauth_trusted_email_domains` (e.g. `{"microsoft": ["iiasa.ac.at"]}`) makes addresses on listed domains count as verified for that provider, exact domain only. Allowed for `microsoft` (a member of a pinned tenant GUID; `upn`/`preferred_username`, or the `email` claim only with `xms_edov`) and `oidc` (never over an explicit `email_verified: false`); Google and GitHub are refused because anyone can add an unverified address on any domain there (#878). + - `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). diff --git a/docs/modules/users.md b/docs/modules/users.md index a087761e..40903841 100644 --- a/docs/modules/users.md +++ b/docs/modules/users.md @@ -226,6 +226,8 @@ Everything else is DB-backed (initial values are pydantic defaults; edit under U | `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 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_trusted_email_domains` | `{}` — per provider, domains whose addresses count as verified; `microsoft` and `oidc` only (see [Trusted email domains](#trusted-email-domains)) | +| `oauth_sync_profile` | `False` — update `full_name` from the IdP's display name on every sign-in, not only when the account is created | | `oauth_oidc_client_id` / `oauth_oidc_client_secret` / `oauth_oidc_discovery_url` / `oauth_oidc_display_name` | `""` / `""` / `""` / `"OIDC"` — generic OIDC | ## Permissions @@ -560,6 +562,18 @@ With `allow_signup` off, an OAuth sign-in for an identity nobody holds is refuse - `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. +### Trusted email domains + +`oauth_trusted_email_domains` lets an operator vouch for addresses on domains their organisation owns, per provider, for example `{"microsoft": ["iiasa.ac.at"]}`. An address on a listed domain then counts as verified for that provider only, so it links to an invited or verified local account and can provision one (see above). Domains match exactly and case-insensitively after IDNA normalisation; subdomains are never implied. + +- Only `microsoft` and `oidc` can be listed. Anyone can add an unverified address on any domain to a Google or GitHub account, so a domain cannot vouch for it there; those keys are refused. +- `microsoft` needs `oauth_microsoft_tenant` set to the tenant GUID (otherwise the domains are ignored and the settings load logs `users.oauth.trusted_domains_ignored`), and a member of that tenant: matching `tid` and no `idp` naming another issuer. The address is the `upn` claim or `preferred_username` on a listed domain; the user-editable `email` claim counts only when Entra marks its domain verified (the `xms_edov` optional claim). +- `oidc` trusts the address your IdP returns on a listed domain unless the IdP itself says `email_verified: false`. List a domain only if your IdP does not let users set their own email. + +### Linked identities + +Each sign-in refreshes the IdP profile on the account's `users_oauth_account` link: `subject` (`sub`), `username`, `display_name`, `extra` (Microsoft's `oid` and `tid`) and `last_sign_in_at`. The admin **Edit user** page lists them under "Linked sign-ins". A new account takes `full_name` from the IdP's display name; later sign-ins update it only with `oauth_sync_profile` on, and never clear it. The account's email never changes on sign-in. + ## Importing users from another system `users` stores passwords through fastapi-users' default `PasswordHelper`, so you can import `hashed_password` values from another system and users keep their existing passwords (no reset needed). Accepted formats: diff --git a/modules/users/README.md b/modules/users/README.md index f9431aa0..567d76c7 100644 --- a/modules/users/README.md +++ b/modules/users/README.md @@ -110,6 +110,13 @@ when they proved the email, while local registration keeps following with signup open too (never the self-signup `user` role); blank (the default) means none until an admin grants one, and `admin` is refused. +**Trusted email domains.** `oauth_trusted_email_domains` (e.g. +`{"microsoft": ["iiasa.ac.at"]}`) makes addresses on the listed domains count +as verified for that provider: `microsoft` (a member of a pinned tenant GUID) +and `oidc` only. `oauth_sync_profile` updates `full_name` from the IdP on every +sign-in; each link stores the IdP's subject, username and last sign-in, shown +on the admin Edit user page. + Each provider's callback URL is `/api/users/auth//callback` (`google`, `github`, `microsoft`, `oidc`). From 70ec04f5df459aac0e26cda874af565ffa7cef69 Mon Sep 17 00:00:00 2001 From: Anto Subash Date: Wed, 11 Nov 2026 21:00:59 +0100 Subject: [PATCH 08/12] i18n(users): German strings for linked sign-ins (#877) Claude-Session: https://claude.ai/code/session_01M9neheZZEe3sVpDi2S3zT4 --- modules/users/users/locales/de.json | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/modules/users/users/locales/de.json b/modules/users/users/locales/de.json index 717d2ab8..06be6015 100644 --- a/modules/users/users/locales/de.json +++ b/modules/users/users/locales/de.json @@ -428,5 +428,11 @@ "email_exists": "Ein Benutzer mit dieser E-Mail-Adresse existiert bereits.", "not_found": "Benutzer nicht gefunden", "external_password": "Externe Benutzer (SSO) haben kein Passwort zum Zurücksetzen." + }, + "linked_sign_ins": { + "title": "Verknüpfte Anmeldungen", + "last_sign_in": "Zuletzt angemeldet {when}", + "never": "Noch nicht darüber angemeldet", + "subject": "Subjekt" } } From 53da4ab35e383016fed7f86f03b636e954568c00 Mon Sep 17 00:00:00 2001 From: Anto Subash Date: Wed, 11 Nov 2026 21:05:33 +0100 Subject: [PATCH 09/12] fix: address code review findings (round 1, pass 1) Shared text_or_none helper; a validated ID token without sub no longer 500s; OAuthAccount column docs. Claude-Session: https://claude.ai/code/session_01M9neheZZEe3sVpDi2S3zT4 --- docs/modules/users.md | 2 +- modules/users/users/oauth/identity.py | 5 +++++ modules/users/users/oauth/microsoft.py | 15 +++++++-------- modules/users/users/oauth/providers.py | 16 ++++++---------- 4 files changed, 19 insertions(+), 19 deletions(-) diff --git a/docs/modules/users.md b/docs/modules/users.md index 40903841..83618a1a 100644 --- a/docs/modules/users.md +++ b/docs/modules/users.md @@ -169,7 +169,7 @@ permissions role pages. The edit page's *Recent activity* card reads the core `UserAccessToken` (table `users_access_token`) — bearer API tokens, stored as SHA-256 digests (the secret is shown once at login); resolved by `UsersAuthProvider` on `Authorization: Bearer` requests (sessions remain the primary browser auth). -`OAuthAccount` (table `users_oauth_account`) — linked OAuth/OIDC accounts: `oauth_name`, `account_id`, `account_email`, `access_token`, `refresh_token`, `expires_at`. +`OAuthAccount` (table `users_oauth_account`) — linked OAuth/OIDC accounts: `oauth_name`, `account_id`, `account_email`, `access_token`, `refresh_token`, `expires_at`, plus the IdP profile refreshed on each sign-in (#877): `subject`, `username`, `display_name`, `extra`, `last_sign_in_at`. `RefreshToken` (table `users_refresh_token`) — opaque refresh tokens for the bearer flow: `token` (PK, SHA-256 digest of the secret), `family_id` (rotation lineage; presenting an already-revoked token revokes the whole family), `user_id`, `created_at`, `expires_at`, `revoked_at`. diff --git a/modules/users/users/oauth/identity.py b/modules/users/users/oauth/identity.py index 2041aeb6..bff246ca 100644 --- a/modules/users/users/oauth/identity.py +++ b/modules/users/users/oauth/identity.py @@ -48,3 +48,8 @@ def email_on_domains(email: str | None, domains: Collection[str]) -> bool: return normalize_domain(email.rsplit("@", 1)[1]) in domains except ValueError: return False + + +def text_or_none(value: object) -> str | None: + """``value`` when it is a non-blank string, else ``None`` (claims are untyped).""" + return value if isinstance(value, str) and value.strip() else None diff --git a/modules/users/users/oauth/microsoft.py b/modules/users/users/oauth/microsoft.py index 4343e6ce..cafdd787 100644 --- a/modules/users/users/oauth/microsoft.py +++ b/modules/users/users/oauth/microsoft.py @@ -20,7 +20,7 @@ from httpx_oauth.exceptions import HTTPXOAuthError from users.core.oauth_settings import MICROSOFT_CONSUMERS_TENANT, is_tenant_guid -from users.oauth.identity import OAuthIdentity, email_on_domains +from users.oauth.identity import OAuthIdentity, email_on_domains, text_or_none _LOGIN_HOST = "https://login.microsoftonline.com" _SCOPES = ["openid", "profile", "email"] @@ -63,6 +63,9 @@ async def identity( oid = claims.get("oid") if not isinstance(oid, str) or not _GUID_RE.fullmatch(oid): raise IdTokenError("ID token has no object id") + subject = claims.get("sub") + if not isinstance(subject, str) or not subject: + raise IdTokenError("ID token has no subject") 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). @@ -81,9 +84,9 @@ async def identity( account_id=graph_account_id(oid), email=email, email_verified=bool(trusted), - subject=claims["sub"], - username=email or _text(claims.get("preferred_username")), - display_name=_text(claims.get("name")), + subject=text_or_none(claims.get("sub")), + username=email or text_or_none(claims.get("preferred_username")), + display_name=text_or_none(claims.get("name")), extra={"oid": oid, "tid": tid}, ) @@ -175,10 +178,6 @@ def _domain_email(claims: dict[str, Any], domains: Collection[str]) -> str | Non return None -def _text(value: object) -> str | None: - return value if isinstance(value, str) and value.strip() else 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}/"} diff --git a/modules/users/users/oauth/providers.py b/modules/users/users/oauth/providers.py index 460ad335..3a6c6397 100644 --- a/modules/users/users/oauth/providers.py +++ b/modules/users/users/oauth/providers.py @@ -17,7 +17,7 @@ from auth.oidc_common.session import pkce_challenge from users.core.oauth_settings import is_tenant_guid -from users.oauth.identity import OAuthIdentity +from users.oauth.identity import OAuthIdentity, text_or_none if TYPE_CHECKING: from httpx_oauth.oauth2 import BaseOAuth2 @@ -99,8 +99,8 @@ async def _profile_identity(self, access_token: str) -> OAuthIdentity: profile.get("email"), profile.get("email_verified") is True, subject=str(profile["sub"]), - username=_text(profile.get("preferred_username")), - display_name=_text(profile.get("name")), + username=text_or_none(profile.get("preferred_username")), + display_name=text_or_none(profile.get("name")), domain_trust_allowed=profile.get("email_verified") is not False, ) if self.name == "google": @@ -115,20 +115,16 @@ async def _profile_identity(self, access_token: str) -> OAuthIdentity: email, verified, subject=account_id, - username=_text(profile.get("login")), - display_name=_text(profile.get("name")), + username=text_or_none(profile.get("login")), + display_name=text_or_none(profile.get("name")), ) -def _text(value: object) -> str | None: - return value if isinstance(value, str) and value.strip() else None - - def _google_identity(profile: dict[str, Any]) -> OAuthIdentity: """People API profile → resourceName, primary email and its ``metadata.verified``.""" subject = str(profile["resourceName"]) names = profile.get("names") or [{}] - display_name = _text(names[0].get("displayName")) if isinstance(names[0], dict) else None + display_name = text_or_none(names[0].get("displayName")) if isinstance(names[0], dict) else None primary = next( (e for e in profile.get("emailAddresses", []) if e.get("metadata", {}).get("primary")), None, From eae27c9322fde55dedaf273c5f63fcb899cc5e05 Mon Sep 17 00:00:00 2001 From: Anto Subash Date: Wed, 11 Nov 2026 21:09:36 +0100 Subject: [PATCH 10/12] fix: Codex review: a guest UPN is never a member; Google reads names (#877 #878) Claude-Session: https://claude.ai/code/session_01M9neheZZEe3sVpDi2S3zT4 --- .../test_users_oauth_google_names.py | 24 ++++++++++++++++ .../test_users_oauth_microsoft_id_token.py | 20 ++++++++++++- modules/users/users/oauth/google.py | 28 +++++++++++++++++++ modules/users/users/oauth/microsoft.py | 9 ++++++ modules/users/users/oauth/providers.py | 4 +-- 5 files changed, 82 insertions(+), 3 deletions(-) create mode 100644 modules/users/tests/oauth/providers/test_users_oauth_google_names.py create mode 100644 modules/users/users/oauth/google.py diff --git a/modules/users/tests/oauth/providers/test_users_oauth_google_names.py b/modules/users/tests/oauth/providers/test_users_oauth_google_names.py new file mode 100644 index 00000000..2fccdeaa --- /dev/null +++ b/modules/users/tests/oauth/providers/test_users_oauth_google_names.py @@ -0,0 +1,24 @@ +"""Google sign-in asks the People API for the name too (#877).""" + +from users.oauth.google import GoogleWithNames +from users.oauth.providers import OAuthProvider + + +async def test_google_profile_requests_names_and_fills_display_name(httpx_mock): + httpx_mock.add_response( + json={ + "resourceName": "people/1", + "names": [{"displayName": "Jane Doe"}], + "emailAddresses": [ + {"value": "jane@example.com", "metadata": {"primary": True, "verified": True}} + ], + } + ) + provider = OAuthProvider("google", "Google", GoogleWithNames("id", "secret")) + + identity = await provider.get_identity({"access_token": "t"}) + + assert identity.display_name == "Jane Doe" + assert identity.email_verified is True + request = httpx_mock.get_request() + assert request.url.params["personFields"] == "emailAddresses,names" 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 index 28ae93e1..caa7907f 100644 --- 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 @@ -168,8 +168,26 @@ async def test_the_upn_claim_wins_over_an_alternate_login_alias(): (TENANT, {"preferred_username": "jane@mail.corp.com"}, "jane@mail.corp.com", False), (TENANT, {"idp": "https://sts.windows.net/other/"}, "jane@corp.com", False), ("common", {}, "jane@corp.com", False), + # A guest UPN must not be rescued by an alternate username on a listed domain. + ( + TENANT, + { + "upn": "jane_corp.com#EXT#@tenant.onmicrosoft.com", + "preferred_username": "jane@corp.com", + }, + "jane_corp.com#EXT#@tenant.onmicrosoft.com", + False, + ), + ], + ids=[ + "upn-on-domain", + "email-unverified", + "email-xms-edov", + "subdomain", + "guest", + "common", + "guest-upn-alias", ], - ids=["upn-on-domain", "email-unverified", "email-xms-edov", "subdomain", "guest", "common"], ) async def test_trusted_domains_need_a_member(tenant, claims, email, verified): token = sign(id_claims(nonce=_NONCE, **claims)) diff --git a/modules/users/users/oauth/google.py b/modules/users/users/oauth/google.py new file mode 100644 index 00000000..a251e381 --- /dev/null +++ b/modules/users/users/oauth/google.py @@ -0,0 +1,28 @@ +"""Google client that also reads the person's name (#877). + +``httpx_oauth``'s ``GoogleOAuth2.get_profile`` asks the People API for +``emailAddresses`` only, so the IdP display name never arrives. The ``profile`` +scope it already requests covers ``names``. +""" + +from __future__ import annotations + +from typing import Any, cast + +from httpx_oauth.clients.google import PROFILE_ENDPOINT, GoogleOAuth2 +from httpx_oauth.exceptions import GetProfileError + +PERSON_FIELDS = "emailAddresses,names" + + +class GoogleWithNames(GoogleOAuth2): + async def get_profile(self, token: str) -> dict[str, Any]: + async with self.get_httpx_client() as client: + response = await client.get( + PROFILE_ENDPOINT, + params={"personFields": PERSON_FIELDS}, + headers={**self.request_headers, "Authorization": f"Bearer {token}"}, + ) + if response.status_code >= 400: + raise GetProfileError(response=response) + return cast(dict[str, Any], response.json()) diff --git a/modules/users/users/oauth/microsoft.py b/modules/users/users/oauth/microsoft.py index cafdd787..7fd8c456 100644 --- a/modules/users/users/oauth/microsoft.py +++ b/modules/users/users/oauth/microsoft.py @@ -74,6 +74,7 @@ async def identity( is_tenant_guid(self.tenant) and tid == self.tenant and (idp is None or (isinstance(idp, str) and idp in _home_issuers(tid))) + and not _guest_name(claims) ) trusted = trust_email and member and email is not None and "#EXT#" not in email.upper() # A member's address on a domain the operator owns is proof too (#878). @@ -158,6 +159,14 @@ def _account_email(claims: dict[str, Any]) -> str | None: return None +def _guest_name(claims: dict[str, Any]) -> bool: + """A guest's UPN (``#EXT#``) in any name claim: never a member, whatever else it says.""" + return any( + isinstance(claims.get(name), str) and "#EXT#" in claims[name].upper() + for name in ("upn", "preferred_username") + ) + + def _domain_email(claims: dict[str, Any], domains: Collection[str]) -> str | None: """The UPN or username on a trusted domain, else a domain-verified ``email``. diff --git a/modules/users/users/oauth/providers.py b/modules/users/users/oauth/providers.py index 3a6c6397..7ab55abf 100644 --- a/modules/users/users/oauth/providers.py +++ b/modules/users/users/oauth/providers.py @@ -159,13 +159,13 @@ def build_clients(settings: UsersSettings) -> list[OAuthProvider]: out: list[OAuthProvider] = [] if settings.oauth_google_client_id and settings.oauth_google_client_secret: - from httpx_oauth.clients.google import GoogleOAuth2 + from users.oauth.google import GoogleWithNames out.append( OAuthProvider( "google", "Google", - GoogleOAuth2( + GoogleWithNames( settings.oauth_google_client_id, settings.oauth_google_client_secret, ), From 4df9e6cae26cedaa58d5b9487594a826ee7811c6 Mon Sep 17 00:00:00 2001 From: Anto Subash Date: Wed, 11 Nov 2026 21:12:36 +0100 Subject: [PATCH 11/12] fix: address code review findings (round 1, pass 2) Google display name from the primary name, junk-safe; Google's explicit unverified blocks domain trust; docs on Google names and guest UPNs. Claude-Session: https://claude.ai/code/session_01M9neheZZEe3sVpDi2S3zT4 --- CHANGELOG.md | 4 ++-- docs/modules/users.md | 4 ++-- .../test_users_oauth_provider_identity.py | 20 +++++++++++++++++++ modules/users/users/oauth/providers.py | 6 ++++-- 4 files changed, 28 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f80dd7e3..1b362fac 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,8 +16,8 @@ All notable changes to this project are documented in this file. The format is b ### Added -- `users`: OAuth sign-ins store the IdP profile on the link: `users_oauth_account` gains `subject`, `username`, `display_name`, `extra` (Microsoft `oid`/`tid`) and `last_sign_in_at` (migration `e480d7dd348f`, users trunk), refreshed on every sign-in and listed under "Linked sign-ins" on the admin Edit user page. A new account takes `full_name` from the IdP's display name; `oauth_sync_profile` (off by default) updates it on later sign-ins. `OAuthProvider.get_identity` returns an `OAuthIdentity` instead of a tuple (#877). -- `users`: `oauth_trusted_email_domains` (e.g. `{"microsoft": ["iiasa.ac.at"]}`) makes addresses on listed domains count as verified for that provider, exact domain only. Allowed for `microsoft` (a member of a pinned tenant GUID; `upn`/`preferred_username`, or the `email` claim only with `xms_edov`) and `oidc` (never over an explicit `email_verified: false`); Google and GitHub are refused because anyone can add an unverified address on any domain there (#878). +- `users`: OAuth sign-ins store the IdP profile on the link: `users_oauth_account` gains `subject`, `username`, `display_name`, `extra` (Microsoft `oid`/`tid`) and `last_sign_in_at` (migration `e480d7dd348f`, users trunk), refreshed on every sign-in and listed under "Linked sign-ins" on the admin Edit user page. A new account takes `full_name` from the IdP's display name; `oauth_sync_profile` (off by default) updates it on later sign-ins. Google sign-in now also requests the People API `names` field for the display name. `OAuthProvider.get_identity` returns an `OAuthIdentity` instead of a tuple (#877). +- `users`: `oauth_trusted_email_domains` (e.g. `{"microsoft": ["iiasa.ac.at"]}`) makes addresses on listed domains count as verified for that provider, exact domain only. Allowed for `microsoft` (a member of a pinned tenant GUID; `upn`/`preferred_username`, or the `email` claim only with `xms_edov`; a token whose `upn` or `preferred_username` carries `#EXT#` is a guest and never trusted) and `oidc` (never over an explicit `email_verified: false`); Google and GitHub are refused because anyone can add an unverified address on any domain there (#878). - `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). diff --git a/docs/modules/users.md b/docs/modules/users.md index 83618a1a..a4e8c0a9 100644 --- a/docs/modules/users.md +++ b/docs/modules/users.md @@ -548,7 +548,7 @@ Microsoft email claims are tenant-controlled, so by default a Microsoft sign-in 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 and other external accounts (an `idp` claim naming another issuer, or a UPN containing `#EXT#`) and an empty username stay unverified. +- Guest and other external accounts (an `idp` claim naming another issuer, or a UPN containing `#EXT#`, even when another name claim such as `preferred_username` shows a listed-domain address) 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. @@ -572,7 +572,7 @@ With `allow_signup` off, an OAuth sign-in for an identity nobody holds is refuse ### Linked identities -Each sign-in refreshes the IdP profile on the account's `users_oauth_account` link: `subject` (`sub`), `username`, `display_name`, `extra` (Microsoft's `oid` and `tid`) and `last_sign_in_at`. The admin **Edit user** page lists them under "Linked sign-ins". A new account takes `full_name` from the IdP's display name; later sign-ins update it only with `oauth_sync_profile` on, and never clear it. The account's email never changes on sign-in. +Each sign-in refreshes the IdP profile on the account's `users_oauth_account` link: `subject` (`sub`), `username`, `display_name`, `extra` (Microsoft's `oid` and `tid`) and `last_sign_in_at`. The admin **Edit user** page lists them under "Linked sign-ins". A new account takes `full_name` from the IdP's display name; later sign-ins update it only with `oauth_sync_profile` on, and never clear it. Google's display name comes from the People API `names` field (the `profile` scope already requested). The account's email never changes on sign-in. ## Importing users from another system 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 c39fc57c..6d5ec38f 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 @@ -67,3 +67,23 @@ async def test_github_requires_the_chosen_email_to_be_verified(emails, expected) async def test_github_unreadable_emails_is_not_proof(): provider = OAuthProvider("github", "GitHub", _GitHub([], fail=True)) assert (await provider.get_identity(_TOKEN)).email_verified is False + + +@pytest.mark.parametrize( + "names, expected", + [ + ( + [{"displayName": "Other"}, {"displayName": "Jane", "metadata": {"primary": True}}], + "Jane", + ), + ([{"displayName": "First"}], "First"), + (["not-a-dict", {"displayName": "Jane"}], "Jane"), + (None, None), + ], + ids=["primary-wins", "first-otherwise", "skips-junk", "none"], +) +async def test_google_display_name_prefers_the_primary_name(names, expected): + google = _Google(True) + google.profile = {**google.profile, "names": names} + provider = OAuthProvider("google", "Google", google) + assert (await provider.get_identity(_TOKEN)).display_name == expected diff --git a/modules/users/users/oauth/providers.py b/modules/users/users/oauth/providers.py index 7ab55abf..e951d7c2 100644 --- a/modules/users/users/oauth/providers.py +++ b/modules/users/users/oauth/providers.py @@ -123,8 +123,9 @@ async def _profile_identity(self, access_token: str) -> OAuthIdentity: def _google_identity(profile: dict[str, Any]) -> OAuthIdentity: """People API profile → resourceName, primary email and its ``metadata.verified``.""" subject = str(profile["resourceName"]) - names = profile.get("names") or [{}] - display_name = text_or_none(names[0].get("displayName")) if isinstance(names[0], dict) else None + names = [n for n in profile.get("names") or [] if isinstance(n, dict)] + name = next((n for n in names if n.get("metadata", {}).get("primary")), None) + display_name = text_or_none((name or (names[0] if names else {})).get("displayName")) primary = next( (e for e in profile.get("emailAddresses", []) if e.get("metadata", {}).get("primary")), None, @@ -138,6 +139,7 @@ def _google_identity(profile: dict[str, Any]) -> OAuthIdentity: subject=subject, username=primary.get("value"), display_name=display_name, + domain_trust_allowed=primary.get("metadata", {}).get("verified") is not False, ) From df9351522a7fe28d1dc62b51775a47607e5460cd Mon Sep 17 00:00:00 2001 From: Anto Subash Date: Wed, 11 Nov 2026 21:19:38 +0100 Subject: [PATCH 12/12] fix: Codex review: Microsoft username stays the sign-in name; one GitHub profile request (#877) Claude-Session: https://claude.ai/code/session_01M9neheZZEe3sVpDi2S3zT4 --- .../oauth/flow/test_users_oauth_email_claim.py | 2 +- .../flow/test_users_oauth_provider_identity.py | 16 ++++++++++++++++ .../test_users_oauth_microsoft_id_token.py | 13 +++++++++++++ modules/users/users/oauth/microsoft.py | 3 ++- modules/users/users/oauth/providers.py | 6 +++++- 5 files changed, 37 insertions(+), 3 deletions(-) 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 a097d513..e3db9d33 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 @@ -20,7 +20,7 @@ def _triple(identity): class _ClaimClient: def __init__(self, claim): - self.profile = {"sub": "idp-attacker", "email": _EMAIL, **claim} + self.profile = {"id": "idp-attacker", "sub": "idp-attacker", "email": _EMAIL, **claim} async def get_authorization_url(self, redirect_uri, state): return f"https://idp.example/authorize?state={state}" 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 6d5ec38f..b7e2cf87 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 @@ -87,3 +87,19 @@ async def test_google_display_name_prefers_the_primary_name(names, expected): google.profile = {**google.profile, "names": names} provider = OAuthProvider("google", "Google", google) assert (await provider.get_identity(_TOKEN)).display_name == expected + + +async def test_github_reads_its_profile_once_when_it_has_a_public_email(): + calls = [] + + class _PublicGitHub(_GitHub): + async def get_profile(self, token): + calls.append("profile") + return {"id": 7, "login": "octo", "name": "Octo Cat", "email": "me@example.com"} + + async def get_id_email(self, token): + raise AssertionError("not needed with a public email") + + github = _PublicGitHub([{"email": "me@example.com", "verified": True}]) + identity = await OAuthProvider("github", "GitHub", github).get_identity(_TOKEN) + assert (identity.account_id, identity.username, calls) == ("7", "octo", ["profile"]) 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 index caa7907f..2f51c317 100644 --- 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 @@ -195,3 +195,16 @@ async def test_trusted_domains_need_a_member(tenant, claims, email, verified): {"id_token": token}, _NONCE, trust_email=False, trusted_domains=_DOMAINS ) assert (identity.email, identity.email_verified) == (email, verified) + + +async def test_the_username_stays_the_sign_in_name_when_a_domain_email_wins(): + claims = id_claims( + nonce=_NONCE, + preferred_username="jane@tenant.onmicrosoft.com", + email="jane@corp.com", + xms_edov=True, + ) + identity = await FakeMicrosoft().identity( + {"id_token": sign(claims)}, _NONCE, trust_email=False, trusted_domains=_DOMAINS + ) + assert (identity.email, identity.username) == ("jane@corp.com", "jane@tenant.onmicrosoft.com") diff --git a/modules/users/users/oauth/microsoft.py b/modules/users/users/oauth/microsoft.py index 7fd8c456..1fdb6848 100644 --- a/modules/users/users/oauth/microsoft.py +++ b/modules/users/users/oauth/microsoft.py @@ -86,7 +86,8 @@ async def identity( email=email, email_verified=bool(trusted), subject=text_or_none(claims.get("sub")), - username=email or text_or_none(claims.get("preferred_username")), + # The IdP's own sign-in name, not the trusted address chosen above. + username=_account_email(claims) or text_or_none(claims.get("preferred_username")), display_name=text_or_none(claims.get("name")), extra={"oid": oid, "tid": tid}, ) diff --git a/modules/users/users/oauth/providers.py b/modules/users/users/oauth/providers.py index e951d7c2..6dbd8d00 100644 --- a/modules/users/users/oauth/providers.py +++ b/modules/users/users/oauth/providers.py @@ -105,10 +105,14 @@ async def _profile_identity(self, access_token: str) -> OAuthIdentity: ) if self.name == "google": return _google_identity(await self.client.get_profile(access_token)) - account_id, email = await self.client.get_id_email(access_token) if self.name != "github": + account_id, email = await self.client.get_id_email(access_token) return OAuthIdentity(account_id, email, False) + # One /user request: ``get_id_email`` would fetch it again internally. profile = await self.client.get_profile(access_token) + account_id, email = str(profile["id"]), profile.get("email") + if email is None: # no public email: get_id_email falls back to /user/emails + account_id, email = await self.client.get_id_email(access_token) verified = email is not None and await _github_verified(self.client, access_token, email) return OAuthIdentity( account_id,