From 2833a86482208e8a6cf37814bb1518218b31bf71 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Tue, 6 Oct 2026 02:06:04 +0200 Subject: [PATCH] fix: extract CUDA build source on runner Python --- scripts/build-cuda-engine-in-docker.py | 53 +++++++++++++++++++++++--- scripts/test-cuda-docker-builder.py | 22 +++++++++++ 2 files changed, 70 insertions(+), 5 deletions(-) diff --git a/scripts/build-cuda-engine-in-docker.py b/scripts/build-cuda-engine-in-docker.py index 77828a47..95fa96b7 100644 --- a/scripts/build-cuda-engine-in-docker.py +++ b/scripts/build-cuda-engine-in-docker.py @@ -6,6 +6,7 @@ from io import BytesIO import json import os from pathlib import Path +from pathlib import PurePosixPath import re import shutil import subprocess @@ -66,6 +67,49 @@ def digest(path): return h.hexdigest() +def extract_git_archive(archive, destination): + """Extract only regular files/directories from git archive on old and new Python.""" + root = destination.resolve() + with tarfile.open(fileobj=BytesIO(archive), mode='r:') as source: + members = source.getmembers() + seen = set() + checked = [] + for member in members: + name = member.name + normalized_name = name.rstrip('/') if member.isdir() else name + path = PurePosixPath(normalized_name) + if (not normalized_name or path.is_absolute() or + any(part in ('', '.', '..') for part in normalized_name.split('/'))): + raise ValueError(f'unsafe path in committed source archive: {name!r}') + if not (member.isdir() or member.isfile()): + raise ValueError(f'unsupported entry in committed source archive: {name!r}') + target = root.joinpath(*path.parts) + if target == root or root not in target.parents: + raise ValueError(f'archive path escapes staging directory: {name!r}') + if path in seen: + raise ValueError(f'duplicate path in committed source archive: {name!r}') + seen.add(path) + checked.append((member, path, target)) + + directories = {root} + for member, path, target in checked: + if member.isdir(): + directories.add(target) + continue + directories.update(parent for parent in target.parents if parent == root or root in parent.parents) + target.parent.mkdir(mode=0o755, parents=True, exist_ok=True) + payload = source.extractfile(member) + if payload is None: + raise ValueError(f'missing file payload in committed source archive: {member.name!r}') + flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, 'O_NOFOLLOW', 0) + fd = os.open(target, flags, member.mode & 0o777 & ~0o6000) + with os.fdopen(fd, 'wb') as output, payload: + shutil.copyfileobj(payload, output) + for directory in sorted(directories, key=lambda item: len(item.parts), reverse=True): + if directory.is_dir(): + directory.chmod(0o755) + + def stage_tracked_source(destination): changed = subprocess.run(['git', '-C', str(REPO), 'diff', '--quiet', 'HEAD', '--'], check=False) if changed.returncode == 1: @@ -75,11 +119,10 @@ def stage_tracked_source(destination): if changed.returncode != 0: raise subprocess.CalledProcessError(changed.returncode, changed.args) archive = subprocess.check_output(['git', '-C', str(REPO), 'archive', '--format=tar', 'HEAD']) - with tarfile.open(fileobj=BytesIO(archive), mode='r:') as source: - try: - source.extractall(destination, filter='data') - except (OSError, tarfile.TarError, ValueError) as error: - raise ValueError(f'could not safely stage the committed source tree: {error}') from error + try: + extract_git_archive(archive, destination) + except (OSError, tarfile.TarError, ValueError) as error: + raise ValueError(f'could not safely stage the committed source tree: {error}') from error return subprocess.check_output(['git', '-C', str(REPO), 'rev-parse', 'HEAD'], text=True).strip(), hashlib.sha256(archive).hexdigest() diff --git a/scripts/test-cuda-docker-builder.py b/scripts/test-cuda-docker-builder.py index 8a32f983..b79e3572 100644 --- a/scripts/test-cuda-docker-builder.py +++ b/scripts/test-cuda-docker-builder.py @@ -1,11 +1,13 @@ #!/usr/bin/env python3 """CPU-only contract tests for the Docker CUDA builder wrapper.""" import importlib.util +from io import BytesIO import json from pathlib import Path import shutil import subprocess import tempfile +import tarfile import unittest MODULE = Path(__file__).with_name('build-cuda-engine-in-docker.py') @@ -174,6 +176,26 @@ else: builder.build(self.arguments()) self.assertFalse(self.log.exists(), self.log.read_text() if self.log.exists() else '') + def test_archive_extraction_rejects_parent_paths_and_symlinks(self): + for name, kind in (('../escape', tarfile.REGTYPE), ('link', tarfile.SYMTYPE)): + with self.subTest(name=name): + archive = BytesIO() + with tarfile.open(fileobj=archive, mode='w:') as output: + entry = tarfile.TarInfo(name) + entry.type = kind + entry.linkname = '../outside' + if kind == tarfile.REGTYPE: + entry.size = 1 + output.addfile(entry, BytesIO(b'x')) + else: + output.addfile(entry) + destination = self.root / f"safe-stage-{name.replace('/', '_')}" + destination.mkdir() + with self.assertRaisesRegex(ValueError, 'unsafe path|unsupported entry'): + builder.extract_git_archive(archive.getvalue(), destination) + self.assertEqual(list(destination.iterdir()), []) + self.assertFalse((self.root / 'escape').exists()) + def test_manual_cuda_job_uses_generic_linux_and_no_artifact_action(self): workflow = (self.original_repo / '.github/workflows/linux.yml').read_text(encoding='utf-8') job = workflow.split(' hosted-cuda-package:', 1)[1].split('\n linux-static-cli:', 1)[0]