Skip to content

Speakr is a personal, self-hosted web application designed for transcribing audio recordings

Python

fix: always resolve OIDC claims via UserInfo endpoint when the ID token lacks email/name/username, with sub-match check (#377)

Murtaza Nasir8efc2cda9176
diff --git a/src/api/auth.py b/src/api/auth.py
index 8c039475..36abe585 100644
--- a/src/api/auth.py
+++ b/src/api/auth.py
@@ -28,6 +28,7 @@ from src.auth.sso import (
create_or_update_sso_user,
is_domain_allowed,
link_sso_to_existing_user,
+ resolve_userinfo,
update_user_profile_from_claims,
)
from src.services.email import (
@@ -290,7 +291,7 @@ def sso_callback():
try:
token = oauth.sso.authorize_access_token()
- userinfo = token.get('userinfo') or oauth.sso.userinfo()
+ userinfo = resolve_userinfo(oauth, token)
except Exception as e:
current_app.logger.warning(f"SSO callback error: {e}")
flash('SSO login failed. Please try again.', 'danger')
diff --git a/src/auth/sso.py b/src/auth/sso.py
index 09480011..2e13d914 100644
--- a/src/auth/sso.py
+++ b/src/auth/sso.py
@@ -100,6 +100,41 @@ def get_sso_client() -> Optional[OAuth]:
return _oauth
+def resolve_userinfo(oauth, token) -> Dict:
+ """Resolve the full OIDC claim set for a login.
+
+ Authlib exposes the ID token claims as ``token['userinfo']``, but many
+ IdPs (Keycloak, Azure AD, LemonLDAP::NG) only publish ``email``, ``name``
+ and ``preferred_username`` at the UserInfo endpoint, not inside the ID
+ token. When any claim we consume is missing from the ID token, fetch the
+ endpoint and overlay its claims. Endpoint claims are discarded if their
+ ``sub`` does not match the ID token's (OIDC Core 5.3.2).
+ """
+ cfg = get_sso_config()
+ claims = dict(token.get("userinfo") or {})
+ wanted = ("email", cfg["username_claim"] or "preferred_username", cfg["name_claim"] or "name")
+ if claims and all(claims.get(c) for c in wanted):
+ return claims
+
+ try:
+ endpoint_claims = dict(oauth.sso.userinfo(token=token))
+ except Exception as e:
+ current_app.logger.warning(
+ "SSO UserInfo endpoint call failed, falling back to ID token claims: %s", e
+ )
+ return claims
+
+ if claims.get("sub") and endpoint_claims.get("sub") and claims["sub"] != endpoint_claims["sub"]:
+ current_app.logger.warning(
+ "SSO UserInfo 'sub' does not match ID token 'sub'; ignoring endpoint claims"
+ )
+ return claims
+
+ merged = dict(claims)
+ merged.update({k: v for k, v in endpoint_claims.items() if v is not None})
+ return merged
+
+
def is_domain_allowed(email: Optional[str]) -> bool:
"""Check if email domain is allowed for auto-registration."""
if not email:
diff --git a/tests/test_sso.py b/tests/test_sso.py
index 86d56003..cb867e14 100644
--- a/tests/test_sso.py
+++ b/tests/test_sso.py
@@ -513,5 +513,84 @@ def test_require_verified_email_on_allows_no_email_claim(cleanup_users):
assert user.email == f"{sub}@placeholder.local"
+# ---------------------------------------------------------------------------
+# resolve_userinfo (#377: ID token claims short-circuited the UserInfo endpoint)
+# ---------------------------------------------------------------------------
+
+class _FakeOAuth:
+ """Stand-in for the Authlib registry: oauth.sso.userinfo(token=...)."""
+
+ class _Sso:
+ def __init__(self, result):
+ self._result = result
+ self.calls = 0
+
+ def userinfo(self, token=None):
+ self.calls += 1
+ if isinstance(self._result, Exception):
+ raise self._result
+ return self._result
+
+ def __init__(self, result):
+ self.sso = self._Sso(result)
+
+
+def test_resolve_userinfo_fetches_endpoint_when_id_token_lacks_claims(app_ctx):
+ """ID token with only sub/iss/aud must not short-circuit the endpoint."""
+ with env(SSO_DEFAULT_USERNAME_CLAIM=None, SSO_DEFAULT_NAME_CLAIM=None):
+ oauth = _FakeOAuth({"sub": "abc", "email": "[email protected]", "name": "Ann", "preferred_username": "ann"})
+ token = {"userinfo": {"sub": "abc", "iss": "https://idp", "aud": "client"}}
+ claims = sso.resolve_userinfo(oauth, token)
+ assert oauth.sso.calls == 1
+ assert claims["email"] == "[email protected]"
+ assert claims["name"] == "Ann"
+ assert claims["preferred_username"] == "ann"
+
+
+def test_resolve_userinfo_skips_endpoint_when_id_token_complete(app_ctx):
+ with env(SSO_DEFAULT_USERNAME_CLAIM=None, SSO_DEFAULT_NAME_CLAIM=None):
+ full = {"sub": "abc", "email": "[email protected]", "name": "Ann", "preferred_username": "ann"}
+ oauth = _FakeOAuth(RuntimeError("endpoint should not be called"))
+ claims = sso.resolve_userinfo(oauth, {"userinfo": full})
+ assert oauth.sso.calls == 0
+ assert claims == full
+
+
+def test_resolve_userinfo_endpoint_failure_falls_back_to_id_token(app_ctx):
+ with env(SSO_DEFAULT_USERNAME_CLAIM=None, SSO_DEFAULT_NAME_CLAIM=None):
+ oauth = _FakeOAuth(RuntimeError("boom"))
+ idt = {"sub": "abc", "email": "[email protected]"}
+ claims = sso.resolve_userinfo(oauth, {"userinfo": idt})
+ assert oauth.sso.calls == 1
+ assert claims == idt
+
+
+def test_resolve_userinfo_rejects_endpoint_claims_on_sub_mismatch(app_ctx):
+ """OIDC Core 5.3.2: endpoint sub must match ID token sub."""
+ with env(SSO_DEFAULT_USERNAME_CLAIM=None, SSO_DEFAULT_NAME_CLAIM=None):
+ oauth = _FakeOAuth({"sub": "EVIL", "email": "[email protected]"})
+ idt = {"sub": "abc"}
+ claims = sso.resolve_userinfo(oauth, {"userinfo": idt})
+ assert claims == idt
+
+
+def test_resolve_userinfo_id_token_claims_survive_merge(app_ctx):
+ """Endpoint claims overlay, but claims absent from the endpoint are kept."""
+ with env(SSO_DEFAULT_USERNAME_CLAIM=None, SSO_DEFAULT_NAME_CLAIM=None):
+ oauth = _FakeOAuth({"sub": "abc", "email": "[email protected]", "name": None})
+ idt = {"sub": "abc", "email_verified": True, "name": "From IDT"}
+ claims = sso.resolve_userinfo(oauth, {"userinfo": idt})
+ assert claims["email"] == "[email protected]"
+ assert claims["email_verified"] is True
+ assert claims["name"] == "From IDT" # None from endpoint must not clobber
+
+
+def test_resolve_userinfo_no_id_token_claims_uses_endpoint(app_ctx):
+ with env(SSO_DEFAULT_USERNAME_CLAIM=None, SSO_DEFAULT_NAME_CLAIM=None):
+ oauth = _FakeOAuth({"sub": "abc", "email": "[email protected]"})
+ claims = sso.resolve_userinfo(oauth, {})
+ assert claims == {"sub": "abc", "email": "[email protected]"}
+
+
if __name__ == "__main__":
sys.exit(pytest.main([__file__, "-q"]))