Polski

Tutorial · Web application security · API security

OWASP Top 10:2025 in practice – vulnerable and fixed code in Node.js, Express and React (with live XSS examples)

We walk through the current OWASP Top 10:2025 using the pierogi shop's online store – for every category a real bug in Node.js/Express or React and its fix. IDOR and SSRF (now in A01), misconfiguration, the supply chain, cryptography, SQL and NoSQL injection with a runnable demo, XSS in two interactive playgrounds, insecure design, authentication, integrity (SRI), security event logging and fail-closed exception handling.

By · · 19 min read

Halina's pierogi shop no longer sells only over the counter, but also through an online store: click-and-collect orders, customer reviews, an admin panel that imports menus from suppliers. The first penetration test produced a 40-page report. Almost every finding mapped to one of the OWASP Top 10 categories – the list of the most important web application risks. In this tutorial we go through its current edition, OWASP Top 10:2025, and for each category show vulnerable code, the fix and how to check that it works.

Prerequisites: JavaScript/TypeScript, Express basics (Express tutorial) and React (React tutorial), SQL. The SQL injection demo needs Node.js 24 (the node:sqlite module).

10
risk categories – the 2025 edition, the eighth ever
2
new categories – A03 supply chain, A10 exceptional conditions
A01
Broken Access Control – still number one, now including SSRF
2021 → 2025
the first major update in 4 years – final version in early 2026
  1. 2003 The first list – OWASP publishes its first Top 10 web application risks
  2. 2010–2017 Further editions – 2010, 2013, 2017 – data from companies and the community, XXE and deserialization in 2017
  3. 2021 Seventh edition – Insecure Design, SSRF and Software and Data Integrity Failures for the first time
  4. 2025 Eighth edition – release candidate in November 2025, final version in early 2026 – new A03 and A10
2025CategoryWhat changed since 2021
A01Broken Access Controlstill 1st; SSRF (formerly A10:2021) absorbed into this category
A02Security Misconfigurationup from 5th place
A03Software Supply Chain Failuresnew, extends the former "Vulnerable and Outdated Components" to the whole chain: dependencies, builds, CI/CD
A04Cryptographic Failuresdown from 2nd
A05Injectiondown from 3rd; still includes XSS
A06Insecure Designdown from 4th
A07Authentication Failuresa new, shorter name
A08Software or Data Integrity Failuresno major changes
A09Security Logging and Alerting Failuresemphasis on alerting, not just logging
A10Mishandling of Exceptional Conditionsnew: exception-handling bugs, fail-open, leaks in error messages
Diagram: The pierogi store's attack surface and where the OWASP categories show up

A01 Broken Access Control: IDOR and SSRF

A customer signed in to their account opens /api/orders/1041. They change the number to 1042 – and see someone else's order with an address and phone number. That's IDOR (insecure direct object reference), known as BOLA in the API world. Login worked perfectly; what was missing was the question "does this order belong to this user?".

IDOR: a vulnerable and a fixed orders endpoint

src/orders.vulnerable.ts
import { Router } from 'express';
import pg from 'pg';
import { requireAuth } from './types.js';

const db = new pg.Pool();
export const orders = Router();

// ❌ A01 Broken Access Control (IDOR/BOLA): any logged-in customer reads ANY order
//    by changing the number in the URL: /api/orders/1041 → /api/orders/1042
orders.get('/api/orders/:id', requireAuth, async (req, res) => {
  const { rows } = await db.query('SELECT * FROM orders WHERE id = $1', [req.params.id]);
  res.json(rows[0]); // also leaks every column: address, phone, internal notes
});
src/orders.fixed.ts
import { Router } from 'express';
import pg from 'pg';
import { requireAuth } from './types.js';

const db = new pg.Pool();
export const orders = Router();

// ✅ The ownership check is part of the query, and only the needed columns leave the server.
orders.get('/api/orders/:id', requireAuth, async (req, res) => {
  const { rows } = await db.query(
    'SELECT id, status, total, items, created_at FROM orders WHERE id = $1 AND customer_id = $2',
    [req.params.id, req.user.id],
  );
  if (!rows[0]) { res.sendStatus(404); return; } // 404, not 403 – don't confirm the order exists
  res.json(rows[0]);
});

