HIGH log injectionadonisjscockroachdb

Log Injection in Adonisjs with Cockroachdb

Log Injection in Adonisjs with Cockroachdb — how this specific combination creates or exposes the vulnerability

Log injection occurs when untrusted input is written directly into application logs without sanitization or formatting, allowing an attacker to forge log entries, inject newlines, or add misleading metadata. In Adonisjs applications using Cockroachdb, this risk arises at the intersection of framework logging behavior and database-driven operations.

Adonisjs uses a structured logger (often based on the local provider or third-party adapters) that can include contextual data such as request identifiers, user IDs, and query parameters. When an application logs database actions—such as query results or error messages—and those messages contain attacker-controlled input (e.g., a username, search term, or HTTP header), the log output may become corrupted or ambiguous.

Cockroachdb, while PostgreSQL-wire compatible, does not inherently sanitize inputs for logging; it returns raw query results and error objects that Adonisjs may pass through to its logging layer. If an endpoint accepts a search parameter and logs the executed query or returned rows without validation, an attacker can supply newline sequences (\n) or structured text to inject fabricated entries. For example, a malicious payload like foo\n{"level":"CRITICAL","msg":"Unauthorized access"} can create a fake log line that appears authoritative.

The risk is compounded when Adonisjs logs include stack traces or error details pulled from Cockroachdb exceptions. An attacker who triggers a malformed query can cause verbose database errors to be logged, potentially revealing schema details or internal paths. In distributed deployments, forged logs can bypass monitoring rules or obscure real incidents, undermining auditability.

middleBrick’s LLM/AI Security checks are relevant here because system prompt leakage patterns can resemble structured log injection attempts (e.g., injected JSON or control sequences). The scanner tests for output pollution and documents findings tied to OWASP API Top 10 and CWE-117 (Log Injection).

Cockroachdb-Specific Remediation in Adonisjs — concrete code fixes

To mitigate log injection when using Cockroachdb with Adonisjs, focus on input validation, structured logging, and safe error handling. Never concatenate raw user input into log messages or database queries.

1. Parameterized Queries with Logging of Safe Metadata

Use Adonisjs query builder or Lucid ORM with bound parameters. Log only sanitized metadata, never raw query strings with user content.

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

export default class SearchController {
  public async search() {
    const { q } = this.ctx.request.qs()
    // Validate and sanitize input
    const safeQuery = q?.trim().substring(0, 100) ?? ''

    const results = await Database.from('items')
      .where('name', 'ilike', `%${safeQuery}%')
      .limit(50)

    // Log safe metadata only
    this.logger.info('search_executed', {
      timestamp: DateTime.local().toISO(),
      query_length: safeQuery.length,
      result_count: results.length,
      user_id: this.auth.user?.id ?? null,
    })

    return results
  }
}

2. Structured Error Handling with Context Stripping

When Cockroachdb throws an error, extract only safe fields for logging. Avoid logging raw SQL or error messages that may contain injected content.

import { HttpException } from '@adonisjs/core/build/standalone'

export default class DatabaseLogger {
  public static logError(error: any, context: { user_id?: number, route?: string }) {
    // Extract only non-sensitive fields
    const safeError = {
      message: error.message?.substring(0, 200) ?? 'Unknown error',
      code: error.code || 'UNKNOWN_ERROR',
      constraint: error.constraint || null,
      context,
      timestamp: new Date().toISOString(),
    }
    // Avoid logging error.sql or raw row content
    logger.error('db_operation_failed', safeError)
  }
}

// Usage in a route handler
try {
  await Database.from('profiles').insert({ user_id: 1, bio: 'test' })
} catch (error) {
  DatabaseLogger.logError(error, { user_id: 1, route: '/profile/update' })
  throw error
}

3. Input Normalization and Log Format Control

Normalize newlines and control characters in any data destined for logs. Configure your logger’s format to escape or reject control sequences.

function sanitizeForLog(input: string): string {
  return input
    .replace(/\r\n|\r|\n/g, ' ')  // collapse newlines
    .replace(/[\x00-\x1F\x7F]/g, '')  // remove control chars
    .trim()
}

const userSupplied = this.ctx.request.input('comment', '')
const safeComment = sanitizeForLog(userSupplied)

logger.info('user_comment', {
  comment_preview: safeComment.substring(0, 200),
})

These practices align with middleBrick’s free scan offerings, which can identify log injection risks in unauthenticated scans. For teams needing continuous assurance, the Pro plan enables scheduled scans and CI/CD integration to flag regressions before deployment.

Frequently Asked Questions

Can middleBrick detect log injection in my Adonisjs app connected to Cockroachdb?
Yes. middleBrick’s unauthenticated scan includes input validation and output checks that can flag log injection patterns. Findings include severity, remediation steps, and mapping to OWASP API Top 10 and CWE-117.
Does middleBrick fix the log injection issues it finds?
No. middleBrick detects and reports findings with remediation guidance. It does not modify code, patch libraries, or alter runtime behavior.