diff --git a/.github/workflows/nightly-dispatch.yml b/.github/workflows/nightly-dispatch.yml new file mode 100644 index 00000000000..58a796ff4a3 --- /dev/null +++ b/.github/workflows/nightly-dispatch.yml @@ -0,0 +1,70 @@ +name: Dispatch release-ref nightly + +# Transport only, never authorization. No checkout, payload parsing or release environment. +on: + workflow_run: + workflows: [PhotoCraft unsigned nightly] + types: [completed] + branches: [main] + +permissions: {} + +jobs: + dispatch: + # SOURCE PREPARATION: literal off until immutable shared tooling and policy qualification. + if: ${{ false }} + 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 release 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') + 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/photocraft', 'wrong event repository') + producer = event.get('workflow_run', {}) + require(producer.get('head_repository', {}).get('full_name') == 'storytold/photocraft', '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': 'release', '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/photocraft/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': 'photocraft-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 new file mode 100644 index 00000000000..79a91df64bd --- /dev/null +++ b/.github/workflows/nightly-sign.yml @@ -0,0 +1,43 @@ +name: PhotoCraft release-ref nightly signer + +# Dormant source registration. Main/release contents must match after reviewed promotion. +# A reusable callee does not change context; this must be a real top-level release dispatch. +on: + workflow_dispatch: + inputs: + producer_run_id: + description: Exact untrusted producer Actions run ID + required: true + type: string + producer_run_attempt: + description: Exact untrusted producer Actions run attempt + required: true + type: string + +permissions: {} + +concurrency: + group: photocraft-nightly-release + cancel-in-progress: false + queue: max + +jobs: + release: + # Literal off until independent qualification. Actual context guards stay after activation. + if: >- + false && github.repository == 'storytold/photocraft' && + github.event_name == 'workflow_dispatch' && + github.ref == 'refs/heads/release' && 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@646d4c0619df19a6e76cb4d669f878e4a1e005d7 + with: + tooling-revision: 646d4c0619df19a6e76cb4d669f878e4a1e005d7 + 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. diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml new file mode 100644 index 00000000000..a23b4de4e39 --- /dev/null +++ b/.github/workflows/nightly.yml @@ -0,0 +1,27 @@ +name: PhotoCraft unsigned nightly + +# Dormant source registration at a reviewed public shared preview; no activation. +# No schedule/cadence has been authorized. A later explicit opt-in may add one. +on: + workflow_dispatch: + +permissions: + contents: read + +jobs: + unsigned: + # Literal off through source/hosted no-key qualification; no inherited/platform secrets. + if: ${{ false }} + # Maximum for the reusable workflow. Its compiler must override to contents-read only; + # only the separate unsigned attester may receive OIDC/attestation-write. + permissions: + contents: read + actions: read + attestations: write + id-token: write + uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@646d4c0619df19a6e76cb4d669f878e4a1e005d7 + with: + tooling-revision: 646d4c0619df19a6e76cb4d669f878e4a1e005d7 + app-name: photocraft + manual-actors: '[]' + craft-fonts-ref: cc9269cd8d8258785dac603fba3122e5d2556795 diff --git a/docs/nightly-release-preparation.md b/docs/nightly-release-preparation.md new file mode 100644 index 00000000000..273e8fd82bf --- /dev/null +++ b/docs/nightly-release-preparation.md @@ -0,0 +1,142 @@ +# Windows release-ref nightly: source preparation + +**Not activated or qualified.** No production signing policy is installed. The producer and +signer workflows are dormant `.yml` registrations, not an activated signing pipeline. +All three jobs remain literally disabled. There is no +schedule or platform secret grant. The unsigned reusable caller's maximum OIDC/attestation +permissions are for its isolated attester; its compiler must explicitly narrow to contents-read. +Shared tooling is pinned to public preview `646d4c0619df19a6e76cb4d669f878e4a1e005d7` +([shared draft #330](https://github.com/storytold/craft-common-actions/pull/330)); this is +reviewed source availability, not provider, queue, native signing or crypto qualification. +Existing stable workflows are unchanged. +This is not a hosted no-key test, a native signing result or a working nightly feed. + +## Ownership and interface + +- `.github/workflows/nightly.yml`: dormant default-main registration for the future unsigned producer, + named `PhotoCraft unsigned nightly`; no signing secrets may be passed or inherited. +- `.github/workflows/nightly-dispatch.yml`: dormant completion transport only. 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`. + No checkout, artifact parsing, application code or release environment is used here. + Its filters are not authorization: a writer can edit main transport. +- `.github/workflows/nightly-sign.yml`: dormant top-level registration, intended to be identical on + main/release after reviewed promotion. 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. No credentials can be reached + by this preparation. +- 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. The release callee's + request inputs are consistently `producer_run_id` and `producer_run_attempt`, while + `tooling-revision` keeps its existing hyphen spelling. Confirm the final landed interface + before any future pin update or activation. Unsigned inputs are `tooling-revision`, `app-name`, + `manual-actors` (default `[]`) and `craft-fonts-ref`; PhotoCraft's title is reviewed source, + not an `app-title` input. The reusable caller grants maximum permissions only; each + callee job must narrow them independently. + Shared code owns attestation validation, candidate quality, archive bounds, native signing, + role-separated receipts and publication. App code must not duplicate those parsers. +- The existing `packaging/windows/sign.ps1 -Required` is the app-owned Windows adapter. + Invoke it only from the immutable **release execution SHA** checkout, never the producer's + main source or extracted archive. Shared Windows tooling must own the flat GUI-only ZIP, + PE/inventory checks and post-sign verification; do not execute `nightly.ps1`, `package.ps1` + or the payload beside keys. No new wrapper is needed. `sign.ps1` is unchanged here. + +## Missing real configuration (all activation blockers) + +`.github/nightly-signing-policy.json` is deliberately absent: there is no authorizing root, +empty debt set, invented workflow ID or guessed publisher subject. The adjacent +[`nightly-signing-policy.example.json`](nightly-signing-policy.example.json) is intentionally +invalid (`null` unresolved values), not installable configuration. Install only independently +read, reviewed real values under schema `craft-nightly-release-policy/v1`: + +| Field | Required source of authority | +|---|---| +| `repository`, `repository_id` | Exact PhotoCraft repository and authenticated numeric ID | +| `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`, `platform` | `release`, `windows-x86_64` only | +| `manual_actors` | Empty by default; any authority needs normal release review | +| `max_age_seconds`, `max_artifact_bytes`, `unsigned_artifact_name` | Reviewed bounded age/size and 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 | +| `windows_publisher_subject` | Exact independently reviewed protected policy string used by both signer and fresh credentialless Windows publisher; nonempty, at most 2048 characters, no CR/LF/NUL; verified native subject must match exactly, never an artifact/caller input | + +Every `workflow_dispatch`, including the signer's first attempt, requires explicit reviewed +`manual_actors` authority. Before future automatic dispatch is activated, its bot must be +reviewed and listed explicitly; there is no implicit bot trust. This preparation does not +populate or authorize that policy. + +At the pinned `646d4c0619df19a6e76cb4d669f878e4a1e005d7` baseline, post-publish recovery +is **not implemented yet**; it is coming in the next common330 update. This packet does +not claim that recovery edge case is solved. + +Confirm the shared parser's final exact fields; unknown/missing/null values must refuse. +Do not derive policy, code/tool paths, trust anchors or ignored debt from a candidate archive. +The reviewed Windows publisher subject and independently pinned signing tools are also +unresolved; configure them only through the reviewed shared/release contract, not a guessed +app value or an override from main. No secret names/scopes or protection settings were audited +by this source change; no secret values were read. + +## Bounded integration and acceptance + +1. The callers now reference the same reviewed public preview commit in `uses` and + `tooling-revision`. Keep callers/dispatcher literally off through independent qualification + and while assembling real policy. Future shared pin updates require review of the exact + public immutable source and interface. Do not claim dormant source as a working pipeline. + Do not temporarily call old same-run signing or use mutable `@main`/`@release` tooling. + Keep compiler permissions contents-read only; isolated unsigned attester may receive only + its required Actions-read, attestation-write and OIDC, never platform keys. Re-run the + no-cache static check over **all** trusted jobs/callees, including setup-action cache options. +2. Register on main through normal review. Promote identical signer/policy/adapter contents + only during an already-intended stable sync, following [the release trust-closure review](releasing.md#cutting-a-release). + A release push can build/update a stable draft or refuse an already-published version; + this source change authorizes no push, skip-CI workaround or dummy version bump. +3. Hosted **no-platform-key**, separately authorized tests must establish actual release + dispatch context/permissions, queue retention/displacement, re-runs/current actor denial, + exact attestation `invocationId` run/attempt and immutable reusable identity. Test wrong + repository/ref/tag/event/actor, substituted run/attempt/artifact/transport ZIP/inner package, + missing/expired artifacts and all digest/claim mismatches. Transport archive SHA, unsigned + package SHA and final signed SHA are different roles, never interchangeable. +4. Candidate-v3 quality must prove exact C required latest runs/jobs and take the Sonar + snapshot first. Require coherent latest main-C revision/SCM at collection boundaries, + complete paginated branch issues scoped to reviewed issue types with count/end reread, + and the same analysis's gate and exact reviewed debt fingerprints. Profiles, rules, + scanner configuration and warnings are **trusted as resolved by the provider**, like + main CI; configuration changes can hide issues. This is not immutable scan-inventory + proof, full scan-scope enforcement or a warning-free-scan guarantee. The example has no + `sonar.scope` field; its exact Sonar fields match the shared candidate-v3 parser. + + Debt may shrink only with analysis-driven FIXED lifecycle proof **and** independently + qualified exact-C source-hash absence; missing/manual/REMOVED/unchanged-source proofs + refuse. Cloud source-hash normalization remains unqualified, so a vanished approved debt + item currently **refuses**, rather than counting absence as a fix. Qualify the real hash + semantics and lifecycle APIs without new credentials before claiming that path works. + + Current main M may advance past C only by verified ancestry; C must strictly advance the + previous authenticated publication P. Retained-snapshot revalidation currently refuses + once the latest Sonar analysis advances past C: no qualified historical issue/proof API + resolves that race. Do not promise publication survives a newer analysis. Repeat + admission/pause/quality/ancestry/newest-run checks before keys and publication. +5. Separately authorize first native Windows signing/publication, signature/publisher/timestamp + checks, Launcher install beside stable, launch/profile/version independence, rollback and + uninstall preservation, and corrupt/unsigned/wrong-publisher rejection. No Linux/macOS + coverage follows from Windows. Keep production/native/publication/prune switches off until + their own acceptance. Nightly assets remain prerelease, `make_latest:false`, with separate + nightly tags/reservations and authenticated cross-attempt interrupted-publication recovery. + +Routine updates ride real stable windows, never automatic main-to-release copying. Pause or +cancel via existing nightly workflow controls without pushing release; urgent repairs need +one explicitly authorized bounded maintenance push. See the shared-identity incident note in +[the release guide](releasing.md#release-ref-nightly-preparation). No daily witness renewal or +per-run human approval is introduced by candidate-v3; provider gaps remain blockers. + +## Local regression checks + +`python3 packaging/nightly-release-tests.py` executes the **actual inline dispatcher** with +synthetic, locally generated event fixtures and a mocked HTTPS opener. It verifies fixed +routing, refusal before contact and no retry; it does not contact GitHub or prove admission, +cryptography, native signing, hosted concurrency, or the shared candidate-v3 implementation. +The same suite enforces the app trusted-workflow no-cache/no-secret preparation boundary. +Run through the normal task allocator; report actionlint/PowerShell/native/hosted checks +separately and never treat a missing runtime as a pass. diff --git a/docs/nightly-signing-policy.example.json b/docs/nightly-signing-policy.example.json new file mode 100644 index 00000000000..e596928df02 --- /dev/null +++ b/docs/nightly-signing-policy.example.json @@ -0,0 +1,36 @@ +{ + "schema": "craft-nightly-release-policy/v1", + "repository": "storytold/photocraft", + "repository_id": null, + "producer_workflow_id": null, + "producer_workflow_path": ".github/workflows/nightly.yml", + "producer_tooling_revision": null, + "producer_workflow_ref": null, + "signer_workflow_path": ".github/workflows/nightly-sign.yml", + "signer_tooling_revision": null, + "release_branch": "release", + "manual_actors": [], + "platform": "windows-x86_64", + "max_age_seconds": null, + "candidate_policy": { + "schema": "craft-nightly-candidate-policy/v3", + "epoch": null, + "repository": "storytold/photocraft", + "branch": "main", + "required_workflows": null, + "sonar": { + "organization": null, + "project": null, + "app_id": null, + "check_name": null, + "details_url": null, + "issue_types": null, + "accepted_conditions": null, + "required_conditions": null, + "debt": null + } + }, + "unsigned_artifact_name": null, + "max_artifact_bytes": null, + "windows_publisher_subject": null +} diff --git a/docs/releasing.md b/docs/releasing.md index f39898724c5..d05ea33fc6a 100644 --- a/docs/releasing.md +++ b/docs/releasing.md @@ -34,7 +34,23 @@ changes are required: publishing a newer stable GitHub Release makes it discover ``` Commit the change (`Cargo.toml` + `Cargo.lock`) through the normal review flow. -2. **Merge `main` into `release`** (or fast-forward it) and push. The workflow starts by itself. +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; + - `packaging/windows/sign.ps1`, its signing configuration, tool installers and imports; + - future macOS nightly signing/import scripts and entitlements, and Linux signing/public + trust configuration; + - **every other workflow that can reach the `release` environment**, including reusable + 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. + 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 Releases page has a draft `PhotoCraft v0.2.0`, tagged `v0.2.0` on the pushed commit, with every artifact and `SHA256SUMS.txt`. The notes are generated from the merged PRs. @@ -58,6 +74,30 @@ it with `cargo xtask version set` before building, so the binaries report it too needs the `release` environment, which only the `release` branch can use, so pick that branch in the dialog. +## Release-ref nightly preparation + +The Windows-first source preparation is documented in +[`nightly-release-preparation.md`](nightly-release-preparation.md). It is not an activated +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 +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 +service compromise therefore affects **both channels**: stop/cancel nightlies immediately, +notify the release maintainers/security owner privately, and have the identity's authorized +owner revoke/rotate it and assess already-signed stable and nightly packages. Stopping one +workflow does not revoke signatures or make stable safe. No credentials or identity values +are recorded in this procedure. + ## What gets built | Platform | Artifacts | Built on | diff --git a/packaging/nightly-release-tests.py b/packaging/nightly-release-tests.py new file mode 100644 index 00000000000..22c1df725e6 --- /dev/null +++ b/packaging/nightly-release-tests.py @@ -0,0 +1,162 @@ +#!/usr/bin/env python3 +"""Synthetic dispatcher regression fixtures; original local work, not live API/crypto evidence.""" +import contextlib +import copy +import io +import json +import os +from pathlib import Path +import re +import tempfile +import textwrap +import unittest +from unittest.mock import patch +import urllib.error + +ROOT = Path(__file__).resolve().parents[1] +DISPATCHER = ROOT / ".github/workflows/nightly-dispatch.yml" + + +def inline_scripts(path): + """Read literal run blocks, not a substitute for YAML/actionlint validation.""" + return [textwrap.dedent(block) for block in re.findall( + r"^ run: \|\n((?: .*\n|\n)+)", path.read_text(), re.MULTILINE)] + + +class Response: + status = 204 + + def __enter__(self): + return self + + def __exit__(self, *args): + return False + + +class DispatchBoundary(unittest.TestCase): + def setUp(self): + # All generated metadata is synthetic, including the presence-only mock token. + self.event = {"action": "completed", "repository": {"full_name": "storytold/photocraft"}, + "workflow_run": {"id": 71, "run_attempt": 1, "status": "completed", + "conclusion": "success", "event": "schedule", + "path": ".github/workflows/nightly.yml", "head_branch": "main", + "head_repository": {"full_name": "storytold/photocraft"}}} + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + self.event_path = Path(self.temp.name) / "event.json" + self.env = {"GITHUB_REPOSITORY": "storytold/photocraft", "GITHUB_EVENT_NAME": "workflow_run", + "GITHUB_EVENT_PATH": str(self.event_path), "GH_TOKEN": "synthetic-not-a-token"} + scripts = inline_scripts(DISPATCHER) + if len(scripts) != 1: + raise RuntimeError("dispatcher must have one locally exercisable literal script") + self.program = compile(scripts[0], str(DISPATCHER), "exec") + + def execute(self, event=None, env=None, failure=None, response=None): + self.event_path.write_text(json.dumps(self.event if event is None else event)) + scope = {} + with patch.dict(os.environ, self.env if env is None else env, clear=True), \ + patch("urllib.request.build_opener") as opener, \ + contextlib.redirect_stdout(io.StringIO()): + opener.return_value.open.return_value = response or Response() + opener.return_value.open.side_effect = failure + try: + exec(self.program, scope) + except Exception as error: + return opener, scope, error + return opener, scope, None + + def assert_refused(self, event=None, env=None): + opener, _, error = self.execute(event=event, env=env) + self.assertIsNotNone(error, "invalid transport must refuse") + opener.assert_not_called() + + def test_only_fixed_release_destination_and_numeric_request_are_transported(self): + # Caller-selected source/ref/digest fields have no effect on the transmitted request. + self.event["workflow_run"].update({"ref": "main", "artifact_id": 999, + "sha256": "untrusted", "tooling": "untrusted"}) + opener, _, error = self.execute() + self.assertIsNone(error) + opener.return_value.open.assert_called_once() + request = opener.return_value.open.call_args.args[0] + 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": { + "producer_run_id": "71", "producer_run_attempt": "1"}}) + self.assertGreater(opener.return_value.open.call_args.kwargs["timeout"], 0) + + def test_wrong_top_level_context_refuses_before_network(self): + for key, value in (("GITHUB_REPOSITORY", "other/photocraft"), + ("GITHUB_EVENT_NAME", "workflow_dispatch")): + with self.subTest(key=key): + self.assert_refused(env={**self.env, key: value}) + + def test_foreign_or_noncompleted_events_refuse_before_network(self): + for key, value in (("action", "requested"), + ("repository", {"full_name": "other/photocraft"})): + with self.subTest(key=key): + self.assert_refused(event={**self.event, key: value}) + + def test_wrong_producer_identity_status_and_manual_retries_refuse(self): + for key, value in (("head_repository", {"full_name": "other/photocraft"}), + ("head_branch", "release"), ("head_branch", "refs/tags/main"), + ("path", ".github/workflows/release.yml"), ("status", "in_progress"), + ("conclusion", "failure"), ("conclusion", "cancelled"), + ("event", "workflow_dispatch"), ("event", "pull_request"), + ("run_attempt", 2)): + event = copy.deepcopy(self.event) + event["workflow_run"][key] = value + with self.subTest(key=key, value=value): + self.assert_refused(event=event) + + def test_ids_are_not_coerced_from_strings_booleans_or_fractional_values(self): + for key in ("id", "run_attempt"): + for value in (None, False, True, 0, -1, 1.5, "1", "1;evil", [], {}): + event = copy.deepcopy(self.event) + event["workflow_run"][key] = value + with self.subTest(key=key, value=value): + self.assert_refused(event=event) + + def test_missing_metadata_never_contacts_api(self): + for key in self.event["workflow_run"]: + event = copy.deepcopy(self.event) + del event["workflow_run"][key] + with self.subTest(key=key): + self.assert_refused(event=event) + + def test_redirect_handler_refuses_instead_of_forwarding_authorization(self): + _, scope, error = self.execute() + self.assertIsNone(error) + with self.assertRaisesRegex(RuntimeError, "redirects are forbidden"): + scope["NoRedirect"]().redirect_request(None, None, 302, "found", {}, "https://untrusted.invalid") + + def test_failed_http_request_is_not_retried_or_reported_successful(self): + for error in (TimeoutError("synthetic timeout"), urllib.error.URLError("synthetic failure")): + with self.subTest(error=type(error).__name__): + opener, _, caught = self.execute(failure=error) + self.assertIs(caught, error) + opener.return_value.open.assert_called_once() + response = Response() + response.status = 202 + opener, _, error = self.execute(response=response) + self.assertIsNotNone(error) + opener.return_value.open.assert_called_once() + + +class TrustedSourcePreparation(unittest.TestCase): + def test_no_cache_actions_or_cache_setup_options_in_app_trusted_closure(self): + # Required R3 static guard for app workflows only; activation must extend + # this check to every reviewed immutable shared trusted callee. + for name in ("nightly-sign.yml", "nightly-dispatch.yml"): + source = (ROOT / ".github/workflows" / name).read_text() + executable = "\n".join(line for line in source.splitlines() + if not line.lstrip().startswith("#")) + with self.subTest(workflow=name): + self.assertNotRegex(executable, r"(?im)^\s*(?:-\s*)?uses:\s*[^\n]*cache") + self.assertNotRegex(executable, r"(?im)^\s*[^\s:#]*cache[^\s:#]*:") + self.assertNotRegex(executable, r"(?im)^\s*(?:environment|secrets):") + self.assertNotIn("secrets.", executable) + + +if __name__ == "__main__": + unittest.main(verbosity=2) diff --git a/packaging/nightly-tests.py b/packaging/nightly-tests.py index 5d410795afc..c3af221f236 100644 --- a/packaging/nightly-tests.py +++ b/packaging/nightly-tests.py @@ -11,6 +11,7 @@ def main() -> int: for name, relative in ( ("photo_archive_suite", "nightly-archive-tests.py"), ("photo_plist_suite", "macos/nightly_plist_tests.py"), + ("photo_release_dispatch_suite", "nightly-release-tests.py"), ): spec = importlib.util.spec_from_file_location(name, here / relative) module = importlib.util.module_from_spec(spec)