CRITICAL api key exposurefirestore

Api Key Exposure in Firestore

How API Key Exposure Manifests in Firestore

API key exposure in Firestore contexts occurs when Firebase configuration credentials—particularly the apiKey from a Firebase project's service account or web app configuration—are inadvertently made accessible to unauthorized clients. Unlike traditional API keys, Firebase's apiKey is used for client-side authentication with Identity Toolkit APIs (like sign-in) and is not inherently a secret, but it becomes critical when paired with other exposed credentials or misconfigured security rules.

Firestore-Specific Attack Patterns:

  • Client-Side Initialization Leakage: Developers often embed the entire Firebase configuration object (including apiKey, authDomain, projectId) in frontend JavaScript/HTML. If the Firestore security rules are permissive (e.g., allow read: if true;), an attacker can use this config to directly query the Firestore database via the client SDK or REST API, bypassing application logic.
  • Admin SDK in Client-Side Code: Accidentally bundling the Firebase Admin SDK (which uses service account credentials) in a frontend bundle exposes a highly privileged key. The Admin SDK bypasses Firestore security rules entirely, granting full read/write access to all collections.
  • REST API URL Construction: Hardcoding the apiKey in Firestore REST API calls (e.g., https://firestore.googleapis.com/v1/projects/{projectId}/databases/(default)/documents/...?key={exposedApiKey}) in client-side code or public repositories.
  • Misconfigured Security Rules with Identity Toolkit: If Firestore rules rely on request.auth.uid but the apiKey is exposed, attackers can create accounts via the exposed Identity Toolkit endpoints and then access data permitted by the rules.

Real Vulnerability Example: A React app initializes Firestore with:

const firebaseConfig = {
  apiKey: "AIzaSy...", // Exposed in source
  authDomain: "project.firebaseapp.com",
  projectId: "project",
  ...
};
firebase.initializeApp(firebaseConfig);
const db = firebase.firestore();

If firestore.rules contains match /public/{doc} { allow read: if true; }, any party with the config can read all public documents. Worse, if the Admin SDK is mistakenly included, full database access is compromised.

Firestore-Specific Detection

Detecting API key exposure in Firestore requires scanning both runtime responses and code artifacts for Firebase-specific patterns. middleBrick's scanner includes checks tailored to Firestore's ecosystem:

  • Configuration Leakage Scanning: middleBrick submits the target URL and analyzes responses for Firebase config objects (regex patterns for apiKey values starting with AIza alongside projectId or authDomain). It correlates these with Firestore database access patterns.
  • Security Rule Assessment: The scanner tests Firestore endpoints (like /v1/projects/{projectId}/databases/(default)/documents) with the discovered apiKey to evaluate rule permissiveness. A finding is triggered if unauthenticated read/write is possible.
  • SDK Misuse Detection: middleBrick identifies if the Admin SDK is referenced in client-side bundles (e.g., firebase-admin in browser builds) by scanning JavaScript files for require('firebase-admin') or import admin from 'firebase-admin'.
  • OpenAPI/Swagger Analysis: For APIs documenting Firestore integration, middleBrick resolves $ref in OpenAPI specs to find parameters named key, apiKey, or firebase_key that might be passed to Firestore REST endpoints.

Manual Detection Steps:

  1. Search code repositories for AIza (Firebase API key prefix) using git grep 'AIza'.
  2. Review Firestore security rules for overly permissive statements like allow read, write: if true; or if request.auth != null without proper validation.
  3. Inspect network traffic (browser DevTools) for Firestore REST calls containing key=AIza... in query parameters.

Using middleBrick: Run a scan via the web dashboard or CLI:

middlebrick scan https://your-api.com

The report will flag any Data Exposure findings related to Firebase credentials, with severity based on rule permissiveness and key privilege level. Pro plan users can enable continuous monitoring to detect new exposures in deployed APIs.

Firestore-Specific Remediation

Remediation focuses on eliminating exposure and enforcing least-privilege access using Firestore's native features:

  • Remove Client-Side Admin SDK: Ensure firebase-admin is only used in server-side environments (Cloud Functions, backend servers). In package.json, mark it as a dependency (not devDependency) and verify bundlers exclude it from frontend builds.
  • Secure Firebase Configuration: Do not rely on apiKey secrecy. Instead, enforce strict Firestore security rules and use Firebase App Check to prevent unauthorized clients. Never commit config files; use environment variables in CI/CD.
  • Harden Firestore Security Rules: Replace permissive rules with attribute-based access control. Example of a vulnerable rule set and a fixed version:
Vulnerable RulesRemediated Rules
rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if true;
    }
  }
}
rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    // Only allow authenticated users to read their own data
    match /users/{userId} {
      allow read, write: if request.auth != null && request.auth.uid == userId;
    }
    // Public read for specific collection
    match /public/{docId} {
      allow read: if true;
      allow write: if false;
    }
  }
}
  • Enable Firebase App Check: Register your app with App Check to ensure only your authentic apps can access Firestore. This mitigates exposure even if config is leaked. Integrate via SDK:
// Initialize App Check
import { initializeApp } from 'firebase/app';
import { initializeAppCheck, ReCaptchaV3Provider } from 'firebase/app-check';

const app = initializeApp(firebaseConfig);
const appCheck = initializeAppCheck(app, {
  provider: new ReCaptchaV3Provider('your-recaptcha-key'),
  isTokenAutoRefreshEnabled: true
});
  • Rotate Exposed Keys: If an apiKey is exposed, rotate it in the Google Cloud Console (APIs & Services > Credentials). Note: Rotating the apiKey does not affect Firestore rules but prevents misuse of Identity Toolkit APIs.
  • Use Backend Proxies for Sensitive Operations: For admin-level Firestore access, create a backend endpoint (e.g., Cloud Function) that uses the Admin SDK, and have the frontend call this endpoint with a custom token or session cookie. Never expose Admin SDK to clients.

Verification: After fixes, rescan with middleBrick to confirm the Data Exposure finding is resolved. Ensure the scanner cannot retrieve data via Firestore endpoints without proper authentication.

Frequently Asked Questions

Can middleBrick detect Firestore security rule misconfigurations?
Yes. middleBrick tests Firestore database endpoints using discovered credentials (like apiKey) to evaluate if rules allow unauthorized access. It reports 'Data Exposure' findings with rule excerpts and severity based on the data sensitivity.
What if I'm using Firestore with a custom backend—does middleBrick still scan for key exposure?
middleBrick scans the provided API endpoint for any leakage of Firebase configuration (apiKey, projectId) in responses or code. If your backend proxies Firestore access but accidentally echoes Firebase config in errors or documentation, middleBrick will detect and report it as a 'Data Exposure' risk.