HIGH command injectionfiberfirestore

Command Injection in Fiber with Firestore

Command Injection in Fiber with Firestore — how this specific combination creates or exposes the vulnerability

Command Injection occurs when untrusted input is passed to a system command without validation or sanitization. In a Fiber application that interacts with Google Firestore, this risk typically arises when dynamic values derived from HTTP requests (e.g., query parameters, headers, or body fields) are used to construct shell commands that include Firestore data such as document IDs, collection names, or field values.

Consider a scenario where an endpoint retrieves a Firestore document based on a user-supplied ID and then passes that ID to a shell command for logging or external processing. If the ID contains shell metacharacters (e.g., ; & | $ ( )), an attacker can inject additional commands. For example, a document ID like doc1; cat /etc/passwd could lead to unintended command execution. Even when Firestore data is not directly sourced from user input, indirect paths—such as an attacker first writing a malicious document ID via a less-restricted API—can set up the injection chain.

Because middleBrick scans unauthenticated attack surfaces, it can detect endpoints that accept input used in command construction and then later used in shell invocations, even if Firestore is involved. The scanner checks for unsafe consumption patterns and input validation weaknesses across the 12 checks, including Unsafe Consumption and Input Validation. While Firestore itself does not execute shell commands, the integration point in your Fiber code where Firestore data meets system command construction is where the vulnerability exists.

Real-world examples include using exec or child_process to call utilities that incorporate Firestore document IDs or collection paths. If those values are not strictly validated, escaped, or sandboxed, the boundary between data and command syntax breaks. This is especially risky when the command is built using string concatenation rather than structured, argument-list APIs. middleBrick’s checks for SSRF and Property Authorization also help surface related risks where external requests or role assumptions might further expose document identifiers to misuse.

To illustrate, a vulnerable Fiber route might look like this in JavaScript, where a document ID from the request is used unsafely:

const { exec } = require('child_process');
const { getFirestore, doc, getDoc } = require('firebase/firestore');

const db = getFirestore();

app.get('/log/:docId', async (c) => {
  const docId = c.req.param('docId');
  const docRef = doc(db, 'events', docId);
  const snapshot = await getDoc(docRef);
  if (snapshot.exists()) {
    const data = snapshot.data();
    // Unsafe: docId used directly in shell command
    exec(`echo "Processed ${data.timestamp}" >> /logs/${docId}`, (err) => {
      if (err) console.error(err);
    });
    return c.json({ status: 'logged' });
  }
  return c.json({ error: 'not found' }, 404);
});

In this example, docId originates from the route parameter, is used to read a Firestore document, and then flows into an exec call. An attacker can supply docId as abc; rm -rf /, leading to command injection. Even if the document exists, the injected command executes in the shell. middleBrick would flag the lack of input validation and unsafe consumption in this flow.

Firestore-Specific Remediation in Fiber — concrete code fixes

Remediation focuses on preventing untrusted input from reaching shell commands and ensuring Firestore interactions remain isolated from command construction. The safest approach is to avoid invoking shell commands with any data derived from requests or Firestore documents. When external tooling is required, use strict allowlists, structured APIs, and isolated execution contexts.

First, validate and sanitize all inputs that could influence command construction. For identifiers such as document IDs, enforce a strict pattern (e.g., alphanumeric and limited length) using Fiber middleware or route-level validation. Reject any input containing shell metacharacters.

Second, avoid passing dynamic values into shell commands. If you must log or process data externally, retrieve the Firestore document first, then pass only safe, sanitized values through environment variables or configuration—not through direct string interpolation. Prefer structured logging over shell commands.

Third, when shell invocation is unavoidable, use argument arrays instead of string concatenation to prevent argument splitting and injection. However, the best practice is to avoid exec and similar functions entirely for request-driven workloads.

Below are concrete, secure code examples for Fiber with Firestore that demonstrate safe handling:

const { execFile } = require('child_process');
const { getFirestore, doc, getDoc } = require('firebase/firestore');

const db = getFirestore();

// Safe: strict validation, no shell injection path
app.get('/log/:docId', async (c) => {
  const docId = c.req.param('docId');

  // Allowlist validation: only alphanumeric and underscores, 1–64 chars
  if (!/^[a-zA-Z0-9_]{1,64}$/.test(docId)) {
    return c.json({ error: 'invalid document ID' }, 400);
  }

  const docRef = doc(db, 'events', docId);
  const snapshot = await getDoc(docRef);
  if (snapshot.exists()) {
    const data = snapshot.data();
    // Safe: use execFile with fixed arguments, no shell interpolation
    execFile('echo', [`Processed ${data.timestamp}`], (err, stdout, stderr) => {
      if (err) console.error(err);
    });
    return c.json({ status: 'logged' });
  }
  return c.json({ error: 'not found' }, 404);
});

In this revised route, input validation ensures docId conforms to a safe pattern. The use of execFile with an argument array prevents the shell from interpreting metacharacters. Even if the Firestore document contains dynamic content, it is passed as a discrete argument rather than interpolated into a command string.

For operations that historically relied on shell commands, consider moving logic into Node.js or serverless functions that interact with Firestore directly. middleBrick’s checks for Input Validation and Unsafe Consumption will highlight remaining risks, while its scans for LLM Security are unaffected by this backend context. Products such as the middleBrick CLI (middlebrick scan <url>) and GitHub Action can help you verify that these patterns are correctly implemented in your CI/CD pipeline.

Related CWEs: inputValidation

CWE IDNameSeverity
CWE-20Improper Input Validation HIGH
CWE-22Path Traversal HIGH
CWE-74Injection CRITICAL
CWE-77Command Injection CRITICAL
CWE-78OS Command Injection CRITICAL
CWE-79Cross-site Scripting (XSS) HIGH
CWE-89SQL Injection CRITICAL
CWE-90LDAP Injection HIGH
CWE-91XML Injection HIGH
CWE-94Code Injection CRITICAL

Frequently Asked Questions

Can command injection occur if Firestore data is used only in backend logging and not directly in user-facing output?
Yes. Even if Firestore data is used only in server-side logging or external commands, unsanitized document IDs or field values can lead to command injection when those values are passed to shell utilities. The risk is in the combination of untrusted data and shell execution, not in user-facing output.
Does middleBrick test for command injection in integrations with databases like Firestore?
middleBrick tests the unauthenticated attack surface of your API endpoints and looks for input validation weaknesses and unsafe consumption patterns that could lead to command injection, regardless of the backend store. If Firestore data influences command construction, the relevant checks will flag the missing validation or unsafe usage.