Skip to content

Commit

Permalink
Fix #18
Browse files Browse the repository at this point in the history
Checks for possible prototype pollution attempts on nested key values by moving the key path check to the recursive function.
  • Loading branch information
mrodrig committed Jan 5, 2021
1 parent e7466c1 commit 2b247fd
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 6 deletions.
2 changes: 1 addition & 1 deletion dist/path.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 5 additions & 5 deletions lib/path.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,11 +48,6 @@ function setPath(obj, kp, v) {
throw new Error('No keyPath was provided.');
}

// If this is clearly a prototype pollution attempt, then refuse to modify the path
if (kp.startsWith('__proto__') || kp.startsWith('constructor') || kp.startsWith('prototype')) {
return obj;
}

return _sp(obj, kp, v);
}

Expand All @@ -67,6 +62,11 @@ function setPath(obj, kp, v) {
function _sp(obj, kp, v) {
let {dotIndex, key, remaining} = state(kp);

// If this is clearly a prototype pollution attempt, then refuse to modify the path
if (kp.startsWith('__proto__') || kp.startsWith('constructor') || kp.startsWith('prototype')) {
return obj;
}

if (dotIndex >= 0) {
// If there is a '.' in the key path, recur on the subdoc and ...
if (!obj[key] && Array.isArray(obj)) {
Expand Down
13 changes: 13 additions & 0 deletions test/tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -230,10 +230,12 @@ describe('doc-path Module', function() {

it('should protect against prototype pollution via __proto__', (done) => {
doc = {};
assert.equal(doc.polluted, undefined);
path.setPath(doc, '__proto__.polluted', 'prototype-polluted');
assert.equal(doc.__proto__.polluted, undefined);
assert.equal(doc.polluted, undefined);
assert.equal({}.polluted, undefined);
assert.equal(Object.polluted, undefined);
done();
});

Expand Down Expand Up @@ -266,5 +268,16 @@ describe('doc-path Module', function() {
assert.equal({}.test, undefined);
done();
});

it('should protect against prototype pollution against a nested document', (done) => {
doc = {};
assert.equal(doc.polluted, undefined);
path.setPath(doc, 'a.__proto__.polluted', 'polluted!');
assert.equal(typeof doc.a, 'object');
assert.equal(doc.polluted, undefined);
assert.equal({}.polluted, undefined);
assert.equal(Object.polluted, undefined);
done();
});
});
});

0 comments on commit 2b247fd

Please sign in to comment.