mirror of
https://github.com/rommapp/romm.git
synced 2026-11-29 10:01:00 +01:00
* feat(saves): add save channels and snapshots * feat(saves): close spec gaps in save channels and hash with sigil * feat(saves): play snapshots in the v2 player, which pushes snapshots * fix(saves): code review: authorization, retention losses, held-save sync, batched responses * refactor(saves): simplify pass * refactor(saves): review-polish pass * docs(saves): humanizer pass * feat(saves): run every EmulatorJS page on the v2 player * feat(saves): per-user snapshot pins * feat(sigil): store the identity a save restore needs and pin sigil 0f05f25 * fix(saves): meet type-aware lint in the v2 player * feat(sigil): store N64 header and playlist title ids, pin sigil 0847fda * feat(saves): convert saves for a core on download and list save layouts * feat(saves): prune unreachable archival snapshots and empty detached channels on delete * feat(saves): device sync from the token, held snapshots and shared-card pushes * feat(saves): arc restores past abandoned snapshots and color channels by age * fix(saves): code-review and security-audit fixes * refactor(saves): simplify pass * chore(saves): review-polish pass * docs(saves): humanizer pass * fix(sync): file RetroArch autosave versions as their channel's next snapshot * fix(saves): address review findings and trim docstrings * fix(saves): share-lock planned rows by id so PostgreSQL accepts the lock * test(saves): stub the detached-channels fetch in SaveDataTab stories * feat(saves): carry the full current snapshot in a 409, pin sigil 2071dff * chore(sigil): pin 5d4ddb4, which reads .cue and .gdi sheets * docs(saves): drop v2 wording now that one UI remains * chore(sigil): pin 0190443, which reads PS2 raw BIN images and cue sheets * fix(sigil): treat a file too short for its format as routine during scans * chore(migrations): renumber save channel migrations after upstream's 0154 * fix(snapshots): a hardcore switch on unchanged content makes a new current * fix(sync): decide a channel's slot from its history and the device's snapshot * chore(docker): pin sigil at 794d99f for PSP Store release save prefixes * refactor(db): squash the save channel migrations into 0161 Fold the slot linking (0162) and the rom_files sigil identity columns (0163) into 0161_save_channels, so the feature ships as one revision. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(saves): close visibility and input gaps found in review (pr-ready step 2) code-review --fix: - negotiate_sync drops channel slots on ROMs hidden from the caller - channel PATCH/attach/DELETE answer 404 when the channel's ROM is hidden - a push copying a save from a hidden ROM answers 404 - _own_device applies require_token_device to bound client tokens - adopting a legacy save syncs its sharing with the channel it joins security-audit follow-ups: - another user's detached public save or state is no longer downloadable - profile and option values must be a single path segment - companions are de-duplicated and capped at 8 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor(saves): share channel and asset lookups, drop duplicates (pr-ready step 3) simplify: - readable_channel_or_404 and channels_on_files replace four copies of the channel 404 check and two copies of the file-fed channel listing - readable_rom_asset_or_404 serves both public save and state downloads - _own_device resolves through require_device; _clone_origin takes the source - reuse _unprocessable, DESCRIPTOR_EXTENSIONS, SAVE_SLOT_MAX_LENGTH, uniqueBy and uuidv7; neutral forms default their required pattern to the allowed one - RetroArch delete checks held rows in one query, a guarded upload lists the slot only without a channel head, and uploads are read off the event loop - snapshotSession builds push requests once; player comment cleanups Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs(saves): trim two docstrings to two lines (pr-ready step 4) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(saves): answer held RetroArch paths with 423, mirror slot labels - RetroArch Cloud Sync answers 423 Locked for a PUT over a held unslotted save and for a DELETE where only held rows sit at the path, instead of 409 and 404 - channelLabelForSlot returns null for blank and state_ slots, as the backend's channel_label does, so the player files them under no channel either - document that sharing a channel lets every user read and push into it Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * chore(docker): pin sigil at 85f88a8 for Switch .nup containers * fix(snapshots): a save pushed in another shape or format makes a new current * refactor(saves): drop the always-true SAVE_SYNC.SNAPSHOTS heartbeat flag Nothing reads it, and the SAVE_SYNC block's presence already tells a client the server speaks the snapshot API. Also trim the rom detail channel field comments to one line each. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor(frontend): use uuidv7 for every client-generated id Drop the randomToken wrapper and the notification inbox's Math.random tab id, so uuidv7 is the one helper that works outside a secure context. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor(saves): trim redundant snapshot API surface, dead code and duplicate logic API: - Drop PUT /snapshots/{id}/devices/{device_id}; GET /snapshots/{id}?hold=true holds. - GET /snapshots is history only (channel_id required); GET /channels serves currents. - A snapshot carries channel_id instead of an embedded channel. - POST /saves/{id}/content takes the same query parameters as the GET, plus container_path. Backend: - Remove the archival write path, clone.py, DBStatesHandler.get_state, the sigil identity-hash path, unused relationships and composite snapshot indexes. - One held/frozen lookup, one bulk-delete guard, SQLAlchemy dialect upserts, and the shared reserve_version_name in the writer. - The writer takes a visibility filter and checks the channel and parent itself. - The restore handler picks per-game or merge; fewer wrapper types and tables. Frontend: - Channel delete uses the shared typed confirm; DeleteChannelDialog is gone. - Held offline pushes go through a per-channel SnapshotSession. - Remove the slot-based pending upload path. - The timeline shares the fan's badge logic. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * refactor(saves): release archival backups through module functions The saves and states handlers each built a private DBSnapshotsHandler to call release_backup and refresh_backup_digests, since they can't import the shared instance. Both only ever ran inside the caller's session, so they are now module functions taking it, like channel_for_slot. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * refactor(saves): share one deleted-assets handler instance The saves handler built its own DBDeletedAssetsHandler because it can't import the package's instance. The instance is now built in deleted_assets_handler.py and re-exported by the package, so both use it. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --------- Co-authored-by: Georges-Antoine Assi <contact@me.gantoine.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
715 lines
25 KiB
Python
715 lines
25 KiB
Python
import hashlib
|
|
import io
|
|
import os
|
|
import shutil
|
|
import tempfile
|
|
import zipfile
|
|
from pathlib import Path
|
|
from unittest.mock import Mock
|
|
|
|
import pytest
|
|
from tests._zipfile_shim import reload_zipfile
|
|
|
|
from config import ASSETS_BASE_PATH
|
|
from handler.filesystem import assets_handler
|
|
from handler.filesystem.assets_handler import (
|
|
FSAssetsHandler,
|
|
hash_save_content,
|
|
hash_save_file,
|
|
)
|
|
from models.user import User
|
|
|
|
|
|
class TestFSAssetsHandler:
|
|
"""Test suite for FSAssetsHandler class"""
|
|
|
|
@pytest.fixture
|
|
def handler(self):
|
|
return FSAssetsHandler()
|
|
|
|
def test_init_uses_assets_base_path(self, handler: FSAssetsHandler):
|
|
"""Test that FSAssetsHandler initializes with ASSETS_BASE_PATH"""
|
|
assert handler.base_path == Path(ASSETS_BASE_PATH).resolve()
|
|
|
|
def test_user_folder_path(self, handler: FSAssetsHandler, editor_user: User):
|
|
"""Test user_folder_path method"""
|
|
result = handler.user_folder_path(editor_user)
|
|
expected = os.path.join("users", editor_user.fs_safe_folder_name)
|
|
assert result == expected
|
|
|
|
def test_build_avatar_path(self, handler: FSAssetsHandler, editor_user: User):
|
|
"""Test build_avatar_path method"""
|
|
result = handler.build_avatar_path(editor_user)
|
|
expected = os.path.join("users", editor_user.fs_safe_folder_name, "profile")
|
|
assert result == expected
|
|
|
|
def test_build_saves_file_path_without_emulator(
|
|
self, handler: FSAssetsHandler, editor_user: User
|
|
):
|
|
"""Test build_saves_file_path method without emulator"""
|
|
platform_fs_slug = "n64"
|
|
rom_id = 456
|
|
|
|
result = handler.build_saves_file_path(
|
|
user=editor_user, platform_fs_slug=platform_fs_slug, rom_id=rom_id
|
|
)
|
|
|
|
expected = os.path.join(
|
|
"users",
|
|
editor_user.fs_safe_folder_name,
|
|
"saves",
|
|
platform_fs_slug,
|
|
str(rom_id),
|
|
)
|
|
assert result == expected
|
|
|
|
def test_build_saves_file_path_with_emulator(
|
|
self, handler: FSAssetsHandler, editor_user: User
|
|
):
|
|
"""Test build_saves_file_path method with emulator"""
|
|
platform_fs_slug = "n64"
|
|
rom_id = 456
|
|
emulator = "mupen64plus"
|
|
|
|
result = handler.build_saves_file_path(
|
|
user=editor_user,
|
|
platform_fs_slug=platform_fs_slug,
|
|
rom_id=rom_id,
|
|
emulator=emulator,
|
|
)
|
|
|
|
expected = os.path.join(
|
|
"users",
|
|
editor_user.fs_safe_folder_name,
|
|
"saves",
|
|
platform_fs_slug,
|
|
str(rom_id),
|
|
emulator,
|
|
)
|
|
assert result == expected
|
|
|
|
def test_build_states_file_path_without_emulator(
|
|
self, handler: FSAssetsHandler, editor_user: User
|
|
):
|
|
"""Test build_states_file_path method without emulator"""
|
|
platform_fs_slug = "snes"
|
|
rom_id = 789
|
|
|
|
result = handler.build_states_file_path(
|
|
user=editor_user, platform_fs_slug=platform_fs_slug, rom_id=rom_id
|
|
)
|
|
|
|
expected = os.path.join(
|
|
"users",
|
|
editor_user.fs_safe_folder_name,
|
|
"states",
|
|
platform_fs_slug,
|
|
str(rom_id),
|
|
)
|
|
assert result == expected
|
|
|
|
def test_build_states_file_path_with_emulator(
|
|
self, handler: FSAssetsHandler, editor_user: User
|
|
):
|
|
"""Test build_states_file_path method with emulator"""
|
|
platform_fs_slug = "snes"
|
|
rom_id = 789
|
|
emulator = "snes9x"
|
|
|
|
result = handler.build_states_file_path(
|
|
user=editor_user,
|
|
platform_fs_slug=platform_fs_slug,
|
|
rom_id=rom_id,
|
|
emulator=emulator,
|
|
)
|
|
|
|
expected = os.path.join(
|
|
"users",
|
|
editor_user.fs_safe_folder_name,
|
|
"states",
|
|
platform_fs_slug,
|
|
str(rom_id),
|
|
emulator,
|
|
)
|
|
assert result == expected
|
|
|
|
def test_build_screenshots_file_path(
|
|
self, handler: FSAssetsHandler, editor_user: User
|
|
):
|
|
"""Test build_screenshots_file_path method"""
|
|
platform_fs_slug = "psx"
|
|
rom_id = 101
|
|
|
|
result = handler.build_screenshots_file_path(
|
|
user=editor_user, platform_fs_slug=platform_fs_slug, rom_id=rom_id
|
|
)
|
|
|
|
expected = os.path.join(
|
|
"users",
|
|
editor_user.fs_safe_folder_name,
|
|
"screenshots",
|
|
platform_fs_slug,
|
|
str(rom_id),
|
|
)
|
|
assert result == expected
|
|
|
|
def test_build_asset_file_path_internal_method(
|
|
self, handler: FSAssetsHandler, editor_user: User
|
|
):
|
|
"""Test _build_asset_file_path internal method"""
|
|
folder = "custom_folder"
|
|
platform_fs_slug = "gba"
|
|
rom_id = 999
|
|
emulator = "mgba"
|
|
|
|
result = handler._build_asset_file_path(
|
|
user=editor_user,
|
|
folder=folder,
|
|
platform_fs_slug=platform_fs_slug,
|
|
rom_id=rom_id,
|
|
emulator=emulator,
|
|
)
|
|
|
|
expected = os.path.join(
|
|
"users",
|
|
editor_user.fs_safe_folder_name,
|
|
folder,
|
|
platform_fs_slug,
|
|
str(rom_id),
|
|
emulator,
|
|
)
|
|
assert result == expected
|
|
|
|
def test_build_asset_file_path_without_emulator(
|
|
self, handler: FSAssetsHandler, editor_user: User
|
|
):
|
|
"""Test _build_asset_file_path internal method without emulator"""
|
|
folder = "custom_folder"
|
|
platform_fs_slug = "gba"
|
|
rom_id = 999
|
|
|
|
result = handler._build_asset_file_path(
|
|
user=editor_user,
|
|
folder=folder,
|
|
platform_fs_slug=platform_fs_slug,
|
|
rom_id=rom_id,
|
|
)
|
|
|
|
expected = os.path.join(
|
|
"users",
|
|
editor_user.fs_safe_folder_name,
|
|
folder,
|
|
platform_fs_slug,
|
|
str(rom_id),
|
|
)
|
|
assert result == expected
|
|
|
|
def test_integration_with_real_user_fixture(
|
|
self, handler: FSAssetsHandler, admin_user: User
|
|
):
|
|
"""Test integration with real user fixture from the project"""
|
|
platform_fs_slug = "n64"
|
|
rom_id = 123
|
|
emulator = "mupen64plus"
|
|
|
|
# Test saves path
|
|
saves_path = handler.build_saves_file_path(
|
|
user=admin_user,
|
|
platform_fs_slug=platform_fs_slug,
|
|
rom_id=rom_id,
|
|
emulator=emulator,
|
|
)
|
|
|
|
assert saves_path.startswith("users/")
|
|
assert platform_fs_slug in saves_path
|
|
assert str(rom_id) in saves_path
|
|
assert emulator in saves_path
|
|
|
|
# Test states path
|
|
states_path = handler.build_states_file_path(
|
|
user=admin_user,
|
|
platform_fs_slug=platform_fs_slug,
|
|
rom_id=rom_id,
|
|
emulator=emulator,
|
|
)
|
|
|
|
assert states_path.startswith("users/")
|
|
assert platform_fs_slug in states_path
|
|
assert str(rom_id) in states_path
|
|
assert emulator in states_path
|
|
|
|
# Test screenshots path
|
|
screenshots_path = handler.build_screenshots_file_path(
|
|
user=admin_user, platform_fs_slug=platform_fs_slug, rom_id=rom_id
|
|
)
|
|
|
|
assert screenshots_path.startswith("users/")
|
|
assert platform_fs_slug in screenshots_path
|
|
assert str(rom_id) in screenshots_path
|
|
|
|
# Test avatar path
|
|
avatar_path = handler.build_avatar_path(admin_user)
|
|
assert avatar_path.startswith("users/")
|
|
assert "profile" in avatar_path
|
|
|
|
def test_paths_are_relative_to_base_path(
|
|
self, handler: FSAssetsHandler, editor_user: User
|
|
):
|
|
"""Test that all generated paths are relative to the base path"""
|
|
platform_fs_slug = "ps1"
|
|
rom_id = 555
|
|
emulator = "duckstation"
|
|
|
|
# Test various path methods
|
|
paths = [
|
|
handler.user_folder_path(editor_user),
|
|
handler.build_avatar_path(editor_user),
|
|
handler.build_saves_file_path(editor_user, platform_fs_slug, rom_id),
|
|
handler.build_saves_file_path(
|
|
editor_user, platform_fs_slug, rom_id, emulator
|
|
),
|
|
handler.build_states_file_path(editor_user, platform_fs_slug, rom_id),
|
|
handler.build_states_file_path(
|
|
editor_user, platform_fs_slug, rom_id, emulator
|
|
),
|
|
handler.build_screenshots_file_path(editor_user, platform_fs_slug, rom_id),
|
|
]
|
|
|
|
for path in paths:
|
|
# Ensure paths are relative (don't start with /)
|
|
assert not os.path.isabs(path), f"Path should be relative: {path}"
|
|
|
|
# Ensure paths can be resolved within the base path
|
|
full_path = handler.validate_path(path)
|
|
assert full_path.is_relative_to(handler.base_path)
|
|
|
|
def test_different_users_have_different_paths(self, handler: FSAssetsHandler):
|
|
"""Test that different users get different folder paths"""
|
|
user1 = Mock(spec=User)
|
|
user1.id = 1
|
|
user1.fs_safe_folder_name = "User:1".encode().hex()
|
|
|
|
user2 = Mock(spec=User)
|
|
user2.id = 2
|
|
user2.fs_safe_folder_name = "User:2".encode().hex()
|
|
|
|
path1 = handler.user_folder_path(user1)
|
|
path2 = handler.user_folder_path(user2)
|
|
|
|
assert path1 != path2
|
|
assert user1.fs_safe_folder_name in path1
|
|
assert user2.fs_safe_folder_name in path2
|
|
|
|
def test_rom_id_conversion_to_string(
|
|
self, handler: FSAssetsHandler, editor_user: User
|
|
):
|
|
"""Test that rom_id is properly converted to string in paths"""
|
|
platform_fs_slug = "dc"
|
|
rom_id = 12345
|
|
|
|
saves_path = handler.build_saves_file_path(
|
|
user=editor_user, platform_fs_slug=platform_fs_slug, rom_id=rom_id
|
|
)
|
|
|
|
assert str(rom_id) in saves_path
|
|
assert saves_path.endswith(str(rom_id))
|
|
|
|
def test_emulator_parameter_handling(
|
|
self, handler: FSAssetsHandler, editor_user: User
|
|
):
|
|
"""Test that emulator parameter is handled consistently"""
|
|
platform_fs_slug = "ps2"
|
|
rom_id = 777
|
|
emulator = "pcsx2"
|
|
|
|
# Test with emulator
|
|
saves_with_emulator = handler.build_saves_file_path(
|
|
user=editor_user,
|
|
platform_fs_slug=platform_fs_slug,
|
|
rom_id=rom_id,
|
|
emulator=emulator,
|
|
)
|
|
|
|
# Test without emulator
|
|
saves_without_emulator = handler.build_saves_file_path(
|
|
user=editor_user, platform_fs_slug=platform_fs_slug, rom_id=rom_id
|
|
)
|
|
|
|
assert emulator in saves_with_emulator
|
|
assert emulator not in saves_without_emulator
|
|
assert saves_with_emulator.startswith(saves_without_emulator)
|
|
|
|
|
|
class TestComputeContentHash:
|
|
"""Regression coverage for compute_content_hash dispatch."""
|
|
|
|
@pytest.fixture
|
|
def temp_base(self):
|
|
path = tempfile.mkdtemp()
|
|
yield path
|
|
shutil.rmtree(path, ignore_errors=True)
|
|
|
|
@pytest.fixture
|
|
def handler(self, temp_base: str):
|
|
handler = FSAssetsHandler()
|
|
handler.base_path = Path(temp_base).resolve()
|
|
return handler
|
|
|
|
@staticmethod
|
|
def _expected_zip_hash(zip_path: Path) -> str:
|
|
with zipfile.ZipFile(zip_path, "r") as zf:
|
|
file_hashes = [
|
|
f"{n}:{hashlib.md5(zf.read(n), usedforsecurity=False).hexdigest()}"
|
|
for n in sorted(zf.namelist())
|
|
if not n.endswith("/")
|
|
]
|
|
combined = "\n".join(file_hashes)
|
|
return hashlib.md5(combined.encode(), usedforsecurity=False).hexdigest()
|
|
|
|
@staticmethod
|
|
def _raw_md5(path: Path) -> str:
|
|
h = hashlib.md5(usedforsecurity=False)
|
|
with open(path, "rb") as f:
|
|
while chunk := f.read(8192):
|
|
h.update(chunk)
|
|
return h.hexdigest()
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_zip_dispatches_to_per_entry_hash(
|
|
self, handler: FSAssetsHandler, temp_base: str
|
|
):
|
|
"""A zip file's content_hash must equal the per-entry zip-hash, not raw MD5.
|
|
|
|
Regression for the path-resolution bug where compute_content_hash called
|
|
zipfile.is_zipfile() with a bare relative path. Because the server WORKDIR
|
|
is not ASSETS_BASE_PATH, that open() failed silently, is_zipfile returned
|
|
False, and the dispatch fell through to _compute_file_hash (raw MD5) for
|
|
every zip save.
|
|
"""
|
|
relative = "users/test/saves/test.zip"
|
|
zip_full = Path(temp_base) / relative
|
|
zip_full.parent.mkdir(parents=True, exist_ok=True)
|
|
reload_zipfile()
|
|
with zipfile.ZipFile(zip_full, "w") as zf:
|
|
zf.writestr("inner/a.txt", b"alpha bytes")
|
|
zf.writestr("inner/b.bin", b"\x00\x01\x02\x03")
|
|
|
|
expected_zip_hash = self._expected_zip_hash(zip_full)
|
|
raw_md5 = self._raw_md5(zip_full)
|
|
assert expected_zip_hash != raw_md5 # different algorithms; sanity check
|
|
|
|
result = await handler.compute_content_hash(relative)
|
|
|
|
assert result == expected_zip_hash, (
|
|
"compute_content_hash should dispatch to per-entry zip-hash for zip "
|
|
"files; got raw MD5 or None, meaning is_zipfile failed to resolve the "
|
|
"relative path."
|
|
)
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_non_zip_returns_raw_md5(
|
|
self, handler: FSAssetsHandler, temp_base: str
|
|
):
|
|
"""Non-zip files dispatch to _compute_file_hash (raw MD5)."""
|
|
relative = "users/test/saves/test.srm"
|
|
full = Path(temp_base) / relative
|
|
full.parent.mkdir(parents=True, exist_ok=True)
|
|
full.write_bytes(b"raw save data \x00\x01\xff")
|
|
|
|
expected = self._raw_md5(full)
|
|
|
|
result = await handler.compute_content_hash(relative)
|
|
|
|
assert result == expected
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_missing_file_returns_none(self, handler: FSAssetsHandler):
|
|
result = await handler.compute_content_hash("users/missing/file.zip")
|
|
assert result is None
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_zip_hash_pinned_single_entry(
|
|
self, handler: FSAssetsHandler, temp_base: str
|
|
):
|
|
"""Smallest possible zip: one file, stored compression. Pins the
|
|
algorithm against a known digest. Any change to the protocol (sort,
|
|
separator, hash, encoding) fails here.
|
|
"""
|
|
relative = "users/test/saves/simple.zip"
|
|
full = Path(temp_base) / relative
|
|
full.parent.mkdir(parents=True, exist_ok=True)
|
|
reload_zipfile()
|
|
with zipfile.ZipFile(full, "w", zipfile.ZIP_STORED) as zf:
|
|
zf.writestr("save.bin", b"\x42" * 256)
|
|
|
|
# md5("save.bin:" + md5(b"\x42"*256).hexdigest())
|
|
pinned = "b3636b49ca5c3d807adee33e75d410ca"
|
|
|
|
result = await handler.compute_content_hash(relative)
|
|
assert (
|
|
result == pinned
|
|
), f"single-entry per-entry zip-hash drifted: got={result} want={pinned}"
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_zip_hash_pinned_mixed(
|
|
self, handler: FSAssetsHandler, temp_base: str
|
|
):
|
|
"""Three-entry zip with one subdir; baseline mixed shape."""
|
|
relative = "users/test/saves/pinned.zip"
|
|
full = Path(temp_base) / relative
|
|
full.parent.mkdir(parents=True, exist_ok=True)
|
|
reload_zipfile()
|
|
with zipfile.ZipFile(full, "w", zipfile.ZIP_STORED) as zf:
|
|
zf.writestr("inner/a.txt", b"alpha")
|
|
zf.writestr("inner/b.txt", b"beta")
|
|
zf.writestr("top.bin", b"\x00\x01\x02")
|
|
|
|
pinned = "8cf6bb36a82a5ee4d7d15fc98599908d"
|
|
|
|
result = await handler.compute_content_hash(relative)
|
|
assert result == pinned, (
|
|
f"per-entry zip-hash drifted from documented protocol: "
|
|
f"got={result} want={pinned}"
|
|
)
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_zip_hash_pinned_nested_switch_shape(
|
|
self, handler: FSAssetsHandler, temp_base: str
|
|
):
|
|
"""Switch-save-shaped zip: deep nesting, mixed sizes, empty file,
|
|
unicode filename. Mirrors what real Switch saves look like (the
|
|
original bug surface) so this test exercises the algorithm against
|
|
a realistic layout.
|
|
"""
|
|
relative = "users/test/saves/switch.zip"
|
|
full = Path(temp_base) / relative
|
|
full.parent.mkdir(parents=True, exist_ok=True)
|
|
reload_zipfile()
|
|
with zipfile.ZipFile(full, "w", zipfile.ZIP_STORED) as zf:
|
|
title = "0100F2C0115B6000"
|
|
zf.writestr(f"{title}/NX6400000-SYSTEM/SYDAT.BIN", b"system data v1")
|
|
zf.writestr(
|
|
f"{title}/album/000_Photo.jpg",
|
|
b"\xff\xd8\xff\xe0jpegdata" * 8,
|
|
)
|
|
zf.writestr(f"{title}/album/000_Thumb.jpg", b"\xff\xd8thumbdata")
|
|
zf.writestr(f"{title}/slot_01/caption.sav", b"slot1 caption")
|
|
zf.writestr(f"{title}/slot_01/progress.sav", b"\x01" * 64)
|
|
zf.writestr(f"{title}/slot_02/caption.sav", b"slot2 caption")
|
|
zf.writestr(f"{title}/slot_02/progress.sav", b"\x02" * 64)
|
|
zf.writestr(f"{title}/storage/CacheStorageKey.dat", b"key=abcd1234")
|
|
zf.writestr(f"{title}/storage/empty.dat", b"")
|
|
zf.writestr(f"{title}/Pokémon.dat", b"unicode-name")
|
|
|
|
pinned = "c0c992d1f1f883f56065bb13b68dfdee"
|
|
|
|
result = await handler.compute_content_hash(relative)
|
|
assert (
|
|
result == pinned
|
|
), f"nested-switch-shape zip-hash drifted: got={result} want={pinned}"
|
|
|
|
|
|
class TestHashSaveFile:
|
|
"""Sync paths hash device files with hash_save_file, so it must agree with the server."""
|
|
|
|
@pytest.fixture
|
|
def temp_base(self):
|
|
path = tempfile.mkdtemp()
|
|
yield Path(path).resolve()
|
|
shutil.rmtree(path, ignore_errors=True)
|
|
|
|
@staticmethod
|
|
def _write_zip(path: Path, compression: int) -> None:
|
|
reload_zipfile()
|
|
with zipfile.ZipFile(path, "w", compression=compression) as zf:
|
|
zf.writestr("card/a.bin", b"alpha bytes" * 64)
|
|
zf.writestr("card/b.bin", b"\x00\x01\x02\x03" * 64)
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_zip_matches_compute_content_hash(self, temp_base: Path):
|
|
self._write_zip(temp_base / "save.zip", zipfile.ZIP_DEFLATED)
|
|
handler = FSAssetsHandler()
|
|
handler.base_path = temp_base
|
|
|
|
assert hash_save_file(temp_base / "save.zip") == (
|
|
await handler.compute_content_hash("save.zip")
|
|
)
|
|
|
|
@pytest.mark.parametrize("is_zip", [False, True], ids=["raw", "zip"])
|
|
def test_in_memory_content_hashes_like_the_file(
|
|
self, temp_base: Path, is_zip: bool
|
|
):
|
|
path = temp_base / "save.bin"
|
|
if is_zip:
|
|
self._write_zip(path, zipfile.ZIP_DEFLATED)
|
|
else:
|
|
path.write_bytes(b"save ram" * 32)
|
|
content = io.BytesIO(path.read_bytes())
|
|
content.seek(5)
|
|
|
|
assert hash_save_content(content) == hash_save_file(path)
|
|
assert content.tell() == 0
|
|
|
|
def test_repacked_zip_with_the_same_entries_hashes_the_same(self, temp_base: Path):
|
|
stored = temp_base / "stored.zip"
|
|
deflated = temp_base / "deflated.zip"
|
|
self._write_zip(stored, zipfile.ZIP_STORED)
|
|
self._write_zip(deflated, zipfile.ZIP_DEFLATED)
|
|
assert stored.read_bytes() != deflated.read_bytes()
|
|
|
|
assert hash_save_file(stored) == hash_save_file(deflated)
|
|
|
|
def test_non_zip_is_the_md5_of_its_bytes(self, temp_base: Path):
|
|
path = temp_base / "save.srm"
|
|
path.write_bytes(b"raw save data \x00\x01\xff")
|
|
|
|
assert (
|
|
hash_save_file(path)
|
|
== hashlib.md5(path.read_bytes(), usedforsecurity=False).hexdigest()
|
|
)
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_an_unreadable_zip_is_unknown_like_compute_content_hash(
|
|
self, temp_base: Path, monkeypatch: pytest.MonkeyPatch
|
|
):
|
|
self._write_zip(temp_base / "save.zip", zipfile.ZIP_DEFLATED)
|
|
monkeypatch.setattr(assets_handler, "MAX_DECOMPRESSED_ARCHIVE_BYTES", 8)
|
|
handler = FSAssetsHandler()
|
|
handler.base_path = temp_base
|
|
|
|
assert hash_save_file(temp_base / "save.zip") is None
|
|
assert await handler.compute_content_hash("save.zip") is None
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_entries_under_the_budget_alone_but_over_it_together_are_unknown(
|
|
self, temp_base: Path, monkeypatch: pytest.MonkeyPatch
|
|
):
|
|
reload_zipfile()
|
|
path = temp_base / "save.zip"
|
|
with zipfile.ZipFile(path, "w", compression=zipfile.ZIP_DEFLATED) as zf:
|
|
for i in range(4):
|
|
zf.writestr(f"part{i}.bin", b"\x00" * 1000)
|
|
handler = FSAssetsHandler()
|
|
handler.base_path = temp_base
|
|
|
|
monkeypatch.setattr(assets_handler, "MAX_DECOMPRESSED_ARCHIVE_BYTES", 4000)
|
|
assert hash_save_file(path) is not None
|
|
|
|
monkeypatch.setattr(assets_handler, "MAX_DECOMPRESSED_ARCHIVE_BYTES", 3999)
|
|
with zipfile.ZipFile(path) as zf, pytest.raises(assets_handler.ArchiveTooLarge):
|
|
assets_handler.hash_zip_contents(zf)
|
|
assert hash_save_file(path) is None
|
|
assert await handler.compute_content_hash("save.zip") is None
|
|
|
|
def test_too_many_entries_is_unknown(
|
|
self, temp_base: Path, monkeypatch: pytest.MonkeyPatch
|
|
):
|
|
path = temp_base / "save.zip"
|
|
self._write_zip(path, zipfile.ZIP_DEFLATED)
|
|
|
|
monkeypatch.setattr(assets_handler, "MAX_ARCHIVE_ENTRIES", 2)
|
|
assert hash_save_file(path) is not None
|
|
|
|
monkeypatch.setattr(assets_handler, "MAX_ARCHIVE_ENTRIES", 1)
|
|
assert hash_save_file(path) is None
|
|
|
|
@pytest.mark.parametrize("error", [RuntimeError, NotImplementedError])
|
|
def test_an_entry_that_cannot_be_opened_is_unknown(
|
|
self, temp_base: Path, monkeypatch: pytest.MonkeyPatch, error: type[Exception]
|
|
):
|
|
"""Encrypted entries and unsupported compression must not stop a sync."""
|
|
path = temp_base / "save.zip"
|
|
self._write_zip(path, zipfile.ZIP_DEFLATED)
|
|
|
|
def fail(_zf: zipfile.ZipFile) -> str:
|
|
raise error("cannot open entry")
|
|
|
|
monkeypatch.setattr(assets_handler, "hash_zip_contents", fail)
|
|
|
|
assert hash_save_file(path) is None
|
|
|
|
|
|
def _md5(data: bytes) -> str:
|
|
return hashlib.md5(data, usedforsecurity=False).hexdigest()
|
|
|
|
|
|
def _zip(members: dict[str, bytes]) -> zipfile.ZipFile:
|
|
reload_zipfile()
|
|
buffer = io.BytesIO()
|
|
with zipfile.ZipFile(buffer, "w") as zf:
|
|
for name, data in members.items():
|
|
zf.writestr(name, data)
|
|
return zipfile.ZipFile(io.BytesIO(buffer.getvalue()))
|
|
|
|
|
|
class TestCheckZip:
|
|
@pytest.mark.parametrize(
|
|
"name",
|
|
["../escape.sav", "/abs.sav", "C:/drive.sav", "dir\\back.sav", "a/../../b.sav"],
|
|
)
|
|
def test_an_entry_leaving_the_folder_is_refused(self, name: str):
|
|
with pytest.raises(assets_handler.UnsafeArchive):
|
|
assets_handler.check_zip(_zip({name: b"x"}))
|
|
|
|
def test_a_symlink_entry_is_refused(self):
|
|
reload_zipfile()
|
|
link = zipfile.ZipInfo("SAVE01/link")
|
|
link.external_attr = 0o120777 << 16
|
|
buffer = io.BytesIO()
|
|
with zipfile.ZipFile(buffer, "w") as zf:
|
|
zf.writestr(link, "/etc/passwd")
|
|
|
|
with pytest.raises(assets_handler.UnsafeArchive):
|
|
assets_handler.check_zip(zipfile.ZipFile(io.BytesIO(buffer.getvalue())))
|
|
|
|
def test_too_many_entries_is_refused(self, monkeypatch: pytest.MonkeyPatch):
|
|
monkeypatch.setattr(assets_handler, "MAX_ARCHIVE_ENTRIES", 2)
|
|
|
|
with pytest.raises(assets_handler.UnsafeArchive):
|
|
assets_handler.check_zip(_zip({"a": b"1", "b": b"2", "c": b"3"}))
|
|
|
|
def test_expanding_past_the_limit_is_refused(self, monkeypatch: pytest.MonkeyPatch):
|
|
monkeypatch.setattr(assets_handler, "MAX_ARCHIVE_EXPANDED_BYTES", 5)
|
|
|
|
with pytest.raises(assets_handler.UnsafeArchive):
|
|
assets_handler.check_zip(_zip({"a": b"123", "b": b"456"}))
|
|
|
|
def test_a_safe_archive_lists_its_files(self):
|
|
archive = _zip({"SAVE01/": b"", "SAVE01/data.bin": b"d", "icon.png": b"i"})
|
|
|
|
assert assets_handler.check_zip(archive) == ["SAVE01/data.bin", "icon.png"]
|
|
|
|
def test_a_raw_upload_is_no_archive_and_keeps_its_position(self):
|
|
stream = io.BytesIO(b"raw sram")
|
|
stream.seek(3)
|
|
|
|
assert assets_handler.check_upload(stream) is None
|
|
assert stream.tell() == 3
|
|
|
|
|
|
class TestZipIdentityHash:
|
|
"""Sigil's identity hash: content without RTC members, one member left hashing raw."""
|
|
|
|
@pytest.mark.parametrize(
|
|
"members",
|
|
[
|
|
{"game.srm": b"sram", "game.rtc": b"tick"},
|
|
{"save.sram": b"sram", "clock.rtc": b"tick"},
|
|
],
|
|
)
|
|
def test_a_clock_member_is_left_out(self, members: dict[str, bytes]):
|
|
assert assets_handler.zip_identity_hash(_zip(members)) == _md5(b"sram")
|
|
|
|
def test_one_member_hashes_as_itself(self):
|
|
with_folder = _zip({"SAVE01/data.bin": b"data"})
|
|
|
|
assert assets_handler.zip_identity_hash(with_folder) == _md5(b"data")
|
|
|
|
def test_several_members_hash_as_the_content_does(self):
|
|
archive = _zip({"eeprom": b"e", "pak1": b"p", "game.rtc": b"tick"})
|
|
without_clock = _zip({"eeprom": b"e", "pak1": b"p"})
|
|
|
|
assert assets_handler.zip_identity_hash(
|
|
archive
|
|
) == assets_handler.hash_zip_contents(without_clock)
|