Skip to main content

Security and hardening · Intermediate · 24 min

Fix command injection and path traversal in a Node 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 Noticeboard's thumbnail route runs shell commands hidden in a file name and its attachment route reads files outside its folder, then fix both with execFile, an allow-list, a contained path check, opaque file IDs and a low-privilege service user.

On this page

SQL is not the only language an app can be tricked into speaking. Two older mistakes still turn up in Node code reviews. The first is command injection: the app builds a shell command as a string, a user-supplied value lands inside it, and characters such as ; or | start a second command the developer never wrote. The second is path traversal: the app joins a user-supplied name onto a folder, and ../ walks out of that folder to any file the process can read.

Both live in Noticeboard, the practice app from this series, in the two attachment routes. POST /files/thumbnail hands a file name to a shell to make a thumbnail, and GET /files reads whatever name the URL asks for. In this part you prove both flaws with tests that use harmless markers, then fix them in layers: no shell, an allow-list for options, a check that every resolved path stays inside the attachments folder, files stored under random IDs instead of their names, and a service user that could not read your secrets even if something got through.

SQL injection has its own tutorial, prevent SQL injection in Python and Node.js; Noticeboard's queries already use parameters. As in every part, practise only on your own copy of the app on 127.0.0.1, and never point these checks at a system you do not own or have written permission to test.

Step 1 · Get the attachment code this part changes

The attachment routes live in their own module, attachments.js, an Express router, so this part changes one file and leaves the rest of the app alone. Work in the demo folder. If you are starting here, the first commands create a minimal package.json with part 1's npm test script; if you followed the earlier parts, they leave yours as it is:

Bash
mkdir -p ~/noticeboard-demo/test/security
cd ~/noticeboard-demo
if [ ! -f package.json ]; then
  npm init -y > /dev/null
  npm pkg set type=module 'scripts.test=node --test "test/*.test.js"'
fi
npm install express@5.3.0 --save-exact

Real thumbnailers such as ImageMagick are large installs, so Noticeboard uses a stand-in with the same shape: a command-line program that takes an input file, a --width option and an --out-dir option, and writes a small text "thumbnail". It parses its arguments with util.parseArgs in strict mode, so an unknown option is an error rather than a silent surprise. Create thumbnailer.js:

Bash
cat > thumbnailer.js <<'JS'
// A stand-in thumbnailer with the command-line shape of a real one.
import { parseArgs } from 'node:util'
import { readFile, writeFile } from 'node:fs/promises'
import path from 'node:path'

const { values, positionals } = parseArgs({
  allowPositionals: true,
  options: {
    width: { type: 'string', default: '120' },
    'out-dir': { type: 'string', default: '.' },
  },
})
if (positionals.length !== 1) {
  console.error('usage: thumbnailer.js <input> [--width N] [--out-dir DIR]')
  process.exit(2)
}
const [input] = positionals
const firstLine = (await readFile(input, 'utf8')).split('\n')[0]
const out = path.join(values['out-dir'], `${path.basename(input)}-${values.width}.txt`)
await writeFile(out, `thumbnail ${values.width}px of ${path.basename(input)}: ${firstLine}\n`)
console.log(out)
JS

In part 1 the two attachment routes sit inline in app.js, and the thumbnail route shells out to cp files/${name} thumbnails/${name} as a stand-in. This part moves both routes into their own router and swaps that cp for a thumbnailer with real options, keeping both flaws. Read the two FLAW comments; they are what this part fixes. The router takes the app's sign-in middleware as signedIn and puts it on the thumbnail route, as part 1 did; GET /files stays public, as it was. The db argument is not used yet; step 5 needs it. Create attachments.js:

Bash
cat > attachments.js <<'JS'
import express from 'express'
import { exec } from 'node:child_process'
import { readFile } from 'node:fs/promises'
import path from 'node:path'
import { promisify } from 'node:util'

const run = promisify(exec)
const thumbnailer = path.join(import.meta.dirname, 'thumbnailer.js')

