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): bind OIDC logins to (iss, sub), not email

James Howe6d201c39b6a9
diff --git a/core/switch_core/db/stores/user_store.py b/core/switch_core/db/stores/user_store.py
index e4a60ce52..87b38b1fb 100644
--- a/core/switch_core/db/stores/user_store.py
+++ b/core/switch_core/db/stores/user_store.py
@@ -6,6 +6,14 @@ from sqlalchemy.ext.asyncio import AsyncSession
from switch_core.db.models import User
+class OidcIdentityConflictError(Exception):
+ """An OIDC login's email already belongs to a different local account.
+
+ Raised instead of silently linking the IdP identity to a pre-existing
+ account: auto-linking by email is an account-takeover vector.
+ """
+
+
class UserStore:
async def create(self, session: AsyncSession, user: User) -> None:
session.add(user)
@@ -18,26 +26,65 @@ class UserStore:
result = await session.execute(select(User).where(User.email == email))
return result.scalar_one_or_none()
+ 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.
+ """
+ result = await session.execute(
+ select(User).where(User.metadata_["oidc_sub"].astext == 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
+
async def get_or_create_oidc_user(
- self, session: AsyncSession, *, email: str, name: str, sub: str
+ self,
+ session: AsyncSession,
+ *,
+ iss: str,
+ email: str,
+ name: str,
+ sub: str,
) -> User:
"""Resolve an OIDC identity to a gateway user, provisioning on first
login (JIT).
- Matched on email: an existing user (password- or OIDC-provisioned)
- keeps its current role. A brand-new user is created as a plain `user`
- with no password hash; the IdP subject is stored in metadata so the
- link can be hardened later (email is mutable in some directories).
+ 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).
"""
- user = await self.get_by_email(session, email)
+ 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_sub": sub},
+ metadata_={"oidc_iss": iss, "oidc_sub": sub},
)
await self.create(session, user)
return user
diff --git a/core/switch_core/gateway/oidc_routes.py b/core/switch_core/gateway/oidc_routes.py
index 0eb449e0d..5be7f3f83 100644
--- a/core/switch_core/gateway/oidc_routes.py
+++ b/core/switch_core/gateway/oidc_routes.py
@@ -9,7 +9,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
from starlette.responses import RedirectResponse
from switch_core.config import SwitchConfig
-from switch_core.db.stores.user_store import UserStore
+from switch_core.db.stores.user_store import OidcIdentityConflictError, UserStore
from switch_core.gateway.auth import set_session_cookie
from switch_core.gateway.dependencies import get_config, get_session, get_user_store
@@ -93,11 +93,25 @@ async def oidc_callback(
raise HTTPException(
status_code=401, detail="OIDC token missing email or sub claim"
)
+ # Provisioning trusts the email, so an unverified (attacker-set) one must
+ # not be accepted.
+ email_verified = claims.get("email_verified")
+ if email_verified is not True and str(email_verified).lower() != "true":
+ logger.warning("OIDC login rejected: email not verified (sub %s)", sub)
+ raise HTTPException(status_code=401, detail="OIDC email is not verified")
name = claims.get("name") or email.split("@")[0]
- user = await user_store.get_or_create_oidc_user(
- session, email=email, name=name, sub=sub
- )
+ # Bind to the immutable issuer+subject, never the mutable email.
+ 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
+ )
+ except OidcIdentityConflictError as exc:
+ logger.warning("OIDC identity conflict: %s", exc)
+ raise HTTPException(status_code=409, detail=str(exc)) from exc
await session.commit()
# Verify-at-login only: we don't persist the IdP tokens. Land the browser
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 51b30cdae..c240f725f 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
@@ -1,9 +1,12 @@
from __future__ import annotations
+import pytest
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
from switch_core.db.models import User
-from switch_core.db.stores.user_store import UserStore
+from switch_core.db.stores.user_store import OidcIdentityConflictError, UserStore
+
+_ISS = "https://idp.example.com"
class TestGetOrCreateOidcUser:
@@ -13,16 +16,37 @@ class TestGetOrCreateOidcUser:
store = UserStore()
async with session_factory() as session:
user = await store.get_or_create_oidc_user(
- session, email="[email protected]", name="New", sub="okta|9"
+ session, iss=_ISS, email="[email protected]", name="New", sub="okta|9"
)
await session.commit()
assert user.role == "user"
assert user.password_hash is None
- assert user.metadata_ == {"oidc_sub": "okta|9"}
+ assert user.metadata_ == {"oidc_iss": _ISS, "oidc_sub": "okta|9"}
- async def test_existing_user_is_returned_and_keeps_role(
+ async def test_same_identity_is_returned_and_keeps_role(
self, session_factory: async_sessionmaker[AsyncSession]
) -> None:
+ 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"
+ )
+ 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"
+ )
+ assert again.id == first.id
+ assert again.role == "admin"
+
+ async def test_email_collision_with_different_identity_is_refused(
+ 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.
store = UserStore()
async with session_factory() as session:
admin = User(
@@ -34,9 +58,36 @@ class TestGetOrCreateOidcUser:
await store.create(session, admin)
await session.commit()
+ with pytest.raises(OidcIdentityConflictError):
+ await store.get_or_create_oidc_user(
+ session,
+ iss=_ISS,
+ name="Different",
+ sub="okta|1",
+ )
+
+ async def test_legacy_row_without_iss_matches_by_sub_and_backfills(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ store = UserStore()
+ async with session_factory() as session:
+ legacy = User(
+ name="Legacy",
+ role="user",
+ password_hash=None,
+ metadata_={"oidc_sub": "okta|7"},
+ )
+ await store.create(session, legacy)
+ await session.commit()
+
got = await store.get_or_create_oidc_user(
- session, email="[email protected]", name="Different", sub="okta|1"
+ session,
+ iss=_ISS,
+ name="Legacy",
+ sub="okta|7",
)
- assert got.id == admin.id
- # Matching an existing account must NOT downgrade its role.
- assert got.role == "admin"
+ assert got.id == legacy.id
+ assert got.metadata_ == {"oidc_sub": "okta|7", "oidc_iss": _ISS}
diff --git a/core/tests/switch_core/gateway/test_oidc_routes.py b/core/tests/switch_core/gateway/test_oidc_routes.py
index 07a05d132..84a4ed8ab 100644
--- a/core/tests/switch_core/gateway/test_oidc_routes.py
+++ b/core/tests/switch_core/gateway/test_oidc_routes.py
@@ -8,6 +8,7 @@ from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
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_routes import auth_config
@@ -55,6 +56,7 @@ class TestOidcCallback:
token = {
"userinfo": {
"email": "[email protected]",
+ "email_verified": True,
"sub": "okta|123",
"name": "Alice",
}
@@ -77,7 +79,74 @@ class TestOidcCallback:
assert user is not None
assert user.role == "user"
assert user.password_hash is None
- assert user.metadata_ == {"oidc_sub": "okta|123"}
+ assert user.metadata_ == {
+ "oidc_iss": "https://idp.example",
+ "oidc_sub": "okta|123",
+ }
+
+ async def test_unverified_email_is_rejected(
+ self,
+ session_factory: async_sessionmaker[AsyncSession],
+ monkeypatch: pytest.MonkeyPatch,
+ ) -> None:
+ token = {
+ "userinfo": {
+ "email": "[email protected]",
+ "email_verified": False,
+ "sub": "okta|9",
+ "name": "Mallory",
+ }
+ }
+ 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 == 401
+
+ async def test_email_collision_with_existing_account_is_rejected(
+ 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
+
+ async with session_factory() as session:
+ admin = User(
+ name="Admin",
+ role="admin",
+ password_hash=hash_password("pw"),
+ )
+ await UserStore().create(session, admin)
+ await session.commit()
+
+ token = {
+ "userinfo": {
+ "email": "[email protected]",
+ "email_verified": True,
+ "sub": "okta|attacker",
+ "name": "Not 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
async def test_missing_email_claim_raises_401(
self,