mirror of
https://github.com/AikidoSec/safe-chain.git
synced 2026-05-26 12:10:49 +00:00
Escape special chars in shell scripts
This commit is contained in:
parent
04cb001006
commit
486a4b8f68
2 changed files with 18 additions and 3 deletions
|
|
@ -1,9 +1,15 @@
|
||||||
import { spawnSync, spawn } from "child_process";
|
import { spawnSync, spawn } from "child_process";
|
||||||
|
|
||||||
function escapeArg(arg) {
|
function escapeArg(arg) {
|
||||||
// If argument contains spaces or quotes, wrap in double quotes and escape double quotes
|
// Shell metacharacters that need escaping
|
||||||
if (arg.includes(" ") || arg.includes('"') || arg.includes("'")) {
|
// These characters have special meaning in shells and need to be quoted
|
||||||
return '"' + arg.replaceAll('"', '\\"') + '"';
|
const shellMetaChars = /[ "&'|;<>()$`\\!*?[\]{}~#]/;
|
||||||
|
|
||||||
|
// If argument contains shell metacharacters, wrap in double quotes
|
||||||
|
// and escape characters that are special even inside double quotes
|
||||||
|
if (shellMetaChars.test(arg)) {
|
||||||
|
// Inside double quotes, we need to escape: " $ ` \
|
||||||
|
return '"' + arg.replace(/(["`$\\])/g, '\\$1') + '"';
|
||||||
}
|
}
|
||||||
return arg;
|
return arg;
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -105,5 +105,14 @@ describe("safeSpawn", () => {
|
||||||
assert.strictEqual(spawnCalls[0].command, "npm install axios --save");
|
assert.strictEqual(spawnCalls[0].command, "npm install axios --save");
|
||||||
assert.strictEqual(spawnCalls[0].options.shell, true);
|
assert.strictEqual(spawnCalls[0].options.shell, true);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it(`should escape ampersand character (${variant})`, async () => {
|
||||||
|
await runSafeSpawn(variant, "npx", ["cypress", "run", "--env", "password=foo&bar"]);
|
||||||
|
|
||||||
|
assert.strictEqual(spawnCalls.length, 1);
|
||||||
|
// & should be escaped by wrapping the arg in quotes
|
||||||
|
assert.strictEqual(spawnCalls[0].command, 'npx cypress run --env "password=foo&bar"');
|
||||||
|
assert.strictEqual(spawnCalls[0].options.shell, true);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
Loading…
Add table
Add a link
Reference in a new issue