Skip to main content

Security and hardening · Advanced · 32 min

Block server-side request forgery in a link-preview feature

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 link preview reads a loopback admin page and a stand-in cloud metadata service, then fix it with a fetcher that checks the scheme, port and every resolved address, connects only to the address it checked, re-checks each redirect and caps size and time.

On this page

Noticeboard has a link preview. A member pastes a URL, the server fetches the page and sends back its title, and the post shows a neat card instead of a bare link. It is the feature every chat app and social network has, and it hides one of the more serious web flaws: server-side request forgery, or SSRF.

The problem is where the request comes from. The member's browser cannot reach the admin page that only listens on your server's loopback address, the database on the private network, or the cloud metadata service at 169.254.169.254 that hands out the machine's credentials. The server can reach all of them. A preview feature that fetches whatever URL it is given lets a member choose the target and read the answer. The OWASP Top 10:2025 lists SSRF under A01 Broken Access Control for that reason: it is a way round the network's own access rules.

A signed-in user sends a URL to Noticeboard, which can reach a loopback admin page, the cloud metadata address and a private 10.0.0.8 host that the user cannot reach directly
The preview request leaves from inside your network, so the user borrows the server's reach.

In this part you start two local stand-ins next to Noticeboard: an admin page that trusts anything on loopback, and a fake metadata service that serves marker strings in place of credentials. Your tests show the preview reading both. Then you build the fix in layers: decide which addresses are off limits, resolve each name once and check every answer, connect to the address you checked so DNS cannot change its mind, check every redirect again, and cap size and time. The last step adds a firewall rule as a backstop outside the code.

The ground rules from part 1 hold. Everything runs on 127.0.0.1 against your own app and stand-ins. Never point a preview, or any of these tests, at a system you do not own or have written permission to test.

Step 1 · Get the Noticeboard files this part needs

This part adds a preview route to the API you secured in part 2, in ~/noticeboard-demo/api. Go to that folder, creating it if you are starting here:

Bash
mkdir -p ~/noticeboard-demo/api/test/security ~/noticeboard-demo/api/routes ~/noticeboard-demo/api/ssrf
cd ~/noticeboard-demo/api

The next block writes the files from part 2 only where they are missing, then installs Express 5.3. It defines a small shell function, write_if_missing, that leaves an existing file alone and prints kept your <file>, so it is safe to run in the folder you worked in during part 2. If you are starting here, it creates them all. The ~5.3.0 range allows patch releases of 5.3 only:

Bash
write_if_missing() {
  if [ -e "$1" ]; then echo "kept your $1"; cat > /dev/null; else cat > "$1"; echo "wrote $1"; fi
}

write_if_missing 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\""
  },
  "dependencies": {
    "express": "~5.3.0"
  }
}
JSON

write_if_missing 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
}
JS

write_if_missing 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' })
  }
}
JS

write_if_missing 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
}
JS

write_if_missing 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
}
JS

