Skip to content
Merged
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
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 @@ -408,9 +416,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):

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: Credential-named variables with very short values remove ordinary text everywhere

_private_check_value treats any non-empty value as secret when the variable name matches _CREDENTIAL_ENV, however short the value is. The test even expects the 3-character value p1n to be redacted. If a project forwards a credential-named flag such as DISABLE_AUTH=1, SKIP_AUTH=true or HF_HUB_DISABLE_TOKEN=1, _redact_check_output replaces every 1 or true in the stage output. That mangles line numbers, counts and messages like tests/x.py:[REDACTED]2, which goes against the acceptance criterion "Preserve ordinary diagnostic text". Smallest fix: skip trivial values in the credential branch too, such as a minimum length of about 3–4 characters plus a check that excludes plain numbers and booleans.

return True
mode = name == "ENV" or name.endswith(("_ENV", "_ENVIRONMENT", "_MODE"))
return len(normalized) >= 6 and not (mode and normalized.casefold() in _CHECK_MODES)

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: Every forwarded value of 6+ characters is redacted, including paths and usernames

Any variable outside _CHECK_CONTEXT_ENV whose value has at least 6 characters is treated as a secret. Common allowlisted or configured variables hold paths or identities, such as USER, CARGO_HOME, GOPATH, JAVA_HOME, VIRTUAL_ENV, PYTHONPATH and SHELL=/bin/bash. Their values then get replaced inside tracebacks and compiler errors. For example, with USER=marcin allowlisted, the worktree path becomes /home/[REDACTED]/.... Verdicts are unaffected, but diagnostics become harder to use. Consider not redacting values that are absolute paths, or names ending in _HOME, _PATH or _DIR, in the non-credential branch. Alternatively, document the trade-off and test a path-valued variable so the behavior is intentional.



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 @@ -428,8 +459,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"))

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: Redaction happens after _proc.run has already cut the output, so part of a secret can survive

_run_one passes tail_chars=CHECK_TAIL_BYTES to _proc.run, so the output is cut to its last 16K characters before _check_tail redacts it. If a secret straddles that cut, the remaining fragment no longer matches the full value and is kept. This shows up in the retained tail when the output is long but has few lines (single-line or minified output), because _proc.tail then keeps that first line. The same applies to runner-provided frame["tail"] and the ProcTimeout.stdout paths. Smallest fix: before redacting, drop the first partial line (or the first max(len(secret)) characters) of a tail that was cut, or redact any secret prefix found at the very start of the text.

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 @@ -451,6 +482,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)}


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: Extra blank line left from conflict resolution

The merge kept the + blank line from the conflict block, so _runner_environment and check_environment are now separated by three blank lines instead of two. The ruff config doesn't select E3, so lint still passes and nothing changes at runtime. To fix, delete the extra blank line.


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 @@ -582,7 +618,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 @@ -607,7 +643,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 @@ -625,10 +661,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 @@ -498,26 +498,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
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
28 changes: 17 additions & 11 deletions tests/test_stage_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,12 @@


