Skip to main content
This lesson covers API and infrastructure security for an Express.js application. Whether your API is public-facing, internal, or restricted to specific customers, apply security controls to protect endpoints and the application surface. Below are excerpts from an automated audit run that frame the issues we address: configuration gaps, exploitability notes, concise proofs-of-concept (PoCs), and minimal drop-in remediations. Audit interactive output (example)
The audit prompt used for the run asked for a focused API & infrastructure security review and to produce a structured finding report:
The audit run produced a structured report for an example Express login app and highlighted several missing controls (CORS configuration, rate limiting, security headers, request size limits, weak JWT secret handling, etc.). Search & audit snippets captured during the run:
A screenshot of a code editor (Visual Studio Code) displaying a Markdown "API & Infrastructure Security Audit Report" for an Express.js login app, showing an executive summary, risk score, and detailed findings (e.g., missing CORS configuration). The left sidebar shows project files and folders for the app.

Executive summary

  • Primary gaps found: missing or permissive CORS, no rate limiting, absent request size limits, missing HTTP security headers, weak JWT secret handling, and inconsistent error handling.
  • Immediate high-impact fixes: add per-route rate limiting on authentication endpoints, enable Helmet.js with sane defaults, set express.json({ limit: '100kb' }), and replace weak secrets.
  • Example overall risk: High (example score 8.5 / 10).
  • Always prefer least-privilege, short token TTLs, and defense-in-depth (WAF, gateway rate limiting, central logging).
This audit is focused on configuration and implementation. If a code artifact (file or function) is missing from the repository, mark the finding as “Unable to verify” and list the specific file(s) that would prove the configuration (e.g., app.js, server.js, routes/auth.js, config/jwt.js).

Common findings, PoCs, and minimal remediations

Note: Do not invent files or functions that aren’t present in the codebase. If the audit cannot verify something, mark it as “Unable to verify” and list the artifact that would prove the configuration.

1) CORS misconfiguration (Critical)

Problem: Using * for Access-Control-Allow-Origin in production, or no origin validation, allows cross-site pages to call your API and may enable credentialed requests from untrusted origins. PoC (malicious site calling your API)
Minimal remediation (strict allowlist and origin validation)
If CORS cannot be found in the codebase, mark as Unable to verify and point auditors to the server entry file (e.g., app.js, server.js) where app.use(cors(...)) should appear. Related reading:

2) Rate limiting (Critical)

Problem: Without rate limiting, attackers can brute-force auth endpoints or perform request floods. PoC (curl brute-force loop)
Minimal remediation (per-route limiter using express-rate-limit)
For scaled deployments, use a distributed store (e.g., Redis) and a compatible adapter like rate-limit-redis or implement gateway-level limits. Related reading:

3) Request size limits / Body parsing (High)

Problem: Unbounded request bodies allow memory exhaustion and DoS. PoC (send a very large JSON payload)
Minimal remediations
For file uploads, use multer with limits:
Validate payloads and enforce schema limits with Ajv or similar to constrain depth and keys:

4) HTTP security headers (Critical)

Problem: Missing headers (CSP, X-Frame-Options, X-Content-Type-Options, HSTS) increase attack surface for content injection, clickjacking, and protocol downgrade. Minimal remediation (Helmet with CSP override)
Confirm headers:
Helmet docs:

5) JWT secret and token management (High)

Problem: Hardcoded or guessable JWT secret allows token forging and privilege escalation. Example insecure .env
PoC (forge token if secret known)
Remediations:
  • Generate a strong secret: require('crypto').randomBytes(64).toString('hex').
  • Store secrets in environment variables or a secrets manager (Vault, AWS Secrets Manager, GCP Secret Manager).
  • Short-lived access tokens + refresh tokens with revocation list.
  • Rotate secrets and support token revocation where feasible.
If JWT usage is not verifiable, mark as Unable to verify and indicate files to inspect: token creation functions, auth middleware, and config files.

6) API versioning security (High)

Problem: Old API versions can harbor vulnerabilities. Recommendations:
  • Use versioned routes: /api/v1/, /api/v2/.
  • Return deprecation headers for old versions and 410 for removed endpoints.
  • Patch or disable old versions; maintain a documented deprecation policy.

7) Error handling and information disclosure (Medium)

Problem: Returning stack traces or full error objects in responses exposes internal implementation details. Minimal remediation (sanitized error handler)
Audit note: Search for console.log, console.error and middleware that exposes err.stack. Replace direct console output with structured logging to a secure sink (e.g., a log service).

Structured report expectations (per finding)

For each issue include:
  • Title
  • Severity (Critical/High/Medium/Low)
  • CWE (if applicable)
  • Evidence (file path, function name, line ranges)
  • Why it matters (concise)
  • Exploitability notes and safe PoC or reproduction steps
  • Remediation: precise code/config change with a minimal snippet
  • Defense-in-depth recommendations
  • Summary risk score (0–10)
  • Top 3–5 prioritized fixes
  • A checklist diff marking items from the “Check for” list as Pass / Fail / Not Applicable
Constraints: Be concrete and cite exact code locations and identifiers. Prefer minimal drop-in fixes. If evidence is missing, mark as Unable to verify and list the artifact that would prove the configuration.

Condensed example audit summary

Quick security checklist (high level) Risk assessment (example)
  • Critical: CORS, Rate Limiting, Security Headers
  • High: Request Limits, JWT Secret, Versioning
  • Medium: Error handling, HSTS enforcement missing
Priority remediation (recommended order)
  1. Replace weak or hardcoded JWT secrets and use secure secret storage.
  2. Add rate limiting on auth and other sensitive endpoints.
  3. Enable Helmet with secure defaults and set a CSP.
  4. Configure a strict CORS allowlist and credentials handling.
  5. Enforce request body and file upload limits and validate payloads.
Overall example risk score: 8.5 / 10 — High Risk
Immediate low-effort, high-impact fixes: add express-rate-limit to authentication routes, enable Helmet with sane defaults, and set express.json({ limit: '100kb' }). These reduce attack surface quickly.

Tests and verification examples

  • Verify HTTP security headers:
  • CORS check (browser-like request)
  • Rate-limit verification: repeat requests to an endpoint and confirm 429 responses when limits are exceeded.
  • JWT secret verification: search for process.env.JWT_SECRET or look for hardcoded strings used with jsonwebtoken.sign(...).

Production readiness checklist (operational recommendations)

  • Store secrets in a secrets manager or platform-provided environment variables.
  • Centralize logging and monitoring for rate-limit events and anomalies.
  • Deploy a WAF or API gateway for bot mitigation and distributed rate limiting.
  • Implement an API versioning and deprecation policy to avoid long-lived insecure endpoints.
  • Regularly audit third-party dependencies for vulnerabilities.

Thanks for reviewing. The audit artifacts and prompts used to generate these findings are available in the referenced repository if you want to replicate or extend these checks.

Watch Video