Open-source personal finance manager. Self-hosted, privacy-first.
fix(oidc): verify id_token at_hash so Google sign-in works (#350)
Albert Dolkun66585a27a1d0
diff --git a/backend/app/api/oidc_auth.py b/backend/app/api/oidc_auth.pyindex 7997fe93..cd4ccd0a 100644--- a/backend/app/api/oidc_auth.py+++ b/backend/app/api/oidc_auth.py@@ -127,7 +127,9 @@ async def _fetch_userinfo(discovery: dict[str, Any], access_token: str) -> dict[return response.json()-async def _decode_id_token(discovery: dict[str, Any], id_token: str, nonce: str) -> dict[str, Any]:+async def _decode_id_token(+ discovery: dict[str, Any], id_token: str, nonce: str, access_token: str = ""+) -> dict[str, Any]:settings = get_settings()jwks_uri = discovery.get("jwks_uri")issuer = discovery.get("issuer")@@ -148,6 +150,7 @@ async def _decode_id_token(discovery: dict[str, Any], id_token: str, nonce: str)algorithms=[key.get("alg", "RS256")],audience=settings.oidc_client_id,issuer=issuer,+ access_token=access_token,)except JWTError as exc:raise HTTPException(status_code=400, detail="Invalid OIDC id_token") from exc@@ -376,7 +379,9 @@ async def oidc_callback(id_token = token_response.get("id_token")if not id_token:raise HTTPException(status_code=400, detail="OIDC provider did not return an id_token")- claims = await _decode_id_token(discovery, id_token, state_data["nonce"])+ claims = await _decode_id_token(+ discovery, id_token, state_data["nonce"], token_response.get("access_token", "")+ )userinfo = await _fetch_userinfo(discovery, token_response.get("access_token", ""))user = await _get_or_create_oidc_user(claims, userinfo, discovery.get("issuer", ""), session, user_manager)if not user.is_active:diff --git a/backend/tests/test_oidc_auth.py b/backend/tests/test_oidc_auth.pyindex e9ccd248..c41c01b4 100644--- a/backend/tests/test_oidc_auth.py+++ b/backend/tests/test_oidc_auth.py@@ -46,6 +46,71 @@ def oidc_settings(monkeypatch):setattr(settings, key, value)+async def test_decode_id_token_accepts_google_style_at_hash(monkeypatch, oidc_settings):+ """Google id_token carrying at_hash must validate (regression for the+ 'Invalid OIDC id_token' failure: jwt.decode got no access_token)."""+ import time++ from cryptography.hazmat.primitives.asymmetric import rsa+ from jose import jwt as jose_jwt+ from jose.backends.cryptography_backend import CryptographyRSAKey+ from jose.constants import ALGORITHMS++ private = rsa.generate_private_key(public_exponent=65537, key_size=2048)+ priv_jwk = CryptographyRSAKey(private, ALGORITHMS.RS256).to_dict()+ pub_jwk = CryptographyRSAKey(private.public_key(), ALGORITHMS.RS256).to_dict()+ pub_jwk.update({"kid": "test-key", "alg": "RS256", "use": "sig"})++ access_token = "ya29.google-access-token"+ issuer = "https://accounts.google.com"+ now = int(time.time())+ id_token = jose_jwt.encode(+ {+ "iss": issuer,+ "aud": oidc_settings.oidc_client_id,+ "sub": "google-sub-123",+ "email": "[email protected]",+ "email_verified": True,+ "nonce": "nonce123",+ "iat": now,+ "exp": now + 600,+ },+ priv_jwk,+ algorithm="RS256",+ headers={"kid": "test-key"},+ access_token=access_token,+ )+ assert "at_hash" in jose_jwt.get_unverified_claims(id_token)++ class _Resp:+ def raise_for_status(self):+ return None++ def json(self):+ return {"keys": [pub_jwk]}++ class _FakeAsyncClient:+ def __init__(self, *a, **k):+ pass++ async def __aenter__(self):+ return self++ async def __aexit__(self, *a):+ return False++ async def get(self, url, **k):+ return _Resp()++ monkeypatch.setattr(oidc_auth.httpx, "AsyncClient", _FakeAsyncClient)++ discovery = {"jwks_uri": "https://accounts.google.com/jwks", "issuer": issuer}+ claims = await oidc_auth._decode_id_token(discovery, id_token, "nonce123", access_token)+ assert claims["sub"] == "google-sub-123"+ assert claims["email"] == "[email protected]"++@pytest.mark.asyncioasync def test_oidc_config_disabled_by_default(client: AsyncClient, clean_db):response = await client.get("/api/auth/oidc/config")@@ -102,7 +167,7 @@ async def test_oidc_callback_creates_user_and_redirects_with_securo_token(assert code == "abc"return {"id_token": "id-token", "access_token": "provider-token"}- async def fake_decode(discovery, id_token, nonce):+ async def fake_decode(discovery, id_token, nonce, access_token=""):assert id_token == "id-token"assert nonce == "nonce123"return {"sub": "user-sub", "email": "[email protected]", "email_verified": True, "name": "OIDC User"}@@ -157,7 +222,7 @@ async def test_oidc_callback_syncs_existing_user_admin_and_workspace_role(async def fake_exchange(discovery, code, code_verifier=""):return {"id_token": "id-token", "access_token": "provider-token"}- async def fake_decode(discovery, id_token, nonce):+ async def fake_decode(discovery, id_token, nonce, access_token=""):return {"sub": "user-sub","email": "[email protected]",@@ -214,7 +279,7 @@ async def test_oidc_callback_sync_roles_can_revoke_admin(async def fake_exchange(discovery, code, code_verifier=""):return {"id_token": "id-token", "access_token": "provider-token"}- async def fake_decode(discovery, id_token, nonce):+ async def fake_decode(discovery, id_token, nonce, access_token=""):return {"sub": "user-sub","email": "[email protected]",@@ -258,7 +323,7 @@ async def test_oidc_callback_signed_claims_override_userinfo_roles(async def fake_exchange(discovery, code, code_verifier=""):return {"id_token": "id-token", "access_token": "provider-token"}- async def fake_decode(discovery, id_token, nonce):+ async def fake_decode(discovery, id_token, nonce, access_token=""):return {"sub": "signed-sub","email": "[email protected]",@@ -306,7 +371,7 @@ async def test_oidc_callback_rejects_userinfo_subject_mismatch(async def fake_exchange(discovery, code, code_verifier=""):return {"id_token": "id-token", "access_token": "provider-token"}- async def fake_decode(discovery, id_token, nonce):+ async def fake_decode(discovery, id_token, nonce, access_token=""):return {"sub": "signed-sub", "email": "[email protected]", "email_verified": True}async def fake_userinfo(discovery, access_token):@@ -339,7 +404,7 @@ async def test_oidc_callback_requires_verified_email_claim_when_enabled(async def fake_exchange(discovery, code, code_verifier=""):return {"id_token": "id-token", "access_token": "provider-token"}- async def fake_decode(discovery, id_token, nonce):+ async def fake_decode(discovery, id_token, nonce, access_token=""):return {"sub": "signed-sub", "email": "[email protected]"}async def fake_userinfo(discovery, access_token):@@ -372,7 +437,7 @@ async def test_oidc_callback_rejects_unlinked_existing_user_by_default(async def fake_exchange(discovery, code, code_verifier=""):return {"id_token": "id-token", "access_token": "provider-token"}- async def fake_decode(discovery, id_token, nonce):+ async def fake_decode(discovery, id_token, nonce, access_token=""):return {"sub": "new-sub", "email": "[email protected]", "email_verified": True}async def fake_userinfo(discovery, access_token):@@ -407,7 +472,7 @@ async def test_oidc_callback_verified_email_link_mode_links_existing_user(async def fake_exchange(discovery, code, code_verifier=""):return {"id_token": "id-token", "access_token": "provider-token"}- async def fake_decode(discovery, id_token, nonce):+ async def fake_decode(discovery, id_token, nonce, access_token=""):return {"sub": "linked-sub", "email": "[email protected]", "email_verified": True}async def fake_userinfo(discovery, access_token):@@ -448,7 +513,7 @@ async def test_oidc_callback_rejects_existing_user_with_different_linked_subjectasync def fake_exchange(discovery, code, code_verifier=""):return {"id_token": "id-token", "access_token": "provider-token"}- async def fake_decode(discovery, id_token, nonce):+ async def fake_decode(discovery, id_token, nonce, access_token=""):return {"sub": "different-sub", "email": "[email protected]", "email_verified": True}async def fake_userinfo(discovery, access_token):@@ -486,7 +551,7 @@ async def test_oidc_callback_respects_disabled_registration_setting(async def fake_exchange(discovery, code, code_verifier=""):return {"id_token": "id-token", "access_token": "provider-token"}- async def fake_decode(discovery, id_token, nonce):+ async def fake_decode(discovery, id_token, nonce, access_token=""):return {"sub": "new-sub", "email": "[email protected]", "email_verified": True}async def fake_userinfo(discovery, access_token):@@ -521,7 +586,7 @@ async def test_oidc_callback_email_link_mode_links_existing_user_without_verifieasync def fake_exchange(discovery, code, code_verifier=""):return {"id_token": "id-token", "access_token": "provider-token"}- async def fake_decode(discovery, id_token, nonce):+ async def fake_decode(discovery, id_token, nonce, access_token=""):return {"sub": "unverified-linked-sub", "email": "[email protected]"}async def fake_userinfo(discovery, access_token):@@ -563,7 +628,7 @@ async def test_oidc_callback_linked_user_can_login_without_verified_email_when_rasync def fake_exchange(discovery, code, code_verifier=""):return {"id_token": "id-token", "access_token": "provider-token"}- async def fake_decode(discovery, id_token, nonce):+ async def fake_decode(discovery, id_token, nonce, access_token=""):return {"sub": "linked-sub", "email": "[email protected]"}async def fake_userinfo(discovery, access_token):@@ -601,7 +666,7 @@ async def test_oidc_callback_linked_user_can_login_without_email_claim(async def fake_exchange(discovery, code, code_verifier=""):return {"id_token": "id-token", "access_token": "provider-token"}- async def fake_decode(discovery, id_token, nonce):+ async def fake_decode(discovery, id_token, nonce, access_token=""):return {"sub": "linked-sub"}async def fake_userinfo(discovery, access_token):@@ -637,7 +702,7 @@ async def test_oidc_callback_registration_disabled_does_not_block_existing_emailasync def fake_exchange(discovery, code, code_verifier=""):return {"id_token": "id-token", "access_token": "provider-token"}- async def fake_decode(discovery, id_token, nonce):+ async def fake_decode(discovery, id_token, nonce, access_token=""):return {"sub": "linked-with-registration-disabled", "email": "[email protected]"}async def fake_userinfo(discovery, access_token):