|
| 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 | + * #1686 end to end: a Codex client injected with `env_key` presents the proxy admission |
| 11 | + * secret as `Authorization: Bearer`. Direct must ADMIT that request and substitute the |
| 12 | + * stored main credential; the admission secret must never appear upstream. |
| 13 | + * |
| 14 | + * The unit matrix in tests/codex-auth-context.test.ts proves the materializer in isolation. |
| 15 | + * It cannot prove the HTTP handler passes the presentation source down to it, which is the |
| 16 | + * half that was missing: the source was resolved at the door and dropped one frame later. |
| 17 | + */ |
| 18 | + |
| 19 | +const originalFetch = globalThis.fetch; |
| 20 | +const previousOcxHome = process.env.OPENCODEX_HOME; |
| 21 | +const previousCodexHome = process.env.CODEX_HOME; |
| 22 | +const previousDataToken = process.env.OPENCODEX_API_AUTH_TOKEN; |
| 23 | + |
| 24 | +let ocxHome = ""; |
| 25 | +let codexHome = ""; |
| 26 | +let upstreamAuth: Array<string | null> = []; |
| 27 | + |
| 28 | +const ADMISSION_SECRET = "ocx_data_envkeysecret"; |
| 29 | + |
| 30 | +/** A JWT whose `exp` is far in the future, so the stored main token reads as live. */ |
| 31 | +function liveJwt(): string { |
| 32 | + const payload = Buffer.from(JSON.stringify({ exp: Math.floor(Date.now() / 1000) + 86_400 })).toString("base64url"); |
| 33 | + return `header.${payload}.signature`; |
| 34 | +} |
| 35 | + |
| 36 | +function directConfig(): OcxConfig { |
| 37 | + return { |
| 38 | + port: 0, |
| 39 | + // Remote bind, so admission is actually required rather than loopback-waived. |
| 40 | + hostname: "0.0.0.0", |
| 41 | + defaultProvider: "openai", |
| 42 | + openaiProviderTierVersion: 2, |
| 43 | + providers: { |
| 44 | + openai: { |
| 45 | + adapter: "openai-responses", |
| 46 | + baseUrl: "https://chatgpt.com/backend-api/codex", |
| 47 | + authMode: "forward", |
| 48 | + codexAccountMode: "direct", |
| 49 | + defaultModel: "gpt-5.6-luna", |
| 50 | + }, |
| 51 | + }, |
| 52 | + apiKeys: [ |
| 53 | + { id: "env-key", name: "env_key", key: ADMISSION_SECRET, createdAt: "2026-08-16T00:00:00.000Z" }, |
| 54 | + ], |
| 55 | + } as OcxConfig; |
| 56 | +} |
| 57 | + |
| 58 | +function writeStoredMain(accessToken: string): void { |
| 59 | + writeFileSync( |
| 60 | + join(codexHome, "auth.json"), |
| 61 | + JSON.stringify({ tokens: { access_token: accessToken, account_id: "stored_main_acc" } }), |
| 62 | + ); |
| 63 | +} |
| 64 | + |
| 65 | +beforeEach(() => { |
| 66 | + ocxHome = mkdtempSync(join(tmpdir(), "ocx-1686-home-")); |
| 67 | + codexHome = mkdtempSync(join(tmpdir(), "ocx-1686-codex-")); |
| 68 | + process.env.OPENCODEX_HOME = ocxHome; |
| 69 | + process.env.CODEX_HOME = codexHome; |
| 70 | + delete process.env.OPENCODEX_API_AUTH_TOKEN; |
| 71 | + upstreamAuth = []; |
| 72 | + globalThis.fetch = (async (input, init) => { |
| 73 | + const raw = input instanceof Request ? input.url : String(input); |
| 74 | + const url = new URL(raw); |
| 75 | + if (url.hostname === "chatgpt.com" || url.hostname === "api.openai.com") { |
| 76 | + const headers = new Headers(input instanceof Request ? input.headers : init?.headers); |
| 77 | + upstreamAuth.push(headers.get("authorization")); |
| 78 | + return Response.json({ id: "resp_1686", object: "response", status: "completed", output: [] }); |
| 79 | + } |
| 80 | + return originalFetch(input, init); |
| 81 | + }) as typeof fetch; |
| 82 | +}); |
| 83 | + |
| 84 | +afterEach(() => { |
| 85 | + globalThis.fetch = originalFetch; |
| 86 | + if (previousOcxHome === undefined) delete process.env.OPENCODEX_HOME; |
| 87 | + else process.env.OPENCODEX_HOME = previousOcxHome; |
| 88 | + if (previousCodexHome === undefined) delete process.env.CODEX_HOME; |
| 89 | + else process.env.CODEX_HOME = previousCodexHome; |
| 90 | + if (previousDataToken === undefined) delete process.env.OPENCODEX_API_AUTH_TOKEN; |
| 91 | + else process.env.OPENCODEX_API_AUTH_TOKEN = previousDataToken; |
| 92 | + if (ocxHome) rmSync(ocxHome, { recursive: true, force: true }); |
| 93 | + if (codexHome) rmSync(codexHome, { recursive: true, force: true }); |
| 94 | + ocxHome = ""; |
| 95 | + codexHome = ""; |
| 96 | +}); |
| 97 | + |
| 98 | +async function postResponses(url: string | URL, authorization: string): Promise<Response> { |
| 99 | + return originalFetch(new URL("/v1/responses", url), { |
| 100 | + method: "POST", |
| 101 | + headers: { "content-type": "application/json", authorization }, |
| 102 | + body: JSON.stringify({ model: "gpt-5.6-luna", input: "hi", stream: false }), |
| 103 | + }); |
| 104 | +} |
| 105 | + |
| 106 | +describe("#1686 env_key bearer admission reaches Direct with substitution", () => { |
| 107 | + test("an admission bearer is served and the stored main credential goes upstream", async () => { |
| 108 | + saveConfig(directConfig()); |
| 109 | + const stored = liveJwt(); |
| 110 | + writeStoredMain(stored); |
| 111 | + |
| 112 | + const server = startServer(0); |
| 113 | + try { |
| 114 | + const response = await postResponses(server.url, `Bearer ${ADMISSION_SECRET}`); |
| 115 | + |
| 116 | + // Before this change the same request answered 401: admission accepted the bearer at the |
| 117 | + // door, then Direct refused it because it could not tell it from a user's own credential. |
| 118 | + expect(response.status).toBe(200); |
| 119 | + expect(upstreamAuth).toEqual([`Bearer ${stored}`]); |
| 120 | + // The proof that matters: our own secret never reached the wire. |
| 121 | + expect(upstreamAuth.join("|")).not.toContain(ADMISSION_SECRET); |
| 122 | + } finally { |
| 123 | + await server.stop(true); |
| 124 | + } |
| 125 | + }); |
| 126 | + |
| 127 | + test("substitution fails closed before any upstream I/O when no main credential is stored", async () => { |
| 128 | + saveConfig(directConfig()); |
| 129 | + writeFileSync(join(codexHome, "auth.json"), JSON.stringify({ tokens: {} })); |
| 130 | + |
| 131 | + const server = startServer(0); |
| 132 | + try { |
| 133 | + const response = await postResponses(server.url, `Bearer ${ADMISSION_SECRET}`); |
| 134 | + |
| 135 | + expect(response.status).toBe(401); |
| 136 | + // Falling through would have forwarded the admission secret, which is the leak the |
| 137 | + // forward guard exists to prevent. Nothing may reach an upstream on this path. |
| 138 | + expect(upstreamAuth).toHaveLength(0); |
| 139 | + } finally { |
| 140 | + await server.stop(true); |
| 141 | + } |
| 142 | + }); |
| 143 | + |
| 144 | + test("a foreign bearer is still Codex Direct passthrough, not admission", async () => { |
| 145 | + saveConfig(directConfig()); |
| 146 | + writeStoredMain(liveJwt()); |
| 147 | + |
| 148 | + const server = startServer(0); |
| 149 | + try { |
| 150 | + // A real ChatGPT credential is NOT one of our secrets, so it must not be admitted as one. |
| 151 | + const response = await postResponses(server.url, "Bearer sk-user-chatgpt-token"); |
| 152 | + expect(response.status).toBe(401); |
| 153 | + expect(upstreamAuth).toHaveLength(0); |
| 154 | + } finally { |
| 155 | + await server.stop(true); |
| 156 | + } |
| 157 | + }); |
| 158 | +}); |
| 159 | + |
0 commit comments