From d26ce117fdc12b27d21258fd511bff9f395fc4ac Mon Sep 17 00:00:00 2001 From: Josh Harvey Date: Fri, 21 Apr 2017 02:10:44 +0300 Subject: [PATCH] add config validation --- lamassu-schema.json | 10 +++++++++- lib/settings-loader.js | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 1 deletion(-) diff --git a/lamassu-schema.json b/lamassu-schema.json index 282c4338..ee3988b2 100644 --- a/lamassu-schema.json +++ b/lamassu-schema.json @@ -117,7 +117,15 @@ "enabledIf": [ "cashOutEnabled" ], - "fieldValidation": [{"code": "required"}] + "fieldValidation": [ + { + "code": "required" + }, + { + "code": "min", + "min": 0 + } + ] }, { "code": "lowBalanceMargin", diff --git a/lib/settings-loader.js b/lib/settings-loader.js index aa066cb5..b437cbc9 100644 --- a/lib/settings-loader.js +++ b/lib/settings-loader.js @@ -6,6 +6,11 @@ const argv = require('minimist')(process.argv.slice(2)) const pify = require('pify') const db = require('./db') +const options = require('./options') +const logger = require('./logger') + +const schemaPath = path.resolve(options.lamassuServerPath, 'lamassu-schema.json') +const schema = require(schemaPath) let settingsCache @@ -68,6 +73,7 @@ function loadConfig (versionId) { return db.oneOrNone(sql, [versionId, 'config']) .then(row => row ? row.data.config : []) + .then(validate) } function loadLatestConfig () { @@ -81,6 +87,37 @@ function loadLatestConfig () { return db.oneOrNone(sql, ['config']) .then(row => row ? row.data.config : []) + .then(validate) +} + +function checkConstraint (entry, constraint) { + switch (constraint.code) { + case 'min': + return entry.fieldValue.value >= constraint.min + default: + return true + } +} + +function validateConstraint (entry, constraint) { + const isValid = checkConstraint(entry, constraint) + if (!isValid) logger.error(`Validation error: ${entry.fieldLocator.code} [${constraint.code}]`) + return isValid +} + +function validateEntry (entry) { + const fieldCode = entry.fieldLocator.code + const schemaEntry = _.find(_.matchesProperty('code', fieldCode), schema.fields) + if (!schemaEntry) throw new Error(`Unsupported field: ${fieldCode}`) + + const validations = schemaEntry.fieldValidation + return _.every(constraint => validateConstraint(entry, constraint), validations) +} + +function validate (config) { + const isValid = _.every(validateEntry, config) + if (!isValid) throw new Error('Invalid config') + return config } function loadAccounts () {