Skip to content

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

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

Alberto Schiabela0f37a7f7728
diff --git a/.changeset/ssrf-guard-and-telemetry-redaction.md b/.changeset/ssrf-guard-and-telemetry-redaction.md
new file mode 100644
index 000000000..2d8205813
--- /dev/null
+++ b/.changeset/ssrf-guard-and-telemetry-redaction.md
@@ -0,0 +1,8 @@
+---
+'@composio/core': patch
+---
+
+Close two secret/SSRF exposure surfaces in the TypeScript SDK:
+
+- **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.
+- **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.
diff --git a/ts/packages/core/src/errors/SsrfErrors.ts b/ts/packages/core/src/errors/SsrfErrors.ts
new file mode 100644
index 000000000..42ba64521
--- /dev/null
+++ b/ts/packages/core/src/errors/SsrfErrors.ts
@@ -0,0 +1,47 @@
+import { ComposioError, ComposioErrorOptions } from './ComposioError';
+
+export const SsrfErrorCodes = {
+ BLOCKED_INTERNAL_URL: 'BLOCKED_INTERNAL_URL',
+} as const;
+
+export interface ComposioBlockedInternalUrlErrorOptions extends Omit<ComposioErrorOptions, 'code'> {
+ /** The user-supplied URL that was refused. */
+ url?: string;
+ /** The resolved address that tripped the guard, when known. */
+ resolvedIp?: string;
+}
+
+/**
+ * Thrown when a URL file input resolves to a private, loopback, link-local, or
+ * otherwise internal address, or points at a non-http(s) scheme. Guards against
+ * turning `composio.files.upload(url)` (and automatic upload during tool
+ * execution) into a server-side request forgery (SSRF) probe of internal
+ * infrastructure such as cloud metadata endpoints (`169.254.169.254`).
+ */
+export class ComposioBlockedInternalUrlError extends ComposioError {
+ constructor(
+ message: string = 'Refusing to fetch an internal or non-public URL',
+ options: ComposioBlockedInternalUrlErrorOptions = {}
+ ) {
+ const { url, resolvedIp, meta: optionsMeta, ...rest } = options;
+
+ const meta: Record<string, unknown> = {
+ ...optionsMeta,
+ ...(url && { url }),
+ ...(resolvedIp && { resolvedIp }),
+ };
+
+ super(message, {
+ ...rest,
+ code: SsrfErrorCodes.BLOCKED_INTERNAL_URL,
+ meta: Object.keys(meta).length > 0 ? meta : undefined,
+ possibleFixes: options.possibleFixes ?? [
+ 'Use a publicly reachable http(s) URL',
+ 'Do not point file inputs at localhost, link-local, or private-network hosts',
+ 'If the source is internal, download it yourself and pass a File/Blob instead of a URL',
+ ],
+ });
+
+ this.name = 'ComposioBlockedInternalUrlError';
+ }
+}
diff --git a/ts/packages/core/src/errors/index.ts b/ts/packages/core/src/errors/index.ts
index ee047fb35..b5455a886 100644
--- a/ts/packages/core/src/errors/index.ts
+++ b/ts/packages/core/src/errors/index.ts
@@ -39,3 +39,6 @@ export * from './RemoteFileErrors';
// File modifier / auto upload
export * from './FileModifierErrors';
+
+// SSRF guard (URL file inputs)
+export * from './SsrfErrors';
diff --git a/ts/packages/core/src/telemetry/Telemetry.ts b/ts/packages/core/src/telemetry/Telemetry.ts
index 586790e47..147ed94a5 100644
--- a/ts/packages/core/src/telemetry/Telemetry.ts
+++ b/ts/packages/core/src/telemetry/Telemetry.ts
@@ -18,6 +18,7 @@ import {
} from '../services/telemetry/TelemetryService.types';
import { TelemetryService } from '../services/telemetry/TelemetryService';
import logger from '../utils/logger';
+import { redactSensitiveText } from './redact';
/**
* The Telemetry class is used to log the telemetry for any given instance which extends InstrumentedInstance.
*
@@ -207,28 +208,30 @@ export class TelemetryTransport {
},
source: this.telemetrySource,
};
+ // Redact secrets (URLs with tokens, Authorization headers, API keys, etc.)
+ // from free-form error text before it is transported off-process.
// client error, this is likely handled by the API itseld
if (error instanceof ComposioClientError) {
telemetryPayload.error = {
errorId: error.errorId,
name: error.name,
- message: error.message,
- stack: error.stack,
+ message: redactSensitiveText(error.message),
+ stack: redactSensitiveText(error.stack),
};
} else if (error instanceof ComposioError) {
telemetryPayload.error = {
errorId: error.errorId,
name: error.name,
code: error.code,
- message: error.message,
- stack: error.stack,
+ message: redactSensitiveText(error.message),
+ stack: redactSensitiveText(error.stack),
};
} else if (error instanceof Error) {
telemetryPayload.error = {
errorId: error.errorId,
name: error.name ?? 'Unknown error',
- message: error.message,
- stack: error.stack,
+ message: redactSensitiveText(error.message),
+ stack: redactSensitiveText(error.stack),
};
}
diff --git a/ts/packages/core/src/telemetry/redact.ts b/ts/packages/core/src/telemetry/redact.ts
new file mode 100644
index 000000000..f538cf72a
--- /dev/null
+++ b/ts/packages/core/src/telemetry/redact.ts
@@ -0,0 +1,40 @@
+/**
+ * Best-effort redaction of secrets from free-form error text before it is sent
+ * to the telemetry endpoint.
+ *
+ * Error `message` and `stack` fields routinely interpolate URLs (with
+ * query-string tokens / presigned signatures), `Authorization` headers, API
+ * keys, and connected-account identifiers. None of that should leave the
+ * process. Structured telemetry fields never carry raw secrets, so only the two
+ * free-form strings are passed through here.
+ *
+ * This is defence-in-depth, not a proof: it targets the shapes we have seen
+ * leak. When in doubt it over-redacts rather than under-redacts.
+ */
+
+const REDACTED = '[REDACTED]';
+
+const REDACTION_RULES: ReadonlyArray<readonly [RegExp, string]> = [
+ // URL query strings — tokens, presigned signatures, one-time codes.
+ [/(\bhttps?:\/\/[^\s?#'"]+)\?[^\s'"]*/gi, `$1?${REDACTED}`],
+ // Authorization scheme + credential: `Bearer <token>`, `Basic <token>`.
+ [/\b(bearer|basic)\s+[A-Za-z0-9._~+/=-]+/gi, `$1 ${REDACTED}`],
+ // Secret-ish `key: value` / `key=value` / `key: "value"` / `key: 'value'` pairs.
+ [
+ /\b(authorization|api[-_]?key|apikey|x-api-key|access[-_]?token|refresh[-_]?token|client[-_]?secret|secret|password|passwd|pwd)\b(\s*[:=]+\s*)(["']?)([^\s"',}&]+)\3/gi,
+ `$1$2$3${REDACTED}$3`,
+ ],
+];
+
+/**
+ * Redact common secret shapes from a free-form string. Returns the input
+ * unchanged when it is empty or `undefined`.
+ */
+export const redactSensitiveText = (input: string | undefined): string | undefined => {
+ if (!input) return input;
+ let output = input;
+ for (const [pattern, replacement] of REDACTION_RULES) {
+ output = output.replace(pattern, replacement);
+ }
+ return output;
+};
diff --git a/ts/packages/core/src/utils/fileUtils.node.ts b/ts/packages/core/src/utils/fileUtils.node.ts
index fc2a63f17..6c30e7753 100644
--- a/ts/packages/core/src/utils/fileUtils.node.ts
+++ b/ts/packages/core/src/utils/fileUtils.node.ts
@@ -9,6 +9,7 @@ import { base64ToUint8Array, uint8ArrayToBase64 } from './buffer';
import type { FileDownloadData, FileUploadData } from '../types/files.types';
import { assertSafeFileUploadPath } from './sensitiveFileUploadPaths';
import { assertPathInsideUploadDirs } from './uploadDirAllowlist.node';
+import { ssrfSafeFetch } from './ssrfGuard.node';
/**
* Options for {@link getFileDataAfterUploadingToS3} (S3 presigned upload from local path, URL, or File).
@@ -169,7 +170,10 @@ const readFileContentFromURL = async (
path: string,
signal?: AbortSignal
): Promise<{ fileName: string; content: string; mimeType: string }> => {
- const response = await fetch(path, { signal });
+ // SSRF guard: `path` is user-supplied (and can come from an LLM-produced tool
+ // argument), so it must not be allowed to reach internal/private addresses or
+ // redirect into them. See ssrfGuard.node.ts.
+ const response = await ssrfSafeFetch(path, { signal });
if (!response.ok) {
throw new Error(`Failed to fetch file: ${response.statusText}`);
}
diff --git a/ts/packages/core/src/utils/ssrfGuard.node.ts b/ts/packages/core/src/utils/ssrfGuard.node.ts
new file mode 100644
index 000000000..728a65e82
--- /dev/null
+++ b/ts/packages/core/src/utils/ssrfGuard.node.ts
@@ -0,0 +1,202 @@
+import { lookup } from 'node:dns/promises'; // we're in a Node.js-specific module
+import { isIP } from 'node:net';
+import { ComposioBlockedInternalUrlError } from '../errors/SsrfErrors';
+
+/**
+ * SSRF guard for user-supplied URL file inputs.
+ *
+ * `composio.files.upload(url)` and automatic file upload during tool execution
+ * fetch arbitrary user-provided URLs. Without a guard, a caller (or a tool
+ * argument produced by an LLM) can point the SDK at internal infrastructure —
+ * loopback, RFC1918 ranges, link-local cloud-metadata endpoints
+ * (`169.254.169.254`), or a public URL that 3xx-redirects into internal space —
+ * turning the SDK into a server-side request forgery probe.
+ *
+ * This module validates the *resolved* address (not just the hostname string,
+ * which defeats decimal/octal/hex IP obfuscation) before every fetch, and
+ * follows redirects manually so each hop is re-validated.
+ *
+ * Known residual: a DNS name could resolve to a public address here and rebind
+ * to an internal one before the underlying `fetch` connects (a TOCTOU / DNS
+ * rebinding window). Closing that fully requires pinning the validated IP at
+ * connect time (a custom dispatcher), which is out of scope for this guard.
+ */
+
+const MAX_REDIRECTS = 5;
+
+const ipv4ToLong = (ip: string): number => {
+ const [a, b, c, d] = ip.split('.').map(Number);
+ return (((a << 24) >>> 0) | (b << 16) | (c << 8) | d) >>> 0;
+};
+
+// Address blocks that must never be reachable from a user-supplied URL.
+// (RFC1918 private, loopback, link-local, CGNAT, TEST-NET, benchmarking,
+// multicast, and reserved ranges.)
+const IPV4_BLOCKED_CIDRS: ReadonlyArray<readonly [string, number]> = [
+ ['0.0.0.0', 8], // "this" network / unspecified
+ ['10.0.0.0', 8], // private
+ ['100.64.0.0', 10], // carrier-grade NAT
+ ['127.0.0.0', 8], // loopback
+ ['169.254.0.0', 16], // link-local (incl. cloud metadata 169.254.169.254)
+ ['172.16.0.0', 12], // private
+ ['192.0.0.0', 24], // IETF protocol assignments
+ ['192.0.2.0', 24], // TEST-NET-1
+ ['192.168.0.0', 16], // private
+ ['198.18.0.0', 15], // benchmarking
+ ['198.51.100.0', 24], // TEST-NET-2
+ ['203.0.113.0', 24], // TEST-NET-3
+ ['224.0.0.0', 4], // multicast
+ ['240.0.0.0', 4], // reserved (incl. 255.255.255.255 broadcast)
+];
+
+const isBlockedIpv4Long = (long: number): boolean =>
+ IPV4_BLOCKED_CIDRS.some(([base, bits]) => {
+ const mask = bits === 0 ? 0 : (0xffffffff << (32 - bits)) >>> 0;
+ return (long & mask) === (ipv4ToLong(base) & mask);
+ });
+
+/**
+ * Expand an IPv6 string into its 8 16-bit groups, converting any trailing
+ * dotted-quad (e.g. `::ffff:1.2.3.4`) into hex groups first. Returns `null` when
+ * the input cannot be parsed.
+ */
+const expandIpv6 = (ip: string): number[] | null => {
+ let addr = ip;
+ const v4Match = addr.match(/^(.*:)(\d+\.\d+\.\d+\.\d+)$/);
+ if (v4Match) {
+ const long = ipv4ToLong(v4Match[2]);
+ addr = `${v4Match[1]}${((long >>> 16) & 0xffff).toString(16)}:${(long & 0xffff).toString(16)}`;
+ }
+
+ const halves = addr.split('::');
+ if (halves.length > 2) return null;
+
+ const head = halves[0] ? halves[0].split(':') : [];
+ const tail = halves.length === 2 ? (halves[1] ? halves[1].split(':') : []) : [];
+
+ let groups: string[];
+ if (halves.length === 2) {
+ const missing = 8 - head.length - tail.length;
+ if (missing < 0) return null;
+ groups = [...head, ...Array(missing).fill('0'), ...tail];
+ } else {
+ groups = head;
+ }
+
+ if (groups.length !== 8) return null;
+ return groups.map(g => parseInt(g || '0', 16));
+};
+
+const isBlockedIpv6 = (ip: string): boolean => {
+ const h = expandIpv6(ip);
+ if (!h) return true; // fail closed on anything we cannot parse
+
+ // :: (unspecified) and ::1 (loopback)
+ if (h.every(x => x === 0)) return true;
+ if (h.slice(0, 7).every(x => x === 0) && h[7] === 1) return true;
+
+ // Addresses that embed an IPv4 address in their low 32 bits must be validated
+ // against the IPv4 blocklist, otherwise `::127.0.0.1` / `::169.254.169.254`
+ // (and mapped/NAT64 forms) would pass as "public" IPv6 and reach internal
+ // targets. Covers:
+ // - IPv4-mapped ::ffff:0:0/96 (h[5] === 0xffff)
+ // - IPv4-compatible ::/96 (deprecated, h[5] === 0) — incl. ::a.b.c.d
+ // - NAT64 64:ff9b::/96
+ const highBitsZero = h[0] === 0 && h[1] === 0 && h[2] === 0 && h[3] === 0 && h[4] === 0;
+ const isMappedOrCompat = highBitsZero && (h[5] === 0xffff || h[5] === 0);
+ const isNat64 =
+ h[0] === 0x0064 && h[1] === 0xff9b && h[2] === 0 && h[3] === 0 && h[4] === 0 && h[5] === 0;
+ if (isMappedOrCompat || isNat64) {
+ return isBlockedIpv4Long((((h[6] << 16) >>> 0) | h[7]) >>> 0);
+ }
+
+ if ((h[0] & 0xfe00) === 0xfc00) return true; // unique local fc00::/7
+ if ((h[0] & 0xffc0) === 0xfe80) return true; // link-local fe80::/10
+ if ((h[0] & 0xff00) === 0xff00) return true; // multicast ff00::/8
+
+ return false;
+};
+
+/**
+ * True when `ip` is a private, loopback, link-local, or otherwise
+ * non-publicly-routable address. Fails closed (returns `true`) for anything that
+ * is not a valid IPv4/IPv6 literal.
+ */
+export const isBlockedIp = (ip: string): boolean => {
+ const family = isIP(ip);
+ if (family === 4) return isBlockedIpv4Long(ipv4ToLong(ip));
+ if (family === 6) return isBlockedIpv6(ip);
+ return true;
+};
+
+/**
+ * Validate a single URL: it must be http(s), its host must resolve, and every
+ * resolved address must be publicly routable. Throws
+ * {@link ComposioBlockedInternalUrlError} otherwise.
+ */
+export const assertSafeFetchTarget = async (rawUrl: string): Promise<void> => {
+ let url: URL;
+ try {
+ url = new URL(rawUrl);
+ } catch {
+ throw new ComposioBlockedInternalUrlError('Refusing to fetch a malformed URL', { url: rawUrl });
+ }
+
+ if (url.protocol !== 'http:' && url.protocol !== 'https:') {
+ throw new ComposioBlockedInternalUrlError(
+ `Refusing to fetch a non-http(s) URL (scheme "${url.protocol}")`,
+ { url: rawUrl }
+ );
+ }
+
+ const host = url.hostname.replace(/^\[|\]$/g, '');
+
+ let resolved: Array<{ address: string }>;
+ try {
+ resolved = await lookup(host, { all: true, verbatim: true });
+ } catch {
+ throw new ComposioBlockedInternalUrlError(`Could not resolve host "${host}"`, { url: rawUrl });
+ }
+
+ for (const { address } of resolved) {
+ if (isBlockedIp(address)) {
+ throw new ComposioBlockedInternalUrlError(
+ `Refusing to fetch "${host}" — it resolves to a private, loopback, or link-local address`,
+ { url: rawUrl, resolvedIp: address }
+ );
+ }
+ }
+};
+
+/**
+ * Drop-in replacement for `fetch` that blocks SSRF. Validates the target before
+ * connecting and re-validates every redirect hop (redirects are followed
+ * manually up to {@link MAX_REDIRECTS}). Non-redirect responses are returned
+ * unchanged.
+ */
+export const ssrfSafeFetch = async (
+ rawUrl: string,
+ init: RequestInit = {},
+ maxRedirects: number = MAX_REDIRECTS
+): Promise<Response> => {
+ let currentUrl = rawUrl;
+
+ for (let hop = 0; hop <= maxRedirects; hop++) {
+ await assertSafeFetchTarget(currentUrl);
+
+ const response = await fetch(currentUrl, { ...init, redirect: 'manual' });
+
+ const isRedirect =
+ response.status >= 300 && response.status < 400 && response.headers.has('location');
+ if (!isRedirect) {
+ return response;
+ }
+
+ currentUrl = new URL(response.headers.get('location')!, currentUrl).toString();
+ }
+
+ throw new ComposioBlockedInternalUrlError(
+ `Refusing to fetch: too many redirects (max ${maxRedirects})`,
+ { url: rawUrl }
+ );
+};
diff --git a/ts/packages/core/test/telemetry/redact.test.ts b/ts/packages/core/test/telemetry/redact.test.ts
new file mode 100644
index 000000000..31050533a
--- /dev/null
+++ b/ts/packages/core/test/telemetry/redact.test.ts
@@ -0,0 +1,48 @@
+import { describe, it, expect } from 'vitest';
+import { redactSensitiveText } from '../../src/telemetry/redact';
+
+describe('redactSensitiveText', () => {
+ it('returns empty/undefined input unchanged', () => {
+ expect(redactSensitiveText(undefined)).toBeUndefined();
+ expect(redactSensitiveText('')).toBe('');
+ });
+
+ it('redacts URL query strings while keeping the path', () => {
+ const out = redactSensitiveText(
+ 'Failed to PUT https://s3.amazonaws.com/bucket/key?X-Amz-Signature=deadbeef&token=abc'
+ );
+ expect(out).toContain('https://s3.amazonaws.com/bucket/key?[REDACTED]');
+ expect(out).not.toContain('deadbeef');
+ expect(out).not.toContain('token=abc');
+ });
+
+ it('redacts Authorization bearer/basic credentials', () => {
+ const auth = redactSensitiveText('Authorization: Bearer sk-live-1234567890')!;
+ expect(auth).toContain('[REDACTED]');
+ expect(auth).not.toContain('sk-live-1234567890');
+ expect(redactSensitiveText('used Basic dXNlcjpwYXNz here')).toBe('used Basic [REDACTED] here');
+ });
+
+ it('redacts secret-like key/value pairs', () => {
+ for (const sample of [
+ 'api_key=ck_abcdef123456',
+ 'x-api-key: "ck_secretvalue"',
+ "client_secret: 'topsecret'",
+ 'password=hunter2',
+ 'access_token=ya29.a0Afoobar',
+ ]) {
+ const out = redactSensitiveText(sample)!;
+ expect(out, sample).toContain('[REDACTED]');
+ expect(out, sample).not.toMatch(/ck_abcdef123456|ck_secretvalue|topsecret|hunter2|ya29/);
+ }
+ });
+
+ it('preserves quotes around redacted values', () => {
+ expect(redactSensitiveText('x-api-key: "ck_secretvalue"')).toContain('"[REDACTED]"');
+ });
+
+ it('leaves benign error text untouched', () => {
+ const benign = 'TypeError: cannot read property foo of undefined at Object.<anonymous>';
+ expect(redactSensitiveText(benign)).toBe(benign);
+ });
+});
diff --git a/ts/packages/core/test/utils/fileUtils.test.ts b/ts/packages/core/test/utils/fileUtils.test.ts
index ad06ae486..50d56c970 100644
--- a/ts/packages/core/test/utils/fileUtils.test.ts
+++ b/ts/packages/core/test/utils/fileUtils.test.ts
@@ -42,6 +42,13 @@ vi.mock('path', async importOriginal => {
};
});
+// Mock DNS resolution so the SSRF guard treats test hosts as public without
+// hitting the network. (URL uploads route through ssrfSafeFetch, which resolves
+// the host and rejects private/internal addresses.)
+vi.mock('node:dns/promises', () => ({
+ lookup: vi.fn().mockResolvedValue([{ address: '93.184.216.34', family: 4 }]),
+}));
+
// Mock global fetch
const mockFetch = vi.fn();
global.fetch = mockFetch;
@@ -107,7 +114,10 @@ describe('fileUtils', () => {
});
expect(result.name).toBe('document.pdf');
- expect(mockFetch).toHaveBeenCalledWith(urlWithQuery, { signal: undefined });
+ expect(mockFetch).toHaveBeenCalledWith(urlWithQuery, {
+ signal: undefined,
+ redirect: 'manual',
+ });
});
it('should generate filename when URL has no filename', async () => {
diff --git a/ts/packages/core/test/utils/ssrfGuard.test.ts b/ts/packages/core/test/utils/ssrfGuard.test.ts
new file mode 100644
index 000000000..000a46546
--- /dev/null
+++ b/ts/packages/core/test/utils/ssrfGuard.test.ts
@@ -0,0 +1,165 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { isBlockedIp, assertSafeFetchTarget, ssrfSafeFetch } from '../../src/utils/ssrfGuard.node';
+import { ComposioBlockedInternalUrlError } from '../../src/errors/SsrfErrors';
+
+vi.mock('node:dns/promises', () => ({
+ lookup: vi.fn(),
+}));
+
+// eslint-disable-next-line no-restricted-imports
+import { lookup } from 'node:dns/promises';
+
+const mockLookup = vi.mocked(lookup);
+const resolvesTo = (...addresses: string[]) =>
+ mockLookup.mockResolvedValue(
+ addresses.map(address => ({ address, family: address.includes(':') ? 6 : 4 })) as never
+ );
+
+describe('isBlockedIp', () => {
+ it('blocks IPv4 loopback, private, and link-local ranges', () => {
+ for (const ip of [
+ '127.0.0.1',
+ '127.1.2.3',
+ '10.0.0.5',
+ '172.16.0.1',
+ '172.31.255.255',
+ '192.168.1.1',
+ '169.254.169.254', // cloud metadata
+ '100.64.0.1', // CGNAT
+ '0.0.0.0',
+ ]) {
+ expect(isBlockedIp(ip), ip).toBe(true);
+ }
+ });
+
+ it('allows public IPv4 addresses', () => {
+ for (const ip of ['8.8.8.8', '1.1.1.1', '93.184.216.34', '172.15.0.1', '172.32.0.1']) {
+ expect(isBlockedIp(ip), ip).toBe(false);
+ }
+ });
+
+ it('blocks IPv6 loopback, ULA, link-local, and mapped/compat internal addresses', () => {
+ for (const ip of [
+ '::1',
+ '::',
+ 'fc00::1',
+ 'fd12:3456::1',
+ 'fe80::1',
+ '::ffff:127.0.0.1',
+ '::ffff:169.254.169.254',
+ // IPv4-compatible ::/96 (deprecated) — the bypass Bugbot flagged
+ '::127.0.0.1',
+ '::169.254.169.254',
+ '::10.0.0.1',
+ // ...and their normalized hex forms (what dns.lookup / URL parsing yield)
+ '::7f00:1', // ::127.0.0.1
+ '::a9fe:a9fe', // ::169.254.169.254
+ ]) {
+ expect(isBlockedIp(ip), ip).toBe(true);
+ }
+ });
+
+ it('allows public IPv6 and public IPv4-mapped/compat addresses', () => {
+ for (const ip of ['2606:4700:4700::1111', '::ffff:8.8.8.8', '::8.8.8.8', '::808:808']) {
+ expect(isBlockedIp(ip), ip).toBe(false);
+ }
+ });
+
+ it('fails closed for non-IP strings', () => {
+ expect(isBlockedIp('not-an-ip')).toBe(true);
+ expect(isBlockedIp('')).toBe(true);
+ });
+});
+
+describe('assertSafeFetchTarget', () => {
+ beforeEach(() => mockLookup.mockReset());
+
+ it('rejects non-http(s) schemes', async () => {
+ await expect(assertSafeFetchTarget('file:///etc/passwd')).rejects.toBeInstanceOf(
+ ComposioBlockedInternalUrlError
+ );
+ await expect(assertSafeFetchTarget('ftp://example.com/x')).rejects.toBeInstanceOf(
+ ComposioBlockedInternalUrlError
+ );
+ });
+
+ it('rejects a host that resolves to an internal address', async () => {
+ resolvesTo('169.254.169.254');
+ await expect(assertSafeFetchTarget('http://metadata.internal/latest')).rejects.toBeInstanceOf(
+ ComposioBlockedInternalUrlError
+ );
+ });
+
+ it('rejects when ANY resolved address is internal (DNS pinning bypass)', async () => {
+ resolvesTo('93.184.216.34', '127.0.0.1');
+ await expect(assertSafeFetchTarget('http://evil.example/x')).rejects.toBeInstanceOf(
+ ComposioBlockedInternalUrlError
+ );
+ });
+
+ it('allows a host that resolves only to public addresses', async () => {
+ resolvesTo('93.184.216.34');
+ await expect(assertSafeFetchTarget('https://example.com/file.pdf')).resolves.toBeUndefined();
+ });
+
+ it('blocks an IPv6 literal loopback host', async () => {
+ resolvesTo('::1');
+ await expect(assertSafeFetchTarget('http://[::1]:8080/x')).rejects.toBeInstanceOf(
+ ComposioBlockedInternalUrlError
+ );
+ });
+});
+
+describe('ssrfSafeFetch', () => {
+ const mockFetch = vi.fn();
+
+ beforeEach(() => {
+ mockLookup.mockReset();
+ mockFetch.mockReset();
+ vi.stubGlobal('fetch', mockFetch);
+ });
+ afterEach(() => vi.unstubAllGlobals());
+
+ it('validates and fetches a public URL', async () => {
+ resolvesTo('93.184.216.34');
+ const ok = new Response('data', { status: 200 });
+ mockFetch.mockResolvedValue(ok);
+
+ const res = await ssrfSafeFetch('https://example.com/file.pdf');
+ expect(res.status).toBe(200);
+ expect(mockFetch).toHaveBeenCalledWith(
+ 'https://example.com/file.pdf',
+ expect.objectContaining({ redirect: 'manual' })
+ );
+ });
+
+ it('re-validates redirect hops and blocks a redirect into internal space', async () => {
+ // First host is public; it 302-redirects to an internal metadata endpoint.
+ mockLookup
+ .mockResolvedValueOnce([{ address: '93.184.216.34', family: 4 }] as never)
+ .mockResolvedValueOnce([{ address: '169.254.169.254', family: 4 }] as never);
+ mockFetch.mockResolvedValueOnce(
+ new Response(null, {
+ status: 302,
+ headers: { location: 'http://169.254.169.254/latest/meta-data/' },
+ })
+ );
+
+ await expect(ssrfSafeFetch('https://public.example/redirect')).rejects.toBeInstanceOf(
+ ComposioBlockedInternalUrlError
+ );
+ // Only the first (public) fetch runs; the internal hop is blocked before fetching.
+ expect(mockFetch).toHaveBeenCalledTimes(1);
+ });
+
+ it('throws after exceeding the redirect budget', async () => {
+ resolvesTo('93.184.216.34');
+ mockFetch.mockResolvedValue(
+ new Response(null, { status: 302, headers: { location: 'https://example.com/again' } })
+ );
+
+ await expect(ssrfSafeFetch('https://example.com/start', {}, 2)).rejects.toBeInstanceOf(
+ ComposioBlockedInternalUrlError
+ );
+ });
+});