Files
romm/backend/handler/streaming/memory_cards.py
Georges-Antoine Assi a688676de7 fix: enforce ROM visibility on assets, sync, collections, stats and scan events (#5498)
* 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>

* docs: state that ROM visibility is enforced as access control

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

* fix(assets): hide saves, states, screenshots and memory cards on hidden ROMs

Visibility is access control, so per-id save/state/screenshot routes now 404
when the save's ROM is hidden from the caller (hidden ROM, hidden platform or
age limit), and the save/state lists and identifier lists leave those rows
out in SQL. GET /api/saves/summary 404s on a hidden ROM. Memory cards on a
hidden platform 404 on every per-id route, drop out of both lists, and can't
be created against a hidden platform.

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

* fix(saves): answer a hidden ROM's save summary like a missing one

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

* fix(permissions): enforce ROM visibility in sync, installs and feeds

Hidden ROMs/platforms and age-limited ROMs are access control, so the
paths that skipped the caller's visibility now apply it:

- sync negotiate: saves on hidden ROMs are neither offered, paired nor
  reported as conflicts; a client save on one negotiates like an unknown ROM
- push-pull SSH sync: resolves the device owner's visibility and skips
  saves on hidden ROMs in both directions
- device installs: list and claim leave out requests whose ROM became
  hidden (they stay pending), and outcome notifications don't name it
- recommendations: a hidden seed ROM is no longer named
- music playlists: track_count counts only tracks on visible ROMs
- audit events: firmware targets on hidden platforms are filtered
- setup library: supported platforms honour the caller's visibility
- feeds: a hidden platform found by slug reads as missing

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

* fix(visibility): hide ROMs from virtual collections, stats and scan events

Virtual collections apply the caller's visibility in SQL: a collection with
no visible member is left out (404 by id), member ids and covers skip hidden
ROMs, and the limit counts only visible collections.

Stats save, state and screenshot totals skip assets of hidden ROMs.

Scan events no longer broadcast to every socket. Progress and end events go
to a scan room that sockets of users holding platforms.write or tasks.run
join on connect. scanning_rom and scanning_platform go to the user rooms of
those followers who can see that ROM or platform, resolved once per scan
and grouped by visibility. get_rom_audience now builds on a shared
get_user_visibilities.

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

* fix: apply code-review findings on ROM visibility enforcement

Match virtual collection members by ROM id, build the cover visibility clauses
once, filter feed platforms by visibility in SQL, resolve every id before a
batch save or state delete, filter push-pull saves in the query, and narrow the
hides query to the requested users.

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

* refactor: apply simplify pass on ROM visibility enforcement

Require an explicit visibility filter on the saves, states and memory card
queries, share one roms_facets visibility join and one owned-asset helper,
filter virtual collection members by hidden ids, batch the scan audience's
scope lookup, and move the empty-room emit guard into socket_handler.

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

* test: start the scan audience before emitting from scan_rom

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

* docs: apply humanizer pass on the visibility rule

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

* fix(streaming): don't mount a memory card on a hidden platform

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

* fix: address Greptile review on ROM visibility enforcement

Refresh a running scan's audience after a permission change, fix the precedence
of the scan-room join assertion, and narrow mock await_args before reading them.

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

* revert: drop per-visibility scan event audience

Scan events go back to every socket. Removes handler/scan/audience.py,
the scan room join on connect, the permissions generation bump and the
batched OAuth scope resolution that only the audience used.

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

---------

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

363 lines
14 KiB
Python

