Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
de2e6fd3bd | ||
|
|
4535438a1c | ||
|
|
602ff49f7b | ||
|
|
467e60627b | ||
|
|
a7d2e552af | ||
|
|
f01c90f7c6 | ||
|
|
9ebc572a9c | ||
|
|
bd92604912 | ||
|
|
a0a75210a3 | ||
|
|
a9f75d66fa | ||
|
|
49f2277ea1 | ||
|
|
06b4c4118c | ||
|
|
444b5efd39 | ||
|
|
83911b842f | ||
|
|
f92d92355a | ||
|
|
364171ebca | ||
|
|
2be1150eec | ||
|
|
1434f75112 | ||
|
|
9cba668088 | ||
|
|
53e4b246a4 |
No files matched your search
@@ -1,5 +1,15 @@
|
||||
name: Reusable Docker Publish
|
||||
|
||||
# Multi-arch (v1.9.0+): builds a manifest list for `platforms` (amd64 + arm64 by default) with
|
||||
# `docker buildx`, so the same tag runs on x86 servers and on the arm64 Raspberry Pi nodes with no
|
||||
# per-host changes. The Trivy gate is preserved by building the native amd64 image first with
|
||||
# --load, scanning that locally, and only then building + pushing the multi-arch manifest (the
|
||||
# amd64 layers are reused from cache, so only arm64 is newly built).
|
||||
#
|
||||
# Runner requirements (baked into the PipelineImage runner; the workflow also self-installs as a
|
||||
# fallback): the `docker buildx` plugin, and a build daemon that permits `--privileged` containers
|
||||
# so QEMU/binfmt can be registered for cross-building arm64 on an amd64 runner.
|
||||
|
||||
on:
|
||||
workflow_call:
|
||||
inputs:
|
||||
@@ -9,6 +19,29 @@ on:
|
||||
dockerfile_path:
|
||||
type: string
|
||||
default: "."
|
||||
floating_tag:
|
||||
type: string
|
||||
default: "edge"
|
||||
platforms:
|
||||
# target platforms for the manifest list. Override to a single platform (e.g.
|
||||
# "linux/amd64") for images that do not need to run on the arm64 nodes.
|
||||
type: string
|
||||
default: "linux/amd64,linux/arm64"
|
||||
run_image_scan:
|
||||
type: boolean
|
||||
default: true
|
||||
scan_severity:
|
||||
type: string
|
||||
default: "HIGH,CRITICAL"
|
||||
use_private_index:
|
||||
# pass the private Gitea PyPI index into the build as a BuildKit secret, for images
|
||||
# whose Dockerfile installs the in-house BB* packages. The Dockerfile must consume it
|
||||
# via `RUN --mount=type=secret,id=pip_extra_index`, never as an ARG or ENV, so the
|
||||
# token is not baked into an image layer.
|
||||
# Gitea 1.27.x does not reliably propagate boolean inputs through
|
||||
# reusable workflows. Callers pass the literal string "true".
|
||||
type: string
|
||||
default: "false"
|
||||
secrets:
|
||||
REGISTRY_USERNAME: { required: true }
|
||||
REGISTRY_PASSWORD: { required: true }
|
||||
@@ -16,12 +49,24 @@ on:
|
||||
NTFY_TOPIC: { required: true }
|
||||
NTFY_TOKEN: { required: true }
|
||||
NTFY_SERVER: { required: true }
|
||||
PIP_EXTRA_INDEX_URL: { required: false }
|
||||
|
||||
# Pinned build tooling. Keep in sync with the ARGs in the PipelineImage Dockerfiles.
|
||||
# buildx: verify the binary against checksums.txt from the buildx GitHub release before bumping.
|
||||
# binfmt: pin by digest (tonistiigi/binfmt@sha256:...) for the strongest posture; the version tag
|
||||
# below is immutable enough for CI and avoids a Docker Hub token dance in the workflow.
|
||||
env:
|
||||
BUILDX_VERSION: "0.36.1"
|
||||
BUILDX_SHA256: "48af8a397ebd60178778bf63611dbcebe5f5e7a9be90eb9147b24b9587455778"
|
||||
BINFMT_IMAGE: "tonistiigi/binfmt:qemu-v10.2.3"
|
||||
TRIVY_VERSION: "0.74.0"
|
||||
TRIVY_SHA256: "2ae6fe3ee734b7fdf11335663e18c75ea12dccc76062f09f164a3b0f8be4371a"
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
runs-on: docker
|
||||
container:
|
||||
image: gitea.tech-buddy.at/bitbuddydev/gitea_runner_python314:dev-bda315b82bb23d83065b77d91fedf0e20d9accf1
|
||||
image: gitea.tech-buddy.at/bitbuddydev/gitea_runner_python314:1.1.0
|
||||
credentials:
|
||||
username: ${{ secrets.REGISTRY_USERNAME }}
|
||||
password: ${{ secrets.REGISTRY_PASSWORD }}
|
||||
@@ -34,100 +79,235 @@ jobs:
|
||||
id: vars
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
SHA_SHORT="$(git rev-parse --short HEAD)"
|
||||
FULL_IMAGE="${{ secrets.DOCKER_REGISTRY }}/${{ inputs.image_name }}"
|
||||
TAGS="-t ${FULL_IMAGE}:${SHA_SHORT}"
|
||||
|
||||
|
||||
# the SHA tag is always built; it is also the target Trivy scans before any push
|
||||
PUSH_TAGS="-t ${FULL_IMAGE}:${SHA_SHORT} -t ${FULL_IMAGE}:${{ inputs.floating_tag }}"
|
||||
|
||||
if echo "${{ gitea.ref }}" | grep -q '^refs/tags/v'; then
|
||||
VERSION="${{ gitea.ref_name }}"
|
||||
VERSION="${VERSION#v}"
|
||||
MAJOR="$(echo "$VERSION" | cut -d. -f1)"
|
||||
MINOR="$(echo "$VERSION" | cut -d. -f1,2)"
|
||||
TAGS="${TAGS} -t ${FULL_IMAGE}:latest -t ${FULL_IMAGE}:${VERSION} -t ${FULL_IMAGE}:${MINOR} -t ${FULL_IMAGE}:${MAJOR}"
|
||||
PUSH_TAGS="${PUSH_TAGS} -t ${FULL_IMAGE}:latest -t ${FULL_IMAGE}:${VERSION} -t ${FULL_IMAGE}:${MINOR} -t ${FULL_IMAGE}:${MAJOR}"
|
||||
fi
|
||||
|
||||
echo "docker_tags=${TAGS}" >> "$GITEA_OUTPUT"
|
||||
|
||||
echo "scan_ref=${FULL_IMAGE}:${SHA_SHORT}" >> "$GITEA_OUTPUT"
|
||||
echo "push_tags=${PUSH_TAGS}" >> "$GITEA_OUTPUT"
|
||||
echo "full_image=${FULL_IMAGE}" >> "$GITEA_OUTPUT"
|
||||
|
||||
- name: Docker Login
|
||||
run: |
|
||||
echo "${{ secrets.REGISTRY_PASSWORD }}" | docker login "${{ secrets.DOCKER_REGISTRY }}" -u "${{ secrets.REGISTRY_USERNAME }}" --password-stdin
|
||||
|
||||
- name: Build image
|
||||
- name: Set up Docker Buildx and QEMU
|
||||
shell: bash
|
||||
env:
|
||||
PLATFORMS: ${{ inputs.platforms }}
|
||||
run: |
|
||||
SHA_SHORT="$(git rev-parse --short HEAD)"
|
||||
FULL_IMAGE="${{ secrets.DOCKER_REGISTRY }}/${{ inputs.image_name }}"
|
||||
set -euo pipefail
|
||||
|
||||
docker build \
|
||||
-t "${FULL_IMAGE}:${SHA_SHORT}" \
|
||||
${{ inputs.dockerfile_path }}
|
||||
# Ensure the buildx plugin. Baked into the runner image (PipelineImage); this fallback
|
||||
# covers older runners, mirroring the Trivy fallback below. Pinned + checksum-verified.
|
||||
if ! docker buildx version >/dev/null 2>&1; then
|
||||
echo "=== buildx not in runner image, installing v${BUILDX_VERSION} ==="
|
||||
mkdir -p /usr/libexec/docker/cli-plugins
|
||||
curl -sSfLo /usr/libexec/docker/cli-plugins/docker-buildx \
|
||||
"https://github.com/docker/buildx/releases/download/v${BUILDX_VERSION}/buildx-v${BUILDX_VERSION}.linux-amd64"
|
||||
echo "${BUILDX_SHA256} /usr/libexec/docker/cli-plugins/docker-buildx" | sha256sum -c -
|
||||
chmod +x /usr/libexec/docker/cli-plugins/docker-buildx
|
||||
fi
|
||||
docker buildx version
|
||||
|
||||
if echo "${{ gitea.ref }}" | grep -q '^refs/tags/v'; then
|
||||
VERSION="${{ gitea.ref_name }}"
|
||||
VERSION="${VERSION#v}"
|
||||
MAJOR="$(echo "$VERSION" | cut -d. -f1)"
|
||||
MINOR="$(echo "$VERSION" | cut -d. -f1,2)"
|
||||
|
||||
docker tag "${FULL_IMAGE}:${SHA_SHORT}" "${FULL_IMAGE}:latest"
|
||||
docker tag "${FULL_IMAGE}:${SHA_SHORT}" "${FULL_IMAGE}:${VERSION}"
|
||||
docker tag "${FULL_IMAGE}:${SHA_SHORT}" "${FULL_IMAGE}:${MINOR}"
|
||||
docker tag "${FULL_IMAGE}:${SHA_SHORT}" "${FULL_IMAGE}:${MAJOR}"
|
||||
# Register QEMU so this amd64 runner can cross-build the non-native platforms. binfmt is
|
||||
# a kernel concern, so it cannot live in the runner image and is installed here against
|
||||
# the build daemon (needs --privileged).
|
||||
if echo "${PLATFORMS}" | grep -q 'arm'; then
|
||||
echo "=== Registering QEMU emulators (${BINFMT_IMAGE}) ==="
|
||||
docker run --privileged --rm "${BINFMT_IMAGE}" --install arm64
|
||||
fi
|
||||
|
||||
- name: Push image
|
||||
# A docker-container builder is required for multi-platform output (the default docker
|
||||
# driver builds a single platform only). Idempotent across re-runs on a warm runner.
|
||||
#
|
||||
# BuildKit cache GC (v1.11.5+): the config is copied into the BuildKit container only
|
||||
# when buildx *creates* it. An existing buildx_buildkit_multiarch0 container (and its
|
||||
# persistent state volume) is reused as-is and never recreated or restarted here, so
|
||||
# concurrent jobs cannot race on reconfiguration. Existing builders are migrated once,
|
||||
# manually: see docs/buildkit-gc.md. maxUsedSpace is a GC threshold, not a hard quota.
|
||||
BUILDER="multiarch"
|
||||
BUILDKIT_CONTAINER="buildx_buildkit_${BUILDER}0"
|
||||
BUILDKITD_CONFIG="$(mktemp)"
|
||||
trap 'rm -f "${BUILDKITD_CONFIG}"' EXIT
|
||||
cat > "${BUILDKITD_CONFIG}" <<'EOF'
|
||||
[worker.oci]
|
||||
gc = true
|
||||
reservedSpace = "10GB"
|
||||
maxUsedSpace = "20GB"
|
||||
minFreeSpace = "50GB"
|
||||
EOF
|
||||
|
||||
# Job containers are ephemeral, so buildx metadata is usually missing even when the
|
||||
# BuildKit container exists on the build daemon. Register metadata only (no --bootstrap)
|
||||
# so a create error is reported as such; the container is started separately below.
|
||||
CONTAINER_EXISTED=false
|
||||
if docker container inspect "${BUILDKIT_CONTAINER}" >/dev/null 2>&1; then
|
||||
CONTAINER_EXISTED=true
|
||||
echo "=== Reusing existing BuildKit container ${BUILDKIT_CONTAINER} (not recreated) ==="
|
||||
fi
|
||||
# true only when this job registers the builder with the config AND buildx will create
|
||||
# the container from it; only then is a missing GC policy a hard error.
|
||||
EXPECT_GC_CONFIG=false
|
||||
if ! docker buildx inspect "${BUILDER}" >/dev/null 2>&1; then
|
||||
docker buildx create --name "${BUILDER}" --driver docker-container \
|
||||
--buildkitd-config "${BUILDKITD_CONFIG}"
|
||||
if [ "${CONTAINER_EXISTED}" = "false" ]; then
|
||||
echo "=== Creating ${BUILDKIT_CONTAINER} with the GC config ==="
|
||||
EXPECT_GC_CONFIG=true
|
||||
fi
|
||||
fi
|
||||
|
||||
# Start/attach the builder. Bootstrap reuses an existing container and its state volume.
|
||||
# One retry covers a concurrent job creating the same container at the same moment; a
|
||||
# second failure fails the job with buildx's own error.
|
||||
if ! docker buildx inspect --bootstrap "${BUILDER}" >/dev/null; then
|
||||
echo "=== Bootstrap of ${BUILDER} failed, retrying once in 10s ==="
|
||||
sleep 10
|
||||
docker buildx inspect --bootstrap "${BUILDER}" >/dev/null
|
||||
fi
|
||||
docker buildx use "${BUILDER}"
|
||||
|
||||
# Verify the GC policy the *running* daemon reports (buildx renders sizes with binary
|
||||
# units; accept both the 10GiB and the 9.313GiB rendering of "10GB", etc.).
|
||||
BUILDER_INFO="$(docker buildx inspect "${BUILDER}")"
|
||||
echo "${BUILDER_INFO}" | sed -n '/GC Policy/,$p'
|
||||
if echo "${BUILDER_INFO}" | grep -Eq 'Reserved Space:[[:space:]]+(10GiB|9\.313GiB)' &&
|
||||
echo "${BUILDER_INFO}" | grep -Eq 'Max Used Space:[[:space:]]+(20GiB|18\.63GiB)' &&
|
||||
echo "${BUILDER_INFO}" | grep -Eq 'Min Free Space:[[:space:]]+(50GiB|46\.57GiB)'; then
|
||||
echo "=== BuildKit GC config is active (reservedSpace 10GB, maxUsedSpace 20GB, minFreeSpace 50GB) ==="
|
||||
elif [ "${EXPECT_GC_CONFIG}" = "true" ]; then
|
||||
echo "::error::Builder ${BUILDER} was created with --buildkitd-config but the running BuildKit daemon does not report the expected GC policy."
|
||||
exit 1
|
||||
else
|
||||
echo "::warning::The managed BuildKit GC limits (20GB target) are NOT active on the existing builder ${BUILDER} (${BUILDKIT_CONTAINER}): it predates the GC config and is reused unchanged, so it still runs with BuildKit's disk-percentage defaults and its cache can keep growing. A one-time manual migration is required, see docs/buildkit-gc.md in SharedWorkflows."
|
||||
fi
|
||||
|
||||
- name: Build image for vulnerability scan
|
||||
if: ${{ inputs.run_image_scan }}
|
||||
shell: bash
|
||||
env:
|
||||
PIP_EXTRA_INDEX_URL: ${{ secrets.PIP_EXTRA_INDEX_URL }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
SECRET_ARGS=""
|
||||
if [ "${{ inputs.use_private_index }}" = "true" ]; then
|
||||
if [ -z "${PIP_EXTRA_INDEX_URL:-}" ]; then
|
||||
echo "use_private_index=true but the PIP_EXTRA_INDEX_URL secret is empty or not set"
|
||||
exit 1
|
||||
fi
|
||||
SECRET_ARGS="--secret id=pip_extra_index,env=PIP_EXTRA_INDEX_URL"
|
||||
fi
|
||||
|
||||
# native amd64 only, loaded into the local image store so Trivy can scan it before
|
||||
# anything is pushed. The amd64 result is cached and reused by the multi-arch push.
|
||||
# CVEs live in the base image and OS/Python packages, which are identical across arches,
|
||||
# so scanning amd64 is a faithful gate for the whole manifest list.
|
||||
DOCKER_BUILDKIT=1 docker buildx build \
|
||||
--load \
|
||||
--platform linux/amd64 \
|
||||
${SECRET_ARGS} \
|
||||
-t "${{ steps.vars.outputs.scan_ref }}" \
|
||||
${{ inputs.dockerfile_path }}
|
||||
|
||||
- name: Image Vulnerability Scan
|
||||
if: ${{ inputs.run_image_scan }}
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
# Fallback for runner images without Trivy baked in. Pinned version +
|
||||
# checksum, never "latest": Trivy releases were compromised in the
|
||||
# March 2026 supply-chain incident (malicious v0.69.4). Keep in sync
|
||||
# with the ARGs in the PipelineImage Dockerfiles.
|
||||
if ! command -v trivy >/dev/null 2>&1; then
|
||||
echo "=== Trivy not in runner image, installing v${TRIVY_VERSION} ==="
|
||||
curl -sSfLO "https://github.com/aquasecurity/trivy/releases/download/v${TRIVY_VERSION}/trivy_${TRIVY_VERSION}_Linux-64bit.tar.gz"
|
||||
echo "${TRIVY_SHA256} trivy_${TRIVY_VERSION}_Linux-64bit.tar.gz" | sha256sum -c -
|
||||
tar -xzf "trivy_${TRIVY_VERSION}_Linux-64bit.tar.gz" -C /usr/local/bin trivy
|
||||
rm "trivy_${TRIVY_VERSION}_Linux-64bit.tar.gz"
|
||||
fi
|
||||
trivy --version
|
||||
|
||||
# Trivy's default vulnerability-DB source (mirror.gcr.io/aquasec/trivy-db) is a
|
||||
# Google-hosted cache of the upstream GHCR image, used to dodge GHCR's unauthenticated
|
||||
# rate limits. That cache occasionally 404s on a specific layer digest (a known,
|
||||
# recurring upstream issue: aquasecurity/trivy). Point at the canonical GHCR source
|
||||
# instead, and retry the DB download alone a few times — trivy exits 1 both for "DB
|
||||
# download failed" and for "vulnerabilities found", so the download is a separate step
|
||||
# from the scan to keep those two outcomes distinguishable.
|
||||
export TRIVY_DB_REPOSITORY="ghcr.io/aquasecurity/trivy-db:2"
|
||||
export TRIVY_JAVA_DB_REPOSITORY="ghcr.io/aquasecurity/trivy-java-db:1"
|
||||
|
||||
echo "=== Ensuring vulnerability DB is up to date ==="
|
||||
db_attempt=1
|
||||
db_max_attempts=3
|
||||
until trivy image --download-db-only; do
|
||||
if [ "$db_attempt" -ge "$db_max_attempts" ]; then
|
||||
echo "=== Failed to download the Trivy vulnerability DB after ${db_max_attempts} attempts ==="
|
||||
exit 1
|
||||
fi
|
||||
echo "=== DB download failed, retrying (${db_attempt}/${db_max_attempts})... ==="
|
||||
db_attempt=$((db_attempt + 1))
|
||||
sleep $((db_attempt * 5))
|
||||
done
|
||||
|
||||
echo "=== Scanning ${{ steps.vars.outputs.scan_ref }} (fail on fixable ${{ inputs.scan_severity }}) ==="
|
||||
trivy image \
|
||||
--exit-code 1 \
|
||||
--severity "${{ inputs.scan_severity }}" \
|
||||
--ignore-unfixed \
|
||||
--skip-db-update \
|
||||
--scanners vuln,secret \
|
||||
"${{ steps.vars.outputs.scan_ref }}"
|
||||
|
||||
- name: Build and push multi-arch image
|
||||
shell: bash
|
||||
env:
|
||||
PIP_EXTRA_INDEX_URL: ${{ secrets.PIP_EXTRA_INDEX_URL }}
|
||||
run: |
|
||||
set -euxo pipefail
|
||||
|
||||
echo "=== Git / Ref Info ==="
|
||||
git rev-parse HEAD
|
||||
git rev-parse --short HEAD
|
||||
echo "gitea.ref=${{ gitea.ref }}"
|
||||
echo "gitea.ref_name=${{ gitea.ref_name }}"
|
||||
echo "platforms=${{ inputs.platforms }}"
|
||||
|
||||
SHA_SHORT="$(git rev-parse --short HEAD)"
|
||||
FULL_IMAGE="${{ secrets.DOCKER_REGISTRY }}/${{ inputs.image_name }}"
|
||||
SECRET_ARGS=""
|
||||
if [ "${{ inputs.use_private_index }}" = "true" ]; then
|
||||
if [ -z "${PIP_EXTRA_INDEX_URL:-}" ]; then
|
||||
echo "use_private_index=true but the PIP_EXTRA_INDEX_URL secret is empty or not set"
|
||||
exit 1
|
||||
fi
|
||||
SECRET_ARGS="--secret id=pip_extra_index,env=PIP_EXTRA_INDEX_URL"
|
||||
fi
|
||||
|
||||
echo "=== Image Info ==="
|
||||
echo "FULL_IMAGE=${FULL_IMAGE}"
|
||||
echo "SHA_SHORT=${SHA_SHORT}"
|
||||
echo "Expected image: ${FULL_IMAGE}:${SHA_SHORT}"
|
||||
# one build produces every platform and pushes a manifest list per tag. The Trivy gate
|
||||
# above already ran on the amd64 image these layers are reused from, so a scan failure
|
||||
# aborts the job before this step. On a version tag this also pushes latest/major/minor.
|
||||
DOCKER_BUILDKIT=1 docker buildx build \
|
||||
--push \
|
||||
--platform "${{ inputs.platforms }}" \
|
||||
${SECRET_ARGS} \
|
||||
${{ steps.vars.outputs.push_tags }} \
|
||||
${{ inputs.dockerfile_path }}
|
||||
|
||||
echo "=== Local Docker Images ==="
|
||||
docker images | grep "${{ inputs.image_name }}" || true
|
||||
|
||||
echo "=== Inspect Image ==="
|
||||
docker image inspect "${FULL_IMAGE}:${SHA_SHORT}" >/dev/null
|
||||
|
||||
echo "=== Docker Auth Check ==="
|
||||
docker info
|
||||
|
||||
echo "=== Push SHA tag ==="
|
||||
docker push "${FULL_IMAGE}:${SHA_SHORT}"
|
||||
|
||||
if echo "${{ gitea.ref }}" | grep -q '^refs/tags/v'; then
|
||||
echo "=== Version tag detected ==="
|
||||
|
||||
VERSION="${{ gitea.ref_name }}"
|
||||
VERSION="${VERSION#v}"
|
||||
MAJOR="$(echo "$VERSION" | cut -d. -f1)"
|
||||
MINOR="$(echo "$VERSION" | cut -d. -f1,2)"
|
||||
|
||||
echo "VERSION=${VERSION}"
|
||||
echo "MINOR=${MINOR}"
|
||||
echo "MAJOR=${MAJOR}"
|
||||
|
||||
echo "=== Push latest ==="
|
||||
docker push "${FULL_IMAGE}:latest"
|
||||
|
||||
echo "=== Push version ==="
|
||||
docker push "${FULL_IMAGE}:${VERSION}"
|
||||
|
||||
echo "=== Push minor ==="
|
||||
docker push "${FULL_IMAGE}:${MINOR}"
|
||||
|
||||
echo "=== Push major ==="
|
||||
docker push "${FULL_IMAGE}:${MAJOR}"
|
||||
else
|
||||
echo "=== No version tag detected, only SHA tag pushed ==="
|
||||
fi
|
||||
- name: Verify pushed manifest
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
# confirm the pushed tag really is a multi-arch manifest list
|
||||
docker buildx imagetools inspect "${{ steps.vars.outputs.scan_ref }}"
|
||||
@@ -0,0 +1,94 @@
|
||||
name: Reusable Image Security Checks
|
||||
|
||||
on:
|
||||
workflow_call:
|
||||
inputs:
|
||||
image_name:
|
||||
required: true
|
||||
type: string
|
||||
image_tag:
|
||||
type: string
|
||||
default: "edge"
|
||||
scan_severity:
|
||||
type: string
|
||||
default: "HIGH,CRITICAL"
|
||||
secrets:
|
||||
REGISTRY_USERNAME: { required: true }
|
||||
REGISTRY_PASSWORD: { required: true }
|
||||
DOCKER_REGISTRY: { required: true }
|
||||
|
||||
jobs:
|
||||
scan:
|
||||
runs-on: docker
|
||||
container:
|
||||
image: gitea.tech-buddy.at/bitbuddydev/gitea_runner_python314:1.1.0
|
||||
credentials:
|
||||
username: ${{ secrets.REGISTRY_USERNAME }}
|
||||
password: ${{ secrets.REGISTRY_PASSWORD }}
|
||||
|
||||
steps:
|
||||
- name: Docker Login
|
||||
run: |
|
||||
echo "${{ secrets.REGISTRY_PASSWORD }}" | docker login "${{ secrets.DOCKER_REGISTRY }}" -u "${{ secrets.REGISTRY_USERNAME }}" --password-stdin
|
||||
|
||||
- name: Pull Image
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
FULL_IMAGE="${{ secrets.DOCKER_REGISTRY }}/${{ inputs.image_name }}:${{ inputs.image_tag }}"
|
||||
echo "=== Pulling ${FULL_IMAGE} ==="
|
||||
docker pull "${FULL_IMAGE}"
|
||||
|
||||
- name: Image Vulnerability Scan
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
# Fallback for runner images without Trivy baked in. Pinned version +
|
||||
# checksum, never "latest": Trivy releases were compromised in the
|
||||
# March 2026 supply-chain incident (malicious v0.69.4). Keep in sync
|
||||
# with the ARGs in the PipelineImage Dockerfiles.
|
||||
TRIVY_VERSION=0.74.0
|
||||
TRIVY_SHA256=2ae6fe3ee734b7fdf11335663e18c75ea12dccc76062f09f164a3b0f8be4371a
|
||||
if ! command -v trivy >/dev/null 2>&1; then
|
||||
echo "=== Trivy not in runner image, installing v${TRIVY_VERSION} ==="
|
||||
curl -sSfLO "https://github.com/aquasecurity/trivy/releases/download/v${TRIVY_VERSION}/trivy_${TRIVY_VERSION}_Linux-64bit.tar.gz"
|
||||
echo "${TRIVY_SHA256} trivy_${TRIVY_VERSION}_Linux-64bit.tar.gz" | sha256sum -c -
|
||||
tar -xzf "trivy_${TRIVY_VERSION}_Linux-64bit.tar.gz" -C /usr/local/bin trivy
|
||||
rm "trivy_${TRIVY_VERSION}_Linux-64bit.tar.gz"
|
||||
fi
|
||||
trivy --version
|
||||
|
||||
FULL_IMAGE="${{ secrets.DOCKER_REGISTRY }}/${{ inputs.image_name }}:${{ inputs.image_tag }}"
|
||||
|
||||
# Trivy's default vulnerability-DB source (mirror.gcr.io/aquasec/trivy-db) is a
|
||||
# Google-hosted cache of the upstream GHCR image, used to dodge GHCR's unauthenticated
|
||||
# rate limits. That cache occasionally 404s on a specific layer digest (a known,
|
||||
# recurring upstream issue: aquasecurity/trivy). Point at the canonical GHCR source
|
||||
# instead, and retry the DB download alone a few times — trivy exits 1 both for "DB
|
||||
# download failed" and for "vulnerabilities found", so the download is a separate step
|
||||
# from the scan to keep those two outcomes distinguishable.
|
||||
export TRIVY_DB_REPOSITORY="ghcr.io/aquasecurity/trivy-db:2"
|
||||
export TRIVY_JAVA_DB_REPOSITORY="ghcr.io/aquasecurity/trivy-java-db:1"
|
||||
|
||||
echo "=== Ensuring vulnerability DB is up to date ==="
|
||||
db_attempt=1
|
||||
db_max_attempts=3
|
||||
until trivy image --download-db-only; do
|
||||
if [ "$db_attempt" -ge "$db_max_attempts" ]; then
|
||||
echo "=== Failed to download the Trivy vulnerability DB after ${db_max_attempts} attempts ==="
|
||||
exit 1
|
||||
fi
|
||||
echo "=== DB download failed, retrying (${db_attempt}/${db_max_attempts})... ==="
|
||||
db_attempt=$((db_attempt + 1))
|
||||
sleep $((db_attempt * 5))
|
||||
done
|
||||
|
||||
echo "=== Scanning ${FULL_IMAGE} (fail on fixable ${{ inputs.scan_severity }}) ==="
|
||||
trivy image \
|
||||
--exit-code 1 \
|
||||
--severity "${{ inputs.scan_severity }}" \
|
||||
--ignore-unfixed \
|
||||
--skip-db-update \
|
||||
--scanners vuln,secret \
|
||||
"${FULL_IMAGE}"
|
||||
@@ -0,0 +1,42 @@
|
||||
name: Reusable Node Checks
|
||||
|
||||
on:
|
||||
workflow_call:
|
||||
inputs:
|
||||
node_version:
|
||||
type: string
|
||||
default: "22"
|
||||
install_command:
|
||||
type: string
|
||||
default: "npm ci"
|
||||
typecheck_command:
|
||||
type: string
|
||||
default: "npm run typecheck"
|
||||
test_command:
|
||||
type: string
|
||||
default: "npm test"
|
||||
build_command:
|
||||
type: string
|
||||
default: "npm run build"
|
||||
|
||||
jobs:
|
||||
check:
|
||||
runs-on: docker
|
||||
container:
|
||||
image: node:${{ inputs.node_version }}-alpine
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Install dependencies
|
||||
run: ${{ inputs.install_command }}
|
||||
|
||||
- name: Typecheck
|
||||
run: ${{ inputs.typecheck_command }}
|
||||
|
||||
- name: Run tests
|
||||
run: ${{ inputs.test_command }}
|
||||
|
||||
- name: Build
|
||||
run: ${{ inputs.build_command }}
|
||||
@@ -40,75 +40,87 @@ jobs:
|
||||
repo = "${{ gitea.repository }}"
|
||||
current_run_number = int("${{ gitea.run_number }}")
|
||||
current_branch = "${{ gitea.ref_name }}"
|
||||
# gitea.event_name is unreliable here: notifications.yml is itself called via
|
||||
# workflow_call from the caller workflow, so inside this job it reports
|
||||
# "workflow_call" rather than the top-level event (push/schedule/...) that
|
||||
# actually started the run. The Actions API reports the real triggering event
|
||||
# per run, so use that for the current run instead of trusting this context
|
||||
# value. It is kept only as a last-resort fallback if the current run can't be
|
||||
# found in the scanned history at all.
|
||||
current_event = "${{ gitea.event_name }}"
|
||||
token = os.environ["API_GITEA_TOKEN"]
|
||||
|
||||
url = (
|
||||
f"{server}/api/v1/repos/{repo}/actions/runs"
|
||||
f"?page=1&limit=5"
|
||||
)
|
||||
|
||||
print(f"Fetching workflow runs from: {url}")
|
||||
print(f"Current run number: {current_run_number}")
|
||||
print(f"Current branch: {current_branch}")
|
||||
print(f"Current event: {current_event}")
|
||||
|
||||
req = urllib.request.Request(
|
||||
url,
|
||||
headers={
|
||||
"Authorization": f"token {token}",
|
||||
"Accept": "application/json",
|
||||
},
|
||||
)
|
||||
|
||||
with urllib.request.urlopen(req) as response:
|
||||
data = json.loads(response.read().decode("utf-8"))
|
||||
|
||||
runs = data.get("workflow_runs", [])
|
||||
|
||||
print(f"Received {len(runs)} workflow runs")
|
||||
|
||||
print(f"Current event (context, may be inaccurate): {current_event}")
|
||||
previous = "unknown"
|
||||
|
||||
for run in runs:
|
||||
run_number = run.get("run_number")
|
||||
status = run.get("status")
|
||||
conclusion = run.get("conclusion")
|
||||
branch = run.get("head_branch")
|
||||
event = run.get("event")
|
||||
|
||||
print(
|
||||
f"Inspecting run #{run_number}: "
|
||||
f"status={status}, "
|
||||
f"conclusion={conclusion}, "
|
||||
f"branch={branch}, "
|
||||
f"event={event}"
|
||||
# Scheduled runs can push the prior run for this branch/event beyond the
|
||||
# first page. Scan a bounded history so a succeeding push after a failure
|
||||
# is still reported as healed.
|
||||
for page in range(1, 11):
|
||||
url = f"{server}/api/v1/repos/{repo}/actions/runs?page={page}&limit=100"
|
||||
print(f"Fetching workflow runs page {page}: {url}")
|
||||
req = urllib.request.Request(
|
||||
url,
|
||||
headers={
|
||||
"Authorization": f"token {token}",
|
||||
"Accept": "application/json",
|
||||
},
|
||||
)
|
||||
with urllib.request.urlopen(req) as response:
|
||||
data = json.loads(response.read().decode("utf-8"))
|
||||
|
||||
# aktuellen Run überspringen
|
||||
if int(run_number) == current_run_number:
|
||||
print(" -> skipping current run")
|
||||
continue
|
||||
runs = data.get("workflow_runs", [])
|
||||
if not isinstance(runs, list):
|
||||
print("Received an invalid workflow-runs payload; stopping lookup.")
|
||||
break
|
||||
print(f"Received {len(runs)} workflow runs on page {page}")
|
||||
if not runs:
|
||||
break
|
||||
|
||||
# nur abgeschlossene Runs
|
||||
if status != "completed":
|
||||
print(" -> skipping non-completed run")
|
||||
continue
|
||||
for run in runs:
|
||||
run_number = run.get("run_number")
|
||||
status = run.get("status")
|
||||
conclusion = run.get("conclusion")
|
||||
branch = run.get("head_branch")
|
||||
event = run.get("event")
|
||||
|
||||
# nur gleicher Branch
|
||||
if branch != current_branch:
|
||||
print(" -> skipping different branch")
|
||||
continue
|
||||
print(
|
||||
f"Inspecting run #{run_number}: "
|
||||
f"status={status}, "
|
||||
f"conclusion={conclusion}, "
|
||||
f"branch={branch}, "
|
||||
f"event={event}"
|
||||
)
|
||||
|
||||
# nur gleiches Event
|
||||
if event != current_event:
|
||||
print(" -> skipping different event")
|
||||
continue
|
||||
# aktuellen Run überspringen, aber dessen echtes Trigger-Event merken
|
||||
if str(run_number) == str(current_run_number):
|
||||
current_event = event or current_event
|
||||
print(f" -> skipping current run (actual event={event})")
|
||||
continue
|
||||
|
||||
previous = conclusion or "unknown"
|
||||
# nur abgeschlossene Runs
|
||||
if status != "completed":
|
||||
print(" -> skipping non-completed run")
|
||||
continue
|
||||
|
||||
print(f" -> selected previous conclusion: {previous}")
|
||||
break
|
||||
# nur gleicher Branch
|
||||
if branch != current_branch:
|
||||
print(" -> skipping different branch")
|
||||
continue
|
||||
|
||||
# nur gleiches Event
|
||||
if event != current_event:
|
||||
print(" -> skipping different event")
|
||||
continue
|
||||
|
||||
previous = conclusion or "unknown"
|
||||
print(f" -> selected previous conclusion: {previous}")
|
||||
break
|
||||
|
||||
if previous != "unknown" or len(runs) < 100:
|
||||
break
|
||||
|
||||
print(f"Previous conclusion final: {previous}")
|
||||
|
||||
@@ -147,7 +159,11 @@ jobs:
|
||||
exit 0
|
||||
fi
|
||||
|
||||
COMMIT_SUBJECT="$(git log -1 --pretty=%s 2>/dev/null || echo 'Commit info unavailable')"
|
||||
COMMIT_SUBJECT="$(curl -fsS \
|
||||
-H "Authorization: Bearer ${{ secrets.API_GITEA_TOKEN }}" \
|
||||
"${{ gitea.server_url }}/api/v1/repos/${{ gitea.repository }}/git/commits/${{ gitea.sha }}" \
|
||||
| python3 -c "import json,sys; d=json.load(sys.stdin); print(d.get('RepoCommit',{}).get('message','').split('\n')[0])" \
|
||||
2>/dev/null || echo 'Commit info unavailable')"
|
||||
RUN_URL="${{ gitea.server_url }}/${{ gitea.repository }}/actions/runs/${{ gitea.run_number }}"
|
||||
|
||||
cat <<EOF >/tmp/ntfy-payload.json
|
||||
@@ -166,4 +182,4 @@ jobs:
|
||||
-H "Authorization: Bearer ${{ secrets.NTFY_TOKEN }}" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d @/tmp/ntfy-payload.json \
|
||||
"${{ secrets.NTFY_SERVER }}"
|
||||
"${{ secrets.NTFY_SERVER }}"
|
||||
@@ -6,15 +6,32 @@ on:
|
||||
python_version:
|
||||
type: string
|
||||
default: "3.14"
|
||||
source_path:
|
||||
type: string
|
||||
default: "app"
|
||||
tests_path:
|
||||
type: string
|
||||
default: "tests"
|
||||
test_command:
|
||||
type: string
|
||||
default: "coverage run -m pytest"
|
||||
coverage_fail_under:
|
||||
type: string
|
||||
default: "80"
|
||||
run_security_scan:
|
||||
type: boolean
|
||||
default: true
|
||||
use_private_index:
|
||||
# Gitea 1.27.x does not reliably propagate boolean inputs through
|
||||
# reusable workflows. Keep this a string until that regression is fixed.
|
||||
type: string
|
||||
default: "false"
|
||||
|
||||
jobs:
|
||||
check:
|
||||
runs-on: docker
|
||||
container:
|
||||
image: gitea.tech-buddy.at/bitbuddydev/gitea_runner_python314:dev-bda315b82bb23d83065b77d91fedf0e20d9accf1
|
||||
image: gitea.tech-buddy.at/bitbuddydev/gitea_runner_python314:1.1.0
|
||||
credentials:
|
||||
username: ${{ secrets.REGISTRY_USERNAME }}
|
||||
password: ${{ secrets.REGISTRY_PASSWORD }}
|
||||
@@ -23,27 +40,93 @@ jobs:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
# Keep this step unconditional. A Gitea Actions update can otherwise silently
|
||||
# skip it when a boolean workflow_call input is not propagated as expected;
|
||||
# pip then misleadingly reports that the private package does not exist.
|
||||
- name: Configure and verify private package index
|
||||
env:
|
||||
PRIVATE_INDEX_ENABLED: ${{ inputs.use_private_index }}
|
||||
PRIVATE_INDEX_URL: ${{ secrets.PIP_EXTRA_INDEX_URL }}
|
||||
run: |
|
||||
echo "Private package index requested: ${PRIVATE_INDEX_ENABLED:-<empty>}"
|
||||
if [ "${PRIVATE_INDEX_ENABLED}" != "true" ]; then
|
||||
echo "Private package index is not requested for this workflow call."
|
||||
exit 0
|
||||
fi
|
||||
if [ -z "$PRIVATE_INDEX_URL" ]; then
|
||||
echo "use_private_index=true but the PIP_EXTRA_INDEX_URL secret is empty or not set"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Probe the configured simple index before pip resolves dependencies. The
|
||||
# probe deliberately prints only scheme/host/path, never URL credentials.
|
||||
# NOTE: Gitea's PyPI package registry does not serve a browsable listing at
|
||||
# the bare /simple/ root (only /simple/<package>/ resolves per PEP 503), so a
|
||||
# 404 against the configured URL is expected there and is not itself a fault.
|
||||
# This probe therefore only fails hard on auth rejection (401/403) or an
|
||||
# unreachable/erroring host; a plain 404 is logged and deferred to pip's own
|
||||
# resolution, which is the real signal for whether the package is installable.
|
||||
python - "$PRIVATE_INDEX_URL" <<'PY'
|
||||
import base64
|
||||
import sys
|
||||
from urllib.error import HTTPError, URLError
|
||||
from urllib.parse import unquote, urlsplit, urlunsplit
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
configured_url = sys.argv[1]
|
||||
parsed = urlsplit(configured_url)
|
||||
hostname = parsed.hostname or "<missing host>"
|
||||
port = f":{parsed.port}" if parsed.port else ""
|
||||
safe_url = urlunsplit((parsed.scheme, f"{hostname}{port}", parsed.path, parsed.query, ""))
|
||||
request = Request(safe_url, headers={"Accept": "application/vnd.pypi.simple.v1+json"})
|
||||
if parsed.username is not None:
|
||||
credentials = f"{unquote(parsed.username)}:{unquote(parsed.password or '')}".encode()
|
||||
request.add_header("Authorization", "Basic " + base64.b64encode(credentials).decode())
|
||||
try:
|
||||
with urlopen(request, timeout=15) as response: # nosec B310 -- configured CI package index
|
||||
print(f"Private package-index probe: HTTP {response.status} at {safe_url}")
|
||||
except HTTPError as error:
|
||||
print(f"Private package-index probe: HTTP {error.code} at {safe_url}")
|
||||
if error.code in {401, 403}:
|
||||
print("Authentication was rejected by the private package index.")
|
||||
raise SystemExit(1)
|
||||
if error.code == 404:
|
||||
print(
|
||||
"Bare index root returned 404; Gitea's PyPI registry does not "
|
||||
"serve a listing at /simple/ (only /simple/<package>/ resolves "
|
||||
"per PEP 503). Treating this as expected and deferring to pip's "
|
||||
"own dependency resolution to confirm the index actually works."
|
||||
)
|
||||
else:
|
||||
raise SystemExit(1)
|
||||
except URLError as error:
|
||||
print(f"Private package-index probe could not reach {safe_url}: {error.reason}")
|
||||
raise SystemExit(1)
|
||||
PY
|
||||
pip config --site set global.extra-index-url "$PRIVATE_INDEX_URL"
|
||||
|
||||
- name: Install Tools & Deps
|
||||
run: |
|
||||
python -m pip install --upgrade pip setuptools wheel
|
||||
pip install -e .[dev] || pip install -e .[test] || pip install -e .
|
||||
pip install -e ".[dev]" || pip install -e ".[test]" || pip install -e .
|
||||
pip install ruff coverage pip-audit bandit
|
||||
|
||||
- name: Linting
|
||||
run: ruff check app tests
|
||||
run: ruff check ${{ inputs.source_path }} ${{ inputs.tests_path }}
|
||||
|
||||
- name: Tests
|
||||
run: |
|
||||
${{ inputs.test_command }}
|
||||
coverage report --fail-under=60
|
||||
coverage report --fail-under=${{ inputs.coverage_fail_under }}
|
||||
coverage xml
|
||||
coverage html
|
||||
|
||||
- name: Security Scan
|
||||
if: ${{ inputs.run_security_scan }}
|
||||
run: |
|
||||
pip freeze | grep -v "git+" > req.txt
|
||||
pip-audit -r req.txt
|
||||
bandit -r app/
|
||||
bandit -r ${{ inputs.source_path }}
|
||||
|
||||
- name: Upload Coverage HTML
|
||||
if: always()
|
||||
@@ -59,4 +142,4 @@ jobs:
|
||||
with:
|
||||
name: coverage-xml
|
||||
path: coverage.xml
|
||||
if-no-files-found: warn
|
||||
if-no-files-found: warn
|
||||
@@ -0,0 +1,95 @@
|
||||
name: Reusable Python Package Publish
|
||||
|
||||
# Builds a Python package with `python -m build` and uploads it to the Gitea PyPI registry with
|
||||
# twine. Intended to run only on version tags (v*), alongside python-checks, so a package is
|
||||
# never published without its tests passing.
|
||||
#
|
||||
# The caller gates this job on python-checks and on the tag ref, the same way docker-publish is
|
||||
# gated. The job itself additionally refuses to publish when the git tag does not match the
|
||||
# version declared in pyproject.toml, so a mistyped tag cannot ship the wrong version.
|
||||
|
||||
on:
|
||||
workflow_call:
|
||||
inputs:
|
||||
package_name:
|
||||
# informational, used only in log output
|
||||
required: true
|
||||
type: string
|
||||
use_private_index:
|
||||
# build backends that need the in-house BB* packages to resolve build dependencies
|
||||
# Gitea 1.27.x does not reliably propagate boolean inputs through
|
||||
# reusable workflows. Callers pass the literal string "true".
|
||||
type: string
|
||||
default: "false"
|
||||
secrets:
|
||||
REGISTRY_USERNAME: { required: true }
|
||||
REGISTRY_PASSWORD: { required: true }
|
||||
PYPI_UPLOAD_URL: { required: true }
|
||||
PYPI_UPLOAD_USER: { required: true }
|
||||
PYPI_UPLOAD_PASSWORD: { required: true }
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
runs-on: docker
|
||||
container:
|
||||
image: gitea.tech-buddy.at/bitbuddydev/gitea_runner_python314:1.1.0
|
||||
credentials:
|
||||
username: ${{ secrets.REGISTRY_USERNAME }}
|
||||
password: ${{ secrets.REGISTRY_PASSWORD }}
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Configure private package index
|
||||
if: ${{ inputs.use_private_index }}
|
||||
env:
|
||||
PRIVATE_INDEX_URL: ${{ secrets.PIP_EXTRA_INDEX_URL }}
|
||||
run: |
|
||||
if [ -z "$PRIVATE_INDEX_URL" ]; then
|
||||
echo "use_private_index=true but the PIP_EXTRA_INDEX_URL secret is empty or not set"
|
||||
exit 1
|
||||
fi
|
||||
pip config --site set global.extra-index-url "$PRIVATE_INDEX_URL"
|
||||
|
||||
- name: Verify the tag matches the package version
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
if ! echo "${{ gitea.ref }}" | grep -q '^refs/tags/v'; then
|
||||
echo "This workflow only publishes on version tags (refs/tags/v*), got '${{ gitea.ref }}'"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
TAG_VERSION="${{ gitea.ref_name }}"
|
||||
TAG_VERSION="${TAG_VERSION#v}"
|
||||
PROJECT_VERSION="$(python -c "import tomllib;print(tomllib.load(open('pyproject.toml','rb'))['project']['version'])")"
|
||||
|
||||
echo "tag version : ${TAG_VERSION}"
|
||||
echo "pyproject version: ${PROJECT_VERSION}"
|
||||
|
||||
if [ "${TAG_VERSION}" != "${PROJECT_VERSION}" ]; then
|
||||
echo "Tag v${TAG_VERSION} does not match the version ${PROJECT_VERSION} in pyproject.toml"
|
||||
echo "Bump the version in pyproject.toml and retag, so the published artifact matches the tag."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Build the package
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
python -m pip install --upgrade pip build twine
|
||||
python -m build
|
||||
echo "=== built artifacts for ${{ inputs.package_name }} ==="
|
||||
ls -1 dist
|
||||
|
||||
- name: Check the artifacts
|
||||
run: python -m twine check dist/*
|
||||
|
||||
- name: Upload to the package registry
|
||||
env:
|
||||
TWINE_USERNAME: ${{ secrets.PYPI_UPLOAD_USER }}
|
||||
TWINE_PASSWORD: ${{ secrets.PYPI_UPLOAD_PASSWORD }}
|
||||
run: |
|
||||
python -m twine upload --repository-url "${{ secrets.PYPI_UPLOAD_URL }}" dist/*
|
||||
@@ -0,0 +1,38 @@
|
||||
name: Reusable Python Security Checks
|
||||
|
||||
on:
|
||||
workflow_call:
|
||||
inputs:
|
||||
install_command:
|
||||
type: string
|
||||
default: 'python -m pip install "bandit[toml]"'
|
||||
security_command:
|
||||
type: string
|
||||
default: "python -m bandit -r app -c pyproject.toml"
|
||||
working_directory:
|
||||
type: string
|
||||
default: "."
|
||||
secrets:
|
||||
REGISTRY_USERNAME: { required: true }
|
||||
REGISTRY_PASSWORD: { required: true }
|
||||
|
||||
jobs:
|
||||
security:
|
||||
runs-on: docker
|
||||
container:
|
||||
image: gitea.tech-buddy.at/bitbuddydev/gitea_runner_python314:1.1.0
|
||||
credentials:
|
||||
username: ${{ secrets.REGISTRY_USERNAME }}
|
||||
password: ${{ secrets.REGISTRY_PASSWORD }}
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Install security tools
|
||||
working-directory: ${{ inputs.working_directory }}
|
||||
run: ${{ inputs.install_command }}
|
||||
|
||||
- name: Run security scan
|
||||
working-directory: ${{ inputs.working_directory }}
|
||||
run: ${{ inputs.security_command }}
|
||||
@@ -0,0 +1,215 @@
|
||||
# BuildKit cache GC and DinD image maintenance
|
||||
|
||||
Applies to `.gitea/workflows/docker-publish.yml` from **v1.11.5** onward. Runs on the
|
||||
`gitea-runner-dind` runner against the `gitea-dind` daemon, with the `multiarch` docker-container
|
||||
builder (`buildx_buildkit_multiarch0`, state volume `buildx_buildkit_multiarch0_state`).
|
||||
|
||||
All commands below run on the Unraid host and target the DinD daemon **explicitly** through
|
||||
`docker exec gitea-dind docker ...`. Never run them as plain `docker ...` on the host: that would
|
||||
target the host daemon that runs the production containers.
|
||||
|
||||
## 1. What the workflow does
|
||||
|
||||
`docker-publish.yml` passes this config to `docker buildx create --buildkitd-config`:
|
||||
|
||||
```toml
|
||||
[worker.oci]
|
||||
gc = true
|
||||
reservedSpace = "10GB" # GC never prunes the cache below this
|
||||
maxUsedSpace = "20GB" # GC prunes when the cache grows beyond this
|
||||
minFreeSpace = "50GB" # GC also prunes (down to reservedSpace) when disk free space drops below this
|
||||
```
|
||||
|
||||
- The `reservedSpace`/`maxUsedSpace`/`minFreeSpace` keys need **BuildKit >= v0.17**. Older daemons
|
||||
only understand `gckeepstorage`. `moby/buildkit:buildx-stable-1` is far newer than v0.17. Check
|
||||
the deployed version anyway (section 3).
|
||||
- BuildKit parses the sizes with go-units. Depending on the version, `docker buildx inspect`
|
||||
shows `20GB` as `20GiB` (binary) or `18.63GiB` (decimal). The workflow check accepts both.
|
||||
- `maxUsedSpace` is a **GC threshold, not a quota**. GC runs after builds and periodically, so the
|
||||
cache can briefly exceed 20 GB during a large build. GC removes the least recently used records
|
||||
first, so hot base and dependency layers survive.
|
||||
- `minFreeSpace` uses the free space that `statfs` reports for `/var/lib/buildkit`. On Btrfs that
|
||||
value can be imprecise, so treat it as a safety net. `maxUsedSpace` is the main limit.
|
||||
- With no explicit `[[worker.oci.gcpolicy]]` blocks, BuildKit builds its default policy set from
|
||||
these three values.
|
||||
|
||||
**The config only applies when buildx creates the BuildKit container.** buildx copies it to
|
||||
`/etc/buildkit/buildkitd.toml` inside the container, and buildkitd loads that path at startup.
|
||||
The file is in the container's filesystem, so it survives `docker restart` and DinD daemon
|
||||
restarts. It is lost only if the container is removed.
|
||||
|
||||
When the container already exists, the workflow **reuses it unchanged**. It never removes,
|
||||
recreates, restarts or reconfigures a builder, so concurrent jobs cannot race on that.
|
||||
|
||||
The setup step runs these steps in order, and none of them hides an error:
|
||||
|
||||
1. If this job has no buildx metadata for `multiarch`, run `docker buildx create
|
||||
--buildkitd-config` without `--bootstrap`. If that fails, the job fails.
|
||||
2. Run `docker buildx inspect --bootstrap multiarch`. This starts the existing container, or
|
||||
creates it if it is missing. If it fails, the step retries once after 10 seconds. That retry
|
||||
covers two jobs creating a missing builder at the same moment. A second failure fails the
|
||||
job with buildx's own error.
|
||||
3. Check the GC policy that the **running daemon** reports (`docker buildx inspect multiarch`;
|
||||
the job log shows the "GC Policy" section):
|
||||
- all three limits match: logs `BuildKit GC config is active`;
|
||||
- this job created the container from the config, but the limits do not match: **job
|
||||
fails** (`::error::`);
|
||||
- the builder already existed without the config: **non-fatal warning** that the managed GC
|
||||
limits are not active and the one-time migration below is required. The build continues
|
||||
unchanged.
|
||||
4. Delete the temporary config file when the step exits.
|
||||
|
||||
## 2. One-time migration of the existing `multiarch` builder (manual)
|
||||
|
||||
The existing `buildx_buildkit_multiarch0` was created without a config file, so it does **not**
|
||||
pick up the new settings by itself. Run this once, in a maintenance window. Both options keep
|
||||
the state volume and the cache in it.
|
||||
|
||||
### Pre-checks (both options)
|
||||
|
||||
```bash
|
||||
# 1. No CI job may be running. The only container listed should be buildx_buildkit_multiarch0.
|
||||
docker exec gitea-dind docker ps --format '{{.Names}}\t{{.Image}}\t{{.Status}}'
|
||||
# Hold new jobs: wait until the runner is idle, or stop gitea-runner-dind once it is idle.
|
||||
# Stopping the runner while a job is running aborts that job.
|
||||
|
||||
# 2. BuildKit version (must be >= v0.17) and current state
|
||||
docker exec gitea-dind docker exec buildx_buildkit_multiarch0 buildctl --version
|
||||
docker exec gitea-dind docker exec buildx_buildkit_multiarch0 cat /etc/buildkit/buildkitd.toml # expected: No such file
|
||||
docker exec gitea-dind docker exec buildx_buildkit_multiarch0 buildctl du | tail -n 3
|
||||
docker exec gitea-dind docker volume ls --filter name=buildx_buildkit_multiarch0_state
|
||||
```
|
||||
|
||||
### Option A (recommended): install the config in place, then restart
|
||||
|
||||
This keeps the same container and volume. It is the same file and path that
|
||||
`buildx create --buildkitd-config` writes.
|
||||
|
||||
```bash
|
||||
cat > /tmp/buildkitd.toml <<'EOF'
|
||||
[worker.oci]
|
||||
gc = true
|
||||
reservedSpace = "10GB"
|
||||
maxUsedSpace = "20GB"
|
||||
minFreeSpace = "50GB"
|
||||
EOF
|
||||
docker exec gitea-dind mkdir -p /tmp/bk/buildkit
|
||||
docker cp /tmp/buildkitd.toml gitea-dind:/tmp/bk/buildkit/buildkitd.toml
|
||||
docker exec gitea-dind docker cp /tmp/bk/buildkit buildx_buildkit_multiarch0:/etc/
|
||||
docker exec gitea-dind docker restart buildx_buildkit_multiarch0
|
||||
docker exec gitea-dind rm -rf /tmp/bk
|
||||
```
|
||||
|
||||
The config is not active until the restart. Verify it (section 3) before you release the runner.
|
||||
If the daemon does not report the expected policy, or the container does not come back up,
|
||||
delete the file again and restart the container (see Rollback in section 5). The cache volume
|
||||
is not affected either way. Once the runner is back in service, the next v1.11.5 publish job
|
||||
should log `BuildKit GC config is active` instead of the migration warning.
|
||||
|
||||
### Option B (fallback): remove only the container and let CI recreate it
|
||||
|
||||
```bash
|
||||
docker exec gitea-dind docker rm -f buildx_buildkit_multiarch0
|
||||
# Do NOT use `docker volume rm`, `docker buildx rm` without --keep-state, or `docker system prune --volumes`.
|
||||
```
|
||||
|
||||
The next publish job runs `buildx create --buildkitd-config`. That creates a new container,
|
||||
which mounts the **existing** named volume `buildx_buildkit_multiarch0_state`, so the cache is
|
||||
kept. Start a single publish job first, so that parallel jobs do not race to create the
|
||||
container. That first job **must use `@v1.11.5` or later**. A consumer still on v1.11.4 or older
|
||||
recreates the container *without* the config. Use this option only if Option A cannot be
|
||||
verified.
|
||||
|
||||
## 3. Verification
|
||||
|
||||
Of the commands below, only the running daemon's GC policy proves that GC is configured.
|
||||
`buildctl du` and `df` show usage, not configuration.
|
||||
|
||||
```bash
|
||||
# Authoritative: the GC policy the running buildkitd uses
|
||||
docker exec gitea-dind docker exec buildx_buildkit_multiarch0 buildctl debug workers -v
|
||||
# expected: GC Policy rules with Reserved Space / Max Used Space / Min Free Space of
|
||||
# 10GiB / 20GiB / 50GiB (or 9.313GiB / 18.63GiB / 46.57GiB, depending on the version).
|
||||
# Without the config you see percentage-derived defaults instead.
|
||||
# The same data appears in every publish job log ("GC Policy" section of `docker buildx inspect multiarch`).
|
||||
|
||||
# The file that buildkitd loads at startup (shows it exists, not that it is active)
|
||||
docker exec gitea-dind docker exec buildx_buildkit_multiarch0 cat /etc/buildkit/buildkitd.toml
|
||||
|
||||
# Cache usage: total should settle around 20 GB after GC runs
|
||||
docker exec gitea-dind docker exec buildx_buildkit_multiarch0 buildctl du | tail -n 3
|
||||
|
||||
# Image store and disk
|
||||
docker exec gitea-dind docker system df
|
||||
df -h /mnt/cache
|
||||
```
|
||||
|
||||
## 4. DinD image retention (proposal, not automated)
|
||||
|
||||
BuildKit GC manages **build cache** in the builder's state volume only. It never removes images
|
||||
from the `gitea-dind` image store. Those images are a separate problem.
|
||||
|
||||
**Where the images come from:** the scan step runs `buildx build --load -t <registry>/<image>:<sha>`.
|
||||
That loads one *tagged* image into the DinD store per publish run, and nothing removes it. Because
|
||||
these images are tagged, a dangling-only prune (`docker image prune --filter until=168h`) does
|
||||
**not** reclaim them. It only removes images whose SHA tag was later reused. The 436 accumulated
|
||||
images are mostly these per-commit scan images.
|
||||
|
||||
Proposed policy: one central job that runs from the Unraid host (for example Unraid "User
|
||||
Scripts", weekly). It is not part of every pipeline, because pipelines in different repositories
|
||||
cannot lock against each other.
|
||||
|
||||
```bash
|
||||
#!/bin/bash
|
||||
# Targets ONLY the gitea-dind daemon. Never deletes volumes or build cache.
|
||||
set -euo pipefail
|
||||
D="docker exec gitea-dind docker"
|
||||
# Guard: skip if any CI job container is running (anything besides the BuildKit builder).
|
||||
busy="$($D ps --format '{{.Names}}' | grep -v '^buildx_buildkit_' || true)"
|
||||
if [ -n "$busy" ]; then echo "CI busy, skipping: $busy"; exit 0; fi
|
||||
$D image ls --format '{{.Repository}}:{{.Tag}}\t{{.CreatedSince}}\t{{.Size}}' # audit log
|
||||
$D image prune -a -f --filter "until=168h" # unused images (tagged + dangling) created > 7 days ago
|
||||
$D system df
|
||||
```
|
||||
|
||||
Safety properties and caveats:
|
||||
|
||||
- `image prune -a` skips images that any container uses, running or stopped. That includes the
|
||||
BuildKit image. It never touches volumes or BuildKit cache.
|
||||
- The idle guard cannot close the race completely. A job could start between the check and the
|
||||
prune. The impact is limited: `until=168h` filters on image *creation* time, and a fresh scan
|
||||
image is normally minutes old. A fully cached rebuild can, however, carry an older creation
|
||||
time, which in the worst case breaks the Trivy step of a job that starts exactly then. Re-running
|
||||
the job fixes it. For a zero-risk window, stop `gitea-runner-dind` while it is idle around the
|
||||
prune.
|
||||
- The runner job image (`gitea_runner_python314`), `tonistiigi/binfmt` and other base images are
|
||||
removed when idle and re-pulled on the next job. That costs bandwidth, not correctness.
|
||||
- Run it once in dry-run mode (only the `image ls` line) and review the list before you enable
|
||||
the prune.
|
||||
- Optional follow-up (not part of this release): remove the scan image at the end of each
|
||||
publish job. This needs a per-run unique local tag, because concurrent branch and tag pushes of
|
||||
the same commit share `<image>:<sha>`.
|
||||
|
||||
Do not use `docker system prune --volumes` or `docker volume prune`. Do not use
|
||||
`docker buildx prune` as routine maintenance; GC now covers the cache.
|
||||
|
||||
**Separate finding (not changed here):** `gitea-dind` exposes an unencrypted Docker API on
|
||||
port 2375. Anyone who can reach that port has root-equivalent control of the DinD daemon. This
|
||||
change does not widen that exposure. Restricting it (bind to the runner network only, or use TLS
|
||||
on 2376) should be tracked as its own infrastructure change.
|
||||
|
||||
## 5. Rollout and rollback
|
||||
|
||||
- Release as **v1.11.5** (patch release: no input, output or secret changes, so it is backward
|
||||
compatible). Existing tags stay unchanged.
|
||||
- Consumers move from `@v1.11.x` to `@v1.11.5` at their own pace. `werkplan-web` is still on
|
||||
`v1.11.1`; going to v1.11.5 also brings in the v1.11.2–v1.11.4 fixes (Trivy DB source,
|
||||
buildx fallback pin, private-index handling, notifications).
|
||||
- The workflow change alone does **not** fix the existing builder. The one-time migration in
|
||||
section 2 is required.
|
||||
- Rollback of the workflow: pin consumers back to `@v1.11.4`. v1.11.4 reuses the existing
|
||||
container, so a builder that is already migrated keeps its GC config. That is harmless.
|
||||
- Rollback of the builder config, in a maintenance window:
|
||||
`docker exec gitea-dind docker exec buildx_buildkit_multiarch0 rm /etc/buildkit/buildkitd.toml`
|
||||
followed by `docker exec gitea-dind docker restart buildx_buildkit_multiarch0`. buildkitd then
|
||||
uses its built-in defaults again. The cache volume is kept.
|
||||
Reference in new issue
Block a user