Skip to main content
Security guideReviewed

Mass assignment vulnerability: when a request sets fields the form never offered

A mass assignment vulnerability is a handler that copies every field a client sends onto a stored record, so the client can set fields the form never offered: a role, a price, an owner, a verified flag.

This guide explains the mistake in plain terms, which fields matter, why a list of allowed fields holds where a list of banned ones does not, and what each framework's documentation gives you. It comes with a request-diff method and worksheet for your own write endpoints, and a local lab with regression tests that fail until the privileged fields stop changing.

Request-diff method, worksheet and lab

An illustration written for this page, not client code. Parts 1 and 2 are a request-diff method and a worksheet for your own write endpoints: list what the client sends and what the record stores, mark each stored field as client-writable, set by the server or never changed by the operation, then compare the stored record after the intended request and after the same request with extra fields.

How to use it

The rest is a Node.js lab with nothing to install: an invented tea shop's profile, order and admin endpoints in a careless version, a block-list version and two careful versions (one refuses unknown fields, one drops them), the request, the response and the stored record for each case, and regression tests, one per privileged property, that fail on the careless version and pass on both careful ones. Recorded on Node.js v26.0.0.

mass-assignment.txt

MASS ASSIGNMENT: REQUEST-DIFF METHOD, WORKSHEET AND LAB
Written for this page. Parts 1 and 2 work without the lab: a method for testing every write endpoint, and a worksheet to fill in for each one. Part 3 onwards is the lab, an illustration that runs the method against an invented tea shop's API on your own machine, in a careless version, a block-list version and two careful versions (one refuses unknown fields, one drops them).

Use the method only on an application you own, or one you are authorised in writing to test, with test accounts and test records, on staging where you can. Nothing here is for changing a role, a price or an owner on someone else's service.

==== PART 1. THE REQUEST-DIFF METHOD ====
A write endpoint is any route that creates or changes a stored record: sign-up, profile edit, checkout, an admin screen, an import, a webhook. For each one:

  1. List the fields the form or client sends. Take them from a real request, not from the design.
  2. List the fields the stored record has. Take them from the database schema or the model, not from the screen, and include the fields no screen shows.
  3. Mark every stored field, for this operation, as one of three classes:
       CLIENT  The request may set it. Write down the rule for its value (type, length, range, allowed values).
       SERVER  The server sets it. Write down where the value comes from (the session, a price list, a clock, a counter). A value the request sends for it is not used.
       NEVER   This operation leaves it exactly as it was.
     A field name that is on neither list is not a field of the record, and must not appear on it afterwards.
  4. Save a copy of the stored record ("before"). Send the intended request. Save the stored record again ("after intended"). Restore the record.
  5. Send the intended request again with extra fields added. Save the stored record ("after extra"). Restore the record. Repeat for each extra field in the list below.
  6. Compare the stored records, not the responses. The extra fields must make no difference outside the CLIENT fields:
       - no NEVER field differs from "before";
       - every SERVER field holds the value it holds in "after intended";
       - no field has appeared that is not a field of the record.
     A refusal that leaves the record exactly as it was passes too.

EXTRA FIELDS TO SEND, ONE REQUEST EACH
  - Every NEVER and SERVER field of the record, by its exact name, with a value that would benefit the sender: a higher role, a lower price, another owner, a verified flag set to true, a status further along.
  - Every field the endpoint's own response shows that the form does not send.
  - Every field an administrator's version of the screen sends, from an ordinary account.
  - A privileged field inside each nested object or list entry the request carries, such as a unit price inside an order line.
  - A privileged field under each wrapper the client uses, such as user or account, if the client nests its fields.
  - The same names in another letter case and another naming style: Role, ROLE, is_admin beside isAdmin, owner_id beside ownerId.
  - A field name that does not exist at all, to see what the endpoint does with an unknown field.

EVIDENCE TO KEEP FOR EVERY REQUEST, PASS OR FAIL
  - The build or commit, the environment and the date.
  - The test account's label, not its session token.
  - The method, the path and the full body sent.
  - The response status and body.
  - The stored record before and after, read from the database, with personal details redacted.
  - Each field that changed, its class, and whether the change is inside the plan.
  - What the request created or changed, and how it was restored.

==== PART 2. THE WORKSHEET ====
Copy one block per write endpoint. Fill in the first two parts before you send anything.

  ENDPOINT
    Method and path: ........................................................
    What it does, in one sentence: ..........................................
    Who may call it, and on whose record: ...................................
    Record written (table or collection): ...................................
    Fields the form or client sends: ........................................

  STORED FIELDS (one line for every field of the record)
    Field name .............  Class: CLIENT / SERVER / NEVER  Rule for the value, or where the server gets it ................
    Field name .............  Class: CLIENT / SERVER / NEVER  Rule for the value, or where the server gets it ................
    Field name .............  Class: CLIENT / SERVER / NEVER  Rule for the value, or where the server gets it ................
    (continue until every stored field has a line, including nested fields)

  UNKNOWN FIELDS
    This endpoint: REFUSES the request / IGNORES the field. Reason: .........................

  REQUESTS SENT
    Intended request ..............  Status ....  Stored record changed only as planned: yes / no
    Extra field ...................  Status ....  Any change outside the plan: yes / no  Which field: ................
    Extra field ...................  Status ....  Any change outside the plan: yes / no  Which field: ................
    (one line per extra field from the list in Part 1)

  RESULT
    Fields outside the plan that changed: ...................................
    Regression test added for each: yes / no

THE WORKSHEET FILLED IN FOR THE LAB'S THREE OPERATIONS
The lab's account record has eight fields and its order record has six, with three more inside each order line.

  Profile edit: PATCH /account. A signed-in customer edits their own account. The form sends displayName and phone.
    id                NEVER
    email             NEVER   Changing an email address is a flow of its own, with a confirmation step.
    displayName       CLIENT  Text, at most 60 characters.
    phone             CLIENT  Text, at most 20 characters.
    role              NEVER
    emailVerified     NEVER
    storeCreditCents  NEVER
    updatedBy         SERVER  The signed-in account's id.

  New order: POST /orders. A signed-in customer places an order. The client sends items (each with sku and quantity) and deliveryNote.
    id                    SERVER  The next order number.
    ownerId               SERVER  The signed-in account's id.
    status                SERVER  Always pending for a new order.
    items.sku             CLIENT  One of the catalogue's item codes.
    items.quantity        CLIENT  A whole number between 1 and 20.
    items.unitPriceCents  SERVER  The catalogue price for that item code.
    deliveryNote          CLIENT  Text, at most 200 characters.
    totalCents            SERVER  Worked out from the stored quantities and catalogue prices.

  Admin edit: PATCH /admin/accounts/:id. An admin edits another account. The admin screen sends role and storeCreditCents.
    id                NEVER
    email             NEVER
    displayName       NEVER
    phone             NEVER
    role              CLIENT  customer or staff. The screen does not offer admin.
    emailVerified     NEVER
    storeCreditCents  CLIENT  A whole number between 0 and 50000.
    updatedBy         SERVER  The signed-in admin's id.

  The same account record, three write lists. Sign-up is not in the lab, and its column is this page's suggestion for a shop like this one.
    Field             Sign-up                       Profile edit   Admin edit
    id                SERVER                        NEVER          NEVER
    email             CLIENT, then confirmed        NEVER          NEVER
    displayName       CLIENT                        CLIENT         NEVER
    phone             SERVER (empty)                CLIENT         NEVER
    role              SERVER (customer)             NEVER          CLIENT
    emailVerified     SERVER (false)                NEVER          NEVER
    storeCreditCents  SERVER (0)                    NEVER          CLIENT
    updatedBy         SERVER                        SERVER         SERVER

==== PART 3. THE LAB (AN ILLUSTRATION) ====
The tea shop, its three accounts, its catalogue, its phone number and its orders are invented. Everything is held in memory, money is counted in whole cents, and nothing is charged or sent anywhere. The lab shows the pattern. It does not reproduce the behaviour of any real framework, binder or database.

The API runs as its own process. It listens only on 127.0.0.1, on a port the operating system assigns because the lab asks for port 0, and the runner stops it by its process id when a run ends. Apart from each other, the lab's files import only node:child_process, node:http, node:url, node:assert/strict and node:test, and the lab installs no packages.

Written and run on: Node.js v26.0.0 on macOS 27.2.1. Every output below was copied from that run's captured output by a script. Test timings will differ on your machine. The Node.js documentation marks node:test stable from v20.0.0, and the lab has been run only on v26.0.0.

Setup: create an empty folder, save the eight files below into it under the names shown, and open a terminal in it.

The accounts: cust-mira and cust-theo are customers, and staff-priya is an admin. The three endpoints:
  PATCH /account                 A customer edits their own profile.
  POST /orders                   A customer places an order.
  PATCH /admin/accounts/:id      An admin changes another account's role or store credit. Every version refuses a customer here with 403.

The four versions share server.mjs, so they check who is signed in and who may call the admin endpoint in the same way. They differ in which fields a successful response returns (the careless and block-list versions answer with the stored record itself, and the two careful versions answer with the fields on a read list, VIEW_FIELDS in careful.mjs) and in how they treat the request body:
  careless        Each handler copies the request body onto the stored record.
  blocklist       The same copy, after removing a short list of field names: role on the profile edit, ownerId and totalCents on a new order, id on the admin edit.
  careful         One written input shape per operation lists the fields the client may send. A request that carries any other field is refused with 422 and a message naming the field. Server-set fields are never read from the body.
  careful-ignore  The same input shapes, but an unknown field is dropped and the request carries on.

================================================================
FILE 1 OF 8: shop.mjs
================================================================

// shop.mjs: the invented tea shop's catalogue, accounts and lab sign-in.
// Illustration only. Every name, address, number and record here is invented.
// Records live in memory and are gone when the process exits. Money is whole cents.

export const CATALOGUE = {
  'TEA-ASSAM-100': { name: 'Assam, 100 g tin', unitPriceCents: 1800 },
  'TEA-SENCHA-100': { name: 'Sencha, 100 g tin', unitPriceCents: 2400 },
  'POT-GLASS-600': { name: 'Glass teapot, 600 ml', unitPriceCents: 5200 },
}

// Lab-only sign-in: one fixed token per invented account, which a request
// sends in a header named x-lab-token. A real service issues a random session
// token at sign-in.
export const TOKENS = {
  'cust-mira': 'lab-token-mira',
  'cust-theo': 'lab-token-theo',
  'staff-priya': 'lab-token-priya',
}

// The stored records. An account has eight fields and an order has six.
// Positions in the accounts list: 0 is Mira, 1 is Theo, 2 is Priya.
export function createStore() {
  return {
    accounts: [
      { id: 'cust-mira', email: 'mira@teashop.example', displayName: 'Mira', phone: '', role: 'customer', emailVerified: false, storeCreditCents: 0, updatedBy: 'sign-up' },
      { id: 'cust-theo', email: 'theo@teashop.example', displayName: 'Theo', phone: '', role: 'customer', emailVerified: false, storeCreditCents: 0, updatedBy: 'sign-up' },
      { id: 'staff-priya', email: 'priya@teashop.example', displayName: 'Priya', phone: '', role: 'admin', emailVerified: true, storeCreditCents: 0, updatedBy: 'sign-up' },
    ],
    orders: [],
  }
}

export function findAccountByToken(store, token) {
  for (const accountId of Object.keys(TOKENS)) {
    if (TOKENS[accountId] === token) return findAccountById(store, accountId)
  }
  return null
}

export function findAccountById(store, accountId) {
  return store.accounts.find((account) => account.id === accountId) || null
}

export function nextOrderId(store) {
  return 'order-' + (1001 + store.orders.length)
}

// The catalogue price of one item, or 0 for an item the shop does not sell.
export function priceOf(sku) {
  return Object.hasOwn(CATALOGUE, sku) ? CATALOGUE[sku].unitPriceCents : 0
}

// Adds up the lines of an order from the unit price and quantity each line holds.
export function totalOf(items) {
  let totalCents = 0
  for (const item of items) totalCents += item.unitPriceCents * item.quantity
  return totalCents
}

================================================================
FILE 2 OF 8: careless.mjs
================================================================

// careless.mjs: the three write operations as a team might first write them,
// and the same three behind a block-list of field names.
//   careless   each handler copies the request body onto the stored record
//   blocklist  the same copy, after removing a short list of field names
// Every handler receives { user, store, account, body }: the signed-in account,
// the records, an account record and the parsed JSON body. The two edits write
// that account record. createOrder is handed the signed-in account and writes
// an order, not the account.
import { nextOrderId, priceOf, totalOf } from './shop.mjs'

