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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
74 changes: 74 additions & 0 deletions .github/workflows/drift.yml
Original file line number Diff line number Diff line change
@@ -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
9 changes: 9 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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/)
8 changes: 7 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
25 changes: 18 additions & 7 deletions scripts/rulesets.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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):
Expand Down Expand Up @@ -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"]:
Expand Down Expand Up @@ -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']})"
Expand Down Expand Up @@ -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


Expand Down
5 changes: 5 additions & 0 deletions scripts/test_rulesets.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()