Skip to content
This repository was archived by the owner on Sep 26, 2023. It is now read-only.

Commit

Permalink
Moving logic out into the route object.
Browse files Browse the repository at this point in the history
  • Loading branch information
tizzo committed Mar 28, 2015
1 parent 9356ddb commit 8161d8b
Show file tree
Hide file tree
Showing 5 changed files with 134 additions and 50 deletions.
6 changes: 6 additions & 0 deletions .npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
./config.yaml
node_modules
*.sw*
*.rdb
coverage
config.yaml
30 changes: 30 additions & 0 deletions gconfig.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
name: Authenticating Proxy
processName: auth-proxy
host: 127.0.0.1
cookieDomain: false
port: 443
# Set this to `false` to not listen on HTTP.
httpPort: 80
sslCert: /usr/lib/node_modules/auth-proxy/test/ssl/cert.pem
sslKey: /usr/lib/node_modules/auth-proxy/test/ssl/key.pem
redisHost: 127.0.0.1
redisPort: 6379
sessionSecret: secret
imageURL: 'http://nodejs.org/images/logos/nodejs.png'
imageAlt: Node.js logo
authenticationStrategies: {}
verbose: false
loginPath: /login
logoutPath: /proxy-logout
indexPath: /
routeWhiteList:
- '/css/bootstrap.css'
- '/img/glyphicons-halflings.png'
authenticationStrategies:
GoogleOAuth2:
# Note this option does not work with `@gmail.com` addresses, you would need to leave it empty.
allowedDomains: zivtech.com
# Note if you leave this empty and populate only the domain everyone in your apps domain will have access.
allowedEmails: false
googleClientId: 928519207178-qed3gidg37rbqfmsisbe0l6p1bqdk8c4.apps.googleusercontent.com
googleClientSecret: 8aO5hCAKcWabCA-KfxtTWPJ1
56 changes: 56 additions & 0 deletions lib/Route.js
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,62 @@ Route.prototype.pathMatches = function(request) {
}
};

Route.prototype.rewriteRequest = function(request) {
if (this.pathRewritePattern !== null) {
var pathRewriteRegex = new RegExp(route.pathPattern);
request.url = request.url.replace(pathRewriteRegex, this.pathRewritePattern);
}
if (this.hostPattern && this.hostRewritePattern) {
var hostRewriteRegex = new RegExp(this.hostPattern)
request.headers.host = request.headers.host.replace(hostRewriteRegex, this.hostRewritePattern);
}
if (request.user && request.user.email) {
request.headers['X-Forwarded-User'] = request.user.email;
}
request.headers['X-Forwarded-Proto'] = 'https';
// Allow the auth proxy to supply basic auth for systems that require some form of auth.
if (this.basicAuth && this.basicAuth.name && this.basicAuth.password) {
var authString = (new Buffer(route.basicAuth.name + ':' + route.basicAuth.password, "ascii")).toString("base64");
request.headers.Authorization = 'Basic ' + authString;
}
if (request.user && request.user.email) {
request.headers['X-Forwarded-User'] = request.user.email;
}
};

