Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

ci: hand semgrep its arguments instead of letting a shell re-parse them (#104838)

Tom Piccirello4b4874a3b33b
diff --git a/.agents/skills/authoring-ci-workflows/SKILL.md b/.agents/skills/authoring-ci-workflows/SKILL.md
index aa90f03ccc00..809938eff342 100644
--- a/.agents/skills/authoring-ci-workflows/SKILL.md
+++ b/.agents/skills/authoring-ci-workflows/SKILL.md
@@ -28,7 +28,7 @@ The linters own the mechanical rules (below); this skill is the **judgment calls
## What the linters already enforce
Run `bin/hogli lint:workflows` and `actionlint` before pushing — they gate CI, and they (not this list) are the source of truth for what's enforced.
-Today that's: `timeout-minutes` on every job, the canonical PR concurrency block, a repo-wide budget for unscoped PR event dispatches, `dorny/paths-filter` negation safety, justification for full-depth checkouts, cache-write gating, semgrep service coverage, MCP path-filter coverage of the trees the MCP build compiles, required-check gate hygiene, secrets a reusable workflow reads being declared and passed by its callers, runner labels that name an OS version rather than a floating `-latest` alias, and generic GHA correctness (bad `secrets.*` / `needs:` refs, deprecated `::set-output`, unknown runner labels).
+Today that's: `timeout-minutes` on every job, the canonical PR concurrency block, a repo-wide budget for unscoped PR event dispatches, `dorny/paths-filter` negation safety, justification for full-depth checkouts, cache-write gating, semgrep service coverage, MCP path-filter coverage of the trees the MCP build compiles, required-check gate hygiene, secrets a reusable workflow reads being declared and passed by its callers, runner labels that name an OS version rather than a floating `-latest` alias, `#`-free values for the action inputs an inner shell re-parses, and generic GHA correctness (bad `secrets.*` / `needs:` refs, deprecated `::set-output`, unknown runner labels).
Third-party action digests are bumped by Renovate.
## Check what a condition does before you push it
@@ -282,6 +282,28 @@ Measured checkout-step durations, from the GitHub API on real runs:
Sparse-checkout `.nvmrc` if the job has no checkout.
- **Pin `setup-uv`'s `version:`** — an unpinned `setup-uv` calls the GitHub API on every job and burns the rate limit.
+## Never splice a caller's input into a command an inner shell re-parses
+
+A composite action that builds `sh -c "... $INPUT"` hands the container's shell a **script**, not a flag list. That inner shell re-parses it, and `exec` replaces the shell on the first command — so a token that ends a command there truncates every flag after it. With `#`, a newline or `;` the truncation is silent: `exec` never returns, nothing else runs, and the job exits 0. `&` and `|` truncate the command too, but the leftover flag then runs as a command of its own and the step fails with 127.
+
+The input reaches it looking innocent. Inside a YAML block scalar (`args: >-`) a `#` is **data**, not a YAML comment, and a more-indented line is not folded, so it keeps its newlines. Neither needs unusual input — a note or an indented flag is enough.
+
+Measured on [#101671](https://github.com/PostHog/posthog/pull/101671) before this was fixed: `semgrep-go` loaded 5 of the 7 configs it listed, `semgrep-rust` 5 of 7, `semgrep-general` 4 of 6, and the `--exclude-rule` / `--include` scopes below the comment went with them. CI was green throughout.
+
+Quoting harder is not the fix — the value already sits inside double quotes, and another pair collapses every flag into one argument. **Split it yourself and pass positional parameters**, the way `.github/actions/semgrep-ci` now does:
+
+```bash
+set -f # split on whitespace WITHOUT expanding globs
+semgrep_args=($SEMGREP_ARGS)
+set +f
+... sh -c 'exec tool ... "$@"' sh "${semgrep_args[@]}"
+```
+
+Nothing re-parses the value: each word reaches the tool verbatim, a glob arrives unexpanded for the tool to match itself, and a stray `#` becomes an argument the tool rejects loudly instead of a comment that eats the rest.
+
+`WF012` watches for the pattern coming back. It flags any action that splices an input into an inner shell, and checks that action's callers until it stops. An empty `SHELL_SPLIT_INPUTS` is the healthy state.
+`#` stays fine in every other input — `dorny/paths-filter` `filters:`, `actions/github-script` `script:`, a webhook `payload:` — so the rule is per-input, never blanket.
+
## Network fetches
Downloads from outside the runner need retries, or a transient reset becomes a red check with no findings ([actionlint died on `curl: (35)`](https://github.com/PostHog/posthog/actions/runs/32022348027/job/95364480249)).
diff --git a/.github/actions/semgrep-ci/action.yml b/.github/actions/semgrep-ci/action.yml
index e26983e4804b..ae2a7dba9b69 100644
--- a/.github/actions/semgrep-ci/action.yml
+++ b/.github/actions/semgrep-ci/action.yml
@@ -13,10 +13,12 @@ inputs:
args:
description: >
Arguments for `semgrep ci` (--config, --include/--exclude, --exclude-rule,
- --jobs, ...). Split on whitespace, so values must not contain spaces or
- quotes. Anchor --include/--exclude patterns with a leading slash
- (--include /bin); unanchored patterns also match same-named nested
- directories anywhere in the tree.
+ --jobs, ...). Split on whitespace and handed to semgrep as positional
+ parameters, so a single argument must not contain spaces or quotes.
+ Everything else reaches semgrep verbatim -- glob characters included,
+ unexpanded. Anchor --include/--exclude
+ patterns with a leading slash (--include /bin); unanchored patterns also
+ match same-named nested directories anywhere in the tree.
required: true
runs:
@@ -35,6 +37,24 @@ runs:
# auth from .git/config, and safe.directory because the workspace is
# owned by the runner user while the container runs as root.
run: |
+ # Split `args` HERE and pass the words as positional parameters.
+ # Never splice the string into the command the container shell
+ # parses: that inner shell re-parses it as a SCRIPT, and a token
+ # that ends a command there truncates every flag after it. With
+ # `#`, a newline or `;` the truncation is silent, because `exec`
+ # never returns and the job exits 0; `&` and `|` leave the flag to
+ # run as a command of its own, so the step fails with 127. A caller
+ # writes this value as a YAML block scalar, where `#` is data rather
+ # than a comment and a more-indented line keeps its newlines, so the
+ # hazard needs no unusual input.
+ # `set -f` splits on whitespace WITHOUT pathname expansion, so a
+ # glob reaches semgrep unexpanded and semgrep does its own matching.
+ # With `"$@"` a stray `#` is just an argument semgrep rejects loudly.
+ set -f
+ # shellcheck disable=SC2206 # deliberate word split; globbing disabled above
+ semgrep_args=($SEMGREP_ARGS)
+ set +f
+
docker run --rm \
-v "$GITHUB_WORKSPACE:/src" -w /src \
-v "$GITHUB_EVENT_PATH:/github-event.json:ro" \
@@ -45,4 +65,4 @@ runs:
-e GITHUB_REPOSITORY_ID -e GITHUB_REPOSITORY_OWNER_ID \
-e GH_TOKEN \
"$SEMGREP_IMAGE" \
- sh -c "git config --global --add safe.directory /src && exec semgrep ci --metrics=off --verbose --timeout 300 $SEMGREP_ARGS"
+ sh -c 'git config --global --add safe.directory /src && exec semgrep ci --metrics=off --verbose --timeout 300 "$@"' sh "${semgrep_args[@]}"
diff --git a/tools/hogli-commands/hogli_commands/tests/test_workflow_lint.py b/tools/hogli-commands/hogli_commands/tests/test_workflow_lint.py
index af82c9100ff4..ad16fc0d308b 100644
--- a/tools/hogli-commands/hogli_commands/tests/test_workflow_lint.py
+++ b/tools/hogli-commands/hogli_commands/tests/test_workflow_lint.py
@@ -16,7 +16,12 @@ import pytest
from click.testing import CliRunner
from hogli_commands.workflow_lint.check import CheckResult, WorkflowCheck
-from hogli_commands.workflow_lint.checks import CHECKS, _build_lookup, get_check
+from hogli_commands.workflow_lint.checks import (
+ CHECKS,
+ _build_lookup,
+ get_check,
+ shell_split_action_args as _ssaa,
+)
from hogli_commands.workflow_lint.checks.cache_writes import (
_can_run_on_branch_ref,
_is_gated,
@@ -34,6 +39,12 @@ from hogli_commands.workflow_lint.checks.pr_event_fanout import PrEventFanoutChe
from hogli_commands.workflow_lint.checks.required_gates import RequiredGateCheck
from hogli_commands.workflow_lint.checks.reusable_secret_passthrough import ReusableSecretPassthroughCheck
from hogli_commands.workflow_lint.checks.semgrep_services_coverage import SemgrepServicesCoverageCheck
+from hogli_commands.workflow_lint.checks.shell_split_action_args import (
+ SHELL_SPLIT_INPUTS,
+ ShellSplitActionArgsCheck,
+ derive_shell_split_inputs,
+ unparseable_actions,
+)
from hogli_commands.workflow_lint.cli import cmd_lint_workflows
from hogli_commands.workflow_lint.model import PR_TRIGGERS, Workflow, WorkflowParseError, read_workflows
@@ -2198,3 +2209,517 @@ class TestReusableSecretPassthroughCheck:
)
issues = ReusableSecretPassthroughCheck().run(_read_all(tmp_path)).issues
assert issues == [], [i.render() for i in issues]
+
+
+# ---------------------------------------------------------------------------
+# ShellSplitActionArgsCheck
+# ---------------------------------------------------------------------------
+
+
+def _write_table_actions(repo_root: Path, *, declared: bool = True) -> None:
+ for action, names in _ssaa.SHELL_SPLIT_INPUTS.items():
+ directory = repo_root / action
+ directory.mkdir(parents=True, exist_ok=True)
+ declarations = sorted(names) if declared else ["renamed"]
+ lines = ["name: A", "description: A", "inputs:"]
+ lines += [f" {name}:\n description: d\n required: true" for name in declarations]
+ lines += ["runs:", " using: composite", " steps:", " - shell: bash", " env:"]
+ lines += [f" {name.upper()}: ${{{{ inputs.{name} }}}}" for name in declarations]
+ refs = " ".join(f"${name.upper()}" for name in declarations)
+ lines += [f' run: sh -c "echo {refs}"']
+ (directory / "action.yml").write_text("\n".join(lines) + "\n")
+
+
+def _caller(args: str, *, uses: str = "./.github/actions/semgrep-ci") -> str:
+ return f"""
+ name: Security
+ on: [pull_request]
+ jobs:
+ semgrep:
+ runs-on: ubuntu-24.04
+ timeout-minutes: 5
+ steps:
+ - uses: {uses}
+ with:
+ image: semgrep/semgrep:1.0.0
+ args: >-
+ {args}
+ """
+
+
+class TestShellSplitActionArgsCheck:
+ @pytest.fixture(autouse=True)
+ def _hazardous_action(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ # The live table is empty because semgrep-ci stopped splicing. Enforcement
+ # still has to work for any action that has not been fixed yet, so these
+ # tests supply one.
+ monkeypatch.setattr(_ssaa, "SHELL_SPLIT_INPUTS", {".github/actions/semgrep-ci": frozenset({"args"})})
+
+ @staticmethod
+ def _run(repo_root: Path, workflow: str) -> list[str]:
+ workflows_dir = repo_root / ".github" / "workflows"
+ workflows_dir.mkdir(parents=True, exist_ok=True)
+ _write(workflows_dir, "ci-security.yaml", workflow)
+ check = ShellSplitActionArgsCheck(repo_root=repo_root)
+ return [issue.render() for issue in check.run(_read_all(workflows_dir)).issues]
+
+ def test_flags_a_hash_in_a_listed_input(self, tmp_path: Path) -> None:
+ _write_table_actions(tmp_path)
+ [issue] = self._run(
+ tmp_path,
+ _caller("--config p/security-audit\n # temporarily off\n --config p/python"),
+ )
+ assert "with.args" in issue, issue
+ assert "'#'" in issue and "hands this value to a shell" in issue, issue
+
+ def test_flags_a_semicolon_the_inner_shell_would_treat_as_a_terminator(self, tmp_path: Path) -> None:
+ _write_table_actions(tmp_path)
+ [issue] = self._run(tmp_path, _caller("--config p/python ; --include /posthog"))
+ assert "';'" in issue, issue
+
+ def test_flags_a_newline_a_more_indented_line_leaves_unfolded(self, tmp_path: Path) -> None:
+ # A folded scalar does not fold a MORE-INDENTED line: YAML keeps the breaks
+ # around it, so an author indenting one flag for readability ships a literal
+ # newline, which truncates the command exactly as a '#' does.
+ _write_table_actions(tmp_path)
+ [issue] = self._run(
+ tmp_path,
+ _caller("--config p/python\n --indented /posthog\n --jobs 4"),
+ )
+ assert "\\n" in issue or "newline" in issue, issue
+
+ def test_derivation_reads_a_single_quoted_shell_c_operand(self, tmp_path: Path) -> None:
+ # Actions substitutes `${{ inputs.x }}` before the shell parses, so a
+ # single-quoted script splices an input exactly as a double-quoted one does.
+ action_dir = tmp_path / ".github" / "actions" / "singlequoted"
+ action_dir.mkdir(parents=True)
+ (action_dir / "action.yml").write_text(
+ "name: A\ndescription: A\ninputs:\n flags:\n description: d\n required: true\n"
+ "runs:\n using: composite\n steps:\n - shell: bash\n"
+ " run: sh -c 'tool ${{ inputs.flags }}'\n",
+ encoding="utf-8",
+ )
+ derived = derive_shell_split_inputs(tmp_path)
+ assert derived.get(".github/actions/singlequoted") == frozenset({"flags"}), derived
+
+ @staticmethod
+ def _shipped_split() -> str:
+ """The `set -f` … `set +f` block from the real action, so these cannot drift from it."""
+ from hogli.manifest import REPO_ROOT
+
+ text = (REPO_ROOT / ".github" / "actions" / "semgrep-ci" / "action.yml").read_text(encoding="utf-8")
+ lines = text.splitlines()
+ first = next(i for i, line in enumerate(lines) if line.strip() == "set -f")
+ last = next(i for i in range(first, len(lines)) if lines[i].strip() == "set +f")
+ return textwrap.dedent("\n".join(line.strip() for line in lines[first : last + 1]))
+
+ @staticmethod
+ def _dispatch(script: str, args: str) -> str:
+ done = subprocess.run(
+ ["bash", "-c", script + '\nsh -c \'printf "[%s]" "$@"\' sh "${semgrep_args[@]}"'],
+ env={"SEMGREP_ARGS": args, "PATH": "/usr/bin:/bin"},
+ capture_output=True,
+ text=True,
+ )
+ assert done.returncode == 0, done.stderr
+ return done.stdout
+
+ def test_the_shipped_action_still_passes_arguments_positionally(self) -> None:
+ from hogli.manifest import REPO_ROOT
+
+ text = (REPO_ROOT / ".github" / "actions" / "semgrep-ci" / "action.yml").read_text(encoding="utf-8")
+ assert '"$@"' in text, "the action must hand semgrep positional parameters"
+ assert "$SEMGREP_ARGS" not in text.split("docker run")[1], (
+ "the value must not be spliced into the command the container shell parses"
+ )
+
+ @pytest.mark.parametrize(
+ ("args", "expected"),
+ [
+ ("--config p/python --jobs 4", "[--config][p/python][--jobs][4]"),
+ # the three terminators that used to truncate the scan silently
+ ("--config p/python # note --jobs 4", "[--config][p/python][#][note][--jobs][4]"),
+ ("--config p/python ; --jobs 4", "[--config][p/python][;][--jobs][4]"),
+ ("--config p/python\n--jobs 4", "[--config][p/python][--jobs][4]"),
+ # globs reach semgrep unexpanded; semgrep does its own matching
+ ("--include *.py --exclude tests/**", "[--include][*.py][--exclude][tests/**]"),
+ ("--config p/python\t--jobs 4", "[--config][p/python][--jobs][4]"),
+ ],
+ )
+ def test_the_shipped_split_hands_over_every_argument(self, args: str, expected: str) -> None:
+ assert self._dispatch(self._shipped_split(), args) == expected
+
+ @pytest.mark.parametrize("args", ["", " ", "\n"])
+ def test_an_empty_args_value_passes_no_arguments_at_all(self, args: str) -> None:
+ # An empty string must not become one EMPTY argument: semgrep would read
+ # that as a target path and scan the wrong tree. Count the arguments
+ # rather than rendering them -- `printf "[%s]"` runs its format once even
+ # with nothing to substitute, so a rendering cannot tell 0 from 1 here.
+ script = self._shipped_split() + '\nsh -c \'printf %s "$#"\' sh "${semgrep_args[@]}"'
+ done = subprocess.run(
+ ["bash", "-c", script],
+ env={"SEMGREP_ARGS": args, "PATH": "/usr/bin:/bin"},
+ capture_output=True,
+ text=True,
+ )
+ assert done.stdout == "0", done.stdout
+
+ def test_the_shipped_split_leaves_globbing_enabled_afterwards(self) -> None:
+ # `set -f` suppresses expansion for the split. Leaving it set would change
+ # every later command in the step.
+ script = self._shipped_split() + "\ncase $- in *f*) echo LEAKED ;; *) echo restored ;; esac"
+ done = subprocess.run(
+ ["bash", "-c", script],
+ env={"SEMGREP_ARGS": "--config p/python", "PATH": "/usr/bin:/bin"},
+ capture_output=True,
+ text=True,
+ )
+ assert done.stdout.strip() == "restored", done.stdout
+
+ def test_derivation_follows_an_input_through_an_env_hop(self, tmp_path: Path) -> None:
+ # The shape the real action used: `env:` binds the input, the script reads
+ # the variable. Derivation has to follow that hop, not just direct interpolation.
+ action_dir = tmp_path / ".github" / "actions" / "envhop"
+ action_dir.mkdir(parents=True)
+ (action_dir / "action.yml").write_text(
+ "name: A\ndescription: A\ninputs:\n flags:\n description: d\n required: true\n"
+ "runs:\n using: composite\n steps:\n - shell: bash\n env:\n"
+ " FLAGS: ${{ inputs.flags }}\n"
+ ' run: sh -c "tool $FLAGS"\n',
+ encoding="utf-8",
+ )
+ assert derive_shell_split_inputs(tmp_path).get(".github/actions/envhop") == frozenset({"flags"})
+
+ @staticmethod
+ def _write_action(repo_root: Path, name: str, run: str, *, env: bool = True) -> None:
+ directory = repo_root / ".github" / "actions" / name
+ directory.mkdir(parents=True, exist_ok=True)
+ env_block = " env:\n ARGS: ${{ inputs.flags }}\n" if env else ""
+ (directory / "action.yml").write_text(
+ "name: A\ndescription: A\ninputs:\n flags:\n description: d\n required: true\n"
+ f"runs:\n using: composite\n steps:\n - shell: bash\n{env_block} run: {run}\n",
+ encoding="utf-8",
+ )
+
+ @pytest.mark.parametrize(
+ ("run", "spliced"),
+ [
+ # unquoted: the action, not the caller, decides where the value
+ # splits into flags, and a `*` in it globs against the container
+ ('sh -c "tool $ARGS"', True),
+ ("sh -c 'tool $ARGS'", True),
+ # double-quoted -- ONE argument, nothing re-parses it
+ ("sh -c 'tool \"$ARGS\"'", False),
+ ("sh -c 'tool --flag \"${ARGS}\" --other'", False),
+ # quoted somewhere, unquoted somewhere else: still listed
+ ("sh -c 'tool \"$OTHER\" $ARGS'", True),
+ # A GitHub expression is NOT a shell variable: Actions substitutes it into
+ # the script text before any shell parses, so a quote in the value closes the
+ # quote around it. Quoting cannot protect it -- both forms are hazards.
+ ("sh -c \"tool '${{ inputs.flags }}'\"", True),
+ ('sh -c "tool ${{ inputs.flags }}"', True),
+ ],
+ )
+ def test_derivation_ignores_a_reference_the_inner_shell_cannot_split(
+ self, tmp_path: Path, run: str, spliced: bool
+ ) -> None:
+ self._write_action(tmp_path, "probe", run)
+ derived = derive_shell_split_inputs(tmp_path)
+ assert (".github/actions/probe" in derived) is spliced, derived
+
+ @pytest.mark.parametrize("metadata", ["action.yml", "action.yaml"])
+ def test_an_action_whose_metadata_does_not_parse_is_reported(self, tmp_path: Path, metadata: str) -> None:
+ # An unreadable action returns None exactly as an absent one does, so
+ # without this the derivation finds nothing and the check passes clean --
+ # the check silently doing nothing, which is what it exists to catch.
+ # Both spellings are reported under the name actually on disk, so the
+ # annotation has a real file to attach to.
+ broken = tmp_path / ".github" / "actions" / "broken"
+ broken.mkdir(parents=True)
+ (broken / metadata).write_text("name: A\n bad: [unclosed\n", encoding="utf-8")
+ assert unparseable_actions(tmp_path) == [f".github/actions/broken/{metadata}"]
+ issues = self._run(tmp_path, _caller("--config p/python"))
+ assert any(f"broken/{metadata}: does not parse" in issue for issue in issues), issues
+
+ def test_derivation_reads_an_unquoted_shell_c_operand(self, tmp_path: Path) -> None:
+ # `sh -c $FLAGS` is if anything worse than a quoted operand: the value is
+ # split before the inner shell even sees it. It must not go uninspected.
+ self._write_action(tmp_path, "bare", "sh -c $ARGS")
+ assert derive_shell_split_inputs(tmp_path).get(".github/actions/bare") == frozenset({"flags"})
+
+ @pytest.mark.parametrize(
+ ("run", "spliced"),
+ [
+ # quoting makes the reference one argument, but `eval` parses that
+ # argument a second time, so the value is read as script anyway
+ ("""sh -c 'eval "$ARGS"'""", True),
+ ("""sh -c 'tool "$OTHER" && eval "$ARGS"'""", True),
+ # eval's command ends at the terminator: $ARGS is tool's argument
+ ("""sh -c 'eval "$OTHER"; tool "$ARGS"'""", False),
+ # `eval` as a literal or an argument re-parses nothing
+ ("""sh -c 'echo "eval $ARGS"'""", False),
+ ("""sh -c 'tool --eval "$ARGS"'""", False),
+ # a nested `-c` parses its argument exactly as `eval` does
+ ("""sh -c 'bash -c "$ARGS"'""", True),
+ ("""sh -c 'docker exec c sh -c "$ARGS"'""", True),
+ ("""sh -c 'sh -c "$OTHER"; tool "$ARGS"'""", False),
+ ],
+ )
+ def test_derivation_reads_a_quoted_reference_handed_to_a_second_parse(
+ self, tmp_path: Path, run: str, spliced: bool
+ ) -> None:
+ # The quoted-reference skip cleared these as safe, which is worse than
+ # missing them: the check affirmatively said a hazardous script had none.
+ self._write_action(tmp_path, "evaluator", run)
+ assert (".github/actions/evaluator" in derive_shell_split_inputs(tmp_path)) is spliced, run
+
+ @pytest.mark.parametrize(
+ ("run", "spliced"),
+ [
+ # a shell joins adjacent segments into ONE word, and the outer shell
+ # expands the double-quoted and bare ones while doing so
+ ("sh -c 'tool '\"$ARGS\"", True),
+ ('sh -c "tool "$ARGS', True),
+ # both segments single-quoted: the text reaches the inner shell
+ # untouched, so its own quotes still protect the variable
+ ("sh -c 'tool \"$ARGS\"'' --flag'", False),
+ ],
+ )
+ def test_derivation_reads_a_concatenated_shell_c_operand(self, tmp_path: Path, run: str, spliced: bool) -> None:
+ # Reading only the first segment left the rest of the operand uninspected.
+ self._write_action(tmp_path, "joined", run)
+ assert (".github/actions/joined" in derive_shell_split_inputs(tmp_path)) is spliced, run
+
+ @pytest.mark.parametrize(
+ "invocation",
+ [
+ "bash -lc",
+ "sh -lc",
+ "bash -euxc",
+ "sh -c",
+ "bash --norc -c",
+ # options whose value is a separate token: the value is not a flag, so
+ # a repetition that accepted only flags stopped there
+ "bash -O extglob -c",
+ "bash -o pipefail -c",
+ "bash +o history -c",
+ "bash --rcfile /dev/null -c",
+ ],
+ )
+ def test_derivation_reads_shell_options_before_c(self, tmp_path: Path, invocation: str) -> None:
+ # `bash -lc "..."` is the same hazard as `bash -l -c "..."`; requiring a
+ # separate -c left those actions uninspected.
+ self._write_action(tmp_path, "bundled", f'{invocation} "tool $ARGS"')
+ assert derive_shell_split_inputs(tmp_path).get(".github/actions/bundled") == frozenset({"flags"}), invocation
+
+ @pytest.mark.parametrize("content", ["", "- a list\n", "just a scalar\n"])
+ def test_action_metadata_that_parses_but_is_unusable_is_reported(self, tmp_path: Path, content: str) -> None:
+ # Parsing is not the bar. These parse fine and are then discarded exactly
+ # as an absent action is, so without this they read as safe.
+ directory = tmp_path / ".github" / "actions" / "odd"
+ directory.mkdir(parents=True)
+ (directory / "action.yml").write_text(content, encoding="utf-8")
+ assert unparseable_actions(tmp_path) == [".github/actions/odd/action.yml"], content
+
+ @pytest.mark.parametrize(
+ ("run", "spliced"),
+ [
+ # single-quoted OPERAND: the outer shell passes the text through, the
+ # inner shell expands "$ARGS" itself -> genuinely one argument
+ ("sh -c 'tool \"$ARGS\"'", False),
+ # double-quoted or bare OPERAND: the OUTER shell expands $ARGS into the
+ # script text first, so inner quoting cannot protect it
+ ("sh -c \"tool '$ARGS'\"", True),
+ ('sh -c "tool \\"$ARGS\\""', True),
+ ('sh -c "$ARGS"', True),
+ ],
+ )
+ def test_inner_quotes_only_protect_inside_a_single_quoted_operand(
+ self, tmp_path: Path, run: str, spliced: bool
+ ) -> None:
+ self._write_action(tmp_path, "operand", run)
+ assert (".github/actions/operand" in derive_shell_split_inputs(tmp_path)) is spliced, run
+
+ @pytest.mark.parametrize(
+ "expression",
+ [
+ "${{ inputs.flags }}",
+ "${{ inputs.flags || '' }}",
+ "${{ format('{0}', inputs.flags) }}",
+ "${{ inputs['flags'] }}",
+ ],
+ )
+ def test_derivation_reads_a_transformed_input_expression(self, tmp_path: Path, expression: str) -> None:
+ # These interpolate exactly the same text as a bare reference; matching
+ # only the bare form left the transformed ones unchecked.
+ self._write_action(tmp_path, "expr", f'sh -c "tool {expression}"', env=False)
+ assert derive_shell_split_inputs(tmp_path).get(".github/actions/expr") == frozenset({"flags"}), expression
+
+ def test_undecodable_action_metadata_is_reported_not_raised(self, tmp_path: Path) -> None:
+ # read_text raises UnicodeDecodeError, which is a ValueError and not an
+ # OSError -- so this used to take the whole lint down rather than report.
+ directory = tmp_path / ".github" / "actions" / "binary"
+ directory.mkdir(parents=True)
+ (directory / "action.yml").write_bytes(b"name: A\ndescription: \xff\xfe\n")
+ assert unparseable_actions(tmp_path) == [".github/actions/binary/action.yml"]
+
+ def test_a_nested_action_with_unreadable_metadata_is_reported(self, tmp_path: Path) -> None:
+ # The derivation scans `.github/actions/**` recursively; this alarm has to
+ # reach as far, or a nested action it would have scanned goes unmentioned.
+ nested = tmp_path / ".github" / "actions" / "group" / "inner"
+ nested.mkdir(parents=True)
+ (nested / "action.yml").write_text("name: A\n bad: [unclosed\n", encoding="utf-8")
+ assert unparseable_actions(tmp_path) == [".github/actions/group/inner/action.yml"]
+
+ def test_a_parseable_action_is_not_reported_as_unparseable(self, tmp_path: Path) -> None:
+ self._write_action(tmp_path, "fine", """sh -c 'tool "$ARGS"'""")
+ assert unparseable_actions(tmp_path) == []
+
+ def test_reverse_drift_stays_quiet_while_the_action_still_splices(self, tmp_path: Path) -> None:
+ _write_table_actions(tmp_path)
+ issues = self._run(tmp_path, _caller("--config p/python"))
+ assert not any("no longer splices" in issue or "nothing there splices" in issue for issue in issues), issues
+
+ def test_flags_a_table_entry_the_tree_no_longer_splices(self, tmp_path: Path) -> None:
+ # Reverse drift. Without this, a table entry outlives the hazard and keeps
+ # callers being checked against something that is gone.
+ action_dir = tmp_path / ".github" / "actions" / "semgrep-ci"
+ action_dir.mkdir(parents=True)
+ (action_dir / "action.yml").write_text(
+ "name: A\ndescription: A\ninputs:\n args:\n description: d\n required: true\n"
+ "runs:\n using: composite\n steps:\n - shell: bash\n"
+ " run: sh -c 'tool \"$@\"' sh $ARGS\n",
+ encoding="utf-8",
+ )
+ issues = self._run(tmp_path, _caller("--config p/python"))
+ assert any("no longer splices" in issue or "nothing there splices" in issue for issue in issues), issues
+
+ def test_a_foreign_action_sharing_our_layout_is_not_matched(self, tmp_path: Path) -> None:
+ # `OtherOrg/repo/.github/actions/semgrep-ci` is a different action. Matching it
+ # would fail a workflow over semantics that action does not have.
+ _write_table_actions(tmp_path)
+ assert (
+ self._run(
+ tmp_path,
+ _caller("--config p/python # off", uses="OtherOrg/repo/.github/actions/semgrep-ci@abc123"),
+ )
+ == []
+ )
+
+ def test_allows_a_value_with_no_hash(self, tmp_path: Path) -> None:
+ _write_table_actions(tmp_path)
+ assert self._run(tmp_path, _caller("--config p/python\n --include /posthog")) == []
+
+ def test_ignores_an_input_the_table_does_not_list(self, tmp_path: Path) -> None:
+ _write_table_actions(tmp_path)
+ workflows_dir = tmp_path / ".github" / "workflows"
+ workflows_dir.mkdir(parents=True)
+ _write(
+ workflows_dir,
+ "ci-security.yaml",
+ """
+ name: Security
+ on: [pull_request]
+ jobs:
+ semgrep:
+ runs-on: ubuntu-24.04
+ timeout-minutes: 5
+ steps:
+ - uses: ./.github/actions/semgrep-ci
+ with:
+ image: semgrep/semgrep@sha256:abc # pinned
+ args: --config p/python
+ """,
+ )
+ check = ShellSplitActionArgsCheck(repo_root=tmp_path)
+ assert check.run(_read_all(workflows_dir)).issues == []
+
+ def test_ignores_an_action_the_table_does_not_list(self, tmp_path: Path) -> None:
+ # 38 `with:` inputs in this repo carry a `#` legitimately, so the rule
+ # has to stay per-input rather than blanket.
+ _write_table_actions(tmp_path)
+ workflows_dir = tmp_path / ".github" / "workflows"
+ workflows_dir.mkdir(parents=True)
+ _write(
+ workflows_dir,
+ "ci-other.yml",
+ """
+ name: Other
+ on: [pull_request]
+ jobs:
+ changes:
+ runs-on: ubuntu-24.04
+ timeout-minutes: 5
+ steps:
+ - uses: dorny/paths-filter@v3
+ with:
+ filters: |
+ # the backend tree, minus docs
+ backend:
+ - 'posthog/**'
+ - uses: actions/github-script@v7
+ with:
+ script: |
+ // #1 in the queue
+ core.info('ok')
+ """,
+ )
+ check = ShellSplitActionArgsCheck(repo_root=tmp_path)
+ assert check.run(_read_all(workflows_dir)).issues == []
+
+ def test_matches_a_repo_qualified_uses(self, tmp_path: Path) -> None:
+ _write_table_actions(tmp_path)
+ issues = self._run(
+ tmp_path,
+ _caller("--config p/python # off", uses="PostHog/posthog/.github/actions/semgrep-ci@abc123"),
+ )
+ assert len(issues) == 1, issues
+
+ def test_reports_an_action_missing_from_the_table(self, tmp_path: Path) -> None:
+ _write_table_actions(tmp_path)
+ made_up = tmp_path / ".github" / "actions" / "made-up"
+ made_up.mkdir(parents=True)
+ (made_up / "action.yml").write_text(
+ "name: M\ndescription: M\ninputs:\n flags:\n description: d\n required: true\n"
+ "runs:\n using: composite\n steps:\n - shell: bash\n env:\n"
+ ' FLAGS: ${{ inputs.flags }}\n run: sh -c "tool $FLAGS"\n'
+ )
+ [issue] = self._run(tmp_path, _caller("--config p/python"))
+ assert ".github/actions/made-up" in issue, issue
+ assert "missing from SHELL_SPLIT_INPUTS" in issue, issue
+
+ def test_reports_a_table_entry_whose_action_was_renamed_away(self, tmp_path: Path) -> None:
+ issues = self._run(tmp_path, _caller("--config p/python"))
+ assert len(issues) == len(_ssaa.SHELL_SPLIT_INPUTS), issues
+ assert all("no action there" in issue for issue in issues), issues
+
+ def test_reports_a_table_input_the_action_no_longer_declares(self, tmp_path: Path) -> None:
+ _write_table_actions(tmp_path, declared=False)
+ issues = self._run(tmp_path, _caller("--config p/python"))
+ assert any("no longer declares" in issue for issue in issues), issues
+
+ def test_derivation_reads_only_the_shell_c_operand(self, tmp_path: Path) -> None:
+ # Harvesting the whole run body would derive `image` too and fire a
+ # drift alarm on a correctly written action.
+ action = tmp_path / ".github" / "actions" / "runner"
+ action.mkdir(parents=True)
+ (action / "action.yml").write_text(
+ "name: R\ndescription: R\ninputs:\n args:\n description: d\n image:\n description: d\n"
+ "runs:\n using: composite\n steps:\n - shell: bash\n env:\n"
+ " A: ${{ inputs.args }}\n I: ${{ inputs.image }}\n"
+ ' run: |\n docker run "$I" sh -c "tool $A"\n'
+ )
+ assert derive_shell_split_inputs(tmp_path) == {".github/actions/runner": frozenset({"args"})}
+
+ def test_live_tree_is_clean(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ # The real table, not the class fixture's hazardous stand-in.
+ monkeypatch.setattr(_ssaa, "SHELL_SPLIT_INPUTS", SHELL_SPLIT_INPUTS)
+ from hogli.manifest import REPO_ROOT
+
+ workflows_dir = REPO_ROOT / ".github" / "workflows"
+ if not workflows_dir.exists():
+ pytest.skip("no .github/workflows directory in this checkout")
+ check = ShellSplitActionArgsCheck(repo_root=REPO_ROOT)
+ issues = check.run(list(read_workflows(workflows_dir))).issues
+ assert issues == [], [issue.render() for issue in issues]
+ assert derive_shell_split_inputs(REPO_ROOT) == SHELL_SPLIT_INPUTS
diff --git a/tools/hogli-commands/hogli_commands/workflow_lint/checks/__init__.py b/tools/hogli-commands/hogli_commands/workflow_lint/checks/__init__.py
index 958ca7c1dfac..4614b7063161 100644
--- a/tools/hogli-commands/hogli_commands/workflow_lint/checks/__init__.py
+++ b/tools/hogli-commands/hogli_commands/workflow_lint/checks/__init__.py
@@ -23,6 +23,7 @@ from .pr_event_fanout import PrEventFanoutCheck
from .required_gates import RequiredGateCheck
from .reusable_secret_passthrough import ReusableSecretPassthroughCheck
from .semgrep_services_coverage import SemgrepServicesCoverageCheck
+from .shell_split_action_args import ShellSplitActionArgsCheck
CHECKS: list[WorkflowCheck] = [
JobTimeoutsCheck(),
@@ -36,6 +37,7 @@ CHECKS: list[WorkflowCheck] = [
McpFilterCoverageCheck(),
ReusableSecretPassthroughCheck(),
PinnedRunnerImagesCheck(),
+ ShellSplitActionArgsCheck(),
]
diff --git a/tools/hogli-commands/hogli_commands/workflow_lint/checks/shell_split_action_args.py b/tools/hogli-commands/hogli_commands/workflow_lint/checks/shell_split_action_args.py
new file mode 100644
index 000000000000..8a3bd201c147
--- /dev/null
+++ b/tools/hogli-commands/hogli_commands/workflow_lint/checks/shell_split_action_args.py
@@ -0,0 +1,499 @@
+"""An action input that reaches an inner shell must not contain ``#``.
+
+``.github/actions/semgrep-ci`` builds its command as
+``sh -c "git config ... && exec semgrep ci ... $SEMGREP_ARGS"``. The outer bash
+expands ``$SEMGREP_ARGS`` inside those double quotes, so the container's ``sh``
+receives one long string and re-parses it as a script. That re-parse is what
+performs the whitespace split into flags the input documents — and the same
+tokenizer treats ``#`` as the start of a comment.
+
+A caller writes the input as a YAML folded scalar (``args: >-``), which keeps
+``#`` as data and collapses the block onto one line. A ``#`` note written inside
+that block therefore comments out every flag after it. Semgrep loads fewer
+configs, finds fewer things, and the job still exits 0 — the failure has no
+symptom. Measured on a real PR: three jobs silently dropped configs and the
+pre-existing ``--exclude-rule`` and ``--include`` scopes went with them.
+
+Quoting is not the fix. ``$SEMGREP_ARGS`` already sits inside double quotes;
+quoting it again would collapse every flag into a single argument.
+
+The table also lists the milder form, ``sh -c 'tool $ARGS'``. There the INNER
+shell expands the value, so a ``#`` in it stays a literal word rather than a
+comment — but the split into flags is still the action's to decide, and the
+same expansion globs, so ``--include *.py`` reaches the tool as whatever
+happened to match in the container. Either way the caller's value does not
+arrive as the caller wrote it, which is what the character set below rejects.
+
+``SHELL_SPLIT_INPUTS`` is the source of truth for which (action, input) pairs
+carry this hazard, and it is what the check enforces.
+"""
+
+from __future__ import annotations
+
+import re
+from collections.abc import Iterator
+from pathlib import Path
+from typing import NamedTuple
+
+import yaml
+from hogli.manifest import REPO_ROOT
+
+from ..check import CheckResult, Issue, WorkflowCheck
+from ..model import Workflow
+
+# Source of truth. Enforcement reads only this table; see `_drift_issues`.
+REPO_PREFIX = "PostHog/posthog/"
+
+# Actions that splice a caller's input into a command string an inner shell
+# re-parses. EMPTY IS THE HEALTHY STATE: semgrep-ci used to be here, and the fix
+# was to stop splicing (it splits the value and passes `"$@"`), not to police the
+# value. An entry here means an action still has the hazard and its callers need
+# checking until it does the same. `derive_shell_split_inputs` alarms in both
+# directions, so neither adding nor removing an entry can go unnoticed.
+SHELL_SPLIT_INPUTS: dict[str, frozenset[str]] = {}
+
+ACTIONS_DIR = ".github/actions"
+
+# Scoped to the `-c` operand: a var elsewhere in the run body (`"$SEMGREP_IMAGE"`)
+# is its own quoted argument, never re-parsed, so it carries no hazard.
+UNSAFE_ARG_RE = re.compile(r"[^ A-Za-z0-9._/@:=+-]")
+# One option token before `-c`, with its value when it takes a separate one.
+# `-o pipefail`, `-O extglob`, their `+` forms and `--rcfile <file>` all put the
+# value in its own token, so a repetition that accepted only flags stopped at
+# that value and left the whole invocation uninspected.
+SHELL_OPTION = r"(?:(?:[-+][oO]|--(?:rcfile|init-file))\s+\S+|[-+]\S+)\s+"
+# The three segment forms. A shell joins ADJACENT segments into one word, so
+# `'tool '"$ARGS"` is a single operand in two segments, each quoted its own way.
+DQUOTED = r"\"(?:[^\"\\]|\\.)*\""
+SQUOTED = r"'[^']*'"
+UNQUOTED = r"[^\s\"']+"
+OPERAND_SEGMENT_RE = re.compile(rf"(?P<dquoted>{DQUOTED})|(?P<squoted>{SQUOTED})|(?P<bare>{UNQUOTED})")
+SHELL_C_RE = re.compile(
+ # The whole operand word. Quoting a segment does not make the value in it
+ # safe, and leaving it bare (`sh -c $FLAGS`) is if anything worse -- the
+ # operand is then split before the inner shell even sees it.
+ rf"\b(?:sh|bash|dash|zsh|ksh)\b\s+(?:{SHELL_OPTION})*-[a-zA-Z]*c\s+"
+ rf"(?P<operand>(?:{DQUOTED}|{SQUOTED}|{UNQUOTED})+)",
+)
+VAR_REF_RE = re.compile(r"\$(?:\{(?P<braced>[A-Za-z_]\w*)[^}]*\}|(?P<plain>[A-Za-z_]\w*))")
+EVAL_RE = re.compile(r"\beval\b")
+# A nested `-c` parses its argument exactly as `eval` does -- verified against
+# `sh`: with ARGS='one ; echo two', `sh -c 'bash -c "$ARGS"'` runs the echo.
+# Unlike `eval` this is not required to be the command word, because it usually
+# is not one: `docker exec c sh -c`, `timeout 30 sh -c`. That is the same shape
+# as the `docker run ... sh -c` the outer matcher exists to find.
+NESTED_SHELL_C_RE = re.compile(r"(?<!-)\b(?:sh|bash|dash|zsh|ksh)\b\s+(?:" + SHELL_OPTION + r")*-[a-zA-Z]*c\b")
+# What `eval` is the head of ends here, so the next command's arguments are not
+# read as eval's.
+COMMAND_END_RE = re.compile(r"[;&|\n()]")
+# `eval` counts only as a command word. After anything else it is an argument or
+# a literal (`tool --eval`), and re-parses nothing.
+COMMAND_HEAD_RE = re.compile(r"(?:[;&|\n(){]|\b(?:then|else|do))[ \t]*$")
+# Any `${{ ... }}` block, then the input names inside it. Matching only a bare
+# `${{ inputs.x }}` missed every transformed form -- `${{ inputs.x || '' }}`,
+# `${{ format('{0}', inputs.x) }}` -- which interpolate exactly the same text.
+EXPR_BLOCK_RE = re.compile(r"\$\{\{(?P<body>.*?)\}\}", re.DOTALL)
+INPUT_REF_RE = re.compile(r"\binputs(?:\.(?P<dot>[\w-]+)|\[\s*['\"](?P<bracket>[\w-]+)['\"]\s*\])")
+
+
+def _expression_inputs(text: str) -> Iterator[str]:
+ """Every input named inside a `${{ ... }}` block in `text`."""
+ for block in EXPR_BLOCK_RE.finditer(text):
+ for ref in INPUT_REF_RE.finditer(block.group("body")):
+ yield _input_name(ref)
+
+
+def _input_name(match: re.Match[str]) -> str:
+ return match.group("dot") or match.group("bracket")
+
+
+def _action_key(uses: str | None) -> str | None:
+ """Normalize a step's ``uses:`` to a repo-relative action path, or None.
+
+ Covers the local form (``./.github/actions/semgrep-ci``) and the
+ repo-qualified one (``PostHog/posthog/.github/actions/semgrep-ci@sha``).
+ """
+ if not uses:
+ return None
+ path = uses.split("@", 1)[0].strip()
+ # Anchored, never a substring search: `OtherOrg/repo/.github/actions/semgrep-ci`
+ # is a different action that happens to share our layout, and matching it would
+ # fail a workflow over semantics that action does not have.
+ if path.startswith("./"):
+ path = path[2:]
+ elif path.startswith(REPO_PREFIX):
+ path = path[len(REPO_PREFIX) :]
+ if not path.startswith(ACTIONS_DIR):
+ return None
+ return path.rstrip("/")
+
+
+def _load_action(action_dir: Path) -> dict[str, object] | None:
+ """Parse ``<action_dir>/action.y[a]ml``. Returns None when there is no action there."""
+ for name in ("action.yml", "action.yaml"):
+ path = action_dir / name
+ if not path.is_file():
+ continue
+ try:
+ data = yaml.safe_load(path.read_text(encoding="utf-8"))
+ except (yaml.YAMLError, OSError, UnicodeDecodeError):
+ return None
+ return data if isinstance(data, dict) else None
+ return None
+
+
+def unparseable_actions(repo_root: Path) -> list[str]:
+ """Repo-relative paths of action metadata files that exist but do not parse.
+
+ The path, not the directory that holds it: an action may be spelled
+ ``action.yml`` or ``action.yaml``, and only the real one can be named in the
+ message or annotated by GitHub.
+
+ These must be REPORTED, never skipped. `_load_action` returns None for an
+ unreadable action exactly as it does for an absent one, so without this a
+ malformed `action.yml` makes `derive_shell_split_inputs` find nothing and the
+ whole check passes clean -- the check silently doing nothing, which is the
+ failure mode it exists to catch.
+ """
+ broken: list[str] = []
+ actions_root = repo_root / ACTIONS_DIR
+ if not actions_root.is_dir():
+ return broken
+ # rglob, matching `derive_shell_split_inputs`: a nested action it would scan
+ # must not be invisible to the alarm that says the scan could not read one.
+ for path in sorted(actions_root.rglob("action.y*ml")):
+ try:
+ data = yaml.safe_load(path.read_text(encoding="utf-8"))
+ except (yaml.YAMLError, OSError, UnicodeDecodeError):
+ broken.append(path.relative_to(repo_root).as_posix())
+ continue
+ # Parsing is not the bar; being usable is. An empty file, a list or a
+ # scalar parses fine and `_load_action` discards it exactly as it
+ # discards an absent action, so it would read here as an action with no
+ # hazard rather than one nothing could inspect.
+ if not isinstance(data, dict):
+ broken.append(path.relative_to(repo_root).as_posix())
+ return broken
+
+
+def _declared_inputs(action_dir: Path) -> frozenset[str] | None:
+ """Input names an action declares, or None when the action is not there."""
+ data = _load_action(action_dir)
+ if data is None:
+ return None
+ inputs = data.get("inputs")
+ return frozenset(str(name) for name in inputs) if isinstance(inputs, dict) else frozenset()
+
+
+def _composite_steps(data: dict[str, object]) -> Iterator[dict[str, object]]:
+ runs = data.get("runs")
+ if not isinstance(runs, dict):
+ return
+ steps = runs.get("steps")
+ if not isinstance(steps, list):
+ return
+ for step in steps:
+ if isinstance(step, dict):
+ yield step
+
+
+class _Span(NamedTuple):
+ """A half-open index range. Named because `start` and `end` share a type and a
+ bare `tuple[int, int]` lets a call site swap them silently."""
+
+ start: int
+ end: int
+
+
+def _quoted_spans(script: str) -> list[_Span]:
+ """Index ranges the inner shell would treat as quoted.
+
+ A quoted reference is ONE argument: the shell expands it without splitting
+ it, so a `#` inside cannot start a comment and nothing after it is dropped.
+ Both quotings count -- `"$ARGS"` and `'${{ inputs.flags }}'` are each safe --
+ and a quote of one kind makes the other literal until it closes, which is why
+ this tracks them together rather than one pass each.
+ """
+ spans: list[_Span] = []
+ index = 0
+ length = len(script)
+ while index < length:
+ char = script[index]
+ if char == "\\":
+ index += 2
+ continue
+ if char in "\"'":
+ quote = char
+ start = index + 1
+ cursor = start
+ while cursor < length:
+ # a backslash escapes only inside double quotes, never inside single
+ if quote == '"' and script[cursor] == "\\":
+ cursor += 2
+ continue
+ if script[cursor] == quote:
+ break
+ cursor += 1
+ spans.append(_Span(start, min(cursor, length)))
+ index = cursor + 1
+ continue
+ index += 1
+ return spans
+
+
+def _operand_segments(operand: str) -> Iterator[tuple[str, bool]]:
+ """Each segment of the `-c` operand word, with whether the OUTER shell expands it.
+
+ A single-quoted segment reaches the inner shell verbatim, so the inner shell
+ is what expands anything in it. Every other segment is expanded by the outer
+ shell first, before the inner shell sees the text at all.
+ """
+ for segment in OPERAND_SEGMENT_RE.finditer(operand):
+ if (squoted := segment.group("squoted")) is not None:
+ yield squoted[1:-1], False
+ elif (dquoted := segment.group("dquoted")) is not None:
+ yield dquoted[1:-1], True
+ else:
+ yield segment.group("bare"), True
+
+
+def _in_any(spans: list[_Span], index: int) -> bool:
+ return any(span.start <= index < span.end for span in spans)
+
+
+def _reparsed_argument_spans(script: str, quoted: list[_Span]) -> list[_Span]:
+ """Index ranges a second parse reads, after the shell expands them.
+
+ A quoted reference is one argument, which is why `_spliced_inputs` skips it.
+ `eval` and a nested `-c` are the exception the skip cannot survive: both take
+ the expanded text and parse it as a command, so a `#`, `;` or newline in the
+ value still truncates or splits what runs. `ssh host "$X"` has the same
+ shape and is not matched -- it hands the value to a shell somewhere else.
+
+ `eval` counts only as a command word, because `--eval` and a bare mention of
+ it are ordinary text.
+ """
+ heads = [(match, True) for match in EVAL_RE.finditer(script)]
+ heads += [(match, False) for match in NESTED_SHELL_C_RE.finditer(script)]
+ spans: list[_Span] = []
+ for match, command_word_only in sorted(heads, key=lambda head: head[0].start()):
+ before = script[: match.start()]
+ if _in_any(quoted, match.start()):
+ continue
+ if command_word_only and before.strip() and not COMMAND_HEAD_RE.search(before):
+ continue
+ end = len(script)
+ for terminator in COMMAND_END_RE.finditer(script, match.end()):
+ if not _in_any(quoted, terminator.start()):
+ end = terminator.start()
+ break
+ spans.append(_Span(match.end(), end))
+ return spans
+
+
+def _spliced_inputs(step: dict[str, object]) -> Iterator[str]:
+ """Input names this composite step splices into an inner shell command string."""
+ run = step.get("run")
+ if not isinstance(run, str):
+ return
+ env = step.get("env")
+ by_var: dict[str, str] = {}
+ if isinstance(env, dict):
+ for var, value in env.items():
+ if not isinstance(value, str):
+ continue
+ for name in _expression_inputs(value):
+ by_var[str(var)] = name
+ for shell_c in SHELL_C_RE.finditer(run):
+ for script, outer_expanded in _operand_segments(shell_c.group("operand")):
+ # Inner quotes protect a variable ONLY inside a single-quoted segment.
+ # There the outer shell passes the text through untouched and the inner
+ # shell expands `"$ARGS"` itself, giving one argument. In a
+ # double-quoted or bare segment the OUTER shell expands the variable into
+ # the script text first, so a quote in the value closes the quote around
+ # it -- the same pre-substitution problem GitHub expressions have.
+ # `eval` and a nested `-c` are where "one argument" stops being
+ # enough; see `_reparsed_argument_spans`.
+ quoted = [] if outer_expanded else _quoted_spans(script)
+ reparsed = _reparsed_argument_spans(script, quoted)
+ for ref in VAR_REF_RE.finditer(script):
+ if _in_any(quoted, ref.start()) and not _in_any(reparsed, ref.start()):
+ continue
+ name = by_var.get(ref.group("braced") or ref.group("plain") or "")
+ if name is not None:
+ yield name
+ # an input interpolated straight into the script, with no env hop
+ # NO quote check here, unlike the variable references above, and the
+ # difference is the whole point. A shell variable is expanded AFTER the
+ # shell parses quotes, so `"$ARGS"` is one argument whatever it holds.
+ # A GitHub expression is substituted into the script text BEFORE any
+ # shell runs, so a quote inside the value closes the quote around it and
+ # the rest is re-parsed as script. Quoting cannot protect it; only
+ # passing it through `env:` and referencing the variable can.
+ yield from _expression_inputs(script)
+
+
+def derive_shell_split_inputs(repo_root: Path) -> dict[str, frozenset[str]]:
+ """Re-derive the ``SHELL_SPLIT_INPUTS`` shape from ``.github/actions/**``.
+
+ Deliberately NOT authoritative — it only feeds the drift alarm below.
+ This pattern matching is the fragile half: rewrite the semgrep step to
+ build its command some other way and the regex matches nothing, the
+ derivation returns an empty mapping, and every caller passes. That is the
+ exact silent-failure mode this check exists to stop, so it must never be
+ the thing that decides whether a caller is checked. The table decides;
+ this only says the table looks out of date.
+ """
+ actions_dir = repo_root / ACTIONS_DIR
+ if not actions_dir.is_dir():
+ return {}
+ derived: dict[str, frozenset[str]] = {}
+ for path in sorted(actions_dir.rglob("action.y*ml")):
+ data = _load_action(path.parent)
+ if data is None:
+ continue
+ names = {name for step in _composite_steps(data) for name in _spliced_inputs(step)}
+ if names:
+ derived[f"{ACTIONS_DIR}/{path.parent.relative_to(actions_dir).as_posix()}"] = frozenset(names)
+ return derived
+
+
+class ShellSplitActionArgsCheck(WorkflowCheck):
+ id = "WF012-shell-split-action-args"
+ label = "shell-split action args"
+ description = "action inputs re-parsed by an inner shell carry no '#', which would comment out the rest"
+
+ def __init__(self, repo_root: Path | None = None) -> None:
+ # Injected so tests can point at a fixture tree without monkeypatching env vars.
+ self._repo_root = repo_root or REPO_ROOT
+
+ @property
+ def fix_hint(self) -> str | None:
+ return (
+ "Delete the '#' or move the note to a YAML comment ABOVE the input key, outside the block scalar — "
+ "YAML strips a comment there, while inside a block scalar '#' is data that reaches the shell. "
+ "Do not add quotes: the value is already spliced inside double quotes, so quoting it again would "
+ "collapse every flag into one argument. If a drift line fired instead, update SHELL_SPLIT_INPUTS in "
+ "workflow_lint/checks/shell_split_action_args.py."
+ )
+
+ def run(self, workflows: list[Workflow]) -> CheckResult:
+ result = CheckResult()
+ for wf in workflows:
+ for job in wf.jobs:
+ for step in job.steps:
+ action = _action_key(step.uses)
+ if action is None:
+ continue
+ for name in sorted(SHELL_SPLIT_INPUTS.get(action, frozenset())):
+ value = (step.with_ or {}).get(name)
+ if not isinstance(value, str):
+ continue
+ offenders = sorted(set(UNSAFE_ARG_RE.findall(value)))
+ if not offenders:
+ continue
+ result.issues.append(
+ Issue(
+ workflow=wf.path.name,
+ job=job.name,
+ step=step.ref,
+ message=(
+ f"with.{name} passed to {action} contains {offenders!r}; the action hands "
+ "this value to a shell rather than passing it as arguments, so a '#', newline "
+ "or ';' can silently drop every flag after it and a '*' can expand against the "
+ "container's filesystem"
+ ),
+ file=str(wf.path),
+ )
+ )
+ result.issues.extend(self._drift_issues())
+ return result
+
+ def _drift_issues(self) -> list[Issue]:
+ """Report the table drifting from ``.github/actions/**``. Never gates a caller.
+
+ The two halves rot differently, and only one of them can go quiet:
+
+ - "renamed away" reads the action file, so it keeps firing however the
+ command is written. Rename or delete the action and it says so.
+ - "missing from the table" depends on ``SHELL_SPLIT_INPUTS`` matching
+ what the derivation regex finds, so a rewritten command makes it
+ silent. That asymmetry is why the table, not the derivation, is what
+ ``run`` enforces.
+
+ Lives in the check rather than only in a test because
+ ``ci-lint-workflows.yml`` triggers on ``.github/actions/**`` while the
+ ``hogli`` path filter that runs this test suite does not — an action
+ edited on its own would otherwise reach master unexamined.
+ """
+ issues: list[Issue] = []
+ for action, names in sorted(SHELL_SPLIT_INPUTS.items()):
+ declared = _declared_inputs(self._repo_root / action)
+ if declared is None:
+ issues.append(
+ Issue(
+ workflow=action,
+ message=(
+ "listed in SHELL_SPLIT_INPUTS but there is no action there; the action was renamed or "
+ "deleted, so callers of its replacement are unchecked — update the table"
+ ),
+ file=str(self._repo_root / action),
+ )
+ )
+ continue
+ for name in sorted(names - declared):
+ issues.append(
+ Issue(
+ workflow=action,
+ message=(
+ f"SHELL_SPLIT_INPUTS lists input '{name}', which the action no longer declares — "
+ "update the table to the input that now carries the value"
+ ),
+ file=str(self._repo_root / action),
+ )
+ )
+ for metadata in unparseable_actions(self._repo_root):
+ issues.append(
+ Issue(
+ workflow=metadata,
+ message=(
+ "does not parse, so this check cannot tell whether the action splices an "
+ "input into an inner shell — fix the file; an unreadable action reads exactly like a "
+ "safe one here"
+ ),
+ file=str(self._repo_root / metadata),
+ )
+ )
+ derived = derive_shell_split_inputs(self._repo_root)
+ for action in sorted(set(SHELL_SPLIT_INPUTS) - set(derived)):
+ # A missing action is already reported above, and more precisely;
+ # this alarm is for one that still exists and has stopped splicing.
+ if _load_action(self._repo_root / action) is None:
+ continue
+ issues.append(
+ Issue(
+ workflow=action,
+ message=(
+ f"SHELL_SPLIT_INPUTS lists {action}, but nothing there splices an input into an inner "
+ "shell any more — drop the entry, or callers keep being checked against a hazard that "
+ "is gone"
+ ),
+ file=str(self._repo_root / action),
+ )
+ )
+ for action, names in sorted(derived.items()):
+ for name in sorted(names - SHELL_SPLIT_INPUTS.get(action, frozenset())):
+ issues.append(
+ Issue(
+ workflow=action,
+ message=(
+ f"input '{name}' is spliced into an inner shell command string but is missing from "
+ "SHELL_SPLIT_INPUTS, so callers passing it are unchecked — add it to the table"
+ ),
+ file=str(self._repo_root / action),
+ )
+ )
+ return issues
+
+
+__all__ = ["SHELL_SPLIT_INPUTS", "ShellSplitActionArgsCheck", "derive_shell_split_inputs", "unparseable_actions"]