Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Condition engine refactor and improvements — JSON Schema Validation #882

Merged
merged 20 commits into from
Mar 25, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .eslintrc
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
"node"
],
"rules": {
"space-before-function-paren": 0,
"comma-dangle": [
2,
"never"
Expand Down
29 changes: 9 additions & 20 deletions lib/conditions/index.js
Original file line number Diff line number Diff line change
@@ -1,41 +1,30 @@
const express = require('express');
const chalk = require('chalk');
const logger = require('../logger').policy;
const schemas = require('../schemas');
const predefined = require('./predefined');
const conditions = {};

function register ({ name, handler, schema }) {
function register({ name, handler, schema }) {
const validate = schemas.register('condition', name, schema);

conditions[name] = (req, config) => {
conditions[name] = config => {
const validationResult = validate(config);
if (validationResult.isValid) {
return handler(req, config);
if (handler.length === 2) {
return req => handler(req, config);
}

return handler(config);
}

logger.error(`Condition ${chalk.default.red.bold(name)} config validation failed: ${validationResult.error}`);
throw new Error(`CONDITION_PARAMS_VALIDATION_FAILED`);
};
}

function init () {
function init() {
predefined.forEach(register);

// extending express.request
express.request.matchEGCondition = function (conditionConfig) {
logger.debug(`matchEGCondition for ${conditionConfig}`);
const func = conditions[conditionConfig.name];

if (!func) {
logger.warn(`Condition not found for ${conditionConfig.name}`);
return null;
}

return func(this, conditionConfig);
};

return { register };
}

module.exports = { init };
module.exports = { init, conditions };
37 changes: 37 additions & 0 deletions lib/conditions/json-schema.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
const express = require('express');
const schemas = require('../schemas');
const logger = require('../logger').gateway;

module.exports = {
name: 'json-schema',
schema: {
$id: 'http://express-gateway.io/schemas/policies/json-schema.json',
type: 'object',
properties: {
schema: {
type: 'object',
description: 'Json schema to validate against.',
examples: ['{"type":"string"}']
},
logErrors: {
type: 'boolean',
default: false,
description: 'Value istructing the gateway to report the errors on the logger or not'
}
},
required: ['schema', 'logErrors']
},
handler: config => {
const validator = schemas.register(String(), String(), config.schema);
if (config.logErrors) {
return req => {
const { isValid, error } = validator(req.body);
logger.warn(error);
return isValid;
};
}

return req => validator(req.body).isValid;
},
middlewares: [express.json(), express.urlencoded({ extended: false })]
};
49 changes: 30 additions & 19 deletions lib/conditions/predefined.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,15 @@
const minimatch = require('minimatch');
const jsonSchema = require('./json-schema');

const grabArray = config => {
const { conditions } = require('./index');
return config.conditions.map(config => conditions[config.name](config));
};

const grabSingle = config => {
const { conditions } = require('./index');
return conditions[config.name](config);
};

module.exports = [
{
Expand All @@ -17,21 +28,21 @@ module.exports = [
},
{
name: 'always',
handler: () => true,
handler: () => () => true,
schema: {
$id: 'http://express-gateway.io/schemas/conditions/always.json'
}
}, {
// Not sure if anyone would ever use this in real life, but it is a
// "legitimate" condition, and is useful during tests.
name: 'never',
handler: () => false,
handler: () => () => false,
schema: {
$id: 'http://express-gateway.io/schemas/conditions/never.json'
}
}, {
name: 'allOf',
handler: (req, actionConfig) => actionConfig.conditions.every(subItem => req.matchEGCondition(subItem)),
handler: config => req => grabArray(config).every(c => c(req)),
schema: {
$id: 'http://express-gateway.io/schemas/conditions/allOf.json',
type: 'object',
Expand All @@ -45,7 +56,7 @@ module.exports = [
}
}, {
name: 'oneOf',
handler: (req, actionConfig) => actionConfig.conditions.some(subItem => req.matchEGCondition(subItem)),
handler: config => req => grabArray(config).some(c => c(req)),
schema: {
$id: 'http://express-gateway.io/schemas/conditions/oneOf.json',
type: 'object',
Expand All @@ -59,7 +70,7 @@ module.exports = [
}
}, {
name: 'not',
handler: (req, actionConfig) => !req.matchEGCondition(actionConfig.condition),
handler: config => req => !grabSingle(config.condition)(req),
schema: {
$id: 'http://express-gateway.io/schemas/conditions/not.json',
type: 'object',
Expand All @@ -70,7 +81,7 @@ module.exports = [
}
}, {
name: 'pathMatch',
handler: (req, actionConfig) => req.url.match(new RegExp(actionConfig.pattern)) !== null,
handler: config => req => req.url.match(new RegExp(config.pattern)) !== null,
schema: {
$id: 'http://express-gateway.io/schemas/conditions/pathMatch.json',
type: 'object',
Expand All @@ -85,7 +96,7 @@ module.exports = [
}
}, {
name: 'pathExact',
handler: (req, actionConfig) => req.url === actionConfig.path,
handler: config => req => req.url === config.path,
schema: {
$id: 'http://express-gateway.io/schemas/conditions/pathExact.json',
type: 'object',
Expand All @@ -99,11 +110,11 @@ module.exports = [
}
}, {
name: 'method',
handler: (req, actionConfig) => {
if (Array.isArray(actionConfig.methods)) {
return actionConfig.methods.includes(req.method);
handler: config => req => {
if (Array.isArray(config.methods)) {
return config.methods.includes(req.method);
} else {
return req.method === actionConfig.methods;
return req.method === config.methods;
}
},
schema: {
Expand All @@ -128,9 +139,9 @@ module.exports = [
}
}, {
name: 'hostMatch',
handler: (req, actionConfig) => {
handler: config => req => {
if (req.headers.host) {
return minimatch(req.headers.host, actionConfig.pattern);
return minimatch(req.headers.host, config.pattern);
}
return false;
},
Expand All @@ -147,7 +158,7 @@ module.exports = [
}
}, {
name: 'expression',
handler: (req, conditionConfig) => req.egContext.match(conditionConfig.expression),
handler: config => req => req.egContext.match(config.expression),
schema: {
$id: 'http://express-gateway.io/schemas/conditions/expression.json',
type: 'object',
Expand All @@ -162,24 +173,24 @@ module.exports = [
},
{
name: 'authenticated',
handler: (req, conditionConfig) => req.isAuthenticated(),
handler: () => req => req.isAuthenticated(),
schema: {
$id: 'http://express-gateway.io/schemas/conditions/authenticated.json'
}
},
{
name: 'anonymous',
handler: (req, conditionConfig) => req.isUnauthenticated(),
handler: () => req => req.isUnauthenticated(),
schema: {
$id: 'http://express-gateway.io/schemas/conditions/anonymous.json'
}
},
{
name: 'tlsClientAuthenticated',
handler: (req, conditionConfig) => req.client.authorized,
handler: () => req => req.client.authorized,
schema: {
$id: 'http://express-gateway.io/schemas/conditions/tlsClientAuthenticated.json'
}
}

},
jsonSchema
];
20 changes: 11 additions & 9 deletions lib/config/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ const eventBus = require('../eventBus');
const schemas = require('../schemas');

class Config {
constructor () {
constructor() {
this.models = {};

this.configTypes = {
Expand All @@ -29,7 +29,7 @@ class Config {
};
}

loadConfig (type) {
loadConfig(type) {
const configType = this.configTypes[type];
let configPath = this[configType.pathProperty] || path.join(process.env.EG_CONFIG_DIR, `${configType.baseFilename}.yml`);
let config;
Expand Down Expand Up @@ -59,9 +59,9 @@ class Config {
log.debug(`ConfigPath: ${configPath}`);
}

loadGatewayConfig () { this.loadConfig('gateway'); }
loadGatewayConfig() { this.loadConfig('gateway'); }

loadModels () {
loadModels() {
['users.json', 'credentials.json', 'applications.json'].forEach(model => {
const module = path.resolve(process.env.EG_CONFIG_DIR, 'models', model);
const name = path.basename(module, '.json');
Expand All @@ -71,7 +71,9 @@ class Config {
});
}

watch () {
watch() {
if (typeof this.systemConfigPath !== 'string' || typeof this.gatewayConfigPath !== 'string') { return; }

const watchEvents = ['add', 'change'];

const watchOptions = {
Expand All @@ -96,15 +98,15 @@ class Config {
});
}

unwatch () {
unwatch() {
this.watcher && this.watcher.close();
}

updateGatewayConfig (modifier) {
updateGatewayConfig(modifier) {
return this._updateConfigFile('gateway', modifier);
}

_updateConfigFile (type, modifier) {
_updateConfigFile(type, modifier) {
const configType = this.configTypes[type];
const path = this[configType.pathProperty];

Expand Down Expand Up @@ -166,7 +168,7 @@ class Config {
// Kindly borrowed from https://github.com/macbre/optimist-config-file/blob/master/lib/envvar-replace.js
// Thanks a lot guys 🙌

function envReplace (str, vars) {
function envReplace(str, vars) {
return str.replace(/\$?\$\{([A-Za-z0-9_]+)(:-(.*?))?\}/g, function (varStr, varName, _, defValue) {
// Handle escaping:
if (varStr.indexOf('$$') === 0) {
Expand Down
2 changes: 1 addition & 1 deletion lib/config/gateway.config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -22,5 +22,5 @@ pipelines:
policies:
# - key-auth: # uncomment to enable key-auth
- proxy:
- action:
action:
serviceEndpoint: backend
5 changes: 4 additions & 1 deletion lib/config/schemas/gateway.config.json
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,10 @@
},
"required": [
"name"
]
],
"default": {
"name": "always"
}
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion lib/gateway/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ module.exports = function ({ plugins, config } = {}) {
});
};

function bootstrap ({ plugins, config } = {}) {
function bootstrap({ plugins, config } = {}) {
const app = express();
app.set('x-powered-by', false);

Expand Down
Loading