// ---------------------------------------------------------------------------
// CARELESS: the request body is copied onto the record. Two values are set
// after the copy and replace what the client sent under the same name:
// updatedBy on an account, and the items list on an order.
// ---------------------------------------------------------------------------

// Server values first, then the body's fields on top of them, then the items
// list: each sent item copied on top of its catalogue price.
function buildOrderByCopying(user, store, body) {
  const sentItems = Array.isArray(body.items) ? body.items : []
  const items = sentItems.map((item) => Object.assign({ unitPriceCents: priceOf(item.sku) }, item))
  const serverValues = { id: nextOrderId(store), ownerId: user.id, status: 'pending', deliveryNote: '', totalCents: totalOf(items) }
  return Object.assign(serverValues, body, { items: items })
}

export const careless = {
  editProfile: ({ user, account, body }) => {
    Object.assign(account, body)
    account.updatedBy = user.id
    return { status: 200, body: account }
  },

  createOrder: ({ user, store, body }) => {
    const order = buildOrderByCopying(user, store, body)
    store.orders.push(order)
    return { status: 201, body: order }
  },

  adminEditAccount: ({ user, account, body }) => {
    Object.assign(account, body)
    account.updatedBy = user.id
    return { status: 200, body: account }
  },
}

// ---------------------------------------------------------------------------
// BLOCKLIST: the same copy, minus the field names someone thought to list.
// Each list is as it stood when its handler was written. The lists compare
// top-level names exactly, and nobody has added to them since.
// ---------------------------------------------------------------------------

const BLOCKED_FIELDS = {
  editProfile: ['role'],
  createOrder: ['ownerId', 'totalCents'],
  adminEditAccount: ['id'],
}

function withoutBlockedFields(operation, body) {
  const kept = {}
  for (const name of Object.keys(body)) {
    if (!BLOCKED_FIELDS[operation].includes(name)) kept[name] = body[name]
  }
  return kept
}

export const blocklist = {
  editProfile: ({ user, store, account, body }) => {
    const keptBody = withoutBlockedFields('editProfile', body)
    return careless.editProfile({ user: user, store: store, account: account, body: keptBody })
  },

  createOrder: ({ user, store, account, body }) => {
    const keptBody = withoutBlockedFields('createOrder', body)
    return careless.createOrder({ user: user, store: store, account: account, body: keptBody })
  },

  adminEditAccount: ({ user, store, account, body }) => {
    const keptBody = withoutBlockedFields('adminEditAccount', body)
    return careless.adminEditAccount({ user: user, store: store, account: account, body: keptBody })
  },
}

================================================================
FILE 3 OF 8: careful.mjs
================================================================

// careful.mjs: the same three operations with one written input shape each.
// A shape lists every field the client may send for that operation and the
// rule for its value. Anything else is an unknown field. The handlers copy
// nothing: they name each field they write, and server-set fields (the owner,
// the prices, the status, who made the change) are never read from the body.
//   careful         refuses a request that carries an unknown field
//   careful-ignore  drops unknown fields and carries on
import { CATALOGUE, nextOrderId, priceOf, totalOf } from './shop.mjs'

// The write lists, one per operation. In other stacks each of these is a data
// transfer object (DTO). orderItem is the shape of one entry in an order's items.
export const INPUT_SHAPES = {
  editProfile: {
    displayName: { kind: 'text', maxLength: 60 },
    phone: { kind: 'text', maxLength: 20 },
  },
  createOrder: {
    items: { kind: 'list', maxLength: 20, entryShape: 'orderItem', required: true },
    deliveryNote: { kind: 'text', maxLength: 200 },
  },
  orderItem: {
    sku: { kind: 'choice', choices: Object.keys(CATALOGUE), required: true },
    quantity: { kind: 'wholeNumber', min: 1, max: 20, required: true },
  },
  adminEditAccount: {
    role: { kind: 'choice', choices: ['customer', 'staff'] },
    storeCreditCents: { kind: 'wholeNumber', min: 0, max: 50000 },
  },
}

// The read lists: what each response may show. They are separate from the
// write lists. A customer may read their own role and store credit, and may
// send neither.
const VIEW_FIELDS = {
  profile: ['id', 'email', 'displayName', 'phone', 'role', 'emailVerified', 'storeCreditCents'],
  order: ['id', 'status', 'items', 'deliveryNote', 'totalCents'],
  accountForAdmin: ['id', 'email', 'displayName', 'phone', 'role', 'emailVerified', 'storeCreditCents', 'updatedBy'],
}

function view(viewName, record) {
  const shown = {}
  for (const field of VIEW_FIELDS[viewName]) shown[field] = record[field]
  return shown
}

function refuse(message) {
  return { status: 422, body: { error: message } }
}

function isPlainObject(value) {
  return value !== null && typeof value === 'object' && !Array.isArray(value)
}

function readText(rule, value, label) {
  const isValid = typeof value === 'string' && value.length <= rule.maxLength
  return isValid ? { value: value } : { error: label + ' must be text of at most ' + rule.maxLength + ' characters' }
}

function readWholeNumber(rule, value, label) {
  const isValid = Number.isInteger(value) && value >= rule.min && value <= rule.max
  return isValid ? { value: value } : { error: label + ' must be a whole number between ' + rule.min + ' and ' + rule.max }
}

function readChoice(rule, value, label) {
  const isValid = rule.choices.includes(value)
  return isValid ? { value: value } : { error: label + ' must be one of: ' + rule.choices.join(', ') }
}

function readList(rule, value, label, unknownFields) {
  const isValid = Array.isArray(value) && value.length >= 1 && value.length <= rule.maxLength
  if (!isValid) return { error: label + ' must be a list of 1 to ' + rule.maxLength + ' entries' }
  const entries = []
  for (const entry of value) {
    const result = readInput(rule.entryShape, entry, unknownFields)
    if (result.error) return result
    entries.push(result.input)
  }
  return { value: entries }
}

function readField(rule, value, label, unknownFields) {
  if (rule.kind === 'text') return readText(rule, value, label)
  if (rule.kind === 'wholeNumber') return readWholeNumber(rule, value, label)
  if (rule.kind === 'choice') return readChoice(rule, value, label)
  return readList(rule, value, label, unknownFields)
}

// Checks a request value against a shape. Returns { input }, which holds the
// listed fields and nothing else, or { error }. unknownFields is 'refuse' or 'ignore'.
function readInput(shapeName, value, unknownFields) {
  if (!isPlainObject(value)) return { error: shapeName + ' expects a JSON object' }
  const shape = INPUT_SHAPES[shapeName]
  const unknownNames = Object.keys(value).filter((name) => !Object.hasOwn(shape, name))
  if (unknownNames.length > 0 && unknownFields === 'refuse') {
    return { error: shapeName + ' does not accept: ' + unknownNames.join(', ') }
  }
  const input = {}
  for (const name of Object.keys(shape)) {
    const rule = shape[name]
    if (!Object.hasOwn(value, name)) {
      if (rule.required) return { error: shapeName + ' needs the field: ' + name }
      continue
    }
    const result = readField(rule, value[name], shapeName + '.' + name, unknownFields)
    if (result.error) return result
    input[name] = result.value
  }
  return { input: input }
}

function createCarefulHandlers(unknownFields) {
  return {
    editProfile: ({ user, account, body }) => {
      const result = readInput('editProfile', body, unknownFields)
      if (result.error) return refuse(result.error)
      if (result.input.displayName !== undefined) account.displayName = result.input.displayName
      if (result.input.phone !== undefined) account.phone = result.input.phone
      account.updatedBy = user.id
      return { status: 200, body: view('profile', account) }
    },

    createOrder: ({ user, store, body }) => {
      const result = readInput('createOrder', body, unknownFields)
      if (result.error) return refuse(result.error)
      const items = result.input.items.map((item) => ({ sku: item.sku, quantity: item.quantity, unitPriceCents: priceOf(item.sku) }))
      const order = {
        id: nextOrderId(store),
        ownerId: user.id,
        status: 'pending',
        items: items,
        deliveryNote: result.input.deliveryNote || '',
        totalCents: totalOf(items),
      }
      store.orders.push(order)
      return { status: 201, body: view('order', order) }
    },

    adminEditAccount: ({ user, account, body }) => {
      const result = readInput('adminEditAccount', body, unknownFields)
      if (result.error) return refuse(result.error)
      if (result.input.role !== undefined) account.role = result.input.role
      if (result.input.storeCreditCents !== undefined) account.storeCreditCents = result.input.storeCreditCents
      account.updatedBy = user.id
      return { status: 200, body: view('accountForAdmin', account) }
    },
  }
}

export const careful = createCarefulHandlers('refuse')
export const carefulIgnore = createCarefulHandlers('ignore')

================================================================
FILE 4 OF 8: server.mjs
================================================================

// server.mjs: the shop API over HTTP, in the version named on the command
// line. It listens on 127.0.0.1 only, on a port the operating system picks,
// and is started and stopped by request-diff.mjs. Every version shares this
// file, so they all check who is signed in and who may call the admin
// endpoint in the same way. They differ in how they treat the request body
// and in which fields of the stored record a response returns.
import { createServer } from 'node:http'
import { careful, carefulIgnore } from './careful.mjs'
import { blocklist, careless } from './careless.mjs'
import { createStore, findAccountById, findAccountByToken } from './shop.mjs'

const VERSIONS = { careless: careless, blocklist: blocklist, careful: careful, 'careful-ignore': carefulIgnore }
const version = process.argv[2]
const handlers = VERSIONS[version]
if (!handlers) throw new Error('Name a version: ' + Object.keys(VERSIONS).join(', '))

const ADMIN_PATH = '/admin/accounts/'
let store = createStore()

function refuse(status, message) {
  return { status: status, body: { error: message } }
}

// Lab-only sign-in: the request names its account with a fixed token.
function readSignedInAccount(request) {
  const token = request.headers['x-lab-token'] || ''
  return findAccountByToken(store, token)
}

// Which operation a request is, and which account record its handler is given:
// the signed-in account, or on the admin path the account the path names.
function matchOperation(method, pathname, user) {
  if (method === 'PATCH' && pathname === '/account') return { name: 'editProfile', account: user }
  if (method === 'POST' && pathname === '/orders') return { name: 'createOrder', account: user }
  if (method === 'PATCH' && pathname.startsWith(ADMIN_PATH)) {
    const accountId = pathname.slice(ADMIN_PATH.length)
    return { name: 'adminEditAccount', account: findAccountById(store, accountId) }
  }
  return null
}

function readJsonBody(request) {
  return new Promise((resolve) => {
    let text = ''
    request.on('data', (chunk) => {
      text += chunk
    })
    request.on('end', () => {
      try {
        resolve(JSON.parse(text))
      } catch {
        resolve(null)
      }
    })
  })
}

async function answer(request) {
  const user = readSignedInAccount(request)
  if (!user) return refuse(401, 'not signed in')
  const pathname = new URL(request.url, 'http://127.0.0.1').pathname
  const operation = matchOperation(request.method, pathname, user)
  if (!operation) return refuse(404, 'not found')
  if (operation.name === 'adminEditAccount' && user.role !== 'admin') return refuse(403, 'only an admin may call this endpoint')
  if (!operation.account) return refuse(404, 'not found')
  const body = await readJsonBody(request)
  if (body === null || typeof body !== 'object' || Array.isArray(body)) return refuse(400, 'the body must be a JSON object')
  return handlers[operation.name]({ user: user, store: store, account: operation.account, body: body })
}

const server = createServer(async (request, response) => {
  const result = await answer(request)
  response.writeHead(result.status, { 'content-type': 'application/json' })
  response.end(JSON.stringify(result.body))
})

// Lab-only channel to the process that started this one: fresh records before
// each request, and a copy of the stored records to compare. A real service
// has neither. In your own tests, read the database.
process.on('message', (message) => {
  if (message === 'reset') {
    store = createStore()
    process.send({ type: 'reset' })
  }
  if (message === 'snapshot') process.send({ type: 'snapshot', store: store })
})

// Port 0 asks the operating system for any unused port.
server.listen(0, '127.0.0.1', () => {
  process.send({ type: 'ready', port: server.address().port, processId: process.pid })
})

================================================================
FILE 5 OF 8: field-plan.mjs
================================================================

// field-plan.mjs: the worksheet as data, and the requests the lab sends.
// FIELD_PLAN has one entry per write operation and one line per stored field:
//   client  the request may set it, within the operation's rules
//   server  the server sets it, and extra fields in the request do not change it
//   never   this operation leaves it exactly as it was
// A stored field with no line here is not a field of the record at all.

