The Attacks to Expect: Injection and Mass Assignment
The first things attackers try against an API are a MongoDB operator where text belongs, a body that sets fields it shouldn't, and errors that give details away, so an API checks that fields are text, copies only an allow-list of fields, answers errors in plain words and runs npm audit.
Journeyman · Node.js · Web Development · Updated
After this lesson you can
- Refuse operator injection by checking that the fields a query uses are text, never objects such as a $gt operator
- Stop mass assignment by copying only an allow-list of the fields a request may change
- Keep error answers free of internal details, and check a project's packages with npm audit
Key takeaways
- JSON can hold an object wherever a value goes, so a sign-in body can send a $gt operator object as the email, and MongoDB reads it as a filter that matches a member.
- Checking with typeof that each field a query uses is text refuses an operator object before it reaches the database.
- Copying a whole request body onto a record lets a member set fields such as role. An allow-list copies only the fields a request may change.
- Error answers say what went wrong in plain words, never the error's own message, its stack trace or database details.
- npm audit checks the packages a project uses against a list of known security holes.
The holes in this lesson are the first ones attackers try against any sign-in or profile route, by hand or with scripts that try them on every API they find. They're on every security checklist an API is reviewed against at work, and each one closes with a few lines you already know how to write.
Operator injection: a body that's a filter
Bean There Coffee Club's sign-in route finds the member by the email in the body, then checks the password:
const member = await members.findOne({ email: req.body.email });
express.json() turns the body into data, and JSON can hold an object anywhere a value goes. So someone sends this:
POST http://localhost:3100/auth/sign-in
Content-Type: application/json
{ "email": { "$gt": "" }, "password": "123456" }
$gt (read "greater than") is one of MongoDB's query operators, from Finding Documents with Filters. The email is no longer text: it's a filter, "any email greater than empty text", which every email is. Run against a members collection holding Dana and Marcus:
const body = JSON.parse('{ "email": { "$gt": "" }, "password": "123456" }');
const member = await members.findOne({ email: body.email });
console.log(member.name, member.email);
Dana dana@beanthere.example
The attacker didn't need anyone's email, and can now guess passwords against Dana's account. This is NoSQL injection: data that sneaks into the shape of a query. (SQL injection is the same idea in SQL databases.)
The fix is to check that each field a query uses is text before it gets there. typeof tells them apart:
const attack = JSON.parse('{ "email": { "$gt": "" }, "password": "123456" }');
const member = JSON.parse('{ "email": "dana@beanthere.example", "password": "dana-test-password" }');
console.log(typeof attack.email);
console.log(typeof member.email);
object
string
So the route answers 400 unless both fields are strings:
const { email, password } = req.body ?? {};
if (typeof email !== "string" || typeof password !== "string") {
sendProblem(res, 400, "Email and password must be text.");
return;
}
A Zod schema with z.string(), as in Validating with Zod, refuses the object too: validating every body closes this hole along with the others.
Mass assignment: a body that sets too much
The club lets members change their own record with PATCH /members/me, and the first version copies the body onto the member. Dana sends a little more than her favorite roast:
const dana = { name: "Dana", favoriteRoast: "Morning Mist", role: "member", cupsLeft: 4 };
const body = JSON.parse('{ "favoriteRoast": "Night Owl", "role": "admin", "cupsLeft": 999 }');
Object.assign(dana, body);
console.log(dana);
{
name: 'Dana',
favoriteRoast: 'Night Owl',
role: 'admin',
cupsLeft: 999
}
Dana is an admin with 999 cups of coffee. That's mass assignment: a request that sets fields the API never meant it to. { ...member, ...req.body } and MongoDB's { $set: req.body } do the same.
The fix is an allow-list: the fields a request may change, copied one by one. in (read "in") asks whether an object has a property:
const changeable = ["name", "favoriteRoast"];
const lucia = { name: "Lucia", favoriteRoast: "Sunrise Blend", role: "member", cupsLeft: 0 };
const body = JSON.parse('{ "name": "Lucia M.", "role": "admin", "cupsLeft": 999 }');
for (const field of changeable) {
if (field in body) {
lucia[field] = body[field];
}
}
console.log(lucia);
{
name: 'Lucia M.',
favoriteRoast: 'Sunrise Blend',
role: 'member',
cupsLeft: 0
}
Why not a block-list instead, deleting role from the body? Because next year someone adds a field such as isVerified, and the block-list doesn't know it. An allow-list lets through only what you named.
Error messages that leak
A sign-up with an email that's taken makes MongoDB throw. An error handler that answers with err.message as its detail sends this to whoever asked (the database's name replaced here by <database>):
{"status":500,"title":"Internal Server Error","detail":"E11000 duplicate key error collection: <database>.members index: email_1 dup key: { email: \"dana@beanthere.example\" }"}
The caller learns the collection, its unique index and that Dana is a member: exactly what one vague sign-in message keeps hidden. Express's own error page is worse: unless NODE_ENV is production, it shows the whole stack trace, with your file paths. Keep the details in your own log and answer in plain words, as Error Handling and Consistent Error Responses does, with a 409 and a plain detail for a taken email:
app.use((err, req, res, next) => {
console.error(err);
sendProblem(res, 500, "Something went wrong on our side.");
});
npm audit: holes in the packages you use
Most of an API's code is other people's packages. npm audit checks the versions you've installed against a list of known security holes:
npm audit
found 0 vulnerabilities
When it finds one, it names the package, how serious it is (low, moderate, high or critical) and the version that fixes it. Package Versions, npm ci and npm audit covers what to do about each warning. Run it before an API goes online, and again whenever you add a package.
Do it: pick the fields a coffee club update may change
The club's PATCH /members/me route needs its two checks as functions it can call: one that keeps only the allowed fields of an update, and one that tells a plain value from an operator object.
Your job: write two functions.
pickAllowedFields(body, allowed):bodyis the update a member sent, an object;allowedis an array of the field names the member may change. Return a new object holding only the fields ofbodywhose names are inallowed, with their values. Fields inallowedthatbodydoesn't have are left out.isPlainValue(value): returntruewhenvalueis a string, a number or a boolean (trueorfalse), andfalsefor anything else: an object such as{ $gt: "" }, an array, ornull.
Worked through: pickAllowedFields({ favoriteRoast: "Night Owl", role: "admin" }, ["name", "favoriteRoast"]) looks at each allowed name. body has no name, so it's left out; it has favoriteRoast, so that's kept; role isn't allowed. It returns { favoriteRoast: "Night Owl" }.
Practiced live on the lesson page: write the JavaScript right there and check it.
Check yourself
2 questions to try on the lesson page.
So what
Check that every field is the kind you expect, copy only the fields you name, and tell callers no more than they need: those three habits close the holes attackers try first on every API, the club's included.