Files
romm/backend/tests/handler/database/test_rom_facets.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

218 lines
7.9 KiB
Python

"""Checks for the `roms_facets` mirror that backs the filter dropdowns.
The table holds a copy of each ROM's filter values (migration 0100) and is
maintained by database triggers on `roms`, not by application code, so these
tests write through the normal handlers and assert the mirror follows.
"""
import gc
from sqlalchemy import String, select
from sqlalchemy.engine import CursorResult, ExecutionContext
from tests.factories import make_rom
from handler.auth.rom_visibility import UNRESTRICTED
from handler.database import db_rom_handler, roms_handler
from handler.database.base_handler import sync_session
from models.platform import Platform
from models.rom import (
METADATA_SOURCE_COLUMNS,
METADATA_SOURCE_FACET_COLUMNS,
Rom,
RomFacets,
)
def _facets(rom_id: int) -> RomFacets | None:
with sync_session.begin() as session:
return session.scalar(select(RomFacets).where(RomFacets.rom_id == rom_id))
class TestRomFacets:
def test_insert_mirrors_the_rom(self, rom: Rom):
facets = _facets(rom.id)
assert facets is not None
assert facets.platform_id == rom.platform_id
def test_min_age_mirrors_the_rom(self, rom: Rom):
db_rom_handler.update_rom(
rom.id,
{"igdb_metadata": {"age_ratings": [{"category": "CERO", "rating": "C"}]}},
)
facets = _facets(rom.id)
assert facets is not None
assert facets.min_age == 15
def test_update_mirrors_derived_and_raw_values(self, rom: Rom):
db_rom_handler.update_rom(
rom.id,
{
"igdb_metadata": {"genres": ["Action", "RPG"], "franchises": ["Zelda"]},
"regions": ["USA"],
"tags": ["Proto"],
},
)
facets = _facets(rom.id)
assert facets is not None
assert facets.genres == ["Action", "RPG"]
assert facets.franchises == ["Zelda"]
assert facets.regions == ["USA"]
assert facets.tags == ["Proto"]
def test_provider_ids_mirror_the_rom(self, rom: Rom):
# Backs the Server Stats metadata-coverage breakdown, which counts these
# off the mirror instead of scanning `roms`.
db_rom_handler.update_rom(
rom.id,
{"igdb_id": 1234, "moby_id": 56, "flashpoint_id": "fp-1"},
)
facets = _facets(rom.id)
assert facets is not None
assert facets.igdb_id == 1234
assert facets.moby_id == 56
assert facets.flashpoint_id == "fp-1"
# Sources the ROM didn't match stay null.
assert facets.ss_id is None
def test_every_provider_id_is_mirrored(self, rom: Rom):
"""Guards the trigger column list: a provider missed there mirrors null."""
# A string id for the providers whose column is a slug, else an int.
values = {
slug: f"{slug}-1" if isinstance(column.type, String) else index + 1
for index, (slug, column) in enumerate(METADATA_SOURCE_COLUMNS.items())
}
db_rom_handler.update_rom(
rom.id,
{
column.key: values[slug]
for slug, column in METADATA_SOURCE_COLUMNS.items()
},
)
facets = _facets(rom.id)
assert facets is not None
assert {
slug: getattr(facets, column.key)
for slug, column in METADATA_SOURCE_FACET_COLUMNS.items()
} == values
def test_publishers_developers_mirror(self, rom: Rom):
db_rom_handler.update_rom(
rom.id,
{
"ss_metadata": {
"companies": ["Atari", "Artech Studios"],
"publishers": ["Atari"],
"developers": ["Artech Studios"],
}
},
)
facets = _facets(rom.id)
assert facets is not None
assert facets.publishers == ["Atari"]
assert facets.developers == ["Artech Studios"]
filters = db_rom_handler.get_rom_filters(UNRESTRICTED)
assert "Atari" in filters["publishers"]
assert "Artech Studios" in filters["developers"]
def test_steam_only_metadata_mirrors(self, rom: Rom):
# Steam feeds the same generated columns as every other provider, so a
# game matched only there is filterable and indexable like any other.
db_rom_handler.update_rom(
rom.id,
{
"steam_metadata": {
"genres": ["Action", "Indie"],
"companies": ["Team Cherry"],
"developers": ["Team Cherry"],
"publishers": ["Team Cherry"],
"game_modes": ["Single player"],
}
},
)
facets = _facets(rom.id)
assert facets is not None
assert facets.genres == ["Action", "Indie"]
assert facets.companies == ["Team Cherry"]
assert facets.developers == ["Team Cherry"]
assert facets.publishers == ["Team Cherry"]
assert facets.game_modes == ["Single player"]
def test_delete_cascades(self, rom: Rom):
rom_id = rom.id
db_rom_handler.delete_rom(rom_id)
assert _facets(rom_id) is None
def test_filter_values_follow_a_metadata_edit(self, rom: Rom):
db_rom_handler.update_rom(
rom.id, {"igdb_metadata": {"genres": ["Puzzle"]}, "languages": ["En"]}
)
filters = db_rom_handler.get_rom_filters(UNRESTRICTED)
assert "Puzzle" in filters["genres"]
assert "En" in filters["languages"]
def test_filter_values_merge_repeated_lists(
self, rom: Rom, second_rom: Rom, platform: Platform, monkeypatch
):
# Three copies of one list can't share a batch of two, so a repeat is
# always skipped in a later batch, whatever order the rows come back in.
monkeypatch.setattr(roms_handler, "_FILTER_VALUES_BATCH_SIZE", 2)
third = make_rom(platform, "test_rom_3", slug="test_rom_slug_3")
for rom_id in (rom.id, second_rom.id, third.id):
db_rom_handler.update_rom(
rom_id, {"igdb_metadata": {"genres": ["RPG", "Action"]}}
)
fourth = make_rom(platform, "test_rom_4", slug="test_rom_slug_4")
db_rom_handler.update_rom(
fourth.id, {"igdb_metadata": {"genres": ["Puzzle", "RPG"]}}
)
make_rom(platform, "test_rom_5", slug="test_rom_slug_5")
filters = db_rom_handler.get_rom_filters(UNRESTRICTED)
assert filters["genres"] == ["Action", "Puzzle", "RPG"]
assert filters["platforms"] == [platform.id]
def test_filter_values_survive_a_scalar_where_a_list_belongs(
self, rom: Rom, second_rom: Rom
):
db_rom_handler.update_rom(rom.id, {"manual_metadata": {"genres": "RPG"}})
db_rom_handler.update_rom(
second_rom.id, {"igdb_metadata": {"genres": ["Action"]}}
)
assert "Action" in db_rom_handler.get_rom_filters(UNRESTRICTED)["genres"]
def test_filter_values_free_the_cursor_without_the_gc(self, rom: Rom):
# A cursor left for the cyclic GC is finalized on whichever thread
# collects next, which segfaults the mariadb connector under load.
db_rom_handler.update_rom(rom.id, {"igdb_metadata": {"genres": ["Puzzle"]}})
was_enabled, debug_flags = gc.isenabled(), gc.get_debug()
gc.collect()
gc.disable()
gc.set_debug(gc.DEBUG_SAVEALL)
garbage_start = len(gc.garbage)
try:
db_rom_handler.get_rom_filters(UNRESTRICTED)
gc.collect()
# The execution context owns the DBAPI cursor, so check it as well.
leaked = [
o
for o in gc.garbage[garbage_start:]
if isinstance(o, (CursorResult, ExecutionContext))
]
finally:
gc.set_debug(debug_flags)
del gc.garbage[garbage_start:]
if was_enabled:
gc.enable()
assert leaked == []