Skip to content
Merged
88 changes: 85 additions & 3 deletions scripts/hooks/gateguard-fact-force.js
Original file line number Diff line number Diff line change
Expand Up @@ -375,6 +375,86 @@ function commandBasename(token) {
.toLowerCase();
}

/**
* Command words that run ANOTHER command: the destructive check has to look
* past them, or the most dangerous spellings are the ones that slip through.
* Every token-based detector keys on `tokens[0]`, so `sudo rm -rf /` reads as
* an invocation of `sudo` and is allowed while the bare `rm -rf /` is denied.
*/
const COMMAND_WRAPPERS = new Set([
'sudo',
'doas',
'env',
'command',
'nohup',
'setsid',
'stdbuf',
'nice',
'ionice',
]);

/**
* Wrapper flags that consume the FOLLOWING token as their value, so the value
* is not mistaken for the wrapped command word (`sudo -u root rm -rf /`).
* Long `--flag=value` forms need no entry: they are a single token.
*/
const WRAPPER_FLAGS_WITH_VALUE = new Set([
'-u',
'-g',
'-p',
'-C',
'-h',
'-r',
'-t',
'-U',
'--user',
'--group',
'--prompt',
'--host',
'--role',
'--type',
'--chdir',
]);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

/**
* Return `tokens` with any leading wrapper commands, their flags, and
* `VAR=value` assignment prefixes removed, so the caller sees the command that
* actually runs.
*
* Flags are only skipped once a wrapper has been seen, so this can never walk
* into an unwrapped command's own arguments. Returns the input array when
* there is nothing to strip.
*
* @param {string[]} tokens
* @returns {string[]}
*/
function stripCommandWrappers(tokens) {
if (!Array.isArray(tokens) || tokens.length === 0) return tokens;
let index = 0;
let sawWrapper = false;
while (index < tokens.length) {
const token = tokens[index];
if (COMMAND_WRAPPERS.has(commandBasename(token))) {
sawWrapper = true;
index += 1;
continue;
}
// `FOO=bar rm -rf /` and `env FOO=bar rm -rf /` both put assignments before
// the command word.
if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(token)) {
index += 1;
continue;
}
if (sawWrapper && token.startsWith('-')) {
if (WRAPPER_FLAGS_WITH_VALUE.has(token)) index += 1;
index += 1;
continue;
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
}
break;
}
return index === 0 ? tokens : tokens.slice(index);
}

/**
* Detect `rm` invocations that recursively force-delete files. Handles
* combined (`-rf`, `-fr`, `-Rf`) and split (`-r -f`) flag forms.
Expand Down Expand Up @@ -613,12 +693,12 @@ function isDestructiveFindExec(command) {
}

// Tokenize the whole command line
const tokens = tokenize(trimmed);
const tokens = stripCommandWrappers(tokenize(trimmed));
if (!tokens || tokens.length === 0) {
return false;
}

// Must start with `find`
// Must start with `find` — after any wrapper prefix (`sudo find . -exec rm`).
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
if (commandBasename(tokens[0]) !== 'find') {
return false;
}
Expand Down Expand Up @@ -702,7 +782,9 @@ function isDestructiveBash(command) {
const stripped = stripQuotedStrings(segment);
if (DESTRUCTIVE_SQL_DD.test(stripped)) return true;
if (extra && extra.test(stripped)) return true;
const tokens = tokenize(segment);
// Look past sudo/doas/env/... so a privileged spelling is not the one that
// gets through (the gate matters MORE for those, not less).
const tokens = stripCommandWrappers(tokenize(segment));
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
if (isDestructiveRm(tokens)) return true;
if (isDestructiveGit(tokens)) return true;
}
Expand Down
78 changes: 78 additions & 0 deletions tests/hooks/gateguard-fact-force.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -253,6 +253,84 @@ function runTests() {
passed++;
else failed++;

// --- Test 4d: wrapper-prefixed destructive commands ---
/**
* Every token-based detector keys on `tokens[0]`, so `sudo rm -rf /` read as
* an invocation of `sudo` and was ALLOWED while the bare `rm -rf /` was
* denied — the gate missed exactly the privileged spellings it matters most
* for. Same for doas/env/command/nohup, `VAR=value` prefixes, sudo's own
* flags, and a wrapper appearing after a compound separator.
*/
for (const command of [
'sudo rm -rf /important/data',
'sudo -u root rm -rf /important/data',
'sudo --user=root rm -rf /important/data',
'doas rm -rf /important/data',
'env rm -rf /important/data',
'FOO=bar rm -rf /important/data',
'command rm -rf /important/data',
'nohup rm -rf /important/data',
'sudo git reset --hard',
'sudo git clean -fd',
'sudo git push --force',
'sudo find . -exec rm {} ;',
'echo hello && sudo rm -rf /important/data'
]) {
clearState();
if (
test(`denies a wrapper-prefixed destructive command: ${command}`, () => {
// Prime the session so the separate first-command routine gate cannot
// be mistaken for a destructive denial.
runBashHook({ tool_name: 'Bash', tool_input: { command: 'printf ready' } });
const result = runBashHook({ tool_name: 'Bash', tool_input: { command } });
assert.strictEqual(result.code, 0, `hook should exit 0 for ${command}`);
const output = parseOutput(result.stdout);
assert.ok(output, `hook should produce JSON output for ${command}`);
assert.ok(output.hookSpecificOutput, `${command} should carry a permission decision`);
assert.strictEqual(
output.hookSpecificOutput.permissionDecision,
'deny',
`${command} must be gated as destructive`
);
assert.ok(output.hookSpecificOutput.permissionDecisionReason.includes('Destructive'));
})
)
passed++;
else failed++;
}

// --- Test 4e: looking past wrappers must not gate ordinary privileged work ---
for (const command of [
'sudo apt-get update',
'sudo systemctl restart nginx',
'sudo ls -la /etc',
'env NODE_ENV=production npm run build',
'command ls'
]) {
clearState();
if (
test(`does not gate an ordinary wrapped command: ${command}`, () => {
runBashHook({ tool_name: 'Bash', tool_input: { command: 'printf ready' } });
const result = runBashHook({ tool_name: 'Bash', tool_input: { command } });
assert.strictEqual(result.code, 0, `hook should exit 0 for ${command}`);
const output = parseOutput(result.stdout);
assert.ok(output, `hook should produce JSON output for ${command}`);
const decision = output.hookSpecificOutput;
if (decision) {
const reason = decision.permissionDecisionReason || '';
assert.ok(
decision.permissionDecision !== 'deny' || !reason.includes('Destructive'),
`${command} must not be gated as destructive`
);
} else {
assert.strictEqual(output.tool_name, 'Bash', 'pass-through should preserve input');
}
})
)
passed++;
else failed++;
}

// --- Test 5: denies first routine Bash, allows second ---
clearState();
if (
Expand Down