diff --git a/.github/actionlint.yaml b/.github/actionlint.yaml index dc6362a59e..f576e9ef9b 100644 --- a/.github/actionlint.yaml +++ b/.github/actionlint.yaml @@ -2,3 +2,10 @@ self-hosted-runner: labels: - macos-release # org larger runner (M2 Pro), used by release.yml + +# actionlint 1.7.12 predates GitHub's queue key. Only this exact false positive is +# suppressed; Packaging lint's independent source-contract job enforces the values. +paths: + .github/workflows/nightly-sign.yml: + ignore: + - '^unexpected key "queue" for "concurrency" section\. expected one of "cancel-in-progress", "group"$' 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/workflows/nightly-dispatch.yml b/.github/workflows/nightly-dispatch.yml new file mode 100644 index 0000000000..17622f5060 --- /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: [PhotoCraft 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/photocraft' && + 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 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 0000000000..a2df41a4ab --- /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@a4f6fd51e854773de8b24b4f92e1ad7e770c08d7 + with: + tooling-revision: a4f6fd51e854773de8b24b4f92e1ad7e770c08d7 + 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 0000000000..b9575f4d55 --- /dev/null +++ b/.github/workflows/nightly.yml @@ -0,0 +1,33 @@ +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 && github.repository == 'storytold/photocraft' && + github.ref == 'refs/heads/main' && github.ref_type == 'branch' && + (github.event_name == 'schedule' || github.event_name == 'workflow_dispatch') + # Maximum for the reusable workflow. Its compiler narrows to contents/actions read; + # no OIDC, attestation write, release environment or platform secrets in compilation. + permissions: + contents: read + actions: read + attestations: write + id-token: write + uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@a4f6fd51e854773de8b24b4f92e1ad7e770c08d7 + with: + tooling-revision: a4f6fd51e854773de8b24b4f92e1ad7e770c08d7 + app-name: photocraft + manual-actors: '[]' + 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 the Linux/macOS signer (#342). + platforms: '["windows-x86_64","linux-x86_64","macos-aarch64"]' diff --git a/.github/workflows/packaging-lint.yml b/.github/workflows/packaging-lint.yml index 560103c61e..b288dbf68d 100644 --- a/.github/workflows/packaging-lint.yml +++ b/.github/workflows/packaging-lint.yml @@ -5,9 +5,9 @@ name: Packaging lint on: push: branches: [main, release] - paths: [".github/workflows/**", "packaging/**", "assets/app-icon/**", "docs/mcp.md", "docs/control-protocol.md"] + paths: [".github/workflows/**", ".github/actionlint.yaml", "packaging/**", "assets/app-icon/**", "docs/mcp.md", "docs/control-protocol.md", "docs/nightly-signing-policy.example.json", ".github/nightly-signing-policy.json", ".github/nightly-linux-signing-key.asc", "sonar-project.properties"] pull_request: - paths: [".github/workflows/**", "packaging/**", "assets/app-icon/**", "docs/mcp.md", "docs/control-protocol.md"] + paths: [".github/workflows/**", ".github/actionlint.yaml", "packaging/**", "assets/app-icon/**", "docs/mcp.md", "docs/control-protocol.md", "docs/nightly-signing-policy.example.json", ".github/nightly-signing-policy.json", ".github/nightly-linux-signing-key.asc", "sonar-project.properties"] workflow_dispatch: permissions: @@ -63,3 +63,20 @@ jobs: - name: Build and check non-executable installer fixtures shell: pwsh run: ./packaging/windows/test-install-policy.ps1 -OutputDirectory (Join-Path $env:RUNNER_TEMP 'craft-install-policy-tests') + + nightly-source-contract: + name: Nightly source contracts (no build or signing) + runs-on: ubuntu-latest + timeout-minutes: 5 + permissions: + contents: read + steps: + - name: Harden runner + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Enforce nightly serialization and synthetic packaging contracts + run: python3 packaging/nightly-tests.py diff --git a/docs/nightly-release-preparation.md b/docs/nightly-release-preparation.md new file mode 100644 index 0000000000..de48432443 --- /dev/null +++ b/docs/nightly-release-preparation.md @@ -0,0 +1,217 @@ +# Windows, Linux and macOS 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 narrows to contents and Actions read +only, with no OIDC, attestation write, release environment or platform signing secrets. +Shared tooling is pinned to `a4f6fd51e854773de8b24b4f92e1ad7e770c08d7`, the craft-common-actions +main commit that merged [#342](https://github.com/storytold/craft-common-actions/pull/342): policy v3, +the `platforms` input and the Linux and macOS legs, all switched off. Both callers name it in `uses` +and `tooling-revision`; the earlier pin, `077d4657` (#330), is Windows-only. A pin is reviewed +source availability, not provider, queue, native signing or crypto qualification. +Existing stable workflows are unchanged. + +**Platform rows (dormant).** The producer caller lists +`platforms: '["windows-x86_64","linux-x86_64","macos-aarch64"]'` on its single, still literally-off +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 +platforms only from the protected policy, so there is no separate Linux or macOS caller job and +the signer caller has no platform input. The shared Linux leg runs the app's +`packaging/linux/nightly.sh --arch x86_64` (GUI-only `photocraft--linux-x86_64-nightly.tar.gz`) +and signs with the stable OpenPGP key; the macOS leg runs `packaging/macos/nightly.sh --arch aarch64` +unsigned on main, then `packaging/macos/nightly-sign.sh` (stable `import-cert.sh`, Developer ID, +hardened runtime, notarization and stapling) and `nightly-verify.sh` from the protected release +checkout. Those scripts are owned by PhotoCraft's Linux and macOS packaging authors, not by these +callers. Neither leg has run on hosted runners: launch, profile isolation beside stable and the +Launcher install still need Linux and macOS desktop QA. +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/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`: 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 `[]`), `craft-fonts-ref` and `platforms`; 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 or invented workflow ID, and installing it is a separate activation step. The adjacent +[`nightly-signing-policy.example.json`](nightly-signing-policy.example.json) is intentionally +invalid (`null` unresolved values), not installable configuration. Its `platforms` rows do carry +the reviewed public values: each fixed `nightly-unsigned-` artifact kind and stable's +identities, read from the v0.23.1 release (Windows Authenticode leaf subject in Windows form, +the Linux release key's primary fingerprint, and the Developer ID team `DJ6XS33FX8` from the +macOS CLI's code signature). Install only independently +read, reviewed real values under explicit schema `craft-nightly-release-policy/v3` (v2 top-level fields +without `platform`, `unsigned_artifact_name` and `windows_publisher_subject`, plus a `platforms` map): + +| 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`, `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`) | +| `manual_actors` | Empty by default; reviewed manual producer/signer and rerun authority only | +| `automatic_signer_actors` | Empty by default; 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.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 2048 characters, no CR/LF/NUL; verified native subject must match exactly, never an artifact/caller input | + +Live admission requires explicit policy v3 once the shared parser lands it; v2 is single-platform +Windows only and is not silently migrated. Historical v1 retains its exact old fields and +broad manual-list semantics, and is not silently migrated or accepted for live admission. The +v2 actor lists are separate, bounded and case-normalized; overlaps refuse. An automatic-only +actor may authorize **only signer attempt 1**, after the validator authenticates a **scheduled +producer attempt 1**. That list grants no manual producer, producer rerun or signer rerun +authority. Those requests require the independently reviewed `manual_actors` list. + +Before future automatic dispatch is activated, its identity needs explicit review for +`automatic_signer_actors`; no bot is implicitly trusted or installed here. Never union that +list into `manual_actors` or the unsigned caller's `manual-actors` input. Both example lists +and the caller input remain empty; this preparation does not populate or authorize policy. + +### Post-publication recovery limitation + +The pinned shared revision now prevents a narrowly scoped failure, not general recovery: +**only after the publisher returns through successful final verification** may an ownership +receipt I/O failure be reported without failing that already-verified publication. A public +PATCH callback alone is insufficient. Pending bytes become canonical `ownership.json` only +after successful write, flush/fsync and close; incomplete receipts supply no canonical +ownership or pruning authority. The optional ownership upload uses only that canonical +path, warns if missing and cannot by itself fail the publication job. + +This does not repair historical failed attempts or reconcile runner loss, timeouts, uncertain +publication responses, or failed/incomplete final verification. Those cases remain stopped +for release-manager reviewed manual handling; re-running does not repair an old recorded +failure. No general authenticated reconciliation protocol, retry or public-state editing/ +deletion authority is introduced. Manual handling of these remaining cases still needs +preactivation review and qualification. These are source behaviors, not hosted/crypto proof. + +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. +Independently pinned signing tools are also unresolved; configure them, and the trust values +above, only through the reviewed shared/release contract, never a guessed app value or an +override from main. The unchanged stable `release.yml` forwards Windows/Azure +secret names from caller scope, while the nightly signer forwards none. Before activation, +verify the existing `release` environment holds the required names and that repository or +organization scopes do not expose signing copies to main. Environment-only missing values +must fail closed; repository/org-only values or same-name scope collisions are blockers, +not permission to copy keys or change settings. 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 and Actions read only, with no OIDC, attestation write, + release environment or platform secrets. Only the isolated unsigned attester receives + 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. Historical failures, uncertain/failed final verification and + runner loss retain the [manual-handling limits described above](#post-publication-recovery-limitation); + receipt-failure prevention does not supply general reconciliation. + +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. +It checks that the policy example's platforms equal the producer list, that each row names its +fixed artifact kind and stable identity, that `.github/nightly-linux-signing-key.asc` holds exactly +one public primary key whose fingerprint is the policy's, and that both callers share one pin in +`uses` and `tooling-revision`. +The same suite covers all three callers for the no-cache/no-platform-secret boundary, +requires every nightly job to stay explicitly off (a top-level OR cannot override false), +and refuses any registered nightly schedule. It also rejects changed root serialization: the fixed PhotoCraft nightly group, `queue: max`, +and `cancel-in-progress: false` must remain literal. Mutation regressions reject invalid queue +values, cancellation and request-dependent groups. Packaging lint runs this suite in its +independent contents-read-only `nightly-source-contract` job, including config-only changes; +it does not rely on the shared Bash packaging hook to run the guard. + +The existing `.github/actionlint.yaml` suppresses only actionlint 1.7.12's anchored exact +unsupported-queue message for `.github/workflows/nightly-sign.yml`. This operator-requested +compatibility exception is not a blanket syntax waiver: other files/messages still fail, +and the mandatory source guard supplies the missing queue-value/serialization checks. +No tool fork or shared lint change is needed. This same-PR nonprivileged CI hook is the +narrow correction requested for the dormant source; stable/release execution is unchanged. +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 0000000000..8611826929 --- /dev/null +++ b/docs/nightly-signing-policy.example.json @@ -0,0 +1,54 @@ +{ + "schema": "craft-nightly-release-policy/v3", + "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": [], + "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 + } + }, + "max_artifact_bytes": null, + "automatic_signer_actors": [], + "platforms": { + "windows-x86_64": { + "unsigned_artifact_name": "nightly-unsigned-windows-x86_64", + "trust": { + "publisher_subject": "CN=Learning Machines Inc, O=Learning Machines Inc, L=Atlanta, S=Georgia, C=US" + } + }, + "linux-x86_64": { + "unsigned_artifact_name": "nightly-unsigned-linux-x86_64", + "trust": { + "fingerprint": "2B76741B414AAD6CD33E631213A005C0B9D7C3ED" + } + }, + "macos-aarch64": { + "unsigned_artifact_name": "nightly-unsigned-macos-aarch64", + "trust": { + "apple_team_id": "DJ6XS33FX8" + } + } + } +} diff --git a/docs/releasing.md b/docs/releasing.md index 262190fb10..7b6b5532b2 100644 --- a/docs/releasing.md +++ b/docs/releasing.md @@ -34,7 +34,24 @@ 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; + - 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 + `.github/nightly-linux-signing-key.asc`; + - **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 +75,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, Linux and macOS 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 0000000000..36309642da --- /dev/null +++ b/packaging/nightly-release-tests.py @@ -0,0 +1,482 @@ +#!/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 base64 +import hashlib +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)] + + +def assert_nightly_serialization(source): + """Fail closed unless this app's plain root concurrency block retains its contract. + + This is a deliberately narrow source guard, not a general YAML parser; actionlint + still checks all other syntax. Expressions, aliases and alternate block shapes + refuse rather than delegating queue-value validation to the old linter. + """ + lines = source.splitlines() + roots = [index for index, line in enumerate(lines) if line.startswith("concurrency:")] + if len(roots) != 1 or lines[roots[0]] != "concurrency:": + raise ValueError("one plain root concurrency block is required") + values = {} + for line in lines[roots[0] + 1:]: + if not line.strip() or line.lstrip().startswith("#"): + continue + if not line[0].isspace(): + break + row = re.fullmatch(r" (group|cancel-in-progress|queue): ([^#]+?)(?: +#.*)?", line) + if row is None or row[1] in values: + raise ValueError("malformed or duplicate nightly concurrency entry") + values[row[1]] = row[2].rstrip() + if values != {"group": "photocraft-nightly-release", "cancel-in-progress": "false", "queue": "max"}: + raise ValueError("nightly serialization must use its stable group, max queue and no cancellation") + + +def literal_off(condition): + expression = " ".join(condition.split()) + if expression.startswith("${{") and expression.endswith("}}"): + expression = expression[3:-2].strip() + if expression == "false": + return True + if not expression.startswith("false && "): + return False + # A top-level OR could override the leading false; parentheses must balance. + expression = re.sub(r"'(?:''|[^'])*'", "''", expression) + depth = 0 + for token in re.findall(r"\(|\)|\|\|", expression): + if token == "(": + depth += 1 + elif token == ")": + depth -= 1 + if depth < 0: + return False + elif depth == 0: + return False + return depth == 0 + + +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 = { + "windows-x86_64": ("publisher_subject", + "CN=Learning Machines Inc, O=Learning Machines Inc, L=Atlanta, S=Georgia, C=US"), + "linux-x86_64": ("fingerprint", "2B76741B414AAD6CD33E631213A005C0B9D7C3ED"), + "macos-aarch64": ("apple_team_id", "DJ6XS33FX8"), +} +LINUX_KEY = ROOT / ".github/nightly-linux-signing-key.asc" + + +def openpgp_primary_fingerprints(armored): + """Return the v4 fingerprints of every primary public-key packet in one armored block. + + A narrow reader for the committed public key, not a general OpenPGP parser: anything + other than one well-formed public-key block refuses. + """ + lines = armored.strip().splitlines() + if lines[:1] != ["-----BEGIN PGP PUBLIC KEY BLOCK-----"] or lines[-1:] != ["-----END PGP PUBLIC KEY BLOCK-----"]: + raise ValueError("exactly one armored public key block is required") + body = lines[1:-1] + if "" not in body: + raise ValueError("armor header separator missing") + body = body[body.index("") + 1:] + if not body or not body[-1].startswith("="): + raise ValueError("armor checksum missing") + data = base64.b64decode("".join(body[:-1]), validate=True) + fingerprints, offset = [], 0 + while offset < len(data): + header = data[offset] + if not header & 0x80: + raise ValueError("invalid packet header") + if header & 0x40: + tag, offset = header & 0x3F, offset + 1 + first = data[offset] + if first < 192: + length, offset = first, offset + 1 + elif first < 224: + length, offset = ((first - 192) << 8) + data[offset + 1] + 192, offset + 2 + elif first == 255: + length, offset = int.from_bytes(data[offset + 1:offset + 5], "big"), offset + 5 + else: + raise ValueError("partial packet lengths are not a public key") + else: + tag, kind, offset = (header >> 2) & 0x0F, header & 0x03, offset + 1 + if kind == 3: + raise ValueError("indeterminate packet length") + size = 1 << kind + length, offset = int.from_bytes(data[offset:offset + size], "big"), offset + size + packet = data[offset:offset + length] + if len(packet) != length: + raise ValueError("truncated packet") + if tag == 5 or tag == 7: + raise ValueError("secret key material must never be committed") + if tag == 6: + if packet[:1] != b"\x04": + raise ValueError("only v4 primary keys are expected") + fingerprints.append(hashlib.sha1(b"\x99" + length.to_bytes(2, "big") + packet).hexdigest().upper()) + offset += length + return fingerprints + + +def producer_platforms(source): + """Read the one producer job's literal platform list; a narrow source guard, not YAML. + + One producer run builds every listed platform for one all-or-nothing release, so the + list must be a compact JSON list of distinct known platforms that keeps Windows. + """ + rows = re.findall(r"(?m)^ platforms: (.*)$", source) + if len(rows) != 1: + raise ValueError("exactly one producer platform list is required") + literal = re.fullmatch(r"'(\[[^']*\])'", rows[0]) + if literal is None: + raise ValueError("the platform list must be one single-quoted literal") + platforms = json.loads(literal[1]) + if not isinstance(platforms, list) or json.dumps(platforms, separators=(",", ":")) != literal[1]: + raise ValueError("the platform list must be compact JSON") + if len(set(platforms)) != len(platforms) or not set(platforms) <= set(NIGHTLY_PLATFORMS): + raise ValueError("platforms must be distinct known nightly targets") + if "windows-x86_64" not in platforms: + raise ValueError("the Windows row stays in the producer") + return platforms + + +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_sonar_classifies_only_the_exact_packaging_fixture_runners(self): + source = (ROOT / "sonar-project.properties").read_text() + self.assertEqual(re.findall(r"(?m)^sonar.sources=(.*)$", source), ["."]) + self.assertEqual(re.findall(r"(?m)^sonar.tests=(.*)$", source), ["packaging"]) + inclusions = re.findall(r"(?m)^sonar.test.inclusions=(.*)$", source) + self.assertEqual(len(inclusions), 1) + entries = inclusions[0].split(",") + expected = {"packaging/nightly-tests.py", "packaging/nightly-archive-tests.py", + "packaging/macos/nightly_plist_tests.py", "packaging/macos/nightly_sign_tests.py", + "packaging/windows/nightly-package-tests.ps1", + "packaging/windows/nightly-signing-tests.ps1", "packaging/nightly-release-tests.py"} + self.assertEqual(set(entries), expected, "classify exact fixtures, never production helpers or wildcard scope") + self.assertEqual(len(entries), len(expected), "duplicate fixture classification") + + def test_policy_example_keeps_explicit_v3_and_no_actor_authority(self): + policy = json.loads((ROOT / "docs/nightly-signing-policy.example.json").read_text()) + expected = {"schema", "repository", "repository_id", "producer_workflow_id", + "producer_workflow_path", "producer_tooling_revision", "producer_workflow_ref", + "signer_workflow_path", "signer_tooling_revision", "release_branch", "manual_actors", + "automatic_signer_actors", "max_age_seconds", "candidate_policy", + "max_artifact_bytes", "platforms"} + self.assertEqual(set(policy), expected, "no single-platform v2 fields or implicit migration") + self.assertEqual(policy["schema"], "craft-nightly-release-policy/v3") + self.assertEqual(policy["manual_actors"], []) + self.assertEqual(policy["automatic_signer_actors"], []) + for key in ("repository_id", "producer_workflow_id", "producer_tooling_revision", + "producer_workflow_ref", "signer_tooling_revision", "max_age_seconds", + "max_artifact_bytes"): + with self.subTest(unresolved=key): + self.assertIsNone(policy[key], "the example must not invent production authority") + path = ROOT / ".github/nightly-signing-policy.json" + self.assertFalse(path.exists() or path.is_symlink(), "installing the policy is a separately reviewed activation") + + def test_policy_platforms_are_exactly_what_the_producer_builds(self): + policy = json.loads((ROOT / "docs/nightly-signing-policy.example.json").read_text()) + built = producer_platforms((ROOT / ".github/workflows/nightly.yml").read_text()) + self.assertEqual(built, list(NIGHTLY_PLATFORMS), "one release carries Windows, Linux and macOS") + self.assertEqual(set(policy["platforms"]), set(built), "a built platform without policy, or the reverse") + for platform, row in policy["platforms"].items(): + field, _ = NIGHTLY_TRUST[platform] + with self.subTest(platform=platform): + self.assertEqual(set(row), {"unsigned_artifact_name", "trust"}) + self.assertEqual(set(row["trust"]), {field}, "each platform has only its own trust anchor") + + def test_candidate_example_has_exact_v3_fields_without_provider_scope_claim(self): + candidate = json.loads((ROOT / "docs/nightly-signing-policy.example.json").read_text())["candidate_policy"] + self.assertEqual(set(candidate), {"schema", "epoch", "repository", "branch", "required_workflows", "sonar"}) + self.assertEqual(candidate["schema"], "craft-nightly-candidate-policy/v3") + self.assertIsNone(candidate["required_workflows"]) + self.assertEqual(set(candidate["sonar"]), {"organization", "project", "app_id", "check_name", + "details_url", "issue_types", "accepted_conditions", "required_conditions", "debt"}) + self.assertTrue(all(value is None for value in candidate["sonar"].values()), "real identity/debt is unresolved") + + def test_every_nightly_job_remains_explicitly_off(self): + for name in ("nightly.yml", "nightly-dispatch.yml", "nightly-sign.yml"): + source = (ROOT / ".github/workflows" / name).read_text() + jobs = source.split("\njobs:\n", 1)[1] + headers = re.findall(r"(?m)^ (?![\s#])[^\n]+", jobs) + conditions = re.findall(r"(?m)^ if: ([^\n]+)(?:\n((?: [^\n]*\n)+))?", jobs) + with self.subTest(workflow=name): + self.assertTrue(headers) + self.assertEqual(len(conditions), len(headers), "every job needs a literal-off condition") + for scalar, folded in conditions: + self.assertTrue(literal_off(folded if scalar == ">-" else scalar), "nightly activation requires reviewed test update") + + def test_one_producer_and_one_signer_job_carry_every_platform(self): + for name, job in (("nightly.yml", "unsigned"), ("nightly-sign.yml", "release")): + jobs = (ROOT / ".github/workflows" / name).read_text().split("\njobs:\n", 1)[1] + with self.subTest(workflow=name): + self.assertEqual(re.findall(r"(?m)^ ([^\s#][^:]*):", jobs), [job], + "a platform is a list entry, not a separately activatable job") + signer = (ROOT / ".github/workflows/nightly-sign.yml").read_text() + self.assertNotRegex(signer, r"(?m)^\s*platforms?:", "the release policy, not the caller, admits platforms") + + def test_malformed_or_narrowed_platform_lists_are_rejected(self): + source = (ROOT / ".github/workflows/nightly.yml").read_text() + current = "platforms: '[\"windows-x86_64\",\"linux-x86_64\",\"macos-aarch64\"]'" + self.assertIn(current, source) + for new in ("platforms: '[\"linux-x86_64\"]'", + "platforms: '[\"linux-x86_64\",\"macos-aarch64\"]'", + "platforms: '[\"windows-x86_64\",\"linux-x86_64\",\"linux-x86_64\"]'", + "platforms: '[\"windows-x86_64\",\"macos-x86_64\"]'", + "platforms: '[\"windows-x86_64\",\"linux-arm64\"]'", + "platforms: '[\"windows-x86_64\", \"linux-x86_64\"]'", + "platforms: [\"windows-x86_64\",\"linux-x86_64\"]", + "platforms: ${{ vars.NIGHTLY_PLATFORMS }}", + "platforms: '{\"windows-x86_64\":1}'", + current + "\n " + current): + with self.subTest(change=new), self.assertRaises(ValueError): + producer_platforms(source.replace(current, new)) + with self.assertRaises(ValueError): + producer_platforms(source.replace(" " + current + "\n", "")) + + def test_dormancy_guard_rejects_activation_and_top_level_or(self): + for condition in ("true", "vars.ENABLE_NIGHTLY", "false || true", "false && true || true", + "false && (true || true", "false && true) || true"): + with self.subTest(condition=condition): + self.assertFalse(literal_off(condition)) + self.assertTrue(literal_off("${{ false }}")) + self.assertTrue(literal_off("false && (github.event_name == 'schedule' || github.event_name == 'workflow_dispatch')")) + + def test_no_nightly_schedule_is_registered(self): + for name, event in (("nightly.yml", "workflow_dispatch"), + ("nightly-dispatch.yml", "workflow_run"), + ("nightly-sign.yml", "workflow_dispatch")): + source = (ROOT / ".github/workflows" / name).read_text() + events = source.split("\non:\n", 1)[1].split("\npermissions:", 1)[0] + triggers = [line for line in events.splitlines() if line.startswith(" ") + and not line.startswith(" ") and line.strip() and not line.lstrip().startswith("#")] + with self.subTest(workflow=name): + self.assertEqual(triggers, [f" {event}:"], "schedule/activation needs explicit review") + + def test_signer_serialization_contract_is_enforced(self): + assert_nightly_serialization((ROOT / ".github/workflows/nightly-sign.yml").read_text()) + + def test_weakened_or_malformed_serialization_is_rejected(self): + source = (ROOT / ".github/workflows/nightly-sign.yml").read_text() + for old, new in ( + ("queue: max", "queue: single"), + ("queue: max", "queue: invalid"), + ("queue: max", "queue: ${{ github.run_id }}"), + ("queue: max", "queue:"), + ("queue: max", "queue: max\n queue: single"), + ("cancel-in-progress: false", "cancel-in-progress: true"), + ("cancel-in-progress: false", "cancel-in-progress: ${{ github.event_name == 'push' }}"), + ("cancel-in-progress: false\n", ""), + ("group: photocraft-nightly-release", "group: ${{ github.run_id }}"), + ("group: photocraft-nightly-release", "group: release-${{ github.ref }}"), + ("concurrency:\n", "concurrency: ${{ github.run_id }}\n"), + ("concurrency:\n", " concurrency:\n"), + ): + with self.subTest(change=new), self.assertRaises(ValueError): + assert_nightly_serialization(source.replace(old, new)) + + 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.yml", "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) + + +class NightlyTrustAnchors(unittest.TestCase): + """The public stable identities each platform's signed nightly must carry (all three platforms).""" + + def setUp(self): + self.policy = json.loads((ROOT / "docs/nightly-signing-policy.example.json").read_text()) + + def test_each_platform_row_names_its_fixed_artifact_kind_and_stable_identity(self): + self.assertEqual(set(self.policy["platforms"]), set(NIGHTLY_TRUST)) + for platform, (field, value) in NIGHTLY_TRUST.items(): + row = self.policy["platforms"][platform] + with self.subTest(platform=platform): + self.assertEqual(row["unsigned_artifact_name"], f"nightly-unsigned-{platform}", + "the artifact kind is fixed by platform, never a caller pattern") + self.assertEqual(row["trust"], {field: value}, "trust must be stable's public identity") + + def test_trust_values_have_the_shapes_the_shared_signer_accepts(self): + rows = self.policy["platforms"] + self.assertRegex(rows["macos-aarch64"]["trust"]["apple_team_id"], r"^[A-Z0-9]{10}$") + self.assertRegex(rows["linux-x86_64"]["trust"]["fingerprint"], r"^[0-9A-F]{40}$") + subject = rows["windows-x86_64"]["trust"]["publisher_subject"] + self.assertTrue(0 < len(subject) <= 2048 and not set(subject) & {"\r", "\n", "\0"}) + + def test_committed_linux_key_is_exactly_the_one_stable_public_key(self): + self.assertFalse(LINUX_KEY.is_symlink(), "the key file must be a regular committed file") + armored = LINUX_KEY.read_text(encoding="ascii") + self.assertEqual(armored.count("-----BEGIN PGP"), 1, "exactly one armored block") + self.assertEqual(openpgp_primary_fingerprints(armored), [NIGHTLY_TRUST["linux-x86_64"][1]], + "exactly one primary key, and it is the stable release key the policy trusts") + + def test_key_reader_refuses_secret_or_extra_material(self): + armored = LINUX_KEY.read_text(encoding="ascii") + for change in (armored.replace("PUBLIC KEY BLOCK", "PRIVATE KEY BLOCK"), + armored.replace("-----END PGP PUBLIC KEY BLOCK-----\n", ""), + "Comment: extra\n" + armored): + with self.subTest(change=change[:40]), self.assertRaises(ValueError): + openpgp_primary_fingerprints(change) + + def test_both_callers_use_one_shared_pin_in_uses_and_tooling_revision(self): + pins = set() + for name, callee in (("nightly.yml", "nightly-unsigned.yml"), ("nightly-sign.yml", "nightly-release.yml")): + source = (ROOT / ".github/workflows" / name).read_text() + uses = re.findall(r"(?m)^ uses: storytold/craft-common-actions/\.github/workflows/" + + re.escape(callee) + r"@(\S+)$", source) + tooling = re.findall(r"(?m)^ tooling-revision: (\S+)$", source) + with self.subTest(workflow=name): + self.assertEqual(len(uses), 1) + self.assertEqual(tooling, uses, "the defining workflow SHA and tooling input must match") + pins.update(uses) + self.assertEqual(len(pins), 1, "producer and signer must pin the same shared commit") + self.assertRegex(pins.pop(), r"^[0-9a-f]{40}$", "pin a full immutable commit, never a branch or placeholder") + + +if __name__ == "__main__": + unittest.main(verbosity=2) diff --git a/packaging/nightly-tests.py b/packaging/nightly-tests.py index b8b673b491..545e08ef67 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"), ("photo_mac_sign_suite", "macos/nightly_sign_tests.py"), ): spec = importlib.util.spec_from_file_location(name, here / relative) diff --git a/sonar-project.properties b/sonar-project.properties index 9f88b6726c..06cf28e7b0 100644 --- a/sonar-project.properties +++ b/sonar-project.properties @@ -4,5 +4,5 @@ sonar.organization=storytold sonar.sources=. # These exact fixture runners are tests, not production code. Do not exclude helpers. sonar.tests=packaging -sonar.test.inclusions=packaging/nightly-tests.py,packaging/nightly-archive-tests.py,packaging/macos/nightly_plist_tests.py,packaging/macos/nightly_sign_tests.py,packaging/windows/nightly-package-tests.ps1,packaging/windows/nightly-signing-tests.ps1 +sonar.test.inclusions=packaging/nightly-tests.py,packaging/nightly-archive-tests.py,packaging/macos/nightly_plist_tests.py,packaging/macos/nightly_sign_tests.py,packaging/windows/nightly-package-tests.ps1,packaging/windows/nightly-signing-tests.ps1,packaging/nightly-release-tests.py sonar.python.coverage.reportPaths=python-coverage.xml