From 1ad31b6256d4b1dd0f0c3ce2d314cbb93485b9ad Mon Sep 17 00:00:00 2001 From: JUN Date: Wed, 25 Nov 2026 12:11:08 +0900 Subject: [PATCH 01/20] fix(egress): keep an explicit provider proxy authoritative over process NO_PROXY --- .../es/reference/configuration/providers.md | 2 +- .../docs/reference/configuration/providers.md | 5 + .../test-layout/layout-server-inbound.json | 1 + src/lib/provider-outbound.ts | 7 +- src/lib/proxy-env.ts | 33 +++++++ src/server/responses/ws-upstream.ts | 5 +- structure/transports/inventory.md | 6 +- tests/fixtures/test-layout-expected.json | 2 +- tests/lib/explicit-proxy-no-proxy.test.ts | 97 +++++++++++++++++++ .../provider-egress-outbound.test.ts | 16 +-- 10 files changed, 160 insertions(+), 14 deletions(-) create mode 100644 tests/lib/explicit-proxy-no-proxy.test.ts 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 08174bb0057..39697ef5cdc 100644 --- a/docs-site/src/content/docs/es/reference/configuration/providers.md +++ b/docs-site/src/content/docs/es/reference/configuration/providers.md @@ -221,7 +221,7 @@ Los proveedores pueden exponer una abreviatura incorporada, como `agy` para `goo | --- | --- | --- | | `adapter` | `string` | Uno de `openai-chat`, `openai-responses`, `anthropic`, `claude-cli`, `step-cli`, `google`, `kiro`, `cursor`, `ollama-native`, `azure-openai` (o alias `azure`), `codebuddy`, `qoder`. | | `baseUrl` | `string` | URL de base ascendente API. La mayoría de los puntos finales fijos incorporados ignoran una falta de coincidencia; los ajustes preestablecidos de clave seguros contra colisiones conservan un destino personalizado con el mismo nombre más antiguo. | -| `proxy?` | `string \| null` | Ruta de salida por proveedor. Omita que herede la decisión de proxy global; use `"direct"` o `null` para forzar la salida directa; o proporcione una URL proxy absoluta `http://`, `https://`, `socks5://` o `socks5h://`. Se rechaza una cadena vacía. | +| `proxy?` | `string \| null` | Ruta de salida por proveedor. Omita que herede la decisión de proxy global; use `"direct"` o `null` para forzar la salida directa; o proporcione una URL proxy absoluta `http://`, `https://`, `socks5://` o `socks5h://`. Se rechaza una cadena vacía. Un `proxy` HTTP(S) no se combina con una entrada de `NO_PROXY` del proceso que coincida con el mismo destino, porque el entorno de ejecución se conectaría directamente: esa solicitud se rechaza. Para conectar directamente, añada el host a `noProxy` del proveedor. | | `noProxy?` | `string \| string[]` | Destinos a los que este proveedor llega directamente, utilizando la sintaxis de patrón de host `NO_PROXY`. Una coincidencia pasa por alto tanto el propio proxy de este proveedor como un proxy global heredado. | | `requestPacing?` | `{ enabled, requestsPerMinute?, minIntervalMs?, maxConcurrentRequests?, models?, keySelection?, keys? }` | Indicadores opcionales de inicio de solicitud de salida del lado del cliente, separados del uso ascendente, la facturación y los indicadores de límite de solicitudes. RPM se convierte en un intervalo uniforme; `minIntervalMs` puede imponer un intervalo más largo. `maxConcurrentRequests` es un límite de enteros positivo en las solicitudes en vuelo. Una regla de proveedor o modelo puede usar el límite de concurrencia solo; los límites de proveedor se aplican a todos los modelos, mientras que las entradas `models` usan ID de modelo ascendente exactos (por ejemplo, `nvidia/llama-3.1-nemotron-ultra-253b-v1`) y solo pueden agregar retardo o concurrencia estrecha. Los esperas de cola no consumen el tiempo de espera del encabezado de respuesta ascendente. HTTP y el adaptador explícito `fetchResponse` / `runTurn` despachos están cubiertos. Un giro canónico Responses WebSocket con límite de concurrencia usa HTTP / SSE para que su arrendamiento pueda liberarse cuando el cuerpo de respuesta se complete, se equivoque o se cancele. Para los adaptadores `runTurn`, incluyendo Cursor, el cap cuenta los giros activos en lugar de los envíos físicos: RunSSE y BidiAppend pueden superponerse en un giro, mientras que otro turno espera. Seguimiento envía todavía obedecer intervalos de inicio. | | `requestPacing.keySelection?` | `"active"`, `"round-robin"` | Selección normal de la tecla de petición. El valor predeterminado `active` conserva la clave guardada y la rotación de fallas existente; `round-robin` distribuye las selecciones locales de solicitud a través de referencias de grupo de claves API elegibles sin cambiar la clave activa guardada. Equilibra las asignaciones, no los tokens o el costo. | diff --git a/docs-site/src/content/docs/reference/configuration/providers.md b/docs-site/src/content/docs/reference/configuration/providers.md index 1f1810476d4..7dc9d8ea81d 100644 --- a/docs-site/src/content/docs/reference/configuration/providers.md +++ b/docs-site/src/content/docs/reference/configuration/providers.md @@ -599,6 +599,11 @@ to choose direct egress explicitly. evaluated for each request. A matching destination goes direct whether the provider would otherwise use its own `proxy` or inherit a global proxy. +An HTTP(S) `proxy` on a provider and a process `NO_PROXY` entry that matches the same destination +cannot both apply, because the runtime would connect directly. Such a request is refused rather than +sent without the configured proxy. List the host in the provider's `noProxy` to connect directly, or +remove it from `NO_PROXY` to keep the proxy. A `socks5://` or `socks5h://` proxy is not affected. + #### What the route covers The route is applied to routed inference, provider discovery and connection tests, and API-key diff --git a/scripts/test-layout/layout-server-inbound.json b/scripts/test-layout/layout-server-inbound.json index 55e5756d102..13ec55a193e 100644 --- a/scripts/test-layout/layout-server-inbound.json +++ b/scripts/test-layout/layout-server-inbound.json @@ -1,4 +1,5 @@ { + "explicit-proxy-no-proxy.test.ts": "lib", "gemini-native.test.ts": "server", "gemini-native-wire.test.ts": "server", "gemini-native-routes.test.ts": "server", diff --git a/src/lib/provider-outbound.ts b/src/lib/provider-outbound.ts index 939fabe4b30..fc57ff1a173 100644 --- a/src/lib/provider-outbound.ts +++ b/src/lib/provider-outbound.ts @@ -311,9 +311,10 @@ async function providerOutboundRequest( // proxy-only DNS answers. // // A provider route replaces that decision outright rather than combining with it. An - // explicit provider proxy applies even where global NO_PROXY exempts the host, because the - // operator named this proxy for this provider; `providers..noProxy` is the exemption - // that belongs to that choice, and `resolveProviderEgress` has already applied it. A + // explicit provider proxy is never traded for direct egress where global NO_PROXY exempts the + // host: `configuredOutboundFetch` refuses that send, because Bun would skip the proxy there. + // `providers..noProxy` is the exemption that belongs to the operator's choice, and + // `resolveProviderEgress` has already applied it. A // provider pinned to `direct` keeps the DNS-pinned transport, which reaches the peer // through no proxy at all — the one route on this path that needs nothing from Bun. const proxyApplies = egress.kind === "inherit" diff --git a/src/lib/proxy-env.ts b/src/lib/proxy-env.ts index 3222cdff7b3..fa493586109 100644 --- a/src/lib/proxy-env.ts +++ b/src/lib/proxy-env.ts @@ -201,6 +201,32 @@ export function socks5ProxyFromEnv(env: ProxyEnvMap = process.env): string | und */ export type ProxyCapableRequestInit = RequestInit & { proxy?: string | false }; +/** A request named an HTTP(S) proxy for a destination the process `NO_PROXY` exempts. */ +export class ExplicitProxyExemptedError extends Error { + override readonly name = "ExplicitProxyExemptedError"; + readonly code = "explicit_proxy_exempted"; +} + +/** + * Whether the process `NO_PROXY` or `no_proxy` exempts `url`. + * + * Bun's fetch and WebSocket connect directly to such a destination even when the request names a + * proxy, as a string or as `{ url }`; only `proxy: false` outranks the environment. Each spelling + * is checked on its own because either one is enough for Bun to skip the proxy. + */ +export function processNoProxyExempts(url: URL, env: ProxyEnvMap = process.env): boolean { + return [env.NO_PROXY, env.no_proxy].some(value => + typeof value === "string" && value.trim() !== "" && noProxyMatches(url, { NO_PROXY: value })); +} + +/** The refusal for an explicit HTTP(S) proxy that the process environment would make Bun skip. */ +export function explicitProxyExemptedError(url: URL): ExplicitProxyExemptedError { + return new ExplicitProxyExemptedError( + `the configured proxy for ${url.origin} cannot be applied because NO_PROXY in the process environment ` + + "exempts this destination; remove it from NO_PROXY to keep the proxy, or list it in the provider's noProxy to connect directly", + ); +} + export function configuredOutboundFetch( input: RequestInfo | URL, init?: RequestInit, @@ -224,6 +250,13 @@ export function configuredOutboundFetch( } catch { return base!(input, init); } + // An HTTP(S) proxy string reaches Bun's fetch as `init.proxy`, and Bun ignores it for a + // destination the process NO_PROXY exempts. The caller named this proxy, so the request must not + // leave without it: refuse instead. SOCKS5 strings never reach Bun's proxy option (below). + if (typeof explicitProxy === "string" && !isSocks5ProxyUrl(explicitProxy) + && (url.protocol === "http:" || url.protocol === "https:") && processNoProxyExempts(url)) { + return Promise.reject(explicitProxyExemptedError(url)); + } // A mixed inherited SOCKS/HTTP ALL_PROXY environment cannot put bare "localhost" in // NO_PROXY: Bun would also bypass its HTTP proxy for app.localhost. Keep the name exact // here and force native fetch direct so the opposite-case HTTP proxy cannot take over. diff --git a/src/server/responses/ws-upstream.ts b/src/server/responses/ws-upstream.ts index 2b088dd24e5..88e1a40aba8 100644 --- a/src/server/responses/ws-upstream.ts +++ b/src/server/responses/ws-upstream.ts @@ -18,7 +18,7 @@ import type { NativeResponseControl } from "./native-response-control"; import { codexWsReuseAcrossTurnsEnabled } from "../../config/codex-ws-reuse-setting"; import { compareBunVersions } from "../../lib/bun-stream-caps"; -import { resolveProxyRoute, socks5ProxyFromEnv } from "../../lib/proxy-env"; +import { processNoProxyExempts, resolveProxyRoute, socks5ProxyFromEnv } from "../../lib/proxy-env"; import { estimateTokens } from "../../lib/token-estimate"; import type { CodexWsQuotaObserver } from "./codex-ws-metadata"; import { CODEX_RESPONSES_HTTP_URL, CODEX_RESPONSES_WS_URL, CODEX_WS_FRAME_HEADERS, prepareCodexHttpInit, prepareCodexWsRequest } from "./codex-ws-request"; @@ -214,6 +214,9 @@ export async function codexWsUpstreamFetch( } const wsUrl = wsUpstreamUrlFor(url); + // Bun's WebSocket also skips an explicit proxy for a destination the process NO_PROXY exempts. + // The HTTP path refuses that route rather than dialing around it. + if (explicitProxy && processNoProxyExempts(new URL(wsUrl))) return sseFallback(url, init); const proxyRoute = explicitProxy ? { kind: "proxy" as const, proxy: explicitProxy } : resolveProxyRoute(new URL(wsUrl)); if (proxyRoute.kind === "fallback") return sseFallback(url, init); const proxy = proxyRoute.kind === "proxy" ? proxyRoute.proxy : undefined; diff --git a/structure/transports/inventory.md b/structure/transports/inventory.md index 75f49e69e55..2752239a84b 100644 --- a/structure/transports/inventory.md +++ b/structure/transports/inventory.md @@ -195,7 +195,11 @@ Kiro generation in `src/adapters/kiro-retry.ts` passes the routed provider execu A reset-triggered rebuild may retarget the request to another region's canonical host mid-flight; that admission is marked `rebasedTarget` and does not consume or require an unused transition/alternate-target allowance (the total-send and replay-safety checks still apply), and the alternate-host fallback resolves the legacy gateway from the current request URL so rebuilt credentials stay with their own region. `src/lib/provider-egress.ts` resolves a provider route for one destination. The route is carried only -by transports that can preserve that request-local decision: +by transports that can preserve that request-local decision. An explicit HTTP(S) proxy is never sent +toward a destination that the process `NO_PROXY` or `no_proxy` exempts, because Bun's fetch and +WebSocket connect directly there: `configuredOutboundFetch` refuses the send with +`ExplicitProxyExemptedError`, and the Responses WebSocket upstream leaves such a turn to that HTTP path. +`tests/lib/explicit-proxy-no-proxy.test.ts` checks the route on real loopback sockets. | Request path | Per-provider route | Current contract | | --- | --- | --- | diff --git a/tests/fixtures/test-layout-expected.json b/tests/fixtures/test-layout-expected.json index f91b3cd8849..62d6195715a 100644 --- a/tests/fixtures/test-layout-expected.json +++ b/tests/fixtures/test-layout-expected.json @@ -1,4 +1,4 @@ -{ "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", +{ "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/lib/explicit-proxy-no-proxy.test.ts b/tests/lib/explicit-proxy-no-proxy.test.ts new file mode 100644 index 00000000000..c0d1323b91c --- /dev/null +++ b/tests/lib/explicit-proxy-no-proxy.test.ts @@ -0,0 +1,97 @@ +/** + * An explicit provider HTTP(S) proxy stays authoritative over the process NO_PROXY. + * + * Bun's fetch connects directly to a destination the process NO_PROXY exempts, even when the + * request names a proxy. These cases use a real transport (two loopback listeners) because a + * mocked fetch only sees the option, not the route the request actually takes. + */ +import { afterAll, afterEach, beforeAll, beforeEach, expect, test } from "bun:test"; +import { + configuredOutboundFetch, + ExplicitProxyExemptedError, + processNoProxyExempts, + type ProxyCapableRequestInit, +} from "../../src/lib/proxy-env"; +import { providerEgressFetchInit, resolveProviderEgress } from "../../src/lib/provider-egress"; + +const ENV_KEYS = ["NO_PROXY", "no_proxy", "HTTP_PROXY", "http_proxy", "HTTPS_PROXY", "https_proxy", "ALL_PROXY", "all_proxy"] as const; +const saved = new Map(); +const hits = { dest: 0, proxy: 0 }; +let dest: ReturnType; +let proxy: ReturnType; +let destUrl: string; +let proxyUrl: string; + +beforeAll(() => { + dest = Bun.serve({ port: 0, hostname: "127.0.0.1", fetch: () => { hits.dest += 1; return new Response("dest"); } }); + proxy = Bun.serve({ port: 0, hostname: "127.0.0.1", fetch: () => { hits.proxy += 1; return new Response("proxy"); } }); + destUrl = `http://127.0.0.1:${dest.port}/v1/models`; + proxyUrl = `http://127.0.0.1:${proxy.port}`; +}); +afterAll(() => { dest.stop(true); proxy.stop(true); }); +beforeEach(() => { + for (const key of ENV_KEYS) { saved.set(key, process.env[key]); delete process.env[key]; } + hits.dest = 0; + hits.proxy = 0; +}); +afterEach(() => { + for (const key of ENV_KEYS) { + const value = saved.get(key); + if (value === undefined) delete process.env[key]; else process.env[key] = value; + } +}); + +const send = (init: ProxyCapableRequestInit) => + configuredOutboundFetch(destUrl, { ...init, headers: { authorization: "Bearer synthetic-test-token" } } as RequestInit); + +test("without NO_PROXY the explicit proxy carries the request", async () => { + const response = await send({ proxy: proxyUrl }); + expect(await response.text()).toBe("proxy"); + expect(hits).toEqual({ dest: 0, proxy: 1 }); +}); + +for (const spelling of ["NO_PROXY", "no_proxy"] as const) { + for (const entry of ["127.0.0.1", "*"]) { + test(`a process ${spelling}=${entry} never sends an explicit-proxy request directly`, async () => { + process.env[spelling] = entry; + const error = await send({ proxy: proxyUrl }).then(() => null, (cause: unknown) => cause); + expect(error).toBeInstanceOf(ExplicitProxyExemptedError); + expect((error as ExplicitProxyExemptedError).code).toBe("explicit_proxy_exempted"); + expect((error as Error).message).not.toContain("synthetic-test-token"); + expect(hits).toEqual({ dest: 0, proxy: 0 }); + }); + } +} + +test("a provider proxy route resolved by the egress authority is refused the same way", async () => { + process.env.NO_PROXY = "127.0.0.1"; + const egress = resolveProviderEgress({ providerName: "p", provider: { proxy: proxyUrl }, url: destUrl }); + expect(egress.kind).toBe("proxy"); + await expect(send(providerEgressFetchInit(egress))).rejects.toBeInstanceOf(ExplicitProxyExemptedError); + expect(hits).toEqual({ dest: 0, proxy: 0 }); +}); + +test("the provider's own noProxy remains the way to connect such a host directly", async () => { + process.env.NO_PROXY = "127.0.0.1"; + const egress = resolveProviderEgress({ providerName: "p", provider: { proxy: proxyUrl, noProxy: "127.0.0.1" }, url: destUrl }); + expect(egress).toEqual({ kind: "direct", reason: "noProxy" }); + expect(await (await send(providerEgressFetchInit(egress))).text()).toBe("dest"); + expect(hits).toEqual({ dest: 1, proxy: 0 }); +}); + +test("an inherited route and proxy:false keep their existing behavior", async () => { + process.env.NO_PROXY = "127.0.0.1"; + expect(await (await send({})).text()).toBe("dest"); + expect(await (await send({ proxy: false })).text()).toBe("dest"); + expect(hits).toEqual({ dest: 2, proxy: 0 }); +}); + +test("exemption matching covers both spellings, wildcards, domains and WebSocket destinations", () => { + const url = new URL("wss://chatgpt.com/backend-api/codex/responses"); + expect(processNoProxyExempts(url, {})).toBe(false); + expect(processNoProxyExempts(url, { NO_PROXY: "example.com" })).toBe(false); + expect(processNoProxyExempts(url, { NO_PROXY: ".chatgpt.com" })).toBe(true); + expect(processNoProxyExempts(url, { no_proxy: "chatgpt.com" })).toBe(true); + expect(processNoProxyExempts(url, { NO_PROXY: "example.com", no_proxy: "*" })).toBe(true); + expect(processNoProxyExempts(url, { NO_PROXY: " " })).toBe(false); +}); diff --git a/tests/providers/provider-egress-outbound.test.ts b/tests/providers/provider-egress-outbound.test.ts index bdf233dc1df..862a4cbcb58 100644 --- a/tests/providers/provider-egress-outbound.test.ts +++ b/tests/providers/provider-egress-outbound.test.ts @@ -113,24 +113,26 @@ describe("per-provider egress on the discovery and quota transport", () => { } }); - test("a provider proxy applies where global NO_PROXY exempts the host", async () => { - // The operator named this proxy for this provider. A global bypass list describes the - // global route and must not silently cancel the provider's own choice; the exemption that - // belongs to that choice is providers..noProxy, asserted below. + test("a provider proxy is never traded for direct egress where global NO_PROXY exempts the host", async () => { + // The operator named this proxy for this provider, but Bun skips a request-scoped proxy for a + // destination the process NO_PROXY exempts and would connect directly. The send is refused + // instead; the exemption that belongs to the provider's choice is providers..noProxy, + // asserted below. tests/lib/explicit-proxy-no-proxy.test.ts proves the route on a real socket. for (const key of proxyKeys) delete process.env[key]; process.env.HTTPS_PROXY = GLOBAL_PROXY; process.env.NO_PROXY = "provider.example"; process.env.no_proxy = "provider.example"; const { providerOutboundGet } = await import("../../src/lib/provider-outbound"); + const { ExplicitProxyExemptedError } = await import("../../src/lib/proxy-env"); const { dependencies } = pinnedDependencies(); const proxied = captureProxiedFetch(); try { - await providerOutboundGet( + await expect(providerOutboundGet( "vendor", { baseUrl: "https://provider.example", proxy: PROVIDER_PROXY }, MODELS_URL, {}, dependencies, - ); - expect(proxied.calls).toEqual([`${PROVIDER_PROXY}/`]); + )).rejects.toBeInstanceOf(ExplicitProxyExemptedError); + expect(proxied.calls).toEqual([]); } finally { proxied.restore(); } From 3a165a522b4eef5059ef8ea8c431cfb460d0e1f1 Mon Sep 17 00:00:00 2001 From: JUN Date: Wed, 25 Nov 2026 12:17:20 +0900 Subject: [PATCH 02/20] fix(egress): match NO_PROXY as broadly as Bun and guard the ChatHub socket dial --- src/adapters/m365-copilot/transport.ts | 11 ++++-- src/lib/proxy-env.ts | 43 ++++++++++++++++++++--- structure/transports/inventory.md | 6 ++-- tests/lib/explicit-proxy-no-proxy.test.ts | 34 ++++++++++++++++-- tests/providers/m365-copilot.test.ts | 19 ++++++++-- 5 files changed, 100 insertions(+), 13 deletions(-) diff --git a/src/adapters/m365-copilot/transport.ts b/src/adapters/m365-copilot/transport.ts index d476ba57142..c81efee294b 100644 --- a/src/adapters/m365-copilot/transport.ts +++ b/src/adapters/m365-copilot/transport.ts @@ -1,7 +1,7 @@ import { m365CopilotClaims } from "../../oauth/m365-copilot"; import { getToneForModel, m365CopilotScenario, M365_COPILOT_BASE_URL } from "../../providers/m365-copilot-models"; import { resolveProviderEgress, providerSocketRoute } from "../../lib/provider-egress"; -import { effectiveProxyFor, noProxyMatches } from "../../lib/proxy-env"; +import { effectiveProxyFor, explicitProxyExemptedError, isSocks5ProxyUrl, noProxyMatches, processNoProxyExempts } from "../../lib/proxy-env"; import type { OcxProviderConfig } from "../../types"; import type { TranslatorBudget } from "../../lib/translator-budget"; import { isTranslatorBudgetExceededError } from "../../lib/translator-budget"; @@ -98,7 +98,14 @@ export function m365SocketDialOptions(route: M365TurnOptions["route"], url: stri route = m365RequestSocketRoute(route); if (typeof route.fetch === "function") throw new M365CopilotTurnError("Microsoft 365 Copilot ChatHub cannot use a custom fetch executor; remove providers.m365-copilot.fetch", 400); const egress = resolveProviderEgress({ providerName: "m365-copilot", provider: route, url }); - if (egress.kind === "proxy") return proxyDialOptions(egress.proxyUrl, headers); + if (egress.kind === "proxy") { + // Bun's WebSocket skips an explicit proxy for a destination the process NO_PROXY exempts and + // would connect directly; this socket's URL carries the access token, so refuse instead. + if (!isSocks5ProxyUrl(egress.proxyUrl) && processNoProxyExempts(new URL(url))) { + throw new M365CopilotTurnError(explicitProxyExemptedError(new URL(url)).message, 400); + } + return proxyDialOptions(egress.proxyUrl, headers); + } if (egress.kind === "direct") return { headers }; const https = new URL(url); https.protocol = "https:"; diff --git a/src/lib/proxy-env.ts b/src/lib/proxy-env.ts index fa493586109..223ba152319 100644 --- a/src/lib/proxy-env.ts +++ b/src/lib/proxy-env.ts @@ -208,15 +208,48 @@ export class ExplicitProxyExemptedError extends Error { } /** - * Whether the process `NO_PROXY` or `no_proxy` exempts `url`. + * One bypass entry as Bun's own matcher reads it (observed on Bun 1.4.4): case-insensitive; a + * leading `*.` or `.` and a trailing `.` are dropped; `*` matches everything; a bare entry + * matches that host and every subdomain of it (`localhost` matches `app.localhost`, `com` matches + * `api.example.com`); an entry port must equal the destination port. + */ +function bunNoProxyEntryMatches(hostname: string, port: string, rawEntry: string): boolean { + const entry = rawEntry.trim().toLowerCase(); + if (!entry) return false; + if (entry === "*") return true; + let entryHost = entry; + let entryPort = ""; + const bracketed = /^\[([^\]]*)\](?::(\d+))?$/.exec(entry); + if (bracketed) { + entryHost = bracketed[1]!; + entryPort = bracketed[2] ?? ""; + } else if ((entry.match(/:/g) ?? []).length === 1) { + const separator = entry.lastIndexOf(":"); + entryHost = entry.slice(0, separator); + entryPort = entry.slice(separator + 1); + } + if (entryPort && entryPort !== port) return false; + entryHost = entryHost.replace(/^\*?\./, "").replace(/\.+$/, ""); + if (!entryHost) return false; + return hostname === entryHost || hostname.endsWith(`.${entryHost}`); +} + +/** + * Whether the process `NO_PROXY` or `no_proxy` exempts `url`, as broadly as Bun reads it. * * Bun's fetch and WebSocket connect directly to such a destination even when the request names a - * proxy, as a string or as `{ url }`; only `proxy: false` outranks the environment. Each spelling - * is checked on its own because either one is enough for Bun to skip the proxy. + * proxy, as a string or as `{ url }`; only `proxy: false` outranks the environment. This guard + * therefore has to match at least everything Bun matches: entries split on commas AND whitespace, + * bare entries match subdomains, and either spelling is enough. It also accepts anything + * `noProxyMatches` accepts, so it never answers narrower than the routing decisions elsewhere. + * Over-matching only refuses a request; under-matching would send it around the proxy. */ export function processNoProxyExempts(url: URL, env: ProxyEnvMap = process.env): boolean { - return [env.NO_PROXY, env.no_proxy].some(value => - typeof value === "string" && value.trim() !== "" && noProxyMatches(url, { NO_PROXY: value })); + const hostname = normalizeProxyHostname(url.hostname); + const port = url.port || (url.protocol === "https:" || url.protocol === "wss:" ? "443" : "80"); + return [env.NO_PROXY, env.no_proxy].some(value => typeof value === "string" && value.trim() !== "" + && (value.split(/[\s,]+/).some(entry => bunNoProxyEntryMatches(hostname, port, entry)) + || noProxyMatches(url, { NO_PROXY: value }))); } /** The refusal for an explicit HTTP(S) proxy that the process environment would make Bun skip. */ diff --git a/structure/transports/inventory.md b/structure/transports/inventory.md index 2752239a84b..db4608e48da 100644 --- a/structure/transports/inventory.md +++ b/structure/transports/inventory.md @@ -198,8 +198,10 @@ A reset-triggered rebuild may retarget the request to another region's canonical by transports that can preserve that request-local decision. An explicit HTTP(S) proxy is never sent toward a destination that the process `NO_PROXY` or `no_proxy` exempts, because Bun's fetch and WebSocket connect directly there: `configuredOutboundFetch` refuses the send with -`ExplicitProxyExemptedError`, and the Responses WebSocket upstream leaves such a turn to that HTTP path. -`tests/lib/explicit-proxy-no-proxy.test.ts` checks the route on real loopback sockets. +`ExplicitProxyExemptedError`, the Responses WebSocket upstream leaves such a turn to that HTTP path, and +the Microsoft 365 Copilot ChatHub dial refuses before creating its socket. `processNoProxyExempts` +matches at least as broadly as Bun (comma and whitespace separators, subdomains of a bare entry, either +spelling). `tests/lib/explicit-proxy-no-proxy.test.ts` checks the route on real loopback sockets. | Request path | Per-provider route | Current contract | | --- | --- | --- | diff --git a/tests/lib/explicit-proxy-no-proxy.test.ts b/tests/lib/explicit-proxy-no-proxy.test.ts index c0d1323b91c..7e34d8a1857 100644 --- a/tests/lib/explicit-proxy-no-proxy.test.ts +++ b/tests/lib/explicit-proxy-no-proxy.test.ts @@ -41,8 +41,8 @@ afterEach(() => { } }); -const send = (init: ProxyCapableRequestInit) => - configuredOutboundFetch(destUrl, { ...init, headers: { authorization: "Bearer synthetic-test-token" } } as RequestInit); +const send = (init: ProxyCapableRequestInit, target = destUrl) => + configuredOutboundFetch(target, { ...init, headers: { authorization: "Bearer synthetic-test-token" } } as RequestInit); test("without NO_PROXY the explicit proxy carries the request", async () => { const response = await send({ proxy: proxyUrl }); @@ -95,3 +95,33 @@ test("exemption matching covers both spellings, wildcards, domains and WebSocket expect(processNoProxyExempts(url, { NO_PROXY: "example.com", no_proxy: "*" })).toBe(true); expect(processNoProxyExempts(url, { NO_PROXY: " " })).toBe(false); }); + +// Bun's own matcher splits on whitespace and lets a bare entry cover subdomains; the guard must too. +for (const spelling of ["NO_PROXY", "no_proxy"] as const) { + test(`a whitespace-separated ${spelling} entry is honored like Bun honors it`, async () => { + process.env[spelling] = "example.com localhost"; + await expect(send({ proxy: proxyUrl }, `http://localhost:${dest.port}/v1/models`)).rejects.toBeInstanceOf(ExplicitProxyExemptedError); + expect(hits).toEqual({ dest: 0, proxy: 0 }); + }); + test(`a bare ${spelling} entry also exempts its subdomains, like Bun`, async () => { + process.env[spelling] = "localhost"; + await expect(send({ proxy: proxyUrl }, `http://app.localhost:${dest.port}/v1/models`)).rejects.toBeInstanceOf(ExplicitProxyExemptedError); + expect(hits).toEqual({ dest: 0, proxy: 0 }); + }); +} + +test("every entry form Bun 1.4.4 treats as a bypass is a bypass here", () => { + const url = new URL("http://api.example.com/x"); + // Each of these made Bun connect directly to api.example.com despite an explicit proxy. + for (const entry of ["example.com", ".example.com", "*.example.com", "api.example.com", "api.example.com:80", "EXAMPLE.COM", + "other.org example.com", "other.org\texample.com", " example.com ", "*", "com", ".com", "example.com.", "other.org,,example.com"]) { + expect(processNoProxyExempts(url, { NO_PROXY: entry }), entry).toBe(true); + expect(processNoProxyExempts(url, { no_proxy: entry }), entry).toBe(true); + } + // Bun kept the proxy for these, and so does the guard. + for (const entry of ["ample.com", "xample.com", "api.example", "api.example.com:8080", "[::1]", "example.*"]) { + expect(processNoProxyExempts(url, { NO_PROXY: entry }), entry).toBe(false); + } + expect(processNoProxyExempts(new URL("https://api.example.com/x"), { NO_PROXY: "api.example.com:443" })).toBe(true); + expect(processNoProxyExempts(new URL("http://[::1]:8080/x"), { NO_PROXY: "[::1]" })).toBe(true); +}); diff --git a/tests/providers/m365-copilot.test.ts b/tests/providers/m365-copilot.test.ts index 41c0c63412e..05802853981 100644 --- a/tests/providers/m365-copilot.test.ts +++ b/tests/providers/m365-copilot.test.ts @@ -437,16 +437,31 @@ describe("Microsoft 365 Copilot socket egress", () => { expect(() => m365SocketDialOptions({ fetch: globalThis.fetch }, socketUrl, headers)).toThrow("cannot use a custom fetch executor"); expect(() => m365SocketDialOptions({ proxy: "" }, socketUrl, headers)).toThrow(/providers[.]m365-copilot[.]proxy is invalid/); }); - test("inherited proxy respects the global bypass list without overriding an explicit provider proxy", () => { + test("inherited proxy respects the global bypass list, and an exempted explicit provider proxy is refused", () => { const previousProxy = process.env.HTTPS_PROXY, previousNoProxy = process.env.NO_PROXY; process.env.HTTPS_PROXY = "http://127.0.0.1:9"; process.env.NO_PROXY = "substrate.office.com"; try { expect(m365SocketDialOptions({}, socketUrl, headers).proxy).toBeUndefined(); - expect(m365SocketDialOptions({ proxy: "http://127.0.0.1:9" }, socketUrl, headers).proxy).toBe("http://127.0.0.1:9/"); + // Bun's WebSocket would skip an explicit proxy here and connect directly, so the dial is refused. + expect(() => m365SocketDialOptions({ proxy: "http://127.0.0.1:9" }, socketUrl, headers)).toThrow("NO_PROXY"); + expect(m365SocketDialOptions({ proxy: "http://127.0.0.1:9", noProxy: ["substrate.office.com"] }, socketUrl, headers).proxy).toBeUndefined(); } finally { if (previousProxy === undefined) delete process.env.HTTPS_PROXY; else process.env.HTTPS_PROXY = previousProxy; if (previousNoProxy === undefined) delete process.env.NO_PROXY; else process.env.NO_PROXY = previousNoProxy; } }); + test("an exempted explicit provider proxy refuses the turn before any socket is created", () => { + const previousNoProxy = process.env.NO_PROXY; + process.env.NO_PROXY = "office.com"; + let sockets = 0; + try { + // The dial is planned synchronously, like the other dial refusals, before any socket exists. + expect(() => runM365CopilotTurn({ token: token(), model: "Claude_Sonnet", text: "fixture", conversation: createM365Conversation(), onText() {}, + route: { proxy: "http://127.0.0.1:9" }, createSocket() { sockets += 1; return new WebSocket("ws://127.0.0.1:9"); } })).toThrow("NO_PROXY"); + expect(sockets).toBe(0); + } finally { + if (previousNoProxy === undefined) delete process.env.NO_PROXY; else process.env.NO_PROXY = previousNoProxy; + } + }); }); From 776d4d43c1a242000e0e3c15fe579a2bded3f8ce Mon Sep 17 00:00:00 2001 From: JUN Date: Wed, 25 Nov 2026 12:21:15 +0900 Subject: [PATCH 03/20] fix(egress): port Bun NO_PROXY matching for the explicit-proxy guard --- src/lib/proxy-env.ts | 131 +++++++++++++++++----- structure/transports/inventory.md | 5 +- tests/lib/explicit-proxy-no-proxy.test.ts | 30 +++++ 3 files changed, 136 insertions(+), 30 deletions(-) diff --git a/src/lib/proxy-env.ts b/src/lib/proxy-env.ts index 223ba152319..6fc8225a1df 100644 --- a/src/lib/proxy-env.ts +++ b/src/lib/proxy-env.ts @@ -208,30 +208,106 @@ export class ExplicitProxyExemptedError extends Error { } /** - * One bypass entry as Bun's own matcher reads it (observed on Bun 1.4.4): case-insensitive; a - * leading `*.` or `.` and a trailing `.` are dropped; `*` matches everything; a bare entry - * matches that host and every subdomain of it (`localhost` matches `app.localhost`, `com` matches - * `api.example.com`); an entry port must equal the destination port. + * Bun's own `NO_PROXY` match, ported from `src/dotenv/no_proxy.rs` at the pinned `bun-v1.4.4`. + * + * Entries split on commas and whitespace. `*` matches everything. An entry containing `/` is a CIDR + * block and matches only an IP-literal host inside it. Otherwise an optional `:port` must equal the + * destination port numerically, a leading `*.` or `.` and one trailing `.` are dropped, an IP-literal + * host matches only an equal address (compared canonically, so `::ffff:127.0.0.1` is `127.0.0.1`), + * and a name matches itself and every subdomain, case-insensitively. */ -function bunNoProxyEntryMatches(hostname: string, port: string, rawEntry: string): boolean { - const entry = rawEntry.trim().toLowerCase(); - if (!entry) return false; - if (entry === "*") return true; - let entryHost = entry; - let entryPort = ""; - const bracketed = /^\[([^\]]*)\](?::(\d+))?$/.exec(entry); - if (bracketed) { - entryHost = bracketed[1]!; - entryPort = bracketed[2] ?? ""; - } else if ((entry.match(/:/g) ?? []).length === 1) { - const separator = entry.lastIndexOf(":"); - entryHost = entry.slice(0, separator); - entryPort = entry.slice(separator + 1); +function bunNoProxyMatches(list: string, url: URL): boolean { + const hostname = stripOneTrailingDot(stripIpv6Brackets(url.hostname)); + if (!hostname) return false; + const port = Number(url.port || (url.protocol === "https:" || url.protocol === "wss:" ? "443" : "80")); + const hostIp = parseIpLiteral(hostname); + for (const entry of list.split(/[,\s]+/)) { + if (!entry) continue; + if (entry === "*") return true; + const slash = entry.indexOf("/"); + if (slash !== -1) { + if (hostIp && cidrContains(entry, slash, hostIp)) return true; + continue; + } + const [rawHost, entryPort] = splitEntryPort(entry); + if (entryPort !== undefined && (!/^\d+$/.test(entryPort) || Number(entryPort) !== port)) continue; + const entryHost = stripOneTrailingDot(rawHost.startsWith("*.") ? rawHost.slice(2) : rawHost.startsWith(".") ? rawHost.slice(1) : rawHost); + if (!entryHost) continue; + if (hostIp) { + const entryIp = parseIpLiteral(entryHost); + if (entryIp && sameIp(entryIp, hostIp)) return true; + continue; + } + const host = hostname.toLowerCase(); + const name = entryHost.toLowerCase(); + if (host === name || (host.length > name.length && host.endsWith(`.${name}`))) return true; + } + return false; +} + +interface IpLiteral { v6: boolean; bytes: number[] } + +function stripOneTrailingDot(host: string): string { return host.endsWith(".") ? host.slice(0, -1) : host; } +function stripIpv6Brackets(host: string): string { + return host.startsWith("[") && host.endsWith("]") ? host.slice(1, -1) : host; +} + +/** `host[:port]` where host may be a bracketed or bare IPv6 literal (only one colon means a port). */ +function splitEntryPort(entry: string): [string, string | undefined] { + if (entry.startsWith("[")) { + const close = entry.indexOf("]"); + if (close === -1) return [entry, undefined]; + const rest = entry.slice(close + 1); + return [entry.slice(1, close), rest.startsWith(":") ? rest.slice(1) : undefined]; + } + const colons = entry.split(":").length - 1; + if (colons === 1) { + const colon = entry.indexOf(":"); + return [entry.slice(0, colon), entry.slice(colon + 1)]; + } + return [entry, undefined]; +} + +/** A dotted quad or an IPv6 literal as bytes, with `::ffff:a.b.c.d` folded to IPv4. */ +function parseIpLiteral(text: string): IpLiteral | null { + if (/^\d{1,3}(?:\.\d{1,3}){3}$/.test(text)) { + const bytes = text.split(".").map(Number); + return bytes.every(byte => byte <= 255) ? { v6: false, bytes } : null; + } + if (!text.includes(":")) return null; + let canonical: string; + try { canonical = new URL(`http://[${text}]/`).hostname.slice(1, -1); } catch { return null; } + const halves = canonical.split("::"); + if (halves.length > 2) return null; + const head = halves[0] ? halves[0].split(":") : []; + const tail = halves.length === 2 && halves[1] ? halves[1].split(":") : []; + const groups = halves.length === 2 ? [...head, ...Array(8 - head.length - tail.length).fill("0"), ...tail] : head; + if (groups.length !== 8 || !groups.every(group => /^[0-9a-f]{1,4}$/.test(group))) return null; + const bytes = groups.flatMap(group => { const value = parseInt(group, 16); return [value >> 8, value & 0xff]; }); + const mapped = bytes.slice(0, 10).every(byte => byte === 0) && bytes[10] === 0xff && bytes[11] === 0xff; + return mapped ? { v6: false, bytes: bytes.slice(12) } : { v6: true, bytes }; +} + +function sameIp(a: IpLiteral, b: IpLiteral): boolean { + return a.v6 === b.v6 && a.bytes.every((byte, index) => byte === b.bytes[index]); +} + +function cidrContains(entry: string, slash: number, host: IpLiteral): boolean { + const writtenText = stripIpv6Brackets(entry.slice(0, slash)); + const network = parseIpLiteral(writtenText); + const prefix = entry.slice(slash + 1); + if (!network || !/^\d+$/.test(prefix)) return false; + let bits = Number(prefix); + // `::ffff:10.0.0.0/104` is `10.0.0.0/8`. + if (writtenText.includes(":") && !network.v6) { + if (bits < 96) return false; + bits -= 96; } - if (entryPort && entryPort !== port) return false; - entryHost = entryHost.replace(/^\*?\./, "").replace(/\.+$/, ""); - if (!entryHost) return false; - return hostname === entryHost || hostname.endsWith(`.${entryHost}`); + if (network.v6 !== host.v6 || bits > network.bytes.length * 8) return false; + const whole = Math.floor(bits / 8); + const rem = bits % 8; + for (let index = 0; index < whole; index += 1) if (network.bytes[index] !== host.bytes[index]) return false; + return rem === 0 || ((network.bytes[whole]! ^ host.bytes[whole]!) >> (8 - rem)) === 0; } /** @@ -239,17 +315,16 @@ function bunNoProxyEntryMatches(hostname: string, port: string, rawEntry: string * * Bun's fetch and WebSocket connect directly to such a destination even when the request names a * proxy, as a string or as `{ url }`; only `proxy: false` outranks the environment. This guard - * therefore has to match at least everything Bun matches: entries split on commas AND whitespace, - * bare entries match subdomains, and either spelling is enough. It also accepts anything + * therefore has to match at least everything Bun matches (`bunNoProxyMatches`: whitespace separators, + * subdomains, CIDR blocks, numeric ports, canonical addresses), and either spelling is enough. It also + * accepts anything * `noProxyMatches` accepts, so it never answers narrower than the routing decisions elsewhere. * Over-matching only refuses a request; under-matching would send it around the proxy. */ export function processNoProxyExempts(url: URL, env: ProxyEnvMap = process.env): boolean { - const hostname = normalizeProxyHostname(url.hostname); - const port = url.port || (url.protocol === "https:" || url.protocol === "wss:" ? "443" : "80"); + // Bun reads `no_proxy`, else `NO_PROXY`; checking each on its own covers whichever it picks. return [env.NO_PROXY, env.no_proxy].some(value => typeof value === "string" && value.trim() !== "" - && (value.split(/[\s,]+/).some(entry => bunNoProxyEntryMatches(hostname, port, entry)) - || noProxyMatches(url, { NO_PROXY: value }))); + && (bunNoProxyMatches(value, url) || noProxyMatches(url, { NO_PROXY: value }))); } /** The refusal for an explicit HTTP(S) proxy that the process environment would make Bun skip. */ diff --git a/structure/transports/inventory.md b/structure/transports/inventory.md index db4608e48da..98e586a89bc 100644 --- a/structure/transports/inventory.md +++ b/structure/transports/inventory.md @@ -200,8 +200,9 @@ toward a destination that the process `NO_PROXY` or `no_proxy` exempts, because WebSocket connect directly there: `configuredOutboundFetch` refuses the send with `ExplicitProxyExemptedError`, the Responses WebSocket upstream leaves such a turn to that HTTP path, and the Microsoft 365 Copilot ChatHub dial refuses before creating its socket. `processNoProxyExempts` -matches at least as broadly as Bun (comma and whitespace separators, subdomains of a bare entry, either -spelling). `tests/lib/explicit-proxy-no-proxy.test.ts` checks the route on real loopback sockets. +matches at least as broadly as Bun: `bunNoProxyMatches` ports Bun 1.4.4's `src/dotenv/no_proxy.rs` +(comma and whitespace separators, subdomains, CIDR blocks, numeric ports, canonical addresses), unioned +with `noProxyMatches`, for either spelling. `tests/lib/explicit-proxy-no-proxy.test.ts` checks the route on real loopback sockets. | Request path | Per-provider route | Current contract | | --- | --- | --- | diff --git a/tests/lib/explicit-proxy-no-proxy.test.ts b/tests/lib/explicit-proxy-no-proxy.test.ts index 7e34d8a1857..6f791c4b161 100644 --- a/tests/lib/explicit-proxy-no-proxy.test.ts +++ b/tests/lib/explicit-proxy-no-proxy.test.ts @@ -110,6 +110,36 @@ for (const spelling of ["NO_PROXY", "no_proxy"] as const) { }); } +for (const spelling of ["NO_PROXY", "no_proxy"] as const) { + test(`a ${spelling} CIDR block covering the destination is honored like Bun honors it`, async () => { + process.env[spelling] = "10.0.0.0/8 127.0.0.0/8"; + await expect(send({ proxy: proxyUrl })).rejects.toBeInstanceOf(ExplicitProxyExemptedError); + expect(hits).toEqual({ dest: 0, proxy: 0 }); + }); + test(`a ${spelling} entry with a zero-padded port is compared numerically, like Bun`, async () => { + process.env[spelling] = `127.0.0.1:00${dest.port}`; + await expect(send({ proxy: proxyUrl })).rejects.toBeInstanceOf(ExplicitProxyExemptedError); + expect(hits).toEqual({ dest: 0, proxy: 0 }); + }); +} + +test("addresses compare canonically and CIDR blocks cover both families", () => { + const v4 = new URL("http://127.0.0.1:8080/x"); + const v6 = new URL("http://[::1]:8080/x"); + for (const entry of ["127.0.0.1", "::ffff:127.0.0.1", "[::ffff:127.0.0.1]", "127.0.0.0/8", "::ffff:127.0.0.0/104", "0.0.0.0/0", "127.0.0.1:08080"]) { + expect(processNoProxyExempts(v4, { NO_PROXY: entry }), entry).toBe(true); + } + for (const entry of ["10.0.0.0/8", "127.0.0.2/32", "127.0.0.1:80", "::ffff:127.0.0.0/95"]) { + expect(processNoProxyExempts(v4, { NO_PROXY: entry }), entry).toBe(false); + } + for (const entry of ["::1", "[::1]", "0:0:0:0:0:0:0:1", "0000::1", "::1/128", "::/0", "[::1]:8080", "[::1]:08080"]) { + expect(processNoProxyExempts(v6, { NO_PROXY: entry }), entry).toBe(true); + } + for (const entry of ["fe80::/10", "[::1]:80", "::2"]) { + expect(processNoProxyExempts(v6, { NO_PROXY: entry }), entry).toBe(false); + } +}); + test("every entry form Bun 1.4.4 treats as a bypass is a bypass here", () => { const url = new URL("http://api.example.com/x"); // Each of these made Bun connect directly to api.example.com despite an explicit proxy. From 6f33421b039341de7c12493323881f8f0d390411 Mon Sep 17 00:00:00 2001 From: JUN Date: Wed, 25 Nov 2026 12:21:47 +0900 Subject: [PATCH 04/20] docs(structure): name the Bun matcher without a foreign path --- structure/transports/inventory.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/structure/transports/inventory.md b/structure/transports/inventory.md index 98e586a89bc..d14c791f97e 100644 --- a/structure/transports/inventory.md +++ b/structure/transports/inventory.md @@ -200,7 +200,7 @@ toward a destination that the process `NO_PROXY` or `no_proxy` exempts, because WebSocket connect directly there: `configuredOutboundFetch` refuses the send with `ExplicitProxyExemptedError`, the Responses WebSocket upstream leaves such a turn to that HTTP path, and the Microsoft 365 Copilot ChatHub dial refuses before creating its socket. `processNoProxyExempts` -matches at least as broadly as Bun: `bunNoProxyMatches` ports Bun 1.4.4's `src/dotenv/no_proxy.rs` +matches at least as broadly as Bun: `bunNoProxyMatches` ports the `NO_PROXY` matcher of Bun 1.4.4 (comma and whitespace separators, subdomains, CIDR blocks, numeric ports, canonical addresses), unioned with `noProxyMatches`, for either spelling. `tests/lib/explicit-proxy-no-proxy.test.ts` checks the route on real loopback sockets. From 6644cd5e11137e626450e6bf0a337e2c8be71b85 Mon Sep 17 00:00:00 2001 From: JUN Date: Wed, 25 Nov 2026 12:25:05 +0900 Subject: [PATCH 05/20] fix(egress): follow explicit-proxy redirects in-house and recheck every hop --- src/lib/proxy-env.ts | 59 ++++++++++++++++++- structure/transports/inventory.md | 5 +- tests/lib/explicit-proxy-no-proxy.test.ts | 72 ++++++++++++++++++++++- 3 files changed, 132 insertions(+), 4 deletions(-) diff --git a/src/lib/proxy-env.ts b/src/lib/proxy-env.ts index 6fc8225a1df..a170a772375 100644 --- a/src/lib/proxy-env.ts +++ b/src/lib/proxy-env.ts @@ -362,8 +362,14 @@ export function configuredOutboundFetch( // destination the process NO_PROXY exempts. The caller named this proxy, so the request must not // leave without it: refuse instead. SOCKS5 strings never reach Bun's proxy option (below). if (typeof explicitProxy === "string" && !isSocks5ProxyUrl(explicitProxy) - && (url.protocol === "http:" || url.protocol === "https:") && processNoProxyExempts(url)) { - return Promise.reject(explicitProxyExemptedError(url)); + && (url.protocol === "http:" || url.protocol === "https:")) { + if (processNoProxyExempts(url)) return Promise.reject(explicitProxyExemptedError(url)); + // Bun would follow a redirect itself and apply NO_PROXY to the new destination, so with any + // bypass list in the environment the redirects are followed here, checking every hop. + const redirectMode = init?.redirect ?? (input instanceof Request ? input.redirect : "follow"); + if (redirectMode === "follow" && processNoProxyConfigured()) { + return followExplicitProxyRedirects(base!, input, init, explicitProxy, url); + } } // A mixed inherited SOCKS/HTTP ALL_PROXY environment cannot put bare "localhost" in // NO_PROXY: Bun would also bypass its HTTP proxy for app.localhost. Keep the name exact @@ -378,6 +384,55 @@ export function configuredOutboundFetch( return base!(input, init); } +function processNoProxyConfigured(env: ProxyEnvMap = process.env): boolean { + return [env.NO_PROXY, env.no_proxy].some(value => typeof value === "string" && value.trim() !== ""); +} + +const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]); +const MAX_EXPLICIT_PROXY_REDIRECTS = 20; +/** Request fields the rebuilt `Request` carries; everything else in `init` (Bun's own options) is passed on. */ +const REQUEST_FIELDS = ["method", "headers", "body", "signal", "redirect", "duplex", "referrer", "referrerPolicy", "mode", "credentials", "cache", "integrity", "window"]; + +/** + * Follow redirects of an explicit HTTP(S)-proxy request here, rechecking every destination before it + * is contacted. Each hop is sent through the same proxy with `redirect: "manual"`. The Fetch rules + * apply: 303, and 301/302 after a POST, become a bodiless GET; 307 and 308 replay the method and + * body; a cross-origin hop drops `Authorization`; more than 20 redirects fail. + */ +async function followExplicitProxyRedirects( + base: typeof globalThis.fetch, input: RequestInfo | URL, init: RequestInit | undefined, proxyUrl: string, firstUrl: URL, +): Promise { + const passthrough: Record = { ...(init as Record | undefined) }; + for (const field of REQUEST_FIELDS) delete passthrough[field]; + let request = new Request(input, { ...init, redirect: "manual" }); + let target = firstUrl; + for (let hops = 0; ; hops += 1) { + const response = await base(request.clone(), { ...passthrough, proxy: proxyUrl, redirect: "manual" } as ProxyCapableRequestInit); + const location = REDIRECT_STATUSES.has(response.status) ? response.headers.get("location") : null; + if (location === null) return response; + let next: URL; + try { + next = new URL(location, target); + } catch { + return response; + } + await response.body?.cancel().catch(() => {}); + if (hops >= MAX_EXPLICIT_PROXY_REDIRECTS) throw new TypeError(`too many redirects from ${firstUrl.origin}`); + if (next.protocol !== "http:" && next.protocol !== "https:") throw new TypeError(`redirect to an unsupported scheme from ${target.origin}`); + if (processNoProxyExempts(next)) throw explicitProxyExemptedError(next); + const toGet = response.status === 303 ? request.method !== "HEAD" + : (response.status === 301 || response.status === 302) && request.method === "POST"; + const headers = new Headers(request.headers); + if (toGet) for (const name of ["content-type", "content-length", "content-encoding", "content-language", "content-location"]) headers.delete(name); + if (next.origin !== target.origin) headers.delete("authorization"); + request = new Request(next, { + method: toGet ? "GET" : request.method, headers, body: toGet ? null : request.body, + redirect: "manual", signal: request.signal, duplex: "half", + } as RequestInit); + target = next; + } +} + type FetchWithPreconnect = typeof globalThis.fetch & { preconnect?: typeof globalThis.fetch.preconnect; }; diff --git a/structure/transports/inventory.md b/structure/transports/inventory.md index d14c791f97e..5dfba338bbd 100644 --- a/structure/transports/inventory.md +++ b/structure/transports/inventory.md @@ -202,7 +202,10 @@ WebSocket connect directly there: `configuredOutboundFetch` refuses the send wit the Microsoft 365 Copilot ChatHub dial refuses before creating its socket. `processNoProxyExempts` matches at least as broadly as Bun: `bunNoProxyMatches` ports the `NO_PROXY` matcher of Bun 1.4.4 (comma and whitespace separators, subdomains, CIDR blocks, numeric ports, canonical addresses), unioned -with `noProxyMatches`, for either spelling. `tests/lib/explicit-proxy-no-proxy.test.ts` checks the route on real loopback sockets. +with `noProxyMatches`, for either spelling. While a bypass list is set, an explicit-proxy request in +`follow` mode has its redirects followed by `configuredOutboundFetch` itself (`redirect: "manual"` per hop, +Fetch method/body rules, `Authorization` dropped cross-origin), so every destination is checked before +it is contacted. `tests/lib/explicit-proxy-no-proxy.test.ts` checks the route on real loopback sockets. | Request path | Per-provider route | Current contract | | --- | --- | --- | diff --git a/tests/lib/explicit-proxy-no-proxy.test.ts b/tests/lib/explicit-proxy-no-proxy.test.ts index 6f791c4b161..7a9c5755286 100644 --- a/tests/lib/explicit-proxy-no-proxy.test.ts +++ b/tests/lib/explicit-proxy-no-proxy.test.ts @@ -5,7 +5,7 @@ * request names a proxy. These cases use a real transport (two loopback listeners) because a * mocked fetch only sees the option, not the route the request actually takes. */ -import { afterAll, afterEach, beforeAll, beforeEach, expect, test } from "bun:test"; +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from "bun:test"; import { configuredOutboundFetch, ExplicitProxyExemptedError, @@ -155,3 +155,73 @@ test("every entry form Bun 1.4.4 treats as a bypass is a bypass here", () => { expect(processNoProxyExempts(new URL("https://api.example.com/x"), { NO_PROXY: "api.example.com:443" })).toBe(true); expect(processNoProxyExempts(new URL("http://[::1]:8080/x"), { NO_PROXY: "[::1]" })).toBe(true); }); + +describe("redirects of an explicit-proxy request", () => { + type Seen = { method: string; path: string; body: string; authorization: string | null; apiKey: string | null }; + const viaProxy: Seen[] = []; + const atExempt: Seen[] = []; + let redirectTo = ""; + let redirectStatus = 307; + let exempt: ReturnType; + let forwardProxy: ReturnType; + const seen = async (req: Request): Promise => ({ method: req.method, path: new URL(req.url).pathname, body: await req.text(), + authorization: req.headers.get("authorization"), apiKey: req.headers.get("x-api-key") }); + + beforeAll(() => { + exempt = Bun.serve({ port: 0, hostname: "127.0.0.1", fetch: async req => { atExempt.push(await seen(req)); return new Response("exempt"); } }); + // A forward proxy: it answers every proxied request itself, redirecting /start. + forwardProxy = Bun.serve({ port: 0, hostname: "127.0.0.1", fetch: async req => { + const request = await seen(req); + viaProxy.push(request); + if (request.path === "/start") return new Response(null, { status: redirectStatus, headers: { location: redirectTo } }); + return new Response(`landed ${request.method} ${request.body}`); + } }); + }); + afterAll(() => { exempt.stop(true); forwardProxy.stop(true); }); + beforeEach(() => { viaProxy.length = 0; atExempt.length = 0; redirectStatus = 307; }); + + const post = () => configuredOutboundFetch(`http://127.0.0.1:${dest.port}/start`, { + method: "POST", body: "synthetic-body", proxy: `http://127.0.0.1:${forwardProxy.port}`, + headers: { authorization: "Bearer synthetic-test-token", "x-api-key": "synthetic-test-key" }, + } as ProxyCapableRequestInit as RequestInit); + + for (const spelling of ["NO_PROXY", "no_proxy"] as const) { + test(`a redirect to a destination ${spelling} exempts is refused before it is contacted`, async () => { + process.env[spelling] = `127.0.0.1:${exempt.port}`; + redirectTo = `http://127.0.0.1:${exempt.port}/landing`; + await expect(post()).rejects.toBeInstanceOf(ExplicitProxyExemptedError); + expect(viaProxy.map(request => request.path)).toEqual(["/start"]); + expect(atExempt).toEqual([]); + }); + } + + test("a redirect to a destination that is not exempt is followed through the proxy, replaying a 307", async () => { + process.env.NO_PROXY = "example.invalid"; + redirectTo = `http://127.0.0.1:${dest.port}/landing`; + const response = await post(); + expect(await response.text()).toBe("landed POST synthetic-body"); + expect(viaProxy.map(request => [request.path, request.method, request.body, request.apiKey])).toEqual([ + ["/start", "POST", "synthetic-body", "synthetic-test-key"], + ["/landing", "POST", "synthetic-body", "synthetic-test-key"], + ]); + expect(atExempt).toEqual([]); + }); + + test("a 303 becomes a bodiless GET and a cross-origin hop drops Authorization", async () => { + process.env.NO_PROXY = "example.invalid"; + redirectStatus = 303; + redirectTo = `http://localhost:${dest.port}/landing`; + const response = await post(); + expect(await response.text()).toBe("landed GET "); + expect(viaProxy[1]).toMatchObject({ path: "/landing", method: "GET", body: "", authorization: null }); + }); + + test("a caller's manual redirect mode is left to the caller", async () => { + process.env.NO_PROXY = `127.0.0.1:${exempt.port}`; + redirectTo = `http://127.0.0.1:${exempt.port}/landing`; + const response = await configuredOutboundFetch(`http://127.0.0.1:${dest.port}/start`, { + redirect: "manual", proxy: `http://127.0.0.1:${forwardProxy.port}` } as ProxyCapableRequestInit as RequestInit); + expect(response.status).toBe(307); + expect(atExempt).toEqual([]); + }); +}); From c1e8ae644b6eda48e1d4dae30e289677d58bd5cd Mon Sep 17 00:00:00 2001 From: JUN Date: Wed, 25 Nov 2026 12:28:31 +0900 Subject: [PATCH 06/20] fix(egress): mirror Bun redirect header stripping and redirected flag in the explicit-proxy follower --- src/lib/proxy-env.ts | 26 +++++++++---- structure/transports/inventory.md | 5 ++- tests/lib/explicit-proxy-no-proxy.test.ts | 46 ++++++++++++++++++++++- 3 files changed, 66 insertions(+), 11 deletions(-) diff --git a/src/lib/proxy-env.ts b/src/lib/proxy-env.ts index a170a772375..3c1e8f73b38 100644 --- a/src/lib/proxy-env.ts +++ b/src/lib/proxy-env.ts @@ -393,11 +393,18 @@ const MAX_EXPLICIT_PROXY_REDIRECTS = 20; /** Request fields the rebuilt `Request` carries; everything else in `init` (Bun's own options) is passed on. */ const REQUEST_FIELDS = ["method", "headers", "body", "signal", "redirect", "duplex", "referrer", "referrerPolicy", "mode", "credentials", "cache", "integrity", "window"]; +/** Removed on a cross-origin hop, as Bun's own follower removes them (`CROSS_ORIGIN_STRIPPED_REQUEST_HEADERS`). */ +const CROSS_ORIGIN_STRIPPED_HEADERS = ["authorization", "proxy-authorization", "cookie", "host"]; +/** Request-body header names, dropped with the body when a redirect turns the request into a GET. */ +const REQUEST_BODY_HEADERS = ["content-type", "content-length", "content-encoding", "content-language", "content-location"]; + /** * Follow redirects of an explicit HTTP(S)-proxy request here, rechecking every destination before it - * is contacted. Each hop is sent through the same proxy with `redirect: "manual"`. The Fetch rules - * apply: 303, and 301/302 after a POST, become a bodiless GET; 307 and 308 replay the method and - * body; a cross-origin hop drops `Authorization`; more than 20 redirects fail. + * is contacted. Each hop is sent through the same proxy with `redirect: "manual"`. The rules are the + * ones Bun 1.4.4's own follower applies: 303 (unless GET or HEAD), and 301/302 after a POST, become a + * bodiless GET; 307 and 308 replay the method and body, but a ReadableStream body cannot be replayed + * and fails; a cross-origin hop (scheme, host or port differ) drops the credential headers and Host; + * more than 20 redirects fail; a followed response reports `redirected: true`. */ async function followExplicitProxyRedirects( base: typeof globalThis.fetch, input: RequestInfo | URL, init: RequestInit | undefined, proxyUrl: string, firstUrl: URL, @@ -405,11 +412,15 @@ async function followExplicitProxyRedirects( const passthrough: Record = { ...(init as Record | undefined) }; for (const field of REQUEST_FIELDS) delete passthrough[field]; let request = new Request(input, { ...init, redirect: "manual" }); + const streamedBody = typeof ReadableStream !== "undefined" && init?.body instanceof ReadableStream; let target = firstUrl; for (let hops = 0; ; hops += 1) { const response = await base(request.clone(), { ...passthrough, proxy: proxyUrl, redirect: "manual" } as ProxyCapableRequestInit); const location = REDIRECT_STATUSES.has(response.status) ? response.headers.get("location") : null; - if (location === null) return response; + if (location === null) { + if (hops > 0) Object.defineProperty(response, "redirected", { value: true }); + return response; + } let next: URL; try { next = new URL(location, target); @@ -420,11 +431,12 @@ async function followExplicitProxyRedirects( if (hops >= MAX_EXPLICIT_PROXY_REDIRECTS) throw new TypeError(`too many redirects from ${firstUrl.origin}`); if (next.protocol !== "http:" && next.protocol !== "https:") throw new TypeError(`redirect to an unsupported scheme from ${target.origin}`); if (processNoProxyExempts(next)) throw explicitProxyExemptedError(next); - const toGet = response.status === 303 ? request.method !== "HEAD" + const toGet = response.status === 303 ? request.method !== "GET" && request.method !== "HEAD" : (response.status === 301 || response.status === 302) && request.method === "POST"; + if (!toGet && response.status !== 303 && streamedBody) throw new TypeError(`request body from ${firstUrl.origin} is not reusable for a redirect`); const headers = new Headers(request.headers); - if (toGet) for (const name of ["content-type", "content-length", "content-encoding", "content-language", "content-location"]) headers.delete(name); - if (next.origin !== target.origin) headers.delete("authorization"); + if (toGet) for (const name of REQUEST_BODY_HEADERS) headers.delete(name); + if (next.origin !== target.origin) for (const name of CROSS_ORIGIN_STRIPPED_HEADERS) headers.delete(name); request = new Request(next, { method: toGet ? "GET" : request.method, headers, body: toGet ? null : request.body, redirect: "manual", signal: request.signal, duplex: "half", diff --git a/structure/transports/inventory.md b/structure/transports/inventory.md index 5dfba338bbd..4384d0f98e1 100644 --- a/structure/transports/inventory.md +++ b/structure/transports/inventory.md @@ -204,8 +204,9 @@ matches at least as broadly as Bun: `bunNoProxyMatches` ports the `NO_PROXY` mat (comma and whitespace separators, subdomains, CIDR blocks, numeric ports, canonical addresses), unioned with `noProxyMatches`, for either spelling. While a bypass list is set, an explicit-proxy request in `follow` mode has its redirects followed by `configuredOutboundFetch` itself (`redirect: "manual"` per hop, -Fetch method/body rules, `Authorization` dropped cross-origin), so every destination is checked before -it is contacted. `tests/lib/explicit-proxy-no-proxy.test.ts` checks the route on real loopback sockets. +with Bun's own redirect rules: method and body changes, no replay of a streamed body, the credential +headers and Host dropped cross-origin, `redirected: true` on the result), so every destination is +checked before it is contacted. `tests/lib/explicit-proxy-no-proxy.test.ts` checks the route on real loopback sockets. | Request path | Per-provider route | Current contract | | --- | --- | --- | diff --git a/tests/lib/explicit-proxy-no-proxy.test.ts b/tests/lib/explicit-proxy-no-proxy.test.ts index 7a9c5755286..f6c3106dc28 100644 --- a/tests/lib/explicit-proxy-no-proxy.test.ts +++ b/tests/lib/explicit-proxy-no-proxy.test.ts @@ -157,7 +157,8 @@ test("every entry form Bun 1.4.4 treats as a bypass is a bypass here", () => { }); describe("redirects of an explicit-proxy request", () => { - type Seen = { method: string; path: string; body: string; authorization: string | null; apiKey: string | null }; + type Seen = { method: string; path: string; body: string; authorization: string | null; apiKey: string | null; + cookie: string | null; proxyAuthorization: string | null; contentType: string | null }; const viaProxy: Seen[] = []; const atExempt: Seen[] = []; let redirectTo = ""; @@ -165,7 +166,8 @@ describe("redirects of an explicit-proxy request", () => { let exempt: ReturnType; let forwardProxy: ReturnType; const seen = async (req: Request): Promise => ({ method: req.method, path: new URL(req.url).pathname, body: await req.text(), - authorization: req.headers.get("authorization"), apiKey: req.headers.get("x-api-key") }); + authorization: req.headers.get("authorization"), apiKey: req.headers.get("x-api-key"), cookie: req.headers.get("cookie"), + proxyAuthorization: req.headers.get("proxy-authorization"), contentType: req.headers.get("content-type") }); beforeAll(() => { exempt = Bun.serve({ port: 0, hostname: "127.0.0.1", fetch: async req => { atExempt.push(await seen(req)); return new Response("exempt"); } }); @@ -216,6 +218,46 @@ describe("redirects of an explicit-proxy request", () => { expect(viaProxy[1]).toMatchObject({ path: "/landing", method: "GET", body: "", authorization: null }); }); + // The same request through Bun's native follower (no bypass list, so Bun follows) and through the + // in-house one (a bypass list that does not match engages it) must reach the second hop identically. + for (const status of [307, 303]) { + test(`a cross-origin ${status} reaches its second hop exactly as Bun's own follower sends it`, async () => { + redirectStatus = status; + redirectTo = `http://localhost:${dest.port}/landing`; + const sendCredentialed = () => configuredOutboundFetch(`http://127.0.0.1:${dest.port}/start`, { + method: "POST", body: "synthetic-body", proxy: `http://127.0.0.1:${forwardProxy.port}`, + headers: { authorization: "Bearer synthetic-test-token", "x-api-key": "synthetic-test-key", cookie: "session=synthetic", + "proxy-authorization": "Basic c3ludGhldGlj", "content-type": "text/plain" }, + } as ProxyCapableRequestInit as RequestInit); + const native = await sendCredentialed(); + const nativeHops = viaProxy.splice(0); + process.env.NO_PROXY = "example.invalid"; + const followed = await sendCredentialed(); + const followedHops = viaProxy.splice(0); + expect(await followed.text()).toBe(await native.text()); + expect(followed.redirected).toBe(native.redirected); + expect(followed.redirected).toBe(true); + expect(followedHops).toEqual(nativeHops); + expect(followedHops[1]).toMatchObject({ authorization: null, cookie: null, proxyAuthorization: null, apiKey: "synthetic-test-key" }); + }); + } + + test("a streamed body is not replayed across a 307, like Bun", async () => { + process.env.NO_PROXY = "example.invalid"; + redirectTo = `http://127.0.0.1:${dest.port}/landing`; + const body = new ReadableStream({ start(controller) { controller.enqueue(new TextEncoder().encode("streamed")); controller.close(); } }); + await expect(configuredOutboundFetch(`http://127.0.0.1:${dest.port}/start`, { + method: "POST", body, duplex: "half", proxy: `http://127.0.0.1:${forwardProxy.port}` } as ProxyCapableRequestInit as RequestInit)).rejects.toThrow(); + expect(viaProxy.map(request => request.path)).toEqual(["/start"]); + }); + + test("an unredirected response keeps redirected false", async () => { + process.env.NO_PROXY = "example.invalid"; + const response = await configuredOutboundFetch(`http://127.0.0.1:${dest.port}/landing`, { proxy: `http://127.0.0.1:${forwardProxy.port}` } as ProxyCapableRequestInit as RequestInit); + expect(await response.text()).toBe("landed GET "); + expect(response.redirected).toBe(false); + }); + test("a caller's manual redirect mode is left to the caller", async () => { process.env.NO_PROXY = `127.0.0.1:${exempt.port}`; redirectTo = `http://127.0.0.1:${exempt.port}/landing`; From ba744b6636701ce2b8a9451651d6d8a5a630b0a3 Mon Sep 17 00:00:00 2001 From: JUN Date: Wed, 25 Nov 2026 12:31:33 +0900 Subject: [PATCH 07/20] fix(egress): refuse explicit-proxy redirects while NO_PROXY is set instead of following them --- .../es/reference/configuration/providers.md | 2 +- .../docs/reference/configuration/providers.md | 4 +- src/lib/proxy-env.ts | 78 +++++---------- structure/transports/inventory.md | 8 +- tests/lib/explicit-proxy-no-proxy.test.ts | 95 +++++++------------ 5 files changed, 65 insertions(+), 122 deletions(-) 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 39697ef5cdc..e497dd6420c 100644 --- a/docs-site/src/content/docs/es/reference/configuration/providers.md +++ b/docs-site/src/content/docs/es/reference/configuration/providers.md @@ -221,7 +221,7 @@ Los proveedores pueden exponer una abreviatura incorporada, como `agy` para `goo | --- | --- | --- | | `adapter` | `string` | Uno de `openai-chat`, `openai-responses`, `anthropic`, `claude-cli`, `step-cli`, `google`, `kiro`, `cursor`, `ollama-native`, `azure-openai` (o alias `azure`), `codebuddy`, `qoder`. | | `baseUrl` | `string` | URL de base ascendente API. La mayoría de los puntos finales fijos incorporados ignoran una falta de coincidencia; los ajustes preestablecidos de clave seguros contra colisiones conservan un destino personalizado con el mismo nombre más antiguo. | -| `proxy?` | `string \| null` | Ruta de salida por proveedor. Omita que herede la decisión de proxy global; use `"direct"` o `null` para forzar la salida directa; o proporcione una URL proxy absoluta `http://`, `https://`, `socks5://` o `socks5h://`. Se rechaza una cadena vacía. Un `proxy` HTTP(S) no se combina con una entrada de `NO_PROXY` del proceso que coincida con el mismo destino, porque el entorno de ejecución se conectaría directamente: esa solicitud se rechaza. Para conectar directamente, añada el host a `noProxy` del proveedor. | +| `proxy?` | `string \| null` | Ruta de salida por proveedor. Omita que herede la decisión de proxy global; use `"direct"` o `null` para forzar la salida directa; o proporcione una URL proxy absoluta `http://`, `https://`, `socks5://` o `socks5h://`. Se rechaza una cadena vacía. Un `proxy` HTTP(S) no se combina con una entrada de `NO_PROXY` del proceso que coincida con el mismo destino, porque el entorno de ejecución se conectaría directamente: esa solicitud se rechaza. Para conectar directamente, añada el host a `noProxy` del proveedor. Mientras `NO_PROXY` esté definido, una redirección en respuesta a esa solicitud se rechaza en lugar de seguirse. | | `noProxy?` | `string \| string[]` | Destinos a los que este proveedor llega directamente, utilizando la sintaxis de patrón de host `NO_PROXY`. Una coincidencia pasa por alto tanto el propio proxy de este proveedor como un proxy global heredado. | | `requestPacing?` | `{ enabled, requestsPerMinute?, minIntervalMs?, maxConcurrentRequests?, models?, keySelection?, keys? }` | Indicadores opcionales de inicio de solicitud de salida del lado del cliente, separados del uso ascendente, la facturación y los indicadores de límite de solicitudes. RPM se convierte en un intervalo uniforme; `minIntervalMs` puede imponer un intervalo más largo. `maxConcurrentRequests` es un límite de enteros positivo en las solicitudes en vuelo. Una regla de proveedor o modelo puede usar el límite de concurrencia solo; los límites de proveedor se aplican a todos los modelos, mientras que las entradas `models` usan ID de modelo ascendente exactos (por ejemplo, `nvidia/llama-3.1-nemotron-ultra-253b-v1`) y solo pueden agregar retardo o concurrencia estrecha. Los esperas de cola no consumen el tiempo de espera del encabezado de respuesta ascendente. HTTP y el adaptador explícito `fetchResponse` / `runTurn` despachos están cubiertos. Un giro canónico Responses WebSocket con límite de concurrencia usa HTTP / SSE para que su arrendamiento pueda liberarse cuando el cuerpo de respuesta se complete, se equivoque o se cancele. Para los adaptadores `runTurn`, incluyendo Cursor, el cap cuenta los giros activos en lugar de los envíos físicos: RunSSE y BidiAppend pueden superponerse en un giro, mientras que otro turno espera. Seguimiento envía todavía obedecer intervalos de inicio. | | `requestPacing.keySelection?` | `"active"`, `"round-robin"` | Selección normal de la tecla de petición. El valor predeterminado `active` conserva la clave guardada y la rotación de fallas existente; `round-robin` distribuye las selecciones locales de solicitud a través de referencias de grupo de claves API elegibles sin cambiar la clave activa guardada. Equilibra las asignaciones, no los tokens o el costo. | diff --git a/docs-site/src/content/docs/reference/configuration/providers.md b/docs-site/src/content/docs/reference/configuration/providers.md index 7dc9d8ea81d..b476d90119a 100644 --- a/docs-site/src/content/docs/reference/configuration/providers.md +++ b/docs-site/src/content/docs/reference/configuration/providers.md @@ -602,7 +602,9 @@ use its own `proxy` or inherit a global proxy. An HTTP(S) `proxy` on a provider and a process `NO_PROXY` entry that matches the same destination cannot both apply, because the runtime would connect directly. Such a request is refused rather than sent without the configured proxy. List the host in the provider's `noProxy` to connect directly, or -remove it from `NO_PROXY` to keep the proxy. A `socks5://` or `socks5h://` proxy is not affected. +remove it from `NO_PROXY` to keep the proxy. While `NO_PROXY` is set, a redirect answered to such a +request is refused rather than followed, because the next hop could leave without the proxy. A +`socks5://` or `socks5h://` proxy is not affected. #### What the route covers diff --git a/src/lib/proxy-env.ts b/src/lib/proxy-env.ts index 3c1e8f73b38..03e0400ccaf 100644 --- a/src/lib/proxy-env.ts +++ b/src/lib/proxy-env.ts @@ -203,8 +203,8 @@ export type ProxyCapableRequestInit = RequestInit & { proxy?: string | false }; /** A request named an HTTP(S) proxy for a destination the process `NO_PROXY` exempts. */ export class ExplicitProxyExemptedError extends Error { - override readonly name = "ExplicitProxyExemptedError"; - readonly code = "explicit_proxy_exempted"; + override readonly name: string = "ExplicitProxyExemptedError"; + readonly code: string = "explicit_proxy_exempted"; } /** @@ -327,6 +327,12 @@ export function processNoProxyExempts(url: URL, env: ProxyEnvMap = process.env): && (bunNoProxyMatches(value, url) || noProxyMatches(url, { NO_PROXY: value }))); } +/** A redirect answer to an explicit-proxy request that Bun would have followed around the proxy. */ +export class ExplicitProxyRedirectRefusedError extends ExplicitProxyExemptedError { + override readonly name = "ExplicitProxyRedirectRefusedError"; + override readonly code = "explicit_proxy_redirect_refused"; +} + /** The refusal for an explicit HTTP(S) proxy that the process environment would make Bun skip. */ export function explicitProxyExemptedError(url: URL): ExplicitProxyExemptedError { return new ExplicitProxyExemptedError( @@ -365,10 +371,10 @@ export function configuredOutboundFetch( && (url.protocol === "http:" || url.protocol === "https:")) { if (processNoProxyExempts(url)) return Promise.reject(explicitProxyExemptedError(url)); // Bun would follow a redirect itself and apply NO_PROXY to the new destination, so with any - // bypass list in the environment the redirects are followed here, checking every hop. + // bypass list in the environment a redirect is refused instead of followed. const redirectMode = init?.redirect ?? (input instanceof Request ? input.redirect : "follow"); if (redirectMode === "follow" && processNoProxyConfigured()) { - return followExplicitProxyRedirects(base!, input, init, explicitProxy, url); + return refuseExplicitProxyRedirects(base!, input, init, url); } } // A mixed inherited SOCKS/HTTP ALL_PROXY environment cannot put bare "localhost" in @@ -389,60 +395,24 @@ function processNoProxyConfigured(env: ProxyEnvMap = process.env): boolean { } const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]); -const MAX_EXPLICIT_PROXY_REDIRECTS = 20; -/** Request fields the rebuilt `Request` carries; everything else in `init` (Bun's own options) is passed on. */ -const REQUEST_FIELDS = ["method", "headers", "body", "signal", "redirect", "duplex", "referrer", "referrerPolicy", "mode", "credentials", "cache", "integrity", "window"]; - -/** Removed on a cross-origin hop, as Bun's own follower removes them (`CROSS_ORIGIN_STRIPPED_REQUEST_HEADERS`). */ -const CROSS_ORIGIN_STRIPPED_HEADERS = ["authorization", "proxy-authorization", "cookie", "host"]; -/** Request-body header names, dropped with the body when a redirect turns the request into a GET. */ -const REQUEST_BODY_HEADERS = ["content-type", "content-length", "content-encoding", "content-language", "content-location"]; /** - * Follow redirects of an explicit HTTP(S)-proxy request here, rechecking every destination before it - * is contacted. Each hop is sent through the same proxy with `redirect: "manual"`. The rules are the - * ones Bun 1.4.4's own follower applies: 303 (unless GET or HEAD), and 301/302 after a POST, become a - * bodiless GET; 307 and 308 replay the method and body, but a ReadableStream body cannot be replayed - * and fails; a cross-origin hop (scheme, host or port differ) drops the credential headers and Host; - * more than 20 redirects fail; a followed response reports `redirected: true`. + * Send an explicit HTTP(S)-proxy request whose caller asked Bun to follow redirects, without letting + * Bun follow them: Bun would apply the process NO_PROXY to each new destination and could send the + * request, credentials and body included, around the proxy. The single hop goes out with + * `redirect: "manual"`; a redirect answer is refused before any second hop is contacted. Callers + * that handle redirects themselves pass `redirect: "manual"` and never reach this. */ -async function followExplicitProxyRedirects( - base: typeof globalThis.fetch, input: RequestInfo | URL, init: RequestInit | undefined, proxyUrl: string, firstUrl: URL, +async function refuseExplicitProxyRedirects( + base: typeof globalThis.fetch, input: RequestInfo | URL, init: RequestInit | undefined, firstUrl: URL, ): Promise { - const passthrough: Record = { ...(init as Record | undefined) }; - for (const field of REQUEST_FIELDS) delete passthrough[field]; - let request = new Request(input, { ...init, redirect: "manual" }); - const streamedBody = typeof ReadableStream !== "undefined" && init?.body instanceof ReadableStream; - let target = firstUrl; - for (let hops = 0; ; hops += 1) { - const response = await base(request.clone(), { ...passthrough, proxy: proxyUrl, redirect: "manual" } as ProxyCapableRequestInit); - const location = REDIRECT_STATUSES.has(response.status) ? response.headers.get("location") : null; - if (location === null) { - if (hops > 0) Object.defineProperty(response, "redirected", { value: true }); - return response; - } - let next: URL; - try { - next = new URL(location, target); - } catch { - return response; - } - await response.body?.cancel().catch(() => {}); - if (hops >= MAX_EXPLICIT_PROXY_REDIRECTS) throw new TypeError(`too many redirects from ${firstUrl.origin}`); - if (next.protocol !== "http:" && next.protocol !== "https:") throw new TypeError(`redirect to an unsupported scheme from ${target.origin}`); - if (processNoProxyExempts(next)) throw explicitProxyExemptedError(next); - const toGet = response.status === 303 ? request.method !== "GET" && request.method !== "HEAD" - : (response.status === 301 || response.status === 302) && request.method === "POST"; - if (!toGet && response.status !== 303 && streamedBody) throw new TypeError(`request body from ${firstUrl.origin} is not reusable for a redirect`); - const headers = new Headers(request.headers); - if (toGet) for (const name of REQUEST_BODY_HEADERS) headers.delete(name); - if (next.origin !== target.origin) for (const name of CROSS_ORIGIN_STRIPPED_HEADERS) headers.delete(name); - request = new Request(next, { - method: toGet ? "GET" : request.method, headers, body: toGet ? null : request.body, - redirect: "manual", signal: request.signal, duplex: "half", - } as RequestInit); - target = next; - } + const response = await base(input, { ...init, redirect: "manual" } as RequestInit); + if (!REDIRECT_STATUSES.has(response.status) || !response.headers.has("location")) return response; + await response.body?.cancel().catch(() => {}); + throw new ExplicitProxyRedirectRefusedError( + `a redirect from ${firstUrl.origin} was not followed through the configured proxy because NO_PROXY is set in the ` + + 'process environment and could route the next hop around it; handle redirects with redirect: "manual"', + ); } type FetchWithPreconnect = typeof globalThis.fetch & { diff --git a/structure/transports/inventory.md b/structure/transports/inventory.md index 4384d0f98e1..bb8fd6939f7 100644 --- a/structure/transports/inventory.md +++ b/structure/transports/inventory.md @@ -202,11 +202,9 @@ WebSocket connect directly there: `configuredOutboundFetch` refuses the send wit the Microsoft 365 Copilot ChatHub dial refuses before creating its socket. `processNoProxyExempts` matches at least as broadly as Bun: `bunNoProxyMatches` ports the `NO_PROXY` matcher of Bun 1.4.4 (comma and whitespace separators, subdomains, CIDR blocks, numeric ports, canonical addresses), unioned -with `noProxyMatches`, for either spelling. While a bypass list is set, an explicit-proxy request in -`follow` mode has its redirects followed by `configuredOutboundFetch` itself (`redirect: "manual"` per hop, -with Bun's own redirect rules: method and body changes, no replay of a streamed body, the credential -headers and Host dropped cross-origin, `redirected: true` on the result), so every destination is -checked before it is contacted. `tests/lib/explicit-proxy-no-proxy.test.ts` checks the route on real loopback sockets. +with `noProxyMatches`, for either spelling. While a bypass list is set, an explicit-proxy request in `follow` mode is sent with `redirect: "manual"` +and a redirect answer is refused (`ExplicitProxyRedirectRefusedError`) instead of being followed, because +Bun would apply the bypass list to the next hop; callers that handle redirects pass `manual` themselves. `tests/lib/explicit-proxy-no-proxy.test.ts` checks the route on real loopback sockets. | Request path | Per-provider route | Current contract | | --- | --- | --- | diff --git a/tests/lib/explicit-proxy-no-proxy.test.ts b/tests/lib/explicit-proxy-no-proxy.test.ts index f6c3106dc28..28488142087 100644 --- a/tests/lib/explicit-proxy-no-proxy.test.ts +++ b/tests/lib/explicit-proxy-no-proxy.test.ts @@ -9,6 +9,7 @@ import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } fr import { configuredOutboundFetch, ExplicitProxyExemptedError, + ExplicitProxyRedirectRefusedError, processNoProxyExempts, type ProxyCapableRequestInit, } from "../../src/lib/proxy-env"; @@ -157,17 +158,14 @@ test("every entry form Bun 1.4.4 treats as a bypass is a bypass here", () => { }); describe("redirects of an explicit-proxy request", () => { - type Seen = { method: string; path: string; body: string; authorization: string | null; apiKey: string | null; - cookie: string | null; proxyAuthorization: string | null; contentType: string | null }; + type Seen = { method: string; path: string; body: string }; const viaProxy: Seen[] = []; const atExempt: Seen[] = []; let redirectTo = ""; let redirectStatus = 307; let exempt: ReturnType; let forwardProxy: ReturnType; - const seen = async (req: Request): Promise => ({ method: req.method, path: new URL(req.url).pathname, body: await req.text(), - authorization: req.headers.get("authorization"), apiKey: req.headers.get("x-api-key"), cookie: req.headers.get("cookie"), - proxyAuthorization: req.headers.get("proxy-authorization"), contentType: req.headers.get("content-type") }); + const seen = async (req: Request): Promise => ({ method: req.method, path: new URL(req.url).pathname, body: await req.text() }); beforeAll(() => { exempt = Bun.serve({ port: 0, hostname: "127.0.0.1", fetch: async req => { atExempt.push(await seen(req)); return new Response("exempt"); } }); @@ -182,87 +180,62 @@ describe("redirects of an explicit-proxy request", () => { afterAll(() => { exempt.stop(true); forwardProxy.stop(true); }); beforeEach(() => { viaProxy.length = 0; atExempt.length = 0; redirectStatus = 307; }); - const post = () => configuredOutboundFetch(`http://127.0.0.1:${dest.port}/start`, { - method: "POST", body: "synthetic-body", proxy: `http://127.0.0.1:${forwardProxy.port}`, - headers: { authorization: "Bearer synthetic-test-token", "x-api-key": "synthetic-test-key" }, - } as ProxyCapableRequestInit as RequestInit); + const proxied = (init: RequestInit = {}) => ({ ...init, proxy: `http://127.0.0.1:${forwardProxy.port}` }) as ProxyCapableRequestInit as RequestInit; + const startUrl = () => `http://127.0.0.1:${dest.port}/start`; + const post = () => configuredOutboundFetch(startUrl(), proxied({ + method: "POST", body: "synthetic-body", headers: { authorization: "Bearer synthetic-test-token", "x-api-key": "synthetic-test-key" } })); for (const spelling of ["NO_PROXY", "no_proxy"] as const) { - test(`a redirect to a destination ${spelling} exempts is refused before it is contacted`, async () => { + test(`a redirect toward a destination ${spelling} exempts is refused and that destination is never contacted`, async () => { process.env[spelling] = `127.0.0.1:${exempt.port}`; redirectTo = `http://127.0.0.1:${exempt.port}/landing`; - await expect(post()).rejects.toBeInstanceOf(ExplicitProxyExemptedError); + await expect(post()).rejects.toBeInstanceOf(ExplicitProxyRedirectRefusedError); expect(viaProxy.map(request => request.path)).toEqual(["/start"]); expect(atExempt).toEqual([]); }); } - test("a redirect to a destination that is not exempt is followed through the proxy, replaying a 307", async () => { - process.env.NO_PROXY = "example.invalid"; - redirectTo = `http://127.0.0.1:${dest.port}/landing`; - const response = await post(); - expect(await response.text()).toBe("landed POST synthetic-body"); - expect(viaProxy.map(request => [request.path, request.method, request.body, request.apiKey])).toEqual([ - ["/start", "POST", "synthetic-body", "synthetic-test-key"], - ["/landing", "POST", "synthetic-body", "synthetic-test-key"], - ]); - expect(atExempt).toEqual([]); - }); - - test("a 303 becomes a bodiless GET and a cross-origin hop drops Authorization", async () => { - process.env.NO_PROXY = "example.invalid"; - redirectStatus = 303; - redirectTo = `http://localhost:${dest.port}/landing`; - const response = await post(); - expect(await response.text()).toBe("landed GET "); - expect(viaProxy[1]).toMatchObject({ path: "/landing", method: "GET", body: "", authorization: null }); - }); - - // The same request through Bun's native follower (no bypass list, so Bun follows) and through the - // in-house one (a bypass list that does not match engages it) must reach the second hop identically. - for (const status of [307, 303]) { - test(`a cross-origin ${status} reaches its second hop exactly as Bun's own follower sends it`, async () => { - redirectStatus = status; - redirectTo = `http://localhost:${dest.port}/landing`; - const sendCredentialed = () => configuredOutboundFetch(`http://127.0.0.1:${dest.port}/start`, { - method: "POST", body: "synthetic-body", proxy: `http://127.0.0.1:${forwardProxy.port}`, - headers: { authorization: "Bearer synthetic-test-token", "x-api-key": "synthetic-test-key", cookie: "session=synthetic", - "proxy-authorization": "Basic c3ludGhldGlj", "content-type": "text/plain" }, - } as ProxyCapableRequestInit as RequestInit); - const native = await sendCredentialed(); - const nativeHops = viaProxy.splice(0); + for (const status of [301, 302, 303, 307, 308]) { + test(`with a bypass list set, a ${status} is refused after exactly one send`, async () => { process.env.NO_PROXY = "example.invalid"; - const followed = await sendCredentialed(); - const followedHops = viaProxy.splice(0); - expect(await followed.text()).toBe(await native.text()); - expect(followed.redirected).toBe(native.redirected); - expect(followed.redirected).toBe(true); - expect(followedHops).toEqual(nativeHops); - expect(followedHops[1]).toMatchObject({ authorization: null, cookie: null, proxyAuthorization: null, apiKey: "synthetic-test-key" }); + redirectStatus = status; + redirectTo = `http://127.0.0.1:${dest.port}/landing`; + const error = await post().then(() => null, (cause: unknown) => cause); + expect(error).toBeInstanceOf(ExplicitProxyRedirectRefusedError); + expect((error as ExplicitProxyRedirectRefusedError).code).toBe("explicit_proxy_redirect_refused"); + expect(viaProxy).toEqual([{ method: "POST", path: "/start", body: "synthetic-body" }]); }); } - test("a streamed body is not replayed across a 307, like Bun", async () => { + test("a Request carrying a streamed body is sent once and its redirect refused", async () => { process.env.NO_PROXY = "example.invalid"; redirectTo = `http://127.0.0.1:${dest.port}/landing`; const body = new ReadableStream({ start(controller) { controller.enqueue(new TextEncoder().encode("streamed")); controller.close(); } }); - await expect(configuredOutboundFetch(`http://127.0.0.1:${dest.port}/start`, { - method: "POST", body, duplex: "half", proxy: `http://127.0.0.1:${forwardProxy.port}` } as ProxyCapableRequestInit as RequestInit)).rejects.toThrow(); - expect(viaProxy.map(request => request.path)).toEqual(["/start"]); + const request = new Request(startUrl(), { method: "POST", body, duplex: "half" } as RequestInit); + await expect(configuredOutboundFetch(request, proxied())).rejects.toBeInstanceOf(ExplicitProxyRedirectRefusedError); + expect(viaProxy).toEqual([{ method: "POST", path: "/start", body: "streamed" }]); + }); + + test("without a bypass list Bun's own redirect handling is unchanged", async () => { + redirectTo = `http://127.0.0.1:${dest.port}/landing`; + const response = await post(); + expect(await response.text()).toBe("landed POST synthetic-body"); + expect(response.redirected).toBe(true); + expect(viaProxy.map(request => request.path)).toEqual(["/start", "/landing"]); }); - test("an unredirected response keeps redirected false", async () => { + test("an unredirected response passes through untouched", async () => { process.env.NO_PROXY = "example.invalid"; - const response = await configuredOutboundFetch(`http://127.0.0.1:${dest.port}/landing`, { proxy: `http://127.0.0.1:${forwardProxy.port}` } as ProxyCapableRequestInit as RequestInit); - expect(await response.text()).toBe("landed GET "); + const response = await configuredOutboundFetch(`http://127.0.0.1:${dest.port}/landing`, proxied()); expect(response.redirected).toBe(false); + expect(response.clone().redirected).toBe(false); + expect(await response.text()).toBe("landed GET "); }); test("a caller's manual redirect mode is left to the caller", async () => { process.env.NO_PROXY = `127.0.0.1:${exempt.port}`; redirectTo = `http://127.0.0.1:${exempt.port}/landing`; - const response = await configuredOutboundFetch(`http://127.0.0.1:${dest.port}/start`, { - redirect: "manual", proxy: `http://127.0.0.1:${forwardProxy.port}` } as ProxyCapableRequestInit as RequestInit); + const response = await configuredOutboundFetch(startUrl(), proxied({ redirect: "manual" })); expect(response.status).toBe(307); expect(atExempt).toEqual([]); }); From 598939f952d89237df6b66bd1de676c437111a98 Mon Sep 17 00:00:00 2001 From: JUN Date: Wed, 25 Nov 2026 12:36:31 +0900 Subject: [PATCH 08/20] fix(egress): refuse an exempted provider proxy route before dispatch side effects --- src/lib/provider-egress.ts | 11 ++++- structure/transports/inventory.md | 5 ++- tests/lib/explicit-proxy-no-proxy.test.ts | 49 +++++++++++++++++++++++ 3 files changed, 62 insertions(+), 3 deletions(-) diff --git a/src/lib/provider-egress.ts b/src/lib/provider-egress.ts index bff5c16340f..cc691dd6213 100644 --- a/src/lib/provider-egress.ts +++ b/src/lib/provider-egress.ts @@ -26,7 +26,7 @@ * therefore a configuration error naming both real alternatives. */ import type { OcxProviderConfig } from "../types"; -import { isSocks5ProxyUrl, noProxyMatches } from "./proxy-env"; +import { explicitProxyExemptedError, isSocks5ProxyUrl, noProxyMatches, processNoProxyExempts } from "./proxy-env"; export class InvalidProviderEgressError extends Error { override readonly name = "InvalidProviderEgressError"; @@ -281,6 +281,15 @@ export function providerEgressSendInit( const url = egressTargetUrl(input); if (url === null) return {}; const egress = resolveProviderEgress({ providerName: binding.providerName, provider: binding.provider, url }); + // Decided here, before any dispatch side effect (attempt accounting, dispatch receipts): an HTTP(S) + // proxy route toward a destination the process NO_PROXY exempts would leave without the proxy. + // `configuredOutboundFetch` keeps the same check as a backstop for callers outside this boundary. + if (egress.kind === "proxy" && egress.transport === "http") { + const target = parseTargetUrl(binding.providerName, url); + if ((target.protocol === "http:" || target.protocol === "https:") && processNoProxyExempts(target)) { + throw explicitProxyExemptedError(target); + } + } if (providerEgressIsExplicit(egress) && !isEgressTransparentExecutor(physicalFetch)) { // Name the field that actually made the route explicit. A bypass-list match with no // `proxy` field at all would otherwise tell the operator to remove an override they diff --git a/structure/transports/inventory.md b/structure/transports/inventory.md index bb8fd6939f7..4b070ab5b8b 100644 --- a/structure/transports/inventory.md +++ b/structure/transports/inventory.md @@ -197,8 +197,9 @@ A reset-triggered rebuild may retarget the request to another region's canonical `src/lib/provider-egress.ts` resolves a provider route for one destination. The route is carried only by transports that can preserve that request-local decision. An explicit HTTP(S) proxy is never sent toward a destination that the process `NO_PROXY` or `no_proxy` exempts, because Bun's fetch and -WebSocket connect directly there: `configuredOutboundFetch` refuses the send with -`ExplicitProxyExemptedError`, the Responses WebSocket upstream leaves such a turn to that HTTP path, and +WebSocket connect directly there: `providerEgressSendInit` refuses such a route before any dispatch +side effect (attempt accounting, dispatch receipts), `configuredOutboundFetch` refuses the send with +`ExplicitProxyExemptedError` as a backstop for every other caller, the Responses WebSocket upstream leaves such a turn to that HTTP path, and the Microsoft 365 Copilot ChatHub dial refuses before creating its socket. `processNoProxyExempts` matches at least as broadly as Bun: `bunNoProxyMatches` ports the `NO_PROXY` matcher of Bun 1.4.4 (comma and whitespace separators, subdomains, CIDR blocks, numeric ports, canonical addresses), unioned diff --git a/tests/lib/explicit-proxy-no-proxy.test.ts b/tests/lib/explicit-proxy-no-proxy.test.ts index 28488142087..b37d557f8d6 100644 --- a/tests/lib/explicit-proxy-no-proxy.test.ts +++ b/tests/lib/explicit-proxy-no-proxy.test.ts @@ -14,6 +14,8 @@ import { type ProxyCapableRequestInit, } from "../../src/lib/proxy-env"; import { providerEgressFetchInit, resolveProviderEgress } from "../../src/lib/provider-egress"; +import { providerFetch } from "../../src/server/responses/fetch-helpers"; +import type { OcxProviderConfig } from "../../src/types"; const ENV_KEYS = ["NO_PROXY", "no_proxy", "HTTP_PROXY", "http_proxy", "HTTPS_PROXY", "https_proxy", "ALL_PROXY", "all_proxy"] as const; const saved = new Map(); @@ -157,6 +159,44 @@ test("every entry form Bun 1.4.4 treats as a bypass is a bypass here", () => { expect(processNoProxyExempts(new URL("http://[::1]:8080/x"), { NO_PROXY: "[::1]" })).toBe(true); }); +describe("the provider send boundary", () => { + const provider = () => ({ adapter: "openai-chat", baseUrl: `http://127.0.0.1:${dest.port}/v1`, proxy: proxyUrl }) as unknown as OcxProviderConfig; + + test("an exempted provider proxy route is refused before any dispatch side effect", async () => { + process.env.NO_PROXY = "127.0.0.1"; + let receipts = 0; + let checked = 0; + const send = providerFetch(provider(), undefined, { + providerName: "p", onPhysicalDispatch: () => { receipts += 1; }, beforeDispatch: () => { checked += 1; }, + }); + await expect(send(destUrl, { method: "POST", body: "synthetic-body" })).rejects.toBeInstanceOf(ExplicitProxyExemptedError); + expect({ receipts, checked }).toEqual({ receipts: 0, checked: 0 }); + expect(hits).toEqual({ dest: 0, proxy: 0 }); + }); + + test("a destination rebuilt by a dispatch override is decided before its dispatch receipt", async () => { + process.env.NO_PROXY = "localhost"; + let receipts = 0; + const send = providerFetch(provider(), undefined, { + providerName: "p", onPhysicalDispatch: () => { receipts += 1; }, + // The queued request is rebuilt against another host at its physical send. + dispatchOverride: (_input, init, execute) => execute(`http://localhost:${dest.port}/v1/models`, init), + }); + await expect(send(destUrl, { method: "POST", body: "synthetic-body" })).rejects.toBeInstanceOf(ExplicitProxyExemptedError); + expect(receipts).toBe(0); + expect(hits).toEqual({ dest: 0, proxy: 0 }); + }); + + test("a route that is not exempted still dispatches once through the proxy", async () => { + process.env.NO_PROXY = "example.invalid"; + let receipts = 0; + const send = providerFetch(provider(), undefined, { providerName: "p", onPhysicalDispatch: () => { receipts += 1; } }); + expect(await (await send(destUrl, { method: "POST", body: "synthetic-body" })).text()).toBe("proxy"); + expect(receipts).toBe(1); + expect(hits).toEqual({ dest: 0, proxy: 1 }); + }); +}); + describe("redirects of an explicit-proxy request", () => { type Seen = { method: string; path: string; body: string }; const viaProxy: Seen[] = []; @@ -232,6 +272,15 @@ describe("redirects of an explicit-proxy request", () => { expect(await response.text()).toBe("landed GET "); }); + test("a caller's error redirect mode reaches Bun unchanged and makes no second request", async () => { + process.env.NO_PROXY = "example.invalid"; + redirectTo = `http://127.0.0.1:${dest.port}/landing`; + const error = await configuredOutboundFetch(startUrl(), proxied({ redirect: "error" })).then(() => null, (cause: unknown) => cause); + expect(error).toBeInstanceOf(Error); + expect(error).not.toBeInstanceOf(ExplicitProxyRedirectRefusedError); + expect(viaProxy.map(request => request.path)).toEqual(["/start"]); + }); + test("a caller's manual redirect mode is left to the caller", async () => { process.env.NO_PROXY = `127.0.0.1:${exempt.port}`; redirectTo = `http://127.0.0.1:${exempt.port}/landing`; From 3e6f7c6cf4b183faef133cdb2e0d807c8f8a2583 Mon Sep 17 00:00:00 2001 From: JUN Date: Wed, 25 Nov 2026 12:40:34 +0900 Subject: [PATCH 09/20] fix(egress): decide the NO_PROXY exemption on the rewritten destination --- src/lib/provider-egress.ts | 11 +++++++---- src/server/responses/fetch-helpers.ts | 6 ++++-- structure/transports/inventory.md | 5 +++-- tests/lib/explicit-proxy-no-proxy.test.ts | 17 +++++++++++++++++ 4 files changed, 31 insertions(+), 8 deletions(-) diff --git a/src/lib/provider-egress.ts b/src/lib/provider-egress.ts index cc691dd6213..0ee65652f3a 100644 --- a/src/lib/provider-egress.ts +++ b/src/lib/provider-egress.ts @@ -277,14 +277,17 @@ export function providerEgressSendInit( binding: ProviderEgressBinding, physicalFetch: unknown, input: string | URL | Request, + /** False for an early check whose destination a plugin rewrite or an override may still change. */ + options: { exemption?: boolean } = {}, ): { proxy?: string | false } { const url = egressTargetUrl(input); if (url === null) return {}; const egress = resolveProviderEgress({ providerName: binding.providerName, provider: binding.provider, url }); - // Decided here, before any dispatch side effect (attempt accounting, dispatch receipts): an HTTP(S) - // proxy route toward a destination the process NO_PROXY exempts would leave without the proxy. - // `configuredOutboundFetch` keeps the same check as a backstop for callers outside this boundary. - if (egress.kind === "proxy" && egress.transport === "http") { + // 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 + // change the destination. `configuredOutboundFetch` keeps the check as a backstop for other callers. + if (options.exemption !== false && egress.kind === "proxy" && egress.transport === "http") { const target = parseTargetUrl(binding.providerName, url); if ((target.protocol === "http:" || target.protocol === "https:") && processNoProxyExempts(target)) { throw explicitProxyExemptedError(target); diff --git a/src/server/responses/fetch-helpers.ts b/src/server/responses/fetch-helpers.ts index 8d802ad417c..6750fe5b767 100644 --- a/src/server/responses/fetch-helpers.ts +++ b/src/server/responses/fetch-helpers.ts @@ -25,7 +25,7 @@ import { providerTlsFetch } from "../../lib/provider-tls-profile"; import { inheritPassiveKeyProof, markPassiveKeyTransparent } from "../../lib/passive-key-fetch-proof"; import type { CodexWsQuotaObserver } from "./codex-ws-metadata"; import { configuredOutboundFetch } from "../../lib/proxy-env"; -import { isLoopbackUrl, rewriteUpstream } from "../../plugins/upstream-hooks"; +import { hasUpstreamRewriters, isLoopbackUrl, rewriteUpstream } from "../../plugins/upstream-hooks"; import { describeProviderEgressForLog, bindProviderSocketRoute, @@ -405,8 +405,10 @@ export function providerFetch( // full decision can be made now. With an override, only the configured value is checked: // the override may rebuild against a different host and select a different transport, and // refusing on this destination would reject a request whose real route is fine. + // The NO_PROXY exemption is asked early only when this URL is final: a plugin rewrite may + // still move it, and is then decided at the physical send, before its receipt. if (override) egressFor(input); - else providerEgressSendInit(egressBinding, transport, input); + else providerEgressSendInit(egressBinding, transport, input, { exemption: !hasUpstreamRewriters() }); // The hook inspects the outgoing headers and refuses the send by throwing; it is not a // mutator, and the copy it receives is deliberately not threaded onward. `Connection` // is decided inside `dispatch`, which runs after this, so the fresh-connection policy diff --git a/structure/transports/inventory.md b/structure/transports/inventory.md index 4b070ab5b8b..f41fd73bd1b 100644 --- a/structure/transports/inventory.md +++ b/structure/transports/inventory.md @@ -197,8 +197,9 @@ A reset-triggered rebuild may retarget the request to another region's canonical `src/lib/provider-egress.ts` resolves a provider route for one destination. The route is carried only by transports that can preserve that request-local decision. An explicit HTTP(S) proxy is never sent toward a destination that the process `NO_PROXY` or `no_proxy` exempts, because Bun's fetch and -WebSocket connect directly there: `providerEgressSendInit` refuses such a route before any dispatch -side effect (attempt accounting, dispatch receipts), `configuredOutboundFetch` refuses the send with +WebSocket connect directly there: `providerEgressSendInit` refuses such a route against the destination +actually sent, before its dispatch receipt (and before `beforeDispatch` when no plugin rewrite or +dispatch override can still change the destination), `configuredOutboundFetch` refuses the send with `ExplicitProxyExemptedError` as a backstop for every other caller, the Responses WebSocket upstream leaves such a turn to that HTTP path, and the Microsoft 365 Copilot ChatHub dial refuses before creating its socket. `processNoProxyExempts` matches at least as broadly as Bun: `bunNoProxyMatches` ports the `NO_PROXY` matcher of Bun 1.4.4 diff --git a/tests/lib/explicit-proxy-no-proxy.test.ts b/tests/lib/explicit-proxy-no-proxy.test.ts index b37d557f8d6..f0e37c03854 100644 --- a/tests/lib/explicit-proxy-no-proxy.test.ts +++ b/tests/lib/explicit-proxy-no-proxy.test.ts @@ -15,6 +15,7 @@ import { } from "../../src/lib/proxy-env"; import { providerEgressFetchInit, resolveProviderEgress } from "../../src/lib/provider-egress"; import { providerFetch } from "../../src/server/responses/fetch-helpers"; +import { registerUpstreamRewriter } from "../../src/plugins/upstream-hooks"; import type { OcxProviderConfig } from "../../src/types"; const ENV_KEYS = ["NO_PROXY", "no_proxy", "HTTP_PROXY", "http_proxy", "HTTPS_PROXY", "https_proxy", "ALL_PROXY", "all_proxy"] as const; @@ -187,6 +188,22 @@ describe("the provider send boundary", () => { expect(hits).toEqual({ dest: 0, proxy: 0 }); }); + test("an exempted original URL that a plugin rewrites to a local sidecar is not refused early", async () => { + process.env.NO_PROXY = "example.com"; + const unregister = registerUpstreamRewriter("test-sidecar", target => { + if (target.url.startsWith("https://example.com/")) target.url = `http://127.0.0.1:${dest.port}/v1/models`; + }); + try { + const send = providerFetch({ adapter: "openai-chat", baseUrl: "https://example.com/v1", proxy: proxyUrl } as unknown as OcxProviderConfig, + undefined, { providerName: "p" }); + expect(await (await send("https://example.com/v1/models")).text()).toBe("dest"); + // A rewrite onto this machine's loopback dials directly, as before. + expect(hits).toEqual({ dest: 1, proxy: 0 }); + } finally { + unregister(); + } + }); + test("a route that is not exempted still dispatches once through the proxy", async () => { process.env.NO_PROXY = "example.invalid"; let receipts = 0; From 1f5256b4c3a2334ad2129b04ea6015b3ff47ac85 Mon Sep 17 00:00:00 2001 From: JUN Date: Wed, 25 Nov 2026 12:45:05 +0900 Subject: [PATCH 10/20] test(egress): the TLS profile transport never receives an exempted route --- structure/transports/inventory.md | 3 ++- tests/lib/explicit-proxy-no-proxy.test.ts | 19 +++++++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/structure/transports/inventory.md b/structure/transports/inventory.md index f41fd73bd1b..b62c444bc19 100644 --- a/structure/transports/inventory.md +++ b/structure/transports/inventory.md @@ -200,7 +200,8 @@ toward a destination that the process `NO_PROXY` or `no_proxy` exempts, because WebSocket connect directly there: `providerEgressSendInit` refuses such a route against the destination actually sent, before its dispatch receipt (and before `beforeDispatch` when no plugin rewrite or dispatch override can still change the destination), `configuredOutboundFetch` refuses the send with -`ExplicitProxyExemptedError` as a backstop for every other caller, the Responses WebSocket upstream leaves such a turn to that HTTP path, and +`ExplicitProxyExemptedError` as a backstop for every other caller (the Antigravity TLS profile +transport, reachable only through `providerFetch`, therefore never receives such a route), the Responses WebSocket upstream leaves such a turn to that HTTP path, and the Microsoft 365 Copilot ChatHub dial refuses before creating its socket. `processNoProxyExempts` matches at least as broadly as Bun: `bunNoProxyMatches` ports the `NO_PROXY` matcher of Bun 1.4.4 (comma and whitespace separators, subdomains, CIDR blocks, numeric ports, canonical addresses), unioned diff --git a/tests/lib/explicit-proxy-no-proxy.test.ts b/tests/lib/explicit-proxy-no-proxy.test.ts index f0e37c03854..b1cbaac0ed7 100644 --- a/tests/lib/explicit-proxy-no-proxy.test.ts +++ b/tests/lib/explicit-proxy-no-proxy.test.ts @@ -16,6 +16,7 @@ import { import { providerEgressFetchInit, resolveProviderEgress } from "../../src/lib/provider-egress"; import { providerFetch } from "../../src/server/responses/fetch-helpers"; import { registerUpstreamRewriter } from "../../src/plugins/upstream-hooks"; +import { resetProviderTlsProfileForTests, setProviderTlsRuntimeForTest } from "../../src/lib/provider-tls-profile"; import type { OcxProviderConfig } from "../../src/types"; const ENV_KEYS = ["NO_PROXY", "no_proxy", "HTTP_PROXY", "http_proxy", "HTTPS_PROXY", "https_proxy", "ALL_PROXY", "all_proxy"] as const; @@ -204,6 +205,24 @@ describe("the provider send boundary", () => { } }); + test("the Antigravity TLS profile transport never receives an exempted proxy route", async () => { + process.env.NO_PROXY = ".googleapis.com"; + let tlsSends = 0; + setProviderTlsRuntimeForTest({ env: { ...process.env }, fetch: async () => { tlsSends += 1; return new Response("tls"); } }); + try { + const send = providerFetch({ + adapter: "google", authMode: "oauth", googleMode: "cloud-code-assist", baseUrl: "https://cloudcode-pa.googleapis.com", + tlsProfile: "antigravity-browser", proxy: proxyUrl, + } as unknown as OcxProviderConfig, undefined, { providerName: "google-antigravity" }); + await expect(send("https://cloudcode-pa.googleapis.com/v1internal:streamGenerateContent", { method: "POST", body: "{}" })) + .rejects.toBeInstanceOf(ExplicitProxyExemptedError); + expect(tlsSends).toBe(0); + expect(hits).toEqual({ dest: 0, proxy: 0 }); + } finally { + resetProviderTlsProfileForTests(); + } + }); + test("a route that is not exempted still dispatches once through the proxy", async () => { process.env.NO_PROXY = "example.invalid"; let receipts = 0; From 44c2dc8d229a2b11aef865ecd8cb1d96dae36706 Mon Sep 17 00:00:00 2001 From: JUN Date: Wed, 25 Nov 2026 12:52:02 +0900 Subject: [PATCH 11/20] feat(egress): per-account routes for Codex pool accounts (G-012) --- .../es/reference/configuration/providers.md | 2 +- .../docs/reference/configuration/providers.md | 5 + .../test-layout/layout-server-inbound.json | 1 + src/codex/account-egress.ts | 14 ++ src/codex/account-store.ts | 10 +- src/config/schema/config-schema.ts | 7 + src/lib/provider-egress.ts | 72 ++++++--- src/server/responses/core-codex-account.ts | 3 +- src/server/responses/fetch-helpers.ts | 9 +- src/server/responses/passthrough-dispatch.ts | 14 +- src/types/accounts.ts | 2 + src/types/pool-account.ts | 12 ++ structure/config.md | 2 +- structure/transports/inventory.md | 1 + tests/fixtures/test-layout-expected.json | 2 +- tests/lib/provider-egress-account.test.ts | 148 ++++++++++++++++++ 16 files changed, 274 insertions(+), 30 deletions(-) create mode 100644 src/codex/account-egress.ts create mode 100644 src/types/pool-account.ts create mode 100644 tests/lib/provider-egress-account.test.ts 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 e497dd6420c..e6306427671 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 para las solicitudes y las renovaciones de token de esa cuenta, un `proxy` omitido conserva el del proveedor, y las entradas `noProxy` de la cuenta se aplican antes que las del proveedor. 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 b476d90119a..f7294d37bd3 100644 --- a/docs-site/src/content/docs/reference/configuration/providers.md +++ b/docs-site/src/content/docs/reference/configuration/providers.md @@ -1425,6 +1425,11 @@ 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 +provider's for that account's requests and token refreshes, an omitted `proxy` keeps the provider's, +and the account's `noProxy` entries apply ahead of the provider's. 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 13ec55a193e..c3dc4f85a41 100644 --- a/scripts/test-layout/layout-server-inbound.json +++ b/scripts/test-layout/layout-server-inbound.json @@ -1,4 +1,5 @@ { + "provider-egress-account.test.ts": "lib", "explicit-proxy-no-proxy.test.ts": "lib", "gemini-native.test.ts": "server", "gemini-native-wire.test.ts": "server", 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..6b136fc696c 100644 --- a/src/codex/account-store.ts +++ b/src/codex/account-store.ts @@ -1,4 +1,7 @@ import { publishCredentialSync } from "../local-credentials/generation"; +import { codexAccountEgressRoute } from "./account-egress"; +import { providerEgressFetchInit, resolveProviderEgress } from "../lib/provider-egress"; +import { configuredOutboundFetch } from "../lib/proxy-env"; import { classifyChatgptRefreshFailure, noteChatgptRefreshFailure, type ChatgptRefreshDiagnosticCode } from "./chatgpt-refresh-failure"; import { readBoundedResponseBody } from "../lib/bounded-body"; export { classifyChatgptRefreshFailure } from "./chatgpt-refresh-failure"; @@ -1405,7 +1408,12 @@ 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 accountRoute = codexAccountEgressRoute(loadConfig(), id); + const res = await (accountRoute ? configuredOutboundFetch : fetch)(CHATGPT_TOKEN_URL, { + ...(accountRoute ? providerEgressFetchInit(resolveProviderEgress({ + providerName: "codex-account", provider: {}, url: CHATGPT_TOKEN_URL, account: accountRoute, + })) : {}), method: "POST", headers: { "Content-Type": "application/json", 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/server/responses/core-codex-account.ts b/src/server/responses/core-codex-account.ts index f93e2c17185..eebd7ad6766 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"; @@ -1085,7 +1086,7 @@ export async function retryCodexPoolOnAlternateAccount( upstream.signal, connectMs, stream, - providerFetch(retryProvider, options.codexWsRuntimeIdentity, { + providerFetch(retryProvider, options.codexWsRuntimeIdentity, { account: () => codexAccountEgressRoute(config, codexLogAccountId(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 6750fe5b767..bb07beb8e78 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"; @@ -339,6 +340,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; @@ -354,7 +360,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 @@ -363,6 +369,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..29fdfe4b625 100644 --- a/src/server/responses/passthrough-dispatch.ts +++ b/src/server/responses/passthrough-dispatch.ts @@ -114,7 +114,9 @@ import { retryCodexPoolOnAlternateAccount, PoolPreOutputRefusals, subscriptionPreOutputRefusalHold, + codexLogAccountId, } from "./core-codex-account"; +import { codexAccountEgressRoute } from "../../codex/account-egress"; import { codexAuthContextLogLabel } from "../../codex/account-label"; import { clearCodexModelDenialEvidence, @@ -269,6 +271,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 = () => codexAccountEgressRoute(config, codexLogAccountId(admissionState.authCtx)); const codexWsCaller = codexWsAdmittedCaller(options.replayPrincipal, () => resolveContextPrincipal(req, config, options.admission)); const { route, @@ -817,7 +821,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 +1015,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 +1096,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 +1190,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 +1560,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 2868b014795..4f2e9bd645c 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..3ac0c888939 100644 --- a/structure/transports/inventory.md +++ b/structure/transports/inventory.md @@ -212,6 +212,7 @@ 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 token refresh 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` 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; `forceRefreshCodexPoolToken` in `src/codex/account-store.ts` refreshes through the same route. `tests/lib/provider-egress-account.test.ts` covers both on real loopback proxies. | | 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/fixtures/test-layout-expected.json b/tests/fixtures/test-layout-expected.json index 62d6195715a..258e3d74112 100644 --- a/tests/fixtures/test-layout-expected.json +++ b/tests/fixtures/test-layout-expected.json @@ -1,4 +1,4 @@ -{ "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", "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/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); +}); From b551eff4e7a053ee7e12087f0f0fe54f50ab1c09 Mon Sep 17 00:00:00 2001 From: JUN Date: Wed, 25 Nov 2026 13:07:00 +0900 Subject: [PATCH 12/20] fix(egress): carry the pool account route on compact, usage, discovery, reset-credit and refresh calls Native compact now reads the send-time pool account's route. Token refresh, usage probes (initial and 401 replay), model discovery and reset-credit inspect/consume send through codexAccountFetch, which resolves the account route over the openai provider's against the server's bound live config, or refuses in a CLI process whose config load fell back to defaults. An account that names no proxy keeps the provider's, as documented. --- .../es/reference/configuration/providers.md | 2 +- .../docs/reference/configuration/providers.md | 9 +- .../test-layout/layout-server-inbound.json | 1 + scripts/test-layout/layout.json | 2 +- src/codex/account-egress-runtime.ts | 91 ++++++++++ src/codex/account-store.ts | 10 +- src/codex/auth-api/pool-quota-probe.ts | 9 +- src/codex/auth-api/reset-credit-service.ts | 9 +- src/codex/model-entitlements.ts | 5 +- src/codex/quota-query-backoff.ts | 6 +- src/lib/state-store-registrations.ts | 2 + src/server/responses/compact.ts | 4 +- src/server/responses/core-codex-account.ts | 6 +- src/server/responses/passthrough-dispatch.ts | 5 +- structure/transports/inventory.md | 3 +- tests/fixtures/test-layout-expected.json | 2 +- .../lib/provider-egress-account-calls.test.ts | 170 ++++++++++++++++++ .../codex-pool-account-egress-compact.test.ts | 82 +++++++++ 18 files changed, 383 insertions(+), 35 deletions(-) create mode 100644 src/codex/account-egress-runtime.ts create mode 100644 tests/lib/provider-egress-account-calls.test.ts create mode 100644 tests/responses/codex-pool-account-egress-compact.test.ts 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 e6306427671..3d8a7efcbad 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. 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 para las solicitudes y las renovaciones de token de esa cuenta, un `proxy` omitido conserva el del proveedor, y las entradas `noProxy` de la cuenta se aplican antes que las del proveedor. El inicio de sesión principal no tiene entrada en el grupo y siempre usa la ruta del proveedor. +`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, descubrimiento de modelos y llamadas de créditos de reinicio de esa cuenta; un `proxy` omitido conserva el del proveedor, y las entradas `noProxy` de la cuenta se aplican antes que las del proveedor. Una cuenta del grupo sin objeto `egress` también envía esas llamadas por la ruta del proveedor `openai`. Si `config.json` no se puede leer, un comando de la CLI rechaza esas llamadas en lugar de enviarlas 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 f7294d37bd3..5582ff71dda 100644 --- a/docs-site/src/content/docs/reference/configuration/providers.md +++ b/docs-site/src/content/docs/reference/configuration/providers.md @@ -1425,11 +1425,10 @@ 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 -provider's for that account's requests and token refreshes, an omitted `proxy` keeps the provider's, -and the account's `noProxy` entries apply ahead of the provider's. The main login has no pool entry and -always uses the provider's route. +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, model discovery and reset-credit calls; an omitted `proxy` keeps the provider's, and the account's `noProxy` entries apply ahead of the provider's. +A pool account without an `egress` object sends those calls by the `openai` provider's route too. +If `config.json` cannot be read, a CLI command refuses these calls instead of sending them 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 c3dc4f85a41..30812e9459b 100644 --- a/scripts/test-layout/layout-server-inbound.json +++ b/scripts/test-layout/layout-server-inbound.json @@ -1,5 +1,6 @@ { "provider-egress-account.test.ts": "lib", + "provider-egress-account-calls.test.ts": "lib", "explicit-proxy-no-proxy.test.ts": "lib", "gemini-native.test.ts": "server", "gemini-native-wire.test.ts": "server", diff --git a/scripts/test-layout/layout.json b/scripts/test-layout/layout.json index 9560e77348e..687ffb6c40c 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-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", "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..e6693a9533c --- /dev/null +++ b/src/codex/account-egress-runtime.ts @@ -0,0 +1,91 @@ +import { existsSync } from "node:fs"; +import { getConfigPath, loadConfig } from "../config"; +import { 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"; + +/** + * Routes for Codex pool calls that run without a request's config in hand: token refresh, usage + * (WHAM) probes, model entitlement discovery and reset-credit calls. + * + * 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 running server binds its live config here (`setLiveStateStoreConfig`), so these calls read the + * same routes as inference without reloading the file. A process with no live config (a CLI command) + * loads the file instead, and refuses when that load fell back to defaults while `config.json` + * exists: a route the operator configured must not be silently dropped. + */ +export type CodexAccountEgressConfig = Pick; + +let liveConfig: CodexAccountEgressConfig | undefined; + +export function bindCodexAccountEgressConfig(config: CodexAccountEgressConfig): void { + liveConfig = config; +} + +/** Tests only. */ +export function resetCodexAccountEgressConfigForTests(): void { + liveConfig = undefined; +} + +export class CodexAccountRouteUnavailableError extends Error { + override readonly name = "CodexAccountRouteUnavailableError"; +} + +/** The provider whose route a pool account inherits. */ +export const CODEX_POOL_PROVIDER = "openai"; + +function routingConfig(): CodexAccountEgressConfig { + if (liveConfig) return liveConfig; + const config = loadConfig(); + if (fileBackedConfigPath(config) === undefined && existsSync(getConfigPath())) { + throw new CodexAccountRouteUnavailableError("Codex account routing configuration could not be loaded; refusing to send without it"); + } + return config; +} + +interface CodexAccountRouting { + provider: Pick; + account?: PoolAccountRoute; +} + +/** + * The routing inputs for one pool account's call, or undefined when nothing configures a route for + * it (not a pool account, or neither the account nor the provider sets `proxy`/`noProxy`), in which + * case the call keeps the process-wide route unchanged. + */ +export function codexAccountRouting( + accountId: string | null | undefined, config?: CodexAccountEgressConfig, +): CodexAccountRouting | undefined { + if (!accountId) return undefined; + const source = config ?? routingConfig(); + if (!source.codexAccounts?.some(row => row.id === accountId && row.isMain !== true)) return undefined; + 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 pool account's credentialed call. 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, base?: typeof globalThis.fetch, config?: CodexAccountEgressConfig, +): typeof globalThis.fetch { + const routing = codexAccountRouting(accountId, config); + if (!routing) return base ?? (((input: RequestInfo | URL, init?: RequestInit) => fetch(input, init)) as typeof globalThis.fetch); + return ((input: RequestInfo | URL, init?: RequestInit) => + configuredOutboundFetch(input, { ...init, ...routeInit(routing, input) } as RequestInit, base)) as typeof globalThis.fetch; +} diff --git a/src/codex/account-store.ts b/src/codex/account-store.ts index 6b136fc696c..a6790cfc95d 100644 --- a/src/codex/account-store.ts +++ b/src/codex/account-store.ts @@ -1,7 +1,5 @@ import { publishCredentialSync } from "../local-credentials/generation"; -import { codexAccountEgressRoute } from "./account-egress"; -import { providerEgressFetchInit, resolveProviderEgress } from "../lib/provider-egress"; -import { configuredOutboundFetch } from "../lib/proxy-env"; +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"; @@ -1409,11 +1407,7 @@ async function resolveCodexToken( }; } // An account with its own route (codexAccounts[].egress) refreshes through it, like its requests. - const accountRoute = codexAccountEgressRoute(loadConfig(), id); - const res = await (accountRoute ? configuredOutboundFetch : fetch)(CHATGPT_TOKEN_URL, { - ...(accountRoute ? providerEgressFetchInit(resolveProviderEgress({ - providerName: "codex-account", provider: {}, url: CHATGPT_TOKEN_URL, account: accountRoute, - })) : {}), + const res = await codexAccountFetch(id)(CHATGPT_TOKEN_URL, { method: "POST", headers: { "Content-Type": "application/json", diff --git a/src/codex/auth-api/pool-quota-probe.ts b/src/codex/auth-api/pool-quota-probe.ts index 3d6ae70bd3e..e0cae57b262 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 diff --git a/src/codex/auth-api/reset-credit-service.ts b/src/codex/auth-api/reset-credit-service.ts index 23ff21da88d..cda8aa70aff 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, undefined, getRuntimeConfig(config))("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, undefined, getRuntimeConfig(config))("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, undefined, getRuntimeConfig(config))( "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, undefined, getRuntimeConfig(config))( "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 255d5a3bf63..4be0e5683b9 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"; @@ -755,7 +756,7 @@ async function fetchAccountModels( Accept: "application/json", }); if (credential.chatgptAccountId) headers.set("ChatGPT-Account-Id", credential.chatgptAccountId); - const response = await fetcher(codexModelsUrl(clientVersion), { + const response = await codexAccountFetch(credential.accountId, fetcher)(codexModelsUrl(clientVersion), { headers, redirect: "error", signal: controller.signal, @@ -909,7 +910,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, fetcher)(codexModelsUrl(CODEX_ROSTER_DISCOVERY_CLIENT_VERSION), { headers, redirect: "error", signal: controller.signal, 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/lib/state-store-registrations.ts b/src/lib/state-store-registrations.ts index 20121e6e894..47bb5edfb17 100644 --- a/src/lib/state-store-registrations.ts +++ b/src/lib/state-store-registrations.ts @@ -1,3 +1,4 @@ +import { bindCodexAccountEgressConfig } from "../codex/account-egress-runtime"; import { bindCodexWsIncrementalConfig } from "../config/codex-ws-incremental-setting"; import { bindUpstreamHistorySlimConfig } from "../server/responses/history-slim"; import { @@ -89,6 +90,7 @@ export function setLiveStateStoreConfig(config: OcxConfig): void { bindUpstreamHistorySlimConfig(config); bindCodexWsIncrementalConfig(config); bindWorkflowBudgetConfig(config); + bindCodexAccountEgressConfig(config); notifyLiveConfigObservers(config); } 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 eebd7ad6766..777f81f6c8b 100644 --- a/src/server/responses/core-codex-account.ts +++ b/src/server/responses/core-codex-account.ts @@ -123,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") @@ -1086,7 +1090,7 @@ export async function retryCodexPoolOnAlternateAccount( upstream.signal, connectMs, stream, - providerFetch(retryProvider, options.codexWsRuntimeIdentity, { account: () => codexAccountEgressRoute(config, codexLogAccountId(retryAuthCtx)), + providerFetch(retryProvider, options.codexWsRuntimeIdentity, { account: () => codexPoolAccountEgressRoute(config, retryAuthCtx), httpOnly, providerName: route.providerName, modelId: route.modelId, diff --git a/src/server/responses/passthrough-dispatch.ts b/src/server/responses/passthrough-dispatch.ts index 29fdfe4b625..539156810e3 100644 --- a/src/server/responses/passthrough-dispatch.ts +++ b/src/server/responses/passthrough-dispatch.ts @@ -114,9 +114,8 @@ import { retryCodexPoolOnAlternateAccount, PoolPreOutputRefusals, subscriptionPreOutputRefusalHold, - codexLogAccountId, + codexPoolAccountEgressRoute, } from "./core-codex-account"; -import { codexAccountEgressRoute } from "../../codex/account-egress"; import { codexAuthContextLogLabel } from "../../codex/account-label"; import { clearCodexModelDenialEvidence, @@ -272,7 +271,7 @@ 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 = () => codexAccountEgressRoute(config, codexLogAccountId(admissionState.authCtx)); + const accountRoute = () => codexPoolAccountEgressRoute(config, admissionState.authCtx); const codexWsCaller = codexWsAdmittedCaller(options.replayPrincipal, () => resolveContextPrincipal(req, config, options.admission)); const { route, diff --git a/structure/transports/inventory.md b/structure/transports/inventory.md index 3ac0c888939..b4d1896eb10 100644 --- a/structure/transports/inventory.md +++ b/structure/transports/inventory.md @@ -212,7 +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 token refresh 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` 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; `forceRefreshCodexPoolToken` in `src/codex/account-store.ts` refreshes through the same route. `tests/lib/provider-egress-account.test.ts` covers both on real loopback proxies. | +| 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, and reset-credit inspect/consume | Honoured | `codexAccountFetch` in `src/codex/account-egress-runtime.ts` resolves the account's route over the `openai` provider's against the server's bound live config (or, in a CLI process, the loaded file, refusing when that load fell back to defaults) and sends through `configuredOutboundFetch`, so the explicit-proxy guards apply. `tests/lib/provider-egress-account-calls.test.ts` asserts the route each call receives with a fake transport, plus the NO_PROXY refusal and the unreadable-config refusal; 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/fixtures/test-layout-expected.json b/tests/fixtures/test-layout-expected.json index 258e3d74112..9ad71a1e782 100644 --- a/tests/fixtures/test-layout-expected.json +++ b/tests/fixtures/test-layout-expected.json @@ -1,4 +1,4 @@ -{ "provider-egress-account.test.ts": "lib", "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", "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/lib/provider-egress-account-calls.test.ts b/tests/lib/provider-egress-account-calls.test.ts new file mode 100644 index 00000000000..6a00adbaca0 --- /dev/null +++ b/tests/lib/provider-egress-account-calls.test.ts @@ -0,0 +1,170 @@ +/** + * 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(); + expect(codexAccountRouting("unknown", config)).toBeUndefined(); + 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/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 }]); +}); From 7f975d82e5e6a5c9fbe216b9c59e1abda3e473ad Mon Sep 17 00:00:00 2001 From: JUN Date: Wed, 25 Nov 2026 13:24:40 +0900 Subject: [PATCH 13/20] fix(egress): route pool warmups and login checks, refuse removed accounts, scope the live binding Warmups (token guardian, quota auto-refresh, deferred validation) and the login usage read and warmup send through the account's route. The route is resolved at each send: a removed account (row gone, credential tombstoned) is refused, and a stored credential with no row takes the openai provider's route. The server binds its config for its background lifecycle with the config path and load status, refuses when it started on an unreadable config, and detaches on final release or a failed start. --- .../es/reference/configuration/providers.md | 2 +- .../docs/reference/configuration/providers.md | 4 +- scripts/test-layout/layout.json | 2 +- src/codex/account-egress-runtime.ts | 101 +++++--- src/codex/account-store.ts | 4 +- src/codex/auth-api/login-flow.ts | 10 +- src/codex/auth-api/pool-quota-probe.ts | 1 + src/codex/auth-api/reset-credit-service.ts | 8 +- src/codex/model-entitlements.ts | 4 +- src/codex/quota-auto-refresh.ts | 3 +- src/codex/warmup.ts | 4 +- src/config/rebase-provenance.ts | 12 + src/config/salvage.ts | 2 + src/lib/state-store-registrations.ts | 2 - src/oauth/token-guardian.ts | 2 + src/server/background-lifecycle.ts | 6 + structure/transports/inventory.md | 2 +- .../codex-account-egress-background.test.ts | 229 ++++++++++++++++++ tests/fixtures/test-layout-expected.json | 2 +- .../lib/provider-egress-account-calls.test.ts | 13 +- 20 files changed, 360 insertions(+), 53 deletions(-) create mode 100644 tests/codex-integration/codex-account-egress-background.test.ts 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 3d8a7efcbad..65284496293 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. 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, descubrimiento de modelos y llamadas de créditos de reinicio de esa cuenta; un `proxy` omitido conserva el del proveedor, y las entradas `noProxy` de la cuenta se aplican antes que las del proveedor. Una cuenta del grupo sin objeto `egress` también envía esas llamadas por la ruta del proveedor `openai`. Si `config.json` no se puede leer, un comando de la CLI rechaza esas llamadas en lugar de enviarlas sin la ruta configurada. El inicio de sesión principal no tiene entrada en el grupo y siempre usa la ruta del proveedor. +`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. Una cuenta del grupo sin objeto `egress` también envía esas llamadas por la ruta del proveedor `openai`. Si `config.json` no se puede leer, o la cuenta se eliminó mientras una de esas llamadas 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 5582ff71dda..880ffa83121 100644 --- a/docs-site/src/content/docs/reference/configuration/providers.md +++ b/docs-site/src/content/docs/reference/configuration/providers.md @@ -1425,9 +1425,9 @@ 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, model discovery and reset-credit calls; an omitted `proxy` keeps the provider's, and the account's `noProxy` entries apply ahead of the provider's. +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. A pool account without an `egress` object sends those calls by the `openai` provider's route too. -If `config.json` cannot be read, a CLI command refuses these calls instead of sending them without the configured route. +If `config.json` cannot be read, or the account was removed while one of these calls 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.json b/scripts/test-layout/layout.json index 687ffb6c40c..f2f00325eb4 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-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", "codex-pool-account-egress-compact.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 index e6693a9533c..741325fb8f9 100644 --- a/src/codex/account-egress-runtime.ts +++ b/src/codex/account-egress-runtime.ts @@ -1,49 +1,83 @@ import { existsSync } from "node:fs"; import { getConfigPath, loadConfig } from "../config"; -import { fileBackedConfigPath } from "../config/rebase-provenance"; +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 entitlement discovery and reset-credit calls. + * (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 running server binds its live config here (`setLiveStateStoreConfig`), so these calls read the - * same routes as inference without reloading the file. A process with no live config (a CLI command) - * loads the file instead, and refuses when that load fell back to defaults while `config.json` - * exists: a route the operator configured must not be silently dropped. + * The route is resolved at each send, and every failure to establish it refuses the send rather + * than letting a pool credential leave by the process-wide route: + * - a pool account that was removed (its row is gone and its stored credential tombstoned) while + * its credential was in hand; + * - a config that could not be read, so the load fell back to defaults while `config.json` exists. + * An account with a live stored credential but no row (a login not saved yet, or a credential the + * config no longer lists) takes the provider's route. + * + * 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; -let liveConfig: CodexAccountEgressConfig | undefined; +interface LiveBinding { + config: CodexAccountEgressConfig; + configPath: string; + /** The config this server started with is defaults standing in for an unreadable file. */ + degraded: boolean; +} + +let live: LiveBinding | undefined; export function bindCodexAccountEgressConfig(config: CodexAccountEgressConfig): void { - liveConfig = config; + const configPath = getConfigPath(); + live = { config, configPath, degraded: configLoadFellBack(configPath) && existsSync(configPath) }; +} + +/** 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 { - liveConfig = undefined; + live = undefined; } export class CodexAccountRouteUnavailableError extends Error { override readonly name = "CodexAccountRouteUnavailableError"; } +/** Whether the account's stored credential is tombstoned; registered by the account store. */ +let removedAccountProbe: ((accountId: string) => boolean) | undefined; + +export function registerRemovedCodexAccountProbe(probe: (accountId: string) => boolean): void { + removedAccountProbe = probe; +} + /** 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"; + function routingConfig(): CodexAccountEgressConfig { - if (liveConfig) return liveConfig; + const configPath = getConfigPath(); + if (live && live.configPath === configPath) { + if (live.degraded) throw new CodexAccountRouteUnavailableError(UNREADABLE); + return live.config; + } const config = loadConfig(); - if (fileBackedConfigPath(config) === undefined && existsSync(getConfigPath())) { - throw new CodexAccountRouteUnavailableError("Codex account routing configuration could not be loaded; refusing to send without it"); + if ((fileBackedConfigPath(config) === undefined || configLoadFellBack(configPath)) && existsSync(configPath)) { + throw new CodexAccountRouteUnavailableError(UNREADABLE); } return config; } @@ -53,17 +87,27 @@ interface CodexAccountRouting { account?: PoolAccountRoute; } +export interface CodexAccountRoutingOptions { + config?: CodexAccountEgressConfig; + /** A new login: an id reused after an earlier deletion is not refused for that old tombstone. */ + newLogin?: boolean; +} + /** - * The routing inputs for one pool account's call, or undefined when nothing configures a route for - * it (not a pool account, or neither the account nor the provider sets `proxy`/`noProxy`), in which - * case the call keeps the process-wide route unchanged. + * 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, or a pool account for + * which neither the account nor the provider configures `proxy`/`noProxy`. */ export function codexAccountRouting( - accountId: string | null | undefined, config?: CodexAccountEgressConfig, + accountId: string | null | undefined, options: CodexAccountRoutingOptions = {}, ): CodexAccountRouting | undefined { - if (!accountId) return undefined; - const source = config ?? routingConfig(); - if (!source.codexAccounts?.some(row => row.id === accountId && row.isMain !== true)) return undefined; + if (!accountId || accountId === MAIN_CODEX_ACCOUNT_ID) return undefined; + const source = options.config ?? routingConfig(); + const row = source.codexAccounts?.find(candidate => candidate.id === accountId); + if (row?.isMain === true) return undefined; + if (!row && options.newLogin !== true && removedAccountProbe?.(accountId) === true) { + throw new CodexAccountRouteUnavailableError("this Codex pool account was removed; 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 }; @@ -77,15 +121,18 @@ function routeInit(routing: CodexAccountRouting, input: RequestInfo | URL): { pr } /** - * A fetch for one pool account's credentialed call. 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. + * 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, base?: typeof globalThis.fetch, config?: CodexAccountEgressConfig, + accountId: string | null | undefined, options: CodexAccountRoutingOptions & { base?: typeof globalThis.fetch } = {}, ): typeof globalThis.fetch { - const routing = codexAccountRouting(accountId, config); - if (!routing) return base ?? (((input: RequestInfo | URL, init?: RequestInit) => fetch(input, init)) as typeof globalThis.fetch); - return ((input: RequestInfo | URL, init?: RequestInit) => - configuredOutboundFetch(input, { ...init, ...routeInit(routing, input) } as RequestInit, base)) as 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-store.ts b/src/codex/account-store.ts index a6790cfc95d..380b6acf15d 100644 --- a/src/codex/account-store.ts +++ b/src/codex/account-store.ts @@ -1,5 +1,5 @@ import { publishCredentialSync } from "../local-credentials/generation"; -import { codexAccountFetch } from "./account-egress-runtime"; +import { codexAccountFetch, registerRemovedCodexAccountProbe } 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"; @@ -356,6 +356,8 @@ export function listCodexAccountIds(): string[] { export function readCodexAccountRecord(id: string): CodexAccountCredentialRecord | null { return loadCodexAccountRecordStore()[id] ?? null; } +// A removed account's credential must not leave by a fallback route (account-egress-runtime.ts). +registerRemovedCodexAccountProbe(id => readCodexAccountRecord(id)?.deletedAt != null); /** * One store load, every record, for a caller that resolves MANY ids in a single synchronous pass. 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 e0cae57b262..bab0c659ed0 100644 --- a/src/codex/auth-api/pool-quota-probe.ts +++ b/src/codex/auth-api/pool-quota-probe.ts @@ -599,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 cda8aa70aff..d2a89d1f341 100644 --- a/src/codex/auth-api/reset-credit-service.ts +++ b/src/codex/auth-api/reset-credit-service.ts @@ -150,7 +150,7 @@ export function createResetCreditWhamClient(config: OcxConfig, accountId: string }; return { inspect: () => run(async auth => { - const resp = await codexAccountFetch(auth.isMain ? null : accountId, undefined, getRuntimeConfig(config))("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), }); @@ -170,7 +170,7 @@ export function createResetCreditWhamClient(config: OcxConfig, accountId: string }) }; }), consume: redeemRequestId => run(async auth => { - const resp = await codexAccountFetch(auth.isMain ? null : accountId, undefined, getRuntimeConfig(config))("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}`, @@ -302,7 +302,7 @@ export async function inspectResetCredits(config: OcxConfig, accountId: string, try { let resp: Response; try { - resp = await codexAccountFetch(auth.isMain ? null : accountId, undefined, getRuntimeConfig(config))( + resp = await codexAccountFetch(auth.isMain ? null : accountId)( "https://chatgpt.com/backend-api/wham/rate-limit-reset-credits", { headers: { @@ -389,7 +389,7 @@ export async function consumeResetCredits(config: OcxConfig, accountId: string, try { let resp: Response; try { - resp = await codexAccountFetch(auth.isMain ? null : accountId, undefined, getRuntimeConfig(config))( + 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 4be0e5683b9..621dbcc04ae 100644 --- a/src/codex/model-entitlements.ts +++ b/src/codex/model-entitlements.ts @@ -756,7 +756,7 @@ async function fetchAccountModels( Accept: "application/json", }); if (credential.chatgptAccountId) headers.set("ChatGPT-Account-Id", credential.chatgptAccountId); - const response = await codexAccountFetch(credential.accountId, fetcher)(codexModelsUrl(clientVersion), { + const response = await codexAccountFetch(credential.accountId, { base: fetcher })(codexModelsUrl(clientVersion), { headers, redirect: "error", signal: controller.signal, @@ -910,7 +910,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 codexAccountFetch(credential.accountId, fetcher)(codexModelsUrl(CODEX_ROSTER_DISCOVERY_CLIENT_VERSION), { + const response = await codexAccountFetch(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/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/lib/state-store-registrations.ts b/src/lib/state-store-registrations.ts index 47bb5edfb17..20121e6e894 100644 --- a/src/lib/state-store-registrations.ts +++ b/src/lib/state-store-registrations.ts @@ -1,4 +1,3 @@ -import { bindCodexAccountEgressConfig } from "../codex/account-egress-runtime"; import { bindCodexWsIncrementalConfig } from "../config/codex-ws-incremental-setting"; import { bindUpstreamHistorySlimConfig } from "../server/responses/history-slim"; import { @@ -90,7 +89,6 @@ export function setLiveStateStoreConfig(config: OcxConfig): void { bindUpstreamHistorySlimConfig(config); bindCodexWsIncrementalConfig(config); bindWorkflowBudgetConfig(config); - bindCodexAccountEgressConfig(config); notifyLiveConfigObservers(config); } 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 { @@ -279,6 +281,9 @@ export function acquireServerBackgroundLifecycle( // The quota-pool identity (homeId and the accountRef key) is minted here, per server and off // the request path, so GET /api/quota-pool only ever reads it. try { ensureQuotaPoolIdentity(); } catch { /* the read reports quota_pool_identity_unavailable */ } + // Pool accounts' background calls (refresh, usage, warmup, reset credits) read this server's + // account routes while a lease is held; the final release (stopProcessLoops) detaches them. + bindCodexAccountEgressConfig(config); const owner: LeaseOwner = { token: Symbol("server-background-lifecycle"), @@ -297,6 +302,7 @@ export function acquireServerBackgroundLifecycle( } catch (error) { owner.lowQuota(); owner.resources.release(); + if (owners.length === 0) unbindCodexAccountEgressConfig(config); throw error; } diff --git a/structure/transports/inventory.md b/structure/transports/inventory.md index b4d1896eb10..57ac37d3df6 100644 --- a/structure/transports/inventory.md +++ b/structure/transports/inventory.md @@ -213,7 +213,7 @@ Bun would apply the bypass list to the next hop; callers that handle redirects p | --- | --- | --- | | 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, and reset-credit inspect/consume | Honoured | `codexAccountFetch` in `src/codex/account-egress-runtime.ts` resolves the account's route over the `openai` provider's against the server's bound live config (or, in a CLI process, the loaded file, refusing when that load fell back to defaults) and sends through `configuredOutboundFetch`, so the explicit-proxy guards apply. `tests/lib/provider-egress-account-calls.test.ts` asserts the route each call receives with a fake transport, plus the NO_PROXY refusal and the unreadable-config refusal; no real proxy is exercised for these vendor endpoints. | +| 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 could not be read or the account was removed (row gone, credential tombstoned); a stored credential with no row takes the provider's route. 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/codex-integration/codex-account-egress-background.test.ts b/tests/codex-integration/codex-account-egress-background.test.ts new file mode 100644 index 00000000000..c1241e31f97 --- /dev/null +++ b/tests/codex-integration/codex-account-egress-background.test.ts @@ -0,0 +1,229 @@ +/** + * 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, 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 { getCodexAccountCredential, markCodexAccountValidated, 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 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 takes the provider's route", async () => { + const cfg = config(); + bindCodexAccountEgressConfig(cfg); + cfg.codexAccounts = []; + await codexAccountFetch("routed")("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, never sent by another route", async () => { + const cfg = config(); + bindCodexAccountEgressConfig(cfg); + cfg.codexAccounts = []; + removeCodexAccountCredential("routed"); // deletion: the row is gone and the credential tombstoned + await expect(codexAccountFetch("routed")("https://chatgpt.com/backend-api/wham/usage")).rejects.toBeInstanceOf(CodexAccountRouteUnavailableError); + expect(calls).toEqual([]); + saveCodexAccountCredential("routed", { accessToken: "routed-access", refreshToken: "routed-grant", expiresAt: Date.now() + 3_600_000, chatgptAccountId: "acc-routed" }); + 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 configures no route. + 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 codexAccountFetch("routed")("https://chatgpt.com/backend-api/wham/usage"); + expect(proxiesFor("/wham/usage")).toEqual([undefined]); + } finally { + process.env.OPENCODEX_HOME = home; + await flushConfigDirHardening(otherHome); + removeTreeWithRetry(otherHome); + } +}); diff --git a/tests/fixtures/test-layout-expected.json b/tests/fixtures/test-layout-expected.json index 9ad71a1e782..08275f5abd9 100644 --- a/tests/fixtures/test-layout-expected.json +++ b/tests/fixtures/test-layout-expected.json @@ -1,4 +1,4 @@ -{ "provider-egress-account.test.ts": "lib", "provider-egress-account-calls.test.ts": "lib", "codex-pool-account-egress-compact.test.ts": "responses", "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", "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/lib/provider-egress-account-calls.test.ts b/tests/lib/provider-egress-account-calls.test.ts index 6a00adbaca0..6ff9348d70e 100644 --- a/tests/lib/provider-egress-account-calls.test.ts +++ b/tests/lib/provider-egress-account-calls.test.ts @@ -91,13 +91,14 @@ afterEach(async () => { 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(); - expect(codexAccountRouting("unknown", config)).toBeUndefined(); + 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 (not removed) takes the provider's route. + expect(codexAccountRouting("unknown", { config })).toEqual({ provider: { proxy: PROVIDER_PROXY, noProxy: undefined } }); delete config.providers.openai!.proxy; - expect(codexAccountRouting("plain", config)).toBeUndefined(); // nothing configured: the process-wide route, unchanged + 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 () => { From 95309d8b1b4186cc1db8d5eddb492bf6c37766d9 Mon Sep 17 00:00:00 2001 From: JUN Date: Wed, 25 Nov 2026 13:33:41 +0900 Subject: [PATCH 14/20] fix(egress): refuse unlisted pool credentials, keep the newest lifecycle owner's routes A stored pool credential whose row the config does not list is refused (removed, even when credential cleanup failed, or orphaned); only a new login takes the openai provider's route without a row, and a direct caller's own bearer keeps the process-wide route. Each background lifecycle owner carries its config, so a release or a failed acquisition restores the surviving owner's routes. --- .../es/reference/configuration/providers.md | 2 +- .../docs/reference/configuration/providers.md | 2 +- src/codex/account-egress-runtime.ts | 34 ++++++-------- src/codex/account-store.ts | 4 +- src/codex/model-entitlements.ts | 5 +- src/server/background-lifecycle.ts | 11 ++++- structure/transports/inventory.md | 2 +- .../codex-account-egress-background.test.ts | 47 ++++++++++++++++--- .../codex-integration/token-guardian.test.ts | 7 ++- .../lib/provider-egress-account-calls.test.ts | 5 +- 10 files changed, 81 insertions(+), 38 deletions(-) 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 65284496293..8322c586b9e 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. 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. Una cuenta del grupo sin objeto `egress` también envía esas llamadas por la ruta del proveedor `openai`. Si `config.json` no se puede leer, o la cuenta se eliminó mientras una de esas llamadas 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. +`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. Una cuenta del grupo sin objeto `egress` también envía esas llamadas por la ruta del proveedor `openai`. Si `config.json` 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 880ffa83121..5efaa6fb76e 100644 --- a/docs-site/src/content/docs/reference/configuration/providers.md +++ b/docs-site/src/content/docs/reference/configuration/providers.md @@ -1427,7 +1427,7 @@ provider in question. `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. A pool account without an `egress` object sends those calls by the `openai` provider's route too. -If `config.json` cannot be read, or the account was removed while one of these calls was in flight, the call is refused instead of sent without the configured route. +If `config.json` 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/src/codex/account-egress-runtime.ts b/src/codex/account-egress-runtime.ts index 741325fb8f9..87bc0f73506 100644 --- a/src/codex/account-egress-runtime.ts +++ b/src/codex/account-egress-runtime.ts @@ -16,12 +16,12 @@ import { MAIN_CODEX_ACCOUNT_ID } from "./account-id"; * 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 the process-wide route: - * - a pool account that was removed (its row is gone and its stored credential tombstoned) while - * its credential was in hand; + * 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. - * An account with a live stored credential but no row (a login not saved yet, or a credential the - * config no longer lists) takes the provider's route. + * Only a new login, whose row does not exist yet, takes the provider's route without a row. A + * process with no binding and no `config.json` has no route configured anywhere and sends unchanged. * * 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 @@ -57,26 +57,21 @@ export class CodexAccountRouteUnavailableError extends Error { override readonly name = "CodexAccountRouteUnavailableError"; } -/** Whether the account's stored credential is tombstoned; registered by the account store. */ -let removedAccountProbe: ((accountId: string) => boolean) | undefined; - -export function registerRemovedCodexAccountProbe(probe: (accountId: string) => boolean): void { - removedAccountProbe = probe; -} - /** 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"; -function routingConfig(): CodexAccountEgressConfig { +/** 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)) && existsSync(configPath)) { + if (fileBackedConfigPath(config) === undefined || configLoadFellBack(configPath)) { throw new CodexAccountRouteUnavailableError(UNREADABLE); } return config; @@ -89,24 +84,25 @@ interface CodexAccountRouting { export interface CodexAccountRoutingOptions { config?: CodexAccountEgressConfig; - /** A new login: an id reused after an earlier deletion is not refused for that old tombstone. */ + /** 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, or a pool account for - * which neither the account nor the provider configures `proxy`/`noProxy`. + * 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) return undefined; const row = source.codexAccounts?.find(candidate => candidate.id === accountId); if (row?.isMain === true) return undefined; - if (!row && options.newLogin !== true && removedAccountProbe?.(accountId) === true) { - throw new CodexAccountRouteUnavailableError("this Codex pool account was removed; refusing to send its credential"); + 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]; diff --git a/src/codex/account-store.ts b/src/codex/account-store.ts index 380b6acf15d..a6790cfc95d 100644 --- a/src/codex/account-store.ts +++ b/src/codex/account-store.ts @@ -1,5 +1,5 @@ import { publishCredentialSync } from "../local-credentials/generation"; -import { codexAccountFetch, registerRemovedCodexAccountProbe } from "./account-egress-runtime"; +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"; @@ -356,8 +356,6 @@ export function listCodexAccountIds(): string[] { export function readCodexAccountRecord(id: string): CodexAccountCredentialRecord | null { return loadCodexAccountRecordStore()[id] ?? null; } -// A removed account's credential must not leave by a fallback route (account-egress-runtime.ts). -registerRemovedCodexAccountProbe(id => readCodexAccountRecord(id)?.deletedAt != null); /** * One store load, every record, for a caller that resolves MANY ids in a single synchronous pass. diff --git a/src/codex/model-entitlements.ts b/src/codex/model-entitlements.ts index 621dbcc04ae..2c5315628f9 100644 --- a/src/codex/model-entitlements.ts +++ b/src/codex/model-entitlements.ts @@ -756,7 +756,8 @@ async function fetchAccountModels( Accept: "application/json", }); if (credential.chatgptAccountId) headers.set("ChatGPT-Account-Id", credential.chatgptAccountId); - const response = await codexAccountFetch(credential.accountId, { base: 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, @@ -910,7 +911,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 codexAccountFetch(credential.accountId, { base: 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/server/background-lifecycle.ts b/src/server/background-lifecycle.ts index 2e0f1a328f3..65348a8d7c9 100644 --- a/src/server/background-lifecycle.ts +++ b/src/server/background-lifecycle.ts @@ -53,6 +53,8 @@ type LeaseOwner = { applyPolicy: PolicyApply; resources: ServerResourceOwnerLease; lowQuota: LowQuotaRegistration; + /** This server's config, whose pool account routes background calls use while it is the newest owner. */ + egressConfig: OcxConfig; }; export type ServerBackgroundLifecycleLease = { @@ -257,6 +259,7 @@ function releaseOwnerSynchronously(owner: LeaseOwner): "inactive" | "shared" | " const nextOwner = owners.at(-1); if (nextOwner) { setLivePolicyOwner(nextOwner.applyPolicy); + bindCodexAccountEgressConfig(nextOwner.egressConfig); return "shared"; } stopProcessLoops(); @@ -282,7 +285,8 @@ export function acquireServerBackgroundLifecycle( // the request path, so GET /api/quota-pool only ever reads it. try { ensureQuotaPoolIdentity(); } catch { /* the read reports quota_pool_identity_unavailable */ } // Pool accounts' background calls (refresh, usage, warmup, reset credits) read this server's - // account routes while a lease is held; the final release (stopProcessLoops) detaches them. + // account routes while it is the newest owner; a release restores the surviving owner's and the + // final release (stopProcessLoops) detaches them. bindCodexAccountEgressConfig(config); const owner: LeaseOwner = { @@ -291,6 +295,7 @@ export function acquireServerBackgroundLifecycle( applyPolicy, resources: acquireServerResourceOwner(), lowQuota: registerCodexLowQuotaProtection(config, { desktopSink: () => resolveLowQuotaDesktopSink() }), + egressConfig: config, }; try { if (!processLoops) { @@ -302,7 +307,9 @@ export function acquireServerBackgroundLifecycle( } catch (error) { owner.lowQuota(); owner.resources.release(); - if (owners.length === 0) unbindCodexAccountEgressConfig(config); + const survivor = owners.at(-1); + if (survivor) bindCodexAccountEgressConfig(survivor.egressConfig); + else unbindCodexAccountEgressConfig(config); throw error; } diff --git a/structure/transports/inventory.md b/structure/transports/inventory.md index 57ac37d3df6..89e1c9bab4c 100644 --- a/structure/transports/inventory.md +++ b/structure/transports/inventory.md @@ -213,7 +213,7 @@ Bun would apply the bypass list to the next hop; callers that handle redirects p | --- | --- | --- | | 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 could not be read or the account was removed (row gone, credential tombstoned); a stored credential with no row takes the provider's route. 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. | +| 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 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/codex-integration/codex-account-egress-background.test.ts b/tests/codex-integration/codex-account-egress-background.test.ts index c1241e31f97..a56d79d9c0d 100644 --- a/tests/codex-integration/codex-account-egress-background.test.ts +++ b/tests/codex-integration/codex-account-egress-background.test.ts @@ -25,6 +25,9 @@ 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"; @@ -163,22 +166,22 @@ test("a new login, which has no pool row yet, takes the provider's route", async expect(proxiesFor("/codex/responses")).toEqual([PROVIDER_PROXY]); }); -test("a stored credential the config does not list takes the provider's route", async () => { +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 codexAccountFetch("routed")("https://chatgpt.com/backend-api/wham/usage"); + 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, never sent by another route", async () => { +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 = []; - removeCodexAccountCredential("routed"); // deletion: the row is gone and the credential tombstoned + 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([]); - saveCodexAccountCredential("routed", { accessToken: "routed-access", refreshToken: "routed-grant", expiresAt: Date.now() + 3_600_000, chatgptAccountId: "acc-routed" }); const live = config(); bindCodexAccountEgressConfig(live); // An expired token makes the reset-credit call refresh first; the account is removed while that @@ -227,3 +230,35 @@ test("a server that started on an unreadable config refuses pool sends, and its 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]); +}); 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/lib/provider-egress-account-calls.test.ts b/tests/lib/provider-egress-account-calls.test.ts index 6ff9348d70e..ead56a1eaeb 100644 --- a/tests/lib/provider-egress-account-calls.test.ts +++ b/tests/lib/provider-egress-account-calls.test.ts @@ -95,8 +95,9 @@ test("a pool account inherits the openai provider's route unless it names its ow 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 (not removed) takes the provider's route. - expect(codexAccountRouting("unknown", { config })).toEqual({ provider: { proxy: PROVIDER_PROXY, noProxy: undefined } }); + // 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 }); From e0303f1d5a1ada61026e4cff09ec4b03cbd78051 Mon Sep 17 00:00:00 2001 From: JUN Date: Wed, 25 Nov 2026 13:43:26 +0900 Subject: [PATCH 15/20] fix(egress): refuse stored pool credentials without routing config; restore each owner's own binding With no binding for the current home and no config.json, a stored pool credential is refused (only a new login proceeds), since its former route cannot be known. Each background-lifecycle owner keeps the binding captured at acquisition (config, config home, load state) and a release or failed acquisition restores exactly that binding. Test fixtures that store credentials without a config keep the earlier behaviour through a preload seam that only works while the test home guard is armed; the account-egress suites clear it. --- .../es/reference/configuration/providers.md | 2 +- .../docs/reference/configuration/providers.md | 2 +- src/codex/account-egress-runtime.ts | 36 ++++++++++--- src/server/background-lifecycle.ts | 19 ++++--- structure/transports/inventory.md | 2 +- .../codex-account-egress-background.test.ts | 53 +++++++++++++++++-- .../codex-integration/token-guardian.test.ts | 7 +-- .../lib/provider-egress-account-calls.test.ts | 3 ++ tests/preload.ts | 4 ++ 9 files changed, 101 insertions(+), 27 deletions(-) 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 8322c586b9e..581438a5e26 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. 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. Una cuenta del grupo sin objeto `egress` también envía esas llamadas por la ruta del proveedor `openai`. Si `config.json` 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. +`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. 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 5efaa6fb76e..c92de56c7c9 100644 --- a/docs-site/src/content/docs/reference/configuration/providers.md +++ b/docs-site/src/content/docs/reference/configuration/providers.md @@ -1427,7 +1427,7 @@ provider in question. `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. A pool account without an `egress` object sends those calls by the `openai` provider's route too. -If `config.json` 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. +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/src/codex/account-egress-runtime.ts b/src/codex/account-egress-runtime.ts index 87bc0f73506..ff83a7400f1 100644 --- a/src/codex/account-egress-runtime.ts +++ b/src/codex/account-egress-runtime.ts @@ -3,6 +3,7 @@ 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 { isTestHomeGuardArmed } from "../lib/test-home-guard"; import type { OcxConfig, OcxProviderConfig } from "../types"; import { codexAccountEgressRoute } from "./account-egress"; import { MAIN_CODEX_ACCOUNT_ID } from "./account-id"; @@ -20,8 +21,9 @@ import { MAIN_CODEX_ACCOUNT_ID } from "./account-id"; * - 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. - * Only a new login, whose row does not exist yet, takes the provider's route without a row. A - * process with no binding and no `config.json` has no route configured anywhere and sends unchanged. + * - 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 @@ -29,18 +31,25 @@ import { MAIN_CODEX_ACCOUNT_ID } from "./account-id"; */ export type CodexAccountEgressConfig = Pick; -interface LiveBinding { +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: LiveBinding | undefined; +let live: CodexAccountEgressBinding | undefined; -export function bindCodexAccountEgressConfig(config: CodexAccountEgressConfig): void { +/** 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. */ @@ -60,6 +69,17 @@ export class CodexAccountRouteUnavailableError extends Error { /** The provider whose route a pool account inherits. */ export const CODEX_POOL_PROVIDER = "openai"; +/** + * Test seam: suites whose fixtures store pool credentials without a config (written long before + * account routes existed) keep the earlier behaviour, sending with no account route instead of + * refusing. The test preload sets it; the account-egress suites clear it to exercise the refusals. + * It has no effect unless the test home guard is armed, so a production process cannot set it. + */ +const UNLISTED_FIXTURE_SEAM = Symbol.for("opencodex.codex-account-egress.unlisted-fixture-seam"); +function unlistedFixturesAllowed(): boolean { + return (globalThis as { [UNLISTED_FIXTURE_SEAM]?: unknown })[UNLISTED_FIXTURE_SEAM] === true && isTestHomeGuardArmed(); +} + 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`). */ @@ -98,10 +118,14 @@ export function codexAccountRouting( ): CodexAccountRouting | undefined { if (!accountId || accountId === MAIN_CODEX_ACCOUNT_ID) return undefined; const source = options.config ?? routingConfig(); - if (!source) return undefined; + if (!source) { + if (options.newLogin === true || unlistedFixturesAllowed()) 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) { + if (unlistedFixturesAllowed()) return undefined; throw new CodexAccountRouteUnavailableError("this Codex pool account is not configured; refusing to send its credential"); } const account = codexAccountEgressRoute(source, accountId); diff --git a/src/server/background-lifecycle.ts b/src/server/background-lifecycle.ts index 65348a8d7c9..9b4094bd63b 100644 --- a/src/server/background-lifecycle.ts +++ b/src/server/background-lifecycle.ts @@ -35,7 +35,12 @@ import { } from "./memory-watchdog"; import { ensureQuotaPoolIdentity } from "../quota-pool/identity"; import { isTelemetryEnvOptOut } from "../telemetry/consent"; -import { bindCodexAccountEgressConfig, unbindCodexAccountEgressConfig } from "../codex/account-egress-runtime"; +import { + bindCodexAccountEgressConfig, + restoreCodexAccountEgressBinding, + unbindCodexAccountEgressConfig, + type CodexAccountEgressBinding, +} from "../codex/account-egress-runtime"; // The state module alone: the scheduler and its aggregation stay behind the dynamic import below. import { TELEMETRY_ENV_OPT_OUT_REFRESH_MS, endTelemetryEnvOptOut, recordTelemetryEnvOptOut } from "../telemetry/state"; import { telemetryProfilePath } from "../telemetry/profile/paths"; @@ -53,8 +58,8 @@ type LeaseOwner = { applyPolicy: PolicyApply; resources: ServerResourceOwnerLease; lowQuota: LowQuotaRegistration; - /** This server's config, whose pool account routes background calls use while it is the newest owner. */ - egressConfig: OcxConfig; + /** This server's routing binding (config, its config home and load state) while it is the newest owner. */ + egressBinding: CodexAccountEgressBinding; }; export type ServerBackgroundLifecycleLease = { @@ -259,7 +264,7 @@ function releaseOwnerSynchronously(owner: LeaseOwner): "inactive" | "shared" | " const nextOwner = owners.at(-1); if (nextOwner) { setLivePolicyOwner(nextOwner.applyPolicy); - bindCodexAccountEgressConfig(nextOwner.egressConfig); + restoreCodexAccountEgressBinding(nextOwner.egressBinding); return "shared"; } stopProcessLoops(); @@ -287,7 +292,7 @@ export function acquireServerBackgroundLifecycle( // Pool accounts' background calls (refresh, usage, warmup, reset credits) read this server's // account routes while it is the newest owner; a release restores the surviving owner's and the // final release (stopProcessLoops) detaches them. - bindCodexAccountEgressConfig(config); + const egressBinding = bindCodexAccountEgressConfig(config); const owner: LeaseOwner = { token: Symbol("server-background-lifecycle"), @@ -295,7 +300,7 @@ export function acquireServerBackgroundLifecycle( applyPolicy, resources: acquireServerResourceOwner(), lowQuota: registerCodexLowQuotaProtection(config, { desktopSink: () => resolveLowQuotaDesktopSink() }), - egressConfig: config, + egressBinding, }; try { if (!processLoops) { @@ -308,7 +313,7 @@ export function acquireServerBackgroundLifecycle( owner.lowQuota(); owner.resources.release(); const survivor = owners.at(-1); - if (survivor) bindCodexAccountEgressConfig(survivor.egressConfig); + if (survivor) restoreCodexAccountEgressBinding(survivor.egressBinding); else unbindCodexAccountEgressConfig(config); throw error; } diff --git a/structure/transports/inventory.md b/structure/transports/inventory.md index 89e1c9bab4c..0b21c1363f2 100644 --- a/structure/transports/inventory.md +++ b/structure/transports/inventory.md @@ -213,7 +213,7 @@ Bun would apply the bypass list to the next hop; callers that handle redirects p | --- | --- | --- | | 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 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. | +| 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/codex-integration/codex-account-egress-background.test.ts b/tests/codex-integration/codex-account-egress-background.test.ts index a56d79d9c0d..e5a8489acfa 100644 --- a/tests/codex-integration/codex-account-egress-background.test.ts +++ b/tests/codex-integration/codex-account-egress-background.test.ts @@ -5,7 +5,7 @@ * 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, writeFileSync } from "node:fs"; +import { mkdirSync, mkdtempSync, unlinkSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { @@ -15,7 +15,7 @@ import { resetCodexAccountEgressConfigForTests, unbindCodexAccountEgressConfig, } from "../../src/codex/account-egress-runtime"; -import { getCodexAccountCredential, markCodexAccountValidated, removeCodexAccountCredential, saveCodexAccountCredential } from "../../src/codex/account-store"; +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"; @@ -32,6 +32,7 @@ import type { OcxConfig } from "../../src/types"; import { removeTreeWithRetry } from "../helpers/remove-tree"; const PROVIDER_PROXY = "http://127.0.0.1:7/"; +const UNLISTED_FIXTURE_SEAM = Symbol.for("opencodex.codex-account-egress.unlisted-fixture-seam"); 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(); @@ -56,6 +57,7 @@ const completed = () => new Response('event: response.completed\ndata: {"type":" }); beforeEach(() => { + (globalThis as Record)[UNLISTED_FIXTURE_SEAM] = false; 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-")); @@ -80,6 +82,7 @@ beforeEach(() => { }); afterEach(async () => { + (globalThis as Record)[UNLISTED_FIXTURE_SEAM] = true; globalThis.fetch = realFetch; resetCodexAccountEgressConfigForTests(); clearAccountQuota(); @@ -214,7 +217,7 @@ test("a server that started on an unreadable config refuses pool sends, and its 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 configures no route. + // 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); @@ -222,8 +225,8 @@ test("a server that started on an unreadable config refuses pool sends, and its process.env.OPENCODEX_HOME = otherHome; try { calls = []; - await codexAccountFetch("routed")("https://chatgpt.com/backend-api/wham/usage"); - expect(proxiesFor("/wham/usage")).toEqual([undefined]); + 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); @@ -262,3 +265,43 @@ test("a direct caller's own bearer keeps the process-wide route under a provider 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/token-guardian.test.ts b/tests/codex-integration/token-guardian.test.ts index f1b8b924c3c..9d97fface44 100644 --- a/tests/codex-integration/token-guardian.test.ts +++ b/tests/codex-integration/token-guardian.test.ts @@ -28,15 +28,10 @@ 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 codexAccounts = partial.codexAccounts ?? POOL_ACCOUNT_IDS.map(id => ({ id, email: `${id}@example.test`, isMain: false })); - const cfg: OcxConfig = { port: 10100, ...partial, providers, defaultProvider, codexAccounts }; + const cfg: OcxConfig = { port: 10100, ...partial, providers, defaultProvider }; writeFileSync(getConfigPath(), JSON.stringify(cfg, null, 2)); } diff --git a/tests/lib/provider-egress-account-calls.test.ts b/tests/lib/provider-egress-account-calls.test.ts index ead56a1eaeb..bfa84fe3efb 100644 --- a/tests/lib/provider-egress-account-calls.test.ts +++ b/tests/lib/provider-egress-account-calls.test.ts @@ -28,6 +28,7 @@ import type { OcxConfig } from "../../src/types"; import { removeTreeWithRetry } from "../helpers/remove-tree"; const PROVIDER_PROXY = "http://127.0.0.1:7/"; +const UNLISTED_FIXTURE_SEAM = Symbol.for("opencodex.codex-account-egress.unlisted-fixture-seam"); 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(); @@ -60,6 +61,7 @@ function respond(url: string): Response { } beforeEach(() => { + (globalThis as Record)[UNLISTED_FIXTURE_SEAM] = false; 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-")); @@ -79,6 +81,7 @@ beforeEach(() => { }); afterEach(async () => { + (globalThis as Record)[UNLISTED_FIXTURE_SEAM] = true; globalThis.fetch = realFetch; resetCodexAccountEgressConfigForTests(); clearAccountQuota(); diff --git a/tests/preload.ts b/tests/preload.ts index 7a89f6bf4ec..3bc272f399e 100644 --- a/tests/preload.ts +++ b/tests/preload.ts @@ -107,6 +107,10 @@ if (!isTestHomeGuardArmed() || !protectedHomeForTests()) { // past a mock. Loopback fixtures and the reserved .test/.example/.invalid names still work. installNetworkEgressGuard(); +// Fixtures that store Codex pool credentials without a config keep sending with no account route; +// the account-egress suites clear this to exercise the refusals (src/codex/account-egress-runtime.ts). +(globalThis as Record)[Symbol.for("opencodex.codex-account-egress.unlisted-fixture-seam")] = true; + // `scripts/test.ts` owns the lock for wrapped runs. A bare `bun test` has no wrapper, // so a single-process runner uses its own PID while true parallel workers rendezvous // on their short-lived controller PID. The first worker acquires the lock and siblings From 5389d79be59ddcb2d08b28e8aa17a222234a66ac Mon Sep 17 00:00:00 2001 From: JUN Date: Wed, 25 Nov 2026 14:49:10 +0900 Subject: [PATCH 16/20] test(egress): give legacy pool fixtures matching rows instead of a suite-wide seam Removes the test seam. Suites that store Codex pool credentials without a config bind, for their test home, a routing config whose pool rows are exactly the stored live accounts (plus credentials a test passes without storing), with no route: the state a running server has for unrouted pool accounts, so a tombstoned account loses its row as on deletion. tests/helpers/codex-pool-routing.ts holds the helper. --- src/codex/account-egress-runtime.ts | 15 +--------- .../claude-bridge-pool-dispatch.test.ts | 2 ++ .../codex-account-egress-background.test.ts | 3 -- ...count-store-refresh-classification.test.ts | 2 ++ .../codex-account-store.test.ts | 2 ++ .../codex-integration/codex-auth-api.test.ts | 4 +-- .../codex-auth-context.test.ts | 2 ++ .../codex-auth-headless-accounts.test.ts | 2 ++ ...odex-convergence-account-selectors.test.ts | 2 ++ .../codex-cooldown-recovery.test.ts | 2 ++ .../codex-credit-scoped-retry.test.ts | 2 ++ .../codex-credits-probes.test.ts | 2 ++ .../codex-direct-credit-renewal.test.ts | 2 ++ .../codex-direct-renewal-revocation.test.ts | 2 ++ .../codex-main-token-invalidated.test.ts | 2 ++ ...x-model-entitlements-program-shape.test.ts | 5 ++-- .../codex-model-entitlements.test.ts | 8 +++-- .../codex-native-availability-nux.test.ts | 5 ++-- .../codex-quota-auto-refresh.test.ts | 2 ++ .../codex-quota-prime.test.ts | 2 ++ .../codex-quota-query-backoff.test.ts | 3 +- .../codex-reset-credit-dto.test.ts | 2 ++ .../codex-stored-main-duplicate.test.ts | 2 ++ .../issue-452-empty-503.test.ts | 2 ++ .../reserve-quota-scope.test.ts | 2 ++ .../codex-integration/token-guardian.test.ts | 7 ++++- tests/helpers/codex-pool-routing.ts | 29 +++++++++++++++++++ tests/helpers/pool-reauth-cause.ts | 2 ++ .../lib/provider-egress-account-calls.test.ts | 3 -- tests/preload.ts | 4 --- tests/providers/provider-quota.test.ts | 2 ++ .../codex-installation-failover.test.ts | 2 ++ .../combo-replay-refusal-attribution.test.ts | 2 ++ .../direct-credit-renewal-ingress.test.ts | 2 ++ ...ive-compaction-gateway-credentials.test.ts | 2 ++ .../pool-retry-client-metadata.test.ts | 2 ++ .../responses-pool-401-refresh.test.ts | 2 ++ .../management-provider-validation.test.ts | 2 ++ .../usage/quota-401-recovery-runtime.test.ts | 2 ++ 39 files changed, 107 insertions(+), 35 deletions(-) create mode 100644 tests/helpers/codex-pool-routing.ts diff --git a/src/codex/account-egress-runtime.ts b/src/codex/account-egress-runtime.ts index ff83a7400f1..f3dfa212aa0 100644 --- a/src/codex/account-egress-runtime.ts +++ b/src/codex/account-egress-runtime.ts @@ -3,7 +3,6 @@ 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 { isTestHomeGuardArmed } from "../lib/test-home-guard"; import type { OcxConfig, OcxProviderConfig } from "../types"; import { codexAccountEgressRoute } from "./account-egress"; import { MAIN_CODEX_ACCOUNT_ID } from "./account-id"; @@ -69,17 +68,6 @@ export class CodexAccountRouteUnavailableError extends Error { /** The provider whose route a pool account inherits. */ export const CODEX_POOL_PROVIDER = "openai"; -/** - * Test seam: suites whose fixtures store pool credentials without a config (written long before - * account routes existed) keep the earlier behaviour, sending with no account route instead of - * refusing. The test preload sets it; the account-egress suites clear it to exercise the refusals. - * It has no effect unless the test home guard is armed, so a production process cannot set it. - */ -const UNLISTED_FIXTURE_SEAM = Symbol.for("opencodex.codex-account-egress.unlisted-fixture-seam"); -function unlistedFixturesAllowed(): boolean { - return (globalThis as { [UNLISTED_FIXTURE_SEAM]?: unknown })[UNLISTED_FIXTURE_SEAM] === true && isTestHomeGuardArmed(); -} - 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`). */ @@ -119,13 +107,12 @@ export function codexAccountRouting( if (!accountId || accountId === MAIN_CODEX_ACCOUNT_ID) return undefined; const source = options.config ?? routingConfig(); if (!source) { - if (options.newLogin === true || unlistedFixturesAllowed()) return undefined; + 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) { - if (unlistedFixturesAllowed()) return undefined; throw new CodexAccountRouteUnavailableError("this Codex pool account is not configured; refusing to send its credential"); } const account = codexAccountEgressRoute(source, accountId); 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 index e5a8489acfa..da0f550aa9e 100644 --- a/tests/codex-integration/codex-account-egress-background.test.ts +++ b/tests/codex-integration/codex-account-egress-background.test.ts @@ -32,7 +32,6 @@ import type { OcxConfig } from "../../src/types"; import { removeTreeWithRetry } from "../helpers/remove-tree"; const PROVIDER_PROXY = "http://127.0.0.1:7/"; -const UNLISTED_FIXTURE_SEAM = Symbol.for("opencodex.codex-account-egress.unlisted-fixture-seam"); 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(); @@ -57,7 +56,6 @@ const completed = () => new Response('event: response.completed\ndata: {"type":" }); beforeEach(() => { - (globalThis as Record)[UNLISTED_FIXTURE_SEAM] = false; 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-")); @@ -82,7 +80,6 @@ beforeEach(() => { }); afterEach(async () => { - (globalThis as Record)[UNLISTED_FIXTURE_SEAM] = true; globalThis.fetch = realFetch; resetCodexAccountEgressConfigForTests(); clearAccountQuota(); 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-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..16832dafbc1 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, registerCodexPoolRowForTests } 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"; @@ -31,7 +32,7 @@ const mainCredential: CodexModelEntitlementCredentialSnapshot = { chatgptAccountId: "synthetic-main-account", credentialIdentity: "synthetic:main", }; const poolCredential: CodexModelEntitlementCredentialSnapshot = { - accountId: "synthetic-pool", accessToken: "synthetic-pool-token", + accountId: registerCodexPoolRowForTests("synthetic-pool"), accessToken: "synthetic-pool-token", chatgptAccountId: "synthetic-pool-account", credentialIdentity: "synthetic:pool", }; @@ -51,7 +52,7 @@ async function snapshot(main: unknown[], pool: unknown[] = [], mainFails = false }); } -beforeEach(() => resetCodexModelEntitlementCacheForTests()); +beforeEach(() => { resetCodexModelEntitlementCacheForTests(); bindStoredCodexPoolRoutingForTests(); }); 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..2e472475480 100644 --- a/tests/codex-integration/codex-quota-prime.test.ts +++ b/tests/codex-integration/codex-quota-prime.test.ts @@ -1,4 +1,5 @@ import { afterEach, beforeEach, describe, expect, test, spyOn } from "bun:test"; +import { bindStoredCodexPoolRoutingForTests } from "../helpers/codex-pool-routing"; import { existsSync, mkdirSync, mkdtempSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -115,6 +116,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; 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/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/helpers/codex-pool-routing.ts b/tests/helpers/codex-pool-routing.ts new file mode 100644 index 00000000000..a1ff7aeca0b --- /dev/null +++ b/tests/helpers/codex-pool-routing.ts @@ -0,0 +1,29 @@ +import { restoreCodexAccountEgressBinding } 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 gets a row in every binding. */ +export function registerCodexPoolRowForTests(accountId: string): string { + registeredIds.add(accountId); + return accountId; +} + +export function bindStoredCodexPoolRoutingForTests(extraIds: readonly string[] = []): void { + 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 }); +} 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 index bfa84fe3efb..ead56a1eaeb 100644 --- a/tests/lib/provider-egress-account-calls.test.ts +++ b/tests/lib/provider-egress-account-calls.test.ts @@ -28,7 +28,6 @@ import type { OcxConfig } from "../../src/types"; import { removeTreeWithRetry } from "../helpers/remove-tree"; const PROVIDER_PROXY = "http://127.0.0.1:7/"; -const UNLISTED_FIXTURE_SEAM = Symbol.for("opencodex.codex-account-egress.unlisted-fixture-seam"); 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(); @@ -61,7 +60,6 @@ function respond(url: string): Response { } beforeEach(() => { - (globalThis as Record)[UNLISTED_FIXTURE_SEAM] = false; 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-")); @@ -81,7 +79,6 @@ beforeEach(() => { }); afterEach(async () => { - (globalThis as Record)[UNLISTED_FIXTURE_SEAM] = true; globalThis.fetch = realFetch; resetCodexAccountEgressConfigForTests(); clearAccountQuota(); diff --git a/tests/preload.ts b/tests/preload.ts index 3bc272f399e..7a89f6bf4ec 100644 --- a/tests/preload.ts +++ b/tests/preload.ts @@ -107,10 +107,6 @@ if (!isTestHomeGuardArmed() || !protectedHomeForTests()) { // past a mock. Loopback fixtures and the reserved .test/.example/.invalid names still work. installNetworkEgressGuard(); -// Fixtures that store Codex pool credentials without a config keep sending with no account route; -// the account-egress suites clear this to exercise the refusals (src/codex/account-egress-runtime.ts). -(globalThis as Record)[Symbol.for("opencodex.codex-account-egress.unlisted-fixture-seam")] = true; - // `scripts/test.ts` owns the lock for wrapped runs. A bare `bun test` has no wrapper, // so a single-process runner uses its own PID while true parallel workers rendezvous // on their short-lived controller PID. The first worker acquires the lock and siblings 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/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(); }); From 0cf73c5c61b2dcb321a6c86c71fe4891deaae374 Mon Sep 17 00:00:00 2001 From: JUN Date: Wed, 25 Nov 2026 14:51:04 +0900 Subject: [PATCH 17/20] test(egress): scope fixture pool rows per binding; a removed account is refused at the routing boundary The registered-id set resets on every bind, and the quota-prime removal case binds its own live config and asserts the removed account's credential is refused with no send. --- .../codex-native-availability-nux.test.ts | 6 +++--- tests/codex-integration/codex-quota-prime.test.ts | 7 ++++++- tests/helpers/codex-pool-routing.ts | 13 +++++++++++-- 3 files changed, 20 insertions(+), 6 deletions(-) diff --git a/tests/codex-integration/codex-native-availability-nux.test.ts b/tests/codex-integration/codex-native-availability-nux.test.ts index 16832dafbc1..ce25f5df138 100644 --- a/tests/codex-integration/codex-native-availability-nux.test.ts +++ b/tests/codex-integration/codex-native-availability-nux.test.ts @@ -1,5 +1,5 @@ import { afterEach, beforeEach, expect, setDefaultTimeout, test } from "bun:test"; -import { bindStoredCodexPoolRoutingForTests, registerCodexPoolRowForTests } from "../helpers/codex-pool-routing"; +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"; @@ -32,7 +32,7 @@ const mainCredential: CodexModelEntitlementCredentialSnapshot = { chatgptAccountId: "synthetic-main-account", credentialIdentity: "synthetic:main", }; const poolCredential: CodexModelEntitlementCredentialSnapshot = { - accountId: registerCodexPoolRowForTests("synthetic-pool"), accessToken: "synthetic-pool-token", + accountId: "synthetic-pool", accessToken: "synthetic-pool-token", chatgptAccountId: "synthetic-pool-account", credentialIdentity: "synthetic:pool", }; @@ -52,7 +52,7 @@ async function snapshot(main: unknown[], pool: unknown[] = [], mainFails = false }); } -beforeEach(() => { resetCodexModelEntitlementCacheForTests(); bindStoredCodexPoolRoutingForTests(); }); +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-prime.test.ts b/tests/codex-integration/codex-quota-prime.test.ts index 2e472475480..d57258cec9d 100644 --- a/tests/codex-integration/codex-quota-prime.test.ts +++ b/tests/codex-integration/codex-quota-prime.test.ts @@ -1,5 +1,6 @@ import { afterEach, beforeEach, describe, expect, test, spyOn } from "bun:test"; -import { bindStoredCodexPoolRoutingForTests } from "../helpers/codex-pool-routing"; +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"; @@ -793,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; @@ -812,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/helpers/codex-pool-routing.ts b/tests/helpers/codex-pool-routing.ts index a1ff7aeca0b..50c639379af 100644 --- a/tests/helpers/codex-pool-routing.ts +++ b/tests/helpers/codex-pool-routing.ts @@ -1,4 +1,4 @@ -import { restoreCodexAccountEgressBinding } from "../../src/codex/account-egress-runtime"; +import { restoreCodexAccountEgressBinding, type CodexAccountEgressConfig } from "../../src/codex/account-egress-runtime"; import { listCodexAccountIds } from "../../src/codex/account-store"; import { getConfigPath } from "../../src/config"; @@ -12,13 +12,14 @@ import { getConfigPath } from "../../src/config"; */ const registeredIds = new Set(); -/** A pool account a test passes as a credential without storing it; it gets a row in every binding. */ +/** 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() { @@ -27,3 +28,11 @@ export function bindStoredCodexPoolRoutingForTests(extraIds: readonly string[] = }; 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 }); +} From b18c8eb656cd51c109c5ed12dc60a51610b8fdb8 Mon Sep 17 00:00:00 2001 From: JUN Date: Wed, 25 Nov 2026 15:00:18 +0900 Subject: [PATCH 18/20] docs(config): pool background calls now follow providers.openai.proxy, and a per-account egress overrides it --- .../src/content/docs/es/reference/configuration/providers.md | 2 +- docs-site/src/content/docs/reference/configuration/providers.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) 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 581438a5e26..6dca44cbee1 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. 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. 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. +`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 c92de56c7c9..5b9e976a5c5 100644 --- a/docs-site/src/content/docs/reference/configuration/providers.md +++ b/docs-site/src/content/docs/reference/configuration/providers.md @@ -1426,7 +1426,7 @@ provider in question. `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. -A pool account without an `egress` object sends those calls by the `openai` provider's route too. +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. From af07642dc9c52d30571b79de26730e239829250e Mon Sep 17 00:00:00 2001 From: JUN Date: Wed, 25 Nov 2026 15:36:34 +0900 Subject: [PATCH 19/20] test(egress): bind matching pool rows in the entitlement suites that pass credentials directly --- tests/codex-integration/codex-model-denial-evidence.test.ts | 2 ++ tests/codex-integration/discovered-native-models.test.ts | 2 ++ 2 files changed, 4 insertions(+) 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/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(); From c93ab0f53f4a6c25dccaa7fa92017fdc5f78bac6 Mon Sep 17 00:00:00 2001 From: JUN Date: Wed, 25 Nov 2026 16:23:03 +0900 Subject: [PATCH 20/20] docs(config): keep the pool egress paragraph on one line so the reference stays under the file-size limit --- .../src/content/docs/reference/configuration/providers.md | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/docs-site/src/content/docs/reference/configuration/providers.md b/docs-site/src/content/docs/reference/configuration/providers.md index f45a225f0b8..bf57ce8b850 100644 --- a/docs-site/src/content/docs/reference/configuration/providers.md +++ b/docs-site/src/content/docs/reference/configuration/providers.md @@ -1425,10 +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. +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`)