Skip to content
Derar Sattouf

OWASP Top 10 for Developers: Vulnerable Code and Practical Fixes

Updated Security

OWASP Top 10 for Developers: Vulnerable Code and Practical Fixes

The OWASP Top 10 is the most quoted and least applied document in application security. Teams cite it in audits, then ship the same bugs: an endpoint that trusts an ID from the URL, a query built with string concatenation, a dependency nobody has updated in two years. The list isn't a checklist of ten things to avoid. It's ten families of mistakes, each containing dozens of concrete weaknesses, and each with a boring, well-understood fix.

The code is in TypeScript (Node and Next.js), Python (FastAPI and Flask) and PHP (Laravel and plain PHP), because those are the stacks where these bugs show up most. Everything here is defensive: the vulnerable snippets exist so you can recognise the pattern in your own code review, not to attack anything.

As of late 2026 the current edition is the OWASP Top 10:2025, which replaced the 2021 list. The 2025 list is ranked: A01 Broken Access Control, A02 Security Misconfiguration, A03 Software Supply Chain Failures, A04 Cryptographic Failures, A05 Injection, A06 Insecure Design, A07 Authentication Failures, A08 Software or Data Integrity Failures, A09 Security Logging and Alerting Failures, A10 Mishandling of Exceptional Conditions. Server-Side Request Forgery (SSRF), a standalone category in 2021, is now folded into A01. Verify the current text on top10.owasp.org before you cite numbers in a compliance document, because audit templates and scanners still map to both editions.

This is the companion to two earlier posts: OAuth 2.1 and OIDC: Common API Security Pitfalls goes deep on authentication flows and token handling, and Prompt Injection Defense for AI Agents covers the LLM-specific injection class. Read them for A07 and for the AI side of A05.

Most real breaches come from a handful of patterns: missing object-level authorization checks, string-built queries, default or leaked configuration, vulnerable or malicious dependencies, and weak secrets handling. Fix them at the framework level rather than per endpoint: deny-by-default authorization middleware, parameterized queries only, an ORM with safe defaults, a lockfile plus automated updates, and centralized error handling.

Automate the boring half. Use Semgrep or CodeQL for code patterns, a software composition analysis scanner for dependencies, Trivy for images and IaC, gitleaks for secrets, and ZAP for a running app. Fail the build on high-confidence findings only, or developers will ignore the pipeline. Test authorization explicitly too: every endpoint that takes an ID needs a test where user B requests user A's resource and gets a 403 or 404.

Design matters as much as code. Rate limits, abuse cases, and threat models catch the flaws no scanner can (see the threat modeling guide). And a scanner that finds zero issues is not proof of security. It's proof you haven't yet found the next one.

Where to start

The sections follow the 2025 ranking, except that SSRF gets its own section because it behaves differently from classic access control. If you're adding an endpoint, read A01, A05 and A10, then the secure code review checklist. For a pull request review, go straight to that checklist and jump to the category it flags. If you're setting up CI, start with the CI security pipeline and read A03 and A04 for dependency and secrets handling. For a security sprint, the maturity roadmap near the end is the place to start, with A06 and A09 for design and logging. An AI agent reviewing code should use the checklist and the "what to grep for" lines in each section, and report with file and line rather than auto-merging fixes.

A01: Broken Access Control (including IDOR)

What it is

Access control decides who may do what to which resource. It breaks when the server trusts the client for that decision. The two most common forms:

  • IDOR (insecure direct object reference), also called BOLA (broken object level authorization) in API security. The endpoint accepts an identifier and returns the object without checking the caller owns it.
  • Missing function-level authorization. An admin action is hidden in the UI but the endpoint accepts any authenticated user.

Other members of the family: privilege escalation by changing a role field in a JSON body (mass assignment), path traversal, CORS misconfiguration that lets another origin read authenticated responses, and forced browsing to unlinked pages. In 2025 the category also covers SSRF, discussed in the SSRF section below.

Vulnerable code: TypeScript (Next.js route handler)

// app/api/invoices/[id]/route.ts  -- VULNERABLE
import { db } from "@/lib/db";
import { getSession } from "@/lib/auth";

export async function GET(
  _req: Request,
  { params }: { params: Promise<{ id: string }> },
) {
  const session = await getSession();
  if (!session) return new Response("Unauthorized", { status: 401 });

  const { id } = await params;
  // Authenticated, but never checks that the invoice belongs to this user.
  const invoice = await db.invoice.findUnique({ where: { id } });
  return Response.json(invoice);
}

Any logged-in user can iterate IDs and read every invoice. Sequential integer IDs make it trivial; UUIDs only make it harder to guess, not impossible to exploit once one leaks in a log, a URL or an email.

The fix

Scope every query by the owner, and make "not yours" indistinguishable from "does not exist".

// app/api/invoices/[id]/route.ts  -- FIXED
import { z } from "zod";
import { db } from "@/lib/db";
import { requireSession } from "@/lib/auth";

const Params = z.object({ id: z.string().uuid() });

export async function GET(
  _req: Request,
  ctx: { params: Promise<{ id: string }> },
) {
  const session = await requireSession(); // throws 401 if absent
  const { id } = Params.parse(await ctx.params);

  const invoice = await db.invoice.findFirst({
    where: { id, organizationId: session.organizationId },
    select: { id: true, total: true, currency: true, issuedAt: true },
  });

  if (!invoice) return new Response("Not found", { status: 404 });
  return Response.json(invoice);
}

Three habits are in that snippet. The ownership predicate is part of the query, not a check after the fact. The response uses select, an allow-list of fields, instead of returning the whole row. And the not-found and forbidden cases return the same status so an attacker cannot probe which IDs exist.

Vulnerable and fixed: Python (FastAPI)

# VULNERABLE: trusts the path parameter
@app.get("/documents/{doc_id}")
def get_document(doc_id: int, user: User = Depends(current_user)):
    return db.query(Document).get(doc_id)
# FIXED: ownership is part of the query; a policy function centralizes rules
def visible_documents(user: User):
    return db.query(Document).filter(Document.tenant_id == user.tenant_id)

@app.get("/documents/{doc_id}", response_model=DocumentOut)
def get_document(doc_id: int, user: User = Depends(current_user)):
    doc = visible_documents(user).filter(Document.id == doc_id).first()
    if doc is None:
        raise HTTPException(status_code=404)
    return doc

Using response_model is a quiet but important control: it strips any attribute not declared in DocumentOut, which also prevents leaking internal columns.

Vulnerable and fixed: PHP (Laravel)

// VULNERABLE: mass assignment lets a client set is_admin
public function update(Request $request, User $user)
{
    $user->update($request->all());
    return $user;
}
// FIXED: policy + validated allow-list of fields
public function update(UpdateProfileRequest $request, User $user)
{
    $this->authorize('update', $user); // UserPolicy::update

    $user->update($request->validated()); // only name, locale, timezone
    return new UserResource($user);
}
// app/Policies/UserPolicy.php
public function update(User $actor, User $target): bool
{
    return $actor->id === $target->id || $actor->hasRole('admin');
}

Design principles that prevent the class

PrincipleConcrete practice
Deny by defaultMiddleware requires an explicit policy on every route; an unlabeled route returns 403 in tests
Scope in the queryRepository layer takes a tenant or owner argument; no unscoped findById exists in the codebase
Server decides rolesNever read role, isAdmin, userId from the request body or a client-controlled cookie
Opaque, unguessable IDsUUIDv4/v7 or ULIDs reduce enumeration but never replace the check
Centralize policyOne module (Laravel Policies, CASL, Oso, Cerbos, OpenFGA) rather than scattered if statements
Row-level safety netDatabase row-level security as a second layer; see multi-tenant Postgres with RLS

Test it: the cross-user matrix

The single most valuable security test you can write is the two-user test. Create user A and user B, create a resource as A, then call every endpoint that takes an ID as B.

// tests/authz.test.ts (Vitest + supertest style)
import { describe, it, expect, beforeAll } from "vitest";
import { api, createUser, asUser } from "./helpers";

describe("invoice authorization", () => {
  let a: Awaited<ReturnType<typeof createUser>>;
  let b: Awaited<ReturnType<typeof createUser>>;
  let invoiceId: string;

  beforeAll(async () => {
    a = await createUser("a@example.test");
    b = await createUser("b@example.test");
    invoiceId = (await asUser(a).post("/api/invoices").send({ total: 10 })).body.id;
  });

  it("owner can read", async () => {
    const res = await asUser(a).get(`/api/invoices/${invoiceId}`);
    expect(res.status).toBe(200);
  });

  it("other user gets 404, not 403 and not data", async () => {
    const res = await asUser(b).get(`/api/invoices/${invoiceId}`);
    expect(res.status).toBe(404);
    expect(res.text).not.toContain("total");
  });

  it("unauthenticated gets 401", async () => {
    const res = await api.get(`/api/invoices/${invoiceId}`);
    expect(res.status).toBe(401);
  });
});

