The agent harness performance optimization system. Skills, instincts, memory, security, and research-first development for Claude Code, Codex, Opencode, Cursor and beyond.
fix(gateguard): unwrap the runners and shell forms the SQL-client check still misses
L4XBf35470e9b885
diff --git a/scripts/hooks/gateguard-fact-force.js b/scripts/hooks/gateguard-fact-force.jsindex 6756a0b79..587e48739 100644--- a/scripts/hooks/gateguard-fact-force.js+++ b/scripts/hooks/gateguard-fact-force.js@@ -421,17 +421,34 @@ const SUDO_VALUE_FLAGS = new Set(['--command-timeout',]);+// Programs that only run the command after them. `valueOptions` consume the+// next token; `positionals` are leading operands of the program itself+// (`timeout DURATION`). sudo, doas and env keep their own handling below.+const RUNNER_PREFIXES = {+ command: {},+ exec: { valueOptions: ['-a'] },+ ionice: { valueOptions: ['-c', '--class', '-n', '--classdata', '-p', '--pid'] },+ nice: { valueOptions: ['-n', '--adjustment'] },+ nohup: {},+ setsid: {},+ stdbuf: { valueOptions: ['-i', '-o', '-e', '--input', '--output', '--error'] },+ time: { valueOptions: ['-f', '--format', '-o', '--output'] },+ timeout: { valueOptions: ['-s', '--signal', '-k', '--kill-after'], positionals: 1 }+};+/*** Advance past `sudo`/`doas`/`env` wrappers including their flags and- * `VAR=value` assignments, so `sudo -u postgres psql ...` and- * `env PGUSER=postgres psql ...` still resolve to the real command.+ * `VAR=value` assignments, and past the runners in {@link RUNNER_PREFIXES},+ * so `sudo -u postgres psql ...`, `env PGUSER=postgres psql ...` and+ * `timeout 30 psql ...` still resolve to the real command. Wrappers stack+ * without a fixed limit: every one consumes at least one token.** @param {string[]} tokens dequoted tokens for one segment* @returns {number} index of the real command token*/function unwrapLeadWrappers(tokens) {let index = 0;- for (let guard = 0; guard < 4; guard += 1) {+ for (let guard = 0; guard < tokens.length; guard += 1) {if (index >= tokens.length) return index;const base = commandBasename(tokens[index]);if (base === 'sudo' || base === 'doas') {@@ -487,11 +504,63 @@ function unwrapLeadWrappers(tokens) {}continue;}+ const runner = RUNNER_PREFIXES[base];+ if (runner) {+ const valueOptions = runner.valueOptions || [];+ index += 1;+ while (index < tokens.length) {+ const arg = tokens[index];+ if (arg === '--') {+ index += 1;+ break;+ }+ if (arg === '-' || !arg.startsWith('-')) break;+ index += valueOptions.includes(arg) ? 2 : 1;+ }+ index += runner.positionals || 0;+ continue;+ }break;}return index;}+/**+ * Command lines that `env -S` / `env --split-string` split and run. The+ * whole command hides inside one argument (`env -S 'psql -c "..."'`), so+ * each payload is scanned as a command line of its own.+ *+ * @param {string[]} tokens dequoted tokens for one segment+ * @returns {string[]} the command lines, possibly none+ */+function envSplitStrings(tokens) {+ const payloads = [];+ for (let i = 0; i < tokens.length; i += 1) {+ if (commandBasename(tokens[i]) !== 'env') continue;+ for (let j = i + 1; j < tokens.length; j += 1) {+ const arg = tokens[j];+ if (arg === '-S' || arg === '--split-string') {+ if (j + 1 < tokens.length) payloads.push(tokens.slice(j + 1).join(' '));+ break;+ }+ if (arg.startsWith('--split-string=')) {+ payloads.push([arg.slice('--split-string='.length), ...tokens.slice(j + 1)].join(' '));+ break;+ }+ if (/^-S./.test(arg)) {+ payloads.push([arg.slice(2), ...tokens.slice(j + 1)].join(' '));+ break;+ }+ if (arg === '-u' || arg === '--unset' || arg === '-C' || arg === '--chdir') {+ j += 1;+ continue;+ }+ if (!arg.startsWith('-') && !/^[A-Za-z_][A-Za-z0-9_]*=/.test(arg)) break;+ }+ }+ return payloads;+}+/*** Detect destructive SQL passed as (possibly quoted) arguments to a known* SQL client. Operates on dequoted tokens from `quoteAwareSegments`, so@@ -513,22 +582,29 @@ function isDestructiveSqlClient(tokens) {* separators, quoted `find -exec`, and `sh -c`/`bash -c` wrappers that evade* the quote-stripping path (GHSA-4v57-ph3x-gf55).*+ * Past the recursion limit the nested command is not visible, so the check+ * fails closed: a guard that allowed it would be bypassed by one more level.+ ** @param {string} raw* @param {number} [depth] recursion guard for shell -c wrappers* @returns {boolean}*/function isDestructiveQuoteAware(raw, depth = 0) {- if (depth > 4) return false;+ if (depth > 4) return true;for (const tokens of quoteAwareSegments(raw)) {if (tokens.length === 0) continue;if (isDestructiveRm(tokens)) return true;if (isDestructiveGit(tokens)) return true;if (isDestructiveSqlClient(tokens)) return true;if (isDestructiveFindExec(tokens.join(' '))) return true;+ for (const payload of envSplitStrings(tokens)) {+ if (isDestructiveQuoteAware(payload, depth + 1)) return true;+ }const wi = unwrapLeadWrappers(tokens);const base = wi < tokens.length ? commandBasename(tokens[wi]) : '';if (SHELL_WRAPPERS.has(base)) {- const ci = tokens.indexOf('-c', wi);+ // `-c`, or a short-option cluster that includes it (`-lc`, `-ec`).+ const ci = tokens.findIndex((token, i) => i > wi && /^-[A-Za-z]*c[A-Za-z]*$/.test(token));if (ci !== -1 && tokens[ci + 1] && isDestructiveQuoteAware(tokens[ci + 1], depth + 1)) {return true;}diff --git a/tests/hooks/gateguard-fact-force.test.js b/tests/hooks/gateguard-fact-force.test.jsindex 9e6a18334..2496182ff 100644--- a/tests/hooks/gateguard-fact-force.test.js+++ b/tests/hooks/gateguard-fact-force.test.js@@ -1539,6 +1539,45 @@ function runTests() {passed++;else failed++;+ if (+ test('denies destructive SQL through runners and shell flag clusters', () => {+ expectDestructiveDeny('bash -lc "psql -c \'drop table users\'"', 'bash -lc psql');+ expectDestructiveDeny('sh -ec "psql -c \'drop table users\'"', 'sh -ec psql');+ expectDestructiveDeny('env -S \'psql -c "drop table users"\'', 'env -S psql');+ expectDestructiveDeny('env --split-string=\'psql -c "drop table users"\'', 'env --split-string psql');+ expectDestructiveDeny('env time -f "%E" psql -c "drop table users"', 'env time -f psql');+ expectDestructiveDeny('nice -n 10 psql -c "drop table users"', 'nice psql');+ expectDestructiveDeny('timeout 30 psql -c "drop table users"', 'timeout psql');+ expectDestructiveDeny('nohup mysql -e "delete from sessions"', 'nohup mysql');+ expectDestructiveDeny('sudo nice -n 5 timeout -s KILL 30 psql -c "drop table users"', 'stacked runners psql');+ })+ )+ passed++;+ else failed++;++ if (+ test('denies a command nested past the shell -c recursion limit', () => {+ // Each level quotes the one inside it. Past the limit the command is not+ // visible, so the check fails closed instead of allowing it.+ let command = 'psql -c "drop table users"';+ for (let level = 0; level < 6; level += 1) command = `sh -c ${JSON.stringify(command)}`;+ expectDestructiveDeny(command, 'sh -c nested six deep');+ })+ )+ passed++;+ else failed++;++ if (+ test('allows harmless commands under the runners and flag clusters', () => {+ expectAllow('bash -lc "psql -c \'select count(*) from users\'"', 'bash -lc select');+ expectAllow('nice -n 10 psql -c "select 1"', 'nice select');+ expectAllow('timeout 30 git status', 'timeout git status');+ expectAllow('env -S \'psql -c "select 1"\'', 'env -S select');+ })+ )+ passed++;+ else failed++;+if (test('allows SQL string literals and non-SQL clients mentioning SQL', () => {expectAllow('psql -c "SELECT \'drop table\' FROM audit_log"', 'SQL string literal');