export const FIELD_PLAN = {
  editProfile: {
    id: 'never',
    email: 'never',
    displayName: 'client',
    phone: 'client',
    role: 'never',
    emailVerified: 'never',
    storeCreditCents: 'never',
    updatedBy: 'server',
  },
  createOrder: {
    id: 'server',
    ownerId: 'server',
    status: 'server',
    'items.sku': 'client',
    'items.quantity': 'client',
    'items.unitPriceCents': 'server',
    deliveryNote: 'client',
    totalCents: 'server',
  },
  adminEditAccount: {
    id: 'never',
    email: 'never',
    displayName: 'never',
    phone: 'never',
    role: 'client',
    emailVerified: 'never',
    storeCreditCents: 'client',
    updatedBy: 'server',
  },
}

const MIRA = 'cust-mira'
const PRIYA = 'staff-priya'

// Which stored record each operation's requests are compared on.
const MIRA_ACCOUNT = { list: 'accounts', position: 0 }
const THEO_ACCOUNT = { list: 'accounts', position: 1 }
const FIRST_ORDER = { list: 'orders', position: 0 }

const PROFILE = { as: MIRA, method: 'PATCH', path: '/account', operation: 'editProfile', watch: MIRA_ACCOUNT }
const ORDER = { as: MIRA, method: 'POST', path: '/orders', operation: 'createOrder', watch: FIRST_ORDER }
const ADMIN = { as: PRIYA, method: 'PATCH', path: '/admin/accounts/cust-theo', operation: 'adminEditAccount', watch: THEO_ACCOUNT }

const TWO_TINS = { sku: 'TEA-ASSAM-100', quantity: 2 }

function defineCase(id, endpoint, title, body, details) {
  return Object.assign({ id: id, title: title, body: body }, endpoint, details)
}

// The first case for each endpoint is the intended request: what the form or
// client really sends. A case with a property is that request with extra
// fields: it names the intended case it is compared with and the privileged
// property it protects. A1 is a control: the admin request from a customer.
export const CASES = [
  defineCase('P0', PROFILE, 'Profile edit, as the form sends it', { displayName: 'Mira K.', phone: '0491 570 156' }, {}),
  defineCase('P1', PROFILE, 'Profile edit with a role added', { displayName: 'Mira K.', phone: '0491 570 156', role: 'admin' }, {
    compareWith: 'P0',
    property: 'role stays as it was on a profile edit',
  }),
  defineCase('P2', PROFILE, 'Profile edit with Role added, in a different letter case', { displayName: 'Mira K.', phone: '0491 570 156', Role: 'admin' }, {
    compareWith: 'P0',
    property: 'a differently cased Role is not stored',
  }),
  defineCase('P3', PROFILE, 'Profile edit with the verified flag added', { displayName: 'Mira K.', phone: '0491 570 156', emailVerified: true }, {
    compareWith: 'P0',
    property: 'emailVerified stays as it was on a profile edit',
  }),
  defineCase('P4', PROFILE, 'Profile edit with store credit added', { displayName: 'Mira K.', phone: '0491 570 156', storeCreditCents: 50000 }, {
    compareWith: 'P0',
    property: 'storeCreditCents stays as it was on a profile edit',
  }),

  defineCase('O0', ORDER, 'New order, as the client sends it', { items: [TWO_TINS], deliveryNote: 'Leave at the front desk' }, {}),
  defineCase('O1', ORDER, 'New order with an owner added', { items: [TWO_TINS], deliveryNote: 'Leave at the front desk', ownerId: 'cust-theo' }, {
    compareWith: 'O0',
    property: 'ownerId is the signed-in account',
  }),
  defineCase('O2', ORDER, 'New order with a total added', { items: [TWO_TINS], deliveryNote: 'Leave at the front desk', totalCents: 1 }, {
    compareWith: 'O0',
    property: 'totalCents is worked out by the server',
  }),
  defineCase('O3', ORDER, 'New order with a unit price inside the nested item', {
    items: [{ sku: 'TEA-ASSAM-100', quantity: 2, unitPriceCents: 1 }],
    deliveryNote: 'Leave at the front desk',
  }, {
    compareWith: 'O0',
    property: 'unitPriceCents inside items comes from the catalogue',
  }),
  defineCase('O4', ORDER, 'New order with a status added', { items: [TWO_TINS], deliveryNote: 'Leave at the front desk', status: 'paid' }, {
    compareWith: 'O0',
    property: 'status starts as pending',
  }),

  defineCase('A0', ADMIN, 'Admin edit, as the admin screen sends it', { role: 'staff', storeCreditCents: 1500 }, {}),
  defineCase('A1', ADMIN, 'The same admin edit, sent by a customer', { role: 'staff', storeCreditCents: 1500 }, { as: MIRA }),
  defineCase('A2', ADMIN, 'Admin edit with an email address and the verified flag added', {
    role: 'staff',
    storeCreditCents: 1500,
    email: 'someone-else@teashop.example',
    emailVerified: true,
  }, {
    compareWith: 'A0',
    property: 'email and emailVerified stay as they were on an admin edit',
  }),
  defineCase('A3', ADMIN, 'Admin edit with an id added', { role: 'staff', storeCreditCents: 1500, id: 'cust-mira' }, {
    compareWith: 'A0',
    property: 'id stays as it was on an admin edit',
  }),
]

================================================================
FILE 6 OF 8: request-diff.mjs
================================================================

// request-diff.mjs: sends every case to one version of the API and compares
// the stored record before and after each request with the field plan.
// The API runs as its own process, started here and stopped by its process id
// when the run ends. Every request starts from the same seeded records.
import { fork } from 'node:child_process'
import { request as httpRequest } from 'node:http'
import { fileURLToPath } from 'node:url'
import { CASES, FIELD_PLAN } from './field-plan.mjs'
import { TOKENS } from './shop.mjs'

const SERVER_FILE = fileURLToPath(new URL('./server.mjs', import.meta.url))

const CLASS_LABELS = {
  client: 'client-writable',
  server: 'set by the server',
  never: 'never changed by this operation',
  unlisted: 'not a field of this record',
}

// ---------------------------------------------------------------------------
// Comparing two copies of a stored record.
// ---------------------------------------------------------------------------

// Writes one line per field, so nested values can be compared one by one:
// { items: [{ sku: 'A' }] } becomes the line 'items.0.sku' holding '"A"'.
function addFieldLines(lines, path, value) {
  const isContainer = value !== null && typeof value === 'object' && Object.keys(value).length > 0
  if (!isContainer) {
    lines[path] = JSON.stringify(value)
    return
  }
  for (const name of Object.keys(value)) addFieldLines(lines, path ? path + '.' + name : name, value[name])
}

function listFieldLines(record) {
  const lines = {}
  if (record !== null) addFieldLines(lines, '', record)
  return lines
}

function isListPosition(pathPart) {
  return pathPart !== '' && String(Number(pathPart)) === pathPart
}

// 'items.0.unitPriceCents' is planned as 'items.unitPriceCents'.
function classOf(operation, path) {
  const planPath = path.split('.').filter((part) => !isListPosition(part)).join('.')
  const plan = FIELD_PLAN[operation]
  return Object.hasOwn(plan, planPath) ? plan[planPath] : 'unlisted'
}

function showValue(line) {
  return line === undefined ? '(absent)' : line
}

// A change is outside the plan when the field is one this operation never
// changes, is not a field of the record, or is a server-set field holding a
// value other than the one the intended request leaves there.
function isOutsideThePlan(fieldClass, afterLine, intendedLine) {
  if (fieldClass === 'client') return false
  if (fieldClass === 'server') return afterLine !== intendedLine
  return true
}

// For a server-set field outside the plan, add the value the intended request leaves.
function describeClass(fieldClass, isOutside, intendedLine) {
  if (fieldClass === 'server' && isOutside) return 'set by the server, which sets ' + showValue(intendedLine)
  return CLASS_LABELS[fieldClass]
}

// Every field that differs between before and after, with its class.
export function listChanges(operation, before, after, afterIntended) {
  const beforeLines = listFieldLines(before)
  const afterLines = listFieldLines(after)
  const intendedLines = listFieldLines(afterIntended)
  const paths = Object.keys(Object.assign({}, beforeLines, afterLines))
  const changes = []
  for (const path of paths) {
    if (beforeLines[path] === afterLines[path]) continue
    const fieldClass = classOf(operation, path)
    const isOutside = isOutsideThePlan(fieldClass, afterLines[path], intendedLines[path])
    const classText = describeClass(fieldClass, isOutside, intendedLines[path])
    changes.push({
      path: path,
      text: path + ': ' + showValue(beforeLines[path]) + ' -> ' + showValue(afterLines[path]) + ' (' + classText + ')',
      isOutsideThePlan: isOutside,
    })
  }
  return changes
}

// ---------------------------------------------------------------------------
// Starting, asking and stopping the API process.
// ---------------------------------------------------------------------------

function startServer(version) {
  const child = fork(SERVER_FILE, [version])
  return new Promise((resolve) => {
    child.once('message', (ready) => resolve({ child: child, port: ready.port, processId: ready.processId }))
  })
}

function askServer(server, message) {
  return new Promise((resolve) => {
    server.child.once('message', resolve)
    server.child.send(message)
  })
}

function stopServer(server) {
  return new Promise((resolve) => {
    server.child.once('exit', resolve)
    process.kill(server.processId)
  })
}

function sendRequest(port, testCase) {
  const text = JSON.stringify(testCase.body)
  const options = {
    host: '127.0.0.1',
    port: port,
    method: testCase.method,
    path: testCase.path,
    headers: {
      'content-type': 'application/json',
      'content-length': Buffer.byteLength(text),
      'x-lab-token': TOKENS[testCase.as],
    },
  }
  return new Promise((resolve, reject) => {
    const request = httpRequest(options, (response) => {
      let body = ''
      response.setEncoding('utf8')
      response.on('data', (chunk) => {
        body += chunk
      })
      response.on('end', () => resolve({ status: response.statusCode, body: body }))
    })
    request.on('error', reject)
    request.end(text)
  })
}

async function readWatchedRecord(server, testCase) {
  const snapshot = await askServer(server, 'snapshot')
  const record = snapshot.store[testCase.watch.list][testCase.watch.position]
  return record === undefined ? null : record
}

// Fresh records, the stored record before, the request, the stored record after.
async function playCase(server, testCase) {
  await askServer(server, 'reset')
  const before = await readWatchedRecord(server, testCase)
  const response = await sendRequest(server.port, testCase)
  const after = await readWatchedRecord(server, testCase)
  return { testCase: testCase, status: response.status, responseBody: response.body, before: before, after: after }
}

// Plays every case against one version, then compares each case with the
// intended request it names in compareWith, or with itself if it names none.
export async function playCases(version) {
  const server = await startServer(version)
  const results = []
  try {
    for (const testCase of CASES) results.push(await playCase(server, testCase))
  } finally {
    await stopServer(server)
  }
  for (const result of results) {
    const intendedId = result.testCase.compareWith || result.testCase.id
    const intended = results.find((item) => item.testCase.id === intendedId)
    result.intended = intended
    result.changes = listChanges(result.testCase.operation, result.before, result.after, intended.after)
    result.outsideThePlan = result.changes.filter((change) => change.isOutsideThePlan).map((change) => change.text)
  }
  return results
}

================================================================
FILE 7 OF 8: run-diff.mjs
================================================================

// run-diff.mjs: plays every case against the versions named on the command
// line and prints, for each case, the request, the stored record before it,
// and for each version the response, the stored record after it and what
// changed. For an extra-field request, the changes are shown as a difference
// from the intended request it is compared with.
// Run: node run-diff.mjs                           (careless and careful)
//      node run-diff.mjs blocklist careful-ignore  (the other two versions)
import { CASES } from './field-plan.mjs'
import { playCases } from './request-diff.mjs'

const NAMED_VERSIONS = process.argv.slice(2)
const VERSIONS = NAMED_VERSIONS.length > 0 ? NAMED_VERSIONS : ['careless', 'careful']
const LINE = '----------------------------------------------------------------'
const FIRST_LABEL = '      changes   '
const NEXT_LABEL = '                '

function showRecord(record) {
  return record === null ? '(no record)' : JSON.stringify(record)
}