Generate this matrix from your route list so new endpoints cannot skip it. A common approach is to export the router table, iterate every route with an ID parameter, and assert that a second user cannot read, update or delete.

Automation

  • Semgrep: rules for "handler uses params.id without ownership predicate" are project-specific; write two or three custom rules for your data layer.
  • CodeQL: has queries for missing authorization and path injection on supported languages.
  • DAST: ZAP and Burp can replay requests with a second session; authenticated scans with two users find many IDORs.
  • Linters: eslint-plugin-security flags a few patterns; do not expect it to find IDOR.

Common mistakes

  1. Checking authorization in the UI only.
  2. Authorizing the parent but not the child: user may read project 5, then fetches /projects/5/files/99 where file 99 belongs to project 6.
  3. Returning 403 for other people's objects and 404 for missing ones, leaking existence.
  4. Trusting a JWT claim that the client can influence, or caching authorization decisions across users.
  5. Allowing PATCH bodies to set any column.
  6. CORS Access-Control-Allow-Origin reflected from the request with credentials allowed.

Checklist

  • Every route has an explicit authorization policy; the default is deny.
  • Every query that loads by ID also filters by owner or tenant.
  • Request bodies are validated against an allow-list schema.
  • Responses use explicit output schemas or DTOs.
  • A cross-user test exists for every ID-taking endpoint.
  • CORS origins are an explicit allow-list.

A02: Security Misconfiguration

What it is

The code is fine and the deployment is not. Default credentials, debug mode in production, open cloud storage buckets, verbose error pages, missing security headers, permissive CORS, unnecessary services exposed, an admin panel on the public internet, or a container running as root. It moved up to second place in 2025 because modern stacks have so many configuration surfaces: cloud IAM, Kubernetes manifests, CI settings, framework flags.

Vulnerable examples

# Kubernetes: VULNERABLE deployment defaults
apiVersion: apps/v1
kind: Deployment
metadata:
  name: api
spec:
  template:
    spec:
      containers:
        - name: api
          image: myorg/api:latest
          securityContext:
            privileged: true
          env:
            - name: DEBUG
              value: "true"
# Flask: VULNERABLE
app.run(host="0.0.0.0", debug=True)  # Werkzeug debugger allows code execution
// Laravel .env in production: VULNERABLE
// APP_DEBUG=true prints stack traces, config values and sometimes secrets

The fix

# Kubernetes: hardened
apiVersion: apps/v1
kind: Deployment
metadata:
  name: api
spec:
  template:
    spec:
      automountServiceAccountToken: false
      securityContext:
        runAsNonRoot: true
        seccompProfile:
          type: RuntimeDefault
      containers:
        - name: api
          image: ghcr.io/myorg/api@sha256:REPLACE_WITH_DIGEST
          securityContext:
            allowPrivilegeEscalation: false
            readOnlyRootFilesystem: true
            capabilities:
              drop: ["ALL"]
          resources:
            requests: { cpu: "100m", memory: "128Mi" }
            limits: { memory: "256Mi" }

Security headers in Next.js:

// next.config.ts
import type { NextConfig } from "next";

const securityHeaders = [
  { key: "Strict-Transport-Security", value: "max-age=63072000; includeSubDomains; preload" },
  { key: "X-Content-Type-Options", value: "nosniff" },
  { key: "Referrer-Policy", value: "strict-origin-when-cross-origin" },
  { key: "Permissions-Policy", value: "camera=(), microphone=(), geolocation=()" },
  {
    key: "Content-Security-Policy",
    value:
      "default-src 'self'; img-src 'self' data: https:; script-src 'self'; " +
      "object-src 'none'; base-uri 'self'; frame-ancestors 'none'",
  },
];

const config: NextConfig = {
  poweredByHeader: false,
  async headers() {
    return [{ source: "/:path*", headers: securityHeaders }];
  },
};

export default config;

A strict script-src 'self' will break inline scripts. Real Next.js apps typically need a nonce-based policy generated in middleware; check the current Next.js CSP guide in the docs for the supported approach rather than copying the static string above blindly.

Nginx defaults worth setting:

server_tokens off;
add_header X-Content-Type-Options "nosniff" always;
add_header X-Frame-Options "DENY" always;
client_max_body_size 5m;

Test and automate

SurfaceToolWhat it catches
Dockerfile, Kubernetes, TerraformTrivy config, Checkov, kube-linter, kubescapePrivileged pods, root users, public buckets
Cloud accountProwler, ScoutSuite, cloud-native posture toolsOpen storage, over-broad IAM
Running siteZAP baseline scan, Mozilla Observatory, securityheaders checksMissing headers, cookies without flags
FrameworkFramework doctor commands, startup assertionsDebug mode in production

Add a startup assertion so misconfiguration fails loudly:

// lib/env.ts
import { z } from "zod";

const Env = z.object({
  NODE_ENV: z.enum(["development", "test", "production"]),
  DATABASE_URL: z.string().url(),
  SESSION_SECRET: z.string().min(32),
});

export const env = Env.parse(process.env);

if (env.NODE_ENV === "production" && process.env.DEBUG) {
  throw new Error("DEBUG must not be set in production");
}

Common mistakes

  • Using the latest tag so what runs is not what was scanned.
  • Leaving /admin, /metrics, /actuator, /_debug reachable from the internet.
  • Same credentials across staging and production.
  • Cloud storage ACLs "temporarily" public.
  • CORS wildcard on authenticated APIs.
  • Cookies without HttpOnly, Secure, SameSite.

Checklist

  • One hardened baseline (base image, pod security settings, headers) applied via templates.
  • Config is validated at startup; production refuses debug flags.
  • IaC scanners run in CI and block high severity.
  • Admin and metrics endpoints are behind a network boundary or authentication.
  • Error pages show a request ID, never a stack trace.
  • Cookies use HttpOnly; Secure; SameSite=Lax (or Strict) unless there is a documented reason.

A03: Software Supply Chain Failures

What it is

New at third place in 2025, and the category that grew out of "Vulnerable and Outdated Components". It now covers the whole chain: dependencies with known vulnerabilities, but also malicious packages (typosquatting, dependency confusion, compromised maintainer accounts), tampered build pipelines, unpinned CI actions, poisoned base images, and unreviewed install scripts. Your application is mostly other people's code; every npm install is a trust decision.

Vulnerable patterns

# GitHub Actions: VULNERABLE
on: pull_request_target
jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          ref: ${{ github.event.pull_request.head.sha }}   # runs untrusted code with secrets
      - uses: some-org/some-action@main                    # mutable ref
      - run: npm install && npm test
# VULNERABLE: unpinned, runs as root, curl | sh
FROM node:latest
RUN curl -fsSL https://example.com/install.sh | sh
COPY . .
RUN npm install

The fix

# GitHub Actions: hardened
name: ci
on:
  pull_request:
permissions:
  contents: read
jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4   # pin to a full commit SHA in real use; verify the current SHA
        with:
          persist-credentials: false
      - uses: actions/setup-node@v4
        with:
          node-version-file: .nvmrc
          cache: npm
      - run: npm ci --ignore-scripts
      - run: npm audit --audit-level=high
      - run: npm test

