name: Reusable — Docker build & push on: workflow_call: inputs: image_name: description: 'Image name (defaults to repo name). Pushed as ghcr.io//.' required: false type: string default: '' dockerfile_path: description: 'Path to Dockerfile (default: Dockerfile at repo root).' required: false type: string default: 'Dockerfile' build_context: description: 'Build context directory (default: repo root).' required: false type: string default: '.' platforms: description: 'Comma-separated platforms.' required: false type: string default: 'linux/amd64,linux/arm64' push: description: 'Push to GHCR. Set false for PR builds.' required: false type: boolean default: true trivy_severity: description: 'Trivy severities that FAIL the build. Pair with trivy_ignore_unfixed.' required: false type: string default: 'CRITICAL,HIGH' trivy_report_severity: description: 'Trivy severities REPORTED to the job summary without failing. Visibility tier.' required: false type: string default: 'CRITICAL,HIGH' trivy_ignore_unfixed: description: 'Only count vulnerabilities that have a fix available. A base image routinely carries unfixable CVEs, so false here makes the gate go red for something no caller can act on.' required: false type: boolean default: true target: description: 'Dockerfile stage to build. Empty builds the final stage. Callers with a multi-stage image (e.g. lean + full) invoke this workflow once per target, and must give each one distinct references via image_name or tag_suffix.' required: false type: string default: '' tag_suffix: description: 'Appended to every computed tag, including latest. The way a multi-target caller keeps one image name while separating its targets, e.g. -full.' required: false type: string default: '' build_args: description: 'Newline-separated KEY=VALUE build args.' required: false type: string default: '' release_version: description: 'Semver (e.g. 1.3.2) to tag this build with. For releases cut by release-please, whose tag is pushed with GITHUB_TOKEN and so cannot trigger a tag-filtered build — the caller passes the version instead. Empty = no version tags.' required: false type: string default: '' smoke_healthcheck: description: 'Start each scanned image and wait for its own HEALTHCHECK to report healthy before anything is pushed. The image must define one; an image without a HEALTHCHECK fails the leg rather than passing by default.' required: false type: boolean default: false smoke_timeout: description: 'Seconds to wait for healthy. Cover the HEALTHCHECK start-period plus a few intervals.' required: false type: number default: 120 secrets: DISCORD_WEBHOOK_URL: required: false jobs: # Single owner of what this invocation publishes: the image, the normalized # platforms, and one id per leg keying its cache scope and SARIF category. plan: permissions: {} runs-on: ubuntu-latest outputs: image: ${{ steps.split.outputs.image }} platforms: ${{ steps.split.outputs.platforms }} list: ${{ steps.split.outputs.list }} cache_from: ${{ steps.split.outputs.cache_from }} steps: # Two invocations differing only in `target` resolve the same image name and # the same tags, so a later push replaces the earlier target. This warns # rather than fails: one target legitimately takes the unsuffixed tags, and # a single invocation cannot see whether its siblings are distinguished. - name: Warn on an undistinguished target if: ${{ inputs.target != '' && inputs.image_name == '' && inputs.tag_suffix == '' }} env: TARGET: ${{ inputs.target }} run: | echo "::warning::target '$TARGET' publishes to the default references. Any sibling target without image_name or tag_suffix overwrites it." - name: Plan image and platforms id: split # Via env: an expression is expanded before bash parses the line. env: IMAGE_NAME_INPUT: ${{ inputs.image_name }} TAG_SUFFIX: ${{ inputs.tag_suffix }} PLATFORMS: ${{ inputs.platforms }} TARGET: ${{ inputs.target }} run: | set -euo pipefail name="${IMAGE_NAME_INPUT:-${GITHUB_REPOSITORY##*/}}" # Siblings in one run share cache and SARIF namespaces, so the id must differ # wherever the output does; the hash separates what the prefix runs together. sum=$(printf '%s\0%s\0%s' "$name" "$TAG_SUFFIX" "$TARGET" | sha256sum) key="${name}${TAG_SUFFIX}-${TARGET:-final}-${sum:0:8}" # Slurped, and split on newlines too: build-push-action accepts either. # A platform with a hosted runner of its own arch builds there; anything # else builds under QEMU on the default runner. list=$(jq -Rsc --arg k "$key" '[splits("[,\n]")] | map(gsub("^\\s+|\\s+$"; "")) | map(select(length > 0)) | map({platform: ., id: ("\($k)-\(.)" | ascii_downcase | gsub("[^a-z0-9._-]"; "-"))} + (if . == "linux/arm64" or . == "linux/arm64/v8" then {runner: "ubuntu-24.04-arm", qemu: false} elif . == "linux/amd64" then {runner: "ubuntu-latest", qemu: false} else {runner: "ubuntu-latest", qemu: true} end)) | unique_by(.id)' <<< "$PLATFORMS") if [ "$(jq length <<< "$list")" -eq 0 ]; then echo "::error::platforms is empty, so nothing would be scanned." exit 1 fi { echo "image=ghcr.io/${GITHUB_REPOSITORY_OWNER,,}/${name,,}" echo "list=$list" # build publishes exactly this list, so nothing unscanned can ship. echo "platforms=$(jq -r 'map(.platform) | join(",")' <<< "$list")" echo 'cache_from<> "$GITHUB_OUTPUT" # Build and scan every published platform locally, with no push, so findings # land BEFORE anything reaches GHCR. The push only runs if every leg passes. scan: name: scan (${{ matrix.platform }}) needs: plan # contents: checkout. security-events: the Trivy SARIF upload. permissions: contents: read security-events: write runs-on: ${{ matrix.runner }} strategy: # One arch failing must not hide the other's report. fail-fast: false matrix: include: ${{ fromJSON(needs.plan.outputs.list) }} env: # Trivy assumes linux/amd64 unless told, and aborts on an image without it. TRIVY_PLATFORM: ${{ matrix.platform }} steps: - name: Checkout uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0 - name: Set up QEMU if: ${{ matrix.qemu }} uses: docker/setup-qemu-action@29109295f81e9208d7d86ff1c6c12d2833863392 # v3.6.0 - name: Set up Buildx uses: docker/setup-buildx-action@e468171a9de216ec08956ac3ada2f0791b6bd435 # v3.11.1 - name: Build image for scanning uses: docker/build-push-action@263435318d21b8e681c14492fe198d362a7d2c83 # v6.18.0 with: context: ${{ inputs.build_context }} file: ${{ inputs.dockerfile_path }} # One platform per leg: a multi-arch manifest cannot be loaded. platforms: ${{ matrix.platform }} load: true push: false tags: chodeus-scan:${{ github.sha }} target: ${{ inputs.target }} build-args: ${{ inputs.build_args }} # Per-platform scope: legs sharing one scope overwrite each other's cache. cache-from: type=gha,scope=${{ matrix.id }} cache-to: type=gha,mode=max,scope=${{ matrix.id }} # The image's own HEALTHCHECK is the runtime gate: a build that scans clean # but never comes up must not reach GHCR either. - name: Smoke test (HEALTHCHECK) if: ${{ inputs.smoke_healthcheck }} env: IMAGE: chodeus-scan:${{ github.sha }} PLATFORM: ${{ matrix.platform }} TIMEOUT: ${{ inputs.smoke_timeout }} run: | set -euo pipefail # A number input admits 0.5, which the arithmetic below rejects cryptically. case "$TIMEOUT" in ''|*[!0-9]*) echo "::error::smoke_timeout must be a whole number of seconds, got '${TIMEOUT}'."; exit 1 ;; esac if [ "$TIMEOUT" -lt 1 ]; then echo "::error::smoke_timeout must be at least 1 second, got ${TIMEOUT}." exit 1 fi hc=$(docker inspect -f '{{if .Config.Healthcheck}}{{index .Config.Healthcheck.Test 0}}{{else}}NONE{{end}}' "$IMAGE") if [ "$hc" = "NONE" ]; then echo "::error::the image defines no HEALTHCHECK, so smoke_healthcheck has nothing to wait for." exit 1 fi cid=$(docker run -d --platform "$PLATFORM" "$IMAGE") # The log tail lands in the run either way; it is the only clue when a leg fails. trap 'echo "--- container log (tail)"; docker logs --tail 40 "$cid" 2>&1 || true; docker rm -f "$cid" >/dev/null 2>&1 || true' EXIT started=$SECONDS # timeout owns the deadline, so a healthy seen after it can never be accepted. if timeout "$TIMEOUT" bash -c ' while :; do case "$(docker inspect -f "{{.State.Status}} {{if .State.Health}}{{.State.Health.Status}}{{else}}none{{end}}" "$1")" in "running healthy") exit 0 ;; "running unhealthy") echo "::error::the container reported unhealthy."; exit 1 ;; "running starting"|"running none") sleep 2 ;; *) echo "::error::the container is not running."; exit 1 ;; esac done' _ "$cid"; then echo "healthy after $((SECONDS - started))s" else rc=$? if [ "$rc" -eq 124 ]; then echo "::error::not healthy within ${TIMEOUT}s (last state: $(docker inspect -f '{{.State.Status}} {{if .State.Health}}{{.State.Health.Status}}{{else}}none{{end}}' "$cid"))." fi exit 1 fi # Two tiers on purpose. The report tier is the wide net and never blocks; # the gate tier is narrow and blocks. Both honour trivy_ignore_unfixed, so # a base image carrying an unfixable CVE cannot wedge every caller's build. - name: Trivy scan (report, non-blocking) uses: aquasecurity/trivy-action@ed142fd0673e97e23eac54620cfb913e5ce36c25 # v0.36.0 with: # The action's default trivy trails its own releases; pin the scanner. version: v0.74.0 # renovate: aquasecurity/trivy scan-type: image image-ref: chodeus-scan:${{ github.sha }} severity: ${{ inputs.trivy_report_severity }} ignore-unfixed: ${{ inputs.trivy_ignore_unfixed }} exit-code: '0' format: table output: trivy-report.txt - name: Publish scan report if: always() # Via env, not `${{ }}` inline: an expression is expanded before bash # parses the line, so a caller-supplied severity could inject a command. env: TRIVY_REPORT_SEVERITY: ${{ inputs.trivy_report_severity }} TRIVY_IGNORE_UNFIXED: ${{ inputs.trivy_ignore_unfixed }} run: | { echo "### Image scan — ${TRIVY_PLATFORM} — ${TRIVY_REPORT_SEVERITY} (fixable only: ${TRIVY_IGNORE_UNFIXED})" echo '```' cat trivy-report.txt 2>/dev/null || echo "(no report produced)" echo '```' } >> "$GITHUB_STEP_SUMMARY" - name: Trivy scan (gate) uses: aquasecurity/trivy-action@ed142fd0673e97e23eac54620cfb913e5ce36c25 # v0.36.0 with: # The action's default trivy trails its own releases; pin the scanner. version: v0.74.0 # renovate: aquasecurity/trivy scan-type: image image-ref: chodeus-scan:${{ github.sha }} severity: ${{ inputs.trivy_severity }} ignore-unfixed: ${{ inputs.trivy_ignore_unfixed }} exit-code: '1' format: sarif # Without it the action drops `severity` for SARIF, so any fixable finding failed the gate limit-severities-for-sarif: true output: trivy-image.sarif # The report step above already installed trivy in this job. skip-setup-trivy: true - name: Upload Trivy SARIF if: always() uses: github/codeql-action/upload-sarif@2892aa5e19bbd11bc0cff5427e3b750a04d9e3c2 # v4.38.2 with: sarif_file: trivy-image.sarif # Per leg, target included: a repeated category in one run fails the upload. category: trivy-image-${{ matrix.id }} build: needs: [plan, scan] # Only exists when actually publishing, so a verification run never holds a # token with packages: write. Every platform is already built in scan. if: ${{ inputs.push }} # One publish per image and ref at a time, whichever workflow calls this. queue: max keeps every # waiting run, where the default replaces a pending one and would drop a release build. concurrency: group: docker-publish-${{ needs.plan.outputs.image }}${{ inputs.tag_suffix }}-${{ github.ref }} queue: max # contents: checkout. packages: the GHCR login and push. permissions: contents: read packages: write runs-on: ubuntu-latest outputs: digest: ${{ steps.build.outputs.digest }} tags: ${{ steps.meta.outputs.tags }} steps: - name: Checkout uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0 - name: Set up QEMU uses: docker/setup-qemu-action@29109295f81e9208d7d86ff1c6c12d2833863392 # v3.6.0 - name: Set up Buildx uses: docker/setup-buildx-action@e468171a9de216ec08956ac3ada2f0791b6bd435 # v3.11.1 - name: Login to GHCR uses: docker/login-action@184bdaa0721073962dff0199f1fb9940f07167d1 # v3.5.0 with: registry: ghcr.io username: ${{ github.actor }} password: ${{ secrets.GITHUB_TOKEN }} # Inside the publish queue: a newer commit's build has already published or waits for this one. # Once the branch has moved past this commit, its branch tag and latest are the newer build's. - name: Check the branch head id: head env: REF: ${{ github.ref }} SHA: ${{ github.sha }} run: | set -euo pipefail latest='{{is_default_branch}}'; branch=true if [[ "$REF" == refs/heads/* ]]; then if ! head=$(git ls-remote --exit-code origin "$REF" | cut -f1); then echo "::error::Could not read ${REF#refs/heads/} from origin, so nothing is published." exit 1 fi if [ "$head" != "$SHA" ]; then latest=false; branch=false echo "::warning::${REF#refs/heads/} has moved on to ${head:0:7}, so this build of ${SHA:0:7} skips its branch tag and latest." fi fi echo "latest=$latest" >> "$GITHUB_OUTPUT" echo "branch=$branch" >> "$GITHUB_OUTPUT" - name: Compute tags id: meta uses: docker/metadata-action@c1e51972afc2121e065aed6d45c65596fe445f3f # v5.8.0 with: images: ${{ needs.plan.outputs.image }} # latest=false leaves latest to the default-branch rule below; the action's # default also adds it for any semver tag, including one on an older commit. flavor: ${{ inputs.tag_suffix != '' && format('latest=false,suffix={0},onlatest=true', inputs.tag_suffix) || 'latest=false' }} tags: | type=ref,event=branch,enable=${{ steps.head.outputs.branch }} type=ref,event=pr type=semver,pattern={{version}} type=semver,pattern={{major}}.{{minor}} type=sha,prefix=sha-,format=short type=raw,value=latest,enable=${{ steps.head.outputs.latest }} type=semver,pattern={{version}},value=${{ inputs.release_version }},enable=${{ inputs.release_version != '' }} type=semver,pattern={{major}}.{{minor}},value=${{ inputs.release_version }},enable=${{ inputs.release_version != '' }} - name: Build & push id: build uses: docker/build-push-action@263435318d21b8e681c14492fe198d362a7d2c83 # v6.18.0 with: context: ${{ inputs.build_context }} file: ${{ inputs.dockerfile_path }} platforms: ${{ needs.plan.outputs.platforms }} push: ${{ inputs.push }} tags: ${{ steps.meta.outputs.tags }} labels: ${{ steps.meta.outputs.labels }} target: ${{ inputs.target }} build-args: ${{ inputs.build_args }} provenance: true sbom: true # The scan legs wrote one scope per platform; this build only reads them. cache-from: ${{ needs.plan.outputs.cache_from }}