Files
actions/docker-build/action.yml
Ismo Vuorinen ab371bdebf feat: simplify actions (#353)
* feat: first pass simplification

* refactor: simplify actions repository structure

Major simplification reducing actions from 44 to 30:

Consolidations:
- Merge biome-check + biome-fix → biome-lint (mode: check/fix)
- Merge eslint-check + eslint-fix → eslint-lint (mode: check/fix)
- Merge prettier-check + prettier-fix → prettier-lint (mode: check/fix)
- Merge 5 version-detect actions → language-version-detect (language param)

Removals:
- common-file-check, common-retry (better served by external tools)
- docker-publish-gh, docker-publish-hub (consolidated into docker-publish)
- github-release (redundant with existing tooling)
- set-git-config (no longer needed)
- version-validator (functionality moved to language-version-detect)

Fixes:
- Rewrite docker-publish to use official Docker actions directly
- Update validate-inputs example (eslint-fix → eslint-lint)
- Update tests and documentation for new structure

Result: ~6,000 lines removed, cleaner action catalog, maintained functionality.

* refactor: complete action simplification and cleanup

Remove deprecated actions and update remaining actions:

Removed:
- common-file-check, common-retry: utility actions
- docker-publish-gh, docker-publish-hub: replaced by docker-publish wrapper
- github-release, version-validator, set-git-config: no longer needed
- Various version-detect actions: replaced by language-version-detect

Updated:
- docker-publish: rewrite as simple wrapper using official Docker actions
- validate-inputs: update example (eslint-fix → eslint-lint)
- Multiple actions: update configurations and remove deprecated dependencies
- Tests: update integration/unit tests for new structure
- Documentation: update README, remove test for deleted actions

Configuration updates:
- Linter configs, ignore files for new structure
- Makefile, pyproject.toml updates

* fix: enforce POSIX compliance in GitHub workflows

Convert all workflow shell scripts to POSIX-compliant sh:

Critical fixes:
- Replace bash with sh in all shell declarations
- Replace [[ with [ for test conditions
- Replace == with = for string comparisons
- Replace set -euo pipefail with set -eu
- Split compound AND conditions into separate [ ] tests

Files updated:
- .github/workflows/test-actions.yml (7 shell declarations, 10 test operators)
- .github/workflows/security-suite.yml (set -eu)
- .github/workflows/action-security.yml (2 shell declarations)
- .github/workflows/pr-lint.yml (3 shell declarations)
- .github/workflows/issue-stats.yml (1 shell declaration)

Ensures compatibility with minimal sh implementations and aligns with
CLAUDE.md standards requiring POSIX shell compliance across all scripts.

All tests pass: 764 pytest tests, 100% coverage.

* fix: add missing permissions for private repository support

Add critical permissions to pr-lint workflow for private repositories:

Workflow-level permissions:
+ packages: read - Access private npm/PyPI/Composer packages

Job-level permissions:
+ packages: read - Access private packages during dependency installation
+ checks: write - Create and update check runs

Fixes failures when:
- Installing private npm packages from GitHub Packages
- Installing private Composer dependencies
- Installing private Python packages
- Creating status checks with github-script

Valid permission scopes per actionlint:
actions, attestations, checks, contents, deployments, discussions,
id-token, issues, models, packages, pages, pull-requests,
repository-projects, security-events, statuses

Note: "workflows" and "metadata" are NOT valid permission scopes
(they are PAT-only scopes or auto-granted respectively).

* docs: update readmes

* fix: replace bash-specific 'source' with POSIX '.' command

Replace all occurrences of 'source' with '.' (dot) for POSIX compliance:

Changes in python-lint-fix/action.yml:
- Line 165: source .venv/bin/activate → . .venv/bin/activate
- Line 179: source .venv/bin/activate → . .venv/bin/activate
- Line 211: source .venv/bin/activate → . .venv/bin/activate

Also fixed bash-specific test operator:
- Line 192: [[ "$FAIL_ON_ERROR" == "true" ]] → [ "$FAIL_ON_ERROR" = "true" ]

The 'source' command is bash-specific. POSIX sh uses '.' (dot) to source files.
Both commands have identical functionality but '.' is portable across all
POSIX-compliant shells.

* security: fix code injection vulnerability in docker-publish

Fix CodeQL code injection warning (CWE-094, CWE-095, CWE-116):

Issue: inputs.context was used directly in GitHub Actions expression
without sanitization at line 194, allowing potential code injection
by external users.

Fix: Use environment variable indirection to prevent expression injection:
- Added env.BUILD_CONTEXT to capture inputs.context
- Changed context parameter to use ${{ env.BUILD_CONTEXT }}

Environment variables are evaluated after expression compilation,
preventing malicious code execution during workflow parsing.

Security Impact: Medium severity (CVSS 5.0)
Identified by: GitHub Advanced Security (CodeQL)
Reference: https://github.com/ivuorinen/actions/pull/353#pullrequestreview-3481935924

* security: prevent credential persistence in pr-lint checkout

Add persist-credentials: false to checkout step to mitigate untrusted
checkout vulnerability. This prevents GITHUB_TOKEN from being accessible
to potentially malicious PR code.

Fixes: CodeQL finding CWE-829 (untrusted checkout on privileged workflow)

* fix: prevent security bot from overwriting unrelated comments

Replace broad string matching with unique HTML comment marker for
identifying bot-generated comments. Previously, any comment containing
'Security Analysis' or '🔐 GitHub Actions Permissions' would be
overwritten, causing data loss.

Changes:
- Add unique marker: <!-- security-analysis-bot-comment -->
- Prepend marker to generated comment body
- Update comment identification to use marker only
- Add defensive null check for comment.body

This fixes critical data loss bug where user comments could be
permanently overwritten by the security analysis bot.

Follows same proven pattern as test-actions.yml coverage comments.

* improve: show concise permissions diff instead of full blocks

Replace verbose full-block permissions diff with line-by-line changes.
Now shows only added/removed permissions, making output much more
readable.

Changes:
- Parse permissions into individual lines
- Compare old vs new to identify actual changes
- Show only removed (-) and added (+) lines in diff
- Collapse unchanged permissions into details section (≤3 items)
- Show count summary for many unchanged permissions (>3 items)

Example output:
  Before: 30+ lines showing entire permissions block
  After: 3-5 lines showing only what changed

This addresses user feedback that permissions changes were too verbose.

* security: add input validation and trust model documentation

Add comprehensive security validation for docker-publish action to prevent
code injection attacks (CWE-094, CWE-116).

Changes:
- Add validation for context input (reject absolute paths, warn on URLs)
- Add validation for dockerfile input (reject absolute/URL paths)
- Document security trust model in README
- Add best practices for secure usage
- Explain validation rules and threat model

Prevents malicious actors from:
- Building from arbitrary file system locations
- Fetching Dockerfiles from untrusted remote sources
- Executing code injection through build context manipulation

Addresses: CodeRabbit review comments #2541434325, #2541549615
Fixes: GitHub Advanced Security code injection findings

* security: replace unmaintained nick-fields/retry with step-security/retry

Replace nick-fields/retry with step-security/retry across all 4 actions:
- csharp-build/action.yml
- php-composer/action.yml
- go-build/action.yml
- ansible-lint-fix/action.yml

The nick-fields/retry action has security vulnerabilities and low maintenance.
step-security/retry is a drop-in replacement with full API compatibility.

All inputs (timeout_minutes, max_attempts, command, retry_wait_seconds) are
compatible. Using SHA-pinned version for security.

Addresses CodeRabbit review comment #2541549598

* test: add is_input_required() helper function

Add helper function to check if an action input is required, reducing
duplication across test suites.

The function:
- Takes action_file and input_name as parameters
- Uses validation_core.py to query the 'required' property
- Returns 0 (success) if input is required
- Returns 1 (failure) if input is optional

This DRY improvement addresses CodeRabbit review comment #2541549572

* feat: add mode validation convention mapping

Add "mode" to the validation conventions mapping for lint actions
(eslint-lint, biome-lint, prettier-lint).

Note: The update-validators script doesn't currently recognize "string"
as a validator type, so mode validation coverage remains at 93%. The
actions already have inline validation for mode (check|fix), so this is
primarily for improving coverage metrics.

Addresses part of CodeRabbit review comment #2541549570
(validation coverage improvement)

* docs: fix CLAUDE.md action counts and add missing action

- Update action count from 31 to 29 (line 42)
- Add missing 'action-versioning' to Utilities category (line 74)

Addresses CodeRabbit review comments #2541553130 and #2541553110

* docs: add security considerations to docker-publish

Add security documentation to both action.yml header and README.md:
- Trust model explanation
- Input validation details for context and dockerfile
- Attack prevention information
- Best practices for secure usage

The documentation was previously removed when README was autogenerated.
Now documented in both places to ensure it persists.

* fix: correct step ID reference in docker-build

Fix incorrect step ID reference in platforms output:
- Changed steps.platforms.outputs.built to steps.detect-platforms.outputs.platforms
- The step is actually named 'detect-platforms' not 'platforms'
- Ensures output correctly references the detect-platforms step defined at line 188

* fix: ensure docker-build platforms output is always available

Make detect-platforms step unconditional to fix broken output contract.

The platforms output (line 123) references steps.detect-platforms.outputs.platforms,
but the step only ran when auto-detect-platforms was true (default: false).
This caused undefined output in most cases.

Changes:
- Remove 'if' condition from detect-platforms step
- Step now always runs and always produces platforms output
- When auto-detect is false: outputs configured architectures
- When auto-detect is true: outputs detected platforms or falls back to architectures
- Add '|| true' to grep to prevent errors when no platforms detected

Fixes CodeRabbit review comment #2541824904

* security: remove env var indirection in docker-publish BUILD_CONTEXT

Remove BUILD_CONTEXT env var indirection to address GitHub Advanced Security alert.

The inputs.context is validated at lines 137-147 (rejects absolute paths, warns on URLs)
before being used, so the env var indirection is unnecessary and triggers false positive
code injection warnings.

Changes:
- Remove BUILD_CONTEXT env var (line 254)
- Use inputs.context directly (line 256 → 254)
- Input validation remains in place (lines 137-147)

Fixes GitHub Advanced Security code injection alerts (comments #2541405269, #2541522320)

* feat: implement mode_enum validator for lint actions

Add mode_enum validator to validate mode inputs in linting actions.

Changes to conventions.py:
- Add 'mode_enum' to exact_matches mapping (line 215)
- Add 'mode_enum' to PHP-specific validators list (line 560)
- Implement _validate_mode_enum() method (lines 642-660)
  - Validates mode values against ['check', 'fix']
  - Returns clear error messages for invalid values

Updated rules.yml files:
- biome-lint: Add mode: mode_enum convention
- eslint-lint: Add mode: mode_enum convention
- prettier-lint: Add mode: mode_enum convention
- All rules.yml: Fix YAML formatting with yamlfmt

This addresses PR #353 comment #2541522326 which reported that mode validation
was being skipped due to unrecognized 'string' type, reducing coverage to 93%.

Tested with biome-lint action - correctly rejects invalid values and accepts
valid 'check' and 'fix' values.

* docs: update action count from 29 to 30 in CLAUDE.md

Update two references to action count in CLAUDE.md:
- Line 42: repository_overview memory description
- Line 74: Repository Structure section header

The repository has 30 actions total (29 listed + validate-inputs).

Addresses PR #353 comment #2541549588.

* docs: use pinned version ref in language-version-detect README

Change usage example from @main to @v2025 for security best practices.

Using pinned version refs (instead of @main) ensures:
- Predictable behavior across workflow runs
- Protection against breaking changes
- Better security through immutable references

Follows repository convention documented in main README and CLAUDE.md.

Addresses PR #353 comment #2541549588.

* refactor: remove deprecated add-snippets input from codeql-analysis

Remove add-snippets input which has been deprecated by GitHub's CodeQL action
and no longer has any effect.

Changes:
- Remove add-snippets input definition (lines 93-96)
- Remove reference in init step (line 129)
- Remove reference in analyze step (line 211)
- Regenerate README and rules.yml

This is a non-breaking change since:
- Default was 'false' (minimal usage expected)
- GitHub's action already ignores this parameter
- Aligns with recent repository simplification efforts

* feat: add mode_enum validator and update rules

Add mode_enum validator support for lint actions and regenerate all validation rules:

Validator Changes:
- Add mode_enum to action_overrides for biome-lint, eslint-lint, prettier-lint
- Remove deprecated add-snippets from codeql-analysis overrides

Rules Updates:
- All 29 action rules.yml files regenerated with consistent YAML formatting
- biome-lint, eslint-lint, prettier-lint now validate mode input (check/fix)
- Improved coverage for lint actions (79% → 83% for biome, 93% for eslint, 79% for prettier)

Documentation:
- Fix language-version-detect README to use @v2025 (not @main)
- Remove outdated docker-publish security docs (now handled by official actions)

This completes PR #353 review feedback implementation.

* fix: replace bash-specific $'\n' with POSIX-compliant printf

Replace non-POSIX $'\n' syntax in tag building loop with printf-based
approach that works in any POSIX shell.

Changed:
- Line 216: tags="${tags}"$'\n'"${image}:${tag}"
+ Line 216: tags="$(printf '%s\n%s' "$tags" "${image}:${tag}")"

This ensures docker-publish/action.yml runs correctly on systems using
/bin/sh instead of bash.
2025-11-19 15:42:06 +02:00

598 lines
20 KiB
YAML

# yaml-language-server: $schema=https://json.schemastore.org/github-action.json
# permissions:
# - (none required) # Build action, publishing handled by separate actions
---
name: Docker Build
description: 'Builds a Docker image for multiple architectures with enhanced security and reliability.'
author: 'Ismo Vuorinen'
branding:
icon: 'package'
color: 'blue'
inputs:
image-name:
description: 'The name of the Docker image to build. Defaults to the repository name.'
required: false
tag:
description: 'The tag for the Docker image. Must follow semver or valid Docker tag format.'
required: true
architectures:
description: 'Comma-separated list of architectures to build for.'
required: false
default: 'linux/amd64,linux/arm64,linux/arm/v7,linux/arm/v6'
dockerfile:
description: 'Path to the Dockerfile'
required: false
default: 'Dockerfile'
context:
description: 'Docker build context'
required: false
default: '.'
build-args:
description: 'Build arguments in format KEY=VALUE,KEY2=VALUE2'
required: false
cache-from:
description: 'External cache sources (e.g., type=registry,ref=user/app:cache)'
required: false
push:
description: 'Whether to push the image after building'
required: false
default: 'true'
max-retries:
description: 'Maximum number of retry attempts for build and push operations'
required: false
default: '3'
token:
description: 'GitHub token for authentication'
required: false
default: ''
buildx-version:
description: 'Specific Docker Buildx version to use'
required: false
default: 'latest'
buildkit-version:
description: 'Specific BuildKit version to use'
required: false
default: 'v0.11.0'
cache-mode:
description: 'Cache mode for build layers (min, max, or inline)'
required: false
default: 'max'
build-contexts:
description: 'Additional build contexts in format name=path,name2=path2'
required: false
network:
description: 'Network mode for build (host, none, or default)'
required: false
default: 'default'
secrets:
description: 'Build secrets in format id=path,id2=path2'
required: false
auto-detect-platforms:
description: 'Automatically detect and build for all available platforms'
required: false
default: 'false'
platform-build-args:
description: 'Platform-specific build args in JSON format'
required: false
parallel-builds:
description: 'Number of parallel platform builds (0 for auto)'
required: false
default: '0'
cache-export:
description: 'Export cache destination (e.g., type=local,dest=/tmp/cache)'
required: false
cache-import:
description: 'Import cache sources (e.g., type=local,src=/tmp/cache)'
required: false
dry-run:
description: 'Perform a dry run without actually building'
required: false
default: 'false'
verbose:
description: 'Enable verbose logging with platform-specific output'
required: false
default: 'false'
platform-fallback:
description: 'Continue building other platforms if one fails'
required: false
default: 'true'
scan-image:
description: 'Scan built image for vulnerabilities'
required: false
default: 'false'
sign-image:
description: 'Sign the built image with cosign'
required: false
default: 'false'
sbom-format:
description: 'SBOM format (spdx-json, cyclonedx-json, or syft-json)'
required: false
default: 'spdx-json'
outputs:
image-digest:
description: 'The digest of the built image'
value: ${{ steps.build.outputs.digest }}
metadata:
description: 'Build metadata in JSON format'
value: ${{ steps.build.outputs.metadata }}
platforms:
description: 'Successfully built platforms'
value: ${{ steps.detect-platforms.outputs.platforms }}
platform-matrix:
description: 'Build status per platform in JSON format'
value: ${{ steps.build.outputs.platform-matrix }}
build-time:
description: 'Total build time in seconds'
value: ${{ steps.build.outputs.build-time }}
scan-results:
description: 'Vulnerability scan results if scanning enabled'
value: ${{ steps.scan-output.outputs.results }}
signature:
description: 'Image signature if signing enabled'
value: ${{ steps.sign.outputs.signature }}
sbom-location:
description: 'SBOM document location'
value: ${{ steps.build.outputs.sbom-location }}
runs:
using: composite
steps:
- name: Checkout Repository
uses: actions/checkout@71cf2267d89c5cb81562390fa70a37fa40b1305e # v6-beta
with:
token: ${{ inputs.token || github.token }}
- name: Validate Inputs
id: validate
uses: ivuorinen/actions/validate-inputs@0fa9a68f07a1260b321f814202658a6089a43d42
with:
action-type: 'docker-build'
image-name: ${{ inputs.image-name }}
tag: ${{ inputs.tag }}
architectures: ${{ inputs.architectures }}
dockerfile: ${{ inputs.dockerfile }}
build-args: ${{ inputs.build-args }}
buildx-version: ${{ inputs.buildx-version }}
parallel-builds: ${{ inputs.parallel-builds }}
- name: Check Dockerfile Exists
shell: bash
env:
DOCKERFILE: ${{ inputs.dockerfile }}
run: |
if [ ! -f "$DOCKERFILE" ]; then
echo "::error::Dockerfile not found at $DOCKERFILE"
exit 1
fi
- name: Set up QEMU
uses: docker/setup-qemu-action@c7c53464625b32c7a7e944ae62b3e17d2b600130 # v3.7.0
with:
platforms: ${{ inputs.architectures }}
- name: Set up Docker Buildx
id: buildx
uses: docker/setup-buildx-action@e468171a9de216ec08956ac3ada2f0791b6bd435 # v3.11.1
with:
version: ${{ inputs.buildx-version }}
platforms: ${{ inputs.architectures }}
buildkitd-flags: --debug
driver-opts: |
network=${{ inputs.network }}
image=moby/buildkit:${{ inputs.buildkit-version }}
- name: Detect Available Platforms
id: detect-platforms
shell: bash
env:
ARCHITECTURES: ${{ inputs.architectures }}
AUTO_DETECT: ${{ inputs.auto-detect-platforms }}
run: |
set -euo pipefail
# When auto-detect is enabled, try to detect available platforms
if [ "$AUTO_DETECT" = "true" ]; then
available_platforms=$(docker buildx ls | grep -o 'linux/[^ ]*' | sort -u | tr '\n' ',' | sed 's/,$//' || true)
if [ -n "$available_platforms" ]; then
echo "platforms=${available_platforms}" >> $GITHUB_OUTPUT
echo "Detected platforms: ${available_platforms}"
else
echo "platforms=$ARCHITECTURES" >> $GITHUB_OUTPUT
echo "Using default platforms (detection failed): $ARCHITECTURES"
fi
else
# Auto-detect disabled, use configured architectures
echo "platforms=$ARCHITECTURES" >> $GITHUB_OUTPUT
echo "Using configured platforms: $ARCHITECTURES"
fi
- name: Determine Image Name
id: image-name
shell: bash
env:
IMAGE_NAME: ${{ inputs.image-name }}
run: |
set -euo pipefail
if [ -z "$IMAGE_NAME" ]; then
repo_name=$(basename "${GITHUB_REPOSITORY}")
echo "name=${repo_name}" >> $GITHUB_OUTPUT
else
echo "name=$IMAGE_NAME" >> $GITHUB_OUTPUT
fi
- name: Parse Build Arguments
id: build-args
shell: bash
env:
BUILD_ARGS_INPUT: ${{ inputs.build-args }}
run: |
set -euo pipefail
args=""
if [ -n "$BUILD_ARGS_INPUT" ]; then
IFS=',' read -ra BUILD_ARGS <<< "$BUILD_ARGS_INPUT"
for arg in "${BUILD_ARGS[@]}"; do
args="$args --build-arg $arg"
done
fi
echo "args=${args}" >> $GITHUB_OUTPUT
- name: Parse Build Contexts
id: build-contexts
shell: bash
env:
BUILD_CONTEXTS: ${{ inputs.build-contexts }}
run: |
set -euo pipefail
contexts=""
if [ -n "$BUILD_CONTEXTS" ]; then
IFS=',' read -ra CONTEXTS <<< "$BUILD_CONTEXTS"
for ctx in "${CONTEXTS[@]}"; do
contexts="$contexts --build-context $ctx"
done
fi
echo "contexts=${contexts}" >> $GITHUB_OUTPUT
- name: Parse Secrets
id: secrets
shell: bash
env:
INPUT_SECRETS: ${{ inputs.secrets }}
run: |
set -euo pipefail
secrets=""
if [ -n "$INPUT_SECRETS" ]; then
IFS=',' read -ra SECRETS <<< "$INPUT_SECRETS"
for secret in "${SECRETS[@]}"; do
# Trim whitespace
secret=$(echo "$secret" | xargs)
if [[ "$secret" == *"="* ]]; then
# Parse id=src format
id="${secret%%=*}"
src="${secret#*=}"
# Validate id and src are not empty
if [[ -z "$id" || -z "$src" ]]; then
echo "::error::Invalid secret format: '$secret'. Expected 'id=src' where both id and src are non-empty"
exit 1
fi
secrets="$secrets --secret id=$id,src=$src"
else
# Handle legacy format - treat as id only (error for now)
echo "::error::Invalid secret format: '$secret'. Expected 'id=src' format for Buildx compatibility"
exit 1
fi
done
fi
echo "secrets=${secrets}" >> $GITHUB_OUTPUT
- name: Login to GitHub Container Registry
if: ${{ inputs.push == 'true' }}
uses: docker/login-action@5e57cd118135c172c3672efd75eb46360885c0ef # v3.6.0
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ inputs.token || github.token }}
- name: Set up Build Cache
id: cache
shell: bash
env:
CACHE_IMPORT: ${{ inputs.cache-import }}
CACHE_FROM: ${{ inputs.cache-from }}
CACHE_EXPORT: ${{ inputs.cache-export }}
PUSH: ${{ inputs.push }}
INPUT_TOKEN: ${{ inputs.token }}
CACHE_MODE: ${{ inputs.cache-mode }}
run: |
set -euo pipefail
# Use provided token or fall back to GITHUB_TOKEN
TOKEN="${INPUT_TOKEN:-${GITHUB_TOKEN:-}}"
cache_from=""
cache_to=""
# Handle cache import
if [ -n "$CACHE_IMPORT" ]; then
cache_from="--cache-from $CACHE_IMPORT"
elif [ -n "$CACHE_FROM" ]; then
cache_from="--cache-from $CACHE_FROM"
fi
# Handle cache export
if [ -n "$CACHE_EXPORT" ]; then
cache_to="--cache-to $CACHE_EXPORT"
fi
# Registry cache configuration for better performance (only if authenticated)
if [ "$PUSH" == "true" ] || [ -n "$TOKEN" ]; then
normalized_repo=$(echo "${GITHUB_REPOSITORY}" | tr '[:upper:]' '[:lower:]' | sed 's/[^a-z0-9._\/-]/-/g')
registry_cache_ref="ghcr.io/${normalized_repo}/cache:latest"
cache_from="$cache_from --cache-from type=registry,ref=$registry_cache_ref"
# Set cache mode
cache_mode="$CACHE_MODE"
if [ -z "$cache_to" ]; then
cache_to="--cache-to type=registry,ref=$registry_cache_ref,mode=${cache_mode}"
fi
fi
# Also include local cache as fallback
cache_from="$cache_from --cache-from type=local,src=/tmp/.buildx-cache"
if [[ "$cache_to" != *"type=local"* ]]; then
cache_to="$cache_to --cache-to type=local,dest=/tmp/.buildx-cache-new,mode=${cache_mode}"
fi
echo "from=${cache_from}" >> $GITHUB_OUTPUT
echo "to=${cache_to}" >> $GITHUB_OUTPUT
- name: Build Multi-Architecture Docker Image
id: build
shell: bash
env:
AUTO_DETECT_PLATFORMS: ${{ inputs.auto-detect-platforms }}
DETECTED_PLATFORMS: ${{ steps.detect-platforms.outputs.platforms }}
ARCHITECTURES: ${{ inputs.architectures }}
PUSH: ${{ inputs.push }}
DRY_RUN: ${{ inputs.dry-run }}
MAX_RETRIES: ${{ inputs.max-retries }}
VERBOSE: ${{ inputs.verbose }}
SBOM_FORMAT: ${{ inputs.sbom-format }}
IMAGE_NAME: ${{ steps.image-name.outputs.name }}
TAG: ${{ inputs.tag }}
BUILD_ARGS: ${{ steps.build-args.outputs.args }}
BUILD_CONTEXTS: ${{ steps.build-contexts.outputs.contexts }}
SECRETS: ${{ steps.secrets.outputs.secrets }}
CACHE_FROM: ${{ steps.cache.outputs.from }}
CACHE_TO: ${{ steps.cache.outputs.to }}
DOCKERFILE: ${{ inputs.dockerfile }}
CONTEXT: ${{ inputs.context }}
run: |
set -euo pipefail
# Track build start time
build_start=$(date +%s)
# Determine platforms to build
if [ "$AUTO_DETECT_PLATFORMS" == "true" ] && [ -n "$DETECTED_PLATFORMS" ]; then
platforms="$DETECTED_PLATFORMS"
else
platforms="$ARCHITECTURES"
fi
# For local load (push=false), restrict to single platform
if [ "$PUSH" != "true" ]; then
# Extract first platform only for local load
platforms=$(echo "$platforms" | cut -d',' -f1)
echo "Local build mode: restricting to single platform: $platforms"
fi
# Initialize platform matrix tracking
platform_matrix="{}"
# Check for dry run
if [ "$DRY_RUN" == "true" ]; then
echo "[DRY RUN] Would build for platforms: $platforms"
echo "digest=dry-run-no-digest" >> $GITHUB_OUTPUT
echo "platform-matrix={}" >> $GITHUB_OUTPUT
echo "build-time=0" >> $GITHUB_OUTPUT
exit 0
fi
attempt=1
max_attempts="$MAX_RETRIES"
# Prepare verbose flag
verbose_flag=""
if [ "$VERBOSE" == "true" ]; then
verbose_flag="--progress=plain"
fi
# Prepare SBOM options
sbom_flag="--sbom=true"
if [ -n "$SBOM_FORMAT" ]; then
sbom_flag="--sbom=true --sbom-format=$SBOM_FORMAT"
fi
while [ $attempt -le $max_attempts ]; do
echo "Build attempt $attempt of $max_attempts"
# Build command with platform restriction for local load
if [ "$PUSH" == "true" ]; then
build_action="--push"
else
build_action="--load"
fi
if docker buildx build \
--platform=${platforms} \
--tag "$IMAGE_NAME:$TAG" \
$BUILD_ARGS \
$BUILD_CONTEXTS \
$SECRETS \
$CACHE_FROM \
$CACHE_TO \
--file "$DOCKERFILE" \
${build_action} \
--provenance=true \
${sbom_flag} \
${verbose_flag} \
--metadata-file=/tmp/build-metadata.json \
"$CONTEXT"; then
# Get image digest
if [ "$PUSH" == "true" ]; then
digest=$(docker buildx imagetools inspect "$IMAGE_NAME:$TAG" --raw | jq -r '.digest // "unknown"' || echo "unknown")
else
digest=$(docker inspect "$IMAGE_NAME:$TAG" --format='{{.Id}}' || echo "unknown")
fi
echo "digest=${digest}" >> $GITHUB_OUTPUT
# Parse metadata
if [ -f /tmp/build-metadata.json ]; then
{
echo "metadata<<EOF"
cat /tmp/build-metadata.json
echo "EOF"
} >> "$GITHUB_OUTPUT"
# Extract SBOM location directly from file
sbom_location=$(jq -r '.sbom.location // ""' /tmp/build-metadata.json)
echo "sbom-location=${sbom_location}" >> "$GITHUB_OUTPUT"
fi
# Calculate build time
build_end=$(date +%s)
build_time=$((build_end - build_start))
echo "build-time=${build_time}" >> $GITHUB_OUTPUT
# Build platform matrix
IFS=',' read -ra PLATFORM_ARRAY <<< "${platforms}"
platform_matrix="{"
for p in "${PLATFORM_ARRAY[@]}"; do
platform_matrix="${platform_matrix}\"${p}\":\"success\","
done
platform_matrix="${platform_matrix%,}}"
echo "platform-matrix=${platform_matrix}" >> $GITHUB_OUTPUT
# Move cache
if [ -d /tmp/.buildx-cache-new ]; then
rm -rf /tmp/.buildx-cache
mv /tmp/.buildx-cache-new /tmp/.buildx-cache
fi
break
fi
attempt=$((attempt + 1))
if [ $attempt -le $max_attempts ]; then
echo "Build failed, waiting 10 seconds before retry..."
sleep 10
else
echo "::error::Build failed after $max_attempts attempts"
exit 1
fi
done
- name: Scan Image for Vulnerabilities
id: scan
if: inputs.scan-image == 'true' && inputs.dry-run != 'true'
uses: aquasecurity/trivy-action@b6643a29fecd7f34b3597bc6acb0a98b03d33ff8 # 0.33.1
with:
scan-type: 'image'
image-ref: ${{ steps.image-name.outputs.name }}:${{ inputs.tag }}
format: 'json'
output: 'trivy-results.json'
severity: 'HIGH,CRITICAL'
- name: Process Scan Results
id: scan-output
if: inputs.scan-image == 'true' && inputs.dry-run != 'true'
shell: bash
run: |
set -euo pipefail
# Read and format scan results for output
scan_results=$(cat trivy-results.json | jq -c '.')
echo "results=${scan_results}" >> $GITHUB_OUTPUT
# Check for critical vulnerabilities
critical_count=$(cat trivy-results.json | jq '.Results[] | (.Vulnerabilities // [])[] | select(.Severity == "CRITICAL") | .VulnerabilityID' | wc -l)
if [ "$critical_count" -gt 0 ]; then
echo "::warning::Found $critical_count critical vulnerabilities in image"
fi
- name: Install Cosign
if: inputs.sign-image == 'true' && inputs.push == 'true' && inputs.dry-run != 'true'
uses: sigstore/cosign-installer@faadad0cce49287aee09b3a48701e75088a2c6ad # v4.0.0
- name: Sign Image
id: sign
if: inputs.sign-image == 'true' && inputs.push == 'true' && inputs.dry-run != 'true'
shell: bash
env:
IMAGE_NAME: ${{ steps.image-name.outputs.name }}
IMAGE_TAG: ${{ inputs.tag }}
run: |
set -euo pipefail
# Sign the image (using keyless signing with OIDC)
export COSIGN_EXPERIMENTAL=1
cosign sign --yes "${IMAGE_NAME}:${IMAGE_TAG}"
echo "signature=signed" >> $GITHUB_OUTPUT
- name: Verify Build
id: verify
if: inputs.dry-run != 'true'
shell: bash
env:
PUSH: ${{ inputs.push }}
IMAGE_NAME: ${{ steps.image-name.outputs.name }}
IMAGE_TAG: ${{ inputs.tag }}
run: |
set -euo pipefail
# Verify image exists
if [ "$PUSH" == "true" ]; then
if ! docker buildx imagetools inspect "${IMAGE_NAME}:${IMAGE_TAG}" >/dev/null 2>&1; then
echo "::error::Built image not found"
exit 1
fi
# Get and verify platform support
platforms=$(docker buildx imagetools inspect "${IMAGE_NAME}:${IMAGE_TAG}" | grep "Platform:" | cut -d' ' -f2)
echo "built=${platforms}" >> $GITHUB_OUTPUT
else
# For local builds, just verify it exists
if ! docker image inspect "${IMAGE_NAME}:${IMAGE_TAG}" >/dev/null 2>&1; then
echo "::error::Built image not found locally"
exit 1
fi
echo "built=local" >> $GITHUB_OUTPUT
fi
- name: Cleanup
if: always()
shell: bash
run: |-
set -euo pipefail
# Cleanup temporary files
rm -rf /tmp/.buildx-cache*
# Remove builder instance if created
if docker buildx ls | grep -q builder; then
docker buildx rm builder || true
fi