21.14. Block prototype pollution in nested writes
Topics
This question is in
21. Recursion and nested dataA settings endpoint receives a JSON body and merges it into the stored settings. It looks harmless, until someone sends {"__proto__": {"isAdmin": true}}. JSON.parse turns that into an object with an own key named __proto__, a naive deep merge walks into target["__proto__"], which is Object.prototype, and from then on every object in the program has isAdmin. This is prototype pollution, and nested writes (merge, set by path, unflatten) are where it happens. The same attack works through constructor.prototype, and through any inherited value the merge walks into.
Write safeMerge(target, patch) in safe-merge.js. It deep-merges an untrusted patch into target in place, refuses the keys that lead to prototypes, and returns the dotted paths of every key it refused, so the caller can log the attempt.
Signature
function safeMerge(target, patch) // returns an array of refused pathstarget: the object to change (an object, possibly with anullprototype).patch: a plain object, usually fromJSON.parse. It is not changed.- Returns an array of strings: the path of each refused key, such as
"settings.__proto__", in the order they were met.
Requirements
- When the patch has a plain object under a key and the target owns a plain object under the same key, the patch object is merged into the target's object, in place, at any depth.
- Otherwise the patch value is written to the target. Plain objects and arrays from the patch are copied through the same filter, never shared; other values (strings, numbers,
null,false) are written as they are. - The keys
__proto__,constructorandprototypeare refused at every depth, including inside objects in arrays, and even when the target already owns such a key. A refused key is not written; its path is added to the returned array. - Paths join keys with
.; array items use their index ("list.0.__proto__"). - Only values the target owns are merged into. An inherited value (such as
toString) counts as missing, so the target gets its own property and the built-in is never touched. - Only own keys of the patch are read: keys the patch inherits are ignored.
- A plain object is one whose prototype is
Object.prototypeornull. Only a plain object that is not protected (rule 10) is merged into: a Date, an array, a class instance or a protected object in the target is replaced by a filtered copy, not merged into. - Keys such as
hasOwnPropertyare ordinary data, on either side, and anull-prototype target works. - A
patchthat is not a plain object, or atargetthat is not an object or function, throws aTypeError. A protectedtarget(rule 10) throws aTypeError. A patch that contains itself throws aTypeError. - A protected object is never written to. The protected objects are: the global object; the standard globals
Object,Function,Array,String,Number,Boolean,Symbol,BigInt,Date,RegExp, the error classes (Error,TypeError,RangeError,SyntaxError,ReferenceError,EvalError,URIError,AggregateErrorandSuppressedError, each where the browser has it),Map,Set,WeakMap,WeakSet,WeakRef,FinalizationRegistry,Promise,Proxy,Reflect,JSON,Math,Intl,Atomics,Iterator,ArrayBuffer,SharedArrayBuffer,DataViewand the typed arrays (Int8ArraythroughBigUint64Array,Float16Arrayincluded where the browser has it); theprototypeof each of them; every object or function stored as a data property directly on one of those (such asObject.prototype.toStringorArray.prototype.push); and any object that owns aconstructorfunction whoseprototypeis that object (the prototype of a class). Owning a key does not make the object under it safe: in{ alias: Object.prototype }the key is the target's own, but the object is shared by the whole program.
Examples
const settings = { theme: { color: "blue" }, lang: "en" };
safeMerge(settings, JSON.parse('{"theme": {"size": 14}}')); // []
// settings is { theme: { color: "blue", size: 14 }, lang: "en" }const settings = {};
safeMerge(settings, JSON.parse('{"__proto__": {"isAdmin": true}, "lang": "fr"}'));
// ["__proto__"]
settings.lang; // "fr"
({}).isAdmin; // undefinedsafeMerge({}, JSON.parse('{"profile": {"constructor": {"prototype": {"isAdmin": true}}}}'));
// ["profile.constructor"]const settings = { alias: Object.prototype };
safeMerge(settings, JSON.parse('{"alias": {"isAdmin": true}}')); // []
settings.alias; // { isAdmin: true }, a new object
({}).isAdmin; // undefined
safeMerge(Object.prototype, {}); // throws a TypeErrorEnvironment
- Plain JavaScript in a browser page; the tests call the global
safeMergefromsafe-merge.js, and check the built-in prototypes after every test. - Only string keys are merged (
Object.keys). Getters, setters and symbol keys are out of scope. - Changes made before a
TypeErrorfor a cyclic patch may remain.
Hints
- On a fresh
{}, what aretarget["__proto__"],target.constructorandtarget.constructor.prototype? - Why is checking the key name not enough on its own? Think of
{"toString": {"polluted": 1}}, and of a target that ownsalias: Object.prototype. - If a new key gets a patch object assigned directly, what happens to the dangerous keys nested inside it?
The explanation comes with the course
A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.
- Every line explained
- The mistakes each test catches
- Links to the lessons behind it