Auth Bypass in Hapi with Cockroachdb
Auth Bypass in Hapi with Cockroachdb — how this specific combination creates or exposes the vulnerability
An Auth Bypass in a Hapi application that uses CockroachDB can occur when session or token validation is implemented at the application layer but the database identity is not consistently enforced. Hapi does not enforce authentication by default; it relies on plugins or custom route pre-handlers. If a route is mistakenly registered without requiring a valid session or token, an unauthenticated request can reach a handler that queries CockroachDB using a connection or session variable that should have been scoped to an authenticated user.
In a typical setup, developers use a database connection pool to execute SQL against CockroachDB. If user identity is derived from a request header, cookie, or JWT that is not validated before constructing queries, an attacker can manipulate the identifier. For example, a route like /user/profile might read a user ID from a JWT claim or a cookie and directly interpolate it into a CockroachDB query such as SELECT * FROM users WHERE id = $1. If the route is accidentally exposed without an authentication check, the attacker can modify the ID to enumerate or modify other users’ data, effectively bypassing intended access controls.
Another vector involves misconfigured role-based access checks. Hapi route definitions may conditionally apply pre-auth logic based on URL patterns or middleware order. If a developer assumes CockroachDB-level permissions will block unauthorized access, but the database user attached to the pool has broader rights than intended, an unauthenticated or low-privilege request might execute privileged statements. This is an Auth Bypass in the application logic, not the database, but it becomes exploitable because the application trusts the caller instead of validating each request against an identity provider.
Consider an endpoint that uses a session cookie set after login. If the cookie is not validated on each request or if the server-side session store is not checked before querying CockroachDB, an attacker can reuse an old or forged cookie. Since Hapi does not automatically verify sessions, the route handler may proceed and run queries as that user. The database may return data because the SQL user has access, but the application failed to ensure the authenticated subject matches the intended resource owner.
Additionally, CORS misconfigurations combined with missing route-level auth can expose endpoints to cross-origin requests where credentials are included. If Hapi routes do not explicitly require authentication and rely on browser same-origin policies, an attacker’s site can make authenticated requests using the victim’s cookies. CockroachDB will serve data according to the connection’s permissions, but the application layer did not enforce the necessary guardrails, resulting in an Auth Bypass that appears to work correctly from a database perspective.
To detect this category with middleBrick, the LLM/AI Security checks include system prompt leakage detection and active prompt injection testing, but for API auth issues, the tool runs checks such as Authentication, BOLA/IDOR, and Property Authorization. These scans can identify endpoints that expose data without proper access controls, including scenarios where CockroachDB integration lacks per-request identity validation.
Cockroachdb-Specific Remediation in Hapi
Remediation focuses on ensuring every route that interacts with CockroachDB validates identity and enforces least privilege. Use Hapi authentication plugins, such as hapi-auth-jwt2, to verify tokens before handlers run. Define a pre-authentication strategy that decodes and validates the JWT against your identity provider and attaches a verified user context to the request.
In your route definitions, require authentication explicitly and scope data access to the authenticated subject. Avoid interpolating identifiers from untrusted sources directly into SQL strings; instead, always use parameterized queries. Below is a concrete example that ties Hapi authentication to CockroachDB queries using the @cockroachdb/client driver with parameterized statements.
const Hapi = require('@hapi/hapi');
const { Pool } = require('pg'); // CockroachDB wire protocol compatible
const Jwt = require('hapi-auth-jwt2');
const validate = async (decoded) => {
// Check token validity, e.g., verify against DB or cache
return { isValid: true, credentials: { id: decoded.sub } };
};
const init = async () => {
const server = Hapi.server({ port: 4000 });
await server.register([Jwt]);
server.auth.strategy('jwt', 'jwt', {
key: process.env.JWT_SECRET,
validate: validate,
verifyOptions: { algorithms: ['HS256'] }
});
const pool = new Pool({
connectionString: process.env.COCKROACHDB_URI,
ssl: {
rejectUnauthorized: true
}
});
server.route({
method: 'GET',
path: '/user/profile',
options: {
auth: 'jwt',
handler: async (request) => {
const userId = request.auth.credentials.id;
const { rows } = await pool.query(
'SELECT id, username, email FROM users WHERE id = $1',
[userId]
);
if (rows.length === 0) {
throw Boom.notFound('User not found');
}
return rows[0];
}
}
});
await server.start();
};
init().catch((err) => {
console.error(err);
});
In this example, the JWT is validated by hapi-auth-jwt2 before the handler executes, ensuring only authenticated requests proceed. The CockroachDB connection uses parameterized queries with $1 to safely bind the user ID from the verified token, preventing ID manipulation. The connection string should enforce SSL to protect credentials in transit, and the database user must have only the necessary permissions to read required tables.
For broader protection, implement a centralized policy layer that checks ownership before data access. If your API supports updating profile data, require the authenticated subject to match the target resource ID and use transactions where multiple statements are needed. Regularly rotate credentials, limit database privileges, and audit query logs in CockroachDB to detect anomalous access patterns.
middleBrick’s Web Dashboard and CLI tool can help verify that routes requiring authentication are correctly configured. By scanning your API endpoints, the tool highlights missing auth requirements and potential BOLA/IDOR issues related to database-backed resources. The GitHub Action can enforce a minimum security score in CI/CD, and the MCP Server allows you to validate configurations directly from development environments.
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 |