beads/.github/workflows/docs-autofix.yml
Julian Knutsen 90b84ea150
ci: auto-push Bazel BUILD sync fixes to PRs; harden docs autofix (#6907)
* ci(bazel): auto-push `make bazel-sync` fixes to PR branches

bazel.yml's BUILD sync step now writes the BUILD.bazel / MODULE.bazel /
MODULE.bazel.lock part of its drift as the bazel-sync-patch artifact
(scripts/ci/bazel-sync-patch.sh) and still fails. The new bazel-autofix.yml
workflow_run job (on "Bazel" and "PR") applies it with
scripts/bazel-autofix-push.sh: a sync commit on same-repo PR branches, an
idempotent apply-recipe comment on fork PRs.

Same security model as docs-autofix: the write-permission side never checks
out or runs PR code, extracts only the two expected regular files, and
refuses any patch naming a path outside an anchored allowlist (no hidden or
`..` segments, nothing under third_party/) or carrying a mode change,
symlink, rename or binary hunk; `git apply --index` and a post-apply check
back that up. Reuses the DOCS_AUTOFIX_TOKEN secret for the push.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* build(bazel): add bazel_autofix_push_test.go to scripts_test

`make bazel-sync` output, produced by scripts/ci/bazel-sync-patch.sh and
applied with scripts/bazel-autofix-push.sh as an end-to-end exercise of the
new autofix path.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(ci): harden the bazel and docs autofix push scripts

Addresses the security review of the autofix pipeline, identically in
scripts/bazel-autofix-push.sh and scripts/docs-autofix-push.sh (the
security-critical functions are now shared verbatim):

- validate_patch refuses ANY "rename "/"copy " header (the legacy
  "rename old/new" form slipped past and, on docs-autofix, pushed a
  scripts.sh -> docs/cli-reference/x.md rename), checks every "index "
  line whatever its ids, takes creations/deletions/renames from
  `git apply --summary`, and reads names from `--numstat -z` (which
  names only the NEW path of a rename; the old comment was wrong).
- docs-autofix gains the post-apply staged re-check and a --check mode.
- The patch is applied to an index in a bare clone (read-tree +
  apply --cached + commit-tree): the PR tree never touches the disk.
  All git calls run with core.hooksPath=/dev/null, GIT_LFS_SKIP_SMUDGE=1.
- Push is leased: --force-with-lease=refs/heads/$HEAD_BRANCH:$HEAD_SHA.
- The PR must target this repo, and the head branch must be neither
  protected nor under a ruleset per the GitHub API (fail closed), on top
  of the name list.
- Only a marker comment written by github-actions[bot] is ever edited.
- bazel-autofix only pushes files in packages the PR changed
  (merge-base..head, computed from fetched refs), MODULE files only when
  go.mod/go.sum/MODULE changed; base-branch drift is left alone and
  listed, and a patch with nothing attributable gets a comment only.

Tests cover each reviewer attack for both scripts (--check and the full
flow against a local bare remote and fake gh), the staged check alone
with the validator disabled, spoofed comments, protection/ruleset/API
errors, the lease, main drift, and symlinked PR trees.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(ci): trigger bazel-autofix on Bazel only; share job-level concurrency

- bazel-autofix.yml triggers only on "Bazel": pr.yml never calls
  bazel.yml, so "PR" runs never carry the artifact, and their completions
  cancelled real fixes through the workflow-level group. The policy test
  now requires the triggering workflow to run on pull_request and upload
  the consumed artifact instead of asserting the false claim.
- Both autofix workflows use one job-level concurrency group per head
  branch (autofix-<head repo>-<head branch>) without cancel-in-progress:
  skipped runs take no part, and the two bots queue instead of racing.
- Base checkouts use persist-credentials: false; docs-autofix extracts
  only cli-docs-freshness.patch, as a regular file, outside the workspace.
- Policy tests for the trigger, concurrency scope, checkout, and the
  scripts' shared guards (rename/index checks, comment author, lease,
  protection lookup, index-only apply, hook-free git).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(ci): tighten autofix attribution, circuit breaker and PR selection

Re-review follow-ups for the bazel and docs autofix push scripts:

- Root package: paths outside any Bazel package (docs/, .github/,
  README.md, ...) no longer count as changing //:. Only root-level Go and
  build inputs (*.go, *.s, *.c, *.h, *.bzl, go.mod, go.sum, BUILD.bazel,
  MODULE.bazel*) make root BUILD.bazel drift the PR's, so main's root
  drift is not pushed onto a docs-only PR.
- Circuit breaker: the head subject is read from the fetched commit (no
  API), a failed read counts as non-convergent, and the check runs only
  once the PR's own staged fix is non-empty. A bot head whose remaining
  drift is main's now gets the "files this PR did not change" comment
  instead of a wrong "did not converge" one. Same in docs-autofix.
- PR selection: several open PRs can share one head branch. bazel picks
  the one whose number matches the artifact metadata (among PRs already
  matching head repo/branch/base repo; head sha still verified); without
  a unique match both scripts skip instead of taking .[0].
- The privileged clone fetches only the head (and, for bazel, base)
  branch into an init'ed bare partial repo instead of cloning every
  branch.
- docs-autofix job gets timeout-minutes: 10 (it shares a non-cancelling
  concurrency group with bazel-autofix).

Tests: docs-only/README/workflow/Makefile PRs with root drift get no push,
a root Go change gets root BUILD.bazel; breaker cases (bot head with own
vs main drift, unreadable subject) for both scripts; PR selection by
metadata and ambiguity; HEAD_SHA 40-hex guard; staged-check mode arm; a
--summary-only validator copy; both workflows' download steps run as
written against a fake gh (run-scoped artifact listing, only the named
files extracted, symlinked entries refused); timeout asserted for both
jobs.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(ci): bazel-autofix requires bash 4; skip its tests on macOS bash 3.2

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* test(ci): skip every autofix script test on bash < 4

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* build(bazel): sync internal/utils BUILD with main

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-28 17:23:27 -07:00

