Pattern: Server security layers and request order

Note for AI agents: This page is baseline guidance, not an exact prescription. Read it, tell your owner what applies to their project, and get their approval before you change anything. Your project's own rules take precedence. If something important for this project is missing here, suggest it to your owner.

Search terms: middleware order, trust proxy, client ip, ipv6, security headers, cors, input validation, fail closed, race condition, error messages, logging masking

Last reviewed:

For agents

1. Problem

Server checks usually exist but in a wrong order or with gaps: a limit that keys on a spoofed address, a permission check after the file was already written, a test flag left on in production, an error message that exposes internals.

2. Options

Topic Option Upside Downside
Client IP Trust a fixed number of proxy hops (recommended) Matches the real chain Must be updated when the chain changes
Client IP Trust the first value in X-Forwarded-For Easy The client can write that value (MDN warns about improper use)
Config errors Fail closed (refuse to start) Unsafe config never serves traffic A deploy can fail loudly
Config errors Warn and continue Service stays up Unsafe state may run unnoticed

Proxy and client IP

Order of the request pipeline (example)

  1. Security headers and CORS (only allowed origins). Use a strict CSP on the admin area (OWASP HTTP Headers and CSP sheets).
  2. General rate limit: per account if the request is signed in, per address if not; counters in a store shared by all server copies so a restart does not reset them. Do not expose remaining quota in headers if that helps attackers.
  3. Identity: token → user → active account (not suspended, not in deletion, terms accepted).
  4. Endpoint-specific limits: upload, comment, report, data export, admin login.
  5. Input validation: path parameters checked centrally (example: not a UUID → 400), request bodies against schemas, an upper length on password fields.
  6. Authorization at object level (OWASP Authorization and IDOR sheets).
  7. The work itself.

For upload endpoints keep the order identity → permission → rate limit → receiving the file, so an unauthorized request never writes to disk.

Feature locks: one file lists locked features; a locked endpoint returns a distinct error code and the handler never runs.

Fail-closed start: refuse to start with an unknown environment name, with test escape variables set in production (disable rate limiting, skip 2FA), with missing storage settings, or without TLS to the database.

Race safety: conditional updates (“only if empty, else 409”); count-based limits via one counter row or a lock; a repeat-safe key on retried writes (see retries). PostgreSQL’s explicit locking is documented in its manual.

Logging and errors

4. Scenarios and edge cases

5. Common mistakes

6. How to audit

Sources