HIGH path traversalrestifyfirestore

Path Traversal in Restify with Firestore

Path Traversal in Restify with Firestore — how this specific combination creates or exposes the vulnerability

Path Traversal occurs when an API concatenates user-controlled input directly into file system or database paths without proper validation or normalization. In a Restify service that uses Cloud Firestore, this often manifests through document ID or collection name parameters supplied by the client. Because Firestore paths are hierarchical (e.g., users/{userId}/orders/{orderId}), unsanitized input can traverse beyond the intended scope, accessing or affecting data belonging to other users.

Consider a route defined as /users/:uid/profile. If the handler uses req.params.uid directly to build a Firestore path, an attacker supplying ../../../admin/settings can escape the intended user partition. While Firestore itself does not use a traditional file system, the resulting document path becomes users/../../../admin/settings (which Firestore resolves to users/admin/settings), potentially accessing administrative data if authorization checks are absent. This is a BOLA (Broken Level Access) / IDOR pattern and is one of the 12 checks middleBrick runs in parallel.

In a black-box scan, middleBrick submits unauthenticated requests to the Restify endpoint, observing whether different user contexts are reachable through manipulated path parameters. For example, an endpoint that returns a user profile might be tested with inputs like user1, user1%2F..%2Fuser2, and crafted sequences that attempt to ascend directories. If the API returns data with a 200 status for another user’s document, middleBrick flags this as a high-severity finding tied to BOLA/IDOR and references the OWASP API Top 10 and the principle of broken access control.

Additional risk occurs when collection or document names are derived from user input. If a route accepts a collection parameter and directly calls db.collection(req.query.collection), an input such as ../../secrets can shift the intended scope. Even though Firestore will normalize some path segments, missing server-side authorization allows an attacker to probe for sensitive collections. middleBrick’s LLM/AI Security checks do not apply here, but its standard authentication and property authorization tests will highlight missing constraints on path elements.

Because middleBrick performs no authentication by default, this unauthenticated attack surface is exactly what the scanner exercises. The tool does not fix the flaw; it detects the existence of path traversal patterns and provides remediation guidance, such as validating identifiers against a whitelist, using Firestore’s built-in security rules to enforce user ownership, and avoiding direct concatenation of client input into database paths.

Firestore-Specific Remediation in Restify — concrete code fixes

Remediation focuses on strict input validation, canonical path construction, and server-side enforcement. Below are concrete, realistic examples for a Restify handler using the Firebase Admin SDK.

1. Validate and sanitize parameters. Treat req.params and req.query as untrusted. Use a allowlist for document IDs and avoid using raw input in paths.

const { uid } = req.params;
// Allowlist validation: only alphanumeric and safe chars
if (!/^[a-zA-Z0-9_-]{1,30}$/.test(uid)) {
  throw new restify.InvalidArgumentError('Invalid user identifier');
}
const docRef = db.collection('users').doc(uid).collection('posts').doc(postId);

2. Use Firestore references instead of string concatenation. Construct paths programmatically to avoid injection-style traversal. Do not build a path string by joining segments that come from the client.

const userId = normalizeUserId(req.params.userId); // server-side normalization
const userRef = db.collection('users').doc(userId);
// Safe: explicitly define the subcollection
const targetRef = userRef.collection('orders').doc(orderId);
const snapshot = await targetRef.get();
if (!snapshot.exists) {
  throw new restify.NotFoundError('Resource not found');
}
return snapshot.data();

3. Enforce ownership via Firestore rules. Even when input is sanitized, ensure Firestore security rules require that the authenticated user can only access their own data. middleBrick’s findings often highlight missing rules that enable property authorization issues.

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{userId} {
      allow read, write: if request.auth != null && request.auth.uid == userId;
      match /posts/{post} {
        allow read, write: if request.auth != null && request.auth.uid == userId;
      }
    }
  }
}

4. Avoid exposing internal structure via error messages. Do not reveal whether a document exists or its path details in responses. Use generic messages and ensure Firestore exceptions are mapped to appropriate HTTP status codes without leaking stack traces or internal paths.

try {
  const doc = await targetRef.get();
  if (!doc.exists) {
    throw new restify.NotFoundError('Not found');
  }
} catch (err) {
  // Log the error internally with context, but return a generic response
  request.log.error({ err, userId, path: targetRef.path });
  throw new restify.InternalServerError('Request failed');
}

By combining these practices—strict allowlists, server-side reference building, and properly scoped Firestore rules—a Restify service using Firestore can mitigate path traversal and BOLA/IDOR risks. middleBrick’s dashboard can track your score over time, and the CLI allows you to integrate checks into scripts, while the Pro plan’s GitHub Action can gate merges if a scan drops below your chosen threshold.

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 path traversal in Restify with Firestore lead to unauthorized data access?
Yes. If user input is directly used to build Firestore document paths, an attacker can traverse beyond intended boundaries and access or modify data belonging to other users, often classified as BOLA/IDOR. Always validate and scope paths server-side and enforce ownership via Firestore rules.
How does middleBrick detect path traversal risks in a Restify + Firestore setup?
middleBrick runs unauthenticated black-box tests, sending crafted path parameters to your endpoints and observing whether data from unintended scopes is returned. It checks for missing authorization, improper input validation, and reports findings with severity and remediation guidance without performing any internal engine explanation.