Skip to content

Commit 4ad8753

Browse files
committed
fix(memory): bound remote JSON responses
1 parent c48a4a3 commit 4ad8753

5 files changed

Lines changed: 200 additions & 18 deletions

File tree

‎packages/memory-host-sdk/src/host/batch-upload.test.ts‎

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ function textResponse(body: string, status: number): Response {
1515
function streamingTextResponse(params: {
1616
body: string;
1717
status: number;
18+
headers?: HeadersInit;
1819
onCancel: () => void;
1920
}): Response {
2021
const encoded = new TextEncoder().encode(params.body);
@@ -26,7 +27,7 @@ function streamingTextResponse(params: {
2627
params.onCancel();
2728
},
2829
});
29-
return new Response(stream, { status: params.status });
30+
return new Response(stream, { status: params.status, headers: params.headers });
3031
}
3132

3233
describe("uploadBatchJsonlFile", () => {
@@ -77,4 +78,33 @@ describe("uploadBatchJsonlFile", () => {
7778
).rejects.toThrow(`file upload failed: 413 ${"x".repeat(1_000)}... [truncated]`);
7879
expect(canceled).toBe(true);
7980
});
81+
82+
it("rejects oversized successful file-upload JSON before parsing", async () => {
83+
let canceled = false;
84+
remoteHttpMock.mockImplementationOnce(async (params) => {
85+
return await params.onResponse(
86+
streamingTextResponse({
87+
body: '{"id":"file_123"}',
88+
status: 200,
89+
headers: { "content-length": "64" },
90+
onCancel: () => {
91+
canceled = true;
92+
},
93+
}),
94+
);
95+
});
96+
97+
await expect(
98+
uploadBatchJsonlFile({
99+
client: {
100+
baseUrl: "https://memory.example/v1",
101+
headers: { Authorization: "Bearer test" },
102+
},
103+
requests: [{ input: "one" }],
104+
errorPrefix: "file upload failed",
105+
maxResponseBytes: 8,
106+
}),
107+
).rejects.toThrow("file upload failed: response body too large: 64 bytes (limit: 8 bytes)");
108+
expect(canceled).toBe(true);
109+
});
80110
});

‎packages/memory-host-sdk/src/host/batch-upload.ts‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,13 @@ import {
55
} from "./batch-utils.js";
66
import { hashText } from "./hash.js";
77
import { withRemoteHttpResponse } from "./remote-http.js";
8-
import { readResponseTextSnippet } from "./response-snippet.js";
8+
import { readResponseJsonWithLimit, readResponseTextSnippet } from "./response-snippet.js";
99

