Fix Unrestricted Resource Consumption in Hapi
Unrestricted resource consumption in Hapi frameworks is a low-hanging fruit for DoS attacks. By default, Hapi is robust, but lazy route configurations allow attackers to exhaust server memory using massive payloads or starve the event loop with infinite timeouts. We're going to harden the payload constraints and implement load shedding to ensure the service stays up under fire.
The Vulnerable Pattern
const Hapi = require('@hapi/hapi');const init = async () => { const server = Hapi.server({ port: 3000 });
server.route({ method: 'POST', path: '/data', handler: (request, h) => { // VULNERABILITY: No maxBytes or timeout defined. // An attacker can send a multi-gigabyte JSON blob to crash the process. return { status: 'received' }; } }); await server.start();
}; init();
The Secure Implementation
The secure implementation applies defense-in-depth at the route and server levels. By setting 'maxBytes' in the payload options, we force Hapi to terminate the connection if the body exceeds 1MB, preventing RAM exhaustion. The 'timeout' prevents 'Slowloris' attacks that hold connections open. Finally, the 'load' configuration on the server object enables automatic load shedding; if the event loop delay or heap usage exceeds the defined thresholds, the server will return 503 Service Unavailable, protecting the underlying infrastructure from a total crash.
const Hapi = require('@hapi/hapi');const init = async () => { const server = Hapi.server({ port: 3000, load: { sampleInterval: 1000, // Monitor process load every 1s maxHeapUsedBytes: 1073741824, // 1GB heap limit before shedding maxEventLoopDelay: 5 // 5ms lag limit } });
server.route({ method: 'POST', path: '/data', options: { payload: { maxBytes: 1048576, // Strict 1MB limit timeout: 15000, // 15s max for payload transfer parse: true, allow: 'application/json' } }, handler: (request, h) => { return { status: 'securely_processed' }; } }); await server.start();
}; init();
Your Hapi API
might be exposed to Unrestricted Resource Consumption
74% of Hapi 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.