Fix Unrestricted Resource Consumption in Fastify
Fastify's speed is a double-edged sword. Without strict constraints, an attacker can weaponize large payloads or high-frequency requests to trigger a Denial of Service (DoS) via resource exhaustion. To mitigate CWE-400, we must implement global and route-level body limits, rate limiting, and aggressive timeout configurations.
The Vulnerable Pattern
const fastify = require('fastify')();// VULNERABLE: No body limit defined globally or per route. // An attacker can send a multi-gigabyte JSON payload to exhaust heap memory. fastify.post(‘/process-data’, async (request, reply) => { return { received: request.body }; });
fastify.listen({ port: 3000 });
The Secure Implementation
The fix involves a multi-layered defense: 1. Set 'bodyLimit' globally in the Fastify constructor to prevent massive payloads from crashing the process. 2. Implement 'connectionTimeout' to kill slow-client attacks (Slowloris). 3. Use '@fastify/rate-limit' to throttle abusive IPs. 4. Apply route-specific 'bodyLimit' overrides for sensitive endpoints to minimize the attack surface further. 5. Always use JSON schemas to ensure the payload structure is predictable, preventing CPU spikes caused by deep-nested object parsing.
const fastify = require('fastify')({ bodyLimit: 1048576, // Global limit: 1MB connectionTimeout: 5000, keepAliveTimeout: 5000, maxRequestsPerSocket: 100 });// Register rate limiting to prevent request flooding fastify.register(require(‘@fastify/rate-limit’), { max: 100, timeWindow: ‘1 minute’ });
// SECURE: Route-specific limit and schema validation fastify.post(‘/process-data’, { bodyLimit: 10240, // 10KB limit for this specific endpoint schema: { body: { type: ‘object’, required: [‘id’], properties: { id: { type: ‘string’ } } } } }, async (request, reply) => { return { status: ‘ok’ }; });
fastify.listen({ port: 3000 });
Your Fastify API
might be exposed to Unrestricted Resource Consumption
74% of Fastify apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.
Free Tier • No Credit Card • Instant Report
Verified by Ghost Labs Security Team
This content is continuously validated by our automated security engine and reviewed by our research team. Ghost Labs analyzes over 500+ vulnerability patterns across 40+ frameworks to provide up-to-date remediation strategies.