Thuta Learning
Node.js
AdvancedWeb DevelopmentBeginner

HTTP Security, Validation & Permissions

Node.jsLesson 1840 min

What you'll walk away with

  • Read a request body with a size limit and return 413, 415 and 400 correctly
  • Prevent mass assignment with allowlist validation
  • Explain 401 versus 403 and compare tokens with timingSafeEqual
  • Explain what security headers and the Node.js permission model are for

Explain it simply

HTTP security in plain language

Not everyone calling your API is your frontend. Someone with curl, an attacker's script, or a buggy client can send any header, any field and a body of any size. HTTP security means checking that input at the door and letting in only what you explicitly allow.

Think of building security: the front desk checks your ID (authentication), then checks which floors you may visit (authorization), and oversized luggage is turned away at the door (body limits).

Problem → Why → Solution

The problem: trusting what the client sends

A profile-update route merges the whole request body into the user object. The frontend sends only name and bio, but an attacker adds { "role": "admin" } and becomes an admin. The same route never checks the id in the URL, so changing it to /users/43 edits someone else's profile, and a 50 MB JSON body fills the server's memory.

update-profile.mjs
app.put('/users/:id', async (req, res) => {
  const user = await db.users.find(req.params.id); // whose user? never checked
  Object.assign(user, req.body); // role, isAdmin, balance... all writable
  await db.users.save(user);
  res.json(user); // may also leak passwordHash back to the client
});

Why one bug becomes a data breach

This route skips three checks: which fields are allowed (allowlist), whether the caller owns the record (authorization), and how big the body may be (limit). Because the default is 'allow', everything a developer forgets becomes a hole. Flip the default to 'deny' and a forgotten case becomes an error instead.

Core concept: deny-by-default checks at the door

Check a request in order before it reaches business logic. Cheapest checks first: is the method and path right, is Content-Type application/json (415 if not), is the body over the limit (413). Count bytes while reading the body stream, because the Content-Length header cannot be trusted and chunked uploads do not send one.

Then check the shape against an allowlist: keep a list of allowed fields, reject unknown ones, and check each field's type and length (400 if wrong). Build a new object from the validated fields; never pass req.body straight to the database.

Check identity in two separate steps. Authentication answers 'who are you?': a missing or wrong token is 401. Authorization answers 'may you do this?': the wrong role or a record you do not own is 403, or 404 if you prefer not to reveal that the record exists. Skipping the ownership check is a bug called IDOR (insecure direct object reference). Comparing a secret token with === stops at the first differing character, so the timing difference can leak information; use crypto.timingSafeEqual.

Protect the response side too. Headers such as X-Content-Type-Options: nosniff and Content-Security-Policy tell the browser how to treat a response; in Express, the helmet package sets a sensible group of them at once. Error responses should carry only messages the client can act on, while internal details such as stack traces, SQL errors and file paths stay in the logs.

StatusMeaningExample
400the request is malformedbroken JSON, an unknown field
401we do not know who you aremissing or invalid token
403we know you, but noa reader tries to delete a user
413 / 415body too large / wrong format2 MB of JSON, form data
The checkpoints at the door
  1. Format and size (415/413)
  2. Token: who is calling? (401)
  3. Role and ownership (403)
  4. Field allowlist (400)
  5. Act only on checked data

Any failed checkpoint returns immediately; later checks and the business logic never run.

General pattern

javascript
async function handle(req, res) {
  setSecurityHeaders(res);
  if (!isJson(req)) return send(res, 415, { error: '...' });
  const caller = authenticate(req.headers.authorization);
  if (!caller) return send(res, 401, { error: '...' });
  if (!mayAccess(caller, resource)) return send(res, 403, { error: '...' });
  const input = await readJsonWithLimit(req, MAX_BYTES); // 413 / 400
  const problem = validateAgainstAllowlist(input);
  if (problem) return send(res, 400, { error: problem });
  return act(pickAllowedFields(input));
}

Every check refuses with an early return, so a request that reaches the last line has passed them all. With a framework, each step becomes one middleware.