@pytest.mark.parametrize('base_ref,body,verdict,tails', [
*[(base_ref, 'print(json.dumps(r))', True, ['ok', 'ok']) for base_ref in ('stale', 'missing', 'recorded', 'abs-link', 'path-link')],
('stale', 'r["exit_code"]=7;print(json.dumps(r))', False, ['ok']),
('stale', 'print("x" * 3000 + "worker socket unavailable", file=sys.stderr);sys.exit(42)', False, None),
*[(base_ref, 'r["tail"]=" ".join((env["UV_CACHE_DIR"],env["NODE_ENV"],env["AUDIT_VALUE"],os.environ["AUDIT_VALUE"]));print(json.dumps(r))',
True, ['/operator/cache production [REDACTED] [REDACTED]'] * 2) for base_ref in ('stale', 'missing', 'recorded', 'abs-link', 'path-link')],
('stale', 'r["exit_code"]=7;r["tail"]="ok "+env["AUDIT_VALUE"];print(json.dumps(r))', False, ['ok [REDACTED]']),
('stale', 'print("x" * 3000 + "worker socket unavailable " + env["AUDIT_VALUE"], file=sys.stderr);sys.exit(42)', False, None),
('stale', 'r["exit_code"]=7;r["tail"]=env["AUDIT_VALUE"]+"Ω"*8183+" newest";print(json.dumps(r))', False,
['[REDACTED]' + 'Ω' * 8183 + ' newest']),
('stale', 'r["exit_code"]=7;r["tail"]="Ω"*10000+" newest";print(json.dumps(r))', False,
['Ω' * 8188 + ' newest']),
('stale', 'subprocess.run(["git","-C",repo,"-c","user.name=test","-c","user.email=t@e","commit","--allow-empty","-m","drift"],stdout=sys.stderr,check=True);print(json.dumps(r))', False, None),
Expand All @@ -47,14 +50,16 @@ def test_runner(git_repo, tmp_path, bwrap_log, monkeypatch, body, verdict, tails
git(git_repo, 'update-ref', 'refs/remotes/origin/main', base)
if base_ref == 'missing':
git(git_repo, 'branch', '-D', 'main')
expected = dict(sandbox.SANDBOX_ENV, UV_CACHE_DIR="/operator/cache")
monkeypatch.setenv("AUDIT_VALUE", "opaque-fake-wrapper-password")
configured = {"UV_CACHE_DIR": "/operator/cache", "NODE_ENV": "production", "AUDIT_VALUE": "opaque-fake-db-password"}
expected = dict(sandbox.SANDBOX_ENV, **configured)
body = (f'repo=r["worktree"]\nassert r["base"] == "{base}"\n'
'assert not Path.cwd().is_relative_to(Path(repo))\n'
f'assert r.pop("env") == {expected!r} and r["network"] is True\n'
f'env=r.pop("env");assert env == {expected!r} and r["network"] is True\n'
f'assert r["env_sha256"] == hashlib.sha256(json.dumps({expected!r},'
'sort_keys=True,separators=(",", ":")).encode()).hexdigest()\n' + body)
path = tmp_path / 'runner.py'
preamble = 'import hashlib,json,sys,subprocess\nfrom pathlib import Path\nr=json.load(sys.stdin)\n'
preamble = 'import hashlib,json,os,sys,subprocess\nfrom pathlib import Path\nr=json.load(sys.stdin)\n'
launcher = (sys.executable, str(path))
if base_ref in ('abs-link', 'path-link'):
link = tmp_path / 'runner-python'
Expand All @@ -65,15 +70,15 @@ def test_runner(git_repo, tmp_path, bwrap_log, monkeypatch, body, verdict, tails
path.write_text(preamble + STAGE_FIELDS.format(fallback=False, tail='ok') + '\n' + body)
calls = []
report = sandbox.run_checks(make_config(checks=('echo one', 'echo two'),
env=(("UV_CACHE_DIR", "/operator/cache"),), network=True,
env=tuple(configured.items()), env_allowlist=("PATH", "AUDIT_VALUE"), network=True,
check_runner=launcher), git_repo, progress=calls.append)
assert report.ok is verdict
if 'exit_code"]=7' in body:
assert report.results[0].exit_code == 7
if 'sys.exit(42)' in body:
result = report.results[0]
assert result.exit_code == 42 and result.duration_s > 0
assert result.tail == 'Stage runner failed: process exit 42\n' + ('x' * 3000 + 'worker socket unavailable')[-2000:]
assert result.tail == 'Stage runner failed: process exit 42\n' + ('x' * 3000 + 'worker socket unavailable [REDACTED]')[-2000:]
if tails is not None:
assert [r.tail for r in report.results] == tails
if not verdict:
Expand Down Expand Up @@ -134,14 +139,15 @@ def test_runner_timeout(git_repo, monkeypatch, fetched_base): # noqa: F811
original = sandbox._proc.run
def run(argv, **kwargs):
if argv[0] == sys.executable:
raise sandbox._proc.ProcTimeout('deadline', 'partial', duration_s=0.25)
raise sandbox._proc.ProcTimeout('deadline', 'partial opaque-fake-db-password', duration_s=0.25)
return original(argv, **kwargs)
monkeypatch.setattr(sandbox._proc, 'run', run)
report = sandbox.run_checks(make_config(check_runner=(sys.executable,)), git_repo, timeout=0.1)
cfg = make_config(check_runner=(sys.executable,), env=(("AUDIT_VALUE", "opaque-fake-db-password"),))
report = sandbox.run_checks(cfg, git_repo, timeout=0.1)
assert not report.ok
result = report.results[0]
assert result.exit_code == 124 and result.duration_s == 0.25
assert 'partial' in result.tail and 'timed out after 0.1s' in result.tail
assert 'partial [REDACTED]' in result.tail and 'timed out after 0.1s' in result.tail


@pytest.mark.parametrize('change', ['fallback', 'base'])
Expand Down
Loading