Skip to content

Agent Zero AI framework

Handle private OAuth auth file edge cases

Cooper Gamble3c6aaae7378c
diff --git a/plugins/_oauth/helpers/codex.py b/plugins/_oauth/helpers/codex.py
index da8f7ad36..4591f49cb 100644
--- a/plugins/_oauth/helpers/codex.py
+++ b/plugins/_oauth/helpers/codex.py
@@ -38,6 +38,7 @@ REFRESH_INTERVAL = timedelta(minutes=55)
FALLBACK_CODEX_VERSION = "0.124.0"
OAUTH_ERROR_KEYS = {"error", "error_description"}
DEVICE_CODE_TIMEOUT_SECONDS = 15 * 60
+WINDOWS_LOCK_RETRY_SECONDS = 0.05
USAGE_ENDPOINT_PATHS = (
"/backend-api/codex/usage",
"/backend-api/wham/usage",
@@ -975,9 +976,12 @@ def resolve_auth_file_candidates() -> list[Path]:
def resolve_auth_write_path() -> Path:
explicit = codex_config()["auth_file_path"]
- if explicit:
- return _validate_private_auth_path(Path(explicit).expanduser())
- return Path(files.get_abs_path("usr", "plugins", "_oauth", "codex", AUTH_FILENAME))
+ path = (
+ Path(explicit).expanduser()
+ if explicit
+ else Path(files.get_abs_path("usr", "plugins", "_oauth", "codex", AUTH_FILENAME))
+ )
+ return _validate_private_auth_path(path)
def read_auth_file() -> tuple[Path, dict[str, Any]]:
@@ -993,7 +997,7 @@ def write_auth_file(path: Path, data: dict[str, Any]) -> None:
@contextmanager
def _auth_file_lock(path: Path) -> Iterator[None]:
- lock_path = path.with_name(f".{path.name}.lock")
+ lock_path = _auth_lock_path(path)
lock_path.parent.mkdir(parents=True, exist_ok=True)
with _AUTH_THREAD_LOCK:
with lock_path.open("a+b") as handle:
@@ -1014,8 +1018,15 @@ def _lock_file(handle: BinaryIO) -> None:
handle.write(b"\0")
handle.flush()
handle.seek(0)
- msvcrt.locking(handle.fileno(), msvcrt.LK_LOCK, 1)
- return
+ while True:
+ try:
+ msvcrt.locking(handle.fileno(), msvcrt.LK_NBLCK, 1)
+ return
+ except OSError as exc:
+ if exc.errno not in {errno.EACCES, errno.EDEADLK}:
+ raise
+ time.sleep(WINDOWS_LOCK_RETRY_SECONDS)
+ handle.seek(0)
raise RuntimeError("This platform does not support locking the Agent Zero OAuth auth file.")
@@ -1043,7 +1054,13 @@ def _write_auth_file_unlocked(path: Path, data: dict[str, Any]) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
temporary_path = path.with_name(f".{path.name}.{os.getpid()}.{secrets.token_hex(8)}.tmp")
try:
- descriptor = os.open(temporary_path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
+ try:
+ descriptor = os.open(temporary_path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
+ except OSError as exc:
+ if exc.errno not in {errno.EACCES, errno.EROFS}:
+ raise
+ _write_auth_file_in_place(path, data)
+ return
with os.fdopen(descriptor, "w", encoding="utf-8") as handle:
handle.write(json.dumps(data, indent=2) + "\n")
handle.flush()
@@ -1071,12 +1088,13 @@ def _write_auth_file_in_place(path: Path, data: dict[str, Any]) -> None:
def _validate_private_auth_path(path: Path) -> Path:
- if _path_key(path) in {_path_key(candidate) for candidate in _known_codex_auth_paths()}:
+ resolved_path = path.expanduser().resolve(strict=False)
+ if _path_key(resolved_path) in {_path_key(candidate) for candidate in _known_codex_auth_paths()}:
raise RuntimeError(
"Agent Zero OAuth credentials must use an Agent Zero-owned auth file. "
"Choose a private auth_file_path or leave it empty for the default private store."
)
- return path
+ return resolved_path
def _known_codex_auth_paths() -> list[Path]:
@@ -1095,6 +1113,11 @@ def _path_key(path: Path) -> str:
return os.path.normcase(str(path.expanduser().resolve(strict=False)))
+def _auth_lock_path(path: Path) -> Path:
+ digest = hashlib.sha256(_path_key(path).encode("utf-8")).hexdigest()
+ return Path(files.get_abs_path("usr", "plugins", "_oauth", "codex", "locks", f"{digest}.lock"))
+
+
def parse_jwt_claims(token: str) -> dict[str, Any]:
if not token or token.count(".") != 2:
return {}
diff --git a/tests/test_oauth_codex.py b/tests/test_oauth_codex.py
index 7a75da025..9c10e42f3 100644
--- a/tests/test_oauth_codex.py
+++ b/tests/test_oauth_codex.py
@@ -19,6 +19,15 @@ from plugins._oauth.extensions.python._functions.models.get_api_key.end._20_code
)
[email protected](autouse=True)
+def use_temporary_auth_locks(tmp_path, monkeypatch):
+ def lock_path(path: Path) -> Path:
+ digest = codex.hashlib.sha256(codex._path_key(path).encode("utf-8")).hexdigest()
+ return tmp_path / "locks" / f"{digest}.lock"
+
+ monkeypatch.setattr(codex, "_auth_lock_path", lock_path)
+
+
def test_generate_pkce_produces_urlsafe_verifier_and_challenge():
pair = codex.generate_pkce()
@@ -298,6 +307,76 @@ def test_write_auth_file_falls_back_for_file_bind_mount(tmp_path, monkeypatch):
assert list(tmp_path.glob(".auth.json.*.tmp")) == []
+def test_write_auth_file_falls_back_when_parent_rejects_temporary_files(tmp_path, monkeypatch):
+ auth_path = tmp_path / "auth.json"
+ auth_path.write_text(json.dumps({"tokens": {"refresh_token": "refresh-0"}}), encoding="utf-8")
+ open_file = codex.os.open
+
+ def reject_temporary_file(path, flags, mode=0o777):
+ if str(path).endswith(".tmp"):
+ raise OSError(codex.errno.EACCES, "Permission denied", path)
+ return open_file(path, flags, mode)
+
+ monkeypatch.setattr(codex.os, "open", reject_temporary_file)
+
+ codex.write_auth_file(auth_path, {"tokens": {"refresh_token": "refresh-1"}})
+
+ assert json.loads(auth_path.read_text(encoding="utf-8")) == {
+ "tokens": {"refresh_token": "refresh-1"}
+ }
+ assert not auth_path.with_name(".auth.json.lock").exists()
+
+
+def test_resolve_auth_write_path_preserves_custom_symlink_target(tmp_path, monkeypatch):
+ target = tmp_path / "mounted" / "auth.json"
+ target.parent.mkdir()
+ target.write_text(json.dumps({"tokens": {"refresh_token": "refresh-0"}}), encoding="utf-8")
+ symlink = tmp_path / "auth.json"
+ symlink.symlink_to(target)
+ monkeypatch.setattr(codex, "codex_config", lambda: {"auth_file_path": str(symlink)})
+
+ resolved_path = codex.resolve_auth_write_path()
+ codex.write_auth_file(resolved_path, {"tokens": {"refresh_token": "refresh-1"}})
+
+ assert resolved_path == target
+ assert symlink.is_symlink()
+ assert json.loads(target.read_text(encoding="utf-8")) == {
+ "tokens": {"refresh_token": "refresh-1"}
+ }
+
+
+def test_lock_file_retries_windows_contention(tmp_path, monkeypatch):
+ class FakeMsvcrt:
+ LK_NBLCK = 1
+ LK_UNLCK = 2
+
+ def __init__(self):
+ self.calls: list[int] = []
+
+ def locking(self, _descriptor: int, mode: int, _length: int) -> None:
+ self.calls.append(mode)
+ if mode == self.LK_NBLCK and self.calls.count(mode) < 3:
+ raise OSError(codex.errno.EACCES, "Permission denied")
+
+ fake_msvcrt = FakeMsvcrt()
+ sleeps: list[float] = []
+ monkeypatch.setattr(codex, "fcntl", None)
+ monkeypatch.setattr(codex, "msvcrt", fake_msvcrt)
+ monkeypatch.setattr(codex.time, "sleep", sleeps.append)
+
+ with (tmp_path / "auth.lock").open("a+b") as handle:
+ codex._lock_file(handle)
+ codex._unlock_file(handle)
+
+ assert fake_msvcrt.calls == [
+ fake_msvcrt.LK_NBLCK,
+ fake_msvcrt.LK_NBLCK,
+ fake_msvcrt.LK_NBLCK,
+ fake_msvcrt.LK_UNLCK,
+ ]
+ assert sleeps == [codex.WINDOWS_LOCK_RETRY_SECONDS, codex.WINDOWS_LOCK_RETRY_SECONDS]
+
+
def test_load_auth_serializes_refresh_across_threads(tmp_path, monkeypatch):
auth_path = tmp_path / "auth.json"
_write_refreshable_auth(auth_path)
@@ -474,6 +553,7 @@ def _rotated_tokens() -> dict[str, str]:
def _load_auth_in_process(auth_path: str, refresh_started, release_refresh, calls, results) -> None:
codex.resolve_auth_write_path = lambda: Path(auth_path)
+ codex._auth_lock_path = lambda _path: Path(auth_path).parent / ".auth.lock"
def refresh_tokens(refresh_token: str) -> dict[str, str]:
calls.put(refresh_token)