Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 39 ยท Authentication and Security

Authorization, Input Hardening and Secrets

Go beyond login: enforce ownership and roles, stop mass assignment and IDOR bugs, limit body size, validate environment secrets and keep them out of logs in Fastify.

Authentication answers "who are you?". Authorization answers "what may you do?". Most real-world API breaches are not broken logins but missing authorization checks: a signed-in user changes an id in the URL and reads someone else's data. This lesson covers the checks that prevent that, how to harden input beyond schema validation, and how to handle secrets.

Fastify itself is not installed on this site; the examples use the small Fastify-like stand-in from earlier lessons (labelled in the code) and plain Node.

Authorization checks

Role What kind of user is this?
Ownership Does this record belong to them?
Allow-list Which fields may they change?

Check on the server, every time.

1 / 2

Roles and ownership

Two kinds of rules cover most APIs:

  • Role-based access control (RBAC): an admin can delete any post, an editor can write, a viewer can only read.
  • Ownership checks: a user may read or change their own records only, whatever their role.

Forgetting the second kind produces the classic IDOR (insecure direct object reference) bug: GET /orders/42 returns order 42 to anyone who is logged in. The fix is to load the record and compare its owner with request.user before doing anything. When the record belongs to somebody else, answering 404 (instead of 403) also avoids confirming that the id exists.

Mass assignment

Mass assignment happens when you copy the whole request body into a record: Object.assign(user, request.body). A client who adds "role": "admin" to a profile update promotes themselves. Defend in two layers: a JSON schema with additionalProperties: false (see JSON Schema Basics), and copying only the fields you list.

Node.js Ownership check and field allow-list

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The attacker's extra fields ownerId, role and id are silently ignored because only title and published are on the list. This is safer than a deny-list, which fails open when you add a new sensitive field later.

Hardening input

Schema validation checks shape. A few more limits cover size and trickery:

  • Body size. Fastify's bodyLimit option (default 1 MiB) rejects oversized bodies with 413. Lower it for small JSON APIs and raise it per route for uploads.
  • Depth and counts. Deeply nested JSON or a million-element array is cheap to send and costly to process. Use schema maxItems, maxLength and maxProperties.
  • Prototype pollution. Keys like __proto__ and constructor can poison shared objects when merged. Fastify's JSON parser refuses __proto__ by default (onProtoPoisoning: 'error'); keep that setting, and never write your own deep merge.
  • Injection. Use parameterized queries (WHERE id = ?), never string concatenation. Escape output when you build HTML.
  • Path traversal. If you serve files by user-supplied name, resolve the path and check it stays inside the base folder.

The last one is easy to demonstrate with node:path:

Node.js Stopping path traversal and oversized input

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

JSON.parse itself is safe: it creates an own property named __proto__. The danger starts when code later copies those keys onto another object with a naive merge, which is why Fastify checks for it up front.

Secrets

Secrets are API keys, database URLs, JWT signing keys and cookie secrets. Rules that cover most mistakes:

  1. Never commit them. Read from environment variables or a secret manager (Docker/Kubernetes secrets, Vault, cloud secret services). Keep .env in .gitignore and commit a .env.example with fake values.
  2. Validate at startup. Missing or weak secrets should stop the server from booting, not fail on the first request. The @fastify/env plugin validates the environment against a JSON schema; the next example does the same by hand.
  3. Keep them out of logs. Use Pino's redact option for headers like authorization and cookie, and fields such as password (see Logging with Pino).
  4. Use different secrets per environment and rotate them when staff leave or a leak is suspected.
Node.js Validate secrets at startup and redact them

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

With real Pino the same idea is one option, logger: { redact: ['req.headers.authorization', 'req.headers.cookie', '*.password'] }.

If a secret ever reached Git, a log file or a chat, treat it as compromised and rotate it. Deleting the commit does not help: clones and caches keep the old value.

A quick audit checklist

  • Does every route check who and which record?
  • Do updates copy only an allow-list of fields?
  • Are body size, array sizes and string lengths bounded?
  • Are queries parameterized and file paths confined?
  • Do secrets come from the environment, get validated at boot, and stay out of logs?
  • Are errors generic for clients and detailed only in logs (see Error Handling and Not Found Routes)?

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A logged-in user requests /orders/42, which belongs to another user, and receives it. What is this bug called?

    The server authenticated the user but never checked that the order belongs to them: an insecure direct object reference.
  2. 2. Why is an allow-list of editable fields safer than a deny-list?

    With an allow-list, a field you add later is ignored until you deliberately permit it. A deny-list fails open.
  3. 3. Which Fastify option limits the size of request bodies?

    bodyLimit (default 1 MiB) makes Fastify answer 413 for larger bodies.
  4. 4. What should happen when JWT_SECRET is missing at startup?

    Failing fast with a clear message prevents running with an insecure or inconsistent configuration.

Summary

  • Authorization needs both role checks and per-record ownership checks; answer 404 for records the user may not know about.
  • Copy only allow-listed fields and set additionalProperties: false to stop mass assignment.
  • Bound body size, depth and string lengths; keep proto-poisoning protection; use parameterized queries and confined file paths.
  • Load secrets from the environment, validate them at boot, redact them in logs, rotate after leaks.

Next: Testing Fastify Apps with inject