Back to Blog
critical SEVERITY7 min read

How Path Traversal happens in Node.js Git Automation and how to fix it

A path traversal vulnerability in `index.js` allowed unsanitized repository names fetched from an external API to be used directly in filesystem operations and git submodule commands. Although `execFile()` with array arguments prevented shell injection, the raw `repoName` value could still escape the intended `libraries/` directory via crafted path segments. The fix adds strict regex validation to reject any repo name that doesn't conform to the expected `owner/repo` format before it ever touche

O
By Orbis AppSec
•Technically reviewed by Anupam Mediratta•Published August 26, 2026•Reviewed August 26, 2026

Answer Summary

This is a path traversal vulnerability (CWE-22) in a Node.js script (`index.js`) that processes GitHub repository names from an external API and uses them in `path.join()` and `git submodule add` filesystem operations without validation. An attacker who controls the API response could supply a crafted repo name like `../../../etc` to escape the intended `libraries/` directory. The fix adds a strict allowlist regex (`/^(?!\.{1,2}\/)(?!.*\/\.{1,2}$)[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+$/`) that validates the `owner/repo` format and explicitly blocks dot-segment traversal sequences before any filesystem or git operation is performed.

Vulnerability at a Glance

cweCWE-22
fixStrict allowlist regex validates `owner/repo` format and rejects dot-segment sequences before any filesystem operation
riskAttacker-controlled repo names can escape the intended directory, overwrite files, or corrupt the git repository
languageJavaScript (Node.js)
root causeExternal API-supplied `repoName` values used directly in `path.join()` and `execFile()` without format or traversal validation
vulnerabilityPath Traversal

The Problem With Trusting API Responses in File Paths

The index.js file in this private Node.js application automates the management of Git submodules by fetching repository names from an external API and using them to clone dependencies into a libraries/ directory. It's a common pattern in monorepo tooling — but a subtle flaw in how those repository names were consumed created a meaningful path traversal risk.

At line 40, the loop over uniqueRepoFullNames passed each repoName value directly into both path.join('libraries', repoName) and as a path argument to git submodule add — without ever checking whether the value looked like a legitimate owner/repo string. This is the textbook setup for CWE-22.


The Vulnerability Explained

Here is the vulnerable loop as it existed before the fix:

// BEFORE — vulnerable code
for (const repoName of uniqueRepoFullNames) {
  if (!fs.existsSync(path.join('libraries', repoName))) {
    console.log('Adding git submodule for', repoName);
    await execFile('git', ['submodule', 'add', '--depth', '1',
      `https://github.com/${repoName}.git`, repoName], {
      // ...
    });
  }
}

At first glance, using execFile() with an array of arguments looks safe — and for shell injection, it is. There's no shell interpreter involved, so a value like foo; rm -rf / won't execute arbitrary commands. However, execFile() does nothing to interpret or sanitize the content of the arguments it passes. The git binary receives exactly what you give it.

The real danger is in how repoName is used as a filesystem path:

  1. path.join('libraries', repoName) — Node's path.join resolves .. segments. A value like ../../../home/user/.ssh/authorized_keys would resolve to a path well outside the libraries/ directory.
  2. The final positional argument to git submodule add — This is the local path where git checks out the submodule. Supplying a traversal sequence here instructs git to write the submodule into an attacker-chosen directory.

Concrete Attack Scenario

Imagine the external API that populates uniqueRepoFullNames is compromised, returns a misconfigured response, or is under an attacker's control. It returns this value:

../../../.git/hooks/pre-commit

When the code runs:

path.join('libraries', '../../../.git/hooks/pre-commit')
// resolves to: '.git/hooks/pre-commit'

fs.existsSync checks whether .git/hooks/pre-commit exists. If it doesn't, the code proceeds to run:

git submodule add --depth 1 \
  https://github.com/../../../.git/hooks/pre-commit.git \
  ../../../.git/hooks/pre-commit

Git would attempt to clone an attacker-controlled repository into the .git/hooks/ directory — a location where git executes scripts automatically. This could result in arbitrary code execution on every subsequent git operation in the repository, affecting every developer who clones or pulls.

Even without reaching .git/hooks, an attacker could overwrite configuration files, inject malicious content into other submodules, or corrupt the repository state — all without shell injection.


The Fix

The fix adds a validation block at the very top of the loop, before any filesystem or process operation occurs:

