From 7792b36a49a611367b03b31a496ec4c2bc261fa8 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 11:15:03 +0000 Subject: [PATCH 1/5] fix(shell): capture before feeding a here-string, so a failed command is seen (RE012 sites) `consumer <<<"$(cmd)"` keeps only `consumer`'s status; `cmd`'s failure is discarded under set -e, pipefail and inherit_errexit alike (bash 5.2.21). Every such site in the tree is rewritten to capture first, in an assignment whose status is `cmd`'s, and to say what a failed read means there. The rule that finds the class, RE012, follows in a stacked PR and finds none here. Real defects the here-strings hid: - scripts/sweeps/estate-pr-automerge.sh: the workflow check ran `jq -r '.[].filename'` on one object per file, which fails (exit 5) on every PR, so no workflow edit was ever classed `meta` and a doc under .github/workflows/ could be armed for auto-merge. It now reads `.filename` from the captured objects, and a failed read is classed meta. New sweep test cases (PRs 18 and 19) fail on main and pass here. - scripts/check-readme-claims.sh anchors(): runs in an `||` list, where errexit is off, so grep's exit 2 inside a pipeline was lost (CodeRabbit on #1208). Each read is now captured and checked. A new test injects a grep that fails for one file only; it fails on main and passes here. - tests/rules-praxis-test.sh row_has (CodeRabbit on #1208): a failed read of the deed returns 2 instead of reading as a missing fact. Rewritten without a behaviour change: - hypatia-scanner-v2.sh: the 18 `parse_rg_line` calls (three subshells per match) become `IFS=: read -r filepath linenum content <<<"$match"`, which splits on the first two colons as `cut -f3-` did. 3006 rg lines compared: identical except 2 whose content ends in `|`, which the old form dropped. The scanner's JSON on a sample tree is identical (26 findings). - security-check.sh (4 sites, one helper spdx_in_head), gen-rules-praxis.sh (3), check-standards-integration.sh, patch_phase2.sh, hypatia-cli-bash.sh, fix-missing-spdx.sh, ci.yml, security-policy.yml, test/ci-health-test.sh (2). Checked: tests/rules-praxis-test.sh 22/22; tests/readme-claims-test.sh 10/10; test/ci-health-test.sh and test/pr-automerge-sweep-test.sh pass; gen-rules-praxis.sh regenerates the deed byte for byte; check-standards-integration.sh pass; ShellCheck adds no warning in any touched file (three fewer in the scanner); actionlint 1.7.7 reports the same 25 pre-existing findings on both workflows before and after. RE012 on this tree: 0 findings; RE011 exposed: 0. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01J4QvDgzT72Tq2HTJmikyNg --- .github/workflows/ci.yml | 5 +- .github/workflows/security-policy.yml | 3 +- hypatia-cli-bash.sh | 6 ++- hypatia-scanner-v2.sh | 49 +++++++++---------- scripts/check-readme-claims.sh | 15 ++++-- scripts/fix-scripts/fix-missing-spdx.sh | 4 +- scripts/gen-rules-praxis.sh | 12 +++-- scripts/security-check.sh | 26 ++++++++-- .../check-standards-integration.sh | 5 +- scripts/sweeps/estate-pr-automerge.sh | 12 +++-- scripts/sweeps/patch_phase2.sh | 3 +- test/ci-health-test.sh | 8 +-- test/pr-automerge-sweep-test.sh | 16 +++++- tests/readme-claims-test.sh | 13 +++++ tests/rules-praxis-test.sh | 4 +- 15 files changed, 126 insertions(+), 55 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a0870bb88..4fa0b3a4f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -450,7 +450,10 @@ jobs: test/placeholder_network_test.exs \ test/test_module_names_test.exs 2>&1 | tee "$RUNNER_TEMP/e0-receipt-tests.log" # A skipped test here means that Nickel was not found: the contract was not checked. - if grep -Eq '[0-9]+ skipped' <<<"$(tail -n 3 "$RUNNER_TEMP/e0-receipt-tests.log")"; then + # Captured first (RE012): an unreadable log stops the step instead of + # reading as "nothing skipped". + summary=$(tail -n 3 "$RUNNER_TEMP/e0-receipt-tests.log") + if grep -Eq '[0-9]+ skipped' <<<"$summary"; then echo "::error::a receipt test was skipped: the Nickel contract was NOT checked" exit 1 fi diff --git a/.github/workflows/security-policy.yml b/.github/workflows/security-policy.yml index 05ab6bb28..fa744e281 100644 --- a/.github/workflows/security-policy.yml +++ b/.github/workflows/security-policy.yml @@ -790,8 +790,9 @@ jobs: failed=1 fi done + job_lines=$(printf '%s\n' "${all_jobs[@]}") for j in $needs_list; do - if ! grep -qx -- "$j" <<<"$(printf '%s\n' "${all_jobs[@]}")"; then + if ! grep -qx -- "$j" <<<"$job_lines"; then echo "::error::aggregator needs '$j' but no such job exists in this workflow (#847)." failed=1 fi diff --git a/hypatia-cli-bash.sh b/hypatia-cli-bash.sh index d1975ec8a..7a6837e49 100755 --- a/hypatia-cli-bash.sh +++ b/hypatia-cli-bash.sh @@ -567,7 +567,7 @@ scan_code_patterns() { # Repository structure / layout checks # ───────────────────────────────────────────────────────────────────── scan_repo_structure() { - local dir="$1" + local dir="$1" first # .machine_readable/ directory if [[ ! -d "$dir/.machine_readable" ]]; then @@ -618,7 +618,9 @@ scan_repo_structure() { if [[ -d "$dir/.github/workflows" ]]; then for wf in "$dir/.github/workflows"/*.yml "$dir/.github/workflows"/*.yaml; do [[ -f "$wf" ]] || continue - if ! grep -q '^# SPDX-License-Identifier:' <<<"$(head -1 "$wf")"; then + # An unreadable workflow is reported as missing the header (RE012). + first=$(head -n 1 "$wf") || first="" + if ! grep -q '^# SPDX-License-Identifier:' <<<"$first"; then emit_finding "medium" "repo_structure" "missing_spdx_header" \ "$wf" 1 "Workflow missing SPDX header" "CWE-1059" \ "Add '# SPDX-License-Identifier: MPL-2.0' as first line" "true" diff --git a/hypatia-scanner-v2.sh b/hypatia-scanner-v2.sh index ce9fdc92f..956aa2f2e 100755 --- a/hypatia-scanner-v2.sh +++ b/hypatia-scanner-v2.sh @@ -67,15 +67,10 @@ scan_file() { local file="$1" local findings=() - # Helper to parse rg output (filepath:linenum:content) - # Only split on first TWO colons - parse_rg_line() { - local line="$1" - local filepath=$(echo "$line" | cut -d: -f1) - local linenum=$(echo "$line" | cut -d: -f2) - local content=$(echo "$line" | cut -d: -f3-) - echo "$filepath|$linenum|$content" - } + # rg -nH prints filepath:linenum:content. `read` splits on the first two + # colons and leaves the rest, colons included, in `content`. A plain + # here-string from the variable: no substitution whose status is lost + # (RE012), and a trailing `|` in content is kept. # Pattern 1: Any .res / .resi file (CRITICAL — ReScript banned 2026-04) if [[ "$file" == *.res || "$file" == *.resi ]]; then @@ -95,7 +90,7 @@ scan_file() { # Pattern 2: Rust unwrap (HIGH) if [[ "$file" == *.rs ]]; then while IFS= read -r match; do - IFS='|' read -r filepath linenum content <<< "$(parse_rg_line "$match")" + IFS=: read -r filepath linenum content <<<"$match" local finding finding=$(make_finding \ "high" \ @@ -113,7 +108,7 @@ scan_file() { # Pattern 3: Obj.magic (HIGH) if [[ "$file" == *.res ]]; then while IFS= read -r match; do - IFS='|' read -r filepath linenum content <<< "$(parse_rg_line "$match")" + IFS=: read -r filepath linenum content <<<"$match" local finding finding=$(make_finding \ "high" \ @@ -130,7 +125,7 @@ scan_file() { # Pattern 4: CORS wildcard (CRITICAL) while IFS= read -r match; do - IFS='|' read -r filepath linenum content <<< "$(parse_rg_line "$match")" + IFS=: read -r filepath linenum content <<<"$match" local finding finding=$(make_finding \ "critical" \ @@ -146,7 +141,7 @@ scan_file() { # Pattern 5: Unverified JWT decode (CRITICAL) while IFS= read -r match; do - IFS='|' read -r filepath linenum content <<< "$(parse_rg_line "$match")" + IFS=: read -r filepath linenum content <<<"$match" local finding finding=$(make_finding \ "critical" \ @@ -162,7 +157,7 @@ scan_file() { # Pattern 6: Google API Key (CRITICAL) while IFS= read -r match; do - IFS='|' read -r filepath linenum content <<< "$(parse_rg_line "$match")" + IFS=: read -r filepath linenum content <<<"$match" local finding finding=$(make_finding \ "critical" \ @@ -180,7 +175,7 @@ scan_file() { if [[ "$file" == *Cargo.lock ]]; then # protobuf recursion crash while IFS= read -r match; do - IFS='|' read -r filepath linenum content <<< "$(parse_rg_line "$match")" + IFS=: read -r filepath linenum content <<<"$match" local finding finding=$(make_finding \ "medium" \ @@ -196,7 +191,7 @@ scan_file() { # idna punycode mishandling while IFS= read -r match; do - IFS='|' read -r filepath linenum content <<< "$(parse_rg_line "$match")" + IFS=: read -r filepath linenum content <<<"$match" local finding finding=$(make_finding \ "medium" \ @@ -212,7 +207,7 @@ scan_file() { # jsonwebtoken type confusion while IFS= read -r match; do - IFS='|' read -r filepath linenum content <<< "$(parse_rg_line "$match")" + IFS=: read -r filepath linenum content <<<"$match" local finding finding=$(make_finding \ "medium" \ @@ -228,7 +223,7 @@ scan_file() { # lru stacked borrows violation while IFS= read -r match; do - IFS='|' read -r filepath linenum content <<< "$(parse_rg_line "$match")" + IFS=: read -r filepath linenum content <<<"$match" local finding finding=$(make_finding \ "low" \ @@ -244,7 +239,7 @@ scan_file() { # glib variantstriter unsoundness while IFS= read -r match; do - IFS='|' read -r filepath linenum content <<< "$(parse_rg_line "$match")" + IFS=: read -r filepath linenum content <<<"$match" local finding finding=$(make_finding \ "medium" \ @@ -260,7 +255,7 @@ scan_file() { # crossbeam-utils atomiccell unsoundness while IFS= read -r match; do - IFS='|' read -r filepath linenum content <<< "$(parse_rg_line "$match")" + IFS=: read -r filepath linenum content <<<"$match" local finding finding=$(make_finding \ "high" \ @@ -276,7 +271,7 @@ scan_file() { # lock_api data race while IFS= read -r match; do - IFS='|' read -r filepath linenum content <<< "$(parse_rg_line "$match")" + IFS=: read -r filepath linenum content <<<"$match" local finding finding=$(make_finding \ "medium" \ @@ -292,7 +287,7 @@ scan_file() { # crossbeam-queue segqueue unsoundness while IFS= read -r match; do - IFS='|' read -r filepath linenum content <<< "$(parse_rg_line "$match")" + IFS=: read -r filepath linenum content <<<"$match" local finding finding=$(make_finding \ "medium" \ @@ -311,7 +306,7 @@ scan_file() { if [[ "$file" == *yarn.lock ]]; then # serialize-javascript while IFS= read -r match; do - IFS='|' read -r filepath linenum content <<< "$(parse_rg_line "$match")" + IFS=: read -r filepath linenum content <<<"$match" local finding finding=$(make_finding \ "high" \ @@ -327,7 +322,7 @@ scan_file() { # minimatch while IFS= read -r match; do - IFS='|' read -r filepath linenum content <<< "$(parse_rg_line "$match")" + IFS=: read -r filepath linenum content <<<"$match" local finding finding=$(make_finding \ "high" \ @@ -343,7 +338,7 @@ scan_file() { # glob while IFS= read -r match; do - IFS='|' read -r filepath linenum content <<< "$(parse_rg_line "$match")" + IFS=: read -r filepath linenum content <<<"$match" local finding finding=$(make_finding \ "high" \ @@ -359,7 +354,7 @@ scan_file() { # js-yaml while IFS= read -r match; do - IFS='|' read -r filepath linenum content <<< "$(parse_rg_line "$match")" + IFS=: read -r filepath linenum content <<<"$match" local finding finding=$(make_finding \ "medium" \ @@ -375,7 +370,7 @@ scan_file() { # h3 while IFS= read -r match; do - IFS='|' read -r filepath linenum content <<< "$(parse_rg_line "$match")" + IFS=: read -r filepath linenum content <<<"$match" local finding finding=$(make_finding \ "high" \ diff --git a/scripts/check-readme-claims.sh b/scripts/check-readme-claims.sh index 47a5b1040..848811ee0 100755 --- a/scripts/check-readme-claims.sh +++ b/scripts/check-readme-claims.sh @@ -63,10 +63,17 @@ fi # The ids an AsciiDoc file defines: explicit [[id]], [[id,label]], [#id], # anchor:id[], and the default section ids (_title_in_lower_case). anchors() { - local file=$1 - # grep exits 1 when a file has no explicit ID: no match, not an error. - { { grep -oE '\[\[[A-Za-z0-9_:.-]+|\[#[A-Za-z0-9_:-]+|anchor:[A-Za-z0-9_:.-]+\[' "$file" || [[ $? -eq 1 ]]; } | sed -E 's/^(\[\[|\[#|anchor:)//; s/\[$//' - sed -nE 's/^=+ +(.*)$/\1/p' "$file" | tr '[:upper:]' '[:lower:]' | sed -E 's/[^a-z0-9]+/_/g; s/_+$//; s/^/_/' + local file=$1 explicit titles + # Each read is captured and checked on its own. The caller runs this in an + # `||` list, where errexit is off, so a failure inside a pipeline would + # otherwise be lost (CodeRabbit on #1208). grep exits 1 when a file has no + # explicit ID: no match, not an error; 2 is an error. + explicit=$(grep -oE '\[\[[A-Za-z0-9_:.-]+|\[#[A-Za-z0-9_:-]+|anchor:[A-Za-z0-9_:.-]+\[' "$file") || + [[ $? -eq 1 ]] || return 2 + titles=$(sed -nE 's/^=+ +(.*)$/\1/p' "$file") || return 2 + { + [[ -z "$explicit" ]] || sed -E 's/^(\[\[|\[#|anchor:)//; s/\[$//' <<<"$explicit" + [[ -z "$titles" ]] || tr '[:upper:]' '[:lower:]' <<<"$titles" | sed -E 's/[^a-z0-9]+/_/g; s/_+$//; s/^/_/' } | sort -u } diff --git a/scripts/fix-scripts/fix-missing-spdx.sh b/scripts/fix-scripts/fix-missing-spdx.sh index d5edbf1af..04be334d9 100755 --- a/scripts/fix-scripts/fix-missing-spdx.sh +++ b/scripts/fix-scripts/fix-missing-spdx.sh @@ -67,7 +67,9 @@ fix_file() { local header="${COMMENT_STYLE[$ext]}" # Handle shebang lines — insert after shebang - if grep -q "^#!" <<<"$(head -1 "$file")"; then + local first + first=$(head -n 1 "$file") || return 1 + if grep -q "^#!" <<<"$first"; then sed -i "1a\\${header}" "$file" else sed -i "1i\\${header}" "$file" diff --git a/scripts/gen-rules-praxis.sh b/scripts/gen-rules-praxis.sh index 1cacff3de..b78f754ff 100755 --- a/scripts/gen-rules-praxis.sh +++ b/scripts/gen-rules-praxis.sh @@ -193,7 +193,8 @@ for f in lib/rules/*.ex; do # Skip only an id already emitted from the severity table above; a # provenance table (`| BP001 | CIS GH 1.1.x | ... |`) is not one. grep -qE "^ *\| $id \| (critical|high|medium|low|info|warn) \| " "$f" && continue - IFS=$'\037' read -r sev adv desc <<<"$(near "$f" "$id")" + rec=$(near "$f" "$id") || { echo "gen-rules-praxis: cannot read $f for $id" >&2; exit 1; } + IFS=$'\037' read -r sev adv desc <<<"$rec" text=$(text_of "$f" "$id") [ -z "$text" ] && text=$(printf '%s' "$desc" | clean) d="" @@ -337,11 +338,13 @@ moved() { grep -qE "rule_id: \"hypatia/[a-z_]+/$2\"" "$1" && ! grep -qE "rule_id # $1 module, $2 names (one per line), $3 hit regex builder: names read from `type:` # atoms or from lowercase `rule: "name"` strings. emit_found() { # - local m=$1 f=lib/rules/$1.ex name sev adv desc; shift + local m=$1 f=lib/rules/$1.ex name sev adv desc rec; shift for name in $(printf '%s\n' "$@" | sort -u); do [ -z "$name" ] && continue moved "$f" "$name" "$m" && continue - IFS=$'\037' read -r sev adv desc <<<"$(near "$f" "$name" "(type|rule): (:|\")$name([^a-z0-9_]|\$)")" + rec=$(near "$f" "$name" "(type|rule): (:|\")$name([^a-z0-9_]|\$)") || + { echo "gen-rules-praxis: cannot read $f for $name" >&2; exit 1; } + IFS=$'\037' read -r sev adv desc <<<"$rec" emit_name "$m" "$name" "$sev" "$desc" "$adv" done } @@ -367,7 +370,8 @@ while IFS='~' read -r mod name f lit sev adv sf slit text; do grep -qF -- "$lit" "$f" || { echo "gen-rules-praxis: $f no longer has '$lit' ($mod/$name)" >&2; exit 1; } if [ "$sf" = "$f" ]; then # same file: beside the literal (a trailing #any: anywhere in it) n=$(grep -nF -- "$lit" "$f" | sed -n 1p | cut -d: -f1) - grep -qF -- "$slit" <<<"$(sed -n "$((n - 3)),$((n + 3))p" "$f")" || + beside=$(sed -n "$((n - 3)),$((n + 3))p" "$f") || { echo "gen-rules-praxis: cannot read $f" >&2; exit 1; } + grep -qF -- "$slit" <<<"$beside" || { echo "gen-rules-praxis: $f no longer states '$slit' beside '$lit' ($mod/$name)" >&2; exit 1; } else sf=${sf%#any} diff --git a/scripts/security-check.sh b/scripts/security-check.sh index 7892ca389..a189807ae 100755 --- a/scripts/security-check.sh +++ b/scripts/security-check.sh @@ -489,6 +489,24 @@ run_container_checks() { # License Compliance # ============================================================================ +# spdx_in_head N FILE: true when the first N lines of FILE name an SPDX licence. +# The lines are captured first (RE012): an unreadable file returns 2, which the +# caller counts as missing, so a failed read is never taken for a header. +spdx_in_head() { + local top + top=$(head -n "$1" "$2") || return 2 + grep -q "SPDX-License-Identifier" <<<"$top" +} + +# spdx_in_head N FILE: true when the first N lines of FILE name an SPDX licence. +# The lines are captured first (RE012): an unreadable file returns 2, which the +# caller counts as missing, so a failed read is never taken for a header. +spdx_in_head() { + local top + top=$(head -n "$1" "$2") || return 2 + grep -q "SPDX-License-Identifier" <<<"$top" +} + check_spdx_headers() { print_subheader "SPDX Headers: Checking license headers" CHECKS_RUN=$((CHECKS_RUN + 1)) @@ -504,7 +522,7 @@ check_spdx_headers() { # Check Rust files echo "## Rust Files (.rs)" >> "$report_file" while IFS= read -r -d '' f; do - if ! grep -q "SPDX-License-Identifier" <<<"$(head -10 "$f")"; then + if ! spdx_in_head 10 "$f"; then echo " - $f" >> "$report_file" missing_count=$((missing_count + 1)) fi @@ -514,7 +532,7 @@ check_spdx_headers() { echo "" >> "$report_file" echo "## Haskell Files (.hs)" >> "$report_file" while IFS= read -r -d '' f; do - if ! grep -q "SPDX-License-Identifier" <<<"$(head -10 "$f")"; then + if ! spdx_in_head 10 "$f"; then echo " - $f" >> "$report_file" missing_count=$((missing_count + 1)) fi @@ -524,7 +542,7 @@ check_spdx_headers() { echo "" >> "$report_file" echo "## Shell Scripts (.sh)" >> "$report_file" while IFS= read -r -d '' f; do - if ! grep -q "SPDX-License-Identifier" <<<"$(head -10 "$f")"; then + if ! spdx_in_head 10 "$f"; then echo " - $f" >> "$report_file" missing_count=$((missing_count + 1)) fi @@ -534,7 +552,7 @@ check_spdx_headers() { echo "" >> "$report_file" echo "## GitHub Workflows (.yml)" >> "$report_file" while IFS= read -r -d '' f; do - if ! grep -q "SPDX-License-Identifier" <<<"$(head -1 "$f")"; then + if ! spdx_in_head 1 "$f"; then echo " - $f" >> "$report_file" missing_count=$((missing_count + 1)) fi diff --git a/scripts/standards-integration/check-standards-integration.sh b/scripts/standards-integration/check-standards-integration.sh index 9009901cf..12908e525 100755 --- a/scripts/standards-integration/check-standards-integration.sh +++ b/scripts/standards-integration/check-standards-integration.sh @@ -105,7 +105,10 @@ EOF_LOCK done grep -qF "'metadatastician/standards@$PIN':" "$LOCK" \ || fail "actions.lock has no dependency entry for metadatastician/standards@$PIN" -grep -qF "commit: 'sha1-$PIN'" <<<"$(grep -A2 -F "'metadatastician/standards@$PIN':" "$LOCK")" \ +# Captured first (RE012): a failed read is said, not taken as a mismatch. +entry=$(grep -A2 -F "'metadatastician/standards@$PIN':" "$LOCK") \ + || fail "actions.lock dependency for standards@$PIN cannot be read" +grep -qF "commit: 'sha1-$PIN'" <<<"$entry" \ || fail "actions.lock dependency for standards@$PIN does not resolve to sha1-$PIN" # --- Lock transitive closure: every workflow ref and every transitive diff --git a/scripts/sweeps/estate-pr-automerge.sh b/scripts/sweeps/estate-pr-automerge.sh index 14fd87682..7b77368f5 100755 --- a/scripts/sweeps/estate-pr-automerge.sh +++ b/scripts/sweeps/estate-pr-automerge.sh @@ -267,7 +267,10 @@ decide_pr() { --jq '.[] | {filename:.filename, patch:(.patch // "")}' 2>/dev/null || echo '') # file-level analysis - files_total=$(jq -c . <<<"$patches" | wc -l) + # One compact object per changed file. Captured once (RE012): the file loop + # and the workflow check below read this, not a fresh substitution each. + fobjs=$(jq -c . <<<"$patches") + files_total=$(grep -c . <<<"$fobjs" || true) poison_hits=0; nonpin_change=0; lock_only=1; meta_only=1; licence_touch=0; pin_files=0 while IFS= read -r fobj; do @@ -316,7 +319,7 @@ decide_pr() { newv=$(resolve_version "$base" "$aref") deltas+=("${base}|${oldv:-?}|${newv:-?}") done <<<"$removed" - done <<<"$(jq -c . <<<"$patches")" + done <<<"$fobjs" delta_json=$(printf '%s\n' "${deltas[@]:-}" | jq -Rsc 'split("\n") | map(select(. != "")) | map(split("|") | {action: .[0], from: .[1], to: .[2]})') @@ -457,7 +460,10 @@ decide_pr() { meta_exemption="MGX-001" else meta_exemption="" - if grep -q '\.github/workflows/' <<<"$(jq -r '.[].filename' <<<"$patches" 2>/dev/null)"; then + # `$patches` is one object per file, not an array: the old `.[].filename` + # failed on every PR, and the here-string hid the failure, so a workflow + # change was never classed meta. A failed read is classed meta (RE012). + if ! filenames=$(jq -r '.filename' <<<"$fobjs") || grep -q '\.github/workflows/' <<<"$filenames"; then change_level="meta" [ "$safety" = "arm_auto" ] && { safety="flag"; disposition="flag"; blocked_by="meta_no_pin_exemption"; } fi diff --git a/scripts/sweeps/patch_phase2.sh b/scripts/sweeps/patch_phase2.sh index 122016b84..b7ba30aab 100755 --- a/scripts/sweeps/patch_phase2.sh +++ b/scripts/sweeps/patch_phase2.sh @@ -40,7 +40,8 @@ END=$(awk -v s="$START" 'NR>s && /'"$NEXT_RE"'/ {print NR; exit}' "$WF" || true) [ -n "${END:-}" ] || END=$((TOTAL + 1)) # Idempotency: bail if the existing block already carries the fix. -if grep -q '^ continue-on-error: true$' <<<"$(sed -n "${START},$((END - 1))p" "$WF")"; then +block=$(sed -n "${START},$((END - 1))p" "$WF") +if grep -q '^ continue-on-error: true$' <<<"$block"; then exit 2 fi diff --git a/test/ci-health-test.sh b/test/ci-health-test.sh index d103f8f7b..a0b0f6bdd 100755 --- a/test/ci-health-test.sh +++ b/test/ci-health-test.sh @@ -75,7 +75,8 @@ for fixture in "$ROOT"/test/fixtures/ci-health/allowlist/*.json; do # Idempotent: a second run finds nothing missing and writes nothing. : > "$STATE_DIR/puts.log" - grep -q '^SKIP ' <<<"$(remediate)" || { echo "FAIL [$name]: second run was not a no-op" >&2; exit 1; } + again=$(remediate) || { echo "FAIL [$name]: the second run failed" >&2; exit 1; } + grep -q '^SKIP ' <<<"$again" || { echo "FAIL [$name]: second run was not a no-op" >&2; exit 1; } [[ ! -s "$STATE_DIR/puts.log" ]] || { echo "FAIL [$name]: second run wrote" >&2; exit 1; } # Converges with detect.sh: B-ALLOWLIST no longer fires. @@ -147,10 +148,11 @@ put_paths=$(grep '^PUT ' "$STATE_DIR/writes.log" | cut -d' ' -f2 | sort | paste grep -qx 'POST repos/test-owner/test-repo/git/refs | ref=refs/heads/ci/ci-health-auto-remediation | sha=cafe0001' "$STATE_DIR/writes.log" || { echo "FAIL [D-BURN]: the branch was not cut from the commit the patches were read at" >&2; exit 1; } put_content() { # the decoded content written to - local file=$1 line + local file=$1 line json line=$(grep "^PUT repos/test-owner/test-repo/contents/.github/workflows/$file " "$STATE_DIR/writes.log") || { echo "FAIL [D-BURN]: no PUT for $file" >&2; exit 1; } - jq -r . <<<"$(sed -E 's/.* \| content=(".*") \| sha=.*/\1/' <<<"$line")" + json=$(sed -E 's/.* \| content=(".*") \| sha=.*/\1/' <<<"$line") + jq -r . <<<"$json" } for f in commented.yml has-concurrency.yml; do written=$(put_content "$f") diff --git a/test/pr-automerge-sweep-test.sh b/test/pr-automerge-sweep-test.sh index 858d7736d..013ca4954 100755 --- a/test/pr-automerge-sweep-test.sh +++ b/test/pr-automerge-sweep-test.sh @@ -111,7 +111,7 @@ threads() { # PR NODES HAS_NEXT_PAGE } estate() { # head sha of PR 7 put orgs__hyperpolymath__repos '[{"name":"r","fork":false,"disabled":false,"archived":false}]' - put repos__hyperpolymath__r__pulls "[$(pr 7 'dependabot[bot]' "$1"),$(pr 8 alice "$SHA1"),$(pr 9 'dependabot[bot]' "$SHA1"),$(pr 10 'dependabot[bot]' "$SHA1"),$(pr 11 'dependabot[bot]' "$SHA1"),$(pr 12 'dependabot[bot]' "$SHA1"),$(pr 13 'dependabot[bot]' "$SHA1"),$(pr 14 'dependabot[bot]' "$SHA1"),$(pr 15 'dependabot[bot]' "$SHA1"),$(pr 16 'dependabot[bot]' "$SHA1"),$(pr 17 'dependabot[bot]' "$SHA1")]" + put repos__hyperpolymath__r__pulls "[$(pr 7 'dependabot[bot]' "$1"),$(pr 8 alice "$SHA1"),$(pr 9 'dependabot[bot]' "$SHA1"),$(pr 10 'dependabot[bot]' "$SHA1"),$(pr 11 'dependabot[bot]' "$SHA1"),$(pr 12 'dependabot[bot]' "$SHA1"),$(pr 13 'dependabot[bot]' "$SHA1"),$(pr 14 'dependabot[bot]' "$SHA1"),$(pr 15 'dependabot[bot]' "$SHA1"),$(pr 16 'dependabot[bot]' "$SHA1"),$(pr 17 'dependabot[bot]' "$SHA1"),$(pr 18 'dependabot[bot]' "$SHA1"),$(pr 19 'dependabot[bot]' "$SHA1")]" put repos__hyperpolymath__r '{"archived":false,"default_branch":"main"}' put repos__hyperpolymath__r__pulls__7 "$(pr 7 'dependabot[bot]' "$1")" put repos__hyperpolymath__r__pulls__8 "$(pr 8 alice "$SHA1")" @@ -132,11 +132,17 @@ estate() { # head sha of PR 7 put repos__hyperpolymath__r__pulls__16__files '[{"filename":"docs/package.json","patch":"@@ -1 +1 @@\n-\"a\": \"1\"\n+\"a\": \"2\""}]' put repos__hyperpolymath__r__pulls__17 "$(pr 17 'dependabot[bot]' "$SHA1")" put repos__hyperpolymath__r__pulls__17__files '[{"filename":"requirements.txt","patch":"@@ -1 +1 @@\n-a==1.0\n+a==1.1"}]' + # A workflow edit that is not a pin substitution is `meta` (the decision + # contract): a doc file under .github/workflows/ is otherwise meta_only. + put repos__hyperpolymath__r__pulls__18 "$(pr 18 'dependabot[bot]' "$SHA1")" + put repos__hyperpolymath__r__pulls__18__files '[{"filename":".github/workflows/README.md","patch":"@@ -1 +1 @@\n-old\n+new"}]' + put repos__hyperpolymath__r__pulls__19 "$(pr 19 'dependabot[bot]' "$SHA1")" + put repos__hyperpolymath__r__pulls__19__files '[{"filename":".github/workflows/ci.yml","patch":"@@ -1 +1 @@\n- runs-on: a\n+ runs-on: b"}]' put repos__hyperpolymath__r__pulls__9__files '[{"filename":"go.sum","patch":"@@ -1 +1 @@\n-h1:old\n+h1:new"}]' put search__issues '{"total_count":2}' for n in 7 8; do put "repos__hyperpolymath__r__pulls__${n}__files" '[{"filename":"Cargo.lock","patch":"@@ -1 +1 @@\n-version = \"1.0.199\"\n+version = \"1.0.200\""}]'; done # R6: every PR's review threads resolved unless a case says otherwise - for n in 7 8 9 10 11 12 13 14 15 16 17; do threads "$n" '[{"isResolved":true}]' false; done + for n in 7 8 9 10 11 12 13 14 15 16 17 18 19; do threads "$n" '[{"isResolved":true}]' false; done # the merge_ready fixtures, for hyperpolymath/r for f in "$FIX"/repos__o__r__*; do cp "$f" "${f/repos__o__r__/repos__hyperpolymath__r__}"; done } @@ -157,6 +163,12 @@ done for n in 16 17; do [ "$(disp $n)" = "flag/dependency_manifest_not_lockfile" ] || fail "a dependency manifest is never documentation: PR $n must be flagged, got $(disp $n)" done +level() { jq -r --argjson n "$1" 'select(.pr.number == $n) | .change_level' "$WORK/out/pr-decisions.jsonl"; } +[ "$(disp 18)" = "flag/meta_no_pin_exemption" ] || fail "a doc under .github/workflows/ is meta, not auto_merge: PR 18 got $(disp 18)" +for n in 18 19; do + [ "$(level $n)" = "meta" ] || fail "a non-pin workflow edit is change_level meta: PR $n got $(level $n)" +done +[ "$(level 12)" != "meta" ] || fail "docs/guide.md is not a workflow edit: PR 12 must not be meta" cp "$WORK/out/pr-decisions.jsonl" "$WORK/plan.jsonl" rm -f "$FIX/pr.log"; run --execute --from "$WORK/plan.jsonl" diff --git a/tests/readme-claims-test.sh b/tests/readme-claims-test.sh index 7c3883695..ebdf32a18 100755 --- a/tests/readme-claims-test.sh +++ b/tests/readme-claims-test.sh @@ -63,6 +63,19 @@ sed -i 's/#_planted_section\[/#_no_such_section[/' "$work/tree/README.adoc" expect_msg "a missing section ID in such a target is refused" 1 "defines no anchor _no_such_section" \ env README_CLAIMS_ROOT="$work/tree" bash "$script" +# grep's exit 2 on a target must reach the caller as "cannot be read", not be +# taken for a target that lacks the anchor (CodeRabbit on #1208). The fault is +# injected: a grep on PATH that fails for the planted file only, so the sed +# that reads the same file succeeds and cannot report the failure for it. +copy; printf '= Planted\n\n[[x]]\ntext\n' > "$work/tree/docs/planted-grep-fails.adoc" +printf '\nlink:docs/planted-grep-fails.adoc#x[planted]\n' >> "$work/tree/README.adoc" +faulty="$work/faulty"; mkdir -p "$faulty" +real_grep=$(command -v grep) +printf '#!/usr/bin/env bash\nfor a in "$@"; do [[ "$a" == *planted-grep-fails.adoc ]] && { echo "grep: $a: I/O error" >&2; exit 2; }; done\nexec %q "$@"\n' "$real_grep" > "$faulty/grep" +chmod +x "$faulty/grep" +expect_msg "a target grep cannot read is refused as unreadable" 1 "the anchors of docs/planted-grep-fails.adoc cannot be read" \ + env README_CLAIMS_ROOT="$work/tree" PATH="$faulty:$PATH" bash "$script" + copy; touch "$work/tree/lib/mix/tasks/hypatia.planted.ex" expect_msg "a Mix task the README does not count is refused" 1 "Mix tasks" \ env README_CLAIMS_ROOT="$work/tree" bash "$script" diff --git a/tests/rules-praxis-test.sh b/tests/rules-praxis-test.sh index 6e1950038..dda518ee8 100755 --- a/tests/rules-praxis-test.sh +++ b/tests/rules-praxis-test.sh @@ -88,7 +88,9 @@ expect_broken "an un-retired tombstone is refused" "$work/tomb.deed" "tombstone row() { local id=$1; awk -v t="\"$id\"" '$1 == ":id" { on = ($2 == t) } on { print }' "$deed"; } # one rule-def # Whether a rule-def carries a fact. Captured, then matched: `row | grep -q` # loses a match to SIGPIPE under pipefail when awk is still writing (RE011). -row_has() { local id=$1 fact=$2; grep -q -- "$fact" <<<"$(row "$id")"; } +# A failed read of the deed is a failure, not a missing fact (RE012): the +# here-string is fed from the captured row, whose status is checked. +row_has() { local id=$1 fact=$2 def; def=$(row "$id") || return 2; grep -q -- "$fact" <<<"$def"; } if row_has hypatia/branch_protection/BP001 ':severity high' && row_has hypatia/supply_chain/SC001 ':status active'; then ok "opt-in scanner rules are registered"; else bad "BP001/SC001 missing or wrong"; fi if row_has hypatia/git_state/GS007 ':class advisory'; then ok "an advisory-severity rule is class advisory"; else bad "GS007 is not class advisory"; fi if row_has hypatia/code_scanning_alerts/CSA006 ':severity medium'; then ok "a multi-severity rule keeps its highest severity"; else bad "CSA006 is not medium"; fi From 3affcc5e48bc4c2901dff2cffc24257eddb31a0b Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 11:00:19 +0000 Subject: [PATCH 2/5] feat(rules): RE012, a here-string fed by a command substitution discards its status `consumer <<<"$(cmd)"` keeps only the status of `consumer`. A failed `cmd` reads as empty input: `set -e` does not fire, `pipefail` does not apply, and `shopt -s inherit_errexit` does not change it (checked on bash 5.2.21, and by the new test's first block, which runs bash). CodeRabbit raised the class on #1208 (`tests/rules-praxis-test.sh` `row_has`); owner decision of 2026-11-24: a rule, every here-string. RE012 reads the sources RE011 reads (shell files, and the run: scripts of the parsed workflows, skipping pwsh, powershell, python and cmd steps). A small lexer per line finds a `<<<` outside quotes and comments whose word holds `$(...)` or a backquote; `$((...))` is not a command, and a here-string inside a substitution is read too. `:warn`, or `:info` when the substitution is a lone printf/echo with no redirection, pipe, list or nested substitution. Flag-only: `:review`, `advisory: true`, and the same inline directive as RE011 (`hypatia: allow research_extensions/RE012 -- ...`). RE011's workflow walk and directive check are now shared (`run_scripts/1`, `shell_files/1`, `shell_line_reviewed?/3`); RE011's behaviour is unchanged (its 98 tests pass). Tests: 46 in test/research_extensions_re012_test.exs; 11 mutants of the rule (arithmetic, comment, single quote, escape, backquote, recursion, shell skip, benign class, benign redirection, review directive, advisory) each fail it. mix test: 3770 tests, 0 failures. The catalogue and the praxis deed are regenerated by their scripts; deed_lint OK. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01J4QvDgzT72Tq2HTJmikyNg --- docs/rules/catalogue.adoc | 4 +- hypatia_rules_praxis.deed | 9 + lib/hypatia/cli.ex | 4 +- lib/rules/research_extensions.ex | 330 ++++++++++++++++++++++-- lib/rules/rules.ex | 7 +- test/research_extensions_re012_test.exs | 297 +++++++++++++++++++++ 6 files changed, 624 insertions(+), 27 deletions(-) create mode 100644 test/research_extensions_re012_test.exs diff --git a/docs/rules/catalogue.adoc b/docs/rules/catalogue.adoc index ae445ac55..48e831ad9 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 07705598d..2b4aab170 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 6a9cebb61..09e29389e 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 b6d662162..8ed37b1e7 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,278 @@ 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 `printf` or `echo` builtin with + # no redirection, pipe, list or nested substitution (`$var` is allowed). + @re012_benign ~r/\A[[:space:]]*(?:printf|echo)(?:[[:space:]]+(?:[^|;&`$<>()]|\$(?!\())*)?[[:space:]]*\z/ + + # Steps whose shell is not a POSIX-family shell: `<<<` means nothing there. + @re012_not_sh ~w(pwsh powershell python cmd) + + @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 whose shell is `pwsh`, `powershell`, + `python` or `cmd` is not read. 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 `$((…))` is not a command. A here-string inside a substitution + (`x=$(grep -c . <<<"$(cmd)")`) is read too. Each line is read on its own, + with full-line comments ignored. + + 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` when the substitution is a lone `printf` + or `echo` with no redirection, pipe, list or nested substitution: that + builtin does not fail on a here-string's buffer, so nothing is lost. + + ## 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, producer} <- here_string_substitution_lines(content), + not shell_line_reviewed?(lines, line, "RE012") do + re012_finding(rel, line, text, producer) + 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, producer} <- re012_workflow_hits(Workflow.parse(bytes, rel), bytes), + not shell_line_reviewed?(source, line, "RE012") do + re012_finding(rel, line, text, producer) + 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), + not re012_not_sh?(shell), + {_line, offset, text, producer} <- here_string_substitution_lines(script) do + {line_of.(offset), text, producer} + end + end + + defp re012_workflow_hits({:error, _error}, bytes) do + for {line, _offset, text, producer} <- here_string_substitution_lines(bytes), + do: {line, text, producer} + end + + defp re012_not_sh?(nil), do: false + + defp re012_not_sh?(shell) do + shell + |> String.split(~r/[[:space:]]+/, trim: true) + |> List.first() + |> Path.basename() + |> then(&(&1 in @re012_not_sh)) + end + + defp re012_finding(rel, line, text, producer) do + benign? = is_binary(producer) and Regex.match?(@re012_benign, producer) + + reason = + if benign? do + "#{rel}:#{line} feeds a here-string from a lone `printf`/`echo`, 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, + 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, producer}`. + `producer` is the text of the first substitution in the here-string's + word, or nil when it does not close on that line (or is a backquote). + """ + 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 + + if Regex.match?(~r/^[[:space:]]*#/, line) do + {hits, next} + else + case hs_walk(line, :none, true) do + {:hit, producer} -> {[{no, offset, line, producer} | hits], next} + :none -> {hits, next} + end + 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. Returns {:hit, producer} at the first here-string fed by a + # command substitution, else :none. + defp hs_walk(<<>>, _state, _ws), do: :none + defp hs_walk(<>, :single, _ws), do: hs_walk(rest, :none, false) + defp hs_walk(<<_, rest::binary>>, :single, _ws), do: hs_walk(rest, :single, false) + defp hs_walk(<>, state, _ws), do: hs_walk(rest, state, false) + defp hs_walk(<>, _state, _ws), do: :none + defp hs_walk(<>, :double, _ws), do: hs_walk(rest, :none, false) + defp hs_walk(<>, :none, _ws), do: hs_walk(rest, :double, false) + defp hs_walk(<>, :none, _ws), do: hs_walk(rest, :single, false) + defp hs_walk(<>, :none, true), do: :none + + defp hs_walk(<<"<<<", rest::binary>>, :none, _ws) do + case hs_word(String.trim_leading(rest), :none) do + {:hit, _} = hit -> hit + :none -> hs_walk(rest, :none, false) + end + end + + # A substitution in :none or :double: read inside it as a fresh line, then + # go on after it in the state we were in. + defp hs_walk(<<"$(", rest::binary>>, state, _ws) do + case hs_close(rest) do + {inner, after_} -> + with :none <- hs_walk(inner, :none, true), do: hs_walk(after_, state, false) + + :open -> + hs_walk(rest, :none, true) + end + end + + defp hs_walk(<>, state, _ws), + do: hs_walk(rest, state, c in [?\s, ?\t, ?;, ?&, ?|, ?(]) + + # The word after `<<<`: a hit when it holds `$(` (not `$((`) or a backquote. + defp hs_word(<<>>, _state), do: :none + defp hs_word(<>, state), do: hs_word(rest, state) + defp hs_word(<<"$((", rest::binary>>, state), do: hs_word(hs_skip_arith(rest), state) + + defp hs_word(<<"$(", rest::binary>>, state) when state in [:none, :double] do + case hs_close(rest) do + {inner, _} -> {:hit, inner} + :open -> {:hit, nil} + end + end + + defp hs_word(<>, state) when state in [:none, :double], do: {:hit, nil} + 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(<>, :single), do: hs_word(rest, :none) + + defp hs_word(<>, :none) when c in [?\s, ?\t, ?;, ?&, ?|, ?), ?<, ?>], + do: :none + + defp hs_word(<<_, rest::binary>>, state), do: hs_word(rest, state) + + defp hs_skip_arith(text) do + case hs_close("(" <> text) do + {_inner, <>} -> after_ + {_inner, after_} -> after_ + :open -> "" + end + end + + # 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 +2493,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 13eb8344d..e52532a7f 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 000000000..01077b715 --- /dev/null +++ b/test/research_extensions_re012_test.exs @@ -0,0 +1,297 @@ +# 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.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`"/, nil}, + {"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/}, + {"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 < f)"/}, + {"a pipe", ~S/cat <<<"$(printf x | cmd)"/}, + {"a list", ~S/cat <<<"$(printf x; cmd)"/}, + {"a nested substitution", ~S/cat <<<"$(echo "$(cmd)")"/}, + {"a backquote", ~S/cat <<<"`echo x`"/} + ] do + test "printf or echo with #{label} is :warn" do + assert [%{severity: :warn}] = scan([{"s.sh", script([unquote(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 pwsh or python step is not read" do + for shell <- ["pwsh", "powershell", "python", "cmd", "/usr/bin/python {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 "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 From c2d8c0aa6f8505fb31952b8d99939bd66c0dc738 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 11:54:38 +0000 Subject: [PATCH 3/5] fix(rules): RE012 reads every here-string and substitution on a line; printf is benign only with a %s format From the review of #1232 (Codex and CodeRabbit), each checked against bash 5.2.21 before the fix: - Every here-string on a line, and every substitution in its word, is read; the finding lists them (`detail.producers`) and names the first that can fail. `cat <<<"$(echo safe)"; cat <<<"$(scan)"` and `cat <<<"$(printf '%s' p)$(scan)"` were :info from their first producer. - :info only when every producer is benign. `printf` is benign only with a quoted literal format converting `%s`/`%%` and no option: `printf '%d' x` exits 1 and `printf -Z` exits 2, so they are :warn. - A command substitution inside `$((...))` is read: bash reads a failed `$(count)` there as 0 and the status is lost. - A backquote body is walked as a command, and its text is the producer. - A backslash escapes nothing inside single quotes: `<<<'foo\'$(cmd)` runs cmd. - An empty or blank `shell:` no longer crashes the scan; the script is read. Tests: 58 in test/research_extensions_re012_test.exs (12 new). Mutants of each fix fail them: escape before single quotes, no single-quote clause, arithmetic not scanned, backquote body not walked, first here-string only, first substitution only, any-benign instead of all-benign, empty-shell crash, printf %d accepted. mix test: 3782 tests, 0 failures. RE012 on this tree: 0. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01J4QvDgzT72Tq2HTJmikyNg --- lib/rules/research_extensions.ex | 180 ++++++++++++++---------- test/research_extensions_re012_test.exs | 61 +++++++- 2 files changed, 163 insertions(+), 78 deletions(-) diff --git a/lib/rules/research_extensions.ex b/lib/rules/research_extensions.ex index 8ed37b1e7..abe62babf 100644 --- a/lib/rules/research_extensions.ex +++ b/lib/rules/research_extensions.ex @@ -2199,9 +2199,10 @@ defmodule Hypatia.Rules.ResearchExtensions do @re012_fix "capture, then feed: `out=$(cmd) || ; consumer <<<\"$out\"`" - # A producer that cannot fail here: a lone `printf` or `echo` builtin with - # no redirection, pipe, list or nested substitution (`$var` is allowed). - @re012_benign ~r/\A[[:space:]]*(?:printf|echo)(?:[[:space:]]+(?:[^|;&`$<>()]|\$(?!\())*)?[[:space:]]*\z/ + # A producer that cannot fail here: a lone `echo`, or a `printf` whose format + # is a quoted literal converting only `%s` (and `%%`), with no option, + # redirection, pipe, list or nested substitution (`$var` is allowed). + @re012_benign ~r/\A[[:space:]]*(?:echo|printf[[:space:]]+(?:'(?:[^'%]|%%|%s)*'|"(?:[^"%$`\\]|\\.|%%|%s)*"))(?:[[:space:]]+(?:[^|;&`$<>()]|\$(?!\())*)?[[:space:]]*\z/ # Steps whose shell is not a POSIX-family shell: `<<<` means nothing there. @re012_not_sh ~w(pwsh powershell python cmd) @@ -2236,9 +2237,12 @@ defmodule Hypatia.Rules.ResearchExtensions do 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 `$((…))` is not a command. A here-string inside a substitution - (`x=$(grep -c . <<<"$(cmd)")`) is read too. Each line is read on its own, - with full-line comments ignored. + 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 detected: the word held in a variable; process substitution (`done < <(cmd)`), which loses the status in the same way; a pipe (`cmd | while @@ -2248,9 +2252,11 @@ defmodule Hypatia.Rules.ResearchExtensions do ## Severity `:warn` (medium), whatever `set -e` or `pipefail` say, since neither - reaches the lost status. `:info` when the substitution is a lone `printf` - or `echo` with no redirection, pipe, list or nested substitution: that - builtin does not fail on a here-string's buffer, so nothing is lost. + 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 converting + only `%s` (and `%%`), each with no option, redirection, pipe, list or + nested substitution: neither fails then, so nothing is lost. Any other + `printf` can fail (`printf '%d' x`, an unknown option) and is `:warn`. ## Flag-only @@ -2268,9 +2274,9 @@ defmodule Hypatia.Rules.ResearchExtensions do rel = Path.relative_to(path, repo_path), {:ok, content} <- [File.read(path)], lines = String.split(content, "\n"), - {line, _offset, text, producer} <- here_string_substitution_lines(content), + {line, _offset, text, producers} <- here_string_substitution_lines(content), not shell_line_reviewed?(lines, line, "RE012") do - re012_finding(rel, line, text, producer) + re012_finding(rel, line, text, producers) end end @@ -2279,9 +2285,9 @@ defmodule Hypatia.Rules.ResearchExtensions do rel = Path.relative_to(path, repo_path), bytes = File.read!(path), source = String.split(bytes, "\n"), - {line, text, producer} <- re012_workflow_hits(Workflow.parse(bytes, rel), bytes), + {line, text, producers} <- re012_workflow_hits(Workflow.parse(bytes, rel), bytes), not shell_line_reviewed?(source, line, "RE012") do - re012_finding(rel, line, text, producer) + re012_finding(rel, line, text, producers) end end @@ -2290,33 +2296,39 @@ defmodule Hypatia.Rules.ResearchExtensions do defp re012_workflow_hits({:ok, %Workflow{} = workflow}, _bytes) do for {script, line_of, shell} <- run_scripts(workflow), not re012_not_sh?(shell), - {_line, offset, text, producer} <- here_string_substitution_lines(script) do - {line_of.(offset), text, producer} + {_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, producer} <- here_string_substitution_lines(bytes), - do: {line, text, producer} + for {line, _offset, text, producers} <- here_string_substitution_lines(bytes), + do: {line, text, producers} end defp re012_not_sh?(nil), do: false + # An empty or blank `shell:` names no executable: the script is still read. defp re012_not_sh?(shell) do - shell - |> String.split(~r/[[:space:]]+/, trim: true) - |> List.first() - |> Path.basename() - |> then(&(&1 in @re012_not_sh)) + case String.split(shell, ~r/[[:space:]]+/, trim: true) do + [] -> false + [first | _] -> Path.basename(first) in @re012_not_sh + end end - defp re012_finding(rel, line, text, producer) do - benign? = is_binary(producer) and Regex.match?(@re012_benign, producer) + # 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 `printf`/`echo`, which does not " <> - "fail here, so no status is lost; a plain expansion says the same. Fix: #{@re012_fix}" + "#{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 " <> @@ -2336,6 +2348,7 @@ defmodule Hypatia.Rules.ResearchExtensions do line: line, text: String.trim(text), producer: producer, + producers: producers, strategy: :review, fix: "Flag-only, never applied for you: #{@re012_fix}" } @@ -2344,9 +2357,11 @@ defmodule Hypatia.Rules.ResearchExtensions do @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, producer}`. - `producer` is the text of the first substitution in the here-string's - word, or nil when it does not close on that line (or is a backquote). + 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} = @@ -2357,13 +2372,12 @@ defmodule Hypatia.Rules.ResearchExtensions do line = String.replace_suffix(raw, "\r", "") next = offset + byte_size(raw) + 1 - if Regex.match?(~r/^[[:space:]]*#/, line) do - {hits, next} - else - case hs_walk(line, :none, true) do - {:hit, producer} -> {[{no, offset, line, producer} | hits], next} - :none -> {hits, next} - end + 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) @@ -2372,70 +2386,88 @@ defmodule Hypatia.Rules.ResearchExtensions do # 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. Returns {:hit, producer} at the first here-string fed by a - # command substitution, else :none. - defp hs_walk(<<>>, _state, _ws), do: :none + # comment. Returns the producers of every here-string fed by a command + # substitution, in order; [] when there is none. + defp hs_walk(<<>>, _state, _ws), do: [] defp hs_walk(<>, :single, _ws), do: hs_walk(rest, :none, false) defp hs_walk(<<_, rest::binary>>, :single, _ws), do: hs_walk(rest, :single, false) defp hs_walk(<>, state, _ws), do: hs_walk(rest, state, false) - defp hs_walk(<>, _state, _ws), do: :none + defp hs_walk(<>, _state, _ws), do: [] defp hs_walk(<>, :double, _ws), do: hs_walk(rest, :none, false) defp hs_walk(<>, :none, _ws), do: hs_walk(rest, :double, false) defp hs_walk(<>, :none, _ws), do: hs_walk(rest, :single, false) - defp hs_walk(<>, :none, true), do: :none + defp hs_walk(<>, :none, true), do: [] - defp hs_walk(<<"<<<", rest::binary>>, :none, _ws) do - case hs_word(String.trim_leading(rest), :none) do - {:hit, _} = hit -> hit - :none -> hs_walk(rest, :none, false) - end - end + # 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. + defp hs_walk(<<"<<<", rest::binary>>, :none, _ws), + do: hs_word(String.trim_leading(rest), :none) ++ hs_walk(rest, :none, false) - # A substitution in :none or :double: read inside it as a fresh line, then - # go on after it in the state we were in. - defp hs_walk(<<"$(", rest::binary>>, state, _ws) do - case hs_close(rest) do - {inner, after_} -> - with :none <- hs_walk(inner, :none, true), do: hs_walk(after_, state, false) + # A command substitution or a backquote body, in :none or :double: read its + # body as a fresh line, then go on after it in the state we were in. + defp hs_walk(<<"$(", rest::binary>>, state, _ws), do: hs_walk_body(hs_close(rest), rest, state) - :open -> - hs_walk(rest, :none, true) - end - end + defp hs_walk(<>, state, _ws), + do: hs_walk_body(hs_backquote(rest), rest, state) defp hs_walk(<>, state, _ws), do: hs_walk(rest, state, c in [?\s, ?\t, ?;, ?&, ?|, ?(]) - # The word after `<<<`: a hit when it holds `$(` (not `$((`) or a backquote. - defp hs_word(<<>>, _state), do: :none + defp hs_walk_body({inner, after_}, _rest, state), + do: hs_walk(inner, :none, true) ++ hs_walk(after_, state, false) + + defp hs_walk_body(:open, rest, _state), do: hs_walk(rest, :none, true) + + # 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: hs_word(hs_skip_arith(rest), state) - defp hs_word(<<"$(", rest::binary>>, state) when state in [:none, :double] do - case hs_close(rest) do - {inner, _} -> {:hit, inner} - :open -> {:hit, nil} + 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(<>, state) when state in [:none, :double], do: {:hit, nil} + 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(<>, :single), do: hs_word(rest, :none) defp hs_word(<>, :none) when c in [?\s, ?\t, ?;, ?&, ?|, ?), ?<, ?>], - do: :none + do: [] defp hs_word(<<_, rest::binary>>, state), do: hs_word(rest, state) - defp hs_skip_arith(text) do - case hs_close("(" <> text) do - {_inner, <>} -> after_ - {_inner, after_} -> after_ - :open -> "" - end - end + 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. diff --git a/test/research_extensions_re012_test.exs b/test/research_extensions_re012_test.exs index 01077b715..4606ff6e4 100644 --- a/test/research_extensions_re012_test.exs +++ b/test/research_extensions_re012_test.exs @@ -38,7 +38,7 @@ defmodule Hypatia.Rules.ResearchExtensionsRE012Test do defp scan(files), do: files |> repo() |> ResearchExtensions.re012_here_string_substitution() defp lines(text), - do: text |> ResearchExtensions.here_string_substitution_lines() |> Enum.map(&elem(&1, 3)) + do: text |> ResearchExtensions.here_string_substitution_lines() |> Enum.flat_map(&elem(&1, 3)) # ─── The claim, checked against bash ──────────────────────────────── @@ -79,19 +79,32 @@ defmodule Hypatia.Rules.ResearchExtensionsRE012Test do {"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`"/, nil}, + {"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 << Date: Tue, 24 Nov 2026 10:40:37 +0000 Subject: [PATCH 4/5] fix(deps): port #1225, url 2.5.9 for RUSTSEC-2026-0592 Security's cargo audit and cargo deny fail on main and here: url 2.5.8 carries RUSTSEC-2026-0592. Same Cargo.lock as #1225 and as f8332b4 on #1195 (cargo update -p url --precise 2.5.9); a no-op once #1225 lands. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01J4QvDgzT72Tq2HTJmikyNg (cherry picked from commit 5c6cb7b5505e94aac0831bb17cb130556c33b31f) --- Cargo.lock | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 30d41a9fb..d8c0f251a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1240,9 +1240,9 @@ checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b" [[package]] name = "form_urlencoded" -version = "1.2.2" +version = "1.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e" dependencies = [ "percent-encoding", ] @@ -4382,9 +4382,9 @@ checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" [[package]] name = "url" -version = "2.5.8" +version = "2.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a" dependencies = [ "form_urlencoded", "idna", From 23a447b0577aac5ce4867617935d9766d8f4d9f7 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 12:07:09 +0000 Subject: [PATCH 5/5] fix(rules): RE012 skips command-less here-strings and non-shell steps; benign needs literal arguments MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Second review round on #1232, each checked on bash 5.2.21: - A command with no command name (`x=1 <<<"$(cmd)"`, `<<<"$(cmd)"` alone) keeps the status of its last command substitution, and bash performs the redirections after the assignments (`x=$(true) <<<"$(exit 3)"` exits 3), so nothing is lost: not reported. The walker now tracks the current simple command's text; leading reserved words, assignments and redirections are not a command name. The end of a compound command (`done`, `fi`, `}`, `)`) is: `(cat) <<<"$(exit 3)"` and `{ cat; } <<<…` exit 0. (Codex) - `printf '-Z'` (quoted) exits 2: a format starting with `-` is no longer benign. (CodeRabbit) - An argument expansion can fail before echo/printf runs (`echo "${v:?}"`, an unset `$v` under `set -u`): benign now needs literal arguments, with no `$`. (Codex) - A workflow step is read only in bash, sh, dash, zsh or ksh (path and `.exe` ignored), or with no or a blank `shell:`; `python3 {0}`, `node {0}`, `ruby {0}`, `pwsh.exe` are not lexed as shell. (Codex) Tests: 71 in test/research_extensions_re012_test.exs (13 new). Mutants of each change fail them: no command-less check, no separator reset, `)` resetting the command, a deny-list of interpreters, no `.exe` strip, printf '-…' accepted, `$` accepted in arguments. mix test: 3795 tests, 0 failures. RE012 on this tree: 0. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01J4QvDgzT72Tq2HTJmikyNg --- lib/rules/research_extensions.ex | 141 +++++++++++++++++------- test/research_extensions_re012_test.exs | 65 +++++++++-- 2 files changed, 157 insertions(+), 49 deletions(-) diff --git a/lib/rules/research_extensions.ex b/lib/rules/research_extensions.ex index abe62babf..497821330 100644 --- a/lib/rules/research_extensions.ex +++ b/lib/rules/research_extensions.ex @@ -2200,12 +2200,18 @@ defmodule Hypatia.Rules.ResearchExtensions do @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 converting only `%s` (and `%%`), with no option, - # redirection, pipe, list or nested substitution (`$var` is allowed). - @re012_benign ~r/\A[[:space:]]*(?:echo|printf[[:space:]]+(?:'(?:[^'%]|%%|%s)*'|"(?:[^"%$`\\]|\\.|%%|%s)*"))(?:[[:space:]]+(?:[^|;&`$<>()]|\$(?!\())*)?[[:space:]]*\z/ + # 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/ - # Steps whose shell is not a POSIX-family shell: `<<<` means nothing there. - @re012_not_sh ~w(pwsh powershell python cmd) + # 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)"`, @@ -2228,9 +2234,11 @@ defmodule Hypatia.Rules.ResearchExtensions do 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 whose shell is `pwsh`, `powershell`, - `python` or `cmd` is not read. A workflow the reader refuses is scanned as - plain lines. + 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 @@ -2244,6 +2252,12 @@ defmodule Hypatia.Rules.ResearchExtensions do 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 @@ -2253,10 +2267,12 @@ defmodule Hypatia.Rules.ResearchExtensions do `: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 converting - only `%s` (and `%%`), each with no option, redirection, pipe, list or - nested substitution: neither fails then, so nothing is lost. Any other - `printf` can fail (`printf '%d' x`, an unknown option) and is `:warn`. + 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 @@ -2295,7 +2311,7 @@ defmodule Hypatia.Rules.ResearchExtensions do defp re012_workflow_hits({:ok, %Workflow{} = workflow}, _bytes) do for {script, line_of, shell} <- run_scripts(workflow), - not re012_not_sh?(shell), + re012_shell?(shell), {_line, offset, text, producers} <- here_string_substitution_lines(script) do {line_of.(offset), text, producers} end @@ -2306,13 +2322,21 @@ defmodule Hypatia.Rules.ResearchExtensions do do: {line, text, producers} end - defp re012_not_sh?(nil), do: false + # 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 - # An empty or blank `shell:` names no executable: the script is still read. - defp re012_not_sh?(shell) do + defp re012_shell?(shell) do case String.split(shell, ~r/[[:space:]]+/, trim: true) do - [] -> false - [first | _] -> Path.basename(first) in @re012_not_sh + [] -> + true + + [first | _] -> + first + |> Path.basename() + |> String.replace_suffix(".exe", "") + |> then(&(&1 in @re012_shells)) end end @@ -2373,7 +2397,7 @@ defmodule Hypatia.Rules.ResearchExtensions do next = offset + byte_size(raw) + 1 producers = - if Regex.match?(~r/^[[:space:]]*#/, line), do: [], else: hs_walk(line, :none, true) + if Regex.match?(~r/^[[:space:]]*#/, line), do: [], else: hs_walk(line, :none, true, "") case producers do [] -> {hits, next} @@ -2386,37 +2410,70 @@ defmodule Hypatia.Rules.ResearchExtensions do # 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. Returns the producers of every here-string fed by a command - # substitution, in order; [] when there is none. - defp hs_walk(<<>>, _state, _ws), do: [] - defp hs_walk(<>, :single, _ws), do: hs_walk(rest, :none, false) - defp hs_walk(<<_, rest::binary>>, :single, _ws), do: hs_walk(rest, :single, false) - defp hs_walk(<>, state, _ws), do: hs_walk(rest, state, false) - defp hs_walk(<>, _state, _ws), do: [] - defp hs_walk(<>, :double, _ws), do: hs_walk(rest, :none, false) - defp hs_walk(<>, :none, _ws), do: hs_walk(rest, :double, false) - defp hs_walk(<>, :none, _ws), do: hs_walk(rest, :single, false) - defp hs_walk(<>, :none, true), do: [] + # 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. - defp hs_walk(<<"<<<", rest::binary>>, :none, _ws), - do: hs_word(String.trim_leading(rest), :none) ++ hs_walk(rest, :none, false) + # 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 line, then go on after it in the state we were in. - defp hs_walk(<<"$(", rest::binary>>, state, _ws), do: hs_walk_body(hs_close(rest), rest, state) + # 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), - do: hs_walk_body(hs_backquote(rest), rest, state) + defp hs_walk(<>, state, _ws, seg), + do: hs_walk(rest, state, c in [?\s, ?\t], seg <> <>) - defp hs_walk(<>, state, _ws), - do: hs_walk(rest, state, c in [?\s, ?\t, ?;, ?&, ?|, ?(]) + 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({inner, after_}, _rest, state), - do: hs_walk(inner, :none, true) ++ hs_walk(after_, state, false) + defp hs_walk_body(:open, rest, _state, _seg, _open, _close), do: hs_walk(rest, :none, true, "") - defp hs_walk_body(:open, rest, _state), 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 diff --git a/test/research_extensions_re012_test.exs b/test/research_extensions_re012_test.exs index 4606ff6e4..58fdd2160 100644 --- a/test/research_extensions_re012_test.exs +++ b/test/research_extensions_re012_test.exs @@ -82,6 +82,12 @@ defmodule Hypatia.Rules.ResearchExtensionsRE012Test do {"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 <<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)) @@ -144,10 +156,10 @@ defmodule Hypatia.Rules.ResearchExtensionsRE012Test do assert [%{severity: :warn}] = scan([{"s.sh", script([~S/grep -q x <<<"$(cmd)"/])}]) end - test "a lone printf or echo cannot fail here: :info" do + test "a lone printf or echo of literal words cannot fail here: :info" do for line <- [ - ~S/grep -qx -- "$j" <<<"$(printf '%s\n' "${all[@]}")"/, - ~S/cat <<<"$(echo "$a" $b)"/ + ~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" @@ -172,7 +184,12 @@ defmodule Hypatia.Rules.ResearchExtensionsRE012Test do {"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)"/} + {"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)])}]) @@ -217,8 +234,18 @@ defmodule Hypatia.Rules.ResearchExtensionsRE012Test do assert [%{file: ".github/workflows/w.yml", detail: %{line: 9}}] = workflow(wf) end - test "a pwsh or python step is not read" do - for shell <- ["pwsh", "powershell", "python", "cmd", "/usr/bin/python {0}"] do + 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: @@ -233,6 +260,30 @@ defmodule Hypatia.Rules.ResearchExtensionsRE012Test do 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 = """