Repository navigation
Expand file tree
/
Copy pathsandbox.py
More file actions
693 lines (607 loc) · 31.5 KB
/
Copy pathsandbox.py
File metadata and controls
693 lines (607 loc) · 31.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
"""Run checks in bwrap, which gives no CPU/memory quotas; ulimit is best-effort."""
from __future__ import annotations
import ast
import errno
import hashlib
import json
import math
import os
import re
import resource
import shutil
import stat
import tempfile
import threading
import time
from collections.abc import Callable, Sequence
from contextlib import ExitStack, contextmanager
from dataclasses import asdict, replace
from os.path import commonpath
from pathlib import Path
from . import __version__, _proc
from . import config as config_mod
from .types import CheckReport, CheckResult, Config, LoopZeroError, is_check_exit_code
from .worktree import WorktreeError, read_local_state
GIT_TIMEOUT = 60.0
DEFAULT_TIMEOUT = 3600.0
TIMEOUT_EXIT = 124
CHECK_SHELL = ("/bin/bash", "--posix", "-o", "pipefail", "-c")
CHECK_TAIL_BYTES = 16 * 1024
FIRST_HEARTBEAT_DELAY = 30.0
HEARTBEAT_INTERVAL = 300.0
SANDBOX_HOME = "/tmp/home"
# Only these system directories are exposed read-only by default; home tool paths
# require explicit `[checks] ro_paths`. Host homes, sockets and processes stay hidden.
SYSTEM_RO = ("/usr", "/bin", "/sbin", "/lib", "/lib32", "/lib64", "/etc", "/opt")
# Writable binds are consumer-trusted shared caches (checks can poison them).
# Scratch binds are per-run empty directories for venvs/caches, preserving read-only source.
# Precedence inside the sandbox: SANDBOX_ENV defaults < allowlisted host vars < Config.env.
SANDBOX_ENV = {
"PYTHONDONTWRITEBYTECODE": "1",
"RUFF_CACHE_DIR": "/tmp/ruff-cache",
"UV_CACHE_DIR": "/tmp/uv-cache",
"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."""
@contextmanager
def _private_directories():
with ExitStack() as stack:
try:
yield stack
finally:
# Keep the stack's own exit as a fallback if SIGTERM arrives before deferral.
with _proc.defer_sigterm():
stack.close()
def _enter_private_directory(stack: ExitStack, prefix: str) -> Path:
with _proc.defer_sigterm():
directory = tempfile.TemporaryDirectory(prefix=prefix)
stack.callback(directory.cleanup)
return Path(directory.name)
@contextmanager
def private_directory(prefix: str):
"""Keep a private directory scoped to an operation, including on SIGTERM."""
with _proc.unwind_on_sigterm(), _private_directories() as stack:
yield _enter_private_directory(stack, prefix)
def run_checks(config: Config, worktree: Path, *, timeout: float = DEFAULT_TIMEOUT,
progress: Callable[[str], None] | None = None,
status: Callable[[str], None] | None = None,
checkpoint: Callable[[CheckReport], None] | None = None,
workflow: str | Path = "workflow.toml", _resolved: bool = False) -> CheckReport:
"""Run until a check fails, reporting commands via progress and stage metadata via status."""
worktree = worktree.resolve()
if not config.check_runner and shutil.which("bwrap") is None:
raise SandboxUnavailable(
"bwrap binary missing: bwrap not found on PATH\n"
"sudo apt install bubblewrap"
)
head = _git(config, worktree, "rev-parse", "HEAD").strip()
dirty = bool(_git(config, worktree, "status", "--porcelain").strip())
if config.check_runner and dirty:
return CheckReport(head, True, (CheckResult("<dirty worktree>", 1, 0.0,
"Runner requires a clean worktree"),))
base = _check_base(config, worktree)
settings_sha256 = settings_fingerprint(config)
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")
_validate_scratch(config.scratch, worktree, common_dir, git_dir)
with _proc.unwind_on_sigterm(), _private_directories() as stack:
prefix = []
if not config.check_runner:
home = _enter_private_directory(stack, "loopzero-home-")
scratch_root = _enter_private_directory(stack, "loopzero-scratch-")
private_parent = Path(commonpath((home, scratch_root)))
for exposed in (*config.sandbox_ro, *config.writable):
if private_parent.is_relative_to(Path(exposed).resolve()):
raise SandboxUnavailable(
f"sandbox path {exposed!r} would expose private check directories"
)
scratch = {entry: scratch_root / entry for entry in config.scratch}
for entry, source in scratch.items():
source.mkdir(parents=True)
# Mount points must exist before bwrap binds the source read-only.
(worktree / entry).mkdir(parents=True, exist_ok=True)
prefix = bwrap_argv(config, worktree, home, common_dir, git_dir, scratch)
probe(config, worktree, prefix)
_preflight_alternates(config, worktree, prefix, common_dir)
missing, preparations = (None, ()) if _resolved else _preflight(config, worktree)
results = [missing] if missing else []
commands = () if missing else (*preparations, *config.checks)
for ordinal, command in enumerate(commands, 1):
if progress:
progress(command)
key = _input_key(config, worktree, command, "" if dirty else base,
status=status, workflow=workflow)
old = previous.get(command)
if key and old and old.input_key == key:
result = old
if status:
status(f"reused {(old.reused_from or head)[:8]}")
else:
with _stage_status(status, ordinal, len(commands)):
result = (_dispatch_one(config, worktree, head, base, command, timeout)
if config.check_runner else _run_one(config, worktree, prefix, command, timeout))
result = replace(result, input_key=key)
if ordinal > len(preparations) or result.exit_code:
results.append(result)
_checkpoint_stage(
checkpoint, CheckReport(head, dirty, tuple(results), settings_sha256),
previous, commands[ordinal:],
)
if status:
status(f"stage {ordinal}/{len(commands)}: exit {result.exit_code} "
f"({result.duration_s:.1f}s)")
if result.exit_code != 0:
break
final_head = _git(config, worktree, "rev-parse", "HEAD").strip()
final_dirty = bool(_git(config, worktree, "status", "--porcelain").strip())
if (final_head, final_dirty) != (head, dirty):
results.append(CheckResult("<worktree changed during run>", 1, 0.0, (
f"HEAD before: {head}; HEAD after: {final_head}; "
f"dirty before: {dirty}; dirty after: {final_dirty}"
)))
dirty = True
# A runner upgrade during execution makes the resulting receipt unverified.
settings_sha256 = (
settings_sha256 if not config.check_runner
or settings_sha256 == settings_fingerprint(config) else None
)
return CheckReport(head=head, dirty=dirty, results=tuple(results), settings_sha256=settings_sha256)
INCOMPLETE_CHECK_COMMAND = "<checks incomplete>"
INCOMPLETE_CHECK = CheckResult(INCOMPLETE_CHECK_COMMAND, 1, 0.0, "")
def _checkpoint_stage(checkpoint: Callable[[CheckReport], None] | None,
report: CheckReport, previous: dict[str, CheckResult],
remaining: tuple[str, ...]) -> None:
if checkpoint is None:
return
stage = report.results[-1]
if stage.exit_code:
checkpoint(report)
elif stage.input_key:
# Even the last stage leaves a nonpassing receipt until final validation.
unvisited = tuple(previous[command] for command in remaining if command in previous)
checkpoint(replace(report, results=(*report.results, *unvisited, INCOMPLETE_CHECK)))
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)
or data.get("settings_sha256") != settings_sha256):
return {}
previous = {}
for result in data["results"]:
command, key = result.get("command"), result.get("input_key")
code, tail = result.get("exit_code"), result.get("tail", "")
if (isinstance(command, str) and isinstance(key, str) and key
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, config), key, reused_from)
return previous
except (OSError, WorktreeError, ValueError, KeyError, TypeError, AttributeError):
return {}
def _check_base(config: Config, worktree: Path) -> str:
if config.check_runner or config.inputs:
try:
return config.trusted_base_revision or config_mod.base_revision(worktree, config.base_branch)
except (config_mod.ConfigError, WorktreeError):
if config.check_runner:
raise
return ""
def _runner_identity(config: Config) -> tuple[str, str, str] | None:
executable = _runner_executable(config)
if executable is None:
return None
try:
target = Path(executable).resolve(strict=True)
if not target.is_file():
return None
with target.open("rb") as source:
digest = hashlib.file_digest(source, "sha256").hexdigest()
except OSError:
return None
return executable, str(target), digest
def _execution_settings(config: Config, base: str) -> dict:
settings = {k: v for k, v in asdict(config).items() if k in {
"network", "env_allowlist", "sandbox_ro", "writable", "scratch", "env", "limits", "check_runner"}}
settings["local_shell"] = CHECK_SHELL
if config.check_runner or config.inputs:
settings["base"] = base
if config.check_runner:
settings["runner_executable"] = _runner_identity(config)
settings["environment"] = _proc.build_env(config.env_allowlist)
else:
settings["environment"] = check_environment(config)
return settings
def settings_fingerprint(config: Config) -> str | None:
"""Bind a receipt to effective check settings, independent of the base revision."""
settings = _execution_settings(config, config.base_branch)
if config.check_runner and settings["runner_executable"] is None:
return None
if not config.check_runner:
# Inherited host settings can differ at readiness. Stage reuse still binds them.
host_env = {"PATH", "LANG", "LC_ALL", "TERM", "HEAVY_SLOT_GRANTED_CORES"}
for name in host_env - dict(config.env).keys():
settings["environment"].pop(name, None)
return hashlib.sha256(json.dumps([settings, config.inputs], sort_keys=True).encode()).hexdigest()
def _input_blobs(config: Config, worktree: Path, paths: tuple[str, ...]) -> str | None:
# Empty pathspecs must not accidentally mean the whole tree.
if not paths:
return ""
empty = _git(config, worktree, "hash-object", "-t", "tree", "/dev/null").strip()
try:
return _git(config, worktree, "-c", "core.quotePath=true", "diff-tree", "--no-commit-id",
"--raw", "-r", "--no-abbrev", empty, "HEAD", "--", *paths)
except OSError as exc:
if exc.errno == errno.E2BIG:
return None
raise
def check_inputs_match(config: Config, worktree: Path, report: CheckReport) -> bool:
base = _check_base(config, worktree) if config.inputs else ""
return all(r.input_key and r.input_key == _input_key(config, worktree, r.command, base)
for r in report.results if _has_inputs(config, r.command))
def _has_inputs(config: Config, command: str) -> bool:
return command in config.inputs or "." in config.inputs.get("*", ())
def _input_key(config: Config, worktree: Path, command: str, base: str, *,
status: Callable[[str], None] | None = None,
workflow: str | Path = "workflow.toml") -> str | None:
if not _has_inputs(config, command) or (not base and status is None):
return None
entries = {key: config.inputs[key] for key in (command, "*") if key in config.inputs}
try:
blobs = _input_blobs(config, worktree, tuple(path for paths in entries.values() for path in paths))
except (SandboxUnavailable, _proc.ProcTimeout, OSError, ValueError):
if not base:
return None
raise
if blobs == "" and status:
status(f"{workflow}: checks.inputs for {command!r} matches no files in HEAD. "
f"Correct these entries: {entries!r}. Running the check fresh.")
if not blobs or not base:
return None
return _hash_inputs(config, worktree, command, base, blobs)
def _hash_inputs(config: Config, worktree: Path, command: str, base: str, blobs: str) -> str | None:
contents = []
root = worktree.resolve()
try:
for entry in blobs.split("\n"):
if not entry:
continue
metadata, name = entry.split("\t", 1)
if name.startswith('"'):
name = os.fsdecode(ast.literal_eval("b" + name))
path = root / name
if (metadata.split()[1] not in {"100644", "100755"}
or path.resolve(strict=True) != path
or not stat.S_ISREG(path.lstat().st_mode)):
return None
with path.open("rb") as stream:
contents.append(hashlib.file_digest(stream, "sha256").hexdigest())
except (OSError, ValueError, SyntaxError, RuntimeError):
return None
payload = [command, __version__, _execution_settings(config, base), blobs, contents]
return hashlib.sha256(json.dumps(payload, sort_keys=True).encode()).hexdigest()
@contextmanager
def _stage_status(status: Callable[[str], None] | None, ordinal: int, total: int):
stopped = threading.Event()
started = time.monotonic()
def heartbeat():
delay = FIRST_HEARTBEAT_DELAY
while not stopped.wait(delay):
status(f"stage {ordinal}/{total}: running "
f"({time.monotonic() - started:.1f}s elapsed)")
delay = HEARTBEAT_INTERVAL
reporter = threading.Thread(target=heartbeat, daemon=True) if status else None
if reporter:
reporter.start()
join_reporter = True
try:
yield
except _proc.Terminated:
join_reporter = False
raise
finally:
stopped.set()
if reporter and join_reporter:
reporter.join()
def _preflight_alternates(config: Config, worktree: Path, prefix: list[str], common_dir: Path) -> None:
env = _proc.build_env(config.env_allowlist)
if not {"GIT_OBJECT_DIRECTORY", "GIT_ALTERNATE_OBJECT_DIRECTORIES"} & env.keys():
try:
(common_dir / "objects/info/alternates").lstat()
except FileNotFoundError:
return
except OSError:
pass
# Git resolves relative and transitive paths; probe actual mounts without broadening visibility.
output = _git(config, worktree, "-c", "core.quotepath=true", "count-objects", "-v")
for alternate in re.findall(r"^alternate: (.*)$", output, re.MULTILINE):
if alternate.startswith('"'):
alternate = os.fsdecode(ast.literal_eval("b" + alternate))
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 = _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:
raise SandboxUnavailable(remedy)
def _preflight(config: Config, worktree: Path) -> tuple[CheckResult | None, tuple[str, ...]]:
# Recognize a deliberately small argv grammar, never interpret shell syntax.
groups = None
for command in config.checks:
if not re.fullmatch(r"[A-Za-z0-9_./=-]+(?: +[A-Za-z0-9_./=-]+)*", command):
continue
words = command.split()
script = words[1] if re.fullmatch(r"python(?:3(?:\.\d+)?)?", words[0]) and len(words) > 1 else words[0]
path = Path(script)
if "=" in words[0] or any(path.is_relative_to(Path(entry)) for entry in config.scratch):
continue
if (not path.is_absolute() and "/" in script and ".." not in path.parts
and not any((worktree / path).resolve().is_relative_to(Path(root)) for root in config.writable)
and not (worktree / path).is_file()):
message = (
f"Check preflight: repo-local file {script!r} is absent from this task tree. "
"If trusted-base checks advanced, integrate the current configured base "
"into this task branch (resolve conflicts), then rerun loopzero check; "
"otherwise restore the required file."
)
return CheckResult(command, 1, 0.0, _check_tail(message)), ()
match = re.fullmatch(r"uv run((?: --group [A-Za-z0-9_-]+)*) [A-Za-z0-9_./][A-Za-z0-9_./-]*(?: [A-Za-z0-9_./=-]+)*", command)
if match:
groups = [*(groups or []), *match[1].split()[1::2]]
flags = "".join(f" --group {group}" for group in dict.fromkeys(groups or []))
return None, ((f"uv sync --offline --locked{flags}",)
if groups is not None and not config.network and (worktree / "pyproject.toml").is_file()
else ())
def _validate_scratch(
entries: tuple[str, ...], worktree: Path, common_dir: Path, git_dir: Path
) -> None:
"""Reject scratch destinations that could escape or alter Git metadata."""
for entry in entries:
parts = Path(entry).parts
if not parts or entry in ("", ".") or Path(entry).is_absolute() or ".." in parts:
raise SandboxUnavailable(f"unsafe scratch destination {entry!r}")
destination = worktree.joinpath(*parts)
if parts[0] == ".git" or any(
destination == path or destination.is_relative_to(path) for path in (common_dir, git_dir)
):
raise SandboxUnavailable(f"scratch destination touches Git metadata: {entry!r}")
current = worktree
for part in parts:
current /= part
if current.is_symlink():
raise SandboxUnavailable(f"scratch destination has symlink component: {entry!r}")
def _cap_limit(requested: int, resource_limit: int) -> int:
hard = resource.getrlimit(resource_limit)[1]
return requested if hard == resource.RLIM_INFINITY else min(requested, hard)
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"))
def _run_one(
config: Config, worktree: Path, prefix: list[str], command: str, timeout: float
) -> CheckResult:
try:
limits = config.limits
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, 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:
"""Raise `SandboxUnavailable` unless bwrap can build the exact sandbox we will use."""
try:
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"
"sudo apt install bubblewrap"
) from exc
except _proc.ProcTimeout:
raise SandboxUnavailable(f"bwrap namespace creation timed out after {GIT_TIMEOUT:g}s") from None
if probe.exit_code != 0:
remedy = ""
probe_error = probe.stderr.lower()
if any(word in probe_error for word in ("permission", "user namespace", "userns")):
remedy = "\nsudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0"
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}
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(
config: Config,
worktree: Path,
home: Path,
common_dir: Path,
git_dir: Path,
scratch: dict[str, Path] | None = None,
*,
clearenv: bool = True,
writable_binds: tuple[tuple[Path, Path], ...] = (),
) -> list[str]:
"""Build mounts and environment options before the command separator.
Reviewers inherit their filtered environment and apply sandbox defaults.
"""
argv = ["bwrap", "--die-with-parent", "--new-session", "--unshare-all"]
if config.network:
argv.append("--share-net")
argv += ["--cap-drop", "ALL"]
for path in SYSTEM_RO:
if Path(path).exists():
argv += ["--ro-bind", path, path]
argv += ["--dev", "/dev", "--proc", "/proc"]
argv += ["--tmpfs", "/tmp", "--tmpfs", "/run", "--tmpfs", "/var/run"]
# Restore resolv.conf (or its parent for masked symlinks) over the private tmpfs.
if config.network:
resolv_conf = Path("/etc/resolv.conf")
resolved = resolv_conf.resolve()
masked_roots = (Path("/tmp"), Path("/run"))
if resolv_conf.is_symlink() and any(resolved.is_relative_to(root) for root in masked_roots):
source = destination = resolved.parent
else:
source, destination = resolved, resolv_conf
argv += ["--ro-bind", str(source), str(destination)]
for flag, paths in (("--ro-bind-try", config.sandbox_ro), ("--bind-try", config.writable)):
for path in paths:
argv += [flag, path, path]
for source, destination in ((home, SANDBOX_HOME), *writable_binds):
argv += ["--bind", str(source), str(destination)]
# Read-only tree/Git binds follow tmpfs so paths under /tmp stay visible.
binds = [worktree]
for path in (common_dir, git_dir):
if not any(path == seen or path.is_relative_to(seen) for seen in binds):
binds.append(path)
for path in binds:
argv += ["--ro-bind", str(path), str(path)]
for entry, source in (scratch or {}).items():
argv += ["--bind", str(source), str(worktree / entry)]
argv += ["--chdir", str(worktree), *(["--clearenv"] if clearenv else [])]
if not clearenv:
for key, value in check_environment(config).items():
argv += ["--setenv", key, value]
return [*argv, "--"]
def _git(config: Config, worktree: Path, *args: str, paths: bool = False) -> str:
run = _proc.run_git_paths if paths else _proc.run
done = run(
["git", *args], cwd=worktree, env_allowlist=config.env_allowlist, timeout=GIT_TIMEOUT
)
if done.exit_code != 0:
raise SandboxUnavailable(
f"git {' '.join(args)} failed in {worktree}: {_proc.tail(done.stderr, 1)}"
)
return done.stdout
def _git_dir(config: Config, worktree: Path, flag: str) -> Path:
return (worktree / _git(config, worktree, "rev-parse", flag, paths=True)).resolve()
def _stage_unchanged(config: Config, worktree: Path, head: str) -> bool:
return (_git(config, worktree, "rev-parse", "HEAD").strip() == head
and not _git(config, worktree, "status", "--porcelain").strip())
def _unique_fields(pairs: list[tuple[str, object]]) -> dict[str, object]:
obj = dict(pairs)
if len(obj) != len(pairs):
raise ValueError("duplicate result field")
return obj
def _runner_executable(config: Config) -> str | None:
executable = config.check_runner[0]
return executable if Path(executable).is_absolute() else shutil.which(executable)
def _stage_frame(stdout: str, binding: dict) -> dict:
frame = json.loads(stdout, object_pairs_hook=_unique_fields)
if (not isinstance(frame, dict)
or set(frame) != {*binding, "exit_code", "duration_s", "not_started", "tail"}
or any(frame[key] != value for key, value in binding.items())
or type(frame["network"]) is not bool
or type(frame["exit_code"]) is not int
or type(frame["duration_s"]) not in (int, float)
or not math.isfinite(frame["duration_s"]) or frame["duration_s"] < 0
or type(frame["not_started"]) is not bool
or not isinstance(frame["tail"], str)):
raise ValueError("invalid or mismatched stage result")
return frame
def _dispatch_one(
config: Config, worktree: Path, head: str, base: str, command: str, timeout: float,
) -> CheckResult:
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()}
try:
if not _stage_unchanged(config, worktree, head):
raise ValueError("Worktree changed before stage")
executable = _runner_executable(config)
if not executable:
raise ValueError("Stage runner executable missing")
argv = (executable, *config.check_runner[1:])
with _private_directories() as stack:
cwd = _enter_private_directory(stack, "loopzero-runner-")
if any((cwd / path).resolve().is_relative_to(worktree.resolve())
or (not Path(path).is_absolute() and ".." in Path(path).parts
and not (cwd / path).resolve().is_relative_to(cwd))
for arg in (*argv, str(cwd))
for value in (arg, arg.partition("=")[2],
arg[2:] if arg.startswith("-") and not arg.startswith("--") else "")
for path in {value, *value.split(":")}
if Path(path).is_absolute() or ".." in Path(path).parts):
raise ValueError("Stage runner references task worktree")
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(_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())
frame = _stage_frame(done.stdout, binding)
if not _stage_unchanged(config, worktree, head):
raise ValueError("Worktree changed after stage")
if frame["not_started"]:
if frame["exit_code"] or frame["duration_s"] or frame["tail"]:
raise ValueError("inconsistent not-started result")
if not _stage_unchanged(config, worktree, head):
raise ValueError("Worktree changed before fallback")
local = run_checks(replace(config, check_runner=(), checks=(command,), inputs={}),
worktree, timeout=timeout, _resolved=True)
if local.dirty:
raise ValueError("Local fallback failed")
return local.results[-1]
return CheckResult(command, frame["exit_code"], frame["duration_s"],
_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, config, suffix=f"\n[loopzero] timed out after {timeout:g}s"))
except (LoopZeroError, ValueError, TypeError, OverflowError, RecursionError, OSError) as exc:
detail = _redact_check_output(config, str(exc))
return CheckResult(command, 1, 0.0, _check_tail(f"Stage runner failed: {detail}"))