From 8d991cbe21e3f13695aa95f431a954a5ba4f1e21 Mon Sep 17 00:00:00 2001 From: Stuart Anderson Date: Wed, 23 Sep 2026 20:20:07 -0500 Subject: [PATCH 1/4] fix(auth): redirect instead of 500 when the OIDC callback is rejected Fixes #4557 --- backend/endpoints/auth.py | 10 ++++-- backend/tests/endpoints/test_identity.py | 42 ++++++++++++++++++++++++ 2 files changed, 50 insertions(+), 2 deletions(-) diff --git a/backend/endpoints/auth.py b/backend/endpoints/auth.py index b0c16ae3c..07f1559bf 100644 --- a/backend/endpoints/auth.py +++ b/backend/endpoints/auth.py @@ -2,6 +2,7 @@ from datetime import datetime, timedelta, timezone from typing import Annotated, Optional from urllib.parse import urlencode +from authlib.integrations.starlette_client import OAuthError from fastapi import BackgroundTasks, Body, Depends, HTTPException, Request, status from fastapi.responses import RedirectResponse from fastapi.security.http import HTTPBasic @@ -278,7 +279,8 @@ async def auth_openid(request: Request): UserDisabledException: Auth is disabled Returns: - RedirectResponse: Redirect to home page + RedirectResponse: Redirect to home page, or back to login when the + provider's response is rejected (e.g. a replayed, already-spent state) """ if not OIDC_ENABLED: @@ -287,7 +289,11 @@ async def auth_openid(request: Request): if not oauth.openid: raise OIDCNotConfiguredException - token = await oauth.openid.authorize_access_token(request) + try: + token = await oauth.openid.authorize_access_token(request) + except OAuthError as exc: + log.warning(f"OIDC callback rejected: {exc.error}: {exc.description}") + return RedirectResponse(url="/" if request.user.is_authenticated else "/login") potential_user, _userinfo = ( await oidc_handler.get_current_active_user_from_openid_token(token) ) diff --git a/backend/tests/endpoints/test_identity.py b/backend/tests/endpoints/test_identity.py index 8d20b3d27..8f03e1f1e 100644 --- a/backend/tests/endpoints/test_identity.py +++ b/backend/tests/endpoints/test_identity.py @@ -7,6 +7,7 @@ from typing import Any from unittest import mock import pytest +from authlib.integrations.base_client.errors import MismatchingStateError from fastapi import status from config import OAUTH_ACCESS_TOKEN_EXPIRE_SECONDS @@ -720,6 +721,47 @@ async def test_logout_with_oidc_rp_initiated_logout(client, admin_user: User): assert f"id_token_hint={fake_id_token}" in data["oidc_logout_url"] +def _replayed_oidc_callback(client, headers: dict[str, str] | None = None): + fake_oauth = mock.MagicMock() + fake_oauth.openid.authorize_access_token = mock.AsyncMock( + side_effect=MismatchingStateError() + ) + with ( + mock.patch("endpoints.auth.OIDC_ENABLED", True), + mock.patch("endpoints.auth.oauth", fake_oauth), + ): + return client.get( + "/api/oauth/openid?code=new&state=spent", + headers=headers, + follow_redirects=False, + ) + + +def test_oidc_callback_with_spent_state_redirects_to_login(client): + response = _replayed_oidc_callback(client) + + assert response.status_code == HTTPStatus.TEMPORARY_REDIRECT + assert response.headers["location"] == "/login" + + +def test_oidc_callback_with_spent_state_keeps_existing_session( + client, admin_user: User +): + basic_auth = base64.b64encode(b"test_admin:test_admin_password").decode("ascii") + response = client.post( + "/api/login", headers={"Authorization": f"Basic {basic_auth}"} + ) + session_cookie = response.cookies.get("romm_session") + assert session_cookie is not None + + response = _replayed_oidc_callback( + client, headers={"Cookie": f"romm_session={session_cookie}"} + ) + + assert response.status_code == HTTPStatus.TEMPORARY_REDIRECT + assert response.headers["location"] == "/" + + def test_update_user_with_valid_ui_settings( client, access_token: str, editor_user: User ): From b658f2fe23832f6137d27abe2b796113b1c80cce Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Thu, 24 Sep 2026 17:43:19 -0400 Subject: [PATCH 2/4] fix(auth): harden the OIDC callback rejection path (pr-ready: code-review) - Catch AuthlibBaseError so rejected id_tokens (JoseError) redirect too - Redirect to /login?bypass_autologin=true to avoid an autologin loop, and honor the flag on the v2 login page like v1 does - Treat the kiosk guest as signed out on failure - Log the provider-supplied error fields with repr() - Cover provider errors, id_token errors, kiosk mode, and session survival Co-Authored-By: Claude Opus 5.5 (1M context) --- backend/endpoints/auth.py | 13 +++++--- backend/tests/endpoints/test_identity.py | 42 +++++++++++++++++++----- frontend/src/v2/views/Auth/Login.vue | 5 ++- 3 files changed, 46 insertions(+), 14 deletions(-) diff --git a/backend/endpoints/auth.py b/backend/endpoints/auth.py index 07f1559bf..a03a93e2b 100644 --- a/backend/endpoints/auth.py +++ b/backend/endpoints/auth.py @@ -2,7 +2,7 @@ from datetime import datetime, timedelta, timezone from typing import Annotated, Optional from urllib.parse import urlencode -from authlib.integrations.starlette_client import OAuthError +from authlib.common.errors import AuthlibBaseError from fastapi import BackgroundTasks, Body, Depends, HTTPException, Request, status from fastapi.responses import RedirectResponse from fastapi.security.http import HTTPBasic @@ -291,9 +291,14 @@ async def auth_openid(request: Request): try: token = await oauth.openid.authorize_access_token(request) - except OAuthError as exc: - log.warning(f"OIDC callback rejected: {exc.error}: {exc.description}") - return RedirectResponse(url="/" if request.user.is_authenticated else "/login") + except AuthlibBaseError as exc: + # repr() because error and description can come from the query string + log.warning(f"OIDC callback rejected: {exc.error!r}: {exc.description!r}") + if request.user.is_authenticated and not request.user.is_kiosk_guest: + return RedirectResponse(url="/") + # Without the bypass, OIDC autologin would send a persistent failure + # straight back to the provider and loop + return RedirectResponse(url="/login?bypass_autologin=true") potential_user, _userinfo = ( await oidc_handler.get_current_active_user_from_openid_token(token) ) diff --git a/backend/tests/endpoints/test_identity.py b/backend/tests/endpoints/test_identity.py index 8f03e1f1e..ccf45c3ee 100644 --- a/backend/tests/endpoints/test_identity.py +++ b/backend/tests/endpoints/test_identity.py @@ -7,7 +7,8 @@ from typing import Any from unittest import mock import pytest -from authlib.integrations.base_client.errors import MismatchingStateError +from authlib.integrations.base_client.errors import MismatchingStateError, OAuthError +from authlib.jose.errors import InvalidClaimError from fastapi import status from config import OAUTH_ACCESS_TOKEN_EXPIRE_SECONDS @@ -721,10 +722,14 @@ async def test_logout_with_oidc_rp_initiated_logout(client, admin_user: User): assert f"id_token_hint={fake_id_token}" in data["oidc_logout_url"] -def _replayed_oidc_callback(client, headers: dict[str, str] | None = None): +def _rejected_oidc_callback( + client, + error: Exception | None = None, + headers: dict[str, str] | None = None, +): fake_oauth = mock.MagicMock() fake_oauth.openid.authorize_access_token = mock.AsyncMock( - side_effect=MismatchingStateError() + side_effect=error or MismatchingStateError() ) with ( mock.patch("endpoints.auth.OIDC_ENABLED", True), @@ -737,11 +742,28 @@ def _replayed_oidc_callback(client, headers: dict[str, str] | None = None): ) -def test_oidc_callback_with_spent_state_redirects_to_login(client): - response = _replayed_oidc_callback(client) +@pytest.mark.parametrize( + "error", + [ + MismatchingStateError(), + OAuthError(error="access_denied"), + InvalidClaimError("nonce"), + ], + ids=["spent_state", "provider_error", "invalid_id_token"], +) +def test_oidc_callback_rejected_redirects_to_login(client, error: Exception): + response = _rejected_oidc_callback(client, error) assert response.status_code == HTTPStatus.TEMPORARY_REDIRECT - assert response.headers["location"] == "/login" + assert response.headers["location"] == "/login?bypass_autologin=true" + + +def test_oidc_callback_rejected_in_kiosk_mode_redirects_to_login(client): + with mock.patch("handler.auth.hybrid_auth.KIOSK_MODE", True): + response = _rejected_oidc_callback(client) + + assert response.status_code == HTTPStatus.TEMPORARY_REDIRECT + assert response.headers["location"] == "/login?bypass_autologin=true" def test_oidc_callback_with_spent_state_keeps_existing_session( @@ -753,13 +775,15 @@ def test_oidc_callback_with_spent_state_keeps_existing_session( ) session_cookie = response.cookies.get("romm_session") assert session_cookie is not None + cookie_header = {"Cookie": f"romm_session={session_cookie}"} - response = _replayed_oidc_callback( - client, headers={"Cookie": f"romm_session={session_cookie}"} - ) + response = _rejected_oidc_callback(client, headers=cookie_header) assert response.status_code == HTTPStatus.TEMPORARY_REDIRECT assert response.headers["location"] == "/" + assert client.get("/api/users/me", headers=cookie_header).status_code == ( + status.HTTP_200_OK + ) def test_update_user_with_valid_ui_settings( diff --git a/frontend/src/v2/views/Auth/Login.vue b/frontend/src/v2/views/Auth/Login.vue index a2588d8b3..16345e1e3 100644 --- a/frontend/src/v2/views/Auth/Login.vue +++ b/frontend/src/v2/views/Auth/Login.vue @@ -5,6 +5,7 @@ // "forgot password". import { RDivider, RExpandTransition } from "@v2/lib"; import { onMounted, ref } from "vue"; +import { useRoute } from "vue-router"; import storeHeartbeat from "@/stores/heartbeat"; import LoginForm from "@/v2/components/Auth/LoginForm.vue"; import OIDCButton from "@/v2/components/Auth/OIDCButton.vue"; @@ -12,6 +13,7 @@ import ResetForm from "@/v2/components/Auth/ResetForm.vue"; import AuthCard from "@/v2/components/shared/AuthCard.vue"; const heartbeatStore = storeHeartbeat(); +const route = useRoute(); const { OIDC: { @@ -27,7 +29,8 @@ const loginFormRef = ref | null>(null); const oidcButtonRef = ref | null>(null); onMounted(() => { - if (oidcEnabled && oidcAutologin) { + const bypassAutologin = route.query.bypass_autologin === "true"; + if (oidcEnabled && oidcAutologin && !bypassAutologin) { oidcButtonRef.value?.login(); } }); From 3a63f5c5c324a434a31683ac67f0e43c2487a75a Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Thu, 24 Sep 2026 17:45:14 -0400 Subject: [PATCH 3/4] refactor(auth): tighten OIDC callback docstring and reuse cookie constant (pr-ready: simplify) Co-Authored-By: Claude Opus 5.5 (1M context) --- backend/endpoints/auth.py | 3 +-- backend/tests/endpoints/test_identity.py | 5 +++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/backend/endpoints/auth.py b/backend/endpoints/auth.py index a03a93e2b..bf3183145 100644 --- a/backend/endpoints/auth.py +++ b/backend/endpoints/auth.py @@ -279,8 +279,7 @@ async def auth_openid(request: Request): UserDisabledException: Auth is disabled Returns: - RedirectResponse: Redirect to home page, or back to login when the - provider's response is rejected (e.g. a replayed, already-spent state) + RedirectResponse: Redirect to home, or to login if the provider rejects """ if not OIDC_ENABLED: diff --git a/backend/tests/endpoints/test_identity.py b/backend/tests/endpoints/test_identity.py index ccf45c3ee..a3695173c 100644 --- a/backend/tests/endpoints/test_identity.py +++ b/backend/tests/endpoints/test_identity.py @@ -15,6 +15,7 @@ from config import OAUTH_ACCESS_TOKEN_EXPIRE_SECONDS from handler.auth import auth_handler from handler.auth import base_handler as auth_handler_module from handler.auth import oauth_handler +from handler.auth.constants import SESSION_COOKIE_NAME from handler.auth.middleware.redis_session_middleware import RedisSessionMiddleware from handler.database import db_notification_handler from handler.database.users_handler import DBUsersHandler @@ -773,9 +774,9 @@ def test_oidc_callback_with_spent_state_keeps_existing_session( response = client.post( "/api/login", headers={"Authorization": f"Basic {basic_auth}"} ) - session_cookie = response.cookies.get("romm_session") + session_cookie = response.cookies.get(SESSION_COOKIE_NAME) assert session_cookie is not None - cookie_header = {"Cookie": f"romm_session={session_cookie}"} + cookie_header = {"Cookie": f"{SESSION_COOKIE_NAME}={session_cookie}"} response = _rejected_oidc_callback(client, headers=cookie_header) From f41f412fbb4ed5dfc9dc91fe3b52f179b92f832d Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Thu, 24 Sep 2026 18:38:35 -0400 Subject: [PATCH 4/4] test(auth): type the OIDC callback test client (address Greptile review) Co-Authored-By: Claude Opus 5.5 (1M context) --- backend/tests/endpoints/test_identity.py | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/backend/tests/endpoints/test_identity.py b/backend/tests/endpoints/test_identity.py index a3695173c..db0c8c057 100644 --- a/backend/tests/endpoints/test_identity.py +++ b/backend/tests/endpoints/test_identity.py @@ -6,10 +6,12 @@ from http import HTTPStatus from typing import Any from unittest import mock +import httpx import pytest from authlib.integrations.base_client.errors import MismatchingStateError, OAuthError from authlib.jose.errors import InvalidClaimError from fastapi import status +from fastapi.testclient import TestClient from config import OAUTH_ACCESS_TOKEN_EXPIRE_SECONDS from handler.auth import auth_handler @@ -724,10 +726,10 @@ async def test_logout_with_oidc_rp_initiated_logout(client, admin_user: User): def _rejected_oidc_callback( - client, + client: TestClient, error: Exception | None = None, headers: dict[str, str] | None = None, -): +) -> httpx.Response: fake_oauth = mock.MagicMock() fake_oauth.openid.authorize_access_token = mock.AsyncMock( side_effect=error or MismatchingStateError() @@ -752,14 +754,18 @@ def _rejected_oidc_callback( ], ids=["spent_state", "provider_error", "invalid_id_token"], ) -def test_oidc_callback_rejected_redirects_to_login(client, error: Exception): +def test_oidc_callback_rejected_redirects_to_login( + client: TestClient, error: Exception +): response = _rejected_oidc_callback(client, error) assert response.status_code == HTTPStatus.TEMPORARY_REDIRECT assert response.headers["location"] == "/login?bypass_autologin=true" -def test_oidc_callback_rejected_in_kiosk_mode_redirects_to_login(client): +def test_oidc_callback_rejected_in_kiosk_mode_redirects_to_login( + client: TestClient, +): with mock.patch("handler.auth.hybrid_auth.KIOSK_MODE", True): response = _rejected_oidc_callback(client) @@ -768,7 +774,7 @@ def test_oidc_callback_rejected_in_kiosk_mode_redirects_to_login(client): def test_oidc_callback_with_spent_state_keeps_existing_session( - client, admin_user: User + client: TestClient, admin_user: User ): basic_auth = base64.b64encode(b"test_admin:test_admin_password").decode("ascii") response = client.post(