diff --git a/.github/workflows/scorecard.yml b/.github/workflows/scorecard.yml index 97ae605..8daeef6 100644 --- a/.github/workflows/scorecard.yml +++ b/.github/workflows/scorecard.yml @@ -19,6 +19,17 @@ # `id-token: write` and the Scorecard API's workflow restrictions, which it checks against the # producing workflow; a repository that wants the badge runs ossf/scorecard-action in its own file # (the action's README "Workflow Restrictions"). The job keeps to the approved action list anyway. +# +# THIS KIT'S OWN RELEASE CHANNEL IS NOT AN UNPINNED THIRD-PARTY ACTION (v1.97.0). Scorecard's +# Pinned-Dependencies check calls every `uses: owner/repo@tag` third-party, so each +# `mjdevaccount/ci-kit@v1` step a caller adds opened a medium alert -- and `v1` is a tag that moves +# BY DESIGN (a fix ships by moving it, docs/versioning.md). Dismissing those by hand did not hold: +# the alert re-opened as a new one whenever the check's score text changed (one caller line was +# dismissed twice and opened a third time, 2026-12-02..03). So the `own-channel` step drops, before +# the upload, exactly the Pinned-Dependencies results whose flagged ref is `@v` or +# `/@v`; code scanning then closes their alerts as fixed. Every other result +# stays, an own ref at any other ref (`@main`, `@v1.2.3`) included. What was dropped is listed in +# the job summary, and the 5-day artifact keeps the unfiltered SARIF next to the uploaded one. name: scorecard on: @@ -28,6 +39,12 @@ on: description: the SARIF file name (also the artifact's) type: string default: scorecard.sarif + own-channel: + description: >- + owner/repo whose major-tag refs (`@v1`) are a release channel the caller follows on + purpose; their Pinned-Dependencies results are dropped before the upload ('' = keep all) + type: string + default: mjdevaccount/ci-kit permissions: contents: read @@ -50,13 +67,52 @@ jobs: results_file: ${{ inputs.results-file }} results_format: sarif publish_results: false + # jq, not a ci_kit tool: the reusable runs at the same `v1` as the action, and a tool new in + # this release would be unknown to the action for the window before `v1` moves + # (tests/test_scorecard_own_channel_must_fire.py runs THIS script against real-shape SARIF) + - name: drop the own release channel's Pinned-Dependencies results + id: own-channel + env: + RESULTS: ${{ inputs.results-file }} + OWN: ${{ inputs.own-channel }} + run: | + set -euo pipefail + # shellcheck disable=SC2016 # the jq program's $own is a jq variable, not a shell one + defs=' + def own_major($own): + ([capture("^(?[^@[:space:]]+)@(?[^[:space:]]+)$")] | .[0]) as $m + | $m != null and ($m.tag | test("^v[0-9]+$")) + and ($m.ref == $own or ($m.ref | startswith($own + "/"))); + def dropped($own): + .ruleId == "PinnedDependenciesID" and $own != "" + and ((.locations // []) | length > 0) + and all(.locations[]; (.physicalLocation.region.snippet.text // "") | own_major($own)); + ' + out="${RESULTS%.sarif}.uploaded.sarif" + before=$(jq '[.runs[].results[]] | length' "$RESULTS") + jq -r --arg own "$OWN" "$defs"'.runs[].results[] | select(dropped($own)) + | .locations[0].physicalLocation | "\(.artifactLocation.uri):\(.region.startLine) \(.region.snippet.text)"' \ + "$RESULTS" > own-channel-dropped.txt + jq --arg own "$OWN" "$defs"'.runs |= map(.results |= map(select(dropped($own) | not)))' "$RESULTS" > "$out" + after=$(jq '[.runs[].results[]] | length' "$out") + dropped=$(wc -l < own-channel-dropped.txt) + if [ $((before - after)) -ne "$dropped" ]; then + echo "::error::own-channel filter removed $((before - after)) results but listed $dropped"; exit 2 + fi + { + echo "### Scorecard: $before results, $dropped dropped as \`${OWN:-}\` release-channel refs, $after uploaded" + sed 's/^/- /' own-channel-dropped.txt + } >> "$GITHUB_STEP_SUMMARY" + echo "sarif=$out" >> "$GITHUB_OUTPUT" - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 with: name: scorecard-sarif - path: ${{ inputs.results-file }} + path: | + ${{ inputs.results-file }} + ${{ steps.own-channel.outputs.sarif }} retention-days: 5 - uses: github/codeql-action/upload-sarif@915412ff23e8b7659517e607487dbeae018f2934 # v4.39.5 with: - sarif_file: ${{ inputs.results-file }} + sarif_file: ${{ steps.own-channel.outputs.sarif }} # ignored in practice: Scorecard's SARIF sets runAutomationDetails (supply-chain/*), which wins category: scorecard diff --git a/docs/gates/supply-chain.md b/docs/gates/supply-chain.md index ed3a194..ed8373e 100644 --- a/docs/gates/supply-chain.md +++ b/docs/gates/supply-chain.md @@ -171,7 +171,9 @@ Two thin reusables around first-party actions, pinned by SHA [`repo-settings.yml`](../repo-settings.md) and read by the preset's `vulnerabilityAlerts` below. - **`scorecard.yml`**: `ossf/scorecard-action` on the default branch, its SARIF uploaded to code scanning under the categories its SARIF names (`supply-chain/online-scm`, `/local`, - `/branch-protection`). A failing check is an open alert, counted with CodeQL's. + `/branch-protection`). A failing check is an open alert, counted with CodeQL's. Pinned-Dependencies + results for the kit's own major-tag channel (`ci-kit@v1`, followed on purpose) are dropped + before the upload, and listed in the job summary. Both need a public repository (dependency review and code scanning are GHAS features on private ones). diff --git a/docs/reusable-workflows.md b/docs/reusable-workflows.md index ed1948a..a502e01 100644 --- a/docs/reusable-workflows.md +++ b/docs/reusable-workflows.md @@ -690,6 +690,16 @@ The analyses land under the categories Scorecard's SARIF names for itself the upload step's `category: scorecard`: a SARIF's own `runAutomationDetails` wins. Filter alerts by the tool name (`Scorecard`), never by a category. +**The kit's own release channel is not an unpinned third-party action.** Scorecard's +Pinned-Dependencies check calls every `uses: owner/repo@tag` third-party, so each +`mjdevaccount/ci-kit@v1` step (or `.../ci-kit/.github/workflows/.yml@v1` call) opened a medium +alert, though `v1` moves by design ([versioning.md](versioning.md)), and a hand dismissal did not hold: the +alert re-opened as a new one when the score text changed. Before the upload, the `own-channel` step +drops exactly the Pinned-Dependencies results whose flagged ref is `@v` or +`/@v`; code scanning closes their alerts as fixed. Every other result stays, +an own ref at `@main` or `@v1.2.3` included. The job summary lists what was dropped and the +artifact keeps the unfiltered SARIF beside the uploaded one. `own-channel: ''` keeps everything. + ```yaml on: push: { branches: [main] } @@ -705,3 +715,4 @@ jobs: | input | type | default | what | |---|---|---|---| | `results-file` | string | `scorecard.sarif` | the SARIF file name (also the artifact's) | +| `own-channel` | string | `mjdevaccount/ci-kit` | owner/repo whose major-tag refs are dropped from Pinned-Dependencies before the upload (`''` = keep all) | diff --git a/pyproject.toml b/pyproject.toml index 4ebfab5..3b2cdab 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "ci-kit" -version = "1.96.0" +version = "1.97.0" description = "Reusable CI gates: the doc-reference gate, the secret-argv lint, the hidden-Unicode gate, the consumer-word purity gate, the armed-PR updater and its heal ladder, the merge train, the pin-drift check, the agent-manual lint, the guard self-proof gate, the hand .env-read ratchet, the unread-config-field ratchet, the line-cap, function-clone, test-standin, untested-module, guards-have-tests, HTTP-client and SQL-placement ratchets, the blind-parse, quarantine, cog, image-PR-filter, migration-number per-stage dependency-closure and per-stage reachable-import (`lock` extra) gates, the duplicate-code gate (jscpd behind a shrink-only baseline), the OpenAPI breaking-change gate (oasdiff), the skip-green CI aggregate gate and the setup-uv pin gate (`workflow` extra), the pre-merge model review gate (`review` extra), the self-hosted runner capacity kit (`runners` extra: schema, budgets, render, the jq admission rule and its Python twin), the GitHub App audit (`apps` extra: a declared App manifest held to live) and the pr-token record reader, the lint-gate kit (ratchet, discover, site_lint), and parsed-SQL gates and the code-edge reader behind the `sql` extra. Every gate exits 0 clean / 1 findings / 2 could-not-look." readme = "README.md" license = "MIT" diff --git a/tests/test_scorecard_own_channel_must_fire.py b/tests/test_scorecard_own_channel_must_fire.py new file mode 100644 index 0000000..1113965 --- /dev/null +++ b/tests/test_scorecard_own_channel_must_fire.py @@ -0,0 +1,156 @@ +"""scorecard.yml's `own-channel` step: the jq filter that drops Pinned-Dependencies results for the +kit's own release channel (`/ci-kit@v1`, `/ci-kit/.github/workflows/x.yml@v1`) before the +SARIF upload, so code scanning stops opening an alert for every caller step that follows `v1` on +purpose (the header of .github/workflows/scorecard.yml says why dismissing them did not hold). + +The test runs the workflow's OWN `run:` script under bash with the step's env, on SARIF in the shape +Scorecard writes (three runs, one location per result, the flagged ref in `region.snippet.text`). +A filter only ever seen dropping might be dropping everything: each direction is proven, and the +look-alikes (another repo with the same prefix, a non-major tag, another rule) must stay.""" + +from __future__ import annotations + +import json +import os +import pathlib +import shutil +import subprocess + +import pytest +import yaml +from _supervisor_sh import bash_path + +ROOT = pathlib.Path(__file__).resolve().parent.parent +OWN = "example-owner/ci-kit" + +pytestmark = pytest.mark.skipif( + shutil.which("jq") is None and not os.environ.get("CI"), + reason="jq not on PATH (workstation; in CI a missing jq FAILS, it does not skip)", +) + + +def _step() -> dict: + wf = yaml.safe_load((ROOT / ".github/workflows/scorecard.yml").read_text(encoding="utf-8")) + steps = [s for s in wf["jobs"]["analysis"]["steps"] if s.get("id") == "own-channel"] + assert len(steps) == 1, "scorecard.yml has no single `own-channel` step: the filter is gone" + return steps[0] + + +def _result(rule: str, snippet: str | None, uri: str = ".github/workflows/ci.yml", line: int = 7) -> dict: + region: dict = {"startLine": line, "endLine": line} + if snippet is not None: + region["snippet"] = {"text": snippet} + return { + "ruleId": rule, + "message": {"text": "score is 5: third-party GitHubAction not pinned by hash"}, + "locations": [{"physicalLocation": {"region": region, "artifactLocation": {"uri": uri}}}], + } + + +def _sarif(local: list[dict]) -> dict: + run = lambda cat, results: {"automationDetails": {"id": f"supply-chain/{cat}/x"}, "tool": {}, "results": results} # noqa: E731 + return { + "version": "2.1.0", + "runs": [ + run("branch-protection", [_result("BranchProtectionID", None)]), + run("local", local), + run("online-scm", [_result("CodeReviewID", None)]), + ], + } + + +DROP = [ + f"{OWN}@v1", + f"{OWN}/.github/workflows/scorecard.yml@v1", + f"{OWN}/.github/workflows/dup-code.yml@v12", +] +KEEP_PINNED = [ + "actions/checkout@v4", # third-party, unpinned: the alert the check exists for + f"{OWN}@main", # own repo, a moving BRANCH: not the release channel + f"{OWN}@v1.2.3", # own repo, a full tag: not the major channel + f"{OWN}-evil@v1", # a look-alike repository sharing the prefix + f"{OWN}x/thing.yml@v1", + f"other/{OWN}@v1", + f"{OWN}@v1 trailing", + "", +] + + +def _run(tmp: pathlib.Path, sarif: dict | str, own: str = OWN) -> tuple[subprocess.CompletedProcess, pathlib.Path]: + step = _step() + src = tmp / "scorecard.sarif" + src.write_text(sarif if isinstance(sarif, str) else json.dumps(sarif), encoding="utf-8") + out, summary = tmp / "out.txt", tmp / "summary.md" + out.touch() + summary.touch() + env = {**os.environ, "RESULTS": "scorecard.sarif", "OWN": own, "GITHUB_OUTPUT": out.name, "GITHUB_STEP_SUMMARY": summary.name} + proc = subprocess.run([bash_path(), "-c", step["run"]], cwd=tmp, env=env, capture_output=True, text=True) + return proc, tmp + + +def _uploaded(tmp: pathlib.Path) -> list[tuple[str, str]]: + line = (tmp / "out.txt").read_text(encoding="utf-8").strip() + assert line.startswith("sarif="), f"no sarif output: {line!r}" + doc = json.loads((tmp / line.removeprefix("sarif=")).read_text(encoding="utf-8")) + assert len(doc["runs"]) == 3, "a run vanished: code scanning would read a missing category as no analysis" + return [ + (r["ruleId"], r["locations"][0]["physicalLocation"]["region"].get("snippet", {}).get("text", "")) + for run in doc["runs"] + for r in run["results"] + ] + + +def test_drops_exactly_the_own_major_channel(tmp_path: pathlib.Path) -> None: + local = [_result("PinnedDependenciesID", s, line=i) for i, s in enumerate(DROP + KEEP_PINNED)] + local.append(_result("PinnedDependenciesID", None, line=99)) # no snippet: cannot be judged own, stays + local.append(_result("SASTID", f"{OWN}@v1")) # another rule is never touched + proc, tmp = _run(tmp_path, _sarif(local)) + assert proc.returncode == 0, proc.stderr + kept = _uploaded(tmp) + assert not [s for rule, s in kept if rule == "PinnedDependenciesID" and s in DROP], kept + pinned = [s for rule, s in kept if rule == "PinnedDependenciesID"] + assert pinned == KEEP_PINNED + [""], pinned + assert ("SASTID", f"{OWN}@v1") in kept + assert {r for r, _ in kept} >= {"BranchProtectionID", "CodeReviewID"} + summary = (tmp / "summary.md").read_text(encoding="utf-8") + assert f"{len(DROP)} dropped" in summary + for s in DROP: + assert s in summary, f"a dropped ref is not named in the job summary: {s}" + + +def test_empty_channel_keeps_everything(tmp_path: pathlib.Path) -> None: + local = [_result("PinnedDependenciesID", s) for s in DROP] + proc, tmp = _run(tmp_path, _sarif(local), own="") + assert proc.returncode == 0, proc.stderr + assert [s for r, s in _uploaded(tmp) if r == "PinnedDependenciesID"] == DROP + + +def test_a_result_with_any_foreign_location_stays(tmp_path: pathlib.Path) -> None: + mixed = _result("PinnedDependenciesID", f"{OWN}@v1") + mixed["locations"] += _result("PinnedDependenciesID", "actions/checkout@v4")["locations"] + proc, tmp = _run(tmp_path, _sarif([mixed])) + assert proc.returncode == 0, proc.stderr + assert [r for r, _ in _uploaded(tmp)].count("PinnedDependenciesID") == 1 + + +@pytest.mark.parametrize("bad", ["not json", json.dumps({"version": "2.1.0"})]) +def test_unreadable_sarif_fails_the_step(tmp_path: pathlib.Path, bad: str) -> None: + proc, tmp = _run(tmp_path, bad) + assert proc.returncode != 0, "an unreadable SARIF passed: the upload would get nothing, silently" + assert (tmp / "out.txt").read_text(encoding="utf-8") == "", "a failed filter still named a file to upload" + + +def test_the_workflow_wires_the_filter_into_the_upload() -> None: + """The script can pass while the workflow bypasses it: the upload must read the step's output, + the step its env from the inputs, and the default channel must be the kit's own repository.""" + wf = yaml.safe_load((ROOT / ".github/workflows/scorecard.yml").read_text(encoding="utf-8")) + # PyYAML reads the bare `on:` key as True + inputs = (wf.get("on") or wf[True])["workflow_call"]["inputs"] + assert inputs["own-channel"]["default"] == "mjdevaccount/ci-kit" + assert _step()["env"] == {"RESULTS": "${{ inputs.results-file }}", "OWN": "${{ inputs.own-channel }}"} + steps = wf["jobs"]["analysis"]["steps"] + names = [str(s.get("uses", s.get("id", ""))) for s in steps] + upload = [s for s in steps if str(s.get("uses", "")).startswith("github/codeql-action/upload-sarif@")] + assert len(upload) == 1, names + assert upload[0]["with"]["sarif_file"] == "${{ steps.own-channel.outputs.sarif }}", "the unfiltered SARIF is uploaded" + assert steps.index(_step()) < steps.index(upload[0]), "the filter runs after the upload" diff --git a/uv.lock b/uv.lock index bc81898..2909aa8 100644 --- a/uv.lock +++ b/uv.lock @@ -158,7 +158,7 @@ wheels = [ [[package]] name = "ci-kit" -version = "1.96.0" +version = "1.97.0" source = { editable = "." } [package.optional-dependencies]