diff --git a/.github/scripts/fedora-proot/fedora_proot.py b/.github/scripts/fedora-proot/fedora_proot.py new file mode 100755 index 0000000000..27d0c9ba61 --- /dev/null +++ b/.github/scripts/fedora-proot/fedora_proot.py @@ -0,0 +1,468 @@ +#!/usr/bin/env python3 +"""Run MLX's Fedora 42 C++ build test in Fedora userspace on a Darkbloom ARM64 runner. + +The sandbox has no Docker, so the unchanged Fedora build script +(.github/scripts/setup+build-cpp-linux-fedora-container.sh) runs under PRoot, built here +from pinned source, in the official archived Fedora 42 container rootfs. PRoot +translates paths and fakes UID 0 through ptrace; it is not an isolation boundary (the +job VM is). +""" + +import argparse +import hashlib +import http.client +import json +import os +import platform +import shutil +import subprocess +import tarfile +import time +import urllib.request +from pathlib import Path, PurePosixPath + +PTRACE_PROBE = r""" +#include +#include +#include +#include +#include +#include +#include +int main(void) { + if (getuid() != 1000 || geteuid() != 1000 || prctl(PR_GET_NO_NEW_PRIVS,0,0,0,0) != 1) + return 10; + printf("PTRACE_PROBE uid=%lu dumpable=%d no_new_privs=1\n", + (unsigned long)getuid(), prctl(PR_GET_DUMPABLE)); + fflush(stdout); + pid_t child = fork(); + if (child < 0) { perror("fork"); return 11; } + if (!child) { + if (ptrace(PTRACE_TRACEME,0,0,0)) { perror("PTRACE_TRACEME"); _exit(12); } + raise(SIGSTOP); _exit(0); + } + int status; + if (waitpid(child,&status,0) != child || !WIFSTOPPED(status)) return 13; + if (ptrace(PTRACE_CONT,child,0,0)) { perror("PTRACE_CONT"); return 14; } + if (waitpid(child,&status,0) != child || !WIFEXITED(status) || WEXITSTATUS(status)) + return 15; + puts("PTRACE_PROBE_OK"); return 0; +} +""" + + +def load_pins(): + return json.loads(Path(__file__).with_name("pins.json").read_text()) + + +def verified(path, spec): + if path.stat().st_size != spec["size"]: + raise ValueError(f"wrong size: {path.name}") + with path.open("rb") as src: + digest = hashlib.file_digest(src, "sha256").hexdigest() + if digest != spec["sha256"]: + raise ValueError(f"wrong SHA-256: {path.name}") + + +OCI_GZIP_LAYER = "application/vnd.oci.image.layer.v1.tar+gzip" + + +def oci_layer(archive, spec, target): + """Write the one pinned gzip layer of the pinned archived OCI image to target. + + Only index.json, the pinned manifest and the pinned layer are read; the index + must name exactly that manifest, whose bytes must hash to its digest, and the + manifest must list exactly that one layer (media type, digest and size). + """ + if target.exists(): + verified(target, spec) + return + manifest_sha = spec["manifest"].removeprefix("sha256:") + part = target.with_name(target.name + ".part") + with tarfile.open(archive, "r:xz") as src: + + def regular(name, limit): + member = src.getmember(name) + if not member.isfile() or member.size > limit: + raise ValueError(f"unexpected OCI member: {name}") + return member + + index = json.loads(src.extractfile(regular("index.json", 1 << 16)).read()) + manifests = index.get("manifests") + if ( + not isinstance(manifests, list) + or len(manifests) != 1 + or manifests[0].get("digest") != spec["manifest"] + ): + raise ValueError("OCI index must name exactly the pinned manifest") + raw = src.extractfile(regular("blobs/sha256/" + manifest_sha, 1 << 16)).read() + if hashlib.sha256(raw).hexdigest() != manifest_sha: + raise ValueError("OCI manifest does not match its digest") + layers = json.loads(raw).get("layers") + if ( + not isinstance(layers, list) + or len(layers) != 1 + or layers[0].get("mediaType") != OCI_GZIP_LAYER + or layers[0].get("digest") != "sha256:" + spec["sha256"] + or layers[0].get("size") != spec["size"] + ): + raise ValueError("OCI manifest must list exactly the pinned gzip layer") + with ( + src.extractfile( + regular("blobs/sha256/" + spec["sha256"], spec["size"]) + ) as data, + part.open("xb") as out, + ): + shutil.copyfileobj(data, out) + verified(part, spec) + part.rename(target) + + +def patch_proot_faccessat2(src): + """Add faccessat2 (439) to PRoot 5.4.1's ARM64 syscall table before it is built. + + The table stops at clone3, so PRoot passes faccessat2 to the kernel untranslated: + a guest `test -x` (bash uses faccessat2) would read the host's path, not the + guest's. enter.c and the seccomp filter already handle PR_faccessat2. + """ + table = src / "syscall" / "sysnums-arm64.h" + text = table.read_text() + anchor = " [435] = PR_clone3,\n" + if text.count(anchor) != 1 or "PR_faccessat2" in text: + raise RuntimeError("unexpected PRoot ARM64 syscall table") + text = text.replace(anchor, anchor + " [439] = PR_faccessat2,\n") + table.write_text(text) + return hashlib.sha256(text.encode()).hexdigest() + + +def verify_inputs(inputs, pins): + """Every pinned download, and the rootfs layer derived from the OCI archive.""" + for name, spec in pins["files"].items(): + verified(inputs / name, spec) + verified(inputs / "fedora.tar.gz", pins["fedora_layer"]) + + +def download(url, part, size, attempts=3, pause=5): + """One pinned download with bounded retries; any stale partial file goes first.""" + for attempt in range(1, attempts + 1): + part.unlink(missing_ok=True) + try: + with urllib.request.urlopen(url, timeout=60) as src, part.open("xb") as out: + copied = 0 + while chunk := src.read(1024 * 1024): + copied += len(chunk) + if copied > size: + raise ValueError(f"oversized download: {part.name}") + out.write(chunk) + if copied != size: + raise ValueError( + f"truncated download: {part.name} ({copied} of {size} bytes)" + ) + return + except (OSError, ValueError, http.client.HTTPException) as error: + part.unlink(missing_ok=True) + if attempt == attempts: + raise + print( + f"FEDORA_PROOT_RETRY {part.name} attempt {attempt}: " + f"{type(error).__name__}: {error}", + flush=True, + ) + time.sleep(pause * attempt) + + +def fetch_inputs(dest, pins): + dest.mkdir(parents=True, exist_ok=True) + for name, spec in pins["files"].items(): + target = dest / name + if not target.exists(): + part = dest / (name + ".part") + download(spec["url"], part, spec["size"]) + verified(part, spec) + part.rename(target) + verified(target, spec) + layer = pins["fedora_layer"] + oci_layer(dest / layer["archive"], layer, dest / "fedora.tar.gz") + + +def extract_root(archive, dest): + """One pinned layer, no overlay merging; links are created after regular files. + + This order prevents tar members writing through links, including absolute + rootfs links. Device nodes are unnecessary: /dev is an explicit PRoot bind. + All real ownership remains the calling runner; setuid/setgid bits are dropped. + """ + dest.mkdir() + dest = dest.resolve() + seen = set() + links = [] + with tarfile.open(archive, "r:*") as src: + for member in src: + p = PurePosixPath(member.name) + if p.is_absolute() or ".." in p.parts or not p.parts: + raise ValueError(f"unsafe tar path: {member.name}") + if any(part.startswith(".wh.") for part in p.parts): + raise ValueError("overlay whiteouts require a different unpacker") + key = str(p) + if key == ".": + continue + if key in seen: + raise ValueError(f"duplicate tar path: {key}") + seen.add(key) + target = dest.joinpath(*p.parts) + if member.isdir(): + target.mkdir(parents=True, exist_ok=True) + elif member.isfile(): + target.parent.mkdir(parents=True, exist_ok=True) + with src.extractfile(member) as source, target.open("xb") as out: + shutil.copyfileobj(source, out) + target.chmod(member.mode & 0o777) + elif member.issym() or member.islnk(): + links.append((member, target)) + elif not (member.ischr() or member.isblk() or member.isfifo()): + raise ValueError(f"unsupported tar entry: {key}") + # Hardlinks must name an already extracted regular file, never a symlink. + for member, target in links: + if not member.islnk(): + continue + link = PurePosixPath(member.linkname) + source = dest.joinpath(*link.parts) + if link.is_absolute() or ".." in link.parts or not source.is_file(): + raise ValueError(f"unsafe hardlink: {member.name}") + target.parent.mkdir(parents=True, exist_ok=True) + os.link(source, target) + for member, target in links: + if member.issym(): + if not target.parent.resolve().is_relative_to(dest): + raise ValueError(f"symlink parent escapes root: {member.name}") + target.parent.mkdir(parents=True, exist_ok=True) + target.symlink_to(member.linkname) + + +def archived_repos(root): + root = root.resolve(strict=True) + repo_dir = root / "etc/yum.repos.d" + target = repo_dir / "pilot-fedora42.repo" + if root.stat().st_uid != os.geteuid(): + raise ValueError("rootfs is not owned by this job user") + for path in (repo_dir, target): + if not path.resolve().is_relative_to(root): + raise ValueError("repository configuration escapes the owned rootfs") + repo_dir.mkdir(parents=True, exist_ok=True) + for repo in repo_dir.glob("*.repo"): + repo.rename(repo.with_suffix(".repo.disabled-pilot")) + key = "file:///etc/pki/rpm-gpg/RPM-GPG-KEY-fedora-42-primary" + text = "" + for name, suffix in ( + ("fedora", "releases/42/Everything/aarch64/os"), + ("updates", "updates/42/Everything/aarch64"), + ): + text += ( + f"[{name}]\nname=Fedora 42 archived {name}\n" + f"baseurl=https://archives.fedoraproject.org/pub/archive/fedora/linux/{suffix}/\n" + f"enabled=1\ngpgcheck=1\ngpgkey={key}\n\n" + ) + target.write_text(text) + + +SCRIPT = ".github/scripts/setup+build-cpp-linux-fedora-container.sh" + + +def run_pilot(work, source, pins): + if platform.system() != "Linux" or platform.machine() != "aarch64": + raise RuntimeError("run only on a Linux ARM64 runner") + if os.getuid() != 1000 or os.geteuid() != 1000: + raise RuntimeError("run as the unchanged UID1000 job user") + status = Path("/proc/self/status").read_text() + if "NoNewPrivs:\t1" not in status: + raise RuntimeError("the job must inherit no_new_privs") + work.mkdir(parents=True, exist_ok=False) + start = time.monotonic() + evidence = { + "pins": pins, + "host_arch": platform.machine(), + "uid": os.getuid(), + "kernel": platform.release(), + "steps": [], + "result": "running", + } + + def call(name, args, *, cwd=work, env=None, timeout=180): + before = time.monotonic() + print(f"FEDORA_PROOT_STEP {name}", flush=True) + with (work / (name + ".log")).open("w") as log: + proc = subprocess.Popen( + args, + cwd=cwd, + env=env, + stdout=log, + stderr=subprocess.STDOUT, + start_new_session=True, + ) + try: + proc.wait(timeout=timeout) + except subprocess.TimeoutExpired: + import signal + + os.killpg(proc.pid, signal.SIGKILL) + proc.wait() + print( + (work / (name + ".log")).read_text(errors="replace"), + end="", + flush=True, + ) + raise + duration = time.monotonic() - before + evidence["steps"].append( + {"name": name, "seconds": duration, "exit": proc.returncode} + ) + print((work / (name + ".log")).read_text(errors="replace"), end="", flush=True) + if proc.returncode: + raise subprocess.CalledProcessError(proc.returncode, args) + + try: + script = (source / SCRIPT).resolve(strict=True) + if not script.is_file() or not script.is_relative_to(source): + raise RuntimeError("the checked-out Fedora build script is missing") + inputs = work / "inputs" + fetch_inputs(inputs, pins) + verify_inputs(inputs, pins) + (work / "ptrace.c").write_text(PTRACE_PROBE) + call( + "ptrace-build", + ["cc", "-O2", "-Wall", "-Wextra", "-Werror", "ptrace.c", "-o", "ptrace"], + ) + call("ptrace", [str(work / "ptrace")], timeout=15) + deps = work / "deps" + for deb in ( + "libtalloc-dev.deb", + "libtalloc2.deb", + "pkgconf-bin.deb", + "libpkgconf3.deb", + ): + call(deb, ["dpkg-deb", "--extract", str(inputs / deb), str(deps)]) + (deps / "usr/bin/pkg-config").symlink_to("pkgconf") + extract_root(inputs / "proot.tar.gz", work / "proot-source") + proot_src = work / "proot-source" / ("proot-" + pins["proot_commit"]) / "src" + evidence["proot_arm64_table_sha256"] = patch_proot_faccessat2(proot_src) + lib = deps / "usr/lib/aarch64-linux-gnu" + env = dict( + os.environ, + PKG_CONFIG_LIBDIR=str(lib / "pkgconfig"), + PKG_CONFIG_SYSROOT_DIR=str(deps), + LDFLAGS=f"-Wl,-rpath,{lib}", + PATH=f"{deps / 'usr/bin'}:{os.environ['PATH']}", + LD_LIBRARY_PATH=str(lib), + ) + call( + "proot-build", + ["make", "-j2", "HAS_SWIG=", "HAS_PYTHON_CONFIG=", "proot"], + cwd=proot_src, + env=env, + ) + proot = proot_src / "proot" + call("proot-version", [str(proot), "--version"]) + with proot.open("rb") as src: + evidence["proot_sha256"] = hashlib.file_digest(src, "sha256").hexdigest() + extract_root(inputs / "fedora.tar.gz", work / "fedora") + root = work / "fedora" + if "VERSION_ID=42" not in (root / "etc/os-release").read_text(): + raise RuntimeError("rootfs is not Fedora42") + archived_repos(root) + scratch = work / "tmp" + scratch.mkdir() + command = [ + str(proot), + "-0", + "-r", + str(root), + "-b", + "/dev", + "-b", + "/proc", + "-b", + f"{scratch}:/tmp", + "-b", + f"{source}:/work", + "-w", + "/work", + ] + # The checkout belongs to the runner's UID 1000; git in the fake-root guest + # must accept it. + guest = dict( + os.environ, + GIT_CONFIG_COUNT="1", + GIT_CONFIG_KEY_0="safe.directory", + GIT_CONFIG_VALUE_0="/work", + ) + # No sudo, no Docker, no namespaces/capabilities, no host /etc or /run bind. + call( + "fedora-smoke", + command + + [ + "/bin/bash", + "-ec", + "cat /etc/fedora-release; test $(uname -m) = aarch64; " + # faccessat2 translation: Fedora has dnf and no apt-get; the Ubuntu host + # has apt-get. + "test -x /usr/bin/dnf; test ! -x /usr/bin/apt-get; " + "test $(id -u) = 0; ldd --version; dnf --version; " + "grep '^NoNewPrivs:' /proc/self/status; (true)& wait", + ], + env=guest, + timeout=60, + ) + # Exercise actual DNS/proxy/TLS and both literal archive repositories + # before the expensive build, using Fedora's own libcurl/trust store. + call( + "fedora-archive-network", + command + ["/usr/bin/dnf", "-q", "makecache", "--refresh"], + env=guest, + timeout=300, + ) + call( + "fedora-build-test", + command + ["/bin/bash", "/work/" + SCRIPT], + env=guest, + timeout=1800, + ) + evidence["result"] = "pass" + except BaseException as error: + evidence["result"] = "failure" + evidence["error_type"] = type(error).__name__ + raise + finally: + evidence["seconds"] = time.monotonic() - start + (work / "evidence.json").write_text(json.dumps(evidence, indent=2) + "\n") + print( + json.dumps({k: v for k, v in evidence.items() if k != "pins"}, indent=2), + flush=True, + ) + print("FEDORA_PROOT_EVIDENCE " + str(work / "evidence.json"), flush=True) + print("FEDORA_PROOT_OK " + evidence["result"], flush=True) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("action", choices=("fetch", "run")) + parser.add_argument( + "--inputs", type=Path, help="fetch: download and verify the pinned inputs here" + ) + parser.add_argument( + "--source", type=Path, help="run: the MLX checkout to build and test" + ) + parser.add_argument("--work", type=Path, help="run: a new private work directory") + args = parser.parse_args() + pins = load_pins() + if args.action == "fetch": + if args.inputs is None: + parser.error("fetch requires --inputs") + fetch_inputs(args.inputs.resolve(), pins) + else: + if args.source is None or args.work is None: + parser.error("run requires --source and --work") + run_pilot(args.work.resolve(), args.source.resolve(strict=True), pins) + + +if __name__ == "__main__": + main() diff --git a/.github/scripts/fedora-proot/pins.json b/.github/scripts/fedora-proot/pins.json new file mode 100644 index 0000000000..34fb962429 --- /dev/null +++ b/.github/scripts/fedora-proot/pins.json @@ -0,0 +1,43 @@ +{ + "schema": 1, + "proot_commit": "d4b49e2243dee34e41c13dfeca6a3d07e9cf0f00", + "fedora_manifest": "sha256:cf9e82fbfad546ad06c626dabe8ba1aac6100ecfde4339e521352e9b77eaa794", + "files": { + "fedora.oci.tar.xz": { + "url": "https://archives.fedoraproject.org/pub/archive/fedora/linux/releases/42/Container/aarch64/images/Fedora-Container-Base-Generic-42-1.1.aarch64.oci.tar.xz", + "size": 57715532, + "sha256": "137a907cd0931d9c4c7cfd5467031e03da3715141f24c39078c7b7f76c809038" + }, + "proot.tar.gz": { + "url": "https://codeload.github.com/proot-me/proot/tar.gz/d4b49e2243dee34e41c13dfeca6a3d07e9cf0f00", + "size": 234642, + "sha256": "25ffd8f31f32a0edd644da770008d8b8ee99197da03dc80cd20226b3012b7d26" + }, + "libtalloc-dev.deb": { + "url": "https://snapshot.ubuntu.com/ubuntu/20261026T000000Z/pool/main/t/talloc/libtalloc-dev_2.4.2-1build2_arm64.deb", + "size": 62224, + "sha256": "d63fc770129092ba8c40d44db4e2d740f645d5291ea6a9bf9b61d7e5294dcf5c" + }, + "libtalloc2.deb": { + "url": "https://snapshot.ubuntu.com/ubuntu/20261026T000000Z/pool/main/t/talloc/libtalloc2_2.4.2-1build2_arm64.deb", + "size": 26748, + "sha256": "4b182e41db5537937a423fc8f9593c65330553442eba17e058c4cc1c7a73a382" + }, + "pkgconf-bin.deb": { + "url": "https://snapshot.ubuntu.com/ubuntu/20261026T000000Z/pool/main/p/pkgconf/pkgconf-bin_1.8.1-2build1_arm64.deb", + "size": 20458, + "sha256": "bcd0d24c48b8b73ed7ba20ffc21a3575d5d9bdd53c3cee5a8051b7bde5fbf638" + }, + "libpkgconf3.deb": { + "url": "https://snapshot.ubuntu.com/ubuntu/20261026T000000Z/pool/main/p/pkgconf/libpkgconf3_1.8.1-2build1_arm64.deb", + "size": 31226, + "sha256": "f476cb81e1ecec6bf974f21181469cf5edcc749c4ead621469cdbf584dfd3be8" + } + }, + "fedora_layer": { + "archive": "fedora.oci.tar.xz", + "manifest": "sha256:cf9e82fbfad546ad06c626dabe8ba1aac6100ecfde4339e521352e9b77eaa794", + "sha256": "cfc0be9fb5518ec8eb4521cdb4dc2ee14df42924e0f468d24a8e6cfbdda5fdc9", + "size": 58468983 + } +} diff --git a/.github/scripts/fedora-proot/test_fedora_proot.py b/.github/scripts/fedora-proot/test_fedora_proot.py new file mode 100644 index 0000000000..9f97d1494d --- /dev/null +++ b/.github/scripts/fedora-proot/test_fedora_proot.py @@ -0,0 +1,405 @@ +import hashlib +import importlib.util +import io +import json +import tarfile +import tempfile +import unittest +import unittest.mock +from pathlib import Path + +HERE = Path(__file__).resolve().parent +SPEC = importlib.util.spec_from_file_location("pilot", HERE / "fedora_proot.py") +pilot = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(pilot) + + +class InputValidation(unittest.TestCase): + def test_size_and_digest_must_both_match(self): + with tempfile.TemporaryDirectory() as tmp: + p = Path(tmp) / "input" + p.write_bytes(b"approved") + spec = {"size": 8, "sha256": hashlib.sha256(b"approved").hexdigest()} + pilot.verified(p, spec) + p.write_bytes(b"replaced") + with self.assertRaisesRegex(ValueError, "SHA-256"): + pilot.verified(p, spec) + p.write_bytes(b"short") + with self.assertRaisesRegex(ValueError, "size"): + pilot.verified(p, spec) + + def extract(self, entries, tmp): + archive = Path(tmp) / "layer.tar" + with tarfile.open(archive, "w") as tar: + for name, typ, content in entries: + info = tarfile.TarInfo(name) + info.type = typ + if typ == tarfile.REGTYPE: + info.size = len(content) + info.mode = 0o6755 + tar.addfile(info, io.BytesIO(content)) + else: + info.linkname = content + tar.addfile(info) + root = Path(tmp) / "root" + pilot.extract_root(archive, root) + return root + + def test_absolute_rootfs_symlink_is_created_last(self): + with tempfile.TemporaryDirectory() as tmp: + root = self.extract( + [ + ("lib", tarfile.SYMTYPE, "/usr/lib"), + ("usr/lib/tool", tarfile.REGTYPE, b"tool"), + ], + tmp, + ) + self.assertEqual((root / "lib").readlink(), Path("/usr/lib")) + self.assertEqual((root / "usr/lib/tool").read_bytes(), b"tool") + self.assertEqual((root / "usr/lib/tool").stat().st_mode & 0o6000, 0) + + def test_bad_paths_and_overlay_layers_are_refused(self): + for name in ("/outside", "../outside", "usr/../../outside", "usr/.wh.hidden"): + with self.subTest(name=name), tempfile.TemporaryDirectory() as tmp: + with self.assertRaises(ValueError): + self.extract([(name, tarfile.REGTYPE, b"bad")], tmp) + + def test_symlink_cannot_redirect_another_symlink_outside(self): + with tempfile.TemporaryDirectory() as tmp: + with self.assertRaisesRegex(ValueError, "parent escapes"): + self.extract( + [ + ("escape", tarfile.SYMTYPE, tmp), + ("escape/other", tarfile.SYMTYPE, "/usr/lib"), + ], + tmp, + ) + self.assertFalse((Path(tmp) / "other").exists()) + + def test_duplicate_and_escaping_hardlinks_are_refused(self): + cases = [ + [("tool", tarfile.REGTYPE, b"x"), ("tool", tarfile.REGTYPE, b"y")], + [("tool", tarfile.LNKTYPE, "../../outside")], + ] + for entries in cases: + with tempfile.TemporaryDirectory() as tmp, self.assertRaises(ValueError): + self.extract(entries, tmp) + + def test_archived_repos_keep_package_signature_checks(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + repo = root / "etc/yum.repos.d" + repo.mkdir(parents=True) + (repo / "mirror.repo").write_text("metalink=https://unbounded.example/\n") + pilot.archived_repos(root) + files = list(repo.glob("*.repo")) + self.assertEqual(len(files), 1) + text = files[0].read_text() + self.assertEqual(text.count("gpgcheck=1"), 2) + self.assertNotIn("metalink", text) + self.assertEqual(text.count("https://archives.fedoraproject.org/"), 2) + + def test_repository_writes_cannot_follow_rootfs_links_outside(self): + for escape_file in (False, True): + with ( + self.subTest(escape_file=escape_file), + tempfile.TemporaryDirectory() as tmp, + ): + root = Path(tmp) / "root" + outside = Path(tmp) / "outside" + root.mkdir() + outside.mkdir() + (root / "etc").mkdir() + if escape_file: + (root / "etc/yum.repos.d").mkdir() + (root / "etc/yum.repos.d/pilot-fedora42.repo").symlink_to( + outside / "target" + ) + else: + (root / "etc/yum.repos.d").symlink_to(outside) + with self.assertRaisesRegex(ValueError, "escapes"): + pilot.archived_repos(root) + self.assertEqual(list(outside.iterdir()), []) + + +class OciLayer(unittest.TestCase): + """The archived Fedora OCI image: only its one pinned gzip layer, by digest.""" + + LAYER = "application/vnd.oci.image.layer.v1.tar+gzip" + + def build(self, tmp, layers=1, manifests=1, media=None, tamper_manifest=False): + layer = b"layer-bytes-" * 100 + digest = hashlib.sha256(layer).hexdigest() + entries = [ + { + "mediaType": media or self.LAYER, + "digest": "sha256:" + digest, + "size": len(layer), + } + ] * layers + manifest = json.dumps({"schemaVersion": 2, "layers": entries}).encode() + mdigest = hashlib.sha256(manifest).hexdigest() + stored = manifest + (b" " if tamper_manifest else b"") + index = json.dumps( + { + "schemaVersion": 2, + "manifests": [{"digest": "sha256:" + mdigest}] * manifests, + } + ).encode() + archive = Path(tmp) / "fedora.oci.tar.xz" + with tarfile.open(archive, "w:xz") as tar: + for name, data in ( + ("index.json", index), + ("blobs/sha256/" + mdigest, stored), + ("blobs/sha256/" + digest, layer), + ): + info = tarfile.TarInfo(name) + info.size = len(data) + tar.addfile(info, io.BytesIO(data)) + spec = { + "archive": "fedora.oci.tar.xz", + "manifest": "sha256:" + mdigest, + "sha256": digest, + "size": len(layer), + } + return archive, spec, layer + + def test_pinned_layer_is_extracted_and_verified(self): + with tempfile.TemporaryDirectory() as tmp: + archive, spec, layer = self.build(tmp) + target = Path(tmp) / "fedora.tar.gz" + pilot.oci_layer(archive, spec, target) + self.assertEqual(target.read_bytes(), layer) + pilot.oci_layer(archive, spec, target) # an existing verified layer is kept + + def test_other_manifest_layers_or_media_are_refused(self): + cases = [ + dict(layers=2), + dict(manifests=2), + dict(media="application/vnd.oci.image.layer.v1.tar"), + dict(tamper_manifest=True), + ] + for case in cases: + with tempfile.TemporaryDirectory() as tmp: + archive, spec, _ = self.build(tmp, **case) + with self.assertRaises(ValueError): + pilot.oci_layer(archive, spec, Path(tmp) / "fedora.tar.gz") + self.assertFalse((Path(tmp) / "fedora.tar.gz").exists()) + + def test_pins_must_name_the_manifest_and_layer(self): + with tempfile.TemporaryDirectory() as tmp: + archive, spec, _ = self.build(tmp) + for change in ( + {"manifest": "sha256:" + "0" * 64}, + {"sha256": "0" * 64}, + {"size": spec["size"] - 1}, + ): + with self.assertRaises(ValueError): + pilot.oci_layer( + archive, dict(spec, **change), Path(tmp) / "fedora.tar.gz" + ) + self.assertFalse((Path(tmp) / "fedora.tar.gz").exists()) + + def rebuild(self, tmp, archive, replace): + """Copy archive, replacing members by name: (TarInfo, bytes or None).""" + out = Path(tmp) / "hostile.oci.tar.xz" + with tarfile.open(archive, "r:xz") as src, tarfile.open(out, "w:xz") as dst: + for member in src: + if member.name in replace: + info, data = replace[member.name] + dst.addfile(info, io.BytesIO(data) if data is not None else None) + else: + dst.addfile(member, src.extractfile(member)) + return out + + def test_non_regular_or_oversized_members_are_refused(self): + with tempfile.TemporaryDirectory() as tmp: + archive, spec, _ = self.build(tmp) + link = tarfile.TarInfo("blobs/sha256/" + spec["sha256"]) + link.type = tarfile.SYMTYPE + link.linkname = "index.json" + big = json.dumps( + {"manifests": [{"digest": spec["manifest"]}], "pad": "x" * (1 << 16)} + ).encode() + index = tarfile.TarInfo("index.json") + index.size = len(big) + for replace in ({link.name: (link, None)}, {"index.json": (index, big)}): + hostile = self.rebuild(tmp, archive, replace) + with self.assertRaisesRegex(ValueError, "unexpected OCI member"): + pilot.oci_layer(hostile, spec, Path(tmp) / "fedora.tar.gz") + self.assertFalse((Path(tmp) / "fedora.tar.gz").exists()) + + def test_existing_target_must_be_the_pinned_layer(self): + with tempfile.TemporaryDirectory() as tmp: + archive, spec, _ = self.build(tmp) + target = Path(tmp) / "fedora.tar.gz" + target.write_bytes(b"not the layer") + with self.assertRaises(ValueError): + pilot.oci_layer(archive, spec, target) + + def test_fetch_inputs_derives_the_layer_and_verify_inputs_checks_it(self): + with tempfile.TemporaryDirectory() as tmp: + archive, spec, layer = self.build(tmp) + raw = archive.read_bytes() + pins = { + "files": { + "fedora.oci.tar.xz": { + "url": "https://unused.invalid/", + "size": len(raw), + "sha256": hashlib.sha256(raw).hexdigest(), + } + }, + "fedora_layer": spec, + } + dest = Path(tmp) / "inputs" + dest.mkdir() + (dest / "fedora.oci.tar.xz").write_bytes(raw) + pilot.fetch_inputs(dest, pins) # present and verified: no download + self.assertEqual((dest / "fedora.tar.gz").read_bytes(), layer) + pilot.verify_inputs(dest, pins) + (dest / "fedora.tar.gz").write_bytes(b"x" * len(layer)) + with self.assertRaisesRegex(ValueError, "SHA-256"): + pilot.verify_inputs(dest, pins) + + def test_rootfs_comes_from_the_archived_oci_image(self): + pins = json.loads((HERE / "pins.json").read_text()) + layer = pins["fedora_layer"] + self.assertNotIn("fedora.tar.gz", pins["files"]) + source = pins["files"][layer["archive"]] + self.assertTrue( + source["url"].startswith( + "https://archives.fedoraproject.org/pub/archive/fedora/linux/releases/42/Container/aarch64/images/" + ) + ) + self.assertEqual(pins["fedora_manifest"], layer["manifest"]) + self.assertEqual(len(layer["sha256"]), 64) + self.assertGreater(layer["size"], 0) + + +class ProotFaccessat2(unittest.TestCase): + """PRoot 5.4.1's ARM64 table lacks faccessat2 (439). + + Guest access checks would otherwise read host paths. + """ + + TABLE = ( + "static const Sysnum sysnums_arm64[] = {\n" + " [291] = PR_statx,\n" + " [435] = PR_clone3,\n" + "};\n" + ) + + def table(self, tmp, text): + path = Path(tmp) / "syscall" + path.mkdir() + (path / "sysnums-arm64.h").write_text(text) + return Path(tmp) + + def test_faccessat2_is_added_once_after_clone3(self): + with tempfile.TemporaryDirectory() as tmp: + src = self.table(tmp, self.TABLE) + digest = pilot.patch_proot_faccessat2(src) + text = (src / "syscall/sysnums-arm64.h").read_text() + self.assertIn(" [435] = PR_clone3,\n [439] = PR_faccessat2,\n", text) + self.assertEqual(digest, hashlib.sha256(text.encode()).hexdigest()) + + def test_unexpected_tables_are_refused(self): + for text in ( + self.TABLE.replace("[435] = PR_clone3,", ""), + self.TABLE + " [435] = PR_clone3,\n", + self.TABLE.replace("};", " [439] = PR_faccessat2,\n};"), + ): + with tempfile.TemporaryDirectory() as tmp: + with self.assertRaises(RuntimeError): + pilot.patch_proot_faccessat2(self.table(tmp, text)) + + +class Downloads(unittest.TestCase): + """Pinned downloads retry a bounded number of times; no partial file is kept.""" + + class Response(io.BytesIO): + def __enter__(self): + return self + + def __exit__(self, *exc): + return False + + def test_a_stale_partial_file_is_removed_before_the_first_attempt(self): + with ( + tempfile.TemporaryDirectory() as tmp, + unittest.mock.patch.object( + pilot.urllib.request, + "urlopen", + lambda url, timeout: self.Response(b"approved"), + ), + ): + part = Path(tmp) / "input.part" + part.write_bytes(b"stale") + pilot.download("https://example.invalid/x", part, 8) + self.assertEqual(part.read_bytes(), b"approved") + + def test_a_truncated_body_is_retried(self): + bodies = [b"appr", b"approved"] + with ( + tempfile.TemporaryDirectory() as tmp, + unittest.mock.patch.object( + pilot.urllib.request, + "urlopen", + lambda url, timeout: self.Response(bodies.pop(0)), + ), + unittest.mock.patch.object(pilot.time, "sleep", lambda s: None), + ): + part = Path(tmp) / "input.part" + pilot.download("https://example.invalid/x", part, 8) + self.assertEqual(part.read_bytes(), b"approved") + self.assertEqual(bodies, []) + + def test_a_failed_attempt_is_retried_after_removing_the_partial_file(self): + calls = [] + + def urlopen(url, timeout): + calls.append(url) + if len(calls) == 1: + raise OSError("Tunnel connection failed: 502 Bad Gateway") + return self.Response(b"approved") + + with ( + tempfile.TemporaryDirectory() as tmp, + unittest.mock.patch.object(pilot.urllib.request, "urlopen", urlopen), + unittest.mock.patch.object(pilot.time, "sleep", lambda s: None), + ): + part = Path(tmp) / "input.part" + part.write_bytes(b"stale") + pilot.download("https://example.invalid/x", part, 8) + self.assertEqual(part.read_bytes(), b"approved") + self.assertEqual(len(calls), 2) + + def test_retries_are_bounded_and_oversized_bodies_refused(self): + calls = [] + + def urlopen(url, timeout): + calls.append(url) + return self.Response(b"x" * 9) + + with ( + tempfile.TemporaryDirectory() as tmp, + unittest.mock.patch.object(pilot.urllib.request, "urlopen", urlopen), + unittest.mock.patch.object(pilot.time, "sleep", lambda s: None), + ): + part = Path(tmp) / "input.part" + with self.assertRaisesRegex(ValueError, "oversized"): + pilot.download("https://example.invalid/x", part, 8, attempts=2) + self.assertFalse(part.exists()) + self.assertEqual(len(calls), 2) + + def test_pins_name_no_mlx_source_archive(self): + pins = json.loads((HERE / "pins.json").read_text()) + self.assertNotIn("mlx.tar.gz", pins["files"]) + self.assertFalse({"mlx_commit", "mlx_script", "mlx_script_sha256"} & set(pins)) + for spec in pins["files"].values(): + self.assertEqual(len(spec["sha256"]), 64) + self.assertTrue(spec["url"].startswith("https://")) + + +if __name__ == "__main__": + unittest.main() diff --git a/.github/workflows/build_and_test.yml b/.github/workflows/build_and_test.yml index f6cc80e68a..86dbbab431 100644 --- a/.github/workflows/build_and_test.yml +++ b/.github/workflows/build_and_test.yml @@ -94,13 +94,26 @@ jobs: linux_fedora_build_cpp_aarch64: name: Linux Fedora (aarch64) needs: check_lint - runs-on: ubuntu-22.04-arm - container: - image: fedora:42 + # The sandbox has no Docker: fedora_proot.py runs the same Fedora script in the archived + # Fedora 42 container rootfs under PRoot (built from pinned source). About 2.5 minutes. + runs-on: [self-hosted, linux, ARM64, darkbloom-linux-arm64] + timeout-minutes: 45 steps: - name: Checkout code uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + persist-credentials: false + + - name: Check the runner tools and test the Fedora PRoot helper + run: | + [[ "$RUNNER_NAME" == darkbloom-* ]] + [[ "$(uname -s)" == Linux && "$(uname -m)" == aarch64 ]] + cc --version + make --version + dpkg-deb --version + python3 --version + python3 -B .github/scripts/fedora-proot/test_fedora_proot.py - name: CPP Build Test - No Release run: | - bash ./.github/scripts/setup+build-cpp-linux-fedora-container.sh + python3 .github/scripts/fedora-proot/fedora_proot.py run --source "$GITHUB_WORKSPACE" --work "$RUNNER_TEMP/fedora-proot" diff --git a/FORKDIFF.md b/FORKDIFF.md index 095f965442..16534abb85 100644 --- a/FORKDIFF.md +++ b/FORKDIFF.md @@ -35,9 +35,14 @@ to hosted runners. These bounds are not a promise of a 24-hour native queue. The `DARKBLOOM_ROUTING` variable controls the separate dynamic route workflow; it does not turn off these native-only jobs. -The GitHub-hosted Pages job still packages and publishes the rendered artifact -through its protected environment. The Fedora jobs still use their existing -hosted runners. The disabled native CodeQL workflow keeps its separate routing +The Fedora aarch64 job runs the unchanged Fedora script on a Darkbloom Linux +ARM64 runner. The sandbox has no Docker, so `.github/scripts/fedora-proot/` +unpacks the archived Fedora 42 container rootfs (pinned by digest) and runs the +script under PRoot, built from pinned source with its missing ARM64 `faccessat2` +entry added. PRoot fakes root through ptrace and is not an isolation boundary; +the job VM is. The Fedora x86_64 job keeps its hosted runner: emulating x86 on +ARM was not qualified. The GitHub-hosted Pages job still packages and publishes +the rendered artifact through its protected environment. The disabled native CodeQL workflow keeps its separate routing and activation rules. ## The gate diff --git a/fork.yaml b/fork.yaml index 2a75f34b34..f246122d58 100644 --- a/fork.yaml +++ b/fork.yaml @@ -761,8 +761,10 @@ def: without a hosted fallback. The Linux lint, ASAN/UBSAN, fork-diff check and Pages renderer also use native-only labels. The sanitizer jobs use the qualified compiler image and a tool preflight, retaining their - original test script within a 60-minute cap. Fedora jobs stay on - GitHub-hosted runners, and the protected Pages publisher stays hosted. + original test script within a 60-minute cap. The Fedora aarch64 job runs + the same Fedora script natively in the archived Fedora 42 container rootfs + under PRoot (`.github/scripts/fedora-proot/`); the Fedora x86_64 job and + the protected Pages publisher stay on GitHub-hosted runners. `FORKDIFF.md` describes the qualification and watchdog time bounds. `darkbloom-watchdog.yml` remains unchanged; a rerun keeps these static labels. On a Darkbloom Sandbox that has @@ -795,6 +797,7 @@ def: `qqmm` and `gather_qmm`) check on the CPU pass that the documented error is raised. globs: - ".github/actionlint.yaml" + - ".github/scripts/fedora-proot/*" - "CMakeLists.txt" - ".github/actions/build/action.yml" - ".github/actions/build-docs/action.yml"