HIGH path traversalexpresscockroachdb

Path Traversal in Express with Cockroachdb

Path Traversal in Express with Cockroachdb — how this specific combination creates or exposes the vulnerability

Path Traversal occurs when an application uses attacker-controlled data to access files outside the intended directory. In an Express API that uses Cockroachdb, the risk typically arises not from Cockroachdb itself, but from how file-system operations are composed with database queries and user input. If an endpoint builds a filesystem path using values taken from request parameters or headers, and then uses a Cockroachdb query to retrieve or log information about that path, the application may expose internal files or allow unauthorized file access.

For example, an endpoint designed to fetch logs stored on disk might accept a logId parameter, look up metadata in Cockroachdb, and then open a file based on the returned path. If the database value is not strictly validated and is directly concatenated into a filesystem path, an attacker can supply crafted input such as ../../../etc/passwd to traverse directories. Cockroachdb does not introduce path traversal, but if the application uses database fields to construct filesystem paths without normalization and strict allowlisting, the combined behavior increases the attack surface.

Another scenario involves dynamic configuration or asset loading: an Express route might read a document name from a request, query Cockroachdb to verify permissions, and then serve the file from disk. If the route trusts the document name returned by the database and uses it in functions like fs.readFile without resolving against a base directory, an attacker who can influence database content (for instance, via compromised admin workflows or injection within application logic) can indirectly cause path traversal. Even when authentication is bypassed via unauthenticated attack surface scanning, such misconfigurations can be detected because the endpoint exposes directory traversal patterns in its behavior.

Because middleBrick scans test the unauthenticated attack surface and run checks such as Input Validation and Property Authorization in parallel, it can identify endpoints where file-system interactions are not properly constrained. Findings may highlight routes where user-supplied data influences filesystem operations and where database fields are used without canonicalization. These findings map to OWASP API Top 10:2023 A01 (Broken Object Level Authorization) and A05 (Security Misconfiguration), and can be relevant for compliance frameworks such as PCI-DSS and SOC2 when sensitive files are at risk.

Cockroachdb-Specific Remediation in Express — concrete code fixes

To prevent path traversal when Express interacts with Cockroachdb, validate and sanitize all inputs and never construct filesystem paths using raw database values. Use a strict allowlist for file identifiers, resolve paths against a configured base directory, and avoid passing raw filenames from the database to filesystem APIs.

Secure Express route example with Cockroachdb

The following example shows an Express route that retrieves a document record from Cockroachdb and safely serves a related file. It uses parameterized queries to prevent SQL injection, validates the document identifier, and ensures filesystem operations are confined to a controlled directory.

const express = require('express');
const { Pool } = require('pg');
const fs = require('fs');
const path = require('path');

const app = express();
const pool = new Pool({
  connectionString: process.env.DATABASE_URL,
});

const BASE_DIR = path.resolve(__dirname, 'safe-docs');

app.get('/documents/:docId', async (req, res) => {
  const docId = req.params.docId;

  // Validate docId format: only allow alphanumeric and underscores
  if (!/^\w+$/.test(docId)) {
    return res.status(400).send('Invalid document identifier');
  }

  let client;
  try {
    client = await pool.connect();
    const query = 'SELECT filename, owner_id FROM documents WHERE id = $1';
    const result = await client.query(query, [docId]);

    if (result.rows.length === 0) {
      return res.status(404).send('Not found');
    }

    const row = result.rows[0];
    // Canonicalize and restrict to base directory
    const safeFilename = path.basename(row.filename);
    const filePath = path.join(BASE_DIR, safeFilename);

    // Ensure the resolved path is within BASE_DIR
    if (!filePath.startsWith(BASE_DIR)) {
      return res.status(403).send('Forbidden path');
    }

    fs.access(filePath, fs.constants.R_OK, (err) => {
      if (err) {
        return res.status(404).send('File not accessible');
      }
      res.sendFile(filePath, (sendErr) => {
        if (sendErr) {
          res.status(500).send('Error serving file');
        }
      });
    });
  } catch (err) {
    console.error(err);
    res.status(500).send('Internal error');
  } finally {
    if (client) {
      client.release();
    }
  }
});

app.listen(3000, () => console.log('Server running on port 3000'));

Key practices applied:

  • Input validation: restrict docId to a safe pattern before using it in SQL.
  • Parameterized queries: use $1 placeholders with the Cockroachdb driver to prevent injection.
  • Filesystem safety: use path.basename to strip directory components from the filename stored in Cockroachdb, and join with a fixed base directory.
  • Path canonicalization: verify that the final resolved path starts with the allowed base directory to prevent traversal via malicious filenames stored in the database.

middleBrick can detect missing validations and risky compositions between database-derived values and filesystem operations. With the Pro plan, continuous monitoring can be enabled to alert when new endpoints introduce file-access patterns that resemble traversal risks, and the GitHub Action can fail builds if submitted URLs exhibit such patterns during CI/CD scans.

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 Cockroachdb queries themselves be exploited for path traversal?
Cockroachdb does not perform filesystem operations, so it cannot directly cause path traversal. The risk arises when application code uses database values to construct filesystem paths without validation. Use parameterized queries and avoid concatenating database fields into paths.
How does middleBrick detect path traversal risks in Express APIs using Cockroachdb?
middleBrick runs unauthenticated black-box scans with checks such as Input Validation and Property Authorization. It identifies endpoints where user-controlled data influences filesystem behavior and highlights findings that align with OWASP API Top 10 and compliance mappings, without modifying or blocking any system.