112 lines
5.2 KiB
YAML

# Auto-fix stale generated CLI docs on PRs.
#
# The PR workflow's check-doc-flags job already computes the exact
# regeneration patch with CI's canonical pinned build and uploads it as the
# cli-docs-freshness-patch artifact (scripts/check-cli-docs-drift.sh). This
# workflow closes the loop: when a PR run fails and left that artifact, it
# pushes the regen commit to the PR branch (same-repo PRs) or leaves an
# idempotent comment with the one-liner apply recipe (fork PRs).
#
# SECURITY MODEL: this runs with write permissions via workflow_run, so it
# never checks out or executes PR code. It checks out the base default branch
# for scripts, and treats the artifact strictly as data: every path in the
# patch must match an anchored generated-docs allowlist (single path segment,
# no traversal), mode/symlink/rename/copy/binary hunks are refused, and the
# patch is applied to an index in a bare clone and re-checked once staged
# (scripts/docs-autofix-push.sh), so a hostile patch can at most rewrite
# generated doc files on its own PR branch. Pushes are leased to the run's
# head SHA and skipped for heads that are protected or under a ruleset.
#
# CONCURRENCY: job-level, shared with bazel-autofix.yml per head branch and
# without cancel-in-progress, so the two bots queue instead of racing on one
# branch (see bazel-autofix.yml).
#
# TOKEN NOTE: pushes made with the default GITHUB_TOKEN do not retrigger PR
# checks. Configure a DOCS_AUTOFIX_TOKEN repo secret (fine-grained PAT or
# GitHub App token with contents:write on this repo) for fully hands-off
# operation on same-repo PRs; without it the pushed fix still lands but
# checks need a manual re-run. Fork PRs always get the apply-recipe comment -
# no token we hold can push to a fork.
name: Docs Autofix
on:
workflow_run:
workflows: ["PR"]
types: [completed]
permissions:
contents: write
pull-requests: write
actions: read
jobs:
autofix:
name: Apply CLI docs regeneration to PR
if: >
github.event.workflow_run.event == 'pull_request' &&
github.event.workflow_run.conclusion == 'failure'
runs-on: ubuntu-latest
# Bounded: a hung run would hold the shared group for the default 6h.
timeout-minutes: 10
# Shared with bazel-autofix.yml; queue, never cancel.
concurrency:
group: autofix-${{ github.event.workflow_run.head_repository.full_name }}-${{ github.event.workflow_run.head_branch }}
cancel-in-progress: false
steps:
# Trusted side only: base repo default branch, never the PR head. The
# workflow token is not left in .git/config.
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6
with:
persist-credentials: false
- name: Download docs freshness patch (if any)
id: patch
env:
GH_TOKEN: ${{ github.token }}
RUN_ID: ${{ github.event.workflow_run.id }}
run: |
artifact_ids="$(gh api "repos/${GITHUB_REPOSITORY}/actions/runs/${RUN_ID}/artifacts" \
--jq '.artifacts[] | select(.name == "cli-docs-freshness-patch") | .id')"
artifact_id="$(printf '%s\n' "$artifact_ids" | head -1)"
if [ -z "$artifact_id" ]; then
echo "No docs patch artifact on run ${RUN_ID}; PR failed for other reasons."
echo "found=false" >> "$GITHUB_OUTPUT"
exit 0
fi
dir="${RUNNER_TEMP}/docs-patch"
mkdir -p "$dir"
gh api "repos/${GITHUB_REPOSITORY}/actions/artifacts/${artifact_id}/zip" > "${RUNNER_TEMP}/docs-patch.zip"
# Extract only the expected name, and only as a regular file.
unzip -o "${RUNNER_TEMP}/docs-patch.zip" cli-docs-freshness.patch -d "$dir" || true
ls -la "$dir"
f="$dir/cli-docs-freshness.patch"
if [ -L "$f" ] || { [ -e "$f" ] && [ ! -f "$f" ]; }; then
echo "::error::artifact entry cli-docs-freshness.patch is not a regular file"
exit 1
fi
if [ ! -f "$f" ]; then
echo "Artifact has no cli-docs-freshness.patch; nothing to do."
echo "found=false" >> "$GITHUB_OUTPUT"
exit 0
fi
echo "found=true" >> "$GITHUB_OUTPUT"
- name: Push regen commit or leave apply recipe
if: steps.patch.outputs.found == 'true'
env:
BASE_REPO: ${{ github.repository }}
HEAD_REPO: ${{ github.event.workflow_run.head_repository.full_name }}
HEAD_BRANCH: ${{ github.event.workflow_run.head_branch }}
HEAD_SHA: ${{ github.event.workflow_run.head_sha }}
PATCH_FILE: ${{ runner.temp }}/docs-patch/cli-docs-freshness.patch
RUN_ID: ${{ github.event.workflow_run.id }}
RUN_URL: ${{ github.event.workflow_run.html_url }}
# Split tokens: gh api calls (PR lookup, comments) always use the
# workflow token, which carries this job's pull-requests:write; the
# optional PAT is used ONLY for the git push, so it needs no more
# than contents:write.
GH_TOKEN: ${{ github.token }}
PUSH_TOKEN: ${{ secrets.DOCS_AUTOFIX_TOKEN || github.token }}
AUTOFIX_TOKEN_KIND: ${{ secrets.DOCS_AUTOFIX_TOKEN && 'pat' || 'default' }}
run: ./scripts/docs-autofix-push.sh