The ownership check is part of the query (AND customer_id = $2), not a separate if added "somewhere later". Plus only the needed columns and a 404 instead of a 403, so you don't confirm that other people's orders exist. Random identifiers (UUIDs) make guessing harder but don't replace authorization – identifiers leak in links, logs and emails.

SSRF (server-side request forgery) is part of A01 in the 2025 edition: the server makes a request to an address supplied by the user and thereby reaches places the user cannot – internal network services or the cloud metadata service (169.254.169.254), which on EC2 with IMDSv1 hands out the role's temporary credentials.

Diagram: SSRF: the server as a proxy into places the attacker cannot reach

SSRF: importing a menu from a supplier's URL

src/menu-import.vulnerable.ts
import { Router } from 'express';
import { requireAdmin } from './types.js';

export const menuImport = Router();

// ❌ A01 (SSRF): "import the menu from your supplier's URL" – the server fetches whatever it's told:
//    http://169.254.169.254/latest/meta-data/..., http://localhost:6379, http://10.20.3.7/admin
menuImport.post('/api/admin/menu/import', requireAdmin, async (req, res) => {
  const response = await fetch(req.body.url);
  res.json({ preview: (await response.text()).slice(0, 500) }); // …and even shows the answer
});
src/menu-import.fixed.ts
import { Router } from 'express';
import { z } from 'zod';
import { requireAdmin } from './types.js';
import { assertSafeUrl } from './safe-url.js';

export const menuImport = Router();
const Menu = z.array(z.object({ name: z.string().max(120), price: z.number().positive() })).max(500);
declare function saveMenu(menu: z.infer<typeof Menu>): Promise<void>;

// ✅ allowlist + https + public IPs only + no redirects + timeout + size limit + schema validation
menuImport.post('/api/admin/menu/import', requireAdmin, async (req, res) => {
  const url = await assertSafeUrl(String(req.body.url)).catch(() => null);
  if (!url) { res.status(400).json({ error: 'url_not_allowed' }); return; }

  const response = await fetch(url, { redirect: 'error', signal: AbortSignal.timeout(5_000) });
  if (!response.ok) { res.status(502).json({ error: 'supplier_unavailable' }); return; }
  if (Number(response.headers.get('content-length') ?? 0) > 1_000_000) { res.sendStatus(413); return; }

  const menu = Menu.safeParse(await response.json());
  if (!menu.success) { res.status(422).json({ error: 'invalid_menu' }); return; }
  await saveMenu(menu.data); // never echo the raw upstream body back to the client
  res.sendStatus(204);
});
src/safe-url.ts
import { lookup } from 'node:dns/promises';
import { BlockList, isIP } from 'node:net';

// Private, loopback, link-local (incl. 169.254.169.254 – the EC2 metadata service) and other internal ranges.
const internal = new BlockList();
for (const [net, prefix] of [['0.0.0.0', 8], ['10.0.0.0', 8], ['100.64.0.0', 10], ['127.0.0.0', 8],
  ['169.254.0.0', 16], ['172.16.0.0', 12], ['192.168.0.0', 16]] as const) internal.addSubnet(net, prefix, 'ipv4');
for (const [net, prefix] of [['::', 128], ['::1', 128], ['fc00::', 7], ['fe80::', 10]] as const) internal.addSubnet(net, prefix, 'ipv6');

const isInternal = (ip: string) => {
  const mapped = ip.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/i)?.[1]; // IPv4-mapped IPv6
  return mapped ? internal.check(mapped, 'ipv4') : internal.check(ip, isIP(ip) === 6 ? 'ipv6' : 'ipv4');
};

const ALLOWED_HOSTS = new Set(['menu.partner-courier.example', 'cdn.supplier.example']);

/** Throws unless the URL is https, on the allowlist and resolves only to public addresses. */
export async function assertSafeUrl(raw: string): Promise<URL> {
  const url = new URL(raw); // throws on garbage
  if (url.protocol !== 'https:') throw new Error('only https is allowed');
  if (url.username || url.password) throw new Error('credentials in URL are not allowed');
  if (!ALLOWED_HOSTS.has(url.hostname)) throw new Error(`host not allowed: ${url.hostname}`);
  const addresses = await lookup(url.hostname, { all: true });
  if (addresses.some((a) => isInternal(a.address))) throw new Error('resolves to an internal address');
  return url;
}

