blob: 153c21f7416d312262b34e1621e0aa09b85e6ee1 [file]
#!/usr/bin/env python3
# Copyright 2026 The Fuchsia Authors
#
# Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0
# <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT
# license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option.
# This file may not be copied, modified, or distributed except according to
# those terms.
"""Sandboxed runner for `experimental/<slug>/` CI checks and main sweeps.
Executes each selected experiment's `ci_command` from `EXPERIMENT.toml` inside
`bwrap --clearenv --new-session --unshare-user --disable-userns --cap-drop ALL
--unshare-net --unshare-pid --unshare-ipc --unshare-uts --unshare-cgroup-try`
with a read-only `/workspace` populated from every non-`.git` top-level entry
(omitting `.git` whether directory, worktree file, or symlink), a private
`tmpfs` workdir, bounded streaming output capture, and a 5-minute wall-clock
cap. Emits `ci_exp_status.v1` JSON assembled strictly from recorded process
exit codes so experiment code cannot forge status artifacts or read GitHub
Actions runtime tokens.
"""
from __future__ import annotations
import argparse
from concurrent.futures import ThreadPoolExecutor, as_completed
import datetime
import json
import os
from pathlib import Path
import re
import secrets
import subprocess
import sys
import tomllib
from typing import Iterable, Sequence
SCHEMA = "ci_exp_status.v1"
DEFAULT_TIMEOUT_SECS = 300
MAX_WORKERS = 4
MAX_OUTPUT_BYTES = 256 * 1024
SLUG_RE = re.compile(r"^[a-z][a-z0-9-]{0,63}$")
_ETC_RO_BINDS = (
"/etc/alternatives",
"/etc/ld.so.cache",
"/etc/ld.so.conf",
"/etc/ld.so.conf.d",
"/etc/nsswitch.conf",
"/etc/ssl",
)
def _validate_slug(slug: str) -> str:
if not SLUG_RE.fullmatch(slug):
raise ValueError(
f"invalid experimental slug {slug!r}: expected lowercase kebab-case "
"(starting with [a-z], max 64 chars)"
)
return slug
def _validate_git_ref(ref: str, label: str) -> str:
if not ref or ref.startswith("-") or "\x00" in ref or any(c.isspace() for c in ref):
raise ValueError(f"invalid {label} git ref: {ref!r}")
return ref
def _validate_ci_command(cmd: object, context: str) -> list[str]:
if (
not isinstance(cmd, list)
or not cmd
or not all(
isinstance(arg, str) and arg.strip() and "\x00" not in arg
for arg in cmd
)
):
raise ValueError(f"{context}: invalid ci_command")
prog = cmd[0]
if (
prog.startswith("/")
or "\\" in prog
or ".." in prog.split("/")
):
raise ValueError(
f"{context}: ci_command[0] {prog!r} must not be absolute or traverse `..`"
)
return list(cmd)
def _is_regular_experiment_dir(repo_root: Path, slug: str) -> bool:
if not SLUG_RE.fullmatch(slug):
return False
exp_root = repo_root / "experimental"
if exp_root.is_symlink() or not exp_root.is_dir():
return False
slug_dir = exp_root / slug
if slug_dir.is_symlink() or not slug_dir.is_dir():
return False
manifest = slug_dir / "EXPERIMENT.toml"
return not manifest.is_symlink() and manifest.is_file()
def discover_all_slugs(repo_root: Path) -> list[str]:
"""Return sorted active experiment slugs under `experimental/`."""
exp_dir = repo_root / "experimental"
if not exp_dir.is_dir() or exp_dir.is_symlink():
return []
return sorted(
child.name
for child in exp_dir.iterdir()
if _is_regular_experiment_dir(repo_root, child.name)
)
def discover_changed_slugs(
repo_root: Path, base_ref: str, head_ref: str
) -> list[str]:
"""Return sorted active slugs touched between `base_ref` and `head_ref`."""
base_ref = _validate_git_ref(base_ref, "base")
head_ref = _validate_git_ref(head_ref, "head")
proc = subprocess.run(
[
"git",
"-C",
str(repo_root),
"diff",
"--name-only",
"--no-renames",
"-z",
f"{base_ref}...{head_ref}",
"--",
"experimental",
],
capture_output=True,
check=True,
)
slugs: set[str] = set()
for raw in proc.stdout.decode("utf-8", "surrogateescape").split("\0"):
if not raw.startswith("experimental/"):
continue
parts = raw.split("/")
if len(parts) < 3:
continue
slug = parts[1]
if _is_regular_experiment_dir(repo_root, slug):
slugs.add(slug)
return sorted(slugs)
def load_ci_command(repo_root: Path, slug: str) -> list[str]:
"""Read and validate `ci_command` from `experimental/<slug>/EXPERIMENT.toml`."""
slug = _validate_slug(slug)
exp_root = repo_root / "experimental"
slug_dir = exp_root / slug
toml_path = slug_dir / "EXPERIMENT.toml"
if (
exp_root.is_symlink()
or slug_dir.is_symlink()
or toml_path.is_symlink()
or not toml_path.is_file()
):
raise ValueError(
f"experimental/{slug}/EXPERIMENT.toml: missing or symlinked manifest"
)
data = tomllib.loads(toml_path.read_text(encoding="utf-8"))
return _validate_ci_command(
data.get("ci_command"), f"experimental/{slug}/EXPERIMENT.toml"
)
def _base_bwrap_argv(path_env: str) -> list[str]:
argv = [
"bwrap",
"--die-with-parent",
"--new-session",
"--unshare-user",
"--disable-userns",
"--unshare-net",
"--unshare-pid",
"--unshare-ipc",
"--unshare-uts",
"--unshare-cgroup-try",
"--cap-drop",
"ALL",
"--clearenv",
"--setenv",
"PATH",
path_env,
"--setenv",
"HOME",
"/tmp/exp-home",
"--setenv",
"TMPDIR",
"/tmp/exp-tmp",
"--ro-bind",
"/usr",
"/usr",
"--ro-bind",
"/bin",
"/bin",
"--ro-bind",
"/lib",
"/lib",
]
if Path("/lib64").exists():
argv.extend(["--ro-bind", "/lib64", "/lib64"])
if Path("/nix").exists():
argv.extend(["--ro-bind", "/nix", "/nix"])
for etc_path in _ETC_RO_BINDS:
argv.extend(["--ro-bind-try", etc_path, etc_path])
argv.extend([
"--proc",
"/proc",
"--dev",
"/dev",
"--tmpfs",
"/tmp",
"--dir",
"/tmp/exp-home",
"--dir",
"/tmp/exp-tmp",
])
return argv
def build_sandbox_argv(
repo_root: Path,
slug: str,
ci_command: Sequence[str],
*,
timeout_secs: int = DEFAULT_TIMEOUT_SECS,
path_env: str = "/usr/bin:/bin",
) -> list[str]:
"""Construct the `timeout` + hardened `bwrap` argv."""
slug = _validate_slug(slug)
if timeout_secs <= 0:
raise ValueError(f"timeout_secs must be positive, got {timeout_secs}")
validated_cmd = _validate_ci_command(list(ci_command), f"experimental/{slug}")
root = repo_root.resolve()
slug_cwd = f"/workspace/experimental/{slug}"
argv = [
"/usr/bin/timeout",
"--kill-after=15s",
f"{timeout_secs}s",
*_base_bwrap_argv(path_env),
"--tmpfs",
"/workspace",
]
for child in sorted(root.iterdir(), key=lambda p: p.name):
if child.name == ".git":
continue
dst = f"/workspace/{child.name}"
if child.is_symlink():
argv.extend(["--symlink", os.readlink(child), dst])
else:
argv.extend(["--ro-bind", str(child), dst])
argv.extend([
"--remount-ro",
"/workspace",
"--chdir",
slug_cwd,
"--",
*validated_cmd,
])
return argv
def probe_sandbox(path_env: str = "/usr/bin:/bin") -> None:
"""Verify `bwrap` can launch `/usr/bin/true` under the hardened profile."""
argv = [*_base_bwrap_argv(path_env), "--", "/usr/bin/true"]
try:
proc = subprocess.run(argv, capture_output=True, check=False)
except OSError as exc:
raise RuntimeError(f"bwrap sandbox probe failed to execute: {exc}") from exc
if proc.returncode != 0:
detail = (proc.stderr or proc.stdout or b"").decode("utf-8", errors="replace").strip()
raise RuntimeError(
f"bwrap sandbox probe exited {proc.returncode}: {detail}"
)
def decode_capped_output(
stdout: bytes | None,
stderr: bytes | None,
*,
max_bytes: int = MAX_OUTPUT_BYTES,
truncated: bool = False,
) -> str:
"""Safely decode raw subprocess output with UTF-8 replacement and size cap."""
raw = (stdout or b"") + (stderr or b"")
was_truncated = truncated or len(raw) > max_bytes
text = raw[:max_bytes].decode("utf-8", errors="replace")
if was_truncated:
text += "\n... [output truncated]"
return text
def run_bounded_capture(
argv: Sequence[str], *, max_bytes: int = MAX_OUTPUT_BYTES
) -> tuple[int, str]:
"""Run `argv` while streaming stdout+stderr into a bounded byte buffer."""
buf = bytearray()
truncated = False
with subprocess.Popen(
argv,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
) as proc:
assert proc.stdout is not None
while True:
chunk = proc.stdout.read(8192)
if not chunk:
break
remaining = max_bytes - len(buf)
if remaining > 0:
buf.extend(chunk[:remaining])
if len(chunk) > remaining:
truncated = True
rc = proc.wait()
return rc, decode_capped_output(
bytes(buf), None, max_bytes=max_bytes, truncated=truncated
)
def run_one_slug(
repo_root: Path,
slug: str,
*,
timeout_secs: int = DEFAULT_TIMEOUT_SECS,
path_env: str = "/usr/bin:/bin",
) -> tuple[str, int, str]:
"""Execute one experiment in the sandbox and return `(slug, rc, output)`."""
try:
cmd = load_ci_command(repo_root, slug)
argv = build_sandbox_argv(
repo_root, slug, cmd, timeout_secs=timeout_secs, path_env=path_env
)
except (ValueError, OSError, tomllib.TOMLDecodeError) as exc:
return slug, 2, str(exc)
rc, output = run_bounded_capture(argv)
return slug, rc, output
def render_status_report(
main_sha: str,
run_url: str,
results: dict[str, int],
*,
generated_at: str | None = None,
) -> dict[str, object]:
"""Assemble the `ci_exp_status.v1` JSON payload from exit codes."""
ts = generated_at or datetime.datetime.now(datetime.timezone.utc).strftime(
"%Y-%m-%dT%H:%M:%SZ"
)
experiments = {
slug: {
"result": "pass" if rc == 0 else "fail",
"exit_code": rc,
"log_url": run_url,
}
for slug, rc in sorted(results.items())
}
return {
"schema": SCHEMA,
"main_sha": main_sha,
"generated_at": ts,
"run_url": run_url,
"experiments": experiments,
}
def _emit_experiment_output(output: str) -> None:
if not output.strip():
return
if os.environ.get("GITHUB_ACTIONS") == "true":
token = secrets.token_hex(16)
print(f"::stop-commands::{token}", file=sys.stderr)
print(output.rstrip(), file=sys.stderr)
print(f"::{token}::", file=sys.stderr)
else:
print(output.rstrip(), file=sys.stderr)
def main(argv: Iterable[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument(
"--root",
type=Path,
default=Path(__file__).resolve().parent.parent,
help="repository root",
)
parser.add_argument(
"--mode",
choices=("changed", "sweep"),
required=True,
help="run only PR-changed slugs or sweep every active experiment",
)
parser.add_argument("--base", help="base git ref (required for --mode=changed)")
parser.add_argument("--head", default="HEAD", help="head git ref")
parser.add_argument(
"--timeout-secs",
type=int,
default=DEFAULT_TIMEOUT_SECS,
help="per-experiment timeout in seconds (default: 300)",
)
parser.add_argument(
"--status-out",
type=Path,
help="optional path to write `ci_exp_status.v1` JSON",
)
parser.add_argument("--main-sha", default="", help="commit SHA for status JSON")
parser.add_argument("--run-url", default="", help="workflow run URL for status JSON")
args = parser.parse_args(list(argv) if argv is not None else None)
if args.timeout_secs <= 0:
print("run_experimental_ci: --timeout-secs must be positive", file=sys.stderr)
return 2
root = args.root.resolve()
if args.mode == "changed":
if not args.base:
print(
"run_experimental_ci: --base is required for --mode=changed",
file=sys.stderr,
)
return 2
try:
slugs = discover_changed_slugs(root, args.base, args.head)
except ValueError as exc:
print(f"run_experimental_ci: {exc}", file=sys.stderr)
return 2
else:
slugs = discover_all_slugs(root)
if not slugs:
print(f"run_experimental_ci ({args.mode}): no active experiments selected.")
if args.status_out is not None:
report = render_status_report(args.main_sha, args.run_url, {})
args.status_out.parent.mkdir(parents=True, exist_ok=True)
args.status_out.write_text(
json.dumps(report, indent=2) + "\n", encoding="utf-8"
)
return 0
path_env = "/nix/var/nix/profiles/default/bin:/usr/local/bin:/usr/bin:/bin"
try:
probe_sandbox(path_env)
except RuntimeError as exc:
print(f"run_experimental_ci: {exc}", file=sys.stderr)
return 2
results: dict[str, int] = {}
with ThreadPoolExecutor(max_workers=min(MAX_WORKERS, len(slugs))) as pool:
futs = {
pool.submit(
run_one_slug,
root,
slug,
timeout_secs=args.timeout_secs,
path_env=path_env,
): slug
for slug in slugs
}
for fut in as_completed(futs):
slug, rc, output = fut.result()
results[slug] = rc
status = "PASS" if rc == 0 else f"FAIL (rc={rc})"
print(f"[experimental/{slug}] {status}")
if rc != 0:
_emit_experiment_output(output)
if args.status_out is not None:
report = render_status_report(args.main_sha, args.run_url, results)
args.status_out.parent.mkdir(parents=True, exist_ok=True)
args.status_out.write_text(
json.dumps(report, indent=2) + "\n", encoding="utf-8"
)
if args.mode == "changed" and any(rc != 0 for rc in results.values()):
return 1
return 0
if __name__ == "__main__":
sys.exit(main())