HIGH api key exposurestrapimongodb

Api Key Exposure in Strapi with Mongodb

Api Key Exposure in Strapi with Mongodb — how this specific combination creates or exposes the vulnerability

When Strapi stores sensitive configuration such as API keys directly in its MongoDB collections, and those collections are inadvertently exposed through an unauthenticated or weakly authenticated endpoint, the keys can be disclosed. Strapi’s content types often include fields meant for internal use (for example, a JSON object or text field storing a third-party service token) that may be returned by default in REST or GraphQL responses if the controller or resolver does not explicitly exclude them. Because Strapi relies on the underlying MongoDB instance for persistence, misconfigured MongoDB access control or an exposed GraphQL endpoint can allow an unauthenticated attacker to read those documents via enumeration or IDOR-style queries, leading to API key exposure.

In this combination, the risk is amplified when developers use MongoDB to store Strapi environments or components that include connection strings or secrets, and the Strapi admin API or custom GraphQL endpoint does not enforce field-level authorization. For example, if a content type serviceConfig has a field apiKey, and the corresponding GraphQL query or REST route returns that field without filtering, an unauthenticated or low-privilege attacker can retrieve the key. This is a data exposure issue that maps to common compliance frameworks (e.g., OWASP API Top 10:2023 A05:2023 — Security Misconfiguration and Data Exposure), and it can lead to privilege escalation or unauthorized access to downstream services.

middleBrick’s 12 security checks run in parallel and include Data Exposure and Authentication checks that specifically test whether unauthenticated access to endpoints returns sensitive fields like API keys. The scanner also performs OpenAPI/Swagger spec analysis (2.0, 3.0, 3.1) with full $ref resolution, cross-referencing spec definitions with runtime findings to highlight unexpected data exposure in responses. If an endpoint returns a MongoDB-stored API key without proper authorization, the scan will flag it with severity and remediation guidance, helping you shift left before an attacker exploits the leak.

Mongodb-Specific Remediation in Strapi — concrete code fixes

To prevent API key exposure when using MongoDB with Strapi, apply field-level filtering in controllers and GraphQL resolvers, and ensure sensitive fields are excluded from responses. Below are concrete MongoDB-based examples for Strapi custom controllers and GraphQL resolvers that omit or redact sensitive values.

  • Strapi controller that queries MongoDB via Strapi’s entity service but excludes the apiKey field from the returned payload:
module.exports = {
  async find(ctx) {
    const { data, meta } = await strapi.entityService.findMany('api::service-config.service-config', {
      filters: ctx.request.query.filters,
      pagination: ctx.request.query.pagination,
      // Explicitly specify which fields to include/exclude at the query level
      fields: ['id', 'name', 'description'], // exclude 'apiKey' intentionally
    });
    return { data, meta };
  },
};
  • Custom GraphQL resolver that sanitizes MongoDB-stored config before returning it, removing the key:
const resolvers = {
  Query: {
    serviceConfigs: async (_, args, ctx) => {
      const configs = await strapi.db.query('api::service-config.service-config').findMany({
        where: {},
      });
      // Remove sensitive fields before sending response
      return configs.map(({ apiKey, ...safeConfig }) => safeConfig);
    },
  },
};
export default resolvers;
  • MongoDB connection strings and secrets stored as environment variables (not in MongoDB) and referenced in Strapi’s config to avoid persisting keys in the database:
// In .env
DATABASE_CLIENT=mongodb
MONGODB_URI=mongodb+srv://user:[email protected]/dbname
MONGODB_DATABASE=strapi

// In config/database.js
module.exports = ({
  connection: {
    client: 'mongodb',
    connection: {
      uri: process.env.MONGODB_URI,
    },
    debug: false,
  },
});

By ensuring that sensitive fields are never returned from endpoints, storing secrets outside MongoDB, and using Strapi’s query APIs to limit returned fields, you reduce the risk of API key exposure. middleBrick’s Pro plan supports continuous monitoring and can be integrated into CI/CD pipelines via the GitHub Action to fail builds if a scan detects exposed sensitive fields, helping enforce these safeguards automatically.

Frequently Asked Questions

How does middleBrick detect API key exposure in Strapi APIs backed by MongoDB?
middleBrick runs parallel checks including Data Exposure and Authentication. It performs unauthenticated scans, tests GraphQL and REST endpoints, and uses OpenAPI/Swagger spec analysis with full $ref resolution to compare expected schema behavior against runtime responses. If a response includes sensitive fields such as apiKey, database connection strings, or other secrets, it is flagged as a finding with severity and remediation guidance.
Can the GitHub Action fail a build if Strapi endpoints expose API keys stored in MongoDB?
Yes. With the Pro plan, you can configure the GitHub Action to fail builds when a scan detects exposed sensitive fields or when the risk score drops below your chosen threshold. This enforces continuous monitoring and prevents deployment of endpoints that might leak API keys from MongoDB-backed Strapi services.