Skip to content

Commit 8752441

Browse files
committed
fix(responses): stop requiring a ChatGPT credential for routed providers
#1686 made a caller that proves admission with one of our own secrets substitute the stored main credential, so that secret never leaves the process. That is right for a route that reaches the ChatGPT backend. It was applied by asking HOW the caller authenticated and never WHERE the request routes, so a request bound for a key-authenticated provider - which carries its own credential and never touches ChatGPT - was gated on a credential it has no use for. An install that deliberately never logged into ChatGPT therefore got 401 "No usable Codex main credential" on every routed request, a regression from v2.23.0 reported in #2132. Gate the substitution on route.codexAccountMode, which is set only for the native openai row and is exactly the test for "this route can consume the stored ChatGPT credential". Both pool and direct keep substituting, so #1686's Direct contract is preserved rather than narrowed to pool. Closes #2132
1 parent 890d339 commit 8752441

3 files changed

Lines changed: 201 additions & 2 deletions

File tree

‎src/server/responses/compact.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -322,7 +322,10 @@ export async function handleResponsesCompact(
322322

323323
// #1686: a bearer-presented admission secret is one of ours, so the stored main credential
324324
// is substituted below instead of the caller bearer being forwarded.
325-
const substituteMainCredential = admission?.source === "bearer";
325+
// #2132: and only when the route is a native Codex one, which is the only route that can
326+
// consume that credential. See the longer note in core.ts resolveResponsesCodexAuth.
327+
const substituteMainCredential = admission?.source === "bearer"
328+
&& route.codexAccountMode !== undefined;
326329
if (route.codexAccountMode === "direct" && !substituteMainCredential) {
327330
try { validateForwardAdmissionCredential(req.headers, config); }
328331
catch (err) {

‎src/server/responses/core.ts‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1085,7 +1085,15 @@ async function resolveResponsesCodexAuth(
10851085
// Refusing it here is what made the codex-cli `env_key` contract unusable against Direct.
10861086
// Admitting it is only safe because the stored main credential is substituted below, so
10871087
// the admission secret still never leaves this process.
1088-
const substituteMainCredential = options.admission?.source === "bearer";
1088+
//
1089+
// #2132: substitution answers "does THIS ROUTE need our stored ChatGPT credential", not
1090+
// "how did the caller authenticate". Only a native Codex route reaches the ChatGPT backend
1091+
// and can consume that credential; a key-authenticated routed provider carries its own and
1092+
// never touches it. Keying on the caller alone made an install that deliberately never
1093+
// logged into ChatGPT fail every routed request with "No usable Codex main credential".
1094+
// `codexAccountMode` is set only for the native openai row, which is exactly that test.
1095+
const substituteMainCredential = options.admission?.source === "bearer"
1096+
&& route.codexAccountMode !== undefined;
10891097
if (route.codexAccountMode === "direct" && !substituteMainCredential) {
10901098
validateForwardAdmissionCredential(req.headers, config);
10911099
}
Lines changed: 188 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,188 @@
1+
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
2+
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
3+
import { tmpdir } from "node:os";
4+
import { join } from "node:path";
5+
import { saveConfig } from "../src/config";
6+
import { startServer } from "../src/server";
7+
import type { OcxConfig } from "../src/types";
8+
9+
/**
10+
* Issue #2132: bearer admission must not require a stored ChatGPT credential.
11+
*
12+
* #1686 made a caller that proves admission with one of OUR secrets substitute the stored
13+
* main credential, so the admission secret never leaves the process. That is right for a
14+
* route that actually reaches the ChatGPT backend. It was applied by asking HOW the caller
15+
* authenticated and never WHERE the request routes, so a request bound for a
16+
* key-authenticated provider — which carries its own credential and never touches ChatGPT —
17+
* was gated on a credential it has no use for. An install that deliberately never logged
18+
* into ChatGPT got 401 "No usable Codex main credential" on every request.
19+
*
20+
* The substitution itself is unchanged and still fails closed for native routes; only the
21+
* question it is asked changes.
22+
*/
23+
24+
const originalFetch = globalThis.fetch;
25+
const previousOcxHome = process.env.OPENCODEX_HOME;
26+
const previousCodexHome = process.env.CODEX_HOME;
27+
const previousDataToken = process.env.OPENCODEX_API_AUTH_TOKEN;
28+
29+
let ocxHome = "";
30+
let codexHome = "";
31+
let routedAuth: Array<string | null> = [];
32+
let nativeAuth: Array<string | null> = [];
33+
34+
const ADMISSION_SECRET = "ocx_data_2132secret";
35+
const ROUTED_KEY = "sk-routed-provider-key";
36+
37+
/** A JWT whose `exp` is far in the future, so a stored main token reads as live. */
38+
function liveJwt(): string {
39+
const payload = Buffer.from(JSON.stringify({ exp: Math.floor(Date.now() / 1000) + 86_400 })).toString("base64url");
40+
return `header.${payload}.signature`;
41+
}
42+
43+
/**
44+
* A remote bind (so admission is required rather than loopback-waived) with BOTH a native
45+
* openai row and a key-authenticated routed provider. The routed provider is the one under
46+
* test; the native row has to exist for the negative case to be reachable.
47+
*/
48+
function mixedConfig(): OcxConfig {
49+
return {
50+
port: 0,
51+
hostname: "0.0.0.0",
52+
defaultProvider: "openai",
53+
openaiProviderTierVersion: 2,
54+
providers: {
55+
openai: {
56+
adapter: "openai-responses",
57+
baseUrl: "https://chatgpt.com/backend-api/codex",
58+
authMode: "forward",
59+
codexAccountMode: "direct",
60+
defaultModel: "gpt-5.6-luna",
61+
},
62+
gateway: {
63+
adapter: "openai-chat",
64+
baseUrl: "https://gateway.example.com/v1",
65+
authMode: "key",
66+
apiKey: ROUTED_KEY,
67+
models: ["gateway-model"],
68+
},
69+
},
70+
apiKeys: [
71+
{ id: "env-key", name: "env_key", key: ADMISSION_SECRET, createdAt: "2026-08-20T00:00:00.000Z" },
72+
],
73+
} as OcxConfig;
74+
}
75+
76+
beforeEach(() => {
77+
ocxHome = mkdtempSync(join(tmpdir(), "ocx-2132-home-"));
78+
codexHome = mkdtempSync(join(tmpdir(), "ocx-2132-codex-"));
79+
process.env.OPENCODEX_HOME = ocxHome;
80+
process.env.CODEX_HOME = codexHome;
81+
delete process.env.OPENCODEX_API_AUTH_TOKEN;
82+
routedAuth = [];
83+
nativeAuth = [];
84+
globalThis.fetch = (async (input, init) => {
85+
const raw = input instanceof Request ? input.url : String(input);
86+
const url = new URL(raw);
87+
const headers = new Headers(input instanceof Request ? input.headers : init?.headers);
88+
if (url.hostname === "gateway.example.com") {
89+
routedAuth.push(headers.get("authorization"));
90+
return Response.json({
91+
id: "chatcmpl_2132",
92+
object: "chat.completion",
93+
created: 0,
94+
model: "gateway-model",
95+
choices: [{ index: 0, message: { role: "assistant", content: "ok" }, finish_reason: "stop" }],
96+
});
97+
}
98+
if (url.hostname === "chatgpt.com" || url.hostname === "api.openai.com") {
99+
nativeAuth.push(headers.get("authorization"));
100+
return Response.json({ id: "resp_2132", object: "response", status: "completed", output: [] });
101+
}
102+
return originalFetch(input, init);
103+
}) as typeof fetch;
104+
});
105+
106+
afterEach(() => {
107+
globalThis.fetch = originalFetch;
108+
if (previousOcxHome === undefined) delete process.env.OPENCODEX_HOME;
109+
else process.env.OPENCODEX_HOME = previousOcxHome;
110+
if (previousCodexHome === undefined) delete process.env.CODEX_HOME;
111+
else process.env.CODEX_HOME = previousCodexHome;
112+
if (previousDataToken === undefined) delete process.env.OPENCODEX_API_AUTH_TOKEN;
113+
else process.env.OPENCODEX_API_AUTH_TOKEN = previousDataToken;
114+
if (ocxHome) rmSync(ocxHome, { recursive: true, force: true });
115+
if (codexHome) rmSync(codexHome, { recursive: true, force: true });
116+
ocxHome = "";
117+
codexHome = "";
118+
});
119+
120+
async function postResponses(url: string | URL, model: string): Promise<Response> {
121+
return originalFetch(new URL("/v1/responses", url), {
122+
method: "POST",
123+
headers: { "content-type": "application/json", authorization: `Bearer ${ADMISSION_SECRET}` },
124+
body: JSON.stringify({ model, input: "hi", stream: false }),
125+
});
126+
}
127+
128+
describe("#2132 bearer admission does not require a ChatGPT credential for routed providers", () => {
129+
test("a key-authenticated route is served with no stored main credential", async () => {
130+
saveConfig(mixedConfig());
131+
// The reported install: no ChatGPT login was ever performed.
132+
writeFileSync(join(codexHome, "auth.json"), JSON.stringify({ tokens: {} }));
133+
134+
const server = startServer(0);
135+
try {
136+
const response = await postResponses(server.url, "gateway/gateway-model");
137+
138+
// Before this change the same request answered 401 "No usable Codex main credential",
139+
// because admission-by-bearer alone decided a ChatGPT token had to be substituted.
140+
expect(response.status).toBe(200);
141+
// The provider's own key is what authenticates it, and our admission secret stays home.
142+
expect(routedAuth).toEqual([`Bearer ${ROUTED_KEY}`]);
143+
expect(routedAuth.join("|")).not.toContain(ADMISSION_SECRET);
144+
expect(nativeAuth).toHaveLength(0);
145+
} finally {
146+
await server.stop(true);
147+
}
148+
});
149+
150+
test("a native route with no stored main credential still fails closed", async () => {
151+
saveConfig(mixedConfig());
152+
writeFileSync(join(codexHome, "auth.json"), JSON.stringify({ tokens: {} }));
153+
154+
const server = startServer(0);
155+
try {
156+
const response = await postResponses(server.url, "gpt-5.6-luna");
157+
158+
// This is the #1686 guarantee and it must survive: a native route genuinely needs the
159+
// stored credential, so it fails BEFORE any upstream I/O rather than forwarding ours.
160+
expect(response.status).toBe(401);
161+
expect(nativeAuth).toHaveLength(0);
162+
expect(routedAuth).toHaveLength(0);
163+
} finally {
164+
await server.stop(true);
165+
}
166+
});
167+
168+
test("a native route still substitutes the stored main credential when one exists", async () => {
169+
saveConfig(mixedConfig());
170+
const stored = liveJwt();
171+
writeFileSync(
172+
join(codexHome, "auth.json"),
173+
JSON.stringify({ tokens: { access_token: stored, account_id: "stored_main_acc" } }),
174+
);
175+
176+
const server = startServer(0);
177+
try {
178+
const response = await postResponses(server.url, "gpt-5.6-luna");
179+
180+
expect(response.status).toBe(200);
181+
expect(nativeAuth).toEqual([`Bearer ${stored}`]);
182+
expect(nativeAuth.join("|")).not.toContain(ADMISSION_SECRET);
183+
} finally {
184+
await server.stop(true);
185+
}
186+
});
187+
});
188+

0 commit comments

Comments
 (0)