// When a handler answers with the stored record itself, the body is printed
// once, under "after".
function showResponse(result) {
  const isStoredRecord = result.after !== null && result.responseBody === JSON.stringify(result.after)
  return result.status + ' ' + (isStoredRecord ? '(the body is the stored record, shown under "after")' : result.responseBody)
}

function showAfter(result) {
  const isUnchanged = showRecord(result.after) === showRecord(result.before)
  return isUnchanged ? '(same as before)' : showRecord(result.after)
}

function showChange(change) {
  return change.text + (change.isOutsideThePlan ? '   <== OUTSIDE THE PLAN' : '')
}

function printAllChanges(result) {
  result.changes.forEach((change, index) => {
    console.log((index === 0 ? FIRST_LABEL : NEXT_LABEL) + showChange(change))
  })
}

// For an extra-field request: only what differs from the intended request.
function printChangesAgainstIntended(result) {
  const intendedChanges = result.intended.changes
  const intendedTexts = intendedChanges.map((change) => change.text)
  const changedPaths = result.changes.map((change) => change.path)
  const added = result.changes.filter((change) => !intendedTexts.includes(change.text))
  const dropped = intendedChanges.filter((change) => !changedPaths.includes(change.path))
  const intendedId = result.intended.testCase.id
  console.log(FIRST_LABEL + 'the same as ' + intendedId + (added.length + dropped.length > 0 ? ', except:' : ''))
  for (const change of added) console.log(NEXT_LABEL + showChange(change))
  for (const change of dropped) console.log(NEXT_LABEL + 'not changed here: ' + change.path)
}

function printChanges(result) {
  if (result.changes.length === 0) console.log(FIRST_LABEL + 'none')
  else if (result.intended === result) printAllChanges(result)
  else printChangesAgainstIntended(result)
}

function printVersionResult(version, result) {
  console.log('  ' + version)
  console.log('      response  ' + showResponse(result))
  console.log('      after     ' + showAfter(result))
  printChanges(result)
}

function printCase(testCase, resultsByVersion) {
  const comparison = testCase.compareWith ? ' (compared with ' + testCase.compareWith + ')' : ''
  console.log(LINE)
  console.log(testCase.id + '  ' + testCase.title + comparison)
  console.log('  request     ' + testCase.method + ' ' + testCase.path + ' as ' + testCase.as + '  ' + JSON.stringify(testCase.body))
  console.log('  before      ' + showRecord(resultsByVersion[VERSIONS[0]].before))
  for (const version of VERSIONS) printVersionResult(version, resultsByVersion[version])
}

function printTotals(version, results) {
  const extraFieldResults = results.filter((result) => result.testCase.property)
  const failed = extraFieldResults.filter((result) => result.outsideThePlan.length > 0)
  const failedIds = failed.map((result) => result.testCase.id).join(' ')
  const detail = failed.length > 0 ? ': ' + failedIds : ''
  console.log(version + ': ' + failed.length + ' of ' + extraFieldResults.length + ' extra-field requests changed something outside the plan' + detail)
}

const resultsFor = {}
for (const version of VERSIONS) resultsFor[version] = await playCases(version)

console.log('Versions: ' + VERSIONS.join(', ') + '. Every request starts from the same seeded records, so "before" is the same for each version.')
CASES.forEach((testCase, index) => {
  const resultsByVersion = {}
  for (const version of VERSIONS) resultsByVersion[version] = resultsFor[version][index]
  printCase(testCase, resultsByVersion)
})
console.log(LINE)
for (const version of VERSIONS) printTotals(version, resultsFor[version])

================================================================
FILE 8 OF 8: privileged-fields.test.mjs
================================================================

// privileged-fields.test.mjs: one test per privileged property. A test fails
// while its extra-field request leaves any stored change outside the plan.
// A last test checks the ordinary requests, so a server that refused
// everything could not pass.
// Run: node privileged-fields.test.mjs careless   (expect failures)
//      node privileged-fields.test.mjs careful    (expect every test to pass)
// With no argument it tests the careful version.
import assert from 'node:assert/strict'
import { test } from 'node:test'
import { playCases } from './request-diff.mjs'

const version = process.argv[2] || 'careful'
const results = await playCases(version)

function resultOf(caseId) {
  return results.find((result) => result.testCase.id === caseId)
}

for (const result of results) {
  if (!result.testCase.property) continue
  test(version + ': ' + result.testCase.id + ' ' + result.testCase.property, () => {
    assert.deepEqual(result.outsideThePlan, [])
  })
}

test(version + ': the intended requests are stored, and a customer cannot call the admin endpoint', () => {
  const profile = resultOf('P0')
  const order = resultOf('O0')
  const adminEdit = resultOf('A0')
  const adminEditByCustomer = resultOf('A1')
  const seen = {
    profile: [profile.status, profile.after.displayName, profile.after.phone, profile.outsideThePlan.length],
    order: [order.status, order.after.items[0].quantity, order.after.totalCents, order.after.ownerId, order.outsideThePlan.length],
    adminEdit: [adminEdit.status, adminEdit.after.role, adminEdit.after.storeCreditCents, adminEdit.outsideThePlan.length],
    adminEditByCustomer: [adminEditByCustomer.status, adminEditByCustomer.changes.length],
  }
  assert.deepEqual(seen, {
    profile: [200, 'Mira K.', '0491 570 156', 0],
    order: [201, 2, 3600, 'cust-mira', 0],
    adminEdit: [200, 'staff', 1500, 0],
    adminEditByCustomer: [403, 0],
  })
})

==== PART 4. STEP 1: THE REQUEST DIFF, CARELESS AND CAREFUL ====
Command: node run-diff.mjs

Versions: careless, careful. Every request starts from the same seeded records, so "before" is the same for each version.
----------------------------------------------------------------
P0  Profile edit, as the form sends it
  request     PATCH /account as cust-mira  {"displayName":"Mira K.","phone":"0491 570 156"}
  before      {"id":"cust-mira","email":"mira@teashop.example","displayName":"Mira","phone":"","role":"customer","emailVerified":false,"storeCreditCents":0,"updatedBy":"sign-up"}
  careless
      response  200 (the body is the stored record, shown under "after")
      after     {"id":"cust-mira","email":"mira@teashop.example","displayName":"Mira K.","phone":"0491 570 156","role":"customer","emailVerified":false,"storeCreditCents":0,"updatedBy":"cust-mira"}
      changes   displayName: "Mira" -> "Mira K." (client-writable)
                phone: "" -> "0491 570 156" (client-writable)
                updatedBy: "sign-up" -> "cust-mira" (set by the server)
  careful
      response  200 {"id":"cust-mira","email":"mira@teashop.example","displayName":"Mira K.","phone":"0491 570 156","role":"customer","emailVerified":false,"storeCreditCents":0}
      after     {"id":"cust-mira","email":"mira@teashop.example","displayName":"Mira K.","phone":"0491 570 156","role":"customer","emailVerified":false,"storeCreditCents":0,"updatedBy":"cust-mira"}
      changes   displayName: "Mira" -> "Mira K." (client-writable)
                phone: "" -> "0491 570 156" (client-writable)
                updatedBy: "sign-up" -> "cust-mira" (set by the server)
----------------------------------------------------------------
P1  Profile edit with a role added (compared with P0)
  request     PATCH /account as cust-mira  {"displayName":"Mira K.","phone":"0491 570 156","role":"admin"}
  before      {"id":"cust-mira","email":"mira@teashop.example","displayName":"Mira","phone":"","role":"customer","emailVerified":false,"storeCreditCents":0,"updatedBy":"sign-up"}
  careless
      response  200 (the body is the stored record, shown under "after")
      after     {"id":"cust-mira","email":"mira@teashop.example","displayName":"Mira K.","phone":"0491 570 156","role":"admin","emailVerified":false,"storeCreditCents":0,"updatedBy":"cust-mira"}
      changes   the same as P0, except:
                role: "customer" -> "admin" (never changed by this operation)   <== OUTSIDE THE PLAN
  careful
      response  422 {"error":"editProfile does not accept: role"}
      after     (same as before)
      changes   none
----------------------------------------------------------------
P2  Profile edit with Role added, in a different letter case (compared with P0)
  request     PATCH /account as cust-mira  {"displayName":"Mira K.","phone":"0491 570 156","Role":"admin"}
  before      {"id":"cust-mira","email":"mira@teashop.example","displayName":"Mira","phone":"","role":"customer","emailVerified":false,"storeCreditCents":0,"updatedBy":"sign-up"}
  careless
      response  200 (the body is the stored record, shown under "after")
      after     {"id":"cust-mira","email":"mira@teashop.example","displayName":"Mira K.","phone":"0491 570 156","role":"customer","emailVerified":false,"storeCreditCents":0,"updatedBy":"cust-mira","Role":"admin"}
      changes   the same as P0, except:
                Role: (absent) -> "admin" (not a field of this record)   <== OUTSIDE THE PLAN
  careful
      response  422 {"error":"editProfile does not accept: Role"}
      after     (same as before)
      changes   none
----------------------------------------------------------------
P3  Profile edit with the verified flag added (compared with P0)
  request     PATCH /account as cust-mira  {"displayName":"Mira K.","phone":"0491 570 156","emailVerified":true}
  before      {"id":"cust-mira","email":"mira@teashop.example","displayName":"Mira","phone":"","role":"customer","emailVerified":false,"storeCreditCents":0,"updatedBy":"sign-up"}
  careless
      response  200 (the body is the stored record, shown under "after")
      after     {"id":"cust-mira","email":"mira@teashop.example","displayName":"Mira K.","phone":"0491 570 156","role":"customer","emailVerified":true,"storeCreditCents":0,"updatedBy":"cust-mira"}
      changes   the same as P0, except:
                emailVerified: false -> true (never changed by this operation)   <== OUTSIDE THE PLAN
  careful
      response  422 {"error":"editProfile does not accept: emailVerified"}
      after     (same as before)
      changes   none
----------------------------------------------------------------
P4  Profile edit with store credit added (compared with P0)
  request     PATCH /account as cust-mira  {"displayName":"Mira K.","phone":"0491 570 156","storeCreditCents":50000}
  before      {"id":"cust-mira","email":"mira@teashop.example","displayName":"Mira","phone":"","role":"customer","emailVerified":false,"storeCreditCents":0,"updatedBy":"sign-up"}
  careless
      response  200 (the body is the stored record, shown under "after")
      after     {"id":"cust-mira","email":"mira@teashop.example","displayName":"Mira K.","phone":"0491 570 156","role":"customer","emailVerified":false,"storeCreditCents":50000,"updatedBy":"cust-mira"}
      changes   the same as P0, except:
                storeCreditCents: 0 -> 50000 (never changed by this operation)   <== OUTSIDE THE PLAN
  careful
      response  422 {"error":"editProfile does not accept: storeCreditCents"}
      after     (same as before)
      changes   none
----------------------------------------------------------------
O0  New order, as the client sends it
  request     POST /orders as cust-mira  {"items":[{"sku":"TEA-ASSAM-100","quantity":2}],"deliveryNote":"Leave at the front desk"}
  before      (no record)
  careless
      response  201 (the body is the stored record, shown under "after")
      after     {"id":"order-1001","ownerId":"cust-mira","status":"pending","deliveryNote":"Leave at the front desk","totalCents":3600,"items":[{"unitPriceCents":1800,"sku":"TEA-ASSAM-100","quantity":2}]}
      changes   id: (absent) -> "order-1001" (set by the server)
                ownerId: (absent) -> "cust-mira" (set by the server)
                status: (absent) -> "pending" (set by the server)
                deliveryNote: (absent) -> "Leave at the front desk" (client-writable)
                totalCents: (absent) -> 3600 (set by the server)
                items.0.unitPriceCents: (absent) -> 1800 (set by the server)
                items.0.sku: (absent) -> "TEA-ASSAM-100" (client-writable)
                items.0.quantity: (absent) -> 2 (client-writable)
  careful
      response  201 {"id":"order-1001","status":"pending","items":[{"sku":"TEA-ASSAM-100","quantity":2,"unitPriceCents":1800}],"deliveryNote":"Leave at the front desk","totalCents":3600}
      after     {"id":"order-1001","ownerId":"cust-mira","status":"pending","items":[{"sku":"TEA-ASSAM-100","quantity":2,"unitPriceCents":1800}],"deliveryNote":"Leave at the front desk","totalCents":3600}
      changes   id: (absent) -> "order-1001" (set by the server)
                ownerId: (absent) -> "cust-mira" (set by the server)
                status: (absent) -> "pending" (set by the server)
                items.0.sku: (absent) -> "TEA-ASSAM-100" (client-writable)
                items.0.quantity: (absent) -> 2 (client-writable)
                items.0.unitPriceCents: (absent) -> 1800 (set by the server)
                deliveryNote: (absent) -> "Leave at the front desk" (client-writable)
                totalCents: (absent) -> 3600 (set by the server)
