HIGH cors wildcardadonisjscockroachdb

Cors Wildcard in Adonisjs with Cockroachdb

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

In AdonisJS, the CORS configuration is typically managed via start/hooks.ts or server.ts using the cors hook. When a wildcard * is set for origin alongside credentials-enabled requests, the combination can expose sensitive backend behavior when paired with a CockroachDB backend. CockroachDB often serves as a distributed SQL datastore for production API servers, and AdonisJS applications frequently connect to it via an ORM layer such as Lucid.

When origin: '*' is used together with credentials: true, browsers may still send cookies or authorization headers to what appears to be a permissive endpoint, but the server may inadvertently reflect or expose database-derived headers, error messages, or route details in responses. This can aid an attacker in mapping the API surface and inferring CockroachDB-specific behaviors, such as connection retry patterns or schema-related timing differences, especially if error handling is verbose.

Furthermore, if the AdonisJS application exposes an unauthenticated endpoint that queries CockroachDB and returns data, a wildcard CORS policy can allow a malicious frontend to orchestrate cross-origin requests that probe for IDOR or BOLA issues. Since CockroachDB does not inherently enforce origin constraints, the responsibility lies with the AdonisJS application to validate the Origin header and avoid reflecting arbitrary origins in response headers like Access-Control-Expose-Headers. Misconfigured CORS can therefore amplify attack surfaces that rely on unauthenticated or weakly authenticated database access patterns.

Cockroachdb-Specific Remediation in Adonisjs — concrete code fixes

Remediation focuses on tightening CORS configuration and ensuring database interaction does not leak information via headers or error messages. Below are concrete examples in AdonisJS that integrate securely with CockroachDB using Lucid.

1. Restrict CORS origins and disable wildcard

Replace wildcard origins with explicit domains. Use environment variables to manage allowed origins in production.

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

export const corsConfig = cors({
  origin: [
    process.env.FRONTEND_URL ?? 'http://localhost:3000',
    process.env.ADMIN_DASHBOARD_URL ?? 'http://localhost:5173',
  ],
  allowCredentials: true,
  allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
  allowHeaders: ['Content-Type', 'Authorization', 'X-Requested-With'],
})

2. Secure CockroachDB connection with environment-based configuration

Use environment variables for database credentials and ensure SSL is enforced. This example shows a typical database.ts configuration for CockroachDB in AdonisJS.

import { DbConnection } from '@ioc:Adonis/Lucid/Database'

const db: DbConnection = {
  connection: 'cockroachdb',
  pool: {
    connectionLimit: 6,
    min: 0,
    max: 10,
    idleTimeout: 30000,
    acquireTimeout: 30000,
  },
  replicas: [
    {
      connection: {
        host: process.env.CRDB_HOST,
        port: Number(process.env.CRDB_PORT),
        user: process.env.CRDB_USER,
        password: process.env.CRDB_PASSWORD,
        database: process.env.CRDB_NAME,
        ssl: {
          rejectUnauthorized: true,
          ca: process.env.CRDB_CA_CERT,
        },
      },
    },
  ],
}

export default db

3. Validate Origin on the server to prevent reflection

In a custom middleware or within the CORS hook, validate the incoming Origin header against a denylist or allowlist to prevent open redirects or header injection.

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

export default class CorsMiddleware {
  public async handle({ request, response }: HttpContextContract) {
    const origin = request.headers().origin
    const allowedOrigins = [
      'https://app.example.com',
      'https://staging.example.com',
    ]

    if (origin && allowedOrigins.includes(origin)) {
      response.header('Access-Control-Allow-Origin', origin)
    }

    response.header('Access-Control-Allow-Credentials', 'true')
    response.header(
      'Access-Control-Expose-Headers',
      'X-RateLimit-Limit,X-RateLimit-Remaining'
    )
  }
}

4. Avoid verbose error messages in production

CockroachDB errors can contain schema or constraint details. Ensure error responses are sanitized before being sent to the client to prevent information leakage.

import { Exception } from '@poppinss/utils'

export function safeCockroachError(error: any): string {
  if (process.env.NODE_ENV === 'production') {
    // Log full error internally, return generic message
    console.error('DB Error:', error)
    return 'Database error occurred'
  }
  return error.message
}

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 a wildcard CORS origin risky with CockroachDB-backed AdonisJS APIs?
A wildcard origin (*) with credentials enabled can allow malicious sites to make authenticated requests to your API. If error responses expose database details or headers, attackers can infer CockroachDB behavior or probe for IDOR issues. Always specify explicit origins and sanitize database-related headers.
How can I test if my CORS configuration is secure in AdonisJS?
Use curl or a browser devtools network tab to inspect response headers. Ensure Access-Control-Allow-Origin is not * when credentials are used, and that Access-Control-Expose-Headers does not include sensitive database metadata. Automated scans can also validate CORS misconfigurations.