Auth Bypass in Hapi with Api Keys
Auth Bypass in Hapi with Api Keys — how this specific combination creates or exposes the vulnerability
Hapi is a rich framework that encourages explicit route configuration. When API keys are used for authentication, developers often implement validation as a route-level extension or a custom handler without enforcing the same controls across all routes. An Auth Bypass occurs when some routes or route combinations are missing key validation, or when key validation is implemented inconsistently, allowing an unauthenticated request to reach a privileged endpoint. This commonly happens in Hapi when routes defined without an auth strategy inherit configuration from a server-level policy, or when a key check is performed in a hook that does not apply to every route.
In a black-box scan, middleBrick tests unauthenticated endpoints and verifies whether a valid API key is required for access. One typical pattern in Hapi is to register an auth strategy using an API key scheme and then apply it selectively. If a developer forgets to apply the strategy to a route that manages users or configuration, the route becomes exposed. Even when a strategy is defined, subtle issues can arise, such as using a validation function that returns true for empty or missing keys, or failing to validate the key against a trusted source on every request.
Another risk specific to API keys in Hapi is key leakage via logs, error messages, or referrer headers when requests are proxied. Because API keys are long-lived secrets compared to session cookies, any bypass increases the window for abuse. Attack patterns include probing common administrative paths that are accidentally left unprotected, or exploiting route inheritance to call an authenticated handler without supplying credentials. middleBrick’s checks include verifying that unauthenticated scanning yields a security risk score impact for routes that should require an API key, and mapping findings to the Authentication and BOLA/IDOR categories in the OWASP API Top 10.
Using an OpenAPI specification can reduce these risks by ensuring that security requirements are declared consistently across paths and that $ref resolution applies securitySchemes to all relevant operations. However, the spec must be aligned with runtime behavior; a mismatch between declared requirements and actual enforcement is a common root cause of Auth Bypass. The scan compares the spec’s declared security schemes with the runtime behavior of each endpoint, highlighting discrepancies that could allow unauthorized access in Hapi services.
Api Keys-Specific Remediation in Hapi — concrete code fixes
To remediate Auth Bypass in Hapi when using API keys, enforce validation on every route that requires protection and avoid relying on inheritance or default behaviors. Define a dedicated auth strategy and apply it explicitly to each route or to a route group. Below is a minimal, secure example of an API key validation function and its registration in Hapi.
const Hapi = require('@hapi/hapi');
const validApiKeys = new Set(['abc123secretkey', 'def456anotherkey']);
const validateApiKey = (request, h) => {
const key = request.headers['x-api-key'];
if (!key) {
return { isValid: false };
}
const isValid = validApiKeys.has(key);
return { isValid, credentials: { key } };
};
const init = async () => {
const server = Hapi.server({ port: 4000, host: 'localhost' });
server.auth.strategy('apiKeyStrategy', 'custom', {
validate: validateApiKey,
});
server.auth.default('apiKeyStrategy');
server.route([
{
method: 'GET',
path: '/public',
handler: (request, h) => 'Public data, no key required',
},
{
method: 'GET',
path: '/secure',
options: {
auth: 'apiKeyStrategy',
handler: (request, h) => `Hello, key ${request.auth.credentials.key}`,
},
},
]);
await server.start();
console.log('Server running on %s', server.info.uri);
};
process.on('unhandledRejection', (err) => {
console.error(err);
process.exit(1);
});
init();
In this example, the strategy is explicitly set to custom validation and applied as the default for all routes. The public route opts out by not specifying an auth configuration, while the secure route requires a valid key in the x-api-key header. This explicit approach prevents accidental inheritance issues and ensures that only intended endpoints are protected.
For broader enforcement, apply the auth configuration to a route group or use a server extension to validate keys before reaching handlers. Avoid returning true when the key is missing or malformed, and ensure that key comparisons are performed using a constant-time operation if stored server-side. Regularly rotate keys and avoid logging them; if keys must be logged for debugging, mask or truncate them to reduce exposure.
middleBrick’s scans include checks for authentication coverage across endpoints and can surface routes that lack required API key validation. By aligning your Hapi configuration with the declared security scheme in an OpenAPI spec and running continuous scans, you can detect deviations before they lead to unauthorized access.
Related CWEs: authentication
| CWE ID | Name | Severity |
|---|---|---|
| CWE-287 | Improper Authentication | CRITICAL |
| CWE-306 | Missing Authentication for Critical Function | CRITICAL |
| CWE-307 | Brute Force | HIGH |
| CWE-308 | Single-Factor Authentication | MEDIUM |
| CWE-309 | Use of Password System for Primary Authentication | MEDIUM |
| CWE-347 | Improper Verification of Cryptographic Signature | HIGH |
| CWE-384 | Session Fixation | HIGH |
| CWE-521 | Weak Password Requirements | MEDIUM |
| CWE-613 | Insufficient Session Expiration | MEDIUM |
| CWE-640 | Weak Password Recovery | HIGH |