Excessive Data Exposure in Adonisjs with Mongodb
Excessive Data Exposure in Adonisjs with Mongodb — how this specific combination creates or exposes the vulnerability
Excessive Data Exposure occurs when an API returns more data than necessary for a given operation, often including sensitive fields that should remain restricted. In an Adonisjs application using Mongodb as the backend, this commonly arises from loosely defined query projections, implicit model serialization, or unchecked aggregation pipelines. Because Adonisjs typically relies on Lucid ORM patterns and custom transformers, developers may inadvertently return entire Mongodb documents—including fields such as password hashes, internal IDs, audit metadata, or PII—when only a subset is intended for the client.
With Mongodb, the schema-less nature of collections can amplify this risk. A query that fetches user documents may return fields like password, resetToken, permissions, or version vectors that are meaningful server-side but should never leave the service. If route handlers or controller methods do not explicitly limit the returned fields, the full document is serialized to JSON and sent over the network. Similarly, aggregation pipelines that $lookup related collections can unintentionally surface sensitive fields from joined documents unless stages explicitly prune or reshape the output.
The risk is compounded when responses are consumed by frontend clients or third party integrations that assume a minimal shape. Attackers can leverage this exposure for further exploitation—enumerating usernames, inferring internal object IDs, or discovering deprecated fields that may indicate older, vulnerable code paths. Because the API remains unauthenticated in many endpoints (as tested by middleBrick’s black-box scans), excessive data exposure can be discovered quickly through automated probes that request resources and inspect the completeness of returned fields.
middleBrick’s LLM/AI Security checks highlight this concern by detecting system prompt leakage and output anomalies, but for API-specific risks, the scanner’s 12 parallel checks—including Property Authorization and Data Exposure—evaluate whether responses contain unnecessary data. By correlating OpenAPI/Swagger specs with runtime behavior, middleBrick can identify mismatches between documented contracts and actual payloads, ensuring that responses adhere strictly to intended schemas without revealing sensitive or extraneous fields.
Mongodb-Specific Remediation in Adonisjs — concrete code fixes
To mitigate Excessive Data Exposure in Adonisjs with Mongodb, explicitly define projection shapes in queries and avoid relying on default model serialization. Use field selection to include only required keys, and apply consistent transformation layers to enforce a safe output contract.
1. Project only necessary fields in Mongodb queries
When fetching documents, specify a projection that includes only required fields. In Adonisjs with the Mongodb driver, this is done by passing a projection object to the query builder.
import { User } from 'App/Models/User'
// Explicitly include only safe fields
const users = await User.query()
.project({
email: 1,
username: 1,
createdAt: 1,
_id: 0 // exclude internal IDs if not needed
})
.exec()
2. Use transformers to control serialization
Define a transformer that maps the minimal safe shape to the response. This ensures that even if the Mongodb document contains extra fields, only intended properties are serialized.
import { DateTime } from 'luxon'
import { BaseSerializer } from '@ioc:Adonisjs/Addons/LucidExtras'
export default class UserSerializer extends BaseSerializer {
public serialize() {
return {
id: this.resource.id,
email: this.resource.email,
username: this.resource.username,
createdAt: DateTime.fromJSDate(this.resource.createdAt).toISO()
}
}
}
Then apply the serializer in the controller:
import UserSerializer from 'App/Serializers/UserSerializer'
import User from 'App/Models/User'
export class UserController {
public async show({ params }) {
const user = await User.findOrFail(params.id)
return this.serialize(new UserSerializer(user))
}
}
3. Prune sensitive fields in aggregation pipelines
If using aggregation to join or reshape data, explicitly exclude sensitive fields at each stage.
import { User } from 'App/Models/User'
const result = await User.query()
.aggregate()
.lookup({
from: 'profiles',
localField: 'profileId',
foreignField: '_id',
as: 'profile'
})
.unwind('profile')
.project({
email: 1,
username: 1,
'profile.bio': 1,
'profile.avatarUrl': 1,
password: 0,
resetToken: 0,
__v: 0
})
.exec()
4. Validate and sanitize inputs to prevent injection-driven data leakage
Ensure that user-controlled parameters used in queries are validated to avoid injection that could alter projection behavior.
import { schema } from '@ioc:Adonisjs/Core/Validator'
const userQuerySchema = schema.create({
email: schema.string.optional([ rules.normalizeEmail() ])
})
export async function getUserByEmail(ctx) {
const payload = await ctx.validate(userQuerySchema)
const user = await User.query()
.where(payload.email ? { email: payload.email } : {})
.project({ email: 1, username: 1 })
.firstOrFail()
return user
}
By combining explicit projections, robust transformers, and careful aggregation design, Adonisjs applications can effectively limit data exposure while maintaining flexibility with Mongodb’s document model. These practices align with the Property Authorization checks performed by middleBrick, which verify that responses contain only authorized and necessary fields.
Related CWEs: propertyAuthorization
| CWE ID | Name | Severity |
|---|---|---|
| CWE-915 | Mass Assignment | HIGH |