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 @@ -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
Expand Down
2 changes: 2 additions & 0 deletions src/loopzero/_proc.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ def run(
merge_output: bool = False,
input: str | None = None,
encoding: str | None = None,
pass_fds: tuple[int, ...] = (),
) -> Completed:
"""Run `argv` (never through a shell) with an environment stripped to the allowlist.

Expand All @@ -86,6 +87,7 @@ def run(
text=True,
encoding=encoding,
errors="replace",
pass_fds=pass_fds,
start_new_session=os.name == "posix",
) as proc:
try:
Expand Down
6 changes: 1 addition & 5 deletions src/loopzero/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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']}. "
Expand Down
70 changes: 36 additions & 34 deletions src/loopzero/sandbox.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,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 @@ -288,7 +288,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 @@ -372,12 +372,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:
Expand Down Expand Up @@ -451,16 +448,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"))
Expand All @@ -470,9 +463,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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: Reviewer namespace probe now differs from the real reviewer launch

runners._sandbox_prefix calls sandbox.probe with a reviewer prefix built with clearenv=False, which already carries --setenv arguments. Because probe now goes through _run_bwrap, the reviewer probe also gets an --args stream built from check_environment(review_config), which adds check defaults such as UV_CACHE_DIR. Its host launcher also gets only PATH, while the real reviewer launch gets BASE_ENV. Running true makes this harmless today, but it undercuts the docstring's claim that the probe tests 'the exact sandbox we will use', and reviewers now set environment through two channels. Consider giving probe a flag, or letting the reviewer path call _proc.run directly as before.

except _proc.ToolMissing as exc:
raise SandboxUnavailable(
f"bwrap binary missing while starting the namespace probe: {exc}\n"
Expand All @@ -488,13 +479,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:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: Null-byte check covers values but not names

_run_bwrap rejects values that contain NUL but writes names without checking them. A config.env key containing \0, or =, would shift the NUL-separated option stream and corrupt the options bwrap parses. Before this change, subprocess rejected such names when building argv. Validate name the same way as 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],

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: _run_bwrap silently relies on the prefix ending in "--"

[*prefix[:-1], "--args", ...] assumes the last element of prefix is the -- separator that bwrap_argv appends. If a caller passes a prefix built some other way, or bwrap_argv later adds anything after --, this would drop a real argument without any error. A check-mode prefix is also unusable without _run_bwrap: it has --clearenv but no --setenv, so a direct [*prefix, cmd] launch would run with an empty environment and no PATH. Smallest fix: assert prefix[-1] == "--", or have bwrap_argv return the options without the trailing -- and let _run_bwrap add it.

cwd=worktree, env_allowlist=("PATH",) if "PATH" in config.env_allowlist else (),
timeout=timeout, merge_output=merge_output, pass_fds=(fd,),
)


def bwrap_argv(
Expand All @@ -508,11 +513,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",
Expand Down Expand Up @@ -552,11 +555,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:
Expand Down
59 changes: 49 additions & 10 deletions tests/test_sandbox.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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"),
[
Expand All @@ -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"):
Expand All @@ -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-")
Expand All @@ -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):
Expand Down Expand Up @@ -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):
Expand All @@ -244,13 +281,15 @@ 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
)
(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):
Expand Down
Loading