From fe3ec700dbcc7da79528015a330160d24eacabf8 Mon Sep 17 00:00:00 2001 From: Suneha Bose Date: Mon, 23 Nov 2026 14:37:30 -0800 Subject: [PATCH] feat: add opt-in private-cluster release gate --- .../workflows/check_release_candidate.yaml | 117 ++++++++++ .github/workflows/create_js_branch.yaml | 19 ++ .github/workflows/create_release.yaml | 20 +- .github/workflows/publish_js_project.yaml | 88 ++++++++ .github/workflows/release_js_project.yaml | 80 ++++--- .github/workflows/test_release_gate.yaml | 23 ++ README.md | 108 +++++++++ tests/test_major_tag.py | 157 +++++++++++++ tests/test_release_gate.py | 209 ++++++++++++++++++ 9 files changed, 788 insertions(+), 33 deletions(-) create mode 100644 .github/workflows/check_release_candidate.yaml create mode 100644 .github/workflows/publish_js_project.yaml create mode 100644 .github/workflows/test_release_gate.yaml create mode 100644 tests/test_major_tag.py create mode 100644 tests/test_release_gate.py diff --git a/.github/workflows/check_release_candidate.yaml b/.github/workflows/check_release_candidate.yaml new file mode 100644 index 0000000..0bb8789 --- /dev/null +++ b/.github/workflows/check_release_candidate.yaml @@ -0,0 +1,117 @@ +name: check release candidate + +on: + workflow_call: + inputs: + branch: + required: true + type: string + commit: + required: true + type: string + version: + required: true + type: string + checkName: + required: true + type: string + checkAppId: + required: true + type: number + timeoutMinutes: + required: false + default: 90 + type: number + +jobs: + check: + runs-on: ubuntu-latest + timeout-minutes: 130 + permissions: + contents: read + checks: read + steps: + - name: validate candidate and wait for the trusted result + env: + GH_TOKEN: ${{ github.token }} + CANDIDATE_REPOSITORY: ${{ github.repository }} + CANDIDATE_BRANCH: ${{ inputs.branch }} + CANDIDATE_COMMIT: ${{ inputs.commit }} + CANDIDATE_VERSION: ${{ inputs.version }} + REQUIRED_CHECK_NAME: ${{ inputs.checkName }} + REQUIRED_CHECK_APP_ID: ${{ inputs.checkAppId }} + CHECK_TIMEOUT_MINUTES: ${{ inputs.timeoutMinutes }} + run: | + python3 - <<'PY' + import json + import os + import re + import subprocess + import time + from urllib.parse import quote + + def api(endpoint, paginate=False): + command = ['gh', 'api', '--method', 'GET', endpoint] + if paginate: + command.extend(['--paginate', '--slurp']) + try: + result = subprocess.run(command, check=True, capture_output=True, text=True, timeout=60) + except subprocess.CalledProcessError as error: + raise RuntimeError(f'GitHub API request failed: {error.stderr}') from error + return json.loads(result.stdout) + + def verify_branch(repository, branch, commit): + ref = api(f'repos/{repository}/git/ref/heads/{quote(branch, safe="/")}') + if ref['object']['type'] != 'commit' or ref['object']['sha'] != commit: + raise ValueError('Release branch no longer matches the candidate commit') + + def wait_for_check(repository, branch, commit, name, app_id, timeout): + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + verify_branch(repository, branch, commit) + pages = api( + f'repos/{repository}/commits/{commit}/check-runs?check_name={quote(name, safe="")}&filter=all&per_page=100', + paginate=True, + ) + matching = [ + check for page in pages for check in page['check_runs'] + if check['name'] == name and check['head_sha'] == commit + and (check.get('app') or {}).get('id') == app_id + ] + if matching: + latest = max(matching, key=lambda check: check['id']) + if latest['status'] == 'completed': + if latest['conclusion'] != 'success': + raise ValueError(f"Required check concluded {latest['conclusion']}: {latest['html_url']}") + verify_branch(repository, branch, commit) + return latest['html_url'] + remaining = deadline - time.monotonic() + if remaining > 0: + time.sleep(min(30, remaining)) + raise TimeoutError('No successful trusted check arrived for the candidate commit') + + def main(): + repository = os.environ['CANDIDATE_REPOSITORY'] + branch = os.environ['CANDIDATE_BRANCH'] + commit = os.environ['CANDIDATE_COMMIT'] + version = os.environ['CANDIDATE_VERSION'] + name = os.environ['REQUIRED_CHECK_NAME'].strip() + app = os.environ['REQUIRED_CHECK_APP_ID'] + minutes = os.environ['CHECK_TIMEOUT_MINUTES'] + if not re.fullmatch(r'v\d+\.\d+\.\d+', version): + raise ValueError('The private-cluster gate requires a stable vX.Y.Z release') + if branch != f'releases/{version}' or not re.fullmatch(r'[0-9a-f]{40}', commit): + raise ValueError('Expected the release branch and a full candidate commit SHA') + if not name or not re.fullmatch(r'[1-9][0-9]*', app): + raise ValueError('A gated release requires a check name and trusted GitHub App ID') + if not re.fullmatch(r'[1-9][0-9]*', minutes) or int(minutes) > 120: + raise ValueError('Check timeout must be between 1 and 120 minutes') + + verify_branch(repository, branch, commit) + result = wait_for_check(repository, branch, commit, name, int(app), int(minutes) * 60) + with open(os.environ['GITHUB_STEP_SUMMARY'], 'a') as summary: + summary.write(f'Release candidate: `{branch}` at `{commit}`\n\n{result}\n') + + if __name__ == '__main__': + main() + PY diff --git a/.github/workflows/create_js_branch.yaml b/.github/workflows/create_js_branch.yaml index c3b299f..c2f6f57 100644 --- a/.github/workflows/create_js_branch.yaml +++ b/.github/workflows/create_js_branch.yaml @@ -7,10 +7,20 @@ on: required: true type: string description: The version of the release + outputs: + branch: + description: The prepared release branch + value: ${{ jobs.branch.outputs.branch }} + commit: + description: The final release commit containing the built artifacts + value: ${{ jobs.branch.outputs.commit }} jobs: branch: runs-on: ubuntu-latest + outputs: + branch: ${{ steps.candidate.outputs.branch }} + commit: ${{ steps.candidate.outputs.commit }} env: BRANCH: releases/${{ inputs.version }} GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} @@ -55,3 +65,12 @@ jobs: git add . git commit -m "build" git push origin ${BRANCH} + + - name: record release candidate + id: candidate + run: | + set -euo pipefail + commit=$(git rev-parse HEAD) + echo "branch=${BRANCH}" >> "$GITHUB_OUTPUT" + echo "commit=${commit}" >> "$GITHUB_OUTPUT" + printf 'Release candidate: `%s` at `%s`\n' "$BRANCH" "$commit" >> "$GITHUB_STEP_SUMMARY" diff --git a/.github/workflows/create_release.yaml b/.github/workflows/create_release.yaml index 8d5954c..6d28ba2 100644 --- a/.github/workflows/create_release.yaml +++ b/.github/workflows/create_release.yaml @@ -20,6 +20,11 @@ on: default: false type: boolean description: Whether the release is a prerelease + expectedCommit: + required: false + default: "" + type: string + description: When set, require the branch to still point to this full commit and tag this commit jobs: release: @@ -37,7 +42,20 @@ jobs: - id: normalize env: INPUT_BRANCH: ${{ inputs.branch }} - run: echo "commit=${INPUT_BRANCH#refs/heads/}" >> "$GITHUB_OUTPUT" + EXPECTED_COMMIT: ${{ inputs.expectedCommit }} + RELEASE_VERSION: ${{ inputs.version }} + run: | + set -euo pipefail + branch=${INPUT_BRANCH#refs/heads/} + commit=$branch + if [[ -n "$EXPECTED_COMMIT" ]]; then + [[ "$EXPECTED_COMMIT" =~ ^[0-9a-f]{40}$ ]] || { echo "Expected a full commit SHA" >&2; exit 1; } + actual=$(git ls-remote origin "refs/heads/$branch" | cut -f1) + [[ "$actual" = "$EXPECTED_COMMIT" ]] || { echo "Release branch no longer matches the tested commit" >&2; exit 1; } + git push origin "$EXPECTED_COMMIT:refs/tags/$RELEASE_VERSION" + commit=$EXPECTED_COMMIT + fi + echo "commit=$commit" >> "$GITHUB_OUTPUT" - uses: ncipollo/release-action@b7eabc95ff50cbeeedec83973935c8f306dfcd0b # v1.20.0 with: diff --git a/.github/workflows/publish_js_project.yaml b/.github/workflows/publish_js_project.yaml new file mode 100644 index 0000000..118413e --- /dev/null +++ b/.github/workflows/publish_js_project.yaml @@ -0,0 +1,88 @@ +name: publish prepared JS project + +on: + workflow_call: + inputs: + branch: + required: true + type: string + commit: + required: true + type: string + version: + required: true + type: string + body: + required: true + type: string + checkName: + required: true + type: string + checkAppId: + required: true + type: number + timeoutMinutes: + required: false + default: 90 + type: number + +jobs: + checkCandidate: + permissions: + contents: read + checks: read + uses: ./.github/workflows/check_release_candidate.yaml + with: + branch: ${{ inputs.branch }} + commit: ${{ inputs.commit }} + version: ${{ inputs.version }} + checkName: ${{ inputs.checkName }} + checkAppId: ${{ inputs.checkAppId }} + timeoutMinutes: ${{ inputs.timeoutMinutes }} + createRelease: + needs: checkCandidate + permissions: + contents: write + uses: ./.github/workflows/create_release.yaml + with: + branch: ${{ inputs.branch }} + expectedCommit: ${{ inputs.commit }} + version: ${{ inputs.version }} + body: ${{ inputs.body }} + updateMajorTag: + needs: createRelease + runs-on: ubuntu-latest + permissions: + contents: write + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ inputs.commit }} + - name: replace the major tag without deleting the remote ref + env: + RELEASE_BRANCH: ${{ inputs.branch }} + CANDIDATE_COMMIT: ${{ inputs.commit }} + RELEASE_VERSION: ${{ inputs.version }} + run: | + set -euo pipefail + [[ "$CANDIDATE_COMMIT" =~ ^[0-9a-f]{40}$ ]] || { echo "Expected a full candidate commit" >&2; exit 1; } + [[ "$RELEASE_VERSION" =~ ^v[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?(\+[0-9A-Za-z.-]+)?$ ]] || { echo "Expected a release version" >&2; exit 1; } + [[ "$RELEASE_BRANCH" = "releases/$RELEASE_VERSION" ]] || { echo "Unexpected release branch" >&2; exit 1; } + + actual=$(git ls-remote --heads origin "refs/heads/$RELEASE_BRANCH" | cut -f1) + [[ "$actual" = "$CANDIDATE_COMMIT" ]] || { echo "Release branch changed after validation" >&2; exit 1; } + git fetch --no-tags origin "refs/tags/$RELEASE_VERSION" + [[ "$(git rev-parse 'FETCH_HEAD^{commit}')" = "$CANDIDATE_COMMIT" ]] || { echo "Release tag does not match the tested commit" >&2; exit 1; } + + major_tag=${RELEASE_VERSION%%.*} + major_ref="refs/tags/$major_tag" + previous=$(git ls-remote --refs origin "$major_ref" | cut -f1) + git config user.name 'github-actions[bot]' + git config user.email 'github-actions[bot]@users.noreply.github.com' + # Checkout may contain a local tag; keep the remote ref intact. + if git show-ref --verify --quiet "$major_ref"; then + git tag --delete "$major_tag" + fi + git tag -a "$major_tag" "$CANDIDATE_COMMIT" -m "Latest $major_tag Release" + # The explicit old object also protects concurrent updates and first creation. + git push --force-with-lease="$major_ref:$previous" origin "$major_ref:$major_ref" diff --git a/.github/workflows/release_js_project.yaml b/.github/workflows/release_js_project.yaml index ccd6cfe..8dbb0b0 100644 --- a/.github/workflows/release_js_project.yaml +++ b/.github/workflows/release_js_project.yaml @@ -7,6 +7,24 @@ on: required: true type: string description: The path to CHANGELOG.md + prepareOnly: + required: false + default: false + type: boolean + description: Prepare the built release commit without publishing or moving tags + outputs: + branch: + description: The prepared release branch + value: ${{ jobs.createBranch.outputs.branch }} + commit: + description: The final release commit containing the built artifacts + value: ${{ jobs.createBranch.outputs.commit }} + version: + description: The release version with its v prefix + value: v${{ jobs.extractChangelog.outputs.version }} + body: + description: The release notes + value: ${{ jobs.extractChangelog.outputs.body }} jobs: extractChangelog: @@ -31,45 +49,43 @@ jobs: if: needs.checkVersion.outputs.exists == 'false' uses: ./.github/workflows/create_js_branch.yaml with: - version: v${{ needs.extractChangelog.outputs.version }} + version: v${{ needs.extractChangelog.outputs.version }} createRelease: needs: [checkVersion, extractChangelog, createBranch] permissions: contents: write - if: needs.checkVersion.outputs.exists == 'false' + if: needs.checkVersion.outputs.exists == 'false' && !inputs.prepareOnly uses: ./.github/workflows/create_release.yaml with: branch: releases/v${{ needs.extractChangelog.outputs.version }} version: v${{ needs.extractChangelog.outputs.version }} body: ${{ needs.extractChangelog.outputs.body }} updateMajorTag: - runs-on: ubuntu-latest - permissions: - contents: write - needs: [extractChangelog, createBranch, createRelease] - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - ref: releases/v${{ needs.extractChangelog.outputs.version }} - - name: get major version tag - id: major-version-tag - env: - NEW_RELEASE_TAG: ${{ needs.extractChangelog.outputs.version }} - run: - echo "MAJOR_VERSION_TAG=v${NEW_RELEASE_TAG%%.*}" >> "$GITHUB_OUTPUT" - - name: delete old major tag - continue-on-error: true - env: - GH_TOKEN: ${{ github.token }} - MAJOR_VERSION_TAG: ${{ steps.major-version-tag.outputs.MAJOR_VERSION_TAG }} - run: - git push origin :refs/tags/$MAJOR_VERSION_TAG - - name: create new major tag - env: - GH_TOKEN: ${{ github.token }} - MAJOR_VERSION_TAG: ${{ steps.major-version-tag.outputs.MAJOR_VERSION_TAG }} - run: | - git config user.name 'github-actions[bot]' - git config user.email 'github-actions[bot]@users.noreply.github.com' - git tag -a $MAJOR_VERSION_TAG -m "Latest $MAJOR_VERSION_TAG Release" - git push origin refs/tags/$MAJOR_VERSION_TAG + runs-on: ubuntu-latest + permissions: + contents: write + needs: [extractChangelog, createBranch, createRelease] + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: releases/v${{ needs.extractChangelog.outputs.version }} + - name: get major version tag + id: major-version-tag + env: + NEW_RELEASE_TAG: ${{ needs.extractChangelog.outputs.version }} + run: echo "MAJOR_VERSION_TAG=v${NEW_RELEASE_TAG%%.*}" >> "$GITHUB_OUTPUT" + - name: delete old major tag + continue-on-error: true + env: + GH_TOKEN: ${{ github.token }} + MAJOR_VERSION_TAG: ${{ steps.major-version-tag.outputs.MAJOR_VERSION_TAG }} + run: git push origin :refs/tags/$MAJOR_VERSION_TAG + - name: create new major tag + env: + GH_TOKEN: ${{ github.token }} + MAJOR_VERSION_TAG: ${{ steps.major-version-tag.outputs.MAJOR_VERSION_TAG }} + run: | + git config user.name 'github-actions[bot]' + git config user.email 'github-actions[bot]@users.noreply.github.com' + git tag -a $MAJOR_VERSION_TAG -m "Latest $MAJOR_VERSION_TAG Release" + git push origin refs/tags/$MAJOR_VERSION_TAG diff --git a/.github/workflows/test_release_gate.yaml b/.github/workflows/test_release_gate.yaml new file mode 100644 index 0000000..6f2b011 --- /dev/null +++ b/.github/workflows/test_release_gate.yaml @@ -0,0 +1,23 @@ +name: Test release gate + +on: + pull_request: + paths: + - ".github/workflows/**" + - "tests/**" + push: + branches: + - main + paths: + - ".github/workflows/**" + - "tests/**" + +permissions: + contents: read + +jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - run: python3 -B -m unittest discover -s tests -v diff --git a/README.md b/README.md index 1bfa55b..9cdd2a1 100644 --- a/README.md +++ b/README.md @@ -18,6 +18,8 @@ Reusable GitHub Actions workflows for automated releases. Includes AI-powered ve | `check_signed_commits.yaml` | `workflow_call` | Reusable: verifies all PR commits are signed | | `release_js_project.yaml` | `workflow_call` | Reusable: full JS project release (changelog, branch, release, major tag) | | `create_js_branch.yaml` | `workflow_call` | Reusable: creates a release branch with built JS artifacts | +| `check_release_candidate.yaml` | `workflow_call` | Reusable: validates the candidate and waits for a check from an approved GitHub App | +| `publish_js_project.yaml` | `workflow_call` | Reusable: publishes the prepared commit only after the trusted check succeeds | | `switch_js_branch.yaml` | `workflow_call` | Reusable: switches/creates a release branch (e.g. nightly) | | `nightly_release.yaml` | `workflow_call` | Reusable: nightly release to `releases/nightly` branch | @@ -153,6 +155,112 @@ jobs: Verifies all commits in a PR are signed. Posts a comment listing unsigned commits if any are found. +### Prepare, validate, and publish a JS release + +`release_js_project.yaml` keeps its existing automatic publication behavior unless +`prepareOnly: true` is supplied. Preparation returns `branch`, `commit`, `version`, +and `body`. The commit is recorded after the release bundle is built, committed, +and pushed, not before the build. Existing preparation steps and the default +publishing, major-tag, and prerelease behavior are preserved. Existing callers +do not need Azure DevOps configuration or additional token permissions. + +For a protected release, separate preparation from publication: + +```text +Prepare built commit + | +Trusted bridge runs the external test for that commit + | +GitHub check from the approved App on that commit + | +publish_js_project.yaml validates the result and publishes that commit +``` + +The following is an activation example. Replace `REVIEWED_COMMIT_SHA` with the +reviewed shared-workflow commit only after the external bridge is configured. +It is not a working bridge or an Azure DevOps trigger. +Keep the existing publisher until preparation, the automatic trusted test +trigger, and gated publication can be switched together. Do not activate an +intermediate preparation-only caller. The bridge must automatically queue the +test after approved preparation; waiting for a result does not itself start it. + +```yaml +jobs: + prepare: + permissions: + actions: read + contents: write + uses: Azure/action-release-workflows/.github/workflows/release_js_project.yaml@REVIEWED_COMMIT_SHA + with: + changelogPath: ./CHANGELOG.md + prepareOnly: true + publish: + needs: prepare + if: needs.prepare.outputs.commit != '' + permissions: + contents: write + checks: read + uses: Azure/action-release-workflows/.github/workflows/publish_js_project.yaml@REVIEWED_COMMIT_SHA + with: + branch: ${{ needs.prepare.outputs.branch }} + commit: ${{ needs.prepare.outputs.commit }} + version: ${{ needs.prepare.outputs.version }} + body: ${{ needs.prepare.outputs.body }} + checkName: '1ES private-cluster release gate' + checkAppId: ${{ fromJSON(vars.PRIVATE_CLUSTER_GATE_APP_ID || '0') }} + timeoutMinutes: 90 +``` + +The gated publisher requires a nonempty check name and a positive GitHub App ID. +There is no ungated fallback in `publish_js_project.yaml`. It accepts only the +latest matching check run from that App on the candidate SHA, with a completed +`success` conclusion. Commit statuses or checks from other Apps cannot satisfy it. +Missing results time out; newer failed, cancelled, or pending runs do not reuse an +older success. The timeout must be between 1 and 120 minutes. +This opt-in private-cluster flow supports stable `vX.Y.Z` releases, matching the +1ES candidate checks. It does not introduce prerelease publishing behavior. + +The release branch must still match the candidate. Publication uses the full SHA +rather than a branch name, and major-tag publication also checks the version tag. +A branch change detected before publication stops the job; pinning the tag target +to the SHA prevents a later branch movement from selecting untested code. + +Only the new gated publisher uses the stricter tag update. It verifies the +release branch and version tag, reads the current major-tag object, and replaces +that single remote ref with an explicit `--force-with-lease=:` guard. +It never deletes the remote major tag first. A rejected push leaves the existing +tag in place, and a concurrent change rejects the update instead of being overwritten. +For a new major tag, the empty expected object requires the ref to remain absent. +Version tags are not force-updated. + +The optional `expectedCommit` input to `create_release.yaml` also applies only +when explicitly supplied. The existing automatic release workflow does not set +it or call the new gate/tag helpers. General hardening of the legacy publisher +and corrections to its prerelease behavior are separate changes, not part of +this opt-in integration. + +The trusted bridge is external to these workflows. It must authorize the +preparation run and approved source revision, queue the exact built candidate +using a governed definition, and report a SHA-bound check using the configured +App. Branch activity or a caller-provided SHA is not authorization to run +privileged code. Define pipeline/service-connection checks and queue permissions +outside candidate-controlled YAML. Failed or cancelled external runs must be +reported, not silently omitted. These workflows grant no Azure permissions and do +not queue Azure DevOps pipelines. + +For the k8s-deploy 1ES pipeline, select the reviewed definition revision as the +Azure DevOps `self` repository revision. Pass the preparation outputs separately +as `releaseCandidateBranch` and `releaseCandidateCommit`. The pipeline checks out +that candidate in a separate directory; its `Build.SourceVersion` identifies the +definition revision, not the action being tested. Do not load pipeline YAML or +cleanup scripts from the candidate checkout. + +Run the local contract tests with: + +```bash +python3 -B -m unittest discover -s tests -v +``` + ## Contributing See [CONTRIBUTING.md](CONTRIBUTING.md) for details on how to contribute, the release process, and the CLA requirement. diff --git a/tests/test_major_tag.py b/tests/test_major_tag.py new file mode 100644 index 0000000..643a1a3 --- /dev/null +++ b/tests/test_major_tag.py @@ -0,0 +1,157 @@ +import json +import os +from pathlib import Path +import subprocess +import tempfile +import textwrap +import unittest + + +ROOT = Path(__file__).resolve().parents[1] +COMMIT = "a" * 40 +PREVIOUS = "b" * 40 +REPLACEMENT = "c" * 40 +CONCURRENT = "d" * 40 + +GIT_STUB = """#!/usr/bin/env python3 +import json +import os +from pathlib import Path +import sys + +state_file = Path(os.environ['FAKE_GIT_STATE']) +state = json.loads(state_file.read_text()) +args = sys.argv[1:] +state['calls'].append(args) + +def finish(code=0): + state_file.write_text(json.dumps(state)) + sys.exit(code) + +if args[:3] == ['ls-remote', '--heads', 'origin']: + print(state['branch'] + '\\trefs/heads/releases/v7.0.2') + finish() +if args == ['fetch', '--no-tags', 'origin', 'refs/tags/v7.0.2']: + finish() +if args == ['rev-parse', 'FETCH_HEAD^{commit}']: + print(state['version_tag']) + finish() +if args == ['ls-remote', '--refs', 'origin', 'refs/tags/v7']: + if state['mode'] == 'lookup_failure': + print('fixture: tag lookup failed', file=sys.stderr) + finish(1) + if state['remote'] is not None: + print(state['remote'] + '\\trefs/tags/v7') + finish() +if args[0] == 'config': + finish() +if args == ['show-ref', '--verify', '--quiet', 'refs/tags/v7']: + finish(0 if state['local_tag'] else 1) +if args == ['tag', '--delete', 'v7']: + state['local_tag'] = None + finish() +if args == ['tag', '-a', 'v7', state['candidate'], '-m', 'Latest v7 Release']: + state['local_tag'] = state['replacement'] + finish() +if args[0] == 'push': + prefix = '--force-with-lease=refs/tags/v7:' + if len(args) != 4 or not args[1].startswith(prefix) or args[2:] != ['origin', 'refs/tags/v7:refs/tags/v7']: + print('fixture: unexpected or unguarded push', file=sys.stderr) + finish(99) + if state['mode'] == 'push_failure': + print('fixture: update failed', file=sys.stderr) + finish(1) + if state['mode'] == 'concurrent_change': + state['remote'] = state['concurrent'] + if args[1][len(prefix):] != (state['remote'] or ''): + print('fixture: lease rejected', file=sys.stderr) + finish(1) + state['remote'] = state['local_tag'] + state['published_commit'] = state['candidate'] + finish() +print('fixture: unexpected Git command', file=sys.stderr) +finish(99) +""" + + +class MajorTagTests(unittest.TestCase): + def run_update(self, mode="success", previous=PREVIOUS, branch=COMMIT, + version_tag=COMMIT, local_tag=False): + workflow = (ROOT / ".github/workflows/publish_js_project.yaml").read_text() + script = textwrap.dedent(workflow.split(" run: |\n", 1)[1]) + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + git = root / "git" + git.write_text(GIT_STUB) + git.chmod(0o755) + state_file = root / "state.json" + state_file.write_text(json.dumps({ + "calls": [], "mode": mode, "remote": previous, "branch": branch, + "version_tag": version_tag, "candidate": COMMIT, + "local_tag": PREVIOUS if local_tag else None, + "replacement": REPLACEMENT, "concurrent": CONCURRENT, + })) + result = subprocess.run( + ["bash", "-c", script], cwd=root, + env={ + **os.environ, + "PATH": str(root) + os.pathsep + os.environ["PATH"], + "FAKE_GIT_STATE": str(state_file), + "RELEASE_BRANCH": "releases/v7.0.2", + "CANDIDATE_COMMIT": COMMIT, + "RELEASE_VERSION": "v7.0.2", + }, + capture_output=True, text=True, timeout=10, + ) + return result, json.loads(state_file.read_text()) + + def test_success_uses_one_guarded_update_without_remote_deletion(self): + for cached in [False, True]: + with self.subTest(local_tag=cached): + result, state = self.run_update(local_tag=cached) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(state["remote"], REPLACEMENT) + self.assertEqual(state["published_commit"], COMMIT) + pushes = [call for call in state["calls"] if call[0] == "push"] + self.assertEqual(pushes, [[ + "push", f"--force-with-lease=refs/tags/v7:{PREVIOUS}", + "origin", "refs/tags/v7:refs/tags/v7", + ]]) + + def test_failed_update_keeps_the_old_remote_tag(self): + result, state = self.run_update(mode="push_failure") + self.assertNotEqual(result.returncode, 0) + self.assertEqual(state["remote"], PREVIOUS) + + def test_concurrent_change_is_not_overwritten(self): + for previous in [PREVIOUS, None]: + with self.subTest(previous=previous): + result, state = self.run_update(mode="concurrent_change", previous=previous) + self.assertNotEqual(result.returncode, 0) + self.assertEqual(state["remote"], CONCURRENT) + self.assertIn("lease rejected", result.stderr) + + def test_first_creation_requires_the_remote_tag_to_remain_absent(self): + result, state = self.run_update(previous=None) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(state["remote"], REPLACEMENT) + push = next(call for call in state["calls"] if call[0] == "push") + self.assertEqual(push[1], "--force-with-lease=refs/tags/v7:") + + def test_branch_or_version_tag_mismatch_stops_before_push(self): + for change in [{"branch": CONCURRENT}, {"version_tag": CONCURRENT}]: + with self.subTest(change=change): + result, state = self.run_update(**change) + self.assertNotEqual(result.returncode, 0) + self.assertEqual(state["remote"], PREVIOUS) + self.assertFalse(any(call[0] == "push" for call in state["calls"])) + + def test_lookup_failure_stops_before_push(self): + result, state = self.run_update(mode="lookup_failure") + self.assertNotEqual(result.returncode, 0) + self.assertEqual(state["remote"], PREVIOUS) + self.assertFalse(any(call[0] == "push" for call in state["calls"])) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_release_gate.py b/tests/test_release_gate.py new file mode 100644 index 0000000..dd052a2 --- /dev/null +++ b/tests/test_release_gate.py @@ -0,0 +1,209 @@ +import os +from pathlib import Path +import re +import subprocess +import tempfile +import textwrap +import types +import unittest +from unittest import mock + + +ROOT = Path(__file__).resolve().parents[1] +WORKFLOWS = ROOT / ".github/workflows" +COMMIT = "a" * 40 +BRANCH = "releases/v7.0.2" +CHECK_NAME = "1ES private-cluster release gate" +ENVIRONMENT = { + "CANDIDATE_REPOSITORY": "Azure/k8s-deploy", + "CANDIDATE_BRANCH": BRANCH, + "CANDIDATE_COMMIT": COMMIT, + "CANDIDATE_VERSION": "v7.0.2", + "REQUIRED_CHECK_NAME": CHECK_NAME, + "REQUIRED_CHECK_APP_ID": "123", + "CHECK_TIMEOUT_MINUTES": "90", +} + + +def load_gate(): + text = (WORKFLOWS / "check_release_candidate.yaml").read_text() + source = text.split("python3 - <<'PY'\n", 1)[1] + source = re.split(r"\n +PY\s*$", source)[0] + module = types.ModuleType("release_gate") + exec(compile(textwrap.dedent(source), "release_gate", "exec"), module.__dict__) + return module + + +def check_run(identifier=1, app=123, commit=COMMIT, status="completed", conclusion="success"): + return { + "id": identifier, + "app": {"id": app}, + "head_sha": commit, + "name": CHECK_NAME, + "status": status, + "conclusion": conclusion, + "html_url": f"https://github.com/checks/{identifier}", + } + + +class ReleaseGateTests(unittest.TestCase): + def setUp(self): + self.gate = load_gate() + + def run_gate(self, pages, branch_commits=None): + commits = iter(branch_commits or [COMMIT, COMMIT]) + + def api(endpoint, paginate=False): + if "/git/ref/" in endpoint: + return {"object": {"type": "commit", "sha": next(commits)}} + self.assertTrue(paginate) + self.assertIn(f"/commits/{COMMIT}/check-runs?", endpoint) + return pages + + with ( + mock.patch.object(self.gate, "api", side_effect=api), + mock.patch.object(self.gate.time, "monotonic", side_effect=[0, 1, 2, 3]), + mock.patch.object(self.gate.time, "sleep"), + ): + return self.gate.wait_for_check("Azure/k8s-deploy", BRANCH, COMMIT, CHECK_NAME, 123, 3) + + def test_trusted_result_can_be_on_a_later_page(self): + result = self.run_gate([ + {"check_runs": [check_run(identifier=99, app=999)]}, + {"check_runs": [check_run(identifier=2)]}, + ]) + self.assertEqual(result, "https://github.com/checks/2") + + def test_wrong_app_or_commit_cannot_satisfy_gate(self): + for result in [check_run(app=999), check_run(commit="b" * 40)]: + with self.subTest(result=result), self.assertRaises(TimeoutError): + self.run_gate([{"check_runs": [result]}]) + + def test_missing_result_times_out(self): + with self.assertRaises(TimeoutError): + self.run_gate([{"check_runs": []}]) + + def test_newer_failed_or_cancelled_run_overrides_old_success(self): + for conclusion in ["failure", "cancelled"]: + with self.subTest(conclusion=conclusion), self.assertRaises(ValueError): + self.run_gate([{"check_runs": [ + check_run(), check_run(identifier=2, conclusion=conclusion) + ]}]) + + def test_newer_pending_run_does_not_reuse_old_success(self): + with self.assertRaises(TimeoutError): + self.run_gate([{"check_runs": [ + check_run(), check_run(identifier=2, status="in_progress", conclusion=None) + ]}]) + + def test_branch_moved_after_success_is_rejected(self): + with self.assertRaisesRegex(ValueError, "no longer matches"): + self.run_gate([{"check_runs": [check_run()]}], [COMMIT, "b" * 40]) + + def test_missing_identity_or_invalid_candidate_fails_before_api(self): + for change in [ + {"REQUIRED_CHECK_APP_ID": "0"}, + {"REQUIRED_CHECK_NAME": ""}, + {"CANDIDATE_COMMIT": "main"}, + {"CANDIDATE_BRANCH": "main"}, + {"CHECK_TIMEOUT_MINUTES": "0"}, + {"CANDIDATE_VERSION": "v7.0.2-rc.1", "CANDIDATE_BRANCH": "releases/v7.0.2-rc.1"}, + ]: + with ( + self.subTest(change=change), + mock.patch.dict(os.environ, {**ENVIRONMENT, **change}, clear=True), + mock.patch.object(self.gate, "api") as api, + self.assertRaises(ValueError), + ): + self.gate.main() + api.assert_not_called() + + def test_entrypoint_waits_for_pending_check_to_succeed(self): + checks = iter([ + check_run(status="in_progress", conclusion=None), + check_run(status="completed"), + ]) + + def api(endpoint, paginate=False): + if "/git/ref/" in endpoint: + return {"object": {"type": "commit", "sha": COMMIT}} + return [{"check_runs": [next(checks)]}] + + with tempfile.TemporaryDirectory() as directory: + summary = Path(directory) / "summary" + with ( + mock.patch.dict(os.environ, {**ENVIRONMENT, "GITHUB_STEP_SUMMARY": str(summary)}, clear=True), + mock.patch.object(self.gate, "api", side_effect=api), + mock.patch.object(self.gate.time, "sleep") as sleep, + ): + self.gate.main() + sleep.assert_called_once() + self.assertIn(COMMIT, summary.read_text()) + self.assertIn("https://github.com/checks/1", summary.read_text()) + + def test_api_failure_cannot_turn_into_success(self): + with ( + mock.patch.object(self.gate.subprocess, "run", side_effect=subprocess.CalledProcessError(1, "gh", stderr="HTTP 403")), + self.assertRaisesRegex(RuntimeError, "GitHub API request failed: HTTP 403"), + ): + self.gate.wait_for_check("Azure/k8s-deploy", BRANCH, COMMIT, CHECK_NAME, 123, 3) + + +class PublishCommitTests(unittest.TestCase): + def normalize(self, expected, actual=COMMIT, tag_conflict=False): + text = (WORKFLOWS / "create_release.yaml").read_text() + script = text.split(" - id: normalize\n", 1)[1].split(" run: |\n", 1)[1] + script = script.split("\n - uses:", 1)[0] + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + git = root / "git" + git.write_text( + "#!/bin/sh\n" + "if [ \"$1\" = ls-remote ]; then\n" + " printf '%s\\trefs/heads/releases/v7.0.2\\n' \"$TEST_REF_SHA\"\n" + "elif [ \"$1\" = push ]; then\n" + " test \"$3\" = \"$EXPECTED_COMMIT:refs/tags/$RELEASE_VERSION\" || exit 99\n" + " exit \"$TEST_TAG_CONFLICT\"\n" + "else exit 99; fi\n" + ) + git.chmod(0o755) + output = root / "output" + result = subprocess.run( + ["bash", "-c", textwrap.dedent(script)], + env={ + **os.environ, + "PATH": str(root) + os.pathsep + os.environ["PATH"], + "INPUT_BRANCH": f"refs/heads/{BRANCH}", + "EXPECTED_COMMIT": expected, + "RELEASE_VERSION": "v7.0.2", + "TEST_REF_SHA": actual, + "TEST_TAG_CONFLICT": "1" if tag_conflict else "0", + "GITHUB_OUTPUT": str(output), + }, + capture_output=True, text=True, timeout=10, + ) + return result, output.read_text() if output.exists() else "" + + def test_existing_ungated_callers_keep_branch_normalization(self): + result, output = self.normalize("") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(output, f"commit={BRANCH}\n") + + def test_gated_publication_targets_exact_commit(self): + result, output = self.normalize(COMMIT) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(output, f"commit={COMMIT}\n") + + def test_changed_branch_prevents_publication(self): + result, output = self.normalize(COMMIT, actual="b" * 40) + self.assertNotEqual(result.returncode, 0) + self.assertEqual(output, "") + + def test_conflicting_version_tag_prevents_publication(self): + result, output = self.normalize(COMMIT, tag_conflict=True) + self.assertNotEqual(result.returncode, 0) + self.assertEqual(output, "") + + +if __name__ == "__main__": + unittest.main()