Skip to content

Commit 8240e57

Browse files
steipetePick-cat
andcommitted
fix(mcp): reject unbounded bodyless responses
Co-authored-by: Pick-cat <[email protected]>
1 parent f0c0fe0 commit 8240e57

3 files changed

Lines changed: 25 additions & 65 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ Docs: https://docs.openclaw.ai
1919

2020
- **Diffs rendering:** render viewer and image output from one SSR preload, preserve language-pack highlighting through hydration, normalize language hints case-insensitively, skip identical before/after inputs with an explicit `changed` result, report truthful file-render and input errors, cache hash-pinned viewer runtimes, and prefer canonical file settings over stale aliases. (#100487)
2121
- **Remote browser reliability:** bound persistent Playwright tab enumeration by the existing remote CDP timeout budget and retire timed-out connection attempts so late completions cannot restore a stuck connection. (#80147, #58968) Thanks @HemantSudarshan and @KeaneYan.
22-
- **MCP OAuth response bounds:** avoid unbounded text fallbacks for body-less foreign error responses while preserving status and headers for SDK diagnostics. (#98143) Thanks @Pick-cat.
22+
- **MCP OAuth response bounds:** reject body-less foreign error bodies without calling their inherently unbounded `text()` fallback, while preserving HTTP status and headers for safe SDK diagnostics. (#98143) Thanks @Pick-cat.
2323
- **Control UI approval prompts:** keep stale resolve failures and busy-state cleanup from leaking across newer approvals or Gateway reconnects. (#98394) Thanks @haruaiclone-droid.
2424
- **Agent empty replies:** surface a visible failure when a completed interactive turn has no deliverable reply, including queued follow-ups, while preserving explicit silence, pending continuations, and committed side effects. (#100456) Thanks @mushuiyu886.
2525
- **Child process output safety:** prevent stdout/stderr pipe failures from crashing agent exec sessions, local TUI shell commands, and bounded process execution. (#100407, #100406, #100410) Thanks @cxbAsDev.

‎src/agents/mcp-http-fetch.test.ts‎

Lines changed: 22 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -33,8 +33,6 @@ class TestProxyAgent {
3333
constructor(readonly options: unknown) {}
3434
}
3535

36-
const MAX_FOREIGN_TEXT_BYTES = 1024 * 1024;
37-
3836
function useBodylessForeignResponse(params: { text: string; contentLength?: string }) {
3937
const text = vi.fn(async () => params.text);
4038
const headers = new Headers({ "content-type": "application/json" });
@@ -242,42 +240,28 @@ describe("MCP HTTP fetch helpers", () => {
242240
expect(calls[1]?.[1]?.headers).toBeUndefined();
243241
});
244242

245-
it("returns fetch responses compatible with MCP SDK OAuth error parsing", async () => {
246-
const body = '{"error":"invalid_client_metadata","error_description":"bad redirect"}';
247-
useBodylessForeignResponse({
248-
text: body,
249-
contentLength: String(Buffer.byteLength(body, "utf8")),
250-
});
251-
252-
const response = await fetchOAuthRegistrationError();
253-
expect(response).toBeInstanceOf(Response);
254-
const error = await parseErrorResponse(response);
255-
expect(error.message).toContain("bad redirect");
256-
expect(error.message).not.toContain("[object Response]");
257-
});
258-
259-
it.each([
260-
{ label: "missing length", contentLength: undefined },
261-
{ label: "exponent length", contentLength: "1e3" },
262-
{ label: "hex length", contentLength: "0x40" },
263-
{ label: "oversized length", contentLength: String(MAX_FOREIGN_TEXT_BYTES + 1) },
264-
])("drops body-less OAuth text with $label before reading", async ({ contentLength }) => {
243+
it.each([undefined, "64", "1048577"])(
244+
"drops body-less foreign OAuth text without trusting Content-Length %s",
245+
async (contentLength) => {
246+
const text = useBodylessForeignResponse({
247+
text: '{"error_description":"unbounded"}',
248+
contentLength,
249+
});
250+
251+
const response = await fetchOAuthRegistrationError();
252+
253+
expect(response).toBeInstanceOf(Response);
254+
expect(response.status).toBe(400);
255+
expect(response.body).toBeNull();
256+
expect(text).not.toHaveBeenCalled();
257+
const error = await parseErrorResponse(response);
258+
expect(error.message).toContain("HTTP 400");
259+
},
260+
);
261+
262+
it("never materializes a body-less foreign response with a lying safe length", async () => {
265263
const text = useBodylessForeignResponse({
266-
text: '{"error_description":"unbounded"}',
267-
contentLength,
268-
});
269-
270-
const response = await fetchOAuthRegistrationError();
271-
272-
expect(response).toBeInstanceOf(Response);
273-
expect(response.status).toBe(400);
274-
expect(response.body).toBeNull();
275-
expect(text).not.toHaveBeenCalled();
276-
});
277-
278-
it("drops body-less text when the returned bytes exceed the declared safe length", async () => {
279-
const text = useBodylessForeignResponse({
280-
text: "x".repeat(MAX_FOREIGN_TEXT_BYTES + 1),
264+
text: "x".repeat(1024 * 1024 + 1),
281265
contentLength: "64",
282266
});
283267

@@ -286,6 +270,6 @@ describe("MCP HTTP fetch helpers", () => {
286270
expect(response).toBeInstanceOf(Response);
287271
expect(response.status).toBe(400);
288272
expect(response.body).toBeNull();
289-
expect(text).toHaveBeenCalledOnce();
273+
expect(text).not.toHaveBeenCalled();
290274
});
291275
});

‎src/agents/mcp-http-fetch.ts‎

Lines changed: 2 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,6 @@ const fetchWithUndiciGuard = async (
2626
): Promise<Response> => await fetchWithUndici(input instanceof Request ? input.url : input, init);
2727

2828
const MCP_HTTP_MAX_REDIRECTS = 20;
29-
const MCP_HTTP_MAX_TEXT_RESPONSE_BYTES = 1024 * 1024;
3029

3130
function resolveFetchRequest(input: RequestInfo | URL, init?: RequestInit) {
3231
if (input instanceof Request) {
@@ -62,34 +61,11 @@ async function ensureGlobalFetchResponse(response: Response): Promise<Response>
6261
if (response.status === 204 || response.status === 205 || response.status === 304) {
6362
return new Response(null, init);
6463
}
65-
if (typeof response.text === "function") {
66-
const contentLengthBytes = parseSafeContentLength(response.headers.get("content-length"));
67-
if (contentLengthBytes === null || contentLengthBytes > MCP_HTTP_MAX_TEXT_RESPONSE_BYTES) {
68-
return new Response(null, init);
69-
}
70-
// Bodyless foreign responses only expose text(); trust Content-Length to avoid
71-
// no-size reads, then verify the returned UTF-8 size before preserving it.
72-
const text = await response.text();
73-
if (Buffer.byteLength(text, "utf8") > MCP_HTTP_MAX_TEXT_RESPONSE_BYTES) {
74-
return new Response(null, init);
75-
}
76-
return new Response(text, init);
77-
}
64+
// A body-less foreign Response exposes no bounded reader. Calling text() or
65+
// arrayBuffer() can allocate an attacker-controlled body before any cap applies.
7866
return new Response(null, init);
7967
}
8068

81-
function parseSafeContentLength(value: string | null): number | null {
82-
if (!value) {
83-
return null;
84-
}
85-
const trimmed = value.trim();
86-
if (!/^\d+$/.test(trimmed)) {
87-
return null;
88-
}
89-
const size = Number(trimmed);
90-
return Number.isSafeInteger(size) && size >= 0 ? size : null;
91-
}
92-
9369
async function buildManagedMcpResponse(
9470
response: Response,
9571
release: () => Promise<void>,

0 commit comments

Comments
 (0)