Skip to main content

Security and hardening · Advanced · 32 min

Keep the Noticeboard fixes fixed with security tests and custom Semgrep rules

By Padding · Updated 18 Nov 2026
node:26 image (Debian) · Node.js 26.13.1 · Express 5.3.0 · Semgrep 1.187.0

You will lock in every Noticeboard fix with one regression test per flaw and three custom Semgrep rules of your own, test the rules, run both on every pull request in GitHub Actions, write a one-page record of the fixes, and then remove the practice app.

On this page

A security fix lasts until someone writes the next route. Six months after you fixed command injection in the thumbnail feature, a colleague adds an export button, copies a line from an old branch, and the shell is back. Nobody meant it; nothing stopped it.

Two kinds of guard stop it, and they catch different things:

  • Regression tests prove that the app still behaves safely: a draft stays private, a cross-site post is refused, a planted session ID is replaced. They catch a fix being undone in a route that already exists. They know nothing about a route nobody has written a test for.
  • Static analysis rules read the code without running it and flag a pattern: a shell command built from a string, a route with no authorisation, request data sent back without escaping. They catch the new route on the day it is written, but they cannot tell you the app works.

In this last part of the series you add both to Noticeboard, the practice app from part 1. You write one regression test per fix from parts 1 to 7, then three Semgrep rules for Noticeboard's own bug classes, each with its own test file. You run everything in a GitHub Actions workflow on pull requests, write a short record of what was fixed and why, and finish by deleting the app.

As in every part: practise only on your own copy, on your own machine. Semgrep reads source code you have; it does not touch any server.

Step 1 · Get the fixed Noticeboard this part protects

The rules and tests below are written against the files in this step: a trimmed Noticeboard with the fixes from parts 1 to 7 in place. It keeps the routes the guards need (posts, comments, search, admin, attachments, thumbnails, sign-in and sign-out) and leaves out the link preview from part 5, the DOMPurify formatting from part 3 and the session store from part 7, which have their own tests in those parts. Post bodies here are plain text.

If ~/noticeboard-demo already exists from earlier parts, move it aside first so nothing you wrote is overwritten. The clean-up step at the end removes both folders:

Bash
if [ -d ~/noticeboard-demo ]; then mv ~/noticeboard-demo ~/noticeboard-demo-earlier-parts; fi
mkdir -p ~/noticeboard-demo/src/routes ~/noticeboard-demo/test/security ~/noticeboard-demo/rules
cd ~/noticeboard-demo
cat > package.json <<'JSON'
{
  "name": "noticeboard",
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "engines": { "node": ">=26" },
  "scripts": {
    "test": "node --test \"test/**/*.test.js\"",
    "test:security": "node --test \"test/security/*.test.js\"",
    "lint:security": "semgrep --test --metrics=off rules/ && semgrep scan --config rules/ --error --metrics=off src/"
  }
}
JSON
cat > .gitignore <<'TXT'
node_modules/
.env
noticeboard.db
data/thumbnails/
TXT
npm install express@5.3.0 --save-exact

lint:security is the script you build up to in this part: it tests the Semgrep rules, then scans the app with them.

Create the escaping helpers. They are the html tagged template from part 3, plus page(), which builds every full page and refuses a body that did not come from html. That refusal matters later: it is what lets a Semgrep rule treat page() as safe.

Bash
cat > src/html.js <<'JS'
const ESCAPES = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }

