Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

πŸ› fix(ssrf-safe-fetch): stream response bodies instead of buffering them (#21701)

Bryan8db8038774fc
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/evalToolForwarding.test.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/evalToolForwarding.test.ts
index 0d81c7128ef..c2ae56eb352 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/evalToolForwarding.test.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/evalToolForwarding.test.ts
@@ -229,6 +229,25 @@ describe('AgentRuntimeService', () => {
});
});
+ it('releases the unread body of a non-2xx forwarding response', async () => {
+ const cancel = vi.fn();
+ mockSsrfSafeFetch.mockResolvedValue(
+ new Response(new ReadableStream({ cancel, pull: () => new Promise(() => {}) }), {
+ status: 503,
+ }),
+ );
+ const hook = createEvalToolForwardingHook({
+ twitter: { endpoint: 'https://mock.test/tool-calls' },
+ });
+
+ await hook.handler!(event as any);
+
+ expect(event.mock).toHaveBeenCalledWith(
+ expect.objectContaining({ content: expect.stringContaining('HTTP 503'), success: false }),
+ );
+ expect(cancel).toHaveBeenCalled();
+ });
+
it('mocks transport failures', async () => {
mockSsrfSafeFetch.mockRejectedValue('SSRF blocked');
const hook = createEvalToolForwardingHook({
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/evalToolForwardingHook.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/evalToolForwardingHook.ts
index 67bf4445d73..264966c8301 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/evalToolForwardingHook.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/evalToolForwardingHook.ts
@@ -41,7 +41,11 @@ export const createEvalToolForwardingHook = (
method: 'POST',
signal: controller.signal,
});
- if (!response.ok) throw `Tool forwarding server responded with HTTP ${response.status}`;
+ if (!response.ok) {
+ // The error body is never read; release its connection now rather than at GC.
+ await response.body?.cancel().catch(() => {});
+ throw `Tool forwarding server responded with HTTP ${response.status}`;
+ }
const body: unknown = await response.json();
if (!isRecord(body)) throw new Error('Invalid tool forwarding response');
diff --git a/apps/server/src/services/generation/index.test.ts b/apps/server/src/services/generation/index.test.ts
index fdce1c6de0d..d26acaefa21 100644
--- a/apps/server/src/services/generation/index.test.ts
+++ b/apps/server/src/services/generation/index.test.ts
@@ -258,6 +258,22 @@ describe('GenerationService', () => {
expect(mockSsrfSafeFetch).toHaveBeenCalledTimes(2);
});
+ it('should retry a connection reset while reading the streamed body', async () => {
+ const reset = new Error('Fetch failed: aborted');
+ mockSsrfSafeFetch
+ .mockResolvedValueOnce({
+ ...okResponse(),
+ arrayBuffer: vi.fn().mockRejectedValue(reset),
+ })
+ .mockResolvedValueOnce(okResponse());
+
+ const promise = fetchImageFromUrl('https://example.com/image.jpg');
+ await vi.runAllTimersAsync();
+
+ await expect(promise).resolves.toMatchObject({ mimeType: 'image/jpeg' });
+ expect(mockSsrfSafeFetch).toHaveBeenCalledTimes(2);
+ });
+
it('should retry 5xx responses', async () => {
mockSsrfSafeFetch
.mockResolvedValueOnce({ ok: false, status: 503, statusText: 'Service Unavailable' })
diff --git a/apps/server/src/services/generation/index.ts b/apps/server/src/services/generation/index.ts
index 9927baf9e08..15df5b46c8c 100644
--- a/apps/server/src/services/generation/index.ts
+++ b/apps/server/src/services/generation/index.ts
@@ -58,16 +58,7 @@ export async function fetchImageFromUrl(
// are read and returned, other responses leak status/statusText for blind probing.
// ssrfSafeFetch blocks private/link-local IPs at connect time and on every redirect hop.
// See GHSA-53h9-fmjf-frwr / #16536.
- const response = await fetchWithRetry(url, fetchHeaders);
- if (!response.ok) {
- throw new Error(
- `Failed to fetch image from ${url}: ${response.status} ${response.statusText}`,
- );
- }
- const arrayBuffer = await response.arrayBuffer();
- const buffer = Buffer.from(arrayBuffer);
- const mimeType = response.headers.get('content-type') || 'application/octet-stream';
- return { buffer, mimeType };
+ return downloadWithRetry(url, fetchHeaders);
}
}
@@ -84,18 +75,23 @@ const isRetryableStatus = (status: number) => status === 408 || status === 429 |
* Download through ssrfSafeFetch, retrying transient failures: thrown network/body-read
* errors and 408/429/5xx responses. SSRF blocks and other 4xx responses are final.
*/
-const fetchWithRetry = async (
+const downloadWithRetry = async (
url: string,
fetchHeaders?: Record<string, string>,
-): Promise<Response> => {
+): Promise<{ buffer: Buffer; mimeType: string }> => {
for (let attempt = 0; ; attempt++) {
const canRetry = attempt < IMAGE_DOWNLOAD_RETRY_DELAYS_MS.length;
+ let response: Response;
try {
- const response = await ssrfSafeFetch(url, { headers: fetchHeaders });
- if (!canRetry || !isRetryableStatus(response.status)) return response;
-
- log('Image download returned %d, retrying (attempt %d)', response.status, attempt + 1);
+ response = await ssrfSafeFetch(url, { headers: fetchHeaders });
+ // ssrfSafeFetch resolves at the headers, so a reset while downloading the body
+ // surfaces here and must stay inside the retry.
+ if (response.ok) {
+ const buffer = Buffer.from(await response.arrayBuffer());
+ const mimeType = response.headers.get('content-type') || 'application/octet-stream';
+ return { buffer, mimeType };
+ }
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
if (message.startsWith('SSRF blocked')) throw error;
@@ -110,8 +106,19 @@ const fetchWithRetry = async (
}
log('Image download failed, retrying (attempt %d): %s', attempt + 1, message);
+ await new Promise((resolve) => setTimeout(resolve, IMAGE_DOWNLOAD_RETRY_DELAYS_MS[attempt]));
+ continue;
+ }
+
+ // The error body is never read; release its connection.
+ await response.body?.cancel().catch(() => {});
+ if (!canRetry || !isRetryableStatus(response.status)) {
+ throw new Error(
+ `Failed to fetch image from ${url}: ${response.status} ${response.statusText}`,
+ );
}
+ log('Image download returned %d, retrying (attempt %d)', response.status, attempt + 1);
await new Promise((resolve) => setTimeout(resolve, IMAGE_DOWNLOAD_RETRY_DELAYS_MS[attempt]));
}
};
diff --git a/apps/server/src/services/skill/importer.ts b/apps/server/src/services/skill/importer.ts
index 6944ee7226b..8cd2cdf8793 100644
--- a/apps/server/src/services/skill/importer.ts
+++ b/apps/server/src/services/skill/importer.ts
@@ -340,25 +340,23 @@ export class SkillImporter {
let resources: Map<string, Buffer> | undefined;
let zipBuffer: Buffer | undefined;
+ // Create abort controller for timeout. It stays armed until the body has been read:
+ // ssrfSafeFetch resolves at the headers and streams the body under the same signal.
+ const controller = new AbortController();
+ const timeoutId = setTimeout(() => controller.abort(), 30000); // 30 seconds timeout
+
try {
log('importFromUrl: fetching URL...');
- // Create abort controller for timeout
- const controller = new AbortController();
- const timeoutId = setTimeout(() => controller.abort(), 30000); // 30 seconds timeout
-
- let response: Response;
- try {
- // Use ssrfSafeFetch (not raw global fetch): input.url is fully user-controlled,
- // so a raw fetch would let an authenticated user make the server request arbitrary
- // internal hosts / cloud metadata (SSRF), and the body is stored and returned to the
- // caller β€” a full-read SSRF. ssrfSafeFetch blocks private/link-local IPs at connect
- // time and re-checks every redirect hop. See GHSA-53h9-fmjf-frwr / #16536.
- response = await ssrfSafeFetch(input.url, { signal: controller.signal });
- } finally {
- clearTimeout(timeoutId);
- }
+ // Use ssrfSafeFetch (not raw global fetch): input.url is fully user-controlled,
+ // so a raw fetch would let an authenticated user make the server request arbitrary
+ // internal hosts / cloud metadata (SSRF), and the body is stored and returned to the
+ // caller β€” a full-read SSRF. ssrfSafeFetch blocks private/link-local IPs at connect
+ // time and re-checks every redirect hop. See GHSA-53h9-fmjf-frwr / #16536.
+ const response = await ssrfSafeFetch(input.url, { signal: controller.signal });
if (!response.ok) {
+ // The error body is never read; release its connection now rather than at GC.
+ await response.body?.cancel().catch(() => {});
if (response.status === 404) {
throw new SkillImportError(`Resource not found at ${input.url}`, 'NOT_FOUND');
}
@@ -408,6 +406,8 @@ export class SkillImporter {
`Failed to process URL: ${(error as Error).message}`,
'DOWNLOAD_FAILED',
);
+ } finally {
+ clearTimeout(timeoutId);
}
log('importFromUrl: parsed manifest=%o', manifest);
diff --git a/apps/server/src/services/skill/importer.urlDownload.test.ts b/apps/server/src/services/skill/importer.urlDownload.test.ts
new file mode 100644
index 00000000000..2c46e82d070
--- /dev/null
+++ b/apps/server/src/services/skill/importer.urlDownload.test.ts
@@ -0,0 +1,85 @@
+// @vitest-environment node
+import type { LobeChatDatabase } from '@lobechat/database';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { SkillImporter } from './importer';
+
+const mocks = vi.hoisted(() => ({
+ parseSkillMd: vi.fn(),
+ ssrfSafeFetch: vi.fn(),
+}));
+vi.mock('@/database/models/agentSkill', () => ({ AgentSkillModel: class {} }));
+vi.mock('@/server/modules/GitHub', () => ({
+ GitHub: class {},
+ GitHubNotFoundError: class extends Error {},
+ GitHubParseError: class extends Error {},
+}));
+vi.mock('@/server/services/file', () => ({ FileService: class {} }));
+vi.mock('./resource', () => ({ SkillResourceService: class {} }));
+vi.mock('./parser', () => ({
+ SkillParser: class {
+ parseSkillMd = mocks.parseSkillMd;
+ },
+}));
+vi.mock('@lobechat/ssrf-safe-fetch', () => ({ ssrfSafeFetch: mocks.ssrfSafeFetch }));
+
+const url = 'https://example.com/skills/slow/SKILL.md';
+const importer = () => new SkillImporter({} as LobeChatDatabase, 'owner', 'scope');
+
+/**
+ * Like ssrfSafeFetch: resolves at the headers and streams a body that only the caller's
+ * signal can end. This one never finishes on its own.
+ */
+const respondWithStalledBody = (_url: string, init: RequestInit) =>
+ new Response(
+ new ReadableStream<Uint8Array>({
+ start(controller) {
+ controller.enqueue(new TextEncoder().encode('---\nname: Slow\n'));
+ init.signal!.addEventListener('abort', () =>
+ controller.error(new Error('Fetch failed: The operation was aborted.')),
+ );
+ },
+ }),
+ { headers: { 'content-type': 'text/markdown' } },
+ );
+
+describe('SkillImporter URL download', () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ mocks.ssrfSafeFetch.mockImplementation(respondWithStalledBody);
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ vi.resetAllMocks();
+ });
+
+ it('applies the 30s download timeout to the body, not just the headers', async () => {
+ const outcome = importer()
+ .importFromUrl({ url })
+ .then(
+ () => 'resolved',
+ (error) => error,
+ );
+
+ await vi.advanceTimersByTimeAsync(30_000);
+
+ await expect(Promise.race([outcome, Promise.resolve('still pending')])).resolves.toMatchObject({
+ code: 'DOWNLOAD_FAILED',
+ message: expect.stringContaining('aborted'),
+ });
+ expect(mocks.parseSkillMd).not.toHaveBeenCalled();
+ });
+
+ it.each([404, 500])('releases the unread body of a %d response', async (status) => {
+ const cancel = vi.fn();
+ mocks.ssrfSafeFetch.mockResolvedValue(
+ new Response(new ReadableStream({ cancel, pull: () => new Promise(() => {}) }), { status }),
+ );
+
+ await expect(importer().importFromUrl({ url })).rejects.toMatchObject({
+ code: status === 404 ? 'NOT_FOUND' : 'DOWNLOAD_FAILED',
+ });
+ expect(cancel).toHaveBeenCalled();
+ });
+});
diff --git a/packages/model-runtime/src/providers/replicate/index.test.ts b/packages/model-runtime/src/providers/replicate/index.test.ts
new file mode 100644
index 00000000000..d996e4d4140
--- /dev/null
+++ b/packages/model-runtime/src/providers/replicate/index.test.ts
@@ -0,0 +1,29 @@
+// @vitest-environment node
+import { describe, expect, it, vi } from 'vitest';
+
+import { LobeReplicateAI } from './index';
+
+const { mockSsrfSafeFetch } = vi.hoisted(() => ({ mockSsrfSafeFetch: vi.fn() }));
+vi.mock('@lobechat/ssrf-safe-fetch', () => ({ ssrfSafeFetch: mockSsrfSafeFetch }));
+
+describe('LobeReplicateAI createImage', () => {
+ it('releases the unread body when a local reference image fails to download', async () => {
+ const cancel = vi.fn();
+ mockSsrfSafeFetch.mockResolvedValue(
+ new Response(new ReadableStream({ cancel, pull: () => new Promise(() => {}) }), {
+ status: 502,
+ }),
+ );
+ const runtime = new LobeReplicateAI({ apiKey: 'test-key' });
+
+ await expect(
+ runtime.createImage({
+ model: 'black-forest-labs/flux-kontext-pro',
+ params: { imageUrl: 'http://127.0.0.1:3010/f/image.png', prompt: 'a cat' },
+ } as any),
+ ).rejects.toThrow();
+
+ expect(mockSsrfSafeFetch).toHaveBeenCalledWith('http://127.0.0.1:3010/f/image.png');
+ expect(cancel).toHaveBeenCalled();
+ });
+});
diff --git a/packages/model-runtime/src/providers/replicate/index.ts b/packages/model-runtime/src/providers/replicate/index.ts
index 98927de7803..17d42961e3a 100644
--- a/packages/model-runtime/src/providers/replicate/index.ts
+++ b/packages/model-runtime/src/providers/replicate/index.ts
@@ -164,6 +164,8 @@ export class LobeReplicateAI implements LobeRuntimeAI {
const { ssrfSafeFetch } = await import('@lobechat/ssrf-safe-fetch');
const imageResponse = await ssrfSafeFetch(imageUrl);
if (!imageResponse.ok) {
+ // The error body is never read; release its connection now rather than at GC.
+ await imageResponse.body?.cancel().catch(() => {});
throw new Error(
`Failed to fetch image: ${imageResponse.status} ${imageResponse.statusText}`,
);
diff --git a/packages/model-runtime/src/utils/imageToBase64.ts b/packages/model-runtime/src/utils/imageToBase64.ts
index 87a0654348e..12d11702b6f 100644
--- a/packages/model-runtime/src/utils/imageToBase64.ts
+++ b/packages/model-runtime/src/utils/imageToBase64.ts
@@ -63,8 +63,8 @@ export const imageUrlToBase64 = async (
// Use SSRF-safe fetch on server-side to prevent SSRF attacks
const init = options.signal ? { signal: options.signal } : undefined;
- // ssrfSafeFetch buffers the whole body before returning, so the cap must be applied
- // there. It truncates silently, so read one extra byte for readBlobWithLimit to reject.
+ // Also cap the stream inside ssrfSafeFetch. It truncates silently, so allow one extra
+ // byte for readBlobWithLimit to detect the overflow and reject.
const res = isServer
? await import('@lobechat/ssrf-safe-fetch').then((m) =>
m.ssrfSafeFetch(
diff --git a/packages/ssrf-safe-fetch/index.network.test.ts b/packages/ssrf-safe-fetch/index.network.test.ts
new file mode 100644
index 00000000000..41a43573289
--- /dev/null
+++ b/packages/ssrf-safe-fetch/index.network.test.ts
@@ -0,0 +1,209 @@
+import type { Server, ServerResponse } from 'node:http';
+import { createServer } from 'node:http';
+import { setFlagsFromString } from 'node:v8';
+import { runInNewContext } from 'node:vm';
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { ssrfSafeFetch } from './index';
+
+const allowPrivate = { allowPrivateIPAddress: true };
+
+const within = <T>(promise: Promise<T>, ms: number, label: string) =>
+ Promise.race([
+ promise,
+ new Promise<never>((_, reject) => {
+ setTimeout(() => reject(new Error(`${label} did not happen within ${ms}ms`)), ms);
+ }),
+ ]);
+
+setFlagsFromString('--expose-gc');
+const gc = runInNewContext('gc') as () => void;
+
+/** Collects garbage every 100 ms until `settled` resolves or `ms` elapses. */
+const collectUntil = async (settled: Promise<unknown>, ms: number) => {
+ let done = false;
+ void settled.then(() => (done = true));
+ for (let waited = 0; !done && waited < ms; waited += 100) {
+ gc();
+ await new Promise((resolve) => setTimeout(resolve, 100));
+ }
+ return done;
+};
+
+/** Writes 16 KB chunks until the client goes away; the response never ends on its own. */
+const writeForever = (res: ServerResponse) => {
+ const chunk = 'x'.repeat(16 * 1024);
+ const pump = () => {
+ while (!res.destroyed && res.write(chunk));
+ if (!res.destroyed) res.once('drain', pump);
+ };
+ pump();
+};
+
+/** Real socket tests: no fetch mocks. */
+describe('ssrfSafeFetch network boundary', () => {
+ let server: Server;
+ let base: string;
+ let requests: string[];
+ let socketClosed: Map<string, Promise<void>>;
+
+ beforeEach(async () => {
+ requests = [];
+ socketClosed = new Map();
+ server = createServer((req, res) => {
+ const path = req.url!;
+ requests.push(path);
+ socketClosed.set(path, new Promise((resolve) => req.socket.once('close', () => resolve())));
+
+ if (path === '/sse') {
+ res.writeHead(200, { 'Cache-Control': 'no-cache', 'Content-Type': 'text/event-stream' });
+ res.write('data: hello\n\n');
+ } else if (path === '/endless') {
+ res.writeHead(200, { 'Content-Type': 'text/plain' });
+ writeForever(res);
+ } else if (path === '/endless-error') {
+ res.writeHead(500, { 'Content-Type': 'text/plain' });
+ writeForever(res);
+ } else if (path === '/sse-ticking') {
+ res.writeHead(200, { 'Content-Type': 'text/event-stream' });
+ let id = 0;
+ const timer = setInterval(() => res.write(`data: ${id++}\n\n`), 50);
+ res.once('close', () => clearInterval(timer));
+ } else if (path === '/json') {
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ ok: true }));
+ } else if (path === '/redirect-private') {
+ res.writeHead(302, { Location: 'http://169.254.169.254/latest/meta-data/' });
+ res.end();
+ } else if (path === '/reset') {
+ res.writeHead(200, { 'Content-Length': '1000', 'Content-Type': 'text/plain' });
+ res.write('partial');
+ setTimeout(() => req.socket.destroy(), 20);
+ } else {
+ res.writeHead(204);
+ res.end();
+ }
+ });
+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
+ const address = server.address();
+ if (!address || typeof address === 'string') throw new Error('Missing test server address');
+ base = `http://127.0.0.1:${address.port}`;
+ vi.stubEnv('SSRF_ALLOW_PRIVATE_IP_ADDRESS', undefined);
+ vi.stubEnv('SSRF_ALLOW_IP_ADDRESS_LIST', undefined);
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ });
+
+ afterEach(async () => {
+ server.closeAllConnections();
+ await new Promise<void>((resolve, reject) =>
+ server.close((error) => (error ? reject(error) : resolve())),
+ );
+ vi.unstubAllEnvs();
+ vi.restoreAllMocks();
+ });
+
+ it('resolves at the headers of a never-ending SSE response and releases it on cancel', async () => {
+ const response = await within(
+ ssrfSafeFetch(`${base}/sse`, undefined, allowPrivate),
+ 2000,
+ 'ssrfSafeFetch resolving',
+ );
+
+ expect(response.status).toBe(200);
+ expect(response.headers.get('content-type')).toBe('text/event-stream');
+
+ const reader = response.body!.getReader();
+ const { value } = await reader.read();
+ expect(new TextDecoder().decode(value)).toBe('data: hello\n\n');
+
+ await reader.cancel();
+ await within(socketClosed.get('/sse')!, 2000, 'upstream socket close');
+ });
+
+ it('soft-truncates at maxContentLength and closes the upstream connection', async () => {
+ const response = await ssrfSafeFetch(`${base}/endless`, undefined, {
+ ...allowPrivate,
+ maxContentLength: 100_000,
+ });
+
+ const text = await within(response.text(), 2000, 'reading the capped body');
+
+ expect(text).toBe('x'.repeat(100_000));
+ await within(socketClosed.get('/endless')!, 2000, 'upstream socket close');
+ });
+
+ it('releases the upstream connection of a response dropped without reading its body', async () => {
+ // Same shape as a caller giving up on a non-2xx status: the Response goes out of scope.
+ const status = await ssrfSafeFetch(`${base}/endless-error`, undefined, allowPrivate).then(
+ (response) => response.status,
+ );
+ expect(status).toBe(500);
+
+ await expect(collectUntil(socketClosed.get('/endless-error')!, 3000)).resolves.toBe(true);
+ });
+
+ it('keeps a stream that is being read alive when its Response is collected', async () => {
+ // A long-lived SSE consumer that keeps only its reader, not the Response.
+ const reader = await ssrfSafeFetch(`${base}/sse-ticking`, undefined, allowPrivate).then(
+ (response) => response.body!.getReader(),
+ );
+ await reader.read();
+
+ const closedDuringGc = await collectUntil(socketClosed.get('/sse-ticking')!, 1000);
+ const { done, value } = await reader.read();
+
+ expect(closedDuringGc).toBe(false);
+ expect(done).toBe(false);
+ expect(new TextDecoder().decode(value)).toMatch(/^data: \d+/);
+ await reader.cancel();
+ });
+
+ it('still reads complete bodies through .json()', async () => {
+ const response = await ssrfSafeFetch(`${base}/json`, undefined, allowPrivate);
+
+ expect(await response.json()).toEqual({ ok: true });
+ });
+
+ it('returns a null body for null-body statuses', async () => {
+ const response = await ssrfSafeFetch(`${base}/no-content`, undefined, allowPrivate);
+
+ expect(response.status).toBe(204);
+ expect(response.body).toBeNull();
+ });
+
+ it('surfaces a connection reset during the body read to the body reader', async () => {
+ const response = await ssrfSafeFetch(`${base}/reset`, undefined, allowPrivate);
+
+ await expect(response.text()).rejects.toThrow(/Fetch failed/);
+ });
+
+ it('lets the caller signal abort the body read after headers arrive', async () => {
+ const controller = new AbortController();
+ const response = await ssrfSafeFetch(
+ `${base}/sse`,
+ { signal: controller.signal },
+ allowPrivate,
+ );
+ const reader = response.body!.getReader();
+ await reader.read();
+
+ const pending = reader.read();
+ controller.abort();
+
+ await expect(pending).rejects.toThrow(/Fetch failed: .*abort/i);
+ await within(socketClosed.get('/sse')!, 2000, 'upstream socket close');
+ });
+
+ it('blocks private addresses by default before any request is sent', async () => {
+ await expect(ssrfSafeFetch(`${base}/sse`)).rejects.toThrow(/^SSRF blocked: /);
+ expect(requests).toEqual([]);
+ });
+
+ it('blocks a redirect from an allowed host to a private address', async () => {
+ await expect(
+ ssrfSafeFetch(`${base}/redirect-private`, undefined, { allowIPAddressList: ['127.0.0.1'] }),
+ ).rejects.toThrow(/^SSRF blocked: .*169\.254\.169\.254/);
+ expect(requests).toEqual(['/redirect-private']);
+ });
+});
diff --git a/packages/ssrf-safe-fetch/index.test.ts b/packages/ssrf-safe-fetch/index.test.ts
index 24e42caa768..5fb277f046e 100644
--- a/packages/ssrf-safe-fetch/index.test.ts
+++ b/packages/ssrf-safe-fetch/index.test.ts
@@ -226,18 +226,17 @@ describe('ssrfSafeFetch', () => {
describe('response conversion', () => {
it('should convert node-fetch Response to standard Response', async () => {
- const mockArrayBuffer = new ArrayBuffer(10);
const mockHeaders = new Map([
['content-type', 'application/json'],
['content-length', '10'],
]);
- const mockResponse = createMockResponse({
- arrayBuffer: mockArrayBuffer,
- headers: mockHeaders,
- status: 201,
- statusText: 'Created',
- });
+ const mockResponse = {
+ ...createMockResponse({ headers: mockHeaders, status: 201, statusText: 'Created' }),
+ body: (async function* () {
+ yield Buffer.from('{"ok":true}');
+ })(),
+ };
mockFetch.mockResolvedValue(mockResponse);
@@ -248,7 +247,9 @@ describe('ssrfSafeFetch', () => {
expect(response.statusText).toBe('Created');
expect(response.headers.get('content-type')).toBe('application/json');
expect(response.headers.get('content-length')).toBe('10');
- expect(mockResponse.arrayBuffer).toHaveBeenCalled();
+ // The body streams through instead of being buffered before resolving.
+ expect(mockResponse.arrayBuffer).not.toHaveBeenCalled();
+ expect(await response.json()).toEqual({ ok: true });
});
it('should handle response with different status codes', async () => {
@@ -282,10 +283,9 @@ describe('ssrfSafeFetch', () => {
describe('maxContentLength (response body cap)', () => {
const buildBodyResponse = (chunks: Buffer[]) => ({
- // arrayBuffer should NOT be called when maxContentLength is set;
- // make it throw so the test fails loudly if the cap path falls through.
+ // The body must stream; make arrayBuffer throw so a buffering regression fails loudly.
arrayBuffer: vi.fn().mockImplementation(async () => {
- throw new Error('arrayBuffer should not be called when maxContentLength is set');
+ throw new Error('arrayBuffer should not be called; the body must stream');
}),
body: (async function* () {
for (const chunk of chunks) yield chunk;
@@ -332,16 +332,12 @@ describe('ssrfSafeFetch', () => {
expect(await response.text()).toBe('');
});
- it('falls back to arrayBuffer when maxContentLength is not set', async () => {
- const mockResponse = createMockResponse({
- arrayBuffer: new TextEncoder().encode('legacy path').buffer as ArrayBuffer,
- });
- mockFetch.mockResolvedValue(mockResponse);
+ it('streams the whole body without buffering when maxContentLength is not set', async () => {
+ mockFetch.mockResolvedValue(buildBodyResponse([Buffer.from('no '), Buffer.from('cap')]));
const response = await ssrfSafeFetch('https://example.com');
- expect(mockResponse.arrayBuffer).toHaveBeenCalledTimes(1);
- expect(await response.text()).toBe('legacy path');
+ expect(await response.text()).toBe('no cap');
});
});
diff --git a/packages/ssrf-safe-fetch/index.ts b/packages/ssrf-safe-fetch/index.ts
index c1c02bc9715..d82368377ef 100644
--- a/packages/ssrf-safe-fetch/index.ts
+++ b/packages/ssrf-safe-fetch/index.ts
@@ -11,51 +11,111 @@ export interface SSRFOptions {
/** Whether to allow private/local IP addresses */
allowPrivateIPAddress?: boolean;
/**
- * Maximum response body size in bytes. When set, the body is consumed
- * incrementally and reading stops as soon as the cap is reached. The returned
- * Response contains only the bytes received up to that point (soft truncation β€”
- * still considered a successful response).
+ * Maximum response body size in bytes. When set, the body stream ends as soon as
+ * the cap is reached and the upstream connection is closed. Readers get only the
+ * bytes received up to that point (soft truncation β€” still considered a
+ * successful response).
*
* Use this for any fetch that downloads untrusted content (e.g. web crawlers)
- * to prevent unbounded buffering of large or malicious responses from blowing
- * up serverless function memory.
+ * so a large or malicious response cannot be buffered without bound by
+ * callers that read the whole body.
*/
maxContentLength?: number;
}
+/** Statuses whose Response must have a null body (Fetch standard "null body status"). */
+const NULL_BODY_STATUSES = new Set([101, 103, 204, 205, 304]);
+
+type NodeBody = NodeJS.ReadableStream & { destroy?: (error?: Error) => void };
+
+const toFetchError = (error: unknown): Error => {
+ const errorMessage = error instanceof Error ? error.message : String(error);
+ // request-filtering-agent errors contain "is not allowed" when blocking private/denied IPs
+ const isSSRFBlock = errorMessage.includes('is not allowed');
+
+ if (isSSRFBlock) {
+ console.error('SSRF protection blocked request:', error);
+ return new Error(
+ `SSRF blocked: ${errorMessage}. ` +
+ 'See: https://lobehub.com/docs/self-hosting/environment-variables/basic#ssrf-allow-private-ip-address',
+ { cause: error },
+ );
+ }
+
+ console.error('Fetch error:', error);
+ return new Error(`Fetch failed: ${errorMessage}`, { cause: error });
+};
+
/**
- * Consume a node-fetch Response body up to `cap` bytes, then stop. Breaking out
- * of `for await` closes the async iterator, which destroys the underlying stream
- * and releases the HTTP connection.
+ * Expose a node-fetch body as a Web stream that is pulled only as the consumer reads.
+ * Ending at `cap` bytes, or a consumer cancel, destroys the node stream, which tears down
+ * the HTTP connection.
*/
-const readBodyWithCap = async (
- body: NodeJS.ReadableStream | null,
- cap: number,
-): Promise<Uint8Array> => {
- if (!body) return new Uint8Array(0);
-
- const chunks: Buffer[] = [];
- let total = 0;
-
- for await (const chunk of body as AsyncIterable<Uint8Array>) {
- const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
- const remaining = cap - total;
- if (buf.length >= remaining) {
- chunks.push(buf.subarray(0, remaining));
- total = cap;
- break;
- }
- chunks.push(buf);
- total += buf.length;
- }
+const toWebBody = (body: NodeBody, cap?: number): ReadableStream<Uint8Array> => {
+ const iterator = (body as AsyncIterable<Uint8Array | string>)[Symbol.asyncIterator]();
+ let received = 0;
+ let released = false;
+
+ const release = () => {
+ if (released) return;
+ released = true;
+ // Destroy directly instead of only awaiting `iterator.return()`: that would queue
+ // behind a pending `next()`, which never settles on an idle stream such as SSE.
+ if (typeof body.destroy === 'function') body.destroy();
+ else iterator.return?.().catch(() => {});
+ };
- return Buffer.concat(chunks, total);
+ return new ReadableStream<Uint8Array>({
+ cancel: release,
+ async pull(controller) {
+ let result: IteratorResult<Uint8Array | string>;
+ try {
+ result = await iterator.next();
+ } catch (error) {
+ // A rejection after release is the teardown we caused; nobody is reading anymore.
+ if (!released) controller.error(toFetchError(error));
+ return;
+ }
+
+ if (result.done) {
+ released = true;
+ controller.close();
+ return;
+ }
+
+ const chunk = typeof result.value === 'string' ? Buffer.from(result.value) : result.value;
+ if (cap && cap > 0 && received + chunk.byteLength >= cap) {
+ controller.enqueue(chunk.subarray(0, cap - received));
+ controller.close();
+ release();
+ return;
+ }
+
+ received += chunk.byteLength;
+ controller.enqueue(chunk);
+ },
+ });
};
+/**
+ * Cancels the body of a Response that was garbage-collected before anyone read or cancelled
+ * it, e.g. a caller that gave up on a non-2xx status. Otherwise a large or never-ending body
+ * keeps its upstream connection open for as long as the server does. A locked body is being
+ * read (such as an SSE consumer that kept only its reader), so it is left alone.
+ */
+const abandonedBodies = new FinalizationRegistry<ReadableStream<Uint8Array>>((body) => {
+ if (!body.locked) body.cancel().catch(() => {});
+});
+
/**
* SSRF-safe fetch implementation for server-side use
* Uses request-filtering-agent to prevent requests to private IP addresses
*
+ * Resolves once the response headers arrive; the body streams. Read the body or cancel it
+ * when giving up on a response so its connection is released right away. A dropped
+ * Response is cleaned up on garbage collection as a fallback, so keep the Response (or
+ * lock its body with a reader) for as long as you intend to read.
+ *
* @param url - The URL to fetch
* @param options - Standard fetch options
* @param ssrfOptions - Optional per-call SSRF configuration overrides
@@ -94,35 +154,24 @@ export const ssrfSafeFetch = async (
agent: (parsedURL: URL) => (parsedURL.protocol === 'https:' ? httpsAgent : httpAgent),
} as any);
- const cap = ssrfOptions?.maxContentLength;
- const body: BodyInit =
- cap && cap > 0
- ? // Buffer is a Uint8Array subclass; the Response constructor accepts it at
- // runtime even though the BodyInit lib type doesn't list Uint8Array.
- ((await readBodyWithCap(response.body as NodeJS.ReadableStream | null, cap)) as any)
- : await response.arrayBuffer();
+ const nodeBody = response.body as NodeBody | null;
+ const status = response.status;
+ let body: ReadableStream<Uint8Array> | null = null;
- // Convert node-fetch Response to standard Response
- return new Response(body, {
+ if (nodeBody && NULL_BODY_STATUSES.has(status)) nodeBody.destroy?.();
+ else if (nodeBody) body = toWebBody(nodeBody, ssrfOptions?.maxContentLength);
+
+ // Resolve as soon as headers arrive: the SSRF checks run at connect time and on every
+ // redirect hop, so the body can stream to the caller (e.g. a never-ending SSE response).
+ const webResponse = new Response(body, {
headers: response.headers as any,
- status: response.status,
+ status,
statusText: response.statusText,
});
+ if (webResponse.body) abandonedBodies.register(webResponse, webResponse.body);
+
+ return webResponse;
} catch (error) {
- const errorMessage = error instanceof Error ? error.message : String(error);
- // request-filtering-agent errors contain "is not allowed" when blocking private/denied IPs
- const isSSRFBlock = errorMessage.includes('is not allowed');
-
- if (isSSRFBlock) {
- console.error('SSRF protection blocked request:', error);
- throw new Error(
- `SSRF blocked: ${errorMessage}. ` +
- 'See: https://lobehub.com/docs/self-hosting/environment-variables/basic#ssrf-allow-private-ip-address',
- { cause: error },
- );
- }
-
- console.error('Fetch error:', error);
- throw new Error(`Fetch failed: ${errorMessage}`, { cause: error });
+ throw toFetchError(error);
}
};
diff --git a/packages/web-crawler/src/crawImpl/__tests__/naive.network.test.ts b/packages/web-crawler/src/crawImpl/__tests__/naive.network.test.ts
new file mode 100644
index 00000000000..86f9077a7c2
--- /dev/null
+++ b/packages/web-crawler/src/crawImpl/__tests__/naive.network.test.ts
@@ -0,0 +1,61 @@
+import type { Server } from 'node:http';
+import { createServer } from 'node:http';
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { TimeoutError } from '../../utils/errorType';
+import type * as WithTimeoutModule from '../../utils/withTimeout';
+import { naive } from '../naive';
+
+vi.mock('../../utils/withTimeout', async (importOriginal) => ({
+ ...(await importOriginal<typeof WithTimeoutModule>()),
+ DEFAULT_TIMEOUT: 300,
+}));
+
+const within = <T>(promise: Promise<T>, ms: number, label: string) =>
+ Promise.race([
+ promise,
+ new Promise<never>((_, reject) => {
+ setTimeout(() => reject(new Error(`${label} did not happen within ${ms}ms`)), ms);
+ }),
+ ]);
+
+/** Real socket tests: no fetch mocks. */
+describe('naive crawler network boundary', () => {
+ let server: Server;
+ let base: string;
+ let socketClosed: Promise<void>;
+
+ beforeEach(async () => {
+ server = createServer((req, res) => {
+ socketClosed = new Promise((resolve) => req.socket.once('close', () => resolve()));
+ // Headers arrive at once, then the body drips without ever ending.
+ res.writeHead(200, { 'Content-Type': 'text/html' });
+ res.write('<html><body>');
+ const timer = setInterval(() => res.write('<p>drip</p>'), 50);
+ res.once('close', () => clearInterval(timer));
+ });
+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
+ const address = server.address();
+ if (!address || typeof address === 'string') throw new Error('Missing test server address');
+ base = `http://127.0.0.1:${address.port}`;
+ vi.stubEnv('SSRF_ALLOW_PRIVATE_IP_ADDRESS', '1');
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ });
+
+ afterEach(async () => {
+ server.closeAllConnections();
+ await new Promise<void>((resolve, reject) =>
+ server.close((error) => (error ? reject(error) : resolve())),
+ );
+ vi.unstubAllEnvs();
+ vi.restoreAllMocks();
+ });
+
+ it('times out a body that keeps dripping after the headers arrive', async () => {
+ await expect(
+ within(naive(`${base}/page`, { filterOptions: {} }), 2000, 'the crawl timing out'),
+ ).rejects.toBeInstanceOf(TimeoutError);
+ await within(socketClosed, 2000, 'upstream socket close');
+ });
+});
diff --git a/packages/web-crawler/src/crawImpl/naive.ts b/packages/web-crawler/src/crawImpl/naive.ts
index 1c3a67bebaf..9e1b030c5d5 100755
--- a/packages/web-crawler/src/crawImpl/naive.ts
+++ b/packages/web-crawler/src/crawImpl/naive.ts
@@ -40,18 +40,20 @@ export const naive: CrawlImpl = async (url, { filterOptions }) => {
let res: Response;
try {
- res = await withTimeout(
- (signal) =>
- ssrfSafeFetch(
- url,
- {
- headers: mixinHeaders,
- signal,
- },
- { maxContentLength: MAX_HTML_SIZE },
- ),
- DEFAULT_TIMEOUT,
- );
+ res = await withTimeout(async (signal) => {
+ const streamed = await ssrfSafeFetch(
+ url,
+ {
+ headers: mixinHeaders,
+ signal,
+ },
+ { maxContentLength: MAX_HTML_SIZE },
+ );
+ // ssrfSafeFetch resolves at the headers; buffer the capped body under the same
+ // timeout so a server that keeps dripping bytes cannot stall the crawl.
+ const body = streamed.body ? await streamed.arrayBuffer() : null;
+ return new Response(body, streamed);
+ }, DEFAULT_TIMEOUT);
} catch (e) {
throw toFetchError(e);
}
diff --git a/src/app/(backend)/webapi/models/[provider]/pricing/route.test.ts b/src/app/(backend)/webapi/models/[provider]/pricing/route.test.ts
index 22618cb5191..2ce572d9827 100644
--- a/src/app/(backend)/webapi/models/[provider]/pricing/route.test.ts
+++ b/src/app/(backend)/webapi/models/[provider]/pricing/route.test.ts
@@ -187,6 +187,32 @@ describe('GET /webapi/models/[provider]/pricing', () => {
expect(responseBody.errorType).toBe(ChatErrorType.BadGateway);
});
+ it('should release the unread bodies of non-2xx pricing responses', async () => {
+ const mockParams = Promise.resolve({ provider: 'newapi' });
+ const mockModelInstance = new AiProviderModel({} as any, 'test-user-id');
+ vi.mocked(mockModelInstance.getAiProviderById).mockResolvedValue({
+ keyVaults: {
+ apiKey: 'test-key',
+ baseURL: 'https://newapi.test.com/v1',
+ },
+ } as any);
+
+ const cancelAuthed = vi.fn();
+ const cancelAnonymous = vi.fn();
+ const stalledResponse = (cancel: () => void, status: number) =>
+ new Response(new ReadableStream({ cancel, pull: () => new Promise(() => {}) }), { status });
+ mockSsrfSafeFetch
+ .mockResolvedValueOnce(stalledResponse(cancelAuthed, 401))
+ .mockResolvedValueOnce(stalledResponse(cancelAnonymous, 503));
+
+ const response = await GET(request, { params: mockParams });
+
+ expect(response.status).toBe(502);
+ expect(mockSsrfSafeFetch).toHaveBeenCalledTimes(2);
+ expect(cancelAuthed).toHaveBeenCalled();
+ expect(cancelAnonymous).toHaveBeenCalled();
+ });
+
it('should return InternalServerError if SSRF protection blocks the request', async () => {
const mockParams = Promise.resolve({ provider: 'newapi' });
const mockModelInstance = new AiProviderModel({} as any, 'test-user-id');
diff --git a/src/app/(backend)/webapi/models/[provider]/pricing/route.ts b/src/app/(backend)/webapi/models/[provider]/pricing/route.ts
index 706032e9f3d..f4c3c439b5c 100644
--- a/src/app/(backend)/webapi/models/[provider]/pricing/route.ts
+++ b/src/app/(backend)/webapi/models/[provider]/pricing/route.ts
@@ -73,11 +73,14 @@ export const GET = checkAuth(async (req, { params, userId, serverDB }) => {
res = await fetchWithAuth(false);
}
+ // Error bodies are never read; release their connections now rather than at GC.
if (!res.ok && usedAuth) {
+ await res.body?.cancel().catch(() => {});
res = await fetchWithAuth(false);
}
if (!res.ok) {
+ await res.body?.cancel().catch(() => {});
return createErrorResponse(ChatErrorType.BadGateway, {
message: `Failed to fetch pricing from provider: ${res.statusText}`,
});