Security and hardening · Intermediate · 26 min
Fix broken access control and insecure direct object references in an Express app
By Padding · Updated 18 Nov 2026
node:26 image (Debian) · Node.js 26.13.1 · Express 5.3.0
You will prove with failing tests that one Noticeboard user can read and edit another user's draft and pose as an admin, then fix both with deny-by-default middleware, ownership checks in the query and server-side roles, and finish with a test that checks every route for every role.
On this page
Broken access control sits at the top of the OWASP Top 10:2025 as A01. It covers every case where an app lets a user do something the rules say they should not: read another person's record, change it, or reach an admin page. Most of these flaws are not clever. The code checks that you are signed in, then trusts whatever ID or role arrives with the request.
The best-known form is the insecure direct object reference, or IDOR. A URL such as /api/posts/3 names a record directly, and the server returns record 3 to anyone who asks, without checking whose it is. Change the 3 to a 4 and you are reading someone else's data.
In this part of the series you work on a cut-down JSON API version of Noticeboard, the practice app from part 1. It runs only on 127.0.0.1, on your own machine. Members sign in, write drafts that only they should see, and publish posts that everyone can read. You will write tests that prove two flaws, then fix them in four moves: one middleware that denies by default, ownership checks inside the SQL, roles read from the database rather than from the request, and random public IDs as an extra layer. The last step adds a matrix test that runs every route as every kind of user, so a new route cannot quietly skip the rules.
Practise only on your own copy of the app. Never point these checks at a system you do not own or have written permission to test.
Step 1 · Build the Noticeboard API for this part
Part 1's Noticeboard serves HTML pages with cookie sessions. Access control is easier to see in a smaller app, so this part uses a cut-down JSON API version with the same idea and the same flaws: members amara and bola, an admin called chen, drafts and published posts, and a role the server takes from the request. Part 1 keeps the role in a cookie the browser can change; here it arrives in an X-User-Role header, which is the same mistake in a form that is easy to send from a test. Work in a new folder inside the demo, ~/noticeboard-demo/api, so part 1's app in ~/noticeboard-demo stays as it is for the later parts. Part 5 adds its link preview to this folder, and part 8's clean-up removes it with the rest of ~/noticeboard-demo. If part 1's app is still running on port 3000, stop it with Ctrl+C first.
mkdir -p ~/noticeboard-demo/api/test/security
cd ~/noticeboard-demo/apiCreate package.json and install Express 5.3. The ~5.3.0 range allows patch releases of 5.3 only. The two scripts run the whole suite and the security tests on their own:
cat > package.json <<'JSON'
{
"name": "noticeboard-api",
"version": "1.0.0",
"private": true,
"type": "module",
"scripts": {
"start": "node --env-file=.env server.js",
"test": "node --test \"test/**/*.test.js\"",
"test:security": "node --test \"test/security/*.test.js\""
}
}
JSON
npm install express@~5.3.0The database lives in memory and is rebuilt with demo data on every start, so each run begins from the same state. The demo users share one sign-in password, read from the NOTICEBOARD_DEMO_PASSWORD environment variable rather than written in the code. Passwords are stored in plain text here, which is one of the app's known flaws, left for later in the series. Create db.js:
cat > db.js <<'JS'
import { DatabaseSync } from 'node:sqlite'
export function openDb() {
const password = process.env.NOTICEBOARD_DEMO_PASSWORD
if (!password) throw new Error('Set NOTICEBOARD_DEMO_PASSWORD (it lives in .env)')
const db = new DatabaseSync(':memory:')
db.exec(`
CREATE TABLE users (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL UNIQUE,
password TEXT NOT NULL,
role TEXT NOT NULL DEFAULT 'member' CHECK (role IN ('member', 'admin'))
);
CREATE TABLE posts (
id INTEGER PRIMARY KEY,
owner_id INTEGER NOT NULL REFERENCES users(id),
title TEXT NOT NULL,
body TEXT NOT NULL,
status TEXT NOT NULL CHECK (status IN ('draft', 'published'))
);
`)
const addUser = db.prepare('INSERT INTO users (name, password, role) VALUES (?, ?, ?)')
addUser.run('amara', password, 'member')
addUser.run('bola', password, 'member')
addUser.run('chen', password, 'admin')
const addPost = db.prepare('INSERT INTO posts (owner_id, title, body, status) VALUES (?, ?, ?, ?)')
addPost.run(1, 'Market day moves to Saturday', 'Stalls open at 8am this week.', 'published')
addPost.run(1, 'Committee minutes', 'Notes not ready to share yet.', 'draft')
return db
}
JSNow the app itself. Read the comments marked FLAW: they are what this part fixes. Create app.js:
cat > app.js <<'JS'
import express from 'express'
import { randomBytes } from 'node:crypto'
function readPost(body) {
const title = typeof body?.title === 'string' ? body.title.trim() : ''
const text = typeof body?.body === 'string' ? body.body.trim() : ''
if (title.length < 1 || title.length > 120 || text.length < 1 || text.length > 5000) return null
return { title, body: text }
}
export function createApp(db) {
const app = express()
app.disable('x-powered-by')
app.use(express.json({ limit: '10kb' }))
const sessions = new Map()
const findUserById = db.prepare('SELECT id, name, role FROM users WHERE id = ?')
const findUserByName = db.prepare('SELECT id, password FROM users WHERE name = ?')
const findPost = db.prepare('SELECT id, owner_id, title, body, status FROM posts WHERE id = ?')
function currentUser(req) {
const header = req.get('authorization') ?? ''
const token = header.startsWith('Bearer ') ? header.slice(7) : ''
const userId = sessions.get(token)
return userId ? findUserById.get(userId) ?? null : null
}
app.post('/api/sign-in', (req, res) => {
const user = findUserByName.get(String(req.body?.name ?? ''))
if (!user || user.password !== req.body?.password) {
return res.status(401).json({ error: 'Wrong name or password' })
}
const token = randomBytes(24).toString('base64url')
sessions.set(token, user.id)
res.json({ token })
})
app.get('/api/posts', (req, res) => {
res.json(db.prepare("SELECT id, title, body FROM posts WHERE status = 'published' ORDER BY id").all())
})
app.post('/api/posts', (req, res) => {
const user = currentUser(req)
if (!user) return res.status(401).json({ error: 'Sign in first' })
const input = readPost(req.body)
if (!input) return res.status(422).json({ error: 'title and body are required' })
const result = db
.prepare("INSERT INTO posts (owner_id, title, body, status) VALUES (?, ?, ?, 'draft')")
.run(user.id, input.title, input.body)
res.status(201).json({ id: Number(result.lastInsertRowid), ...input, status: 'draft' })
})
// FLAW: no sign-in check and no owner check. Any ID returns any post, drafts included.
app.get('/api/posts/:id', (req, res) => {
const post = findPost.get(req.params.id)
if (!post) return res.status(404).json({ error: 'Post not found' })
res.json(post)
})
// FLAW: checks that someone is signed in, not that they own the post.
app.put('/api/posts/:id', (req, res) => {
if (!currentUser(req)) return res.status(401).json({ error: 'Sign in first' })
const post = findPost.get(req.params.id)
if (!post) return res.status(404).json({ error: 'Post not found' })
const input = readPost(req.body)
if (!input) return res.status(422).json({ error: 'title and body are required' })
db.prepare('UPDATE posts SET title = ?, body = ? WHERE id = ?').run(input.title, input.body, post.id)
res.json(findPost.get(post.id))
})
// FLAW: trusts a role header that the caller chooses.
app.get('/api/admin/users', (req, res) => {
if (req.get('x-user-role') !== 'admin') return res.status(403).json({ error: 'Admins only' })
res.json(db.prepare('SELECT id, name, role FROM users ORDER BY id').all())
})
app.use((req, res) => res.status(404).json({ error: 'Not found' }))
app.use((err, req, res, next) => {
const status = err.status >= 400 && err.status < 500 ? err.status : 500
if (status === 500) console.error(err)
res.status(status).json({ error: status === 500 ? 'Something went wrong' : 'Bad request' })
})
return app
}
JSserver.js starts the app on 127.0.0.1 only, so nothing on your network can reach it:
cat > server.js <<'JS'
import { openDb } from './db.js'
import { createApp } from './app.js'
const port = Number(process.env.PORT ?? 3000)
createApp(openDb()).listen(port, '127.0.0.1', (err) => {
if (err) throw err
console.log(`Noticeboard on http://127.0.0.1:${port}`)
})
JSThe tests share a small helper. It starts the app on a free port, signs users in, and sets a random demo password for the run if none is set, so no password is written in a test file. Create test/helpers.js and two baseline tests in test/app.test.js:
cat > test/helpers.js <<'JS'
import { randomUUID } from 'node:crypto'
import { openDb } from '../db.js'
import { createApp } from '../app.js'
process.env.NOTICEBOARD_DEMO_PASSWORD ??= randomUUID()
export async function startApp() {
const app = createApp(openDb())
const server = await new Promise((resolve) => {
const s = app.listen(0, '127.0.0.1', () => resolve(s))
})
return {
base: `http://127.0.0.1:${server.address().port}`,
close: () => new Promise((resolve) => server.close(resolve)),
}
}
export async function signIn(base, name) {
const res = await fetch(`${base}/api/sign-in`, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ name, password: process.env.NOTICEBOARD_DEMO_PASSWORD }),
})
if (res.status !== 200) throw new Error(`sign-in for ${name} returned ${res.status}`)
const { token } = await res.json()
return { authorization: `Bearer ${token}` }
}
export async function createDraft(base, headers, title, body) {
const res = await fetch(`${base}/api/posts`, {
method: 'POST',
headers: { ...headers, 'content-type': 'application/json' },
body: JSON.stringify({ title, body }),
})
if (res.status !== 201) throw new Error(`creating a draft returned ${res.status}`)
return (await res.json()).id
}
JS
cat > test/app.test.js <<'JS'
import { test, before, after } from 'node:test'
import assert from 'node:assert/strict'
import { startApp } from './helpers.js'
let app
before(async () => { app = await startApp() })
after(() => app.close())
test('sign-in rejects a wrong password', async () => {
const res = await fetch(`${app.base}/api/sign-in`, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ name: 'amara', password: 'not-the-password' }),
})
assert.equal(res.status, 401)
})
test('the public list shows published posts only', async () => {
const res = await fetch(`${app.base}/api/posts`)
assert.equal(res.status, 200)
const titles = (await res.json()).map((p) => p.title)
assert.deepEqual(titles, ['Market day moves to Saturday'])
})
JSFinally, create .env with a random demo password. The subshell sets umask 077 first, so the file is private from the moment it exists. If .env already holds the variable, the line is left alone; otherwise it is added:
(umask 077; touch .env)
grep -q '^NOTICEBOARD_DEMO_PASSWORD=' .env || node -e "console.log('NOTICEBOARD_DEMO_PASSWORD=' + crypto.randomUUID())" >> .env
ls -l .envCheck it worked
Run the baseline tests:
npm testBoth tests pass, and the summary shows pass 2 and fail 0. Then start the app in a second terminal:
cd ~/noticeboard-demo/api
npm startIt prints Noticeboard on http://127.0.0.1:3000. Back in the first terminal, ask for the public list:
curl -s http://127.0.0.1:3000/api/postsYou see one post, Market day moves to Saturday, as JSON. The draft is not in the list. Stop the server with Ctrl+C; the rest of this part works through tests.
Step 2 · Write tests that prove the flaws
A security fix starts with a test that fails for the right reason. Write down what the rules say, run it against the app as it is, and watch it fail. When the fix lands, the same test passes and stays in the suite, so the flaw cannot come back unnoticed.
Noticeboard's rules are short. A draft is visible only to its owner. Only the owner can edit it. Only an admin can list users, and being an admin is decided by the server. Create test/security/access-control.test.js. Each draft body carries a harmless marker string, so a test can tell whether private text leaked into a response:
cat > test/security/access-control.test.js <<'JS'
import { test, before, after } from 'node:test'
import assert from 'node:assert/strict'
import { startApp, signIn, createDraft } from '../helpers.js'
let app, amara, bola, chen, draftId
before(async () => {
app = await startApp()
amara = await signIn(app.base, 'amara')
bola = await signIn(app.base, 'bola')
chen = await signIn(app.base, 'chen')
draftId = await createDraft(app.base, bola, 'Bola draft', 'MARKER-bola-private-draft')
})
after(() => app.close())
const json = { 'content-type': 'application/json' }
test('A01: a signed-out visitor cannot read a draft', async () => {
const res = await fetch(`${app.base}/api/posts/${draftId}`)
assert.ok([401, 404].includes(res.status), `got ${res.status}`)
assert.doesNotMatch(await res.text(), /MARKER-bola/)
})
test('A01: another member cannot read a draft by changing the ID', async () => {
const res = await fetch(`${app.base}/api/posts/${draftId}`, { headers: amara })
assert.equal(res.status, 404)
assert.doesNotMatch(await res.text(), /MARKER-bola/)
})
test('A01: another member cannot edit a draft', async () => {
const res = await fetch(`${app.base}/api/posts/${draftId}`, {
method: 'PUT',
headers: { ...amara, ...json },
body: JSON.stringify({ title: 'Changed by amara', body: 'MARKER-overwritten' }),
})
assert.equal(res.status, 404)
const check = await fetch(`${app.base}/api/posts/${draftId}`, { headers: bola })
assert.equal((await check.json()).title, 'Bola draft')
})
test('A01: the owner can still read and edit their draft', async () => {
const mine = await createDraft(app.base, bola, 'Second draft', 'MARKER-bola-second')
const edit = await fetch(`${app.base}/api/posts/${mine}`, {
method: 'PUT',
headers: { ...bola, ...json },
body: JSON.stringify({ title: 'Second draft, edited', body: 'MARKER-bola-second' }),
})
assert.equal(edit.status, 200)
const read = await fetch(`${app.base}/api/posts/${mine}`, { headers: bola })
assert.equal((await read.json()).title, 'Second draft, edited')
})
test('A01: a member cannot become an admin by sending a role header', async () => {
const res = await fetch(`${app.base}/api/admin/users`, { headers: { ...amara, 'x-user-role': 'admin' } })
assert.equal(res.status, 403)
})
test('A01: a real admin can list users without sending any role', async () => {
const res = await fetch(`${app.base}/api/admin/users`, { headers: chen })
assert.equal(res.status, 200)
assert.deepEqual((await res.json()).map((u) => u.name), ['amara', 'bola', 'chen'])
})
JSThe fourth test is a control: it passes now and must keep passing, so a "fix" that locks everyone out is caught too. The last test fails today for a telling reason. The app never looks at who chen is; it only reads the header.
Run the security tests:
npm run test:securityCheck it worked
Five tests fail and one passes; the summary ends with something like pass 1 and fail 5. Read the failures. The read test reports 200 !== 404, so amara got bola's draft by putting its ID in the URL. The edit test reports 200 !== 404, so amara's PUT to bola's draft succeeded. The role test reports 200 !== 403. If a different test fails, or the owner test fails, fix that before you go on, because the rest of this part relies on these exact failures.
Step 3 · Deny by default with one authorisation middleware
The vulnerable app decides access route by route. One route checks for a user, the next forgets. A new route is open until someone remembers to close it. Turn that around: one middleware runs before every route and refuses any request from a signed-out caller, except for a short, written-down list of public routes.
Put the sign-in logic and the middleware in auth.js. authenticate works out who is calling from the token and loads that user, role included, from the database. denyByDefault lets a request through only if it is on the public list or comes from a signed-in user. requireRole is used in a later step.
cat > auth.js <<'JS'
import { randomBytes } from 'node:crypto'
// Everything not listed here needs a signed-in user. Add to this list on purpose, never by accident.
const PUBLIC_ROUTES = [
['POST', '/api/sign-in'],
['GET', '/api/posts'],
]
export function createAuth(db) {
const sessions = new Map()
const findUserById = db.prepare('SELECT id, name, role FROM users WHERE id = ?')
const findUserByName = db.prepare('SELECT id, password FROM users WHERE name = ?')
function signIn(req, res) {
const user = findUserByName.get(String(req.body?.name ?? ''))
if (!user || user.password !== req.body?.password) {
return res.status(401).json({ error: 'Wrong name or password' })
}
const token = randomBytes(24).toString('base64url')
sessions.set(token, user.id)
res.json({ token })
}
// Sets req.user from the session token. The role comes from the users table, never from the request.
function authenticate(req, res, next) {
const header = req.get('authorization') ?? ''
const token = header.startsWith('Bearer ') ? header.slice(7) : ''
const userId = sessions.get(token)
req.user = userId ? findUserById.get(userId) ?? null : null
next()
}
return { signIn, authenticate }
}
export function denyByDefault(req, res, next) {
const isPublic = PUBLIC_ROUTES.some(([method, path]) => req.method === method && req.path === path)
if (isPublic || req.user) return next()
res.status(401).json({ error: 'Sign in first' })
}
export function requireRole(role) {
return (req, res, next) => {
if (req.user?.role === role) return next()
res.status(403).json({ error: 'Not allowed' })
}
}
JSNext, move the routes into two routers, so each area of the app sits in its own file. In this step the route code moves across unchanged, flaws included: you fix one thing at a time and let the tests show what each change does.
mkdir -p routes
cat > routes/posts.js <<'JS'
import { Router } from 'express'
export function readPost(body) {
const title = typeof body?.title === 'string' ? body.title.trim() : ''
const text = typeof body?.body === 'string' ? body.body.trim() : ''
if (title.length < 1 || title.length > 120 || text.length < 1 || text.length > 5000) return null
return { title, body: text }
}
export function postsRouter(db) {
const router = Router()
const findPost = db.prepare('SELECT id, owner_id, title, body, status FROM posts WHERE id = ?')
router.get('/', (req, res) => {
res.json(db.prepare("SELECT id, title, body FROM posts WHERE status = 'published' ORDER BY id").all())
})
router.post('/', (req, res) => {
const input = readPost(req.body)
if (!input) return res.status(422).json({ error: 'title and body are required' })
const result = db
.prepare("INSERT INTO posts (owner_id, title, body, status) VALUES (?, ?, ?, 'draft')")
.run(req.user.id, input.title, input.body)
res.status(201).json({ id: Number(result.lastInsertRowid), ...input, status: 'draft' })
})
// FLAW (still): no owner check.
router.get('/:id', (req, res) => {
const post = findPost.get(req.params.id)
if (!post) return res.status(404).json({ error: 'Post not found' })
res.json(post)
})
// FLAW (still): no owner check.
router.put('/:id', (req, res) => {
const post = findPost.get(req.params.id)
if (!post) return res.status(404).json({ error: 'Post not found' })
const input = readPost(req.body)
if (!input) return res.status(422).json({ error: 'title and body are required' })
db.prepare('UPDATE posts SET title = ?, body = ? WHERE id = ?').run(input.title, input.body, post.id)
res.json(findPost.get(post.id))
})
return router
}
JS
cat > routes/admin.js <<'JS'
import { Router } from 'express'
export function adminRouter(db) {
const router = Router()
// FLAW (still): trusts a role header that the caller chooses.
router.get('/users', (req, res) => {
if (req.get('x-user-role') !== 'admin') return res.status(403).json({ error: 'Admins only' })
res.json(db.prepare('SELECT id, name, role FROM users ORDER BY id').all())
})
return router
}
JSNow rewrite app.js to wire it together. The order matters: authenticate and denyByDefault are registered before any route, so no route can be reached without passing them. The route handlers no longer check for a user themselves; req.user is always set by the time they run.
cat > app.js <<'JS'
import express from 'express'
import { createAuth, denyByDefault } from './auth.js'
import { postsRouter } from './routes/posts.js'
import { adminRouter } from './routes/admin.js'
export function createApp(db) {
const app = express()
app.disable('x-powered-by')
app.use(express.json({ limit: '10kb' }))
const auth = createAuth(db)
app.use(auth.authenticate)
app.use(denyByDefault)
app.post('/api/sign-in', auth.signIn)
app.use('/api/posts', postsRouter(db))
app.use('/api/admin', adminRouter(db))
app.use((req, res) => res.status(404).json({ error: 'Not found' }))
app.use((err, req, res, next) => {
const status = err.status >= 400 && err.status < 500 ? err.status : 500
if (status === 500) console.error(err)
res.status(status).json({ error: status === 500 ? 'Something went wrong' : 'Bad request' })
})
return app
}
JSdenyByDefault is registered with app.use and no path, so req.path is the full path, such as /api/posts/3. An unknown path from a signed-out caller gets 401 rather than 404, which also stops strangers from mapping which routes exist.
Check it worked
npm run test:securityNow four tests fail instead of five. The signed-out visitor gets 401, so that test passes. The other member's read and edit still fail, and so do both role tests: deny-by-default answers "is anyone signed in?", not "is this the right person?". Run node --test test/app.test.js as well: the two baseline tests still pass, because sign-in and the public list are on the public list. (npm test would also run the security tests and show the four expected failures.)
Step 4 · Check ownership inside the query
The tempting fix for the IDOR is to load the post, then compare post.owner_id with req.user.id in JavaScript. It works until someone adds a route and forgets the comparison. Put the rule where the data is fetched instead: the query asks for "post 3, if this user may see it", so there is no way to get the row without the check.
Two choices shape the responses:
- 404, not 403. If amara asks for bola's draft and gets 403 Forbidden, she has learned that a post with that ID exists. A 404 Not Found gives the same answer for "does not exist" and "not yours", so probing IDs tells her nothing.
- One query per rule. Reading allows the owner, or anyone signed in when the post is published. Editing allows the owner only. The
UPDATEcarries the owner in itsWHEREclause and reports how many rows it changed; zero means not found or not yours.
Rewrite routes/posts.js:
cat > routes/posts.js <<'JS'
import { Router } from 'express'
export function readPost(body) {
const title = typeof body?.title === 'string' ? body.title.trim() : ''
const text = typeof body?.body === 'string' ? body.body.trim() : ''
if (title.length < 1 || title.length > 120 || text.length < 1 || text.length > 5000) return null
return { title, body: text }
}
export function postsRouter(db) {
const router = Router()
const listPublished = db.prepare(
"SELECT id, title, body FROM posts WHERE status = 'published' ORDER BY id",
)
const insertDraft = db.prepare(
"INSERT INTO posts (owner_id, title, body, status) VALUES (?, ?, ?, 'draft')",
)
// The owner sees their own posts; everyone signed in sees published ones. Nothing else.
const findVisible = db.prepare(`
SELECT id, title, body, status FROM posts
WHERE id = ? AND (owner_id = ? OR status = 'published')
`)
// Only the owner can change a post. The owner check is part of the statement.
const updateOwn = db.prepare('UPDATE posts SET title = ?, body = ? WHERE id = ? AND owner_id = ?')
const notFound = (res) => res.status(404).json({ error: 'Post not found' })
router.get('/', (req, res) => res.json(listPublished.all()))
router.post('/', (req, res) => {
const input = readPost(req.body)
if (!input) return res.status(422).json({ error: 'title and body are required' })
const result = insertDraft.run(req.user.id, input.title, input.body)
res.status(201).json({ id: Number(result.lastInsertRowid), ...input, status: 'draft' })
})
router.get('/:id', (req, res) => {
const post = findVisible.get(req.params.id, req.user.id)
if (!post) return notFound(res)
res.json(post)
})
router.put('/:id', (req, res) => {
const input = readPost(req.body)
if (!input) return res.status(422).json({ error: 'title and body are required' })
const { changes } = updateOwn.run(input.title, input.body, req.params.id, req.user.id)
if (changes === 0) return notFound(res)
res.json(findVisible.get(req.params.id, req.user.id))
})
return router
}
JSowner_id no longer appears in responses. The client has no use for it, and every internal field you send is one more thing to reason about.
A member who tries to edit someone else's published post also gets 404 here, even though the post's existence is public. That is a choice, not a rule: 403 would be equally safe in that case. What matters is that the answer never depends on a check the client can skip.
Check it worked
npm run test:securityTwo tests fail now, both about the admin route. The read and edit tests pass: amara gets 404 for bola's draft, the response has no MARKER-bola text, and the title is still Bola draft. The owner control test still passes.
Step 5 · Take roles from the server only
The admin route asks the request whether the caller is an admin. Anyone can send X-User-Role: admin with curl, a browser extension or a few lines of script. The same flaw shows up as a role field in a JSON body, a hidden form input, a cookie the server never signs, or an isAdmin flag in browser storage. Whatever the client sends, the client controls.
The role is already loaded from the users table by authenticate and sits on req.user.role. Guard the whole admin router with requireRole('admin'), and delete the header check. Putting the guard on the router, rather than on each route, means every admin route added later is covered too. Rewrite routes/admin.js:
cat > routes/admin.js <<'JS'
import { Router } from 'express'
import { requireRole } from '../auth.js'
export function adminRouter(db) {
const router = Router()
router.use(requireRole('admin'))
router.get('/users', (req, res) => {
res.json(db.prepare('SELECT id, name, role FROM users ORDER BY id').all())
})
return router
}
JSHere 403 is the right answer for a member. The admin area is not a secret, and a clear "not allowed" helps a member who followed a stale link. Signed-out callers still get 401 from denyByDefault, before the admin router runs.
Check it worked
npm run test:security
npm testAll six security tests pass, and npm test passes all eight tests: the two baseline tests and the six security tests. amara's forged header now gets 403, and chen lists the three users without sending any role.
Step 6 · Add random public IDs as defence in depth
The ownership check is the fix. Numeric IDs still leak a little: post 41 tells anyone that about 40 posts exist, and invites trying 42. Links to Noticeboard posts get forwarded in WhatsApp groups and by SMS, so an ID in a URL travels further than you expect. A random public ID gives nothing away and cannot be guessed.
Random IDs alone do not fix an IDOR. A link that is forwarded, logged by a proxy or kept in browser history still opens the post for anyone holding it, unless the server checks ownership. Keep the check from the previous step and add the random ID on top.
Give each post a public_id, filled with crypto.randomUUID(), and keep the integer id for joins inside the database. Rewrite db.js:
cat > db.js <<'JS'
import { DatabaseSync } from 'node:sqlite'
import { randomUUID } from 'node:crypto'
export function openDb() {
const password = process.env.NOTICEBOARD_DEMO_PASSWORD
if (!password) throw new Error('Set NOTICEBOARD_DEMO_PASSWORD (it lives in .env)')
const db = new DatabaseSync(':memory:')
db.exec(`
CREATE TABLE users (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL UNIQUE,
password TEXT NOT NULL,
role TEXT NOT NULL DEFAULT 'member' CHECK (role IN ('member', 'admin'))
);
CREATE TABLE posts (
id INTEGER PRIMARY KEY,
public_id TEXT NOT NULL UNIQUE,
owner_id INTEGER NOT NULL REFERENCES users(id),
title TEXT NOT NULL,
body TEXT NOT NULL,
status TEXT NOT NULL CHECK (status IN ('draft', 'published'))
);
`)
const addUser = db.prepare('INSERT INTO users (name, password, role) VALUES (?, ?, ?)')
addUser.run('amara', password, 'member')
addUser.run('bola', password, 'member')
addUser.run('chen', password, 'admin')
const addPost = db.prepare(
'INSERT INTO posts (public_id, owner_id, title, body, status) VALUES (?, ?, ?, ?, ?)',
)
addPost.run(randomUUID(), 1, 'Market day moves to Saturday', 'Stalls open at 8am this week.', 'published')
addPost.run(randomUUID(), 1, 'Committee minutes', 'Notes not ready to share yet.', 'draft')
return db
}
JSThen rewrite routes/posts.js so every query looks posts up by public_id and returns it as id. The ownership conditions are unchanged:
cat > routes/posts.js <<'JS'
import { Router } from 'express'
import { randomUUID } from 'node:crypto'
export function readPost(body) {
const title = typeof body?.title === 'string' ? body.title.trim() : ''
const text = typeof body?.body === 'string' ? body.body.trim() : ''
if (title.length < 1 || title.length > 120 || text.length < 1 || text.length > 5000) return null
return { title, body: text }
}
export function postsRouter(db) {
const router = Router()
const listPublished = db.prepare(
"SELECT public_id AS id, title, body FROM posts WHERE status = 'published' ORDER BY posts.id",
)
const insertDraft = db.prepare(
"INSERT INTO posts (public_id, owner_id, title, body, status) VALUES (?, ?, ?, ?, 'draft')",
)
// The owner sees their own posts; everyone signed in sees published ones. Nothing else.
const findVisible = db.prepare(`
SELECT public_id AS id, title, body, status FROM posts
WHERE public_id = ? AND (owner_id = ? OR status = 'published')
`)
// Only the owner can change a post. The owner check is part of the statement.
const updateOwn = db.prepare(
'UPDATE posts SET title = ?, body = ? WHERE public_id = ? AND owner_id = ?',
)
const notFound = (res) => res.status(404).json({ error: 'Post not found' })
router.get('/', (req, res) => res.json(listPublished.all()))
router.post('/', (req, res) => {
const input = readPost(req.body)
if (!input) return res.status(422).json({ error: 'title and body are required' })
const publicId = randomUUID()
insertDraft.run(publicId, req.user.id, input.title, input.body)
res.status(201).json({ id: publicId, ...input, status: 'draft' })
})
router.get('/:id', (req, res) => {
const post = findVisible.get(req.params.id, req.user.id)
if (!post) return notFound(res)
res.json(post)
})
router.put('/:id', (req, res) => {
const input = readPost(req.body)
if (!input) return res.status(422).json({ error: 'title and body are required' })
const { changes } = updateOwn.run(input.title, input.body, req.params.id, req.user.id)
if (changes === 0) return notFound(res)
res.json(findVisible.get(req.params.id, req.user.id))
})
return router
}
JSAdd a test that pins the new behaviour down: IDs in responses are UUIDs, and the old numeric URL no longer works, even for the post's owner. Create test/security/public-ids.test.js:
cat > test/security/public-ids.test.js <<'JS'
import { test, before, after } from 'node:test'
import assert from 'node:assert/strict'
import { startApp, signIn, createDraft } from '../helpers.js'
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/
let app, amara
before(async () => {
app = await startApp()
amara = await signIn(app.base, 'amara')
})
after(() => app.close())
test('posts are addressed by a random UUID', async () => {
const id = await createDraft(app.base, amara, 'Hall booking', 'MARKER-amara-hall')
assert.match(id, UUID)
const res = await fetch(`${app.base}/api/posts/${id}`, { headers: amara })
assert.equal(res.status, 200)
})
test('a sequential number no longer finds a post, even for its owner', async () => {
for (const guess of ['1', '2', '3']) {
const res = await fetch(`${app.base}/api/posts/${guess}`, { headers: amara })
assert.equal(res.status, 404)
}
})
JSCheck it worked
npm testAll ten tests pass. The access-control tests needed no change, because they take each post's ID from the API's own responses rather than assuming a number. That is worth copying: tests that build URLs from responses survive changes like this one.
Step 7 · Test every route for every role
The tests so far cover the flaws you knew about. The next flaw will be in a route someone adds next month. An access-control matrix states, for every route and every kind of caller, the status the app must return, and a loop checks every cell. A new route without a row is visible in review, and a row with a wrong answer fails.
Noticeboard has four kinds of caller: signed out, a member who does not own the post, the owner, and an admin. Admins here manage users, not other people's drafts, so an admin gets 404 for a draft that is not theirs. Your app might decide differently; the matrix is where you write that decision down. Create test/security/access-matrix.test.js:
cat > test/security/access-matrix.test.js <<'JS'
import { test, before, after } from 'node:test'
import assert from 'node:assert/strict'
import { startApp, signIn, createDraft } from '../helpers.js'
const ROLES = ['anonymous', 'member', 'owner', 'admin']
const edit = { title: 'Matrix edit', body: 'MARKER-matrix-edit' }
const draft = { title: 'Matrix new draft', body: 'MARKER-matrix-new' }
// One row per route. Each cell is the status that role must get.
const MATRIX = [
{ route: 'GET /api/posts', path: () => '/api/posts',
expect: { anonymous: 200, member: 200, owner: 200, admin: 200 } },
{ route: 'POST /api/posts', method: 'POST', body: draft, path: () => '/api/posts',
expect: { anonymous: 401, member: 201, owner: 201, admin: 201 } },
{ route: 'GET /api/posts/:id (draft)', path: (ids) => `/api/posts/${ids.draft}`,
expect: { anonymous: 401, member: 404, owner: 200, admin: 404 } },
{ route: 'PUT /api/posts/:id (draft)', method: 'PUT', body: edit, path: (ids) => `/api/posts/${ids.draft}`,
expect: { anonymous: 401, member: 404, owner: 200, admin: 404 } },
{ route: 'GET /api/posts/:id (published)', path: (ids) => `/api/posts/${ids.published}`,
expect: { anonymous: 401, member: 200, owner: 200, admin: 200 } },
{ route: 'PUT /api/posts/:id (published)', method: 'PUT', body: edit, path: (ids) => `/api/posts/${ids.published}`,
expect: { anonymous: 401, member: 404, owner: 200, admin: 404 } },
{ route: 'GET /api/admin/users', path: () => '/api/admin/users',
expect: { anonymous: 401, member: 403, owner: 403, admin: 200 } },
{ route: 'GET /api/admin/users with a forged role header', path: () => '/api/admin/users',
headers: { 'x-user-role': 'admin' },
expect: { anonymous: 401, member: 403, owner: 403, admin: 200 } },
{ route: 'GET an unknown route', path: () => '/api/no-such-route',
expect: { anonymous: 401, member: 404, owner: 404, admin: 404 } },
]
let app
const as = { anonymous: {} }
const ids = {}
before(async () => {
app = await startApp()
as.owner = await signIn(app.base, 'amara')
as.member = await signIn(app.base, 'bola')
as.admin = await signIn(app.base, 'chen')
ids.draft = await createDraft(app.base, as.owner, 'Matrix draft', 'MARKER-matrix-private')
ids.published = (await (await fetch(`${app.base}/api/posts`)).json())[0].id
})
after(() => app.close())
for (const row of MATRIX) {
for (const role of ROLES) {
const expected = row.expect[role]
test(`${row.route} as ${role} returns ${expected}`, async () => {
const res = await fetch(`${app.base}${row.path(ids)}`, {
method: row.method ?? 'GET',
headers: { ...as[role], ...row.headers, 'content-type': 'application/json' },
body: row.body ? JSON.stringify(row.body) : undefined,
})
assert.equal(res.status, expected)
if (expected >= 400) assert.doesNotMatch(await res.text(), /MARKER-matrix-private/)
})
}
}
JSEvery row lists all four roles, so leaving a role out shows up as returns undefined in the test name. Beyond status codes, each refused response is checked for the draft's private marker.
Check it worked
npm run test:securityThe run reports 44 passing tests: the matrix's 36 (nine routes times four roles), the six access-control tests and the two public ID tests. Each matrix test name reads as a rule, for example PUT /api/posts/:id (draft) as member returns 404.
To see the matrix catch a regression, open routes/posts.js, delete AND owner_id = ? from the UPDATE, remove the last argument req.user.id from updateOwn.run(...), and run npm run test:security again. The member and admin cells for both PUT rows fail, and so does the edit test from step 2. Put the two pieces back and the run is clean again.
Next steps
Your Noticeboard now refuses signed-out callers by default, checks ownership in every post query, takes roles only from its own database, and has a matrix that will flag the next route that gets this wrong. Keep ~/noticeboard-demo/api as it is: part 5 adds a link preview to this API, and part 8's clean-up removes it with the rest of ~/noticeboard-demo. To bring these fixes into part 1's app, make the same moves there: read the role from the users table instead of the role cookie, and add the owner to the queries behind /posts/:id, /posts/:id/edit and /admin.
- Control which programs can call an API at all, as well as which user: /tutorials/protect-an-api-with-api-keys
- If your app uses tokens rather than server-side sessions, avoid the mistakes that let a client forge its own role: /tutorials/avoid-the-jwt-mistakes-that-break-api-security
Part of these paths
Related tutorials
- Protect an API with API keys you can rotate and revokeYou will build an API key system for an Express 5.3 API on Node.js 26 that issues prefixed random keys, stores only their SHA-256 hashes, checks scopes, records last use, and rotates or revokes any key without breaking the partners who hold the others.
- Avoid the JWT mistakes that break API securityYou will break a deliberately weak Node.js API with forged, misdirected and expired JSON Web Tokens, then replace its checks with a jose 6.2 verifier that pins the algorithm and every claim, so each attack ends in a 401.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials