From 413b14c9ba0b16de72fc1c01867348c9caf70df2 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 12:34:11 +0100 Subject: [PATCH 1/2] Deduplicate candidate and workflow policy handling Architecture-Review: unchanged; keep the same attestation inputs, trusted workflow policy, and hosted publication boundaries. Co-Authored-By: Codex --- src/loopzero/candidate.py | 69 +++++++++++++-------------------------- src/loopzero/config.py | 49 ++++++++++++--------------- src/loopzero/hosted.py | 16 +++------ 3 files changed, 47 insertions(+), 87 deletions(-) diff --git a/src/loopzero/candidate.py b/src/loopzero/candidate.py index e1beb361..38a68c8a 100644 --- a/src/loopzero/candidate.py +++ b/src/loopzero/candidate.py @@ -165,51 +165,30 @@ def _candidate_lineage(status: JsonObject, candidate_number: int) -> tuple[str, return candidate_id, sorted(source_numbers), sorted(missing) +def _repo_identity(repo: JsonObject) -> tuple[object, object]: + return repo.get("id"), repo.get("full_name") + + def _candidate_snapshot( - candidate: JsonObject, - *, - event_pr: JsonObject, - repository: JsonObject, + candidate: JsonObject, number: int, event_head: JsonObject, repository: JsonObject, expected_identity: tuple[object, object, object, object], ) -> None: - _require( - candidate.get("number") == event_pr.get("number"), - "GitHub returned the wrong candidate PR", - ) - _require(candidate.get("state") != "closed", "Mergify candidate PR is superseded (closed)") - _require(candidate.get("state") == "open", "Mergify candidate PR is not open") + _require(candidate.get("number") == number, "GitHub returned the wrong candidate PR") + state = candidate.get("state") + state_error = "Mergify candidate PR is superseded (closed)" if state == "closed" else "Mergify candidate PR is not open" + _require(state == "open", state_error) _require(candidate.get("draft") is True, "Mergify candidate PR must be a draft") - _require( - _identity(candidate.get("user")) == expected_identity, - "Candidate author is not the verified Mergify GitHub App", - ) - head = candidate.get("head") - event_head = event_pr.get("head") - base = candidate.get("base") - _require( - isinstance(head, dict) and isinstance(event_head, dict) and isinstance(base, dict), - "Candidate refs are missing", - ) - _require( - head.get("sha") == event_head.get("sha"), - "Candidate head changed after the workflow event", - ) - _require( - head.get("ref") == event_head.get("ref") - and isinstance(head.get("ref"), str) - and head["ref"].startswith(QUEUE_BRANCH_PREFIX), - "Mergify candidate has an unexpected head ref", - ) - _require( - base.get("ref") == "main", - "Mergify candidate must target the real main branch", - ) - expected_repo = (repository.get("id"), repository.get("full_name")) + _require(_identity(candidate.get("user")) == expected_identity, + "Candidate author is not the verified Mergify GitHub App") + head, base = candidate.get("head"), candidate.get("base") + _require(isinstance(head, dict) and isinstance(base, dict), "Candidate refs are missing") + _require(head.get("sha") == event_head.get("sha"), "Candidate head changed after the workflow event") + _require(head.get("ref") == event_head.get("ref"), "Mergify candidate has an unexpected head ref") + _require(base.get("ref") == "main", "Mergify candidate must target the real main branch") + expected_repo = _repo_identity(repository) for label, repo in (("head", head.get("repo")), ("base", base.get("repo"))): - _require( - isinstance(repo, dict) and (repo.get("id"), repo.get("full_name")) == expected_repo, - f"Mergify candidate {label} repository does not match this repository", - ) + _require(isinstance(repo, dict) and _repo_identity(repo) == expected_repo, + f"Mergify candidate {label} repository does not match this repository") def _source_fingerprint(source: JsonObject) -> tuple[object, ...]: @@ -263,8 +242,7 @@ def _attest_source( _require( base.get("ref") == "main" and isinstance(base_repo, dict) - and (base_repo.get("id"), base_repo.get("full_name")) - == (repository.get("id"), repository.get("full_name")), + and _repo_identity(base_repo) == _repo_identity(repository), f"source PR #{number} does not target this repository's main branch", ) source_sha = head.get("sha") @@ -503,8 +481,7 @@ def _attest_candidate_once( candidate_path = f"/repos/{full_name}/pulls/{candidate_number}" def recheck_candidate(message: str = "GitHub candidate lookup returned an invalid payload") -> None: candidate = _object(github_get(candidate_path), message) - _candidate_snapshot(candidate, event_pr=event_pr, repository=repository, - expected_identity=expected_identity) + _candidate_snapshot(candidate, candidate_number, event_head, repository, expected_identity) recheck_candidate() @@ -590,6 +567,4 @@ def live_lineage() -> tuple[str, list[int], list[str]]: f"source PR #{number} metadata changed during attestation", CandidateRaceError, ) - return [ - {"number": number, "head_sha": source_snapshots[number][0]} for number in first_lineage[1] - ] + return [{"number": number, "head_sha": sha} for number, (sha, _) in source_snapshots.items()] diff --git a/src/loopzero/config.py b/src/loopzero/config.py index edf87338..a0c8103e 100644 --- a/src/loopzero/config.py +++ b/src/loopzero/config.py @@ -89,12 +89,11 @@ def _has_replacement_refs(common_dir: Path) -> bool: return True return True try: - packed = (common_dir / "packed-refs").read_bytes() + return b" refs/replace/" in (common_dir / "packed-refs").read_bytes() except FileNotFoundError: return False except OSError: return True - return b" refs/replace/" in packed def _remote_workflow(worktree: Path, branch: str, previous: Config | None, *, refresh: bool) -> tuple[Config, str]: @@ -102,11 +101,8 @@ def _remote_workflow(worktree: Path, branch: str, previous: Config | None, *, re hint = "Fetch the trusted base workflow, or supply --config for bootstrap or an override." ref = f"refs/remotes/origin/{branch}" if refresh: - fetched = _proc.run( - ["git", "fetch", "--quiet", "--no-tags", "--no-recurse-submodules", - "--no-write-fetch-head", "origin", f"+refs/heads/{branch}:{ref}"], - cwd=worktree, env_allowlist=worktree_mod.GIT_ENV, timeout=60, - ) + fetched = run_git(worktree, "fetch", "--quiet", "--no-tags", "--no-recurse-submodules", + "--no-write-fetch-head", "origin", f"+refs/heads/{branch}:{ref}") if fetched.exit_code != 0: raise ConfigError(f"could not refresh origin/{branch}. {hint}") directory_args = ["--path-format=absolute", "--git-common-dir"] if previous is not None else [] @@ -127,13 +123,12 @@ def _remote_workflow(worktree: Path, branch: str, previous: Config | None, *, re if shown.exit_code != 0: raise ConfigError(f"cannot read {source}. {hint}") try: - data = tomllib.loads(shown.stdout.encode("utf-8", errors="surrogateescape").decode("utf-8")) + text = shown.stdout.encode("utf-8", errors="surrogateescape").decode("utf-8") + return _build(tomllib.loads(text)), revision except UnicodeDecodeError as exc: raise ConfigError(f"{source}: {exc}") from exc except tomllib.TOMLDecodeError as exc: raise ConfigError(f"{source}: invalid TOML: {exc}. {hint}") from None - try: - return _build(data), revision except ConfigError as exc: raise ConfigError(f"{source}: {exc}. {hint}") from None @@ -150,12 +145,12 @@ def load_trusted(worktree: Path, *, previous: Config | None = None, refresh: boo ) branch = ref.removeprefix(prefix) policy, revision = _remote_workflow(worktree, branch, previous, refresh=refresh) - if policy.base_branch == branch: - return replace(policy, trusted_base_revision=revision) - base, revision = _remote_workflow(worktree, policy.base_branch, previous, refresh=refresh) - if base.base_branch != policy.base_branch: - raise ConfigError("trusted origin workflows disagree on repo.base; align them or supply --config") - return replace(base, trusted_base_revision=revision) + if policy.base_branch != branch: + branch = policy.base_branch + policy, revision = _remote_workflow(worktree, branch, previous, refresh=refresh) + if policy.base_branch != branch: + raise ConfigError("trusted origin workflows disagree on repo.base; align them or supply --config") + return replace(policy, trusted_base_revision=revision) def _build(data: dict[str, Any]) -> Config: @@ -222,21 +217,18 @@ def _build(data: dict[str, Any]) -> Config: if "/" in runner[0] and not Path(runner[0]).is_absolute(): raise ConfigError("checks.runner executable paths must be absolute") kwargs["check_runner"] = runner - if "inputs" in checks: - inputs = {} - for key, value in checks["inputs"].items(): - label = f'checks.inputs."{key}"' - if key != "*" and key not in commands: - raise ConfigError(f"{label} must exactly match a checks.commands entry") - inputs[key] = _strings(label, value) - kwargs["inputs"] = inputs + inputs = {} + for key, value in checks.get("inputs", {}).items(): + label = f'checks.inputs."{key}"' + if key != "*" and key not in commands: + raise ConfigError(f"{label} must exactly match a checks.commands entry") + inputs[key] = _strings(label, value) for key, field, read in (("env_allowlist", "env_allowlist", _strings), ("ro_paths", "sandbox_ro", _host_paths), ("writable", "writable", _host_paths)): if key in checks: kwargs[field] = read(f"checks.{key}", checks[key]) - if "env" in checks: - kwargs["env"] = _env_table(checks["env"]) + env = _env_table(checks.get("env", {})) if "scratch" in checks: kwargs["scratch"] = _strings("checks.scratch", checks["scratch"]) for entry in kwargs["scratch"]: @@ -265,7 +257,7 @@ def _build(data: dict[str, Any]) -> Config: reviewer_ro_paths=reviewer_ro_paths, review_chunk_bytes=review_chunk_bytes, network=checks.get("network", False), - **kwargs, + inputs=inputs, env=env, **kwargs, ) @@ -323,8 +315,7 @@ def _env_table(table: dict[str, Any]) -> tuple[tuple[str, str], ...]: def _limits(table: dict[str, Any]) -> ResourceLimits: defaults = ResourceLimits() - allowed = tuple(defaults.__dict__) - _reject_unknown("checks.limits", table, allowed) + _reject_unknown("checks.limits", table, defaults.__dict__) values = defaults.__dict__ | table for name, value in values.items(): if isinstance(value, bool) or not isinstance(value, int) or value <= 0: diff --git a/src/loopzero/hosted.py b/src/loopzero/hosted.py index 24046c22..8a9fdd12 100644 --- a/src/loopzero/hosted.py +++ b/src/loopzero/hosted.py @@ -4,7 +4,6 @@ import json import os import sys -from collections.abc import Callable from contextlib import suppress from pathlib import Path @@ -71,10 +70,9 @@ def _run(cfg: Config) -> int: head = pr["head"]["sha"] candidate = (pr["head"]["ref"].startswith("mergify/merge-queue/") or pr["user"]["login"] == "mergify[bot]") - if not candidate and pr.get("merged") is True: + active = _candidate_event(event, head) if candidate else pr.get("merged") is not True + if not active: return 0 # A landed source needs no new verdict; a late refresh must not turn it red. - if candidate and not _candidate_event(event, head): - return 0 def publish(state: str, message: str) -> None: github.commit_status(cfg.repo, head, eligibility.CONTEXT, state, message[:140]) publish("pending", "Refreshing live source review evidence") @@ -110,7 +108,9 @@ def policy(source_number: int, source: dict) -> None: print(f"Eligibility pending: evidence unavailable ({exc})", file=sys.stderr) return 0 except Exception as exc: - _mark_refresh_failed(publish, exc) + if not isinstance(exc, github.StatusLimitReached): + with suppress(Exception): + publish("failure", "Eligibility refresh failed; inspect workflow logs") raise _publish_verdict(cfg.repo, head, state, message[:140]) print(message) @@ -142,11 +142,5 @@ def _publish_verdict(repo: str, head: str, state: str, description: str) -> None raise LoopZeroError(f"Could not confirm eligibility status publication: {exc}") from exc -def _mark_refresh_failed(publish: Callable[[str, str], None], exc: Exception) -> None: - if not isinstance(exc, github.StatusLimitReached): - with suppress(Exception): - publish("failure", "Eligibility refresh failed; inspect workflow logs") - - if __name__ == "__main__": raise SystemExit(main()) From 4cd3faa32247cbcec55eb23a980f4cd245ffe28d Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 12:43:19 +0100 Subject: [PATCH 2/2] Use exclusive staging and safe lock opens for account files Architecture-Review: unchanged; the account helper retains its state format and lock order. Co-Authored-By: Codex --- scripts/ai-accounts/ai-accounts | 20 ++++++++++++++------ tests/test_ai_accounts.py | 23 +++++++++++++++++++++++ 2 files changed, 37 insertions(+), 6 deletions(-) diff --git a/scripts/ai-accounts/ai-accounts b/scripts/ai-accounts/ai-accounts index bf9d96d1..5c4c901d 100755 --- a/scripts/ai-accounts/ai-accounts +++ b/scripts/ai-accounts/ai-accounts @@ -56,8 +56,10 @@ import os import re import shutil import signal +import stat import subprocess import sys +import tempfile import threading import time import urllib.error @@ -115,11 +117,14 @@ def notify(msg: str) -> None: def write_private(path: Path, text: str) -> None: path.parent.mkdir(parents=True, exist_ok=True, mode=0o700) - tmp = path.with_name(f"{path.name}.{os.getpid()}.{threading.get_ident()}.tmp") - fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) - with os.fdopen(fd, "w", encoding="utf-8") as fh: - fh.write(text) - os.replace(tmp, path) + fd, staged = tempfile.mkstemp(prefix=f".{path.name}.", dir=path.parent) + try: + with os.fdopen(fd, "w", encoding="utf-8") as fh: + fh.write(text) + os.replace(staged, path) + except BaseException: + Path(staged).unlink(missing_ok=True) + raise # ----------------------------------------------------------------- accounts @@ -171,7 +176,10 @@ class AccountLockTimeout(TimeoutError): @contextmanager def _locked(name: str): - with (STATE / name).open("a") as lock: + fd = os.open(STATE / name, os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW | os.O_NONBLOCK, 0o600) + with os.fdopen(fd, "rb") as lock: + if not stat.S_ISREG(os.fstat(lock.fileno()).st_mode): + raise ValueError(f"{name} is not a regular lock file") deadline = time.monotonic() + 60 while (remaining := deadline - time.monotonic()) > 0: try: diff --git a/tests/test_ai_accounts.py b/tests/test_ai_accounts.py index 82041ff8..c161c052 100644 --- a/tests/test_ai_accounts.py +++ b/tests/test_ai_accounts.py @@ -570,3 +570,26 @@ def open_(*args, **kwargs): monkeypatch.setattr(helper.urllib.request, "urlopen", open_) with pytest.raises(TimeoutError, match="provider HTTP request timed out"): helper._http(request, timeout=1) + + +@pytest.mark.parametrize("symlink", [False, True]) +def test_account_staging_preserves_colliding_path(helper, tmp_path, symlink): + path = helper.STATE / "status.json" + staged = path.with_name(f"{path.name}.{helper.os.getpid()}.{helper.threading.get_ident()}.tmp") + target = tmp_path / "unrelated" if symlink else staged + target.write_text("preserve") + if symlink: + staged.symlink_to(target) + helper.write_private(path, "{}") + assert path.read_text() == "{}" and target.read_text() == "preserve" + + +def test_account_lock_preserves_existing_file_and_rejects_symlink(helper): + lock = helper.STATE / ".lock" + lock.write_text("preserve") + with helper._locked(lock.name): + assert lock.read_text() == "preserve" + (helper.STATE / ".codex-sync.lock").symlink_to(lock) + with pytest.raises(OSError), helper._locked(".codex-sync.lock"): + pytest.fail("redirected lock opened") + assert lock.read_text() == "preserve"