----------------------------------------------------------------
O1  New order with an owner added (compared with O0)
  request     POST /orders as cust-mira  {"items":[{"sku":"TEA-ASSAM-100","quantity":2}],"deliveryNote":"Leave at the front desk","ownerId":"cust-theo"}
  before      (no record)
  careless
      response  201 (the body is the stored record, shown under "after")
      after     {"id":"order-1001","ownerId":"cust-theo","status":"pending","deliveryNote":"Leave at the front desk","totalCents":3600,"items":[{"unitPriceCents":1800,"sku":"TEA-ASSAM-100","quantity":2}]}
      changes   the same as O0, except:
                ownerId: (absent) -> "cust-theo" (set by the server, which sets "cust-mira")   <== OUTSIDE THE PLAN
  careful
      response  422 {"error":"createOrder does not accept: ownerId"}
      after     (same as before)
      changes   none
----------------------------------------------------------------
O2  New order with a total added (compared with O0)
  request     POST /orders as cust-mira  {"items":[{"sku":"TEA-ASSAM-100","quantity":2}],"deliveryNote":"Leave at the front desk","totalCents":1}
  before      (no record)
  careless
      response  201 (the body is the stored record, shown under "after")
      after     {"id":"order-1001","ownerId":"cust-mira","status":"pending","deliveryNote":"Leave at the front desk","totalCents":1,"items":[{"unitPriceCents":1800,"sku":"TEA-ASSAM-100","quantity":2}]}
      changes   the same as O0, except:
                totalCents: (absent) -> 1 (set by the server, which sets 3600)   <== OUTSIDE THE PLAN
  careful
      response  422 {"error":"createOrder does not accept: totalCents"}
      after     (same as before)
      changes   none
----------------------------------------------------------------
O3  New order with a unit price inside the nested item (compared with O0)
  request     POST /orders as cust-mira  {"items":[{"sku":"TEA-ASSAM-100","quantity":2,"unitPriceCents":1}],"deliveryNote":"Leave at the front desk"}
  before      (no record)
  careless
      response  201 (the body is the stored record, shown under "after")
      after     {"id":"order-1001","ownerId":"cust-mira","status":"pending","deliveryNote":"Leave at the front desk","totalCents":2,"items":[{"unitPriceCents":1,"sku":"TEA-ASSAM-100","quantity":2}]}
      changes   the same as O0, except:
                totalCents: (absent) -> 2 (set by the server, which sets 3600)   <== OUTSIDE THE PLAN
                items.0.unitPriceCents: (absent) -> 1 (set by the server, which sets 1800)   <== OUTSIDE THE PLAN
  careful
      response  422 {"error":"orderItem does not accept: unitPriceCents"}
      after     (same as before)
      changes   none
----------------------------------------------------------------
O4  New order with a status added (compared with O0)
  request     POST /orders as cust-mira  {"items":[{"sku":"TEA-ASSAM-100","quantity":2}],"deliveryNote":"Leave at the front desk","status":"paid"}
  before      (no record)
  careless
      response  201 (the body is the stored record, shown under "after")
      after     {"id":"order-1001","ownerId":"cust-mira","status":"paid","deliveryNote":"Leave at the front desk","totalCents":3600,"items":[{"unitPriceCents":1800,"sku":"TEA-ASSAM-100","quantity":2}]}
      changes   the same as O0, except:
                status: (absent) -> "paid" (set by the server, which sets "pending")   <== OUTSIDE THE PLAN
  careful
      response  422 {"error":"createOrder does not accept: status"}
      after     (same as before)
      changes   none
----------------------------------------------------------------
A0  Admin edit, as the admin screen sends it
  request     PATCH /admin/accounts/cust-theo as staff-priya  {"role":"staff","storeCreditCents":1500}
  before      {"id":"cust-theo","email":"theo@teashop.example","displayName":"Theo","phone":"","role":"customer","emailVerified":false,"storeCreditCents":0,"updatedBy":"sign-up"}
  careless
      response  200 (the body is the stored record, shown under "after")
      after     {"id":"cust-theo","email":"theo@teashop.example","displayName":"Theo","phone":"","role":"staff","emailVerified":false,"storeCreditCents":1500,"updatedBy":"staff-priya"}
      changes   role: "customer" -> "staff" (client-writable)
                storeCreditCents: 0 -> 1500 (client-writable)
                updatedBy: "sign-up" -> "staff-priya" (set by the server)
  careful
      response  200 (the body is the stored record, shown under "after")
      after     {"id":"cust-theo","email":"theo@teashop.example","displayName":"Theo","phone":"","role":"staff","emailVerified":false,"storeCreditCents":1500,"updatedBy":"staff-priya"}
      changes   role: "customer" -> "staff" (client-writable)
                storeCreditCents: 0 -> 1500 (client-writable)
                updatedBy: "sign-up" -> "staff-priya" (set by the server)
----------------------------------------------------------------
A1  The same admin edit, sent by a customer
  request     PATCH /admin/accounts/cust-theo as cust-mira  {"role":"staff","storeCreditCents":1500}
  before      {"id":"cust-theo","email":"theo@teashop.example","displayName":"Theo","phone":"","role":"customer","emailVerified":false,"storeCreditCents":0,"updatedBy":"sign-up"}
  careless
      response  403 {"error":"only an admin may call this endpoint"}
      after     (same as before)
      changes   none
  careful
      response  403 {"error":"only an admin may call this endpoint"}
      after     (same as before)
      changes   none
----------------------------------------------------------------
A2  Admin edit with an email address and the verified flag added (compared with A0)
  request     PATCH /admin/accounts/cust-theo as staff-priya  {"role":"staff","storeCreditCents":1500,"email":"someone-else@teashop.example","emailVerified":true}
  before      {"id":"cust-theo","email":"theo@teashop.example","displayName":"Theo","phone":"","role":"customer","emailVerified":false,"storeCreditCents":0,"updatedBy":"sign-up"}
  careless
      response  200 (the body is the stored record, shown under "after")
      after     {"id":"cust-theo","email":"someone-else@teashop.example","displayName":"Theo","phone":"","role":"staff","emailVerified":true,"storeCreditCents":1500,"updatedBy":"staff-priya"}
      changes   the same as A0, except:
                email: "theo@teashop.example" -> "someone-else@teashop.example" (never changed by this operation)   <== OUTSIDE THE PLAN
                emailVerified: false -> true (never changed by this operation)   <== OUTSIDE THE PLAN
  careful
      response  422 {"error":"adminEditAccount does not accept: email, emailVerified"}
      after     (same as before)
      changes   none
----------------------------------------------------------------
A3  Admin edit with an id added (compared with A0)
  request     PATCH /admin/accounts/cust-theo as staff-priya  {"role":"staff","storeCreditCents":1500,"id":"cust-mira"}
  before      {"id":"cust-theo","email":"theo@teashop.example","displayName":"Theo","phone":"","role":"customer","emailVerified":false,"storeCreditCents":0,"updatedBy":"sign-up"}
  careless
      response  200 (the body is the stored record, shown under "after")
      after     {"id":"cust-mira","email":"theo@teashop.example","displayName":"Theo","phone":"","role":"staff","emailVerified":false,"storeCreditCents":1500,"updatedBy":"staff-priya"}
      changes   the same as A0, except:
                id: "cust-theo" -> "cust-mira" (never changed by this operation)   <== OUTSIDE THE PLAN
  careful
      response  422 {"error":"adminEditAccount does not accept: id"}
      after     (same as before)
      changes   none
----------------------------------------------------------------
careless: 10 of 10 extra-field requests changed something outside the plan: P1 P2 P3 P4 O1 O2 O3 O4 A2 A3
careful: 0 of 10 extra-field requests changed something outside the plan

Reading the output
  request   The method, the path, the account that sent it and the body.
  before    The stored record the request is compared on, before the request. An order does not exist before it is placed, so the order cases show (no record).
  response  The status and the body. Where the body is the stored record itself, it is printed once, under "after".
  after     The stored record after the request, read from the API process, not from the response.
  changes   For an intended request (P0, O0, A0), every field that changed, with its class from the field plan. For an extra-field request, only what differs from the intended request it is compared with.
  <== OUTSIDE THE PLAN  A NEVER field that changed, a SERVER field holding a value the server did not set, or a field that is not a field of the record.

What the run shows
  P1, P3, P4  The careless profile edit stored a role of admin, a verified flag of true and 50000 cents of store credit, because each arrived beside the display name. The careful version answered 422 and changed nothing.
  P2          Role with a capital R did not change role. The careless version stored it as a ninth field on the account. Whether a field like that is ever read as the real one depends on what reads the record next, so the plan counts any field that is not part of the record as a failure.
  O1          The careless order was stored with cust-theo as its owner, placed by cust-mira.
  O2, O3      A total sent at the top level replaced the server's 3600. A unit price sent inside the nested order line replaced the catalogue's 1800, and the server then worked out the total from it: 2 cents for two tins.
  O4          The careless order was stored as paid.
  A1          Every version refused the customer with 403. Who may call an endpoint is a separate check, shared here, and it is not what this lab varies.
  A2, A3      The admin is allowed to call the endpoint and to change role and store credit. The careless version also let the request replace the account's email address, mark it verified, and overwrite its id with another account's id.
  Totals      The careless version stored something outside the plan for 10 of the 10 extra-field requests. The careful version stored nothing outside the plan for any of them.

==== PART 5. STEP 2: THE BLOCK-LIST VERSION AND THE IGNORE VERSION ====
Command: node run-diff.mjs blocklist careful-ignore

Versions: blocklist, careful-ignore. Every request starts from the same seeded records, so "before" is the same for each version.
----------------------------------------------------------------
P1  Profile edit with a role added (compared with P0)
  request     PATCH /account as cust-mira  {"displayName":"Mira K.","phone":"0491 570 156","role":"admin"}
  before      {"id":"cust-mira","email":"mira@teashop.example","displayName":"Mira","phone":"","role":"customer","emailVerified":false,"storeCreditCents":0,"updatedBy":"sign-up"}
  blocklist
      response  200 (the body is the stored record, shown under "after")
      after     {"id":"cust-mira","email":"mira@teashop.example","displayName":"Mira K.","phone":"0491 570 156","role":"customer","emailVerified":false,"storeCreditCents":0,"updatedBy":"cust-mira"}
      changes   the same as P0
  careful-ignore
      response  200 {"id":"cust-mira","email":"mira@teashop.example","displayName":"Mira K.","phone":"0491 570 156","role":"customer","emailVerified":false,"storeCreditCents":0}
      after     {"id":"cust-mira","email":"mira@teashop.example","displayName":"Mira K.","phone":"0491 570 156","role":"customer","emailVerified":false,"storeCreditCents":0,"updatedBy":"cust-mira"}
      changes   the same as P0
----------------------------------------------------------------
P2  Profile edit with Role added, in a different letter case (compared with P0)
  request     PATCH /account as cust-mira  {"displayName":"Mira K.","phone":"0491 570 156","Role":"admin"}
  before      {"id":"cust-mira","email":"mira@teashop.example","displayName":"Mira","phone":"","role":"customer","emailVerified":false,"storeCreditCents":0,"updatedBy":"sign-up"}
  blocklist
      response  200 (the body is the stored record, shown under "after")
      after     {"id":"cust-mira","email":"mira@teashop.example","displayName":"Mira K.","phone":"0491 570 156","role":"customer","emailVerified":false,"storeCreditCents":0,"updatedBy":"cust-mira","Role":"admin"}
      changes   the same as P0, except:
                Role: (absent) -> "admin" (not a field of this record)   <== OUTSIDE THE PLAN
  careful-ignore
      response  200 {"id":"cust-mira","email":"mira@teashop.example","displayName":"Mira K.","phone":"0491 570 156","role":"customer","emailVerified":false,"storeCreditCents":0}
      after     {"id":"cust-mira","email":"mira@teashop.example","displayName":"Mira K.","phone":"0491 570 156","role":"customer","emailVerified":false,"storeCreditCents":0,"updatedBy":"cust-mira"}
      changes   the same as P0
