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
44 changes: 21 additions & 23 deletions src/loopzero/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,13 @@
import random
import re
import sys
import tempfile
import time
from collections.abc import Callable, Iterator
from contextlib import contextmanager
from contextlib import contextmanager, suppress
from datetime import UTC, datetime
from functools import partial, wraps
from pathlib import Path
from uuid import uuid4

from loopzero import _proc, eligibility, github, mergify, runners, sandbox, worktree
from loopzero import config as config_mod
Expand Down Expand Up @@ -353,20 +353,19 @@ def _print_receipt(wt: Path, report: CheckReport, action: str) -> None:


@contextmanager
def _lock_task_state(wt: Path) -> Iterator[None]:
def _lock_task_state(wt: Path) -> Iterator[int]:
directory = wt / ".loopzero"
directory.mkdir(parents=True, exist_ok=True)

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: New review-state directory is not private until after creation

Before this change, _save_review created .loopzero with mode=0o700. Now _lock_task_state creates it with the umask default (usually 0o755), and _save_review only fixes it with fchmod(0o700) once the directory is open. Staged files are 0o600, so the exposure is small. Still, _lock_task_state could pass mode=0o700 to mkdir so a newly created directory starts out private for every caller.

fd = os.open(directory, os.O_RDONLY | os.O_DIRECTORY)
fd = os.open(directory, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
try:
fcntl.flock(fd, fcntl.LOCK_EX)
yield
yield fd
finally:
os.close(fd)


def _save_report(wt: Path, report: CheckReport) -> str | None:
"""Publish the receipt or return the current HEAD if the result is stale."""
path = wt / CHECKS_FILE
payload = {
"head": report.head,
"dirty": report.dirty,
Expand All @@ -376,27 +375,26 @@ def _save_report(wt: Path, report: CheckReport) -> str | None:
}
if report.settings_sha256 is not None:
payload["settings_sha256"] = report.settings_sha256
with _lock_task_state(wt):
with _lock_task_state(wt) as directory:
current_head = worktree.head(wt)
if report.head != current_head:
return current_head
_write_json_atomically(path, payload)
_write_json_atomically(directory, CHECKS_FILE.name, payload)
return None


def _write_json_atomically(path: Path, payload: dict) -> None:
with tempfile.NamedTemporaryFile(
mode="w", encoding="utf-8", dir=path.parent, prefix=f".{path.name}-", delete=False
) as stream:
temp = Path(stream.name)
try:
def _write_json_atomically(directory: int, name: str, payload: dict) -> None:
temp = f".{name}-{uuid4().hex}"
fd = os.open(temp, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600, dir_fd=directory)
try:
with os.fdopen(fd, "w", encoding="utf-8") as stream:
stream.write(json.dumps(payload, indent=2) + "\n")
stream.flush()
os.fsync(stream.fileno())
stream.close()
os.replace(temp, path)
finally:
temp.unlink(missing_ok=True)
os.replace(temp, name, src_dir_fd=directory, dst_dir_fd=directory)
finally:
with suppress(FileNotFoundError):
os.unlink(temp, dir_fd=directory)


def _load_report(wt: Path) -> CheckReport | None:
Expand Down Expand Up @@ -1108,14 +1106,14 @@ def _review_file(wt: Path, head: str, kind: str) -> Path:

def _save_review(wt: Path, result: ReviewResult, publication: dict | None = None) -> None:
path = _review_file(wt, result.head, result.kind)
path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
path.parent.chmod(0o700)
data = dataclasses.asdict(result)
if publication is not None:
data["publication"] = publication
if path.is_symlink():
raise OSError(f"refusing to replace symbolic link: {path}")
_write_json_atomically(path, data)
with _lock_task_state(wt) as directory:
os.fchmod(directory, 0o700)
if path.is_symlink():

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: Symlink pre-check uses the path, not the locked directory fd

Both receipts are now published with os.replace(..., src_dir_fd=directory, dst_dir_fd=directory). A rename replaces the directory entry itself and does not follow a symlink, so a symlinked receipt can no longer send the write somewhere else. The remaining path.is_symlink() check goes back through wt/.loopzero/... by path instead of using the fd that was opened and locked. That makes it a separate check that can drift from the one actually enforced. If you want to keep refusing a symlinked receipt, use stat.S_ISLNK(os.lstat(path.name, dir_fd=directory).st_mode) and handle FileNotFoundError, so the check uses the same directory handle. Otherwise drop the check, since the dir_fd rename already makes it unnecessary.

raise OSError(f"refusing to replace symbolic link: {path}")
_write_json_atomically(directory, path.name, data)


def _load_review(wt: Path, head: str, kind: str) -> ReviewResult:
Expand Down
24 changes: 18 additions & 6 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -4694,23 +4694,35 @@ def test_wait_rechecks_closed_unmerged_pr(monkeypatch, final) -> None:
assert _closed_unmerged_wait(monkeypatch, reads, steps=1) == final


def test_checks_report_survives_failed_publication(tmp_path, monkeypatch):
@pytest.mark.parametrize("redirected", [False, True])
def test_checks_report_survives_failed_publication(tmp_path, monkeypatch, redirected):
path = tmp_path / cli.CHECKS_FILE
monkeypatch.setattr(cli.worktree, "head", lambda _: next(heads))
heads = iter(("a" * 40, "b" * 40))
cli._save_report(tmp_path, CheckReport("a" * 40, False, ()))

def interrupt(staged, dest):
assert Path(staged).parent == dest.parent
assert json.loads(Path(staged).read_text())["head"] == "b" * 40
assert json.loads(dest.read_text())["head"] == "a" * 40
def interrupt(staged, dest, *, src_dir_fd, dst_dir_fd):
assert src_dir_fd == dst_dir_fd and dest == path.name
assert json.loads(path.with_name(staged).read_text())["head"] == "b" * 40
assert json.loads(path.read_text())["head"] == "a" * 40
raise OSError("publication interrupted")

if redirected:
external = path.parent.rename(tmp_path / "external")
path.parent.symlink_to(external, target_is_directory=True)
monkeypatch.setattr(cli.os, "replace", interrupt)
with pytest.raises(OSError, match="publication interrupted"):
with pytest.raises(OSError, match="Not a directory" if redirected else "publication interrupted"):

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: Test expects one platform's error for a refused symlink

In the redirected case, the test matches "Not a directory". That message comes from Linux, which returns ENOTDIR when O_DIRECTORY | O_NOFOLLOW meets a symlink. Other systems such as macOS/BSD return ELOOP, so the test would fail there even though the code is correct. If the project only targets Linux this is fine. Otherwise accept either errno (for example match="Not a directory|Too many levels", or check exc.errno in {ENOTDIR, ELOOP}). The same applies to the _save_review assertion further down.

cli._save_report(tmp_path, CheckReport("b" * 40, False, ()))
assert json.loads(path.read_text())["head"] == "a" * 40
assert list(path.parent.iterdir()) == [path]
if redirected:
external.chmod(0o755)
review = ReviewResult("claude", "a" * 40, "primary", "approve", (), "")
receipt = cli._review_file(tmp_path, review.head, review.kind)
receipt.write_text("user file")
with pytest.raises(OSError, match="Not a directory"):
cli._save_review(tmp_path, review)
assert receipt.read_text() == "user file" and external.stat().st_mode & 0o777 == 0o755


def test_already_merged_finishes_partial_cleanup(wt, repo, gh, capsys, monkeypatch, head):
Expand Down
Loading