Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
157 changes: 120 additions & 37 deletions .github/workflows/java-sdk-dependabot-verification-metadata.yml
Original file line number Diff line number Diff line change
Expand Up @@ -18,15 +18,29 @@
# When Dependabot bumps a Gradle dependency under java-sdk/, it edits the build
# script but cannot regenerate java-sdk/gradle/verification-metadata.xml (Gradle
# dependency verification, verify-metadata=true). The new artifacts then have no
# trusted checksum and `./gradlew build` fails in java-sdk-release-verify.yml.
# trusted checksum, so `./gradlew build` fails in java-sdk-release-verify.yml and
# the prek hook fails Static checks.
#
# This is a MANUAL job: a committer runs it from the Actions tab (or `gh workflow
# run`) with the PR number. It checks that PR out, regenerates the metadata with
# the same script as the `regenerate-java-sdk-verification-metadata` prek hook
# (so stale entries are dropped and Static checks agree with the result), and
# pushes the refreshed file back onto the PR branch. Being workflow_dispatch, it
# runs with the committer's own trigger and the normal repo GITHUB_TOKEN -- no
# standing Dependabot secret or pull_request_target write token required.
# This is manual on purpose: the metadata is checksum-only (no PGP verification), so
# a new entry records whatever the repository served at that moment and only a human
# checking the new coordinates and hashes makes it trustworthy. A committer dispatches
# it from the Actions tab (or `gh workflow run`) with a PR number, as that deliberate
# step. It runs the same script as the `regenerate-java-sdk-verification-metadata`
# prek hook, so the file matches what Static checks expects, and pushes the result to
# the PR branch as a follow-up commit.
#
# The work is split so no job holds both a write token and dependency code:
# `regenerate` runs Gradle (dependency code, verification off) with a read-only
# token and hands only the file onward. `publish` has the write token and
# validates that file, using the script and baseline from the dispatched ref (same
# header as there, only generated checksum entries, no changed hash for a coordinate
# that is kept) before committing it. If validation fails,
# a human regenerates the file with the prek hook and reviews why.
#
# The bot's push uses GITHUB_TOKEN, so CI for that commit waits for approval. That
# is a side effect of GITHUB_TOKEN, not a review of the entries, and green CI
# verifies against this same file, so it says nothing about checksum
# authenticity. Review the new entries on the PR.
---
name: Java SDK refresh verification metadata

Expand All @@ -42,71 +56,140 @@ permissions:
contents: read

concurrency:
group: java-sdk-refresh-verification-metadata-${{ github.event.inputs.pr_number }}
group: java-sdk-refresh-verification-metadata-${{ inputs.pr_number }}
cancel-in-progress: true

jobs:
refresh-verification-metadata:
name: Refresh Gradle verification-metadata.xml
resolve:
name: Resolve PR head
runs-on: ubuntu-slim
permissions:
contents: write
contents: read
pull-requests: read
outputs:
head_ref: ${{ steps.pr.outputs.head_ref }}
head_sha: ${{ steps.pr.outputs.head_sha }}
steps:
# Resolve the PR's head branch (and guard that it lives in this repo --
# Dependabot pushes to apache/airflow itself, never a fork).
- name: Resolve PR head branch
# The bot pushes to the PR branch, so it must be in this repository, not a fork.
- name: Resolve PR head
id: pr
env:
GH_TOKEN: ${{ github.token }}
PR_NUMBER: ${{ github.event.inputs.pr_number }}
PR_NUMBER: ${{ inputs.pr_number }}
run: |
set -euo pipefail
repo="${{ github.repository }}"
head_repo=$(gh pr view "$PR_NUMBER" --repo "$repo" --json headRepositoryOwner \
--jq '.headRepositoryOwner.login')
head_ref=$(gh pr view "$PR_NUMBER" --repo "$repo" --json headRefName --jq '.headRefName')
if [ "$head_repo" != "${repo%%/*}" ]; then
echo "PR #$PR_NUMBER head is not in $repo (owner: $head_repo); refusing to push." >&2
# A URL selector would make gh read a PR from another repo, where isCrossRepository means nothing.
[[ "$PR_NUMBER" =~ ^[0-9]+$ ]] || { echo "pr_number must be a number." >&2; exit 1; }
read -r cross_repo head_ref head_sha < <(gh pr view "$PR_NUMBER" --repo "$GITHUB_REPOSITORY" \
--json isCrossRepository,headRefName,headRefOid \
--jq '[.isCrossRepository, .headRefName, .headRefOid] | @tsv')
if [ "$cross_repo" != "false" ]; then
echo "PR #$PR_NUMBER head is not in $GITHUB_REPOSITORY; refusing to push." >&2
exit 1
fi
echo "head_ref=$head_ref" >> "$GITHUB_OUTPUT"
- name: Checkout the PR head branch
echo "head_sha=$head_sha" >> "$GITHUB_OUTPUT"

