Skip to content

7.4 billion tokens per month. 34 free LLM providers. 635 free model endpoints. All behind one /v1 endpoint, plus any custom OpenAI-compatible endpoint. Smart routing, automatic failover, encrypted keys. Personal experimentation only.

TypeScript

fix(security): close two bypasses in the custom-provider SSRF guard (#440) (#450)

Tashfeenbea85a24d0d4
diff --git a/server/src/__tests__/lib/proxy.test.ts b/server/src/__tests__/lib/proxy.test.ts
index 73f63fce..4a8583e5 100644
--- a/server/src/__tests__/lib/proxy.test.ts
+++ b/server/src/__tests__/lib/proxy.test.ts
@@ -99,6 +99,62 @@ describe('proxyFetch routing', () => {
});
});
+// SSRF guard, request-time half (#440). The save-time check validates the
+// literal base_url, but fetch()'s default redirect: 'follow' would re-request
+// a 3xx Location target with no re-validation — a public base_url answering
+// 302 → http://169.254.169.254/ used to defeat the guard entirely. Custom
+// providers therefore never follow redirects; the 3xx becomes an explicit
+// error naming the target so the operator can fix base_url.
+describe('proxyFetch custom-provider redirect guard', () => {
+ const redirectResponse = (status: number, location?: string) =>
+ ({ ok: false, status, headers: new Headers(location ? { location } : {}) }) as Response;
+
+ it('forces redirect: "manual" on custom-provider requests', async () => {
+ const spy = vi.spyOn(global, 'fetch').mockResolvedValue(okResponse());
+ await proxyFetch('http://93.184.216.34/v1/chat/completions', { method: 'POST' }, 'custom');
+ const [, init] = spy.mock.calls[0];
+ expect((init as any)?.redirect).toBe('manual');
+ });
+
+ it('rejects a custom-provider 302 instead of following it', async () => {
+ const spy = vi.spyOn(global, 'fetch').mockResolvedValue(
+ redirectResponse(302, 'http://169.254.169.254/latest/meta-data/'),
+ );
+ await expect(proxyFetch('http://93.184.216.34/v1', { method: 'POST' }, 'custom'))
+ .rejects.toThrow(/redirects are not followed/);
+ // The Location target is never requested.
+ expect(spy).toHaveBeenCalledTimes(1);
+ });
+
+ it('rejects every redirect status the same way', async () => {
+ for (const status of [301, 303, 307, 308]) {
+ vi.spyOn(global, 'fetch').mockResolvedValue(redirectResponse(status, 'http://10.0.0.1/'));
+ await expect(proxyFetch('http://93.184.216.34/v1', undefined, 'custom'))
+ .rejects.toThrow(new RegExp(`redirected \\(${status}\\)`));
+ }
+ });
+
+ it('names the redirect target in the error so the operator can fix base_url', async () => {
+ vi.spyOn(global, 'fetch').mockResolvedValue(redirectResponse(301, 'https://api.example.com/v1/'));
+ await expect(proxyFetch('http://93.184.216.34/v1', undefined, 'custom'))
+ .rejects.toThrow(/https:\/\/api\.example\.com\/v1\//);
+ });
+
+ it('passes 3xx responses through untouched for built-in platforms', async () => {
+ vi.spyOn(global, 'fetch').mockResolvedValue(redirectResponse(302, 'https://elsewhere.example.com/'));
+ const res = await proxyFetch('https://api.example.com/v1', undefined, 'groq');
+ expect(res.status).toBe(302);
+ });
+
+ it('blocks hex-form IPv4-mapped metadata literals before any fetch happens', async () => {
+ // new URL() canonicalises [::ffff:169.254.169.254] to [::ffff:a9fe:a9fe].
+ const spy = vi.spyOn(global, 'fetch').mockResolvedValue(okResponse());
+ await expect(proxyFetch('http://[::ffff:169.254.169.254]/latest/', undefined, 'custom'))
+ .rejects.toThrow(/metadata/);
+ expect(spy).not.toHaveBeenCalled();
+ });
+});
+
// Compact abort-error triage tag formatting. The string written to
// `requests.error` is `The operation was aborted (<platform>, <type>, <N>s)`
// — round-trip what's already on the row so an operator can read the abort
diff --git a/server/src/__tests__/lib/url-guard.test.ts b/server/src/__tests__/lib/url-guard.test.ts
index 7ebb615f..05bdc46d 100644
--- a/server/src/__tests__/lib/url-guard.test.ts
+++ b/server/src/__tests__/lib/url-guard.test.ts
@@ -46,6 +46,24 @@ describe('classifyIp', () => {
expect(classifyIp('::ffff:169.254.169.254')).toBe('metadata'); // mapped
expect(classifyIp('::ffff:8.8.8.8')).toBe('public');
});
+
+ it('classifies IPv4-mapped IPv6 in hex form (what the WHATWG URL parser emits)', () => {
+ // new URL('http://[::ffff:169.254.169.254]/').hostname === '[::ffff:a9fe:a9fe]'
+ // — the dotted form never reaches classifyIp from a URL, only this one.
+ expect(classifyIp('::ffff:a9fe:a9fe')).toBe('metadata'); // 169.254.169.254
+ expect(classifyIp('::ffff:7f00:1')).toBe('loopback'); // 127.0.0.1
+ expect(classifyIp('::ffff:a00:1')).toBe('private'); // 10.0.0.1
+ expect(classifyIp('::ffff:808:808')).toBe('public'); // 8.8.8.8
+ expect(classifyIp('0:0:0:0:0:ffff:a9fe:a9fe')).toBe('metadata'); // uncompressed
+ });
+
+ it('classifies NAT64, IPv4-compatible, and alternate-spelling metadata addresses', () => {
+ expect(classifyIp('64:ff9b::a9fe:a9fe')).toBe('metadata'); // NAT64 → 169.254.169.254
+ expect(classifyIp('64:ff9b::808:808')).toBe('public'); // NAT64 → 8.8.8.8
+ expect(classifyIp('::a9fe:a9fe')).toBe('metadata'); // deprecated v4-compatible form
+ expect(classifyIp('192.0.0.192')).toBe('metadata'); // Oracle Cloud legacy IMDS
+ expect(classifyIp('fd00:0ec2:0:0:0:0:0:0254')).toBe('metadata'); // AWS IMDS, uncompressed
+ });
});
describe('assessProviderUrl', () => {
@@ -66,6 +84,13 @@ describe('assessProviderUrl', () => {
expect(verdict.reason).toMatch(/metadata/);
});
+ it('blocks bracketed IPv4-mapped metadata literals end to end', async () => {
+ // The parser rewrites this hostname to the hex form ::ffff:a9fe:a9fe.
+ const verdict = await assessProviderUrl('http://[::ffff:169.254.169.254]/latest/meta-data/');
+ expect(verdict.allowed).toBe(false);
+ expect(verdict.reason).toMatch(/metadata/);
+ });
+
it('blocks hostnames that resolve to metadata or link-local addresses', async () => {
const verdict = await assessProviderUrl('http://innocent.example.com/v1', {
resolve: async () => ['169.254.169.254'],
diff --git a/server/src/lib/proxy.ts b/server/src/lib/proxy.ts
index 175d2a30..6c5e15e2 100644
--- a/server/src/lib/proxy.ts
+++ b/server/src/lib/proxy.ts
@@ -315,6 +315,8 @@ function socksFetch(
* to `undefined` / `'unknown'` when callers haven't been updated yet —
* the abort still fires, it just omits the unknown fields.
*/
+const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
+
export async function proxyFetch(
url: string,
init?: RequestInit,
@@ -330,27 +332,26 @@ export async function proxyFetch(
// metadata / link-local addresses.
if (platform === 'custom') {
await assertProviderUrlAllowed(url);
+ // Redirects are never followed for custom providers: fetch()'s default
+ // 'follow' would re-request the Location target WITHOUT re-running the
+ // guard above, so a public base_url answering 302 → an internal or
+ // metadata address would defeat the check. socksFetch (http.request)
+ // never followed redirects; forcing redirect: 'manual' here makes every
+ // path behave the same, and the 3xx is converted to an explicit error
+ // below so the operator sees why instead of a confusing empty body.
+ init = { ...init, redirect: 'manual' };
}
- // Bypass check: disabled globally, or this platform is exempt.
- if (shouldBypassProxy(platform)) {
- return await fetch(url, init);
- }
-
- const resolved = await resolveDispatcher();
-
- // No dispatcher (no proxy URL configured, or it failed to build) → direct
- if (!resolved) {
- return await fetch(url, init);
- }
+ const response = await dispatchFetch(url, init, platform, requestType, timeoutMs);
- // SOCKS proxy → http/https fallback
- if (resolved.isSocks) {
- return await socksFetch(url, init, resolved.dispatcher as http.Agent, platform, requestType, timeoutMs);
+ if (platform === 'custom' && REDIRECT_STATUSES.has(response.status)) {
+ const location = response.headers.get('location') ?? 'an unspecified location';
+ throw new Error(
+ `Custom provider URL blocked: upstream redirected (${response.status}) to ${location}; ` +
+ 'redirects are not followed for custom providers, point base_url directly at the API',
+ );
}
-
- // HTTP/HTTPS proxy → undici (dispatcher is an undici extension not in TS types)
- return await fetch(url, { ...init, dispatcher: resolved.dispatcher } as unknown as RequestInit);
+ return response;
} catch (err) {
// Rewrite bare "The operation was aborted" rejections so they carry the
// compact triage tag. Preserves the AbortError name so
@@ -359,6 +360,35 @@ export async function proxyFetch(
}
}
+/** Route the request through the configured proxy (or straight to fetch). */
+async function dispatchFetch(
+ url: string,
+ init: RequestInit | undefined,
+ platform: string | undefined,
+ requestType: ProxyRequestType,
+ timeoutMs: number | undefined,
+): Promise<Response> {
+ // Bypass check: disabled globally, or this platform is exempt.
+ if (shouldBypassProxy(platform)) {
+ return fetch(url, init);
+ }
+
+ const resolved = await resolveDispatcher();
+
+ // No dispatcher (no proxy URL configured, or it failed to build) → direct
+ if (!resolved) {
+ return fetch(url, init);
+ }
+
+ // SOCKS proxy → http/https fallback
+ if (resolved.isSocks) {
+ return socksFetch(url, init, resolved.dispatcher as http.Agent, platform, requestType, timeoutMs);
+ }
+
+ // HTTP/HTTPS proxy → undici (dispatcher is an undici extension not in TS types)
+ return fetch(url, { ...init, dispatcher: resolved.dispatcher } as unknown as RequestInit);
+}
+
/**
* Returns true when the proxy is configured AND enabled. Used by the dashboard
* to show the "Active" badge. Intentionally does NOT construct a dispatcher (so
diff --git a/server/src/lib/url-guard.ts b/server/src/lib/url-guard.ts
index 79625b1f..6dd24d56 100644
--- a/server/src/lib/url-guard.ts
+++ b/server/src/lib/url-guard.ts
@@ -23,6 +23,11 @@ import net from 'node:net';
// instances hosted on a VPS where the dashboard is exposed).
// - Everything else (public addresses): allowed.
//
+// Related: proxyFetch refuses HTTP redirects from custom providers outright —
+// following one would re-request the Location target without re-running this
+// guard, so a public base_url answering 302 → an internal address would
+// otherwise defeat every check in this file.
+//
// Known limitation: hostnames are resolved and classified here, but the
// actual fetch re-resolves DNS, so a hostile authoritative DNS server could
// still rebind between check and use. Pinning the resolved address into the
@@ -37,12 +42,16 @@ const METADATA_HOSTNAMES = new Set([
'metadata.goog',
]);
-// Exact metadata addresses that sit outside the link-local range.
+// Exact IPv4 metadata addresses that sit outside the link-local range.
const METADATA_ADDRESSES = new Set([
'100.100.100.200', // Alibaba Cloud IMDS
- 'fd00:ec2::254', // AWS IMDSv2 IPv6
+ '192.0.0.192', // Oracle Cloud legacy IMDS
]);
+// AWS IMDSv2 IPv6 (fd00:ec2::254) as its eight expanded hextets, so every
+// spelling (compressed, uncompressed, zero-padded) matches.
+const AWS_IMDS_V6 = [0xfd00, 0x0ec2, 0, 0, 0, 0, 0, 0x0254];
+
function classifyIpv4(ip: string): AddressClass {
const octets = ip.split('.').map(Number);
const [a, b] = octets;
@@ -59,17 +68,59 @@ function classifyIpv4(ip: string): AddressClass {
return 'public';
}
+/**
+ * Expand an IPv6 literal into its eight 16-bit hextets. Handles `::`
+ * compression, an embedded dotted-IPv4 tail (::ffff:169.254.169.254), and
+ * zone ids. Returns null for anything that isn't a well-formed address.
+ */
+function expandIpv6(ip: string): number[] | null {
+ let s = ip.toLowerCase();
+ const zone = s.indexOf('%');
+ if (zone !== -1) s = s.slice(0, zone);
+ const lastColon = s.lastIndexOf(':');
+ if (s.indexOf('.', lastColon) !== -1) {
+ // Dotted-IPv4 tail → fold into the last two hextets.
+ const octets = s.slice(lastColon + 1).split('.').map(Number);
+ if (octets.length !== 4 || octets.some((o) => !Number.isInteger(o) || o < 0 || o > 255)) return null;
+ s = s.slice(0, lastColon + 1)
+ + ((octets[0] << 8) | octets[1]).toString(16) + ':'
+ + ((octets[2] << 8) | octets[3]).toString(16);
+ }
+ const halves = s.split('::');
+ if (halves.length > 2) return null;
+ const head = halves[0] ? halves[0].split(':') : [];
+ const tail = halves.length === 2 && halves[1] ? halves[1].split(':') : [];
+ const fill = 8 - head.length - tail.length;
+ if (halves.length === 2 ? fill < 0 : fill !== 0) return null;
+ const groups = [...head, ...new Array(halves.length === 2 ? fill : 0).fill('0'), ...tail];
+ if (groups.length !== 8 || groups.some((g) => !/^[0-9a-f]{1,4}$/.test(g))) return null;
+ return groups.map((g) => parseInt(g, 16));
+}
+
function classifyIpv6(ip: string): AddressClass {
- const lower = ip.toLowerCase();
- // IPv4-mapped (::ffff:a.b.c.d) — classify the embedded IPv4.
- const mapped = lower.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/);
- if (mapped) return classifyIpv4(mapped[1]);
- if (METADATA_ADDRESSES.has(lower)) return 'metadata';
- if (lower === '::1' || lower === '::') return 'loopback';
- const firstHextet = lower.split(':')[0] || '0';
- const value = parseInt(firstHextet.padStart(4, '0'), 16);
- if ((value & 0xffc0) === 0xfe80) return 'link-local'; // fe80::/10
- if ((value & 0xfe00) === 0xfc00) return 'private'; // fc00::/7 (ULA)
+ const hextets = expandIpv6(ip);
+ // net.isIP already vetted the input, so this branch is unreachable in
+ // practice — but an unparseable address must not classify as public.
+ if (!hextets) return 'link-local';
+ const [h0, h1, h2, h3, h4, h5, h6, h7] = hextets;
+ const embedded = `${h6 >> 8}.${h6 & 0xff}.${h7 >> 8}.${h7 & 0xff}`;
+ if (h0 === 0 && h1 === 0 && h2 === 0 && h3 === 0 && h4 === 0) {
+ // ::ffff:0:0/96 (IPv4-mapped) and ::/96 (deprecated IPv4-compatible,
+ // which also covers :: and ::1 → 0.0.0.0 / 0.0.0.1 → loopback). The
+ // WHATWG URL parser canonicalises mapped literals to the HEX form —
+ // http://[::ffff:169.254.169.254]/ parses to hostname ::ffff:a9fe:a9fe —
+ // so classification must go through the expanded hextets; a dotted-form
+ // string match never fires on URL-sourced hostnames.
+ if (h5 === 0xffff || h5 === 0) return classifyIpv4(embedded);
+ }
+ // NAT64 well-known prefix (64:ff9b::/96) — a NAT64 gateway would route
+ // this straight to the embedded IPv4.
+ if (h0 === 0x64 && h1 === 0xff9b && h2 === 0 && h3 === 0 && h4 === 0 && h5 === 0) {
+ return classifyIpv4(embedded);
+ }
+ if (AWS_IMDS_V6.every((h, i) => h === hextets[i])) return 'metadata';
+ if ((h0 & 0xffc0) === 0xfe80) return 'link-local'; // fe80::/10
+ if ((h0 & 0xfe00) === 0xfc00) return 'private'; // fc00::/7 (ULA)
return 'public';
}