// Rewrite the request to ensure that the location header is properly rewritten.
Route.prototype.rewriteResponse = function(response) {
function rewriteResponse(response, route) {
var self = this;
var _writeHead = response.writeHead
var sent = false;
response.writeHead = function() {
if (sent) {
logger.error('Response headers already sent but http-proxy tried to send them again.');
response.end();
return;
}
// TODO: Due to https://github.com/nodejitsu/node-http-proxy/pull/388 we
// need to make sure we don't send headers twice.
// TODO: Can we just catch the error?
if (arguments[1] && arguments[1].headers && arguments[1].headers.host) {
if (self.hostPattern && self.hostRewritePattern) {
arguments[1].headers.host = arguments[1].headers.host.replace(self.hostPattern, self.hostRewritePattern);
}
}
if (arguments[1] && arguments[1].location) {
// Ensure that our location is being written with the ssl protocol.
arguments[1].location = arguments[1].location.replace(/^http:/, 'https:');
if (self.hostPattern && self.hostRewritePattern) {
arguments[1].location = arguments[1].location.replace(self.hostPattern, self.hostRewritePattern);
}
}
sent = true;
_writeHead.apply(this, arguments);
};
return response;
};

// Check to see whether this route should be included in the list of available services.
Route.prototype.isListable = function() {
return (this.name !== '' && this.description !== '' && this.link !== '' && this.list);
Expand Down
52 changes: 6 additions & 46 deletions lib/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ function createHttpServer(done) {
res.writeHead(301, { location: 'https://' + location });
res.end('This resource is only available over SSL, please use https://' + location);
});

httpServer.on('listening', function() {
var message = 'now redirecting http requests on port %d to https on port %s';
logger.info(message, config.httpPort, config.port);
Expand Down Expand Up @@ -119,6 +120,7 @@ function createHttpsServer(done) {
port: route.port,
},
});

});
done();
});
Expand Down Expand Up @@ -320,57 +322,13 @@ function lookupRoute(req, res, next) {

// Rewrite the request object based on configured patterns.
function rewriteRequest(req, route) {
if (route.pathRewritePattern !== null) {
var pathRewriteRegex = new RegExp(route.pathPattern);
req.url = req.url.replace(pathRewriteRegex, route.pathRewritePattern);
}
if (route.hostPattern && route.hostRewritePattern) {
var hostRewriteRegex = new RegExp(route.hostPattern)
req.headers.host = req.headers.host.replace(hostRewriteRegex, route.hostRewritePattern);
}
if (req.user && req.user.email) {
req.headers['X-Forwarded-User'] = req.user.email;
}
req.headers['X-Forwarded-Proto'] = 'https';
// Allow the auth proxy to supply basic auth for systems that require some form of auth.
if (route.basicAuth && route.basicAuth.name && route.basicAuth.password) {
var authString = (new Buffer(route.basicAuth.name + ':' + route.basicAuth.password, "ascii")).toString("base64");
req.headers.Authorization = 'Basic ' + authString;
}
if (req.user && req.user.email) {
req.headers['X-Forwarded-User'] = req.user.email;
}
route.rewriteRequest(req);
return req;
}

// Rewrite the request to ensure that the location header is properly rewritten.
function rewriteResponse(res, route) {
var _writeHead = res.writeHead
var sent = false;
res.writeHead = function() {
if (sent) {
logger.error('Response headers already sent but http-proxy tried to send them again.');
res.end();
return;
}
// TODO: Due to https://github.com/nodejitsu/node-http-proxy/pull/388 we
// need to make sure we don't send headers twice.
// TODO: Can we just catch the error?
if (arguments[1] && arguments[1].headers && arguments[1].headers.host) {
if (route.hostPattern && route.hostRewritePattern) {
arguments[1].headers.host = arguments[1].headers.host.replace(route.hostPattern, route.hostRewritePattern);
}
}
if (arguments[1] && arguments[1].location) {
// Ensure that our location is being written with the ssl protocol.
arguments[1].location = arguments[1].location.replace(/^http:/, 'https:');
if (route.hostPattern && route.hostRewritePattern) {
arguments[1].location = arguments[1].location.replace(route.hostPattern, route.hostRewritePattern);
}
}
sent = true;
_writeHead.apply(this, arguments);
};
route.rewriteResponse(res);
return res;
}

Expand All @@ -397,6 +355,7 @@ function proxyRoute(req, res, next) {
proxy.on('error', function(error) {
var message = 'There was an error proxying to the backend.';
logger.error(message, route.name);
/*
// TODO: Should this be in `lib/routes.js`?
var options = {
name: config.name,
Expand All @@ -405,6 +364,7 @@ function proxyRoute(req, res, next) {
error: error,
};
res.render('bad-route', options);
*/
});
proxy.web(req, res, {
target: {
Expand Down
40 changes: 36 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
{
"name": "auth-proxy",
"author": "Howard Tyson",
"author": {
"name": "Howard Tyson"
},
"version": "0.1.3",
"description": "An authetnicating proxy server protecting operations services.",
"main": "server.js",
Expand Down Expand Up @@ -35,9 +37,12 @@
"test": "./node_modules/mocha/bin/mocha",
"start": "bin/auth-proxy",
"watch": "./node_modules/mocha/bin/mocha -w",
"coverage": "./node_modules/.bin/istanbul cover ./node_modules/.bin/_mocha"
"coverage": "istanbul cover ./node_modules/.bin/_mocha"
},
"repository": {
"type": "git",
"url": "https://github.com/tizzo/authenticating-proxy.git"
},
"repository": "https://github.com/tizzo/authenticating-proxy.git",
"license": "GPL",
"config": {
"blanket": {
Expand All @@ -50,5 +55,32 @@
"should": "~2.1.0",
"coveralls": "^2.7.1",
"istanbul": "^0.3.2"
}
},
"gitHead": "8ea2fe0ac520271f0c41b1090dfdd61d5ce5d0f7",
"bugs": {
"url": "https://github.com/tizzo/authenticating-proxy/issues"
},
"homepage": "https://github.com/tizzo/authenticating-proxy",
"_id": "[email protected]",
"_shasum": "67fefaf24c4e097581159a4b798fa9a79fcb07af",
"_from": "auth-proxy@*",
"_npmVersion": "1.4.21",
"_npmUser": {
"name": "tizzo",
"email": "[email protected]"
},
"maintainers": [
{
"name": "tizzo",
"email": "[email protected]"
}
],
"dist": {
"shasum": "6eb5c470f54ef21d00b63d45e42b295e9f5a158a",
"tarball": "http://registry.npmjs.org/auth-proxy/-/auth-proxy-0.1.2.tgz"
},
"directories": {},
"_resolved": "https://registry.npmjs.org/auth-proxy/-/auth-proxy-0.1.2.tgz",
"readme": "# Authenitcating Proxy\n\n[![Build Status](https://travis-ci.org/tizzo/auth-proxy.png?branch=master)](https://travis-ci.org/tizzo/auth-proxy)\n[![Coverage Status](https://coveralls.io/repos/tizzo/auth-proxy/badge.png)](https://coveralls.io/r/tizzo/auth-proxy)\n\n**STATUS - This project is under active development and while it is currently functional it is not yet stable or properly documented, I'll keep the README up to date as this project takes shape.**\n\nThis module is a little bit of glue wrapping [express](http://expressjs.com/), [passport](http://passportjs.org/), and [HTTP Proxy](https://github.com/nodejitsu/node-http-proxy). It allows you to setup a simple reverse proxy server to provide authentication for otherwise unsecured services in your infrastructure. It currently ships with authentication using either [Google apps oauth2](http://npmjs.org/package/passport-google-oauth). You must add apps domains and allowed users to a whitelist before anyone can authenticate, you'll also need to define your proxy routes before auth-proxy does anything useful for you.\n\nPull requests adding support for other authentication strategies are most welcome.\n\n## Installation\n\n1. Clone the repo\n2. `cd` into the directory and run `npm install`\n3. Create a config.yaml in the root of the repository, any configuration added to this yaml file will override the defaults (set in `default.config.yaml`)\n4. Setup your authentication strategies in the config.yaml file. See `examples/config` for more.\n5. Setup your routes in config.yaml (see the documentation and examples below).\n6. Verify that you have your configuration correct by starting the server with `npm start`.\n7. Copy and edit the appropriate init script from the init directory to your system daemon.\n\n### Configuring\n\nThe `default.config.yaml` file holds the default configuration used by the proxy. If a `config.yaml` file is created in the root of the repository then any keys set will override defaults set in the default configuration file. Environment variables will override anything set in the configuration files. Environment variables can be set for any configuration key but are converted (all capital letters with underscores rather than camel case).\n\n### Defining Routes\n\nThe routes configuration key is an array of route objects. This list of routes is searched (in the order they are defined) when any incomming request is received in the proxy. A path and/or a hostname are checked (if configured - both optional) and the first matching route is used. For a small performance gain the most commonly used routes should probably be at the beginning of the list.\n\n#### Required configuration keys\n\n- `host` The host to proxy matching requests to.\n- `port` The port at `host` to route the requests to.\n\n#### Optional configuration keys\n\n- `name` A name for the route; used on the index page to list this service.\n- `description` A description for the route; used on the index page.\n- `link` Used on the index page to link to this resource. This can be relative if paths are used to match or absolute for hosts.\n- `pathPattern` A regex of the path to match, usually this should start with a `^/` (to match only instances at the beginning of the path and end with `/?` to optionally allow a trailing slash.\n- `hostPattern` A regex to search for host to match for incomming routes. This allows you to route to different applications based on host name.\n- `pathRewritePattern` This rewrites the request path sent to the backend used for this route. This may use regex matches from the `pathPattern` setting in normal javascript `replace()` syntax.\n- `hostRewritePattern` This rewrite the request host sent in the headers to the backend for this route. Like `pathRewritePattern` this may use tokens from the `hostPattern` regex as per the normal javascript `replace()` syntax.\n- `basicAuth` An object with attributes of `name` and `password`. This will be added as http basic auth for all requests proxied through this route.\n\n#### Configuration example\n\n```yaml\nroutes:\n - name: \"Jenkins\"\n description: \"An extendable open source continuous integration server.\"\n host: localhost\n port: 8080\n pathPattern: \"^/jenkins/?\"\n link: /jenkins\n - name: \"Jenkins Git Calback\"\n description: A brutal task master\n pathRewritePattern: /\n host: localhost\n port: 8080\n pathPattern: \"^/jenkins/?\"\n - name: test route\n pathPattern: \"/test/?\"\n description: debug info\n pathRewritePattern: \"/\"\n host: localhost\n hostPattern: 127.0.0.1\n link: test\n hostRewritePattern: fooozbazzzz\n port: 8989\n```\n\n## Authentication Strategy Plugins\n\nAuth-proxy uses a plugin system for authentication strategies which are pluggable. It ships with a couple of strategies but if a strategy is specified\nin configuration that is not found when requiring `lib/plugins/index.js` than a global require will be attempted.\n\n### Built in strategies\n\n 1. Google OAuth 2\n 2. Mock Strategy\n\n### Writing a Passport Authentication Strategy Plugin \n\nAn auth-proxy strategy plugin is a simple wrapper around the passport strategy responsible for receiving it's configuration,\ninstantiating the underlying passport plugin, registering any necessary express routes, and rendering whatever widget needs to\nappear on the login page.\n\n#### Required methods:\n\n##### 1. attach()\n\n``` javasctipt\nattach = function(passport, app, config, pluginConfig, logger) {}\n```\n\n**Parameters:**\n\n - `passport`: The instantiated and configured passport object.\n - `app`: The express app object, use this to register new routes needed for authentication.\n - `config`: The current configuration for the server as a whole.\n - `pluginConfig`: The configuration for this specific plugin.\n - `logger`: The instantiated and configured [winston](https://www.npmjs.org/package/winston) logger object.\n\n##### 2. renderLogin()\n\nRender login is responsible for rendering the necessary logn widget for the login page. It receives no parameters and if the module needs to use configurationfor this portion it should be retained from the `attach()` call which will always run first.\n",
"readmeFilename": "README.md"
}

0 comments on commit 8161d8b

Please sign in to comment.