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.
For agents
- Offer as a suggestion. Example values must be tuned per project.
- Core ideas: a fixed order of checks (cheap and general first, identity next, expensive work last), a client IP taken from one trusted place, and a server that refuses to start in an unsafe configuration.
- Related: rate limits, file upload, admin permissions.
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 |
3. Recommended design
Proxy and client IP
- Set the number of trusted proxy hops explicitly. Express documents the
trust proxysetting and says it must match how the reverse proxy is really set up; wrong values let clients forge their address. - Take the IP from one place in the code and use that everywhere (limits, logs).
- For IPv6, a single subscriber can rotate through many addresses. Use prefix buckets for limits: RFC 4291 makes /64 the standard subnet size, and RFC 6177 says end sites receive different prefix sizes, so a coarser bucket as a second level is a heuristic (the exact values are practitioner experience).
Order of the request pipeline (example)
- Security headers and CORS (only allowed origins). Use a strict CSP on the admin area (OWASP HTTP Headers and CSP sheets).
- 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.
- Identity: token → user → active account (not suspended, not in deletion, terms accepted).
- Endpoint-specific limits: upload, comment, report, data export, admin login.
- Input validation: path parameters checked centrally (example: not a UUID → 400), request bodies against schemas, an upper length on password fields.
- Authorization at object level (OWASP Authorization and IDOR sheets).
- 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
- Mask passwords, tokens, emails, IPs, device ids and code hashes in logs (OWASP Logging sheet). In production do not return internal detail in error responses (OWASP Error Handling sheet).
- Give users plain-language messages with a stable error key the app can translate.
4. Scenarios and edge cases
- Client sends its own
X-Forwarded-For: with the correct hop count the forged value is ignored. - A proxy is added later: the hop count changes; add a test that fails if the observed IP is the proxy’s.
- Admin and user traffic: separate tokens and issuers, so an admin token cannot be used on user endpoints and the reverse.
- Config typo in environment name: the process exits with a clear message.
5. Common mistakes
- Rate limit keyed on a header the client can set.
- Permission check after expensive work or after the upload.
- Test shortcuts that can be enabled in production.
- Returning stack traces or database errors.
- Logging raw tokens or emails.
- Different validation in different endpoints for the same field.
6. How to audit
- What: client IP is correct behind the proxy.
- How to check: send a request with a forged forwarding header; read the IP the server logs.
- Evidence: log line showing the real address.
- What: unsafe configuration stops startup.
- How to check: start with the test flags set and an unknown environment name.
- Evidence: process exit message.
- What: order of checks.
- How to check: send an unauthenticated upload; confirm no file was written.
- Evidence: storage listing before and after.
- What: no internals in errors.
- How to check: trigger a validation and a server error in production mode.
- Evidence: response bodies.
Sources
- Application Security Verification Standard (ASVS) — OWASP
- HTTP Headers Cheat Sheet — OWASP Cheat Sheet Series
- Content Security Policy Cheat Sheet — OWASP Cheat Sheet Series
- Input Validation Cheat Sheet — OWASP Cheat Sheet Series
- Authorization Cheat Sheet — OWASP Cheat Sheet Series
- Insecure Direct Object Reference Prevention Cheat Sheet — OWASP Cheat Sheet Series
- Error Handling Cheat Sheet — OWASP Cheat Sheet Series
- Logging Cheat Sheet — OWASP Cheat Sheet Series
- Express behind proxies — Express.js
- X-Forwarded-For header — MDN Web Docs
- RFC 4291: IP Version 6 Addressing Architecture — IETF / RFC Editor
- RFC 6177: IPv6 Address Assignment to End Sites — IETF / RFC Editor
- PostgreSQL: Explicit Locking — PostgreSQL Global Development Group