Files
romm/backend/tests/handler/auth/test_auth.py
Georges-Antoine Assi 75e8a9efae fix(sync): keep RetroArch Cloud Sync from stalling the event loop (#5171)
* fix(sync): keep RetroArch Cloud Sync from stalling the event loop

Basic auth ran its bcrypt check (~250ms) on the event loop for every
WebDAV request, and the manifest ran its queries there too, so parallel
RetroArch requests queued behind each other. Both now run in a thread.

Cloud Sync resolves every save and state to a ROM by fs_name_no_ext,
which no index led with; 0149 adds one so unmatched uploads fail fast.

The upload dialog now offers a core for saves as well as states, so a
manually uploaded save lands in the core folder RetroArch reads, and its
slot hint says only unslotted saves reach RetroArch.

Refs #5158

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* test(sync): cover manifest queries running off the event loop

Addresses Greptile review on #5171: trim the 0149 migration docstring to
its summary, annotate the new MockConnection constructor, and add
regression tests that build_manifest and list_manifest_paths query from a
worker thread.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(auth): mark Basic-auth users active off the event loop

pr-ready step 2 (code-review): run the user lookup, password check and
set_last_active in one worker-thread hop, and test that SaveDataTab offers
save cores and forwards the picked core on upload.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* test(v2): build SaveDataTab test saves and states from shared fixtures

pr-ready step 3 (simplify): replace the hand-cast UserSaveSchema and
UserStateSchema stubs with saveFixture/stateFixture plus toUserSave/toUserState.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* chore(sync): drop restating index comment and type the test spy

pr-ready step 4 (review-polish): remove the comment that only restated
idx_roms_fs_name_no_ext, and type the manifest test's get_saves spy so mypy
passes across the backend.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(auth): check the password grant's credentials off the event loop

The OAuth password grant ran bcrypt (~250ms) on the event loop, stalling
every other request the worker was serving.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(sync): run RetroArch WebDAV database work off the event loop

GET, PUT, DELETE and PROPFIND resolved ROMs, looked up and wrote save,
state and screenshot rows, and listed whole platforms synchronously inside
async handlers; the PSP bundle helpers did the same. Each now runs that
work in a worker thread.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(saves): keep another core's same-named save on upload

A slot-less upload matched an existing save by file name alone, so
uploading game.srm for a second core rewrote the first core's row to the
new folder and deleted its file. The lookup now only matches a save made
with the requested core. Clients that send no core still match any, so
device conflict detection is unchanged, preferring a save filed under no
core.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* feat(v2): file a save picked with a core out of the slots

RetroArch Cloud Sync only lists unslotted saves, so picking a core in the
upload dialog moves an untouched slot from autosave to "No slot", and
clearing the core moves it back. A slot the user picked is kept.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* revert(i18n): restore the original upload slot hint

Picking a core now files a save out of the slots, so the hint no longer
needs to explain RetroArch Cloud Sync.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-07 14:37:36 -04:00

414 lines
13 KiB
Python

import threading
from base64 import b64encode
from datetime import timedelta
from typing import Any
import pytest
from fastapi import status
from fastapi.exceptions import HTTPException
from starlette.datastructures import Headers
from starlette.requests import HTTPConnection
from tests.factories import make_device_token
from config import OAUTH_REFRESH_TOKEN_EXPIRE_SECONDS
from handler.auth.base_handler import auth_handler, oauth_handler
from handler.auth.constants import EDIT_SCOPES
from handler.auth.hybrid_auth import HybridAuthBackend
from handler.database import (
db_device_handler,
db_user_handler,
)
from models.device import Device
from models.user import User
def test_verify_password():
assert auth_handler.verify_password(
"password", auth_handler.get_password_hash("password")
)
assert not auth_handler.verify_password(
"password", auth_handler.get_password_hash("notpassword")
)
# OIDC-provisioned accounts hold a placeholder instead of a bcrypt hash;
# it has to fail the check rather than raise.
assert not auth_handler.verify_password(
"password", "3f2b1c7e-0c1d-4f5a-9a2b-8e7d6c5b4a39"
)
assert not auth_handler.verify_password("password", None)
def test_verify_password_long_secret():
long_password = "x" * 100
assert auth_handler.verify_password(
long_password, auth_handler.get_password_hash(long_password)
)
@pytest.mark.parametrize(
"password, legacy_hash",
[
(
"password",
"$2b$12$LMZZK1kiutIELMOo4/fpOeljO2j6NrutGrLk72/mJQfhueGMPCi/O",
),
(
"x" * 100,
"$2b$12$6PshUF896mGxuAeJyKdlVewsFCgOlduOYYHWQo.VtTvXtuw.4tbou",
),
],
)
def test_verify_password_passlib_hash(password: str, legacy_hash: str):
"""Hashes stored by passlib 1.7 with bcrypt 4 keep verifying."""
assert auth_handler.verify_password(password, legacy_hash)
assert not auth_handler.verify_password("wrong", legacy_hash)
def test_authenticate_user(admin_user: User):
current_user = auth_handler.authenticate_user("test_admin", "test_admin_password")
assert current_user
assert current_user.id == admin_user.id
async def test_get_current_active_user_from_session(editor_user: User):
class MockConnection(HTTPConnection):
def __init__(self):
self.scope: dict[str, dict[str, Any]] = {"session": {}}
self.scope["session"] = {"iss": "romm:auth", "sub": editor_user.username}
conn = MockConnection()
current_user = await auth_handler.get_current_active_user_from_session(conn)
assert current_user
assert isinstance(current_user, User)
assert current_user.id == editor_user.id
async def test_get_current_active_user_from_session_bad_username(editor_user: User):
class MockConnection(HTTPConnection):
def __init__(self):
self.scope: dict[str, dict[str, Any]] = {"session": {}}
self.scope["session"] = {"iss": "romm:auth", "sub": "not_real_username"}
conn = MockConnection()
try:
await auth_handler.get_current_active_user_from_session(conn)
except HTTPException as e:
assert e.status_code == status.HTTP_403_FORBIDDEN
assert e.detail == "User not found"
async def test_get_current_active_user_from_session_disabled_user(editor_user: User):
class MockConnection(HTTPConnection):
def __init__(self):
self.scope: dict[str, dict[str, Any]] = {"session": {}}
self.scope["session"] = {"iss": "romm:auth", "sub": editor_user.username}
self._headers = Headers()
conn = MockConnection()
db_user_handler.update_user(editor_user.id, {"enabled": False})
try:
await auth_handler.get_current_active_user_from_session(conn)
except HTTPException as e:
assert e.status_code == status.HTTP_403_FORBIDDEN
assert e.detail == "Inactive user test_editor"
async def test_hybrid_auth_backend_session(editor_user: User):
class MockConnection(HTTPConnection):
def __init__(self):
self.scope: dict[str, dict[str, Any]] = {"session": {}}
self.scope["session"] = {"iss": "romm:auth", "sub": editor_user.username}
backend = HybridAuthBackend()
conn = MockConnection()
result = await backend.authenticate(conn)
assert result is not None
creds, user = result
assert user.id == editor_user.id
assert creds.scopes == editor_user.oauth_scopes
assert creds.scopes == EDIT_SCOPES
async def test_hybrid_auth_backend_empty_session_and_headers(editor_user: User):
class MockConnection(HTTPConnection):
def __init__(self):
self.scope: dict[str, dict[str, Any]] = {"session": {}}
self._headers = Headers()
backend = HybridAuthBackend()
conn = MockConnection()
result = await backend.authenticate(conn)
assert result is None
async def test_hybrid_auth_backend_bearer_auth_header(editor_user: User):
access_token = oauth_handler.create_access_token(
data={
"sub": editor_user.username,
"iss": "romm:oauth",
"scopes": " ".join(editor_user.oauth_scopes),
},
)
class MockConnection(HTTPConnection):
def __init__(self):
self.scope: dict[str, dict[str, Any]] = {"session": {}}
self._headers = Headers({"Authorization": f"Bearer {access_token}"})
backend = HybridAuthBackend()
conn = MockConnection()
result = await backend.authenticate(conn)
assert result is not None
creds, user = result
assert user.id == editor_user.id
assert set(creds.scopes).issubset(editor_user.oauth_scopes)
async def test_hybrid_auth_backend_bearer_invalid_token(editor_user: User):
class MockConnection(HTTPConnection):
def __init__(self):
self.scope: dict[str, dict[str, Any]] = {"session": {}}
self._headers = Headers({"Authorization": "Bearer invalid_token"})
backend = HybridAuthBackend()
conn = MockConnection()
result = await backend.authenticate(conn)
assert result is None
async def test_hybrid_auth_backend_bearer_expired_token(editor_user: User):
expired_token = oauth_handler.create_access_token(
data={
"sub": editor_user.username,
"iss": "romm:oauth",
"scopes": " ".join(editor_user.oauth_scopes),
},
expires_delta=timedelta(seconds=-1),
)
class MockConnection(HTTPConnection):
def __init__(self):
self.scope: dict[str, dict[str, Any]] = {"session": {}}
self._headers = Headers({"Authorization": f"Bearer {expired_token}"})
backend = HybridAuthBackend()
conn = MockConnection()
result = await backend.authenticate(conn)
assert result is None
async def test_hybrid_auth_backend_basic_auth_header(editor_user: User):
token = b64encode(b"test_editor:test_editor_password").decode()
class MockConnection(HTTPConnection):
def __init__(self):
self.scope: dict[str, dict[str, Any]] = {"session": {}}
self._headers = Headers({"Authorization": f"Basic {token}"})
backend = HybridAuthBackend()
conn = MockConnection()
result = await backend.authenticate(conn)
assert result is not None
creds, user = result
assert user.id == editor_user.id
assert creds.scopes == EDIT_SCOPES
assert set(creds.scopes).issubset(editor_user.oauth_scopes)
async def test_hybrid_auth_backend_basic_auth_runs_db_and_bcrypt_off_event_loop(
editor_user: User, monkeypatch: pytest.MonkeyPatch
):
token = b64encode(b"test_editor:test_editor_password").decode()
loop_thread = threading.get_ident()
check_threads: list[int] = []
active_threads: list[int] = []
verify_password = auth_handler.verify_password
set_last_active = User.set_last_active
def recording_verify_password(*args: Any) -> bool:
check_threads.append(threading.get_ident())
return verify_password(*args)
def recording_set_last_active(self: User) -> None:
active_threads.append(threading.get_ident())
set_last_active(self)
monkeypatch.setattr(auth_handler, "verify_password", recording_verify_password)
monkeypatch.setattr(User, "set_last_active", recording_set_last_active)
class MockConnection(HTTPConnection):
def __init__(self) -> None:
self.scope: dict[str, dict[str, Any]] = {"session": {}}
self._headers = Headers({"Authorization": f"Basic {token}"})
result = await HybridAuthBackend().authenticate(MockConnection())
assert result is not None
assert check_threads and loop_thread not in check_threads
assert active_threads and loop_thread not in active_threads
async def test_hybrid_auth_backend_basic_auth_header_unencoded(editor_user: User):
class MockConnection(HTTPConnection):
def __init__(self):
self.scope: dict[str, dict[str, Any]] = {"session": {}}
self._headers = Headers(
{"Authorization": "Basic test_editor:test_editor_password"}
)
backend = HybridAuthBackend()
conn = MockConnection()
result = await backend.authenticate(conn)
assert result is None
async def test_hybrid_auth_backend_invalid_scheme():
class MockConnection(HTTPConnection):
def __init__(self):
self.scope: dict[str, dict[str, Any]] = {"session": {}}
self._headers = Headers({"Authorization": "Some invalid_scheme"})
backend = HybridAuthBackend()
conn = MockConnection()
result = await backend.authenticate(conn)
assert result is None
@pytest.mark.parametrize("authorization_header", ["Bearer ", "Foo", "a b c"])
async def test_hybrid_auth_backend_malformed_authorization_header(
authorization_header: str,
):
class MockConnection(HTTPConnection):
def __init__(self):
self.scope: dict[str, dict[str, Any]] = {"session": {}}
self._headers = Headers({"Authorization": authorization_header})
backend = HybridAuthBackend()
conn = MockConnection()
result = await backend.authenticate(conn)
assert result is None
async def test_hybrid_auth_backend_with_refresh_token(editor_user: User):
refresh_token = oauth_handler.create_refresh_token(
data={
"sub": editor_user.username,
"iss": "romm:oauth",
"scopes": " ".join(editor_user.oauth_scopes),
},
expires_delta=timedelta(seconds=OAUTH_REFRESH_TOKEN_EXPIRE_SECONDS),
)
class MockConnection(HTTPConnection):
def __init__(self):
self.scope: dict[str, dict[str, Any]] = {"session": {}}
self._headers = Headers({"Authorization": f"Bearer {refresh_token}"})
backend = HybridAuthBackend()
conn = MockConnection()
result = await backend.authenticate(conn)
assert result is None
async def test_hybrid_auth_backend_scope_subset(editor_user: User):
scopes = editor_user.oauth_scopes[:3]
access_token = oauth_handler.create_access_token(
data={
"sub": editor_user.username,
"iss": "romm:oauth",
"scopes": " ".join(scopes),
},
)
class MockConnection(HTTPConnection):
def __init__(self):
self.scope: dict[str, dict[str, Any]] = {"session": {}}
self._headers = Headers({"Authorization": f"Bearer {access_token}"})
backend = HybridAuthBackend()
conn = MockConnection()
result = await backend.authenticate(conn)
assert result is not None
creds, user = result
assert user.id == editor_user.id
assert set(creds.scopes).issubset(editor_user.oauth_scopes)
assert set(creds.scopes).issubset(scopes)
def _issue_client_token(user: User, device_id: str | None = None) -> str:
_, raw_token = make_device_token(
user, device_id, scopes=" ".join(user.oauth_scopes[:3])
)
return raw_token
async def test_hybrid_auth_client_token_unbound_sets_device_id_none(
editor_user: User,
):
raw_token = _issue_client_token(editor_user)
class MockConnection(HTTPConnection):
def __init__(self):
self.scope: dict[str, dict[str, Any]] = {"session": {}, "state": {}}
self._headers = Headers({"Authorization": f"Bearer {raw_token}"})
backend = HybridAuthBackend()
conn = MockConnection()
result = await backend.authenticate(conn)
assert result is not None
_, user = result
assert user.id == editor_user.id
assert conn.scope["state"].get("device_id") is None
async def test_hybrid_auth_client_token_bound_sets_device_id_and_bumps_last_seen(
editor_user: User,
):
device = db_device_handler.add_device(
Device(
id="bound-device-1",
user_id=editor_user.id,
name="Bound Device",
client_device_identifier="cid-bound-1",
)
)
raw_token = _issue_client_token(editor_user, device_id=device.id)
class MockConnection(HTTPConnection):
def __init__(self):
self.scope: dict[str, dict[str, Any]] = {"session": {}, "state": {}}
self._headers = Headers({"Authorization": f"Bearer {raw_token}"})
backend = HybridAuthBackend()
conn = MockConnection()
result = await backend.authenticate(conn)
assert result is not None
assert conn.scope["state"].get("device_id") == device.id
refreshed = db_device_handler.get_device(
device_id=device.id, user_id=editor_user.id
)
assert refreshed is not None
assert refreshed.last_seen is not None