review(pr-ready step 2): harden import archives and fix review findings

Security (from the step 1 audit):
- Inflate zip entries a chunk at a time, so an entry whose header
  understates its size fails the CRC check instead of inflating in full.
- Cap the broker manifest at 1 MiB before reading it.
- Rebuild copied entries as regular files, keeping only permission bits,
  so a symlink entry cannot ride into the container.

Code review (xhigh):
- Bound the broker error body read at 1 MiB and truncate what is logged
  and returned.
- De-duplicate refusal hints in Stream.vue.
- Unpack only save members as zips; a zip-shaped state stays whole.
- Pick the newest state off an archive by created_at.
- Run newest_restorable off the event loop.
- Name a carried base entry by its staged path in the manifest.
This commit is contained in:
Zach Clendenen
2026-09-25 19:15:38 -05:00
parent cf4353e9e2
commit b6f2abb30f
6 changed files with 288 additions and 32 deletions

View File

@@ -855,19 +855,20 @@ async def claim_session(
container = await _win_container(request, candidates, session, platform)
session_key = container.key
# On an archive-resume container (DuckStation, RPCS3) the save archive
# carries its own exit state, and only the newest archive carries the newest
# capture, so any other state and save pairing needs the state imported.
# An archive-resume container's newest archive carries only the newest capture,
# so any other state and save pairing needs the state imported.
state_off_archive = False
if (
resume_state is not None
and not resume_foreign
and container.resumes_from_archive
):
newest_states = await asyncio.to_thread(
own_states = await asyncio.to_thread(
states.user_states_for_emulator, request.user.id, rom.id, container.emulator
)
state_off_archive = not newest_states or newest_states[0].id != resume_state.id
# Capture order, like the archive pick: replacing a state's bytes bumps updated_at.
newest_state = max(own_states, key=lambda s: (s.created_at, s.id), default=None)
state_off_archive = newest_state is None or newest_state.id != resume_state.id
if not state_off_archive and picked_save is not None:
newest_save = None
if not save_foreign:

View File

@@ -96,9 +96,10 @@ def broker_headers(container: ResolvedContainer) -> dict[str, str]:
_BROKER_READ_CHUNK = 1024 * 1024
# Control responses are small; a JSON body past this is a broker fault.
_BROKER_JSON_MAX_BYTES = 4 * 1024 * 1024
# An error body only ever reaches a log line and a 502 detail, except an
# import refusal, which can carry one entry per rejected member.
_BROKER_ERROR_MAX_BYTES = 64 * 1024
# An import refusal lists every rejected member and only parses whole, so the
# read takes all of it; the log line and 502 detail keep just the head.
_BROKER_ERROR_MAX_BYTES = 1024 * 1024
_BROKER_ERROR_SHOWN_CHARS = 8 * 1024
def broker_error_body(exc: urllib.error.HTTPError) -> str:
@@ -312,7 +313,9 @@ def raise_http_error(exc: urllib.error.HTTPError) -> NoReturn:
"""Translate a broker error response into the 502 the frontend parses, or
an ImportRefusedError when the broker refused a declared import."""
error_body = broker_error_body(exc)
log.error("broker HTTP error %d: %s", exc.code, error_body)
log.error(
"broker HTTP error %d: %s", exc.code, error_body[:_BROKER_ERROR_SHOWN_CHARS]
)
try:
detail: Any = json.loads(error_body)
except Exception:
@@ -341,7 +344,8 @@ def raise_http_error(exc: urllib.error.HTTPError) -> NoReturn:
truncated = truncated_raw if isinstance(truncated_raw, int) else 0
raise ImportRefusedError(refusals, truncated) from exc
raise HTTPException(
status_code=502, detail=f"Broker returned {exc.code}: {detail}"
status_code=502,
detail=f"Broker returned {exc.code}: {str(detail)[:_BROKER_ERROR_SHOWN_CHARS]}",
) from exc

View File

@@ -5,6 +5,7 @@ launch's `activate` call sends, under `.import/<kind>/` for the broker to place.
import asyncio
import io
import json
import stat
import time
import zipfile
from collections.abc import Callable
@@ -25,6 +26,8 @@ _MANIFEST_NAME = ".broker-manifest.json"
# upload cannot inflate past the ceiling any stored save archive has.
_MAX_EXPANDED_BYTES = broker.SAVE_FILE_MAX_BYTES
_MAX_MEMBERS = 2000
_READ_CHUNK = 64 * 1024
_MAX_MANIFEST_BYTES = 1024 * 1024
@dataclass(frozen=True)
@@ -62,18 +65,35 @@ def _utf8_zipinfo(name: str, source: zipfile.ZipInfo | None) -> zipfile.ZipInfo:
info = zipfile.ZipInfo(name, date_time=time.localtime()[:6])
else:
info = zipfile.ZipInfo(name, date_time=source.date_time)
info.external_attr = source.external_attr
# Only the permission bits, so a symlink entry lands as a regular file.
info.external_attr = (
stat.S_IFREG | stat.S_IMODE(source.external_attr >> 16)
) << 16
info.flag_bits |= 0x800 # UTF-8 filename flag
info.compress_type = zipfile.ZIP_DEFLATED
return info
def _read_member(zf: zipfile.ZipFile, info: zipfile.ZipInfo | str) -> bytes:
"""An entry's bytes, inflated a chunk at a time so a size the header
understates fails the CRC check before it can exhaust memory."""
out = bytearray()
with zf.open(info) as f:
while chunk := f.read(_READ_CHUNK):
out += chunk
return bytes(out)
def _manifest_files(zf: zipfile.ZipFile) -> dict[str, dict[str, Any]]:
"""A broker archive's manifest entries by path, empty when it has none."""
if _MANIFEST_NAME not in zf.namelist():
try:
info = zf.getinfo(_MANIFEST_NAME)
except KeyError:
return {}
if info.file_size > _MAX_MANIFEST_BYTES:
return {}
try:
manifest = json.loads(zf.read(_MANIFEST_NAME))
manifest = json.loads(_read_member(zf, info))
except (json.JSONDecodeError, KeyError, UnicodeDecodeError):
return {}
files = manifest.get("files") if isinstance(manifest, dict) else None
@@ -126,21 +146,26 @@ def _stage_zip(
continue
budget.charge(info.file_size)
path, manifest_entry = place(name, entry)
staged[path] = (zf.read(info), manifest_entry, info)
staged[path] = (_read_member(zf, info), manifest_entry, info)
def _write_member(
member: ForeignMember, staged: _Staged, budget: _ArchiveBudget
) -> None:
"""Stage one foreign member's inner entries, or itself when it is not a zip."""
"""Stage a foreign save archive's inner entries, or the member itself as one file."""
def place(name: str, _entry: dict[str, Any] | None) -> tuple[str, dict[str, Any]]:
path = f".import/{member.kind}/{name}"
return path, {"path": path, "kind": member.kind, "origin": member.origin}
try:
inner = zipfile.ZipFile(io.BytesIO(member.content))
except zipfile.BadZipFile:
# A state is one emulator file even when it is zip-shaped (a PCSX2 .p2s).
inner = None
if member.kind == "save":
try:
inner = zipfile.ZipFile(io.BytesIO(member.content))
except zipfile.BadZipFile:
pass
if inner is None:
budget.charge(len(member.content))
path, entry = place(_safe_name(member.name) or "data", None)
staged[path] = (member.content, entry, None)
@@ -156,11 +181,7 @@ def build_import_archive(
base: tuple[str, bytes] | None,
members: list[ForeignMember],
) -> tuple[bytes, list[dict[str, Any]]]:
"""Build the single zip `activate`'s `save.archive` wants.
The base archive's members are carried over (minus its state when a
foreign state replaces it), then each foreign member lands under
`.import/<kind>/`, and the manifest is rewritten as v2.
"""Build the single v2 zip `activate`'s `save.archive` wants: the base plus `.import/` members.
Returns:
The archive bytes, and the manifest's `files` list actually written.
@@ -183,7 +204,11 @@ def build_import_archive(
skip_state=any(m.kind == "state" for m in members),
place=lambda name, entry: (
name,
entry if entry is not None else {"path": name, "kind": "save"},
(
{**entry, "path": name}
if entry is not None
else {"path": name, "kind": "save"}
),
),
)
for member in members:
@@ -270,7 +295,9 @@ async def hydrate_import_archive(
base: tuple[str, bytes] | None = None
if not save_is_foreign:
native = save or saves.newest_restorable(user_id, rom.id, container.emulator)
native = save or await asyncio.to_thread(
saves.newest_restorable, user_id, rom.id, container.emulator
)
if native is not None:
base = await saves.read_restorable_archive(native)

View File

@@ -5525,6 +5525,56 @@ def test_build_import_archive_expands_a_foreign_zips_own_members():
assert zf.read(".import/save/save.mcr") == b"card-bytes"
def test_build_import_archive_keeps_a_zip_shaped_state_whole():
from tests._zipfile_shim import reload_zipfile
# zipfile-inflate64 in the import chain breaks writestr; restore stdlib first.
reload_zipfile()
inner = io.BytesIO()
with zipfile.ZipFile(inner, "w") as izf:
izf.writestr("eeMemory.bin", b"ee-bytes")
member = imports.ForeignMember(
kind="state",
name="SLUS-20062 (ABCD1234).01.p2s",
content=inner.getvalue(),
origin="standalone",
)
zip_bytes, carried = imports.build_import_archive(
rom_id=7, base=None, members=[member]
)
with zipfile.ZipFile(io.BytesIO(zip_bytes)) as zf:
assert zf.read(".import/state/SLUS-20062 (ABCD1234).01.p2s") == inner.getvalue()
assert [f["path"] for f in carried] == [
".import/state/SLUS-20062 (ABCD1234).01.p2s"
]
def test_build_import_archive_names_a_carried_entry_by_its_staged_path():
from tests._zipfile_shim import reload_zipfile
# zipfile-inflate64 in the import chain breaks writestr; restore stdlib first.
reload_zipfile()
base_zip = io.BytesIO()
with zipfile.ZipFile(base_zip, "w") as bzf:
bzf.writestr("saves\\Game.srm", b"native-save-bytes")
bzf.writestr(
".broker-manifest.json",
json.dumps(
{"version": 1, "files": [{"path": "saves\\Game.srm", "kind": "save"}]}
),
)
_zip_bytes, carried = imports.build_import_archive(
rom_id=7,
base=("Game.saves.zip", base_zip.getvalue()),
members=[
imports.ForeignMember(
kind="state", name="Game.00.pcsx2", content=b"s", origin="standalone"
)
],
)
assert {"path": "saves/Game.srm", "kind": "save"} in carried
def test_build_import_archive_keeps_a_native_base_alongside_a_foreign_state():
"""One native save and one foreign state in the same launch: the save
stays entirely on its own v1 entry, only the state gets an import
@@ -5724,6 +5774,71 @@ def test_build_import_archive_rejects_a_foreign_member_over_the_expanded_byte_bu
imports.build_import_archive(rom_id=7, base=None, members=[member])
def _understated_zip(name: str, content: bytes, declared_size: int) -> bytes:
"""A one-entry zip whose central directory understates the entry's size."""
from tests._zipfile_shim import reload_zipfile
reload_zipfile()
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf:
zf.writestr(name, content)
raw = bytearray(buf.getvalue())
central = raw.rindex(b"PK\x01\x02")
raw[central + 24 : central + 28] = declared_size.to_bytes(4, "little")
return bytes(raw)
def test_build_import_archive_does_not_inflate_past_a_members_declared_size():
import tracemalloc
bomb = _understated_zip("Game.srm", b"\0" * (64 * 1024 * 1024), 16)
tracemalloc.start()
try:
with pytest.raises(zipfile.BadZipFile):
imports.build_import_archive(
rom_id=7, base=("Game.saves.zip", bomb), members=[]
)
_current, peak = tracemalloc.get_traced_memory()
finally:
tracemalloc.stop()
assert peak < 16 * 1024 * 1024
def test_manifest_files_ignores_a_manifest_over_the_size_cap():
from tests._zipfile_shim import reload_zipfile
reload_zipfile()
manifest = {"files": [{"path": "Game.srm", "kind": "save"}], "pad": "x" * 64}
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w") as zf:
zf.writestr(".broker-manifest.json", json.dumps(manifest))
with (
patch("handler.streaming.imports._MAX_MANIFEST_BYTES", 32),
zipfile.ZipFile(buf) as zf,
):
assert imports._manifest_files(zf) == {}
def test_build_import_archive_rebuilds_a_symlink_entry_as_a_regular_file():
import stat
from tests._zipfile_shim import reload_zipfile
reload_zipfile()
base_zip = io.BytesIO()
with zipfile.ZipFile(base_zip, "w") as bzf:
link = zipfile.ZipInfo("Game.srm")
link.external_attr = (stat.S_IFLNK | 0o777) << 16
bzf.writestr(link, b"/etc/passwd")
zip_bytes, _carried = imports.build_import_archive(
rom_id=7, base=("Game.saves.zip", base_zip.getvalue()), members=[]
)
with zipfile.ZipFile(io.BytesIO(zip_bytes)) as zf:
mode = zf.getinfo("Game.srm").external_attr >> 16
assert stat.S_ISREG(mode)
assert stat.S_IMODE(mode) == 0o777
def test_hydrate_import_archive_uploads_a_foreign_save_with_no_native_base(
rom: Rom, admin_user: User
):
@@ -7391,6 +7506,43 @@ def test_an_older_exit_state_stays_off_the_import_path_without_broker_support(
assert run_launch_mock.call_args.kwargs["archive_path"] == "/romm/saves/archive.zip"
def test_a_rewritten_older_state_is_still_not_the_archives_capture(
client, access_token, rom: Rom, admin_user: User
):
older = db_state_handler.add_state(
_state_for(
rom,
admin_user,
"SLUS-00594_resume.20260917-010000000000.sav",
"duckstation",
)
)
db_state_handler.add_state(
_state_for(
rom,
admin_user,
"SLUS-00594_resume.20260918-010000000000.sav",
"duckstation",
)
)
db_state_handler.update_state(
older.id, {"updated_at": datetime.now(timezone.utc) + timedelta(days=1)}
)
run_launch_mock = AsyncMock()
with _streaming({**_webstation_for(rom), "emulator": "duckstation"}):
with (
patch("handler.streaming.webstation.import_spec", return_value=None),
patch(
"handler.streaming.saves.hydrate_saves_to_webstation",
new=AsyncMock(return_value="/romm/saves/archive.zip"),
),
patch("handler.streaming.launch.run_launch", run_launch_mock),
):
r = _claim(client, access_token, rom.id, state_id=older.id)
assert r.status_code == 202
assert run_launch_mock.call_args.kwargs["resume_import"] == "lost"
def _duckstation_pairing(rom: Rom, user: User) -> tuple[Save, Save, State]:
"""An older and a newer DuckStation archive, plus the newest capture."""
older, newer = (
@@ -8031,6 +8183,51 @@ def test_raise_http_error_raises_import_refused_as_a_typed_error():
assert raised.value.refusals[0].member == ".import/save/Game.mcr"
def test_raise_http_error_parses_a_refusal_list_at_the_brokers_cap():
import http.client
import urllib.error
refusal = {
"reason": "unrecognised_layout",
"expected": "<card>/" + "x" * 200,
"detail": "plan is partial: other members were refused",
"suggest_emulator": None,
"docs": "/docs/api/imports#unrecognised-layout",
}
payload = json.dumps(
{
"detail": {
"error": "import_refused",
"refusals": [
{**refusal, "member": f".import/save/card/{i:04d}/" + "y" * 100}
for i in range(200)
],
"truncated": 40,
}
}
).encode()
assert len(payload) > 64 * 1024
exc = urllib.error.HTTPError(
"http://broker/activate",
422,
"err",
http.client.HTTPMessage(),
io.BytesIO(payload),
)
with pytest.raises(broker.ImportRefusedError) as raised:
broker.raise_http_error(exc)
assert len(raised.value.refusals) == 200
assert raised.value.truncated == 40
def test_raise_http_error_keeps_a_long_plain_error_out_of_the_502_detail():
exc = _http_error(500)
with patch.object(exc, "read", return_value=b"x" * (100 * 1024)):
with pytest.raises(HTTPException) as raised:
broker.raise_http_error(exc)
assert len(raised.value.detail) < 9 * 1024
def test_raise_http_error_still_raises_502_for_a_plain_broker_error():
"""An ordinary broker error (not an import refusal) is still a plain 502."""
exc = _http_error(500)

View File

@@ -1046,6 +1046,30 @@ describe("Stream launch recovery", () => {
expect(vmOf(wrapper).errorHint).toBe("shape_mismatch");
});
it("names each refusal reason once however many members share it", async () => {
const wrapper = await launch({ picker: false });
await vmOf(wrapper).onPlay();
const refusal = (member: string, reason: string) => ({
reason,
member,
expected: null,
detail: null,
suggest_emulator: null,
docs: null,
});
await launchFailed({
refusals: [
refusal(".import/save/a.bin", "unrecognised_layout"),
refusal(".import/save/b.bin", "unrecognised_layout"),
refusal(".import/save/c.bin", "too_large"),
],
refusals_truncated: 0,
});
expect(vmOf(wrapper).errorHint).toBe("unrecognised_layout, too_large");
});
});
describe("Stream join", () => {

View File

@@ -733,13 +733,16 @@ useSocketEvent<LaunchFailed>("streaming:launch-failed", (payload) => {
errorType.value = "server";
if (payload.refusals?.length) {
errorMessage.value = t("play.stream-error-import-refused");
const hints = payload.refusals
.map((r) =>
r.suggest_emulator
? streamingStore.emulatorLabel(r.suggest_emulator)
: r.reason,
)
.join(", ");
// One refusal per rejected member, so a large archive repeats each reason.
const hints = [
...new Set(
payload.refusals.map((r) =>
r.suggest_emulator
? streamingStore.emulatorLabel(r.suggest_emulator)
: r.reason,
),
),
].join(", ");
const truncated = payload.refusals_truncated;
errorHint.value = truncated
? `${hints} (${t("play.import-refusals-truncated", truncated)})`