From 87c38eebf6bfb97aac518c3c3ed27c53a0d484ce Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi <3247106+gantoine@users.noreply.github.com> Date: Tue, 17 Nov 2026 08:56:12 -0500 Subject: [PATCH] fix(patcher): cap the output size a patch can declare (#5632) * fix(patcher): cap the output size a patch can declare RomPatcher.js allocates the patched ROM from the size written in the patch header, so a few-byte UPS/BPS/APS/BDF/RUP patch could make the Node patcher allocate and write gigabytes. patcher.js now wraps the BinFile constructor and refuses any allocation above a cap passed by the backend: twice the source ROM, or the ROM plus 64 MiB when that is larger, never above ROM_PATCHER_MAX_FILE_SIZE_BYTES. An oversized output is reported with exit code 3 and surfaces as a 400. Co-Authored-By: Claude Opus 5.5 * test(patcher): run the output size guard through the real patcher.js The CI pytest job now installs Node and RomPatcher.js so the patcher tests can exercise patcher.js itself: a UPS patch declaring a 2 GiB output is rejected, and one growing the ROM within the cap applies. The tests skip when node or RomPatcher.js is missing locally. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- .github/workflows/pytest.yml | 10 ++ backend/tests/endpoints/roms/test_patch.py | 25 +++++ backend/tests/utils/test_rom_patcher.py | 107 ++++++++++++++++++++- backend/utils/rom_patcher/patcher.js | 32 +++++- backend/utils/rom_patcher/patcher.py | 23 ++++- 5 files changed, 189 insertions(+), 8 deletions(-) diff --git a/.github/workflows/pytest.yml b/.github/workflows/pytest.yml index abc8f509d..c259519fa 100644 --- a/.github/workflows/pytest.yml +++ b/.github/workflows/pytest.yml @@ -76,6 +76,16 @@ jobs: sync-args: --extra test apt-packages: 7zip + # The ROM patcher tests run the real patcher.js, which needs RomPatcher.js. + - name: Set up Node.js + uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version-file: frontend/.nvmrc + + - name: Install the ROM patcher dependencies + working-directory: backend/utils/rom_patcher + run: npm ci --ignore-scripts --no-audit --no-fund + - name: Initiate MariaDB database if: matrix.db == 'mariadb' env: diff --git a/backend/tests/endpoints/roms/test_patch.py b/backend/tests/endpoints/roms/test_patch.py index 8f9057888..1624db039 100644 --- a/backend/tests/endpoints/roms/test_patch.py +++ b/backend/tests/endpoints/roms/test_patch.py @@ -542,6 +542,31 @@ class TestPatcherFailures: assert len(scratch.made) == 1 assert scratch.all_removed() + def test_a_patch_declaring_too_large_an_output_is_rejected( + self, + client: TestClient, + access_token: str, + rom: Rom, + library: Path, + scratch: Scratch, + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + ): + install_fake_node(tmp_path, monkeypatch, "sys.exit(3)") + game = _file(library, rom, "game.sfc", b"rom") + + response = client.post( + f"/api/roms/{game.id}/patch", + headers=bearer(access_token), + files={"patch_file": ("bomb.ups", b"UPS1")}, + ) + + assert response.status_code == status.HTTP_400_BAD_REQUEST + assert response.json() == { + "detail": "The patch would produce a ROM that is too large" + } + assert scratch.all_removed() + def test_an_unexpected_error_is_a_500( self, client: TestClient, diff --git a/backend/tests/utils/test_rom_patcher.py b/backend/tests/utils/test_rom_patcher.py index 6533f7a50..79d920450 100644 --- a/backend/tests/utils/test_rom_patcher.py +++ b/backend/tests/utils/test_rom_patcher.py @@ -1,6 +1,9 @@ import json import os +import shutil +import struct import zipfile +import zlib from collections.abc import Awaitable, Callable, Iterator from pathlib import Path from unittest.mock import MagicMock @@ -17,6 +20,10 @@ from utils.rom_patcher import ( apply_patch, ) from utils.rom_patcher import patcher as rom_patcher +from utils.rom_patcher.patcher import ( + MIN_PATCH_OUTPUT_GROWTH_BYTES, + max_patch_output_size, +) from utils.zip_cache import ensure_zipfile_writable @@ -47,6 +54,23 @@ def _fake_patcher( return patch +@pytest.mark.parametrize( + ("rom_size", "cap", "expected"), + [ + (4, 4 * 1024**3, 4 + MIN_PATCH_OUTPUT_GROWTH_BYTES), + (512 * 1024**2, 4 * 1024**3, 1024 * 1024**2), + (3 * 1024**3, 4 * 1024**3, 4 * 1024**3), + ], + ids=["small_rom_grows_by_the_minimum", "large_rom_doubles", "global_cap"], +) +def test_max_patch_output_size( + monkeypatch: pytest.MonkeyPatch, rom_size: int, cap: int, expected: int +): + monkeypatch.setattr(rom_patcher, "ROM_PATCHER_MAX_FILE_SIZE_BYTES", cap) + + assert max_patch_output_size(rom_size) == expected + + def test_supported_patch_extensions_include_xdelta(): assert ".xdelta" in SUPPORTED_PATCH_EXTENSIONS @@ -378,7 +402,7 @@ class TestPatcherProcess: patch.write_bytes(b"+patch") return rom, patch, tmp_path / "out" / "patched.sfc" - async def test_runs_the_patcher_script_on_the_three_paths( + async def test_runs_the_patcher_script_on_the_paths_and_output_cap( self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, @@ -397,7 +421,32 @@ class TestPatcherProcess: assert output.read_bytes() == b"rom+patch" argv = json.loads((tmp_path / "argv.json").read_text()) - assert argv == [str(PATCHER_SCRIPT), str(rom), str(patch), str(output)] + assert argv == [ + str(PATCHER_SCRIPT), + str(rom), + str(patch), + str(output), + str(max_patch_output_size(len(b"rom"))), + ] + + async def test_an_output_over_the_cap_is_an_input_error( + self, + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + files: tuple[Path, Path, Path], + ): + rom, patch, output = files + install_fake_node( + tmp_path, + monkeypatch, + """ + sys.stderr.write(json.dumps({"error": "declares 2147483647 bytes"})) + sys.exit(3) + """, + ) + + with pytest.raises(PatcherInputError, match="too large"): + await apply_patch(rom, patch, output) @pytest.mark.parametrize( "stdout", @@ -550,6 +599,60 @@ class TestPatcherProcess: ] +def _ups_number(value: int) -> bytes: + encoded = bytearray() + while True: + low = value & 0x7F + value >>= 7 + if value == 0: + encoded.append(0x80 | low) + return bytes(encoded) + encoded.append(low) + value -= 1 + + +def _ups_patch(source: bytes, target_size: int, target: bytes) -> bytes: + """A UPS patch with no records, declaring ``target_size`` as its output.""" + body = b"UPS1" + _ups_number(len(source)) + _ups_number(target_size) + body += struct.pack(" + * node patcher.js * * Exit codes: * 0 - success * 1 - usage / argument error * 2 - patching error + * 3 - the patch declares an output larger than max_output_bytes */ const path = require("path"); @@ -34,7 +35,9 @@ function resolveRomPatcherBase() { const ROM_PATCHER_BASE = resolveRomPatcherBase(); // Load the library (sets globals that RomPatcher.js expects) -require(path.join(ROM_PATCHER_BASE, "modules", "BinFile.js")); +const BaseBinFile = require( + path.join(ROM_PATCHER_BASE, "modules", "BinFile.js"), +); require(path.join(ROM_PATCHER_BASE, "modules", "HashCalculator.js")); require(path.join(ROM_PATCHER_BASE, "modules", "RomPatcher.format.aps_gba.js")); require(path.join(ROM_PATCHER_BASE, "modules", "RomPatcher.format.aps_n64.js")); @@ -49,13 +52,32 @@ require(path.join(ROM_PATCHER_BASE, "modules", "RomPatcher.format.vcdiff.js")); const RomPatcher = require(path.join(ROM_PATCHER_BASE, "RomPatcher.js")); const args = process.argv.slice(2); -if (args.length !== 3) { - console.error("Usage: node patcher.js "); +const maxOutputBytes = Number(args[3]); +if (args.length !== 4 || !Number.isSafeInteger(maxOutputBytes)) { + console.error( + "Usage: node patcher.js ", + ); process.exit(1); } const [romPath, patchPath, outputPath] = args; +class OutputTooLargeError extends Error {} + +// Every format allocates its output with `new BinFile(size)` from a size read +// out of the patch, so a tiny patch can otherwise demand gigabytes. +globalThis.BinFile = new Proxy(BaseBinFile, { + construct(target, ctorArgs, newTarget) { + const [source] = ctorArgs; + if (typeof source === "number" && source > maxOutputBytes) { + throw new OutputTooLargeError( + `The patch declares an output of ${source} bytes (max ${maxOutputBytes})`, + ); + } + return Reflect.construct(target, ctorArgs, newTarget); + }, +}); + try { // Validate input files exist if (!fs.existsSync(romPath)) { @@ -115,5 +137,5 @@ try { console.error( JSON.stringify({ success: false, error: err.message || String(err) }), ); - process.exit(2); + process.exit(err instanceof OutputTooLargeError ? 3 : 2); } diff --git a/backend/utils/rom_patcher/patcher.py b/backend/utils/rom_patcher/patcher.py index a71eb0ff4..d0a6328a7 100644 --- a/backend/utils/rom_patcher/patcher.py +++ b/backend/utils/rom_patcher/patcher.py @@ -52,6 +52,22 @@ def is_patch_file_name(file_name: str) -> bool: return Path(file_name).suffix.lower() in SUPPORTED_PATCH_EXTENSIONS +# Hacks may double a ROM or expand a small one to its console's largest +# cartridge, but never further; the patch's own declared size is not trusted. +MIN_PATCH_OUTPUT_GROWTH_BYTES = 64 * 1024 * 1024 + +# Exit code patcher.js uses when the patch declares too large an output. +_OUTPUT_TOO_LARGE_EXIT_CODE = 3 + + +def max_patch_output_size(rom_size: int) -> int: + """Largest patched ROM accepted for a source ROM of ``rom_size`` bytes.""" + return min( + ROM_PATCHER_MAX_FILE_SIZE_BYTES, + rom_size + max(rom_size, MIN_PATCH_OUTPUT_GROWTH_BYTES), + ) + + # Bound concurrent operations because each Node subprocess loads a full ROM. _patch_semaphore = asyncio.Semaphore(ROM_PATCHER_MAX_CONCURRENCY) @@ -217,14 +233,17 @@ async def _apply_binary_patch( regardless; the result lets callers warn on a likely ROM/patch mismatch. Raises :class:`PatcherError` if the subprocess fails, times out, or the - output file is missing. + output file is missing, and :class:`PatcherInputError` if the patch + declares an output larger than :func:`max_patch_output_size` allows. """ + rom_size = (await AnyioPath(rom_path).stat()).st_size proc = await asyncio.create_subprocess_exec( "node", str(PATCHER_SCRIPT), str(rom_path), str(patch_path), str(output_path), + str(max_patch_output_size(rom_size)), stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, ) @@ -237,6 +256,8 @@ async def _apply_binary_patch( await proc.wait() raise PatcherError(f"Patching timed out after {ROM_PATCHER_TIMEOUT}s") from e + if proc.returncode == _OUTPUT_TOO_LARGE_EXIT_CODE: + raise PatcherInputError("The patch would produce a ROM that is too large") if proc.returncode != 0: error = _last_json_object(stderr).get("error") if isinstance(error, str) and error: