Skip to content
63 changes: 50 additions & 13 deletions src/loopzero/sandbox.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,14 @@
"PYTEST_ADDOPTS": "-p no:cacheprovider",
}

_CHECK_CONTEXT_ENV = {*Config.env_allowlist, "TMP", "TEMP", "TMPDIR", "UV_PYTHON_INSTALL_DIR",
*(name for name in SANDBOX_ENV if name.endswith("_CACHE_DIR"))}
_CHECK_MODES = {"development", "production", "staging", "testing"}
_CREDENTIAL_ENV = re.compile(
r"PASSWORD|PASSWD|PASSPHRASE|(?:^|_)(?:PWD|PIN|PAT|AUTH|TOKEN|SECRET|CREDENTIALS?|COOKIE|"
r"(?:API|ACCESS|PRIVATE)_KEY)(?:_|$)", re.IGNORECASE,
)


class SandboxUnavailable(LoopZeroError):
"""bubblewrap is missing or cannot create a sandbox on this host."""
Expand Down Expand Up @@ -96,7 +104,7 @@ def run_checks(config: Config, worktree: Path, *, timeout: float = DEFAULT_TIMEO
"Runner requires a clean worktree"),))
base = _check_base(config, worktree)
settings_sha256 = settings_fingerprint(config)
previous = _previous(worktree, settings_sha256) if config.inputs and base and settings_sha256 and not dirty else {}
previous = _previous(config, worktree, settings_sha256) if config.inputs and base and settings_sha256 and not dirty else {}
common_dir = _git_dir(config, worktree, "--git-common-dir")
git_dir = _git_dir(config, worktree, "--git-dir")

