@devries-cameron20 / composio Mirror · read-only / commits / a0f37a7f7
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, 18:30 UTC

fix(core): SSRF guard on URL file inputs + telemetry secret redaction (#3779)

## What & why Two v1 non-negotiable gates from the [SDK road to v1](https://github.com/ComposioHQ/composio) plan are currently red. Both are self-contained and closed here. ### ① SSRF guard on URL file inputs — `@composio/core` `composio.files.upload(url)` and automatic file upload during tool execution did a **raw `fetch()`** on user-supplied URLs (`readFileContentFromURL`, `fileUtils.node.ts`) with no guard. Because URL inputs deliberately bypass the local-path allowlist, a caller — or an LLM-produced tool argument — could point the SDK at internal infrastructure (`http://169.254.169.254/…` cloud metadata, RFC1918 hosts) or a public URL that 3xx-redirects into internal space. New `ssrfGuard.node.ts`: - resolves the host and refuses **private, loopback, link-local (incl. `169.254.169.254`), CGNAT, TEST-NET, benchmarking, multicast, and reserved** ranges (IPv4 + IPv6, incl. IPv4-mapped / NAT64); - validates the **resolved address**, not the hostname string, so decimal/octal/hex IP obfuscation doesn't slip through; - rejects non-`http(s)` schemes; - follows redirects **manually** so every hop is re-validated; - blocked requests throw the new `ComposioBlockedInternalUrlError`. Behaviour for legitimate public URLs is unchanged. Node-only path. Known residual (documented in-file): a DNS-rebinding TOCTOU window between our lookup and `fetch`'s connect — closing it fully needs connect-time IP pinning (a custom dispatcher), out of scope here. ### ② Telemetry secret redaction — `@composio/core` Error telemetry shipped `error.message` / `error.stack` **verbatim** to `telemetry.composio.dev` with zero redaction. New `redact.ts` runs at the single chokepoint (`prepareAndSendErrorTelemetry`) and strips URL query strings, `Authorization` bearer/basic credentials, and secret-like `key=value` pairs (API keys, tokens, client secrets, passwords) before transport. ## Tests - `ssrfGuard.test.ts` — IP classification (v4/v6, mapped, CGNAT, metadata), scheme rejection, resolve-to-internal, "any resolved address internal" pinning bypass, redirect-into-internal, redirect budget. - `redact.test.ts` — URL query, bearer/basic, key/value secrets, quote preservation, benign text untouched. - Updated `fileUtils.test.ts` to mock DNS (hermetic) and expect `redirect: 'manual'`. - `tsc --noEmit` clean; lint clean. ## Notes - `patch` changeset included. - Adds `ComposioBlockedInternalUrlError` to the public error exports.

Alberto Schiabel committed Jul 10, 2026 at 19:35 UTC a0f37a7f7728c922e044dfb35c33dad9aae7ae7c
10 files changed +538 -8
.changeset/ssrf-guard-and-telemetry-redaction.md new
+8
@@ -0,0 +1,8 @@
1 +---
2 +'@composio/core': patch
3 +---
4 +
5 +Close two secret/SSRF exposure surfaces in the TypeScript SDK:
6 +
7 +- **SSRF guard on URL file inputs.** `composio.files.upload(url)` and automatic file upload during tool execution previously did a raw `fetch()` on user-supplied URLs with no guard. They now resolve the host and refuse private, loopback, link-local (incl. the `169.254.169.254` cloud-metadata endpoint), CGNAT, and reserved addresses, reject non-`http(s)` schemes, and follow redirects manually so each hop is re-validated (blocking a public URL that redirects into internal space). Blocked requests throw `ComposioBlockedInternalUrlError`. Node-only; behaviour for public URLs is unchanged.
8 +- **Telemetry redaction.** Error telemetry previously shipped `error.message` / `error.stack` verbatim. They are now passed through a redactor that strips URL query strings, `Authorization` bearer/basic credentials, and secret-like `key=value` pairs (API keys, tokens, client secrets, passwords) before transport.
ts/packages/core/src/errors/SsrfErrors.ts new
+47
@@ -0,0 +1,47 @@
1 +import { ComposioError, ComposioErrorOptions } from './ComposioError';
2 +
3 +export const SsrfErrorCodes = {
4 + BLOCKED_INTERNAL_URL: 'BLOCKED_INTERNAL_URL',
5 +} as const;
6 +
7 +export interface ComposioBlockedInternalUrlErrorOptions extends Omit<ComposioErrorOptions, 'code'> {
8 + /** The user-supplied URL that was refused. */
9 + url?: string;
10 + /** The resolved address that tripped the guard, when known. */
11 + resolvedIp?: string;
12 +}
13 +
14 +/**
15 + * Thrown when a URL file input resolves to a private, loopback, link-local, or
16 + * otherwise internal address, or points at a non-http(s) scheme. Guards against
17 + * turning `composio.files.upload(url)` (and automatic upload during tool
18 + * execution) into a server-side request forgery (SSRF) probe of internal
19 + * infrastructure such as cloud metadata endpoints (`169.254.169.254`).
20 + */
21 +export class ComposioBlockedInternalUrlError extends ComposioError {
22 + constructor(
23 + message: string = 'Refusing to fetch an internal or non-public URL',
24 + options: ComposioBlockedInternalUrlErrorOptions = {}
25 + ) {
26 + const { url, resolvedIp, meta: optionsMeta, ...rest } = options;
27 +
28 + const meta: Record<string, unknown> = {
29 + ...optionsMeta,
30 + ...(url && { url }),
31 + ...(resolvedIp && { resolvedIp }),
32 + };
33 +
34 + super(message, {
35 + ...rest,
36 + code: SsrfErrorCodes.BLOCKED_INTERNAL_URL,
37 + meta: Object.keys(meta).length > 0 ? meta : undefined,
38 + possibleFixes: options.possibleFixes ?? [
39 + 'Use a publicly reachable http(s) URL',
40 + 'Do not point file inputs at localhost, link-local, or private-network hosts',
41 + 'If the source is internal, download it yourself and pass a File/Blob instead of a URL',
42 + ],
43 + });
44 +
45 + this.name = 'ComposioBlockedInternalUrlError';
46 + }
47 +}
ts/packages/core/src/errors/index.ts
+3
@@ -39,3 +39,6 @@ export * from './RemoteFileErrors';
39
40 // File modifier / auto upload
41 export * from './FileModifierErrors';
42 +
43 +// SSRF guard (URL file inputs)
44 +export * from './SsrfErrors';
ts/packages/core/src/telemetry/Telemetry.ts
+9 -6
@@ -18,6 +18,7 @@ import {
18 } from '../services/telemetry/TelemetryService.types';
19 import { TelemetryService } from '../services/telemetry/TelemetryService';
20 import logger from '../utils/logger';
21 +import { redactSensitiveText } from './redact';
22 /**
23 * The Telemetry class is used to log the telemetry for any given instance which extends InstrumentedInstance.
24 *
@@ -207,28 +208,30 @@ export class TelemetryTransport {
208 },
209 source: this.telemetrySource,
210 };
211 + // Redact secrets (URLs with tokens, Authorization headers, API keys, etc.)
212 + // from free-form error text before it is transported off-process.
213 // client error, this is likely handled by the API itseld
214 if (error instanceof ComposioClientError) {
215 telemetryPayload.error = {
216 errorId: error.errorId,
217 name: error.name,
215 - message: error.message,
216 - stack: error.stack,
218 + message: redactSensitiveText(error.message),
219 + stack: redactSensitiveText(error.stack),
220 };
221 } else if (error instanceof ComposioError) {
222 telemetryPayload.error = {
223 errorId: error.errorId,
224 name: error.name,
225 code: error.code,
223 - message: error.message,
224 - stack: error.stack,
226 + message: redactSensitiveText(error.message),
227 + stack: redactSensitiveText(error.stack),
228 };
229 } else if (error instanceof Error) {
230 telemetryPayload.error = {
231 errorId: error.errorId,
232 name: error.name ?? 'Unknown error',
230 - message: error.message,
231 - stack: error.stack,
233 + message: redactSensitiveText(error.message),
234 + stack: redactSensitiveText(error.stack),
235 };
236 }
237
ts/packages/core/src/telemetry/redact.ts new
+40
@@ -0,0 +1,40 @@
1 +/**
2 + * Best-effort redaction of secrets from free-form error text before it is sent
3 + * to the telemetry endpoint.
4 + *
5 + * Error `message` and `stack` fields routinely interpolate URLs (with
6 + * query-string tokens / presigned signatures), `Authorization` headers, API
7 + * keys, and connected-account identifiers. None of that should leave the
8 + * process. Structured telemetry fields never carry raw secrets, so only the two
9 + * free-form strings are passed through here.
10 + *
11 + * This is defence-in-depth, not a proof: it targets the shapes we have seen
12 + * leak. When in doubt it over-redacts rather than under-redacts.
13 + */
14 +
15 +const REDACTED = '[REDACTED]';
16 +
17 +const REDACTION_RULES: ReadonlyArray<readonly [RegExp, string]> = [
18 + // URL query strings — tokens, presigned signatures, one-time codes.
19 + [/(\bhttps?:\/\/[^\s?#'"]+)\?[^\s'"]*/gi, `$1?${REDACTED}`],
20 + // Authorization scheme + credential: `Bearer <token>`, `Basic <token>`.
21 + [/\b(bearer|basic)\s+[A-Za-z0-9._~+/=-]+/gi, `$1 ${REDACTED}`],
22 + // Secret-ish `key: value` / `key=value` / `key: "value"` / `key: 'value'` pairs.
23 + [
24 + /\b(authorization|api[-_]?key|apikey|x-api-key|access[-_]?token|refresh[-_]?token|client[-_]?secret|secret|password|passwd|pwd)\b(\s*[:=]+\s*)(["']?)([^\s"',}&]+)\3/gi,
25 + `$1$2$3${REDACTED}$3`,
26 + ],
27 +];
28 +
29 +/**
30 + * Redact common secret shapes from a free-form string. Returns the input
31 + * unchanged when it is empty or `undefined`.
32 + */
33 +export const redactSensitiveText = (input: string | undefined): string | undefined => {
34 + if (!input) return input;
35 + let output = input;
36 + for (const [pattern, replacement] of REDACTION_RULES) {
37 + output = output.replace(pattern, replacement);
38 + }
39 + return output;
40 +};
ts/packages/core/src/utils/fileUtils.node.ts
+5 -1
@@ -9,6 +9,7 @@ import { base64ToUint8Array, uint8ArrayToBase64 } from './buffer';
9 import type { FileDownloadData, FileUploadData } from '../types/files.types';
10 import { assertSafeFileUploadPath } from './sensitiveFileUploadPaths';
11 import { assertPathInsideUploadDirs } from './uploadDirAllowlist.node';
12 +import { ssrfSafeFetch } from './ssrfGuard.node';
13
14 /**
15 * Options for {@link getFileDataAfterUploadingToS3} (S3 presigned upload from local path, URL, or File).
@@ -169,7 +170,10 @@ const readFileContentFromURL = async (
170 path: string,
171 signal?: AbortSignal
172 ): Promise<{ fileName: string; content: string; mimeType: string }> => {
172 - const response = await fetch(path, { signal });
173 + // SSRF guard: `path` is user-supplied (and can come from an LLM-produced tool
174 + // argument), so it must not be allowed to reach internal/private addresses or
175 + // redirect into them. See ssrfGuard.node.ts.
176 + const response = await ssrfSafeFetch(path, { signal });
177 if (!response.ok) {
178 throw new Error(`Failed to fetch file: ${response.statusText}`);
179 }
ts/packages/core/src/utils/ssrfGuard.node.ts new
+202
@@ -0,0 +1,202 @@
1 +import { lookup } from 'node:dns/promises'; // we're in a Node.js-specific module
2 +import { isIP } from 'node:net';
3 +import { ComposioBlockedInternalUrlError } from '../errors/SsrfErrors';
4 +
5 +/**
6 + * SSRF guard for user-supplied URL file inputs.
7 + *
8 + * `composio.files.upload(url)` and automatic file upload during tool execution
9 + * fetch arbitrary user-provided URLs. Without a guard, a caller (or a tool
10 + * argument produced by an LLM) can point the SDK at internal infrastructure —
11 + * loopback, RFC1918 ranges, link-local cloud-metadata endpoints
12 + * (`169.254.169.254`), or a public URL that 3xx-redirects into internal space —
13 + * turning the SDK into a server-side request forgery probe.
14 + *
15 + * This module validates the *resolved* address (not just the hostname string,
16 + * which defeats decimal/octal/hex IP obfuscation) before every fetch, and
17 + * follows redirects manually so each hop is re-validated.
18 + *
19 + * Known residual: a DNS name could resolve to a public address here and rebind
20 + * to an internal one before the underlying `fetch` connects (a TOCTOU / DNS
21 + * rebinding window). Closing that fully requires pinning the validated IP at
22 + * connect time (a custom dispatcher), which is out of scope for this guard.
23 + */
24 +
25 +const MAX_REDIRECTS = 5;
26 +
27 +const ipv4ToLong = (ip: string): number => {
28 + const [a, b, c, d] = ip.split('.').map(Number);
29 + return (((a << 24) >>> 0) | (b << 16) | (c << 8) | d) >>> 0;
30 +};
31 +
32 +// Address blocks that must never be reachable from a user-supplied URL.
33 +// (RFC1918 private, loopback, link-local, CGNAT, TEST-NET, benchmarking,
34 +// multicast, and reserved ranges.)
35 +const IPV4_BLOCKED_CIDRS: ReadonlyArray<readonly [string, number]> = [
36 + ['0.0.0.0', 8], // "this" network / unspecified
37 + ['10.0.0.0', 8], // private
38 + ['100.64.0.0', 10], // carrier-grade NAT
39 + ['127.0.0.0', 8], // loopback
40 + ['169.254.0.0', 16], // link-local (incl. cloud metadata 169.254.169.254)
41 + ['172.16.0.0', 12], // private
42 + ['192.0.0.0', 24], // IETF protocol assignments
43 + ['192.0.2.0', 24], // TEST-NET-1
44 + ['192.168.0.0', 16], // private
45 + ['198.18.0.0', 15], // benchmarking
46 + ['198.51.100.0', 24], // TEST-NET-2
47 + ['203.0.113.0', 24], // TEST-NET-3
48 + ['224.0.0.0', 4], // multicast
49 + ['240.0.0.0', 4], // reserved (incl. 255.255.255.255 broadcast)
50 +];
51 +
52 +const isBlockedIpv4Long = (long: number): boolean =>
53 + IPV4_BLOCKED_CIDRS.some(([base, bits]) => {
54 + const mask = bits === 0 ? 0 : (0xffffffff << (32 - bits)) >>> 0;
55 + return (long & mask) === (ipv4ToLong(base) & mask);
56 + });
57 +
58 +/**
59 + * Expand an IPv6 string into its 8 16-bit groups, converting any trailing
60 + * dotted-quad (e.g. `::ffff:1.2.3.4`) into hex groups first. Returns `null` when
61 + * the input cannot be parsed.
62 + */
63 +const expandIpv6 = (ip: string): number[] | null => {
64 + let addr = ip;
65 + const v4Match = addr.match(/^(.*:)(\d+\.\d+\.\d+\.\d+)$/);
66 + if (v4Match) {
67 + const long = ipv4ToLong(v4Match[2]);
68 + addr = `${v4Match[1]}${((long >>> 16) & 0xffff).toString(16)}:${(long & 0xffff).toString(16)}`;
69 + }
70 +
71 + const halves = addr.split('::');
72 + if (halves.length > 2) return null;
73 +
74 + const head = halves[0] ? halves[0].split(':') : [];
75 + const tail = halves.length === 2 ? (halves[1] ? halves[1].split(':') : []) : [];
76 +
77 + let groups: string[];
78 + if (halves.length === 2) {
79 + const missing = 8 - head.length - tail.length;
80 + if (missing < 0) return null;
81 + groups = [...head, ...Array(missing).fill('0'), ...tail];
82 + } else {
83 + groups = head;
84 + }
85 +
86 + if (groups.length !== 8) return null;
87 + return groups.map(g => parseInt(g || '0', 16));
88 +};
89 +
90 +const isBlockedIpv6 = (ip: string): boolean => {
91 + const h = expandIpv6(ip);
92 + if (!h) return true; // fail closed on anything we cannot parse
93 +
94 + // :: (unspecified) and ::1 (loopback)
95 + if (h.every(x => x === 0)) return true;
96 + if (h.slice(0, 7).every(x => x === 0) && h[7] === 1) return true;
97 +
98 + // Addresses that embed an IPv4 address in their low 32 bits must be validated
99 + // against the IPv4 blocklist, otherwise `::127.0.0.1` / `::169.254.169.254`
100 + // (and mapped/NAT64 forms) would pass as "public" IPv6 and reach internal
101 + // targets. Covers:
102 + // - IPv4-mapped ::ffff:0:0/96 (h[5] === 0xffff)
103 + // - IPv4-compatible ::/96 (deprecated, h[5] === 0) — incl. ::a.b.c.d
104 + // - NAT64 64:ff9b::/96
105 + const highBitsZero = h[0] === 0 && h[1] === 0 && h[2] === 0 && h[3] === 0 && h[4] === 0;
106 + const isMappedOrCompat = highBitsZero && (h[5] === 0xffff || h[5] === 0);
107 + const isNat64 =
108 + h[0] === 0x0064 && h[1] === 0xff9b && h[2] === 0 && h[3] === 0 && h[4] === 0 && h[5] === 0;
109 + if (isMappedOrCompat || isNat64) {
110 + return isBlockedIpv4Long((((h[6] << 16) >>> 0) | h[7]) >>> 0);
111 + }
112 +
113 + if ((h[0] & 0xfe00) === 0xfc00) return true; // unique local fc00::/7
114 + if ((h[0] & 0xffc0) === 0xfe80) return true; // link-local fe80::/10
115 + if ((h[0] & 0xff00) === 0xff00) return true; // multicast ff00::/8
116 +
117 + return false;
118 +};
119 +
120 +/**
121 + * True when `ip` is a private, loopback, link-local, or otherwise
122 + * non-publicly-routable address. Fails closed (returns `true`) for anything that
123 + * is not a valid IPv4/IPv6 literal.
124 + */
125 +export const isBlockedIp = (ip: string): boolean => {
126 + const family = isIP(ip);
127 + if (family === 4) return isBlockedIpv4Long(ipv4ToLong(ip));
128 + if (family === 6) return isBlockedIpv6(ip);
129 + return true;
130 +};
131 +
132 +/**
133 + * Validate a single URL: it must be http(s), its host must resolve, and every
134 + * resolved address must be publicly routable. Throws
135 + * {@link ComposioBlockedInternalUrlError} otherwise.
136 + */
137 +export const assertSafeFetchTarget = async (rawUrl: string): Promise<void> => {
138 + let url: URL;
139 + try {
140 + url = new URL(rawUrl);
141 + } catch {
142 + throw new ComposioBlockedInternalUrlError('Refusing to fetch a malformed URL', { url: rawUrl });
143 + }
144 +
145 + if (url.protocol !== 'http:' && url.protocol !== 'https:') {
146 + throw new ComposioBlockedInternalUrlError(
147 + `Refusing to fetch a non-http(s) URL (scheme "${url.protocol}")`,
148 + { url: rawUrl }
149 + );
150 + }
151 +
152 + const host = url.hostname.replace(/^\[|\]$/g, '');
153 +
154 + let resolved: Array<{ address: string }>;
155 + try {
156 + resolved = await lookup(host, { all: true, verbatim: true });
157 + } catch {
158 + throw new ComposioBlockedInternalUrlError(`Could not resolve host "${host}"`, { url: rawUrl });
159 + }
160 +
161 + for (const { address } of resolved) {
162 + if (isBlockedIp(address)) {
163 + throw new ComposioBlockedInternalUrlError(
164 + `Refusing to fetch "${host}" — it resolves to a private, loopback, or link-local address`,
165 + { url: rawUrl, resolvedIp: address }
166 + );
167 + }
168 + }
169 +};
170 +
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.
176 + */
177 +export const ssrfSafeFetch = async (
178 + rawUrl: string,
179 + init: RequestInit = {},
180 + maxRedirects: number = MAX_REDIRECTS
181 +): Promise<Response> => {
182 + let currentUrl = rawUrl;
183 +
184 + for (let hop = 0; hop <= maxRedirects; hop++) {
185 + await assertSafeFetchTarget(currentUrl);
186 +
187 + const response = await fetch(currentUrl, { ...init, redirect: 'manual' });
188 +
189 + const isRedirect =
190 + response.status >= 300 && response.status < 400 && response.headers.has('location');
191 + if (!isRedirect) {
192 + return response;
193 + }
194 +
195 + currentUrl = new URL(response.headers.get('location')!, currentUrl).toString();
196 + }
197 +
198 + throw new ComposioBlockedInternalUrlError(
199 + `Refusing to fetch: too many redirects (max ${maxRedirects})`,
200 + { url: rawUrl }
201 + );
202 +};
ts/packages/core/test/telemetry/redact.test.ts new
+48
@@ -0,0 +1,48 @@
1 +import { describe, it, expect } from 'vitest';
2 +import { redactSensitiveText } from '../../src/telemetry/redact';
3 +
4 +describe('redactSensitiveText', () => {
5 + it('returns empty/undefined input unchanged', () => {
6 + expect(redactSensitiveText(undefined)).toBeUndefined();
7 + expect(redactSensitiveText('')).toBe('');
8 + });
9 +
10 + it('redacts URL query strings while keeping the path', () => {
11 + const out = redactSensitiveText(
12 + 'Failed to PUT https://s3.amazonaws.com/bucket/key?X-Amz-Signature=deadbeef&token=abc'
13 + );
14 + expect(out).toContain('https://s3.amazonaws.com/bucket/key?[REDACTED]');
15 + expect(out).not.toContain('deadbeef');
16 + expect(out).not.toContain('token=abc');
17 + });
18 +
19 + it('redacts Authorization bearer/basic credentials', () => {
20 + const auth = redactSensitiveText('Authorization: Bearer sk-live-1234567890')!;
21 + expect(auth).toContain('[REDACTED]');
22 + expect(auth).not.toContain('sk-live-1234567890');
23 + expect(redactSensitiveText('used Basic dXNlcjpwYXNz here')).toBe('used Basic [REDACTED] here');
24 + });
25 +
26 + it('redacts secret-like key/value pairs', () => {
27 + for (const sample of [
28 + 'api_key=ck_abcdef123456',
29 + 'x-api-key: "ck_secretvalue"',
30 + "client_secret: 'topsecret'",
31 + 'password=hunter2',
32 + 'access_token=ya29.a0Afoobar',
33 + ]) {
34 + const out = redactSensitiveText(sample)!;
35 + expect(out, sample).toContain('[REDACTED]');
36 + expect(out, sample).not.toMatch(/ck_abcdef123456|ck_secretvalue|topsecret|hunter2|ya29/);
37 + }
38 + });
39 +
40 + it('preserves quotes around redacted values', () => {
41 + expect(redactSensitiveText('x-api-key: "ck_secretvalue"')).toContain('"[REDACTED]"');
42 + });
43 +
44 + it('leaves benign error text untouched', () => {
45 + const benign = 'TypeError: cannot read property foo of undefined at Object.<anonymous>';
46 + expect(redactSensitiveText(benign)).toBe(benign);
47 + });
48 +});
ts/packages/core/test/utils/fileUtils.test.ts
+11 -1
@@ -42,6 +42,13 @@ vi.mock('path', async importOriginal => {
42 };
43 });
44
45 +// Mock DNS resolution so the SSRF guard treats test hosts as public without
46 +// hitting the network. (URL uploads route through ssrfSafeFetch, which resolves
47 +// the host and rejects private/internal addresses.)
48 +vi.mock('node:dns/promises', () => ({
49 + lookup: vi.fn().mockResolvedValue([{ address: '93.184.216.34', family: 4 }]),
50 +}));
51 +
52 // Mock global fetch
53 const mockFetch = vi.fn();
54 global.fetch = mockFetch;
@@ -107,7 +114,10 @@ describe('fileUtils', () => {
114 });
115
116 expect(result.name).toBe('document.pdf');
110 - expect(mockFetch).toHaveBeenCalledWith(urlWithQuery, { signal: undefined });
117 + expect(mockFetch).toHaveBeenCalledWith(urlWithQuery, {
118 + signal: undefined,
119 + redirect: 'manual',
120 + });
121 });
122
123 it('should generate filename when URL has no filename', async () => {
ts/packages/core/test/utils/ssrfGuard.test.ts new
+165
@@ -0,0 +1,165 @@
1 +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
2 +import { isBlockedIp, assertSafeFetchTarget, ssrfSafeFetch } from '../../src/utils/ssrfGuard.node';
3 +import { ComposioBlockedInternalUrlError } from '../../src/errors/SsrfErrors';
4 +
5 +vi.mock('node:dns/promises', () => ({
6 + lookup: vi.fn(),
7 +}));
8 +
9 +// eslint-disable-next-line no-restricted-imports
10 +import { lookup } from 'node:dns/promises';
11 +
12 +const mockLookup = vi.mocked(lookup);
13 +const resolvesTo = (...addresses: string[]) =>
14 + mockLookup.mockResolvedValue(
15 + addresses.map(address => ({ address, family: address.includes(':') ? 6 : 4 })) as never
16 + );
17 +
18 +describe('isBlockedIp', () => {
19 + it('blocks IPv4 loopback, private, and link-local ranges', () => {
20 + for (const ip of [
21 + '127.0.0.1',
22 + '127.1.2.3',
23 + '10.0.0.5',
24 + '172.16.0.1',
25 + '172.31.255.255',
26 + '192.168.1.1',
27 + '169.254.169.254', // cloud metadata
28 + '100.64.0.1', // CGNAT
29 + '0.0.0.0',
30 + ]) {
31 + expect(isBlockedIp(ip), ip).toBe(true);
32 + }
33 + });
34 +
35 + it('allows public IPv4 addresses', () => {
36 + for (const ip of ['8.8.8.8', '1.1.1.1', '93.184.216.34', '172.15.0.1', '172.32.0.1']) {
37 + expect(isBlockedIp(ip), ip).toBe(false);
38 + }
39 + });
40 +
41 + it('blocks IPv6 loopback, ULA, link-local, and mapped/compat internal addresses', () => {
42 + for (const ip of [
43 + '::1',
44 + '::',
45 + 'fc00::1',
46 + 'fd12:3456::1',
47 + 'fe80::1',
48 + '::ffff:127.0.0.1',
49 + '::ffff:169.254.169.254',
50 + // IPv4-compatible ::/96 (deprecated) — the bypass Bugbot flagged
51 + '::127.0.0.1',
52 + '::169.254.169.254',
53 + '::10.0.0.1',
54 + // ...and their normalized hex forms (what dns.lookup / URL parsing yield)
55 + '::7f00:1', // ::127.0.0.1
56 + '::a9fe:a9fe', // ::169.254.169.254
57 + ]) {
58 + expect(isBlockedIp(ip), ip).toBe(true);
59 + }
60 + });
61 +
62 + it('allows public IPv6 and public IPv4-mapped/compat addresses', () => {
63 + for (const ip of ['2606:4700:4700::1111', '::ffff:8.8.8.8', '::8.8.8.8', '::808:808']) {
64 + expect(isBlockedIp(ip), ip).toBe(false);
65 + }
66 + });
67 +
68 + it('fails closed for non-IP strings', () => {
69 + expect(isBlockedIp('not-an-ip')).toBe(true);
70 + expect(isBlockedIp('')).toBe(true);
71 + });
72 +});
73 +
74 +describe('assertSafeFetchTarget', () => {
75 + beforeEach(() => mockLookup.mockReset());
76 +
77 + it('rejects non-http(s) schemes', async () => {
78 + await expect(assertSafeFetchTarget('file:///etc/passwd')).rejects.toBeInstanceOf(
79 + ComposioBlockedInternalUrlError
80 + );
81 + await expect(assertSafeFetchTarget('ftp://example.com/x')).rejects.toBeInstanceOf(
82 + ComposioBlockedInternalUrlError
83 + );
84 + });
85 +
86 + it('rejects a host that resolves to an internal address', async () => {
87 + resolvesTo('169.254.169.254');
88 + await expect(assertSafeFetchTarget('http://metadata.internal/latest')).rejects.toBeInstanceOf(
89 + ComposioBlockedInternalUrlError
90 + );
91 + });
92 +
93 + it('rejects when ANY resolved address is internal (DNS pinning bypass)', async () => {
94 + resolvesTo('93.184.216.34', '127.0.0.1');
95 + await expect(assertSafeFetchTarget('http://evil.example/x')).rejects.toBeInstanceOf(
96 + ComposioBlockedInternalUrlError
97 + );
98 + });
99 +
100 + it('allows a host that resolves only to public addresses', async () => {
101 + resolvesTo('93.184.216.34');
102 + await expect(assertSafeFetchTarget('https://example.com/file.pdf')).resolves.toBeUndefined();
103 + });
104 +
105 + it('blocks an IPv6 literal loopback host', async () => {
106 + resolvesTo('::1');
107 + await expect(assertSafeFetchTarget('http://[::1]:8080/x')).rejects.toBeInstanceOf(
108 + ComposioBlockedInternalUrlError
109 + );
110 + });
111 +});
112 +
113 +describe('ssrfSafeFetch', () => {
114 + const mockFetch = vi.fn();
115 +
116 + beforeEach(() => {
117 + mockLookup.mockReset();
118 + mockFetch.mockReset();
119 + vi.stubGlobal('fetch', mockFetch);
120 + });
121 + afterEach(() => vi.unstubAllGlobals());
122 +
123 + it('validates and fetches a public URL', async () => {
124 + resolvesTo('93.184.216.34');
125 + const ok = new Response('data', { status: 200 });
126 + mockFetch.mockResolvedValue(ok);
127 +
128 + const res = await ssrfSafeFetch('https://example.com/file.pdf');
129 + expect(res.status).toBe(200);
130 + expect(mockFetch).toHaveBeenCalledWith(
131 + 'https://example.com/file.pdf',
132 + expect.objectContaining({ redirect: 'manual' })
133 + );
134 + });
135 +
136 + it('re-validates redirect hops and blocks a redirect into internal space', async () => {
137 + // First host is public; it 302-redirects to an internal metadata endpoint.
138 + mockLookup
139 + .mockResolvedValueOnce([{ address: '93.184.216.34', family: 4 }] as never)
140 + .mockResolvedValueOnce([{ address: '169.254.169.254', family: 4 }] as never);
141 + mockFetch.mockResolvedValueOnce(
142 + new Response(null, {
143 + status: 302,
144 + headers: { location: 'http://169.254.169.254/latest/meta-data/' },
145 + })
146 + );
147 +
148 + await expect(ssrfSafeFetch('https://public.example/redirect')).rejects.toBeInstanceOf(
149 + ComposioBlockedInternalUrlError
150 + );
151 + // Only the first (public) fetch runs; the internal hop is blocked before fetching.
152 + expect(mockFetch).toHaveBeenCalledTimes(1);
153 + });
154 +
155 + it('throws after exceeding the redirect budget', async () => {
156 + resolvesTo('93.184.216.34');
157 + mockFetch.mockResolvedValue(
158 + new Response(null, { status: 302, headers: { location: 'https://example.com/again' } })
159 + );
160 +
161 + await expect(ssrfSafeFetch('https://example.com/start', {}, 2)).rejects.toBeInstanceOf(
162 + ComposioBlockedInternalUrlError
163 + );
164 + });
165 +});