From 9d4bb40a6dcca2c42b7aed92096af970d3a6c032 Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Mon, 28 Sep 2026 14:40:22 -0400 Subject: [PATCH] fix(auth): match OIDC users by their sub claim so an email change still logs in Store the provider's `sub` on a new nullable users.oidc_sub column, look users up by it first and fall back to email, backfilling the sub on the next login. A user matched by sub gets their stored email updated, unless another account already holds it. Fixes #1690 Co-Authored-By: Claude Opus 5.5 (1M context) --- .../alembic/versions/0144_user_oidc_sub.py | 37 ++++++ backend/handler/auth/base_handler.py | 51 ++++++--- backend/handler/database/users_handler.py | 8 ++ backend/models/user.py | 4 + backend/tests/handler/auth/test_oidc.py | 105 +++++++++++++++++- backend/tests/test_migrations.py | 17 +++ docs/BACKEND_ARCHITECTURE.md | 1 + 7 files changed, 208 insertions(+), 15 deletions(-) create mode 100644 backend/alembic/versions/0144_user_oidc_sub.py diff --git a/backend/alembic/versions/0144_user_oidc_sub.py b/backend/alembic/versions/0144_user_oidc_sub.py new file mode 100644 index 000000000..9ce55fe31 --- /dev/null +++ b/backend/alembic/versions/0144_user_oidc_sub.py @@ -0,0 +1,37 @@ +"""add oidc_sub to users + +Revision ID: 0144_user_oidc_sub +Revises: 0143_sibling_platform_names +Create Date: 2026-09-28 00:00:00.000000 + +""" + +import sqlalchemy as sa +from alembic import op + +# revision identifiers, used by Alembic. +revision = "0144_user_oidc_sub" +down_revision = "0143_sibling_platform_names" +branch_labels = None +depends_on = None + + +def upgrade() -> None: + # Existing OIDC users are linked on their next login, matched by email. + with op.batch_alter_table("users", schema=None) as batch_op: + batch_op.add_column( + sa.Column("oidc_sub", sa.String(length=255), nullable=True), + if_not_exists=True, + ) + batch_op.create_index( + batch_op.f("ix_users_oidc_sub"), + ["oidc_sub"], + unique=True, + if_not_exists=True, + ) + + +def downgrade() -> None: + with op.batch_alter_table("users", schema=None) as batch_op: + batch_op.drop_index(batch_op.f("ix_users_oidc_sub"), if_exists=True) + batch_op.drop_column("oidc_sub", if_exists=True) diff --git a/backend/handler/auth/base_handler.py b/backend/handler/auth/base_handler.py index ea2a675d9..5f25d7c8f 100644 --- a/backend/handler/auth/base_handler.py +++ b/backend/handler/auth/base_handler.py @@ -655,7 +655,12 @@ class OpenIDHandler: detail="User has not been granted any roles for this application.", ) - user = db_user_handler.get_user_by_email(email) + sub = userinfo.get("sub") or None + user = db_user_handler.get_user_by_oidc_sub(sub) if sub else None + matched_by_sub = user is not None + if user is None: + user = db_user_handler.get_user_by_email(email) + if user is None: if not OIDC_ALLOW_REGISTRATION: log.error( @@ -675,6 +680,7 @@ class OpenIDHandler: username=username, hashed_password=str(uuid.uuid4()), email=email, + oidc_sub=sub, enabled=True, role=role, ) @@ -685,19 +691,36 @@ class OpenIDHandler: AuditTarget.of_user(user), {"role": user.role, "via": "oidc"}, ) - elif claims_provided and user.role != role: - previous_role = user.role - user = db_user_handler.update_user(user.id, {"role": role}) - record( - AuditAction.USER_EDIT, - SYSTEM_ACTOR, - AuditTarget.of_user(user), - { - "changed": ["role"], - "role": {"from": previous_role, "to": role}, - "via": "oidc", - }, - ) + else: + updates: dict[str, Any] = {} + if sub and user.oidc_sub != sub: + updates["oidc_sub"] = sub + if matched_by_sub and (user.email or "").lower() != email.lower(): + if db_user_handler.get_user_by_email(email) is None: + updates["email"] = email + else: + log.warning( + "Not updating the email of %s: '%s' belongs to another user", + hl(user.username, color=CYAN), + hl(email, color=CYAN), + ) + if claims_provided and user.role != role: + updates["role"] = role + + if updates: + previous_role = user.role + user = db_user_handler.update_user(user.id, updates) + changed = [f for f in ("email", "role") if f in updates] + if changed: + data: dict[str, Any] = {"changed": changed, "via": "oidc"} + if "role" in updates: + data["role"] = {"from": previous_role, "to": role} + record( + AuditAction.USER_EDIT, + SYSTEM_ACTOR, + AuditTarget.of_user(user), + data, + ) if not user.enabled: raise UserDisabledException diff --git a/backend/handler/database/users_handler.py b/backend/handler/database/users_handler.py index b4e017d02..b8c3a3821 100644 --- a/backend/handler/database/users_handler.py +++ b/backend/handler/database/users_handler.py @@ -64,6 +64,14 @@ class DBUsersHandler(DBBaseHandler): query = self.filter(select(User), emails=[email]) return session.scalar(query.limit(1)) + @begin_session + def get_user_by_oidc_sub( + self, + oidc_sub: str, + session: Session = INJECTED_SESSION, + ) -> User | None: + return session.scalar(select(User).filter_by(oidc_sub=oidc_sub).limit(1)) + @begin_session def get_user( self, diff --git a/backend/models/user.py b/backend/models/user.py index 386089499..a7bf645af 100644 --- a/backend/models/user.py +++ b/backend/models/user.py @@ -60,6 +60,10 @@ class User(BaseModel, SimpleUser): email: Mapped[str | None] = mapped_column( String(length=TEXT_FIELD_LENGTH), unique=True, index=True ) + # The identity provider's `sub` claim, which survives an email change. + oidc_sub: Mapped[str | None] = mapped_column( + String(length=TEXT_FIELD_LENGTH), unique=True, index=True + ) enabled: Mapped[bool] = mapped_column(default=True) # VARCHAR-backed (native_enum=False) storing the lowercase value, so the # vocabulary stays portable across SQLite/MariaDB/Postgres. diff --git a/backend/tests/handler/auth/test_oidc.py b/backend/tests/handler/auth/test_oidc.py index 03df3f8f2..da8a65e5a 100644 --- a/backend/tests/handler/auth/test_oidc.py +++ b/backend/tests/handler/auth/test_oidc.py @@ -6,7 +6,8 @@ from fastapi import HTTPException, status from joserfc.jwt import Token from handler.auth.base_handler import OpenIDHandler -from models.user import TEXT_FIELD_LENGTH, Role +from handler.database import db_user_handler +from models.user import TEXT_FIELD_LENGTH, Role, User from utils.validation import validate_username # Mock constants @@ -790,3 +791,105 @@ async def test_oidc_discovery_failure_falls_back_to_id_token( ) assert claims == mock_id_token_only_standard_claims["userinfo"] + + +def _add_user(username: str, email: str, oidc_sub: str | None = None) -> User: + return db_user_handler.add_user( + User( + username=username, + hashed_password="", + email=email, + oidc_sub=oidc_sub, + role=Role.USER, + ) + ) + + +async def test_oidc_login_links_the_sub_to_the_user_matched_by_email( + mocker, mock_oidc_enabled, mock_token, mock_openid_configuration +): + existing = _add_user("testuser", "test@example.com") + mock_token["userinfo"]["sub"] = "sub-1" + mocker.patch.object( + StarletteOAuth2App, + "load_server_metadata", + return_value=mock_openid_configuration, + ) + + user, _ = await OpenIDHandler().get_current_active_user_from_openid_token( + mock_token + ) + + assert user is not None + assert user.id == existing.id + assert user.oidc_sub == "sub-1" + + +async def test_oidc_login_follows_an_email_change_at_the_provider( + mocker, + mock_oidc_enabled, + mock_oidc_allow_registration_disabled, + mock_token, + mock_openid_configuration, +): + existing = _add_user("testuser", "old@example.com", oidc_sub="sub-1") + mock_token["userinfo"]["sub"] = "sub-1" + mock_token["userinfo"]["email"] = "new@example.com" + mocker.patch.object( + StarletteOAuth2App, + "load_server_metadata", + return_value=mock_openid_configuration, + ) + + user, _ = await OpenIDHandler().get_current_active_user_from_openid_token( + mock_token + ) + + assert user is not None + assert user.id == existing.id + assert user.email == "new@example.com" + + +async def test_oidc_login_keeps_the_email_when_another_user_holds_the_new_one( + mocker, mock_oidc_enabled, mock_token, mock_openid_configuration +): + existing = _add_user("testuser", "old@example.com", oidc_sub="sub-1") + _add_user("other", "new@example.com") + mock_token["userinfo"]["sub"] = "sub-1" + mock_token["userinfo"]["email"] = "new@example.com" + mocker.patch.object( + StarletteOAuth2App, + "load_server_metadata", + return_value=mock_openid_configuration, + ) + + user, _ = await OpenIDHandler().get_current_active_user_from_openid_token( + mock_token + ) + + assert user is not None + assert user.id == existing.id + assert user.email == "old@example.com" + + +async def test_oidc_registration_stores_the_sub( + mocker, + mock_oidc_enabled, + mock_oidc_allow_registration_enabled, + mock_token, + mock_openid_configuration, +): + mock_token["userinfo"]["sub"] = "sub-1" + mocker.patch.object( + StarletteOAuth2App, + "load_server_metadata", + return_value=mock_openid_configuration, + ) + + user, _ = await OpenIDHandler().get_current_active_user_from_openid_token( + mock_token + ) + + assert user is not None + assert user.oidc_sub == "sub-1" + assert db_user_handler.get_user_by_oidc_sub("sub-1") is not None diff --git a/backend/tests/test_migrations.py b/backend/tests/test_migrations.py index f934f728b..b003e1403 100644 --- a/backend/tests/test_migrations.py +++ b/backend/tests/test_migrations.py @@ -244,6 +244,7 @@ def _replay(connection: sa.Connection, filename: str) -> None: ("0141_device_capabilities.py", "devices"), ("0142_state_core.py", "states"), ("0143_sibling_platform_names.py", "platforms"), + ("0144_user_oidc_sub.py", "users"), ], ) def test_a_revision_replayed_over_the_migrated_schema_is_a_no_op( @@ -311,6 +312,22 @@ def test_the_state_core_revision_reverses_and_replays(): assert _schema_of(connection, "states") == before +def test_the_user_oidc_sub_revision_reverses_and_replays(): + migration = _load_migration("0144_user_oidc_sub.py") + + with sync_engine.begin() as connection: + before = _schema_of(connection, "users") + with Operations.context(MigrationContext.configure(connection)): + migration.downgrade() + assert not has_column(connection, "users", "oidc_sub") + + migration.downgrade() + migration.upgrade() + migration.upgrade() + + assert _schema_of(connection, "users") == before + + def _slot_collations(connection: sa.Connection) -> dict[str, str | None]: inspector = sa.inspect(connection) collations = {} diff --git a/docs/BACKEND_ARCHITECTURE.md b/docs/BACKEND_ARCHITECTURE.md index de978ac1f..4bd4827bd 100644 --- a/docs/BACKEND_ARCHITECTURE.md +++ b/docs/BACKEND_ARCHITECTURE.md @@ -527,6 +527,7 @@ Constants: `FILE_NAME_MAX_LENGTH=450`, `FILE_PATH_MAX_LENGTH=1000`, `FILE_EXTENS | `username` | String(255) | Unique, indexed | | `hashed_password` | String(255) | Nullable (OIDC users) | | `email` | String(255) | Unique, indexed, nullable | +| `oidc_sub` | String(255) | OIDC `sub`, unique, null | | `enabled` | Boolean | Default `True` | | `role` | Enum(`VIEWER`, `EDITOR`, `ADMIN`) | Default `VIEWER` | | `avatar_path` | String(255) | Default `""` |