HIGH token leakageadonisjsapi keys

Token Leakage in Adonisjs with Api Keys

Token Leakage in Adonisjs with Api Keys — how this specific combination creates or exposes the vulnerability

Token leakage in AdonisJS applications that use API keys often occurs around how keys are stored, transmitted, and logged. AdonisJS does not inherently leak tokens, but patterns common in projects can expose them. For example, storing API keys in environment files that are accidentally committed, echoing keys in debug output, or including them in URLs or client‑side JavaScript increases the risk of exposure.

AdonisJS projects typically manage configuration via env files and the Config helper. If an API key is loaded from .env and then reflected into responses, logs, or error messages, a token leakage finding may be surfaced by a scanner. Consider a route that forwards requests using an API key read from config:

import Env from '@ioc:Adonis/Core/Env'
import axios from 'axios'

Route.get('/proxy', async ({ request, response }) => {
  const apiKey = Env.get('EXTERNAL_API_KEY')
  const res = await axios.get('https://api.external.com/data', {
    headers: { Authorization: `Bearer ${apiKey}` }
  })
  response.send(res.data)
})

If the application ever sends apiKey to the client—such as embedding it in serialized state, error details returned to the browser, or console logs accessible to an authenticated user—the key is leaked. Another scenario involves OpenAPI specs generation where examples include literal keys; if these specs are publicly served or committed to version control, the key is exposed. MiddleBrick scans detect such leakage by checking whether API keys appear in responses, logs, or documentation artifacts reachable without authentication.

SSRF interactions can also lead to token leakage. If an AdonisJS endpoint accepts a user-supplied URL and makes requests using an API key, an attacker may supply a malicious endpoint that captures the key. For instance:

Route.post('/fetch', async ({ request, response }) => {
  const { url } = request.body()
  const apiKey = Env.get('EXTERNAL_API_KEY')
  // Risk: attacker-controlled url can redirect the request to a server they control
  const res = await axios.get(url, {
    headers: { Authorization: `Bearer ${apiKey}` }
  })
  response.send(res.data)
})

Without strict URL validation and SSRF protections, an attacker can coax the service into sending the API key to an external endpoint they operate. MiddleBrick’s SSRF and Data Exposure checks highlight these risks when specs or runtime behavior indicate that tokens may leave the service boundary unintentionally.

Finally, insecure handling of OpenAPI specs that include examples with placeholder keys that are mistakenly replaced with real values can cause leakage. If a generated spec is served publicly and contains a literal key, any visitor can extract it. MiddleBrick’s OpenAPI/Swagger analysis resolves $ref definitions and cross-references spec examples with runtime findings to surface such mismatches.

Api Keys-Specific Remediation in Adonisjs — concrete code fixes

Remediation focuses on ensuring API keys never reach the client, are not logged inappropriately, and are transmitted only over secure channels. Use server-side headers, avoid echoing keys in responses, and validate all user input that influences outbound requests.

1) Keep keys server-side and use them only in request headers. Do not include API keys in the response body or frontend state:

import Env from '@ioc:Adonis/Core/Env'
import axios from 'axios'

Route.get('/data', async ({ response }) => {
  const apiKey = Env.get('EXTERNAL_API_KEY')
  const res = await axios.get('https://api.external.com/data', {
    headers: { Authorization: `Bearer ${apiKey}` }
  })
  // Send only the data, never the key
  response.send(res.data)
})

2) Avoid logging API keys. Ensure that request and error logging does not include the key. Use selective serialization:

import logger from '@ioc:Adonis/Core/Logger'

Route.post('/proxy', async ({ request, response }) => {
  const apiKey = Env.get('EXTERNAL_API_KEY')
  try {
    const res = await axios.get('https://api.external.com/data', {
      headers: { Authorization: `Bearer ${apiKey}` }
    })
    response.send(res.data)
  } catch (error) {
    // Log safely without the key
    logger.error('External request failed', { status: error.response?.status, url: error.config?.url })
    response.status(502).send({ error: 'upstream failure' })
  }
})

3) Validate and restrict outbound URLs to prevent SSRF. Do not forward user-controlled URLs without strict allowlisting or pattern checks:

import Route from '@ioc:Adonis/Core/Route'
import axios from 'axios'
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'

Route.post('/fetch', async ({ request, response }: HttpContextContract) => {
  const { url } = request.body()
  // Allowlist approach: only permit known prefixes
  if (!url.startsWith('https://api.example.com/')) {
    return response.status(400).send({ error: 'invalid target' })
  }
  const apiKey = Env.get('EXTERNAL_API_KEY')
  const res = await axios.get(url, {
    headers: { Authorization: `Bearer ${apiKey}` }
  })
  response.send(res.data)
})

4) Do not embed API keys in client-side artifacts. Ensure generated OpenAPI specs do not contain real keys in examples or schemas served to browsers. If examples require keys, use placeholder values that are replaced at build time and never shipped to clients.

5) Use environment-based configuration and secret management. Store keys in environment variables and, where possible, integrate with secret managers. Rotate keys regularly and monitor for unexpected usage patterns.

Adopting these patterns reduces token leakage risk and aligns with secure handling of credentials in server-side JavaScript applications.

Frequently Asked Questions

Can MiddleBrick detect API key leakage in AdonisJS projects?
Yes. MiddleBrick scans for tokens in responses, logs, and specs, and flags leakage when API keys appear in client‑facing artifacts or insecure locations.
Does MiddleBrick fix token leakage findings in AdonisJS?
No. MiddleBrick detects and reports findings with remediation guidance. It does not modify code, block traffic, or patch applications.