diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 6d63539f..bee57903 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -174,7 +174,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 1f850468..1d70e76f 100644 --- a/src/loopzero/_proc.py +++ b/src/loopzero/_proc.py @@ -167,6 +167,7 @@ def run( encoding: str | None = None, preserve_newlines: bool = False, tail_chars: int | None = None, + pass_fds: tuple[int, ...] = (), ) -> Completed: """Run `argv` (never through a shell) with an environment stripped to the allowlist. @@ -195,6 +196,7 @@ def run( stderr=subprocess.STDOUT if merge_output else subprocess.PIPE, 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 ccf5cdd5..8e5155a0 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -643,7 +643,7 @@ def cmd_check(args: argparse.Namespace) -> int: print(preview, 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 fdd06721..16f64df7 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 @@ -233,7 +233,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 @@ -356,12 +356,9 @@ def _preflight_alternates(config: Config, worktree: Path, prefix: list[str], com 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: @@ -435,17 +432,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, - tail_chars=CHECK_TAIL_BYTES, + 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, tail_chars=CHECK_TAIL_BYTES) except _proc.ProcTimeout as exc: return CheckResult(command, TIMEOUT_EXIT, timeout, _check_tail(exc.stdout + f"\n[loopzero] timed out after {timeout:g}s")) @@ -455,9 +447,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" @@ -473,13 +463,29 @@ 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, tail_chars: int | None = None, +) -> _proc.Completed: + if not prefix or prefix[-1] != "--": + raise ValueError("sandbox prefix must end at the command separator") + # Keep the environment option stream out of the launcher 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=tail_chars is not None, tail_chars=tail_chars, pass_fds=(fd,), + ) def bwrap_argv( @@ -493,11 +499,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"] if config.network: @@ -533,11 +537,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, paths: bool = False) -> str: diff --git a/tests/test_sandbox.py b/tests/test_sandbox.py index 41d9cbcb..14ff87a0 100644 --- a/tests/test_sandbox.py +++ b/tests/test_sandbox.py @@ -38,6 +38,10 @@ separator = args.index("--") options, command = args[:separator], args[separator + 1:] env = {{}} if "--clearenv" in options else dict(os.environ) +if "--args" in options: + index = options.index("--args") + with os.fdopen(int(options[index + 1]), "rb") as arguments: + options[index:index + 2] = list(map(os.fsdecode, arguments.read().split(b"\\0")[:-1])) home_source = None i = 0 while i < len(options): @@ -147,7 +151,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"): @@ -162,11 +167,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 and "kept" 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-") @@ -183,7 +185,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] @pytest.mark.parametrize("checks", [(), ("echo hello",)], ids=["probe", "stage"]) @@ -210,15 +212,17 @@ def test_extra_paths_and_env_override(git_repo, bwrap_log, tmp_path, monkeypatch extra, cache = tmp_path / "ro", tmp_path / "rw" monkeypatch.setenv("UV_CACHE_DIR", str(cache)) 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 = make_config( + sandbox_ro=(str(extra),), writable=(str(cache),), scratch=(), + env_allowlist=("PATH", "UV_CACHE_DIR", "RUFF_CACHE_DIR"), env=(("RUFF_CACHE_DIR", "cfg"),), + checks=('printf "%s\\n" "$UV_CACHE_DIR" "$RUFF_CACHE_DIR"',), + ) + (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): @@ -235,7 +239,7 @@ def read_output_tail(process, limit, timeout): monkeypatch.setattr(sandbox._proc, "_read_output_tail", read_output_tail) -def test_verbose_stage_bounds_parent_memory(git_repo): +def test_verbose_stage_bounds_parent_memory(git_repo, bwrap_log): command = shlex.join([sys.executable, "-c", """ import os import sys @@ -252,7 +256,7 @@ def test_verbose_stage_bounds_parent_memory(git_repo): try: tracemalloc.reset_peak() baseline, _ = tracemalloc.get_traced_memory() - result = sandbox._run_one(make_config(), git_repo, [], command, 30) + result = sandbox._run_one(make_config(), git_repo, ["bwrap", "--chdir", str(git_repo), "--"], command, 30) _, peak = tracemalloc.get_traced_memory() finally: tracemalloc.stop()