From 528e1d0a55351568b7dd6c608c5d1c303fb7f9d1 Mon Sep 17 00:00:00 2001 From: david ruiz Date: Mon, 23 Nov 2026 11:25:51 +0100 Subject: [PATCH 1/2] new CI pipeline --- .github/scripts/gradle.sh | 178 +++++ .../scripts/update-verification-metadata.sh | 40 + .github/scripts/verify-artifacts.py | 556 ++++++++++++++ .github/workflows/build-master.yml | 15 +- .github/workflows/build-pull-request.yml | 21 +- .github/workflows/build-release.yml | 443 ++++++++++- .github/workflows/codeql-analysis.yml | 25 +- build.gradle | 26 +- gradle/verification-metadata.xml | 693 ++++++++++++++++++ gradle/wrapper/gradle-wrapper.properties | 1 + 10 files changed, 1931 insertions(+), 67 deletions(-) create mode 100755 .github/scripts/gradle.sh create mode 100755 .github/scripts/update-verification-metadata.sh create mode 100755 .github/scripts/verify-artifacts.py create mode 100644 gradle/verification-metadata.xml diff --git a/.github/scripts/gradle.sh b/.github/scripts/gradle.sh new file mode 100755 index 000000000..b988f1009 --- /dev/null +++ b/.github/scripts/gradle.sh @@ -0,0 +1,178 @@ +#!/usr/bin/env bash +# The only way CI runs Gradle: bash .github/scripts/gradle.sh ... +# +# 1. Arguments: tasks and a short allowlist of options only (no system properties, project +# directory, init script or verification flag can reach Gradle from a workflow). +# 2. Early warning (static): gradle/verification-metadata.xml verifies metadata and trusts no +# artifact or key without a checksum, the wrapper settings are exactly the official download +# into the Gradle user home with its sha256, gradle.properties holds project values only, and no +# Gradle user home init script, properties file, environment variable or build script +# mentions dependency verification. +# 3. Canary (runtime, the check that matters): Gradle starts from the validated wrapper jar, not +# the committed gradlew script. A first run, before settings are evaluated, resolves an +# artifact gradle/verification-metadata.xml does not list and stops; dependency verification +# must refuse it. What that run left is removed, then the build runs with exactly the same +# command line (the same init script path, now empty). +# 4. The working tree must be clean before, between and after the runs: no build logic may +# rewrite tracked files (gradle.properties, the metadata, this script). +set -euo pipefail + +fail() { echo "::error::$1"; exit 1; } +cd "$(git rev-parse --show-toplevel)" + +# ---- 1. arguments +previous="" +for arg in "$@"; do + if [ "$previous" = "-x" ]; then + [[ "$arg" =~ ^[a-z][A-Za-z0-9]*$ ]] || fail "gradle.sh: -x needs a task name" + else + case "$arg" in + --no-daemon | --no-build-cache | --fail-fast | --no-scan | -q | --quiet | --stacktrace | -x) ;; + *) [[ "$arg" =~ ^[a-z][A-Za-z0-9]*$ ]] || fail "gradle.sh does not pass $arg to Gradle" ;; + esac + fi + previous="$arg" +done +[ "$previous" != "-x" ] || fail "gradle.sh: -x needs a task name" + +# ---- 2. early warning +metadata=gradle/verification-metadata.xml +[ -f "$metadata" ] && [ ! -L "$metadata" ] || fail "$metadata is missing" +grep -qx ' true' "$metadata" || fail "$metadata must keep true" +if grep -qiE 'trusted-artifacts|<([a-z0-9_-]+:)?trust[[:space:]>/]|ignored-key|trusted-key|/dev/null || shasum -a 256 "$zip") | cut -d' ' -f1)" + [ "$actual" = "$dist_sha" ] || fail "$zip does not match distributionSha256Sum" +done +if [ -d "$gradle_home/init.d" ] && [ -n "$(ls -A "$gradle_home/init.d")" ]; then + fail "$gradle_home/init.d holds init scripts" +fi +for script in init.gradle init.gradle.kts; do + [ ! -e "$gradle_home/$script" ] || fail "$gradle_home/$script exists" +done +# Tracked gradle.properties: project values only. Every line is a plain lowercase key, no dot, +# no backslash (no org.gradle.* setting such as jvmargs or java.home, no systemProp.*, no escape +# or continuation line). +pattern='verification|\\u|disableDependencyVerification' +while IFS= read -r -d '' file; do + if grep -vE '^[[:space:]]*(#.*)?$' "$file" | grep -qvE '^[a-z][a-z0-9_]*=[^\\]*$'; then + fail "$file may only hold plain project values (key=value, lowercase key without dots)" + fi +done < <(git ls-files -z -- '*gradle.properties') +if [ -f "$gradle_home/gradle.properties" ] && grep -qiE "$pattern|org\.gradle\.|systemProp" "$gradle_home/gradle.properties"; then + fail "$gradle_home/gradle.properties holds Gradle settings" +fi +if env | grep -qiE 'verification'; then + fail "an environment variable mentions dependency verification" +fi +if env | grep -qiE '^(GRADLE_OPTS|JAVA_OPTS|JAVA_TOOL_OPTIONS|JDK_JAVA_OPTIONS|_JAVA_OPTIONS)=.*(-javaagent|-agentpath|-agentlib|-Xbootclasspath|java\.home)'; then + fail "a JVM options variable loads an agent or changes the boot class path" +fi +while IFS= read -r -d '' file; do + if grep -qiE 'DependencyVerification|dependency[._-]?verification' "$file"; then + fail "$file changes dependency verification" + fi +done < <(git ls-files -z -- '*.gradle' '*.gradle.kts' 'gradlew' 'gradlew.bat') +[ -z "$(git status --porcelain)" ] || fail "the working tree is not clean before the build" + +# ---- 3. canary, then the build, with the same command line +# The committed gradlew script is not used: Gradle starts from the wrapper jar, which every job +# validates first (gradle/actions/wrapper-validation), so no repository script sits between this +# check and Gradle. Gradle keeps a verification failure for the rest of an invocation, so the +# probe has its own run. Both runs have exactly the same command line (same init script path, +# same arguments); only the init script's content differs. The probe fires before settings are +# evaluated, so no settings plugin, build script or plugin is resolved or run before it. +work="$(mktemp -d)" +trap 'rm -rf "$work"' EXIT +init="$work/init.gradle" +java_cmd="java" +if [ -n "${JAVA_HOME:-}" ]; then java_cmd="$JAVA_HOME/bin/java"; fi +gradle() { + "$java_cmd" -Xmx64m -Xms64m -Dorg.gradle.appname=gradlew \ + -classpath gradle/wrapper/gradle-wrapper.jar org.gradle.wrapper.GradleWrapperMain \ + --init-script "$init" "$@" +} + +cat > "$init" <<'GRADLE' +beforeSettings { settings -> + settings.buildscript.repositories.mavenCentral() + def probe = settings.buildscript.configurations.detachedConfiguration( + settings.buildscript.dependencies.create('junit:junit:4.13.2')) + def refused = false + try { + probe.resolve() + } catch (Exception e) { + def text = '' + for (def cause = e; cause != null; cause = cause.cause) { text += String.valueOf(cause.message) + '\n' } + if (!text.contains('Dependency verification failed')) { + throw new GradleException('VERIFICATION-PROBE-ERROR: the probe failed for another reason', e) + } + refused = true + } + throw new GradleException(refused ? 'VERIFICATION-PROBE-REFUSED' : 'VERIFICATION-PROBE-RESOLVED') +} +GRADLE + +# NUL-separated records: paths with spaces or special characters are handled exactly. Ignored +# and untracked directories are listed once, not file by file, so the comparison stays small +# (the probe fires before any build code, so all it can create is Gradle's own .gradle/). +snapshot() { git status --porcelain=v1 -z --ignored=traditional --untracked-files=normal | od -An -v -tx1 | tr -d ' \n'; } +state_before="$(snapshot)" +git status --porcelain=v1 -z --ignored=traditional --untracked-files=normal > "$work/before.z" +out="$(gradle "$@" 2>&1)" && fail "the dependency verification probe did not run" +if grep -q 'VERIFICATION-PROBE-RESOLVED' <<< "$out"; then + fail "dependency verification is not enforced: an unlisted artifact resolved" +fi +if ! grep -q 'VERIFICATION-PROBE-REFUSED' <<< "$out"; then + echo "$out" | tail -20 + fail "the dependency verification probe failed for another reason" +fi +echo "Dependency verification is enforced (unlisted artifact refused)" + +# Whatever the probe run left (Gradle's project cache, ignored files) goes, so the build run +# starts from the same state as the probe run did. +while IFS= read -r -d '' record; do + code="${record:0:2}" + path="${record:3}" + case "$code" in "??" | "!!") ;; *) fail "the probe run changed a tracked file: $path" ;; esac + case "$path" in /* | ../* | */../* | "") fail "unexpected path after the probe run: $path" ;; esac + known=false + while IFS= read -r -d '' earlier; do + if [ "$earlier" = "$record" ]; then known=true; break; fi + done < "$work/before.z" + if [ "$known" = false ]; then rm -rf -- "./$path"; fi +done < <(git status --porcelain=v1 -z --ignored=traditional --untracked-files=normal) +[ "$(snapshot)" = "$state_before" ] || fail "the probe run changed the working tree" + +: > "$init" +status=0 +gradle "$@" || status=$? + +# ---- 4. nothing tracked changed during the build +if [ -n "$(git status --porcelain)" ]; then + git status --porcelain | head -20 + fail "the build changed the working tree" +fi +exit "$status" diff --git a/.github/scripts/update-verification-metadata.sh b/.github/scripts/update-verification-metadata.sh new file mode 100755 index 000000000..30a9cb125 --- /dev/null +++ b/.github/scripts/update-verification-metadata.sh @@ -0,0 +1,40 @@ +#!/usr/bin/env bash +# Regenerates gradle/verification-metadata.xml (sha256 of every dependency and plugin artifact +# Gradle resolves). Run it after any change to a dependency or plugin version (Dependabot pull +# requests included: Dependabot does not update this file) and review the diff before committing: +# CI fails when an artifact is missing from the file or its checksum differs. No trust rule is +# added: IDEs that download -sources or -javadoc jars need them listed too (run the IDE sync +# once with --write-verification-metadata sha256, or resolve them here). +# +# It uses a fresh Gradle home and an empty local Maven repository, so every artifact is +# downloaded again from Maven Central or the Gradle Plugin Portal instead of a local copy, and +# it resolves every configuration (plugins, compile, test, jacoco, javadoc, the release staging) +# so nothing CI uses is left out. +# Entries already in the file are kept; delete the file first to drop stale ones. +set -euo pipefail + +root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" +cd "$root" +work="$(mktemp -d)" +trap 'rm -rf "$work"' EXIT + +cat > "$work/resolve-all.gradle" <<'GRADLE' +allprojects { + tasks.register('resolveAllConfigurations') { + doLast { + configurations.findAll { it.canBeResolved }.each { it.resolve() } + buildscript.configurations.findAll { it.canBeResolved }.each { it.resolve() } + } + } +} +GRADLE + +# An empty local Maven repository too: build.gradle lists mavenLocal() first, so a developer's +# ~/.m2 copy would otherwise be what gets pinned. +GRADLE_USER_HOME="$work/gradle-home" ./gradlew --no-daemon --quiet -Dmaven.repo.local="$work/m2" \ + --init-script "$work/resolve-all.gradle" \ + --write-verification-metadata sha256 \ + resolveAllConfigurations compileJava compileTestJava javadoc jar sourcesJar javadocJar \ + jacocoTestReport publishMavenPublicationToStagingRepository -x test + +echo "gradle/verification-metadata.xml updated; review 'git diff gradle/verification-metadata.xml'" diff --git a/.github/scripts/verify-artifacts.py b/.github/scripts/verify-artifacts.py new file mode 100755 index 000000000..5b272c79b --- /dev/null +++ b/.github/scripts/verify-artifacts.py @@ -0,0 +1,556 @@ +#!/usr/bin/env python3 +"""Verify the release artifacts before they are signed and uploaded (build-release.yml, verify job). + +Usage: python3 -I .github/scripts/verify-artifacts.py --version --directory [--repo ] + + must hold exactly the five files Maven Central receives for checkout-sdk-java : the +jar, the sources and javadoc jars, the POM and the Gradle module metadata. Every check refuses +on anything unexpected (fail closed): + +- the file set is exact and every file is a regular file; +- every archive: entry names read from the raw central directory and equal to each local + header's name (no NUL, ASCII only, no absolute, `..` or backslash names, no names that differ + only in case, no directory entry with data, no zip comment or trailing data) and a manifest + with exactly the bytes Gradle writes; +- jar: only classes whose package is a package of src/main/java, plus the manifest, whose + Implementation-Version is ; +- sources jar: exactly the tracked src/main/java/**/*.java files, byte for byte, plus the manifest; +- javadoc jar: documentation file types only (no class, jar or other binary; only the javadoc + search-index zips, each holding only its JSON index); +- POM: UTF-8 and ASCII only, its name, description, url, license, developer and scm values + exactly the project_* values of gradle.properties, no DTD, entity or processing instruction, no control or format characters (also + as character references), no attribute below the root, no text next to child elements, the + nested licenses, developers and scm shapes Gradle writes, only the expected top-level elements, coordinates com.checkout:checkout-sdk-java:, and dependencies + exactly the `implementation` dependencies of build.gradle, scope runtime; +- module: no duplicate JSON keys, the same coordinates and dependencies, exactly the two Gradle + variants of the main jar with their expected attributes (JSON types compared too), and each + file entry bound to the real file by size and sha256. + +The expected dependencies come from build.gradle itself, so a dependency change needs no edit +here; a build.gradle declaration this script cannot read fails the check. +""" + +import argparse +import hashlib +import io +import json +import os +import re +import stat +import struct +import subprocess +import sys +import unicodedata +import xml.etree.ElementTree as ET +import zlib +import zipfile + +GROUP = "com.checkout" +ARTIFACT = "checkout-sdk-java" +POM_NS = "{http://maven.apache.org/POM/4.0.0}" +XSI_SCHEMA_LOCATION = "{http://www.w3.org/2001/XMLSchema-instance}schemaLocation" +POM_TOP_LEVEL = { + "modelVersion", "groupId", "artifactId", "version", "name", "description", "url", + "licenses", "developers", "scm", "dependencies", "packaging", +} +POM_LEAVES = {"modelVersion", "groupId", "artifactId", "version", "name", "description", "url", "packaging"} +POM_DEPENDENCY_CHILDREN = {"groupId", "artifactId", "version", "scope"} +# The sources and javadoc jars are attached to the publication as plain artifacts, so the module +# metadata only describes the main jar. Attributes as Gradle writes them for a Java 8 library. +VARIANT_ATTRIBUTES = { + "apiElements": { + "org.gradle.category": "library", "org.gradle.dependency.bundling": "external", + "org.gradle.jvm.version": 8, "org.gradle.libraryelements": "jar", "org.gradle.usage": "java-api", + }, + "runtimeElements": { + "org.gradle.category": "library", "org.gradle.dependency.bundling": "external", + "org.gradle.jvm.version": 8, "org.gradle.libraryelements": "jar", "org.gradle.usage": "java-runtime", + }, +} +COMPONENT_ATTRIBUTES = {"org.gradle.status": "release"} +JAVADOC_EXTENSIONS = {".html", ".css", ".js", ".png", ".gif", ".svg", ".md"} +JAVADOC_NAMES = { + "element-list", "package-list", + "legal/LICENSE", "legal/ADDITIONAL_LICENSE_INFO", "legal/ASSEMBLY_EXCEPTION", + "member-search-index.zip", "package-search-index.zip", "type-search-index.zip", + "module-search-index.zip", "tag-search-index.zip", +} +PLAIN_MANIFEST = b"Manifest-Version: 1.0\r\n\r\n" +DEPENDENCY_LINE = re.compile(r"^\s*implementation\s+'([A-Za-z0-9_.-]+):([A-Za-z0-9_.-]+):([A-Za-z0-9_.-]+)'\s*$") +CONFIGURATION_LINE = re.compile(r"^\s*(api|implementation|runtimeOnly|compileOnlyApi)\b") + + +class VerificationError(Exception): + pass + + +def fail(message): + raise VerificationError(message) + + +def expected_files(version): + base = f"{ARTIFACT}-{version}" + return { + "jar": f"{base}.jar", + "sources": f"{base}-sources.jar", + "javadoc": f"{base}-javadoc.jar", + "pom": f"{base}.pom", + "module": f"{base}.module", + } + + +def check_file_set(directory, files): + if not os.path.isdir(directory) or os.path.islink(directory): + fail(f"{directory} is not a directory") + actual = sorted(os.listdir(directory)) + if actual != sorted(files.values()): + fail(f"the directory must hold exactly {sorted(files.values())}, found {actual}") + for name in files.values(): + mode = os.lstat(os.path.join(directory, name)).st_mode + if not stat.S_ISREG(mode): + fail(f"{name} is not a regular file") + + +def read_dependencies(build_gradle): + expected = set() + with open(build_gradle, encoding="utf-8") as handle: + for number, line in enumerate(handle, 1): + if not CONFIGURATION_LINE.match(line): + continue + match = DEPENDENCY_LINE.match(line) + if not match: + fail(f"build.gradle:{number}: dependency declaration not in the form implementation 'group:name:version'") + expected.add(match.groups()) + if not expected: + fail("build.gradle declares no implementation dependency") + return expected + + +def tracked_sources(repo): + output = subprocess.run( + ["git", "-C", repo, "ls-files", "-z", "--", "src/main/java"], + check=True, capture_output=True, + ).stdout.decode("utf-8") + prefix = "src/main/java/" + sources = {path[len(prefix):] for path in output.split("\0") if path.endswith(".java")} + if not sources: + fail("no tracked source under src/main/java") + return sources + + +def raw_zip_names(data, label): + """Entry names as stored in the zip (zipfile cuts them at a NUL), after checking that the + local entries follow each other from the first byte to the central directory with nothing + in between: no entry can hide from the central directory, and each local name equals the + central one (stream readers such as JarInputStream use the local headers).""" + end = data.rfind(b"PK\x05\x06") + if end < 0 or len(data) - end < 22: + fail(f"{label} has no zip end record") + disk, cd_disk, here, total, size, offset, comment = struct.unpack("= 20 and data[end - 20:end - 16] == b"PK\x06\x07" + if disk or cd_disk or here != total or total == 0xFFFF or offset == 0xFFFFFFFF or zip64: + fail(f"{label} is a multi-disk or zip64 archive") + if offset + size != end: + fail(f"{label} has data between its central directory and its end record") + entries, position = [], offset + for _ in range(total): + if data[position:position + 4] != b"PK\x01\x02": + fail(f"{label} has a damaged central directory") + (needed,) = struct.unpack("