Practices that matter more than any single tool:

  1. Commit lockfiles and install with npm ci, pip install --require-hashes -r requirements.txt (or uv sync --frozen), composer install from composer.lock.
  2. Pin CI actions to a commit SHA and let Dependabot or Renovate update them. Tags can be moved.
  3. Default permissions: contents: read on workflows; grant more per job.
  4. Delay adoption of brand-new releases where your tooling supports it (Renovate minimumReleaseAge, npm and pnpm release-age settings; verify availability in your tool's current docs). Most malicious package releases are caught within days.
  5. Disable install scripts by default (--ignore-scripts) and allow-list the few packages that need them.
  6. Use private registries or scoped names to avoid dependency confusion; reserve your internal package names on public registries.
  7. Generate and store an SBOM (CycloneDX or SPDX) for every release.
  8. Sign and attest builds with Sigstore cosign and provenance (SLSA); verify at deploy time.
# Python: reproducible, hash-checked installs
pip install --require-hashes -r requirements.txt

# PHP: audit and install exactly the locked set
composer audit
composer install --no-dev --prefer-dist --no-interaction

# Node: audit and install exactly the locked set
npm audit --omit=dev --audit-level=high
npm ci --ignore-scripts

Automation

NeedTools
Known vulnerable dependenciesnpm audit, pip-audit, composer audit, OSV-Scanner, Trivy fs, Dependabot alerts, Snyk
Automated updatesDependabot, Renovate (grouping and age rules)
Malicious package signalsSocket, OpenSSF Scorecard, package provenance checks; verify what your registry supports
Image and OS packagesTrivy image, Grype
SBOMSyft, CycloneDX generators, Trivy --format cyclonedx
Signing and provenancecosign, GitHub artifact attestations, SLSA generators
Workflow lintingzizmor, actionlint, StepSecurity Harden-Runner

Reachability and triage

A dependency alert is not automatically an exploitable vulnerability. Triage with three questions: is the vulnerable function reachable from your code, is the component exposed to untrusted input, and is a fixed version available? Record decisions in a VEX statement or an ignore file with an expiry date, never a permanent silent ignore.

Common mistakes

  • Ignoring transitive dependencies because "we never installed that".
  • Auto-merging all dependency updates without tests.
  • Not rebuilding images when the base image gets patched.
  • Using npm install in CI, which can rewrite the lockfile.
  • Mutable tags for Actions and base images.
  • Long-lived publish tokens in CI instead of trusted publishing via OIDC (see the secrets management guide).

Checklist

  • Lockfiles committed; CI uses frozen installs.
  • Dependabot or Renovate enabled with grouped PRs and passing tests required.
  • CI actions pinned by SHA; workflow permissions minimal.
  • SCA scan fails the build on high or critical issues with a fix available.
  • Images scanned and rebuilt on a schedule.
  • SBOM generated; releases signed.

A04: Cryptographic Failures

What it is

Sensitive data exposed because cryptography is missing, weak, or misused: plaintext transport, passwords hashed with MD5 or unsalted SHA-256, hard-coded keys, ECB mode, predictable tokens from Math.random, disabled TLS verification, secrets in source control. The 2025 text stresses the root cause (weak or absent cryptography), not just the symptom (data exposure).

Vulnerable code

// TypeScript: VULNERABLE
import crypto from "node:crypto";

const hash = crypto.createHash("md5").update(password).digest("hex"); // fast, unsalted
const resetToken = Math.random().toString(36).slice(2);                // predictable
const key = "super-secret-key-1234";                                   // hard-coded
# Python: VULNERABLE
import hashlib, requests
pw_hash = hashlib.sha1(password.encode()).hexdigest()
requests.get("https://internal.example.com/data", verify=False)  # disables TLS validation
// PHP: VULNERABLE
$hash = md5($password);
$token = rand();                                 // not cryptographically secure
openssl_encrypt($data, 'AES-128-ECB', $key);     // ECB leaks patterns

The fix

// TypeScript: Node crypto, argon2 and CSPRNG
import crypto from "node:crypto";
import argon2 from "argon2"; // verify current package and parameters in its docs

export async function hashPassword(password: string) {
  return argon2.hash(password, { type: argon2.argon2id }); // tune memory/time cost; see OWASP guidance
}

export function newToken(bytes = 32) {
  return crypto.randomBytes(bytes).toString("base64url");
}

// Authenticated encryption (AES-256-GCM) with a unique 12-byte nonce per message
export function encrypt(plaintext: Buffer, key: Buffer) {
  const iv = crypto.randomBytes(12);
  const cipher = crypto.createCipheriv("aes-256-gcm", key, iv);
  const ct = Buffer.concat([cipher.update(plaintext), cipher.final()]);
  return Buffer.concat([iv, cipher.getAuthTag(), ct]);
}

export function decrypt(blob: Buffer, key: Buffer) {
  const iv = blob.subarray(0, 12);
  const tag = blob.subarray(12, 28);
  const ct = blob.subarray(28);
  const decipher = crypto.createDecipheriv("aes-256-gcm", key, iv);
  decipher.setAuthTag(tag);
  return Buffer.concat([decipher.update(ct), decipher.final()]);
}
# Python: argon2-cffi and secrets
from argon2 import PasswordHasher
import secrets

ph = PasswordHasher()           # argon2id defaults; review parameters against current OWASP guidance
hashed = ph.hash(password)
ph.verify(hashed, candidate)    # raises on mismatch
token = secrets.token_urlsafe(32)
// PHP: built-in password API and random_bytes
$hash = password_hash($password, PASSWORD_ARGON2ID);
if (password_verify($candidate, $hash)) { /* ok */ }
if (password_needs_rehash($hash, PASSWORD_ARGON2ID)) { /* store new hash */ }
$token = bin2hex(random_bytes(32));

Rules of thumb

NeedUseAvoid
Password storageArgon2id, scrypt or bcrypt via a libraryMD5, SHA-1, plain SHA-256, home-grown schemes
Random tokensOS CSPRNG (crypto.randomBytes, secrets, random_bytes)Math.random, rand, random.random
Symmetric encryptionAES-GCM or ChaCha20-Poly1305 through a high-level library (libsodium, Tink)ECB, CBC without MAC, DIY
Integrity of messagesHMAC-SHA-256 with constant-time comparePlain hash, == comparison
TransportTLS 1.2+ (prefer 1.3), HSTSPlain HTTP, disabled verification
Key storageKMS, secret manager, HSMSource code, .env committed, image layers
Data at restDisk or database encryption plus field-level encryption for the most sensitive fieldsBelieving disk encryption protects against a SQL injection

Do not invent your own cryptographic protocol. When you need field-level encryption, use envelope encryption: a data key per record or per tenant, encrypted by a key held in a KMS, with key IDs stored next to the ciphertext so you can rotate.

Test and automate

  • Semgrep rules for weak hashes, verify=False, Math.random in security contexts, ECB mode. The public Semgrep registry has maintained rule packs for these.
  • CodeQL queries for weak cryptographic algorithms and hard-coded credentials.
  • gitleaks or TruffleHog for committed secrets, with push protection on the host.
  • testssl.sh or SSL Labs for TLS configuration; ZAP passive rules for missing HSTS.
  • Unit tests that assert hashes are argon2 or bcrypt format and that tokens have enough entropy (length and uniqueness).

Common mistakes

  • Encrypting without authenticating.
  • Reusing a nonce with the same key.
  • Comparing secrets with ===; use crypto.timingSafeEqual, hmac.compare_digest, hash_equals.
  • Logging tokens, then wondering why they leak.
  • Storing API keys in plaintext in the database instead of a hash (show once, store a hash, like passwords but fast hash is acceptable for high-entropy keys).
  • Rolling your own JWT validation (see the OAuth post).

Checklist

  • Passwords use a modern adaptive hash; rehash on login when parameters change.
  • All tokens come from a CSPRNG with at least 128 bits of entropy.
  • TLS everywhere, HSTS on, certificate verification never disabled.
  • Encryption keys live in a KMS or secret manager, with a rotation plan.
  • No secrets in source control or container layers.
  • Sensitive fields classified; those that need it are encrypted at the field level.

A05: Injection

What it is

Untrusted data is interpreted as code or commands. SQL injection is the classic, but the class includes NoSQL operator injection, OS command injection, LDAP, template injection, header injection, XPath, expression language injection, and in the AI era, prompt injection. Cross-site scripting (XSS) is also counted here: untrusted data interpreted as HTML or script by a browser. The cure is the same everywhere: keep data and code on separate channels (parameters, escaping by context, safe APIs) and validate input as a second line of defense.

SQL injection

// TypeScript: VULNERABLE
const rows = await db.query(
  `SELECT id, email FROM users WHERE email = '${email}' ORDER BY ${sort}`,
);
// TypeScript: FIXED. Values are parameters; identifiers come from an allow-list.
const SORTABLE = { created: "created_at", email: "email" } as const;
type SortKey = keyof typeof SORTABLE;

export async function listUsers(email: string, sort: string) {
  const column = SORTABLE[(sort as SortKey)] ?? "created_at";
  return db.query(
    `SELECT id, email FROM users WHERE email = $1 ORDER BY ${column}`,
    [email],
  );
}

Parameters cannot be used for identifiers like column names or ORDER BY direction, which is why an allow-list map is the safe pattern. With Prisma, the tagged template form $queryRaw parameterizes, but $queryRawUnsafe does not:

// Prisma
await prisma.$queryRaw`SELECT * FROM "User" WHERE email = ${email}`; // parameterized
await prisma.$queryRawUnsafe(`SELECT * FROM "User" WHERE email = '${email}'`); // VULNERABLE
# Python: VULNERABLE vs FIXED
cursor.execute(f"SELECT * FROM users WHERE email = '{email}'")           # vulnerable
cursor.execute("SELECT * FROM users WHERE email = %s", (email,))          # fixed (driver placeholders)

# SQLAlchemy
from sqlalchemy import text
session.execute(text("SELECT * FROM users WHERE email = :email"), {"email": email})
// PHP: VULNERABLE vs FIXED
$res = $pdo->query("SELECT * FROM users WHERE email = '$email'");        // vulnerable

$stmt = $pdo->prepare('SELECT * FROM users WHERE email = :email');        // fixed
$stmt->execute(['email' => $email]);

// Laravel: whereRaw with bindings
User::whereRaw('lower(email) = ?', [strtolower($email)])->first();
// VULNERABLE: User::whereRaw("email = '$email'")

Make sure PDO is configured with PDO::ATTR_EMULATE_PREPARES => false and PDO::ERRMODE_EXCEPTION for real server-side prepared statements.

NoSQL injection

// VULNERABLE: body is { "email": "a@b.c", "password": { "$ne": null } }
const user = await users.findOne({ email: req.body.email, password: req.body.password });

An attacker sends an object instead of a string, and MongoDB interprets the operator. Fix by validating types before the query, and never storing plaintext passwords in the first place:

import { z } from "zod";

const Login = z.object({ email: z.string().email(), password: z.string().min(1).max(256) });

export async function login(body: unknown) {
  const { email, password } = Login.parse(body); // rejects objects
  const user = await users.findOne({ email });
  if (!user || !(await argon2.verify(user.passwordHash, password))) return null;
  return user;
}

OS command injection

# VULNERABLE
import os
os.system(f"convert {filename} -resize 200x200 out.png")   # filename = "a.png; curl evil|sh"
# FIXED: no shell, argument list, validated input
import subprocess, re
from pathlib import Path

SAFE_NAME = re.compile(r"^[A-Za-z0-9._-]{1,100}$")

def make_thumbnail(filename: str):
    if not SAFE_NAME.fullmatch(filename):
        raise ValueError("bad filename")
    src = (UPLOAD_DIR / filename).resolve()
    if UPLOAD_DIR.resolve() not in src.parents:
        raise ValueError("path escape")
    subprocess.run(
        ["convert", str(src), "-resize", "200x200", "out.png"],
        check=True, timeout=10, shell=False,
    )
// Node: VULNERABLE vs FIXED
import { exec, execFile } from "node:child_process";
exec(`ping -c 1 ${host}`);                       // vulnerable: shell parses host
execFile("ping", ["-c", "1", host], { timeout: 5000 }, cb); // fixed: no shell
// PHP
system("convert " . $file);                                  // vulnerable
system("convert " . escapeshellarg($file));                  // acceptable minimum
// Better: avoid the shell; use a library (Imagick, Intervention Image).

The best fix is to not call a shell at all. If you must, pass arguments as an array, validate against an allow-list, and run with the least privilege.

Template injection and XSS

// VULNERABLE: React escape hatch with user content
<div dangerouslySetInnerHTML={{ __html: comment.body }} />
// FIXED: sanitize with an allow-list sanitizer, or render as text
import DOMPurify from "isomorphic-dompurify";

export function Comment({ html }: { html: string }) {
  const clean = DOMPurify.sanitize(html, { ALLOWED_TAGS: ["b", "i", "em", "strong", "a", "p"] });
  return <div dangerouslySetInnerHTML={{ __html: clean }} />;
}
// Even better: store Markdown, render with a safe renderer, and add a CSP.
# Server-side template injection (Jinja2): VULNERABLE
from jinja2 import Template
Template("Hello " + user_input).render()      # user_input = "{{ ... }}" runs template code

# FIXED: never build templates from user input; pass data as variables
from jinja2 import Environment, select_autoescape
env = Environment(autoescape=select_autoescape())
env.from_string("Hello {{ name }}").render(name=user_input)
# For user-authored templates use jinja2.sandbox.SandboxedEnvironment and treat as high risk.
// PHP: VULNERABLE vs FIXED
echo "<p>Hello " . $_GET['name'] . "</p>";                              // XSS
echo "<p>Hello " . htmlspecialchars($_GET['name'], ENT_QUOTES, 'UTF-8') . "</p>";
// Blade: {{ $name }} escapes; {!! $name !!} does not. Grep for {!! in reviews.

Injection into prompts

LLM prompt injection is the same bug class: data (a web page, an email, a document) is interpreted as instructions. The defenses differ because there is no parameterized-query equivalent for natural language. See Prompt Injection Defense for AI Agents for privilege separation, tool allow-lists, and confirmation gates.

Testing and automation

TechniqueToolNotes
Static analysisSemgrep (p/owasp-top-ten, language packs), CodeQL query suitesTaint tracking from request to sink
Dependency-levelFramework-specific linters, bandit for Python, PHPStan/Psalm with taint analysis for PHPPsalm taint analysis finds XSS and SQLi flows
DynamicZAP active scan against staging only, sqlmap against your own test environmentNever against systems you do not own
UnitTable-driven tests with hostile strings: quotes, semicolons, ../, operators as objectsAssert behavior, not just "no crash"
FuzzingSchemathesis for OpenAPI, Jazzer.js, AtherisFinds crashes and validation gaps

A reusable hostile-input table for unit tests:

export const HOSTILE = [
  "' OR '1'='1",
  "\"; DROP TABLE users; --",
  "../../etc/passwd",
  "<script>alert(1)</script>",
  "${7*7}",
  "{{7*7}}",
  "a; id",
  "\u0000",
  "A".repeat(100_000),
];

Common mistakes

  • Validating on the client only.
  • Escaping once and reusing the string in a different context (HTML escaping does not protect a SQL query or a URL).
  • Using a blocklist ("remove <script>").
  • Trusting ORM safety while using the raw escape hatch.
  • Building ORDER BY, table names or LIMIT from input.
  • Using eval, new Function, pickle.loads or unserialize on user data (also an A08 issue).

Checklist

  • Parameterized queries or ORM everywhere; raw-query APIs reviewed.
  • Identifiers from allow-lists.
  • Input validated by schema (type, length, format) at the boundary.
  • No shell invocation with user data; if unavoidable, array arguments and allow-lists.
  • Output encoding by context; no unsanitized dangerouslySetInnerHTML or {!! !!}.
  • CSP deployed as defense in depth.
  • Taint-aware SAST runs on every PR.

A06: Insecure Design

What it is

Flaws that no amount of perfect implementation fixes, because the design lacks a control. Examples: a password reset flow that reveals whether an email is registered and has no rate limit; a coupon endpoint that can be redeemed a thousand times in parallel; a "free trial" that can be restarted forever; a multi-tenant system where tenant isolation depends on every developer remembering a WHERE clause; an export feature with no size limit that can take the service down.

Vulnerable design: race condition on a limited resource

// VULNERABLE: check-then-act, two concurrent requests both pass
const coupon = await db.coupon.findUnique({ where: { code } });
if (coupon.usedCount >= coupon.maxUses) throw new Error("exhausted");
await db.coupon.update({ where: { code }, data: { usedCount: { increment: 1 } } });
await applyDiscount(order);

The fix: make the invariant atomic

// FIXED: single conditional update; the database enforces the limit
const updated = await db.$executeRaw`
  UPDATE coupon
  SET used_count = used_count + 1
  WHERE code = ${code} AND used_count < max_uses
`;
if (updated === 0) throw new Error("exhausted");
await applyDiscount(order);

For idempotency on payments and webhooks, use an idempotency key with a unique constraint:

CREATE TABLE processed_events (
  event_id   text PRIMARY KEY,
  processed_at timestamptz NOT NULL DEFAULT now()
);
-- INSERT ... ON CONFLICT DO NOTHING; process only if a row was inserted.

Rate limiting and abuse controls

// Simple fixed-window limiter with Redis (use a maintained library in production)
import { redis } from "@/lib/redis";

export async function limit(key: string, max: number, windowSec: number) {
  const k = `rl:${key}:${Math.floor(Date.now() / 1000 / windowSec)}`;
  const n = await redis.incr(k);
  if (n === 1) await redis.expire(k, windowSec);
  return n <= max;
}

// usage
if (!(await limit(`login:${ip}:${email}`, 5, 60))) {
  return new Response("Too many attempts", { status: 429 });
}
# FastAPI with slowapi (verify current API in docs)
from slowapi import Limiter
from slowapi.util import get_remote_address

limiter = Limiter(key_func=get_remote_address)

@app.post("/auth/forgot-password")
@limiter.limit("3/minute")
async def forgot(request: Request, body: ForgotIn):
    # Always return the same response whether or not the email exists
    await maybe_send_reset(body.email)
    return {"status": "If the account exists, an email was sent."}

Secure design practices

PracticeWhat you do
Threat modelingOne hour per feature; see the STRIDE workflow guide
Abuse casesWrite "as an attacker I want to..." stories next to user stories
Security requirementsASVS levels as acceptance criteria; pick Level 1 as baseline, Level 2 for sensitive data
Secure defaultsNew features ship with the safest setting; relax with explicit flags
Resource limitsMax upload size, page size, request rate, query cost, background job concurrency
Business logic testsTests for double-spend, replay, out-of-order steps, negative quantities
IsolationTenant boundaries enforced in more than one layer

Business logic tests catch what scanners cannot:

def test_cannot_apply_negative_quantity(client, cart):
    r = client.post(f"/cart/{cart.id}/items", json={"sku": "X", "quantity": -5})
    assert r.status_code == 422

def test_coupon_parallel_redemption(client, coupon_one_use):
    import concurrent.futures as cf
    with cf.ThreadPoolExecutor(10) as ex:
        results = list(ex.map(lambda _: client.post("/coupons/redeem", json={"code": coupon_one_use.code}), range(10)))
    assert sum(r.status_code == 200 for r in results) == 1

Common mistakes

  • Treating security as a late-stage scan.
  • Rate limiting by IP only (shared NATs) or by account only (lockout abuse); combine them.
  • Security questions as recovery.
  • Returning different errors for "user not found" and "wrong password".
  • Letting the client calculate prices.
  • Unbounded pagination, uploads, and regex input.

Checklist

  • Each new feature has a short threat model or at least a list of abuse cases.
  • Critical invariants (balances, quotas, uniqueness) are enforced by the database.
  • Rate limits on login, signup, password reset, OTP, search, export, and expensive endpoints.
  • Idempotency for payments and webhooks.
  • Limits on sizes, counts and time for every user-controlled resource.

A07: Authentication Failures

What it is

Weak or broken proof of identity: credential stuffing allowed by no rate limiting or breached-password checks, weak password policies, session IDs in URLs, sessions that never expire or are not rotated at login, missing MFA on sensitive actions, insecure recovery flows, JWT validation mistakes. For the protocol level (Authorization Code with PKCE, token validation, refresh rotation) read the OAuth 2.1 and OIDC pitfalls post; this section is the application-level view.

Vulnerable code

// VULNERABLE session handling
res.cookie("session", user.id);                  // guessable, unsigned, no flags
// login does not regenerate session ID => session fixation
// JWT verified with a decoded payload but no signature check
const payload = JSON.parse(Buffer.from(token.split(".")[1], "base64").toString());
// VULNERABLE: timing and enumeration
if ($user === null) { return 'No such user'; }
if ($user->password !== md5($input)) { return 'Wrong password'; }

The fix

// Session cookie done right (framework session libraries do this for you)
cookies().set("__Host-session", sessionId, {
  httpOnly: true,
  secure: true,
  sameSite: "lax",
  path: "/",
  maxAge: 60 * 60 * 8,
});

The __Host- prefix requires Secure, Path=/, and no Domain, which prevents subdomain cookie injection.

# FastAPI login: generic error, rate limit, rotate session, argon2 verify
@app.post("/login")
@limiter.limit("10/minute")
async def login(body: LoginIn, response: Response):
    user = await get_user_by_email(body.email)
    # Verify against a dummy hash when the user does not exist to equalize timing
    hashed = user.password_hash if user else DUMMY_HASH
    ok = ph.verify_safe(hashed, body.password)  # wrapper returning bool, not raising
    if not user or not ok:
        raise HTTPException(401, "Invalid email or password")
    session_id = await create_session(user.id)  # new ID on every login
    response.set_cookie("__Host-session", session_id, httponly=True, secure=True, samesite="lax", max_age=28800)
    return {"ok": True}
// Laravel: use the framework guards, rate limit, regenerate
public function store(LoginRequest $request)
{
    $request->ensureIsNotRateLimited(); // Breeze/Fortify throttle
    if (! Auth::attempt($request->only('email', 'password'), $request->boolean('remember'))) {
        RateLimiter::hit($request->throttleKey());
        throw ValidationException::withMessages(['email' => __('auth.failed')]);
    }
    $request->session()->regenerate();
    return redirect()->intended('/dashboard');
}

Authentication design table

ConcernRecommendation
Primary loginUse a maintained library or an identity provider (Auth.js, Lucia-style patterns, Laravel Fortify/Breeze, Django allauth, Keycloak, a managed IdP) instead of writing your own
MFAOffer passkeys (WebAuthn) and TOTP; require MFA for admin and for sensitive actions (step-up)
PasswordsMinimum length over complexity rules, check against breached-password lists (k-anonymity APIs such as Have I Been Pwned), no forced periodic rotation without evidence of compromise (consistent with NIST SP 800-63B; verify the current revision)
SessionsServer-side sessions or short-lived JWTs with refresh rotation; absolute and idle timeouts; revoke on password change
RecoverySingle-use, short-lived, hashed reset tokens; same response whether or not the account exists; notify the user on change
Brute forcePer-account and per-IP throttling with exponential backoff; CAPTCHA only as a fallback
Service accountsWorkload identity, not shared passwords (see the secrets management article)

Test and automate

  • Tests: login rate limit triggers; session ID changes after login; logout invalidates server-side; reset token is single use; expired token rejected; the same response for known and unknown emails.
  • ZAP authentication tests and session management scripts; Burp sequencer for token randomness during pentests.
  • Semgrep rules for JWT alg: none, jwt.decode without verify (PyJWT verify_signature: False), and jsonwebtoken decode used where verify is intended.

Common mistakes

  • Using JWTs as sessions without a revocation story.
  • Storing tokens in localStorage for browser apps where an XSS bug exposes them.
  • Accepting the alg from the token header.
  • Allowing password reset links to be reused or never expire.
  • Email change without re-authentication.
  • Treating "remember me" as a permanent bearer token with no rotation.

Checklist

  • Login, reset, signup and OTP endpoints are rate limited.
  • Session ID rotates on login and privilege change; cookie flags set.
  • MFA available; required for privileged roles.
  • Generic error messages and equalized timing.
  • Reset and verification tokens are random, hashed at rest, single use, short lived.
  • Sensitive actions require recent authentication.

A08: Software or Data Integrity Failures

What it is

Code or data is trusted without verifying integrity. This is the sibling of A03: A03 is about the components and pipeline you consume; A08 is about the runtime assumption that data, updates or serialized objects are what they claim to be. Examples: insecure deserialization, auto-update without signature verification, loading scripts from a CDN without Subresource Integrity, trusting unsigned webhooks, CI artifacts that can be replaced between build and deploy, and cookies or hidden fields that carry unsigned state.

Vulnerable code

# Python: VULNERABLE, pickle executes code on load
import pickle
data = pickle.loads(request.get_data())        # arbitrary code execution if attacker controls bytes
// PHP: VULNERABLE
$obj = unserialize($_COOKIE['prefs']);          // object injection / gadget chains
// Node: VULNERABLE webhook
app.post("/webhooks/payments", express.json(), (req, res) => {
  // no signature check: anyone can POST "payment succeeded"
  markOrderPaid(req.body.orderId);
  res.sendStatus(200);
});
<!-- VULNERABLE: third-party script with no integrity check -->
<script src="https://cdn.example.com/lib.js"></script>

The fix

// Verify webhook signatures over the RAW body, with constant-time comparison
import crypto from "node:crypto";

export function verifyWebhook(rawBody: Buffer, header: string, secret: string) {
  const expected = crypto.createHmac("sha256", secret).update(rawBody).digest("hex");
  const a = Buffer.from(expected);
  const b = Buffer.from(header);
  return a.length === b.length && crypto.timingSafeEqual(a, b);
}

app.post("/webhooks/payments", express.raw({ type: "application/json" }), (req, res) => {
  const sig = req.header("x-signature") ?? "";
  if (!verifyWebhook(req.body, sig, process.env.WEBHOOK_SECRET!)) return res.sendStatus(401);
  // Also check a timestamp to prevent replays, and dedupe by event ID
  res.sendStatus(200);
});

Most payment providers ship their own verification helper with replay protection; prefer it over hand-rolled code.

# Python: use data-only formats
import json
from pydantic import BaseModel

class Prefs(BaseModel):
    theme: str = "light"
    locale: str = "en"

prefs = Prefs.model_validate_json(request.get_data())   # data, not code
// PHP: JSON, or restrict classes
$prefs = json_decode($_COOKIE['prefs'] ?? '{}', true, 8, JSON_THROW_ON_ERROR);
// If unserialize is unavoidable: unserialize($s, ['allowed_classes' => false]);
// Better: signed cookies (Laravel encrypts and signs cookies by default).
<script
  src="https://cdn.example.com/lib.js"
  integrity="sha384-REPLACE_WITH_HASH"
  crossorigin="anonymous"></script>

Better still, self-host and pin the asset.

Integrity checklist for the delivery pipeline

Developer commit (signed)
      |
      v
CI build (hermetic, pinned deps, minimal permissions)
      |
      +--> SBOM + provenance attestation
      +--> image signed with cosign (keyless OIDC)
      v
Registry (immutable tags, digest references)
      |
      v
Deploy gate: verify signature + attestation + vulnerability policy
      |
      v
Cluster admission policy (Kyverno / Sigstore policy controller)

Automation

  • Semgrep and CodeQL rules for pickle.loads, yaml.load without SafeLoader, unserialize, ObjectInputStream, eval.
  • Bandit for Python; PHPStan or Psalm rules for unserialize.
  • cosign verify in the deploy job; admission controllers to refuse unsigned images.
  • SRI hash generation in the build (Next.js supports an experimental.sri option in some versions; verify against current docs).

Common mistakes

  • Verifying a webhook signature after parsing JSON (the re-serialized body differs).
  • No timestamp or replay protection.
  • Treating a signed cookie as encrypted, or vice versa.
  • Trusting client-side state for pricing or role.
  • Downloading and executing binaries in CI without checking checksums.

Checklist

  • No native deserialization of untrusted data.
  • All inbound webhooks verified with signature, timestamp and event ID dedupe.
  • Third-party scripts avoided or protected with SRI and CSP.
  • Build artifacts signed; deploys verify signatures.
  • Auto-update mechanisms verify signatures.

A09: Security Logging and Alerting Failures

What it is

You cannot respond to what you cannot see. The 2025 name adds "alerting" on purpose: logs nobody monitors are just disk usage. Failures include no logging of authentication and access control events, logs without context, logs that contain secrets or personal data, logs that can be tampered with, and no alerts for obvious signals such as 500 failed logins in a minute or an admin created at 3 a.m.

Vulnerable code

# VULNERABLE
logger.info(f"Login attempt {email} password={password}")      # secret in logs
try:
    process_payment(order)
except Exception:
    pass                                                        # swallowed; no signal at all

The fix: structured, contextual, minimal security events

// lib/audit.ts: one function for security-relevant events
import pino from "pino";

const log = pino({
  redact: {
    paths: ["req.headers.authorization", "req.headers.cookie", "*.password", "*.token", "*.secret"],
    censor: "[REDACTED]",
  },
});

type AuditEvent = {
  event:
    | "auth.login.success"
    | "auth.login.failure"
    | "auth.mfa.failure"
    | "authz.denied"
    | "user.role.changed"
    | "data.export";
  actorId?: string;
  targetId?: string;
  ip?: string;
  requestId: string;
  outcome: "success" | "failure";
  reason?: string;
};

export function audit(e: AuditEvent) {
  log.info({ type: "security", ...e }, e.event);
}
# Python: structlog with a processor that drops sensitive keys
import structlog

SENSITIVE = {"password", "token", "authorization", "secret", "card_number"}

def scrub(_, __, event_dict):
    return {k: ("[REDACTED]" if k.lower() in SENSITIVE else v) for k, v in event_dict.items()}

structlog.configure(processors=[scrub, structlog.processors.add_log_level, structlog.processors.JSONRenderer()])
log = structlog.get_logger()
log.warning("authz.denied", actor_id=user.id, resource="invoice", resource_id=inv_id, request_id=rid)

What to log and what to alert on

EventLogAlert
Login success and failureYes, with user ID, IP, user agent hash, request IDSpike in failures per account or per IP; success after many failures
Authorization denialsYesMany denials by one actor (probing for IDOR)
Privilege or role changesYesAlways
Password reset, MFA changes, email changeYesNew device plus reset
Data exports, bulk readsYesVolume anomalies
Admin actionsYes, immutable storeAlways for production admins
Input validation failuresAggregateSudden increases
Secrets, tokens, full card numbers, passwordsNeverAlert if detected in logs
Personal dataMinimize, mask, set retentionNot applicable

Pipeline

App (structured JSON logs, request ID)
   -> collector (OpenTelemetry Collector / Vector / Fluent Bit)
      -> central store (Loki, Elasticsearch/OpenSearch, CloudWatch, Datadog)
         -> detection rules / alerts -> on-call (PagerDuty, Opsgenie, Slack)
   -> append-only archive (object storage with retention lock) for audit

Use the same request or trace ID in application logs and traces so an alert leads directly to a story. The OpenTelemetry for LLM apps post shows a good instrumentation baseline.

Tests

it("logs a security event on authorization denial", async () => {
  const spy = vi.spyOn(auditModule, "audit");
  await asUser(b).get(`/api/invoices/${invoiceId}`);
  expect(spy).toHaveBeenCalledWith(expect.objectContaining({ event: "authz.denied", actorId: b.id }));
});

it("does not log passwords", async () => {
  const lines = await captureLogs(() => api.post("/login").send({ email: "x@y.z", password: "hunter2hunter2" }));
  expect(lines.join("\n")).not.toContain("hunter2hunter2");
});

Common mistakes

  • Logging the full request body.
  • Not logging failures, only successes.
  • Logs on the same server with the same privileges as the app (an attacker deletes them).
  • Alert fatigue: 200 rules, nobody reads them. Start with five that page a human.
  • No retention policy: either forever (privacy risk) or 24 hours (no forensics).
  • Log injection: newline characters in user input forging entries; JSON logging fixes most of it.

Checklist

  • Security events defined and logged in a single module.
  • Redaction configured and tested.
  • Logs shipped off-host; tamper-resistant archive.
  • Alerts exist for the top five abuse signals and have an owner and a runbook.
  • Retention matches policy and privacy law.

A10: Mishandling of Exceptional Conditions

What it is

New in 2025. The application behaves insecurely when something goes wrong: errors leak internals, exceptions are swallowed and the code proceeds as if a check passed (fail open), resource exhaustion is not handled, partial transactions leave inconsistent state, and unexpected input crashes the process. The key rule: fail closed. If the authorization service times out, deny.

Vulnerable code

// VULNERABLE: fails open
async function canAccess(userId: string, resourceId: string) {
  try {
    return await policyService.check(userId, resourceId);
  } catch {
    return true; // "don't block users if the policy service is down"
  }
}
# VULNERABLE: leaks internals, leaves state half-done
@app.post("/transfer")
def transfer(body: TransferIn):
    try:
        debit(body.from_account, body.amount)
        credit(body.to_account, body.amount)   # if this fails, money vanished
    except Exception as e:
        return {"error": str(e), "trace": traceback.format_exc()}
// VULNERABLE: error suppression hides failures of a security check
$ok = @verify_signature($payload, $sig);
if ($ok != false) { process($payload); }       // loose comparison; null passes differently than expected

The fix

async function canAccess(userId: string, resourceId: string): Promise<boolean> {
  try {
    return (await policyService.check(userId, resourceId, { timeoutMs: 300 })) === true;
  } catch (err) {
    audit({ event: "authz.denied", actorId: userId, requestId: currentRequestId(), outcome: "failure", reason: "policy_unavailable" });
    return false; // fail closed
  }
}
@app.post("/transfer")
def transfer(body: TransferIn):
    with db.begin():                       # one transaction: both or neither
        debit(body.from_account, body.amount)
        credit(body.to_account, body.amount)
    return {"status": "ok"}

@app.exception_handler(Exception)
async def unhandled(request: Request, exc: Exception):
    rid = request.state.request_id
    logger.exception("unhandled", request_id=rid)             # details go to logs
    return JSONResponse({"error": "internal_error", "request_id": rid}, status_code=500)
// Laravel: report internally, render a generic response
// app/Exceptions/Handler.php or bootstrap/app.php
->withExceptions(function (Exceptions $exceptions) {
    $exceptions->render(function (Throwable $e, Request $request) {
        if ($request->expectsJson() && ! config('app.debug')) {
            return response()->json(['error' => 'internal_error', 'request_id' => $request->header('X-Request-Id')], 500);
        }
    });
})

Patterns

SituationSecure behavior
Dependency (auth, policy, rate limiter) unavailableFail closed for authorization; for rate limiting decide explicitly, and document
Unexpected exceptionGeneric message to client, detail to logs, same HTTP status semantics
Multi-step operationTransaction, saga with compensation, or idempotent retries
Resource exhaustionTimeouts, size limits, bounded queues, circuit breakers, backpressure
Parsing untrusted inputStrict schema; reject, do not coerce silently
Global handlersLast line of defense: log, redact, respond, never crash the process on one request

Tests

  • Fault-injection tests: make the policy service throw and assert access is denied.
  • Chaos and resilience tests in staging: kill the database mid-request and verify consistent state.
  • Fuzzing: malformed JSON, huge payloads, unexpected types.
  • Check that 500 responses contain no stack trace, SQL, or file paths.
it("denies when the policy service fails", async () => {
  vi.spyOn(policyService, "check").mockRejectedValue(new Error("timeout"));
  const res = await asUser(a).get(`/api/invoices/${invoiceId}`);
  expect(res.status).toBe(403);
});

Common mistakes

  • Empty catch blocks and except: pass.
  • Returning raw exception messages to the client.
  • Retrying non-idempotent operations blindly.
  • Missing timeouts on outbound calls, so a slow dependency exhausts the thread pool.
  • Using == loose comparisons where a failure value (null, false, 0) is equal to a pass value.

Checklist

  • Central error handler returns generic errors with a request ID.
  • Security checks fail closed.
  • Multi-step operations are atomic or compensated.
  • Timeouts and limits on all I/O.
  • Fault-injection tests for security-critical dependencies.

SSRF: Server-Side Request Forgery (now part of A01)

What it is

The server fetches a URL supplied by the user: webhook targets, avatar by URL, link previews, PDF generation, import from URL. An attacker points it at internal services or the cloud metadata endpoint (for example the link-local address used by cloud instance metadata) and the server returns the response or acts on it. In cloud environments SSRF has been the entry point of well-known breaches because metadata services hand out credentials.

Vulnerable code

// VULNERABLE
app.get("/preview", async (req, res) => {
  const r = await fetch(String(req.query.url));   // anything: internal hosts, file:, metadata
  res.send(await r.text());
});

The fix: layered

  1. Allow-list schemes (https only) and, if possible, allow-list destination hostnames.
  2. Resolve DNS yourself, check that every resolved IP is public (not loopback, private, link-local, multicast, unique-local), then connect to that IP, so DNS rebinding cannot swap it afterwards.
  3. Disable redirects, or re-validate at each hop.
  4. Set timeouts and response size limits.
  5. Run fetchers in a network segment with no access to internal services, and enforce IMDSv2 and hop limits on cloud metadata.
import dns from "node:dns/promises";
import net from "node:net";
import { Agent } from "undici";

const BLOCKED_V4 = [
  /^10\./, /^127\./, /^169\.254\./, /^172\.(1[6-9]|2\d|3[01])\./, /^192\.168\./, /^0\./, /^100\.(6[4-9]|[7-9]\d|1[01]\d|12[0-7])\./,
];

function isPublicIp(ip: string) {
  if (net.isIPv4(ip)) return !BLOCKED_V4.some((r) => r.test(ip));
  const v6 = ip.toLowerCase();
  return !(v6 === "::1" || v6.startsWith("fc") || v6.startsWith("fd") || v6.startsWith("fe80") || v6.startsWith("::ffff:"));
}

export async function safeFetch(rawUrl: string) {
  const url = new URL(rawUrl);
  if (url.protocol !== "https:") throw new Error("https only");
  const addrs = await dns.lookup(url.hostname, { all: true });
  if (addrs.length === 0 || !addrs.every((a) => isPublicIp(a.address))) throw new Error("blocked address");

  // Pin the connection to the vetted address to defeat DNS rebinding
  const pinned = addrs[0].address;
  const dispatcher = new Agent({
    connect: { lookup: (_h, _o, cb) => cb(null, pinned, net.isIPv4(pinned) ? 4 : 6) },
  });

  const res = await fetch(url, {
    dispatcher, redirect: "manual", signal: AbortSignal.timeout(5000),
  } as RequestInit);
  if (res.status >= 300 && res.status < 400) throw new Error("redirects not followed");
  return res;
}

This sketch is a starting point. IP-range matching by regex misses encodings and IPv6 mapping edge cases; prefer a maintained library that parses addresses into ranges (for example ipaddr.js) and verify the undici dispatcher options against current docs. In Python, use ipaddress (ip.is_global) and pin the resolved IP the same way.

import ipaddress, socket
from urllib.parse import urlparse
import httpx

def assert_public(host: str) -> str:
    infos = socket.getaddrinfo(host, 443, proto=socket.IPPROTO_TCP)
    ips = {i[4][0] for i in infos}
    for ip in ips:
        if not ipaddress.ip_address(ip).is_global:
            raise ValueError("blocked address")
    return next(iter(ips))

def safe_get(url: str):
    u = urlparse(url)
    if u.scheme != "https" or not u.hostname:
        raise ValueError("https only")
    assert_public(u.hostname)
    # follow_redirects=False; if you must follow, re-run assert_public on each hop
    return httpx.get(url, follow_redirects=False, timeout=5.0)

Note this Python version re-resolves at connect time, which leaves a small DNS rebinding window; for high-risk fetchers use an egress proxy such as Smokescreen that enforces the policy outside application code.

Cloud metadata hardening

PlatformControl
AWS EC2Require IMDSv2 and set the hop limit to 1 so containers cannot reach it by default
GCPMetadata concealment or workload identity on GKE; restrict the metadata server for pods
AzureManaged identity scoping; network policy blocking the metadata address for untrusted pods
KubernetesNetworkPolicy default deny egress; allow only needed destinations

Test and automate

  • Semgrep and CodeQL have SSRF queries (request forgery) for common HTTP clients.
  • Unit tests with a table of blocked inputs: http://127.0.0.1, http://[::1], http://169.254.169.254, decimal and hex IP forms, hostnames resolving to private IPs, redirect to an internal address.
  • DAST: ZAP out-of-band checks against staging; internal-only canary hosts that alert if contacted.

Checklist

  • Features that fetch user-supplied URLs are listed and justified.
  • Allow-list or egress proxy in front of every fetcher.
  • IMDSv2 enforced; pods and containers cannot reach the metadata service unless needed.
  • Redirects disabled or re-validated; response size and time capped.

Secure code review checklist

Use this at the pull request level. It is short enough to memorize and maps to the categories above.

#QuestionCategory
1Does every new endpoint have an explicit authorization check, and is it scoped by owner or tenant in the query?A01
2Can a client set fields it should not (role, ownerId, price, status)?A01, A06
3Is every database call parameterized and every identifier from an allow-list?A05
4Is any user input passed to a shell, template engine, eval, deserializer, or file path?A05, A08
5Is untrusted data rendered as HTML without sanitization?A05
6Does the code fetch a user-supplied URL?A01 (SSRF)
7Are secrets, keys or tokens in the diff, config, tests or logs?A04, A09
8Is crypto using vetted libraries and modern algorithms; are random values from a CSPRNG?A04
9Are new dependencies necessary, maintained, pinned, and scanned?A03
10Does a workflow or Dockerfile change add permissions, mutable tags, or a download piped into a shell?A02, A03
11What happens on error, timeout, or partial failure? Does it fail closed?A10
12Is there a limit on size, rate, count and time for new user-controlled resources?A06
13Are security-relevant events logged without leaking sensitive data?A09
14Are webhooks, updates and serialized data verified for integrity?A08
15Is there a test, including a negative one, for each security property added?all

For AI-assisted review, give the agent the table plus the diff and ask it to cite file and line for each finding, state confidence, and propose a patch without applying it. Treat the output as a lead to confirm, not as a verdict. Agent-written code needs the same review as human-written code, and often more, because it tends to produce plausible-looking raw queries and permissive defaults.

What to grep for in a legacy codebase

# Quick, noisy, useful: find the sinks that deserve a human look
rg -n "dangerouslySetInnerHTML|innerHTML\s*=|\{!!" src resources
rg -n "\\\$queryRawUnsafe|executeRawUnsafe|whereRaw\(|DB::raw\(|\.raw\(" src app
rg -n "child_process|exec\(|os\.system|subprocess.*shell=True|shell_exec|passthru" .
rg -n "pickle\.loads|yaml\.load\(|unserialize\(|eval\(|new Function" .
rg -n "verify\s*=\s*False|rejectUnauthorized:\s*false|CURLOPT_SSL_VERIFYPEER" .
rg -n "md5\(|sha1\(|Math\.random|\brand\(" .
rg -n "AKIA[0-9A-Z]{16}|BEGIN (RSA|EC|OPENSSH) PRIVATE KEY" .

Lab: find and fix five bugs in 60 minutes

A guided exercise you can run with a team. Use a deliberately vulnerable training app on localhost (OWASP Juice Shop, DVWA or a small app you write) and never point scanners at systems you do not own.

  1. Set up (10 min). Run the target locally (for example with Docker, bound to 127.0.0.1). Create two users.
  2. IDOR (10 min). As user A, create a resource. As user B, request it by ID. Write the failing test, scope the query, watch the test pass.
  3. Injection (10 min). Find a query built by concatenation using Semgrep with the p/owasp-top-ten ruleset. Replace with a parameterized form. Add a hostile-input test.
  4. Dependency (10 min). Run the ecosystem audit and Trivy filesystem scan. Upgrade one vulnerable dependency; confirm tests pass.
  5. Misconfiguration (10 min). Run a ZAP baseline scan against your local app, review missing headers and cookie flags, fix two.
  6. Logging (10 min). Add an audit event for authorization denial; trigger it; confirm the log line has the actor and request ID and no secrets.

Deliverable: one pull request per fix with a test and a one-sentence description of the weakness. This turns abstract categories into muscle memory.

A CI security pipeline you can copy

A layered pipeline runs cheap, fast checks on every pull request and slower ones on a schedule or on merge. The goal is signal over volume: each scanner should block only on findings you will actually fix.

PR opened
  |
  +-- secrets: gitleaks (diff)             ~10s    BLOCK on any finding
  +-- SAST: Semgrep (OWASP + custom)       ~1-3m   BLOCK on high confidence
  +-- SCA: OSV-Scanner / npm audit         ~1m     BLOCK on critical/high with fix
  +-- IaC/Dockerfile: Trivy config         ~1m     BLOCK on high
  +-- unit + authz tests                   ~3-8m   BLOCK
  |
merge to main
  |
  +-- CodeQL (deep SAST)                   ~5-20m  report to Security tab
  +-- build image -> Trivy image scan      ~2m     BLOCK on critical with fix
  +-- SBOM + cosign sign + attest          ~1m
  +-- deploy to staging
  +-- DAST: ZAP baseline/full (auth)       ~5-30m  report; block on high
  |
nightly
  +-- full dependency + image rescan, secret history scan, ZAP full scan
# .github/workflows/security.yml
name: security
on:
  pull_request:
  push:
    branches: [main]
  schedule:
    - cron: "17 3 * * *"

permissions:
  contents: read

jobs:
  secrets:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with: { fetch-depth: 0, persist-credentials: false }
      - name: gitleaks
        run: |
          docker run --rm -v "$PWD:/repo" zricethezav/gitleaks:latest \
            detect --source /repo --redact --exit-code 1

  semgrep:
    runs-on: ubuntu-latest
    container: semgrep/semgrep:latest
    steps:
      - uses: actions/checkout@v4
        with: { persist-credentials: false }
      - run: semgrep scan --config p/owasp-top-ten --config p/typescript --config .semgrep/ --error --severity ERROR

  sca-and-config:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with: { persist-credentials: false }
      - name: Trivy filesystem and config scan
        uses: aquasecurity/trivy-action@master   # pin to a release SHA in real use
        with:
          scan-type: fs
          scanners: vuln,secret,misconfig
          severity: HIGH,CRITICAL
          ignore-unfixed: true
          exit-code: "1"

  codeql:
    if: github.event_name != 'schedule' || true
    runs-on: ubuntu-latest
    permissions:
      contents: read
      security-events: write
    steps:
      - uses: actions/checkout@v4
        with: { persist-credentials: false }
      - uses: github/codeql-action/init@v3
        with:
          languages: javascript-typescript,python
          queries: security-extended
      - uses: github/codeql-action/analyze@v3

  zap-baseline:
    if: github.ref == 'refs/heads/main'
    runs-on: ubuntu-latest
    steps:
      - name: ZAP baseline scan against staging
        uses: zaproxy/action-baseline@v0.14.0      # verify the current release tag
        with:
          target: https://staging.example.com
          rules_file_name: .zap/rules.tsv
          cmd_options: "-a"

Notes you should not skip:

  • Action versions above are illustrative. Pin each to a verified commit SHA, and confirm current inputs in each action's README, because these actions change.
  • Run Semgrep with your own rules directory (.semgrep/) for project-specific data-access patterns; community rules cannot know your repository layer.
  • Only point ZAP at environments you own, and use a dedicated test tenant and credentials.
  • Start in report-only mode for a week, triage the baseline, add suppressions with expiry dates, then turn on blocking.
  • Keep findings in one place (GitHub code scanning, DefectDojo, or similar) with owners and SLAs, for example critical within 7 days and high within 30. Pick numbers your team will actually meet.

A minimal custom Semgrep rule that enforces scoped queries in a Prisma codebase:

# .semgrep/prisma-unscoped-find.yml
rules:
  - id: prisma-find-by-id-without-tenant
    languages: [typescript]
    severity: ERROR
    message: "Prisma lookup by id without organizationId scope. Add the ownership predicate."
    patterns:
      - pattern: $DB.$MODEL.findUnique({ where: { id: $ID } })
      - pattern-not-inside: |
          // semgrep-allow-unscoped
          ...
    metadata:
      category: security
      owasp: "A01:2025 Broken Access Control"

Test rules against both a vulnerable and a fixed example in the repository (semgrep --test) so the rule does not rot.

Tool selection guide

ToolTypeBest atWeakness
SemgrepSAST, pattern-basedFast, easy custom rules, good PR feedbackCross-file taint analysis depends on edition and configuration
CodeQLSAST, semanticDeep dataflow queries, free for public reposSlower; requires build for some languages
TrivySCA, container, IaC, secretsOne tool for many surfacesNoisy without severity and fix filters
OSV-Scanner / audit commandsSCAAccurate advisory dataReports reachability poorly
gitleaks / TruffleHogSecretsPre-commit, CI, historyNeeds allow-lists for test fixtures
ZAPDASTFree, scriptable, CI baselineAuthenticated scans take setup
Burp SuiteDAST, manualPentesting depthCommercial for the full feature set
Checkov / kube-linterIaCTerraform and Kubernetes policyRules need tuning
cosign / SLSAIntegritySigning and provenanceRequires deploy-time verification to matter

Where this usually goes wrong

  1. Treating the Top 10 as a compliance checkbox. The list is awareness material. For a testable standard use OWASP ASVS, and for mobile or APIs use the MASVS and the API Security Top 10.
  2. Scanning without owning findings. A backlog of 3,000 unreviewed alerts is worse than 30 triaged ones.
  3. Fixing symptoms: escaping one query instead of banning string-built SQL with a lint rule.
  4. Trusting the framework blindly. Frameworks are safe by default until you use the escape hatch, so search for the escape hatches.
  5. Security work that stops at the web layer. The queue consumer, cron job and admin script have the same bugs.
  6. No negative tests. If your tests only prove that valid users succeed, you have tested nothing about security.
  7. Over-blocking CI. A pipeline that fails randomly gets bypassed.
  8. Believing AI-generated code is reviewed. It isn't unless you review it. See the injection and design sections for what to look at first.

When to hold back

A prototype with no real data and a one-week lifespan needs only the basics: HTTPS, parameterized queries, no secrets in git, a real auth library. Skip custom Semgrep rules and SBOM signing, but set a delete date for the prototype, because prototypes have a way of becoming production. A tiny team shouldn't adopt every scanner at once. Start with secret scanning, dependency updates, and one SAST tool in report mode, and add DAST and signing once the first three are quiet.

Don't block merges on low-confidence findings, because it trains developers to disable the tool. Don't write custom crypto, auth or sanitizers because a library "feels heavy"; use the library. An annual pentest report does not substitute for tests in CI: pentesters are best used for business logic and architecture, after the automated baseline is clean. And match rigor to data sensitivity and exposure, so no heavy ASVS Level 3 controls on a low-risk internal tool.

A maturity roadmap

StageFocusTypical outcome
0. Baseline (week 1)HTTPS, secrets out of git, dependency updates on, framework auth, parameterized queriesEliminates the cheapest attacks
1. Guardrails (month 1)Semgrep, SCA and gitleaks in CI; security headers; error handler; audit logRegressions are caught on PRs
2. Tests (month 2-3)Cross-user authorization matrix, hostile-input tables, fail-closed testsAccess control bugs caught before review
3. Design (quarter)Threat models for new features, abuse cases, rate limits, ASVS L1 requirementsFewer design flaws
4. Supply chain (quarter)SHA-pinned actions, SBOMs, signed images, deploy-time verificationResistance to pipeline and package attacks
5. Detection (ongoing)Alerts with owners, incident runbooks, tabletop exercisesFaster detection and response

If you only have a week

Add a cross-user authorization test to your highest-value endpoints, turn on dependency updates and secret scanning with push protection, and write down the abuse cases for the next feature before you build it.

Questions that come up

Is the 2025 list final, and should I still use 2021 mappings? The 2025 edition is published on top10.owasp.org and is the current one. Many scanners and audit templates still tag findings with 2021 identifiers, so keep a mapping table. The big changes: Software Supply Chain Failures (A03) and Mishandling of Exceptional Conditions (A10) are new, SSRF is merged into Broken Access Control, and Security Misconfiguration rose to second.

Is the Top 10 enough for compliance such as PCI DSS or SOC 2? No. It is an awareness document. Auditors expect a secure development lifecycle, evidence of testing, and change management. Use ASVS as the verification standard and keep scan reports and fixes as evidence.

SAST or DAST first? SAST. It runs on every pull request, points to a line of code, and needs no deployed environment. Add DAST once you have a staging environment and a test user.

Do ORMs make SQL injection impossible? They make it much less likely when you use the query builder. Every ORM has raw-query escape hatches, and sorting and filtering by dynamic column names is a common path back to injection.

How do I handle false positives? Suppress at the narrowest scope with a reason and an expiry date. Track suppression counts; if a rule produces mostly false positives, tune or remove it rather than teaching the team to ignore alerts.

How do I apply this to AI-generated code? Same review checklist, plus extra attention to raw queries, missing authorization, hard-coded keys and permissive CORS. Agents optimize for code that works, not code that resists abuse. Put the checklist in the agent's instructions and run the CI pipeline on every agent-authored pull request. For agent runtime risks see the prompt injection article.

Sources and docs