Chapter 1 · Practice 4 of 4
Limit size and complexity before you parse
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:
- Request size at the proxy and in the framework (for example
express.json({ limit: '100kb' })). - Parser depth and counts: nesting depth for JSON and XML, number of form fields, number of multipart parts.
- String and array lengths in the schema itself.
- 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