regenerate:
name: Regenerate verification-metadata.xml
needs: resolve
runs-on: ubuntu-latest
timeout-minutes: 45
# Dependency code runs here, and a dispatch run could otherwise write to the default branch's cache.
cache-mode: none
# Runs dependency code with verification off, so it holds no write token
# and passes only the generated file onward.
permissions:
contents: read
steps:
- name: Checkout the PR head
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
ref: ${{ steps.pr.outputs.head_ref }}
fetch-depth: 0
ref: ${{ needs.resolve.outputs.head_sha }}
fetch-depth: 1
persist-credentials: false
# 11: main build toolchain, 17/21: example toolchains + Gradle runtime.
# The last JDK is the default JAVA_HOME and runs Gradle; 11 matches the default on
# the ubuntu-22.04 image Static checks uses, so the same plugin variants get recorded.
- name: Install JDK toolchains
uses: actions/setup-java@77dd5b2ce225ea11469928ac317850245a74ae78 # v6.2.0
with:
distribution: temurin
java-version: |
11
17
21
# Same script as the `regenerate-java-sdk-verification-metadata` prek hook: it
# rewrites the file from an empty component list and resolves every task the
# hook does. Plain `--write-verification-metadata` only appends, leaving the
# superseded versions behind, and the hook then fails Static checks on them.
11
- name: Regenerate verification-metadata.xml
run: python3 scripts/ci/prek/regenerate_java_sdk_verification_metadata.py
- name: Upload the regenerated file
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: java-sdk-verification-metadata
path: java-sdk/gradle/verification-metadata.xml
retention-days: 1
if-no-files-found: error