1010
export async function uploadBatchJsonlFile(params: {
1111
client: BatchHttpClientConfig;
1212
requests: unknown[];
1313
errorPrefix: string;
14+
maxResponseBytes?: number;
1415
}): Promise<string> {
1516
const baseUrl = normalizeBatchBaseUrl(params.client);
1617
const jsonl = params.requests.map((request) => JSON.stringify(request)).join("\n");
@@ -35,11 +36,10 @@ export async function uploadBatchJsonlFile(params: {
3536
const text = await readResponseTextSnippet(fileRes);
3637
throw new Error(`${params.errorPrefix}: ${fileRes.status} ${text}`);
3738
}
38-
try {
39-
return (await fileRes.json()) as { id?: string };
40-
} catch (cause) {
41-
throw new Error(`${params.errorPrefix}: malformed JSON response`, { cause });
42-
}
39+
return (await readResponseJsonWithLimit(fileRes, {
40+
errorPrefix: params.errorPrefix,
41+
maxBytes: params.maxResponseBytes,
42+
})) as { id?: string };
4343
},
4444
});
4545
if (!filePayload.id) {

‎packages/memory-host-sdk/src/host/post-json.test.ts‎

Lines changed: 57 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ function textResponse(body: string, status: number): Response {
1919
function streamingTextResponse(params: {
2020
body: string;
2121
status: number;
22+
headers?: HeadersInit;
2223
onCancel: () => void;
2324
}): Response {
2425
const encoded = new TextEncoder().encode(params.body);
@@ -30,7 +31,7 @@ function streamingTextResponse(params: {
3031
params.onCancel();
3132
},
3233
});
33-
return new Response(stream, { status: params.status });
34+
return new Response(stream, { status: params.status, headers: params.headers });
3435
}
3536

3637
describe("postJson", () => {
@@ -136,4 +137,59 @@ describe("postJson", () => {
136137
}),
137138
).rejects.toThrow("post failed: malformed JSON response");
138139
});
140+
141+
it("rejects successful JSON responses with oversized content-length", async () => {
142+
let canceled = false;
143+
remoteHttpMock.mockImplementationOnce(async (params) => {
144+
return await params.onResponse(
145+
streamingTextResponse({
146+
body: "{}",
147+
status: 200,
148+
headers: { "content-length": "32" },
149+
onCancel: () => {
150+
canceled = true;
151+
},
152+
}),
153+
);
154+
});
155+
156+
await expect(
157+
postJson({
158+
url: "https://memory.example/v1/post",
159+
headers: {},
160+
body: {},
161+
errorPrefix: "post failed",
162+
maxResponseBytes: 8,
163+
parse: () => ({}),
164+
}),
165+
).rejects.toThrow("post failed: response body too large: 32 bytes (limit: 8 bytes)");
166+
expect(canceled).toBe(true);
167+
});
168+
169+
it("cancels successful JSON responses that exceed the streaming byte cap", async () => {
170+
let canceled = false;
171+
remoteHttpMock.mockImplementationOnce(async (params) => {
172+
return await params.onResponse(
173+
streamingTextResponse({
174+
body: `{"data":"${"x".repeat(32)}"}`,
175+
status: 200,
176+
onCancel: () => {
177+
canceled = true;
178+
},
179+
}),
180+
);
181+
});
182+
183+
await expect(
184+
postJson({
185+
url: "https://memory.example/v1/post",
186+
headers: {},
187+
body: {},
188+
errorPrefix: "post failed",
189+
maxResponseBytes: 16,
190+
parse: () => ({}),
191+
}),
192+
).rejects.toThrow("post failed: response body too large");
193+
expect(canceled).toBe(true);
194+
});
139195
});

‎packages/memory-host-sdk/src/host/post-json.ts‎

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { withRemoteHttpResponse } from "./remote-http.js";
2-
import { readResponseTextSnippet } from "./response-snippet.js";
2+
import { readResponseJsonWithLimit, readResponseTextSnippet } from "./response-snippet.js";
33
import type { SsrFPolicy } from "./ssrf-policy.js";
44

