HIGH information disclosureadonisjscockroachdb

Information Disclosure in Adonisjs with Cockroachdb

Information Disclosure in Adonisjs with Cockroachdb — how this specific combination creates or exposes the vulnerability

AdonisJS, a Node.js web framework, relies on its ORM layer to manage database interactions, including connections to CockroachDB. Information disclosure occurs when application logic or framework behavior unintentionally exposes sensitive data—such as raw query results, stack traces, configuration details, or internal schema information—to unauthenticated or low-privileged actors.

When AdonisJS connects to CockroachDB, developers often configure database connections using environment variables and ORM mappings. If error handling is not strict, an invalid query or a misconfigured model can cause AdonisJS to return detailed database errors, including SQL syntax issues, constraint violations, or connection failures. These messages may reveal table names, column definitions, or internal query structures. For example, a missing index or a malformed WHERE clause in a CockroachDB query can trigger verbose errors that include the exact statement and positional markers, which an attacker can use to infer schema details.

CockroachDB’s wire protocol and SQL dialect can also contribute to disclosure when AdonisJS logs or surfaces database responses without sanitization. If an endpoint directly exposes query results—such as a user profile endpoint that returns a JSON object containing internal CockroachDB row IDs, timestamps, or sequence values—attackers can map relationships or enumerate resources. This is especially risky if the API responses include stack traces or debug metadata in development mode, which might reference internal file paths or environment variables that are sensitive.

Another vector involves improper usage of AdonisJS query scopes or dynamic model building. If a controller passes user-controlled input directly into a CockroachDB query without strict validation, an attacker may use injection techniques not to execute arbitrary SQL, but to observe differences in behavior—such as timing discrepancies or error messages—to infer the existence of columns or records. This can lead to indirect information leakage even when the database does not return explicit data.

Compliance mappings such as OWASP API Top 10 (A01:2023 Broken Object Level Authorization often overlaps with information exposure), PCI-DSS, and SOC2 highlight the need to limit data exposure in API responses. With middleBrick scanning this specific combination, findings can highlight unhandled error messages, verbose stack traces in HTTP responses, or overly detailed database exceptions that violate the principle of minimal information disclosure.

Cockroachdb-Specific Remediation in Adonisjs — concrete code fixes

To mitigate information disclosure when using AdonisJS with CockroachDB, apply strict error handling, response sanitization, and query parameterization. Below are concrete code examples that demonstrate secure patterns.

1. Centralized Error Handling

Use AdonisJS exception handling to catch database errors and return generic messages. Avoid exposing raw query errors to the client.

// start/src/Exceptions/Handler.ts
import { ExceptionHandler } from '@poppinss/dev-utils'
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'

export default class ExceptionHandler extends ExceptionHandler {
  public async handle(error: any, ctx: HttpContextContract) {
    if (error.name === 'QueryException') {
      // Log detailed error internally
      console.error('DB Error:', error)
      // Return generic message to client
      ctx.response.status(400).json({ message: 'Request failed due to invalid data.' })
      return
    }
    await super.handle(error, ctx)
  }
}

2. Parameterized Queries with Lucid ORM

Always use parameterized queries or Lucid ORM methods to avoid leaking schema details through malformed SQL.

// start/controllers/UserController.ts
import User from 'App/Models/User'

export class UserController {
  public async show({ params, response }: HttpContextContract) {
    try {
      const user = await User.query()
        .where('id', params.id)
        .preload('profile')
        .firstOrFail()

      response.json(user.serialize())
    } catch (error) {
      response.status(404).json({ message: 'Resource not found.' })
    }
  }
}

3. Safe Response Serialization

Define explicit serialize methods on models to control which fields are exposed, avoiding accidental exposure of internal CockroachDB metadata.

// start/models/User.ts
import { DateTime } from 'luxon'
import { BaseModel, beforeSerialize } from '@ioc:Adonis/Lucid/Orm'

export default class User extends BaseModel {
  public static serializeRelations = true

  @beforeSerialize()
  public static hideSensitiveFields(user: User) {
    user.merge({
      password: undefined,
      resetToken: undefined,
    })
  }

  public serialize() {
    return {
      id: this.id,
      email: this.email,
      createdAt: this.createdAt.toISODate(),
    }
  }
}

4. Environment-Based Error Verbosity

Ensure detailed errors are only enabled in development, never in production where CockroachDB responses might be exposed.

// start/kernel.ts
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'

export default class Kernel {
  public async handle(ctx: HttpContextContract) {
    ctx.response.debug = !!process.env.DEBUG
    // ... rest of handler
  }
}

5. Input Validation to Prevent Enumeration

Validate and sanitize inputs to prevent attackers from probing schema differences through error behavior.

// start/validators/user.ts
import { schema } from '@ioc:Adonis/Core/Validator'

export const userSchema = schema.create({
  id: schema.number([
    () => rules.unsigned(),
    () => rules.exists({ table: 'users', column: 'id' })
  ])
})

Frequently Asked Questions

How does middleBrick detect information disclosure risks with AdonisJS and CockroachDB?
middleBrick runs black-box checks that analyze HTTP responses, error messages, and API output for verbose database errors, stack traces, or exposed internal identifiers. It correlates findings with OWASP API Top 10 and maps remediation guidance to your specific framework and database.
Can middleBrick integrate into CI/CD to catch information disclosure before deployment?
Yes, with the middleBrick GitHub Action you can add API security checks to your CI/CD pipeline, fail builds if risk scores drop below your threshold, and scan staging APIs before deploy.