Security Headers and Rate Limits

helmet adds a set of security headers to every answer of an Express API in one line, and express-rate-limit counts each address's requests to a route such as sign-in and answers 429 Too Many Requests when it goes over the limit.

Journeyman · Node.js · Web Development · Updated

By

After this lesson you can

  • Add security headers to every answer of an Express API with helmet, and explain what a few of them tell the browser
  • Limit how often one address may call a route such as sign-in with express-rate-limit, answering 429 Too Many Requests

Key takeaways

  • By default every Express answer says X-Powered-By, Express, and carries none of the headers that tell a browser to be careful.
  • app.use(helmet()) adds about a dozen security headers to every answer and takes X-Powered-By away.
  • Four of helmet's headers worth knowing are Content-Security-Policy, Strict-Transport-Security, X-Content-Type-Options and X-Frame-Options.
  • A rate limit counts each address's requests in a window of time, and past the limit answers 429 Too Many Requests.
  • Sign-in gets a strict limit of its own, so nobody can try thousands of passwords, while the rest of the API stays open.

The day an API goes online, two kinds of visitor turn up that nobody invited: scanners that read your answers to learn what you're running, and scripts that try one password after another on your sign-in route. A few lines of middleware deal with both, and they're among the first things a security review at work looks for.

Here's what Bean There Coffee Club's API tells every visitor now, in answer to GET /roasts (the length, ETag, date and connection lines left out):

HTTP/1.1 200 OK
X-Powered-By: Express
Content-Type: application/json; charset=utf-8

X-Powered-By: Express tells everyone which framework answers, which is the first thing someone looking for a known weakness wants to know. And nothing in the answer tells a browser how carefully to treat it.

helmet: safe handling notes in one line

Status Codes and Headers compared headers to the notes on a parcel's label. Some notes are about safety: "this side up", "fragile", "deliver only to this address". The helmet package puts a set of safety notes on every answer your API sends. Install it with npm install helmet and add it before your routes:

import express from "express";
import helmet from "helmet";

export const app = express();

app.use(helmet());

The same GET /roasts now answers with these headers before Content-Type:

HTTP/1.1 200 OK
Content-Security-Policy: default-src 'self';base-uri 'self';font-src 'self' https: data:;form-action 'self';frame-ancestors 'self';img-src 'self' data:;object-src 'none';script-src 'self';script-src-attr 'none';style-src 'self' https: 'unsafe-inline';upgrade-insecure-requests
Cross-Origin-Opener-Policy: same-origin
Cross-Origin-Resource-Policy: same-origin
Origin-Agent-Cluster: ?1
Referrer-Policy: no-referrer
Strict-Transport-Security: max-age=31536000; includeSubDomains
X-Content-Type-Options: nosniff
X-DNS-Prefetch-Control: off
X-Download-Options: noopen
X-Frame-Options: SAMEORIGIN
X-Permitted-Cross-Domain-Policies: none
X-XSS-Protection: 0

X-Powered-By is gone. You don't need to learn all twelve; four are worth knowing:

Header What it tells the browser
Content-Security-Policy Where a page from this server may load scripts, styles and pictures from: here, mostly its own origin ('self')
Strict-Transport-Security Use HTTPS for this site from now on, for a year (31,536,000 seconds), even if someone types http://
X-Content-Type-Options: nosniff Believe the Content-Type; never guess the type from what the body looks like
X-Frame-Options: SAMEORIGIN Only pages from this origin may show this one inside a frame, so another site can't hide it under a fake button

To be honest about what they buy: most of these protect pages that a browser shows. A JSON API shows few pages, so for the club they're cheap insurance. An error page or a file served by mistake is still covered, and security scanners stop flagging the API.

Too many tries: a rate limit

Sign-Up and Sign-In Routes answers a wrong email and a wrong password with the same vague 401, so nobody learns which emails are members. But a script can still try thousands of passwords a minute against one email. A phone solves this by locking for a while after too many wrong PINs.

A rate limit does the same for a route: it counts each address's requests in a window of time, and past the limit it stops answering normally. The express-rate-limit package gives you one as middleware. Install it with npm install express-rate-limit:

import { rateLimit } from "express-rate-limit";

const signInLimiter = rateLimit({
  windowMs: 15 * 60 * 1000,
  limit: 5,
  standardHeaders: "draft-8",
  legacyHeaders: false,
  handler: (req, res) => sendProblem(res, 429, "Too many sign-in attempts. Try again in 15 minutes."),
});

app.post("/auth/sign-in", signInLimiter, async (req, res) => {
  // the sign-in route, unchanged
});

windowMs is the window in milliseconds (15 minutes), limit is the number of tries in it, and handler answers once they're used up, here with sendProblem, the course's one error shape from Error Handling and Consistent Error Responses. standardHeaders: "draft-8" sends the current standard's headers, and legacyHeaders: false leaves out the older ones. The limiter sits between the path and the handler, so it counts sign-in requests only.

Send a wrong password six times from REST Client. The first five get 401; the sixth gets (the lines that matter):

HTTP/1.1 429 Too Many Requests
RateLimit: "5-in-15min"; r=0; t=900
Retry-After: 900

{"status":429,"title":"Too Many Requests","detail":"Too many sign-in attempts. Try again in 15 minutes."}

429 reads "you've sent too many requests; wait and try again". RateLimit says the policy (5 in 15 minutes), the tries remaining (r=0) and the seconds until the count starts over (t=900), and Retry-After says how long to wait.

Where limits go, and what they count

  • A strict limit on the routes worth guessing at: sign-in and sign-up. Reading roasts needs none, or a far looser one for the whole API with app.use(rateLimit({ ... })).
  • Each address has its own count. A member who mistypes twice isn't locked out by a script somewhere else.
  • The counts live in the server's memory, so a restart starts them again, and two copies of a server count separately. One server is fine; a shared store, such as Redis, is how big sites share the counts.
  • Behind a host's proxy, every request seems to come from the proxy's address. app.set("trust proxy", 1) tells Express to read the real one, and express-rate-limit warns you (ERR_ERL_UNEXPECTED_X_FORWARDED_FOR) when it sees that it's needed.

Check yourself

2 questions to try on the lesson page.

So what

Two app.use lines and one limiter turn a chatty API that lets anyone guess forever into one that gives away nothing and slows guessers to five tries every fifteen minutes, which is the difference between a password list that works and one that takes years.

Key terms

Related