Skip to content

Commit 51b64b8

Browse files
committed
fix(proxy): stream debug capture bodies
1 parent b804d20 commit 51b64b8

2 files changed

Lines changed: 228 additions & 22 deletions

File tree

‎src/proxy-capture/proxy-server.test.ts‎

Lines changed: 163 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,126 @@
11
// Proxy capture server tests cover request recording and response handling.
2-
import { describe, expect, it } from "vitest";
3-
import { parseConnectTarget } from "./proxy-server.js";
2+
import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
3+
import { request as httpRequest, createServer as createHttpServer } from "node:http";
4+
import type { AddressInfo } from "node:net";
5+
import { tmpdir } from "node:os";
6+
import { join } from "node:path";
7+
import { afterEach, describe, expect, it } from "vitest";
8+
import type { DebugProxySettings } from "./env.js";
9+
import { parseConnectTarget, startDebugProxyServer } from "./proxy-server.js";
10+
import { closeDebugProxyCaptureStore, getDebugProxyCaptureStore } from "./store.sqlite.js";
11+
12+
let testRoot: string | undefined;
13+
14+
async function cleanupTestRoot(): Promise<void> {
15+
closeDebugProxyCaptureStore();
16+
if (!testRoot) {
17+
return;
18+
}
19+
const root = testRoot;
20+
testRoot = undefined;
21+
await rm(root, { recursive: true, force: true });
22+
}
23+
24+
async function makeSettings(): Promise<DebugProxySettings> {
25+
testRoot = await mkdtemp(join(tmpdir(), "openclaw-debug-proxy-server-"));
26+
const certDir = join(testRoot, "certs");
27+
await mkdir(certDir, { recursive: true });
28+
await writeFile(join(certDir, "root-ca.pem"), "test root cert\n", "utf8");
29+
await writeFile(join(certDir, "root-ca-key.pem"), "test root key\n", "utf8");
30+
return {
31+
enabled: true,
32+
required: false,
33+
dbPath: ":memory:",
34+
blobDir: join(testRoot, "blobs"),
35+
certDir,
36+
sessionId: "debug-proxy-server-test",
37+
sourceProcess: "test",
38+
};
39+
}
40+
41+
async function startLargeBodyOrigin(): Promise<{
42+
receivedRequestBody: () => string;
43+
responseBody: string;
44+
stop: () => Promise<void>;
45+
url: string;
46+
}> {
47+
let receivedBody = "";
48+
const responseBody = "r".repeat(12_000);
49+
const server = createHttpServer((req, res) => {
50+
req.setEncoding("utf8");
51+
req.on("data", (chunk) => {
52+
receivedBody += chunk;
53+
});
54+
req.on("end", () => {
55+
res.writeHead(200, {
56+
"content-length": Buffer.byteLength(responseBody),
57+
"content-type": "text/plain; charset=utf-8",
58+
});
59+
res.end(responseBody);
60+
});
61+
});
62+
await new Promise<void>((resolve, reject) => {
63+
server.once("error", reject);
64+
server.listen(0, "127.0.0.1", () => {
65+
server.off("error", reject);
66+
resolve();
67+
});
68+
});
69+
const address = server.address() as AddressInfo;
70+
return {
71+
receivedRequestBody: () => receivedBody,
72+
responseBody,
73+
stop: async () =>
74+
await new Promise<void>((resolve, reject) => {
75+
server.close((error) => {
76+
if (error) {
77+
reject(error);
78+
return;
79+
}
80+
resolve();
81+
});
82+
}),
83+
url: `http://127.0.0.1:${address.port}/capture`,
84+
};
85+
}
86+
87+
async function postThroughProxy(params: {
88+
body: string;
89+
proxyUrl: string;
90+
targetUrl: string;
91+
}): Promise<string> {
92+
const proxy = new URL(params.proxyUrl);
93+
return await new Promise<string>((resolve, reject) => {
94+
const req = httpRequest(
95+
{
96+
host: proxy.hostname,
97+
port: Number(proxy.port),
98+
method: "POST",
99+
path: params.targetUrl,
100+
headers: {
101+
connection: "close",
102+
"content-length": Buffer.byteLength(params.body),
103+
"content-type": "text/plain; charset=utf-8",
104+
},
105+
},
106+
(res) => {
107+
const chunks: Buffer[] = [];
108+
res.on("data", (chunk) => {
109+
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
110+
});
111+
res.on("end", () => {
112+
resolve(Buffer.concat(chunks).toString("utf8"));
113+
});
114+
},
115+
);
116+
req.on("error", reject);
117+
req.end(params.body);
118+
});
119+
}
120+
121+
afterEach(async () => {
122+
await cleanupTestRoot();
123+
});
4124

