mirror of
https://github.com/rommapp/romm.git
synced 2026-12-02 10:08:40 +01:00
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) <noreply@anthropic.com>
This commit is contained in:
committed by
GitHub
parent
de0eff320c
commit
9d4bb40a6d
37
backend/alembic/versions/0144_user_oidc_sub.py
Normal file
37
backend/alembic/versions/0144_user_oidc_sub.py
Normal file
@@ -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)
|
||||
@@ -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
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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 = {}
|
||||
|
||||
@@ -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 `""` |
|
||||
|
||||
Reference in New Issue
Block a user