From b7c60e63a317ba0cd6a1a24808dc3a17fe3279ab Mon Sep 17 00:00:00 2001 From: Spinnich Date: Sat, 18 Jul 2026 20:06:12 +0000 Subject: [PATCH 1/3] fix(retroachievements): extract non-zip archives before RAHasher hashing RAHasher only decompresses .zip archives itself; any other container (.7z, .rar, .gz, .bz2, .xz, .tar, ...) was hashed as its raw archive bytes, silently storing a well-formed hash that matches nothing on RetroAchievements (issue #3808). Non-zip archives on buffer-hash platforms are now extracted to a temp file via the bundled 7zz binary and the extracted ROM is hashed instead. The new extract_largest_archive_member helper follows the existing 7zz subprocess patterns, handles single-stream formats whose listings carry no Attributes line (.gz/.xz), and unwraps one level of nesting so compressed tarballs (.tgz) reach the ROM inside the inner tar. Arcade is exempt: its RA hash is computed from the file's basename, so any container format already hashes correctly and extraction (which renames the file) would break it. Disc platforms keep their existing archive skip. When extraction fails (corrupt archive, or a codec the 7zz build lacks, e.g. RAR) no hash is stored at all and the 7zz stderr reason is logged at error level, so scan logs explain the missing hash instead of silently storing a garbage one. Fixes #3808 Co-Authored-By: Claude Fable 5 --- backend/adapters/services/rahasher.py | 40 +++ .../tests/adapters/services/test_rahasher.py | 256 +++++++++++++++++- backend/tests/utils/test_archives.py | 218 +++++++++++++++ backend/utils/archives.py | 134 +++++++++ 4 files changed, 647 insertions(+), 1 deletion(-) diff --git a/backend/adapters/services/rahasher.py b/backend/adapters/services/rahasher.py index faa14d568..769f330dd 100644 --- a/backend/adapters/services/rahasher.py +++ b/backend/adapters/services/rahasher.py @@ -1,5 +1,6 @@ import asyncio import re +import tempfile from pathlib import Path from handler.metadata.base_handler import UniversalPlatformSlug as UPS @@ -7,6 +8,7 @@ from handler.metadata.ra_handler import RAGamesPlatform from logger.formatter import LIGHTMAGENTA from logger.formatter import highlight as hl from logger.logger import log +from utils.archives import extract_largest_archive_member from utils.filesystem import COMPRESSED_FILE_EXTENSIONS from utils.psp_hasher import calculate_psp_ra_hash, is_psp_native_hash_file from utils.rvz_hasher import ( @@ -17,6 +19,11 @@ from utils.rvz_hasher import ( RAHASHER_VALID_HASH_REGEX = re.compile(r"[0-9a-f]{32}") +# The only archive format RAHasher decompresses itself (via miniz). Any other +# container is hashed as its raw archive bytes, silently producing a hash that +# matches nothing on RetroAchievements (issue #3808). +RAHASHER_NATIVE_ARCHIVE_EXTENSIONS: tuple[str, ...] = (".zip",) + # Disc descriptor / playlist files that point RAHasher at the real data # tracks. Handing RAHasher one of these reproduces the hash a shell-expanded # glob would, in priority order: a per-disc descriptor (.cue/.gdi) wins over @@ -179,6 +186,7 @@ RA_BUFFER_HASH_UNSUPPORTED_IDS: frozenset[int] = frozenset( PSP_RA_ID: int = PLATFORM_SLUG_TO_RETROACHIEVEMENTS_ID[UPS.PSP] NGC_RA_ID: int = PLATFORM_SLUG_TO_RETROACHIEVEMENTS_ID[UPS.NGC] WII_RA_ID: int = PLATFORM_SLUG_TO_RETROACHIEVEMENTS_ID[UPS.WII] +ARCADE_RA_ID: int = PLATFORM_SLUG_TO_RETROACHIEVEMENTS_ID[UPS.ARCADE] class RAHasherError(Exception): ... @@ -263,6 +271,38 @@ class RAHasherService: if is_native_entry: file_path = entry_str + # RAHasher only decompresses .zip archives itself; any other container + # gets hashed as its raw archive bytes, silently storing a hash that + # matches nothing on RetroAchievements (issue #3808). Extract the ROM + # to a temp file and hash that instead. Arcade is exempt: its RA hash + # is the file's own basename, so the container format never matters + # and extraction (which renames the file) would break it. + lower_path = file_path.lower() + if ( + lower_path.endswith(tuple(COMPRESSED_FILE_EXTENSIONS)) + and not lower_path.endswith(RAHASHER_NATIVE_ARCHIVE_EXTENSIONS) + and platform["ra_id"] != ARCADE_RA_ID + ): + with tempfile.TemporaryDirectory(prefix="romm_rahasher_") as tmp_dir: + extracted = await asyncio.to_thread( + extract_largest_archive_member, Path(file_path), Path(tmp_dir) + ) + if extracted is None: + log.debug( + f"Skipping {hl('RAHasher', color=LIGHTMAGENTA)} for " + f"{hl(file_path)}: could not extract a ROM from the archive" + ) + return "" + return await self._hash_resolved_file(platform, str(extracted)) + + return await self._hash_resolved_file(platform, file_path) + + async def _hash_resolved_file( + self, platform: RAGamesPlatform, file_path: str + ) -> str: + """Hash a single real file: natively for containers RAHasher can't + read (PSP compressed ISOs, RVZ/WIA), via the RAHasher binary otherwise. + """ # PSP compressed-ISO containers (.cso/.ciso/.zso/.dax) can't be read by # RAHasher ("Could not open track"). Compute the PSP RA hash natively # from the container instead, decompressing only PARAM.SFO + EBOOT.BIN. diff --git a/backend/tests/adapters/services/test_rahasher.py b/backend/tests/adapters/services/test_rahasher.py index d84de833d..19930f6bf 100644 --- a/backend/tests/adapters/services/test_rahasher.py +++ b/backend/tests/adapters/services/test_rahasher.py @@ -1,5 +1,5 @@ import asyncio -from unittest.mock import AsyncMock, patch +from unittest.mock import AsyncMock, MagicMock, patch import pytest @@ -1153,6 +1153,260 @@ class TestRAHasherM3uNativeResolution: assert str(disc1) in call_args +class TestRAHasherArchiveExtraction: + """Non-zip archives on buffer-hash platforms must be extracted to a temp + file before hashing. RAHasher only decompresses .zip itself; any other + container is hashed as raw archive bytes, silently producing a hash that + matches nothing on RetroAchievements (GitHub issue #3808).""" + + @pytest.fixture + def service(self): + return RAHasherService() + + @staticmethod + def _fake_extractor(inner_name: str): + """Build an extractor mock that writes `inner_name` into the given + destination directory, like the real helper does.""" + + def _extract(archive_path, dest_dir): + extracted = dest_dir / inner_name + extracted.write_bytes(b"rom-bytes") + return extracted + + return MagicMock(side_effect=_extract) + + @pytest.mark.asyncio + @pytest.mark.parametrize( + "ext", [".7z", ".rar", ".gz", ".bz2", ".xz", ".tar", ".tgz"] + ) + async def test_non_zip_archive_extracted_before_hashing( + self, service: RAHasherService, ext + ): + """RAHasher must receive the extracted ROM file, never the archive.""" + gba_id = PLATFORM_SLUG_TO_RETROACHIEVEMENTS_ID[UPS.GBA] + extractor = self._fake_extractor("game.gba") + + mock_proc = AsyncMock() + mock_proc.wait.return_value = 0 + mock_proc.stdout.read.return_value = b"a1b2c3d4e5f6789012345678901234ab\n" + mock_proc.stderr = None + + with ( + patch( + "adapters.services.rahasher.extract_largest_archive_member", + extractor, + ), + patch( + "asyncio.create_subprocess_exec", return_value=mock_proc + ) as mock_subprocess, + ): + result = await service.calculate_hash( + {"ra_id": gba_id, "slug": "gba"}, f"/roms/gba/game{ext}" + ) + + assert result == "a1b2c3d4e5f6789012345678901234ab" + extractor.assert_called_once() + call_args = mock_subprocess.call_args[0] + assert any(str(a).endswith("game.gba") for a in call_args) + assert not any(str(a).endswith(ext) for a in call_args) + + @pytest.mark.asyncio + async def test_zip_archive_still_handed_to_rahasher_directly( + self, service: RAHasherService + ): + """RAHasher decompresses .zip natively; no extraction round-trip.""" + gba_id = PLATFORM_SLUG_TO_RETROACHIEVEMENTS_ID[UPS.GBA] + + mock_proc = AsyncMock() + mock_proc.wait.return_value = 0 + mock_proc.stdout.read.return_value = b"a1b2c3d4e5f6789012345678901234ab\n" + mock_proc.stderr = None + + with ( + patch( + "adapters.services.rahasher.extract_largest_archive_member" + ) as extractor, + patch( + "asyncio.create_subprocess_exec", return_value=mock_proc + ) as mock_subprocess, + ): + result = await service.calculate_hash( + {"ra_id": gba_id, "slug": "gba"}, "/roms/gba/game.zip" + ) + + assert result == "a1b2c3d4e5f6789012345678901234ab" + extractor.assert_not_called() + call_args = mock_subprocess.call_args[0] + assert "/roms/gba/game.zip" in call_args + + @pytest.mark.asyncio + async def test_extraction_failure_returns_empty_hash_without_rahasher( + self, service: RAHasherService + ): + """When extraction fails (unsupported codec, corrupt archive), no + hash is produced at all; the archive must never reach RAHasher, + which would silently hash the raw container bytes.""" + gba_id = PLATFORM_SLUG_TO_RETROACHIEVEMENTS_ID[UPS.GBA] + + with ( + patch( + "adapters.services.rahasher.extract_largest_archive_member", + return_value=None, + ) as extractor, + patch("asyncio.create_subprocess_exec") as mock_subprocess, + ): + result = await service.calculate_hash( + {"ra_id": gba_id, "slug": "gba"}, "/roms/gba/game.rar" + ) + + assert result == "" + extractor.assert_called_once() + mock_subprocess.assert_not_called() + + @pytest.mark.asyncio + async def test_arcade_archives_bypass_extraction(self, service: RAHasherService): + """Arcade RA hashes are computed from the file's basename, not its + contents, so any container format already hashes correctly and + extraction (which renames the file) would break it.""" + arcade_id = PLATFORM_SLUG_TO_RETROACHIEVEMENTS_ID[UPS.ARCADE] + + mock_proc = AsyncMock() + mock_proc.wait.return_value = 0 + mock_proc.stdout.read.return_value = b"a1b2c3d4e5f6789012345678901234ab\n" + mock_proc.stderr = None + + with ( + patch( + "adapters.services.rahasher.extract_largest_archive_member" + ) as extractor, + patch( + "asyncio.create_subprocess_exec", return_value=mock_proc + ) as mock_subprocess, + ): + result = await service.calculate_hash( + {"ra_id": arcade_id, "slug": "arcade"}, "/roms/arcade/sf2.7z" + ) + + assert result == "a1b2c3d4e5f6789012345678901234ab" + extractor.assert_not_called() + call_args = mock_subprocess.call_args[0] + assert "/roms/arcade/sf2.7z" in call_args + + @pytest.mark.asyncio + async def test_disc_platform_archives_still_skipped_without_extraction( + self, service: RAHasherService + ): + """Disc platforms keep the existing skip; no extraction is attempted + (a multi-gigabyte disc image round-trip is out of scope).""" + psx_id = PLATFORM_SLUG_TO_RETROACHIEVEMENTS_ID[UPS.PSX] + + with ( + patch( + "adapters.services.rahasher.extract_largest_archive_member" + ) as extractor, + patch("asyncio.create_subprocess_exec") as mock_subprocess, + ): + result = await service.calculate_hash( + {"ra_id": psx_id, "slug": "psx"}, "/roms/psx/game.7z" + ) + + assert result == "" + extractor.assert_not_called() + mock_subprocess.assert_not_called() + + @pytest.mark.asyncio + async def test_folder_of_non_zip_archives_extracts_largest( + self, service: RAHasherService, tmp_path + ): + """Folder-based ROM holding non-zip archives: the largest archive is + picked (existing behavior) and must then go through extraction.""" + gba_id = PLATFORM_SLUG_TO_RETROACHIEVEMENTS_ID[UPS.GBA] + (tmp_path / "small.7z").write_bytes(b"s" * 100) + large = tmp_path / "large.7z" + large.write_bytes(b"l" * 500) + extractor = self._fake_extractor("game.gba") + + mock_proc = AsyncMock() + mock_proc.wait.return_value = 0 + mock_proc.stdout.read.return_value = b"a1b2c3d4e5f6789012345678901234ab\n" + mock_proc.stderr = None + + with ( + patch( + "adapters.services.rahasher.extract_largest_archive_member", + extractor, + ), + patch( + "asyncio.create_subprocess_exec", return_value=mock_proc + ) as mock_subprocess, + ): + result = await service.calculate_hash( + {"ra_id": gba_id, "slug": "gba"}, f"{tmp_path}/*" + ) + + assert result == "a1b2c3d4e5f6789012345678901234ab" + assert extractor.call_args[0][0] == large + call_args = mock_subprocess.call_args[0] + assert any(str(a).endswith("game.gba") for a in call_args) + + @pytest.mark.asyncio + async def test_extracted_rvz_short_circuits_native_hasher( + self, service: RAHasherService + ): + """GameCube is buffer-hash capable, so its archives are extracted; + when the archive holds an .rvz the native hasher must see it.""" + ngc_id = PLATFORM_SLUG_TO_RETROACHIEVEMENTS_ID[UPS.NGC] + extractor = self._fake_extractor("game.rvz") + + with ( + patch( + "adapters.services.rahasher.extract_largest_archive_member", + extractor, + ), + patch( + "adapters.services.rahasher.calculate_gamecube_ra_hash", + return_value="a1b2c3d4e5f6789012345678901234ab", + ) as mock_native, + patch("asyncio.create_subprocess_exec") as mock_subprocess, + ): + result = await service.calculate_hash( + {"ra_id": ngc_id, "slug": "ngc"}, "/roms/ngc/game.7z" + ) + + assert result == "a1b2c3d4e5f6789012345678901234ab" + assert mock_native.call_args[0][0].endswith("game.rvz") + mock_subprocess.assert_not_called() + + @pytest.mark.asyncio + async def test_temp_extraction_dir_removed_after_hashing( + self, service: RAHasherService + ): + """The temp directory holding the extracted ROM must not outlive the + hash calculation.""" + gba_id = PLATFORM_SLUG_TO_RETROACHIEVEMENTS_ID[UPS.GBA] + extractor = self._fake_extractor("game.gba") + + mock_proc = AsyncMock() + mock_proc.wait.return_value = 0 + mock_proc.stdout.read.return_value = b"a1b2c3d4e5f6789012345678901234ab\n" + mock_proc.stderr = None + + with ( + patch( + "adapters.services.rahasher.extract_largest_archive_member", + extractor, + ), + patch("asyncio.create_subprocess_exec", return_value=mock_proc), + ): + result = await service.calculate_hash( + {"ra_id": gba_id, "slug": "gba"}, "/roms/gba/game.7z" + ) + + assert result == "a1b2c3d4e5f6789012345678901234ab" + dest_dir = extractor.call_args[0][1] + assert not dest_dir.exists() + + class TestRAHasherError: """Test the RAHasherError exception.""" diff --git a/backend/tests/utils/test_archives.py b/backend/tests/utils/test_archives.py index 26e66608b..c68018aad 100644 --- a/backend/tests/utils/test_archives.py +++ b/backend/tests/utils/test_archives.py @@ -10,6 +10,42 @@ def _fake_7z_listing(names: list[str]) -> str: return "\n".join(f"Path = {name}\nSize = 10\nAttributes = A\n" for name in names) +def _fake_7z_listing_sized( + entries: list[tuple[str, int]], attributes: bool = True +) -> str: + """Build a `7zz l -slt -ba` style listing with explicit member sizes. + + Single-stream formats (.gz/.xz) list no Attributes line at all, which + `attributes=False` reproduces. + """ + blocks = [] + for name, size in entries: + block = f"Path = {name}\nSize = {size}\n" + if attributes: + block += "Attributes = A -rw-rw-r--\n" + blocks.append(block) + return "\n".join(blocks) + + +def _mock_popen_streaming( + chunk_streams: list[list[bytes]], + returncodes: list[int], + stderr: bytes = b"", +): + """Build a subprocess.Popen mock whose consecutive context-managed calls + stream the given chunk lists and finish with the given return codes.""" + popen = MagicMock() + processes = [] + for chunks, returncode in zip(chunk_streams, returncodes, strict=True): + process = MagicMock() + process.stdout.read.side_effect = [*chunks, b""] + process.stderr.read.return_value = stderr + process.returncode = returncode + processes.append(process) + popen.return_value.__enter__.side_effect = processes + return popen + + def test_stream_7z_chunks_yields_until_eof(): process = MagicMock() process.stdout.read.side_effect = [b"abc", b"def", b""] @@ -60,3 +96,185 @@ def test_read_7z_archive_files_timeout_logs_once_without_spam(monkeypatch): assert results == [] popen_patch.assert_not_called() assert log_error.call_count == 1 + + +class TestExtractLargestArchiveMember: + """Extraction of an archive's largest member to a destination directory, + used to feed RAHasher a real ROM file instead of raw container bytes + (GitHub issue #3808).""" + + def test_extracts_largest_member_to_dest_dir(self, tmp_path): + listing = MagicMock( + stdout=_fake_7z_listing_sized([("small.txt", 10), ("game.gba", 500)]) + ) + popen = _mock_popen_streaming([[b"abc", b"def"]], [0]) + + with ( + patch.object(archives.subprocess, "run", return_value=listing), + patch.object(archives.subprocess, "Popen", popen), + ): + result = archives.extract_largest_archive_member( + Path("/fake/game.7z"), tmp_path + ) + + assert result is not None + assert result == tmp_path / "game.gba" + assert result.read_bytes() == b"abcdef" + # The largest member, not the first, must be requested from 7zz. + extract_args = popen.call_args[0][0] + assert "game.gba" in extract_args + + def test_member_folder_prefix_is_stripped_from_dest_name(self, tmp_path): + """Members nested in archive folders extract to a flat file name.""" + listing = MagicMock(stdout=_fake_7z_listing_sized([("subdir/game.gba", 500)])) + popen = _mock_popen_streaming([[b"abc"]], [0]) + + with ( + patch.object(archives.subprocess, "run", return_value=listing), + patch.object(archives.subprocess, "Popen", popen), + ): + result = archives.extract_largest_archive_member( + Path("/fake/game.7z"), tmp_path + ) + + assert result == tmp_path / "game.gba" + + def test_listing_without_attributes_still_finds_member(self, tmp_path): + """Single-stream formats (.gz/.xz) list no Attributes line; the member + must still be found (7zz omits it for them).""" + listing = MagicMock( + stdout=_fake_7z_listing_sized([("game.gba", 500)], attributes=False) + ) + popen = _mock_popen_streaming([[b"abc"]], [0]) + + with ( + patch.object(archives.subprocess, "run", return_value=listing), + patch.object(archives.subprocess, "Popen", popen), + ): + result = archives.extract_largest_archive_member( + Path("/fake/game.gba.gz"), tmp_path + ) + + assert result == tmp_path / "game.gba" + + def test_directory_members_are_ignored(self, tmp_path): + listing = MagicMock( + stdout=( + "Path = folder\nSize = 0\nAttributes = D drwxr-xr-x\n\n" + + _fake_7z_listing_sized([("game.gba", 500)]) + ) + ) + popen = _mock_popen_streaming([[b"abc"]], [0]) + + with ( + patch.object(archives.subprocess, "run", return_value=listing), + patch.object(archives.subprocess, "Popen", popen), + ): + result = archives.extract_largest_archive_member( + Path("/fake/game.7z"), tmp_path + ) + + assert result == tmp_path / "game.gba" + + def test_nested_archive_is_extracted_once_more(self, tmp_path): + """A .tgz lists only its inner .tar; the ROM inside the tar must be + reached through a second extraction pass.""" + listings = [ + MagicMock(stdout=_fake_7z_listing_sized([("game.tar", 600)])), + MagicMock(stdout=_fake_7z_listing_sized([("game.gba", 500)])), + ] + popen = _mock_popen_streaming([[b"tarbytes"], [b"rombytes"]], [0, 0]) + + with ( + patch.object(archives.subprocess, "run", side_effect=listings), + patch.object(archives.subprocess, "Popen", popen), + ): + result = archives.extract_largest_archive_member( + Path("/fake/game.tgz"), tmp_path + ) + + assert result is not None + assert result == tmp_path / "game.gba" + assert result.read_bytes() == b"rombytes" + # The intermediate tar must not be left behind. + assert not (tmp_path / "game.tar").exists() + + def test_gives_up_on_doubly_nested_archives(self, tmp_path): + """Two levels of nesting is the limit; deeper nesting returns None + and leaves no partial files behind.""" + listings = [ + MagicMock(stdout=_fake_7z_listing_sized([("inner.tar", 600)])), + MagicMock(stdout=_fake_7z_listing_sized([("innermost.7z", 500)])), + ] + popen = _mock_popen_streaming([[b"tarbytes"], [b"7zbytes"]], [0, 0]) + + with ( + patch.object(archives.subprocess, "run", side_effect=listings), + patch.object(archives.subprocess, "Popen", popen), + ): + result = archives.extract_largest_archive_member( + Path("/fake/game.tgz"), tmp_path + ) + + assert result is None + assert list(tmp_path.iterdir()) == [] + + def test_returns_none_when_listing_fails(self, tmp_path): + with patch.object( + archives.subprocess, + "run", + side_effect=archives.subprocess.CalledProcessError(2, "7zz"), + ): + result = archives.extract_largest_archive_member( + Path("/fake/game.7z"), tmp_path + ) + + assert result is None + + def test_returns_none_when_archive_has_no_members(self, tmp_path): + listing = MagicMock(stdout="") + + with patch.object(archives.subprocess, "run", return_value=listing): + result = archives.extract_largest_archive_member( + Path("/fake/game.7z"), tmp_path + ) + + assert result is None + + def test_returns_none_and_cleans_up_on_extract_failure(self, tmp_path): + """A codec the 7zz build can't decompress (e.g. RAR) streams nothing + and exits non-zero; no partial file may be left behind, and the 7zz + reason must reach the error log so scans explain the missing hash.""" + listing = MagicMock(stdout=_fake_7z_listing_sized([("game.gba", 500)])) + popen = _mock_popen_streaming( + [[]], [2], stderr=b"ERROR: Unsupported Method : game.gba" + ) + + with ( + patch.object(archives.subprocess, "run", return_value=listing), + patch.object(archives.subprocess, "Popen", popen), + patch.object(archives.log, "error") as log_error, + ): + result = archives.extract_largest_archive_member( + Path("/fake/game.rar"), tmp_path + ) + + assert result is None + assert list(tmp_path.iterdir()) == [] + assert "Unsupported Method" in log_error.call_args[0][0] + + def test_returns_none_and_cleans_up_on_timeout(self, tmp_path, monkeypatch): + monkeypatch.setattr(archives, "SEVEN_ZIP_TIMEOUT", -1) + listing = MagicMock(stdout=_fake_7z_listing_sized([("game.gba", 500)])) + popen = _mock_popen_streaming([[b"abc", b"def"]], [0]) + + with ( + patch.object(archives.subprocess, "run", return_value=listing), + patch.object(archives.subprocess, "Popen", popen), + ): + result = archives.extract_largest_archive_member( + Path("/fake/game.7z"), tmp_path + ) + + assert result is None + assert list(tmp_path.iterdir()) == [] diff --git a/backend/utils/archives.py b/backend/utils/archives.py index 8e9851224..0cc0e0706 100644 --- a/backend/utils/archives.py +++ b/backend/utils/archives.py @@ -404,6 +404,140 @@ def read_rar_archive_files( return read_7z_archive_files(file_path, excluded_names, excluded_exts) +def _list_archive_file_members(file_path: Path) -> list[tuple[str, int]]: + """List `(member_path, size)` for every file member via `7zz l -slt -ba`. + + Single-stream formats (.gz/.xz) list no `Attributes` line at all, so an + entry is committed when the next `Path =` starts or the listing ends, + and only dropped when its attributes mark it as a directory. + """ + try: + result = subprocess.run( + [SEVEN_ZIP_PATH, "l", "-slt", "-ba", str(file_path)], + capture_output=True, + text=True, + check=True, + timeout=SEVEN_ZIP_TIMEOUT, + shell=False, # trunk-ignore(bandit/B603): 7z path is hardcoded, args are validated + ) + except ( + subprocess.TimeoutExpired, + subprocess.CalledProcessError, + FileNotFoundError, + ) as e: + log.error(f"Error listing archive {file_path}: {e}") + return [] + + entries: list[tuple[str, int]] = [] + current_file: str | None = None + current_size = 0 + current_is_dir = False + + def _commit() -> None: + if current_file and not current_is_dir: + entries.append((current_file, current_size)) + + for line in result.stdout.split("\n"): + line = line.lstrip() + if line.startswith("Path = "): + _commit() + current_file = line.split(" = ", 1)[1] + current_size = 0 + current_is_dir = False + elif line.startswith("Size = "): + try: + current_size = int(line.split(" = ")[1].strip()) + except ValueError: + current_size = 0 + elif line.startswith("Attributes = "): + current_is_dir = line.split(" = ")[1].strip().startswith("D") + _commit() + + return entries + + +def _extract_member_to_dir( + file_path: Path, member: str, dest_dir: Path, deadline: float +) -> Path | None: + """Stream one archive member into `dest_dir`, named after its basename. + + Returns None (leaving no partial file) when extraction fails, exceeds + the deadline, or the 7zz build lacks the codec (it then streams nothing + and exits non-zero, e.g. for RAR). + """ + dest_path = dest_dir / Path(member).name + stderr_output = b"" + try: + with ( + open(dest_path, "wb") as dest_file, + subprocess.Popen( + [SEVEN_ZIP_PATH, "e", str(file_path), member, "-so", "-y"], + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + shell=False, # trunk-ignore(bandit/B603): 7z path is hardcoded, args are validated + ) as process, + ): + assert process.stdout is not None + while chunk := process.stdout.read(FILE_READ_CHUNK_SIZE): + if time.monotonic() > deadline: + process.terminate() + log.error(f"Extraction of {member} from {file_path} timed out") + dest_path.unlink(missing_ok=True) + return None + dest_file.write(chunk) + if process.stderr is not None: + stderr_output = process.stderr.read() + + if process.returncode != 0: + # Surface the 7zz reason (e.g. "Unsupported Method" from a build + # without the RAR codec) so scan logs explain the missing hash. + detail = stderr_output.decode(errors="replace").strip() + log.error( + f"Extraction of {member} from {file_path} failed " + f"with code {process.returncode}: {detail or 'no error output'}" + ) + dest_path.unlink(missing_ok=True) + return None + + return dest_path + except OSError as e: + log.error(f"Error extracting {member} from {file_path}: {e}") + dest_path.unlink(missing_ok=True) + return None + + +def extract_largest_archive_member(file_path: Path, dest_dir: Path) -> Path | None: + """Extract an archive's largest file member into `dest_dir` via 7zz. + + Compressed tarballs (.tgz/.tbz2/.txz) list only their inner .tar, so one + nested extraction pass unwraps it; deeper nesting gives up. Returns the + extracted file's path, or None on any failure (no partial files remain). + """ + deadline = time.monotonic() + SEVEN_ZIP_TIMEOUT + source = file_path + + for _ in range(2): + members = _list_archive_file_members(source) + extracted = ( + _extract_member_to_dir( + source, max(members, key=lambda m: m[1])[0], dest_dir, deadline + ) + if members + else None + ) + if source != file_path: + source.unlink(missing_ok=True) + if extracted is None: + return None + if not str(extracted).lower().endswith(tuple(COMPRESSED_FILE_EXTENSIONS)): + return extracted + source = extracted + + log.error(f"Archive {file_path} is nested too deeply to extract") + source.unlink(missing_ok=True) + return None + + def is_chd_file(file_path: Path) -> bool: """Return True if the file is a CHD by extension or libmagic-detected MIME type.""" if file_path.suffix.lower() == ".chd": From e24b40a4eb86d2e3a4e89c23ecd8c567628661eb Mon Sep 17 00:00:00 2001 From: Spinnich Date: Sat, 18 Jul 2026 20:11:21 +0000 Subject: [PATCH 2/3] docs(archives): correct RAR support claim in read_rar_archive_files The bundled Alpine 7zz build lacks the RAR codec: listing RAR members works, but streaming their contents fails with "Unsupported Method" (verified against the production image). Co-Authored-By: Claude Fable 5 --- backend/utils/archives.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/backend/utils/archives.py b/backend/utils/archives.py index 0cc0e0706..f6d640359 100644 --- a/backend/utils/archives.py +++ b/backend/utils/archives.py @@ -399,7 +399,9 @@ def read_rar_archive_files( ) -> Iterator[tuple[str, int, Iterator[bytes]]]: """Yield eligible files from a RAR archive, sorted by internal path (ASCII). - Delegates to the 7zz binary, which natively supports RAR (v3-v5, read-only). + Delegates to the 7zz binary. Listing RAR members always works, but + streaming their contents requires a 7zz build with the RAR codec; the + bundled Alpine build lacks it, so content reads fail and log an error. """ return read_7z_archive_files(file_path, excluded_names, excluded_exts) From e6c1ca8487d0912de54db8a2e2a767c7eb9e9da9 Mon Sep 17 00:00:00 2001 From: Spinnich Date: Sat, 18 Jul 2026 20:34:44 +0000 Subject: [PATCH 3/3] fix(archives): address extraction review findings from PR #3813 Disable 7zz wildcard matching (-spd) when extracting a named member: a member literally named with "*" or "?" would otherwise act as a pattern, matching other members and concatenating them into the -so stream, which would hash plausible-but-wrong data. Applied to all three extraction call sites, including the two pre-existing readers that share the hazard. Verified against the production Alpine 7zz build. Route extraction stderr to an unlinked temp file instead of a pipe: a filled pipe blocks 7zz while the parent waits on stdout.read(), which the chunk-based deadline never interrupts. A file-backed stderr applies no backpressure and is still read back for the error log on failure. Co-Authored-By: Claude Fable 5 --- backend/tests/utils/test_archives.py | 24 ++++++++-- backend/utils/archives.py | 69 +++++++++++++++------------- 2 files changed, 57 insertions(+), 36 deletions(-) diff --git a/backend/tests/utils/test_archives.py b/backend/tests/utils/test_archives.py index c68018aad..16dda569b 100644 --- a/backend/tests/utils/test_archives.py +++ b/backend/tests/utils/test_archives.py @@ -33,16 +33,29 @@ def _mock_popen_streaming( stderr: bytes = b"", ): """Build a subprocess.Popen mock whose consecutive context-managed calls - stream the given chunk lists and finish with the given return codes.""" + stream the given chunk lists and finish with the given return codes. + + `stderr` bytes are written into the file object the caller passes as the + `stderr` argument, mirroring 7zz writing diagnostics to a file-backed + stderr.""" popen = MagicMock() processes = [] for chunks, returncode in zip(chunk_streams, returncodes, strict=True): process = MagicMock() process.stdout.read.side_effect = [*chunks, b""] - process.stderr.read.return_value = stderr process.returncode = returncode processes.append(process) - popen.return_value.__enter__.side_effect = processes + process_iter = iter(processes) + + def _popen_call(*args, **kwargs): + stderr_target = kwargs.get("stderr") + if stderr and stderr_target is not None: + stderr_target.write(stderr) + context = MagicMock() + context.__enter__.return_value = next(process_iter) + return context + + popen.side_effect = _popen_call return popen @@ -120,9 +133,12 @@ class TestExtractLargestArchiveMember: assert result is not None assert result == tmp_path / "game.gba" assert result.read_bytes() == b"abcdef" - # The largest member, not the first, must be requested from 7zz. + # The largest member, not the first, must be requested from 7zz, with + # wildcard matching disabled so a member name containing "*" or "?" + # can't select (and concatenate) other members. extract_args = popen.call_args[0][0] assert "game.gba" in extract_args + assert "-spd" in extract_args def test_member_folder_prefix_is_stripped_from_dest_name(self, tmp_path): """Members nested in archive folders extract to a flat file name.""" diff --git a/backend/utils/archives.py b/backend/utils/archives.py index f6d640359..d7451490c 100644 --- a/backend/utils/archives.py +++ b/backend/utils/archives.py @@ -5,6 +5,7 @@ import fnmatch import os import subprocess import tarfile +import tempfile import threading import time import zipfile @@ -155,7 +156,7 @@ def _process_largest_7z_member( start_decompression_time = time.monotonic() with subprocess.Popen( - [SEVEN_ZIP_PATH, "e", str(file_path), largest_file, "-so", "-y"], + [SEVEN_ZIP_PATH, "e", str(file_path), largest_file, "-so", "-y", "-spd"], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, shell=False, # trunk-ignore(bandit/B603): 7z path is hardcoded, args are validated @@ -369,7 +370,7 @@ def read_7z_archive_files( break try: with subprocess.Popen( - [SEVEN_ZIP_PATH, "e", str(file_path), name, "-so", "-y"], + [SEVEN_ZIP_PATH, "e", str(file_path), name, "-so", "-y", "-spd"], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, shell=False, # trunk-ignore(bandit/B603) @@ -468,38 +469,42 @@ def _extract_member_to_dir( and exits non-zero, e.g. for RAR). """ dest_path = dest_dir / Path(member).name - stderr_output = b"" try: - with ( - open(dest_path, "wb") as dest_file, - subprocess.Popen( - [SEVEN_ZIP_PATH, "e", str(file_path), member, "-so", "-y"], - stdout=subprocess.PIPE, - stderr=subprocess.PIPE, - shell=False, # trunk-ignore(bandit/B603): 7z path is hardcoded, args are validated - ) as process, - ): - assert process.stdout is not None - while chunk := process.stdout.read(FILE_READ_CHUNK_SIZE): - if time.monotonic() > deadline: - process.terminate() - log.error(f"Extraction of {member} from {file_path} timed out") - dest_path.unlink(missing_ok=True) - return None - dest_file.write(chunk) - if process.stderr is not None: - stderr_output = process.stderr.read() + # stderr goes to an unlinked temp file rather than a pipe: a pipe can + # fill and block 7zz while this thread waits on stdout, stalling past + # the deadline. "-spd" disables wildcard matching so a member name + # containing "*" or "?" can't select (and concatenate) other members. + with tempfile.TemporaryFile() as stderr_file: + with ( + open(dest_path, "wb") as dest_file, + subprocess.Popen( + [SEVEN_ZIP_PATH, "e", str(file_path), member, "-so", "-y", "-spd"], + stdout=subprocess.PIPE, + stderr=stderr_file, + shell=False, # trunk-ignore(bandit/B603): 7z path is hardcoded, args are validated + ) as process, + ): + assert process.stdout is not None + while chunk := process.stdout.read(FILE_READ_CHUNK_SIZE): + if time.monotonic() > deadline: + process.terminate() + log.error(f"Extraction of {member} from {file_path} timed out") + dest_path.unlink(missing_ok=True) + return None + dest_file.write(chunk) - if process.returncode != 0: - # Surface the 7zz reason (e.g. "Unsupported Method" from a build - # without the RAR codec) so scan logs explain the missing hash. - detail = stderr_output.decode(errors="replace").strip() - log.error( - f"Extraction of {member} from {file_path} failed " - f"with code {process.returncode}: {detail or 'no error output'}" - ) - dest_path.unlink(missing_ok=True) - return None + if process.returncode != 0: + # Surface the 7zz reason (e.g. "Unsupported Method" from a + # build without the RAR codec) so scan logs explain the + # missing hash. + stderr_file.seek(0) + detail = stderr_file.read().decode(errors="replace").strip() + log.error( + f"Extraction of {member} from {file_path} failed " + f"with code {process.returncode}: {detail or 'no error output'}" + ) + dest_path.unlink(missing_ok=True) + return None return dest_path except OSError as e: