Broken access control and IDOR: where the check goes missing, and how to test for it
Broken access control is an application letting someone read, change or do something its own rules say they may not.
This guide explains horizontal and vertical access, the places in real applications where the check goes missing, and a two-account test matrix you can run against your own application, with a local lab that runs the matrix against a flawed and a fixed API.
In this guide
Two-account access control test matrix, with a lab that runs it
Part 1 is the matrix: four accounts and a signed-out row, seven object routes, the expected result for every cell and the evidence to keep, usable on its own for an application you own or are authorised in writing to test. Part 2 is an illustration, not a client system: an invented expense app for two invented businesses, served by Node.js alone on 127.0.0.1 in a flawed and a fixed version, a runner that walks the matrix and prints every cell, and a regression test that fails on the flawed version and passes on the fixed one.
broken-access-control-idor.txt
Introduction5 lines
Part 1: The matrix53 lines
Part 2: The lab (an illustration)760 lines
Whole template830 lines
TWO-ACCOUNT ACCESS CONTROL TEST MATRIX
Use it only on an application you own, or one you are authorised in writing to test, with test accounts and test records. Changing an identifier in a request to a system you do not own, without written authority from its owner, is not something this matrix is for.
Part 1 is the matrix and works without the lab. Part 2 is the lab: an illustration that runs the same matrix on your own machine.
================================================================
PART 1: THE MATRIX
================================================================
ACCOUNTS, DOWN THE SIDE
A1 Ordinary user in tenant A. Owns every record the matrix targets.
A2 A second ordinary user in the same tenant A.
B1 An ordinary user in a different tenant, B.
ADMIN-A An administrator in tenant A.
NONE No session: signed out, or the session cookie or token left off.
A tenant is whatever your application keeps apart: a customer business, a household or a team.
If administrators belong to one tenant, add a row for tenant B's administrator and expect it to reach none of A1's records.
ROUTES, ACROSS THE TOP. Every request targets something A1 owns.
C1 Read by direct identifier GET one of A1's records by its id.
C2 Change by direct identifier PATCH, PUT or DELETE the same record. Test records only.
C3 Nested resource A child of A1's record, asked for under a parent the caller owns.
C4 List or search The list or search route, with any owner or filter parameter pointed at A1.
C5 Export The export or report route, with any tenant or owner parameter pointed at A1's tenant.
C6 Background job The status and the result of a job A1 started.
C7 Administrative function An action reserved for administrators, aimed at A1's record.
EXPECTED RESULTS
These are the rules of the lab's expense app: members see and edit only their own claims, the administrator sees every claim in their tenant and approves claims but does not edit them, and nobody crosses tenants. Rewrite any cell your own rules decide differently before you test.
C1 read A1 200 | A2 404 | B1 404 | ADMIN-A 200 | NONE 401
C2 change A1 200 | A2 404 | B1 404 | ADMIN-A 403 | NONE 401
C3 nested A1 200 | A2 404 | B1 404 | ADMIN-A 404, because the child is not under the parent named | NONE 401
C4 list A1 200 own records | A2 200 none of A1's | B1 200 none of A1's | ADMIN-A 200 A1's records | NONE 401
C5 export A1 200 own rows only | A2 200 own rows only | B1 200 own rows only | ADMIN-A 200 tenant A's rows | NONE 401
C6 job A1 200 | A2 404 | B1 404 | ADMIN-A 200 | NONE 401
C7 admin A1 403 | A2 404 | B1 404 | ADMIN-A 200 | NONE 401
404 means the same status and the same body as a record that does not exist.
403 is for a record the caller may already see but may not act on.
A 200 that holds even one record the caller should not see is a failure, whatever else it holds.
EVIDENCE TO KEEP FOR EVERY CELL, PASS OR FAIL
- The build or commit, the environment and the date.
- The account label, such as A2. Not the session token itself.
- The method, the full path with its query, and the request body.
- The status code, and the content type and length of the response.
- From the body, the record ids and the owner or tenant fields. Redact names, email addresses and other personal details.
- The expected result, the actual result, and MATCH or MISMATCH.
- For C2 and C7: the record read back by its owner before and after, to show whether it changed.
- For C5: the number of rows in the file and the owners they belong to.
- For C6: the job id, the account that started it, and what the status and result routes returned.
- What was created or changed for the test, and how it was cleaned up.
READING THE RESULTS
- A 200 holding another account's record: a leak. Horizontal from A2 or B1. Vertical in column C7.
- A 200 for the right account but with extra rows in C4 or C5: the filter is missing, or it comes from the request.
- A 403 where the matrix expects 404: not a leak by itself, but it confirms the record exists. Decide whether that matters for this record.
- A different error body for "not yours" and "does not exist": the same disclosure as a 403.
- A 500: not a pass. Find out whether the error happened before or after the record was loaded.
- A MISMATCH in the NONE row: the sign-in check itself is missing on that route.
================================================================
PART 2: THE LAB (AN ILLUSTRATION)
================================================================
The two businesses, their users, claims, receipts and jobs are invented. The API runs on your own machine, listens on 127.0.0.1 only, on a port the operating system picks, and keeps everything in memory. Use it for learning and for testing code you own.
Needs: Node.js, with nothing to install. The lab uses node:http, node:crypto, node:os, node:test and node:assert, and the fetch function built into Node.js.
Written and run on: Node.js 26.0.0. Every output below was copied from that run's captured output. Test timings will differ on your machine.
Setup: create an empty folder, save the five files below into it under the names shown, and open a terminal in it.
What the flawed version gets wrong, column by column:
C1 and C6 Signed in is the only check.
C2 Checks the tenant, not the owner.
C3 Checks the parent claim, then finds the receipt by its own id alone.
C4 Trusts the ownerId the screen sends.
C5 Builds its own query from a tenantId in the request.
C7 Relies on the Approve button only showing for administrators.
The fixed version sends every route through one policy: POLICY, decide and readableClaims in api.mjs.
================================================================
FILE 1 OF 5: data.mjs
================================================================
// data.mjs: the invented tenants, users and records, and the lab's own sessions.
// Illustration only. Two invented small businesses share one expense app.
// Everything lives in memory and disappears when the process exits.
import { randomBytes } from 'node:crypto'
// tenant-a is an invented bakery, tenant-b an invented plumbing business.
// Members submit their own expense claims; an admin approves claims in their tenant.
export const USERS = {
a1: { id: 'a1', tenantId: 'tenant-a', role: 'member' },
a2: { id: 'a2', tenantId: 'tenant-a', role: 'member' },
b1: { id: 'b1', tenantId: 'tenant-b', role: 'member' },
'admin-a': { id: 'admin-a', tenantId: 'tenant-a', role: 'admin' },
}
// Identifiers name their owner so the evidence is easy to read. The fixed
// version does not rely on that: it would hold with random identifiers too.
export function createStore() {
return {
claims: [
{ id: 'a1-claim-1', tenantId: 'tenant-a', ownerId: 'a1', description: 'Flour delivery', amountCents: 4250, status: 'pending' },
{ id: 'a1-claim-2', tenantId: 'tenant-a', ownerId: 'a1', description: 'Market stall', amountCents: 6000, status: 'pending' },
{ id: 'a2-claim-1', tenantId: 'tenant-a', ownerId: 'a2', description: 'Oven parts', amountCents: 18900, status: 'pending' },
{ id: 'admin-claim-1', tenantId: 'tenant-a', ownerId: 'admin-a', description: 'Bookkeeping app', amountCents: 3500, status: 'pending' },
{ id: 'b1-claim-1', tenantId: 'tenant-b', ownerId: 'b1', description: 'Pipe fittings', amountCents: 7725, status: 'pending' },
],
receipts: [
{ id: 'a1-receipt-1', claimId: 'a1-claim-1', fileName: 'flour-invoice.pdf' },
{ id: 'a2-receipt-1', claimId: 'a2-claim-1', fileName: 'oven-parts.pdf' },
{ id: 'admin-receipt-1', claimId: 'admin-claim-1', fileName: 'subscription.pdf' },
{ id: 'b1-receipt-1', claimId: 'b1-claim-1', fileName: 'fittings.pdf' },
],
// A finished background job: a1 asked for an export of their own claims.
jobs: [
{ id: 'a1-job-1', tenantId: 'tenant-a', startedBy: 'a1', kind: 'claims-export', status: 'done', claimIds: ['a1-claim-1', 'a1-claim-2'] },
{ id: 'b1-job-1', tenantId: 'tenant-b', startedBy: 'b1', kind: 'claims-export', status: 'done', claimIds: ['b1-claim-1'] },
],
}
}
// Session tokens invented by the lab: random values held in memory, sent
// back by the client in a cookie named session.
export function createSessions() {
const userIdByToken = new Map()
const tokenByUserId = new Map()
for (const userId of Object.keys(USERS)) {
const token = randomBytes(16).toString('hex')
userIdByToken.set(token, userId)
tokenByUserId.set(userId, token)
}
return {
tokenFor: (userId) => tokenByUserId.get(userId),
userFor: (token) => USERS[userIdByToken.get(token)] || null,
}
}
================================================================
FILE 2 OF 5: api.mjs
================================================================
// api.mjs: one small expense-claims API, served in two versions.
// flawed: some routes check only that the caller is signed in, and others
// check the wrong thing.
// fixed: every route asks one policy, kept in one place, about the caller
// and the record.
// The server listens on 127.0.0.1 only.
import { createServer } from 'node:http'
import { EOL } from 'node:os'
// ---------------------------------------------------------------------------
// Shared plumbing. Both versions use it unchanged, including the sign-in check.
// ---------------------------------------------------------------------------
const NOT_FOUND = { status: 404, body: { error: 'Not found' } }
const FORBIDDEN = { status: 403, body: { error: 'Forbidden' } }
const NOT_SIGNED_IN = { status: 401, body: { error: 'Not signed in' } }
const ROUTES = [
['GET', '/api/claims', 'listClaims'],
['GET', '/api/claims/:claimId', 'readClaim'],
['PATCH', '/api/claims/:claimId', 'updateClaim'],
['GET', '/api/claims/:claimId/receipts/:receiptId', 'readReceipt'],
['GET', '/api/exports/claims.csv', 'exportClaims'],
['GET', '/api/jobs/:jobId', 'readJob'],
['POST', '/api/admin/claims/:claimId/approve', 'approveClaim'],
]
function matchRoute(method, pathname) {
const pathParts = pathname.split('/')
for (const [routeMethod, pattern, handlerName] of ROUTES) {
const patternParts = pattern.split('/')
if (routeMethod !== method || patternParts.length !== pathParts.length) continue
const params = {}
const isMatch = patternParts.every((part, index) => {
if (part.startsWith(':')) {
params[part.slice(1)] = pathParts[index]
return true
}
return part === pathParts[index]
})
if (isMatch) return { handlerName: handlerName, params: params }
}
return null
}
function readSessionUser(request, sessions) {
const cookies = (request.headers.cookie || '').split(';')
for (const cookie of cookies) {
const parts = cookie.trim().split('=')
if (parts[0] === 'session') return sessions.userFor(parts[1])
}
return null
}
function readJsonBody(request) {
return new Promise((resolve) => {
let text = ''
request.on('data', (chunk) => {
text += chunk
})
request.on('end', () => {
try {
resolve(text ? JSON.parse(text) : {})
} catch {
resolve({})
}
})
})
}
function findById(list, id) {
return list.find((item) => item.id === id) || null
}
function toCsv(claims) {
const lines = ['id,owner,description,amountCents,status']
for (const claim of claims) {
lines.push([claim.id, claim.ownerId, claim.description, claim.amountCents, claim.status].join(','))
}
return { status: 200, csv: lines.join(EOL) }
}
// ---------------------------------------------------------------------------
// FLAWED: checks a team can ship without noticing, because every screen works.
// ---------------------------------------------------------------------------
const flawed = {
// Signed in is the only check: any user can read any claim by its id.
readClaim: ({ store, params }) => {
const claim = findById(store.claims, params.claimId)
return claim ? { status: 200, body: claim } : NOT_FOUND
},
// Checks the tenant but not the owner, so a colleague can edit your claim.
updateClaim: ({ user, store, params, body }) => {
const claim = findById(store.claims, params.claimId)
if (!claim || claim.tenantId !== user.tenantId) return NOT_FOUND
claim.description = String(body.description || claim.description)
return { status: 200, body: claim }
},
// Checks the parent claim properly, then finds the receipt by its own id
// alone, so any receipt can be read under a claim the caller can see.
readReceipt: ({ user, store, params }) => {
const claim = findById(store.claims, params.claimId)
const canSeeClaim =
claim && claim.tenantId === user.tenantId && (claim.ownerId === user.id || user.role === 'admin')
if (!canSeeClaim) return NOT_FOUND
const receipt = findById(store.receipts, params.receiptId)
return receipt ? { status: 200, body: receipt } : NOT_FOUND
},
// Trusts the ownerId the screen sends, so anyone's claims can be listed.
listClaims: ({ user, store, query }) => {
const ownerId = query.get('ownerId') || user.id
return { status: 200, body: store.claims.filter((claim) => claim.ownerId === ownerId) }
},
// The export builds its own query from a tenantId in the request.
exportClaims: ({ user, store, query }) => {
const tenantId = query.get('tenantId') || user.tenantId
return toCsv(store.claims.filter((claim) => claim.tenantId === tenantId))
},
// Signed in is the only check: any user can read any job and its result.
readJob: ({ store, params }) => {
const job = findById(store.jobs, params.jobId)
return job ? { status: 200, body: job } : NOT_FOUND
},
// The Approve button only appears for admins, and the route relies on that.
approveClaim: ({ store, params }) => {
const claim = findById(store.claims, params.claimId)
if (!claim) return NOT_FOUND
claim.status = 'approved'
return { status: 200, body: claim }
},
}
// ---------------------------------------------------------------------------
// FIXED: one policy, asked by every route. Each rule answers one question:
// may this user do this to this record?
// ---------------------------------------------------------------------------
const POLICY = {
'claim:read': (user, claim) =>
claim.tenantId === user.tenantId && (claim.ownerId === user.id || user.role === 'admin'),
'claim:update': (user, claim) => claim.tenantId === user.tenantId && claim.ownerId === user.id,
'claim:approve': (user, claim) => claim.tenantId === user.tenantId && user.role === 'admin',
'job:read': (user, job) =>
job.tenantId === user.tenantId && (job.startedBy === user.id || user.role === 'admin'),
}
// A record the caller may not read gets the same 404 as a record that does
// not exist. A record they may read but not act on gets a 403.
// Returns null when the action is allowed.
function decide(user, type, action, record) {
if (!record || !POLICY[type + ':read'](user, record)) return NOT_FOUND
if (!POLICY[type + ':' + action](user, record)) return FORBIDDEN
return null
}
// Lists and exports start from what the caller may read, not from the request.
function readableClaims(user, store) {
return store.claims.filter((claim) => POLICY['claim:read'](user, claim))
}
const fixed = {
readClaim: ({ user, store, params }) => {
const claim = findById(store.claims, params.claimId)
return decide(user, 'claim', 'read', claim) || { status: 200, body: claim }
},
updateClaim: ({ user, store, params, body }) => {
const claim = findById(store.claims, params.claimId)
const refusal = decide(user, 'claim', 'update', claim)
if (refusal) return refusal
claim.description = String(body.description || claim.description)
return { status: 200, body: claim }
},
// The receipt has to belong to the claim named in the path.
readReceipt: ({ user, store, params }) => {
const claim = findById(store.claims, params.claimId)
const refusal = decide(user, 'claim', 'read', claim)
if (refusal) return refusal
const receipt = store.receipts.find((item) => item.id === params.receiptId && item.claimId === claim.id)
return receipt ? { status: 200, body: receipt } : NOT_FOUND
},
// An ownerId in the request only narrows what the caller may already read.
listClaims: ({ user, store, query }) => {
const ownerId = query.get('ownerId')
const claims = readableClaims(user, store).filter((claim) => !ownerId || claim.ownerId === ownerId)
return { status: 200, body: claims }
},
// The scope comes from the session. A tenantId in the request is ignored.
exportClaims: ({ user, store }) => toCsv(readableClaims(user, store)),
readJob: ({ user, store, params }) => {
const job = findById(store.jobs, params.jobId)
return decide(user, 'job', 'read', job) || { status: 200, body: job }
},
approveClaim: ({ user, store, params }) => {
const claim = findById(store.claims, params.claimId)
const refusal = decide(user, 'claim', 'approve', claim)
if (refusal) return refusal
claim.status = 'approved'
return { status: 200, body: claim }
},
}
// ---------------------------------------------------------------------------
// The server.
// ---------------------------------------------------------------------------
const VERSIONS = { flawed: flawed, fixed: fixed }
async function answer(request, handlers, state, sessions) {
const url = new URL(request.url, 'http://127.0.0.1')
const route = matchRoute(request.method, url.pathname)
if (!route) return NOT_FOUND
const user = readSessionUser(request, sessions)
if (!user) return NOT_SIGNED_IN
const body = await readJsonBody(request)
const context = { user: user, store: state.store, params: route.params, query: url.searchParams, body: body }
return handlers[route.handlerName](context)
}
function sendResult(response, result) {
if (typeof result.csv === 'string') {
response.writeHead(result.status, { 'content-type': 'text/csv' })
response.end(result.csv)
return
}
response.writeHead(result.status, { 'content-type': 'application/json' })
response.end(JSON.stringify(result.body))
}
// state.store holds the records, so a caller can swap in a fresh copy.
export function startApi(version, state, sessions) {
const handlers = VERSIONS[version]
if (!handlers) throw new Error('Unknown version: ' + version)
const server = createServer(async (request, response) => {
sendResult(response, await answer(request, handlers, state, sessions))
})
return new Promise((resolve) => {
// Port 0 asks the operating system for any unused port.
server.listen(0, '127.0.0.1', () => resolve(server))
})
}
================================================================
FILE 3 OF 5: matrix.mjs
================================================================
// matrix.mjs: the two-account role and object matrix as data, and a walker
// that sends every cell to one version of the API and compares the answer
// with the expected result. Every request targets records that a1 owns.
import { EOL } from 'node:os'
import { createSessions, createStore } from './data.mjs'
import { startApi } from './api.mjs'
// Accounts down the side.
export const ACCOUNTS = [
{ key: 'A1', userId: 'a1' },
{ key: 'A2', userId: 'a2' },
{ key: 'B1', userId: 'b1' },
{ key: 'ADMIN-A', userId: 'admin-a' },
{ key: 'NONE', userId: null },
]
// A claim each account owns, used as the parent in column C3.
const OWN_CLAIM = { A1: 'a1-claim-1', A2: 'a2-claim-1', B1: 'b1-claim-1', 'ADMIN-A': 'admin-claim-1', NONE: 'a1-claim-1' }
// Object routes across the top.
export const COLUMNS = [
{ key: 'C1', title: 'read a claim by its id', request: () => ({ method: 'GET', path: '/api/claims/a1-claim-1' }) },
{
key: 'C2',
title: 'change a claim by its id',
request: () => ({ method: 'PATCH', path: '/api/claims/a1-claim-1', body: { description: 'Edited in test' } }),
},
{
key: 'C3',
title: "a1's receipt, asked for under a claim the caller owns",
request: (account) => ({ method: 'GET', path: '/api/claims/' + OWN_CLAIM[account.key] + '/receipts/a1-receipt-1' }),
},
{ key: 'C4', title: 'list claims, with the owner filter the screen sends', request: () => ({ method: 'GET', path: '/api/claims?ownerId=a1' }) },
{
key: 'C5',
title: 'export claims as CSV, with a tenant in the request',
request: () => ({ method: 'GET', path: '/api/exports/claims.csv?tenantId=tenant-a' }),
},
{ key: 'C6', title: "status and result of a1's export job", request: () => ({ method: 'GET', path: '/api/jobs/a1-job-1' }) },
{ key: 'C7', title: 'approve a claim (administrator function)', request: () => ({ method: 'POST', path: '/api/admin/claims/a1-claim-1/approve' }) },
]
function allowed(ids) {
return { status: 200, ids: ids }
}
function refused(status) {
return { status: status, ids: null }
}
const SIGNED_OUT = refused(401)
// The expected result of every cell: a status and, for a 200, the records that may come back.
export const EXPECTED = {
A1: {
C1: allowed(['a1-claim-1']),
C2: allowed(['a1-claim-1']),
C3: allowed(['a1-receipt-1']),
C4: allowed(['a1-claim-1', 'a1-claim-2']),
C5: allowed(['a1-claim-1', 'a1-claim-2']),
C6: allowed(['a1-job-1']),
C7: refused(403),
},
A2: {
C1: refused(404),
C2: refused(404),
C3: refused(404),
C4: allowed([]),
C5: allowed(['a2-claim-1']),
C6: refused(404),
C7: refused(404),
},
B1: {
C1: refused(404),
C2: refused(404),
C3: refused(404),
C4: allowed([]),
C5: allowed(['b1-claim-1']),
C6: refused(404),
C7: refused(404),
},
'ADMIN-A': {
C1: allowed(['a1-claim-1']),
C2: refused(403),
C3: refused(404),
C4: allowed(['a1-claim-1', 'a1-claim-2']),
C5: allowed(['a1-claim-1', 'a1-claim-2', 'a2-claim-1', 'admin-claim-1']),
C6: allowed(['a1-job-1']),
C7: allowed(['a1-claim-1']),
},
NONE: { C1: SIGNED_OUT, C2: SIGNED_OUT, C3: SIGNED_OUT, C4: SIGNED_OUT, C5: SIGNED_OUT, C6: SIGNED_OUT, C7: SIGNED_OUT },
}
function listOrNone(ids) {
return ids.length ? ids.join(', ') : 'none'
}
function readIds(isCsv, text) {
if (isCsv) return text.split(EOL).slice(1).map((line) => line.split(',')[0])
const body = JSON.parse(text)
return Array.isArray(body) ? body.map((item) => item.id) : [body.id]
}
// A short description of what came back, so the evidence reads on one line.
function summariseBody(status, isCsv, text, ids) {
if (status !== 200) return status + ' ' + JSON.parse(text).error
if (isCsv) return '200 CSV rows: ' + listOrNone(ids)
const body = JSON.parse(text)
if (Array.isArray(body)) return '200 claims: ' + listOrNone(ids)
if (body.claimId) return '200 receipt ' + body.id + ' (' + body.fileName + ')'
if (body.startedBy) return '200 job ' + body.id + ', ' + body.status + ', result: ' + body.claimIds.join(', ')
return '200 claim ' + body.id + ', ' + body.status + ', "' + body.description + '"'
}
function describeExpected(expected) {
if (expected.status !== 200) return 'want ' + expected.status
return 'want 200 ' + (expected.ids.length ? expected.ids.join(', ') : 'with no claims')
}
function isSameList(actual, expected) {
return Array.isArray(actual) && actual.join('|') === expected.join('|')
}
async function sendCell(baseUrl, sessions, column, account) {
const request = column.request(account)
const headers = { 'content-type': 'application/json' }
if (account.userId) headers.cookie = 'session=' + sessions.tokenFor(account.userId)
const response = await fetch(baseUrl + request.path, {
method: request.method,
headers: headers,
body: request.body ? JSON.stringify(request.body) : undefined,
})
const text = await response.text()
const isCsv = (response.headers.get('content-type') || '').startsWith('text/csv')
const ids = response.status === 200 ? readIds(isCsv, text) : null
const expected = EXPECTED[account.key][column.key]
return {
column: column.key,
account: account.key,
request: request.method + ' ' + request.path,
summary: summariseBody(response.status, isCsv, text, ids),
expected: describeExpected(expected),
matches: response.status === expected.status && (expected.ids === null || isSameList(ids, expected.ids)),
}
}
// Sends every cell to one version. Each cell starts from the same seeded
// records, so a change made in one cell cannot affect the next.
export async function walkMatrix(version) {
const state = { store: createStore() }
const sessions = createSessions()
const server = await startApi(version, state, sessions)
const baseUrl = 'http://127.0.0.1:' + server.address().port
const results = []
try {
for (const column of COLUMNS) {
for (const account of ACCOUNTS) {
state.store = createStore()
results.push(await sendCell(baseUrl, sessions, column, account))
}
}
} finally {
server.close()
}
return results
}
================================================================
FILE 4 OF 5: run-matrix.mjs
================================================================
// run-matrix.mjs: walks the matrix against both versions and prints every cell:
// the account, the request, what came back, what was expected, and whether they match.
// Run: node run-matrix.mjs
import { COLUMNS, walkMatrix } from './matrix.mjs'
for (const version of ['flawed', 'fixed']) {
const results = await walkMatrix(version)
console.log('VERSION: ' + version)
for (const column of COLUMNS) {
console.log('')
console.log(column.key + ' ' + column.title)
for (const result of results.filter((item) => item.column === column.key)) {
const verdict = result.matches ? 'MATCH' : 'MISMATCH'
console.log(' ' + result.account.padEnd(8) + result.request + ' -> ' + result.summary + ' | ' + result.expected + ' | ' + verdict)
}
}
const mismatchCount = results.filter((item) => !item.matches).length
console.log('')
console.log('Total for ' + version + ': ' + results.length + ' cells, ' + (results.length - mismatchCount) + ' match, ' + mismatchCount + ' do not.')
console.log('')
}
================================================================
FILE 5 OF 5: access.test.mjs
================================================================
// access.test.mjs: one test per matrix column. A column fails while any of
// its cells differs from the expected result.
// Run: node access.test.mjs flawed (expect failures)
// node access.test.mjs fixed (expect every test to pass)
// With no argument it tests the fixed version, which is what node --test runs.
import assert from 'node:assert/strict'
import { test } from 'node:test'
import { COLUMNS, walkMatrix } from './matrix.mjs'
const version = process.argv[2] || 'fixed'
const results = await walkMatrix(version)
for (const column of COLUMNS) {
test(version + ': ' + column.key + ' ' + column.title, () => {
const differences = results
.filter((result) => result.column === column.key && !result.matches)
.map((result) => result.account + ' ' + result.request + ' got ' + result.summary + ', ' + result.expected)
assert.deepEqual(differences, [])
})
}
================================================================
STEP 1: walk the matrix against both versions
================================================================
Command: node run-matrix.mjs
VERSION: flawed
C1 read a claim by its id
A1 GET /api/claims/a1-claim-1 -> 200 claim a1-claim-1, pending, "Flour delivery" | want 200 a1-claim-1 | MATCH
A2 GET /api/claims/a1-claim-1 -> 200 claim a1-claim-1, pending, "Flour delivery" | want 404 | MISMATCH
B1 GET /api/claims/a1-claim-1 -> 200 claim a1-claim-1, pending, "Flour delivery" | want 404 | MISMATCH
ADMIN-A GET /api/claims/a1-claim-1 -> 200 claim a1-claim-1, pending, "Flour delivery" | want 200 a1-claim-1 | MATCH
NONE GET /api/claims/a1-claim-1 -> 401 Not signed in | want 401 | MATCH
C2 change a claim by its id
A1 PATCH /api/claims/a1-claim-1 -> 200 claim a1-claim-1, pending, "Edited in test" | want 200 a1-claim-1 | MATCH
A2 PATCH /api/claims/a1-claim-1 -> 200 claim a1-claim-1, pending, "Edited in test" | want 404 | MISMATCH
B1 PATCH /api/claims/a1-claim-1 -> 404 Not found | want 404 | MATCH
ADMIN-A PATCH /api/claims/a1-claim-1 -> 200 claim a1-claim-1, pending, "Edited in test" | want 403 | MISMATCH
NONE PATCH /api/claims/a1-claim-1 -> 401 Not signed in | want 401 | MATCH
C3 a1's receipt, asked for under a claim the caller owns
A1 GET /api/claims/a1-claim-1/receipts/a1-receipt-1 -> 200 receipt a1-receipt-1 (flour-invoice.pdf) | want 200 a1-receipt-1 | MATCH
A2 GET /api/claims/a2-claim-1/receipts/a1-receipt-1 -> 200 receipt a1-receipt-1 (flour-invoice.pdf) | want 404 | MISMATCH
B1 GET /api/claims/b1-claim-1/receipts/a1-receipt-1 -> 200 receipt a1-receipt-1 (flour-invoice.pdf) | want 404 | MISMATCH
ADMIN-A GET /api/claims/admin-claim-1/receipts/a1-receipt-1 -> 200 receipt a1-receipt-1 (flour-invoice.pdf) | want 404 | MISMATCH
NONE GET /api/claims/a1-claim-1/receipts/a1-receipt-1 -> 401 Not signed in | want 401 | MATCH
C4 list claims, with the owner filter the screen sends
A1 GET /api/claims?ownerId=a1 -> 200 claims: a1-claim-1, a1-claim-2 | want 200 a1-claim-1, a1-claim-2 | MATCH
A2 GET /api/claims?ownerId=a1 -> 200 claims: a1-claim-1, a1-claim-2 | want 200 with no claims | MISMATCH
B1 GET /api/claims?ownerId=a1 -> 200 claims: a1-claim-1, a1-claim-2 | want 200 with no claims | MISMATCH
ADMIN-A GET /api/claims?ownerId=a1 -> 200 claims: a1-claim-1, a1-claim-2 | want 200 a1-claim-1, a1-claim-2 | MATCH
NONE GET /api/claims?ownerId=a1 -> 401 Not signed in | want 401 | MATCH
C5 export claims as CSV, with a tenant in the request
A1 GET /api/exports/claims.csv?tenantId=tenant-a -> 200 CSV rows: a1-claim-1, a1-claim-2, a2-claim-1, admin-claim-1 | want 200 a1-claim-1, a1-claim-2 | MISMATCH
A2 GET /api/exports/claims.csv?tenantId=tenant-a -> 200 CSV rows: a1-claim-1, a1-claim-2, a2-claim-1, admin-claim-1 | want 200 a2-claim-1 | MISMATCH
B1 GET /api/exports/claims.csv?tenantId=tenant-a -> 200 CSV rows: a1-claim-1, a1-claim-2, a2-claim-1, admin-claim-1 | want 200 b1-claim-1 | MISMATCH
ADMIN-A GET /api/exports/claims.csv?tenantId=tenant-a -> 200 CSV rows: a1-claim-1, a1-claim-2, a2-claim-1, admin-claim-1 | want 200 a1-claim-1, a1-claim-2, a2-claim-1, admin-claim-1 | MATCH
NONE GET /api/exports/claims.csv?tenantId=tenant-a -> 401 Not signed in | want 401 | MATCH
C6 status and result of a1's export job
A1 GET /api/jobs/a1-job-1 -> 200 job a1-job-1, done, result: a1-claim-1, a1-claim-2 | want 200 a1-job-1 | MATCH
A2 GET /api/jobs/a1-job-1 -> 200 job a1-job-1, done, result: a1-claim-1, a1-claim-2 | want 404 | MISMATCH
B1 GET /api/jobs/a1-job-1 -> 200 job a1-job-1, done, result: a1-claim-1, a1-claim-2 | want 404 | MISMATCH
ADMIN-A GET /api/jobs/a1-job-1 -> 200 job a1-job-1, done, result: a1-claim-1, a1-claim-2 | want 200 a1-job-1 | MATCH
NONE GET /api/jobs/a1-job-1 -> 401 Not signed in | want 401 | MATCH
C7 approve a claim (administrator function)
A1 POST /api/admin/claims/a1-claim-1/approve -> 200 claim a1-claim-1, approved, "Flour delivery" | want 403 | MISMATCH
A2 POST /api/admin/claims/a1-claim-1/approve -> 200 claim a1-claim-1, approved, "Flour delivery" | want 404 | MISMATCH
B1 POST /api/admin/claims/a1-claim-1/approve -> 200 claim a1-claim-1, approved, "Flour delivery" | want 404 | MISMATCH
ADMIN-A POST /api/admin/claims/a1-claim-1/approve -> 200 claim a1-claim-1, approved, "Flour delivery" | want 200 a1-claim-1 | MATCH
NONE POST /api/admin/claims/a1-claim-1/approve -> 401 Not signed in | want 401 | MATCH
Total for flawed: 35 cells, 18 match, 17 do not.
VERSION: fixed
C1 read a claim by its id
A1 GET /api/claims/a1-claim-1 -> 200 claim a1-claim-1, pending, "Flour delivery" | want 200 a1-claim-1 | MATCH
A2 GET /api/claims/a1-claim-1 -> 404 Not found | want 404 | MATCH
B1 GET /api/claims/a1-claim-1 -> 404 Not found | want 404 | MATCH
ADMIN-A GET /api/claims/a1-claim-1 -> 200 claim a1-claim-1, pending, "Flour delivery" | want 200 a1-claim-1 | MATCH
NONE GET /api/claims/a1-claim-1 -> 401 Not signed in | want 401 | MATCH
C2 change a claim by its id
A1 PATCH /api/claims/a1-claim-1 -> 200 claim a1-claim-1, pending, "Edited in test" | want 200 a1-claim-1 | MATCH
A2 PATCH /api/claims/a1-claim-1 -> 404 Not found | want 404 | MATCH
B1 PATCH /api/claims/a1-claim-1 -> 404 Not found | want 404 | MATCH
ADMIN-A PATCH /api/claims/a1-claim-1 -> 403 Forbidden | want 403 | MATCH
NONE PATCH /api/claims/a1-claim-1 -> 401 Not signed in | want 401 | MATCH
C3 a1's receipt, asked for under a claim the caller owns
A1 GET /api/claims/a1-claim-1/receipts/a1-receipt-1 -> 200 receipt a1-receipt-1 (flour-invoice.pdf) | want 200 a1-receipt-1 | MATCH
A2 GET /api/claims/a2-claim-1/receipts/a1-receipt-1 -> 404 Not found | want 404 | MATCH
B1 GET /api/claims/b1-claim-1/receipts/a1-receipt-1 -> 404 Not found | want 404 | MATCH
ADMIN-A GET /api/claims/admin-claim-1/receipts/a1-receipt-1 -> 404 Not found | want 404 | MATCH
NONE GET /api/claims/a1-claim-1/receipts/a1-receipt-1 -> 401 Not signed in | want 401 | MATCH
C4 list claims, with the owner filter the screen sends
A1 GET /api/claims?ownerId=a1 -> 200 claims: a1-claim-1, a1-claim-2 | want 200 a1-claim-1, a1-claim-2 | MATCH
A2 GET /api/claims?ownerId=a1 -> 200 claims: none | want 200 with no claims | MATCH
B1 GET /api/claims?ownerId=a1 -> 200 claims: none | want 200 with no claims | MATCH
ADMIN-A GET /api/claims?ownerId=a1 -> 200 claims: a1-claim-1, a1-claim-2 | want 200 a1-claim-1, a1-claim-2 | MATCH
NONE GET /api/claims?ownerId=a1 -> 401 Not signed in | want 401 | MATCH
C5 export claims as CSV, with a tenant in the request
A1 GET /api/exports/claims.csv?tenantId=tenant-a -> 200 CSV rows: a1-claim-1, a1-claim-2 | want 200 a1-claim-1, a1-claim-2 | MATCH
A2 GET /api/exports/claims.csv?tenantId=tenant-a -> 200 CSV rows: a2-claim-1 | want 200 a2-claim-1 | MATCH
B1 GET /api/exports/claims.csv?tenantId=tenant-a -> 200 CSV rows: b1-claim-1 | want 200 b1-claim-1 | MATCH
ADMIN-A GET /api/exports/claims.csv?tenantId=tenant-a -> 200 CSV rows: a1-claim-1, a1-claim-2, a2-claim-1, admin-claim-1 | want 200 a1-claim-1, a1-claim-2, a2-claim-1, admin-claim-1 | MATCH
NONE GET /api/exports/claims.csv?tenantId=tenant-a -> 401 Not signed in | want 401 | MATCH
C6 status and result of a1's export job
A1 GET /api/jobs/a1-job-1 -> 200 job a1-job-1, done, result: a1-claim-1, a1-claim-2 | want 200 a1-job-1 | MATCH
A2 GET /api/jobs/a1-job-1 -> 404 Not found | want 404 | MATCH
B1 GET /api/jobs/a1-job-1 -> 404 Not found | want 404 | MATCH
ADMIN-A GET /api/jobs/a1-job-1 -> 200 job a1-job-1, done, result: a1-claim-1, a1-claim-2 | want 200 a1-job-1 | MATCH
NONE GET /api/jobs/a1-job-1 -> 401 Not signed in | want 401 | MATCH
C7 approve a claim (administrator function)
A1 POST /api/admin/claims/a1-claim-1/approve -> 403 Forbidden | want 403 | MATCH
A2 POST /api/admin/claims/a1-claim-1/approve -> 404 Not found | want 404 | MATCH
B1 POST /api/admin/claims/a1-claim-1/approve -> 404 Not found | want 404 | MATCH
ADMIN-A POST /api/admin/claims/a1-claim-1/approve -> 200 claim a1-claim-1, approved, "Flour delivery" | want 200 a1-claim-1 | MATCH
NONE POST /api/admin/claims/a1-claim-1/approve -> 401 Not signed in | want 401 | MATCH
Total for fixed: 35 cells, 35 match, 0 do not.
Reading the evidence:
C1 In the flawed version A2 and B1 read a1's claim. NONE is refused in both versions: the sign-in check works, and it is not the problem.
C2 The tenant check stops B1 but not A2, and it lets the administrator edit a member's claim, which the rules leave to the owner.
C3 Each account reads a1's receipt by naming its own claim as the parent. For ADMIN-A that exposes nothing new, since the administrator can read the receipt under its real parent, but it shows the route does not check that the receipt belongs to the claim in the path.
C4 The owner filter comes from the request, so A2 and B1 list a1's claims. In the fixed version the same request returns an empty list.
C5 The export trusts tenantId. B1 receives tenant A's claims, and A1 and A2 each receive every claim in their tenant, the administrator's included. Only the ADMIN-A row comes out right.
C6 Any signed-in account reads a1's finished export job and the claim ids in its result.
C7 All three ordinary accounts approve a1's claim, A1 included. In the fixed version A1 gets 403, because it can see the claim but may not approve it, while A2 and B1 get 404, because they may not see it.
Totals: 17 of the 35 cells do not match in the flawed version. All 35 match in the fixed version.
================================================================
STEP 2: run the regression test against the flawed version
================================================================
Command: node access.test.mjs flawed
✖ flawed: C1 read a claim by its id (2.22375ms)
✖ flawed: C2 change a claim by its id (0.112084ms)
✖ flawed: C3 a1's receipt, asked for under a claim the caller owns (0.089875ms)
✖ flawed: C4 list claims, with the owner filter the screen sends (0.065541ms)
✖ flawed: C5 export claims as CSV, with a tenant in the request (0.07825ms)
✖ flawed: C6 status and result of a1's export job (0.070792ms)
✖ flawed: C7 approve a claim (administrator function) (0.059375ms)
ℹ tests 7
ℹ suites 0
ℹ pass 0
ℹ fail 7
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 5.554125
✖ failing tests:
test at access.test.mjs:14:3
✖ flawed: C1 read a claim by its id (2.22375ms)
AssertionError [ERR_ASSERTION]: Expected values to be strictly deep-equal:
+ actual - expected
+ [
+ 'A2 GET /api/claims/a1-claim-1 got 200 claim a1-claim-1, pending, "Flour delivery", want 404',
+ 'B1 GET /api/claims/a1-claim-1 got 200 claim a1-claim-1, pending, "Flour delivery", want 404'
+ ]
- []
(stack trace and error object lines removed here)
(The other six failures are left out here. Each one lists the cells that step 1 marks MISMATCH in its column.)
The process exits with code 1, so a pipeline step that runs this test fails.
================================================================
STEP 3: run it against the fixed version
================================================================
Command: node access.test.mjs fixed
✔ fixed: C1 read a claim by its id (1.04575ms)
✔ fixed: C2 change a claim by its id (0.044333ms)
✔ fixed: C3 a1's receipt, asked for under a claim the caller owns (0.036541ms)
✔ fixed: C4 list claims, with the owner filter the screen sends (0.026458ms)
✔ fixed: C5 export claims as CSV, with a tenant in the request (0.031625ms)
✔ fixed: C6 status and result of a1's export job (0.025916ms)
✔ fixed: C7 approve a claim (administrator function) (0.02925ms)
ℹ tests 7
ℹ suites 0
ℹ pass 7
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 3.80675
The process exits with code 0. With no argument the file tests the fixed version, which is what node --test runs when it finds the file by its .test.mjs name.
================================================================
STEP 4: point the matrix at your own application
================================================================
1. Copy matrix.mjs and access.test.mjs into your project's tests.
2. Replace startApi with your application running against a test database seeded with two tenants and the four accounts, and replace sessions.tokenFor with however your tests sign each account in.
3. Rewrite OWN_CLAIM, the paths in COLUMNS and the results in EXPECTED from Part 1, for your own routes and rules.
4. Keep the reset between cells: recreate or restore the seeded records so a change made in one cell cannot affect the next.
5. Run it in the pipeline that deploys your application, as a check that has to pass before a change merges.What broken access control is
An application with accounts makes two separate decisions on every request.
The first is who is asking. The second is whether that person may do this particular thing to this particular record. Access control is the second decision. OWASP's Top 10:2025 describes its job as enforcing policy so that users cannot act outside their intended permissions, and says failures typically lead to unauthorised information disclosure, modification or destruction of data, or a business function performed outside the user's limits.
Broken Access Control is A01, the first of the ten categories in the OWASP Top 10:2025. OWASP's page for the category says it keeps its position at number one, with some form of broken access control found in 100% of the applications tested.
MITRE's CWE list names the family and its shapes. CWE-284, Improper Access Control, is the broad entry: the product does not restrict, or incorrectly restricts, access to a resource from an unauthorised actor. Three more specific entries describe the shapes this page keeps returning to.
CWE-862, Missing Authorization, is a route that performs no authorisation check when someone asks for a resource or an action. CWE-863, Incorrect Authorization, is a route that performs a check but does not perform it correctly.
CWE-639, Authorization Bypass Through User-Controlled Key, which MITRE lists as a child of CWE-863, is one user reaching another user's data or record by changing the key value that identifies it.
IDOR, BOLA and the other names for it
IDOR stands for insecure direct object reference. CWE-639 lists it, and Broken Object Level Authorization (BOLA), among its alternate terms, with two caveats: OWASP's IDOR term is broader than CWE-639 because it also covers path traversal, and BOLA appears to have some overlap with CWE-639 but may also apply to other weaknesses.
OWASP's IDOR Prevention Cheat Sheet breaks the flaw into three ingredients: an object, such as an account, a document, a support ticket or a transaction; a reference to it, such as an ID, UUID, account number, token or slug; and a missing object-level authorisation check that lets a user reach an object they should not be able to.
In OWASP's API list, the object-level form is API1:2023, Broken Object Level Authorization, the first entry in the OWASP Top 10 API Security Risks 2023. Its neighbour, API5:2023 Broken Function Level Authorization, is about reaching a function rather than a record, and OWASP's API1 page draws the line between them: an attacker who reaches an endpoint or function they should not have access to is a case of BFLA rather than BOLA.
Horizontal and vertical access, and the tenant boundary
Access control failures are described by direction.
WSTG v4.2's privilege escalation test, WSTG-ATHZ-03, says people usually refer to vertical escalation when someone reaches resources granted to more privileged accounts, such as administrative privileges for the application, and to horizontal escalation when they reach resources granted to a similarly configured account, such as information about a different user in an online banking application.
Horizontal is the IDOR case: the same role, someone else's record. Vertical is privilege escalation in a web application: a function above the caller's role, such as approving, refunding, inviting users or changing roles. The two are independent. In the lab on this page, member a1 owns claim a1-claim-1 and may read and edit it, yet approving it is still a vertical failure, because approval belongs to the administrator. Owning a record does not grant every action on it.
Multi-tenant applications add a boundary of their own. When several customer businesses share one database, a member of one tenant reaching another tenant's records is horizontal in form and larger in effect: OWASP's Multi-Tenant Application Security Cheat Sheet notes that a single vulnerability can expose all tenants' data.
It lists cross-tenant data leakage, IDOR through manipulated tenant or resource IDs, and privilege escalation across tenants through admin functions among its key risks.
ASVS 5.0 requirement 8.4.1, at Level 2, asks multi-tenant applications to use cross-tenant controls so that a consumer's operations cannot affect tenants they have no permission to interact with.
Inside one tenant, a colleague is not automatically entitled to your records either. Whether they are depends on the application's rules. In the lab's expense app, members see only their own claims and the administrator sees every claim in the tenant; in a household budgeting app, family members might be meant to share.
Write the rule down before you test it. ASVS 5.0 requirement 8.1.1, at Level 1, asks for authorisation documentation that defines rules for restricting function-level and data-specific access based on consumer permissions and resource attributes.
A role check on its own does not settle horizontal access. MITRE's guidance for CWE-862 notes that role-based access control may not protect against horizontal authorisation, since it will not stop a user attacking others with the same role. OWASP's Authorization Cheat Sheet says role-based models do a poor job of object-level or horizontal decisions, and prefers attribute-based and relationship-based rules for application development.
Why signing in is not the same as being allowed
Authentication answers who is asking.
Authorisation answers whether they may. OWASP's Authorization Cheat Sheet keeps the two apart and puts the practical consequence plainly: a user who has been authenticated is often not authorised to access every resource and perform every action that is technically possible through a system. MITRE's entry for CWE-284 lists authentication, authorisation and accountability as separate protection mechanisms within access control.
The two get confused in code because a sign-in guard can be added to a whole group of routes at once, while a record check depends on each route's data. A route behind a "must be signed in" guard looks protected, and against a signed-out visitor it is.
The lab's flawed API shows the gap. Every route turns away a request with no session with a 401, so the signed-out row matches the expected result in all seven columns.
Every leak in the matrix comes from an account that is signed in: a member reading a colleague's claim, a member of another business reading a receipt, and each ordinary account approving a claim.
Next.js builds the distinction into its own audit checklist. Its data security guide asks, of each "use server" file, whether the user is re-authorised inside the action and whether the action checks ownership of the resource, which the guide labels as authorisation rather than authentication alone.
One tempting half-fix compares the id in the request with the signed-in user's id. OWASP's API1:2023 page says comparing the user ID of the current session with the vulnerable ID parameter is not a sufficient solution, and could address only a small subset of cases.
The limit is structural: a session-id comparison can only protect a route where the record is the user, such as /users/123. An invoice, a receipt or a job has an id of its own, and it is not a user id.
Sign-in flaws themselves, such as account enumeration, password reset and session handling, belong to the authentication failures guide in this library, and checking a token's signature and claims belongs to the JWT security guide. This page starts at the point where the server already knows, correctly, who is asking.
Why an unguessable identifier is not an access check
Switching from sequential numbers to UUIDs or other long random identifiers makes guessing harder, and that is worth having.
It is not an access check. OWASP's IDOR Prevention Cheat Sheet says that in some cases, complex identifiers such as GUIDs can make it practically impossible for attackers to guess valid values, but that even with them, access control checks are essential: if attackers obtain URLs for unauthorised objects, the application should still block their access attempts. The cheat sheet treats random identifiers as an additional defence-in-depth measure.
OWASP's API1:2023 page recommends random and unpredictable values as GUIDs for records' IDs, and in the same entry notes that object IDs can be anything from sequential integers to UUIDs or generic strings, and that whatever their type they are easy to identify in the request path, query string, headers or payload.
The Multi-Tenant Application Security Cheat Sheet puts it in one line: opaque, random identifiers can reduce enumeration, but they are not authorisation controls.
Identifiers travel. A random id can sit in the address bar, in a link a customer forwards, in an exported spreadsheet, in a support ticket, in browser history and in the responses the application itself sends. An export job can hand its id back to the person who started it, and from then on that id is a string anyone holding it can paste into a request.
The question the server has to answer is not whether the caller could have guessed the id, but whether the record it names is theirs.
Next.js applies the same thinking to its own Server Actions. Its data security guide says it creates encrypted, non-deterministic IDs for them, recalculated periodically between builds, and that this reduces the risk where an authentication layer is missing. It then says to treat Server Actions as reachable by direct POST requests regardless, and to verify authentication and authorisation inside each one.
Where the check goes missing in real applications
The route behind the main screen is the one a team tests simply by using the product.
The gaps sit on the other ways into the same data. Each one below is a column in the matrix, with the lab's version of the flaw beside it.
WSTG-ATHZ-04, the WSTG v4.2 test for insecure direct object references, starts by mapping every place where user input is used to reference objects directly, such as a database row, a file or an application page. The identifier is not always a number in the path.
OWASP's IDOR Prevention Cheat Sheet shows one in a hidden form field in a POST body and a filename acting as the object reference, and CWE-639 adds URL parameters and unencrypted cookie variables.
Reads are the obvious case; changes are where records get damaged. OWASP's A01 lists an accessible API with missing access controls for POST, PUT and DELETE among its common access control vulnerabilities. The lab's flawed change route shows a quieter version: it checks that the claim belongs to the caller's tenant but not that the caller owns it, so a colleague can rewrite another member's claim (column C2). That is the CWE-863 shape, a check that runs but checks the wrong thing.
A route such as /claims/:claimId/receipts/:receiptId carries two identifiers, and WSTG-ATHZ-04 notes that an object reference may be split between more than one parameter, with testing adjusted to match. The flaw to look for is a check on the first identifier only. The lab's flawed receipt route checks that the caller may see the claim in the path, then looks the receipt up by its own id alone, so any member can read a1's receipt by naming one of their own claims as the parent (column C3). The check that ran is correct; it was aimed at the wrong record.
The fix looks the child up inside the parent: the receipt has to belong to the claim named in the path, or the answer is 404. OWASP's IDOR Prevention Cheat Sheet makes the same move for single records, recommending lookups through the datasets the user has access to, such as the current user's projects, rather than through the whole table.
A list route answers with many records at once, so a missing filter leaks in bulk. The lab's flaw is a filter the screen sends: the claims list accepts an ownerId so the page can show "my claims", and the flawed version trusts it, so a member of either business who sends ownerId=a1 gets a1's claims (column C4).
CWE-639 names search screens as a place to look for exactly this, a lookup key the user controls. The fixed version starts from the records the caller may read and lets ownerId narrow that set, and only narrow it.
OWASP's Authorization Decisions and Output Handling Cheat Sheet states the rule for every collection: enforce the restriction on list, search, export, count, aggregate and direct-object reads, and do not treat an authorised list as permission for a later update or delete.
An export route has a query of its own, so the filter that protects the list screen does not come with it. The lab's flawed export takes a tenantId from the request and returns that tenant's claims as a CSV file.
That leaks across tenants for b1, and it leaks inside the tenant as well: a1 and a2, both ordinary members, each receive every claim in their business, the administrator's included (column C5). OWASP's IDOR Prevention Cheat Sheet lists export alongside read, create, update, delete and administrative actions among the operations its two-user verification should cover, and the Multi-Tenant Application Security Cheat Sheet says a client-supplied tenant identifier is a selector, to be checked against the caller's membership, not proof of it.
Reporting layers can carry the same gap into the database. Supabase's row level security documentation warns that views bypass row level security by default, because they are usually created with the postgres user, so a view over a protected table hands out every row its policies were meant to withhold.
A background job has two places to lose the check. The first is the status and result route. A job id is an identifier like any other, and the lab's flawed job route hands a1's finished export, with the claim ids in its result, to anyone signed in (column C6).
The second is the worker itself, which runs after the request has gone and can hold broader database access than any user. The lab covers the first. The second needs a test that starts a job as one account and checks that the result holds only that account's records.
The worker has to apply the requester's scope itself. OWASP's Multi-Tenant Application Security Cheat Sheet says that for tenant-scoped asynchronous work, tenant context should come from the authenticated producer, and that the consumer should re-establish tenant context and authorise the operation and its target resource, rather than treating a tenant identifier in a queued message as authorisation proof.
ASVS 5.0 requirement 8.3.3, at Level 3, asks that access to an object is based on the originating subject's permissions, not on those of an intermediary or service acting on their behalf.
On Supabase, a server-side job that uses a secret key works through the service_role role and bypasses row level security when the request carries no user access token, so the job's own code has to do the scoping the policies would otherwise do.
An administrative function reached from an ordinary account is the vertical case. OWASP's A01 describes an application that puts all of its access control in the front end, which an attacker gets around by requesting the admin page directly.
WSTG-ATHZ-02 notes that developers sometimes validate authorisation at the GUI level only and leave the functions themselves unchecked, and OWASP's API5:2023 warns against deciding whether an endpoint is regular or administrative from its URL path alone.
In the lab, the flawed approve route relies on the Approve button only appearing for administrators, so all three ordinary accounts approve a1's claim, a1 included (column C7).
In a Next.js application, every Server Action and route handler is a door of its own. The Next.js data security guide says that by default, a Server Action that is created and exported is reachable by a direct POST request, not only through the application's interface, and that a page-level authentication check does not extend to the Server Actions defined within the page.
Its authentication guide says to treat Server Actions and Route Handlers with the same security considerations as public-facing API endpoints, and that Proxy should not be the only line of defence, with the majority of security checks performed as close as possible to the data source.
Supabase's documentation describes row level security as granular authorisation rules that run inside the database, and pairs it with Supabase Auth for end-to-end user security from the browser to the database. It describes two checks before a client touches a table: grants decide whether a role can run an operation on the table at all, and policies decide which rows that operation applies to.
It says to enable row level security on every table in an exposed schema. Writing and testing those policies across tables, views, storage and database functions is the work of the Supabase guide in this library.
For this page, the point is that the matrix applies unchanged, because a policy is the same check living in the database.
Put the check on the server, next to the data, in one place
On the server.
OWASP's A01 says access control is only effective in trusted server-side code or serverless APIs, where the attacker cannot modify the check or its metadata. ASVS 5.0 requirement 8.3.1, at Level 1, asks that authorisation rules are enforced at a trusted service layer and do not rely on controls an untrusted consumer could manipulate, such as client-side JavaScript.
Hiding a button is good interface design and is not access control. OWASP's Authorization Decisions and Output Handling Cheat Sheet says UI checks can decide which buttons to display, but the operation itself still requires server-side authorisation.
Next to the data. The check needs to know who owns the record, so it belongs where the record is loaded. OWASP's IDOR Prevention Cheat Sheet recommends working out the current user from session information and looking records up through the datasets that user can access, and the Next.js authentication guide recommends a Data Access Layer that centralises data requests and authorisation logic.
A check made earlier, in middleware that has only seen the URL, cannot know whose receipt a receipt id points to.
In one place. OWASP's A01 asks for access control mechanisms to be implemented once and reused throughout the application, with deny by default for everything except public resources, and model access controls that enforce record ownership. OWASP's API5:2023 asks for a consistent, easy-to-analyse authorisation module invoked from all business functions, and the Authorization Cheat Sheet wants permission validated on every request, by technology that allows global, application-wide configuration rather than a check applied to every method or class one at a time.
The lab's fixed API is built that way. One policy object holds four rules, each answering a single question, such as whether this user may approve this claim. One function, decide, applies them in order: a record the caller may not read gets the same 404 as a record that does not exist, and a record they may read but not act on gets a 403.
Lists and the export start from readableClaims, the set the caller may read, so a request parameter can narrow the result but cannot widen it.
Every route goes through one of those two functions, and the receipt route adds one more condition, that the receipt belongs to the claim in the path.
The rules are relationships between the user, the record and the tenant, plus the role, which is the attribute- and relationship-based style the Authorization Cheat Sheet prefers. When a rule changes, it changes in one place.
Keep a second layer where the platform offers one. Supabase describes row level security as defence in depth, because as a Postgres feature it also protects data reached through third-party tooling. A policy in the database and a check in the application make the same decision twice, so on a path where both apply, a gap has to exist in both before data leaks.
404 or 403: what each response gives away
A refusal still says something.
RFC 9110, the HTTP semantics standard, defines 403 Forbidden as the server understanding the request and refusing to fulfil it, and allows an origin server that wishes to hide the current existence of a forbidden resource to respond with 404 Not Found instead.
Its definition of 404 covers both cases: the origin server did not find a current representation for the target resource, or it is not willing to disclose that one exists.
The difference matters for records. If the server answers 403 for a record that exists and 404 for one that does not, the status alone tells an outsider which identifiers are real. With sequential ids that turns into a list of every record in the system; with random ones it still confirms that a leaked or shared link points at something live.
OWASP's IDOR Prevention Cheat Sheet notes that a check made after loading the record can tell a missing object from one the caller may not access, and says that where the resource's existence is sensitive, the scoped lookup should map both cases to the same public response, such as a 404.
The lab uses a simple rule. If the caller may not read the record, the answer is the same 404, with the same body, as for a record that does not exist. If the caller may read it but not perform the action, the answer is 403, because it reveals nothing they could not already see.
In the matrix output, a1 gets 403 for approving their own claim, and the administrator gets 403 for editing a member's claim.
For a regression test, either refusal is evidence the leak is closed. OWASP's Authorization Regression Testing Cheat Sheet asserts a 403 or a 404 for its multi-user replay, never a 200 OK. What matters is consistency: compare the body and headers of the refusal for a record that exists with those for one that does not, because a different error message gives away the same thing a different status code would.
Running the matrix on your own application
The matrix on this page is built for an application you own, or one you are authorised in writing to test, using test accounts and test records.
Changing an identifier in a request to a system you do not own, without written authority from its owner, is not something this page helps with.
It follows the method in WSTG v4.2. WSTG-ATHZ-04 says the best way to test for direct object references is with at least two users who own different objects and, where relevant, users with different privileges such as administrators. WSTG-ATHZ-02 keeps a session open for each user, swaps the session identifier and the relevant parameters between them on every request, and treats the application as vulnerable if the responses are the same, contain the same private data or indicate a successful operation on the other user's data.
- Seed two tenants. In tenant A, create the owner account (A1), a second ordinary account (A2) and an administrator. In tenant B, create one ordinary account (B1). Give A1 a record of every kind the matrix touches: a record, a child record under it, something to export and a finished background job.
- Write the expected result for every cell before you send anything, from your own rules. The lab's expected results are a starting point. Change any cell your application decides differently, such as records a household is meant to share.
- Send each request as each account, changing only the session. In the nested column, name a parent the caller owns and the child that belongs to A1.
- Where a route accepts more than one method, try the others as well. OWASP's API5:2023 includes swapping the HTTP method, such as GET for DELETE, among its questions.
- Restore the records between cells that change data, so one cell's change does not alter the next, and run changes and administrator actions only against test records.
- Keep the evidence the matrix lists for every cell, including the cells that pass. A recorded refusal is what lets you answer later whether a route was checked.
- If administrators belong to a single tenant, add a row for tenant B's administrator. An administrator check that forgets the tenant fails only in that row.
The lab: one API in a flawed and a fixed version
The lab is an illustration: an invented expense app shared by two invented businesses, a bakery and a plumbing firm, with four users, five claims, four receipts and two finished export jobs.
It is five files that use only modules shipped with Node.js, so there is nothing to install. data.mjs holds the records and issues each user a random session token, sent back in a cookie. api.mjs serves the same seven routes in two versions. matrix.mjs holds the matrix as data and walks it. run-matrix.mjs prints every cell, and access.test.mjs is the regression test.
The server listens on 127.0.0.1 and asks for port 0. The Node.js documentation says a port of 0 makes the operating system assign an arbitrary unused port, and that a server given no host accepts connections on the unspecified address, which is why the lab names 127.0.0.1 explicitly.
It was written and run on Node.js 26.0.0, and every output in the asset comes from that run; test timings will differ on your machine.
Against the flawed version, 17 of the 35 cells do not match the expected result, and every column has at least one mismatch. Against the fixed version, all 35 match. The regression test fails all seven columns on the flawed version and passes all seven on the fixed one.
Turning the matrix into a regression test
A matrix run once tells you about one build.
Run in the pipeline, it tells you whether the next change broke something. OWASP's A01 asks developers and QA staff to include functional access control in their unit and integration tests, and OWASP's API1:2023 says to write tests that evaluate the authorisation mechanism and not to deploy changes that make those tests fail.
OWASP's Authorization Regression Testing Cheat Sheet describes the shape the lab follows: the matrix kept as data a test runner can read, rather than in a spreadsheet; a multi-user replay for horizontal access; a role demotion check that sends administrator requests from every lower role, signed-out included; and a cross-tenant boundary test, where it says even a single leaked record identifier constitutes a critical failure.
It also says the suite must be a required check, so a pull request cannot merge while an authorisation test fails.
The lab's access.test.mjs is that idea at its smallest. It walks the whole matrix, runs one test per column, and fails with the list of cells that differ. Run with node --test, Node.js finds it by its .test.mjs name, and a failing test sets the process exit code to 1, which is what stops a pipeline.
A passing suite speaks for the cases it contains. OWASP's Authorization Cheat Sheet says automated unit and integration tests of access control logic can help reduce the number of security flaws that make it into production, and are not a substitute for a dedicated security test or penetration test.
If other customers' records were reachable
A failing cell on a build that matches production means real customers' records were reachable there too, and the finding is about the past as well as the present: the route was open before you found it.
Work through these in order.
- Keep the evidence. Save the test's request and response, and copy the access logs for the affected routes before you deploy anything, in case your hosting keeps logs only for a limited window or per deployment.
- Close the gap. Deploy the fix, add the failing cell to the regression test, and run the matrix again on the deployed build for that route.
- Answer the question from the logs, not by opening more records. Look for requests to the affected route where the account in the session and the identifier in the path or parameters belong to different customers, and note which records and accounts were involved. Opening more real customers' records to measure the problem adds to it.
- Bring in whoever handles privacy for your business early, and check what any cyber insurance policy asks you to do and when, before taking steps it may have wanted to hear about first.
- Under the Notifiable Data Breaches scheme, the OAIC explains that an organisation or agency covered by the Privacy Act 1988 must notify affected individuals and the OAIC when a data breach is likely to result in serious harm to a person whose personal information is involved. Whether that applies to your finding is a question for your privacy adviser, not for this page.
- Watch for the next attempt. OWASP's A01 recommends logging access control failures and alerting administrators when appropriate, such as after repeated failures. Once the fix is live, a run of 404s to one signed-in account asking for other people's records is that signal.
What this guide leaves to other guides
Broken access control sits beside several neighbouring topics, and each has a guide of its own in this library:
- Authentication failures: sign-up, sign-in, recovery, email change and re-authentication, where the question is whether the server knows who is asking.
- JWT security: how a token's signature, algorithm, issuer, audience and expiry are checked before any claim inside it is trusted.
- API security: the wider API surface, including the endpoint register, field-level writes, alternate HTTP methods, pagination and rate limits.
- Supabase: writing and testing row level security policies across tables, views, storage and database functions.
- Business logic vulnerabilities: rules about order and limits, such as skipped steps, replayed approvals and changed limits, where the caller may touch the record but not in that way.
Where an outside security test fits
Your own matrix covers the routes you know about.
For a Clever Ops web application and API penetration test, the scope asks for two test accounts in each role, and accounts in two separate customer organisations if your application serves more than one, so access can be tried in both directions between users and between tenants. Every route that names a record by id is sent again from a second account that does not own the record, and requests only an administrator should be able to make are sent from a lower role's session and with no session (WSTG-ATHZ-02, WSTG-ATHZ-04; ASVS 5.0 requirements 8.2.1 and 8.2.2).
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.
A report is evidence for your decisions, not a certificate. If a tender or contract requires a CREST-accredited provider, Clever Ops is not CREST accredited, so we refer that work to a provider that is. 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 an application letting a user read, change or do something its own rules say they may not, such as opening another customer's invoice or reaching an administrator function. It is A01 in the OWASP Top 10:2025. MITRE catalogues it as CWE-284, Improper Access Control, with missing checks (CWE-862), incorrect checks (CWE-863) and user-controlled keys (CWE-639) as more specific forms.
An insecure direct object reference is a route that takes an identifier from the request, such as an invoice number, and returns or changes that record without checking the caller may have it. OWASP's IDOR Prevention Cheat Sheet names three ingredients: an object, a reference to it, and a missing object-level authorisation check. MITRE's CWE-639 lists IDOR and Broken Object Level Authorization (BOLA) among its alternate terms, while noting that OWASP's IDOR term is broader than CWE-639 and that BOLA appears to have some overlap with it but may apply to other weaknesses too. API1:2023 is OWASP's name for the object-level form in APIs.
They make identifiers harder to guess, which OWASP treats as defence in depth. They do not stop someone who obtains a real identifier from a link, an export or a response. OWASP's IDOR Prevention Cheat Sheet says access control checks are essential even with complex identifiers.
Horizontal escalation reaches resources belonging to a similarly configured account, such as another customer's records. Vertical escalation reaches resources or functions granted to a more privileged account, such as an administrator's. WSTG v4.2 tests both, and an application can fail one while passing the other.
If the caller is not allowed to know the record exists, return the same 404 you return for a missing record: RFC 9110 allows an origin server to hide a forbidden resource that way, and OWASP's IDOR Prevention Cheat Sheet suggests it where existence is sensitive. A 403 suits a record the caller can already see but may not act on. Keep the response body the same as well as the status.
On an application you own or are authorised in writing to test, create two ordinary accounts in one tenant, one in a second tenant and an administrator, give one account test records of each kind, and send every object route as every account. Compare each answer with the result your rules expect. The matrix and lab on this page give the cells, the expected results and the evidence to keep.
No. Signing in establishes who is asking. It does not decide which records that person may read or change. In the lab on this page, every flawed route turns away signed-out requests, and 17 of the 35 cells in the matrix still break the expense app's rules.
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.