Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 2 additions & 0 deletions src/loopzero/_proc.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down Expand Up @@ -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:
Expand Down
11 changes: 8 additions & 3 deletions src/loopzero/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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']}. "
Expand Down Expand Up @@ -1401,18 +1401,22 @@ def _merge_check_hint(config: Config, pr: github.PR, readiness: github.Readiness


def _poll_until(
started: float, timeout: float, *, bounded: bool = False, initial_read_time: float = 0.0,
started: float, timeout: float, *, bounded: bool = False,
initial_read_time: float = 0.0, admitted: Callable[[], bool] | None = None,
) -> Iterator[None]:
delay = WAIT_INTERVAL
longest_read = initial_read_time
while True:
was_admitted = admitted is not None and admitted()
read_started = time.monotonic()
yield # Observe immediately, including --wait=0.
now = time.monotonic()
longest_read = max(longest_read, now - read_started)
remaining = timeout - (now - started)
if remaining <= 0:
return
if admitted is not None and not was_admitted and admitted():
delay = WAIT_INTERVAL
pause = delay * random.uniform(0.9, 1.0)
if bounded and remaining <= pause:
# Poll late enough to see a settled check while reserving time to read it.
Expand Down Expand Up @@ -1670,7 +1674,8 @@ def _wait_for_mergify(
state = None
deferred_landing_read = False
print(f"PR #{pr.number} following Mergify queue {queue}; head {pr.head_sha[:12]}; waiting up to {timeout:g}s")
for _ in _poll_until(started, timeout):
polls = _poll_until(started, timeout, admitted=lambda: confirmed)
for _ in polls:
sha = _landed(config, pr, closed)
if sha:
return sha
Expand Down
73 changes: 38 additions & 35 deletions src/loopzero/sandbox.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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


Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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"))
Expand All @@ -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"
Expand All @@ -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(
Expand All @@ -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:
Expand Down Expand Up @@ -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:
Expand Down
30 changes: 15 additions & 15 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -4408,7 +4408,8 @@ def test_ready_pins_review_publishers_to_base(wt, repo, gh, capsys, monkeypatch,
assert json.loads(gh.calls[-1]["--input"])["state"] == ("success" if publisher == LOGIN else "pending")


def test_mergify_confirmed_wait_reads_pr_once_per_steady_poll(wt, gh, monkeypatch):
@pytest.mark.parametrize("confirmed", [True, False])
def test_mergify_confirmed_wait_reads_pr_once_per_steady_poll(wt, gh, monkeypatch, confirmed):
head = commit_mergify_configuration(wt)
config = cli.config_mod.load_trusted(wt)
pr = github.PR(7, URL, head, "main", False, "OPEN", "MERGEABLE")
Expand All @@ -4420,22 +4421,21 @@ def test_mergify_confirmed_wait_reads_pr_once_per_steady_poll(wt, gh, monkeypatc

def membership(*_):
reads_at_membership.append(len(gh.calls))
if clock.now == 60:
if confirmed and clock.now == 60:
gh.respond(" ".join(detail), merge_json(state="MERGED", head=head, sha="e" * 40))
return mergify.Membership()

def configured(*args):
configurations.append(args)
return True
return mergify.Membership() if confirmed or clock.now >= 210 else None

monkeypatch.setattr(mergify, "configured", configured)
monkeypatch.setattr(mergify, "configured", lambda *args: configurations.append(args) or True)
monkeypatch.setattr(mergify, "mark_confirmed", lambda *_: gh.respond(
" ".join(detail), merge_json(state="MERGED", head=head, sha="e" * 40)))
monkeypatch.setattr(mergify, "membership", membership)

assert cli._wait_for_mergify(config, pr, 60, confirmed=True) == "e" * 40
assert clock.sleeps == [30, 30]
assert configurations == [(REPO, "main", "main")] * 3
assert reads_at_membership == [1, 2, 3]
assert [c["argv"][:2] for c in gh.calls] == [detail] * 4
assert cli._wait_for_mergify(config, pr, 60 if confirmed else 360, confirmed=confirmed) == "e" * 40
assert clock.sleeps == ([30, 30] if confirmed else [30, 60, 120, 30])
assert configurations == [(REPO, "main", "main")] * (3 if confirmed else 4)
assert reads_at_membership == ([1, 2, 3] if confirmed else [1, 4, 7, 10])
assert sum(c["argv"][:2] == detail for c in gh.calls) == (4 if confirmed else 9)
assert len(gh.calls) == (4 if confirmed else 12)


@pytest.mark.parametrize("outcome,jitter", [
Expand Down Expand Up @@ -4508,9 +4508,9 @@ def membership(*_):
if outcome == "worktree_removed":
poll_until = cli._poll_until

def remove_worktree_then_poll(*args):
def remove_worktree_then_poll(*args, **kwargs):
git(repo, "worktree", "remove", "--force", str(wt))
return poll_until(*args)
return poll_until(*args, **kwargs)

monkeypatch.setattr(cli, "_poll_until", remove_worktree_then_poll)
try:
Expand Down
32 changes: 18 additions & 14 deletions tests/test_sandbox.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -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"):
Expand All @@ -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-")
Expand All @@ -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"])
Expand All @@ -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):
Expand All @@ -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
Expand All @@ -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()
Expand Down
Loading