Api Key Exposure in Adonisjs with Mysql
Api Key Exposure in Adonisjs with Mysql — how this specific combination creates or exposes the vulnerability
AdonisJS, a Node.js web framework, often uses environment variables to manage sensitive credentials such as database passwords and API keys. When integrating with Mysql, developers may inadvertently expose API keys through misconfigured environment files, insecure logging, or improper handling of configuration in AdonisJS applications. In this stack, API keys might be stored in .env files and referenced in AdonisJS configuration files (e.g., config/database.ts). If these keys are accidentally committed to source control, logged in application output, or exposed through error messages, they become accessible to unauthorized parties.
Mysql itself does not store API keys used by AdonisJS, but the application may embed keys in connection strings or ORM query options passed to Mysql drivers. For example, an API key used to authenticate with a third-party service could be constructed dynamically using values from the Mysql database, such as a tenant identifier retrieved via an ORM query. If this key is then included in logs, HTTP responses, or debug output, it becomes exposed. Additionally, if an attacker gains access to the Mysql instance used by the application, they might infer key usage patterns through query analysis, especially when keys are derived from database-stored configuration rows.
The risk is amplified when AdonisJS applications are deployed in environments where Mysql is accessible without network restrictions, and environment variables are not properly isolated. For instance, if an application uses a single .env file across development and production, a leaked key from a development environment could grant access to production Mysql resources. Furthermore, AdonisJS service providers that initialize external API clients using keys fetched from Mysql rows can inadvertently expose those keys through insecure deserialization or improperly secured endpoints, such as those vulnerable to IDOR (Insecure Direct Object Reference) when keys are referenced via predictable identifiers.
To detect such exposure using middleBrick, which scans the unauthenticated attack surface of an API endpoint, submit the application’s public endpoint. The tool performs 12 parallel security checks, including Data Exposure and Unsafe Consumption, to identify whether API keys appear in responses, logs, or error messages. middleBrick also supports OpenAPI/Swagger spec analysis, cross-referencing spec definitions with runtime findings to highlight mismatches between declared and actual behavior. For LLM-related risks, its unique LLM/AI Security checks can detect system prompt leakage or output containing sensitive strings like API keys, even when keys are embedded in generated text.
middleBrick provides prioritized findings with severity ratings and remediation guidance, helping teams address exposure without assuming it automatically fixes issues. The tool integrates with Web Dashboard, CLI, GitHub Actions, and MCP Server environments, enabling continuous monitoring and CI/CD enforcement. While it does not block or patch vulnerabilities, it delivers actionable steps, such as rotating exposed keys and securing configuration handling in AdonisJS and Mysql integrations.
Mysql-Specific Remediation in Adonisjs — concrete code fixes
Securing API keys in AdonisJS when using Mysql requires precise configuration and code practices to prevent accidental exposure. Below are concrete remediation steps with syntactically correct examples.
1. Use environment-specific configuration with strict variable separation
Ensure production and development configurations are isolated. Store API keys exclusively in environment variables and avoid hardcoding them in AdonisJS configuration files.
// config/database.ts
import { Env } from '@ioc:Adonis/Core/Env'
export default {
connection: 'mysql',
connections: {
mysql: {
client: 'mysql',
host: Env.get('DB_HOST', '127.0.0.1'),
port: Env.get('DB_PORT', 3306),
user: Env.get('DB_USER', 'root'),
password: Env.get('DB_PASSWORD', ''),
database: Env.get('DB_NAME', 'adonis'),
ssl: Env.get('DB_SSL') === 'true' ? { rejectUnauthorized: false } : false,
},
},
}
In this setup, API keys used by external services should be referenced as separate environment variables, not derived from Mysql rows.
2. Avoid dynamic key construction from Mysql data
Do not generate API keys by querying Mysql and concatenating values in application code. If keys must be associated with database records, store only references (e.g., key IDs) and resolve them securely at runtime using environment mappings.
// Bad practice: constructing key from DB row
const row = await Database.from('tenants').where('id', tenantId).first()
const apiKey = `${row.prefix}_${row.secret}` // Risk of exposure
// Recommended: use preloaded environment mapping
const apiKey = Env.get(`TENANT_${tenantId}_API_KEY`)
3. Secure logging and error handling
Prevent API keys from appearing in logs or error responses. Configure AdonisJS to filter sensitive fields and avoid logging raw query results that might contain key-related metadata.
// start/hooks.ts
import { Exception } from '@poppinss/utils'
Exception.handle((error, { response }) => {
if (error?.message?.includes('API_KEY')) {
response.status(500).send({ error: 'Internal server error' })
} else {
// default handling
}
})
4. Validate and sanitize inputs that influence key usage
Even when keys are stored securely, ensure that Mysql queries using user input are parameterized to prevent injection that could lead to key extraction.
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
import { schema } from '@ioc:Adonis/Core/Validator'
export default class ApiController {
public async store({ request, response }: HttpContextContract) {
const bodySchema = schema.create({
tenant_id: schema.number(),
})
const validated = await request.validate({ schema: bodySchema })
const keyRef = validated.tenant_id // used to look up key securely from env
const apiKey = Env.get(`KEY_REF_${keyRef}`)
// use apiKey securely without logging or exposing
}
}