Files
romm/backend/utils/memory_cards.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

227 lines
9.3 KiB
Python

"""Storage for whole memory card images. Shared by the streaming teardown that
evacuates a card off a container and by the upload route that takes one from
the user, so both agree on how a version is hashed, named and deduplicated."""
import hashlib
import io
import ntpath
import re
import zipfile
from datetime import datetime, timezone
from pathlib import PurePosixPath
from handler.database import db_memory_card_handler
from handler.filesystem import fs_asset_handler
from handler.filesystem.assets_handler import (
ArchiveTooLarge,
hash_zip_contents,
iter_zip_entry,
)
from handler.scan_handler import scan_memory_card_version
from logger.logger import log
from models.assets import MemoryCard, MemoryCardVersion
from models.user import User
from utils.filesystem import fit_filename, sanitize_filename
# The broker caps card transfers at the same figure. Raising one side alone
# just moves where the transfer fails.
MEMORY_CARD_MAX_BYTES = 256 * 1024 * 1024
def content_hash_of_bytes(content: bytes) -> str | None:
"""Compute the dedup hash of a card without writing it to disk. Mirrors
fs_asset_handler.compute_content_hash exactly (zip-entry hash for zips,
plain md5 otherwise, None on failure) so it matches stored content_hash
values.
"""
try:
buf = io.BytesIO(content)
if zipfile.is_zipfile(buf):
with zipfile.ZipFile(buf, "r") as zf:
return hash_zip_contents(zf)
return hashlib.md5(content, usedforsecurity=False).hexdigest()
except Exception as exc:
log.debug("could not hash memory card in memory, %s", exc)
return None
class UnsafeCardArchive(ValueError):
"""A card archive the broker must not be asked to unpack."""
# The unix mode a zip entry carries in the top half of its external attributes,
# and the bits that mark it a symlink.
_ZIP_MODE_SHIFT = 16
_S_IFMT = 0o170000
_S_IFLNK = 0o120000
# Enough that a card-sized entry is a handful of reads, small enough that the
# check never holds much more than this per entry.
_UNPACK_CHUNK_BYTES = 1024 * 1024
def _assert_entry_fits(zf: zipfile.ZipFile, entry: zipfile.ZipInfo, budget: int) -> int:
"""Decompress one entry against what is left of the archive's budget, and
return what it consumed.
Decompressed rather than trusting `file_size`: that header is whatever the
uploader put there, and an unpacker writes what actually comes out.
"""
try:
return sum(
len(chunk)
for chunk in iter_zip_entry(zf, entry, budget, _UNPACK_CHUNK_BYTES)
)
except ArchiveTooLarge:
raise UnsafeCardArchive(
f"unpacks to over {MEMORY_CARD_MAX_BYTES} bytes"
) from None
def assert_card_archive_safe(content: bytes) -> None:
"""Refuse an archive the broker must not be asked to unpack: one whose
entries would escape the directory they land in, or fill the disk they land
on. RomM stores the zip whole, and this is the last point that can look at
what is inside before a container unpacks it.
"""
try:
with zipfile.ZipFile(io.BytesIO(content), "r") as zf:
# Budgeted over the whole archive, not per entry: a card set is
# several files and the container's disk pays for the total. The
# archive's own size says nothing about it, since a few hundred
# compressed megabytes of zeros expand to hundreds of gigabytes.
budget = MEMORY_CARD_MAX_BYTES
for entry in zf.infolist():
name = entry.filename
# Zip names are meant to be slash-separated, so a hand-written
# entry can hide `..\..\evil` in what PurePosixPath reads as one
# opaque part. Both separators are split before the parts are
# judged.
parts = re.split(r"[\\/]", name)
if (
PurePosixPath(name).is_absolute()
or ntpath.isabs(name)
or ".." in parts
):
raise UnsafeCardArchive(f"unsafe path: {name}")
# A symlink's own name is harmless; its target is not, and an
# unpacker that follows it writes wherever the target points on
# the next entry.
mode = entry.external_attr >> _ZIP_MODE_SHIFT
if mode & _S_IFMT == _S_IFLNK:
raise UnsafeCardArchive(f"symlink entry: {name}")
if not name.endswith("/"):
budget -= _assert_entry_fits(zf, entry, budget)
# Encrypted entries and unsupported compression raise on the read rather
# than on the open, and an archive this cannot look inside is one the broker
# must not be handed either.
except zipfile.BadZipFile, NotImplementedError, RuntimeError:
raise UnsafeCardArchive("not a readable zip archive") from None
# Names only ever collide when two snapshots land in the same millisecond, so
# the walk exists to break that tie, not to search.
_FILENAME_COLLISION_ATTEMPTS = 20
async def _free_version_filename(cards_path: str, card_name: str, ts: str) -> str:
"""A version filename no archive already occupies.
`write_file` overwrites silently, so a name reused by a second snapshot
would replace the first one's bytes on disk while its row lived on
describing content that is no longer there.
"""
for attempt in range(1, _FILENAME_COLLISION_ATTEMPTS + 1):
suffix = "" if attempt == 1 else f" ({attempt})"
# A 255-character card name can still overflow the 255-byte name limit.
filename = sanitize_filename(
fit_filename(card_name, f" [{ts}{suffix}].card.zip")
)
if not await fs_asset_handler.file_exists(f"{cards_path}/{filename}"):
return filename
raise RuntimeError(f"could not find a free filename for card {card_name}")
async def _discard_version_file(cards_path: str, filename: str) -> None:
"""Drop an archive no version row will reference. Best effort: it is
already unreachable, and raising here would mask the reason we are here."""
try:
await fs_asset_handler.remove_file(f"{cards_path}/{filename}")
except OSError as exc:
log.warning("could not remove unreferenced card archive %s, %s", filename, exc)
async def store_memory_card_version(
user: User,
card: MemoryCard,
content: bytes,
deduplicate: bool = True,
) -> MemoryCardVersion | None:
"""Store card content as a new MemoryCardVersion. Identical content is
deduplicated by hash so repeated exits do not pile up copies. Either way the
card's updated_at is bumped so it floats to the top of the next pick list.
Returns the version that was written, or None when the content was already
in the history.
`deduplicate` is off for an upload, where the user is asking for exactly
this content to become current: matching an older snapshot would leave that
snapshot where it is and the newer one still at the head, so the card the
next claim hydrates would not be the one that was just uploaded.
"""
# Hashed once here, in memory: it answers the dedup precheck below and is
# handed to the scan, which would otherwise read the whole archive back off
# disk and decompress every entry to reach the same value.
content_hash = content_hash_of_bytes(content)
if deduplicate and content_hash:
existing = db_memory_card_handler.get_version_by_content_hash(
card_id=card.id, content_hash=content_hash
)
if existing is not None:
db_memory_card_handler.update_card(
card.id, {"updated_at": datetime.now(timezone.utc)}
)
return None
ts = datetime.now().strftime("%Y-%m-%d %H-%M-%S-%f")[:-3]
cards_path = fs_asset_handler.build_memory_cards_file_path(
user=user, emulator=card.emulator, card_id=card.id
)
filename = await _free_version_filename(cards_path, card.name, ts)
await fs_asset_handler.write_file(file=content, path=cards_path, filename=filename)
try:
version = await scan_memory_card_version(
file_name=filename,
user=user,
emulator=card.emulator,
card_id=card.id,
content_hash=content_hash,
)
# Fallback dedup on the scanned hash, for when the in-memory hash could
# not be computed. Keeps duplicates out even when the precheck misses.
stored: MemoryCardVersion | None = None
if (
deduplicate
and version.content_hash
and db_memory_card_handler.get_version_by_content_hash(
card_id=card.id, content_hash=version.content_hash
)
is not None
):
await _discard_version_file(cards_path, filename)
else:
stored = db_memory_card_handler.add_version(version)
except Exception:
# No row points at the archive yet, so leaving it behind strands bytes
# that nothing can reach and no delete would ever clean up.
await _discard_version_file(cards_path, filename)
raise
# Touch the card so "most recent" ordering reflects this session even when
# the content was unchanged (updated_at has no onupdate on add_version).
db_memory_card_handler.update_card(
card.id, {"updated_at": datetime.now(timezone.utc)}
)
return stored