mirror of
https://github.com/rommapp/romm.git
synced 2026-11-28 17:48:31 +01:00
* feat(auth): use the OIDC picture claim as the user's avatar On each OIDC sign-in, a user with no avatar, or one synced from the provider earlier, gets the picture claim stored as their avatar. An uploaded avatar is never replaced. The download goes through the SSRF-guarded client (the configured provider's origin may reach a LAN address), is capped at 5 MB, must sniff as a supported image, and any failure is logged without blocking the sign-in. Closes #4297 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(auth): address review on the OIDC avatar sync Addresses Greptile's review on #5730: - ask the UserInfo endpoint when the ID token has no picture claim - keep an avatar uploaded while the picture downloaded - allow only the OIDC provider's origins to reach private addresses - trim docstrings and narrow await_args in the callback test Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(auth): type the OIDC avatar test helpers for mypy Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * pr-ready: code-review Bound the OIDC picture download with an overall deadline, trust the OIDC CA bundle, catch hostname encoding errors so sign-in never 500s, and set the synced avatar with a conditional update so a concurrent upload wins. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * pr-ready: simplify Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * pr-ready: review-polish Type the pytest fixtures and helpers in the OIDC avatar tests. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * pr-ready: prose Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(auth): remove the synced OIDC avatar when the user uploads one Once avatar_path points at the uploaded avatar.<ext>, the sync never touches the user's avatar again, so the old oidc-avatar.<ext> file would otherwise stay on disk for good. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
308 lines
11 KiB
Python
308 lines
11 KiB
Python
import base64
|
|
import time
|
|
from http import HTTPStatus
|
|
from typing import Any
|
|
from unittest import mock
|
|
|
|
import httpx2
|
|
import pytest
|
|
from fastapi import status
|
|
from fastapi.testclient import TestClient
|
|
from joserfc import jwt
|
|
from joserfc.jwk import OctKey
|
|
from tests.audit_events import recorded_events
|
|
|
|
from handler.auth import base_handler as auth_handler_module
|
|
from handler.auth.base_handler import auth_handler, oauth_handler, oidc_handler
|
|
from handler.auth.constants import ALGORITHM, SESSION_COOKIE_NAME
|
|
from handler.database import db_user_handler
|
|
from handler.redis_handler import redis_client
|
|
from models.user import User
|
|
|
|
|
|
def _basic(username: str, password: str) -> dict[str, str]:
|
|
encoded = base64.b64encode(f"{username}:{password}".encode()).decode()
|
|
return {"Authorization": f"Basic {encoded}"}
|
|
|
|
|
|
def _reset_password(client, token: str, new_password: str = "a_new_password"):
|
|
return client.post(
|
|
"/api/reset-password", json={"token": token, "new_password": new_password}
|
|
)
|
|
|
|
|
|
def test_reset_password_with_a_valid_token(client, admin_user: User):
|
|
token = auth_handler.generate_password_reset_token(admin_user)
|
|
|
|
response = _reset_password(client, token)
|
|
|
|
assert response.status_code == status.HTTP_200_OK
|
|
old = client.post("/api/login", headers=_basic("test_admin", "test_admin_password"))
|
|
new = client.post("/api/login", headers=_basic("test_admin", "a_new_password"))
|
|
assert old.status_code == status.HTTP_401_UNAUTHORIZED
|
|
assert new.status_code == status.HTTP_200_OK
|
|
assert "auth.password_reset" in [event.action for event in recorded_events()]
|
|
|
|
|
|
def test_reset_password_token_works_once(client, admin_user: User):
|
|
token = auth_handler.generate_password_reset_token(admin_user)
|
|
assert _reset_password(client, token).status_code == status.HTTP_200_OK
|
|
|
|
response = _reset_password(client, token, "another_password")
|
|
|
|
assert response.status_code == status.HTTP_400_BAD_REQUEST
|
|
assert client.post(
|
|
"/api/login", headers=_basic("test_admin", "another_password")
|
|
).status_code == (status.HTTP_401_UNAUTHORIZED)
|
|
|
|
|
|
@pytest.mark.parametrize("new_password", ["", "short", "pässword"])
|
|
def test_reset_password_rejects_an_invalid_password_and_keeps_the_link(
|
|
client, admin_user: User, new_password: str
|
|
):
|
|
token = auth_handler.generate_password_reset_token(admin_user)
|
|
|
|
response = _reset_password(client, token, new_password)
|
|
|
|
assert response.status_code == status.HTTP_400_BAD_REQUEST
|
|
assert client.post(
|
|
"/api/login", headers=_basic("test_admin", "test_admin_password")
|
|
).status_code == (status.HTTP_200_OK)
|
|
assert _reset_password(client, token).status_code == status.HTTP_200_OK
|
|
|
|
|
|
def test_reset_password_rejects_a_malformed_token(client):
|
|
assert _reset_password(client, "not-a-jwt").status_code == (
|
|
status.HTTP_400_BAD_REQUEST
|
|
)
|
|
|
|
|
|
def test_reset_password_rejects_a_token_signed_with_another_key(
|
|
client, admin_user: User
|
|
):
|
|
forged = jwt.encode(
|
|
{"alg": ALGORITHM},
|
|
{"sub": admin_user.username, "type": "reset", "jti": "forged"},
|
|
OctKey.import_key("not-the-server-secret-key-not-the-server"),
|
|
)
|
|
redis_client.set("reset-jti:forged", "valid", ex=60)
|
|
|
|
assert _reset_password(client, forged).status_code == (status.HTTP_400_BAD_REQUEST)
|
|
|
|
|
|
def test_reset_password_rejects_a_token_for_another_purpose(client, admin_user: User):
|
|
invite = jwt.encode(
|
|
{"alg": ALGORITHM},
|
|
{
|
|
"sub": admin_user.username,
|
|
"type": "invite",
|
|
"jti": "invite",
|
|
"exp": int(time.time()) + 60,
|
|
},
|
|
auth_handler_module.oct_key,
|
|
)
|
|
redis_client.set("reset-jti:invite", "valid", ex=60)
|
|
|
|
response = _reset_password(client, invite)
|
|
|
|
assert response.status_code == status.HTTP_400_BAD_REQUEST
|
|
assert response.json()["detail"] == "Invalid token purpose"
|
|
|
|
|
|
def test_reset_password_rejects_an_expired_token(client, admin_user: User):
|
|
expired = jwt.encode(
|
|
{"alg": ALGORITHM},
|
|
{
|
|
"sub": admin_user.username,
|
|
"type": "reset",
|
|
"jti": "expired",
|
|
"exp": int(time.time()) - 1,
|
|
},
|
|
auth_handler_module.oct_key,
|
|
)
|
|
redis_client.set("reset-jti:expired", "valid", ex=60)
|
|
|
|
response = _reset_password(client, expired)
|
|
|
|
assert response.status_code == status.HTTP_400_BAD_REQUEST
|
|
assert response.json()["detail"] == "Token has expired"
|
|
|
|
|
|
def test_reset_password_revokes_oauth_tokens(client, admin_user: User):
|
|
old = client.post(
|
|
"/api/token",
|
|
data={
|
|
"grant_type": "password",
|
|
"username": "test_admin",
|
|
"password": "test_admin_password",
|
|
"scope": "me.read",
|
|
},
|
|
).json()
|
|
|
|
token = auth_handler.generate_password_reset_token(admin_user)
|
|
assert _reset_password(client, token).status_code == status.HTTP_200_OK
|
|
|
|
response = client.get(
|
|
"/api/users/me", headers={"Authorization": f"Bearer {old['access_token']}"}
|
|
)
|
|
assert response.status_code == status.HTTP_401_UNAUTHORIZED
|
|
response = client.post(
|
|
"/api/token",
|
|
data={"grant_type": "refresh_token", "refresh_token": old["refresh_token"]},
|
|
)
|
|
assert response.status_code == status.HTTP_401_UNAUTHORIZED
|
|
|
|
|
|
def test_a_revocation_during_the_password_check_covers_the_login(
|
|
client, admin_user: User
|
|
):
|
|
check = auth_handler.authenticate_user
|
|
|
|
def check_then_revoke(username: str, password: str) -> User | None:
|
|
user = check(username, password)
|
|
# The password changes while this login's check is still in flight.
|
|
oauth_handler.revoke_user_tokens(username)
|
|
return user
|
|
|
|
with mock.patch.object(
|
|
auth_handler, "authenticate_user", side_effect=check_then_revoke
|
|
):
|
|
tokens = client.post(
|
|
"/api/token",
|
|
data={
|
|
"grant_type": "password",
|
|
"username": "test_admin",
|
|
"password": "test_admin_password",
|
|
"scope": "me.read",
|
|
},
|
|
).json()
|
|
|
|
response = client.get(
|
|
"/api/users/me", headers={"Authorization": f"Bearer {tokens['access_token']}"}
|
|
)
|
|
assert response.status_code == status.HTTP_401_UNAUTHORIZED
|
|
response = client.post(
|
|
"/api/token",
|
|
data={"grant_type": "refresh_token", "refresh_token": tokens["refresh_token"]},
|
|
)
|
|
assert response.status_code == status.HTTP_401_UNAUTHORIZED
|
|
|
|
|
|
def test_reset_password_for_a_deleted_user_is_not_found(client, viewer_user: User):
|
|
token = auth_handler.generate_password_reset_token(viewer_user)
|
|
db_user_handler.delete_user(viewer_user.id)
|
|
|
|
assert _reset_password(client, token).status_code == status.HTTP_404_NOT_FOUND
|
|
|
|
|
|
def _oidc_callback(
|
|
client: TestClient, user: User | None, userinfo: dict[str, Any] | None = None
|
|
) -> httpx2.Response:
|
|
fake_oauth = mock.MagicMock()
|
|
fake_oauth.openid.authorize_access_token = mock.AsyncMock(
|
|
return_value={"id_token": "provider-id-token"}
|
|
)
|
|
with (
|
|
mock.patch("endpoints.auth.OIDC_ENABLED", True),
|
|
mock.patch("endpoints.auth.OIDC_RP_INITIATED_LOGOUT", True),
|
|
mock.patch("endpoints.auth.oauth", fake_oauth),
|
|
mock.patch.object(
|
|
oidc_handler,
|
|
"get_current_active_user_from_openid_token",
|
|
mock.AsyncMock(return_value=(user, userinfo or {})),
|
|
),
|
|
):
|
|
return client.get("/api/oauth/openid?code=c&state=s", follow_redirects=False)
|
|
|
|
|
|
def test_oidc_callback_logs_the_user_in(client: TestClient, admin_user: User):
|
|
response = _oidc_callback(client, admin_user)
|
|
|
|
assert response.status_code == HTTPStatus.TEMPORARY_REDIRECT
|
|
assert response.headers["location"] == "/"
|
|
session_cookie = response.cookies.get(SESSION_COOKIE_NAME)
|
|
assert session_cookie is not None
|
|
cookie_header = {"Cookie": f"{SESSION_COOKIE_NAME}={session_cookie}"}
|
|
me = client.get("/api/users/me", headers=cookie_header)
|
|
assert me.status_code == status.HTTP_200_OK
|
|
assert me.json()["username"] == "test_admin"
|
|
|
|
updated = db_user_handler.get_user(admin_user.id)
|
|
assert updated and updated.last_login is not None
|
|
[event] = recorded_events()
|
|
assert (event.action, event.data["method"]) == ("auth.login", "oidc")
|
|
assert event.device_id is not None
|
|
|
|
with (
|
|
mock.patch("endpoints.auth.OIDC_RP_INITIATED_LOGOUT", True),
|
|
mock.patch(
|
|
"endpoints.auth.OIDC_END_SESSION_ENDPOINT", "https://idp.example/logout"
|
|
),
|
|
):
|
|
logout = client.post("/api/logout", headers=cookie_header)
|
|
assert "id_token_hint=provider-id-token" in logout.json()["oidc_logout_url"]
|
|
|
|
|
|
def test_oidc_callback_syncs_the_picture_claim(client: TestClient, admin_user: User):
|
|
userinfo = {"picture": "https://idp.example/me.png"}
|
|
with mock.patch("endpoints.auth.sync_oidc_avatar") as sync:
|
|
response = _oidc_callback(client, admin_user, userinfo)
|
|
|
|
assert response.status_code == HTTPStatus.TEMPORARY_REDIRECT
|
|
sync.assert_awaited_once()
|
|
await_args = sync.await_args
|
|
assert await_args is not None
|
|
assert await_args.args[1] == userinfo
|
|
|
|
|
|
def test_oidc_callback_for_an_unknown_user_is_unauthorized(client: TestClient):
|
|
response = _oidc_callback(client, None)
|
|
|
|
assert response.status_code == status.HTTP_401_UNAUTHORIZED
|
|
assert SESSION_COOKIE_NAME not in response.cookies
|
|
[event] = recorded_events()
|
|
assert (event.action, event.data["reason"]) == ("auth.login_failed", "credentials")
|
|
|
|
|
|
def test_oidc_callback_for_a_disabled_user_is_unauthorized(
|
|
client: TestClient, viewer_user: User
|
|
):
|
|
db_user_handler.update_user(viewer_user.id, {"enabled": False})
|
|
disabled = db_user_handler.get_user(viewer_user.id)
|
|
|
|
response = _oidc_callback(client, disabled)
|
|
|
|
assert response.status_code == status.HTTP_401_UNAUTHORIZED
|
|
assert SESSION_COOKIE_NAME not in response.cookies
|
|
[event] = recorded_events()
|
|
assert (event.action, event.data["reason"]) == ("auth.login_failed", "disabled")
|
|
|
|
|
|
def test_oidc_login_survives_an_unreachable_discovery_document(client: TestClient):
|
|
fake_oauth = mock.MagicMock()
|
|
fake_oauth.openid.authorize_redirect = mock.AsyncMock(
|
|
side_effect=httpx2.HTTPStatusError(
|
|
"404 Not Found",
|
|
request=httpx2.Request("GET", "https://idp.example/.well-known"),
|
|
response=httpx2.Response(404),
|
|
)
|
|
)
|
|
with (
|
|
mock.patch("endpoints.auth.OIDC_ENABLED", True),
|
|
mock.patch("endpoints.auth.oauth", fake_oauth),
|
|
):
|
|
response = client.get("/api/login/openid", follow_redirects=False)
|
|
|
|
# Same landing as a rejected callback: no 500, and no autologin loop
|
|
assert response.status_code == HTTPStatus.TEMPORARY_REDIRECT
|
|
assert response.headers["location"] == "/login?bypass_autologin=true"
|
|
|
|
|
|
@pytest.mark.parametrize("path", ["/api/login/openid", "/api/oauth/openid"])
|
|
def test_oidc_endpoints_refuse_when_oidc_is_disabled(client: TestClient, path: str):
|
|
with mock.patch("endpoints.auth.OIDC_ENABLED", False):
|
|
response = client.get(path, follow_redirects=False)
|
|
|
|
assert response.status_code == status.HTTP_500_INTERNAL_SERVER_ERROR
|
|
assert response.json()["detail"] == "OAuth disabled"
|