From 047b813043dfa40e71ebfa4e0113305ec24ed586 Mon Sep 17 00:00:00 2001 From: L4XB Date: Sat, 12 Sep 2026 10:00:42 +0200 Subject: [PATCH 01/14] fix(block-no-verify): treat a git command line quoted as data as data The hook scanned the whole command string for a git invocation with a bypass flag, so a quoted git command line handed to another program as an argument was blocked even though no git command ran: passing it to a CLI, printing it, or grepping for it in docs. Quoted regions are now scanned once and classified by the word that opens them: a quoted string that is an argument to a non-shell program is data, while a shell or command wrapper (sh -c, bash -lc, sudo, env, xargs, eval) still has its quoted body scanned as a command, as do command substitutions and every branch of a compound command. The scanner lives in scripts/lib/shell-quotes.js so the hook stays inside the file size limit. --- scripts/hooks/block-no-verify.js | 96 ++++++++++++- scripts/lib/shell-quotes.js | 210 ++++++++++++++++++++++++++++ tests/hooks/block-no-verify.test.js | 90 ++++++++++++ 3 files changed, 391 insertions(+), 5 deletions(-) create mode 100644 scripts/lib/shell-quotes.js diff --git a/scripts/hooks/block-no-verify.js b/scripts/hooks/block-no-verify.js index 16e0044d7fd..add0f6d7b23 100644 --- a/scripts/hooks/block-no-verify.js +++ b/scripts/hooks/block-no-verify.js @@ -15,6 +15,8 @@ 'use strict'; +const { quotedRegionAt } = require('../lib/shell-quotes'); + const MAX_STDIN = 1024 * 1024; let raw = ''; @@ -35,6 +37,52 @@ const GIT_COMMANDS_WITH_NO_VERIFY = [ */ const VALID_BEFORE_GIT = ' \t\n\r;&|$`(<{!"\']/.~\\'; +/** + * Programs that execute a quoted argument as a shell command line, so a + * `git` inside one of their quoted arguments is a command that must still + * be checked (`sh -c "git commit --no-verify"`, `sudo`, `xargs`, `env`...). + * For any other argv0 (`node cli.js 'git commit --no-verify'`, + * `printf '%s' '...'`, `python3 -c "..."`) a quoted string is data. + */ +const COMMAND_WRAPPERS = new Set([ + 'sh', + 'bash', + 'zsh', + 'dash', + 'ksh', + 'fish', + 'busybox', + 'eval', + 'exec', + 'command', + 'xargs', + 'sudo', + 'doas', + 'su', + 'env', + 'nice', + 'ionice', + 'nohup', + 'timeout', + 'time', + 'watch', + 'flock', + 'ssh', + 'script', + 'csh', + 'tcsh', + 'setsid', + 'stdbuf', + 'taskset', + 'chrt', + 'unshare', + 'chroot', + 'runuser', + 'npx', + 'bunx', + 'pnpx', +]); + // Git config section and variable names are case-insensitive // (subsection names are case-sensitive but core.hooksPath has none), // so we normalize the candidate token to lowercase before matching. @@ -149,7 +197,11 @@ function tokenizeShellWords(input, start = 0, end = input.length) { continue; } - if (/\s/.test(char)) { + // Whitespace ends a word; so do the unquoted substitution delimiters, + // which can never be part of a word (`echo "$(git push --no-verify)"`, + // "`git push --no-verify`" used to yield the token `--no-verify)` / + // `--no-verify\``, hiding the flag). + if (/[\s`()]/.test(char)) { pushToken(i); continue; } @@ -289,6 +341,32 @@ function isInComment(input, idx) { return false; } +/** + * Strip a leading path and a trailing `.exe` from a command word. + */ +function commandBasename(word) { + return String(word || '') + .replace(/^.*[\\/]/, '') + .replace(/\.exe$/i, '') + .toLowerCase(); +} + +/** + * A `git` inside a quoted string is only a command when that string is + * handed to something that executes it. Otherwise it is an argument of an + * unrelated program (a CLI under test, printf, python -c, ...) and must not + * be inspected for bypass flags. A double-quoted string that contains a + * command substitution (`"$(git ...)"`, "`git ...`") runs git before any + * program receives it, so it is never data. + */ +function isQuotedDataArgument(input, idx) { + const region = quotedRegionAt(input, idx); + if (region === null || region.argv0 === '') return false; + if (region.substitution) return false; + const base = commandBasename(region.argv0); + return base !== 'git' && !COMMAND_WRAPPERS.has(base); +} + /** * Find the next 'git' token in the input starting from a position. */ @@ -307,7 +385,9 @@ function findGit(input, start) { } const before = idx > 0 ? input[idx - 1] : ' '; - if (VALID_BEFORE_GIT.includes(before)) return { idx, len }; + if (VALID_BEFORE_GIT.includes(before) && !isQuotedDataArgument(input, idx)) { + return { idx, len }; + } pos = idx + 1; } return null; @@ -409,8 +489,8 @@ function isNoVerifyLongFlag(value) { * right after the detected subcommand keyword) so that flags belonging to * earlier commands in a chain are not falsely matched. */ -function hasNoVerifyFlag(input, command, offset) { - const segmentEnd = findCommandSegmentEnd(input, offset); +function hasNoVerifyFlag(input, command, offset, limit = input.length) { + const segmentEnd = Math.min(findCommandSegmentEnd(input, offset), limit); const tokens = tokenizeShellWords(input, offset, segmentEnd); let skipNext = false; @@ -497,7 +577,13 @@ function checkCommand(input) { }; } - if (hasNoVerifyFlag(input, gitCommand, offset)) { + // A git command line inside a quoted string (`sh -c 'git push ...'`) + // ends with that string: scanning past the closing quote would read the + // rest of the outer statement in the wrong quote state, so `sh -c 'git + // push --no-verify'; echo done` glued `; echo done` onto the flag token. + const region = quotedRegionAt(input, detected.gitStart); + const limit = region === null ? input.length : region.end; + if (hasNoVerifyFlag(input, gitCommand, offset, limit)) { return { blocked: true, reason: `BLOCKED: --no-verify flag is not allowed with git ${gitCommand}. Git hooks must not be bypassed.`, diff --git a/scripts/lib/shell-quotes.js b/scripts/lib/shell-quotes.js new file mode 100644 index 00000000000..0fe3252921c --- /dev/null +++ b/scripts/lib/shell-quotes.js @@ -0,0 +1,210 @@ +'use strict'; + +/** + * Quoted-region scanner for shell command lines. + * + * One forward pass records every quoted region: where it starts and ends, the + * argv0 of the statement containing it (the first non-assignment, non-reserved + * word before the quote; '' when the quote is part of that first word) and + * whether the string carries a command substitution. A `$(` or backtick inside + * "..." suspends the string: the substitution body is top-level shell again + * (its own statements and quotes) until the matching `)` / backtick, after + * which the string resumes as a new region. Both halves are flagged + * `substitution`. Regions are appended only once complete, in order, so they + * are disjoint and sorted. The result is cached per input, so a command line + * holding thousands of quoted tokens is scanned once. + */ + +// Words that open or structure a compound command; none of them receives the +// quoted string that follows, so none may become a statement's argv0. +const SHELL_RESERVED_WORDS = new Set([ + 'if', 'then', 'else', 'elif', 'fi', 'do', 'done', 'while', 'until', 'for', + 'case', 'esac', 'in', 'select', 'function', 'coproc', '!', '{', '}', '[[', ']]', +]); + +const ASSIGNMENT_WORD = /^[A-Za-z_][A-Za-z0-9_]*=/; + +// Unquoted characters that start a new statement (or a nested command). +const STATEMENT_SEPARATORS = new Set([';', '|', '&', '\n', '(', ')', '`']); + +let cache = { input: null, regions: [] }; + +function createState() { + return { + regions: [], + suspended: [], + quote: null, + escaped: false, + open: null, + argv0: null, + word: '', + inWord: false, + }; +} + +function endWord(state) { + if (!state.inWord) return; + if ( + state.argv0 === null && + state.word !== '' && + !SHELL_RESERVED_WORDS.has(state.word) && + !ASSIGNMENT_WORD.test(state.word) + ) { + state.argv0 = state.word; + } + state.word = ''; + state.inWord = false; +} + +function newStatement(state) { + endWord(state); + state.argv0 = null; +} + +function openRegion(state, start, quote, argv0, substitution) { + state.quote = quote; + state.open = { start, quote, argv0, substitution }; +} + +function closeRegion(state, end, substitution) { + const region = state.open; + state.regions.push({ ...region, end, substitution: region.substitution || substitution }); + state.open = null; + state.quote = null; +} + +/** + * `$(` or a backtick inside "...": park the outer statement's word state (the + * outer word `FOO="pre$(cmd)post"` continues after the substitution as if it + * were a single character) and scan the body as a fresh statement. Returns + * the number of characters consumed. + */ +function suspendString(state, index, char) { + state.suspended.push({ + backtick: char === '`', + depth: 0, + argv0: state.open.argv0, + outer: { word: state.word, inWord: state.inWord, argv0: state.argv0 }, + }); + closeRegion(state, index, true); + state.word = ''; + state.inWord = false; + state.argv0 = null; + return char === '$' ? 2 : 1; +} + +function resumeString(state, index, outer) { + state.suspended.pop(); + state.word = outer.outer.word; + state.inWord = outer.outer.inWord; + state.argv0 = outer.outer.argv0; + openRegion(state, index, '"', outer.argv0, true); +} + +/** A character inside a quoted string. Returns the number of characters consumed. */ +function scanQuotedChar(state, input, index) { + const char = input.charAt(index); + if (state.quote === '"' && char === '\\') { + state.escaped = true; + return 1; + } + if (char === state.quote) { + closeRegion(state, index, false); + return 1; + } + if (state.quote === '"' && (char === '`' || (char === '$' && input.charAt(index + 1) === '('))) { + return suspendString(state, index, char); + } + state.word += char; + state.inWord = true; + return 1; +} + +/** A character outside quotes. Returns the number of characters consumed. */ +function scanBareChar(state, index, char) { + if (char === '\\') { + state.escaped = true; + state.inWord = true; + return 1; + } + if (char === '"' || char === "'") { + state.inWord = true; + openRegion(state, index, char, state.argv0 === null ? '' : state.argv0, false); + return 1; + } + const outer = state.suspended.length > 0 ? state.suspended[state.suspended.length - 1] : null; + if (outer !== null) { + const resumes = outer.backtick ? char === '`' : char === ')' && outer.depth === 0; + if (resumes) { + resumeString(state, index, outer); + return 1; + } + if (!outer.backtick && (char === '(' || char === ')')) { + const depth = outer.depth + (char === '(' ? 1 : -1); + state.suspended = [...state.suspended.slice(0, -1), { ...outer, depth }]; + } + } + if (STATEMENT_SEPARATORS.has(char)) { + newStatement(state); + return 1; + } + if (/\s/.test(char)) { + endWord(state); + return 1; + } + state.word += char; + state.inWord = true; + return 1; +} + +/** + * Every quoted region of `input`, sorted by start and disjoint. + * + * @param {string} input + * @returns {Array<{start: number, end: number, quote: string, argv0: string, substitution: boolean}>} + */ +function quotedRegions(input) { + if (cache.input === input) return cache.regions; + const state = createState(); + for (let i = 0; i < input.length; ) { + const char = input.charAt(i); + if (state.escaped) { + state.escaped = false; + state.word += char; + state.inWord = true; + i += 1; + continue; + } + i += state.quote ? scanQuotedChar(state, input, i) : scanBareChar(state, i, char); + } + if (state.open !== null) state.regions.push({ ...state.open, end: input.length }); + cache = { input, regions: state.regions }; + return state.regions; +} + +/** + * The quoted region that strictly contains `idx`, or null when `idx` is not + * inside a quote. Regions are disjoint and sorted, so this is a binary search. + * + * @param {string} input + * @param {number} idx + */ +function quotedRegionAt(input, idx) { + const regions = quotedRegions(input); + let lo = 0; + let hi = regions.length - 1; + while (lo <= hi) { + const mid = (lo + hi) >> 1; + const region = regions[mid]; + if (idx <= region.start) { + hi = mid - 1; + } else if (idx >= region.end) { + lo = mid + 1; + } else { + return region; + } + } + return null; +} + +module.exports = { quotedRegions, quotedRegionAt, SHELL_RESERVED_WORDS }; diff --git a/tests/hooks/block-no-verify.test.js b/tests/hooks/block-no-verify.test.js index 8b07d5f00f2..ebf8df46567 100644 --- a/tests/hooks/block-no-verify.test.js +++ b/tests/hooks/block-no-verify.test.js @@ -251,6 +251,96 @@ if (test('allows --no-verbose (not a prefix of --no-verify)', () => { assert.strictEqual(r.code, 0, `expected exit 0, got ${r.code}: ${r.stderr}`); })) passed++; else failed++; +// --- A git command line quoted as an argument to another program is data --- + +if (test('allows a quoted git command line passed as an argument to another program', () => { + for (const command of [ + "node /tmp/cli.js 'git commit --no-verify -m x'", + 'node /tmp/cli.js "git push --no-verify"', + "printf '%s' 'git commit --no-verify -m x' | node /tmp/x.js", + 'python3 -c "print(\'git commit --no-verify\')"', + "grep -n 'git commit --no-verify' docs/hooks.md", + ]) { + const r = runHook({ tool_input: { command } }); + assert.strictEqual(r.code, 0, `expected exit 0 for ${command}, got ${r.code}: ${r.stderr}`); + } +})) passed++; else failed++; + +if (test('blocks a quoted git command line behind a process prefix or another shell', () => { + for (const command of [ + "setsid sh -c 'git commit --no-verify -m x'", + 'csh -c "git commit --no-verify -m x"', + "tcsh -c 'git push --no-verify'", + "stdbuf -oL bash -c 'git commit -n -m x'", + "taskset -c 0 sh -c 'git push --no-verify'", + "unshare -n sh -c 'git commit --no-verify -m x'", + "runuser -u deploy -- sh -c 'git push --no-verify'", + "npx some-runner 'git commit --no-verify -m x'", + ]) { + const r = runHook({ tool_input: { command } }); + assert.strictEqual(r.code, 2, `expected exit 2 for ${command}, got ${r.code}`); + } +})) passed++; else failed++; + +if (test('blocks a git command substituted inside a double-quoted data argument', () => { + for (const command of [ + 'echo "$(git commit --no-verify -m x)"', + 'echo "$(git push --no-verify)"', + 'printf "%s" "`git push --no-verify`"', + 'node /tmp/cli.js "result: $(git commit -n -m x)"', + ]) { + const r = runHook({ tool_input: { command } }); + assert.strictEqual(r.code, 2, `expected exit 2 for ${command}, got ${r.code}`); + } +})) passed++; else failed++; + +if (test('blocks a quoted git command line inside a compound command or a nested substitution', () => { + for (const command of [ + "( sh -c 'git commit --no-verify -m x' )", + "{ sh -c 'git push --no-verify'; }", + "if sh -c 'git commit --no-verify -m x'; then echo ok; fi", + "for f in a b; do sh -c 'git commit --no-verify -m x'; done", + 'echo "$(echo "x"; git commit --no-verify -m x)"', + 'echo "before $(sh -c \'git commit --no-verify -m x\') after"', + 'echo "$(echo "$(git push --no-verify)")"', + "FOO=\"pre$(echo x)post\" sh -c 'git commit --no-verify -m x'", + "PREFIX=\"`date`\" sh -c 'git push --no-verify'", + "sh -c 'git push --no-verify'; echo done", + "sh -c 'git push --no-verify' && echo done", + 'sh -c "git commit --no-verify -m x" || true', + ]) { + const r = runHook({ tool_input: { command } }); + assert.strictEqual(r.code, 2, `expected exit 2 for ${command}, got ${r.code}`); + } +})) passed++; else failed++; + +if (test('stays fast on a large quoted data payload full of git tokens', () => { + const payload = 'git commit --no-verify -m x '.repeat(12000); + const command = `node /tmp/cli.js '${payload}'`; + assert.ok(command.length > 300000, 'payload should exceed 300 KB'); + const started = Date.now(); + const r = runHook({ tool_input: { command } }); + const elapsed = Date.now() - started; + assert.strictEqual(r.code, 0, `expected exit 0, got ${r.code}: ${r.stderr}`); + assert.ok(elapsed < 5000, `hook took ${elapsed}ms on a 300 KB quoted payload`); +})) passed++; else failed++; + +if (test('still blocks a quoted git command line handed to a shell or command wrapper', () => { + for (const command of [ + 'sh -c "git commit --no-verify -m x"', + "bash -lc 'git push --no-verify'", + 'sudo git commit --no-verify -m x', + "xargs -0 git commit --no-verify", + 'env FOO=1 git commit -n -m x', + "eval 'git commit --no-verify -m x'", + 'node /tmp/cli.js "data" && git commit --no-verify -m x', + "echo 'git commit --no-verify' ; git push --no-verify", + ]) { + const r = runHook({ tool_input: { command } }); + assert.strictEqual(r.code, 2, `expected exit 2 for ${command}, got ${r.code}`); + } +})) passed++; else failed++; + console.log('─'.repeat(50)); console.log(`Passed: ${passed} Failed: ${failed}`); From f409441bd4d7ffb3652a41cbac8d711c6fe1e15c Mon Sep 17 00:00:00 2001 From: L4XB Date: Sat, 12 Sep 2026 13:10:20 +0200 Subject: [PATCH 02/14] fix(block-no-verify): scan a quoted argument that a runtime evaluates A quoted git command line handed to an unrelated program is data, but a runtime invoked with an eval flag (`node -e`, `python3 -c`, `perl -E`, `deno eval`) runs that argument as source, so a bypass inside it reaches git. Those regions are inspected again, while a script argument such as `node cli.js 'git commit --no-verify'` stays data. In a code payload the flag is followed by the punctuation that closes the call, `execSync("git push --no-verify")`, and the word tokenizer kept it in the token, so the flag never matched. Trailing quotes, brackets and separators are trimmed before the flag comparison, which also closes the same hole for shell payloads. The quoted-region scanner now records where the statement's argv0 starts, so the words between the program and its quoted argument can be read. --- scripts/hooks/block-no-verify.js | 65 ++++++++++++++++++++++++++--- scripts/lib/shell-quotes.js | 31 +++++++++----- tests/hooks/block-no-verify.test.js | 32 +++++++++++++- 3 files changed, 112 insertions(+), 16 deletions(-) diff --git a/scripts/hooks/block-no-verify.js b/scripts/hooks/block-no-verify.js index add0f6d7b23..7f0f02b236a 100644 --- a/scripts/hooks/block-no-verify.js +++ b/scripts/hooks/block-no-verify.js @@ -42,7 +42,8 @@ const VALID_BEFORE_GIT = ' \t\n\r;&|$`(<{!"\']/.~\\'; * `git` inside one of their quoted arguments is a command that must still * be checked (`sh -c "git commit --no-verify"`, `sudo`, `xargs`, `env`...). * For any other argv0 (`node cli.js 'git commit --no-verify'`, - * `printf '%s' '...'`, `python3 -c "..."`) a quoted string is data. + * `printf '%s' '...'`, `grep -n '...' docs.md`) a quoted string is data, + * unless it is a runtime given an eval flag (see CODE_EVALUATORS). */ const COMMAND_WRAPPERS = new Set([ 'sh', @@ -351,10 +352,53 @@ function commandBasename(word) { .toLowerCase(); } +/** + * Runtimes that run a quoted argument as program source once they are given + * an eval flag (`node -e`, `python3 -c`, `perl -E`, `deno eval`). That source + * can spawn git itself, so it stays subject to the guard. The same runtime + * without an eval flag receives a script argument, which is data + * (`node cli.js 'git commit --no-verify'`). + */ +const CODE_EVALUATORS = new Set([ + 'node', + 'nodejs', + 'bun', + 'deno', + 'python', + 'python2', + 'python3', + 'pythonw', + 'perl', + 'ruby', + 'php', + 'lua', + 'luajit', + 'rscript', + 'osascript', + 'tclsh', + 'groovy', + 'julia', + 'elixir', + 'erl', +]); + +/** `-e`, `-E`, `--eval`, `-c`, `-p`, `--print`, `-r` and deno's `eval`. */ +const EVAL_FLAG = /(?:^|\s)(?:-{1,2}(?:e|eval|c|command|p|print|r)|eval)(?:=|\s|$)/i; + +/** + * Whether the words between the program and its quoted argument turn that + * argument into code. + */ +function evaluatesQuotedArgument(input, region, base) { + if (!CODE_EVALUATORS.has(base)) return false; + return EVAL_FLAG.test(input.slice(region.argv0Start, region.start)); +} + /** * A `git` inside a quoted string is only a command when that string is - * handed to something that executes it. Otherwise it is an argument of an - * unrelated program (a CLI under test, printf, python -c, ...) and must not + * handed to something that executes it: a shell or process wrapper, or a + * runtime given an eval flag. Otherwise it is an argument of an unrelated + * program (a CLI under test, printf, grep, a script path, ...) and must not * be inspected for bypass flags. A double-quoted string that contains a * command substitution (`"$(git ...)"`, "`git ...`") runs git before any * program receives it, so it is never data. @@ -364,7 +408,8 @@ function isQuotedDataArgument(input, idx) { if (region === null || region.argv0 === '') return false; if (region.substitution) return false; const base = commandBasename(region.argv0); - return base !== 'git' && !COMMAND_WRAPPERS.has(base); + if (base === 'git' || COMMAND_WRAPPERS.has(base)) return false; + return !evaluatesQuotedArgument(input, region, base); } /** @@ -483,6 +528,16 @@ function isNoVerifyLongFlag(value) { return value.length >= '--no-v'.length && '--no-verify'.startsWith(value); } +/** + * A flag inside a code payload is followed by the punctuation that closes the + * call (`execSync("git push --no-verify")`), and the word tokenizer keeps that + * punctuation in the token. Trim it so the flag is comparable; a real flag + * never ends in one of these characters. + */ +function flagToken(value) { + return value.replace(/[)\]}'"`;,]+$/, ''); +} + /** * Check if the input contains a --no-verify flag for a specific git command. * Only inspects the portion of the input starting at `offset` (the position @@ -495,7 +550,7 @@ function hasNoVerifyFlag(input, command, offset, limit = input.length) { let skipNext = false; for (const token of tokens) { - const value = token.value; + const value = flagToken(token.value); if (skipNext) { skipNext = false; diff --git a/scripts/lib/shell-quotes.js b/scripts/lib/shell-quotes.js index 0fe3252921c..c85d613d3c4 100644 --- a/scripts/lib/shell-quotes.js +++ b/scripts/lib/shell-quotes.js @@ -5,8 +5,9 @@ * * One forward pass records every quoted region: where it starts and ends, the * argv0 of the statement containing it (the first non-assignment, non-reserved - * word before the quote; '' when the quote is part of that first word) and - * whether the string carries a command substitution. A `$(` or backtick inside + * word before the quote; '' when the quote is part of that first word, with + * `argv0Start` holding its offset so a caller can read the words in between) + * and whether the string carries a command substitution. A `$(` or backtick inside * "..." suspends the string: the substitution body is top-level shell again * (its own statements and quotes) until the matching `)` / backtick, after * which the string resumes as a new region. Both halves are flagged @@ -37,11 +38,18 @@ function createState() { escaped: false, open: null, argv0: null, + argv0Start: -1, word: '', + wordStart: -1, inWord: false, }; } +function startWord(state, index) { + if (!state.inWord) state.wordStart = index; + state.inWord = true; +} + function endWord(state) { if (!state.inWord) return; if ( @@ -51,6 +59,7 @@ function endWord(state) { !ASSIGNMENT_WORD.test(state.word) ) { state.argv0 = state.word; + state.argv0Start = state.wordStart; } state.word = ''; state.inWord = false; @@ -59,11 +68,12 @@ function endWord(state) { function newStatement(state) { endWord(state); state.argv0 = null; + state.argv0Start = -1; } -function openRegion(state, start, quote, argv0, substitution) { +function openRegion(state, start, quote, argv0, argv0Start, substitution) { state.quote = quote; - state.open = { start, quote, argv0, substitution }; + state.open = { start, quote, argv0, argv0Start, substitution }; } function closeRegion(state, end, substitution) { @@ -84,6 +94,7 @@ function suspendString(state, index, char) { backtick: char === '`', depth: 0, argv0: state.open.argv0, + argv0Start: state.open.argv0Start, outer: { word: state.word, inWord: state.inWord, argv0: state.argv0 }, }); closeRegion(state, index, true); @@ -98,7 +109,7 @@ function resumeString(state, index, outer) { state.word = outer.outer.word; state.inWord = outer.outer.inWord; state.argv0 = outer.outer.argv0; - openRegion(state, index, '"', outer.argv0, true); + openRegion(state, index, '"', outer.argv0, outer.argv0Start, true); } /** A character inside a quoted string. Returns the number of characters consumed. */ @@ -124,12 +135,12 @@ function scanQuotedChar(state, input, index) { function scanBareChar(state, index, char) { if (char === '\\') { state.escaped = true; - state.inWord = true; + startWord(state, index); return 1; } if (char === '"' || char === "'") { - state.inWord = true; - openRegion(state, index, char, state.argv0 === null ? '' : state.argv0, false); + startWord(state, index); + openRegion(state, index, char, state.argv0 === null ? '' : state.argv0, state.argv0Start, false); return 1; } const outer = state.suspended.length > 0 ? state.suspended[state.suspended.length - 1] : null; @@ -153,7 +164,7 @@ function scanBareChar(state, index, char) { return 1; } state.word += char; - state.inWord = true; + startWord(state, index); return 1; } @@ -161,7 +172,7 @@ function scanBareChar(state, index, char) { * Every quoted region of `input`, sorted by start and disjoint. * * @param {string} input - * @returns {Array<{start: number, end: number, quote: string, argv0: string, substitution: boolean}>} + * @returns {Array<{start: number, end: number, quote: string, argv0: string, argv0Start: number, substitution: boolean}>} */ function quotedRegions(input) { if (cache.input === input) return cache.regions; diff --git a/tests/hooks/block-no-verify.test.js b/tests/hooks/block-no-verify.test.js index ebf8df46567..7d002fa8498 100644 --- a/tests/hooks/block-no-verify.test.js +++ b/tests/hooks/block-no-verify.test.js @@ -258,7 +258,8 @@ if (test('allows a quoted git command line passed as an argument to another prog "node /tmp/cli.js 'git commit --no-verify -m x'", 'node /tmp/cli.js "git push --no-verify"', "printf '%s' 'git commit --no-verify -m x' | node /tmp/x.js", - 'python3 -c "print(\'git commit --no-verify\')"', + "python3 /tmp/check.py 'git commit --no-verify'", + "node /tmp/cli.js --expect 'git push --no-verify'", "grep -n 'git commit --no-verify' docs/hooks.md", ]) { const r = runHook({ tool_input: { command } }); @@ -266,6 +267,35 @@ if (test('allows a quoted git command line passed as an argument to another prog } })) passed++; else failed++; +// A runtime given an eval flag executes its quoted argument as source, so a +// bypass in that source runs git for real and stays blocked. +if (test('blocks a git bypass inside a runtime eval payload', () => { + for (const command of [ + 'node -e "require(\'child_process\').execSync(\'git commit --no-verify -m x\')"', + "node -e 'require(\"child_process\").execSync(\"git push --no-verify\")'", + 'node --eval="git commit --no-verify -m x"', + 'node -p "cp.execSync(\'git push --no-verify\')"', + "python3 -c 'import os; os.system(\"git push --no-verify\")'", + "perl -e 'system(\"git commit --no-verify -m x\")'", + "ruby -e 'system(\"git push --no-verify\")'", + "php -r 'shell_exec(\"git commit --no-verify -m x\");'", + 'deno eval "git push --no-verify"', + ]) { + const r = runHook({ tool_input: { command } }); + assert.strictEqual(r.code, 2, `expected exit 2 for ${command}, got ${r.code}`); + } +})) passed++; else failed++; + +if (test('still allows a bypass phrase in an eval payload that does not run git', () => { + for (const command of [ + 'node -e "console.log(\'use --no-verify only in emergencies\')"', + "python3 -c 'print(\"never pass -n to commit\")'", + ]) { + const r = runHook({ tool_input: { command } }); + assert.strictEqual(r.code, 0, `expected exit 0 for ${command}, got ${r.code}: ${r.stderr}`); + } +})) passed++; else failed++; + if (test('blocks a quoted git command line behind a process prefix or another shell', () => { for (const command of [ "setsid sh -c 'git commit --no-verify -m x'", From 5e6de0d7b4fd0f7613915c7a0f1f6c7a0896171d Mon Sep 17 00:00:00 2001 From: L4XB Date: Sat, 12 Sep 2026 14:02:01 +0200 Subject: [PATCH 03/14] fix(block-no-verify): scope the eval flags to each runtime One shared flag expression treated every letter as an eval flag for every runtime, so `node -r setup.js cli.js 'git push --no-verify'` was blocked: node's `-r` preloads a module and leaves the rest of the command line as ordinary arguments, while `-r` is exactly how php is handed code. The same letter cannot mean both. Each runtime now carries its own flags, matched as whole words or their `=` form, so a path ending in one of them cannot qualify either. --- scripts/hooks/block-no-verify.js | 68 +++++++++++++++-------------- tests/hooks/block-no-verify.test.js | 25 +++++++++++ 2 files changed, 61 insertions(+), 32 deletions(-) diff --git a/scripts/hooks/block-no-verify.js b/scripts/hooks/block-no-verify.js index 7f0f02b236a..29705cebde7 100644 --- a/scripts/hooks/block-no-verify.js +++ b/scripts/hooks/block-no-verify.js @@ -353,45 +353,49 @@ function commandBasename(word) { } /** - * Runtimes that run a quoted argument as program source once they are given - * an eval flag (`node -e`, `python3 -c`, `perl -E`, `deno eval`). That source - * can spawn git itself, so it stays subject to the guard. The same runtime - * without an eval flag receives a script argument, which is data - * (`node cli.js 'git commit --no-verify'`). + * Runtimes that run a quoted argument as program source, each with the + * flags that do it: `node -e`, `python3 -c`, `perl -E`, `php -r`, + * `deno eval`. That source can spawn git itself, so it stays subject to the + * guard. The same runtime without one of its own eval flags receives a + * script path and arguments, which are data (`node cli.js 'git commit + * --no-verify'`). + * + * The flags are per runtime because the same letter means different things: + * node's `-r` preloads a module and leaves the rest of the command line as + * ordinary arguments, while php's `-r` is how php is handed code. */ -const CODE_EVALUATORS = new Set([ - 'node', - 'nodejs', - 'bun', - 'deno', - 'python', - 'python2', - 'python3', - 'pythonw', - 'perl', - 'ruby', - 'php', - 'lua', - 'luajit', - 'rscript', - 'osascript', - 'tclsh', - 'groovy', - 'julia', - 'elixir', - 'erl', +const CODE_EVALUATORS = new Map([ + ['node', ['-e', '--eval', '-p', '--print']], + ['nodejs', ['-e', '--eval', '-p', '--print']], + ['bun', ['-e', '--eval', '-p', '--print']], + ['deno', ['-e', '--eval', 'eval']], + ['python', ['-c']], + ['python2', ['-c']], + ['python3', ['-c']], + ['pythonw', ['-c']], + ['perl', ['-e', '-E']], + ['ruby', ['-e']], + ['php', ['-r']], + ['lua', ['-e']], + ['luajit', ['-e']], + ['rscript', ['-e']], + ['osascript', ['-e']], + ['groovy', ['-e']], + ['julia', ['-e', '-E']], + ['elixir', ['-e']], + ['erl', ['-eval']], ]); -/** `-e`, `-E`, `--eval`, `-c`, `-p`, `--print`, `-r` and deno's `eval`. */ -const EVAL_FLAG = /(?:^|\s)(?:-{1,2}(?:e|eval|c|command|p|print|r)|eval)(?:=|\s|$)/i; - /** * Whether the words between the program and its quoted argument turn that - * argument into code. + * argument into code. A flag is matched as a whole word, or as the `=` form + * of itself, so a path that happens to end in one of them cannot qualify. */ function evaluatesQuotedArgument(input, region, base) { - if (!CODE_EVALUATORS.has(base)) return false; - return EVAL_FLAG.test(input.slice(region.argv0Start, region.start)); + const flags = CODE_EVALUATORS.get(base); + if (flags === undefined) return false; + const words = input.slice(region.argv0Start, region.start).split(/\s+/); + return words.some((word) => flags.some((flag) => word === flag || word.startsWith(`${flag}=`))); } /** diff --git a/tests/hooks/block-no-verify.test.js b/tests/hooks/block-no-verify.test.js index 7d002fa8498..0350ac168a7 100644 --- a/tests/hooks/block-no-verify.test.js +++ b/tests/hooks/block-no-verify.test.js @@ -286,6 +286,31 @@ if (test('blocks a git bypass inside a runtime eval payload', () => { } })) passed++; else failed++; +if (test('allows a runtime flag that loads code but leaves the quoted argument as data', () => { + for (const command of [ + // node -r preloads a module; the script and its arguments stay data. + "node -r setup.js cli.js 'git push --no-verify'", + 'node --require ts-node/register cli.js "git commit --no-verify -m x"', + "ruby -r./setup cli.rb 'git push --no-verify'", + "python3 -B check.py 'git commit --no-verify'", + ]) { + const r = runHook({ tool_input: { command } }); + assert.strictEqual(r.code, 0, `expected exit 0 for ${command}, got ${r.code}: ${r.stderr}`); + } +})) passed++; else failed++; + +if (test('blocks each runtime through its own eval flag', () => { + for (const command of [ + 'node -p "cp.execSync(\'git push --no-verify\')"', + "php -r 'shell_exec(\"git commit --no-verify -m x\");'", + "perl -E 'system(\"git push --no-verify\")'", + "lua -e 'os.execute(\"git commit --no-verify -m x\")'", + ]) { + const r = runHook({ tool_input: { command } }); + assert.strictEqual(r.code, 2, `expected exit 2 for ${command}, got ${r.code}`); + } +})) passed++; else failed++; + if (test('still allows a bypass phrase in an eval payload that does not run git', () => { for (const command of [ 'node -e "console.log(\'use --no-verify only in emergencies\')"', From 599a14fd055f50a9290589c26cdf50f2ac0014cb Mon Sep 17 00:00:00 2001 From: L4XB Date: Thu, 24 Sep 2026 22:43:45 +0200 Subject: [PATCH 04/14] fix(block-no-verify): check awk program source and expect -c scripts awk takes its program as the first operand, without an eval flag, so `awk 'BEGIN { system("git commit --no-verify") }'` ran git while the quoted program was treated as data. awk, gawk, mawk and nawk now keep every quoted argument subject to the guard, and expect joins the evaluators through -c. The flag check also missed a bypass when the payload went on after the call that runs git: in `system("git push --no-verify") }` the closing quote reads to the tokenizer as an opening one, so the rest of the payload landed in the flag's token. The token is now cut at its first closing punctuation or whitespace instead of trimmed at the end. --- scripts/hooks/block-no-verify.js | 19 +++++++++++++++---- tests/hooks/block-no-verify.test.js | 23 +++++++++++++++++++++++ 2 files changed, 38 insertions(+), 4 deletions(-) diff --git a/scripts/hooks/block-no-verify.js b/scripts/hooks/block-no-verify.js index 29705cebde7..66ede8f082c 100644 --- a/scripts/hooks/block-no-verify.js +++ b/scripts/hooks/block-no-verify.js @@ -384,8 +384,17 @@ const CODE_EVALUATORS = new Map([ ['julia', ['-e', '-E']], ['elixir', ['-e']], ['erl', ['-eval']], + ['expect', ['-c']], ]); +/** + * Runtimes whose first operand is itself program source, with no eval flag: + * `awk 'BEGIN { system("git commit --no-verify") }'` runs git. Every quoted + * argument they receive stays subject to the guard, at the cost of also + * checking an awk pattern that merely mentions a bypass flag. + */ +const SOURCE_OPERAND_RUNTIMES = new Set(['awk', 'gawk', 'mawk', 'nawk']); + /** * Whether the words between the program and its quoted argument turn that * argument into code. A flag is matched as a whole word, or as the `=` form @@ -412,7 +421,7 @@ function isQuotedDataArgument(input, idx) { if (region === null || region.argv0 === '') return false; if (region.substitution) return false; const base = commandBasename(region.argv0); - if (base === 'git' || COMMAND_WRAPPERS.has(base)) return false; + if (base === 'git' || COMMAND_WRAPPERS.has(base) || SOURCE_OPERAND_RUNTIMES.has(base)) return false; return !evaluatesQuotedArgument(input, region, base); } @@ -535,11 +544,13 @@ function isNoVerifyLongFlag(value) { /** * A flag inside a code payload is followed by the punctuation that closes the * call (`execSync("git push --no-verify")`), and the word tokenizer keeps that - * punctuation in the token. Trim it so the flag is comparable; a real flag - * never ends in one of these characters. + * punctuation in the token. When the payload goes on after the call, the + * closing quote reads to the tokenizer as an opening one, and the rest of the + * payload lands in the same token (`system("git push --no-verify") }`). Keep + * the part before the first such character; a real flag contains none. */ function flagToken(value) { - return value.replace(/[)\]}'"`;,]+$/, ''); + return value.replace(/[)\]}'"`;,\s][\s\S]*$/, ''); } /** diff --git a/tests/hooks/block-no-verify.test.js b/tests/hooks/block-no-verify.test.js index 0350ac168a7..c8e2acd87ec 100644 --- a/tests/hooks/block-no-verify.test.js +++ b/tests/hooks/block-no-verify.test.js @@ -311,6 +311,29 @@ if (test('blocks each runtime through its own eval flag', () => { } })) passed++; else failed++; +// awk takes its program as the first operand, without an eval flag, and +// expect runs a Tcl script given with -c; both can spawn git. +if (test('blocks a git bypass in awk program source and an expect -c script', () => { + for (const command of [ + "awk 'BEGIN { system(\"git commit --no-verify -m x\") }'", + "gawk 'BEGIN { system(\"git push --no-verify\") }' /dev/null", + "mawk '{ print | \"git commit -n -m x\" }' input.txt", + "expect -c 'spawn git commit --no-verify -m x'", + // The payload goes on after the call that runs git. + "awk 'BEGIN { system(\"git push --no-verify\") }'", + "node -e 'require(\"child_process\").execSync(\"git push --no-verify\"); console.log(\"done\")'", + ]) { + const r = runHook({ tool_input: { command } }); + assert.strictEqual(r.code, 2, `expected exit 2 for ${command}, got ${r.code}`); + } +})) passed++; else failed++; + +if (test('allows an expect script path whose arguments mention a bypass', () => { + const command = "expect release.exp 'git push --no-verify'"; + const r = runHook({ tool_input: { command } }); + assert.strictEqual(r.code, 0, `expected exit 0 for ${command}, got ${r.code}: ${r.stderr}`); +})) passed++; else failed++; + if (test('still allows a bypass phrase in an eval payload that does not run git', () => { for (const command of [ 'node -e "console.log(\'use --no-verify only in emergencies\')"', From f129cbb05f95bdb547e7de8d9fc745acc5164eab Mon Sep 17 00:00:00 2001 From: L4XB Date: Thu, 24 Sep 2026 23:13:32 +0200 Subject: [PATCH 05/14] fix(block-no-verify): check a quoted git run by find, fd or parallel `find . -exec sh -c 'git commit --no-verify -m x' \;` passed: find was not a known launcher, so the quoted program counted as data, although find hands it to sh. main blocked it, since it checked every quoted git. find, fd (and fdfind) and parallel run a command line of their own for each file or input line, so they join the command wrappers. --- scripts/hooks/block-no-verify.js | 5 +++++ tests/hooks/block-no-verify.test.js | 14 ++++++++++++++ 2 files changed, 19 insertions(+) diff --git a/scripts/hooks/block-no-verify.js b/scripts/hooks/block-no-verify.js index 66ede8f082c..f3c3ff5dc09 100644 --- a/scripts/hooks/block-no-verify.js +++ b/scripts/hooks/block-no-verify.js @@ -82,6 +82,11 @@ const COMMAND_WRAPPERS = new Set([ 'npx', 'bunx', 'pnpx', + // Run a command for each file or input line: find -exec, fd -x, parallel. + 'find', + 'fd', + 'fdfind', + 'parallel', ]); // Git config section and variable names are case-insensitive diff --git a/tests/hooks/block-no-verify.test.js b/tests/hooks/block-no-verify.test.js index c8e2acd87ec..bbb0953cc4c 100644 --- a/tests/hooks/block-no-verify.test.js +++ b/tests/hooks/block-no-verify.test.js @@ -311,6 +311,20 @@ if (test('blocks each runtime through its own eval flag', () => { } })) passed++; else failed++; +// find, fd and parallel run a command line of their own for each file or +// input line; a quoted git handed to them runs for real. +if (test('blocks a quoted git command line run by find, fd or parallel', () => { + for (const command of [ + "find . -exec sh -c 'git commit --no-verify -m x' \\;", + "find . -name '*.md' -execdir bash -c 'git push --no-verify' \\;", + "fd -e md -x sh -c 'git commit -n -m x'", + "parallel 'git push --no-verify {}' ::: origin upstream", + ]) { + const r = runHook({ tool_input: { command } }); + assert.strictEqual(r.code, 2, `expected exit 2 for ${command}, got ${r.code}`); + } +})) passed++; else failed++; + // awk takes its program as the first operand, without an eval flag, and // expect runs a Tcl script given with -c; both can spawn git. if (test('blocks a git bypass in awk program source and an expect -c script', () => { From e8574210ca201b10165e779f332271aef094812d Mon Sep 17 00:00:00 2001 From: L4XB Date: Thu, 24 Sep 2026 23:45:45 +0200 Subject: [PATCH 06/14] fix(block-no-verify): check find and fd operands only after an exec flag find and fd run a command only after -exec/-execdir/-ok/-okdir or -x/--exec/-X/--exec-batch. As unconditional wrappers they also blocked `find . -name 'git commit --no-verify'` and similar searches for the phrase. They move to CODE_EVALUATORS with those flags, the same rule node -e and python -c follow; parallel stays a wrapper. --- scripts/hooks/block-no-verify.js | 10 ++++++---- tests/hooks/block-no-verify.test.js | 13 +++++++++++++ 2 files changed, 19 insertions(+), 4 deletions(-) diff --git a/scripts/hooks/block-no-verify.js b/scripts/hooks/block-no-verify.js index f3c3ff5dc09..b7751dd67c0 100644 --- a/scripts/hooks/block-no-verify.js +++ b/scripts/hooks/block-no-verify.js @@ -82,10 +82,8 @@ const COMMAND_WRAPPERS = new Set([ 'npx', 'bunx', 'pnpx', - // Run a command for each file or input line: find -exec, fd -x, parallel. - 'find', - 'fd', - 'fdfind', + // Runs a command line for each input line; find and fd, which do so only + // after one of their exec flags, are in CODE_EVALUATORS. 'parallel', ]); @@ -390,6 +388,10 @@ const CODE_EVALUATORS = new Map([ ['elixir', ['-e']], ['erl', ['-eval']], ['expect', ['-c']], + // Launchers that run a command given after one of their flags. + ['find', ['-exec', '-execdir', '-ok', '-okdir']], + ['fd', ['-x', '--exec', '-X', '--exec-batch']], + ['fdfind', ['-x', '--exec', '-X', '--exec-batch']], ]); /** diff --git a/tests/hooks/block-no-verify.test.js b/tests/hooks/block-no-verify.test.js index bbb0953cc4c..972123c6b67 100644 --- a/tests/hooks/block-no-verify.test.js +++ b/tests/hooks/block-no-verify.test.js @@ -325,6 +325,19 @@ if (test('blocks a quoted git command line run by find, fd or parallel', () => { } })) passed++; else failed++; +// Without one of their exec flags, find and fd only search for or print a +// quoted operand. +if (test('allows a bypass phrase that find or fd only searches for or prints', () => { + for (const command of [ + "find . -name 'git commit --no-verify'", + "find . -type f -printf 'git push --no-verify %p\\n'", + "fd 'git push --no-verify' docs", + ]) { + const r = runHook({ tool_input: { command } }); + assert.strictEqual(r.code, 0, `expected exit 0 for ${command}, got ${r.code}: ${r.stderr}`); + } +})) passed++; else failed++; + // awk takes its program as the first operand, without an eval flag, and // expect runs a Tcl script given with -c; both can spawn git. if (test('blocks a git bypass in awk program source and an expect -c script', () => { From cba56e961ce62c27a82c0e99cbc3cfd9ac89d606 Mon Sep 17 00:00:00 2001 From: L4XB Date: Fri, 25 Sep 2026 00:21:48 +0200 Subject: [PATCH 07/14] fix(block-no-verify): judge a quoted argument by the program find or fd launches After an exec flag, every quoted argument was treated as code, so `find . -exec grep 'git push --no-verify' {} \;` was blocked although grep only searches for the phrase. The program after the flag now decides, as it would at the top level: grep receives data, sh -c runs it. After find's `\;`, `';'` or `{} +`, the arguments are find's own again. A program named by an expansion, such as `$SHELL`, is only known when the line runs, so its quoted arguments stay subject to the guard, at the top level and after an exec flag alike. --- scripts/hooks/block-no-verify.js | 50 ++++++++++++++++++++++------- tests/hooks/block-no-verify.test.js | 29 +++++++++++++++++ 2 files changed, 67 insertions(+), 12 deletions(-) diff --git a/scripts/hooks/block-no-verify.js b/scripts/hooks/block-no-verify.js index b7751dd67c0..8be1b6a73b7 100644 --- a/scripts/hooks/block-no-verify.js +++ b/scripts/hooks/block-no-verify.js @@ -83,7 +83,7 @@ const COMMAND_WRAPPERS = new Set([ 'bunx', 'pnpx', // Runs a command line for each input line; find and fd, which do so only - // after one of their exec flags, are in CODE_EVALUATORS. + // after one of their exec flags, are in LAUNCHERS. 'parallel', ]); @@ -388,12 +388,23 @@ const CODE_EVALUATORS = new Map([ ['elixir', ['-e']], ['erl', ['-eval']], ['expect', ['-c']], - // Launchers that run a command given after one of their flags. +]); + +/** + * Launchers that run another program given after one of their flags: + * `find . -exec CMD ARGS \;`, `fd -x CMD ARGS`. A quoted argument of the + * launched program is judged as that program's own, so `-exec grep '...'` + * searches and `-exec sh -c '...'` runs. After find's `;` or `{} +` the + * arguments are find's again. + */ +const LAUNCHERS = new Map([ ['find', ['-exec', '-execdir', '-ok', '-okdir']], ['fd', ['-x', '--exec', '-X', '--exec-batch']], ['fdfind', ['-x', '--exec', '-X', '--exec-batch']], ]); +const EXEC_TERMINATORS = new Set(['\\;', "';'", '";"']); + /** * Runtimes whose first operand is itself program source, with no eval flag: * `awk 'BEGIN { system("git commit --no-verify") }'` runs git. Every quoted @@ -403,15 +414,31 @@ const CODE_EVALUATORS = new Map([ const SOURCE_OPERAND_RUNTIMES = new Set(['awk', 'gawk', 'mawk', 'nawk']); /** - * Whether the words between the program and its quoted argument turn that - * argument into code. A flag is matched as a whole word, or as the `=` form - * of itself, so a path that happens to end in one of them cannot qualify. + * Whether a quoted argument is data for the program that receives it. + * `words` runs from that program's name up to the argument. An eval flag is + * matched as a whole word, or as the `=` form of itself, so a path that + * happens to end in one of them cannot qualify. */ -function evaluatesQuotedArgument(input, region, base) { +function receivesAsData(words) { + // A program named by an expansion is only known when the line runs. + if (/[$`]/.test(words[0])) return false; + const base = commandBasename(words[0]); + if (base === 'git' || COMMAND_WRAPPERS.has(base) || SOURCE_OPERAND_RUNTIMES.has(base)) return false; + const launchFlags = LAUNCHERS.get(base); + if (launchFlags !== undefined) { + const at = words.findLastIndex((word) => launchFlags.includes(word)); + if (at === -1) return true; + const launched = words.slice(at + 1); + if (launched.some((word, i) => EXEC_TERMINATORS.has(word) || (word === '+' && launched[i - 1] === '{}'))) { + return true; + } + // The quoted argument is the launched program's name itself. + if (launched.length === 0) return false; + return receivesAsData([launched[0].replace(/['"\\]/g, ''), ...launched.slice(1)]); + } const flags = CODE_EVALUATORS.get(base); - if (flags === undefined) return false; - const words = input.slice(region.argv0Start, region.start).split(/\s+/); - return words.some((word) => flags.some((flag) => word === flag || word.startsWith(`${flag}=`))); + if (flags === undefined) return true; + return !words.some((word) => flags.some((flag) => word === flag || word.startsWith(`${flag}=`))); } /** @@ -427,9 +454,8 @@ function isQuotedDataArgument(input, idx) { const region = quotedRegionAt(input, idx); if (region === null || region.argv0 === '') return false; if (region.substitution) return false; - const base = commandBasename(region.argv0); - if (base === 'git' || COMMAND_WRAPPERS.has(base) || SOURCE_OPERAND_RUNTIMES.has(base)) return false; - return !evaluatesQuotedArgument(input, region, base); + const words = input.slice(region.argv0Start, region.start).split(/\s+/).filter(Boolean); + return receivesAsData([region.argv0, ...words.slice(1)]); } /** diff --git a/tests/hooks/block-no-verify.test.js b/tests/hooks/block-no-verify.test.js index 972123c6b67..8b4ae1d116d 100644 --- a/tests/hooks/block-no-verify.test.js +++ b/tests/hooks/block-no-verify.test.js @@ -318,6 +318,7 @@ if (test('blocks a quoted git command line run by find, fd or parallel', () => { "find . -exec sh -c 'git commit --no-verify -m x' \\;", "find . -name '*.md' -execdir bash -c 'git push --no-verify' \\;", "fd -e md -x sh -c 'git commit -n -m x'", + "find . -exec 'sh' -c 'git commit --no-verify -m x' \\;", "parallel 'git push --no-verify {}' ::: origin upstream", ]) { const r = runHook({ tool_input: { command } }); @@ -338,6 +339,34 @@ if (test('allows a bypass phrase that find or fd only searches for or prints', ( } })) passed++; else failed++; +// A program that find or fd launches decides for itself: grep searches for a +// quoted phrase, a shell runs it. After find's `;` the arguments are find's. +if (test('allows a bypass phrase that a program run by find or fd searches for', () => { + for (const command of [ + "find . -exec grep 'git push --no-verify' {} \\;", + "find . -name '*.md' -exec grep -l 'git commit --no-verify' {} +", + "fd -e md -x grep 'git push --no-verify'", + "find . -exec sh -c 'echo {}' \\; -name 'git commit --no-verify'", + "find . -exec sh -c 'echo {}' ';' -name 'git push --no-verify'", + "find . -exec sh -c 'ls \"$@\"' sh {} + -name 'git push --no-verify'", + ]) { + const r = runHook({ tool_input: { command } }); + assert.strictEqual(r.code, 0, `expected exit 0 for ${command}, got ${r.code}: ${r.stderr}`); + } +})) passed++; else failed++; + +// A program named by an expansion is only known when the line runs. +if (test('blocks a quoted git whose program is known only at run time', () => { + for (const command of [ + "$SHELL -c 'git commit --no-verify -m x'", + "\"$SHELL\" -c 'git commit --no-verify -m x'", + "find . -exec $SHELL -c 'git commit --no-verify -m x' \\;", + ]) { + const r = runHook({ tool_input: { command } }); + assert.strictEqual(r.code, 2, `expected exit 2 for ${command}, got ${r.code}`); + } +})) passed++; else failed++; + // awk takes its program as the first operand, without an eval flag, and // expect runs a Tcl script given with -c; both can spawn git. if (test('blocks a git bypass in awk program source and an expect -c script', () => { From 5fe77751b6eaa9f8399d91ee5a3f98923edb94be Mon Sep 17 00:00:00 2001 From: L4XB Date: Fri, 25 Sep 2026 00:22:15 +0200 Subject: [PATCH 08/14] fix(block-no-verify): keep checking quoted text that still reaches a shell Treating a quoted git as data unless its own program runs it let several forms through that main blocks: `echo '...' | sh`, `$(command -v sh) -c '...'`, `$(echo '...')`, `source <(echo '...')`, `builtin eval '...'`, `trap '...' EXIT` and `noglob sh -c '...'`. A quoted string is now checked when a later pipe feeds a program that runs what it reads (a shell or command wrapper, a runtime without a script operand, or a program named by an expansion), when its statement opens inside or right after a substitution, and when builtin, noglob, nocorrect, trap or alias receives it. --- scripts/hooks/block-no-verify.js | 68 ++++++++++++++++++++++++++++- scripts/lib/shell-quotes.js | 2 +- tests/hooks/block-no-verify.test.js | 49 ++++++++++++++++++++- 3 files changed, 115 insertions(+), 4 deletions(-) diff --git a/scripts/hooks/block-no-verify.js b/scripts/hooks/block-no-verify.js index 8be1b6a73b7..b00d1127035 100644 --- a/scripts/hooks/block-no-verify.js +++ b/scripts/hooks/block-no-verify.js @@ -15,7 +15,7 @@ 'use strict'; -const { quotedRegionAt } = require('../lib/shell-quotes'); +const { quotedRegionAt, ASSIGNMENT_WORD } = require('../lib/shell-quotes'); const MAX_STDIN = 1024 * 1024; let raw = ''; @@ -85,6 +85,13 @@ const COMMAND_WRAPPERS = new Set([ // Runs a command line for each input line; find and fd, which do so only // after one of their exec flags, are in LAUNCHERS. 'parallel', + // Shell builtins and zsh precommand modifiers that run a command line, or + // keep one to run later (`trap '...' EXIT`, `alias x='...'`). + 'builtin', + 'noglob', + 'nocorrect', + 'trap', + 'alias', ]); // Git config section and variable names are case-insensitive @@ -441,6 +448,59 @@ function receivesAsData(words) { return !words.some((word) => flags.some((flag) => word === flag || word.startsWith(`${flag}=`))); } +/** + * Whether a statement's first word sits right inside or right after a + * substitution. `$(echo '...')` runs what echo prints, `source <(echo '...')` + * reads it as a script, and in `$(command -v sh) -c '...'` the program is only + * known when the line runs. + */ +function startsAtSubstitution(input, argv0Start) { + let i = argv0Start - 1; + while (i >= 0 && /\s/.test(input.charAt(i))) i--; + const char = input.charAt(i); + if (char === '`' || char === ')') return true; + return char === '(' && /[$<>]/.test(input.charAt(i - 1)); +} + +/** + * Whether a program reads the text piped into it as code: a shell or command + * wrapper (`| sh`, `| xargs sh -c`), a runtime with no script operand of its + * own (`| node`, `| python3 -`), or a program named by an expansion. + */ +function readsCodeFromStdin(words) { + if (/[$`]/.test(words[0])) return true; + const base = commandBasename(words[0]); + if (COMMAND_WRAPPERS.has(base)) return true; + if (CODE_EVALUATORS.has(base)) return words.slice(1).every((word) => word.startsWith('-')); + return false; +} + +/** + * Whether a later part of the command line pipes into a program that reads + * what it receives as code (`echo '...' | sh`). Every later pipe counts, not + * only the rest of this pipeline, so a group such as `{ echo '...'; } | sh` + * is covered as well. + */ +function pipesIntoCodeReader(input, from) { + let pos = from; + while (pos < input.length) { + const end = findCommandSegmentEnd(input, pos); + if (end >= input.length) return false; + pos = end + 1; + if (input.charAt(end) !== '|') continue; + if (input.charAt(pos) === '|') { + pos += 1; + continue; + } + if (input.charAt(pos) === '&') pos += 1; + const words = tokenizeShellWords(input, pos, findCommandSegmentEnd(input, pos)) + .map((token) => token.value) + .filter((word) => !ASSIGNMENT_WORD.test(word)); + if (words.length > 0 && readsCodeFromStdin(words)) return true; + } + return false; +} + /** * A `git` inside a quoted string is only a command when that string is * handed to something that executes it: a shell or process wrapper, or a @@ -448,12 +508,16 @@ function receivesAsData(words) { * program (a CLI under test, printf, grep, a script path, ...) and must not * be inspected for bypass flags. A double-quoted string that contains a * command substitution (`"$(git ...)"`, "`git ...`") runs git before any - * program receives it, so it is never data. + * program receives it, so it is never data. Nor is a string whose program + * prints it into something that runs it: a pipe into a shell, or a + * substitution whose output is run or sourced. */ function isQuotedDataArgument(input, idx) { const region = quotedRegionAt(input, idx); if (region === null || region.argv0 === '') return false; if (region.substitution) return false; + if (startsAtSubstitution(input, region.argv0Start)) return false; + if (pipesIntoCodeReader(input, region.end + 1)) return false; const words = input.slice(region.argv0Start, region.start).split(/\s+/).filter(Boolean); return receivesAsData([region.argv0, ...words.slice(1)]); } diff --git a/scripts/lib/shell-quotes.js b/scripts/lib/shell-quotes.js index c85d613d3c4..83bf69f036c 100644 --- a/scripts/lib/shell-quotes.js +++ b/scripts/lib/shell-quotes.js @@ -218,4 +218,4 @@ function quotedRegionAt(input, idx) { return null; } -module.exports = { quotedRegions, quotedRegionAt, SHELL_RESERVED_WORDS }; +module.exports = { quotedRegions, quotedRegionAt, SHELL_RESERVED_WORDS, ASSIGNMENT_WORD }; diff --git a/tests/hooks/block-no-verify.test.js b/tests/hooks/block-no-verify.test.js index 8b4ae1d116d..762f6ed5f2f 100644 --- a/tests/hooks/block-no-verify.test.js +++ b/tests/hooks/block-no-verify.test.js @@ -355,12 +355,59 @@ if (test('allows a bypass phrase that a program run by find or fd searches for', } })) passed++; else failed++; -// A program named by an expansion is only known when the line runs. +// Printed text piped into something that runs what it reads is a command line. +if (test('blocks a quoted git piped into a program that runs what it reads', () => { + for (const command of [ + "echo 'git commit --no-verify -m x' | sh", + "printf '%s\\n' 'git push --no-verify' | bash -s", + "{ echo 'git commit --no-verify -m x'; } | sh", + "echo 'git push --no-verify' | xargs -I{} sh -c '{}'", + "echo 'require(\"child_process\").execSync(\"git push --no-verify\")' | node", + "echo 'git commit --no-verify -m x' |& sh", + "echo 'git commit --no-verify -m x' | $SHELL", + "echo 'git push --no-verify' | FOO=1 sh", + ]) { + const r = runHook({ tool_input: { command } }); + assert.strictEqual(r.code, 2, `expected exit 2 for ${command}, got ${r.code}`); + } +})) passed++; else failed++; + +if (test('allows a bypass phrase piped into a program that reads it as text', () => { + for (const command of [ + "echo 'git commit --no-verify' | grep -c verify", + "printf '%s' 'git push --no-verify' | node /tmp/x.js", + "grep -q 'git commit --no-verify' notes.md || sh setup.sh", + ]) { + const r = runHook({ tool_input: { command } }); + assert.strictEqual(r.code, 0, `expected exit 0 for ${command}, got ${r.code}: ${r.stderr}`); + } +})) passed++; else failed++; + +// A program named by an expansion is only known when the line runs, and a +// substitution runs or sources the text it produces. if (test('blocks a quoted git whose program is known only at run time', () => { for (const command of [ "$SHELL -c 'git commit --no-verify -m x'", "\"$SHELL\" -c 'git commit --no-verify -m x'", + "$(command -v sh) -c 'git commit --no-verify -m x'", + "`command -v bash` -c 'git push --no-verify'", "find . -exec $SHELL -c 'git commit --no-verify -m x' \\;", + "$(echo 'git commit --no-verify -m x')", + "source <(echo 'git commit --no-verify -m x')", + ". <(printf '%s' 'git push --no-verify')", + ]) { + const r = runHook({ tool_input: { command } }); + assert.strictEqual(r.code, 2, `expected exit 2 for ${command}, got ${r.code}`); + } +})) passed++; else failed++; + +if (test('blocks a quoted git that a shell builtin runs or keeps to run', () => { + for (const command of [ + "builtin eval 'git commit --no-verify -m x'", + "trap 'git push --no-verify' EXIT", + "noglob sh -c 'git commit --no-verify -m x'", + "nocorrect sh -c 'git push --no-verify'", + "alias gc='git commit --no-verify -m x'", ]) { const r = runHook({ tool_input: { command } }); assert.strictEqual(r.code, 2, `expected exit 2 for ${command}, got ${r.code}`); From 99b2d056e85841bbe31523b73e432c0778e8311a Mon Sep 17 00:00:00 2001 From: L4XB Date: Fri, 25 Sep 2026 02:48:50 +0200 Subject: [PATCH 09/14] fix(block-no-verify): end the pipe search where a statement ends Every later pipe counted, so `echo '...'; printf x | sh` was blocked although only `printf x` reaches `sh`. The end of a statement (`;`, a newline, `&&`, `||` or a background `&`) now ends the search when nothing before it can group the statement with later commands: a brace group, a subshell, a function body, a compound command or a substitution. The `&` of a redirection such as `2>&1` does not end a statement. A newline right after a pipe continues the pipeline, so a quoted git piped into a shell on the next line is now blocked as well. --- scripts/hooks/block-no-verify.js | 47 +++++++++++++++++++++++++++-- tests/hooks/block-no-verify.test.js | 33 ++++++++++++++++++++ 2 files changed, 78 insertions(+), 2 deletions(-) diff --git a/scripts/hooks/block-no-verify.js b/scripts/hooks/block-no-verify.js index b00d1127035..dcbf612b115 100644 --- a/scripts/hooks/block-no-verify.js +++ b/scripts/hooks/block-no-verify.js @@ -15,7 +15,7 @@ 'use strict'; -const { quotedRegionAt, ASSIGNMENT_WORD } = require('../lib/shell-quotes'); +const { quotedRegions, quotedRegionAt, SHELL_RESERVED_WORDS, ASSIGNMENT_WORD } = require('../lib/shell-quotes'); const MAX_STDIN = 1024 * 1024; let raw = ''; @@ -475,17 +475,58 @@ function readsCodeFromStdin(words) { return false; } +/** + * Whether the separator at `i` ends a statement instead of joining the next + * command to it: `;`, a newline, `&&`, `||` or a background `&`. A pipe (`|`, + * `|&`) joins, and so does the `&` of a redirection (`2>&1`, `>&2`, `&>`). + */ +function endsStatement(input, i) { + const char = input.charAt(i); + if (char === ';' || char === '\n') return true; + if (char === '|') return input.charAt(i + 1) === '|'; + if (char !== '&') return false; + const before = input.charAt(i - 1); + return before !== '>' && before !== '<' && before !== '|' && input.charAt(i + 1) !== '>'; +} + +/** + * Whether the command line before `end` holds anything that can carry the + * output of a finished statement into a later pipe: a brace group or + * subshell (`{ echo '...'; } | sh`), a function body called later on, a + * compound command (`if ...; fi | sh`) or a substitution. Quoted text does + * not count. + */ +function mayGroupStatements(input, end) { + let bare = ''; + let pos = 0; + for (const region of quotedRegions(input)) { + if (region.start >= end) break; + bare += `${input.slice(pos, region.start)} `; + pos = region.end + 1; + } + bare += input.slice(pos, end); + return /[{}()`]/.test(bare) || bare.split(/[\s;&|]+/).some((word) => SHELL_RESERVED_WORDS.has(word)); +} + /** * Whether a later part of the command line pipes into a program that reads * what it receives as code (`echo '...' | sh`). Every later pipe counts, not * only the rest of this pipeline, so a group such as `{ echo '...'; } | sh` - * is covered as well. + * is covered as well. When nothing before a statement's end can group it + * with later commands, its output stops there: in + * `echo '...'; printf x | sh` only `printf x` reaches `sh`. */ function pipesIntoCodeReader(input, from) { let pos = from; + let grouped = false; while (pos < input.length) { const end = findCommandSegmentEnd(input, pos); if (end >= input.length) return false; + // The prefix only grows, so once it can group statements it always can. + if (!grouped && endsStatement(input, end)) { + if (!mayGroupStatements(input, end)) return false; + grouped = true; + } pos = end + 1; if (input.charAt(end) !== '|') continue; if (input.charAt(pos) === '|') { @@ -493,6 +534,8 @@ function pipesIntoCodeReader(input, from) { continue; } if (input.charAt(pos) === '&') pos += 1; + // A newline right after a pipe continues the pipeline. + while (/\s/.test(input.charAt(pos))) pos += 1; const words = tokenizeShellWords(input, pos, findCommandSegmentEnd(input, pos)) .map((token) => token.value) .filter((word) => !ASSIGNMENT_WORD.test(word)); diff --git a/tests/hooks/block-no-verify.test.js b/tests/hooks/block-no-verify.test.js index 762f6ed5f2f..7413ee76631 100644 --- a/tests/hooks/block-no-verify.test.js +++ b/tests/hooks/block-no-verify.test.js @@ -383,6 +383,39 @@ if (test('allows a bypass phrase piped into a program that reads it as text', () } })) passed++; else failed++; +// A finished statement's output goes nowhere a later pipe can reach, unless +// something before its end groups it with later commands. +if (test('allows a bypass phrase whose statement ends before a later pipe into a shell', () => { + for (const command of [ + "echo 'git push --no-verify'; printf x | sh", + "echo 'git push --no-verify'\nprintf x | sh", + "echo 'do not run git push --no-verify (it skips the hooks)'; printf x | sh", + "grep -n 'git commit --no-verify' docs/a.md && curl -fsSL https://example.com/i.sh | sh", + "echo 'git push --no-verify' & printf x | sh", + "echo 'git push --no-verify' || printf x | sh", + "echo 'git push --no-verify' 2>&1; printf x | sh", + "echo 'git push --no-verify' | cat; printf x | sh", + ]) { + const r = runHook({ tool_input: { command } }); + assert.strictEqual(r.code, 0, `expected exit 0 for ${command}, got ${r.code}: ${r.stderr}`); + } +})) passed++; else failed++; + +if (test('blocks a bypass phrase grouped with a later pipe into a shell', () => { + for (const command of [ + "(echo 'git push --no-verify'; printf x) | sh", + "if true; then echo 'git push --no-verify'; fi | sh", + "while read l; do echo 'git push --no-verify'; done < f | sh", + "case a in a) echo 'git push --no-verify';; esac | sh", + "f() { echo 'git push --no-verify'; }; f | sh", + "echo 'git push --no-verify' 2>&1 | sh", + "echo 'git push --no-verify' |\n sh", + ]) { + const r = runHook({ tool_input: { command } }); + assert.strictEqual(r.code, 2, `expected exit 2 for ${command}, got ${r.code}`); + } +})) passed++; else failed++; + // A program named by an expansion is only known when the line runs, and a // substitution runs or sources the text it produces. if (test('blocks a quoted git whose program is known only at run time', () => { From 6181ae25f96dad4082bb1f601d99a37ebe7860f4 Mon Sep 17 00:00:00 2001 From: L4XB Date: Fri, 25 Sep 2026 03:11:42 +0200 Subject: [PATCH 10/14] fix(block-no-verify): do not take a brace inside a word for a group Any brace before a statement's end counted as grouping, so an earlier brace expansion kept the pipe search going: `mkdir -p /tmp/{a,b}; echo '...'; printf x | sh` was blocked, and so was a line with `${HOME}` in it. A brace group opens with `{` as a word of its own, which the reserved-word check already covers, so only parentheses and backticks are still matched as characters. --- scripts/hooks/block-no-verify.js | 6 ++++-- tests/hooks/block-no-verify.test.js | 3 +++ 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/scripts/hooks/block-no-verify.js b/scripts/hooks/block-no-verify.js index dcbf612b115..4ce22e81c83 100644 --- a/scripts/hooks/block-no-verify.js +++ b/scripts/hooks/block-no-verify.js @@ -494,7 +494,9 @@ function endsStatement(input, i) { * output of a finished statement into a later pipe: a brace group or * subshell (`{ echo '...'; } | sh`), a function body called later on, a * compound command (`if ...; fi | sh`) or a substitution. Quoted text does - * not count. + * not count, and neither does a brace inside a word, which is brace or + * parameter expansion (`/tmp/{a,b}`, `${HOME}`): a brace group opens with + * `{` as a word of its own. */ function mayGroupStatements(input, end) { let bare = ''; @@ -505,7 +507,7 @@ function mayGroupStatements(input, end) { pos = region.end + 1; } bare += input.slice(pos, end); - return /[{}()`]/.test(bare) || bare.split(/[\s;&|]+/).some((word) => SHELL_RESERVED_WORDS.has(word)); + return /[()`]/.test(bare) || bare.split(/[\s;&|]+/).some((word) => SHELL_RESERVED_WORDS.has(word)); } /** diff --git a/tests/hooks/block-no-verify.test.js b/tests/hooks/block-no-verify.test.js index 7413ee76631..013313aba73 100644 --- a/tests/hooks/block-no-verify.test.js +++ b/tests/hooks/block-no-verify.test.js @@ -390,6 +390,8 @@ if (test('allows a bypass phrase whose statement ends before a later pipe into a "echo 'git push --no-verify'; printf x | sh", "echo 'git push --no-verify'\nprintf x | sh", "echo 'do not run git push --no-verify (it skips the hooks)'; printf x | sh", + "mkdir -p /tmp/{a,b}; echo 'git push --no-verify'; printf x | sh", + "cd ${HOME}; echo 'git push --no-verify'; printf x | sh", "grep -n 'git commit --no-verify' docs/a.md && curl -fsSL https://example.com/i.sh | sh", "echo 'git push --no-verify' & printf x | sh", "echo 'git push --no-verify' || printf x | sh", @@ -408,6 +410,7 @@ if (test('blocks a bypass phrase grouped with a later pipe into a shell', () => "while read l; do echo 'git push --no-verify'; done < f | sh", "case a in a) echo 'git push --no-verify';; esac | sh", "f() { echo 'git push --no-verify'; }; f | sh", + "{ echo 'git push --no-verify';}|sh", "echo 'git push --no-verify' 2>&1 | sh", "echo 'git push --no-verify' |\n sh", ]) { From 0d96d747ebfcc206836e7c98a7028472f6a0a8c2 Mon Sep 17 00:00:00 2001 From: L4XB Date: Fri, 25 Sep 2026 04:55:59 +0200 Subject: [PATCH 11/14] fix(block-no-verify): check the command lines a sed script runs GNU sed runs a command line through a shell for an `s` command with the `e` flag, and for an `e` command. The quoted script of sed was data, so `printf x | sed 's/x/git commit --no-verify/e'` and `printf x | sed 'e git commit --no-verify'` were allowed; the second was blocked on main. Inside the script the flag is glued to the delimiter, so the replacement and the `e` argument are now checked as the command lines they are, and a pipe into sed with such a script counts as a pipe into something that runs what it reads. A sed script that only mentions a bypass flag, in a pattern or in a replacement it does not run, stays data. --- scripts/hooks/block-no-verify.js | 86 ++++++++++++++++++++++++++++- tests/hooks/block-no-verify.test.js | 33 +++++++++++ 2 files changed, 118 insertions(+), 1 deletion(-) diff --git a/scripts/hooks/block-no-verify.js b/scripts/hooks/block-no-verify.js index 4ce22e81c83..e939582a49f 100644 --- a/scripts/hooks/block-no-verify.js +++ b/scripts/hooks/block-no-verify.js @@ -462,15 +462,91 @@ function startsAtSubstitution(input, argv0Start) { return char === '(' && /[$<>]/.test(input.charAt(i - 1)); } +const SED_PROGRAMS = new Set(['sed', 'gsed']); + +/** + * Where a sed command letter can stand: the start of the script, or after a + * separator, a block brace, a negation or an address. + */ +const SED_COMMAND_START = /[\s;{}!$0-9/]/; + +/** + * One part of a sed `s` command, from `start` up to the next unescaped + * `delimiter`. An escaped delimiter stands for itself. + */ +function sedPart(script, start, delimiter) { + let text = ''; + for (let i = start; i < script.length; i++) { + const char = script[i]; + if (char === '\\' && i + 1 < script.length) { + text += script[i + 1] === delimiter ? delimiter : char + script[i + 1]; + i++; + continue; + } + if (char === delimiter) return { text, end: i }; + text += char; + } + return null; +} + +/** + * What a sed script runs through a shell, as far as its text shows it (GNU + * sed). An `s` command with the `e` flag runs the pattern space once the + * replacement is made, and an `e` command runs its argument, or the pattern + * space when it has none. `commands` holds the command text the script itself + * supplies; `runsInput` says the text sed reads is run too. + */ +function sedExecution(script) { + const commands = []; + let runsInput = false; + for (let i = 0; i < script.length; i++) { + const letter = script[i]; + if (letter !== 's' && letter !== 'e') continue; + if (i > 0 && !SED_COMMAND_START.test(script[i - 1])) continue; + if (letter === 'e') { + const command = /^e(?:[ \t]+([^\n]+)|[ \t]*(?=[\n;}]|$))/.exec(script.slice(i)); + if (!command) continue; + if (command[1] === undefined) runsInput = true; + else commands.push(command[1]); + continue; + } + const delimiter = script[i + 1]; + if (!delimiter || /[\w\s\\]/.test(delimiter)) continue; + const pattern = sedPart(script, i + 2, delimiter); + const replacement = pattern && sedPart(script, pattern.end + 1, delimiter); + if (!replacement) continue; + const flags = /^[gpiImMe0-9]*/.exec(script.slice(replacement.end + 1))[0]; + if (flags.includes('e')) { + commands.push(replacement.text); + runsInput = true; + } + i = replacement.end + flags.length; + } + return { commands, runsInput }; +} + +/** + * The commands the sed scripts in `input` run, taken from each quoted script + * whose statement is sed. A script that only mentions a bypass flag, in a + * pattern or a replacement it does not run, adds nothing. + */ +function sedExecutedCommands(input) { + return quotedRegions(input) + .filter((region) => SED_PROGRAMS.has(commandBasename(region.argv0))) + .flatMap((region) => sedExecution(input.slice(region.start + 1, region.end)).commands); +} + /** * Whether a program reads the text piped into it as code: a shell or command * wrapper (`| sh`, `| xargs sh -c`), a runtime with no script operand of its - * own (`| node`, `| python3 -`), or a program named by an expansion. + * own (`| node`, `| python3 -`), sed with a script that runs its input + * (`| sed e`), or a program named by an expansion. */ function readsCodeFromStdin(words) { if (/[$`]/.test(words[0])) return true; const base = commandBasename(words[0]); if (COMMAND_WRAPPERS.has(base)) return true; + if (SED_PROGRAMS.has(base)) return words.slice(1).some((word) => sedExecution(word).runsInput); if (CODE_EVALUATORS.has(base)) return words.slice(1).every((word) => word.startsWith('-')); return false; } @@ -774,6 +850,14 @@ function hasHooksPathOverride(input, detected) { * Check a command string for git hook bypass attempts. */ function checkCommand(input) { + // sed runs these through a shell, and inside its script they are glued to + // the delimiters (`s/x/git push --no-verify/e`), so they are checked as the + // command lines they are. + for (const command of sedExecutedCommands(input)) { + const result = checkCommand(command); + if (result.blocked) return result; + } + let start = 0; while (start < input.length) { diff --git a/tests/hooks/block-no-verify.test.js b/tests/hooks/block-no-verify.test.js index 013313aba73..f333240a9ac 100644 --- a/tests/hooks/block-no-verify.test.js +++ b/tests/hooks/block-no-verify.test.js @@ -452,6 +452,39 @@ if (test('blocks a quoted git that a shell builtin runs or keeps to run', () => // awk takes its program as the first operand, without an eval flag, and // expect runs a Tcl script given with -c; both can spawn git. +// GNU sed runs a command line through a shell for an `s` command with the `e` +// flag and for an `e` command, so what those run is checked, while a sed +// script that only mentions a bypass flag stays data. +if (test('blocks a git bypass that a sed script runs', () => { + for (const command of [ + "printf x | sed 's/x/git commit --no-verify/e'", + "printf x | sed -e 's/x/git commit --no-verify/e'", + "printf x | sed --expression='s/x/git push --no-verify/e'", + "printf x | sed 's|x|git push --no-verify|e'", + "printf x | sed 'e git commit --no-verify'", + "echo 'git push --no-verify' | sed e", + "echo 'git push --no-verify' | sed 's/^//e'", + ]) { + const r = runHook({ tool_input: { command } }); + assert.strictEqual(r.code, 2, `expected exit 2 for ${command}, got ${r.code}`); + } +})) passed++; else failed++; + +if (test('allows a sed script that only mentions a bypass flag', () => { + for (const command of [ + "sed -i 's/git commit --no-verify/git commit/' notes.md", + "sed -n '/git push --no-verify/p' docs/hooks.md", + "echo 'git push --no-verify' | sed 's/push/pull/'", + "printf x | sed 's/x/git status/e'", + "sed -i 's/use git commit --no-verify here/use git commit here/' README.md", + "sed -n '/use git commit --no-verify here/p' README.md", + "grep -F 's/x/git push --no-verify/e' notes.md", + ]) { + const r = runHook({ tool_input: { command } }); + assert.strictEqual(r.code, 0, `expected exit 0 for ${command}, got ${r.code}: ${r.stderr}`); + } +})) passed++; else failed++; + if (test('blocks a git bypass in awk program source and an expect -c script', () => { for (const command of [ "awk 'BEGIN { system(\"git commit --no-verify -m x\") }'", From 58a34720cc678e59ad3137e4c0b9c878001cb51e Mon Sep 17 00:00:00 2001 From: L4XB Date: Fri, 25 Sep 2026 06:24:46 +0200 Subject: [PATCH 12/14] refactor(shell-quotes): record where each statement's argv0 starts The scanner already finds every statement's argv0, including statements inside a substitution, but kept it only for the quoted regions. commandStatements() returns all of them, so a caller can find a statement that holds no quoted text at all. --- scripts/lib/shell-quotes.js | 45 ++++++++++++++++++++++++++----------- 1 file changed, 32 insertions(+), 13 deletions(-) diff --git a/scripts/lib/shell-quotes.js b/scripts/lib/shell-quotes.js index 83bf69f036c..2077e11d3e6 100644 --- a/scripts/lib/shell-quotes.js +++ b/scripts/lib/shell-quotes.js @@ -12,7 +12,8 @@ * (its own statements and quotes) until the matching `)` / backtick, after * which the string resumes as a new region. Both halves are flagged * `substitution`. Regions are appended only once complete, in order, so they - * are disjoint and sorted. The result is cached per input, so a command line + * are disjoint and sorted. The same pass records where each statement's argv0 + * starts, quoted or not. The result is cached per input, so a command line * holding thousands of quoted tokens is scanned once. */ @@ -28,11 +29,12 @@ const ASSIGNMENT_WORD = /^[A-Za-z_][A-Za-z0-9_]*=/; // Unquoted characters that start a new statement (or a nested command). const STATEMENT_SEPARATORS = new Set([';', '|', '&', '\n', '(', ')', '`']); -let cache = { input: null, regions: [] }; +let cache = { input: null, regions: [], statements: [] }; function createState() { return { regions: [], + statements: [], suspended: [], quote: null, escaped: false, @@ -60,6 +62,7 @@ function endWord(state) { ) { state.argv0 = state.word; state.argv0Start = state.wordStart; + state.statements.push({ argv0: state.argv0, argv0Start: state.argv0Start }); } state.word = ''; state.inWord = false; @@ -168,14 +171,8 @@ function scanBareChar(state, index, char) { return 1; } -/** - * Every quoted region of `input`, sorted by start and disjoint. - * - * @param {string} input - * @returns {Array<{start: number, end: number, quote: string, argv0: string, argv0Start: number, substitution: boolean}>} - */ -function quotedRegions(input) { - if (cache.input === input) return cache.regions; +function scan(input) { + if (cache.input === input) return cache; const state = createState(); for (let i = 0; i < input.length; ) { const char = input.charAt(i); @@ -189,8 +186,30 @@ function quotedRegions(input) { i += state.quote ? scanQuotedChar(state, input, i) : scanBareChar(state, i, char); } if (state.open !== null) state.regions.push({ ...state.open, end: input.length }); - cache = { input, regions: state.regions }; - return state.regions; + cache = { input, regions: state.regions, statements: state.statements }; + return cache; +} + +/** + * Every quoted region of `input`, sorted by start and disjoint. + * + * @param {string} input + * @returns {Array<{start: number, end: number, quote: string, argv0: string, argv0Start: number, substitution: boolean}>} + */ +function quotedRegions(input) { + return scan(input).regions; +} + +/** + * Every statement of `input` whose argv0 ends before the input does, with + * the offset where that argv0 starts: top-level statements and those inside a + * substitution alike. + * + * @param {string} input + * @returns {Array<{argv0: string, argv0Start: number}>} + */ +function commandStatements(input) { + return scan(input).statements; } /** @@ -218,4 +237,4 @@ function quotedRegionAt(input, idx) { return null; } -module.exports = { quotedRegions, quotedRegionAt, SHELL_RESERVED_WORDS, ASSIGNMENT_WORD }; +module.exports = { quotedRegions, quotedRegionAt, commandStatements, SHELL_RESERVED_WORDS, ASSIGNMENT_WORD }; From 77cc9313883283c05fd28202a2c7645c768fa9d7 Mon Sep 17 00:00:00 2001 From: L4XB Date: Fri, 25 Sep 2026 06:24:46 +0200 Subject: [PATCH 13/14] fix(block-no-verify): read sed's arguments and script as GNU sed does The sed check read every quoted sed operand as a script and scanned it for an `s` or `e` letter after a separator. So an input file named like a command, and the text an `a`, `i` or `c` command adds or a comment, were blocked, while an `s` command with a letter as its delimiter (`sxfooxgit push --no-verifyxe`) was not checked at all. - The scripts are taken as GNU sed's option parser takes them: every -e/--expression value (long option prefixes, attached values, -ie as -i with a suffix), or else the first operand. Other operands are input files. When the shell may still change the words ($VAR, a substitution), every operand is checked, each on its own. - The script is read command by command: addresses, `!`, text of a/i/c/e up to an unescaped newline, comments, labels and file names, and `s`/`y` with any delimiter. An escaped character in the command text stands for itself, as it does when sed runs it. - sed statements are found wherever they start, not only through their quoted text, so an unquoted script and sed behind a wrapper (sudo) are checked too. --- scripts/hooks/block-no-verify.js | 285 ++++++++++++++++++++++++---- tests/hooks/block-no-verify.test.js | 46 +++++ 2 files changed, 294 insertions(+), 37 deletions(-) diff --git a/scripts/hooks/block-no-verify.js b/scripts/hooks/block-no-verify.js index e939582a49f..1fc2aaa419b 100644 --- a/scripts/hooks/block-no-verify.js +++ b/scripts/hooks/block-no-verify.js @@ -15,7 +15,13 @@ 'use strict'; -const { quotedRegions, quotedRegionAt, SHELL_RESERVED_WORDS, ASSIGNMENT_WORD } = require('../lib/shell-quotes'); +const { + quotedRegions, + quotedRegionAt, + commandStatements, + SHELL_RESERVED_WORDS, + ASSIGNMENT_WORD, +} = require('../lib/shell-quotes'); const MAX_STDIN = 1024 * 1024; let raw = ''; @@ -465,14 +471,87 @@ function startsAtSubstitution(input, argv0Start) { const SED_PROGRAMS = new Set(['sed', 'gsed']); /** - * Where a sed command letter can stand: the start of the script, or after a - * separator, a block brace, a negation or an address. + * The arguments sed receives in a statement, or null when the statement does + * not run sed: `sed ARGS`, or sed behind a wrapper (`sudo sed ARGS`). */ -const SED_COMMAND_START = /[\s;{}!$0-9/]/; +function sedArguments(words) { + const base = commandBasename(words[0]); + if (SED_PROGRAMS.has(base)) return words.slice(1); + if (!COMMAND_WRAPPERS.has(base)) return null; + const at = words.findIndex((word) => SED_PROGRAMS.has(commandBasename(word))); + return at === -1 ? null : words.slice(at + 1); +} + +/** + * The scripts in sed's arguments, read as GNU sed's option parser reads them: + * each `-e`/`--expression` value, or else the first operand. The other + * operands are input files, and a script named with `-f` is not on the line. + * When the shell may still change the words (`$OPTS`, a substitution), every + * operand may be the script. + */ +function sedScripts(args, everyOperand = false) { + const scripts = []; + const operands = []; + let scriptOption = false; + for (let i = 0; i < args.length; i++) { + const arg = args[i]; + if (arg === '--') { + operands.push(...args.slice(i + 1)); + break; + } + if (arg.startsWith('--')) { + // A long option may be shortened to any prefix that names only it. + const [name, value] = arg.slice(2).split(/=(.*)/s); + if ('expression'.startsWith(name)) { + scripts.push(value ?? args[++i] ?? ''); + scriptOption = true; + } else if (name.length >= 2 && 'file'.startsWith(name)) { + scriptOption = true; + if (value === undefined) i++; + } else if ('line-length'.startsWith(name) && value === undefined) { + i++; + } + continue; + } + if (arg.startsWith('-') && arg !== '-') { + for (let j = 1; j < arg.length; j++) { + const option = arg[j]; + // -i takes the rest of the word as its backup suffix: `-ie` is -i with suffix e. + if (option === 'i') break; + if (option !== 'e' && option !== 'f' && option !== 'l') continue; + const value = j + 1 < arg.length ? arg.slice(j + 1) : args[++i]; + if (option === 'e') scripts.push(value ?? ''); + if (option !== 'l') scriptOption = true; + break; + } + continue; + } + operands.push(arg); + } + if (everyOperand) return [...scripts, ...operands]; + if (!scriptOption && operands.length > 0) scripts.push(operands[0]); + return scripts; +} + +/** + * The texts to read as sed scripts, each on its own. sed joins its scripts + * with newlines into one; when the shell may still change the words, every + * operand is read as a script of its own. + */ +function sedScriptTexts(args, opaque) { + return opaque ? sedScripts(args, true) : [sedScripts(args).join('\n')]; +} + +/** Past the spaces and tabs at `i`. */ +function skipBlanks(script, i) { + while (script[i] === ' ' || script[i] === '\t') i++; + return i; +} /** - * One part of a sed `s` command, from `start` up to the next unescaped - * `delimiter`. An escaped delimiter stands for itself. + * One part of a sed `s` or `y` command or of a regex address, from `start` up + * to the next unescaped `delimiter`. An escaped delimiter stands for itself. + * sed rejects a part that an unescaped newline cuts short. */ function sedPart(script, start, delimiter) { let text = ''; @@ -484,56 +563,185 @@ function sedPart(script, start, delimiter) { continue; } if (char === delimiter) return { text, end: i }; + if (char === '\n') return null; text += char; } return null; } /** - * What a sed script runs through a shell, as far as its text shows it (GNU - * sed). An `s` command with the `e` flag runs the pattern space once the - * replacement is made, and an `e` command runs its argument, or the pattern - * space when it has none. `commands` holds the command text the script itself - * supplies; `runsInput` says the text sed reads is run too. + * Past the sed address at `i`, if there is one: a line number (`3`, `0~4`), + * `$`, a regex (`/re/I`, `\%re%`) or, as the second address, `+N` or `~N`. + */ +function sedAddressEnd(script, i, second) { + const char = script[i]; + if (char === '/' || char === '\\') { + const delimiter = char === '\\' ? script[i + 1] : char; + const regex = sedPart(script, char === '\\' ? i + 2 : i + 1, delimiter); + if (regex === null) return script.length; + i = skipBlanks(script, regex.end + 1); + while (script[i] === 'I' || script[i] === 'M') i = skipBlanks(script, i + 1); + return i; + } + if (char === '$') return i + 1; + if (!/[0-9]/.test(char || '') && !(second && (char === '+' || char === '~'))) return i; + if (!/[0-9]/.test(char)) i = skipBlanks(script, i + 1); + while (/[0-9]/.test(script[i] || '')) i++; + const step = skipBlanks(script, i); + if (second || script[step] !== '~') return i; + i = skipBlanks(script, step + 1); + while (/[0-9]/.test(script[i] || '')) i++; + return i; +} + +/** + * The end of the text of an `a`, `i`, `c` or `e` command: the first newline + * that no backslash escapes. A backslash before a newline carries the text on. + */ +function sedTextEnd(script, i) { + for (; i < script.length; i++) { + if (script[i] === '\\') i++; + else if (script[i] === '\n') return i; + } + return script.length; +} + +/** + * sed's text as the shell running it reads it: escaped characters stand for + * themselves, and a backslash before a newline joins the two lines. + */ +function sedUnescape(text) { + return text.replace(/\\\n/g, '').replace(/\\([\s\S])/g, (match, char) => (char === 'n' ? '\n' : char)); +} + +// Commands whose argument runs to the end of the line: a comment and a file name. +const SED_LINE_COMMANDS = new Set(['#', 'r', 'R', 'w', 'W']); +// Commands that take text, which the next newline without a backslash ends. +const SED_TEXT_COMMANDS = new Set(['a', 'i', 'c', 'e']); +// Commands that take a label or a version, which a blank or `;` ends. +const SED_LABEL_COMMANDS = new Set([':', 'b', 't', 'T', 'v']); + +/** + * What a sed script runs through a shell (GNU sed). An `s` command with the + * `e` flag runs the pattern space once the replacement is made, and an `e` + * command runs its text, or the pattern space when it has none. The script is + * read command by command, as sed reads it, so the text `a`, `i` and `c` add, + * a comment, a label or a file name is never taken for a command. `commands` + * holds the command text the script itself supplies; `runsInput` says the text + * sed reads is run too. */ function sedExecution(script) { const commands = []; let runsInput = false; - for (let i = 0; i < script.length; i++) { - const letter = script[i]; - if (letter !== 's' && letter !== 'e') continue; - if (i > 0 && !SED_COMMAND_START.test(script[i - 1])) continue; - if (letter === 'e') { - const command = /^e(?:[ \t]+([^\n]+)|[ \t]*(?=[\n;}]|$))/.exec(script.slice(i)); - if (!command) continue; - if (command[1] === undefined) runsInput = true; - else commands.push(command[1]); + let i = 0; + while (i < script.length) { + if (/[\s;]/.test(script[i])) { + i++; continue; } - const delimiter = script[i + 1]; - if (!delimiter || /[\w\s\\]/.test(delimiter)) continue; - const pattern = sedPart(script, i + 2, delimiter); - const replacement = pattern && sedPart(script, pattern.end + 1, delimiter); - if (!replacement) continue; - const flags = /^[gpiImMe0-9]*/.exec(script.slice(replacement.end + 1))[0]; - if (flags.includes('e')) { - commands.push(replacement.text); - runsInput = true; + i = skipBlanks(script, sedAddressEnd(script, i, false)); + if (script[i] === ',') i = skipBlanks(script, sedAddressEnd(script, skipBlanks(script, i + 1), true)); + while (script[i] === '!') i = skipBlanks(script, i + 1); + const command = script[i]; + i++; + if (SED_LINE_COMMANDS.has(command)) { + const end = script.indexOf('\n', i); + i = end === -1 ? script.length : end; + } else if (SED_TEXT_COMMANDS.has(command)) { + i = skipBlanks(script, i); + const opensText = script[i] === '\\'; + if (opensText) i += script[i + 1] === '\n' ? 2 : 1; + const end = sedTextEnd(script, i); + if (command === 'e') { + const text = sedUnescape(script.slice(i, end)).trim(); + if (text === '') runsInput = true; + else commands.push(text); + } + i = end; + } else if (SED_LABEL_COMMANDS.has(command)) { + i = skipBlanks(script, i); + while (i < script.length && !/[\s;]/.test(script[i])) i++; + } else if (command === 's' || command === 'y') { + const delimiter = script[i]; + const pattern = delimiter === undefined ? null : sedPart(script, i + 1, delimiter); + const replacement = pattern && sedPart(script, pattern.end + 1, delimiter); + // sed rejects a script with an unfinished command and runs none of it. + if (!replacement) break; + i = replacement.end + 1; + if (command === 'y') continue; + const flags = /^[gpiImMe0-9]*/.exec(script.slice(i))[0]; + i += flags.length; + if (script[i] === 'w') { + const end = script.indexOf('\n', i); + i = end === -1 ? script.length : end; + } + if (flags.includes('e')) { + commands.push(sedUnescape(replacement.text)); + runsInput = true; + } } - i = replacement.end + flags.length; } return { commands, runsInput }; } /** - * The commands the sed scripts in `input` run, taken from each quoted script - * whose statement is sed. A script that only mentions a bypass flag, in a - * pattern or a replacement it does not run, adds nothing. + * Where the statement that starts at `start` ends: at an unquoted `;`, `|`, + * `&` or newline, or at a `)` that closes the substitution or subshell around + * it. A substitution inside the statement is part of it. `opaque` says the + * shell may still change the statement's words: a parameter expansion or a + * substitution in them. + */ +function statementBounds(input, start) { + let quote = null; + let opaque = false; + let depth = 0; + let backtick = false; + for (let i = start; i < input.length; i++) { + const char = input.charAt(i); + if (quote === "'") { + if (char === "'") quote = null; + continue; + } + if (char === '\\') { + i++; + continue; + } + if (char === '$' && /[\w{(@*#?$!-]/.test(input.charAt(i + 1))) opaque = true; + if (char === '`') { + // A backtick that closes a substitution around the statement reads as + // opening one, so the rest of the line counts: more operands, not fewer. + opaque = true; + backtick = !backtick; + } else if (quote === '"') { + if (char === '"') quote = null; + } else if (char === "'" || char === '"') { + quote = char; + } else if (char === '(') { + opaque = true; + depth++; + } else if (char === ')') { + if (depth === 0) return { end: i, opaque }; + depth--; + } else if (depth === 0 && !backtick && /[;|&\n]/.test(char)) { + return { end: i, opaque }; + } + } + return { end: input.length, opaque }; +} + +/** + * The commands the sed scripts in `input` run, from every statement that runs + * sed. A script that only mentions a bypass flag, in a pattern or a text it + * does not run, adds nothing, and neither does an input file name. */ function sedExecutedCommands(input) { - return quotedRegions(input) - .filter((region) => SED_PROGRAMS.has(commandBasename(region.argv0))) - .flatMap((region) => sedExecution(input.slice(region.start + 1, region.end)).commands); + return commandStatements(input).flatMap(({ argv0Start }) => { + const { end, opaque } = statementBounds(input, argv0Start); + const words = tokenizeShellWords(input, argv0Start, end).map((token) => token.value); + const args = sedArguments(words); + if (args === null) return []; + return sedScriptTexts(args, opaque).flatMap((script) => sedExecution(script).commands); + }); } /** @@ -546,7 +754,10 @@ function readsCodeFromStdin(words) { if (/[$`]/.test(words[0])) return true; const base = commandBasename(words[0]); if (COMMAND_WRAPPERS.has(base)) return true; - if (SED_PROGRAMS.has(base)) return words.slice(1).some((word) => sedExecution(word).runsInput); + if (SED_PROGRAMS.has(base)) { + const opaque = words.some((word) => /[$`]/.test(word)); + return sedScriptTexts(words.slice(1), opaque).some((script) => sedExecution(script).runsInput); + } if (CODE_EVALUATORS.has(base)) return words.slice(1).every((word) => word.startsWith('-')); return false; } diff --git a/tests/hooks/block-no-verify.test.js b/tests/hooks/block-no-verify.test.js index f333240a9ac..5d63e867f2e 100644 --- a/tests/hooks/block-no-verify.test.js +++ b/tests/hooks/block-no-verify.test.js @@ -464,12 +464,58 @@ if (test('blocks a git bypass that a sed script runs', () => { "printf x | sed 'e git commit --no-verify'", "echo 'git push --no-verify' | sed e", "echo 'git push --no-verify' | sed 's/^//e'", + // Any character but a backslash or a newline can delimit an `s` command. + "printf foo | sed 'sxfooxgit push --no-verifyxe'", + // sed reads an escaped character in a replacement as that character. + "printf x | sed 's/x/git\\ push\\ --no-verify/e'", + // The script is read wherever sed takes it from. + 'printf x | sed s/x/git\\ push\\ --no-verify/e', + 'printf x | sed -es/x/git\\ push\\ --no-verify/e', + "printf x | sed --expr='s/x/git push --no-verify/e'", + "sed -n -- 'e git push --no-verify' notes.md", + "sed notes.md -e 'e git push --no-verify'", + "sed -l 80 'e git push --no-verify' notes.md", + // -ie is -i with the backup suffix e, so the operand is the script. + "sed -ie -n 'e git push --no-verify' notes.md", + "printf x | sudo sed 's/x/git push --no-verify/e'", + "printf x | sed -n '/x/!d; e git push --no-verify'", + // $EXPR may be an option such as -n, and then the quoted operand is the script. + "sed \"$EXPR\" 'e git push --no-verify' notes.md", + // So may the output of a substitution. + "printf x | sed `printf %s -n` 's/x/git push --no-verify/e'", + "printf x | sed $(printf %s -n) 's/x/git push --no-verify/e'", ]) { const r = runHook({ tool_input: { command } }); assert.strictEqual(r.code, 2, `expected exit 2 for ${command}, got ${r.code}`); } })) passed++; else failed++; +// sed reads its script command by command: the text `a`, `i` and `c` add, a +// comment, a label or a file name is never a command, and an operand after +// the script, or after an -e or -f option, is an input file. +if (test('allows sed input files, added text and comments that mention a bypass', () => { + for (const command of [ + "sed 's/x/y/' 'e git commit --no-verify'", + "sed -e 's/x/y/' 'e git commit --no-verify'", + "sed --expression='s/x/y/' 'e git push --no-verify'", + "sed -f fix.sed 'e git push --no-verify'", + "sed --file=fix.sed 'e git push --no-verify'", + "sed -i '1i e git push --no-verify is unsafe' README.md", + "sed -i '$a e git push --no-verify is unsafe' README.md", + "sed -i '/hooks/c e git push --no-verify is unsafe' README.md", + "sed -n '# e git push --no-verify' README.md", + // Addresses that match the text of a sed command that runs git. + "sed -n '/s|x|git push --no-verify|e/p' notes.md", + "sed -n '\\%s/x/git push --no-verify/e%p' notes.md", + "sed -n 'w e git push --no-verify' notes.md", + // Labels named e, which the t command branches to. + "echo 'git push --no-verify' | sed -e :e -e '$!N;s/\\n/ /;te'", + ]) { + const r = runHook({ tool_input: { command } }); + assert.strictEqual(r.code, 0, `expected exit 0 for ${command}, got ${r.code}: ${r.stderr}`); + } +})) passed++; else failed++; + if (test('allows a sed script that only mentions a bypass flag', () => { for (const command of [ "sed -i 's/git commit --no-verify/git commit/' notes.md", From 27aa8b359646c53b5b7aedd7aeb4ac1f3a80a4f3 Mon Sep 17 00:00:00 2001 From: L4XB Date: Fri, 25 Sep 2026 07:44:58 +0200 Subject: [PATCH 14/14] refactor(block-no-verify): move the sed, statement and code-receiver logic into scripts/lib The hook had grown to 1,172 lines, over the 800-line file limit in AGENTS.md, and sedExecution to 53 lines, over the 50-line function limit. Its helpers move into three focused modules: - scripts/lib/sed-script.js: which of sed's arguments are scripts, and what a script runs. sedExecution is now a loop over readSedCommand, with readSedText, readSedSubstitution and sedCommandStart. - scripts/lib/shell-statements.js: where a statement ends and what can tie it to later commands. - scripts/lib/code-receivers.js: which programs run a quoted argument or their input as code. The hook is 693 lines. Behaviour is unchanged: the hook's 59 tests pass, and its verdicts on 76 sed and pipeline commands match the previous commit's. Each module has a test file in tests/lib, and so does shell-quotes.js, which this pull request added without one. --- scripts/hooks/block-no-verify.js | 495 +---------------------------- scripts/lib/code-receivers.js | 194 +++++++++++ scripts/lib/sed-script.js | 238 ++++++++++++++ scripts/lib/shell-statements.js | 104 ++++++ tests/lib/code-receivers.test.js | 69 ++++ tests/lib/sed-script.test.js | 89 ++++++ tests/lib/shell-quotes.test.js | 57 ++++ tests/lib/shell-statements.test.js | 77 +++++ 8 files changed, 836 insertions(+), 487 deletions(-) create mode 100644 scripts/lib/code-receivers.js create mode 100644 scripts/lib/sed-script.js create mode 100644 scripts/lib/shell-statements.js create mode 100644 tests/lib/code-receivers.test.js create mode 100644 tests/lib/sed-script.test.js create mode 100644 tests/lib/shell-quotes.test.js create mode 100644 tests/lib/shell-statements.test.js diff --git a/scripts/hooks/block-no-verify.js b/scripts/hooks/block-no-verify.js index 1fc2aaa419b..4fb7c548a01 100644 --- a/scripts/hooks/block-no-verify.js +++ b/scripts/hooks/block-no-verify.js @@ -15,13 +15,15 @@ 'use strict'; +const { quotedRegionAt, commandStatements, ASSIGNMENT_WORD } = require('../lib/shell-quotes'); const { - quotedRegions, - quotedRegionAt, - commandStatements, - SHELL_RESERVED_WORDS, - ASSIGNMENT_WORD, -} = require('../lib/shell-quotes'); + startsAtSubstitution, + statementBounds, + endsStatement, + mayGroupStatements, +} = require('../lib/shell-statements'); +const { receivesAsData, sedArguments, readsCodeFromStdin } = require('../lib/code-receivers'); +const { sedScriptTexts, sedExecution } = require('../lib/sed-script'); const MAX_STDIN = 1024 * 1024; let raw = ''; @@ -43,63 +45,6 @@ const GIT_COMMANDS_WITH_NO_VERIFY = [ */ const VALID_BEFORE_GIT = ' \t\n\r;&|$`(<{!"\']/.~\\'; -/** - * Programs that execute a quoted argument as a shell command line, so a - * `git` inside one of their quoted arguments is a command that must still - * be checked (`sh -c "git commit --no-verify"`, `sudo`, `xargs`, `env`...). - * For any other argv0 (`node cli.js 'git commit --no-verify'`, - * `printf '%s' '...'`, `grep -n '...' docs.md`) a quoted string is data, - * unless it is a runtime given an eval flag (see CODE_EVALUATORS). - */ -const COMMAND_WRAPPERS = new Set([ - 'sh', - 'bash', - 'zsh', - 'dash', - 'ksh', - 'fish', - 'busybox', - 'eval', - 'exec', - 'command', - 'xargs', - 'sudo', - 'doas', - 'su', - 'env', - 'nice', - 'ionice', - 'nohup', - 'timeout', - 'time', - 'watch', - 'flock', - 'ssh', - 'script', - 'csh', - 'tcsh', - 'setsid', - 'stdbuf', - 'taskset', - 'chrt', - 'unshare', - 'chroot', - 'runuser', - 'npx', - 'bunx', - 'pnpx', - // Runs a command line for each input line; find and fd, which do so only - // after one of their exec flags, are in LAUNCHERS. - 'parallel', - // Shell builtins and zsh precommand modifiers that run a command line, or - // keep one to run later (`trap '...' EXIT`, `alias x='...'`). - 'builtin', - 'noglob', - 'nocorrect', - 'trap', - 'alias', -]); - // Git config section and variable names are case-insensitive // (subsection names are case-sensitive but core.hooksPath has none), // so we normalize the candidate token to lowercase before matching. @@ -358,377 +303,6 @@ function isInComment(input, idx) { return false; } -/** - * Strip a leading path and a trailing `.exe` from a command word. - */ -function commandBasename(word) { - return String(word || '') - .replace(/^.*[\\/]/, '') - .replace(/\.exe$/i, '') - .toLowerCase(); -} - -/** - * Runtimes that run a quoted argument as program source, each with the - * flags that do it: `node -e`, `python3 -c`, `perl -E`, `php -r`, - * `deno eval`. That source can spawn git itself, so it stays subject to the - * guard. The same runtime without one of its own eval flags receives a - * script path and arguments, which are data (`node cli.js 'git commit - * --no-verify'`). - * - * The flags are per runtime because the same letter means different things: - * node's `-r` preloads a module and leaves the rest of the command line as - * ordinary arguments, while php's `-r` is how php is handed code. - */ -const CODE_EVALUATORS = new Map([ - ['node', ['-e', '--eval', '-p', '--print']], - ['nodejs', ['-e', '--eval', '-p', '--print']], - ['bun', ['-e', '--eval', '-p', '--print']], - ['deno', ['-e', '--eval', 'eval']], - ['python', ['-c']], - ['python2', ['-c']], - ['python3', ['-c']], - ['pythonw', ['-c']], - ['perl', ['-e', '-E']], - ['ruby', ['-e']], - ['php', ['-r']], - ['lua', ['-e']], - ['luajit', ['-e']], - ['rscript', ['-e']], - ['osascript', ['-e']], - ['groovy', ['-e']], - ['julia', ['-e', '-E']], - ['elixir', ['-e']], - ['erl', ['-eval']], - ['expect', ['-c']], -]); - -/** - * Launchers that run another program given after one of their flags: - * `find . -exec CMD ARGS \;`, `fd -x CMD ARGS`. A quoted argument of the - * launched program is judged as that program's own, so `-exec grep '...'` - * searches and `-exec sh -c '...'` runs. After find's `;` or `{} +` the - * arguments are find's again. - */ -const LAUNCHERS = new Map([ - ['find', ['-exec', '-execdir', '-ok', '-okdir']], - ['fd', ['-x', '--exec', '-X', '--exec-batch']], - ['fdfind', ['-x', '--exec', '-X', '--exec-batch']], -]); - -const EXEC_TERMINATORS = new Set(['\\;', "';'", '";"']); - -/** - * Runtimes whose first operand is itself program source, with no eval flag: - * `awk 'BEGIN { system("git commit --no-verify") }'` runs git. Every quoted - * argument they receive stays subject to the guard, at the cost of also - * checking an awk pattern that merely mentions a bypass flag. - */ -const SOURCE_OPERAND_RUNTIMES = new Set(['awk', 'gawk', 'mawk', 'nawk']); - -/** - * Whether a quoted argument is data for the program that receives it. - * `words` runs from that program's name up to the argument. An eval flag is - * matched as a whole word, or as the `=` form of itself, so a path that - * happens to end in one of them cannot qualify. - */ -function receivesAsData(words) { - // A program named by an expansion is only known when the line runs. - if (/[$`]/.test(words[0])) return false; - const base = commandBasename(words[0]); - if (base === 'git' || COMMAND_WRAPPERS.has(base) || SOURCE_OPERAND_RUNTIMES.has(base)) return false; - const launchFlags = LAUNCHERS.get(base); - if (launchFlags !== undefined) { - const at = words.findLastIndex((word) => launchFlags.includes(word)); - if (at === -1) return true; - const launched = words.slice(at + 1); - if (launched.some((word, i) => EXEC_TERMINATORS.has(word) || (word === '+' && launched[i - 1] === '{}'))) { - return true; - } - // The quoted argument is the launched program's name itself. - if (launched.length === 0) return false; - return receivesAsData([launched[0].replace(/['"\\]/g, ''), ...launched.slice(1)]); - } - const flags = CODE_EVALUATORS.get(base); - if (flags === undefined) return true; - return !words.some((word) => flags.some((flag) => word === flag || word.startsWith(`${flag}=`))); -} - -/** - * Whether a statement's first word sits right inside or right after a - * substitution. `$(echo '...')` runs what echo prints, `source <(echo '...')` - * reads it as a script, and in `$(command -v sh) -c '...'` the program is only - * known when the line runs. - */ -function startsAtSubstitution(input, argv0Start) { - let i = argv0Start - 1; - while (i >= 0 && /\s/.test(input.charAt(i))) i--; - const char = input.charAt(i); - if (char === '`' || char === ')') return true; - return char === '(' && /[$<>]/.test(input.charAt(i - 1)); -} - -const SED_PROGRAMS = new Set(['sed', 'gsed']); - -/** - * The arguments sed receives in a statement, or null when the statement does - * not run sed: `sed ARGS`, or sed behind a wrapper (`sudo sed ARGS`). - */ -function sedArguments(words) { - const base = commandBasename(words[0]); - if (SED_PROGRAMS.has(base)) return words.slice(1); - if (!COMMAND_WRAPPERS.has(base)) return null; - const at = words.findIndex((word) => SED_PROGRAMS.has(commandBasename(word))); - return at === -1 ? null : words.slice(at + 1); -} - -/** - * The scripts in sed's arguments, read as GNU sed's option parser reads them: - * each `-e`/`--expression` value, or else the first operand. The other - * operands are input files, and a script named with `-f` is not on the line. - * When the shell may still change the words (`$OPTS`, a substitution), every - * operand may be the script. - */ -function sedScripts(args, everyOperand = false) { - const scripts = []; - const operands = []; - let scriptOption = false; - for (let i = 0; i < args.length; i++) { - const arg = args[i]; - if (arg === '--') { - operands.push(...args.slice(i + 1)); - break; - } - if (arg.startsWith('--')) { - // A long option may be shortened to any prefix that names only it. - const [name, value] = arg.slice(2).split(/=(.*)/s); - if ('expression'.startsWith(name)) { - scripts.push(value ?? args[++i] ?? ''); - scriptOption = true; - } else if (name.length >= 2 && 'file'.startsWith(name)) { - scriptOption = true; - if (value === undefined) i++; - } else if ('line-length'.startsWith(name) && value === undefined) { - i++; - } - continue; - } - if (arg.startsWith('-') && arg !== '-') { - for (let j = 1; j < arg.length; j++) { - const option = arg[j]; - // -i takes the rest of the word as its backup suffix: `-ie` is -i with suffix e. - if (option === 'i') break; - if (option !== 'e' && option !== 'f' && option !== 'l') continue; - const value = j + 1 < arg.length ? arg.slice(j + 1) : args[++i]; - if (option === 'e') scripts.push(value ?? ''); - if (option !== 'l') scriptOption = true; - break; - } - continue; - } - operands.push(arg); - } - if (everyOperand) return [...scripts, ...operands]; - if (!scriptOption && operands.length > 0) scripts.push(operands[0]); - return scripts; -} - -/** - * The texts to read as sed scripts, each on its own. sed joins its scripts - * with newlines into one; when the shell may still change the words, every - * operand is read as a script of its own. - */ -function sedScriptTexts(args, opaque) { - return opaque ? sedScripts(args, true) : [sedScripts(args).join('\n')]; -} - -/** Past the spaces and tabs at `i`. */ -function skipBlanks(script, i) { - while (script[i] === ' ' || script[i] === '\t') i++; - return i; -} - -/** - * One part of a sed `s` or `y` command or of a regex address, from `start` up - * to the next unescaped `delimiter`. An escaped delimiter stands for itself. - * sed rejects a part that an unescaped newline cuts short. - */ -function sedPart(script, start, delimiter) { - let text = ''; - for (let i = start; i < script.length; i++) { - const char = script[i]; - if (char === '\\' && i + 1 < script.length) { - text += script[i + 1] === delimiter ? delimiter : char + script[i + 1]; - i++; - continue; - } - if (char === delimiter) return { text, end: i }; - if (char === '\n') return null; - text += char; - } - return null; -} - -/** - * Past the sed address at `i`, if there is one: a line number (`3`, `0~4`), - * `$`, a regex (`/re/I`, `\%re%`) or, as the second address, `+N` or `~N`. - */ -function sedAddressEnd(script, i, second) { - const char = script[i]; - if (char === '/' || char === '\\') { - const delimiter = char === '\\' ? script[i + 1] : char; - const regex = sedPart(script, char === '\\' ? i + 2 : i + 1, delimiter); - if (regex === null) return script.length; - i = skipBlanks(script, regex.end + 1); - while (script[i] === 'I' || script[i] === 'M') i = skipBlanks(script, i + 1); - return i; - } - if (char === '$') return i + 1; - if (!/[0-9]/.test(char || '') && !(second && (char === '+' || char === '~'))) return i; - if (!/[0-9]/.test(char)) i = skipBlanks(script, i + 1); - while (/[0-9]/.test(script[i] || '')) i++; - const step = skipBlanks(script, i); - if (second || script[step] !== '~') return i; - i = skipBlanks(script, step + 1); - while (/[0-9]/.test(script[i] || '')) i++; - return i; -} - -/** - * The end of the text of an `a`, `i`, `c` or `e` command: the first newline - * that no backslash escapes. A backslash before a newline carries the text on. - */ -function sedTextEnd(script, i) { - for (; i < script.length; i++) { - if (script[i] === '\\') i++; - else if (script[i] === '\n') return i; - } - return script.length; -} - -/** - * sed's text as the shell running it reads it: escaped characters stand for - * themselves, and a backslash before a newline joins the two lines. - */ -function sedUnescape(text) { - return text.replace(/\\\n/g, '').replace(/\\([\s\S])/g, (match, char) => (char === 'n' ? '\n' : char)); -} - -// Commands whose argument runs to the end of the line: a comment and a file name. -const SED_LINE_COMMANDS = new Set(['#', 'r', 'R', 'w', 'W']); -// Commands that take text, which the next newline without a backslash ends. -const SED_TEXT_COMMANDS = new Set(['a', 'i', 'c', 'e']); -// Commands that take a label or a version, which a blank or `;` ends. -const SED_LABEL_COMMANDS = new Set([':', 'b', 't', 'T', 'v']); - -/** - * What a sed script runs through a shell (GNU sed). An `s` command with the - * `e` flag runs the pattern space once the replacement is made, and an `e` - * command runs its text, or the pattern space when it has none. The script is - * read command by command, as sed reads it, so the text `a`, `i` and `c` add, - * a comment, a label or a file name is never taken for a command. `commands` - * holds the command text the script itself supplies; `runsInput` says the text - * sed reads is run too. - */ -function sedExecution(script) { - const commands = []; - let runsInput = false; - let i = 0; - while (i < script.length) { - if (/[\s;]/.test(script[i])) { - i++; - continue; - } - i = skipBlanks(script, sedAddressEnd(script, i, false)); - if (script[i] === ',') i = skipBlanks(script, sedAddressEnd(script, skipBlanks(script, i + 1), true)); - while (script[i] === '!') i = skipBlanks(script, i + 1); - const command = script[i]; - i++; - if (SED_LINE_COMMANDS.has(command)) { - const end = script.indexOf('\n', i); - i = end === -1 ? script.length : end; - } else if (SED_TEXT_COMMANDS.has(command)) { - i = skipBlanks(script, i); - const opensText = script[i] === '\\'; - if (opensText) i += script[i + 1] === '\n' ? 2 : 1; - const end = sedTextEnd(script, i); - if (command === 'e') { - const text = sedUnescape(script.slice(i, end)).trim(); - if (text === '') runsInput = true; - else commands.push(text); - } - i = end; - } else if (SED_LABEL_COMMANDS.has(command)) { - i = skipBlanks(script, i); - while (i < script.length && !/[\s;]/.test(script[i])) i++; - } else if (command === 's' || command === 'y') { - const delimiter = script[i]; - const pattern = delimiter === undefined ? null : sedPart(script, i + 1, delimiter); - const replacement = pattern && sedPart(script, pattern.end + 1, delimiter); - // sed rejects a script with an unfinished command and runs none of it. - if (!replacement) break; - i = replacement.end + 1; - if (command === 'y') continue; - const flags = /^[gpiImMe0-9]*/.exec(script.slice(i))[0]; - i += flags.length; - if (script[i] === 'w') { - const end = script.indexOf('\n', i); - i = end === -1 ? script.length : end; - } - if (flags.includes('e')) { - commands.push(sedUnescape(replacement.text)); - runsInput = true; - } - } - } - return { commands, runsInput }; -} - -/** - * Where the statement that starts at `start` ends: at an unquoted `;`, `|`, - * `&` or newline, or at a `)` that closes the substitution or subshell around - * it. A substitution inside the statement is part of it. `opaque` says the - * shell may still change the statement's words: a parameter expansion or a - * substitution in them. - */ -function statementBounds(input, start) { - let quote = null; - let opaque = false; - let depth = 0; - let backtick = false; - for (let i = start; i < input.length; i++) { - const char = input.charAt(i); - if (quote === "'") { - if (char === "'") quote = null; - continue; - } - if (char === '\\') { - i++; - continue; - } - if (char === '$' && /[\w{(@*#?$!-]/.test(input.charAt(i + 1))) opaque = true; - if (char === '`') { - // A backtick that closes a substitution around the statement reads as - // opening one, so the rest of the line counts: more operands, not fewer. - opaque = true; - backtick = !backtick; - } else if (quote === '"') { - if (char === '"') quote = null; - } else if (char === "'" || char === '"') { - quote = char; - } else if (char === '(') { - opaque = true; - depth++; - } else if (char === ')') { - if (depth === 0) return { end: i, opaque }; - depth--; - } else if (depth === 0 && !backtick && /[;|&\n]/.test(char)) { - return { end: i, opaque }; - } - } - return { end: input.length, opaque }; -} - /** * The commands the sed scripts in `input` run, from every statement that runs * sed. A script that only mentions a bypass flag, in a pattern or a text it @@ -744,59 +318,6 @@ function sedExecutedCommands(input) { }); } -/** - * Whether a program reads the text piped into it as code: a shell or command - * wrapper (`| sh`, `| xargs sh -c`), a runtime with no script operand of its - * own (`| node`, `| python3 -`), sed with a script that runs its input - * (`| sed e`), or a program named by an expansion. - */ -function readsCodeFromStdin(words) { - if (/[$`]/.test(words[0])) return true; - const base = commandBasename(words[0]); - if (COMMAND_WRAPPERS.has(base)) return true; - if (SED_PROGRAMS.has(base)) { - const opaque = words.some((word) => /[$`]/.test(word)); - return sedScriptTexts(words.slice(1), opaque).some((script) => sedExecution(script).runsInput); - } - if (CODE_EVALUATORS.has(base)) return words.slice(1).every((word) => word.startsWith('-')); - return false; -} - -/** - * Whether the separator at `i` ends a statement instead of joining the next - * command to it: `;`, a newline, `&&`, `||` or a background `&`. A pipe (`|`, - * `|&`) joins, and so does the `&` of a redirection (`2>&1`, `>&2`, `&>`). - */ -function endsStatement(input, i) { - const char = input.charAt(i); - if (char === ';' || char === '\n') return true; - if (char === '|') return input.charAt(i + 1) === '|'; - if (char !== '&') return false; - const before = input.charAt(i - 1); - return before !== '>' && before !== '<' && before !== '|' && input.charAt(i + 1) !== '>'; -} - -/** - * Whether the command line before `end` holds anything that can carry the - * output of a finished statement into a later pipe: a brace group or - * subshell (`{ echo '...'; } | sh`), a function body called later on, a - * compound command (`if ...; fi | sh`) or a substitution. Quoted text does - * not count, and neither does a brace inside a word, which is brace or - * parameter expansion (`/tmp/{a,b}`, `${HOME}`): a brace group opens with - * `{` as a word of its own. - */ -function mayGroupStatements(input, end) { - let bare = ''; - let pos = 0; - for (const region of quotedRegions(input)) { - if (region.start >= end) break; - bare += `${input.slice(pos, region.start)} `; - pos = region.end + 1; - } - bare += input.slice(pos, end); - return /[()`]/.test(bare) || bare.split(/[\s;&|]+/).some((word) => SHELL_RESERVED_WORDS.has(word)); -} - /** * Whether a later part of the command line pipes into a program that reads * what it receives as code (`echo '...' | sh`). Every later pipe counts, not diff --git a/scripts/lib/code-receivers.js b/scripts/lib/code-receivers.js new file mode 100644 index 00000000000..56eddf07634 --- /dev/null +++ b/scripts/lib/code-receivers.js @@ -0,0 +1,194 @@ +'use strict'; + +/** + * Which programs run the text they receive as code: a quoted argument + * (`sh -c '...'`, `node -e '...'`, `awk '...'`), or what is piped into them + * (`| sh`, `| python3 -`, `| sed e`). + */ + +const { SED_PROGRAMS, sedScriptTexts, sedExecution } = require('./sed-script'); + +/** + * Programs that execute a quoted argument as a shell command line, so a + * `git` inside one of their quoted arguments is a command that must still + * be checked (`sh -c "git commit --no-verify"`, `sudo`, `xargs`, `env`...). + * For any other argv0 (`node cli.js 'git commit --no-verify'`, + * `printf '%s' '...'`, `grep -n '...' docs.md`) a quoted string is data, + * unless it is a runtime given an eval flag (see CODE_EVALUATORS). + */ +const COMMAND_WRAPPERS = new Set([ + 'sh', + 'bash', + 'zsh', + 'dash', + 'ksh', + 'fish', + 'busybox', + 'eval', + 'exec', + 'command', + 'xargs', + 'sudo', + 'doas', + 'su', + 'env', + 'nice', + 'ionice', + 'nohup', + 'timeout', + 'time', + 'watch', + 'flock', + 'ssh', + 'script', + 'csh', + 'tcsh', + 'setsid', + 'stdbuf', + 'taskset', + 'chrt', + 'unshare', + 'chroot', + 'runuser', + 'npx', + 'bunx', + 'pnpx', + // Runs a command line for each input line; find and fd, which do so only + // after one of their exec flags, are in LAUNCHERS. + 'parallel', + // Shell builtins and zsh precommand modifiers that run a command line, or + // keep one to run later (`trap '...' EXIT`, `alias x='...'`). + 'builtin', + 'noglob', + 'nocorrect', + 'trap', + 'alias', +]); + +/** + * Strip a leading path and a trailing `.exe` from a command word. + */ +function commandBasename(word) { + return String(word || '') + .replace(/^.*[\\/]/, '') + .replace(/\.exe$/i, '') + .toLowerCase(); +} + +/** + * Runtimes that run a quoted argument as program source, each with the + * flags that do it: `node -e`, `python3 -c`, `perl -E`, `php -r`, + * `deno eval`. That source can spawn git itself, so it stays subject to the + * guard. The same runtime without one of its own eval flags receives a + * script path and arguments, which are data (`node cli.js 'git commit + * --no-verify'`). + * + * The flags are per runtime because the same letter means different things: + * node's `-r` preloads a module and leaves the rest of the command line as + * ordinary arguments, while php's `-r` is how php is handed code. + */ +const CODE_EVALUATORS = new Map([ + ['node', ['-e', '--eval', '-p', '--print']], + ['nodejs', ['-e', '--eval', '-p', '--print']], + ['bun', ['-e', '--eval', '-p', '--print']], + ['deno', ['-e', '--eval', 'eval']], + ['python', ['-c']], + ['python2', ['-c']], + ['python3', ['-c']], + ['pythonw', ['-c']], + ['perl', ['-e', '-E']], + ['ruby', ['-e']], + ['php', ['-r']], + ['lua', ['-e']], + ['luajit', ['-e']], + ['rscript', ['-e']], + ['osascript', ['-e']], + ['groovy', ['-e']], + ['julia', ['-e', '-E']], + ['elixir', ['-e']], + ['erl', ['-eval']], + ['expect', ['-c']], +]); + +/** + * Launchers that run another program given after one of their flags: + * `find . -exec CMD ARGS \;`, `fd -x CMD ARGS`. A quoted argument of the + * launched program is judged as that program's own, so `-exec grep '...'` + * searches and `-exec sh -c '...'` runs. After find's `;` or `{} +` the + * arguments are find's again. + */ +const LAUNCHERS = new Map([ + ['find', ['-exec', '-execdir', '-ok', '-okdir']], + ['fd', ['-x', '--exec', '-X', '--exec-batch']], + ['fdfind', ['-x', '--exec', '-X', '--exec-batch']], +]); + +const EXEC_TERMINATORS = new Set(['\\;', "';'", '";"']); + +/** + * Runtimes whose first operand is itself program source, with no eval flag: + * `awk 'BEGIN { system("git commit --no-verify") }'` runs git. Every quoted + * argument they receive stays subject to the guard, at the cost of also + * checking an awk pattern that merely mentions a bypass flag. + */ +const SOURCE_OPERAND_RUNTIMES = new Set(['awk', 'gawk', 'mawk', 'nawk']); + +/** + * Whether a quoted argument is data for the program that receives it. + * `words` runs from that program's name up to the argument. An eval flag is + * matched as a whole word, or as the `=` form of itself, so a path that + * happens to end in one of them cannot qualify. + */ +function receivesAsData(words) { + // A program named by an expansion is only known when the line runs. + if (/[$`]/.test(words[0])) return false; + const base = commandBasename(words[0]); + if (base === 'git' || COMMAND_WRAPPERS.has(base) || SOURCE_OPERAND_RUNTIMES.has(base)) return false; + const launchFlags = LAUNCHERS.get(base); + if (launchFlags !== undefined) { + const at = words.findLastIndex((word) => launchFlags.includes(word)); + if (at === -1) return true; + const launched = words.slice(at + 1); + if (launched.some((word, i) => EXEC_TERMINATORS.has(word) || (word === '+' && launched[i - 1] === '{}'))) { + return true; + } + // The quoted argument is the launched program's name itself. + if (launched.length === 0) return false; + return receivesAsData([launched[0].replace(/['"\\]/g, ''), ...launched.slice(1)]); + } + const flags = CODE_EVALUATORS.get(base); + if (flags === undefined) return true; + return !words.some((word) => flags.some((flag) => word === flag || word.startsWith(`${flag}=`))); +} + +/** + * The arguments sed receives in a statement, or null when the statement does + * not run sed: `sed ARGS`, or sed behind a wrapper (`sudo sed ARGS`). + */ +function sedArguments(words) { + const base = commandBasename(words[0]); + if (SED_PROGRAMS.has(base)) return words.slice(1); + if (!COMMAND_WRAPPERS.has(base)) return null; + const at = words.findIndex((word) => SED_PROGRAMS.has(commandBasename(word))); + return at === -1 ? null : words.slice(at + 1); +} + +/** + * Whether a program reads the text piped into it as code: a shell or command + * wrapper (`| sh`, `| xargs sh -c`), a runtime with no script operand of its + * own (`| node`, `| python3 -`), sed with a script that runs its input + * (`| sed e`), or a program named by an expansion. + */ +function readsCodeFromStdin(words) { + if (/[$`]/.test(words[0])) return true; + const base = commandBasename(words[0]); + if (COMMAND_WRAPPERS.has(base)) return true; + if (SED_PROGRAMS.has(base)) { + const opaque = words.some((word) => /[$`]/.test(word)); + return sedScriptTexts(words.slice(1), opaque).some((script) => sedExecution(script).runsInput); + } + if (CODE_EVALUATORS.has(base)) return words.slice(1).every((word) => word.startsWith('-')); + return false; +} + +module.exports = { COMMAND_WRAPPERS, commandBasename, receivesAsData, sedArguments, readsCodeFromStdin }; diff --git a/scripts/lib/sed-script.js b/scripts/lib/sed-script.js new file mode 100644 index 00000000000..490ed24538d --- /dev/null +++ b/scripts/lib/sed-script.js @@ -0,0 +1,238 @@ +'use strict'; + +/** + * GNU sed, as far as a command guard needs it: which of sed's arguments are + * its scripts, and what a script runs through a shell. The `e` command and + * the `e` flag of `s` run a command line; nothing else in a script does. + */ + +const SED_PROGRAMS = new Set(['sed', 'gsed']); + +/** + * The scripts in sed's arguments, read as GNU sed's option parser reads them: + * each `-e`/`--expression` value, or else the first operand. The other + * operands are input files, and a script named with `-f` is not on the line. + * When the shell may still change the words (`$OPTS`, a substitution), every + * operand may be the script. + */ +function sedScripts(args, everyOperand = false) { + const scripts = []; + const operands = []; + let scriptOption = false; + for (let i = 0; i < args.length; i++) { + const arg = args[i]; + if (arg === '--') { + operands.push(...args.slice(i + 1)); + break; + } + if (arg.startsWith('--')) { + // A long option may be shortened to any prefix that names only it. + const [name, value] = arg.slice(2).split(/=(.*)/s); + if ('expression'.startsWith(name)) { + scripts.push(value ?? args[++i] ?? ''); + scriptOption = true; + } else if (name.length >= 2 && 'file'.startsWith(name)) { + scriptOption = true; + if (value === undefined) i++; + } else if ('line-length'.startsWith(name) && value === undefined) { + i++; + } + continue; + } + if (arg.startsWith('-') && arg !== '-') { + for (let j = 1; j < arg.length; j++) { + const option = arg[j]; + // -i takes the rest of the word as its backup suffix: `-ie` is -i with suffix e. + if (option === 'i') break; + if (option !== 'e' && option !== 'f' && option !== 'l') continue; + const value = j + 1 < arg.length ? arg.slice(j + 1) : args[++i]; + if (option === 'e') scripts.push(value ?? ''); + if (option !== 'l') scriptOption = true; + break; + } + continue; + } + operands.push(arg); + } + if (everyOperand) return [...scripts, ...operands]; + if (!scriptOption && operands.length > 0) scripts.push(operands[0]); + return scripts; +} + +/** + * The texts to read as sed scripts, each on its own. sed joins its scripts + * with newlines into one; when the shell may still change the words, every + * operand is read as a script of its own. + */ +function sedScriptTexts(args, opaque) { + return opaque ? sedScripts(args, true) : [sedScripts(args).join('\n')]; +} + +/** Past the spaces and tabs at `i`. */ +function skipBlanks(script, i) { + while (script[i] === ' ' || script[i] === '\t') i++; + return i; +} + +/** + * One part of a sed `s` or `y` command or of a regex address, from `start` up + * to the next unescaped `delimiter`. An escaped delimiter stands for itself. + * sed rejects a part that an unescaped newline cuts short. + */ +function sedPart(script, start, delimiter) { + let text = ''; + for (let i = start; i < script.length; i++) { + const char = script[i]; + if (char === '\\' && i + 1 < script.length) { + text += script[i + 1] === delimiter ? delimiter : char + script[i + 1]; + i++; + continue; + } + if (char === delimiter) return { text, end: i }; + if (char === '\n') return null; + text += char; + } + return null; +} + +/** + * Past the sed address at `i`, if there is one: a line number (`3`, `0~4`), + * `$`, a regex (`/re/I`, `\%re%`) or, as the second address, `+N` or `~N`. + */ +function sedAddressEnd(script, i, second) { + const char = script[i]; + if (char === '/' || char === '\\') { + const delimiter = char === '\\' ? script[i + 1] : char; + const regex = sedPart(script, char === '\\' ? i + 2 : i + 1, delimiter); + if (regex === null) return script.length; + i = skipBlanks(script, regex.end + 1); + while (script[i] === 'I' || script[i] === 'M') i = skipBlanks(script, i + 1); + return i; + } + if (char === '$') return i + 1; + if (!/[0-9]/.test(char || '') && !(second && (char === '+' || char === '~'))) return i; + if (!/[0-9]/.test(char)) i = skipBlanks(script, i + 1); + while (/[0-9]/.test(script[i] || '')) i++; + const step = skipBlanks(script, i); + if (second || script[step] !== '~') return i; + i = skipBlanks(script, step + 1); + while (/[0-9]/.test(script[i] || '')) i++; + return i; +} + +/** + * The end of the text of an `a`, `i`, `c` or `e` command: the first newline + * that no backslash escapes. A backslash before a newline carries the text on. + */ +function sedTextEnd(script, i) { + for (; i < script.length; i++) { + if (script[i] === '\\') i++; + else if (script[i] === '\n') return i; + } + return script.length; +} + +/** + * sed's text as the shell running it reads it: escaped characters stand for + * themselves, and a backslash before a newline joins the two lines. + */ +function sedUnescape(text) { + return text.replace(/\\\n/g, '').replace(/\\([\s\S])/g, (match, char) => (char === 'n' ? '\n' : char)); +} + +// Commands whose argument runs to the end of the line: a comment and a file name. +const SED_LINE_COMMANDS = new Set(['#', 'r', 'R', 'w', 'W']); + +// Commands that take text, which the next newline without a backslash ends. +const SED_TEXT_COMMANDS = new Set(['a', 'i', 'c', 'e']); + +// Commands that take a label or a version, which a blank or `;` ends. +const SED_LABEL_COMMANDS = new Set([':', 'b', 't', 'T', 'v']); + +/** The end of the line that `i` is on. */ +function lineEnd(script, i) { + const end = script.indexOf('\n', i); + return end === -1 ? script.length : end; +} + +/** Past a command's addresses and any `!`, to its command letter. */ +function sedCommandStart(script, i) { + i = skipBlanks(script, sedAddressEnd(script, i, false)); + if (script[i] === ',') i = skipBlanks(script, sedAddressEnd(script, skipBlanks(script, i + 1), true)); + while (script[i] === '!') i = skipBlanks(script, i + 1); + return i; +} + +/** + * The text of an `a`, `i`, `c` or `e` command, from `i` after its letter: past + * blanks and one backslash. An `e` command's text is recorded in `found`: the + * command it runs, or, with no text, the pattern space. Returns where it ends. + */ +function readSedText(script, i, command, found) { + i = skipBlanks(script, i); + if (script[i] === '\\') i += script[i + 1] === '\n' ? 2 : 1; + const end = sedTextEnd(script, i); + if (command === 'e') { + const text = sedUnescape(script.slice(i, end)).trim(); + if (text === '') found.runsInput = true; + else found.commands.push(text); + } + return end; +} + +/** + * An `s` or `y` command from its delimiter at `i`. An `s` command with the `e` + * flag runs its replacement, and the text sed reads with it, which `found` + * records. Returns where the command ends, or -1 when a part is not closed: + * sed then rejects the whole script and runs none of it. + */ +function readSedSubstitution(script, i, command, found) { + const delimiter = script[i]; + const pattern = delimiter === undefined ? null : sedPart(script, i + 1, delimiter); + const replacement = pattern && sedPart(script, pattern.end + 1, delimiter); + if (!replacement) return -1; + i = replacement.end + 1; + if (command === 'y') return i; + const flags = /^[gpiImMe0-9]*/.exec(script.slice(i))[0]; + i += flags.length; + if (script[i] === 'w') i = lineEnd(script, i); + if (flags.includes('e')) { + found.commands.push(sedUnescape(replacement.text)); + found.runsInput = true; + } + return i; +} + +/** The command whose letter is at `i`. Returns where it ends, or -1 (see above). */ +function readSedCommand(script, i, found) { + const command = script[i]; + const next = i + 1; + if (SED_LINE_COMMANDS.has(command)) return lineEnd(script, next); + if (SED_TEXT_COMMANDS.has(command)) return readSedText(script, next, command, found); + if (command === 's' || command === 'y') return readSedSubstitution(script, next, command, found); + if (!SED_LABEL_COMMANDS.has(command)) return next; + let end = skipBlanks(script, next); + while (end < script.length && !/[\s;]/.test(script[end])) end++; + return end; +} + +/** + * What a sed script runs through a shell (GNU sed). An `s` command with the + * `e` flag runs the pattern space once the replacement is made, and an `e` + * command runs its text, or the pattern space when it has none. The script is + * read command by command, as sed reads it, so the text `a`, `i` and `c` add, + * a comment, a label or a file name is never taken for a command. `commands` + * holds the command text the script itself supplies; `runsInput` says the text + * sed reads is run too. + */ +function sedExecution(script) { + const found = { commands: [], runsInput: false }; + let i = 0; + while (i >= 0 && i < script.length) { + if (/[\s;]/.test(script[i])) i++; + else i = readSedCommand(script, sedCommandStart(script, i), found); + } + return found; +} + +module.exports = { SED_PROGRAMS, sedScripts, sedScriptTexts, sedExecution }; diff --git a/scripts/lib/shell-statements.js b/scripts/lib/shell-statements.js new file mode 100644 index 00000000000..b29a2395e3b --- /dev/null +++ b/scripts/lib/shell-statements.js @@ -0,0 +1,104 @@ +'use strict'; + +/** + * Where a shell statement ends, and what can tie it to the commands after it, + * for a guard that reads a command line without running a shell. + */ + +const { quotedRegions, SHELL_RESERVED_WORDS } = require('./shell-quotes'); + +/** + * Whether a statement's first word sits right inside or right after a + * substitution. `$(echo '...')` runs what echo prints, `source <(echo '...')` + * reads it as a script, and in `$(command -v sh) -c '...'` the program is only + * known when the line runs. + */ +function startsAtSubstitution(input, argv0Start) { + let i = argv0Start - 1; + while (i >= 0 && /\s/.test(input.charAt(i))) i--; + const char = input.charAt(i); + if (char === '`' || char === ')') return true; + return char === '(' && /[$<>]/.test(input.charAt(i - 1)); +} + +/** + * Where the statement that starts at `start` ends: at an unquoted `;`, `|`, + * `&` or newline, or at a `)` that closes the substitution or subshell around + * it. A substitution inside the statement is part of it. `opaque` says the + * shell may still change the statement's words: a parameter expansion or a + * substitution in them. + */ +function statementBounds(input, start) { + let quote = null; + let opaque = false; + let depth = 0; + let backtick = false; + for (let i = start; i < input.length; i++) { + const char = input.charAt(i); + if (quote === "'") { + if (char === "'") quote = null; + continue; + } + if (char === '\\') { + i++; + continue; + } + if (char === '$' && /[\w{(@*#?$!-]/.test(input.charAt(i + 1))) opaque = true; + if (char === '`') { + // A backtick that closes a substitution around the statement reads as + // opening one, so the rest of the line counts: more operands, not fewer. + opaque = true; + backtick = !backtick; + } else if (quote === '"') { + if (char === '"') quote = null; + } else if (char === "'" || char === '"') { + quote = char; + } else if (char === '(') { + opaque = true; + depth++; + } else if (char === ')') { + if (depth === 0) return { end: i, opaque }; + depth--; + } else if (depth === 0 && !backtick && /[;|&\n]/.test(char)) { + return { end: i, opaque }; + } + } + return { end: input.length, opaque }; +} + +/** + * Whether the separator at `i` ends a statement instead of joining the next + * command to it: `;`, a newline, `&&`, `||` or a background `&`. A pipe (`|`, + * `|&`) joins, and so does the `&` of a redirection (`2>&1`, `>&2`, `&>`). + */ +function endsStatement(input, i) { + const char = input.charAt(i); + if (char === ';' || char === '\n') return true; + if (char === '|') return input.charAt(i + 1) === '|'; + if (char !== '&') return false; + const before = input.charAt(i - 1); + return before !== '>' && before !== '<' && before !== '|' && input.charAt(i + 1) !== '>'; +} + +/** + * Whether the command line before `end` holds anything that can carry the + * output of a finished statement into a later pipe: a brace group or + * subshell (`{ echo '...'; } | sh`), a function body called later on, a + * compound command (`if ...; fi | sh`) or a substitution. Quoted text does + * not count, and neither does a brace inside a word, which is brace or + * parameter expansion (`/tmp/{a,b}`, `${HOME}`): a brace group opens with + * `{` as a word of its own. + */ +function mayGroupStatements(input, end) { + let bare = ''; + let pos = 0; + for (const region of quotedRegions(input)) { + if (region.start >= end) break; + bare += `${input.slice(pos, region.start)} `; + pos = region.end + 1; + } + bare += input.slice(pos, end); + return /[()`]/.test(bare) || bare.split(/[\s;&|]+/).some((word) => SHELL_RESERVED_WORDS.has(word)); +} + +module.exports = { startsAtSubstitution, statementBounds, endsStatement, mayGroupStatements }; diff --git a/tests/lib/code-receivers.test.js b/tests/lib/code-receivers.test.js new file mode 100644 index 00000000000..6535b211c0d --- /dev/null +++ b/tests/lib/code-receivers.test.js @@ -0,0 +1,69 @@ +'use strict'; +const assert = require('assert'); +const { + commandBasename, + receivesAsData, + sedArguments, + readsCodeFromStdin, +} = require('../../scripts/lib/code-receivers'); + +console.log('=== Testing code-receivers.js ===\n'); + +let passed = 0; +let failed = 0; + +function test(desc, fn) { + try { + fn(); + console.log(` ✓ ${desc}`); + passed++; + } catch (e) { + console.log(` ✗ ${desc}: ${e.message}`); + failed++; + } +} + +test('commandBasename drops the path and .exe, and lowercases', () => { + assert.deepStrictEqual(['/usr/bin/SED', 'C:\\bin\\node.EXE', 'git'].map(commandBasename), ['sed', 'node', 'git']); +}); + +console.log('\nreceivesAsData (a quoted argument after these words):'); +test('an unrelated program receives it as data', () => { + assert.strictEqual(receivesAsData(['printf']), true); + assert.strictEqual(receivesAsData(['node', 'x.js']), true); + assert.strictEqual(receivesAsData(['find', '.', '-exec', 'grep']), true); +}); +test('a shell, a wrapper, an eval flag or awk runs it', () => { + assert.strictEqual(receivesAsData(['sh', '-c']), false); + assert.strictEqual(receivesAsData(['sudo']), false); + assert.strictEqual(receivesAsData(['node', '-e']), false); + assert.strictEqual(receivesAsData(['find', '.', '-exec', 'sh', '-c']), false); + assert.strictEqual(receivesAsData(['awk']), false); +}); +test('a program named by an expansion is unknown, so it may run it', () => { + assert.strictEqual(receivesAsData(['$SHELL', '-c']), false); +}); + +console.log('\nsedArguments:'); +test("sed's arguments, also behind a wrapper", () => { + assert.deepStrictEqual(sedArguments(['sed', '-n', 'p']), ['-n', 'p']); + assert.deepStrictEqual(sedArguments(['sudo', '-u', 'x', 'sed', 'e']), ['e']); +}); +test('null when the statement does not run sed', () => { + assert.strictEqual(sedArguments(['grep', 'sed']), null); +}); + +console.log('\nreadsCodeFromStdin:'); +test('a shell, a runtime without a script, or sed that runs its input', () => { + for (const words of [['sh'], ['node'], ['python3', '-'], ['sed', 'e'], ['$SHELL']]) { + assert.strictEqual(readsCodeFromStdin(words), true, words.join(' ')); + } +}); +test('a runtime with a script, sed that only edits, or cat', () => { + for (const words of [['node', 'x.js'], ['sed', 's/x/y/'], ['cat']]) { + assert.strictEqual(readsCodeFromStdin(words), false, words.join(' ')); + } +}); + +console.log(`\nPassed: ${passed} Failed: ${failed}`); +if (failed > 0) process.exit(1); diff --git a/tests/lib/sed-script.test.js b/tests/lib/sed-script.test.js new file mode 100644 index 00000000000..386cb917a6b --- /dev/null +++ b/tests/lib/sed-script.test.js @@ -0,0 +1,89 @@ +'use strict'; +const assert = require('assert'); +const { sedScripts, sedScriptTexts, sedExecution } = require('../../scripts/lib/sed-script'); + +console.log('=== Testing sed-script.js ===\n'); + +let passed = 0; +let failed = 0; + +function test(desc, fn) { + try { + fn(); + console.log(` ✓ ${desc}`); + passed++; + } catch (e) { + console.log(` ✗ ${desc}: ${e.message}`); + failed++; + } +} + +console.log('Which arguments are scripts:'); +test('the first operand is the script, the others are input files', () => { + assert.deepStrictEqual(sedScripts(['-n', 's/x/y/p', 'a.txt', 'b.txt']), ['s/x/y/p']); +}); +test('with -e, every operand is an input file', () => { + assert.deepStrictEqual(sedScripts(['-e', 's/x/y/', 'e git push']), ['s/x/y/']); + assert.deepStrictEqual(sedScripts(['notes.md', '-e', 'p']), ['p']); +}); +test('attached and long forms of -e, including a prefix of --expression', () => { + assert.deepStrictEqual(sedScripts(['-es/x/y/', '--expression=p', '--expr', 'd']), ['s/x/y/', 'p', 'd']); +}); +test('-f and --file name a script that is not on the line', () => { + assert.deepStrictEqual(sedScripts(['-f', 'fix.sed', 'e git push']), []); + assert.deepStrictEqual(sedScripts(['--file=fix.sed', 'e git push']), []); +}); +test('-ie is -i with the backup suffix e', () => { + assert.deepStrictEqual(sedScripts(['-ie', '-n', 'p', 'notes.md']), ['p']); +}); +test('-l takes a value, and -- ends the options', () => { + assert.deepStrictEqual(sedScripts(['-l', '80', 'p']), ['p']); + assert.deepStrictEqual(sedScripts(['-n', '--', '-p', 'f']), ['-p']); +}); +test('every operand may be a script when the words can still change', () => { + assert.deepStrictEqual(sedScripts(['$EXPR', 'e git push', 'f'], true), ['$EXPR', 'e git push', 'f']); +}); +test('sed joins its scripts into one, unless the words can still change', () => { + assert.deepStrictEqual(sedScriptTexts(['-e', 'a\\', '-e', 'text']), ['a\\\ntext']); + assert.deepStrictEqual(sedScriptTexts(['%s', 's/x/y/e'], true), ['%s', 's/x/y/e']); +}); + +console.log('\nWhat a script runs:'); +test('an e command runs its text, to the end of the line', () => { + assert.deepStrictEqual(sedExecution('e git push; echo done'), { + commands: ['git push; echo done'], + runsInput: false, + }); +}); +test('an e command without text runs the pattern space', () => { + assert.deepStrictEqual(sedExecution('1e'), { commands: [], runsInput: true }); +}); +test('the e flag of s runs the replacement, with any delimiter', () => { + for (const script of ['s/x/git push/e', 's|x|git push|e', 'sxfooxgit pushxe']) { + assert.deepStrictEqual(sedExecution(script).commands, ['git push'], script); + } +}); +test('an escaped character in the replacement stands for itself', () => { + assert.deepStrictEqual(sedExecution('s/x/git\\ push/e').commands, ['git push']); +}); +test('the text of a, i and c, a comment and a file name run nothing', () => { + for (const script of ['1i e git push', '$a e git push', '/x/c e git push', '# e git push', 'w e git push']) { + assert.deepStrictEqual(sedExecution(script), { commands: [], runsInput: false }, script); + } +}); +test('labels named e are not e commands', () => { + assert.deepStrictEqual(sedExecution(':e\n$!N;s/\\n/ /;te'), { commands: [], runsInput: false }); +}); +test('an address regex is not read as a command', () => { + assert.deepStrictEqual(sedExecution('/s|x|git push|e/p'), { commands: [], runsInput: false }); + assert.deepStrictEqual(sedExecution('\\%s/x/git push/e%p'), { commands: [], runsInput: false }); +}); +test('an unfinished s command ends the reading: sed rejects the script', () => { + assert.deepStrictEqual(sedExecution('s/x/y\ne git push'), { commands: [], runsInput: false }); +}); +test('a y command is read past, whatever its parts hold', () => { + assert.deepStrictEqual(sedExecution('y/e/E/;e git push').commands, ['git push']); +}); + +console.log(`\nPassed: ${passed} Failed: ${failed}`); +if (failed > 0) process.exit(1); diff --git a/tests/lib/shell-quotes.test.js b/tests/lib/shell-quotes.test.js new file mode 100644 index 00000000000..f26cd265253 --- /dev/null +++ b/tests/lib/shell-quotes.test.js @@ -0,0 +1,57 @@ +'use strict'; +const assert = require('assert'); +const { quotedRegions, quotedRegionAt, commandStatements } = require('../../scripts/lib/shell-quotes'); + +console.log('=== Testing shell-quotes.js ===\n'); + +let passed = 0; +let failed = 0; + +function test(desc, fn) { + try { + fn(); + console.log(` ✓ ${desc}`); + passed++; + } catch (e) { + console.log(` ✗ ${desc}: ${e.message}`); + failed++; + } +} + +test('each quoted region, with the argv0 of its statement', () => { + assert.deepStrictEqual(quotedRegions("echo 'a b' \"c\""), [ + { start: 5, quote: "'", argv0: 'echo', argv0Start: 0, substitution: false, end: 9 }, + { start: 11, quote: '"', argv0: 'echo', argv0Start: 0, substitution: false, end: 13 }, + ]); +}); +test('a substitution splits a double-quoted string, and both halves say so', () => { + const regions = quotedRegions('echo "x $(printf y) z"'); + assert.deepStrictEqual( + regions.map(({ start, end, substitution }) => ({ start, end, substitution })), + [ + { start: 5, end: 8, substitution: true }, + { start: 18, end: 21, substitution: true }, + ] + ); +}); +test('quotedRegionAt finds the region around an index, or null', () => { + const input = "echo 'a b' \"c\""; + assert.strictEqual(quotedRegionAt(input, 7).start, 5); + assert.strictEqual(quotedRegionAt(input, 2), null); +}); +test('commandStatements lists the argv0 of every statement', () => { + assert.deepStrictEqual(commandStatements('FOO=1 sed e f | if grep -q x f; then :; fi'), [ + { argv0: 'sed', argv0Start: 6 }, + { argv0: 'grep', argv0Start: 19 }, + { argv0: ':', argv0Start: 37 }, + ]); +}); +test('commandStatements includes a statement inside a substitution', () => { + assert.deepStrictEqual( + commandStatements('echo "$(sed e f)"').map(({ argv0 }) => argv0), + ['echo', 'sed'] + ); +}); + +console.log(`\nPassed: ${passed} Failed: ${failed}`); +if (failed > 0) process.exit(1); diff --git a/tests/lib/shell-statements.test.js b/tests/lib/shell-statements.test.js new file mode 100644 index 00000000000..38797572e46 --- /dev/null +++ b/tests/lib/shell-statements.test.js @@ -0,0 +1,77 @@ +'use strict'; +const assert = require('assert'); +const { + startsAtSubstitution, + statementBounds, + endsStatement, + mayGroupStatements, +} = require('../../scripts/lib/shell-statements'); + +console.log('=== Testing shell-statements.js ===\n'); + +let passed = 0; +let failed = 0; + +function test(desc, fn) { + try { + fn(); + console.log(` ✓ ${desc}`); + passed++; + } catch (e) { + console.log(` ✗ ${desc}: ${e.message}`); + failed++; + } +} + +console.log('statementBounds:'); +test('a statement ends at ; or at a pipe', () => { + assert.deepStrictEqual(statementBounds('sed -n p f; echo x', 0), { end: 10, opaque: false }); + assert.deepStrictEqual(statementBounds("sed '$d' f | cat", 0), { end: 11, opaque: false }); +}); +test('a statement inside a substitution ends where the substitution closes', () => { + assert.deepStrictEqual(statementBounds('echo "$(sed e f)" x', 9), { end: 15, opaque: false }); +}); +test('a parameter expansion makes the words opaque, a quoted $ does not', () => { + assert.deepStrictEqual(statementBounds('sed $OPTS f', 0), { end: 11, opaque: true }); + assert.strictEqual(statementBounds("sed '$d' f", 0).opaque, false); +}); +test('a substitution is part of the statement, and makes it opaque', () => { + assert.deepStrictEqual(statementBounds("sed $(printf -n) 'e x' f; echo", 0), { end: 24, opaque: true }); + assert.deepStrictEqual(statementBounds("sed `printf -n` 'e x' f", 0), { end: 23, opaque: true }); +}); + +console.log('\nendsStatement:'); +test('; && || and a background & end a statement', () => { + assert.strictEqual(endsStatement('a; b', 1), true); + assert.strictEqual(endsStatement('a && b', 2), true); + assert.strictEqual(endsStatement('a || b', 2), true); + assert.strictEqual(endsStatement('a & b', 2), true); +}); +test('a pipe and the & of a redirection do not', () => { + assert.strictEqual(endsStatement('a | b', 2), false); + assert.strictEqual(endsStatement('a 2>&1', 4), false); + assert.strictEqual(endsStatement('a &> f', 2), false); + assert.strictEqual(endsStatement('a >&2', 3), false); +}); + +console.log('\nmayGroupStatements:'); +test('a group, a subshell or a compound command can carry output on', () => { + assert.strictEqual(mayGroupStatements('{ echo x; }', 10), true); + assert.strictEqual(mayGroupStatements('( echo x )', 10), true); + assert.strictEqual(mayGroupStatements('if true; then echo', 18), true); +}); +test('quoted parentheses and a brace inside a word do not', () => { + assert.strictEqual(mayGroupStatements("echo '(x)'", 10), false); + assert.strictEqual(mayGroupStatements('ls /tmp/{a,b}', 13), false); +}); + +console.log('\nstartsAtSubstitution:'); +test('a statement right inside $( ), backticks or <( ) starts at a substitution', () => { + assert.strictEqual(startsAtSubstitution('echo $(sed e f)', 7), true); + assert.strictEqual(startsAtSubstitution('echo `sed e f`', 6), true); + assert.strictEqual(startsAtSubstitution('source <(echo x)', 9), true); + assert.strictEqual(startsAtSubstitution('sed e f', 0), false); +}); + +console.log(`\nPassed: ${passed} Failed: ${failed}`); +if (failed > 0) process.exit(1);