HIGH api key exposurehapifirestore

Api Key Exposure in Hapi with Firestore

Api Key Exposure in Hapi with Firestore — how this specific combination creates or exposes the vulnerability

When an API built with Hapi uses Google Cloud Firestore and handles API keys, improper server-side handling can lead to key exposure. A typical pattern is reading Firestore documents that contain service account keys or application-level API keys to authorize downstream services. If route handlers construct responses without carefully filtering sensitive fields, keys stored in Firestore may be returned to the client.

For example, a developer might store per-client secrets in a Firestore collection and retrieve them during request processing. If the document snapshot is serialized directly into the response using snapshot.data(), any field named apiKey or secret will be exposed. This becomes a server-side source-to-server credential leak, because the client receives a credential it should not possess.

Another common mistake is logging or echoing Firestore document contents in error messages. In Hapi, custom error handlers that include the full document payload can inadvertently surface API keys in server logs or crash reports. Even server-side code that passes Firestore data to other internal services must ensure keys are not passed through insecure channels or attached to outbound requests that an attacker could intercept.

Middleware that enforces authentication can also contribute to exposure if it reads API keys from Firestore and mistakenly attaches them to the request context in a way that downstream routes include them in JSON responses. Because Hapi allows attaching custom extensions to the request object, developers might store the entire Firestore document for convenience. Without explicit redaction, this makes it trivial for an attacker who gains access to a response to harvest embedded credentials.

Consider an endpoint that retrieves a Firestore document containing a Stripe key to perform payment operations. If the route handler returns the entire document to the frontend, the Stripe key is exposed. This is a server misconfiguration rather than a client-side issue; the fix is to ensure Firestore data is projected to only safe fields before serialization.

These risks are detectable by middleBrick’s checks for Data Exposure and Property Authorization. The tool correlates Firestore access patterns in the OpenAPI spec (if available) with runtime behavior to identify whether sensitive fields such as apiKey or secret can reach the HTTP response. By mapping document schemas to responses, it highlights where credential leakage is possible in the Hapi routes.

Firestore-Specific Remediation in Hapi

To prevent exposing API keys when using Firestore in Hapi, apply strict field selection and avoid returning raw documents. Use projection to retrieve only the fields you need, and redact sensitive values before attaching them to the request or response.

Example of unsafe code that returns a full Firestore document:

// Unsafe: exposes all fields including apiKey
server.route({
  method: 'GET',
  path: '/client-config',
  handler: async (request, h) => {
    const doc = await db.collection('clients').doc(request.query.id).get();
    if (!doc.exists) {
      throw Boom.notFound();
    }
    return doc.data(); // Dangerous: may include apiKey
  }
});

Safe alternative using explicit projection and redaction:

// Safe: returns only non-sensitive fields
server.route({
  method: 'GET',
  path: '/client-config',
  handler: async (request, h) => {
    const doc = await db.collection('clients').doc(request.query.id).get();
    if (!doc.exists) {
      throw Boom.notFound();
    }
    const data = doc.data();
    // Explicitly omit sensitive fields
    const { apiKey, secret, stripeKey, ...publicData } = data;
    return publicData;
  }
});

When you must use sensitive values internally, keep them in server memory and never attach them to the request extension that might be serialized. For example, store only the key identifier in request.extensions and fetch the actual key from a secure runtime secret manager when needed.

Additionally, configure Firestore security rules to enforce least-privilege access. Rules should restrict read access to documents containing keys and prevent listing operations that could enumerate sensitive documents. Combine this with application-level checks in Hapi to ensure the requesting context is authorized for the specific key being accessed.

For error handling, sanitize any Firestore document before including it in error responses or logs. Use a helper to strip sensitive fields:

function sanitizeFirestoreDoc(doc) {
  const data = doc.data();
  const { apiKey, secret, ...safe } = data;
  return safe;
}

middleBrick’s scans for Data Exposure and Property Authorization in this scenario will highlight routes where Firestore documents containing keys are returned without redaction. The tool maps these findings to OWASP API Top 10 and provides remediation guidance specific to Hapi and Firestore patterns.

Frequently Asked Questions

Can middleBrick detect Firestore API key exposure in Hapi routes?
Yes. middleBrick checks for Data Exposure and Property Authorization misconfigurations. It cross-references Firestore document definitions from OpenAPI specs with runtime behavior to identify whether sensitive fields such as apiKey or secret can appear in HTTP responses generated by Hapi handlers.
Does middleBrick fix the exposure of API keys in Firestore documents?
No. middleBrick detects and reports the exposure with severity, location, and remediation guidance. It does not modify code, block requests, or alter Firestore rules. Developers must apply field-level projections and redaction in Hapi to remediate.