Skip to content

Commit

Permalink
Fix #11. Throw when move path is descendent of from
Browse files Browse the repository at this point in the history
  • Loading branch information
briancavalier committed May 20, 2014
1 parent f009166 commit a86ffd9
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 0 deletions.
5 changes: 5 additions & 0 deletions lib/jsonPointer.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ exports.find = find;
exports.join = join;
exports.absolute = absolute;
exports.parse = parse;
exports.contains = contains;
exports.encodeSegment = encodeSegment;
exports.decodeSegment = decodeSegment;
exports.parseArrayIndex = parseArrayIndex;
Expand Down Expand Up @@ -69,6 +70,10 @@ function parse(path) {
return split(path).map(decodeSegment);
}

function contains(a, b) {
return b.indexOf(a) === 0 && b[a.length] === separator;
}

/**
* Decode a JSON Pointer path segment
* @see http://tools.ietf.org/html/rfc6901#page-3
Expand Down
4 changes: 4 additions & 0 deletions lib/patches.js
Original file line number Diff line number Diff line change
Expand Up @@ -284,6 +284,10 @@ function commuteRemove(remove, b) {
* @param {object} change move operation
*/
function applyMove(x, change) {
if(jsonPointer.contains(change.path, change.from)) {
throw new InvalidPatchOperationError('move.from cannot be ancestor of move.path');
}

var pto = find(x, change.path);
var pfrom = find(x, change.from);

Expand Down
9 changes: 9 additions & 0 deletions test/jsonPatch-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ var buster = require('buster');
var assert = buster.referee.assert;
var refute = buster.referee.refute;

var patches = require('../lib/patches');
var jsonPatch = require('../lib/jsonPatch');
var InvalidPatchOperationError = require('../lib/InvalidPatchOperationError');

Expand Down Expand Up @@ -109,6 +110,14 @@ buster.testCase('jsonPatch', {
var result = jsonPatch.apply([{ op: 'move', path: '/y', from: '/x' }], a);
assert.equals(result.y, 1);
refute.defined(result.x);
},

'=>should not allow moving to ancestor path': function() {
var from = '/a/b/c';
var to = '/a/b';
assert.exception(function() {
patches.move.apply({ a: { b: { c: 1 }}}, { op: 'move', from: from, path: to });
});
}
},

Expand Down

0 comments on commit a86ffd9

Please sign in to comment.