// AFTER — patched code
for (const repoName of uniqueRepoFullNames) {
  if (
    typeof repoName !== 'string' ||
    !/^(?!\.{1,2}\/)(?!.*\/\.{1,2}$)[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+$/.test(repoName)
  ) {
    console.warn('Skipping invalid repo name:', repoName);
    continue;
  }
  if (!fs.existsSync(path.join('libraries', repoName))) {
    console.log('Adding git submodule for', repoName);
    await execFile('git', ['submodule', 'add', '--depth', '1',
      `https://github.com/${repoName}.git`, repoName], {
      // ...
    });
  }
}

Let's break down exactly what the regex enforces:

/^(?!\.{1,2}\/)(?!.*\/\.{1,2}$)[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+$/
Component What it does
^ Anchors to the start of the string
(?!\.{1,2}\/) Negative lookahead: rejects strings starting with ./ or ../
(?!.*\/\.{1,2}$) Negative lookahead: rejects strings ending with /. or /..
[a-zA-Z0-9_.-]+ Owner segment: only alphanumeric, underscore, dot, hyphen
\/ Exactly one forward slash separator
[a-zA-Z0-9_.-]+ Repo segment: same character class
$ Anchors to end of string

This is an allowlist approach — it defines precisely what a valid owner/repo string looks like and rejects everything else. The negative lookaheads add explicit defense against dot-segment traversal even within otherwise-valid characters.

The typeof repoName !== 'string' check at the start guards against non-string values (null, undefined, objects) that would cause path.join to throw or behave unexpectedly.

A value like ../../../.git/hooks/pre-commit fails the first negative lookahead immediately. A value like legitimate-org/../../secrets fails the character class check (the repeated slashes and dots don't form a valid single-slash owner/repo pattern). A value like valid-org/valid-repo passes all checks and proceeds normally.


Key Takeaways

  • execFile() with array arguments prevents shell injection, but not path traversal — both the argument structure and the argument content must be validated independently.
  • The repoName variable in index.js was the exact trust boundary that needed a gate — it crossed from external API data into filesystem operations without any validation checkpoint.
  • The negative lookaheads in the fix ((?!\.{1,2}\/)) are critical — a simpler character-class regex without them could still allow traversal sequences in edge cases.
  • Git submodule path arguments are especially dangerous — because git executes hooks from paths it manages, path traversal into .git/hooks/ can escalate directly to code execution.
  • Allowlist validation must happen before both fs.existsSync() and execFile() — the fix correctly places the check at the top of the loop, before either operation runs.

How Orbis AppSec Detected This

  • Source: repoName values sourced from uniqueRepoFullNames, populated by an external API response in index.js
  • Sink: path.join('libraries', repoName) at line 40 and the positional path argument in execFile('git', ['submodule', 'add', ..., repoName], ...) — both consuming the unsanitized external value
  • Missing control: No type check, no format validation, and no path boundary assertion before the value was used in filesystem and child process operations
  • CWE: CWE-22 — Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
  • Fix: A strict allowlist regex was inserted at the top of the loop to validate the owner/repo format and explicitly reject dot-segment traversal sequences, with a continue to skip invalid entries and a console.warn to surface them for monitoring

Orbis AppSec automatically detected this vulnerability and opened a pull request with the fix. Try Orbis AppSec on your repositories to find and fix issues like this automatically.


Conclusion

Path traversal vulnerabilities are easy to overlook precisely because the code around them often looks secure. In this case, the use of execFile() with array arguments was a correct and important security choice — but it addressed only half the problem. The repoName values flowing from an external API into path.join() and git's path argument represented an unguarded trust boundary.

The fix is elegant in its simplicity: a single regex validation block that enforces the known-good format of a GitHub repository name. It's a reminder that the most effective security controls are those applied closest to where untrusted data enters a sensitive operation — and that allowlist validation almost always beats blocklist approaches for path and identifier inputs.

If your Node.js tooling consumes external API data and uses it in filesystem paths, audit those data flows carefully. The gap between "prevents shell injection" and "prevents path traversal" is smaller than it looks, but the consequences of missing it can be severe.


Prevention and further reading

View the Security Fix

Check out the pull request that fixed this vulnerability

View PR #10

Related Articles

high

clean_path() Path Traversal: rel_path Escapes USERDATA Dir

A path traversal flaw in the `clean_path()` helper let a user-controlled `rel_path` value escape the intended USERDATA directory and reach arbitrary files on disk. The function joined path segments without checking the final result, so `../` sequences in route parameters or query strings could be used to read or write files outside the sandboxed storage area. The fix normalizes the path and verifies it still resolves inside the USERDATA root before returning it, raising an error otherwise.

critical

path.resolve() Path Traversal in Node CLI's Dynamic import()

A Node.js CLI script for validating expression definitions took a file path from `process.argv[2]`, resolved it with `path.resolve()`, and passed the result straight into a dynamic `import()` — with no check that the resolved path stayed inside the working directory. An attacker (or a malicious skill/plugin invocation) could supply traversal sequences to load and execute arbitrary `.js` files from anywhere on disk. The fix adds a boundary check with `path.relative()` and an extension allowlist b

high

bookDir() Path Traversal via Unsanitized bookId Parameter

The `bookDir()` function accepted unsanitized `bookId` values derived from user-created book titles, enabling path traversal attacks through `../` sequences. A fix was applied that validates the identifier using `path.basename()` and throws on mismatch, ensuring all resolved paths remain within `LIBRARY_DIR`.

high

Express `app.get('*')` Wildcard Handler Path Traversal in watch.js

A first-party Express server's wildcard route handler used `req.url.indexOf('font.woff2')` to gate access to a font file, allowing attackers to bypass the substring check with crafted paths. The fix replaces the catch-all handler with explicit route registration.

high

updateCardBg() Follows Unvalidated 302 Location Headers

A background-image updater fetched a configured image URL with manual redirect handling and then re-issued the request to whatever `Location` header came back, with no scheme or host checks. A redirect to `http://169.254.169.254/` or `http://127.0.0.1:<port>/` would have been followed with the original fetch options attached, and the response body written to disk as an image asset. The fix resolves the redirect target against `imgDownloadUrl` and rejects anything that is not HTTPS on the same ho

high

markitdown_bridge.py Path Traversal: Arbitrary File Read via sys.argv

The markitdown_bridge.py script, used by MDView for DOCX-to-Markdown conversion, accepted file paths directly from command-line arguments without validating they stayed within intended directories. An attacker could exploit this to read arbitrary files from the filesystem by passing path traversal sequences in the source_path parameter.