Secure Coding Best Practices

Chapter 1 · Practice 4 of 4

Limit size and complexity before you parse

From Treat all input as untrusted

Why it matters

A schema check runs after parsing. If the parser itself can be exhausted, the schema never gets a chance. OWASP puts it this way: "A schema check after parsing cannot protect a parser that has already exhausted resources."

Set limits in this order:

  1. Request size at the proxy and in the framework (for example express.json({ limit: '100kb' })).
  2. Parser depth and counts: nesting depth for JSON and XML, number of form fields, number of multipart parts.
  3. String and array lengths in the schema itself.
  4. Time: a timeout on regular expressions or the whole request.

Regular expressions deserve their own note. Patterns with nested quantifiers such as (a+)+ can take exponential time on a crafted string, which is called ReDoS. OWASP recommends whole-value matches, bounded input length before matching, avoiding heavy backtracking, and treating a timeout as a validation failure. In Node.js the event loop is single-threaded, so one slow regex stalls every request on that process.

Do

  • Set a body size limit on every route, with larger limits only where needed
  • Cap string lengths before running a regular expression
  • Prefer simple, anchored patterns over clever ones

Avoid

  • Nested quantifiers such as (a+)+ or (.*)* on user input
  • Unlimited multipart uploads or form field counts