UNPKG

2.97 kBJavaScriptView Raw
1var http = require('http');
2var https = require('https');
3var net = require('net');
4var fs = require('fs');
5var path = require('path');
6var should = require('should');
7var tunnel = require('../index');
8
9function readPem(file) {
10 return fs.readFileSync(path.join('test/keys', file + '.pem'));
11}
12
13describe('HTTP over HTTPS', function() {
14 it('should finish without error', function(done) {
15 var serverPort = 3002;
16 var proxyPort = 3003;
17 var poolSize = 3;
18 var N = 10;
19 var serverConnect = 0;
20 var proxyConnect = 0;
21 var clientConnect = 0;
22 var agent;
23
24 var server = http.createServer(function(req, res) {
25 ++serverConnect;
26
27 res.writeHead(200);
28 res.end('Hello' + req.url);
29 });
30 server.listen(serverPort, function() {
31 var proxy = https.createServer({
32 key: readPem('agent4-key'),
33 cert: readPem('agent4-cert'),
34 ca: [readPem('ca2-cert')], // ca for agent3
35 requestCert: true,
36 rejectUnauthorized: true
37 }, function(req, res) {
38 should.fail();
39 });
40 proxy.on('connect', function(req, clientSocket, head) {
41 req.method.should.equal('CONNECT');
42 req.url.should.equal('localhost:' + serverPort);
43 ++proxyConnect;
44
45 var serverSocket = net.connect(serverPort, function() {
46 clientSocket.write('HTTP/1.1 200 Connection established\r\n\r\n');
47 clientSocket.pipe(serverSocket);
48 serverSocket.write(head);
49 serverSocket.pipe(clientSocket);
50 // workaround, see joyent/node#2524
51 serverSocket.on('end', function() {
52 clientSocket.end();
53 });
54 });
55 });
56 proxy.listen(proxyPort, function() {
57 agent = tunnel.httpOverHttps({
58 maxSockets: poolSize,
59 proxy: {
60 port: proxyPort,
61 // client certification for proxy
62 key: readPem('agent3-key'),
63 cert: readPem('agent3-cert')
64 }
65 });
66
67 for (var i = 0; i < N; ++i) {
68 (function(i) {
69 var req = http.get({
70 port: serverPort,
71 path: '/' + i,
72 agent: agent
73 }, function(res) {
74 res.setEncoding('utf8');
75 res.on('data', function(data) {
76 data.should.equal('Hello/' + i);
77 });
78 res.on('end', function() {
79 ++clientConnect;
80 if (clientConnect === N) {
81 proxy.close();
82 server.close();
83 }
84 });
85 });
86 })(i);
87 }
88 });
89 });
90
91 server.on('close', function() {
92 serverConnect.should.equal(N);
93 proxyConnect.should.equal(poolSize);
94 clientConnect.should.equal(N);
95
96 var name = 'localhost:' + serverPort;
97 agent.sockets.should.not.have.ownProperty(name);
98 agent.requests.should.not.have.ownProperty(name);
99
100 done();
101 });
102 });
103});