diff --git a/docs/rules/catalogue.adoc b/docs/rules/catalogue.adoc index ae445ac5..48e831ad 100644 --- a/docs/rules/catalogue.adoc +++ b/docs/rules/catalogue.adoc @@ -3,7 +3,7 @@ = Hypatia rule catalogue -Generated from `+lib/rules/*.ex+` on 2026-11-18. Regenerate with: +Generated from `+lib/rules/*.ex+` on 2026-11-24. Regenerate with: [source,bash] ---- @@ -43,7 +43,7 @@ a blank ID column means the module emits atom-keyed findings rather than prefixe |`+pr_automerge+` |— |Decide whether a pull request is an unambiguous bump or chore that may be |`+proof_obligation+` |— |ProofObligation recipe type for Hypatia. |`+proof_strategy_selection+` |— |Prover-strategy selection from VeriSimDB historical outcomes. -|`+research_extensions+` |RE001 RE002 RE003 RE004 RE005 RE006 RE007 RE008 RE009 RE010 RE011 |Static detection of GitHub Actions workflow defects sourced from +|`+research_extensions+` |RE001 RE002 RE003 RE004 RE005 RE006 RE007 RE008 RE009 RE010 RE011 RE012 |Static detection of GitHub Actions workflow defects sourced from |`+root_hygiene+` |ERR-GIT-001 |Root directory hygiene enforcement rules. |`+rsr_conformance+` |— |The RSR v2.0 conformance **oracle** (increment 3 of the HYP-S family): |`+rsr_criteria+` |— |Loads the **RSR v2.0 criteria SSOT** (`rsr-criteria-v2.a2ml` from diff --git a/hypatia_rules_praxis.deed b/hypatia_rules_praxis.deed index 07705598..2b4aab17 100644 --- a/hypatia_rules_praxis.deed +++ b/hypatia_rules_praxis.deed @@ -2581,6 +2581,15 @@ :excusable-at repo :scope-form exact-paths :status active) + ;; defaulted: excusable-at scope-form + (rule-def + :id "hypatia/research_extensions/RE012" + :text "a here-string fed by a command substitution" + :class advisory + :severity medium + :excusable-at repo + :scope-form exact-paths + :status active) ;; defaulted: text class excusable-at scope-form (rule-def :id "hypatia/root_hygiene/ERR-GIT-001" diff --git a/lib/hypatia/cli.ex b/lib/hypatia/cli.ex index 6a9cebb6..09e29389 100644 --- a/lib/hypatia/cli.ex +++ b/lib/hypatia/cli.ex @@ -714,7 +714,7 @@ defmodule Hypatia.CLI do results end - # Research Extensions (RE001-RE011) - Snyk/StepSecurity/Endor/academic + # Research Extensions (RE001-RE012) - Snyk/StepSecurity/Endor/academic results = if :research_extensions in rules do case Hypatia.Rules.ResearchExtensions.scan(repo_path) do @@ -733,7 +733,7 @@ defmodule Hypatia.CLI do reason: f.reason, action: to_string(f.action) } - # RE011 is `advisory: true` (flag-only): the class has to cross + # RE011 and RE012 are `advisory: true` (flag-only): the class has to cross # this seam, or `report_sets/2` counts it toward exit 1. |> Map.merge(Map.take(f, [:advisory])) end) diff --git a/lib/rules/research_extensions.ex b/lib/rules/research_extensions.ex index b6d66216..49782133 100644 --- a/lib/rules/research_extensions.ex +++ b/lib/rules/research_extensions.ex @@ -15,8 +15,8 @@ defmodule Hypatia.Rules.ResearchExtensions do the patterns surfaced by commercial / academic research that aren't yet covered by the OSS auditors. - Rule IDs RE001-RE011. RE011 is the one rule here that also reads shell - sources, not only workflows. + Rule IDs RE001-RE012. RE011 and RE012 are the rules here that also read + shell sources, not only workflows. ## Provenance map @@ -86,6 +86,12 @@ defmodule Hypatia.Rules.ResearchExtensions do fail-open in a gate. Flag-only (`:review`, `advisory: true`). Reproduced in metadatastician/standards on 2026-11-17; the detector is a port of its `scripts/check-pipe-grep-q.sh`. + - **RE012** — A here-string fed by a command substitution + (`consumer <<<"$(cmd)"`) in a shell source or a workflow `run:` block. + Bash keeps only the status of the command the here-string feeds, so a + failed `cmd` reads as empty input, under `set -e` and `pipefail` alike. + Flag-only (`:review`, `advisory: true`). Raised by CodeRabbit on + hyperpolymath/hypatia#1208. ## Architecture @@ -1887,19 +1893,19 @@ defmodule Hypatia.Rules.ResearchExtensions do do: re011_shell_findings(repo_path) ++ re011_workflow_findings(repo_path) defp re011_shell_findings(repo_path) do - for path <- re011_shell_files(repo_path), + for path <- shell_files(repo_path), rel = Path.relative_to(path, repo_path), {:ok, content} <- [File.read(path)], lines = String.split(content, "\n"), pipefail = re011_script_pipefail(content, "the file does not set it"), {line, _offset, text} <- pipe_grep_q_lines(content), - not re011_reviewed?(lines, line) do + not shell_line_reviewed?(lines, line, "RE011") do re011_finding(rel, line, text, pipefail) end end # The shell sources of a repo: by name, by directory, by shebang. - defp re011_shell_files(repo_path) do + defp shell_files(repo_path) do {output, _status} = System.cmd( "find", @@ -1920,12 +1926,12 @@ defmodule Hypatia.Rules.ResearchExtensions do rel = Path.relative_to(path, repo_path) String.ends_with?(rel, ".sh") or String.starts_with?(rel, ".githooks/") or - re011_shell_shebang?(path) + shell_shebang?(path) end) |> Enum.sort() end - defp re011_shell_shebang?(path) do + defp shell_shebang?(path) do with {:ok, "#!" <> _ = head} <- File.open(path, [:read, :binary], &IO.binread(&1, 256)) do Regex.match?(@re011_shebang, head |> String.split("\n", parts: 2) |> hd()) else @@ -1939,7 +1945,7 @@ defmodule Hypatia.Rules.ResearchExtensions do bytes = File.read!(path), source = String.split(bytes, "\n"), {line, text, pipefail} <- re011_workflow_hits(Workflow.parse(bytes, rel), bytes), - not re011_reviewed?(source, line) do + not shell_line_reviewed?(source, line, "RE011") do re011_finding(rel, line, text, pipefail) end end @@ -1948,14 +1954,7 @@ defmodule Hypatia.Rules.ResearchExtensions do defp re011_workflow_hits({:ok, nil}, _bytes), do: [] defp re011_workflow_hits({:ok, %Workflow{} = workflow}, _bytes) do - workflow_shell = re011_default_shell(workflow.doc) - - for job <- workflow.jobs, - # `<- [...]`, not `=`: a nil shell is a value here, not a filter. - job_shell <- [re011_default_shell(job.node) || workflow_shell], - step <- job.steps, - {script, line_of} <- Workflow.strings(re011_child(step.node, "run")), - shell <- [Workflow.text(re011_child(step.node, "shell")) || job_shell], + for {script, line_of, shell} <- run_scripts(workflow), pipefail = re011_step_pipefail(script, shell), {_line, offset, text} <- pipe_grep_q_lines(script) do {line_of.(offset), text, pipefail} @@ -1969,6 +1968,23 @@ defmodule Hypatia.Rules.ResearchExtensions do for {line, _offset, text} <- pipe_grep_q_lines(bytes), do: {line, text, unknown} end + # Every `run:` script of a parsed workflow, as `{script, line_of, shell}`: + # `line_of` maps a byte offset in the script to its source line, and + # `shell` is the step's `shell:`, else the job's `defaults.run.shell`, + # else the workflow's, else nil. Read by RE011 and RE012. + defp run_scripts(%Workflow{} = workflow) do + workflow_shell = re011_default_shell(workflow.doc) + + for job <- workflow.jobs, + # `<- [...]`, not `=`: a nil shell is a value here, not a filter. + job_shell <- [re011_default_shell(job.node) || workflow_shell], + step <- job.steps, + {script, line_of} <- Workflow.strings(re011_child(step.node, "run")), + shell <- [Workflow.text(re011_child(step.node, "shell")) || job_shell] do + {script, line_of, shell} + end + end + # A mapping's value for `key`, read through an alias as Hypatia.Workflow # reads it. defp re011_child(node, key) do @@ -2026,13 +2042,14 @@ defmodule Hypatia.Rules.ResearchExtensions do end) end - # A line is reviewed when it, or the line above it, carries the directive. - defp re011_reviewed?(lines, line) do + # A line is reviewed for `rule` when it, or the line above it, carries the + # directive. Used by RE011 and RE012. + defp shell_line_reviewed?(lines, line, rule) do Hypatia.ScannerSuppression.inline_allowed?( Enum.at(lines, line - 1), line > 1 && Enum.at(lines, line - 2), "research_extensions", - "RE011" + rule ) end @@ -2178,6 +2195,367 @@ defmodule Hypatia.Rules.ResearchExtensions do Regex.match?(~r/(?:^|[^|&])\|$/, t) or String.ends_with?(t, "|&") end + # ─── RE012: a here-string fed by a command substitution ───────────── + + @re012_fix "capture, then feed: `out=$(cmd) || ; consumer <<<\"$out\"`" + + # A producer that cannot fail here: a lone `echo`, or a `printf` whose format + # is a quoted literal not starting with `-` and converting only `%s` (and + # `%%`), with literal arguments only: no `$` (an expansion can fail before + # the builtin runs), redirection, pipe, list or substitution. + @re012_benign ~r/\A[[:space:]]*(?:echo|printf[[:space:]]+(?:'(?!-)(?:[^'%]|%%|%s)*'|"(?!-)(?:[^"%$`\\]|\\.|%%|%s)*"))(?:[[:space:]]+[^|;&`$<>()]*)?[[:space:]]*\z/ + + # The shells a workflow step's script is read in: `<<<` means nothing to + # any other interpreter (pwsh, python3, node, ruby, cmd, ...). + @re012_shells ~w(bash sh dash zsh ksh) + + # A simple command so far with no command name: reserved words that start + # a command, then assignments and redirections only (see hs_command_less?/1). + @re012_command_less ~r/\A[[:space:]]*(?:(?:if|then|else|elif|do|while|until|!|time|\{)[[:space:]]+)*(?:(?:[A-Za-z_][A-Za-z0-9_]*(?:\[[^\]]*\])?\+?=(?:'[^']*'|"(?:[^"\\]|\\.)*"|[^[:space:]'"])*|[0-9]*(?:<<<|<<-?|>>|<>|>&|<&|>\||[<>])[[:space:]]*(?:'[^']*'|"(?:[^"\\]|\\.)*"|[^[:space:]'"<>;&|])+)(?:[[:space:]]+|\z))*\z/ + + @doc """ + RE012: a here-string fed by a command substitution, `consumer <<<"$(cmd)"`, + in a shell source or in a workflow `run:` block. + + Bash keeps only the status of the command the here-string feeds. The exit + status of `cmd` is discarded: `set -e` does not fire on it, `pipefail` + does not apply (there is no pipeline), and `shopt -s inherit_errexit` does + not change it. A failed `cmd` reads as empty input. `if grep -q BAD + <<<"$(scan)"` then reads a crashed scan as "nothing bad"; `while read …; + done <<<"$(list)"` runs zero times; `read -r v <<<"$(get)"` leaves `v` + empty with status 0. The fix is to capture first, in an assignment, whose + status is `cmd`'s: `out=$(cmd) || ; consumer <<<"$out"`. + Provenance: CodeRabbit on hyperpolymath/hypatia#1208 + (`scripts/check-readme-claims.sh`, `tests/rules-praxis-test.sh`); owner + decision of 2026-11-24, "a rule, every here-string". Reproduced on bash + 5.2.21: `bash -ec 'read -r v <<<"$(exit 3)"; echo $?'` prints `0`. + + ## What is read + + The same sources as RE011: every shell source (`*.sh`, `.githooks/`, a + shell shebang), and the `run:` script of every step of every workflow, + read from the parsed workflow. A step is read when it has no `shell:`, a + blank one, or one whose interpreter is `bash`, `sh`, `dash`, `zsh` or `ksh` + (a path and `.exe` are ignored); any other interpreter (`pwsh`, `python3 + {0}`, `node {0}`, `cmd`, ...) has no `<<<`. A workflow the reader refuses + is scanned as plain lines. + + ## What is detected + + A `<<<` outside quotes and comments whose word holds a command + substitution, `$(…)` or a backquote, anywhere in it: `<<<"$(cmd)"`, + `<<< $(cmd)`, `<<<"prefix $(cmd)"`, `` <<<"`cmd`" ``. An arithmetic + expansion `$((…))` runs no command, but a substitution inside it does and + is read (`<<<"$(( $(count) + 1 ))"`). A here-string inside a substitution + or a backquote body (`x=$(grep -c . <<<"$(cmd)")`) is read too. Every + here-string on a line, and every substitution in its word, is read; the + finding lists them all. A backslash escapes nothing inside single quotes. + Each line is read on its own, with full-line comments ignored. + + Not reported: a here-string in a command with no command name (only + assignments and redirections, `x=1 <<<"$(cmd)"`, or `<<<"$(cmd)"` alone). + Such a command's status is that of its last command substitution, and bash + performs the redirections after the assignments, so the status is kept. + The end of a compound command (`done`, `fi`, `}`, `)`) counts as a command. + + Not detected: the word held in a variable; process substitution (`done < + <(cmd)`), which loses the status in the same way; a pipe (`cmd | while + read`), which is RE011's territory under pipefail. A heredoc body, or a + string that spans lines, that spells the form is a false positive. + + ## Severity + + `:warn` (medium), whatever `set -e` or `pipefail` say, since neither + reaches the lost status. `:info` only when every substitution on the line + is a lone `echo`, or a `printf` whose format is a quoted literal that does + not start with `-` and converts only `%s` (and `%%`), each with literal + arguments only: no option, parameter expansion, redirection, pipe, list or + nested substitution. Neither fails then, so nothing is lost. Anything else + can fail (`printf '%d' x`, `printf '-Z'`, `echo "${v:?}"`, an unset `$v` + under `set -u`) and is `:warn`. + + ## Flag-only + + Action `:review`, every finding `advisory: true`, as RE011: the rule names + the fix and never applies it, and an advisory finding never counts toward + the CLI exit code. A reviewed line carries `hypatia: allow + research_extensions/RE012 -- ` (or `hypatia:ignore RE012 -- + `) on the line itself or on the line above. + """ + def re012_here_string_substitution(repo_path), + do: re012_shell_findings(repo_path) ++ re012_workflow_findings(repo_path) + + defp re012_shell_findings(repo_path) do + for path <- shell_files(repo_path), + rel = Path.relative_to(path, repo_path), + {:ok, content} <- [File.read(path)], + lines = String.split(content, "\n"), + {line, _offset, text, producers} <- here_string_substitution_lines(content), + not shell_line_reviewed?(lines, line, "RE012") do + re012_finding(rel, line, text, producers) + end + end + + defp re012_workflow_findings(repo_path) do + for path <- Enum.sort(workflow_files(repo_path)), + rel = Path.relative_to(path, repo_path), + bytes = File.read!(path), + source = String.split(bytes, "\n"), + {line, text, producers} <- re012_workflow_hits(Workflow.parse(bytes, rel), bytes), + not shell_line_reviewed?(source, line, "RE012") do + re012_finding(rel, line, text, producers) + end + end + + defp re012_workflow_hits({:ok, nil}, _bytes), do: [] + + defp re012_workflow_hits({:ok, %Workflow{} = workflow}, _bytes) do + for {script, line_of, shell} <- run_scripts(workflow), + re012_shell?(shell), + {_line, offset, text, producers} <- here_string_substitution_lines(script) do + {line_of.(offset), text, producers} + end + end + + defp re012_workflow_hits({:error, _error}, bytes) do + for {line, _offset, text, producers} <- here_string_substitution_lines(bytes), + do: {line, text, producers} + end + + # No `shell:` runs bash (or sh); an empty or blank one names no executable, + # and the script is still read. Otherwise the step is read only when its + # interpreter is one of @re012_shells (a path and `.exe` are ignored). + defp re012_shell?(nil), do: true + + defp re012_shell?(shell) do + case String.split(shell, ~r/[[:space:]]+/, trim: true) do + [] -> + true + + [first | _] -> + first + |> Path.basename() + |> String.replace_suffix(".exe", "") + |> then(&(&1 in @re012_shells)) + end + end + + # True when a substitution's command cannot fail on its own: see @re012_benign. + defp re012_benign?(producer), do: is_binary(producer) and Regex.match?(@re012_benign, producer) + + defp re012_finding(rel, line, text, producers) do + benign? = Enum.all?(producers, &re012_benign?/1) + # The producer the finding names: the first that can fail, else the first. + producer = Enum.find(producers, hd(producers), &(not re012_benign?(&1))) + + reason = + if benign? do + "#{rel}:#{line} feeds a here-string from a lone `echo`, or a `printf` whose " <> + "format converts only `%s`, which does not fail here, so no status is lost; " <> + "a plain expansion says the same. Fix: #{@re012_fix}" + else + "#{rel}:#{line} feeds a here-string from a command substitution: bash keeps only " <> + "the status of the command the here-string feeds, so the substituted command's " <> + "failure is discarded (set -e, pipefail and inherit_errexit alike) and reads as " <> + "empty input. Fix: #{@re012_fix}" + end + + %{ + rule: "RE012", + # Never part of an exit code or a gate: see "Flag-only" in the @doc. + advisory: true, + file: rel, + severity: if(benign?, do: :info, else: :warn), + reason: reason, + action: :review, + detail: %{ + line: line, + text: String.trim(text), + producer: producer, + producers: producers, + strategy: :review, + fix: "Flag-only, never applied for you: #{@re012_fix}" + } + } + end + + @doc """ + The lines of a shell text that feed a here-string from a command + substitution, as `{line number, byte offset of the line, line, producers}`. + `producers` lists, in order, the text of every command substitution in the + word of every such here-string on the line: a substitution inside an + arithmetic expansion counts, and nil stands for one that does not close on + the line. + """ + def here_string_substitution_lines(text) when is_binary(text) do + {hits, _offset} = + text + |> String.split("\n") + |> Enum.with_index(1) + |> Enum.reduce({[], 0}, fn {raw, no}, {hits, offset} -> + line = String.replace_suffix(raw, "\r", "") + next = offset + byte_size(raw) + 1 + + producers = + if Regex.match?(~r/^[[:space:]]*#/, line), do: [], else: hs_walk(line, :none, true, "") + + case producers do + [] -> {hits, next} + _ -> {[{no, offset, line, producers} | hits], next} + end + end) + + Enum.reverse(hits) + end + + # Walk a line in a quote state (:none, :single, :double); `word_start?` is + # true at the start of the line or after blank space, where `#` opens a + # comment; `seg` is the text of the current simple command so far. Returns + # the producers of every here-string fed by a command substitution, in + # order; [] when there is none. + defp hs_walk(<<>>, _state, _ws, _seg), do: [] + + defp hs_walk(<>, :single, _ws, seg), + do: hs_walk(rest, :none, false, seg <> "'") + + defp hs_walk(<>, :single, _ws, seg), + do: hs_walk(rest, :single, false, seg <> <>) + + defp hs_walk(<>, state, _ws, seg), + do: hs_walk(rest, state, false, seg <> <>) + + defp hs_walk(<>, _state, _ws, _seg), do: [] + + defp hs_walk(<>, :double, _ws, seg), + do: hs_walk(rest, :none, false, seg <> "\"") + + defp hs_walk(<>, :none, _ws, seg), + do: hs_walk(rest, :double, false, seg <> "\"") + + defp hs_walk(<>, :none, _ws, seg), + do: hs_walk(rest, :single, false, seg <> "'") + + defp hs_walk(<>, :none, true, _seg), do: [] + + # The word's own producers, then the rest of the line from just after `<<<`, + # so a here-string inside one of the word's substitutions is read too. A + # command with no command name (only assignments and redirections) keeps + # the status of its last command substitution, and bash performs its + # redirections last, so its here-string loses nothing and is not reported. + defp hs_walk(<<"<<<", rest::binary>>, :none, _ws, seg) do + own = if hs_command_less?(seg), do: [], else: hs_word(String.trim_leading(rest), :none) + own ++ hs_walk(rest, :none, false, seg <> "<<<") + end + + # A command substitution or a backquote body, in :none or :double: read its + # body as a fresh command, then go on after it in the state we were in. + defp hs_walk(<<"$(", rest::binary>>, state, _ws, seg), + do: hs_walk_body(hs_close(rest), rest, state, seg, "$(", ")") + + defp hs_walk(<>, state, _ws, seg), + do: hs_walk_body(hs_backquote(rest), rest, state, seg, "`", "`") + + # A command separator, or the start of a subshell, begins a new command. + defp hs_walk(<>, :none, _ws, _seg) when c in [?;, ?&, ?|, ?(], + do: hs_walk(rest, :none, true, "") + + defp hs_walk(<>, state, _ws, seg), + do: hs_walk(rest, state, c in [?\s, ?\t], seg <> <>) + + defp hs_walk_body({inner, after_}, _rest, state, seg, open, close), + do: + hs_walk(inner, :none, true, "") ++ + hs_walk(after_, state, false, seg <> open <> inner <> close) + + defp hs_walk_body(:open, rest, _state, _seg, _open, _close), do: hs_walk(rest, :none, true, "") + + # True when the command text so far holds no command name: only leading + # reserved words that start a command, assignments and redirections. The + # words that end a compound command (`done`, `fi`, `esac`, `}`, `)`) are + # a command name here: the here-string feeds that compound command. + defp hs_command_less?(seg), do: Regex.match?(@re012_command_less, seg) + + # The producers of the word after `<<<`: each `$(…)` or backquote in it, + # including those inside an arithmetic expansion, whose own `$((…))` runs no + # command. A backslash escapes the next byte except inside single quotes. + defp hs_word(<<>>, _state), do: [] + defp hs_word(<>, :single), do: hs_word(rest, :none) + defp hs_word(<<_, rest::binary>>, :single), do: hs_word(rest, :single) + defp hs_word(<>, state), do: hs_word(rest, state) + + defp hs_word(<<"$((", rest::binary>>, state) do + case hs_close("(" <> rest) do + {inner, <>} -> hs_subs(inner) ++ hs_word(after_, state) + {inner, after_} -> hs_subs(inner) ++ hs_word(after_, state) + :open -> hs_subs(rest) + end + end + + defp hs_word(<<"$(", rest::binary>>, state), do: hs_word_sub(hs_close(rest), state) + defp hs_word(<>, state), do: hs_word_sub(hs_backquote(rest), state) + defp hs_word(<>, :none), do: hs_word(rest, :double) + defp hs_word(<>, :double), do: hs_word(rest, :none) + defp hs_word(<>, :none), do: hs_word(rest, :single) + + defp hs_word(<>, :none) when c in [?\s, ?\t, ?;, ?&, ?|, ?), ?<, ?>], + do: [] + + defp hs_word(<<_, rest::binary>>, state), do: hs_word(rest, state) + + defp hs_word_sub({inner, after_}, state), do: [inner | hs_word(after_, state)] + defp hs_word_sub(:open, _state), do: [nil] + + # Every command substitution in an arithmetic body; quotes are not read. + defp hs_subs(<<>>), do: [] + defp hs_subs(<<"$((", rest::binary>>), do: hs_subs(rest) + defp hs_subs(<<"$(", rest::binary>>), do: hs_subs_next(hs_close(rest)) + defp hs_subs(<>), do: hs_subs_next(hs_backquote(rest)) + defp hs_subs(<<_, rest::binary>>), do: hs_subs(rest) + + defp hs_subs_next({inner, after_}), do: [inner | hs_subs(after_)] + defp hs_subs_next(:open), do: [nil] + + # The text after a backquote up to the next unescaped one, as {inner, after}, + # or :open when the line ends first. + defp hs_backquote(text), do: hs_backquote(text, []) + defp hs_backquote(<<>>, _acc), do: :open + + defp hs_backquote(<>, acc), + do: {acc |> Enum.reverse() |> IO.iodata_to_binary(), rest} + + defp hs_backquote(<>, acc), do: hs_backquote(rest, [n, ?\\ | acc]) + defp hs_backquote(<>, acc), do: hs_backquote(rest, [c | acc]) + + # The text after `$(` up to its matching `)`, as {inner, after}, or :open + # when the line ends first. Quotes inside are honoured. + defp hs_close(text), do: hs_close(text, 0, :none, []) + + defp hs_close(<<>>, _depth, _state, _acc), do: :open + + defp hs_close(<>, 0, :none, acc), + do: {acc |> Enum.reverse() |> IO.iodata_to_binary(), rest} + + defp hs_close(<>, depth, state, acc) do + {depth, state} = + case {c, state} do + {?', :none} -> {depth, :single} + {?', :single} -> {depth, :none} + {?", :none} -> {depth, :double} + {?", :double} -> {depth, :none} + {?(, :none} -> {depth + 1, :none} + {?), :none} -> {depth - 1, :none} + _ -> {depth, state} + end + + case {c, rest, state} do + {?\\, <>, s} when s != :single -> + hs_close(rest2, depth, state, [n, c | acc]) + + _ -> + hs_close(rest, depth, state, [c | acc]) + end + end + # ─── Scan facade ──────────────────────────────────────────────────── @doc """ @@ -2204,7 +2582,8 @@ defmodule Hypatia.Rules.ResearchExtensions do re008_spoofable_bot_gate(repo_path) ++ re009_fromjson_secret(repo_path) ++ re010_workflow_run_artifact_no_provenance(repo_path) ++ - re011_pipe_into_quiet_grep(repo_path) + re011_pipe_into_quiet_grep(repo_path) ++ + re012_here_string_substitution(repo_path) %{ findings: findings, diff --git a/lib/rules/rules.ex b/lib/rules/rules.ex index 13eb8344..e52532a7 100644 --- a/lib/rules/rules.ex +++ b/lib/rules/rules.ex @@ -708,13 +708,14 @@ defmodule Hypatia.Rules do defdelegate scan_branch_protection(owner, repo), to: BranchProtection, as: :scan @doc """ - Run research-extension checks (RE001-RE011) drawn from Snyk, + Run research-extension checks (RE001-RE012) drawn from Snyk, StepSecurity, Endor Labs and the academic supply-chain literature: absent/audit-only harden-runner, cache-key poisoning via head_ref, tag-pinned containers, exit-swallowing test steps, unpinned nested composite uses, workflow-level secret env, spoofable bot gates, - fromJSON(secrets), provenance-free workflow_run artifacts, and (RE011, - flag-only) a pipe into a quiet grep in shell sources and `run:` blocks. + fromJSON(secrets), provenance-free workflow_run artifacts, and (RE011 and + RE012, flag-only) a pipe into a quiet grep and a here-string fed by a + command substitution, in shell sources and `run:` blocks. Pure local file scan - no GitHub API. """ defdelegate scan_research_extensions(repo_path, opts \\ []), to: ResearchExtensions, as: :scan diff --git a/test/research_extensions_re012_test.exs b/test/research_extensions_re012_test.exs new file mode 100644 index 00000000..58fdd216 --- /dev/null +++ b/test/research_extensions_re012_test.exs @@ -0,0 +1,401 @@ +# SPDX-License-Identifier: MPL-2.0 +# Copyright (c) 2026 Jonathan D.A. Jewell (hyperpolymath) + +defmodule Hypatia.Rules.ResearchExtensionsRE012Test do + @moduledoc """ + RE012: a here-string fed by a command substitution (`consumer <<<"$(cmd)"`). + + Bash keeps only the status of the command the here-string feeds, so `cmd`'s + failure is discarded. Each spelling of the form is flagged once; what is not + the form (a here-string from a variable, a `<<<` in quotes or a comment, an + arithmetic expansion) is not. The first describe block runs bash itself, so + the claim the rule rests on is checked, not assumed. + """ + use ExUnit.Case, async: true + + alias Hypatia.CLI + alias Hypatia.Rules.ResearchExtensions + + @tmp_dir System.tmp_dir!() + + defp repo(files) do + root = Path.join(@tmp_dir, "re012_#{System.unique_integer([:positive])}") + File.rm_rf!(root) + File.mkdir_p!(root) + + for {rel, content} <- files do + path = Path.join(root, rel) + File.mkdir_p!(Path.dirname(path)) + File.write!(path, content) + end + + on_exit(fn -> File.rm_rf!(root) end) + root + end + + defp script(lines), do: Enum.join(["#!/usr/bin/env bash", "set -euo pipefail" | lines], "\n") + + defp scan(files), do: files |> repo() |> ResearchExtensions.re012_here_string_substitution() + + defp lines(text), + do: text |> ResearchExtensions.here_string_substitution_lines() |> Enum.flat_map(&elem(&1, 3)) + + # ─── The claim, checked against bash ──────────────────────────────── + + describe "bash discards the substituted command's status" do + @describetag :bash + + for {label, body} <- [ + {"read", ~S/read -r v <<<"$(exit 3)"; echo "status=$?"/}, + {"a while loop", ~S/while read -r l; do :; done <<<"$(exit 4)"; echo "status=$?"/}, + {"cat", ~S/cat <<<"$(exit 7)"; echo "status=$?"/} + ] do + test "#{label}: set -euo pipefail and inherit_errexit do not see it" do + {out, 0} = + System.cmd("bash", [ + "-c", + "set -euo pipefail; shopt -s inherit_errexit; " <> unquote(body) + ]) + + assert out =~ "status=0" + end + end + + test "the fix, capture then feed, does see it" do + {_out, status} = + System.cmd("bash", ["-c", ~S/set -e; out=$(exit 5); cat <<<"$out"; echo reached/]) + + assert status == 5 + end + end + + # ─── What is flagged ──────────────────────────────────────────────── + + describe "each spelling is flagged" do + for {label, line, producer} <- [ + {"grep -q", ~S/grep -q x <<<"$(cmd)"/, "cmd"}, + {"read", ~S/IFS='|' read -r a b <<<"$(parse "$m")"/, ~S/parse "$m"/}, + {"done", ~S/done <<<"$(list | sort)"/, "list | sort"}, + {"unquoted, after a blank", ~S/read -r v <<< $(get a)/, "get a"}, + {"text before the substitution", ~S/cat <<<"pre $(cmd) post"/, "cmd"}, + {"after a ${var}", ~S/cat <<<"${v}$(z)"/, "z"}, + {"a backquote", ~S/cat <<<"pre `cmd`"/, "cmd"}, + {"inside an assignment's substitution", ~S/n=$(grep -c . <<<"$(cmd)")/, "cmd"}, + {"after an earlier here-string", ~S/y=$(a << then(&scan([{"s.sh", &1}])) |> Enum.map(& &1.detail.line) + end + end + + describe "what is not the form is not flagged" do + for {label, line} <- [ + {"a here-string from a variable", ~S/grep -q x <<<"$out"/}, + {"a here-string from a literal", ~S/cat <<<"done"/}, + {"<<< inside double quotes", ~S/echo "<<<$(x)"/}, + {"<<< inside single quotes", ~S/grep -F '<<<"$(' f/}, + {"a substitution inside single quotes after <<<", ~S/cat <<<'$(x)'/}, + {"an arithmetic expansion", ~S/cat <<<"$((1 + 2))"/}, + {"a full-line comment", ~S/# grep -q x <<<"$(c)"/}, + {"a trailing comment", ~S/f # grep <<<"$(c)"/}, + {"a heredoc", ~S/cat <e <<<"$(cmd)"/}, + {"a bare here-string", ~S/<<<"$(cmd)"/}, + {"an assignment-only command after a separator", ~S/f; x=$(a) <<<"$(cmd)"/} + ] do + test label do + assert [] == lines(unquote(line)) + end + end + end + + # ─── Severity ─────────────────────────────────────────────────────── + + describe "severity" do + test "a command is :warn" do + assert [%{severity: :warn}] = scan([{"s.sh", script([~S/grep -q x <<<"$(cmd)"/])}]) + end + + test "a lone printf or echo of literal words cannot fail here: :info" do + for line <- [ + ~S/grep -qx -- "$j" <<<"$(printf '%s\n' a b)"/, + ~S/cat <<<"$(echo hello world)"/ + ] do + assert [%{severity: :info} = f] = scan([{"s.sh", script([line])}]) + assert f.reason =~ "does not" + end + end + + for {label, line} <- [ + {"a redirection", ~S/cat <<<"$(printf x > f)"/}, + {"a pipe", ~S/cat <<<"$(printf x | cmd)"/}, + {"a list", ~S/cat <<<"$(printf x; cmd)"/}, + {"a nested substitution", ~S/cat <<<"$(echo "$(cmd)")"/}, + {"a backquote around a pipe", ~S/cat <<<"`echo x | cmd`"/} + ] do + test "printf or echo with #{label} is :warn" do + assert [%{severity: :warn}] = scan([{"s.sh", script([unquote(line)])}]) + end + end + + # Codex and CodeRabbit on #1232: printf fails on a bad conversion or option. + for {label, line} <- [ + {"a numeric conversion", ~S/cat <<<"$(printf '%d\n' "$n")"/}, + {"an option", ~S/cat <<<"$(printf -Z)"/}, + {"-v", ~S/cat <<<"$(printf -v x '%s' y)"/}, + {"an unquoted format", ~S/cat <<<"$(printf $fmt x)"/}, + {"a format from a variable", ~S/cat <<<"$(printf "$fmt" x)"/}, + # CodeRabbit on #1232: a quoted format can still be an option. + {"a quoted option as the format", ~S/cat <<<"$(printf '-Z')"/}, + # Codex on #1232: an expansion can fail before the builtin runs. + {"a ${v:?} argument", ~S/cat <<<"$(echo "${value:?missing}")"/}, + {"a $var argument (unset under set -u)", ~S/cat <<<"$(printf '%s' "$value")"/} + ] do + test "printf with #{label} can fail: :warn" do + assert [%{severity: :warn}] = scan([{"s.sh", script([unquote(line)])}]) + end + end + + test "one failing substitution on the line makes it :warn, and is the one named" do + for line <- [ + ~S/cat <<<"$(echo safe)"; cat <<<"$(scan)"/, + ~S/cat <<<"$(printf '%s' p)$(scan)"/ + ] do + assert [%{severity: :warn, detail: %{producer: "scan", producers: [_, "scan"]}}] = + scan([{"s.sh", script([line])}]) + end + end + + test "set -e and pipefail do not change it" do + bare = "#!/bin/bash\ngrep -q x <<<\"$(cmd)\"\n" + assert [%{severity: :warn}] = scan([{"s.sh", bare}]) + assert [%{severity: :warn}] = scan([{"s.sh", script([~S/grep -q x <<<"$(cmd)"/])}]) + end + end + + # ─── Workflows ────────────────────────────────────────────────────── + + describe "a workflow run: block" do + defp workflow(text), do: scan([{".github/workflows/w.yml", text}]) + + test "is flagged at its source line" do + wf = """ + on: push + jobs: + t: + runs-on: ubuntu-latest + steps: + - shell: bash + run: | + echo start + grep -q x <<<"$(cmd)" + """ + + assert [%{file: ".github/workflows/w.yml", detail: %{line: 9}}] = workflow(wf) + end + + test "a step in another interpreter is not read" do + for shell <- [ + "pwsh", + "pwsh.exe", + "powershell", + "python", + "python3 {0}", + "/usr/bin/python {0}", + "node {0}", + "ruby {0}", + "cmd" + ] do + wf = """ + on: push + jobs: + t: + runs-on: ubuntu-latest + steps: + - shell: #{shell} + run: grep -q x <<<"$(cmd)" + """ + + assert [] == workflow(wf), shell + end + end + + test "a step in a POSIX-family shell is read" do + for shell <- [ + "bash", + "sh", + "bash -eo pipefail {0}", + "bash.exe {0}", + "/bin/zsh {0}", + "dash {0}", + "ksh {0}" + ] do + wf = """ + on: push + jobs: + t: + runs-on: ubuntu-latest + steps: + - shell: #{shell} + run: grep -q x <<<"$(cmd)" + """ + + assert [_] = workflow(wf), shell + end + end + + test "an empty shell: is not a reason to skip, nor to crash (#1232 review)" do + for shell <- ["''", "' '"] do + wf = """ + on: push + jobs: + t: + runs-on: ubuntu-latest + steps: + - shell: #{shell} + run: grep -q x <<<"$(cmd)" + """ + + assert [%{detail: %{line: 7}}] = workflow(wf), shell + end + end + + test "text outside run: is not read" do + wf = """ + on: push + jobs: + t: + runs-on: ubuntu-latest + env: + HINT: 'grep -q x <<<"$(cmd)"' + steps: + - name: 'grep -q x <<<"$(cmd)"' + run: echo ok + """ + + assert [] == workflow(wf) + end + + test "a workflow the reader refuses is still scanned" do + wf = """ + on: push + x: &x + runs-on: ubuntu-latest + jobs: + t: + <<: *x + steps: + - run: grep -q x <<<"$(cmd)" + """ + + assert [%{detail: %{line: 8}}] = workflow(wf) + end + end + + # ─── The reviewed escape ──────────────────────────────────────────── + + describe "a reviewed line" do + test "hypatia: allow on the line above" do + lines = [ + "# hypatia: allow research_extensions/RE012 -- cmd cannot fail here", + ~S/grep -q x <<<"$(cmd)"/ + ] + + assert [] == scan([{"s.sh", script(lines)}]) + end + + test "hypatia:ignore at the end of the line" do + lines = [~S/grep -q x <<<"$(cmd)" # hypatia:ignore RE012 -- cmd cannot fail here/] + assert [] == scan([{"s.sh", script(lines)}]) + end + + test "a directive for RE011 does not cover it" do + lines = ["# hypatia: allow research_extensions/RE011 -- other rule", ~S/cat <<<"$(c)"/] + assert [%{rule: "RE012"}] = scan([{"s.sh", script(lines)}]) + end + end + + # ─── Flag-only, and through the CLI ───────────────────────────────── + + describe "the finding" do + test "says what was found, why, and the fix; flag-only and advisory" do + assert [f] = + scan([ + {"scripts/g.sh", script([~S/if grep -q BAD <<<"$(scan)"; then exit 1; fi/])} + ]) + + assert f.rule == "RE012" + assert f.advisory == true + assert f.action == :review + assert f.detail.strategy == :review + assert f.detail.producer == "scan" + assert f.reason =~ "scripts/g.sh:3" + assert f.reason =~ "here-string" + assert f.reason =~ ~s(out=$(cmd\) || ; consumer <<<"$out") + refute Map.has_key?(f, :fix_script) + end + + test "scan/2 runs RE012 and never recommends auto-execution for it" do + root = repo([{"s.sh", script([~S/cat <<<"$(c)"/])}]) + result = ResearchExtensions.scan(root) + + assert [%{rule: "RE012"}] = result.findings + assert [%{rule: "RE012", action: :review, confidence: confidence}] = result.dispatch + assert confidence < 0.95 + end + + test "the CLI carries it as advisory, so it never fails a scan" do + root = repo([{"scripts/s.sh", script([~S/cat <<<"$(c)"/])}]) + + assert [finding] = + root + |> CLI.collect_findings([:research_extensions]) + |> Enum.filter(&(&1.type == "RE012")) + + assert finding.line == 3 + assert finding.severity == "warn" + assert finding.advisory == true + assert {[_], []} = CLI.report_sets([finding], %{severity: "medium", advisory: false}) + end + end +end