Every plain object inherits from one shared object, Object.prototype: it's where methods like toString and hasOwnProperty come from. Prototype pollution is a security bug in which input from outside the program, such as a query string, a form field's name, or a JSON request body, gets code to write a property onto Object.prototype. From then on, every object in the program seems to have that property.
The way in is a few special key names. On a plain object, obj.__proto__ isn't an ordinary property: it's a getter and setter, inherited from Object.prototype, that reads or replaces the object's prototype. So obj["__proto__"] is Object.prototype itself, and a property written through it is written for everyone:
const settings = {};
const key = "__proto__"; // imagine it came from a query string
settings[key].isAdmin = true; // settings.__proto__ is Object.prototype
({}).isAdmin; // true: every object has it now
const user = { name: "Ada" };
user.isAdmin; // true, though user never had the property
delete Object.prototype.isAdmin; // clean up
constructor and prototype lead to the same place: obj.constructor is Object, and Object.prototype is the shared prototype. Here's where a function that sets a value at a dotted path would write, if it followed each key as given:
| Path | Following it reaches | The value lands on |
|---|---|---|
user.isAdmin | obj.user, an ordinary nested object | obj.user, as intended |
__proto__.isAdmin | obj.__proto__, which is Object.prototype | Object.prototype, so every object |
constructor.prototype.isAdmin | obj.constructor, which is Object, then Object.prototype | Object.prototype, so every object |
Why it's a security bug: code often checks a property that's normally missing, like if (user.isAdmin), and after pollution every object passes. Replacing an inherited method, such as toString, can also make code all over the app throw. Bugs like this have been found and fixed in popular libraries, Lodash and jQuery among them.
One more detail. Assigning obj["__proto__"] = value on a plain object doesn't create a key named __proto__: it replaces obj's prototype with value, or does nothing if value isn't an object or null. JSON.parse, though, does create an ordinary key named __proto__, so parsed JSON can carry one into code that copies or merges keys:
const parsed = JSON.parse('{"__proto__": {"isAdmin": true}}');
Object.keys(parsed); // ["__proto__"]: a real own key, harmless so far
const target = {};
target["__proto__"] = parsed["__proto__"]; // replaces target's prototype
Object.keys(target); // []: no key was created
target.isAdmin; // true, inherited from its new prototype
Write deepMerge(...objects). It merges any number of plain objects, left to right, into a new object, the way you'd layer a user's settings over the defaults.
When two objects both have a plain object under the same key, merge those too, recursively. In every other case the later value wins, whatever it is: arrays, dates, and class instances replace the earlier value rather than merging with it. A key whose value is undefined is skipped, so it never erases an earlier value.
Don't change any argument. Every plain object in the result is new, so changing the result can't reach the inputs; other values, arrays included, are used as they are. Ignore any key named __proto__, so merging parsed JSON can't change Object.prototype.
const defaults = { theme: { color: "blue", size: 12 }, plugins: ["a", "b"], debug: false };
const user = { theme: { size: 14 }, plugins: ["c"], debug: undefined };
deepMerge(defaults, user);
// { theme: { color: "blue", size: 14 }, plugins: ["c"], debug: false }
expect(deepMerge({ a: { x: 1 } }, { a: { y: 2 } })).toEqual({ a: { x: 1, y: 2 } });
expect(deepMerge({ a: 1, b: { c: 1, d: 1 } }, { a: 2, b: { c: 2 } })).toEqual({ a: 2, b: { c: 2, d: 1 } });
expect(deepMerge({ a: 1 }, { b: { x: 1 } }, { b: { y: 2 } }, { a: 3 })).toEqual({ a: 3, b: { x: 1, y: 2 } });
expect(deepMerge()).toEqual({});
expect(deepMerge({ tags: ["a", "b"] }, { tags: ["c"] })).toEqual({ tags: ["c"] });
expect(deepMerge({ list: { 0: "x" } }, { list: ["y"] })).toEqual({ list: ["y"] });
expect(deepMerge({ a: { x: 1 } }, { a: null })).toEqual({ a: null });
expect(deepMerge({ a: { x: 1 } }, { a: 5 })).toEqual({ a: 5 });
expect(deepMerge({ a: 1 }, { a: { x: 1 } })).toEqual({ a: { x: 1 } });
class Point {
constructor() {
this.x = 1;
}
}
const when = new Date(0);
const at = new Point();
const result = deepMerge({ when: { y: 1 }, at: { y: 2 } }, { when, at });
expect(result.when).toBe(when);
expect(result.at).toBe(at);
expect(deepMerge({ a: 1, b: { c: 1 } }, { a: undefined, b: { c: undefined } })).toEqual({ a: 1, b: { c: 1 } });
expect(deepMerge({ a: 1 }, { z: undefined })).toEqual({ a: 1 });
const first = { a: { x: 1 } };
const second = { b: { y: 2 } };
const result = deepMerge(first, second);
result.a.x = 99;
result.b.y = 99;
expect(first).toEqual({ a: { x: 1 } });
expect(second).toEqual({ b: { y: 2 } });
try {
const result = deepMerge({}, JSON.parse('{ "__proto__": { "polluted": true }, "ok": 1 }'));
expect(({}).polluted).toBeUndefined();
expect(result.polluted).toBeUndefined();
expect(result).toEqual({ ok: 1 });
} finally {
delete Object.prototype.polluted;
}
Run tests runs every test on your code, here in your browser. The problem is solved when they all pass.
Ctrl + Enter runs the tests (⌘ + Enter on a Mac).
I'm here to help with Deep merge. I give hints, never the solution, so you get to solve it yourself. Ask for a hint, select code to ask about it, or press Ask Tuto why on a failing test.
Your first 3 answers need no account. for free to keep asking.