----------------------------------------------------------------
P3  Profile edit with the verified flag added (compared with P0)
  request     PATCH /account as cust-mira  {"displayName":"Mira K.","phone":"0491 570 156","emailVerified":true}
  before      {"id":"cust-mira","email":"mira@teashop.example","displayName":"Mira","phone":"","role":"customer","emailVerified":false,"storeCreditCents":0,"updatedBy":"sign-up"}
  blocklist
      response  200 (the body is the stored record, shown under "after")
      after     {"id":"cust-mira","email":"mira@teashop.example","displayName":"Mira K.","phone":"0491 570 156","role":"customer","emailVerified":true,"storeCreditCents":0,"updatedBy":"cust-mira"}
      changes   the same as P0, except:
                emailVerified: false -> true (never changed by this operation)   <== OUTSIDE THE PLAN
  careful-ignore
      response  200 {"id":"cust-mira","email":"mira@teashop.example","displayName":"Mira K.","phone":"0491 570 156","role":"customer","emailVerified":false,"storeCreditCents":0}
      after     {"id":"cust-mira","email":"mira@teashop.example","displayName":"Mira K.","phone":"0491 570 156","role":"customer","emailVerified":false,"storeCreditCents":0,"updatedBy":"cust-mira"}
      changes   the same as P0
----------------------------------------------------------------
O3  New order with a unit price inside the nested item (compared with O0)
  request     POST /orders as cust-mira  {"items":[{"sku":"TEA-ASSAM-100","quantity":2,"unitPriceCents":1}],"deliveryNote":"Leave at the front desk"}
  before      (no record)
  blocklist
      response  201 (the body is the stored record, shown under "after")
      after     {"id":"order-1001","ownerId":"cust-mira","status":"pending","deliveryNote":"Leave at the front desk","totalCents":2,"items":[{"unitPriceCents":1,"sku":"TEA-ASSAM-100","quantity":2}]}
      changes   the same as O0, except:
                totalCents: (absent) -> 2 (set by the server, which sets 3600)   <== OUTSIDE THE PLAN
                items.0.unitPriceCents: (absent) -> 1 (set by the server, which sets 1800)   <== OUTSIDE THE PLAN
  careful-ignore
      response  201 {"id":"order-1001","status":"pending","items":[{"sku":"TEA-ASSAM-100","quantity":2,"unitPriceCents":1800}],"deliveryNote":"Leave at the front desk","totalCents":3600}
      after     {"id":"order-1001","ownerId":"cust-mira","status":"pending","items":[{"sku":"TEA-ASSAM-100","quantity":2,"unitPriceCents":1800}],"deliveryNote":"Leave at the front desk","totalCents":3600}
      changes   the same as O0
----------------------------------------------------------------
(cut here: cases P0, P4, O0, O1, O2, O4, A0, A1, A2 and A3, which print in the same form)
----------------------------------------------------------------
blocklist: 6 of 10 extra-field requests changed something outside the plan: P2 P3 P4 O3 O4 A2
careful-ignore: 0 of 10 extra-field requests changed something outside the plan

What the run shows
  blocklist       The lists stopped the four names on them: role (P1), ownerId (O1), totalCents (O2) and id (A3). Six requests still stored something outside the plan: Role in another letter case (P2), the verified flag and store credit that no list names (P3, P4), the unit price inside the nested order line (O3), the order status (O4), and the email address and verified flag on the admin edit (A2).
  careful-ignore  Each extra-field request was answered 200 or 201, and the stored record came out the same as for the intended request. The response does not tell the sender that a field was dropped.

==== PART 6. STEPS 3 TO 6: THE REGRESSION TESTS ====
One test per privileged property, and a last test for the ordinary requests. Each privileged-property test passes only if its extra-field request left nothing outside the plan in the stored record.

Command: node privileged-fields.test.mjs careless

✖ careless: P1 role stays as it was on a profile edit (2.344709ms)
✖ careless: P2 a differently cased Role is not stored (0.134834ms)
✖ careless: P3 emailVerified stays as it was on a profile edit (0.090625ms)
✖ careless: P4 storeCreditCents stays as it was on a profile edit (0.075667ms)
✖ careless: O1 ownerId is the signed-in account (0.10925ms)
✖ careless: O2 totalCents is worked out by the server (0.065166ms)
✖ careless: O3 unitPriceCents inside items comes from the catalogue (0.06575ms)
✖ careless: O4 status starts as pending (0.077375ms)
✖ careless: A2 email and emailVerified stay as they were on an admin edit (0.090583ms)
✖ careless: A3 id stays as it was on an admin edit (0.0995ms)
✔ careless: the intended requests are stored, and a customer cannot call the admin endpoint (0.209584ms)
ℹ tests 11
ℹ suites 0
ℹ pass 1
ℹ fail 10
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 6.692959

✖ failing tests:

test at privileged-fields.test.mjs:21:3
✖ careless: P1 role stays as it was on a profile edit (2.344709ms)
  AssertionError [ERR_ASSERTION]: Expected values to be strictly deep-equal:
  + actual - expected
  
  + [
  +   'role: "customer" -> "admin" (never changed by this operation)'
  + ]
  - []
  
      (cut here: the stack trace, which shows local file paths, and the error object fields)

test at privileged-fields.test.mjs:21:3
✖ careless: P2 a differently cased Role is not stored (0.134834ms)
  AssertionError [ERR_ASSERTION]: Expected values to be strictly deep-equal:
  + actual - expected
  
  + [
  +   'Role: (absent) -> "admin" (not a field of this record)'
  + ]
  - []
  
      (cut here: the stack trace, which shows local file paths, and the error object fields)

(cut here: the details of the other 8 failing tests, which print in the same form. Each lists the change that step 1 marks OUTSIDE THE PLAN for its case.)

Command: node privileged-fields.test.mjs blocklist

✔ blocklist: P1 role stays as it was on a profile edit (1.202875ms)
✖ blocklist: P2 a differently cased Role is not stored (1.140542ms)
✖ blocklist: P3 emailVerified stays as it was on a profile edit (0.125792ms)
✖ blocklist: P4 storeCreditCents stays as it was on a profile edit (0.086708ms)
✔ blocklist: O1 ownerId is the signed-in account (0.045084ms)
✔ blocklist: O2 totalCents is worked out by the server (0.036333ms)
✖ blocklist: O3 unitPriceCents inside items comes from the catalogue (0.072959ms)
✖ blocklist: O4 status starts as pending (0.072542ms)
✖ blocklist: A2 email and emailVerified stay as they were on an admin edit (0.102416ms)
✔ blocklist: A3 id stays as it was on an admin edit (0.06725ms)
✔ blocklist: the intended requests are stored, and a customer cannot call the admin endpoint (0.154208ms)
ℹ tests 11
ℹ suites 0
ℹ pass 5
ℹ fail 6
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 5.993708

(cut here: the details of the 6 failing tests, which print in the same form as above)

Command: node privileged-fields.test.mjs careful

✔ careful: P1 role stays as it was on a profile edit (1.681375ms)
✔ careful: P2 a differently cased Role is not stored (0.076125ms)
✔ careful: P3 emailVerified stays as it was on a profile edit (0.043958ms)
✔ careful: P4 storeCreditCents stays as it was on a profile edit (0.039125ms)
✔ careful: O1 ownerId is the signed-in account (0.042208ms)
✔ careful: O2 totalCents is worked out by the server (0.035167ms)
✔ careful: O3 unitPriceCents inside items comes from the catalogue (0.034542ms)
✔ careful: O4 status starts as pending (0.043667ms)
✔ careful: A2 email and emailVerified stay as they were on an admin edit (0.046291ms)
✔ careful: A3 id stays as it was on an admin edit (0.075792ms)
✔ careful: the intended requests are stored, and a customer cannot call the admin endpoint (0.180416ms)
ℹ tests 11
ℹ suites 0
ℹ pass 11
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 5.768625

Command: node privileged-fields.test.mjs careful-ignore

✔ careful-ignore: P1 role stays as it was on a profile edit (1.311583ms)
✔ careful-ignore: P2 a differently cased Role is not stored (0.053458ms)
✔ careful-ignore: P3 emailVerified stays as it was on a profile edit (0.043791ms)
✔ careful-ignore: P4 storeCreditCents stays as it was on a profile edit (0.045917ms)
✔ careful-ignore: O1 ownerId is the signed-in account (0.037084ms)
✔ careful-ignore: O2 totalCents is worked out by the server (0.031333ms)
✔ careful-ignore: O3 unitPriceCents inside items comes from the catalogue (0.032708ms)
✔ careful-ignore: O4 status starts as pending (0.057416ms)
✔ careful-ignore: A2 email and emailVerified stay as they were on an admin edit (0.042791ms)
✔ careful-ignore: A3 id stays as it was on an admin edit (0.0755ms)
✔ careful-ignore: the intended requests are stored, and a customer cannot call the admin endpoint (0.154417ms)
ℹ tests 11
ℹ suites 0
ℹ pass 11
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 5.368417

Exit codes, as the shell reported them after each command (node --test, run in the same folder, finds privileged-fields.test.mjs by its name and tests the careful version):
node run-diff.mjs: exit code 0
node run-diff.mjs blocklist careful-ignore: exit code 0
node privileged-fields.test.mjs careless: exit code 1
node privileged-fields.test.mjs blocklist: exit code 1
node privileged-fields.test.mjs careful: exit code 0
node privileged-fields.test.mjs careful-ignore: exit code 0
node --test: exit code 0

==== PART 7. USING IT ON YOUR OWN APPLICATION ====
  1. Fill in a worksheet block from Part 2 for every write endpoint, and turn each block into an entry in FIELD_PLAN in field-plan.mjs.
  2. Rewrite CASES for your own endpoints: the intended request for each one, then one case per extra field from the list in Part 1, each naming the property it protects.
  3. In request-diff.mjs, replace startServer with your application running against a test database, replace the x-lab-token header with however your tests sign a test account in, and replace the snapshot with a read of the stored record from that database.
  4. Keep the reset before every request, so one request's leftovers cannot change the next comparison.
  5. Run privileged-fields.test.mjs on every build, as a check that has to pass before a change merges.
  6. When someone adds a field to a record, give it a line in the field plan and a case that sends it. Until the plan has a line for it, a request that sets the new field shows as outside the plan.

What a mass assignment vulnerability is

Web frameworks save developers from writing one line of code per field.

A form arrives with a dozen values, the framework matches each name to a field on a record, and one call saves them all. That convenience goes by several names, mass assignment among them. It turns into a vulnerability when the handler binds the whole request to the record, because the client decides what the whole request is.

A profile form that offers a display name and a phone number can be sent back with a role, a price, an owner or a verified flag added, and a handler that copies every field it receives will store those as well.

OWASP's Mass Assignment Cheat Sheet defines it this way. Software frameworks sometimes allow developers to automatically bind HTTP request parameters into program code variables or objects, to make using that framework easier on developers. Attackers can sometimes use this to create new parameters that the developer never intended, which in turn creates or overwrites new variables or objects in program code that was not intended.

MITRE catalogues the weakness as CWE-915, Improperly Controlled Modification of Dynamically-Determined Object Attributes: the product receives input from an upstream component that specifies multiple attributes, properties or fields that are to be initialised or updated in an object, but it does not properly control which attributes can be modified.

Its consequences table lists modifying application data, where an attacker could modify sensitive data or program variables, alongside two more entries: executing unauthorised code or commands, and an impact that varies by context and alters execution logic.

Laravel's 13.x documentation gives the shortest version: a mass assignment vulnerability occurs when a user passes an unexpected HTTP request field and that field changes a column in your database that you did not expect. Its example is a malicious user sending an is_admin parameter that is passed to a model's create method, allowing the user to escalate themselves to an administrator.

Nothing about such a request looks wrong. It comes from a signed-in account, to an endpoint that account may call, about a record that account may edit, and every value in it is well formed. The flaw is in which fields of the record the request was allowed to reach.

That is the one mistake this guide covers, along with the three controls that stop it: an explicit list of the fields each operation may write, a separate input shape for each operation, and tests that prove the privileged fields did not change.

Overposting, autobinding and the other names for it

The cheat sheet says the vulnerability can have several alternative names depending on the language or framework: mass assignment for Ruby on Rails and NodeJS, autobinding for Spring MVC and ASP NET MVC, and object injection for PHP. CWE-915 lists three alternate terms.

Mass Assignment, it says, is the name of a feature in Ruby on Rails that allows simultaneous modification of multiple object attributes. AutoBinding is a term used in frameworks such as Spring MVC and ASP.NET MVC.

PHP Object Injection is a term some PHP application researchers use for attacking unsafe use of the unserialize() function, and MITRE notes that it is also used for CWE-502, the weakness the insecure deserialisation guide in this library covers.

