Skip to content

Commit 968256f

Browse files
authored
fix(copilot): authenticate azure byok proxy requests (#134781)
The red CI doesn't appear related to this PR.
1 parent 75ab3f7 commit 968256f

2 files changed

Lines changed: 162 additions & 9 deletions

File tree

‎extensions/copilot/src/byok-proxy.test.ts‎

Lines changed: 86 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { request as httpRequest } from "node:http";
12
// Copilot BYOK proxy tests verify SDK-local transport is guarded outbound fetch.
23
import { expectDefined } from "@openclaw/normalization-core";
34
import type { fetchWithSsrFGuard } from "openclaw/plugin-sdk/ssrf-runtime";
@@ -14,6 +15,16 @@ vi.mock("openclaw/plugin-sdk/ssrf-runtime", async (importOriginal) => ({
1415
fetchWithSsrFGuard: ssrfRuntimeMock.fetchWithSsrFGuard,
1516
}));
1617

18+
function getProxyCredentialHeader(headers: Record<string, string>): [string, string] {
19+
return expectDefined(
20+
Object.entries(headers).find(
21+
([name, value]) =>
22+
/^x-openclaw-copilot-byok-[a-f0-9]{24}$/.test(name) && /^[a-f0-9]{24}$/.test(value),
23+
),
24+
"proxy credential header",
25+
);
26+
}
27+
1728
describe("createCopilotByokProxy", () => {
1829
afterEach(() => {
1930
ssrfRuntimeMock.fetchWithSsrFGuard.mockReset();
@@ -319,19 +330,29 @@ describe("createCopilotByokProxy", () => {
319330
api: "azure-openai-responses",
320331
id: "deployment-gpt",
321332
baseUrl: "https://example.openai.azure.com/openai/v1",
333+
headers: {
334+
"X-OpenClaw-Copilot-Byok-Proxy-Token": "configured-value",
335+
"X-Trace": "test",
336+
},
322337
},
323338
resolvedApiKey: "azure-key",
324339
});
325340

326341
const proxy = await createCopilotByokProxy(resolvedProvider);
327342
expect(proxy?.provider.provider?.baseUrl).toMatch(/^http:\/\/127\.0\.0\.1:\d+$/);
343+
const sdkHeaders = expectDefined(proxy?.provider.provider?.headers, "Azure SDK headers");
344+
const [proxyCredentialHeader] = getProxyCredentialHeader(sdkHeaders);
345+
expect(sdkHeaders).toMatchObject({
346+
"X-OpenClaw-Copilot-Byok-Proxy-Token": "configured-value",
347+
"X-Trace": "test",
348+
});
328349

329350
try {
330351
const response = await fetch(
331352
`${proxy?.provider.provider?.baseUrl}/openai/v1/responses?trace=request`,
332353
{
333354
method: "POST",
334-
headers: { "api-key": "azure-key" },
355+
headers: { ...sdkHeaders, "api-key": "azure-key" },
335356
body: JSON.stringify({ model: "deployment-gpt" }),
336357
},
337358
);
@@ -346,10 +367,72 @@ describe("createCopilotByokProxy", () => {
346367
headers: expect.objectContaining({
347368
"accept-encoding": "identity",
348369
"api-key": "azure-key",
370+
"x-openclaw-copilot-byok-proxy-token": "configured-value",
371+
"x-trace": "test",
349372
}),
350373
}),
351374
}),
352375
);
376+
const call = ssrfRuntimeMock.fetchWithSsrFGuard.mock.calls[0]?.[0] as
377+
| { init?: { headers?: Record<string, string> } }
378+
| undefined;
379+
expect(call?.init?.headers).not.toHaveProperty(proxyCredentialHeader);
380+
} finally {
381+
await proxy?.close();
382+
}
383+
});
384+
385+
it("rejects nonce-less Azure SDK paths before reading the request body", async () => {
386+
ssrfRuntimeMock.fetchWithSsrFGuard.mockResolvedValue({
387+
response: new Response("unexpected", { status: 200 }),
388+
release: vi.fn(async () => undefined),
389+
});
390+
const proxy = await createCopilotByokProxy(
391+
resolveCopilotProvider({
392+
model: {
393+
provider: "custom-azure",
394+
api: "azure-openai-responses",
395+
id: "deployment-gpt",
396+
baseUrl: "https://example.openai.azure.com/openai/v1",
397+
},
398+
}),
399+
);
400+
const sdkHeaders = expectDefined(proxy?.provider.provider?.headers, "Azure SDK headers");
401+
const [proxyCredentialHeader] = getProxyCredentialHeader(sdkHeaders);
402+
403+
try {
404+
const status = await new Promise<number>((resolve, reject) => {
405+
const client = httpRequest(
406+
`${proxy?.provider.provider?.baseUrl}/openai/v1/responses`,
407+
{ method: "POST", headers: { "content-length": "1048576" } },
408+
(response) => {
409+
clearTimeout(timeout);
410+
response.resume();
411+
resolve(response.statusCode ?? 0);
412+
},
413+
);
414+
const timeout = setTimeout(() => {
415+
client.destroy();
416+
reject(new Error("proxy waited for the unauthenticated request body"));
417+
}, 1_000);
418+
client.on("error", (error) => {
419+
clearTimeout(timeout);
420+
reject(error);
421+
});
422+
client.flushHeaders();
423+
});
424+
425+
expect(status).toBe(404);
426+
const wrongCredential = await fetch(
427+
`${proxy?.provider.provider?.baseUrl}/openai/v1/responses`,
428+
{
429+
method: "POST",
430+
headers: { [proxyCredentialHeader]: "wrong" },
431+
body: JSON.stringify({ model: "deployment-gpt" }),
432+
},
433+
);
434+
expect(wrongCredential.status).toBe(404);
435+
expect(ssrfRuntimeMock.fetchWithSsrFGuard).not.toHaveBeenCalled();
353436
} finally {
354437
await proxy?.close();
355438
}
@@ -372,10 +455,12 @@ describe("createCopilotByokProxy", () => {
372455
});
373456

374457
const proxy = await createCopilotByokProxy(resolvedProvider);
458+
const sdkHeaders = expectDefined(proxy?.provider.provider?.headers, "Azure SDK headers");
375459

376460
try {
377461
const response = await fetch(`${proxy?.provider.provider?.baseUrl}/openai/v1/responses`, {
378462
method: "POST",
463+
headers: sdkHeaders,
379464
body: JSON.stringify({ model: "deployment-gpt" }),
380465
});
381466

‎extensions/copilot/src/byok-proxy.ts‎

Lines changed: 76 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
// Copilot BYOK transport proxy keeps OpenClaw in charge of outbound network policy.
2-
import { randomBytes } from "node:crypto";
2+
import { randomBytes, timingSafeEqual } from "node:crypto";
33
import { createServer, type IncomingMessage, type ServerResponse } from "node:http";
44
import { Readable } from "node:stream";
55
import { pipeline } from "node:stream/promises";
@@ -8,6 +8,7 @@ import { fetchWithSsrFGuard } from "openclaw/plugin-sdk/ssrf-runtime";
88
import type { ResolvedCopilotProvider } from "./provider-bridge.js";
99

1010
const LOOPBACK_HOST = "127.0.0.1";
11+
const PROXY_CREDENTIAL_HEADER_PREFIX = "x-openclaw-copilot-byok-";
1112

1213
type CopilotByokProxyHandle = {
1314
close: () => Promise<void>;
@@ -32,14 +33,21 @@ export async function createCopilotByokProxy(
3233
const nonce = randomBytes(12).toString("hex");
3334
const targetPathPrefix = trimTrailingSlash(targetBaseUrl.pathname);
3435
const proxyPathPrefix = `/${nonce}${targetPathPrefix}`;
36+
// Azure rebuilds nonce-less /openai paths, so carry the same per-proxy secret
37+
// in an SDK provider header and validate it before accepting request bytes.
3538
const acceptsAzureSdkPaths = providerConfig.type === "azure";
39+
const proxyCredentialHeader = acceptsAzureSdkPaths
40+
? createProxyCredentialHeaderName(providerConfig.headers)
41+
: undefined;
3642
const upstreamBearerAuthorization = resolveUpstreamBearerAuthorization(providerConfig);
3743
const activeFetches = new Set<AbortController>();
3844
const server = createServer((req, res) => {
3945
void handleProxyRequest(req, res, {
4046
acceptsAzureSdkPaths,
4147
activeFetches,
4248
proxyPathPrefix,
49+
proxyCredential: nonce,
50+
proxyCredentialHeader,
4351
targetBaseUrl,
4452
targetPathPrefix,
4553
upstreamBearerAuthorization,
@@ -69,6 +77,15 @@ export async function createCopilotByokProxy(
6977
provider: {
7078
...providerConfig,
7179
baseUrl: sdkBaseUrl,
80+
...(proxyCredentialHeader
81+
? {
82+
headers: buildSdkProviderHeaders(
83+
providerConfig.headers,
84+
proxyCredentialHeader,
85+
nonce,
86+
),
87+
}
88+
: {}),
7289
},
7390
},
7491
close: async () => {
@@ -92,6 +109,8 @@ async function handleProxyRequest(
92109
acceptsAzureSdkPaths: boolean;
93110
activeFetches: Set<AbortController>;
94111
proxyPathPrefix: string;
112+
proxyCredential: string;
113+
proxyCredentialHeader: string | undefined;
95114
targetBaseUrl: URL;
96115
targetPathPrefix: string;
97116
upstreamBearerAuthorization: string | undefined;
@@ -108,9 +127,14 @@ async function handleProxyRequest(
108127
}
109128
});
110129
try {
111-
const canInjectBearerAuthorization = isNonceProtectedProxyRequest(req, params.proxyPathPrefix);
130+
const isNonceProtected = isNonceProtectedProxyRequest(req, params.proxyPathPrefix);
112131
const url = resolveTargetUrl(req, params);
113-
if (!url) {
132+
if (
133+
!url ||
134+
(!isNonceProtected &&
135+
(!params.proxyCredentialHeader ||
136+
!hasValidProxyCredential(req, params.proxyCredentialHeader, params.proxyCredential)))
137+
) {
114138
res.writeHead(404);
115139
res.end("Not found");
116140
return;
@@ -121,9 +145,10 @@ async function handleProxyRequest(
121145
init: {
122146
method: req.method,
123147
headers: buildProxyRequestHeaders(req.headers, {
124-
upstreamBearerAuthorization: canInjectBearerAuthorization
148+
upstreamBearerAuthorization: isNonceProtected
125149
? params.upstreamBearerAuthorization
126150
: undefined,
151+
proxyCredentialHeader: params.proxyCredentialHeader,
127152
}),
128153
signal: upstreamAbort.signal,
129154
...(body ? { body } : {}),
@@ -210,6 +235,22 @@ function isNonceProtectedProxyRequest(req: IncomingMessage, proxyPathPrefix: str
210235
);
211236
}
212237

238+
function hasValidProxyCredential(
239+
req: IncomingMessage,
240+
headerName: string,
241+
expected: string,
242+
): boolean {
243+
const received = req.headers[headerName];
244+
if (typeof received !== "string") {
245+
return false;
246+
}
247+
const receivedBytes = Buffer.from(received);
248+
const expectedBytes = Buffer.from(expected);
249+
return (
250+
receivedBytes.length === expectedBytes.length && timingSafeEqual(receivedBytes, expectedBytes)
251+
);
252+
}
253+
213254
async function readBody(req: IncomingMessage): Promise<Buffer<ArrayBuffer> | undefined> {
214255
const chunks: Buffer[] = [];
215256
for await (const chunk of req) {
@@ -218,10 +259,17 @@ async function readBody(req: IncomingMessage): Promise<Buffer<ArrayBuffer> | und
218259
return chunks.length > 0 ? Buffer.concat(chunks) : undefined;
219260
}
220261

221-
function normalizeProxyRequestHeaders(headers: IncomingMessage["headers"]): Record<string, string> {
262+
function normalizeProxyRequestHeaders(
263+
headers: IncomingMessage["headers"],
264+
proxyCredentialHeader: string | undefined,
265+
): Record<string, string> {
222266
const out: Record<string, string> = {};
223267
for (const [key, value] of Object.entries(headers)) {
224-
if (isHopByHopHeader(key) || key.toLowerCase() === "accept-encoding") {
268+
if (
269+
isHopByHopHeader(key) ||
270+
key.toLowerCase() === "accept-encoding" ||
271+
key.toLowerCase() === proxyCredentialHeader
272+
) {
225273
continue;
226274
}
227275
const normalized = normalizeHeaderValue(value);
@@ -233,11 +281,31 @@ function normalizeProxyRequestHeaders(headers: IncomingMessage["headers"]): Reco
233281
return out;
234282
}
235283

284+
function buildSdkProviderHeaders(
285+
headers: ProviderConfig["headers"],
286+
proxyCredentialHeader: string,
287+
proxyCredential: string,
288+
): Record<string, string> {
289+
return { ...headers, [proxyCredentialHeader]: proxyCredential };
290+
}
291+
292+
function createProxyCredentialHeaderName(headers: ProviderConfig["headers"]): string {
293+
for (;;) {
294+
const name = `${PROXY_CREDENTIAL_HEADER_PREFIX}${randomBytes(12).toString("hex")}`;
295+
if (!headers || !hasHeader(headers, name)) {
296+
return name;
297+
}
298+
}
299+
}
300+
236301
function buildProxyRequestHeaders(
237302
headers: IncomingMessage["headers"],
238-
params: { upstreamBearerAuthorization: string | undefined },
303+
params: {
304+
proxyCredentialHeader: string | undefined;
305+
upstreamBearerAuthorization: string | undefined;
306+
},
239307
): Record<string, string> {
240-
const out = normalizeProxyRequestHeaders(headers);
308+
const out = normalizeProxyRequestHeaders(headers, params.proxyCredentialHeader);
241309
if (params.upstreamBearerAuthorization && !hasHeader(out, "authorization")) {
242310
// The SDK declares bearerToken as Authorization auth, but some BYOK
243311
// adapter paths can omit it before reaching our loopback proxy. The proxy

0 commit comments

Comments
 (0)