HIGH cors wildcardadonisjsbasic auth

Cors Wildcard in Adonisjs with Basic Auth

Cors Wildcard in Adonisjs with Basic Auth — how this specific combination creates or exposes the vulnerability

AdonisJS is a Node.js web framework that relies on underlying HTTP server CORS behavior. When you configure CORS with a wildcard origin (*) while using HTTP Basic Authentication, the browser may allow cross-origin requests that expose credentials unintentionally. The vulnerability arises because * permits any origin to read the response, and when credentials are included, some browsers treat the wildcard as too permissive, potentially bypassing intended origin restrictions.

In AdonisJS, the CORS configuration is typically defined in start/cors.ts. A common but risky setup looks like this:

import { defineConfig } from '@ioc:Adonis/Addons/Cors'

export default defineConfig({
  enabled: true,
  origin: '*',
  allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH'],
  allowHeaders: ['Authorization', 'Content-Type'],
  allowCredentials: true,
})

Setting allowCredentials: true alongside origin: '*' is non-compliant with the CORS specification. Browsers will reject such combinations in many scenarios, but when they do permit the request, the wildcard origin allows any site to make authenticated requests on behalf of the user. This can lead to unauthorized access to protected resources if the browser sends the Basic Auth credentials automatically to the wildcard-origin site.

An attacker can craft a malicious webpage that includes an Image tag or an XMLHttpRequest/fetch call to your AdonisJS API endpoint. If the user is logged in via Basic Auth (credentials stored in the browser), the browser may include the Authorization header in the request to your API. The response, now accessible to the attacker’s origin, might leak sensitive data. This scenario is especially dangerous when endpoints return sensitive information without additional checks, as the wildcard origin grants broad access.

For example, consider an endpoint that returns user profile details:

Route.get('/profile', async ({ auth }) => {
  const user = await auth.authenticate()
  return user.serialize()
})

If the CORS configuration allows credentials with a wildcard origin, an attacker’s site could load this endpoint via JavaScript and read the response, exposing the authenticated user’s data. This constitutes a cross-origin information disclosure that should be prevented by tightening CORS rules and avoiding wildcards when credentials are involved.

Basic Auth-Specific Remediation in Adonisjs — concrete code fixes

To mitigate CORS issues with Basic Auth in AdonisJS, you must avoid using a wildcard origin when credentials are allowed. Instead, specify explicit origins and ensure that the Authorization header is handled securely.

First, update your CORS configuration to list trusted origins explicitly:

import { defineConfig } from '@ioc:Adonis/Addons/Cors'

export default defineConfig({
  enabled: true,
  origin: ['https://your-frontend.com', 'https://app.yourdomain.com'],
  allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH'],
  allowHeaders: ['Authorization', 'Content-Type'],
  allowCredentials: true,
})

This change ensures that only known origins can make authenticated requests, reducing the risk of cross-origin data exposure. It aligns with CORS best practices and browser security mechanisms.

Second, implement Basic Auth in a way that does not rely on the browser’s automatic credential handling for cross-origin requests unless absolutely necessary. For API endpoints, consider using token-based authentication instead. If you must use Basic Auth, ensure that the endpoint validates the origin on the server side as an additional safeguard:

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

export default class AuthController {
  public async login({ request, auth, response }: HttpContextContract) {
    const { username, password } = request.only(['username', 'password'])
    try {
      const token = await auth.attempt(username, password)
      return response.ok({ token })
    } catch {
      return response.unauthorized({ message: 'Invalid credentials' })
    }
  }

  public async profile({ auth, response }: HttpContextContract) {
    const user = await auth.authenticate()
    return response.ok(user.serialize())
  }
}

In this example, the login endpoint uses token-based authentication, which is safer for cross-origin scenarios. The profile endpoint relies on the established authentication, which should be protected by proper CORS settings as shown earlier.

Additionally, you can add a middleware to verify the Origin header for sensitive endpoints:

import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
import { HttpException } from '@poppinss/utils'

export default function validateOrigin({ request, response }: HttpContextContract) {
  const allowedOrigin = 'https://your-frontend.com'
  const requestOrigin = request.headers().origin

  if (requestOrigin !== allowedOrigin) {
    throw new HttpException(403, 'Forbidden')
  }
}

Register this middleware for routes that require strict origin validation. Combining explicit origins, secure authentication methods, and server-side origin checks provides a robust defense against CORS-related vulnerabilities when using Basic Auth.

Real-world detection and remediation with middleBrick

middleBrick can detect CORS misconfigurations, including wildcard origins with credentials, during scans. To run a scan from your terminal, use the CLI:

middlebrick scan https://api.yourservice.com

For continuous monitoring, the Pro plan provides configurable schedules and alerts. You can integrate scans into your CI/CD pipeline using the GitHub Action to fail builds if a risky CORS setup is found:

uses: middlebrick/github-action@v1
with:
  url: ${{ secrets.API_URL }}
  threshold: 70

When findings appear, review the remediation guidance provided. Adjust your CORS configuration as shown in the remediation examples, and re-scan to confirm the issue is resolved.

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

Why is using 'origin: *' with 'allowCredentials: true' problematic in AdonisJS?
This combination violates the CORS specification. Browsers may reject the request or, if allowed, permit any origin to read authenticated responses, enabling cross-origin data exposure via Basic Auth credentials.
Can middleBrick fix CORS issues automatically?
middleBrick detects and reports CORS misconfigurations with severity and remediation guidance. It does not automatically fix issues; you must update your AdonisJS CORS configuration based on the findings.