diff --git a/docs-site/src/content/docs/es/reference/configuration/providers.md b/docs-site/src/content/docs/es/reference/configuration/providers.md index 9b25a315fc0..de3a5222c15 100644 --- a/docs-site/src/content/docs/es/reference/configuration/providers.md +++ b/docs-site/src/content/docs/es/reference/configuration/providers.md @@ -920,7 +920,7 @@ Rotar entre cuentas de suscripción gasta la cuota de una segunda cuenta y puede ### Formas de registro administradas -`apiKeys[]` entradas contienen `id`, `name`, generado `key`, y cadenas ISO `createdAt`. Opcional `allowMeteredComboTargets: true` permite explícitamente los objetivos marcados `metered: true`; el consentimiento omitido o falso los niega. El token de entorno nunca califica. Las personas que llaman solo en bucle local pueden usar per-combo `allowMeteredTargets: true`; las personas que llaman con clave configurada y vinculada aún necesitan consentimiento de clave. Véase [Consentimiento de fallback medido](/es/guides/combos/#metered-fallback-consent). `codexAccounts[]` entradas requieren `id`, `email`, y `isMain`, con opcional `plan`, `chatgptAccountId`, y la privacidad de seguridad `logLabel`. Estos registros normalmente se administran en el panel de control. +`apiKeys[]` entradas contienen `id`, `name`, generado `key`, y cadenas ISO `createdAt`. Opcional `allowMeteredComboTargets: true` permite explícitamente los objetivos marcados `metered: true`; el consentimiento omitido o falso los niega. El token de entorno nunca califica. Las personas que llaman solo en bucle local pueden usar per-combo `allowMeteredTargets: true`; las personas que llaman con clave configurada y vinculada aún necesitan consentimiento de clave. Véase [Consentimiento de fallback medido](/es/guides/combos/#metered-fallback-consent). `codexAccounts[]` entradas requieren `id`, `email`, y `isMain`, con opcional `plan`, `chatgptAccountId`, y la privacidad de seguridad `logLabel`. Estos registros normalmente se administran en el panel de control. Un objeto opcional `egress` da a una cuenta del grupo su propia ruta, con los mismos valores `proxy` y `noProxy` que la salida por proveedor: un `proxy` de la cuenta sustituye al del proveedor `openai` para las solicitudes, compactaciones, renovaciones de token, consultas de uso, calentamientos, descubrimiento de modelos y llamadas de créditos de reinicio de esa cuenta, y la consulta de uso y el calentamiento tras iniciar sesión; un `proxy` omitido conserva el del proveedor, y las entradas `noProxy` de la cuenta se aplican antes que las del proveedor. Las llamadas en segundo plano del grupo ahora siguen `providers.openai.proxy`, y un `egress` por cuenta lo sustituye: una cuenta del grupo sin objeto `egress` también envía esas llamadas por la ruta del proveedor `openai`. Si `config.json` falta o no se puede leer, o una credencial guardada ya no figura en `codexAccounts` (por ejemplo, se eliminó mientras una llamada estaba en curso), la llamada se rechaza en lugar de enviarse sin la ruta configurada. El inicio de sesión principal no tiene entrada en el grupo y siempre usa la ruta del proveedor. ### `tokenGuardian` (`OcxTokenGuardianConfig`) diff --git a/docs-site/src/content/docs/reference/configuration/providers.md b/docs-site/src/content/docs/reference/configuration/providers.md index 880b0c531e6..bf57ce8b850 100644 --- a/docs-site/src/content/docs/reference/configuration/providers.md +++ b/docs-site/src/content/docs/reference/configuration/providers.md @@ -1425,6 +1425,7 @@ provider in question. `apiKeys[]` entries contain `id`, `name`, generated `key`, and ISO `createdAt` strings. Optional `allowMeteredComboTargets: true` explicitly permits targets marked `metered: true`; omitted or false consent denies them. The environment token never qualifies. Local loopback-only callers can instead use per-combo `allowMeteredTargets: true`; configured-key and linked callers still need key consent. See [Metered fallback consent](/guides/combos/#metered-fallback-consent). `codexAccounts[]` entries require `id`, `email`, and `isMain`, with optional `plan`, `chatgptAccountId`, and privacy-safe `logLabel`. These records are normally dashboard-managed. +An optional `egress` object gives one pool account its own route, with the same `proxy` and `noProxy` values as a provider's [per-provider egress](#per-provider-egress): an account `proxy` replaces the `openai` provider's for that account's requests, compactions, token refreshes, usage checks, warmups, model discovery and reset-credit calls, and the usage check and warmup after signing in; an omitted `proxy` keeps the provider's, and the account's `noProxy` entries apply ahead of the provider's. Pool background calls now follow `providers.openai.proxy`, and a per-account `egress` overrides it: a pool account without an `egress` object sends those calls by the `openai` provider's route too. If `config.json` is missing or cannot be read, or a stored account credential is no longer listed in `codexAccounts` (for example, removed while a call was in flight), the call is refused instead of sent without the configured route. The main login has no pool entry and always uses the provider's route. ### `tokenGuardian` (`OcxTokenGuardianConfig`) diff --git a/scripts/test-layout/layout-server-inbound.json b/scripts/test-layout/layout-server-inbound.json index b77830002b7..3e8e8c32c17 100644 --- a/scripts/test-layout/layout-server-inbound.json +++ b/scripts/test-layout/layout-server-inbound.json @@ -1,4 +1,6 @@ { + "provider-egress-account.test.ts": "lib", + "provider-egress-account-calls.test.ts": "lib", "account-diagnostics-routes.test.ts": "server", "explicit-proxy-no-proxy.test.ts": "lib", "gemini-native.test.ts": "server", diff --git a/scripts/test-layout/layout.json b/scripts/test-layout/layout.json index 6c60cd343d1..363080d7704 100644 --- a/scripts/test-layout/layout.json +++ b/scripts/test-layout/layout.json @@ -2,7 +2,7 @@ "version": 1, "root": "tests", "explicitShards": ["layout-route-intent.json", "layout-client-connections.json", "layout-release-signing.json", "layout-file-identity.json", "layout-clients.json", "layout-codex-collision.json", "layout-native-profiles.json", "layout-agent-assertion.json", "layout-chat.json", "layout-replay.json", "layout-adapters.json", "layout-jev.json", "layout-workbuddy.json", "layout-combos.json", "layout-credit-renewal.json", "layout-server-inbound.json", "layout-providers.json", "layout-responses.json", "layout-exec-boundary.json", "layout-persistent-dashboard.json", "layout-start-ownership.json", "layout-config.json", "layout-kiro-usage.json", "layout-usage.json", "layout-docs-guides.json", "layout-docs.json", "layout-claude-keychain.json", "layout-test-hygiene.json", "layout-codex-journal.json", "layout-upload-reduction.json", "layout-step-cli.json"], - "explicit": { "gui-account-quota-table.test.ts": "gui", "account-probe-routes.test.ts": "server", "web-search-local-deadline-provenance.test.ts": "web-search", "kimi-monthly-quota.test.ts": "providers", "vertex-adc-verified.test.ts": "adapters/google", "sync-fanout.test.ts": "cli", "sync-command-fanout.test.ts": "cli", "link-pinned-sync-argv.test.ts": "clients", "sync-link-status.test.ts": "cli", "sync-fanout-process.test.ts": "cli", "codex-installation-acl.test.ts": "codex-integration", "codex-installation-id.test.ts": "codex-integration", "codex-installation-wire.test.ts": "codex-integration", "codex-installation-failover.test.ts": "responses", "service-desktop-recovery.test.ts": "service", "catalog-omit-disabled-native.test.ts": "codex-integration", "provider-input-modalities.test.ts": "providers", "combo-description.test.ts": "routing", "combo-description-catalog.test.ts": "codex-integration", "codex-provider-routing.test.ts": "codex-integration", "config-native-reasoning-retention.test.ts": "config", "server-native-reasoning-retention-merge.test.ts": "server", "server-native-reasoning-retention.test.ts": "server", "config-workflow-budget.test.ts": "config", "server-workflow-budget-settings.test.ts": "server", "responses-retained-reasoning-stream-recovery.test.ts": "responses", "openai-native-hosted-search-history.test.ts": "adapters/openai", "responses-native-compact-search-history.test.ts": "responses", "config-hosted-search-projection.test.ts": "config", "gcp-credential-boundary.test.ts": "adapters/google", "gcp-sa-marker.test.ts": "adapters/google", "gcp-sa-adapter.test.ts": "adapters/google", "management-gcp-credential-input.test.ts": "server", "codex-preserve-signed-in.test.ts": "codex-integration", "cli-account-preservation.test.ts": "cli", "cli-provider-list-active.test.ts": "cli", "service-state-isolation.test.ts": "service", "compaction-history-framing.test.ts": "responses", "catalog-native-max-context.test.ts": "codex-integration", "protocol-argon-thought-boundary.test.ts": "responses", "service-log.test.ts": "service", "messages-native-empty-inline.test.ts": "claude-integration", "catalog-auto-review-override.test.ts": "codex-integration", "management-auto-review-settings.test.ts": "server", "management-auto-review-auth.test.ts": "server", "prefer-model-alias-ids.test.ts": "server", "responses-mimo-envelope.test.ts": "responses", "responses-call-id-linkage.test.ts": "responses", "bridge-terminal-refusal.test.ts": "adapters", "loop-terminal-refusal.test.ts": "images", "web-search-terminal-refusal.test.ts": "web-search", "combo-terminal-refusal.test.ts": "routing", "server-terminal-refusal-wiring.test.ts": "server", "incomplete-reason-normalization.test.ts": "responses", "advisor-retention.test.ts": "advisor", "responses-native-key-cooldown.test.ts": "responses", "responses-run-turn-key-readmission.test.ts": "responses", "qoder-spawn-readmission.test.ts": "adapters", "api-key-selection-cooldown.test.ts": "providers", "api-key-auto-pause-distribution.test.ts": "providers", "explicit-key-pause-oauth-boundary.test.ts": "providers", "server-chat-native-key-selection.test.ts": "server", "compact-key-selection.test.ts": "responses", "messages-native-key-selection.test.ts": "claude-integration", "coding-agent-windows-dispatch.test.ts": "adapters", "coding-agent-native-empty-argv.test.ts": "windows", "cli-message-mcp-resume.test.ts": "cli", "messaging-mcp-resume.test.ts": "codex-integration", "pr-gates-workflow.test.ts": "ci-workflows", + "explicit": { "gui-account-quota-table.test.ts": "gui", "account-probe-routes.test.ts": "server", "web-search-local-deadline-provenance.test.ts": "web-search", "kimi-monthly-quota.test.ts": "providers", "vertex-adc-verified.test.ts": "adapters/google", "sync-fanout.test.ts": "cli", "sync-command-fanout.test.ts": "cli", "link-pinned-sync-argv.test.ts": "clients", "sync-link-status.test.ts": "cli", "sync-fanout-process.test.ts": "cli", "codex-installation-acl.test.ts": "codex-integration", "codex-installation-id.test.ts": "codex-integration", "codex-installation-wire.test.ts": "codex-integration", "codex-installation-failover.test.ts": "responses", "codex-pool-account-egress-compact.test.ts": "responses", "codex-account-egress-background.test.ts": "codex-integration", "service-desktop-recovery.test.ts": "service", "catalog-omit-disabled-native.test.ts": "codex-integration", "provider-input-modalities.test.ts": "providers", "combo-description.test.ts": "routing", "combo-description-catalog.test.ts": "codex-integration", "codex-provider-routing.test.ts": "codex-integration", "config-native-reasoning-retention.test.ts": "config", "server-native-reasoning-retention-merge.test.ts": "server", "server-native-reasoning-retention.test.ts": "server", "config-workflow-budget.test.ts": "config", "server-workflow-budget-settings.test.ts": "server", "responses-retained-reasoning-stream-recovery.test.ts": "responses", "openai-native-hosted-search-history.test.ts": "adapters/openai", "responses-native-compact-search-history.test.ts": "responses", "config-hosted-search-projection.test.ts": "config", "gcp-credential-boundary.test.ts": "adapters/google", "gcp-sa-marker.test.ts": "adapters/google", "gcp-sa-adapter.test.ts": "adapters/google", "management-gcp-credential-input.test.ts": "server", "codex-preserve-signed-in.test.ts": "codex-integration", "cli-account-preservation.test.ts": "cli", "cli-provider-list-active.test.ts": "cli", "service-state-isolation.test.ts": "service", "compaction-history-framing.test.ts": "responses", "catalog-native-max-context.test.ts": "codex-integration", "protocol-argon-thought-boundary.test.ts": "responses", "service-log.test.ts": "service", "messages-native-empty-inline.test.ts": "claude-integration", "catalog-auto-review-override.test.ts": "codex-integration", "management-auto-review-settings.test.ts": "server", "management-auto-review-auth.test.ts": "server", "prefer-model-alias-ids.test.ts": "server", "responses-mimo-envelope.test.ts": "responses", "responses-call-id-linkage.test.ts": "responses", "bridge-terminal-refusal.test.ts": "adapters", "loop-terminal-refusal.test.ts": "images", "web-search-terminal-refusal.test.ts": "web-search", "combo-terminal-refusal.test.ts": "routing", "server-terminal-refusal-wiring.test.ts": "server", "incomplete-reason-normalization.test.ts": "responses", "advisor-retention.test.ts": "advisor", "responses-native-key-cooldown.test.ts": "responses", "responses-run-turn-key-readmission.test.ts": "responses", "qoder-spawn-readmission.test.ts": "adapters", "api-key-selection-cooldown.test.ts": "providers", "api-key-auto-pause-distribution.test.ts": "providers", "explicit-key-pause-oauth-boundary.test.ts": "providers", "server-chat-native-key-selection.test.ts": "server", "compact-key-selection.test.ts": "responses", "messages-native-key-selection.test.ts": "claude-integration", "coding-agent-windows-dispatch.test.ts": "adapters", "coding-agent-native-empty-argv.test.ts": "windows", "cli-message-mcp-resume.test.ts": "cli", "messaging-mcp-resume.test.ts": "codex-integration", "pr-gates-workflow.test.ts": "ci-workflows", "stop-restore-history-ownership.test.ts": "service", "cli-stop-refusal-transport.test.ts": "cli", "service-proxy-env.test.ts": "service", "openai-chat-standalone-bare-block.test.ts": "adapters/openai", diff --git a/src/codex/account-egress-runtime.ts b/src/codex/account-egress-runtime.ts new file mode 100644 index 00000000000..f3dfa212aa0 --- /dev/null +++ b/src/codex/account-egress-runtime.ts @@ -0,0 +1,145 @@ +import { existsSync } from "node:fs"; +import { getConfigPath, loadConfig } from "../config"; +import { configLoadFellBack, fileBackedConfigPath } from "../config/rebase-provenance"; +import { providerEgressFetchInit, resolveProviderEgress, type PoolAccountRoute } from "../lib/provider-egress"; +import { configuredOutboundFetch } from "../lib/proxy-env"; +import type { OcxConfig, OcxProviderConfig } from "../types"; +import { codexAccountEgressRoute } from "./account-egress"; +import { MAIN_CODEX_ACCOUNT_ID } from "./account-id"; + +/** + * Routes for Codex pool calls that run without a request's config in hand: token refresh, usage + * (WHAM) probes, model discovery, reset credits, warmup and the post-login usage read. + * + * A pool account's credentialed calls leave by the same route as its inference: the account's own + * `codexAccounts[].egress` over the `openai` provider's `proxy`/`noProxy` (the provider that owns + * the account pool), over the global proxy. An account that names no proxy keeps the provider's. + * + * The route is resolved at each send, and every failure to establish it refuses the send rather + * than letting a pool credential leave by another route: + * - a stored pool credential whose row the config no longer lists (removed while the credential was + * in hand, even if credential cleanup failed, or an orphan whose former route is unknown); + * - a config that could not be read, so the load fell back to defaults while `config.json` exists. + * - no routing configuration at all (no binding for the current home and no `config.json`): a + * stored credential's former route cannot be known once its config is gone. + * Only a new login, whose row does not exist yet, takes the provider's route without a row. + * + * The running server binds its live config here for the lifetime of its background lifecycle + * (`src/server/background-lifecycle.ts`), together with the config path it was loaded from. A call + * made with no binding, or under a different config home, loads that home's file instead. + */ +export type CodexAccountEgressConfig = Pick; + +export interface CodexAccountEgressBinding { + config: CodexAccountEgressConfig; + configPath: string; + /** The config this server started with is defaults standing in for an unreadable file. */ + degraded: boolean; +} + +let live: CodexAccountEgressBinding | undefined; + +/** Bind a server's config under the current config home; returns the binding so an owner can restore it. */ +export function bindCodexAccountEgressConfig(config: CodexAccountEgressConfig): CodexAccountEgressBinding { + const configPath = getConfigPath(); + live = { config, configPath, degraded: configLoadFellBack(configPath) && existsSync(configPath) }; + return live; +} + +/** Reinstall a binding exactly as it was captured, with its own config home and load state. */ +export function restoreCodexAccountEgressBinding(binding: CodexAccountEgressBinding): void { + live = binding; +} + +/** Detach the live binding; with a config, only when it is still the bound one. */ +export function unbindCodexAccountEgressConfig(config?: CodexAccountEgressConfig): void { + if (!config || live?.config === config) live = undefined; +} + +/** Tests only. */ +export function resetCodexAccountEgressConfigForTests(): void { + live = undefined; +} + +export class CodexAccountRouteUnavailableError extends Error { + override readonly name = "CodexAccountRouteUnavailableError"; +} + +/** The provider whose route a pool account inherits. */ +export const CODEX_POOL_PROVIDER = "openai"; + +const UNREADABLE = "Codex account routing configuration could not be loaded; refusing to send without it"; + +/** The config whose routes apply now, or undefined when none exists (no binding, no `config.json`). */ +function routingConfig(): CodexAccountEgressConfig | undefined { + const configPath = getConfigPath(); + if (live && live.configPath === configPath) { + if (live.degraded) throw new CodexAccountRouteUnavailableError(UNREADABLE); + return live.config; + } + if (!existsSync(configPath)) return undefined; + const config = loadConfig(); + if (fileBackedConfigPath(config) === undefined || configLoadFellBack(configPath)) { + throw new CodexAccountRouteUnavailableError(UNREADABLE); + } + return config; +} + +interface CodexAccountRouting { + provider: Pick; + account?: PoolAccountRoute; +} + +export interface CodexAccountRoutingOptions { + config?: CodexAccountEgressConfig; + /** A new login, whose pool row does not exist yet: it takes the provider's route. */ + newLogin?: boolean; +} + +/** + * The routing inputs for one account's call, or undefined when the call keeps the process-wide + * route unchanged: no account (a direct or main-login caller), the main login, no config at all, or + * a pool account for which neither the account nor the provider configures `proxy`/`noProxy`. + */ +export function codexAccountRouting( + accountId: string | null | undefined, options: CodexAccountRoutingOptions = {}, +): CodexAccountRouting | undefined { + if (!accountId || accountId === MAIN_CODEX_ACCOUNT_ID) return undefined; + const source = options.config ?? routingConfig(); + if (!source) { + if (options.newLogin === true) return undefined; + throw new CodexAccountRouteUnavailableError("no Codex account routing configuration exists; refusing to send a stored pool credential"); + } + const row = source.codexAccounts?.find(candidate => candidate.id === accountId); + if (row?.isMain === true) return undefined; + if (!row && options.newLogin !== true) { + throw new CodexAccountRouteUnavailableError("this Codex pool account is not configured; refusing to send its credential"); + } + const account = codexAccountEgressRoute(source, accountId); + const providerConfig = source.providers?.[CODEX_POOL_PROVIDER]; + const provider = { proxy: providerConfig?.proxy, noProxy: providerConfig?.noProxy }; + if (!account && provider.proxy === undefined && provider.noProxy === undefined) return undefined; + return { provider, ...(account ? { account } : {}) }; +} + +function routeInit(routing: CodexAccountRouting, input: RequestInfo | URL): { proxy?: string | false } { + const url = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url; + return providerEgressFetchInit(resolveProviderEgress({ providerName: CODEX_POOL_PROVIDER, provider: routing.provider, url, account: routing.account })); +} + +/** + * A fetch for one account's credentialed call. The route is resolved when the call is sent; a + * refusal rejects the call before any byte leaves. With a configured route it sends through + * `configuredOutboundFetch` (so the explicit-proxy guards apply) over `base`; without one it is + * `base` (or the global fetch, looked up at call time) unchanged. + */ +export function codexAccountFetch( + accountId: string | null | undefined, options: CodexAccountRoutingOptions & { base?: typeof globalThis.fetch } = {}, +): typeof globalThis.fetch { + const { base } = options; + return (async (input: RequestInfo | URL, init?: RequestInit) => { + const routing = codexAccountRouting(accountId, options); + if (!routing) return (base ?? fetch)(input, init); + return configuredOutboundFetch(input, { ...init, ...routeInit(routing, input) } as RequestInit, base); + }) as typeof globalThis.fetch; +} diff --git a/src/codex/account-egress.ts b/src/codex/account-egress.ts new file mode 100644 index 00000000000..94fdae74d5b --- /dev/null +++ b/src/codex/account-egress.ts @@ -0,0 +1,14 @@ +import type { PoolAccountRoute } from "../lib/provider-egress"; +import type { OcxConfig } from "../types"; + +/** + * The configured route of one Codex pool account (`codexAccounts[].egress`), or undefined when the + * account has none or is not a pool account. The main login has no pool entry and uses the provider's route. + */ +export function codexAccountEgressRoute( + config: Pick, accountId: string | null | undefined, +): PoolAccountRoute | undefined { + if (!accountId) return undefined; + const account = config.codexAccounts?.find(row => row.id === accountId && row.isMain !== true); + return account?.egress ? { id: account.id, scope: `codexAccounts.${account.id}.egress`, egress: account.egress } : undefined; +} diff --git a/src/codex/account-store.ts b/src/codex/account-store.ts index 35af6227a32..a6790cfc95d 100644 --- a/src/codex/account-store.ts +++ b/src/codex/account-store.ts @@ -1,4 +1,5 @@ import { publishCredentialSync } from "../local-credentials/generation"; +import { codexAccountFetch } from "./account-egress-runtime"; import { classifyChatgptRefreshFailure, noteChatgptRefreshFailure, type ChatgptRefreshDiagnosticCode } from "./chatgpt-refresh-failure"; import { readBoundedResponseBody } from "../lib/bounded-body"; export { classifyChatgptRefreshFailure } from "./chatgpt-refresh-failure"; @@ -1405,7 +1406,8 @@ async function resolveCodexToken( provenance: "self-refresh", }; } - const res = await fetch(CHATGPT_TOKEN_URL, { + // An account with its own route (codexAccounts[].egress) refreshes through it, like its requests. + const res = await codexAccountFetch(id)(CHATGPT_TOKEN_URL, { method: "POST", headers: { "Content-Type": "application/json", diff --git a/src/codex/auth-api/login-flow.ts b/src/codex/auth-api/login-flow.ts index 792530d1f88..315a66ad6df 100644 --- a/src/codex/auth-api/login-flow.ts +++ b/src/codex/auth-api/login-flow.ts @@ -13,6 +13,7 @@ import { clearCodexPoolRefreshFailure } from "../pool-refresh-backoff"; import { reconcileLiveStateStores } from "../../lib/state-store-registrations"; import { emailMaskingEnabled, projectEmail } from "../../lib/privacy"; import { CodexWarmupError, codexWarmupFailureReason, isCodexWarmupProvisioningFailure, warmCodexAccount } from "../warmup"; +import { codexAccountFetch } from "../account-egress-runtime"; import type { CodexAccount, CodexAccountCredentials, OcxConfig } from "../../types"; import type { OAuthCredentials } from "../../oauth/types"; import type { CatalogDisposition } from "../convergence-types"; @@ -48,9 +49,10 @@ export async function verifyCodexAccountWarmup( accountId: string, accessToken: string, chatgptAccountId: string, + transport?: typeof globalThis.fetch, ): Promise<{ ok: true; validatedAt: number } | { ok: false; response: Response }> { try { - await warmCodexAccount({ accessToken, chatgptAccountId }); + await warmCodexAccount({ accessToken, chatgptAccountId, ...(transport ? { transport } : {}) }); return { ok: true, validatedAt: Date.now() }; } catch (err) { const reason = codexWarmupFailureReason(err); @@ -298,9 +300,11 @@ export async function handleCodexAuthLoginStart(req: Request, config: OcxConfig, let plan = extractChatgptPlanType(undefined, cred.access); let quota: Omit | null = null; let policyQuota: Omit | null = null; + // The account's route; a new login has no row yet and takes the provider's. + const accountTransport = codexAccountFetch(accountId, { newLogin: !reauth }); try { const tokens = { access_token: cred.access, account_id: oauthAccountId }; - const resp = await fetch("https://chatgpt.com/backend-api/wham/usage", { + const resp = await accountTransport("https://chatgpt.com/backend-api/wham/usage", { headers: { Authorization: `Bearer ${tokens.access_token}`, "ChatGPT-Account-Id": tokens.account_id }, signal: AbortSignal.timeout(8000), }); @@ -372,7 +376,7 @@ export async function handleCodexAuthLoginStart(req: Request, config: OcxConfig, // and keep it unavailable to routing. Unknown/failed usage reads retain the gate. const warmup = isCodexQuotaExhausted(quota, plan) ? { ok: true as const, validatedAt: undefined } - : await verifyCodexAccountWarmup(accountId, cred.access, oauthAccountId); + : await verifyCodexAccountWarmup(accountId, cred.access, oauthAccountId, accountTransport); if (!ownsPendingFlow()) return; if (!warmup.ok) { const body = await warmup.response.json().catch(() => ({})) as { error?: string; code?: string; reason?: string }; diff --git a/src/codex/auth-api/pool-quota-probe.ts b/src/codex/auth-api/pool-quota-probe.ts index 3d6ae70bd3e..bab0c659ed0 100644 --- a/src/codex/auth-api/pool-quota-probe.ts +++ b/src/codex/auth-api/pool-quota-probe.ts @@ -1,3 +1,4 @@ +import { codexAccountFetch } from "../account-egress-runtime"; import { rememberCodexCredits } from "../credits"; import { fetchCodexUsage } from "../quota-query-backoff"; import type { CodexUsageOwner } from "../quota-query-backoff"; @@ -271,8 +272,8 @@ export async function recoverPoolQuotaFrom401(ctx: { }, signal: AbortSignal.timeout(WHAM_REQUEST_TIMEOUT_MS), }, () => markQuotaProbeAttempted(ctx.quotaProbeEvidence, refreshed.generation), - ctx.recoveryProbeNow === undefined ? { poolAccountId: accountId } - : { poolAccountId: accountId, recoveryProbe: true, now: () => ctx.recoveryProbeNow! }); + ctx.recoveryProbeNow === undefined ? { poolAccountId: accountId, transport: codexAccountFetch(accountId) } + : { poolAccountId: accountId, recoveryProbe: true, now: () => ctx.recoveryProbeNow!, transport: codexAccountFetch(accountId) }); if (!replayRead) return { quota: existing ?? null, needsReauth: false, credentialGeneration: refreshed.generation, quotaProbeSkipped: true }; if (replayRead.kind === "joined") { if (!isCodexAccountGenerationLive(accountId, refreshed.generation) @@ -419,8 +420,8 @@ export async function fetchFreshPoolAccountQuota( headers: { Authorization: `Bearer ${accessToken}`, "ChatGPT-Account-Id": chatgptAccountId }, signal: AbortSignal.timeout(8000), }, () => markQuotaProbeAttempted(quotaProbeEvidence, generation), - recoveryProbeNow === undefined ? { poolAccountId: accountId } - : { poolAccountId: accountId, recoveryProbe: true, now: () => recoveryProbeNow }); + recoveryProbeNow === undefined ? { poolAccountId: accountId, transport: codexAccountFetch(accountId) } + : { poolAccountId: accountId, recoveryProbe: true, now: () => recoveryProbeNow, transport: codexAccountFetch(accountId) }); if (!admission) return { quota: existing ?? null, needsReauth: false, credentialGeneration: generation, quotaProbeSkipped: true }; if (admission.kind === "joined") return isCodexAccountGenerationLive(accountId, generation) && quotaProbeEvidence.mayPublish?.() !== false @@ -598,6 +599,7 @@ export async function fetchPoolAccountQuota( await warmCodexAccount({ accessToken: sourceToken?.accessToken ?? record.credential.accessToken, chatgptAccountId: sourceToken?.chatgptAccountId ?? record.credential.chatgptAccountId, + transport: codexAccountFetch(accountId), }); markCodexAccountValidated(accountId, Date.now(), generation); clearAccountNeedsReauth(accountId, generation); diff --git a/src/codex/auth-api/reset-credit-service.ts b/src/codex/auth-api/reset-credit-service.ts index 23ff21da88d..d2a89d1f341 100644 --- a/src/codex/auth-api/reset-credit-service.ts +++ b/src/codex/auth-api/reset-credit-service.ts @@ -1,3 +1,4 @@ +import { codexAccountFetch } from "../account-egress-runtime"; import { codexAccountUsesCreditsAfterLimit } from "../account-credit-use"; import { getValidCodexToken, isCodexAccountGenerationLive, readCodexAccountRecord, CodexCredentialGenerationConflictError } from "../account-store"; import { isCompleteCodexQuotaRecoverySnapshot } from "../quota"; @@ -149,7 +150,7 @@ export function createResetCreditWhamClient(config: OcxConfig, accountId: string }; return { inspect: () => run(async auth => { - const resp = await fetch("https://chatgpt.com/backend-api/wham/rate-limit-reset-credits", { + const resp = await codexAccountFetch(auth.isMain ? null : accountId)("https://chatgpt.com/backend-api/wham/rate-limit-reset-credits", { headers: { Authorization: `Bearer ${auth.accessToken}`, "ChatGPT-Account-Id": auth.chatgptAccountId }, signal: AbortSignal.timeout(8000), }); @@ -169,7 +170,7 @@ export function createResetCreditWhamClient(config: OcxConfig, accountId: string }) }; }), consume: redeemRequestId => run(async auth => { - const resp = await fetch("https://chatgpt.com/backend-api/wham/rate-limit-reset-credits/consume", { + const resp = await codexAccountFetch(auth.isMain ? null : accountId)("https://chatgpt.com/backend-api/wham/rate-limit-reset-credits/consume", { method: "POST", headers: { Authorization: `Bearer ${auth.accessToken}`, @@ -301,7 +302,7 @@ export async function inspectResetCredits(config: OcxConfig, accountId: string, try { let resp: Response; try { - resp = await fetch( + resp = await codexAccountFetch(auth.isMain ? null : accountId)( "https://chatgpt.com/backend-api/wham/rate-limit-reset-credits", { headers: { @@ -388,7 +389,7 @@ export async function consumeResetCredits(config: OcxConfig, accountId: string, try { let resp: Response; try { - resp = await fetch( + resp = await codexAccountFetch(auth.isMain ? null : accountId)( "https://chatgpt.com/backend-api/wham/rate-limit-reset-credits/consume", { method: "POST", diff --git a/src/codex/model-entitlements.ts b/src/codex/model-entitlements.ts index fc8e600c894..a43e10ef7a9 100644 --- a/src/codex/model-entitlements.ts +++ b/src/codex/model-entitlements.ts @@ -1,3 +1,4 @@ +import { codexAccountFetch } from "./account-egress-runtime"; import { createHash } from "node:crypto"; import { readBoundedResponseBody } from "../lib/bounded-body"; import type { CodexAccountCredentialRecord, OcxConfig } from "../types"; @@ -787,7 +788,8 @@ async function fetchAccountModels( Accept: "application/json", }); if (credential.chatgptAccountId) headers.set("ChatGPT-Account-Id", credential.chatgptAccountId); - const response = await fetcher(codexModelsUrl(clientVersion), { + // A direct caller's own bearer is not a pool credential and keeps the process-wide route. + const response = await codexAccountFetch(credential.accountId.startsWith(DIRECT_CALLER_ACCOUNT_PREFIX) ? null : credential.accountId, { base: fetcher })(codexModelsUrl(clientVersion), { headers, redirect: "error", signal: controller.signal, @@ -941,7 +943,7 @@ async function fetchDiscoveryRoster( const now = options.now ?? Date.now(); const cached = discoveryEtags.get(credential.credentialIdentity); if (cached && now - cached.fetchedAt < DISCOVERY_ETAG_MAX_AGE_MS) headers.set("If-None-Match", cached.etag); - const response = await fetcher(codexModelsUrl(CODEX_ROSTER_DISCOVERY_CLIENT_VERSION), { + const response = await codexAccountFetch(credential.accountId.startsWith(DIRECT_CALLER_ACCOUNT_PREFIX) ? null : credential.accountId, { base: fetcher })(codexModelsUrl(CODEX_ROSTER_DISCOVERY_CLIENT_VERSION), { headers, redirect: "error", signal: controller.signal, diff --git a/src/codex/quota-auto-refresh.ts b/src/codex/quota-auto-refresh.ts index 42fa040ee53..5bc8077d376 100644 --- a/src/codex/quota-auto-refresh.ts +++ b/src/codex/quota-auto-refresh.ts @@ -18,6 +18,7 @@ import { resolveNativeProfileContext } from "./native-profile-store"; import { getMainQuotaCredentialGeneration, observeMainQuotaCredential } from "./main-account-cache"; import { applyAccountQuotaFromUpstreamHeaders, getAccountQuota, type StoredAccountQuota } from "./quota"; import { CodexWarmupError, codexWarmupFailureReason, warmCodexAccount } from "./warmup"; +import { codexAccountFetch } from "./account-egress-runtime"; import { completedByAccount, retryAfterByAccount, scheduledByAccount, quotaRefreshAfterByAccount, resetCodexQuotaAutoRefreshStateForTests, @@ -224,7 +225,7 @@ async function warmAccount(config: OcxConfig, accountId: string): Promise { + await warmCodexAccount({ ...token, transport: codexAccountFetch(accountId), onCompleted: headers => { if (isCodexAccountGenerationLive(accountId, token.generation)) { applyAccountQuotaFromUpstreamHeaders(accountId, headers, writerGeneration, undefined, { poolWriter, poolResponse: true }); } diff --git a/src/codex/quota-query-backoff.ts b/src/codex/quota-query-backoff.ts index ee2b9d46a62..014cb9c4dcd 100644 --- a/src/codex/quota-query-backoff.ts +++ b/src/codex/quota-query-backoff.ts @@ -44,6 +44,8 @@ export interface CodexUsageSchedule { recoveryProbe?: true; /** The sweep's clock also drives its quota-query deadline. */ now?: () => number; + /** The account's own route for this credentialed read (`codexAccountFetch`); absent uses the global fetch. */ + transport?: typeof globalThis.fetch; } /** Removal invalidates even active reads, so their late settlements cannot restore pacing. */ @@ -68,7 +70,7 @@ export async function fetchCodexUsage( ): Promise | null> { if (schedule.unpaced) { onDispatch?.(); - const response = await fetch("https://chatgpt.com/backend-api/wham/usage", init); + const response = await (schedule.transport ?? fetch)("https://chatgpt.com/backend-api/wham/usage", init); return { kind: "owner", response, settle: () => {} }; } const pacingKey = scopedKey(schedule.pacingKey ?? baseQueryKey(key)); @@ -134,7 +136,7 @@ export async function fetchCodexUsage( }; try { onDispatch?.(); - response = await fetch("https://chatgpt.com/backend-api/wham/usage", init); + response = await (schedule.transport ?? fetch)("https://chatgpt.com/backend-api/wham/usage", init); return { kind: "owner", response, settle }; } catch (error) { settle(false); diff --git a/src/codex/warmup.ts b/src/codex/warmup.ts index a8ae8c7af5f..228c89bfd16 100644 --- a/src/codex/warmup.ts +++ b/src/codex/warmup.ts @@ -24,6 +24,8 @@ export interface CodexWarmupOptions { timeoutMs?: number; /** Publish quota headers only after a completed inference, never on a failed stream. */ onCompleted?: (headers: Headers) => void; + /** A pool account's route for this credentialed send (`codexAccountFetch`); absent uses the global fetch. */ + transport?: typeof globalThis.fetch; } const CODEX_RESPONSES_URL = "https://chatgpt.com/backend-api/codex/responses"; @@ -247,7 +249,7 @@ async function tryWarmup(options: CodexWarmupOptions, model: string): Promise(); +// Config paths whose most recent load fell back to defaults (an unreadable file); a later load or +// save that records the path as file-backed clears it. +const fallbackConfigPaths = new Set(); export function recordFileBackedConfig(config: OcxConfig, path: string): OcxConfig { fileBackedConfigs.set(config, path); + fallbackConfigPaths.delete(path); return config; } +export function recordConfigLoadFallback(path: string): void { + fallbackConfigPaths.add(path); +} + +export function configLoadFellBack(path: string): boolean { + return fallbackConfigPaths.has(path); +} + export function fileBackedConfigPath(config: OcxConfig): string | undefined { return fileBackedConfigs.get(config); } diff --git a/src/config/salvage.ts b/src/config/salvage.ts index 13a1cab8db8..34c70beddee 100644 --- a/src/config/salvage.ts +++ b/src/config/salvage.ts @@ -5,6 +5,7 @@ import { CODEX_ACCOUNT_NAMESPACE_COMBO_ALIAS_COLLISION_ERROR } from "../codex/ac import { redactSecretString } from "../lib/redact"; import { isPassiveRead } from "../lib/passive-read"; import { hasWarnedConfigFallback, markWarnedConfigFallback } from "./warn-memo"; +import { recordConfigLoadFallback } from "./rebase-provenance"; import { configSchema } from "./schema/config-schema"; import type { OcxConfig } from "../types"; @@ -224,6 +225,7 @@ export function warnDroppedConfigSections(configPath: string, dropped: string[], } export function warnAndBackupInvalidConfig(configPath: string, error: unknown): void { + recordConfigLoadFallback(configPath); if (hasWarnedConfigFallback(configPath)) return; markWarnedConfigFallback(configPath); diff --git a/src/config/schema/config-schema.ts b/src/config/schema/config-schema.ts index 4fc23938db7..591a569c705 100644 --- a/src/config/schema/config-schema.ts +++ b/src/config/schema/config-schema.ts @@ -1,3 +1,4 @@ +import { poolAccountEgressConfigError } from "../../lib/provider-egress"; import { dashboardTrustedProxySchema } from "../dashboard-trusted-proxy"; import { MAIN_ACCOUNT_HARD_LOCK_MIN_PERCENT } from "../../codex/quota-types"; import { validRemainingQuotaAccountIds } from "../../codex/account-use-remaining"; @@ -534,6 +535,12 @@ export const configSchema = z.object({ } } + // A pool account's own route follows the provider egress rules (src/lib/provider-egress.ts). + if (Array.isArray(config.codexAccounts)) config.codexAccounts.forEach((account: unknown, index: number) => { + const { id, egress } = (account ?? {}) as { id?: unknown; egress?: unknown }; + const error = poolAccountEgressConfigError(`codexAccounts.${typeof id === "string" ? id : index}.egress`, egress); + if (error) ctx.addIssue({ code: "custom", path: ["codexAccounts", index, "egress"], message: error }); + }); const accountNamespaces = config.codexAccountNamespaces; if (accountNamespaces) { const configuredAccountIds = configuredCodexPoolAccountIds(config.codexAccounts); diff --git a/src/lib/provider-egress.ts b/src/lib/provider-egress.ts index 0ee65652f3a..39146cfe00b 100644 --- a/src/lib/provider-egress.ts +++ b/src/lib/provider-egress.ts @@ -26,6 +26,7 @@ * therefore a configuration error naming both real alternatives. */ import type { OcxProviderConfig } from "../types"; +import type { PoolAccountEgress } from "../types/pool-account"; import { explicitProxyExemptedError, isSocks5ProxyUrl, noProxyMatches, processNoProxyExempts } from "./proxy-env"; export class InvalidProviderEgressError extends Error { @@ -49,14 +50,24 @@ export type ProviderEgress = | { kind: "direct"; reason: "configured" | "noProxy" } | { kind: "proxy"; proxyUrl: string; transport: "http" | "socks5" }; +/** The selected pool account's own route, with the config path that names it in errors. */ +export interface PoolAccountRoute { + id: string; + /** Config path of the egress object, e.g. `codexAccounts..egress`. */ + scope: string; + egress?: PoolAccountEgress; +} + export interface ProviderEgressContext { providerName: string; provider: Pick; url: string | URL; + /** The pool account serving this request; its route outranks the provider's. */ + account?: PoolAccountRoute; } -function egressFailure(providerName: string, field: "proxy" | "noProxy", reason: string): never { - throw new InvalidProviderEgressError(field, reason, `providers.${providerName}.${field} is invalid: ${reason}`); +function egressFailure(providerName: string, field: "proxy" | "noProxy", reason: string, scope = `providers.${providerName}`): never { + throw new InvalidProviderEgressError(field, reason, `${scope}.${field} is invalid: ${reason}`); } /** @@ -93,23 +104,23 @@ function parseTargetUrl(providerName: string, url: string | URL): URL { } } -function normalizeNoProxy(providerName: string, raw: string | string[] | undefined): string | null { +function normalizeNoProxy(providerName: string, raw: string | string[] | undefined, scope?: string): string | null { if (raw === undefined) return null; const entries = Array.isArray(raw) ? raw : [raw]; for (const entry of entries) { if (typeof entry !== "string") { - return egressFailure(providerName, "noProxy", "every entry must be a string host pattern"); + return egressFailure(providerName, "noProxy", "every entry must be a string host pattern", scope); } } const joined = entries.join(",").trim(); return joined.length > 0 ? joined : null; } -function parseProviderProxyRoute(providerName: string, raw: string): ProviderEgress { +function parseProviderProxyRoute(providerName: string, raw: string, scope?: string): ProviderEgress { + const egressFailureScoped = (field: "proxy" | "noProxy", reason: string): never => egressFailure(providerName, field, reason, scope); const trimmed = raw.trim(); if (trimmed.length === 0) { - return egressFailure( - providerName, + return egressFailureScoped( "proxy", `an empty value is ambiguous; write "${PROVIDER_EGRESS_DIRECT}" to force direct egress, or remove the field to inherit the global proxy`, ); @@ -119,27 +130,25 @@ function parseProviderProxyRoute(providerName: string, raw: string): ProviderEgr try { parsed = new URL(trimmed); } catch { - return egressFailure( - providerName, + return egressFailureScoped( "proxy", `"${PROVIDER_EGRESS_DIRECT}" or an absolute proxy URL is required; this value is neither`, ); } if (isSocks5ProxyUrl(trimmed)) { if (!parsed.hostname) { - return egressFailure(providerName, "proxy", "the SOCKS5 proxy URL has no host"); + return egressFailureScoped("proxy", "the SOCKS5 proxy URL has no host"); } return { kind: "proxy", proxyUrl: trimmed, transport: "socks5" }; } if (parsed.protocol !== "http:" && parsed.protocol !== "https:") { - return egressFailure( - providerName, + return egressFailureScoped( "proxy", `unsupported proxy scheme "${parsed.protocol}"; supported schemes are http, https, socks5 and socks5h`, ); } if (!parsed.hostname) { - return egressFailure(providerName, "proxy", "the proxy URL has no host"); + return egressFailureScoped("proxy", "the proxy URL has no host"); } return { kind: "proxy", proxyUrl: parsed.toString(), transport: "http" }; } @@ -158,19 +167,26 @@ function parseProviderProxyRoute(providerName: string, raw: string): ProviderEgr * proxy — which is how a provider exempts one host without owning a proxy of its own. */ export function resolveProviderEgress(context: ProviderEgressContext): ProviderEgress { - const { providerName, provider } = context; - const raw = provider.proxy; + const { providerName, provider, account } = context; + // An account that names its own proxy replaces the provider's; one that does not inherits it. + const accountProxy = account?.egress?.proxy; + const scope = accountProxy !== undefined ? account!.scope : undefined; + const raw = accountProxy !== undefined ? accountProxy : provider.proxy; let route: ProviderEgress; if (raw === undefined) { route = { kind: "inherit" }; } else if (raw === null) { route = { kind: "direct", reason: "configured" }; } else if (typeof raw !== "string") { - return egressFailure(providerName, "proxy", "the value must be a proxy URL string, \"direct\", null, or absent"); + return egressFailure(providerName, "proxy", "the value must be a proxy URL string, \"direct\", null, or absent", scope); } else { - route = parseProviderProxyRoute(providerName, raw); + route = parseProviderProxyRoute(providerName, raw, scope); } - const noProxy = normalizeNoProxy(providerName, provider.noProxy); + // The account's bypass list comes first and the provider's still applies. + const noProxy = [ + normalizeNoProxy(providerName, account?.egress?.noProxy, account?.scope), + normalizeNoProxy(providerName, provider.noProxy), + ].filter((value): value is string => value !== null).join(",") || null; if (noProxy !== null) { const target = parseTargetUrl(providerName, context.url); if (noProxyMatches(target, { NO_PROXY: noProxy })) return { kind: "direct", reason: "noProxy" }; @@ -260,6 +276,8 @@ export function egressTargetUrl(input: string | URL | Request): string | null { export interface ProviderEgressBinding { providerName: string; provider: Pick; + /** Read at each physical send, so a request moved to another pool account follows that account. */ + account?: () => PoolAccountRoute | undefined; } /** @@ -282,7 +300,7 @@ export function providerEgressSendInit( ): { proxy?: string | false } { const url = egressTargetUrl(input); if (url === null) return {}; - const egress = resolveProviderEgress({ providerName: binding.providerName, provider: binding.provider, url }); + const egress = resolveProviderEgress({ providerName: binding.providerName, provider: binding.provider, url, account: binding.account?.() }); // An HTTP(S) proxy route toward a destination the process NO_PROXY exempts would leave without the // proxy. Decided against the destination actually sent, before the dispatch receipt and before // any byte leaves; `providerFetch` also asks early, before `beforeDispatch`, when nothing can still @@ -325,6 +343,22 @@ const EGRESS_VALIDATION_URL = "https://validation.invalid/"; * one rejected here is rejected there for the identical reason. Restating the rules would give * this repository two definitions of a valid proxy value and no check that they agree. */ +/** The configuration error for a pool account's egress object, or null when it is usable. */ +export function poolAccountEgressConfigError(scope: string, egress: unknown): string | null { + if (egress === undefined) return null; + if (!egress || typeof egress !== "object" || Array.isArray(egress)) return `${scope} must be an object with optional proxy and noProxy`; + const { proxy, noProxy, ...rest } = egress as PoolAccountEgress & Record; + if (Object.keys(rest).length > 0) return `${scope} accepts only proxy and noProxy`; + try { + resolveProviderEgress({ providerName: "", provider: {}, url: EGRESS_VALIDATION_URL, + account: { id: "", scope, egress: { proxy, noProxy } } }); + return null; + } catch (error) { + if (error instanceof InvalidProviderEgressError) return error.message; + throw error; + } +} + export function providerEgressConfigError( provider: Pick, ): string | null { diff --git a/src/oauth/token-guardian.ts b/src/oauth/token-guardian.ts index 886dcf2aad4..fc63d02357e 100644 --- a/src/oauth/token-guardian.ts +++ b/src/oauth/token-guardian.ts @@ -26,6 +26,7 @@ import { CodexCredentialRefreshStaleError, } from "../codex/account-store"; import { codexWarmupFailureReason, warmCodexAccount } from "../codex/warmup"; +import { codexAccountFetch } from "../codex/account-egress-runtime"; import { getMainAccountToken, MAIN_CODEX_ACCOUNT_ID } from "../codex/main-account"; import { isCanonicalOpenAiForwardProvider, OPENAI_CODEX_PROVIDER_ID } from "../providers/openai-tiers"; import { providerCodexAccountMode } from "../providers/registry"; @@ -246,6 +247,7 @@ export async function guardianSweep(nowMs: number = Date.now()): Promise resolveLowQuotaDesktopSink() }), + egressBinding, }; try { if (!processLoops) { @@ -302,6 +317,9 @@ export function acquireServerBackgroundLifecycle( } catch (error) { owner.lowQuota(); owner.resources.release(); + const survivor = owners.at(-1); + if (survivor) restoreCodexAccountEgressBinding(survivor.egressBinding); + else unbindCodexAccountEgressConfig(config); if (owners.length === 0) uninstallApiKeyCooldownPersistence({ dropLocalHolds: true }); throw error; } diff --git a/src/server/responses/compact.ts b/src/server/responses/compact.ts index 88be963b493..0c312198313 100644 --- a/src/server/responses/compact.ts +++ b/src/server/responses/compact.ts @@ -238,7 +238,7 @@ import { } from "./core"; import { fetchWithHeaderTimeout, providerFetch, safeHostLabel, safeOriginLabel, sendWithConnectionPolicy } from "./fetch-helpers"; import { requestPacingOverloadResponse } from "./pacing-overload"; -import { shouldRetryCodexPoolAccountQuota, shouldRetryCodexPoolAccountTransient } from "./core-codex-account"; +import { codexPoolAccountEgressRoute, shouldRetryCodexPoolAccountQuota, shouldRetryCodexPoolAccountTransient } from "./core-codex-account"; import { mapCodexAuthContextErrorToResponse, nativeMainRefreshFailureResponse } from "./codex-auth-error"; import { affinityLaneFromRequest, linkRequestSessionLane, reasoningReplayConversationIdFromResponsesRequest, sessionIdHeaderFromRequest, sessionLaneIdFromRequest } from "../request-log-conversation"; import { recallComboForLane } from "./combo-session-recall"; @@ -1240,7 +1240,7 @@ export async function handleResponsesCompact( sendProvider.authMode !== "forward" && sendProvider.apiKey ? 0 : connectMs(), false, providerFetch(sendProvider, undefined, { - providerName: route.providerName, + providerName: route.providerName, account: () => codexPoolAccountEgressRoute(config, sendAuthCtx), modelId: route.modelId, accountAutoPause: (name, provider, headers) => captureAccountAutoPauseAttempt(name, provider, { config, codex: sendAuthCtx }, headers), beforeDispatch: isCanonicalOpenAiForwardProvider(sendProvider) diff --git a/src/server/responses/core-codex-account.ts b/src/server/responses/core-codex-account.ts index f93e2c17185..777f81f6c8b 100644 --- a/src/server/responses/core-codex-account.ts +++ b/src/server/responses/core-codex-account.ts @@ -1,3 +1,4 @@ +import { codexAccountEgressRoute } from "../../codex/account-egress"; import { conversationStateAccountId, releaseRequestOwnedMainOnOutcome, isKeyedRequestOwnedMain } from "../../codex/request-owned-affinity"; import { CodexInstallationIdUnavailableError } from "../../codex/installation-id"; import { captureAccountAutoPauseAttempt, wasPermanentAccountRefusal } from "../../oauth/account-auto-pause"; @@ -122,6 +123,10 @@ export function codexLogAccountId(authCtx: CodexAuthContext): string | null { return authCtx.kind === "pool" || authCtx.kind === "main-pool" ? authCtx.accountId : null; } +/** The route of the pool account this auth context sends with (`codexAccounts[].egress`), if it has one. */ +export function codexPoolAccountEgressRoute(config: OcxConfig, authCtx: CodexAuthContext) { + return codexAccountEgressRoute(config, codexLogAccountId(authCtx)); +} export function isFixedCodexAccount(authCtx: CodexAuthContext): boolean { return (authCtx.kind === "pool" || authCtx.kind === "main-pool") @@ -1085,7 +1090,7 @@ export async function retryCodexPoolOnAlternateAccount( upstream.signal, connectMs, stream, - providerFetch(retryProvider, options.codexWsRuntimeIdentity, { + providerFetch(retryProvider, options.codexWsRuntimeIdentity, { account: () => codexPoolAccountEgressRoute(config, retryAuthCtx), httpOnly, providerName: route.providerName, modelId: route.modelId, diff --git a/src/server/responses/fetch-helpers.ts b/src/server/responses/fetch-helpers.ts index 8a8fc4160f7..f591de22139 100644 --- a/src/server/responses/fetch-helpers.ts +++ b/src/server/responses/fetch-helpers.ts @@ -33,6 +33,7 @@ import { providerEgressSendInit, providerEgressIsExplicit, resolveProviderEgress, + type PoolAccountRoute, type ProviderEgressBinding, } from "../../lib/provider-egress"; import { redactSecretString } from "../../lib/redact"; @@ -341,6 +342,11 @@ export interface ProviderFetchOptions { * incremental prefixes are scoped to it; absent means no caller may continue a prefix. */ codexWsCaller?: string; + /** + * The pool account serving this request, read at each physical send (and for the WebSocket + * route decision), so a request that failover moves to another account takes that account's route. + */ + account?: () => PoolAccountRoute | undefined; /** Revalidate/rebuild a queued request at its physical send boundary, after pacing. */ dispatchOverride?: (input: Parameters[0], init: RequestInit, execute: typeof globalThis.fetch, reacquirePacing?: (provider: OcxProviderConfig, modelId?: string) => Promise) => Promise; @@ -356,7 +362,7 @@ export function providerFetch( const customExecutor = (provider as OcxProviderConfig & { fetch?: typeof globalThis.fetch }).fetch; // The route is applied at the physical send (see `sendWithConnectionPolicy`). This binding is // only what that boundary needs to decide it. - const egressBinding: ProviderEgressBinding = { providerName, provider }; + const egressBinding: ProviderEgressBinding = { providerName, provider, ...(options.account ? { account: options.account } : {}) }; // Resolved per request, not once per wrapper: `providers..noProxy` is evaluated against // the destination, so two requests through the same executor can legitimately take different // routes. A malformed value throws and rejects the request rather than degrading to the @@ -365,6 +371,7 @@ export function providerFetch( providerName, provider, url: typeof input === "string" ? input : input instanceof URL ? input : input.url, + account: options.account?.(), }); // The built-in executor forwards its init to a transport that honours the proxy option. const configuredFetch = markEgressTransparentExecutor(Object.assign( diff --git a/src/server/responses/passthrough-dispatch.ts b/src/server/responses/passthrough-dispatch.ts index 964db93a881..539156810e3 100644 --- a/src/server/responses/passthrough-dispatch.ts +++ b/src/server/responses/passthrough-dispatch.ts @@ -114,6 +114,7 @@ import { retryCodexPoolOnAlternateAccount, PoolPreOutputRefusals, subscriptionPreOutputRefusalHold, + codexPoolAccountEgressRoute, } from "./core-codex-account"; import { codexAuthContextLogLabel } from "../../codex/account-label"; import { @@ -269,6 +270,8 @@ export async function preparePassthroughExchange( >, ) { const { config, logCtx, options, req } = requestContext; + // Read at each physical send: failover may move this request to another pool account. + const accountRoute = () => codexPoolAccountEgressRoute(config, admissionState.authCtx); const codexWsCaller = codexWsAdmittedCaller(options.replayPrincipal, () => resolveContextPrincipal(req, config, options.admission)); const { route, @@ -817,7 +820,7 @@ export async function preparePassthroughExchange( signal, sendConnectMs(), true, - providerFetch(route.provider, options.codexWsRuntimeIdentity, { + providerFetch(route.provider, options.codexWsRuntimeIdentity, { account: accountRoute, httpOnly: true, providerName: route.providerName, modelId: route.modelId, @@ -1011,7 +1014,7 @@ export async function preparePassthroughExchange( headers: request.headers, body: request.body, }, recovery), upstream.signal, sendConnectMs(), upstreamRequestsStream, - providerFetch(route.provider, options.codexWsRuntimeIdentity, { + providerFetch(route.provider, options.codexWsRuntimeIdentity, { account: accountRoute, httpOnly: canonicalBufferedJson, codexWsCaller, captureCodexWsRecovery: capturePhysicalSendRecovery, onRecoveryPhysicalDispatch: recordPhysicalSend(), nativeControl: nativeResponseControlEligible(route.provider, options.nativeControl) && options.inboundTransport === "websocket" && !options.comboAttempt && responseEffects.plaintextV2AgentMessageToolNames.size === 0 @@ -1092,7 +1095,7 @@ export async function preparePassthroughExchange( recovery => fetchWithHeaderTimeout(request.url, applyUpstreamRecoveryInit({ method: request.method, headers: request.headers, body: request.body, }, recovery), upstream.signal, sendConnectMs(), upstreamRequestsStream, - providerFetch(route.provider, options.codexWsRuntimeIdentity, { + providerFetch(route.provider, options.codexWsRuntimeIdentity, { account: accountRoute, httpOnly: canonicalBufferedJson, codexWsCaller, captureCodexWsRecovery: capturePhysicalSendRecovery, onRecoveryPhysicalDispatch: recordPhysicalSend(() => commit(request, adapter)), nativeControl: nativeResponseControlEligible(route.provider, options.nativeControl) && options.inboundTransport === "websocket" && !options.comboAttempt && responseEffects.plaintextV2AgentMessageToolNames.size === 0 ? options.nativeControl : undefined, @@ -1186,7 +1189,7 @@ export async function preparePassthroughExchange( headers: request.headers, body: request.body, }, innerRecovery), upstream.signal, sendConnectMs(), upstreamRequestsStream, - providerFetch(route.provider, options.codexWsRuntimeIdentity, { + providerFetch(route.provider, options.codexWsRuntimeIdentity, { account: accountRoute, httpOnly: canonicalBufferedJson, codexWsCaller, captureCodexWsRecovery: capturePhysicalSendRecovery, onRecoveryPhysicalDispatch: recordPhysicalSend(), nativeControl: nativeResponseControlEligible(route.provider, options.nativeControl) && options.inboundTransport === "websocket" && !options.comboAttempt && responseEffects.plaintextV2AgentMessageToolNames.size === 0 @@ -1556,7 +1559,7 @@ export async function preparePassthroughExchange( headers: request.headers, body: request.body, }, recovery), upstream.signal, sendConnectMs(), upstreamRequestsStream, - providerFetch(route.provider, options.codexWsRuntimeIdentity, { + providerFetch(route.provider, options.codexWsRuntimeIdentity, { account: accountRoute, httpOnly: canonicalBufferedJson, codexWsCaller, captureCodexWsRecovery: capturePhysicalSendRecovery, onRecoveryPhysicalDispatch: recordPhysicalSend(), nativeControl: nativeResponseControlEligible(route.provider, options.nativeControl) && options.inboundTransport === "websocket" && !options.comboAttempt && responseEffects.plaintextV2AgentMessageToolNames.size === 0 diff --git a/src/types/accounts.ts b/src/types/accounts.ts index fbd19df8b04..cdbce93c995 100644 --- a/src/types/accounts.ts +++ b/src/types/accounts.ts @@ -16,6 +16,8 @@ export interface CodexAccount { chatgptAccountId?: string; logLabel?: string; isMain: boolean; + /** This account's own upstream route (proxy / noProxy); absent uses the provider's. */ + egress?: import("./pool-account").PoolAccountEgress; } export interface CodexAccountCredentials { diff --git a/src/types/pool-account.ts b/src/types/pool-account.ts new file mode 100644 index 00000000000..1716f492447 --- /dev/null +++ b/src/types/pool-account.ts @@ -0,0 +1,12 @@ +/** + * Per-account egress for a pool account (`codexAccounts[].egress`). + * + * The values follow the same rules as `providers..proxy` and `noProxy`: `proxy` absent inherits the + * provider's route, `"direct"` or `null` connects directly, an http(s) or socks5(h) URL selects a proxy for + * this account; `noProxy` entries send matching destinations directly and are merged ahead of the + * provider's own list. Resolved per request by `src/lib/provider-egress.ts`. + */ +export interface PoolAccountEgress { + proxy?: string | null; + noProxy?: string | string[]; +} diff --git a/structure/config.md b/structure/config.md index a6b924fd154..3047e56947d 100644 --- a/structure/config.md +++ b/structure/config.md @@ -104,7 +104,7 @@ A schema-invalid top-level JSON value is repairable only when it is a non-array | Spend | `spend.root`, `spend.identity`, `spend.pool`, `spend.retentionDays`, top-level `spendPoolAliases` | Durable token ceilings for the spend-reservation ledger. Absent is the default and means observe-only accounting: spend is still journaled and nothing is refused, so observe-only and enforced servers take the same state-directory writer lease. One live process may write one directory; explicit sibling instances need separate `OPENCODEX_HOME` directories. There is no default figure for any scope — the ledger is on by default, so a shipped ceiling would refuse real traffic on upgrade against a number nobody chose. Strictly validated and positive-integer only, because 0 would read as a budget and refuse everything; a malformed section degrades to no ceiling, which is why the write path rejects it and load diagnostics report it. Top-level `spendPoolAliases` is preserved verbatim on load; malformed mappings leave ceilings intact and refuse pool admission, while candidate writes reject them. Current provider IDs automatically own their ordinary salted pool buckets at read time; other historical labels need explicit mappings or remain conservatively unbound. Neither self-bindings nor explicit mappings persist as journal links. Padded destinations and destinations absent from the provider roster are rejected on write and warn/refuse pool admission on load. `src/lib/spend-pool-alias-validation.ts` checks the existing home salt without creating it and rejects a configured provider’s own pool alias mapped to a different provider, including when providers are added later. Live provider and full-config adoption call `reconcileLiveStateStores` in `src/lib/state-store-registrations.ts` to refresh this policy from the active roster; detached config reads do not change it. It stays outside the legacy strict `spend` object. Resolution and application live in `src/lib/spend-reservation-ledger.ts`; see [historical continuity and rollback](transports/responses-spend.md#historical-pool-continuity-and-rollback). | | Transport | stream mode, timeouts, proxy settings, `websockets`, `linkResponsesWebsocket` (the [link WebSocket](remote-link.md#responses-websocket-over-the-link), which also needs `websockets`), `linkResponsesWebsocketOptOut` (on a Child: `true` keeps Codex on HTTP over the link whatever the Home offers; read once when the Child's listener starts), `emptyCompletionRetry` | `streamMode` persists in config.json; Windows services need a persisted input, and macOS uses it for explicit eager-relay opt-in. Empty-completion replay is an explicit top-level opt-in because its second upstream request may be billable. | | Canonical ChatGPT upstream transport and Lite history | `providers.openai.upstreamWebsocket`, per-provider `projectResponsesLiteHostedSearchHistory` | Omitted `upstreamWebsocket` uses upstream WebSocket when eligible; explicit `false` selects HTTP/SSE without changing the canonical provider identity. `true` is rejected on the canonical row. This is independent of the client-facing `websockets` setting. `src/config/schema/leaf-validators.ts` validates `projectResponsesLiteHostedSearchHistory` as an optional strict boolean, default off; only runtime `=== true` enables the ordinary lossy policy, still limited by the exact destination and explicit Lite [hosted-search history boundary](providers-and-adapters.md#hosted-search-continuation-binding). `src/providers/model-rename-fields.ts` classifies it as provider-wide policy with no model-ID rewrite role. | -| Provider egress | `providers..proxy`, `providers..noProxy` | An absent `proxy` inherits global egress; `"direct"` or `null` forces direct egress; HTTP(S) and SOCKS5(H) URLs select a provider-owned proxy. `noProxy` uses NO_PROXY syntax and sends a matching destination direct across either a provider-owned or inherited global proxy. `src/lib/provider-egress.ts` owns parsing and request-local resolution. `forwardClientHeaders` opts into `originator`, `x-client-request-id`, `x-codex-app-version`, `user-agent`, `x-codex-window-id`, or `x-codex-installation-id` on Responses inference only; provider headers win and all other names are rejected on load/write and filtered at runtime. | +| Provider egress | `providers..proxy`, `providers..noProxy` | An absent `proxy` inherits global egress; `"direct"` or `null` forces direct egress; HTTP(S) and SOCKS5(H) URLs select a provider-owned proxy. `noProxy` uses NO_PROXY syntax and sends a matching destination direct across either a provider-owned or inherited global proxy. `src/lib/provider-egress.ts` owns parsing and request-local resolution; a Codex pool account's optional `codexAccounts[].egress` (`src/types/pool-account.ts`, validated by `poolAccountEgressConfigError`) outranks the provider's `proxy` and adds its `noProxy` ahead of the provider's. `forwardClientHeaders` opts into `originator`, `x-client-request-id`, `x-codex-app-version`, `user-agent`, `x-codex-window-id`, or `x-codex-installation-id` on Responses inference only; provider headers win and all other names are rejected on load/write and filtered at runtime. | | Credentials | `apiKeys` | Data-plane only; never admitted to `/api/*`. | | Lifecycle | `codexAutoStart`, shim/start behavior, resume-history sync, storage cleanup | Startup safety reads these; see [`gui-and-management-api.md`](gui-and-management-api.md). | diff --git a/structure/transports/inventory.md b/structure/transports/inventory.md index b62c444bc19..0b21c1363f2 100644 --- a/structure/transports/inventory.md +++ b/structure/transports/inventory.md @@ -212,6 +212,8 @@ Bun would apply the bypass list to the next hop; callers that handle redirects p | Request path | Per-provider route | Current contract | | --- | --- | --- | | Main routed inference through `providerFetch` in `src/server/responses/fetch-helpers.ts` | Honoured | Applied at the physical send in `sendWithConnectionPolicy`, so a request rebuilt against a different destination or a reselected provider transport resolves its route against the destination actually used. The built-in executor passes direct, HTTP(S)-proxy, and SOCKS5(H)-proxy choices through `configuredOutboundFetch` in `src/lib/proxy-env.ts`; an inherited route leaves the global decision unchanged. Native Chat in `src/server/chat-native.ts` and the Responses transport in `src/server/responses/request-transport.ts` bind their own sends. | +| Codex pool inference and native compact for an account with `codexAccounts[].egress` | Honoured | `providerFetch`'s `account` option (`codexAccountEgressRoute` over the current Codex auth context in `src/server/responses/passthrough-dispatch.ts`, `src/server/responses/compact.ts`, and the alternate-account retry in `src/server/responses/core-codex-account.ts`) is read at each physical send, so a request moved to another pool account takes that account's route. `tests/lib/provider-egress-account.test.ts` covers two accounts and a moved request on real loopback proxies; `tests/responses/codex-pool-account-egress-compact.test.ts` covers a compact moved by a 429 with a fake transport. | +| Codex pool token refresh, usage probes (initial and 401 replay), model discovery, reset-credit inspect/consume, warmups (token guardian, quota auto-refresh, deferred validation), and the login usage read and warmup | Honoured | `codexAccountFetch` in `src/codex/account-egress-runtime.ts` resolves the account's route over the `openai` provider's at each send, against the config the server binds for its background lifecycle (`src/server/background-lifecycle.ts`, detached on final release) or, without a binding for the current home, the loaded file. It refuses when that config is missing or could not be read, or a stored credential has no row (removed, even if cleanup failed, or orphaned); only a new login, whose row does not exist yet, takes the provider's route, and a direct caller's own bearer keeps the process-wide route. Each background-lifecycle owner carries its config, so a release restores the surviving owner's routes. Sends go through `configuredOutboundFetch`, so the explicit-proxy guards apply. `tests/lib/provider-egress-account-calls.test.ts` and `tests/codex-integration/codex-account-egress-background.test.ts` assert the route each call receives with a fake transport, plus the refusals; no real proxy is exercised for these vendor endpoints. | | Every caller of `providerOutboundGet` or `providerOutboundPost` in `src/lib/provider-outbound.ts` | Honoured | This includes provider discovery and model-catalog gathering in `src/codex/catalog/provider-models.ts`, management provider tests in `src/server/management/provider-routes.ts`, and the Ollama show probe in `src/providers/ollama-show.ts`. An optional caller authorization predicate is rechecked after DNS and immediately before each physical send, including injected executors and proxy fallback. | | API-key quota probes in `src/providers/quota/vendor-probes-key.ts` | Honoured | Each probe receives its provider config and sends through `configuredOutboundFetch` with the resolved route, so a quota reading and the inference it describes leave by the same exit. | | OAuth token exchange and refresh under `src/oauth/` | Not honoured | These reach fixed vendor endpoints from modules that hold no provider config, so no provider route is in scope at the call site. A provider pinned to its own proxy or to direct still refreshes credentials by the process-wide route. | diff --git a/tests/claude-integration/claude-bridge-pool-dispatch.test.ts b/tests/claude-integration/claude-bridge-pool-dispatch.test.ts index 5b900ee7fe9..c07173c8c50 100644 --- a/tests/claude-integration/claude-bridge-pool-dispatch.test.ts +++ b/tests/claude-integration/claude-bridge-pool-dispatch.test.ts @@ -1,4 +1,5 @@ import { afterEach, beforeEach, expect, spyOn, test } from "bun:test"; +import { bindStoredCodexPoolRoutingForTests } from "../helpers/codex-pool-routing"; import { mkdtempSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -47,6 +48,7 @@ beforeEach(() => { previous = process.env.OPENCODEX_HOME; home = mkdtempSync(join(tmpdir(), "ocx-bridge-pool-")); process.env.OPENCODEX_HOME = home; + bindStoredCodexPoolRoutingForTests(); isolated = installIsolatedCodexHome("ocx-bridge-codex-"); release = acquireOwnedSpendHome(); clearThreadAccountMap(); clearCodexUpstreamHealth(); clearAccountQuota(); clearCodexThreadLineageForTests(); clearConversationStateIssuerMap(); diff --git a/tests/codex-integration/codex-account-egress-background.test.ts b/tests/codex-integration/codex-account-egress-background.test.ts new file mode 100644 index 00000000000..da0f550aa9e --- /dev/null +++ b/tests/codex-integration/codex-account-egress-background.test.ts @@ -0,0 +1,304 @@ +/** + * A Codex pool account's background and login sends carry its credential, so they leave by its + * route (catch-up G-012): token-guardian and quota auto-refresh warmups, the reauthentication usage + * read and warmup, and a new login (no row yet) by the provider's route. A pool account removed while + * its credential is in hand, and a server whose config could not be read, refuse instead. + */ +import { afterEach, beforeEach, expect, spyOn, test } from "bun:test"; +import { mkdirSync, mkdtempSync, unlinkSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { + bindCodexAccountEgressConfig, + codexAccountFetch, + CodexAccountRouteUnavailableError, + resetCodexAccountEgressConfigForTests, + unbindCodexAccountEgressConfig, +} from "../../src/codex/account-egress-runtime"; +import { forceRefreshCodexPoolToken, getCodexAccountCredential, markCodexAccountValidated, readCodexAccountRecord, removeCodexAccountCredential, saveCodexAccountCredential } from "../../src/codex/account-store"; +import { handleCodexAuthLoginStart } from "../../src/codex/auth-api/login-flow"; +import { CODEX_LOGIN_TERMINAL_TTL_MS, codexAuthLoginState } from "../../src/codex/auth-api/login-state"; +import { inspectResetCredits } from "../../src/codex/auth-api/reset-credit-service"; +import { clearAccountQuota } from "../../src/codex/quota"; +import { resetCodexQuotaAutoRefreshForTests, runCodexQuotaAutoRefresh } from "../../src/codex/quota-auto-refresh"; +import { getConfigPath, loadConfig, saveConfig } from "../../src/config"; +import { flushConfigDirHardening } from "../../src/config/paths"; +import { clearLoginState, OAUTH_PROVIDERS, waitForLoginSettled } from "../../src/oauth"; +import { __resetGuardianState, guardianSweep } from "../../src/oauth/token-guardian"; +import { ACCOUNT_GATED_NATIVE_OPENAI_MODELS } from "../../src/codex/catalog/native-models"; +import { isDirectCallerEntitledToCodexModel, resetCodexModelEntitlementCacheForTests } from "../../src/codex/model-entitlements"; +import { acquireServerBackgroundLifecycle } from "../../src/server/background-lifecycle"; +import type { OcxConfig } from "../../src/types"; +import { removeTreeWithRetry } from "../helpers/remove-tree"; + +const PROVIDER_PROXY = "http://127.0.0.1:7/"; +const ACCOUNT_PROXY = "http://127.0.0.1:9/"; +const PROXY_ENV = ["NO_PROXY", "no_proxy", "HTTP_PROXY", "http_proxy", "HTTPS_PROXY", "https_proxy", "ALL_PROXY", "all_proxy"] as const; +const savedEnv = new Map(); +const homeKeys = ["OPENCODEX_HOME", "CODEX_HOME"] as const; +const realFetch = globalThis.fetch; +let previousHomes: Array = []; +let home = ""; +let calls: Array<{ url: string; proxy: unknown }> = []; + +function config(extra: Partial = {}): OcxConfig { + return { + port: 0, defaultProvider: "openai", + providers: { openai: { adapter: "openai-responses", baseUrl: "https://chatgpt.com/backend-api/codex", authMode: "forward", + codexAccountMode: "pool", refreshPolicy: "proactive", proxy: PROVIDER_PROXY } }, + codexAccounts: [{ id: "routed", email: "routed@example.test", plan: "plus", isMain: false, egress: { proxy: ACCOUNT_PROXY } }], + ...extra, + } as OcxConfig; +} + +const completed = () => new Response('event: response.completed\ndata: {"type":"response.completed"}\n\n', { + status: 200, headers: { "content-type": "text/event-stream" }, +}); + +beforeEach(() => { + for (const key of PROXY_ENV) { savedEnv.set(key, process.env[key]); delete process.env[key]; } + previousHomes = homeKeys.map(name => process.env[name]); + home = mkdtempSync(join(tmpdir(), "ocx-account-egress-bg-")); + process.env.OPENCODEX_HOME = home; + process.env.CODEX_HOME = join(home, "codex"); + mkdirSync(join(home, "codex"), { recursive: true }); + calls = []; + clearAccountQuota(); + __resetGuardianState(); + resetCodexQuotaAutoRefreshForTests(); + resetCodexAccountEgressConfigForTests(); + globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => { + const url = input instanceof Request ? input.url : String(input); + calls.push({ url, proxy: (init as { proxy?: unknown } | undefined)?.proxy }); + if (url.endsWith("/codex/responses")) return completed(); + if (url.includes("/wham/usage")) return Response.json({ plan_type: "plus", email: "routed@example.test", + rate_limit: { primary_window: { used_percent: 10, limit_window_seconds: 18000 }, secondary_window: { used_percent: 10, limit_window_seconds: 604800 } } }); + if (url.endsWith("/rate-limit-reset-credits")) return Response.json({ credits: [] }); + return new Response("unexpected", { status: 599 }); + }) as typeof fetch; + saveCodexAccountCredential("routed", { accessToken: "routed-access", refreshToken: "routed-grant", expiresAt: Date.now() + 3_600_000, chatgptAccountId: "acc-routed" }); +}); + +afterEach(async () => { + globalThis.fetch = realFetch; + resetCodexAccountEgressConfigForTests(); + clearAccountQuota(); + __resetGuardianState(); + resetCodexQuotaAutoRefreshForTests(); + for (const key of PROXY_ENV) { const value = savedEnv.get(key); if (value === undefined) delete process.env[key]; else process.env[key] = value; } + homeKeys.forEach((name, index) => { const value = previousHomes[index]; if (value === undefined) delete process.env[name]; else process.env[name] = value; }); + await flushConfigDirHardening(home); + removeTreeWithRetry(home); +}); + +const proxiesFor = (suffix: string) => calls.filter(call => call.url.endsWith(suffix) || call.url.includes(suffix)).map(call => call.proxy); + +test("token-guardian warmup of a pool account leaves by the account route", async () => { + saveConfig(config({ tokenGuardian: { enabled: true, tickSeconds: 60, leadSeconds: 60, codexWarmupEnabled: true, codexWarmupMaxAgeSeconds: 60 } })); + markCodexAccountValidated("routed", Date.now() - 120_000); + const result = await guardianSweep(Date.now()); + expect(result.warmed).toContain("codex:routed"); + expect(proxiesFor("/codex/responses")).toEqual([ACCOUNT_PROXY]); +}); + +test("quota auto-refresh warmup of a pool account leaves by the account route", async () => { + const cfg = config({ codexQuotaAutoRefresh: { routed: { fiveHour: true, weekly: true } } }); + bindCodexAccountEgressConfig(cfg); + const now = Date.now(); + await runCodexQuotaAutoRefresh(cfg, now, { + getQuota: () => ({ shortWindowSeconds: 18_000, shortResetAt: now / 1000 - 60, weeklyResetAt: now / 1000 - 60, updatedAt: now - 120_000 }), + persistCompleted: () => true, + refreshQuota: async () => undefined, + } as never); + expect(proxiesFor("/codex/responses")).toEqual([ACCOUNT_PROXY]); +}); + +async function runPoolLogin(body: Record, cfg: OcxConfig, accountId: string): Promise { + const originalLogin = OAUTH_PROVIDERS.chatgpt.login; + const originalSetTimeout = globalThis.setTimeout; + let poll: (() => void) | undefined; + const stopped = Promise.withResolvers(); + const timer = spyOn(globalThis, "setTimeout").mockImplementation(((callback, delay, ...args) => { + if (delay === 2_000) poll = () => callback(...args); + else if (delay === CODEX_LOGIN_TERMINAL_TTL_MS) stopped.resolve(); + else if (delay !== 30_000) return originalSetTimeout(callback, delay, ...args); + return 0 as unknown as ReturnType; + }) as typeof setTimeout); + OAUTH_PROVIDERS.chatgpt.login = async controller => { + controller.onAuth({ url: "https://example.test/oauth" }); + return { access: "fresh-access", refresh: "fresh-grant", expires: Date.now() + 3_600_000, accountId, email: "routed@example.test" }; + }; + let flowId: string | undefined; + try { + const response = await handleCodexAuthLoginStart(new Request("http://127.0.0.1/api/codex-auth/login", { + method: "POST", body: JSON.stringify({ ...body, openBrowser: false }), + }), cfg); + expect(response.status).toBe(200); + flowId = (await response.json() as { flowId: string }).flowId; + expect(await waitForLoginSettled("chatgpt", 1_000, flowId)).toBe(true); + poll?.(); + await Promise.race([stopped.promise, new Promise((_, reject) => originalSetTimeout(() => reject(new Error("login poller did not settle")), 5_000))]); + expect(codexAuthLoginState.get(flowId)).toMatchObject({ status: "done" }); + } finally { + clearLoginState("chatgpt"); + if (flowId) codexAuthLoginState.delete(flowId); + timer.mockRestore(); + OAUTH_PROVIDERS.chatgpt.login = originalLogin; + } +} + +test("reauthentication reads usage and warms up by the account route", async () => { + const cfg = config(); + saveConfig(cfg); + bindCodexAccountEgressConfig(cfg); + await runPoolLogin({ id: "routed", reauth: true }, cfg, "acc-routed"); + expect(getCodexAccountCredential("routed")?.accessToken).toBe("fresh-access"); + expect(proxiesFor("/wham/usage")).toEqual([ACCOUNT_PROXY]); + expect(proxiesFor("/codex/responses")).toEqual([ACCOUNT_PROXY]); +}); + +test("a new login, which has no pool row yet, takes the provider's route", async () => { + const cfg = config(); + saveConfig(cfg); + bindCodexAccountEgressConfig(cfg); + await runPoolLogin({ id: "newcomer" }, cfg, "acc-newcomer"); + expect(proxiesFor("/wham/usage")).toEqual([PROVIDER_PROXY]); + expect(proxiesFor("/codex/responses")).toEqual([PROVIDER_PROXY]); +}); + +test("a stored credential the config does not list is refused; only a new login takes the provider's route", async () => { + const cfg = config(); + bindCodexAccountEgressConfig(cfg); + cfg.codexAccounts = []; + await expect(codexAccountFetch("routed")("https://chatgpt.com/backend-api/wham/usage")).rejects.toBeInstanceOf(CodexAccountRouteUnavailableError); + expect(calls).toEqual([]); + await codexAccountFetch("routed", { newLogin: true })("https://chatgpt.com/backend-api/wham/usage"); + expect(proxiesFor("/wham/usage")).toEqual([PROVIDER_PROXY]); +}); + +test("a pool account removed while its credential is in hand is refused, even when credential cleanup failed", async () => { + const cfg = config(); + bindCodexAccountEgressConfig(cfg); + cfg.codexAccounts = []; // the row removal committed; the credential was not tombstoned + await expect(codexAccountFetch("routed")("https://chatgpt.com/backend-api/wham/usage")).rejects.toBeInstanceOf(CodexAccountRouteUnavailableError); + expect(calls).toEqual([]); + const live = config(); + bindCodexAccountEgressConfig(live); + // An expired token makes the reset-credit call refresh first; the account is removed while that + // refresh is in flight, after the call already checked it. + saveCodexAccountCredential("routed", { accessToken: "stale", refreshToken: "routed-grant", expiresAt: Date.now() - 1_000, chatgptAccountId: "acc-routed" }); + const recording = globalThis.fetch; + globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => { + if (String(input).startsWith("https://auth.openai.com/")) { + calls.push({ url: String(input), proxy: (init as { proxy?: unknown } | undefined)?.proxy }); + live.codexAccounts = []; + removeCodexAccountCredential("routed"); + return Response.json({ access_token: "fresh-access", refresh_token: "fresh-grant", expires_in: 3600 }); + } + return recording(input, init); + }) as typeof fetch; + const outcome = await inspectResetCredits(live, "routed", new AbortController().signal).then(r => r, (error: unknown) => error); + expect(calls.map(call => call.url.startsWith("https://auth.openai.com/"))).toEqual([true]); + expect(calls[0]!.proxy).toBe(ACCOUNT_PROXY); + expect(calls.filter(call => call.url.includes("/rate-limit-reset-credits"))).toEqual([]); + expect(outcome instanceof Response ? outcome.status : (outcome as Error).name).not.toBe(200); +}); + +test("a server that started on an unreadable config refuses pool sends, and its binding ends with the lifecycle", async () => { + writeFileSync(getConfigPath(), "{ not json"); + const degraded = loadConfig(); + degraded.codexAccounts = config().codexAccounts; + bindCodexAccountEgressConfig(degraded); + await expect(codexAccountFetch("routed")("https://chatgpt.com/backend-api/wham/usage")).rejects.toBeInstanceOf(CodexAccountRouteUnavailableError); + unbindCodexAccountEgressConfig(degraded); + saveConfig(config()); + await codexAccountFetch("routed")("https://chatgpt.com/backend-api/wham/usage"); + expect(proxiesFor("/wham/usage")).toEqual([ACCOUNT_PROXY]); + // A binding for one config home does not answer for another: this home has no config at all. + const other = config(); + other.codexAccounts![0]!.egress = { proxy: "http://127.0.0.1:13/" }; + bindCodexAccountEgressConfig(other); + const otherHome = mkdtempSync(join(tmpdir(), "ocx-account-egress-bg-other-")); + process.env.OPENCODEX_HOME = otherHome; + try { + calls = []; + await expect(codexAccountFetch("routed")("https://chatgpt.com/backend-api/wham/usage")).rejects.toBeInstanceOf(CodexAccountRouteUnavailableError); + expect(calls).toEqual([]); + } finally { + process.env.OPENCODEX_HOME = home; + await flushConfigDirHardening(otherHome); + removeTreeWithRetry(otherHome); + } +}); + +test("overlapping server lifecycles: the newest owner's routes apply, and its release restores the survivor's", async () => { + const first = config({ clientIntegrations: { codex: false } } as Partial); + first.codexAccounts![0]!.egress = { proxy: "http://127.0.0.1:21/" }; + const second = config({ clientIntegrations: { codex: false } } as Partial); + second.codexAccounts![0]!.egress = { proxy: "http://127.0.0.1:23/" }; + saveConfig(first); + const firstLease = acquireServerBackgroundLifecycle(() => {}, first); + try { + const secondLease = acquireServerBackgroundLifecycle(() => {}, second); + await codexAccountFetch("routed")("https://chatgpt.com/backend-api/wham/usage"); + await secondLease.release(); + await codexAccountFetch("routed")("https://chatgpt.com/backend-api/wham/usage"); + } finally { + await firstLease.release(); + } + expect(proxiesFor("/wham/usage")).toEqual(["http://127.0.0.1:23/", "http://127.0.0.1:21/"]); +}); + +test("a direct caller's own bearer keeps the process-wide route under a provider proxy", async () => { + resetCodexModelEntitlementCacheForTests(); + bindCodexAccountEgressConfig(config()); + const model = [...ACCOUNT_GATED_NATIVE_OPENAI_MODELS][0]!; + const seen: unknown[] = []; + const fetcher = (async (_input: RequestInfo | URL, init?: RequestInit) => { + seen.push((init as { proxy?: unknown } | undefined)?.proxy); + return Response.json({ models: [{ slug: model }] }); + }) as typeof fetch; + await isDirectCallerEntitledToCodexModel(new Headers({ authorization: "Bearer direct-token", "chatgpt-account-id": "acc-direct" }), model, { fetcher }); + resetCodexModelEntitlementCacheForTests(); + expect(seen).toEqual([undefined]); +}); + +test("a stored credential whose config was deleted is refused, never sent without its former route", async () => { + saveConfig(config()); + await codexAccountFetch("routed")("https://chatgpt.com/backend-api/wham/usage"); + expect(proxiesFor("/wham/usage")).toEqual([ACCOUNT_PROXY]); + unlinkSync(getConfigPath()); + calls = []; + const generation = readCodexAccountRecord("routed")!.generation; + await expect(forceRefreshCodexPoolToken("routed", { rejectedGeneration: generation, rejectedAccessToken: "routed-access" })) + .rejects.toBeInstanceOf(CodexAccountRouteUnavailableError); + await expect(codexAccountFetch("routed")("https://chatgpt.com/backend-api/wham/usage")).rejects.toBeInstanceOf(CodexAccountRouteUnavailableError); + expect(calls).toEqual([]); +}); + +test("restoring a surviving lifecycle owner keeps its own config home", async () => { + const homeA = home; + const first = config({ clientIntegrations: { codex: false } } as Partial); + first.codexAccounts![0]!.egress = { proxy: "http://127.0.0.1:21/" }; + saveConfig(first); + const firstLease = acquireServerBackgroundLifecycle(() => {}, first); + const homeB = mkdtempSync(join(tmpdir(), "ocx-account-egress-bg-b-")); + try { + process.env.OPENCODEX_HOME = homeB; + const second = config({ clientIntegrations: { codex: false } } as Partial); + second.codexAccounts![0]!.egress = { proxy: "http://127.0.0.1:23/" }; + saveConfig(second); + const secondLease = acquireServerBackgroundLifecycle(() => {}, second); + await secondLease.release(); + // Home B is current; the survivor's binding belongs to home A, so B's own file answers. + await codexAccountFetch("routed")("https://chatgpt.com/backend-api/wham/usage"); + process.env.OPENCODEX_HOME = homeA; + await codexAccountFetch("routed")("https://chatgpt.com/backend-api/wham/usage"); + } finally { + process.env.OPENCODEX_HOME = homeA; + await firstLease.release(); + await flushConfigDirHardening(homeB); + removeTreeWithRetry(homeB); + } + expect(proxiesFor("/wham/usage")).toEqual(["http://127.0.0.1:23/", "http://127.0.0.1:21/"]); +}); diff --git a/tests/codex-integration/codex-account-store-refresh-classification.test.ts b/tests/codex-integration/codex-account-store-refresh-classification.test.ts index 09a614365b6..adb1fec3e58 100644 --- a/tests/codex-integration/codex-account-store-refresh-classification.test.ts +++ b/tests/codex-integration/codex-account-store-refresh-classification.test.ts @@ -1,4 +1,5 @@ import { describe, expect, test, beforeEach, afterEach, spyOn } from "bun:test"; +import { bindStoredCodexPoolRoutingForTests } from "../helpers/codex-pool-routing"; import { mkdtempSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -35,6 +36,7 @@ describe("codex refresh-failure classification", () => { setAsyncIcaclsRunnerForTests(async () => ICACLS_OK); TEST_DIR = mkdtempSync(join(tmpdir(), "ocx-codex-refresh-class-")); process.env.OPENCODEX_HOME = TEST_DIR; + bindStoredCodexPoolRoutingForTests(); }); afterEach(async () => { diff --git a/tests/codex-integration/codex-account-store.test.ts b/tests/codex-integration/codex-account-store.test.ts index 49147c416c1..8294d26c735 100644 --- a/tests/codex-integration/codex-account-store.test.ts +++ b/tests/codex-integration/codex-account-store.test.ts @@ -1,4 +1,5 @@ import { describe, expect, test, beforeEach, afterEach, spyOn } from "bun:test"; +import { bindStoredCodexPoolRoutingForTests } from "../helpers/codex-pool-routing"; import { createHash } from "node:crypto"; import { Database } from "bun:sqlite"; import * as fs from "node:fs"; @@ -28,6 +29,7 @@ function installScratchHome(): void { TEST_DIR = mkdtempSync(join(tmpdir(), "ocx-codex-accounts-")); ACCOUNTS_PATH = join(TEST_DIR, "codex-accounts.json"); process.env.OPENCODEX_HOME = TEST_DIR; + bindStoredCodexPoolRoutingForTests(); } async function removeScratchHome(): Promise { diff --git a/tests/codex-integration/codex-auth-api.test.ts b/tests/codex-integration/codex-auth-api.test.ts index 5905e0a27f2..68a7694908c 100644 --- a/tests/codex-integration/codex-auth-api.test.ts +++ b/tests/codex-integration/codex-auth-api.test.ts @@ -1,7 +1,7 @@ import { registerMainCollisionCases } from "../helpers/codex-main-collision"; import { registerReloginPauseCases, registerWarmupRateLimitCases } from "../helpers/codex-warmup-rate-limit"; import { registerResetCreditConsumeValidationTests } from "../helpers/reset-credit-consume-validation"; -import { registerPoolReauthCauseCases } from "../helpers/pool-reauth-cause"; +import { bindStoredCodexPoolRoutingForTests, registerPoolReauthCauseCases } from "../helpers/pool-reauth-cause"; import * as usageHistoryModule from "../../src/usage/log"; import { getAccountQuotaHistory } from "../../src/codex/quota"; import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test"; @@ -551,7 +551,7 @@ beforeEach(() => { TEST_CODEX_HOME = join(TEST_DIR, "codex"); mkdirSync(TEST_CODEX_HOME, { recursive: true }); process.env.OPENCODEX_HOME = TEST_DIR; - process.env.CODEX_HOME = TEST_CODEX_HOME; + process.env.CODEX_HOME = TEST_CODEX_HOME; bindStoredCodexPoolRoutingForTests(); delete process.env[MANUAL_IMPORT_ENV]; clearAccountNeedsReauth("__main__"); clearAccountQuota(); diff --git a/tests/codex-integration/codex-auth-context.test.ts b/tests/codex-integration/codex-auth-context.test.ts index 84cde5d664e..19184dc1076 100644 --- a/tests/codex-integration/codex-auth-context.test.ts +++ b/tests/codex-integration/codex-auth-context.test.ts @@ -1,4 +1,5 @@ import { registerStoredDirectIdentityTests } from "../helpers/stored-direct-identity"; +import { bindStoredCodexPoolRoutingForTests } from "../helpers/codex-pool-routing"; import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test"; import { mkdtempSync, readFileSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; @@ -102,6 +103,7 @@ beforeEach(() => { testDir = mkdtempSync(join(tmpdir(), "ocx-auth-ctx-")); previousOpencodexHome = process.env.OPENCODEX_HOME; process.env.OPENCODEX_HOME = testDir; + bindStoredCodexPoolRoutingForTests(); // Isolate the main-account credential source: testDir has no auth.json, so the main // account is deterministically absent (these cases test pool-only fail-closed behavior). previousCodexHome = process.env.CODEX_HOME; diff --git a/tests/codex-integration/codex-auth-headless-accounts.test.ts b/tests/codex-integration/codex-auth-headless-accounts.test.ts index d095cebfcd5..03903ded229 100644 --- a/tests/codex-integration/codex-auth-headless-accounts.test.ts +++ b/tests/codex-integration/codex-auth-headless-accounts.test.ts @@ -1,4 +1,5 @@ import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test"; +import { bindStoredCodexPoolRoutingForTests } from "../helpers/codex-pool-routing"; import { chmodSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, symlinkSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -85,6 +86,7 @@ beforeEach(() => { previousOcxHome = process.env.OPENCODEX_HOME; previousCodexHome = process.env.CODEX_HOME; process.env.OPENCODEX_HOME = join(root, "ocx"); + bindStoredCodexPoolRoutingForTests(); process.env.CODEX_HOME = nativeHome; mkdirSync(process.env.OPENCODEX_HOME); originalFetch = globalThis.fetch; diff --git a/tests/codex-integration/codex-convergence-account-selectors.test.ts b/tests/codex-integration/codex-convergence-account-selectors.test.ts index 1ef7916625a..a327327916b 100644 --- a/tests/codex-integration/codex-convergence-account-selectors.test.ts +++ b/tests/codex-integration/codex-convergence-account-selectors.test.ts @@ -1,4 +1,5 @@ import { afterEach, beforeEach, expect, setDefaultTimeout, spyOn, test } from "bun:test"; +import { bindStoredCodexPoolRoutingForTests } from "../helpers/codex-pool-routing"; import { chmodSync, existsSync, @@ -307,6 +308,7 @@ beforeEach(() => { mkdirSync(opencodexHome); process.env.CODEX_HOME = codexHome; process.env.OPENCODEX_HOME = opencodexHome; + bindStoredCodexPoolRoutingForTests(); previousFetch = globalThis.fetch; modelRostersByChatgptAccount = new Map(); modelAccessProgramsByChatgptAccount = new Map(); diff --git a/tests/codex-integration/codex-cooldown-recovery.test.ts b/tests/codex-integration/codex-cooldown-recovery.test.ts index 62fbe66c15c..208f9f7b7bd 100644 --- a/tests/codex-integration/codex-cooldown-recovery.test.ts +++ b/tests/codex-integration/codex-cooldown-recovery.test.ts @@ -1,5 +1,6 @@ // Reserve fixtures here exercise routing state only; they do not authorize or dispatch Reserve. import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { bindStoredCodexPoolRoutingForTests } from "../helpers/codex-pool-routing"; import { existsSync, mkdirSync} from "node:fs"; import { join } from "node:path"; import { @@ -94,6 +95,7 @@ describe("Codex cooldown recovery worker", () => { if (existsSync(TEST_DIR)) removeTreeWithRetry(TEST_DIR); mkdirSync(TEST_CODEX_HOME, { recursive: true }); process.env.OPENCODEX_HOME = TEST_DIR; + bindStoredCodexPoolRoutingForTests(); process.env.CODEX_HOME = TEST_CODEX_HOME; clearAccountQuota(); clearCodexUpstreamHealth(); diff --git a/tests/codex-integration/codex-credit-scoped-retry.test.ts b/tests/codex-integration/codex-credit-scoped-retry.test.ts index 7c44f9a2713..7c71b2f2a2d 100644 --- a/tests/codex-integration/codex-credit-scoped-retry.test.ts +++ b/tests/codex-integration/codex-credit-scoped-retry.test.ts @@ -1,4 +1,5 @@ import { afterEach, beforeEach, expect, spyOn, test } from "bun:test"; +import { bindStoredCodexPoolRoutingForTests } from "../helpers/codex-pool-routing"; import { mkdtempSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -51,6 +52,7 @@ beforeEach(() => { previousHome = process.env.OPENCODEX_HOME; previousCodexHome = process.env.CODEX_HOME; home = mkdtempSync(join(tmpdir(), "ocx-credit-scoped-retry-")); process.env.OPENCODEX_HOME = home; process.env.CODEX_HOME = home; + bindStoredCodexPoolRoutingForTests(); clock = spyOn(Date, "now").mockReturnValue(NOW); const ok = { success: true, exitCode: 0, timedOut: false, stdout: "", stderr: "" }; setIcaclsRunnerForTests(() => ok); setAsyncIcaclsRunnerForTests(async () => ok); diff --git a/tests/codex-integration/codex-credits-probes.test.ts b/tests/codex-integration/codex-credits-probes.test.ts index 5661aea13bd..7e44a307351 100644 --- a/tests/codex-integration/codex-credits-probes.test.ts +++ b/tests/codex-integration/codex-credits-probes.test.ts @@ -1,4 +1,5 @@ import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { bindStoredCodexPoolRoutingForTests } from "../helpers/codex-pool-routing"; import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -56,6 +57,7 @@ beforeEach(() => { originalFetch = globalThis.fetch; testDir = mkdtempSync(join(tmpdir(), "ocx-credits-probes-")); process.env.OPENCODEX_HOME = testDir; + bindStoredCodexPoolRoutingForTests(); process.env.CODEX_HOME = join(testDir, "codex"); mkdirSync(process.env.CODEX_HOME, { recursive: true }); globalThis.fetch = (async () => { throw new Error("unexpected fixture network request"); }) as typeof fetch; diff --git a/tests/codex-integration/codex-direct-credit-renewal.test.ts b/tests/codex-integration/codex-direct-credit-renewal.test.ts index e1176862faa..532d4842422 100644 --- a/tests/codex-integration/codex-direct-credit-renewal.test.ts +++ b/tests/codex-integration/codex-direct-credit-renewal.test.ts @@ -1,4 +1,5 @@ import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test"; +import { bindStoredCodexPoolRoutingForTests } from "../helpers/codex-pool-routing"; import { mkdtempSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -82,6 +83,7 @@ describe("Direct explicit-account credit renewal", () => { priorHome = process.env.OPENCODEX_HOME; home = mkdtempSync(join(tmpdir(), "ocx-direct-credit-")); process.env.OPENCODEX_HOME = home; + bindStoredCodexPoolRoutingForTests(); codexHome = installIsolatedCodexHome("ocx-direct-credit-native-"); writeFileSync(join(codexHome.path, "auth.json"), JSON.stringify({ tokens: { access_token: "fixture-native-main", account_id: "fixture-native-account" }, diff --git a/tests/codex-integration/codex-direct-renewal-revocation.test.ts b/tests/codex-integration/codex-direct-renewal-revocation.test.ts index 6f3dec6284d..2b19d9883fb 100644 --- a/tests/codex-integration/codex-direct-renewal-revocation.test.ts +++ b/tests/codex-integration/codex-direct-renewal-revocation.test.ts @@ -1,4 +1,5 @@ import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { bindStoredCodexPoolRoutingForTests } from "../helpers/codex-pool-routing"; import { mkdtempSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -71,6 +72,7 @@ describe("credit renewal rechecks authority after token preparation", () => { priorHome = process.env.OPENCODEX_HOME; home = mkdtempSync(join(tmpdir(), "ocx-renewal-revocation-")); process.env.OPENCODEX_HOME = home; + bindStoredCodexPoolRoutingForTests(); nativeHome = installIsolatedCodexHome("ocx-renewal-revocation-native-"); clearCodexQuotaPrimeState(); clearAccountQuota(); resetQuotaQueryBackoffForTests(); config = { diff --git a/tests/codex-integration/codex-main-token-invalidated.test.ts b/tests/codex-integration/codex-main-token-invalidated.test.ts index bb57d586343..300c1db959f 100644 --- a/tests/codex-integration/codex-main-token-invalidated.test.ts +++ b/tests/codex-integration/codex-main-token-invalidated.test.ts @@ -1,4 +1,5 @@ import { afterEach, beforeEach, expect, test } from "bun:test"; +import { bindStoredCodexPoolRoutingForTests } from "../helpers/codex-pool-routing"; import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -45,6 +46,7 @@ beforeEach(() => { const codexHome = join(dir, "codex"); mkdirSync(codexHome, { recursive: true }); process.env.OPENCODEX_HOME = dir; + bindStoredCodexPoolRoutingForTests(); process.env.CODEX_HOME = codexHome; clearAccountNeedsReauth(MAIN_CODEX_ACCOUNT_ID); clearMainAccountInfoCache(); diff --git a/tests/codex-integration/codex-model-denial-evidence.test.ts b/tests/codex-integration/codex-model-denial-evidence.test.ts index 6ffb0bfd0c7..ab2236e931b 100644 --- a/tests/codex-integration/codex-model-denial-evidence.test.ts +++ b/tests/codex-integration/codex-model-denial-evidence.test.ts @@ -1,4 +1,5 @@ import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { bindStoredCodexPoolRoutingForTests } from "../helpers/codex-pool-routing"; import { cachedDeniedCodexAccountIdsForModel, cachedAvailableAccountGatedNativeModels, @@ -76,6 +77,7 @@ describe("a refusal fences roster fetches that started before it", () => { credentials.push({ accountId, accessToken: `access-${accountId}`, chatgptAccountId: `chatgpt-${accountId}`, credentialIdentity: `pool:${readCodexAccountRecord(accountId)!.generation}:chatgpt-${accountId}` }); } + bindStoredCodexPoolRoutingForTests(); setObservedDenialGenerationCheck(beginCodexAccountGenerationLiveCheck); }); diff --git a/tests/codex-integration/codex-model-entitlements-program-shape.test.ts b/tests/codex-integration/codex-model-entitlements-program-shape.test.ts index f5a04c7d9fb..fa3b80e4f00 100644 --- a/tests/codex-integration/codex-model-entitlements-program-shape.test.ts +++ b/tests/codex-integration/codex-model-entitlements-program-shape.test.ts @@ -1,4 +1,5 @@ import { beforeEach, describe, expect, test } from "bun:test"; +import { bindStoredCodexPoolRoutingForTests, registerCodexPoolRowForTests } from "../helpers/codex-pool-routing"; import { MAIN_CODEX_ACCOUNT_ID, } from "../../src/codex/main-account"; @@ -16,14 +17,14 @@ const SOL = "gpt-5.6-sol"; function credential(accountId: string): CodexModelEntitlementCredentialSnapshot { return { - accountId, + accountId: registerCodexPoolRowForTests(accountId), accessToken: `token-${accountId}`, chatgptAccountId: `chatgpt-${accountId}`, credentialIdentity: `test:${accountId}`, }; } -beforeEach(() => resetCodexModelEntitlementCacheForTests()); +beforeEach(() => { resetCodexModelEntitlementCacheForTests(); bindStoredCodexPoolRoutingForTests(); }); describe("Codex roster access program metadata", () => { test("a routed row never inherits native access programs from its template", () => { diff --git a/tests/codex-integration/codex-model-entitlements.test.ts b/tests/codex-integration/codex-model-entitlements.test.ts index d7589eb0e99..069161924ca 100644 --- a/tests/codex-integration/codex-model-entitlements.test.ts +++ b/tests/codex-integration/codex-model-entitlements.test.ts @@ -1,4 +1,5 @@ import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { bindStoredCodexPoolRoutingForTests, registerCodexPoolRowForTests } from "../helpers/codex-pool-routing"; import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -50,7 +51,7 @@ const ASTRA = "gpt-6-astra"; function credential(accountId: string): CodexModelEntitlementCredentialSnapshot { return { - accountId, + accountId: registerCodexPoolRowForTests(accountId), accessToken: `token-${accountId}`, chatgptAccountId: `chatgpt-${accountId}`, credentialIdentity: `test:${accountId}`, @@ -80,7 +81,7 @@ function deferred(): { return { promise, resolve }; } -beforeEach(() => resetCodexModelEntitlementCacheForTests()); +beforeEach(() => { resetCodexModelEntitlementCacheForTests(); bindStoredCodexPoolRoutingForTests(); }); describe("Codex account model entitlements", () => { test("keeps parsed-empty distinct from refresh failures end to end", async () => { @@ -490,6 +491,7 @@ describe("ensureCodexEntitlementFreshness", () => { mkdirSync(codexHome, { recursive: true }); process.env.OPENCODEX_HOME = join(root, "opencodex"); process.env.CODEX_HOME = codexHome; + bindStoredCodexPoolRoutingForTests(); }); afterEach(() => { @@ -1588,7 +1590,7 @@ describe("entitlement client version (#2886)", () => { let fetches = 0; const backend = (async () => { fetches += 1; return roster(SOL); }) as typeof fetch; const credentials = [{ - accountId: "pool-miss-budget", + accountId: registerCodexPoolRowForTests("pool-miss-budget"), accessToken: "tok-miss", chatgptAccountId: "acct-miss", credentialIdentity: "pool:1:acct-miss", diff --git a/tests/codex-integration/codex-native-availability-nux.test.ts b/tests/codex-integration/codex-native-availability-nux.test.ts index abfc51423a8..ce25f5df138 100644 --- a/tests/codex-integration/codex-native-availability-nux.test.ts +++ b/tests/codex-integration/codex-native-availability-nux.test.ts @@ -1,4 +1,5 @@ import { afterEach, beforeEach, expect, setDefaultTimeout, test } from "bun:test"; +import { bindStoredCodexPoolRoutingForTests } from "../helpers/codex-pool-routing"; import { chmodSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { captureCatalogAdmissionSnapshot } from "../../src/codex/catalog-admission"; @@ -51,7 +52,7 @@ async function snapshot(main: unknown[], pool: unknown[] = [], mainFails = false }); } -beforeEach(() => resetCodexModelEntitlementCacheForTests()); +beforeEach(() => { resetCodexModelEntitlementCacheForTests(); bindStoredCodexPoolRoutingForTests(["synthetic-pool"]); }); test("confirmed main roster projects only its bounded message onto a bare native row", async () => { const result = await snapshot([rosterRow(MODEL, { message: ` ${"M".repeat(2_100)} `, extra: "ignored" })], diff --git a/tests/codex-integration/codex-quota-auto-refresh.test.ts b/tests/codex-integration/codex-quota-auto-refresh.test.ts index 63462bec737..4054beca982 100644 --- a/tests/codex-integration/codex-quota-auto-refresh.test.ts +++ b/tests/codex-integration/codex-quota-auto-refresh.test.ts @@ -1,4 +1,5 @@ import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test"; +import { bindStoredCodexPoolRoutingForTests } from "../helpers/codex-pool-routing"; import { mkdtempSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -111,6 +112,7 @@ beforeEach(() => { previousHome = process.env.OPENCODEX_HOME; testHome = mkdtempSync(join(tmpdir(), "ocx-quota-auto-refresh-")); process.env.OPENCODEX_HOME = testHome; + bindStoredCodexPoolRoutingForTests(); clearAccountQuota(); resetCodexQuotaAutoRefreshForTests(); }); diff --git a/tests/codex-integration/codex-quota-prime.test.ts b/tests/codex-integration/codex-quota-prime.test.ts index f972cdeb24c..d57258cec9d 100644 --- a/tests/codex-integration/codex-quota-prime.test.ts +++ b/tests/codex-integration/codex-quota-prime.test.ts @@ -1,4 +1,6 @@ import { afterEach, beforeEach, describe, expect, test, spyOn } from "bun:test"; +import { bindCodexPoolRoutingConfigForTests, bindStoredCodexPoolRoutingForTests } from "../helpers/codex-pool-routing"; +import { codexAccountFetch, CodexAccountRouteUnavailableError } from "../../src/codex/account-egress-runtime"; import { existsSync, mkdirSync, mkdtempSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -115,6 +117,7 @@ describe("primeCodexPoolQuotas", () => { setAsyncIcaclsRunnerForTests(async () => aclSuccess); mkdirSync(TEST_CODEX_HOME, { recursive: true }); process.env.OPENCODEX_HOME = TEST_DIR; + bindStoredCodexPoolRoutingForTests(); // Isolate the main-account source: TEST_CODEX_HOME has no auth.json, so the // main account is deterministically absent and priming only touches the pool. process.env.CODEX_HOME = TEST_CODEX_HOME; @@ -791,6 +794,7 @@ describe("primeCodexPoolQuotas", () => { test("removing an account from the pool purges its failed-prime backoff", async () => { const config = makeConfig(); seedPoolAccount(config, "p1"); + bindCodexPoolRoutingConfigForTests(config); const originalPool = [...(config.codexAccounts ?? [])]; const originalFetch = globalThis.fetch; let calls = 0; @@ -810,6 +814,9 @@ describe("primeCodexPoolQuotas", () => { config.codexAccounts = []; clearCodexQuotaPrimeSingleFlightForTests(); await primeCodexPoolQuotas(config, "removed"); + // A removed account's stored credential is refused at the routing boundary, not sent. + await expect(codexAccountFetch("p1")("https://chatgpt.com/backend-api/wham/usage")).rejects.toBeInstanceOf(CodexAccountRouteUnavailableError); + expect(calls).toBe(1); config.codexAccounts = originalPool; upstreamHealthy = true; diff --git a/tests/codex-integration/codex-quota-query-backoff.test.ts b/tests/codex-integration/codex-quota-query-backoff.test.ts index 6a642668fea..3a7af346cbe 100644 --- a/tests/codex-integration/codex-quota-query-backoff.test.ts +++ b/tests/codex-integration/codex-quota-query-backoff.test.ts @@ -1,4 +1,5 @@ import { afterEach, beforeEach, expect, spyOn, test } from "bun:test"; +import { bindStoredCodexPoolRoutingForTests } from "../helpers/codex-pool-routing"; import { mkdtempSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -28,7 +29,7 @@ beforeEach(() => { originalFetch = globalThis.fetch; home = mkdtempSync(join(tmpdir(), "quota-query-backoff-")); process.env.OPENCODEX_HOME = home; - clearAccountQuota(); resetQuotaQueryBackoffForTests(); save(); + clearAccountQuota(); resetQuotaQueryBackoffForTests(); save(); bindStoredCodexPoolRoutingForTests(); }); afterEach(() => { globalThis.fetch = originalFetch; diff --git a/tests/codex-integration/codex-reset-credit-dto.test.ts b/tests/codex-integration/codex-reset-credit-dto.test.ts index c8a745837a6..6631bbd19e6 100644 --- a/tests/codex-integration/codex-reset-credit-dto.test.ts +++ b/tests/codex-integration/codex-reset-credit-dto.test.ts @@ -1,4 +1,5 @@ import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { bindStoredCodexPoolRoutingForTests } from "../helpers/codex-pool-routing"; import { mkdtempSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -32,6 +33,7 @@ describe("reset-credit safe DTO", () => { oldHome = process.env.OPENCODEX_HOME; home = mkdtempSync(join(tmpdir(), "ocx-reset-dto-")); process.env.OPENCODEX_HOME = home; + bindStoredCodexPoolRoutingForTests(); originalFetch = globalThis.fetch; saveCodexAccountCredential("dto-pool", { accessToken: "test-access", refreshToken: "test-refresh", expiresAt: Date.now() + 3600_000, chatgptAccountId: "test-account" }); globalThis.fetch = (async (input: RequestInfo | URL) => { diff --git a/tests/codex-integration/codex-stored-main-duplicate.test.ts b/tests/codex-integration/codex-stored-main-duplicate.test.ts index 765d27957fb..987c032a7d9 100644 --- a/tests/codex-integration/codex-stored-main-duplicate.test.ts +++ b/tests/codex-integration/codex-stored-main-duplicate.test.ts @@ -1,4 +1,5 @@ import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test"; +import { bindStoredCodexPoolRoutingForTests } from "../helpers/codex-pool-routing"; import { mkdirSync, mkdtempSync, writeFileSync, unlinkSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -58,6 +59,7 @@ beforeEach(() => { previousOcxHome = process.env.OPENCODEX_HOME; process.env.CODEX_HOME = join(home, "codex"); process.env.OPENCODEX_HOME = join(home, "ocx"); + bindStoredCodexPoolRoutingForTests(); mkdirSync(process.env.CODEX_HOME, { recursive: true }); mkdirSync(process.env.OPENCODEX_HOME, { recursive: true }); config = { port: 10100, providers: {}, defaultProvider: "openai", activeCodexAccountId: poolId, diff --git a/tests/codex-integration/discovered-native-models.test.ts b/tests/codex-integration/discovered-native-models.test.ts index 90c7d42835d..4e8931d7156 100644 --- a/tests/codex-integration/discovered-native-models.test.ts +++ b/tests/codex-integration/discovered-native-models.test.ts @@ -1,4 +1,5 @@ import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { bindStoredCodexPoolRoutingForTests } from "../helpers/codex-pool-routing"; import { mkdirSync, mkdtempSync, readFileSync, statSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -75,6 +76,7 @@ beforeEach(() => { previousHome = process.env.OPENCODEX_HOME; home = mkdtempSync(join(tmpdir(), "ocx-discovered-native-")); process.env.OPENCODEX_HOME = home; + bindStoredCodexPoolRoutingForTests(["future-test"]); path = join(home, "discovered-native-models.json"); resetDiscoveredNativeModelsForTests(); resetConfiguredNativeOpenAiModelsForTests(); diff --git a/tests/codex-integration/issue-452-empty-503.test.ts b/tests/codex-integration/issue-452-empty-503.test.ts index 63e964a13d4..80a5b212b42 100644 --- a/tests/codex-integration/issue-452-empty-503.test.ts +++ b/tests/codex-integration/issue-452-empty-503.test.ts @@ -1,4 +1,5 @@ import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { bindStoredCodexPoolRoutingForTests } from "../helpers/codex-pool-routing"; import { existsSync, mkdirSync} from "node:fs"; import { join } from "node:path"; import { saveCodexAccountCredential } from "../../src/codex/account-store"; @@ -186,6 +187,7 @@ async function withPoolPassthrough( if (existsSync(TEST_DIR)) removeTreeWithRetry(TEST_DIR); mkdirSync(TEST_DIR, { recursive: true }); process.env.OPENCODEX_HOME = TEST_DIR; + bindStoredCodexPoolRoutingForTests(); delete process.env.OPENCODEX_API_AUTH_TOKEN; clearCodexUpstreamHealth(); clearThreadAccountMap(); diff --git a/tests/codex-integration/reserve-quota-scope.test.ts b/tests/codex-integration/reserve-quota-scope.test.ts index 3b82407549d..fafbeab7406 100644 --- a/tests/codex-integration/reserve-quota-scope.test.ts +++ b/tests/codex-integration/reserve-quota-scope.test.ts @@ -1,4 +1,5 @@ import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { bindStoredCodexPoolRoutingForTests } from "../helpers/codex-pool-routing"; import { mkdirSync, mkdtempSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -70,6 +71,7 @@ describe("Reserve quota scope", () => { previousFetch = globalThis.fetch; directory = mkdtempSync(join(tmpdir(), "ocx-reserve-quota-scope-")); process.env.OPENCODEX_HOME = directory; + bindStoredCodexPoolRoutingForTests(); process.env.CODEX_HOME = join(directory, "codex"); mkdirSync(process.env.CODEX_HOME, { recursive: true }); clearAccountQuota(); diff --git a/tests/codex-integration/token-guardian.test.ts b/tests/codex-integration/token-guardian.test.ts index 9d97fface44..f1b8b924c3c 100644 --- a/tests/codex-integration/token-guardian.test.ts +++ b/tests/codex-integration/token-guardian.test.ts @@ -28,10 +28,15 @@ function kimiProvider(refreshPolicy?: OcxProviderConfig["refreshPolicy"]): OcxPr return { adapter: "openai-chat", baseUrl: "https://api.moonshot.ai/v1", authMode: "oauth", ...(refreshPolicy ? { refreshPolicy } : {}) }; } +// Pool accounts the guardian may refresh or warm have rows: a stored credential the config does not +// list is never sent (its route would be unknown). +const POOL_ACCOUNT_IDS = ["acct-1", "acct-late", "acct-resolving", "acct-pending", "acct-stale", "acct-warm", "acct-revoked", "acct-transient", "acct-replaced", "acct-dead"]; + function writeConfig(partial: Partial): void { const providers = partial.providers ?? { kimi: kimiProvider() }; const defaultProvider = partial.defaultProvider ?? Object.keys(providers)[0] ?? "kimi"; - const cfg: OcxConfig = { port: 10100, ...partial, providers, defaultProvider }; + const codexAccounts = partial.codexAccounts ?? POOL_ACCOUNT_IDS.map(id => ({ id, email: `${id}@example.test`, isMain: false })); + const cfg: OcxConfig = { port: 10100, ...partial, providers, defaultProvider, codexAccounts }; writeFileSync(getConfigPath(), JSON.stringify(cfg, null, 2)); } diff --git a/tests/fixtures/test-layout-expected.json b/tests/fixtures/test-layout-expected.json index f73e47de83c..d59fc114bee 100644 --- a/tests/fixtures/test-layout-expected.json +++ b/tests/fixtures/test-layout-expected.json @@ -1,4 +1,4 @@ -{ "account-diagnostics-routes.test.ts": "server", "explicit-proxy-no-proxy.test.ts": "lib", "gemini-native.test.ts": "server", "gemini-native-wire.test.ts": "server", "gemini-native-routes.test.ts": "server", "provider-upstream-deadlines.test.ts": "responses", "web-search-local-deadline-provenance.test.ts": "web-search", "responses-combo-unavailable-cause.test.ts": "responses", "responses-native-sse-stall.test.ts": "responses", "client-restart-sync-fence.test.ts": "clients", "service-scheduler-restart-respawn-refusal.test.ts": "service", "route-to-home-sync-review.test.ts": "routing", "route-intent-connect-post-commit.test.ts": "clients", "route-intent-file-originals.test.ts": "clients", "route-to-child-defaults.test.ts": "routing", "route-to-home-live-flags.test.ts": "routing", "route-to-home-native-truth.test.ts": "routing", "route-to-home-decisions.test.ts": "routing", "route-to-ephemeral.test.ts": "server", "link-pinned-sync-overwrite.test.ts": "clients", "cli-sync-fanout-ephemeral.test.ts": "cli", "route-intent-home-consent.test.ts": "clients", "management-route-intent-native-errors.test.ts": "server", "route-intent-offline-mode-switch.test.ts": "clients", "route-intent-parity-withdrawal.test.ts": "clients", "service-scheduler-restart-cleanup.test.ts": "service", "route-to-retirement-review.test.ts": "server", "route-to-policy-review.test.ts": "server", "management-route-intent-native-review.test.ts": "server", "route-to-home-off-review.test.ts": "routing", "codex-journal-provider-reserialization.test.ts": "codex-integration", "route-intent-parity-fallback.test.ts": "clients", "route-intent-native-originals.test.ts": "clients", "route-intent-native-review.test.ts": "clients", "route-intent-connected-capabilities.test.ts": "clients", "route-intent-connected-review.test.ts": "clients", "route-intent-connect-recovery.test.ts": "clients", "client-disconnect-field-snapshot.test.ts": "clients", "cli-route-to-confirmation.test.ts": "cli", "route-intent-runtime-stop.test.ts": "clients", "route-intent-codex-connect-disabled.test.ts": "clients", "route-intent-codex-transitions.test.ts": "clients", "route-to-live-settings.test.ts": "server", "route-intent-claude-surface.test.ts": "clients", "route-intent-local-receipt.test.ts": "clients", "route-intent-scheduler.test.ts": "clients", "route-intent-watch-client.test.ts": "clients", "route-intent-watch-boundary.test.ts": "server", "route-intent-watch-waiters.test.ts": "server", "home-route-intent-upgrade.test.ts": "clients", "route-intent-overwrite.test.ts": "clients", "codex-disconnect-owned-recovery.test.ts": "codex-integration", "service-restart-registration-guard.test.ts": "service", "client-disconnect-config-recovery.test.ts": "clients", "route-intent-aside.test.ts": "clients", "route-intent-connected.test.ts": "clients", "cli-link-route-intent.test.ts": "cli", "cli-route-to-aliases.test.ts": "cli", "cli-route-to.test.ts": "cli", "client-disconnect-edited-codex.test.ts": "clients", "codex-disconnect-fields.test.ts": "codex-integration", "link-home-route-intent.test.ts": "clients", "link-route-intent.test.ts": "server", "route-intent-desktop.test.ts": "clients", "route-intent-materializer.test.ts": "clients", "route-intent-parity.test.ts": "clients", "route-intent-reporter.test.ts": "clients", "route-intent-state.test.ts": "clients", "route-intent.test.ts": "clients", "route-to-routes.test.ts": "server", "route-to-sync-child.test.ts": "routing", "service-disconnected-client-restart.test.ts": "service", "responses-forward-client-headers-live.test.ts": "responses", "pool-retry-client-metadata.test.ts": "responses", "responses-websocket-workflow-ceiling.test.ts": "responses", "responses-workflow-send-ceiling.test.ts": "responses", "kimi-monthly-quota.test.ts": "providers", "sync-fanout.test.ts": "cli", "sync-command-fanout.test.ts": "cli", "link-pinned-sync-argv.test.ts": "clients", "sync-link-status.test.ts": "cli", "sync-fanout-process.test.ts": "cli", "codex-installation-acl.test.ts": "codex-integration", "codex-installation-id.test.ts": "codex-integration", "codex-installation-wire.test.ts": "codex-integration", "codex-installation-failover.test.ts": "responses", "lmstudio-system-policy.test.ts": "config", "openai-chat-single-system.test.ts": "adapters/openai", "update-reclaim-authorizer.test.ts": "update", "update-capability-policy.test.ts": "update", "update-service-home.test.ts": "update", "update-service-home-policy.test.ts": "update", "update-home-recovery.test.ts": "update", "update-recovery-authority.test.ts": "update", "update-recovery-boundaries.test.ts": "update", "update-home-launcher.test.ts": "update", "update-home-worker.test.ts": "update", "update-mutation-boundaries.test.ts": "update", "update-mutation-guard.test.ts": "update", "update-guarded-ops.test.ts": "update", "update-effect-authority.test.ts": "update", "update-windows-wrapper-authority.test.ts": "update", "update-mutation-scanner.test.ts": "update", "refreshed-upstream-deadlines.test.ts": "responses", "local-upstream-deadlines.test.ts": "responses", "service-desktop-recovery.test.ts": "service", "provider-input-modalities.test.ts": "providers", "turn-membership.test.ts": "responses", "turn-membership-ingress.test.ts": "responses", "workbuddy-quota.test.ts": "providers", "workbuddy-login.test.ts": "oauth", "workbuddy-adapter.test.ts": "adapters", "workbuddy-provider.test.ts": "providers", "link-tunnel-history.test.ts": "clients", "link-readiness.test.ts": "clients", "link-tunnel-status.test.ts": "clients", "link-diagnostics.test.ts": "clients", "combo-description.test.ts": "routing", "combo-description-catalog.test.ts": "codex-integration", "catalog-auto-review-override.test.ts": "codex-integration", "management-auto-review-settings.test.ts": "server", "management-auto-review-auth.test.ts": "server", "prefer-model-alias-ids.test.ts": "server", "responses-mimo-envelope.test.ts": "responses", "responses-call-id-linkage.test.ts": "responses", "responses-chat-raw-summary.test.ts": "responses", "responses-phase-inference.test.ts": "responses", "cli-message-mcp-resume.test.ts": "cli", "messaging-mcp-resume.test.ts": "codex-integration", "link-diagnostics-read.test.ts": "clients", "cli-link-diagnostics.test.ts": "cli", "link-diagnostics-route.test.ts": "server", "provider-passive-wire-model.test.ts": "providers", "passive-key-observation.test.ts": "providers", "responses-passive-key-limits.test.ts": "responses", "passive-key-limits.test.ts": "providers", "terminal-safe-text.test.ts": "lib", +{ "provider-egress-account.test.ts": "lib", "provider-egress-account-calls.test.ts": "lib", "codex-pool-account-egress-compact.test.ts": "responses", "codex-account-egress-background.test.ts": "codex-integration", "account-diagnostics-routes.test.ts": "server", "explicit-proxy-no-proxy.test.ts": "lib", "gemini-native.test.ts": "server", "gemini-native-wire.test.ts": "server", "gemini-native-routes.test.ts": "server", "provider-upstream-deadlines.test.ts": "responses", "web-search-local-deadline-provenance.test.ts": "web-search", "responses-combo-unavailable-cause.test.ts": "responses", "responses-native-sse-stall.test.ts": "responses", "client-restart-sync-fence.test.ts": "clients", "service-scheduler-restart-respawn-refusal.test.ts": "service", "route-to-home-sync-review.test.ts": "routing", "route-intent-connect-post-commit.test.ts": "clients", "route-intent-file-originals.test.ts": "clients", "route-to-child-defaults.test.ts": "routing", "route-to-home-live-flags.test.ts": "routing", "route-to-home-native-truth.test.ts": "routing", "route-to-home-decisions.test.ts": "routing", "route-to-ephemeral.test.ts": "server", "link-pinned-sync-overwrite.test.ts": "clients", "cli-sync-fanout-ephemeral.test.ts": "cli", "route-intent-home-consent.test.ts": "clients", "management-route-intent-native-errors.test.ts": "server", "route-intent-offline-mode-switch.test.ts": "clients", "route-intent-parity-withdrawal.test.ts": "clients", "service-scheduler-restart-cleanup.test.ts": "service", "route-to-retirement-review.test.ts": "server", "route-to-policy-review.test.ts": "server", "management-route-intent-native-review.test.ts": "server", "route-to-home-off-review.test.ts": "routing", "codex-journal-provider-reserialization.test.ts": "codex-integration", "route-intent-parity-fallback.test.ts": "clients", "route-intent-native-originals.test.ts": "clients", "route-intent-native-review.test.ts": "clients", "route-intent-connected-capabilities.test.ts": "clients", "route-intent-connected-review.test.ts": "clients", "route-intent-connect-recovery.test.ts": "clients", "client-disconnect-field-snapshot.test.ts": "clients", "cli-route-to-confirmation.test.ts": "cli", "route-intent-runtime-stop.test.ts": "clients", "route-intent-codex-connect-disabled.test.ts": "clients", "route-intent-codex-transitions.test.ts": "clients", "route-to-live-settings.test.ts": "server", "route-intent-claude-surface.test.ts": "clients", "route-intent-local-receipt.test.ts": "clients", "route-intent-scheduler.test.ts": "clients", "route-intent-watch-client.test.ts": "clients", "route-intent-watch-boundary.test.ts": "server", "route-intent-watch-waiters.test.ts": "server", "home-route-intent-upgrade.test.ts": "clients", "route-intent-overwrite.test.ts": "clients", "codex-disconnect-owned-recovery.test.ts": "codex-integration", "service-restart-registration-guard.test.ts": "service", "client-disconnect-config-recovery.test.ts": "clients", "route-intent-aside.test.ts": "clients", "route-intent-connected.test.ts": "clients", "cli-link-route-intent.test.ts": "cli", "cli-route-to-aliases.test.ts": "cli", "cli-route-to.test.ts": "cli", "client-disconnect-edited-codex.test.ts": "clients", "codex-disconnect-fields.test.ts": "codex-integration", "link-home-route-intent.test.ts": "clients", "link-route-intent.test.ts": "server", "route-intent-desktop.test.ts": "clients", "route-intent-materializer.test.ts": "clients", "route-intent-parity.test.ts": "clients", "route-intent-reporter.test.ts": "clients", "route-intent-state.test.ts": "clients", "route-intent.test.ts": "clients", "route-to-routes.test.ts": "server", "route-to-sync-child.test.ts": "routing", "service-disconnected-client-restart.test.ts": "service", "responses-forward-client-headers-live.test.ts": "responses", "pool-retry-client-metadata.test.ts": "responses", "responses-websocket-workflow-ceiling.test.ts": "responses", "responses-workflow-send-ceiling.test.ts": "responses", "kimi-monthly-quota.test.ts": "providers", "sync-fanout.test.ts": "cli", "sync-command-fanout.test.ts": "cli", "link-pinned-sync-argv.test.ts": "clients", "sync-link-status.test.ts": "cli", "sync-fanout-process.test.ts": "cli", "codex-installation-acl.test.ts": "codex-integration", "codex-installation-id.test.ts": "codex-integration", "codex-installation-wire.test.ts": "codex-integration", "codex-installation-failover.test.ts": "responses", "lmstudio-system-policy.test.ts": "config", "openai-chat-single-system.test.ts": "adapters/openai", "update-reclaim-authorizer.test.ts": "update", "update-capability-policy.test.ts": "update", "update-service-home.test.ts": "update", "update-service-home-policy.test.ts": "update", "update-home-recovery.test.ts": "update", "update-recovery-authority.test.ts": "update", "update-recovery-boundaries.test.ts": "update", "update-home-launcher.test.ts": "update", "update-home-worker.test.ts": "update", "update-mutation-boundaries.test.ts": "update", "update-mutation-guard.test.ts": "update", "update-guarded-ops.test.ts": "update", "update-effect-authority.test.ts": "update", "update-windows-wrapper-authority.test.ts": "update", "update-mutation-scanner.test.ts": "update", "refreshed-upstream-deadlines.test.ts": "responses", "local-upstream-deadlines.test.ts": "responses", "service-desktop-recovery.test.ts": "service", "provider-input-modalities.test.ts": "providers", "turn-membership.test.ts": "responses", "turn-membership-ingress.test.ts": "responses", "workbuddy-quota.test.ts": "providers", "workbuddy-login.test.ts": "oauth", "workbuddy-adapter.test.ts": "adapters", "workbuddy-provider.test.ts": "providers", "link-tunnel-history.test.ts": "clients", "link-readiness.test.ts": "clients", "link-tunnel-status.test.ts": "clients", "link-diagnostics.test.ts": "clients", "combo-description.test.ts": "routing", "combo-description-catalog.test.ts": "codex-integration", "catalog-auto-review-override.test.ts": "codex-integration", "management-auto-review-settings.test.ts": "server", "management-auto-review-auth.test.ts": "server", "prefer-model-alias-ids.test.ts": "server", "responses-mimo-envelope.test.ts": "responses", "responses-call-id-linkage.test.ts": "responses", "responses-chat-raw-summary.test.ts": "responses", "responses-phase-inference.test.ts": "responses", "cli-message-mcp-resume.test.ts": "cli", "messaging-mcp-resume.test.ts": "codex-integration", "link-diagnostics-read.test.ts": "clients", "cli-link-diagnostics.test.ts": "cli", "link-diagnostics-route.test.ts": "server", "provider-passive-wire-model.test.ts": "providers", "passive-key-observation.test.ts": "providers", "responses-passive-key-limits.test.ts": "responses", "passive-key-limits.test.ts": "providers", "terminal-safe-text.test.ts": "lib", "codex-ws-recovery-budget.test.ts": "responses", "codex-ws-cache-miss.test.ts": "responses", "codex-ws-incremental.test.ts": "responses", diff --git a/tests/helpers/codex-pool-routing.ts b/tests/helpers/codex-pool-routing.ts new file mode 100644 index 00000000000..50c639379af --- /dev/null +++ b/tests/helpers/codex-pool-routing.ts @@ -0,0 +1,38 @@ +import { restoreCodexAccountEgressBinding, type CodexAccountEgressConfig } from "../../src/codex/account-egress-runtime"; +import { listCodexAccountIds } from "../../src/codex/account-store"; +import { getConfigPath } from "../../src/config"; + +/** + * Pool fixtures written before account routes existed store credentials without a config row, and + * production refuses to send a stored pool credential its config does not list. This binds, for the + * current config home, a routing config whose pool rows are exactly the live stored accounts (plus + * `extraIds`, for credentials a test passes without storing them), none with a route: the state a + * running server has for unrouted pool accounts. A tombstoned account loses its row, as on deletion. + * Call it after the test home is in place; a binding for another home is ignored. + */ +const registeredIds = new Set(); + +/** A pool account a test passes as a credential without storing it; it has a row until the next bind. */ +export function registerCodexPoolRowForTests(accountId: string): string { + registeredIds.add(accountId); + return accountId; +} + +export function bindStoredCodexPoolRoutingForTests(extraIds: readonly string[] = []): void { + registeredIds.clear(); + const config = { + providers: {}, + get codexAccounts() { + return [...new Set([...listCodexAccountIds(), ...extraIds, ...registeredIds])].map(id => ({ id, email: "", isMain: false })); + }, + }; + restoreCodexAccountEgressBinding({ config: config as never, configPath: getConfigPath(), degraded: false }); +} + +/** + * Bind a test's own live config for the current config home, for cases that change account + * membership: a row the test removes from `config.codexAccounts` is gone from routing too. + */ +export function bindCodexPoolRoutingConfigForTests(config: CodexAccountEgressConfig): void { + restoreCodexAccountEgressBinding({ config, configPath: getConfigPath(), degraded: false }); +} diff --git a/tests/helpers/pool-reauth-cause.ts b/tests/helpers/pool-reauth-cause.ts index ddeb6d17d1d..04b869354ed 100644 --- a/tests/helpers/pool-reauth-cause.ts +++ b/tests/helpers/pool-reauth-cause.ts @@ -214,3 +214,5 @@ export function registerPoolReauthCauseCases( expect(account?.health?.status).not.toBe("reauth_required"); }); } + +export { bindStoredCodexPoolRoutingForTests } from "./codex-pool-routing"; diff --git a/tests/lib/provider-egress-account-calls.test.ts b/tests/lib/provider-egress-account-calls.test.ts new file mode 100644 index 00000000000..ead56a1eaeb --- /dev/null +++ b/tests/lib/provider-egress-account-calls.test.ts @@ -0,0 +1,172 @@ +/** + * Per-account egress for a Codex pool account's credentialed calls outside inference (catch-up + * G-012): token refresh, usage probes (initial and 401 replay), model discovery and reset credits + * leave by the account's route over the \`openai\` provider's, and refuse rather than drop a route. + * + * These use a fake transport and assert the route each physical call receives; real loopback + * proxies for inference are in provider-egress-account.test.ts. + */ +import { afterEach, beforeEach, expect, test } from "bun:test"; +import { mkdtempSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { + bindCodexAccountEgressConfig, + codexAccountRouting, + CodexAccountRouteUnavailableError, + resetCodexAccountEgressConfigForTests, +} from "../../src/codex/account-egress-runtime"; +import { forceRefreshCodexPoolToken, readCodexAccountRecord, saveCodexAccountCredential } from "../../src/codex/account-store"; +import { fetchFreshPoolAccountQuota, recoverPoolQuotaFrom401 } from "../../src/codex/auth-api/pool-quota-probe"; +import { consumeResetCredits, createResetCreditWhamClient, inspectResetCredits } from "../../src/codex/auth-api/reset-credit-service"; +import { discoverCodexNativeRoster, resetCodexNativeRosterDiscoveryForTests } from "../../src/codex/model-entitlements"; +import { clearAccountQuota } from "../../src/codex/quota"; +import { getConfigPath, saveConfig } from "../../src/config"; +import { flushConfigDirHardeningForTests } from "../../src/config/paths"; +import { ExplicitProxyExemptedError } from "../../src/lib/proxy-env"; +import type { OcxConfig } from "../../src/types"; +import { removeTreeWithRetry } from "../helpers/remove-tree"; + +const PROVIDER_PROXY = "http://127.0.0.1:7/"; +const ACCOUNT_PROXY = "http://127.0.0.1:9/"; +const PROXY_ENV = ["NO_PROXY", "no_proxy", "HTTP_PROXY", "http_proxy", "HTTPS_PROXY", "https_proxy", "ALL_PROXY", "all_proxy"] as const; +const savedEnv = new Map(); +const realFetch = globalThis.fetch; +const homeKeys = ["OPENCODEX_HOME", "CODEX_HOME"] as const; +let previousHomes: Array = []; +let home = ""; +let calls: Array<{ url: string; proxy: unknown }> = []; + +function poolConfig(): OcxConfig { + return { + port: 0, defaultProvider: "openai", + providers: { openai: { adapter: "openai-responses", baseUrl: "https://chatgpt.com/backend-api/codex", authMode: "forward", + codexAccountMode: "pool", proxy: PROVIDER_PROXY } }, + codexAccounts: [ + { id: "routed", email: "", isMain: false, egress: { proxy: ACCOUNT_PROXY } }, + { id: "bypass", email: "", isMain: false, egress: { noProxy: "example.invalid" } }, + { id: "plain", email: "", isMain: false }, + ], + } as unknown as OcxConfig; +} + +function respond(url: string): Response { + if (url.startsWith("https://auth.openai.com/")) return Response.json({ access_token: "fresh-access", refresh_token: "fresh-grant", expires_in: 3600 }); + if (url.includes("/wham/usage")) return Response.json({ rate_limit: { primary_window: { used_percent: 10 } } }); + if (url.endsWith("/rate-limit-reset-credits/consume")) return Response.json({ code: "ok" }); + if (url.endsWith("/rate-limit-reset-credits")) return Response.json({ credits: [] }); + if (url.includes("/models")) return Response.json({ models: [] }); + return new Response("unexpected", { status: 599 }); +} + +beforeEach(() => { + for (const key of PROXY_ENV) { savedEnv.set(key, process.env[key]); delete process.env[key]; } + previousHomes = homeKeys.map(name => process.env[name]); + home = mkdtempSync(join(tmpdir(), "ocx-account-egress-calls-")); + for (const name of homeKeys) process.env[name] = home; + calls = []; + clearAccountQuota(); + resetCodexAccountEgressConfigForTests(); + resetCodexNativeRosterDiscoveryForTests(); + globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => { + const url = input instanceof Request ? input.url : String(input); + calls.push({ url, proxy: (init as { proxy?: unknown } | undefined)?.proxy }); + return respond(url); + }) as typeof fetch; + for (const id of ["routed", "bypass", "plain"]) { + saveCodexAccountCredential(id, { accessToken: `${id}-access`, refreshToken: `${id}-grant`, expiresAt: Date.now() + 3_600_000, chatgptAccountId: `acc-${id}` }); + } +}); + +afterEach(async () => { + globalThis.fetch = realFetch; + resetCodexAccountEgressConfigForTests(); + clearAccountQuota(); + for (const key of PROXY_ENV) { const value = savedEnv.get(key); if (value === undefined) delete process.env[key]; else process.env[key] = value; } + homeKeys.forEach((name, index) => { const value = previousHomes[index]; if (value === undefined) delete process.env[name]; else process.env[name] = value; }); + await flushConfigDirHardeningForTests(); + removeTreeWithRetry(home); +}); + +test("a pool account inherits the openai provider's route unless it names its own proxy", () => { + const config = poolConfig(); + config.codexAccounts!.push({ id: "__main__", email: "", isMain: true, egress: { proxy: ACCOUNT_PROXY } } as never); + expect(codexAccountRouting("routed", { config })).toMatchObject({ provider: { proxy: PROVIDER_PROXY }, account: { egress: { proxy: ACCOUNT_PROXY } } }); + expect(codexAccountRouting("bypass", { config })).toMatchObject({ provider: { proxy: PROVIDER_PROXY }, account: { egress: { noProxy: "example.invalid" } } }); + expect(codexAccountRouting("plain", { config })).toEqual({ provider: { proxy: PROVIDER_PROXY, noProxy: undefined } }); + expect(codexAccountRouting("__main__", { config })).toBeUndefined(); + // A stored credential the config does not list is refused; a new login takes the provider's route. + expect(() => codexAccountRouting("unknown", { config })).toThrow(CodexAccountRouteUnavailableError); + expect(codexAccountRouting("unknown", { config, newLogin: true })).toEqual({ provider: { proxy: PROVIDER_PROXY, noProxy: undefined } }); + delete config.providers.openai!.proxy; + expect(codexAccountRouting("plain", { config })).toBeUndefined(); // nothing configured: the process-wide route, unchanged +}); + +test("token refresh follows the account route, inheriting the provider's when the account names none", async () => { + saveConfig(poolConfig()); + for (const id of ["routed", "bypass", "plain"]) { + const generation = readCodexAccountRecord(id)!.generation; + await forceRefreshCodexPoolToken(id, { rejectedGeneration: generation, rejectedAccessToken: `${id}-access` }); + } + expect(calls.map(call => [call.url.startsWith("https://auth.openai.com/"), call.proxy])) + .toEqual([[true, ACCOUNT_PROXY], [true, PROVIDER_PROXY], [true, PROVIDER_PROXY]]); +}); + +test("a refresh whose explicit proxy the process NO_PROXY exempts is refused before any send", async () => { + saveConfig(poolConfig()); + process.env.NO_PROXY = "auth.openai.com"; + const generation = readCodexAccountRecord("routed")!.generation; + const error = await forceRefreshCodexPoolToken("routed", { rejectedGeneration: generation, rejectedAccessToken: "routed-access" }) + .then(() => null, (thrown: unknown) => thrown); + expect(calls).toEqual([]); + expect(error).toBeInstanceOf(ExplicitProxyExemptedError); + expect((error as Error).message).not.toContain("routed-grant"); +}); + +test("an unreadable config refuses the refresh rather than sending without the configured route", async () => { + writeFileSync(getConfigPath(), "{ not json"); + const generation = readCodexAccountRecord("routed")!.generation; + const error = await forceRefreshCodexPoolToken("routed", { rejectedGeneration: generation, rejectedAccessToken: "routed-access" }) + .then(() => null, (thrown: unknown) => thrown); + expect(calls).toEqual([]); + expect(error).toBeInstanceOf(CodexAccountRouteUnavailableError); +}); + +test("usage probes, initial and after a 401 refresh, leave by the account route", async () => { + bindCodexAccountEgressConfig(poolConfig()); + await fetchFreshPoolAccountQuota("routed", null, undefined, undefined, + async () => ({ accessToken: "routed-access", chatgptAccountId: "acc-routed", generation: readCodexAccountRecord("routed")!.generation }) as never); + await recoverPoolQuotaFrom401({ + accountId: "bypass", existing: null, configuredPlan: undefined, rejectedAccessToken: "bypass-access", + rejectedGeneration: readCodexAccountRecord("bypass")!.generation, resp: new Response("", { status: 401 }), quotaProbeEvidence: {}, + }); + const usage = calls.filter(call => call.url.includes("/wham/usage")); + const refresh = calls.filter(call => call.url.startsWith("https://auth.openai.com/")); + expect(usage.map(call => call.proxy)).toEqual([ACCOUNT_PROXY, PROVIDER_PROXY]); + expect(refresh.map(call => call.proxy)).toEqual([PROVIDER_PROXY]); +}); + +test("model discovery sends each account's credential by that account's route", async () => { + bindCodexAccountEgressConfig(poolConfig()); + const fetcher = globalThis.fetch; + await discoverCodexNativeRoster(poolConfig(), { fetcher, credentials: [ + { accountId: "routed", accessToken: "routed-access", chatgptAccountId: "acc-routed", credentialIdentity: "routed:1" }, + ] }); + const models = calls.filter(call => call.url.includes("/models")); + expect(models.length).toBeGreaterThan(0); + expect(models.every(call => call.proxy === ACCOUNT_PROXY)).toBe(true); +}); + +test("reset-credit inspection and consumption, manual and background, leave by the account route", async () => { + const config = poolConfig(); + bindCodexAccountEgressConfig(config); + await (await inspectResetCredits(config, "routed", new AbortController().signal)).text(); + await (await consumeResetCredits(config, "routed", undefined)).text(); + const client = createResetCreditWhamClient(config, "plain"); + await client.inspect(); + await client.consume("redeem-1"); + const credits = calls.filter(call => call.url.includes("/rate-limit-reset-credits")); + expect(credits.map(call => [call.url.endsWith("/consume"), call.proxy])).toEqual([ + [false, ACCOUNT_PROXY], [true, ACCOUNT_PROXY], [false, PROVIDER_PROXY], [true, PROVIDER_PROXY], + ]); +}); diff --git a/tests/lib/provider-egress-account.test.ts b/tests/lib/provider-egress-account.test.ts new file mode 100644 index 00000000000..4dc30565d09 --- /dev/null +++ b/tests/lib/provider-egress-account.test.ts @@ -0,0 +1,148 @@ +/** + * Per-account egress for Codex pool accounts (catch-up G-012): an account's own proxy / noProxy + * outranks the provider's, follows the account a request is sent with, and also carries that + * account's token refresh. + */ +import { afterAll, afterEach, beforeAll, beforeEach, expect, test } from "bun:test"; +import { mkdtempSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { + InvalidProviderEgressError, + poolAccountEgressConfigError, + resolveProviderEgress, + type PoolAccountRoute, +} from "../../src/lib/provider-egress"; +import { codexAccountEgressRoute } from "../../src/codex/account-egress"; +import { providerFetch } from "../../src/server/responses/fetch-helpers"; +import { saveConfig } from "../../src/config"; +import type { OcxConfig, OcxProviderConfig } from "../../src/types"; +import { removeTreeWithRetry } from "../helpers/remove-tree"; + +const URL_A = "https://chatgpt.com/backend-api/codex/responses"; +const account = (egress: PoolAccountRoute["egress"], id = "acct-a"): PoolAccountRoute => ({ id, scope: `codexAccounts.${id}.egress`, egress }); + +test("an account proxy outranks the provider's, and an account without one inherits it", () => { + const provider = { proxy: "http://provider.proxy:8080" }; + expect(resolveProviderEgress({ providerName: "openai", provider, url: URL_A, account: account({ proxy: "http://account.proxy:3128" }) })) + .toEqual({ kind: "proxy", proxyUrl: "http://account.proxy:3128/", transport: "http" }); + expect(resolveProviderEgress({ providerName: "openai", provider, url: URL_A, account: account({ noProxy: "example.com" }) })) + .toEqual({ kind: "proxy", proxyUrl: "http://provider.proxy:8080/", transport: "http" }); + expect(resolveProviderEgress({ providerName: "openai", provider, url: URL_A, account: account({ proxy: "direct" }) })) + .toEqual({ kind: "direct", reason: "configured" }); + expect(resolveProviderEgress({ providerName: "openai", provider, url: URL_A, account: account({ proxy: null }) })) + .toEqual({ kind: "direct", reason: "configured" }); + expect(resolveProviderEgress({ providerName: "openai", provider: {}, url: URL_A, account: account({ proxy: "socks5h://account.proxy:1080" }) })) + .toEqual({ kind: "proxy", proxyUrl: "socks5h://account.proxy:1080", transport: "socks5" }); + expect(resolveProviderEgress({ providerName: "openai", provider, url: URL_A })).toMatchObject({ proxyUrl: "http://provider.proxy:8080/" }); +}); + +test("account and provider bypass lists both apply", () => { + const provider = { proxy: "http://provider.proxy:8080", noProxy: "provider-only.example" }; + const viaAccount = account({ proxy: "http://account.proxy:3128", noProxy: ["chatgpt.com"] }); + expect(resolveProviderEgress({ providerName: "openai", provider, url: URL_A, account: viaAccount })).toEqual({ kind: "direct", reason: "noProxy" }); + expect(resolveProviderEgress({ providerName: "openai", provider, url: "https://provider-only.example/x", account: viaAccount })) + .toEqual({ kind: "direct", reason: "noProxy" }); + expect(resolveProviderEgress({ providerName: "openai", provider, url: "https://other.example/x", account: viaAccount })) + .toMatchObject({ proxyUrl: "http://account.proxy:3128/" }); +}); + +test("an invalid account value names the account's field, never the provider's", () => { + const thrown = (() => { + try { resolveProviderEgress({ providerName: "openai", provider: {}, url: URL_A, account: account({ proxy: "ftp://x" }) }); } + catch (error) { return error; } + })(); + expect(thrown).toBeInstanceOf(InvalidProviderEgressError); + expect((thrown as Error).message).toStartWith("codexAccounts.acct-a.egress.proxy is invalid:"); + expect(poolAccountEgressConfigError("codexAccounts.a.egress", { proxy: "http://ok.example:1" })).toBeNull(); + expect(poolAccountEgressConfigError("codexAccounts.a.egress", undefined)).toBeNull(); + expect(poolAccountEgressConfigError("codexAccounts.a.egress", { proxy: "" })).toStartWith("codexAccounts.a.egress.proxy is invalid:"); + expect(poolAccountEgressConfigError("codexAccounts.a.egress", { noProxy: [1] })).toStartWith("codexAccounts.a.egress.noProxy is invalid:"); + expect(poolAccountEgressConfigError("codexAccounts.a.egress", { proxy: "http://ok.example:1", weight: 2 })).toBe("codexAccounts.a.egress accepts only proxy and noProxy"); + expect(poolAccountEgressConfigError("codexAccounts.a.egress", "http://x")).toBe("codexAccounts.a.egress must be an object with optional proxy and noProxy"); +}); + +test("only pool accounts that configure a route get one", () => { + const config = { codexAccounts: [ + { id: "a", email: "", isMain: false, egress: { proxy: "http://a.proxy:1" } }, + { id: "b", email: "", isMain: false }, + { id: "__main__", email: "", isMain: true, egress: { proxy: "http://main.proxy:1" } }, + ] } as Pick; + expect(codexAccountEgressRoute(config, "a")).toEqual({ id: "a", scope: "codexAccounts.a.egress", egress: { proxy: "http://a.proxy:1" } }); + expect(codexAccountEgressRoute(config, "b")).toBeUndefined(); + expect(codexAccountEgressRoute(config, "__main__")).toBeUndefined(); + expect(codexAccountEgressRoute(config, null)).toBeUndefined(); +}); + +// Real sockets: two proxies, one destination. Each account's sends leave through its own proxy. +const hits = { dest: 0, a: 0, b: 0 }; +let dest: ReturnType; +let proxyA: ReturnType; +let proxyB: ReturnType; +const PROXY_ENV = ["NO_PROXY", "no_proxy", "HTTP_PROXY", "http_proxy", "HTTPS_PROXY", "https_proxy", "ALL_PROXY", "all_proxy"] as const; +const savedEnv = new Map(); +let home = ""; +const previousHome = process.env.OPENCODEX_HOME; + +beforeAll(() => { + dest = Bun.serve({ port: 0, hostname: "127.0.0.1", fetch: () => { hits.dest += 1; return new Response("dest"); } }); + proxyA = Bun.serve({ port: 0, hostname: "127.0.0.1", fetch: () => { hits.a += 1; return new Response("via-a"); } }); + proxyB = Bun.serve({ port: 0, hostname: "127.0.0.1", fetch: () => { hits.b += 1; return new Response("via-b"); } }); +}); +afterAll(() => { dest.stop(true); proxyA.stop(true); proxyB.stop(true); }); +beforeEach(() => { + for (const key of PROXY_ENV) { savedEnv.set(key, process.env[key]); delete process.env[key]; } + hits.dest = 0; hits.a = 0; hits.b = 0; + home = mkdtempSync(join(tmpdir(), "ocx-account-egress-")); + process.env.OPENCODEX_HOME = home; +}); +afterEach(() => { + for (const key of PROXY_ENV) { const value = savedEnv.get(key); if (value === undefined) delete process.env[key]; else process.env[key] = value; } + if (previousHome === undefined) delete process.env.OPENCODEX_HOME; else process.env.OPENCODEX_HOME = previousHome; + removeTreeWithRetry(home); +}); + +test("two accounts of one provider send through their own proxies, and a moved request follows its account", async () => { + const provider = { adapter: "openai-chat", baseUrl: `http://127.0.0.1:${dest.port}/v1` } as unknown as OcxProviderConfig; + const routes: Record = { + a: account({ proxy: `http://127.0.0.1:${proxyA.port}` }, "a"), + b: account({ proxy: `http://127.0.0.1:${proxyB.port}` }, "b"), + }; + let current = "a"; + const send = providerFetch(provider, undefined, { providerName: "pool", account: () => routes[current] }); + const target = `http://127.0.0.1:${dest.port}/v1/models`; + expect(await (await send(target)).text()).toBe("via-a"); + current = "b"; // failover moved the request to another pool account + expect(await (await send(target)).text()).toBe("via-b"); + expect(hits).toEqual({ dest: 0, a: 1, b: 1 }); + const plain = providerFetch(provider, undefined, { providerName: "pool" }); + expect(await (await plain(target)).text()).toBe("dest"); +}); + +test("an account's token refresh leaves through that account's route", async () => { + saveConfig({ + port: 0, defaultProvider: "openai", providers: {}, + codexAccounts: [ + { id: "routed", email: "", isMain: false, egress: { proxy: "http://127.0.0.1:9" } }, + { id: "plain", email: "", isMain: false }, + ], + } as unknown as OcxConfig); + const { forceRefreshCodexPoolToken, readCodexAccountRecord, saveCodexAccountCredential } = await import("../../src/codex/account-store"); + const seen: Array<{ url: string; proxy: unknown }> = []; + const originalFetch = globalThis.fetch; + globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => { + seen.push({ url: String(input), proxy: (init as { proxy?: unknown } | undefined)?.proxy }); + return new Response(JSON.stringify({ error: "server_error" }), { status: 503 }); + }) as typeof fetch; + try { + for (const id of ["routed", "plain"]) { + saveCodexAccountCredential(id, { accessToken: "rejected", refreshToken: `grant-${id}`, expiresAt: Date.now() + 3_600_000, chatgptAccountId: "acc" }); + const generation = readCodexAccountRecord(id)!.generation; + await forceRefreshCodexPoolToken(id, { rejectedGeneration: generation, rejectedAccessToken: "rejected" }).catch(() => undefined); + } + } finally { + globalThis.fetch = originalFetch; + } + expect(seen.map(call => call.proxy)).toEqual(["http://127.0.0.1:9/", undefined]); + expect(seen.every(call => call.url.startsWith("https://auth.openai.com/"))).toBe(true); +}); diff --git a/tests/providers/provider-quota.test.ts b/tests/providers/provider-quota.test.ts index 3668886271d..7bdc569f041 100644 --- a/tests/providers/provider-quota.test.ts +++ b/tests/providers/provider-quota.test.ts @@ -1,4 +1,5 @@ import { afterEach, beforeEach, describe, expect, setSystemTime, spyOn, test } from "bun:test"; +import { bindStoredCodexPoolRoutingForTests } from "../helpers/codex-pool-routing"; import { existsSync, mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { removeTreeWithRetry } from "../helpers/remove-tree"; import { tmpdir } from "node:os"; @@ -87,6 +88,7 @@ beforeEach(() => { opencodexHome = mkdtempSync(join(tmpdir(), "ocx-quota-")); codexHome = mkdtempSync(join(tmpdir(), "codex-quota-")); process.env.OPENCODEX_HOME = opencodexHome; + bindStoredCodexPoolRoutingForTests(); process.env.CODEX_HOME = codexHome; mkdirSync(codexHome, { recursive: true }); writeFileSync(join(codexHome, "auth.json"), JSON.stringify({ diff --git a/tests/responses/codex-installation-failover.test.ts b/tests/responses/codex-installation-failover.test.ts index f9a450c80db..100bc4af877 100644 --- a/tests/responses/codex-installation-failover.test.ts +++ b/tests/responses/codex-installation-failover.test.ts @@ -1,4 +1,5 @@ import { afterEach, beforeEach, expect, test } from "bun:test"; +import { bindStoredCodexPoolRoutingForTests } from "../helpers/codex-pool-routing"; import { createHash } from "node:crypto"; import { mkdtempSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; @@ -28,6 +29,7 @@ beforeEach(() => { home = mkdtempSync(join(tmpdir(), "ocx-installation-failover-")); previous = homeKeys.map(name => process.env[name]); for (const name of homeKeys) process.env[name] = home; + bindStoredCodexPoolRoutingForTests(); release = acquireOwnedSpendHome(); clear(); for (const id of ["work", "other"]) setAccountQuotaFromParsed(id, { weeklyPercent: 10 }); writeFileSync(join(home, "codex-accounts.json"), JSON.stringify(Object.fromEntries(["work", "other"].map(id => [id, { diff --git a/tests/responses/codex-pool-account-egress-compact.test.ts b/tests/responses/codex-pool-account-egress-compact.test.ts new file mode 100644 index 00000000000..4ee446cfbfd --- /dev/null +++ b/tests/responses/codex-pool-account-egress-compact.test.ts @@ -0,0 +1,82 @@ +/** + * Native compact carries a Codex pool account's credential, so it must leave by that account's + * route (catch-up G-012), read at the physical send: a compact moved from one pool account to + * another by a 429 takes the second account's route. + */ +import { afterEach, beforeEach, expect, test } from "bun:test"; +import { createHash } from "node:crypto"; +import { mkdtempSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { clearAccountNeedsReauth } from "../../src/codex/auth-api"; +import { clearAccountQuota, setAccountQuotaFromParsed } from "../../src/codex/quota"; +import { clearCodexUpstreamHealth, clearThreadAccountMap } from "../../src/codex/routing"; +import { clearPoolRotationState } from "../../src/codex/pool-rotation"; +import { bindCodexAccountEgressConfig, resetCodexAccountEgressConfigForTests } from "../../src/codex/account-egress-runtime"; +import { clearPoolRecoveryState } from "../../src/routing/probe-lease"; +import { handleResponsesCompact } from "../../src/server/responses"; +import { acquireOwnedSpendHome } from "../helpers/owned-spend-home"; +import { drainAndRemoveFixtureRoots } from "../helpers/fixture-teardown"; +import type { OcxConfig } from "../../src/types"; + +const PROXY_WORK = "http://127.0.0.1:9/"; +const PROXY_OTHER = "http://127.0.0.1:11/"; +const realFetch = globalThis.fetch; +const homeKeys = ["OPENCODEX_HOME", "CODEX_HOME"] as const; +const PROXY_ENV = ["NO_PROXY", "no_proxy", "HTTP_PROXY", "http_proxy", "HTTPS_PROXY", "https_proxy", "ALL_PROXY", "all_proxy"] as const; +const savedEnv = new Map(); +let home: string; +let previous: Array; +let release: () => void; +function clear() { + clearAccountQuota(); clearCodexUpstreamHealth(); clearThreadAccountMap(); clearPoolRotationState(); clearPoolRecoveryState(); + for (const id of ["work", "other"]) clearAccountNeedsReauth(id); + resetCodexAccountEgressConfigForTests(); +} +beforeEach(() => { + for (const key of PROXY_ENV) { savedEnv.set(key, process.env[key]); delete process.env[key]; } + home = mkdtempSync(join(tmpdir(), "ocx-compact-account-egress-")); + previous = homeKeys.map(name => process.env[name]); + for (const name of homeKeys) process.env[name] = home; + release = acquireOwnedSpendHome(); clear(); + for (const id of ["work", "other"]) setAccountQuotaFromParsed(id, { weeklyPercent: 10 }); + writeFileSync(join(home, "codex-accounts.json"), JSON.stringify(Object.fromEntries(["work", "other"].map(id => [id, { + credential: { accessToken: `${id}-access`, refreshToken: `${id}-grant`, expiresAt: Date.now() + 3_600_000, chatgptAccountId: `acc-${id}` }, + generation: 1, refreshGrantFingerprint: createHash("sha256").update(`codex-refresh-grant:${id}-grant`).digest("hex"), + }])))); +}); +afterEach(async () => { + globalThis.fetch = realFetch; release(); clear(); + for (const key of PROXY_ENV) { const value = savedEnv.get(key); if (value === undefined) delete process.env[key]; else process.env[key] = value; } + await drainAndRemoveFixtureRoots({ roots: [{ path: home }], restoreEnvironment: () => { + homeKeys.forEach((name, i) => { if (previous[i] === undefined) delete process.env[name]; else process.env[name] = previous[i]; }); + } }); +}); +const config = (): OcxConfig => ({ port: 0, defaultProvider: "openai", activeCodexAccountId: "work", autoSwitchThreshold: 0, + accountPoolStrategy: "round-robin", codexAccounts: [ + { id: "work", label: "work", egress: { proxy: PROXY_WORK } }, + { id: "other", label: "other", egress: { proxy: PROXY_OTHER } }, + ], + providers: { openai: { adapter: "openai-responses", baseUrl: "https://chatgpt.com/backend-api/codex", authMode: "forward", codexAccountMode: "pool", upstreamWebsocket: false } }, +} as OcxConfig); + +test("a compact moved from one pool account to another by a 429 leaves by each account's own route", async () => { + const cfg = config(); + bindCodexAccountEgressConfig(cfg); + const sends: Array<{ account: string | null; proxy: unknown }> = []; + globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => { + const url = String(input instanceof Request ? input.url : input); + if (!url.endsWith("/responses/compact")) return Response.json({ rate_limit: { primary_window: { used_percent: 10 } } }); + const headers = new Headers(init?.headers); + sends.push({ account: headers.get("chatgpt-account-id"), proxy: (init as { proxy?: unknown } | undefined)?.proxy }); + return headers.get("authorization") === "Bearer work-access" + ? Response.json({ error: { message: "You have hit your usage limit." } }, { status: 429, headers: { "retry-after": "600" } }) + : Response.json({ id: "resp_done", object: "response.compaction", status: "completed", output: [] }); + }) as typeof fetch; + const req = new Request("http://localhost/v1/responses/compact", { method: "POST", headers: { "content-type": "application/json" }, + body: JSON.stringify({ model: "gpt-5.5", input: [], stream: false }) }); + const response = await handleResponsesCompact(req, cfg, { model: "", provider: "" }); + await response.text(); + expect(response.status).toBe(200); + expect(sends).toEqual([{ account: "acc-work", proxy: PROXY_WORK }, { account: "acc-other", proxy: PROXY_OTHER }]); +}); diff --git a/tests/responses/combo-replay-refusal-attribution.test.ts b/tests/responses/combo-replay-refusal-attribution.test.ts index 77d407029da..0b453309551 100644 --- a/tests/responses/combo-replay-refusal-attribution.test.ts +++ b/tests/responses/combo-replay-refusal-attribution.test.ts @@ -1,4 +1,5 @@ import { afterEach, beforeEach, expect, test } from "bun:test"; +import { bindStoredCodexPoolRoutingForTests } from "../helpers/codex-pool-routing"; import type { ServerWebSocket } from "bun"; import { saveConfig } from "../../src/config"; import { startServer } from "../../src/server"; @@ -43,6 +44,7 @@ function clearRouting(): void { beforeEach(() => { home = createTempHome("ocx-combo-refusal-"); + bindStoredCodexPoolRoutingForTests(); release = acquireOwnedSpendHome(); clearRouting(); clearRequestLogsForTests(); diff --git a/tests/responses/direct-credit-renewal-ingress.test.ts b/tests/responses/direct-credit-renewal-ingress.test.ts index 3df9a1c9fe2..0e7ef449e3b 100644 --- a/tests/responses/direct-credit-renewal-ingress.test.ts +++ b/tests/responses/direct-credit-renewal-ingress.test.ts @@ -1,4 +1,5 @@ import { afterEach, beforeEach, expect, spyOn, test } from "bun:test"; +import { bindStoredCodexPoolRoutingForTests } from "../helpers/codex-pool-routing"; import { mkdtempSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -38,6 +39,7 @@ beforeEach(() => { previousHome = process.env.OPENCODEX_HOME; home = mkdtempSync(join(tmpdir(), "ocx-direct-credit-ingress-")); process.env.OPENCODEX_HOME = home; + bindStoredCodexPoolRoutingForTests(); codexHome = installIsolatedCodexHome("ocx-credit-ingress-native-"); releaseSpendHome = acquireOwnedSpendHome(); clearAccountQuota(); clearCodexQuotaPrimeState(); resetQuotaQueryBackoffForTests(); diff --git a/tests/responses/native-compaction-gateway-credentials.test.ts b/tests/responses/native-compaction-gateway-credentials.test.ts index 035a6fe1bee..e1f0e4d5859 100644 --- a/tests/responses/native-compaction-gateway-credentials.test.ts +++ b/tests/responses/native-compaction-gateway-credentials.test.ts @@ -1,4 +1,5 @@ import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test"; +import { bindStoredCodexPoolRoutingForTests } from "../helpers/codex-pool-routing"; import * as registry from "../../src/providers/registry"; import * as authContext from "../../src/codex/auth-context"; import { mkdtempSync, writeFileSync } from "node:fs"; @@ -82,6 +83,7 @@ beforeEach(() => { previousOcxHome = process.env.OPENCODEX_HOME; previousCodexHome = process.env.CODEX_HOME; process.env.OPENCODEX_HOME = home; + bindStoredCodexPoolRoutingForTests(); process.env.CODEX_HOME = home; releaseSpendHome = acquireOwnedSpendHome(); for (const id of ["work", "other"]) clearAccountNeedsReauth(id); diff --git a/tests/responses/pool-retry-client-metadata.test.ts b/tests/responses/pool-retry-client-metadata.test.ts index 02bd7aa56b6..2661bf84c98 100644 --- a/tests/responses/pool-retry-client-metadata.test.ts +++ b/tests/responses/pool-retry-client-metadata.test.ts @@ -1,4 +1,5 @@ import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { bindStoredCodexPoolRoutingForTests } from "../helpers/codex-pool-routing"; import { createHash } from "node:crypto"; import { mkdtempSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; @@ -112,6 +113,7 @@ beforeEach(() => { previousHomes = HOME_KEYS.map(key => process.env[key]); home = mkdtempSync(join(tmpdir(), "ocx-pool-retry-metadata-")); for (const key of HOME_KEYS) process.env[key] = home; + bindStoredCodexPoolRoutingForTests(); releaseSpendHome = acquireOwnedSpendHome(); clearPoolState(); for (const id of [WORK, OTHER]) setAccountQuotaFromParsed(id, { weeklyPercent: 10 }); diff --git a/tests/responses/responses-pool-401-refresh.test.ts b/tests/responses/responses-pool-401-refresh.test.ts index 27d37520fc8..760ed7d1d4a 100644 --- a/tests/responses/responses-pool-401-refresh.test.ts +++ b/tests/responses/responses-pool-401-refresh.test.ts @@ -1,4 +1,5 @@ import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test"; +import { bindStoredCodexPoolRoutingForTests } from "../helpers/codex-pool-routing"; import { existsSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -268,6 +269,7 @@ beforeEach(() => { previousCodexHome = process.env.CODEX_HOME; process.env.OPENCODEX_HOME = home; process.env.CODEX_HOME = home; + bindStoredCodexPoolRoutingForTests(); // Direct handler dispatches need the writer lease that startServer normally holds. releaseSpendHome = acquireOwnedSpendHome(); clearAccountNeedsReauth(ACCOUNT_ID); diff --git a/tests/server/management-provider-validation.test.ts b/tests/server/management-provider-validation.test.ts index f8f74cf6926..49223a774ae 100644 --- a/tests/server/management-provider-validation.test.ts +++ b/tests/server/management-provider-validation.test.ts @@ -1,4 +1,5 @@ import { config, registerRelativeSendPathTests } from "../helpers/management-relative-send-paths"; +import { bindStoredCodexPoolRoutingForTests } from "../helpers/codex-pool-routing"; import { afterEach, beforeEach, describe, expect, setDefaultTimeout, spyOn, test } from "bun:test"; import { managementFetch as fetch, ManagementRequest as Request } from "../helpers/management-auth"; import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs"; @@ -1088,6 +1089,7 @@ describe("provider management validation", () => { expiresAt: now + 60_000, chatgptAccountId: "chatgpt-entitlement-diagnostic", }); + bindStoredCodexPoolRoutingForTests(); const generation = readCodexAccountRecord(accountId)!.generation; const storedCredential: CodexModelEntitlementCredentialSnapshot = { accountId, diff --git a/tests/usage/quota-401-recovery-runtime.test.ts b/tests/usage/quota-401-recovery-runtime.test.ts index af26b89487c..32ac1f64a66 100644 --- a/tests/usage/quota-401-recovery-runtime.test.ts +++ b/tests/usage/quota-401-recovery-runtime.test.ts @@ -1,4 +1,5 @@ import { afterEach, beforeEach, expect, test } from "bun:test"; +import { bindStoredCodexPoolRoutingForTests } from "../helpers/codex-pool-routing"; import { mkdtempSync} from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -25,6 +26,7 @@ beforeEach(async () => { home = mkdtempSync(join(tmpdir(), "ocx-quota-401-")); process.env.OPENCODEX_HOME = home; originalFetch = globalThis.fetch; + bindStoredCodexPoolRoutingForTests(); const { resetQuotaRecoveryForTests } = await import("../../src/codex/quota-401-recovery"); resetQuotaRecoveryForTests(); });