export function escapeHtml(value) {
  return String(value).replace(/[&<>"']/g, (ch) => ESCAPES[ch])
}

export class SafeHtml {
  constructor(value) {
    this.value = value
  }
  toString() {
    return this.value
  }
}

function render(value) {
  if (value instanceof SafeHtml) return value.value
  if (Array.isArray(value)) return value.map(render).join('')
  if (value === null || value === undefined || value === false) return ''
  return escapeHtml(value)
}

// Escapes every value unless it is already an html fragment.
export function html(strings, ...values) {
  let out = strings[0]
  values.forEach((value, i) => {
    out += render(value) + strings[i + 1]
  })
  return new SafeHtml(out)
}

// The only way to build a full page. It refuses a body that is not an html fragment.
export function page(title, user, body) {
  if (!(body instanceof SafeHtml)) throw new TypeError('page() needs an html`` body')
  const who = user
    ? html`Signed in as ${user.name} <form method="post" action="/signout"><button>Sign out</button></form>`
    : html`<a href="/signin">Sign in</a>`
  return String(html`<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
<title>${title} - Noticeboard</title></head>
<body><header><a href="/">Noticeboard</a> ${who}</header><main>${body}</main></body>
</html>`)
}
JS

Create src/auth.js. It holds the session fixes from part 7 (a new ID at every sign-in, HttpOnly, Secure, SameSite=Lax and the __Host- prefix, idle and absolute timeouts, sign-out on the server), the authorisation convention from part 2, and the cross-site check from part 4. The convention is the part your rules will enforce: every route says who may call it, with authorize('member'), authorize('admin') or publicRoute straight after its path.

Bash
cat > src/auth.js <<'JS'
import { randomBytes } from 'node:crypto'

export const SESSION_COOKIE = '__Host-sid'
const IDLE_MS = 30 * 60 * 1000
const ABSOLUTE_MS = 8 * 60 * 60 * 1000

function parseCookies(header = '') {
  const cookies = {}
  for (const pair of header.split(';')) {
    const i = pair.indexOf('=')
    if (i > 0) cookies[pair.slice(0, i).trim()] = decodeURIComponent(pair.slice(i + 1).trim())
  }
  return cookies
}

export function createSessions(db) {
  const sessions = new Map() // session ID -> { userId, created, seen }

  function loadUser(req, res, next) {
    const sid = parseCookies(req.get('cookie'))[SESSION_COOKIE]
    const s = sid && sessions.get(sid)
    const now = Date.now()
    if (s && now - s.seen < IDLE_MS && now - s.created < ABSOLUTE_MS) {
      s.seen = now
      req.sid = sid
      req.user = db.prepare('SELECT id, name, role FROM users WHERE id = ?').get(s.userId)
    } else if (s) {
      sessions.delete(sid)
    }
    next()
  }

  // Always a new ID at sign-in, so a session ID planted before sign-in is worthless.
  function start(req, res, userId) {
    if (req.sid) sessions.delete(req.sid)
    const sid = randomBytes(32).toString('base64url')
    sessions.set(sid, { userId, created: Date.now(), seen: Date.now() })
    res.cookie(SESSION_COOKIE, sid, { httpOnly: true, secure: true, sameSite: 'lax', path: '/' })
  }

  function end(req, res) {
    if (req.sid) sessions.delete(req.sid)
    res.clearCookie(SESSION_COOKIE, { httpOnly: true, secure: true, sameSite: 'lax', path: '/' })
  }

  return { loadUser, start, end }
}

// Every route names who may call it: authorize('member'), authorize('admin') or publicRoute.
export function authorize(role) {
  return (req, res, next) => {
    if (!req.user) return res.status(401).type('text/plain').send('Sign in first.')
    if (role === 'admin' && req.user.role !== 'admin') return res.status(403).type('text/plain').send('Admins only.')
    next()
  }
}

export const publicRoute = (req, res, next) => next()

// Refuses state-changing requests that a browser marks as coming from another site.
export function rejectCrossSite(req, res, next) {
  if (['GET', 'HEAD', 'OPTIONS'].includes(req.method)) return next()
  const site = req.get('sec-fetch-site')
  const origin = req.get('origin')
  const crossSite = site
    ? !['same-origin', 'none'].includes(site)
    : Boolean(origin) && origin !== `${req.protocol}://${req.get('host')}`
  if (crossSite) return res.status(403).type('text/plain').send('Cross-site request refused.')
  next()
}
JS

Now the routes. Posts check ownership inside the query (part 2) and build every page with html (part 3). There is no GET route that deletes (part 4):

Bash
cat > src/routes/posts.js <<'JS'
import { Router } from 'express'
import { authorize, publicRoute } from '../auth.js'
import { html, page } from '../html.js'

export function postsRouter(db) {
  const router = Router()

  router.get('/', publicRoute, (req, res) => {
    const posts = db.prepare('SELECT id, title FROM posts WHERE published = 1 ORDER BY id DESC').all()
    const items = posts.map((p) => html`<li><a href="/posts/${p.id}">${p.title}</a></li>`)
    res.send(page('Home', req.user, html`<h1>Notices</h1><ul>${items}</ul>`))
  })

  router.get('/search', publicRoute, (req, res) => {
    const q = String(req.query.q ?? '')
    const rows = db
      .prepare("SELECT id, title FROM posts WHERE published = 1 AND title LIKE '%' || ? || '%'")
      .all(q)
    const items = rows.map((p) => html`<li><a href="/posts/${p.id}">${p.title}</a></li>`)
    res.send(page('Search', req.user, html`<h1>Results for ${q}</h1><ul>${items}</ul>`))
  })

  router.post('/posts', authorize('member'), (req, res) => {
    const { title = '', body = '', published } = req.body ?? {}
    const { lastInsertRowid } = db
      .prepare('INSERT INTO posts (owner_id, title, body, published) VALUES (?, ?, ?, ?)')
      .run(req.user.id, String(title), String(body), published === 'on' ? 1 : 0)
    res.redirect(303, `/posts/${lastInsertRowid}`)
  })

  router.get('/posts/:id', authorize('member'), (req, res) => {
    // Published posts, or your own drafts. Anything else is "not found".
    const post = db
      .prepare(`SELECT p.id, p.title, p.body, p.published, u.name AS author
                FROM posts p JOIN users u ON u.id = p.owner_id
                WHERE p.id = ? AND (p.published = 1 OR p.owner_id = ?)`)
      .get(req.params.id, req.user.id)
    if (!post) return res.status(404).send(page('Not found', req.user, html`<p>No such post.</p>`))
    const comments = db
      .prepare(`SELECT c.body, u.name AS author FROM comments c
                JOIN users u ON u.id = c.author_id WHERE c.post_id = ? ORDER BY c.id`)
      .all(post.id)
    const list = comments.map((c) => html`<li><strong>${c.author}</strong>: ${c.body}</li>`)
    res.send(page(post.title, req.user, html`<article><h1>${post.title}</h1>
<p>By ${post.author}${post.published ? '' : ' (draft)'}</p><p>${post.body}</p></article>
<h2>Comments</h2><ul>${list}</ul>`))
  })

  router.post('/posts/:id/comments', authorize('member'), (req, res) => {
    const post = db
      .prepare('SELECT id FROM posts WHERE id = ? AND (published = 1 OR owner_id = ?)')
      .get(req.params.id, req.user.id)
    if (!post) return res.status(404).type('text/plain').send('No such post.')
    db.prepare('INSERT INTO comments (post_id, author_id, body) VALUES (?, ?, ?)')
      .run(post.id, req.user.id, String(req.body?.body ?? ''))
    res.redirect(303, `/posts/${post.id}`)
  })

  router.post('/posts/:id/delete', authorize('member'), (req, res) => {
    const own = db.prepare('SELECT id FROM posts WHERE id = ? AND owner_id = ?').get(req.params.id, req.user.id)
    if (!own) return res.status(404).type('text/plain').send('No such post.')
    db.prepare('DELETE FROM comments WHERE post_id = ?').run(own.id)
    db.prepare('DELETE FROM posts WHERE id = ?').run(own.id)
    res.redirect(303, '/')
  })

  router.get('/admin', authorize('admin'), (req, res) => {
    const users = db.prepare('SELECT name, role FROM users ORDER BY name').all()
    const items = users.map((u) => html`<li>${u.name} (${u.role})</li>`)
    res.send(page('Admin', req.user, html`<h1>Users</h1><ul>${items}</ul>`))
  })

  return router
}
JS

Attachments use opaque IDs and res.sendFile with a root, and the thumbnailer calls execFile with an argument array (part 6). Sign-in and sign-out go through the session helpers:

Bash
cat > src/routes/files.js <<'JS'
import { Router } from 'express'
import { execFile } from 'node:child_process'
import path from 'node:path'
import { promisify } from 'node:util'
import { authorize } from '../auth.js'

const execFileAsync = promisify(execFile)

export function filesRouter(db, dataDir) {
  const router = Router()
  const filesDir = path.join(dataDir, 'files')
  const thumbsDir = path.join(dataDir, 'thumbnails')
  const lookup = db.prepare('SELECT id, stored_name FROM files WHERE id = ?')

  // Files are addressed by an opaque ID; the name on disk never comes from the request.
  router.get('/files/:id', authorize('member'), (req, res) => {
    const file = lookup.get(req.params.id)
    if (!file) return res.status(404).type('text/plain').send('No such file.')
    res.sendFile(file.stored_name, { root: filesDir })
  })

  // A stand-in for a real thumbnailer: it copies the file. No shell, arguments as an array.
  router.post('/files/:id/thumbnail', authorize('member'), async (req, res) => {
    const file = lookup.get(req.params.id)
    if (!file) return res.status(404).type('text/plain').send('No such file.')
    await execFileAsync('cp', ['--', path.join(filesDir, file.stored_name), path.join(thumbsDir, file.stored_name)])
    res.json({ thumbnail: `/thumbnails/${file.id}` })
  })

  return router
}
JS
cat > src/routes/account.js <<'JS'
import { Router } from 'express'
import { publicRoute } from '../auth.js'
import { html, page } from '../html.js'

export function accountRouter(db, sessions) {
  const router = Router()

  router.get('/signin', publicRoute, (req, res) => {
    res.send(page('Sign in', req.user, html`<form method="post" action="/signin">
<label>Name <input name="name" autocomplete="username"></label>
<label>Password <input name="password" type="password" autocomplete="current-password"></label>
<button>Sign in</button></form>`))
  })

  router.post('/signin', publicRoute, (req, res) => {
    const { name = '', password = '' } = req.body ?? {}
    const user = db
      .prepare('SELECT id FROM users WHERE name = ? AND password = ?')
      .get(String(name), String(password))
    if (!user) return res.status(401).send(page('Sign in', undefined, html`<p>Wrong name or password.</p>`))
    sessions.start(req, res, user.id)
    res.redirect(303, '/')
  })

  router.post('/signout', publicRoute, (req, res) => {
    sessions.end(req, res)
    res.redirect(303, '/')
  })

  return router
}
JS

Last, the database, the error handler from part 1 and the app that joins them:

Bash
cat > src/db.js <<'JS'
import { DatabaseSync } from 'node:sqlite'
import { randomUUID } from 'node:crypto'

export function openDb(file, seedPassword) {
  const db = new DatabaseSync(file)
  db.exec(`
    CREATE TABLE IF NOT EXISTS users (
      id INTEGER PRIMARY KEY,
      name TEXT UNIQUE NOT NULL,
      password TEXT NOT NULL,
      role TEXT NOT NULL DEFAULT 'member'
    );
    CREATE TABLE IF NOT EXISTS posts (
      id INTEGER PRIMARY KEY,
      owner_id INTEGER NOT NULL REFERENCES users(id),
      title TEXT NOT NULL,
      body TEXT NOT NULL,
      published INTEGER NOT NULL DEFAULT 0
    );
    CREATE TABLE IF NOT EXISTS comments (
      id INTEGER PRIMARY KEY,
      post_id INTEGER NOT NULL REFERENCES posts(id),
      author_id INTEGER NOT NULL REFERENCES users(id),
      body TEXT NOT NULL
    );
    CREATE TABLE IF NOT EXISTS files (
      id TEXT PRIMARY KEY,
      stored_name TEXT NOT NULL
    );
  `)
  const { n } = db.prepare('SELECT COUNT(*) AS n FROM users').get()
  if (n === 0) seed(db, seedPassword)
  return db
}

function seed(db, password) {
  if (!password) throw new Error('Set SEED_PASSWORD to create the demo users')
  // Still plain text: /tutorials/hash-passwords-with-argon2id covers the fix.
  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, published) VALUES (?, ?, ?, ?)')
  addPost.run(1, 'Welcome to Noticeboard', 'Notices for the whole office.', 1)
  addPost.run(2, 'Draft: team lunch plans', 'Not ready to share yet.', 0)
  db.prepare('INSERT INTO files (id, stored_name) VALUES (?, ?)').run(randomUUID(), 'welcome.txt')
}
JS
cat > src/errors.js <<'JS'
import { randomUUID } from 'node:crypto'

// Full details go to the server log; the visitor gets a reference to quote.
export function errorHandler(err, req, res, next) {
  const ref = randomUUID().slice(0, 8)
  console.error(`[error ${ref}] ${req.method} ${req.path}`, err)
  if (res.headersSent) return next(err)
  const status = Number.isInteger(err.status) && err.status >= 400 && err.status < 500 ? err.status : 500
  res.status(status).type('text/plain').send(`Something went wrong. Reference: ${ref}`)
}
JS
cat > src/app.js <<'JS'
import express from 'express'
import { createSessions, rejectCrossSite } from './auth.js'
import { errorHandler } from './errors.js'
import { accountRouter } from './routes/account.js'
import { filesRouter } from './routes/files.js'
import { postsRouter } from './routes/posts.js'

export function createApp({ db, dataDir }) {
  const app = express()
  const sessions = createSessions(db)

  app.use(express.urlencoded({ extended: false }))
  app.use(sessions.loadUser)
  app.use(rejectCrossSite)
  app.use(accountRouter(db, sessions))
  app.use(postsRouter(db))
  app.use(filesRouter(db, dataDir))
  app.use((req, res) => res.status(404).type('text/plain').send('Not found.'))
  app.use(errorHandler)
  return app
}
JS

Add the shared test helper and the baseline feature tests. The helper starts a fresh copy of the app on a random port with an in-memory database, a throwaway data folder and a random password, so no password is written anywhere:

Bash
cat > test/helpers.js <<'JS'
import { mkdtemp, mkdir, writeFile, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import path from 'node:path'
import { randomBytes } from 'node:crypto'
import { createApp } from '../src/app.js'
import { openDb } from '../src/db.js'

export async function startApp() {
  const dataDir = await mkdtemp(path.join(tmpdir(), 'noticeboard-test-'))
  await mkdir(path.join(dataDir, 'files'))
  await mkdir(path.join(dataDir, 'thumbnails'))
  await writeFile(path.join(dataDir, 'files', 'welcome.txt'), 'Welcome to Noticeboard.\n')
  const password = randomBytes(12).toString('hex')
  const db = openDb(':memory:', password)
  const app = createApp({ db, dataDir })
  const server = await new Promise((resolve, reject) => {
    const s = app.listen(0, '127.0.0.1', (err) => (err ? reject(err) : resolve(s)))
  })
  const base = `http://127.0.0.1:${server.address().port}`

  return {
    base,
    db,
    dataDir,
    // Signs in and returns the Set-Cookie headers and a Cookie header for later requests.
    async signIn(name, { pass = password, cookie } = {}) {
      const res = await fetch(`${base}/signin`, {
        method: 'POST',
        headers: cookie ? { cookie } : {},
        body: new URLSearchParams({ name, password: pass }),
        redirect: 'manual',
      })
      const setCookies = res.headers.getSetCookie()
      return { status: res.status, setCookies, cookie: setCookies.map((c) => c.split(';')[0]).join('; ') }
    },
    async close() {
      server.closeAllConnections()
      await new Promise((resolve) => server.close(resolve))
      db.close()
      await rm(dataDir, { recursive: true, force: true })
    },
  }
}
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('home lists published posts and hides drafts', async () => {
  const html = await (await fetch(`${app.base}/`)).text()
  assert.match(html, /Welcome to Noticeboard/)
  assert.doesNotMatch(html, /team lunch/)
})

test('a member can publish a post and comment on it', async () => {
  const { cookie } = await app.signIn('bola')
  const created = await fetch(`${app.base}/posts`, {
    method: 'POST',
    headers: { cookie },
    body: new URLSearchParams({ title: 'Fire drill on Friday', body: 'At 10:00.', published: 'on' }),
    redirect: 'manual',
  })
  assert.equal(created.status, 303)
  const url = `${app.base}${created.headers.get('location')}`
  await fetch(`${url}/comments`, {
    method: 'POST', headers: { cookie }, body: new URLSearchParams({ body: 'Noted.' }), redirect: 'manual',
  })
  const html = await (await fetch(url, { headers: { cookie } })).text()
  assert.match(html, /Fire drill on Friday/)
  assert.match(html, /Noted\./)
})

test('a member can download an attachment and make a thumbnail', async () => {
  const { cookie } = await app.signIn('amara')
  const { id } = app.db.prepare('SELECT id FROM files').get()
  const file = await fetch(`${app.base}/files/${id}`, { headers: { cookie } })
  assert.equal(file.status, 200)
  assert.match(await file.text(), /Welcome to Noticeboard/)
  const thumb = await fetch(`${app.base}/files/${id}/thumbnail`, { method: 'POST', headers: { cookie } })
  assert.equal(thumb.status, 200)
})
JS

Check it worked

Bash
npm test

The summary shows # tests 3, # pass 3 and # fail 0. If a test fails with Cannot find module, one of the heredocs above was cut short; run that block again.

Step 2 · Write one regression test per fix

A regression test is the security test from an earlier part, kept for good. Put them in one file, one test per fix, named after the part and the OWASP Top 10:2025 category. When one fails in a year's time, the name tells whoever is on call which promise was broken and where to read about it.

Each test uses the harmless marker nb-marker-42 and checks the safe result, not the attack. The command injection test, for example, does not try to run anything clever: it adds a file record whose stored name carries shell syntax, welcome.txt; touch nb-marker-42 #, asks for a thumbnail, and checks that the request fails and no marker file appears. The path traversal test works the same way, with a stored name that points one folder up, at a file just outside files/.

Both tests go through a file record on purpose. A file ID that matches no record gets a 404 before the risky code runs, so a test that only sends odd IDs would still pass if someone undid the fix.

Bash
cat > test/security/regressions.test.js <<'JS'
// One test per fixed flaw. If any of these fails, a fix has been undone.
import { test, before, after } from 'node:test'
import assert from 'node:assert/strict'
import { readdir, writeFile } from 'node:fs/promises'
import path from 'node:path'
import { startApp } from '../helpers.js'

const MARKER = 'nb-marker-42'
let app, amara, bola

before(async () => {
  app = await startApp()
  amara = (await app.signIn('amara')).cookie
  bola = (await app.signIn('bola')).cookie
})
after(() => app.close())

test('part 2 (A01): a member cannot read another member\'s draft', async () => {
  const res = await fetch(`${app.base}/posts/2`, { headers: { cookie: amara } })
  assert.equal(res.status, 404)
  assert.doesNotMatch(await res.text(), /team lunch/)
})

test('part 2 (A01): a role cookie from the browser does not make you an admin', async () => {
  const res = await fetch(`${app.base}/admin`, { headers: { cookie: `${amara}; role=admin` } })
  assert.equal(res.status, 403)
})

test('part 3 (A05): the search term is shown as text, not markup', async () => {
  const q = encodeURIComponent(`<b>${MARKER}</b>`)
  const html = await (await fetch(`${app.base}/search?q=${q}`)).text()
  assert.ok(html.includes(`&lt;b&gt;${MARKER}&lt;/b&gt;`))
  assert.ok(!html.includes(`<b>${MARKER}</b>`))
})

test('part 3 (A05): a stored comment is shown as text, not markup', async () => {
  await fetch(`${app.base}/posts/1/comments`, {
    method: 'POST', headers: { cookie: bola },
    body: new URLSearchParams({ body: `<img src=x data-${MARKER}>` }), redirect: 'manual',
  })
  const html = await (await fetch(`${app.base}/posts/1`, { headers: { cookie: bola } })).text()
  assert.ok(html.includes(`&lt;img src=x data-${MARKER}&gt;`))
  assert.ok(!html.includes(`<img src=x data-${MARKER}>`))
})

test('part 4 (A01): a cross-site form post cannot delete a post', async () => {
  for (const headers of [{ 'sec-fetch-site': 'cross-site' }, { origin: 'http://attacker.invalid' }]) {
    const res = await fetch(`${app.base}/posts/1/delete`, {
      method: 'POST', headers: { cookie: amara, ...headers }, redirect: 'manual',
    })
    assert.equal(res.status, 403)
  }
  const get = await fetch(`${app.base}/posts/1/delete`, { headers: { cookie: amara }, redirect: 'manual' })
  assert.equal(get.status, 404, 'a GET must never delete')
  assert.equal(app.db.prepare('SELECT COUNT(*) AS n FROM posts WHERE id = 1').get().n, 1)
})

test('part 6 (A01): a file record cannot point outside the files folder', async () => {
  // A file one level above files/. Only the missing root option would let it out.
  await writeFile(path.join(app.dataDir, 'outside.txt'), `${MARKER}\n`)
  app.db.prepare('INSERT INTO files (id, stored_name) VALUES (?, ?)').run('escape', '../outside.txt')
  const res = await fetch(`${app.base}/files/escape`, { headers: { cookie: amara } })
  assert.ok(res.status >= 400 && res.status < 500, `expected a 4xx, got ${res.status}`)
  assert.ok(!(await res.text()).includes(MARKER), 'the file outside files/ was sent')
  // A path in the ID itself never reaches the disk either.
  const byId = await fetch(`${app.base}/files/..%2F..%2F..%2Fetc%2Fpasswd`, { headers: { cookie: amara } })
  assert.equal(byId.status, 404)
  assert.doesNotMatch(await byId.text(), /root:/)
})

test('part 6 (A05): shell syntax in a stored file name is never run', async () => {
  app.db.prepare('INSERT INTO files (id, stored_name) VALUES (?, ?)').run('evil', `welcome.txt; touch ${MARKER} #`)
  const res = await fetch(`${app.base}/files/evil/thumbnail`, { method: 'POST', headers: { cookie: amara } })
  // cp gets the whole odd name as one argument, finds no such file and fails.
  assert.ok(res.status >= 400, `expected an error, got ${res.status}`)
  for (const dir of [app.dataDir, path.join(app.dataDir, 'files'), path.join(app.dataDir, 'thumbnails')]) {
    assert.ok(!(await readdir(dir)).includes(MARKER), `marker file found in ${dir}`)
  }
})

test('part 7 (A07): sign-in replaces a planted session ID and sets safe cookie flags', async () => {
  const planted = '__Host-sid=planted-by-someone-else'
  const { setCookies } = await app.signIn('amara', { cookie: planted })
  const sid = setCookies.find((c) => c.startsWith('__Host-sid='))
  assert.ok(sid, 'no session cookie was set')
  assert.ok(!sid.startsWith(`${planted};`), 'the planted ID was kept')
  for (const flag of ['HttpOnly', 'Secure', 'SameSite=Lax', 'Path=/']) assert.ok(sid.includes(flag), `missing ${flag}`)
  assert.ok(!/domain=/i.test(sid), 'a __Host- cookie must not set Domain')
})

test('part 7 (A07): signing out ends the session on the server', async () => {
  const { cookie } = await app.signIn('bola')
  await fetch(`${app.base}/signout`, { method: 'POST', headers: { cookie }, redirect: 'manual' })
  const res = await fetch(`${app.base}/posts/1`, { headers: { cookie } })
  assert.equal(res.status, 401)
})

test('part 1 (A10): errors do not show stack traces or server paths', async () => {
  app.db.prepare('INSERT INTO files (id, stored_name) VALUES (?, ?)').run('gone', 'not-on-disk.txt')
  const res = await fetch(`${app.base}/files/gone`, { headers: { cookie: amara } })
  const text = await res.text()
  assert.ok(res.status >= 400)
  assert.match(text, /^Something went wrong\. Reference: \w{8}$/)
  assert.ok(!text.includes(app.dataDir))
})
JS

With the fixes in place, send refuses the .. in ../outside.txt with a 403 because sendFile was given a root, and cp treats the whole stored name as one file name. Replace the root option with path.join(filesDir, file.stored_name), or go back to a shell command string, and the matching test fails: the first sends the marker file, the second runs touch in the data folder and gets a 200.

The sign-out test reuses the old cookie after signing out. A sign-out that only cleared the cookie in the browser would let that old value back in; this one must get 401. The last test points a file record at a file that is not on disk, which makes sendFile fail inside the request, and checks that the visitor sees only the reference, never the data folder's path.

Check it worked

Bash
npm run test:security

The run reports # pass 10 and # fail 0. It also prints three [error ...] log lines with stack traces (the refused path, the failed cp and the missing file): that is the error handler writing the details to the server log, where they belong.

To see a guard do its job, open src/auth.js, change httpOnly: true to httpOnly: false in start(), and run npm run test:security again. The part 7 cookie test fails with missing HttpOnly. Change it back and the run is clean.

Step 3 · Install Semgrep and write a rule for shell commands

Semgrep is an open-source static analysis tool. A rule is a few lines of YAML with a pattern that looks like the code it matches, so you can write one for your own codebase's mistakes in minutes rather than waiting for a generic rule set to cover them. The Semgrep introduction covers the registry rules; this part is about rules of your own.

Install it with pipx, which puts Semgrep in its own Python environment and keeps it apart from system packages. On Ubuntu:

Bash
sudo apt update
sudo apt install -y pipx
pipx install semgrep==1.187.0
Bash
pipx ensurepath

pipx ensurepath adds ~/.local/bin to your PATH; open a new terminal afterwards and cd ~/noticeboard-demo again. On macOS, run brew install pipx first, then the same pipx commands. On macOS, Semgrep 1.187.0 ships a ready-built package for Apple silicon only; on an Intel Mac, use Homebrew's brew install semgrep (its version may differ from 1.187.0) or run these steps in an Ubuntu VM or container. The download is roughly 75 MB on Linux (about 53 MB on Apple silicon), plus its dependencies, so on a prepaid or metered connection do it once, on Wi-Fi if you can.

Bash
cd ~/noticeboard-demo
semgrep --version

The first rule is for part 6's flaw: a shell command built from a string that has a value in it. Create rules/exec-with-template-string.yaml:

Bash
cat > rules/exec-with-template-string.yaml <<'YAML'
rules:
  - id: noticeboard-exec-with-template-string
    languages: [javascript]
    severity: ERROR
    message: >-
      A shell command is built from a string with values in it. Use execFile or spawn
      with an argument array and no shell (part 6 of the series).
    pattern-either:
      - pattern: exec(`...${$X}...`, ...)
      - pattern: execSync(`...${$X}...`, ...)
      - pattern: exec($A + $B, ...)
      - pattern: execSync($A + $B, ...)
      - pattern: '$FN($CMD, $ARGS, {..., shell: true, ...}, ...)'
      # The promise version from util.promisify(exec), as part 1 of the series used it.
      - patterns:
          - pattern-inside: |
              $RUN = promisify(exec)
              ...
          - pattern-either:
              - pattern: $RUN(`...${$X}...`, ...)
              - pattern: $RUN($A + $B, ...)
YAML

How to read it:

  • pattern-either matches if any of its patterns match.
  • ` `...${$X}... ` is a template literal with at least one value in it; `$X is a metavariable that stands for any expression. A plain ` `ls -l `` with no value does not match.
  • $A + $B catches the older form, string concatenation.
  • The shell: true pattern catches spawn or execFile with a shell turned on, which brings the same risk back with an argument array.
  • The last block catches the wrapper part 1 used, const run = promisify(exec). pattern-inside limits the match to code that comes after that line, so a function called run elsewhere is left alone. A pattern only sees names, which is why rules are written for the way your codebase does things.

The single quotes around the shell: true pattern are there for YAML, not Semgrep: an unquoted key: value inside a list item is read as a YAML mapping.

Now the rule's test file. Semgrep finds it by name: for rules/exec-with-template-string.yaml with languages: [javascript], it reads rules/exec-with-template-string.js. A // ruleid: comment says the next line must match; // ok: says it must not. The ok lines matter as much as the others: they stop someone from "fixing" a missed case by making the rule flag everything.

Bash
cat > rules/exec-with-template-string.js <<'JS'
import { exec, execSync, execFile, spawn } from 'node:child_process'
import { promisify } from 'node:util'

const run = promisify(exec)
const runFile = promisify(execFile)

export async function examples(name) {
  // ruleid: noticeboard-exec-with-template-string
  exec(`cp files/${name} thumbnails/${name}`)

  // ruleid: noticeboard-exec-with-template-string
  execSync(`convert ${name} -resize 200 out.png`, { cwd: '/srv/data' })

  // ruleid: noticeboard-exec-with-template-string
  exec('cp files/' + name + ' thumbnails/')

  // ruleid: noticeboard-exec-with-template-string
  await run(`tar -czf exports/${name}.tar.gz files`)

  // ruleid: noticeboard-exec-with-template-string
  spawn('cp', [name, 'thumbnails/'], { shell: true })

  // ok: noticeboard-exec-with-template-string
  execFile('cp', ['--', name, 'thumbnails/'])

  // ok: noticeboard-exec-with-template-string
  await runFile('cp', ['--', name, `thumbnails/${name}`])

  // ok: noticeboard-exec-with-template-string
  exec('ls -l files')

  // ok: noticeboard-exec-with-template-string
  spawn('cp', ['--', name, 'thumbnails/'], { cwd: '/srv/data' })
}
JS
semgrep --test --metrics=off rules/

--metrics=off stops the command line tool from sending usage data to Semgrep. It costs you nothing and keeps the run entirely local.

Check it worked

semgrep --version prints 1.187.0, and the test run prints 1/1: ✓ All tests passed. If it says missed lines: [12] or incorrect lines: [24], the rule did not match a ruleid line or matched an ok line; the numbers are the lines in the .js file.

Step 4 · Write a rule for routes that skip authorisation

Part 2's lesson was "deny by default". In Noticeboard that is a convention, and a convention can be checked: every router.get, router.post and friends must have authorize(...) or publicRoute as the first handler after the path. A route that forgets is not necessarily open (it may sit behind other middleware), but it no longer says who may call it, and that is worth a look in review. Create rules/route-without-authorize.yaml:

Bash
cat > rules/route-without-authorize.yaml <<'YAML'
rules:
  - id: noticeboard-route-without-authorize
    languages: [javascript]
    severity: ERROR
    message: >-
      This route does not say who may call it. Put authorize('member'),
      authorize('admin') or publicRoute straight after the path (part 2 of the series).
    patterns:
      - pattern: $ROUTER.$METHOD($PATH, $HANDLER, ...)
      - metavariable-regex:
          metavariable: $ROUTER
          regex: ^(app|router|\w+Router)$
      - metavariable-regex:
          metavariable: $METHOD
          regex: ^(get|post|put|patch|delete|all)$
      - pattern-not: $ROUTER.$METHOD($PATH, authorize(...), ...)
      - pattern-not: $ROUTER.$METHOD($PATH, publicRoute, ...)
YAML

patterns means every entry must hold. The two metavariable-regex filters are what keep the rule quiet on ordinary code: db.prepare(sql).get(id, userId) has the same shape as a route, a method called get with two arguments, but its object is not named app, router or somethingRouter. Requiring a $HANDLER after the path skips app.get('env'), which reads a setting.

The test file covers both kinds of miss, including a route with some other middleware in the guard's place:

Bash
cat > rules/route-without-authorize.js <<'JS'
import express, { Router } from 'express'
import { authorize, publicRoute } from '../src/auth.js'

const router = Router()

// ruleid: noticeboard-route-without-authorize
router.get('/drafts', (req, res) => res.json([]))

// ruleid: noticeboard-route-without-authorize
router.post('/posts/:id/pin', express.json(), (req, res) => res.end())

// ok: noticeboard-route-without-authorize
router.get('/admin', authorize('admin'), (req, res) => res.end())

// ok: noticeboard-route-without-authorize
router.get('/', publicRoute, (req, res) => res.end())

function notARoute(db, req) {
  // ok: noticeboard-route-without-authorize
  return db.prepare('SELECT id FROM posts WHERE id = ? AND owner_id = ?').get(req.params.id, req.user.id)
}
JS
semgrep --test --metrics=off rules/

Check it worked

The run prints 2/2: ✓ All tests passed: both rule files and their tests. To see a false positive caught, delete the metavariable-regex block for $ROUTER and run the test again; it reports incorrect lines with the line number of the db.prepare(...).get(...) call. Put the block back.

Step 5 · Write a taint rule for unescaped responses

The third bug class is part 3's: request data sent back in HTML without escaping. A plain pattern cannot see this, because the value usually travels through a variable or two before it reaches res.send. Semgrep's taint mode follows it. You name the sources where untrusted data comes from, the sinks where it must not arrive, and the sanitizers that make it safe on the way. Create rules/send-unescaped-input.yaml:

Bash
cat > rules/send-unescaped-input.yaml <<'YAML'
rules:
  - id: noticeboard-send-unescaped-input
    languages: [javascript]
    severity: ERROR
    message: >-
      Request data reaches res.send without going through html`` or page(). Build the
      response with the html tag so every value is escaped (part 3 of the series).
    mode: taint
    pattern-sources:
      - pattern: $REQ.query
      - pattern: $REQ.params
      - pattern: $REQ.body
    pattern-sanitizers:
      - pattern: html`...`
      - pattern: escapeHtml(...)
      - pattern: page(...)
    pattern-sinks:
      - pattern: $RES.send(...)
YAML
cat > rules/send-unescaped-input.js <<'JS'
import { html, page } from '../src/html.js'

export function routes(router, db) {
  router.get('/search', (req, res) => {
    const q = String(req.query.q ?? '')
    // ruleid: noticeboard-send-unescaped-input
    res.send(`<h1>Results for ${q}</h1>`)
  })

  router.get('/hello/:name', (req, res) => {
    // ruleid: noticeboard-send-unescaped-input
    res.status(200).send('<p>Hello ' + req.params.name + '</p>')
  })

  router.get('/search-safe', (req, res) => {
    const q = String(req.query.q ?? '')
    // ok: noticeboard-send-unescaped-input
    res.send(page('Search', req.user, html`<h1>Results for ${q}</h1>`))
  })

  router.get('/posts/:id', (req, res) => {
    const post = db.prepare('SELECT title FROM posts WHERE id = ?').get(req.params.id)
    // ok: noticeboard-send-unescaped-input
    res.send(page(post.title, req.user, html`<h1>${post.title}</h1>`))
  })

  router.get('/status', (req, res) => {
    // ok: noticeboard-send-unescaped-input
    res.type('text/plain').send('Up.')
  })
}
JS
semgrep --test --metrics=off rules/

Two details decide whether a taint rule helps or annoys:

  • Taint flows through function calls by default. String(req.query.q) is still tainted, which is what you want. So is the row from db.prepare(...).get(req.params.id), because an ID from the request went in. Without page(...) as a sanitizer, every post page would be flagged.
  • A sanitizer must really be one. page() earns its place because it throws unless its body came from html, and html escapes the title it is given. Listing a function as a sanitizer when it does not escape everything would hide real bugs. If you change page() later, look at this rule again.

The rule also has limits worth knowing. The free engine follows taint within one function, so a helper in another file that builds HTML from a parameter is not traced; following data across functions and files is a paid Semgrep feature. Stored XSS, where the value comes from the database, is the regression test's job. And res.json is not a sink, because JSON is not parsed as HTML.

Check it worked

The run prints 3/3: ✓ All tests passed.

Step 6 · Scan the app and catch a regression

Now point the three rules at the app. Scan src/ only: the rules/ folder is full of deliberate bad examples, and scanning it would report them all.

Bash
semgrep scan --config rules/ --error --metrics=off src/

--config rules/ loads every YAML file in the folder, and --error makes Semgrep exit with a non-zero status when it finds anything, which is what fails a CI job. The scan ends with a summary line like Ran 3 rules on 8 files: 0 findings. The fixed app follows all three conventions.

Now play the colleague in a hurry. Create a new export route the way someone might write it from an old branch. You never mount it or run it; Semgrep only reads it.

Bash
cat > src/routes/export.js <<'JS'
import { Router } from 'express'
import { exec } from 'node:child_process'
import { promisify } from 'node:util'

const run = promisify(exec)

// A new feature, written in a hurry. Never mount this router.
export function exportRouter(dataDir) {
  const router = Router()

  router.post('/export', async (req, res) => {
    const name = String(req.body?.name ?? 'export')
    await run(`tar -czf exports/${name}.tar.gz files`, { cwd: dataDir })
    res.send(`<p>Export ${name} is ready.</p>`)
  })

  return router
}
JS
npm test

The whole test suite still passes, all 13 tests. Nothing tests a route that is not mounted, and even once it is mounted, no test exists for it yet. Run the scan again:

Bash
semgrep scan --config rules/ --error --metrics=off src/

Check it worked

The scan exits with an error and reports 3 Code Findings, all in src/routes/export.js: rules.noticeboard-route-without-authorize on the router.post call, rules.noticeboard-exec-with-template-string on the run(...) line, and rules.noticeboard-send-unescaped-input on the res.send line. Semgrep puts the folder name in front of each rule ID. Each finding prints the message you wrote, so the person who wrote the route learns which fix to apply and which part explains why.

Remove the file, and check the scan is clean again:

Bash
rm src/routes/export.js
semgrep scan --config rules/ --error --metrics=off src/

When a finding is a false positive you have checked, add // nosemgrep: noticeboard-route-without-authorize (with the rule ID) at the end of the flagged line, and write why in the line above. Keep those rare and reviewed; every one is a hole in the net.

Step 7 · Run both on every pull request

The guards only help if they run without anyone remembering. Create a GitHub Actions workflow with two jobs: the test suite, and the Semgrep rule tests plus the scan. They run on every pull request and on pushes to main. The workflow can read the code and nothing else, and the checkout does not leave a token behind in the job:

Bash
mkdir -p .github/workflows
cat > .github/workflows/security.yml <<'YAML'
name: Security checks

on:
  pull_request:
  push:
    branches: [main]

permissions:
  contents: read

jobs:
  tests:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
        with:
          persist-credentials: false
      - uses: actions/setup-node@v7
        with:
          node-version: 26
          cache: npm
      - run: npm ci
      - run: npm test

  semgrep:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
        with:
          persist-credentials: false
      - run: pipx install semgrep==1.187.0
      - name: Test the rules
        run: semgrep --test --metrics=off rules/
      - name: Scan the app
        run: semgrep scan --config rules/ --error --metrics=off src/
YAML

The Semgrep job runs the rule tests before the scan on purpose. If someone weakens a rule to silence a finding, its ruleid lines stop matching and the job fails there, in the open, rather than passing quietly. pipx comes preinstalled on GitHub's Ubuntu runners, and the version is pinned so the rules behave the same on your laptop and in CI. For pinning actions to commit SHAs and other workflow hardening, see harden GitHub Actions workflows.

Run the same commands the workflow runs, from a clean install:

Bash
npm ci
npm test
npm run lint:security

To watch it on GitHub, put the project in a private repository of your own and open a pull request that brings the export route back. With the gh CLI signed in:

Bash
git init -b main
git add .
git commit -m "Noticeboard with security tests and Semgrep rules"
gh repo create noticeboard-demo --private --source=. --remote=origin --push
git switch -c add-export
# Re-create src/routes/export.js from the previous step, then:
git add src/routes/export.js
git commit -m "Add export"
git push -u origin add-export
gh pr create --fill

In repository settings, under branches, add a rule for main that requires the tests and semgrep checks to pass, so a failing pull request cannot be merged.

Check it worked

Locally, npm ci installs from the lock file, npm test reports 13 passing tests, and npm run lint:security prints 3/3: ✓ All tests passed followed by a scan with 0 findings. On GitHub, the pull request shows two checks: tests passes and semgrep fails at "Scan the app" with the same three findings you saw in the previous step.

Step 8 · Write a one-page record of what was fixed

Tests and rules say what must stay true. They do not say why, and in a year nobody will remember why GET /posts/:id answers 404 rather than 403, or why page() throws. Write it down next to the code, one entry per fix, with the guard that keeps it. Keep it to a page; anything longer stops being read.

Bash
cat > SECURITY-FIXES.md <<'MD'
# Noticeboard security fixes

Each entry: the flaw, the OWASP Top 10:2025 category, the fix, and what keeps it fixed.
Tests live in test/security/regressions.test.js. Rules live in rules/ and run in CI.

- **Error pages showed stack traces** (A10). The handler logs details with a reference
  and shows only the reference. Guard: test "part 1 (A10)".
- **Drafts readable by changing the ID; role taken from a cookie** (A01). Ownership is
  checked in the SQL; roles come from the database; not-yours is 404 so drafts do not
  leak by existence. Guards: tests "part 2 (A01)"; rule noticeboard-route-without-authorize.
- **Titles, comments and search terms rendered as markup** (A05). Every page is built
  with html`` and page(), which refuses unescaped bodies. Guards: tests "part 3 (A05)";
  rule noticeboard-send-unescaped-input.
- **Cross-site forms could delete posts; GET could delete** (A01). SameSite=Lax cookie,
  Sec-Fetch-Site and Origin checks on unsafe methods, no state change on GET.
  Guard: test "part 4 (A01)".
- **Link preview fetched internal addresses** (A01). Removed from this trimmed copy;
  see part 5 for the allow-list and address checks.
- **Attachment names joined onto a path; file names passed to a shell** (A01, A05).
  Opaque file IDs, sendFile with a root, execFile with an argument array.
  Guards: tests "part 6"; rule noticeboard-exec-with-template-string.
- **Session fixation, weak cookie flags, sign-out only in the browser** (A07). New ID at
  sign-in, __Host- cookie with HttpOnly, Secure and SameSite, idle and absolute timeouts,
  server-side sign-out. Guards: tests "part 7 (A07)".

Known and not fixed here: passwords are stored in plain text (see Argon2id tutorial).

Last reviewed: replace with today's date and your name.
MD
grep -c '^- \*\*' SECURITY-FIXES.md

The last two lines matter as much as the rest. A record that lists only what was fixed reads as "secure", and the plain-text passwords say otherwise. The review line tells the next reader how stale the page is; replace the placeholder with the date and your name.

If your team works in more than one language, write the record in the one your reviewers read most easily. Its job is to be read in a pull request, not to impress an auditor.

Check it worked

The grep prints 7, one entry for each group of fixes. Open SECURITY-FIXES.md and check that every entry names a guard you can find: a test name in test/security/regressions.test.js or a rule ID in rules/. The part 5 entry is the honest exception and says so.

Step 9 · Clean up the series

This is the end of the series, so the practice app goes. The next command deletes ~/noticeboard-demo and, if you moved your earlier copy aside in step 1, ~/noticeboard-demo-earlier-parts, including any .env file and database in them. Copy anything you want to keep, such as the rules folder or SECURITY-FIXES.md, somewhere else first.

Bash
cd ~
rm -rf ~/noticeboard-demo ~/noticeboard-demo-earlier-parts

If you will not use Semgrep again soon, remove it too:

Bash
pipx uninstall semgrep

If you created the GitHub repository in the pull request step, delete it as well. gh asks you to type the repository name to confirm, and needs the delete_repo scope, which gh auth refresh -s delete_repo adds:

Bash
gh repo delete noticeboard-demo

If you started the app from an earlier part in a second terminal, stop it with Ctrl+C there.

Check it worked

Bash
if [ -e ~/noticeboard-demo ] || [ -e ~/noticeboard-demo-earlier-parts ]; then echo "A Noticeboard folder is still there"; else echo "Noticeboard removed"; fi

The command prints Noticeboard removed. semgrep --version now reports that the command is not found, and on GitHub, the repository page returns 404.

Next steps

The app is gone, but the method is not: for each flaw you fix, keep the test that proved it, write a rule for the shape of code that caused it, and run both on every pull request.

  • Add Semgrep's maintained rule sets alongside your own rules: /tutorials/find-security-bugs-with-semgrep
  • Build out the CI side with a Node.js version matrix and caching: /tutorials/run-node-tests-in-github-actions
  • Lock down the workflow itself, with pinned actions and least-privilege tokens: /tutorials/harden-github-actions-workflows
  • Fix the flaw this series left in place, plain-text passwords: /tutorials/hash-passwords-with-argon2id

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.