export function attachmentsRouter({ db, dataDir, signedIn }) {
  const router = express.Router()
  router.use(express.json({ limit: '10kb' }))

  router.get('/files', async (req, res) => {
    // FLAW (A01 path traversal): joins a name from the URL onto the folder.
    const file = path.join(dataDir, 'files', String(req.query.name ?? ''))
    res.type('text/plain').send(await readFile(file, 'utf8'))
  })

  router.post('/files/thumbnail', signedIn, async (req, res) => {
    // FLAW (A05 command injection): the name and width are pasted into a shell command.
    const name = String(req.body?.name ?? '')
    const width = String(req.body?.width ?? '120')
    const { stdout } = await run(
      `"${process.execPath}" "${thumbnailer}" files/${name} --out-dir thumbnails --width ${width}`,
      { cwd: dataDir },
    )
    res.json({ thumbnail: stdout.trim() })
  })

  return router
}
JS

If your app.js from part 1 still has its own GET /files and POST /files/thumbnail handlers, delete those two and mount the router in their place, before the error handler: app.use(attachmentsRouter({ db, dataDir, signedIn })), with import { attachmentsRouter } from './attachments.js' at the top. Passing signedIn keeps the thumbnail route for signed-in users only, as it was in part 1; leave it out and Express refuses to start rather than serve the route to everyone. The tests below do not depend on that edit; they mount the router on a small app of their own, with a stand-in signedIn that lets every request through.

The test helper builds that small app: a fresh data folder in your system's temp directory with files/ and thumbnails/ inside, an in-memory database, a 404 handler and an error handler that logs one line and tells the visitor nothing. Create test/attachments-helpers.js and two baseline tests in test/attachments.test.js:

