Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
116 changes: 75 additions & 41 deletions action.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand All @@ -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")

Expand All @@ -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
printf '%s\n' "$changed_file" >> "$tmp_dir/changed-files.txt"
done < "$tmp_dir/changed-files.bin"

git diff --name-only "$BASE_REF...$HEAD_REF" > "$RUNNER_TEMP/changed-files.txt"

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
Expand All @@ -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
Expand All @@ -165,37 +189,42 @@ 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 "${HEAD_REF}" | while IFS= read -r file; do
basename="${file##*/}"
for pattern in "${ALL_PATTERNS[@]}"; do
if [[ "$basename" == $pattern ]]; then
printf '%s\n' "$file"
break
fi
done
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
else
git ls-tree -r --name-only "${HEAD_REF}"
[ "$matched_type" = true ] || continue
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"

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
else
cp "$RUNNER_TEMP/changed-files-sorted.txt" "$RUNNER_TEMP/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"
if [ "${#INCLUDE_PATTERNS[@]}" -eq 0 ]; then
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
Expand All @@ -205,25 +234,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 -I -c 'import secrets; print(secrets.token_hex(16))')"
while grep -Fqx -- "$delimiter" "$tmp_dir/matched-files.txt"; do
delimiter="EOF_$(python3 -I -c 'import secrets; print(secrets.token_hex(16))')"
done
{
echo "matched_files<<EOF"
cat "$RUNNER_TEMP/matched-files.txt"
echo "EOF"
printf 'matched_files<<%s\n' "$delimiter"
cat "$tmp_dir/matched-files.txt"
printf '%s\n' "$delimiter"
} >> "$GITHUB_OUTPUT"
else
echo "matched=false" >> "$GITHUB_OUTPUT"
Expand Down
175 changes: 175 additions & 0 deletions tests/test_detect_relevant_changes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,175 @@
"""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, 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)
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")
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")

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,
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, base_files
)
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_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", "")

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()
Loading