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
20 changes: 14 additions & 6 deletions scripts/ai-accounts/ai-accounts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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):

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: Non-regular lock rejection path is untested

The new S_ISREG check, together with O_NONBLOCK, guards against a FIFO or device at the lock path. No test covers it. Add a short case that creates STATE/.lock with os.mkfifo and expects ValueError from helper._locked('.lock'). That way a later refactor can't quietly drop O_NONBLOCK and let a FIFO hang the open.

raise ValueError(f"{name} is not a regular lock file")
deadline = time.monotonic() + 60
while (remaining := deadline - time.monotonic()) > 0:
try:
Expand Down
23 changes: 23 additions & 0 deletions tests/test_ai_accounts.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")

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: Staging test only checks the old temp-file name, which the new code never uses

The test puts a regular file or symlink at the old status.json.<pid>.<tid>.tmp name. write_private now stages through tempfile.mkstemp(prefix='.status.json.'), so it never touches that path. The test would pass even if the new staging were not exclusive. It works as a regression guard against the old naming, but it does not show that a collision with the actual staging name leaves the existing file intact. Smallest fix: monkeypatch helper.tempfile._get_candidate_names (or mkstemp's name sequence) so the first candidate matches a pre-created file or symlink. Then assert that the update still lands and the collided target still reads "preserve". Alternatively, assert that no .status.json.* residue remains after the call.

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