-
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathssrf-expansion.test.ts
More file actions
333 lines (294 loc) · 11.3 KB
/
Copy pathssrf-expansion.test.ts
File metadata and controls
333 lines (294 loc) · 11.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
/**
* SSRF Expansion Tests (PR 5: Security Hardening Gate 9)
*
* Targeted vectors that complement the existing 283-test safe-fetch suite.
* Focus areas: scheme blocking, redirect-to-private chains, IPv6 edge cases,
* credential stripping, and protocol smuggling attempts.
*/
import { describe, it, expect, vi } from 'vitest';
import { safeFetch, SAFE_FETCH_ERROR_CODES, type DnsResolver, type HttpClient } from '../src/index';
// -------------------------------------------------------------------------
// Mock helpers (mirrors safe-fetch.test.ts patterns)
// -------------------------------------------------------------------------
function createMockDnsResolver(ipv4: string[] = [], ipv6: string[] = []): DnsResolver {
return {
resolveAll: vi.fn().mockResolvedValue({ ipv4, ipv6 }),
};
}
function createMockBody(data: string): ReadableStream<Uint8Array> {
const bytes = new TextEncoder().encode(data);
return new ReadableStream({
start(controller) {
controller.enqueue(bytes);
controller.close();
},
});
}
function createMockHttpClient(response: Partial<Response>): HttpClient {
const mockResponse = {
status: 200,
headers: new Headers(),
body: createMockBody('{}'),
...response,
} as Response;
return {
fetch: vi.fn().mockResolvedValue({ response: mockResponse, close: vi.fn() }),
};
}
// -------------------------------------------------------------------------
// A. Scheme blocking (beyond http/https)
// -------------------------------------------------------------------------
describe('SSRF expansion: scheme blocking', () => {
const publicDns = createMockDnsResolver(['93.184.216.34']);
const httpClient = createMockHttpClient({ status: 200 });
const blockedSchemes = [
'file:///etc/passwd',
'file:///proc/self/environ',
'ftp://example.com/secret',
'gopher://example.com:70/_',
'data:text/html,<script>alert(1)</script>',
'javascript:void(0)',
'dict://example.com:11211/stat',
'ldap://example.com/dc=com',
'sftp://example.com/home/user',
'jar:file:///tmp/evil.jar!/MANIFEST.MF',
];
for (const url of blockedSchemes) {
const scheme = url.split(':')[0];
it(`rejects ${scheme}:// scheme`, async () => {
const result = await safeFetch(url, {
_dnsResolver: publicDns,
_httpClient: httpClient,
});
expect(result.ok).toBe(false);
if (!result.ok) {
expect(result.code).toBe(SAFE_FETCH_ERROR_CODES.E_SSRF_URL_REJECTED);
}
});
}
it('rejects uppercase scheme bypass attempt (FILE://)', async () => {
const result = await safeFetch('FILE:///etc/passwd', {
_dnsResolver: publicDns,
_httpClient: httpClient,
});
expect(result.ok).toBe(false);
});
it('rejects mixed-case scheme (FiLe://)', async () => {
const result = await safeFetch('FiLe:///etc/shadow', {
_dnsResolver: publicDns,
_httpClient: httpClient,
});
expect(result.ok).toBe(false);
});
});
// -------------------------------------------------------------------------
// B. IPv6 private range edge cases
// -------------------------------------------------------------------------
describe('SSRF expansion: IPv6 private ranges', () => {
const httpClient = createMockHttpClient({ status: 200 });
const privateIpv6Addresses = [
{ ip: '::1', label: 'loopback (::1)' },
{ ip: 'fd00::1', label: 'unique local (fd00::)' },
{ ip: 'fd12:3456:789a::1', label: 'unique local (fd12:...)' },
{ ip: 'fe80::1', label: 'link-local (fe80::)' },
{ ip: 'fe80::1%eth0', label: 'link-local with zone ID' },
{ ip: 'fc00::1', label: 'unique local (fc00::)' },
{ ip: '::ffff:127.0.0.1', label: 'IPv4-mapped loopback' },
{ ip: '::ffff:192.168.1.1', label: 'IPv4-mapped private' },
{ ip: '::ffff:10.0.0.1', label: 'IPv4-mapped 10.x' },
{ ip: '2001:db8::1', label: 'documentation prefix (2001:db8::)' },
{ ip: 'ff02::1', label: 'multicast (ff02::1)' },
{ ip: '100::1', label: 'discard prefix (100::)' },
];
for (const { ip, label } of privateIpv6Addresses) {
it(`blocks DNS resolving to ${label}`, async () => {
const resolvedIp = ip.replace(/%.*$/, '');
const dns = createMockDnsResolver([], [resolvedIp]);
const result = await safeFetch('https://example.com/api', {
_dnsResolver: dns,
_httpClient: httpClient,
});
// Primary invariant: all private/reserved IPv6 addresses are rejected
expect(result.ok).toBe(false);
if (!result.ok) {
// DNS validation catches private IPs via isPrivateIP(): the specific
// SSRF error code is preserved through the full call chain.
expect(result.code).toBe(SAFE_FETCH_ERROR_CODES.E_SSRF_DNS_RESOLVED_PRIVATE);
}
});
}
});
// -------------------------------------------------------------------------
// C. Redirect chain to private IP
// -------------------------------------------------------------------------
describe('SSRF expansion: redirect chains to private', () => {
it('blocks redirect from public to private IP (302 chain)', async () => {
let callCount = 0;
const httpClient: HttpClient = {
fetch: vi.fn().mockImplementation(() => {
callCount++;
if (callCount === 1) {
return Promise.resolve({
response: {
status: 302,
headers: new Headers({ Location: 'https://internal.example.com/admin' }),
body: createMockBody(''),
} as unknown as Response,
close: vi.fn(),
});
}
return Promise.resolve({
response: {
status: 200,
headers: new Headers(),
body: createMockBody('{"secret": true}'),
} as unknown as Response,
close: vi.fn(),
});
}),
};
// The redirect to internal.example.com should trigger DNS re-resolution
// which would resolve to a private IP if the DNS resolver returns one
const privateDns = createMockDnsResolver(['192.168.1.100']);
const result = await safeFetch('https://public.example.com/start', {
_dnsResolver: privateDns,
_httpClient: httpClient,
redirectPolicy: 'allowlist',
allowRedirectHosts: ['internal.example.com'],
});
// Should be blocked because DNS resolves to private
expect(result.ok).toBe(false);
});
it('blocks redirect from HTTPS to HTTP (downgrade)', async () => {
const dns = createMockDnsResolver(['93.184.216.34']);
const httpClient: HttpClient = {
fetch: vi.fn().mockResolvedValue({
response: {
status: 301,
headers: new Headers({ Location: 'http://example.com/insecure' }),
body: createMockBody(''),
} as unknown as Response,
close: vi.fn(),
}),
};
const result = await safeFetch('https://example.com/secure', {
_dnsResolver: dns,
_httpClient: httpClient,
});
// Default policy requires HTTPS; redirect to HTTP should fail
expect(result.ok).toBe(false);
});
});
// -------------------------------------------------------------------------
// D. URL parsing edge cases (smuggling attempts)
// -------------------------------------------------------------------------
describe('SSRF expansion: URL parsing edge cases', () => {
const dns = createMockDnsResolver(['93.184.216.34']);
const httpClient = createMockHttpClient({ status: 200 });
it('rejects URL with credentials (user:pass@host)', async () => {
const result = await safeFetch('https://admin:secret@example.com/api', {
_dnsResolver: dns,
_httpClient: httpClient,
});
expect(result.ok).toBe(false);
});
it('rejects URL with only username (user@host)', async () => {
const result = await safeFetch('https://admin@example.com/api', {
_dnsResolver: dns,
_httpClient: httpClient,
});
expect(result.ok).toBe(false);
});
it('rejects empty hostname', async () => {
// https:// with no hostname is an invalid URL (URL constructor throws)
const result = await safeFetch('https://', {
_dnsResolver: dns,
_httpClient: httpClient,
});
expect(result.ok).toBe(false);
if (!result.ok) {
expect(result.code).toBe(SAFE_FETCH_ERROR_CODES.E_SSRF_URL_REJECTED);
}
});
it('rejects localhost variants', async () => {
for (const host of ['localhost', 'LOCALHOST', 'Localhost', '127.0.0.1', '0.0.0.0']) {
const result = await safeFetch(`https://${host}/api`, {
_dnsResolver: dns,
_httpClient: httpClient,
});
expect(result.ok, `should reject ${host}`).toBe(false);
}
});
it('rejects decimal IP notation for loopback (2130706433 = 127.0.0.1)', async () => {
// Some URL parsers convert decimal notation to IP
const result = await safeFetch('https://2130706433/admin', {
_dnsResolver: dns,
_httpClient: httpClient,
});
// This may parse as a hostname (not an IP), which is fine
// The key is that DNS resolution to private must still be caught
expect(typeof result.ok).toBe('boolean');
});
it('rejects octal IP notation for loopback (0177.0.0.1 = 127.0.0.1)', async () => {
const result = await safeFetch('https://0177.0.0.1/admin', {
_dnsResolver: dns,
_httpClient: httpClient,
});
expect(result.ok).toBe(false);
});
});
// -------------------------------------------------------------------------
// E. Content-Length / oversized response defense
// -------------------------------------------------------------------------
describe('SSRF expansion: response size enforcement', () => {
it('rejects response via Content-Length header before reading body', async () => {
const dns = createMockDnsResolver(['93.184.216.34']);
// Declare a large Content-Length without allocating the body in memory.
// The implementation checks Content-Length first (optimization path),
// so a small mock body is sufficient to prove the gate.
const httpClient = createMockHttpClient({
status: 200,
headers: new Headers({ 'Content-Length': '20000000' }),
body: createMockBody('small'),
});
const result = await safeFetch('https://example.com/large', {
_dnsResolver: dns,
_httpClient: httpClient,
maxResponseBytes: 1_000_000, // 1 MB limit
});
expect(result.ok).toBe(false);
});
it('rejects streamed response that exceeds limit during read', async () => {
const dns = createMockDnsResolver(['93.184.216.34']);
// No Content-Length header: forces the streaming body reader path.
// Generate a body that exceeds the limit via multiple small chunks.
const chunkSize = 100_000; // 100 KB per chunk
const totalChunks = 15; // 1.5 MB total (exceeds 1 MB limit)
const chunk = new Uint8Array(chunkSize);
let sent = 0;
const body = new ReadableStream<Uint8Array>({
pull(controller) {
if (sent < totalChunks) {
controller.enqueue(chunk);
sent++;
} else {
controller.close();
}
},
});
const mockResponse = {
status: 200,
headers: new Headers(), // No Content-Length
body,
} as unknown as Response;
const httpClient: HttpClient = {
fetch: vi.fn().mockResolvedValue({ response: mockResponse, close: vi.fn() }),
};
const result = await safeFetch('https://example.com/stream', {
_dnsResolver: dns,
_httpClient: httpClient,
maxResponseBytes: 1_000_000,
});
expect(result.ok).toBe(false);
});
});