Files
romm/backend/tests/tasks/test_sync_push_pull.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

1035 lines
37 KiB
Python

"""Tests for SyncPushPullTask initialization and configuration."""
from dataclasses import replace
from datetime import datetime, timezone
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from tests.factories import make_esrb_rated_rom, make_save
from endpoints.sockets import sync as sync_sockets
from handler.auth.rom_visibility import UNRESTRICTED, RomVisibilityFilter
from handler.database import (
db_deleted_asset_handler,
db_device_handler,
db_device_save_sync_handler,
db_permission_handler,
db_save_handler,
db_sync_session_handler,
db_user_handler,
)
from handler.database.base_handler import sync_session
from handler.sync.ssh_handler import RemoteSaveInfo
from models.assets import Save
from models.device import Device, SyncMode
from models.permission import HiddenEntity, PermEntity
from models.platform import Platform
from models.rom import Rom
from models.sync_session import SyncSessionStatus
from models.user import User
from tasks import sync_push_pull_task as push_pull
from tasks.registry import SYNC_PUSH_PULL_SPEC
from tasks.sync_push_pull_task import (
SyncPushPullTask,
_process_remote_save,
_push_missing_saves,
_sync_device,
run_push_pull_sync,
sync_push_pull_task,
)
from tasks.tasks import PeriodicTask, TaskType
class TestSyncPushPullTaskInit:
@pytest.fixture
def task(self):
return SyncPushPullTask()
def test_init(self, task: SyncPushPullTask):
assert task.spec.title == "Push-Pull Sync"
assert task.spec.description == "Sync saves with devices via SSH/SFTP"
assert task.spec.task_type == TaskType.SYNC
def test_is_periodic_task(self, task: SyncPushPullTask):
assert isinstance(task, PeriodicTask)
def test_module_singleton_exists(self):
assert sync_push_pull_task is not None
assert isinstance(sync_push_pull_task, SyncPushPullTask)
def test_cron_string_set(self, task: SyncPushPullTask):
assert task.spec.cron_string is not None
class TestRunPushPullSync:
@patch(
"tasks.sync_push_pull_task.SYNC_PUSH_PULL_SPEC",
replace(SYNC_PUSH_PULL_SPEC, enabled=False),
)
async def test_run_disabled_returns_disabled(self):
from tasks.sync_push_pull_task import run_push_pull_sync
result = await run_push_pull_sync()
assert result["status"] == "disabled"
@patch(
"tasks.sync_push_pull_task.SYNC_PUSH_PULL_SPEC",
replace(SYNC_PUSH_PULL_SPEC, enabled=True),
)
@patch("tasks.sync_push_pull_task.db_device_handler")
async def test_run_no_devices(self, mock_device_handler):
from tasks.sync_push_pull_task import run_push_pull_sync
mock_device_handler.get_all_devices_by_sync_mode.return_value = []
result = await run_push_pull_sync()
assert result["status"] == "no_devices"
@patch(
"tasks.sync_push_pull_task.SYNC_PUSH_PULL_SPEC",
replace(SYNC_PUSH_PULL_SPEC, enabled=True),
)
@patch("tasks.sync_push_pull_task.db_device_handler")
async def test_run_device_not_found(self, mock_device_handler):
from tasks.sync_push_pull_task import run_push_pull_sync
mock_device_handler.get_device_by_id.return_value = None
result = await run_push_pull_sync(device_id="nonexistent")
assert result["status"] == "error"
assert "not found" in result["message"]
@patch(
"tasks.sync_push_pull_task.SYNC_PUSH_PULL_SPEC",
replace(SYNC_PUSH_PULL_SPEC, enabled=False),
)
async def test_run_force_override(self):
from tasks.sync_push_pull_task import run_push_pull_sync
with patch("tasks.sync_push_pull_task.db_device_handler") as mock_handler:
mock_handler.get_device_by_id.return_value = None
result = await run_push_pull_sync(device_id="test", force=True)
assert result["status"] == "error" # Device not found, but didn't skip
class TestNullSlotLeakInProcessRemoteSave:
"""Bug R1a: `_process_remote_save` selects the first save with matching
filename, including null-slot archival saves. This mirrors the negotiate
Invariant 2 leak — archival saves must never participate in device sync.
"""
@pytest.fixture
def device(self, admin_user: User) -> Device:
return db_device_handler.add_device(
Device(
id="pp-dev-1",
user_id=admin_user.id,
sync_mode=SyncMode.PUSH_PULL,
sync_enabled=True,
sync_config={"ssh_host": "1.2.3.4"},
)
)
async def test_remote_filename_does_not_match_null_slot_archival(
self,
device: Device,
admin_user: User,
rom: Rom,
platform: Platform,
archival_save: Save,
):
"""Only an archival (null-slot) save exists with the colliding name.
A remote file with that filename must NOT be paired with the archival
row. The function should treat this as 'no matching server save' and
return 'skipped' (it certainly must not write to the archival save).
"""
remote_save = RemoteSaveInfo(
path=f"/remote/{platform.fs_slug}/{archival_save.file_name}",
file_name=archival_save.file_name,
platform_slug=platform.fs_slug,
file_size=999,
mtime=datetime.now(timezone.utc),
)
ssh = MagicMock()
ssh.download_save = AsyncMock(
return_value=("/tmp/should_not_be_called", "deadbeef")
)
ssh.upload_save = AsyncMock()
with patch("tasks.sync_push_pull_task.get_ssh_sync_handler", return_value=ssh):
action = await _process_remote_save(
device,
conn=MagicMock(),
remote_save=remote_save,
session_id=1,
visibility=UNRESTRICTED,
)
# Archival rows must not be selected as a sync target.
assert action == "skipped"
# The archival row's bytes must be untouched.
refreshed = db_save_handler.get_save(user_id=admin_user.id, id=archival_save.id)
assert refreshed is not None
assert refreshed.content_hash == archival_save.content_hash
assert refreshed.file_size_bytes == archival_save.file_size_bytes
# And nothing should have been downloaded from the device for this row.
ssh.download_save.assert_not_called()
async def test_remote_filename_matches_slotted_save_when_archival_collides(
self,
device: Device,
admin_user: User,
rom: Rom,
platform: Platform,
save: Save,
):
"""When both an archival and a slotted save share the filename, the
function must pick the slotted save, not the archival row that appears
first in the unfiltered query result.
"""
# Create an additional archival (null-slot) save with the same filename
# as the slotted `save` fixture (test_save.sav). Insert it FIRST so the
# unfiltered iteration order favours it under the current bug.
archival = make_save(
rom,
admin_user,
save.file_name,
emulator=save.emulator,
slot=None,
file_path=save.file_path,
file_size_bytes=42,
content_hash="archival_hash_unique",
)
remote_save = RemoteSaveInfo(
path=f"/remote/{platform.fs_slug}/{save.file_name}",
file_name=save.file_name,
platform_slug=platform.fs_slug,
file_size=1,
mtime=datetime.now(timezone.utc),
)
ssh = MagicMock()
ssh.download_save = AsyncMock(
return_value=("/tmp/should_not_matter", save.content_hash or "x")
)
ssh.upload_save = AsyncMock()
with (
patch("tasks.sync_push_pull_task.get_ssh_sync_handler", return_value=ssh),
patch("tasks.sync_push_pull_task.fs_asset_handler"),
patch("tasks.sync_push_pull_task.compare_save_state") as mock_cmp,
patch("tasks.sync_push_pull_task.AnyioPath") as mock_anyio_path,
):
mock_cmp.return_value = MagicMock(action="no_op", reason=None)
mock_anyio_path.return_value.exists = AsyncMock(return_value=False)
await _process_remote_save(
device,
conn=MagicMock(),
remote_save=remote_save,
session_id=1,
visibility=UNRESTRICTED,
)
# compare_save_state should have been called with the SLOTTED save's
# hash, not the archival one. The bug picks the archival because it
# appears first in the unfiltered iteration.
kwargs = mock_cmp.call_args.kwargs
assert (
kwargs["server_hash"] != "archival_hash_unique"
), "archival null-slot save leaked into push-pull match path"
# Archival row must remain untouched regardless.
refreshed = db_save_handler.get_save(user_id=admin_user.id, id=archival.id)
assert refreshed is not None
assert refreshed.content_hash == "archival_hash_unique"
async def test_a_version_removed_since_the_device_wrote_it_is_replaced(
self, device: Device, admin_user: User, platform: Platform, save: Save
):
"""Newer than the server's save by its timestamp, yet lost since it was written."""
assert save.slot
db_save_handler.update_save(
save.id, {"updated_at": datetime(2020, 1, 1, tzinfo=timezone.utc)}
)
db_deleted_asset_handler.record_deletion(
admin_user.id, save.rom_id, save.slot, "removed_here"
)
remote_save = RemoteSaveInfo(
path=f"/remote/{platform.fs_slug}/{save.file_name}",
file_name=save.file_name,
platform_slug=platform.fs_slug,
file_size=1,
mtime=datetime(2021, 1, 1, tzinfo=timezone.utc),
)
ssh = MagicMock()
ssh.download_save = AsyncMock(return_value=("/tmp/unused", "removed_here"))
ssh.upload_save = AsyncMock()
with (
patch("tasks.sync_push_pull_task.get_ssh_sync_handler", return_value=ssh),
patch("tasks.sync_push_pull_task.fs_asset_handler"),
patch("tasks.sync_push_pull_task.AnyioPath") as mock_anyio_path,
):
mock_anyio_path.return_value.exists = AsyncMock(return_value=False)
action = await _process_remote_save(
device,
conn=MagicMock(),
remote_save=remote_save,
session_id=1,
visibility=UNRESTRICTED,
)
assert action == "pushed"
ssh.upload_save.assert_awaited_once()
class TestProcessRemoteSaveConflict:
async def test_conflict_names_the_matched_rom(
self, admin_user: User, rom: Rom, platform: Platform, save: Save
):
device = db_device_handler.add_device(
Device(
id="pp-dev-conflict",
user_id=admin_user.id,
sync_mode=SyncMode.PUSH_PULL,
sync_enabled=True,
sync_config={"ssh_host": "1.2.3.4"},
)
)
remote_save = RemoteSaveInfo(
path=f"/remote/{platform.fs_slug}/{save.file_name}",
file_name=save.file_name,
platform_slug=platform.fs_slug,
file_size=1,
mtime=datetime.now(timezone.utc),
)
ssh = MagicMock()
ssh.download_save = AsyncMock(return_value=("/tmp/pp-conflict", "remote"))
with (
patch("tasks.sync_push_pull_task.get_ssh_sync_handler", return_value=ssh),
patch("tasks.sync_push_pull_task.compare_save_state") as mock_cmp,
patch("tasks.sync_push_pull_task.AnyioPath") as mock_anyio_path,
patch(
"endpoints.sockets.sync.emit_sync_conflict", new_callable=AsyncMock
) as emit,
):
mock_cmp.return_value = MagicMock(action="conflict", reason="both changed")
mock_anyio_path.return_value.exists = AsyncMock(return_value=False)
action = await _process_remote_save(
device,
conn=MagicMock(),
remote_save=remote_save,
session_id=5,
visibility=UNRESTRICTED,
)
assert action == "conflict"
emit.assert_awaited_once_with(
user_id=admin_user.id,
device_id=device.id,
session_id=5,
file_name=save.file_name,
rom_id=rom.id,
rom_name="test_rom",
reason="both changed",
)
class TestNullSlotLeakInPushMissingSaves:
"""Bug R1b: `_push_missing_saves` iterates every Save for the platform,
including null-slot archival rows, and uploads them to the device.
"""
@pytest.fixture
def device(self, admin_user: User) -> Device:
return db_device_handler.add_device(
Device(
id="pp-dev-2",
user_id=admin_user.id,
sync_mode=SyncMode.PUSH_PULL,
sync_enabled=True,
sync_config={"ssh_host": "1.2.3.4"},
)
)
async def test_archival_save_is_not_pushed_to_device(
self,
device: Device,
admin_user: User,
platform: Platform,
save: Save,
archival_save: Save,
):
"""Only the slotted save should be uploaded. The null-slot archival
save must never be pushed to a device under push-pull sync.
"""
ssh = MagicMock()
ssh.upload_save = AsyncMock()
save_directories = [
{"platform_slug": platform.fs_slug, "path": "/remote/saves"}
]
# Empty remote_saves means every server save would be considered "missing".
with (
patch("tasks.sync_push_pull_task.get_ssh_sync_handler", return_value=ssh),
patch("tasks.sync_push_pull_task.fs_asset_handler") as mock_assets,
):
mock_assets.validate_path.side_effect = lambda p: f"/server/{p}"
pushed = await _push_missing_saves(
device,
conn=MagicMock(),
remote_saves=[],
save_directories=save_directories,
visibility=UNRESTRICTED,
)
uploaded_local_paths = [call.args[1] for call in ssh.upload_save.call_args_list]
# The archival file_name MUST NOT appear in any uploaded path.
assert not any(
archival_save.file_name in p for p in uploaded_local_paths
), f"archival save {archival_save.file_name} leaked into device push: {uploaded_local_paths}"
# The slotted save SHOULD have been pushed.
assert any(
save.file_name in p for p in uploaded_local_paths
), f"slotted save was not pushed: {uploaded_local_paths}"
# And the upload count should reflect slotted-only.
assert pushed == (1, 0)
class TestBaselineInProcessRemoteSave:
"""This path hashes the device's file itself, so it can record both halves."""
@pytest.fixture
def device(self, admin_user: User) -> Device:
return db_device_handler.add_device(
Device(
id="pp-baseline-dev",
user_id=admin_user.id,
sync_mode=SyncMode.PUSH_PULL,
sync_enabled=True,
sync_config={"ssh_host": "1.2.3.4"},
)
)
@pytest.fixture
def local_save_file(self, tmp_path) -> str:
path = tmp_path / "pp_baseline.sav"
path.write_bytes(b"remote save bytes")
return str(path)
@staticmethod
def _save(
admin_user: User, rom: Rom, platform: Platform, content_hash: str
) -> Save:
return make_save(
rom,
admin_user,
"pp_baseline.sav",
emulator="test_emulator",
slot="autosave",
file_path=f"{platform.slug}/saves/test_emulator",
file_size_bytes=100,
content_hash=content_hash,
)
@staticmethod
def _remote(platform: Platform) -> RemoteSaveInfo:
return RemoteSaveInfo(
path=f"/remote/{platform.fs_slug}/pp_baseline.sav",
file_name="pp_baseline.sav",
platform_slug=platform.fs_slug,
file_size=100,
mtime=datetime.now(timezone.utc),
)
@staticmethod
def _ssh(local_path: str, remote_hash: str) -> MagicMock:
ssh = MagicMock()
ssh.download_save = AsyncMock(return_value=(local_path, remote_hash))
ssh.upload_save = AsyncMock()
return ssh
async def test_comparison_receives_the_recorded_baseline(
self,
device: Device,
admin_user: User,
rom: Rom,
platform: Platform,
local_save_file: str,
):
save = self._save(admin_user, rom, platform, "server_old")
db_device_save_sync_handler.upsert_sync(
device.id,
save.id,
synced_at=datetime(2026, 1, 5, tzinfo=timezone.utc),
last_sync_hash="client_at_boundary",
last_sync_server_hash="server_at_boundary",
)
with (
patch("tasks.sync_push_pull_task.get_ssh_sync_handler") as mock_handler,
patch("tasks.sync_push_pull_task.compare_save_state") as mock_cmp,
):
mock_handler.return_value = self._ssh(local_save_file, "remote_now")
mock_cmp.return_value = MagicMock(action="no_op", reason=None)
await _process_remote_save(
device,
conn=MagicMock(),
remote_save=self._remote(platform),
session_id=1,
visibility=UNRESTRICTED,
)
kwargs = mock_cmp.call_args.kwargs
assert kwargs["device_last_sync_hash"] == "client_at_boundary"
assert kwargs["device_last_sync_server_hash"] == "server_at_boundary"
@pytest.mark.parametrize(
"server_hash,recorded",
[("remote_now", "remote_now"), ("server_hash", None)],
)
async def test_no_op_records_a_baseline_only_for_identical_content(
self,
device: Device,
admin_user: User,
rom: Rom,
platform: Platform,
local_save_file: str,
server_hash: str,
recorded: str | None,
):
"""A timestamp-only no-op must not record two different saves as in sync."""
save = self._save(admin_user, rom, platform, server_hash)
with (
patch("tasks.sync_push_pull_task.get_ssh_sync_handler") as mock_handler,
patch("tasks.sync_push_pull_task.compare_save_state") as mock_cmp,
):
mock_handler.return_value = self._ssh(local_save_file, "remote_now")
mock_cmp.return_value = MagicMock(action="no_op", reason=None)
await _process_remote_save(
device,
conn=MagicMock(),
remote_save=self._remote(platform),
session_id=1,
visibility=UNRESTRICTED,
)
sync = db_device_save_sync_handler.get_sync(device.id, save.id)
assert sync is not None
assert sync.last_sync_hash == recorded
assert sync.last_sync_server_hash == recorded
async def test_upload_records_both_halves_as_the_remote_hash(
self,
device: Device,
admin_user: User,
rom: Rom,
platform: Platform,
local_save_file: str,
):
save = self._save(admin_user, rom, platform, "server_old")
with (
patch("tasks.sync_push_pull_task.get_ssh_sync_handler") as mock_handler,
patch("tasks.sync_push_pull_task.compare_save_state") as mock_cmp,
patch("tasks.sync_push_pull_task.fs_asset_handler") as mock_assets,
):
mock_assets.write_file = AsyncMock()
mock_assets.unrecorded_hash = AsyncMock(return_value=None)
mock_handler.return_value = self._ssh(local_save_file, "remote_now")
mock_cmp.return_value = MagicMock(action="upload", reason=None)
await _process_remote_save(
device,
conn=MagicMock(),
remote_save=self._remote(platform),
session_id=1,
visibility=UNRESTRICTED,
)
sync = db_device_save_sync_handler.get_sync(device.id, save.id)
assert sync is not None
assert sync.last_sync_hash == "remote_now"
assert sync.last_sync_server_hash == "remote_now"
async def test_download_records_the_pushed_file_as_both_halves(
self,
device: Device,
admin_user: User,
rom: Rom,
platform: Platform,
local_save_file: str,
):
save = self._save(admin_user, rom, platform, "server_new")
with (
patch("tasks.sync_push_pull_task.get_ssh_sync_handler") as mock_handler,
patch("tasks.sync_push_pull_task.compare_save_state") as mock_cmp,
patch("tasks.sync_push_pull_task.fs_asset_handler"),
):
mock_handler.return_value = self._ssh(local_save_file, "remote_old")
mock_cmp.return_value = MagicMock(action="download", reason=None)
await _process_remote_save(
device,
conn=MagicMock(),
remote_save=self._remote(platform),
session_id=1,
visibility=UNRESTRICTED,
)
sync = db_device_save_sync_handler.get_sync(device.id, save.id)
assert sync is not None
assert sync.last_sync_hash == "server_new"
assert sync.last_sync_server_hash == "server_new"
async def test_conflict_records_nothing(
self,
device: Device,
admin_user: User,
rom: Rom,
platform: Platform,
local_save_file: str,
):
save = self._save(admin_user, rom, platform, "server_hash")
db_device_save_sync_handler.upsert_sync(
device.id,
save.id,
synced_at=datetime(2026, 1, 5, tzinfo=timezone.utc),
last_sync_hash="client_at_boundary",
last_sync_server_hash="server_at_boundary",
)
with (
patch("tasks.sync_push_pull_task.get_ssh_sync_handler") as mock_handler,
patch("tasks.sync_push_pull_task.compare_save_state") as mock_cmp,
):
mock_handler.return_value = self._ssh(local_save_file, "remote_now")
mock_cmp.return_value = MagicMock(action="conflict", reason="both changed")
action = await _process_remote_save(
device,
conn=MagicMock(),
remote_save=self._remote(platform),
session_id=1,
visibility=UNRESTRICTED,
)
assert action == "conflict"
sync = db_device_save_sync_handler.get_sync(device.id, save.id)
assert sync is not None
assert sync.last_sync_hash == "client_at_boundary"
assert sync.last_sync_server_hash == "server_at_boundary"
async def test_push_missing_saves_records_the_pushed_file_as_both_halves(
self,
device: Device,
admin_user: User,
rom: Rom,
platform: Platform,
):
save = self._save(admin_user, rom, platform, "server_hash")
with (
patch("tasks.sync_push_pull_task.get_ssh_sync_handler") as mock_handler,
patch("tasks.sync_push_pull_task.fs_asset_handler") as mock_assets,
):
mock_handler.return_value = self._ssh("/tmp/unused.sav", "unused")
mock_assets.validate_path.side_effect = lambda p: f"/server/{p}"
pushed = await _push_missing_saves(
device,
conn=MagicMock(),
remote_saves=[],
save_directories=[
{"platform_slug": platform.fs_slug, "path": "/remote/saves"}
],
visibility=UNRESTRICTED,
)
assert pushed == (1, 0)
sync = db_device_save_sync_handler.get_sync(device.id, save.id)
assert sync is not None
assert sync.last_sync_hash == "server_hash"
assert sync.last_sync_server_hash == "server_hash"
async def test_push_missing_saves_counts_a_failed_upload(
self,
device: Device,
admin_user: User,
rom: Rom,
platform: Platform,
):
self._save(admin_user, rom, platform, "server_hash")
ssh = self._ssh("/tmp/unused.sav", "unused")
ssh.upload_save = AsyncMock(side_effect=OSError("device full"))
with (
patch("tasks.sync_push_pull_task.get_ssh_sync_handler", return_value=ssh),
patch("tasks.sync_push_pull_task.fs_asset_handler") as mock_assets,
):
mock_assets.validate_path.side_effect = lambda p: f"/server/{p}"
result = await _push_missing_saves(
device,
conn=MagicMock(),
remote_saves=[],
save_directories=[
{"platform_slug": platform.fs_slug, "path": "/remote/saves"}
],
visibility=UNRESTRICTED,
)
assert result == (0, 1)
def _remote(file_name: str) -> RemoteSaveInfo:
return RemoteSaveInfo(
path=f"/saves/gba/{file_name}",
file_name=file_name,
platform_slug="gba",
file_size=1,
mtime=datetime(2026, 1, 1, tzinfo=timezone.utc),
)
class TestSyncDevice:
SAVE_DIRECTORIES = [{"platform_slug": "gba", "path": "/saves/gba"}]
@pytest.fixture
def device(self, admin_user: User) -> Device:
return db_device_handler.add_device(
Device(
id="push-pull-deck",
user_id=admin_user.id,
sync_mode=SyncMode.PUSH_PULL,
sync_enabled=True,
sync_config={
"ssh_host": "deck.local",
"save_directories": self.SAVE_DIRECTORIES,
},
)
)
@pytest.fixture
def conn(self) -> MagicMock:
return MagicMock()
@pytest.fixture
def ssh(self, mocker, conn: MagicMock) -> MagicMock:
handler = MagicMock()
handler.connect = AsyncMock(return_value=conn)
handler.list_remote_saves = AsyncMock(return_value=[])
mocker.patch.object(push_pull, "get_ssh_sync_handler", return_value=handler)
return handler
@pytest.fixture
def emitted(self, mocker) -> dict[str, AsyncMock]:
return {
name: mocker.patch.object(sync_sockets, f"emit_sync_{name}", AsyncMock())
for name in ("started", "progress", "completed", "error")
}
@pytest.fixture
def process(self, mocker):
return mocker.patch.object(
push_pull, "_process_remote_save", AsyncMock(return_value="pulled")
)
@pytest.fixture
def push_missing(self, mocker):
return mocker.patch.object(
push_pull, "_push_missing_saves", AsyncMock(return_value=(0, 0))
)
@staticmethod
def _sessions(device: Device):
return db_sync_session_handler.get_sessions(
user_id=device.user_id, device_id=device.id
)
async def test_syncs_each_remote_save_and_pushes_the_missing_ones(
self, device, ssh, conn, emitted, process, push_missing
):
ssh.list_remote_saves.return_value = [_remote("a.srm"), _remote("b.srm")]
process.side_effect = ["pulled", "pushed"]
push_missing.return_value = (1, 0)
result = await _sync_device(device)
assert result == {
"device_id": device.id,
"status": "completed",
"completed": 3,
"failed": 0,
}
ssh.connect.assert_awaited_once_with(device.sync_config, device_id=device.id)
ssh.list_remote_saves.assert_awaited_once_with(conn, self.SAVE_DIRECTORIES)
[session] = self._sessions(device)
assert session.status == SyncSessionStatus.COMPLETED
assert (session.operations_planned, session.operations_completed) == (3, 3)
assert emitted["progress"].await_count == 2
emitted["completed"].assert_awaited_once()
emitted["error"].assert_not_awaited()
conn.close.assert_called_once()
refreshed = db_device_handler.get_device_by_id(device.id)
assert refreshed and refreshed.last_seen is not None
async def test_a_failing_save_is_counted_and_the_rest_still_sync(
self, device, ssh, conn, emitted, process, push_missing
):
ssh.list_remote_saves.return_value = [_remote("bad.srm"), _remote("ok.srm")]
process.side_effect = [OSError("disk full"), "pushed"]
result = await _sync_device(device)
assert (result["completed"], result["failed"]) == (1, 1)
assert process.await_count == 2
[session] = self._sessions(device)
assert session.status == SyncSessionStatus.COMPLETED
assert session.operations_failed == 1
async def test_a_failed_push_of_a_missing_save_is_counted(
self, device, ssh, emitted, process, push_missing
):
ssh.list_remote_saves.return_value = [_remote("a.srm")]
push_missing.return_value = (1, 2)
result = await _sync_device(device)
assert (result["completed"], result["failed"]) == (2, 2)
[session] = self._sessions(device)
assert session.operations_planned == 4
assert (session.operations_completed, session.operations_failed) == (2, 2)
async def test_a_connection_failure_fails_the_session(
self, device, ssh, emitted, process
):
ssh.connect.side_effect = OSError("host unreachable")
result = await _sync_device(device)
assert result == {
"device_id": device.id,
"status": "connection_failed",
"error": "host unreachable",
}
[session] = self._sessions(device)
assert session.status == SyncSessionStatus.FAILED
assert session.error_message == "host unreachable"
emitted["error"].assert_awaited_once()
process.assert_not_awaited()
async def test_a_listing_failure_fails_the_session_and_closes_the_connection(
self, device, ssh, conn, emitted
):
ssh.list_remote_saves.side_effect = OSError("sftp subsystem missing")
result = await _sync_device(device)
assert result["status"] == "failed"
[session] = self._sessions(device)
assert session.status == SyncSessionStatus.FAILED
emitted["error"].assert_awaited_once()
emitted["completed"].assert_not_awaited()
conn.close.assert_called_once()
async def test_without_save_directories_there_is_nothing_to_do(
self, device, ssh, conn, emitted
):
db_device_handler.update_device(
device_id=device.id,
user_id=device.user_id,
data={"sync_config": {"ssh_host": "deck.local"}},
)
bare = db_device_handler.get_device_by_id(device.id)
assert bare
result = await _sync_device(bare)
assert result == {"device_id": device.id, "status": "no_directories"}
ssh.list_remote_saves.assert_not_awaited()
[session] = self._sessions(device)
assert session.status == SyncSessionStatus.COMPLETED
conn.close.assert_called_once()
async def test_without_a_host_nothing_is_attempted(self, device, ssh, emitted):
db_device_handler.update_device(
device_id=device.id, user_id=device.user_id, data={"sync_config": {}}
)
hostless = db_device_handler.get_device_by_id(device.id)
assert hostless
result = await _sync_device(hostless)
assert result["status"] == "error"
ssh.connect.assert_not_awaited()
assert self._sessions(device) == []
async def test_a_disabled_owner_syncs_nothing(self, device, ssh, emitted):
db_user_handler.update_user(device.user_id, {"enabled": False})
result = await _sync_device(device)
assert result == {
"device_id": device.id,
"status": "error",
"message": "No owner",
}
ssh.connect.assert_not_awaited()
async def test_reuses_the_session_the_trigger_created(
self, device, ssh, emitted, process, push_missing
):
queued = db_sync_session_handler.create_session(
device_id=device.id, user_id=device.user_id
)
await _sync_device(device, session_id=queued.id)
[session] = self._sessions(device)
assert session.id == queued.id
assert session.status == SyncSessionStatus.COMPLETED
async def test_an_unknown_session_gets_a_new_one(
self, device, ssh, emitted, process, push_missing
):
await _sync_device(device, session_id=999_999)
[session] = self._sessions(device)
assert session.id != 999_999
assert session.status == SyncSessionStatus.COMPLETED
class TestRunPushPullSyncDevices:
@pytest.fixture
def sync_device(self, mocker):
return mocker.patch.object(
push_pull, "_sync_device", AsyncMock(return_value={"status": "completed"})
)
def _device(self, user: User, device_id: str, enabled: bool) -> Device:
return db_device_handler.add_device(
Device(
id=device_id,
user_id=user.id,
sync_mode=SyncMode.PUSH_PULL,
sync_enabled=enabled,
)
)
async def test_syncs_only_enabled_push_pull_devices(
self, admin_user: User, sync_device: AsyncMock
):
self._device(admin_user, "on", enabled=True)
self._device(admin_user, "off", enabled=False)
result = await run_push_pull_sync(force=True)
assert result["status"] == "completed"
assert [c.args[0].id for c in sync_device.await_args_list] == ["on"]
async def test_a_named_device_passes_its_session_along(
self, admin_user: User, sync_device: AsyncMock
):
self._device(admin_user, "deck", enabled=True)
await run_push_pull_sync(device_id="deck", session_id=7, force=True)
call = sync_device.await_args
assert call is not None
assert (call.args[0].id, call.kwargs["session_id"]) == ("deck", 7)
def _owner_visibility(user: User) -> RomVisibilityFilter:
return db_permission_handler.get_user_visibilities([user.id])[user.id]
class TestRomsHiddenFromTheOwner:
@pytest.fixture
def device(self, viewer_user: User) -> Device:
return db_device_handler.add_device(
Device(
id="pp-hidden",
user_id=viewer_user.id,
sync_mode=SyncMode.PUSH_PULL,
sync_enabled=True,
sync_config={"ssh_host": "1.2.3.4"},
)
)
@pytest.fixture
def ssh(self, mocker) -> MagicMock:
handler = MagicMock()
handler.download_save = AsyncMock(return_value=("/tmp/unused", "remote"))
handler.upload_save = AsyncMock()
mocker.patch.object(push_pull, "get_ssh_sync_handler", return_value=handler)
mocker.patch.object(push_pull, "fs_asset_handler")
return handler
@staticmethod
def _hide(rom: Rom, user: User) -> None:
with sync_session.begin() as s:
s.add(
HiddenEntity(entity=PermEntity.ROMS, entity_id=rom.id, user_id=user.id)
)
async def test_a_hidden_roms_save_is_not_pulled(
self, device: Device, viewer_user: User, rom: Rom, platform: Platform, ssh
):
save = make_save(rom, viewer_user, "hidden.sav", slot="autosave")
self._hide(rom, viewer_user)
remote_save = RemoteSaveInfo(
path=f"/remote/{save.file_name}",
file_name=save.file_name,
platform_slug=platform.fs_slug,
file_size=1,
mtime=datetime(2099, 1, 1, tzinfo=timezone.utc),
)
action = await _process_remote_save(
device,
conn=MagicMock(),
remote_save=remote_save,
session_id=1,
visibility=_owner_visibility(viewer_user),
)
assert action == "skipped"
ssh.download_save.assert_not_awaited()
async def test_a_hidden_roms_save_is_not_pushed(
self, device: Device, viewer_user: User, rom: Rom, platform: Platform, ssh
):
make_save(rom, viewer_user, "hidden.sav", slot="autosave")
self._hide(rom, viewer_user)
pushed = await _push_missing_saves(
device,
conn=MagicMock(),
remote_saves=[],
save_directories=[{"platform_slug": platform.fs_slug, "path": "/r"}],
visibility=_owner_visibility(viewer_user),
)
assert pushed == (0, 0)
ssh.upload_save.assert_not_awaited()
async def test_a_rom_above_the_owners_age_limit_is_not_pushed(
self, device: Device, viewer_user: User, platform: Platform, ssh
):
mature = make_esrb_rated_rom(platform, "Mature", "M")
make_save(mature, viewer_user, "mature.sav", slot="autosave")
db_user_handler.update_user(viewer_user.id, {"age_limit": 12})
pushed = await _push_missing_saves(
device,
conn=MagicMock(),
remote_saves=[],
save_directories=[{"platform_slug": platform.fs_slug, "path": "/r"}],
visibility=_owner_visibility(viewer_user),
)
assert pushed == (0, 0)
ssh.upload_save.assert_not_awaited()