HIGH ssrf server sideadonisjsmongodb

Ssrf Server Side in Adonisjs with Mongodb

Ssrf Server Side in Adonisjs with Mongodb — how this specific combination creates or exposes the vulnerability

Server-side request forgery (SSRF) in an AdonisJS application that uses MongoDB can arise when user-controlled data is used to drive HTTP requests or internal network calls, and those calls reach back-end services such as the MongoDB deployment or its administrative interfaces. In AdonisJS, routes, controllers, and jobs often perform outbound HTTP calls—commonly via third-party HTTP clients—without adequate validation of the target. If an endpoint accepts a URL or host parameter from the client and uses it to request metadata, configuration, or another service, an attacker can point the request to internal addresses like 127.0.0.1, 169.254.169.254 (cloud metadata), or internal MongoDB endpoints (e.g., mongodb://localhost:27017 or a MongoDB URI supplied via environment variables).

With MongoDB, risk increases when AdonisJS code resolves a user-provided hostname to a MongoDB connection string or passes a host/port into code that talks to the database. For example, if an AdonisJS controller uses a user-supplied hostname to fetch a remote file and then stores or logs data into MongoDB based on that response, SSRF can lead to unauthorized database discovery, connection to internal replica sets, or abuse of local MongoDB admin endpoints (if exposed). Attack patterns include probing internal infrastructure, bypassing network ACLs, and using SSRF as a pivot to reach MongoDB instances that do not accept external traffic. Because AdonisJS often relies on environment variables for MongoDB connection strings, a compromised or misleading internal endpoint can redirect connections or leak configuration details, effectively turning SSRF into a MongoDB exposure vector.

Metadata and internal endpoints are commonly targeted: cloud instance metadata services, local Redis or MongoDB instances, and internal load balancers. In an AdonisJS app, this typically occurs inside services or HTTP client wrappers where the destination is not strictly validated or restricted. Even seemingly benign features—such as fetching a webhook URL, pinging a health-check endpoint, or importing remote configuration—can become SSRF opportunities if the target is user-influenced. Because MongoDB deployments may be bound to localhost or internal networks, an SSRF that reaches 127.0.0.1:27017 can reveal server-side information or allow operations that would otherwise be blocked by network segregation.

To map this to the middleBrick scanning model, an unauthenticated scan that supplies a URL which triggers internal HTTP calls to MongoDB-related ports and metadata services can surface findings in multiple categories: Input Validation (type confusion, unexpected protocols), SSRF, BFLA/Privilege Escalation (if internal endpoints expose higher privileges), and Data Exposure (if database metadata or banner information is returned). The scanner does not need credentials to detect whether user-controlled inputs can reach internal services; it observes whether responses from internal endpoints are returned and categorizes the severity based on reachability and data sensitivity.

Developers should assume that any network path from the application to internal endpoints is reachable if user input can influence the destination. Mitigation requires strict allowlisting of protocols and hosts, removal of unnecessary metadata and internal service references from runtime data, and network-level protections that prevent internal services from being exposed to the application layer unless explicitly required.

Mongodb-Specific Remediation in Adonisjs — concrete code fixes

Remediation focuses on removing user influence over network destinations and hardening MongoDB connectivity in AdonisJS. Do not construct MongoDB connection strings or HTTP request targets from user input. If you must accept configuration from external sources, validate and sanitize strictly, and prefer referencing known, static endpoints via environment variables.

1) Validate and restrict outbound HTTP calls

Use an allowlist approach for protocols and hosts. Reject URLs with dangerous schemes and unexpected ports. Below is a safe AdonisJS controller pattern that validates the target before making an HTTP request:

import { schema } from '@ioc:Adonis/Core/Validator'
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
import { Http } from '@poppinss/utils'

export default class WebhookController {
  public async fetchConfig({ request, response }: HttpContextContract) {
    const bodySchema = schema.create({
      url: schema.string({}, [
        (value, _, options) => {
          const allowedProtocols = ['https:']
          const parsedUrl = new URL(value)
          if (!allowedProtocols.includes(parsedUrl.protocol)) {
            throw new Error('Only HTTPS protocol is allowed')
          }
          const allowedHosts = ['config.example.com']
          if (!allowedHosts.includes(parsedUrl.hostname)) {
            throw new Error('Hostname not allowed')
          }
          // reject common SSRF-prone patterns
          if (parsedUrl.hostname === 'localhost' || parsedUrl.hostname === '127.0.0.1') {
            throw new Error('Localhost is not allowed')
          }
        }),
      ]),
    })

    const payload = await request.validate({ schema: bodySchema })
    try {
      const resp = await Http.request(payload.url)
      response.send(resp)
    } catch (err) {
      response.status(500).send({ error: 'Failed to fetch' })
    }
  }
}

2) Use static, environment-backed MongoDB connections

Define the MongoDB connection string via environment variables and avoid any runtime concatenation with user data. In start/hash.ts or your database provider, rely on AdonisJS’s built-in config resolution:

// config/database.ts
import { DatabaseConfig } from '@ioc:Adonis/Addons/Lucid'

const dbConfig: DatabaseConfig = {
  connection: 'mongo',
  connections: {
    mongo: {
      client: 'MongoDB',
      connectionString: process.env.MONGODB_URI || 'mongodb://localhost:27017',
      // Prefer DNS seeds only if they resolve to controlled hosts
      // Avoid host:port overrides from user input
      database: process.env.MONGODB_DB || 'appdb',
      extra: {
        serverSelectionTimeoutMS: 5000,
        socketTimeoutMS: 10000,
      },
    },
  },
}
export default dbConfig

3) Reject or sanitize fields that may be interpreted as network locations

If your domain requires referencing external endpoints, store only allowed values and map them server-side. For instance, instead of accepting a mongoHost parameter, use an enum or lookup table:

const allowedEndpoints = {
  analytics: 'https://analytics.example.com',
  export: 'https://export.example.com',
}

export async function getEndpoint(key: string) {
  if (!(key in allowedEndpoints)) {
    throw new Error('Invalid endpoint key')
  }
  return allowedEndpoints[key]
}

4) Network-level protections

Ensure MongoDB is not bound to interfaces accessible from the application’s network zone unless required. Use firewall rules to restrict inbound traffic to MongoDB ports and avoid exposing admin interfaces on localhost if they are not meant for local-only use within the application runtime. In containerized environments, use network policies to prevent lateral movement.

5) Monitoring and detection

Instrument outbound calls to log target hosts and reject unexpected destinations in production. Combine this with periodic scans (using tools like middleBrick) that can detect whether user-influenced inputs can reach internal endpoints such as MongoDB ports or metadata services. The middleBrick CLI can be integrated into scripts to validate that no SSRF-prone paths remain in your API surface.

These steps reduce the likelihood that SSRF becomes a MongoDB exposure path and ensure that AdonisJS network interactions remain within explicitly defined boundaries.

Frequently Asked Questions

Can SSRF in AdonisJS lead to MongoDB compromise even if the database is bound to localhost?
Yes. If your application makes outbound requests to user-supplied targets and those requests resolve to 127.0.0.1 or internal hostnames, SSRF can reach MongoDB on localhost:27017. This can expose database metadata or enable operations against local instances, depending on network and authentication settings.
Does middleBrick detect SSRF that leads to MongoDB exposure?
middleBrick scans unauthenticated attack surfaces and can identify whether user-controlled inputs can reach internal endpoints, including MongoDB-related ports and metadata services. Findings include severity and remediation guidance, but note that middleBrick detects and reports—it does not fix or block.