Insufficient Logging in Adonisjs with Cockroachdb
Insufficient Logging in Adonisjs with Cockroachdb — how this specific combination creates or exposes the vulnerability
Insufficient logging in an Adonisjs application using Cockroachdb can leave security-relevant events unrecorded, reducing the ability to detect, investigate, or respond to incidents. Adonisjs relies on its logging system (often using the provider-based logger built on concrete or pino) to capture application behavior, while Cockroachdb exposes detailed server-side logs and execution context for SQL operations. When diagnostic logs are not explicitly emitted for authentication, authorization, and data access events, important signals—such as repeated authentication failures, privilege escalation attempts, or unexpected query patterns—are not persisted in Adonisjs logs and may be missed during incident review.
In a typical Adonisjs + Cockroachdb setup, developers may log only high-level request identifiers or query results, omitting structured details like user identifiers, roles, tenant context, SQL statement metadata, and execution outcomes. For example, failing to log which rows were accessed or modified in a BOLA/IDOR scenario means that an attacker’s probing behavior is not visible in Adonisjs logs, even though Cockroachdb may record the statement internally. Because middleBrick performs black-box scanning and checks such as Authentication, BOLA/IDOR, and Data Exposure, it can surface gaps where logs do not contain sufficient detail to correlate runtime findings with audit trails. Without logs that capture request context, parameter values, and outcome status codes, organizations cannot reliably trace an incident back to a specific user or API call, weakening forensic capabilities and compliance reporting.
The risk is compounded when error handling in Adonisjs swallows stack traces or database errors without recording key context, such as the user ID, request path, or bound parameters sent to Cockroachdb. If an attacker triggers error conditions that result in verbose messages returned to the client but not logged server-side, the organization gains an attacker’s view while losing the defender’s view. middleBrick’s checks for Input Validation, Property Authorization, and Data Exposure highlight scenarios where logs do not provide actionable insight into malformed inputs or unauthorized data access. Because middleBrick scans the unauthenticated attack surface and correlates findings with best practices, it underscores the importance of structured, comprehensive logging that captures both successful and denied operations across the Adonisjs application and its Cockroachdb interactions.
To align with frameworks like OWASP API Top 10 and controls such as SOC2 and GDPR, logging must be explicit, consistent, and tied to identity and scope. middleBrick does not fix or block these issues; it detects and reports them with remediation guidance. Teams should ensure that Adonisjs middleware and service classes produce logs that include request identifiers, user or client context, tenant scope, SQL operation metadata, success or failure status, and sanitized parameter representations. These logs should be structured and forwarded to a centralized observability pipeline to enable correlation with Cockroachdb server logs, query performance metrics, and security event timelines.
Cockroachdb-Specific Remediation in Adonisjs — concrete code fixes
Remediation focuses on instrumenting Adonisjs to emit detailed, structured logs for every interaction with Cockroachdb, including authentication, data access, and error paths. Use Adonisjs providers and hooks to capture context before and after database operations, and ensure logs contain sufficient detail for traceability without exposing sensitive data.
Structured logging with the built-in logger
Configure Adonisjs to use structured logging (e.g., pino or concrete) and include correlation IDs, tenant identifiers, and user context. For example, in a controller that queries Cockroachdb via Lucid ORM:
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
import Database from '@ioc:Adonis/Addons/Lucid'
export default class UsersController {
public async show({ request, response, auth, logger }: HttpContextContract) {
const correlationId = request.correlationId || request.id()
const user = await auth.authenticate()
const tenantId = user.tenantId
logger.info({
correlationId,
tenantId,
userId: user.id,
event: 'user.profile.fetch',
endpoint: request.url(),
method: request.method(),
}, 'Fetching user profile')
try {
const result = await Database.from('profiles')
.where('user_id', user.id)
.select('id', 'displayName', 'email')
logger.info({
correlationId,
tenantId,
userId: user.id,
event: 'db.query.success',
table: 'profiles',
rows: result.length,
durationMs: /* optional timer */ 0,
}, 'Query executed successfully')
return response.send(result)
} catch (error) {
logger.error({
correlationId,
tenantId,
userId: user.id,
event: 'db.query.error',
table: 'profiles',
errorCode: error.code,
sqlState: error.sqlState,
}, 'Database query failed')
return response.badRequest({ message: 'Unable to fetch profile' })
}
}
}
Instrumenting Lucid models for Cockroachdb operations
Extend Lucid models to emit lifecycle hooks that log database actions with tenant and ownership context. This ensures that reads, updates, and deletes are recorded with sufficient detail to support BOLA/IDOR detection and Data Exposure checks.
import BaseModel from '@ioc:Adonis/Lucid/Model'
import { DateTime } from 'luxon'
export default class Profile extends BaseModel {
public static boot() {
super.boot()
this.addHook('beforeFind', (query) => {
// In a request context, attach correlation/logging externally; hooks alone cannot emit logs.
// Use service-layer logging to capture tenantId and userId.
})
this.addHook('afterFind', (result, { parentQuery }) => {
// Logging should be orchestrated by the service or controller to retain context.
})
this.addHook('afterSave', (result, { isCreate, isUpdate }) => {
// Prefer service-layer logging for structured context.
})
}
}
Middleware to capture request and DB context
Add a middleware layer that attaches a correlation ID and tenant context, and ensure that services log both request metadata and Cockroachdb outcomes. Example middleware:
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
export default class LoggingMiddleware {
public async handle({ request, response, auth, logger, connection }: HttpContextContract, next) {
const correlationId = request.correlationId || request.id()
const user = await auth.getUser()
const tenantId = user ? user.tenantId : 'anonymous'
logger.info({
correlationId,
tenantId,
userId: user ? user.id : null,
path: request.url(),
method: request.method(),
timestamp: DateTime.local().toISO(),
}, 'Request received')
try {
const result = await next()
logger.info({
correlationId,
tenantId,
statusCode: response.status,
event: 'request.complete',
}, 'Request completed')
return result
} catch (error) {
logger.error({
correlationId,
tenantId,
path: request.url(),
method: request.method(),
errorCode: error.code,
sqlState: error.sqlState,
}, 'Request failed')
throw error
}
}
}
Parameter binding and query metadata
When executing parameterized queries against Cockroachdb via Adonisjs/Lucid, log the sanitized parameter keys (not values) and the affected table and row identifiers where possible. This supports investigations into BOLA/IDOR and Privilege Escalation findings reported by middleBrick.
// Service layer example with logging
import logger from '@ioc:Adonis/Core/Logger'
export class ProfileService {
public async updateProfile(userId: number, tenantId: string, data: any) {
logger.info({
event: 'profile.update',
tenantId,
userId,
table: 'profiles',
filter: { user_id: userId },
updateFields: Object.keys(data),
}, 'Updating profile')
const updated = await Database.from('profiles')
.where('user_id', userId)
.where('tenant_id', tenantId)
.update(data)
logger.info({
event: 'profile.update.complete',
tenantId,
userId,
rowsAffected: updated,
}, 'Profile update completed')
return updated
}
}
Compliance and operational considerations
Ensure logs do not contain sensitive data such as raw passwords, API keys, or PII. Use structured fields to enable correlation with Cockroachdb server logs and to feed monitoring systems. middleBrick’s findings related to Authentication, BOLA/IDOR, Data Exposure, and Input Validation can be prioritized using these logs to accelerate incident response and compliance audits.