5125
describe("parseConnectTarget", () => {
6126
it("parses bracketed IPv6 CONNECT targets safely", () => {
@@ -23,3 +143,44 @@ describe("parseConnectTarget", () => {
23143
expect(() => parseConnectTarget("api.openai.com:0x50")).toThrow("Invalid CONNECT target port");
24144
});
25145
});
146+
147+
describe("startDebugProxyServer", () => {
148+
it("caps captured body previews while forwarding full request and response bodies", async () => {
149+
const settings = await makeSettings();
150+
const origin = await startLargeBodyOrigin();
151+
const proxy = await startDebugProxyServer({ settings });
152+
const requestBody = "q".repeat(12_000);
153+
154+
try {
155+
const responseBody = await postThroughProxy({
156+
body: requestBody,
157+
proxyUrl: proxy.proxyUrl,
158+
targetUrl: origin.url,
159+
});
160+
161+
expect(origin.receivedRequestBody()).toBe(requestBody);
162+
expect(responseBody).toBe(origin.responseBody);
163+
const events = getDebugProxyCaptureStore(settings.dbPath, settings.blobDir).getSessionEvents(
164+
settings.sessionId,
165+
10,
166+
);
167+
const capturedRequest = events.find((event) => event.kind === "request");
168+
const capturedResponse = events.find((event) => event.kind === "response");
169+
expect(capturedRequest?.dataText).toBe("q".repeat(8192));
170+
expect(capturedResponse?.dataText).toBe("r".repeat(8192));
171+
expect(JSON.parse(String(capturedRequest?.metaJson))).toMatchObject({
172+
bodyBytes: 12_000,
173+
capturePreviewBytes: 8192,
174+
captureTruncated: true,
175+
});
176+
expect(JSON.parse(String(capturedResponse?.metaJson))).toMatchObject({
177+
bodyBytes: 12_000,
178+
capturePreviewBytes: 8192,
179+
captureTruncated: true,
180+
});
181+
} finally {
182+
await proxy.stop();
183+
await origin.stop();
184+
}
185+
});
186+
});

‎src/proxy-capture/proxy-server.ts‎

Lines changed: 65 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,14 @@ import type { CaptureEventRecord } from "./types.js";
1313
const TRUTHY_ENV = new Set(["1", "true", "yes", "on"]);
1414
const DEBUG_PROXY_DIRECT_CONNECT_OVERRIDE =
1515
"OPENCLAW_DEBUG_PROXY_ALLOW_DIRECT_CONNECT_WITH_MANAGED_PROXY";
16+
const CAPTURE_BODY_PREVIEW_BYTES = 8192;
17+
18+
type BodyPreviewCapture = {
19+
chunks: Buffer[];
20+
previewBytes: number;
21+
totalBytes: number;
22+
truncated: boolean;
23+
};
1624

1725
function isTruthyEnvValue(value: string | undefined): boolean {
1826
return TRUTHY_ENV.has((value ?? "").trim().toLowerCase());
@@ -104,12 +112,40 @@ function normalizeTargetUrl(req: IncomingMessage): URL {
104112
return new URL(`http://${host}${req.url ?? "/"}`);
105113
}
106114

107-
async function readBody(req: IncomingMessage): Promise<Buffer> {
108-
const chunks: Buffer[] = [];
109-
for await (const chunk of req) {
110-
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
115+
function createBodyPreviewCapture(): BodyPreviewCapture {
116+
return { chunks: [], previewBytes: 0, totalBytes: 0, truncated: false };
117+
}
118+
119+
function appendBodyPreviewCapture(capture: BodyPreviewCapture, chunk: Buffer | string): void {
120+
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
121+
capture.totalBytes += buffer.byteLength;
122+
const remaining = CAPTURE_BODY_PREVIEW_BYTES - capture.previewBytes;
123+
if (remaining <= 0) {
124+
capture.truncated = capture.truncated || buffer.byteLength > 0;
125+
return;
126+
}
127+
const slice = buffer.byteLength > remaining ? buffer.subarray(0, remaining) : buffer;
128+
capture.chunks.push(slice);
129+
capture.previewBytes += slice.byteLength;
130+
if (slice.byteLength < buffer.byteLength) {
131+
capture.truncated = true;
111132
}
112-
return Buffer.concat(chunks);
133+
}
134+
135+
function finishBodyPreviewCapture(capture: BodyPreviewCapture): {
136+
dataText: string;
137+
metaJson?: string;
138+
} {
139+
return {
140+
dataText: Buffer.concat(capture.chunks, capture.previewBytes).toString("utf8"),
141+
metaJson: capture.truncated
142+
? JSON.stringify({
143+
bodyBytes: capture.totalBytes,
144+
capturePreviewBytes: CAPTURE_BODY_PREVIEW_BYTES,
145+
captureTruncated: true,
146+
})
147+
: undefined,
148+
};
113149
}
114150

115151
export async function startDebugProxyServer(params: {
@@ -180,40 +216,52 @@ export async function startDebugProxyServer(params: {
180216
res.end(responseBody);
181217
return;
182218
}
183-
const body = await readBody(req);
184-
recordTargetEvent({
185-
direction: "outbound",
186-
kind: "request",
187-
headersJson: JSON.stringify(req.headers),
188-
dataText: body.subarray(0, 8192).toString("utf8"),
189-
});
219+
const requestCapture = createBodyPreviewCapture();
190220
const upstream = (target.protocol === "https:" ? httpsRequest : httpRequest)(
191221
target,
192222
{
193223
method: req.method,
194224
headers: req.headers,
195225
},
196226
(upstreamRes) => {
197-
const chunks: Buffer[] = [];
227+
const responseCapture = createBodyPreviewCapture();
198228
upstreamRes.on("data", (chunk) => {
199229
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
200-
chunks.push(buffer);
230+
appendBodyPreviewCapture(responseCapture, buffer);
201231
res.write(buffer);
202232
});
203233
upstreamRes.on("end", () => {
204-
const responseBody = Buffer.concat(chunks);
205234
recordTargetEvent({
206235
direction: "inbound",
207236
kind: "response",
208237
status: upstreamRes.statusCode ?? undefined,
209238
headersJson: JSON.stringify(upstreamRes.headers),
210-
dataText: responseBody.subarray(0, 8192).toString("utf8"),
239+
...finishBodyPreviewCapture(responseCapture),
211240
});
212241
res.end();
213242
});
214243
res.writeHead(upstreamRes.statusCode ?? 502, upstreamRes.headers);
215244
},
216245
);
246+
req.on("data", (chunk) => {
247+
appendBodyPreviewCapture(requestCapture, chunk);
248+
});
249+
req.on("end", () => {
250+
recordTargetEvent({
251+
direction: "outbound",
252+
kind: "request",
253+
headersJson: JSON.stringify(req.headers),
254+
...finishBodyPreviewCapture(requestCapture),
255+
});
256+
});
257+
req.on("error", (error) => {
258+
recordTargetEvent({
259+
direction: "local",
260+
kind: "error",
261+
errorText: error.message,
262+
});
263+
upstream.destroy(error);
264+
});
217265
upstream.on("error", (error) => {
218266
recordTargetEvent({
219267
direction: "local",
@@ -223,10 +271,7 @@ export async function startDebugProxyServer(params: {
223271
res.statusCode = 502;
224272
res.end(error.message);
225273
});
226-
if (body.byteLength > 0) {
227-
upstream.write(body);
228-
}
229-
upstream.end();
274+
req.pipe(upstream);
230275
})();
231276
});
232277

0 commit comments

Comments
 (0)