HIGH token leakageadonisjsmongodb

Token Leakage in Adonisjs with Mongodb

Token Leakage in Adonisjs with Mongodb — how this specific combination creates or exposes the vulnerability

Token leakage occurs when authentication tokens are unintentionally exposed in logs, error messages, browser storage, or network traffic. In AdonisJS applications that use MongoDB as the primary data store, the risk is amplified when JSON Web Tokens (JWT) or session identifiers are mishandled alongside sensitive user documents stored in MongoDB collections.

AdonisJS typically manages authentication via packages such as @adonisjs/auth or jwt-simple. These packages generate tokens and attach them to the HTTP response, often within cookies or JSON bodies. If the application stores user roles, permissions, or session metadata directly in MongoDB and inadvertently includes sensitive fields in API responses, tokens or token-related data can be exposed.

For example, a user profile endpoint that retrieves a document from MongoDB may return the entire document, including fields such as authToken, refreshToken, or internal flags like isTokenRevoked. When these fields are present in API responses, clients such as browsers or mobile apps may store them insecurely, leading to leakage through logs, browser developer tools, or network interception.

Another scenario involves error handling. AdonisJS applications interacting with MongoDB may throw detailed database errors that include stack traces or query snippets. If a token is passed as part of a query or stored temporarily in a MongoDB document during debugging, these errors can reveal the token in plaintext.

The combination of AdonisJS middleware pipelines and MongoDB document structures requires careful control over what data is serialized and sent to the client. Without strict field filtering and secure session management, token leakage becomes a realistic threat vector, potentially leading to account compromise or privilege escalation.

Mongodb-Specific Remediation in Adonisjs — concrete code fixes

To prevent token leakage in AdonisJS applications using MongoDB, implement strict field selection, secure cookie attributes, and careful error handling. The following examples demonstrate concrete remediation steps.

1. Exclude sensitive fields from MongoDB responses

When querying MongoDB collections, explicitly select only the fields required for the response. Avoid returning entire documents when they contain authentication-related fields.

// User controller example using MongoDB via Lucid or raw driver
const User = use('App/Models/User')

async showProfile ({ request, response }) {
  const user = await User.query()
    .where('_id', request.$params.id)
    .select(['username', 'email', 'createdAt']) // Explicitly exclude tokens
    .first()

  return response.send(user)
}

2. Secure token storage and cookie configuration

Ensure tokens are stored in HTTP-only, Secure cookies with SameSite attributes. Avoid storing tokens in MongoDB fields that might be returned in API responses.

// Example using JWT and cookie configuration in AdonisJS
const { createJWT, getToken } = require('@adonisjs/framework/src/Helpers')

async login ({ request, response }) {
  const { email, password } = request.all()
  const user = await User.findBy('email', email)

  if (!user || !(await verifyPassword(password, user.password))) {
    return response.status(401).send({ error: 'Invalid credentials' })
  }

  const token = createJWT({ id: user._id }, { expiresIn: '2h' })

  response.cookie('auth_token', token, {
    httpOnly: true,
    secure: true,
    sameSite: 'strict',
    path: '/'
  })

  // Do not include token in response body
  return response.send({ message: 'Login successful' })
}

3. Sanitize error messages and avoid logging tokens

Ensure that MongoDB query errors do not expose sensitive data. Avoid logging full request or token information.

try {
  const result = await User.collection().findOne({ email: 'test@example.com' })
} catch (error) {
  // Log only error code, not the full error or any token
  logger.error('MongoDB query failed', { code: error.code })
  return response.status(500).send({ error: 'Internal server error' })
}

4. Use environment-based configuration for token handling

Configure token expiration and cookie settings based on environment variables to ensure consistency across development, staging, and production.

// .env file
NODE_ENV=production
JWT_SECRET=your_secure_secret
COOKIE_SECURE=true
// config/jwt.js
module.exports = {
  secret: process.env.JWT_SECRET,
  expiresIn: '1h',
  cookie: {
    secure: process.env.COOKIE_SECURE === 'true'
  }
}

Frequently Asked Questions

How can I verify that tokens are not being returned in API responses?
Use the middleBrick CLI to scan your endpoints and review the Data Exposure findings. For example, run middlebrick scan https://api.example.com/users and check whether any response includes authentication tokens in JSON or headers.
Does middleBrick test for token leakage in logged MongoDB errors?
middleBrick performs black-box scanning and does not inspect internal logging mechanisms. However, its error handling checks can identify verbose error messages that may expose sensitive data patterns, prompting you to review MongoDB error handling practices.