Worked example: the input boundary of a notes API

This server uses node:http only, with no packages, so you can see every check yourself. It starts on port 0 and sends five requests in order: a valid note, one with a field that is not allowed, broken JSON, a 2 MB body and form data. At the end it confirms that responses carry the security headers.

notes-server.mjs
import { createServer } from 'node:http';

const MAX_BODY_BYTES = 1024;
const ALLOWED_FIELDS = new Set(['title', 'body']);

function setSecurityHeaders(res) {
  res.setHeader('X-Content-Type-Options', 'nosniff');
  res.setHeader('Content-Security-Policy', "default-src 'none'; frame-ancestors 'none'");
  res.setHeader('Referrer-Policy', 'no-referrer');
}

function send(res, status, payload) {
  res.writeHead(status, { 'Content-Type': 'application/json' });
  res.end(JSON.stringify(payload));
}

function httpError(status, message) {
  return Object.assign(new Error(message), { status });
}

async function readJson(req) {
  if (Number(req.headers['content-length'] ?? 0) > MAX_BODY_BYTES) {
    throw httpError(413, 'body too large'); // reject before reading a byte
  }
  let size = 0;
  const chunks = [];
  for await (const chunk of req) {
    size += chunk.length; // chunked uploads have no Content-Length to trust
    if (size > MAX_BODY_BYTES) throw httpError(413, 'body too large');
    chunks.push(chunk);
  }
  try {
    return JSON.parse(Buffer.concat(chunks).toString('utf8'));
  } catch {
    throw httpError(400, 'malformed JSON');
  }
}

function validateNote(input) {
  if (typeof input !== 'object' || input === null || Array.isArray(input)) {
    return 'body must be a JSON object';
  }
  const unknown = Object.keys(input).filter((key) => !ALLOWED_FIELDS.has(key));
  if (unknown.length > 0) return `unknown field: ${unknown.join(', ')}`;
  if (typeof input.title !== 'string' || input.title.trim() === '') {
    return 'title is required';
  }
  if (input.title.length > 80) return 'title is longer than 80 characters';
  if (input.body !== undefined && typeof input.body !== 'string') {
    return 'body must be text';
  }
  return null;
}

const server = createServer(async (req, res) => {
  setSecurityHeaders(res);
  if (req.method !== 'POST' || req.url !== '/notes') {
    return send(res, 404, { error: 'not found' });
  }
  if (!req.headers['content-type']?.startsWith('application/json')) {
    return send(res, 415, { error: 'send application/json' });
  }
  try {
    const input = await readJson(req);
    const problem = validateNote(input);
    if (problem) return send(res, 400, { error: problem });
    send(res, 201, { title: input.title.trim(), body: input.body ?? '' });
  } catch (error) {
    // Known client errors explain themselves; anything else stays generic.
    const message = error.status ? error.message : 'internal error';
    send(res, error.status ?? 500, { error: message });
  }
});

await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
const url = `http://127.0.0.1:${server.address().port}/notes`;
const post = (body, type = 'application/json') =>
  fetch(url, { method: 'POST', headers: { 'Content-Type': type }, body });

const attempts = [
  ['valid note', JSON.stringify({ title: ' Hello ', body: 'first' })],
  ['extra field', JSON.stringify({ title: 'Hi', isAdmin: true })],
  ['broken JSON', '{"title":'],
  ['huge body', JSON.stringify({ title: 'x', body: 'y'.repeat(2_000_000) })],
  ['form data', 'title=Hi', 'application/x-www-form-urlencoded'],
];
for (const [label, body, type] of attempts) {
  const res = await post(body, type);
  console.log(label.padEnd(12), res.status, JSON.stringify(await res.json()));
}
const sample = await post(JSON.stringify({ title: 'Headers' }));
console.log('nosniff header:', sample.headers.get('x-content-type-options'));
server.close();

