2019-01-18 15:45:06 +03:00
|
|
|
const jwt = require('jsonwebtoken');
|
2019-08-09 17:13:41 +03:00
|
|
|
const url = require('url');
|
2019-01-18 15:45:06 +03:00
|
|
|
const models = require('../../../models');
|
2020-04-30 22:26:12 +03:00
|
|
|
const errors = require('@tryghost/errors');
|
2021-04-09 15:45:26 +03:00
|
|
|
const limitService = require('../../../services/limits');
|
2021-05-03 19:29:44 +03:00
|
|
|
const i18n = require('../../../../shared/i18n');
|
2019-09-23 19:12:53 +03:00
|
|
|
const _ = require('lodash');
|
2019-01-18 15:45:06 +03:00
|
|
|
|
2020-10-20 02:02:56 +03:00
|
|
|
let JWT_OPTIONS_DEFAULTS = {
|
2019-09-23 19:12:53 +03:00
|
|
|
algorithms: ['HS256'],
|
|
|
|
maxAge: '5m'
|
2019-01-18 15:45:06 +03:00
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Remove 'Ghost' from raw authorization header and extract the JWT token.
|
|
|
|
* Eg. Authorization: Ghost ${JWT}
|
|
|
|
* @param {string} header
|
|
|
|
*/
|
|
|
|
const _extractTokenFromHeader = function extractTokenFromHeader(header) {
|
|
|
|
const [scheme, token] = header.split(' ');
|
|
|
|
|
|
|
|
if (/^Ghost$/i.test(scheme)) {
|
|
|
|
return token;
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
2019-09-23 19:12:53 +03:00
|
|
|
* Extract JWT token from admin API URL query
|
|
|
|
* Eg. ${ADMIN_API_URL}/?token=${JWT}
|
|
|
|
* @param {string} reqUrl
|
2019-01-18 15:45:06 +03:00
|
|
|
*/
|
2019-09-23 19:12:53 +03:00
|
|
|
const _extractTokenFromUrl = function extractTokenFromUrl(reqUrl) {
|
|
|
|
const {query} = url.parse(reqUrl, true);
|
|
|
|
return query.token;
|
|
|
|
};
|
|
|
|
|
2019-01-18 19:30:07 +03:00
|
|
|
const authenticate = (req, res, next) => {
|
2019-01-18 19:03:03 +03:00
|
|
|
// CASE: we don't have an Authorization header so allow fallthrough to other
|
2019-01-18 15:45:06 +03:00
|
|
|
// auth middleware or final "ensure authenticated" check
|
|
|
|
if (!req.headers || !req.headers.authorization) {
|
2019-01-18 19:03:03 +03:00
|
|
|
req.api_key = null;
|
2019-01-18 15:45:06 +03:00
|
|
|
return next();
|
|
|
|
}
|
|
|
|
const token = _extractTokenFromHeader(req.headers.authorization);
|
|
|
|
|
|
|
|
if (!token) {
|
2020-04-30 22:26:12 +03:00
|
|
|
return next(new errors.UnauthorizedError({
|
|
|
|
message: i18n.t('errors.middleware.auth.incorrectAuthHeaderFormat'),
|
2019-01-18 15:45:06 +03:00
|
|
|
code: 'INVALID_AUTH_HEADER'
|
|
|
|
}));
|
|
|
|
}
|
|
|
|
|
2020-10-20 02:02:56 +03:00
|
|
|
return authenticateWithToken(req, res, next, {token, JWT_OPTIONS: JWT_OPTIONS_DEFAULTS});
|
2019-09-23 19:12:53 +03:00
|
|
|
};
|
|
|
|
|
|
|
|
const authenticateWithUrl = (req, res, next) => {
|
|
|
|
const token = _extractTokenFromUrl(req.originalUrl);
|
|
|
|
if (!token) {
|
2020-04-30 22:26:12 +03:00
|
|
|
return next(new errors.UnauthorizedError({
|
|
|
|
message: i18n.t('errors.middleware.auth.invalidTokenWithMessage', {message: 'No token found in URL'}),
|
2019-09-23 19:12:53 +03:00
|
|
|
code: 'INVALID_JWT'
|
|
|
|
}));
|
|
|
|
}
|
|
|
|
// CASE: Scheduler publish URLs can have long maxAge but controllerd by expiry and neverBefore
|
2020-10-20 02:02:56 +03:00
|
|
|
return authenticateWithToken(req, res, next, {token, JWT_OPTIONS: _.omit(JWT_OPTIONS_DEFAULTS, 'maxAge')});
|
2019-09-23 19:12:53 +03:00
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Admin API key authentication flow:
|
|
|
|
* 1. extract the JWT token from the `Authorization: Ghost xxxx` header or from URL(for schedules)
|
|
|
|
* 2. decode the JWT to extract the api_key id from the "key id" header claim
|
|
|
|
* 3. find a matching api_key record
|
|
|
|
* 4. verify the JWT (matching secret, matching URL path, not expired)
|
|
|
|
* 5. place the api_key object on `req.api_key`
|
|
|
|
*
|
|
|
|
* There are some specifcs of the JWT that we expect:
|
|
|
|
* - the "Key ID" header parameter should be set to the id of the api_key used to sign the token
|
|
|
|
* https://tools.ietf.org/html/rfc7515#section-4.1.4
|
|
|
|
* - the "Audience" claim should match the requested API path
|
|
|
|
* https://tools.ietf.org/html/rfc7519#section-4.1.3
|
|
|
|
*/
|
2021-04-07 07:52:26 +03:00
|
|
|
const authenticateWithToken = async (req, res, next, {token, JWT_OPTIONS}) => {
|
2019-01-18 15:45:06 +03:00
|
|
|
const decoded = jwt.decode(token, {complete: true});
|
|
|
|
|
|
|
|
if (!decoded || !decoded.header) {
|
2020-04-30 22:26:12 +03:00
|
|
|
return next(new errors.BadRequestError({
|
|
|
|
message: i18n.t('errors.middleware.auth.invalidToken'),
|
2019-01-18 15:45:06 +03:00
|
|
|
code: 'INVALID_JWT'
|
|
|
|
}));
|
|
|
|
}
|
|
|
|
|
2019-02-26 07:03:47 +03:00
|
|
|
const apiKeyId = decoded.header.kid;
|
2019-01-18 15:45:06 +03:00
|
|
|
|
2019-01-18 19:32:41 +03:00
|
|
|
if (!apiKeyId) {
|
2020-04-30 22:26:12 +03:00
|
|
|
return next(new errors.BadRequestError({
|
|
|
|
message: i18n.t('errors.middleware.auth.adminApiKidMissing'),
|
2019-02-26 07:03:47 +03:00
|
|
|
code: 'MISSING_ADMIN_API_KID'
|
2019-01-18 19:32:41 +03:00
|
|
|
}));
|
|
|
|
}
|
|
|
|
|
2021-04-07 07:52:26 +03:00
|
|
|
try {
|
2021-04-09 15:45:26 +03:00
|
|
|
const apiKey = await models.ApiKey.findOne({id: apiKeyId}, {withRelated: ['integration']});
|
2021-04-07 07:52:26 +03:00
|
|
|
|
2019-01-18 15:45:06 +03:00
|
|
|
if (!apiKey) {
|
2020-04-30 22:26:12 +03:00
|
|
|
return next(new errors.UnauthorizedError({
|
|
|
|
message: i18n.t('errors.middleware.auth.unknownAdminApiKey'),
|
2019-01-18 15:45:06 +03:00
|
|
|
code: 'UNKNOWN_ADMIN_API_KEY'
|
|
|
|
}));
|
|
|
|
}
|
|
|
|
|
|
|
|
if (apiKey.get('type') !== 'admin') {
|
2020-04-30 22:26:12 +03:00
|
|
|
return next(new errors.UnauthorizedError({
|
|
|
|
message: i18n.t('errors.middleware.auth.invalidApiKeyType'),
|
2019-01-18 15:45:06 +03:00
|
|
|
code: 'INVALID_API_KEY_TYPE'
|
|
|
|
}));
|
|
|
|
}
|
|
|
|
|
2021-04-09 15:45:26 +03:00
|
|
|
// CASE: blocking all non-internal: "custom" and "builtin" integration requests when the limit is reached
|
|
|
|
if (limitService.isLimited('customIntegrations')
|
|
|
|
&& (apiKey.relations.integration && !['internal'].includes(apiKey.relations.integration.get('type')))) {
|
|
|
|
// NOTE: using "checkWouldGoOverLimit" instead of "checkIsOverLimit" here because flag limits don't have
|
|
|
|
// a concept of measuring if the limit has been surpassed
|
|
|
|
await limitService.errorIfWouldGoOverLimit('customIntegrations');
|
|
|
|
}
|
|
|
|
|
2019-02-01 17:04:25 +03:00
|
|
|
// Decoding from hex and transforming into bytes is here to
|
|
|
|
// keep comparison of the bytes that are stored in the secret.
|
|
|
|
// Useful context:
|
|
|
|
// https://github.com/auth0/node-jsonwebtoken/issues/208#issuecomment-231861138
|
2019-01-18 15:45:06 +03:00
|
|
|
const secret = Buffer.from(apiKey.get('secret'), 'hex');
|
2019-01-18 19:22:19 +03:00
|
|
|
|
2019-08-09 17:13:41 +03:00
|
|
|
const {pathname} = url.parse(req.originalUrl);
|
2021-03-02 05:19:33 +03:00
|
|
|
const [hasMatch, version = 'v4', api = 'admin'] = pathname.match(/ghost\/api\/([^/]+)\/([^/]+)\/(.+)*/); // eslint-disable-line no-unused-vars
|
2019-08-09 17:13:41 +03:00
|
|
|
|
|
|
|
// ensure the token was meant for this api version
|
2019-01-18 15:45:06 +03:00
|
|
|
const options = Object.assign({
|
2019-08-09 17:13:41 +03:00
|
|
|
audience: new RegExp(`\/?${version}\/${api}\/?$`) // eslint-disable-line no-useless-escape
|
2019-01-18 15:45:06 +03:00
|
|
|
}, JWT_OPTIONS);
|
|
|
|
|
|
|
|
try {
|
|
|
|
jwt.verify(token, secret, options);
|
|
|
|
} catch (err) {
|
|
|
|
if (err.name === 'TokenExpiredError' || err.name === 'JsonWebTokenError') {
|
2020-04-30 22:26:12 +03:00
|
|
|
return next(new errors.UnauthorizedError({
|
|
|
|
message: i18n.t('errors.middleware.auth.invalidTokenWithMessage', {message: err.message}),
|
2019-01-18 15:45:06 +03:00
|
|
|
code: 'INVALID_JWT',
|
|
|
|
err
|
|
|
|
}));
|
|
|
|
}
|
|
|
|
|
|
|
|
// unknown error
|
2020-04-30 22:26:12 +03:00
|
|
|
return next(new errors.InternalServerError({err}));
|
2019-01-18 15:45:06 +03:00
|
|
|
}
|
|
|
|
|
2020-10-23 17:34:41 +03:00
|
|
|
// authenticated OK
|
|
|
|
|
|
|
|
if (apiKey.get('user_id')) {
|
|
|
|
// fetch the user and store it on the request for later checks and logging
|
2021-04-07 07:52:26 +03:00
|
|
|
const user = await models.User.findOne(
|
2020-11-17 16:49:48 +03:00
|
|
|
{id: apiKey.get('user_id'), status: 'active'},
|
|
|
|
{require: true}
|
2021-04-07 07:52:26 +03:00
|
|
|
);
|
|
|
|
|
|
|
|
req.user = user;
|
|
|
|
|
|
|
|
next();
|
2021-04-29 10:56:27 +03:00
|
|
|
return;
|
2020-10-23 17:34:41 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// store the api key on the request for later checks and logging
|
2019-01-18 15:45:06 +03:00
|
|
|
req.api_key = apiKey;
|
2021-04-07 07:52:26 +03:00
|
|
|
|
2019-01-18 15:45:06 +03:00
|
|
|
next();
|
2021-04-07 07:52:26 +03:00
|
|
|
} catch (err) {
|
2021-04-09 15:45:26 +03:00
|
|
|
if (err instanceof errors.HostLimitError) {
|
|
|
|
next(err);
|
|
|
|
} else {
|
|
|
|
next(new errors.InternalServerError({err}));
|
|
|
|
}
|
2021-04-07 07:52:26 +03:00
|
|
|
}
|
2019-01-18 15:45:06 +03:00
|
|
|
};
|
|
|
|
|
|
|
|
module.exports = {
|
2019-09-23 19:12:53 +03:00
|
|
|
authenticate,
|
|
|
|
authenticateWithUrl
|
2019-01-18 15:45:06 +03:00
|
|
|
};
|