Microsoft's ASP.NET Core documentation calls it overposting. Its Razor Pages tutorial says the scaffolded code for a create page is vulnerable to overposting, and its web API tutorial has a section headed "Prevent over-posting". This page treats an overposting vulnerability and a mass assignment vulnerability as two names for one mistake: the client posts more than the form held, and the server assigns all of it.

OWASP's API Security Top 10 has carried it under two headings. The 2019 edition lists it as API6:2019, Mass Assignment. The 2023 edition's release notes say the project combined Excessive Data Exposure and Mass Assignment, focusing on the common root cause: object property level authorisation validation failures.

API3:2023, Broken Object Property Level Authorization, carries both former names. It says an API endpoint is vulnerable if it allows a user to change, add or delete the value of a sensitive object property which the user should not be able to access, and marks that case as previously named Mass Assignment.

The same entry covers exposing properties a user should not read, previously named Excessive Data Exposure. API overposting now shares an entry with its mirror image: the fields a client should not write, and the fields it should not read.

Why the form on the screen is not the limit of what a client can send

A form is a suggestion.

The browser draws the fields the page describes, and when the visitor presses save, it sends a request. Nothing ties that request to the form. Anyone signed in can send the same request from a script, or change it on its way out, and add any field name they like.

A hidden input, a disabled input and a field the page never drew all look the same to the server, which receives only names and values.

The documentation says this in several ways. WSTG v4.2's test for forged requests, WSTG-BUSL-02, describes forging requests as going around the front end to submit information directly for back end processing. Django's documentation says of its model forms that, depending on how the form is rendered, the problem may not even be visible on the web page.

Microsoft's Razor Pages tutorial uses a model with a Secret property the page should not update: even if the app has no Secret field on its create or update page, it says, someone could set the value by overposting, and the original code does not limit the fields that the model binder uses.

Keeping the field names quiet is not a defence. The cheat sheet says field names may be guessed or discovered, and that source-code access is not required. OWASP's API6:2019 entry says exploitation of mass assignment is easier in APIs, since by design they expose the underlying implementation of the application along with the properties' names.

API3:2023 says fuzzing is usually used to identify additional (hidden) properties, and that whether they can be changed is a matter of crafting an API request and analysing the response.

In the lab on this page, the response to a profile edit shows the customer their role, their verified flag and their store credit. All three are reasonable things to show, and that response is also a list of names to try.

A public example from 2012

GitHub published an account of one on 4 March 2012. Its post says a GitHub user exploited a security vulnerability in the public key update form in order to add his public key to the rails organisation, and was then able to push a new file to the project as a demonstration.

GitHub says it rolled out a fix that morning, that database and log analysis showed the user compromised three accounts (rails and two others that appear to have been proofs of concept), and that the root cause was a failure to properly check incoming form parameters, a problem known as the mass-assignment vulnerability.

Django's documentation points to the same company when it explains why it wants a form's fields listed explicitly. It says the approach of including all fields automatically, or removing only some, is known to be much less secure and has led to serious exploits on major websites, and it gives GitHub as its example.

Which fields matter: who you are, what you may do, what you owe and who owns the record

Four questions find the fields worth protecting on a record.

Who are you: the fields that identify an account, such as its id, its email address and whether that address has been verified. What may you do: a role, a permission list, an admin flag, a plan. What do you owe, or what are you owed: a price, a total, a discount, a balance, store credit.

Who owns the record: an owner, a customer, a tenant or an organisation id. A fifth group is the record's place in a process, such as a status of paid, approved or shipped.

OWASP's own lists run along similar lines. API6:2019 gives three kinds of sensitive property, each with examples: permission-related properties, where user.is_admin and user.is_vip should only be set by admins; process-dependent properties, where user.cash should only be set internally after payment verification; and internal properties, where article.created_time should only be set internally by the application.

The mass assignment test in the latest edition of the WSTG gives the same three groups with examples of its own, among them role, approved, balance, status, email_verified, created_at and updated_at. The cheat sheet names a role or an account owner as fields a caller is not authorised to change, and CWE-915 notes that if an object contains attributes that were only intended for internal use, their unexpected modification could lead to a vulnerability.

The lab's records carry at least one of each. An account has an id, an email address and an emailVerified flag, a role, and a storeCreditCents balance. An order has an ownerId, a status, a unitPriceCents on every line and a totalCents. The customer's profile form sends none of them, and the order request sends none of them either.

What a change to one of these fields is worth depends on the field. The WSTG's latest test says modifying an object's id can lead to application denial of service or privilege escalation, and that modifying a user's role or status, such as role or isAdmin, leads to vertical privilege escalation.

API6:2019's first scenario is a ride sharing app whose profile endpoint accepts a credit balance added to the legitimate request, so the attacker receives credits without paying. API3:2023 says that under certain circumstances, unauthorised access to object properties can lead to privilege escalation or partial or full account takeover.

A property allowlist, and why a block-list fails when a field is added

There are two ways to tell a handler which fields it may write.

A block-list names the dangerous fields and lets everything else through. A property allowlist names the fields this operation may write and refuses or drops everything else. They look like mirror images, and they fail in opposite directions. When someone adds a field to a record, an allowlist that has not heard of it keeps it out, and a block-list that has not heard of it lets it in.

The sources point the same way, each in its own words. The first of CWE-915's mitigations is to use language or framework features that allow allowlists of the attributes or fields that may be modified, if available, and to prefer allowlists over denylists if possible.

The cheat sheet says not to rely on a block-list as the sole protection, because a new or overlooked sensitive field remains bindable, and it notes that Spring describes its disallowedFields setting as fragile because fields can be missed or added later.

Django's documentation strongly recommends explicitly setting all fields that should be edited in a form, and says failure to do so can easily lead to security problems, such as unintentionally exposing newly added model fields. The WSTG's latest test says an approach based on allowed fields, in which only the properties that should be updated by the user are explicitly defined, is preferable.

API3:2023 asks that changes are allowed only to the object's properties that should be updated by the client.

OWASP's 2019 entry listed both approaches among its four prevention items: whitelist only the properties that should be updated by the client, and use built-in features to blacklist properties that should not be accessed by clients. A block-list can sit behind an allowlist as a second check. The lab shows what happens when it stands alone.

Each handler in the lab's block-list version removes the field names someone thought of when it was written: role on the profile edit, ownerId and totalCents on a new order, id on the admin edit. Those four names were stopped.

Six of the ten extra-field requests still stored something they should not have: the verified flag and the store credit, which no list names; the order status; a unit price sent inside the nested order line, which a list of top-level names never sees; Role with a capital R; and a new email address, marked verified, on the admin edit.

The careful version, which lists what each operation may write, stored nothing outside its plan for any of the ten.

Letter case deserves a note of its own, because a block-list compares names, and a binder may not compare them the same way. Microsoft's Razor Pages tutorial says TryUpdateModelAsync looks for form fields with a "student" prefix, such as Student.FirstMidName, and that it is not case sensitive.

Its System.Text.Json documentation lists PropertyNameCaseInsensitive = true among the options that have different defaults for web apps. Whether a differently cased name reaches the real field therefore depends on the binder and the storage layer in front of you.

In the lab it does not: the careless version stores Role as a new, ninth field and leaves role alone. The field plan counts that as a failure anyway, because nothing outside the record's own fields should be stored at all.

One input shape per operation: sign-up, profile edit and admin edit

A record is written by more than one operation, and each operation is allowed a different set of fields.

