Agent Zero AI framework
Harden Codex OAuth refresh token ownership
Cooper Gamble2d5f7b89eccd
diff --git a/plugins/_oauth/README.md b/plugins/_oauth/README.mdindex 7f0f46ab9..29a8a818a 100644--- a/plugins/_oauth/README.md+++ b/plugins/_oauth/README.md@@ -5,8 +5,8 @@ Generic local OAuth bridge for Agent Zero.The first provider is `Codex/ChatGPT Account`:- signs in with OpenAI's Codex device-code flow-- writes Codex-compatible `auth.json` credentials+- writes credentials to an Agent Zero-owned `auth.json` file- refreshes local tokens when needed- exposes a loopback OpenAI-compatible wrapper at `/oauth/codex/v1`-Tokens in `auth.json` are password-equivalent credentials. Keep this plugin on trusted local machines only.+Tokens in `auth.json` are password-equivalent credentials. Keep this plugin on trusted local machines only. Do not configure `auth_file_path` to share a rotating refresh-token file with Codex CLI or another client.diff --git a/plugins/_oauth/default_config.yaml b/plugins/_oauth/default_config.yamlindex 66a88481d..e18b12afa 100644--- a/plugins/_oauth/default_config.yaml+++ b/plugins/_oauth/default_config.yaml@@ -2,8 +2,8 @@codex:enabled: true- # Empty means auto-discover CODEX_HOME/auth.json, ~/.codex/auth.json,- # CHATGPT_LOCAL_HOME/auth.json, then ~/.chatgpt-local/auth.json.+ # Empty stores credentials in Agent Zero's private OAuth directory.+ # Never share a rotating refresh-token file with Codex CLI or another client.auth_file_path: ""issuer: "https://auth.openai.com"diff --git a/plugins/_oauth/helpers/codex.py b/plugins/_oauth/helpers/codex.pyindex 37e2aa94a..131f54f4d 100644--- a/plugins/_oauth/helpers/codex.py+++ b/plugins/_oauth/helpers/codex.py@@ -6,11 +6,13 @@ import jsonimport osimport secretsimport subprocess+import threadingimport time+from contextlib import contextmanagerfrom dataclasses import dataclassfrom datetime import datetime, timedelta, timezonefrom pathlib import Path-from typing import Any, Iterable, Mapping+from typing import Any, BinaryIO, Iterable, Iterator, Mappingfrom urllib.parse import parse_qs, urlencode, urljoin, urlparseimport requests@@ -18,6 +20,16 @@ import requestsfrom helpers import filesfrom plugins._oauth.helpers.config import codex_config+try:+ import fcntl+except ImportError:+ fcntl = None++try:+ import msvcrt+except ImportError:+ msvcrt = None+AUTH_FILENAME = "auth.json"ACCESS_EXPIRY_MARGIN = timedelta(minutes=5)@@ -30,6 +42,7 @@ USAGE_ENDPOINT_PATHS = ("/backend-api/wham/usage","/api/codex/usage",)+_AUTH_THREAD_LOCK = threading.RLock()@dataclass(frozen=True)@@ -240,53 +253,63 @@ def poll_device_authorization(device_auth_id: str, user_code: str) -> dict[str,def load_auth(*, ensure_fresh: bool = True) -> EffectiveAuth:- path, data = read_auth_file()- tokens = data.get("tokens") if isinstance(data, dict) else {}- tokens = tokens if isinstance(tokens, dict) else {}-- access_token = _string(tokens.get("access_token"))- id_token = _string(tokens.get("id_token"))- refresh_token = _string(tokens.get("refresh_token"))- account_id = _string(tokens.get("account_id")) or derive_account_id(id_token)- last_refresh = _string(data.get("last_refresh")) if isinstance(data, dict) else ""-- if ensure_fresh and refresh_token and should_refresh(access_token, last_refresh):- refreshed = refresh_tokens(refresh_token)- access_token = refreshed.get("access_token") or access_token- id_token = refreshed.get("id_token") or id_token- refresh_token = refreshed.get("refresh_token") or refresh_token- account_id = derive_account_id(id_token) or account_id- last_refresh = utc_now_iso()- data["tokens"] = {- "id_token": id_token,- "access_token": access_token,- "refresh_token": refresh_token,- "account_id": account_id,- }- data["last_refresh"] = last_refresh- write_auth_file(path, data)-- if not access_token:- raise RuntimeError("Codex/ChatGPT account access token not found. Connect the account first.")- if not account_id:- raise RuntimeError("Codex/ChatGPT account id not found. Connect the account again.")-- return EffectiveAuth(- access_token=access_token,- account_id=account_id,- id_token=id_token,- refresh_token=refresh_token,- source_path=str(path),- last_refresh=last_refresh,- )+ path = resolve_auth_write_path()+ with _auth_file_lock(path):+ data = _read_auth_file_unlocked(path)+ tokens = data.get("tokens") if isinstance(data, dict) else {}+ tokens = tokens if isinstance(tokens, dict) else {}++ access_token = _string(tokens.get("access_token"))+ id_token = _string(tokens.get("id_token"))+ refresh_token = _string(tokens.get("refresh_token"))+ account_id = _string(tokens.get("account_id")) or derive_account_id(id_token)+ last_refresh = _string(data.get("last_refresh")) if isinstance(data, dict) else ""++ if ensure_fresh and refresh_token and should_refresh(access_token, last_refresh):+ refreshed = refresh_tokens(refresh_token)+ access_token = refreshed.get("access_token") or access_token+ id_token = refreshed.get("id_token") or id_token+ refresh_token = refreshed.get("refresh_token") or refresh_token+ account_id = derive_account_id(id_token) or account_id+ last_refresh = utc_now_iso()+ data["tokens"] = {+ "id_token": id_token,+ "access_token": access_token,+ "refresh_token": refresh_token,+ "account_id": account_id,+ }+ data["last_refresh"] = last_refresh+ _write_auth_file_unlocked(path, data)++ if not access_token:+ raise RuntimeError("Codex/ChatGPT account access token not found. Connect the account first.")+ if not account_id:+ raise RuntimeError("Codex/ChatGPT account id not found. Connect the account again.")++ return EffectiveAuth(+ access_token=access_token,+ account_id=account_id,+ id_token=id_token,+ refresh_token=refresh_token,+ source_path=str(path),+ last_refresh=last_refresh,+ )def status() -> dict[str, Any]:- candidates = resolve_auth_file_candidates()- existing = [str(path) for path in candidates if path.is_file()]+ try:+ path = resolve_auth_write_path()+ except Exception as exc:+ return {+ "connected": False,+ "auth_file_path": "",+ "discovered_auth_files": [],+ "message": str(exc),+ }+ existing = [str(path)] if path.is_file() else []result: dict[str, Any] = {"connected": False,- "auth_file_path": str(resolve_auth_write_path()),+ "auth_file_path": str(path),"discovered_auth_files": existing,}try:@@ -323,16 +346,23 @@ def disconnect_auth() -> dict[str, Any]:removed_paths: list[str] = []preserved_paths: list[str] = []- for path in resolve_auth_file_candidates():+ path = resolve_auth_write_path()+ with _auth_file_lock(path):if not path.is_file():- continue- try:- with path.open("r", encoding="utf-8") as handle:- data = json.load(handle)- except Exception:- continue+ return {+ "disconnected": False,+ "cleared_auth_files": [],+ "removed_auth_files": [],+ "preserved_auth_files": [],+ }+ data = _read_auth_file_unlocked(path)if not isinstance(data, dict) or not _contains_chatgpt_auth(data):- continue+ return {+ "disconnected": False,+ "cleared_auth_files": [],+ "removed_auth_files": [],+ "preserved_auth_files": [],+ }cleaned = dict(data)cleaned.pop("tokens", None)@@ -342,12 +372,11 @@ def disconnect_auth() -> dict[str, Any]:cleared_paths.append(str(path))if _has_meaningful_auth_data(cleaned):- write_auth_file(path, cleaned)+ _write_auth_file_unlocked(path, cleaned)preserved_paths.append(str(path))- continue-- path.unlink(missing_ok=True)- removed_paths.append(str(path))+ else:+ path.unlink(missing_ok=True)+ removed_paths.append(str(path))return {"disconnected": bool(cleared_paths),@@ -940,57 +969,116 @@ def resolve_codex_version() -> str:def resolve_auth_file_candidates() -> list[Path]:- cfg = codex_config()- explicit = cfg["auth_file_path"]- if explicit:- return [Path(explicit).expanduser()]-- candidates: list[Path] = []- for env_name in ("CHATGPT_LOCAL_HOME", "CODEX_HOME"):- env_home = os.getenv(env_name)- if env_home:- candidates.append(Path(env_home).expanduser() / AUTH_FILENAME)-- home = Path.home()- candidates.extend(- [- home / ".codex" / AUTH_FILENAME,- home / ".chatgpt-local" / AUTH_FILENAME,- Path(files.get_abs_path("usr", "plugins", "_oauth", "codex", AUTH_FILENAME)),- ]- )- return _unique_paths(candidates)+ return [resolve_auth_write_path()]def resolve_auth_write_path() -> Path:- for candidate in resolve_auth_file_candidates():- if candidate.is_file():- return candidate- return resolve_auth_file_candidates()[-1]+ 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))def read_auth_file() -> tuple[Path, dict[str, Any]]:- candidates = resolve_auth_file_candidates()- for candidate in candidates:- try:- with candidate.open("r", encoding="utf-8") as handle:- payload = json.load(handle)- if isinstance(payload, dict):- return candidate, payload- except FileNotFoundError:- continue- except Exception:- continue- return resolve_auth_write_path(), {}+ path = resolve_auth_write_path()+ with _auth_file_lock(path):+ return path, _read_auth_file_unlocked(path)def write_auth_file(path: Path, data: dict[str, Any]) -> None:+ with _auth_file_lock(path):+ _write_auth_file_unlocked(path, data)+++@contextmanager+def _auth_file_lock(path: Path) -> Iterator[None]:+ lock_path = path.with_name(f".{path.name}.lock")+ lock_path.parent.mkdir(parents=True, exist_ok=True)+ with _AUTH_THREAD_LOCK:+ with lock_path.open("a+b") as handle:+ _lock_file(handle)+ try:+ yield+ finally:+ _unlock_file(handle)+++def _lock_file(handle: BinaryIO) -> None:+ if fcntl is not None:+ fcntl.flock(handle.fileno(), fcntl.LOCK_EX)+ return+ if msvcrt is not None:+ handle.seek(0, os.SEEK_END)+ if handle.tell() == 0:+ handle.write(b"\0")+ handle.flush()+ handle.seek(0)+ msvcrt.locking(handle.fileno(), msvcrt.LK_LOCK, 1)+ return+ raise RuntimeError("This platform does not support locking the Agent Zero OAuth auth file.")+++def _unlock_file(handle: BinaryIO) -> None:+ if fcntl is not None:+ fcntl.flock(handle.fileno(), fcntl.LOCK_UN)+ return+ if msvcrt is not None:+ handle.seek(0)+ msvcrt.locking(handle.fileno(), msvcrt.LK_UNLCK, 1)+++def _read_auth_file_unlocked(path: Path) -> dict[str, Any]:+ try:+ with path.open("r", encoding="utf-8") as handle:+ payload = json.load(handle)+ return payload if isinstance(payload, dict) else {}+ except FileNotFoundError:+ return {}+ except Exception:+ return {}+++def _write_auth_file_unlocked(path: Path, data: dict[str, Any]) -> None:path.parent.mkdir(parents=True, exist_ok=True)- path.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8")+ temporary_path = path.with_name(f".{path.name}.{os.getpid()}.{secrets.token_hex(8)}.tmp")try:- path.chmod(0o600)- except OSError:- pass+ descriptor = os.open(temporary_path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)+ with os.fdopen(descriptor, "w", encoding="utf-8") as handle:+ handle.write(json.dumps(data, indent=2) + "\n")+ handle.flush()+ os.fsync(handle.fileno())+ os.replace(temporary_path, path)+ try:+ path.chmod(0o600)+ except OSError:+ pass+ finally:+ temporary_path.unlink(missing_ok=True)+++def _validate_private_auth_path(path: Path) -> Path:+ if _path_key(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+++def _known_codex_auth_paths() -> list[Path]:+ candidates = [+ Path.home() / ".codex" / AUTH_FILENAME,+ Path.home() / ".chatgpt-local" / AUTH_FILENAME,+ ]+ for env_name in ("CODEX_HOME", "CHATGPT_LOCAL_HOME"):+ env_home = os.getenv(env_name)+ if env_home:+ candidates.append(Path(env_home).expanduser() / AUTH_FILENAME)+ return _unique_paths(candidates)+++def _path_key(path: Path) -> str:+ return os.path.normcase(str(path.expanduser().resolve(strict=False)))def parse_jwt_claims(token: str) -> dict[str, Any]:diff --git a/plugins/_oauth/webui/config.html b/plugins/_oauth/webui/config.htmlindex 4bbeb131d..f2269c2ff 100644--- a/plugins/_oauth/webui/config.html+++ b/plugins/_oauth/webui/config.html@@ -219,14 +219,15 @@</div><div><span>Auth file</span>- <code x-text="$store.oauthConfig.status?.codex?.auth_file_path || 'Auto-discover'"></code>+ <code x-text="$store.oauthConfig.status?.codex?.auth_file_path || 'Agent Zero private store'"></code></div></div><div class="oauth-grid"><label><span>Auth file path</span>- <input type="text" x-model="$store.oauthConfig.codex().auth_file_path" placeholder="Auto-discover" />+ <input type="text" x-model="$store.oauthConfig.codex().auth_file_path" placeholder="Agent Zero private store" />+ <small>Use an Agent Zero-owned file. Shared Codex CLI auth files are rejected.</small></label><label><span>Issuer</span>@@ -749,6 +750,12 @@gap: 6px;}+ .oauth-grid small {+ color: var(--color-text-secondary);+ font-size: 0.72rem;+ line-height: 1.35;+ }+.oauth-grid input[type="text"],.oauth-grid input[type="password"] {width: 100%;diff --git a/tests/test_oauth_codex.py b/tests/test_oauth_codex.pyindex d284b4921..e120e15de 100644--- a/tests/test_oauth_codex.py+++ b/tests/test_oauth_codex.py@@ -1,9 +1,15 @@from __future__ import annotationsimport json+import multiprocessing+import queue+import statimport sys+import threading+import timefrom pathlib import Path+import pytestimport yamlsys.path.insert(0, str(Path(__file__).resolve().parents[1]))@@ -227,14 +233,167 @@ def test_normalize_usage_payload_accepts_zero_percent_headers():assert usage["primary"]["label"] == "5h"-def test_disconnect_auth_clears_chatgpt_tokens_and_preserves_api_key(tmp_path, monkeypatch):+def test_default_auth_file_ignores_codex_cli_credentials(tmp_path, monkeypatch):+ shared_auth = tmp_path / ".codex" / "auth.json"+ private_auth = tmp_path / "usr" / "plugins" / "_oauth" / "codex" / "auth.json"+ shared_auth.parent.mkdir()+ shared_auth.write_text(json.dumps({"tokens": {"refresh_token": "shared"}}), encoding="utf-8")+ monkeypatch.setenv("HOME", str(tmp_path))+ monkeypatch.setattr(codex, "codex_config", lambda: {"auth_file_path": ""})+ monkeypatch.setattr(codex.files, "get_abs_path", lambda *parts: str(tmp_path.joinpath(*parts)))++ path, data = codex.read_auth_file()++ assert codex.resolve_auth_file_candidates() == [private_auth]+ assert path == private_auth+ assert data == {}+++def test_explicit_codex_cli_auth_path_is_rejected(tmp_path, monkeypatch):+ codex_home = tmp_path / "codex-home"+ monkeypatch.setenv("CODEX_HOME", str(codex_home))+ monkeypatch.setattr(codex, "codex_config", lambda: {"auth_file_path": str(codex_home / "auth.json")})++ with pytest.raises(RuntimeError, match="Agent Zero-owned auth file"):+ codex.resolve_auth_write_path()+++def test_write_auth_file_uses_atomic_replace_and_private_permissions(tmp_path, monkeypatch):+ auth_path = tmp_path / "auth.json"+ replacements: list[tuple[Path, Path]] = []+ replace = codex.os.replace++ def record_replace(source, destination):+ replacements.append((Path(source), Path(destination)))+ replace(source, destination)++ monkeypatch.setattr(codex.os, "replace", record_replace)++ codex.write_auth_file(auth_path, {"tokens": {"refresh_token": "refresh"}})++ assert json.loads(auth_path.read_text(encoding="utf-8")) == {+ "tokens": {"refresh_token": "refresh"}+ }+ assert stat.S_IMODE(auth_path.stat().st_mode) == 0o600+ assert len(replacements) == 1+ assert replacements[0][0] != auth_path+ assert replacements[0][1] == auth_path+ assert list(tmp_path.glob(".auth.json.*.tmp")) == []+++def test_load_auth_serializes_refresh_across_threads(tmp_path, monkeypatch):+ auth_path = tmp_path / "auth.json"+ _write_refreshable_auth(auth_path)+ monkeypatch.setattr(codex, "resolve_auth_write_path", lambda: auth_path)+ refresh_started = threading.Event()+ release_refresh = threading.Event()+ calls: list[str] = []+ results: list[codex.EffectiveAuth] = []++ def refresh_tokens(refresh_token: str) -> dict[str, str]:+ calls.append(refresh_token)+ refresh_started.set()+ assert release_refresh.wait(timeout=2)+ return _rotated_tokens()++ monkeypatch.setattr(codex, "refresh_tokens", refresh_tokens)+ first = threading.Thread(target=lambda: results.append(codex.load_auth()))+ second = threading.Thread(target=lambda: results.append(codex.load_auth()))++ first.start()+ assert refresh_started.wait(timeout=2)+ second.start()+ time.sleep(0.1)++ assert calls == ["refresh-0"]+ release_refresh.set()+ first.join(timeout=2)+ second.join(timeout=2)++ assert not first.is_alive()+ assert not second.is_alive()+ assert calls == ["refresh-0"]+ assert [result.refresh_token for result in results] == ["refresh-1", "refresh-1"]+++def test_load_auth_holds_lock_until_rotated_token_is_persisted(tmp_path, monkeypatch):+ auth_path = tmp_path / "auth.json"+ _write_refreshable_auth(auth_path)+ monkeypatch.setattr(codex, "resolve_auth_write_path", lambda: auth_path)+ persist_started = threading.Event()+ release_persist = threading.Event()+ calls: list[str] = []+ results: list[codex.EffectiveAuth] = []+ write_auth_file = codex._write_auth_file_unlocked++ def refresh_tokens(refresh_token: str) -> dict[str, str]:+ calls.append(refresh_token)+ return _rotated_tokens()++ def delay_write(path: Path, data: dict) -> None:+ persist_started.set()+ assert release_persist.wait(timeout=2)+ write_auth_file(path, data)++ monkeypatch.setattr(codex, "refresh_tokens", refresh_tokens)+ monkeypatch.setattr(codex, "_write_auth_file_unlocked", delay_write)+ first = threading.Thread(target=lambda: results.append(codex.load_auth()))+ second = threading.Thread(target=lambda: results.append(codex.load_auth()))++ first.start()+ assert persist_started.wait(timeout=2)+ second.start()+ time.sleep(0.1)++ assert calls == ["refresh-0"]+ release_persist.set()+ first.join(timeout=2)+ second.join(timeout=2)++ assert not first.is_alive()+ assert not second.is_alive()+ assert calls == ["refresh-0"]+ assert [result.refresh_token for result in results] == ["refresh-1", "refresh-1"]+++def test_load_auth_serializes_refresh_across_processes(tmp_path):+ auth_path = tmp_path / "auth.json"+ _write_refreshable_auth(auth_path)+ context = multiprocessing.get_context("spawn")+ refresh_started = context.Event()+ release_refresh = context.Event()+ calls = context.Queue()+ results = context.Queue()+ process_args = (str(auth_path), refresh_started, release_refresh, calls, results)+ first = context.Process(target=_load_auth_in_process, args=process_args)+ second = context.Process(target=_load_auth_in_process, args=process_args)++ first.start()+ assert refresh_started.wait(timeout=2)+ assert calls.get(timeout=2) == "refresh-0"+ second.start()+ with pytest.raises(queue.Empty):+ calls.get(timeout=0.2)++ release_refresh.set()+ first.join(timeout=3)+ second.join(timeout=3)++ assert first.exitcode == 0+ assert second.exitcode == 0+ with pytest.raises(queue.Empty):+ calls.get(timeout=0.2)+ assert sorted([results.get(timeout=2), results.get(timeout=2)]) == ["refresh-1", "refresh-1"]+++def test_disconnect_auth_only_mutates_agent_zero_private_auth_file(tmp_path, monkeypatch):private_auth = tmp_path / "private-auth.json"- shared_auth = tmp_path / "shared-auth.json"+ shared_auth = tmp_path / ".codex" / "auth.json"private_auth.write_text(json.dumps({"auth_mode": "chatgpt",- "OPENAI_API_KEY": None,+ "OPENAI_API_KEY": "sk-keep","tokens": {"access_token": "access","refresh_token": "refresh",@@ -246,26 +405,67 @@ def test_disconnect_auth_clears_chatgpt_tokens_and_preserves_api_key(tmp_path, m),encoding="utf-8",)+ shared_auth.parent.mkdir()shared_auth.write_text(json.dumps({"auth_mode": "chatgpt",- "OPENAI_API_KEY": "sk-keep",+ "OPENAI_API_KEY": None,"tokens": {"access_token": "access", "account_id": "account"},"last_refresh": "2026-01-01T00:00:00Z",}),encoding="utf-8",)- monkeypatch.setattr(codex, "resolve_auth_file_candidates", lambda: [private_auth, shared_auth])+ shared_before = shared_auth.read_text(encoding="utf-8")+ monkeypatch.setattr(codex, "resolve_auth_write_path", lambda: private_auth)result = codex.disconnect_auth()assert result["disconnected"] is True- assert str(private_auth) in result["removed_auth_files"]- assert not private_auth.exists()- preserved = json.loads(shared_auth.read_text(encoding="utf-8"))+ assert result["preserved_auth_files"] == [str(private_auth)]+ preserved = json.loads(private_auth.read_text(encoding="utf-8"))assert preserved == {"OPENAI_API_KEY": "sk-keep"}+ assert shared_auth.read_text(encoding="utf-8") == shared_before+++def _write_refreshable_auth(path: Path) -> None:+ path.write_text(+ json.dumps(+ {+ "auth_mode": "chatgpt",+ "tokens": {+ "access_token": "",+ "refresh_token": "refresh-0",+ "id_token": "",+ "account_id": "account",+ },+ "last_refresh": "",+ }+ ),+ encoding="utf-8",+ )+++def _rotated_tokens() -> dict[str, str]:+ return {+ "access_token": "access-1",+ "refresh_token": "refresh-1",+ "id_token": "",+ }+++def _load_auth_in_process(auth_path: str, refresh_started, release_refresh, calls, results) -> None:+ codex.resolve_auth_write_path = lambda: Path(auth_path)++ def refresh_tokens(refresh_token: str) -> dict[str, str]:+ calls.put(refresh_token)+ refresh_started.set()+ assert release_refresh.wait(timeout=5)+ return _rotated_tokens()++ codex.refresh_tokens = refresh_tokens+ results.put(codex.load_auth().refresh_token)def test_provider_config_uses_container_local_agent_zero_origin():