export { isInternal };
Testing the URL guard – output of node dist/ssrf-check.js
169.254.169.254          BLOCKED
10.20.1.5                BLOCKED
::ffff:169.254.169.254   BLOCKED
fd00:ec2::254            BLOCKED
8.8.8.8                  public
2a00:1450:4001::200e     public
REJECT  http://169.254.169.254/latest/meta-data/ → only https is allowed
REJECT  https://localhost:8080/admin → host not allowed: localhost
REJECT  file:///etc/passwd → only https is allowed
REJECT  https://menu.partner-courier.example@169.254.169.254/ → credentials in URL are not allowed

A host allowlist is the strongest control; checking IP addresses after DNS resolution is the second layer (it catches, for example, IPv4 written as IPv6 and the IPv6 metadata address fd00:ec2::254). Remember the limitation code can't solve: between the check and the connection, DNS may answer differently (DNS rebinding). That's why we add network controls – IMDSv2 required on instances, outbound traffic through a proxy with a domain list, security groups without internal network access for services that fetch user-supplied URLs.

A02, A04, A08: configuration, cryptography and integrity

Three categories that rarely need much code but are easy to forget:

  • A02 Security Misconfiguration – framework defaults, detailed errors with stack traces for clients, open admin panels, Access-Control-Allow-Origin: * with cookies, public buckets. In Express we start with helmet(), a body size limit and a single error handler. Headers are covered in detail in Security headers and CSP, and buckets in S3 bucket security.
  • A04 Cryptographic Failures – Math.random() in password reset tokens, MD5 and SHA-256 for passwords, tokens stored in plain text, no TLS. Generate tokens with crypto.randomBytes, store only their hash, hash passwords with argon2id (authentication tutorial).
  • A08 Software or Data Integrity Failures – code or data whose integrity nobody checks: a script from a CDN, an update downloaded without a signature, an unsigned cookie holding the user's role, deserializing objects from an untrusted source. For CDN scripts – Subresource Integrity (the integrity attribute; I computed the hash below from the npm file and checked it against jsDelivr's response).

Hardened Express, tokens and Subresource Integrity

src/hardening.ts
import express, { type ErrorRequestHandler } from 'express';
import helmet from 'helmet';
import { randomUUID } from 'node:crypto';
import { pino } from 'pino';

const log = pino();
const app = express();

// A02 Security Misconfiguration: safe defaults instead of framework defaults.
app.use(helmet()); // security headers, removes X-Powered-By
app.use(express.json({ limit: '100kb' })); // no 50 MB JSON bodies
app.use((req, res, next) => { res.locals.requestId = randomUUID(); next(); });

// …routes…

// A10 Mishandling of Exceptional Conditions: one place for errors, no stack traces for clients.
const onError: ErrorRequestHandler = (err, req, res, _next) => {
  log.error({ err, requestId: res.locals.requestId, path: req.path }, 'unhandled error');
  res.status(500).json({ error: 'internal_error', requestId: res.locals.requestId });
};
app.use(onError);
process.on('unhandledRejection', (reason) => { log.fatal({ reason }, 'unhandled rejection'); process.exit(1); });

export { app };
src/tokens.ts
import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';

// ❌ A04 Cryptographic Failures: Math.random() is predictable – never for tokens, codes or reset links
export const weakToken = () => Math.random().toString(36).slice(2);

// ✅ a CSPRNG, 256 bits, URL-safe; store only the hash, compare in constant time
export const newResetToken = () => randomBytes(32).toString('base64url');
export const hashToken = (token: string) => createHash('sha256').update(token).digest();
export const sameHash = (a: Buffer, b: Buffer) => a.length === b.length && timingSafeEqual(a, b);
// Passwords: never SHA-256/MD5 – use argon2id (see the authentication tutorial).
public/index.html
<!-- A08 Software or Data Integrity Failures: a script from a CDN must be exactly the file you reviewed.
     If the CDN (or someone who hijacked it) serves different bytes, the browser refuses to run them. -->
