Skip to content

Commit 0539d96

Browse files
committed
fix(sidecar): scope keyed to web-search and HTTPS fail-closed
CodeRabbit #1890 second review: - visionSidecar rejects backend=keyed and provider - resolveKeyedWebSearchSidecar requires https baseUrl - keyed executor uses Headers().set for Content-Type/Authorization
1 parent dba6a8b commit 0539d96

5 files changed

Lines changed: 156 additions & 12 deletions

File tree

‎src/server/management/agent-settings-routes.ts‎

Lines changed: 27 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1050,14 +1050,29 @@ export async function handleAgentSettingsRoutes(ctx: ManagementContext): Promise
10501050
for (const field of ["webSearchSidecar", "visionSidecar"] as const) {
10511051
const section = body[field];
10521052
if (section === undefined || section === null) continue;
1053-
if (!isPlainObject(section)) return jsonResponse({ error: `${field} must be an object or null` }, 400);
1054-
if (section.backend !== undefined && section.backend !== null
1055-
&& section.backend !== "openai" && section.backend !== "anthropic" && section.backend !== "keyed") {
1056-
return jsonResponse({ error: `${field}.backend must be openai, anthropic, keyed, or null` }, 400);
1053+
if (!isPlainObject(section)) return jsonResponse({ error: `${field} must be an object or null` }, 400);
1054+
if (section.backend !== undefined && section.backend !== null) {
1055+
// keyed is web-search-only. Vision still only supports openai/anthropic.
1056+
const allowed =
1057+
section.backend === "openai"
1058+
|| section.backend === "anthropic"
1059+
|| (field === "webSearchSidecar" && section.backend === "keyed");
1060+
if (!allowed) {
1061+
return jsonResponse({
1062+
error: field === "webSearchSidecar"
1063+
? "webSearchSidecar.backend must be openai, anthropic, keyed, or null"
1064+
: "visionSidecar.backend must be openai, anthropic, or null",
1065+
}, 400);
1066+
}
10571067
}
1058-
if (field === "webSearchSidecar" && section.provider !== undefined && section.provider !== null
1059-
&& (typeof section.provider !== "string" || section.provider.trim() === "")) {
1060-
return jsonResponse({ error: "webSearchSidecar.provider must be a nonblank provider name" }, 400);
1068+
if (section.provider !== undefined && section.provider !== null) {
1069+
// provider is a keyed-web-search field only; vision has no provider override.
1070+
if (field !== "webSearchSidecar") {
1071+
return jsonResponse({ error: "visionSidecar.provider is not supported" }, 400);
1072+
}
1073+
if (typeof section.provider !== "string" || section.provider.trim() === "") {
1074+
return jsonResponse({ error: "webSearchSidecar.provider must be a nonblank provider name" }, 400);
1075+
}
10611076
}
10621077
if (section.model !== undefined && typeof section.model !== "string") {
10631078
return jsonResponse({ error: `${field}.model must be a string` }, 400);
@@ -1092,8 +1107,11 @@ export async function handleAgentSettingsRoutes(ctx: ManagementContext): Promise
10921107
const override: Record<string, unknown> = { ...next[field] };
10931108
if (requested.backend === null) delete override.backend;
10941109
else if (requested.backend !== undefined) override.backend = requested.backend;
1095-
if (requested.provider === null || requested.provider === "") delete override.provider;
1096-
else if (requested.provider !== undefined) override.provider = requested.provider;
1110+
// provider only exists on webSearchSidecar (keyed backend). Never persist it for vision.
1111+
if (field === "webSearchSidecar") {
1112+
if (requested.provider === null || requested.provider === "") delete override.provider;
1113+
else if (requested.provider !== undefined) override.provider = requested.provider;
1114+
}
10971115
if (requested.model === "") delete override.model;
10981116
else if (requested.model !== undefined) override.model = requested.model;
10991117
if (Object.keys(override).length > 0) next[field] = override;

‎src/web-search/executor.ts‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -135,9 +135,11 @@ export async function runKeyedWebSearch(
135135
settings: SidecarSettings,
136136
abortSignal?: AbortSignal,
137137
): Promise<SidecarOutcome> {
138-
const headers: Record<string, string> = { "Content-Type": "application/json" };
139-
if (sidecar.provider.headers) Object.assign(headers, sidecar.provider.headers);
140-
headers["authorization"] = `Bearer ${sidecar.apiKey}`;
138+
// Headers() normalizes casing so provider headers cannot create a second
139+
// Authorization/Content-Type entry that would race with the required ones.
140+
const headers = new Headers(sidecar.provider.headers);
141+
headers.set("Content-Type", "application/json");
142+
headers.set("Authorization", `Bearer ${sidecar.apiKey}`);
141143
const body = {
142144
model: settings.model,
143145
instructions: settings.describeImages ? BASE_INSTRUCTION + IMAGE_INSTRUCTION : BASE_INSTRUCTION,

‎src/web-search/index.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,13 @@ export function resolveKeyedWebSearchSidecar(config: OcxConfig): KeyedWebSearchS
149149
if (wire !== KEYED_MODEL_ADAPTER && provider.adapter !== KEYED_MODEL_ADAPTER) return undefined;
150150
const apiKey = resolveEnvValue(provider.apiKey)?.trim();
151151
if (!apiKey) return undefined;
152+
// Fail closed: never attach a Bearer key to a non-HTTPS base URL.
153+
try {
154+
const base = new URL(provider.baseUrl);
155+
if (base.protocol !== "https:") return undefined;
156+
} catch {
157+
return undefined;
158+
}
152159
return { providerName, provider, apiKey, model };
153160
}
154161

‎tests/claude-management-api.test.ts‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -469,6 +469,32 @@ test("Claude webSearchSidecar accepts keyed backend and returns provider on GET"
469469
}
470470
});
471471

472+
test("Claude visionSidecar rejects keyed backend and provider", async () => {
473+
const server = startServer(0);
474+
const put = (body: unknown) => fetch(new URL("/api/claude-code", server.url), {
475+
method: "PUT",
476+
headers: { "Content-Type": "application/json" },
477+
body: JSON.stringify(body),
478+
});
479+
try {
480+
// Seed a valid vision override so a rejected PUT leaves it untouched.
481+
const seed = await put({ visionSidecar: { backend: "openai", model: "gpt-vision" } });
482+
expect(seed.status).toBe(200);
483+
const before = loadConfig().claudeCode;
484+
485+
for (const body of [
486+
{ visionSidecar: { backend: "keyed" } },
487+
{ visionSidecar: { provider: "opencode-go" } },
488+
]) {
489+
const response = await put(body);
490+
expect(response.status).toBe(400);
491+
expect(loadConfig().claudeCode).toEqual(before);
492+
}
493+
} finally {
494+
await server.stop(true);
495+
}
496+
});
497+
472498
test("PUT immediately restores generated agents after re-enable and roster changes", async () => {
473499
const server = startServer(0);
474500
const agentsDir = join(process.env.CLAUDE_CONFIG_DIR!, "agents");

‎tests/web-search-keyed.test.ts‎

Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,28 @@ describe("keyed web-search sidecar eligibility", () => {
143143
),
144144
).toBeUndefined();
145145
});
146+
147+
test("fails closed when the provider baseUrl is not HTTPS", () => {
148+
expect(
149+
resolveKeyedWebSearchSidecar(
150+
configFor(
151+
{ backend: "keyed", provider: "opencode-go", model: "deepseek-v4-flash" },
152+
zenProvider({ baseUrl: "http://opencode.ai/zen/go/v1" }),
153+
),
154+
),
155+
).toBeUndefined();
156+
});
157+
158+
test("fails closed when the provider baseUrl is not a valid URL", () => {
159+
expect(
160+
resolveKeyedWebSearchSidecar(
161+
configFor(
162+
{ backend: "keyed", provider: "opencode-go", model: "deepseek-v4-flash" },
163+
zenProvider({ baseUrl: "not-a-url" }),
164+
),
165+
),
166+
).toBeUndefined();
167+
});
146168
});
147169

148170
describe("runKeyedWebSearch request shape", () => {
@@ -303,4 +325,73 @@ describe("runKeyedWebSearch request shape", () => {
303325
expect(out.error).toBeUndefined();
304326
expect(capturedUrl).toBe("https://search.example/v1/custom-responses");
305327
});
328+
329+
test("normalizes case-variant content-type and keeps a single Authorization", async () => {
330+
let captured: { headers: Record<string, string> } | null = null;
331+
globalThis.fetch = (async (_url: string | URL | Request, init?: RequestInit) => {
332+
const headers: Record<string, string> = {};
333+
new Headers(init?.headers).forEach((v, k) => {
334+
headers[k] = v;
335+
});
336+
captured = { headers };
337+
const body = [
338+
"event: response.output_text.done\ndata: " +
339+
JSON.stringify({ type: "response.output_text.done", text: "ok" }) +
340+
"\n\n",
341+
"event: response.completed\ndata: " +
342+
JSON.stringify({
343+
type: "response.completed",
344+
response: {
345+
output: [
346+
{
347+
type: "message",
348+
role: "assistant",
349+
content: [{ type: "output_text", text: "ok", annotations: [] }],
350+
},
351+
],
352+
},
353+
}) +
354+
"\n\n",
355+
].join("");
356+
return new Response(
357+
new ReadableStream({
358+
start(c) {
359+
c.enqueue(new TextEncoder().encode(body));
360+
c.close();
361+
},
362+
}),
363+
{ status: 200 },
364+
);
365+
}) as unknown as typeof fetch;
366+
367+
const out = await runKeyedWebSearch(
368+
"latest bun release",
369+
{ type: "web_search" } as unknown as Record<string, unknown>,
370+
{
371+
providerName: "opencode-go",
372+
provider: zenProvider({
373+
headers: {
374+
"content-type": "text/plain",
375+
Authorization: "Bearer stale-key",
376+
},
377+
}),
378+
apiKey: "zen-key",
379+
},
380+
{
381+
model: "deepseek-v4-flash",
382+
reasoning: "low",
383+
timeoutMs: 5000,
384+
describeImages: false,
385+
},
386+
);
387+
expect(out.error).toBeUndefined();
388+
const c = captured!;
389+
// Headers() + set() wins over the provider's case-variant entries.
390+
expect(c.headers["content-type"]).toBe("application/json");
391+
expect(c.headers["authorization"]).toBe("Bearer zen-key");
392+
// No second authorization key left behind by Object.assign-style merges.
393+
expect(Object.keys(c.headers).filter((k) => k.toLowerCase() === "authorization")).toEqual([
394+
"authorization",
395+
]);
396+
});
306397
});

0 commit comments

Comments
 (0)