diff --git a/.github/workflows/nightly-dispatch.yml b/.github/workflows/nightly-dispatch.yml index 4ef372c40b..4581f75d39 100644 --- a/.github/workflows/nightly-dispatch.yml +++ b/.github/workflows/nightly-dispatch.yml @@ -16,9 +16,11 @@ jobs: github.repository == 'storytold/vectorcraft' && github.event_name == 'workflow_run' runs-on: ubuntu-latest - timeout-minutes: 5 + # Most of the time is the wait for the producer commit's SonarCloud analysis (up to 280 minutes). + timeout-minutes: 300 permissions: actions: write + checks: read steps: - name: Dispatch only the exact completed producer run and attempt shell: python @@ -27,6 +29,10 @@ jobs: run: | import json import os + import re + import time + import urllib.error + import urllib.parse import urllib.request def require(value, message): @@ -51,22 +57,58 @@ jobs: run_id, attempt = producer.get('id'), producer.get('run_attempt') require(type(run_id) is int and run_id > 0, 'invalid producer run id') require(type(attempt) is int and attempt == 1, 'invalid automatic producer attempt') + source = producer.get('head_sha') + require(isinstance(source, str) and re.fullmatch(r'[0-9a-f]{40}', source), 'invalid producer commit') + headers = { + 'Authorization': 'Bearer ' + os.environ['GH_TOKEN'], + 'Accept': 'application/vnd.github+json', + 'X-GitHub-Api-Version': '2022-11-28', + 'User-Agent': 'vectorcraft-nightly-dispatch' + } + class NoRedirect(urllib.request.HTTPRedirectHandler): + def redirect_request(self, req, fp, code, msg, headers, newurl): + raise RuntimeError('dispatch redirects are forbidden') + opener = urllib.request.build_opener(NoRedirect()) + + def read(path): + request = urllib.request.Request('https://api.github.com/repos/storytold/vectorcraft' + path, headers=headers) + with opener.open(request, timeout=20) as response: + require(response.status == 200, 'read was not accepted') + return json.load(response) + + # Stage 2 admits the producer only on its commit's own SonarCloud analysis, which + # sonarcloud.yml starts when the producer starts. Wait for the check that analysis posts; + # a SonarCloud run that ended without one gets 20 minutes before the wait gives up. + checks_path = '/commits/' + source + '/check-runs?' + urllib.parse.urlencode( + {'app_id': 12526, 'check_name': 'SonarCloud Code Analysis', 'filter': 'latest'}) + runs_path = '/actions/workflows/sonarcloud.yml/runs?' + urllib.parse.urlencode( + {'event': 'workflow_run', 'head_sha': source, 'per_page': 1}) + deadline = time.monotonic() + 280 * 60 + ended = None + while True: + try: + checks = read(checks_path).get('check_runs', []) + if any(c.get('head_sha') == source and c.get('status') == 'completed' for c in checks): + break + runs = read(runs_path).get('workflow_runs', []) + if runs and runs[0].get('status') == 'completed' and ended is None: + ended = time.monotonic() + print('SonarCloud run', runs[0].get('id'), 'ended:', runs[0].get('conclusion')) + except (urllib.error.URLError, OSError, ValueError) as error: + print('Read failed, polling again:', error) + require(ended is None or time.monotonic() < ended + 20 * 60, + 'the SonarCloud run for the producer commit ended without an analysis check') + require(time.monotonic() < deadline, 'no SonarCloud analysis of the producer commit in time') + time.sleep(60) + print('SonarCloud analysis check of', source, 'is complete.') + body = json.dumps({'ref': 'refs/heads/nightly-signer', 'inputs': { 'producer_run_id': str(run_id), 'producer_run_attempt': str(attempt) }}).encode('utf-8') request = urllib.request.Request( 'https://api.github.com/repos/storytold/vectorcraft/actions/workflows/nightly-sign.yml/dispatches', - data=body, method='POST', headers={ - 'Authorization': 'Bearer ' + os.environ['GH_TOKEN'], - 'Accept': 'application/vnd.github+json', - 'Content-Type': 'application/json', - 'X-GitHub-Api-Version': '2022-11-28', - 'User-Agent': 'vectorcraft-nightly-dispatch' - }) - class NoRedirect(urllib.request.HTTPRedirectHandler): - def redirect_request(self, req, fp, code, msg, headers, newurl): - raise RuntimeError('dispatch redirects are forbidden') + data=body, method='POST', headers=dict(headers, **{'Content-Type': 'application/json'})) # One bounded request, no retry: duplicate transport is not publication authority. - with urllib.request.build_opener(NoRedirect()).open(request, timeout=20) as response: + with opener.open(request, timeout=20) as response: require(response.status == 204, 'dispatch was not accepted') print('Dispatched producer run/attempt to the release-ref validator; not a signing result.') diff --git a/.github/workflows/sonarcloud.yml b/.github/workflows/sonarcloud.yml index 98e9c1d00a..312ab1cbda 100644 --- a/.github/workflows/sonarcloud.yml +++ b/.github/workflows/sonarcloud.yml @@ -1,8 +1,12 @@ name: SonarCloud +# Main is analyzed once a day, at the commit the nightly builds: Stage 2 admits a nightly only on +# that commit's own analysis, and nightly-dispatch.yml waits for it before dispatching the signer. on: workflow_dispatch: - push: + workflow_run: + workflows: [VectorCraft unsigned nightly] + types: [requested] branches: [main] pull_request: types: [opened, synchronize, reopened] @@ -12,11 +16,35 @@ permissions: concurrency: group: ${{ github.ref == 'refs/heads/main' && format('sonarcloud-main-{0}', github.sha) || format('sonarcloud-{0}', github.ref) }} - # A push to main is the run that publishes coverage; superseded runs there would never finish. + # A main run is the analysis a nightly waits for; superseded runs there would never finish. cancel-in-progress: ${{ github.ref != 'refs/heads/main' }} jobs: + nightly-commit: + name: Nightly commit is main's head + # A workflow_run checks out and analyzes main's head, so main must not have moved since the + # nightly started. + if: github.event_name == 'workflow_run' + runs-on: ubuntu-latest + timeout-minutes: 2 + steps: + - name: Harden runner + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit + - name: Require main's head to be the nightly's commit + env: + NIGHTLY_SHA: ${{ github.event.workflow_run.head_sha }} + RUN_SHA: ${{ github.sha }} + run: | + if [ "$NIGHTLY_SHA" != "$RUN_SHA" ]; then + echo "::error::main moved from $NIGHTLY_SHA to $RUN_SHA after the nightly started; this run would not analyze the nightly's commit" + exit 1 + fi + sonarcloud: + needs: nightly-commit + if: ${{ !cancelled() && contains(fromJSON('["success","skipped"]'), needs.nightly-commit.result) }} # Tracked at @main so org-wide CI improvements propagate without PR churn. # The reusable workflow defaults build-jobs to 2 so a cold instrumented # archive stays within hosted-runner memory (craft-common-actions#333). diff --git a/docs/nightly-release-preparation.md b/docs/nightly-release-preparation.md index 29ca838f1d..1074e90299 100644 --- a/docs/nightly-release-preparation.md +++ b/docs/nightly-release-preparation.md @@ -79,7 +79,7 @@ Read on 2026-11-24; re-read anything that may have moved before `nightly-signer` | `max_age_seconds`, `max_artifact_bytes` | `86400`, `2147483648` | Go-live checklist | | `platforms` | three rows | Learning Machines stable identities (Windows Authenticode publisher subject, Linux OpenPGP fingerprint, Apple Developer ID team `DJ6XS33FX8`) | | `candidate_policy.required_workflows` | CI (`ci.yml`, workflow `380135806`), 9 jobs | Workflow list API; jobs that succeeded on recent main push runs | -| `candidate_policy.sonar` | `storytold` / `storytold_vectorcraft`, app `12526` | `sonar-project.properties`; the SonarCloud check on main commits | +| `candidate_policy.sonar` | `storytold` / `storytold_vectorcraft`, app `12526` | `sonar-project.properties`; the SonarCloud check on the nightly's commit | The signer reads the policy from `nightly-signer`, so a candidate whose CI built the tests once (`build`, `lint` and `test 1/5` to `test 5/5`) is admitted only after `nightly-signer` advances to @@ -97,9 +97,12 @@ a main commit with this policy. Candidates whose CI ran six shards (`cache warm` from stable, cancellation is off and `queue: max` must be hosted-qualified. The caller itself passes no credentials; only the shared callee's sign jobs bind the `release` environment, which must admit `nightly-signer` alongside `release` before the first dispatch. -- `.github/workflows/nightly-dispatch.yml`: transport only, never authorization. It is literally - off (`false &&`) and forwards only a first-attempt scheduled producer to `nightly-sign.yml` on - `nightly-signer`. No schedule is registered until activation is reviewed. +- `.github/workflows/nightly-dispatch.yml`: transport only, never authorization. It forwards only + a first-attempt scheduled producer to `nightly-sign.yml` on `nightly-signer`, after the + SonarCloud check on the producer's commit has completed. +- `.github/workflows/sonarcloud.yml`: analyzes main only at the commit a nightly builds. It starts + when the producer starts and fails when main has moved past the producer's commit. Pull requests + are analyzed on every push as before. - Shared reusable entrypoints are `nightly-unsigned.yml` and `nightly-release.yml` in `storytold/craft-common-actions`. Both must resolve to a **real reviewed public immutable commit**; the defining workflow SHA and tooling input must match. @@ -117,8 +120,9 @@ a main commit with this policy. Candidates whose CI ran six shards (`cache warm` - A trust-closure scan reads every workflow: nothing binds an `environment`, only `nightly-sign.yml` calls `nightly-release.yml` (at a full SHA), and the only caller of the shared stable `release.yml` is `release.yml`. -- `nightly-dispatch.yml` keeps a literal-off guard, a `workflow_run`-only trigger and a - `refs/heads/nightly-signer` request. +- `nightly-dispatch.yml` keeps its exact context guard, a `workflow_run`-only trigger and a + `refs/heads/nightly-signer` request, and sends that request only after the SonarCloud check on + the producer's commit has completed. ## The app side of a Nightly build diff --git a/packaging/nightly-release-tests.py b/packaging/nightly-release-tests.py index 2729b40282..ef1003f46e 100755 --- a/packaging/nightly-release-tests.py +++ b/packaging/nightly-release-tests.py @@ -2,10 +2,15 @@ """Local regression checks for VectorCraft nightly workflow and signing-policy contracts.""" import copy from decimal import Decimal +import io import json +import os from pathlib import Path import re +import tempfile +import textwrap import unittest +from unittest import mock ROOT = Path(__file__).resolve().parents[1] INSTALLED_POLICY = ROOT / ".github/nightly-signing-policy.json" @@ -907,5 +912,92 @@ class NightlyDispatchTransport(unittest.TestCase): self.assertIn("repos/storytold/" + APP_NAME + "/actions/workflows/nightly-sign.yml/dispatches", self.source) self.assertNotIn("'ref': 'release'", self.source) + +SONAR_SOURCE = "c" * 40 + + +def dispatch_script(): + """The dispatch job's inline Python, as the runner's `shell: python` step receives it.""" + source = (ROOT / ".github/workflows/nightly-dispatch.yml").read_text() + block = source.split(" run: |\n", 1)[1] + return textwrap.dedent(block) + + +class FakeGitHub: + """Answers the dispatch script's API reads from scripted poll results and records every request.""" + + def __init__(self, polls, run=None): + self.polls = list(polls) + self.run = run + self.requests = [] + self.now = 0.0 + + def open(self, request, timeout): + self.requests.append((request.get_method(), request.full_url)) + if request.get_method() == "POST": + payload = b"" + status = 204 + elif "/check-runs?" in request.full_url: + done = self.polls.pop(0) if self.polls else False + rows = [{"head_sha": SONAR_SOURCE, "status": "completed" if done else "in_progress"}] + payload, status = json.dumps({"check_runs": rows}).encode(), 200 + else: + runs = [self.run] if self.run else [] + payload, status = json.dumps({"workflow_runs": runs}).encode(), 200 + response = io.BytesIO(payload) + response.status = status + return response + + def sleep(self, seconds): + self.now += seconds + + +def run_dispatch(github): + producer = {"head_repository": {"full_name": "storytold/vectorcraft"}, "path": ".github/workflows/nightly.yml", + "head_branch": "main", "status": "completed", "conclusion": "success", "event": "schedule", + "id": 7, "run_attempt": 1, "head_sha": SONAR_SOURCE} + event = {"action": "completed", "repository": {"full_name": "storytold/vectorcraft"}, "workflow_run": producer} + with tempfile.TemporaryDirectory() as folder: + path = Path(folder) / "event.json" + path.write_text(json.dumps(event)) + env = {"GITHUB_REPOSITORY": "storytold/vectorcraft", "GITHUB_EVENT_NAME": "workflow_run", + "GITHUB_EVENT_PATH": str(path), "GH_TOKEN": "token"} + with mock.patch.dict(os.environ, env), \ + mock.patch("urllib.request.build_opener", return_value=github), \ + mock.patch("time.monotonic", side_effect=lambda: github.now), \ + mock.patch("time.sleep", side_effect=github.sleep), \ + mock.patch("builtins.print"): + exec(compile(dispatch_script(), "nightly-dispatch.yml", "exec"), {}) + + +class NightlyDispatchWaitsForSonar(unittest.TestCase): + """The signer is dispatched only after the producer commit's SonarCloud check completes.""" + + def posts(self, github): + return [url for method, url in github.requests if method == "POST"] + + def test_dispatch_waits_for_the_completed_check_of_the_producer_commit(self): + github = FakeGitHub([False, False, True]) + run_dispatch(github) + checks = [url for method, url in github.requests if "/check-runs?" in url] + self.assertEqual(len(checks), 3) + self.assertTrue(all("/commits/" + SONAR_SOURCE + "/" in url and "app_id=12526" in url for url in checks)) + self.assertEqual(len(self.posts(github)), 1) + self.assertEqual(github.requests[-1][0], "POST", "the dispatch comes after the last check read") + + def test_a_sonar_run_that_ended_without_a_check_stops_the_dispatch(self): + github = FakeGitHub([], run={"id": 9, "status": "completed", "conclusion": "failure"}) + with self.assertRaisesRegex(RuntimeError, "ended without an analysis check"): + run_dispatch(github) + self.assertEqual(self.posts(github), []) + self.assertLessEqual(github.now, 21 * 60, "a finished run does not wait for the whole deadline") + + def test_no_analysis_by_the_deadline_stops_the_dispatch(self): + github = FakeGitHub([]) + with self.assertRaisesRegex(RuntimeError, "in time"): + run_dispatch(github) + self.assertEqual(self.posts(github), []) + + if __name__ == "__main__": unittest.main(verbosity=2)