HIGH pii leakageadonisjsbasic auth

Pii Leakage in Adonisjs with Basic Auth

Pii Leakage in Adonisjs with Basic Auth — how this specific combination creates or exposes the vulnerability

When an AdonisJS application uses HTTP Basic Authentication without additional safeguards, personally identifiable information (PII) can be exposed in multiple layers of the stack. Basic Auth transmits credentials in an Authorization header encoded as Base64 (not encrypted), so any interception or logging of that header can reveal usernames and passwords. In AdonisJS, developers sometimes rely on the built-in auth helpers without enforcing strict transport protections or output filtering, which can lead to PII leakage in logs, error messages, or API responses.

For example, if an endpoint returns user profile details including email or full name alongside an authenticated session, and the response is cached or logged by an upstream proxy, PII can be retained indefinitely. AdonisJS’s default JSON body parsing and response serialization do not automatically redact sensitive fields when Basic Auth is used. Additionally, if error handling exposes stack traces or configuration details (e.g., database connection names that include usernames), an attacker who gains access to logs can correlate credentials with PII.

Another scenario involves middleware that logs request headers for debugging. If the Authorization header is logged in plaintext or in a recoverable format, it exposes credentials and may link to user records containing PII stored in the database. This is especially risky when combined with insufficient rate limiting, as attackers can brute-force credentials and monitor logs for successful authentication patterns that confirm valid user PII.

OpenAPI specifications that include securitySchemes of type http with scheme basic must also be scrutinized. If the spec documents PII-rich endpoints without requiring additional authorization scopes or masking rules, runtime responses may inadvertently return sensitive data. middleBrick’s OpenAPI/Swagger analysis (2.0, 3.0, 3.1) with full $ref resolution can cross-reference spec definitions with runtime findings to highlight endpoints where authentication does not align with data exposure risks.

During black-box scanning, middleBrick runs 12 security checks in parallel, including Authentication, Data Exposure, and Input Validation, to detect whether Basic Auth–protected endpoints return PII in responses or headers. The scanner checks for missing no-cache headers, overly verbose error messages, and unencrypted transport usage. Findings include severity levels and remediation guidance, helping teams understand whether PII leakage stems from transport, logging, or response serialization issues.

Basic Auth-Specific Remediation in Adonisjs — concrete code fixes

To mitigate PII leakage when using Basic Auth in AdonisJS, apply transport enforcement, strict header handling, and response filtering. Below are concrete, syntactically correct examples that you can adopt directly.

1. Enforce HTTPS in production

Ensure all routes using Basic Auth are served over TLS to prevent credential and PII interception. In start/hooks.ts, redirect HTTP to HTTPS in production:

import { defineConfig } from '@adonisjs/core/app'

export default defineConfig({
  http: {
    middleware: ['start-request-hook'],
  },
  https: {
    enabled: true,
    port: 443,
  },
})

2. Use middleware to strip or mask sensitive response fields

Create an auth middleware that removes PII from responses when credentials are provided via Basic Auth. In src/Middleware/StripPii.ts:

import { Exception } from '@adonisjs/core/build/standalone'
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'

export default class StripPiiMiddleware {
  public async handle({ request, response, session }: HttpContextContract, next: () => Promise) {
    await next()

    // Only apply to authenticated requests using Basic Auth
    if (request.auth.user && request.headers().authorization?.startsWith('Basic ')) {
      const body = response.getBody()
      if (body && typeof body === 'object' && 'email' in body) {
        // Mask or remove PII fields
        const { email, ssn, ...safeBody } = body as Record
        response.mergeBody(safeBody)
      }
    }
  }
}

3. Secure route registration and authentication

Define routes that use Basic Auth via an auth scheme and apply the PII stripping middleware. In routes.ts:

import Route from '@ioc:Adonis/Core/Route'
import StripPii from 'App/Middleware/StripPii'

Route.group(() => {
  Route.get('/profile', async ({ auth }) => {
    const user = auth.getUserOrFail()
    // Ensure only necessary fields are returned
    return {
      id: user.id,
      username: user.username,
      // Do not include email or PII here
    }
  }).middleware(['auth:basic', StripPii])
}).prefix('api/v1')

4. Configure logging to avoid storing Authorization headers

Update your logger configuration to exclude Authorization headers. In config/app.ts or a custom provider:

import { Logger } from '@adonisjs/core'

Logger.hooks((hooks) => {
  hooks.pushLogListener((event) => {
    const req = event.ctx?.request?.originalUrl
    const headers = event.ctx?.request?.headers()
    if (headers?.authorization) {
      // Redact Basic Auth headers before logging
      delete headers.authorization
    }
    // Proceed with safe logging
  })
})

5. Validate and limit authentication attempts

Combine Basic Auth with rate limiting to reduce brute-force risks that could lead to PII correlation attacks. In start/kernel.ts:

import { Route } from '@adonisjs/core/types'

const rateLimiter = {
  identifier: 'basic-auth',
  window: 60000,
  max: 10,
}

Route.group(() => {
  // routes here
}).rateLimit(rateLimiter)

These steps ensure that PII is not leaked through logging, error responses, or unencrypted channels while maintaining Basic Auth compatibility in AdonisJS.

Related CWEs: dataExposure

CWE IDNameSeverity
CWE-200Exposure of Sensitive Information HIGH
CWE-209Error Information Disclosure MEDIUM
CWE-213Exposure of Sensitive Information Due to Incompatible Policies HIGH
CWE-215Insertion of Sensitive Information Into Debugging Code MEDIUM
CWE-312Cleartext Storage of Sensitive Information HIGH
CWE-359Exposure of Private Personal Information (PII) HIGH
CWE-522Insufficiently Protected Credentials CRITICAL
CWE-532Insertion of Sensitive Information into Log File MEDIUM
CWE-538Insertion of Sensitive Information into Externally-Accessible File HIGH
CWE-540Inclusion of Sensitive Information in Source Code HIGH

Frequently Asked Questions

Can middleBrick detect PII leakage in Basic Auth–protected AdonisJS endpoints?
Yes. middleBrick runs parallel checks including Data Exposure and Authentication. It cross-references OpenAPI/Swagger specs (2.0, 3.0, 3.1) with runtime responses to identify endpoints where Basic Auth does not prevent PII leakage, and it flags missing output filtering or oververbose error messages.
Does Basic Auth alone comply with frameworks like OWASP API Top 10 and GDPR when used in AdonisJS?
Basic Auth alone does not ensure compliance. OWASP API Top 10 requires transport encryption, strong credential storage, and output validation. GDPR requires data minimization and protection of PII. middleBrick’s checks for Encryption, Data Exposure, and Input Validation help identify gaps, but you must enforce HTTPS, response filtering, and secure logging to align with these frameworks.