"""Whole memory-card sync (per-user card model).
Opt-in per container via `memory_card_sync: true`. When on, the container's
entire card (PCSX2 Slot 1, Dolphin Slot A) is one owned image: hydrated (or
wiped to a fresh blank card) on claim, and evacuated to the library before the
game is stopped. This REPLACES the /save-file in-game-save path for that
container; save-STATE sync is untouched.
"""
import asyncio
import io
import urllib.error
import zipfile
from pathlib import PurePosixPath
from typing import TypedDict
from fastapi import HTTPException
from handler.auth.rom_visibility import RomVisibilityFilter
from handler.database import db_memory_card_handler, db_user_handler
from handler.filesystem import fs_asset_handler
from handler.streaming import broker
from handler.streaming.config import ResolvedContainer
from handler.streaming.session_store import StreamingSession
from logger.logger import log
from models.assets import MemoryCard
from utils.memory_cards import MEMORY_CARD_MAX_BYTES, content_hash_of_bytes
from utils.memory_cards import store_memory_card_version as store_memory_card_version
def _empty_zip_bytes() -> bytes:
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w"):
pass
return buf.getvalue()
# PUT to a freshly claimed container to wipe slot 1 to a blank card, so the next
# player never inherits the previous owner's saves (the isolation guarantee for
# pooled hosts). The broker's wipe-then-replace lays down an empty card and
# PCSX2 formats it on first save.
EMPTY_CARD = _empty_zip_bytes()
class MemoryCardUnavailable(Exception):
"""The broker's Slot-1 card could not be read (endpoint missing, wrong card
type, oversize, or a transport error). Distinct from a broker-confirmed
EMPTY slot: unavailable means we must NOT wipe, since we never captured it."""
# Its messages carry the broker host and port, so the client gets this fixed
# string and the real cause stays in the server log.
CARD_UNREADABLE_REASON = "The streaming container did not return its memory card"
CARD_IMPORT_FAILED_DETAIL = "Could not import the memory card"
def fetch_card(
container: ResolvedContainer, timeout: float = broker.CARD_HYDRATE_TIMEOUT
) -> bytes | None:
"""GET /memory-card from the broker. Tri-state:
- bytes: the Slot-1 card was captured and can be stored.
- None: the broker CONFIRMS the slot is empty (404 tagged
`X-Memory-Card: absent`). Nothing to store, safe to wipe.
- raise `MemoryCardUnavailable`: the card could not be read (endpoint
missing / unmarked 404, 409 File card, oversize, empty 200, or a transport
error). The caller must NOT wipe, since the card was never captured.
"""
try:
_, content = broker.get_binary(
container,
container.memory_card_route(),
max_bytes=MEMORY_CARD_MAX_BYTES,
timeout=timeout,
)
return content
except urllib.error.HTTPError as exc:
try:
if exc.code == 404 and exc.headers.get("X-Memory-Card") == "absent":
# Broker confirms the slot is genuinely empty (first run, or
# already wiped). Safe to wipe; there is nothing to evacuate.
return None
if exc.code == 409:
raise MemoryCardUnavailable(
"broker slot 1 is a File card, not a Folder card"
) from exc
raise MemoryCardUnavailable(
f"broker memory-card GET failed, HTTP {exc.code}"
) from exc
finally:
exc.close()
except Exception as exc:
raise MemoryCardUnavailable(f"broker memory-card GET failed, {exc}") from exc
def push_card(
container: ResolvedContainer,
content: bytes,
timeout: float = broker.CARD_HYDRATE_TIMEOUT,
) -> bool:
"""PUT /memory-card to the broker (wipe-then-replace). Best-effort, logs
but never raises. The caller decides whether a failure aborts the claim."""
return broker.put_binary(
container,
container.memory_card_route(),
content,
"memory-card PUT",
content_type="application/zip",
timeout=timeout,
)
class MemoryCardSummary(TypedDict):
file_count: int
total_bytes: int
game_codes: list[str]
def summarize_card(content: bytes) -> MemoryCardSummary:
"""Describe a fetched card for the import dialog. GameCube names its saves
`<makercode>-<gamecode>-<comment>.gci`, so the gamecode is a filename field,
not something that needs the card format parsed.
Never raises: a card we cannot parse still has to be offered to the user.
"""
codes: set[str] = set()
file_count = 0
total = 0
try:
with zipfile.ZipFile(io.BytesIO(content)) as zf:
for info in zf.infolist():
if info.is_dir():
continue
file_count += 1
total += info.file_size
parts = PurePosixPath(info.filename).name.split("-")
if len(parts) >= 3 and info.filename.lower().endswith(".gci"):
codes.add(parts[1])
except Exception:
# Unparseable: nothing describable, so report nothing rather than a
# file-less card that still claims a size.
return {"file_count": 0, "total_bytes": 0, "game_codes": []}
return {
"file_count": file_count,
"total_bytes": total,
"game_codes": sorted(codes),
}
def resolve_card(
user_id: int,
emulator: str,
memory_card_id: int | None,
visibility: RomVisibilityFilter,
) -> MemoryCard | None:
"""Pick the card to mount for a claim.
An explicit id must be one the user owns for this emulator. Shared/public
cards are view-only: they are browsable and downloadable through the memory
card UI, but never live-mounted onto another user's session, since a mounted
card is written back as a new version on release and that version belongs to
the owner. With no id, use the user's most-recently-used
card for the emulator, or None when the user has no card yet. Resolution
never creates rows; the claim path creates a blank card only after the
claim is won.
"""
if memory_card_id is not None:
card = db_memory_card_handler.get_card(user_id=user_id, id=memory_card_id)
if (
card is None
or card.emulator != emulator
or card.platform_id in visibility.hidden_platform_ids
):
raise HTTPException(
status_code=404, detail="Memory card not found for this emulator"
)
return card
cards = db_memory_card_handler.get_cards(
user_id=user_id, emulator=emulator, visibility=visibility
)
if cards:
return cards[0] # get_cards orders by updated_at desc
return None
def create_blank_card(
user_id: int, emulator: str, platform_id: int | None
) -> MemoryCard:
"""Create a fresh blank card for a user's first play on an emulator. The
blank carries no version, so hydrate wipes the container to a clean card
that the emulator formats on first save.
"""
blank = MemoryCard(
user_id=user_id,
emulator=emulator,
platform_id=platform_id,
name=f"{emulator} memory card",
slot=1,
is_public=False,
)
return db_memory_card_handler.add_card(blank)
async def hydrate_card_to_broker(
user_id: int, card: MemoryCard, container: ResolvedContainer
) -> bool:
"""Push the card's newest version down to a freshly claimed container BEFORE
launch (games read the card at boot). A blank card, or one whose stored file
has gone missing, wipes the container to a fresh card so the player never
inherits a previous owner's saves. Returns False only when the broker push
itself fails, so the caller can abort a claim it could not isolate.
"""
latest = db_memory_card_handler.get_latest_version(card.id)
content = EMPTY_CARD
if latest is not None:
try:
content = await fs_asset_handler.read_file(
f"{latest.file_path}/{latest.file_name}"
)
except FileNotFoundError:
# The version row exists but the file is gone. Wiping to a blank
# card keeps isolation intact rather than leaking the last card.
log.warning(
"memory card file missing on disk, %s, wiping to blank",
latest.file_name,
)
ok = await asyncio.to_thread(push_card, container, content)
if ok:
log.info(
"hydrated memory card to container, card=%d version=%s",
card.id,
latest.file_name if latest is not None else "(blank)",
)
return ok
def adoption_already_stored(card_id: int, content: bytes | None) -> bool:
"""Is the container's card already this card's latest version?
Dedup can refuse a version because a previous claim stored it and then died
before recording the adoption decision, leaving the prompt to fire again on
unchanged content. That retry is idempotent: hydrate would push back the
very bytes sitting on the container, so the adoption stands and only the
decision row is missing. A match against an older version means hydrate
would push something else over the card, which is the case that must abort.
"""
if not content:
return False
content_hash = content_hash_of_bytes(content)
if not content_hash:
return False
latest = db_memory_card_handler.get_latest_version(card_id)
return latest is not None and latest.content_hash == content_hash
async def discard_blank_card(card_id: int) -> None:
"""Drop a card this claim created, unless adoption already stored a version."""
# The adoption stays recorded, so the next claim must find this card to mount.
if db_memory_card_handler.get_latest_version(card_id) is not None:
log.info("keeping adopted card %d after an aborted claim", card_id)
return
for path in db_memory_card_handler.delete_card(card_id):
try:
await fs_asset_handler.remove_file(file_path=path)
except OSError as exc:
log.warning("could not remove card archive %s, %s", path, exc)
async def evacuate_card(
user_id: int, card_id: int, container: ResolvedContainer
) -> bool:
"""Pull the whole Slot-1 card off the broker and store it as a new version.
Called before the emulator is stopped so a pooled container is captured
before it can be reclaimed. Returns `safe_to_wipe`: True only when the card
was captured (or the broker confirmed the slot is empty), False when it
could not be read. The caller wipes the slot only when this is True, so a
card that failed to evacuate is never destroyed.
"""
user = db_user_handler.get_user(user_id)
card = db_memory_card_handler.get_card_by_id(card_id)
if user is None or card is None:
return False
try:
# Teardown must not hang a release for the full transfer window, so the
# fetch gets a tighter bound than hydrate-on-claim.
content = await asyncio.to_thread(
fetch_card, container, timeout=broker.CARD_TEARDOWN_TIMEOUT
)
except MemoryCardUnavailable as exc:
log.warning(
"could not evacuate memory card %d, not safe to wipe, %s",
card_id,
exc,
)
return False
if content is None:
log.info("broker slot empty, nothing to evacuate, card=%d", card_id)
return True
try:
stored = await store_memory_card_version(user, card, content)
except Exception:
log.exception("failed to store evacuated memory card %d", card_id)
return False
if stored:
log.info("memory card evacuated to library, card=%d", card_id)
else:
log.info("evacuated memory card unchanged, card=%d", card_id)
return True
async def evacuate_session_card(
session: StreamingSession, container: ResolvedContainer
) -> bool:
"""Evacuate a whole-card-sync session's card before its container is freed.
MUST be awaited while the Redis claim is still held: releasing the claim
first would let another user claim the container and wipe the card (claim
hydrates wipe-then-replace) before we capture it. Returns `safe_to_wipe`:
True only when the card was captured (or confirmed empty). No-op returning
False for containers without memory_card_sync or sessions that never
resolved a card, so those are never wiped.
"""
if not container.memory_card_sync:
return False
card_id = session.get("memory_card_id")
user_id = session.get("user_id")
if not isinstance(card_id, int) or not isinstance(user_id, int):
return False
try:
return await evacuate_card(user_id, card_id, container)
except Exception:
log.exception("memory card evacuation failed, card=%d", card_id)
return False
async def wipe_session_card(container: ResolvedContainer) -> None:
"""Blank the broker's Slot-1 card after a confirmed evacuation.
Defense in depth for pooled hosts: hydrate already wipes-then-replaces on
the next claim, but wiping now guarantees no card is left behind between
sessions for a bad or crashing hydrate to inherit. MUST run only when
evacuation reported safe_to_wipe, after the game is stopped (so the
emulator's exit flush cannot re-lay the card) and BEFORE the Redis claim is
released (so a concurrent claimant's fresh card is never clobbered).
Best-effort: a failed wipe is logged, not fatal, since the next claim wipes.
"""
if not container.memory_card_sync:
return
# Teardown path, so a tighter bound than hydrate-on-claim.
ok = await asyncio.to_thread(
push_card,
container,
EMPTY_CARD,
timeout=broker.CARD_TEARDOWN_TIMEOUT,
)
if ok:
log.info("wiped broker memory-card slot after evacuation")
else:
log.warning("memory-card slot wipe failed, relying on next-claim wipe")