
APIs fail differently from web pages. There's no HTML to hide behind, every endpoint is a documented door, and an attacker can script thousands of requests a minute against any of them.
OWASP keeps a separate Top 10 for exactly this, distinct from its main list for web applications. The current edition is the 2023 list, which is still the latest on OWASP's project page as I write this.
Each risk below gets a plain-English summary and a Node.js fix. The examples use Express 5, where a rejected promise in an async handler reaches your error handler automatically (on Express 4, wrap async handlers yourself). The ideas carry over to Fastify, NestJS and anything else.
# | Risk | One-line fix |
|---|---|---|
API1 | Broken Object Level Authorization | Put ownership in the query, not just the ID |
API2 | Broken Authentication | Slow password hashes, strict token checks, login rate limits |
API3 | Broken Object Property Level Authorization | Allowlist the fields you accept and return |
API4 | Unrestricted Resource Consumption | Cap rate, body size, page size and time |
API5 | Broken Function Level Authorization | Deny by default, require a role per route |
API6 | Unrestricted Access to Sensitive Business Flows | Limit the flow, not just the endpoint |
API7 | Server Side Request Forgery | Allowlist destinations, block internal addresses |
API8 | Security Misconfiguration | Harden headers, CORS and error output |
API9 | Improper Inventory Management | Keep one spec, retire old versions |
API10 | Unsafe Consumption of APIs | Validate third-party responses like user input |
Most of these map to a step in the life of a request. Authorization is the cluster that matters most: function, then object, then property.
flowchart LR
R["Request"] --> A["Authenticate<br/>API2"]
A --> L["Limit rate and size<br/>API4, API6"]
L --> F["May this role call it?<br/>API5"]
F --> O["Is this object theirs?<br/>API1"]
O --> P["Which fields in and out?<br/>API3"]
P --> H["Handler"]
H --> X["Outbound calls<br/>API7, API10"]
classDef edge fill:#dbeafe,stroke:#3b82f6,color:#1e3a8a
classDef authz fill:#fef3c7,stroke:#f59e0b,color:#78350f
classDef app fill:#dcfce7,stroke:#22c55e,color:#14532d
classDef out fill:#fee2e2,stroke:#ef4444,color:#7f1d1d
class R,A,L edge
class F,O,P authz
class H app
class X outAPI8 and API9 wrap around the whole pipeline: how it's configured, and what you've actually deployed.
API1: Broken Object Level Authorization
This is the big one, and the easiest to exploit. A user requests /orders/1043, the API loads order 1043, and nothing checks whether it's theirs. Change the number, read someone else's order.
The fix is to put ownership into the query itself. A record that doesn't exist and a record that isn't yours should look the same to the caller.
app.get("/orders/:id", requireAuth, async (req, res) => {
const { rows } = await db.query(
"SELECT * FROM orders WHERE id = $1 AND user_id = $2",
[req.params.id, req.user.id]
);
if (rows.length === 0) return res.status(404).json({ title: "Not found", status: 404 });
res.json(rows[0]);
});Unguessable IDs such as UUIDs help, but they aren't a control. Check ownership anyway. Then write one test where user A asks for user B's object and expects a 404. It's the cheapest security test you'll ever write.
API2: Broken Authentication
This covers anything that lets someone pose as someone else: weak login protection, careless token handling, credentials in URLs. Most of the damage comes from three mistakes:
Passwords stored with a fast hash, or worse. Use a slow, salted algorithm such as argon2id.
No brute-force protection on login and password reset. Limit attempts per account as well as per IP.
Tokens accepted without strict checks. Pin the algorithm and verify issuer, audience and expiry.
import * as argon2 from "argon2";
import { createRemoteJWKSet, jwtVerify } from "jose";
// Passwords: argon2id is the default in current versions
const hash = await argon2.hash(password);
const ok = await argon2.verify(hash, password);
// Tokens: pin the algorithm, check issuer and audience, and require an expiry
const jwks = createRemoteJWKSet(new URL("https://auth.example.com/.well-known/jwks.json"));
const { payload } = await jwtVerify(token, jwks, {
algorithms: ["RS256"],
issuer: "https://auth.example.com/",
audience: "orders-api",
requiredClaims: ["exp"], // reject tokens that never expire
});API3: Broken Object Property Level Authorization
This merges two older risks: returning too many fields (excessive data exposure) and accepting too many (mass assignment). It looks like User.update(req.body) letting a caller send { "role": "admin" }, or res.json(user) sending passwordHash out along with the name.
Allowlist in both directions: a strict schema for input, and an explicit mapper for output.
import { z } from "zod";
const UpdateProfile = z
.object({ name: z.string().min(1).max(80), bio: z.string().max(500) })
.partial()
.strict(); // unknown keys such as "role" are rejected
const toPublicUser = ({ id, name, bio }) => ({ id, name, bio });
app.patch("/me", requireAuth, async (req, res) => {
const input = UpdateProfile.safeParse(req.body);
if (!input.success) return res.status(422).json({ title: "Validation failed", status: 422 });
const user = await users.update(req.user.id, input.data);
res.json(toPublicUser(user));
});API4: Unrestricted Resource Consumption
Every request costs CPU, memory and bandwidth, and sometimes real money: SMS, email, AI calls, paid third-party APIs. If clients can ask for unlimited amounts of anything, one script can knock you over or run up the bill.
Cap what a single caller can consume: request rate, body size, page size, request time, upload size, and spend on paid downstream calls.
import express from "express";
import rateLimit from "express-rate-limit";
app.set("trust proxy", 1); // the number of proxies in front of your app
app.use(rateLimit({ windowMs: 60_000, limit: 100, standardHeaders: "draft-7", legacyHeaders: false }));
app.use(express.json({ limit: "100kb" }));
// Clamp page size, whatever the client asks for
const pageSize = (value) => Math.min(Math.max(Number.parseInt(value, 10) || 20, 1), 100);Two gotchas. Behind a proxy or load balancer, get trust proxy right or every client shares the proxy's IP. And the default in-memory store is per process, so use a shared store such as Redis once you run more than one instance.
Also set server.requestTimeout and server.headersTimeout deliberately instead of living with the defaults. If you expose GraphQL, limit query depth and batching too.
API5: Broken Function Level Authorization
Here the object may be yours, but the function isn't: a regular user calling an admin endpoint, or sending DELETE where the UI only ever uses GET. It usually happens because authorization is added per screen instead of per route.
Make deny-by-default the rule, and attach the required role to each route.
const requireRole = (...roles) => (req, res, next) =>
roles.includes(req.user?.role)
? next()
: res.status(403).json({ title: "Forbidden", status: 403 });
app.use("/admin", requireAuth, requireRole("admin")); // everything under /admin
app.delete("/users/:id", requireAuth, requireRole("admin"), deleteUser);Take the role from your verified token or session, never from the request body or a header the client controls. Then test every route with a low-privilege user.
API6: Unrestricted Access to Sensitive Business Flows
Nothing is technically broken here. The endpoint does what it was built to do, and the abuse is in how it's used: bots buying out limited stock, coupon farming, mass fake signups, scraping every profile. Scanners won't find these.
Start by listing the flows where automation hurts the business, then limit those flows specifically:
Per-account and per-device limits, not just per IP.
Quantity caps on things like tickets and coupons.
Step-up checks (email or phone verification, CAPTCHA) for risky actions.
Monitoring for patterns, such as one account doing the same thing hundreds of times.
import rateLimit from "express-rate-limit";
const checkoutLimiter = rateLimit({
windowMs: 60 * 60 * 1000,
limit: 5,
keyGenerator: (req) => req.user.id, // per account, not per IP
});
app.post("/checkout", requireAuth, checkoutLimiter, checkout);API7: Server Side Request Forgery
If your API fetches a URL the caller supplied (webhooks, link previews, image imports), an attacker can point it at things only your server can reach. That means internal services, or the cloud metadata endpoint at 169.254.169.254, which can hand out credentials.
Allowlist the destinations if you can. Either way, resolve the hostname yourself, refuse internal and link-local addresses, and don't follow redirects.
import { BlockList } from "node:net";
import { lookup } from "node:dns/promises";
const blocked = new BlockList();
blocked.addSubnet("10.0.0.0", 8);
blocked.addSubnet("172.16.0.0", 12);
blocked.addSubnet("192.168.0.0", 16);
blocked.addSubnet("127.0.0.0", 8);
blocked.addSubnet("0.0.0.0", 8); // "this network", often reaches localhost
blocked.addSubnet("100.64.0.0", 10); // shared address space, used for metadata by some providers
blocked.addSubnet("169.254.0.0", 16); // link-local, includes cloud metadata
blocked.addAddress("::", "ipv6"); // unspecified
blocked.addSubnet("::1", 128, "ipv6");
blocked.addSubnet("fc00::", 7, "ipv6"); // unique local
blocked.addSubnet("fe80::", 10, "ipv6"); // link-local
const ALLOWED_HOSTS = new Set(["api.partner.example"]); // drop only if you truly must accept any host
export async function safeFetch(rawUrl) {
const url = new URL(rawUrl);
if (url.protocol !== "https:" || !ALLOWED_HOSTS.has(url.hostname)) {
throw new Error("URL not allowed");
}
const addresses = await lookup(url.hostname, { all: true });
for (const { address, family } of addresses) {
if (blocked.check(address, family === 6 ? "ipv6" : "ipv4")) {
throw new Error("Address not allowed");
}
}
return fetch(url, { redirect: "error", signal: AbortSignal.timeout(5_000) });
}This still has a gap. The name is resolved once for the check and again when fetch connects, so DNS rebinding can slip through. For high-risk features, pin the checked address when connecting, or send these calls through an egress proxy that blocks internal ranges. On AWS, also require IMDSv2 on your instances.
API8: Security Misconfiguration
The unglamorous one: debug mode in production, stack traces in error responses, permissive CORS, missing security headers, default credentials, unpatched dependencies. Every item is simple. The trouble is that nobody owns the checklist.
import helmet from "helmet";
import cors from "cors";
app.use(helmet()); // sensible security headers, and no X-Powered-By
app.use(cors({ origin: ["https://app.example.com"] })); // explicit origins, never a reflected Origin
// Register this last, after your routes. Log the details, return a generic message.
app.use((err, req, res, next) => {
console.error(err);
res.status(500).json({ title: "Internal Server Error", status: 500 });
});Beyond the code: run with NODE_ENV=production, terminate TLS everywhere, run npm audit in CI, and keep secrets out of logs and error output.
API9: Improper Inventory Management
You can't protect endpoints you've forgotten about. Old /v1 routes that skipped the new auth middleware, debug endpoints, a staging API holding real data. Attackers find these because they're usually the weakest door.
Treat inventory as an engineering task, not a spreadsheet:
Keep an OpenAPI spec as the source of truth, and generate it from code where you can (
@nestjs/swaggerand@fastify/swaggerboth do).Compare the spec with real traffic from your gateway logs to spot undocumented routes.
Retire old versions on a schedule, and announce it with
DeprecationandSunsetheaders.Keep non-production environments off real data and off the public internet.
API10: Unsafe Consumption of APIs
We tend to trust third-party APIs more than we trust users, and that's backwards. A partner's response can be malformed, compromised, or changed without notice, and it often flows straight into your database, your logs or your own responses.
Validate what comes back as strictly as what goes in.
import { z } from "zod";
const PartnerOrder = z.object({
id: z.string().max(64),
total: z.number().nonnegative(),
currency: z.string().length(3),
});
const res = await fetch(url, { redirect: "error", signal: AbortSignal.timeout(5_000) });
if (!res.ok) throw new Error(`Partner API returned ${res.status}`);
const order = PartnerOrder.parse(await res.json());Add timeouts and a response size cap, use TLS, and never build SQL or HTML straight from a response.
Where to start
You don't need to fix all ten at once. If you have a week, do these in order:
Write authorization tests for API1 and API5: every route, with a user who shouldn't have access.
Put schemas on every input and output (API3, API10).
Add rate limits, body limits and page-size caps (API4, API6).
Build the inventory (API9), then work through the configuration list (API8).
The list is a starting point, not a full audit. It won't replace threat modeling or a penetration test, but it covers the mistakes that show up again and again.
Comments0
Log in to join the discussion.
No comments yet.