<script
  src="https://cdn.jsdelivr.net/npm/dompurify@3.5.0/dist/purify.min.js"
  integrity="sha384-DOUwTXbuiiQxlONuue5N42674XXDfjIJ/LTPtJMZ2ZV1Ir4NRQ3OnM/yM505YQAc"
  crossorigin="anonymous"
></script>
<!-- Generate the hash: curl -s <url> | openssl dgst -sha384 -binary | openssl base64 -A -->

A03 Software Supply Chain Failures

The new category describes a risk that stopped being theoretical in recent years. In September 2025 a hijacked maintainer account of popular npm packages (including chalk and debug) was used to publish versions with malicious code that ran in the browsers of users of applications that installed them. A few days later the Shai-Hulud worm started spreading on its own: it stole npm and GitHub tokens from developer machines and pipelines, then published infected versions of further packages; a second, broader wave followed in November 2025. In March 2025 and March 2026 attackers moved the tags of popular GitHub Actions (tj-actions/changed-files, the Trivy actions) to malicious commits.

The minimum defence: a lockfile and npm ci in CI, reviewed and delayed updates (Renovate/Dependabot with a cooldown), dependency scanning (npm audit, OSV-Scanner), an SBOM, GitHub Actions pinned to a SHA, no long-lived publishing tokens (trusted publishing via OIDC). I show the whole setup in the DevSecOps pipeline tutorial.

A05 Injection: SQL, NoSQL and XSS

Injection always works the same way: user data reaches an interpreter (SQL, a MongoDB query, HTML, a shell) as part of a command. You can run the demo below without a database – Node.js 24 has SQLite built in.

SQL injection (runnable demo) and NoSQL injection

src/sqli-demo.ts
// Runnable demo: node sqli-demo.ts (Node 24) – an in-memory SQLite, no database server needed.
import express from 'express';
import { DatabaseSync } from 'node:sqlite';

const db = new DatabaseSync(':memory:');
db.exec(`CREATE TABLE orders (id INTEGER PRIMARY KEY, customer TEXT, total REAL);
  INSERT INTO orders (customer, total) VALUES ('anna', 64.5), ('bartek', 38.0), ('celina', 121.0);`);
const app = express();

// ❌ A05 Injection: user input glued into SQL
app.get('/v1/orders', (req, res) => {
  const sql = `SELECT id, customer, total FROM orders WHERE customer = '${req.query.customer}'`;
  res.json(db.prepare(sql).all());
});

// ✅ a parameterized query: the input is data, never code (pg: 'WHERE customer = $1', [customer])
app.get('/v2/orders', (req, res) => {
  res.json(db.prepare('SELECT id, customer, total FROM orders WHERE customer = ?').all(String(req.query.customer)));
});

app.listen(3005, () => console.log('http://localhost:3005'));
src/pickup.nosql.ts
import { Router } from 'express';
import mongoose from 'mongoose';
import { z } from 'zod';

const Order = mongoose.model('Order', new mongoose.Schema({ pickupCode: String, status: String }));
export const pickup = Router();

// ❌ A05 NoSQL injection: body {"code": {"$ne": ""}} turns the filter into "any order with a code"
pickup.post('/v1/pickup', async (req, res) => {
  const order = await Order.findOne({ pickupCode: req.body.code });
  res.json(order ? { ok: true, orderId: order.id } : { ok: false });
});

// ✅ validate the shape and type first; sanitizeFilter as a safety net for the whole app
mongoose.set('sanitizeFilter', true); // wraps $-operators coming from user objects in $eq
const PickupBody = z.object({ code: z.string().regex(/^[A-Z0-9]{8}$/) }).strict();

pickup.post('/v2/pickup', async (req, res) => {
  const body = PickupBody.safeParse(req.body);
  if (!body.success) { res.sendStatus(400); return; }
  const order = await Order.findOne({ pickupCode: body.data.code });
  res.json(order ? { ok: true, orderId: order.id } : { ok: false });
});
curl output for both versions of the endpoint (run locally)
$ curl -s "localhost:3005/v1/orders?customer=anna"
[{"id":1,"customer":"anna","total":64.5}]
$ curl -s "localhost:3005/v1/orders?customer=x'%20OR%20'1'='1"
[{"id":1,"customer":"anna","total":64.5},{"id":2,"customer":"bartek","total":38},{"id":3,"customer":"celina","total":121}]
$ curl -s "localhost:3005/v2/orders?customer=x'%20OR%20'1'='1"
[]