Take the account record in the lab. Sign-up, which the lab leaves out, would let a visitor supply an email address and a display name (the lab's account record holds no password), with the server setting everything else: the role is customer, the address is unverified, the credit is zero.

On a profile edit, the customer may change the display name and the phone number and nothing else. On an admin edit, an administrator may change the role and the store credit, and may not touch the display name.

One list of "the account's editable fields" is either too generous for the customer or too tight for the administrator, so the list belongs to the operation, not to the record.

ASVS 5.0 words its requirement the same way. Requirement 15.3.3, at Level 2, asks that the application has countermeasures to protect against mass assignment attacks by limiting allowed fields per controller and action, and gives the example that it is not possible to insert or update a field value when it was not intended to be part of that action.

The introduction to that section says it also considers the risks associated with using objects to represent data items and accepting and returning these via external APIs, and that in this case the application must ensure that data fields that should not be writable are not modified by user input.

A per-operation list goes by the name data transfer object, or DTO, among others. The cheat sheet says to prefer dedicated input objects, such as DTOs, containing only fields the caller may edit. Microsoft's web API tutorial says the subset of a model is usually referred to as a DTO, input model or view model, and its Razor Pages tutorial describes a view model as containing only the properties needed for the UI page, for example the create page.

The lab calls them input shapes.

Each one lists every field the client may send for one operation, with the rule for its value, and the handler writes only what the shape returned.

A careful handler also never reads a server-set field from the body, whatever the shape allows. The owner of a new order is the signed-in account. The unit price comes from the catalogue, looked up by the item code the client sent.

The total is worked out from the stored lines, and the status starts as pending. None of those lines of code mentions the request body, so no field in the body can change them.

An administrator's request has a field list too

An admin-only endpoint needs the same treatment, for a different reason. The caller is trusted to change a role, and that does not make every field of the account theirs to change through this screen. In the lab, the careless admin edit let one request replace the account's email address and mark it verified, and let another overwrite the account's id with a different account's id.

The careful version's admin shape lists role, limited to customer or staff, and store credit, limited to a range, and it refused both requests with a message naming the fields it does not accept.

The reverse also holds. The cheat sheet says DTOs and field allowlists restrict writable properties and do not replace authorisation for the requested object and operation. In the lab, every version refuses a customer who calls the admin endpoint with a 403, because that check lives in code all four versions share.

This guide starts once the question of who may call an endpoint, and on whose record, has been answered correctly.

Unknown fields: ignore them or refuse the request

Once an operation has a list, the handler has to decide what to do with a field that is not on it.

There are two honest answers. It can ignore the field: drop it, carry on, and answer as if it had never been sent. Or it can refuse the request with an error that names the field. Both keep the stored record intact, and the lab shows both.

The careful version refuses, answering 422 with a message such as "editProfile does not accept: role". The careful-ignore version drops the field and answers 200 or 201. Across the ten extra-field requests, neither stored anything outside the plan.

Frameworks document both behaviours, and their defaults differ. The Rails 8.1 guide says a key that has not been permitted is filtered out, and the Rails 8.1.4.1 API documentation says the action_on_unpermitted_parameters setting controls what else happens: its default is to log in test and development environments and to take no action otherwise, and it can be set to raise an exception.

Laravel 13.x says attributes outside the Fillable attribute are silently discarded by default, and offers preventSilentlyDiscardingAttributes to throw an exception instead. Zod 4's z.object() strips unrecognised keys from the parsed result, where z.strictObject() throws an error when unknown keys are found.

Mongoose 9.12.1's strict option, enabled by default, keeps values that are not in the schema from being saved, and can be set to "throw" to produce errors instead of dropping the data.

The lab refuses, and for a new endpoint that is this page's advice. A refusal tells you something a silently dropped field does not: a client is sending a field this operation does not take. In development that is a bug in your own front end, found the first time the request is sent.

In production it may be an old client or someone probing, and either is worth a log line. Laravel's 13.x documentation makes the development half of that point itself: it says silent discarding is expected behaviour in production, but during local development can lead to confusion as to why model changes are not taking effect.

A refusal is also kinder to whoever is using the client, because a screen that appears to save a field the server quietly dropped has misled them.

Ignoring is the better choice where you do not control the clients. A public API with integrations that still send fields from an older version would start failing the day you refused them. If you ignore, log the dropped names, so the information a refusal would have given you is not lost.

Either way, keep the error plain. The lab's message names only the field the client itself sent, so it tells the sender nothing they did not already know. The WSTG's latest test describes the opposite case: an application with no control such as a list of allowed fields is likely to answer an unknown attribute with an error, and those errors sometimes help a tester discover attribute names and value data types.

Reading and writing use different field lists

The fields a client may read and the fields it may write are two lists, and neither can be worked out from the other.

A customer should see their role and their store credit on their own profile, and should be able to send neither. The mistake that follows from confusing the two looks like this: a client fetches a record, changes one value and sends the whole object back, and the handler treats everything in it as writable because everything in it was readable.

The standards keep the two halves side by side. API3:2023 covers both in one entry: the properties a user should not read, and the properties a user should not change. ASVS 5.0 does the same within one section.

Requirement 15.3.1, at Level 1, asks that the application only returns the required subset of fields from a data object, and 15.3.3 limits the fields each action accepts. Where field access depends on a user's permissions, the same section points to the field-level access control requirement in the Authorization chapter.

In that chapter, requirement 8.2.3, at Level 2, asks that field-level access is restricted to consumers with explicit permissions to specific fields.

The lab's careful version keeps two sets of lists in one file. The input shapes say what each operation may write. A second set says what each response may show: the customer's profile view includes role, emailVerified and storeCreditCents and leaves out the internal updatedBy field, and the order view leaves out ownerId.

The careless version answers with the whole stored record. Frameworks offer the read half as well. Prisma ORM v7's documentation says to use select when you only need a few scalar fields, and Microsoft's web API tutorial says a DTO may be used to hide properties that clients are not supposed to view, as well as to prevent over-posting.

What a response should and should not carry is the subject of the sensitive data exposure guide in this library.

One consequence for testing follows from the split: a write can succeed without the response showing it. API3:2023 says side-effect analysis may be required if the target property is not returned in the API response. In the lab, the careful order response never shows ownerId, so only the stored record can show who owns the order. That is why the method on this page compares stored records, not responses.

What each framework's documentation gives you

Each subsection below reports what one project's own documentation says about restricting the fields a request can assign, as it read on 14 November 2026, with the version it covers.

Check the page for the version you run before relying on a default.

Ruby on Rails: strong parameters

The Rails 8.1 guide says that with strong parameters, parameters cannot be used in Active Model mass assignments until they have been explicitly permitted, and that this means deciding which attributes to permit for mass update and declaring them in the controller. 1 min read

Laravel: fillable and guarded attributes

Laravel's 13.x documentation says all Eloquent models are protected against mass assignment vulnerabilities by default: before using the create method, a model needs either a Fillable or a Guarded attribute. 1 min read

Django: model forms and the fields option

Django 6.1's documentation says it is strongly recommended that you explicitly set all fields that should be edited in a model form using the fields attribute. 1 min read

ASP.NET Core: guidance on overposting

Microsoft's documentation for ASP.NET Core 10.0 gives three tools and says where each one stops. 1 min read

Mongoose: schema strictness is not a field list

Mongoose 9.12.1's schema guide says the strict option, enabled by default, ensures that values passed to the model constructor that were not specified in the schema do not get saved to the database. 1 min read

Prisma: typed inputs describe the model, not the operation

Prisma ORM v7's documentation describes generated types as TypeScript types derived from your models, which you can use to type the objects passed to methods such as create and update. 1 min read

Schema libraries: a strict object per operation

A schema library puts the list and the rules in one declaration. 1 min read

How to test for mass assignment on every write endpoint

Test only an application you own, or one you are authorised in writing to test, with test accounts and test records, on staging where you can.

Nothing on this page is for changing a role, a price or an owner on someone else's service.

The method is a request diff. For each write endpoint you send the request the form really sends, then the same request with one extra field, and compare what was stored each time. The asset on this page gives it in full, with a worksheet to fill in for each endpoint. In short:

  • List every write endpoint: each route that creates or changes a stored record, including sign-up, admin screens, imports and webhooks. The WSTG's latest test begins in a similar place, by enumerating the HTTP requests that appear to allow create or update operations on the back end.
  • For each one, list the fields the form or client sends, taken from a real request.
  • List the fields the stored record has, taken from the schema or the model, including the ones no screen shows.
  • Mark each stored field, for this operation, as client-writable, set by the server, or never changed by this operation.
  • Save the stored record, send the intended request, and save the record again.
  • Restore the record, send the intended request with one extra field added, and save the record a third time. Repeat for each privileged field, for the same field inside any nested object, for the same name in another letter case, and for a name that does not exist.
  • Compare the stored records. The extra field must make no difference outside the client-writable fields: nothing marked never changed has moved, every server-set field holds what the intended request left there, and no new field has appeared.

Where the extra field names come from

Start with the record itself: every field you marked as server-set or never changed is a name to send. Then use what the application shows you. The WSTG's latest test suggests reading the responses of handlers that return an object's details for clues about its fields.

Where there are several roles, it suggests comparing the requests made by different user levels and trying the extra parameters from an administrator's requests as a low-privileged user. Where input names use bracket syntax, such as user[name], it suggests adding an input for an attribute that does not exist and analysing the response.

It also notes that access to the database schema or the source code makes the sensitive fields easy to identify.

Which WSTG edition has the test

OWASP's Web Security Testing Guide has a mass assignment test only in some editions. The stable edition is v4.2, and its input validation section runs from 4.7.1 to 4.7.19 with no mass assignment test. The edition the site labels Latest, which it says represents the latest contributions to the guide and may frequently change, has one: 4.7.20 Mass Assignment, with the ID WSTG-INJT-20, in a section titled Injection.

This page uses the Latest edition for that test, as it read on 14 November 2026, and v4.2 for the forged requests test, WSTG-BUSL-02.

The test's two objectives are to identify requests that modify objects, and to assess whether it is possible to modify fields never intended to be modified from outside.

The lab: an invented tea shop, careless and careful

The lab in the asset is an illustration written for this page, not client code.

The tea shop, its three accounts, its catalogue and its orders are invented, everything is held in memory, and money is counted in whole cents. It shows the pattern. It does not reproduce the behaviour of any real framework, binder or database.

It is eight files. shop.mjs holds the catalogue and the seeded accounts. careless.mjs holds the careless handlers and the block-list ones, and careful.mjs holds the input shapes and the careful handlers. server.mjs serves whichever version is named on the command line and holds the checks every version shares. field-plan.mjs is the worksheet as data, with the fourteen requests the lab sends. request-diff.mjs plays the requests and compares stored records, run-diff.mjs prints the evidence, and privileged-fields.test.mjs is the regression test. The lab imports only node:child_process, node:http, node:url, node:assert/strict and node:test, and installs no packages.

The API runs as its own process, listening only on 127.0.0.1 and asking for port 0. The Node.js documentation says the HTTP server's listen method is identical to the one on net.Server, where a port of 0 has the operating system assign an arbitrary unused port.

The runner starts the API, resets its records before every request, sends the request, reads the stored record back, and stops the API by its process id when the run ends.

On Node.js v26.0.0 on macOS 27.2.1, the careless version stored something outside the plan for all 10 extra-field requests: a role of admin, a second Role field, a verified flag, 50000 cents of store credit, an order owned by another customer, a total of 1 cent, a unit price of 1 cent inside the order line, an order marked paid, and on the admin edit a replaced email address and a replaced id.

The block-list version stopped four of the ten and let six through.

The careful version refused all ten with a 422 and stored nothing. The careful-ignore version answered 200 or 201 and stored only what the intended request stores.

The Node.js documentation marks node:test as stable from version 20.0.0. The lab has been run only on v26.0.0, and its test timings will differ on your machine.

Regression tests that prove the privileged fields did not change

A request diff run once tells you about one build.

The same comparison kept as a test tells you when a later change reopens the hole, for example when someone adds a field to a record or swaps a field-by-field update for a convenient one.

The lab's test file has one test per privileged property: role, the differently cased Role, emailVerified, storeCreditCents, ownerId, totalCents, the nested unitPriceCents, status, and the admin edit's email address and id. The file plays all fourteen requests once against the chosen version, and each of these tests passes only if its extra-field request left nothing outside the plan changed in the stored record.

An eleventh test checks the ordinary requests: the intended profile edit, order and admin edit are stored as sent, and a customer calling the admin endpoint gets a 403. Without it, a server that refused every request would pass.

Against the careless version, 10 of the 11 tests failed and the process exited with code 1. Against the block-list version, 6 failed. Against the careful version and the careful-ignore version, all 11 passed with exit code 0.

The Node.js documentation says the process exit code is set to 1 if any tests fail, and that node --test by default runs files matching patterns that include names ending in .test.mjs.

In the lab folder, node --test exited with code 0; the asset shows that exit code and not the command's output. Run with no version named, the test file tests the careful version.

Two habits make tests like these worth keeping. Assert on the stored record, read from the database, not on the response: a handler can accept a field and leave it out of what it sends back. And name each test after the property it protects, so that a failure reads as a sentence, such as "role stays as it was on a profile edit".

What this guide leaves to other guides

Five neighbouring topics get one sentence here and a guide of their own elsewhere in this library:

  • Broken access control and IDOR: whether this account may reach this record or this function at all, which has to be answered before the question of which fields it may write.
  • Business logic vulnerabilities: whether amounts, limits and steps still add up across a whole flow, such as a quantity changed after the total was fixed.
  • NoSQL injection: a request value that changes what a database query asks, such as an object sent where text was expected, where this guide is about which fields a write may set.
  • API security, a guide planned for this library: the wider API surface, including the inventory of endpoints that the worksheet here assumes you have.
  • Secure code review: reading the create and update handlers themselves, to see whether a whole request body reaches the database.

Where an outside test or code review fits

Your own worksheet covers the endpoints you know about and the fields you thought to send.

In a Clever Ops web application and API penetration test, each route in scope is called directly as well as through the interface, with fields the form never sends, from test accounts in each role the scope names. Fields get test cases of their own, including whether the server will accept a change to a property the user should not control, such as plan, role, credit balance or owner (WSTG v4.2 test WSTG-BUSL-02; ASVS 5.0 requirements 8.2.3 and 15.3.3; OWASP API3:2023).

Reading the code answers the same question from the other side. Clever Ops reviews code for applications such as Next.js, React and Node with read-only access to the repository, and a secure code review checks that create and update handlers limit the fields they accept rather than passing a whole request body to the database.

Code findings are confirmed against a running build where the scope allows, and the report marks any that rest on the code alone. Laravel applications sit outside this service.

Destructive actions are off by default for real people's accounts and records that existed before the test, and reset, lockout and deletion checks run only on test accounts and test records where the rules of engagement allow them. The report gives each finding with redacted evidence, its business impact, a fix and the criteria the retest will use.

If Clever Ops built or hosts your application, the work is a security review rather than an independent test, and the report says who built it and who hosts it.

Frequently asked questions

It is a handler that binds a whole request to a stored record, so a client can set fields the form never offered, such as a role, a price, an owner or a verified flag. MITRE catalogues it as CWE-915: the product receives input that specifies multiple attributes to be initialised or updated in an object, but does not properly control which attributes can be modified. OWASP's cheat sheet lists autobinding (Spring MVC and ASP NET MVC) and object injection (PHP) as alternative names, depending on the language or framework.

This page treats them as two names for one mistake. Microsoft's ASP.NET Core documentation uses overposting for a client posting a value for a property the page was not meant to set, and OWASP's cheat sheet lists autobinding as a name used with ASP NET MVC. In OWASP's API Security Top 10 it was API6:2019 Mass Assignment, and API3:2023 now covers a user changing a sensitive property they should not be able to access.

Give every write operation an explicit list of the fields a client may send, as its own input shape or DTO, and write only those fields. Set server-owned values such as the owner, the price and the status in code that never reads the request body. ASVS 5.0 requirement 15.3.3, at Level 2, asks for allowed fields to be limited per controller and action. Then keep a regression test for each privileged field.

A list of the properties one operation is allowed to write, with everything else refused or dropped. It is the opposite of a block-list of dangerous names. CWE-915 says to prefer allowlists over denylists if possible, and OWASP's cheat sheet says a block-list leaves a new or overlooked sensitive field bindable. In this page's lab, a block-list stopped the four names on it and let six of ten extra-field requests through.

Either keeps the stored record intact, as long as the handler writes only listed fields. Refusing tells you a client is sending something the operation does not take, which is why the lab on this page refuses. Ignoring suits a public API whose clients you do not control. Frameworks document both: Zod 4's z.object() strips unknown keys and z.strictObject() throws, and Laravel 13.x discards unfillable attributes silently by default, with an option to throw instead.

Not by itself. Mongoose 9.12.1's strict option, enabled by default, keeps values that are not in the schema from being saved, but a role field is in the schema. Prisma ORM v7's generated input types are derived from the model, and its documentation shows an unchecked input type that contains a relation scalar field, authorId. A per-operation list of allowed fields is still needed in front of either.

On an application you own or are authorised in writing to test, send each write endpoint its intended request, then the same request with one privileged field added, and compare the stored record each time. Try the field at the top level, inside nested objects and in another letter case. The latest edition of OWASP's WSTG covers it as WSTG-INJT-20, and the worksheet and lab on this page give the steps and a regression test.

Scope the right test for your application

Tell us what you have built, who uses it and when it needs to launch. You will get a plain-English recommendation: a website audit, a web application test or a referral to a specialist.