Auth Bypass in Hapi (Javascript)
Auth Bypass in Hapi with Javascript — how this specific combination creates or exposes the vulnerability
Auth bypass in a Hapi application built with JavaScript typically arises from missing or misconfigured authentication/authorization checks on routes, enabling an unauthenticated or low-privilege actor to reach protected endpoints. In a black-box scan, middleBrick tests the unauthenticated attack surface and checks whether routes intended for authenticated users are reachable without valid credentials. A common root cause is incomplete route-level protection: developers may guard some routes while leaving others—such as administrative or data-export endpoints—exposed. Another pattern is weak validation of tokens or session identifiers, where an attacker can guess or reuse identifiers to impersonate other users (BOLA/IDOR). JavaScript-specific risks include dynamic route registration or conditionally applied auth schemes where a route inadvertently inherits a less restrictive policy. Server-side misconfiguration, such as failing to validate the presence and scope of a JWT or session cookie, also contributes. middleBrick checks for these issues under Authentication, BOLA/IDOR, and Property Authorization, correlating findings with the OpenAPI spec to see whether defined security schemes are consistently applied. When a spec declares security requirements but runtime behavior does not enforce them, the discrepancy is flagged as a high-severity finding. The scanner also tests for BFLA/Privilege Escalation by attempting actions beyond a user’s role, and for unsafe consumption patterns where authorization decisions rely on client-supplied data without server-side verification.
Javascript-Specific Remediation in Hapi — concrete code fixes
Remediation centers on enforcing authentication on all protected routes and ensuring consistent policy application across the API surface. Use Hapi’s built-in auth mechanisms and scope checks, and validate server-side on every request. Below are two concrete examples: a vulnerable route and a hardened equivalent.
Vulnerable Hapi route (JavaScript)
// Insecure: no auth enforcement on this route
server.route({
method: 'GET',
path: '/api/users/{id}',
handler: function (request, h) {
const userId = request.params.id;
// No check that request.auth.credentials.userId matches userId or has proper scope
return db.users.get(userId);
}
});
Hardened Hapi route with proper auth and scope checks (JavaScript)
// Apply authentication strategy globally or per-route
server.route({
method: 'GET',
path: '/api/users/{id}',
options: {
auth: 'jwt', // registered strategy name
plugins: {
'hapi-auth-cookie': { redirectTo: false }
}
},
handler: function (request, h) {
const userId = request.params.id;
const authUserId = request.auth.credentials.userId;
const userScopes = request.auth.credentials.scopes || [];
// Server-side: ensure the requesting user owns the resource or has adequate scope
if (userId !== authUserId && !userScopes.includes('read:users')) {
throw Boom.unauthorized('Insufficient scope or mismatched user ID');
}
// Additional server-side validation: sanitize and validate userId format
if (!/^[0-9a-fA-F]{24}$/.test(userId)) {
throw Boom.badRequest('Invalid user ID');
}
return db.users.get(userId);
}
});
Key practices illustrated:
- Define and register a robust JWT validation strategy (e.g., using
@hapi/jwt) and reference it by name in route options. - Always validate and compare server-side identifiers; never rely on route parameters or client claims alone for access decisions.
- Use scope or role checks to enforce least privilege, and fail explicitly with appropriate HTTP errors (401/403).
- Apply consistent auth options across routes; avoid mixing authenticated and unauthenticated handlers for similar resources.
middleBrick’s checks align with these patterns under Authentication, Property Authorization, and BOLA/IDOR. By correlating spec-defined security schemes with runtime behavior, it highlights missing or inconsistent protections. For teams using continuous scanning, the middleBrick CLI (“middlebrick scan <url>”) can be integrated into scripts, while the GitHub Action adds API security checks to CI/CD pipelines and can fail builds if the risk score drops below a chosen threshold. The Dashboard allows tracking scores over time, and the Pro plan supports continuous monitoring and configurable scan schedules with alerts.
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 |