The classic ' OR '1'='1 turns the condition into one that is always true and returns every customer's orders. In the parameterized version the same text is just a customer name that doesn't exist in the database. In MongoDB the equivalent is an object with an operator ({"$ne": ""}) where you expect a string – so we validate the shape of the data first (zod), and Mongoose's sanitizeFilter is the safety net.

XSS in the browser – try it yourself

XSS (cross-site scripting) is injection into HTML: text from one user becomes code in another user's browser. The playgrounds below use a classic, harmless payload – an image that fails to load, with an onerror attribute. Instead of stealing cookies, it only changes a section's colour or shows an alarm.

DOM XSS: innerHTML vs textContent – Type your own text or change the payload – the code in the tabs is editable.

/index.html
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>DOM XSS</title>
  </head>
  <body>
    <main>
      <label for="q">Search the menu</label>
      <input id="q" autocomplete="off" />
      <section id="unsafe"><h2>innerHTML ❌</h2><p class="out"></p></section>
      <section id="safe"><h2>textContent ✅</h2><p class="out"></p></section>
    </main>
    <script src="index.js"></script>
  </body>
</html>
/index.js
import "./styles.css";

// A harmless classic: a broken <img> whose onerror marks the section red.
const PAYLOAD = `<img src="x" onerror="this.closest('section').classList.add('pwned')">ruskie`;

const input = document.getElementById("q");
const unsafeOut = document.querySelector("#unsafe .out");
const safeOut = document.querySelector("#safe .out");

function render() {
  document.querySelectorAll("section").forEach((s) => s.classList.remove("pwned"));

  // ❌ the input becomes HTML – tags and event handlers run inside our page
  unsafeOut.innerHTML = `Results for: <b>${input.value}</b>`;

  // ✅ the input stays text – build elements, set textContent
  const b = document.createElement("b");
  b.textContent = input.value;
  safeOut.replaceChildren("Results for: ", b);
}

