Token Leakage in Adonisjs with Cockroachdb
Token Leakage in Adonisjs with Cockroachdb — how this specific combination creates or exposes the vulnerability
Token leakage occurs when authentication tokens, session identifiers, or cryptographic keys are exposed in logs, error messages, URLs, or response bodies. The combination of AdonisJS and CockroachDB can inadvertently facilitate token leakage through misconfigured database interactions, ORM behavior, and logging practices.
AdonisJS relies on Lucid ORM, which abstracts SQL queries. When querying CockroachDB, if developer code binds sensitive token values as query parameters but also logs the full query or result set, tokens can appear in application logs or debugging output. For example, constructing a query with concatenated strings instead of parameterized bindings may expose tokens in query logs:
// Risky: token may appear in logs or query history
const user = await User.query().whereRaw(`email = '${email}' AND api_token = '${token}'`).first()
Error handling in AdonisJS can also contribute. Unhandled exceptions that include request payloads or database error details might surface tokens if developers inadvertently include sensitive fields in error messages returned to clients or written to logs. CockroachDB’s wire protocol and storage layer do not encrypt data in transit by default when TLS is not enforced; if AdonisJS connects without forcing SSL, tokens could be exposed in network traffic.
Another vector involves session management. If AdonisJS stores session data (including tokens) in a CockroachDB table without proper access controls, an attacker who gains read access to that table can exfiltrate valid session tokens. This often maps to the Broken Object Level Authorization (BOLA) or IDOR checks in middleBrick’s security scan: an unauthenticated or low-privilege actor might enumerate user IDs and retrieve session records containing tokens.
Middleware configuration is critical. Missing or misconfigured CORS settings in AdonisJS can allow cross-origin requests that expose tokens via the Authorization header in browser-based clients. Additionally, if AdonisJS generates JWTs and stores the signing key in environment variables that are inadvertently logged (e.g., via debug output), CockroachDB connection strings that reference those keys may amplify exposure.
middleBrick’s LLM/AI Security checks specifically test for system prompt leakage and output scanning that could expose tokens if an AI integration logs sensitive database responses. Its Runtime checks for BOLA/IDOR and Data Exposure align with detecting token leakage paths when scanning an API that uses AdonisJS with CockroachDB, providing prioritized findings and remediation guidance to address these vectors before tokens are exposed in production environments.
Cockroachdb-Specific Remediation in Adonisjs — concrete code fixes
Remediation focuses on secure query construction, enforced encryption, strict access controls, and safe error handling. Always use parameterized queries to prevent token leakage in logs and to defend against SQL injection.
1. Parameterized Queries with CockroachDB
Use AdonisJS Lucid ORM’s built-in parameter binding instead of raw string concatenation. This ensures tokens are not interpolated into query text that may be logged.
// Secure: parameterized binding
const user = await User.query()
.where('email', email)
.andWhere('api_token', token)
.first()
2. Enforce TLS for CockroachDB Connections
Configure the database client to require SSL/TLS. In database.ts, set ssl: true and provide the CA certificate when connecting to CockroachDB.
// config/database.ts
import { DbConnectionSource } from '@ioc:Adonis/Lucid/Database'
const connectionSource: DbConnectionSource = {
connection: 'cockroachdb',
connections: {
cockroachdb: {
client: 'cockroachdb',
connectionString: process.env.DATABASE_URL,
ssl: {
rejectUnauthorized: true,
ca: process.env.COCKRACKDB_CA_CERT_PATH
}
}
}
}
export default connectionSource
3. Restrict Session Storage Access
If using CockroachDB to store sessions, limit which database roles can read the session table. Define a dedicated database user for AdonisJS with only the necessary permissions and avoid granting broad SELECT on sensitive tables.
-- CockroachDB SQL example: least-privilege role
CREATE USER adonis_app WITH PASSWORD '${process.env.DB_PASSWORD}';
GRANT SELECT, INSERT, UPDATE ON TABLE user_sessions TO adonis_app;
4. Safe Error Handling
Ensure error handlers do not echo tokens or raw query details. Use AdonisJS’s exception handler to sanitize responses and logs.
// start/handlers.ts
import { ExceptionHandler } from '@ioc:Adonis/Core/ExceptionHandler'
export default class CustomExceptionHandler extends ExceptionHandler {
public handle(error: any, reporter: ExceptionReporter) {
// Avoid exposing token or sensitive fields in production
if (error.code === 'E_UNAUTHORIZED') {
reporter.info('Authentication failure')
}
super.handle(error, reporter)
}
}
5. Environment and Configuration Hygiene
Do not log environment variables or configuration that may contain signing keys or connection strings. In AdonisJS, avoid console.log(config.get('auth.tokenSecret')) or similar debug statements in production code.
middleBrick’s CLI can validate these configurations by scanning your API endpoints and flagging missing TLS or overly permissive database permissions. If you use the GitHub Action, you can fail builds when risk scores exceed your defined thresholds, and the MCP Server allows you to scan APIs directly from your IDE for early detection of token leakage risks.