From 1a076f4fa9bf038e0c947feea40ec19eb9876c65 Mon Sep 17 00:00:00 2001 From: "Jason T. Greene" Date: Thu, 3 Sep 2026 19:04:27 -0500 Subject: [PATCH] build: publish a FROM scratch artifact image of the gog binary Containerfile.artifact builds gog exactly as upstream's Dockerfile does (static, trimmed, stripped, -X stamped) in a digest-pinned hi/go stage and emits a FROM scratch image whose only content is /gog. Consumers such as rh-forge/openclaw-saw-image inline it with a digest-pinned COPY --from instead of compiling gog inside their own builds. The publish workflows are the organisation's standard set (publish-image, publish-pr-image via workflow_run, cleanup-pr-image, prune-images) with two deliberate differences for an artifact that downstream pins by digest: - sha- tags are immutable. A guard step refuses to publish a commit whose sha- tag already exists, because re-pointing the tag would orphan the old digest and let prune-images delete it out from under every consumer pinned to it. - No semver/tag trigger. This fork cuts no releases, and a tag build would be exactly the kind of same-commit republish the guard forbids. Version, commit, and date are stamped from git in the workflow (commit date rather than wall clock) because .dockerignore excludes .git. Each push run writes the ready-to-paste tag@digest pin to the job summary. Co-Authored-By: Claude Opus 5 --- .github/workflows/cleanup-pr-image.yml | 44 ++++++ .github/workflows/prune-images.yml | 87 ++++++++++++ .github/workflows/publish-image.yml | 177 +++++++++++++++++++++++++ .github/workflows/publish-pr-image.yml | 132 ++++++++++++++++++ Containerfile.artifact | 49 +++++++ 5 files changed, 489 insertions(+) create mode 100644 .github/workflows/cleanup-pr-image.yml create mode 100644 .github/workflows/prune-images.yml create mode 100644 .github/workflows/publish-image.yml create mode 100644 .github/workflows/publish-pr-image.yml create mode 100644 Containerfile.artifact diff --git a/.github/workflows/cleanup-pr-image.yml b/.github/workflows/cleanup-pr-image.yml new file mode 100644 index 000000000..3c3310caf --- /dev/null +++ b/.github/workflows/cleanup-pr-image.yml @@ -0,0 +1,44 @@ +name: cleanup-pr-image + +# Delete the pr- image tag once its pull request closes, so PR +# builds do not pile up in billed GHCR storage. The sha-* / semver / latest +# tags published from the default branch are never touched -- PR pushes only +# ever create pr-. +# +# pull_request_target rather than pull_request because fork PRs get a +# read-only GITHUB_TOKEN on pull_request, which cannot delete package +# versions. pull_request_target is safe here because this workflow never +# checks out or executes PR code. + +on: + pull_request_target: + types: [closed] + +permissions: + packages: write + +jobs: + delete: + runs-on: ubuntu-latest + env: + # Keep in step with the image matrix in the publish-image workflow. + IMAGES: gog + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + PR_NUMBER: ${{ github.event.number }} + steps: + - name: Delete pr-${{ github.event.number }} package versions + run: | + for image in $IMAGES; do + ids=$(gh api "orgs/${{ github.repository_owner }}/packages/container/${image}/versions" \ + --paginate \ + --jq ".[] | select(.metadata.container.tags[]? == \"pr-${PR_NUMBER}\") | .id") + if [ -z "$ids" ]; then + echo "No pr-${PR_NUMBER} version of ${image} to delete." + continue + fi + for id in $ids; do + echo "Deleting ${image} version ${id} (pr-${PR_NUMBER})" + gh api --method DELETE \ + "orgs/${{ github.repository_owner }}/packages/container/${image}/versions/${id}" + done + done diff --git a/.github/workflows/prune-images.yml b/.github/workflows/prune-images.yml new file mode 100644 index 000000000..c3a02505b --- /dev/null +++ b/.github/workflows/prune-images.yml @@ -0,0 +1,87 @@ +name: prune-images + +# Weekly registry hygiene: delete package versions that are MAX_AGE_DAYS old +# or older and are either +# - tagged only pr-* : images whose close-time cleanup was missed, or for +# open PRs untouched for a month -- the next push to such a PR simply +# republishes its image, or +# - untagged : orphaned digests that escaped the inline superseded- +# digest deletion in publish-pr-image (e.g. a run that failed mid-push). +# +# sha-*, semver and latest tags are never deleted regardless of age, and any +# digest referenced as a child of a *tagged* index is skipped, so this stays +# safe if builds ever go multi-arch (GHCR lists index children as untagged +# versions). +# +# Note: GitHub suspends cron workflows after ~60 days without repository +# activity; a push re-arms them. + +on: + schedule: + - cron: "17 3 * * 1" # Mondays 03:17 UTC + workflow_dispatch: + inputs: + dry_run: + description: Only report what would be deleted + type: boolean + default: true + +jobs: + prune: + runs-on: ubuntu-latest + permissions: + packages: write + env: + # Keep in step with the image matrix in the publish-image workflow. + IMAGES: gog + MAX_AGE_DAYS: 30 + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + # Empty on scheduled runs, which therefore delete for real. + DRY_RUN: ${{ inputs.dry_run }} + steps: + - name: Prune old PR images and orphans + run: | + set -euo pipefail + owner="${{ github.repository_owner }}" + cutoff=$(date -u -d "${MAX_AGE_DAYS} days ago" +%s) + echo "$GH_TOKEN" | skopeo login ghcr.io --username "${{ github.actor }}" --password-stdin + + for image in $IMAGES; do + versions=$(gh api "orgs/${owner}/packages/container/${image}/versions" --paginate) + + # Digests referenced by any tagged index must survive, or the + # tagged image breaks. + protected=$(echo "$versions" \ + | jq -r '.[] | select(.metadata.container.tags | length > 0) | .name' \ + | while read -r digest; do + skopeo inspect --raw "docker://ghcr.io/${owner}/${image}@${digest}" \ + | jq -r '.manifests[]?.digest // empty' + done | sort -u) + + candidates=$(echo "$versions" | jq -r --argjson cutoff "$cutoff" ' + .[] + | select((.updated_at | fromdateiso8601) <= $cutoff) + | select((.metadata.container.tags | length == 0) + or (.metadata.container.tags | all(startswith("pr-")))) + | "\(.id)\t\(.name)\t\(.metadata.container.tags | join(","))"') + + if [ -z "$candidates" ]; then + echo "${image}: nothing ${MAX_AGE_DAYS}+ days old to prune." + continue + fi + + while IFS=$'\t' read -r id name tags; do + [ -z "$id" ] && continue + if [ -n "$protected" ] && echo "$protected" | grep -qx "$name"; then + echo "${image}: keeping ${name} (child of a tagged index)" + continue + fi + if [ "$DRY_RUN" = "true" ]; then + echo "${image}: DRY RUN, would delete version ${id} (${tags:-untagged}) ${name}" + else + echo "${image}: deleting version ${id} (${tags:-untagged}) ${name}" + gh api --method DELETE \ + "orgs/${owner}/packages/container/${image}/versions/${id}" + fi + done <<< "$candidates" + done diff --git a/.github/workflows/publish-image.yml b/.github/workflows/publish-image.yml new file mode 100644 index 000000000..5f324a261 --- /dev/null +++ b/.github/workflows/publish-image.yml @@ -0,0 +1,177 @@ +name: publish-image + +# Build this fork's artifact image (Containerfile.artifact: a FROM scratch +# image containing only the static gog binary at /gog) and publish it to the +# organisation's private GitHub Container Registry as ghcr.io/rh-forge/gog. +# +# Consumers pin it by tag *and* digest, e.g. in rh-forge/openclaw-saw-image: +# ARG GOG_IMAGE=ghcr.io/rh-forge/gog:sha-@sha256: +# so sha- tags must be immutable: the guard step below refuses to +# publish a commit whose sha- tag already exists. A re-run must never +# re-point sha- at a new digest -- the old digest would become +# untagged and prune-images would delete it, breaking every pinned consumer. +# There is deliberately no semver/tag trigger here for the same reason: this +# fork cuts no releases, and every published artifact maps 1:1 to a commit. +# +# Pull requests build the image and hand it off as an OCI-archive artifact +# instead of pushing. The publish-pr-image workflow (workflow_run) picks the +# artifact up and pushes it as pr-. The split exists because +# GITHUB_TOKEN is downgraded to read-only on pull_request runs from forks -- +# so this workflow's PR path only ever reads, and the privileged half never +# executes PR code. PR builds publish only pr-, so unreviewed images +# stay clearly labelled and never enter the sha-* namespace. +# +# `latest` tracks the default branch. Nothing should pin it. + +on: + push: + branches: [main] + pull_request: + workflow_dispatch: + +# GITHUB_TOKEN can push to ghcr.io for repositories in this organisation, so +# no PAT and no organisation secret is needed. +permissions: + contents: read + packages: write + +concurrency: + group: publish-image-${{ github.ref }} + cancel-in-progress: true + +env: + IMAGE: gog + REGISTRY_IMAGE: ghcr.io/${{ github.repository_owner }}/gog + +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: + # Full history and tags: the version stamp comes from git describe. + fetch-depth: 0 + + - name: Derive version metadata + id: build-meta + run: | + set -euo pipefail + { + echo "version=$(git describe --tags --always)" + echo "commit=$(git rev-parse --short=12 HEAD)" + # Commit date rather than wall clock, so rebuilding the same + # commit stamps the same date. + echo "date=$(git log -1 --format=%cI)" + } >> "$GITHUB_OUTPUT" + + - uses: docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3 + + - name: Log in to ghcr.io + if: github.event_name != 'pull_request' + uses: docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Refuse to republish an existing sha- tag + if: github.event_name != 'pull_request' + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + set -euo pipefail + echo "$GH_TOKEN" | skopeo login ghcr.io --username "${{ github.actor }}" --password-stdin + ref="docker://${REGISTRY_IMAGE}:sha-${GITHUB_SHA}" + if digest=$(skopeo inspect --no-tags --format '{{.Digest}}' "$ref" 2>/dev/null); then + echo "::error::${REGISTRY_IMAGE}:sha-${GITHUB_SHA} is already published as ${digest}." + echo "::error::sha- tags are immutable (consumers pin them by digest). Push a new commit to publish a new artifact." + exit 1 + fi + echo "No existing artifact for sha-${GITHUB_SHA}; proceeding." + + - id: meta + name: Derive tags and OCI labels + uses: docker/metadata-action@c299e40c65443455700f0fdfc63efafe5b349051 # v5 + with: + images: ${{ env.REGISTRY_IMAGE }} + tags: | + type=sha,format=long,prefix=sha- + type=raw,value=latest,enable={{is_default_branch}} + type=ref,event=pr + labels: | + org.opencontainers.image.title=${{ env.IMAGE }} + + - name: Build and push + id: build + if: github.event_name != 'pull_request' + uses: docker/build-push-action@10e90e3645eae34f1e60eeb005ba3a3d33f178e8 # v6 + with: + context: . + file: Containerfile.artifact + # Stated, not inherited: a silent runner flip would ship binaries + # that die on the cluster with "Exec format error". + platforms: linux/amd64 + push: true + tags: ${{ steps.meta.outputs.tags }} + labels: ${{ steps.meta.outputs.labels }} + build-args: | + VERSION=${{ steps.build-meta.outputs.version }} + COMMIT=${{ steps.build-meta.outputs.commit }} + DATE=${{ steps.build-meta.outputs.date }} + cache-from: type=gha,scope=${{ env.IMAGE }} + cache-to: type=gha,mode=max,scope=${{ env.IMAGE }},ignore-error=true + # Suppress the unknown/unknown attestation manifest. With a single + # platform this also makes the pushed object a plain manifest, so + # the digest below is exactly what FROM ...@sha256 needs. + provenance: false + + - name: Record the pin for consumers + if: github.event_name != 'pull_request' + env: + DIGEST: ${{ steps.build.outputs.digest }} + run: | + set -euo pipefail + { + echo "## Published ${REGISTRY_IMAGE}" + echo + echo "Pin (tag and digest):" + echo + echo '```' + echo "${REGISTRY_IMAGE}:sha-${GITHUB_SHA}@${DIGEST}" + echo '```' + echo + echo "Bump the consumer with:" + echo + echo '```' + echo "scripts/bump-tool-pin.sh ${IMAGE} sha-${GITHUB_SHA}" + echo '```' + } >> "$GITHUB_STEP_SUMMARY" + + # Deliberately untagged: each tag becomes a separate entry in the + # archive's index and skopeo then refuses to pick ("more than one + # image in oci"). The destination tag is applied by publish-pr-image. + - name: Build to OCI archive + if: github.event_name == 'pull_request' + uses: docker/build-push-action@10e90e3645eae34f1e60eeb005ba3a3d33f178e8 # v6 + with: + context: . + file: Containerfile.artifact + platforms: linux/amd64 + outputs: type=oci,dest=/tmp/${{ env.IMAGE }}.tar + labels: ${{ steps.meta.outputs.labels }} + build-args: | + VERSION=${{ steps.build-meta.outputs.version }} + COMMIT=${{ steps.build-meta.outputs.commit }} + DATE=${{ steps.build-meta.outputs.date }} + cache-from: type=gha,scope=${{ env.IMAGE }} + cache-to: type=gha,mode=max,scope=${{ env.IMAGE }},ignore-error=true + provenance: false + + - name: Upload image artifact + if: github.event_name == 'pull_request' + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + with: + name: pr-image-${{ env.IMAGE }} + path: /tmp/${{ env.IMAGE }}.tar + retention-days: 1 + compression-level: 0 diff --git a/.github/workflows/publish-pr-image.yml b/.github/workflows/publish-pr-image.yml new file mode 100644 index 000000000..57955a09a --- /dev/null +++ b/.github/workflows/publish-pr-image.yml @@ -0,0 +1,132 @@ +name: publish-pr-image + +# Second half of the PR image pipeline. The publish-image workflow builds PR +# images without credentials and uploads them as OCI archives; this workflow +# runs in the base-repository context (workflow_run), so it holds a real +# GITHUB_TOKEN even when the PR came from a fork, and pushes the archives to +# ghcr.io as pr-. +# +# Deliberately NOT gated on the triggering run's conclusion: a PR image is a +# debugging artifact, and it is most useful exactly when tests fail. The PR +# still fails verification through its own checks; this workflow only ever +# writes the pr- tag, never sha-*/latest/semver, so a failing PR +# cannot contaminate any tag a deployment consumes. If the image build +# itself failed there is simply no artifact, and this run skips cleanly. +# +# Everything taken from the triggering run is untrusted -- the artifact was +# built from unreviewed PR code. This workflow therefore +# - never executes anything from the artifact: skopeo streams it to the +# registry as data, +# - only pushes image names on the hard-coded allowlist below, so a +# malicious PR cannot rename its artifact to overwrite another +# repository's package, and +# - derives the PR number from the head SHA via the API instead of +# trusting anything the PR run wrote. +# +# workflow_run always executes this file as it exists on the default branch, +# never the PR's copy. + +on: + workflow_run: + workflows: [publish-image] + types: [completed] + +permissions: + contents: read + # Download artifacts from the triggering run. + actions: read + # List the PRs associated with the head commit. + pull-requests: read + packages: write + +concurrency: + group: publish-pr-image-${{ github.event.workflow_run.head_repository.full_name }}-${{ github.event.workflow_run.head_branch }} + cancel-in-progress: true + +env: + # Images this workflow is willing to push. Keep in step with the image + # matrix in the publish-image workflow. + ALLOWED_IMAGES: gog + +jobs: + push: + if: > + github.event.workflow_run.event == 'pull_request' && + github.event.workflow_run.conclusion != 'cancelled' + runs-on: ubuntu-latest + steps: + - name: Find the open PR for this head SHA + id: pr + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + HEAD_SHA: ${{ github.event.workflow_run.head_sha }} + run: | + # The SHA-equality filter also drops runs whose PR has since gained + # newer commits -- the newer run, not this one, owns the pr-N tag. + number=$(gh api "repos/${{ github.repository }}/commits/${HEAD_SHA}/pulls" \ + --jq "[.[] | select(.state == \"open\" and .head.sha == \"${HEAD_SHA}\")][0].number // empty") + if [ -z "$number" ]; then + echo "No open PR has ${HEAD_SHA} as its head; nothing to publish." + echo "skip=true" >> "$GITHUB_OUTPUT" + else + echo "number=$number" >> "$GITHUB_OUTPUT" + fi + + - name: Download image artifacts + if: steps.pr.outputs.skip != 'true' + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4 + with: + pattern: pr-image-* + path: /tmp/pr-images + run-id: ${{ github.event.workflow_run.id }} + github-token: ${{ secrets.GITHUB_TOKEN }} + + - name: Push to ghcr.io + if: steps.pr.outputs.skip != 'true' + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + PR_NUMBER: ${{ steps.pr.outputs.number }} + run: | + shopt -s nullglob + dirs=(/tmp/pr-images/pr-image-*/) + if [ ${#dirs[@]} -eq 0 ]; then + # The triggering run failed before any image built, or its path + # filters skipped the image jobs. Nothing to publish. + echo "No image artifacts on run ${{ github.event.workflow_run.id }}; skipping." + exit 0 + fi + echo "$GH_TOKEN" | skopeo login ghcr.io --username "${{ github.actor }}" --password-stdin + for dir in "${dirs[@]}"; do + image=$(basename "$dir") + image=${image#pr-image-} + case " $ALLOWED_IMAGES " in + *" $image "*) ;; + *) + echo "::warning::ignoring artifact for unexpected image '$image'" + continue + ;; + esac + dest="ghcr.io/${{ github.repository_owner }}/${image}:pr-${PR_NUMBER}" + + # Remember what pr-N pointed at so the superseded digest can be + # deleted after the tag moves; empty on the PR's first push. + old_digest=$(skopeo inspect --format '{{.Digest}}' --no-tags "docker://${dest}" 2>/dev/null || true) + + skopeo copy "oci-archive:${dir}${image}.tar" "docker://${dest}" + + new_digest=$(skopeo inspect --format '{{.Digest}}' --no-tags "docker://${dest}") + if [ -n "$old_digest" ] && [ "$old_digest" != "$new_digest" ]; then + # Delete exactly the version the tag moved off of, and only if + # nothing else still tags it. Never a blanket untagged purge: + # that would also hit child manifests of any future multi-arch + # index, which are listed as untagged versions. + id=$(gh api "orgs/${{ github.repository_owner }}/packages/container/${image}/versions" \ + --paginate \ + --jq ".[] | select(.name == \"${old_digest}\" and (.metadata.container.tags | length == 0)) | .id") + if [ -n "$id" ]; then + echo "Deleting superseded ${image}@${old_digest} (version ${id})" + gh api --method DELETE \ + "orgs/${{ github.repository_owner }}/packages/container/${image}/versions/${id}" + fi + fi + done diff --git a/Containerfile.artifact b/Containerfile.artifact new file mode 100644 index 000000000..a5e656ceb --- /dev/null +++ b/Containerfile.artifact @@ -0,0 +1,49 @@ +# Artifact image for the gog CLI: a FROM scratch image whose only content is +# the static binary at /gog. Consumers (rh-forge/openclaw-saw-image) inline it +# with a digest-pinned `FROM ghcr.io/rh-forge/gog:sha-@sha256:... AS +# gog-artifact` / `COPY --from=gog-artifact /gog /usr/local/bin/gog`, so the +# heavyweight Go build happens here, once per fork commit, not in every +# downstream image build. Published by .github/workflows/publish-image.yml. +# +# Same build recipe as upstream's Dockerfile (CGO_ENABLED=0, -trimpath, +# stripped, version/commit/date stamped via -X). gog embeds tzdata; CA +# certificates come from the consumer image. Version metadata arrives as +# build-args because .dockerignore excludes .git. +# +# hi/go only publishes stream-level tags (1.26), not exact patch pins, so the +# digest was resolved from that tag at the time of pinning. Re-resolve with +# `skopeo inspect --no-tags --override-os linux --override-arch amd64 \ +# --format '{{.Digest}}' docker://registry.access.redhat.com/hi/go:1.26` +# when a newer patch is wanted. +ARG GO_IMAGE=registry.access.redhat.com/hi/go:1.26@sha256:78aea4b29a79c66de2b6b6fbe9dae2f3d00d5c371b7d6cb50c2b08bc8ca001a1 + +FROM ${GO_IMAGE} AS build + +WORKDIR /src +COPY go.mod go.sum ./ +RUN go mod download + +COPY . . + +ARG VERSION=dev +ARG COMMIT=unknown +ARG DATE=unknown + +# TARGETARCH is the platform the image is being built for (BuildKit and +# buildah both set it), so `--platform linux/amd64` yields an amd64 binary +# even on an arm64 builder, and a native arm64 trial build works locally. The +# published arch is decided by the workflow's `platforms:` setting, which +# states linux/amd64 explicitly. +ARG TARGETARCH +RUN CGO_ENABLED=0 GOOS=linux GOARCH=${TARGETARCH} go build -trimpath \ + -ldflags="-s -w -X github.com/openclaw/gogcli/internal/cmd.version=${VERSION} -X github.com/openclaw/gogcli/internal/cmd.commit=${COMMIT} -X github.com/openclaw/gogcli/internal/cmd.date=${DATE}" \ + -o /out/gog ./cmd/gog \ + && /out/gog --version + +FROM scratch + +LABEL org.opencontainers.image.source="https://github.com/rh-forge/gogcli" +LABEL org.opencontainers.image.description="gog CLI static binary (artifact image; not runnable on its own)" +LABEL org.opencontainers.image.licenses="MIT" + +COPY --from=build /out/gog /gog