| #!/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. | |
| """Trusted defender harness for Anneal automated red-teaming.""" | |
| from __future__ import annotations | |
| import argparse | |
| import bz2 | |
| from dataclasses import dataclass | |
| import gzip | |
| import hashlib | |
| import io | |
| import json | |
| import lzma | |
| import math | |
| import os | |
| from pathlib import Path | |
| import re | |
| import secrets | |
| import shutil | |
| import signal | |
| import stat | |
| import subprocess | |
| import sys | |
| import tarfile | |
| import tempfile | |
| import threading | |
| from typing import Any, Callable, Iterable | |
| import zlib | |
| if __package__ in (None, ""): | |
| _CI_DIR = Path(__file__).resolve().parents[1] | |
| if str(_CI_DIR) not in sys.path: | |
| sys.path.insert(0, str(_CI_DIR)) | |
| from redteam import dedup, scenarios | |
| else: | |
| from . import dedup, scenarios | |
| import anneal_ci_lib | |
| RECEIPT_SCHEMA = "anneal-redteam-receipt/v1" | |
| REPLAY_SCHEMA = "anneal-redteam-replay/v1" | |
| MAX_SUBMISSION_FILES = 64 | |
| MAX_SUBMISSION_DIRS = 64 | |
| MAX_SUBMISSION_DEPTH = 16 | |
| MAX_TAR_MEMBERS = 256 | |
| MAX_TAR_PAX_BYTES = 4096 | |
| MAX_SUBMISSION_FILE_BYTES = 1_048_576 | |
| MAX_SUBMISSION_TOTAL_BYTES = 8_388_608 | |
| MAX_SUBMISSION_TAR_BYTES = 8_388_608 | |
| MAX_TAR_UNCOMPRESSED_BYTES = 8_912_896 | |
| MAX_XZ_DECOMPRESS_MEM_BYTES = 32 * 1024 * 1024 | |
| MAX_WITNESS_BYTES = 65_536 | |
| MAX_EXPLANATION_BYTES = 65_536 | |
| _MAX_CAPTURE_BYTES = 8 * 1024 * 1024 | |
| _MAX_THEORY_ARTIFACT_BYTES = 128 * 1024 * 1024 | |
| _MAX_REL_PATH_BYTES = 1024 | |
| _MAX_PATH_SEGMENT_BYTES = 255 | |
| VERIFIED_RUST_TARGET = "x86_64-unknown-linux-gnu" | |
| VERDICT_INVALID_SUBMISSION = "INVALID_SUBMISSION" | |
| VERDICT_ATTACKER_WON_HARNESS_COMPROMISED = "ATTACKER_WON_HARNESS_COMPROMISED" | |
| VERDICT_ATTACKER_WON_ANNEAL_COMPROMISED = "ATTACKER_WON_ANNEAL_COMPROMISED" | |
| VERDICT_DEFENDER_HELD_ANNEAL_FAIL_CLOSED = "DEFENDER_HELD_ANNEAL_FAIL_CLOSED" | |
| VERDICT_HARNESS_ERROR = "HARNESS_ERROR" | |
| WINNING_VERDICTS = frozenset({ | |
| VERDICT_ATTACKER_WON_HARNESS_COMPROMISED, | |
| VERDICT_ATTACKER_WON_ANNEAL_COMPROMISED, | |
| }) | |
| _KNOWN_BROKEN_VERIFY_KINDS = frozenset({"PROOF_HACK", "SPEC_PREFLIGHT_HACK"}) | |
| _LEAN_IDENT_RE = re.compile(r"^[A-Za-z][A-Za-z0-9_]*$") | |
| _RESERVED_LEAN_ROOTS = frozenset({ | |
| "Captured", "Expected", "Trusted", "Anneal", "Init", | |
| "Std", "Lean", "Lake", "TrustedBoundary", "SpecPreflight", "Spec", "Specs", | |
| "IncorrectnessCheck", "IncorrectnessExpected", "src", | |
| }) | |
| _OLEAN_AUDIT_SCRIPT = Path(__file__).resolve().with_name("olean_audit.lean") | |
| _THEORY_AUDIT_TRUSTED_FILES = ( | |
| "trusted/audit/TrustedBoundary.lean", | |
| "trusted/audit/SpecPreflight.lean", | |
| "trusted/audit/library-lock.json", | |
| ) | |
| _ALLOWED_ENV_KEYS = ( | |
| "PATH", "LANG", "LC_ALL", "LC_CTYPE", "TZ", "USER", "LOGNAME", "RUSTUP_HOME", | |
| ) | |
| _TRUSTED_BIN_ROOTS = (Path("/usr/bin"), Path("/bin"), Path("/usr/local/bin"), Path("/nix/store")) | |
| _CREDENTIAL_ENV_KEYS = ( | |
| "GITHUB_TOKEN", "GH_TOKEN", "GH_ENTERPRISE_TOKEN", "AWS_ACCESS_KEY_ID", | |
| "AWS_SECRET_ACCESS_KEY", "AWS_SESSION_TOKEN", "GOOGLE_APPLICATION_CREDENTIALS", | |
| "SSH_AUTH_SOCK", | |
| ) | |
| _CREDENTIAL_HOME_RELS = ( | |
| ".ssh", ".config/gh", ".config/git/credentials", ".git-credentials", | |
| ".netrc", ".aws", ".config/gcloud", ".docker", ".kube", ".gnupg", | |
| ".cargo/credentials", ".cargo/credentials.toml", | |
| ) | |
| _CLEAN_STANDIN_RS = "#![no_std]\n\npub fn redteam_target() -> u64 {\n 0\n}\n" | |
| _CLEAN_STANDIN_SPEC = ( | |
| "module\nprelude\npublic import Trusted.MirSemantics\n\n" | |
| "@[expose] public section\nnamespace Spec\nopen Trusted.MirSemantics\n" | |
| "noncomputable def specs : Specs := ⟨fun _ _ => True, fun _ => True⟩\n" | |
| "end Spec\nend\n" | |
| ) | |
| class InvalidSubmissionError(Exception): | |
| """Raised when an untrusted submission violates staging or schema rules.""" | |
| class OracleInfrastructureError(Exception): | |
| """Raised when defender setup or execution infrastructure malfunctions.""" | |
| class _ArtifactSymlinkError(OracleInfrastructureError): | |
| """Raised when untrusted `verify` outputs contain a symlink entry.""" | |
| class DefenderTamperError(Exception): | |
| """Raised when execution mutates defender-locked assets or directories.""" | |
| def __init__(self, message: str, *, phase: str, tampered_assets: tuple[dict[str, Any], ...]) -> None: | |
| super().__init__(message) | |
| self.phase = phase | |
| self.tampered_assets = tampered_assets | |
| self.tampered_paths = tuple(entry["path"] for entry in tampered_assets) | |
| @dataclass(frozen=True) | |
| class LoadedSubmission: | |
| """Validated attacker submission paired with its mandatory brief.""" | |
| files: dict[str, bytes] | |
| explanation_text: str | |
| explanation_sha256: str | |
| @dataclass(frozen=True) | |
| class _PinnedAssetSnapshot: | |
| sha256: str | |
| dev: int | |
| ino: int | |
| mode: int | |
| nlink: int | |
| ctime_ns: int | |
| mtime_ns: int | |
| def _open_flags() -> tuple[int, int]: | |
| for attr in ("O_NOFOLLOW", "O_DIRECTORY", "O_NONBLOCK"): | |
| if not hasattr(os, attr): | |
| raise OracleInfrastructureError(f"host OS lacks required os.{attr} safety flag") | |
| ro = os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK | |
| return ro, ro | os.O_DIRECTORY | |
| def _loads_strict_dict(text: str, *, label: str, exc_type: type[Exception]) -> dict[str, Any]: | |
| try: | |
| data = json.loads(text, object_pairs_hook=anneal_ci_lib.reject_duplicate_json_keys) | |
| except (TypeError, ValueError, json.JSONDecodeError) as exc: | |
| raise exc_type(f"invalid {label}: {exc}") from exc | |
| if not isinstance(data, dict): | |
| raise exc_type(f"{label} must be a JSON object") | |
| return data | |
| def _open_regular_ro( | |
| path: Path | str, | |
| *, | |
| dir_fd: int | None = None, | |
| max_bytes: int | None = None, | |
| disallow_hardlink: bool = False, | |
| exc_type: type[Exception] = InvalidSubmissionError, | |
| ) -> tuple[os.stat_result, Any]: | |
| ro_flags, _ = _open_flags() | |
| try: | |
| fd = os.open(path, ro_flags, dir_fd=dir_fd) if dir_fd is not None else os.open(path, ro_flags) | |
| except OSError as exc: | |
| raise exc_type(f"cannot open {path}: {exc}") from exc | |
| try: | |
| fst = os.fstat(fd) | |
| if not stat.S_ISREG(fst.st_mode) or (disallow_hardlink and fst.st_nlink > 1): | |
| raise exc_type(f"disallowed non-regular or linked file: {path}") | |
| if max_bytes is not None and fst.st_size > max_bytes: | |
| raise exc_type(f"file exceeds {max_bytes} bytes: {path}") | |
| fh = os.fdopen(fd, "rb") | |
| fd = -1 | |
| return fst, fh | |
| finally: | |
| if fd >= 0: | |
| os.close(fd) | |
| def _inspect_regular_nofollow(path: Path, *, exc_type: type[Exception] = OracleInfrastructureError) -> _PinnedAssetSnapshot: | |
| fst, handle = _open_regular_ro(path, exc_type=exc_type) | |
| hasher = hashlib.sha256() | |
| with handle: | |
| while chunk := handle.read(65_536): | |
| hasher.update(chunk) | |
| return _PinnedAssetSnapshot(hasher.hexdigest(), fst.st_dev, fst.st_ino, fst.st_mode, fst.st_nlink, fst.st_ctime_ns, fst.st_mtime_ns) | |
| def _read_regular_file_nofollow(path: Path, *, max_bytes: int | None = None, exc_type: type[Exception] = InvalidSubmissionError) -> bytes: | |
| _, handle = _open_regular_ro(path, max_bytes=max_bytes, exc_type=exc_type) | |
| with handle: | |
| data = handle.read((max_bytes + 1) if max_bytes is not None else -1) | |
| if max_bytes is not None and len(data) > max_bytes: | |
| raise exc_type(f"file grew past {max_bytes} bytes: {path}") | |
| return data | |
| def _write_new_regular_file_excl(dest: Path, data: bytes) -> None: | |
| _open_flags() | |
| try: | |
| dest.parent.mkdir(parents=True, exist_ok=True) | |
| fd = os.open(dest, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o644) | |
| except OSError as exc: | |
| raise InvalidSubmissionError(f"cannot stage file {dest.name}: {exc}") from exc | |
| try: | |
| with os.fdopen(fd, "wb") as handle: | |
| fd = -1 | |
| handle.write(data) | |
| finally: | |
| if fd >= 0: | |
| os.close(fd) | |
| def _kill_pg_quiet(pid: int) -> None: | |
| try: | |
| os.killpg(pid, signal.SIGKILL) | |
| except ProcessLookupError: | |
| pass | |
| def _run_bounded_subprocess( | |
| cmd: list[str], *, timeout: int, cwd: Path | None = None, env: dict[str, str] | None = None | |
| ) -> subprocess.CompletedProcess[str]: | |
| buckets: list[list[bytes]] = [[], []] | |
| def _drain(stream: Any, idx: int) -> None: | |
| kept = 0 | |
| try: | |
| while chunk := stream.read(65_536): | |
| if kept < _MAX_CAPTURE_BYTES: | |
| take = chunk[: _MAX_CAPTURE_BYTES - kept] | |
| buckets[idx].append(take) | |
| kept += len(take) | |
| finally: | |
| try: | |
| stream.close() | |
| except OSError: | |
| pass | |
| proc = subprocess.Popen(cmd, cwd=cwd, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, start_new_session=True) | |
| assert proc.stdout is not None and proc.stderr is not None | |
| threads = [threading.Thread(target=_drain, args=(s, i), daemon=True) for i, s in enumerate((proc.stdout, proc.stderr))] | |
| for t in threads: | |
| t.start() | |
| try: | |
| try: | |
| rc = proc.wait(timeout=timeout) | |
| except subprocess.TimeoutExpired: | |
| _kill_pg_quiet(proc.pid) | |
| try: | |
| proc.wait(timeout=5) | |
| except subprocess.TimeoutExpired: | |
| pass | |
| for t in threads: | |
| t.join(timeout=2) | |
| raise | |
| for t in threads: | |
| t.join(timeout=5) | |
| if any(t.is_alive() for t in threads): | |
| _kill_pg_quiet(proc.pid) | |
| for t in threads: | |
| t.join(timeout=2) | |
| raise OracleInfrastructureError("subprocess exited while descendant held output pipes open") | |
| return subprocess.CompletedProcess(cmd, rc, stdout=b"".join(buckets[0]).decode("utf-8", errors="replace"), stderr=b"".join(buckets[1]).decode("utf-8", errors="replace")) | |
| finally: | |
| # Unconditionally terminate same-session/pgid descendants (including | |
| # stdio-detached children) before running post-phase integrity checks. | |
| _kill_pg_quiet(proc.pid) | |
| def _find_bwrap_bin() -> str | None: | |
| if (found := shutil.which("bwrap")) and Path(found).is_file(): | |
| return found | |
| default = Path("/usr/bin/bwrap") | |
| return str(default) if default.is_file() else None | |
| _SYSTEM_CONTAINER_ROOTS = frozenset({ | |
| Path("/"), Path("/tmp"), Path("/var"), Path("/var/tmp"), Path("/home"), | |
| Path("/root"), Path("/usr"), Path("/usr/local"), Path("/usr/local/src"), | |
| Path("/usr/src"), Path("/usr/bin"), Path("/usr/sbin"), Path("/usr/lib"), | |
| Path("/usr/lib32"), Path("/usr/lib64"), Path("/usr/libx32"), | |
| Path("/usr/libexec"), Path("/usr/share"), Path("/usr/include"), | |
| Path("/usr/local/bin"), Path("/usr/local/sbin"), Path("/usr/local/lib"), | |
| Path("/usr/local/lib32"), Path("/usr/local/lib64"), Path("/usr/local/libx32"), | |
| Path("/usr/local/libexec"), Path("/usr/local/share"), | |
| Path("/usr/local/include"), Path("/etc"), Path("/opt"), Path("/nix"), | |
| }) | |
| def _repo_protected_paths(anneal_root: Path) -> tuple[Path, ...]: | |
| """Return `anneal_root` (and parent repo checkout if safe to mask/deny).""" | |
| cands: list[Path] = [] | |
| for p in (anneal_root, *( (anneal_root.parent,) if anneal_root.name == "anneal" else () )): | |
| try: | |
| rp = p.resolve() | |
| except OSError: | |
| rp = p | |
| if rp not in _SYSTEM_CONTAINER_ROOTS: | |
| cands.append(rp) | |
| return tuple(dict.fromkeys(cands)) | |
| def _is_broad_protected_root( | |
| path: Path, *, extra_protected: Iterable[Path] = () | |
| ) -> bool: | |
| """Return True if `path` equals or contains a masked/host-sensitive prefix.""" | |
| try: | |
| rp = path.resolve() | |
| except OSError: | |
| return True | |
| protected: set[Path] = { | |
| Path("/"), Path("/tmp"), Path("/var/tmp"), Path("/home"), Path("/root"), | |
| Path("/usr"), Path("/usr/local"), Path("/usr/local/src"), Path("/usr/src"), | |
| Path("/etc"), | |
| } | |
| for extra in (str(Path.home()), os.environ.get("HOME", ""), *(str(p) for p in extra_protected)): | |
| if extra: | |
| try: | |
| protected.add(Path(extra).resolve()) | |
| except OSError: | |
| protected.add(Path(extra)) | |
| return any(rp == pr or pr.is_relative_to(rp) for pr in protected) | |
| def _is_credential_path(path: Path) -> bool: | |
| """Return True if `path` touches or contains any sensitive home credential path.""" | |
| try: | |
| rp = path.resolve() | |
| except OSError: | |
| return True | |
| homes: set[Path] = {Path.home()} | |
| if raw_home := os.environ.get("HOME", "").strip(): | |
| homes.add(Path(raw_home)) | |
| for h in homes: | |
| for rel in _CREDENTIAL_HOME_RELS: | |
| try: | |
| cp = (h / rel).resolve() | |
| except OSError: | |
| cp = h / rel | |
| if rp == cp or rp.is_relative_to(cp) or cp.is_relative_to(rp): | |
| return True | |
| return False | |
| def _build_bwrap_cmd( | |
| cmd: list[str], | |
| *, | |
| ro_paths: Iterable[Path], | |
| rw_paths: Iterable[Path], | |
| chdir: Path, | |
| env: dict[str, str], | |
| mem_limit_kb: int | None = None, | |
| require_bwrap: bool = False, | |
| protected_paths: Iterable[Path] = (), | |
| ) -> list[str]: | |
| """Confine untrusted subprocesses in an empty-rootfs Linux `bwrap` sandbox.""" | |
| bwrap_bin = _find_bwrap_bin() | |
| if bwrap_bin is None: | |
| if require_bwrap: | |
| raise OracleInfrastructureError("required `bwrap` outer sandbox missing") | |
| if mem_limit_kb is not None: | |
| return ["/bin/sh", "-c", 'ulimit -v "$1" && shift && exec "$@"', "_", str(mem_limit_kb), *cmd] | |
| return cmd | |
| wrapped = [ | |
| bwrap_bin, "--unshare-all", "--die-with-parent", "--new-session", | |
| "--clearenv", "--tmpfs", "/tmp", "--proc", "/proc", "--dev", "/dev", | |
| ] | |
| # Bind only standard OS binary/library subdirectories rather than `/usr` or | |
| # `/usr/local` wholesale, so site-local trees or checkouts under | |
| # `/usr/...` remain invisible unless explicitly targeted and masked. | |
| sys_ros = [ | |
| p for p in ( | |
| Path("/bin"), Path("/sbin"), Path("/lib"), Path("/lib32"), | |
| Path("/lib64"), Path("/libx32"), | |
| Path("/usr/bin"), Path("/usr/sbin"), Path("/usr/lib"), | |
| Path("/usr/lib32"), Path("/usr/lib64"), Path("/usr/libx32"), | |
| Path("/usr/libexec"), Path("/usr/share"), Path("/usr/include"), | |
| Path("/usr/local/bin"), Path("/usr/local/sbin"), | |
| Path("/usr/local/lib"), Path("/usr/local/lib32"), | |
| Path("/usr/local/lib64"), Path("/usr/local/libx32"), | |
| Path("/usr/local/libexec"), Path("/usr/local/share"), | |
| Path("/usr/local/include"), | |
| Path("/etc/ld.so.cache"), Path("/etc/ld.so.conf"), | |
| Path("/etc/ld.so.conf.d"), Path("/etc/alternatives"), Path("/nix"), | |
| ) | |
| if p.exists() | |
| ] | |
| for sys_ro in sys_ros: | |
| wrapped.extend(["--ro-bind", str(sys_ro), str(sys_ro)]) | |
| rw_resolved = sorted({p.resolve() for p in rw_paths}, key=lambda p: len(p.parts)) | |
| prot_list = tuple(protected_paths) | |
| # Mask user homes and protected repo/site directories whenever they sit | |
| # beneath a bound system prefix, before re-binding explicit tool paths. | |
| mask_candidates: list[Path] = [] | |
| for cand_str in ( | |
| str(Path.home()), | |
| os.environ.get("HOME", ""), | |
| *(str(p) for p in prot_list), | |
| ): | |
| if cand_str: | |
| try: | |
| cp = Path(cand_str).resolve() | |
| if cp in _SYSTEM_CONTAINER_ROOTS: | |
| continue | |
| if any(cp == s or cp.is_relative_to(s) for s in sys_ros) and not any(cp == rw or cp.is_relative_to(rw) for rw in rw_resolved): | |
| mask_candidates.append(cp) | |
| except OSError: | |
| pass | |
| masked_dedup: list[Path] = [] | |
| for mp in sorted(set(mask_candidates), key=lambda p: len(p.parts)): | |
| if not any(mp == prev or mp.is_relative_to(prev) for prev in masked_dedup): | |
| masked_dedup.append(mp) | |
| wrapped.extend(["--tmpfs", str(mp)]) | |
| raw_ros: list[Path] = [] | |
| for p in ro_paths: | |
| abs_p = Path(os.path.abspath(p)) | |
| res_p = p.resolve() | |
| if _is_broad_protected_root(abs_p, extra_protected=prot_list) or _is_broad_protected_root(res_p, extra_protected=prot_list): | |
| raise OracleInfrastructureError(f"refusing broad read-only sandbox mount: {p}") | |
| if _is_credential_path(abs_p) or _is_credential_path(res_p): | |
| raise OracleInfrastructureError(f"refusing credential read-only sandbox mount: {p}") | |
| raw_ros.append(res_p if p.is_dir() else abs_p) | |
| if not p.is_dir() and res_p != abs_p: | |
| raw_ros.append(res_p) | |
| ro_dedup: list[Path] = [] | |
| for cand in sorted(set(raw_ros), key=lambda p: (len(p.parts), str(p))): | |
| cand_res = cand.resolve() | |
| if any(cand_res == rw or cand_res.is_relative_to(rw) for rw in rw_resolved): | |
| continue | |
| # Only skip `cand` when `cand` itself (not a symlink target) sits | |
| # directly inside an unmasked `sys_ros` prefix. | |
| if any( | |
| (cand == s or cand.is_relative_to(s)) | |
| and not any( | |
| cand == m or cand.is_relative_to(m) | |
| or cand_res == m or cand_res.is_relative_to(m) | |
| for m in masked_dedup | |
| ) | |
| for s in sys_ros | |
| ): | |
| continue | |
| if any(prev == cand or (prev.is_dir() and cand.is_relative_to(prev)) for prev in ro_dedup): | |
| continue | |
| ro_dedup.append(cand) | |
| for rp in ro_dedup: | |
| wrapped.extend(["--ro-bind", str(rp), str(rp)]) | |
| for rp in rw_resolved: | |
| wrapped.extend(["--bind", str(rp), str(rp)]) | |
| rw_env = {"HOME": "/tmp", "TMPDIR": "/tmp"} | |
| for key in ("HOME", "XDG_CACHE_HOME", "TMPDIR"): | |
| if raw_v := env.get(key): | |
| vp = Path(raw_v).resolve() | |
| if any(vp == rw or vp.is_relative_to(rw) for rw in rw_resolved): | |
| rw_env[key] = str(vp) | |
| for k in ("PATH", "LD_LIBRARY_PATH", "DYLD_LIBRARY_PATH", "NO_COLOR", "LEAN_PATH", "CARGO_NET_OFFLINE"): | |
| if k in env: | |
| wrapped.extend(["--setenv", k, env[k]]) | |
| for k, v in sorted(rw_env.items()): | |
| wrapped.extend(["--setenv", k, v]) | |
| wrapped.extend(["--chdir", str(chdir.resolve()), "--"]) | |
| if mem_limit_kb is not None: | |
| wrapped.extend(["/bin/sh", "-c", 'ulimit -v "$1" && shift && exec "$@"', "_", str(mem_limit_kb)]) | |
| wrapped.extend(cmd) | |
| return wrapped | |
| def _probe_outer_bwrap(*, tmp_root: Path, env: dict[str, str], timeout: int) -> bool: | |
| """Return True when credential-free outer `bwrap` execution works on host.""" | |
| marker = tmp_root / ".outer-bwrap-ok" | |
| try: | |
| lst = os.lstat(marker) | |
| if stat.S_ISREG(lst.st_mode) and not stat.S_ISLNK(lst.st_mode): | |
| return True | |
| except OSError: | |
| pass | |
| if _find_bwrap_bin() is None: | |
| return False | |
| true_bin = shutil.which("true") or "/bin/true" | |
| probe_cmd = _build_bwrap_cmd([true_bin], ro_paths=(), rw_paths=(), chdir=Path("/tmp"), env=env, require_bwrap=True) | |
| try: | |
| proc = _run_bounded_subprocess(probe_cmd, env=env, timeout=min(timeout, 15)) | |
| except (subprocess.TimeoutExpired, OSError, OracleInfrastructureError): | |
| return False | |
| if proc.returncode != 0: | |
| return False | |
| try: | |
| _write_new_regular_file_excl(marker, b"ok\n") | |
| except InvalidSubmissionError: | |
| pass | |
| return True | |
| def _resolve_outer_sandbox(*, tmp_root: Path, env: dict[str, str], timeout: int, isolated_host: bool) -> bool: | |
| """Require either working outer `bwrap` or a verified credential-free host.""" | |
| if _probe_outer_bwrap(tmp_root=tmp_root, env=env, timeout=timeout): | |
| return True | |
| if not isolated_host: | |
| raise OracleInfrastructureError( | |
| "outer `bwrap` sandbox is unavailable; refusing unisolated execution without `--isolated-host` inside a credential-free container/VM" | |
| ) | |
| if bad_vars := [k for k in _CREDENTIAL_ENV_KEYS if os.environ.get(k)]: | |
| raise OracleInfrastructureError(f"`--isolated-host` refused: ambient credential env var(s) set: {bad_vars}") | |
| home_dir = Path.home() | |
| if bad_paths := [rel for rel in _CREDENTIAL_HOME_RELS if (home_dir / rel).exists()]: | |
| raise OracleInfrastructureError(f"`--isolated-host` refused: credential path(s) present under HOME: {bad_paths}") | |
| return False | |
| def _git_provenance(anneal_root: Path) -> tuple[str, bool | None, str | None, Path | None]: | |
| found = shutil.which("git") | |
| if not found or not anneal_root.is_dir(): | |
| return "unknown", None, None, None | |
| try: | |
| git_bin = Path(found).resolve(strict=True) | |
| st = os.stat(git_bin) | |
| if not any(git_bin.is_relative_to(r) for r in _TRUSTED_BIN_ROOTS) or not stat.S_ISREG(st.st_mode) or (st.st_mode & 0o022) or st.st_uid not in (0, os.geteuid()): | |
| return "unknown", None, None, None | |
| env = {k: v for k, v in os.environ.items() if not k.startswith("GIT_") and k not in ("CDPATH", "ENV", "BASH_ENV")} | |
| env.update({"GIT_CONFIG_NOSYSTEM": "1", "GIT_CONFIG_GLOBAL": os.devnull, "GIT_TERMINAL_PROMPT": "0", "LC_ALL": "C"}) | |
| base = [str(git_bin), *anneal_ci_lib.SAFE_GIT_FLAGS] | |
| sha_p = _run_bounded_subprocess([*base, "rev-parse", "HEAD"], cwd=anneal_root, env=env, timeout=10) | |
| if sha_p.returncode != 0 or not sha_p.stdout.strip(): | |
| return "unknown", None, None, git_bin | |
| st_p = _run_bounded_subprocess([*base, "status", "--porcelain", "--", "."], cwd=anneal_root, env=env, timeout=10) | |
| top_p = _run_bounded_subprocess([*base, "rev-parse", "--show-toplevel"], cwd=anneal_root, env=env, timeout=10) | |
| tree_oid: str | None = None | |
| if top_p.returncode == 0 and top_p.stdout.strip(): | |
| top_dir = Path(top_p.stdout.strip()).resolve() | |
| root_dir = anneal_root.resolve() | |
| if root_dir == top_dir: | |
| tree_spec = "HEAD^{tree}" | |
| elif root_dir.is_relative_to(top_dir): | |
| tree_spec = f"HEAD:{root_dir.relative_to(top_dir).as_posix()}" | |
| else: | |
| tree_spec = "HEAD^{tree}" | |
| tree_p = _run_bounded_subprocess([*base, "rev-parse", tree_spec], cwd=top_dir, env=env, timeout=10) | |
| if tree_p.returncode == 0 and tree_p.stdout.strip(): | |
| tree_oid = tree_p.stdout.strip() | |
| return ( | |
| sha_p.stdout.strip(), | |
| bool(st_p.stdout.strip()) if st_p.returncode == 0 else None, | |
| tree_oid, | |
| git_bin, | |
| ) | |
| except (OSError, subprocess.SubprocessError, OracleInfrastructureError): | |
| return "unknown", None, None, None | |
| def _pinned_lean_toolchain_dir(anneal_root: Path) -> str: | |
| """Return the `.elan/toolchains` dir matching `trusted/lean/lean-toolchain`.""" | |
| tc_file = anneal_root / "trusted" / "lean" / "lean-toolchain" | |
| tc_spec = "" | |
| try: | |
| if tc_file.is_file() and not tc_file.is_symlink(): | |
| if lines := tc_file.read_text(encoding="utf-8").strip().splitlines(): | |
| tc_spec = lines[0].strip() | |
| except (OSError, UnicodeDecodeError): | |
| pass | |
| tc_dir = (tc_spec or "leanprover/lean4:v4.35.0").replace("/", "--").replace(":", "---") | |
| if "/" in tc_dir or "\\" in tc_dir or "\x00" in tc_dir or tc_dir in ("", ".", ".."): | |
| return "leanprover--lean4---v4.35.0" | |
| return tc_dir | |
| def _discover_pinned_local_defaults( | |
| anneal_root: Path, | |
| *, | |
| need_cli: bool, | |
| need_capture: bool, | |
| need_lean: bool, | |
| need_sysroot: bool, | |
| ) -> dict[str, Path | None]: | |
| """Locate local tools without invoking ambient `PATH` `rustup`.""" | |
| raw_t = os.environ.get("CARGO_TARGET_DIR", "").strip() | |
| tdir = Path(raw_t) if raw_t else anneal_root / "target" | |
| cli = (tdir / "debug/cargo-anneal") if need_cli and (tdir / "debug/cargo-anneal").is_file() else None | |
| capture = next( | |
| (c for c in (tdir / "debug/anneal-rustc-capture", anneal_root / "trusted/rustc-capture/target/debug/anneal-rustc-capture") if need_capture and c.is_file()), | |
| None, | |
| ) | |
| home = Path.home() | |
| lean = None | |
| if need_lean: | |
| tc_root = (Path(os.environ["XDG_CACHE_HOME"].strip()) if os.environ.get("XDG_CACHE_HOME", "").strip() else home / ".cache") / "anneal/toolchain" | |
| cands: list[Path] = [] | |
| if tc_root.is_dir(): | |
| timed_entries: list[tuple[float, Path]] = [] | |
| try: | |
| for entry in tc_root.iterdir(): | |
| try: | |
| if entry.is_dir(): | |
| timed_entries.append((entry.stat().st_mtime, entry)) | |
| except OSError: | |
| pass | |
| except OSError: | |
| timed_entries = [] | |
| cands.extend(p for _, e in sorted(timed_entries, reverse=True) if (p := e / "lean/bin/lean").is_file()) | |
| elan_base = Path(raw_eh) if (raw_eh := os.environ.get("ELAN_HOME", "").strip()) else (home / ".elan") | |
| cands.append(elan_base / "toolchains" / _pinned_lean_toolchain_dir(anneal_root) / "bin/lean") | |
| lean = next((p for p in cands if p.is_file()), None) | |
| sysroot = None | |
| if need_sysroot: | |
| tc_dir = (Path(os.environ["RUSTUP_HOME"].strip()) if os.environ.get("RUSTUP_HOME", "").strip() else home / ".rustup") / "toolchains" | |
| pinned = None | |
| if tc_dir.is_dir() and not tc_dir.is_symlink(): | |
| exact = tc_dir / f"nightly-2026-05-31-{VERIFIED_RUST_TARGET}" | |
| if exact.is_dir() and not exact.is_symlink(): | |
| pinned = exact | |
| else: | |
| try: | |
| pinned = next((c for c in sorted(tc_dir.iterdir(), key=lambda p: p.name) if c.name.startswith("nightly-2026-05-31-") and c.is_dir() and not c.is_symlink()), None) | |
| except OSError: | |
| pass | |
| if pinned is not None and (rustc_bin := pinned / "bin/rustc").is_file(): | |
| try: | |
| proc = _run_bounded_subprocess( | |
| [str(rustc_bin), "--print", "sysroot"], | |
| env={"PATH": f"{pinned / 'bin'}:/usr/bin:/bin", "LD_LIBRARY_PATH": str(pinned / "lib"), "HOME": "/tmp", "TMPDIR": "/tmp", "NO_COLOR": "1"}, | |
| timeout=15, | |
| ) | |
| if proc.returncode == 0 and proc.stdout.strip() and Path(proc.stdout.strip()).resolve(strict=True) == pinned.resolve(strict=True): | |
| sysroot = pinned.resolve(strict=True) | |
| except (OSError, subprocess.SubprocessError, OracleInfrastructureError): | |
| pass | |
| return {"cli": cli, "capture": capture, "lean": lean, "sysroot": sysroot} | |
| def _raw_local_tool_candidates( | |
| anneal_root: Path, | |
| *, | |
| explicit_overrides: dict[str, Path | None], | |
| need_auditor: bool, | |
| raw_defaults: dict[str, Path | None], | |
| ) -> dict[str, Path | None]: | |
| """Locate unresolved tool paths prior to symlink canonicalization.""" | |
| raw: dict[str, Path | None] = {} | |
| raw_target = os.environ.get("CARGO_TARGET_DIR", "").strip() | |
| tdir = Path(raw_target) if raw_target else anneal_root / "target" | |
| cands_map: dict[str, list[Path | None]] = { | |
| "cli": [tdir / "release/cargo-anneal", tdir / "debug/cargo-anneal", raw_defaults.get("cli")], | |
| "capture": [tdir / "release/anneal-rustc-capture", tdir / "debug/anneal-rustc-capture", raw_defaults.get("capture")], | |
| "lean": [raw_defaults.get("lean")], | |
| "auditor": [tdir / "release/anneal-audit", tdir / "debug/anneal-audit"] if need_auditor else [], | |
| } | |
| for name, cands in cands_map.items(): | |
| if (exp := explicit_overrides.get(name)) is not None: | |
| raw[name] = exp | |
| else: | |
| raw[name] = next((c for c in cands if c is not None and c.is_file()), None) | |
| return raw | |
| def _snapshot_tool_provenance( | |
| tools: dict[str, Path | None], | |
| *, | |
| explicit_overrides: dict[str, Path | None], | |
| raw_paths: dict[str, Path | None] | None = None, | |
| git_bin: Path | None, | |
| include_auditor: bool = False, | |
| pin_olean_audit: bool = False, | |
| ) -> tuple[dict[str, dict[str, Any]], dict[str, tuple[Path, Path, _PinnedAssetSnapshot]]]: | |
| prov: dict[str, dict[str, Any]] = {} | |
| pinned_bins: dict[str, tuple[Path, Path, _PinnedAssetSnapshot]] = {} | |
| items = {**tools, "git": git_bin} | |
| if not include_auditor: | |
| items.pop("auditor", None) | |
| if pin_olean_audit: | |
| items["olean_audit"] = _OLEAN_AUDIT_SCRIPT if _OLEAN_AUDIT_SCRIPT.is_file() else None | |
| for name, tpath in items.items(): | |
| src = "explicit" if explicit_overrides.get(name) is not None else ("builtin" if name == "olean_audit" else "discovered") | |
| if tpath is None: | |
| prov[name] = {"present": False, "source": src} | |
| continue | |
| raw_path = explicit_overrides.get(name) or (raw_paths or {}).get(name) or tpath | |
| entry: dict[str, Any] = {"present": True, "source": src, "name": tpath.name} | |
| if name != "sysroot": | |
| try: | |
| resolved = tpath.resolve(strict=True) | |
| raw_resolved = raw_path.resolve(strict=True) | |
| except OSError as exc: | |
| raise OracleInfrastructureError(f"cannot resolve `{name}` tool `{tpath}`: {exc}") from exc | |
| if raw_resolved != resolved: | |
| raise OracleInfrastructureError(f"`{name}` raw path `{raw_path}` resolved to `{raw_resolved}` != `{resolved}`") | |
| snap = _inspect_regular_nofollow(resolved) | |
| entry.update({"sha256": snap.sha256, "mtime_ns": snap.mtime_ns}) | |
| pinned_bins[name] = (raw_path, resolved, snap) | |
| prov[name] = entry | |
| return prov, pinned_bins | |
| def _verify_pinned_tools(pinned_bins: dict[str, tuple[Path, Path, _PinnedAssetSnapshot]], *, phase: str) -> None: | |
| tampered: list[dict[str, Any]] = [] | |
| for name, (raw_path, tpath, exp) in sorted(pinned_bins.items()): | |
| try: | |
| if raw_path.resolve(strict=True) != tpath: | |
| tampered.append({"path": f"<tool:{name}>", "reasons": ["tool symlink retargeted"], "expected_sha256": exp.sha256, "actual_sha256": None}) | |
| continue | |
| act = _inspect_regular_nofollow(tpath) | |
| if act.sha256 != exp.sha256 or act.dev != exp.dev or act.ino != exp.ino: | |
| tampered.append({"path": f"<tool:{name}>", "reasons": ["tool binary mutated"], "expected_sha256": exp.sha256, "actual_sha256": act.sha256}) | |
| except OracleInfrastructureError as exc: | |
| tampered.append({"path": f"<tool:{name}>", "reasons": [f"tool unreadable: {exc}"], "expected_sha256": exp.sha256, "actual_sha256": None}) | |
| except OSError as exc: | |
| tampered.append({"path": f"<tool:{name}>", "reasons": [f"tool link unreadable: {exc}"], "expected_sha256": exp.sha256, "actual_sha256": None}) | |
| if tampered: | |
| raise DefenderTamperError(f"tool binary compromised during `{phase}`", phase=phase, tampered_assets=tuple(tampered)) | |
| def _validate_rel_posix(raw: str, *, allow_dot_prefix: bool = False) -> str: | |
| if not isinstance(raw, str) or not raw or "\x00" in raw or "\\" in raw or raw.startswith("/"): | |
| raise InvalidSubmissionError(f"invalid submission path: {raw!r}") | |
| norm = raw[2:] if (allow_dot_prefix and raw.startswith("./")) else raw | |
| segs = norm.split("/") | |
| if not norm or any(s in ("", ".", "..") for s in segs) or any(ord(c) < 32 for c in norm): | |
| raise InvalidSubmissionError(f"unsafe path segment in {raw!r}") | |
| if len(norm.encode("utf-8")) > _MAX_REL_PATH_BYTES or any(len(s.encode("utf-8")) > _MAX_PATH_SEGMENT_BYTES for s in segs): | |
| raise InvalidSubmissionError(f"submission path exceeds limit: {raw!r}") | |
| return norm | |
| def _check_case_colliding_paths(relpaths: Iterable[str]) -> None: | |
| seen_segs: dict[tuple[str, str], str] = {} | |
| seen_files: dict[str, str] = {} | |
| for rel in sorted(relpaths): | |
| parts = rel.split("/") | |
| folded = [p.casefold() for p in parts] | |
| full = "/".join(folded) | |
| if full in seen_files and seen_files[full] != rel: | |
| raise InvalidSubmissionError(f"case-colliding paths disallowed: {seen_files[full]!r} vs {rel!r}") | |
| seen_files[full] = rel | |
| parent = "" | |
| for idx, (orig, fold) in enumerate(zip(parts, folded)): | |
| if (prev := seen_segs.get((parent, fold))) is not None and prev != orig: | |
| raise InvalidSubmissionError(f"case-colliding components disallowed: {prev!r} vs {orig!r}") | |
| seen_segs[(parent, fold)] = orig | |
| if idx < len(parts) - 1: | |
| parent = f"{parent}/{fold}" if parent else fold | |
| class _BoundedReadStream(io.RawIOBase): | |
| """Fail closed once decompressed tar input exceeds `limit` bytes.""" | |
| def __init__(self, inner: Any, limit: int) -> None: | |
| self._inner, self._limit, self._seen = inner, limit, 0 | |
| def readable(self) -> bool: | |
| return True | |
| def read(self, size: int = -1) -> bytes: | |
| want = -1 if size is None else int(size) | |
| parts: list[bytes] = [] | |
| while (chunk := self._inner.read(want if want >= 0 else 65_536)): | |
| self._seen += len(chunk) | |
| if self._seen > self._limit: | |
| raise InvalidSubmissionError(f"tar stream exceeds {self._limit} bytes") | |
| if want >= 0: | |
| return chunk | |
| parts.append(chunk) | |
| return b"" if want >= 0 else b"".join(parts) | |
| def _read_bounded_xz(raw_fh: Any) -> io.BytesIO: | |
| buf, out = bytearray(), bytearray() | |
| decomp: lzma.LZMADecompressor | None = None | |
| while True: | |
| if decomp is None: | |
| while len(buf) < 4 and (chunk := raw_fh.read(65_536)): | |
| buf.extend(chunk) | |
| while buf[:4] == b"\x00\x00\x00\x00": | |
| del buf[:4] | |
| while len(buf) < 4 and (chunk := raw_fh.read(65_536)): | |
| buf.extend(chunk) | |
| if not buf: | |
| break | |
| decomp = lzma.LZMADecompressor(format=lzma.FORMAT_XZ, memlimit=MAX_XZ_DECOMPRESS_MEM_BYTES) | |
| if decomp.needs_input and not buf: | |
| if not (chunk := raw_fh.read(65_536)): | |
| raise lzma.LZMAError("truncated XZ archive") | |
| buf.extend(chunk) | |
| inp = bytes(buf) | |
| buf.clear() | |
| out.extend(decomp.decompress(inp, max_length=MAX_TAR_UNCOMPRESSED_BYTES - len(out) + 1)) | |
| if len(out) > MAX_TAR_UNCOMPRESSED_BYTES: | |
| raise InvalidSubmissionError(f"tar stream exceeds {MAX_TAR_UNCOMPRESSED_BYTES} bytes") | |
| if decomp.eof: | |
| buf.extend(decomp.unused_data) | |
| decomp = None | |
| return io.BytesIO(out) | |
| def _load_submission_dir(sub_dir: Path) -> dict[str, bytes]: | |
| _, dir_ro = _open_flags() | |
| try: | |
| root_fd = os.open(sub_dir, dir_ro) | |
| except OSError as exc: | |
| raise InvalidSubmissionError(f"cannot open submission dir {sub_dir}: {exc}") from exc | |
| files: dict[str, bytes] = {} | |
| dir_count, total_bytes = 0, 0 | |
| entry_cap = MAX_SUBMISSION_FILES + MAX_SUBMISSION_DIRS | |
| def _walk(cur_fd: int, prefix: str, depth: int) -> None: | |
| nonlocal dir_count, total_bytes | |
| try: | |
| with os.scandir(cur_fd) as entries: | |
| names = [e.name for i, e in enumerate(entries) if i < entry_cap] | |
| except OSError as exc: | |
| raise InvalidSubmissionError(f"cannot read directory `{prefix or '.'}`: {exc}") from exc | |
| if len(names) >= entry_cap: | |
| raise InvalidSubmissionError(f"dir exceeds {entry_cap} entries") | |
| for name in sorted(names): | |
| cand = f"{prefix}/{name}" if prefix else name | |
| try: | |
| est = os.stat(name, dir_fd=cur_fd, follow_symlinks=False) | |
| except OSError as exc: | |
| raise InvalidSubmissionError(f"cannot stat `{cand}`: {exc}") from exc | |
| if stat.S_ISDIR(est.st_mode): | |
| if depth + 1 > MAX_SUBMISSION_DEPTH or dir_count >= MAX_SUBMISSION_DIRS: | |
| raise InvalidSubmissionError(f"directory limit exceeded: {cand}") | |
| dir_count += 1 | |
| try: | |
| cfd = os.open(name, dir_ro, dir_fd=cur_fd) | |
| except OSError as exc: | |
| raise InvalidSubmissionError(f"cannot enter directory `{cand}`: {exc}") from exc | |
| try: | |
| _walk(cfd, _validate_rel_posix(cand), depth + 1) | |
| finally: | |
| os.close(cfd) | |
| elif stat.S_ISREG(est.st_mode): | |
| rel = _validate_rel_posix(cand) | |
| if len(files) >= MAX_SUBMISSION_FILES: | |
| raise InvalidSubmissionError("too many submission files") | |
| _, fh = _open_regular_ro(name, dir_fd=cur_fd, max_bytes=MAX_SUBMISSION_FILE_BYTES, disallow_hardlink=True) | |
| with fh: | |
| data = fh.read(MAX_SUBMISSION_FILE_BYTES + 1) | |
| total_bytes += len(data) | |
| if len(data) > MAX_SUBMISSION_FILE_BYTES or total_bytes > MAX_SUBMISSION_TOTAL_BYTES: | |
| raise InvalidSubmissionError(f"submission exceeds byte limit: {rel}") | |
| files[rel] = data | |
| else: | |
| raise InvalidSubmissionError(f"non-regular or symlink entry disallowed: {cand}") | |
| try: | |
| if not stat.S_ISDIR(os.fstat(root_fd).st_mode): | |
| raise InvalidSubmissionError("submission dir must be a directory") | |
| _walk(root_fd, "", 0) | |
| finally: | |
| os.close(root_fd) | |
| _check_case_colliding_paths(files.keys()) | |
| return files | |
| def _load_submission_tar(tar_path: Path) -> dict[str, bytes]: | |
| _, raw_ctx = _open_regular_ro(tar_path, max_bytes=MAX_SUBMISSION_TAR_BYTES) | |
| files: dict[str, bytes] = {} | |
| total_bytes, seen, dir_count = 0, 0, 0 | |
| try: | |
| with raw_ctx as raw_fh: | |
| head = raw_fh.read(6) | |
| raw_fh.seek(0) | |
| if head.startswith(b"\x1f\x8b"): | |
| stream: Any = _BoundedReadStream(gzip.GzipFile(fileobj=raw_fh, mode="rb"), MAX_TAR_UNCOMPRESSED_BYTES) | |
| elif head.startswith(b"BZh"): | |
| stream = _BoundedReadStream(bz2.BZ2File(raw_fh, mode="rb"), MAX_TAR_UNCOMPRESSED_BYTES) | |
| elif head.startswith(b"\xfd7zXZ\x00"): | |
| stream = _read_bounded_xz(raw_fh) | |
| else: | |
| stream = _BoundedReadStream(raw_fh, MAX_TAR_UNCOMPRESSED_BYTES) | |
| with tarfile.open(fileobj=stream, mode="r|") as tf: | |
| while (m := tf.next()) is not None: | |
| seen += 1 | |
| if seen > MAX_TAR_MEMBERS or (m.pax_headers and sum(len(str(k)) + len(str(v)) for k, v in m.pax_headers.items()) > MAX_TAR_PAX_BYTES): | |
| raise InvalidSubmissionError("tar metadata limit exceeded") | |
| if m.issym() or m.islnk(): | |
| raise InvalidSubmissionError(f"link disallowed in tar: {m.name!r}") | |
| if m.isdir(): | |
| if (raw_d := m.name.rstrip("/")) not in ("", "."): | |
| norm_d = _validate_rel_posix(raw_d, allow_dot_prefix=True) | |
| dir_count += 1 | |
| if dir_count > MAX_SUBMISSION_DIRS or len(norm_d.split("/")) > MAX_SUBMISSION_DEPTH: | |
| raise InvalidSubmissionError(f"tar directory limit exceeded: {norm_d}") | |
| continue | |
| if not m.isreg() or m.type != tarfile.REGTYPE: | |
| raise InvalidSubmissionError(f"special tar member: {m.name!r}") | |
| rel = _validate_rel_posix(m.name, allow_dot_prefix=True) | |
| if len(rel.split("/")) - 1 > MAX_SUBMISSION_DEPTH: | |
| raise InvalidSubmissionError(f"directory limit exceeded: {rel}") | |
| if rel in files or len(files) >= MAX_SUBMISSION_FILES or m.size < 0 or m.size > MAX_SUBMISSION_FILE_BYTES: | |
| raise InvalidSubmissionError(f"invalid or duplicate tar file: {rel}") | |
| if (ext := tf.extractfile(m)) is None: | |
| raise InvalidSubmissionError(f"unreadable tar member: {rel}") | |
| with ext: | |
| data = ext.read(MAX_SUBMISSION_FILE_BYTES + 1) | |
| total_bytes += len(data) | |
| if len(data) != m.size or total_bytes > MAX_SUBMISSION_TOTAL_BYTES: | |
| raise InvalidSubmissionError(f"tar size error: {rel}") | |
| files[rel] = data | |
| while stream.read(65_536): | |
| pass | |
| except InvalidSubmissionError: | |
| raise | |
| except (tarfile.TarError, lzma.LZMAError, zlib.error, gzip.BadGzipFile, EOFError, UnicodeError, RecursionError, OSError, ValueError) as exc: | |
| raise InvalidSubmissionError(f"invalid submission tar: {exc}") from exc | |
| _check_case_colliding_paths(files.keys()) | |
| return files | |
| def _validate_lean_slot_path(relpath: str, prefix: str) -> str: | |
| if not relpath.startswith(f"{prefix}/") or not relpath.endswith(".lean"): | |
| raise InvalidSubmissionError(f"path outside `{prefix}/*.lean` slot: {relpath}") | |
| parts = relpath[len(prefix) + 1 : -len(".lean")].split("/") | |
| if not parts or any(not _LEAN_IDENT_RE.match(p) for p in parts): | |
| raise InvalidSubmissionError(f"invalid Lean module path: {relpath}") | |
| if parts[0].lower() in {r.lower() for r in _RESERVED_LEAN_ROOTS}: | |
| raise InvalidSubmissionError(f"reserved Lean root disallowed: {relpath}") | |
| return ".".join(parts) | |
| def _validate_proof_slots(payload: dict[str, bytes]) -> None: | |
| if not payload: | |
| raise InvalidSubmissionError("submission contains no proof files") | |
| for rel in payload: | |
| _validate_lean_slot_path(rel, "Proof") | |
| if "Proof/Proof.lean" not in payload: | |
| raise InvalidSubmissionError("missing required `Proof/Proof.lean`") | |
| def _validate_spec_preflight_slots(payload: dict[str, bytes]) -> None: | |
| spec_files: dict[str, bytes] = {} | |
| proof_files: dict[str, bytes] = {} | |
| staged: dict[str, str] = {} | |
| for rel, data in sorted(payload.items()): | |
| if rel.startswith("Spec/"): | |
| spec_files[rel] = data | |
| if rel == "Spec/Spec.lean": | |
| srel = "Spec.lean" | |
| else: | |
| _validate_lean_slot_path(rel, "Spec") | |
| srel = rel | |
| elif rel.startswith("Proof/"): | |
| proof_files[rel] = data | |
| _validate_lean_slot_path(rel, "Proof") | |
| srel = rel[len("Proof/") :] | |
| else: | |
| raise InvalidSubmissionError( | |
| f"path outside `Spec/*.lean` or `Proof/*.lean` slot: {rel}" | |
| ) | |
| if srel in staged: | |
| raise InvalidSubmissionError( | |
| f"submission collides on staged path: {rel} vs {staged[srel]}" | |
| ) | |
| staged[srel] = rel | |
| if "Spec/Spec.lean" not in spec_files: | |
| raise InvalidSubmissionError("missing required `Spec/Spec.lean`") | |
| if proof_files: | |
| _validate_proof_slots(proof_files) | |
| def _validate_theory_audit_slots(payload: dict[str, bytes]) -> None: | |
| if not payload: | |
| raise InvalidSubmissionError("submission contains no theory files") | |
| protected = { | |
| "theory/bundle-manifest.json", | |
| *(f"theory/{p}" for p in scenarios.THEORY_CORE_MODULES), | |
| } | |
| for rel in sorted(payload): | |
| if rel in protected: | |
| raise InvalidSubmissionError( | |
| f"submission collides with defender asset: {rel}" | |
| ) | |
| if rel != "theory/Anneal.lean": | |
| _validate_lean_slot_path(rel, "theory/Anneal") | |
| def _validate_scenario_slots( | |
| spec: scenarios.ScenarioSpec, files: dict[str, bytes] | |
| ) -> LoadedSubmission: | |
| if not files: | |
| raise InvalidSubmissionError("submission contains no files") | |
| _check_case_colliding_paths(files.keys()) | |
| if "explanation.md" not in files: | |
| raise InvalidSubmissionError("missing required `explanation.md`") | |
| raw_exp = files["explanation.md"] | |
| if len(raw_exp) > MAX_EXPLANATION_BYTES: | |
| raise InvalidSubmissionError(f"`explanation.md` exceeds {MAX_EXPLANATION_BYTES} bytes") | |
| try: | |
| exp_text = raw_exp.decode("utf-8") | |
| except UnicodeDecodeError as exc: | |
| raise InvalidSubmissionError(f"`explanation.md` invalid UTF-8: {exc}") from exc | |
| if "\x00" in exp_text or not exp_text.strip(): | |
| raise InvalidSubmissionError("`explanation.md` must be non-empty valid UTF-8") | |
| if "manifest.json" in files: | |
| raw_man = files["manifest.json"] | |
| if len(raw_man) > MAX_WITNESS_BYTES: | |
| raise InvalidSubmissionError("manifest.json exceeds byte limit") | |
| _loads_strict_dict(raw_man.decode("utf-8"), label="manifest.json", exc_type=InvalidSubmissionError) | |
| payload = {k: v for k, v in files.items() if k not in ("manifest.json", "explanation.md")} | |
| if spec.kind == "PROOF_HACK": | |
| _validate_proof_slots(payload) | |
| elif spec.kind == "SPEC_PREFLIGHT_HACK": | |
| _validate_spec_preflight_slots(payload) | |
| elif spec.kind == "THEORY_AUDIT_HACK": | |
| _validate_theory_audit_slots(payload) | |
| else: | |
| raise OracleInfrastructureError(f"unsupported scenario kind {spec.kind!r}") | |
| return LoadedSubmission( | |
| files=payload, | |
| explanation_text=exp_text, | |
| explanation_sha256=anneal_ci_lib.sha256_bytes(raw_exp), | |
| ) | |
| def _lstat_or_raise(path: Path, *, context: str) -> os.stat_result: | |
| try: | |
| return os.lstat(path) | |
| except OSError as exc: | |
| raise OracleInfrastructureError(f"cannot inspect {context} `{path}`: {exc}") from exc | |
| def _require_walkable_dir(path: Path, *, context: str) -> os.stat_result: | |
| st = _lstat_or_raise(path, context=context) | |
| if stat.S_ISLNK(st.st_mode): | |
| raise _ArtifactSymlinkError(f"verify produced symlink directory `{path}`") | |
| if not stat.S_ISDIR(st.st_mode): | |
| raise OracleInfrastructureError(f"verify produced non-directory `{path}`") | |
| if (st.st_mode & 0o500) != 0o500: | |
| raise OracleInfrastructureError(f"unreadable output directory `{path}` (mode={stat.S_IMODE(st.st_mode):#o})") | |
| return st | |
| def _raise_tree_walk_error(exc: OSError) -> None: | |
| raise OracleInfrastructureError(f"unreadable output tree `{exc.filename or ''}`: {exc}") from exc | |
| def _collect_tree_regular_files(root: Path) -> set[str]: | |
| _require_walkable_dir(root, context="output directory") | |
| rels: set[str] = set() | |
| for cur_root, dirnames, filenames in os.walk( | |
| root, topdown=True, followlinks=False, onerror=_raise_tree_walk_error | |
| ): | |
| cur = Path(cur_root) | |
| for d in sorted(dirnames): | |
| _require_walkable_dir(cur / d, context="output directory") | |
| dirnames.sort() | |
| rels.update((cur / f).relative_to(root).as_posix() for f in sorted(filenames)) | |
| return rels | |
| def _collect_tree_dirs(root: Path, *, prefix: str) -> set[str]: | |
| _require_walkable_dir(root, context="output directory") | |
| dirs: set[str] = {prefix} | |
| for cur_root, dirnames, _ in os.walk( | |
| root, topdown=True, followlinks=False, onerror=_raise_tree_walk_error | |
| ): | |
| cur = Path(cur_root) | |
| for d in sorted(dirnames): | |
| _require_walkable_dir(cur / d, context="output directory") | |
| dirnames.sort() | |
| rel_cur = prefix if cur == root else f"{prefix}/{cur.relative_to(root).as_posix()}" | |
| dirs.update(f"{rel_cur}/{d}" for d in dirnames) | |
| return dirs | |
| def _check_strict_subdir( | |
| root: Path, expected: dict[str, _PinnedAssetSnapshot], strict_subdir: str, | |
| *, allowed_dirs: set[str] | frozenset[str] = frozenset(), | |
| ) -> list[dict[str, Any]]: | |
| tampered: list[dict[str, Any]] = [] | |
| sub_root = root if not strict_subdir else root / strict_subdir | |
| if not os.path.lexists(sub_root): | |
| return tampered | |
| try: | |
| sub_st = os.lstat(sub_root) | |
| if stat.S_ISLNK(sub_st.st_mode) or not stat.S_ISDIR(sub_st.st_mode): | |
| return [{"path": strict_subdir or ".", "reasons": ["unexpected symlink or non-dir"], "expected_sha256": None, "actual_sha256": None}] | |
| except OSError as exc: | |
| return [{"path": strict_subdir or ".", "reasons": [f"unreadable dir: {exc}"], "expected_sha256": None, "actual_sha256": None}] | |
| exp_sub = set(expected) if not strict_subdir else {r for r in expected if r.startswith(f"{strict_subdir}/")} | |
| exp_dirs: set[str] = ({strict_subdir} if strict_subdir else set()) | set(allowed_dirs) | |
| for rel in exp_sub: | |
| parts = rel.split("/")[:-1] | |
| start = 0 if not strict_subdir else 1 | |
| for idx in range(start, len(parts)): | |
| exp_dirs.add("/".join(parts[: idx + 1])) | |
| def _on_walk_err(exc: OSError) -> None: | |
| raw_p = Path(exc.filename) if exc.filename else sub_root | |
| try: | |
| if raw_p == sub_root: | |
| err_rel = strict_subdir or "." | |
| else: | |
| rel_s = raw_p.relative_to(sub_root).as_posix() | |
| err_rel = rel_s if not strict_subdir else f"{strict_subdir}/{rel_s}" | |
| except ValueError: | |
| err_rel = strict_subdir or "." | |
| tampered.append({"path": err_rel, "reasons": [f"dir unreadable: {exc}"], "expected_sha256": None, "actual_sha256": None}) | |
| for cur_root, dirnames, filenames in os.walk( | |
| sub_root, topdown=True, followlinks=False, onerror=_on_walk_err | |
| ): | |
| cur = Path(cur_root) | |
| if cur == sub_root: | |
| rel_cur = strict_subdir | |
| else: | |
| rel_sub = cur.relative_to(sub_root).as_posix() | |
| rel_cur = rel_sub if not strict_subdir else f"{strict_subdir}/{rel_sub}" | |
| keep_dirs: list[str] = [] | |
| for dname in sorted(dirnames): | |
| d_rel = dname if not rel_cur else f"{rel_cur}/{dname}" | |
| d_path = cur / dname | |
| try: | |
| dst = os.lstat(d_path) | |
| except OSError as exc: | |
| tampered.append({"path": d_rel, "reasons": [f"dir unreadable: {exc}"], "expected_sha256": None, "actual_sha256": None}) | |
| continue | |
| if stat.S_ISLNK(dst.st_mode) or not stat.S_ISDIR(dst.st_mode): | |
| tampered.append({"path": d_rel, "reasons": ["unexpected symlink or special dir"], "expected_sha256": None, "actual_sha256": None}) | |
| elif d_rel not in exp_dirs: | |
| tampered.append({"path": d_rel, "reasons": ["unexpected directory added"], "expected_sha256": None, "actual_sha256": None}) | |
| else: | |
| keep_dirs.append(dname) | |
| dirnames[:] = keep_dirs | |
| for fname in sorted(filenames): | |
| full = fname if not rel_cur else f"{rel_cur}/{fname}" | |
| if full not in exp_sub: | |
| try: | |
| esha: str | None = _inspect_regular_nofollow(root / full).sha256 | |
| except OracleInfrastructureError: | |
| esha = None | |
| tampered.append({"path": full, "reasons": ["unexpected file added"], "expected_sha256": None, "actual_sha256": esha}) | |
| return tampered | |
| def _verify_tree_hashes( | |
| root: Path, expected: dict[str, _PinnedAssetSnapshot], *, phase: str, | |
| strict_subdir: str | None = None, allowed_dirs: set[str] | frozenset[str] = frozenset(), | |
| exact_root: bool = False, | |
| ) -> None: | |
| """Detect defender-asset or metadata mutations with explicit phase.""" | |
| tampered: list[dict[str, Any]] = [] | |
| for rel, exp in sorted(expected.items()): | |
| cur, parent_err = root, None | |
| for part in Path(rel).parts[:-1]: | |
| cur = cur / part | |
| try: | |
| pst = os.lstat(cur) | |
| if stat.S_ISLNK(pst.st_mode) or not stat.S_ISDIR(pst.st_mode): | |
| parent_err = "symlink or non-dir parent" | |
| break | |
| except OSError as exc: | |
| parent_err = f"parent unreadable: {exc}" | |
| break | |
| if parent_err is not None: | |
| tampered.append({"path": rel, "reasons": [parent_err], "expected_sha256": exp.sha256, "actual_sha256": None}) | |
| continue | |
| try: | |
| act = _inspect_regular_nofollow(root / rel) | |
| except OracleInfrastructureError as exc: | |
| tampered.append({"path": rel, "reasons": [f"missing/non-regular: {exc}"], "expected_sha256": exp.sha256, "actual_sha256": None}) | |
| continue | |
| reasons = [ | |
| lbl for cond, lbl in ( | |
| (act.sha256 != exp.sha256, "checksum"), (act.dev != exp.dev or act.ino != exp.ino, "inode"), | |
| (act.mode != exp.mode, f"mode {exp.mode:#o}->{act.mode:#o}"), (act.nlink != exp.nlink, f"nlink {exp.nlink}->{act.nlink}"), | |
| (act.ctime_ns != exp.ctime_ns or act.mtime_ns != exp.mtime_ns, "timestamps"), | |
| ) if cond | |
| ] | |
| if reasons: | |
| tampered.append({"path": rel, "reasons": reasons, "expected_sha256": exp.sha256, "actual_sha256": act.sha256}) | |
| if exact_root: | |
| tampered.extend(_check_strict_subdir(root, expected, "", allowed_dirs=allowed_dirs)) | |
| elif strict_subdir: | |
| tampered.extend(_check_strict_subdir(root, expected, strict_subdir, allowed_dirs=allowed_dirs)) | |
| if tampered: | |
| msg = "; ".join(f"{a['path']} ({', '.join(a['reasons'])})" for a in tampered) | |
| raise DefenderTamperError(f"defender asset compromised during `{phase}`: {msg}", phase=phase, tampered_assets=tuple(tampered)) | |
| def _collect_private_roots( | |
| *, tmp_root: Path | None, anneal_root: Path, tools: dict[str, Path | None], | |
| submission_dir: Path | None, submission_tar: Path | None, | |
| ) -> tuple[tuple[str, str], ...]: | |
| raw_items: list[tuple[Path | str | None, str]] = [ | |
| (tmp_root, "<ephemeral>"), (anneal_root, "<anneal_root>"), (submission_tar, "<submission_tar>"), | |
| *((v, "<sysroot>" if k == "sysroot" else f"<tool:{k}>") for k, v in sorted(tools.items())), | |
| *((os.environ.get(k, "").strip(), tag) for k, tag in (("CARGO_TARGET_DIR", "<cargo_target>"), ("CARGO_HOME", "<cargo_home>"), ("RUSTUP_HOME", "<rustup_home>"))), | |
| ] | |
| if (anneal_root.parent / ".git").exists(): | |
| raw_items.append((anneal_root.parent, "<repo_root>")) | |
| if submission_dir is not None and submission_dir.resolve() not in (Path("/"), Path("/tmp"), Path("/var/tmp"), Path("/home")): | |
| raw_items.append((submission_dir, "<submission_dir>")) | |
| try: | |
| raw_items.append((Path.home(), "<home>")) | |
| except (RuntimeError, OSError): | |
| pass | |
| pairs: dict[str, str] = {} | |
| for val, tag in raw_items: | |
| if val: | |
| try: | |
| p = Path(val) | |
| cands = (p, p.resolve()) if p.is_absolute() else (p.resolve(),) | |
| for cand_p in cands: | |
| cand = str(cand_p).rstrip("/") | |
| if cand and cand not in ("/", "/tmp", "/var/tmp", "/home"): | |
| pairs.setdefault(cand, tag) | |
| except (OSError, ValueError, TypeError): | |
| pass | |
| return tuple(sorted(pairs.items(), key=lambda kv: (-len(kv[0]), kv[0]))) | |
| def _sanitize_obj(val: Any, *, private_roots: tuple[tuple[str, str], ...] = ()) -> Any: | |
| if isinstance(val, str): | |
| for prefix, tag in private_roots: | |
| val = val.replace(prefix, tag) | |
| return re.sub(r"/tmp/anneal-[A-Za-z0-9_.-]+", "<ephemeral>", val) | |
| if isinstance(val, list): | |
| return [_sanitize_obj(v, private_roots=private_roots) for v in val] | |
| if isinstance(val, dict): | |
| return {k: _sanitize_obj(v, private_roots=private_roots) for k, v in val.items()} | |
| return val | |
| def _sanitize_snippet(text: str | None, *, private_roots: tuple[tuple[str, str], ...] = (), limit: int = 2000) -> str | None: | |
| if not text or not (cleaned := _sanitize_obj(text.strip(), private_roots=private_roots)): | |
| return None | |
| return (cleaned[:limit] + "...[truncated]") if len(cleaned) > limit else cleaned | |
| def _stage_verify_workspace( | |
| work: Path, spec: scenarios.ScenarioSpec, submission: LoadedSubmission | |
| ) -> tuple[Path, dict[str, _PinnedAssetSnapshot]]: | |
| work.mkdir(parents=True, exist_ok=True) | |
| work_resolved = work.resolve() | |
| defender_rels = list(spec.defender_files) | |
| for rel, content in spec.defender_files.items(): | |
| _write_new_regular_file_excl(work / rel, content.encode("utf-8")) | |
| proof_entries: list[dict[str, str]] = ( | |
| [{"module": "Spec", "path": "Spec.lean", "role": "specification"}] | |
| if spec.kind == "PROOF_HACK" | |
| else [] | |
| ) | |
| if spec.kind == "SPEC_PREFLIGHT_HACK" and "Proof/Proof.lean" not in submission.files: | |
| _write_new_regular_file_excl( | |
| work / "Proof.lean", | |
| scenarios.DEFAULT_SPEC_PREFLIGHT_PROOF.encode("utf-8"), | |
| ) | |
| defender_rels.append("Proof.lean") | |
| proof_entries.append({"module": "Proof", "path": "Proof.lean", "role": "proof"}) | |
| defender_set = set(defender_rels) | |
| attacker_stage: list[tuple[Path, bytes]] = [] | |
| for rel, data in sorted(submission.files.items()): | |
| if rel.startswith("Spec/"): | |
| mod = "Spec" if rel == "Spec/Spec.lean" else f"Spec.{_validate_lean_slot_path(rel, 'Spec')}" | |
| staged_rel = "Spec.lean" if rel == "Spec/Spec.lean" else rel | |
| role = "specification" | |
| else: | |
| mod = _validate_lean_slot_path(rel, "Proof") | |
| staged_rel = rel[len("Proof/") :] | |
| role = "proof" | |
| if staged_rel in defender_set or staged_rel == "request.json": | |
| raise InvalidSubmissionError(f"submission collides with defender asset: {rel}") | |
| dest = (work / staged_rel).resolve() | |
| if not dest.is_relative_to(work_resolved) or dest == work_resolved: | |
| raise InvalidSubmissionError(f"staged path escapes workspace: {rel}") | |
| proof_entries.append({"module": mod, "path": staged_rel, "role": role}) | |
| attacker_stage.append((dest, data)) | |
| proof_entries.sort(key=lambda item: item["module"]) | |
| scope_obj = ( | |
| {"kind": "crate"} | |
| if spec.scope_kind == "crate" | |
| else {"kind": spec.scope_kind, "roots": list(spec.scope_roots)} | |
| ) | |
| req_obj = { | |
| "schema_version": 1, | |
| "compilation": { | |
| "source_root": ".", | |
| "crate_root": spec.crate_root, | |
| "crate_name": spec.crate_name, | |
| "edition": "2024", | |
| "target": VERIFIED_RUST_TARGET, | |
| "source_files": ["src/lib.rs"], | |
| }, | |
| "scope": scope_obj, | |
| "proof": { | |
| "source_root": ".", | |
| "specification": spec.spec_decl, | |
| "theorem": spec.proof_theorem, | |
| "sources": proof_entries, | |
| }, | |
| } | |
| _write_new_regular_file_excl( | |
| work / "request.json", (json.dumps(req_obj, indent=2) + "\n").encode("utf-8") | |
| ) | |
| pinned = { | |
| rel: _inspect_regular_nofollow(work / rel) | |
| for rel in sorted([*defender_rels, "request.json"]) | |
| } | |
| for dest, data in attacker_stage: | |
| _write_new_regular_file_excl(dest, data) | |
| _verify_tree_hashes(work, pinned, phase="staging", strict_subdir="src") | |
| return work / "request.json", pinned | |
| def _stage_theory_audit_workspace( | |
| work: Path, root: Path, submission: LoadedSubmission | |
| ) -> tuple[dict[str, _PinnedAssetSnapshot], set[str], set[str]]: | |
| """Stage defender `trusted/` + `MirWp` core closure alongside theory.""" | |
| work.mkdir(parents=True, exist_ok=True) | |
| for sub_dir in (root / "trusted", root / "trusted/lean", root / "trusted/audit", root / "theory"): | |
| if sub_dir.is_symlink() or not sub_dir.is_dir(): | |
| raise OracleInfrastructureError(f"missing or symlinked defender directory: `{sub_dir.relative_to(root).as_posix()}`") | |
| trusted_lean = root / "trusted/lean" | |
| copy_rels: list[str] = [ | |
| f"trusted/lean/{rel}" for rel in sorted(_collect_tree_regular_files(trusted_lean)) | |
| ] | |
| copy_rels.extend(_THEORY_AUDIT_TRUSTED_FILES) | |
| copy_rels.append("theory/bundle-manifest.json") | |
| copy_rels.extend(f"theory/{p}" for p in scenarios.THEORY_CORE_MODULES) | |
| defender_theory_rels = { | |
| "bundle-manifest.json", | |
| *scenarios.THEORY_CORE_MODULES, | |
| } | |
| for rel in copy_rels: | |
| for parent_rel in Path(rel).parents: | |
| if parent_rel != Path(".") and (root / parent_rel).is_symlink(): | |
| raise OracleInfrastructureError(f"symlink in defender dir: {parent_rel.as_posix()}") | |
| src = root / rel | |
| if src.is_symlink(): | |
| raise OracleInfrastructureError(f"symlink in defender asset: {rel}") | |
| data = _read_regular_file_nofollow(src, exc_type=OracleInfrastructureError) | |
| try: | |
| _write_new_regular_file_excl(work / rel, data) | |
| except InvalidSubmissionError as exc: | |
| raise OracleInfrastructureError(str(exc)) from exc | |
| pinned = {rel: _inspect_regular_nofollow(work / rel) for rel in sorted(copy_rels)} | |
| submitted_theory_rels = {rel[len("theory/") :] for rel in submission.files} | |
| work_resolved = work.resolve() | |
| for rel, data in sorted(submission.files.items()): | |
| if rel in pinned: | |
| raise InvalidSubmissionError(f"submission collides with defender asset: {rel}") | |
| dest = (work / rel).resolve() | |
| if not dest.is_relative_to(work_resolved) or dest == work_resolved: | |
| raise InvalidSubmissionError(f"staged path escapes workspace: {rel}") | |
| _write_new_regular_file_excl(dest, data) | |
| _verify_tree_hashes(work, pinned, phase="staging", strict_subdir="trusted") | |
| _verify_theory_tree_exact( | |
| work, defender_theory_rels | submitted_theory_rels, phase="staging" | |
| ) | |
| return pinned, defender_theory_rels, submitted_theory_rels | |
| def _verify_theory_tree_exact( | |
| work: Path, expected_rels: set[str], *, phase: str | |
| ) -> None: | |
| theory_dir = work / "theory" | |
| if theory_dir.is_symlink() or not theory_dir.is_dir(): | |
| raise DefenderTamperError( | |
| f"`theory/` removed during `{phase}`", | |
| phase=phase, | |
| tampered_assets=({"path": "theory", "reasons": ["missing"], "expected_sha256": None, "actual_sha256": None},), | |
| ) | |
| try: | |
| actual_rels = _collect_tree_regular_files(theory_dir) | |
| except OracleInfrastructureError as exc: | |
| raise DefenderTamperError( | |
| f"unreadable or symlinked entry inside `theory/` during `{phase}`: {exc}", | |
| phase=phase, | |
| tampered_assets=({"path": "theory", "reasons": [str(exc)], "expected_sha256": None, "actual_sha256": None},), | |
| ) from exc | |
| if extras := sorted(actual_rels - expected_rels): | |
| tampered = tuple( | |
| {"path": f"theory/{rel}", "reasons": ["unexpected file added"], "expected_sha256": None, "actual_sha256": None} | |
| for rel in extras | |
| ) | |
| raise DefenderTamperError( | |
| f"unexpected file added to `theory/` during `{phase}`", | |
| phase=phase, | |
| tampered_assets=tampered, | |
| ) | |
| def _validate_exit1_failure_receipt(receipt: dict[str, Any]) -> None: | |
| """Confirm exit-1 receipt is valid Receipt v3 proof/policy rejection.""" | |
| if not isinstance(receipt, dict): | |
| raise OracleInfrastructureError("invalid exit-1 failure receipt: not a JSON object") | |
| failures: list[str] = [] | |
| if not anneal_ci_lib.is_exact_int(receipt.get("schema_version"), 3): | |
| failures.append(f"schema_version={receipt.get('schema_version')!r}") | |
| if "tainted" in receipt: | |
| failures.append("unexpected legacy tainted key") | |
| if "sorry_declarations" in receipt: | |
| failures.append(f"sorry_declarations={receipt.get('sorry_declarations')!r}") | |
| if receipt.get("taint_reasons") != []: | |
| failures.append(f"taint_reasons={receipt.get('taint_reasons')!r}") | |
| deferred = receipt.get("deferred", []) | |
| if not isinstance(deferred, list) or not all(isinstance(d, str) for d in deferred): | |
| failures.append(f"deferred={deferred!r}") | |
| elif "hostile Lean elaborator effects" in deferred: | |
| failures.append("hostile Lean elaborator effects deferred") | |
| if failures: | |
| raise OracleInfrastructureError(f"invalid exit-1 failure receipt: {'; '.join(failures)}") | |
| status = receipt.get("status") | |
| phase = receipt.get("phase") | |
| sandbox = receipt.get("elaboration_sandbox") | |
| reason = receipt.get("reason") | |
| if status == "proof_failed": | |
| if phase not in ("audit", "elaboration", "target_audit"): | |
| raise OracleInfrastructureError(f"unexpected `proof_failed` phase={phase!r}") | |
| if sandbox not in anneal_ci_lib.VALID_SANDBOXES: | |
| raise OracleInfrastructureError(f"invalid `proof_failed` sandbox={sandbox!r}") | |
| if reason is not None and not (phase == "audit" and reason in ("heartbeat_limit_exceeded", "recursion_depth_exceeded")): | |
| raise OracleInfrastructureError(f"unexpected `proof_failed` reason={reason!r}") | |
| return | |
| if status == "unsupported" and phase == "proof": | |
| if sandbox is not None and sandbox not in anneal_ci_lib.VALID_SANDBOXES: | |
| raise OracleInfrastructureError(f"invalid `unsupported` sandbox={sandbox!r}") | |
| if reason is not None: | |
| raise OracleInfrastructureError(f"unexpected `unsupported` reason={reason!r}") | |
| return | |
| raise OracleInfrastructureError(f"non-proof exit-1 failure ({status}/{phase}): {receipt.get('detail', '')}") | |
| def _exit0_envelope_failures( | |
| receipt: dict[str, Any], *, returncode: int, expected_status: str = "selected_unit_verified" | |
| ) -> list[str]: | |
| """Return Receipt v3 envelope and audit structure failures on exit 0.""" | |
| failures: list[str] = [] | |
| if returncode != 0: | |
| failures.append(f"exit={returncode}") | |
| if not anneal_ci_lib.is_exact_int(receipt.get("schema_version"), 3): | |
| failures.append(f"schema_version={receipt.get('schema_version')!r}") | |
| if receipt.get("status") not in (expected_status, f"tainted_{expected_status}"): | |
| failures.append(f"status={receipt.get('status')!r}") | |
| if "tainted" in receipt: | |
| failures.append("unexpected legacy tainted key") | |
| if "sorry_declarations" in receipt: | |
| sd = receipt.get("sorry_declarations") | |
| if not isinstance(sd, list) or not all(isinstance(item, str) for item in sd): | |
| failures.append(f"sorry_declarations={sd!r}") | |
| for list_key in ("taint_reasons", "deferred"): | |
| val = receipt.get(list_key, [] if list_key == "deferred" else None) | |
| if not isinstance(val, list) or not all(isinstance(item, str) for item in val): | |
| failures.append(f"{list_key}={receipt.get(list_key)!r}") | |
| if receipt.get("elaboration_sandbox") not in (*anneal_ci_lib.VALID_SANDBOXES, "none"): | |
| failures.append(f"elaboration_sandbox={receipt.get('elaboration_sandbox')!r}") | |
| audit = receipt.get("audit") | |
| if not isinstance(audit, dict): | |
| failures.append("missing audit object") | |
| else: | |
| for bkey in ("replay", "exactType"): | |
| if not isinstance(audit.get(bkey), bool): | |
| failures.append(f"audit.{bkey}={audit.get(bkey)!r}") | |
| if not anneal_ci_lib.is_nonneg_int(audit.get("checkedAlternateProofs")): | |
| failures.append(f"checkedAlternateProofs={audit.get('checkedAlternateProofs')!r}") | |
| if not isinstance(audit.get("sorryDeclarations"), list): | |
| failures.append(f"audit.sorryDeclarations={audit.get('sorryDeclarations')!r}") | |
| ax = audit.get("axioms") | |
| if not isinstance(ax, list) or not all(isinstance(a, str) for a in ax): | |
| failures.append(f"audit.axioms={ax!r}") | |
| return failures | |
| def _strict_verify_anomalies( | |
| receipt: dict[str, Any], *, expected_status: str = "selected_unit_verified" | |
| ) -> list[str]: | |
| anomalies: list[str] = [] | |
| if receipt.get("status") != expected_status: | |
| anomalies.append(f"status={receipt.get('status')!r}") | |
| if tr := receipt.get("taint_reasons") or []: | |
| anomalies.append(f"taint_reasons={tr!r}") | |
| if sd := receipt.get("sorry_declarations") or []: | |
| anomalies.append(f"sorry_declarations={sd!r}") | |
| if receipt.get("elaboration_sandbox") == "none": | |
| anomalies.append("elaboration_sandbox=none") | |
| if isinstance(def_list := receipt.get("deferred"), list): | |
| if extra_def := [d for d in def_list if isinstance(d, str) and d not in dedup.BASELINE_DEFERRED]: | |
| anomalies.append(f"unexpected deferred={extra_def!r}") | |
| audit = receipt.get("audit") | |
| if isinstance(audit, dict): | |
| for k, expected in (("replay", True), ("exactType", True)): | |
| if audit.get(k) is not expected: | |
| anomalies.append(f"audit.{k}={audit.get(k)!r}") | |
| cap = audit.get("checkedAlternateProofs") | |
| if not anneal_ci_lib.is_nonneg_int(cap) or cap != 0: | |
| anomalies.append(f"checkedAlternateProofs={cap!r}") | |
| if audit.get("sorryDeclarations") != []: | |
| anomalies.append(f"audit.sorryDeclarations={audit.get('sorryDeclarations')!r}") | |
| ax = audit.get("axioms") | |
| if isinstance(ax, list): | |
| if bad_ax := sorted({a for a in ax if isinstance(a, str)} - dedup.ALLOWED_STANDARD_AXIOMS): | |
| anomalies.append(f"disallowed audit.axioms={bad_ax!r}") | |
| return anomalies | |
| def _run_inspect_gate( | |
| *, cli: Path, receipt_path: Path, artifacts_dir: Path, env: dict[str, str], timeout: int, inspect_runner: Callable[..., Any] | None | |
| ) -> tuple[bool, list[str], dict[str, Any] | None]: | |
| cmd = [ | |
| str(cli), "inspect", "--format", "json", "--require-untainted", | |
| "--require-containment", "--verify-artifacts", str(artifacts_dir), "--require-exact-artifacts", str(receipt_path), | |
| ] | |
| proc = inspect_runner(cmd, env=env, timeout=timeout) if inspect_runner is not None else _run_bounded_subprocess(cmd, env=env, timeout=timeout) | |
| if proc.returncode < 0: | |
| raise OracleInfrastructureError(f"inspect killed by signal {-proc.returncode}") | |
| if proc.returncode != 0: | |
| parsed: dict[str, Any] | None = None | |
| if proc.returncode == 1 and proc.stdout.strip(): | |
| try: | |
| parsed = _loads_strict_dict(proc.stdout, label="inspect failure JSON", exc_type=OracleInfrastructureError) | |
| except OracleInfrastructureError: | |
| parsed = None | |
| return False, [f"inspect exit={proc.returncode}: {(proc.stderr or proc.stdout).strip()[:240]}"], parsed | |
| inspected = _loads_strict_dict(proc.stdout, label="inspect JSON", exc_type=OracleInfrastructureError) | |
| failures = [f"inspect tainted={inspected.get('tainted')!r}"] if inspected.get("tainted") is not False else [] | |
| failures.extend(f"inspect {f}={inspected.get(f)!r}" for f in ("policy_violations", "invariant_violations", "unrecognized_fields") if inspected.get(f) != []) | |
| art = inspected.get("artifact_verification") | |
| if not isinstance(art, dict) or art.get("exact_match") is not True: | |
| failures.append(f"inspect artifact_verification={art!r}") | |
| return len(failures) == 0, failures, inspected | |
| def _inspect_taint_or_policy_anomalies(ir: dict[str, Any] | None) -> bool: | |
| """Return True only when `inspect` reports taint or non-artifact policy faults.""" | |
| if not isinstance(ir, dict): | |
| return False | |
| if ir.get("tainted") is not False or bool(ir.get("invariant_violations")): | |
| return True | |
| art = ir.get("artifact_verification") | |
| art_failures = ( | |
| {x for x in art.get("failures", []) if isinstance(x, str)} | |
| if isinstance(art, dict) and isinstance(art.get("failures"), list) | |
| else set() | |
| ) | |
| has_unrec = bool(ir.get("unrecognized_fields")) | |
| return any( | |
| isinstance(v, str) | |
| and v not in art_failures | |
| and not (has_unrec and v.startswith("unrecognized receipt field(s) ")) | |
| for v in (ir.get("policy_violations") or []) | |
| ) | |
| def _load_capture_manifest(artifacts_dir: Path) -> dict[str, Any] | None: | |
| try: | |
| cap_dir = artifacts_dir / "capture" | |
| cap_path = cap_dir / "capture.json" | |
| if artifacts_dir.is_symlink() or cap_dir.is_symlink() or cap_path.is_symlink(): | |
| return None | |
| raw = _read_regular_file_nofollow(cap_path, max_bytes=_MAX_CAPTURE_BYTES, exc_type=RuntimeError) | |
| return _loads_strict_dict(raw.decode("utf-8"), label="capture.json", exc_type=RuntimeError) | |
| except Exception: | |
| return None | |
| _SORRY_CONTROL_PROOF = ( | |
| b"module\nprelude\npublic import Expected\n" | |
| b"namespace Proof\npublic theorem verify : Expected.claim := by sorry\nend Proof\n" | |
| ) | |
| def _tool_ro_paths(*, root: Path, tools: dict[str, Path | None]) -> list[Path]: | |
| extra_prot = _repo_protected_paths(root) | |
| paths: list[Path] = [] | |
| exe = Path(sys.executable) | |
| for cand in (exe, exe.resolve()): | |
| if not _is_broad_protected_root(cand, extra_protected=extra_prot): | |
| paths.append(cand) | |
| prefix = Path(sys.prefix) | |
| if sys.prefix != sys.base_prefix and not _is_broad_protected_root(prefix, extra_protected=extra_prot): | |
| paths.append(prefix) | |
| for name, val in tools.items(): | |
| if val is None: | |
| continue | |
| rv = val.resolve() | |
| if name in ("sysroot", "miri_sysroot"): | |
| paths.append(rv) | |
| elif name == "lean": | |
| paths.append(val) | |
| if rv != val: | |
| paths.append(rv) | |
| if rv.name == "lean" and rv.parent.name == "bin": | |
| tc_dir = rv.parent.parent | |
| if not _is_broad_protected_root(tc_dir, extra_protected=extra_prot): | |
| paths.append(tc_dir) | |
| elif (lean_lib := tc_dir / "lib/lean").is_dir() and not _is_broad_protected_root(lean_lib, extra_protected=extra_prot): | |
| paths.append(lean_lib) | |
| else: | |
| paths.append(val) | |
| if rv != val: | |
| paths.append(rv) | |
| return paths | |
| def _make_sandboxed_runner( | |
| *, | |
| ro_paths: list[Path], | |
| rw_paths: list[Path], | |
| default_cwd: Path, | |
| use_outer_bwrap: bool, | |
| protected_paths: Iterable[Path] = (), | |
| ) -> Callable[..., subprocess.CompletedProcess[str]]: | |
| prot = tuple(protected_paths) | |
| def _run(cmd: list[str], *, cwd: Path | None = None, env: dict[str, str] | None = None, timeout: float = 60.0) -> subprocess.CompletedProcess[str]: | |
| run_cwd = cwd or default_cwd | |
| run_cmd = ( | |
| _build_bwrap_cmd( | |
| list(cmd), ro_paths=ro_paths, rw_paths=rw_paths, chdir=run_cwd, | |
| env=dict(env or {}), require_bwrap=True, protected_paths=prot, | |
| ) | |
| if use_outer_bwrap | |
| else list(cmd) | |
| ) | |
| return _run_bounded_subprocess(run_cmd, cwd=run_cwd, env=env, timeout=max(1, int(math.ceil(timeout)))) | |
| return _run | |
| def _verify_defender_sorry_baseline( | |
| *, tmp_root: Path, spec: scenarios.ScenarioSpec, cli_path: Path, capture: Path | None, | |
| sysroot: Path | None, lean: Path | None, env: dict[str, str], timeout: int, v_runner: Callable[..., Any], | |
| ) -> None: | |
| """Confirm exit-1 `proof_failed` traces to attacker proof rather than broken defender fixtures.""" | |
| ctrl_root = tmp_root / f"_ctrl_{secrets.token_hex(8)}" | |
| try: | |
| ctrl_root.mkdir(mode=0o700, exist_ok=False) | |
| except OSError as exc: | |
| raise OracleInfrastructureError(f"cannot allocate defender baseline control dir: {exc}") from exc | |
| ctrl_work, ctrl_art = ctrl_root / "workspace", ctrl_root / "artifacts" | |
| ctrl_receipt, ctrl_ocache = ctrl_root / "verify-receipt.json", ctrl_root / "olean-cache" | |
| try: | |
| ctrl_ocache.mkdir(mode=0o700, exist_ok=False) | |
| ctrl_def = dict(spec.defender_files) | |
| ctrl_def.setdefault("src/lib.rs", _CLEAN_STANDIN_RS) | |
| ctrl_def.setdefault("Spec.lean", _CLEAN_STANDIN_SPEC) | |
| ctrl_spec = scenarios.ScenarioSpec( | |
| scenario_id=f"{spec.scenario_id}_ctrl", | |
| kind="PROOF_HACK" if spec.kind == "SPEC_PREFLIGHT_HACK" else spec.kind, | |
| title=spec.title, scope_kind=spec.scope_kind, allowed_paths=spec.allowed_paths, | |
| defender_files=ctrl_def, crate_name=spec.crate_name, crate_root=spec.crate_root, | |
| scope_roots=spec.scope_roots, spec_decl=spec.spec_decl, | |
| proof_theorem=spec.proof_theorem, context=spec.context, | |
| ) | |
| ctrl_sub = LoadedSubmission( | |
| files={"Proof/Proof.lean": _SORRY_CONTROL_PROOF}, | |
| explanation_text="# Control\n", | |
| explanation_sha256=anneal_ci_lib.sha256_bytes(b"# Control\n"), | |
| ) | |
| ctrl_req, ctrl_pinned = _stage_verify_workspace(ctrl_work, ctrl_spec, ctrl_sub) | |
| except (InvalidSubmissionError, OSError) as exc: | |
| shutil.rmtree(ctrl_root, ignore_errors=True) | |
| raise OracleInfrastructureError(f"defender baseline control setup failed: {exc}") from exc | |
| try: | |
| try: | |
| ctrl_proc, ctrl_rcpt = anneal_ci_lib.run_cargo_anneal_verify( | |
| cli=cli_path, request_path=ctrl_req, cwd=ctrl_work, capture=capture, sysroot=sysroot, lean=lean, | |
| artifacts_dir=ctrl_art, extra_flags=["--receipt-out", str(ctrl_receipt), "--olean-cache-dir", str(ctrl_ocache)], | |
| env=env, timeout=float(timeout), runner=v_runner, label=ctrl_spec.scenario_id, | |
| ) | |
| except (subprocess.TimeoutExpired, RuntimeError, OSError) as exc: | |
| raise OracleInfrastructureError(f"defender baseline control failed: {exc}") from exc | |
| finally: | |
| _verify_tree_hashes(ctrl_work, ctrl_pinned, phase="verify", strict_subdir="src") | |
| finally: | |
| shutil.rmtree(ctrl_root, ignore_errors=True) | |
| if ctrl_proc.returncode != 1 or not isinstance(ctrl_rcpt, dict): | |
| raise OracleInfrastructureError(f"defender baseline control returned unexpected exit={ctrl_proc.returncode}") | |
| _validate_exit1_failure_receipt(ctrl_rcpt) | |
| if ctrl_rcpt.get("status") != "proof_failed" or ctrl_rcpt.get("phase") != "audit": | |
| raise OracleInfrastructureError( | |
| f"defender baseline control failed before audit ({ctrl_rcpt.get('status')}/{ctrl_rcpt.get('phase')})" | |
| ) | |
| if "sorryAx" not in str(ctrl_rcpt.get("detail") or ""): | |
| raise OracleInfrastructureError( | |
| f"defender baseline control did not fail on `sorryAx`: {ctrl_rcpt.get('detail', '')}"[:240] | |
| ) | |
| def _run_verify_and_inspect( | |
| *, tmp_root: Path, work: Path, pinned: dict[str, _PinnedAssetSnapshot], | |
| pinned_bins: dict[str, tuple[Path, Path, _PinnedAssetSnapshot]], | |
| request_path: Path, artifacts_dir: Path, receipt_path: Path, olean_cache: Path, | |
| spec: scenarios.ScenarioSpec, tools: dict[str, Path | None], env: dict[str, str], timeout: int, | |
| verify_runner: Callable[..., Any] | None, inspect_runner: Callable[..., Any] | None, | |
| state: dict[str, Any] | None = None, root: Path | None = None, isolated_host: bool = False, | |
| ) -> tuple[bool, bool, list[str], dict[str, Any] | None, dict[str, Any] | None, list[str]]: | |
| cli, capture, sysroot, lean = tools.get("cli"), tools.get("capture"), tools.get("sysroot"), tools.get("lean") | |
| if verify_runner is None: | |
| if missing := [n for n, p in (("cargo-anneal", cli), ("anneal-rustc-capture", capture), ("sysroot", sysroot), ("lean", lean)) if p is None]: | |
| raise OracleInfrastructureError(f"missing verification tools: {', '.join(missing)}") | |
| cli_path = cli or Path("cargo-anneal") | |
| eff_root = (root or Path(__file__).resolve().parents[2]).resolve() | |
| use_outer_bwrap = False | |
| if verify_runner is None or inspect_runner is None: | |
| use_outer_bwrap = _resolve_outer_sandbox(tmp_root=tmp_root, env=env, timeout=timeout, isolated_host=isolated_host) | |
| sb_runner = _make_sandboxed_runner( | |
| ro_paths=_tool_ro_paths(root=eff_root, tools=tools), | |
| rw_paths=[tmp_root], default_cwd=tmp_root, use_outer_bwrap=use_outer_bwrap, | |
| protected_paths=_repo_protected_paths(eff_root), | |
| ) | |
| v_runner = verify_runner or sb_runner | |
| i_runner = inspect_runner or sb_runner | |
| exp_status = "crate_verified" if spec.scope_kind == "crate" else "selected_unit_verified" | |
| extra_flags = ["--receipt-out", str(receipt_path), "--olean-cache-dir", str(olean_cache)] | |
| if spec.kind == "SPEC_PREFLIGHT_HACK": | |
| extra_flags.append("--export-lean-lib") | |
| verify_cmd = anneal_ci_lib.build_cargo_anneal_verify_cmd( | |
| cli=cli_path, request_path=request_path, capture=capture, sysroot=sysroot, lean=lean, | |
| artifacts_dir=artifacts_dir, extra_flags=extra_flags, | |
| ) | |
| verify_env = anneal_ci_lib.strip_actions_env(env, include_oidc=True) | |
| proc: Any = None | |
| receipt: dict[str, Any] | None = None | |
| stdout_err: str | None = None | |
| try: | |
| try: | |
| proc = v_runner(verify_cmd, cwd=work, env=verify_env, timeout=float(timeout)) | |
| if state is not None: | |
| state["v_exit_code"] = proc.returncode | |
| state["cap"] = _load_capture_manifest(artifacts_dir) | |
| try: | |
| receipt = _loads_strict_dict(proc.stdout, label="verify stdout receipt", exc_type=OracleInfrastructureError) | |
| except OracleInfrastructureError as exc: | |
| stdout_err = str(exc) | |
| if state is not None: | |
| state["v_receipt"] = receipt | |
| if proc.returncode == 0 and isinstance(receipt, dict): | |
| env_f = _exit0_envelope_failures(receipt, returncode=0, expected_status=exp_status) | |
| state["v_ok"] = (not env_f and not _strict_verify_anomalies(receipt, expected_status=exp_status)) | |
| except (subprocess.TimeoutExpired, RuntimeError, OSError) as exc: | |
| raise OracleInfrastructureError(f"verify failure: {exc}") from exc | |
| finally: | |
| _verify_tree_hashes(work, pinned, phase="verify", strict_subdir="src") | |
| _verify_pinned_tools(pinned_bins, phase="verify") | |
| if proc.returncode < 0: | |
| raise OracleInfrastructureError(f"verify killed by signal {-proc.returncode}") | |
| if stdout_err is not None and proc.returncode != 0: | |
| raise OracleInfrastructureError(f"verify invalid stdout receipt (exit={proc.returncode}): {stdout_err}") | |
| if proc.returncode not in (0, 1) or (proc.returncode != 0 and isinstance(receipt, dict) and receipt.get("status") == "tool_failed"): | |
| detail = receipt.get("detail", "") if isinstance(receipt, dict) else "" | |
| raise OracleInfrastructureError(f"verify operational failure (exit={proc.returncode}): {detail}") | |
| if proc.returncode == 1: | |
| assert receipt is not None | |
| _validate_exit1_failure_receipt(receipt) | |
| if receipt.get("status") == "proof_failed": | |
| _verify_defender_sorry_baseline( | |
| tmp_root=tmp_root, spec=spec, cli_path=cli_path, capture=capture, | |
| sysroot=sysroot, lean=lean, env=env, timeout=timeout, v_runner=v_runner, | |
| ) | |
| return False, False, [], receipt, None, [f"exit=1 ({receipt.get('status')}/{receipt.get('phase')}): {receipt.get('detail', '')}"[:240]] | |
| dedup_extra: list[str] = [] | |
| anomalies: list[str] = [] | |
| if stdout_err is not None: | |
| dedup_extra.append("verify:stdout_invalid") | |
| anomalies.append(f"verify exited 0 with invalid stdout: {stdout_err}") | |
| can_run_inspect = True | |
| skip_reason: str | None = None | |
| if receipt_path.is_symlink(): | |
| can_run_inspect = False | |
| dedup_extra.append("verify:receipt_out_symlink") | |
| anomalies.append("verify wrote symlink `--receipt-out`") | |
| elif not receipt_path.is_file(): | |
| can_run_inspect = False | |
| dedup_extra.append("verify:receipt_out_missing") | |
| anomalies.append("verify exited 0 without `--receipt-out` file") | |
| else: | |
| try: | |
| raw_p = _read_regular_file_nofollow(receipt_path, max_bytes=_MAX_CAPTURE_BYTES, exc_type=OracleInfrastructureError) | |
| parsed_out = _loads_strict_dict(raw_p.decode("utf-8"), label="--receipt-out", exc_type=OracleInfrastructureError) | |
| if receipt is not None and parsed_out != receipt: | |
| dedup_extra.append("verify:receipt_out_mismatch") | |
| anomalies.append("`--receipt-out` differs from stdout receipt") | |
| except (OracleInfrastructureError, UnicodeDecodeError) as exc: | |
| can_run_inspect = False | |
| dedup_extra.append("verify:receipt_out_invalid") | |
| anomalies.append(f"invalid `--receipt-out`: {exc}") | |
| if not can_run_inspect: | |
| skip_reason = "inspect skipped: invalid or missing `--receipt-out`" | |
| if isinstance(receipt, dict): | |
| for ef in _exit0_envelope_failures(receipt, returncode=proc.returncode, expected_status=exp_status): | |
| dedup_extra.append(f"verify_envelope:{ef}") | |
| anomalies.append(f"exit-0 envelope:{ef}") | |
| strict_anoms = _strict_verify_anomalies(receipt, expected_status=exp_status) | |
| anomalies.extend(strict_anoms) | |
| else: | |
| strict_anoms = [] | |
| receipt_rel = receipt_path.relative_to(tmp_root).as_posix() | |
| inspect_pinned: dict[str, _PinnedAssetSnapshot] = ( | |
| {receipt_rel: _inspect_regular_nofollow(receipt_path)} if can_run_inspect else {} | |
| ) | |
| artifact_dirs: set[str] = set() | |
| artifacts_clean = True | |
| try: | |
| try: | |
| art_st = os.lstat(artifacts_dir) | |
| except FileNotFoundError: | |
| art_st = None | |
| except OSError as exc: | |
| raise OracleInfrastructureError(f"cannot inspect `artifacts`: {exc}") from exc | |
| if art_st is not None: | |
| if stat.S_ISLNK(art_st.st_mode): | |
| raise _ArtifactSymlinkError("verify produced symlink `artifacts` directory") | |
| if not stat.S_ISDIR(art_st.st_mode): | |
| raise OracleInfrastructureError("verify produced non-directory `artifacts` path") | |
| art_rels = sorted( | |
| (artifacts_dir / r).relative_to(tmp_root).as_posix() | |
| for r in _collect_tree_regular_files(artifacts_dir) | |
| ) | |
| artifact_dirs = _collect_tree_dirs(artifacts_dir, prefix="artifacts") | |
| art_pinned: dict[str, _PinnedAssetSnapshot] = {} | |
| for rel in art_rels: | |
| ap = tmp_root / rel | |
| fst = _lstat_or_raise(ap, context="output file") | |
| if stat.S_ISLNK(fst.st_mode): | |
| raise _ArtifactSymlinkError(f"verify produced symlink file `{ap}`") | |
| art_pinned[rel] = _inspect_regular_nofollow(ap) | |
| else: | |
| art_pinned = {} | |
| except OracleInfrastructureError as exc: | |
| artifacts_clean = False | |
| can_run_inspect = False | |
| dedup_extra.append("verify:artifacts_symlink" if isinstance(exc, _ArtifactSymlinkError) else "verify:artifacts_unsafe") | |
| anomalies.append(str(exc)) | |
| if skip_reason is None: | |
| skip_reason = f"inspect skipped: {exc}" | |
| else: | |
| inspect_pinned.update(art_pinned) | |
| v_ok_clean = (len(dedup_extra) == 0 and len(strict_anoms) == 0) | |
| if state is not None: | |
| state["v_ok"] = v_ok_clean | |
| state["dedup_extra_anomalies"] = list(dedup_extra) | |
| allow_inspect_fault = (spec.kind in _KNOWN_BROKEN_VERIFY_KINDS) or (not v_ok_clean) | |
| ins_ok = False | |
| inspected: dict[str, Any] | None = None | |
| ins_failures: list[str] = [skip_reason] if skip_reason is not None else [] | |
| added_ins_tag = False | |
| try: | |
| if can_run_inspect: | |
| try: | |
| ins_ok, ins_failures, inspected = _run_inspect_gate( | |
| cli=cli_path, receipt_path=receipt_path, artifacts_dir=artifacts_dir, env=env, timeout=timeout, inspect_runner=i_runner | |
| ) | |
| except (subprocess.TimeoutExpired, OSError) as exc: | |
| if not allow_inspect_fault: | |
| raise OracleInfrastructureError(f"inspect failure: {exc}") from exc | |
| ins_ok, inspected = False, None | |
| ins_failures = [f"inspect failure: {exc}"] | |
| anomalies.append(ins_failures[0]) | |
| dedup_extra.append("inspect:timeout" if isinstance(exc, subprocess.TimeoutExpired) else "inspect:os_error") | |
| added_ins_tag = True | |
| except OracleInfrastructureError as exc: | |
| # Signal kills fail closed on clean pass-capable targets; broken | |
| # targets and drifted exits stay P0 if inspect dies. | |
| is_sig = "killed by signal" in str(exc) | |
| if is_sig and not allow_inspect_fault: | |
| raise | |
| ins_ok, inspected = False, None | |
| ins_failures = [str(exc)] | |
| if is_sig: | |
| anomalies.append(str(exc)) | |
| dedup_extra.append("inspect:signal") | |
| else: | |
| dedup_extra.append("inspect:invalid_output") | |
| added_ins_tag = True | |
| if not ins_ok and can_run_inspect and not added_ins_tag and not dedup.extract_receipt_anomalies(None, inspect_report=inspected): | |
| rc_match = re.match(r"inspect exit=(\d+):", ins_failures[0]) if ins_failures else None | |
| dedup_extra.append(f"inspect:exit_{rc_match.group(1)}" if rc_match else "inspect:rejected") | |
| if state is not None: | |
| state["inspect"] = inspected | |
| state["i_ok"] = ins_ok | |
| state["dedup_extra_anomalies"] = list(dedup_extra) | |
| finally: | |
| _verify_tree_hashes(work, pinned, phase="inspect", strict_subdir="src") | |
| _verify_tree_hashes( | |
| tmp_root, | |
| inspect_pinned, | |
| phase="inspect", | |
| strict_subdir=("artifacts" if artifacts_clean else None), | |
| allowed_dirs=artifact_dirs, | |
| ) | |
| _verify_pinned_tools(pinned_bins, phase="inspect") | |
| return v_ok_clean, ins_ok, anomalies, receipt, inspected, ins_failures | |
| def _lean_sysroot(lean: Path | None, *, env: dict[str, str], timeout: int) -> str: | |
| if lean is None: | |
| return "<mock-lean-sysroot>" | |
| proc = _run_bounded_subprocess([str(lean), "--print-prefix"], env=env, timeout=min(timeout, 30)) | |
| if proc.returncode != 0 or not proc.stdout.strip(): | |
| raise OracleInfrastructureError(f"`lean --print-prefix` failed: {proc.stderr.strip()}") | |
| return proc.stdout.strip() | |
| def _invoke_olean_audit( | |
| req_obj: dict[str, Any], | |
| *, lean: Path | None, tmp_root: Path, req_name: str, | |
| env: dict[str, str], timeout: int, runner: Callable[..., Any] | None, | |
| use_outer_bwrap: bool | None = None, root: Path | None = None, | |
| ) -> dict[str, Any]: | |
| req_path = tmp_root / req_name | |
| anneal_ci_lib.atomic_write_text(req_path, json.dumps(req_obj) + "\n") | |
| if lean is None and runner is None: | |
| raise OracleInfrastructureError("missing `lean` tool for `.olean` audit") | |
| cmd = [str(lean or Path("lean")), "--run", str(_OLEAN_AUDIT_SCRIPT), str(req_path)] | |
| if runner is not None: | |
| proc = runner(cmd, env=env, timeout=timeout, req=req_obj) | |
| else: | |
| assert lean is not None | |
| need_bwrap = ( | |
| _resolve_outer_sandbox( | |
| tmp_root=tmp_root, env=env, timeout=timeout, | |
| isolated_host=(os.environ.get("ANNEAL_REDTEAM_ISOLATED_HOST") == "1"), | |
| ) | |
| if use_outer_bwrap is None | |
| else use_outer_bwrap | |
| ) | |
| eff_root = (root or Path(__file__).resolve().parents[2]).resolve() | |
| prot = _repo_protected_paths(eff_root) | |
| lean_sys = Path(_lean_sysroot(lean, env=env, timeout=timeout)) | |
| ro_paths: list[Path] = [ | |
| *([lean_sys] if not _is_broad_protected_root(lean_sys, extra_protected=prot) else []), | |
| *_tool_ro_paths(root=eff_root, tools={"lean": lean}), | |
| _OLEAN_AUDIT_SCRIPT, | |
| _OLEAN_AUDIT_SCRIPT.resolve(), | |
| req_path, | |
| ] | |
| if isinstance(sp := req_obj.get("searchPath"), list): | |
| ro_paths.extend(Path(p) for p in sp if isinstance(p, str) and p) | |
| if isinstance(srcs := req_obj.get("sources"), list): | |
| ro_paths.extend(Path(row[1]).parent for row in srcs if isinstance(row, list) and len(row) > 1) | |
| run_cmd = ( | |
| _build_bwrap_cmd( | |
| cmd, ro_paths=ro_paths, rw_paths=[], chdir=Path("/tmp"), env=env, | |
| require_bwrap=True, protected_paths=prot, | |
| ) | |
| if need_bwrap | |
| else cmd | |
| ) | |
| proc = _run_bounded_subprocess(run_cmd, cwd=tmp_root, env=env, timeout=timeout) | |
| if proc.returncode != 0: | |
| raise OracleInfrastructureError( | |
| f"olean_audit failed (exit={proc.returncode}): {(proc.stderr or proc.stdout).strip()[:240]}" | |
| ) | |
| return _loads_strict_dict(proc.stdout, label="olean_audit JSON", exc_type=OracleInfrastructureError) | |
| def _extract_olean_audit_violations(oa_res: Any) -> list[str]: | |
| """Extract violation strings fail-closed from an `olean_audit` payload.""" | |
| if not isinstance(oa_res, dict): | |
| return ["malformed_olean_audit"] | |
| raw_ok = oa_res.get("ok") | |
| raw_vs = oa_res.get("violations") | |
| if not isinstance(raw_ok, bool) or not isinstance(raw_vs, list): | |
| return ["malformed_olean_audit"] | |
| out: list[str] = [] | |
| has_bad_entry = False | |
| for item in raw_vs: | |
| if isinstance(item, str) and item: | |
| out.append(item) | |
| else: | |
| has_bad_entry = True | |
| if has_bad_entry: | |
| out.append("malformed_olean_audit_entry") | |
| if not raw_ok and not out: | |
| out.append("olean_audit_failed_without_violations") | |
| return out | |
| def _audit_exported_spec_oleans( | |
| *, sub: LoadedSubmission, artifacts_dir: Path, lean: Path | None, tmp_root: Path, | |
| env: dict[str, str], timeout: int, olean_audit_runner: Callable[..., Any] | None, | |
| use_outer_bwrap: bool | None = None, isolated_host: bool = False, | |
| root: Path | None = None, | |
| ) -> dict[str, Any] | None: | |
| """Audit exported `Spec*.olean` artifacts for preflight-bypass constructs. | |
| Example attack scenario: a specification hides a custom `axiom` or | |
| `@[implemented_by]` override behind a macro that `SpecPreflight` misses. | |
| Even if `Proof.lean` later fails, `--export-lean-lib` emits compiled | |
| `Spec*.olean` modules, which `olean_audit.lean` inspects at `trustLevel=0`. | |
| """ | |
| if artifacts_dir.is_symlink() or (os.path.lexists(artifacts_dir) and not artifacts_dir.is_dir()): | |
| return {"ok": False, "auditedModules": [], "violations": ["unsafe_artifacts_dir"]} | |
| lean_lib_dir = artifacts_dir / "lean-lib" | |
| if lean_lib_dir.is_symlink() or (os.path.lexists(lean_lib_dir) and not lean_lib_dir.is_dir()): | |
| return {"ok": False, "auditedModules": [], "violations": ["unsafe_spec_olean_dir"]} | |
| if not lean_lib_dir.is_dir(): | |
| return None | |
| try: | |
| lib_files = _collect_tree_regular_files(lean_lib_dir) | |
| except OracleInfrastructureError: | |
| return {"ok": False, "auditedModules": [], "violations": ["unsafe_spec_olean_tree"]} | |
| for rel_lib in sorted(lib_files): | |
| root_seg = rel_lib.split("/", 1)[0].split(".", 1)[0] | |
| if root_seg in ("Init", "Std", "Lean", "Lake", "System", "IO", "Task"): | |
| return {"ok": False, "auditedModules": [], "violations": [f"sp_shadows_sysroot:{root_seg}"]} | |
| spec_mods = sorted( | |
| "Spec" if rel == "Spec/Spec.lean" else f"Spec.{_validate_lean_slot_path(rel, 'Spec')}" | |
| for rel in sub.files | |
| if rel.startswith("Spec/") | |
| ) | |
| present: list[str] = [] | |
| for mod in spec_mods: | |
| op = lean_lib_dir / f"{mod.replace('.', '/')}.olean" | |
| if os.path.lexists(op): | |
| try: | |
| _inspect_regular_nofollow(op) | |
| except OracleInfrastructureError: | |
| return {"ok": False, "auditedModules": [], "violations": ["unsafe_spec_olean_file"]} | |
| present.append(mod) | |
| if not present: | |
| return None | |
| eff_bwrap = ( | |
| _resolve_outer_sandbox(tmp_root=tmp_root, env=env, timeout=timeout, isolated_host=isolated_host) | |
| if use_outer_bwrap is None and olean_audit_runner is None and lean is not None | |
| else use_outer_bwrap | |
| ) | |
| req = { | |
| "mode": "audit", | |
| "sysroot": _lean_sysroot(lean, env=env, timeout=timeout), | |
| "searchPath": [str(lean_lib_dir)], | |
| "modules": present, | |
| "role": "spec", | |
| } | |
| return _invoke_olean_audit( | |
| req, lean=lean, tmp_root=tmp_root, req_name="olean-audit-spec.json", | |
| env=env, timeout=timeout, runner=olean_audit_runner, use_outer_bwrap=eff_bwrap, root=root, | |
| ) | |
| def _compile_and_audit_theory( | |
| *, work: Path, submitted_rels: set[str], lean: Path | None, tmp_root: Path, | |
| env: dict[str, str], timeout: int, olean_audit_runner: Callable[..., Any] | None, | |
| mocked_audit: bool = False, use_outer_bwrap: bool | None = None, | |
| root: Path | None = None, | |
| ) -> tuple[dict[str, Any], list[str]]: | |
| """Compile submitted `Anneal.*` dependency closure and audit its `.olean`s. | |
| Because `anneal-audit` builds inside its own ephemeral directory without | |
| exporting compiled artifacts, this secondary check recompiles the needed | |
| dependency DAG under matching Lean flags (`-j1 -DElab.async=false | |
| -Ddebug.skipKernelTC=false`, plus `-DwarningAsError=true` on `Anneal*`) | |
| inside `bwrap`, pinning the compiled `.olean`s and inspecting all | |
| `.olean*`/`.ir*` parts at `trustLevel=0`. | |
| Example attack scenario: an attacker submits `theory/Anneal/Evil.lean` | |
| carrying a custom `axiom`, `partial` loop, `@[csimp]` hook, `IO`/`Lean.*` | |
| escape, `Trusted.*` declaration, or `False` theorem that slips past | |
| `anneal-audit`. | |
| """ | |
| submitted_mods = sorted( | |
| "Anneal" if rel == "Anneal.lean" else "Anneal." + ".".join(Path(rel).relative_to("Anneal").with_suffix("").parts) | |
| for rel in submitted_rels | |
| ) | |
| if olean_audit_runner is not None and (lean is None or mocked_audit): | |
| oa = _invoke_olean_audit( | |
| {"mode": "audit", "sysroot": "<mock-lean-sysroot>", "searchPath": [str(tmp_root / "theory-lib")], "modules": submitted_mods, "role": "theory"}, | |
| lean=None, tmp_root=tmp_root, req_name="olean-audit-theory.json", env=env, timeout=timeout, runner=olean_audit_runner, root=root, | |
| ) | |
| vs = _extract_olean_audit_violations(oa) | |
| return ({**oa, "ok": not vs, "violations": vs} if isinstance(oa, dict) else {"ok": False, "violations": vs}), vs | |
| if lean is None: | |
| raise OracleInfrastructureError("missing `lean` tool for `.olean` verification") | |
| need_bwrap = ( | |
| _resolve_outer_sandbox( | |
| tmp_root=tmp_root, env=env, timeout=timeout, | |
| isolated_host=(os.environ.get("ANNEAL_REDTEAM_ISOLATED_HOST") == "1"), | |
| ) | |
| if use_outer_bwrap is None | |
| else use_outer_bwrap | |
| ) | |
| eff_root = (root or Path(__file__).resolve().parents[2]).resolve() | |
| prot = _repo_protected_paths(eff_root) | |
| sources: dict[str, tuple[Path, Path]] = {} | |
| for base in (work / "trusted/lean", work / "theory"): | |
| for rel in sorted(_collect_tree_regular_files(base)): | |
| if rel.endswith(".lean"): | |
| sources[".".join(Path(rel).with_suffix("").parts)] = (base, base / rel) | |
| hdr_res = _invoke_olean_audit( | |
| {"mode": "headers", "sources": [[m, str(p)] for m, (_, p) in sorted(sources.items())]}, | |
| lean=lean, tmp_root=tmp_root, req_name="olean-headers-theory.json", env=env, timeout=timeout, | |
| runner=None, use_outer_bwrap=need_bwrap, root=eff_root, | |
| ) | |
| imports = dict(hdr_res.get("headers", [])) | |
| need: set[str] = set() | |
| stack = list(submitted_mods) | |
| while stack: | |
| cur = stack.pop() | |
| if cur in sources and cur not in need: | |
| need.add(cur) | |
| stack.extend(imports.get(cur, [])) | |
| indeg = {m: 0 for m in need} | |
| adj: dict[str, list[str]] = {m: [] for m in need} | |
| for m in need: | |
| for dep in imports.get(m, []): | |
| if dep in need and dep != m: | |
| adj[dep].append(m) | |
| indeg[m] += 1 | |
| queue = sorted(m for m, deg in indeg.items() if deg == 0) | |
| order: list[str] = [] | |
| while queue: | |
| u = queue.pop(0) | |
| order.append(u) | |
| for v in sorted(adj[u]): | |
| indeg[v] -= 1 | |
| if indeg[v] == 0: | |
| queue.append(v) | |
| if len(order) != len(need): | |
| return {"ok": False, "auditedModules": submitted_mods, "violations": ["audit_bypass:import_cycle"]}, ["audit_bypass:import_cycle"] | |
| lib_dir = tmp_root / "theory-lib" | |
| steps_root = tmp_root / "theory-steps" | |
| for d in (lib_dir, steps_root): | |
| if d.is_symlink() or (os.path.lexists(d) and not d.is_dir()): | |
| raise OracleInfrastructureError(f"unsafe theory staging directory `{d.name}`") | |
| if d.exists(): | |
| shutil.rmtree(d) | |
| d.mkdir(parents=True, exist_ok=True) | |
| comp_env = {**env, "LEAN_PATH": str(lib_dir)} | |
| lean_sys = Path(_lean_sysroot(lean, env=env, timeout=timeout)) | |
| ro_roots = [ | |
| *([lean_sys] if not _is_broad_protected_root(lean_sys, extra_protected=prot) else []), | |
| *_tool_ro_paths(root=eff_root, tools={"lean": lean}), | |
| work / "trusted/lean", | |
| work / "theory", | |
| lib_dir, | |
| ] | |
| sub_set = set(submitted_mods) | |
| lib_pinned: dict[str, _PinnedAssetSnapshot] = {} | |
| compiled_subs: list[str] = [] | |
| compiled_anneal: list[str] = [] | |
| extra_vs: list[str] = [] | |
| for step_idx, mod in enumerate(order): | |
| _verify_tree_hashes(lib_dir, lib_pinned, phase="audit", exact_root=True) | |
| root_dir, src_path = sources[mod] | |
| step_dir = steps_root / f"s{step_idx}" | |
| step_dir.mkdir(parents=True, exist_ok=True) | |
| rel_stem = mod.replace(".", "/") | |
| rel_olean = f"{rel_stem}.olean" | |
| allowed_rels = { | |
| f"{rel_stem}{ext}" | |
| for ext in (".olean", ".olean.private", ".olean.server", ".ir", ".ir.sig") | |
| } | |
| step_out = step_dir / rel_olean | |
| step_out.parent.mkdir(parents=True, exist_ok=True) | |
| raw_c_cmd = [ | |
| str(lean), | |
| "-j1", | |
| "-DElab.async=false", | |
| "-Ddebug.skipKernelTC=false", | |
| *( | |
| ["-DwarningAsError=true"] | |
| if mod == "Anneal" or mod.startswith("Anneal.") | |
| else [] | |
| ), | |
| "-R", | |
| str(root_dir), | |
| "-o", | |
| str(step_out), | |
| str(src_path), | |
| ] | |
| c_cmd = ( | |
| _build_bwrap_cmd( | |
| raw_c_cmd, ro_paths=ro_roots, rw_paths=[step_dir], chdir=root_dir, | |
| env=comp_env, require_bwrap=True, protected_paths=prot, | |
| ) | |
| if need_bwrap | |
| else raw_c_cmd | |
| ) | |
| try: | |
| c_proc = _run_bounded_subprocess(c_cmd, cwd=root_dir, env=comp_env, timeout=timeout) | |
| except (subprocess.TimeoutExpired, OSError) as exc: | |
| raise OracleInfrastructureError(f"failed invoking lean for `{mod}`: {exc}") from exc | |
| finally: | |
| _verify_tree_hashes(lib_dir, lib_pinned, phase="audit", exact_root=True) | |
| if c_proc.returncode < 0: | |
| raise OracleInfrastructureError( | |
| f"lean killed by signal {-c_proc.returncode} compiling `{mod}`" | |
| ) | |
| if c_proc.returncode != 0: | |
| if mod in sub_set and c_proc.returncode == 1: | |
| extra_vs.append(f"audit_bypass:failed_compile:{mod}") | |
| continue | |
| role_lbl = "submitted" if mod in sub_set else "defender" | |
| raise OracleInfrastructureError( | |
| f"failed compiling {role_lbl} `{mod}` (exit={c_proc.returncode}): {c_proc.stderr.strip()[:240]}" | |
| ) | |
| staged_artifacts: dict[str, bytes] = {} | |
| try: | |
| step_files = _collect_tree_regular_files(step_dir) | |
| if rel_olean in step_files and step_files <= allowed_rels: | |
| for rel_art in sorted(step_files): | |
| staged_artifacts[rel_art] = _read_regular_file_nofollow( | |
| step_dir / rel_art, | |
| max_bytes=_MAX_THEORY_ARTIFACT_BYTES, | |
| exc_type=OracleInfrastructureError, | |
| ) | |
| except OracleInfrastructureError as exc: | |
| if mod in sub_set: | |
| extra_vs.append(f"audit_bypass:unexpected_compile_output:{mod}") | |
| continue | |
| raise OracleInfrastructureError(f"defender compile step error for `{mod}`: {exc}") from exc | |
| if not staged_artifacts: | |
| if mod in sub_set: | |
| extra_vs.append(f"audit_bypass:unexpected_compile_output:{mod}") | |
| continue | |
| raise OracleInfrastructureError( | |
| f"unexpected files emitted while compiling defender `{mod}`: {sorted(step_files)}" | |
| ) | |
| for rel_art, art_bytes in staged_artifacts.items(): | |
| lib_dest = lib_dir / rel_art | |
| _write_new_regular_file_excl(lib_dest, art_bytes) | |
| lib_pinned[rel_art] = _inspect_regular_nofollow(lib_dest) | |
| if mod in sub_set: | |
| compiled_subs.append(mod) | |
| if mod == "Anneal" or mod.startswith("Anneal."): | |
| compiled_anneal.append(mod) | |
| if not compiled_subs and not compiled_anneal: | |
| return {"ok": False, "auditedModules": submitted_mods, "violations": extra_vs}, extra_vs | |
| base_anneal = [m for m in compiled_anneal if m not in sub_set] | |
| if base_anneal: | |
| try: | |
| base_oa = _invoke_olean_audit( | |
| {"mode": "audit", "sysroot": str(lean_sys), "searchPath": [str(lib_dir)], "modules": base_anneal, "role": "theory"}, | |
| lean=lean, tmp_root=tmp_root, req_name="olean-audit-theory-base.json", env=env, timeout=timeout, | |
| runner=olean_audit_runner, use_outer_bwrap=need_bwrap, root=eff_root, | |
| ) | |
| finally: | |
| _verify_tree_hashes(lib_dir, lib_pinned, phase="audit", exact_root=True) | |
| base_vs = base_oa.get("violations") | |
| if not base_oa.get("ok") or not isinstance(base_vs, list) or base_vs: | |
| raise OracleInfrastructureError(f"defender theory baseline failed olean_audit: {base_vs}") | |
| audit_mods = compiled_anneal or compiled_subs | |
| try: | |
| oa = _invoke_olean_audit( | |
| {"mode": "audit", "sysroot": str(lean_sys), "searchPath": [str(lib_dir)], "modules": audit_mods, "role": "theory"}, | |
| lean=lean, tmp_root=tmp_root, req_name="olean-audit-theory.json", env=env, timeout=timeout, | |
| runner=olean_audit_runner, use_outer_bwrap=need_bwrap, root=eff_root, | |
| ) | |
| finally: | |
| _verify_tree_hashes(lib_dir, lib_pinned, phase="audit", exact_root=True) | |
| merged = extra_vs + _extract_olean_audit_violations(oa) | |
| oa["violations"] = merged | |
| oa["ok"] = len(merged) == 0 | |
| return oa, merged | |
| def _build_trace_artifacts( | |
| *, state: dict[str, Any], private_roots: tuple[tuple[str, str], ...], | |
| phase: str | None, tampered: tuple[dict[str, Any], ...], stderr_note: str | None, | |
| ) -> dict[str, Any] | None: | |
| sub: LoadedSubmission | None = state["submission"] | |
| if sub is None and not state["hashes"]: | |
| return None | |
| vr, ir, cm = state["v_receipt"], state["inspect"], state["cap"] | |
| prog = cm.get("program") if isinstance(cm, dict) else None | |
| s_tampered = _sanitize_obj(list(tampered), private_roots=private_roots) | |
| v_sum = { | |
| "status": vr.get("status"), "phase": vr.get("phase"), | |
| "detail": _sanitize_snippet(str(vr.get("detail")) if vr.get("detail") is not None else None, private_roots=private_roots), | |
| "taint_reasons": vr.get("taint_reasons"), "deferred": vr.get("deferred"), | |
| "elaboration_sandbox": vr.get("elaboration_sandbox"), "audit": _sanitize_obj(vr.get("audit"), private_roots=private_roots), | |
| } if isinstance(vr, dict) else None | |
| i_sum = _sanitize_obj( | |
| {k: ir.get(k) for k in ("tainted", "policy_violations", "invariant_violations", "unrecognized_fields", "artifact_verification")}, | |
| private_roots=private_roots, | |
| ) if isinstance(ir, dict) else None | |
| ra, oa = state.get("repo_audit"), state.get("olean_audit") | |
| ra_sum = _sanitize_obj( | |
| {k: ra.get(k) for k in ("guarantee", "toolchain", "replay", "kernelDeclarations", "replayedDeclarations", "axioms", "vettedModules", "candidateFeatures")}, | |
| private_roots=private_roots, | |
| ) if isinstance(ra, dict) else None | |
| oa_sum = _sanitize_obj(oa, private_roots=private_roots) if isinstance(oa, dict) else None | |
| return { | |
| "verify_summary": v_sum, | |
| "inspect_summary": i_sum, | |
| "repo_audit_summary": ra_sum, | |
| "olean_audit_summary": oa_sum, | |
| "capture_summary": { | |
| "mir_profile_version": prog.get("mir_profile_version"), "scope": prog.get("scope"), | |
| "has_local_panic_handler": prog.get("has_local_panic_handler"), | |
| "body_count": len(prog.get("bodies", [])) if isinstance(prog.get("bodies"), list) else 0, | |
| } if isinstance(prog, dict) else None, | |
| "harness_compromise": {"detected": True, "phase": phase, "tampered_assets": s_tampered} if phase or tampered else None, | |
| "attacker_provenance_sha256": state["hashes"], | |
| "explanation_sha256": sub.explanation_sha256 if sub else None, | |
| "explanation_excerpt": _sanitize_snippet(sub.explanation_text, private_roots=private_roots, limit=4000) if sub else None, | |
| "tool_stderr_snippet": _sanitize_snippet(stderr_note, private_roots=private_roots), | |
| } | |
| def _run_theory_audit_eval( | |
| *, tmp_root: Path, work: Path, root: Path, spec: scenarios.ScenarioSpec, sub: LoadedSubmission, | |
| tools: dict[str, Path | None], pinned_bins: dict[str, tuple[Path, Path, _PinnedAssetSnapshot]], | |
| env: dict[str, str], timeout: int, state: dict[str, Any], | |
| audit_runner: Callable[..., Any] | None, olean_audit_runner: Callable[..., Any] | None, | |
| private_roots: tuple[tuple[str, str], ...] = (), isolated_host: bool = False, | |
| ) -> tuple[str, list[str], str | None, dict[str, Any] | None, str | None]: | |
| auditor, lean = tools.get("auditor"), tools.get("lean") | |
| if audit_runner is None: | |
| missing = [n for n, p in (("anneal-audit", auditor), ("lean", lean)) if p is None] | |
| if missing: | |
| raise OracleInfrastructureError(f"missing verification tools: {', '.join(missing)}") | |
| use_outer_bwrap = False | |
| if audit_runner is None: | |
| use_outer_bwrap = _resolve_outer_sandbox(tmp_root=tmp_root, env=env, timeout=timeout, isolated_host=isolated_host) | |
| extra_ro: list[Path] = [] | |
| eff_root = root.resolve() | |
| prot = _repo_protected_paths(eff_root) | |
| if audit_runner is None and lean is not None: | |
| lean_sys = Path(_lean_sysroot(lean, env=env, timeout=timeout)) | |
| if not _is_broad_protected_root(lean_sys, extra_protected=prot): | |
| extra_ro.append(lean_sys) | |
| sb_runner = _make_sandboxed_runner( | |
| ro_paths=[*_tool_ro_paths(root=eff_root, tools=tools), *extra_ro], | |
| rw_paths=[tmp_root], default_cwd=work, use_outer_bwrap=use_outer_bwrap, | |
| protected_paths=prot, | |
| ) | |
| a_runner = audit_runner or sb_runner | |
| pinned, def_theory, sub_theory = _stage_theory_audit_workspace(work, root, sub) | |
| all_pinned = { | |
| **pinned, | |
| **{f"theory/{rel}": _inspect_regular_nofollow(work / "theory" / rel) for rel in sorted(sub_theory)}, | |
| } | |
| cmd = [str(auditor or Path("anneal-audit")), "--anneal-root", str(work), "--lean", str(lean or Path("lean")), "--json"] | |
| try: | |
| try: | |
| proc = a_runner(cmd, cwd=work, env=env, timeout=timeout) | |
| except (subprocess.TimeoutExpired, OSError) as exc: | |
| raise OracleInfrastructureError(f"anneal-audit failure: {exc}") from exc | |
| finally: | |
| _verify_tree_hashes(work, all_pinned, phase="audit", strict_subdir="trusted") | |
| _verify_theory_tree_exact(work, def_theory | sub_theory, phase="audit") | |
| _verify_pinned_tools(pinned_bins, phase="audit") | |
| if proc.returncode < 0: | |
| raise OracleInfrastructureError(f"anneal-audit killed by signal {-proc.returncode}") | |
| is_theory_compile_fail = ( | |
| proc.returncode == 2 | |
| and bool( | |
| re.search( | |
| r"(?:^|\n)(?:Error: )?Trusted check failed \(compile-Anneal(?:\.[A-Za-z0-9_]+)*\): Lean exited Some\(1\)", | |
| proc.stderr or "", | |
| ) | |
| ) | |
| ) | |
| if proc.returncode == 1 or is_theory_compile_fail: | |
| # Confirm the defender-only baseline passes `anneal-audit` cleanly so | |
| # defender drift or missing core modules fails closed as HARNESS_ERROR. | |
| base_work = tmp_root / "baseline-audit" | |
| base_sub = LoadedSubmission(files={}, explanation_text=sub.explanation_text, explanation_sha256=sub.explanation_sha256) | |
| base_pinned, base_def, base_empty = _stage_theory_audit_workspace(base_work, root, base_sub) | |
| base_cmd = [str(auditor or Path("anneal-audit")), "--anneal-root", str(base_work), "--lean", str(lean or Path("lean")), "--json"] | |
| try: | |
| try: | |
| base_proc = a_runner(base_cmd, cwd=base_work, env=env, timeout=timeout) | |
| except (subprocess.TimeoutExpired, OSError) as exc: | |
| raise OracleInfrastructureError(f"baseline anneal-audit failure: {exc}") from exc | |
| finally: | |
| _verify_tree_hashes(base_work, base_pinned, phase="audit", strict_subdir="trusted") | |
| _verify_theory_tree_exact(base_work, base_def | base_empty, phase="audit") | |
| _verify_pinned_tools(pinned_bins, phase="audit") | |
| if base_proc.returncode != 0: | |
| raise OracleInfrastructureError( | |
| f"defender baseline failed anneal-audit (exit={base_proc.returncode}); cannot attribute exit=1" | |
| ) | |
| detail = (proc.stderr or proc.stdout).strip()[:240] or "anneal-audit rejected submission" | |
| return VERDICT_DEFENDER_HELD_ANNEAL_FAIL_CLOSED, [f"audit exit={proc.returncode}: {detail}"], None, None, proc.stderr | |
| if proc.returncode != 0: | |
| raise OracleInfrastructureError(f"anneal-audit operational failure (exit={proc.returncode}): {proc.stderr.strip()[:240]}") | |
| audit_report = _loads_strict_dict(proc.stdout, label="anneal-audit JSON", exc_type=OracleInfrastructureError) | |
| if not isinstance(audit_report.get("replay"), bool): | |
| raise OracleInfrastructureError("anneal-audit JSON missing boolean `replay`") | |
| state["repo_audit"] = audit_report | |
| audit_anoms = dedup.extract_receipt_anomalies(None, audit_report=audit_report) | |
| oa_vs: list[str] = [] | |
| if audit_runner is None or olean_audit_runner is not None: | |
| try: | |
| oa_report, oa_vs = _compile_and_audit_theory( | |
| work=work, submitted_rels=sub_theory, lean=lean, tmp_root=tmp_root, | |
| env=env, timeout=timeout, olean_audit_runner=olean_audit_runner, | |
| mocked_audit=(audit_runner is not None), | |
| use_outer_bwrap=use_outer_bwrap if audit_runner is None else None, | |
| root=eff_root, | |
| ) | |
| state["olean_audit"] = oa_report | |
| finally: | |
| _verify_tree_hashes(work, all_pinned, phase="audit", strict_subdir="trusted") | |
| _verify_theory_tree_exact(work, def_theory | sub_theory, phase="audit") | |
| _verify_pinned_tools(pinned_bins, phase="audit") | |
| if audit_anoms or oa_vs: | |
| dedup_obj = dedup.compute_dedup_metadata( | |
| scenario_id=spec.scenario_id, scenario_kind=spec.kind, submission_files=sub.files, | |
| audit_report=_sanitize_obj(audit_report, private_roots=private_roots), | |
| olean_violations=_sanitize_obj(oa_vs, private_roots=private_roots), | |
| ) | |
| reasons = [*(f"audit anomaly: {a}" for a in audit_anoms), *(f"olean audit: {v}" for v in oa_vs)] | |
| return VERDICT_ATTACKER_WON_ANNEAL_COMPROMISED, reasons, "P0", dedup_obj, "; ".join(reasons) | |
| return ( | |
| VERDICT_DEFENDER_HELD_ANNEAL_FAIL_CLOSED, | |
| ["benign theory submission cleanly passed anneal-audit and .olean checks"], | |
| None, | |
| None, | |
| None, | |
| ) | |
| def evaluate_submission( | |
| *, scenario_id: str, submission_dir: Path | None = None, submission_tar: Path | None = None, | |
| anneal_root: Path | None = None, cli: Path | None = None, capture: Path | None = None, | |
| sysroot: Path | None = None, lean: Path | None = None, auditor: Path | None = None, | |
| timeout_sec: int = 300, verify_runner: Callable[..., Any] | None = None, | |
| inspect_runner: Callable[..., Any] | None = None, audit_runner: Callable[..., Any] | None = None, | |
| olean_audit_runner: Callable[..., Any] | None = None, isolated_host: bool | None = None, | |
| ) -> dict[str, Any]: | |
| """Evaluate one red-team submission against a defender-fixed target.""" | |
| if not isinstance(timeout_sec, int) or isinstance(timeout_sec, bool) or timeout_sec <= 0: | |
| raise ValueError(f"timeout_sec must be positive int, got {timeout_sec!r}") | |
| if (submission_dir is None) == (submission_tar is None): | |
| raise ValueError("specify exactly one of submission_dir or submission_tar") | |
| spec = scenarios.get_scenario(scenario_id) | |
| root = (anneal_root or Path(__file__).resolve().parents[2]).resolve() | |
| eff_isolated_host = bool(isolated_host) if isolated_host is not None else (os.environ.get("ANNEAL_REDTEAM_ISOLATED_HOST") == "1") | |
| overrides = {"cli": cli, "capture": capture, "sysroot": sysroot, "lean": lean, "auditor": auditor} | |
| state: dict[str, Any] = { | |
| "tmp_root": None, "tools": None, "target_sha": "unknown", "target_dirty": None, "target_tree_oid": None, | |
| "tool_prov": None, "submission": None, "hashes": {}, "v_receipt": None, "v_exit_code": None, | |
| "dedup_extra_anomalies": [], "inspect": None, "cap": None, "repo_audit": None, "olean_audit": None, | |
| "v_ok": False, "i_ok": False, | |
| } | |
| def _private_roots() -> tuple[tuple[str, str], ...]: | |
| merged = {**overrides, **{k: v for k, v in (state["tools"] or {}).items() if v is not None}} | |
| return _collect_private_roots( | |
| tmp_root=state["tmp_root"], anneal_root=root, tools=merged, | |
| submission_dir=submission_dir, submission_tar=submission_tar, | |
| ) | |
| def _finish( | |
| verdict: str, *, reasons: list[str], invalid_reason: str | None = None, integrity_ok: bool = True, | |
| phase: str | None = None, tampered: tuple[dict[str, Any], ...] = (), severity: str | None = None, | |
| dedup_obj: dict[str, Any] | None = None, stderr_note: str | None = None, | |
| ) -> dict[str, Any]: | |
| pr = _private_roots() | |
| vr, s_reasons = state["v_receipt"], [_sanitize_snippet(r, private_roots=pr) or "" for r in reasons] | |
| s_dedup = _sanitize_obj(dedup_obj, private_roots=pr) if verdict in WINNING_VERDICTS and dedup_obj is not None else None | |
| return { | |
| "schema_version": RECEIPT_SCHEMA, "scenario_id": spec.scenario_id, "scenario_kind": spec.kind, "verdict": verdict, | |
| "invalid_reason": _sanitize_snippet(invalid_reason, private_roots=pr) if invalid_reason else None, | |
| "defender_integrity_ok": integrity_ok, "sandbox_escape_detected": (not integrity_ok and phase == "verify"), | |
| "compromise_phase": phase, "tampered_assets": _sanitize_obj(list(tampered), private_roots=pr), "proposed_severity": severity, | |
| "anneal_verify_ok": state["v_ok"], "anneal_inspect_ok": state["i_ok"], | |
| "target_sha": state["target_sha"], "target_dirty": state["target_dirty"], "target_tree_oid": state["target_tree_oid"], | |
| "tool_provenance": state["tool_prov"], "summary": "; ".join(s_reasons), "reasons": s_reasons, | |
| "verify_status": vr.get("status") if isinstance(vr, dict) else None, | |
| "verify_taint_reasons": vr.get("taint_reasons") if isinstance(vr, dict) else None, | |
| "elaboration_sandbox": vr.get("elaboration_sandbox") if isinstance(vr, dict) else None, | |
| "dedup": s_dedup, | |
| "trace_artifacts": _build_trace_artifacts(state=state, private_roots=pr, phase=phase, tampered=tampered, stderr_note=stderr_note), | |
| } | |
| try: | |
| _open_flags() | |
| raw = _load_submission_dir(submission_dir) if submission_dir is not None else _load_submission_tar(submission_tar) # type: ignore[arg-type] | |
| sub = _validate_scenario_slots(spec, raw) | |
| except OracleInfrastructureError as exc: | |
| return _finish(VERDICT_HARNESS_ERROR, reasons=[str(exc)], stderr_note=str(exc)) | |
| except (InvalidSubmissionError, UnicodeError, RecursionError, LookupError, tarfile.TarError, lzma.LZMAError, zlib.error, gzip.BadGzipFile, ValueError, TypeError, IndexError, KeyError) as exc: | |
| return _finish(VERDICT_INVALID_SUBMISSION, reasons=[str(exc)], invalid_reason=str(exc)) | |
| state["submission"], state["hashes"] = sub, {r: anneal_ci_lib.sha256_bytes(d) for r, d in sorted(sub.files.items())} | |
| try: | |
| state["target_sha"], state["target_dirty"], state["target_tree_oid"], git_bin = _git_provenance(root) | |
| is_theory = spec.kind == "THEORY_AUDIT_HACK" | |
| need_v = (not is_theory) and verify_runner is None | |
| raw_defaults = _discover_pinned_local_defaults( | |
| root, need_cli=(cli is None and need_v), need_capture=(capture is None and need_v), | |
| need_lean=(lean is None), need_sysroot=(sysroot is None and need_v), | |
| ) | |
| raw_tools = _raw_local_tool_candidates( | |
| root, explicit_overrides=overrides, need_auditor=(is_theory or auditor is not None), raw_defaults=raw_defaults, | |
| ) | |
| tools = anneal_ci_lib.discover_tools( | |
| root, cli=cli, capture=capture, sysroot=sysroot, lean=lean, auditor=auditor, | |
| defaults_fn=lambda _ar: raw_defaults, | |
| ) | |
| state["tools"] = dict(tools) | |
| state["tool_prov"], pinned_bins = _snapshot_tool_provenance( | |
| tools, explicit_overrides=overrides, raw_paths=raw_tools, git_bin=git_bin, | |
| include_auditor=(is_theory or auditor is not None), | |
| pin_olean_audit=(spec.kind in ("SPEC_PREFLIGHT_HACK", "THEORY_AUDIT_HACK")), | |
| ) | |
| with tempfile.TemporaryDirectory(prefix="anneal-redteam-") as tmp_dir: | |
| tmp_root = Path(tmp_dir).resolve(strict=True) | |
| try: | |
| state["tmp_root"] = tmp_root | |
| work, artifacts_dir, receipt_path = tmp_root / "workspace", tmp_root / "artifacts", tmp_root / "verify-receipt.json" | |
| olean_cache = tmp_root / "olean-cache" | |
| for d in (tmp_root / "home", tmp_root / "xdg", tmp_root / "tmp", olean_cache): | |
| d.mkdir(parents=True, exist_ok=True) | |
| env = {k: os.environ[k] for k in _ALLOWED_ENV_KEYS if os.environ.get(k)} | |
| env.update({"NO_COLOR": "1", "CARGO_NET_OFFLINE": "true", "HOME": str(tmp_root / "home"), "XDG_CACHE_HOME": str(tmp_root / "xdg"), "TMPDIR": str(tmp_root / "tmp")}) | |
| if (sr := tools.get("sysroot")) is not None: | |
| env["LD_LIBRARY_PATH"] = env["DYLD_LIBRARY_PATH"] = str(sr / "lib") | |
| if is_theory: | |
| verdict, reasons, sev, dedup_obj, note = _run_theory_audit_eval( | |
| tmp_root=tmp_root, work=work, root=root, spec=spec, sub=sub, tools=tools, | |
| pinned_bins=pinned_bins, env=env, timeout=timeout_sec, state=state, | |
| audit_runner=audit_runner, olean_audit_runner=olean_audit_runner, | |
| private_roots=_private_roots(), isolated_host=eff_isolated_host, | |
| ) | |
| return _finish(verdict, reasons=reasons, severity=sev, dedup_obj=dedup_obj, stderr_note=note) | |
| req_path, pinned = _stage_verify_workspace(work, spec, sub) | |
| v_ok, i_ok, anomalies, vr, ir, failures = _run_verify_and_inspect( | |
| tmp_root=tmp_root, work=work, pinned=pinned, pinned_bins=pinned_bins, | |
| request_path=req_path, artifacts_dir=artifacts_dir, receipt_path=receipt_path, olean_cache=olean_cache, | |
| spec=spec, tools=tools, env=env, timeout=timeout_sec, verify_runner=verify_runner, inspect_runner=inspect_runner, | |
| state=state, root=root, isolated_host=eff_isolated_host, | |
| ) | |
| state.update({"v_ok": v_ok, "i_ok": i_ok, "v_receipt": vr, "inspect": ir, "cap": _load_capture_manifest(artifacts_dir)}) | |
| oa_vs: list[str] = [] | |
| skip_spec_oa = any( | |
| a.startswith("verify:artifacts_") for a in state["dedup_extra_anomalies"] | |
| ) | |
| if spec.kind == "SPEC_PREFLIGHT_HACK" and not skip_spec_oa: | |
| try: | |
| try: | |
| oa_res = _audit_exported_spec_oleans( | |
| sub=sub, artifacts_dir=artifacts_dir, lean=tools.get("lean"), tmp_root=tmp_root, | |
| env=env, timeout=timeout_sec, olean_audit_runner=olean_audit_runner, | |
| isolated_host=eff_isolated_host, root=root, | |
| ) | |
| if oa_res is not None: | |
| oa_vs = _extract_olean_audit_violations(oa_res) | |
| state["olean_audit"] = ( | |
| {**oa_res, "ok": len(oa_vs) == 0, "violations": oa_vs} | |
| if isinstance(oa_res, dict) | |
| else {"ok": False, "violations": oa_vs} | |
| ) | |
| except (OracleInfrastructureError, subprocess.TimeoutExpired, OSError) as exc: | |
| if state["v_exit_code"] != 0: | |
| raise OracleInfrastructureError(f"spec olean audit failure: {exc}") from exc | |
| msg = f"spec olean audit failure after exit-0 verify: {exc}" | |
| anomalies.append(msg) | |
| state["dedup_extra_anomalies"].append( | |
| "spec_olean_audit:timeout" if isinstance(exc, subprocess.TimeoutExpired) else "spec_olean_audit:error" | |
| ) | |
| failures = [*failures, msg] | |
| finally: | |
| _verify_tree_hashes(work, pinned, phase="audit", strict_subdir="src") | |
| _verify_pinned_tools(pinned_bins, phase="audit") | |
| known_broken = spec.kind in _KNOWN_BROKEN_VERIFY_KINDS | |
| verify_exited_zero = (state["v_exit_code"] == 0) | |
| verify_accepted_exit0 = bool(v_ok and i_ok and not anomalies) | |
| inspect_taint_or_policy = verify_exited_zero and _inspect_taint_or_policy_anomalies(ir) | |
| won = ( | |
| (verify_exited_zero or bool(oa_vs)) | |
| if known_broken | |
| else (verify_accepted_exit0 or bool(anomalies) or inspect_taint_or_policy or bool(oa_vs)) | |
| ) | |
| if not known_broken and v_ok and not i_ok and not won: | |
| return _finish( | |
| VERDICT_HARNESS_ERROR, | |
| reasons=[f"clean verify exit=0 rejected by inspect: {'; '.join(failures)}"], | |
| stderr_note="; ".join(failures) or None, | |
| ) | |
| win_reasons: list[str] = [] | |
| if anomalies or inspect_taint_or_policy or (known_broken and verify_exited_zero and not i_ok): | |
| if anomalies: | |
| win_reasons.append(f"verify exited 0 despite policy/audit anomalies: {'; '.join(anomalies)}") | |
| if failures: | |
| win_reasons.extend(failures) | |
| elif verify_accepted_exit0: | |
| win_reasons.append("strict verify + inspect accepted proof on broken target") | |
| win_reasons.extend(f"spec olean audit violation: {v}" for v in oa_vs) | |
| if not won: | |
| win_reasons = failures | |
| pr = _private_roots() | |
| dedup_obj = dedup.compute_dedup_metadata( | |
| scenario_id=spec.scenario_id, scenario_kind=spec.kind, submission_files=sub.files, | |
| receipt=_sanitize_obj(vr, private_roots=pr), | |
| inspect_report=_sanitize_obj(ir, private_roots=pr), | |
| olean_violations=_sanitize_obj(oa_vs, private_roots=pr), | |
| extra_anomalies=_sanitize_obj(state["dedup_extra_anomalies"], private_roots=pr), | |
| ) if won else None | |
| return _finish( | |
| VERDICT_ATTACKER_WON_ANNEAL_COMPROMISED if won else VERDICT_DEFENDER_HELD_ANNEAL_FAIL_CLOSED, | |
| reasons=win_reasons, | |
| severity="P0" if won else None, dedup_obj=dedup_obj, | |
| stderr_note=("; ".join(win_reasons) or None) if not (verify_accepted_exit0 and not oa_vs) else None, | |
| ) | |
| finally: | |
| for cur_root, dirnames, _ in os.walk(tmp_root, topdown=True, followlinks=False): | |
| for dname in dirnames: | |
| dp = Path(cur_root) / dname | |
| try: | |
| if not dp.is_symlink(): | |
| os.chmod(dp, 0o700) | |
| except OSError: | |
| pass | |
| except DefenderTamperError as exc: | |
| pr = _private_roots() | |
| dedup_obj = dedup.compute_dedup_metadata( | |
| scenario_id=spec.scenario_id, scenario_kind=spec.kind, submission_files=sub.files, | |
| receipt=_sanitize_obj(state["v_receipt"], private_roots=pr), | |
| inspect_report=_sanitize_obj(state["inspect"], private_roots=pr), | |
| audit_report=_sanitize_obj(state.get("repo_audit"), private_roots=pr), | |
| extra_anomalies=_sanitize_obj(state["dedup_extra_anomalies"], private_roots=pr), | |
| compromise_detected=True, compromise_phase=exc.phase, tampered_paths=exc.tampered_paths, | |
| ) | |
| return _finish(VERDICT_ATTACKER_WON_HARNESS_COMPROMISED, reasons=[str(exc)], integrity_ok=False, phase=exc.phase, tampered=exc.tampered_assets, severity="P0", dedup_obj=dedup_obj, stderr_note=str(exc)) | |
| except InvalidSubmissionError as exc: | |
| return _finish(VERDICT_INVALID_SUBMISSION, reasons=[str(exc)], invalid_reason=str(exc), stderr_note=str(exc)) | |
| except (OracleInfrastructureError, OSError, subprocess.SubprocessError, RuntimeError, ValueError, TypeError, KeyError, IndexError, RecursionError, UnicodeError, LookupError) as exc: | |
| return _finish(VERDICT_HARNESS_ERROR, reasons=[str(exc)], stderr_note=str(exc)) | |
| def replay_tripwires(*, expected_bug_id: str | None = None, **evaluate_kwargs: Any) -> tuple[int, dict[str, Any]]: | |
| """Replay a stored witness and confirm reproducible exploit detection.""" | |
| receipt = evaluate_submission(**evaluate_kwargs) | |
| actual = receipt["dedup"].get("bug_id") if isinstance(receipt.get("dedup"), dict) else None | |
| reproduced = receipt["verdict"] in WINNING_VERDICTS and (expected_bug_id is None or actual == expected_bug_id) | |
| payload = {"schema_version": REPLAY_SCHEMA, "reproduced": reproduced, "expected_bug_id": expected_bug_id, "receipt": receipt} | |
| return (2, payload) if receipt["verdict"] == VERDICT_HARNESS_ERROR else ((0 if reproduced else 1), payload) | |
| def _emit_json(data: dict[str, Any], json_out: Path | None) -> None: | |
| encoded = json.dumps(data, indent=2) + "\n" | |
| if json_out is not None: | |
| anneal_ci_lib.atomic_write_text(json_out, encoded) | |
| sys.stdout.write(encoded) | |
| def main(argv: list[str] | None = None) -> int: | |
| """CLI entrypoint for Anneal red-teaming.""" | |
| parser = argparse.ArgumentParser(prog="anneal-redteam", description="Trusted defender evaluation harness for Anneal.") | |
| sub = parser.add_subparsers(dest="command", required=True) | |
| sub.add_parser("list-scenarios").add_argument("--json", action="store_true", required=True) | |
| for name in ("evaluate", "replay-tripwires"): | |
| p = sub.add_parser(name) | |
| p.add_argument("--scenario", required=True) | |
| grp = p.add_mutually_exclusive_group(required=True) | |
| for flag in ("--submission-dir", "--submission-tar"): | |
| grp.add_argument(flag, type=Path) | |
| for flag, kw in (("--json-out", {}), ("--anneal-root", {}), ("--cargo-anneal", {"dest": "cli"}), ("--capture", {}), ("--sysroot", {}), ("--lean", {}), ("--auditor", {})): | |
| p.add_argument(flag, type=Path, **kw) | |
| p.add_argument("--timeout-sec", type=int, default=300) | |
| p.add_argument( | |
| "--isolated-host", action="store_true", default=None, | |
| help="Acknowledge execution inside a credential-free throwaway container/VM when outer bwrap is unavailable.", | |
| ) | |
| if name == "replay-tripwires": | |
| p.add_argument("--expected-bug-id") | |
| args = parser.parse_args(argv) | |
| if args.command == "list-scenarios": | |
| _emit_json(scenarios.list_scenarios_manifest(), None) | |
| return 0 | |
| if args.timeout_sec <= 0: | |
| sys.stderr.write(f"error: --timeout-sec must be positive, got {args.timeout_sec}\n") | |
| return 2 | |
| try: | |
| scenarios.get_scenario(args.scenario) | |
| except KeyError: | |
| sys.stderr.write(f"error: unknown scenario {args.scenario!r}\n") | |
| return 2 | |
| common = {k: getattr(args, k) for k in ("submission_dir", "submission_tar", "anneal_root", "cli", "capture", "sysroot", "lean", "auditor", "timeout_sec", "isolated_host")} | |
| if args.command == "evaluate": | |
| rcpt = evaluate_submission(scenario_id=args.scenario, **common) | |
| _emit_json(rcpt, args.json_out) | |
| return 2 if rcpt["verdict"] == VERDICT_HARNESS_ERROR else 0 | |
| rc, payload = replay_tripwires(scenario_id=args.scenario, expected_bug_id=args.expected_bug_id, **common) | |
| _emit_json(payload, args.json_out) | |
| return rc | |
| if __name__ == "__main__": | |
| sys.exit(main()) |