Skip to content

Commit

Permalink
additional sanity checks around patch input
Browse files Browse the repository at this point in the history
  • Loading branch information
Evan King committed Nov 7, 2016
1 parent 1e5d98a commit 68b1a7b
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 7 deletions.
19 changes: 13 additions & 6 deletions lib/joi-validate-patch.js
Original file line number Diff line number Diff line change
Expand Up @@ -72,23 +72,25 @@ function isArrayPath(path) {
}

function validateStep(schema, options, step) {
const
fail = msg => { return {error: new ValidationError(msg, step), value: null}; },
pass = () => { return {error: null, value: clean}; };

const formatErr = jsonpatch.validate([step]);
if(formatErr) return fail(new ValidationError(formatErr.message));

const
opts = Object.assign({}, options),
clean = Object.assign({}, step),
rule = getValidator(schema, step.path),
allowed = opts.allowedOps,
fail = msg => { return {error: new ValidationError(msg, step), value: null}; },
pass = () => { return {error: null, value: clean}; };
allowed = opts.allowedOps;

// Joi rejects unknown configuration options
delete opts.allowedOps;

if(allowed.indexOf(step.op) < 0) return fail(`disallowed op ${step.op}`);
if(!rule && !opts.allowUnknown) return fail(`invalid path ${step.path}`);

const formatErr = jsonpatch.validate([step]);
if(formatErr) return fail(new ValidationError(formatErr.message));

if(step.from) {
const source = getValidator(schema, step.from);
if(!source && !opts.allowUnknown) return fail(`invalid source ${step.path}`);
Expand Down Expand Up @@ -148,6 +150,11 @@ exports.validate = function(patch, schema, options, cb) {

const sanitized = [], errors = [];

if(!patch || !patch[0]) {
errors.push(new ValidationError('empty patch'));
patch = [];
}

patch.every(function(step) {
const result = validateStep(schema, options, step);

Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "joi-validate-patch",
"version": "0.0.2",
"version": "0.0.3",
"description": "Validator for json patch contents according to joi document schemas",
"main": "index.js",
"scripts": {
Expand Down
10 changes: 10 additions & 0 deletions test/joi-validate-patch.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,16 @@ function test(patch, match, errors, options) {

describe('JoiValidatePatch', function() {

it('rejects non-patch inputs', function() {
test('blah', null, true);
test(null, null, true);
test(5, null, true);
});

it('rejects empty patches', function() {
test([], null, 'empty patch');
});

it('validates step properties', function() {
Object.keys(patchProps).forEach(function(type) {
const patch = {op: type};
Expand Down

0 comments on commit 68b1a7b

Please sign in to comment.