diff --git a/.github/scripts/gradle.sh b/.github/scripts/gradle.sh new file mode 100755 index 000000000..b5ccf863a --- /dev/null +++ b/.github/scripts/gradle.sh @@ -0,0 +1,188 @@ +#!/usr/bin/env bash +# The only way CI runs Gradle: bash .github/scripts/gradle.sh ... +# +# 1. Arguments: task names and a short list of options. Build scans are never published +# (--no-scan on every run). +# 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 +# changes dependency verification. +# 3. Probe run: Gradle starts from the wrapper jar. Before settings are evaluated, an init script +# resolves a probe artifact from a temporary local repository (a coordinate no project uses, +# so it is never in gradle/verification-metadata.xml); dependency verification must refuse it. +# The files that run created are removed, then the build runs with the same command line. +# 4. The working tree is clean before, between and after the runs. +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 files hold project values only: plain lowercase keys without dots, +# values without backslashes. +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 +# The environment variables the JVM or Gradle read (GRADLE_OPTS and JAVA_OPTS are not used, see +# below): no dependency verification setting, agent, boot class path or other Java home. +for variable in JAVA_TOOL_OPTIONS JDK_JAVA_OPTIONS _JAVA_OPTIONS JAVA_OPTIONS; do + if grep -qiE 'verification|-javaagent|-agentpath|-agentlib|-Xbootclasspath|java\.home' <<< "${!variable:-}"; then + fail "$variable sets dependency verification, an agent, the boot class path or the Java home" + fi +done +if env | grep -iE '^ORG_GRADLE_' | grep -qiE 'verification'; then + fail "an ORG_GRADLE_* variable sets dependency verification" +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. probe run, then the build, with the same command line +# Gradle starts from the wrapper jar, which every job validates first +# (gradle/actions/wrapper-validation). A verification failure lasts for the whole invocation, so +# the probe has its own run; both runs use the same command line and the same init script path, +# only the init script's content differs. +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 +# The wrapper jar is started directly, so the client JVM options gradlew would read are not used. +for variable in GRADLE_OPTS JAVA_OPTS; do + if [ -n "${!variable:-}" ]; then + echo "::warning::$variable is set but not used: gradle.sh starts the wrapper jar directly" + fi +done +gradle() { + "$java_cmd" -Xmx64m -Xms64m -Dorg.gradle.appname=gradlew \ + -classpath gradle/wrapper/gradle-wrapper.jar org.gradle.wrapper.GradleWrapperMain \ + --init-script "$init" --no-scan "$@" +} + +# The probe artifact: a coordinate no project uses, served from a temporary local repository. +probe_dir="$work/probe-repository/local/gradle-sh/verification-probe/1" +mkdir -p "$probe_dir" +printf '%s\n' '4.0.0local.gradle-shverification-probe1' \ + > "$probe_dir/verification-probe-1.pom" +printf 'probe\n' > "$probe_dir/verification-probe-1.jar" + +cat > "$init" < + settings.buildscript.repositories.maven { url = new File('$work/probe-repository').toURI() } + def probe = settings.buildscript.configurations.detachedConfiguration( + settings.buildscript.dependencies.create('local.gradle-sh:verification-probe:1')) + 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, so paths with spaces or special characters are compared exactly. +# Ignored and untracked directories are listed once, not file by file. +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)" + +# Files the probe run added (Gradle's project cache) are removed, so the build run starts from the +# same state. +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..dec00e1c1 --- /dev/null +++ b/.github/scripts/update-verification-metadata.sh @@ -0,0 +1,38 @@ +#!/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, 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 + +GRADLE_USER_HOME="$work/gradle-home" ./gradlew --no-daemon --quiet --no-scan \ + --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..1720f6c1a --- /dev/null +++ b/.github/scripts/verify-artifacts.py @@ -0,0 +1,571 @@ +#!/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; name, description, url, license, developer and scm values exactly + the project_* values of gradle.properties; no DTD, entity, processing instruction, control or + format character, attribute below the root or text next to child elements; the licenses, + developers and scm shapes Gradle writes; only the expected top-level elements; coordinates + com.checkout:checkout-sdk-java:; dependencies exactly the `api` (scope compile), + `implementation` and `runtimeOnly` (scope runtime) dependencies of build.gradle; +- 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*(api|implementation|runtimeOnly)\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") +# How Gradle publishes each configuration: POM scope, and whether the module's apiElements variant +# lists it (runtimeElements lists all three). +PUBLISHED_CONFIGURATIONS = {"api": ("compile", True), "implementation": ("runtime", False), "runtimeOnly": ("runtime", False)} + + +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): + """{(group, name, version): configuration} for the api, implementation and runtimeOnly lines.""" + expected = {} + 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 " + f"api|implementation|runtimeOnly 'group:name:version'") + configuration, key = match.group(1), match.groups()[1:] + if any(known[:2] == key[:2] for known in expected): + fail(f"build.gradle:{number}: {key[0]}:{key[1]} is declared twice") + expected[key] = configuration + if not expected: + fail("build.gradle declares no published dependency") + return expected + + +def pom_dependencies(dependencies): + return {key: PUBLISHED_CONFIGURATIONS[configuration][0] for key, configuration in dependencies.items()} + + +def module_dependencies(dependencies, variant): + if variant == "runtimeElements": + return set(dependencies) + return {key for key, configuration in dependencies.items() if PUBLISHED_CONFIGURATIONS[configuration][1]} + + +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, after checking that the local entries follow each other + from the first byte to the central directory and match the central records.""" + 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("\n'): + fail("the POM does not start with the UTF-8 XML declaration") + body = decoded[len('\n'):] + if not body.isascii() or bad_characters(body): + fail("the POM holds non-ASCII, control or format characters") + if re.search(r" 1: + fail("the POM has two dependencies sections") + if (text(root, "groupId"), text(root, "artifactId"), text(root, "version")) != (GROUP, ARTIFACT, version): + fail("the POM coordinates are not com.checkout:checkout-sdk-java at this version") + check_pom_values(root, properties) + if text(root, "packaging") not in (None, "jar"): + fail("the POM packaging is not jar") + found = {} + container = root.find(POM_NS + "dependencies") + for dependency in ([] if container is None else list(container)): + if dependency.tag != POM_NS + "dependency": + fail(f"unexpected element {dependency.tag!r} in POM dependencies") + children = [local(child.tag) for child in dependency] + if sorted(children) != sorted(POM_DEPENDENCY_CHILDREN) or any(len(child) for child in dependency): + fail(f"POM dependency with elements {sorted(str(c) for c in children)}") + key = (text(dependency, "groupId"), text(dependency, "artifactId"), text(dependency, "version")) + if key in found: + fail(f"duplicate POM dependency {key}") + found[key] = text(dependency, "scope") + expected = pom_dependencies(dependencies) + if found != expected: + differ = sorted(set(found.items()) ^ set(expected.items())) + fail(f"POM dependencies or scopes differ from build.gradle ({differ[:6]})") + + +def sha256(path): + digest = hashlib.sha256() + with open(path, "rb") as handle: + for block in iter(lambda: handle.read(1 << 20), b""): + digest.update(block) + return digest.hexdigest() + + +def no_duplicate_keys(pairs): + keys = [key for key, _ in pairs] + if len(keys) != len(set(keys)): + fail("the module file has duplicate JSON keys") + return dict(pairs) + + +def check_module(path, directory, version, dependencies): + try: + with open(path, encoding="utf-8") as handle: + module = json.load(handle, object_pairs_hook=no_duplicate_keys) + except (ValueError, UnicodeDecodeError): + fail("the module file is not JSON") + if not isinstance(module, dict) or set(module) != {"formatVersion", "component", "createdBy", "variants"}: + fail("unexpected top-level keys in the module file") + if module["formatVersion"] != "1.1": + fail("unexpected module format version") + component = module["component"] + if not isinstance(component, dict) or set(component) != {"group", "module", "version", "attributes"}: + fail("the module component has unexpected keys") + if (component["group"], component["module"], component["version"]) != (GROUP, ARTIFACT, version): + fail("the module coordinates are not com.checkout:checkout-sdk-java at this version") + if not strictly_equal(component["attributes"], COMPONENT_ATTRIBUTES): + fail("unexpected module component attributes") + variants = module["variants"] + if not isinstance(variants, list) or not all(isinstance(v, dict) for v in variants) \ + or sorted(str(v.get("name")) for v in variants) != sorted(VARIANT_ATTRIBUTES): + fail(f"the module variants must be exactly {sorted(VARIANT_ATTRIBUTES)}") + wanted = f"{ARTIFACT}-{version}.jar" + real = os.path.join(directory, wanted) + for variant in variants: + name = variant["name"] + extra = set(variant) - {"name", "attributes", "files", "dependencies"} + if extra or "files" not in variant or "attributes" not in variant: + fail(f"module variant {name} has unexpected or missing keys") + if not strictly_equal(variant["attributes"], VARIANT_ATTRIBUTES[name]): + fail(f"module variant {name} has unexpected attributes") + files = variant["files"] + if not isinstance(files, list) or len(files) != 1 or not isinstance(files[0], dict): + fail(f"module variant {name} must list exactly one file") + entry = files[0] + if set(entry) != {"name", "url", "size", "sha512", "sha256", "sha1", "md5"}: + fail(f"module variant {name} file entry has unexpected keys") + if entry["name"] != wanted or entry["url"] != wanted: + fail(f"module variant {name} does not point at {wanted}") + if type(entry["size"]) is not int or entry["size"] != os.path.getsize(real) or entry["sha256"] != sha256(real): + fail(f"module variant {name} does not match {wanted} (size or sha256)") + found = set() + listed = variant.get("dependencies", []) + if not isinstance(listed, list): + fail(f"module variant {name} dependencies are not a list") + for dependency in listed: + if not isinstance(dependency, dict) or set(dependency) != {"group", "module", "version"} \ + or not isinstance(dependency["version"], dict) or set(dependency["version"]) != {"requires"} \ + or not all(isinstance(value, str) for value in + (dependency["group"], dependency["module"], dependency["version"]["requires"])): + fail(f"module variant {name} has a dependency of an unexpected shape") + key = (dependency["group"], dependency["module"], dependency["version"]["requires"]) + if key in found: + fail(f"duplicate module dependency {key}") + found.add(key) + expected = module_dependencies(dependencies, name) + if found != expected: + fail(f"module variant {name} dependencies differ from build.gradle (extra {sorted(found - expected)}, missing {sorted(expected - found)})") + + +def main(argv): + parser = argparse.ArgumentParser() + parser.add_argument("--version", required=True) + parser.add_argument("--directory", required=True) + parser.add_argument("--repo", default=".") + args = parser.parse_args(argv) + if not re.fullmatch(r"[0-9A-Za-z.-]+", args.version) or ".." in args.version: + fail("invalid version") + files = expected_files(args.version) + check_file_set(args.directory, files) + dependencies = read_dependencies(os.path.join(args.repo, "build.gradle")) + sources = tracked_sources(args.repo) + path = {kind: os.path.join(args.directory, name) for kind, name in files.items()} + check_jar(path["jar"], args.version, sources) + check_sources(path["sources"], args.repo, sources) + check_javadoc(path["javadoc"]) + check_pom(path["pom"], args.version, dependencies, read_properties(os.path.join(args.repo, "gradle.properties"))) + check_module(path["module"], args.directory, args.version, dependencies) + print(f"Artifacts of {ARTIFACT} {args.version} verified ({len(dependencies)} dependencies)") + + +if __name__ == "__main__": + try: + main(sys.argv[1:]) + except VerificationError as error: + print(f"::error::{error}") + sys.exit(1) + except Exception as error: # any malformed input not caught above still fails closed + print(f"::error::unexpected artifact structure ({type(error).__name__})") + sys.exit(1) diff --git a/.github/workflows/build-master.yml b/.github/workflows/build-master.yml index bd98031ca..54cfb18af 100644 --- a/.github/workflows/build-master.yml +++ b/.github/workflows/build-master.yml @@ -3,18 +3,25 @@ on: push: branches: - master + +permissions: + contents: read + jobs: job-container: if: "!contains(github.event.commits[0].message, 'Release')" runs-on: ubuntu-latest + timeout-minutes: 60 steps: - - uses: actions/checkout@v7 - - uses: actions/setup-java@v5 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: actions/setup-java@d1374f8ac74474200d16ef8ecee22c7ae7a51880 # v6.3.0 with: distribution: 'temurin' java-version: '11' - id: validate-wrapper - uses: gradle/wrapper-validation-action@v3 + uses: gradle/actions/wrapper-validation@0723195856401067f7a2779048b490ace7a47d7c # v5.0.2 - id: build env: CHECKOUT_PROCESSING_CHANNEL_ID: ${{ secrets.IT_CHECKOUT_PROCESSING_CHANNEL_ID }} @@ -31,4 +38,4 @@ jobs: CHECKOUT_DEFAULT_OAUTH_ISSUING_CLIENT_ID: ${{ secrets.IT_CHECKOUT_DEFAULT_OAUTH_ISSUING_CLIENT_ID }} CHECKOUT_DEFAULT_OAUTH_ISSUING_CLIENT_SECRET: ${{ secrets.IT_CHECKOUT_DEFAULT_OAUTH_ISSUING_CLIENT_SECRET }} CHECKOUT_MERCHANT_SUBDOMAIN: ${{ secrets.IT_CHECKOUT_MERCHANT_SUBDOMAIN }} - run: ./gradlew build test --fail-fast + run: bash .github/scripts/gradle.sh build test --fail-fast diff --git a/.github/workflows/build-pull-request.yml b/.github/workflows/build-pull-request.yml index 0f03cb957..385d4539c 100644 --- a/.github/workflows/build-pull-request.yml +++ b/.github/workflows/build-pull-request.yml @@ -5,23 +5,30 @@ on: - master - 'integration/**' - 'feature/**' + +permissions: + contents: read + jobs: job-container: runs-on: ubuntu-latest + timeout-minutes: 60 steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false - id: setup-java-11-build - uses: actions/setup-java@v5 + uses: actions/setup-java@d1374f8ac74474200d16ef8ecee22c7ae7a51880 # v6.3.0 with: distribution: 'temurin' java-version: '11' - id: validate-wrapper - uses: gradle/wrapper-validation-action@v3 + uses: gradle/actions/wrapper-validation@0723195856401067f7a2779048b490ace7a47d7c # v5.0.2 - id: cache-gradle-packages - uses: actions/cache@v6 + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: path: ~/.gradle/caches - key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle') }} + key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle', 'gradle/verification-metadata.xml', 'gradle/wrapper/gradle-wrapper.properties') }} restore-keys: ${{ runner.os }}-gradle - id: build env: @@ -39,6 +46,4 @@ jobs: CHECKOUT_DEFAULT_OAUTH_ISSUING_CLIENT_ID: ${{ secrets.IT_CHECKOUT_DEFAULT_OAUTH_ISSUING_CLIENT_ID }} CHECKOUT_DEFAULT_OAUTH_ISSUING_CLIENT_SECRET: ${{ secrets.IT_CHECKOUT_DEFAULT_OAUTH_ISSUING_CLIENT_SECRET }} CHECKOUT_MERCHANT_SUBDOMAIN: ${{ secrets.IT_CHECKOUT_MERCHANT_SUBDOMAIN }} - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} - run: ./gradlew build + run: bash .github/scripts/gradle.sh build diff --git a/.github/workflows/build-release.yml b/.github/workflows/build-release.yml index b64bd3db3..c7225028c 100644 --- a/.github/workflows/build-release.yml +++ b/.github/workflows/build-release.yml @@ -1,26 +1,222 @@ name: build-release + +# Runs on a push to master that changes gradle.properties. Only a release commit publishes: its +# first line is "Release " or starts with "Release " (the /release PR title), +# where is the one gradle.properties declares. A first line that starts with "Release" +# but names another version fails the run. Any other push builds and tests only. A version +# already on Maven Central is not uploaded again. To finish a release that failed part way (the +# upload or the GitHub release), re-run that same run: a later push is not the release commit of +# that version, so it does not publish or create the release. +# +# build no secrets; Gradle with verified dependencies (through gradle.sh); +# stages the five release files; artifact +# verify no secrets, no Gradle, a fresh runner: verify-artifacts.py and the artifact's sha256 +# test integration secrets only; gradle.sh test check +# publish environment "maven-central", the signing key and the Central token, actions: read; +# no checkout, no Gradle, no repository code; signs and uploads the artifact only after +# its sha256 matches the verify job's, once per run (a re-run after an upload waits for +# the version on Maven Central instead) +# release contents: write; gh release create on: push: branches: - master paths: - gradle.properties + +permissions: + contents: read + +# One run at a time. GitHub keeps one pending run per group: a newer push cancels a pending one. +# A cancelled release run publishes nothing, even when the newer push carries its version, since +# that push is not the release commit; the build job then warns that the version is not on Maven +# Central. Re-run the cancelled run (re-runs use its original commit). +concurrency: + group: build-release + cancel-in-progress: false + jobs: - deploy: + build: + if: github.ref == 'refs/heads/master' runs-on: ubuntu-latest + timeout-minutes: 30 + outputs: + version: ${{ steps.version.outputs.version }} + prerelease: ${{ steps.version.outputs.prerelease }} + release_commit: ${{ steps.version.outputs.release_commit }} + central_state: ${{ steps.published.outputs.central_state }} + release_exists: ${{ steps.release-exists.outputs.release_exists }} steps: - - uses: actions/checkout@v7 - - uses: actions/setup-java@v5 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: actions/setup-java@d1374f8ac74474200d16ef8ecee22c7ae7a51880 # v6.3.0 with: distribution: 'temurin' java-version: '11' - - id: read-version - run: echo "CURRENT_VERSION=$( grep "version" gradle.properties | awk -F "=" '{print $2}' )" >> $GITHUB_ENV - - id: print-version - run: echo "Releasing $CURRENT_VERSION" - id: validate-wrapper - uses: gradle/wrapper-validation-action@v3 - - id: build + uses: gradle/actions/wrapper-validation@0723195856401067f7a2779048b490ace7a47d7c # v5.0.2 + - id: version + name: Read and validate the version + env: + HEAD_MESSAGE: ${{ github.event.head_commit.message }} + run: | + set -euo pipefail + # gradle.properties must declare the version literally, once, on its own line. + lines="$(grep -c '^version=' gradle.properties || true)" + if [ "$lines" != 1 ]; then + echo "::error::gradle.properties must declare version= exactly once" + exit 1 + fi + version="$(sed -n 's/^version=//p' gradle.properties)" + semver='^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(-[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?$' + if ! [[ "$version" =~ $semver ]]; then + echo "::error::Version in gradle.properties is not MAJOR.MINOR.PATCH[-PRERELEASE]" + exit 1 + fi + prerelease=false + case "$version" in *-*) prerelease=true ;; esac + # Only the release commit of this version publishes (see the top of this file). + message="${HEAD_MESSAGE:-}" + subject="${message%%$'\n'*}" + release_commit=false + case "$subject" in + "Release $version" | "Release $version "*) release_commit=true ;; + [Rr][Ee][Ll][Ee][Aa][Ss][Ee] | [Rr][Ee][Ll][Ee][Aa][Ss][Ee][[:space:]]*) + echo "::error::The commit looks like a release but is not \"Release $version\" (the version in gradle.properties)" + exit 1 + ;; + esac + { + echo "version=$version" + echo "prerelease=$prerelease" + echo "release_commit=$release_commit" + } >> "$GITHUB_OUTPUT" + echo "Version $version (pre-release: $prerelease, release commit: $release_commit)" + if [ "$release_commit" = false ]; then + echo "::notice::Not a release commit for $version: build and test only, nothing is published" + fi + - id: publishing-secrets + name: Check the publishing secrets live only in the maven-central environment + # This job has no environment. The expression yields only true or false. + env: + VISIBLE: ${{ secrets.GPG_KEY != '' || secrets.GPG_PASSPHRASE != '' || secrets.SONATYPE_USERNAME != '' || secrets.SONATYPE_PASSWORD != '' }} + RELEASE_COMMIT: ${{ steps.version.outputs.release_commit }} + run: | + set -euo pipefail + if [ "$VISIBLE" != false ]; then + message="GPG_KEY, GPG_PASSPHRASE, SONATYPE_USERNAME and SONATYPE_PASSWORD must be secrets of the maven-central environment only, not repository or organisation secrets" + if [ "$RELEASE_COMMIT" = true ]; then + echo "::error::$message" + exit 1 + fi + echo "::warning::$message" + fi + - id: published + name: Check Maven Central for this version + env: + VERSION: ${{ steps.version.outputs.version }} + RELEASE_COMMIT: ${{ steps.version.outputs.release_commit }} + run: | + set -euo pipefail + url="https://repo1.maven.org/maven2/com/checkout/checkout-sdk-java/$VERSION/checkout-sdk-java-$VERSION.pom" + code="$(curl -sS --retry 3 -o /dev/null -w '%{http_code}' "$url")" || code=000 + case "$code" in + 200) state=published; echo "::notice::$VERSION is already on Maven Central; nothing to upload" ;; + 404) state=missing ;; + *) echo "::error::Maven Central lookup for $VERSION failed (HTTP $code)"; exit 1 ;; + esac + if [ "${RELEASE_COMMIT:-}" = true ] && [ "$state" = published ] && [ "${GITHUB_RUN_ATTEMPT:-1}" = 1 ]; then + echo "::warning::$VERSION was already on Maven Central before this release commit: nothing is uploaded and no release is created" + fi + if [ "${RELEASE_COMMIT:-}" != true ] && [ "$state" != published ]; then + echo "::warning::$VERSION is not on Maven Central and this push is not its release commit: if its release run was cancelled or failed, re-run that run" + fi + echo "central_state=$state" >> "$GITHUB_OUTPUT" + - id: release-exists + name: Check for the GitHub release of this version + env: + GH_TOKEN: ${{ github.token }} + VERSION: ${{ steps.version.outputs.version }} + run: | + set -euo pipefail + code="$(curl -sS --retry 3 -o /dev/null -w '%{http_code}' \ + -H "Authorization: Bearer $GH_TOKEN" -H "Accept: application/vnd.github+json" \ + "$GITHUB_API_URL/repos/$GITHUB_REPOSITORY/releases/tags/$VERSION")" || code=000 + case "$code" in + 200) exists=true ;; + 404) exists=false ;; + *) echo "::error::GitHub release lookup for $VERSION failed (HTTP $code)"; exit 1 ;; + esac + echo "release_exists=$exists" >> "$GITHUB_OUTPUT" + - id: stage + name: Build and stage the release files + # Every dependency and plugin is checked against gradle/verification-metadata.xml. + run: bash .github/scripts/gradle.sh --no-daemon --no-build-cache publishMavenPublicationToStagingRepository + - id: collect + name: Collect the five release files + env: + VERSION: ${{ steps.version.outputs.version }} + run: | + set -euo pipefail + staged="build/staging-deploy/com/checkout/checkout-sdk-java/$VERSION" + out="$RUNNER_TEMP/maven-artifacts" + mkdir "$out" + for suffix in .jar -sources.jar -javadoc.jar .pom .module; do + cp "$staged/checkout-sdk-java-$VERSION$suffix" "$out/" + done + - id: upload + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: maven-artifacts + path: ${{ runner.temp }}/maven-artifacts/ + if-no-files-found: error + retention-days: 7 + + verify: + # A separate runner, with no secret and no Gradle. + needs: build + runs-on: ubuntu-latest + timeout-minutes: 10 + outputs: + artifacts_sha256: ${{ steps.hashes.outputs.artifacts_sha256 }} + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - id: download + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + name: maven-artifacts + path: ${{ runner.temp }}/maven-artifacts + - id: hashes + name: Verify the release files and record their sha256 + env: + VERSION: ${{ needs.build.outputs.version }} + run: | + set -euo pipefail + out="$RUNNER_TEMP/maven-artifacts" + python3 -I .github/scripts/verify-artifacts.py --version "$VERSION" --directory "$out" --repo . + cd "$out" + sums="$(LC_ALL=C find . -mindepth 1 -printf '%P\n' | LC_ALL=C sort | xargs -d '\n' sha256sum)" + echo "$sums" + echo "artifacts_sha256=$(sha256sum <<< "$sums" | cut -d' ' -f1)" >> "$GITHUB_OUTPUT" + + test: + needs: build + runs-on: ubuntu-latest + timeout-minutes: 60 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: actions/setup-java@d1374f8ac74474200d16ef8ecee22c7ae7a51880 # v6.3.0 + with: + distribution: 'temurin' + java-version: '11' + - id: validate-wrapper + uses: gradle/actions/wrapper-validation@0723195856401067f7a2779048b490ace7a47d7c # v5.0.2 + - id: test env: CHECKOUT_PROCESSING_CHANNEL_ID: ${{ secrets.IT_CHECKOUT_PROCESSING_CHANNEL_ID }} CHECKOUT_PREVIOUS_SECRET_KEY: ${{ secrets.IT_CHECKOUT_PREVIOUS_SECRET_KEY }} @@ -36,21 +232,287 @@ jobs: CHECKOUT_DEFAULT_OAUTH_ISSUING_CLIENT_ID: ${{ secrets.IT_CHECKOUT_DEFAULT_OAUTH_ISSUING_CLIENT_ID }} CHECKOUT_DEFAULT_OAUTH_ISSUING_CLIENT_SECRET: ${{ secrets.IT_CHECKOUT_DEFAULT_OAUTH_ISSUING_CLIENT_SECRET }} CHECKOUT_MERCHANT_SUBDOMAIN: ${{ secrets.IT_CHECKOUT_MERCHANT_SUBDOMAIN }} - run: ./gradlew build test --fail-fast jar - - id: publish - env: - GPG_KEY: '${{ secrets.GPG_KEY }}' - GPG_PASSPHRASE: '${{ secrets.GPG_PASSPHRASE }}' - SONATYPE_PASSWORD: '${{ secrets.SONATYPE_PASSWORD }}' - SONATYPE_USERNAME: '${{ secrets.SONATYPE_USERNAME }}' - run: ./gradlew publishToSonatype closeAndReleaseSonatypeStagingRepository --no-daemon --stacktrace - - id: create-release - uses: actions/create-release@v1 - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - with: - tag_name: ${{ env.CURRENT_VERSION }} - release_name: ${{ env.CURRENT_VERSION }} - body: ${{ github.event.head_commit.message }} - draft: false - prerelease: false + run: bash .github/scripts/gradle.sh --no-daemon test --fail-fast check + + publish: + needs: [build, verify, test] + if: needs.build.outputs.release_commit == 'true' && needs.build.outputs.central_state == 'missing' + runs-on: ubuntu-latest + timeout-minutes: 75 + environment: maven-central + permissions: + actions: read # the jobs of earlier attempts of this run (step "published") + steps: + # done: the version is on Maven Central already (nothing to upload); wait: an earlier attempt + # of this run uploaded it (wait until it is on Maven Central, no second upload); upload. + - id: published + name: Check whether this version is already uploaded + env: + GH_TOKEN: ${{ github.token }} + VERSION: ${{ needs.build.outputs.version }} + run: | + set -euo pipefail + if ! [[ "$VERSION" =~ ^[0-9A-Za-z.-]+$ ]]; then + echo "::error::Invalid version from the build job" + exit 1 + fi + url="https://repo1.maven.org/maven2/com/checkout/checkout-sdk-java/$VERSION/checkout-sdk-java-$VERSION.pom" + code="$(curl -sS --retry 3 -o /dev/null -w '%{http_code}' "$url")" || code=000 + case "$code" in + 200) echo "::notice::$VERSION is on Maven Central; nothing to upload"; echo "mode=done" >> "$GITHUB_OUTPUT"; exit 0 ;; + 404) ;; + *) echo "::error::Maven Central lookup for $VERSION failed (HTTP $code)"; exit 1 ;; + esac + mode="upload" + attempt=1 + while [ "$attempt" -lt "${GITHUB_RUN_ATTEMPT:-1}" ]; do + jobs="$(gh api --paginate "repos/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID/attempts/$attempt/jobs?per_page=100" \ + --jq '.jobs[] | select(.name == "publish") | .steps[] | select(.name == "Upload to Maven Central") | .conclusion')" + if grep -qx success <<< "$jobs"; then + mode="wait" + echo "::notice::Attempt $attempt of this run uploaded $VERSION; waiting for it on Maven Central instead of uploading again" + fi + attempt=$((attempt + 1)) + done + echo "mode=$mode" >> "$GITHUB_OUTPUT" + - id: download + if: steps.published.outputs.mode == 'upload' + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + name: maven-artifacts + path: ${{ runner.temp }}/maven-artifacts + - id: verify + if: steps.published.outputs.mode == 'upload' + name: Verify the artifact is the one the verify job checked + env: + VERSION: ${{ needs.build.outputs.version }} + ARTIFACTS_SHA256: ${{ needs.verify.outputs.artifacts_sha256 }} + run: | + set -euo pipefail + dir="$RUNNER_TEMP/maven-artifacts" + if [ ! -d "$dir" ] || [ -L "$dir" ]; then + echo "::error::The maven-artifacts artifact is missing" + exit 1 + fi + # The build job validated the version; this only keeps it a plain token in file names. + if ! [[ "$VERSION" =~ ^[0-9A-Za-z.-]+$ ]]; then + echo "::error::Invalid version from the build job" + exit 1 + fi + if ! [[ "$ARTIFACTS_SHA256" =~ ^[0-9a-f]{64}$ ]]; then + echo "::error::Missing or invalid sha256 from the verify job" + exit 1 + fi + cd "$dir" + expected="$(for suffix in .jar -sources.jar -javadoc.jar .pom .module; do + echo "checkout-sdk-java-$VERSION$suffix"; done | LC_ALL=C sort)" + actual="$(LC_ALL=C find . -mindepth 1 -printf '%P\n' | LC_ALL=C sort)" + if [ "$actual" != "$expected" ]; then + echo "::error::The artifact must hold exactly the five release files of $VERSION" + exit 1 + fi + while IFS= read -r file; do + if [ ! -f "$file" ] || [ -L "$file" ]; then + echo "::error::$file is not a regular file" + exit 1 + fi + done <<< "$expected" + sums="$(xargs -d '\n' sha256sum <<< "$expected")" + if [ "$(sha256sum <<< "$sums" | cut -d' ' -f1)" != "$ARTIFACTS_SHA256" ]; then + echo "::error::The artifact does not match the sha256 the verify job recorded" + exit 1 + fi + echo "$sums" + - id: sign + if: steps.published.outputs.mode == 'upload' + name: Sign and bundle + env: + VERSION: ${{ needs.build.outputs.version }} + GPG_KEY: ${{ secrets.GPG_KEY }} + GPG_PASSPHRASE: ${{ secrets.GPG_PASSPHRASE }} + run: | + set -euo pipefail + if [ -z "${GPG_KEY:-}" ] || [ -z "${GPG_PASSPHRASE:-}" ]; then + echo "::error::GPG_KEY or GPG_PASSPHRASE is empty (expected as secrets of the maven-central environment)" + exit 1 + fi + # Throwaway keyring. On every exit, success or failure, no agent keeps the unlocked key + # and the keyring is removed. + GNUPGHOME="$(mktemp -d)" + export GNUPGHOME + trap 'gpgconf --kill gpg-agent || true; rm -rf "$GNUPGHOME"' EXIT + chmod 700 "$GNUPGHOME" + if ! gpg --batch --quiet --import <<< "$GPG_KEY"; then + echo "::error::GPG_KEY is not a GPG secret key" + exit 1 + fi + keys="$(gpg --batch --list-secret-keys --with-colons | grep -c '^sec:' || true)" + if [ "$keys" != 1 ]; then + echo "::error::GPG_KEY must hold exactly one secret key" + exit 1 + fi + bundle_root="$(mktemp -d)" + target="$bundle_root/com/checkout/checkout-sdk-java/$VERSION" + mkdir -p "$target" + cp "$RUNNER_TEMP/maven-artifacts/"* "$target/" + cd "$target" + for file in *; do + if ! gpg --batch --yes --quiet --pinentry-mode loopback --passphrase-fd 0 \ + --armor --detach-sign --output "$file.asc" "$file" <<< "$GPG_PASSPHRASE"; then + echo "::error::Signing failed (check GPG_KEY and GPG_PASSPHRASE)" + exit 1 + fi + gpg --batch --quiet --verify "$file.asc" "$file" + md5sum "$file" | cut -d' ' -f1 > "$file.md5" + sha1sum "$file" | cut -d' ' -f1 > "$file.sha1" + sha256sum "$file" | cut -d' ' -f1 > "$file.sha256" + sha512sum "$file" | cut -d' ' -f1 > "$file.sha512" + done + cd "$bundle_root" + zip -q -r -X "$RUNNER_TEMP/central-bundle.zip" com + unzip -Z1 "$RUNNER_TEMP/central-bundle.zip" + - id: upload + if: steps.published.outputs.mode == 'upload' + name: Upload to Maven Central + env: + VERSION: ${{ needs.build.outputs.version }} + SONATYPE_USERNAME: ${{ secrets.SONATYPE_USERNAME }} + SONATYPE_PASSWORD: ${{ secrets.SONATYPE_PASSWORD }} + run: | + set -euo pipefail + if [ -z "${SONATYPE_USERNAME:-}" ] || [ -z "${SONATYPE_PASSWORD:-}" ]; then + echo "::error::SONATYPE_USERNAME or SONATYPE_PASSWORD is empty (expected as secrets of the maven-central environment)" + exit 1 + fi + token="$(printf '%s:%s' "$SONATYPE_USERNAME" "$SONATYPE_PASSWORD" | base64 -w0)" + echo "::add-mask::$token" + # The header goes to curl on stdin (printf is a shell builtin), never on a command line. + auth() { printf 'Authorization: Bearer %s\n' "$token"; } + response="$RUNNER_TEMP/central-response" + # One request per attempt; a failed upload is retried by re-running the run. + code="$(auth | curl -sS -o "$response" -w '%{http_code}' -H @- \ + -F "bundle=@$RUNNER_TEMP/central-bundle.zip;type=application/octet-stream" \ + "https://central.sonatype.com/api/v1/publisher/upload?name=checkout-sdk-java-$VERSION&publishingType=AUTOMATIC")" || code=000 + if [ "$code" != 201 ]; then + echo "::error::Maven Central upload failed (HTTP $code)" + exit 1 + fi + # The body is the bare deployment id; only a trailing line break is dropped. + deployment="$(tr -d '\r\n' < "$response")" + if ! [[ "$deployment" =~ ^[0-9A-Za-z-]{1,64}$ ]]; then + echo "::error::Maven Central returned an unexpected deployment id" + exit 1 + fi + echo "Deployment $deployment" + echo "deployment=$deployment" >> "$GITHUB_OUTPUT" + - id: status + if: steps.published.outputs.mode == 'upload' + name: Wait for the deployment to publish + env: + DEPLOYMENT: ${{ steps.upload.outputs.deployment }} + SONATYPE_USERNAME: ${{ secrets.SONATYPE_USERNAME }} + SONATYPE_PASSWORD: ${{ secrets.SONATYPE_PASSWORD }} + run: | + set -euo pipefail + if ! [[ "$DEPLOYMENT" =~ ^[0-9A-Za-z-]{1,64}$ ]]; then + echo "::error::Missing deployment id from the upload step" + exit 1 + fi + token="$(printf '%s:%s' "$SONATYPE_USERNAME" "$SONATYPE_PASSWORD" | base64 -w0)" + echo "::add-mask::$token" + auth() { printf 'Authorization: Bearer %s\n' "$token"; } + response="$RUNNER_TEMP/central-status" + # AUTOMATIC: validation, then publication. PUBLISHING means validation passed and the files + # are on their way to the repository. Lookup errors and states other than FAILED are + # retried until the deadline (30 minutes). + for _ in $(seq 1 120); do + code="$(auth | curl -sS -o "$response" -w '%{http_code}' -H @- -X POST \ + "https://central.sonatype.com/api/v1/publisher/status?id=$DEPLOYMENT")" || code=000 + state="" + if [ "$code" = 200 ]; then + state="$(jq -r '.deploymentState // empty' "$response" 2> /dev/null || true)" + fi + case "$state" in + PUBLISHING | PUBLISHED) echo "Deployment $DEPLOYMENT: $state"; exit 0 ;; + FAILED) + echo "::error::Maven Central refused the deployment" + jq -c '.errors // empty' "$response" 2> /dev/null || true + exit 1 + ;; + PENDING | VALIDATING | VALIDATED) ;; + "") echo "::warning::Maven Central status lookup failed (HTTP $code); retrying" ;; + *) echo "::warning::Unexpected Maven Central deployment state; retrying" ;; + esac + sleep 15 + done + echo "::error::Deployment $DEPLOYMENT was not published in time; check it in the Central Portal, then re-run this run" + exit 1 + - id: wait-central + if: steps.published.outputs.mode == 'wait' + name: Wait for the earlier upload on Maven Central + env: + VERSION: ${{ needs.build.outputs.version }} + run: | + set -euo pipefail + url="https://repo1.maven.org/maven2/com/checkout/checkout-sdk-java/$VERSION/checkout-sdk-java-$VERSION.pom" + for _ in $(seq 1 80); do + code="$(curl -sS -o /dev/null -w '%{http_code}' "$url")" || code=000 + if [ "$code" = 200 ]; then + echo "$VERSION is on Maven Central" + exit 0 + fi + sleep 30 + done + echo "::error::$VERSION is not on Maven Central after 40 minutes; check deployment checkout-sdk-java-$VERSION in the Central Portal, then re-run this run" + exit 1 + + release: + # Runs after this run's upload, or, when publish was skipped because the version is on Maven + # Central, only on a re-run of the run (its upload succeeded, its GitHub release failed). A + # later "Release " commit for a published version does nothing. + needs: [build, verify, test, publish] + if: >- + always() && + needs.build.result == 'success' && needs.verify.result == 'success' && + needs.test.result == 'success' && + (needs.publish.result == 'success' || + (needs.publish.result == 'skipped' && github.run_attempt > 1)) && + needs.build.outputs.release_commit == 'true' && + needs.build.outputs.release_exists == 'false' + runs-on: ubuntu-latest + timeout-minutes: 10 + permissions: + contents: write + steps: + - id: release-tag + env: + GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} + VERSION: ${{ needs.build.outputs.version }} + PRERELEASE: ${{ needs.build.outputs.prerelease }} + NOTES: ${{ github.event.head_commit.message }} + run: | + set -euo pipefail + # The build job validated the version; this only keeps it a plain token. + if ! [[ "$VERSION" =~ ^[0-9A-Za-z.-]+$ ]]; then + echo "::error::Invalid version from the build job" + exit 1 + fi + # gh reuses an existing tag and ignores --target, so a tag on another commit is refused. + refs="$(gh api "repos/$GH_REPO/git/matching-refs/tags/$VERSION")" + ref="$(jq -c --arg r "refs/tags/$VERSION" 'map(select(.ref == $r)) | first // empty' <<< "$refs")" + if [ -n "$ref" ]; then + sha="$(jq -r '.object.sha' <<< "$ref")" + if [ "$(jq -r '.object.type' <<< "$ref")" = tag ]; then + sha="$(gh api "repos/$GH_REPO/git/tags/$sha" --jq '.object.sha')" + fi + if [ "$sha" != "$GITHUB_SHA" ]; then + echo "::error::Tag $VERSION already exists on another commit" + exit 1 + fi + fi + args=(--target "$GITHUB_SHA") + if [ "$PRERELEASE" = true ]; then + args+=(--prerelease) + fi + gh release create "$VERSION" "${args[@]}" --title "$VERSION" --notes "${NOTES:-$VERSION}" diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml index 746d5dca1..d8068b744 100644 --- a/.github/workflows/codeql-analysis.yml +++ b/.github/workflows/codeql-analysis.yml @@ -20,12 +20,15 @@ on: schedule: - cron: '34 2 * * 0' +permissions: + contents: read + jobs: analyze: name: Analyze runs-on: ubuntu-latest + timeout-minutes: 60 permissions: - actions: read contents: read security-events: write @@ -38,25 +41,31 @@ jobs: steps: - name: Checkout repository - uses: actions/checkout@v7 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: - submodules: recursive + persist-credentials: false - name: Set up JDK 11 - uses: actions/setup-java@v5 + uses: actions/setup-java@d1374f8ac74474200d16ef8ecee22c7ae7a51880 # v6.3.0 with: java-version: '11' distribution: 'temurin' + - name: Validate the Gradle wrapper + uses: gradle/actions/wrapper-validation@0723195856401067f7a2779048b490ace7a47d7c # v5.0.2 + # Initializes the CodeQL tools for scanning. - name: Initialize CodeQL - uses: github/codeql-action/init@v4 + uses: github/codeql-action/init@1bd86f2fdb4b86187fa4059f16f31a3202acc9ea # v4.39.4 with: languages: ${{ matrix.language }} queries: security-and-quality config-file: .github/codeql/codeql-config.yml - - name: Autobuild - uses: github/codeql-action/autobuild@v4 + build-mode: manual + # Explicit build instead of autobuild: the same Gradle wrapper and verified dependencies as + # the other workflows, and nothing else is run. + - name: Build + run: bash .github/scripts/gradle.sh --no-daemon --no-build-cache testClasses - name: Perform CodeQL Analysis - uses: github/codeql-action/analyze@v4 + uses: github/codeql-action/analyze@1bd86f2fdb4b86187fa4059f16f31a3202acc9ea # v4.39.4 diff --git a/build.gradle b/build.gradle index 7a4e8faab..ea982d3dd 100644 --- a/build.gradle +++ b/build.gradle @@ -1,8 +1,6 @@ plugins { id 'java-library' - id 'signing' id 'maven-publish' - id 'io.github.gradle-nexus.publish-plugin' version '2.0.0' id 'io.freefair.lombok' version '8.14.4' id "org.sonarqube" version "7.5.0.8588" id 'jacoco' @@ -10,7 +8,6 @@ plugins { allprojects { repositories { - mavenLocal() mavenCentral() } } @@ -121,27 +118,14 @@ publishing { } } } -} - -nexusPublishing { + // CI stages the release here (build-release.yml, build job); the publish job of that workflow + // signs the files and uploads them to Maven Central. repositories { - sonatype { - nexusUrl.set(uri("https://ossrh-staging-api.central.sonatype.com/service/local/")) - snapshotRepositoryUrl.set(uri("https://central.sonatype.com/repository/maven-snapshots/")) - username = System.getenv("SONATYPE_USERNAME") - password = System.getenv("SONATYPE_PASSWORD") + maven { + name = 'staging' + url = layout.buildDirectory.dir('staging-deploy') } } - connectTimeout = Duration.ofMinutes(3) - clientTimeout = Duration.ofMinutes(3) -} - -signing { - def signingKey = System.getenv('GPG_KEY') - def signingPassword = System.getenv('GPG_PASSPHRASE') - required { signingKey != null && signingPassword != null && gradle.taskGraph.hasTask("publish") } - useInMemoryPgpKeys(signingKey, signingPassword) - sign publishing.publications.maven } jar { diff --git a/gradle/verification-metadata.xml b/gradle/verification-metadata.xml new file mode 100644 index 000000000..4cff12461 --- /dev/null +++ b/gradle/verification-metadata.xml @@ -0,0 +1,693 @@ + + + + true + false + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index fa5db097c..347a359ff 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,5 +1,6 @@ #Fri Aug 02 15:19:01 BST 2019 distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-all.zip +distributionSha256Sum=ed1a8d686605fd7c23bdf62c7fc7add1c5b23b2bbc3721e661934ef4a4911d7c distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStorePath=wrapper/dists