55
export async function postJson<T>(params: {
@@ -11,6 +11,7 @@ export async function postJson<T>(params: {
1111
body: unknown;
1212
errorPrefix: string;
1313
attachStatus?: boolean;
14+
maxResponseBytes?: number;
1415
parse: (payload: unknown) => T | Promise<T>;
1516
}): Promise<T> {
1617
return await withRemoteHttpResponse({
@@ -34,15 +35,11 @@ export async function postJson<T>(params: {
3435
}
3536
throw err;
3637
}
37-
return await params.parse(await readJsonResponse(res, params.errorPrefix));
38+
const payload = await readResponseJsonWithLimit(res, {
39+
errorPrefix: params.errorPrefix,
40+
maxBytes: params.maxResponseBytes,
41+
});
42+
return await params.parse(payload);
3843
},
3944
});
4045
}
41-
42-
async function readJsonResponse(res: Response, errorPrefix: string): Promise<unknown> {
43-
try {
44-
return await res.json();
45-
} catch (cause) {
46-
throw new Error(`${errorPrefix}: malformed JSON response`, { cause });
47-
}
48-
}

‎packages/memory-host-sdk/src/host/response-snippet.ts‎

Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,18 @@
11
const DEFAULT_ERROR_BODY_MAX_BYTES = 8 * 1024;
22
const DEFAULT_ERROR_BODY_MAX_CHARS = 1_000;
3+
const DEFAULT_JSON_BODY_MAX_BYTES = 64 * 1024 * 1024;
34
const TRUNCATED_SUFFIX = "... [truncated]";
45

56
type ResponseTextSnippetOptions = {
67
maxBytes?: number;
78
maxChars?: number;
89
};
910

11+
type ResponseJsonOptions = {
12+
maxBytes?: number;
13+
errorPrefix: string;
14+
};
15+
1016
type ResponsePrefix = {
1117
bytes: Uint8Array[];
1218
length: number;
@@ -35,6 +41,26 @@ export async function readResponseTextSnippet(
3541
return collapsed;
3642
}
3743

44+
export async function readResponseJsonWithLimit(
45+
res: Response,
46+
options: ResponseJsonOptions,
47+
): Promise<unknown> {
48+
const maxBytes = options.maxBytes ?? DEFAULT_JSON_BODY_MAX_BYTES;
49+
const contentLength = parseContentLength(res.headers.get("content-length"), options.errorPrefix);
50+
if (typeof contentLength === "number" && contentLength > maxBytes) {
51+
await cancelResponseBody(res);
52+
throw responseTooLarge(options.errorPrefix, contentLength, maxBytes);
53+
}
54+
55+
const text = await readResponseTextWithLimit(res, maxBytes, options.errorPrefix);
56+
57+
try {
58+
return JSON.parse(text);
59+
} catch (cause) {
60+
throw new Error(`${options.errorPrefix}: malformed JSON response`, { cause });
61+
}
62+
}
63+
3864
async function readResponsePrefix(res: Response, maxBytes: number): Promise<ResponsePrefix> {
3965
const body = res.body;
4066
if (!body || typeof body.getReader !== "function") {
@@ -79,6 +105,79 @@ async function readResponsePrefix(res: Response, maxBytes: number): Promise<Resp
79105
return { bytes: chunks, length, truncated };
80106
}
81107

108+
async function readResponseTextWithLimit(
109+
res: Response,
110+
maxBytes: number,
111+
errorPrefix: string,
112+
): Promise<string> {
113+
const body = res.body;
114+
if (!body || typeof body.getReader !== "function") {
115+
return "";
116+
}
117+
118+
const reader = body.getReader();
119+
const chunks: Uint8Array[] = [];
120+
let length = 0;
121+
122+
try {
123+
while (true) {
124+
const { done, value } = await reader.read();
125+
if (done) {
126+
break;
127+
}
128+
if (!value?.length) {
129+
continue;
130+
}
131+
132+
const nextLength = length + value.length;
133+
if (nextLength > maxBytes) {
134+
await reader.cancel().catch(() => undefined);
135+
throw responseTooLarge(errorPrefix, nextLength, maxBytes);
136+
}
137+
138+
chunks.push(value);
139+
length = nextLength;
140+
}
141+
} finally {
142+
try {
143+
reader.releaseLock();
144+
} catch {}
145+
}
146+
147+
return new TextDecoder().decode(joinChunks(chunks, length));
148+
}
149+
150+
async function cancelResponseBody(res: Response): Promise<void> {
151+
const body = res.body;
152+
if (!body || typeof body.cancel !== "function") {
153+
return;
154+
}
155+
await body.cancel().catch(() => undefined);
156+
}
157+
158+
function parseContentLength(raw: string | null, errorPrefix: string): number | undefined {
159+
const trimmed = raw?.trim();
160+
if (!trimmed) {
161+
return undefined;
162+
}
163+
if (!/^(0|[1-9]\d*)$/.test(trimmed)) {
164+
throw new Error(`${errorPrefix}: invalid content-length header: ${raw}`);
165+
}
166+
const value = Number(trimmed);
167+
if (!Number.isSafeInteger(value)) {
168+
throw new Error(`${errorPrefix}: invalid content-length header: ${raw}`);
169+
}
170+
return value;
171+
}
172+
173+
function responseTooLarge(errorPrefix: string, size: number, maxBytes: number): Error {
174+
return new Error(responseTooLargeMessage(errorPrefix, size, maxBytes));
175+
}
176+
177+
function responseTooLargeMessage(errorPrefix: string, size: number, maxBytes: number): string {
178+
return `${errorPrefix}: response body too large: ${size} bytes (limit: ${maxBytes} bytes)`;
179+
}
180+
82181
function joinChunks(chunks: Uint8Array[], length: number): Uint8Array {
83182
if (chunks.length === 1 && chunks[0]?.length === length) {
84183
return chunks[0];

0 commit comments

Comments
 (0)