Files
romm/backend/tests/endpoints/test_auth.py
Georges-Antoine Assi 37e4ca304d fix: permission, validation and resource-limit hardening (#5496)
* fix(sync): cap play sessions on sync completion and require roms.user.write

The completion endpoint fed an unbounded play_sessions list to the same
ingest as POST /api/play-sessions, which allows 100 per batch and requires
roms.user.write. Apply both rules before the session is completed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(config): reject empty platform binding and version values

config.yml exits on load when a platforms or versions value is empty, so
the API must not write one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(collections): require smart collection criteria to be a JSON object

Any other JSON value was stored, then failed the response schema and broke
the smart collection list for every user who could see the collection.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(stats): require roms.read on /api/stats

Anonymous callers were served counts over the whole library, including
platforms and ROMs hidden from users. The UI only calls it after login.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(permissions): apply ROM visibility to filters, saves, play sessions and collection removal

/api/roms/filters aggregated facet values over the whole library, GET
/api/saves/{id} and GET /api/play-sessions returned the caller's own rows on
hidden ROMs, and removing ROMs from a collection could drop members hidden
from its owner. The facet visibility clauses move onto RomVisibilityFilter so
stats and filters share them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(webhooks): keep non-admin webhooks off the admin's internal metadata origins

The SSRF exception for a self-hosted Playmatch or Hasheous applied to every
request, so a user's webhook could reach any path on that private origin.
Non-admin webhooks now validate and connect with an empty allowlist.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(saves): bound total decompressed size when hashing zip archives

Zip content hashing capped each entry but not the archive, so many
entries each under the cap could still decompress and hash far more
than any real save or memory card holds. Budget the decompressed bytes
across the whole archive and cap the entry count; callers keep treating
an over-budget archive as an unknown hash.

The chunked, budgeted entry reader is shared with the memory card
archive check, and the RetroArch store path now hashes off the event
loop like its siblings.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(psp): clamp LZ4 literal and match copies to the ZISO block size

The ZISO block decoder appended literals and copied matches for their
full encoded length before checking the output size, and an LZ4 length
can be extended without bound by 0xFF bytes. A small crafted block
could therefore expand far past the block size before being truncated.

Clamp each copy to the room left in the block, stop once it is full,
end the block on a truncated match offset, and copy matches with slices
instead of a per-byte loop (overlapping matches repeat their pattern).
Output for valid blocks is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(auth): revoke OAuth tokens when a user's credentials change

A password change, admin reset, reset-link reset or rename cleared the
account's web sessions, but its OAuth access tokens kept working until they
expired and its refresh tokens could still be exchanged at /api/token.

Revoking a user's credentials now also records a per-username revocation
time in Redis, kept for the longest token lifetime. Bearer validation and
refresh consumption reject any token whose iat is at or before it. OAuth
tokens now carry a sub-second iat, so a login right after the change still
works; a token without iat counts as older than any revocation.

The revocation is keyed by the token's sub, the same username sessions are
keyed by, so a rename revokes tokens issued under the old name even if
another account later takes it. Client (API) tokens are left alone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(api): reject local file URLs for user-supplied covers and manuals

file:// and launchbox-file:// URLs are meant for covers and manuals that
a scan records from gamelist.xml or LaunchBox metadata. The collection
create/update endpoints and the ROM update endpoint passed a user-supplied
url_cover (and url_manual) straight to the resource handler, which copied
whatever library file it named into the entity's resources. That let any
user with collections.write or roms.write pull files they cannot otherwise
read, including those of hidden platforms and ROMs.

These endpoints now answer 400 for a local file URL, unless it is the value
already stored, which the edit forms echo back on every save.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(resources): bound cover downloads and decodes

Remote covers, screenshots, manuals, badges and media files were streamed
to disk with no size limit, and a gzip-encoded body was read whole and
inflated in memory. Downloads now go through one helper that counts bytes
against MAX_ASSET_UPLOAD_SIZE_BYTES, inflates gzip incrementally under the
same cap, and aborts past it, so the partial file is removed and any
earlier copy kept.

Covers are also bounded once on disk: a still image whose header declares
more than MAX_COVER_PIXELS is discarded before it is decoded (and an
uploaded one is refused with a 400), and a DecompressionBombError while
deriving the small cover now discards the download instead of failing the
request and leaving the file behind.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test: fix mypy errors in the new tests

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: address Greptile review on permission and input hardening

- Date OAuth tokens to before the credential check, so a password change
  that lands during the check revokes the tokens it issues.
- Apply ROM visibility to play sessions in SQL, before the page slice.
- Reject truncated gzip bodies and inflate every gzip member.
- Shorten the zip budget comment; stream real httpx2 responses in tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: apply code-review findings on permission hardening

Revoke OAuth tokens and sessions on user deletion, apply ROM visibility to
GET /states/{id}, validate update_collection rom_ids, run get_rom_filters off
the event loop, and reuse the shared httpx client factory for webhooks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor: apply simplify pass on permission hardening

Read the OAuth revocation stamp through the async cache, share the
play-session batch-size check, raise a plain OSError for oversized downloads,
and drop a dead slice in the LZ4 decoder.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* style: apply review-polish pass on permission hardening

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(play-sessions): filter rom_id and device_id on PlaySession after the visibility join

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 11:39:30 -05:00

273 lines
9.7 KiB
Python

import base64
import time
from http import HTTPStatus
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) -> 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, {})),
),
):
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_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")
@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"