Bash
cat > test/attachments-helpers.js <<'JS'
import express from 'express'
import { DatabaseSync } from 'node:sqlite'
import { mkdtemp, mkdir, writeFile, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import path from 'node:path'
import { attachmentsRouter } from '../attachments.js'

export async function startAttachments() {
  const dataDir = await mkdtemp(path.join(tmpdir(), 'noticeboard-files-'))
  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 db = new DatabaseSync(':memory:')

  const app = express()
  // Tests call the thumbnail route directly, so sign-in always passes here.
  app.use(attachmentsRouter({ db, dataDir, signedIn: (req, res, next) => next() }))
  app.use((req, res) => res.status(404).type('text/plain').send('Not found'))
  app.use((err, req, res, next) => {
    console.error(`[error] ${req.method} ${req.path}: ${err.message.split('\n')[0]}`)
    res.status(500).type('text/plain').send('Something went wrong')
  })

  const server = await new Promise((resolve, reject) => {
    const s = app.listen(0, '127.0.0.1', (err) => (err ? reject(err) : resolve(s)))
  })
  return {
    base: `http://127.0.0.1:${server.address().port}`,
    dataDir,
    db,
    async close() {
      server.closeAllConnections()
      await new Promise((resolve) => server.close(resolve))
      db.close()
      await rm(dataDir, { recursive: true, force: true })
    },
  }
}

export async function postJson(url, body) {
  const res = await fetch(url, {
    method: 'POST',
    headers: { 'content-type': 'application/json' },
    body: JSON.stringify(body),
  })
  return { status: res.status, text: await res.text() }
}
JS
cat > test/attachments.test.js <<'JS'
import { test, before, after } from 'node:test'
import assert from 'node:assert/strict'
import { readFile } from 'node:fs/promises'
import path from 'node:path'
import { startAttachments, postJson } from './attachments-helpers.js'

let app
before(async () => { app = await startAttachments() })
after(() => app.close())

test('an attachment can be read', async () => {
  const res = await fetch(`${app.base}/files?name=welcome.txt`)
  assert.equal(res.status, 200)
  assert.match(await res.text(), /Welcome to Noticeboard/)
})

test('a thumbnail can be made', async () => {
  const { status, text } = await postJson(`${app.base}/files/thumbnail`, { name: 'welcome.txt', width: '120' })
  assert.equal(status, 200)
  const { thumbnail } = JSON.parse(text)
  const made = await readFile(path.join(app.dataDir, thumbnail), 'utf8')
  assert.match(made, /thumbnail 120px of welcome\.txt/)
})
JS

Check it worked

Run the baseline tests:

Bash
node --test test/attachments.test.js

The summary shows pass 2 and fail 0. Both features work; that is exactly why flaws like these survive review. A test that only checks the happy path cannot see them.

Step 2 · Write tests that prove both flaws

Each test states a rule and uses a marker that does no harm. For command injection the marker is touch nb-marker-42: if a shell runs it, an empty file of that name appears in the throwaway data folder, and the test fails. For path traversal the marker is a file outside files/ that contains nb-marker-42: if its text comes back, the test fails.

The command tests try the two values that reach the shell, the name and the width. In a shell, ; ends one command and starts the next, and # turns the rest of the line into a comment, which keeps the injected command tidy. A third test asks for a width the app never offers:

Bash
cat > test/security/attachments-command.test.js <<'JS'
import { test, before, after } from 'node:test'
import assert from 'node:assert/strict'
import { existsSync } from 'node:fs'
import path from 'node:path'
import { startAttachments, postJson } from '../attachments-helpers.js'

let app
before(async () => { app = await startAttachments() })
after(() => app.close())

test('a file name cannot run a shell command', async () => {
  await postJson(`${app.base}/files/thumbnail`, { name: 'welcome.txt; touch nb-marker-42 #', width: '120' })
  assert.equal(existsSync(path.join(app.dataDir, 'nb-marker-42')), false, 'the shell ran touch from the name')
})

test('a width cannot run a shell command', async () => {
  await postJson(`${app.base}/files/thumbnail`, { name: 'welcome.txt', width: '120; touch nb-marker-43 #' })
  assert.equal(existsSync(path.join(app.dataDir, 'nb-marker-43')), false, 'the shell ran touch from the width')
})

test('a width outside the allow-list is refused', async () => {
  const { status } = await postJson(`${app.base}/files/thumbnail`, { name: 'welcome.txt', width: '9999' })
  assert.ok(status >= 400 && status < 500, `width 9999 answered ${status}`)
})
JS

The path tests set up four ways out of the folder: a plain ../, a sibling folder whose name starts with files (it catches a common broken fix, shown in step 4), an absolute path, and a symbolic link inside files/ that points outside it. Every one must be answered with 400 or 404 and no marker:

Bash
cat > test/security/attachments-path.test.js <<'JS'
import { test, before, after } from 'node:test'
import assert from 'node:assert/strict'
import { mkdir, writeFile, symlink } from 'node:fs/promises'
import path from 'node:path'
import { startAttachments } from '../attachments-helpers.js'

let app
before(async () => {
  app = await startAttachments()
  const dir = app.dataDir
  await writeFile(path.join(dir, 'private.txt'), 'nb-marker-42 private\n')
  await mkdir(path.join(dir, 'files-old'))
  await writeFile(path.join(dir, 'files-old', 'leak.txt'), 'nb-marker-42 old folder\n')
  await symlink(path.join(dir, 'private.txt'), path.join(dir, 'files', 'shortcut.txt'))
})
after(() => app.close())

async function assertRefused(name) {
  const res = await fetch(`${app.base}/files?${new URLSearchParams({ name })}`)
  const text = await res.text()
  assert.ok(!text.includes('nb-marker-42'), `${name} returned a file from outside files/`)
  assert.ok([400, 404].includes(res.status), `${name} answered ${res.status}`)
}

test('a ../ name cannot leave the folder', () => assertRefused('../private.txt'))
test('a sibling folder with the same prefix is refused', () => assertRefused('../files-old/leak.txt'))
test('an absolute path is refused', () => assertRefused(path.join(app.dataDir, 'private.txt')))
test('a symlink that points outside the folder is refused', () => assertRefused('shortcut.txt'))
JS

Run both files. Node expands the quoted pattern itself, so it works the same in any shell:

Bash
node --test "test/security/attachments-*.test.js"

Check it worked

The run fails, which is the result you want: pass 0 and fail 7. The messages name each flaw: the shell ran touch from the name, the shell ran touch from the width, and ../private.txt returned a file from outside files/. The absolute path test fails differently, with answered 500: path.join glued the absolute path onto the folder, so the read failed with a server error rather than leaking. Remember that one; the fix in step 4 uses path.resolve, which treats an absolute path very differently.

Step 3 · Run the thumbnailer without a shell

exec hands one string to /bin/sh (or cmd.exe on Windows), and the shell decides where each argument starts and ends. Any ;, |, &&, $( ) or backtick in user input is a command to it. Escaping those characters by hand is a losing game: the rules differ between shells and every gap is a new hole.

execFile skips the shell. You give it a program and an array of arguments, and the operating system passes each array item to the program as one argument, whatever characters it contains. welcome.txt; touch nb-marker-42 # becomes one strange file name that does not exist. The same is true of spawn and execFileSync, as long as you never add shell: true: that option puts the shell back, and with it the flaw. On Windows, .bat and .cmd files can only be started through a shell, so do not call them with user input at all.

The fix has four more parts. The width is checked against an allow-list, so the thumbnailer only ever sees values you chose. A -- before the file name tells the program that everything after it is a file, never an option, so a name such as --out-dir=/tmp cannot change its behaviour. env: {} gives the child process no environment variables, so it never sees your secrets. And a timeout and an output limit stop a stuck or noisy tool from tying up the app.

Replace attachments.js. The GET /files route is unchanged for now:

Bash
cat > attachments.js <<'JS'
import express from 'express'
import { execFile } from 'node:child_process'
import { readFile } from 'node:fs/promises'
import path from 'node:path'
import { promisify } from 'node:util'

const runFile = promisify(execFile)
const thumbnailer = path.join(import.meta.dirname, 'thumbnailer.js')
const WIDTHS = new Set(['120', '320', '640'])

export function attachmentsRouter({ db, dataDir, signedIn }) {
  const router = express.Router()
  router.use(express.json({ limit: '10kb' }))

  router.get('/files', async (req, res) => {
    // FLAW (A01 path traversal): joins a name from the URL onto the folder.
    const file = path.join(dataDir, 'files', String(req.query.name ?? ''))
    res.type('text/plain').send(await readFile(file, 'utf8'))
  })

  router.post('/files/thumbnail', signedIn, async (req, res) => {
    const name = String(req.body?.name ?? '')
    const width = String(req.body?.width ?? '120')
    if (!WIDTHS.has(width)) return res.status(400).json({ error: 'width must be 120, 320 or 640' })
    // No shell: each array item reaches the thumbnailer as exactly one argument.
    const { stdout } = await runFile(
      process.execPath,
      [thumbnailer, '--width', width, '--out-dir', 'thumbnails', '--', path.join('files', name)],
      { cwd: dataDir, env: {}, timeout: 10_000, maxBuffer: 64 * 1024 },
    )
    res.json({ thumbnail: stdout.trim() })
  })

  return router
}
JS
node --test test/security/attachments-command.test.js
node --test test/attachments.test.js

Then make sure no shell call is left in the file:

Bash
grep -nE "exec\(|shell: *true" attachments.js || echo "No shell calls left"

Check it worked

The command tests show pass 3 and fail 0, and the baseline still shows pass 2. The log has a line like [error] POST /files/thumbnail: Command failed: ... from the first test: the thumbnailer was asked for a file literally named welcome.txt; touch nb-marker-42 #, could not find it, and no marker file appeared. The grep prints No shell calls left.

The path tests still fail, because the thumbnail route also trusts the name: ../private.txt would make a thumbnail of the private file. The next step fixes both routes.

Step 4 · Keep every path inside the attachments folder

path.join(folder, name) does not check anything. It joins and tidies, and files/../private.txt tidies to private.txt. The safe pattern has three moves:

  1. Resolve the name against the folder with path.resolve. Unlike join, it turns any input into one absolute path, and an absolute input wins outright: path.resolve('/data/files', '/etc/hosts') is /etc/hosts. That is why you must check the result, never the input.
  2. Check containment with path.relative(folder, target). If the answer starts with .. followed by a separator, or is itself absolute (on Windows, a different drive), the target is outside. Do not use target.startsWith(folder): /data/files-old/leak.txt starts with /data/files, which is exactly what the sibling-folder test catches.
  3. Check again after following links with fs.realpath, which returns the path with every symbolic link resolved. A link inside the folder that points outside passes the first check and fails this one. The folder itself goes through realpath too, because on macOS the temp folder is a link (/var points to /private/var).

Names with a NUL byte are refused up front, because Node throws on them and that would be a 500 rather than a clean 404. Replace attachments.js:

Bash
cat > attachments.js <<'JS'
import express from 'express'
import { execFile } from 'node:child_process'
import { readFile, realpath } from 'node:fs/promises'
import path from 'node:path'
import { promisify } from 'node:util'

const runFile = promisify(execFile)
const thumbnailer = path.join(import.meta.dirname, 'thumbnailer.js')
const WIDTHS = new Set(['120', '320', '640'])

function isInside(folder, target) {
  const rel = path.relative(folder, target)
  return rel !== '' && rel !== '..' && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel)
}