write_if_missing 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}`)
})
JS
npm install express@~5.3.0

Then the shared test helper and the baseline tests, again only where they are missing:

Bash
write_if_missing 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

write_if_missing 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'])
})
JS

Now the new code. routes/preview.js is the link preview as it ships: it fetches the URL and returns the page title and the first 160 characters of text, which is what the card shows under the title. Read the FLAW comment:

Bash
cat > routes/preview.js <<'JS'
import { Router } from 'express'

function summarise(html) {
  const title = /<title[^>]*>([^<]*)<\/title>/i.exec(html)?.[1]?.trim() ?? ''
  const snippet = html.replace(/<[^>]*>/g, ' ').replace(/\s+/g, ' ').trim().slice(0, 160)
  return { title, snippet }
}

export function previewRouter() {
  const router = Router()

  // FLAW (SSRF, A01:2025): fetches any URL a member sends, from inside your network,
  // follows any redirect, reads any amount for any time, and sends the answer back.
  router.post('/', async (req, res) => {
    const response = await fetch(String(req.body?.url ?? ''))
    res.json(summarise(await response.text()))
  })

  return router
}
JS

Replace app.js so it mounts the preview. Two things change from part 2, both marked part 5: createApp takes an options object, which the tests use later, and the preview router sits behind denyByDefault, so only signed-in members can use it. If you have added your own middleware to app.js since part 2, keep your file and add only the lines marked part 5:

Bash
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'
import { previewRouter } from './routes/preview.js' // part 5

export function createApp(db, options = {}) { // part 5: options
  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('/api/preview', previewRouter(options.preview)) // part 5

  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
}
JS

Last, the stand-ins. test/stand-ins.js starts three tiny servers on 127.0.0.1, each on a free port: an internal admin page of the kind many servers run for monitoring scripts, a fake metadata service laid out like the one cloud providers run at 169.254.169.254, and an ordinary public-looking site with three pages that misbehave on purpose. The "credentials" are marker strings, not keys:

Bash
cat > test/stand-ins.js <<'JS'
import { createServer } from 'node:http'

function listen(handler) {
  return new Promise((resolve, reject) => {
    const server = createServer(handler)
    server.once('error', reject)
    server.listen(0, '127.0.0.1', () => resolve(server))
  })
}

// Meant only for scripts on this machine. Like many internal tools, it trusts anyone who can connect.
function internalAdmin(req, res) {
  res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' })
  res.end('<!doctype html><title>Internal admin nb-marker-internal</title><p>Backups: on. Users: 3.</p>')
}

// Laid out like a cloud metadata service. The values are markers, not credentials.
function fakeMetadata(req, res) {
  if (req.url === '/latest/meta-data/iam/security-credentials/noticeboard-role') {
    res.writeHead(200, { 'content-type': 'application/json' })
    return res.end(JSON.stringify({
      AccessKeyId: 'nb-marker-key', SecretAccessKey: 'nb-marker-secret', Token: 'nb-marker-token',
    }))
  }
  res.writeHead(404).end()
}

// An ordinary website. /moved, /huge and /slow misbehave on purpose.
function publicSite(internalUrl) {
  return (req, res) => {
    if (req.url === '/moved') {
      res.writeHead(302, { location: internalUrl })
      return res.end()
    }
    if (req.url === '/huge') {
      res.writeHead(200, { 'content-type': 'text/html' })
      res.write('<!doctype html><title>Huge</title>')
      for (let i = 0; i < 64; i++) res.write('x'.repeat(32 * 1024)) // 2 MB, no Content-Length
      return res.end()
    }
    if (req.url === '/slow') {
      res.writeHead(200, { 'content-type': 'text/html' })
      return res.write('<!doctype html><title>') // and never finishes
    }
    res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' })
    res.end('<!doctype html><html><head><title>Market day moves to Saturday</title></head>' +
      '<body><p>Stalls open at 8am.</p></body></html>')
  }
}

export async function startStandIns() {
  const internal = await listen(internalAdmin)
  const metadata = await listen(fakeMetadata)
  const internalUrl = `http://127.0.0.1:${internal.address().port}/`
  const site = await listen(publicSite(internalUrl))
  const servers = [internal, metadata, site]
  return {
    internal: internalUrl,
    internalPort: internal.address().port,
    metadata: `http://127.0.0.1:${metadata.address().port}`,
    site: `http://127.0.0.1:${site.address().port}`,
    sitePort: site.address().port,
    async close() {
      for (const s of servers) {
        s.closeAllConnections()
        await new Promise((resolve) => s.close(resolve))
      }
    },
  }
}
JS

Check it worked

Bash
npm test

The run passes. If you are starting here, it shows pass 2 and fail 0; if you have the security tests from earlier parts, they pass too. The preview route is mounted but nothing tests it yet.

Step 2 · Prove the flaw with failing tests

Write down what the preview may and may not do, as tests. Most of them run against a small Express app built around previewRouter alone, with a stand-in signed-in user. That keeps the SSRF tests independent of how sign-in works, which part 7 changes. Two more run against the full app.

Two helpers come first. The stand-ins all live on 127.0.0.1, so the tests need a way to say "treat this one port as if it were a public website". The fixed router will take an alsoAllow option for that: a list of exact address:port pairs, empty in the real app. The tests also need names that resolve to chosen addresses, including one whose answer changes between lookups, which is what a DNS rebinding attack does. test/fake-dns.js is a pretend resolver with the same shape as Node's dns.promises.lookup with all: true, and it records every name it is asked for:

Bash
cat > test/fake-dns.js <<'JS'
import { isIP } from 'node:net'

// A pretend resolver. Each name maps to a list of addresses, or to a function that returns one.
export function fakeDns(table) {
  const calls = []
  async function lookup(hostname) {
    calls.push(hostname)
    const entry = table[hostname]
    const addresses = typeof entry === 'function' ? entry() : entry
    if (!addresses) throw Object.assign(new Error(`getaddrinfo ENOTFOUND ${hostname}`), { code: 'ENOTFOUND' })
    return addresses.map((address) => ({ address, family: isIP(address) }))
  }
  lookup.calls = calls
  return lookup
}
JS