input.value = PAYLOAD;
input.addEventListener("input", render);
render();
/styles.css
body { font-family: system-ui, sans-serif; margin: 0; padding: 16px; color: #1f2328; }
main { max-width: 640px; display: grid; gap: 10px; }
input { font: 13px ui-monospace, monospace; padding: 8px; }
section { border: 1px solid #d0d7de; border-radius: 8px; padding: 4px 12px; }
section h2 { font-size: 14px; margin: 8px 0 4px; }
.out { word-break: break-all; }
.pwned { background: #ffe3e3; border-color: #ff8787; }
.pwned h2::after { content: " – code from the search box just ran!"; color: #a51111; }

In the first example innerHTML interprets the typed text as HTML, so the browser creates an <img> element and runs its onerror. textContent (and building elements with createElement) inserts the < and > characters as text.

XSS in customer reviews: dangerouslySetInnerHTML vs DOMPurify – Switch modes and watch the red alarm. The payload only changes the page inside the preview.

/App.js
import { useEffect, useState } from "react";
import DOMPurify from "dompurify";

// A harmless classic: an <img> that fails to load runs its onerror handler.
const SAMPLE = "Best <b>pierogi</b> in town! <img src=\"x\" onerror=\"document.getElementById('alarm').hidden = false\">";

const MODES = { unsafe: "dangerouslySetInnerHTML ❌", purified: "DOMPurify ✅", text: "plain text ✅" };

export default function App() {
  const [review, setReview] = useState(SAMPLE);
  const [mode, setMode] = useState("unsafe");

  // Hide the alarm on every change – it reappears only if the payload runs again.
  useEffect(() => {
    document.getElementById("alarm").hidden = true;
  }, [review, mode]);

  const html =
    mode === "purified"
      ? DOMPurify.sanitize(review, { ALLOWED_TAGS: ["b", "i", "em", "strong", "br"], ALLOWED_ATTR: [] })
      : review;

  return (
    <main>
      <p id="alarm" className="alarm" hidden>⚠ Code from a customer review just ran in the browser!</p>
      <label htmlFor="review">Customer review (with HTML)</label>
      <textarea id="review" rows={3} value={review} onChange={(e) => setReview(e.target.value)} />
      <div className="modes">
        {Object.entries(MODES).map(([key, label]) => (
          <label key={key}>
            <input type="radio" name="mode" checked={mode === key} onChange={() => setMode(key)} /> {label}
          </label>
        ))}
      </div>
      <h3>What other customers will see</h3>
      {mode === "text" ? (
        <p className="review">{review}</p>
      ) : (
        <p className="review" dangerouslySetInnerHTML={{ __html: html }} />
      )}
      <h3>HTML that reaches the DOM</h3>
      <pre>{mode === "text" ? "React inserts text – < and > are escaped" : html}</pre>
    </main>
  );
}
/styles.css
body { font-family: system-ui, sans-serif; margin: 0; padding: 16px; color: #1f2328; }
main { max-width: 640px; display: grid; gap: 10px; }
textarea { width: 100%; font: 13px ui-monospace, monospace; padding: 8px; box-sizing: border-box; }
.modes { display: flex; flex-wrap: wrap; gap: 14px; font-size: 14px; }
.review { border: 1px solid #d0d7de; border-radius: 8px; padding: 10px 12px; min-height: 24px; }
pre { background: #f6f8fa; padding: 10px; border-radius: 8px; white-space: pre-wrap; word-break: break-all; font-size: 12px; }
.alarm { background: #ffe3e3; color: #a51111; border: 1px solid #ffa8a8; border-radius: 8px; padding: 8px 12px; margin: 0; font-weight: 600; }
h3 { margin: 8px 0 0; font-size: 14px; }

React escapes everything you put in JSX by default – "plain text" mode is safe with no extra work. The risk appears when you bypass that mechanism: dangerouslySetInnerHTML, ref.current.innerHTML, javascript: URLs in href (React 19 blocks them and replaces them with a URL that throws an error; older versions only warned), or HTML from a WYSIWYG editor. If you really need HTML, run it through DOMPurify with a narrow tag allowlist – ideally on the server when saving and again in the browser when displaying. The second line of defence is a Content Security Policy, which won't let an injected script run even if it reaches the page.

A06 Insecure Design: a flaw in the design, not the code

The pierogi shop's pickup codes had 4 digits. The code was flawless: validation, parameters, cashier authorization. The problem is that 10,000 combinations can be tried by a script in a few minutes, and an "invalid code" response limits nothing. No library fixes that – the design has to change: 8-character codes of letters and digits (almost 3 trillion combinations), an attempt limit per order and per IP address, a lockout after 5 failures, a notification to the customer.

Problems like this are caught by threat modeling at design time ("what can go wrong in this flow?") and abuse cases written next to user stories. More on building that into the process in the DevSecOps pipeline tutorial.

A07 Authentication Failures

No limits on login attempts (credential stuffing from leaked databases), weak password resets, sessions that never expire, no MFA for the admin panel, session identifiers in URLs. This topic has its own, extensive tutorial: Login and registration (argon2id, refresh token rotation, cookies, OAuth/OIDC, attempt limits). Rate limiting for the whole API is covered in API security.

A09 and A10: logging, alerting and exceptional conditions

The new category A10 Mishandling of Exceptional Conditions collects bugs that appear when something goes wrong: an exception swallowed in a catch block that returns true, an unhandled promise rejection that brings the process down, database details in an error message for the client, a transaction aborted halfway. A09 reminds us that without security events in logs and alerts on their growth, an attack goes on for weeks before anyone notices.

Refunds: fail-open vs fail-closed with event logging

src/refunds.ts
import { Router } from 'express';
import { pino } from 'pino';
import { requireAuth } from './types.js';

const log = pino();
declare const policy: { check(userId: string, action: string, resourceId: string): Promise<boolean> };
export const refunds = Router();

// ❌ A10: fail-open – when the policy service times out, EVERYONE may refund
export async function canRefundFailOpen(userId: string, orderId: string) {
  try { return await policy.check(userId, 'order:refund', orderId); } catch { return true; }
}

// ✅ fail closed + A09: security events are logged (without secrets) so alarms can fire on spikes
async function canRefund(userId: string, orderId: string) {
  try {
    return await policy.check(userId, 'order:refund', orderId);
  } catch (err) {
    log.error({ err, event: 'authz.error', userId, orderId }, 'policy check failed – denying');
    return false;
  }
}

refunds.post('/api/orders/:id/refund', requireAuth, async (req, res) => {
  if (!(await canRefund(req.user.id, req.params.id))) {
    log.warn({ event: 'authz.denied', userId: req.user.id, action: 'order:refund', orderId: req.params.id }, 'access denied');
    res.sendStatus(403);
    return;
  }
  // …refund…
  res.sendStatus(202);
});

The rule: when a security check errors, deny (fail closed). A customer who can't request a refund for a minute is a smaller problem than a minute in which anyone can refund any order. authz.denied and authz.error events (no passwords, tokens or personal data) go to the logs, and an alarm on a sudden spike goes to on-call (observability tutorial).

Cheat sheet: one control per category

CategoryThe key control in the storeHow to check
A01owner in every query, host allowlist for fetchestests with two accounts, a 169.254.169.254 attempt
A02helmet, limits, one error handler, no default passwordsheader scan, IaC configuration review
A03lockfile, npm ci, dependency scanning, actions pinned to SHAnpm audit / OSV-Scanner in CI
A04a CSPRNG for tokens, argon2id for passwords, TLScode review, TLS configuration tests
A05SQL parameters, shape validation, text instead of HTMLpayload tests, SAST (Semgrep, CodeQL)
A06threat modeling, limits in business flowsabuse cases in tests
A07attempt limits, MFA, secure sessionslogin tests, DAST scan
A08SRI, signed artifacts, no deserialization of untrusted datafrontend dependency review
A09security events in logs, alarmstest: does an alarm arrive after 50 denials?
A10fail closed, global error handling, no details for clientstests with a dependency switched off (e.g. the permission service)

Common mistakes

  • Input "sanitization" instead of output encoding – stripping <script> from text doesn't protect against <img onerror>. Escape where the data enters HTML, SQL or a shell.
  • Address blocklists against SSRF – there's always a notation you didn't foresee (decimal, IPv6, a redirect). A host allowlist plus network controls.
  • A stack trace in a 500 response – a map of your application for the attacker.
  • One scan before launch – dependencies and configuration change every week; scan in every pipeline.

The OWASP Top 10 list

  • a common language for developers, testers and auditors
  • a good checklist for code review and test planning
  • based on application testing data, CWE analysis and a community survey

What it won't replace

  • it's a risk awareness list, not a complete standard – use OWASP ASVS for verification
  • it doesn't cover API-specific risks (separate list: API Security Top 10) or LLMs
  • it won't replace threat modeling for your specific system

Test yourself

Question: `GET /api/orders/:id` requires login and uses UUIDs as identifiers. Is it secure?

  • Yes – UUIDs can't be guessed
  • No, if the query doesn't check that the order belongs to the signed-in customer
  • Yes – login is enough

Question: A React component renders a review with `dangerouslySetInnerHTML` because customers can bold text. What is the best fix?

  • Remove the string `<script>` from the text
  • Sanitize the HTML with DOMPurify using a tag allowlist (e.g. `b`, `i`) and add a CSP
  • Replace `dangerouslySetInnerHTML` with `innerHTML` in `useEffect`
Interview question: what changed in OWASP Top 10:2025 and what does it mean for a team?

A good answer names the two new categories: A03 Software Supply Chain Failures (extending the former vulnerable components category to the whole chain – dependencies, build systems, CI/CD, distribution) and A10 Mishandling of Exceptional Conditions (poor exception handling, fail-open, information leaks in errors). Further: SSRF is no longer a separate category and is part of A01 Broken Access Control, which is still number one; Security Misconfiguration moved up to second place. The practical conclusion: object-level authorization in every endpoint and tests with two accounts, supply-chain hygiene in the pipeline (lockfile, scanning, SBOM, pinned actions, OIDC instead of tokens), a fail-closed policy and consistent error handling, configuration as code with review. Bonus points for mentioning that OWASP ASVS is the verification standard, and APIs have a separate API Security Top 10.

What's next