// Returns the real path of a file inside folder, or null if it is missing or outside.
export async function insideFolder(folder, name) {
  if (name.includes('\0')) return null
  const base = await realpath(folder)
  const target = path.resolve(base, name)
  if (!isInside(base, target)) return null
  try {
    const real = await realpath(target)
    return isInside(base, real) ? real : null
  } catch (err) {
    if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return null
    throw err
  }
}

export function attachmentsRouter({ db, dataDir, signedIn }) {
  const filesDir = path.join(dataDir, 'files')
  const router = express.Router()
  router.use(express.json({ limit: '10kb' }))

  router.get('/files', async (req, res) => {
    const file = await insideFolder(filesDir, String(req.query.name ?? ''))
    if (!file) return res.status(404).type('text/plain').send('Not found')
    res.type('text/plain').send(await readFile(file, 'utf8'))
  })

  router.post('/files/thumbnail', signedIn, async (req, res) => {
    const width = String(req.body?.width ?? '120')
    if (!WIDTHS.has(width)) return res.status(400).json({ error: 'width must be 120, 320 or 640' })
    const file = await insideFolder(filesDir, String(req.body?.name ?? ''))
    if (!file) return res.status(404).json({ error: 'Not found' })
    const { stdout } = await runFile(
      process.execPath,
      [thumbnailer, '--width', width, '--out-dir', 'thumbnails', '--', file],
      { cwd: dataDir, env: {}, timeout: 10_000, maxBuffer: 64 * 1024 },
    )
    res.json({ thumbnail: stdout.trim() })
  })

  return router
}
JS
node --test "test/security/attachments-*.test.js"
node --test test/attachments.test.js

