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

next
ts 187 lines 6.6 KB
Raw
1 import { describe, it, expect, afterEach } from 'vitest';
2 import { createServer, type Server } from 'node:http';
3 import { getDefaultAutoSelectFamily, setDefaultAutoSelectFamily, type AddressInfo } from 'node:net';
4 import { Agent, ProxyAgent, getGlobalDispatcher, setGlobalDispatcher } from 'undici';
5 import {
6 createPinnedDispatcher,
7 hasCustomGlobalDispatcher,
8 pinnedHttpFetch,
9 } from '../../src/utils/pinnedDispatcher.node';
10
11 /**
12 * The SSRF guard resolves a hostname to validate it. If `fetch` then resolves
13 * that hostname again to open the socket, the two answers can differ — a
14 * short-TTL record can answer publicly for the check and internally for the
15 * connect (DNS rebinding, issue #4151).
16 *
17 * These tests use a real server and a hostname under `.invalid`, which RFC 2606
18 * guarantees never resolves. A request that arrives at the server therefore
19 * proves the connect used the pinned address and never consulted DNS — which is
20 * exactly the property that closes the rebinding window.
21 */
22 describe('createPinnedDispatcher', () => {
23 let server: Server | undefined;
24 const hosts: string[] = [];
25
26 const startServer = async (): Promise<number> => {
27 server = createServer((request, response) => {
28 hosts.push(request.headers.host ?? '');
29 response.writeHead(200, { 'content-type': 'text/plain' });
30 response.end('pinned payload');
31 });
32 await new Promise<void>(resolve => server!.listen(0, '127.0.0.1', resolve));
33 return (server!.address() as AddressInfo).port;
34 };
35
36 afterEach(async () => {
37 hosts.length = 0;
38 if (server) {
39 await new Promise<void>(resolve => server!.close(() => resolve()));
40 server = undefined;
41 }
42 });
43
44 it('connects to the pinned address instead of resolving the hostname', async () => {
45 const port = await startServer();
46 const dispatcher = await createPinnedDispatcher(['127.0.0.1']);
47
48 const response = await fetch(`http://pinned.invalid:${port}/payload`, {
49 dispatcher,
50 } as RequestInit);
51
52 expect(response.status).toBe(200);
53 expect(await response.text()).toBe('pinned payload');
54 await dispatcher.close();
55 });
56
57 it('leaves the hostname on the wire, so Host and TLS SNI are unchanged', async () => {
58 const port = await startServer();
59 const dispatcher = await createPinnedDispatcher(['127.0.0.1']);
60
61 await fetch(`http://pinned.invalid:${port}/payload`, { dispatcher } as RequestInit);
62
63 // Pinning by rewriting the URL to the IP would send `Host: 127.0.0.1` and
64 // offer the IP as SNI, failing certificate verification against every
65 // origin whose certificate names a hostname.
66 expect(hosts).toEqual([`pinned.invalid:${port}`]);
67 await dispatcher.close();
68 });
69
70 it('is the only reason the request lands: unpinned, the hostname does not resolve', async () => {
71 const port = await startServer();
72
73 await expect(fetch(`http://pinned.invalid:${port}/payload`)).rejects.toThrow();
74 expect(hosts).toEqual([]);
75 });
76
77 it('pins just as well with Happy Eyeballs off, which asks for one address', async () => {
78 // Node calls the lookup with `all: false` here and expects a single
79 // address rather than a list. A host that disables auto-select-family —
80 // a common workaround for Happy Eyeballs stalls — would otherwise get
81 // `ERR_INVALID_IP_ADDRESS` on every SDK fetch.
82 const port = await startServer();
83 const previous = getDefaultAutoSelectFamily();
84 setDefaultAutoSelectFamily(false);
85
86 try {
87 const dispatcher = await createPinnedDispatcher(['127.0.0.1']);
88 const response = await fetch(`http://pinned.invalid:${port}/payload`, {
89 dispatcher,
90 } as RequestInit);
91
92 expect(response.status).toBe(200);
93 expect(await response.text()).toBe('pinned payload');
94 await dispatcher.close();
95 } finally {
96 setDefaultAutoSelectFamily(previous);
97 }
98 });
99 });
100
101 describe('pinnedHttpFetch', () => {
102 let server: Server | undefined;
103
104 afterEach(async () => {
105 if (server) {
106 await new Promise<void>(resolve => server!.close(() => resolve()));
107 server = undefined;
108 }
109 });
110
111 it('connects to a validated address while preserving the original host', async () => {
112 let receivedHost = '';
113 let receivedBody = '';
114 let receivedContentLength = '';
115 server = createServer((request, response) => {
116 receivedHost = request.headers.host ?? '';
117 receivedContentLength = request.headers['content-length'] ?? '';
118 request.setEncoding('utf8');
119 request.on('data', chunk => {
120 receivedBody += chunk;
121 });
122 request.on('end', () => {
123 response.writeHead(200, { 'content-type': 'text/plain' });
124 response.end('pinned payload');
125 });
126 });
127 await new Promise<void>(resolve => server!.listen(0, '127.0.0.1', resolve));
128 const port = (server.address() as AddressInfo).port;
129
130 const response = await pinnedHttpFetch(
131 `http://pinned.invalid:${port}/payload`,
132 { method: 'PUT', body: 'upload body' },
133 ['127.0.0.1']
134 );
135
136 expect(response.status).toBe(200);
137 expect(await response.text()).toBe('pinned payload');
138 expect(receivedHost).toBe(`pinned.invalid:${port}`);
139 expect(receivedBody).toBe('upload body');
140 expect(receivedContentLength).toBe('11');
141 });
142
143 it('does not add Content-Length to a request without a body', async () => {
144 let receivedContentLength: string | undefined;
145 server = createServer((request, response) => {
146 receivedContentLength = request.headers['content-length'];
147 response.end('ok');
148 });
149 await new Promise<void>(resolve => server!.listen(0, '127.0.0.1', resolve));
150 const port = (server.address() as AddressInfo).port;
151
152 const response = await pinnedHttpFetch(
153 `http://pinned.invalid:${port}/payload`,
154 { method: 'GET' },
155 ['127.0.0.1']
156 );
157
158 expect(await response.text()).toBe('ok');
159 expect(receivedContentLength).toBeUndefined();
160 });
161 });
162
163 describe('hasCustomGlobalDispatcher', () => {
164 it('reports the stock dispatcher as not custom', () => {
165 expect(hasCustomGlobalDispatcher()).toBe(false);
166 });
167
168 it('reports a configured proxy dispatcher as custom', () => {
169 const previous = getGlobalDispatcher();
170 setGlobalDispatcher(new ProxyAgent({ uri: 'http://127.0.0.1:9' }));
171 try {
172 expect(hasCustomGlobalDispatcher()).toBe(true);
173 } finally {
174 setGlobalDispatcher(previous);
175 }
176 });
177
178 it('still calls a plain Agent stock, even when created by this package', () => {
179 const previous = getGlobalDispatcher();
180 setGlobalDispatcher(new Agent());
181 try {
182 expect(hasCustomGlobalDispatcher()).toBe(false);
183 } finally {
184 setGlobalDispatcher(previous);
185 }
186 });
187 });