9 Commits

Author SHA1 Message Date
Georges-Antoine Assi
2d7b9e3c34 test(api): check that routes document the error statuses they raise (#5686)
* test(api): check that routes document the error statuses they raise

protected_route now documents the scope guard's 401 and 403 on every
route that declares scopes, appending to a route's own description when
it has one.

tools/route_errors.py follows each route's calls through imports,
handler instances, custom exception classes and HTTPException subclasses
to the statuses it can raise. test_raised_statuses_are_documented fails
on a status the route's responses= leaves out, against a baseline of
existing gaps that can only shrink.

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

* docs(api): document error responses for roms routes

Describe every 4xx and 5xx the rom routes and their helpers raise in each
decorator's responses=, so the OpenAPI schema lists them. A hidden rom,
platform or file is described like a missing one.

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

* docs(api): document error responses for saves routes

Describe every 4xx/5xx the saves, states, screenshots, snapshots,
play-sessions and sync routes raise in their responses=, and rewrite the
states identifiers docstring that carried Args/Returns blocks.

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

* docs(api): document error responses for devices routes

Describe the 4xx/5xx statuses that the device, device auth, install,
client token, notification, notification channel, sync channel and
heartbeat routes raise, and fill the empty install route entries.
Rewrite the setup and heartbeat docstrings that published Args and
Returns blocks.

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

* docs(api): document error responses for streaming routes

Describe the 4xx and 5xx statuses the streaming, memory card and netplay routes raise in their responses= declarations, and replace the Args: blocks in route docstrings that FastAPI published verbatim.

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

* docs(api): document error responses for admin routes

Describe the 4xx and 5xx statuses the config, permissions, user, auth,
tasks, logs, activity and export routes raise, and rewrite their
Args/Returns docstrings as plain operation descriptions.

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

* docs(api): document error responses for library routes

Describe the 400/403/404/409/500 statuses the collection, feed, firmware,
platform, music, playlist and search routes raise, and replace route
docstrings that carried Args/Returns blocks with plain sentences.

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

* fix(api): answer like a missing resource for hidden play sessions and private collections

DELETE /play-sessions/{id} deleted the caller's session even on a rom
hidden from them, so 204 versus 404 showed the session existed. The
handler now takes the caller's rom visibility.

Another user's private collection, smart collection or playlist
answered 403, which showed it existed. It now answers 404 on every
route; a public one the caller does not own still answers 403 on write.

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

* docs(api): describe private collections and playlists as missing

Matches #5686, where another user's private collection or playlist
answers 404 and a play session on a hidden rom answers like a missing
one. The read routes drop their 403, and the write 403 now covers only
a public resource another user owns.

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

* docs(collections): use #5693's docstrings on the routes this PR touches

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

* docs(api): address Greptile review on route error docs

Fold the nine multi-paragraph route docstrings into one line, and keep
the device-scope 403 descriptions in utils/auth.py next to
resolve_device, which raises them, instead of in both saves.py and
states.py.

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

* test(api): follow route dependencies in the status analyzer

Addresses Greptile's review: route_errors now follows the callable in
Depends(...) and Security(...), whether it is a parameter default or
inside an Annotated alias, and the module docstring is one line.

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

* docs(api): tighten wording of route error descriptions

Give clipped responses descriptions and helper docstrings their missing
subjects and verbs, use 'the caller lacks' and 'is not allowed to'
consistently, and replace 'picked' with 'chosen'.

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

* test(api): drop the route error baseline

Every status left in the baseline was one a client cannot get:

- The export routes' empty platform list check is dead, since FastAPI
  answers a missing required list query with 422. Removed.
- get_save_layouts went through _restore_error, whose 500 fallback it
  cannot reach. It raises its 400 and 503 directly now.
- The notification test and confirm routes only catch ChannelError,
  since the cooldown and email errors come from other actions.
- The analyzer now skips asyncio.gather(..., return_exceptions=True),
  which covers search_rom.
- A '# route-errors: ignore' marker, with its reason, skips code whose
  errors never reach the client: the metadata heartbeat probe, the
  force-release teardowns, and the legacy save adoption.

The check now fails on any undocumented status.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 10:00:18 -05:00
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
Sam Dornan
452b52cbae chore(mypy): replace type-ignore defaults with typed injection sentinels (#4843) 2026-09-27 15:51:50 -04:00
Sam Dornan
c4f4d22687 chore(mypy): require coded ignores and flag stale ones, type protected_route (#4794) 2026-09-25 22:33:13 -04:00
Sam Dornan
9a19d94ec5 fix(backend): type DML row counts from Session.execute for mypy (#4718) 2026-09-22 18:24:12 -04:00
Georges-Antoine Assi
4e5ee69343 more simplify 2026-04-06 22:29:55 -04:00
Georges-Antoine Assi
b2e1e094f7 some simplification 2026-04-06 21:53:49 -04:00
nendo
719b98faaf Batch session inserts into single transaction
Replace per-item add_session with add_sessions using add_all.
No fallback on IntegrityError -- duplicate concurrent submissions
are the client's responsibility.
2026-03-22 21:21:27 +09:00
nendo
75302ed59a Add play session ingest for game time tracking
Backend API for collecting and querying play sessions, modeled after
the Argosy session data format. Clients submit batches per device,
recording both the session window and screen-on time.
2026-03-22 20:22:55 +09:00