Difficulty: Intermediate
What is JSON poisoning? Explain how duplicate keys, prototype pollution and oversized payloads can be used to attack an API.
JSON poisoning is a loose term for attacks that craft a JSON payload so that it is parsed or processed in a way the developer did not expect. The main variants are duplicate keys that different parsers interpret differently, special keys like __proto__ that pollute JavaScript object prototypes, and huge or deeply nested payloads that exhaust memory or CPU. The defences are strict parsing, schema validation with unknown keys rejected, safe merging, and size and depth limits.
RFC 8259 says object names SHOULD be unique but does not require it, and leaves behaviour for duplicates unspecified. In practice:
JSON.parse, Python json, and many others keep the last value.This matters when two components parse the same request. Suppose an API gateway validates {"amount": 100, "amount": 100000} and sees the first value, but the payment service reads the last. The check passes on ₹100 while the service processes ₹1,00,000. The same applies between a WAF and the backend, or between a signature check and the business logic. Research by Bishop Fox in 2021 found such inconsistencies across dozens of popular JSON parsers.
JSON.parse('{"__proto__": {"isAdmin": true}}') creates an object with an own property literally named __proto__. That is harmless on its own, but if the result is passed to a naive recursive merge or set(obj, path, value) helper, the merge writes into Object.prototype. Now every object in the process has isAdmin === true, which can bypass authorization checks or, with the right gadget, lead to RCE. Older versions of lodash merge, defaultsDeep and many small utilities were affected. constructor.prototype is an alternative path to the same target.
express.json() defaults to a 100 kb limit; keep a limit everywhere.[[[[...]]]] thousands of levels deep can overflow recursive parsers or later recursive code.2^53 - 1, so 9007199254740993 becomes 9007199254740992, which can corrupt IDs..strict(), JSON Schema with additionalProperties: false, Pydantic with extra='forbid').__proto__, constructor and prototype keys, use Object.create(null) or Map for dictionaries, and keep libraries patched. Node's --disable-proto=delete flag removes the __proto__ accessor.// 1. Duplicate keys: last one wins in JSON.parse
console.log(JSON.parse('{"amount": 100, "amount": 100000}').amount);
// 2. Naive deep merge pollutes Object.prototype
function merge(target, src) {
for (const key in src) {
if (typeof src[key] === 'object' && src[key] !== null) {
target[key] ??= {};
merge(target[key], src[key]);
} else target[key] = src[key];
}
return target;
}
const body = JSON.parse('{"__proto__": {"isAdmin": true}}');
merge({}, body);
console.log({}.isAdmin);
// Fix: skip dangerous keys (or use a vetted library / Map)
const BAD = new Set(['__proto__', 'constructor', 'prototype']);
const safeKeys = (o) => Object.keys(o).filter((k) => !BAD.has(k));
// 3. Precision loss on big integers
console.log(JSON.parse('{"id": 9007199254740993}').id);
target['__proto__'] resolves to Object.prototype, so the merge writes isAdmin onto every object. Filtering keys and using strict schemas prevents both tricks.
import express from 'express';
import { z } from 'zod';
const app = express();
app.use(express.json({ limit: '20kb', strict: true }));
const Payment = z.object({
orderId: z.string().uuid(),
amountPaise: z.number().int().positive().max(10_000_000),
}).strict(); // unknown keys such as __proto__ are rejected
app.post('/pay', (req, res) => {
const r = Payment.safeParse(req.body);
if (!r.success) return res.status(400).json(r.error.flatten());
res.json({ ok: true });
});
The size limit stops oversized payloads before parsing, and .strict() rejects any field not in the schema, including prototype keys.
JSON Duplicate Keys, Parser Differentials, Prototype Pollution, JSON DoS, Schema Validation