Skip to content

Commit

Permalink
Add middleware for handling CORS
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
jaswilli committed Mar 31, 2016
1 parent 23c1627 commit 07dab14
Show file tree
Hide file tree
Showing 8 changed files with 218 additions and 154 deletions.
53 changes: 2 additions & 51 deletions core/server/middleware/auth.js
Original file line number Diff line number Diff line change
@@ -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'),

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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;
Expand All @@ -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);
Expand Down
64 changes: 64 additions & 0 deletions core/server/middleware/cors.js
Original file line number Diff line number Diff line change
@@ -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);
4 changes: 3 additions & 1 deletion core/server/middleware/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -43,7 +44,8 @@ middleware = {
authenticateUser: auth.authenticateUser,
requiresAuthorizedUser: auth.requiresAuthorizedUser,
requiresAuthorizedUserPublicAPI: auth.requiresAuthorizedUserPublicAPI,
errorHandler: errors.handleAPIError
errorHandler: errors.handleAPIError,
cors: cors
}
};

Expand Down
9 changes: 7 additions & 2 deletions core/server/routes/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -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));
Expand Down
4 changes: 1 addition & 3 deletions core/server/translations/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
97 changes: 0 additions & 97 deletions core/test/unit/middleware/authentication_spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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);
Expand All @@ -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);
Expand All @@ -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);
Expand Down
Loading

0 comments on commit 07dab14

Please sign in to comment.