@devries-cameron20 / composio Mirror · read-only / commits / ecd086174
Fork 0

Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

Mirrored from https://github.com/Camo67/composio.git

Synced Nov 21, 16:00 UTC

fix(core): release unread response bodies (#4078)

This PR: - follows [Undici's recommendation](https://github.com/nodejs/undici#garbage-collection) to consume or cancel unread response bodies instead of leaving connection-resource cleanup to the garbage collector, which can increase connection pressure and reduce reuse - cancels every intermediate redirect body in `ssrfSafeFetch` before validating and following the next hop - cancels non-success response bodies in both URL-upload callers before preserving their existing errors - adds regression coverage for redirect ordering, redirect-budget exhaustion, and both caller error paths - adds a patch changeset for `@composio/core` - supersedes https://github.com/ComposioHQ/composio/pull/4018 and credits @pacocartones as co-author ## Verification - `pnpm --filter @composio/core test ssrfGuard fileUtils ToolRouterSessionFilesMount` (4 files, 58 tests passed) - `pnpm --filter @composio/core test` (47 files, 1,049 tests passed) - `pnpm --filter @composio/core typecheck` - `pnpm lint:packages` (0 errors; existing warnings only) - Prettier check on all touched files - `pnpm validate:changesets` Co-authored-by: pacocartones <pacocartones@users.noreply.github.com>

Alberto Schiabel committed Aug 6, 2026 at 17:52 UTC ecd0861741e2a385e991e0d57ad4a938480e98ba
7 files changed +84 -4
.changeset/release-ssrf-redirect-bodies.md new
+5
@@ -0,0 +1,5 @@
1 +---
2 +'@composio/core': patch
3 +---
4 +
5 +Release unread response bodies on the paths the SDK knowingly abandons: cancel every intermediate redirect body in `ssrfSafeFetch`, and the response body before throwing on `!response.ok` in both URL-upload call sites, instead of leaving them for the garbage collector to reclaim.
ts/packages/core/src/models/ToolRouterSessionFileMount.ts
+3
@@ -114,6 +114,9 @@ export class ToolRouterSessionFilesMount {
114 if (input.startsWith('http://') || input.startsWith('https://')) {
115 const response = await ssrfSafeFetch(input);
116 if (!response.ok) {
117 + // The error path never reads the body, so release it explicitly (mirrors
118 + // `readResponseBodyWithLimit`) instead of leaving it to the garbage collector.
119 + await response.body?.cancel().catch(() => undefined);
120 throw new Error(`Failed to fetch file from URL: ${response.statusText}`);
121 }
122 const content = await readResponseBodyWithLimit(response);
ts/packages/core/src/utils/fileUtils.node.ts
+3
@@ -176,6 +176,9 @@ const readFileContentFromURL = async (
176 // redirect into them. See ssrfGuard.node.ts.
177 const response = await ssrfSafeFetch(path, { signal });
178 if (!response.ok) {
179 + // The error path never reads the body, so release it explicitly (mirrors
180 + // `readResponseBodyWithLimit`) instead of leaving it to the garbage collector.
181 + await response.body?.cancel().catch(() => undefined);
182 throw new Error(`Failed to fetch file: ${response.statusText}`);
183 }
184 const content = await readResponseBodyWithLimit(response);
ts/packages/core/src/utils/ssrfGuard.node.ts
+6 -2
@@ -171,8 +171,8 @@ export const assertSafeFetchTarget = async (rawUrl: string): Promise<void> => {
171 /**
172 * Drop-in replacement for `fetch` that blocks SSRF. Validates the target before
173 * connecting and re-validates every redirect hop (redirects are followed
174 - * manually up to {@link MAX_REDIRECTS}). Non-redirect responses are returned
175 - * unchanged.
174 + * manually up to {@link MAX_REDIRECTS}). Intermediate redirect bodies are
175 + * cancelled; non-redirect responses are returned unchanged.
176 */
177 export const ssrfSafeFetch = async (
178 rawUrl: string,
@@ -192,6 +192,10 @@ export const ssrfSafeFetch = async (
192 return response;
193 }
194
195 + // Only `location` is read from a redirect, so release its body explicitly rather
196 + // than leaving it to the garbage collector (mirrors `readResponseBodyWithLimit`).
197 + await response.body?.cancel().catch(() => undefined);
198 +
199 currentUrl = new URL(response.headers.get('location')!, currentUrl).toString();
200 }
201
ts/packages/core/test/models/ToolRouterSessionFilesMount.test.ts
+18
@@ -265,6 +265,24 @@ describe('ToolRouterSessionFilesMount', () => {
265 expect(mockClient.toolRouter.session.files.createUploadURL).not.toHaveBeenCalled();
266 });
267
268 + it('should release a failed URL response body before throwing', async () => {
269 + mockLookup.mockResolvedValue([{ address: '93.184.216.34', family: 4 }] as never);
270 + const cancel = vi.fn();
271 + const response = new Response(new ReadableStream({ cancel }), {
272 + status: 500,
273 + statusText: 'Internal Server Error',
274 + });
275 + vi.mocked(fetch).mockResolvedValueOnce(response);
276 +
277 + await expect(filesMount.upload('https://files.example/failed.txt')).rejects.toThrow(
278 + 'Failed to fetch file from URL: Internal Server Error'
279 + );
280 +
281 + expect(cancel).toHaveBeenCalledOnce();
282 + expect(response.bodyUsed).toBe(true);
283 + expect(mockClient.toolRouter.session.files.createUploadURL).not.toHaveBeenCalled();
284 + });
285 +
286 it('should fetch and upload a public URL through the SSRF-safe path', async () => {
287 mockLookup.mockResolvedValue([{ address: '93.184.216.34', family: 4 }] as never);
288 vi.mocked(fetch)
ts/packages/core/test/utils/fileUtils.test.ts
+7 -2
@@ -462,10 +462,12 @@ describe('fileUtils', () => {
462 });
463
464 it('should handle fetch errors for URLs', async () => {
465 - mockFetch.mockResolvedValue({
466 - ok: false,
465 + const cancel = vi.fn();
466 + const response = new Response(new ReadableStream({ cancel }), {
467 + status: 500,
468 statusText: 'Internal Server Error',
469 });
470 + mockFetch.mockResolvedValue(response);
471
472 await expect(
473 getFileDataAfterUploadingToS3('https://example.com/file.pdf', {
@@ -474,6 +476,9 @@ describe('fileUtils', () => {
476 client: mockClient,
477 })
478 ).rejects.toThrow('Failed to fetch file: Internal Server Error');
479 +
480 + expect(cancel).toHaveBeenCalledOnce();
481 + expect(response.bodyUsed).toBe(true);
482 });
483
484 it('should handle S3 upload errors', async () => {
ts/packages/core/test/utils/ssrfGuard.test.ts
+42
@@ -162,4 +162,46 @@ describe('ssrfSafeFetch', () => {
162 ComposioBlockedInternalUrlError
163 );
164 });
165 +
166 + it('releases the redirect body before following the hop', async () => {
167 + resolvesTo('93.184.216.34');
168 + const fetchCallsWhenReleased: number[] = [];
169 + const cancel = vi.fn(() => {
170 + fetchCallsWhenReleased.push(mockFetch.mock.calls.length);
171 + });
172 + const redirect = new Response(new ReadableStream({ cancel }), {
173 + status: 302,
174 + headers: { location: 'https://example.com/final' },
175 + });
176 + mockFetch
177 + .mockResolvedValueOnce(redirect)
178 + .mockResolvedValueOnce(new Response('data', { status: 200 }));
179 +
180 + const res = await ssrfSafeFetch('https://example.com/start');
181 +
182 + expect(res.status).toBe(200);
183 + expect(cancel).toHaveBeenCalledOnce();
184 + expect(redirect.bodyUsed).toBe(true);
185 + // Released while following the first hop, not left dangling for the rest of the call.
186 + expect(fetchCallsWhenReleased).toEqual([1]);
187 + });
188 +
189 + it('releases every hop body when the redirect budget is exhausted', async () => {
190 + resolvesTo('93.184.216.34');
191 + const cancel = vi.fn();
192 + // A fresh body per hop: cancelling the same stream twice is a no-op the second time.
193 + mockFetch.mockImplementation(
194 + async () =>
195 + new Response(new ReadableStream({ cancel }), {
196 + status: 302,
197 + headers: { location: 'https://example.com/again' },
198 + })
199 + );
200 +
201 + await expect(ssrfSafeFetch('https://example.com/start', {}, 2)).rejects.toBeInstanceOf(
202 + ComposioBlockedInternalUrlError
203 + );
204 + // maxRedirects = 2 => hops 0, 1, 2 are fetched before the budget throws.
205 + expect(cancel).toHaveBeenCalledTimes(3);
206 + });
207 });