-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathconnectProxy.ts
More file actions
357 lines (319 loc) · 9.94 KB
/
Copy pathconnectProxy.ts
File metadata and controls
357 lines (319 loc) · 9.94 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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
*--------------------------------------------------------------------------------------------*/
import fs from "fs";
import http from "http";
import net from "net";
import os from "os";
import path from "path";
import tls from "tls";
import {
type CaData,
createSecureContextForHost,
generateCA,
} from "./certUtils";
const debugLogPath = process.env.E2E_PROXY_DEBUG
? path.join(os.tmpdir(), `e2e-proxy-debug-${process.pid}.log`)
: undefined;
function debugLog(msg: string): void {
if (debugLogPath) {
fs.appendFileSync(
debugLogPath,
`[${new Date().toISOString()}] [connect] ${msg}\n`,
);
}
}
export type RequestHandler = (
req: http.IncomingMessage,
res: http.ServerResponse,
targetHost: string,
) => boolean | Promise<boolean>;
export class ConnectProxy {
private proxyServer?: http.Server;
private internalServer?: http.Server;
private ca?: CaData;
private certCache = new Map<string, tls.SecureContext>();
private _caFilePath?: string;
private _proxyUrl?: string;
private _connectLog: Array<{
host: string;
port: string;
timestamp: number;
}> = [];
private interceptDomains: Set<string>;
private passthroughDomains: Set<string>;
private onBlockedConnection?: (host: string, port: string) => void;
private openSockets = new Set<net.Socket>();
constructor(
private handler: RequestHandler,
options?: {
interceptDomains?: string[];
passthroughDomains?: string[];
onBlockedConnection?: (host: string, port: string) => void;
},
) {
this.interceptDomains = new Set(options?.interceptDomains ?? []);
this.passthroughDomains = new Set(options?.passthroughDomains ?? []);
this.onBlockedConnection = options?.onBlockedConnection;
}
get proxyUrl(): string {
if (!this._proxyUrl) {
throw new Error("ConnectProxy not started");
}
return this._proxyUrl;
}
get caFilePath(): string {
if (!this._caFilePath) {
throw new Error("ConnectProxy not started");
}
return this._caFilePath;
}
get connectLog(): ReadonlyArray<{
host: string;
port: string;
timestamp: number;
}> {
return this._connectLog;
}
async start(): Promise<void> {
this.ca = generateCA();
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "e2e-proxy-ca-"));
fs.writeFileSync(path.join(tmpDir, "test-ca.pem"), this.ca.certPem);
this._caFilePath = path.join(tmpDir, "test-ca-bundle.pem");
fs.writeFileSync(
this._caFilePath,
[...tls.rootCertificates, this.ca.certPem].join("\n"),
);
this.internalServer = http.createServer((req, res) => {
const socket = req.socket as tls.TLSSocket & { _connectTarget?: string };
const targetHost = socket._connectTarget ?? req.headers.host ?? "unknown";
void Promise.resolve(this.handler(req, res, targetHost))
.then((handled) => {
if (!handled && !res.headersSent) {
res.writeHead(502, { "content-type": "text/plain" });
res.end(
`E2E proxy: no handler for ${req.method} ${targetHost}${req.url}`,
);
}
})
.catch((err) => {
console.warn(
`[E2E proxy] handler error for ${req.method} ${targetHost}${req.url}: ${err}`,
);
if (!res.headersSent) {
res.writeHead(502, { "content-type": "text/plain" });
res.end("E2E proxy: handler error");
}
});
});
this.proxyServer = http.createServer((req, res) => {
this.handleForwardProxy(req, res);
});
this.proxyServer.on("connect", (req, clientSocket, head) => {
this.handleConnect(req, clientSocket as net.Socket, head);
});
await new Promise<void>((resolve, reject) => {
this.proxyServer!.on("error", reject);
this.proxyServer!.listen(0, "127.0.0.1", () => resolve());
});
const addr = this.proxyServer.address() as net.AddressInfo;
this._proxyUrl = `http://${addr.address}:${addr.port}`;
}
async stop(): Promise<void> {
for (const socket of this.openSockets) {
socket.destroy();
}
this.openSockets.clear();
const closeServer = (server?: http.Server) =>
new Promise<void>((resolve) => {
if (!server) {
resolve();
return;
}
server.close(() => resolve());
});
await Promise.all([
closeServer(this.proxyServer),
closeServer(this.internalServer),
]);
if (this._caFilePath) {
try {
fs.rmSync(path.dirname(this._caFilePath), {
recursive: true,
force: true,
});
} catch {
// Best-effort cleanup.
}
}
}
private handleConnect(
req: http.IncomingMessage,
clientSocket: net.Socket,
head: Buffer,
) {
const { host, port } = parseConnectTarget(req.url ?? "");
debugLog(`CONNECT ${host}:${port}`);
if (!host) {
clientSocket.write("HTTP/1.1 400 Bad Request\r\n\r\n");
clientSocket.destroy();
return;
}
this._connectLog.push({ host, port, timestamp: Date.now() });
if (this.passthroughDomains.has(host)) {
this.pipeToRealTarget(clientSocket, head, host, port);
return;
}
if (!this.interceptDomains.has(host)) {
this.onBlockedConnection?.(host, port);
clientSocket.write("HTTP/1.1 502 Blocked by E2E proxy\r\n\r\n");
clientSocket.destroy();
return;
}
clientSocket.write("HTTP/1.1 200 Connection Established\r\n\r\n");
const tlsSocket = new tls.TLSSocket(clientSocket, {
isServer: true,
secureContext: this.getOrCreateSecureContext(host),
ALPNProtocols: ["http/1.1"],
});
this.openSockets.add(clientSocket);
this.openSockets.add(tlsSocket);
let cleaned = false;
const cleanup = () => {
if (cleaned) {
return;
}
cleaned = true;
tlsSocket.off("close", cleanup);
clientSocket.off("close", cleanup);
tlsSocket.off("error", onTlsError);
clientSocket.off("error", onClientError);
this.openSockets.delete(clientSocket);
this.openSockets.delete(tlsSocket);
};
const onTlsError = (err: Error) => {
debugLog(`TLS error for ${host}: ${err.message}`);
cleanup();
clientSocket.destroy();
};
const onClientError = () => {
cleanup();
tlsSocket.destroy();
};
tlsSocket.on("close", cleanup);
clientSocket.on("close", cleanup);
tlsSocket.on("error", onTlsError);
clientSocket.on("error", onClientError);
(tlsSocket as tls.TLSSocket & { _connectTarget?: string })._connectTarget =
host;
if (head.length > 0) {
tlsSocket.unshift(head);
}
this.internalServer!.emit("connection", tlsSocket);
}
private handleForwardProxy(
req: http.IncomingMessage,
res: http.ServerResponse,
) {
let targetHost: string;
try {
const url = new URL(req.url ?? "");
targetHost = url.hostname;
req.url = url.pathname + url.search;
} catch {
targetHost = req.headers.host ?? "unknown";
}
void Promise.resolve(this.handler(req, res, targetHost))
.then((handled) => {
if (!handled && !res.headersSent) {
res.writeHead(502, { "content-type": "text/plain" });
res.end(
`E2E proxy: no handler for HTTP ${req.method} ${targetHost}${req.url}`,
);
}
})
.catch(() => {
if (!res.headersSent) {
res.writeHead(502, { "content-type": "text/plain" });
res.end("E2E proxy: handler error");
}
});
}
private getOrCreateSecureContext(hostname: string): tls.SecureContext {
let context = this.certCache.get(hostname);
if (!context) {
context = createSecureContextForHost(hostname, this.ca!);
this.certCache.set(hostname, context);
}
return context;
}
private pipeToRealTarget(
clientSocket: net.Socket,
head: Buffer,
host: string,
port: string,
) {
const targetSocket = net.connect(Number.parseInt(port, 10), host, () => {
if (clientSocket.destroyed || targetSocket.destroyed) {
return;
}
clientSocket.write("HTTP/1.1 200 Connection Established\r\n\r\n");
if (head.length > 0) {
targetSocket.write(head);
}
clientSocket.pipe(targetSocket);
targetSocket.pipe(clientSocket);
});
this.openSockets.add(clientSocket);
this.openSockets.add(targetSocket);
let cleaned = false;
const cleanup = () => {
if (cleaned) {
return;
}
cleaned = true;
clientSocket.off("error", cleanup);
clientSocket.off("close", cleanup);
targetSocket.off("error", cleanup);
targetSocket.off("close", cleanup);
clientSocket.destroy();
targetSocket.destroy();
this.openSockets.delete(clientSocket);
this.openSockets.delete(targetSocket);
};
clientSocket.on("error", cleanup);
clientSocket.on("close", cleanup);
targetSocket.on("error", cleanup);
targetSocket.on("close", cleanup);
}
}
export function parseConnectTarget(authority: string): {
host: string;
port: string;
} {
if (!authority) {
return { host: "", port: "" };
}
if (authority.startsWith("[")) {
const closeBracket = authority.indexOf("]");
if (closeBracket === -1) {
return { host: "", port: "" };
}
const host = authority.slice(1, closeBracket);
const afterBracket = authority.slice(closeBracket + 1);
if (afterBracket === "" || afterBracket === ":") {
return { host, port: "443" };
}
if (afterBracket[0] !== ":") {
return { host: "", port: "" };
}
return { host, port: afterBracket.slice(1) || "443" };
}
const lastColon = authority.lastIndexOf(":");
if (lastColon === -1) {
return { host: authority, port: "443" };
}
const host = authority.slice(0, lastColon);
const port = authority.slice(lastColon + 1) || "443";
return { host, port };
}