diff --git a/src/rules/utils.spec.ts b/src/rules/utils.spec.ts new file mode 100644 index 0000000..be4f9e2 --- /dev/null +++ b/src/rules/utils.spec.ts @@ -0,0 +1,210 @@ +/** + * @fileoverview Unit tests for the shared rule helpers. + */ + +import { describe, expect, it } from "vitest"; +import { splitShellCommands, spanOfTokens } from "./utils.js"; +import { parseDocker } from "../parser/parse.js"; +import type { ShellCommand } from "./utils.js"; +import type { RunInstructionNode, ShellFormNode } from "../types.js"; + +function parseRun(command: string): { + text: string; + form: ShellFormNode; +} { + const text = `RUN ${command}\n`; + const { ast } = parseDocker(text); + const run = ast.body[0] as RunInstructionNode; + + return { text, form: run.command as ShellFormNode }; +} + +function split(command: string): ShellCommand[] { + const { text, form } = parseRun(command); + + return splitShellCommands(form, text); +} + +describe("splitShellCommands", () => { + it("should return a single command when there are no separators", () => { + const commands = split("apt-get install -y git"); + + expect(commands).toHaveLength(1); + expect(commands[0]?.words).toEqual(["apt-get", "install", "-y", "git"]); + }); + + it("should keep the source spelling of each word", () => { + const commands = split("(echo a\\\"b 'c\\\n d'; make"); + + expect(commands.map(command => command.raw)).toEqual([ + ["echo", 'a\\"b', "'c", "d'"], + ["make"], + ]); + }); + + it("should split on && and || operator tokens", () => { + const commands = split( + "apt-get update && apt-get install -y git || true", + ); + + expect(commands.map(command => command.words)).toEqual([ + ["apt-get", "update"], + ["apt-get", "install", "-y", "git"], + ["true"], + ]); + }); + + it("should split on pipes and standalone semicolons", () => { + const commands = split("cat foo | grep bar ; ls"); + + expect(commands.map(command => command.words)).toEqual([ + ["cat", "foo"], + ["grep", "bar"], + ["ls"], + ]); + }); + + it("should split on trailing semicolons attached to a token", () => { + const commands = split("cd /app; make"); + + expect(commands.map(command => command.words)).toEqual([ + ["cd", "/app"], + ["make"], + ]); + }); + + it("should not split on escaped trailing semicolons", () => { + const commands = split("echo marker\\; sudo apt-get upgrade"); + + expect(commands.map(command => command.words)).toEqual([ + ["echo", "marker;", "sudo", "apt-get", "upgrade"], + ]); + }); + + it("should not split on quoted trailing semicolons", () => { + const commands = split("echo 'marker;' sudo"); + + expect(commands.map(command => command.words)).toEqual([ + ["echo", "'marker;'", "sudo"], + ]); + }); + + it("should split after an escaped backslash before a semicolon", () => { + const commands = split("echo a\\\\; make"); + + expect(commands.map(command => command.words)).toEqual([ + ["echo", "a\\"], + ["make"], + ]); + }); + + it("should strip a leading parenthesis from the first word", () => { + const commands = split("(cd /app && make)"); + + expect(commands[0]?.words[0]).toBe("cd"); + }); + + it("should omit a standalone group opener", () => { + const commands = split("( cd /app && make )"); + + expect(commands[0]?.words).toEqual(["cd", "/app"]); + expect(commands[0]?.tokens[0].value).toBe("cd"); + }); + + it("should keep an escaped opening parenthesis", () => { + const commands = split("\\(cd /app"); + + expect(commands[0]?.words[0]).toBe("(cd"); + }); + + it("should stop at a comment right after a semicolon", () => { + const commands = split("echo ok;# note && make"); + + expect(commands.map(command => command.words)).toEqual([ + ["echo", "ok"], + ]); + }); + + it("should not start a comment after an escaped blank", () => { + const commands = split("echo word\\ #tag && make"); + + expect(commands.map(command => command.words[0])).toEqual([ + "echo", + "make", + ]); + }); + + it("should start a comment after an unescaped blank that follows an escaped one", () => { + const commands = split("echo word\\ # note && make"); + + expect(commands.map(command => command.words[0])).toEqual(["echo"]); + }); + + it("should start a comment after an escaped backslash and a blank", () => { + const commands = split("echo word\\\\ # note && make"); + + expect(commands.map(command => command.words[0])).toEqual(["echo"]); + }); + + it("should ignore comment lines inside continued tokens", () => { + const commands = split('echo o\\\n# "\nk && make'); + + expect(commands.map(command => command.words[0])).toEqual([ + "echo", + "make", + ]); + }); + + it("should classify operators split by a line continuation", () => { + const commands = split("echo ok &\\\n& make"); + + expect(commands.map(command => command.words[0])).toEqual([ + "echo", + "make", + ]); + }); + + it("should not split quoted operators", () => { + const commands = split('echo "a && b"'); + + // "a && b" is quoted, so the && token never stands alone. + expect(commands).toHaveLength(1); + }); + + it("should ignore words after an unquoted shell comment", () => { + const commands = split("echo ok # example && sudo id"); + + expect(commands.map(command => command.words)).toEqual([ + ["echo", "ok"], + ]); + }); + + it("should not treat a quoted or mid-word # as a comment", () => { + const commands = split("echo '# a' b#c && ls"); + + expect(commands.map(command => command.words)).toEqual([ + ["echo", "'#", "a'", "b#c"], + ["ls"], + ]); + }); + + it("should keep token nodes alongside the cleaned words", () => { + const commands = split("cd /app; make"); + const first = commands[0]; + + expect(first?.tokens.map(token => token.value)).toEqual([ + "cd", + "/app;", + ]); + expect(first?.words).toEqual(["cd", "/app"]); + }); +}); + +describe("spanOfTokens", () => { + it("should span from the first to the last token", () => { + const [command] = split("echo one two"); + const span = spanOfTokens((command as ShellCommand).tokens); + + expect(span).toEqual({ start: 4, end: 16 }); + }); +}); diff --git a/src/rules/utils.ts b/src/rules/utils.ts new file mode 100644 index 0000000..805481b --- /dev/null +++ b/src/rules/utils.ts @@ -0,0 +1,234 @@ +/** + * @fileoverview Shared helpers for rules that analyze shell-form commands. + * + * Shell-form arguments are whitespace-delimited tokens. The helpers here + * split a token list into simple commands using standalone operator tokens + * and trailing semicolons, tracking quote state so that quoted operators + * (`echo "a && b"`) do not split; they intentionally do not implement full + * shell parsing. An unquoted word starting with `#` begins a shell comment + * and ends the scan. + */ + +//------------------------------------------------------------------------------ +// Imports +//------------------------------------------------------------------------------ + +import type { ArgumentNode, ShellFormNode } from "../types.js"; + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** Operator tokens that separate simple commands. */ +const COMMAND_SEPARATORS = new Set(["&&", "||", ";", "|", "&"]); + +/** + * A Dockerfile line continuation (with either escape character) plus any + * full-line comments and empty lines after it. Docker removes these + * before the shell sees the command, so they are removed from the raw + * token text before scanning it. + */ +const CONTINUATION = /[\\`][ \t]*\r?\n(?:[ \t]*(?:#[^\n]*)?\r?\n)*/gu; + +/** + * Matches text ending in a blank that is not escaped: preceded by an even + * number of backslashes. + */ +const UNESCAPED_TRAILING_BLANK = /(?:^|[^\\])(?:\\\\)*[ \t]$/u; + +/** A token made up only of subshell group openers, such as `(`. */ +const GROUP_OPENER = /^\(+$/u; + +/** + * A list of tokens with at least one element. + */ +export type NonEmptyTokens = [ArgumentNode, ...ArgumentNode[]]; + +/** + * A simple command inside a shell-form instruction: the tokens that make + * it up plus their cleaned-up string values. + */ +export interface ShellCommand { + /** The tokens of this command, in source order. */ + tokens: NonEmptyTokens; + + /** + * The token values with an unescaped leading `(` removed from the first + * word and a trailing separator `;` (unquoted and unescaped) removed + * from the last word. Standalone `(` tokens are omitted from both + * `tokens` and `words`. + */ + words: string[]; + + /** + * The source spelling of each word, with Dockerfile continuations + * removed but quotes and shell escapes kept, trimmed the same way as + * `words`. Use this to decode shell quoting, because `words` already + * has some escapes resolved. + */ + raw: string[]; +} + +/** + * Splits shell-form arguments into simple commands on `&&`, `||`, `;`, + * `|`, and `&` operator tokens, as well as on tokens ending with an + * unquoted, unescaped `;`. Scanning stops at an unquoted shell comment. + * Quoting and escaping are read from the source text because argument + * values already have some escapes resolved. + */ +export function splitShellCommands( + shellForm: ShellFormNode, + sourceText: string, +): ShellCommand[] { + const commands: ShellCommand[] = []; + let current: ArgumentNode[] = []; + let currentRaw: string[] = []; + + const push = (endsWithSeparator = false): void => { + // A standalone `(` opens a subshell; the command starts after it. + while ( + currentRaw.length > 0 && + GROUP_OPENER.test(currentRaw[0] ?? "") + ) { + current.shift(); + currentRaw.shift(); + } + + const [first, ...rest] = current; + + if (first) { + const tokens: NonEmptyTokens = [first, ...rest]; + const firstRaw = currentRaw[0] as string; + + /** + * Removes a group opener from the first word and a separator + * from the last word. + */ + const trim = (word: string, index: number): string => { + let result = word; + + // Only an unescaped `(` opens a group; `\(cd` is a word. + if (index === 0 && firstRaw.startsWith("(")) { + result = result.replace(/^\(+/u, ""); + } + + if (endsWithSeparator && index === tokens.length - 1) { + result = result.replace(/;(?:#.*)?$/u, ""); + } + + return result; + }; + + commands.push({ + tokens, + words: tokens.map((token, index) => trim(token.value, index)), + raw: currentRaw.map(trim), + }); + } + + current = []; + currentRaw = []; + }; + + let quote: string | null = null; + + /** + * Updates the open-quote state after consuming a token. Reports whether + * the token ends with a semicolon that is neither quoted nor escaped, + * which separates commands, and whether a comment starts right after + * such a semicolon (`ok;# note`). + */ + const consumeQuotes = ( + value: string, + ): { endsWithSeparator: boolean; startsComment: boolean } => { + let endsWithSeparator = false; + + for (let i = 0; i < value.length; i++) { + const character = value[i] as string; + + endsWithSeparator = false; + + if (character === "\\" && quote !== "'") { + i++; + } else if (character === ";" && quote === null) { + if (value[i + 1] === "#") { + return { endsWithSeparator: true, startsComment: true }; + } + + endsWithSeparator = true; + } else if ( + quote === null && + (character === '"' || character === "'") + ) { + quote = character; + } else if (character === quote) { + quote = null; + } + } + + return { endsWithSeparator, startsComment: false }; + }; + + let previousEnd: number | null = null; + + for (const argument of shellForm.arguments) { + const raw = sourceText + .slice(argument.start, argument.end) + .replace(CONTINUATION, ""); + const gap = + previousEnd === null + ? "" + : sourceText.slice(previousEnd, argument.start); + + previousEnd = argument.end; + + // A `#` starts a comment only at the start of a word: after an + // unescaped blank. An escaped blank (`word\ #tag`) keeps the `#` + // inside the word, but `word\ #note` has a second, unescaped + // blank before it. + if ( + quote === null && + raw.startsWith("#") && + (gap === "" || + UNESCAPED_TRAILING_BLANK.test(gap.replace(CONTINUATION, ""))) + ) { + // The shell ignores the rest of the line after a comment. + break; + } + + if (quote === null && COMMAND_SEPARATORS.has(raw)) { + push(); + continue; + } + + current.push(argument); + currentRaw.push(raw); + + const { endsWithSeparator, startsComment } = consumeQuotes(raw); + + if (endsWithSeparator) { + push(true); + } + + if (startsComment) { + break; + } + } + + push(); + + return commands; +} + +/** + * Returns the offsets spanning a non-empty list of tokens. + */ +export function spanOfTokens(tokens: Readonly): { + start: number; + end: number; +} { + return { + start: tokens[0].start, + end: (tokens.at(-1) as ArgumentNode).end, + }; +}