Every refusal is a plain 404. The visitor learns nothing about which check failed or whether a file exists outside the folder.

Check it worked

The security run shows pass 7 and fail 0, and the baseline shows pass 2. To see the sibling-folder trap for yourself, change isInside to return target.startsWith(folder) and run the path tests again: a sibling folder with the same prefix is refused fails. Put the function back before you go on.

Step 5 · Store attachments under opaque IDs

The containment check works, but the design still asks the file system a question chosen by a stranger. The stronger fix removes the question: store each upload under a random ID that the server makes, keep the person's file name only as data in the database, and look files up by ID. Then there is no user-supplied path left to check.

Three details make this work. The ID is 16 random bytes written as 32 hex characters, so it cannot be guessed and it has no /, . or other special characters, and the route refuses anything that does not match that exact pattern before it touches the database. The file is written with the wx flag, so an existing file is never overwritten. And the original name goes back to the browser only in the Content-Disposition header, through Express's res.attachment, which encodes it safely. That matters for names such as Ìpàdé ọjọ́ Ẹtì.txt or ስብሰባ.txt: people in Lagos or Addis Ababa name files in their own languages and scripts, and the encoded header keeps those names intact on download without them ever touching a path.

The containment check stays in place as defence in depth. Replace attachments.js with the final version. The routes become GET /files/:id and POST /files/:id/thumbnail:

Bash
cat > attachments.js <<'JS'
import express from 'express'
import { execFile } from 'node:child_process'
import { randomBytes } from 'node:crypto'
import { readFile, realpath, writeFile } from 'node:fs/promises'
import path from 'node:path'
import { promisify } from 'node:util'

const runFile = promisify(execFile)
const thumbnailer = path.join(import.meta.dirname, 'thumbnailer.js')
const WIDTHS = new Set(['120', '320', '640'])
const ID_PATTERN = /^[0-9a-f]{32}$/

