|
| 1 | +import { afterEach, beforeEach, describe, expect, test } from "bun:test"; |
| 2 | +import { mkdtempSync, readFileSync, writeFileSync } from "node:fs"; |
| 3 | +import { tmpdir } from "node:os"; |
| 4 | +import { join } from "node:path"; |
| 5 | +import { callerSessionId, withCallerSessionIdentity } from "../../src/server/caller-session-identity"; |
| 6 | +import { withGrokSessionIdentity } from "../../src/grok/session-identity"; |
| 7 | +import { handleResponses } from "../../src/server/responses/core"; |
| 8 | +import { tryAdmitTurn } from "../../src/server/lifecycle"; |
| 9 | +import type { OcxConfig } from "../../src/types"; |
| 10 | +import { fakeChatGptJwt } from "../helpers/fake-chatgpt-jwt"; |
| 11 | +import { installIsolatedCodexHome, type IsolatedCodexHome } from "../helpers/isolated-codex-home"; |
| 12 | +import { removeTreeWithRetry } from "../helpers/remove-tree"; |
| 13 | +import { repoPath } from "../helpers/repo-root"; |
| 14 | +import { acquireOwnedSpendHome } from "../helpers/owned-spend-home"; |
| 15 | + |
| 16 | +const SESSION = "0f1e2d3c-4b5a-6978-8796-a5b4c3d2e1f0"; |
| 17 | + |
| 18 | +function callerHeaders(extra: Record<string, string> = {}): Headers { |
| 19 | + return new Headers({ |
| 20 | + "content-type": "application/json", |
| 21 | + "x-session-id": SESSION, |
| 22 | + ...extra, |
| 23 | + }); |
| 24 | +} |
| 25 | + |
| 26 | +describe("callerSessionId", () => { |
| 27 | + test("promotes the caller's x-session-id when no session header is present", () => { |
| 28 | + expect(callerSessionId(callerHeaders())).toBe(SESSION); |
| 29 | + expect(callerSessionId(callerHeaders({ "x-session-id": `sess-${SESSION}` }))).toBe(`sess-${SESSION}`); |
| 30 | + }); |
| 31 | + |
| 32 | + test("does nothing when the caller sent no x-session-id", () => { |
| 33 | + const headers = callerHeaders(); |
| 34 | + headers.delete("x-session-id"); |
| 35 | + expect(callerSessionId(headers)).toBeUndefined(); |
| 36 | + }); |
| 37 | + |
| 38 | + for (const explicit of ["session_id", "session-id", "thread-id"]) { |
| 39 | + test(`an explicit ${explicit} header wins`, () => { |
| 40 | + expect(callerSessionId(callerHeaders({ [explicit]: "caller" }))).toBeUndefined(); |
| 41 | + }); |
| 42 | + } |
| 43 | + |
| 44 | + test("ignores empty and unsafe session ids", () => { |
| 45 | + expect(callerSessionId(callerHeaders({ "x-session-id": "" }))).toBeUndefined(); |
| 46 | + expect(callerSessionId(callerHeaders({ "x-session-id": "a b" }))).toBeUndefined(); |
| 47 | + expect(callerSessionId(callerHeaders({ "x-session-id": "x".repeat(200) }))).toBeUndefined(); |
| 48 | + }); |
| 49 | + |
| 50 | + test("the rewritten request keeps its body and abort signal", async () => { |
| 51 | + const controller = new AbortController(); |
| 52 | + const original = new Request("http://localhost/v1/responses", { |
| 53 | + method: "POST", headers: callerHeaders(), body: "{\"a\":1}", signal: controller.signal, |
| 54 | + }); |
| 55 | + const rewritten = withCallerSessionIdentity(original); |
| 56 | + expect(rewritten.headers.get("session_id")).toBe(SESSION); |
| 57 | + expect(original.headers.has("session_id")).toBe(false); |
| 58 | + controller.abort(); |
| 59 | + expect(rewritten.signal.aborted).toBe(true); |
| 60 | + expect(await rewritten.text()).toBe("{\"a\":1}"); |
| 61 | + }); |
| 62 | + |
| 63 | + test("returns the same request when nothing is promoted", () => { |
| 64 | + const original = new Request("http://localhost/v1/responses", { method: "POST", body: "{}" }); |
| 65 | + expect(withCallerSessionIdentity(original)).toBe(original); |
| 66 | + }); |
| 67 | + |
| 68 | + test("composes after the Grok promotion without double-writing", () => { |
| 69 | + const grok = withGrokSessionIdentity(new Request("http://localhost/v1/responses", { |
| 70 | + method: "POST", |
| 71 | + headers: new Headers({ "x-opencodex-grok": "1", "x-grok-conv-id": SESSION }), |
| 72 | + body: "{}", |
| 73 | + })); |
| 74 | + const composed = withCallerSessionIdentity(grok); |
| 75 | + expect(composed.headers.get("session_id")).toBe(SESSION); |
| 76 | + expect(composed.headers.get("x-grok-conv-id")).toBe(SESSION); |
| 77 | + }); |
| 78 | +}); |
| 79 | + |
| 80 | +describe("Non-Codex callers reach the ChatGPT Codex backend with session_id", () => { |
| 81 | + const originalFetch = globalThis.fetch; |
| 82 | + let isolated: IsolatedCodexHome; |
| 83 | + let home: string; |
| 84 | + let previousHome: string | undefined; |
| 85 | + let releaseSpendHome: (() => void) | undefined; |
| 86 | + let token = ""; |
| 87 | + |
| 88 | + beforeEach(() => { |
| 89 | + previousHome = process.env.OPENCODEX_HOME; |
| 90 | + home = mkdtempSync(join(tmpdir(), "ocx-caller-session-")); |
| 91 | + process.env.OPENCODEX_HOME = home; |
| 92 | + isolated = installIsolatedCodexHome("ocx-caller-session-codex-"); |
| 93 | + token = fakeChatGptJwt({ exp: Math.floor(Date.now() / 1000) + 86400, chatgpt_account_id: "fixture-caller-main" }); |
| 94 | + writeFileSync(join(isolated.path, "auth.json"), JSON.stringify({ tokens: { access_token: token, account_id: "fixture-caller-main" } })); |
| 95 | + releaseSpendHome = acquireOwnedSpendHome(); |
| 96 | + }); |
| 97 | + afterEach(() => { |
| 98 | + releaseSpendHome?.(); |
| 99 | + releaseSpendHome = undefined; |
| 100 | + globalThis.fetch = originalFetch; |
| 101 | + isolated.restore(); |
| 102 | + if (previousHome === undefined) delete process.env.OPENCODEX_HOME; |
| 103 | + else process.env.OPENCODEX_HOME = previousHome; |
| 104 | + removeTreeWithRetry(home); |
| 105 | + }); |
| 106 | + |
| 107 | + test("the upstream request carries the promoted session_id", async () => { |
| 108 | + const cfg = { openaiProviderTierVersion: 2, providers: { |
| 109 | + openai: { adapter: "openai-responses", authMode: "forward", codexAccountMode: "direct", baseUrl: "https://chatgpt.com/backend-api/codex", models: ["gpt-5.6-luna"] }, |
| 110 | + } } as OcxConfig; |
| 111 | + const seen: Array<{ url: string; headers: Headers; body: Record<string, unknown> }> = []; |
| 112 | + globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => { |
| 113 | + seen.push({ url: String(input), headers: new Headers(init?.headers), body: JSON.parse(String(init?.body)) }); |
| 114 | + return Response.json({ id: "resp_caller", object: "response", status: "completed", output: [], |
| 115 | + usage: { input_tokens: 1, output_tokens: 0, total_tokens: 1 } }); |
| 116 | + }) as typeof fetch; |
| 117 | + const lease = tryAdmitTurn(); |
| 118 | + expect(lease).not.toBeNull(); |
| 119 | + try { |
| 120 | + const req = withCallerSessionIdentity(new Request("http://localhost/v1/responses", { |
| 121 | + method: "POST", headers: callerHeaders({ authorization: `Bearer ${token}` }), |
| 122 | + body: JSON.stringify({ model: "openai/gpt-5.6-luna", stream: false, store: false, input: "ping" }), |
| 123 | + })); |
| 124 | + const logCtx = { model: "", provider: "" } as Parameters<typeof handleResponses>[2]; |
| 125 | + const response = await handleResponses(req, cfg, logCtx, { turnAdmissionLease: lease!, admission: { kind: "loopback", source: "loopback" }, inboundWire: "responses" }); |
| 126 | + const text = await response.text(); |
| 127 | + expect(response.status, text).toBe(200); |
| 128 | + const wire = seen.at(-1)!; |
| 129 | + expect(wire.url).toBe("https://chatgpt.com/backend-api/codex/responses"); |
| 130 | + expect(wire.headers.get("session_id")).toBe(SESSION); |
| 131 | + expect(logCtx.conversationId).toBeTruthy(); |
| 132 | + } finally { lease?.release(); } |
| 133 | + }); |
| 134 | +}); |
| 135 | + |
| 136 | +test("the public routes hand their handlers the caller-promoted request", () => { |
| 137 | + // Pins the two-line wiring; the cases above call the helper directly. |
| 138 | + const source = readFileSync(repoPath("src", "server", "index", "serve-options.ts"), "utf8"); |
| 139 | + expect(source).toContain("await handleResponses(withCallerSessionIdentity(withGrokSessionIdentity(req)), config, logCtx, {"); |
| 140 | + expect(source).toContain("await handleClaudeMessages(withCallerSessionIdentity(req), config, logCtx,"); |
| 141 | +}); |
0 commit comments