fix(sync): apply code-review xhigh findings

- Stream RetroArch PUT bodies with a byte cap, so a chunked upload
  can't bypass the Content-Length check and exhaust memory
- Map shared core folders back to the mednafen_* ids the web player uses
- Enforce PSP bundle limits on write, return 409 for invalid bundles,
  and never delete an unreadable bundle when removing one member
- Challenge the kiosk guest so RetroArch sends credentials
- Move a slot-matched state's row with its bytes, scan saves under the
  name actually written
- Reject NUL path segments and core folder names over the emulator
  column length
- Cache PSP bundle member hashes in the manifest

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Georges-Antoine Assi
2026-09-24 15:34:05 -04:00
parent 638a21f88b
commit 918afcf1df
7 changed files with 330 additions and 58 deletions

View File

@@ -13,13 +13,15 @@ heap.
import os
import uuid
from collections.abc import Callable
from contextlib import suppress
from collections.abc import AsyncIterator, Callable
from contextlib import asynccontextmanager, suppress
from tempfile import SpooledTemporaryFile
from urllib.parse import quote
from fastapi import APIRouter, Request, Response, status
from fastapi import APIRouter, Request, Response, UploadFile, status
from fastapi.responses import JSONResponse, RedirectResponse
from config import MAX_ASSET_UPLOAD_SIZE_BYTES
from handler.auth.constants import Scope
from handler.auth.dependencies import get_permissions
from handler.auth.permissions import ResolvedPermissions
@@ -52,6 +54,9 @@ router = APIRouter(prefix="/retroarch")
ALLOWED_METHODS = "OPTIONS, PROPFIND, GET, HEAD, PUT, DELETE, MKCOL, MOVE, LOCK, UNLOCK"
# Starlette's own threshold for spooling a multipart upload to disk.
_BODY_MEMORY_MAX_BYTES = 1024 * 1024
def _empty(status_code: int, headers: dict[str, str] | None = None) -> Response:
return Response(status_code=status_code, headers=headers)
@@ -70,7 +75,9 @@ def _authorize(request: Request, scope: Scope) -> Response | None:
WebDAV clients expect a 401 challenge rather than the 403 that
`@protected_route` produces, so this endpoint gates itself.
"""
if not request.user.is_authenticated:
# The kiosk guest is anonymous, and RetroArch only sends credentials once
# challenged.
if not request.user.is_authenticated or request.user.is_kiosk_guest:
return _unauthorized()
if scope not in request.auth.scopes:
@@ -79,6 +86,35 @@ def _authorize(request: Request, scope: Scope) -> Response | None:
return None
@asynccontextmanager
async def _request_body(
request: Request, max_size: int = 0
) -> AsyncIterator[UploadFile | None]:
"""The request body spooled to disk past 1 MiB, or None once over the cap.
Args:
max_size: A cap tighter than MAX_ASSET_UPLOAD_SIZE_BYTES, if any.
"""
# UploadSizeLimitMiddleware only reads Content-Length, which a chunked body lacks.
limit = min(filter(None, (MAX_ASSET_UPLOAD_SIZE_BYTES, max_size)), default=0)
body = UploadFile(
SpooledTemporaryFile(max_size=_BODY_MEMORY_MAX_BYTES) # type: ignore[arg-type]
)
try:
size = 0
async for chunk in request.stream():
size += len(chunk)
if limit and size > limit:
yield None
return
await body.write(chunk)
await body.seek(0)
yield body
finally:
await body.close()
def _can_read_roms(request: Request) -> bool:
return Scope.ROMS_READ in request.auth.scopes
@@ -431,15 +467,18 @@ async def retroarch_sync_put(request: Request, file_path: str) -> Response:
blob_path = sync_handler.parse_retroarch_sync_blob_path(file_path)
if blob_path:
disk_path = sync_handler.user_blob_path(request.user, blob_path)
try:
existed = await fs_retroarch_sync_handler.file_exists(disk_path)
await fs_retroarch_sync_handler.write_file(
file=await request.body(),
path=os.path.dirname(disk_path),
filename=os.path.basename(disk_path),
)
except ValueError:
return _empty(status.HTTP_409_CONFLICT)
async with _request_body(request) as body:
if body is None:
return _empty(status.HTTP_413_CONTENT_TOO_LARGE)
try:
existed = await fs_retroarch_sync_handler.file_exists(disk_path)
await fs_retroarch_sync_handler.write_file(
file=body,
path=os.path.dirname(disk_path),
filename=os.path.basename(disk_path),
)
except ValueError:
return _empty(status.HTTP_409_CONFLICT)
return _empty(
status.HTTP_204_NO_CONTENT if existed else status.HTTP_201_CREATED
@@ -450,14 +489,20 @@ async def retroarch_sync_put(request: Request, file_path: str) -> Response:
# PSP engine cache file (shader cache etc.), not save data.
return _empty(status.HTTP_204_NO_CONTENT)
if psp_path:
# Bundle members are merged in memory, so the bundle limit caps the body.
async with _request_body(request, psp.BUNDLE_MAX_UNCOMPRESSED_BYTES) as body:
if body is None:
return _empty(status.HTTP_413_CONTENT_TOO_LARGE)
content = await body.read()
try:
await psp.put_psp_file(
request.user,
psp_path,
await request.body(),
content,
_rom_visibility(get_permissions(request)),
)
except (psp.PspFolderUnresolved, ValueError):
except (psp.PspFolderUnresolved, psp.PspBundleInvalid, ValueError):
return _empty(status.HTTP_409_CONFLICT)
return _empty(status.HTTP_201_CREATED)
@@ -496,11 +541,12 @@ async def retroarch_sync_put(request: Request, file_path: str) -> Response:
platform_fs_slug=rom.platform.fs_slug,
rom_id=rom.id,
)
await fs_asset_handler.write_file(
file=await request.body(),
path=screenshot_path,
filename=screenshot_file_name,
)
async with _request_body(request) as body:
if body is None:
return _empty(status.HTTP_413_CONTENT_TOO_LARGE)
await fs_asset_handler.write_file(
file=body, path=screenshot_path, filename=screenshot_file_name
)
scanned_screenshot = await scan_screenshot(
file_name=screenshot_file_name,
@@ -535,13 +581,16 @@ async def retroarch_sync_put(request: Request, file_path: str) -> Response:
existing = _get_asset(request.user, rom, parsed)
write_file_name = existing.file_name if existing else file_name
await fs_asset_handler.write_file(
file=await request.body(), path=asset_path, filename=write_file_name
)
async with _request_body(request) as body:
if body is None:
return _empty(status.HTTP_413_CONTENT_TOO_LARGE)
await fs_asset_handler.write_file(
file=body, path=asset_path, filename=write_file_name
)
if parsed.kind == "saves":
scanned_save = await scan_save(
file_name=file_name,
file_name=write_file_name,
user=request.user,
platform_fs_slug=rom.platform.fs_slug,
rom_id=rom.id,
@@ -570,13 +619,19 @@ async def retroarch_sync_put(request: Request, file_path: str) -> Response:
emulator=parsed.emulator,
)
if existing:
# The row moves with the bytes when it was filed elsewhere, e.g.
# under the ROM's previous platform folder.
db_state_handler.update_state(
existing.id,
{
"file_size_bytes": scanned_state.file_size_bytes,
"file_path": scanned_state.file_path,
"missing_from_fs": False,
},
)
if existing.file_path != scanned_state.file_path:
with suppress(FileNotFoundError):
await fs_asset_handler.remove_file(file_path=existing.full_path)
else:
scanned_state.rom_id = rom.id
scanned_state.user_id = request.user.id

View File

@@ -15,12 +15,12 @@ RETROARCH_DIR_BY_ROMM_EMULATOR: dict[str, str] = {
"fceumm": "FCEUmm",
"mesen": "Mesen",
# PlayStation
"mednafen_psx": "Beetle PSX",
"mednafen_psx_hw": "Beetle PSX HW",
"beetle_psx": "Beetle PSX",
"beetle_psx_hw": "Beetle PSX HW",
"pcsx_rearmed": "PCSX-ReARMed",
"swanstation": "SwanStation",
"mednafen_psx": "Beetle PSX",
"mednafen_psx_hw": "Beetle PSX HW",
# Game Boy
"gambatte": "Gambatte",
"sameboy": "SameBoy",
@@ -36,9 +36,9 @@ RETROARCH_DIR_BY_ROMM_EMULATOR: dict[str, str] = {
"mupen64plus_next": "Mupen64Plus-Next",
"parallel_n64": "ParaLLEl N64",
# Saturn
"mednafen_saturn": "Beetle Saturn",
"beetle_saturn": "Beetle Saturn",
"kronos": "Kronos",
"mednafen_saturn": "Beetle Saturn",
# Arcade / Neo Geo
"mame": "MAME",
"fbneo": "FBNeo",
@@ -53,10 +53,10 @@ RETROARCH_DIR_BY_ROMM_EMULATOR: dict[str, str] = {
# Atari
"stella": "Stella",
# PC Engine
"beetle_pce": "Beetle PCE",
"beetle_pce_fast": "Beetle PCE Fast",
"mednafen_pce": "Beetle PCE",
"mednafen_pce_fast": "Beetle PCE Fast",
"beetle_pce": "Beetle PCE",
"beetle_pce_fast": "Beetle PCE Fast",
# Other common cores
"dosbox_pure": "DOSBox-Pure",
"scummvm": "ScummVM",
@@ -67,7 +67,8 @@ RETROARCH_DIR_BY_ROMM_EMULATOR: dict[str, str] = {
}
# Reversed so the first core listed for a shared folder (e.g. "Beetle PSX") wins.
# Reversed so the first core listed for a shared folder wins, which is the
# `mednafen_*` id the web player (EmulatorJS) stores for the Beetle cores.
ROMM_EMULATOR_BY_RETROARCH_DIR: dict[str, str] = {
dir_name: emulator
for emulator, dir_name in reversed(RETROARCH_DIR_BY_ROMM_EMULATOR.items())

View File

@@ -10,6 +10,7 @@ from __future__ import annotations
import asyncio
import hashlib
import json
import re
import struct
import zipfile
@@ -25,8 +26,8 @@ from handler.database import db_platform_handler, db_rom_handler, db_save_handle
from handler.filesystem import fs_asset_handler
from handler.filesystem.assets_handler import hash_zip_contents
from handler.filesystem.base_handler import FSHandler
from handler.redis_handler import async_cache
from handler.sync.retroarch import sync_handler
from handler.sync.retroarch.emulator_names import to_romm_emulator
from logger.formatter import highlight as hl
from logger.logger import log
from models.assets import Save
@@ -40,7 +41,7 @@ _SAVEDATA_CATEGORY = "SAVEDATA"
# Real PSP save folders hold a handful of small files; anything past these is
# not one, and inflating it on every manifest build would exhaust memory.
_BUNDLE_MAX_MEMBERS = 64
_BUNDLE_MAX_UNCOMPRESSED_BYTES = 64 * 1024 * 1024
BUNDLE_MAX_UNCOMPRESSED_BYTES = 64 * 1024 * 1024
_BUNDLE_FOLDER_PATTERN = re.compile(r"^PSP-(.+?)(?: \[.*])?\.zip$")
@@ -51,6 +52,10 @@ class PspFolderUnresolved(Exception):
"""A save folder no ROM matches yet; its files wait on disk until one does."""
class PspBundleInvalid(Exception):
"""The folder's bundle is unreadable, or the upload would push it past the limits."""
@dataclass(frozen=True)
class PspFilePath:
"""A parsed ``saves/[<emulator>/]PSP/SAVEDATA/<save_folder>/<file_name>`` path."""
@@ -71,7 +76,9 @@ def resolve_psp_path(file_path: str) -> PspFilePath | Literal["ignore"] | None:
if segments[1].upper() == "PSP" and segments[2].upper() in categories:
emulator, rest = None, segments[2:]
elif len(segments) >= 4 and segments[2].upper() == "PSP":
emulator, rest = to_romm_emulator(segments[1]), segments[3:]
emulator, rest = sync_handler.emulator_from_dir_name(segments[1]), segments[3:]
if emulator is None:
return None
else:
return None
@@ -248,6 +255,13 @@ def _resolve_rom(
return None
def _exceeds_bundle_limits(member_sizes: Collection[int]) -> bool:
return (
len(member_sizes) > _BUNDLE_MAX_MEMBERS
or sum(member_sizes) > BUNDLE_MAX_UNCOMPRESSED_BYTES
)
def _load_bundle_entries(
zip_bytes: bytes, names: Collection[str] | None = None
) -> dict[str, bytes]:
@@ -258,9 +272,7 @@ def _load_bundle_entries(
"""
with zipfile.ZipFile(BytesIO(zip_bytes)) as zf:
infos = zf.infolist()
if len(infos) > _BUNDLE_MAX_MEMBERS or (
sum(info.file_size for info in infos) > _BUNDLE_MAX_UNCOMPRESSED_BYTES
):
if _exceeds_bundle_limits([info.file_size for info in infos]):
raise zipfile.BadZipFile("PSP bundle exceeds the size limits")
# `read` stops at each member's declared size, so the check above holds.
return {
@@ -365,6 +377,7 @@ async def put_psp_file(
Raises:
PspFolderUnresolved: No ROM matches the folder yet; the file is buffered.
PspBundleInvalid: The bundle is unreadable or would exceed the limits.
"""
# PPSSPP writes a folder as a burst of PUTs, so the bundle is rewritten in
# place rather than keeping each partial merge as save history.
@@ -379,7 +392,10 @@ async def put_psp_file(
except FileNotFoundError:
log.warning(f"PSP bundle {hl(existing.full_path)} is gone, rebuilding")
else:
merged = _load_bundle_entries(zip_bytes)
try:
merged = _load_bundle_entries(zip_bytes)
except zipfile.BadZipFile as exc:
raise PspBundleInvalid(existing.full_path) from exc
else:
rom = await _resolve_folder_rom(info, content, pending_dir, can_see)
@@ -392,6 +408,8 @@ async def put_psp_file(
f"{pending_dir}/{name}"
)
merged[info.file_name] = content
if _exceeds_bundle_limits([len(data) for data in merged.values()]):
raise PspBundleInvalid(info.save_folder)
if existing:
await _rewrite_bundle(existing, merged)
@@ -453,11 +471,13 @@ async def delete_psp_file(
if not bundle:
return
entries = await _read_bundle(bundle) or {}
if entries and info.file_name not in entries:
# An unreadable bundle is kept rather than dropped along with every
# other member it holds.
entries = await _read_bundle(bundle)
if entries is None or info.file_name not in entries:
return
entries.pop(info.file_name, None)
del entries[info.file_name]
if entries:
await _rewrite_bundle(bundle, entries)
return
@@ -467,6 +487,30 @@ async def delete_psp_file(
await fs_asset_handler.remove_file(file_path=bundle.full_path)
async def _bundle_member_md5s(bundle: Save) -> dict[str, str] | None:
"""Each member's MD5, cached so a manifest build doesn't inflate every bundle."""
cache_key = (
f"romm:retroarch_sync:psp_member_md5s:{bundle.full_path}"
f":{bundle.content_hash}:{bundle.updated_at.timestamp()}"
)
cached = await async_cache.get(cache_key)
if cached:
return json.loads(cached)
members = await _read_bundle(bundle)
if members is None:
return None
digests = {
name: hashlib.md5(data, usedforsecurity=False).hexdigest()
for name, data in members.items()
}
await async_cache.set(
cache_key, json.dumps(digests), ex=sync_handler.HASH_CACHE_TTL_SECONDS
)
return digests
async def build_psp_manifest_entries(
saves: Iterable[Save], can_see: Callable[[Rom], bool]
) -> list[dict[str, str]]:
@@ -475,11 +519,11 @@ async def build_psp_manifest_entries(
for save_folder, save in _latest_bundles_by_folder(saves, can_see).items():
if save.missing_from_fs:
continue
members = await _read_bundle(save)
if members is None:
digests = await _bundle_member_md5s(save)
if digests is None:
continue
for member_name, data in members.items():
for member_name, digest in digests.items():
entries.append(
{
"path": sync_handler.build_retroarch_sync_path(
@@ -487,7 +531,7 @@ async def build_psp_manifest_entries(
save.emulator,
f"PSP/SAVEDATA/{save_folder}/{member_name}",
),
"hash": hashlib.md5(data, usedforsecurity=False).hexdigest(),
"hash": digest,
}
)

View File

@@ -23,7 +23,7 @@ from handler.sync.retroarch.emulator_names import (
to_retroarch_dir_name,
to_romm_emulator,
)
from models.assets import Save, Screenshot, State
from models.assets import EMULATOR_MAX_LENGTH, Save, Screenshot, State
from models.rom import Rom
from models.user import User
@@ -43,7 +43,7 @@ STATE_SUFFIX_PATTERN = re.compile(r"\.state\d*(?:\.auto)?$", re.IGNORECASE)
# Rehashing every asset on each manifest fetch would read gigabytes. Keys carry
# size and mtime, so a changed file misses the cache instead of going stale.
_HASH_CACHE_TTL_SECONDS = 60 * 60 * 24
HASH_CACHE_TTL_SECONDS = 60 * 60 * 24
@dataclass(frozen=True)
@@ -60,13 +60,21 @@ class RetroArchSyncPath:
def split_segments(path: str) -> list[str] | None:
"""A client path's non-empty segments, or None if any is `.` or `..`."""
"""A client path's non-empty segments, or None if any is `.`, `..` or holds a NUL."""
segments = [segment for segment in path.strip("/").split("/") if segment]
if any(segment in (os.curdir, os.pardir) for segment in segments):
if any(
segment in (os.curdir, os.pardir) or "\x00" in segment for segment in segments
):
return None
return segments
def emulator_from_dir_name(dir_name: str) -> str | None:
"""RomM's `emulator` for a core folder name, or None if too long to store."""
emulator = to_romm_emulator(dir_name)
return emulator if len(emulator) <= EMULATOR_MAX_LENGTH else None
def parse_retroarch_sync_path(path: str) -> RetroArchSyncPath | None:
"""Parse a ``<root>/[<core>/]<file>`` client path, or None if unsupported."""
segments = split_segments(path)
@@ -79,11 +87,13 @@ def parse_retroarch_sync_path(path: str) -> RetroArchSyncPath | None:
# RomM's web player matches saves on the lowercase libretro core id, not
# RetroArch's display-cased folder name.
return RetroArchSyncPath(
kind=kind,
emulator=to_romm_emulator(segments[1]) if len(segments) == 3 else None,
file_name=segments[-1],
)
emulator = None
if len(segments) == 3:
emulator = emulator_from_dir_name(segments[1])
if emulator is None:
return None
return RetroArchSyncPath(kind=kind, emulator=emulator, file_name=segments[-1])
def is_state_screenshot_path(file_name: str) -> bool:
@@ -235,7 +245,7 @@ async def _cached_md5(
digest = await compute()
if digest:
await async_cache.set(cache_key, digest, ex=_HASH_CACHE_TTL_SECONDS)
await async_cache.set(cache_key, digest, ex=HASH_CACHE_TTL_SECONDS)
return digest

View File

@@ -23,6 +23,7 @@ if TYPE_CHECKING:
SAVE_SLOT_MAX_LENGTH = 255
EMULATOR_MAX_LENGTH = 50
ASSET_LABEL_MAX_LENGTH = 255
ASSET_LABELS_MAX = 20
@@ -103,7 +104,7 @@ class Save(RomAsset):
{"extend_existing": True},
)
emulator: Mapped[str | None] = mapped_column(String(length=50))
emulator: Mapped[str | None] = mapped_column(String(length=EMULATOR_MAX_LENGTH))
slot: Mapped[str | None] = mapped_column(
String(length=SAVE_SLOT_MAX_LENGTH), index=True
)
@@ -150,7 +151,7 @@ class State(RomAsset):
{"extend_existing": True},
)
emulator: Mapped[str | None] = mapped_column(String(length=50))
emulator: Mapped[str | None] = mapped_column(String(length=EMULATOR_MAX_LENGTH))
# `is_public` mirrors Screenshot/RomNote — lets other users browse and
# download a user's public states (community). Defaults false (private).
is_public: Mapped[bool] = mapped_column(default=False)
@@ -202,7 +203,7 @@ class MemoryCard(BaseModel):
user_id: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"))
# `emulator` is the hard scoping key: a card is looked up by (user, emulator)
# at session claim, so one Dolphin card serves both GameCube and Wii roms.
emulator: Mapped[str] = mapped_column(String(length=50))
emulator: Mapped[str] = mapped_column(String(length=EMULATOR_MAX_LENGTH))
# `platform_id` is a loose, nullable hint (which platform the card was
# created under) for display/filtering only. It never scopes the lookup, so
# a card stays visible across every platform its emulator drives.

View File

@@ -117,7 +117,10 @@ class TestRetroArchSyncEmulatorNames:
("Snes9x", "snes9x"),
("Genesis Plus GX", "genesis_plus_gx"),
("PCSX-ReARMed", "pcsx_rearmed"),
("Beetle PSX", "beetle_psx"),
# The web player stores the Beetle cores under their mednafen ids.
("Beetle PSX", "mednafen_psx"),
("Beetle PSX HW", "mednafen_psx_hw"),
("Beetle PCE", "mednafen_pce"),
("RetroArduous", "RetroArduous"),
("Beetle VB", "Beetle VB"),
],
@@ -193,6 +196,8 @@ class TestRetroArchSyncPathParsing:
"saves",
"saves/Snes9x/nested/test_rom.srm",
"saves/../../etc/passwd",
"saves/Snes9x/test\x00rom.srm",
f"saves/{'x' * 51}/test_rom.srm",
],
)
def test_rejects_unsupported_paths(self, path):
@@ -239,6 +244,14 @@ class TestRetroArchSyncAuth:
assert response.status_code == status.HTTP_401_UNAUTHORIZED
def test_kiosk_guest_is_challenged(self, client):
with mock.patch("handler.auth.hybrid_auth.KIOSK_MODE", True):
options = client.options("/api/sync/retroarch/")
manifest = client.get("/api/sync/retroarch/manifest.server")
assert options.status_code == status.HTTP_401_UNAUTHORIZED
assert manifest.status_code == status.HTTP_401_UNAUTHORIZED
class TestRetroArchSyncStateSlotResolution:
def test_resolves_canonical_name_to_the_web_created_row(
@@ -825,6 +838,75 @@ class TestRetroArchSyncUpload:
assert response.status_code == status.HTTP_204_NO_CONTENT
@mock.patch(
"endpoints.sync.retroarch.fs_asset_handler.write_file",
new_callable=mock.AsyncMock,
)
def test_rejects_a_chunked_body_over_the_upload_cap(
self,
mock_write_file: mock.AsyncMock,
client,
admin_user: User,
rom: Rom,
):
# A generator body goes out chunked, with no Content-Length to reject on.
with mock.patch("endpoints.sync.retroarch.MAX_ASSET_UPLOAD_SIZE_BYTES", 4):
response = client.put(
"/api/sync/retroarch/saves/Snes9x/test_rom.srm",
content=iter([b"dat", b"a!"]),
auth=ADMIN_AUTH,
)
assert response.status_code == status.HTTP_413_CONTENT_TOO_LARGE
assert response.content == b""
mock_write_file.assert_not_awaited()
assert db_save_handler.get_saves(user_id=admin_user.id, rom_ids=[rom.id]) == []
@mock.patch(
"endpoints.sync.retroarch.fs_asset_handler.remove_file",
new_callable=mock.AsyncMock,
)
@mock.patch(
"endpoints.sync.retroarch.fs_asset_handler.write_file",
new_callable=mock.AsyncMock,
)
@mock.patch("endpoints.sync.retroarch.scan_state", new_callable=mock.AsyncMock)
def test_state_filed_elsewhere_moves_with_the_upload(
self,
mock_scan_state: mock.AsyncMock,
_mock_write_file: mock.AsyncMock,
mock_remove_file: mock.AsyncMock,
client,
admin_user: User,
rom: Rom,
states_path: str,
):
legacy_state = db_state_handler.add_state(
State(
rom_id=rom.id,
user_id=admin_user.id,
file_name="test_rom.state",
file_path="legacy/states/snes9x",
file_size_bytes=4,
emulator="snes9x",
)
)
mock_scan_state.return_value = State(
file_name="test_rom.state", file_path=states_path, file_size_bytes=8
)
response = client.put(
"/api/sync/retroarch/states/Snes9x/test_rom.state",
content=b"statedat",
auth=ADMIN_AUTH,
)
assert response.status_code == status.HTTP_204_NO_CONTENT
state = db_state_handler.get_state(user_id=admin_user.id, id=legacy_state.id)
assert state is not None
assert state.file_path == states_path
mock_remove_file.assert_awaited_once_with(file_path=legacy_state.full_path)
class TestRetroArchSyncDownload:
def test_missing_file_is_not_found(self, client, admin_user: User, rom: Rom):
@@ -1144,6 +1226,58 @@ class TestRetroArchSyncPsp:
)
assert get_response.status_code == status.HTTP_404_NOT_FOUND
def test_upload_past_the_bundle_limits_conflicts(
self, client, admin_user: User, monkeypatch: pytest.MonkeyPatch
):
monkeypatch.setattr(psp, "_BUNDLE_MAX_MEMBERS", 1)
client.put(
"/api/sync/retroarch/saves/PPSSPP/PSP/SAVEDATA/TEST12345DATA0/PARAM.SFO",
content=b"sfo",
auth=ADMIN_AUTH,
)
response = client.put(
"/api/sync/retroarch/saves/PPSSPP/PSP/SAVEDATA/TEST12345DATA0/SAVE.BIN",
content=b"data",
auth=ADMIN_AUTH,
)
assert response.status_code == status.HTTP_409_CONFLICT
get_sfo = client.get(
"/api/sync/retroarch/saves/PPSSPP/PSP/SAVEDATA/TEST12345DATA0/PARAM.SFO",
auth=ADMIN_AUTH,
)
assert get_sfo.content == b"sfo"
def test_unreadable_bundle_survives_a_member_delete(
self, client, admin_user: User, rom: Rom
):
client.put(
"/api/sync/retroarch/saves/PPSSPP/PSP/SAVEDATA/TEST12345DATA0/PARAM.SFO",
content=b"sfo",
auth=ADMIN_AUTH,
)
[bundle] = db_save_handler.get_saves(user_id=admin_user.id, rom_ids=[rom.id])
bundle_file = fs_asset_handler.validate_path(bundle.full_path)
bundle_file.write_bytes(b"not a zip")
response = client.request(
"DELETE",
"/api/sync/retroarch/saves/PPSSPP/PSP/SAVEDATA/TEST12345DATA0/PARAM.SFO",
auth=ADMIN_AUTH,
)
assert response.status_code == status.HTTP_204_NO_CONTENT
assert db_save_handler.get_save(user_id=admin_user.id, id=bundle.id)
assert bundle_file.is_file()
put_response = client.put(
"/api/sync/retroarch/saves/PPSSPP/PSP/SAVEDATA/TEST12345DATA0/SAVE.BIN",
content=b"data",
auth=ADMIN_AUTH,
)
assert put_response.status_code == status.HTTP_409_CONFLICT
class TestRetroArchSyncDevice:
def test_first_manifest_fetch_registers_a_device(self, client, admin_user: User):
@@ -1288,6 +1422,27 @@ class TestRetroArchSyncBlobs:
assert response.status_code == status.HTTP_404_NOT_FOUND
def test_delete_of_a_nul_blob_path_is_not_found(self, client, admin_user: User):
response = client.request(
"DELETE", "/api/sync/retroarch/config/a%00b.cfg", auth=ADMIN_AUTH
)
assert response.status_code == status.HTTP_404_NOT_FOUND
def test_rejects_a_chunked_blob_over_the_upload_cap(self, client, admin_user: User):
with mock.patch("endpoints.sync.retroarch.MAX_ASSET_UPLOAD_SIZE_BYTES", 4):
response = client.put(
"/api/sync/retroarch/config/retroarch.cfg",
content=iter([b"dat", b"a!"]),
auth=ADMIN_AUTH,
)
assert response.status_code == status.HTTP_413_CONTENT_TOO_LARGE
get_response = client.get(
"/api/sync/retroarch/config/retroarch.cfg", auth=ADMIN_AUTH
)
assert get_response.status_code == status.HTTP_404_NOT_FOUND
def test_manifest_includes_blobs_alongside_assets(self, client, admin_user: User):
client.put(
"/api/sync/retroarch/config/retroarch.cfg",

View File

@@ -92,6 +92,12 @@ class TestResolvePspPath:
def test_unrelated_category_is_none(self):
assert resolve_psp_path("saves/PPSSPP/PSP/OTHER/foo") is None
def test_core_folder_too_long_to_store_is_none(self):
assert (
resolve_psp_path(f"saves/{'x' * 51}/PSP/SAVEDATA/ULUS10336DATA0/PARAM.SFO")
is None
)
class TestIsPspBundleFileName:
def test_matches_bundle_names(self):