HIGH missing tlsexpressfirestore

Missing Tls in Express with Firestore

Missing Tls in Express with Firestore — how this specific combination creates or exposes the vulnerability

When an Express service communicates with Google Cloud Firestore without enforcing Transport Layer Security (TLS), credentials and data can traverse the network in cleartext. This typically occurs when the Firestore client is initialized without explicit HTTPS enforcement or when the environment is misconfigured to allow plain HTTP endpoints. An attacker who can observe or inject traffic between the Express process and Firestore may capture service account keys, impersonate functions, or alter database responses.

Firestore requires secure connections for all operations, and the Node.js client library defaults to using TLS when connecting to googleapis.com. However, if a developer overrides the default host or uses a proxy/intercepting environment that does not present a valid certificate, requests may fall back to unencrypted channels. In a cloud environment, this can happen when custom endpoints are set via the FIRESTORE_EMULATOR_HOST environment variable or when an internal load balancer terminates TLS without enforcing it for upstream services.

An Express route that directly uses the Firestore SDK without validating connection security might look benign, but under specific network conditions it could transmit authentication material unencrypted. For example, an application that reads a document containing user PII and streams it through an unencrypted channel violates data exposure controls. middleBrick detects missing TLS as a distinct security check because it surfaces the risk even when the code appears correct, highlighting environmental misconfigurations rather than implementation bugs.

Compliance mappings are relevant here: missing TLS can breach controls in frameworks such as OWASP API Security Top 10 (2023) API4:2023 — Lack of Resources & Rate Limiting on the control side, and it intersects with data exposure and encryption checks required by PCI-DSS, SOC2, and GDPR. Continuous monitoring, such as that provided by the Pro plan, can alert teams when TLS enforcement drifts across environments.

Firestore-Specific Remediation in Express — concrete code fixes

Remediation centers on ensuring that all Firestore interactions occur exclusively over validated TLS channels and that the Express application does not inadvertently allow cleartext fallbacks. Below are concrete, working examples that demonstrate secure initialization and usage patterns.

Secure Firestore Initialization in Express

Initialize the Firestore client with strict host settings and without overrides that bypass TLS. Avoid using emulator variables in production, and if necessary, restrict their scope to development with explicit warnings.

const { initializeApp, cert } = require('firebase-admin');
const express = require('express');
const app = express();

initializeApp({
  credential: cert({
    projectId: process.env.GCP_PROJECT_ID,
    clientEmail: process.env.GCP_CLIENT_EMAIL,
    privateKey: process.env.GCP_PRIVATE_KEY.replace(/\\n/g, '\n'),
  }),
  databaseURL: `https://${process.env.GCP_PROJECT_ID}.firebaseio.com`,
});

const db = require('firebase-admin').firestore();

// Explicitly ensure TLS is used by not setting any custom host.
// Do not set FIRESTORE_EMULATOR_HOST in production.
if (process.env.NODE_ENV !== 'development') {
  delete process.env.FIRESTORE_EMULATOR_HOST;
}

Secured Express Route with Firestore Read

This route retrieves a document over a TLS-verified channel and ensures no cleartext exposure in error paths or logs.

app.get('/api/users/:id', async (req, res) => {
  try {
    const doc = await db.collection('users').doc(req.params.id).get();
    if (!doc.exists) {
      return res.status(404).json({ error: 'Not found' });
    }
    // Do not log sensitive fields; only safe metadata.
    res.json({ id: doc.id, data: doc.data() });
  } catch (err) {
    // Avoid exposing stack traces or internal details.
    console.error('Firestore read error:', err.message);
    res.status(500).json({ error: 'Internal server error' });
  }
});

Environment and Runtime Controls

Use runtime checks and deployment configurations to enforce TLS. For CI/CD, integrate the middleBrick CLI to scan endpoints and validate that no insecure configurations are present. In the Pro plan, continuous monitoring can alert on regressions such as accidental emulator activation in production.

# Verify environment before starting the service
if (process.env.NODE_ENV === 'production' && process.env.FIRESTORE_EMULATOR_HOST) {
  console.error('FATAL: FIRESTORE_EMULATOR_HOST is set in production. Aborting.');
  process.exit(1);
}

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT} with enforced TLS`);
});

These examples ensure that Firestore traffic remains encrypted in transit, aligning with security best practices and compliance requirements. The GitHub Action can be added to pipelines to block deployments that lack proper TLS configurations, and the Dashboard can track historical compliance of your API security posture.

Related CWEs: encryption

CWE IDNameSeverity
CWE-319Cleartext Transmission of Sensitive Information HIGH
CWE-295Improper Certificate Validation HIGH
CWE-326Inadequate Encryption Strength HIGH
CWE-327Use of a Broken or Risky Cryptographic Algorithm HIGH
CWE-328Use of Weak Hash HIGH
CWE-330Use of Insufficiently Random Values HIGH
CWE-338Use of Cryptographically Weak PRNG MEDIUM
CWE-693Protection Mechanism Failure MEDIUM
CWE-757Selection of Less-Secure Algorithm During Negotiation HIGH
CWE-261Weak Encoding for Password HIGH

Frequently Asked Questions

Can using a proxy or load balancer that terminates TLS still expose Firestore traffic to risk?
Yes, if the proxy does not enforce TLS for upstream connections to Firestore, traffic between the proxy and Firestore may be unencrypted. Ensure that the proxy is configured to use valid certificates and that the Firestore client is not inadvertently pointed to an HTTP endpoint.
How does middleBrick detect missing TLS in an Express + Firestore setup?
middleBrick runs black-box scans that inspect runtime behavior and configuration signals. It checks whether Firestore endpoints are served over valid TLS and flags missing enforcement, even when the code appears correct, by analyzing environment variables and observed network behavior during the scan.