Skip to content

Commit

Permalink
rudimentary __proto__ guarding
Browse files Browse the repository at this point in the history
  • Loading branch information
mickhansen committed Jun 8, 2023
1 parent b48e227 commit 7d3aee1
Show file tree
Hide file tree
Showing 4 changed files with 27 additions and 0 deletions.
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ dottie.get(values, ['some.dot.included', 'key']); // returns 'barfoo'
*Note: lodash.get() also works fine for this*

### Set value

Sets nested value, creates nested structure if needed

```js
Expand All @@ -42,6 +43,8 @@ dottie.set(values, 'some.nested.object', someValue, {
});
```

If you accept arbitrary/user-defined paths to `set` you should call `Object.preventExtensions(values)` first to guard against potential pollution.

### Transform object
Transform object from keys with dottie notation to nested objects

Expand Down
4 changes: 4 additions & 0 deletions dottie.js
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@
// Set nested value
Dottie.set = function(object, path, value, options) {
var pieces = Array.isArray(path) ? path : path.split('.'), current = object, piece, length = pieces.length;
if (pieces[0] === '__proto__') return;

if (typeof current !== 'object') {
throw new Error('Parent is not an object.');
Expand Down Expand Up @@ -140,6 +141,9 @@

if (key.indexOf(options.delimiter) !== -1) {
pieces = key.split(options.delimiter);

if (pieces[0] === '__proto__') break;

piecesLength = pieces.length;
current = transformed;

Expand Down
8 changes: 8 additions & 0 deletions test/set.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -65,4 +65,12 @@ describe("dottie.set", function () {
});
expect(data.foo.bar.baz).to.equal('someValue');
});

it('should not attempt to set __proto__', function () {
var data = {};

dottie.set(data, '__proto__.pollution', 'polluted');

expect(data.__proto__.pollution).to.be.undefined;
});
});
12 changes: 12 additions & 0 deletions test/transform.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -145,4 +145,16 @@ describe("dottie.transform", function () {
expect(transformed.user.location.city).to.equal('Zanzibar City');
expect(transformed.project.title).to.equal('dottie');
});

it("should guard against prototype pollution", function () {
var values = {
'user.name': 'John Doe',
'__proto__.pollution': 'pollution'
};

var transformed = dottie.transform(values);
expect(transformed.user).not.to.equal(undefined);
expect(transformed.user.name).to.equal('John Doe');
expect(transformed.__proto__.pollution).to.be.undefined;
});
});

0 comments on commit 7d3aee1

Please sign in to comment.