Skip to content

Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.

fix(gateway): link a verified OIDC identity to its account by email (CHOO-2624)

Wojciech Wojtyniak83f9d7b107e4
diff --git a/core/switch_core/db/models.py b/core/switch_core/db/models.py
index c01d4961d..dcdbf5a04 100644
--- a/core/switch_core/db/models.py
+++ b/core/switch_core/db/models.py
@@ -51,6 +51,30 @@ class User(Base):
)
+class OidcIdentity(Base):
+ """A verified IdP identity linked to a user (CHOO-2624).
+
+ One row per linked ``(iss, sub)``, unique so a subject can never bind to
+ more than one account. A user may hold several — accounts are keyed on
+ verified email, not on login method, so a password sign-up that later
+ signs in with an IdP sharing its email gets this identity added to the
+ same account rather than a second one.
+ """
+
+ __tablename__ = "oidc_identities"
+ __table_args__ = (
+ UniqueConstraint("iss", "sub", name="uq_oidc_identities_iss_sub"),
+ )
+
+ id: Mapped[str] = mapped_column(Text, primary_key=True, default=_uuid)
+ user_id: Mapped[str] = mapped_column(Text, ForeignKey("users.id"), nullable=False)
+ iss: Mapped[str] = mapped_column(Text, nullable=False)
+ sub: Mapped[str] = mapped_column(Text, nullable=False)
+ created_at: Mapped[str] = mapped_column(
+ DateTime(timezone=True), server_default=func.now(), nullable=False
+ )
+
+
# ── API Keys ─────────────────────────────────────────────────────────────────
diff --git a/core/switch_core/db/stores/user_store.py b/core/switch_core/db/stores/user_store.py
index 87b38b1fb..7e64aab3c 100644
--- a/core/switch_core/db/stores/user_store.py
+++ b/core/switch_core/db/stores/user_store.py
@@ -3,14 +3,16 @@ from __future__ import annotations
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
-from switch_core.db.models import User
+from switch_core.db.models import OidcIdentity, User
class OidcIdentityConflictError(Exception):
- """An OIDC login's email already belongs to a different local account.
+ """An unverified OIDC login's email already belongs to a different account.
Raised instead of silently linking the IdP identity to a pre-existing
- account: auto-linking by email is an account-takeover vector.
+ account: an unverified email is attacker-controllable, so trusting it to
+ pick an account is an account-takeover vector. A verified email links
+ instead — see ``get_or_create_oidc_user``.
"""
@@ -29,20 +31,13 @@ class UserStore:
async def get_by_oidc_identity(
self, session: AsyncSession, *, iss: str, sub: str
) -> User | None:
- """Find the user bound to this IdP identity by its immutable (iss, sub).
-
- Legacy rows (provisioned before iss was stored) carry only ``oidc_sub``;
- those match on sub alone and get their ``oidc_iss`` backfilled by the
- caller. ``sub`` is unique per issuer, so matching on it is safe.
- """
+ """Find the user linked to this IdP identity by its immutable (iss, sub)."""
result = await session.execute(
- select(User).where(User.metadata_["oidc_sub"].astext == sub)
+ select(User)
+ .join(OidcIdentity, OidcIdentity.user_id == User.id)
+ .where(OidcIdentity.iss == iss, OidcIdentity.sub == sub)
)
- for user in result.scalars().all():
- stored_iss = (user.metadata_ or {}).get("oidc_iss")
- if stored_iss is None or stored_iss == iss:
- return user
- return None
+ return result.scalar_one_or_none()
async def get_or_create_oidc_user(
self,
@@ -52,43 +47,49 @@ class UserStore:
email: str,
name: str,
sub: str,
+ email_verified: bool,
) -> User:
"""Resolve an OIDC identity to a gateway user, provisioning on first
login (JIT).
- Identity is bound to the immutable ``(iss, sub)`` pair, never to the
- mutable email: an existing user is only returned when its stored IdP
- subject matches. A brand-new subject provisions a fresh ``user`` (no
- password hash). If the email is already taken by a different local
- account (a password user, or a different IdP subject), we refuse rather
- than link, so a token bearing someone else's email cannot take over
- their account (including the seeded admin).
+ Accounts are keyed on verified email, not on login method: a subject
+ already linked to a user is returned as-is (looked up on the
+ immutable ``(iss, sub)`` pair, never the mutable email). Otherwise, a
+ *verified* email that matches an existing account links this identity
+ to it — one user can hold several linked identities — so someone who
+ signed up with a password and later signs in with an IdP sharing that
+ email lands in the same account instead of a second one.
+
+ An unverified email must never pick an existing account: that is an
+ attacker-controllable claim, so a collision with a pre-existing
+ account is refused rather than linked. A brand-new email — verified
+ or not — provisions a fresh ``user`` (no password hash).
"""
user = await self.get_by_oidc_identity(session, iss=iss, sub=sub)
if user is not None:
- meta = dict(user.metadata_ or {})
- if meta.get("oidc_iss") != iss:
- meta["oidc_iss"] = iss
- user.metadata_ = meta
- await session.flush()
return user
- if await self.get_by_email(session, email) is not None:
- raise OidcIdentityConflictError(
- f"An account with email {email!r} already exists and is not "
- "linked to this identity."
- )
-
- user = User(
- name=name,
- email=email,
- role="user",
- password_hash=None,
- metadata_={"oidc_iss": iss, "oidc_sub": sub},
- )
+ existing = await self.get_by_email(session, email)
+ if existing is not None:
+ if not email_verified:
+ raise OidcIdentityConflictError(
+ f"An account with email {email!r} already exists and this "
+ "identity's email is not verified."
+ )
+ await self._link_identity(session, user=existing, iss=iss, sub=sub)
+ return existing
+
+ user = User(name=name, email=email, role="user", password_hash=None)
await self.create(session, user)
+ await self._link_identity(session, user=user, iss=iss, sub=sub)
return user
+ async def _link_identity(
+ self, session: AsyncSession, *, user: User, iss: str, sub: str
+ ) -> None:
+ session.add(OidcIdentity(user_id=user.id, iss=iss, sub=sub))
+ await session.flush()
+
async def get_all(self, session: AsyncSession) -> list[User]:
result = await session.execute(select(User))
return list(result.scalars().all())
diff --git a/core/switch_core/gateway/oidc_routes.py b/core/switch_core/gateway/oidc_routes.py
index 968c2d24a..0ac2e3ed0 100644
--- a/core/switch_core/gateway/oidc_routes.py
+++ b/core/switch_core/gateway/oidc_routes.py
@@ -115,13 +115,15 @@ async def oidc_callback(
)
name = claims.get("name") or email.split("@")[0]
- # Bind to the immutable issuer+subject, never the mutable email.
+ # A returning identity is looked up on the immutable issuer+subject, never
+ # the mutable email; email only decides which account a *new* identity
+ # lands in, and only once it's verified (see get_or_create_oidc_user).
iss = claims.get("iss") or config.gateway_oidc_issuer_url
if not iss:
raise HTTPException(status_code=401, detail="OIDC token missing issuer")
try:
user = await user_store.get_or_create_oidc_user(
- session, iss=iss, email=email, name=name, sub=sub
+ session, iss=iss, email=email, name=name, sub=sub, email_verified=verified
)
except OidcIdentityConflictError as exc:
logger.warning("OIDC identity conflict: %s", exc)
diff --git a/core/switch_core/migrations/versions/04f27f37e474_oidc_identities_table.py b/core/switch_core/migrations/versions/04f27f37e474_oidc_identities_table.py
new file mode 100644
index 000000000..3bf129082
--- /dev/null
+++ b/core/switch_core/migrations/versions/04f27f37e474_oidc_identities_table.py
@@ -0,0 +1,83 @@
+"""oidc identities become a table, not a metadata pair
+
+Revision ID: 04f27f37e474
+Revises: c8e4a10b7f36
+
+Accounts are now keyed on verified email, not on login method (CHOO-2624): a
+verified OIDC identity links to the account with a matching email instead of
+being refused. A single ``oidc_iss``/``oidc_sub`` pair in ``users.metadata``
+can only ever name one identity per user, which cannot represent that — a
+password sign-up that later links a second IdP needs a second identity on the
+same account. Identity moves into its own table instead: one row per linked
+``(iss, sub)``, unique so a subject can never be bound to more than one
+account, with a user able to hold several.
+
+Existing ``oidc_iss``/``oidc_sub`` pairs are copied into the new table and
+removed from ``metadata``, which becomes the single remaining source of truth
+going forward. Older rows that predate ``oidc_iss`` being stored (``oidc_sub``
+only, no issuer) can't be attributed to an issuer here and are left as-is;
+the application no longer reads them, but the next login from that IdP
+resolves the account the same way any first-time link does now — by the
+verified email matching the existing account — so no manual fix-up is needed.
+"""
+
+from collections.abc import Sequence
+
+import sqlalchemy as sa
+from alembic import op
+
+revision: str = "04f27f37e474"
+down_revision: str | Sequence[str] | None = "c8e4a10b7f36"
+branch_labels: str | Sequence[str] | None = None
+depends_on: str | Sequence[str] | None = None
+
+
+def upgrade() -> None:
+ op.create_table(
+ "oidc_identities",
+ sa.Column("id", sa.Text(), primary_key=True),
+ sa.Column("user_id", sa.Text(), sa.ForeignKey("users.id"), nullable=False),
+ sa.Column("iss", sa.Text(), nullable=False),
+ sa.Column("sub", sa.Text(), nullable=False),
+ sa.Column(
+ "created_at",
+ sa.DateTime(timezone=True),
+ server_default=sa.func.now(),
+ nullable=False,
+ ),
+ sa.UniqueConstraint("iss", "sub", name="uq_oidc_identities_iss_sub"),
+ )
+
+ connection = op.get_bind()
+ connection.execute(
+ sa.text(
+ """
+ INSERT INTO oidc_identities (id, user_id, iss, sub)
+ SELECT gen_random_uuid()::text, id, metadata->>'oidc_iss', metadata->>'oidc_sub'
+ FROM users
+ WHERE metadata ? 'oidc_sub' AND metadata ? 'oidc_iss'
+ """
+ )
+ )
+ connection.execute(
+ sa.text(
+ "UPDATE users SET metadata = metadata - 'oidc_iss' - 'oidc_sub' "
+ "WHERE metadata ? 'oidc_sub' AND metadata ? 'oidc_iss'"
+ )
+ )
+
+
+def downgrade() -> None:
+ connection = op.get_bind()
+ connection.execute(
+ sa.text(
+ """
+ UPDATE users
+ SET metadata = coalesce(metadata, '{}'::jsonb)
+ || jsonb_build_object('oidc_iss', oidc_identities.iss, 'oidc_sub', oidc_identities.sub)
+ FROM oidc_identities
+ WHERE oidc_identities.user_id = users.id
+ """
+ )
+ )
+ op.drop_table("oidc_identities")
diff --git a/core/tests/switch_core/db/stores/test_user_store_oidc.py b/core/tests/switch_core/db/stores/test_user_store_oidc.py
index c240f725f..ee194b32b 100644
--- a/core/tests/switch_core/db/stores/test_user_store_oidc.py
+++ b/core/tests/switch_core/db/stores/test_user_store_oidc.py
@@ -16,12 +16,20 @@ class TestGetOrCreateOidcUser:
store = UserStore()
async with session_factory() as session:
user = await store.get_or_create_oidc_user(
- session, iss=_ISS, email="[email protected]", name="New", sub="okta|9"
+ session,
+ iss=_ISS,
+ name="New",
+ sub="okta|9",
+ email_verified=True,
)
await session.commit()
assert user.role == "user"
assert user.password_hash is None
- assert user.metadata_ == {"oidc_iss": _ISS, "oidc_sub": "okta|9"}
+ assert user.metadata_ is None
+
+ again = await store.get_by_oidc_identity(session, iss=_ISS, sub="okta|9")
+ assert again is not None and again.id == user.id
async def test_same_identity_is_returned_and_keeps_role(
self, session_factory: async_sessionmaker[AsyncSession]
@@ -29,24 +37,107 @@ class TestGetOrCreateOidcUser:
store = UserStore()
async with session_factory() as session:
first = await store.get_or_create_oidc_user(
- session, iss=_ISS, email="[email protected]", name="A", sub="okta|1"
+ session,
+ iss=_ISS,
+ name="A",
+ sub="okta|1",
+ email_verified=True,
)
await session.commit()
first.role = "admin"
await session.commit()
again = await store.get_or_create_oidc_user(
- session, iss=_ISS, email="[email protected]", name="A", sub="okta|1"
+ session,
+ iss=_ISS,
+ name="A",
+ sub="okta|1",
+ email_verified=True,
)
assert again.id == first.id
assert again.role == "admin"
- async def test_email_collision_with_different_identity_is_refused(
+ async def test_verified_email_links_to_existing_account(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ # The reversal this fix makes: someone who signed up with a password
+ # and later signs in with an IdP sharing that verified email lands in
+ # the same account, not a second one.
+ store = UserStore()
+ async with session_factory() as session:
+ existing = User(
+ name="Pat",
+ role="user",
+ password_hash="bcrypt-hash",
+ )
+ await store.create(session, existing)
+ await session.commit()
+
+ linked = await store.get_or_create_oidc_user(
+ session,
+ iss=_ISS,
+ name="Pat",
+ sub="okta|42",
+ email_verified=True,
+ )
+ await session.commit()
+
+ assert linked.id == existing.id
+ # Password login must not be weakened by the link.
+ assert linked.password_hash == "bcrypt-hash"
+
+ by_identity = await store.get_by_oidc_identity(
+ session, iss=_ISS, sub="okta|42"
+ )
+ assert by_identity is not None and by_identity.id == existing.id
+
+ async def test_two_subjects_same_issuer_can_both_link_to_one_account(
self, session_factory: async_sessionmaker[AsyncSession]
) -> None:
- # The takeover this fix closes: an existing (password) admin must not be
- # returned to an OIDC login that merely shares its email with a
- # different subject.
+ # A user may hold several identities (e.g. two Google accounts
+ # forwarding to one mailbox at the IdP) without either one being able
+ # to impersonate the other: each keeps its own (iss, sub) row and
+ # both resolve back to the same account, never to each other.
+ store = UserStore()
+ async with session_factory() as session:
+ first = await store.get_or_create_oidc_user(
+ session,
+ iss=_ISS,
+ name="Shared",
+ sub="okta|1",
+ email_verified=True,
+ )
+ await session.commit()
+
+ second = await store.get_or_create_oidc_user(
+ session,
+ iss=_ISS,
+ name="Shared",
+ sub="okta|2",
+ email_verified=True,
+ )
+ await session.commit()
+
+ assert second.id == first.id
+ assert (
+ await store.get_by_oidc_identity(session, iss=_ISS, sub="okta|1")
+ ).id == first.id # type: ignore[union-attr]
+ assert (
+ await store.get_by_oidc_identity(session, iss=_ISS, sub="okta|2")
+ ).id == first.id # type: ignore[union-attr]
+
+ async def test_unverified_email_collision_with_different_identity_is_refused(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ # The takeover this closes: an existing (password) admin must not be
+ # handed to an OIDC login that merely shares its email with a
+ # different, unverified subject.
store = UserStore()
async with session_factory() as session:
admin = User(
@@ -65,29 +156,42 @@ class TestGetOrCreateOidcUser:
name="Different",
sub="okta|1",
+ email_verified=False,
)
- async def test_legacy_row_without_iss_matches_by_sub_and_backfills(
+ async def test_identity_already_bound_elsewhere_is_never_relinked(
self, session_factory: async_sessionmaker[AsyncSession]
) -> None:
+ # Once (iss, sub) is bound, that lookup — not the email on the
+ # incoming claim — decides the account, so a stale or changed email on
+ # the same subject can never move the identity to someone else's row.
store = UserStore()
async with session_factory() as session:
- legacy = User(
- name="Legacy",
+ owner = await store.get_or_create_oidc_user(
+ session,
+ iss=_ISS,
+ name="Owner",
+ sub="okta|owned",
+ email_verified=True,
+ )
+ await session.commit()
+
+ other = User(
+ name="Other",
role="user",
- password_hash=None,
- metadata_={"oidc_sub": "okta|7"},
+ password_hash="bcrypt-hash",
)
- await store.create(session, legacy)
+ await store.create(session, other)
await session.commit()
- got = await store.get_or_create_oidc_user(
+ again = await store.get_or_create_oidc_user(
session,
iss=_ISS,
- name="Legacy",
- sub="okta|7",
+ name="Owner",
+ sub="okta|owned",
+ email_verified=True,
)
- assert got.id == legacy.id
- assert got.metadata_ == {"oidc_sub": "okta|7", "oidc_iss": _ISS}
+ assert again.id == owner.id
diff --git a/core/tests/switch_core/gateway/test_oidc_routes.py b/core/tests/switch_core/gateway/test_oidc_routes.py
index 64043cb5b..60da1c5fe 100644
--- a/core/tests/switch_core/gateway/test_oidc_routes.py
+++ b/core/tests/switch_core/gateway/test_oidc_routes.py
@@ -10,6 +10,7 @@ import switch_core.gateway.oidc_routes as oidc_routes
from switch_core.config import SwitchConfig
from switch_core.db.models import User
from switch_core.db.stores.user_store import UserStore
+from switch_core.gateway.auth import hash_password
from switch_core.gateway.auth_routes import auth_config
@@ -75,10 +76,11 @@ class TestOidcCallback:
assert user is not None
assert user.role == "user"
assert user.password_hash is None
- assert user.metadata_ == {
- "oidc_iss": "https://idp.example",
- "oidc_sub": "okta|123",
- }
+ assert user.metadata_ is None
+ linked = await UserStore().get_by_oidc_identity(
+ session, iss="https://idp.example", sub="okta|123"
+ )
+ assert linked is not None and linked.id == user.id
@pytest.mark.parametrize("email_verified", [False, None, "false"])
async def test_unverified_email_is_rejected(
@@ -140,10 +142,10 @@ class TestOidcCallback:
assert response.status_code == 303
user = await UserStore().get_by_email(session, "[email protected]")
assert user is not None
- assert user.metadata_ == {
- "oidc_iss": "https://idp.example",
- "oidc_sub": "okta|55",
- }
+ linked = await UserStore().get_by_oidc_identity(
+ session, iss="https://idp.example", sub="okta|55"
+ )
+ assert linked is not None and linked.id == user.id
async def test_missing_email_claim_still_rejected_when_check_disabled(
self,
@@ -170,8 +172,6 @@ class TestOidcCallback:
monkeypatch: pytest.MonkeyPatch,
) -> None:
# The takeover guard is independent of the verified-email check.
- from switch_core.gateway.auth import hash_password
-
async with session_factory() as session:
await UserStore().create(
session,
@@ -204,15 +204,15 @@ class TestOidcCallback:
)
assert exc.value.status_code == 409
- async def test_email_collision_with_existing_account_is_rejected(
+ async def test_verified_email_links_to_existing_account(
self,
session_factory: async_sessionmaker[AsyncSession],
monkeypatch: pytest.MonkeyPatch,
) -> None:
- # A verified token whose email matches an existing account but whose
- # subject does not must not take that account over.
- from switch_core.gateway.auth import hash_password
-
+ # A verified token whose email matches an existing (password) account
+ # but whose subject does not must land the login in that account,
+ # rather than being refused: accounts are keyed on verified email, not
+ # on login method.
async with session_factory() as session:
admin = User(
name="Admin",
@@ -222,26 +222,93 @@ class TestOidcCallback:
)
await UserStore().create(session, admin)
await session.commit()
+ admin_id = admin.id
token = {
"userinfo": {
"email": "[email protected]",
"email_verified": True,
- "sub": "okta|attacker",
- "name": "Not Admin",
+ "sub": "okta|second-device",
+ "name": "Admin",
}
}
monkeypatch.setattr(oidc_routes, "_client", lambda: _FakeClient(token))
async with session_factory() as session:
- with pytest.raises(HTTPException) as exc:
- await oidc_routes.oidc_callback(
- request=SimpleNamespace(), # type: ignore[arg-type]
- config=_config(),
- session=session,
- user_store=UserStore(),
- )
- assert exc.value.status_code == 409
+ response = await oidc_routes.oidc_callback(
+ request=SimpleNamespace(), # type: ignore[arg-type]
+ config=_config(),
+ session=session,
+ user_store=UserStore(),
+ )
+ assert response.status_code == 303
+
+ user = await UserStore().get_by_email(session, "[email protected]")
+ assert user is not None
+ assert user.id == admin_id
+ # The link must not weaken password login on the account.
+ assert user.password_hash is not None
+ assert user.role == "admin"
+
+ linked = await UserStore().get_by_oidc_identity(
+ session, iss="https://idp.example", sub="okta|second-device"
+ )
+ assert linked is not None and linked.id == admin_id
+
+ async def test_bound_identity_is_not_relinked_by_a_different_claimed_email(
+ self,
+ session_factory: async_sessionmaker[AsyncSession],
+ monkeypatch: pytest.MonkeyPatch,
+ ) -> None:
+ # Once (iss, sub) is linked, that binding decides the account on every
+ # later login, regardless of what email the claim carries this time.
+ token = {
+ "userinfo": {
+ "email": "[email protected]",
+ "email_verified": True,
+ "sub": "okta|77",
+ "name": "Carol",
+ }
+ }
+ monkeypatch.setattr(oidc_routes, "_client", lambda: _FakeClient(token))
+
+ async with session_factory() as session:
+ first = await oidc_routes.oidc_callback(
+ request=SimpleNamespace(), # type: ignore[arg-type]
+ config=_config(),
+ session=session,
+ user_store=UserStore(),
+ )
+ assert first.status_code == 303
+ carol = await UserStore().get_by_email(session, "[email protected]")
+ assert carol is not None
+ carol_id = carol.id
+
+ other_email_token = {
+ "userinfo": {
+ "email": "[email protected]",
+ "email_verified": True,
+ "sub": "okta|77",
+ "name": "Carol",
+ }
+ }
+ monkeypatch.setattr(
+ oidc_routes, "_client", lambda: _FakeClient(other_email_token)
+ )
+
+ async with session_factory() as session:
+ response = await oidc_routes.oidc_callback(
+ request=SimpleNamespace(), # type: ignore[arg-type]
+ config=_config(),
+ session=session,
+ user_store=UserStore(),
+ )
+ assert response.status_code == 303
+ linked = await UserStore().get_by_oidc_identity(
+ session, iss="https://idp.example", sub="okta|77"
+ )
+ assert linked is not None and linked.id == carol_id
+ assert linked.email == "[email protected]"
async def test_missing_email_claim_raises_401(
self,