mirror of
https://github.com/headroomlabs-ai/headroom.git
synced 2026-11-22 13:29:19 +08:00
fix(codex): preserve auth.json API keys through Headroom (#3355)
## Description Closes #3354. When Codex uses an OpenAI API key stored in auth.json, Headroom's generated provider block did not configure authentication. Codex therefore sent requests to the local Headroom proxy without an Authorization header and received 401 Missing bearer. This is separate from #3206: that issue covers ChatGPT OAuth authentication, while this change covers file-backed API-key authentication. ## Type of Change - [x] Bug fix (non-breaking change that fixes an issue) - [ ] New feature - [ ] Breaking change - [ ] Documentation update - [ ] Performance improvement - [ ] Code refactoring ## Changes Made - Resolve API-key and OAuth credentials from `codex_home_dir()` for both project and user configurations, honoring `CODEX_HOME`. - Generate a private, config-specific helper beside `auth.json`; API keys stay out of generated TOML and Headroom environment variables. - Configure Codex's supported `auth.command` field for persistent install, init, and wrap. - Serialize command and argument paths with literal Unicode and validate generated TOML before writing provider configurations. - Abort provider updates with an actionable error if a helper collides with another file/symlink or cannot be created. - Use exclusive creation, 0600 permissions on Unix, and content checks for helper ownership. - Give project and user configurations independent helper lifetimes. Retain legacy shared helpers and helpers referenced by restored/remaining providers or unparseable configurations. - Preserve unrelated files and the original provider config when authentication setup fails. - Remove an unused config-specific helper on uninstall/unwrap. ## Testing - [x] Focused unit and integration tests pass - [x] Linting and formatting pass - [ ] Type checking - [x] New regression tests added - [x] Manual runtime testing performed ### Test Output ```text $ .venv/bin/python -m pytest tests/test_provider_codex_install.py tests/test_install/test_codex_install.py tests/test_cli/test_init_cli.py tests/test_install/test_providers.py tests/test_cli/test_wrap_codex.py -q 284 passed $ .venv/bin/ruff check . All checks passed! $ .venv/bin/ruff format --check . 1744 files already formatted ``` Ruff 0.16.8 matches this branch's CI pin. A focused coverage run reports 93% line/branch coverage for `headroom/providers/codex/install.py` and covers 44/45 newly added executable lines across the three production files in this follow-up. This is local focused coverage, not a claim about the hosted Codecov aggregate. Before the follow-up implementation, the added local-init/Unicode/helper-isolation regressions produced 6 failures while 118 existing tests passed. ## Real Behavior Proof - Environment: macOS 26.6.2, Apple Silicon arm64, Python 3.12.11, Headroom source from this PR, Codex CLI 0.160.0, Sub2API OpenAI-compatible provider, model `gpt-6-luna`, existing API key in the user's Codex `auth.json`. - Setup: start an isolated Headroom proxy on an unused loopback port with `ProxyConfig(optimize=False, cache_enabled=False, rate_limit_enabled=False, openai_api_url=<existing upstream>)`. Generate a temporary provider config with `_ensure_codex_provider(config_path, port)` while credentials resolve from the user's Codex home. Add `model = "gpt-6-luna"` and `model_reasoning_effort = "low"` at the document root. Run the child with its own temporary `CODEX_HOME` and no `OPENAI_API_KEY` or `OPENAI_BASE_URL` environment variable; its home contains the generated config, not a copied credential file. - Exact child command: ```sh CODEX_HOME=<temporary-home> codex exec --ephemeral --skip-git-repo-check --sandbox read-only --json -C <temporary-workspace> 'Reply with exactly OK. Do not call tools.' ``` Captured after-fix output on 2026-10-07: ```text Headroom test proxy: ready (optimization disabled) Codex: 0.160.0; model: gpt-6-luna; auth: generated command, no API-key environment variable codex exec exit: 0 agent messages: ['OK'] Responses bearer matches auth.json: True ``` The last line comes from an ASGI wrapper that compares the HTTP/WebSocket Responses request bearer with the file-backed key without logging either value. The command completed against the real upstream; no mocked model response was used. The temporary provider config/helper and test proxy were removed after validation. - Observed limitation: this upstream rejects WebSocket negotiation with HTTP 426, so Headroom's existing HTTP streaming fallback completed the request. This run proves file-backed command authentication and successful proxy routing, not a successful upstream WebSocket session. - Not tested in this follow-up: a new Windows/Linux runtime run, full test suite, native-extension rebuild, or optimization behavior. The focused Python suite reused the existing local native extension; no Rust code changed. ## Runtime Rollout Safety - Rollout-managed feature(s): None. - Minimum rollout channel: N/A. - Stable/default behavior changed: Yes, only when Codex has a file-backed API key and Headroom writes a provider block. - Kill switch / disable path: Remove the Headroom-managed provider block or run the existing Codex unwrap command. - Unsafe override required: No. - Qualification impact: None. - Rollback path: Revert the generated provider block; auth.json is unchanged. ## Review Readiness - [x] I have performed a self-review - [x] This PR is ready for human review ## Checklist - [x] My code follows the project's style guidelines - [x] I have performed a self-review of the code - [x] My changes generate no new warnings - [x] I have added tests that prove my fix is effective - [x] New and existing unit tests pass locally with my changes - [x] I did not edit CHANGELOG.md ## Additional Notes Helpers contain no credential value and read the user's existing credential file at runtime, so key rotation does not require reinstalling. Helper names now include a hash of the owning config's canonical path. Legacy fixed-name helpers are retained conservatively because other project configurations may still use them. <!-- devin-review-badge-begin --> --- <a href="https://app.devin.ai/review/headroomlabs-ai/headroom/pull/3355" target="_blank"><picture><source media="(prefers-color-scheme: dark)" srcset="https://static.devin.ai/assets/gh-devin-review-dark.svg?v=4"><img src="https://static.devin.ai/assets/gh-devin-review-light.svg?v=4" alt="Devin Review"></picture></a> <!-- devin-review-badge-end --> --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com> Co-authored-by: JD Davis <mxjerrett@gmail.com>
This commit is contained in:
co-authored by
Claude Opus 4.6
JD Davis
parent
59bd482fa1
commit
a6523b1967
+78
-5
@@ -36,6 +36,7 @@ from headroom.install.models import ConfigScope, InstallPreset, RuntimeKind, Sup
|
||||
from headroom.install.paths import (
|
||||
claude_settings_path,
|
||||
codex_config_path,
|
||||
codex_home_dir,
|
||||
codex_hooks_path,
|
||||
codex_project_config_path,
|
||||
validate_profile_name,
|
||||
@@ -56,7 +57,11 @@ from headroom.install.state import ManifestError, load_manifest, save_manifest
|
||||
from headroom.install.supervisors import start_supervisor
|
||||
from headroom.providers.claude import TOOL_SEARCH_DEFAULT, TOOL_SEARCH_ENV
|
||||
from headroom.providers.claude.runtime import TOOL_SEARCH_FOUNDRY_DEFAULT
|
||||
from headroom.providers.codex.install import codex_uses_chatgpt_auth
|
||||
from headroom.providers.codex.install import (
|
||||
CodexAuthConfigError,
|
||||
build_codex_auth_config,
|
||||
codex_uses_chatgpt_auth,
|
||||
)
|
||||
from headroom.providers.codex.threads import retag_to_headroom
|
||||
|
||||
from .main import main
|
||||
@@ -340,10 +345,26 @@ def _strip_codex_root_routing_orphans(content: str) -> str:
|
||||
return root + rest
|
||||
|
||||
|
||||
def _strip_codex_init_block(content: str) -> str:
|
||||
_CODEX_PROVIDER_SNAPSHOT_PREFIX = "# Headroom init previous provider: "
|
||||
|
||||
|
||||
def _codex_init_provider_snapshot(content: str) -> str | None:
|
||||
match = re.search(r"(?m)^" + re.escape(_CODEX_PROVIDER_SNAPSHOT_PREFIX) + r"([^\n]*)", content)
|
||||
if match is None:
|
||||
return None
|
||||
snapshot = json.loads(match.group(1))
|
||||
if not isinstance(snapshot, str):
|
||||
raise ValueError("Invalid Headroom init provider snapshot")
|
||||
tomllib.loads(snapshot)
|
||||
return snapshot
|
||||
|
||||
|
||||
def _strip_codex_init_block(content: str, *, restore_provider: bool = True) -> str:
|
||||
"""Remove all Headroom init-managed blocks and orphan keys from a Codex config.toml string."""
|
||||
import re
|
||||
|
||||
provider_snapshot = _codex_init_provider_snapshot(content)
|
||||
|
||||
# Remove any provider marker → end marker span, possibly repeated.
|
||||
while _CODEX_PROVIDER_MARKER_START in content and _CODEX_PROVIDER_MARKER_END in content:
|
||||
start = content.index(_CODEX_PROVIDER_MARKER_START)
|
||||
@@ -368,6 +389,8 @@ def _strip_codex_init_block(content: str) -> str:
|
||||
r"(?=^\[|\Z)"
|
||||
)
|
||||
content = orphan_headroom_table.sub("", content)
|
||||
if restore_provider and provider_snapshot is not None:
|
||||
content = content.rstrip() + "\n\n" + provider_snapshot
|
||||
|
||||
return content.lstrip("\n").rstrip() + "\n" if content.strip() else ""
|
||||
|
||||
@@ -377,14 +400,17 @@ def _ensure_codex_provider(path: Path, port: int) -> None:
|
||||
|
||||
logger.debug("ensure codex provider block: %s (port=%s)", path, port)
|
||||
warn_codex_provider_port_change(path, port)
|
||||
auth_path = codex_home_dir() / "auth.json"
|
||||
# Emit requires_openai_auth only for ChatGPT-OAuth users (restores the
|
||||
# account menu); omitting it for API-key users avoids forcing an OAuth
|
||||
# login (#406).
|
||||
requires_openai_auth = (
|
||||
"requires_openai_auth = true\n"
|
||||
if codex_uses_chatgpt_auth(path.parent / "auth.json")
|
||||
else ""
|
||||
"requires_openai_auth = true\n" if codex_uses_chatgpt_auth(auth_path) else ""
|
||||
)
|
||||
try:
|
||||
auth_config = build_codex_auth_config(auth_path, config_path=path)
|
||||
except CodexAuthConfigError as exc:
|
||||
raise click.ClickException(str(exc)) from exc
|
||||
block = (
|
||||
f"{_CODEX_PROVIDER_MARKER_START}\n"
|
||||
'model_provider = "headroom"\n'
|
||||
@@ -396,10 +422,56 @@ def _ensure_codex_provider(path: Path, port: int) -> None:
|
||||
'name = "OpenAI"\n'
|
||||
f'base_url = "http://127.0.0.1:{port}/v1"\n'
|
||||
"supports_websockets = true\n"
|
||||
f"{auth_config}"
|
||||
f"{requires_openai_auth}"
|
||||
f"{_CODEX_PROVIDER_MARKER_END}"
|
||||
)
|
||||
content = path.read_text(encoding="utf-8") if path.exists() else ""
|
||||
# Adopt an existing unmarked provider table instead of declaring it twice.
|
||||
# Keep user options that are not owned by the generated provider block.
|
||||
provider_snapshot = _codex_init_provider_snapshot(content)
|
||||
provider_table = re.search(
|
||||
r"(?m)^[ \t]*\[model_providers\.headroom\][ \t]*(?:#[^\n]*)?\r?\n", content
|
||||
)
|
||||
if provider_table:
|
||||
next_table = re.search(r"(?m)^[ \t]*\[", content[provider_table.end() :])
|
||||
table_end = provider_table.end() + next_table.start() if next_table else len(content)
|
||||
if provider_snapshot is None and _CODEX_PROVIDER_MARKER_START not in content:
|
||||
provider_snapshot = content[provider_table.start() : table_end]
|
||||
existing_options = content[provider_table.end() : table_end]
|
||||
existing_options = re.sub(
|
||||
r"(?m)^" + re.escape(_CODEX_PROVIDER_SNAPSHOT_PREFIX) + r"[^\n]*(?:\n|$)",
|
||||
"",
|
||||
existing_options,
|
||||
)
|
||||
existing_options = existing_options.replace(_CODEX_PROVIDER_MARKER_END, "")
|
||||
generated_keys = set(re.findall(r"(?m)^([A-Za-z_][A-Za-z_0-9]*)[ \t]*=", block))
|
||||
generated_keys.update(
|
||||
{"auth", "env_key", "requires_openai_auth", "experimental_bearer_token"}
|
||||
)
|
||||
for key in generated_keys:
|
||||
existing_options = re.sub(
|
||||
rf"(?m)^[ \t]*{re.escape(key)}[ \t]*=[^\n]*(?:\n|$)",
|
||||
"",
|
||||
existing_options,
|
||||
)
|
||||
block = block.replace(
|
||||
_CODEX_PROVIDER_MARKER_END,
|
||||
existing_options + _CODEX_PROVIDER_MARKER_END,
|
||||
)
|
||||
if _CODEX_PROVIDER_MARKER_START not in content:
|
||||
content = content[: provider_table.start()] + content[table_end:]
|
||||
content = _replace_marker_block(
|
||||
content, _CODEX_PROVIDER_MARKER_START, _CODEX_PROVIDER_MARKER_END, "", at_root=True
|
||||
)
|
||||
if provider_snapshot is not None:
|
||||
block = block.replace(
|
||||
_CODEX_PROVIDER_MARKER_END,
|
||||
_CODEX_PROVIDER_SNAPSHOT_PREFIX
|
||||
+ json.dumps(provider_snapshot)
|
||||
+ "\n"
|
||||
+ _CODEX_PROVIDER_MARKER_END,
|
||||
)
|
||||
# init owns the ROOT-level model_provider/openai_base_url: drop any prior
|
||||
# root assignment so we replace it instead of emitting a duplicate top-level
|
||||
# key (#260). Scope the strip to the document root (everything before the
|
||||
@@ -418,6 +490,7 @@ def _ensure_codex_provider(path: Path, port: int) -> None:
|
||||
content, _CODEX_PROVIDER_MARKER_START, _CODEX_PROVIDER_MARKER_END, block, at_root=True
|
||||
)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
tomllib.loads(content)
|
||||
path.write_text(content, encoding="utf-8")
|
||||
# Codex filters its history menu by the active model_provider, so existing
|
||||
# native threads vanish once we switch to "headroom". Retag them to match the
|
||||
|
||||
+50
-3
@@ -113,7 +113,14 @@ from headroom.providers.claude import (
|
||||
)
|
||||
from headroom.providers.claude.runtime import TOOL_SEARCH_FOUNDRY_DEFAULT
|
||||
from headroom.providers.codex import build_launch_env as _build_codex_launch_env
|
||||
from headroom.providers.codex.install import codex_uses_chatgpt_auth
|
||||
from headroom.providers.codex.install import (
|
||||
CodexAuthConfigError,
|
||||
build_codex_auth_config,
|
||||
cleanup_codex_auth_helper,
|
||||
codex_auth_helper_is_referenced,
|
||||
codex_auth_helper_path,
|
||||
codex_uses_chatgpt_auth,
|
||||
)
|
||||
from headroom.providers.codex.threads import retag_to_headroom, retag_to_native
|
||||
from headroom.providers.copilot import (
|
||||
build_launch_env as _build_copilot_launch_env,
|
||||
@@ -3516,6 +3523,10 @@ def _inject_codex_provider_config(port: int) -> str | None:
|
||||
requires_openai_auth = (
|
||||
"requires_openai_auth = true\n" if codex_uses_chatgpt_auth(config_dir / "auth.json") else ""
|
||||
)
|
||||
try:
|
||||
auth_config = build_codex_auth_config(config_dir / "auth.json", config_path=config_file)
|
||||
except CodexAuthConfigError as exc:
|
||||
raise click.ClickException(str(exc)) from exc
|
||||
# Per-project savings: Codex sends the X-Headroom-Project header only
|
||||
# when the mapped env var (HEADROOM_PROJECT, set by `headroom wrap
|
||||
# codex`) exists at Codex runtime. When a custom upstream was detected,
|
||||
@@ -3531,6 +3542,7 @@ def _inject_codex_provider_config(port: int) -> str | None:
|
||||
'name = "OpenAI via Headroom proxy"\n'
|
||||
f'base_url = "http://127.0.0.1:{port}/v1"\n'
|
||||
f"supports_websockets = true\n"
|
||||
f"{auth_config}"
|
||||
f"{requires_openai_auth}"
|
||||
# Inline table keeps the key inside this section so
|
||||
# _strip_codex_headroom_blocks removes it with the rest of the block.
|
||||
@@ -3645,12 +3657,27 @@ def _restore_codex_provider_config() -> tuple[str, Path]:
|
||||
content (created by wrap or init) and has been deleted.
|
||||
* ``"noop"`` — nothing to undo; no Headroom marker and no backup.
|
||||
"""
|
||||
from headroom.cli.init import _CODEX_PROVIDER_MARKER_START, _strip_codex_init_block
|
||||
from headroom.cli.init import (
|
||||
_CODEX_PROVIDER_MARKER_START,
|
||||
_codex_init_provider_snapshot,
|
||||
_strip_codex_init_block,
|
||||
)
|
||||
|
||||
config_file, backup_file = _codex_config_paths()
|
||||
helper_auth_path = config_file.parent / "auth.json"
|
||||
helper_path = codex_auth_helper_path(helper_auth_path, config_path=config_file)
|
||||
|
||||
# Case 1: pre-wrap snapshot exists — restore it exactly.
|
||||
if backup_file.exists():
|
||||
try:
|
||||
helper_was_preexisting = (
|
||||
codex_auth_helper_is_referenced(_read_text(backup_file), str(helper_path.resolve()))
|
||||
is not False
|
||||
)
|
||||
except OSError:
|
||||
# If the backup cannot be inspected, preserve the helper rather than
|
||||
# risk deleting a file that predates this wrap.
|
||||
helper_was_preexisting = True
|
||||
# A snapshot taken after `headroom init codex` still carries init's
|
||||
# routing block; restoring it verbatim would leave Codex pinned to the
|
||||
# proxy while unwrap reports success (#3749). The snapshot is deleted
|
||||
@@ -3661,11 +3688,17 @@ def _restore_codex_provider_config() -> tuple[str, Path]:
|
||||
if not cleaned.strip():
|
||||
config_file.unlink(missing_ok=True)
|
||||
backup_file.unlink()
|
||||
cleanup_codex_auth_helper(helper_auth_path, config_path=config_file)
|
||||
return "removed", config_file
|
||||
_write_text(config_file, cleaned)
|
||||
# Init's helper may predate wrap but its only reference was just
|
||||
# removed. Cleanup checks all retained providers before deleting it.
|
||||
cleanup_codex_auth_helper(helper_auth_path, config_path=config_file)
|
||||
else:
|
||||
shutil.copy2(backup_file, config_file)
|
||||
backup_file.unlink()
|
||||
if not helper_was_preexisting:
|
||||
cleanup_codex_auth_helper(helper_auth_path, config_path=config_file)
|
||||
return "restored", config_file
|
||||
|
||||
# Case 2: no backup, but config file exists and has markers — strip them.
|
||||
@@ -3673,6 +3706,9 @@ def _restore_codex_provider_config() -> tuple[str, Path]:
|
||||
original = _read_text(config_file)
|
||||
has_init_block = _CODEX_PROVIDER_MARKER_START in original
|
||||
if has_init_block or _codex_config_has_headroom_markers(original):
|
||||
helper_was_referenced = codex_auth_helper_is_referenced(
|
||||
original, str(helper_path.resolve())
|
||||
)
|
||||
# Without a backup, only remove named MCP blocks when this file
|
||||
# also carries wrap-owned provider markers from a full wrap.
|
||||
remove_named_mcp = any(
|
||||
@@ -3686,18 +3722,29 @@ def _restore_codex_provider_config() -> tuple[str, Path]:
|
||||
)
|
||||
# `headroom init codex` writes its own routing block, and nothing else
|
||||
# removes it (#3749). Strip it first so its markers go with its keys.
|
||||
content = _strip_codex_init_block(original) if has_init_block else original
|
||||
provider_snapshot = _codex_init_provider_snapshot(original) if has_init_block else None
|
||||
content = (
|
||||
_strip_codex_init_block(original, restore_provider=False)
|
||||
if has_init_block
|
||||
else original
|
||||
)
|
||||
cleaned = _strip_codex_headroom_blocks(
|
||||
content,
|
||||
remove_mcp=True,
|
||||
remove_named_mcp=remove_named_mcp,
|
||||
)
|
||||
if provider_snapshot is not None:
|
||||
cleaned = cleaned.rstrip() + "\n\n" + provider_snapshot
|
||||
if not cleaned.strip():
|
||||
# Nothing left but Headroom content — remove the file entirely
|
||||
# so Codex falls back to its default config.
|
||||
config_file.unlink()
|
||||
if helper_was_referenced is True:
|
||||
cleanup_codex_auth_helper(helper_auth_path, config_path=config_file)
|
||||
return "removed", config_file
|
||||
_write_text(config_file, cleaned)
|
||||
if helper_was_referenced is True:
|
||||
cleanup_codex_auth_helper(helper_auth_path, config_path=config_file)
|
||||
return "cleaned", config_file
|
||||
|
||||
# Nothing to undo.
|
||||
|
||||
@@ -7,6 +7,8 @@ import json
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
from hashlib import sha256
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
@@ -44,6 +46,21 @@ _ORPHAN_HEADROOM_TABLE = re.compile(
|
||||
_TOML_TABLE_HEADER_RE = re.compile(r"^[ \t]*(?:\[\[[^\]\r\n]+\]\]|\[[^\]\r\n]+\])[ \t]*(?:#.*)?$")
|
||||
_ROOT_MODEL_PROVIDER_RE = re.compile(r"^[ \t]*model_provider[ \t]*=")
|
||||
_ROOT_OPENAI_BASE_URL_RE = re.compile(r"^[ \t]*openai_base_url[ \t]*=")
|
||||
_CODEX_API_KEY_HELPER = """from pathlib import Path
|
||||
import json
|
||||
|
||||
|
||||
try:
|
||||
auth = json.loads(Path(__file__).with_name("auth.json").read_text(encoding="utf-8"))
|
||||
except (OSError, ValueError):
|
||||
raise SystemExit(2)
|
||||
|
||||
key = auth.get("OPENAI_API_KEY") if isinstance(auth, dict) else None
|
||||
if not isinstance(key, str) or not key.strip():
|
||||
raise SystemExit(2)
|
||||
|
||||
print(key, end="")
|
||||
"""
|
||||
|
||||
|
||||
def _codex_credential_store(config_dir: Path) -> str | None:
|
||||
@@ -107,6 +124,158 @@ def codex_uses_chatgpt_auth(auth_path: Path) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def codex_uses_api_key_auth(auth_path: Path) -> bool:
|
||||
"""Whether Codex has a file-backed OpenAI API key.
|
||||
|
||||
A custom provider does not read Codex's ``auth.json`` when
|
||||
``requires_openai_auth`` is false. Detect the API-key shape separately so
|
||||
the generated provider can use Codex's command-backed bearer-token config
|
||||
without forcing API-key users into the OAuth login flow.
|
||||
"""
|
||||
try:
|
||||
data = json.loads(auth_path.read_text(encoding="utf-8"))
|
||||
except (OSError, ValueError):
|
||||
return False
|
||||
return (
|
||||
isinstance(data, dict)
|
||||
and isinstance(data.get("OPENAI_API_KEY"), str)
|
||||
and bool(data["OPENAI_API_KEY"].strip())
|
||||
)
|
||||
|
||||
|
||||
class CodexAuthConfigError(RuntimeError):
|
||||
"""A file-backed API key cannot be safely wired into the provider."""
|
||||
|
||||
|
||||
def codex_auth_helper_path(auth_path: Path, *, config_path: Path | None = None) -> Path:
|
||||
"""Give each provider config its own helper beside the credential file.
|
||||
|
||||
Local and user configs can share credentials without sharing a helper's
|
||||
lifetime. The old fixed-name helper is deliberately never deleted: other
|
||||
project configs may still reference it.
|
||||
"""
|
||||
config_path = config_path or auth_path.parent / "config.toml"
|
||||
identity = os.path.normcase(str(config_path.resolve()))
|
||||
digest = sha256(identity.encode("utf-8")).hexdigest()
|
||||
return auth_path.parent / f".headroom-codex-auth-{digest}.py"
|
||||
|
||||
|
||||
def build_codex_auth_config(auth_path: Path | None, *, config_path: Path | None = None) -> str:
|
||||
"""Build a Codex provider auth command for a file-backed API key.
|
||||
|
||||
The helper is generated next to ``auth.json`` and emits only the token at
|
||||
runtime. The token is never copied into Headroom's environment or the
|
||||
generated TOML configuration.
|
||||
"""
|
||||
if auth_path is None or codex_uses_chatgpt_auth(auth_path):
|
||||
return ""
|
||||
if not codex_uses_api_key_auth(auth_path):
|
||||
return ""
|
||||
|
||||
helper_path = codex_auth_helper_path(auth_path, config_path=config_path)
|
||||
if not _ensure_codex_auth_helper(helper_path):
|
||||
raise CodexAuthConfigError(
|
||||
f"Cannot create or validate Codex auth helper {helper_path}. "
|
||||
"Check directory permissions and move any conflicting file or symlink, "
|
||||
"then retry. Codex provider configuration was not updated."
|
||||
)
|
||||
|
||||
config = (
|
||||
"auth = { command = "
|
||||
f"{json.dumps(sys.executable, ensure_ascii=False)}, "
|
||||
f"args = [{json.dumps(str(helper_path.resolve()), ensure_ascii=False)}], "
|
||||
"refresh_interval_ms = 300000 }\n"
|
||||
)
|
||||
tomllib.loads(config)
|
||||
return config
|
||||
|
||||
|
||||
def _ensure_codex_auth_helper(helper_path: Path) -> bool:
|
||||
"""Create or validate the private, Headroom-owned auth helper."""
|
||||
created = False
|
||||
try:
|
||||
# Never follow a user-created link or overwrite an unrelated file.
|
||||
if helper_path.is_symlink():
|
||||
return False
|
||||
if helper_path.exists():
|
||||
if not helper_path.is_file():
|
||||
return False
|
||||
if helper_path.read_text(encoding="utf-8") != _CODEX_API_KEY_HELPER:
|
||||
return False
|
||||
helper_path.chmod(0o600)
|
||||
return True
|
||||
|
||||
flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL
|
||||
flags |= getattr(os, "O_NOFOLLOW", 0)
|
||||
fd = os.open(helper_path, flags, 0o600)
|
||||
created = True
|
||||
try:
|
||||
with os.fdopen(fd, "w", encoding="utf-8", newline="") as handle:
|
||||
fd = -1
|
||||
handle.write(_CODEX_API_KEY_HELPER)
|
||||
handle.flush()
|
||||
os.fsync(handle.fileno())
|
||||
finally:
|
||||
if fd >= 0:
|
||||
os.close(fd)
|
||||
helper_path.chmod(0o600)
|
||||
return True
|
||||
except (OSError, UnicodeError):
|
||||
if created:
|
||||
try:
|
||||
if helper_path.is_file() and not helper_path.is_symlink():
|
||||
helper_path.unlink()
|
||||
except OSError:
|
||||
pass
|
||||
return False
|
||||
|
||||
|
||||
def cleanup_codex_auth_helper(auth_path: Path, *, config_path: Path | None = None) -> None:
|
||||
"""Remove this config's helper only when no retained provider uses it."""
|
||||
config_path = config_path or auth_path.parent / "config.toml"
|
||||
helper_path = codex_auth_helper_path(auth_path, config_path=config_path)
|
||||
try:
|
||||
if (
|
||||
config_path.exists()
|
||||
and codex_auth_helper_is_referenced(
|
||||
config_path.read_text(encoding="utf-8"), str(helper_path.resolve())
|
||||
)
|
||||
is not False
|
||||
):
|
||||
return
|
||||
if (
|
||||
helper_path.is_symlink()
|
||||
or not helper_path.is_file()
|
||||
or helper_path.read_text(encoding="utf-8") != _CODEX_API_KEY_HELPER
|
||||
):
|
||||
return
|
||||
helper_path.unlink()
|
||||
except (OSError, UnicodeError):
|
||||
return
|
||||
|
||||
|
||||
def codex_auth_helper_is_referenced(content: str, helper_path: str) -> bool | None:
|
||||
"""Whether any parsed Codex provider names this exact generated helper.
|
||||
|
||||
``None`` means the configuration is not parseable, so callers can retain
|
||||
the helper instead of risking deletion of a pre-existing user file.
|
||||
"""
|
||||
try:
|
||||
document = tomllib.loads(content)
|
||||
except (tomllib.TOMLDecodeError, TypeError):
|
||||
return None
|
||||
|
||||
providers = document.get("model_providers")
|
||||
if not isinstance(providers, dict):
|
||||
return False
|
||||
for provider in providers.values():
|
||||
auth = provider.get("auth") if isinstance(provider, dict) else None
|
||||
args = auth.get("args") if isinstance(auth, dict) else None
|
||||
if isinstance(args, list) and helper_path in args:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _id_token_carries_chatgpt_account(raw: Any) -> bool:
|
||||
"""Whether an ``id_token`` carries the ChatGPT account claim (#3206).
|
||||
|
||||
@@ -150,6 +319,8 @@ def build_provider_section(
|
||||
marker_end: str = _CODEX_MARKER_END,
|
||||
include_markers: bool = True,
|
||||
requires_openai_auth: bool = False,
|
||||
auth_path: Path | None = None,
|
||||
config_path: Path | None = None,
|
||||
) -> str:
|
||||
"""Build a managed Codex provider block.
|
||||
|
||||
@@ -163,6 +334,7 @@ def build_provider_section(
|
||||
f'name = "{name}"\n'
|
||||
f'base_url = "{proxy_base_url(port)}"\n'
|
||||
"supports_websockets = true\n"
|
||||
f"{build_codex_auth_config(auth_path, config_path=config_path)}"
|
||||
)
|
||||
if requires_openai_auth:
|
||||
body += "requires_openai_auth = true\n"
|
||||
@@ -228,6 +400,8 @@ def apply_provider_scope(manifest: DeploymentManifest) -> ManagedMutation | None
|
||||
name="Headroom persistent proxy",
|
||||
include_markers=False,
|
||||
requires_openai_auth=codex_uses_chatgpt_auth(path.parent / "auth.json"),
|
||||
auth_path=path.parent / "auth.json",
|
||||
config_path=path,
|
||||
)
|
||||
+ f"{_CODEX_MARKER_END}\n"
|
||||
)
|
||||
@@ -237,6 +411,7 @@ def apply_provider_scope(manifest: DeploymentManifest) -> ManagedMutation | None
|
||||
existing = _CODEX_PATTERN.sub("", existing)
|
||||
existing = _strip_root_provider_assignments(existing)
|
||||
merged = _insert_block_at_root(existing, section)
|
||||
tomllib.loads(merged)
|
||||
path.write_text(merged, encoding="utf-8")
|
||||
# Pull existing native threads into the headroom-provider menu so Codex's
|
||||
# history list stays whole once it routes through Headroom. Best-effort.
|
||||
@@ -253,6 +428,8 @@ def revert_provider_scope(mutation: ManagedMutation, manifest: DeploymentManifes
|
||||
if not path.exists():
|
||||
return
|
||||
content = path.read_text(encoding="utf-8")
|
||||
helper_path = codex_auth_helper_path(path.parent / "auth.json", config_path=path)
|
||||
helper_was_referenced = codex_auth_helper_is_referenced(content, str(helper_path.resolve()))
|
||||
# Remove the managed marker block.
|
||||
if _CODEX_MARKER_START in content:
|
||||
content = _CODEX_PATTERN.sub("", content)
|
||||
@@ -262,6 +439,8 @@ def revert_provider_scope(mutation: ManagedMutation, manifest: DeploymentManifes
|
||||
content = _ORPHAN_OPENAI_BASE_URL.sub("", content)
|
||||
content = _ORPHAN_HEADROOM_TABLE.sub("", content)
|
||||
path.write_text(content.strip() + "\n", encoding="utf-8")
|
||||
if helper_was_referenced is True:
|
||||
cleanup_codex_auth_helper(path.parent / "auth.json", config_path=path)
|
||||
# Hand the threads back to the native-provider menu so the full history stays
|
||||
# visible once Codex no longer routes through Headroom. Best-effort.
|
||||
retag_to_native(path.parent)
|
||||
|
||||
@@ -22,6 +22,11 @@ from click.testing import CliRunner
|
||||
from headroom.install.paths import _PROFILE_RE as PROFILE_RE
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _isolate_user_home(monkeypatch, tmp_path: Path) -> None:
|
||||
monkeypatch.setattr(Path, "home", lambda: tmp_path / "user-home")
|
||||
|
||||
|
||||
def _load_init_module(monkeypatch):
|
||||
monkeypatch.delitem(sys.modules, "headroom.cli.init", raising=False)
|
||||
monkeypatch.delitem(sys.modules, "headroom.cli.main", raising=False)
|
||||
@@ -573,7 +578,7 @@ def test_ensure_codex_provider_replaces_existing_marker(monkeypatch, tmp_path: P
|
||||
init_cli, _ = _load_init_module(monkeypatch)
|
||||
path = tmp_path / "config.toml"
|
||||
path.write_text(
|
||||
f"prefix\n{init_cli._CODEX_PROVIDER_MARKER_START}\nold = true\n{init_cli._CODEX_PROVIDER_MARKER_END}\n",
|
||||
f"# prefix\n{init_cli._CODEX_PROVIDER_MARKER_START}\nold = true\n{init_cli._CODEX_PROVIDER_MARKER_END}\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
@@ -660,6 +665,7 @@ def test_ensure_codex_provider_emits_requires_openai_auth_for_chatgpt(
|
||||
monkeypatch, tmp_path: Path
|
||||
) -> None:
|
||||
init_cli, _ = _load_init_module(monkeypatch)
|
||||
monkeypatch.setenv("CODEX_HOME", str(tmp_path))
|
||||
path = tmp_path / "config.toml"
|
||||
(tmp_path / "auth.json").write_text('{"auth_mode": "chatgpt"}', encoding="utf-8")
|
||||
|
||||
@@ -672,12 +678,17 @@ def test_ensure_codex_provider_omits_requires_openai_auth_for_api_key(
|
||||
monkeypatch, tmp_path: Path
|
||||
) -> None:
|
||||
init_cli, _ = _load_init_module(monkeypatch)
|
||||
monkeypatch.setenv("CODEX_HOME", str(tmp_path))
|
||||
path = tmp_path / "config.toml"
|
||||
(tmp_path / "auth.json").write_text('{"auth_mode": "apikey"}', encoding="utf-8")
|
||||
(tmp_path / "auth.json").write_text(
|
||||
'{"auth_mode": "apikey", "OPENAI_API_KEY": "sk-test-only"}', encoding="utf-8"
|
||||
)
|
||||
|
||||
init_cli._ensure_codex_provider(path, 8787)
|
||||
|
||||
assert "requires_openai_auth" not in path.read_text(encoding="utf-8")
|
||||
assert "auth = { command =" in path.read_text(encoding="utf-8")
|
||||
assert "sk-test-only" not in path.read_text(encoding="utf-8")
|
||||
|
||||
|
||||
def test_ensure_codex_feature_flag_replaces_existing_marker(monkeypatch, tmp_path: Path) -> None:
|
||||
@@ -696,6 +707,59 @@ def test_ensure_codex_feature_flag_replaces_existing_marker(monkeypatch, tmp_pat
|
||||
assert "codex_hooks" not in content
|
||||
|
||||
|
||||
@pytest.mark.parametrize("custom_home", [False, True])
|
||||
@pytest.mark.parametrize("auth_mode", ["apikey", "chatgpt"])
|
||||
def test_local_codex_provider_reads_credentials_from_user_home(
|
||||
monkeypatch, tmp_path: Path, custom_home: bool, auth_mode: str
|
||||
) -> None:
|
||||
init_cli, _ = _load_init_module(monkeypatch)
|
||||
monkeypatch.setattr(Path, "home", lambda: tmp_path / "home")
|
||||
codex_home = tmp_path / "custom" if custom_home else tmp_path / "home" / ".codex"
|
||||
if custom_home:
|
||||
monkeypatch.setenv("CODEX_HOME", str(codex_home))
|
||||
codex_home.mkdir(parents=True)
|
||||
(codex_home / "auth.json").write_text(
|
||||
json.dumps({"auth_mode": auth_mode, "OPENAI_API_KEY": "sk-test-only"}),
|
||||
encoding="utf-8",
|
||||
)
|
||||
project_config = tmp_path / "project" / ".codex" / "config.toml"
|
||||
|
||||
init_cli._ensure_codex_provider(project_config, 8787)
|
||||
|
||||
provider = tomllib.loads(project_config.read_text(encoding="utf-8"))["model_providers"][
|
||||
"headroom"
|
||||
]
|
||||
if auth_mode == "chatgpt":
|
||||
assert provider["requires_openai_auth"] is True
|
||||
assert "auth" not in provider
|
||||
else:
|
||||
assert "requires_openai_auth" not in provider
|
||||
assert Path(provider["auth"]["args"][0]).parent == codex_home.resolve()
|
||||
assert "sk-test-only" not in project_config.read_text(encoding="utf-8")
|
||||
|
||||
|
||||
def test_init_codex_helper_collision_leaves_provider_config_unchanged(
|
||||
monkeypatch, tmp_path: Path
|
||||
) -> None:
|
||||
from headroom.providers.codex.install import codex_auth_helper_path
|
||||
|
||||
init_cli, _ = _load_init_module(monkeypatch)
|
||||
monkeypatch.setenv("CODEX_HOME", str(tmp_path))
|
||||
auth = tmp_path / "auth.json"
|
||||
auth.write_text('{"OPENAI_API_KEY": "sk-test-only"}', encoding="utf-8")
|
||||
config = tmp_path / "config.toml"
|
||||
original = 'model_provider = "openai"\n'
|
||||
config.write_text(original, encoding="utf-8")
|
||||
helper = codex_auth_helper_path(auth, config_path=config)
|
||||
helper.write_text("user content", encoding="utf-8")
|
||||
|
||||
with pytest.raises(click.ClickException, match="Codex provider configuration was not updated"):
|
||||
init_cli._ensure_codex_provider(config, 8787)
|
||||
|
||||
assert config.read_text(encoding="utf-8") == original
|
||||
assert helper.read_text(encoding="utf-8") == "user content"
|
||||
|
||||
|
||||
def test_ensure_codex_feature_flag_replaces_marker_inside_features_scope(
|
||||
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
|
||||
) -> None:
|
||||
|
||||
@@ -331,6 +331,26 @@ class TestCodexProviderPortWarning:
|
||||
assert "port 9200" in capsys.readouterr().err
|
||||
assert 'base_url = "http://127.0.0.1:8787/v1"' in config.read_text(encoding="utf-8")
|
||||
|
||||
def test_init_provider_preserves_user_options_on_repoint(self, tmp_path, monkeypatch):
|
||||
import tomllib
|
||||
|
||||
monkeypatch.setattr(init_mod, "retag_to_headroom", lambda _path: None)
|
||||
config = tmp_path / "config.toml"
|
||||
config.write_text(
|
||||
"[model_providers.headroom]\n"
|
||||
'base_url = "http://127.0.0.1:9200/v1"\n'
|
||||
"request_max_retries = 7\n"
|
||||
'[profiles.work]\nmodel_provider = "custom"\n',
|
||||
encoding="utf-8",
|
||||
)
|
||||
for port in (8787, 9500):
|
||||
init_mod._ensure_codex_provider(config, port)
|
||||
parsed = tomllib.loads(config.read_text(encoding="utf-8"))
|
||||
provider = parsed["model_providers"]["headroom"]
|
||||
assert provider["base_url"] == f"http://127.0.0.1:{port}/v1"
|
||||
assert provider["request_max_retries"] == 7
|
||||
assert parsed["profiles"]["work"]["model_provider"] == "custom"
|
||||
|
||||
|
||||
class TestInitPortResolution:
|
||||
def _ctx(self, args: list[str]) -> click.Context:
|
||||
@@ -589,3 +609,49 @@ class TestSelfhealWarning:
|
||||
monkeypatch.setattr(pd, "find_live_proxy_elsewhere", lambda requested, **k: None)
|
||||
wrap_mod._warn_live_proxy_after_selfheal({"port": 8787})
|
||||
assert capsys.readouterr().err == ""
|
||||
|
||||
|
||||
def test_init_adopted_provider_survives_unwrap(tmp_path, monkeypatch):
|
||||
import tomllib
|
||||
|
||||
monkeypatch.setattr(init_mod, "retag_to_headroom", lambda _path: None)
|
||||
config = tmp_path / "config.toml"
|
||||
original = '[model_providers.headroom]\nbase_url = "http://127.0.0.1:9200/v1"\nrequest_max_retries = 7\n'
|
||||
config.write_text(original, encoding="utf-8")
|
||||
for port in (8787, 9500):
|
||||
init_mod._ensure_codex_provider(config, port)
|
||||
restored = init_mod._strip_codex_init_block(config.read_text(encoding="utf-8"))
|
||||
assert tomllib.loads(restored) == tomllib.loads(original)
|
||||
|
||||
|
||||
def test_init_replaces_auth_when_credentials_change(tmp_path, monkeypatch):
|
||||
import json
|
||||
|
||||
import tomllib
|
||||
|
||||
monkeypatch.setattr(init_mod, "retag_to_headroom", lambda _path: None)
|
||||
monkeypatch.setattr(init_mod, "codex_home_dir", lambda: tmp_path)
|
||||
auth = tmp_path / "auth.json"
|
||||
config = tmp_path / "config.toml"
|
||||
for payload, oauth in (
|
||||
(
|
||||
{
|
||||
"auth_mode": "chatgpt",
|
||||
"tokens": {"access_token": "test-oauth", "account_id": "test-account"},
|
||||
},
|
||||
True,
|
||||
),
|
||||
({"OPENAI_API_KEY": "test-key"}, False),
|
||||
(
|
||||
{
|
||||
"auth_mode": "chatgpt",
|
||||
"tokens": {"access_token": "test-oauth", "account_id": "test-account"},
|
||||
},
|
||||
True,
|
||||
),
|
||||
):
|
||||
auth.write_text(json.dumps(payload), encoding="utf-8")
|
||||
init_mod._ensure_codex_provider(config, 8787)
|
||||
provider = tomllib.loads(config.read_text(encoding="utf-8"))["model_providers"]["headroom"]
|
||||
assert provider.get("requires_openai_auth", False) is oauth
|
||||
assert ("auth" in provider) is not oauth
|
||||
|
||||
@@ -453,6 +453,47 @@ class TestInjectAndRestoreRoundTrip:
|
||||
assert not config_file.exists()
|
||||
assert not (tmp_path / ".codex" / "config.toml.headroom-backup").exists()
|
||||
|
||||
def test_wrap_unwrap_removes_generated_auth_helper(
|
||||
self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
|
||||
) -> None:
|
||||
_set_test_home(monkeypatch, tmp_path)
|
||||
config_dir = tmp_path / ".codex"
|
||||
config_dir.mkdir()
|
||||
(config_dir / "auth.json").write_text(
|
||||
'{"OPENAI_API_KEY": "sk-test-only"}', encoding="utf-8"
|
||||
)
|
||||
|
||||
wrap_mod._inject_codex_provider_config(8787)
|
||||
helper = wrap_mod.codex_auth_helper_path(config_dir / "auth.json")
|
||||
assert helper.exists()
|
||||
config = tomllib.loads((config_dir / "config.toml").read_text(encoding="utf-8"))
|
||||
assert config["model_providers"]["headroom"]["auth"]["args"] == [str(helper.resolve())]
|
||||
|
||||
status, _ = wrap_mod._restore_codex_provider_config()
|
||||
|
||||
assert status == "removed"
|
||||
assert not helper.exists()
|
||||
|
||||
def test_wrap_unwrap_preserves_preexisting_unrelated_auth_helper(
|
||||
self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
|
||||
) -> None:
|
||||
_set_test_home(monkeypatch, tmp_path)
|
||||
config_dir = tmp_path / ".codex"
|
||||
config_dir.mkdir()
|
||||
config_file = config_dir / "config.toml"
|
||||
config_file.write_text('model = "gpt-5"\n', encoding="utf-8")
|
||||
(config_dir / "auth.json").write_text(
|
||||
'{"OPENAI_API_KEY": "sk-test-only"}', encoding="utf-8"
|
||||
)
|
||||
helper = config_dir / ".headroom-codex-auth.py"
|
||||
helper.write_text("user content", encoding="utf-8")
|
||||
|
||||
wrap_mod._inject_codex_provider_config(8787)
|
||||
status, _ = wrap_mod._restore_codex_provider_config()
|
||||
|
||||
assert status == "restored"
|
||||
assert helper.read_text(encoding="utf-8") == "user content"
|
||||
|
||||
def test_wrap_unwrap_respects_codex_home(
|
||||
self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
|
||||
) -> None:
|
||||
@@ -468,8 +509,49 @@ class TestInjectAndRestoreRoundTrip:
|
||||
|
||||
status, _ = wrap_mod._restore_codex_provider_config()
|
||||
assert status == "removed"
|
||||
|
||||
assert not config_file.exists()
|
||||
|
||||
def test_wrap_helper_collision_aborts_before_backup(self, monkeypatch, tmp_path: Path) -> None:
|
||||
_set_test_home(monkeypatch, tmp_path)
|
||||
config_dir = tmp_path / ".codex"
|
||||
config_dir.mkdir()
|
||||
auth = config_dir / "auth.json"
|
||||
auth.write_text('{"OPENAI_API_KEY": "sk-test-only"}', encoding="utf-8")
|
||||
config_file = config_dir / "config.toml"
|
||||
original = 'model_provider = "openai"\n'
|
||||
config_file.write_text(original, encoding="utf-8")
|
||||
helper = wrap_mod.codex_auth_helper_path(auth, config_path=config_file)
|
||||
helper.write_text("user content", encoding="utf-8")
|
||||
|
||||
with pytest.raises(
|
||||
wrap_mod.click.ClickException, match="Codex provider configuration was not updated"
|
||||
):
|
||||
wrap_mod._inject_codex_provider_config(8787)
|
||||
|
||||
assert config_file.read_text(encoding="utf-8") == original
|
||||
assert not (config_dir / "config.toml.headroom-backup").exists()
|
||||
assert helper.read_text(encoding="utf-8") == "user content"
|
||||
|
||||
def test_unwrap_keeps_helper_used_by_restored_custom_provider(
|
||||
self, monkeypatch, tmp_path: Path
|
||||
) -> None:
|
||||
_set_test_home(monkeypatch, tmp_path)
|
||||
config_dir = tmp_path / ".codex"
|
||||
config_dir.mkdir()
|
||||
auth = config_dir / "auth.json"
|
||||
auth.write_text('{"OPENAI_API_KEY": "sk-test-only"}', encoding="utf-8")
|
||||
original = "[model_providers.custom]\n" + wrap_mod.build_codex_auth_config(auth)
|
||||
config_file = config_dir / "config.toml"
|
||||
config_file.write_text(original, encoding="utf-8")
|
||||
|
||||
wrap_mod._inject_codex_provider_config(8787)
|
||||
status, _ = wrap_mod._restore_codex_provider_config()
|
||||
|
||||
assert status == "restored"
|
||||
assert config_file.read_text(encoding="utf-8") == original
|
||||
assert wrap_mod.codex_auth_helper_path(auth).exists()
|
||||
|
||||
def test_wrap_unwrap_restores_prior_model_provider(
|
||||
self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
|
||||
) -> None:
|
||||
@@ -2436,3 +2518,46 @@ class TestCodexLaunchExportsCustomUpstream:
|
||||
) -> None:
|
||||
env = self._launch_env(monkeypatch, tmp_path, custom_upstream=None)
|
||||
assert wrap_mod._UPSTREAM_BASE_URL_ENV_VAR not in env
|
||||
|
||||
|
||||
@pytest.mark.parametrize("original", ["", 'model = "gpt-5"\n'])
|
||||
def test_unwrap_init_snapshot_removes_unreferenced_auth_helper(monkeypatch, tmp_path, original):
|
||||
from headroom.cli import init as init_cli
|
||||
from headroom.providers.codex.install import codex_auth_helper_path
|
||||
|
||||
_set_test_home(monkeypatch, tmp_path)
|
||||
config = tmp_path / ".codex/config.toml"
|
||||
config.parent.mkdir()
|
||||
config.write_text(original, encoding="utf-8")
|
||||
auth = config.with_name("auth.json")
|
||||
auth.write_text('{"OPENAI_API_KEY":"test-key"}', encoding="utf-8")
|
||||
init_cli._ensure_codex_provider(config, 8787)
|
||||
helper = codex_auth_helper_path(auth, config_path=config)
|
||||
assert helper.exists()
|
||||
backup = wrap_mod._codex_config_paths()[1]
|
||||
backup.write_text(config.read_text(encoding="utf-8"), encoding="utf-8")
|
||||
wrap_mod._restore_codex_provider_config()
|
||||
assert not helper.exists()
|
||||
assert not backup.exists()
|
||||
if original:
|
||||
assert tomllib.loads(config.read_text(encoding="utf-8")) == tomllib.loads(original)
|
||||
else:
|
||||
assert not config.exists()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("with_backup", [False, True])
|
||||
def test_unwrap_preserves_adopted_provider_options(monkeypatch, tmp_path, with_backup):
|
||||
from headroom.cli import init as init_cli
|
||||
|
||||
_set_test_home(monkeypatch, tmp_path)
|
||||
config = tmp_path / ".codex/config.toml"
|
||||
config.parent.mkdir()
|
||||
original = '[model_providers.headroom]\nbase_url = "http://127.0.0.1:9200/v1"\nrequest_max_retries = 7\n'
|
||||
config.write_text(original, encoding="utf-8")
|
||||
init_cli._ensure_codex_provider(config, 8787)
|
||||
init_cli._ensure_codex_provider(config, 9500)
|
||||
if with_backup:
|
||||
backup = wrap_mod._codex_config_paths()[1]
|
||||
backup.write_text(config.read_text(encoding="utf-8"), encoding="utf-8")
|
||||
wrap_mod._restore_codex_provider_config()
|
||||
assert tomllib.loads(config.read_text(encoding="utf-8")) == tomllib.loads(original)
|
||||
|
||||
@@ -1,14 +1,27 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
if sys.version_info >= (3, 11):
|
||||
import tomllib
|
||||
else: # pragma: no cover - exercised only on Python 3.10
|
||||
import tomli as tomllib # type: ignore[no-redef]
|
||||
|
||||
from headroom.install.models import DeploymentManifest
|
||||
from headroom.providers.codex.install import (
|
||||
CodexAuthConfigError,
|
||||
_codex_login_status,
|
||||
apply_provider_scope,
|
||||
build_codex_auth_config,
|
||||
build_provider_section,
|
||||
codex_auth_helper_path,
|
||||
codex_uses_chatgpt_auth,
|
||||
revert_provider_scope,
|
||||
)
|
||||
|
||||
|
||||
@@ -85,6 +98,94 @@ def test_file_backed_auth_preserves_existing_modes(tmp_path: Path) -> None:
|
||||
assert codex_uses_chatgpt_auth(auth) is False
|
||||
|
||||
|
||||
def test_api_key_auth_is_persisted_as_a_codex_command(tmp_path: Path, monkeypatch) -> None:
|
||||
config = tmp_path / "config.toml"
|
||||
auth = tmp_path / "auth.json"
|
||||
config.write_text('model = "gpt-5"\n', encoding="utf-8")
|
||||
auth.write_text('{"OPENAI_API_KEY": "sk-test-only"}', encoding="utf-8")
|
||||
monkeypatch.setattr("headroom.providers.codex.install.codex_config_path", lambda: config)
|
||||
|
||||
mutation = apply_provider_scope(_manifest(tmp_path))
|
||||
assert mutation is not None
|
||||
|
||||
content = config.read_text(encoding="utf-8")
|
||||
helper = codex_auth_helper_path(auth, config_path=config)
|
||||
assert "auth = { command =" in content
|
||||
assert tomllib.loads(content)["model_providers"]["headroom"]["auth"]["args"] == [
|
||||
str(helper.resolve())
|
||||
]
|
||||
assert "sk-test-only" not in content
|
||||
assert helper.exists()
|
||||
|
||||
revert_provider_scope(mutation, _manifest(tmp_path))
|
||||
|
||||
assert not helper.exists()
|
||||
|
||||
|
||||
def test_persistent_install_helper_collision_preserves_config(tmp_path: Path, monkeypatch) -> None:
|
||||
config = tmp_path / "config.toml"
|
||||
auth = tmp_path / "auth.json"
|
||||
auth.write_text('{"OPENAI_API_KEY": "sk-test-only"}', encoding="utf-8")
|
||||
original = 'model_provider = "openai"\n'
|
||||
config.write_text(original, encoding="utf-8")
|
||||
helper = codex_auth_helper_path(auth, config_path=config)
|
||||
helper.write_text("user content", encoding="utf-8")
|
||||
monkeypatch.setattr("headroom.providers.codex.install.codex_config_path", lambda: config)
|
||||
|
||||
with pytest.raises(CodexAuthConfigError, match="Codex provider configuration was not updated"):
|
||||
apply_provider_scope(_manifest(tmp_path))
|
||||
|
||||
assert config.read_text(encoding="utf-8") == original
|
||||
assert helper.read_text(encoding="utf-8") == "user content"
|
||||
|
||||
|
||||
def test_persistent_uninstall_preserves_project_authentication(tmp_path: Path, monkeypatch) -> None:
|
||||
from headroom.cli.init import _ensure_codex_provider
|
||||
|
||||
monkeypatch.setenv("CODEX_HOME", str(tmp_path))
|
||||
config = tmp_path / "config.toml"
|
||||
auth = tmp_path / "auth.json"
|
||||
auth.write_text('{"OPENAI_API_KEY": "sk-test-only"}', encoding="utf-8")
|
||||
monkeypatch.setattr("headroom.providers.codex.install.codex_config_path", lambda: config)
|
||||
project_config = tmp_path / "project" / ".codex" / "config.toml"
|
||||
_ensure_codex_provider(project_config, 8787)
|
||||
project_helper = codex_auth_helper_path(auth, config_path=project_config)
|
||||
mutation = apply_provider_scope(_manifest(tmp_path))
|
||||
assert mutation is not None
|
||||
|
||||
revert_provider_scope(mutation, _manifest(tmp_path))
|
||||
|
||||
assert project_helper.exists()
|
||||
assert tomllib.loads(project_config.read_text(encoding="utf-8"))["model_providers"]["headroom"][
|
||||
"auth"
|
||||
]["args"] == [str(project_helper.resolve())]
|
||||
assert not codex_auth_helper_path(auth, config_path=config).exists()
|
||||
|
||||
|
||||
def test_uninstall_retains_legacy_shared_helper(tmp_path: Path) -> None:
|
||||
from headroom.install.models import ManagedMutation
|
||||
|
||||
auth = tmp_path / "auth.json"
|
||||
auth.write_text('{"OPENAI_API_KEY": "sk-test-only"}', encoding="utf-8")
|
||||
build_codex_auth_config(auth)
|
||||
legacy_helper = tmp_path / ".headroom-codex-auth.py"
|
||||
legacy_helper.write_text(codex_auth_helper_path(auth).read_text(encoding="utf-8"))
|
||||
config = tmp_path / "config.toml"
|
||||
config.write_text(
|
||||
"# --- Headroom persistent provider ---\n"
|
||||
"[model_providers.headroom]\n"
|
||||
f'auth = {{ command = "python", args = [{json.dumps(str(legacy_helper), ensure_ascii=False)}] }}\n'
|
||||
"# --- end Headroom persistent provider ---\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
revert_provider_scope(
|
||||
ManagedMutation(target="codex", kind="toml-block", path=str(config)), _manifest(tmp_path)
|
||||
)
|
||||
|
||||
assert legacy_helper.exists()
|
||||
|
||||
|
||||
def test_legacy_file_backed_account_id_stays_supported(tmp_path: Path) -> None:
|
||||
auth = tmp_path / "auth.json"
|
||||
auth.write_text('{"tokens": {"account_id": "acct"}}', encoding="utf-8")
|
||||
|
||||
@@ -741,6 +741,10 @@ def test_inject_codex_provider_config_writes_openai_base_url(
|
||||
home = tmp_path
|
||||
monkeypatch.setenv("HOME", str(home))
|
||||
monkeypatch.setenv("USERPROFILE", str(home))
|
||||
(home / ".codex").mkdir()
|
||||
(home / ".codex" / "auth.json").write_text(
|
||||
'{"OPENAI_API_KEY": "sk-test-only"}', encoding="utf-8"
|
||||
)
|
||||
|
||||
wrap_mod._inject_codex_provider_config(8787)
|
||||
|
||||
@@ -763,6 +767,8 @@ def test_inject_codex_provider_config_writes_openai_base_url(
|
||||
assert "requires_openai_auth" not in content, (
|
||||
f"requires_openai_auth must be absent from the injected provider block; got:\n{content}"
|
||||
)
|
||||
assert "auth = { command =" in content
|
||||
assert "sk-test-only" not in content
|
||||
# openai_base_url must be in the top-level block, NOT inside [model_providers.*]
|
||||
lines = content.splitlines()
|
||||
in_provider_section = False
|
||||
|
||||
@@ -1,8 +1,27 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from headroom.providers.codex.install import build_provider_section, codex_uses_chatgpt_auth
|
||||
import pytest
|
||||
|
||||
if sys.version_info >= (3, 11):
|
||||
import tomllib
|
||||
else: # pragma: no cover - exercised only on Python 3.10
|
||||
import tomli as tomllib # type: ignore[no-redef]
|
||||
|
||||
from headroom.providers.codex.install import (
|
||||
CodexAuthConfigError,
|
||||
build_codex_auth_config,
|
||||
build_provider_section,
|
||||
cleanup_codex_auth_helper,
|
||||
codex_auth_helper_is_referenced,
|
||||
codex_auth_helper_path,
|
||||
codex_uses_api_key_auth,
|
||||
codex_uses_chatgpt_auth,
|
||||
)
|
||||
|
||||
|
||||
def test_codex_provider_section_omits_requires_openai_auth_by_default() -> None:
|
||||
@@ -52,6 +71,169 @@ def test_codex_uses_chatgpt_auth_false_for_api_key(tmp_path: Path) -> None:
|
||||
assert codex_uses_chatgpt_auth(auth) is False
|
||||
|
||||
|
||||
def test_codex_uses_api_key_auth_detects_file_backed_key(tmp_path: Path) -> None:
|
||||
auth = tmp_path / "auth.json"
|
||||
auth.write_text('{"OPENAI_API_KEY": "sk-x"}', encoding="utf-8")
|
||||
|
||||
assert codex_uses_api_key_auth(auth) is True
|
||||
|
||||
|
||||
def test_codex_uses_api_key_auth_rejects_missing_or_blank_key(tmp_path: Path) -> None:
|
||||
auth = tmp_path / "auth.json"
|
||||
for document in ("{}", '{"OPENAI_API_KEY": " "}', "not json"):
|
||||
auth.write_text(document, encoding="utf-8")
|
||||
assert codex_uses_api_key_auth(auth) is False
|
||||
|
||||
|
||||
def test_build_codex_auth_config_generates_helper_without_copying_key(tmp_path: Path) -> None:
|
||||
auth = tmp_path / "auth.json"
|
||||
auth.write_text('{"OPENAI_API_KEY": "sk-test-only"}', encoding="utf-8")
|
||||
|
||||
config = build_codex_auth_config(auth)
|
||||
helper = codex_auth_helper_path(auth)
|
||||
|
||||
assert "auth = { command =" in config
|
||||
assert tomllib.loads(config)["auth"]["args"] == [str(helper.resolve())]
|
||||
assert "sk-test-only" not in config
|
||||
assert helper.read_text(encoding="utf-8").count("OPENAI_API_KEY") == 1
|
||||
if sys.platform != "win32":
|
||||
assert helper.stat().st_mode & 0o777 == 0o600
|
||||
result = subprocess.run(
|
||||
[sys.executable, str(helper)], capture_output=True, text=True, check=True
|
||||
)
|
||||
assert result.stdout == "sk-test-only"
|
||||
|
||||
|
||||
def test_codex_auth_helper_reference_parses_toml_escaped_windows_path() -> None:
|
||||
helper = r"C:\Users\example\.codex\.headroom-codex-auth.py"
|
||||
config = (
|
||||
"[model_providers.headroom]\n"
|
||||
f'auth = {{ command = "python", args = [{json.dumps(helper)}] }}\n'
|
||||
)
|
||||
|
||||
assert codex_auth_helper_is_referenced(config, helper) is True
|
||||
|
||||
|
||||
def test_build_codex_auth_config_does_not_overwrite_existing_helper(
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
auth = tmp_path / "auth.json"
|
||||
auth.write_text('{"OPENAI_API_KEY": "sk-test-only"}', encoding="utf-8")
|
||||
helper = codex_auth_helper_path(auth)
|
||||
helper.write_text("user content", encoding="utf-8")
|
||||
|
||||
with pytest.raises(CodexAuthConfigError, match="conflicting file or symlink"):
|
||||
build_codex_auth_config(auth)
|
||||
assert helper.read_text(encoding="utf-8") == "user content"
|
||||
|
||||
|
||||
def test_build_codex_auth_config_rejects_helper_symlink(tmp_path: Path) -> None:
|
||||
auth = tmp_path / "auth.json"
|
||||
auth.write_text('{"OPENAI_API_KEY": "sk-test-only"}', encoding="utf-8")
|
||||
target = tmp_path / "user-file.txt"
|
||||
target.write_text("user content", encoding="utf-8")
|
||||
helper = codex_auth_helper_path(auth)
|
||||
try:
|
||||
helper.symlink_to(target)
|
||||
except OSError:
|
||||
pytest.skip("symlinks are unavailable")
|
||||
|
||||
with pytest.raises(CodexAuthConfigError, match="conflicting file or symlink"):
|
||||
build_codex_auth_config(auth)
|
||||
assert target.read_text(encoding="utf-8") == "user content"
|
||||
assert helper.is_symlink()
|
||||
|
||||
|
||||
def test_build_codex_auth_config_handles_invalid_existing_helper(tmp_path: Path) -> None:
|
||||
auth = tmp_path / "auth.json"
|
||||
auth.write_text('{"OPENAI_API_KEY": "sk-test-only"}', encoding="utf-8")
|
||||
helper = codex_auth_helper_path(auth)
|
||||
helper.write_bytes(b"\xff\xfe")
|
||||
|
||||
with pytest.raises(CodexAuthConfigError, match="conflicting file or symlink"):
|
||||
build_codex_auth_config(auth)
|
||||
assert helper.read_bytes() == b"\xff\xfe"
|
||||
|
||||
|
||||
def test_cleanup_codex_auth_helper_only_removes_headroom_file(tmp_path: Path) -> None:
|
||||
auth = tmp_path / "auth.json"
|
||||
auth.write_text('{"OPENAI_API_KEY": "sk-test-only"}', encoding="utf-8")
|
||||
build_codex_auth_config(auth)
|
||||
helper = codex_auth_helper_path(auth)
|
||||
|
||||
cleanup_codex_auth_helper(auth)
|
||||
|
||||
assert not helper.exists()
|
||||
|
||||
|
||||
def test_build_codex_auth_config_skips_chatgpt_auth(tmp_path: Path) -> None:
|
||||
auth = tmp_path / "auth.json"
|
||||
auth.write_text('{"auth_mode": "chatgpt"}', encoding="utf-8")
|
||||
|
||||
assert build_codex_auth_config(auth) == ""
|
||||
|
||||
|
||||
def test_auth_command_round_trips_astral_paths(tmp_path: Path, monkeypatch) -> None:
|
||||
home = tmp_path / "😀"
|
||||
home.mkdir()
|
||||
auth = home / "auth.json"
|
||||
auth.write_text('{"OPENAI_API_KEY": "sk-test-only"}', encoding="utf-8")
|
||||
executable = str(home / "python-🐍")
|
||||
monkeypatch.setattr(sys, "executable", executable)
|
||||
|
||||
command = tomllib.loads(build_codex_auth_config(auth))["auth"]
|
||||
|
||||
assert command["command"] == executable
|
||||
assert Path(command["args"][0]).parent == home.resolve()
|
||||
|
||||
|
||||
def test_auth_helpers_are_scoped_to_the_provider_config(tmp_path: Path) -> None:
|
||||
auth = tmp_path / "auth.json"
|
||||
auth.write_text('{"OPENAI_API_KEY": "sk-test-only"}', encoding="utf-8")
|
||||
first = tmp_path / "config.toml"
|
||||
second = tmp_path / "project" / ".codex" / "config.toml"
|
||||
first_command = tomllib.loads(build_codex_auth_config(auth, config_path=first))["auth"]
|
||||
second_command = tomllib.loads(build_codex_auth_config(auth, config_path=second))["auth"]
|
||||
first_helper = Path(first_command["args"][0])
|
||||
second_helper = Path(second_command["args"][0])
|
||||
|
||||
assert first_helper != second_helper
|
||||
cleanup_codex_auth_helper(auth, config_path=first)
|
||||
|
||||
assert not first_helper.exists()
|
||||
result = subprocess.run(
|
||||
[sys.executable, str(second_helper)], capture_output=True, text=True, check=True
|
||||
)
|
||||
assert result.stdout == "sk-test-only"
|
||||
|
||||
|
||||
def test_auth_helper_creation_failure_is_explicit(tmp_path: Path, monkeypatch) -> None:
|
||||
auth = tmp_path / "auth.json"
|
||||
auth.write_text('{"OPENAI_API_KEY": "sk-test-only"}', encoding="utf-8")
|
||||
|
||||
def denied(*args, **kwargs):
|
||||
raise PermissionError("read-only directory")
|
||||
|
||||
monkeypatch.setattr("headroom.providers.codex.install.os.open", denied)
|
||||
with pytest.raises(CodexAuthConfigError, match="Check directory permissions"):
|
||||
build_codex_auth_config(auth)
|
||||
assert not codex_auth_helper_path(auth).exists()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("content", ["invalid TOML", "[model_providers.other]\n{auth}"])
|
||||
def test_cleanup_preserves_helper_for_retained_or_unparseable_config(
|
||||
tmp_path: Path, content: str
|
||||
) -> None:
|
||||
auth = tmp_path / "auth.json"
|
||||
auth.write_text('{"OPENAI_API_KEY": "sk-test-only"}', encoding="utf-8")
|
||||
fragment = build_codex_auth_config(auth)
|
||||
(tmp_path / "config.toml").write_text(content.replace("{auth}", fragment), encoding="utf-8")
|
||||
|
||||
cleanup_codex_auth_helper(auth)
|
||||
|
||||
assert codex_auth_helper_path(auth).exists()
|
||||
|
||||
|
||||
def test_codex_uses_chatgpt_auth_false_for_missing_or_malformed(tmp_path: Path) -> None:
|
||||
assert codex_uses_chatgpt_auth(tmp_path / "absent.json") is False
|
||||
bad = tmp_path / "auth.json"
|
||||
|
||||
Reference in New Issue
Block a user