function isInside(folder, target) {
  const rel = path.relative(folder, target)
  return rel !== '' && rel !== '..' && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel)
}

// Returns the real path of a file inside folder, or null if it is missing or outside.
export async function insideFolder(folder, name) {
  if (name.includes('\0')) return null
  const base = await realpath(folder)
  const target = path.resolve(base, name)
  if (!isInside(base, target)) return null
  try {
    const real = await realpath(target)
    return isInside(base, real) ? real : null
  } catch (err) {
    if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return null
    throw err
  }
}

function createTable(db) {
  db.exec(`CREATE TABLE IF NOT EXISTS attachments (
    id            TEXT PRIMARY KEY,
    original_name TEXT NOT NULL,
    created_at    TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
  )`)
}

// Saves content under a random ID. The original name is kept as data only.
export async function storeAttachment({ db, dataDir }, originalName, content) {
  createTable(db)
  const id = randomBytes(16).toString('hex')
  await writeFile(path.join(dataDir, 'files', id), content, { flag: 'wx' })
  db.prepare('INSERT INTO attachments (id, original_name) VALUES (?, ?)').run(id, String(originalName))
  return id
}

export function attachmentsRouter({ db, dataDir, signedIn }) {
  createTable(db)
  const filesDir = path.join(dataDir, 'files')
  const findAttachment = db.prepare('SELECT id, original_name FROM attachments WHERE id = ?')
  const router = express.Router()
  router.use(express.json({ limit: '10kb' }))

  async function lookup(id) {
    if (!ID_PATTERN.test(id)) return null
    const row = findAttachment.get(id)
    if (!row) return null
    const file = await insideFolder(filesDir, row.id)
    return file ? { ...row, file } : null
  }

  router.get('/files/:id', async (req, res) => {
    const found = await lookup(req.params.id)
    if (!found) return res.status(404).type('text/plain').send('Not found')
    res.attachment(found.original_name)
    res.set('X-Content-Type-Options', 'nosniff')
    res.send(await readFile(found.file))
  })

  router.post('/files/:id/thumbnail', signedIn, async (req, res) => {
    const width = String(req.body?.width ?? '120')
    if (!WIDTHS.has(width)) return res.status(400).json({ error: 'width must be 120, 320 or 640' })
    const found = await lookup(req.params.id)
    if (!found) return res.status(404).json({ error: 'Not found' })
    const { stdout } = await runFile(
      process.execPath,
      [thumbnailer, '--width', width, '--out-dir', 'thumbnails', '--', found.file],
      { cwd: dataDir, env: {}, timeout: 10_000, maxBuffer: 64 * 1024 },
    )
    res.json({ thumbnail: stdout.trim() })
  })

  return router
}
JS

The helper now stores the welcome file through storeAttachment and hands its ID to the tests. The baseline tests change with the routes, and a new security file checks the ID routes directly, including an upload whose own name tries to climb out of the folder. Replace the helper and the baseline, and add the new tests:

