name: Docs - Build and commit # Reusable workflow invoked by the review-driven, push-driven, and manual # dispatch docs workflows. Concurrency is owned by the callers (group keyed # on PR number) since workflow_call ignores a called workflow's concurrency # block. # # Inputs are optional: the push-driven caller has a PR payload and leaves # them unset, in which case the workflow reads from # `github.event.pull_request`. The manual-dispatch and approval-driven paths # have no PR payload, so they look the PR up via the API and pass the values # explicitly. on: workflow_call: inputs: pr_number: description: PR number (defaults to github.event.pull_request.number) required: false type: number head_sha: required: false type: string head_ref: required: false type: string head_repo: required: false type: string base_sha: required: false type: string bypass_skip_docs: description: When true, run even if the PR has skip-docs applied required: false type: boolean default: false bypass_attack_files: description: When true, run even if the PR diff touches build-config attack files required: false type: boolean default: false secrets: OMRS_PR_BOT_CLIENT_ID: required: true OMRS_PR_BOT_PRIVATE_KEY: required: true # Bot user PAT, used only to push docs commits to fork branches. OMRS_BOT_GH_TOKEN: required: true permissions: {} jobs: preflight: runs-on: ubuntu-latest permissions: contents: read issues: read pull-requests: write env: REPO: ${{ github.repository }} PR_NUMBER: ${{ inputs.pr_number || github.event.pull_request.number }} HEAD_REPO: ${{ inputs.head_repo || github.event.pull_request.head.repo.full_name }} HEAD_REF: ${{ inputs.head_ref || github.event.pull_request.head.ref }} HEAD_SHA: ${{ inputs.head_sha || github.event.pull_request.head.sha }} BASE_SHA: ${{ inputs.base_sha || github.event.pull_request.base.sha }} BYPASS_SKIP_DOCS: ${{ inputs.bypass_skip_docs }} BYPASS_ATTACK_FILES: ${{ inputs.bypass_attack_files }} outputs: proceed: ${{ steps.gate.outputs.proceed }} status_check_id: ${{ steps.status.outputs.id }} steps: - name: Gate id: gate env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} run: | set -euo pipefail # HEAD_REF is interpolated into a refspec on the push line in the # commit job; reject anything outside a conservative subset before # any privileged step touches it. if ! [[ "${HEAD_REF}" =~ ^[A-Za-z0-9._/-]+$ ]]; then echo "Refusing unsafe head ref: ${HEAD_REF}" echo "proceed=false" >> "$GITHUB_OUTPUT" exit 0 fi labels=$(gh api "repos/${REPO}/issues/${PR_NUMBER}/labels" --jq '[.[].name] | join(",")') if echo ",${labels}," | grep -q ",skip-docs,"; then if [ "${BYPASS_SKIP_DOCS}" = "true" ]; then echo "skip-docs label present but bypass requested; proceeding" else echo "skip-docs label set; aborting" echo "proceed=false" >> "$GITHUB_OUTPUT" exit 0 fi fi is_fork=false if [[ "${HEAD_REPO}" != "${REPO}" ]]; then is_fork=true fi # Each caller implements its own approval gate; re-verify here so a # future caller that forgets to gate (or a regression in caller # logic) can't smuggle PR code execution through this workflow. approved_by_writer=false for u in $(gh api --paginate "repos/${REPO}/pulls/${PR_NUMBER}/reviews?per_page=100" --jq '.[] | select(.state == "APPROVED") | .user.login' | sort -u); do permission=$(gh api "repos/${REPO}/collaborators/${u}/permission" --jq '.permission' 2>/dev/null || echo "none") if [[ "${permission}" == "write" || "${permission}" == "admin" ]]; then approved_by_writer=true break fi done if [[ "${approved_by_writer}" != "true" ]]; then echo "No write-access approval present; aborting" echo "proceed=false" >> "$GITHUB_OUTPUT" exit 0 fi # Anything that influences what `yarn turbo run document` actually # executes belongs here; modifying these files in a PR head could # otherwise hijack the build job's typedoc plugin code path. ATTACK_FILES=( "packages/framework/esm-framework/typedoc.json" "packages/framework/esm-framework/tsconfig.typedoc.json" "tools/document.sh" "turbo.json" ".yarnrc.yml" ) # Resolve the diff at the SHAs this run pinned, not via pulls/N/files # (which returns the *current* PR diff): a contributor could # otherwise revert attack-listed files after this gate runs but # before the build job checks that SHA out. # # API call here so we correctly fail if BASE_SHA or HEAD_SHA do not resolve compare=$(gh api "repos/${REPO}/compare/${BASE_SHA}...${HEAD_SHA}") # compare caps `files` at 300 and `--paginate` walks commits, not # files, so at the cap a complete diff is indistinguishable from a # truncated one. Refuse rather than scan a partial list. file_count=$(echo "${compare}" | jq '.files | length') if [ "${file_count}" -ge 300 ] && [ "${BYPASS_ATTACK_FILES}" != "true" ]; then echo "PR diff has ${file_count} files, at or above the compare API's cap; cannot audit it for docs-build configuration changes" gh pr comment "${PR_NUMBER}" --repo "${REPO}" --body "Automatic documentation regeneration is disabled for this PR because its diff (${file_count} files) is too large for the docs-build configuration audit to be complete. After auditing the changes, a maintainer can either: - Apply the \`skip-docs\` label to skip docs entirely, or - Trigger the **Docs - Rebuild on demand** workflow from the Actions tab with **bypass_attack_files** enabled to force the build." echo "proceed=false" >> "$GITHUB_OUTPUT" exit 0 fi # No `?` after .files: a response shape we don't expect should be a # hard error here, not an empty list that opens the gate. changed=$(echo "${compare}" | jq -r '.files[].filename') touched_attack=false attack_match="" while IFS= read -r f; do [ -z "$f" ] && continue for a in "${ATTACK_FILES[@]}"; do if [[ "$f" == "$a" ]]; then touched_attack=true attack_match="$f" break 2 fi done case "$f" in packages/tooling/typedoc-plugin-file-categories/*) touched_attack=true; attack_match="$f"; break ;; packages/framework/*/tsconfig.json|packages/framework/*/tsconfig.build.json) touched_attack=true; attack_match="$f"; break ;; .yarn/plugins/*|.yarn/releases/*|.yarn/versions/*) touched_attack=true; attack_match="$f"; break ;; esac # Callers run on pull_request_target or workflow_run, both of # which use the base-branch workflow file (which transitively # pulls this one via uses:), so a fork's modifications to docs # workflow files never execute. Block here so the change still # requires maintainer audit via skip-docs rather than passing # auto-build silently. if [[ "${is_fork}" == "true" ]]; then case "$f" in .github/workflows/docs-*.yml) touched_attack=true; attack_match="$f"; break ;; esac fi done <<< "${changed}" if [[ "${touched_attack}" == "true" ]]; then if [[ "${BYPASS_ATTACK_FILES}" == "true" ]]; then echo "Attack file touched (${attack_match}) but bypass requested; proceeding" else echo "PR modifies docs-build configuration (${attack_match}); refusing auto-build" gh pr comment "${PR_NUMBER}" --repo "${REPO}" --body "Automatic documentation regeneration is disabled for this PR because it touches \`${attack_match}\`, which is part of the docs build configuration. After auditing the changes, a maintainer can either: - Apply the \`skip-docs\` label to skip docs entirely, or - Trigger the **Docs - Rebuild on demand** workflow from the Actions tab with **bypass_attack_files** enabled to force the build." echo "proceed=false" >> "$GITHUB_OUTPUT" exit 0 fi fi echo "proceed=true" >> "$GITHUB_OUTPUT" - name: Mint app token if: steps.gate.outputs.proceed == 'true' id: app-token uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v3.3.0 with: client-id: ${{ secrets.OMRS_PR_BOT_CLIENT_ID }} private-key: ${{ secrets.OMRS_PR_BOT_PRIVATE_KEY }} permission-checks: write # The approval-driven caller runs on the default branch, so its own # jobs are invisible on the PR. This check run is the PR-visible signal # that a build is under way, and the callers' decide jobs read it to # avoid starting (and thereby cancelling) a duplicate build for the # same SHA. `finalize` completes it. - name: Post build status if: steps.gate.outputs.proceed == 'true' id: status env: GH_TOKEN: ${{ steps.app-token.outputs.token }} RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} run: | set -euo pipefail id=$(gh api -X POST "repos/${REPO}/check-runs" \ -f name='Docs / Build' \ -f head_sha="${HEAD_SHA}" \ -f status=in_progress \ -f details_url="${RUN_URL}" \ -f 'output[title]=Regenerating documentation' \ -f "output[summary]=Building docs for \`${HEAD_SHA}\`; see the linked run." \ --jq '.id') echo "id=${id}" >> "$GITHUB_OUTPUT" build: needs: preflight if: needs.preflight.outputs.proceed == 'true' runs-on: ubuntu-latest # contents:read is the minimum actions/checkout needs to authenticate; # everything else stays denied. This is the only job that executes PR # code (typedoc plugins, build scripts), and `persist-credentials: false` # below keeps the token from reaching the working tree. permissions: contents: read env: # Block lifecycle scripts on PR-controlled deps so `yarn install` # can't side-execute arbitrary code from a malicious package.json. YARN_ENABLE_SCRIPTS: "0" steps: - name: Checkout PR head (sandboxed) uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: ref: ${{ inputs.head_sha || github.event.pull_request.head.sha }} repository: ${{ inputs.head_repo || github.event.pull_request.head.repo.full_name }} # Belt-and-suspenders: this job has no tokens to begin with, but # if a future change grants one, don't leave it in .git/config # where PR-controlled paths could exfiltrate it. persist-credentials: false - name: Setup Node.js uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 with: node-version: 20 - name: Install dependencies run: yarn install --immutable - name: Build documentation run: yarn turbo run document - name: Validate output # typedoc plugins run as PR-controlled code and could write symlinks # into the docs tree — they'd then be carried by the artifact and # extracted in the privileged commit job. Reject them at the source. run: | set -euo pipefail docs_dir="packages/framework/esm-framework/docs" if [ ! -d "$docs_dir" ]; then echo "Expected docs dir not found" exit 1 fi if find "$docs_dir" -type l | grep -q .; then echo "Symlinks found in docs output" exit 1 fi - name: Upload docs artifact uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: docs path: packages/framework/esm-framework/docs/ retention-days: 1 include-hidden-files: false commit: needs: [preflight, build] # Explicit preflight gate (in addition to `needs:`) so this privileged # job can never run if preflight didn't pass, even if `build`'s `if:` # is changed in a future refactor. if: needs.preflight.outputs.proceed == 'true' runs-on: ubuntu-latest permissions: actions: write contents: read pull-requests: write env: REPO: ${{ github.repository }} PR_NUMBER: ${{ inputs.pr_number || github.event.pull_request.number }} HEAD_REF: ${{ inputs.head_ref || github.event.pull_request.head.ref }} HEAD_REPO: ${{ inputs.head_repo || github.event.pull_request.head.repo.full_name }} HEAD_SHA: ${{ inputs.head_sha || github.event.pull_request.head.sha }} steps: - name: Checkout the SHA the build ran against uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: ref: ${{ inputs.head_sha || github.event.pull_request.head.sha }} repository: ${{ inputs.head_repo || github.event.pull_request.head.repo.full_name }} persist-credentials: false - name: Download docs artifact uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 with: name: docs path: /tmp/docs-artifact - name: Validate artifact contents run: | set -euo pipefail # Artifact tarball is produced by PR-controlled typedoc plugins. # Reject anything that could escape the docs tree on extraction. if find /tmp/docs-artifact -type l | grep -q .; then echo "Symlinks present in artifact" exit 1 fi if find /tmp/docs-artifact -mindepth 1 ! -type f ! -type d | grep -q .; then echo "Non-regular files present in artifact" exit 1 fi while IFS= read -r f; do relative="${f#/tmp/docs-artifact/}" case "$relative" in */../*|../*|*/..) echo "Path traversal in artifact: $relative"; exit 1 ;; esac done < <(find /tmp/docs-artifact -type f) - name: Replace docs tree run: | set -euo pipefail docs_dir="packages/framework/esm-framework/docs" rm -rf "$docs_dir" mkdir -p "$docs_dir" cp -a /tmp/docs-artifact/. "$docs_dir/" # The push must not use GITHUB_TOKEN: GitHub creates no # `pull_request_target` runs for pushes made with it, so the drift, # title, and description checks would never run on the docs commit and # the PR could not merge. Same-repo branches are pushed with the App # token. Forks need the bot user's PAT instead: "Allow edits by # maintainers" grants push access to users with write access to this # repo, and an App is not such a user. The PR tree is on disk in this # job, but nothing below executes PR-controlled code (no scripts, no # hooks), and whichever token is used only ever appears on a command # line. - name: Mint app token id: app-token uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v3.3.0 with: client-id: ${{ secrets.OMRS_PR_BOT_CLIENT_ID }} private-key: ${{ secrets.OMRS_PR_BOT_PRIVATE_KEY }} permission-contents: write permission-checks: write - name: Commit and push id: commit env: APP_TOKEN: ${{ steps.app-token.outputs.token }} BOT_TOKEN: ${{ secrets.OMRS_BOT_GH_TOKEN }} run: | set -euo pipefail if [ "${HEAD_REPO}" = "${REPO}" ]; then push_token="${APP_TOKEN}" else push_token="${BOT_TOKEN}" fi git config user.name "openmrs-bot" git config user.email "infrastructure@openmrs.org" git add packages/framework/esm-framework/docs/ if git diff --cached --quiet; then echo "No doc changes; treating as success" { echo "pushed=true" echo "committed=false" echo "pushed_sha=$(git rev-parse HEAD)" } >> "$GITHUB_OUTPUT" exit 0 fi git commit -m "(chore) Add docs" # Push from detached HEAD to the specific branch. Non-FF fails # (head moved during build); never force-push. Token lives only # on this command line, never persisted to .git/config, so the # working tree never holds a write-scoped credential reachable # from PR-controlled paths. push_url="https://x-access-token:${push_token}@github.com/${HEAD_REPO}.git" if git push "${push_url}" "HEAD:refs/heads/${HEAD_REF}"; then # Pin to local HEAD (= the SHA we just pushed). A fresh # `current head` API lookup would race against contributor # pushes and could attest a SHA whose docs we didn't build. { echo "pushed=true" echo "committed=true" echo "pushed_sha=$(git rev-parse HEAD)" } >> "$GITHUB_OUTPUT" else echo "pushed=false" >> "$GITHUB_OUTPUT" exit 1 fi # Only runs when the SHA was actually pushed (or already current): # attesting a SHA we didn't publish would falsely claim its docs are # fresh. Posted in this job, right after the push, because the push # itself fires `synchronize` runs that query this check within seconds; # deferring it to another job races them into a redundant rebuild and # a spurious drift failure. - name: Post check run if: steps.commit.outputs.pushed_sha != '' env: GH_TOKEN: ${{ steps.app-token.outputs.token }} PUSHED_SHA: ${{ steps.commit.outputs.pushed_sha }} run: | set -euo pipefail # A commit pushed to a fork only becomes visible here once GitHub # has updated refs/pull/N/head, which can lag the push by a few # seconds; until then the API rejects the SHA. for attempt in 1 2 3 4 5; do if gh api -X POST "repos/${REPO}/check-runs" \ -f name='Docs / Regenerated' \ -f head_sha="${PUSHED_SHA}" \ -f status=completed \ -f conclusion=success \ -f 'output[title]=Documentation regenerated' \ -f "output[summary]=Generated docs reflect the PR head at \`${PUSHED_SHA}\`."; then exit 0 fi echo "Attempt ${attempt} failed; retrying" sleep 3 done exit 1 # When the build produced no new commit there is no push to fire a # fresh `synchronize`, so the drift run that already failed for this # SHA would stay red even though the check run above now satisfies it. # Re-running that run is the only way to get a passing `drift` onto # the head SHA; a run started by any other event reports against main. - name: Re-run drift check if: steps.commit.outputs.committed == 'false' env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} run: | set -euo pipefail run=$(gh api --method GET "repos/${REPO}/actions/workflows/docs-drift-check.yml/runs" \ -f head_sha="${HEAD_SHA}" -f event=pull_request_target -f per_page=1 \ --jq '.workflow_runs[0] | select(. != null) | "\(.id) \(.status) \(.conclusion)"') if [ -z "${run}" ]; then echo "No drift run found for ${HEAD_SHA}; nothing to re-run" exit 0 fi read -r id status conclusion <<< "${run}" if [ "${status}" != "completed" ]; then echo "Drift run ${id} is still ${status}; it will pick up the check run itself" exit 0 fi if [ "${conclusion}" = "success" ]; then echo "Drift run ${id} already passed" exit 0 fi echo "Re-running drift run ${id} (was ${conclusion})" gh api -X POST "repos/${REPO}/actions/runs/${id}/rerun" - name: Comment on push failure if: failure() && steps.commit.outputs.pushed == 'false' env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} run: | gh pr comment "${PR_NUMBER}" --repo "${REPO}" --body "Documentation was regenerated successfully but pushing the docs commit to this branch failed. Common causes: - The branch advanced after the build started — push another commit to retrigger. - The PR is from a fork without **Allow edits by maintainers** enabled (please enable it). If neither applies, apply the \`skip-docs\` label and push the docs commit yourself." finalize: needs: [preflight, build, commit] # `always()` so a cancelled or failed build still closes the status # check; an in-progress check left behind would make the callers' # decide jobs treat the SHA as still building. if: always() && needs.preflight.outputs.status_check_id != '' runs-on: ubuntu-latest permissions: {} env: REPO: ${{ github.repository }} CHECK_ID: ${{ needs.preflight.outputs.status_check_id }} BUILD_RESULT: ${{ needs.build.result }} COMMIT_RESULT: ${{ needs.commit.result }} steps: - name: Mint app token id: app-token uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v3.3.0 with: client-id: ${{ secrets.OMRS_PR_BOT_CLIENT_ID }} private-key: ${{ secrets.OMRS_PR_BOT_PRIVATE_KEY }} permission-checks: write - name: Complete build status env: GH_TOKEN: ${{ steps.app-token.outputs.token }} run: | set -euo pipefail if [ "${COMMIT_RESULT}" = "success" ]; then conclusion=success title="Documentation build finished" elif [ "${BUILD_RESULT}" = "cancelled" ] || [ "${COMMIT_RESULT}" = "cancelled" ]; then conclusion=cancelled title="Documentation build cancelled" else conclusion=failure title="Documentation build failed" fi gh api -X PATCH "repos/${REPO}/check-runs/${CHECK_ID}" \ -f status=completed \ -f conclusion="${conclusion}" \ -f "output[title]=${title}" \ -f "output[summary]=build: ${BUILD_RESULT}, commit: ${COMMIT_RESULT}. See the linked run for details."