mirror of
https://github.com/agent0ai/agent-zero.git
synced 2026-12-04 03:58:09 +00:00
Replace loopback trust with an internal process credential supplied automatically to local account-model calls. Keep configured external proxy tokens and deny tokenless requests from every source address. Finalize local proxy credentials after model defaults are merged so legacy stored keys, inline keys, additional parameters and auth headers work without changing saved settings or account connections. Limit replacement to this process's loopback WebUI port and provider proxy path, preserving explicit credentials for other endpoints. Keep the internal credential in the stable framework runtime module so plugin reloads do not invalidate existing model clients. No saved credential or configuration migration is required. Isolate proxy tests from saved accounts and plugin toggles. Cover all account providers, disconnected state, custom ports, external endpoint credentials, public hostnames, forwarded headers, OAuth callback accessibility and real SDK HTTP streaming. Document the intentional requirement for external clients that previously relied on tokenless loopback trust. Validation: 643 focused framework tests passed with 3 expected failures for two pre-existing backup/A2A issues, plus 52 isolated host checks and the OAuth UI regression. A live Codex Responses call using the existing account after plugin reload returned OK; saved credentials and configuration remained byte-for-byte unchanged.
1403 lines
50 KiB
Python
1403 lines
50 KiB
Python
from __future__ import annotations
|
|
|
|
import json
|
|
import multiprocessing
|
|
import queue
|
|
import stat
|
|
import sys
|
|
import threading
|
|
import time
|
|
from pathlib import Path
|
|
from types import SimpleNamespace
|
|
|
|
import pytest
|
|
import yaml
|
|
|
|
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
|
from plugins._oauth.helpers import codex
|
|
from plugins._oauth.helpers import routes
|
|
from plugins._oauth.helpers.providers import codex as codex_provider
|
|
from plugins._oauth.helpers.providers.base import DUMMY_API_KEY
|
|
from plugins._oauth.extensions.python._functions.models.get_api_key.end import (
|
|
_20_oauth_account_dummy_key as oauth_dummy_key,
|
|
)
|
|
from plugins._oauth.extensions.python.chat_model_call_before._20_codex_session import (
|
|
CodexSession,
|
|
)
|
|
|
|
|
|
@pytest.fixture(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()
|
|
|
|
assert 43 <= len(pair.verifier) <= 128
|
|
assert pair.verifier
|
|
assert pair.challenge
|
|
assert "=" not in pair.verifier
|
|
assert "=" not in pair.challenge
|
|
|
|
|
|
def test_build_authorize_url_uses_existing_a0_origin_callback(monkeypatch):
|
|
monkeypatch.setattr(
|
|
codex,
|
|
"codex_config",
|
|
lambda: {
|
|
"issuer": "https://auth.openai.com",
|
|
"client_id": "app_EMoamEEZ73f0CkXaXp7hrann",
|
|
"scopes": [
|
|
"openid",
|
|
"profile",
|
|
"email",
|
|
"offline_access",
|
|
"api.connectors.read",
|
|
"api.connectors.invoke",
|
|
],
|
|
"forced_workspace_id": "",
|
|
},
|
|
)
|
|
pair = codex.PkcePair(verifier="verifier", challenge="challenge")
|
|
auth_url = codex.build_authorize_url(
|
|
"http://localhost:50001/auth/callback",
|
|
"state",
|
|
pair,
|
|
)
|
|
|
|
assert auth_url.startswith("https://auth.openai.com/oauth/authorize?")
|
|
assert "redirect_uri=http%3A%2F%2Flocalhost%3A50001%2Fauth%2Fcallback" in auth_url
|
|
assert "code_challenge=challenge" in auth_url
|
|
assert "originator=codex_cli_rs" in auth_url
|
|
|
|
|
|
def test_chat_messages_to_response_body_extracts_instructions():
|
|
metadata = {"session_id": "chat-session", "thread_id": "chat-thread"}
|
|
body = codex.chat_messages_to_response_body(
|
|
{
|
|
"model": "gpt-5.2",
|
|
"messages": [
|
|
{"role": "system", "content": "Be precise."},
|
|
{"role": "user", "content": "Hello"},
|
|
],
|
|
"temperature": 0.2,
|
|
"reasoning_effort": "high",
|
|
"client_metadata": metadata,
|
|
"prompt_cache_key": "caller-cache",
|
|
}
|
|
)
|
|
|
|
assert body["model"] == "gpt-5.2"
|
|
assert body["instructions"] == "Be precise."
|
|
assert body["input"] == [{"role": "user", "content": "Hello"}]
|
|
assert body["temperature"] == 0.2
|
|
assert body["reasoning"] == {"effort": "high"}
|
|
assert body["client_metadata"] == metadata
|
|
assert body["prompt_cache_key"] == "caller-cache"
|
|
|
|
|
|
def test_chat_messages_to_response_body_uses_current_codex_default_model():
|
|
body = codex.chat_messages_to_response_body(
|
|
{
|
|
"messages": [
|
|
{"role": "user", "content": "Hello"},
|
|
],
|
|
}
|
|
)
|
|
|
|
assert body["model"] == "gpt-5.5"
|
|
|
|
|
|
def test_codex_provider_metadata_recommends_main_and_utility_without_restricting_catalog(monkeypatch):
|
|
monkeypatch.setattr(
|
|
codex_provider,
|
|
"_codex_config",
|
|
lambda: {
|
|
"models": [],
|
|
"proxy_base_path": "/oauth/codex",
|
|
"callback_path": "/auth/callback",
|
|
},
|
|
)
|
|
|
|
metadata = codex_provider.CodexOAuthProvider().metadata()
|
|
|
|
assert metadata.default_model == "gpt-6.1-terra"
|
|
assert metadata.default_models == ["gpt-6.1-terra", "gpt-6-luna"]
|
|
|
|
monkeypatch.setattr(codex, "fetch_models", lambda: ["another-account-model"])
|
|
assert codex_provider.CodexOAuthProvider().models() == ["another-account-model"]
|
|
|
|
|
|
def test_codex_provider_metadata_preserves_configured_model_order(monkeypatch):
|
|
monkeypatch.setattr(
|
|
codex_provider,
|
|
"_codex_config",
|
|
lambda: {
|
|
"models": ["custom-main", "custom-utility"],
|
|
"proxy_base_path": "/oauth/codex",
|
|
"callback_path": "/auth/callback",
|
|
},
|
|
)
|
|
|
|
metadata = codex_provider.CodexOAuthProvider().metadata()
|
|
|
|
assert metadata.default_model == "custom-main"
|
|
assert metadata.default_models == ["custom-main", "custom-utility"]
|
|
|
|
|
|
def test_codex_fetch_models_omits_fake_client_version(monkeypatch):
|
|
calls = []
|
|
|
|
class FakeResponse:
|
|
ok = True
|
|
|
|
def json(self):
|
|
return {"models": [{"slug": "upstream-model"}]}
|
|
|
|
monkeypatch.setattr(codex, "codex_config", lambda: {"models": []})
|
|
monkeypatch.setattr(codex, "resolve_codex_version", lambda: "")
|
|
monkeypatch.setattr(codex, "request_codex", lambda path, params=None: calls.append((path, params)) or FakeResponse())
|
|
|
|
assert codex.fetch_models() == ["upstream-model"]
|
|
assert calls == [("/models", None)]
|
|
|
|
|
|
def test_codex_fetch_model_catalog_preserves_model_metadata(monkeypatch):
|
|
class FakeResponse:
|
|
ok = True
|
|
|
|
def json(self):
|
|
return {
|
|
"models": [
|
|
{
|
|
"slug": "gpt-5.5",
|
|
"display_name": "GPT-5.5",
|
|
"description": "Frontier coding model.",
|
|
"default_reasoning_level": "medium",
|
|
"base_instructions": "too large for the settings UI",
|
|
}
|
|
]
|
|
}
|
|
|
|
monkeypatch.setattr(codex, "codex_config", lambda: {"models": []})
|
|
monkeypatch.setattr(codex, "resolve_codex_version", lambda: "0.142.5")
|
|
monkeypatch.setattr(codex, "request_codex", lambda path, params=None: FakeResponse())
|
|
|
|
assert codex.fetch_model_catalog() == [
|
|
{
|
|
"slug": "gpt-5.5",
|
|
"id": "gpt-5.5",
|
|
"display_name": "GPT-5.5",
|
|
"description": "Frontier coding model.",
|
|
"default_reasoning_level": "medium",
|
|
}
|
|
]
|
|
|
|
|
|
def test_prepare_responses_body_adds_codex_client_metadata(monkeypatch):
|
|
monkeypatch.setattr(codex, "codex_config", lambda: {})
|
|
monkeypatch.setattr(
|
|
codex,
|
|
"build_client_metadata",
|
|
lambda: {
|
|
"x-codex-installation-id": "install-1",
|
|
"session_id": "session-1",
|
|
"thread_id": "thread-1",
|
|
"x-codex-window-id": "agent-zero",
|
|
},
|
|
)
|
|
|
|
body = codex.prepare_responses_body(
|
|
{
|
|
"model": "gpt-5.5",
|
|
"input": "hello",
|
|
"client_metadata": {
|
|
"caller": "plugin-test",
|
|
"x-codex-installation-id": "stale",
|
|
},
|
|
"reasoning": {"effort": "medium"},
|
|
"include": ["output_text"],
|
|
},
|
|
force_stream=True,
|
|
)
|
|
|
|
assert body["client_metadata"] == {
|
|
"caller": "plugin-test",
|
|
"x-codex-installation-id": "install-1",
|
|
"session_id": "session-1",
|
|
"thread_id": "thread-1",
|
|
"x-codex-window-id": "agent-zero",
|
|
}
|
|
assert body["input"] == [{"role": "user", "content": "hello"}]
|
|
assert body["stream"] is True
|
|
assert body["reasoning"] == {"effort": "medium", "summary": "auto"}
|
|
assert body["include"] == ["output_text", "reasoning.encrypted_content"]
|
|
|
|
|
|
def test_codex_session_metadata_is_stable_and_scoped(monkeypatch):
|
|
monkeypatch.setattr(codex, "codex_config", lambda: {})
|
|
monkeypatch.setattr(codex, "resolve_installation_id", lambda: "install-1")
|
|
|
|
def prepare(context_id="chat-1", number=0, provider="codex_oauth", metadata=None):
|
|
extra_body = {"client_metadata": dict(metadata or {}), "other": "keep"}
|
|
model = SimpleNamespace(
|
|
a0_model_conf=SimpleNamespace(provider=provider),
|
|
kwargs={"extra_body": extra_body},
|
|
)
|
|
agent = SimpleNamespace(context=SimpleNamespace(id=context_id), number=number)
|
|
CodexSession(agent=agent).execute(call_data={"model": model})
|
|
assert extra_body == {"client_metadata": dict(metadata or {}), "other": "keep"}
|
|
assert model.kwargs["extra_body"]["other"] == "keep"
|
|
if provider != "codex_oauth":
|
|
assert model.kwargs["extra_body"] is extra_body
|
|
return None
|
|
return codex.prepare_responses_body(
|
|
{"input": [], **model.kwargs["extra_body"]}, force_stream=True
|
|
)["client_metadata"]
|
|
|
|
first = prepare()
|
|
assert first == prepare()
|
|
assert first["session_id"] == first["thread_id"] == "agent-zero-chat-1-0"
|
|
assert first["session_id"] != prepare(context_id="chat-2")["session_id"]
|
|
assert first["session_id"] != prepare(number=1)["session_id"]
|
|
explicit = prepare(metadata={
|
|
"session_id": "caller-session", "thread_id": "caller-thread",
|
|
"caller": "keep", "x-codex-installation-id": "stale",
|
|
})
|
|
assert explicit["session_id"] == "caller-session"
|
|
assert explicit["thread_id"] == "caller-thread"
|
|
assert explicit["caller"] == "keep"
|
|
assert explicit["x-codex-installation-id"] == "install-1"
|
|
assert prepare(provider="openai") is None
|
|
|
|
|
|
@pytest.mark.parametrize("session_id", ["chat-session", "x" * 100])
|
|
def test_codex_cache_key_uses_caller_session_without_mutating_input(monkeypatch, session_id):
|
|
monkeypatch.setattr(codex, "codex_config", lambda: {})
|
|
monkeypatch.setattr(codex, "build_client_metadata", lambda: {"session_id": "random-fallback"})
|
|
source = {"input": [], "client_metadata": {"session_id": session_id}}
|
|
first = codex.prepare_responses_body(source, force_stream=True)
|
|
second = codex.prepare_responses_body(source, force_stream=True)
|
|
|
|
assert first["prompt_cache_key"] == second["prompt_cache_key"]
|
|
assert first["prompt_cache_key"] == (
|
|
session_id if len(session_id) <= 64 else codex.hashlib.sha256(session_id.encode()).hexdigest()
|
|
)
|
|
assert len(first["prompt_cache_key"]) <= 64
|
|
assert "prompt_cache_key" not in source
|
|
assert codex.prepare_responses_body(
|
|
{**source, "prompt_cache_key": "caller-cache"}, force_stream=True
|
|
)["prompt_cache_key"] == "caller-cache"
|
|
assert "prompt_cache_key" not in codex.prepare_responses_body(
|
|
{"input": []}, force_stream=True
|
|
)
|
|
|
|
|
|
def test_prepare_responses_body_tightens_existing_response_tool_only(monkeypatch):
|
|
monkeypatch.setattr(codex, "codex_config", lambda: {})
|
|
monkeypatch.setattr(codex, "build_client_metadata", lambda: {})
|
|
response_tool = {
|
|
"type": "function",
|
|
"name": "response",
|
|
"description": "final answer",
|
|
"parameters": {"type": "object", "additionalProperties": True},
|
|
}
|
|
other_tool = {
|
|
"type": "function",
|
|
"name": "search",
|
|
"parameters": {"type": "object", "additionalProperties": True},
|
|
}
|
|
|
|
body = codex.prepare_responses_body(
|
|
{"input": [], "tools": [response_tool, other_tool]},
|
|
force_stream=True,
|
|
)
|
|
|
|
assert body["tools"] == [
|
|
{
|
|
**response_tool,
|
|
"strict": True,
|
|
"parameters": {
|
|
"type": "object",
|
|
"properties": {"text": {"type": "string"}},
|
|
"required": ["text"],
|
|
"additionalProperties": False,
|
|
},
|
|
},
|
|
other_tool,
|
|
]
|
|
assert codex.prepare_responses_body(
|
|
{"input": [], "tools": [other_tool]},
|
|
force_stream=True,
|
|
)["tools"] == [other_tool]
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
("request_reasoning", "expected"),
|
|
[
|
|
({"reasoning_effort": "xhigh"}, {"effort": "xhigh", "summary": "auto"}),
|
|
(
|
|
{"reasoning": {"effort": "medium"}, "reasoning_effort": "xhigh"},
|
|
{"effort": "medium", "summary": "auto"},
|
|
),
|
|
(
|
|
{"reasoning": {"effort": "medium", "summary": "detailed"}},
|
|
{"effort": "medium", "summary": "detailed"},
|
|
),
|
|
],
|
|
)
|
|
def test_prepare_responses_body_normalizes_reasoning_effort(
|
|
monkeypatch, request_reasoning, expected
|
|
):
|
|
monkeypatch.setattr(codex, "codex_config", lambda: {})
|
|
monkeypatch.setattr(codex, "build_client_metadata", lambda: {})
|
|
|
|
body = codex.prepare_responses_body(
|
|
{"model": "gpt-5.5", "input": "hello", **request_reasoning},
|
|
force_stream=True,
|
|
)
|
|
|
|
assert body["reasoning"] == expected
|
|
assert "reasoning_effort" not in body
|
|
|
|
|
|
def test_prepare_responses_body_applies_codex_response_defaults(monkeypatch):
|
|
monkeypatch.setattr(codex, "build_client_metadata", lambda: {})
|
|
monkeypatch.setattr(
|
|
codex,
|
|
"codex_config",
|
|
lambda: {
|
|
"reasoning_effort": "high",
|
|
"reasoning_summary": "concise",
|
|
"text_verbosity": "low",
|
|
},
|
|
)
|
|
|
|
defaults = codex.prepare_responses_body(
|
|
{"model": "gpt-5.5", "input": "hello"}, force_stream=True
|
|
)
|
|
overrides = codex.prepare_responses_body(
|
|
{
|
|
"model": "gpt-5.5",
|
|
"input": "hello",
|
|
"reasoning": {"effort": "low", "summary": "detailed"},
|
|
"text": {"verbosity": "high"},
|
|
},
|
|
force_stream=True,
|
|
)
|
|
|
|
assert defaults["reasoning"] == {"effort": "high", "summary": "concise"}
|
|
assert defaults["text"] == {"verbosity": "low"}
|
|
assert overrides["reasoning"] == {"effort": "low", "summary": "detailed"}
|
|
assert overrides["text"] == {"verbosity": "high"}
|
|
|
|
|
|
def test_codex_config_validates_response_defaults():
|
|
from plugins._oauth.helpers.config import codex_config
|
|
|
|
config = codex_config(
|
|
{
|
|
"codex": {
|
|
"reasoning_effort": "invalid",
|
|
"reasoning_summary": "DETAILED",
|
|
"text_verbosity": "low",
|
|
}
|
|
}
|
|
)
|
|
|
|
assert config["reasoning_effort"] == "high"
|
|
assert config["reasoning_summary"] == "detailed"
|
|
assert config["text_verbosity"] == "low"
|
|
|
|
|
|
def test_prepare_responses_body_sends_empty_continuation_input_as_list(monkeypatch):
|
|
monkeypatch.setattr(codex, "codex_config", lambda: {})
|
|
monkeypatch.setattr(codex, "build_client_metadata", lambda: {})
|
|
|
|
body = codex.prepare_responses_body(
|
|
{
|
|
"model": "gpt-5.5",
|
|
"input": "",
|
|
"previous_response_id": "resp_1",
|
|
},
|
|
force_stream=True,
|
|
)
|
|
|
|
assert body["input"] == []
|
|
assert body["previous_response_id"] == "resp_1"
|
|
|
|
|
|
@pytest.mark.parametrize("client_version", ["0.142.5", ""])
|
|
def test_request_codex_sends_current_codex_headers_from_body(
|
|
monkeypatch, client_version
|
|
):
|
|
calls = []
|
|
body = json.dumps(
|
|
{
|
|
"client_metadata": {
|
|
"x-codex-installation-id": "install-1",
|
|
"session_id": "session-1",
|
|
"thread_id": "thread-1",
|
|
"x-codex-window-id": "agent-zero",
|
|
}
|
|
}
|
|
)
|
|
|
|
class FakeResponse:
|
|
ok = True
|
|
|
|
monkeypatch.setattr(
|
|
codex,
|
|
"codex_config",
|
|
lambda: {
|
|
"upstream_base_url": "https://chatgpt.example/backend-api/codex",
|
|
"request_timeout_seconds": 120,
|
|
},
|
|
)
|
|
monkeypatch.setattr(
|
|
codex,
|
|
"load_auth",
|
|
lambda: codex.EffectiveAuth(
|
|
access_token="access-token",
|
|
account_id="account-1",
|
|
),
|
|
)
|
|
monkeypatch.setattr(codex, "resolve_codex_version", lambda: client_version)
|
|
|
|
def fake_request(method, target, headers, data, params, timeout, stream):
|
|
calls.append(
|
|
{
|
|
"method": method,
|
|
"target": target,
|
|
"headers": headers,
|
|
"data": data,
|
|
"params": params,
|
|
"timeout": timeout,
|
|
"stream": stream,
|
|
}
|
|
)
|
|
return FakeResponse()
|
|
|
|
monkeypatch.setattr(codex._UPSTREAM_SESSION, "request", fake_request)
|
|
|
|
response = codex.request_codex(
|
|
"/responses",
|
|
method="POST",
|
|
headers={"Content-Type": "application/json"},
|
|
body=body,
|
|
stream=True,
|
|
)
|
|
|
|
assert response.ok is True
|
|
call = calls[0]
|
|
assert call["target"] == "https://chatgpt.example/backend-api/codex/responses"
|
|
assert call["headers"]["Authorization"] == "Bearer access-token"
|
|
assert call["headers"]["chatgpt-account-id"] == "account-1"
|
|
assert call["headers"]["OpenAI-Beta"] == "responses=experimental"
|
|
assert call["headers"]["originator"] == "codex_cli_rs"
|
|
assert call["headers"]["x-codex-installation-id"] == "install-1"
|
|
assert call["headers"]["session-id"] == "session-1"
|
|
assert call["headers"]["thread-id"] == "thread-1"
|
|
assert call["headers"]["x-codex-window-id"] == "agent-zero"
|
|
if client_version:
|
|
assert call["headers"]["version"] == "0.142.5"
|
|
else:
|
|
assert "version" not in call["headers"]
|
|
|
|
|
|
def test_chat_messages_to_response_body_preserves_image_parts_for_responses():
|
|
data_url = "data:image/png;base64,abcd"
|
|
|
|
body = codex.chat_messages_to_response_body(
|
|
{
|
|
"model": "gpt-5.5",
|
|
"messages": [
|
|
{
|
|
"role": "user",
|
|
"content": [
|
|
{"type": "text", "text": "Inspect this screenshot."},
|
|
{"type": "text", "text": "Fresh screen attached."},
|
|
{"type": "image_url", "image_url": {"url": data_url}},
|
|
],
|
|
}
|
|
],
|
|
}
|
|
)
|
|
|
|
assert body["input"] == [
|
|
{
|
|
"role": "user",
|
|
"content": [
|
|
{"type": "input_text", "text": "Inspect this screenshot."},
|
|
{"type": "input_text", "text": "Fresh screen attached."},
|
|
{"type": "input_image", "image_url": data_url, "detail": "auto"},
|
|
],
|
|
}
|
|
]
|
|
|
|
|
|
def test_chat_messages_to_response_body_keeps_text_only_lists_as_text():
|
|
body = codex.chat_messages_to_response_body(
|
|
{
|
|
"model": "gpt-5.5",
|
|
"messages": [
|
|
{
|
|
"role": "user",
|
|
"content": [
|
|
{"type": "text", "text": "first"},
|
|
{"type": "text", "text": "second"},
|
|
],
|
|
}
|
|
],
|
|
}
|
|
)
|
|
|
|
assert body["input"] == [{"role": "user", "content": "first\nsecond"}]
|
|
|
|
|
|
def test_response_text_reads_output_text_or_output_blocks():
|
|
assert codex.response_text({"output_text": "direct"}) == "direct"
|
|
|
|
assert (
|
|
codex.response_text(
|
|
{
|
|
"output": [
|
|
{
|
|
"content": [
|
|
{"type": "output_text", "text": "a"},
|
|
{"type": "output_text", "text": "b"},
|
|
]
|
|
}
|
|
]
|
|
}
|
|
)
|
|
== "ab"
|
|
)
|
|
|
|
|
|
def test_parse_sse_block_joins_data_lines():
|
|
event = codex.parse_sse_block(
|
|
'event: response.completed\ndata: {"response":\ndata: {"id":"r"}}\n'
|
|
)
|
|
|
|
assert event["event"] == "response.completed"
|
|
assert json.loads(event["data"]) == {"response": {"id": "r"}}
|
|
|
|
|
|
def test_extract_sse_text_deltas_reads_chat_completion_chunks():
|
|
deltas = codex.extract_sse_text_deltas(
|
|
{
|
|
"id": "chatcmpl_test",
|
|
"choices": [
|
|
{"delta": {"role": "assistant"}},
|
|
{"delta": {"content": "Hel"}},
|
|
{"delta": {"content": "lo"}},
|
|
],
|
|
}
|
|
)
|
|
|
|
assert deltas == ["Hel", "lo"]
|
|
|
|
|
|
def test_extract_sse_text_deltas_ignores_final_done_text():
|
|
assert (
|
|
codex.extract_sse_text_deltas(
|
|
{"type": "response.output_text.done", "text": "Hello"},
|
|
"response.output_text.done",
|
|
)
|
|
== []
|
|
)
|
|
|
|
|
|
def test_collect_completed_response_restores_native_output_items():
|
|
item = {
|
|
"id": "msg_1",
|
|
"type": "message",
|
|
"status": "completed",
|
|
"content": [
|
|
{
|
|
"type": "output_text",
|
|
"annotations": [],
|
|
"logprobs": [],
|
|
"text": "Hello",
|
|
}
|
|
],
|
|
"role": "assistant",
|
|
}
|
|
|
|
class FakeResponse:
|
|
encoding = "utf-8"
|
|
|
|
def iter_content(self, chunk_size=8192, decode_unicode=True):
|
|
del chunk_size, decode_unicode
|
|
yield (
|
|
'data: {"type":"response.output_item.done","output_index":0,'
|
|
f'"item":{json.dumps(item)}}}\n\n'
|
|
).encode()
|
|
yield (
|
|
b'data: {"type":"response.completed",'
|
|
b'"response":{"id":"resp_1","output":[]}}\n\n'
|
|
)
|
|
|
|
assert codex.collect_completed_response(FakeResponse()) == {
|
|
"id": "resp_1",
|
|
"output": [item],
|
|
}
|
|
|
|
|
|
def test_collect_completed_response_falls_back_to_text_deltas():
|
|
class FakeResponse:
|
|
encoding = "utf-8"
|
|
|
|
def iter_content(self, chunk_size=8192, decode_unicode=True):
|
|
del chunk_size, decode_unicode
|
|
yield b'data: {"choices":[{"delta":{"content":"Hel"}}]}\n\n'
|
|
yield b'data: {"choices":[{"delta":{"content":"lo"}}]}\n\n'
|
|
yield b'event: response.completed\ndata: {"response":{"output":[]}}\n\n'
|
|
yield b"data: [DONE]\n\n"
|
|
|
|
assert codex.collect_completed_response(FakeResponse()) == {"output": [], "output_text": "Hello"}
|
|
|
|
|
|
def test_normalize_usage_payload_reads_codex_windows():
|
|
usage = codex.normalize_usage_payload(
|
|
{
|
|
"plan_type": "plus",
|
|
"rate_limit": {
|
|
"primary_window": {
|
|
"used_percent": 39,
|
|
"reset_at": 1_738_300_000,
|
|
"limit_window_seconds": 18_000,
|
|
},
|
|
"secondary_window": {
|
|
"used_percent": 15,
|
|
"reset_at": 1_738_900_000,
|
|
"limit_window_seconds": 604_800,
|
|
},
|
|
},
|
|
"credits": {"has_credits": True, "unlimited": False, "balance": 5.39},
|
|
}
|
|
)
|
|
|
|
assert usage["available"] is True
|
|
assert usage["plan_type"] == "plus"
|
|
assert usage["primary"]["used_percent"] == 39
|
|
assert usage["primary"]["remaining_percent"] == 61
|
|
assert usage["primary"]["label"] == "5h"
|
|
assert usage["secondary"]["used_percent"] == 15
|
|
assert usage["secondary"]["label"] == "7d"
|
|
assert usage["credits"]["balance"] == 5.39
|
|
|
|
|
|
def test_normalize_usage_payload_accepts_zero_percent_headers():
|
|
usage = codex.normalize_usage_payload(
|
|
{},
|
|
{
|
|
"x-codex-primary-used-percent": "0",
|
|
"x-codex-primary-window-minutes": "300",
|
|
},
|
|
)
|
|
|
|
assert usage["available"] is True
|
|
assert usage["primary"]["used_percent"] == 0
|
|
assert usage["primary"]["remaining_percent"] == 100
|
|
assert usage["primary"]["label"] == "5h"
|
|
|
|
|
|
def test_token_error_message_prefers_description():
|
|
class FakeResponse:
|
|
status_code = 400
|
|
text = '{"error":"invalid_grant","error_description":"refresh token was already used"}'
|
|
|
|
@staticmethod
|
|
def json():
|
|
return {
|
|
"error": "invalid_grant",
|
|
"error_description": "refresh token was already used",
|
|
}
|
|
|
|
assert codex._token_error_message(FakeResponse()) == "refresh token was already used"
|
|
|
|
|
|
@pytest.mark.parametrize("error", [
|
|
{"error": {"code": "upstream_error", "message": "Invalid refresh token."}},
|
|
{"error": "invalid_grant", "error_description": "private upstream detail"},
|
|
{"error": {"code": "refresh_token_reused", "message": "private upstream detail"}},
|
|
{"error": {"code": "refresh_token_expired", "message": "private upstream detail"}},
|
|
{"error": {"code": "refresh_token_invalidated", "message": "private upstream detail"}},
|
|
])
|
|
def test_rejected_refresh_notifies_once_and_recovers_after_sign_in(tmp_path, monkeypatch, error):
|
|
from helpers.notification import NotificationManager
|
|
|
|
path = tmp_path / "auth.json"
|
|
auth = {
|
|
"tokens": {"access_token": "old-access", "refresh_token": "old-refresh", "account_id": "account"},
|
|
"last_refresh": "2000-01-01T00:00:00Z",
|
|
}
|
|
path.write_text(json.dumps(auth))
|
|
monkeypatch.setattr(codex, "resolve_auth_write_path", lambda: path)
|
|
monkeypatch.setattr(codex, "codex_config", lambda: {
|
|
"token_url": "https://auth.example/token", "client_id": "client", "forced_workspace_id": "",
|
|
})
|
|
monkeypatch.setattr(codex, "resolve_agent_zero_user_agent", lambda: "test")
|
|
refresh_calls, notifications = [], []
|
|
monkeypatch.setattr(codex.requests, "post", lambda *a, **kw: refresh_calls.append(kw) or SimpleNamespace(
|
|
ok=False, status_code=400, text=json.dumps(error), json=lambda: error,
|
|
))
|
|
monkeypatch.setattr(NotificationManager, "send_notification", lambda **kw: notifications.append(kw))
|
|
|
|
for _ in range(2):
|
|
with pytest.raises(codex.ProviderError, match="Reconnect your account") as failure:
|
|
codex.load_auth()
|
|
assert failure.value.status == 401
|
|
assert failure.value.code == "reconnect_required"
|
|
assert len(refresh_calls) == len(notifications) == 1
|
|
saved = json.loads(path.read_text())
|
|
assert saved["tokens"] == auth["tokens"]
|
|
assert saved["reconnect_required"] is True
|
|
status = codex.status()
|
|
assert status["connected"] is True
|
|
assert status["reconnect_required"] is True
|
|
assert len(refresh_calls) == len(notifications) == 1
|
|
message = notifications[0]["message"]
|
|
assert "Open OAuth settings" in message and "openConfig('_oauth')" in message
|
|
assert "private upstream detail" not in message and "old-refresh" not in message
|
|
|
|
monkeypatch.setattr(codex, "derive_account_id", lambda _: "account")
|
|
monkeypatch.setattr(codex, "obtain_api_key", lambda _: "")
|
|
monkeypatch.setattr(codex, "fetch_usage", lambda: {"available": False})
|
|
codex.persist_exchanged_tokens({"id_token": "new-id", "access_token": "new-access", "refresh_token": "new-refresh"})
|
|
assert codex.load_auth().access_token == "new-access"
|
|
assert codex.status()["reconnect_required"] is False
|
|
assert "reconnect_required" not in json.loads(path.read_text())
|
|
|
|
|
|
def test_transient_refresh_failure_does_not_require_reconnect(tmp_path, monkeypatch):
|
|
path = tmp_path / "auth.json"
|
|
_write_refreshable_auth(path)
|
|
original = path.read_text()
|
|
monkeypatch.setattr(codex, "resolve_auth_write_path", lambda: path)
|
|
monkeypatch.setattr(codex, "codex_config", lambda: {"token_url": "https://auth.example/token", "client_id": "client"})
|
|
monkeypatch.setattr(codex, "resolve_agent_zero_user_agent", lambda: "test")
|
|
monkeypatch.setattr(codex.requests, "post", lambda *a, **kw: SimpleNamespace(
|
|
ok=False, status_code=503, text="unavailable", json=lambda: {"error": "temporarily_unavailable"},
|
|
))
|
|
with pytest.raises(RuntimeError, match="temporarily_unavailable"):
|
|
codex.load_auth()
|
|
assert path.read_text() == original
|
|
|
|
|
|
@pytest.mark.parametrize("route", [routes.codex_models, routes.codex_responses, routes.codex_chat_completions])
|
|
@pytest.mark.parametrize("stream", [False, True])
|
|
def test_codex_routes_preserve_reconnect_error(monkeypatch, route, stream):
|
|
from flask import Flask
|
|
|
|
def rejected(*args, **kwargs):
|
|
raise codex.ProviderError(codex.RECONNECT_MESSAGE, status=401, code="reconnect_required")
|
|
|
|
monkeypatch.setattr(routes, "_proxy_denied_response", lambda: None)
|
|
monkeypatch.setattr(codex, "prepare_responses_body", lambda body, **kw: body)
|
|
monkeypatch.setattr(codex, "fetch_models", rejected)
|
|
monkeypatch.setattr(codex, "request_codex", rejected)
|
|
with Flask(__name__).test_request_context("/", method="POST", json={"model": "test", "messages": [], "stream": stream}):
|
|
response, status = route()
|
|
assert status == 401
|
|
assert response.json["error"]["code"] == "reconnect_required"
|
|
assert response.json["error"]["message"] == codex.RECONNECT_MESSAGE
|
|
|
|
|
|
def test_refresh_tokens_sends_agent_zero_user_agent(monkeypatch):
|
|
requests: list[dict] = []
|
|
|
|
class FakeResponse:
|
|
ok = True
|
|
|
|
@staticmethod
|
|
def json():
|
|
return {
|
|
"access_token": "access-1",
|
|
"refresh_token": "refresh-1",
|
|
}
|
|
|
|
def post(url, *, headers, json, timeout):
|
|
requests.append(
|
|
{
|
|
"url": url,
|
|
"headers": headers,
|
|
"json": json,
|
|
"timeout": timeout,
|
|
}
|
|
)
|
|
return FakeResponse()
|
|
|
|
monkeypatch.setattr(
|
|
codex,
|
|
"codex_config",
|
|
lambda: {"token_url": "https://auth.example/oauth/token", "client_id": "client"},
|
|
)
|
|
monkeypatch.setattr(codex, "resolve_agent_zero_user_agent", lambda: "agent-zero/v1.18")
|
|
monkeypatch.setattr(codex.requests, "post", post)
|
|
|
|
assert codex.refresh_tokens("refresh-0") == {
|
|
"id_token": "",
|
|
"access_token": "access-1",
|
|
"refresh_token": "refresh-1",
|
|
}
|
|
assert requests == [
|
|
{
|
|
"url": "https://auth.example/oauth/token",
|
|
"headers": {
|
|
"Content-Type": "application/json",
|
|
"User-Agent": "agent-zero/v1.18",
|
|
},
|
|
"json": {
|
|
"client_id": "client",
|
|
"grant_type": "refresh_token",
|
|
"refresh_token": "refresh-0",
|
|
},
|
|
"timeout": 30,
|
|
}
|
|
]
|
|
|
|
|
|
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_explicit_codex_cli_auth_hard_link_is_rejected(tmp_path, monkeypatch):
|
|
shared_auth = tmp_path / ".codex" / "auth.json"
|
|
shared_auth.parent.mkdir()
|
|
shared_auth.write_text(json.dumps({"tokens": {"refresh_token": "shared"}}), encoding="utf-8")
|
|
alias = tmp_path / "agent-zero-auth.json"
|
|
alias.hardlink_to(shared_auth)
|
|
monkeypatch.setenv("HOME", str(tmp_path))
|
|
monkeypatch.setattr(codex, "codex_config", lambda: {"auth_file_path": str(alias)})
|
|
|
|
with pytest.raises(RuntimeError, match="Agent Zero-owned auth file"):
|
|
codex.resolve_auth_write_path()
|
|
|
|
|
|
def test_explicit_private_auth_hard_link_is_rejected(tmp_path, monkeypatch):
|
|
private_auth = tmp_path / "private-auth.json"
|
|
private_auth.write_text(json.dumps({"tokens": {"refresh_token": "private"}}), encoding="utf-8")
|
|
alias = tmp_path / "agent-zero-auth.json"
|
|
alias.hardlink_to(private_auth)
|
|
monkeypatch.setattr(codex, "codex_config", lambda: {"auth_file_path": str(alias)})
|
|
|
|
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_write_auth_file_falls_back_for_file_bind_mount(tmp_path, monkeypatch):
|
|
auth_path = tmp_path / "auth.json"
|
|
auth_path.write_text(json.dumps({"tokens": {"refresh_token": "refresh-0"}}), encoding="utf-8")
|
|
|
|
def reject_replace(source, destination):
|
|
raise OSError(codex.errno.EBUSY, "Device or resource busy", destination)
|
|
|
|
monkeypatch.setattr(codex.os, "replace", reject_replace)
|
|
|
|
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 stat.S_IMODE(auth_path.stat().st_mode) == 0o600
|
|
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 stat.S_IMODE(auth_path.stat().st_mode) == 0o600
|
|
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]
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
("host", "expected"),
|
|
[
|
|
("localhost:5000", True),
|
|
("127.0.0.1:5000", True),
|
|
("[::1]:5000", True),
|
|
("::1", True),
|
|
("example.com:5000", False),
|
|
],
|
|
)
|
|
def test_proxy_local_host_detection_supports_loopback_ipv6(host, expected):
|
|
assert routes._host_is_local(host) is expected
|
|
|
|
|
|
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 / ".codex" / "auth.json"
|
|
private_auth.write_text(
|
|
json.dumps(
|
|
{
|
|
"auth_mode": "chatgpt",
|
|
"OPENAI_API_KEY": "sk-keep",
|
|
"reconnect_required": True,
|
|
"tokens": {
|
|
"access_token": "access",
|
|
"refresh_token": "refresh",
|
|
"id_token": "id",
|
|
"account_id": "account",
|
|
},
|
|
"last_refresh": "2026-01-01T00:00:00Z",
|
|
}
|
|
),
|
|
encoding="utf-8",
|
|
)
|
|
shared_auth.parent.mkdir()
|
|
shared_auth.write_text(
|
|
json.dumps(
|
|
{
|
|
"auth_mode": "chatgpt",
|
|
"OPENAI_API_KEY": None,
|
|
"tokens": {"access_token": "access", "account_id": "account"},
|
|
"last_refresh": "2026-01-01T00:00:00Z",
|
|
}
|
|
),
|
|
encoding="utf-8",
|
|
)
|
|
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 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)
|
|
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)
|
|
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():
|
|
provider_path = Path(__file__).resolve().parents[1] / "plugins/_oauth/conf/model_providers.yaml"
|
|
provider_config = yaml.safe_load(provider_path.read_text(encoding="utf-8"))
|
|
codex_provider = provider_config["chat"]["codex_oauth"]
|
|
|
|
assert codex_provider["name"] == "Codex/ChatGPT Account"
|
|
assert codex_provider["models_list"]["endpoint_url"] == "/models"
|
|
assert codex_provider["kwargs"]["api_base"] == "http://127.0.0.1/oauth/codex/v1"
|
|
assert codex_provider["kwargs"]["responses_state"] == "local"
|
|
assert "50001" not in json.dumps(codex_provider)
|
|
|
|
|
|
def test_codex_provider_leaves_api_key_empty_until_connected(monkeypatch):
|
|
monkeypatch.setattr(oauth_dummy_key, "oauth_provider_is_connected", lambda _provider_id: False)
|
|
data = {"args": ("codex_oauth",), "kwargs": {}, "result": "None"}
|
|
|
|
oauth_dummy_key.OAuthAccountDummyKey(agent=None).execute(data=data)
|
|
|
|
assert data["result"] == "None"
|
|
|
|
|
|
def test_codex_provider_reports_dummy_api_key_when_connected(monkeypatch):
|
|
monkeypatch.setattr(oauth_dummy_key, "oauth_provider_is_connected", lambda _provider_id: True)
|
|
data = {"args": ("codex_oauth",), "kwargs": {}, "result": "None"}
|
|
|
|
oauth_dummy_key.OAuthAccountDummyKey(agent=None).execute(data=data)
|
|
|
|
assert data["result"] == DUMMY_API_KEY
|
|
|
|
|
|
def test_codex_provider_replaces_legacy_stored_key_when_connected(monkeypatch):
|
|
monkeypatch.setattr(oauth_dummy_key, "oauth_provider_is_connected", lambda _provider_id: True)
|
|
data = {"args": ("codex_oauth",), "kwargs": {}, "result": "legacy-stored-key"}
|
|
|
|
oauth_dummy_key.OAuthAccountDummyKey(agent=None).execute(data=data)
|
|
|
|
assert data["result"] == DUMMY_API_KEY
|
|
|
|
|
|
@pytest.mark.parametrize('mode,options,expected', [
|
|
('chat', None, {'include_usage': True}),
|
|
('chat_completions', {'include_usage': False}, {'include_usage': False}),
|
|
('responses', None, None),
|
|
])
|
|
def test_codex_chat_requests_usage_without_changing_responses_or_explicit_options(mode, options, expected):
|
|
kwargs = {'a0_api_mode': mode}
|
|
if options is not None:
|
|
kwargs['stream_options'] = options
|
|
model = SimpleNamespace(a0_model_conf=SimpleNamespace(provider='codex_oauth'), kwargs=kwargs)
|
|
agent = SimpleNamespace(context=SimpleNamespace(id='test'), number=0)
|
|
CodexSession(agent=agent).execute(call_data={'model':model})
|
|
assert model.kwargs.get('stream_options') == expected
|
|
|
|
|
|
@pytest.mark.parametrize('include_usage', [True, False])
|
|
@pytest.mark.parametrize('ending', ['completed', 'incomplete', 'failed', 'missing', 'no_usage'])
|
|
def test_codex_chat_stream_usage_terminal_state_and_cleanup(monkeypatch, include_usage, ending):
|
|
from flask import Flask
|
|
from unittest.mock import Mock
|
|
usage = {'input_tokens': 2000, 'output_tokens': 20, 'total_tokens': 2020,
|
|
'input_tokens_details': {'cached_tokens': 1024},
|
|
'output_tokens_details': {'reasoning_tokens': 8}}
|
|
expected = {'prompt_tokens': 2000, 'completion_tokens': 20, 'total_tokens': 2020,
|
|
'prompt_tokens_details': {'cached_tokens': 1024},
|
|
'completion_tokens_details': {'reasoning_tokens': 8}}
|
|
events = [{'type':'response.output_text.delta', 'delta':'Hello'}]
|
|
if ending != 'missing':
|
|
event_type = ending if ending in {'incomplete','failed'} else 'completed'
|
|
response = {'usage': usage} if ending != 'no_usage' else {}
|
|
if ending == 'incomplete':
|
|
response['incomplete_details'] = {'reason':'max_output_tokens'}
|
|
if ending == 'failed':
|
|
response['error'] = {'message':'upstream failed', 'type':'server_error'}
|
|
events.append({'type':'response.'+event_type, 'response':response})
|
|
upstream = SimpleNamespace(close=Mock())
|
|
monkeypatch.setattr(codex, 'iter_sse_events', lambda response: ({'data':json.dumps(event)} for event in events))
|
|
app = Flask(__name__)
|
|
with app.test_request_context('/'):
|
|
result = routes._stream_chat_completion(upstream, 'test-model', include_usage=include_usage)
|
|
blocks = result.get_data(as_text=True).split('\n\n')
|
|
chunks = [json.loads(block[6:]) for block in blocks if block.startswith('data: ') and block != 'data: [DONE]']
|
|
upstream.close.assert_called_once()
|
|
assert chunks[1]['choices'][0]['delta']['content'] == 'Hello'
|
|
if ending in {'failed', 'missing'}:
|
|
assert 'error' in chunks[-1]
|
|
assert not any(c.get('choices') and c['choices'][0]['finish_reason'] for c in chunks)
|
|
else:
|
|
final_choices = [c for c in chunks if c.get('choices')][-1]['choices']
|
|
assert final_choices[0]['finish_reason'] == ('length' if ending == 'incomplete' else 'stop')
|
|
if include_usage and ending != 'no_usage':
|
|
assert chunks[-1]['choices'] == []
|
|
assert chunks[-1]['usage'] == expected
|
|
else:
|
|
assert not any(c.get('usage') for c in chunks)
|
|
assert routes._chat_usage(usage) == expected
|
|
assert routes._chat_usage(None) == {}
|
|
|
|
|
|
@pytest.mark.parametrize('status,expected_reason', [('completed','stop'), ('incomplete','length'), ('failed',None)])
|
|
def test_codex_chat_nonstream_maps_usage_and_terminal_state(monkeypatch, status, expected_reason):
|
|
from flask import Flask
|
|
monkeypatch.setattr(routes, '_proxy_denied_response', lambda: None)
|
|
monkeypatch.setattr(codex, 'chat_messages_to_response_body', lambda body: {'model':'test'})
|
|
monkeypatch.setattr(codex, 'prepare_responses_body', lambda body, **kwargs: body)
|
|
monkeypatch.setattr(codex, 'request_codex', lambda *args, **kwargs: SimpleNamespace(ok=True))
|
|
monkeypatch.setattr(codex, 'collect_completed_response', lambda upstream: {
|
|
'status':status, 'output_text':'partial answer',
|
|
'incomplete_details':{'reason':'max_output_tokens'},
|
|
'usage':{'input_tokens':2048,'output_tokens':10,'input_tokens_details':{'cached_tokens':1024}},
|
|
})
|
|
app = Flask(__name__)
|
|
with app.test_request_context('/chat', method='POST', json={'model':'test','messages':[]}):
|
|
response = app.make_response(routes.codex_chat_completions())
|
|
if expected_reason is None:
|
|
assert response.status_code == 502
|
|
assert 'error' in response.get_json()
|
|
else:
|
|
data = response.get_json()
|
|
assert data['choices'][0]['finish_reason'] == expected_reason
|
|
assert data['usage'] == {'prompt_tokens':2048,'completion_tokens':10,'prompt_tokens_details':{'cached_tokens':1024}}
|
|
assert 'total_tokens' not in data['usage']
|
|
|
|
|
|
@pytest.mark.parametrize("ending", ["unread", "cancelled", "completed", "error"])
|
|
def test_oauth_native_stream_closes_upstream_with_response(ending):
|
|
from flask import Flask
|
|
from unittest.mock import Mock
|
|
|
|
chunks = [b"data: first\n\n", b"data: second\n\n"]
|
|
|
|
def iter_content(chunk_size):
|
|
yield chunks[0]
|
|
if ending == "error":
|
|
raise RuntimeError("upstream disconnected")
|
|
yield chunks[1]
|
|
|
|
upstream = SimpleNamespace(
|
|
status_code=200,
|
|
headers={"Content-Type": "text/event-stream", "x-request-id": "test-request"},
|
|
iter_content=iter_content,
|
|
close=Mock(),
|
|
)
|
|
with Flask(__name__).test_request_context("/"):
|
|
response = routes._stream_upstream_sse(upstream)
|
|
try:
|
|
assert response.status_code == 200
|
|
assert response.headers["x-request-id"] == "test-request"
|
|
assert response.headers["Cache-Control"] == "no-cache"
|
|
iterator = iter(response.response)
|
|
if ending == "cancelled":
|
|
assert next(iterator) == chunks[0]
|
|
elif ending == "completed":
|
|
assert list(iterator) == chunks
|
|
elif ending == "error":
|
|
with pytest.raises(RuntimeError, match="upstream disconnected"):
|
|
list(iterator)
|
|
finally:
|
|
response.close()
|
|
upstream.close.assert_called_once()
|
|
|
|
|
|
def test_codex_chat_stream_closes_upstream_when_consumer_stops():
|
|
from flask import Flask
|
|
from unittest.mock import Mock
|
|
upstream = SimpleNamespace(close=Mock())
|
|
with Flask(__name__).test_request_context('/'):
|
|
response = routes._stream_chat_completion(upstream, 'test')
|
|
iterator = iter(response.response)
|
|
next(iterator)
|
|
iterator.close()
|
|
upstream.close.assert_called_once()
|