The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: Codex CLI recovery no longer replaces a credential from another workspace
Tranquil-Flowa745c3528214
diff --git a/hermes_cli/auth_codex.py b/hermes_cli/auth_codex.pyindex db55aefe802..4687f9b834b 100644--- a/hermes_cli/auth_codex.py+++ b/hermes_cli/auth_codex.py@@ -175,13 +175,21 @@ def _save_codex_tokens(tokens: Dict[str, str], last_refresh: str = None, label:_save_auth_store(auth_store)-def _recover_codex_tokens_from_cli(reason: str) -> Optional[Dict[str, str]]:+def _recover_codex_tokens_from_cli(+ reason: str, observed_access_token: Optional[str] = None) -> Optional[Dict[str, str]]:"""Adopt a valid Codex CLI token pair into Hermes auth, if available.Automatic adoption only; the interactive import offer in ``_login_openai_codex`` asks first and is- not subject to ``auth.adopt_external_logins``."""+ not subject to ``auth.adopt_external_logins``.++ ``observed_access_token`` is the singleton access_token (or None) the caller saw when it decided+ the credential needs repair. Recovery repairs THAT credential and nothing else (#73667): a Codex+ Desktop/CLI login into another ChatGPT workspace must not replace it silently, and a concurrent+ explicit re-auth must not be overwritten, so the save is a compare-and-swap under the store lock.+ """+ from agent.credential_pool import _codex_principal_identityfrom agent.credential_sources import adopt_external_logins_enabled- from hermes_cli.auth import _import_codex_cli_tokens, _save_codex_tokens+ from hermes_cli.auth import _import_codex_cli_tokens, _provider_state_transaction, _save_codex_tokensif not adopt_external_logins_enabled():return Noneimported = _import_codex_cli_tokens()@@ -190,8 +198,22 @@ def _recover_codex_tokens_from_cli(reason: str) -> Optional[Dict[str, str]]:if not (imported and _stripped(imported.get("access_token"))and _stripped(imported.get("refresh_token"))):return None- logger.info("Codex auth recovered from Codex CLI auth.json (%s).", reason)- _save_codex_tokens(imported)+ observed = _stripped(observed_access_token) or None+ with _provider_state_transaction("openai-codex") as (_store, state, _source):+ stored = (state or {}).get("tokens")+ stored = stored if isinstance(stored, dict) else {}+ if (_stripped(stored.get("access_token")) or None) != observed:+ logger.info("Codex CLI recovery skipped (%s): the credential was re-authenticated meanwhile.", reason)+ return None+ known = _codex_principal_identity(observed)+ if known and _codex_principal_identity(imported["access_token"]) not in (None, known):+ logger.warning(+ "Codex CLI recovery refused (%s): the Codex CLI login belongs to a different ChatGPT "+ "workspace than the Hermes credential. Run `%s` to re-authenticate it.",+ reason, _codex_relogin_command())+ return None+ logger.info("Codex auth recovered from Codex CLI auth.json (%s).", reason)+ _save_codex_tokens(imported) # nested: the per-path lock is reentrantreturn dict(imported)@@ -432,7 +454,8 @@ def _refresh_codex_auth_tokens(tokens: Dict[str, str], timeout_seconds: float) -if not getattr(exc, "relogin_required", False):raiseimported = _recover_codex_tokens_from_cli(- f"refresh_token rejected: {getattr(exc, 'code', None) or 'auth_error'}")+ f"refresh_token rejected: {getattr(exc, 'code', None) or 'auth_error'}",+ observed_access_token=stored_at or None)if not imported:raisereturn imported@@ -485,14 +508,22 @@ def resolve_codex_runtime_credentials(_read_codex_tokens)read_error: Optional[AuthError] = Nonedata = None+ observed: Optional[str] = Nonetry:- data = _read_codex_tokens()+ with _auth_store_lock():+ # Observe the singleton in the same locked snapshot the read validates, so recovery can+ # compare-and-swap against exactly the credential it is repairing (#73667).+ from hermes_cli.auth import _load_auth_store, _load_provider_state+ raw = (_load_provider_state(_load_auth_store(), "openai-codex") or {}).get("tokens")+ observed = raw.get("access_token") if isinstance(raw, dict) else None+ data = _read_codex_tokens(_lock=False)except AuthError as exc:read_error = excif exc.relogin_required and exc.code in {"codex_auth_missing_access_token", "codex_auth_missing_refresh_token","codex_auth_invalid_shape"}:- imported = _recover_codex_tokens_from_cli(str(exc.code or "auth_error"))+ imported = _recover_codex_tokens_from_cli(+ str(exc.code or "auth_error"), observed_access_token=observed)if imported:data = {"tokens": imported, "last_refresh": imported.get("last_refresh")}if data is None:diff --git a/tests/hermes_cli/test_auth_codex_self_heal.py b/tests/hermes_cli/test_auth_codex_self_heal.pyindex fa6182d7cb2..7d1247e9cf0 100644--- a/tests/hermes_cli/test_auth_codex_self_heal.py+++ b/tests/hermes_cli/test_auth_codex_self_heal.py@@ -10,7 +10,9 @@ surfacing a hard 401 — but ONLY for relogin-required failures, never for transones (e.g. 429 quota, where the stored token is still valid)."""+import base64import json+import timeimport pytest@@ -127,3 +129,61 @@ def test_opt_out_never_adopts_codex_cli_login(tmp_path, monkeypatch):_refresh_codex_auth_tokens(dict(STALE), 5.0)assert info.value.relogin_required # surfaced, not papered over with the CLI pairassert json.loads((hermes_home / "auth.json").read_text()) == hermes_auth+++def _codex_jwt(account_id: str, sub: str = "user-1") -> str:+ def _b64(d):+ return base64.urlsafe_b64encode(json.dumps(d).encode()).rstrip(b"=").decode()+ claims = {"sub": sub, "exp": int(time.time()) + 3600,+ "https://api.openai.com/auth": {"chatgpt_account_id": account_id}}+ return f"{_b64({'alg': 'none'})}.{_b64(claims)}.sig"+++def _seed_homes(tmp_path, monkeypatch, hermes_tokens, cli_tokens):+ hermes_home, codex_home = tmp_path / "hermes", tmp_path / "codex"+ hermes_home.mkdir()+ codex_home.mkdir()+ (hermes_home / "auth.json").write_text(json.dumps({"version": 1, "providers": {"openai-codex": {+ "tokens": hermes_tokens, "auth_mode": "chatgpt"}}}))+ (codex_home / "auth.json").write_text(json.dumps({"tokens": cli_tokens}))+ monkeypatch.setenv("HERMES_HOME", str(hermes_home))+ monkeypatch.setenv("CODEX_HOME", str(codex_home))+ return hermes_home / "auth.json"+++def test_recovery_refuses_codex_cli_login_from_another_workspace(tmp_path, monkeypatch, caplog):+ """#73667: a Codex Desktop/CLI login into ANOTHER ChatGPT workspace must not silently replace the+ Hermes credential it is supposed to repair — the store stays byte-identical and the log says why."""+ personal, team = _codex_jwt("acct-personal"), _codex_jwt("acct-team")+ auth_file = _seed_homes(tmp_path, monkeypatch, {"access_token": personal},+ {"access_token": team, "refresh_token": "rt-team"})+ before = auth_file.read_bytes()++ with caplog.at_level("WARNING", logger="hermes_cli.auth"), pytest.raises(AuthError) as info:+ resolve_codex_runtime_credentials(refresh_if_expiring=False)++ assert info.value.code == "codex_auth_missing_refresh_token"+ assert auth_file.read_bytes() == before+ assert "different ChatGPT workspace" in caplog.text and team not in caplog.text+++def test_recovery_does_not_overwrite_concurrent_reauth(tmp_path, monkeypatch):+ """#73667 (review): an explicit re-auth landing between the failed read and the recovery save must+ win — the save is a compare-and-swap on the observed access_token, not a blind overwrite."""+ personal, reauthed = _codex_jwt("acct-personal"), _codex_jwt("acct-personal", sub="user-1-fresh")+ auth_file = _seed_homes(tmp_path, monkeypatch, {"access_token": personal},+ {"access_token": _codex_jwt("acct-personal"), "refresh_token": "rt-cli"})+ real_import = auth_codex._import_codex_cli_tokens++ def _import_racing_with_reauth():+ auth_codex._save_codex_tokens({"access_token": reauthed, "refresh_token": "rt-reauthed"})+ return real_import()++ monkeypatch.setattr(auth, "_import_codex_cli_tokens", _import_racing_with_reauth)+ monkeypatch.setattr(auth_codex, "_import_codex_cli_tokens", _import_racing_with_reauth)++ with pytest.raises(AuthError):+ resolve_codex_runtime_credentials(refresh_if_expiring=False)++ tokens = json.loads(auth_file.read_text())["providers"]["openai-codex"]["tokens"]+ assert tokens == {"access_token": reauthed, "refresh_token": "rt-reauthed"}diff --git a/website/docs/user-guide/security.md b/website/docs/user-guide/security.mdindex 9b1b77b1383..41fec8ff91f 100644--- a/website/docs/user-guide/security.md+++ b/website/docs/user-guide/security.md@@ -674,7 +674,7 @@ auth:adopt_external_logins: false # default: true```-With the switch off Hermes never reads or refreshes those files: the `claude_code` credential-pool row disappears, `hermes auth list` prints one line saying so, and the log carries one INFO line per process. Only automatic adoption is affected — `hermes auth add openai-codex` still asks before importing an existing Codex CLI login. Add your own logins with `hermes auth add anthropic` / `hermes auth add openai-codex`.+With the switch off Hermes never reads or refreshes those files: the `claude_code` credential-pool row disappears, `hermes auth list` prints one line saying so, and the log carries one INFO line per process. Only automatic adoption is affected — `hermes auth add openai-codex` still asks before importing an existing Codex CLI login. Automatic recovery also only repairs the credential Hermes already holds: a Codex CLI/Desktop login into a different ChatGPT workspace is refused with a warning (re-authenticate with `hermes auth add openai-codex`), and a login you complete while recovery is running is never overwritten. Add your own logins with `hermes auth add anthropic` / `hermes auth add openai-codex`.### What Each Sandbox Filters