ci: declare branch protection as rulesets and audit effective drift (#298) - #344
parthrohit22 wants to merge 3 commits into
Conversation
…WASP#298) Declare dev and main protection as versioned GitHub rulesets and add a scheduled audit that compares the rules GitHub actually enforces with them, fails on drift, and retains a JSON evidence artifact. - dev: 1 approval, main: 2; code owner review, last-push approval, stale review dismissal, conversation resolution, strict required checks (CI Summary, DCO sign-off, dependency-review, CodeQL), no bypass actors - tests fail if a declared ruleset is weakened or names a check no job runs - run CI and CodeQL on pushes to dev and main for post-merge assurance - stop pushing statistics straight to protected dev; open a PR instead - document admin apply steps, evidence, and the emergency procedure Signed-off-by: parthrohit22 <parthrohit60@gmail.com>
Semgrep flagged the dynamic urllib call. Requests now go to a fixed api.github.com host over a verified default TLS context, and API error statuses or connection failures are reported as drift. Signed-off-by: parthrohit22 <parthrohit60@gmail.com>
| connection = http.client.HTTPSConnection( # nosemgrep: python.lang.security.audit.httpsconnection-detected.httpsconnection-detected # noqa: E501 | ||
| API_HOST, timeout=30, context=ssl.create_default_context() | ||
| ) |
m-khan-97
left a comment
There was a problem hiding this comment.
I reviewed the current head end to end and verified the declared rules, audit behavior, workflow integration, and tests. The implementation is careful and the focused suite passes locally: 16 tests, plus validation of both committed rulesets. The required check names also match the checks currently emitted by the repository.
Approved from my side. One important operational boundary remains: this PR declares and audits the policy, but it does not make the live repository compliant by itself. The live rules API still reports no effective rulesets. Please keep #298 open until an organization administrator applies both rulesets, runs the audit successfully with bypass visibility, and completes the documented failure, stale-head, and self-approval drills.
ritiksah141
left a comment
There was a problem hiding this comment.
Approving. Reviewed end to end: read the full diff, checked the branch out locally, re-ran the suite, and reproduced the live audit against OWASP/openshield independently.
Local verification
- Full backend suite: 1064 passed, 6 skipped.
tests/test_check_branch_protection.py: 16 passed (the description says 15; the file collects 16 with parametrization).ruff checkandruff format --checkon the new script and tests: clean. All four changed workflow YAMLs and both ruleset JSONs parse.python scripts/check_branch_protection.py --validate-only: "Declared rulesets are valid for: dev, main".- Ran the live audit with a read-only token: it reproduces the evidence in the description exactly (DRIFT on both branches with all four rule types unenforced, the classic-protection note with status-check enforcement off, exit 1), and
GET /repos/OWASP/openshield/rulesetsconfirms no rulesets are applied yet. The evidence JSON record is well-formed. - Push-trigger compatibility:
enforce-source-branchno-ops on push events (github.base_refis empty, the step skips, the job succeeds), and the CI Summary fail gate seessuccessfrom every job on push runs, so post-merge runs report green correctly. The per-SHA concurrency key means push runs never cancel each other. - Action pins (checkout, setup-python, upload-artifact) match the SHAs used elsewhere in the repo.
Design notes
test_required_checks_match_real_workflow_job_namesis the right guard against the classic ruleset footgun: it parses every workflow (with CodeQL matrix expansion), runs insidepytest tests/on every PR, so renaming a required job anywhere breaks CI immediately instead of blocking merges forever.- Fail-closed layering is solid: declared-file validation gates the live comparison, API errors and unreachable API count as drift, and
MIN_APPROVALSis hardcoded in the script so weakeningmainbelow 2 requires a second reviewed edit, not just a JSON tweak. - PR mode is validate-only and offline, so fork PRs need no secrets; the fixed-host TLS client with path validation is careful.
- Docs are honest about the current state ("declared, not enforced") and the emergency procedure avoids standing bypass. Good.
Findings (non-blocking; #1 deserves a response or follow-up)
- Bypass-actor visibility gap. GitHub's docs confirm
bypass_actorsis filtered fromGET /rulesets/{id}responses for tokens without write access (the request does not 403). So with the defaultgithub.token, a standing bypass added later through the UI produces only an "unverified" note: the branch record and evidence JSON still saycompliant: trueand the weekly run stays green. The description's "never as compliant" overstates what the evidence shows. Minimal fixes: add abypass_actors_verifiedboolean per branch to the evidence record, and/or treat unverified visibility as drift on scheduled runs. At minimum, theBRANCH_PROTECTION_AUDIT_TOKENsecret probably should not be labelled "Optional" in the admin actions, since without it the bypass half of the audit is decorative. github_fetchertreats 3xx as success (onlystatus >= 400raises). A 301 (moved repo) returns a JSON message object, and downstream code then raisesAttributeErrorwith a traceback. Still non-zero exit, but confusing;if not 200 <= response.status < 300: raise GitHubApiError(response.status)is a one-line fix.- Ruleset details are always fetched via
/repos/{repo}/rulesets/{id}. If an org-level ruleset ever applies to these branches (ruleset_source_type: Organization), that fetch 404s and the whole branch reports non-compliant. Fail-closed but misleading; routing byruleset_source_typewould future-proof it. - Admin action sequencing: applying the rulesets (action 1) before
STATS_BOT_TOKENexists (action 3) means the stats bot's PRs can never merge, because PRs opened withGITHUB_TOKENstart no workflows and the required checks never report. Suggest doing 3 before or together with 1. - Coordination note for #335:
dismiss_stale_reviews_on_pushplus strict checks means every "Update branch" or merge-queue rebase dismisses approvals, andrequire_last_push_approvalbars the last pusher from re-approving. Mergify will wait for conditions to be re-met rather than deadlocking, but maintainer cadence changes noticeably on both branches once this is active. Worth verifying queue behavior when #335 lands. - Trivial: merging a stats PR re-triggers
update-learn-pageon dev, and if the stats drift between runs it immediately opens the next PR. Bounded by the changed-check, just something to expect.
Strong infrastructure PR: the declared-state vs effective-state split is exactly the right model for #298, the tests guard the guards, and the live audit confirms the evidence rather than trusting documentation.
TFT444
left a comment
There was a problem hiding this comment.
@parthrohit22 PR is approved and all CI checks are green, but there is a merge conflict with dev. Please rebase onto current dev and re-push to unblock the merge.
Resolves the CHANGELOG conflict by keeping both the OWASP#298 branch-protection entries and the AKS/OIDC entries added on dev. Signed-off-by: parthrohit22 <parthrohit60@gmail.com>
a4e7117
|
@TFT444 conflict with Merged current Re-verified on the merged head, since dev added new CI jobs since the last run:
Nothing in the declared rulesets or the audit logic changed. The operational boundary @m-khan-97 raised still stands: this declares and audits the policy, it does not make the live repository compliant, so #298 should stay open until an administrator applies both rulesets and completes the drills. @m-khan-97 @ritiksah141 your approvals were dismissed by the push, sorry for the churn — re-requesting. |
What does this PR do?
Declares
devandmainbranch protection as versioned GitHub rulesets and adds an automated audit that fails when the protection GitHub actually enforces is weaker than declared, so #298's controls are demonstrated rather than only documented.Type of change
Changes
Declared state:
.github/branch-protection/{dev,main}.json, in GitHub's ruleset import formatCI Summary,DCO sign-off,dependency-review,Analyze (python),Analyze (javascript); no standing bypass actors.devrequires 1 approval andmainrequires 2. The existingEnforce dev to main sourcejob already runs insideCI Summary.Effective state:
scripts/check_branch_protection.pyplus.github/workflows/branch-protection-audit.ymlGET /repos/{repo}/rules/branches/{branch}and each applied ruleset, then reports missing rules, fewer approvals than declared, missing flags, missing or non-strict checks, and standing bypass actors.branch-protection-evidenceJSON artifact (kept 90 days).Post-merge assurance
ci.ymlandcodeql.ymlnow also run onpushtodevandmain. Post-merge runs are never cancelled (concurrency is keyed by SHA for pushes). This is compatible with the Mergify queue proposed in infra: add Mergify serial merge queue for dev branch #335.Stats bot no longer pushes to protected
devupdate-learn-page.ymlhas been failing withGH006: Protected branch update failed. It now force-updatesdocs/refresh-learn-page-statsand opens or refreshes a PR through the normal protected flow. It uses theSTATS_BOT_TOKENsecret if one is set, because PRs opened withGITHUB_TOKENdon't start workflows.Docs:
docs/ci-pipeline.mdnow separates declared state from effective state, and covers admin apply commands, how to verify each acceptance criterion, and an emergency procedure with no standing bypass.Current effective state (evidence)
Running the audit against
OWASP/openshieldtoday:This matches the #298 finding: no required check is enforced on either branch.
Admin actions needed after merge (I can't do these: my role is write, not admin)
gh api -X POST repos/OWASP/openshield/rulesets --input .github/branch-protection/dev.json(repeat withmain.json), then retire the classic protection.BRANCH_PROTECTION_AUDIT_TOKENsecret (ruleset read-admin) so the audit can verify bypass actors.STATS_BOT_TOKENsecret and allow GitHub Actions to create PRs.Testing
tests/test_check_branch_protection.py: 15 tests. They cover:mainrequires 2 approvalstest_devops_client.pyare local-only (azure-devopsisn't installed on my machine) and also fail on unmodifieddev.ruff check .andruff format --check .are clean, and all workflow YAML parses.OWASP/openshield(output above).Related issue
Partially addresses #298. The in-repo work is complete, but the issue should stay open until an administrator applies the rulesets and the audit and acceptance drills pass.
Checklist
Signed-off-bytrailerinfra/description