mirror of
https://github.com/rommapp/romm.git
synced 2026-11-28 17:48:31 +01:00
* chore(mypy): switch to strict mode with listed exceptions Replace the hand-picked flags with `strict = True`, turning off only the four flags that aren't clean yet (disallow_any_generics, warn_return_any, disallow_untyped_calls, disallow_untyped_decorators). Any other strict flag, including those future mypy releases add to the preset, is on by default. That turns on no_implicit_reexport, strict_equality and extra_checks: - Import each name from the module that defines it. About 240 test sites patched a dependency through the module that imported it (`scan_module.fs_rom_handler`); they now import the same object from its source, so every patch targets what it did before. Tests that replace a module attribute are unchanged. - handler.streaming.memory_cards re-exports store_memory_card_version explicitly, since endpoints call it there and tests patch it there. - mutagen gets implicit_reexport, as it re-exports without __all__. - Test comparisons build typed values (CoverResult, a typed expected dict, enum .value) and the CORS lookup casts for its identity check. - One ss_handler ** spread keeps a coded ignore: extra_checks wants its NotRequired dump_* keys spelled out, and the media dict never has them. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PLzXae5up2pYXRoBjfjn2G * chore(mypy): give every generic its type arguments Drop disallow_any_generics from the strict-mode exceptions and fix the 347 bare generics it reports, 230 of them in app code. - Bare `dict` becomes `dict[str, Any]`: update payloads, raw provider JSON and endpoint bodies map string keys to mixed values, so the Any is real and now written down. The OpenAPI document is unchanged. - Rom query filters take and return RomSelect; _music_facet_joins and _exclude_hidden are generic over the Select they're given, and _build_hash_selects returns id-only selects. - Redis clients are typed by what they return: the decoding caches are Redis[str], the RQ connection and binary cache Redis[bytes]. - The rest get explicit parameters: Row, Pattern, ColumnElement, QueryableAttribute, SpooledTemporaryFile, Task, Future and friends. Precise types reached callers that had been getting Any, which surfaced: - The LaunchBox cache writer is fed binary-cache pipelines. - The flashpoint and IGDB request helpers return raw JSON of varying shape, not always a dict. - The rom search endpoint returned dicts under a list[SearchRomSchema] annotation; it now validates them into that schema. - The audit filter's id subquery selects strings. - In tests the binary cache is the non-decoding fake shared with async_cache, so it is cast to Redis[bytes] rather than changed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PLzXae5up2pYXRoBjfjn2G * test(upload): assert cleanup against the patched upload directory The 409 test checked config's ROM_UPLOAD_TMP_BASE while the fixture patches the endpoint's copy to tmp_path/uploads, so it passed even if cleanup failed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PLzXae5up2pYXRoBjfjn2G * chore(mypy): keep the row type through the ROM filter helpers filter_roms and its helpers also receive select(Rom.id) membership queries, so they now take and return the caller's Select type instead of narrowing to RomSelect. merged_ra_metadata mixes scalar and list values. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PLzXae5up2pYXRoBjfjn2G --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
362 lines
12 KiB
Python
362 lines
12 KiB
Python
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 config import OAUTH_REFRESH_TOKEN_EXPIRE_SECONDS
|
|
from handler.auth import auth_handler, oauth_handler
|
|
from handler.auth.constants import EDIT_SCOPES
|
|
from handler.auth.hybrid_auth import HybridAuthBackend
|
|
from handler.database import (
|
|
db_client_token_handler,
|
|
db_device_handler,
|
|
db_user_handler,
|
|
)
|
|
from models.client_token import ClientToken
|
|
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"
|
|
)
|
|
|
|
|
|
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_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 = auth_handler.generate_client_token()
|
|
hashed = auth_handler.hash_client_token(raw_token)
|
|
db_client_token_handler.add_token(
|
|
ClientToken(
|
|
user_id=user.id,
|
|
name="test-token",
|
|
hashed_token=hashed,
|
|
scopes=" ".join(user.oauth_scopes[:3]),
|
|
device_id=device_id,
|
|
)
|
|
)
|
|
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
|