Token Leakage in Adonisjs with Basic Auth
Token Leakage in Adonisjs with Basic Auth — how this specific combination creates or exposes the vulnerability
Token leakage occurs when authentication credentials or session tokens are exposed beyond their intended scope. In AdonisJS, using HTTP Basic Authentication without additional safeguards can inadvertently expose tokens or session identifiers through logs, error messages, or downstream network calls. When Basic Auth is implemented naively, the base64-encoded credentials are often decoded and attached to the request context for the lifetime of the connection. If the application passes these credentials to external services, logs them, or reflects them in API responses, a token or credential can be leaked to unauthorized parties.
Consider a scenario where an AdonisJS route decodes Basic Auth credentials and uses them to sign JWTs or to forward requests to an internal service. If the downstream service returns an error that includes the Authorization header or if the application logs the decoded credentials, an attacker who can read logs or intercept error responses may obtain valid tokens or session identifiers. This becomes more impactful when combined with insecure transport, insufficient input validation, or improper error handling, which are common in APIs with broad unauthenticated attack surfaces.
AdonisJS applications that expose OpenAPI specs or debug endpoints may further amplify the risk. An attacker performing black-box scanning with middleBrick can detect whether Basic Auth is used, whether tokens are reflected in responses, and whether error messages disclose sensitive information. The scanner checks for SSRF, Data Exposure, and Unsafe Consumption findings that can indicate paths where leaked credentials or tokens are transmitted inadvertently. For example, if an endpoint echoes the Authorization header into an outbound request or into a response body, middleBrick may flag Data Exposure because runtime tests reveal that credentials or tokens are present in outputs that should be sanitized.
Another vector involves improper handling of tokens within middleware. If an AdonisJS app decodes Basic Auth and then stores the credentials or derived tokens in request-scoped objects that are later serialized into logs or client responses, leakage can occur during serialization or when exceptions are thrown. The presence of LLM/AI Security checks in middleBrick helps identify whether system prompts or configuration details that reference authentication flows are exposed, but for token leakage the key indicators are reflected credentials in responses, verbose error messages, and missing header normalization before logging.
To contextualize the risk, middleBrick evaluates multiple categories in parallel. Authentication checks verify whether credentials are handled securely, while Data Exposure checks determine whether tokens or credentials appear in responses or logs. Input Validation ensures that credentials are not reflected unsanitized, and SSRF testing confirms that internal calls do not propagate sensitive headers. Together, these checks highlight how the combination of Basic Auth and token handling in AdonisJS can create leakage paths that are detectable without authentication.
Basic Auth-Specific Remediation in Adonisjs — concrete code fixes
Remediation focuses on preventing credentials and derived tokens from being logged, reflected, or forwarded unintentionally. Always treat Basic Auth credentials as opaque identifiers, avoid decoding them unless necessary, and never include them in responses or logs.
Example: Safe Basic Auth handler in AdonisJS
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
import { schema } from '@ioc:Adonis/Core/Validator'
export default class AuthController {
public async basicAuth({ request, response }: HttpContextContract) {
// Validate the presence of the Authorization header
const authHeader = request.header('authorization')
if (!authHeader || !authHeader.startsWith('Basic ')) {
return response.unauthorized({ message: 'Missing or invalid Authorization header' })
}
// Extract and decode credentials without persisting them unnecessarily
const base64 = authHeader.split(' ')[1]
const decoded = Buffer.from(base64, 'base64').toString('utf8')
const [username, password] = decoded.split(':')
// Validate format early and avoid logging credentials
const authSchema = schema.create({
username: schema.string.optional(),
password: schema.string.optional(),
})
const payload = await request.validate({ schema: authSchema })
// Perform authentication using a secure provider, not by echoing credentials
const user = await this.authenticateUser(payload.username, payload.password)
if (!user) {
return response.unauthorized({ message: 'Invalid credentials' })
}
// Issue a short-lived token or session identifier, not a transformation of the Basic credentials
const token = this.generateSessionToken(user.id)
// Ensure no credentials or tokens are included in error logs or responses
return response.ok({ access_token: token, token_type: 'Bearer' })
}
private authenticateUser(username: string | undefined, password: string | undefined) {
// Replace with secure user lookup and password verification
return { id: 1, username } // simplified example
}
private generateSessionToken(userId: number): string {
// Use a cryptographically secure method to generate a token
return Buffer.from(`${userId}:${Date.now()}:${Math.random()}`).toString('base64')
}
}
Key remediation practices
- Do not reflect the Authorization header or decoded credentials in API responses.
- Avoid logging raw credentials or derived tokens; log only anonymized identifiers if necessary.
- Ensure transport security (HTTPS) to prevent interception of Basic Auth credentials.
- Normalize and sanitize all headers before forwarding them to downstream services or including them in logs.
- Use short-lived access tokens issued after successful authentication rather than reusing Basic credentials.
When integrating with external services, configure outbound HTTP clients to strip sensitive headers unless explicitly required. In AdonisJS, this can be done at the HTTP client layer by filtering headers before requests are sent. middleBrick can then verify that runtime tests do not expose tokens or credentials in outbound calls, reducing Data Exposure and SSRF findings related to credential propagation.