Difficulty: Advanced
What are the most important security risks for a REST API and how would you mitigate them?
API security is layered, like protecting a bank branch: locked doors, ID checks at the counter, limited access to the vault, cameras, and alarms. No single control is enough. The OWASP API Security Top 10 is the standard checklist, and being able to walk through the top items with concrete mitigations is a strong interview answer.
Broken object level authorization (BOLA/IDOR) is number one. If GET /orders/{id} returns any order to any authenticated user, attackers simply iterate ids. Fix: check ownership or permission on every object access, scoping queries by the caller (WHERE id = ? AND user_id = ?), and test for it explicitly. Broken authentication: weak password reset flows, missing rate limits on login, long-lived tokens, JWTs with alg none or unchecked signatures. Fix: strong hashing (argon2 or bcrypt), MFA, short-lived tokens, rate limiting and lockouts, verifying iss, aud and exp.
Broken object property level authorization covers two things: excessive data exposure, where the API returns whole database rows including internal fields such as password_hash or cost_price and relies on the client to hide them, and mass assignment, where request bodies are bound straight to models so a user can send role=admin or balance=1000000. Fix: explicit response DTOs or serializers, and allowlists (schema validation) for accepted input fields.
Unrestricted resource consumption: no rate limits, unbounded page sizes, huge payloads, expensive queries or GraphQL depth abuse lead to denial of service and cost blowups. Fix: rate limits and quotas, maximum page size and body size, timeouts, query cost limits, and pagination everywhere. Broken function level authorization: normal users hitting admin endpoints because only the UI hides them. Fix: role checks in middleware for every route, deny by default.
Server-side request forgery (SSRF): endpoints that fetch user-supplied URLs (webhook targets, image imports, URL shorteners) can be pointed at internal services or cloud metadata (169.254.169.254). Fix: allowlists, block private IP ranges after DNS resolution, disable redirects or revalidate them, and use IMDSv2. Security misconfiguration: verbose stack traces, permissive CORS, default credentials, missing security headers, unpatched dependencies, exposed debug endpoints. Fix: hardened baselines, minimal error detail, HTTPS with HSTS, dependency scanning, and CORS allowlists.
Improper inventory management: forgotten old versions, shadow or zombie endpoints and staging APIs exposed publicly. Fix: keep an API inventory tied to the OpenAPI spec, retire old versions and monitor gateway logs. Unsafe consumption of third-party APIs: trusting upstream data blindly. Fix: validate and sanitise responses, set timeouts and use TLS.
Cross-cutting practices. Validate every input against a schema (types, lengths, formats) at the boundary, and use parameterised queries to defeat SQL injection; the same goes for NoSQL operators. Always HTTPS. Keep secrets out of URLs and logs, since query strings are logged everywhere. Use security headers such as Content-Type: application/json plus X-Content-Type-Options: nosniff. Log authentication and authorization failures with request ids and alert on anomalies, but never log secrets, tokens or card data. Encrypt sensitive data at rest, rotate keys, and scan secrets in repositories.
When answering, pick the top four or five risks, name the attack in one line, and give the concrete fix. That structure sounds much stronger than reciting the list.
import { z } from 'zod';
const UpdateProfile = z.object({
name: z.string().min(1).max(80).optional(),
phone: z.string().regex(/^\+?[0-9]{10,13}$/).optional()
}).strict(); // unknown keys such as role are rejected
app.patch('/v1/me', requireAuth, async (req, res) => {
const parsed = UpdateProfile.safeParse(req.body);
if (!parsed.success) return res.status(422).json({ title: 'Validation failed', errors: parsed.error.issues });
const user = await db.user.update({ where: { id: req.auth.sub }, data: parsed.data });
res.json({ id: user.id, name: user.name, phone: user.phone }); // explicit DTO, no password hash
});
A strict schema blocks mass assignment, the update is scoped to the caller, and the response is an explicit DTO.
import dns from 'dns/promises';
import net from 'net';
async function assertPublicUrl(raw) {
const u = new URL(raw);
if (!['http:', 'https:'].includes(u.protocol)) throw new Error('Bad scheme');
const { address } = await dns.lookup(u.hostname);
const isPrivate = /^(10\.|127\.|192\.168\.|169\.254\.|172\.(1[6-9]|2\d|3[01])\.)/.test(address) || address === '::1';
if (net.isIP(address) === 0 || isPrivate) throw new Error('Blocked address');
}
Resolves the hostname and blocks loopback, private and metadata addresses before fetching.
API security, OWASP, input validation, mass assignment