~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
security: backport bounded CPython zipfile decompression (#6204)
LearningCircuitced84c5232ce
diff --git a/.grype.yaml b/.grype.yamlindex 9403fbad68..8547bba6f6 100644--- a/.grype.yaml+++ b/.grype.yaml@@ -289,6 +289,20 @@ ignore:package: { name: python, type: binary }reason: "Medium stringprep processes RFC 3454 B.2/B.3 tables with current Unicode instead of 3.2.0, causing IDNA-2003 mismatches. Not reachable: zero stringprep/encodings.idna usage in src/ (dns_pinning.py deliberately avoids the idna codec); hostname encoding goes through the third-party idna package (IDNA 2008) via requests/urllib3. Fix post-3.14.7; remove when base image ships 3.14.8+."+ # CVE-2026-15310 is tracked separately from the 2026-08-18 batch above: it is+ # not merely unreachable/unfixed-upstream, it is actively patched in the+ # image, and its removal condition is its own.+ - vulnerability: CVE-2026-15310+ package: { name: python, type: binary }+ reason: >-+ The official CPython 3.14 zipfile fix (31980e84b9a708424a0a1dfecde3fc991e313f89)+ is backported by scripts/patch_cpython_zipfile_cve_2026_15310.py in both stages+ built directly from the pinned base image (builder-base, ldr); the other two+ stages (builder, ldr-test) inherit it from builder-base. Verified during the+ build. The binary CPE remains 3.14.7, so Grype cannot observe the patched+ pure-Python stdlib file. Remove this entry and the backport when a fixed+ Python 3.14 image is released.+# ==========================================================================# NO FIX AVAILABLE IN DEBIAN TRIXIE# ==========================================================================diff --git a/Dockerfile b/Dockerfileindex 17b0cc5342..1bda65c21a 100644--- a/Dockerfile+++ b/Dockerfile@@ -3,6 +3,12 @@####FROM python:3.14.7-slim@sha256:83ff1d245a3d57d04152252d3ef9cb361494d0b3395abd65a5ebe91c401c8e83 AS builder-base+# CVE-2026-15310 is fixed on CPython's 3.14 maintenance branch but no patched+# 3.14 image has been released yet. Apply the reviewed pure-Python backport;+# the script fails closed if a future base image no longer matches its anchors.+COPY scripts/patch_cpython_zipfile_cve_2026_15310.py /tmp/patch_cpython_zipfile.py+RUN python3 /tmp/patch_cpython_zipfile.py && rm /tmp/patch_cpython_zipfile.py+# Set shell to bash with pipefail for safer pipe handlingSHELL ["/bin/bash", "-o", "pipefail", "-c"]@@ -273,6 +279,11 @@ ENV PATH="/install/.venv/bin:$PATH"###FROM python:3.14.7-slim@sha256:83ff1d245a3d57d04152252d3ef9cb361494d0b3395abd65a5ebe91c401c8e83 AS ldr+# Keep the production stage's independent stdlib in sync with the builder/test+# stages until the base image ships the upstream CVE-2026-15310 fix.+COPY scripts/patch_cpython_zipfile_cve_2026_15310.py /tmp/patch_cpython_zipfile.py+RUN python3 /tmp/patch_cpython_zipfile.py && rm /tmp/patch_cpython_zipfile.py+# Set shell to bash with pipefail for safer pipe handlingSHELL ["/bin/bash", "-o", "pipefail", "-c"]diff --git a/changelog.d/+cpython-zipfile-cve-2026-15310.security.md b/changelog.d/+cpython-zipfile-cve-2026-15310.security.mdnew file mode 100644index 0000000000..a1cd0ad909--- /dev/null+++ b/changelog.d/+cpython-zipfile-cve-2026-15310.security.md@@ -0,0 +1,7 @@+Bound the Python ZIP reader's per-call decompression output while awaiting the+next patched Python 3.14 base image, so a crafted bzip2/lzma/zstd member can no+longer expand into one unexpectedly large allocation behind a small buffered+read. Upstream deliberately leaves whole-member reads unbounded, so+`ZipFile.read()` and `read(-1)` still return the full decompressed member;+`extractall()` is now bounded by `copyfileobj()`'s chunking on top of the+per-read bound.diff --git a/scripts/patch_cpython_zipfile_cve_2026_15310.py b/scripts/patch_cpython_zipfile_cve_2026_15310.pynew file mode 100644index 0000000000..504ce0677c--- /dev/null+++ b/scripts/patch_cpython_zipfile_cve_2026_15310.py@@ -0,0 +1,286 @@+"""Backport the CPython 3.14 fix for CVE-2026-15310.++The production image is pinned to Python 3.14.7. The upstream fix is merged+on the 3.14 maintenance branch but is not part of a released 3.14 image yet.+This script applies the pure-Python ``zipfile`` portion of that backport and+fails closed if the pinned base image no longer matches the reviewed source.++Upstream backport: https://github.com/python/cpython/commit/31980e84b9a708424a0a1dfecde3fc991e313f89+"""++from __future__ import annotations++import argparse+import hashlib+import io+import subprocess+import sys+import sysconfig+from pathlib import Path+++_PATCHES = (+ (+ """ def decompress(self, data):+ if self._decomp is None:+""",+ """ @property+ def _needs_input(self):+ # While the LZMA properties header is still being buffered, more input+ # is required; afterwards defer to the wrapped decompressor so a bounded+ # decompress() call can be drained across reads.+ if self._decomp is None:+ return True+ return self._decomp.needs_input++ def decompress(self, data, max_length=-1):+ if self._decomp is None:+""",+ ),+ (+ """ result = self._decomp.decompress(data)+ self.eof = self._decomp.eof+""",+ """ result = self._decomp.decompress(data, max_length)+ self.eof = self._decomp.eof+""",+ ),+ (+ """def _get_decompressor(compress_type):+""",+ """def _decompressor_needs_input(decompressor):+ # bz2/zstd expose the stdlib decompressor's public needs_input; the LZMA+ # wrapper keeps it private (_needs_input) to avoid adding public API.+ needs_input = getattr(decompressor, "needs_input", None)+ return decompressor._needs_input if needs_input is None else needs_input+++def _get_decompressor(compress_type):+""",+ ),+ (+ """ else:+ data = self._read2(n)++ if self._compress_type == ZIP_STORED:+""",+ """ elif self._compress_type == ZIP_STORED:+ data = self._read2(n)+ else:+ # bzip2/lzma/zstd: a bounded decompress() call may leave input+ # buffered inside the decompressor; drain that before reading more.+ if _decompressor_needs_input(self._decompressor):+ data = self._read2(n)+ else:+ data = b''++ if self._compress_type == ZIP_STORED:+""",+ ),+ (+ """ else:+ data = self._decompressor.decompress(data)+ self._eof = self._decompressor.eof or self._compress_left <= 0+""",+ """ else:+ # Bound the output of a single decompress() call (mirroring the+ # DEFLATE path above) so that a small compressed member cannot+ # expand into one unbounded read.+ data = self._decompressor.decompress(data, max(n, self.MIN_READ_SIZE))+ self._eof = (self._decompressor.eof or+ self._compress_left <= 0 and+ _decompressor_needs_input(self._decompressor))+""",+ ),+)++# One marker per hunk in ``_PATCHES``, in the same order, each absent from the+# unpatched 3.14.7 source. ``main()`` requires all of them in the written file,+# so a hunk dropped from ``_PATCHES`` fails the build even when+# ``verify_runtime()`` cannot observe its absence: the ``_read1()`` branch-chain+# restructure has no public-API-visible effect on its own, because ``_read2()``+# clamps the compressed input it hands to the decompressor.+_PATCH_MARKERS = (+ "def _needs_input(self):",+ "result = self._decomp.decompress(data, max_length)",+ "def _decompressor_needs_input(decompressor):",+ "if _decompressor_needs_input(self._decompressor):",+ "self._decompressor.decompress(data, max(n, self.MIN_READ_SIZE))",+)+++def default_target() -> Path:+ """Return the active interpreter's ``zipfile`` source path."""+ return Path(sysconfig.get_path("stdlib")) / "zipfile" / "__init__.py"+++def apply_patch(target: Path) -> bool:+ """Apply the reviewed backport to *target* and return whether it changed."""+ source = target.read_text(encoding="utf-8")+ if all(marker in source for marker in _PATCH_MARKERS):+ return False++ patched = source+ for old, new in _PATCHES:+ occurrences = patched.count(old)+ if occurrences != 1:+ raise RuntimeError(+ f"refusing to patch {target}: expected one reviewed source anchor, "+ f"found {occurrences}"+ )+ patched = patched.replace(old, new, 1)++ compile(patched, str(target), "exec")+ target.write_text(patched, encoding="utf-8")+ return True+++def _incompressible(size: int) -> bytes:+ """Return *size* deterministic, effectively incompressible bytes.++ A SHA-256 chain rather than ``random`` so the build check is reproducible+ (and so it does not trip lint rules about non-cryptographic RNGs).+ """+ out = bytearray()+ digest = b"cve-2026-15310"+ while len(out) < size:+ digest = hashlib.sha256(digest).digest()+ out += digest+ return bytes(out[:size])+++def verify_runtime() -> None:+ """Check that one small read stays bounded and that content round-trips.++ Two payloads are used per codec. A highly compressible one proves the+ bound: on an unpatched interpreter a single ``_read1(100)`` call expands+ the whole member. An incompressible one proves the bounded path still+ returns every byte -- a correctly patched ``_read1()`` may legitimately+ return ``b''`` mid-stream while the decompressor drains buffered input,+ so the drain loop keys off ``_eof`` rather than on a falsy chunk.++ STORED and DEFLATE are included because the fourth hunk restructures the+ ``_read1()`` branch chain that those codecs also flow through.++ This always exercises the ambient interpreter's ``zipfile``; ``--target``+ selects what is patched, not what is verified.+ """+ import zipfile++ compressible = b"\0" * (4 * 1024 * 1024)+ incompressible = _incompressible(100 * 1024)++ compressions = [zipfile.ZIP_STORED, zipfile.ZIP_DEFLATED]+ # zipfile sets these attributes to None when the codec's support module is+ # missing. bz2 and lzma are the codecs this CVE is about, so a base image+ # without them cannot verify the fix at all: say so plainly instead of+ # letting writestr() raise something that reads like a broken patch.+ for module_name, compression in (+ ("bz2", zipfile.ZIP_BZIP2),+ ("lzma", zipfile.ZIP_LZMA),+ ):+ if getattr(zipfile, module_name, None) is None:+ raise RuntimeError(+ f"codec unavailable: this interpreter's zipfile has no "+ f"{module_name} support, so the bounded-decompression "+ "backport cannot be verified for a codec the CVE covers "+ "(base-image problem, not a failed patch)"+ )+ compressions.append(compression)+ # zstd is genuinely optional: unlike bz2/lzma it is absent from older+ # interpreters entirely, so its absence is skipped rather than fatal.+ if getattr(zipfile, "zstd", None) is not None:+ compressions.append(zipfile.ZIP_ZSTANDARD)++ for compression in compressions:+ for payload in (compressible, incompressible):+ archive = io.BytesIO()+ with zipfile.ZipFile(+ archive, "w", compression=compression+ ) as output:+ output.writestr("payload", payload)+ raw = archive.getvalue()++ # Bound: a single small read must not exceed MIN_READ_SIZE.+ with zipfile.ZipFile(io.BytesIO(raw)) as incoming:+ with incoming.open("payload") as member:+ first = member._read1(100)+ if len(first) > member.MIN_READ_SIZE:+ raise RuntimeError(+ "zipfile decompression output is not bounded by "+ f"MIN_READ_SIZE (compression={compression}, "+ f"one read returned {len(first)} bytes)"+ )++ # Correctness: the ordinary read path is lossless.+ with zipfile.ZipFile(io.BytesIO(raw)) as incoming:+ with incoming.open("payload") as member:+ if member.read() != payload:+ raise RuntimeError(+ "zipfile.read() changed archive contents "+ f"(compression={compression})"+ )++ # Correctness: draining in bounded steps is also lossless.+ with zipfile.ZipFile(io.BytesIO(raw)) as incoming:+ with incoming.open("payload") as member:+ chunks = []+ budget = 4 * (len(payload) // member.MIN_READ_SIZE + 16)+ while not member._eof:+ chunks.append(member._read1(100))+ budget -= 1+ if budget < 0:+ raise RuntimeError(+ "zipfile bounded reads do not terminate "+ f"(compression={compression})"+ )+ if b"".join(chunks) != payload:+ raise RuntimeError(+ "zipfile bounded reads changed archive contents "+ f"(compression={compression})"+ )+++def main() -> None:+ parser = argparse.ArgumentParser()+ parser.add_argument(+ "--target",+ type=Path,+ default=default_target(),+ help=(+ "zipfile source to rewrite (apply-only: --verify-runtime always "+ "imports the ambient interpreter's zipfile, so pointing --target "+ "at another interpreter's stdlib patches that copy but still "+ "verifies this one; import the patched copy via PYTHONPATH in a "+ "subprocess to check it)"+ ),+ )+ parser.add_argument("--verify-runtime", action="store_true")+ args = parser.parse_args()++ if args.verify_runtime:+ verify_runtime()+ return++ apply_patch(args.target)++ # Fail the build if any hunk is missing from the written file. Runtime+ # verification alone cannot catch every partial application: see the+ # comment on _PATCH_MARKERS.+ written = args.target.read_text(encoding="utf-8")+ missing = [marker for marker in _PATCH_MARKERS if marker not in written]+ if missing:+ raise RuntimeError(+ f"incomplete backport in {args.target}: the patched file is "+ f"missing {len(missing)} of {len(_PATCH_MARKERS)} reviewed hunks "+ f"{missing}"+ )++ subprocess.run(+ [sys.executable, str(Path(__file__).resolve()), "--verify-runtime"],+ check=True,+ )+++if __name__ == "__main__":+ main()diff --git a/tests/deployment/test_cpython_zipfile_backport.py b/tests/deployment/test_cpython_zipfile_backport.pynew file mode 100644index 0000000000..53eab32dde--- /dev/null+++ b/tests/deployment/test_cpython_zipfile_backport.py@@ -0,0 +1,146 @@+"""Contract tests for the temporary CPython zipfile security backport.++The regression must hold on hosts where the interpreter's own ``zipfile`` has+already been patched (the ``ldr-test`` Docker stage inherits ``builder-base``,+which runs the patch script) as well as on unpatched hosts. So the test never+trusts the ambient stdlib: it copies the module, reverse-applies the reviewed+hunks to synthesise a guaranteed-unpatched baseline, and drives every+assertion against that copy through ``PYTHONPATH``.+"""++# allow: no-sut-import — the system under test is the build-time patch script+# scripts/patch_cpython_zipfile_cve_2026_15310.py, which rewrites the+# interpreter's stdlib during the Docker build; it is deliberately outside the+# local_deep_research package so the image can be patched before install.++from __future__ import annotations++import importlib.util+import os+import shutil+import subprocess+import sys+import zipfile+from pathlib import Path++REPO_ROOT = Path(__file__).resolve().parents[2]+SCRIPT = REPO_ROOT / "scripts" / "patch_cpython_zipfile_cve_2026_15310.py"++_SPEC = importlib.util.spec_from_file_location(+ "patch_cpython_zipfile_cve_2026_15310", SCRIPT+)+assert _SPEC is not None and _SPEC.loader is not None+patcher = importlib.util.module_from_spec(_SPEC)+_SPEC.loader.exec_module(patcher)++apply_patch = patcher.apply_patch++# The hunk that actually bounds the decompressor's per-call output. Removing+# it must make verify_runtime() fail, otherwise the check cannot catch a+# revert of the security fix.+BOUND_HUNK_MARKER = (+ "self._decompressor.decompress(data, max(n, self.MIN_READ_SIZE))"+)+++def _copy_stdlib_zipfile(destination: Path) -> Path:+ """Copy the live ``zipfile`` package into *destination* and return it."""+ source_package = Path(zipfile.__file__).resolve().parent+ copied_package = destination / "zipfile"+ shutil.copytree(source_package, copied_package)+ return copied_package / "__init__.py"+++def _unapply_patch(target: Path) -> bool:+ """Reverse the reviewed hunks so *target* is a known-unpatched baseline.++ Returns whether anything changed (False when the source package the host+ provided was not patched to begin with).+ """+ source = target.read_text(encoding="utf-8")+ if not all(marker in source for marker in patcher._PATCH_MARKERS):+ return False++ reverted = source+ for old, new in patcher._PATCHES:+ assert reverted.count(new) == 1, f"expected one anchor for {new!r}"+ reverted = reverted.replace(new, old, 1)+ compile(reverted, str(target), "exec")+ target.write_text(reverted, encoding="utf-8")+ return True+++def _apply_hunks(target: Path, hunks) -> None:+ """Apply an explicit subset of ``_PATCHES`` to *target*."""+ patched = target.read_text(encoding="utf-8")+ for old, new in hunks:+ assert patched.count(old) == 1, f"expected one anchor for {old!r}"+ patched = patched.replace(old, new, 1)+ compile(patched, str(target), "exec")+ target.write_text(patched, encoding="utf-8")+++def _run_runtime_check(package_root: Path) -> subprocess.CompletedProcess[str]:+ """Run ``verify_runtime()`` against the ``zipfile`` under *package_root*."""+ env = os.environ.copy()+ env["PYTHONPATH"] = os.pathsep.join(+ (str(package_root), env.get("PYTHONPATH", ""))+ )+ return subprocess.run(+ [+ sys.executable,+ "-c",+ (+ "import importlib.util, sys;"+ "spec = importlib.util.spec_from_file_location("+ "'patcher', sys.argv[1]);"+ "mod = importlib.util.module_from_spec(spec);"+ "spec.loader.exec_module(mod);"+ "mod.verify_runtime()"+ ),+ str(SCRIPT),+ ],+ env=env,+ capture_output=True,+ text=True,+ check=False,+ )+++def test_backport_bounds_zipfile_decompression(tmp_path: Path) -> None:+ baseline = tmp_path / "baseline"+ baseline.mkdir()+ module = _copy_stdlib_zipfile(baseline)+ _unapply_patch(module)++ # Negative control: the unpatched module has the unbounded read, so the+ # runtime check must reject it. This is synthesised rather than taken+ # from the ambient interpreter, which may already be patched.+ unpatched = _run_runtime_check(baseline)+ assert unpatched.returncode != 0, unpatched.stdout + unpatched.stderr+ assert "MIN_READ_SIZE" in unpatched.stderr++ assert apply_patch(module) is True+ assert apply_patch(module) is False+ patched = _run_runtime_check(baseline)+ assert patched.returncode == 0, patched.stdout + patched.stderr+++def test_runtime_check_catches_a_revert_of_the_bound(tmp_path: Path) -> None:+ """Dropping the bounding hunk must reopen the finding, not pass quietly."""+ without_bound = tmp_path / "without-bound"+ without_bound.mkdir()+ module = _copy_stdlib_zipfile(without_bound)+ _unapply_patch(module)++ hunks = [+ hunk for hunk in patcher._PATCHES if BOUND_HUNK_MARKER not in hunk[1]+ ]+ assert len(hunks) == len(patcher._PATCHES) - 1, (+ "the bounding hunk is no longer identifiable in _PATCHES"+ )+ _apply_hunks(module, hunks)++ reverted = _run_runtime_check(without_bound)+ assert reverted.returncode != 0, reverted.stdout + reverted.stderr+ assert "MIN_READ_SIZE" in reverted.stderrdiff --git a/tests/deployment/test_deployment_surface_contracts.py b/tests/deployment/test_deployment_surface_contracts.pyindex c3d3967dcf..b3d498c177 100644--- a/tests/deployment/test_deployment_surface_contracts.py+++ b/tests/deployment/test_deployment_surface_contracts.py@@ -43,6 +43,8 @@ COMPOSE_BASE = REPO_ROOT / "docker-compose.yml"COMPOSE_UNRAID = REPO_ROOT / "docker-compose.unraid.yml"COMPOSE_GPU = REPO_ROOT / "docker-compose.gpu.override.yml"ENTRYPOINT = REPO_ROOT / "scripts" / "ldr_entrypoint.sh"+ZIPFILE_PATCH_SCRIPT_REL = "scripts/patch_cpython_zipfile_cve_2026_15310.py"+ZIPFILE_PATCH_SCRIPT = REPO_ROOT / ZIPFILE_PATCH_SCRIPT_RELCOOKIECUTTER_DIR = REPO_ROOT / "cookiecutter-docker"UNRAID_TEMPLATE = REPO_ROOT / "unraid-templates" / "local-deep-research.xml"REVERSE_PROXY_DOC = REPO_ROOT / "docs" / "deployment" / "reverse-proxy.md"@@ -181,6 +183,70 @@ def dockerfile_stages(return stages+def dockerfile_stage_parents(+ instructions: list[tuple[str, str]],+) -> dict[str, str]:+ """Return ``{stage name: the image or stage its FROM names}``.++ ``dockerfile_stages()`` drops the ``FROM`` line itself, so this is its+ companion for questions about what a stage is built *from*. Leading+ ``--flags`` (e.g. ``--platform=$BUILDPLATFORM``) are skipped the same+ way the COPY token filter does below, so a flagged FROM still resolves+ to the image/stage token rather than the flag itself.+ """+ parents: dict[str, str] = {}+ for keyword, argument in instructions:+ if keyword != "FROM":+ continue+ named = re.search(r"\bAS\s+(\S+)\s*$", argument, re.IGNORECASE)+ tokens = [t for t in argument.split() if not t.startswith("--")]+ parent = tokens[0] if tokens else argument.split()[0]+ parents[named.group(1) if named else parent] = parent+ return parents+++def stages_from_base_image(+ instructions: list[tuple[str, str]],+) -> tuple[str, list[str]]:+ """Return ``(base image ref, stages built directly from it)``.++ The base image is derived rather than hardcoded: it is the single ``FROM``+ target that does not name another stage in this Dockerfile.+ """+ parents = dockerfile_stage_parents(instructions)+ external = sorted({p for p in parents.values() if p not in parents})+ assert len(external) == 1, (+ f"expected exactly one external base image, found {external}"+ )+ base = external[0]+ return base, [name for name, parent in parents.items() if parent == base]+++def copy_argument_tokens(argument: str) -> list[str] | None:+ """Return a ``COPY`` argument's source/dest tokens, flags stripped.++ Handles ordinary shell-form (``COPY [--flag ...] src... dst``) plus the+ JSON exec-form (``COPY [--flag ...] ["src", ..., "dst"]``). Returns+ ``None`` for JSON-form text that fails to parse as a JSON list, so+ callers can fail loudly instead of silently matching nothing.+ """+ remainder = argument+ while remainder.startswith("--"):+ _, _, rest = remainder.partition(" ")+ remainder = rest.lstrip()+ if remainder.startswith("["):+ try:+ parsed = json.loads(remainder)+ except (json.JSONDecodeError, ValueError):+ return None+ if not isinstance(parsed, list) or not all(+ isinstance(t, str) for t in parsed+ ):+ return None+ return parsed+ return [t for t in argument.split() if not t.startswith("--")]++def parse_healthcheck(argument: str) -> dict[str, object] | None:"""Split a HEALTHCHECK argument into its flags and its exec-form CMD."""if argument.strip().upper() == "NONE":@@ -1401,3 +1467,90 @@ class TestUnraidTemplate:extra = unraid_xml.findtext("ExtraParams") or ""assert "no-new-privileges" in extraassert "cap-drop" in extra+++# ---------------------------------------------------------------------------+# 9. The temporary CPython zipfile backport (CVE-2026-15310)+# ---------------------------------------------------------------------------+++class TestCPythonZipfileBackportWiring:+ """The backport only exists in an image if the Dockerfile applies it.++ ``scripts/patch_cpython_zipfile_cve_2026_15310.py`` rewrites the+ interpreter's stdlib at build time, and its own tests resolve it by path,+ so deleting the ``COPY``/``RUN`` pair from a stage leaves every other+ check green while shipping an unpatched ``zipfile``. Grype will not+ notice either: ``.grype.yaml`` suppresses ``CVE-2026-15310`` for the+ ``python`` binary package unconditionally, because the binary CPE stays+ 3.14.7 whether or not the pure-Python fix was applied. This class is the+ only thing that fails when those four lines go away.++ The wiring check below only confirms the ``COPY``/``RUN`` pair is+ present; it does not run the patch. Runtime verification happens+ because the script's own ``main()`` re-execs itself with+ ``--verify-runtime`` after applying the patch -- that flag never+ appears on the Dockerfile's ``RUN`` line, so a refactor of ``main()``+ that drops the self re-exec would not be caught here.+ """++ def test_patch_script_is_present(self):+ assert ZIPFILE_PATCH_SCRIPT.is_file(), (+ f"{ZIPFILE_PATCH_SCRIPT_REL} is gone but the Dockerfile and the "+ "CVE-2026-15310 .grype.yaml suppression still reference it"+ )++ def test_every_stage_built_from_the_base_image_applies_the_backport(+ self, dockerfile_instructions+ ):+ """Deleting the COPY/RUN pair from any base-rooted stage must fail.++ Derived from the parsed stages rather than from the names+ ``builder-base`` and ``ldr``, so a future stage rooted at the base+ image is held to the same requirement.+ """+ base, rooted = stages_from_base_image(dockerfile_instructions)+ assert base.startswith("python:"), (+ f"base image is no longer a python image ({base}); the "+ "CVE-2026-15310 backport and its .grype.yaml suppression need "+ "re-checking"+ )+ # Floor: the derived list must not be silently empty.+ assert {"builder-base", "ldr"} <= set(rooted), (+ "expected builder-base and ldr to be built directly from "+ f"{base}, got {sorted(rooted)}"+ )++ stages = dockerfile_stages(dockerfile_instructions)+ for stage in rooted:+ body = stages[stage]+ copies = []+ for index, (keyword, argument) in enumerate(body):+ if keyword != "COPY":+ continue+ tokens = copy_argument_tokens(argument)+ if tokens is None:+ continue+ if len(tokens) >= 2 and ZIPFILE_PATCH_SCRIPT_REL in tokens[:-1]:+ copies.append((index, tokens[-1]))+ assert len(copies) == 1, (+ f"stage '{stage}' is built from {base} but does not COPY "+ f"{ZIPFILE_PATCH_SCRIPT_REL} exactly once (found "+ f"{len(copies)}); it would ship an unpatched zipfile while "+ ".grype.yaml still suppresses CVE-2026-15310"+ )+ index, destination = copies[0]+ executed = [+ argument+ for keyword, argument in body[index + 1 :]+ if keyword == "RUN"+ and re.search(+ r"\bpython[0-9.]*\s+" + re.escape(destination),+ argument,+ )+ ]+ assert executed, (+ f"stage '{stage}' copies {ZIPFILE_PATCH_SCRIPT_REL} to "+ f"{destination} but never RUNs it, so the stdlib is left "+ "unpatched"+ )