diff --git a/.github/nightly-linux-signing-key.asc b/.github/nightly-linux-signing-key.asc new file mode 100644 index 0000000000..a1c1f31e8d --- /dev/null +++ b/.github/nightly-linux-signing-key.asc @@ -0,0 +1,16 @@ +-----BEGIN PGP PUBLIC KEY BLOCK----- + +mDMEaulK1xYJKwYBBAHaRw8BAQdAqHJeDCjY6Hx5FTn/hW+aqu6V394ubLk0Zj3C +bftDwFm0IkFydENyYWZ0IExpbnV4IFJlbGVhc2UgU2lnbmluZyBLZXmIkwQTFgoA +OxYhBCt2dBtBSq1s0z5jEhOgBcC518PtBQJq6UrXAhsBBQsJCAcCAiICBhUKCQgL +AgQWAgMBAh4HAheAAAoJEBOgBcC518PtGeUA/RjvULBTLlccc+2wtJkfjSnCV+cf +PUMEGmW7XkZWkk51AP9w2A/WLv+79nREWEpZzI8LGK5EjrNazP+sY0l7j5rFCLgz +BGrpStcWCSsGAQQB2kcPAQEHQPl7XkQ1gWsvSPf/T9b4m/UHcjJjBpSOtpYlWR56 +er5RiO8EGBYKACAWIQQrdnQbQUqtbNM+YxIToAXAudfD7QUCaulK1wIbAgCBCRAT +oAXAudfD7XYgBBkWCgAdFiEEVo3B9o+Prsx5fzx7AG2va7DvM04FAmrpStcACgkQ +AG2va7DvM07taQEA4d2VFkKRIP0g9TrE86KpnuXPap+LKqe0tfIxpdf9YxIA/0Wo +9H/iG8nH++nxC087p3HE0S+0UovxqkhXJLSr8B4JDOoA/iLRpqTdYmk6fVXMyPJo +SkOVuwZIGS6VgBdSQP0e2P2YAP41L5OoSvwdQIG3/uNrM+ieqpYeM597/hCLFs5A +ga/qCA== +=3wGQ +-----END PGP PUBLIC KEY BLOCK----- diff --git a/.github/nightly-signing-policy.json b/.github/nightly-signing-policy.json index f59894c462..fd5a203059 100644 --- a/.github/nightly-signing-policy.json +++ b/.github/nightly-signing-policy.json @@ -2,13 +2,13 @@ "schema": "craft-nightly-release-policy/v3", "repository": "storytold/vectorcraft", "repository_id": 1398097510, - "producer_workflow_id": null, + "producer_workflow_id": 430275079, "producer_workflow_path": ".github/workflows/nightly.yml", - "producer_tooling_revision": "605d58766e8f536564da8fc81d3676ac86816dea", - "producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@605d58766e8f536564da8fc81d3676ac86816dea", + "producer_tooling_revision": "88148a57ef09ef407d73c0f385e04cc7f4c2720a", + "producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@88148a57ef09ef407d73c0f385e04cc7f4c2720a", "signer_workflow_path": ".github/workflows/nightly-sign.yml", - "signer_tooling_revision": "605d58766e8f536564da8fc81d3676ac86816dea", - "release_branch": "release", + "signer_tooling_revision": "88148a57ef09ef407d73c0f385e04cc7f4c2720a", + "release_branch": "nightly-signer", "manual_actors": [ "bflatastic", "dylanmtaylor", diff --git a/.github/workflows/nightly-dispatch.yml b/.github/workflows/nightly-dispatch.yml new file mode 100644 index 0000000000..dd4a4a02da --- /dev/null +++ b/.github/workflows/nightly-dispatch.yml @@ -0,0 +1,72 @@ +name: Dispatch release-ref nightly + +# Transport only, never authorization. No checkout, payload parsing or release environment. +on: + workflow_run: + workflows: [VectorCraft unsigned nightly] + types: [completed] + branches: [main] + +permissions: {} + +jobs: + dispatch: + # SOURCE PREPARATION: literal off until immutable shared tooling and policy qualification. + if: >- + false && github.repository == 'storytold/vectorcraft' && + github.event_name == 'workflow_run' + runs-on: ubuntu-latest + timeout-minutes: 5 + permissions: + actions: write + steps: + - name: Dispatch only the exact completed producer run and attempt + shell: python + env: + GH_TOKEN: ${{ github.token }} + run: | + import json + import os + import urllib.request + + def require(value, message): + if not value: + raise RuntimeError(message) + + # These filters reduce noise; the protected signer-branch validator repeats admission + # against authenticated API metadata and required attestation/quality evidence. + require(os.environ.get('GITHUB_REPOSITORY') == 'storytold/vectorcraft', 'wrong repository') + require(os.environ.get('GITHUB_EVENT_NAME') == 'workflow_run', 'wrong event') + with open(os.environ['GITHUB_EVENT_PATH'], encoding='utf-8') as stream: + event = json.load(stream) + require(event.get('action') == 'completed', 'producer is not complete') + require(event.get('repository', {}).get('full_name') == 'storytold/vectorcraft', 'wrong event repository') + producer = event.get('workflow_run', {}) + require(producer.get('head_repository', {}).get('full_name') == 'storytold/vectorcraft', 'foreign producer') + require(producer.get('path') == '.github/workflows/nightly.yml', 'wrong producer path') + require(producer.get('head_branch') == 'main', 'wrong producer branch') + require(producer.get('status') == 'completed' and producer.get('conclusion') == 'success', 'producer did not succeed') + # First scheduled attempt only; reviewed manual/re-run authority belongs to release policy. + require(producer.get('event') == 'schedule', 'not an automatic scheduled producer') + 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') + 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') + # One bounded request, no retry: duplicate transport is not publication authority. + with urllib.request.build_opener(NoRedirect()).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/nightly-sign.yml b/.github/workflows/nightly-sign.yml index 38cb6b24a9..6f651d2372 100644 --- a/.github/workflows/nightly-sign.yml +++ b/.github/workflows/nightly-sign.yml @@ -1,7 +1,8 @@ name: VectorCraft release-ref nightly signer -# Enabled for supervised manual dispatch on release. Main/release contents must match. -# A reusable callee does not change context; this must be a real top-level release dispatch. +# Enabled for supervised manual dispatch on the dedicated nightly-signer branch, which only ever +# fast-forwards to reviewed main commits (never the stable release branch). +# A reusable callee does not change context; this must be a real top-level signer-branch dispatch. on: workflow_dispatch: inputs: @@ -22,21 +23,23 @@ concurrency: jobs: release: - # Actual context guards: official repository, manual dispatch, real release branch. + # Actual context guards: official repository, manual dispatch, real nightly-signer branch. if: >- github.repository == 'storytold/vectorcraft' && github.event_name == 'workflow_dispatch' && - github.ref == 'refs/heads/release' && github.ref_type == 'branch' + github.ref == 'refs/heads/nightly-signer' && github.ref_type == 'branch' permissions: contents: write actions: read checks: read attestations: write id-token: write - uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@605d58766e8f536564da8fc81d3676ac86816dea + uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@88148a57ef09ef407d73c0f385e04cc7f4c2720a with: - tooling-revision: 605d58766e8f536564da8fc81d3676ac86816dea + tooling-revision: 88148a57ef09ef407d73c0f385e04cc7f4c2720a + app-name: vectorcraft producer_run_id: ${{ inputs.producer_run_id }} producer_run_attempt: ${{ inputs.producer_run_attempt }} # No secrets: inherit or raw platform values in this caller. Only the isolated native - # callee job may bind the existing release environment and export keys in its signing step. + # callee job may bind the existing release environment (which trusts release and + # nightly-signer) and export keys in its signing step. diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index 1139f67f9b..cf64e9b055 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -22,13 +22,12 @@ jobs: actions: read attestations: write id-token: write - uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@605d58766e8f536564da8fc81d3676ac86816dea + uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@88148a57ef09ef407d73c0f385e04cc7f4c2720a with: - tooling-revision: 605d58766e8f536564da8fc81d3676ac86816dea + tooling-revision: 88148a57ef09ef407d73c0f385e04cc7f4c2720a app-name: vectorcraft manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]' craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 # One producer run builds every listed platform for one all-or-nothing release. The pin is the - # craft-common-actions main commit that merged #339 (bounded lineage compares), on top of the - # Linux/macOS signer (#342). + # craft-common-actions main commit that merged the signer-branch change (#364, after #363). platforms: '["windows-x86_64","linux-x86_64","macos-aarch64"]' diff --git a/docs/nightly-release-preparation.md b/docs/nightly-release-preparation.md index fd323a5928..36cc4620e7 100644 --- a/docs/nightly-release-preparation.md +++ b/docs/nightly-release-preparation.md @@ -1,11 +1,12 @@ # Windows, Linux and macOS release-ref nightly: supervised manual go-live -**Enabled for supervised manual runs, not yet qualified.** The producer (`nightly.yml`, main) and the -signer (`nightly-sign.yml`, release) keep only their exact context guards and run when one of the reviewed -manual actors dispatches them. There is no schedule yet. The installed policy -[`.github/nightly-signing-policy.json`](../.github/nightly-signing-policy.json) is the v3 -policy. Once `nightly.yml` reaches `main`, populate `producer_workflow_id` with its registration ID -before promoting the policy to `release`: +**Enabled for supervised manual runs, not yet qualified.** The producer (`nightly.yml`, main) and +the signer (`nightly-sign.yml`, on the dedicated `nightly-signer` branch) keep only their exact +context guards and run when one of the reviewed manual actors dispatches them. +`nightly-dispatch.yml` stays literally off: it only forwards scheduled producers. There is no +schedule. The installed policy +[`.github/nightly-signing-policy.json`](../.github/nightly-signing-policy.json) is the v3 policy. +Its `producer_workflow_id` is the registration of `nightly.yml` on main, read with: ```bash gh api repos/storytold/vectorcraft/actions/workflows/nightly.yml --jq .id @@ -14,38 +15,61 @@ gh api repos/storytold/vectorcraft/actions/workflows/nightly.yml --jq .id The callers pass no platform secrets. The unsigned reusable caller's maximum OIDC/attestation permissions are for its isolated attester; its compiler narrows to contents and Actions read only, with no OIDC, attestation write, release environment or platform signing secrets. -Shared tooling is pinned to `605d58766e8f536564da8fc81d3676ac86816dea`, the craft-common-actions -main commit that merged [#339](https://github.com/storytold/craft-common-actions/pull/339) (bounded -lineage compares and an issue reread at the end of candidate admission) on top of -[#342](https://github.com/storytold/craft-common-actions/pull/342) (policy v3, the `platforms` input -and the Linux and macOS legs). Both callers name it in `uses` and `tooling-revision`. A pin is reviewed -source availability, not provider, queue, native signing or crypto qualification. -Existing stable workflows are unchanged. +Shared tooling is pinned to `88148a57ef09ef407d73c0f385e04cc7f4c2720a`, the craft-common-actions +main commit that merged [#364](https://github.com/storytold/craft-common-actions/pull/364), which +lets the signer run on the policy's signer branch (`release` or `nightly-signer`). It includes +[#363](https://github.com/storytold/craft-common-actions/pull/363) (the multi-app pipeline, which +makes the signer's `app-name` input required), #339 (`605d5876`) and #342 (`a4f6fd51`). Both callers +name it in `uses` and `tooling-revision`. A pin is reviewed source availability, not provider, +queue, native signing or crypto qualification. Existing stable workflows are unchanged. **First runs.** The first runs are manual dispatches in this order: `nightly.yml` on main (only a -listed manual actor passes the producer's plan step), then `nightly-sign.yml` on `release` with that -producer run ID and attempt, by a listed manual actor. +listed manual actor passes the producer's plan step), then `nightly-sign.yml` on `nightly-signer` +with that producer run ID and attempt, by a listed manual actor. `nightly-dispatch.yml` only matters +once a schedule is approved. + +**Signer branch.** The signer runs on `refs/heads/nightly-signer`, not on the stable `release` +branch, so nightly signer files never need a stable release sync. The policy's `release_branch` +names it, the signer's guard requires it and the dispatcher targets it. The branch only +fast-forwards to reviewed main commits, through the settings script's `advance` (no queued signer +run, a trust-closure scan, then the full diff of `.github/` and `packaging/`), and the existing +`release` environment trusts it alongside `release`. Its trust closure is all of `.github/` and +`packaging/`, including `packaging/env.sh`, which `packaging/macos/import-cert.sh` sources with +the Apple keys. On that branch only the pinned `nightly-sign.yml` caller may reach an environment: +no app workflow binds one, nothing else calls `nightly-release.yml`, and the only caller of the +shared stable `release.yml` is `release.yml`, whose callee must carry the stable-only environment +guard. The contract tests check the in-repo part on every main PR; the settings scan also resolves +the callee. Stable releases still come only from `refs/heads/release`. History does not carry over +a switch between `release` and `nightly-signer`, so the switch happens before the first +publication. + +**Registry admission.** The signer requires the protected policy's `platforms` map to equal the +run app's admitted targets in craft-common-actions' `nightly-apps.json`, and it refuses rather +than sign a subset. VectorCraft's row admits `linux-x86_64`; the matching `windows-x86_64` and +`macos-aarch64` targets and entrypoints are a craft-common-actions follow-up, and the first +signer run stops at admission until they merge. **Manual actors.** `bflatastic`, `dylanmtaylor`, `echelon`, `FredApps` and `skylartaylor`, in the producer's `manual-actors` and the policy's `manual_actors`. The list mirrors the release-managers -team (id 19837241), leaving out `echelon-robot`; update it by PR in both places when the team changes. +team (id 19837241), leaving out `echelon-robot`; update it by PR in both places when the team +changes. **Platform rows.** The producer caller lists `platforms: '["windows-x86_64","linux-x86_64","macos-aarch64"]'` on its single job: one producer run builds every listed platform for one all-or-nothing release (one failed or -skipped platform stops that night's release, Windows included), and the release-ref signer admits +skipped platform stops that night's release, Windows included), and the signer admits platforms only from the protected policy, so there is no separate Linux or macOS caller job and the signer caller has no platform input. ## Installed policy values and their sources -Read on 2026-11-24; re-read anything that may have moved (and populate `producer_workflow_id` after `nightly.yml` lands on `main`) before the policy is promoted to `release`. +Read on 2026-11-24; re-read anything that may have moved before `nightly-signer` is advanced to it. | Field | Value | Source | |---|---|---| | `repository_id` | `1398097510` | `gh api repos/storytold/vectorcraft --jq .id` | -| `producer_workflow_id` | `null` (pending first registration on `main`) | Read via `gh api repos/storytold/vectorcraft/actions/workflows/nightly.yml --jq .id` once `nightly.yml` is on `main` | -| `producer_tooling_revision`, `signer_tooling_revision`, `producer_workflow_ref` | `605d5876…` (craft-common-actions #339) | The callers' pin | +| `producer_workflow_id` | `430275079` | `gh api repos/storytold/vectorcraft/actions/workflows/nightly.yml --jq .id` | +| `producer_tooling_revision`, `signer_tooling_revision`, `producer_workflow_ref` | `88148a5…` (craft-common-actions #364) | The callers' pin | | `manual_actors` / `automatic_signer_actors` | the five release managers / `[]` | release-managers team (id 19837241) members who can push; equals the producer caller's `manual-actors` | | `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`) | @@ -57,11 +81,15 @@ Read on 2026-11-24; re-read anything that may have moved (and populate `producer - `.github/workflows/nightly.yml`: default-main registration of the unsigned producer, named `VectorCraft unsigned nightly`, enabled for manual dispatch by `manual-actors`; no signing secrets may be passed or inherited. -- `.github/workflows/nightly-sign.yml`: top-level release registration, enabled for manual dispatch, - and identical on main and release after reviewed promotion. It rejects wrong repository/event/actual branch, +- `.github/workflows/nightly-sign.yml`: top-level registration on `nightly-signer`, enabled for manual dispatch, + and only ever fast-forwards to reviewed main commits. It rejects wrong repository/event/actual branch, including same-name tags. Its constant whole-run concurrency (`vectorcraft-nightly-release`) is distinct 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. + credentials; only the shared callee's sign jobs bind the `release` environment, which trusts `release` and + `nightly-signer`. +- `.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. - 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. @@ -74,6 +102,13 @@ Read on 2026-11-24; re-read anything that may have moved (and populate `producer - Both callers pin the same immutable `craft-common-actions` commit in `uses` and `tooling-revision`. - No nightly schedule is registered, no cache actions or secrets appear in the app callers, and `nightly-sign.yml` retains its literal root `concurrency` block (`group: vectorcraft-nightly-release`, `cancel-in-progress: false`, `queue: max`). - Policy v3 schema, platform rows, bounds, required main-push CI workflow, and SonarCloud project identity match `sonar-project.properties`. +- The signer guards `refs/heads/nightly-signer`, passes `app-name: vectorcraft`, and the policy's + `release_branch` names it. +- 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. ## The app side of a Nightly build @@ -145,6 +180,7 @@ The pinned candidate validator requires every entry in `candidate_policy.sonar.i from a reviewed `accepted_conditions` row, and it requires the gate condition set to equal `accepted_conditions` plus `required_conditions`. The installed policy lists `VULNERABILITY` with no accepted condition, so it fails that contract before SonarCloud is read. Correct the policy in this -app's activation review with Skylar, together with the live gate conditions, before the first run: -the callers cannot run before that review anyway, because their `producer_workflow_id` stays null -until `nightly.yml` is registered on `main` and the signer is promoted to `release`. +app's activation review with Skylar, together with the live gate conditions, before the first run. +`producer_workflow_id` is now populated and the signer runs on `nightly-signer`, so this policy +correction - with the registry's Windows and macOS targets - is what still stands between this tree +and a first signed nightly. diff --git a/docs/releasing.md b/docs/releasing.md index bfa3f4e21c..f6cb13e857 100644 --- a/docs/releasing.md +++ b/docs/releasing.md @@ -247,6 +247,12 @@ which only the `release` branch can use and which holds the signing secrets. The secrets. Every secret is optional: a missing one produces unsigned artifacts and a warning, never a failed build. +The supervised nightly signer does not sign from `release`: it runs on `refs/heads/nightly-signer`, +which only ever fast-forwards to reviewed main commits, and the `release` environment trusts both +branches. Everything that can reach it is the trust closure: all of `.github/` and `packaging/`, +including `packaging/env.sh`, which `packaging/macos/import-cert.sh` sources with the Apple keys. +Stable releases still come only from `refs/heads/release`. + | Secret | Used for | |---|---| | `APPLE_CERTIFICATE`, `APPLE_CERTIFICATE_PASSWORD`, `KEYCHAIN_PASSWORD` | the Developer ID certificate (base64 `.p12`), imported into a temporary keychain by `packaging/macos/import-cert.sh` | diff --git a/packaging/nightly-release-tests.py b/packaging/nightly-release-tests.py index c3c0b3e399..d09b2d0624 100755 --- a/packaging/nightly-release-tests.py +++ b/packaging/nightly-release-tests.py @@ -9,6 +9,9 @@ import unittest ROOT = Path(__file__).resolve().parents[1] INSTALLED_POLICY = ROOT / ".github/nightly-signing-policy.json" +APP_NAME = "vectorcraft" +PRODUCER_WORKFLOW_NAME = "VectorCraft unsigned nightly" + NIGHTLY_PLATFORMS = ("windows-x86_64", "linux-x86_64", "macos-aarch64") # Each platform's one trust field in policy v3, and the public stable identity it must name. NIGHTLY_TRUST = { @@ -262,7 +265,7 @@ class NightlyEnabledCallers(unittest.TestCase): "github.ref_type == 'branch' && (github.event_name == 'schedule' || " "github.event_name == 'workflow_dispatch')", "nightly-sign.yml": "github.repository == 'storytold/vectorcraft' && github.event_name == 'workflow_dispatch' && " - "github.ref == 'refs/heads/release' && github.ref_type == 'branch'", + "github.ref == 'refs/heads/nightly-signer' && github.ref_type == 'branch'", } def test_enabled_jobs_keep_exact_context_guards(self): @@ -334,7 +337,8 @@ class NightlyInstalledPolicy(unittest.TestCase): self.assertEqual(set(self.policy), expected) self.assertEqual(self.policy["schema"], "craft-nightly-release-policy/v3") self.assertEqual(self.policy["repository"], "storytold/vectorcraft") - self.assertEqual(self.policy["release_branch"], "release") + self.assertEqual(self.policy["release_branch"], SIGNER_BRANCH, + "the signer runs on its dedicated branch") self.assertIs(type(self.policy["repository_id"]), int) self.assertGreater(self.policy["repository_id"], 0) producer_id = self.policy["producer_workflow_id"] @@ -426,5 +430,294 @@ class NightlyInstalledPolicy(unittest.TestCase): self.assertRegex(item["hash"], r"^[0-9a-f]{32}$") +SIGNER_BRANCH = "nightly-signer" +SHARED = "storytold/craft-common-actions/.github/workflows/" +# App workflows reviewed to call the shared stable release.yml. That callee must carry the +# stable-only environment guard (dry runs and non-release refs bind no environment); the +# nightly-signer settings scan checks the resolved callee before creating or advancing the branch. +REVIEWED_STABLE_RELEASE_CALLERS = {"release.yml"} + + +def app_workflows(): + return {path.name: path.read_text() for path in sorted((ROOT / ".github/workflows").glob("*.y*ml"))} + + +WORKFLOW_KEY = re.compile(r'''("(?:[^"\\]|\\.)*"|'(?:[^']|'')*'|[^\s'"#{}\[\],:&*!|>%@`?-][^:#,{}]*?|-[^\s:#][^:#,{}]*?)\s*:(?:\s+(.*))?$''') + + +def _workflow_key(text): + if text.startswith('"'): + return None if "\\" in text else text[1:-1] + if text.startswith("'"): + return text[1:-1].replace("''", "'") + return text + + +def _workflow_value(text): + """A one-line scalar value without its comment and quotes; None when escaped or unterminated.""" + text = text.strip() + if text.startswith('"'): + quoted = re.match(r'"((?:[^"\\]|\\.)*)"\s*(?:#.*)?$', text) + return None if quoted is None or "\\" in quoted.group(1) else quoted.group(1) + if text.startswith("'"): + quoted = re.match(r"'((?:[^']|'')*)'\s*(?:#.*)?$", text) + return None if quoted is None else quoted.group(1).replace("''", "'") + return re.split(r"\s+#", text, maxsplit=1)[0].strip() + + +def _strip_comment(text): + """(text without its comment, unterminated) using a quote-aware scan. + + As in YAML, a quote opens a quoted scalar only where a scalar starts (line start or after + `:`, `-`, `,`, `{` or `[`), and a `#` starts a comment only outside quotes, at the start or + after whitespace. + """ + quote, index = None, 0 + while index < len(text): + char = text[index] + if quote == '"': + if char == "\\": + index += 2 + continue + if char == '"': + quote = None + elif quote == "'": + if char == "'": + if text[index + 1:index + 2] == "'": + index += 2 + continue + quote = None + elif char in "\"'" and text[:index].rstrip()[-1:] in ("", ":", "-", ",", "{", "["): + quote = char + elif char == "#" and (index == 0 or text[index - 1] in " \t"): + return text[:index].rstrip(), False + index += 1 + return text.rstrip(), quote is not None + + +FLOW_QUOTED = re.compile(r"\"(?:[^\"\\]|\\.)*\"|'(?:[^']|'')*'") +FLOW_FORBIDDEN_KEYS = {"environment", "uses"} + + +def workflow_entries(source): + """Every mapping entry in a workflow, plus the YAML forms this reader refuses. + + A narrow reader, not a YAML parser (none ships with the runner's Python). Each entry is + (line, key, value, multiline): plain, single- and double-quoted keys and one-line values in + block and simple one-line flow mappings. Block scalar bodies are skipped, and an entry whose + value is a block scalar or continues on the next lines is marked multiline. It refuses whatever + could hide a key from it: escaped double-quoted keys, explicit `?` keys, merge keys, anchors, + aliases, tags, tab indentation and nested or multi-line flow. + """ + lines = source.splitlines() + entries, refused, block = [], [], None + + def continues(index, indent): + for follow in lines[index + 1:]: + stripped = follow.strip() + if not stripped or stripped.startswith("#"): + continue + deeper = len(follow) - len(follow.lstrip(" ")) > indent + return deeper and not stripped.startswith("- ") and WORKFLOW_KEY.match(stripped) is None + return False + + for index, raw in enumerate(lines): + number = index + 1 + stripped = raw.strip() + indent = len(raw) - len(raw.lstrip(" ")) + if block is not None: + if not stripped or indent > block: + continue + block = None + if not stripped or stripped.startswith("#"): + continue + if "\t" in raw[:indent + 1]: + refused.append(f"line {number}: tab indentation"); continue + body, unterminated = _strip_comment(stripped) + if unterminated: + refused.append(f"line {number}: unterminated or multi-line quoted scalar"); continue + if not body: + continue + while body.startswith("- "): + body = body[2:].lstrip() + if body == "?" or body.startswith("? "): + refused.append(f"line {number}: explicit key"); continue + match = WORKFLOW_KEY.match(body) + value = body + if match is not None: + key, value = _workflow_key(match.group(1)), match.group(2) or "" + if key is None: + refused.append(f"line {number}: escaped double-quoted key"); continue + if key == "<<": + refused.append(f"line {number}: merge key"); continue + plain = re.sub(r"\$\{\{.*?\}\}", "", value).strip() + bare = re.sub(r"\"(?:[^\"\\]|\\.)*\"|'(?:[^']|'')*'", "''", plain) + if re.match(r"[&*!]", plain): + refused.append(f"line {number}: anchor, alias or tag") + is_block = re.fullmatch(r"[|>][0-9+-]*", plain) is not None + if match is not None: + entries.append((number, key, _workflow_value(value), + is_block or ((value == "" or not is_block) and continues(index, indent)))) + if "{" in bare and bare != "{}": + flow = re.fullmatch(r"\{([^{}\[\]]*)\}", FLOW_QUOTED.sub("''", value.strip())) + if any(set(scalar[1:-1]) & set("#{}[],") for scalar in FLOW_QUOTED.findall(value)): + refused.append(f"line {number}: flow mapping quoted scalar with # or flow punctuation") + elif flow is None: + refused.append(f"line {number}: nested or multi-line flow mapping") + elif not re.fullmatch(r"\{([^{}\[\]]*)\}", value.strip()): + refused.append(f"line {number}: nested or multi-line flow mapping") + else: + for item in flow.group(1).split(","): + entry = WORKFLOW_KEY.match(item.strip()) + key = _workflow_key(entry.group(1)) if entry else None + if key is None: + refused.append(f"line {number}: unreadable flow mapping entry") + elif key in FLOW_FORBIDDEN_KEYS: + refused.append(f"line {number}: {key} in a flow mapping (must be block style)") + else: + entries.append((number, key, _workflow_value(entry.group(2) or ""), False)) + if match is not None and is_block: + block = indent + return entries, refused + + +def workflow_keys(source): + """(line, key) for every mapping entry, plus the refused YAML forms.""" + entries, refused = workflow_entries(source) + return [(number, key) for number, key, _, _ in entries], refused + + +SHARED_CALLEE = re.compile(r"storytold/craft-common-actions/\.github/workflows/([\w.-]+\.ya?ml)@(\S+)", re.IGNORECASE) +INSPECTED_KEYS = {"environment", "uses"} + + +def trust_closure_problems(workflows): + """The nightly-signer trust-closure scan over app workflow sources; empty when the tree is safe. + + Every key it inspects comes from workflow_entries(), never a regex over the raw text. + """ + problems, stable_callers, signer_calls = [], set(), 0 + for name, source in workflows.items(): + entries, refused = workflow_entries(source) + problems.extend(name + " uses YAML the scan cannot read (" + reason + ")" for reason in refused) + for number, key, value, multiline in entries: + if key not in INSPECTED_KEYS: + continue + if key == "environment": + problems.append(f"{name} binds an environment directly (line {number})") + continue + if value is None or multiline: + problems.append(f"{name} has a uses value the scan cannot read (line {number})") + continue + callee = SHARED_CALLEE.fullmatch(value) + if callee is None: + if re.search(r"craft-common-actions", value, re.IGNORECASE) and re.search(r"workflows/(nightly-)?release\.ya?ml", value, re.IGNORECASE): + problems.append(f"{name} has an unrecognised shared release caller (line {number})") + continue + workflow, ref = callee.group(1), callee.group(2) + if workflow.lower() in ("nightly-release.yml", "nightly-release.yaml"): + if name == "nightly-sign.yml": + signer_calls += 1 + if name != "nightly-sign.yml" or not re.fullmatch(r"[0-9a-f]{40}", ref): + problems.append(name + " calls nightly-release.yml@" + ref) + if workflow.lower() in ("release.yml", "release.yaml"): + stable_callers.add(name) + if ref != "main" and not re.fullmatch(r"[0-9a-f]{40}", ref): + problems.append(name + " calls release.yml@" + ref + "; use @main or a reviewed full SHA") + if stable_callers != REVIEWED_STABLE_RELEASE_CALLERS: + problems.append("shared release.yml callers are " + ", ".join(sorted(stable_callers))) + if signer_calls != 1: + problems.append("nightly-sign.yml must call nightly-release.yml exactly once") + return problems + + +class NightlySignerBranchTrustClosure(unittest.TestCase): + """On refs/heads/nightly-signer, only the pinned signer caller may reach an environment.""" + + def test_trust_closure_scan_passes_on_this_tree(self): + self.assertEqual(trust_closure_problems(app_workflows()), []) + + def test_trust_closure_scan_refuses_each_route_into_an_environment(self): + tree = app_workflows() + bad = { + "a workflow binds an environment": {**tree, "extra.yml": "jobs:\n x:\n runs-on: ubuntu-latest\n environment: release\n"}, + "a double-quoted environment key": {**tree, "extra.yml": 'jobs:\n x:\n runs-on: ubuntu-latest\n "environment": release\n'}, + "a single-quoted environment key": {**tree, "extra.yml": "jobs:\n x:\n runs-on: ubuntu-latest\n 'environment' : release\n"}, + "an environment mapping": {**tree, "extra.yml": "jobs:\n x:\n runs-on: ubuntu-latest\n environment:\n name: release\n"}, + "an environment in a flow mapping": {**tree, "extra.yml": "jobs:\n x: {runs-on: ubuntu-latest, environment: release}\n"}, + "an escaped key": {**tree, "extra.yml": 'jobs:\n x:\n runs-on: ubuntu-latest\n "environ\\u006dent": release\n'}, + "a merge key": {**tree, "extra.yml": "base: &b\n runs-on: ubuntu-latest\njobs:\n x:\n <<: *b\n"}, + "an explicit key": {**tree, "extra.yml": "jobs:\n x:\n ? environment\n : release\n"}, + "a nested flow mapping": {**tree, "extra.yml": "jobs:\n x: {steps: [{run: a}]}\n"}, + "a double-quoted uses key copying the signer": {**tree, "extra.yml": 'jobs:\n x:\n "uses": ' + SHARED + "nightly-release.yml@" + "a" * 40 + "\n"}, + "a single-quoted uses key": {**tree, "extra.yml": "jobs:\n x:\n 'uses': " + SHARED + "nightly-release.yml@" + "a" * 40 + "\n"}, + "a quoted uses value": {**tree, "extra.yml": 'jobs:\n x:\n uses: "' + SHARED + "nightly-release.yml@" + "a" * 40 + '"\n'}, + "uses in a flow mapping": {**tree, "extra.yml": "jobs:\n x: {uses: " + SHARED + "nightly-release.yml@" + "a" * 40 + "}\n"}, + "a differently cased owner": {**tree, "extra.yml": "jobs:\n x:\n uses: Storytold/Craft-Common-Actions/.github/workflows/nightly-release.yml@" + "a" * 40 + "\n"}, + "a folded uses value": {**tree, "extra.yml": "jobs:\n x:\n uses: >-\n " + SHARED + "nightly-release.yml@" + "a" * 40 + "\n"}, + "a continued uses value": {**tree, "extra.yml": "jobs:\n x:\n uses: " + SHARED + "\n nightly-release.yml@" + "a" * 40 + "\n"}, + "a quoted second signer call": {**tree, "nightly-sign.yml": tree["nightly-sign.yml"] + " again:\n \"uses\": " + SHARED + "nightly-release.yml@" + "a" * 40 + "\n"}, + "a hash inside a quoted flow scalar": {**tree, "extra.yml": 'jobs:\n x: {name: "a} # b", runs-on: ubuntu-latest, environment: release, steps: []}\n'}, + "a single-quoted hash in a flow scalar": {**tree, "extra.yml": "jobs:\n x: {name: 'a # b', runs-on: ubuntu-latest}\n"}, + "a comma inside a quoted flow scalar": {**tree, "extra.yml": 'jobs:\n x: {name: "a, environment: release", runs-on: ubuntu-latest}\n'}, + "a bracket inside a quoted flow scalar": {**tree, "extra.yml": 'jobs:\n x: {name: "[a]", runs-on: ubuntu-latest}\n'}, + "an unterminated quote": {**tree, "extra.yml": 'jobs:\n x:\n name: "a\n b"\n runs-on: ubuntu-latest\n'}, + "environment in any flow mapping": {**tree, "extra.yml": "jobs:\n x:\n runs-on: ubuntu-latest\n with: {environment: release}\n"}, + "uses in any flow mapping": {**tree, "extra.yml": "jobs:\n x:\n steps:\n - {uses: actions/checkout@v4}\n"}, + "another caller of the signer": {**tree, "extra.yml": "jobs:\n x:\n uses: " + SHARED + "nightly-release.yml@" + "a" * 40 + "\n"}, + "a mutable signer pin": {**tree, "nightly-sign.yml": re.sub(r"nightly-release\.yml@[0-9a-f]{40}", "nightly-release.yml@main", tree["nightly-sign.yml"])}, + "a new stable release caller": {**tree, "extra.yml": "jobs:\n x:\n uses: " + SHARED + "release.yml@main\n"}, + "a stable caller on a branch or tag ref": {**tree, "release.yml": tree["release.yml"].replace(SHARED + "release.yml@main", SHARED + "release.yml@v1")}, + } + for label, workflows in bad.items(): + with self.subTest(case=label): + self.assertTrue(trust_closure_problems(workflows)) + + def test_signer_dispatch_guard_and_policy_name_the_same_branch(self): + sign = (ROOT / ".github/workflows/nightly-sign.yml").read_text() + (_, guard), = job_conditions(sign.split("\njobs:\n", 1)[1]) + self.assertIn("github.ref == 'refs/heads/" + SIGNER_BRANCH + "'", guard) + self.assertNotIn("refs/heads/release", sign, "the signer no longer runs on the stable branch") + self.assertEqual(re.findall(r"(?m)^ app-name: (\S+)$", sign), [APP_NAME], + "the shared signer needs the reviewed registry app") + dispatch = (ROOT / ".github/workflows/nightly-dispatch.yml").read_text() + self.assertEqual(re.findall(r"'ref': '([^']+)'", dispatch), ["refs/heads/" + SIGNER_BRANCH]) + self.assertEqual(json.loads(INSTALLED_POLICY.read_text())["release_branch"], SIGNER_BRANCH) + + +def dispatch_triggers(source): + """The dispatch workflow's own triggers, one per line, as a caller may register them.""" + events = source.split("\non:\n", 1)[1].split("\npermissions:", 1)[0] + return [line for line in events.splitlines() if line.startswith(" ") and not line.startswith(" ") + and line.strip() and not line.lstrip().startswith("#")] + + +class NightlyDispatchTransport(unittest.TestCase): + """The scheduled transport stays literally off and can only reach the signer branch.""" + + def setUp(self): + self.source = (ROOT / ".github/workflows/nightly-dispatch.yml").read_text() + + def test_every_dispatch_job_is_literal_off(self): + jobs = self.source.split("\njobs:\n", 1)[1] + headers = re.findall(r"(?m)^ (?![\s#])[^\n]+", jobs) + conditions = job_conditions(jobs) + self.assertTrue(headers) + self.assertEqual(len(conditions), len(headers), "every job needs a literal-off condition") + for _, expression in conditions: + self.assertTrue(literal_off(expression), "nightly activation requires reviewed test update") + + def test_only_a_completed_scheduled_producer_is_transported(self): + self.assertEqual(re.findall(r"(?m)^ workflows: (.+)$", self.source), + ["[" + PRODUCER_WORKFLOW_NAME + "]"]) + self.assertEqual(dispatch_triggers(self.source), [" workflow_run:"], + "the transport is not a second entry point") + self.assertNotIn("schedule:", self.source) + self.assertIn("producer.get('event') == 'schedule'", self.source) + + def test_the_request_names_the_signer_workflow_and_branch(self): + self.assertIn("repos/storytold/" + APP_NAME + "/actions/workflows/nightly-sign.yml/dispatches", self.source) + self.assertNotIn("'ref': 'release'", self.source) + if __name__ == "__main__": unittest.main(verbosity=2)