Code breakdown

  1. Security headersres.setHeader('X-Content-Type-Options', 'nosniff');

    Tells the browser to trust the Content-Type and never guess that JSON is a script. The CSP default-src 'none' forbids loading anything from a JSON API response.

  2. Cheap rejection firstif (Number(req.headers['content-length'] ?? 0) > MAX_BODY_BYTES) {

    If the declared size is too big, it answers 413 without reading a byte. Headers can lie, so the loop checks again.

  3. Count while streamingif (size > MAX_BODY_BYTES) throw httpError(413, 'body too large');

    The running total is checked as each chunk arrives, so even a chunked upload without a length header cannot fill memory.

  4. Allowlist, not blocklistconst unknown = Object.keys(input).filter((key) => !ALLOWED_FIELDS.has(key));

    Instead of blocking isAdmin, only the two allowed fields are accepted. A column added to the database later is not automatically writable by clients.

  5. Generic 500const message = error.status ? error.message : 'internal error';

    Client errors explain themselves, but an unexpected error's message and stack never go to the client, because they can leak internal details.

You should see
valid note   201 {"title":"Hello","body":"first"}
extra field  400 {"error":"unknown field: isAdmin"}
broken JSON  400 {"error":"malformed JSON"}
huge body    413 {"error":"body too large"}
form data    415 {"error":"send application/json"}
nosniff header: nosniff

Giving the process only the permissions it needs

Even with request checks, a dependency can still have a bug or a path-traversal hole. The Node.js permission model restricts the whole process's access to the file system, child processes, worker threads and more. Started with --permission, everything is denied except what the allow flags grant. Recent Node 22 releases accept --permission; earlier ones spelled it --experimental-permission, so check node --help.

bash
# read config and public files only; no writes, no child processes
node --permission --allow-fs-read=./config --allow-fs-read=./public server.js

# inside the app you can ask at runtime:
#   process.permission.has('fs.write')  -> false

A seatbelt, not a sandbox

The Node.js documentation itself says the permission model does not protect against malicious code. It limits what trusted code can do by accident. Running untrusted code needs OS-level isolation such as a container or a VM.

In real projects

In real Express projects

Express apps rarely hand-write every one of these checks, but you need to understand what the libraries do. A typical setup uses helmet for security headers, express.json({ limit: '100kb' }) to cap body size, and a schema library such as zod for allowlist validation.

  • Authentication middleware verifies a session or JWT and sets req.user; each route still checks authorization against req.user.
  • Put ownership into the query itself: WHERE id = $1 AND owner_id = $2 can never return someone else's record.
  • Add rate limiting to login and password-reset routes, and set the server's requestTimeout and headersTimeout deliberately.
  • Audit dependencies with npm audit and keep Node.js itself patched on a supported LTS line.

Common mistakes

Common HTTP security mistakes

Mixing up 401 and 403

Returning 401 to a user with a valid token but the wrong role makes the client send them back to login in a loop. 401 means 'we do not know who you are'; 403 means 'we know you, and you may not do this'.

Validating with a blocklist

Deleting fields one by one, as in delete req.body.role, breaks the day the database gains a new column such as isAdmin or balance. Pick the allowed fields and reject everything else.

Comparing tokens with ===, or checking length first

=== stops at the first differing character, so response times can reveal a token one character at a time. timingSafeEqual throws when lengths differ, and checking the length first leaks the length. Hash both values with SHA-256 and compare the equal-length digests.

Best practices

Best practices

  • Make 'deny' the default for every new route, so it works only once authentication and authorization are deliberately added.
  • Build new objects from validated fields, and pick the fields you return in responses too.
  • Keep secrets out of source code, read them from a secret store, and store API keys hashed.
  • Write an integration test proving each security check returns its 401, 403 or 413.

Mini challenge

Mini challenge: token and role middleware

Protect a DELETE /users/:id route so only callers with the admin role can use it. Find the caller from the Authorization: Bearer <token> header and compare tokens in a timing-safe way. Start the server on port 0 and try four cases: no token, a wrong token, a reader token and an admin token.

  • 401 when the token is missing or invalid
  • 403 when the token is valid but the role is not admin
  • Compare tokens with sha256 digests and timingSafeEqual
  • Write a reusable requireRole(role, handler) middleware
admin-only.mjs
import { createHash, timingSafeEqual } from 'node:crypto';
import { createServer } from 'node:http';

const API_KEYS = [
  { key: 'reader-key-123', user: 'mya', role: 'reader' },
  { key: 'admin-key-456', user: 'ko-aung', role: 'admin' },
];

function findCaller(header) {
  // TODO: require the "Bearer " prefix
  // TODO: hash the presented token and each stored key, compare safely
}

function requireRole(role, handler) {
  // TODO: return (req, res) => { 401 / 403 / call handler(req, res, caller) }
}

// TODO: DELETE /users/:id protected by requireRole('admin', ...)
// TODO: listen on port 0, try four Authorization headers, print the statuses

Expected: No token and 'guess' get 401, reader-key-123 gets 403, and admin-key-456 gets 200 with { deleted: '42', by: 'ko-aung' }.

Show hint

createHash('sha256').update(value).digest() always returns 32 bytes, whatever the input length, so timingSafeEqual never throws a length error. In requireRole, check for no caller (401) before checking the role (403).

Show solution
admin-only.mjs
import { createHash, timingSafeEqual } from 'node:crypto';
import { createServer } from 'node:http';

// In production these come from a secret store, never from source code.
const API_KEYS = [
  { key: 'reader-key-123', user: 'mya', role: 'reader' },
  { key: 'admin-key-456', user: 'ko-aung', role: 'admin' },
];

const digest = (value) => createHash('sha256').update(value).digest();

function findCaller(header) {
  if (!header?.startsWith('Bearer ')) return null;
  const presented = digest(header.slice('Bearer '.length));
  // Equal-length digests let timingSafeEqual compare without leaking the length.
  return API_KEYS.find((entry) => timingSafeEqual(presented, digest(entry.key))) ?? null;
}

function requireRole(role, handler) {
  return (req, res) => {
    const caller = findCaller(req.headers.authorization);
    if (!caller) return reply(res, 401, { error: 'missing or invalid token' });
    if (caller.role !== role) return reply(res, 403, { error: `needs role ${role}` });
    handler(req, res, caller);
  };
}

function reply(res, status, payload) {
  res.writeHead(status, { 'Content-Type': 'application/json' });
  res.end(JSON.stringify(payload));
}

const deleteUser = requireRole('admin', (req, res, caller) => {
  reply(res, 200, { deleted: req.url.split('/').at(-1), by: caller.user });
});

const server = createServer((req, res) => {
  if (req.method === 'DELETE' && req.url.startsWith('/users/')) {
    return deleteUser(req, res);
  }
  reply(res, 404, { error: 'not found' });
});

await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
const base = `http://127.0.0.1:${server.address().port}`;

for (const token of [undefined, 'guess', 'reader-key-123', 'admin-key-456']) {
  const headers = token ? { Authorization: `Bearer ${token}` } : {};
  const res = await fetch(`${base}/users/42`, { method: 'DELETE', headers });
  console.log(String(token).padEnd(15), res.status, JSON.stringify(await res.json()));
}
server.close();

Quick quiz 1 / 3

A logged-in reader calls an admin-only route. Which status is most correct?

Quick quiz 2 / 3

A request body contains an isAdmin field that is not allowed. What should happen?

Quick quiz 3 / 3

What happens when timingSafeEqual(a, b) gets buffers of different lengths?

What to remember

  • Treat every request as untrusted input and run the cheapest checks first.
  • Count bytes while reading the body: 413 over the limit, 415 for the wrong format, 400 for a bad shape.
  • Allowlist validation and building a fresh object prevent mass assignment.
  • 401 is about identity, 403 about permission and ownership; compare tokens in a timing-safe way.
  • Security headers (or helmet) and --permission add further layers of defence.

Permissions — Node.js

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

HTTP Security, Validation & Permissions | Thuta Learning