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

367 lines
12 KiB
Python

"""Sync folder watcher for File Transfer mode.
This module is invoked by watchfiles when changes are detected in the sync
folder. It processes incoming save files from devices that use file_transfer
sync mode.
The watcher is configured to run as a separate watchfiles process monitoring
the sync base path. When files appear in a device's incoming/ directory, they
are matched to ROMs and processed as save uploads.
"""
import asyncio
import json
import os
import shutil
from collections.abc import Sequence
from datetime import datetime, timezone
from typing import cast
from config import ENABLE_SYNC_FOLDER_WATCHER
from handler.auth.rom_visibility import UNRESTRICTED
from handler.database import (
db_deleted_asset_handler,
db_device_handler,
db_device_save_sync_handler,
db_platform_handler,
db_save_handler,
db_sync_session_handler,
)
from handler.filesystem import fs_asset_handler, get_fs_sync_handler
from handler.sync.comparison import compare_save_state
from logger.formatter import highlight as hl
from logger.logger import log
from models.device import Device, SyncMode
from models.sync_session import SyncSessionStatus
from utils.sentry import init_sentry
init_sentry()
Change = tuple[str, str]
def _extract_device_and_platform(path: str) -> tuple[str, str, str] | None:
"""Extract device_id, platform_slug, and filename from a sync incoming path.
Expected path format: {ROMM_BASE_PATH}/sync/{device_id}/incoming/{platform_slug}/filename.ext
"""
fs_sync_handler = get_fs_sync_handler()
try:
rel_path = os.path.relpath(path, start=str(fs_sync_handler.base_path))
parts = rel_path.split(os.sep)
if len(parts) < 4 or parts[1] != "incoming":
return None
device_id = parts[0]
platform_slug = parts[2]
filename = parts[-1]
return (device_id, platform_slug, filename)
except ValueError, IndexError:
return None
def _ensure_conflicts_dir(device_id: str, platform_slug: str) -> str:
fs_sync_handler = get_fs_sync_handler()
conflicts_dir = str(
fs_sync_handler.base_path
/ fs_sync_handler.build_conflicts_path(device_id, platform_slug)
)
os.makedirs(conflicts_dir, exist_ok=True)
return conflicts_dir
def process_sync_changes(changes: Sequence[Change]) -> None:
"""Process file changes detected in the sync folder."""
if not ENABLE_SYNC_FOLDER_WATCHER:
return
# Only process added/modified files in incoming directories
added_files: list[tuple[str, str, str, str]] = (
[]
) # (device_id, platform_slug, filename, full_path)
for _event_type, change_path in changes:
src_path = os.fsdecode(change_path)
# Only process files (not directories)
if not os.path.isfile(src_path):
continue
parsed = _extract_device_and_platform(src_path)
if not parsed:
continue
device_id, platform_slug, filename = parsed
added_files.append((device_id, platform_slug, filename, src_path))
if not added_files:
return
# Group by device
by_device: dict[str, list[tuple[str, str, str]]] = {}
for device_id, platform_slug, filename, full_path in added_files:
by_device.setdefault(device_id, []).append((platform_slug, filename, full_path))
for device_id, files in by_device.items():
_process_device_incoming(device_id, files)
def _process_device_incoming(
device_id: str,
files: list[tuple[str, str, str]], # (platform_slug, filename, full_path)
) -> None:
"""Process incoming files for a single device."""
from endpoints.sockets.sync import (
emit_sync_completed,
emit_sync_error,
emit_sync_started,
)
# Look up device - try all users since file transfer is server-side
device = db_device_handler.get_device_by_id(device_id)
if not device:
log.warning(f"Sync watcher: unknown device {device_id}, skipping")
return
if device.sync_mode != SyncMode.FILE_TRANSFER:
log.warning(
f"Sync watcher: device {device_id} is not in file_transfer mode, skipping"
)
return
if not device.sync_enabled:
log.info(f"Sync watcher: device {device_id} sync is disabled, skipping")
return
# Create a sync session
sync_session = db_sync_session_handler.create_session(
device_id=device.id, user_id=device.user_id
)
db_sync_session_handler.update_session(
session_id=sync_session.id,
data={
"status": SyncSessionStatus.IN_PROGRESS,
"operations_planned": len(files),
},
)
asyncio.run(
emit_sync_started(
user_id=device.user_id,
device_id=device.id,
session_id=sync_session.id,
sync_mode="file_transfer",
)
)
completed = 0
failed = 0
for platform_slug, filename, full_path in files:
try:
_process_incoming_file(
device, sync_session.id, platform_slug, filename, full_path
)
completed += 1
except Exception:
log.error(
f"Sync watcher: failed to process {filename} for device {device_id}",
exc_info=True,
)
failed += 1
# Complete the session
db_sync_session_handler.complete_session(
session_id=sync_session.id,
operations_completed=completed,
operations_failed=failed,
)
if failed > 0:
asyncio.run(
emit_sync_error(
user_id=device.user_id,
device_id=device.id,
session_id=sync_session.id,
error_message=f"{failed} file(s) failed to process",
)
)
asyncio.run(
emit_sync_completed(
user_id=device.user_id,
device_id=device.id,
session_id=sync_session.id,
operations_completed=completed,
operations_failed=failed,
)
)
log.info(
f"Sync watcher: device {device_id} processed {completed} files, {failed} failures"
)
def _process_incoming_file(
device: Device,
session_id: int,
platform_slug: str,
filename: str,
full_path: str,
) -> None:
"""Process a single incoming file from a device's sync folder."""
from endpoints.sockets.sync import emit_sync_conflict
fs_sync_handler = get_fs_sync_handler()
# Look up platform
platform = db_platform_handler.get_platform_by_fs_slug(platform_slug)
if not platform:
log.warning(f"Sync watcher: unknown platform slug {platform_slug}")
return
# Compute hash of incoming file
file_hash = fs_sync_handler.compute_file_hash(full_path)
file_size = os.path.getsize(full_path)
file_mtime = datetime.fromtimestamp(os.path.getmtime(full_path), tz=timezone.utc)
# Try to find matching saves on this platform for this user. Only
# slot-bound saves participate in sync; null-slot saves are web-UI /
# archival uploads and must never be paired with a device push. Filter
# in SQL so archival rows never load.
saves_on_platform = db_save_handler.get_saves(
user_id=device.user_id,
platform_id=platform.id,
slot_not_null=True,
visibility=UNRESTRICTED,
)
matched_save = None
for save in saves_on_platform:
if save.file_name == filename:
matched_save = save
break
if matched_save:
# Compare with existing save
device_sync = db_device_save_sync_handler.get_sync(
device_id=device.id, save_id=matched_save.id
)
result = compare_save_state(
client_hash=file_hash,
client_updated_at=file_mtime,
server_hash=matched_save.content_hash,
server_updated_at=matched_save.updated_at,
device_last_synced_at=device_sync.last_synced_at if device_sync else None,
device_last_sync_hash=device_sync.last_sync_hash if device_sync else None,
device_last_sync_server_hash=(
device_sync.last_sync_server_hash if device_sync else None
),
# Identical content is a no_op, which never reads removals.
removed_at=(
db_deleted_asset_handler.removal_times(
device.user_id, matched_save.rom_id, matched_save.slot
)
if file_hash != matched_save.content_hash
else None
),
)
if result.action == "no_op":
log.debug(f"Sync watcher: {filename} is already in sync, skipping")
if file_hash == matched_save.content_hash:
db_device_save_sync_handler.record_identical_content(
device.id, matched_save.id, file_hash
)
fs_sync_handler.remove_incoming_file(full_path)
return
if result.action == "upload":
# Client file is newer - update server save
log.info(
f"Sync watcher: updating save {hl(filename)} from device {device.id}"
)
with open(full_path, "rb") as f:
file_data = f.read()
replaced_hash = asyncio.run(fs_asset_handler.unrecorded_hash(matched_save))
asyncio.run(
fs_asset_handler.write_file(
file=file_data,
path=matched_save.file_path,
filename=matched_save.file_name,
)
)
db_save_handler.update_save(
matched_save.id,
{
"file_size_bytes": file_size,
"content_hash": file_hash,
},
replaced_hash=replaced_hash,
)
# This path hashes the device's file itself, so both sides hold file_hash.
db_device_save_sync_handler.upsert_sync(
device_id=device.id,
save_id=matched_save.id,
last_sync_hash=file_hash,
last_sync_server_hash=file_hash,
)
fs_sync_handler.remove_incoming_file(full_path)
elif result.action == "conflict":
log.warning(
f"Sync watcher: conflict detected for {filename} "
f"on device {device.id}: {result.reason}"
)
# Move conflicting file to conflicts directory
conflicts_dir = _ensure_conflicts_dir(device.id, platform_slug)
conflict_path = os.path.join(conflicts_dir, filename)
shutil.move(full_path, conflict_path)
log.info(f"Sync watcher: moved conflicting file to {conflict_path}")
# Emit socket notification for conflict
asyncio.run(
emit_sync_conflict(
user_id=device.user_id,
device_id=device.id,
session_id=session_id,
file_name=filename,
rom_id=matched_save.rom_id,
rom_name=matched_save.rom.name or matched_save.rom.fs_name,
reason=result.reason,
)
)
elif result.action == "download":
# Server is newer - write server save to device's outgoing directory
log.info(
f"Sync watcher: server save is newer for {filename}, "
f"writing to outgoing"
)
server_file_path = f"{matched_save.file_path}/{matched_save.file_name}"
server_full_path = fs_asset_handler.validate_path(server_file_path)
with open(str(server_full_path), "rb") as f:
server_data = f.read()
fs_sync_handler.write_outgoing_file(
device_id=device.id,
platform_slug=platform_slug,
file_name=filename,
data=server_data,
)
# The device has no bytes yet, so only the server half is known.
db_device_save_sync_handler.upsert_sync(
device_id=device.id,
save_id=matched_save.id,
last_sync_server_hash=matched_save.content_hash,
)
fs_sync_handler.remove_incoming_file(full_path)
else:
log.info(
f"Sync watcher: new file {hl(filename)} from device {device.id} "
f"on platform {platform_slug} - no matching save found, skipping"
)
if __name__ == "__main__":
changes = cast(list[Change], json.loads(os.getenv("WATCHFILES_CHANGES", "[]")))
if changes:
process_sync_changes(changes)