diff --git a/.github/nightly-signing-policy.json b/.github/nightly-signing-policy.json index 1a02a434ba..23471feb7b 100644 --- a/.github/nightly-signing-policy.json +++ b/.github/nightly-signing-policy.json @@ -4,11 +4,11 @@ "repository_id": 1398080271, "producer_workflow_id": 428462603, "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 index 17622f5060..1b95f58059 100644 --- a/.github/workflows/nightly-dispatch.yml +++ b/.github/workflows/nightly-dispatch.yml @@ -33,7 +33,7 @@ jobs: if not value: raise RuntimeError(message) - # These filters reduce noise; the protected release validator repeats admission + # 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/photocraft', 'wrong repository') require(os.environ.get('GITHUB_EVENT_NAME') == 'workflow_run', 'wrong event') @@ -51,7 +51,7 @@ 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') - body = json.dumps({'ref': 'release', 'inputs': { + 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( diff --git a/.github/workflows/nightly-sign.yml b/.github/workflows/nightly-sign.yml index 6039660348..d7014736a5 100644 --- a/.github/workflows/nightly-sign.yml +++ b/.github/workflows/nightly-sign.yml @@ -1,7 +1,8 @@ name: PhotoCraft 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: @@ -23,21 +24,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/photocraft' && 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: photocraft 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 cdeba1084a..3ff3e5eac6 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: photocraft manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]' craft-fonts-ref: cc9269cd8d8258785dac603fba3122e5d2556795 # 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 24fd38774a..3449244e19 100644 --- a/docs/nightly-release-preparation.md +++ b/docs/nightly-release-preparation.md @@ -1,7 +1,7 @@ # 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 +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 and there is no schedule: it only forwards scheduled producers. The installed policy [`.github/nightly-signing-policy.json`](../.github/nightly-signing-policy.json) is the real v3 @@ -14,21 +14,34 @@ gh api repos/storytold/photocraft/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`; #339 changes -neither callee's inputs nor the policy fields. The earlier pins, `a4f6fd51` (#342) and `077d4657` -(#330), lack those follow-ups or are Windows-only. A pin is reviewed +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 +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 `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. + **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`, which can only read photocraft; update it by PR @@ -61,13 +74,13 @@ This is not a hosted no-key test, a native signing result or a working nightly f ## Installed policy values and their sources -Read on 2026-11-23, with the Sonar gate and debt re-read on 2026-11-24; re-read anything that may have moved before the policy is promoted to `release`. +Read on 2026-11-23, with the Sonar gate and debt re-read on 2026-11-24; re-read anything that may have moved before `nightly-signer` is advanced to it. | Field | Value | Source | |---|---|---| | `repository_id` | `1398080271` | `gh api repos/storytold/photocraft --jq .id` | | `producer_workflow_id` | `428462603` | `gh api repos/storytold/photocraft/actions/workflows/nightly.yml` after `nightly.yml` reached main (path `.github/workflows/nightly.yml`, state `active`) | -| `producer_tooling_revision`, `signer_tooling_revision`, `producer_workflow_ref` | `605d5876…` (craft-common-actions #339) | The callers' pin | +| `producer_tooling_revision`, `signer_tooling_revision`, `producer_workflow_ref` | `88148a57…` (craft-common-actions signer-branch change, on #363) | The callers' pin | | `manual_actors` / `automatic_signer_actors` | the five release managers / `[]` | release-managers team (id 19837241) members who can push (4 admin, FredApps write); equals the producer caller's `manual-actors` | | `max_age_seconds`, `max_artifact_bytes` | `86400`, `2147483648` | Go-live checklist (Linux tarball is about 126 MB) | | `platforms` | three rows | v0.23.1 stable identities, as in the example; the Windows publisher subject was confirmed by reading the stable v0.23.1 `photocraft.exe` Authenticode signature on Windows | @@ -78,7 +91,7 @@ Read on 2026-11-23, with the Sonar gate and debt re-read on 2026-11-24; re-read The candidate check refuses whenever main's unresolved vulnerability set differs from `debt`, whether an issue is new or fixed, and whenever a required condition fails or a listed CI job is renamed. Refresh -those values in the same reviewed change that promotes the policy to `release`. +those values in the same reviewed main change that `nightly-signer` is then advanced to. ## Ownership and interface @@ -88,15 +101,16 @@ those values in the same reviewed change that promotes the policy to `release`. - `.github/workflows/nightly-dispatch.yml`: completion transport only, still literally off until a schedule is approved. On activation it accepts only a successful same-repository/main first scheduled producer attempt, then sends only - `producer_run_id` and `producer_run_attempt` to the fixed `nightly-sign.yml` on `release`. + `producer_run_id` and `producer_run_attempt` to the fixed `nightly-sign.yml` on + `refs/heads/nightly-signer`. No checkout, artifact parsing, application code or release environment is used here. Its filters are not authorization: a writer can edit main transport. - `.github/nightly-linux-signing-key.asc`: the stable Linux release public key, byte for byte the `release-signing-key.asc` published with v0.23.1 (one ed25519 primary key, `2B76741B414AAD6CD33E631213A005C0B9D7C3ED`, with one signing subkey). The shared Linux verifier - reads it from the protected release checkout, never from a release asset. Public material only. -- `.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, + reads it from the protected `nightly-signer` checkout, never from a release asset. Public material only. +- `.github/workflows/nightly-sign.yml`: top-level signer registration, enabled for manual dispatch + on `nightly-signer`, which carries a reviewed main commit. It rejects wrong repository/event/actual branch, including same-name tags. Its constant whole-run concurrency 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. @@ -136,12 +150,12 @@ without `platform`, `unsigned_artifact_name` and `windows_publisher_subject`, pl | `producer_workflow_id`, `producer_workflow_path` | Real default-branch registration ID and `.github/workflows/nightly.yml` | | `producer_tooling_revision`, `producer_workflow_ref` | Approved shared unsigned producer/attester commit and exact reusable path at that commit | | `signer_workflow_path`, `signer_tooling_revision` | `.github/workflows/nightly-sign.yml` and reviewed public shared signer commit | -| `release_branch`, `platforms` keys | `release`; exactly the producer's `platforms` list and the targets admitted in the shared registry (`windows-x86_64`, `linux-x86_64`, `macos-aarch64`) | +| `release_branch`, `platforms` keys | `nightly-signer` (the shared validator allows `release` or `nightly-signer`); exactly the producer's `platforms` list and the targets admitted in the shared registry (`windows-x86_64`, `linux-x86_64`, `macos-aarch64`) | | `manual_actors` | Reviewed manual producer/signer and rerun authority only: the five release managers, the same list as the producer's `manual-actors` | | `automatic_signer_actors` | Empty while there is no schedule; separate reviewed automatic-only authority for signer attempt 1 after authenticating a scheduled producer attempt 1; no manual producer or rerun grant | | `max_age_seconds`, `max_artifact_bytes`, `platforms..unsigned_artifact_name` | Reviewed bounded age/size and each platform's fixed unsigned artifact kind/prefix; actual upload/discovery name is that prefix + `-` + authenticated producer run ID + `-` + authenticated producer attempt, never a caller pattern or substitution | | `candidate_policy` | Full reviewed `craft-nightly-candidate-policy/v3` with real required workflow/job/check/app IDs, Sonar organization/project/issue types/conditions and exact approved debt fingerprints; provider configuration is trusted as resolved, not a pinned scan inventory | -| `platforms.linux-x86_64.trust.fingerprint` | Full primary fingerprint of the stable Linux release key, independently reviewed; the release checkout must also hold exactly that one public key at `.github/nightly-linux-signing-key.asc`, and the existing `LINUX_SIGNING_KEY` must be in the `release` environment only | +| `platforms.linux-x86_64.trust.fingerprint` | Full primary fingerprint of the stable Linux release key, independently reviewed; the signer-branch checkout must also hold exactly that one public key at `.github/nightly-linux-signing-key.asc`, and the existing `LINUX_SIGNING_KEY` must be in the `release` environment only | | `platforms.macos-aarch64.trust.apple_team_id` | Stable's ten-character Developer ID team `DJ6XS33FX8`, read from the stable v0.23.1 macOS code signature, whose leaf is `CN=Developer ID Application: Learning Machines LLC (DJ6XS33FX8), OU=DJ6XS33FX8, O=Learning Machines LLC`. The Windows certificate names a different entity, `Learning Machines Inc`; only the team ID `DJ6XS33FX8` is enforced on macOS. Never a repository variable. The six stable `APPLE_*`/`KEYCHAIN_PASSWORD` names must be in the `release` environment only | | `platforms.windows-x86_64.trust.publisher_subject` | Exact independently reviewed protected policy string used by both signer and fresh credentialless Windows publisher; nonempty, at most 1024 characters (the native signer's bound, checked at policy validation since #339), no CR/LF/NUL; verified native subject must match exactly, never an artifact/caller input | diff --git a/docs/nightly-signing-policy.example.json b/docs/nightly-signing-policy.example.json index 8611826929..cf11106001 100644 --- a/docs/nightly-signing-policy.example.json +++ b/docs/nightly-signing-policy.example.json @@ -8,7 +8,7 @@ "producer_workflow_ref": null, "signer_workflow_path": ".github/workflows/nightly-sign.yml", "signer_tooling_revision": null, - "release_branch": "release", + "release_branch": "nightly-signer", "manual_actors": [], "max_age_seconds": null, "candidate_policy": { diff --git a/docs/releasing.md b/docs/releasing.md index 7b6b5532b2..f359966acd 100644 --- a/docs/releasing.md +++ b/docs/releasing.md @@ -37,8 +37,9 @@ changes are required: publishing a newer stable GitHub Release makes it discover 2. **Review the release trust boundary, then merge `main` into `release`** (or fast-forward it) and push. The stable workflow starts by itself. Compare the proposed tree with the **previous trusted release**, not a manifest from main. Review and preserve: - - `.github/workflows/nightly-sign.yml`, `.github/nightly-signing-policy.json`, and - every transitive reusable workflow/action pin; + - every transitive reusable workflow/action pin. The nightly signer no longer rides this sync: + it runs on the dedicated `nightly-signer` branch (see below), but the `release` environment + trusts both branches, so this review still covers everything that can reach it; - `packaging/windows/sign.ps1`, its signing configuration, tool installers and imports; - the macOS nightly signing scripts (`packaging/macos/nightly-sign.sh`, `nightly-verify.sh`, `nightly-lib.sh`, `import-cert.sh`) and entitlements, and the Linux public key @@ -47,9 +48,8 @@ changes are required: publishing a newer stable GitHub Release makes it discover callees, dynamic environment selection and changed executable dependencies. A new workflow outside the named nightly paths is not exempt. - Stop the sync if that closure is unreviewed. The intended signer-owned files are identical - on main and release after promotion; actual top-level repository/event/branch checks and - the existing environment restrictions provide authority, not permanent branch divergence. + Stop the sync if that closure is unreviewed. Actual top-level repository/event/branch checks + and the existing environment restrictions provide authority, not permanent branch divergence. Main CI changes do not need a separate blanket review gate. This procedure does not repair the stable workflow's existing mutable dependencies, builds or caches. 3. **Wait for the draft.** After about 30 to 45 minutes (notarization is the slow part), the @@ -82,14 +82,18 @@ The Windows, Linux and macOS source preparation is documented in signing or publication pipeline. Stable `release.yml`, its schedule, tags, concurrency, environment values and environment rules are unchanged. -Initial installation **and later signer/policy updates** ride an already-intended reviewed -stable release sync, with an appropriate version/build state. Every release-branch push may -rebuild/update a stable draft or refuse an already-published version. An urgent change that -cannot wait means pause/cancel nightlies using existing workflow controls, then request one -bounded maintenance push with its exact stable consequences understood. Pausing must never -require a release push. Do not bypass CI, overwrite a stable release or make a dummy version -bump. Verify the actual environment permits only the release **branch**, excludes main and -same-name tags, and introduces no per-run approval requirement before activation; unresolved +Stable releases still come only from `refs/heads/release`. The nightly signer runs on +`refs/heads/nightly-signer` instead, so signer and policy +updates never need a stable release sync or a release-branch push. That branch is created once at +a reviewed main commit and later only fast-forwards to main commits, by a release manager running +the nightly-signer settings script's `advance`: it refuses while a `nightly-sign` run is queued or +running, scans the tree so only the pinned `nightly-sign.yml` caller can reach an environment, and +prints the full diff of `.github/` and `packaging/` for review before `--apply`. That diff is the +trust closure, including `packaging/env.sh`, which `import-cert.sh` sources with the Apple keys. +Org rulesets let only release managers create or update the branch and forbid force-pushes and +deletion. Pausing never requires a push: cancel or disable the nightly workflows. Verify the +actual environment permits only the `release` and `nightly-signer` **branches**, excludes main +and same-name tags, and introduces no per-run approval requirement before activation; unresolved protection or secret-scope collisions are blockers, not permission to change settings. Nightlies share the existing Windows signing identity with stable. A suspected key or signing @@ -439,9 +443,11 @@ caching, the iframe snippet and the `?webgl` / `?cpu` flags. ## Secrets All secrets live in the repository's **`release` environment** (*Settings → Environments → -release*). Restrict its deployment branches to `release`. Every job in `release.yml` that -signs or publishes declares `environment: release` (the Flatpak and FreeBSD jobs sign nothing -and don't), so only pushes to that branch, or manual runs on it, can read the secrets. Each secret is optional. If one is missing, that platform's artifacts are unsigned and +release*). Restrict its deployment branches to `release` and the nightly signer's +`nightly-signer`. Every job in the shared stable `release.yml` that signs or publishes binds the +environment only for a non-dry run on `refs/heads/release` (the Flatpak and FreeBSD jobs sign +nothing and don't), so only stable runs on that branch, or the pinned nightly signer on +`nightly-signer`, can read the secrets. Each secret is optional. If one is missing, that platform's artifacts are unsigned and the run shows a `::warning::`. | Secret | Used for | diff --git a/packaging/nightly-release-tests.py b/packaging/nightly-release-tests.py index 46004a7a00..018adc70bd 100644 --- a/packaging/nightly-release-tests.py +++ b/packaging/nightly-release-tests.py @@ -240,7 +240,7 @@ class DispatchBoundary(unittest.TestCase): self.assertEqual(request.full_url, "https://api.github.com/repos/storytold/photocraft/actions/workflows/nightly-sign.yml/dispatches") self.assertEqual(request.get_method(), "POST") - self.assertEqual(json.loads(request.data), {"ref": "release", "inputs": { + self.assertEqual(json.loads(request.data), {"ref": "refs/heads/nightly-signer", "inputs": { "producer_run_id": "71", "producer_run_attempt": "1"}}) self.assertGreater(opener.return_value.open.call_args.kwargs["timeout"], 0) @@ -531,7 +531,7 @@ class NightlyEnabledCallers(unittest.TestCase): "github.ref_type == 'branch' && (github.event_name == 'schedule' || " "github.event_name == 'workflow_dispatch')", "nightly-sign.yml": "github.repository == 'storytold/photocraft' && 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): @@ -610,7 +610,7 @@ class NightlyInstalledPolicy(unittest.TestCase): self.assertEqual(set(self.policy), set(example)) self.assertEqual(self.policy["schema"], "craft-nightly-release-policy/v3") self.assertEqual(self.policy["repository"], "storytold/photocraft") - self.assertEqual(self.policy["release_branch"], "release") + self.assertEqual(self.policy["release_branch"], SIGNER_BRANCH, "the signer runs on its dedicated branch") # Both read from the GitHub API (the repository and nightly.yml's registration on main). for key in ("repository_id", "producer_workflow_id"): with self.subTest(key=key): @@ -689,5 +689,261 @@ 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), ["photocraft"], "the shared signer needs the reviewed registry app") + dispatch = inline_scripts(DISPATCHER)[0] + self.assertEqual(re.findall(r"'ref': '([^']+)'", dispatch), ["refs/heads/" + SIGNER_BRANCH]) + self.assertEqual(json.loads(INSTALLED_POLICY.read_text())["release_branch"], SIGNER_BRANCH) + self.assertEqual(json.loads((ROOT / "docs/nightly-signing-policy.example.json").read_text())["release_branch"], + SIGNER_BRANCH) + + if __name__ == "__main__": unittest.main(verbosity=2)