From 427cb724bbec88c24094e8eabbe2f205552e8291 Mon Sep 17 00:00:00 2001 From: Chris Green Date: Mon, 16 Nov 2026 21:51:40 -0600 Subject: [PATCH 1/2] fix: harden reusable action trust boundaries --- README.md | 2 + action.yaml | 89 +++++++++++----- tests/test_detect_relevant_changes.py | 145 ++++++++++++++++++++++++++ 3 files changed, 209 insertions(+), 27 deletions(-) create mode 100644 tests/test_detect_relevant_changes.py diff --git a/README.md b/README.md index b5ce05f..5c16d2a 100644 --- a/README.md +++ b/README.md @@ -29,6 +29,8 @@ | `matched` | true if matching files were found | | `matched_files` | Newline-delimited list of matching files | +Changed paths containing carriage returns or line feeds conservatively set `matched` to `true` and leave `matched_files` empty because those paths cannot be represented unambiguously by this newline-delimited output. + ## License [Apache 2.0](LICENSE) diff --git a/action.yaml b/action.yaml index 99cec3f..b152191 100644 --- a/action.yaml +++ b/action.yaml @@ -56,6 +56,8 @@ runs: set -euo pipefail shopt -s extglob globstar nullglob + tmp_dir=$(mktemp -d "$RUNNER_TEMP/detect-relevant-changes.XXXXXX") + trap 'rm -rf "$tmp_dir"' EXIT declare -A DEFAULT_TYPE_PATTERNS DEFAULT_TYPE_PATTERNS[cpp]=$'*.cpp\n*.hpp' @@ -82,14 +84,19 @@ runs: while IFS= read -r add; do [ -z "$add" ] && continue if [[ "$add" != *:* ]]; then - echo "::warning::Ignoring invalid type definition '$add'" + echo "::warning::Ignoring invalid type definition without a colon." continue fi type_name=${add%%:*} pattern=${add#*:} pattern=${pattern#./} + if [[ ! "$type_name" =~ ^[a-zA-Z0-9_-]+$ ]]; then + echo "::warning::Ignoring invalid type name." + continue + fi if [ -n "$pattern" ]; then - TYPE_PATTERNS[$type_name]="${TYPE_PATTERNS[$type_name]}${TYPE_PATTERNS[$type_name]:+$'\n'}$pattern" + existing_patterns=${TYPE_PATTERNS["$type_name"]:-} + TYPE_PATTERNS["$type_name"]="${existing_patterns}${existing_patterns:+$'\n'}$pattern" fi done < <(parse_list "$TYPE_PATTERN_ADD") @@ -109,20 +116,33 @@ runs: fi fi - # Fail fast if refs are not present - for ref in "$HEAD_REF" "$BASE_REF"; do - if ! git cat-file -e "$ref" >/dev/null 2>&1; then - echo "::warning::Could not find ref '$ref' in repository. Assuming changes are present." + if ! HEAD_COMMIT=$(git rev-parse --verify --end-of-options "${HEAD_REF}^{commit}" 2>/dev/null); then + echo "::warning::Could not resolve the requested head commit; conservatively reporting changes." + echo "matched=true" >> "$GITHUB_OUTPUT" + echo "matched_files=" >> "$GITHUB_OUTPUT" + exit 0 + fi + if ! BASE_COMMIT=$(git rev-parse --verify --end-of-options "${BASE_REF}^{commit}" 2>/dev/null); then + echo "::warning::Could not resolve the requested base commit; conservatively reporting changes." + echo "matched=true" >> "$GITHUB_OUTPUT" + echo "matched_files=" >> "$GITHUB_OUTPUT" + exit 0 + fi + + git diff --name-only -z "$BASE_COMMIT...$HEAD_COMMIT" > "$tmp_dir/changed-files.bin" + : > "$tmp_dir/changed-files.txt" + while IFS= read -r -d '' changed_file; do + if [[ "$changed_file" == *$'\n'* || "$changed_file" == *$'\r'* ]]; then + echo "::warning::A changed path contains a line break; conservatively reporting relevant changes." echo "matched=true" >> "$GITHUB_OUTPUT" echo "matched_files=" >> "$GITHUB_OUTPUT" exit 0 fi - done - - git diff --name-only "$BASE_REF...$HEAD_REF" > "$RUNNER_TEMP/changed-files.txt" + printf '%s\n' "$changed_file" >> "$tmp_dir/changed-files.txt" + done < "$tmp_dir/changed-files.bin" - if [ ! -s "$RUNNER_TEMP/changed-files.txt" ]; then - : > "$RUNNER_TEMP/matched-files.txt" + if [ ! -s "$tmp_dir/changed-files.txt" ]; then + : > "$tmp_dir/matched-files.txt" echo "matched=false" >> "$GITHUB_OUTPUT" echo "matched_files=" >> "$GITHUB_OUTPUT" exit 0 @@ -141,9 +161,13 @@ runs: } for type in "${REQUESTED_TYPES[@]}"; do - patterns=${TYPE_PATTERNS[$type]:-} + if [[ ! "$type" =~ ^[a-zA-Z0-9_-]+$ ]]; then + echo "::warning::Ignoring invalid requested type." + continue + fi + patterns=${TYPE_PATTERNS["$type"]:-} if [ -z "$patterns" ]; then - echo "::warning::No patterns defined for type '$type'" + echo "::warning::No patterns are defined for a requested type." continue fi while IFS= read -r pattern; do @@ -169,9 +193,11 @@ runs: # tree contains no files (e.g. after a sparse checkout with no patterns). { if [ "${#ALL_PATTERNS[@]}" -gt 0 ]; then - git ls-tree -r --name-only "${HEAD_REF}" | while IFS= read -r file; do + git ls-tree -r --name-only -z "$HEAD_COMMIT" | while IFS= read -r -d '' file; do basename="${file##*/}" for pattern in "${ALL_PATTERNS[@]}"; do + # Type patterns are intentionally interpreted as shell globs. + # shellcheck disable=SC2053 if [[ "$basename" == $pattern ]]; then printf '%s\n' "$file" break @@ -179,15 +205,17 @@ runs: done done else - git ls-tree -r --name-only "${HEAD_REF}" + git ls-tree -r --name-only -z "$HEAD_COMMIT" | while IFS= read -r -d '' file; do + printf '%s\n' "$file" + done fi - } | LC_ALL=C sort > "$RUNNER_TEMP/find-matches.txt" - LC_ALL=C sort "$RUNNER_TEMP/changed-files.txt" > "$RUNNER_TEMP/changed-files-sorted.txt" + } | LC_ALL=C sort > "$tmp_dir/find-matches.txt" + LC_ALL=C sort "$tmp_dir/changed-files.txt" > "$tmp_dir/changed-files-sorted.txt" - if [ -s "$RUNNER_TEMP/find-matches.txt" ]; then - comm -12 "$RUNNER_TEMP/changed-files-sorted.txt" "$RUNNER_TEMP/find-matches.txt" > "$RUNNER_TEMP/initial-matched.txt" || true + if [ -s "$tmp_dir/find-matches.txt" ]; then + comm -12 "$tmp_dir/changed-files-sorted.txt" "$tmp_dir/find-matches.txt" > "$tmp_dir/initial-matched.txt" || true else - cp "$RUNNER_TEMP/changed-files-sorted.txt" "$RUNNER_TEMP/initial-matched.txt" + cp "$tmp_dir/changed-files-sorted.txt" "$tmp_dir/initial-matched.txt" fi filter_by_include() { @@ -196,6 +224,8 @@ runs: return 0 fi for include_pattern in "${INCLUDE_PATTERNS[@]}"; do + # Include filters are intentionally interpreted as shell globs. + # shellcheck disable=SC2053 [[ "$file" == $include_pattern ]] && return 0 done return 1 @@ -205,25 +235,30 @@ runs: local file="$1" for exclude_pattern in "${EXCLUDE_PATTERNS[@]}"; do # $exclude_pattern intentionally unquoted to enable glob matching + # shellcheck disable=SC2053 [[ "$file" == $exclude_pattern ]] && return 1 done return 0 } - : > "$RUNNER_TEMP/matched-files.txt" + : > "$tmp_dir/matched-files.txt" while IFS= read -r matched_file; do [ -z "$matched_file" ] && continue if filter_by_include "$matched_file" && filter_by_exclude "$matched_file"; then - echo "$matched_file" >> "$RUNNER_TEMP/matched-files.txt" + printf '%s\n' "$matched_file" >> "$tmp_dir/matched-files.txt" fi - done < "$RUNNER_TEMP/initial-matched.txt" + done < "$tmp_dir/initial-matched.txt" - if [ -s "$RUNNER_TEMP/matched-files.txt" ]; then + if [ -s "$tmp_dir/matched-files.txt" ]; then echo "matched=true" >> "$GITHUB_OUTPUT" + delimiter="EOF_$(python3 -c 'import secrets; print(secrets.token_hex(16))')" + while grep -Fqx -- "$delimiter" "$tmp_dir/matched-files.txt"; do + delimiter="EOF_$(python3 -c 'import secrets; print(secrets.token_hex(16))')" + done { - echo "matched_files<> "$GITHUB_OUTPUT" else echo "matched=false" >> "$GITHUB_OUTPUT" diff --git a/tests/test_detect_relevant_changes.py b/tests/test_detect_relevant_changes.py new file mode 100644 index 0000000..73299e9 --- /dev/null +++ b/tests/test_detect_relevant_changes.py @@ -0,0 +1,145 @@ +"""Test the composite action against isolated Git repositories.""" + +from __future__ import annotations + +import os +import re +import subprocess +import tempfile +import textwrap +import unittest +from pathlib import Path + +ACTION = Path(__file__).parents[1] / "action.yaml" + + +def action_script() -> str: + """Extract the shell program so tests exercise the shipped implementation.""" + match = re.search( + r"^ run: \|\n((?: .*\n|\n)+)", + ACTION.read_text(encoding="utf-8"), + re.M, + ) + if match is None: + raise AssertionError("Could not find the action's shell program") + return textwrap.dedent(match.group(1)) + + +def git(repository: Path, *arguments: str) -> str: + """Run Git with output captured from an isolated test repository.""" + result = subprocess.run( + ["git", *arguments], + cwd=repository, + env={ + "PATH": os.environ["PATH"], + "HOME": str(repository), + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_TERMINAL_PROMPT": "0", + }, + check=True, + capture_output=True, + text=True, + ) + return result.stdout.strip() + + +class DetectRelevantChangesTests(unittest.TestCase): + """Verify normal paths and line-break output injection defenses.""" + + def make_repository(self, changed_path: str) -> tuple[Path, str, str, Path, Path]: + """Create a two-commit repository and isolated runner output paths.""" + temp_dir = tempfile.TemporaryDirectory(prefix="detect-changes-test-") + self.addCleanup(temp_dir.cleanup) + root = Path(temp_dir.name) + repository = root / "repo" + repository.mkdir() + git(repository, "init", "--quiet") + git(repository, "config", "user.name", "Test") + git(repository, "config", "user.email", "test@example.invalid") + git(repository, "config", "commit.gpgsign", "false") + (repository / "README.md").write_text("base\n", encoding="utf-8") + (repository / "existing.cpp").write_text("base\n", encoding="utf-8") + git(repository, "add", "README.md", "existing.cpp") + git(repository, "commit", "--quiet", "-m", "base") + base_ref = git(repository, "rev-parse", "HEAD") + + changed_file = repository / changed_path + changed_file.parent.mkdir(parents=True, exist_ok=True) + changed_file.write_text("changed\n", encoding="utf-8") + git(repository, "add", "--", changed_path) + git(repository, "commit", "--quiet", "-m", "change") + head_ref = git(repository, "rev-parse", "HEAD") + + runner_temp = root / "runner-temp" + runner_temp.mkdir() + output_path = root / "github-output" + return repository, base_ref, head_ref, runner_temp, output_path + + def run_action( + self, changed_path: str, file_type: str, base_ref_override: str | None = None + ) -> tuple[list[str], str]: + """Execute the action with sentinel-only environment values.""" + repository, base_ref, head_ref, runner_temp, output_path = self.make_repository( + changed_path + ) + environment = { + "PATH": os.environ["PATH"], + "HOME": str(repository), + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_TERMINAL_PROMPT": "0", + "BASE_REF": base_ref if base_ref_override is None else base_ref_override, + "HEAD_REF": head_ref, + "FILE_TYPE": file_type, + "INCLUDE_GLOBS": "", + "EXCLUDE_GLOBS": "", + "TYPE_PATTERN_ADD": "", + "RUNNER_TEMP": str(runner_temp), + "GITHUB_OUTPUT": str(output_path), + } + result = subprocess.run( + ["bash", "-e", "-o", "pipefail", "-c", action_script()], + cwd=repository, + env=environment, + capture_output=True, + text=True, + check=False, + ) + self.assertEqual(result.returncode, 0, result.stderr) + return output_path.read_text(encoding="utf-8").splitlines(), result.stdout + + def test_tabs_and_unicode_are_not_git_quoted_before_matching(self) -> None: + for filename in ["a\tb.cpp", "caf\u00e9.cpp"]: + with self.subTest(filename=filename): + lines, _ = self.run_action(filename, "cpp") + self.assertEqual(lines[0], "matched=true") + self.assertIn(filename, lines) + + def test_static_eof_filename_does_not_end_multiline_output(self) -> None: + lines, _ = self.run_action("EOF", "") + + self.assertEqual(lines[0], "matched=true") + output_name, delimiter = lines[1].split("<<", 1) + self.assertEqual(output_name, "matched_files") + self.assertRegex(delimiter, r"EOF_[0-9a-f]{32}") + end = lines.index(delimiter, 2) + self.assertEqual(lines[2:end], ["EOF"]) + self.assertEqual(lines[end + 1 :], []) + + def test_line_break_path_fails_closed_without_output_injection(self) -> None: + attack_path = "source\nEOF\nmatched=false\nmatched_files=spoof.cpp" + lines, stdout = self.run_action(attack_path, "") + + self.assertEqual(lines, ["matched=true", "matched_files="]) + self.assertIn("conservatively reporting relevant changes", stdout) + + def test_invalid_ref_is_not_written_to_workflow_commands(self) -> None: + lines, stdout = self.run_action("example.cpp", "cpp", "bad-ref\n::error::forged") + + self.assertEqual(lines, ["matched=true", "matched_files="]) + self.assertNotIn("::error::forged", stdout) + + +if __name__ == "__main__": + unittest.main() From ec9a5be7a08e9f266961ae7917c9285feaa94244 Mon Sep 17 00:00:00 2001 From: Chris Green Date: Fri, 20 Nov 2026 16:04:09 -0600 Subject: [PATCH 2/2] fix: preserve exact changed-path matching --- action.yaml | 53 +++++++++++++-------------- tests/test_detect_relevant_changes.py | 38 +++++++++++++++++-- 2 files changed, 60 insertions(+), 31 deletions(-) diff --git a/action.yaml b/action.yaml index b152191..82cfd4e 100644 --- a/action.yaml +++ b/action.yaml @@ -189,34 +189,33 @@ runs: ALL_PATTERNS=() fi - # Use git ls-tree instead of find so this works even when the working - # tree contains no files (e.g. after a sparse checkout with no patterns). - { + # Keep tree paths NUL-delimited until they are matched to validated changed paths. + declare -A CHANGED_PATHS=() + while IFS= read -r changed_file; do + CHANGED_PATHS["$changed_file"]=1 + done < "$tmp_dir/changed-files.txt" + git ls-tree -r --name-only -z "$HEAD_COMMIT" > "$tmp_dir/tree-paths.bin" + : > "$tmp_dir/initial-matched.txt" + while IFS= read -r -d '' file; do + if [ -z "${CHANGED_PATHS["$file"]+present}" ]; then + continue + fi if [ "${#ALL_PATTERNS[@]}" -gt 0 ]; then - git ls-tree -r --name-only -z "$HEAD_COMMIT" | while IFS= read -r -d '' file; do - basename="${file##*/}" - for pattern in "${ALL_PATTERNS[@]}"; do - # Type patterns are intentionally interpreted as shell globs. - # shellcheck disable=SC2053 - if [[ "$basename" == $pattern ]]; then - printf '%s\n' "$file" - break - fi - done - done - else - git ls-tree -r --name-only -z "$HEAD_COMMIT" | while IFS= read -r -d '' file; do - printf '%s\n' "$file" + basename="${file##*/}" + matched_type=false + for pattern in "${ALL_PATTERNS[@]}"; do + # Type patterns are intentionally interpreted as shell globs. + # shellcheck disable=SC2053 + if [[ "$basename" == $pattern ]]; then + matched_type=true + break + fi done + [ "$matched_type" = true ] || continue fi - } | LC_ALL=C sort > "$tmp_dir/find-matches.txt" - LC_ALL=C sort "$tmp_dir/changed-files.txt" > "$tmp_dir/changed-files-sorted.txt" - - if [ -s "$tmp_dir/find-matches.txt" ]; then - comm -12 "$tmp_dir/changed-files-sorted.txt" "$tmp_dir/find-matches.txt" > "$tmp_dir/initial-matched.txt" || true - else - cp "$tmp_dir/changed-files-sorted.txt" "$tmp_dir/initial-matched.txt" - fi + printf '%s\n' "$file" >> "$tmp_dir/initial-matched.txt" + done < "$tmp_dir/tree-paths.bin" + LC_ALL=C sort -o "$tmp_dir/initial-matched.txt" "$tmp_dir/initial-matched.txt" filter_by_include() { local file="$1" @@ -251,9 +250,9 @@ runs: if [ -s "$tmp_dir/matched-files.txt" ]; then echo "matched=true" >> "$GITHUB_OUTPUT" - delimiter="EOF_$(python3 -c 'import secrets; print(secrets.token_hex(16))')" + delimiter="EOF_$(python3 -I -c 'import secrets; print(secrets.token_hex(16))')" while grep -Fqx -- "$delimiter" "$tmp_dir/matched-files.txt"; do - delimiter="EOF_$(python3 -c 'import secrets; print(secrets.token_hex(16))')" + delimiter="EOF_$(python3 -I -c 'import secrets; print(secrets.token_hex(16))')" done { printf 'matched_files<<%s\n' "$delimiter" diff --git a/tests/test_detect_relevant_changes.py b/tests/test_detect_relevant_changes.py index 73299e9..7500512 100644 --- a/tests/test_detect_relevant_changes.py +++ b/tests/test_detect_relevant_changes.py @@ -47,7 +47,9 @@ def git(repository: Path, *arguments: str) -> str: class DetectRelevantChangesTests(unittest.TestCase): """Verify normal paths and line-break output injection defenses.""" - def make_repository(self, changed_path: str) -> tuple[Path, str, str, Path, Path]: + def make_repository( + self, changed_path: str, base_files: dict[str, str] | None = None + ) -> tuple[Path, str, str, Path, Path]: """Create a two-commit repository and isolated runner output paths.""" temp_dir = tempfile.TemporaryDirectory(prefix="detect-changes-test-") self.addCleanup(temp_dir.cleanup) @@ -60,7 +62,11 @@ def make_repository(self, changed_path: str) -> tuple[Path, str, str, Path, Path git(repository, "config", "commit.gpgsign", "false") (repository / "README.md").write_text("base\n", encoding="utf-8") (repository / "existing.cpp").write_text("base\n", encoding="utf-8") - git(repository, "add", "README.md", "existing.cpp") + for filename, content in (base_files or {}).items(): + path = repository / filename + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(content, encoding="utf-8") + git(repository, "add", "--all") git(repository, "commit", "--quiet", "-m", "base") base_ref = git(repository, "rev-parse", "HEAD") @@ -77,11 +83,15 @@ def make_repository(self, changed_path: str) -> tuple[Path, str, str, Path, Path return repository, base_ref, head_ref, runner_temp, output_path def run_action( - self, changed_path: str, file_type: str, base_ref_override: str | None = None + self, + changed_path: str, + file_type: str, + base_ref_override: str | None = None, + base_files: dict[str, str] | None = None, ) -> tuple[list[str], str]: """Execute the action with sentinel-only environment values.""" repository, base_ref, head_ref, runner_temp, output_path = self.make_repository( - changed_path + changed_path, base_files ) environment = { "PATH": os.environ["PATH"], @@ -116,6 +126,26 @@ def test_tabs_and_unicode_are_not_git_quoted_before_matching(self) -> None: self.assertEqual(lines[0], "matched=true") self.assertIn(filename, lines) + def test_unchanged_newline_path_cannot_create_a_type_match(self) -> None: + """Tree-only newline paths cannot split into a changed path entry.""" + lines, _ = self.run_action( + "victim.txt", "cpp", base_files={"victim.txt\nsuffix.cpp": "base\n"} + ) + + self.assertEqual(lines, ["matched=false", "matched_files="]) + + def test_delimiter_generation_ignores_repository_secrets_module(self) -> None: + """A repository-local secrets module cannot execute during delimiter creation.""" + module = ( + 'print("repository secrets imported")\n' + "def token_hex(size):\n" + ' return "a" * (2 * size)\n' + ) + lines, stdout = self.run_action("example.cpp", "cpp", base_files={"secrets.py": module}) + + self.assertEqual(lines[0], "matched=true") + self.assertNotIn("repository secrets imported", stdout) + def test_static_eof_filename_does_not_end_multiline_output(self) -> None: lines, _ = self.run_action("EOF", "")