Commit bf68dc30 authored by indexzero's avatar indexzero

[api test doc] Improve HTTPS support. Update minor documentation. Change tests accordingly.

parent 4d18ac1a
/*
basic-proxy-https.js: Basic example of proxying over HTTPS
Copyright (c) 2010 Charlie Robbins, Mikeal Rogers, Fedor Indutny, & Marak Squires.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
var https = require('https'),
http = require('http'),
util = require('util'),
colors = require('colors'),
httpProxy = require('./../lib/node-http-proxy'),
helpers = require('./../test/helpers');
var opts = helpers.loadHttps();
//
// Crete the target HTTPS server
//
https.createServer(opts, function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.write('hello https\n');
res.end();
}).listen(8000);
//
// Create the proxy server listening on port 443.
//
httpProxy.createServer(443, 'localhost', {
https: opts,
}).listen(8080);
util.puts('https proxy server'.blue + ' started '.green.bold + 'on port '.blue + '8000'.yellow);
util.puts('https server '.blue + 'started '.green.bold + 'on port '.blue + '8080 '.yellow);
\ No newline at end of file
/*
demo.js: http proxy for node.js
basic-proxy.js: Basic example of proxying over HTTP
Copyright (c) 2010 Charlie Robbins, Mikeal Rogers, Fedor Indutny, & Marak Squires.
......
/*
demo.js: http proxy for node.js
forward-proxy.js: Example of proxying over HTTP with additional forward proxy
Copyright (c) 2010 Charlie Robbins, Mikeal Rogers, Fedor Indutny, & Marak Squires.
......
/*
demo.js: http proxy for node.js
latent-proxy.js: Example of proxying over HTTP with latency
Copyright (c) 2010 Charlie Robbins, Mikeal Rogers, Fedor Indutny, & Marak Squires.
......
/*
demo.js: http proxy for node.js
proxy-table.js: Example of proxying over HTTP with proxy table
Copyright (c) 2010 Charlie Robbins, Mikeal Rogers, Fedor Indutny, & Marak Squires.
......
/*
demo.js: http proxy for node.js
standalone-proxy.js: Example of proxying over HTTP inside of a standalone HTTP server.
Copyright (c) 2010 Charlie Robbins, Mikeal Rogers, Fedor Indutny, & Marak Squires.
......
/*
demo.js: http proxy for node.js
web-socket-proxy.js: Example of proxying over HTTP and WebSockets.
Copyright (c) 2010 Charlie Robbins, Mikeal Rogers, Fedor Indutny, & Marak Squires.
......
......@@ -41,7 +41,7 @@ exports.version = [0, 4, 2];
// #### @host {string} Host of the agent to get
// #### @port {number} Port of the agent to get
// #### @secure {boolean} Value indicating whether or not to use HTTPS
// Retreives an agent from the `http` module
// Retreives an agent from the `http` or `https` module
// and sets the `maxSockets` property appropriately.
//
function _getAgent (host, port, secure) {
......@@ -55,18 +55,19 @@ function _getAgent (host, port, secure) {
}
//
// ### function _getProtocol (outgoing, https)
// #### @outgoing {Object} Outgoing request options
// ### function _getProtocol (secure, outgoing)
// #### @secure {Object|boolean} Settings for `https`
// #### @outgoing {Object} Outgoing request options
// Returns the appropriate protocol based on the settings in
// `secure`. If the protocol is `https` this function will update
// the options in `outgoing` as appropriate by adding `ca`, `key`,
// and `cert` if they exist in `secure`.
//
function _getProtocol (outgoing, secure) {
function _getProtocol (secure, outgoing) {
var protocol = secure ? https : http;
if (typeof secure === 'object') {
outgoing = outgoing || {};
['ca', 'cert', 'key'].forEach(function (prop) {
if (secure[prop]) {
outgoing[prop] = secure[prop];
......@@ -110,11 +111,10 @@ exports.setMaxSockets = function (value) {
// * `httpPRoxy.createServer(function (req, res, proxy) { ... })`
//
exports.createServer = function () {
var args, callback, port, host, forward,
silent, options, proxy, server;
args = Array.prototype.slice.call(arguments);
callback = typeof args[args.length - 1] === 'function' && args.pop();
var args = Array.prototype.slice.call(arguments),
callback = typeof args[0] === 'function' && args.shift(),
options = {},
port, host, forward, silent, proxy, server;
if (args.length >= 2) {
port = args[0];
......@@ -129,7 +129,8 @@ exports.createServer = function () {
}
proxy = new HttpProxy(options);
server = http.createServer(function (req, res) {
handler = function (req, res) {
if (callback) {
//
// If we were passed a callback to process the request
......@@ -160,7 +161,11 @@ exports.createServer = function () {
//
throw new Error('Cannot proxy without port, host, or router.')
}
});
};
server = options.https
? https.createServer(options.https, handler)
: http.createServer(handler);
server.on('close', function () {
proxy.close();
......@@ -187,7 +192,7 @@ exports.createServer = function () {
// Set the proxy on the server so it is available
// to the consumer of the server
//
server.proxy = proxy;
//server.proxy = proxy;
return server;
};
......@@ -374,12 +379,12 @@ HttpProxy.prototype.proxyRequest = function (req, res, options) {
path: req.url,
headers: req.headers
};
// Force the `connection` header to be 'close' until
// node.js core re-implements 'keep-alive'.
outgoing.headers['connection'] = 'close';
protocol = _getProtocol(outgoing, options.https || this.https);
protocol = _getProtocol(options.https || this.https, outgoing);
// Open new HTTP request to internal resource with will act as a reverse proxy pass
reverseProxy = protocol.request(outgoing, function (response) {
......@@ -474,7 +479,7 @@ HttpProxy.prototype._forwardRequest = function (req) {
// node.js core re-implements 'keep-alive'.
outgoing.headers['connection'] = 'close';
protocol = _getProtocol(outgoing, this.forward.https);
protocol = _getProtocol(this.forward.https, outgoing);
// Open new HTTP request to internal resource with will act as a reverse proxy pass
forwardProxy = protocol.request(outgoing, function (response) {
......
-----BEGIN CERTIFICATE-----
MIIB7DCCAZYCCQC7gs0MDNn6MTANBgkqhkiG9w0BAQUFADB9MQswCQYDVQQGEwJV
UzELMAkGA1UECBMCQ0ExCzAJBgNV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Jx4YehkChpxIyDUm
U3J9q9MDUf0+Y2+EGkssFfk=
-----END CERTIFICATE REQUEST-----
-----BEGIN RSA PRIVATE KEY-----
MIIBOgIBAAJBAMl2/Ba0XSm4ayi4C0rJ+tYtQu8O31VVXezkLJlf+6fVgdpVhYg5
QlihlPUoiM/wOsDWQ1ALnNhPlcLaQk+etQECAwEAAQJBAMT6Bf34+UHKY1ObpsbH
9u2jsVblFq1rWvs8GPMY6oertzvwm3DpuSUp7PTgOB1nLTLYtCERbQ4ovtN8tn3p
OHUCIQDzIEGsoCr5vlxXvy2zJwu+fxYuhTZWMVuo1397L0VyhwIhANQh+yzqUgaf
WRtSB4T2W7ADtJI35ET61jKBty3CqJY3AiAIwju7dVW3A5WeD6Qc1SZGKZvp9yCb
AFI2BfVwwaY11wIgXF3PeGcvACMyMWsuSv7aPXHfliswAbkWuzcwA4TW01ECIGWa
cgsDvVFxmfM5NPSuT/UDTa6R5BFISB5ea0N0AR3I
-----END RSA PRIVATE KEY-----
[ req ]
default_bits = 1024
days = 999
distinguished_name = req_distinguished_name
attributes = req_attributes
prompt = no
[ req_distinguished_name ]
C = US
ST = CA
L = SF
O = Joyent
OU = Node.js
CN = agent2
emailAddress = ry@tinyclouds.org
[ req_attributes ]
challengePassword = A challenge password
......@@ -5,21 +5,54 @@
*
*/
var http = require('http'),
var fs = require('fs'),
http = require('http'),
https = require('https'),
path = require('path'),
vows = require('vows'),
assert = require('assert'),
request = require('request'),
httpProxy = require('./../lib/node-http-proxy');
exports.assertProxiedWithTarget = function (runner, host, proxyPort, port, createProxy) {
var assertion = "should receive 'hello " + host + "'",
function merge (target) {
var objs = Array.prototype.slice.call(arguments, 1);
objs.forEach(function(o) {
Object.keys(o).forEach(function (attr) {
if (! o.__lookupGetter__(attr)) {
target[attr] = o[attr];
}
});
});
return target;
}
var loadHttps = exports.loadHttps = function () {
return {
key: fs.readFileSync(path.join(__dirname, 'fixtures', 'agent2-key.pem'), 'utf8'),
cert: fs.readFileSync(path.join(__dirname, 'fixtures', 'agent2-cert.pem'), 'utf8')
};
};
var TestRunner = exports.TestRunner = function (protocol) {
this.options = {};
this.protocol = protocol;
this.testServers = [];
if (protocol === 'https') {
this.options.https = loadHttps();
}
};
TestRunner.prototype.assertProxied = function (host, proxyPort, port, createProxy) {
var self = this,
assertion = "should receive 'hello " + host + "'",
output = 'hello ' + host;
var test = {
topic: function () {
var that = this, options = {
method: 'GET',
uri: 'http://localhost:' + proxyPort,
uri: self.protocol + '://localhost:' + proxyPort,
headers: {
host: host
}
......@@ -27,7 +60,7 @@ exports.assertProxiedWithTarget = function (runner, host, proxyPort, port, creat
function startTest () {
if (port) {
return runner.startTargetServer(port, output, function () {
return self.startTargetServer(port, output, function () {
request(options, that.callback);
});
}
......@@ -47,7 +80,7 @@ exports.assertProxiedWithTarget = function (runner, host, proxyPort, port, creat
return test;
};
exports.assertProxiedWithNoTarget = function (runner, proxyPort, statusCode, createProxy) {
TestRunner.prototype.assertResponseCode = function (proxyPort, statusCode, createProxy) {
var assertion = "should receive " + statusCode + " responseCode";
var test = {
......@@ -76,10 +109,6 @@ exports.assertProxiedWithNoTarget = function (runner, proxyPort, statusCode, cre
};
return test;
}
var TestRunner = exports.TestRunner = function () {
this.testServers = [];
};
//
......@@ -109,8 +138,8 @@ TestRunner.prototype.startLatentProxyServer = function (port, targetPort, host,
buffer: buffer
});
}, latency);
});
}, this.options);
proxyServer.listen(port, function () {
that.testServers.push(proxyServer);
callback();
......@@ -121,7 +150,7 @@ TestRunner.prototype.startLatentProxyServer = function (port, targetPort, host,
// Creates the reverse proxy server with a ProxyTable
//
TestRunner.prototype.startProxyServerWithTable = function (port, options, callback) {
var that = this, proxyServer = httpProxy.createServer(options);
var that = this, proxyServer = httpProxy.createServer(merge({}, options, this.options));
proxyServer.listen(port, function () {
that.testServers.push(proxyServer);
callback();
......@@ -135,7 +164,7 @@ TestRunner.prototype.startProxyServerWithTable = function (port, options, callba
//
TestRunner.prototype.startProxyServerWithTableAndLatency = function (port, latency, options, callback) {
// Initialize the nodeProxy and start proxying the request
var proxyServer, that = this, proxy = new httpProxy.HttpProxy(options);
var proxyServer, that = this, proxy = new httpProxy.HttpProxy(merge({}, options, this.options));
proxyServer = http.createServer(function (req, res) {
var buffer = proxy.buffer(req);
setTimeout(function () {
......@@ -143,7 +172,7 @@ TestRunner.prototype.startProxyServerWithTableAndLatency = function (port, laten
buffer: buffer
});
}, latency);
});
}, this.options);
proxyServer.listen(port, function () {
that.testServers.push(proxyServer);
......@@ -157,7 +186,7 @@ TestRunner.prototype.startProxyServerWithTableAndLatency = function (port, laten
// Creates proxy server forwarding to the specified options
//
TestRunner.prototype.startProxyServerWithForwarding = function (port, targetPort, host, options, callback) {
var that = this, proxyServer = httpProxy.createServer(targetPort, host, options);
var that = this, proxyServer = httpProxy.createServer(targetPort, host, merge({}, options, this.options));
proxyServer.listen(port, function () {
that.testServers.push(proxyServer);
callback(null, proxyServer);
......@@ -168,11 +197,15 @@ TestRunner.prototype.startProxyServerWithForwarding = function (port, targetPort
// Creates the 'hellonode' server
//
TestRunner.prototype.startTargetServer = function (port, output, callback) {
var that = this, targetServer = http.createServer(function (req, res) {
var that = this, targetServer, handler = function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.write(output);
res.end();
});
};
targetServer = this.options.https
? https.createServer(this.options.https, handler)
: http.createServer(handler);
targetServer.listen(port, function () {
that.testServers.push(targetServer);
......
......@@ -28,6 +28,7 @@ var vows = require('vows'),
util = require('util'),
request = require('request'),
assert = require('assert'),
argv = require('optimist').argv,
helpers = require('./helpers');
var forwardOptions = {
......@@ -44,25 +45,24 @@ var badForwardOptions = {
}
};
var runner = new helpers.TestRunner(),
assertProxiedWithTarget = helpers.assertProxiedWithTarget,
assertProxiedWithNoTarget = helpers.assertProxiedWithNoTarget;
var protocol = argv.https ? 'https' : 'http',
runner = new helpers.TestRunner(protocol);
vows.describe('node-http-proxy').addBatch({
vows.describe('node-http-proxy/' + protocol).addBatch({
"When using server created by httpProxy.createServer()": {
"with no latency" : {
"and a valid target server": assertProxiedWithTarget(runner, 'localhost', 8080, 8081, function (callback) {
"and a valid target server": runner.assertProxied('localhost', 8080, 8081, function (callback) {
runner.startProxyServer(8080, 8081, 'localhost', callback);
}),
"and without a valid target server": assertProxiedWithNoTarget(runner, 8082, 500, function (callback) {
"and without a valid target server": runner.assertResponseCode(8082, 500, function (callback) {
runner.startProxyServer(8082, 9000, 'localhost', callback);
})
},
"with latency": {
"and a valid target server": assertProxiedWithTarget(runner, 'localhost', 8083, 8084, function (callback) {
"and a valid target server": runner.assertProxied('localhost', 8083, 8084, function (callback) {
runner.startLatentProxyServer(8083, 8084, 'localhost', 1000, callback);
}),
"and without a valid target server": assertProxiedWithNoTarget(runner, 8085, 500, function (callback) {
"and without a valid target server": runner.assertResponseCode(8085, 500, function (callback) {
runner.startLatentProxyServer(8085, 9000, 'localhost', 1000, callback);
})
},
......@@ -71,10 +71,10 @@ vows.describe('node-http-proxy').addBatch({
runner.startTargetServer(8300, 'forward proxy', this.callback);
},
"with no latency" : {
"and a valid target server": assertProxiedWithTarget(runner, 'localhost', 8120, 8121, function (callback) {
"and a valid target server": runner.assertProxied('localhost', 8120, 8121, function (callback) {
runner.startProxyServerWithForwarding(8120, 8121, 'localhost', forwardOptions, callback);
}),
"and without a valid forward server": assertProxiedWithTarget(runner, 'localhost', 8122, 8123, function (callback) {
"and without a valid forward server": runner.assertProxied('localhost', 8122, 8123, function (callback) {
runner.startProxyServerWithForwarding(8122, 8123, 'localhost', badForwardOptions, callback);
})
}
......
......@@ -12,12 +12,12 @@ var fs = require('fs'),
request = require('request'),
assert = require('assert'),
helpers = require('./helpers'),
argv = require('optimist').argv,
TestRunner = helpers.TestRunner;
var runner = new TestRunner(),
routeFile = path.join(__dirname, 'config.json'),
assertProxiedWithTarget = helpers.assertProxiedWithTarget,
assertProxiedWithNoTarget = helpers.assertProxiedWithNoTarget;
var protocol = argv.https ? 'https' : 'http',
runner = new TestRunner(protocol),
routeFile = path.join(__dirname, 'config.json');
var fileOptions = {
router: {
......@@ -38,27 +38,27 @@ var hostnameOptions = {
router: {
"foo.com": "127.0.0.1:8091",
"bar.com": "127.0.0.1:8092"
},
}
}
};
vows.describe('node-http-proxy/proxy-table').addBatch({
vows.describe('node-http-proxy/proxy-table/' + protocol).addBatch({
"When using server created by httpProxy.createServer()": {
"when passed a routing table": {
"and routing by RegExp": {
topic: function () {
this.server = runner.startProxyServerWithTable(8090, defaultOptions, this.callback);
},
"an incoming request to foo.com": assertProxiedWithTarget(runner, 'foo.com', 8090, 8091),
"an incoming request to bar.com": assertProxiedWithTarget(runner, 'bar.com', 8090, 8092),
"an incoming request to unknown.com": assertProxiedWithNoTarget(runner, 8090, 404)
"an incoming request to foo.com": runner.assertProxied('foo.com', 8090, 8091),
"an incoming request to bar.com": runner.assertProxied('bar.com', 8090, 8092),
"an incoming request to unknown.com": runner.assertResponseCode(8090, 404)
},
"and routing by Hostname": {
topic: function () {
this.server = runner.startProxyServerWithTable(8093, hostnameOptions, this.callback);
},
"an incoming request to foo.com": assertProxiedWithTarget(runner, 'foo.com', 8093, 8094),
"an incoming request to bar.com": assertProxiedWithTarget(runner, 'bar.com', 8093, 8095),
"an incoming request to unknown.com": assertProxiedWithNoTarget(runner, 8093, 404)
"an incoming request to foo.com": runner.assertProxied('foo.com', 8093, 8094),
"an incoming request to bar.com": runner.assertProxied('bar.com', 8093, 8095),
"an incoming request to unknown.com": runner.assertResponseCode(8093, 404)
}
},
"when passed a routing file": {
......@@ -68,9 +68,9 @@ vows.describe('node-http-proxy/proxy-table').addBatch({
router: routeFile
}, this.callback);
},
"an incoming request to foo.com": assertProxiedWithTarget(runner, 'foo.com', 8100, 8101),
"an incoming request to bar.com": assertProxiedWithTarget(runner, 'bar.com', 8100, 8102),
"an incoming request to unknown.com": assertProxiedWithNoTarget(runner, 8100, 404),
"an incoming request to foo.com": runner.assertProxied('foo.com', 8100, 8101),
"an incoming request to bar.com": runner.assertProxied('bar.com', 8100, 8102),
"an incoming request to unknown.com": runner.assertResponseCode(8100, 404),
"an incoming request to dynamic.com": {
"after the file has been modified": {
topic: function () {
......@@ -112,9 +112,9 @@ vows.describe('node-http-proxy/proxy-table').addBatch({
}
}, this.callback);
},
"an incoming request to foo.com": assertProxiedWithTarget(runner, 'foo.com', 8110, 8111),
"an incoming request to bar.com": assertProxiedWithTarget(runner, 'bar.com', 8110, 8112),
"an incoming request to unknown.com": assertProxiedWithNoTarget(runner, 8110, 404)
"an incoming request to foo.com": runner.assertProxied('foo.com', 8110, 8111),
"an incoming request to bar.com": runner.assertProxied('bar.com', 8110, 8112),
"an incoming request to unknown.com": runner.assertResponseCode(8110, 404)
}
}).addBatch({
"When the tests are over": {
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment