Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Guard against prototype pollution in json0 #51

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion lib/json0.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ var isObject = function(obj) {
return (!!obj) && (obj.constructor === Object);
};

var hasOwn = Object.hasOwn || Object.prototype.hasOwnProperty.call;

/**
* Clones the passed object using JSON serialization (which is slow).
*
Expand All @@ -55,7 +57,7 @@ var json = {
// You can register another OT type as a subtype in a JSON document using
// the following function. This allows another type to handle certain
// operations instead of the builtin JSON type.
var subtypes = {};
var subtypes = Object.create(null);
json.registerSubtype = function(subtype) {
subtypes[subtype.name] = subtype;
};
Expand Down Expand Up @@ -157,6 +159,9 @@ json.apply = function(snapshot, op) {
for (var j = 0; j < c.p.length; j++) {
var p = c.p[j];

if (p in elem && !hasOwn(elem, p))
throw new Error('Path invalid');

parent = elem;
parentKey = key;
elem = elem[key];
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
"dependencies": {},
"devDependencies": {
"coffee-script": "^1.7.1",
"colors": "1.4.0",
"mocha": "^9.0.2",
"ot-fuzzer": "^1.0.0"
},
Expand Down
10 changes: 10 additions & 0 deletions test/json0.coffee
Original file line number Diff line number Diff line change
Expand Up @@ -418,6 +418,16 @@ genTests = (type) ->
assert.deepEqual [], type.transform [{p:['k'], od:'x'}], [{p:['k'], od:'x'}], 'left'
assert.deepEqual [], type.transform [{p:['k'], od:'x'}], [{p:['k'], od:'x'}], 'right'

it 'disallows reassignment of special JS property names', ->
assert.throws -> type.apply {x:'a'}, [{p:['__proto__'], oi:'oops'}]
assert.throws -> type.apply {x:{y:'a'}}, [{p:['x', '__proto__'], oi:'oops'}]
assert.throws -> type.apply {x:'a'}, [{p:['constructor'], oi:'oops'}]
assert.throws -> type.apply {x:{y:'a'}}, [{p:['x', 'constructor'], oi:'oops'}]

it 'disallows modification of prototype property objects', ->
obj = {x:'a'}
assert.throws -> type.apply obj, [{p:['toString', 'name'], oi:'oops'}]

it 'throws when the insertion key is a number', ->
assert.throws -> type.apply {'1':'a'}, [{p:[2], oi: 'a'}]

Expand Down