Now test/security/ssrf.test.js. Every refused request must answer 400 and must not contain any nb-marker text. The .invalid top-level domain is reserved and never resolves, so names like sneaky.nb.invalid cannot reach any machine even if the fake resolver is bypassed. (Avoid .test here: tools such as Laravel Valet answer every .test name with 127.0.0.1 on a developer's machine.)

Bash
cat > test/security/ssrf.test.js <<'JS'
import { test, before, after } from 'node:test'
import assert from 'node:assert/strict'
import express from 'express'
import { previewRouter } from '../../routes/preview.js'
import { startStandIns } from '../stand-ins.js'
import { fakeDns } from '../fake-dns.js'
import { startApp, signIn } from '../helpers.js'

let stand, mini, base, app
let rebinds = 0
const dns = fakeDns({
  localhost: ['127.0.0.1', '::1'],
  'metadata.nb.invalid': ['169.254.169.254'],
  'sneaky.nb.invalid': ['203.0.113.10', '10.0.0.8'],
  // Public on the first lookup, private on every one after: a DNS rebinding attack.
  'rebind.nb.invalid': () => (rebinds++ === 0 ? ['127.0.0.1'] : ['10.0.0.8']),
})

before(async () => {
  stand = await startStandIns()
  const router = express()
  router.use(express.json())
  router.use((req, res, next) => { req.user = { id: 1, name: 'amara', role: 'member' }; next() })
  router.use('/api/preview', previewRouter({
    lookup: dns,
    alsoAllow: [`127.0.0.1:${stand.sitePort}`], // the stand-in site plays a public website
    timeoutMs: 1500,
  }))
  router.use((err, req, res, next) => res.status(500).json({ error: 'Something went wrong' }))
  mini = await new Promise((resolve) => { const s = router.listen(0, '127.0.0.1', () => resolve(s)) })
  base = `http://127.0.0.1:${mini.address().port}`
  app = await startApp()
})

after(async () => {
  mini.closeAllConnections()
  await new Promise((resolve) => mini.close(resolve))
  await app.close()
  await stand.close()
})

async function preview(url, { to = base, headers = {} } = {}) {
  const res = await fetch(`${to}/api/preview`, {
    method: 'POST',
    headers: { ...headers, 'content-type': 'application/json' },
    body: JSON.stringify({ url }),
    signal: AbortSignal.timeout(4000),
  })
  return { status: res.status, text: await res.text() }
}

function assertBlocked({ status, text }, url) {
  assert.equal(status, 400, `${url} answered ${status}: ${text}`)
  assert.doesNotMatch(text, /nb-marker/, `${url} leaked a marker`)
}

test('SSRF control: an ordinary page still gets a title', async () => {
  const res = await preview(`${stand.site}/`)
  assert.equal(res.status, 200, res.text)
  assert.equal(JSON.parse(res.text).title, 'Market day moves to Saturday')
})

test('SSRF: an admin page on loopback cannot be read', async () => {
  assertBlocked(await preview(stand.internal), stand.internal)
})

test('SSRF: loopback written another way is still refused', async () => {
  const port = stand.internalPort
  for (const url of [
    `http://localhost:${port}/`,
    `http://2130706433:${port}/`,
    `http://0x7f.1:${port}/`,
    `http://[::ffff:127.0.0.1]:${port}/`,
    `http://0.0.0.0:${port}/`,
  ]) assertBlocked(await preview(url), url)
})

test('SSRF: the cloud metadata service cannot be read', async () => {
  for (const url of [
    `${stand.metadata}/latest/meta-data/iam/security-credentials/noticeboard-role`,
    'http://metadata.nb.invalid/latest/meta-data/',
  ]) assertBlocked(await preview(url), url)
})

test('SSRF: only http and https links are fetched', async () => {
  assertBlocked(await preview('file:///etc/hostname'), 'file:///etc/hostname')
})

test('SSRF: a name with any private address is refused', async () => {
  assertBlocked(await preview('http://sneaky.nb.invalid/'), 'http://sneaky.nb.invalid/')
})

test('SSRF: DNS is asked once and the checked address is the one used', async () => {
  const res = await preview(`http://rebind.nb.invalid:${stand.sitePort}/`)
  assert.equal(res.status, 200, res.text)
  assert.equal(JSON.parse(res.text).title, 'Market day moves to Saturday')
  assert.equal(dns.calls.filter((name) => name === 'rebind.nb.invalid').length, 1)
})

test('SSRF: a redirect to an internal address is refused', async () => {
  assertBlocked(await preview(`${stand.site}/moved`), `${stand.site}/moved`)
})

test('SSRF: a huge page is cut off', async () => {
  const res = await preview(`${stand.site}/huge`)
  assert.equal(res.status, 422, res.text)
})

test('SSRF: a page that never finishes is cut off', async () => {
  const started = Date.now()
  const res = await preview(`${stand.site}/slow`)
  assert.equal(res.status, 504, res.text)
  assert.ok(Date.now() - started < 3000, 'the preview waited too long')
})

test('SSRF: the preview needs a signed-in member', async () => {
  const res = await preview(`${stand.site}/`, { to: app.base })
  assert.equal(res.status, 401)
})

test('SSRF: the real app refuses loopback with its default settings', async () => {
  const amara = await signIn(app.base, 'amara')
  assertBlocked(await preview(stand.internal, { to: app.base, headers: amara }), stand.internal)
})
JS

The first test is a control. It passes now and must keep passing, so a "fix" that refuses every link is caught. The rebinding test looks odd at first: it expects success. The fake resolver answers with an allowed address the first time and a private one after that, so the only way to get the public title is to ask DNS once and connect to that answer.

Run the security tests:

Bash
npm run test:security

Check it worked

Ten SSRF tests fail and two pass: the control and the signed-out test. The run takes a few seconds longer than usual, because the slow-page test waits for its own four-second limit. Read the failures, which tell the story:

  • The loopback test reports 200 !== 400 and leaked a marker: the preview returned Internal admin nb-marker-internal as the title.
  • The metadata test fails the same way, and the snippet carries nb-marker-key. On a real cloud server that would be a working access key.
  • The redirect test shows a public page bouncing the server to the admin page, and the huge-page test shows the server reading all 2 MB.
  • The file:, sneaky and rebinding cases answer 500, because the app passes the URL straight to fetch and the request fails in some other way. A 500 is not a defence: it depends on the name not resolving, and it leaks nothing only by luck.

If your earlier security tests now fail, check that app.js still has your changes from parts 3 and 4.

Step 3 · Decide which addresses are off limits

Before any code can refuse an internal address, it needs a precise list of what "internal" means. String checks on the URL do not work. The URL parser accepts many spellings of the same address, and a name can point anywhere. See what Node's parser makes of a few:

Bash
node -e "for (const u of ['http://2130706433/', 'http://0x7f.1/', 'http://127.1/', 'http://[::ffff:127.0.0.1]/', 'http://LOCALHOST./']) console.log(u.padEnd(28), new URL(u).hostname)"

The first three all come out as 127.0.0.1. The IPv6 one comes out as [::ffff:7f00:1], an IPv4-mapped address that also means loopback, and LOCALHOST. becomes localhost., a name. So the rule is: parse with new URL, then check IP addresses, never text. For a name, check the addresses it resolves to.

Create ssrf/addresses.js. It uses BlockList from node:net, which matches addresses against subnets for IPv4 and IPv6. The ranges come from the IANA special-purpose registries, trimmed to the ones a link preview must never reach:

Bash
cat > ssrf/addresses.js <<'JS'
import { BlockList, isIP } from 'node:net'

// Ranges a link preview must never connect to.
const IPV4 = [
  ['0.0.0.0', 8], // "this network"; 0.0.0.0 reaches the local machine on Linux
  ['10.0.0.0', 8], // private
  ['100.64.0.0', 10], // carrier-grade NAT, shared by many mobile and ISP networks
  ['127.0.0.0', 8], // loopback, all of it, not only 127.0.0.1
  ['169.254.0.0', 16], // link-local, including the 169.254.169.254 metadata service
  ['172.16.0.0', 12], // private
  ['192.0.0.0', 24], // IETF protocol assignments, used by some metadata services
  ['192.168.0.0', 16], // private
  ['198.18.0.0', 15], // benchmarking
  ['224.0.0.0', 4], // multicast
  ['240.0.0.0', 4], // reserved, including 255.255.255.255
]
const IPV6 = [
  ['::', 128], // unspecified
  ['::1', 128], // loopback
  ['64:ff9b::', 96], // NAT64, which embeds an IPv4 address
  ['64:ff9b:1::', 48], // local-use NAT64
  ['2001::', 32], // Teredo tunnels
  ['2002::', 16], // 6to4, which embeds an IPv4 address
  ['fc00::', 7], // unique local, including fd00:ec2::254 (AWS metadata over IPv6)
  ['fe80::', 10], // link-local
  ['ff00::', 8], // multicast
]

// BlockList also checks IPv4-mapped IPv6 addresses such as ::ffff:127.0.0.1 against
// the IPv4 rules, so loopback in disguise is caught without a rule of its own.
const blocked = new BlockList()
for (const [network, prefix] of IPV4) blocked.addSubnet(network, prefix, 'ipv4')
for (const [network, prefix] of IPV6) blocked.addSubnet(network, prefix, 'ipv6')

export function isPublicAddress(address) {
  const family = isIP(address)
  if (family === 0) return false // not an IP address at all
  return !blocked.check(address, family === 4 ? 'ipv4' : 'ipv6')
}

// A preview only needs ordinary web ports, so it cannot be used to probe other services.
export const ALLOWED_PORTS = new Set([80, 443])

export function defaultAllow(address, port) {
  return ALLOWED_PORTS.has(port) && isPublicAddress(address)
}
JS

Do not add a rule for the IPv4-mapped range ::ffff:0:0/96. BlockList treats a mapped address as the IPv4 address inside it, in both directions, so such a rule would match every IPv4 address and refuse the whole internet; the test below would catch that. NAT64, 6to4 and Teredo addresses are refused outright, which is simpler than unpacking the IPv4 address inside each one, and a public website has no reason to publish one in DNS. If your servers sit on an IPv6-only network that reaches IPv4 sites through NAT64, unpack the embedded address and check it against the IPv4 list instead of refusing the range.

The 100.64.0.0/10 line matters more than it looks. Mobile operators across Africa and elsewhere use carrier-grade NAT heavily, and some hosting and VPN set-ups use the same range for internal links. It is not the public internet, so a preview has no business there.

Lock the list down with unit tests in test/security/ssrf-addresses.test.js. Each address is a row, so adding a case later is one line:

Bash
cat > test/security/ssrf-addresses.test.js <<'JS'
import { test } from 'node:test'
import assert from 'node:assert/strict'
import { isPublicAddress, defaultAllow } from '../../ssrf/addresses.js'

const INTERNAL = [
  '127.0.0.1', '127.8.8.8', '0.0.0.0', '10.1.2.3', '100.64.0.9', '169.254.169.254',
  '172.16.5.4', '172.31.255.255', '192.168.0.10', '192.0.0.192', '224.0.0.251', '255.255.255.255',
  '::', '::1', 'fe80::1', 'fc00::5', 'fd00:ec2::254', '::ffff:127.0.0.1', '::ffff:7f00:1',
  '::ffff:169.254.169.254', '64:ff9b::a9fe:a9fe', 'not-an-address',
]
const PUBLIC = ['1.1.1.1', '8.8.8.8', '172.32.0.1', '100.128.0.1', '2606:4700:4700::1111', '2a00:1450:4001:80b::200e']

for (const address of INTERNAL) {
  test(`SSRF list: ${address} is not public`, () => assert.equal(isPublicAddress(address), false))
}
for (const address of PUBLIC) {
  test(`SSRF list: ${address} is public`, () => assert.equal(isPublicAddress(address), true))
}

test('SSRF list: only ports 80 and 443 are allowed', () => {
  assert.equal(defaultAllow('1.1.1.1', 443), true)
  assert.equal(defaultAllow('1.1.1.1', 80), true)
  assert.equal(defaultAllow('1.1.1.1', 22), false)
  assert.equal(defaultAllow('127.0.0.1', 443), false)
})
JS
node --test test/security/ssrf-addresses.test.js

Check it worked

The node one-liner printed 127.0.0.1 three times, then [::ffff:7f00:1] and localhost.. The address tests all pass: 29 of them, with fail 0. Note 172.32.0.1 and 100.128.0.1 in the public list: they sit just outside the private and carrier-grade NAT ranges, so they prove the prefixes are not wider than intended.

Step 4 · Resolve each name once and check every answer

The next piece takes a parsed URL and returns the single address the preview may connect to, or refuses. Three details carry the weight:

  • Every answer must pass. A name can have several A and AAAA records. If the code checked only the first and the socket picked another, a name with one public and one private address would get through. So one bad address refuses the whole name.
  • One lookup, returned to the caller. The function hands back the address it checked. The next step connects to exactly that address, so DNS is never asked a second time.
  • IP literals skip DNS. A URL like http://[::ffff:127.0.0.1]/ is checked as the address it is.

Create ssrf/resolve.js. Its error messages never repeat the resolved address: telling a member that intranet.example.com points at 10.4.0.12 would itself be a leak.

Bash
cat > ssrf/resolve.js <<'JS'
import { lookup as systemLookup } from 'node:dns/promises'
import { isIP } from 'node:net'
import { defaultAllow } from './addresses.js'

// A refusal the route can show to the member. status is the HTTP status to answer with.
export class PreviewError extends Error {
  constructor(message, status = 400) {
    super(message)
    this.name = 'PreviewError'
    this.status = status
  }
}

// Returns the one address a request to this URL may connect to, or throws PreviewError.
export async function resolveTarget(url, { lookup = systemLookup, allow = defaultAllow } = {}) {
  if (url.protocol !== 'http:' && url.protocol !== 'https:') {
    throw new PreviewError('Only http and https links can be previewed')
  }
  if (url.username || url.password) {
    throw new PreviewError('Links with a user name or password cannot be previewed')
  }
  const port = Number(url.port) || (url.protocol === 'https:' ? 443 : 80)
  const host = url.hostname.startsWith('[') ? url.hostname.slice(1, -1) : url.hostname

  let answers
  if (isIP(host)) {
    answers = [{ address: host, family: isIP(host) }]
  } else {
    try {
      answers = await lookup(host, { all: true })
    } catch {
      throw new PreviewError('That site could not be found')
    }
  }
  if (answers.length === 0) throw new PreviewError('That site could not be found')

  // One private or forbidden answer refuses the whole name.
  for (const { address } of answers) {
    if (!allow(address, port)) throw new PreviewError('That address cannot be previewed')
  }
  return { hostname: host, address: answers[0].address, family: answers[0].family, port }
}
JS

Test it on its own with the fake resolver. The 203.0.113.0/24 and 2001:db8::/32 ranges are reserved for documentation, which makes them good stand-ins for public addresses in a test that never connects. Create test/security/ssrf-resolve.test.js:

Bash
cat > test/security/ssrf-resolve.test.js <<'JS'
import { test } from 'node:test'
import assert from 'node:assert/strict'
import { resolveTarget, PreviewError } from '../../ssrf/resolve.js'
import { fakeDns } from '../fake-dns.js'

const table = {
  'news.nb.invalid': ['203.0.113.10', '2001:db8::10'],
  'metadata.nb.invalid': ['169.254.169.254'],
  'sneaky.nb.invalid': ['203.0.113.10', '10.0.0.8'],
  'v6-internal.nb.invalid': ['fd00:ec2::254'],
}
const check = (url, lookup) => resolveTarget(new URL(url), { lookup })

test('SSRF resolve: a public name gives one checked target', async () => {
  const dns = fakeDns(table)
  const target = await check('https://news.nb.invalid/notices', dns)
  assert.deepEqual(target, { hostname: 'news.nb.invalid', address: '203.0.113.10', family: 4, port: 443 })
  assert.deepEqual(dns.calls, ['news.nb.invalid'])
})

test('SSRF resolve: schemes other than http and https are refused', async () => {
  for (const url of ['file:///etc/hostname', 'ftp://news.nb.invalid/', 'gopher://news.nb.invalid:70/', 'data:text/html,hi']) {
    await assert.rejects(check(url, fakeDns(table)), PreviewError, url)
  }
})

test('SSRF resolve: links with credentials are refused', async () => {
  await assert.rejects(check('http://someone:secret@news.nb.invalid/', fakeDns(table)), PreviewError)
})

test('SSRF resolve: names that point inside the network are refused', async () => {
  for (const name of ['metadata.nb.invalid', 'sneaky.nb.invalid', 'v6-internal.nb.invalid']) {
    await assert.rejects(check(`http://${name}/`, fakeDns(table)), PreviewError, name)
  }
})

test('SSRF resolve: ports other than 80 and 443 are refused', async () => {
  for (const url of ['http://news.nb.invalid:8080/', 'http://news.nb.invalid:22/']) {
    await assert.rejects(check(url, fakeDns(table)), PreviewError, url)
  }
})

test('SSRF resolve: IP literals are checked without asking DNS', async () => {
  const dns = fakeDns(table)
  for (const url of ['http://[::ffff:127.0.0.1]/', 'http://2130706433/', 'http://[fe80::1]/']) {
    await assert.rejects(check(url, dns), PreviewError, url)
  }
  assert.equal(dns.calls.length, 0)
})

test('SSRF resolve: unknown names are refused', async () => {
  await assert.rejects(check('http://nowhere.nb.invalid/', fakeDns(table)), PreviewError)
})
JS
node --test test/security/ssrf-resolve.test.js

Check it worked

All seven resolve tests pass. The first one shows the contract: one call to DNS, and a target with a single address and a port. The ssrf.test.js failures from step 2 are unchanged, because the route does not use any of this yet.

Step 5 · Connect to the checked address and re-check every redirect

Four steps in a row: parse the URL, resolve once, connect to the checked address, read with limits; a dashed arrow from the last step back to the first marks a redirect, at most three times
Each hop, including every redirect, goes through the same checks.

This is where DNS rebinding is defeated. An attacker who controls a domain can answer the first lookup with a public address, so the check passes, and the next lookup, a moment later, with 127.0.0.1. Code that checks a name and then calls fetch(url) asks DNS twice and connects to the second answer. The fix is to never let the socket look the name up. Node's http.request takes a lookup option, the function it calls to turn the host name into an address. Pass one that returns the address you already checked. The request keeps the real host name for the Host header and, for https, for checking the certificate, so TLS still works.

The same file handles the other controls from the diagram:

  • Redirects by hand, at most three. A public page can answer 302 with a Location of http://127.0.0.1/. The fetcher never follows a redirect for you; it builds the new URL and sends it through resolveTarget again.
  • One deadline for everything. AbortSignal.timeout starts once and covers every hop and the whole body, so a server that drips one byte a second cannot hold a request open.
  • A size cap that does not trust headers. A declared Content-Length over the cap is refused at once, and the body is counted as it arrives, because a chunked response has no length at all.
  • Web pages only. Anything but text/html is refused, so a JSON answer such as a metadata response never reaches the snippet.

Create ssrf/safe-fetch.js:

Bash
cat > ssrf/safe-fetch.js <<'JS'
import http from 'node:http'
import https from 'node:https'
import { defaultAllow } from './addresses.js'
import { PreviewError, resolveTarget } from './resolve.js'

export { PreviewError }

// One request to an address that has already been checked.
function requestPinned(url, target, signal) {
  const client = url.protocol === 'https:' ? https : http
  // Hand the socket the checked address, so nothing can look the name up a second time.
  const lookup = (hostname, options, callback) => {
    if (options.all) callback(null, [{ address: target.address, family: target.family }])
    else callback(null, target.address, target.family)
  }
  return new Promise((resolve, reject) => {
    const req = client.get(url, {
      lookup,
      signal,
      agent: false, // a fresh connection; no pooled socket from an earlier hop
      headers: { 'user-agent': 'NoticeboardPreview/1.0', accept: 'text/html' },
    }, resolve)
    req.on('error', reject)
  })
}

async function readCapped(res, maxBytes) {
  const tooLarge = () => new PreviewError('That page is too large to preview', 422)
  if (Number(res.headers['content-length']) > maxBytes) {
    res.destroy()
    throw tooLarge()
  }
  const chunks = []
  let size = 0
  for await (const chunk of res) {
    size += chunk.length
    if (size > maxBytes) {
      res.destroy()
      throw tooLarge()
    }
    chunks.push(chunk)
  }
  return Buffer.concat(chunks).toString('utf8')
}

export function createSafeFetcher({
  lookup, // DNS function; the system resolver unless a test passes a fake one
  alsoAllow = [], // exact "address:port" pairs treated as public; for tests only, empty in the app
  timeoutMs = 5000,
  maxBytes = 256 * 1024,
  maxRedirects = 3,
} = {}) {
  const allow = (address, port) => alsoAllow.includes(`${address}:${port}`) || defaultAllow(address, port)

  return async function fetchPage(input) {
    if (typeof input !== 'string' || input.length > 2048) {
      throw new PreviewError('Send a link of up to 2,048 characters')
    }
    let url
    try {
      url = new URL(input)
    } catch {
      throw new PreviewError('That is not a valid link')
    }

    const signal = AbortSignal.timeout(timeoutMs) // one deadline for every hop and the whole body
    try {
      for (let hop = 0; hop <= maxRedirects; hop++) {
        const target = await resolveTarget(url, { lookup, allow })
        const res = await requestPinned(url, target, signal)
        const location = res.headers.location
        if (res.statusCode >= 300 && res.statusCode < 400 && location) {
          res.destroy()
          url = new URL(location, url) // checked again at the top of the loop
          continue
        }
        if (res.statusCode !== 200) {
          res.destroy()
          throw new PreviewError(`The page answered ${res.statusCode}`, 502)
        }
        if (!/^text\/html\b/i.test(res.headers['content-type'] ?? '')) {
          res.destroy()
          throw new PreviewError('Only web pages can be previewed', 422)
        }
        return await readCapped(res, maxBytes)
      }
      throw new PreviewError('That link redirects too many times', 502)
    } catch (err) {
      if (err instanceof PreviewError) throw err
      if (signal.aborted) throw new PreviewError('The page took too long to answer', 504)
      throw new PreviewError('The page could not be fetched', 502)
    }
  }
}
JS

Network errors become a plain 502 with a fixed message. Passing the raw error on would tell a member whether a port was closed or filtered, which turns the preview into a port scanner even when it cannot read anything.

Check it worked

Load the module and fetch the public stand-in through it, using the same alsoAllow seam as the tests:

Bash
node --input-type=module -e "
import { startStandIns } from './test/stand-ins.js'
import { createSafeFetcher } from './ssrf/safe-fetch.js'
const stand = await startStandIns()
const fetchPage = createSafeFetcher({ alsoAllow: ['127.0.0.1:' + stand.sitePort] })
console.log((await fetchPage(stand.site + '/')).match(/<title>(.*)<\/title>/)[1])
await fetchPage(stand.site + '/moved').catch((err) => console.log(err.status, err.message))
await stand.close()
"

It prints Market day moves to Saturday, then 400 That address cannot be previewed: the redirect to the admin page was checked as a new hop and refused before any request was sent to it.

Step 6 · Use the safe fetcher in the preview route

Rewrite routes/preview.js. The route now returns only the title, trimmed to 200 characters, because that is all the card shows. Sending back less is a control of its own: even a page you meant to allow cannot be used to read large chunks of text through your server. A PreviewError becomes a JSON error with its status, and anything else goes to the app's error handler as before:

Bash
cat > routes/preview.js <<'JS'
import { Router } from 'express'
import { createSafeFetcher, PreviewError } from '../ssrf/safe-fetch.js'

function titleOf(html) {
  const title = /<title[^>]*>([^<]*)<\/title>/i.exec(html)?.[1] ?? ''
  return title.replace(/\s+/g, ' ').trim().slice(0, 200)
}

// options: { lookup, alsoAllow, timeoutMs, maxBytes, maxRedirects }. The app passes none.
export function previewRouter(options) {
  const router = Router()
  const fetchPage = createSafeFetcher(options)

  router.post('/', async (req, res) => {
    try {
      const html = await fetchPage(req.body?.url)
      res.json({ title: titleOf(html) })
    } catch (err) {
      if (!(err instanceof PreviewError)) throw err
      res.status(err.status).json({ error: err.message })
    }
  })

  return router
}
JS
npm run test:security
npm test

The title is still text from a stranger's page. Whatever shows it must treat it as text, never as HTML, which is the output-encoding rule from part 3.

If you kept the access-control matrix from part 2, add a row for the new route so the next change to it is checked too: POST /api/preview answers 401 for a signed-out caller and 400 for any signed-in role when the body has no link.

Check it worked

All twelve SSRF tests pass, along with the address and resolve tests and whatever security tests you have from earlier parts, and npm test finishes with fail 0. In the SSRF output, the slow-page test now finishes in about one and a half seconds with 504, the huge page gets 422, and the rebinding test shows DNS was asked exactly once. The loopback, metadata, file:, sneaky and redirect cases all answer 400 with no marker text.

To see the rebinding defence earn its place, open ssrf/safe-fetch.js, delete the lookup, line inside client.get(...), and run npm run test:security. The rebinding test fails, because the socket now resolves rebind.nb.invalid itself. Put the line back and the run is clean again.

Step 7 · Add a network-level backstop

Code checks can have bugs, and the next feature that fetches URLs, a webhook sender or an image importer, might not use createSafeFetcher. Add a control that does not depend on the code: stop the app's own operating-system user from opening new connections to internal ranges. Part 6 runs Noticeboard as a dedicated low-privilege user; the rules below assume that user is called noticeboard.

On an Ubuntu 26.04 server, nftables can match packets by the user that owns the socket. Write the rules to a file first, so you can read them before loading anything. Warning: these rules also stop that user from reaching anything else on these ranges, including a database on 127.0.0.1, another server on your private network and the local DNS resolver. On a stock Ubuntu server, /etc/resolv.conf points at the systemd-resolved stub on 127.0.0.53 port 53, so DNS to that stub must stay open or every name lookup by the app fails, and every real preview with it. The two 127.0.0.53 lines below keep it open. Add an accept line above the reject lines for each other internal service the app really needs, such as meta skuid "noticeboard" ip daddr 127.0.0.1 tcp dport 5432 accept for PostgreSQL:

Bash
id noticeboard || sudo useradd --system --no-create-home --shell /usr/sbin/nologin noticeboard
cat > ~/noticeboard-demo/api/egress.nft <<'NFT'
table inet noticeboard_egress {
  chain output {
    type filter hook output priority 0; policy accept;
    ct state established,related accept
    meta skuid "noticeboard" ip daddr 127.0.0.53 udp dport 53 accept
    meta skuid "noticeboard" ip daddr 127.0.0.53 tcp dport 53 accept
    meta skuid "noticeboard" ip daddr { 0.0.0.0/8, 10.0.0.0/8, 100.64.0.0/10, 127.0.0.0/8, 169.254.0.0/16, 172.16.0.0/12, 192.0.0.0/24, 192.168.0.0/16 } reject
    meta skuid "noticeboard" ip6 daddr { ::1, fc00::/7, fe80::/10 } reject
  }
}
NFT
sudo nft -f ~/noticeboard-demo/api/egress.nft
sudo nft list table inet noticeboard_egress

The ct state established,related accept line comes first so the app can still answer the connections people make to it; only new outbound connections are refused. The sets are shorter than the list in ssrf/addresses.js on purpose: the firewall covers the internal ranges that matter most, including 192.0.0.0/24 where some metadata services live, and the code covers the rest, such as benchmarking, multicast and the IPv6 transition ranges. Rules loaded with nft -f last until the next reboot. To keep them, include the file from /etc/nftables.conf and enable the nftables service, and keep your SSH access in mind as you would with any firewall change; the UFW tutorial covers the safe order.

Two other network controls are worth knowing:

  • An egress proxy. Larger set-ups send every outbound request from app servers through one proxy that applies an address policy like ssrf/addresses.js, so each new feature gets it for free. Stripe's open-source Smokescreen is built for exactly this.
  • Cloud metadata settings. On AWS, require IMDSv2: a metadata request then needs a session token obtained with a PUT, which a preview's plain GET cannot get, and a hop limit of 1 keeps containers from reaching it. Google Cloud and Azure already refuse metadata requests without a special header (Metadata-Flavor: Google and Metadata: true), and the safe fetcher never sends those.

None of these replaces the code fix. They make sure that if the code is wrong one day, the mistake is a failed preview, not a leaked key.

Check it worked

On a server where you loaded the rules, sudo nft list table inet noticeboard_egress prints the table with both reject lines. Run a request as the app's user to confirm it is refused: sudo -u noticeboard node -e "fetch('http://127.0.0.1:22').catch((e) => console.log(e.cause?.code))" prints ECONNREFUSED, because the firewall turned the connection away before it reached any service. Then confirm DNS still works for that user: sudo -u noticeboard node -e "require('dns').promises.lookup('example.com').then(console.log)" prints an object with a public address and family: 4 (or 6). If it prints EAI_AGAIN instead, the two 127.0.0.53 accept lines are missing or sit below the reject lines. On your laptop, you can skip loading the rules; the tests from the earlier steps are the proof for this part.

Keep ~/noticeboard-demo as it is: part 6 goes back to part 1's app in that folder, and part 8 removes it, api included.

Next steps

Your link preview now accepts only http and https on ports 80 and 443, resolves each name once and refuses it if any answer is internal, connects to the address it checked, re-checks every redirect, and gives up after 5 seconds or 256 KB. Twelve route tests, backed by 36 unit tests, keep it that way.

  • Webhooks are the other feature that sends requests to URLs your users choose; apply the same fetcher there: /tutorials/send-webhooks-with-signatures-and-retries
  • Compare how a client library handles timeouts and redirects when you call an API you trust: /tutorials/call-a-web-api-from-python-with-httpx

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.