publish:
name: Commit verification-metadata.xml
needs: [resolve, regenerate]
runs-on: ubuntu-latest
# Runs no PR code: the validator and its baseline come from the dispatched ref.
# head_ref/head_sha come from `resolve` only.
permissions:
contents: write
steps:
- name: Checkout the PR head
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
ref: ${{ needs.resolve.outputs.head_sha }}
fetch-depth: 1
persist-credentials: false
# The PR head's script could predate `--validate`, which it would ignore and run
# Gradle. The PR head is no baseline either: it includes earlier bot commits,
# so an entry removed by one could return with another hash as if it were new.
- name: Checkout the validator and its baseline
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
ref: ${{ github.sha }}
path: trusted
fetch-depth: 1
persist-credentials: false
- name: Download the regenerated file
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
with:
name: java-sdk-verification-metadata
path: ${{ runner.temp }}/java-sdk-verification-metadata
- name: Validate the regenerated file
env:
ARTIFACT_DIR: ${{ runner.temp }}/java-sdk-verification-metadata
run: |
set -euo pipefail
# The artifact came from a job that ran PR code: accept one regular file only.
src="$ARTIFACT_DIR/verification-metadata.xml"
if [ ! -f "$src" ] || [ -L "$src" ]; then
echo "Artifact is missing verification-metadata.xml or it is not a regular file." >&2
exit 1
fi
python3 -I trusted/scripts/ci/prek/regenerate_java_sdk_verification_metadata.py --validate "$src"
- name: Commit and push if the metadata changed
env:
# Explicit token push: the checkout stores no credentials
# (persist-credentials: false), so authenticate the push via the URL.
# The checkout stores no credentials (persist-credentials: false),
# so authenticate the push via the URL.
GH_TOKEN: ${{ github.token }}
HEAD_REF: ${{ steps.pr.outputs.head_ref }}
HEAD_REF: ${{ needs.resolve.outputs.head_ref }}
ARTIFACT_DIR: ${{ runner.temp }}/java-sdk-verification-metadata
run: |
set -euo pipefail
if git diff --quiet -- java-sdk/gradle/verification-metadata.xml; then
metadata=java-sdk/gradle/verification-metadata.xml
cp --remove-destination "$ARTIFACT_DIR/verification-metadata.xml" "$metadata"
if git diff --quiet -- "$metadata"; then
echo "verification-metadata.xml already up to date; nothing to do."
exit 0
fi
git config user.name "github-actions[bot]"
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
git add java-sdk/gradle/verification-metadata.xml
git add -- "$metadata"
git commit -m "Refresh Gradle dependency verification metadata for java-sdk"
# Non-force: if the branch moved since `resolve`, the push is rejected
# instead of overwriting the newer commits.
git push "https://x-access-token:${GH_TOKEN}@github.com/${GITHUB_REPOSITORY}.git" \
"HEAD:${HEAD_REF}"
"HEAD:refs/heads/${HEAD_REF}"
2 changes: 2 additions & 0 deletions java-sdk/DEVELOPMENT.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,8 @@ Gradle only appends to the file, so the script empties the component list before

Review every entry in the diff. Generating the file records what the repositories served at that moment; it does not make those bytes trustworthy. Cross-check new coordinates and checksums against the dependency's official release information, and never bypass a failure with lenient or disabled verification.

For a Dependabot PR that changes Java SDK dependencies, a committer can dispatch `.github/workflows/java-sdk-dependabot-verification-metadata.yml` (Actions tab or `gh workflow run`) with the PR number, for a branch in this repository. It regenerates the file with the same script, validates it, and pushes it as a follow-up commit. CI for that commit waits for a maintainer's approval, but approving runs is not a review of the entries and green CI verifies against the same file, so review the new entries on the PR. The workflow is manual because the metadata is checksum-only. If validation refuses the file, regenerate it with the hook and review why.

Not covered: the `example/`, `scala_spark_example/`, and `kubernetes-tests/lang_sdk/java_example/` builds, and the JDK auto-provisioned by the foojay resolver.

## Building documentation
Expand Down
84 changes: 81 additions & 3 deletions scripts/ci/prek/regenerate_java_sdk_verification_metadata.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,15 +21,20 @@
Gradle only ever appends to that file, so a version bump leaves the superseded
entries behind and they stay trusted for good. Starting from an empty list drops
them, which is what turns a stale checksum into a visible diff.