Bash
cat > test/attachments-helpers.js <<'JS'
import express from 'express'
import { DatabaseSync } from 'node:sqlite'
import { mkdtemp, mkdir, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import path from 'node:path'
import { attachmentsRouter, storeAttachment } from '../attachments.js'

export async function startAttachments() {
  const dataDir = await mkdtemp(path.join(tmpdir(), 'noticeboard-files-'))
  await mkdir(path.join(dataDir, 'files'))
  await mkdir(path.join(dataDir, 'thumbnails'))
  const db = new DatabaseSync(':memory:')
  const welcomeId = await storeAttachment({ db, dataDir }, 'welcome.txt', 'Welcome to Noticeboard.\n')

  const app = express()
  // Tests call the thumbnail route directly, so sign-in always passes here.
  app.use(attachmentsRouter({ db, dataDir, signedIn: (req, res, next) => next() }))
  app.use((req, res) => res.status(404).type('text/plain').send('Not found'))
  app.use((err, req, res, next) => {
    console.error(`[error] ${req.method} ${req.path}: ${err.message.split('\n')[0]}`)
    res.status(500).type('text/plain').send('Something went wrong')
  })

  const server = await new Promise((resolve, reject) => {
    const s = app.listen(0, '127.0.0.1', (err) => (err ? reject(err) : resolve(s)))
  })
  return {
    base: `http://127.0.0.1:${server.address().port}`,
    dataDir,
    db,
    welcomeId,
    async close() {
      server.closeAllConnections()
      await new Promise((resolve) => server.close(resolve))
      db.close()
      await rm(dataDir, { recursive: true, force: true })
    },
  }
}

export async function postJson(url, body) {
  const res = await fetch(url, {
    method: 'POST',
    headers: { 'content-type': 'application/json' },
    body: JSON.stringify(body),
  })
  return { status: res.status, text: await res.text() }
}
JS
cat > test/attachments.test.js <<'JS'
import { test, before, after } from 'node:test'
import assert from 'node:assert/strict'
import { readFile } from 'node:fs/promises'
import path from 'node:path'
import { storeAttachment } from '../attachments.js'
import { startAttachments, postJson } from './attachments-helpers.js'

let app
before(async () => { app = await startAttachments() })
after(() => app.close())

test('an attachment can be read by its ID', async () => {
  const res = await fetch(`${app.base}/files/${app.welcomeId}`)
  assert.equal(res.status, 200)
  assert.match(await res.text(), /Welcome to Noticeboard/)
  assert.match(res.headers.get('content-disposition'), /filename="?welcome\.txt"?/)
})

test('a file name in any script survives the download header', async () => {
  const id = await storeAttachment(app, 'Ìpàdé ọjọ́ Ẹtì.txt', 'Agenda\n')
  const res = await fetch(`${app.base}/files/${id}`)
  await res.text()
  const header = res.headers.get('content-disposition')
  assert.match(header, /filename\*=UTF-8''/)
  assert.ok(decodeURIComponent(header.split("UTF-8''")[1]).startsWith('Ìpàdé ọjọ́ Ẹtì.txt'))
})

test('a thumbnail can be made by ID', async () => {
  const { status, text } = await postJson(`${app.base}/files/${app.welcomeId}/thumbnail`, { width: '320' })
  assert.equal(status, 200)
  const { thumbnail } = JSON.parse(text)
  assert.equal(thumbnail, path.join('thumbnails', `${app.welcomeId}-320.txt`))
  assert.match(await readFile(path.join(app.dataDir, thumbnail), 'utf8'), /thumbnail 320px/)
})
JS
cat > test/security/attachments-ids.test.js <<'JS'
import { test, before, after } from 'node:test'
import assert from 'node:assert/strict'
import { existsSync } from 'node:fs'
import { writeFile, readdir } from 'node:fs/promises'
import { randomBytes } from 'node:crypto'
import path from 'node:path'
import { storeAttachment } from '../../attachments.js'
import { startAttachments, postJson } from '../attachments-helpers.js'

let app
before(async () => {
  app = await startAttachments()
  await writeFile(path.join(app.dataDir, 'private.txt'), 'nb-marker-42 private\n')
})
after(() => app.close())

test('an ID that is not 32 hex characters is refused', async () => {
  for (const id of ['../private.txt', '..%2Fprivate.txt', 'welcome.txt', `${app.welcomeId}x`]) {
    const res = await fetch(`${app.base}/files/${encodeURIComponent(id)}`)
    const text = await res.text()
    assert.equal(res.status, 404, `${id} answered ${res.status}`)
    assert.ok(!text.includes('nb-marker-42'), `${id} leaked a file`)
  }
})

test('a well-formed ID that was never stored is refused', async () => {
  const res = await fetch(`${app.base}/files/${randomBytes(16).toString('hex')}`)
  assert.equal(res.status, 404)
})

test('an upload name never becomes a path', async () => {
  const id = await storeAttachment(app, '../../private.txt', 'harmless content\n')
  assert.deepEqual((await readdir(path.join(app.dataDir, 'files'))).sort(), [app.welcomeId, id].sort())
  const res = await fetch(`${app.base}/files/${id}`)
  assert.equal(await res.text(), 'harmless content\n')
})

test('the thumbnail route still refuses injected widths', async () => {
  const { status } = await postJson(`${app.base}/files/${app.welcomeId}/thumbnail`, {
    width: '120; touch nb-marker-43 #',
  })
  assert.equal(status, 400)
  assert.equal(existsSync(path.join(app.dataDir, 'nb-marker-43')), false)
})
JS
node --test "test/security/attachments-*.test.js"
node --test test/attachments.test.js

If you mounted the router in your part 1 app.js, two things from part 1 no longer fit the new routes. First, the test attachments are served from the files folder in test/app.test.js still asks for /files?name=welcome.txt, a route that no longer exists, so it now gets a 404 and fails. Delete that test from test/app.test.js; test/attachments.test.js covers reading an attachment by its ID. Second, files already in data/files/ under their own names, such as part 1's welcome.txt, have no row in the attachments table, so the app can no longer serve them. To keep one, store its content again with storeAttachment, which gives it an ID, and delete the old copy.

Then run the whole suite:

Bash
npm test

Check it worked

The security run shows pass 11 and fail 0, and the baseline shows pass 3. npm test ends with fail 0: if you are starting here it runs only test/attachments.test.js, and if you followed part 1 it runs your remaining test/app.test.js tests as well. The an upload name never becomes a path test lists the files/ folder and finds only the two random IDs: the name ../../private.txt was stored as text in the database and nothing else.

The step 2 tests still pass, now because the name-based routes are gone and every request to them gets a 404. Keep them. If someone adds a ?name= route back one day, they fail again and say why.

Step 6 · Run the service as a low-privilege user

Every fix so far is in the code, and code changes. The last layer is in the operating system: run Noticeboard, and the thumbnailer it starts, as a user that owns nothing of value. Then a flaw you have not found yet can only reach what that user can reach, which is the data folder and not your home directory, your SSH keys or your .env.

Create a system account for the service. It has no home directory and no login shell, so nobody can sign in as it. The id check makes the command safe to run twice:

Bash
id noticeboard > /dev/null 2>&1 || sudo useradd --system --no-create-home --shell /usr/sbin/nologin noticeboard
id noticeboard

If you are starting here and have no .env yet, create one the way part 1 does, with a random demo password in SEED_PASSWORD and private from the moment it exists:

Bash
cd ~/noticeboard-demo
if [ ! -f .env ]; then
  (umask 077 && node -p "'SEED_PASSWORD=' + require('node:crypto').randomBytes(12).toString('hex')" > .env)
fi
ls -l .env

Now try to read your secrets as the service user:

Bash
sudo -u noticeboard cat ~/noticeboard-demo/.env

Child processes run as the same user as the app, so this one account covers the thumbnailer too. Do not run the web app as root so that it can switch users per command with the uid and gid options of execFile: a flaw in a root process is a flaw with root's reach. When you deploy, give the service its own user in its systemd unit, make the file system read-only for it and let it write only to its data folder. These are the lines that matter in the [Service] section; run an app as a systemd service covers the whole unit, and sandbox a systemd service goes further:

INI
[Service]
User=noticeboard
Group=noticeboard
NoNewPrivileges=yes
ProtectSystem=strict
ProtectHome=yes
ReadWritePaths=/var/lib/noticeboard

ProtectSystem=strict mounts the whole file system read-only for the service, ProtectHome=yes hides every home directory from it, and ReadWritePaths then opens the one folder it may change. ReadWritePaths on its own restricts nothing: without ProtectSystem=strict the service can still write anywhere the noticeboard user can. Because of ProtectHome=yes, install the deployed app outside /home, for example in /opt/noticeboard, not in ~/noticeboard-demo. If you host on a small VPS with a few hundred megabytes of RAM, these settings cost nothing to run; they are a few lines of configuration.

Check it worked

id noticeboard prints a line such as uid=999(noticeboard) gid=999(noticeboard) groups=999(noticeboard); the numbers vary. ls -l .env shows -rw-------, readable by you alone. The sudo -u noticeboard cat command fails with Permission denied, either on .env itself or on your home directory: an injected command running as this user would hit the same wall.

Nothing later in the series uses the noticeboard user, so remove it now. ~/noticeboard-demo stays; part 8 removes it.

Bash
sudo userdel noticeboard
id noticeboard > /dev/null 2>&1 && echo "noticeboard still exists" || echo "noticeboard removed"

The last line prints noticeboard removed.

Next steps

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.