HIGH integrity failuresfiberfirestore

Integrity Failures in Fiber with Firestore

Integrity Failures in Fiber with Firestore — how this specific combination creates or exposes the vulnerability

An integrity failure occurs when an application fails to preserve the accuracy and completeness of data over its entire lifecycle. In a Fiber application that uses Google Firestore as a backend, this typically manifests when data writes or updates do not enforce strict validation, leading to records that contradict business rules or expected relationships. Firestore’s flexible schema and client-side writes can amplify these risks when the server-side logic in Fiber does not rigorously validate every incoming request.

Consider a financial ledger API built with Fiber where each transaction document in Firestore must preserve the consistency of account balances. If the endpoint that creates a transaction only applies the incoming delta without re-reading and verifying the current balance, an attacker can submit multiple concurrent requests that each use the same stale balance. Because Firestore does not enforce server-side atomic constraints by default on simple updates, the final balance can become inconsistent—this is a classic BOLA/IDOR and data integrity issue. The scan may flag this as a finding under Data Exposure and Property Authorization because the operation does not prove that the resulting state is correct.

Another scenario involves document references and subcollections where referential integrity is assumed but not enforced. A Fiber route might accept a JSON payload that includes a Firestore document path for a parent entity, but if the route does not verify that the referenced document exists and belongs to the expected tenant or context, an attacker can supply paths pointing to other users’ data. Because Firestore returns the referenced data when rules permit, the Fiber handler may inadvertently incorporate unauthorized data into writes, creating integrity violations across aggregates. This pattern is often highlighted in the Inventory Management and Property Authorization checks of middleBrick, which cross-reference the OpenAPI spec’s parameter definitions with runtime behavior to detect missing ownership checks.

Middleware that deserializes JSON directly into Firestore document updates without whitelisting fields can also introduce integrity failures. Malicious clients might inject fields that affect server-side calculations, such as setting an administrative override flag or tampering with version numbers used for optimistic concurrency. If the Fiber handler does not strip or validate these fields, Firestore will persist them, and subsequent reads may produce incorrect results or bypass intended controls. middleBrick’s Input Validation and Unsafe Consumption checks are designed to surface these risks by analyzing the spec and contrasting it with observed payload handling.

LLM/AI Security checks are particularly relevant when endpoints expose generated summaries or instructions that are stored back into Firestore. System prompt leakage patterns or prompt injection probes can reveal whether attacker-influenced content is being persisted and later rendered to other users, compounding integrity failures with confidentiality issues. The scanner’s 27 regex patterns for chat formats and its active probes for data exfiltration help identify such cross-context contamination early.

Finally, Rate Limiting checks highlight how missing request throttling can enable integrity abuse through rapid, low-volume attacks. An endpoint that applies updates without sufficient controls may allow an attacker to flood Firestore with small, seemingly valid changes that collectively corrupt aggregate values. By correlating the OpenAPI spec’s operation definitions with runtime tests, middleBrick can identify missing rate controls that would otherwise allow integrity degradations to proceed unnoticed.

Firestore-Specific Remediation in Fiber — concrete code fixes

Remediation focuses on ensuring that every write to Firestore is validated, atomic where needed, and scoped to the correct tenant and context. Below are Fiber handler examples that incorporate strong integrity controls.

Atomic balance update with transaction

Use a Firestore transaction to re-read the account document, verify constraints, and apply the delta. This prevents concurrent updates from using stale data.

const fiber = require('fiber');
const { initializeApp } = require('firebase-admin/app');
const { getFirestore, runTransaction } = require('firebase-admin/firestore');

initializeApp();
const db = getFirestore();

const app = fiber();
app.post('/transaction', async (req, res) => {
  const { accountId, deltaCents } = req.body;
  if (typeof deltaCents !== 'number' || deltaCents === 0) {
    return res.status(400).send({ error: 'Invalid delta' });
  }
  const accountRef = db.collection('accounts').doc(accountId);
  try {
    await runTransaction(db, async (transaction) => {
      const snap = await transaction.get(accountRef);
      if (!snap.exists) {
        throw new Error('Account not found');
      }
      const data = snap.data();
      const newBalance = (data.balanceCents || 0) + deltaCents;
      if (newBalance < 0) {
        throw new Error('Insufficient funds');
      }
      transaction.update(accountRef, { balanceCents: newBalance });
    });
    res.send({ ok: true });
  } catch (err) {
    res.status(409).send({ error: err.message });
  }
});

Validate and scope document references

When a request includes a reference to another document, resolve it within the same transaction and confirm ownership against the request context.

app.post('/record-entry', async (req, res) => {
  const { ledgerRefPath, amount } = req.body;
  const tenantId = req.tenantId; // from auth context
  // Validate path format before using
  if (!ledgerRefPath || !ledgerRefPath.startsWith(`tenants/${tenantId}/ledgers/`)) {
    return res.status(400).send({ error: 'Invalid reference' });
  }
  const ledgerRef = db.doc(ledgerRefPath);
  try {
    await runTransaction(db, async (transaction) => {
      const ledger = await transaction.get(ledgerRef);
      if (!ledger.exists) {
        throw new Error('Ledger not found');
      }
      const entriesRef = ledgerRef.collection('entries').doc();
      transaction.set(entriesRef, { amount, createdAt: new Date() });
      // Update aggregate within same transaction
      transaction.update(ledgerRef, { totalAmount: FieldValue.increment(amount) });
    });
    res.send({ ok: true });
  } catch (err) {
    res.status(409).send({ error: err.message });
  }
});

Whitelist update fields and reject unknown keys

Do not forward raw request bodies to Firestore. Explicitly pick allowed fields and ensure metadata like version or flags are validated.

app.put('/profile/:profileId', async (req, res) => {
  const profileId = req.params.profileId;
  const tenantId = req.tenantId;
  const { displayName, theme } = req.body;
  // Strict validation
  if (typeof displayName !== 'string' || displayName.length > 100) {
    return res.status(400).send({ error: 'Invalid displayName' });
  }
  if (typeof theme !== 'string' || !['light', 'dark'].includes(theme)) {
    return res.status(400).send({ error: 'Invalid theme' });
  }
  const profileRef = db.collection('profiles').doc(profileId);
  await runTransaction(db, async (transaction) => {
    const snap = await transaction.get(profileRef);
    if (!snap.exists) {
      throw new Error('Profile not found');
    }
    // Ensure the profile belongs to the tenant
    if ((snap.data().tenantId || '') !== tenantId) {
      throw new Error('Forbidden');
    }
    transaction.update(profileRef, { displayName, theme, updatedAt: new Date() });
  });
  res.send({ ok: true });
});

Use Firestore server-side features where possible, such as security rules for basic existence checks, but do not rely on rules alone for integrity. Combine rules with server-side validation in Fiber as shown above. middleBrick’s Pro plan supports continuous monitoring and CI/CD integration, which can help detect regressions in these validation patterns before they reach production.

Frequently Asked Questions

Why does Firestore not prevent integrity failures by itself?
Firestore provides flexible schemas and client-driven writes; it does not enforce business rules or atomic constraints across documents by default. Integrity must be implemented in application logic, such as in Fiber handlers, using transactions, strict validation, and ownership checks.
Can middleBrick detect integrity issues in Firestore-backed Fiber APIs?
Yes. middleBrick scans the OpenAPI/Swagger spec and runs parallel checks including Data Exposure, Property Authorization, and Input Validation. It cross-references the spec with runtime tests to identify missing validation, insufficient scoping, and unsafe update patterns that can lead to integrity failures.