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] 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"