How to Prevent Mass Assignment Vulnerabilities
Stop mass assignment: never spread request data into models, allowlist writable fields per operation, and separate input and persistence shapes.
On this page
Introduction
Mass assignment is a quiet privilege escalation. A model has fields the client may set, like a display name, and fields it must not, like a role or a balance. If the code assigns the request body to the model wholesale, or a framework binds every field automatically, an attacker adds the protected field to the payload and sets it. The hidden field is not in the UI, but nothing stops it being sent.
This tutorial covers why spreading request data is dangerous, how to allowlist the fields each operation may change, how to separate the request shape from the stored record so a direct assignment is impossible, and how to test with payloads that attempt to set privilege fields. The examples use a typical service and apply to any framework that binds input to models.
Never spread request data into a model
The root cause is a direct assignment: update(user, req.body) or new User(req.body), which copies every field the client sent. The convenience hides the risk. Any field present on the model is settable, including ones the product never intended the client to control. Never assign a request body wholesale; copy named fields explicitly, so the set of writable fields is visible in the code.
Framework helpers that auto-bind are the same hazard with extra steps. If a framework fills a model from the request, configure it to allowlist the writable fields or, better, do not use the auto-binding for security-sensitive models. The default should be that nothing is writable unless it is named, not the reverse.
// vulnerable: every field in the body is assigned, including role and isAdmin
await User.update({ where: { id } }, req.body); // attacker sends { isAdmin: true }
await User.create(req.body); // attacker sets protected fields
// fixed: copy only the fields this operation may change
const allowed = pick(req.body, ['displayName', 'timezone', 'locale']);
await User.update({ where: { id } }, allowed);
Allowlist writable fields per operation
Each operation has a different writable set. Creating a profile allows a display name and preferences; updating a profile allows the same; an admin operation may allow a role. Define the allowed fields per operation and copy only those. A role field in a profile payload is then ignored, not rejected with a revealing error, which also avoids telling the attacker which fields exist.
Keep the allowlist next to the operation so it is reviewed with the logic. A shared utility that takes the input and a list of allowed keys, and returns a new object with only those keys, makes the pattern uniform and auditable. Every write path uses it, so a new endpoint cannot forget and spread the body by habit.
function pick<T extends object, K extends keyof T>(src: T, keys: K[]): Pick<T, K> {
const out = {} as Pick<T, K>;
for (const k of keys) if (k in src) out[k] = src[k];
return out;
}
const profileInput = (body: unknown) => pick(body as Record<string, unknown>, ['displayName', 'timezone', 'locale']);
const adminInput = (body: unknown) => pick(body as Record<string, unknown>, ['displayName', 'timezone', 'locale', 'role']);
Separate the input shape from the persistence shape
The strongest structure is to have two types: one for what the client may send, containing only writable fields, and one for what is stored, containing everything. Map explicitly from the input type to the stored record. Then there is no direct assignment possible, because the input type does not have the protected fields, and the compiler rejects an attempt to spread it into the record.
This also makes the boundary visible. The input type is the contract with the client, and the stored type is the internal model. A change to the stored type, such as adding an internal flag, does not accidentally expose it, because the input type does not include it and the mapping does not copy it. The two shapes evolving separately is the point, not an inconvenience.
interface ProfileInput { displayName: string; timezone: string; locale: string }
interface UserRecord {
id: number; displayName: string; timezone: string; locale: string;
role: 'user' | 'admin'; isAdmin: boolean; balanceCents: number;
}
function toRecord(base: UserRecord, input: ProfileInput): UserRecord {
// explicit mapping: protected fields come from base, never from input
return { ...base, displayName: input.displayName, timezone: input.timezone, locale: input.locale };
}
Validate strictly and reject unknown fields
Pair the allowlist with a strict schema that rejects unknown fields, so a payload with an unexpected field is refused at the boundary with a clear message for well-behaved clients. Strict validation catches the mistake early and documents the contract, while the allowlist mapping ensures that even if something passes validation, only named fields are written.
Be careful not to reveal too much in the rejection. A generic ‘unknown field’ error is fine for most APIs, but if the field name is itself sensitive, a generic message avoids confirming which fields exist. The combination of strict validation and explicit mapping means you do not have to choose between a good developer experience and safety: reject clearly at the edge, write narrowly inside.
const ProfileSchema = z.object({
displayName: z.string().min(1).max(80),
timezone: z.string().max(64),
locale: z.string().max(16),
}).strict(); // reject unknown fields, including role and isAdmin
Test with privilege-field payloads
Send payloads that include fields the client must not control: role set to admin, isAdmin true, ownerId of another user, and a numeric balance or a credit amount. Assert each is either rejected by the strict schema or ignored by the allowlist mapping, and that the stored record’s protected fields are unchanged. Repeat for create and update, because the two often differ.
Also test that a legitimate field is written, so the fix does not block normal use. And test the nested case: a payload with a nested object that contains a protected field should not let that field through a deep merge. Assert the record after the request has the intended value for writable fields and the original value for protected ones.
curl -s -X PATCH -H "Authorization: Bearer $USER" -H 'content-type: application/json' \
-d '{"displayName":"ok","role":"admin","isAdmin":true,"balanceCents":999999}' http://localhost:3000/me
curl -s -H "Authorization: Bearer $USER" http://localhost:3000/me
# assert role is still 'user', isAdmin false, balanceCents unchanged, displayName = 'ok'
Common pitfalls
Spreading req.body into a model, using a framework’s auto-binding without an allowlist, deep-merging a nested payload that carries a protected field, relying on the UI hiding a field instead of the server rejecting it, and a different writable set on create and update that leaves one path open are the recurring mistakes. Explicit field copying, per-operation allowlists, separate input and record types, and strict validation address them.
Conclusion
Mass assignment lets a client set a field it should not, simply by sending it. Never spread request data into a model, allowlist the writable fields per operation, separate the input type from the record type so direct assignment is impossible, and validate strictly. Self-check by sending role, isAdmin, ownerId, and a balance in the payload and asserting none takes effect. Then only the fields you name are ever written.
Sources: OWASP: Mass assignment cheat sheet, OWASP: Insecure direct object references and mass assignment, OWASP: API security — broken object property level authorization.
FAQ
- What exactly is mass assignment?
- It is when a framework or your code binds request fields to object properties automatically, so any field the client sends is set. If a model has a role or isAdmin field the client should not control, sending it in the payload escalates the user. The fix is to allowlist the writable fields.
- Is validating the schema enough?
- A strict schema that rejects unknown fields helps, but the durable fix is a separate input type that contains only writable fields, and mapping explicitly from it to the stored record. Then even a valid extra field cannot reach a protected property.
Report a problem with this articleOpens a pre-filled issue on GitHub.