|
| 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