Broken Authentication in Adonisjs with Api Keys
Broken Authentication in Adonisjs with Api Keys — how this specific combination creates or exposes the vulnerability
AdonisJS does not provide built-in API key management; developers integrate keys via application code or middleware. When API keys are used for authentication, broken authentication can occur if key validation is incomplete, keys are transmitted insecurely, or keys are stored or logged in plaintext. A typical vulnerability arises when an endpoint that should require a valid API key fails to enforce verification consistently, for example by allowing access when the key is missing, empty, or malformed.
Consider an AdonisJS route that relies on a custom middleware to check an X-API-Key header:
// start/hooks.ts
import { defineConfig } from '@adonisjs/core/app'
export default defineConfig({
http: {
middleware: () => import('#ioc/Middleware')
}
})
And a middleware implementation that performs key validation:
// start/hooks.ts
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
import { middleware } from '@adonisjs/core/fold'
const validKeys = new Set([process.env.API_KEY_1, process.env.API_KEY_2])
export const apiKeyAuth = middleware(async (ctx: HttpContextContract, next) => {
const key = ctx.request.header('x-api-key')
if (!key || !validKeys.has(key)) {
ctx.response.status(401).send({ error: 'Unauthorized' })
return
}
await next()
})
Broken authentication can occur if the check is bypassed by omitting the header, using a key that is accidentally exposed in client-side code, or if environment variables are misconfigured so that the keys are undefined or duplicated across environments. If the middleware is not applied to all sensitive routes, an attacker can access unprotected endpoints using known API keys intended for other routes. Additionally, if keys are passed over HTTP instead of HTTPS, they can be intercepted, leading to credential compromise.
Another risk specific to AdonisJS is improper error handling. If key validation failures return verbose errors or stack traces, attackers can infer whether a key is partially valid or gather information about the server configuration. Insecure logging of headers, including API keys, can also lead to unintended exposure in log files, especially if centralized logging is enabled without redaction.
In the context of the LLM/AI Security checks provided by middleBrick, system prompt leakage detection and active prompt injection testing are relevant because an improperly secured API key endpoint might expose internal instructions or configuration hints that could be probed via crafted inputs. middleBrick scans for such exposure patterns in unauthent attack surfaces, including missing or weak API key validation that aligns with these classes of broken authentication issues.
Api Keys-Specific Remediation in Adonisjs — concrete code fixes
To remediate broken authentication when using API keys in AdonisJS, enforce strict validation, secure transmission, and safe handling of keys. Use environment variables to store keys, avoid hardcoding them, and ensure that all sensitive routes are protected by consistent middleware checks.
Here is a secure pattern for API key validation in AdonisJS middleware:
// start/hooks.ts
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
import { middleware } from '@adonisjs/core/fold'
const validKeys = new Set(
(process.env.API_KEYS || '').split(',').map((k) => k.trim()).filter(Boolean)
)
export const apiKeyAuth = middleware(async (ctx: HttpContextContract, next) => {
const key = ctx.request.header('x-api-key')
if (!key || !validKeys.has(key)) {
ctx.response.status(401).send({ error: 'Unauthorized' })
return
}
await next()
})
In your route definitions, apply the middleware explicitly to endpoints that require protection:
// start/routes.ts
import Route from '@ioc:Adonis/Core/Route'
import { apiKeyAuth } from '#ioc/Middleware'
Route.get('/admin/settings', apiKeyAuth, async ({ response }) => {
return response.send({ settings: {} })
})
Ensure that API keys are transmitted only over HTTPS by configuring your server to redirect HTTP to HTTPS and by setting the SECURE_COOKIES and related security headers appropriately. Do not log API key values; if you must log requests, sanitize headers before logging:
// start/hooks.ts
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
import { middleware } from '@adonisjs/core/fold'
export const sanitizeLogging = middleware(async (ctx: HttpContextContract, next) => {
const headers = { ...ctx.request.headers() }
delete headers['x-api-key']
// safe logging using sanitized headers
console.log({ path: ctx.request.url(), method: ctx.request.method(), headers })
await next()
})
For production, rotate keys periodically and implement rate limiting to reduce the impact of leaked keys. The middleBrick Pro plan supports continuous monitoring and configurable scanning schedules to help detect regressions in key handling over time. Its GitHub Action can be integrated into CI/CD pipelines to fail builds if risk scores drop below your defined thresholds.
FAQ
- FAQ: How does middleBrick detect broken authentication related to API keys in AdonisJS scans?
middleBrick runs 12 security checks in parallel, including Authentication and BOLA/IDOR, against the unauthenticated attack surface. It compares runtime behavior against expected patterns for API key validation and flags missing or inconsistent enforcement, such as endpoints that should require keys but do not, or verbose error messages that leak validation state.
- FAQ: Can middleBrick test API key endpoints that require specific values without credentials?
Yes. middleBrick scans the unauthenticated attack surface by default. If you provide an OpenAPI/Swagger spec with examples or security schemes, it can cross-reference spec definitions with runtime findings to highlight mismatches in key requirements without needing authentication or credentials.
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 |