From fb7e54e424310df10dafc8fc8d366ff40ac911d6 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 03:49:41 +0100 Subject: [PATCH] Pass check environment through a private descriptor Co-Authored-By: Codex --- docs/ARCHITECTURE.md | 4 ++- src/loopzero/_proc.py | 2 ++ src/loopzero/cli.py | 6 +--- src/loopzero/sandbox.py | 70 +++++++++++++++++++++-------------------- tests/test_sandbox.py | 59 ++++++++++++++++++++++++++++------ 5 files changed, 91 insertions(+), 50 deletions(-) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 560b2481..86cff58c 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -149,7 +149,9 @@ person / agent session / T3 workspace ``` The [sandbox](../src/loopzero/sandbox.py) bounds check writes, credentials, -network access and resources. [Reviewer runners](../src/loopzero/runners.py) +network access and resources. Checks and their Bubblewrap probes pass +sandbox environment settings over a private file descriptor, keeping +forwarded values out of process arguments. [Reviewer runners](../src/loopzero/runners.py) bound source access while allowing the network required by model CLIs; that network means the sandbox cannot prevent exfiltration of readable data. For a Codex executable installed inside protected native state, the implicit diff --git a/src/loopzero/_proc.py b/src/loopzero/_proc.py index 3bfaf9a0..3f7507dd 100644 --- a/src/loopzero/_proc.py +++ b/src/loopzero/_proc.py @@ -116,6 +116,7 @@ def run( input: str | None = None, encoding: str | None = None, preserve_newlines: bool = False, + pass_fds: tuple[int, ...] = (), ) -> Completed: """Run `argv` (never through a shell) with an environment stripped to the allowlist. @@ -141,6 +142,7 @@ def run( text=not preserve_newlines, encoding=None if preserve_newlines else encoding, errors=None if preserve_newlines else "replace", + pass_fds=pass_fds, start_new_session=os.name == "posix", ) as proc: try: diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index df90da9c..e49d358d 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -609,11 +609,7 @@ def cmd_check(args: argparse.Namespace) -> int: print(tail, file=sys.stderr) if not config.network and (result.command.startswith("uv sync --offline --locked") or OFFLINE_FAILURE_RE.search(tail)): - env = { - **sandbox.SANDBOX_ENV, - **_proc.build_env(config.env_allowlist), - **dict(config.env), - } + env = sandbox.check_environment(config) print( "\nThe sandbox has no network because `[checks] network = false`; " f"the effective UV_CACHE_DIR inside the sandbox is {env['UV_CACHE_DIR']}. " diff --git a/src/loopzero/sandbox.py b/src/loopzero/sandbox.py index f74eed7e..2d7ff239 100644 --- a/src/loopzero/sandbox.py +++ b/src/loopzero/sandbox.py @@ -15,7 +15,7 @@ import tempfile import threading import time -from collections.abc import Callable +from collections.abc import Callable, Sequence from contextlib import ExitStack, contextmanager from dataclasses import asdict, replace from os.path import commonpath @@ -238,7 +238,7 @@ def _execution_settings(config: Config, base: str) -> dict: settings["runner_executable"] = _runner_identity(config) settings["environment"] = _proc.build_env(config.env_allowlist) else: - settings["environment"] = _sandbox_environment(config) + settings["environment"] = check_environment(config) return settings @@ -322,12 +322,9 @@ def _preflight_alternates(config: Config, worktree: Path, prefix: list[str]) -> remedy = (f"Git object alternate {alternate!r} is not readable in the check sandbox. " "Create a standalone clone without --shared/--reference, then run " "loopzero start there and rerun loopzero check.") + command = ("/bin/sh", "-c", 'test -d "$1" && test -r "$1" && test -x "$1"', "loopzero-alternate", alternate) try: - result = _proc.run( - [*prefix, "/bin/sh", "-c", 'test -d "$1" && test -r "$1" && test -x "$1"', - "loopzero-alternate", alternate], - cwd=worktree, env_allowlist=config.env_allowlist, timeout=GIT_TIMEOUT, - ) + result = _run_bwrap(config, worktree, prefix, command, timeout=GIT_TIMEOUT) except _proc.ProcTimeout: raise SandboxUnavailable(f"Git alternate visibility probe timed out. {remedy}") from None if result.exit_code != 0: @@ -401,16 +398,12 @@ def _run_one( ) -> CheckResult: try: limits = config.limits - done = _proc.run( - [*prefix, "prlimit", - f"--as={_cap_limit(limits.memory_mb * 1024 * 1024, resource.RLIMIT_AS)}", - f"--fsize={_cap_limit(limits.file_mb * 1024 * 1024, resource.RLIMIT_FSIZE)}", - "--", *CHECK_SHELL, command], - cwd=worktree, - env_allowlist=config.env_allowlist, - timeout=timeout, - merge_output=True, + argv = ( + "prlimit", f"--as={_cap_limit(limits.memory_mb * 1024 * 1024, resource.RLIMIT_AS)}", + f"--fsize={_cap_limit(limits.file_mb * 1024 * 1024, resource.RLIMIT_FSIZE)}", + "--", *CHECK_SHELL, command, ) + done = _run_bwrap(config, worktree, prefix, argv, timeout=timeout, merge_output=True) except _proc.ProcTimeout as exc: return CheckResult(command, TIMEOUT_EXIT, timeout, _check_tail(exc.stdout + f"\n[loopzero] timed out after {timeout:g}s")) @@ -420,9 +413,7 @@ def _run_one( def probe(config: Config, worktree: Path, prefix: list[str]) -> None: """Raise `SandboxUnavailable` unless bwrap can build the exact sandbox we will use.""" try: - probe = _proc.run( - [*prefix, "true"], cwd=worktree, env_allowlist=config.env_allowlist, timeout=GIT_TIMEOUT - ) + probe = _run_bwrap(config, worktree, prefix, ("true",), timeout=GIT_TIMEOUT) except _proc.ToolMissing as exc: raise SandboxUnavailable( f"bwrap binary missing while starting the namespace probe: {exc}\n" @@ -438,13 +429,27 @@ def probe(config: Config, worktree: Path, prefix: list[str]) -> None: raise SandboxUnavailable(f"bwrap namespace creation failed: exit {probe.exit_code}{remedy}") -def _sandbox_environment(config: Config) -> dict[str, str]: - return { - **SANDBOX_ENV, - **_proc.build_env(config.env_allowlist), - **dict(config.env), - "HOME": SANDBOX_HOME, - } +def check_environment(config: Config) -> dict[str, str]: + return SANDBOX_ENV | _proc.build_env(config.env_allowlist, dict(config.env)) | {"HOME": SANDBOX_HOME} + + +def _run_bwrap( + config: Config, worktree: Path, prefix: list[str], command: Sequence[str], + *, timeout: float, merge_output: bool = False, +) -> _proc.Completed: + # Apply settings inside bwrap without exposing the option stream in argv. + with tempfile.TemporaryFile() as options: + for name, value in check_environment(config).items(): + if "\0" in value: + raise ValueError("embedded null byte in check environment") + options.write(os.fsencode(f"--setenv\0{name}\0{value}\0")) + options.seek(0) + fd = options.fileno() + return _proc.run( + [*prefix[:-1], "--args", str(fd), "--", *command], + cwd=worktree, env_allowlist=("PATH",) if "PATH" in config.env_allowlist else (), + timeout=timeout, merge_output=merge_output, pass_fds=(fd,), + ) def bwrap_argv( @@ -458,11 +463,9 @@ def bwrap_argv( clearenv: bool = True, writable_binds: tuple[tuple[Path, Path], ...] = (), ) -> list[str]: - """Build the bwrap command line up to and including the `--` separator. + """Build mounts and environment options before the command separator. - With ``clearenv=False`` the caller's (already filtered) environment is inherited - instead of cleared, so secrets never appear as ``--setenv`` arguments. - ``writable_binds`` overlays specific paths inside the otherwise private HOME. + Reviewers inherit their filtered environment and apply sandbox defaults. """ argv = [ "bwrap", "--die-with-parent", "--new-session", "--unshare-all", @@ -502,11 +505,10 @@ def bwrap_argv( for entry, source in (scratch or {}).items(): argv += ["--bind", str(source), str(worktree / entry)] argv += ["--chdir", str(worktree), *(["--clearenv"] if clearenv else [])] - for key, value in _sandbox_environment(config).items(): - if key != "HOME": + if not clearenv: + for key, value in check_environment(config).items(): argv += ["--setenv", key, value] - argv += ["--setenv", "HOME", SANDBOX_HOME, "--"] - return argv + return [*argv, "--"] def _git(config: Config, worktree: Path, *args: str) -> str: diff --git a/tests/test_sandbox.py b/tests/test_sandbox.py index 5e805278..5d1fe3e5 100644 --- a/tests/test_sandbox.py +++ b/tests/test_sandbox.py @@ -37,6 +37,11 @@ home_source = None i = 0 while i < len(options): + if options[i] == "--args": + with os.fdopen(int(options[i + 1]), "rb") as arguments: + extra = [os.fsdecode(arg) for arg in arguments.read().split(b"\\0")[:-1]] + options[i:i + 2] = extra + continue if options[i] == "--setenv": env[options[i + 1]] = options[i + 2] i += 3 @@ -119,6 +124,37 @@ def test_tail_merges_streams_and_truncates(git_repo, bwrap_log, command, exit_co assert len(result.tail.encode("utf-8")) <= 16 * 1024 +def test_check_environment_values_stay_out_of_launcher_arguments( + git_repo, bwrap_log, tmp_path, monkeypatch, +): + secret = "synthetic-forwarded-value" + monkeypatch.setenv("LZ_KEEP", secret) + monkeypatch.setenv("LZ_DROP", "synthetic-unlisted-value") + alternate = tmp_path / "alternate" + alternate.mkdir() + (git_repo / ".git/objects/info/alternates").write_text(f"{alternate}\n") + real_run = sandbox._proc.run + launchers = [] + + def record(argv, **kwargs): + if argv[0] == "bwrap": + launchers.append(tuple(argv[argv.index("--") + 1:])) + assert secret not in argv + assert "LZ_KEEP" not in kwargs["env_allowlist"] + (fd,) = kwargs["pass_fds"] + assert os.pread(fd, 65536, 0).split(b"\0").count(secret.encode()) == 1 + return real_run(argv, **kwargs) + + monkeypatch.setattr(sandbox._proc, "run", record) + command = 'test -n "$LZ_KEEP" && test -z "$LZ_DROP" && test -d "$HOME" && test "$HOME" != "$PWD"' + report = sandbox.run_checks(make_config(checks=(command,)), git_repo) + + assert report.ok + assert [argv[0] for argv in launchers] == ["true", "/bin/sh", "prlimit"] + assert secret not in bwrap_log.read_text() + assert "synthetic-unlisted-value" not in bwrap_log.read_text() + + @pytest.mark.parametrize( ("command", "stage_exit"), [ @@ -142,7 +178,8 @@ def test_check_pipeline_verdict(git_repo, bwrap_log, monkeypatch, capsys, comman def test_bwrap_flags(git_repo, bwrap_log, monkeypatch): monkeypatch.setenv("LZ_KEEP", "kept") monkeypatch.setenv("LZ_DROP", "dropped") - sandbox.run_checks(make_config(), git_repo) + values = 'printf "%s\\n" "$PATH" "$LZ_KEEP" "${LZ_DROP-unset}" "$UV_CACHE_DIR" "$PYTHONDONTWRITEBYTECODE"' + (result,) = sandbox.run_checks(make_config(checks=(values,)), git_repo).results argv = argv_of(bwrap_log) head, tail = argv[: argv.index("--")], argv[argv.index("--") + 1 :] for flag in ("--die-with-parent", "--new-session", "--unshare-all", "--clearenv"): @@ -157,11 +194,8 @@ def test_bwrap_flags(git_repo, bwrap_log, monkeypatch): assert all(("--tmpfs", p) in windows for p in ("/tmp", "/run", "/var/run")) assert ("--dev", "/dev") in windows and ("--proc", "/proc") in windows assert head[head.index("--chdir") + 1] == str(git_repo) - setenv = dict(_pairs(head, "--setenv")) - assert setenv["PATH"] == os.environ["PATH"] and setenv["LZ_KEEP"] == "kept" - assert "LZ_DROP" not in setenv - assert setenv["HOME"] == sandbox.SANDBOX_HOME - assert setenv["UV_CACHE_DIR"] == "/tmp/uv-cache" and setenv["PYTHONDONTWRITEBYTECODE"] == "1" + assert "--args" in head and "--setenv" not in head + assert result.tail.splitlines() == [os.environ["PATH"], "kept", "unset", "/tmp/uv-cache", "1"] binds = _pairs(head, "--bind") home_src, home_dst = binds[0] assert home_dst == sandbox.SANDBOX_HOME and Path(home_src).name.startswith("loopzero-home-") @@ -178,7 +212,7 @@ def test_bwrap_flags(git_repo, bwrap_log, monkeypatch): assert head.index("--tmpfs") < head.index(str(git_repo)) assert tail == ["prlimit", f"--as={sandbox._cap_limit(4096 << 20, resource.RLIMIT_AS)}", f"--fsize={sandbox._cap_limit(2048 << 20, resource.RLIMIT_FSIZE)}", - "--", "/bin/bash", "--posix", "-o", "pipefail", "-c", "echo hello"] + "--", *sandbox.CHECK_SHELL, values] def test_probe_uses_real_flags(git_repo, bwrap_log): @@ -216,13 +250,16 @@ def test_extra_paths_and_env_override(git_repo, bwrap_log, tmp_path, monkeypatch monkeypatch.setenv("RUFF_CACHE_DIR", "host-ruff") cfg = make_config(sandbox_ro=(str(extra),), writable=(str(cache),), scratch=()) cfg = Config(**{**cfg.__dict__, "env_allowlist": ("PATH", "UV_CACHE_DIR", "RUFF_CACHE_DIR")}) - sandbox.run_checks(Config(**{**cfg.__dict__, "env": (("RUFF_CACHE_DIR", "cfg"),)}), git_repo) + cfg = replace( + cfg, checks=('printf "%s\\n" "$UV_CACHE_DIR" "$RUFF_CACHE_DIR"',), + env=(("RUFF_CACHE_DIR", "cfg"),), + ) + (result,) = sandbox.run_checks(cfg, git_repo).results argv = argv_of(bwrap_log) assert _pairs(argv, "--ro-bind-try") == [(str(extra),) * 2] assert _pairs(argv, "--bind-try") == [(str(cache),) * 2] assert len(_pairs(argv, "--bind")) == 1 # only HOME; no scratch - setenv = dict(_pairs(argv, "--setenv")) # defaults < host allowlist < config.env - assert (setenv["UV_CACHE_DIR"], setenv["RUFF_CACHE_DIR"]) == (str(cache), "cfg") + assert result.tail.splitlines() == [str(cache), "cfg"] def test_temp_parent_cannot_be_exposed(git_repo, bwrap_log): @@ -244,6 +281,7 @@ def communicate_with_timeout(process, input=None, timeout=None): def test_timeout_is_recorded_not_raised(git_repo, bwrap_log, monkeypatch): + monkeypatch.setenv("LZ_KEEP", "synthetic-timeout-value") inject_check_timeout(monkeypatch, b"x" * 20_000 + b"partial") report = sandbox.run_checks( make_config(checks=("echo partial", "echo after")), git_repo, timeout=0.3 @@ -251,6 +289,7 @@ def test_timeout_is_recorded_not_raised(git_repo, bwrap_log, monkeypatch): (first,) = report.results assert (first.exit_code, len(first.tail.encode("utf-8"))) == (sandbox.TIMEOUT_EXIT, 16 * 1024) assert "partial\n[loopzero] timed out" in first.tail and not report.ok + assert "synthetic-timeout-value" not in first.tail def test_configured_resource_limits_are_converted_to_bytes(git_repo, bwrap_log, monkeypatch):