Skip to content

Commit 7f76107

Browse files
committed
test(responses): fence terminal key rotation owner
1 parent 4e9820f commit 7f76107

1 file changed

Lines changed: 245 additions & 0 deletions

File tree

Lines changed: 245 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,245 @@
1+
import { afterEach, beforeEach, describe, expect, mock, test } from "bun:test";
2+
import { mkdtempSync, rmSync } from "node:fs";
3+
import { tmpdir } from "node:os";
4+
import { join } from "node:path";
5+
import type { ProviderAdapter } from "../src/adapters/base";
6+
import { saveConfig } from "../src/config";
7+
import { clearKeyCooldowns } from "../src/providers/key-failover";
8+
import { reasoningReplayKeyCredentialIdentity } from "../src/responses/reasoning-replay-cache";
9+
import {
10+
clearResponseStateForTests,
11+
previousResponseProviderState,
12+
} from "../src/responses/state";
13+
import type {
14+
AdapterEvent,
15+
OcxConfig,
16+
OcxParsedRequest,
17+
OcxProviderConfig,
18+
} from "../src/types";
19+
20+
interface BuildObservation {
21+
key: string;
22+
continuation?: string;
23+
}
24+
25+
let builds: BuildObservation[] = [];
26+
27+
function eventsForPhase(phase: string): AdapterEvent[] {
28+
if (phase === "seed") {
29+
return [
30+
{ type: "text_delta", text: "seeded" },
31+
{
32+
type: "done",
33+
stopReason: "end_turn",
34+
providerState: { kiro: { conversationId: "private-a" } },
35+
},
36+
];
37+
}
38+
if (phase === "plan") {
39+
return [
40+
{ type: "text_delta", text: "I will modify the file now." },
41+
{
42+
type: "done",
43+
stopReason: "end_turn",
44+
providerState: { kiro: { conversationId: "private-a-plan" } },
45+
},
46+
];
47+
}
48+
if (phase === "rotated") {
49+
return [
50+
{ type: "text_delta", text: "completed on the rotated key" },
51+
{
52+
type: "done",
53+
stopReason: "end_turn",
54+
providerState: { kiro: { conversationId: "private-b" } },
55+
},
56+
];
57+
}
58+
if (phase === "follow") {
59+
return [
60+
{ type: "text_delta", text: "continued on the rotated key" },
61+
{
62+
type: "done",
63+
stopReason: "end_turn",
64+
providerState: { kiro: { conversationId: "private-b-next" } },
65+
},
66+
];
67+
}
68+
throw new Error(`unexpected test phase: ${phase}`);
69+
}
70+
71+
const actualResolver = await import("../src/server/adapter-resolve");
72+
const actualResolveAdapter = actualResolver.resolveAdapter;
73+
74+
mock.module("../src/server/adapter-resolve", () => ({
75+
...actualResolver,
76+
resolveAdapter(provider: OcxProviderConfig, cacheRetention?: "none" | "short" | "long") {
77+
if (provider.adapter !== "test-terminal-owned") {
78+
return actualResolveAdapter(provider, cacheRetention);
79+
}
80+
const key = provider.apiKey ?? "";
81+
const adapter: ProviderAdapter = {
82+
// The terminal guard is enabled for Anthropic adapters. The transport is otherwise a
83+
// narrow test double so the test can emit provider-private state deterministically.
84+
name: "anthropic",
85+
buildRequest(parsed: OcxParsedRequest) {
86+
const continuation = parsed._providerContinuation?.kiro?.conversationId;
87+
builds.push({ key, ...(continuation ? { continuation } : {}) });
88+
return {
89+
url: "https://owned-terminal.test/v1/messages",
90+
method: "POST",
91+
headers: { authorization: `Bearer ${key}` },
92+
body: "{}",
93+
};
94+
},
95+
async *parseStream(response: Response): AsyncGenerator<AdapterEvent> {
96+
yield* eventsForPhase(response.headers.get("x-test-phase") ?? "");
97+
},
98+
async parseResponse(response: Response): Promise<AdapterEvent[]> {
99+
return eventsForPhase(response.headers.get("x-test-phase") ?? "");
100+
},
101+
};
102+
return adapter;
103+
},
104+
}));
105+
106+
const { handleResponses } = await import("../src/server/responses");
107+
108+
describe("terminal continuation provider-owner rotation", () => {
109+
let originalFetch: typeof fetch;
110+
let previousHome: string | undefined;
111+
let testHome = "";
112+
113+
beforeEach(() => {
114+
originalFetch = globalThis.fetch;
115+
previousHome = process.env.OPENCODEX_HOME;
116+
testHome = mkdtempSync(join(tmpdir(), "ocx-terminal-owner-"));
117+
process.env.OPENCODEX_HOME = testHome;
118+
builds = [];
119+
clearKeyCooldowns();
120+
clearResponseStateForTests();
121+
});
122+
123+
afterEach(() => {
124+
globalThis.fetch = originalFetch;
125+
if (previousHome === undefined) delete process.env.OPENCODEX_HOME;
126+
else process.env.OPENCODEX_HOME = previousHome;
127+
clearKeyCooldowns();
128+
clearResponseStateForTests();
129+
rmSync(testHome, { recursive: true, force: true });
130+
});
131+
132+
test("429 rotation fences inherited state and persists the rotated owner", async () => {
133+
const keyA = "key-alpha-000111222333";
134+
const keyB = "key-beta-444555666777";
135+
const config: OcxConfig = {
136+
port: 0,
137+
defaultProvider: "owned",
138+
providers: {
139+
owned: {
140+
adapter: "test-terminal-owned",
141+
baseUrl: "https://owned-terminal.test/v1",
142+
authMode: "key",
143+
apiKey: keyA,
144+
apiKeyPool: [
145+
{ id: "k1", key: keyA, addedAt: 1 },
146+
{ id: "k2", key: keyB, addedAt: 2 },
147+
],
148+
},
149+
},
150+
} as OcxConfig;
151+
const keyAIdentity = reasoningReplayKeyCredentialIdentity({ apiKey: keyA });
152+
saveConfig(config);
153+
154+
const phases = ["seed", "plan", "rate-limit", "rotated", "follow"];
155+
const seenAuthorization: string[] = [];
156+
globalThis.fetch = (async (_input, init) => {
157+
seenAuthorization.push(new Headers(init?.headers).get("authorization") ?? "");
158+
const phase = phases.shift();
159+
if (!phase) throw new Error("unexpected extra upstream request");
160+
if (phase === "rate-limit") {
161+
return Response.json(
162+
{ error: { message: "rotate" } },
163+
{ status: 429, headers: { "retry-after": "30" } },
164+
);
165+
}
166+
return new Response("", { headers: { "x-test-phase": phase } });
167+
}) as typeof fetch;
168+
169+
const post = (body: Record<string, unknown>) => handleResponses(
170+
new Request("http://localhost/v1/responses", {
171+
method: "POST",
172+
headers: { "content-type": "application/json" },
173+
body: JSON.stringify(body),
174+
}),
175+
config,
176+
{ model: "", provider: "" },
177+
);
178+
179+
const seed = await post({
180+
model: "owned/model",
181+
input: "seed",
182+
stream: false,
183+
store: true,
184+
});
185+
expect(seed.status).toBe(200);
186+
const seedJson = await seed.json() as { id: string };
187+
expect(previousResponseProviderState(seedJson.id)).toMatchObject({
188+
__ocxOwner: { credentialIdentity: keyAIdentity },
189+
kiro: { conversationId: "private-a" },
190+
});
191+
192+
const rotated = await post({
193+
model: "owned/model",
194+
previous_response_id: seedJson.id,
195+
input: "Please modify the file now",
196+
stream: false,
197+
store: true,
198+
tools: [{
199+
type: "function",
200+
name: "read_file",
201+
description: "read a file",
202+
parameters: { type: "object" },
203+
}],
204+
});
205+
expect(rotated.status).toBe(200);
206+
const rotatedJson = await rotated.json() as { id: string };
207+
const keyBIdentity = reasoningReplayKeyCredentialIdentity(config.providers.owned!);
208+
expect(keyBIdentity).toBeDefined();
209+
expect(keyBIdentity).not.toBe(keyAIdentity);
210+
expect(previousResponseProviderState(rotatedJson.id)).toMatchObject({
211+
__ocxOwner: { credentialIdentity: keyBIdentity },
212+
kiro: { conversationId: "private-b" },
213+
});
214+
215+
const follow = await post({
216+
model: "owned/model",
217+
previous_response_id: rotatedJson.id,
218+
input: "follow up",
219+
stream: false,
220+
store: true,
221+
});
222+
expect(follow.status).toBe(200);
223+
const followJson = await follow.json() as { id: string };
224+
expect(previousResponseProviderState(followJson.id)).toMatchObject({
225+
__ocxOwner: { credentialIdentity: keyBIdentity },
226+
kiro: { conversationId: "private-b-next" },
227+
});
228+
229+
expect(seenAuthorization).toEqual([
230+
`Bearer ${keyA}`,
231+
`Bearer ${keyA}`,
232+
`Bearer ${keyA}`,
233+
`Bearer ${keyB}`,
234+
`Bearer ${keyB}`,
235+
]);
236+
expect(builds).toEqual([
237+
{ key: keyA },
238+
{ key: keyA, continuation: "private-a" },
239+
{ key: keyA, continuation: "private-a" },
240+
{ key: keyB },
241+
{ key: keyB, continuation: "private-b" },
242+
]);
243+
expect(phases).toEqual([]);
244+
});
245+
});

0 commit comments

Comments
 (0)