From b75781ced7061b3218278609ea7071c846114c1f Mon Sep 17 00:00:00 2001 From: aldbr Date: Thu, 3 Dec 2026 11:48:28 +0100 Subject: [PATCH] ci: check the rulesets for drift every week Nothing applies the rulesets automatically, so GitHub can drift from the templates: a forgotten `apply`, or a change made by hand. A weekly workflow runs `scripts/rulesets.py diff` and keeps a "Configuration drift" issue open while something differs. It uses the workflow token only, so the diff now skips the bypass lists that the token cannot read. The unit tests of the scripts now run in pre-commit. Assisted-by: Claude:claude-fable-5-2 --- .github/workflows/drift.yml | 74 +++++++++++++++++++++++++++++++++++++ .pre-commit-config.yaml | 9 +++++ README.md | 8 +++- scripts/rulesets.py | 25 +++++++++---- scripts/test_rulesets.py | 5 +++ 5 files changed, 113 insertions(+), 8 deletions(-) create mode 100644 .github/workflows/drift.yml diff --git a/.github/workflows/drift.yml b/.github/workflows/drift.yml new file mode 100644 index 0000000..29fd65d --- /dev/null +++ b/.github/workflows/drift.yml @@ -0,0 +1,74 @@ +name: Configuration drift + +# Compares the rulesets on GitHub with the files of this repository, once a week. +# When they differ, it opens the "Configuration drift" issue, or updates it; +# it closes the issue once they agree again. +# +# It runs with the workflow token, so it only sees what is public: the rulesets +# without their bypass lists. An admin runs `scripts/rulesets.py diff` to compare +# those too. + +on: + schedule: + - cron: "0 6 * * 1" + workflow_dispatch: + +concurrency: + group: ${{ github.workflow }} + +permissions: {} + +jobs: + drift: + name: drift + if: github.repository == 'DIRACGrid/.github' + runs-on: ubuntu-latest + permissions: + contents: read + issues: write + env: + GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} + TITLE: Configuration drift + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 + with: + python-version: 3.x + - name: Compare with GitHub + id: compare + run: | + drift=false + section() { + printf '\n### `%s`\n\n```\n' "$*" + # The scripts exit with 1 when something differs, or cannot be read. + output=$("$@" 2>&1) || drift=true + grep -v ': ok$' <<< "$output" || true + printf '```\n' + } + { + echo "The rulesets on GitHub and the files of this repository differ." + echo "Either apply the files (see the README), or change them in a pull request." + section scripts/rulesets.py diff + printf '\nFrom the [weekly check](%s). ' "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID" + echo "It does not see the bypass lists: an admin runs \`scripts/rulesets.py diff\` for those." + } > report.md + cat report.md >> "$GITHUB_STEP_SUMMARY" + echo "drift=$drift" >> "$GITHUB_OUTPUT" + - name: Open, update or close the issue + env: + DRIFT: ${{ steps.compare.outputs.drift }} + run: | + issue=$(gh issue list --state open --limit 200 --json number,title \ + --jq "[.[] | select(.title == \"$TITLE\")][0].number // empty") + if [ "$DRIFT" = true ]; then + if [ -n "$issue" ]; then + gh issue edit "$issue" --body-file report.md + else + gh issue create --title "$TITLE" --body-file report.md + fi + elif [ -n "$issue" ]; then + gh issue close "$issue" --comment "The rulesets and the files agree again." + fi diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 58bde0a..17756d3 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -19,3 +19,12 @@ repos: - id: zizmor # Overrides the hook's own args, so keep its --no-progress (zizmor#582). args: ["--no-progress", "--no-online-audits"] + + - repo: local + hooks: + - id: scripts-tests + name: Test the scripts + entry: python -m unittest discover --start-directory scripts + language: python + pass_filenames: false + files: ^(scripts/|rulesets/) diff --git a/README.md b/README.md index 5083126..ccf51d9 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ Organization-level GitHub configuration for [DIRACGrid](https://github.com/DIRAC | `renovate-config.json` | The shared [Renovate](https://docs.renovatebot.com/) preset extended by the DIRACGrid repositories: digest-pinned GitHub Actions, grouped updates, a 7-day release-age cooldown, lock file maintenance, and no CI interpreter bumps | | `rulesets/`, `scripts/rulesets.py` | The branch and tag rulesets every repository should have, and the script that compares them with GitHub or applies them | | `profile/` | The organization profile shown on https://github.com/DIRACGrid | -| `.github/workflows/` | Workflows of this repository: pre-commit, Renovate config validation, and PR review reminders for the diracx repositories | +| `.github/workflows/` | Workflows of this repository: pre-commit, Renovate config validation, PR review reminders for the diracx repositories, and the weekly [drift check](#drift-check) | | `CONTRIBUTING.md`, `SECURITY.md` | Default community health files inherited by repositories without their own | ## Adopting the Renovate preset @@ -50,6 +50,12 @@ scripts/rulesets.py apply --repo diracx --yes # create or update the rulesets To change the rules, edit the template or `repos.toml` in a pull request, then run `apply` once it is merged. Organization-level rulesets would replace this script, but they need a paid GitHub plan. +## Drift check + +Nothing applies the rulesets automatically, so GitHub can drift from them: an `apply` that was forgotten after a merge, or a change made by hand on GitHub. The `Configuration drift` workflow compares the two every Monday. When they differ it opens an issue named `Configuration drift`, or updates it, and it closes the issue once they agree again. + +The workflow has no secret: it uses its own token, which only sees what is public. It does not see the bypass lists of the rulesets: an admin of the repositories runs `scripts/rulesets.py diff` to compare those too. + ## More information - [CONTRIBUTING.md](CONTRIBUTING.md) — how to contribute to DIRACGrid projects diff --git a/scripts/rulesets.py b/scripts/rulesets.py index 8600157..b7397f9 100755 --- a/scripts/rulesets.py +++ b/scripts/rulesets.py @@ -5,7 +5,9 @@ scripts/rulesets.py diff --repo diracx scripts/rulesets.py apply --repo diracx --yes [--prune] -Needs the ``gh`` CLI, logged in as an admin of the repositories. +Needs the ``gh`` CLI. ``apply`` needs an admin of the repository. ``diff`` works +for anyone, but only people with write access see the bypass lists: without it +they are not compared. """ from __future__ import annotations @@ -18,6 +20,8 @@ from pathlib import Path RULESETS_DIR = Path(__file__).resolve().parent.parent / "rulesets" +# Repositories whose bypass lists the token could not read. +HIDDEN_BYPASS: set[str] = set() def gh(*args: str, body: dict | None = None): @@ -128,7 +132,8 @@ def compare(live: dict, wanted: dict) -> list[str]: diffs = [ f"{key}: live {live[key]} != template {wanted[key]}" for key in ("enforcement", "target", "include", "exclude", "bypass_actors") - if live[key] != wanted[key] + # None: the bypass list could not be read, so it is not compared. + if live[key] != wanted[key] and live[key] is not None ] for rule in sorted(set(live["rules"]) | set(wanted["rules"])): if rule not in wanted["rules"]: @@ -158,12 +163,13 @@ def diff_repo(org: str, repo: str, params: dict, actors: dict) -> list[str]: if name not in live: lines.append(f"{name}: missing") continue + got = normalize(live[name], default_branch) + # GitHub only gives the bypass list to people with write access. + if "bypass_actors" not in live[name]: + got["bypass_actors"] = None + HIDDEN_BYPASS.add(repo) lines += [ - f"{name}: {d}" - for d in compare( - normalize(live[name], default_branch), - normalize(ruleset, default_branch), - ) + f"{name}: {d}" for d in compare(got, normalize(ruleset, default_branch)) ] lines += [ f"{name}: not in template ({live[name]['enforcement']})" @@ -228,6 +234,11 @@ def main() -> int: print(f"{repo}: ok" if not lines else f"{repo}:") for line in lines: print(f" {line}") + if HIDDEN_BYPASS: + print( + f"Bypass lists not compared in {len(HIDDEN_BYPASS)} repositories: " + "only people with write access can read them." + ) return 1 if drift else 0 diff --git a/scripts/test_rulesets.py b/scripts/test_rulesets.py index dc8b339..1d910d5 100644 --- a/scripts/test_rulesets.py +++ b/scripts/test_rulesets.py @@ -121,6 +121,11 @@ def test_drift_is_reported(self): self.assertTrue(any(d.startswith("bypass_actors") for d in diffs)) self.assertTrue(any("missing" in d for d in diffs)) + def test_unreadable_bypass_list_is_not_compared(self): + wanted = render({}, "main")["fork-only"] + live = norm({**wanted, "bypass_actors": []}) | {"bypass_actors": None} + self.assertEqual(compare(live, norm(wanted)), []) + if __name__ == "__main__": unittest.main()