Add middleware for handling CORS

Refs #6644
- deps: cors@2.7.1; Add express cors package.
- Adds new middleware for proper CORS support.
- Handles CORS pre-flight checks.
- Separates request authentication/authorization from
  CORS.
This commit is contained in:
Jason Williams 2016-03-26 17:28:00 -05:00
parent 23c162796a
commit 07dab144bd
8 changed files with 218 additions and 154 deletions

View File

@ -1,9 +1,5 @@
var _ = require('lodash'),
passport = require('passport'),
url = require('url'),
os = require('os'),
var passport = require('passport'),
errors = require('../errors'),
config = require('../config'),
labs = require('../utils/labs'),
i18n = require('../i18n'),
@ -32,40 +28,6 @@ function isBearerAutorizationHeader(req) {
return false;
}
function getIPs() {
var ifaces = os.networkInterfaces(),
ips = [];
Object.keys(ifaces).forEach(function (ifname) {
ifaces[ifname].forEach(function (iface) {
// only support IPv4
if (iface.family !== 'IPv4') {
return;
}
ips.push(iface.address);
});
});
return ips;
}
function isValidOrigin(origin, client) {
var configHostname = url.parse(config.url).hostname;
if (origin && client && client.type === 'ua' && (
_.indexOf(getIPs(), origin) >= 0
|| _.some(client.trustedDomains, {trusted_domain: origin})
|| origin === configHostname
|| configHostname === 'my-ghost-blog.com'
|| origin === url.parse(config.urlSSL ? config.urlSSL : '').hostname
// @TODO do this in dev mode only, once we can auto-configure the url #2240
|| (origin === 'localhost')
)) {
return true;
} else {
return false;
}
}
auth = {
// ### Authenticate Client Middleware
@ -94,16 +56,10 @@ auth = {
return passport.authenticate(['oauth2-client-password'], {session: false, failWithError: false},
function authenticate(err, client) {
var origin = null;
if (err) {
return next(err); // will generate a 500 error
}
if (req.headers && req.headers.origin) {
origin = url.parse(req.headers.origin).hostname;
}
// req.body needs to be null for GET requests to build options correctly
delete req.body.client_id;
delete req.body.client_secret;
@ -117,13 +73,8 @@ auth = {
return errors.handleAPIError(new errors.UnauthorizedError(i18n.t('errors.middleware.auth.accessDenied')), req, res, next);
}
if (!origin && client && client.type === 'ua') {
res.header('Access-Control-Allow-Origin', config.url);
} else if (isValidOrigin(origin, client)) {
res.header('Access-Control-Allow-Origin', req.headers.origin);
}
req.client = client;
return next(null, client);
}
)(req, res, next);

View File

@ -0,0 +1,64 @@
var cors = require('cors'),
_ = require('lodash'),
url = require('url'),
os = require('os'),
whitelist = [
'localhost'
],
ENABLE_CORS = {origin: true, maxAge: 86400},
DISABLE_CORS = {origin: false};
/**
* Gather a list of local ipv4 addresses
* @return {Array<String>}
*/
function getIPs() {
var ifaces = os.networkInterfaces(),
ips = [];
Object.keys(ifaces).forEach(function (ifname) {
ifaces[ifname].forEach(function (iface) {
// only support IPv4
if (iface.family !== 'IPv4') {
return;
}
ips.push(iface.address);
});
});
return ips;
}
// origins that always match: localhost, local IPs, etc.
whitelist = whitelist.concat(getIPs());
/**
* Checks the origin and enables/disables CORS headers in the response.
* @param {Object} req express request object.
* @param {Function} cb callback that configures CORS.
* @return {null}
*/
function handleCORS(req, cb) {
var origin = req.get('origin'),
trustedDomains = req.client && req.client.trustedDomains;
// Request must have an Origin header
if (!origin) {
return cb(null, DISABLE_CORS);
}
// Origin matches a client_trusted_domain
if (_.some(trustedDomains, {trusted_domain: origin})) {
return cb(null, ENABLE_CORS);
}
// Origin matches whitelist
if (whitelist.indexOf(url.parse(origin).hostname) > -1) {
return cb(null, ENABLE_CORS);
}
return cb(null, DISABLE_CORS);
}
module.exports = cors(handleCORS);

View File

@ -25,6 +25,7 @@ var bodyParser = require('body-parser'),
staticTheme = require('./static-theme'),
themeHandler = require('./theme-handler'),
uncapitalise = require('./uncapitalise'),
cors = require('./cors'),
ClientPasswordStrategy = require('passport-oauth2-client-password').Strategy,
BearerStrategy = require('passport-http-bearer').Strategy,
@ -43,7 +44,8 @@ middleware = {
authenticateUser: auth.authenticateUser,
requiresAuthorizedUser: auth.requiresAuthorizedUser,
requiresAuthorizedUserPublicAPI: auth.requiresAuthorizedUserPublicAPI,
errorHandler: errors.handleAPIError
errorHandler: errors.handleAPIError,
cors: cors
}
};

View File

@ -9,18 +9,23 @@ apiRoutes = function apiRoutes(middleware) {
authenticatePublic = [
middleware.api.authenticateClient,
middleware.api.authenticateUser,
middleware.api.requiresAuthorizedUserPublicAPI
middleware.api.requiresAuthorizedUserPublicAPI,
middleware.api.cors
],
// Require user for private endpoints
authenticatePrivate = [
middleware.api.authenticateClient,
middleware.api.authenticateUser,
middleware.api.requiresAuthorizedUser
middleware.api.requiresAuthorizedUser,
middleware.api.cors
];
// alias delete with del
router.del = router.delete;
// ## CORS pre-flight check
router.options('*', middleware.api.cors);
// ## Configuration
router.get('/configuration', authenticatePrivate, api.http(api.configuration.read));
router.get('/configuration/:key', authenticatePrivate, api.http(api.configuration.read));

View File

@ -68,9 +68,7 @@
"clientCredentialsNotValid": "Client credentials were not valid",
"forInformationRead": "For information on how to fix this, please read {url}.",
"accessDenied": "Access denied.",
"accessDeniedFromUrl": "Access Denied from url: {origin}. Please use the url configured in config.js",
"pleaseSignIn": "Please Sign In",
"attemptedToAccessAdmin": "You have attempted to access your Ghost admin panel from a url that does not appear in config.js."
"pleaseSignIn": "Please Sign In"
},
"ghostbusboy": {
"fileUploadingError": "Something went wrong uploading the file",

View File

@ -3,7 +3,6 @@ var sinon = require('sinon'),
should = require('should'),
passport = require('passport'),
rewire = require('rewire'),
configUtils = require('../../utils/configUtils'),
errors = require('../../../server/errors'),
auth = rewire('../../../server/middleware/auth'),
BearerStrategy = require('passport-http-bearer').Strategy,
@ -127,14 +126,6 @@ describe('Auth', function () {
});
describe('User Authentication', function () {
beforeEach(function () {
configUtils.set({url: 'http://my-domain.com'});
});
afterEach(function () {
configUtils.restore();
});
it('should authenticate user', function (done) {
req.headers = {};
req.headers.authorization = 'Bearer ' + token;
@ -374,78 +365,6 @@ describe('Auth', function () {
req.body.client_id = testClient;
req.body.client_secret = testSecret;
req.headers = {};
req.headers.origin = configUtils.config.url;
res.header = {};
sandbox.stub(res, 'header', function (key, value) {
key.should.equal('Access-Control-Allow-Origin');
value.should.equal(configUtils.config.url);
});
registerSuccessfulClientPasswordStrategy();
auth.authenticateClient(req, res, next);
next.called.should.be.true();
next.calledWith(null, client).should.be.true();
done();
});
it('should authenticate client without origin', function (done) {
req.body = {};
req.body.client_id = testClient;
req.body.client_secret = testSecret;
res.header = {};
sandbox.stub(res, 'header', function (key, value) {
key.should.equal('Access-Control-Allow-Origin');
value.should.equal(configUtils.config.url);
});
registerSuccessfulClientPasswordStrategy();
auth.authenticateClient(req, res, next);
next.called.should.be.true();
next.calledWith(null, client).should.be.true();
done();
});
it('should authenticate client with origin `localhost`', function (done) {
req.body = {};
req.body.client_id = testClient;
req.body.client_secret = testSecret;
req.headers = {};
req.headers.origin = 'http://localhost';
res.header = {};
sandbox.stub(res, 'header', function (key, value) {
key.should.equal('Access-Control-Allow-Origin');
value.should.equal('http://localhost');
});
registerSuccessfulClientPasswordStrategy();
auth.authenticateClient(req, res, next);
next.called.should.be.true();
next.calledWith(null, client).should.be.true();
done();
});
it('should authenticate client with origin `127.0.0.1`', function (done) {
req.body = {};
req.body.client_id = testClient;
req.body.client_secret = testSecret;
req.headers = {};
req.headers.origin = 'http://127.0.0.1';
res.header = {};
sandbox.stub(res, 'header', function (key, value) {
key.should.equal('Access-Control-Allow-Origin');
value.should.equal('http://127.0.0.1');
});
registerSuccessfulClientPasswordStrategy();
auth.authenticateClient(req, res, next);
@ -461,14 +380,6 @@ describe('Auth', function () {
req.query.client_id = testClient;
req.query.client_secret = testSecret;
req.headers = {};
req.headers.origin = configUtils.config.url;
res.header = {};
sandbox.stub(res, 'header', function (key, value) {
key.should.equal('Access-Control-Allow-Origin');
value.should.equal(configUtils.config.url);
});
registerSuccessfulClientPasswordStrategy();
auth.authenticateClient(req, res, next);
@ -484,14 +395,6 @@ describe('Auth', function () {
req.query.client_id = testClient;
req.query.client_secret = testSecret;
req.headers = {};
req.headers.origin = configUtils.config.url;
res.header = {};
sandbox.stub(res, 'header', function (key, value) {
key.should.equal('Access-Control-Allow-Origin');
value.should.equal(configUtils.config.url);
});
registerSuccessfulClientPasswordStrategy();
auth.authenticateClient(req, res, next);

View File

@ -0,0 +1,140 @@
/*globals describe, it, beforeEach, afterEach */
var sinon = require('sinon'),
should = require('should'),
cors = require('../../../server/middleware/cors');
describe('cors', function () {
var res, req, next, sandbox;
beforeEach(function () {
sandbox = sinon.sandbox.create();
req = {
headers: {
origin: null
},
client: {
trustedDomains: []
}
};
res = {
headers: {},
getHeader: function () {},
setHeader: function (h, v) {
this.headers[h] = v;
}
};
next = sandbox.spy();
});
afterEach(function () {
sandbox.restore();
});
it('should not be enabled without a request origin header', function (done) {
req.get = sinon.stub().withArgs('origin').returns(null);
cors(req, res, next);
next.called.should.be.true();
should.not.exist(res.headers['Access-Control-Allow-Origin']);
done();
});
it('should be enabled when origin is 127.0.0.1', function (done) {
var origin = 'http://127.0.0.1:2368';
req.get = sinon.stub().withArgs('origin').returns(origin);
res.get = sinon.stub().withArgs('origin').returns(origin);
req.headers.origin = origin;
cors(req, res, next);
next.called.should.be.true();
res.headers['Access-Control-Allow-Origin'].should.equal(origin);
done();
});
it('should be enabled when origin is localhost', function (done) {
var origin = 'http://localhost:2368';
req.get = sinon.stub().withArgs('origin').returns(origin);
res.get = sinon.stub().withArgs('origin').returns(origin);
req.headers.origin = origin;
cors(req, res, next);
next.called.should.be.true();
res.headers['Access-Control-Allow-Origin'].should.equal(origin);
done();
});
it('should be enabled when origin is a client_trusted_domain', function (done) {
var origin = 'http://my-trusted-domain.com';
req.client.trustedDomains.push({trusted_domain: origin});
req.get = sinon.stub().withArgs('origin').returns(origin);
res.get = sinon.stub().withArgs('origin').returns(origin);
req.headers.origin = origin;
cors(req, res, next);
next.called.should.be.true();
res.headers['Access-Control-Allow-Origin'].should.equal(origin);
done();
});
it('should be enabled when there are multiple trusted domains', function (done) {
var origin = 'http://my-other-trusted-domain.com';
req.client.trustedDomains.push({trusted_domain: origin});
req.client.trustedDomains.push({trusted_domain: 'http://my-trusted-domain.com'});
req.get = sinon.stub().withArgs('origin').returns(origin);
res.get = sinon.stub().withArgs('origin').returns(origin);
req.headers.origin = origin;
cors(req, res, next);
next.called.should.be.true();
res.headers['Access-Control-Allow-Origin'].should.equal(origin);
done();
});
it('should not be enabled the origin is not trusted or whitelisted', function (done) {
var origin = 'http://not-trusted.com';
req.client.trustedDomains.push({trusted_domain: 'http://example.com'});
req.get = sinon.stub().withArgs('origin').returns(origin);
res.get = sinon.stub().withArgs('origin').returns(origin);
req.headers.origin = origin;
cors(req, res, next);
next.called.should.be.true();
should.not.exist(res.headers['Access-Control-Allow-Origin']);
done();
});
it('should not be enabled the origin client_trusted_domains is empty', function (done) {
var origin = 'http://example.com';
req.get = sinon.stub().withArgs('origin').returns(origin);
res.get = sinon.stub().withArgs('origin').returns(origin);
req.headers.origin = origin;
cors(req, res, next);
next.called.should.be.true();
should.not.exist(res.headers['Access-Control-Allow-Origin']);
done();
});
});

View File

@ -36,6 +36,7 @@
"compression": "1.6.1",
"connect-slashes": "1.3.1",
"cookie-session": "1.2.0",
"cors": "2.7.1",
"downsize": "0.0.8",
"express": "4.13.4",
"express-hbs": "0.8.4",