With --validate FILE it instead checks a regenerated file before it is committed.
"""

from __future__ import annotations

import argparse
import pathlib
import re
import subprocess
import sys
import time
from collections.abc import Callable
import xml.etree.ElementTree as ET
from collections.abc import Callable, Sequence

REPO_ROOT = pathlib.Path(__file__).resolve().parents[3]
JAVA_SDK = REPO_ROOT / "java-sdk"
Expand All @@ -44,6 +49,10 @@
"publishToMavenLocal",
]

XML_NAMESPACE = "{https://schema.gradle.org/dependency-verification}"
SHA256_PATTERN = re.compile(r"[0-9a-f]{64}")
GENERATED_ORIGIN = "Generated by Gradle"

MAX_ATTEMPTS = 3
RETRY_DELAY_SECONDS = 30

Expand Down Expand Up @@ -81,6 +90,10 @@ class RegenerationFailedError(RuntimeError):
"""Gradle could not regenerate the metadata within the attempt budget."""


class UnsafeMetadataError(ValueError):
"""The regenerated metadata is not a plain list of generated checksums."""


def build_empty_metadata(committed: str) -> str:
"""Return the committed metadata with its component list emptied."""
kept: list[str] = []
Expand Down Expand Up @@ -150,7 +163,72 @@ def metadata_changed(metadata: pathlib.Path) -> bool:
return result.returncode != 0


def main() -> int:
def get_checksum_map(regenerated: str) -> dict[tuple[str, str, str, str], frozenset[str]]:
"""Parse the metadata, requiring the exact shape Gradle writes, and map artifacts to their hashes."""
if "<!DOCTYPE" in regenerated:
raise UnsafeMetadataError("DOCTYPE declarations are not allowed")
try:
root = ET.fromstring(regenerated)
except ET.ParseError as error:
raise UnsafeMetadataError(f"malformed XML: {error}") from error
if [child.tag for child in root] != [f"{XML_NAMESPACE}configuration", f"{XML_NAMESPACE}components"]:
raise UnsafeMetadataError("root must contain exactly <configuration> then <components>")
checksums: dict[tuple[str, str, str, str], frozenset[str]] = {}
for component in root[1]:
if component.tag != f"{XML_NAMESPACE}component" or set(component.attrib) != {
"group",
"name",
"version",
}:
raise UnsafeMetadataError(f"unexpected element under <components>: {component.tag}")
coordinate = (component.attrib["group"], component.attrib["name"], component.attrib["version"])
for artifact in component:
if artifact.tag != f"{XML_NAMESPACE}artifact" or set(artifact.attrib) != {"name"}:
raise UnsafeMetadataError(f"unexpected element under <component>: {artifact.tag}")
values: set[str] = set()
for sha256 in artifact:
if (
sha256.tag != f"{XML_NAMESPACE}sha256"
or set(sha256.attrib) != {"value", "origin"}
or not SHA256_PATTERN.fullmatch(sha256.attrib["value"])
or sha256.attrib["origin"] != GENERATED_ORIGIN
or len(sha256)
):
raise UnsafeMetadataError(f"unexpected element under <artifact>: {sha256.tag}")
values.add(sha256.attrib["value"])
key = (*coordinate, artifact.attrib["name"])
if not values:
raise UnsafeMetadataError(f"entry without a checksum: {'/'.join(key)}")
# Gradle merges duplicates, so a second entry could add a hash to a retained artifact.
if key in checksums:
raise UnsafeMetadataError(f"duplicate entry: {'/'.join(key)}")
checksums[key] = frozenset(values)
return checksums


def validate_regenerated(committed: str, regenerated: str) -> None:
"""Raise UnsafeMetadataError unless `regenerated` only adds or removes generated checksum entries."""
checksums = get_checksum_map(regenerated)
marker = "<components>"
if marker not in regenerated or regenerated.split(marker, 1)[0] != committed.split(marker, 1)[0]:
raise UnsafeMetadataError("text before <components> differs from the committed file")
committed_checksums = get_checksum_map(committed)
for key, values in checksums.items():
if key in committed_checksums and committed_checksums[key] != values:
raise UnsafeMetadataError(f"checksum changed for a retained artifact: {'/'.join(key)}")


def main(argv: Sequence[str] = ()) -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--validate", type=pathlib.Path, metavar="FILE")
args = parser.parse_args(argv)
if args.validate:
try:
validate_regenerated(METADATA.read_text(), args.validate.read_text())
except UnsafeMetadataError as error:
print(f"ERROR: {error}", file=sys.stderr)
return 1
return 0
try:
regenerate(METADATA, run_gradle)
except RegenerationFailedError as error:
Expand All @@ -162,4 +240,4 @@ def main() -> int:


if __name__ == "__main__":
sys.exit(main())
sys.exit(main(sys.argv[1:]))
Loading
Loading