12 Commits

Author SHA1 Message Date
Georges-Antoine Assi
f89f6ef185 fix(security): check collection ownership in the ROM filters (#5201)
* fix(security): check collection ownership in the ROM filters

The collection endpoints refuse a private collection to anyone but its
owner, but the ROM listing endpoints accepted the same id as a
collection_id or smart_collection_id filter without checking it. Any
user (or a kiosk visitor) could list, randomly pick from and bulk
download another user's private collections and Favourites, and re-share
one through a public smart collection scoped to it.

The membership filters now match only collections that are public or
owned by the caller. A collection_id inside smart collection criteria is
checked against the smart collection's owner, both when the criteria are
saved and when they are evaluated.

Reported by Takaya Sato (dagadjno).

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

* fix(security): clear stale smart collection caches across owners

Addresses Greptile's review on #5201. Smart collections cache their
membership on the row, so one scoped to another user's private
collection kept serving the members it cached before the ownership
check. Migration 0152 empties those caches on upgrade, and sharing or
unsharing a collection now refreshes the smart collections scoped to
it. Also covers a second user listing a public smart collection scoped
to its owner's private collection.

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

* fix(collections): harden smart collection scope refreshes (code-review)

Allow re-saving a smart collection whose stored scope was since lost,
reject non-object criteria in from_stored_criteria, guard the scoped
refresh, and refresh smart collections when a collection's ROMs are
replaced or the collection is deleted.

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

* refactor(collections): share the refresh wrapper and trim scope tests (simplify)

Move the scoped smart collection refresh next to the existing wrapper,
match the scope on the raw criteria before refreshing, batch the
migration update, and fold the duplicate unshare test into helpers.

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

* docs(migrations): describe the cleared smart scopes by current behavior (review-polish)

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

* docs(roms): state the collection filter comment plainly (humanizer)

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-09 13:20:26 -04:00
Sam Dornan
79fbce6beb test(backend): build test rows through shared factories and enforce them with ruff (#4972)
* test(backend): build test ROMs through one make_rom factory

Tests created Rom rows by hand in dozens of places, each spelling out the
same slug and filename fields and deriving the slug inline. Production never
computes a slug from a name, so this was test-only filler duplicated across
files.

tests/factories.py adds make_rom(platform, name, *, fs_stem, fs_extension,
**overrides), which fills the slug and filename columns and persists through
db_rom_handler.add_rom. The shared conftest fixtures, scan_stubs.add_rom and
the local helpers and inline constructors across 35 test files now use it.
Each test keeps its filename shape (underscored stems in the FULLTEXT search
tests, spaced "Name (USA)" stems in the sibling tests), and fixtures shared
across files keep their exact slugs.

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

* test(backend): keep extensionless filenames intact in scan_stubs.add_rom

rpartition(".") on a name with no dot returned an empty stem and the whole
name as the extension, so make_rom stored ".README" for "README".
os.path.splitext leaves such names whole.

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

* test(backend): build test saves, states and screenshots through factories

Tests built Save, State and Screenshot rows by hand across about 20 files,
each spelling out file_name_no_tags, file_name_no_ext and file_extension
although BaseAsset already derives them from file_name.

tests/factories.py adds make_save, make_state and make_screenshot. Each sets
the rom and user ids, the file name, and a default file_path under the rom's
platform, applies overrides last, and persists through the matching db
handler. The conftest asset fixtures and the persisted constructors and local
helpers now use them. Rows a test observes keep their file_path, emulator,
slot, size and hash, and a filename part stays an override wherever it
differs from what the model derives.

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

* test(backend): ban direct add_* persistence in tests via ruff TID251

The factories only stay the one home for test rows if nothing routes
around them. Ruff's banned-api rule now flags db_rom_handler.add_rom,
db_save_handler.add_save, db_state_handler.add_state and
db_screenshot_handler.add_screenshot anywhere under tests/ except
tests/factories.py. Production code is unaffected.

The remaining add_rom calls move onto make_rom: the unique-path, soundtrack
and id-index tests in test_roms_handler.py, the scan tests in
test_fastapi.py, physical and missing rows in the feed, download and model
tests, and the name=None exporter rows. Scan tests keep a filename-derived
placeholder as the name, which scan_rom treats the same as no name. Three
calls keep a noqa: the tests of how add_rom merges a partial scanned row,
and the rescan test that persists scan_rom's output as a scan does.

The backend skill and the architecture doc now point at tests/factories.py.

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

* test(backend): move the firmware and client-token factories into tests/factories.py

The add_firmware and add_device_token conftest fixtures returned a builder,
unlike the importable make_* functions. They become make_firmware and
make_device_token alongside them, with the same defaults, and their callers
import them rather than requesting a fixture. make_device_token now draws the
raw credential from auth_handler.generate_client_token, so it carries the
real rmm_ prefix instead of restating it, and the hand-built client tokens in
the auth tests use it too.

The ruff TID251 ban now also covers db_firmware_handler.add_firmware and
db_client_token_handler.add_token under tests/.

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

* docs: point at every test factory, not just the ROM and asset ones

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 14:01:56 -05:00
Sam Dornan
5a6c895d33 chore(mypy): give every generic its type arguments (#4818)
* 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>
2026-09-26 16:32:29 -05:00
Sam Dornan
1c20e77e41 Reject unusable smart collection criteria instead of dropping them
The real /code-review and /simplify passes over this PR, which an earlier
run substituted hand review for.

`from_stored_criteria` dropped the entries the model rejects. Dropping a
filter drops the constraint with it, so a row holding
`platform_ids: [3, "gba"]` widened from one platform to the whole library.
It now answers None, and the one caller turns that into a query matching
nothing: the loop over every smart collection still cannot be stopped by
one bad row, and a collection never shows more than its criteria claim.

`/api/roms/download` declared `collection_id` and `smart_collection_id`
unbounded while `get_roms_scalar` validates them through the model, so
`collection_id=0` raised inside the handler as a 500. They now carry the
`ge=1` the other two routes already declare, and fail at the boundary as
a 422.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MLreYqGLgHJLei6NThVXCz
2026-09-13 06:36:54 +00:00
Sam Dornan
983e24d5f8 refactor(roms): carry the ROM filters as one model
The filter vocabulary (13 multi-value filters with their logic operators,
plus the boolean and scope filters) was written out in five places: the
`/api/roms` query parameters, `filter_roms`'s 63-line signature, the
`kwargs.get` block in `get_roms_scalar`, the criteria translation in
`get_smart_collection_criteria`, and the `is_unscoped` test that decides
what may be cached.

That last one is the dangerous copy. The gallery's sidecar caches are keyed
on user/order/grouping but not on the filters, so a filter missing from
`is_unscoped` would let one user's narrowed gallery be stored under, and
served from, the shared "all" key.

`RomFilterParams` becomes the single home. The route takes it as a
dependency, `filter_roms` reads its fields, and smart collections rebuild
it from their stored criteria (legacy `selected_*` keys and the
`platform_id` scalar included, keeping `from_stored_criteria` the only
place that knows about them). `has_filters` now reads the model's own
fields, so a filter added later counts towards the cache gate without
anyone remembering to list it, and a test asserts that for every field.

The route reaches the model through `as_query_dependency` rather than
`Annotated[RomFilterParams, Query()]`, because FastAPI expands a query
model into its fields only when the model is a route's *only* query
parameter. `/api/roms` has a dozen others, so the native form would leave
one required parameter named `filters`: the schema would advertise it, the
generated client would be built from that, and a request carrying the
fields themselves would be rejected. A dependency's parameters are
flattened individually, so building one from the model keeps the fields.
An endpoint test pins that, since the failure is silent.

The API contract is unchanged: `/api/roms` still takes the same 58 query
parameters with identical types, descriptions, defaults and constraints,
and regenerating the frontend types from the new schema produces a
byte-identical `src/__generated__`. Only the order of the parameters in
the OpenAPI array differs, since FastAPI lists a dependency's parameters
after the route's own.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MLreYqGLgHJLei6NThVXCz
2026-09-12 23:18:56 +00:00
Spinnich
f4ac78c46b perf(collections): serve smart collections from a composed query
A smart collection re-ran its filters across the whole library on every
request, loaded every match into memory with its joined metadata, wrote
the membership back, and only then asked for the page being displayed.
The cost tracked library size rather than collection size, was paid twice
on first load and again on every scroll, and the write bumped updated_at,
which the covers embed as a ?ts= cache-buster.

Translate the stored filter_criteria into filter_roms keyword arguments
and apply them to a bare Rom.id select instead, so membership stays in
SQL and the database returns just the rows being rendered. The criteria
vocabulary is filter_roms' own, so this composes with the gallery's
filters. smart_collection_id is dropped from the criteria: the v2 create
dialog records the route it was opened from, so a collection built while
viewing another one carries its id, which would nest and could cycle.

Bind parameters for the MATCH clauses are now named after the term they
carry. A statement can hold two of them (the collection's search term and
the gallery's), and SQLAlchemy does not uniquify explicitly named text()
parameters, so a fixed name let one term overwrite the other.

The cached rom_ids / rom_count / path_covers_* columns still back the
collections list and the ROM detail page, so refresh them on write --
smart collection create and update, after a scan, and after ROMs are
deleted -- rather than as a side effect of browsing. They are computed
for the owner: the row is shared, so a per-user criterion like favorite
would otherwise describe whoever opened the collection last.

Regular collections and the favorites filter get the smaller half of the
same treatment: an indexed subquery over collections_roms instead of an
IN list built in Python. An unknown collection or smart collection now
returns nothing rather than falling through to the entire library.

Fixes #4029

AI assistance: implemented with Claude Code (Opus 5), tests first, then
reviewed and verified by me.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-31 20:23:31 +00:00
Georges-Antoine Assi
49d1ae71b2 Fix smart collections dropping newer filters
Smart collections silently ignored several filters at both ends:

- The backend never applied has_soundtrack, has_saves, has_states, or
  player_counts from stored criteria, so a "has soundtrack" smart
  collection contained every game. get_roms_scalar also dropped
  has_soundtrack before it reached filter_roms.
- The v2 criteria serializer had no fields for has_saves/has_states and
  only stored tri-state filters when true, so "unmatched" or "has
  saves" produced empty criteria and the no-filters guard blocked the
  save.

Criteria now carry saves/states filters and explicit false states, the
backend applies them, and summaries render negative states with the
existing "show-not-*" labels.

Fixes #3888

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-25 13:53:02 -04:00
Georges-Antoine Assi
753556af7b perf(backend): materialize virtual collection membership
virtual_collections was a view that unnested five JSON arrays per rom on
every read, so both the collection list and opening a single collection
scanned the whole library. Opening a collection with a handful of roms
cost as much as one with thousands, since the name is computed inside the
view and nothing can be narrowed down early.

Membership now lives in virtual_collection_roms, one narrow row per
(type, name, rom_id) plus that rom's covers, derived from the generated_*
columns and maintained by triggers on roms (deletions ride the foreign
key cascade). The view becomes a plain aggregate over that table, so the
model, schemas and API shape are unchanged, and filtering roms by a
virtual collection is an indexed subquery instead of an IN list of every
member id.

Covers are no longer aggregated in the view, which materialized every
member's cover path on every request; the handler resolves at most five
per collection, matching the smart collection cap and what both UIs
render.

On a synthetic 50k-rom library the list goes from 1.42s to 0.128s and a
single collection from 0.111s to 0.0006s, with identical output.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-22 10:06:05 -04:00
Georges-Antoine Assi
602faccc5c fix: generate virtual collections from all metadata sources
The virtual_collections view read only roms.igdb_metadata, so franchises,
genres, companies and play modes set manually or provided by non-IGDB sources
(ScreenScraper, Flashpoint, gamelist) never produced auto-generated
collections, even though the same values already drove /api/roms filtering and
the game detail page.

Redefine the view to source each grouping from the roms_metadata view, which
coalesces manual and provider metadata in priority order. Matching values now
merge into a single collection regardless of their source. The 3-ROM minimum
threshold is unchanged.

Fixes #3187

Generated-By: PostHog Code
Task-Id: 10289bf4-b0d0-4856-80c9-1be93c926f37
2026-07-06 10:39:03 -04:00
Spinnich
14a0a98661 feat(roms): filter games by custom tags
Adds a "Tag" gallery filter so a library can be narrowed by the custom
tags parsed from filenames (No-Intro / Redump nomenclature, e.g. Proto,
Beta, Demo), mirroring the existing data-derived multi-value filters
(regions, languages). Closes #3546.

Backend:
- New `_filter_by_tags` over `Rom.tags` with any/all/none logic; wired
  through filter_roms, get_roms_scalar, the /roms endpoint (tags +
  tags_logic), and the unscoped cache gate.
- Tags are data-derived, so the selectable list is surfaced via
  filter_values: added to _collect_filter_values, with_filter_values,
  get_rom_filters, and RomFiltersDict.
- Smart collections apply the criterion via get_smart_collection_roms.

Frontend (v1 + v2):
- Wired into the galleryFilter store, rom API service, request cache key,
  both filter drawers, v2 URL persistence, the v2 refetch watcher, and
  smart-collection serialization/summary + create dialog.
- Added the `platform.tag` key to all locales (distinct from the existing
  `platform.tags` section heading).

Tests:
- Backend handler (any/all/none + unknown-value), endpoint, filter_values,
  and smart-collection coverage.
- Frontend smartCollectionCriteria serialization/summary coverage.

AI assistance: implemented with Claude Code (Anthropic).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-29 11:29:12 +00:00
Spinnich
983f016efe feat(roms): filter games by matched metadata provider
Adds a "Metadata provider" gallery filter so a library can be narrowed by
which providers each ROM matched (IGDB, MobyGames, ScreenScraper, etc.),
mirroring the existing multi-value filters (player count, age rating).

Backend:
- New `_filter_by_metadata_providers` keyed off each provider's id column
  on Rom, with any/all/none logic; wired through filter_roms,
  get_roms_scalar, the /roms endpoint, and the unscoped cache gate.
- Smart collections apply the criterion via get_smart_collection_roms.
- Unknown provider slugs are ignored (no-op) so stale bookmarks or
  hand-edited URLs don't error.

Frontend (v1 + v2):
- Shared METADATA_PROVIDER_OPTIONS registry; provider list is a fixed set
  rather than data-derived, so options are static.
- Wired into the galleryFilter store, rom API service, request cache key,
  both filter drawers, v2 URL persistence, the v2 refetch watcher, and
  smart-collection serialization/summary.
- Added the `platform.metadata-provider` key to all locales.

Tests:
- Backend handler, endpoint, and smart-collection coverage (any/all/none
  plus unknown-slug).
- Frontend smartCollectionCriteria serialization/summary coverage.

Also normalized collections_handler.py to LF (it was the only CRLF file in
the backend, which tripped git-diff-check on the edited lines).

AI assistance: implemented with Claude Code (Anthropic).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-26 13:52:19 +00:00
copilot-swe-agent[bot]
7ab4052f93 Fix legacy smart collection status list normalization
Co-authored-by: gantoine <3247106+gantoine@users.noreply.github.com>
2026-06-08 12:25:56 +00:00