diff --git a/.github/actions/build-chroot-images/action.yml b/.github/actions/build-chroot-images/action.yml new file mode 100644 index 000000000..e86c6239f --- /dev/null +++ b/.github/actions/build-chroot-images/action.yml @@ -0,0 +1,34 @@ +name: Build cached chroot images +description: Load checkout-built integration images using daily GitHub Actions layer caches +inputs: + browser: + description: Include the API proxy image used by browser tests + default: 'false' + runner-variant: + description: Distinguish the browser runner matrix caches + default: ubuntu-latest +runs: + using: composite + steps: + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1 + with: + driver: docker + + - name: Expose GitHub Actions cache runtime for Buildx CLI + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + with: + script: | + for (const name of ['ACTIONS_RUNTIME_TOKEN', 'ACTIONS_RESULTS_URL']) { + const value = process.env[name]; + if (!value) throw new Error(`Missing ${name} for Buildx cache`); + if (name === 'ACTIONS_RUNTIME_TOKEN') core.setSecret(value); + core.exportVariable(name, value); + } + + - name: Build and verify local integration images + shell: bash + env: + CHROOT_BROWSER: ${{ inputs.browser }} + CHROOT_CACHE_VARIANT: ${{ github.job }}-${{ inputs.runner-variant }}-${{ runner.arch }} + run: bash scripts/ci/build-chroot-images.sh diff --git a/.github/workflows/supply-chain-scan.yml b/.github/workflows/supply-chain-scan.yml index 9a1ce33b6..958ac9853 100644 --- a/.github/workflows/supply-chain-scan.yml +++ b/.github/workflows/supply-chain-scan.yml @@ -156,8 +156,28 @@ jobs: df -h / - name: Configure Docker Hub cache + env: + AWF_DOCKER_CONTAINERD_SNAPSHOTTER: ${{ matrix.scan == 'pr-images' && 'true' || 'false' }} run: bash scripts/ci/configure-docker-mirror.sh + - name: Set up Docker Buildx for cached PR builds + if: matrix.scan == 'pr-images' + uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1 + with: + driver: docker + + - name: Expose GitHub Actions cache runtime for Buildx CLI + if: matrix.scan == 'pr-images' + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + with: + script: | + for (const name of ['ACTIONS_RUNTIME_TOKEN', 'ACTIONS_RESULTS_URL']) { + const value = process.env[name]; + if (!value) throw new Error(`Missing ${name} for Buildx cache`); + if (name === 'ACTIONS_RUNTIME_TOKEN') core.setSecret(value); + core.exportVariable(name, value); + } + - name: Prepare pinned Grype scanner if: matrix.scan != 'licenses' run: docker pull ghcr.io/anchore/grype@sha256:fd4ab4d1042b522c896e73bdf09ab8bf384fa417df99d6dd0d6e1008c7e7c821 @@ -202,6 +222,10 @@ jobs: -e GRYPE_DB_CACHE_DIR=/cache \ ghcr.io/anchore/grype@sha256:fd4ab4d1042b522c896e73bdf09ab8bf384fa417df99d6dd0d6e1008c7e7c821 \ db update + # Docker creates root-owned DB directories; actions/cache runs as the + # runner user and must be able to traverse and archive every file. + sudo chown -R "$(id -u):$(id -g)" "$GRYPE_DB" + chmod -R u+rwX "$GRYPE_DB" - name: Save Grype vulnerability DB cache if: matrix.scan != 'licenses' @@ -263,9 +287,12 @@ jobs: GRYPE_DB: ${{ runner.temp }}/grype-db run: | python3 - <<'PYEOF' - import hashlib, os, subprocess, sys + import datetime, hashlib, os, subprocess, sys cwd = os.getcwd() db_cache = os.environ['GRYPE_DB'] + # Never import yesterday's package layers: refresh apt/apk security + # upgrades at least daily, while reusing all stages within the UTC day. + cache_day = datetime.datetime.now(datetime.timezone.utc).strftime('%Y-%m-%d') # The router build requires the SHA-256 of its OpenAPI contract. with open('containers/router/openapi.yaml', 'rb') as f: router_openapi_sha256 = hashlib.sha256(f.read()).hexdigest() @@ -306,12 +333,28 @@ jobs: tag = f'awf-pr-scan-{name}:pr' tar = f'/tmp/awf-pr-scan-{name}.tar' print(f'::group::docker build {name}', flush=True) - b = subprocess.run(['docker', 'build', *build_args, '-t', tag, context]) + cache_scope = f'supply-chain-v1-{name}-{cache_day}' + # The Docker driver shares the daemon's image store. Do not + # --pull enclave-agent's exact locally built build-tools base. + pull_args = [] if name == 'enclave-agent' else ['--pull'] + b = subprocess.run([ + 'docker', 'buildx', 'build', '--load', '--progress=plain', + *pull_args, + '--cache-from', f'type=gha,version=2,scope={cache_scope}', + '--cache-to', f'type=gha,version=2,mode=max,scope={cache_scope}', + *build_args, '-t', tag, context, + ]) print('::endgroup::', flush=True) prune_build_cache() if b.returncode != 0: print(f'::error::docker build failed for {name}', flush=True) rc = b.returncode + # Cache export can fail after --load has created the tag. + subprocess.run( + ['docker', 'image', 'rm', '--force', tag], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + ) continue if name == 'build-tools': build_tools_ready = True diff --git a/.github/workflows/test-chroot.yml b/.github/workflows/test-chroot.yml index 32551fc49..4eef735b5 100644 --- a/.github/workflows/test-chroot.yml +++ b/.github/workflows/test-chroot.yml @@ -26,6 +26,8 @@ jobs: uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v4 - name: Configure Docker Hub cache + env: + AWF_DOCKER_CONTAINERD_SNAPSHOTTER: 'true' run: bash scripts/ci/configure-docker-mirror.sh - name: Setup Node.js @@ -41,10 +43,10 @@ jobs: run: /opt/google/chrome/chrome --version - name: Build local containers - run: | - docker build -t ghcr.io/github/gh-aw-firewall/squid:latest containers/squid/ - docker build -t ghcr.io/github/gh-aw-firewall/agent:latest containers/agent/ - docker build -t ghcr.io/github/gh-aw-firewall/api-proxy:latest containers/api-proxy/ + uses: ./.github/actions/build-chroot-images + with: + browser: 'true' + runner-variant: ${{ matrix.os }} - name: Run real chroot browser launch run: npm run test:integration -- --testPathPatterns=chroot-browser --verbose @@ -63,6 +65,8 @@ jobs: uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v4 - name: Configure Docker Hub cache + env: + AWF_DOCKER_CONTAINERD_SNAPSHOTTER: 'true' run: bash scripts/ci/configure-docker-mirror.sh - name: Setup Node.js @@ -136,10 +140,7 @@ jobs: run: npm run build - name: Build local containers - run: | - echo "=== Building local containers ===" - docker build -t ghcr.io/github/gh-aw-firewall/squid:latest containers/squid/ - docker build -t ghcr.io/github/gh-aw-firewall/agent:latest containers/agent/ + uses: ./.github/actions/build-chroot-images - name: Pre-test cleanup run: | @@ -181,6 +182,8 @@ jobs: uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v4 - name: Configure Docker Hub cache + env: + AWF_DOCKER_CONTAINERD_SNAPSHOTTER: 'true' run: bash scripts/ci/configure-docker-mirror.sh - name: Setup Node.js @@ -283,10 +286,7 @@ jobs: run: npm run build - name: Build local containers - run: | - echo "=== Building local containers ===" - docker build -t ghcr.io/github/gh-aw-firewall/squid:latest containers/squid/ - docker build -t ghcr.io/github/gh-aw-firewall/agent:latest containers/agent/ + uses: ./.github/actions/build-chroot-images - name: Pre-test cleanup run: | @@ -327,6 +327,8 @@ jobs: uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v4 - name: Configure Docker Hub cache + env: + AWF_DOCKER_CONTAINERD_SNAPSHOTTER: 'true' run: bash scripts/ci/configure-docker-mirror.sh - name: Setup Node.js @@ -360,10 +362,7 @@ jobs: run: npm run build - name: Build local containers - run: | - echo "=== Building local containers ===" - docker build -t ghcr.io/github/gh-aw-firewall/squid:latest containers/squid/ - docker build -t ghcr.io/github/gh-aw-firewall/agent:latest containers/agent/ + uses: ./.github/actions/build-chroot-images - name: Pre-test cleanup run: | @@ -404,6 +403,8 @@ jobs: uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v4 - name: Configure Docker Hub cache + env: + AWF_DOCKER_CONTAINERD_SNAPSHOTTER: 'true' run: bash scripts/ci/configure-docker-mirror.sh - name: Setup Node.js @@ -419,10 +420,7 @@ jobs: run: npm run build - name: Build local containers - run: | - echo "=== Building local containers ===" - docker build -t ghcr.io/github/gh-aw-firewall/squid:latest containers/squid/ - docker build -t ghcr.io/github/gh-aw-firewall/agent:latest containers/agent/ + uses: ./.github/actions/build-chroot-images - name: Pre-test cleanup run: | diff --git a/containers/agent/Dockerfile b/containers/agent/Dockerfile index a04381e49..b7b580468 100644 --- a/containers/agent/Dockerfile +++ b/containers/agent/Dockerfile @@ -41,7 +41,7 @@ FROM ubuntu:22.04@sha256:0a9887931b0e38af2e3487ed39e29436b0535c4f3f52e57745baaf7 RUN set -eux; \ BROWSER_PKGS="libasound2 libatk-bridge2.0-0 libatk1.0-0 libatspi2.0-0 libcairo2 libcups2 libdbus-1-3 libdrm2 libexpat1 libgbm1 libglib2.0-0 libnspr4 libnss3 libpango-1.0-0 libpangocairo-1.0-0 libudev1 libx11-6 libxcb1 libxcomposite1 libxdamage1 libxext6 libxfixes3 libxkbcommon0 libxrandr2 libxrender1 libxshmfence1 fonts-liberation"; \ - apt-get -o Acquire::Retries=3 update && \ + apt-get -o Acquire::Retries=3 -o APT::Update::Error-Mode=any update && \ apt-get -o Acquire::Retries=3 install -y --no-install-recommends $BROWSER_PKGS && \ apt-get -o Acquire::Retries=3 upgrade -y --no-install-recommends && \ # Include dependencies already in the base image (e.g. libpcre3), not just @@ -65,42 +65,12 @@ RUN set -eux; \ FROM ${BASE_IMAGE} AS one-shot-token-build COPY one-shot-token/one-shot-token.c /tmp/one-shot-token.c +# Use the base image's standard archive/security mirrors, not DNS-only Azure selection. RUN set -eux; \ - force_archive_mirror() { \ - echo "Falling back to archive.ubuntu.com mirror..." >&2; \ - if [ -f /etc/apt/sources.list ]; then \ - sed -i 's|http://azure.archive.ubuntu.com|http://archive.ubuntu.com|g' /etc/apt/sources.list; \ - sed -i 's|http://security.ubuntu.com|http://archive.ubuntu.com|g' /etc/apt/sources.list 2>/dev/null || true; \ - fi; \ - if [ -d /etc/apt/sources.list.d ]; then \ - find /etc/apt/sources.list.d -name '*.sources' -exec \ - sed -i -e 's|http://azure.archive.ubuntu.com|http://archive.ubuntu.com|g' \ - -e 's|http://security.ubuntu.com|http://archive.ubuntu.com|g' {} + 2>/dev/null || true; \ - fi; \ - rm -rf /var/lib/apt/lists/* && \ - apt-get -o Acquire::Retries=3 -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 update; \ - }; \ - apt_install_retry() { \ - apt-get -o Acquire::Retries=3 -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 \ - install -y --no-install-recommends "$@" && return 0; \ - echo "apt-get install failed (likely mirror fetch timeout), forcing archive.ubuntu.com and retrying..." >&2; \ - force_archive_mirror; \ - apt-get -o Acquire::Retries=3 -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 \ - install -y --no-install-recommends "$@"; \ - }; \ - if getent hosts azure.archive.ubuntu.com >/dev/null 2>&1; then \ - if [ -f /etc/apt/sources.list ]; then \ - sed -i 's|http://archive.ubuntu.com|http://azure.archive.ubuntu.com|g' /etc/apt/sources.list; \ - sed -i 's|http://security.ubuntu.com|http://azure.archive.ubuntu.com|g' /etc/apt/sources.list; \ - fi; \ - if [ -d /etc/apt/sources.list.d ]; then \ - find /etc/apt/sources.list.d -name '*.sources' -exec \ - sed -i -e 's|http://archive.ubuntu.com|http://azure.archive.ubuntu.com|g' \ - -e 's|http://security.ubuntu.com|http://azure.archive.ubuntu.com|g' {} +; \ - fi; \ - fi && \ - apt-get -o Acquire::Retries=3 -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 update && \ - apt_install_retry gcc libc6-dev binutils && \ + apt-get -o Acquire::Retries=3 -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 \ + -o APT::Update::Error-Mode=any update && \ + apt-get -o Acquire::Retries=3 -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 \ + install -y --no-install-recommends gcc libc6-dev binutils && \ gcc -shared -fPIC -fvisibility=hidden -O2 -Wall -s \ -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=0 \ -o /tmp/one-shot-token.so /tmp/one-shot-token.c -ldl -lpthread && \ @@ -110,85 +80,34 @@ FROM ${BASE_IMAGE} COPY --from=browser-libs /usr/local/share/awf/ /usr/local/share/awf/ -# Optionally switch to Azure apt mirror for faster package fetches in CI -# Only rewrite if azure.archive.ubuntu.com is resolvable (BuildKit DNS can fail) -# Falls back to default archive.ubuntu.com which is universally reachable -RUN if getent hosts azure.archive.ubuntu.com >/dev/null 2>&1; then \ - echo "Using Azure apt mirror (DNS resolved successfully)"; \ - if [ -f /etc/apt/sources.list ]; then \ - sed -i 's|http://archive.ubuntu.com|http://azure.archive.ubuntu.com|g' /etc/apt/sources.list; \ - sed -i 's|http://security.ubuntu.com|http://azure.archive.ubuntu.com|g' /etc/apt/sources.list; \ - fi; \ - if [ -d /etc/apt/sources.list.d ]; then \ - find /etc/apt/sources.list.d -name '*.sources' -exec \ - sed -i 's|http://archive.ubuntu.com|http://azure.archive.ubuntu.com|g' {} + 2>/dev/null || true; \ - find /etc/apt/sources.list.d -name '*.sources' -exec \ - sed -i 's|http://security.ubuntu.com|http://azure.archive.ubuntu.com|g' {} + 2>/dev/null || true; \ - fi; \ - else \ - echo "Azure apt mirror not reachable, using default archive.ubuntu.com"; \ - fi - # Install required and runner-parity packages, apply security upgrades, then install # Node.js 22.23.2 and npm 12.2.1. Keeping apt work in one layer avoids repeatedly # downloading package indexes during cold CI builds. # Note: Some packages may already exist in runner-like base images, apt handles this gracefully -# apt_update_retry: retries up to 3 times with backoff; if all fail, reverts to archive.ubuntu.com +# Retain the base image's mirrors; apt retries fetch failures and rejects partial indexes. RUN set -eux; \ - force_archive_mirror() { \ - echo "Falling back to archive.ubuntu.com mirror..." >&2; \ - if [ -f /etc/apt/sources.list ]; then \ - sed -i 's|http://azure.archive.ubuntu.com|http://archive.ubuntu.com|g' /etc/apt/sources.list; \ - sed -i 's|http://security.ubuntu.com|http://archive.ubuntu.com|g' /etc/apt/sources.list 2>/dev/null || true; \ - fi; \ - if [ -d /etc/apt/sources.list.d ]; then \ - find /etc/apt/sources.list.d -name '*.sources' -exec \ - sed -i -e 's|http://azure.archive.ubuntu.com|http://archive.ubuntu.com|g' \ - -e 's|http://security.ubuntu.com|http://archive.ubuntu.com|g' {} + 2>/dev/null || true; \ - fi; \ - rm -rf /var/lib/apt/lists/* && \ - apt-get -o Acquire::Retries=3 -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 update; \ - }; \ apt_update_retry() { \ - local i; for i in 1 2 3; do \ - rm -rf /var/lib/apt/lists/*; \ - if apt-get -o Acquire::Retries=3 -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 \ - update > /tmp/apt-update.log 2>&1; then \ - cat /tmp/apt-update.log; \ - if ! grep -q "Failed to fetch" /tmp/apt-update.log; then return 0; fi; \ - else \ - cat /tmp/apt-update.log; \ - fi; \ - echo "apt-get update attempt $i/3 failed or had fetch failures, retrying in $((i*10))s..." >&2; sleep $((i*10)); \ - done; \ - echo "All apt-get update retries failed, falling back to archive.ubuntu.com..." >&2; \ - force_archive_mirror; \ + apt-get -o Acquire::Retries=3 -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 \ + -o APT::Update::Error-Mode=any update; \ }; \ apt_install_retry() { \ - apt-get -o Acquire::Retries=3 -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 \ - install -y --no-install-recommends "$@" && return 0; \ - echo "apt-get install failed (likely mirror fetch timeout), forcing archive.ubuntu.com and retrying..." >&2; \ - force_archive_mirror; \ apt-get -o Acquire::Retries=3 -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 \ install -y --no-install-recommends "$@"; \ }; \ apt_upgrade_retry() { \ apt-get -o Acquire::Retries=3 -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 \ - upgrade -y && return 0; \ - echo "apt-get upgrade failed (likely mirror fetch timeout), forcing archive.ubuntu.com and retrying..." >&2; \ - force_archive_mirror && \ - apt-get -o Acquire::Retries=3 -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 upgrade -y; \ + upgrade -y; \ }; \ PKGS="iptables curl ca-certificates git gnupg dnsutils net-tools netcat-openbsd libcap2-bin libgdiplus libev-dev libssl-dev php-intl php-gd python3"; \ apt_update_retry && \ apt_install_retry $PKGS && \ # Native packages serve non-chroot execution. Chroot execution uses the # independent Ubuntu 22.04 payload above, never these newer image libraries. - BROWSER_PKGS="$(cat /usr/local/share/awf/browser-packages.txt)"; \ + BROWSER_PKGS="$(cat /usr/local/share/awf/browser-packages.txt)" && \ # Ubuntu 24.04 renamed several of these to time_t-64 variants (e.g. libasound2t64), # and the old names became ambiguous virtual packages. Prefer the t64 package when # the base image provides one, otherwise keep the 22.04 name. - BROWSER_ACTUAL_PKGS=""; \ + BROWSER_ACTUAL_PKGS="" && \ for pkg in $BROWSER_PKGS; do \ if apt-cache show "${pkg}t64" >/dev/null 2>&1; then \ BROWSER_ACTUAL_PKGS="$BROWSER_ACTUAL_PKGS ${pkg}t64"; \ diff --git a/containers/build-tools/Dockerfile b/containers/build-tools/Dockerfile index 9dbf1dad1..527bceb15 100644 --- a/containers/build-tools/Dockerfile +++ b/containers/build-tools/Dockerfile @@ -56,61 +56,14 @@ FROM ubuntu:26.04@sha256:f144425ff09be612d6d9ad965196e9cdc23dae1f42110a8a11a3e9a LABEL org.opencontainers.image.source="https://github.com/github/gh-aw-firewall" LABEL org.opencontainers.image.description="Build-tools sysroot for ARC/DinD agent containers" -# Reuse Azure mirror optimization for legacy and deb822 Ubuntu sources. -RUN if getent hosts azure.archive.ubuntu.com >/dev/null 2>&1; then \ - echo "Using Azure apt mirror (DNS resolved successfully)"; \ - if [ -f /etc/apt/sources.list ]; then \ - sed -i 's|http://archive.ubuntu.com|http://azure.archive.ubuntu.com|g' /etc/apt/sources.list; \ - sed -i 's|http://security.ubuntu.com|http://azure.archive.ubuntu.com|g' /etc/apt/sources.list; \ - fi; \ - if [ -d /etc/apt/sources.list.d ]; then \ - find /etc/apt/sources.list.d -name '*.sources' -exec \ - sed -i -e 's|http://archive.ubuntu.com|http://azure.archive.ubuntu.com|g' \ - -e 's|http://security.ubuntu.com|http://azure.archive.ubuntu.com|g' {} +; \ - fi; \ - else \ - echo "Azure apt mirror not reachable, using default archive.ubuntu.com"; \ - fi - # Install build essentials and system libraries. # This mirrors the packages available on GitHub-hosted runner VMs # (see actions/runner-images toolset-2204.json) minus language runtimes. +# Keep Ubuntu's standard archive/security mirrors: DNS reachability alone does +# not establish Azure mirror throughput, and apt timeouts do not bound slow transfers. RUN set -eux; \ - force_archive_mirror() { \ - echo "Falling back to archive.ubuntu.com mirror..." >&2; \ - if [ -f /etc/apt/sources.list ]; then \ - sed -i 's|http://azure.archive.ubuntu.com|http://archive.ubuntu.com|g' /etc/apt/sources.list; \ - sed -i 's|http://security.ubuntu.com|http://archive.ubuntu.com|g' /etc/apt/sources.list 2>/dev/null || true; \ - fi; \ - if [ -d /etc/apt/sources.list.d ]; then \ - find /etc/apt/sources.list.d -name '*.sources' -exec \ - sed -i -e 's|http://azure.archive.ubuntu.com|http://archive.ubuntu.com|g' \ - -e 's|http://security.ubuntu.com|http://archive.ubuntu.com|g' {} + 2>/dev/null || true; \ - fi; \ - rm -rf /var/lib/apt/lists/* && apt-get update; \ - }; \ - apt_update_retry() { \ - local i; for i in 1 2 3; do \ - rm -rf /var/lib/apt/lists/*; \ - if apt-get update > /tmp/apt-update.log 2>&1; then \ - cat /tmp/apt-update.log; \ - if ! grep -q "Failed to fetch" /tmp/apt-update.log; then return 0; fi; \ - else \ - cat /tmp/apt-update.log; \ - fi; \ - echo "apt-get update attempt $i/3 failed, retrying in $((i*10))s..." >&2; sleep $((i*10)); \ - done; \ - echo "All apt-get update retries failed, falling back to archive.ubuntu.com..." >&2; \ - force_archive_mirror; \ - }; \ - apt_install_retry() { \ - apt-get install -y --no-install-recommends "$@" && return 0; \ - echo "apt-get install failed, forcing archive.ubuntu.com and retrying..." >&2; \ - force_archive_mirror; \ - apt-get install -y --no-install-recommends "$@"; \ - }; \ - apt_update_retry && \ - apt_install_retry \ + apt-get -o Acquire::Retries=3 -o APT::Update::Error-Mode=any update && \ + apt-get -o Acquire::Retries=3 install -y --no-install-recommends \ # Build toolchain build-essential gcc g++ make cmake autoconf automake libtool \ pkg-config binutils bison flex m4 \ @@ -131,7 +84,7 @@ RUN set -eux; \ libcap2-bin gosu gnupg \ && \ # Upgrade all packages for security patches - apt-get upgrade -y && \ + apt-get -o Acquire::Retries=3 upgrade -y && \ # Match the agent image: the inherited Pebble service manager is not used. rm -f /usr/bin/pebble && \ rm -rf /var/lib/apt/lists/* /tmp/* diff --git a/docs/INTEGRATION-TESTS.md b/docs/INTEGRATION-TESTS.md index 3905ec7d6..fa78fde1d 100644 --- a/docs/INTEGRATION-TESTS.md +++ b/docs/INTEGRATION-TESTS.md @@ -71,6 +71,70 @@ digests. Scan targets, vulnerability database updates, and the blocking High/Critical PR-image gate are unchanged. The setup script validates the merged daemon configuration before restart and refuses local or self-hosted runners. +For PR-image scans only, the runner opts into Docker's containerd image store +before pulling images, then uses Buildx's `docker` driver with `--load`. Each +image imports/exports a separate GitHub Actions v2 build cache (`mode=max`), +scoped by image and UTC date. Only the current day's scope is imported: the first +build each UTC day reruns package installation and security upgrades, rather than +indefinitely reusing stale apt/apk layers. Within that day, fresh hosted runners +can reuse the layers subject to normal Actions cache visibility/eviction. +Cache export failures remain build failures, not silently ignored warnings. + +The shared build-tools image remains in the local daemon until enclave-agent +finishes; that dependent build does not pull a replacement base. Intermediate +builder cache is pruned after each export, and scanned image archives/images are +removed sequentially to bound disk use. Build-tools retains Ubuntu's default +archive/security mirrors instead of selecting Azure based on DNS alone. Apt +retries transient fetch failures, treats incomplete index updates as errors, and +still upgrades every installed package. + +After Grype's DB warm-up, the job restores ownership and owner read/write/traverse +permissions to the runner user before `actions/cache/save` archives the DB. +Warm-up and permission-repair failures stop the job. The +`scripts/ci/docker-registry-ci.test.ts` and +`scripts/ci/apt-mirror-dockerfiles.test.ts` fixtures cover these cache, freshness, +mirror, scan-failure, base-image lifetime, and cleanup contracts; they do not +replace a Linux Docker/hosted-runner build. + +All five chroot job definitions (including both browser runner variants) use +`.github/actions/build-chroot-images` to build the checkout's Squid and agent, +plus API proxy for browser tests, with the exact existing `:latest` local tags. +The composite action uses the same Docker-driver/containerd-store and daily +GitHub Actions v2 cache policy. Its scopes are separate by image, job, runner +variant, and architecture to avoid concurrent matrix writers colliding; no +previous-day scopes are imported. It verifies loaded images and prunes only +intermediate build cache after export, keeping the images needed by tests. +Build, cache export, inspection, and pruning errors fail preparation rather than +running tests against incomplete images. Existing suites, runner matrix, cleanup, +network isolation, and job/test timeout limits are unchanged. + +The agent's token-compiler and runtime stages now retain their base image's apt +mirrors rather than selecting Azure via DNS; all Ubuntu stages reject partial +index updates, retain fetch retries, and preserve required packages and runtime +security upgrades. The oldest-runner browser payload and native t64 dependency +resolution are unchanged. `scripts/ci/chroot-image-cache.test.ts` exercises the +shared builder with Docker test doubles; actual Linux chroot execution remains +the responsibility of the integration jobs. Grype is not used by these jobs. + +### NVX harness-observation limitation + +NVX currently launches the configured command through one atomic +`NvxManager.execute()` lifecycle. It does not expose a persistent ready guest or +a selected-harness probe/pre-command release interface, so NVX harness +observations remain `runtime_probe_unsupported`. The existing manager tests and +live evidence runner validate NVX execution and result/cleanup behavior only; +they do not establish selected-harness evidence or guest compatibility for a +probe lifecycle. + +**Current live acceptance status:** blocked, not live-accepted. A provider-free +NVX guest acceptance run requires signed OpenVMM/kernel/initramfs/manifest +artifacts, a distro layer, and host tooling including Bubblewrap and +`mkfs.erofs`, in addition to a supported Linux x86_64/KVM runner. The recorded +prerequisite attempt had no signed runtime bundle or distro layer and lacked +Bubblewrap and `mkfs.erofs`. Deterministic fixtures are not a substitute for +that guest evidence. No NVX harness-observation producer or live acceptance is +claimed. + ### Provider-free Docker harness observations `.github/workflows/test-docker-harness-observation.yml` automatically runs two diff --git a/scripts/ci/apt-mirror-dockerfiles.test.ts b/scripts/ci/apt-mirror-dockerfiles.test.ts index 04ec7199e..47b07dc76 100644 --- a/scripts/ci/apt-mirror-dockerfiles.test.ts +++ b/scripts/ci/apt-mirror-dockerfiles.test.ts @@ -1,159 +1,97 @@ import * as fs from 'fs'; -import * as os from 'os'; import * as path from 'path'; import { spawnSync } from 'child_process'; -const targets = [ - { image: 'build-tools', stage: 'main', index: 0 }, - { image: 'agent', stage: 'one-shot-token-build', index: 0 }, - { image: 'agent', stage: 'main', index: 1 }, -]; - -const legacySources = [ - 'deb http://archive.ubuntu.com/ubuntu resolute main universe', - 'deb http://security.ubuntu.com/ubuntu resolute-security main universe', - 'deb https://download.docker.com/linux/ubuntu resolute stable', - '', -].join('\n'); - -const deb822Sources = [ - 'Types: deb', - 'URIs: http://archive.ubuntu.com/ubuntu/', - 'Suites: resolute resolute-updates resolute-backports', - 'Components: main universe', - 'Signed-By: /usr/share/keyrings/ubuntu-archive-keyring.gpg', - '', - 'Types: deb', - 'URIs: http://security.ubuntu.com/ubuntu/', - 'Suites: resolute-security', - 'Components: main universe', - 'Signed-By: /usr/share/keyrings/ubuntu-archive-keyring.gpg', - '', -].join('\n'); - -const thirdPartySources = 'Types: deb\nURIs: https://example.com/packages\nSuites: stable\n'; - -describe.each(targets)('$image Dockerfile ($stage) apt mirrors', ({ image, index }) => { - const dockerfile = fs.readFileSync( - path.resolve(__dirname, `../../containers/${image}/Dockerfile`), 'utf8', - ); - const selectionBlocks = dockerfile.match( - /if getent hosts azure\.archive\.ubuntu\.com[\s\S]*?^ fi/gm, - ) ?? []; - const fallbackBlocks = dockerfile.match( - /force_archive_mirror\(\) \{[\s\S]*?^ \};/gm, - ) ?? []; - - it('covers every mirror selection and fallback block', () => { - const expected = targets.filter(target => target.image === image).length; - expect(selectionBlocks).toHaveLength(expected); - expect(fallbackBlocks).toHaveLength(expected); +const read = (image: string) => fs.readFileSync( + path.resolve(__dirname, `../../containers/${image}/Dockerfile`), 'utf8', +); +const instructions = (source: string) => source + .replace(/^[ \t]*#.*\r?\n/gm, '') + .replace(/\\\r?\n/g, ' ') + .split('\n'); + +describe.each(['build-tools', 'agent'])('%s standard Ubuntu mirrors', image => { + const dockerfile = read(image); + + it('retains the base image archive/security sources instead of DNS-only Azure selection', () => { + expect(dockerfile).not.toContain('azure.archive.ubuntu.com'); + expect(dockerfile).not.toContain('getent hosts'); + expect(dockerfile).not.toMatch(/sed .*sources|force_archive_mirror/); }); - describe.each(['legacy', 'deb822', 'mixed', 'missing'])('%s sources', layout => { - let directory: string; - let originals: Map; - - beforeEach(() => { - directory = fs.mkdtempSync(path.join(os.tmpdir(), 'awf-apt-mirror-')); - originals = new Map(); - if (layout === 'legacy' || layout === 'mixed') { - originals.set('sources.list', legacySources); - } - if (layout === 'deb822' || layout === 'mixed') { - originals.set('sources.list.d/ubuntu.sources', deb822Sources); - originals.set('sources.list.d/third-party.sources', thirdPartySources); - } - for (const [file, contents] of originals) { - const destination = path.join(directory, 'apt', file); - fs.mkdirSync(path.dirname(destination), { recursive: true }); - fs.writeFileSync(destination, contents); - } - }); + it('retries fetches and rejects incomplete package indexes in every Ubuntu stage', () => { + const updates = dockerfile.match(/apt-get [^;]*?\bupdate/g) ?? []; + expect(updates).toHaveLength(image === 'agent' ? 3 : 1); + for (const command of updates) { + expect(command).toContain('Acquire::Retries=3'); + expect(command).toContain('APT::Update::Error-Mode=any'); + } + }); +}); - afterEach(() => { - fs.rmSync(directory, { recursive: true, force: true }); - }); +const agentInstructions = instructions(read('agent')); +const cases = [ + { + stage: 'build-tools', + instruction: instructions(read('build-tools')).find(line => line.includes('libcap2-bin gosu gnupg'))!, + stop: 'rm -f /usr/bin/pebble', + packages: ['build-essential gcc g++ make cmake', 'ca-certificates curl wget git jq', 'libcap2-bin gosu gnupg'], + upgrade: true, + }, + { + stage: 'agent token compiler', + instruction: agentInstructions.find(line => line.includes('gcc -shared'))!, + stop: 'gcc -shared', + packages: ['gcc libc6-dev binutils'], + upgrade: false, + }, + { + stage: 'agent browser libraries', + instruction: agentInstructions.find(line => line.startsWith('RUN ') && line.includes('BROWSER_PKGS="'))!, + stop: 'apt-cache depends', + packages: ['libasound2', 'libudev1', 'fonts-liberation'], + upgrade: true, + }, + { + stage: 'agent runtime', + instruction: agentInstructions.find(line => line.includes('NPM_TGZ_URL='))!, + stop: 'rm -f /usr/bin/pebble', + packages: ['iptables curl ca-certificates git gnupg', 'libcap2-bin libgdiplus libev-dev libssl-dev php-intl php-gd python3'], + upgrade: true, + }, +]; - const run = (script: string, dnsStatus = 0, updateStatus = 0) => { - let shell = script - .replace(/\\\r?\n/g, ' ') - .replace(/\/etc\/apt/g, '"$FIXTURE_APT"') - .replace(/\/var\/lib\/apt\/lists/g, '"$FIXTURE_APT/lists"'); - // Docker uses GNU sed; adapt only its in-place flag for local macOS runs. - if (process.platform === 'darwin') { - shell = shell.replace(/sed -i /g, "sed -i '' "); - } - return spawnSync('bash', ['-eu', '-c', ` -getent() { return "$DNS_STATUS"; } -rm() { printf 'rm %s\\n' "$*"; } -apt-get() { printf 'apt-get %s\\n' "$*"; return "$UPDATE_STATUS"; } -${shell} +describe.each(cases)('$stage apt failure handling', ({ instruction, stop, packages, upgrade }) => { + it.each(['success', 'update', 'install', ...(upgrade ? ['upgrade'] : [])])( + 'preserves required packages and stops on %s failure', + failure => { + expect(instruction).toBeDefined(); + expect(instruction.indexOf(stop)).toBeGreaterThan(0); + const script = instruction.slice('RUN '.length, instruction.indexOf(stop)); + const result = spawnSync('bash', ['-eu', '-c', ` +apt-get() { + printf 'apt-get %s\\n' "$*" + case " $* " in + *" $FAILURE "*) return 100 ;; + esac +} +cat() { printf 'libasound2 libudev1\\n'; } +apt-cache() { return 100; } +${script} printf 'apt-complete\\n' `], { encoding: 'utf8', timeout: 5000, - env: { - PATH: process.env.PATH, - FIXTURE_APT: path.join(directory, 'apt'), - DNS_STATUS: String(dnsStatus), - UPDATE_STATUS: String(updateStatus), - }, + env: { PATH: process.env.PATH, FAILURE: failure }, }); - }; - - const expectSources = (mirror?: 'azure' | 'archive') => { - for (const [file, original] of originals) { - const expected = mirror - ? original.replace( - /http:\/\/(?:archive|security)\.ubuntu\.com/g, - `http://${mirror === 'azure' ? 'azure.archive' : 'archive'}.ubuntu.com`, - ) - : original; - expect(fs.readFileSync(path.join(directory, 'apt', file), 'utf8')).toBe(expected); - } - }; - - it('selects Azure for archive and security sources when DNS resolves', () => { - const result = run(selectionBlocks[index]); - expect(result.error).toBeUndefined(); - expect(result.status).toBe(0); - expectSources('azure'); - }); - - it('leaves sources unchanged when Azure DNS fails', () => { - const result = run(selectionBlocks[index], 1); - expect(result.error).toBeUndefined(); - expect(result.status).toBe(0); - expectSources(); - }); - - it('falls back from Azure to archive and refreshes package indexes', () => { - const selected = run(selectionBlocks[index]); - expect(selected.status).toBe(0); - expectSources('azure'); - const result = run(`${fallbackBlocks[index]}\nforce_archive_mirror`); expect(result.error).toBeUndefined(); - expect(result.status).toBe(0); - expect(result.stderr).toContain('Falling back to archive.ubuntu.com mirror'); - expect(result.stdout).toContain(`rm -rf ${path.join(directory, 'apt/lists')}/*`); - expect(result.stdout).toMatch(/apt-get .*update/); - expectSources('archive'); - }); - - it('normalizes default security sources during fallback', () => { - const result = run(`${fallbackBlocks[index]}\nforce_archive_mirror`); - expect(result.error).toBeUndefined(); - expect(result.status).toBe(0); - expectSources('archive'); - }); - - it('propagates apt update failures after switching back to archive', () => { - const selected = run(selectionBlocks[index]); - expect(selected.status).toBe(0); - const result = run(`${fallbackBlocks[index]}\nforce_archive_mirror`, 0, 100); - expect(result.error).toBeUndefined(); - expect(result.status).toBe(100); - expectSources('archive'); - }); - }); + expect(result.status).toBe(failure === 'success' ? 0 : 100); + expect(result.stdout).toContain('APT::Update::Error-Mode=any update'); + expect(result.stdout.includes('apt-complete')).toBe(failure === 'success'); + if (failure === 'success') { + expect(result.stdout).toContain('install -y --no-install-recommends'); + for (const required of packages) expect(result.stdout).toContain(required); + expect(result.stdout.includes('upgrade -y')).toBe(upgrade); + } + }, + ); }); diff --git a/scripts/ci/build-chroot-images.sh b/scripts/ci/build-chroot-images.sh new file mode 100644 index 000000000..7f1b092dd --- /dev/null +++ b/scripts/ci/build-chroot-images.sh @@ -0,0 +1,46 @@ +#!/usr/bin/env bash +set -euo pipefail + +if [[ "${GITHUB_ACTIONS:-}" != true || "${RUNNER_ENVIRONMENT:-}" != github-hosted || "${RUNNER_OS:-}" != Linux ]]; then + echo "Cached chroot image builds require a GitHub-hosted Linux Actions runner" >&2 + exit 1 +fi + +: "${ACTIONS_RUNTIME_TOKEN:?Buildx cache runtime token is required}" +: "${ACTIONS_RESULTS_URL:?Buildx cache results URL is required}" +: "${CHROOT_CACHE_VARIANT:?Chroot cache variant is required}" +if [[ ! "$CHROOT_CACHE_VARIANT" =~ ^[a-zA-Z0-9._-]+$ ]]; then + echo "Invalid chroot cache variant" >&2 + exit 1 +fi +case "${CHROOT_BROWSER:-false}" in + true) images=(squid agent api-proxy) ;; + false) images=(squid agent) ;; + *) echo "CHROOT_BROWSER must be true or false" >&2; exit 1 ;; +esac + +# Import only today's package layers; never freeze apt/apk security updates. +cache_day=$(date -u +%F) +for image in "${images[@]}"; do + tag="ghcr.io/github/gh-aw-firewall/${image}:latest" + scope="chroot-v1-${CHROOT_CACHE_VARIANT}-${image}-${cache_day}" + echo "::group::Build chroot image ${image}" + status=0 + docker buildx build --load --pull --progress=plain \ + --cache-from "type=gha,version=2,scope=${scope}" \ + --cache-to "type=gha,version=2,mode=max,scope=${scope}" \ + --tag "$tag" "containers/${image}/" || status=$? + echo "::endgroup::" + if (( status == 0 )); then + docker image inspect "$tag" >/dev/null || status=$? + fi + if (( status != 0 )); then + echo "::error::Chroot image build/cache export/inspection failed for ${image} (exit ${status})" >&2 + # Export can fail after --load has already created the tag. + docker image rm --force "$tag" >/dev/null 2>&1 || true + docker builder prune --all --force || true + exit "$status" + fi + # Retain exact loaded images for integration tests, not intermediate layers. + docker builder prune --all --force +done diff --git a/scripts/ci/chroot-image-cache.test.ts b/scripts/ci/chroot-image-cache.test.ts new file mode 100644 index 000000000..c8686c23b --- /dev/null +++ b/scripts/ci/chroot-image-cache.test.ts @@ -0,0 +1,169 @@ +import * as fs from 'fs'; +import * as os from 'os'; +import * as path from 'path'; +import { spawnSync } from 'child_process'; +import * as yaml from 'js-yaml'; + +const root = path.resolve(__dirname, '../..'); +interface Step { + name?: string; + run?: string; + uses?: string; + env?: Record; + with?: Record; +} +const workflow = yaml.load(fs.readFileSync(path.join(root, '.github/workflows/test-chroot.yml'), 'utf8')) as { + permissions: Record; + jobs: Record; +}; +const action = yaml.load(fs.readFileSync(path.join(root, '.github/actions/build-chroot-images/action.yml'), 'utf8')) as { + runs: { using: string; steps: Step[] }; +}; + +describe('chroot cached image wiring', () => { + it('keeps every job, suite, timeout and cleanup while using the shared cache builder', () => { + const expected = [ + ['test-chroot-browser', 'chroot-browser', 30], + ['test-chroot-languages', 'chroot-languages', 30], + ['test-chroot-package-managers', 'chroot-package-managers', 45], + ['test-chroot-procfs', 'chroot-procfs', 30], + ['test-chroot-edge-cases', 'chroot-edge-cases', 30], + ] as const; + expect(Object.keys(workflow.jobs)).toEqual(expected.map(([name]) => name)); + expect(workflow.permissions).toEqual({ contents: 'read' }); + for (const [name, suite, minutes] of expected) { + const job = workflow.jobs[name]; + expect(job['timeout-minutes']).toBe(minutes); + const configure = job.steps.findIndex(step => step.name === 'Configure Docker Hub cache'); + const build = job.steps.findIndex(step => step.name === 'Build local containers'); + const test = job.steps.findIndex(step => step.run?.includes(`--testPathPatterns=${suite}`) + || step.run?.includes(`--testPathPatterns="${suite}"`)); + expect(configure).toBeGreaterThan(0); + expect(job.steps[configure].env).toEqual({ AWF_DOCKER_CONTAINERD_SNAPSHOTTER: 'true' }); + expect(configure).toBeLessThan(build); + expect(build).toBeLessThan(test); + expect(job.steps[build].uses).toBe('./.github/actions/build-chroot-images'); + expect(job.steps.some(step => step.name === 'Post-test cleanup')).toBe(true); + expect(job.steps.some(step => step.run?.includes('docker build'))).toBe(false); + } + const browser = workflow.jobs['test-chroot-browser']; + expect(browser.strategy).toEqual({ + 'fail-fast': false, matrix: { os: ['ubuntu-22.04', 'ubuntu-24.04'] }, + }); + expect(browser.steps.find(step => step.name === 'Build local containers')?.with) + .toEqual({ browser: 'true', 'runner-variant': '${{ matrix.os }}' }); + }); + + it('uses the pinned Docker driver and masks cache credentials before export', () => { + expect(action.runs.using).toBe('composite'); + expect(action.runs.steps[0].uses) + .toBe('docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069'); + expect(action.runs.steps[0].with?.driver).toBe('docker'); + const runtime = action.runs.steps[1]; + expect(runtime.uses).toBe('actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3'); + expect(runtime.with?.script).toContain('core.setSecret(value)'); + expect(runtime.with?.script).toContain('throw new Error'); + expect(runtime.with?.script?.indexOf('core.setSecret(value)')) + .toBeLessThan(runtime.with!.script.indexOf('core.exportVariable(name, value)')); + expect(action.runs.steps[2].env?.CHROOT_CACHE_VARIANT) + .toBe('${{ github.job }}-${{ inputs.runner-variant }}-${{ runner.arch }}'); + }); +}); + +describe('cached chroot image builder', () => { + let temp: string; + beforeEach(() => { + temp = fs.mkdtempSync(path.join(os.tmpdir(), 'awf-chroot-cache-')); + fs.writeFileSync(path.join(temp, 'docker'), `#!/usr/bin/env bash +set -euo pipefail +printf '%s\\n' "$*" >> "$TRACE" +if [[ "$*" == "buildx build"* && "$*" == *"/agent:latest"* && "\${FAILURE:-}" == build ]]; then exit 17; fi +if [[ "$*" == "image inspect"* && "\${FAILURE:-}" == inspect ]]; then exit 18; fi +if [[ "$*" == "builder prune"* && "\${FAILURE:-}" == prune ]]; then exit 19; fi +`, { mode: 0o755 }); + fs.writeFileSync(path.join(temp, 'date'), `#!/usr/bin/env bash +[[ "$*" == "-u +%F" ]] || exit 99 +printf '%s\\n' "$FIXTURE_DAY" +`, { mode: 0o755 }); + }); + afterEach(() => fs.rmSync(temp, { recursive: true, force: true })); + + function run(extra: NodeJS.ProcessEnv = {}) { + return spawnSync('bash', [path.join(root, 'scripts/ci/build-chroot-images.sh')], { + encoding: 'utf8', + timeout: 5000, + env: { + ...process.env, + PATH: `${temp}${path.delimiter}${process.env.PATH}`, + TRACE: path.join(temp, 'trace'), + FIXTURE_DAY: '2026-11-04', + GITHUB_ACTIONS: 'true', + RUNNER_ENVIRONMENT: 'github-hosted', + RUNNER_OS: 'Linux', + ACTIONS_RUNTIME_TOKEN: 'fixture-token', + ACTIONS_RESULTS_URL: 'https://cache.example/', + CHROOT_CACHE_VARIANT: 'test-chroot-languages-ubuntu-latest-X64', + CHROOT_BROWSER: 'false', + ...extra, + }, + }); + } + function trace() { + return fs.readFileSync(path.join(temp, 'trace'), 'utf8').trim().split('\n'); + } + + it.each(['2026-11-04', '2026-11-05'])('imports only %s layers and retains exact local tags', day => { + const result = run({ FIXTURE_DAY: day }); + expect(result.status).toBe(0); + expect(result.stdout + result.stderr).not.toContain('fixture-token'); + const calls = trace(); + expect(calls).toHaveLength(6); + ['squid', 'agent'].forEach((image, index) => { + const scope = `chroot-v1-test-chroot-languages-ubuntu-latest-X64-${image}-${day}`; + expect(calls[index * 3]).toBe( + 'buildx build --load --pull --progress=plain ' + + `--cache-from type=gha,version=2,scope=${scope} ` + + `--cache-to type=gha,version=2,mode=max,scope=${scope} ` + + `--tag ghcr.io/github/gh-aw-firewall/${image}:latest containers/${image}/`, + ); + expect(calls[index * 3 + 1]).toBe(`image inspect ghcr.io/github/gh-aw-firewall/${image}:latest`); + expect(calls[index * 3 + 2]).toBe('builder prune --all --force'); + }); + expect(calls.join('\n')).not.toMatch(/image rm|image prune|system prune|ignore-error/); + }); + + it('includes the browser API proxy but no other unrelated images', () => { + expect(run({ CHROOT_BROWSER: 'true' }).status).toBe(0); + expect(trace().filter(call => call.startsWith('buildx build'))).toHaveLength(3); + expect(trace()[7]).toBe('image inspect ghcr.io/github/gh-aw-firewall/api-proxy:latest'); + }); + + it.each([ + ['build', 17], ['inspect', 18], ['prune', 19], + ])('propagates %s failures instead of running tests on incomplete images', (failure, code) => { + const result = run({ FAILURE: String(failure), CHROOT_BROWSER: 'true' }); + expect(result.status).toBe(code); + const calls = trace(); + expect(calls.join('\n')).not.toContain('api-proxy'); + if (failure === 'build') { + expect(result.stderr).toContain('::error::Chroot image build/cache export/inspection failed for agent'); + expect(calls.slice(-2)).toEqual([ + 'image rm --force ghcr.io/github/gh-aw-firewall/agent:latest', 'builder prune --all --force', + ]); + } + if (failure === 'inspect') { + expect(calls.slice(-2)).toEqual([ + 'image rm --force ghcr.io/github/gh-aw-firewall/squid:latest', 'builder prune --all --force', + ]); + } + }); + + it.each([ + { GITHUB_ACTIONS: 'false' }, { RUNNER_ENVIRONMENT: 'self-hosted' }, { RUNNER_OS: 'macOS' }, + { ACTIONS_RUNTIME_TOKEN: '' }, { ACTIONS_RESULTS_URL: '' }, { CHROOT_CACHE_VARIANT: '' }, + { CHROOT_CACHE_VARIANT: 'bad,scope=oops' }, { CHROOT_BROWSER: 'maybe' }, + ])('fails before Docker on unsupported environment %j', extra => { + expect(run(extra).status).not.toBe(0); + expect(fs.existsSync(path.join(temp, 'trace'))).toBe(false); + }); +}); diff --git a/scripts/ci/configure-docker-mirror.sh b/scripts/ci/configure-docker-mirror.sh index b147dfea8..19fb4c8c1 100755 --- a/scripts/ci/configure-docker-mirror.sh +++ b/scripts/ci/configure-docker-mirror.sh @@ -18,9 +18,13 @@ else fi # Preserve runner settings and existing mirrors; never relax TLS verification. -jq --exit-status --arg mirror "$mirror" ' +jq --exit-status --arg mirror "$mirror" \ + --arg snapshotter "${AWF_DOCKER_CONTAINERD_SNAPSHOTTER:-false}" ' if type != "object" then error("Docker daemon config must be an object") else . end | .["registry-mirrors"] = ([$mirror] + ((.["registry-mirrors"] // []) | map(select(. != $mirror)))) + | if $snapshotter == "true" then .features["containerd-snapshotter"] = true + elif $snapshotter == "false" then . + else error("AWF_DOCKER_CONTAINERD_SNAPSHOTTER must be true or false") end ' "$config" > "$config.updated" mv "$config.updated" "$config" sudo dockerd --validate --config-file "$config" @@ -28,3 +32,9 @@ sudo install -m 0644 "$config" /etc/docker/daemon.json sudo systemctl restart docker docker info --format '{{json .RegistryConfig.Mirrors}}' | jq --exit-status --arg mirror "$mirror/" 'index($mirror) != null' +if [[ "${AWF_DOCKER_CONTAINERD_SNAPSHOTTER:-false}" == true ]]; then + # The Docker Buildx driver needs this store for external cache export while + # keeping locally loaded images available to dependent FROM instructions. + docker info --format '{{json .DriverStatus}}' | + jq --exit-status 'any(.[]; . == ["driver-type", "io.containerd.snapshotter.v1"])' +fi diff --git a/scripts/ci/docker-registry-ci.test.ts b/scripts/ci/docker-registry-ci.test.ts index e85aa52d9..5ce8b0ee0 100644 --- a/scripts/ci/docker-registry-ci.test.ts +++ b/scripts/ci/docker-registry-ci.test.ts @@ -56,15 +56,20 @@ describe('CI registry retrieval', () => { expect(buildTools).toContain('test "$(gosu nobody id -u)" = 65534'); }); - it.each(['success', 'base-build', 'agent-build', 'scan', 'save'])( - 'retains the shared PR base through dependent builds and cleans up on %s', - (failure) => { + it.each([ + ['success', '2026-11-04'], + ['success', '2026-11-05'], + ...['base-build', 'agent-build', 'cache-export', 'scan', 'save'] + .map(failure => [failure, '2026-11-04']), + ])( + 'retains the shared PR base through dependent builds and cleans up on %s (%s)', + (failure, day) => { const step = jobs('supply-chain-scan.yml')['image-scans'].steps.find( (entry) => entry.name?.startsWith('Build and scan PR container images'), )!; const python = step.run!.split("<<'PYEOF'\n")[1].split('\nPYEOF')[0]; const result = spawnSync('python3', ['-c', ` -import contextlib, io, json, os, subprocess, sys +import contextlib, datetime, io, json, os, subprocess, sys from unittest.mock import patch code = sys.stdin.read() live = set() @@ -73,17 +78,25 @@ cache = set() calls = [] saves = [] failure = sys.argv[1] +class Clock(datetime.datetime): + @classmethod + def now(cls, tz=None): + return cls.fromisoformat(sys.argv[2]).replace(tzinfo=tz) base = 'awf-pr-scan-build-tools:pr' agent = 'awf-pr-scan-enclave-agent:pr' def run(args, **kwargs): calls.append(args) rc = 0 - if args[:2] == ['docker', 'build']: + if args[:3] == ['docker', 'buildx', 'build']: tag = args[args.index('-t') + 1] if tag == agent and base not in live: raise AssertionError('base removed before enclave-agent build') cache.add(tag) - if (failure == 'base-build' and tag == base) or (failure == 'agent-build' and tag == agent): + if failure == 'cache-export': + # Buildx may load the result before the remote cache exporter fails. + live.add(tag) + if ((failure == 'base-build' and tag == base) or (failure == 'agent-build' and tag == agent) + or (failure == 'cache-export' and tag == 'awf-pr-scan-api-proxy:pr')): rc = 1 else: live.add(tag) @@ -107,7 +120,8 @@ def run(args, **kwargs): raise AssertionError('unexpected image/system prune: ' + ' '.join(args)) return subprocess.CompletedProcess(args, rc) exit_code = 0 -with patch('subprocess.run', run), patch.dict(os.environ, {'GRYPE_DB': '/tmp/mock-db'}), \\ +with patch('subprocess.run', run), patch('datetime.datetime', Clock), \\ + patch.dict(os.environ, {'GRYPE_DB': '/tmp/mock-db'}), \\ patch('os.path.exists', lambda file: file in archives), patch('os.remove', archives.remove): with contextlib.redirect_stdout(io.StringIO()): try: @@ -118,7 +132,7 @@ with patch('subprocess.run', run), patch.dict(os.environ, {'GRYPE_DB': '/tmp/moc exit_code = error.returncode print(json.dumps({'live': sorted(live), 'archives': sorted(archives), 'cache': sorted(cache), 'saves': saves, 'calls': calls, 'exit': exit_code})) -`, failure], { cwd: root, input: python, encoding: 'utf8' }); +`, failure, day], { cwd: root, input: python, encoding: 'utf8' }); expect(result.stderr).toBe(''); expect(result.status).toBe(0); const trace = JSON.parse(result.stdout) as { @@ -140,13 +154,31 @@ print(json.dumps({'live': sorted(live), 'archives': sorted(archives), 'cache': s } expect(trace.exit).toBe(failure === 'success' ? 0 : failure === 'scan' ? 2 : 1); const agentBuild = trace.calls.find((args) => - args[1] === 'build' && args.includes('awf-pr-scan-enclave-agent:pr')); + args[1] === 'buildx' && args.includes('awf-pr-scan-enclave-agent:pr')); if (failure === 'base-build' || failure === 'save') { expect(agentBuild).toBeUndefined(); } else { expect(agentBuild).toBeDefined(); } const scans = trace.calls.filter((args) => args[1] === 'run'); + const builds = trace.calls.filter((args) => args[1] === 'buildx'); + expect(builds.length).toBeGreaterThan(0); + const scopes = new Set(); + for (const args of builds) { + const tag = args[args.indexOf('-t') + 1]; + const name = tag.slice('awf-pr-scan-'.length, -':pr'.length); + const scope = `supply-chain-v1-${name}-${day}`; + scopes.add(scope); + expect(args).toContain('--load'); + expect(args[args.indexOf('--cache-from') + 1]).toBe(`type=gha,version=2,scope=${scope}`); + expect(args[args.indexOf('--cache-to') + 1]).toBe(`type=gha,version=2,mode=max,scope=${scope}`); + expect(args.includes('--pull')).toBe(name !== 'enclave-agent'); + expect(args.join(' ')).not.toMatch(/ignore-error|no-cache/); + } + expect(scopes.size).toBe(builds.length); + if (agentBuild) { + expect(agentBuild).toContain('BUILD_TOOLS_IMAGE=awf-pr-scan-build-tools:pr'); + } for (const args of scans) { expect(args).toContain(grype); expect(args.slice(args.indexOf('--fail-on'), args.indexOf('--fail-on') + 2)) @@ -155,6 +187,121 @@ print(json.dumps({'live': sorted(live), 'archives': sorted(archives), 'cache': s if (failure === 'success' || failure === 'scan') { expect(scans).toHaveLength(9); } + if (failure === 'cache-export') { + expect(scans).toHaveLength(8); + expect(scans.flat()).not.toContain('docker-archive:/tmp/awf-pr-scan-api-proxy.tar'); + } + }, + ); + + it('sets up an external-cache-capable Docker driver before pulling scanners', () => { + const workflow = jobs('supply-chain-scan.yml'); + const steps = workflow['image-scans'].steps; + const mirror = steps.findIndex(step => step.name === 'Configure Docker Hub cache'); + expect(steps[mirror].env?.AWF_DOCKER_CONTAINERD_SNAPSHOTTER) + .toBe("${{ matrix.scan == 'pr-images' && 'true' || 'false' }}"); + const setup = steps.findIndex(step => step.name === 'Set up Docker Buildx for cached PR builds'); + expect(setup).toBeGreaterThan(mirror); + expect(setup).toBeLessThan(steps.findIndex(step => step.run?.startsWith('docker pull'))); + expect(steps[setup].uses) + .toBe('docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069'); + expect(steps[setup].with?.driver).toBe('docker'); + expect(steps[setup].if).toBe("matrix.scan == 'pr-images'"); + expect(steps[setup]['continue-on-error']).toBeUndefined(); + expect(workflow.compile.steps.some(step => step.env?.AWF_DOCKER_CONTAINERD_SNAPSHOTTER)) + .toBe(false); + }); + + it.each(['complete', 'missing-token', 'missing-url'])( + 'masks the runtime token and fails closed on missing Buildx cache credentials (%s)', + state => { + const step = jobs('supply-chain-scan.yml')['image-scans'].steps.find( + entry => entry.name === 'Expose GitHub Actions cache runtime for Buildx CLI', + )!; + expect(step.if).toBe("matrix.scan == 'pr-images'"); + expect(step.uses).toBe('actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3'); + const result = spawnSync(process.execPath, ['-e', ` +const calls = []; +const core = { + setSecret: value => calls.push(['mask', value]), + exportVariable: (name, value) => calls.push(['export', name, value]), +}; +const env = { + ...(process.argv[1] === 'missing-token' ? {} : { ACTIONS_RUNTIME_TOKEN: 'fixture-token' }), + ...(process.argv[1] === 'missing-url' ? {} : { ACTIONS_RESULTS_URL: 'https://cache.example/' }), +}; +try { + new Function('core', 'process', ${JSON.stringify(step.with?.script)})(core, { env }); +} catch (error) { + process.exitCode = 1; +} +console.log(JSON.stringify(calls)); +`, state], { encoding: 'utf8' }); + expect(result.stderr).toBe(''); + expect(result.status).toBe(state === 'complete' ? 0 : 1); + const calls = JSON.parse(result.stdout) as string[][]; + if (state !== 'missing-token') { + expect(calls.slice(0, 2)).toEqual([ + ['mask', 'fixture-token'], + ['export', 'ACTIONS_RUNTIME_TOKEN', 'fixture-token'], + ]); + } + if (state === 'complete') { + expect(calls).toHaveLength(3); + expect(calls[2]).toEqual(['export', 'ACTIONS_RESULTS_URL', 'https://cache.example/']); + } + }, + ); + + it.each(['success', 'warm-failure', 'chown-failure'])( + 'repairs Grype cache ownership and traversal before saving (%s)', + failure => { + const steps = jobs('supply-chain-scan.yml')['image-scans'].steps; + const warm = steps.findIndex(step => step.name === 'Warm Grype vulnerability DB'); + expect(steps[warm + 1].name).toBe('Save Grype vulnerability DB cache'); + const temp = fs.mkdtempSync(path.join(os.tmpdir(), 'awf-grype-cache-')); + const db = path.join(temp, 'db'); + try { + fs.writeFileSync(path.join(temp, 'docker'), `#!/usr/bin/env bash +set -euo pipefail +echo docker >> "$TRACE" +[[ "$FAILURE" != warm-failure ]] || exit 100 +mkdir -p "$GRYPE_DB/6" +echo fixture-db > "$GRYPE_DB/6/vulnerability.db" +chmod 0500 "$GRYPE_DB/6" +chmod 0400 "$GRYPE_DB/6/vulnerability.db" +`, { mode: 0o755 }); + fs.writeFileSync(path.join(temp, 'sudo'), `#!/usr/bin/env bash +set -euo pipefail +echo "$*" >> "$TRACE" +[[ "$1" == chown && "$2" == -R && "$3" == "$(id -u):$(id -g)" && "$4" == "$GRYPE_DB" ]] +[[ "$FAILURE" != chown-failure ]] || exit 101 +`, { mode: 0o755 }); + const result = spawnSync('bash', ['-e', '-c', steps[warm].run!], { + encoding: 'utf8', + env: { + ...process.env, + PATH: `${temp}${path.delimiter}${process.env.PATH}`, + GRYPE_DB: db, + TRACE: path.join(temp, 'trace'), + FAILURE: failure, + }, + }); + expect(result.stderr).toBe(''); + expect(result.status).toBe(failure === 'success' ? 0 : failure === 'warm-failure' ? 100 : 101); + const trace = fs.readFileSync(path.join(temp, 'trace'), 'utf8').trim().split('\n'); + expect(trace).toHaveLength(failure === 'warm-failure' ? 1 : 2); + if (failure === 'success') { + expect(trace[1]).toBe(`chown -R ${process.getuid!()}:${process.getgid!()} ${db}`); + expect(fs.statSync(path.join(db, '6')).mode & 0o700).toBe(0o700); + expect(fs.statSync(path.join(db, '6/vulnerability.db')).mode & 0o600).toBe(0o600); + const archive = spawnSync('tar', ['-cf', path.join(temp, 'cache.tar'), '-C', db, '.']); + expect(archive.status).toBe(0); + } + } finally { + if (fs.existsSync(path.join(db, '6'))) fs.chmodSync(path.join(db, '6'), 0o700); + fs.rmSync(temp, { recursive: true, force: true }); + } }, ); @@ -169,7 +316,8 @@ print(json.dumps({'live': sorted(live), 'archives': sorted(archives), 'cache': s it.each(affected)('configures the runner mirror before Docker use in %s / %s', (file, job) => { const steps = jobs(file)[job].steps; const setup = steps.findIndex((step) => step.run === 'bash scripts/ci/configure-docker-mirror.sh'); - const docker = steps.findIndex((step) => step.run?.includes('docker ')); + const docker = steps.findIndex((step) => step.run?.includes('docker ') + || step.uses === './.github/actions/build-chroot-images'); expect(setup).toBeGreaterThanOrEqual(0); expect(setup).toBeLessThan(docker); expect(steps[setup].if).toBeUndefined(); @@ -376,7 +524,11 @@ esac fs.writeFileSync(path.join(temp, 'docker'), `#!/usr/bin/env bash set -euo pipefail echo docker >> "$TRACE" -printf '%s\\n' "\${DOCKER_MIRRORS:-[\\"https://mirror.gcr.io/\\"]}" +if [[ "$*" == *DriverStatus* ]]; then + printf '%s\\n' "\${DRIVER_STATUS:-[[\\"driver-type\\",\\"io.containerd.snapshotter.v1\\"]]}" +else + printf '%s\\n' "\${DOCKER_MIRRORS:-[\\"https://mirror.gcr.io/\\"]}" +fi `, { mode: 0o755 }); }); @@ -423,6 +575,31 @@ printf '%s\\n' "\${DOCKER_MIRRORS:-[\\"https://mirror.gcr.io/\\"]}" }); }); + it('opts into the containerd store without losing other daemon features', () => { + fs.writeFileSync(path.join(temp, 'daemon.json'), JSON.stringify({ + features: { other: true, 'containerd-snapshotter': false }, + })); + expect(run({ AWF_DOCKER_CONTAINERD_SNAPSHOTTER: 'true' }).status).toBe(0); + expect(JSON.parse(fs.readFileSync(path.join(temp, 'daemon.json'), 'utf8'))).toEqual({ + features: { other: true, 'containerd-snapshotter': true }, + 'registry-mirrors': ['https://mirror.gcr.io'], + }); + expect(fs.readFileSync(path.join(temp, 'trace'), 'utf8').trim().split('\n').slice(-2)) + .toEqual(['docker', 'docker']); + }); + + it('does not silently proceed with an unsupported external cache store', () => { + expect(run({ + AWF_DOCKER_CONTAINERD_SNAPSHOTTER: 'true', + DRIVER_STATUS: '[["Backing Filesystem","extfs"]]', + }).status).not.toBe(0); + }); + + it('rejects invalid snapshotter settings before restarting Docker', () => { + expect(run({ AWF_DOCKER_CONTAINERD_SNAPSHOTTER: 'yes' }).status).not.toBe(0); + expect(fs.readFileSync(path.join(temp, 'trace'), 'utf8')).not.toContain('systemctl'); + }); + it.each(['not-json', '[]', '{"registry-mirrors":42}'])('rejects invalid config %s without restarting', (config) => { fs.writeFileSync(path.join(temp, 'daemon.json'), config); expect(run().status).not.toBe(0);