Expand Down Expand Up @@ -169,7 +177,7 @@ def run_checks(config: Config, worktree: Path, *, timeout: float = DEFAULT_TIMEO
INCOMPLETE_CHECK_COMMAND = "<checks incomplete>"


def _previous(worktree: Path, settings_sha256: str) -> dict[str, CheckResult]:
def _previous(config: Config, worktree: Path, settings_sha256: str) -> dict[str, CheckResult]:
try:
data = json.loads(read_local_state(worktree, "checks.json"))
if (data["dirty"] is not False or not isinstance(data["head"], str)
Expand All @@ -183,7 +191,7 @@ def _previous(worktree: Path, settings_sha256: str) -> dict[str, CheckResult]:
and is_check_exit_code(code) and code == 0 and isinstance(tail, str)):
source = result.get("reused_from")
reused_from = source if isinstance(source, str) else data["head"]
previous[command] = CheckResult(command, 0, 0.0, _check_tail(tail), key, reused_from)
previous[command] = CheckResult(command, 0, 0.0, _check_tail(tail, config), key, reused_from)
return previous
except (OSError, WorktreeError, ValueError, KeyError, TypeError, AttributeError):
return {}
Expand Down Expand Up @@ -418,9 +426,32 @@ def _cap_limit(requested: int, resource_limit: int) -> int:
return requested if hard == resource.RLIM_INFINITY else min(requested, hard)


def _check_tail(text: str) -> str:
suffix = text.rstrip("\n")[-CHECK_TAIL_BYTES:]
encoded = suffix.encode("utf-8", errors="replace")[-CHECK_TAIL_BYTES:]
def _private_check_value(name: str, value: str) -> bool:
if name in _CHECK_CONTEXT_ENV or value == SANDBOX_ENV.get(name):
return False
normalized = value.strip()
if not normalized:
return False
if _CREDENTIAL_ENV.search(name):
return True
mode = name == "ENV" or name.endswith(("_ENV", "_ENVIRONMENT", "_MODE"))
return len(normalized) >= 6 and not (mode and normalized.casefold() in _CHECK_MODES)


def _redact_check_output(config: Config, text: str) -> str:
stage_env = _runner_environment(config) if config.check_runner else check_environment(config)
wrapper_env = _proc.build_env(config.env_allowlist)
secrets = {value for env in (stage_env, wrapper_env) for name, value in env.items()
if _private_check_value(name, value)}
pattern = "|".join(map(re.escape, sorted(secrets, key=len, reverse=True)))
return re.sub(pattern, "[REDACTED]", text) if pattern else text


def _check_tail(text: str, config: Config | None = None, *, suffix: str = "") -> str:
if config is not None:
text = _redact_check_output(config, text)
bounded = (text + suffix).rstrip("\n")[-CHECK_TAIL_BYTES:]
encoded = bounded.encode("utf-8", errors="replace")[-CHECK_TAIL_BYTES:]
# A byte cut can start inside a multibyte character.
return _proc.tail(encoded.decode("utf-8", errors="ignore"))

Expand All @@ -438,8 +469,8 @@ def _run_one(
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"))
return CheckResult(command, done.exit_code, done.duration_s, _check_tail(done.stdout))
_check_tail(exc.stdout, config, suffix=f"\n[loopzero] timed out after {timeout:g}s"))
return CheckResult(command, done.exit_code, done.duration_s, _check_tail(done.stdout, config))


def probe(config: Config, worktree: Path, prefix: list[str]) -> None:
Expand All @@ -461,6 +492,11 @@ def probe(config: Config, worktree: Path, prefix: list[str]) -> None:
raise SandboxUnavailable(f"bwrap namespace creation failed: exit {probe.exit_code}{remedy}")


def _runner_environment(config: Config) -> dict[str, str]:
return {**SANDBOX_ENV, **dict(config.env)}



def check_environment(config: Config) -> dict[str, str]:
return SANDBOX_ENV | _proc.build_env(config.env_allowlist, dict(config.env)) | {"HOME": SANDBOX_HOME}

Expand Down Expand Up @@ -592,7 +628,7 @@ def _stage_frame(stdout: str, binding: dict) -> dict:
def _dispatch_one(
config: Config, worktree: Path, head: str, base: str, command: str, timeout: float,
) -> CheckResult:
env = {**SANDBOX_ENV, **dict(config.env)}
env = _runner_environment(config)
binding = {"worktree": str(worktree.resolve()), "head": head, "base": base, "command": command, "network": config.network,
"env_sha256": hashlib.sha256(json.dumps(
env, sort_keys=True, separators=(",", ":")).encode("utf-8")).hexdigest()}
Expand All @@ -617,7 +653,7 @@ def _dispatch_one(
done = _proc.run(argv, cwd=cwd, env_allowlist=config.env_allowlist, timeout=timeout,
input=json.dumps({**binding, "env": env}), encoding="utf-8")
if done.exit_code:
stderr = _proc.tail(done.stderr)[-2000:]
stderr = _proc.tail(_redact_check_output(config, done.stderr))[-2000:]
detail = f"Stage runner failed: process exit {done.exit_code}"
return CheckResult(command, done.exit_code, done.duration_s,
f"{detail}\n{stderr}".rstrip())
Expand All @@ -635,10 +671,11 @@ def _dispatch_one(
raise ValueError("Local fallback failed")
return local.results[-1]
return CheckResult(command, frame["exit_code"], frame["duration_s"],
_check_tail(frame["tail"]))
_check_tail(frame["tail"], config))
except _proc.ProcTimeout as exc:
return CheckResult(command, TIMEOUT_EXIT,
exc.duration_s if exc.duration_s is not None else timeout,
_check_tail(exc.stdout + f"\n[loopzero] timed out after {timeout:g}s"))
_check_tail(exc.stdout, config, suffix=f"\n[loopzero] timed out after {timeout:g}s"))
except (LoopZeroError, ValueError, TypeError, OverflowError, RecursionError, OSError) as exc:
return CheckResult(command, 1, 0.0, _check_tail(f"Stage runner failed: {exc}"))
detail = _redact_check_output(config, str(exc))
return CheckResult(command, 1, 0.0, _check_tail(f"Stage runner failed: {detail}"))
15 changes: 12 additions & 3 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -500,26 +500,35 @@ def test_check_skips_closed_pr_history(wt, gh, capsys, head, state):
@pytest.mark.parametrize("pushed,refresh_timeout,stage_exit", [
(False, False, 0), (True, False, 0), (True, True, 0), (True, True, 124),
])
def test_check_refresh_preserves_local_verdict(wt, gh, capsys, monkeypatch, pushed, refresh_timeout, stage_exit):
def test_check_refresh_preserves_local_verdict(wt, gh, capsys, monkeypatch, tmp_path, pushed, refresh_timeout, stage_exit):
git(wt, "push", "-q", "-u", "origin", "lz/t1")
arm_pr(gh, head_of(wt))
if not pushed:
git(wt, "commit", "-q", "--allow-empty", "-m", "unpushed change")
options = ()
if stage_exit:
inject_check_timeout(monkeypatch, b"local check output")
monkeypatch.setenv("AUDIT_TOKEN", "ghs_FAKE0123")
private = tmp_path / "private.toml"
private.write_text(WORKFLOW.replace("[checks]", '[checks]\nenv_allowlist = ["PATH", "AUDIT_TOKEN"]'))
options = ("--config", str(private))
inject_check_timeout(monkeypatch, b"local check ghs_FAKE0123 output")
endpoint = f"repos/{REPO}/pulls/7"
gh.respond(f"api {endpoint} --method PATCH", {})
if refresh_timeout:
timeout = cli._proc.ProcTimeout(f"PATCH {endpoint} timed out")
monkeypatch.setattr(github, "update_body", Mock(side_effect=timeout))
code, out, err = run(capsys, "check")
code, out, err = run(capsys, *options, "check")
assert (code, out.splitlines()[-1]) == ((1, "FAIL") if stage_exit else (0, "PASS"))
assert [call["argv"][:2] for call in gh.calls] == LOOKUP_CALLS + (
[["api", endpoint]] if pushed and not refresh_timeout else [])
report = json.loads((wt / ".loopzero/checks.json").read_text())
assert report["head"] == head_of(wt) and report["dirty"] is False
assert report["results"][0]["exit_code"] == stage_exit
assert bool(err) == refresh_timeout
if stage_exit:
assert "local check [REDACTED] output" in err
assert "local check [REDACTED] output" in report["results"][0]["tail"]
assert "ghs_FAKE0123" not in err
if refresh_timeout:
assert f"note: could not refresh PR checks: PATCH {endpoint} timed out" in err
if pushed and not refresh_timeout:
Expand Down
22 changes: 6 additions & 16 deletions tests/test_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,8 @@ def test_missing_file(tmp_path):
config.load(tmp_path / "nope.toml")


MINIMAL = '[repo]\nname = "o/n"\n'
FORBIDDEN = ["/", "/home", "/root", "/run", "/var/run", "/run/user/1000", "/proc/1", "/dev",
"/var/run/docker.sock", "/sys/fs", "/tmp/../run"]


@pytest.mark.parametrize("text,message", [
Expand Down Expand Up @@ -102,6 +103,7 @@ def test_missing_file(tmp_path):
(MINIMAL + '[delivery.review.codex]\nallowed_efforts = "medium"\n',
"allowed_efforts must be a list"),
(MINIMAL + '[checks]\nro_paths = ["rel/path"]\n', "must be absolute"),
*((MINIMAL + table("checks", ro_paths=[path]), "must not expose") for path in FORBIDDEN),
(MINIMAL + '[checks]\nwritable = ["/run/x"]\n', "writable must not expose"),
*((MINIMAL + f'[checks]\nscratch = ["{path}"]\n', "scratch entries must be relative")
for path in ("../x", "/abs")),
Expand All @@ -127,24 +129,12 @@ def test_invalid_content(tmp_path, text, message):
assert str(info.value).startswith(str(tmp_path / "workflow.toml"))


FORBIDDEN = ["/", "/home", "/root", "/run", "/var/run", "/run/user/1000", "/proc/1", "/dev"]
FORBIDDEN += ["/var/run/docker.sock", "/sys/fs", "/tmp/../run"]


@pytest.mark.parametrize("runner", [("dispatch", "--stage"), ("python3", "tools/run_stage.py"),
("dispatch", "--opt=/operator/run.py")])
def test_runner_prefix(tmp_path, runner):
assert config.load(write(tmp_path, MINIMAL + f"[checks]\nrunner = {list(runner)!r}")).check_runner == runner


@pytest.mark.parametrize("path,allowed", [
*((path, False) for path in FORBIDDEN),
*((path, True) for path in ("/home/me/.local/bin", "/opt/tool", "/tmp/x")),
])
def test_ro_path_boundary(tmp_path, path, allowed):
cfg = write(tmp_path, f'[repo]\nname = "o/n"\n[checks]\nro_paths = ["{path}"]\n')
if allowed:
assert config.load(cfg).sandbox_ro == (path,)
else:
with pytest.raises(config.ConfigError, match="must not expose"):
config.load(cfg)
@pytest.mark.parametrize("path", ["/home/me/.local/bin", "/opt/tool", "/tmp/x"])
def test_ro_path_boundary(tmp_path, path):
assert config.load(write(tmp_path, MINIMAL + table("checks", ro_paths=[path]))).sandbox_ro == (path,)
34 changes: 15 additions & 19 deletions tests/test_proc.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,15 +44,6 @@ def run(script, *, timeout=30, env_allowlist=("PATH",), unbuffered=False, args=(
return run


def test_run_strips_environment_to_allowlist(run_python, monkeypatch):
monkeypatch.delenv("LZ_ABSENT", raising=False)
monkeypatch.setenv("LZ_SECRET", "nope")
monkeypatch.setenv("LZ_KEEP", "yes")
done = run_python("import os; print(sorted(k for k in os.environ if k.startswith('LZ_')))",
env_allowlist=("PATH", "LZ_KEEP", "LZ_ABSENT"), extra_env={"LZ_EXTRA": "1"})
assert done.stdout.strip() == "['LZ_EXTRA', 'LZ_KEEP']"


def test_run_raises_tool_missing(tmp_path):
with pytest.raises(_proc.ToolMissing, match="definitely-not-a-tool"):
_proc.run(["definitely-not-a-tool"], cwd=tmp_path, env_allowlist=("PATH",), timeout=30)
Expand Down Expand Up @@ -122,14 +113,21 @@ def communicate(self, input=None, timeout=None):


@pytest.mark.parametrize("merge,stderr", [(True, ""), (False, "b\n")])
def test_run_captures_exit_duration_cwd_and_streams(tmp_path, run_python, merge, stderr):
def test_run_captures_streams_and_allowlisted_environment(tmp_path, run_python, monkeypatch, merge, stderr):
monkeypatch.delenv("LZ_ABSENT", raising=False)
monkeypatch.setenv("LZ_SECRET", "nope")
monkeypatch.setenv("LZ_KEEP", "yes")
done = run_python(
"import os,sys; print(os.getcwd()); print('b', file=sys.stderr); print(sys.argv[1]); sys.exit(3)",
unbuffered=True, merge_output=merge, env_allowlist=(), args=("argument with spaces",),
"import os,sys; print(os.getcwd()); print('b', file=sys.stderr); print(sys.argv[1]); "
"print(sorted(k for k in os.environ if k.startswith('LZ_'))); sys.exit(3)",
unbuffered=True, merge_output=merge, args=("argument with spaces",),
env_allowlist=("PATH", "LZ_KEEP", "LZ_ABSENT"), extra_env={"LZ_EXTRA": "1"},
)
assert (done.exit_code, done.stderr) == (3, stderr)
assert done.duration_s >= 0
assert done.stdout.splitlines() == [str(tmp_path.resolve()), *(["b"] if merge else []), "argument with spaces"]
assert done.stdout.splitlines() == [
str(tmp_path.resolve()), *(["b"] if merge else []), "argument with spaces", "['LZ_EXTRA', 'LZ_KEEP']",
]


def test_tail_keeps_last_lines():
Expand All @@ -138,7 +136,7 @@ def test_tail_keeps_last_lines():
assert _proc.tail("", 3) == ""


def test_explicit_utf8_input_under_ascii_parent_locale(tmp_path):
def test_explicit_utf8_input_under_ascii_parent_locale(run_python):
source = str(Path(_proc.__file__).resolve().parents[1])
script = r"""
import locale, sys
Expand All @@ -150,10 +148,8 @@ def test_explicit_utf8_input_under_ascii_parent_locale(tmp_path):
assert _proc.run(argv, input='\u03a9', **options).stdout.strip() == '3f'
print(_proc.run(argv, input='\u03a9\r\n\u2028\r', encoding='utf-8', **options).stdout.strip())
"""
done = _proc.run(
[sys.executable, "-c", script], cwd=tmp_path, env_allowlist=(), timeout=30,
extra_env={"PYTHONPATH": source, "LC_ALL": "C", "PYTHONUTF8": "0",
"PYTHONCOERCECLOCALE": "0"},
)
done = run_python(script, env_allowlist=(), extra_env={
"PYTHONPATH": source, "LC_ALL": "C", "PYTHONUTF8": "0", "PYTHONCOERCECLOCALE": "0",
})
assert done.exit_code == 0, done.stderr
assert done.stdout.strip() == "Ω\r\n\u2028\r".encode("utf-8").hex()
23 changes: 17 additions & 6 deletions tests/test_sandbox.py
Original file line number Diff line number Diff line change
Expand Up @@ -542,8 +542,13 @@ def test_silent_stage_reports_live_metadata_then_completion(

events, _, status, wait_for_heartbeat = heartbeat_log
monkeypatch.setenv("LZ_KEEP", "credential-value")
command = f'echo "$LZ_KEEP"; echo private-stderr >&2; exit {exit_code}'
cfg = make_config(checks=(command, "echo next"))
monkeypatch.setenv("AUDIT_TOKEN", "p1n")
monkeypatch.setenv("RUST_BACKTRACE", "1")
command = ('test -z "$LZ_KEEP" || echo "$LZ_KEEP"; echo "$AUDIT_TOKEN"; '
'echo "tests/test_example.py:12: $RUST_BACKTRACE $NODE_ENV $DJANGO_DEBUG" >&2; '
f'exit {exit_code}')
cfg = make_config(checks=(command, "echo next"), env_allowlist=("PATH", "AUDIT_TOKEN", "RUST_BACKTRACE"),
env=(("NODE_ENV", "test"), ("DJANGO_DEBUG", "true")))
run_one = sandbox._run_one

def run_stage(config, worktree, prefix, stage_command, timeout):
Expand All @@ -554,15 +559,15 @@ def run_stage(config, worktree, prefix, stage_command, timeout):
monkeypatch.setattr(sandbox, "_run_one", run_stage)
report = sandbox.run_checks(cfg, git_repo, progress=events.append, status=status)
assert report.results[0].exit_code == exit_code
assert report.results[0].tail == "credential-value\nprivate-stderr"
assert report.results[0].tail == "[REDACTED]\ntests/test_example.py:12: 1 test true"
statuses = [event for event in events if event not in cfg.checks]
heartbeats = [event for event in statuses if "running" in event]
assert heartbeats and all(re.fullmatch(
r"stage [12]/2: running \([0-9]+\.[0-9]s elapsed\)", event
) for event in heartbeats)
completion = next(event for event in statuses if f"exit {exit_code}" in event)
assert re.fullmatch(rf"stage 1/2: exit {exit_code} \([0-9]+\.[0-9]s\)", completion)
assert all("private" not in event and "credential-value" not in event for event in statuses)
assert all("tests/test_example.py" not in event and "p1n" not in event for event in statuses)
assert any(event.startswith("stage 1/2: running") for event in statuses)
assert all(not event.startswith("stage 1/2: running")
for event in events[events.index(completion) + 1:])
Expand Down Expand Up @@ -728,7 +733,7 @@ def cache(config, *, clean=False, verify_reuse=False):
'failed', 'boolean_exit_code', 'dirty_receipt', 'keyless',
'dirty_tree', 'legacy', 'grant'])
def test_declared_input_reuse(git_repo, bwrap_log, monkeypatch, fetched_base, change, cache_check, receipt_path):
cfg = make_config(checks=('echo one', 'echo two'),
cfg = make_config(checks=('echo one', 'echo two'), env=(('AUDIT_TOKEN', 'fake-cached-token'), ('NODE_ENV', 'test')),
inputs={'echo one': ('*.md',), 'echo two': ('*.md',), '*': ('shared',)})
if change == 'grant':
cfg = replace(cfg, env_allowlist=(*cfg.env_allowlist, "HEAVY_SLOT_GRANTED_CORES"))
Expand All @@ -738,7 +743,9 @@ def test_declared_input_reuse(git_repo, bwrap_log, monkeypatch, fetched_base, ch
whole = replace(cfg, inputs={'*': ('.',)})
key = sandbox._input_key(whole, git_repo, 'unlisted', fetched_base)
assert key is not None
cache_check(cfg, clean=True)
first = cache_check(cfg, clean=True)
original_tails = tuple(replace(r, tail=f"{r.tail} tests/test_example.py:12 fake-cached-token") for r in first.results)
_save_report(git_repo, replace(first, results=original_tails))
if change in {'other', 'input', 'shared', 'dirty_tree'}:
path = 'README.md' if change in {'input', 'dirty_tree'} else 'src.py' if change == 'other' else change
(git_repo / path).write_text('new content')
Expand Down Expand Up @@ -776,6 +783,10 @@ def test_declared_input_reuse(git_repo, bwrap_log, monkeypatch, fetched_base, ch
report = sandbox.run_checks(cfg, git_repo, status=(messages := []).append)
assert [r.command for r in report.results] == list(cfg.checks)
assert all(bool(r.reused_from) == (change == 'other') for r in report.results)
if change == 'other':
assert [r.tail for r in report.results] == [
'one tests/test_example.py:12 [REDACTED]', 'two tests/test_example.py:12 [REDACTED]',
]
assert any('reused ' in m for m in messages) == (change == 'other')
assert report.head == git(git_repo, 'rev-parse', 'HEAD').strip()

Expand Down
Loading
Loading