name: Build Runtime Images on: pull_request: types: [opened, synchronize, reopened, edited] workflow_run: workflows: ["CI — Validation"] types: [completed] repository_dispatch: types: [pr-runtime-base-refresh] workflow_dispatch: run-name: Build Runtime Images ${{ (github.event_name == 'pull_request' || github.event_name == 'repository_dispatch') && format('pr-{0} base-{1} head-{2} merge-{3} mode-{4}', github.event_name == 'pull_request' && github.event.pull_request.number || github.event.client_payload.pr_number, github.event_name == 'pull_request' && github.event.pull_request.base.sha || github.event.client_payload.base_sha, github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.event.client_payload.head_sha, github.event_name == 'pull_request' && github.sha || github.event.client_payload.merge_sha, github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.changes.base.ref == null && 'metadata' || 'required') || github.event_name == 'workflow_run' && github.event.workflow_run.event == 'push' && github.event.workflow_run.conclusion == 'success' && format('trusted-branch branch-{0} sha-{1}', github.event.workflow_run.head_branch, github.event.workflow_run.head_sha) || github.event_name == 'workflow_run' && format('base-refresh-only branch-{0} sha-{1} ci-{2}', github.event.workflow_run.head_branch, github.event.workflow_run.head_sha, github.event.workflow_run.conclusion) || github.ref_name }} permissions: contents: read # GitHub rejects queue: max together with a cancelling run, so the workflow # group never cancels. Typed refresh tuples and protected commits queue every # pending request, so a main request cannot replace a pending develop # publication of the same commit. Each PR run has its own group here; the PR # build jobs below cancel the PR's older build at job level instead. concurrency: group: runtime-images-${{ github.workflow }}-${{ (github.event_name == 'pull_request' && format('pr-{0}-run-{1}', github.event.pull_request.number, github.run_id)) || (github.event_name == 'repository_dispatch' && github.event.client_payload.pr_number != '' && github.event.client_payload.base_sha != '' && github.event.client_payload.head_sha != '' && github.event.client_payload.merge_sha != '' && format('pr-{0}-base-{1}-head-{2}-merge-{3}', github.event.client_payload.pr_number, github.event.client_payload.base_sha, github.event.client_payload.head_sha, github.event.client_payload.merge_sha)) || (github.event_name == 'repository_dispatch' && format('repository-dispatch-run-{0}', github.run_id)) || (github.event_name == 'workflow_run' && github.event.workflow_run.event == 'pull_request' && format('ci-pr-run-{0}-attempt-{1}', github.event.workflow_run.id, github.event.workflow_run.run_attempt)) || (github.event_name == 'workflow_run' && github.event.workflow_run.event == 'push' && github.event.workflow_run.conclusion == 'success' && (github.event.workflow_run.head_branch == 'main' || github.event.workflow_run.head_branch == 'develop') && format('protected-sha-{0}', github.event.workflow_run.head_sha)) || (github.event_name == 'workflow_dispatch' && (github.ref == 'refs/heads/main' || github.ref == 'refs/heads/develop') && format('protected-sha-{0}', github.sha)) || (github.event_name == 'workflow_run' && github.event.workflow_run.event == 'push' && format('ci-push-run-{0}-attempt-{1}', github.event.workflow_run.id, github.event.workflow_run.run_attempt)) || github.ref }}-${{ github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.changes.base.ref == null && format('metadata-{0}', github.run_id) || 'required' }} cancel-in-progress: false queue: max jobs: changes: name: Detect Smoke-Relevant Changes runs-on: ubuntu-latest permissions: contents: read pull-requests: read if: ${{ github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} outputs: run_smoke_full: ${{ steps.compute.outputs.run_smoke_full }} steps: - name: Harden runner uses: step-security/harden-runner@aebdcf6156ab6691adf63218240e476564a1ed4c # v2.23.0 with: egress-policy: audit - name: Compute smoke scope id: compute uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 with: script: | // Classify the exact test merge this run builds. The live PR file list // can already describe a later head. const base = context.payload.pull_request.base.sha; const merge = context.sha; let fileEntries = []; let fileListComplete = false; try { const {data: comparison} = await github.request("GET /repos/{owner}/{repo}/compare/{basehead}", { ...context.repo, basehead: `${base}...${merge}`, page: 1, per_page: 1, }); fileEntries = Array.isArray(comparison?.files) ? comparison.files : []; // Only a merge whose ordered parents are the event base and head may skip // smoke; otherwise image-meta resolves the exact merge and smoke runs. const {data: commit} = await github.request("GET /repos/{owner}/{repo}/commits/{ref}", { ...context.repo, ref: merge, }); const parents = (commit?.parents ?? []).map((parent) => parent?.sha); fileListComplete = parents.length === 2 && parents[0] === base && parents[1] === context.payload.pull_request.head.sha && comparison?.base_commit?.sha === base && comparison.merge_base_commit?.sha === base && comparison.status === "ahead" && Array.isArray(comparison.files) && comparison.files.length < 300; } catch (error) { core.warning(`Test-merge comparison unavailable: ${error.message}`); } const fileEntriesValid = fileEntries.every((file) => file && typeof file === "object" && typeof file.filename === "string" && file.filename.length > 0 && (file.previous_filename === undefined || (typeof file.previous_filename === "string" && file.previous_filename.length > 0)) ); const files = fileEntriesValid ? fileEntries.flatMap((file) => [file.filename, file.previous_filename].filter(Boolean) ) : []; if (!fileListComplete || !fileEntriesValid) { core.warning("PR file-list detection was incomplete; requiring full-stack smoke."); core.setOutput("run_smoke_full", "true"); return; } const docsOnlyPredicate = (file) => file === "AGENTS.md" || file === "mkdocs.yml" || file.startsWith("design/") || file.startsWith("dev-tools/docs/") || // Markdown under src/main/ is a packaged resource, so it is runtime input. (file.endsWith(".md") && !file.includes("/src/main/")); const frontendOnlyPredicate = (file) => file.startsWith("web-client/") || file.startsWith("config/openapi/"); const fullRelevantPrefixes = [ "buildSrc/", "gradle/", "protos/", "docker/", "services/", ".github/actions/load-workflow-tool-versions/", ".github/actions/setup-python/", ".github/actions/setup-gh/", ".env.sample", "dev-tools/smoke/", "dev-tools/minio/", ]; const fullRelevantFiles = new Set([ "build.gradle.kts", "settings.gradle.kts", "gradle.properties", "gradlew", "gradlew.bat", ".dockerignore", ".python-version", ".github/actions/load-workflow-tool-versions/action.yml", ".github/workflows/smoke-full.yml", ".github/workflows/runtime-images.yml", ".github/workflows/publish-pr-runtime-images.yml", "config/workflow-tool-versions.env", "config/python/smoke-requirements.txt", "config/python/smoke-requirements.in", "dev-tools/build-compose-service-jars.sh", "dev-tools/validation/run-gradle-with-dependency-recovery.sh", "dev-tools/validation/run-locked-gradle.sh", "dev-tools/validation/gradle-run-supervisor.py", "dev-tools/build-local-smoke-images.sh", "dev-tools/backups/verify-backups.sh", "dev-tools/backups/pg-dump-s3-selection.shlib", "dev-tools/backups/smoke-backup-verifier-image.sh", "dev-tools/certs/generate-dev-certs.sh", "dev-tools/verify-compose-health.sh", "dev-tools/verify-fresh-bootstrap.sh", "dev-tools/verify-restart-state.sh", "dev-tools/verify-smoke-images.sh", "dev-tools/hosted/controller/smoke-paused-controller-image.sh", ]); const nonDocFiles = files.filter((file) => !docsOnlyPredicate(file)); const nonDocsAreFrontendOnly = nonDocFiles.length > 0 && nonDocFiles.every((file) => frontendOnlyPredicate(file)); if (nonDocFiles.length === 0 || nonDocsAreFrontendOnly) { core.setOutput("run_smoke_full", "false"); return; } const runSmokeFull = nonDocFiles.some( (file) => fullRelevantFiles.has(file) || fullRelevantPrefixes.some((prefix) => file.startsWith(prefix)) ); core.setOutput("run_smoke_full", runSmokeFull ? "true" : "false"); image-meta: name: Derive Runtime Image Metadata needs: [changes] if: ${{ !cancelled() && ((github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) && needs.changes.outputs.run_smoke_full == 'true') || (github.event_name == 'repository_dispatch' && github.event.action == 'pr-runtime-base-refresh') || github.event_name == 'workflow_dispatch' || (github.event_name == 'workflow_run' && github.event.workflow_run.event == 'push' && github.event.workflow_run.conclusion == 'success' && (github.event.workflow_run.head_branch == 'main' || github.event.workflow_run.head_branch == 'develop'))) }} runs-on: ubuntu-latest outputs: pr_number: ${{ steps.meta.outputs.pr_number }} base_ref: ${{ steps.meta.outputs.base_ref }} base_sha: ${{ steps.meta.outputs.base_sha }} head_sha: ${{ steps.meta.outputs.head_sha }} merge_sha: ${{ steps.meta.outputs.merge_sha }} head_branch: ${{ steps.meta.outputs.head_branch }} checkout_ref: ${{ steps.meta.outputs.checkout_ref }} head_current: ${{ steps.meta.outputs.head_current }} image_tag: ${{ steps.meta.outputs.image_tag }} candidate_tag: ${{ steps.meta.outputs.candidate_tag }} base_image: ${{ steps.meta.outputs.base_image }} runtime_smoke_required: ${{ steps.smoke_scope.outputs.runtime_smoke_required }} controller_smoke_required: ${{ steps.smoke_scope.outputs.controller_smoke_required }} skip_build: ${{ steps.published.outputs.skip_build }} permissions: actions: read contents: read packages: read # Check existing pr-merge tags before a typed refresh rebuilds. pull-requests: read steps: - name: Harden runner uses: step-security/harden-runner@aebdcf6156ab6691adf63218240e476564a1ed4c # v2.23.0 with: egress-policy: audit - name: Check out trusted workflow helpers uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: ref: ${{ github.event.repository.default_branch }} persist-credentials: false - name: Set up canonical GitHub CLI uses: ./.github/actions/setup-gh - name: Set up canonical Python uses: ./.github/actions/setup-python - name: Derive image tags id: meta env: GH_TOKEN: ${{ github.token }} EVENT_HEAD_SHA: ${{ github.event.pull_request.head.sha || github.event.client_payload.head_sha || '' }} EVENT_HEAD_BRANCH: ${{ github.event.workflow_run.head_branch || '' }} EVENT_PR_NUMBER: ${{ github.event.pull_request.number || github.event.client_payload.pr_number || '' }} EVENT_BASE_REF: ${{ github.event.pull_request.base.ref || github.event.client_payload.base_ref || '' }} EVENT_BASE_SHA: ${{ github.event.pull_request.base.sha || github.event.client_payload.base_sha || '' }} EVENT_MERGE_SHA: ${{ github.event.client_payload.merge_sha || '' }} EVENT_ACTION: ${{ github.event.action || '' }} DEFAULT_BRANCH: ${{ github.event.repository.default_branch }} run: | set -euo pipefail EVENT_NAME="${{ github.event_name }}" PR_NUMBER="" BASE_REF="" BASE_SHA="" MERGE_SHA="" if [ "$EVENT_NAME" = "pull_request" ]; then PR_NUMBER="$EVENT_PR_NUMBER" BASE_REF="$EVENT_BASE_REF" BASE_SHA="$EVENT_BASE_SHA" HEAD_SHA="$EVENT_HEAD_SHA" HEAD_BRANCH="" MERGE_SHA="${GITHUB_SHA}" CHECKOUT_REF="$MERGE_SHA" [[ "$MERGE_SHA" =~ ^[0-9a-f]{40}$ ]] || { echo "PR merge SHA is not a lowercase 40-character commit SHA." >&2 exit 1 } [[ "$BASE_SHA" =~ ^[0-9a-f]{40}$ && "$HEAD_SHA" =~ ^[0-9a-f]{40}$ ]] || { echo "PR event base/head SHAs are not lowercase 40-character commit SHAs." >&2 exit 1 } exact_merge() { gh api "repos/${GITHUB_REPOSITORY}/commits/$1" | jq -e \ --arg base_sha "$BASE_SHA" \ --arg head_sha "$HEAD_SHA" \ --arg merge_sha "$1" \ '.sha == $merge_sha and (.parents | type) == "array" and (.parents | length) == 2 and .parents[0].sha == $base_sha and .parents[1].sha == $head_sha' \ >/dev/null } if ! exact_merge "$MERGE_SHA"; then # A retarget edit can carry the previous test merge. Build GitHub's # recomputed merge instead when its parents are exactly the event's. MERGE_SHA="" for attempt in 1 2 3 4 5 6; do live_merge="$(gh api "repos/${GITHUB_REPOSITORY}/pulls/${PR_NUMBER}" --jq '.merge_commit_sha // ""')" || live_merge="" if [[ "$live_merge" =~ ^[0-9a-f]{40}$ ]] && exact_merge "$live_merge"; then MERGE_SHA="$live_merge" break fi (( attempt < 6 )) && sleep 10 done [[ -n "$MERGE_SHA" ]] || { echo "No PR test merge has the event's exact base/head parents; refusing a stale PR artifact." >&2 exit 1 } CHECKOUT_REF="$MERGE_SHA" echo "Event merge was stale; building recomputed test merge ${MERGE_SHA}." fi elif [ "$EVENT_NAME" = "repository_dispatch" ]; then [[ "$EVENT_ACTION" == "pr-runtime-base-refresh" ]] || { echo "Runtime PR refresh requires the typed pr-runtime-base-refresh dispatch." >&2 exit 1 } [[ "$GITHUB_REF" == "refs/heads/${DEFAULT_BRANCH}" ]] || { echo "Runtime PR refresh must run from the repository default branch." >&2 exit 1 } PR_NUMBER="$EVENT_PR_NUMBER" BASE_REF="$EVENT_BASE_REF" BASE_SHA="$EVENT_BASE_SHA" MERGE_SHA="$EVENT_MERGE_SHA" HEAD_SHA="$EVENT_HEAD_SHA" HEAD_BRANCH="" CHECKOUT_REF="$MERGE_SHA" # The payload is untrusted: any writer can send this dispatch. # Everything below is rechecked against the live API. [[ "$PR_NUMBER" =~ ^[1-9][0-9]{0,50}$ ]] || { echo "Runtime PR refresh payload has an invalid pull request number." >&2 exit 1 } git check-ref-format "refs/heads/${BASE_REF}" >/dev/null || { echo "Runtime PR refresh payload has an invalid base ref." >&2 exit 1 } for sha_name in BASE_SHA HEAD_SHA MERGE_SHA; do sha_value="${!sha_name}" [[ "$sha_value" =~ ^[0-9a-f]{40}$ ]] || { echo "Runtime PR refresh payload has an invalid ${sha_name}." >&2 exit 1 } done encoded_base_ref="$(python3 -c 'import sys; from urllib.parse import quote; print(quote(sys.argv[1], safe="/"))' "$BASE_REF")" current_base_ref_json="$(gh api "repos/${GITHUB_REPOSITORY}/git/ref/heads/${encoded_base_ref}")" jq -e \ --arg base_sha "$BASE_SHA" \ --arg base_ref "refs/heads/${BASE_REF}" \ '.ref == $base_ref and .object.sha == $base_sha' \ <<<"$current_base_ref_json" >/dev/null || { echo "Runtime PR refresh base SHA is not the current ${BASE_REF} branch ref." >&2 exit 1 } pull_request_json="$(gh api "repos/${GITHUB_REPOSITORY}/pulls/${PR_NUMBER}")" jq -e \ --arg repository "$GITHUB_REPOSITORY" \ --arg base_ref "$BASE_REF" \ --arg head_sha "$HEAD_SHA" \ --arg merge_sha "$MERGE_SHA" \ '( .state == "open" and .base.ref == $base_ref and .base.repo.full_name == $repository and .head.sha == $head_sha and .head.repo.full_name == $repository and (.mergeable | type) == "boolean" and .mergeable == true and (.mergeable_state | type) == "string" and .mergeable_state != "dirty" and .mergeable_state != "conflicting" and .mergeable_state != "unknown" and .merge_commit_sha == $merge_sha )' <<<"$pull_request_json" >/dev/null || { echo "Runtime PR refresh payload is stale, conflicted, fork-owned, closed, or has an invalid merge tuple." >&2 exit 1 } merge_commit_json="$(gh api "repos/${GITHUB_REPOSITORY}/commits/${MERGE_SHA}")" jq -e \ --arg base_sha "$BASE_SHA" \ --arg head_sha "$HEAD_SHA" \ --arg merge_sha "$MERGE_SHA" \ '.sha == $merge_sha and (.parents | type) == "array" and (.parents | length) == 2 and .parents[0].sha == $base_sha and .parents[1].sha == $head_sha' \ <<<"$merge_commit_json" >/dev/null || { echo "Runtime PR refresh merge commit does not have the exact current base/head parents." >&2 exit 1 } elif [ "${{ github.event_name }}" = "workflow_run" ]; then [[ "${{ github.event.workflow_run.event }}" == "push" ]] || { echo "Runtime branch publication requires a CI push workflow run." >&2 exit 1 } [[ "${{ github.event.workflow_run.conclusion }}" == "success" ]] || { echo "Runtime branch publication requires a successful CI workflow run." >&2 exit 1 } HEAD_SHA="${EVENT_HEAD_SHA:-${{ github.event.workflow_run.head_sha }}}" HEAD_BRANCH="$EVENT_HEAD_BRANCH" CHECKOUT_REF="$HEAD_SHA" else HEAD_SHA="${GITHUB_SHA}" CHECKOUT_REF="${GITHUB_SHA}" HEAD_BRANCH="${GITHUB_REF_NAME}" fi [[ "$HEAD_SHA" =~ ^[0-9a-f]{40}$ ]] || { echo "Runtime publication head SHA is not a lowercase 40-character commit SHA." >&2 exit 1 } if [ "$EVENT_NAME" != "pull_request" ] && [ "$EVENT_NAME" != "repository_dispatch" ]; then [[ "$HEAD_BRANCH" == main || "$HEAD_BRANCH" == develop ]] || { echo "Runtime branch publication is restricted to main or develop." >&2 exit 1 } current_head="$(gh api "repos/${GITHUB_REPOSITORY}/git/ref/heads/${HEAD_BRANCH}" --jq '.object.sha')" [[ "$current_head" =~ ^[0-9a-f]{40}$ ]] || { echo "Runtime publication could not prove the live ${HEAD_BRANCH} head." >&2 exit 1 } if [[ "$current_head" != "$HEAD_SHA" ]]; then echo "Skipping runtime builds for obsolete ${HEAD_BRANCH}@${HEAD_SHA}; current head is ${current_head}." exit 0 fi fi # A delayed run of a superseded comparison (older head, or base before a # retarget) must not enter the per-PR smoke groups, where it would cancel # the current comparison's smoke. An unreadable PR counts as current so # the gate still gets proof. HEAD_CURRENT=true if [ "$EVENT_NAME" = "pull_request" ]; then live_pr="$(gh api "repos/${GITHUB_REPOSITORY}/pulls/${PR_NUMBER}" --jq '"\(.head.sha // "") \(.base.ref // "")"')" || live_pr="" read -r live_head live_base_ref <<<"$live_pr" || true if [[ -n "${live_head:-}" && ( "$live_head" != "$HEAD_SHA" || "${live_base_ref:-}" != "$BASE_REF" ) ]]; then HEAD_CURRENT=false echo "::notice::PR now compares ${live_head} against ${live_base_ref}; skipping smoke for superseded ${HEAD_SHA} against ${BASE_REF}." fi fi if [ "$EVENT_NAME" = "pull_request" ] || [ "$EVENT_NAME" = "repository_dispatch" ]; then IMAGE_TAG="pr-merge-${MERGE_SHA}" else IMAGE_TAG="${HEAD_SHA}" fi CANDIDATE_TAG="candidate-${HEAD_SHA}-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}" if [ "$EVENT_NAME" = "pull_request" ] || [ "$EVENT_NAME" = "repository_dispatch" ]; then BASE_IMAGE="ghcr.io/benhook1013/firemud-base:${MERGE_SHA}" else BASE_IMAGE="ghcr.io/benhook1013/firemud-base:${CANDIDATE_TAG}" fi { echo "pr_number=${PR_NUMBER}" echo "base_ref=${BASE_REF}" echo "base_sha=${BASE_SHA}" echo "head_sha=${HEAD_SHA}" echo "merge_sha=${MERGE_SHA}" echo "head_branch=${HEAD_BRANCH}" echo "checkout_ref=${CHECKOUT_REF}" echo "head_current=${HEAD_CURRENT}" echo "image_tag=${IMAGE_TAG}" echo "candidate_tag=${CANDIDATE_TAG}" echo "base_image=${BASE_IMAGE}" } >> "$GITHUB_OUTPUT" - name: Log in to GHCR for the publication check if: ${{ github.event_name == 'repository_dispatch' }} uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0 with: registry: ghcr.io username: ${{ github.actor }} password: ${{ secrets.GITHUB_TOKEN }} # One rule: build only when no pr-merge tag exists. Tags are write-once and # the publisher serializes per merge and leaves a complete set alone, so a # duplicate build only costs CI time. Any existing tag means a publisher has # already started; a rebuild cannot complete a partial set. - name: Skip a refresh whose PR merge images are already being published id: published if: ${{ github.event_name == 'repository_dispatch' }} env: GHCR_USERNAME: ${{ github.actor }} GHCR_TOKEN: ${{ secrets.GITHUB_TOKEN }} MERGE_SHA: ${{ steps.meta.outputs.merge_sha }} run: | set -euo pipefail source ./dev-tools/hosted/shared/protected-runtime-image-registry.sh pr_merge_publication_state "$MERGE_SHA" state case "$state" in none) echo "skip_build=false" >> "$GITHUB_OUTPUT" ;; complete) echo "skip_build=true" >> "$GITHUB_OUTPUT" echo "All pr-merge-${MERGE_SHA} runtime images already exist; skipping the rebuild." ;; *) echo "skip_build=true" >> "$GITHUB_OUTPUT" echo "::warning title=Partial PR runtime publication::Some pr-merge-${MERGE_SHA} tags exist. A running publisher will finish them; otherwise this is a manual hold: re-run the original publisher while its source archive exists, or delete the partial tags or push a new PR head." ;; esac - name: Verify successful CI push for manual publication if: ${{ github.event_name == 'workflow_dispatch' && steps.meta.outputs.head_sha != '' }} env: GH_TOKEN: ${{ github.token }} EXPECTED_SHA: ${{ steps.meta.outputs.head_sha }} EXPECTED_BRANCH: ${{ steps.meta.outputs.head_branch }} run: | set -euo pipefail ci_runs="$(gh api --paginate --slurp \ "repos/${GITHUB_REPOSITORY}/actions/workflows/ci.yml/runs?event=push&head_sha=${EXPECTED_SHA}&per_page=100")" jq -e \ --arg expected_sha "$EXPECTED_SHA" \ --arg expected_branch "$EXPECTED_BRANCH" \ '[.[].workflow_runs[]?] | any(.[]; .head_sha == $expected_sha and .head_branch == $expected_branch and .event == "push" and .status == "completed" and .conclusion == "success")' \ <<<"$ci_runs" >/dev/null || { echo "No successful CI push run exists for manual runtime publication ${EXPECTED_BRANCH}@${EXPECTED_SHA}." >&2 exit 1 } - name: Detect PR smoke scopes id: smoke_scope uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 env: VERIFIED_BASE_SHA: ${{ steps.meta.outputs.base_sha }} VERIFIED_MERGE_SHA: ${{ steps.meta.outputs.merge_sha }} with: script: | let runtimeSmokeRequired = true; let controllerSmokeRequired = true; if (context.eventName === "pull_request" || context.eventName === "repository_dispatch") { try { let changedFiles; { // Classify the verified test merge this run builds; a live PR // file list can already describe a later head. const {VERIFIED_BASE_SHA: base, VERIFIED_MERGE_SHA: merge} = process.env; if (![base, merge].every(sha => typeof sha === "string" && /^[0-9a-f]{40}$/.test(sha))) { throw new Error("missing immutable test-merge comparison"); } const {data: comparison} = await github.request("GET /repos/{owner}/{repo}/compare/{basehead}", { ...context.repo, basehead: `${base}...${merge}`, page: 1, per_page: 1, request: {signal: AbortSignal.timeout(10000)}, }); if (comparison?.base_commit?.sha !== base || comparison.merge_base_commit?.sha !== base || comparison.status !== "ahead" || !Array.isArray(comparison.files) || comparison.files.length >= 300) { throw new Error("incomplete immutable test-merge file comparison"); } changedFiles = comparison.files; } const validFileEntries = changedFiles.every((file) => file && typeof file.filename === "string" && file.filename.length > 0 && (file.previous_filename === undefined || (typeof file.previous_filename === "string" && file.previous_filename.length > 0)) ); if (!validFileEntries) { core.warning("PR smoke scope detection was incomplete; running both local smokes."); } else { const paths = changedFiles.flatMap((file) => [file.filename, file.previous_filename].filter(Boolean) ); const runtimePrefixes = [ "buildSrc/", "docker/", "dev-tools/minio/", "dev-tools/smoke/", "gradle/", "protos/", ".github/actions/load-workflow-tool-versions/", ".github/actions/setup-python/", ".github/actions/setup-gh/", ".env.sample", ]; const workflowToolAuthorityPath = "config/workflow-tool-versions.env"; const runtimeFiles = new Set([ ".dockerignore", ".github/workflows/publish-pr-runtime-images.yml", ".github/workflows/runtime-images.yml", ".github/workflows/smoke-full.yml", ".github/actions/load-workflow-tool-versions/action.yml", ".python-version", "build.gradle.kts", "config/python/smoke-requirements.txt", "config/python/smoke-requirements.in", "dev-tools/build-compose-service-jars.sh", "dev-tools/validation/run-gradle-with-dependency-recovery.sh", "dev-tools/validation/run-locked-gradle.sh", "dev-tools/validation/gradle-run-supervisor.py", "dev-tools/build-local-smoke-images.sh", "dev-tools/backups/verify-backups.sh", "dev-tools/backups/pg-dump-s3-selection.shlib", "dev-tools/backups/smoke-backup-verifier-image.sh", "dev-tools/certs/generate-dev-certs.sh", "dev-tools/verify-compose-health.sh", "dev-tools/verify-fresh-bootstrap.sh", "dev-tools/verify-restart-state.sh", "dev-tools/verify-smoke-images.sh", "gradle.properties", "docker/backup-verifier.Dockerfile", "gradlew", "gradlew.bat", "settings.gradle.kts", ]); const controllerPrefixes = [ "buildSrc/", "gradle/", "services/hosted-environment-identity-controller/", ]; const controllerFiles = new Set([ ".dockerignore", ".github/workflows/runtime-images.yml", "build.gradle.kts", "dev-tools/hosted/controller/smoke-paused-controller-image.sh", "docker/base.Dockerfile", "gradle.properties", "gradlew", "gradlew.bat", "settings.gradle.kts", ]); const authorityChanged = paths.includes(workflowToolAuthorityPath); const nonAuthorityPaths = paths.filter( (path) => path !== workflowToolAuthorityPath ); runtimeSmokeRequired = nonAuthorityPaths.some( (path) => runtimeFiles.has(path) || runtimePrefixes.some((prefix) => path.startsWith(prefix)) || (path.startsWith("services/") && !path.startsWith( "services/hosted-environment-identity-controller/" )) ); runtimeSmokeRequired = runtimeSmokeRequired || authorityChanged; controllerSmokeRequired = paths.some( (path) => controllerFiles.has(path) || controllerPrefixes.some((prefix) => path.startsWith(prefix)) ); } } catch (error) { core.warning( `PR smoke scope detection failed; running both local smokes: ${error.message}` ); } } core.setOutput("runtime_smoke_required", String(runtimeSmokeRequired)); core.setOutput("controller_smoke_required", String(controllerSmokeRequired)); dispatch-pr-base-refreshes: name: Dispatch PR Base Refreshes if: ${{ github.event_name == 'workflow_run' && github.event.workflow_run.status == 'completed' && (github.event.workflow_run.event == 'pull_request' || (github.event.workflow_run.event == 'push' && (github.event.workflow_run.head_branch == 'main' || github.event.workflow_run.head_branch == 'develop'))) && github.event.workflow_run.head_repository.full_name == github.repository }} runs-on: ubuntu-latest timeout-minutes: 15 permissions: actions: read contents: write pull-requests: read steps: - name: Harden runner uses: step-security/harden-runner@aebdcf6156ab6691adf63218240e476564a1ed4c # v2.23.0 with: egress-policy: audit - name: Dispatch exact PR runtime refreshes and preview reconciles uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 with: script: | const workflowRun = context.payload.workflow_run; const refreshBranch = workflowRun.head_branch; const refreshSha = workflowRun.head_sha; const shaPattern = /^[0-9a-f]{40}$/; const runtimePrefixes = [ "buildSrc/", "docker/", "dev-tools/minio/", "dev-tools/smoke/", "gradle/", "protos/", ".github/actions/load-workflow-tool-versions/", ".github/actions/setup-python/", ".github/actions/setup-gh/", ".env.sample", ]; const runtimeFiles = new Set([ ".dockerignore", ".github/workflows/publish-pr-runtime-images.yml", ".github/workflows/runtime-images.yml", ".github/workflows/smoke-full.yml", ".github/actions/load-workflow-tool-versions/action.yml", ".python-version", "build.gradle.kts", "config/workflow-tool-versions.env", "config/python/smoke-requirements.txt", "config/python/smoke-requirements.in", "dev-tools/build-compose-service-jars.sh", "dev-tools/validation/run-gradle-with-dependency-recovery.sh", "dev-tools/validation/run-locked-gradle.sh", "dev-tools/validation/gradle-run-supervisor.py", "dev-tools/build-local-smoke-images.sh", "dev-tools/backups/verify-backups.sh", "dev-tools/backups/pg-dump-s3-selection.shlib", "dev-tools/backups/smoke-backup-verifier-image.sh", "dev-tools/certs/generate-dev-certs.sh", "dev-tools/hosted/controller/smoke-paused-controller-image.sh", "dev-tools/verify-compose-health.sh", "dev-tools/verify-fresh-bootstrap.sh", "dev-tools/verify-restart-state.sh", "dev-tools/verify-smoke-images.sh", "gradle.properties", "gradlew", "gradlew.bat", "settings.gradle.kts", ]); const waitForMergeRefresh = async () => { await new Promise((resolve) => setTimeout(resolve, 2000)); }; const hasRuntimeChange = async (pullRequest) => { const files = await github.paginate( github.rest.pulls.listFiles, { ...context.repo, pull_number: pullRequest.number, per_page: 100, }, (response) => response.data ); const expectedFileCount = pullRequest.changed_files; const validFileEntries = Number.isInteger(expectedFileCount) && files.length === expectedFileCount && files.every((file) => file && typeof file.filename === "string" && file.filename.length > 0 && (file.previous_filename === undefined || (typeof file.previous_filename === "string" && file.previous_filename.length > 0)) ); if (!validFileEntries) { core.warning(`PR #${pullRequest.number} changed-file metadata was incomplete; refreshing its runtime images.`); return true; } // A main/develop PR deploys base images for unpackaged Markdown, as the // preview resolver decides; stacked PRs always need their merge images. const protectedBase = ["main", "develop"].includes(pullRequest.base?.ref); return files.flatMap((file) => [file.filename, file.previous_filename].filter(Boolean)).some((path) => !(protectedBase && path.endsWith(".md") && !path.includes("/src/main/")) && ( runtimeFiles.has(path) || runtimePrefixes.some((prefix) => path.startsWith(prefix)) || path.startsWith("services/") ) ); }; const dependencyBotAuthors = new Set([ "app/dependabot", "dependabot[bot]", "app/renovate", "renovate[bot]", ]); const isPreviewEligible = (pullRequest) => { const labels = pullRequest.labels; return typeof pullRequest.user?.login === "string" && pullRequest.user.login.length > 0 && !dependencyBotAuthors.has(pullRequest.user.login) && Array.isArray(labels) && labels.every((label) => label && typeof label.name === "string") && (["main", "develop"].includes(pullRequest.base?.ref) || labels.some((label) => label.name === "preview:priority")); }; const resolveExactMerge = async (number, baseBranch = refreshBranch, baseSha = refreshSha, expectedHeadSha = null) => { for (let attempt = 1; attempt <= 5; attempt += 1) { const response = await github.rest.pulls.get({ ...context.repo, pull_number: number, }); const pullRequest = response.data; const currentHeadSha = pullRequest.head?.sha; const currentBaseRef = pullRequest.base?.ref; const headRepository = pullRequest.head?.repo?.full_name; const baseRepository = pullRequest.base?.repo?.full_name; if (pullRequest.state !== "open" || headRepository !== context.payload.repository.full_name || baseRepository !== context.payload.repository.full_name || currentBaseRef !== baseBranch || !shaPattern.test(currentHeadSha || "") || (expectedHeadSha !== null && currentHeadSha !== expectedHeadSha)) { return null; } const mergeableState = typeof pullRequest.mergeable_state === "string" ? pullRequest.mergeable_state : pullRequest.mergeable_state === null ? "unknown" : "invalid"; if (pullRequest.mergeable === false || mergeableState === "dirty" || mergeableState === "conflicting") { core.warning(`Skipping PR #${number}: GitHub reports a merge conflict.`); return null; } if (pullRequest.mergeable === null || mergeableState === "unknown") { if (attempt < 5) { await waitForMergeRefresh(); continue; } core.warning(`Skipping PR #${number}: GitHub did not produce a ready merge tuple.`); return null; } if (pullRequest.mergeable !== true || mergeableState === "invalid") { core.warning(`Skipping PR #${number}: GitHub returned invalid merge metadata.`); return null; } const mergeSha = pullRequest.merge_commit_sha; if (!shaPattern.test(mergeSha || "")) { if (attempt < 5) { await waitForMergeRefresh(); continue; } core.warning(`Skipping PR #${number}: merge SHA is null or invalid.`); return null; } try { const commit = await github.rest.repos.getCommit({ ...context.repo, ref: mergeSha, }); const parents = commit.data.parents?.map((parent) => parent.sha) || []; if (commit.data.sha !== mergeSha || parents.length !== 2 || parents[0] !== baseSha || parents[1] !== currentHeadSha) { if (attempt < 5) { await waitForMergeRefresh(); continue; } core.warning(`Skipping PR #${number}: merge commit parents do not match the current base/head.`); return null; } } catch (error) { if (attempt < 5) { await waitForMergeRefresh(); continue; } core.warning(`Skipping PR #${number}: exact merge commit could not be read (${error.message}).`); return null; } return { tuple: { prNumber: String(number), baseRef: baseBranch, baseSha, headSha: currentHeadSha, mergeSha, }, pullRequest, }; } return null; }; if (!shaPattern.test(refreshSha) || typeof refreshBranch !== "string" || refreshBranch.length === 0) { core.setFailed("Completed CI callback did not identify a branch and lowercase SHA."); return; } let sourcePrNumber = null; if (workflowRun.event === "pull_request") { // Completion is a reconcile signal only for a substantive CI attempt. // Metadata edits also complete CI, but must never reconstruct runtime. const positiveInteger = (value) => Number.isSafeInteger(value) && value > 0; const ciPath = ".github/workflows/ci.yml"; const ciName = "CI — Validation"; const titleMatch = /^CI — Validation pr-([1-9][0-9]*) base-([0-9a-f]{40}) head-([0-9a-f]{40})$/.exec(workflowRun.display_title || ""); const matchesSource = (run) => positiveInteger(workflowRun.id) && positiveInteger(workflowRun.run_attempt) && positiveInteger(workflowRun.workflow_id) && run.id === workflowRun.id && run.run_attempt === workflowRun.run_attempt && run.workflow_id === workflowRun.workflow_id && run.event === "pull_request" && run.status === "completed" && typeof run.conclusion === "string" && run.conclusion.length > 0 && run.repository?.full_name === context.payload.repository.full_name && run.head_repository?.full_name === context.payload.repository.full_name && run.head_branch === refreshBranch && run.head_sha === refreshSha && run.display_title === workflowRun.display_title && [ciName, workflowRun.display_title].includes(run.name) && (run.path === ciPath || (typeof run.path === "string" && run.path.startsWith(`${ciPath}@`) && run.path.length > ciPath.length + 1)); if (!titleMatch || titleMatch[3] !== refreshSha) { core.warning("Skipping PR runtime reconciliation: callback lacks exact CI PR/base/head title metadata."); return; } const {data: ciWorkflow} = await github.rest.actions.getWorkflow({ ...context.repo, workflow_id: "ci.yml", }); const {data: source} = await github.rest.actions.getWorkflowRun({ ...context.repo, run_id: workflowRun.id, }); if (ciWorkflow.id !== workflowRun.workflow_id || ciWorkflow.path !== ciPath || ciWorkflow.name !== ciName || !matchesSource(source)) { core.warning("Skipping PR runtime reconciliation: current CI workflow/run identity differs from callback."); return; } const jobs = await github.paginate( "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs", {...context.repo, run_id: source.id, attempt_number: source.run_attempt, per_page: 100} ); const gates = jobs.filter((job) => job.name === "Validation Gate"); const gate = gates.length === 1 ? gates[0] : null; const preservation = gate?.steps?.filter((step) => step.name === "Preserve successful required gate on metadata-only edit") || []; const enforcement = gate?.steps?.filter((step) => step.name === "Enforce validation success") || []; const checkPrefix = `https://api.github.com/repos/${context.payload.repository.full_name}/check-runs/`; if (!gate || !positiveInteger(gate.id) || gate.run_id !== source.id || gate.run_attempt !== source.run_attempt || gate.head_sha !== source.head_sha || ![ciName, source.display_title].includes(gate.workflow_name) || gate.status !== "completed" || typeof gate.check_run_url !== "string" || !gate.check_run_url.startsWith(checkPrefix) || !/^[1-9][0-9]*$/.test(gate.check_run_url.slice(checkPrefix.length)) || preservation.length !== 1 || preservation[0].status !== "completed" || preservation[0].conclusion !== "skipped" || enforcement.length !== 1 || enforcement[0].status !== "completed" || !["success", "failure"].includes(enforcement[0].conclusion)) { core.info("Skipping PR runtime reconciliation: exact CI attempt is metadata-only or lacks substantive native gate evidence."); return; } const {data: latest} = await github.rest.actions.getWorkflowRun({ ...context.repo, run_id: source.id, }); if (!matchesSource(latest)) { core.warning("Skipping PR runtime reconciliation: CI attempt was superseded during classification."); return; } sourcePrNumber = titleMatch[1]; } let currentBranch; try { currentBranch = await github.rest.git.getRef({ ...context.repo, ref: `heads/${refreshBranch}`, }); } catch (error) { if (error.status !== 404) throw error; core.info(`Skipping obsolete CI callback: branch ${refreshBranch} no longer exists.`); return; } if (currentBranch.data.object?.sha !== refreshSha) { core.warning(`Skipping PR base refresh: ${refreshBranch} advanced beyond the completed CI callback ${refreshSha}.`); return; } // Protected push callbacks own dependent fan-out; PR callbacks for // those heads still reconcile their own exact source PR below. const protectedPrHead = workflowRun.event === "pull_request" && ["main", "develop"].includes(refreshBranch); const pullRequests = protectedPrHead ? [] : await github.paginate( github.rest.pulls.list, { ...context.repo, state: "open", base: refreshBranch, per_page: 100, }, (response) => response.data ); const refreshTargets = []; for (const listedPullRequest of pullRequests) { if (listedPullRequest.state !== "open" || listedPullRequest.base?.ref !== refreshBranch || listedPullRequest.head?.repo?.full_name !== context.payload.repository.full_name || listedPullRequest.base?.repo?.full_name !== context.payload.repository.full_name) { continue; } const resolved = await resolveExactMerge(listedPullRequest.number); if (resolved) { refreshTargets.push(resolved); } } if (workflowRun.event === "pull_request") { // A retarget/edit can carry an unusable event merge SHA. CI completion // is only a reconcile signal: re-read its source's current exact tuple. const sourcePullRequests = await github.paginate( github.rest.pulls.list, { ...context.repo, state: "open", head: `${context.repo.owner}:${refreshBranch}`, per_page: 100, }, (response) => response.data ); for (const source of sourcePullRequests) { if (String(source.number) !== sourcePrNumber || source.state !== "open" || source.head?.sha !== refreshSha || source.head?.ref !== refreshBranch || source.head?.repo?.full_name !== context.payload.repository.full_name || source.base?.repo?.full_name !== context.payload.repository.full_name || typeof source.base?.ref !== "string" || source.base.ref.length === 0) { continue; } const sourceBase = await github.rest.git.getRef({ ...context.repo, ref: `heads/${source.base.ref}`, }); const sourceBaseSha = sourceBase.data.object?.sha; if (!shaPattern.test(sourceBaseSha || "")) { core.warning(`Skipping source PR #${source.number}: current base ref SHA is invalid.`); continue; } const resolved = await resolveExactMerge(source.number, source.base.ref, sourceBaseSha, refreshSha); if (resolved && !refreshTargets.some((target) => target.tuple.prNumber === resolved.tuple.prNumber)) { refreshTargets.push(resolved); } } } const dispatchFailures = []; const dispatch = async (eventType, payload) => { try { await github.rest.repos.createDispatchEvent({ ...context.repo, event_type: eventType, client_payload: payload, }); } catch (error) { const failure = `${eventType} for PR #${payload.pr_number}: ${error.message}`; dispatchFailures.push(failure); core.warning(failure); } }; for (const {tuple, pullRequest} of refreshTargets) { const target = { pr_number: tuple.prNumber, base_ref: tuple.baseRef, base_sha: tuple.baseSha, head_sha: tuple.headSha, merge_sha: tuple.mergeSha, }; if (await hasRuntimeChange(pullRequest)) { // The receiver's concurrency group collapses duplicates and it // skips the build when the pr-merge tags already exist. core.info(`Dispatching PR runtime refresh for #${tuple.prNumber} (${tuple.baseRef} / ${tuple.mergeSha}).`); await dispatch("pr-runtime-base-refresh", target); } else { core.info(`Skipping PR runtime image refresh for #${tuple.prNumber}: no runtime-changing files.`); } if (!isPreviewEligible(pullRequest)) { core.info(`Skipping preview deploy reconciliation for #${tuple.prNumber}: target is not preview-eligible.`); continue; } core.info(`Dispatching preview deploy reconciliation for #${tuple.prNumber} (${tuple.baseSha} / ${tuple.headSha} / ${tuple.mergeSha}).`); await dispatch("preview-deploy", { ...target, action: "deploy", preview_domain: "preview.firedevops.net", }); } if (dispatchFailures.length) core.setFailed(dispatchFailures.join("\n")); build-base-image: name: Build Runtime Base Image needs: [image-meta] if: ${{ github.event_name != 'pull_request' && github.event_name != 'repository_dispatch' && needs.image-meta.result == 'success' && (needs.image-meta.outputs.head_branch == 'main' || needs.image-meta.outputs.head_branch == 'develop') }} runs-on: ubuntu-latest outputs: digest: ${{ steps.select_base_image_digest.outputs.digest }} permissions: # This job publishes the shared runtime base image to GHCR. contents: read packages: write steps: - name: Harden runner uses: step-security/harden-runner@aebdcf6156ab6691adf63218240e476564a1ed4c # v2.23.0 with: egress-policy: audit - name: ⬇️ Checkout Code uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: ref: ${{ needs.image-meta.outputs.checkout_ref }} persist-credentials: false - name: Set up Docker Buildx uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1 - name: Login to GHCR uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0 with: registry: ghcr.io username: ${{ github.actor }} password: ${{ secrets.GITHUB_TOKEN }} - name: Build and push runtime base image id: build_base_image_first continue-on-error: true uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0 with: context: . file: ./docker/base.Dockerfile push: true tags: ${{ needs.image-meta.outputs.base_image }} cache-from: | type=registry,ref=ghcr.io/benhook1013/firemud-base:buildcache type=registry,ref=ghcr.io/benhook1013/firemud-base:latest type=gha cache-to: | type=registry,ref=ghcr.io/benhook1013/firemud-base:buildcache,mode=max type=gha,mode=max - name: Retry build and push runtime base image id: build_base_image_retry if: ${{ steps.build_base_image_first.outcome == 'failure' }} uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0 with: context: . file: ./docker/base.Dockerfile push: true tags: ${{ needs.image-meta.outputs.base_image }} cache-from: | type=registry,ref=ghcr.io/benhook1013/firemud-base:buildcache type=registry,ref=ghcr.io/benhook1013/firemud-base:latest type=gha cache-to: | type=registry,ref=ghcr.io/benhook1013/firemud-base:buildcache,mode=max type=gha,mode=max - name: Select exact published runtime base digest id: select_base_image_digest if: ${{ !cancelled() }} env: FIRST_OUTCOME: ${{ steps.build_base_image_first.outcome }} FIRST_DIGEST: ${{ steps.build_base_image_first.outputs.digest }} RETRY_OUTCOME: ${{ steps.build_base_image_retry.outcome }} RETRY_DIGEST: ${{ steps.build_base_image_retry.outputs.digest }} run: | set -euo pipefail published_digests=() if [[ "$FIRST_OUTCOME" == "success" ]]; then published_digests+=("$FIRST_DIGEST") fi if [[ "$RETRY_OUTCOME" == "success" ]]; then published_digests+=("$RETRY_DIGEST") fi if ((${#published_digests[@]} != 1)); then echo "Expected exactly one successful runtime base-image publication digest." >&2 exit 1 fi base_image_digest="${published_digests[0]}" [[ "$base_image_digest" =~ ^sha256:[0-9a-f]{64}$ ]] || { echo "Runtime base-image publisher returned an invalid sha256 digest." >&2 exit 1 } echo "digest=$base_image_digest" >> "$GITHUB_OUTPUT" build-runtime-images: name: Build Runtime Images (${{ matrix.service }}) needs: [image-meta, build-base-image, select-protected-runtime-digests] if: ${{ github.event_name != 'pull_request' && github.event_name != 'repository_dispatch' && needs.image-meta.result == 'success' && needs.select-protected-runtime-digests.result == 'success' && needs.select-protected-runtime-digests.outputs.missing_services != '' && needs.select-protected-runtime-digests.outputs.missing_services != '[]' && (needs.image-meta.outputs.head_branch == 'main' || needs.image-meta.outputs.head_branch == 'develop') }} runs-on: ubuntu-latest permissions: # This job publishes only unique staging service tags. Canonical aliases # are written by publish-runtime-images after the exact candidate passes smoke. contents: read packages: write strategy: fail-fast: false matrix: service: ${{ fromJSON(needs.select-protected-runtime-digests.outputs.missing_services) }} steps: - name: Harden runner uses: step-security/harden-runner@aebdcf6156ab6691adf63218240e476564a1ed4c # v2.23.0 with: egress-policy: audit - name: ⬇️ Checkout Code uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: ref: ${{ needs.image-meta.outputs.checkout_ref }} persist-credentials: false - name: ⚙️ Set Up Java uses: actions/setup-java@d1374f8ac74474200d16ef8ecee22c7ae7a51880 # v6.3.0 with: distribution: 'temurin' java-version: '25' - name: ⚙️ Set Up Gradle uses: gradle/actions/setup-gradle@8da46b539cd8fe6ab27ca75128919a18d757604c # v6.4.1 with: build-scan-publish: true build-scan-terms-of-use-url: 'https://gradle.com/help/legal-terms-of-use' build-scan-terms-of-use-agree: 'yes' cache-read-only: false - name: Set up Python for Gradle recovery uses: ./.github/actions/setup-python with: requirements: none - name: Build service JAR run: bash ./dev-tools/validation/run-gradle-with-dependency-recovery.sh --runner ./gradlew -- :${{ matrix.service }}:bootJar - name: Set up Docker Buildx uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1 - name: Login to GHCR uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0 with: registry: ghcr.io username: ${{ github.actor }} password: ${{ secrets.GITHUB_TOKEN }} - name: Build and push runtime service image id: build_runtime_image_first continue-on-error: true uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0 with: context: ./services/${{ matrix.service }}/build/libs file: ./services/${{ matrix.service }}/Dockerfile push: true build-contexts: | repo_root=. build-args: | BASE_IMAGE=ghcr.io/benhook1013/firemud-base@${{ needs.build-base-image.outputs.digest }} tags: ghcr.io/benhook1013/${{ matrix.service }}:${{ needs.image-meta.outputs.candidate_tag }} cache-from: | type=registry,ref=ghcr.io/benhook1013/${{ matrix.service }}:buildcache type=registry,ref=ghcr.io/benhook1013/${{ matrix.service }}:latest type=gha cache-to: | type=registry,ref=ghcr.io/benhook1013/${{ matrix.service }}:buildcache,mode=max type=gha,mode=max - name: Retry build and push runtime service image if: ${{ steps.build_runtime_image_first.outcome == 'failure' }} uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0 with: context: ./services/${{ matrix.service }}/build/libs file: ./services/${{ matrix.service }}/Dockerfile push: true build-contexts: | repo_root=. build-args: | BASE_IMAGE=ghcr.io/benhook1013/firemud-base@${{ needs.build-base-image.outputs.digest }} tags: ghcr.io/benhook1013/${{ matrix.service }}:${{ needs.image-meta.outputs.candidate_tag }} cache-from: | type=registry,ref=ghcr.io/benhook1013/${{ matrix.service }}:buildcache type=registry,ref=ghcr.io/benhook1013/${{ matrix.service }}:latest type=gha cache-to: | type=registry,ref=ghcr.io/benhook1013/${{ matrix.service }}:buildcache,mode=max type=gha,mode=max build-backup-verifier: name: Build Backup Verifier Image needs: [image-meta] if: ${{ github.event_name != 'pull_request' && github.event_name != 'repository_dispatch' && needs.image-meta.result == 'success' && (needs.image-meta.outputs.head_branch == 'develop' || needs.image-meta.outputs.head_branch == 'main') }} runs-on: ubuntu-latest timeout-minutes: 15 outputs: image_id: ${{ steps.smoke.outputs.image_id }} permissions: contents: read env: BACKUP_VERIFIER_IMAGE: ghcr.io/benhook1013/backup-verifier:${{ needs.image-meta.outputs.image_tag }} steps: - name: Harden runner uses: step-security/harden-runner@aebdcf6156ab6691adf63218240e476564a1ed4c # v2.23.0 with: egress-policy: audit - name: Checkout trusted branch commit uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: ref: ${{ needs.image-meta.outputs.checkout_ref }} persist-credentials: false - name: Load workflow tool versions id: workflow-tool-versions uses: ./.github/actions/load-workflow-tool-versions - name: Build backup verifier image run: | docker build \ --file docker/backup-verifier.Dockerfile \ --tag "$BACKUP_VERIFIER_IMAGE" \ . - name: Smoke backup verifier image id: smoke env: VELERO_VERSION: ${{ steps.workflow-tool-versions.outputs.velero-version }} run: | set -euo pipefail bash ./dev-tools/backups/smoke-backup-verifier-image.sh "$BACKUP_VERIFIER_IMAGE" "$VELERO_VERSION" image_id="$(docker image inspect --format '{{.Id}}' "$BACKUP_VERIFIER_IMAGE")" [[ "$image_id" =~ ^sha256:[0-9a-f]{64}$ ]] || { echo "Backup verifier image did not return an exact image ID." >&2 exit 1 } echo "image_id=$image_id" >> "$GITHUB_OUTPUT" - name: Export exact verified backup verifier image artifact env: VERIFIED_IMAGE_ID: ${{ steps.smoke.outputs.image_id }} run: | set -euo pipefail current_image_id="$(docker image inspect --format '{{.Id}}' "$BACKUP_VERIFIER_IMAGE")" [[ "$current_image_id" == "$VERIFIED_IMAGE_ID" ]] || { echo "Backup verifier image changed after its smoke proof; refusing artifact export." >&2 exit 1 } docker save "$BACKUP_VERIFIER_IMAGE" | gzip -1 > "$RUNNER_TEMP/backup-verifier.tar.gz" - name: Upload exact verified backup verifier image artifact uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 with: name: backup-verifier-${{ needs.image-meta.outputs.image_tag }} path: ${{ runner.temp }}/backup-verifier.tar.gz if-no-files-found: error retention-days: 1 publish-backup-verifier: name: Publish Trusted Backup Verifier Image needs: [image-meta, build-backup-verifier] if: ${{ always() && github.event_name != 'pull_request' && github.event_name != 'repository_dispatch' && (needs.image-meta.outputs.head_branch == 'develop' || needs.image-meta.outputs.head_branch == 'main') && needs.image-meta.result == 'success' && needs.build-backup-verifier.result == 'success' }} runs-on: ubuntu-latest timeout-minutes: 15 permissions: contents: read packages: write id-token: write attestations: write env: BACKUP_VERIFIER_IMAGE_NAME: ghcr.io/benhook1013/backup-verifier BACKUP_VERIFIER_IMAGE: ghcr.io/benhook1013/backup-verifier:${{ needs.image-meta.outputs.image_tag }} steps: - name: Harden runner uses: step-security/harden-runner@aebdcf6156ab6691adf63218240e476564a1ed4c # v2.23.0 with: egress-policy: audit - name: Checkout trusted publication commit uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: ref: ${{ needs.image-meta.outputs.checkout_ref }} persist-credentials: false - name: Download exact verified backup verifier image artifact uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8 with: name: backup-verifier-${{ needs.image-meta.outputs.image_tag }} path: ${{ runner.temp }}/backup-verifier-artifact - name: Load and verify exact backup verifier image env: BACKUP_VERIFIER_ARCHIVE: ${{ runner.temp }}/backup-verifier-artifact/backup-verifier.tar.gz VERIFIED_IMAGE_ID: ${{ needs.build-backup-verifier.outputs.image_id }} run: | set -euo pipefail [[ -f "$BACKUP_VERIFIER_ARCHIVE" ]] || { echo "Verified backup verifier image artifact is missing." >&2 exit 1 } gzip -dc "$BACKUP_VERIFIER_ARCHIVE" | docker load loaded_image_id="$(docker image inspect --format '{{.Id}}' "$BACKUP_VERIFIER_IMAGE")" [[ "$loaded_image_id" == "$VERIFIED_IMAGE_ID" ]] || { echo "Loaded backup verifier image does not match the exact verified build image." >&2 exit 1 } - name: Login to GHCR uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0 with: registry: ghcr.io username: ${{ github.actor }} password: ${{ secrets.GITHUB_TOKEN }} - name: Publish exact verified backup verifier image id: publish run: | set -euo pipefail bash ./dev-tools/hosted/shared/push-verified-image.sh "$BACKUP_VERIFIER_IMAGE" - name: Attest trusted backup verifier image provenance uses: actions/attest@1e69f48acb82d1966a394da916b4c1698aa569d6 # v4.2.2 with: subject-name: ${{ env.BACKUP_VERIFIER_IMAGE_NAME }} subject-digest: ${{ steps.publish.outputs.digest }} push-to-registry: true create-storage-record: false build-hosted-identity-controller: name: Build Trusted Hosted Identity Controller needs: [image-meta, build-base-image] if: ${{ github.event_name != 'pull_request' && github.event_name != 'repository_dispatch' && (needs.image-meta.outputs.head_branch == 'develop' || needs.image-meta.outputs.head_branch == 'main') && needs.image-meta.result == 'success' && needs.build-base-image.result == 'success' }} runs-on: ubuntu-latest timeout-minutes: 25 outputs: image_id: ${{ steps.smoke.outputs.image_id }} permissions: contents: read packages: read env: CONTROLLER_IMAGE_NAME: ghcr.io/benhook1013/firemud-hosted-identity-controller CONTROLLER_IMAGE: ghcr.io/benhook1013/firemud-hosted-identity-controller:${{ needs.image-meta.outputs.image_tag }} steps: - name: Harden runner uses: step-security/harden-runner@aebdcf6156ab6691adf63218240e476564a1ed4c # v2.23.0 with: egress-policy: audit - name: Checkout trusted branch commit uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: ref: ${{ needs.image-meta.outputs.checkout_ref }} persist-credentials: false - name: Set up Java uses: actions/setup-java@d1374f8ac74474200d16ef8ecee22c7ae7a51880 # v6.3.0 with: distribution: 'temurin' java-version: '25' - name: Set up Gradle uses: gradle/actions/setup-gradle@8da46b539cd8fe6ab27ca75128919a18d757604c # v6.4.1 with: build-scan-publish: true build-scan-terms-of-use-url: 'https://gradle.com/help/legal-terms-of-use' build-scan-terms-of-use-agree: 'yes' cache-read-only: false - name: Login to GHCR uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0 with: registry: ghcr.io username: ${{ github.actor }} password: ${{ secrets.GITHUB_TOKEN }} - name: Set up Python for Gradle recovery uses: ./.github/actions/setup-python with: requirements: none - name: Build controller JAR and image locally run: | set -euo pipefail bash ./dev-tools/validation/run-gradle-with-dependency-recovery.sh --runner ./gradlew -- :hosted-environment-identity-controller:bootJar docker build \ --file services/hosted-environment-identity-controller/Dockerfile \ --build-arg BASE_IMAGE="ghcr.io/benhook1013/firemud-base@${{ needs.build-base-image.outputs.digest }}" \ --tag "$CONTROLLER_IMAGE" \ services/hosted-environment-identity-controller/build/libs - name: Smoke exact controller image id: smoke run: | set -euo pipefail smoked_image_id="$(bash ./dev-tools/hosted/controller/smoke-paused-controller-image.sh "$CONTROLLER_IMAGE")" local_image_id="$(docker image inspect --format '{{.Id}}' "$CONTROLLER_IMAGE")" [[ "$smoked_image_id" == "$local_image_id" ]] || { echo "Controller smoke did not execute the exact locally tagged image." >&2 exit 1 } echo "image_id=$local_image_id" >> "$GITHUB_OUTPUT" - name: Export exact verified controller image artifact env: VERIFIED_IMAGE_ID: ${{ steps.smoke.outputs.image_id }} run: | set -euo pipefail current_image_id="$(docker image inspect --format '{{.Id}}' "$CONTROLLER_IMAGE")" [[ "$current_image_id" == "$VERIFIED_IMAGE_ID" ]] || { echo "Controller image changed after its smoke proof; refusing artifact export." >&2 exit 1 } docker save "$CONTROLLER_IMAGE" | gzip -1 > "$RUNNER_TEMP/hosted-identity-controller.tar.gz" - name: Upload exact verified controller image artifact uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 with: name: hosted-identity-controller-${{ needs.image-meta.outputs.image_tag }} path: ${{ runner.temp }}/hosted-identity-controller.tar.gz if-no-files-found: error retention-days: 1 publish-hosted-identity-controller: name: Publish Trusted Hosted Identity Controller needs: [image-meta, build-base-image, build-hosted-identity-controller] if: ${{ always() && github.event_name != 'pull_request' && github.event_name != 'repository_dispatch' && (needs.image-meta.outputs.head_branch == 'develop' || needs.image-meta.outputs.head_branch == 'main') && needs.image-meta.result == 'success' && needs.build-base-image.result == 'success' && needs.build-hosted-identity-controller.result == 'success' }} runs-on: ubuntu-latest timeout-minutes: 25 permissions: contents: read packages: write id-token: write attestations: write env: CONTROLLER_IMAGE_NAME: ghcr.io/benhook1013/firemud-hosted-identity-controller CONTROLLER_IMAGE: ghcr.io/benhook1013/firemud-hosted-identity-controller:${{ needs.image-meta.outputs.image_tag }} steps: - name: Harden runner uses: step-security/harden-runner@aebdcf6156ab6691adf63218240e476564a1ed4c # v2.23.0 with: egress-policy: audit - name: Checkout trusted publication commit uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: ref: ${{ needs.image-meta.outputs.checkout_ref }} persist-credentials: false - name: Download exact verified controller image artifact uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8 with: name: hosted-identity-controller-${{ needs.image-meta.outputs.image_tag }} path: ${{ runner.temp }}/hosted-identity-controller-artifact - name: Load and verify exact controller image env: CONTROLLER_ARCHIVE: ${{ runner.temp }}/hosted-identity-controller-artifact/hosted-identity-controller.tar.gz VERIFIED_IMAGE_ID: ${{ needs.build-hosted-identity-controller.outputs.image_id }} run: | set -euo pipefail [[ -f "$CONTROLLER_ARCHIVE" ]] || { echo "Verified hosted identity controller image artifact is missing." >&2 exit 1 } gzip -dc "$CONTROLLER_ARCHIVE" | docker load loaded_image_id="$(docker image inspect --format '{{.Id}}' "$CONTROLLER_IMAGE")" [[ "$loaded_image_id" == "$VERIFIED_IMAGE_ID" ]] || { echo "Loaded controller image does not match the exact verified build image." >&2 exit 1 } - name: Login to GHCR uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0 with: registry: ghcr.io username: ${{ github.actor }} password: ${{ secrets.GITHUB_TOKEN }} - name: Publish exact verified controller image id: publish env: VERIFIED_IMAGE_ID: ${{ needs.build-hosted-identity-controller.outputs.image_id }} run: | set -euo pipefail current_image_id="$(docker image inspect --format '{{.Id}}' "$CONTROLLER_IMAGE")" [[ "$current_image_id" == "$VERIFIED_IMAGE_ID" ]] || { echo "Controller image changed after its verification proof; refusing publication." >&2 exit 1 } bash ./dev-tools/hosted/shared/push-verified-image.sh "$CONTROLLER_IMAGE" - name: Attest trusted controller image provenance uses: actions/attest@1e69f48acb82d1966a394da916b4c1698aa569d6 # v4.2.2 with: subject-name: ${{ env.CONTROLLER_IMAGE_NAME }} subject-digest: ${{ steps.publish.outputs.digest }} push-to-registry: true create-storage-record: false pr-local-smoke: outputs: publishable: ${{ steps.runtime-artifact.outcome == 'success' }} name: PR Full-Stack Smoke (runtime-required=${{ needs.image-meta.outputs.runtime_smoke_required }}) needs: [image-meta] if: ${{ (github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) && needs.image-meta.outputs.head_current == 'true') || (github.event_name == 'repository_dispatch' && needs.image-meta.outputs.skip_build == 'false') }} runs-on: ubuntu-latest timeout-minutes: 45 # No cancelling group: GitHub orders cancellation by arrival, so a delayed # older run could cancel the current one. image-meta skips superseded # comparisons before smoke instead. # A repository dispatch runs on the default branch but builds candidate code. cache-mode: read permissions: # PR-controlled source receives no registry or repository write credential. contents: read pull-requests: read # Read live PR labels for the PLAY waiver. env: COMPOSE_PROJECT_NAME: smoke-full-${{ github.run_id }}-${{ github.run_attempt }} SMOKE_TIMEOUT_SECONDS: 20 SMOKE_IMAGE_TAG: ${{ needs.image-meta.outputs.image_tag }} SMOKE_IMAGE_LOCAL_ONLY: 'true' SMOKE_MINIO_LOCAL_ONLY: 'true' SMOKE_MINIO_SERVER_IMAGE: >- firemud-minio-server-smoke:${{ github.run_id }}-${{ github.run_attempt }} SMOKE_MINIO_CLIENT_IMAGE: >- firemud-minio-client-smoke:${{ github.run_id }}-${{ github.run_attempt }} BACKUP_VERIFIER_IMAGE: ghcr.io/benhook1013/backup-verifier:${{ needs.image-meta.outputs.image_tag }} steps: - name: Harden runner uses: step-security/harden-runner@aebdcf6156ab6691adf63218240e476564a1ed4c # v2.23.0 with: egress-policy: audit - name: Checkout PR merge uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: ref: ${{ needs.image-meta.outputs.checkout_ref }} persist-credentials: false - name: Load workflow tool versions id: workflow-tool-versions uses: ./.github/actions/load-workflow-tool-versions - name: Set up canonical Python if: ${{ needs.image-meta.outputs.runtime_smoke_required == 'true' }} uses: ./.github/actions/setup-python with: requirements: smoke - name: Set up canonical GitHub CLI if: ${{ needs.image-meta.outputs.runtime_smoke_required == 'true' }} uses: ./.github/actions/setup-gh - name: Set up Java uses: actions/setup-java@d1374f8ac74474200d16ef8ecee22c7ae7a51880 # v6.3.0 with: distribution: 'temurin' java-version: '25' - name: Set up Gradle uses: gradle/actions/setup-gradle@8da46b539cd8fe6ab27ca75128919a18d757604c # v6.4.1 with: build-scan-publish: true build-scan-terms-of-use-url: 'https://gradle.com/help/legal-terms-of-use' build-scan-terms-of-use-agree: 'yes' cache-read-only: true - name: Build local PR runtime images id: runtime-images-build env: MERGE_SHA: ${{ needs.image-meta.outputs.merge_sha }} run: | set -euo pipefail bash ./dev-tools/build-local-smoke-images.sh "$MERGE_SHA" for service in \ account-service \ automation-scripting-service \ entity-management-service \ game-design-service \ game-logic-service \ game-session-service \ logging-admin-service \ social-groups-service \ spring-cloud-gateway \ tcp-proxy-service \ world-management-service; do docker tag \ "ghcr.io/benhook1013/${service}:${MERGE_SHA}" \ "ghcr.io/benhook1013/${service}:${SMOKE_IMAGE_TAG}" done - name: Retain runtime bootJar compile-failure evidence if: ${{ failure() && steps.runtime-images-build.outcome == 'failure' }} continue-on-error: true uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 with: name: runtime-bootjar-compile-failure-${{ github.run_id }}-attempt-${{ github.run_attempt }} path: ${{ steps.runtime-images-build.outputs.runtime_compile_failure_path || format('build/reports/compile-failure/runtime-bootjar/unavailable-{0}-{1}', github.run_id, github.run_attempt) }} if-no-files-found: warn retention-days: 3 - name: Build PR backup verifier image run: | docker build \ --file docker/backup-verifier.Dockerfile \ --tag "$BACKUP_VERIFIER_IMAGE" \ . - name: Smoke PR backup verifier image env: VELERO_VERSION: ${{ steps.workflow-tool-versions.outputs.velero-version }} run: bash ./dev-tools/backups/smoke-backup-verifier-image.sh "$BACKUP_VERIFIER_IMAGE" "$VELERO_VERSION" - name: Build and smoke pinned MinIO sources for PR Compose id: minio-source if: >- ${{ needs.image-meta.outputs.runtime_smoke_required == 'true' }} run: | bash ./dev-tools/minio/build-and-smoke-images.sh \ "$SMOKE_MINIO_SERVER_IMAGE" "$SMOKE_MINIO_CLIENT_IMAGE" - name: Run credential-free full-stack smoke id: runtime-smoke # The terminal guard admits only the classified, labeled transition failure. continue-on-error: true if: ${{ needs.image-meta.outputs.runtime_smoke_required == 'true' }} env: FIREMUD_SMOKE_ADMISSION_QUALIFICATION: held SMOKE_MINIO_SERVER_IMAGE_ID: >- ${{ steps.minio-source.outputs.server_image_id }} SMOKE_MINIO_CLIENT_IMAGE_ID: >- ${{ steps.minio-source.outputs.client_image_id }} run: bash ./dev-tools/verify-smoke-images.sh --keep-running # A recomputed retarget merge differs from the run title's merge, so the # publisher could never select its archive; the typed refresh publishes it. - name: Export fixed-tag preview image artifact if: ${{ success() && (needs.image-meta.outputs.runtime_smoke_required == 'false' || steps.runtime-smoke.outcome == 'success') && (github.event_name != 'pull_request' || needs.image-meta.outputs.merge_sha == github.sha) }} run: | service_manifest=/tmp/pr-runtime-services.txt provenance=/tmp/pr-runtime-provenance.json : > "$service_manifest" images=() for service in \ account-service \ automation-scripting-service \ entity-management-service \ game-design-service \ game-logic-service \ game-session-service \ logging-admin-service \ social-groups-service \ spring-cloud-gateway \ tcp-proxy-service \ world-management-service; do printf '%s\n' "$service" >> "$service_manifest" images+=("ghcr.io/benhook1013/${service}:${SMOKE_IMAGE_TAG}") done printf '%s\n' 'backup-verifier' >> "$service_manifest" images+=("$BACKUP_VERIFIER_IMAGE") PR_NUMBER="${{ needs.image-meta.outputs.pr_number }}" \ BASE_SHA="${{ needs.image-meta.outputs.base_sha }}" \ HEAD_SHA="${{ needs.image-meta.outputs.head_sha }}" \ MERGE_SHA="${{ needs.image-meta.outputs.merge_sha }}" \ IMAGE_TAG="${SMOKE_IMAGE_TAG}" \ SOURCE_RUN_ID="${{ github.run_id }}" \ REPOSITORY="${GITHUB_REPOSITORY}" \ PROVENANCE_PATH="$provenance" \ python3 - <<'PY' import json import os services = [ "account-service", "automation-scripting-service", "entity-management-service", "game-design-service", "game-logic-service", "game-session-service", "logging-admin-service", "social-groups-service", "spring-cloud-gateway", "tcp-proxy-service", "world-management-service", "backup-verifier", ] provenance = { "repository": os.environ["REPOSITORY"], "prNumber": int(os.environ["PR_NUMBER"]), "baseSha": os.environ["BASE_SHA"], "headSha": os.environ["HEAD_SHA"], "mergeSha": os.environ["MERGE_SHA"], "imageTag": os.environ["IMAGE_TAG"], "sourceRunId": int(os.environ["SOURCE_RUN_ID"]), "services": services, } with open(os.environ["PROVENANCE_PATH"], "w", encoding="utf-8") as output: json.dump(provenance, output, separators=(",", ":"), sort_keys=True) output.write("\n") PY docker save "${images[@]}" | gzip -1 > /tmp/pr-runtime-images.tar.gz - name: Upload preview image artifact id: runtime-artifact if: ${{ success() && (needs.image-meta.outputs.runtime_smoke_required == 'false' || steps.runtime-smoke.outcome == 'success') && (github.event_name != 'pull_request' || needs.image-meta.outputs.merge_sha == github.sha) }} uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 with: name: pr-runtime-images-${{ needs.image-meta.outputs.image_tag }} path: | /tmp/pr-runtime-images.tar.gz /tmp/pr-runtime-services.txt /tmp/pr-runtime-provenance.json if-no-files-found: error retention-days: 1 - name: Summarize secure PR runtime artifact if: ${{ success() && (needs.image-meta.outputs.runtime_smoke_required == 'false' || steps.runtime-smoke.outcome == 'success') && (github.event_name != 'pull_request' || needs.image-meta.outputs.merge_sha == github.sha) }} env: PR_NUMBER: ${{ needs.image-meta.outputs.pr_number }} BASE_SHA: ${{ needs.image-meta.outputs.base_sha }} HEAD_SHA: ${{ needs.image-meta.outputs.head_sha }} MERGE_SHA: ${{ needs.image-meta.outputs.merge_sha }} ARTIFACT_NAME: pr-runtime-images-${{ needs.image-meta.outputs.image_tag }} run: | { echo "### PR runtime images and applicable full-stack smoke" echo echo "- Pull request: #${PR_NUMBER}" echo "- Base SHA: \`${BASE_SHA}\`" echo "- PR head SHA: \`${HEAD_SHA}\`" echo "- Built PR merge SHA (full-stack smoke runs when required): \`${MERGE_SHA}\`" echo "- Merge-scoped publication tag: \`pr-merge-${MERGE_SHA}\`" echo "- Artifact: \`${ARTIFACT_NAME}\`" echo echo "This read-only PR workflow built the PR merge commit and runs full-stack smoke when required by change scope. The trusted default-branch publisher uploads only the exact merge-scoped artifact from this successful run." } >> "$GITHUB_STEP_SUMMARY" - name: Dump Docker Compose logs on failure if: >- ${{ always() && steps.runtime-smoke.outcome == 'failure' && needs.image-meta.outputs.runtime_smoke_required == 'true' && steps.minio-source.outputs.server_image_id != '' && steps.minio-source.outputs.client_image_id != '' }} env: SMOKE_MINIO_SERVER_IMAGE_ID: >- ${{ steps.minio-source.outputs.server_image_id }} SMOKE_MINIO_CLIENT_IMAGE_ID: >- ${{ steps.minio-source.outputs.client_image_id }} run: | docker compose \ -f docker/docker-compose.yml \ -f docker/docker-compose.override.yml \ -f docker/docker-compose.smoke-images.override.yml \ -f docker/docker-compose.pr-local-minio.override.yml \ logs || true - name: Stop smoke stack id: runtime-cleanup if: >- ${{ always() && needs.image-meta.outputs.runtime_smoke_required == 'true' && steps.minio-source.outputs.server_image_id != '' && steps.minio-source.outputs.client_image_id != '' }} env: SMOKE_MINIO_SERVER_IMAGE_ID: >- ${{ steps.minio-source.outputs.server_image_id }} SMOKE_MINIO_CLIENT_IMAGE_ID: >- ${{ steps.minio-source.outputs.client_image_id }} run: | source ./dev-tools/smoke/run-owned-compose.sh if ! stop_run_owned_compose_project \ -f docker/docker-compose.yml \ -f docker/docker-compose.override.yml \ -f docker/docker-compose.smoke-images.override.yml \ -f docker/docker-compose.pr-local-minio.override.yml; then echo "Unable to prove or release the smoke Compose project; refusing unowned teardown." >&2 exit 1 fi # Canonical-transition diagnostic evidence, not runtime qualification. The # native smoke outcome remains failed; only the terminal guard, after a live # read of the PR's canonical-play-transition label, may let the job pass. - name: Known canonical transition PLAY failure with successful authenticated cleanup id: canonical-play-transition if: >- ${{ always() && github.repository == 'benhook1013/FireMUD' && needs.image-meta.outputs.runtime_smoke_required == 'true' && steps.runtime-smoke.outcome == 'failure' && steps.runtime-smoke.outputs.known_play_failure == 'direct-backend-play-entitlement-unavailable-after-login' && steps.runtime-cleanup.outcome == 'success' }} run: | echo '### Canonical PLAY transition exception evidence' >> "$GITHUB_STEP_SUMMARY" echo 'LOGIN succeeded; direct backend PLAY failed: ERROR ENTITLEMENT_UNAVAILABLE. Held-admission qualification and authenticated cleanup passed. No runtime qualification, image export, or publication.' >> "$GITHUB_STEP_SUMMARY" - name: Require successful runtime smoke and authenticated cleanup if: ${{ always() }} uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 env: RUNTIME_SMOKE_REQUIRED: ${{ needs.image-meta.outputs.runtime_smoke_required }} RUNTIME_SMOKE_OUTCOME: ${{ steps.runtime-smoke.outcome }} RUNTIME_CLEANUP_OUTCOME: ${{ steps.runtime-cleanup.outcome }} KNOWN_PLAY_EXCEPTION_OUTCOME: ${{ steps.canonical-play-transition.outcome }} PR_NUMBER: ${{ needs.image-meta.outputs.pr_number }} with: script: | const env = process.env; const required = env.RUNTIME_SMOKE_REQUIRED; if (required !== "true" && required !== "false") { core.setFailed("Runtime smoke scope is unavailable or invalid."); return; } if (required === "false") return; if (env.RUNTIME_CLEANUP_OUTCOME !== "success") { core.setFailed("Required runtime smoke needs successful authenticated cleanup."); return; } if (env.RUNTIME_SMOKE_OUTCOME === "success") return; if (env.RUNTIME_SMOKE_OUTCOME !== "failure" || env.KNOWN_PLAY_EXCEPTION_OUTCOME !== "success") { core.setFailed("Required runtime smoke did not pass and is not the exact canonical PLAY transition failure."); return; } // The waiver needs the label now, not when the event was sent. let labels; try { ({data: {labels}} = await github.rest.pulls.get({...context.repo, pull_number: Number(env.PR_NUMBER)})); } catch (error) { core.setFailed(`Unable to read the live PR labels for the canonical PLAY transition waiver: ${error.message}`); return; } if (!Array.isArray(labels) || !labels.some(label => label?.name === "canonical-play-transition")) { core.setFailed("The canonical PLAY transition failure is waived only while the PR carries the canonical-play-transition label."); return; } core.warning("CI passed under the canonical PLAY transition exception. Runtime qualification and image publication remain blocked."); pr-controller-smoke: name: PR Hosted Identity Controller Smoke needs: [image-meta] if: ${{ ((github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) && needs.image-meta.outputs.head_current == 'true') || (github.event_name == 'repository_dispatch' && needs.image-meta.outputs.skip_build == 'false')) && needs.image-meta.outputs.controller_smoke_required == 'true' }} runs-on: ubuntu-latest timeout-minutes: 15 # No cancelling group: GitHub orders cancellation by arrival, so a delayed # older run could cancel the current one. image-meta skips superseded # comparisons before smoke instead. cache-mode: read permissions: # PR-controlled source receives no registry or repository write credential. contents: read env: BASE_IMAGE: ${{ needs.image-meta.outputs.base_image }} CONTROLLER_IMAGE: firemud-hosted-identity-controller-local:${{ needs.image-meta.outputs.image_tag }} steps: - name: Harden runner uses: step-security/harden-runner@aebdcf6156ab6691adf63218240e476564a1ed4c # v2.23.0 with: egress-policy: audit - name: Checkout PR merge uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: ref: ${{ needs.image-meta.outputs.checkout_ref }} persist-credentials: false - name: Set up Java uses: actions/setup-java@d1374f8ac74474200d16ef8ecee22c7ae7a51880 # v6.3.0 with: distribution: 'temurin' java-version: '25' - name: Set up Gradle uses: gradle/actions/setup-gradle@8da46b539cd8fe6ab27ca75128919a18d757604c # v6.4.1 with: build-scan-publish: true build-scan-terms-of-use-url: 'https://gradle.com/help/legal-terms-of-use' build-scan-terms-of-use-agree: 'yes' cache-read-only: true - name: Set up Docker Buildx uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1 - name: Build exact local runtime base image uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0 with: context: . file: docker/base.Dockerfile push: false load: true tags: ${{ env.BASE_IMAGE }} cache-from: type=gha,scope=pr-controller-smoke - name: Set up Python for Gradle recovery uses: ./.github/actions/setup-python with: requirements: none - name: Build controller image for credential-free local validation run: | set -euo pipefail bash ./dev-tools/validation/run-gradle-with-dependency-recovery.sh \ --runner ./gradlew -- :hosted-environment-identity-controller:bootJar docker build \ --file services/hosted-environment-identity-controller/Dockerfile \ --build-arg BASE_IMAGE="$BASE_IMAGE" \ --tag "$CONTROLLER_IMAGE" \ services/hosted-environment-identity-controller/build/libs - name: Smoke controller image entrypoint and paused health run: | set -euo pipefail bash ./dev-tools/hosted/controller/smoke-paused-controller-image.sh "$CONTROLLER_IMAGE" >/dev/null smoke-gate: name: Smoke Gate runs-on: ubuntu-latest permissions: checks: read # Preserve a prior successful required context on metadata-only edits. contents: read # Check out the shared required-gate composite action. actions: read # Bind preserved proof to its exact workflow run. statuses: write # Publish acknowledged supplementary metadata gate barriers. pull-requests: read # Re-read the current PR during metadata preservation. needs: [changes, image-meta, pr-local-smoke, pr-controller-smoke] if: ${{ always() && github.event_name == 'pull_request' }} timeout-minutes: 15 steps: - name: Harden runner uses: step-security/harden-runner@aebdcf6156ab6691adf63218240e476564a1ed4c # v2.23.0 with: egress-policy: audit - name: Classify smoke gate execution id: smoke_gate_context env: SMOKE_GATE_REQUIRED: ${{ github.event.action != 'edited' || github.event.changes.base.ref != null }} CHANGES_RESULT: ${{ needs.changes.result }} run: | echo "required=$SMOKE_GATE_REQUIRED" >> "$GITHUB_OUTPUT" if [ "$SMOKE_GATE_REQUIRED" = "true" ] && [ "$CHANGES_RESULT" = "success" ]; then echo "execute=true" >> "$GITHUB_OUTPUT" else echo "execute=false" >> "$GITHUB_OUTPUT" fi - name: Check out required-gate action if: ${{ steps.smoke_gate_context.outputs.required != 'true' }} uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: ref: ${{ github.event.pull_request.base.sha }} persist-credentials: false - name: Preserve successful required gate on metadata-only edit id: preserved_gate if: ${{ steps.smoke_gate_context.outputs.required != 'true' }} uses: ./.github/actions/preserve-required-gate with: gate-name: Smoke Gate workflow-name: Build Runtime Images workflow-file: runtime-images.yml workflow-path: .github/workflows/runtime-images.yml - name: Publish pending required gate status id: publish-pending-status if: ${{ steps.smoke_gate_context.outputs.required != 'true' }} uses: ./.github/actions/publish-required-gate-status with: assessment: ${{ steps.preserved_gate.outputs.assessment }} gate-name: Smoke Gate workflow-name: Build Runtime Images workflow-file: runtime-images.yml workflow-path: .github/workflows/runtime-images.yml - name: Report dependency-deferred required gate if: ${{ !cancelled() && steps.smoke_gate_context.outputs.required != 'true' }} env: PUBLISHER_OUTCOME: ${{ steps.publish-pending-status.outcome }} ASSESSMENT: ${{ steps.preserved_gate.outputs.assessment }} PUBLICATION: ${{ steps.publish-pending-status.outputs.publication }} run: | case "$PUBLISHER_OUTCOME/$ASSESSMENT/$PUBLICATION" in success/dependency-deferred/pending-acknowledged|success/success/unchanged|success/success/success-acknowledged|success/success/pending-acknowledged) ;; *) echo "Required-gate assessment or status acknowledgment is unavailable; dependency-deferred failure." >&2 exit 1 ;; esac - name: Fail when smoke dependencies did not succeed if: ${{ steps.smoke_gate_context.outputs.required == 'true' && steps.smoke_gate_context.outputs.execute != 'true' }} env: CHANGES_RESULT: ${{ needs.changes.result }} run: | echo "Smoke change detection did not succeed: changes=$CHANGES_RESULT" >&2 exit 1 - name: Record skipped runtime smoke if: ${{ steps.smoke_gate_context.outputs.execute == 'true' && needs.changes.outputs.run_smoke_full != 'true' }} run: echo "No runtime-stack smoke proof is required for this change." - name: Require this run's runtime smoke if: ${{ steps.smoke_gate_context.outputs.execute == 'true' && needs.changes.outputs.run_smoke_full == 'true' }} env: IMAGE_META_RESULT: ${{ needs.image-meta.result }} LOCAL_SMOKE_RESULT: ${{ needs.pr-local-smoke.result }} CONTROLLER_SMOKE_RESULT: ${{ needs.pr-controller-smoke.result }} CONTROLLER_SMOKE_REQUIRED: ${{ needs.image-meta.outputs.controller_smoke_required }} run: | # The terminal guard in PR Full-Stack Smoke already decided the PLAY waiver. if [[ "$IMAGE_META_RESULT" == success && "$LOCAL_SMOKE_RESULT" == success && ( "$CONTROLLER_SMOKE_RESULT" == success || ( "$CONTROLLER_SMOKE_REQUIRED" == false && "$CONTROLLER_SMOKE_RESULT" == skipped ) ) ]]; then exit 0 fi echo "Runtime smoke did not pass: image-meta=$IMAGE_META_RESULT local=$LOCAL_SMOKE_RESULT controller=$CONTROLLER_SMOKE_RESULT" >&2 exit 1 select-protected-runtime-digests: name: Select Existing Complete Runtime Digest Set needs: [image-meta] if: ${{ github.event_name != 'pull_request' && github.event_name != 'repository_dispatch' && needs.image-meta.result == 'success' && (needs.image-meta.outputs.head_branch == 'main' || needs.image-meta.outputs.head_branch == 'develop') }} runs-on: ubuntu-latest timeout-minutes: 5 permissions: contents: read packages: read outputs: fixed_digests: ${{ steps.select.outputs.fixed_digests }} missing_services: ${{ steps.select.outputs.missing_services }} env: HEAD_SHA: ${{ needs.image-meta.outputs.head_sha }} HEAD_BRANCH: ${{ needs.image-meta.outputs.head_branch }} steps: - name: Harden runner uses: step-security/harden-runner@aebdcf6156ab6691adf63218240e476564a1ed4c # v2.23.0 with: egress-policy: audit - name: Checkout trusted runtime selection source uses: actions/checkout@3d3c42e5aac5ba805825da76410c581273ba90b1 # v7 with: ref: ${{ github.workflow_sha }} persist-credentials: false - name: Verify trusted runtime selection revision run: test "$(git rev-parse HEAD)" = "$GITHUB_WORKFLOW_SHA" - name: Set up canonical GitHub CLI uses: ./.github/actions/setup-gh - name: Set up Docker Buildx uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1 - name: Login to GHCR with read access uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0 with: registry: ghcr.io username: ${{ github.actor }} password: ${{ secrets.GITHUB_TOKEN }} - name: Read the fixed digest inventory id: select env: GHCR_USERNAME: ${{ github.actor }} GHCR_TOKEN: ${{ secrets.GITHUB_TOKEN }} run: | set -euo pipefail source ./dev-tools/hosted/shared/protected-runtime-image-registry.sh select_existing_fixed_digests dispatch-pr-runtime-publication: name: Dispatch Trusted PR Runtime Publication needs: [image-meta, pr-local-smoke, pr-controller-smoke] if: ${{ always() && !cancelled() && github.event_name == 'repository_dispatch' && github.event.action == 'pr-runtime-base-refresh' && github.ref == format('refs/heads/{0}', github.event.repository.default_branch) && needs.image-meta.result == 'success' && needs.pr-local-smoke.result == 'success' && needs.pr-local-smoke.outputs.publishable == 'true' && (needs.pr-controller-smoke.result == 'success' || (needs.image-meta.outputs.controller_smoke_required == 'false' && needs.pr-controller-smoke.result == 'skipped')) }} runs-on: ubuntu-latest timeout-minutes: 5 permissions: # This trusted no-checkout job only sends an exact source-run handoff. contents: write steps: - name: Harden runner uses: step-security/harden-runner@aebdcf6156ab6691adf63218240e476564a1ed4c # v2.23.0 with: egress-policy: audit - name: Dispatch exact runtime publication source uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 with: script: | await github.rest.repos.createDispatchEvent({ ...context.repo, event_type: "pr-runtime-image-publication", client_payload: { source_run_id: String(context.runId) }, }); pin-protected-runtime-digests: name: Pin Runtime Digest Set for Smoke needs: [image-meta, build-runtime-images, select-protected-runtime-digests] if: ${{ always() && !cancelled() && github.event_name != 'pull_request' && github.event_name != 'repository_dispatch' && needs.image-meta.result == 'success' && needs.select-protected-runtime-digests.result == 'success' && ((needs.select-protected-runtime-digests.outputs.missing_services != '' && needs.select-protected-runtime-digests.outputs.missing_services != '[]' && needs.build-runtime-images.result == 'success') || (needs.select-protected-runtime-digests.outputs.missing_services == '[]' && needs.build-runtime-images.result == 'skipped')) }} runs-on: ubuntu-latest timeout-minutes: 5 permissions: contents: read packages: read outputs: runtime_digests: ${{ steps.pin.outputs.runtime_digests }} steps: - name: Harden runner uses: step-security/harden-runner@aebdcf6156ab6691adf63218240e476564a1ed4c # v2.23.0 with: egress-policy: audit - name: Checkout trusted digest inventory source uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: ref: ${{ github.workflow_sha }} persist-credentials: false - name: Verify trusted digest inventory revision run: test "$(git rev-parse HEAD)" = "$GITHUB_WORKFLOW_SHA" - name: Set up canonical GitHub CLI uses: ./.github/actions/setup-gh - name: Set up Docker Buildx uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1 - name: Login to GHCR with read access uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0 with: registry: ghcr.io username: ${{ github.actor }} password: ${{ secrets.GITHUB_TOKEN }} - name: Bind the complete smoke digest set id: pin env: CANDIDATE_TAG: ${{ needs.image-meta.outputs.candidate_tag }} FIXED_RUNTIME_DIGESTS: ${{ needs.select-protected-runtime-digests.outputs.fixed_digests }} run: | set -euo pipefail source ./dev-tools/hosted/shared/protected-runtime-image-registry.sh pin_runtime_digests smoke-full: name: Published Runtime Full-Stack Smoke needs: [image-meta, pin-protected-runtime-digests] if: ${{ always() && !cancelled() && github.event_name != 'pull_request' && github.event_name != 'repository_dispatch' && needs.image-meta.result == 'success' && needs.pin-protected-runtime-digests.result == 'success' && needs.pin-protected-runtime-digests.outputs.runtime_digests != '' }} permissions: # The trusted smoke workflow pulls the complete fixed and staged set by digest. contents: read packages: read uses: ./.github/workflows/smoke-full.yml with: action: full head_sha: ${{ needs.image-meta.outputs.head_sha }} checkout_ref: ${{ needs.image-meta.outputs.checkout_ref }} image_tag: ${{ needs.image-meta.outputs.candidate_tag }} runtime_digests: ${{ needs.pin-protected-runtime-digests.outputs.runtime_digests }} secrets: inherit publish-runtime-images: name: Promote Smoke-Tested Runtime Images needs: [image-meta, select-protected-runtime-digests, pin-protected-runtime-digests, smoke-full] if: ${{ always() && !cancelled() && github.event_name != 'pull_request' && github.event_name != 'repository_dispatch' && needs.image-meta.result == 'success' && needs.select-protected-runtime-digests.result == 'success' && needs.pin-protected-runtime-digests.result == 'success' && needs.pin-protected-runtime-digests.outputs.runtime_digests != '' && needs.smoke-full.result == 'success' && (needs.image-meta.outputs.head_branch == 'main' || needs.image-meta.outputs.head_branch == 'develop') }} runs-on: ubuntu-latest timeout-minutes: 20 concurrency: # Fixed SHA tags are shared across branches; branch alias checks remain required. group: runtime-image-promotion-protected-branches cancel-in-progress: false queue: max permissions: contents: read packages: write env: HEAD_SHA: ${{ needs.image-meta.outputs.head_sha }} HEAD_BRANCH: ${{ needs.image-meta.outputs.head_branch }} RUNTIME_DIGESTS: ${{ needs.pin-protected-runtime-digests.outputs.runtime_digests }} FIXED_RUNTIME_DIGESTS: ${{ needs.select-protected-runtime-digests.outputs.fixed_digests }} steps: - name: Harden runner uses: step-security/harden-runner@aebdcf6156ab6691adf63218240e476564a1ed4c # v2.23.0 with: egress-policy: audit - name: Checkout trusted publication source uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: ref: ${{ github.workflow_sha }} persist-credentials: false - name: Verify trusted publication revision run: test "$(git rev-parse HEAD)" = "$GITHUB_WORKFLOW_SHA" - name: Set up canonical GitHub CLI uses: ./.github/actions/setup-gh - name: Set up Docker Buildx uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1 - name: Login to GHCR uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0 with: registry: ghcr.io username: ${{ github.actor }} password: ${{ secrets.GITHUB_TOKEN }} - name: Promote smoke-tested service digests env: GH_TOKEN: ${{ github.token }} GHCR_USERNAME: ${{ github.actor }} GHCR_TOKEN: ${{ secrets.GITHUB_TOKEN }} run: | set -euo pipefail source ./dev-tools/hosted/shared/protected-runtime-image-registry.sh promote_alias() { local source="$1" target="$2" fixed="$3" retained_digest="${4:-}" local source_digest="${source##*@}" existing_digest target_digest local target_state if ! registry_manifest_state "$target" target_state; then echo "Immutable target preflight failed for $target; refusing to publish." >&2 exit 1 fi if [[ "$target_state" == missing ]]; then if [[ "$fixed" == true && -n "$retained_digest" ]]; then echo "Fixed runtime tag $target disappeared after smoke qualification." >&2 exit 1 fi if [[ "$fixed" != true ]]; then assert_current_branch_head fi docker buildx imagetools create --prefer-index=false --tag "$target" "$source" else existing_digest="$(registry_digest "$target")" if [[ "$fixed" == true && "$existing_digest" != "$source_digest" ]]; then echo "Refusing to overwrite fixed runtime tag $target: existing digest $existing_digest differs from candidate $source_digest." >&2 exit 1 fi if [[ "$existing_digest" != "$source_digest" ]]; then assert_current_branch_head docker buildx imagetools create --prefer-index=false --tag "$target" "$source" fi fi target_digest="$(registry_digest "$target")" [[ "$target_digest" == "$source_digest" ]] || { echo "Promoted runtime tag $target does not match candidate digest $source_digest (got $target_digest)." >&2 exit 1 } } preflight_fixed_digest_set || { preflight_status=$? echo 'If another run published a fixed SHA tag after selection, use Re-run all jobs to reselect and smoke-test the entire set before promotion.' >&2 exit "$preflight_status" } for service in "${services[@]}"; do candidate="${smoke_sources[$service]}" sha_tag="ghcr.io/benhook1013/${service}:${HEAD_SHA}" branch_tag="ghcr.io/benhook1013/${service}:${HEAD_BRANCH}" assert_current_branch_head promote_alias "$candidate" "$sha_tag" true "${retained_fixed[$service]}" promote_alias "$candidate" "$branch_tag" false if [[ "$HEAD_BRANCH" == develop ]]; then promote_alias "$candidate" "ghcr.io/benhook1013/${service}:latest" false fi done