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): require GATEWAY_OIDC_SCOPES with openid, and stop a userinfo hiccup from 500ing (#418)

wojtyniakAQec455b611509
diff --git a/.env.example b/.env.example
index 981e00cd7..06f5deafc 100644
--- a/.env.example
+++ b/.env.example
@@ -136,9 +136,10 @@ MATTERMOST_USER_PASSWORD=
# distinct from the OAUTH_* block above) ──────────────────────────────────────
# See docs/old/GATEWAY_OIDC_SETUP.md before setting these, especially if the
# provider is WorkOS: it needs a Connect application, not a User Management
-# client id. Issuer/client id/secret are all-or-nothing — set all three or
-# none. Quote GATEWAY_OIDC_SCOPES; it must include "openid" or no id_token is
-# issued.
+# client id. Issuer/client id/secret/scopes are all-or-nothing — set all four
+# or none. Quote GATEWAY_OIDC_SCOPES, and include "openid": the server refuses
+# to start without it, because no id_token is issued for a scope list missing
+# it.
# GATEWAY_OIDC_ISSUER_URL=https://<your-idp-or-authkit-domain>
# GATEWAY_OIDC_CLIENT_ID=<client-id>
# GATEWAY_OIDC_CLIENT_SECRET=<client-secret>
diff --git a/core/switch_core/config.py b/core/switch_core/config.py
index d7e83bfc2..59b05d80d 100644
--- a/core/switch_core/config.py
+++ b/core/switch_core/config.py
@@ -86,11 +86,16 @@ class SwitchConfig(BaseSettings):
# Gateway OIDC login (optional — bring-your-own identity provider for the
# gateway browser login, e.g. Okta). Distinct from the agent oauth_*
# settings above, which gate the MCP/agent bridge and may point at a
- # different IdP. Active only when issuer + client id + secret are all
- # set; the provider's endpoints are read from OIDC discovery.
+ # different IdP. Active only when issuer + client id + secret + scopes
+ # are all set; the provider's endpoints are read from OIDC discovery.
gateway_oidc_issuer_url: str | None = None
gateway_oidc_client_id: str | None = None
gateway_oidc_client_secret: str | None = None
+ # Must include "openid": authlib omits the scope parameter entirely when
+ # this is unset, so the provider applies its own default scope, which may
+ # not include "openid" — the provider then issues no id_token, and the
+ # callback falls back to the provider's userinfo endpoint, which may not
+ # answer.
gateway_oidc_scopes: str | None = None
gateway_oidc_provider_label: str | None = None
# Absolute callback URL registered with the IdP. Must exactly match the
@@ -362,13 +367,24 @@ class SwitchConfig(BaseSettings):
self.gateway_oidc_issuer_url,
self.gateway_oidc_client_id,
self.gateway_oidc_client_secret,
+ self.gateway_oidc_scopes,
)
set_count = sum(1 for value in required if value)
if 0 < set_count < len(required):
raise ValueError(
"Partial gateway OIDC config: set all of "
"GATEWAY_OIDC_ISSUER_URL / GATEWAY_OIDC_CLIENT_ID / "
- "GATEWAY_OIDC_CLIENT_SECRET, or none of them."
+ "GATEWAY_OIDC_CLIENT_SECRET / GATEWAY_OIDC_SCOPES, or none "
+ "of them."
+ )
+ if self.gateway_oidc_scopes and "openid" not in (
+ self.gateway_oidc_scopes.split()
+ ):
+ raise ValueError(
+ "GATEWAY_OIDC_SCOPES must include 'openid': without it the "
+ "provider issues no id_token, and the callback falls back "
+ "to the provider's userinfo endpoint, which may not answer. "
+ f"Got {self.gateway_oidc_scopes!r}."
)
return self
diff --git a/core/switch_core/gateway/oidc_routes.py b/core/switch_core/gateway/oidc_routes.py
index 5c45ef4e3..338ac2811 100644
--- a/core/switch_core/gateway/oidc_routes.py
+++ b/core/switch_core/gateway/oidc_routes.py
@@ -1,8 +1,10 @@
from __future__ import annotations
+import json
import logging
from typing import Annotated, Any
+import httpx
from authlib.integrations.starlette_client import OAuth, OAuthError
from fastapi import APIRouter, Depends, HTTPException, Request
from sqlalchemy.ext.asyncio import AsyncSession
@@ -98,7 +100,42 @@ async def oidc_callback(
claims = token.get("userinfo")
if not claims:
- claims = await client.userinfo(token=token)
+ try:
+ claims = await client.userinfo(token=token)
+ except KeyError as exc:
+ # authlib's userinfo() looks up metadata["userinfo_endpoint"],
+ # which OIDC discovery makes optional. We only reach this call
+ # because token["userinfo"] was falsy, which authlib sets only
+ # when both an id_token and the stored nonce were present — so
+ # that can mean no id_token came back, or one did but the nonce
+ # didn't match. Either way, a provider that also has no
+ # userinfo_endpoint leaves no way to read claims at all — a
+ # configuration mistake (the wrong issuer for this deployment),
+ # not a transient upstream fault, so retrying won't help. Not a
+ # 500: that's for something unanticipated, and this is diagnosed
+ # precisely enough to name.
+ logger.error(
+ "OIDC callback failed: the provider published no "
+ "userinfo_endpoint and no claims were available from the "
+ "token, so there is nowhere to read claims from (%s)",
+ exc,
+ )
+ raise HTTPException(
+ status_code=503,
+ detail=(
+ "OIDC provider has no userinfo endpoint and no claims "
+ "were available from the token"
+ ),
+ ) from exc
+ except (httpx.HTTPError, json.JSONDecodeError) as exc:
+ # A non-2xx response, a transport failure (timeout, connection
+ # refused), or a 200 whose body isn't JSON (a proxy or captive
+ # portal in front of the provider) — the provider's fault, not
+ # the caller's.
+ logger.error("OIDC userinfo request failed: %s", exc)
+ raise HTTPException(
+ status_code=502, detail="OIDC provider did not respond"
+ ) from exc
email = claims.get("email")
sub = claims.get("sub")
if not email or not sub:
diff --git a/core/tests/switch_core/gateway/test_oidc_config.py b/core/tests/switch_core/gateway/test_oidc_config.py
index 8a75ec747..1db31590a 100644
--- a/core/tests/switch_core/gateway/test_oidc_config.py
+++ b/core/tests/switch_core/gateway/test_oidc_config.py
@@ -27,6 +27,7 @@ def _kwargs(**overrides: object) -> dict[str, object]:
gateway_oidc_issuer_url=None,
gateway_oidc_client_id=None,
gateway_oidc_client_secret=None,
+ gateway_oidc_scopes=None,
)
base.update(overrides)
return base
@@ -41,12 +42,13 @@ class TestGatewayOidcConfig:
# Opting out of the verified-email check must be deliberate.
assert config.gateway_oidc_require_email_verified is True
- def test_enabled_when_all_three_set(self) -> None:
+ def test_enabled_when_all_required_set(self) -> None:
config = SwitchConfig(
**_kwargs(
gateway_oidc_issuer_url="https://idp.example/realms/x",
gateway_oidc_client_id="cid",
gateway_oidc_client_secret="secret",
+ gateway_oidc_scopes="openid email profile",
) # type: ignore[arg-type]
)
assert config.gateway_oidc_enabled is True
@@ -55,13 +57,38 @@ class TestGatewayOidcConfig:
)
def test_partial_config_fails_loud(self) -> None:
- # Issuer set but client id/secret missing must raise at construction,
- # not silently disable OIDC.
+ # Issuer set but client id/secret/scopes missing must raise at
+ # construction, not silently disable OIDC.
with pytest.raises(ValidationError):
SwitchConfig(
**_kwargs(gateway_oidc_issuer_url="https://idp.example") # type: ignore[arg-type]
)
+ def test_scopes_required_alongside_the_others(self) -> None:
+ # A deployment that set issuer/client id/secret but not scopes used to
+ # come up with OIDC "on" and authlib silently omitting the scope
+ # parameter, so the provider applied its own default (which may not
+ # include openid, or omit an id_token). Now it must fail to start.
+ with pytest.raises(ValidationError):
+ SwitchConfig(
+ **_kwargs(
+ gateway_oidc_issuer_url="https://idp.example",
+ gateway_oidc_client_id="cid",
+ gateway_oidc_client_secret="secret",
+ ) # type: ignore[arg-type]
+ )
+
+ def test_scopes_must_include_openid(self) -> None:
+ with pytest.raises(ValidationError):
+ SwitchConfig(
+ **_kwargs(
+ gateway_oidc_issuer_url="https://idp.example",
+ gateway_oidc_client_id="cid",
+ gateway_oidc_client_secret="secret",
+ gateway_oidc_scopes="email profile",
+ ) # type: ignore[arg-type]
+ )
+
class TestVerifyPassword:
def test_none_hash_is_false_not_error(self) -> None:
diff --git a/core/tests/switch_core/gateway/test_oidc_routes.py b/core/tests/switch_core/gateway/test_oidc_routes.py
index 2f6c54090..e782fbea2 100644
--- a/core/tests/switch_core/gateway/test_oidc_routes.py
+++ b/core/tests/switch_core/gateway/test_oidc_routes.py
@@ -1,7 +1,9 @@
from __future__ import annotations
+import json
from types import SimpleNamespace
+import httpx
import pytest
from fastapi import HTTPException
from sqlalchemy import select
@@ -30,6 +32,7 @@ def _config(**overrides: object) -> SwitchConfig:
gateway_oidc_issuer_url="https://idp.example",
gateway_oidc_client_id="cid",
gateway_oidc_client_secret="sec",
+ gateway_oidc_scopes="openid email profile",
)
base.update(overrides)
return SwitchConfig(**base) # type: ignore[arg-type]
@@ -45,6 +48,19 @@ class _FakeClient:
return self._token
+class _FakeClientNoUserinfoInToken:
+ """A token with no embedded userinfo, forcing the userinfo HTTP call."""
+
+ def __init__(self, userinfo_error: Exception) -> None:
+ self._userinfo_error = userinfo_error
+
+ async def authorize_access_token(self, _request: object) -> dict:
+ return {"access_token": "at"}
+
+ async def userinfo(self, **_kwargs: object) -> dict:
+ raise self._userinfo_error
+
+
class TestOidcCallback:
async def test_provisions_user_and_sets_session_cookie(
self,
@@ -412,6 +428,92 @@ class TestOidcCallback:
)
assert exc.value.status_code == 401
+ async def test_userinfo_upstream_failure_maps_to_502(
+ self,
+ session_factory: async_sessionmaker[AsyncSession],
+ monkeypatch: pytest.MonkeyPatch,
+ ) -> None:
+ # A token with no embedded userinfo forces the fallback HTTP call to
+ # the provider's userinfo endpoint; that call failing is the IdP's
+ # fault, not the caller's, and must not surface as an unhandled 500.
+ monkeypatch.setattr(
+ oidc_routes,
+ "_client",
+ lambda: _FakeClientNoUserinfoInToken(
+ httpx.ConnectError("connection refused")
+ ),
+ )
+
+ 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 == 502
+ assert exc.value.detail == "OIDC provider did not respond"
+
+ async def test_userinfo_non_json_response_maps_to_502(
+ self,
+ session_factory: async_sessionmaker[AsyncSession],
+ monkeypatch: pytest.MonkeyPatch,
+ ) -> None:
+ # A 200 whose body isn't JSON (a proxy or captive portal sitting in
+ # front of the provider) fails in resp.json(), not raise_for_status()
+ # — still the provider's fault, so still a 502.
+ monkeypatch.setattr(
+ oidc_routes,
+ "_client",
+ lambda: _FakeClientNoUserinfoInToken(
+ json.JSONDecodeError("Expecting value", "<html>not json</html>", 0)
+ ),
+ )
+
+ 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 == 502
+ assert exc.value.detail == "OIDC provider did not respond"
+
+ async def test_missing_userinfo_endpoint_maps_to_503(
+ self,
+ session_factory: async_sessionmaker[AsyncSession],
+ monkeypatch: pytest.MonkeyPatch,
+ ) -> None:
+ # A provider whose discovery document has no userinfo_endpoint (it's
+ # optional in the OIDC spec — WorkOS's User Management surface is one
+ # such provider) combined with a token carrying no usable claims
+ # leaves nowhere to read claims from. That's a configuration mistake
+ # for this deployment, not a transient upstream fault — 503, not
+ # 500, since it's diagnosed precisely enough to name rather than
+ # unanticipated, and not a 502 since the provider didn't misbehave.
+ monkeypatch.setattr(
+ oidc_routes,
+ "_client",
+ lambda: _FakeClientNoUserinfoInToken(KeyError("userinfo_endpoint")),
+ )
+
+ 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 == 503
+ assert exc.value.detail == (
+ "OIDC provider has no userinfo endpoint and no claims were "
+ "available from the token"
+ )
+
class TestTheCallbackPlacesTheUserInATenant:
"""Sign-in provisions accounts, and an account with no membership can
@@ -550,6 +652,7 @@ class TestAuthConfigEndpoint:
gateway_oidc_issuer_url=None,
gateway_oidc_client_id=None,
gateway_oidc_client_secret=None,
+ gateway_oidc_scopes=None,
gateway_password_login_enabled=False,
)
result = await auth_config(config=config)
diff --git a/deploy/remote/helm/switch/templates/_helpers.tpl b/deploy/remote/helm/switch/templates/_helpers.tpl
index 572799ea4..10c96cc0b 100644
--- a/deploy/remote/helm/switch/templates/_helpers.tpl
+++ b/deploy/remote/helm/switch/templates/_helpers.tpl
@@ -551,8 +551,12 @@ Include with `nindent 12`.
secretKeyRef:
name: {{ include "switch.secretName" . }}
key: GATEWAY_OIDC_CLIENT_SECRET
+{{- $oidcScopes := required "switchCore.oidc.scopes is required when oidc.enabled" .Values.switchCore.oidc.scopes }}
+{{- if not (has "openid" (regexSplit "\\s+" (trim $oidcScopes) -1)) }}
+{{- fail (printf "switchCore.oidc.scopes must include \"openid\" — without it the provider issues no id_token and the gateway falls back to a userinfo call it may not answer. Got %q." $oidcScopes) }}
+{{- end }}
- name: GATEWAY_OIDC_SCOPES
- value: {{ .Values.switchCore.oidc.scopes | quote }}
+ value: {{ $oidcScopes | quote }}
- name: GATEWAY_OIDC_PROVIDER_LABEL
value: {{ .Values.switchCore.oidc.providerLabel | quote }}
{{- if .Values.switchCore.oidc.redirectUrl }}
diff --git a/docs/old/GATEWAY_OIDC_SETUP.md b/docs/old/GATEWAY_OIDC_SETUP.md
index 8bbda6c4f..f6e09c5b0 100644
--- a/docs/old/GATEWAY_OIDC_SETUP.md
+++ b/docs/old/GATEWAY_OIDC_SETUP.md
@@ -20,29 +20,31 @@ you explicitly turn it off with `GATEWAY_PASSWORD_LOGIN_ENABLED=false`.
| `GATEWAY_OIDC_ISSUER_URL` | yes* | The IdP's issuer. The gateway appends `/.well-known/openid-configuration` to it and discovers the authorize, token, JWKS and (where published) userinfo endpoints from there — nothing else about the provider is configured by hand. |
| `GATEWAY_OIDC_CLIENT_ID` | yes* | The client id registered with the IdP for this application. |
| `GATEWAY_OIDC_CLIENT_SECRET` | yes* | The client secret for that same registration. |
-| `GATEWAY_OIDC_SCOPES` | no, but see below | Space-separated OAuth scopes requested at authorize time, e.g. `openid profile email`. |
+| `GATEWAY_OIDC_SCOPES` | yes* | Space-separated OAuth scopes requested at authorize time, e.g. `openid profile email`. Must include `openid`. |
| `GATEWAY_OIDC_REDIRECT_URL` | no, but see below | The absolute callback URL registered with the IdP. |
| `GATEWAY_OIDC_PROVIDER_LABEL` | no | Text shown on the login button ("Log in with `<label>`"). Defaults to "SSO" if unset. |
| `GATEWAY_OIDC_REQUIRE_EMAIL_VERIFIED` | no | Defaults to `true`. See "What turning this off means" below. |
-*\*All-or-nothing.* `GATEWAY_OIDC_ISSUER_URL`, `GATEWAY_OIDC_CLIENT_ID` and
-`GATEWAY_OIDC_CLIENT_SECRET` are validated as a group at startup: set all
-three or none of them. Setting one or two without the rest fails config
-construction immediately (`Partial gateway OIDC config: set all of
-GATEWAY_OIDC_ISSUER_URL / GATEWAY_OIDC_CLIENT_ID / GATEWAY_OIDC_CLIENT_SECRET,
-or none of them.`) rather than starting up with OIDC silently disabled. OIDC
-is considered configured (`gateway_oidc_enabled`) exactly when all three are
-set; every other variable in the table is independently optional and has a
-default.
-
-### Scopes: always set this, and quote it
-
-`GATEWAY_OIDC_SCOPES` has no default — if you don't set it, the gateway asks
-authlib to request an unspecified scope, which most providers resolve to
-whatever their own default is. Set it explicitly, and **make sure it includes
-`openid`**: without that scope the token response carries no `id_token`, and
-the callback is left asking the provider's userinfo endpoint for claims
-instead — which some providers answer and some refuse.
+*\*All-or-nothing.* `GATEWAY_OIDC_ISSUER_URL`, `GATEWAY_OIDC_CLIENT_ID`,
+`GATEWAY_OIDC_CLIENT_SECRET` and `GATEWAY_OIDC_SCOPES` are validated as a
+group at startup: set all four or none of them. Setting some without the rest
+fails config construction immediately (`Partial gateway OIDC config: set all
+of GATEWAY_OIDC_ISSUER_URL / GATEWAY_OIDC_CLIENT_ID /
+GATEWAY_OIDC_CLIENT_SECRET / GATEWAY_OIDC_SCOPES, or none of them.`) rather
+than starting up with OIDC silently disabled. OIDC is considered configured
+(`gateway_oidc_enabled`) exactly when all four are set; every other variable
+in the table is independently optional and has a default.
+
+### Scopes: required, must include `openid`, and quote it
+
+`GATEWAY_OIDC_SCOPES` has no default, and OIDC will not start without it: it
+is part of the all-or-nothing group above, and a value that does not include
+`openid` is refused at startup with its own error. Both refusals exist for
+the same reason — without that scope the token response carries no
+`id_token`, and the callback is left asking the provider's userinfo endpoint
+for claims instead, which some providers answer and some refuse. Failing to
+boot is better than a login path that works against one provider and not the
+next.
Quote the value in your env file. `GATEWAY_OIDC_SCOPES=openid profile email`
(unquoted, with spaces) breaks `just`'s env-file parser — every recipe loads
@@ -52,11 +54,11 @@ loudly: `error: failed to load environment file ... Error parsing line`, exit
though: running `uv run python -m switch_core.main` directly skips it
entirely. Plain `uv run` doesn't read `.env` at all, so the variable is
simply unset there; `uv run --env-file .env` reads it but only warns on the
-bad line and continues. Either way, going around `just` trades the loud
-parse error for a silent one: `GATEWAY_OIDC_SCOPES` ends up unset, and the
-provider is asked for whatever scope it defaults to instead — with nothing
-pointing back at the scope configuration if that default happens not to
-include `openid`. Write it as:
+bad line and continues. Either way, going around `just` leaves
+`GATEWAY_OIDC_SCOPES` unset — which the startup check above now catches,
+refusing to boot rather than quietly asking the provider for whatever scope
+it defaults to. The error names the group rather than the quoting, so if you
+see it and believe you set the value, suspect the line. Write it as:
```
GATEWAY_OIDC_SCOPES="openid profile email"
@@ -188,8 +190,8 @@ email"` (quoted, per the warning above).
## Verifying it end to end
-1. Set the three required variables plus `GATEWAY_OIDC_SCOPES` and
- `GATEWAY_OIDC_REDIRECT_URL`, and restart the server.
+1. Set the four required variables plus `GATEWAY_OIDC_REDIRECT_URL`, and
+ restart the server.
2. `GET /gateway/auth/config` should report `oidc_enabled: true` and your
`oidc_provider_label` (or `null`, which the login page shows as "SSO").
3. Visiting the login page should show a "Log in with `<label>`" button