mirror of
https://github.com/rommapp/romm.git
synced 2026-12-05 05:07:31 +01:00
Merge pull request #4746 from andest01/fix/oidc-stale-state-redirect
fix(auth): redirect instead of 500 when the OIDC callback is rejected
This commit is contained in:
@@ -2,6 +2,7 @@ from datetime import datetime, timedelta, timezone
|
||||
from typing import Annotated, Final, Literal, Optional
|
||||
from urllib.parse import urlencode
|
||||
|
||||
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
|
||||
@@ -362,7 +363,7 @@ async def auth_openid(request: Request):
|
||||
UserDisabledException: Auth is disabled
|
||||
|
||||
Returns:
|
||||
RedirectResponse: Redirect to home page
|
||||
RedirectResponse: Redirect to home, or to login if the provider rejects
|
||||
"""
|
||||
|
||||
if not OIDC_ENABLED:
|
||||
@@ -371,7 +372,16 @@ 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 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)
|
||||
)
|
||||
|
||||
@@ -6,13 +6,18 @@ 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
|
||||
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
|
||||
@@ -720,6 +725,74 @@ 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 _rejected_oidc_callback(
|
||||
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()
|
||||
)
|
||||
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,
|
||||
)
|
||||
|
||||
|
||||
@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: 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: TestClient,
|
||||
):
|
||||
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(
|
||||
client: TestClient, 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(SESSION_COOKIE_NAME)
|
||||
assert session_cookie is not None
|
||||
cookie_header = {"Cookie": f"{SESSION_COOKIE_NAME}={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(
|
||||
client, access_token: str, editor_user: User
|
||||
):
|
||||
|
||||
@@ -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<InstanceType<typeof LoginForm> | null>(null);
|
||||
const oidcButtonRef = ref<InstanceType<typeof OIDCButton> | null>(null);
|
||||
|
||||
onMounted(() => {
|
||||
if (oidcEnabled && oidcAutologin) {
|
||||
const bypassAutologin = route.query.bypass_autologin === "true";
|
||||
if (oidcEnabled && oidcAutologin && !bypassAutologin) {
|
||||
oidcButtonRef.value?.login();
|
||||
}
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user