mirror of
https://github.com/storytold/craft-common-actions.git
synced 2026-11-28 13:58:10 -08:00
nightly: add Linux and macOS to the PhotoCraft nightly signer (switched off) (#342)
* nightly: add Linux and macOS to the PhotoCraft nightly signer (switched off) * Address CodeRabbit on the Linux and macOS nightly signer * Apply the metadata size limit only to JSON metadata, not Linux tarballs
This commit is contained in:
1 parent
504b7852c7
commit
a4f6fd51e8
38 files changed
+3984
-521
No files matched your search
@@ -1,6 +1,7 @@
|
||||
name: Windows release-ref nightly signer
|
||||
name: Release-ref nightly signer
|
||||
# No push, schedule, workflow_run or workflow_dispatch entry point here.
|
||||
# Only the protected app caller can satisfy the real release-ref admission.
|
||||
# One release carries every admitted platform: all sign/verify jobs must succeed.
|
||||
on:
|
||||
workflow_call:
|
||||
inputs:
|
||||
@@ -25,7 +26,7 @@ jobs:
|
||||
validate:
|
||||
if: github.repository == 'storytold/photocraft' && github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/release' && github.ref_type == 'branch'
|
||||
runs-on: windows-latest
|
||||
timeout-minutes: 15
|
||||
timeout-minutes: 20
|
||||
permissions:
|
||||
contents: read
|
||||
actions: read
|
||||
@@ -33,9 +34,9 @@ jobs:
|
||||
attestations: read
|
||||
outputs:
|
||||
admitted: ${{ steps.admit.outputs.admitted }}
|
||||
platforms: ${{ steps.admit.outputs.platforms }}
|
||||
artifact-id: ${{ steps.upload.outputs.artifact-id }}
|
||||
bundle-sha256: ${{ steps.validate.outputs.bundle-sha256 }}
|
||||
unsigned-asset: ${{ steps.validate.outputs.unsigned-asset }}
|
||||
steps:
|
||||
- name: Check out only the actual release execution source
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
@@ -50,7 +51,7 @@ jobs:
|
||||
DEFINING_SHA: ${{ job.workflow_sha }}
|
||||
run: |
|
||||
if ((git -C .release-source rev-parse HEAD) -cne $env:GITHUB_SHA) { throw 'release source differs from real execution SHA' }
|
||||
python -I -B -c "import os,json,re; p=os.environ['TOOLING_REVISION']; assert re.fullmatch('[0-9a-f]{40}',p) and p!='0'*40; assert os.environ['DEFINING_REPOSITORY']=='storytold/craft-common-actions'; assert os.environ['DEFINING_SHA']==p; config=json.load(open('.release-source/.github/nightly-signing-policy.json')); assert config['schema']=='craft-nightly-release-policy/v2'; assert config['signer_tooling_revision']==p"
|
||||
python -I -B -c "import os,json,re; p=os.environ['TOOLING_REVISION']; assert re.fullmatch('[0-9a-f]{40}',p) and p!='0'*40; assert os.environ['DEFINING_REPOSITORY']=='storytold/craft-common-actions'; assert os.environ['DEFINING_SHA']==p; config=json.load(open('.release-source/.github/nightly-signing-policy.json')); assert config['schema']=='craft-nightly-release-policy/v3'; assert config['signer_tooling_revision']==p"
|
||||
if ($LASTEXITCODE -ne 0) { throw 'protected policy/tooling binding refused' }
|
||||
- name: Check out only the defining shared workflow revision
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
@@ -69,18 +70,41 @@ jobs:
|
||||
run: |
|
||||
python -I -B .nightly-tools/scripts/nightly_release_entry.py admit --source .release-source --producer-run-id "$env:PRODUCER_RUN_ID" --producer-run-attempt "$env:PRODUCER_RUN_ATTEMPT" --output .admission
|
||||
if ($LASTEXITCODE -ne 0) { throw 'producer/quality admission refused' }
|
||||
- name: Download exact authenticated producer artifact; verify transport ZIP digest
|
||||
if: steps.admit.outputs.admitted == 'true'
|
||||
# One exact authenticated artifact ID per admitted platform, each into its own directory.
|
||||
- name: Download exact authenticated Windows producer artifact; verify transport ZIP digest
|
||||
if: steps.admit.outputs.admitted == 'true' && contains(fromJSON(steps.admit.outputs.platforms), 'windows-x86_64')
|
||||
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
|
||||
with:
|
||||
github-token: ${{ github.token }}
|
||||
repository: ${{ github.repository }}
|
||||
run-id: ${{ inputs.producer_run_id }}
|
||||
artifact-ids: ${{ steps.admit.outputs.artifact-id }}
|
||||
path: .unsigned
|
||||
artifact-ids: ${{ steps.admit.outputs.artifact-id-windows-x86_64 }}
|
||||
path: .unsigned/windows-x86_64
|
||||
merge-multiple: true
|
||||
digest-mismatch: error
|
||||
- name: Verify unsigned payload with trusted patched gh, then revalidate admission
|
||||
- name: Download exact authenticated macOS producer artifact; verify transport ZIP digest
|
||||
if: steps.admit.outputs.admitted == 'true' && contains(fromJSON(steps.admit.outputs.platforms), 'macos-aarch64')
|
||||
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
|
||||
with:
|
||||
github-token: ${{ github.token }}
|
||||
repository: ${{ github.repository }}
|
||||
run-id: ${{ inputs.producer_run_id }}
|
||||
artifact-ids: ${{ steps.admit.outputs.artifact-id-macos-aarch64 }}
|
||||
path: .unsigned/macos-aarch64
|
||||
merge-multiple: true
|
||||
digest-mismatch: error
|
||||
- name: Download exact authenticated Linux producer artifact; verify transport ZIP digest
|
||||
if: steps.admit.outputs.admitted == 'true' && contains(fromJSON(steps.admit.outputs.platforms), 'linux-x86_64')
|
||||
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
|
||||
with:
|
||||
github-token: ${{ github.token }}
|
||||
repository: ${{ github.repository }}
|
||||
run-id: ${{ inputs.producer_run_id }}
|
||||
artifact-ids: ${{ steps.admit.outputs.artifact-id-linux-x86_64 }}
|
||||
path: .unsigned/linux-x86_64
|
||||
merge-multiple: true
|
||||
digest-mismatch: error
|
||||
- name: Verify every unsigned payload with trusted patched gh, then revalidate admission
|
||||
if: steps.admit.outputs.admitted == 'true'
|
||||
id: validate
|
||||
shell: pwsh
|
||||
@@ -99,9 +123,9 @@ jobs:
|
||||
include-hidden-files: true
|
||||
if-no-files-found: error
|
||||
retention-days: 14
|
||||
sign:
|
||||
sign-windows:
|
||||
needs: validate
|
||||
if: needs.validate.outputs.admitted == 'true' && github.repository == 'storytold/photocraft' && github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/release' && github.ref_type == 'branch'
|
||||
if: needs.validate.outputs.admitted == 'true' && contains(fromJSON(needs.validate.outputs.platforms), 'windows-x86_64') && github.repository == 'storytold/photocraft' && github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/release' && github.ref_type == 'branch'
|
||||
runs-on: windows-latest
|
||||
timeout-minutes: 20
|
||||
environment: release
|
||||
@@ -113,7 +137,6 @@ jobs:
|
||||
outputs:
|
||||
artifact-id: ${{ steps.upload.outputs.artifact-id }}
|
||||
bundle-sha256: ${{ steps.sign.outputs.bundle-sha256 }}
|
||||
asset: ${{ steps.sign.outputs.asset }}
|
||||
steps:
|
||||
- name: Check out only the actual release execution source
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
@@ -128,7 +151,7 @@ jobs:
|
||||
DEFINING_SHA: ${{ job.workflow_sha }}
|
||||
run: |
|
||||
if ((git -C .release-source rev-parse HEAD) -cne $env:GITHUB_SHA) { throw 'release source differs from real execution SHA' }
|
||||
python -I -B -c "import os,json,re; p=os.environ['TOOLING_REVISION']; assert re.fullmatch('[0-9a-f]{40}',p) and p!='0'*40; assert os.environ['DEFINING_REPOSITORY']=='storytold/craft-common-actions'; assert os.environ['DEFINING_SHA']==p; config=json.load(open('.release-source/.github/nightly-signing-policy.json')); assert config['schema']=='craft-nightly-release-policy/v2'; assert config['signer_tooling_revision']==p"
|
||||
python -I -B -c "import os,json,re; p=os.environ['TOOLING_REVISION']; assert re.fullmatch('[0-9a-f]{40}',p) and p!='0'*40; assert os.environ['DEFINING_REPOSITORY']=='storytold/craft-common-actions'; assert os.environ['DEFINING_SHA']==p; config=json.load(open('.release-source/.github/nightly-signing-policy.json')); assert config['schema']=='craft-nightly-release-policy/v3'; assert config['signer_tooling_revision']==p"
|
||||
if ($LASTEXITCODE -ne 0) { throw 'protected policy/tooling binding refused' }
|
||||
- name: Check out only the defining shared workflow revision
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
@@ -148,17 +171,15 @@ jobs:
|
||||
shell: pwsh
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
EXACT_ASSET: ${{ needs.validate.outputs.unsigned-asset }}
|
||||
EXPECTED_BUNDLE_SHA256: ${{ needs.validate.outputs.bundle-sha256 }}
|
||||
run: |
|
||||
python -I -B .nightly-tools/scripts/nightly_release_entry.py guard --source .release-source --directory .validated --asset "$env:EXACT_ASSET" --expected-sha256 "$env:EXPECTED_BUNDLE_SHA256"
|
||||
python -I -B .nightly-tools/scripts/nightly_release_entry.py guard --source .release-source --platform windows-x86_64 --directory .validated --expected-sha256 "$env:EXPECTED_BUNDLE_SHA256"
|
||||
if ($LASTEXITCODE -ne 0) { throw 'pre-secret signing gate refused' }
|
||||
- name: Sign data only through protected existing Windows adapter
|
||||
id: sign
|
||||
shell: pwsh
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
EXACT_ASSET: ${{ needs.validate.outputs.unsigned-asset }}
|
||||
EXPECTED_BUNDLE_SHA256: ${{ needs.validate.outputs.bundle-sha256 }}
|
||||
WINDOWS_CERTIFICATE: ${{ secrets.WINDOWS_CERTIFICATE }}
|
||||
WINDOWS_CERTIFICATE_PASSWORD: ${{ secrets.WINDOWS_CERTIFICATE_PASSWORD }}
|
||||
@@ -169,25 +190,354 @@ jobs:
|
||||
AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }}
|
||||
AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }}
|
||||
run: |
|
||||
python -I -B .nightly-tools/scripts/nightly_release_entry.py sign --source .release-source --directory .validated --asset "$env:EXACT_ASSET" --expected-sha256 "$env:EXPECTED_BUNDLE_SHA256" --output .signed
|
||||
python -I -B .nightly-tools/scripts/nightly_release_entry.py sign --source .release-source --platform windows-x86_64 --directory .validated --expected-sha256 "$env:EXPECTED_BUNDLE_SHA256" --output .signed
|
||||
if ($LASTEXITCODE -ne 0) { throw 'mandatory native signing/verification refused' }
|
||||
- name: Upload only finite signed bytes and two-role receipts
|
||||
id: upload
|
||||
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
with:
|
||||
name: nightly-release-signed-${{ github.run_id }}-${{ github.run_attempt }}
|
||||
name: nightly-release-signed-windows-x86_64-${{ github.run_id }}-${{ github.run_attempt }}
|
||||
path: .signed/*
|
||||
include-hidden-files: true
|
||||
if-no-files-found: error
|
||||
retention-days: 14
|
||||
sign-macos:
|
||||
needs: validate
|
||||
if: needs.validate.outputs.admitted == 'true' && contains(fromJSON(needs.validate.outputs.platforms), 'macos-aarch64') && github.repository == 'storytold/photocraft' && github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/release' && github.ref_type == 'branch'
|
||||
# Same Apple route and `release` environment as the stable macOS job.
|
||||
runs-on: macos-15
|
||||
timeout-minutes: 120
|
||||
environment: release
|
||||
permissions:
|
||||
contents: read
|
||||
actions: read
|
||||
checks: read
|
||||
attestations: read
|
||||
outputs:
|
||||
artifact-id: ${{ steps.upload.outputs.artifact-id }}
|
||||
bundle-sha256: ${{ steps.sign.outputs.bundle-sha256 }}
|
||||
steps:
|
||||
- name: Select Python for nightly helpers
|
||||
uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6
|
||||
with:
|
||||
python-version: '3.13'
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
|
||||
with:
|
||||
egress-policy: audit
|
||||
- name: Check out only the actual release execution source
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
ref: ${{ github.sha }}
|
||||
path: .release-source
|
||||
persist-credentials: false
|
||||
- name: Bind protected policy and actual immutable defining workflow
|
||||
shell: bash
|
||||
env:
|
||||
DEFINING_REPOSITORY: ${{ job.workflow_repository }}
|
||||
DEFINING_SHA: ${{ job.workflow_sha }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
test "$(git -C .release-source rev-parse HEAD)" = "$GITHUB_SHA" || { echo 'release source differs from real execution SHA'; exit 1; }
|
||||
python3 -I -B -c "import os,json,re; p=os.environ['TOOLING_REVISION']; assert re.fullmatch('[0-9a-f]{40}',p) and p!='0'*40; assert os.environ['DEFINING_REPOSITORY']=='storytold/craft-common-actions'; assert os.environ['DEFINING_SHA']==p; config=json.load(open('.release-source/.github/nightly-signing-policy.json')); assert config['schema']=='craft-nightly-release-policy/v3'; assert config['signer_tooling_revision']==p"
|
||||
- name: Check out only the defining shared workflow revision
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
repository: ${{ job.workflow_repository }}
|
||||
ref: ${{ job.workflow_sha }}
|
||||
path: .nightly-tools
|
||||
persist-credentials: false
|
||||
- name: Download only the trusted same-run validator artifact
|
||||
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
|
||||
with:
|
||||
artifact-ids: ${{ needs.validate.outputs.artifact-id }}
|
||||
path: .validated
|
||||
merge-multiple: true
|
||||
digest-mismatch: error
|
||||
- name: Recheck real ref, quality, pause and freshness before raw signing-secret exports
|
||||
shell: bash
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
EXPECTED_BUNDLE_SHA256: ${{ needs.validate.outputs.bundle-sha256 }}
|
||||
run: python3 -I -B .nightly-tools/scripts/nightly_release_entry.py guard --source .release-source --platform macos-aarch64 --directory .validated --expected-sha256 "$EXPECTED_BUNDLE_SHA256"
|
||||
- name: Sign, notarize and staple data only through the protected app macOS adapter
|
||||
id: sign
|
||||
shell: bash
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
EXPECTED_BUNDLE_SHA256: ${{ needs.validate.outputs.bundle-sha256 }}
|
||||
APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
|
||||
APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
|
||||
KEYCHAIN_PASSWORD: ${{ secrets.KEYCHAIN_PASSWORD }}
|
||||
APPLE_ID: ${{ secrets.APPLE_ID }}
|
||||
APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
|
||||
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
|
||||
run: python3 -I -B .nightly-tools/scripts/nightly_release_entry.py sign --source .release-source --platform macos-aarch64 --directory .validated --expected-sha256 "$EXPECTED_BUNDLE_SHA256" --output .signed
|
||||
- name: Upload only finite signed bytes and two-role receipts
|
||||
id: upload
|
||||
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
with:
|
||||
name: nightly-release-signed-macos-aarch64-${{ github.run_id }}-${{ github.run_attempt }}
|
||||
path: .signed/*
|
||||
include-hidden-files: true
|
||||
if-no-files-found: error
|
||||
retention-days: 14
|
||||
verify-macos:
|
||||
needs: [validate, sign-macos]
|
||||
if: needs.validate.outputs.admitted == 'true' && contains(fromJSON(needs.validate.outputs.platforms), 'macos-aarch64') && github.repository == 'storytold/photocraft' && github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/release' && github.ref_type == 'branch'
|
||||
# Fresh runner, NO release environment or platform secrets.
|
||||
runs-on: macos-15
|
||||
timeout-minutes: 20
|
||||
permissions:
|
||||
contents: read
|
||||
actions: read
|
||||
checks: read
|
||||
attestations: read
|
||||
outputs:
|
||||
final-sha256: ${{ steps.verify.outputs.final-sha256 }}
|
||||
asset: ${{ steps.verify.outputs.asset }}
|
||||
steps:
|
||||
- name: Select Python for nightly helpers
|
||||
uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6
|
||||
with:
|
||||
python-version: '3.13'
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
|
||||
with:
|
||||
egress-policy: audit
|
||||
- name: Check out only the actual release execution source
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
ref: ${{ github.sha }}
|
||||
path: .release-source
|
||||
persist-credentials: false
|
||||
- name: Bind protected policy and actual immutable defining workflow
|
||||
shell: bash
|
||||
env:
|
||||
DEFINING_REPOSITORY: ${{ job.workflow_repository }}
|
||||
DEFINING_SHA: ${{ job.workflow_sha }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
test "$(git -C .release-source rev-parse HEAD)" = "$GITHUB_SHA" || { echo 'release source differs from real execution SHA'; exit 1; }
|
||||
python3 -I -B -c "import os,json,re; p=os.environ['TOOLING_REVISION']; assert re.fullmatch('[0-9a-f]{40}',p) and p!='0'*40; assert os.environ['DEFINING_REPOSITORY']=='storytold/craft-common-actions'; assert os.environ['DEFINING_SHA']==p; config=json.load(open('.release-source/.github/nightly-signing-policy.json')); assert config['schema']=='craft-nightly-release-policy/v3'; assert config['signer_tooling_revision']==p"
|
||||
- name: Check out only the defining shared workflow revision
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
repository: ${{ job.workflow_repository }}
|
||||
ref: ${{ job.workflow_sha }}
|
||||
path: .nightly-tools
|
||||
persist-credentials: false
|
||||
- name: Download only exact signer-produced macOS artifact ID
|
||||
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
|
||||
with:
|
||||
artifact-ids: ${{ needs.sign-macos.outputs.artifact-id }}
|
||||
path: .signed/macos-aarch64
|
||||
merge-multiple: true
|
||||
digest-mismatch: error
|
||||
- name: Independently verify Developer ID, team, runtime, timestamp, staple and Gatekeeper
|
||||
id: verify
|
||||
shell: bash
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
EXPECTED_BUNDLE_SHA256: ${{ needs.sign-macos.outputs.bundle-sha256 }}
|
||||
run: python3 -I -B .nightly-tools/scripts/nightly_release_entry.py verify-platform --source .release-source --platform macos-aarch64 --directory .signed/macos-aarch64 --expected-sha256 "$EXPECTED_BUNDLE_SHA256"
|
||||
smoke-macos:
|
||||
needs: [validate, sign-macos, verify-macos]
|
||||
if: needs.validate.outputs.admitted == 'true' && contains(fromJSON(needs.validate.outputs.platforms), 'macos-aarch64') && github.repository == 'storytold/photocraft' && github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/release' && github.ref_type == 'branch'
|
||||
# The only job that runs signed payload code: no environment, secrets, tokens or
|
||||
# outputs the publisher consumes. Hardened runtime only applies once signed.
|
||||
runs-on: macos-15
|
||||
timeout-minutes: 15
|
||||
permissions:
|
||||
contents: read
|
||||
steps:
|
||||
- name: Select Python for nightly helpers
|
||||
uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6
|
||||
with:
|
||||
python-version: '3.13'
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
|
||||
with:
|
||||
egress-policy: audit
|
||||
- name: Check out only the actual release execution source
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
ref: ${{ github.sha }}
|
||||
path: .release-source
|
||||
persist-credentials: false
|
||||
- name: Bind protected policy and actual immutable defining workflow
|
||||
shell: bash
|
||||
env:
|
||||
DEFINING_REPOSITORY: ${{ job.workflow_repository }}
|
||||
DEFINING_SHA: ${{ job.workflow_sha }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
test "$(git -C .release-source rev-parse HEAD)" = "$GITHUB_SHA" || { echo 'release source differs from real execution SHA'; exit 1; }
|
||||
python3 -I -B -c "import os,json,re; p=os.environ['TOOLING_REVISION']; assert re.fullmatch('[0-9a-f]{40}',p) and p!='0'*40; assert os.environ['DEFINING_REPOSITORY']=='storytold/craft-common-actions'; assert os.environ['DEFINING_SHA']==p; config=json.load(open('.release-source/.github/nightly-signing-policy.json')); assert config['schema']=='craft-nightly-release-policy/v3'; assert config['signer_tooling_revision']==p"
|
||||
- name: Download only exact signer-produced macOS artifact ID
|
||||
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
|
||||
with:
|
||||
artifact-ids: ${{ needs.sign-macos.outputs.artifact-id }}
|
||||
path: .signed/macos-aarch64
|
||||
merge-multiple: true
|
||||
digest-mismatch: error
|
||||
- name: Launch the exact verified signed app once, secret-free, through the app verifier
|
||||
shell: bash
|
||||
env:
|
||||
ASSET: ${{ needs.verify-macos.outputs.asset }}
|
||||
FINAL_SHA256: ${{ needs.verify-macos.outputs.final-sha256 }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
[[ "$ASSET" =~ ^photocraft-[0-9A-Za-z.-]+-macos-aarch64-nightly[.]zip$ ]]
|
||||
final="$PWD/.signed/macos-aarch64/$ASSET"
|
||||
test -f "$final" && test ! -L "$final"
|
||||
test "$(shasum -a 256 "$final" | cut -d' ' -f1)" = "$FINAL_SHA256"
|
||||
team="$(git -C .release-source show HEAD:.github/nightly-signing-policy.json | python3 -I -c "import json,re,sys; t=json.load(sys.stdin)['platforms']['macos-aarch64']['trust']['apple_team_id']; assert re.fullmatch('[A-Z0-9]{10}',t); print(t)")"
|
||||
bash .release-source/packaging/macos/nightly-verify.sh --input "$final" --expect signed --team "$team"
|
||||
sign-linux:
|
||||
# Linux signs on Ubuntu with the existing stable LINUX_SIGNING_KEY in the release environment,
|
||||
# exposed only to the single sign step. Never builds, extracts or runs the payload.
|
||||
needs: validate
|
||||
if: >-
|
||||
needs.validate.outputs.admitted == 'true' && contains(fromJSON(needs.validate.outputs.platforms), 'linux-x86_64') &&
|
||||
github.repository == 'storytold/photocraft' && github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/release' && github.ref_type == 'branch'
|
||||
runs-on: ubuntu-22.04
|
||||
timeout-minutes: 20
|
||||
environment: release
|
||||
permissions:
|
||||
contents: read
|
||||
actions: read
|
||||
checks: read
|
||||
attestations: read
|
||||
outputs:
|
||||
artifact-id: ${{ steps.upload.outputs.artifact-id }}
|
||||
bundle-sha256: ${{ steps.sign.outputs.bundle-sha256 }}
|
||||
final-sha256: ${{ steps.sign.outputs.final-sha256 }}
|
||||
steps:
|
||||
- name: Select Python for nightly helpers
|
||||
uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6
|
||||
with:
|
||||
python-version: '3.13'
|
||||
- name: Check out only the actual release execution source
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
ref: ${{ github.sha }}
|
||||
path: .release-source
|
||||
persist-credentials: false
|
||||
- name: Bind protected policy and actual immutable defining workflow
|
||||
env:
|
||||
DEFINING_REPOSITORY: ${{ job.workflow_repository }}
|
||||
DEFINING_SHA: ${{ job.workflow_sha }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
test "$(git -C .release-source rev-parse HEAD)" = "$GITHUB_SHA"
|
||||
python3 -I -B -c "import os,json,re; p=os.environ['TOOLING_REVISION']; assert re.fullmatch('[0-9a-f]{40}',p) and p!='0'*40; assert os.environ['DEFINING_REPOSITORY']=='storytold/craft-common-actions'; assert os.environ['DEFINING_SHA']==p; config=json.load(open('.release-source/.github/nightly-signing-policy.json')); assert config['schema']=='craft-nightly-release-policy/v3'; assert config['signer_tooling_revision']==p; assert 'linux-x86_64' in config['platforms']"
|
||||
- name: Check out only the defining shared workflow revision
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
repository: ${{ job.workflow_repository }}
|
||||
ref: ${{ job.workflow_sha }}
|
||||
path: .nightly-tools
|
||||
persist-credentials: false
|
||||
- name: Download only the trusted same-run validator artifact
|
||||
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
|
||||
with:
|
||||
artifact-ids: ${{ needs.validate.outputs.artifact-id }}
|
||||
path: .validated
|
||||
merge-multiple: true
|
||||
digest-mismatch: error
|
||||
- name: Recheck real ref, quality, pause and freshness before the signing secret is exposed
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
EXPECTED_BUNDLE_SHA256: ${{ needs.validate.outputs.bundle-sha256 }}
|
||||
run: python3 -I -B .nightly-tools/scripts/nightly_release_entry.py guard --platform linux-x86_64 --source .release-source --directory .validated --expected-sha256 "$EXPECTED_BUNDLE_SHA256"
|
||||
- name: Sign data only with the existing stable OpenPGP key (detached .asc)
|
||||
id: sign
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
EXPECTED_BUNDLE_SHA256: ${{ needs.validate.outputs.bundle-sha256 }}
|
||||
LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }}
|
||||
run: python3 -I -B .nightly-tools/scripts/nightly_release_entry.py sign --platform linux-x86_64 --source .release-source --directory .validated --expected-sha256 "$EXPECTED_BUNDLE_SHA256" --output .signed
|
||||
- name: Upload only finite signed bytes, detached signature support and receipts
|
||||
id: upload
|
||||
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
with:
|
||||
name: nightly-release-signed-linux-x86_64-${{ github.run_id }}-${{ github.run_attempt }}
|
||||
path: .signed/*
|
||||
include-hidden-files: true
|
||||
if-no-files-found: error
|
||||
retention-days: 14
|
||||
verify-linux:
|
||||
# Fresh keyless runner: no release environment or secrets. gpgv trusts only the
|
||||
# reviewed key in release source and the policy fingerprint, never the release asset.
|
||||
needs: [validate, sign-linux]
|
||||
if: >-
|
||||
needs.sign-linux.result == 'success' && contains(fromJSON(needs.validate.outputs.platforms), 'linux-x86_64') &&
|
||||
github.repository == 'storytold/photocraft' && github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/release' && github.ref_type == 'branch'
|
||||
runs-on: ubuntu-22.04
|
||||
timeout-minutes: 15
|
||||
permissions:
|
||||
contents: read
|
||||
actions: read
|
||||
checks: read
|
||||
attestations: read
|
||||
outputs:
|
||||
final-sha256: ${{ steps.verify.outputs.final-sha256 }}
|
||||
steps:
|
||||
- name: Select Python for nightly helpers
|
||||
uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6
|
||||
with:
|
||||
python-version: '3.13'
|
||||
- name: Check out only the actual release execution source
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
ref: ${{ github.sha }}
|
||||
path: .release-source
|
||||
persist-credentials: false
|
||||
- name: Bind protected policy and actual immutable defining workflow
|
||||
env:
|
||||
DEFINING_REPOSITORY: ${{ job.workflow_repository }}
|
||||
DEFINING_SHA: ${{ job.workflow_sha }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
test "$(git -C .release-source rev-parse HEAD)" = "$GITHUB_SHA"
|
||||
python3 -I -B -c "import os,json,re; p=os.environ['TOOLING_REVISION']; assert re.fullmatch('[0-9a-f]{40}',p) and p!='0'*40; assert os.environ['DEFINING_REPOSITORY']=='storytold/craft-common-actions'; assert os.environ['DEFINING_SHA']==p; config=json.load(open('.release-source/.github/nightly-signing-policy.json')); assert config['schema']=='craft-nightly-release-policy/v3'; assert config['signer_tooling_revision']==p; assert 'linux-x86_64' in config['platforms']"
|
||||
- name: Check out only the defining shared workflow revision
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
repository: ${{ job.workflow_repository }}
|
||||
ref: ${{ job.workflow_sha }}
|
||||
path: .nightly-tools
|
||||
persist-credentials: false
|
||||
- name: Download only the exact signer-produced Linux artifact ID
|
||||
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
|
||||
with:
|
||||
artifact-ids: ${{ needs.sign-linux.outputs.artifact-id }}
|
||||
path: .signed/linux-x86_64
|
||||
merge-multiple: true
|
||||
digest-mismatch: error
|
||||
- name: Independently verify the detached signature, exact bytes and published key without credentials
|
||||
id: verify
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
EXPECTED_BUNDLE_SHA256: ${{ needs.sign-linux.outputs.bundle-sha256 }}
|
||||
run: python3 -I -B .nightly-tools/scripts/nightly_release_entry.py verify-platform --platform linux-x86_64 --source .release-source --directory .signed/linux-x86_64 --expected-sha256 "$EXPECTED_BUNDLE_SHA256"
|
||||
publish:
|
||||
name: Publish signed nightly
|
||||
needs: sign
|
||||
if: github.repository == 'storytold/photocraft' && github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/release' && github.ref_type == 'branch'
|
||||
needs: [validate, sign-windows, sign-macos, verify-macos, smoke-macos, sign-linux, verify-linux]
|
||||
# !cancelled() (not always()) so a skipped NON-admitted platform cannot block while a cancel
|
||||
# still stops release writes; every admitted
|
||||
# platform's jobs must have succeeded, and the bridge refuses a missing digest too.
|
||||
if: >-
|
||||
!cancelled() && needs.validate.result == 'success' && needs.validate.outputs.admitted == 'true' &&
|
||||
(!contains(fromJSON(needs.validate.outputs.platforms), 'windows-x86_64') || needs.sign-windows.result == 'success') &&
|
||||
(!contains(fromJSON(needs.validate.outputs.platforms), 'macos-aarch64') || (needs.sign-macos.result == 'success' && needs.verify-macos.result == 'success' && needs.smoke-macos.result == 'success')) &&
|
||||
(!contains(fromJSON(needs.validate.outputs.platforms), 'linux-x86_64') || (needs.sign-linux.result == 'success' && needs.verify-linux.result == 'success')) &&
|
||||
github.repository == 'storytold/photocraft' && github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/release' && github.ref_type == 'branch'
|
||||
runs-on: windows-latest
|
||||
# Every step has its own bound and the job budget exceeds their sum, so a slow
|
||||
# step fails as a step: the tolerant ownership upload can never time the job out.
|
||||
timeout-minutes: 75
|
||||
timeout-minutes: 95
|
||||
# Fresh Windows verifier, but NO release environment or platform secrets.
|
||||
permissions:
|
||||
contents: write
|
||||
@@ -211,7 +561,7 @@ jobs:
|
||||
DEFINING_SHA: ${{ job.workflow_sha }}
|
||||
run: |
|
||||
if ((git -C .release-source rev-parse HEAD) -cne $env:GITHUB_SHA) { throw 'release source differs from real execution SHA' }
|
||||
python -I -B -c "import os,json,re; p=os.environ['TOOLING_REVISION']; assert re.fullmatch('[0-9a-f]{40}',p) and p!='0'*40; assert os.environ['DEFINING_REPOSITORY']=='storytold/craft-common-actions'; assert os.environ['DEFINING_SHA']==p; config=json.load(open('.release-source/.github/nightly-signing-policy.json')); assert config['schema']=='craft-nightly-release-policy/v2'; assert config['signer_tooling_revision']==p"
|
||||
python -I -B -c "import os,json,re; p=os.environ['TOOLING_REVISION']; assert re.fullmatch('[0-9a-f]{40}',p) and p!='0'*40; assert os.environ['DEFINING_REPOSITORY']=='storytold/craft-common-actions'; assert os.environ['DEFINING_SHA']==p; config=json.load(open('.release-source/.github/nightly-signing-policy.json')); assert config['schema']=='craft-nightly-release-policy/v3'; assert config['signer_tooling_revision']==p"
|
||||
if ($LASTEXITCODE -ne 0) { throw 'protected policy/tooling binding refused' }
|
||||
- name: Check out only the defining shared workflow revision
|
||||
timeout-minutes: 5
|
||||
@@ -221,24 +571,46 @@ jobs:
|
||||
ref: ${{ job.workflow_sha }}
|
||||
path: .nightly-tools
|
||||
persist-credentials: false
|
||||
- name: Download only exact signer-produced artifact ID
|
||||
- name: Download only exact signer-produced Windows artifact ID
|
||||
timeout-minutes: 10
|
||||
if: contains(fromJSON(needs.validate.outputs.platforms), 'windows-x86_64')
|
||||
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
|
||||
with:
|
||||
artifact-ids: ${{ needs.sign.outputs.artifact-id }}
|
||||
path: .signed
|
||||
artifact-ids: ${{ needs.sign-windows.outputs.artifact-id }}
|
||||
path: .signed/windows-x86_64
|
||||
merge-multiple: true
|
||||
digest-mismatch: error
|
||||
- name: Revalidate actual producer and independently verify final native signatures
|
||||
- name: Download only exact signer-produced macOS artifact ID
|
||||
timeout-minutes: 10
|
||||
if: contains(fromJSON(needs.validate.outputs.platforms), 'macos-aarch64')
|
||||
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
|
||||
with:
|
||||
artifact-ids: ${{ needs.sign-macos.outputs.artifact-id }}
|
||||
path: .signed/macos-aarch64
|
||||
merge-multiple: true
|
||||
digest-mismatch: error
|
||||
- name: Download only exact signer-produced Linux artifact ID
|
||||
timeout-minutes: 10
|
||||
if: contains(fromJSON(needs.validate.outputs.platforms), 'linux-x86_64')
|
||||
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
|
||||
with:
|
||||
artifact-ids: ${{ needs.sign-linux.outputs.artifact-id }}
|
||||
path: .signed/linux-x86_64
|
||||
merge-multiple: true
|
||||
digest-mismatch: error
|
||||
- name: Revalidate actual producer, natively verify Windows and bind each fresh platform verifier
|
||||
timeout-minutes: 15
|
||||
id: final
|
||||
shell: pwsh
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
EXACT_ASSET: ${{ needs.sign.outputs.asset }}
|
||||
EXPECTED_BUNDLE_SHA256: ${{ needs.sign.outputs.bundle-sha256 }}
|
||||
SIGNED_BUNDLE_SHA256_WINDOWS_X86_64: ${{ needs.sign-windows.outputs.bundle-sha256 }}
|
||||
SIGNED_BUNDLE_SHA256_MACOS_AARCH64: ${{ needs.sign-macos.outputs.bundle-sha256 }}
|
||||
VERIFIED_FINAL_SHA256_MACOS_AARCH64: ${{ needs.verify-macos.outputs.final-sha256 }}
|
||||
SIGNED_BUNDLE_SHA256_LINUX_X86_64: ${{ needs.sign-linux.outputs.bundle-sha256 }}
|
||||
VERIFIED_FINAL_SHA256_LINUX_X86_64: ${{ needs.verify-linux.outputs.final-sha256 }}
|
||||
run: |
|
||||
python -I -B .nightly-tools/scripts/nightly_release_entry.py final --source .release-source --directory .signed --asset "$env:EXACT_ASSET" --expected-sha256 "$env:EXPECTED_BUNDLE_SHA256"
|
||||
python -I -B .nightly-tools/scripts/nightly_release_entry.py final --source .release-source --directory .signed
|
||||
if ($LASTEXITCODE -ne 0) { throw 'fresh native signature or publication preflight refused' }
|
||||
- name: Attest actual final signed-output bytes from trusted publisher
|
||||
timeout-minutes: 5
|
||||
@@ -251,10 +623,13 @@ jobs:
|
||||
shell: pwsh
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
EXACT_ASSET: ${{ needs.sign.outputs.asset }}
|
||||
EXPECTED_BUNDLE_SHA256: ${{ needs.sign.outputs.bundle-sha256 }}
|
||||
SIGNED_BUNDLE_SHA256_WINDOWS_X86_64: ${{ needs.sign-windows.outputs.bundle-sha256 }}
|
||||
SIGNED_BUNDLE_SHA256_MACOS_AARCH64: ${{ needs.sign-macos.outputs.bundle-sha256 }}
|
||||
VERIFIED_FINAL_SHA256_MACOS_AARCH64: ${{ needs.verify-macos.outputs.final-sha256 }}
|
||||
SIGNED_BUNDLE_SHA256_LINUX_X86_64: ${{ needs.sign-linux.outputs.bundle-sha256 }}
|
||||
VERIFIED_FINAL_SHA256_LINUX_X86_64: ${{ needs.verify-linux.outputs.final-sha256 }}
|
||||
run: |
|
||||
python -I -B .nightly-tools/scripts/nightly_release_entry.py publish --source .release-source --directory .signed --asset "$env:EXACT_ASSET" --expected-sha256 "$env:EXPECTED_BUNDLE_SHA256" --packet .packet --ownership .ownership
|
||||
python -I -B .nightly-tools/scripts/nightly_release_entry.py publish --source .release-source --directory .signed --combined .combined --packet .packet --ownership .ownership
|
||||
if ($LASTEXITCODE -ne 0) { throw 'publication stopped; reconcile any public state before retrying' }
|
||||
- name: Retain only finalized ownership evidence
|
||||
timeout-minutes: 5
|
||||
|
||||
@@ -1,7 +1,22 @@
|
||||
name: Isolated pending Unix nightly signing
|
||||
# No native/registry admission. Called only after separately qualified builds.
|
||||
# Called only by nightly-unix.yml after the secret-free build, and only with production-signing.
|
||||
on:
|
||||
workflow_call:
|
||||
secrets:
|
||||
APPLE_CERTIFICATE:
|
||||
required: false
|
||||
APPLE_CERTIFICATE_PASSWORD:
|
||||
required: false
|
||||
KEYCHAIN_PASSWORD:
|
||||
required: false
|
||||
APPLE_ID:
|
||||
required: false
|
||||
APPLE_PASSWORD:
|
||||
required: false
|
||||
APPLE_TEAM_ID:
|
||||
required: false
|
||||
LINUX_SIGNING_KEY:
|
||||
required: false
|
||||
inputs:
|
||||
manual-actors:
|
||||
description: "Reviewed literal JSON logins in caller source; accidental-use guard only; empty disables manual runs and re-runs"
|
||||
@@ -34,10 +49,18 @@ on:
|
||||
asset:
|
||||
type: string
|
||||
required: true
|
||||
linux-signing-fingerprint:
|
||||
description: "Reviewed full uppercase primary fingerprint of the stable Linux key, committed in caller source; never a repository variable"
|
||||
type: string
|
||||
default: ''
|
||||
production-signing:
|
||||
description: "Opt in to production-signed nightly artifacts (and their publication). Off unless the caller sets true; a caller existing is not consent to sign."
|
||||
type: boolean
|
||||
default: false
|
||||
apple-team-id:
|
||||
description: "Reviewed literal Apple Developer team ID from caller source (public); empty refuses macOS signing"
|
||||
type: string
|
||||
default: ''
|
||||
outputs:
|
||||
artifact-id:
|
||||
value: ${{ jobs.linux.outputs.artifact-id || jobs.macos.outputs.artifact-id }}
|
||||
@@ -66,7 +89,7 @@ jobs:
|
||||
permissions:
|
||||
contents: read
|
||||
env:
|
||||
NIGHTLY_LINUX_SIGNING_FINGERPRINT: ${{ vars.NIGHTLY_LINUX_SIGNING_FINGERPRINT }}
|
||||
NIGHTLY_LINUX_SIGNING_FINGERPRINT: ${{ inputs.linux-signing-fingerprint }}
|
||||
outputs:
|
||||
artifact-id: ${{ steps.upload.outputs.artifact-id }}
|
||||
sha256: ${{ steps.sign.outputs.sha256 }}
|
||||
@@ -202,18 +225,22 @@ jobs:
|
||||
((github.event_name == 'schedule' || github.event_name == 'workflow_dispatch') &&
|
||||
contains(fromJSON(inputs.manual-actors), github.triggering_actor)))
|
||||
runs-on: macos-15
|
||||
timeout-minutes: 90
|
||||
timeout-minutes: 120
|
||||
environment: nightly-signing
|
||||
permissions:
|
||||
contents: read
|
||||
env:
|
||||
NIGHTLY_APPLE_TEAM_ID: ${{ vars.NIGHTLY_APPLE_TEAM_ID }}
|
||||
NIGHTLY_APPLE_TEAM_ID: ${{ inputs.apple-team-id }}
|
||||
outputs:
|
||||
artifact-id: ${{ steps.upload.outputs.artifact-id }}
|
||||
sha256: ${{ steps.sign.outputs.sha256 }}
|
||||
receipt-artifact-id: ${{ steps.receipt.outputs.artifact-id }}
|
||||
receipt-sha256: ${{ steps.sign.outputs.receipt-sha256 }}
|
||||
steps:
|
||||
- name: Select Python for nightly helpers
|
||||
uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6
|
||||
with:
|
||||
python-version: '3.13'
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
|
||||
with:
|
||||
|
||||
@@ -1,9 +1,24 @@
|
||||
name: Private pending Unix nightly artifacts
|
||||
|
||||
# Source preparation only. Native build guards remain false; protected signing is authored, not native proof.
|
||||
# Each job runs only when the app caller opts in with production-signing and lists its platform.
|
||||
# Windows proof, then Linux server, then Skylar Mac is the actual-run order.
|
||||
on:
|
||||
workflow_call:
|
||||
secrets:
|
||||
APPLE_CERTIFICATE:
|
||||
required: false
|
||||
APPLE_CERTIFICATE_PASSWORD:
|
||||
required: false
|
||||
KEYCHAIN_PASSWORD:
|
||||
required: false
|
||||
APPLE_ID:
|
||||
required: false
|
||||
APPLE_PASSWORD:
|
||||
required: false
|
||||
APPLE_TEAM_ID:
|
||||
required: false
|
||||
LINUX_SIGNING_KEY:
|
||||
required: false
|
||||
inputs:
|
||||
manual-actors:
|
||||
description: "Reviewed literal JSON logins in caller source; accidental-use guard only; empty disables manual runs and re-runs"
|
||||
@@ -32,10 +47,35 @@ on:
|
||||
required: false
|
||||
type: string
|
||||
default: bfcbf714e45a3ea8e98f88ab2b7971372a576414
|
||||
linux-signing-fingerprint:
|
||||
description: "Reviewed full uppercase primary fingerprint of the stable Linux key, committed in caller source; never a repository variable"
|
||||
type: string
|
||||
default: ''
|
||||
production-signing:
|
||||
description: "Opt in to production-signed nightly artifacts (and their publication). Off unless the caller sets true; a caller existing is not consent to sign."
|
||||
type: boolean
|
||||
default: false
|
||||
apple-team-id:
|
||||
description: "Reviewed literal Apple Developer team ID from caller source (public); empty refuses macOS signing"
|
||||
type: string
|
||||
default: ''
|
||||
outputs:
|
||||
artifact-id:
|
||||
description: Exact immutable upload ID of the final signed package and any signature support
|
||||
value: ${{ jobs.sign-linux.outputs.artifact-id || jobs.sign-macos.outputs.artifact-id }}
|
||||
sha256:
|
||||
description: Final signed package SHA256
|
||||
value: ${{ jobs.sign-linux.outputs.sha256 || jobs.sign-macos.outputs.sha256 }}
|
||||
asset:
|
||||
description: Exact producer-selected asset name
|
||||
value: ${{ jobs.linux.outputs.asset || jobs.macos.outputs.asset }}
|
||||
unsigned-sha256:
|
||||
description: Original unsigned build producer hash
|
||||
value: ${{ jobs.linux.outputs.sha256 || jobs.macos.outputs.sha256 }}
|
||||
receipt-artifact-id:
|
||||
value: ${{ jobs.sign-linux.outputs.receipt-artifact-id || jobs.sign-macos.outputs.receipt-artifact-id }}
|
||||
receipt-sha256:
|
||||
value: ${{ jobs.sign-linux.outputs.receipt-sha256 || jobs.sign-macos.outputs.receipt-sha256 }}
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
@@ -46,7 +86,12 @@ env:
|
||||
|
||||
jobs:
|
||||
git-sources:
|
||||
if: ${{ false }} # Pending source, not execution authority.
|
||||
if: >-
|
||||
inputs.production-signing == true && inputs.app-name == 'photocraft' && github.repository == 'storytold/photocraft' &&
|
||||
github.ref == 'refs/heads/main' &&
|
||||
((github.event_name == 'schedule' && github.run_attempt == '1') ||
|
||||
((github.event_name == 'schedule' || github.event_name == 'workflow_dispatch') &&
|
||||
contains(fromJSON(inputs.manual-actors), github.triggering_actor)))
|
||||
name: Git dependencies come from storytold
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
@@ -96,7 +141,12 @@ jobs:
|
||||
|
||||
|
||||
linux:
|
||||
if: ${{ false }} # Pending app adapter/native proof; signing source is not admission.
|
||||
if: >-
|
||||
inputs.platform == 'linux-x86_64' && inputs.production-signing == true && inputs.app-name == 'photocraft' && github.repository == 'storytold/photocraft' &&
|
||||
github.ref == 'refs/heads/main' &&
|
||||
((github.event_name == 'schedule' && github.run_attempt == '1') ||
|
||||
((github.event_name == 'schedule' || github.event_name == 'workflow_dispatch') &&
|
||||
contains(fromJSON(inputs.manual-actors), github.triggering_actor)))
|
||||
needs: [git-sources, linux-signing-config]
|
||||
runs-on: ubuntu-22.04
|
||||
timeout-minutes: 90
|
||||
@@ -268,7 +318,12 @@ jobs:
|
||||
retention-days: 14
|
||||
|
||||
macos:
|
||||
if: ${{ false }} # Pending app adapter/native proof; signing source is not admission.
|
||||
if: >-
|
||||
inputs.platform == 'macos-aarch64' && inputs.production-signing == true && inputs.app-name == 'photocraft' && github.repository == 'storytold/photocraft' &&
|
||||
github.ref == 'refs/heads/main' &&
|
||||
((github.event_name == 'schedule' && github.run_attempt == '1') ||
|
||||
((github.event_name == 'schedule' || github.event_name == 'workflow_dispatch') &&
|
||||
contains(fromJSON(inputs.manual-actors), github.triggering_actor)))
|
||||
needs: [git-sources, macos-signing-config]
|
||||
runs-on: macos-15-xlarge
|
||||
timeout-minutes: 90
|
||||
@@ -283,6 +338,10 @@ jobs:
|
||||
CARGO_INCREMENTAL: 0
|
||||
RUST_BACKTRACE: 1
|
||||
steps:
|
||||
- name: Select Python for nightly helpers
|
||||
uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6
|
||||
with:
|
||||
python-version: '3.13'
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a
|
||||
with:
|
||||
@@ -403,17 +462,25 @@ jobs:
|
||||
CRAFT_FONTS_DIR: ${{ github.workspace }}/craft-fonts
|
||||
CRAFT_FONTS_REQUIRED: "1"
|
||||
run: bash packaging/macos/nightly.sh --arch aarch64
|
||||
# check refuses this path until the production signing/team/notarization
|
||||
# policy is explicitly implemented. Inventory is never signature proof.
|
||||
- name: Inspect the exact full-version Mac bundle inventory
|
||||
# Inventory and the ad-hoc --version smoke are never signature proof; Developer ID,
|
||||
# notarization and stapling happen only in the separate protected signing job.
|
||||
- name: Inspect the exact full-version Mac bundle inventory and smoke without secrets
|
||||
shell: bash
|
||||
env:
|
||||
EXACT_VERSION: ${{ steps.contract.outputs.version }}
|
||||
EXACT_ASSET: ${{ steps.contract.outputs.asset }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
python3 -B .nightly-tools/scripts/nightly_unix.py inventory \
|
||||
--pending .nightly-tools/nightly-unix-pending.json --platform macos-aarch64 \
|
||||
--version "$EXACT_VERSION" --archive "$RUNNER_TEMP/nightly-dist/macos-aarch64/$EXACT_ASSET"
|
||||
python3 -B .nightly-tools/scripts/nightly_unix.py unpack-private \
|
||||
--pending .nightly-tools/nightly-unix-pending.json --platform macos-aarch64 \
|
||||
--version "$EXACT_VERSION" --archive "$RUNNER_TEMP/nightly-dist/macos-aarch64/$EXACT_ASSET" \
|
||||
--output "$RUNNER_TEMP/private-nightly-smoke-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}"
|
||||
python3 -B .nightly-tools/scripts/nightly_smoke.py \
|
||||
--executable "$RUNNER_TEMP/private-nightly-smoke-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}/PhotoCraft Nightly.app/Contents/MacOS/PhotoCraft" \
|
||||
--profile-root "$RUNNER_TEMP/private-nightly-profile-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}" --version "$EXACT_VERSION"
|
||||
- name: Hash exact unsigned package before immutable upload
|
||||
id: seal
|
||||
shell: bash
|
||||
@@ -430,7 +497,13 @@ jobs:
|
||||
retention-days: 14
|
||||
|
||||
linux-signing-config:
|
||||
if: ${{ false }} # Pending native adapters; presence preflight only.
|
||||
# Presence preflight only, before secret-free compilation.
|
||||
if: >-
|
||||
inputs.platform == 'linux-x86_64' && inputs.production-signing == true && inputs.app-name == 'photocraft' && github.repository == 'storytold/photocraft' &&
|
||||
github.ref == 'refs/heads/main' &&
|
||||
((github.event_name == 'schedule' && github.run_attempt == '1') ||
|
||||
((github.event_name == 'schedule' || github.event_name == 'workflow_dispatch') &&
|
||||
contains(fromJSON(inputs.manual-actors), github.triggering_actor)))
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
environment: nightly-signing
|
||||
@@ -440,7 +513,7 @@ jobs:
|
||||
- name: Require signing configuration before secret-free compilation
|
||||
env:
|
||||
LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY != '' }}
|
||||
FINGERPRINT: ${{ vars.NIGHTLY_LINUX_SIGNING_FINGERPRINT }}
|
||||
FINGERPRINT: ${{ inputs.linux-signing-fingerprint }}
|
||||
run: |
|
||||
python3 -I -B - <<'PY'
|
||||
import os
|
||||
@@ -450,7 +523,13 @@ jobs:
|
||||
PY
|
||||
|
||||
macos-signing-config:
|
||||
if: ${{ false }} # Pending native adapters; presence preflight only.
|
||||
# Presence preflight only, before secret-free compilation.
|
||||
if: >-
|
||||
inputs.platform == 'macos-aarch64' && inputs.production-signing == true && inputs.app-name == 'photocraft' && github.repository == 'storytold/photocraft' &&
|
||||
github.ref == 'refs/heads/main' &&
|
||||
((github.event_name == 'schedule' && github.run_attempt == '1') ||
|
||||
((github.event_name == 'schedule' || github.event_name == 'workflow_dispatch') &&
|
||||
contains(fromJSON(inputs.manual-actors), github.triggering_actor)))
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
environment: nightly-signing
|
||||
@@ -465,10 +544,13 @@ jobs:
|
||||
APPLE_ID: ${{ secrets.APPLE_ID != '' }}
|
||||
APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD != '' }}
|
||||
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID != '' }}
|
||||
TEAM: ${{ inputs.apple-team-id }}
|
||||
run: |
|
||||
python3 -I -B - <<'PY'
|
||||
import os
|
||||
assert all(os.environ[key]=='true' for key in ('APPLE_CERTIFICATE', 'APPLE_CERTIFICATE_PASSWORD', 'KEYCHAIN_PASSWORD', 'APPLE_ID', 'APPLE_PASSWORD', 'APPLE_TEAM_ID')), 'all required signing configuration must exist; no unsigned fallback'
|
||||
import re
|
||||
assert re.fullmatch(r'[A-Z0-9]{10}', os.environ['TEAM']), 'independently reviewed ten-character Apple team required'
|
||||
PY
|
||||
|
||||
sign-linux:
|
||||
@@ -494,6 +576,9 @@ jobs:
|
||||
unsigned-artifact-id: ${{ needs.linux.outputs.artifact-id }}
|
||||
unsigned-sha256: ${{ needs.linux.outputs.sha256 }}
|
||||
asset: ${{ needs.linux.outputs.asset }}
|
||||
linux-signing-fingerprint: ${{ inputs.linux-signing-fingerprint }}
|
||||
secrets:
|
||||
LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }}
|
||||
|
||||
sign-macos:
|
||||
if: >-
|
||||
@@ -511,6 +596,7 @@ jobs:
|
||||
production-signing: ${{ inputs.production-signing }}
|
||||
tooling-revision: ${{ inputs.tooling-revision }}
|
||||
platform: macos-aarch64
|
||||
apple-team-id: ${{ inputs.apple-team-id }}
|
||||
app-name: ${{ inputs.app-name }}
|
||||
version: ${{ inputs.version }}
|
||||
identity-artifact-id: ${{ inputs.identity-artifact-id }}
|
||||
@@ -518,3 +604,10 @@ jobs:
|
||||
unsigned-artifact-id: ${{ needs.macos.outputs.artifact-id }}
|
||||
unsigned-sha256: ${{ needs.macos.outputs.sha256 }}
|
||||
asset: ${{ needs.macos.outputs.asset }}
|
||||
secrets:
|
||||
APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
|
||||
APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
|
||||
KEYCHAIN_PASSWORD: ${{ secrets.KEYCHAIN_PASSWORD }}
|
||||
APPLE_ID: ${{ secrets.APPLE_ID }}
|
||||
APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
|
||||
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
|
||||
@@ -1,4 +1,4 @@
|
||||
name: Windows unsigned nightly producer
|
||||
name: Unsigned nightly producer (every listed platform, one run)
|
||||
# Reusable only. Main application code never runs with signing keys or OIDC.
|
||||
on:
|
||||
workflow_call:
|
||||
@@ -15,6 +15,10 @@ on:
|
||||
craft-fonts-ref:
|
||||
type: string
|
||||
default: bfcbf714e45a3ea8e98f88ab2b7971372a576414
|
||||
platforms:
|
||||
description: "Reviewed literal JSON list of platforms this caller builds; the release signer still requires every admitted platform"
|
||||
type: string
|
||||
default: '["windows-x86_64"]'
|
||||
outputs:
|
||||
unsigned-artifact-id:
|
||||
value: ${{ jobs.build.outputs.artifact-id }}
|
||||
@@ -76,9 +80,39 @@ jobs:
|
||||
cargo metadata --locked --format-version 1 > /dev/null
|
||||
|
||||
|
||||
build:
|
||||
needs: git-sources
|
||||
select-platforms:
|
||||
# Validate the caller's list once. Build jobs then match exact array elements; a bare
|
||||
# JSON string such as "not-linux-x86_64" can never substring-match a platform.
|
||||
if: inputs.app-name == 'photocraft' && github.repository == 'storytold/photocraft' && github.ref == 'refs/heads/main'
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
permissions: {}
|
||||
outputs:
|
||||
platforms: ${{ steps.select.outputs.platforms }}
|
||||
steps:
|
||||
- name: Require a JSON array of distinct supported platform IDs
|
||||
id: select
|
||||
env:
|
||||
PLATFORMS: ${{ inputs.platforms }}
|
||||
run: |
|
||||
python3 -I -B - <<'PY'
|
||||
import json, os, sys
|
||||
supported = {'linux-x86_64', 'macos-aarch64', 'windows-x86_64'}
|
||||
try:
|
||||
value = json.loads(os.environ['PLATFORMS'])
|
||||
except ValueError:
|
||||
sys.exit('platforms must be a JSON array of supported platform IDs')
|
||||
if not (isinstance(value, list) and value and all(isinstance(item, str) and item in supported for item in value)):
|
||||
sys.exit('platforms must be a non-empty JSON array of supported platform IDs')
|
||||
if len(set(value)) != len(value):
|
||||
sys.exit('platforms must not repeat a platform')
|
||||
with open(os.environ['GITHUB_OUTPUT'], 'a', encoding='utf-8') as stream:
|
||||
stream.write('platforms='+json.dumps(sorted(value), separators=(',', ':'))+'\n')
|
||||
PY
|
||||
|
||||
build:
|
||||
needs: [git-sources, select-platforms]
|
||||
if: inputs.app-name == 'photocraft' && github.repository == 'storytold/photocraft' && github.ref == 'refs/heads/main' && contains(fromJSON(needs.select-platforms.outputs.platforms), 'windows-x86_64')
|
||||
runs-on: windows-latest
|
||||
timeout-minutes: 90
|
||||
permissions:
|
||||
@@ -113,7 +147,7 @@ jobs:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
if ((git -C .nightly-tools rev-parse HEAD) -cne $env:TOOLING_REVISION) { throw 'tooling checkout differs' }
|
||||
python -I -B .nightly-tools/scripts/nightly_release_entry.py main-plan --output .unsigned-plan
|
||||
python -I -B .nightly-tools/scripts/nightly_release_entry.py main-plan --platform windows-x86_64 --output .unsigned-plan
|
||||
if ($LASTEXITCODE -ne 0) { throw 'unsigned producer identity refused' }
|
||||
- uses: storytold/craft-common-actions/actions/checkout-craft-fonts@f5141455aac7b2eb4708aa259d8ffcdf10fde939
|
||||
with:
|
||||
@@ -159,7 +193,7 @@ jobs:
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
python -I -B .nightly-tools/scripts/nightly_release_entry.py main-seal --directory dist --plan .unsigned-plan/plan.json --output .unsigned-handoff
|
||||
python -I -B .nightly-tools/scripts/nightly_release_entry.py main-seal --platform windows-x86_64 --directory dist --plan .unsigned-plan/plan.json --output .unsigned-handoff
|
||||
if ($LASTEXITCODE -ne 0) { throw 'compiler handoff refused' }
|
||||
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
id: upload
|
||||
@@ -213,7 +247,318 @@ jobs:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
EXPECTED_COMPILER_SHA256: ${{ needs.build.outputs.unsigned-sha256 }}
|
||||
run: |
|
||||
python3 -I -B .nightly-tools/scripts/nightly_release_entry.py main-subject --directory .unsigned
|
||||
python3 -I -B .nightly-tools/scripts/nightly_release_entry.py main-subject --platform windows-x86_64 --directory .unsigned
|
||||
- name: Attest actual independently hashed unsigned payload, never a caller digest
|
||||
uses: actions/attest-build-provenance@96278af6caaf10aea03fd8d33a09a777ca52d62f
|
||||
with:
|
||||
subject-path: ${{ steps.subject.outputs.subject-path }}
|
||||
build-macos:
|
||||
needs: [git-sources, select-platforms]
|
||||
if: inputs.app-name == 'photocraft' && github.repository == 'storytold/photocraft' && github.ref == 'refs/heads/main' && contains(fromJSON(needs.select-platforms.outputs.platforms), 'macos-aarch64')
|
||||
# Same larger Arm runner as the stable macOS build; no secrets, environment, OIDC or cache.
|
||||
runs-on: macos-15-xlarge
|
||||
timeout-minutes: 90
|
||||
permissions:
|
||||
contents: read
|
||||
actions: read
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
CARGO_INCREMENTAL: 0
|
||||
RUST_BACKTRACE: 1
|
||||
outputs:
|
||||
artifact-id: ${{ steps.upload.outputs.artifact-id }}
|
||||
unsigned-sha256: ${{ steps.seal.outputs.unsigned-sha256 }}
|
||||
steps:
|
||||
- name: Select Python for nightly helpers
|
||||
uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6
|
||||
with:
|
||||
python-version: '3.13'
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
|
||||
with:
|
||||
egress-policy: audit
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
ref: ${{ github.sha }}
|
||||
persist-credentials: false
|
||||
- name: Bind immutable defining workflow before any shared code
|
||||
shell: bash
|
||||
env:
|
||||
DEFINING_REPOSITORY: ${{ job.workflow_repository }}
|
||||
DEFINING_SHA: ${{ job.workflow_sha }}
|
||||
run: |
|
||||
python3 -I -B -c "import os,re; p=os.environ['TOOLING_REVISION']; assert re.fullmatch('[0-9a-f]{40}',p) and p!='0'*40; assert os.environ['DEFINING_REPOSITORY']=='storytold/craft-common-actions'; assert os.environ['DEFINING_SHA']==p"
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
repository: ${{ job.workflow_repository }}
|
||||
ref: ${{ job.workflow_sha }}
|
||||
path: .nightly-tools
|
||||
persist-credentials: false
|
||||
- name: Prepare exact original-run identity without editing source
|
||||
id: plan
|
||||
shell: bash
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
test "$(git -C .nightly-tools rev-parse HEAD)" = "$TOOLING_REVISION"
|
||||
test "$(git rev-parse HEAD)" = "$GITHUB_SHA"
|
||||
test "$(uname -m)" = arm64
|
||||
python3 -I -B .nightly-tools/scripts/nightly_release_entry.py main-plan --platform macos-aarch64 --output .unsigned-plan
|
||||
- uses: storytold/craft-common-actions/actions/checkout-craft-fonts@f5141455aac7b2eb4708aa259d8ffcdf10fde939
|
||||
with:
|
||||
ref: ${{ inputs.craft-fonts-ref }}
|
||||
- uses: storytold/craft-common-actions/actions/checkout-craft-i18n@f5141455aac7b2eb4708aa259d8ffcdf10fde939
|
||||
- id: rust
|
||||
uses: storytold/craft-common-actions/actions/rust-channel@f5141455aac7b2eb4708aa259d8ffcdf10fde939
|
||||
with:
|
||||
targets: aarch64-apple-darwin
|
||||
- uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0
|
||||
with:
|
||||
toolchain: ${{ steps.rust.outputs.toolchain }}
|
||||
targets: ${{ steps.rust.outputs.targets }}
|
||||
components: ${{ steps.rust.outputs.components }}
|
||||
# No platform secrets, environment, OIDC permission, cache, or version mutation.
|
||||
# The app-owned script builds the GUI-only nightly app; Developer ID comes later.
|
||||
- name: Compile unsigned package only
|
||||
shell: bash
|
||||
env:
|
||||
PHOTOCRAFT_BUILD_CHANNEL: nightly-v1
|
||||
PHOTOCRAFT_VERSION: ${{ steps.plan.outputs.version }}
|
||||
PHOTOCRAFT_BUILD_SHA: ${{ steps.plan.outputs.source-commit }}
|
||||
PHOTOCRAFT_BUILD_DATE: ${{ steps.plan.outputs.build-date }}
|
||||
CARGO_TARGET_DIR: ${{ runner.temp }}/nightly-targets
|
||||
DIST: ${{ runner.temp }}/nightly-dist/macos-aarch64
|
||||
CRAFT_FONTS_DIR: ${{ github.workspace }}/craft-fonts
|
||||
CRAFT_FONTS_REQUIRED: '1'
|
||||
run: bash packaging/macos/nightly.sh --arch aarch64
|
||||
- name: Smoke only in the credentialless compiler job
|
||||
shell: bash
|
||||
env:
|
||||
EXACT_VERSION: ${{ steps.plan.outputs.version }}
|
||||
BUILT_ASSET: ${{ steps.plan.outputs.built-asset }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
archive="$RUNNER_TEMP/nightly-dist/macos-aarch64/$BUILT_ASSET"
|
||||
python3 -B .nightly-tools/scripts/nightly_unix.py inventory --pending .nightly-tools/nightly-unix-pending.json \
|
||||
--platform macos-aarch64 --version "$EXACT_VERSION" --archive "$archive"
|
||||
python3 -B .nightly-tools/scripts/nightly_unix.py unpack-private --pending .nightly-tools/nightly-unix-pending.json \
|
||||
--platform macos-aarch64 --version "$EXACT_VERSION" --archive "$archive" \
|
||||
--output "$RUNNER_TEMP/nightly-compiler-smoke"
|
||||
python3 -B .nightly-tools/scripts/nightly_smoke.py \
|
||||
--executable "$RUNNER_TEMP/nightly-compiler-smoke/PhotoCraft Nightly.app/Contents/MacOS/PhotoCraft" \
|
||||
--profile-root "$RUNNER_TEMP/nightly-compiler-profile" --version "$EXACT_VERSION"
|
||||
- name: Seal only the exact unsigned compiler bytes
|
||||
id: seal
|
||||
shell: bash
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: python3 -I -B .nightly-tools/scripts/nightly_release_entry.py main-seal --platform macos-aarch64 --directory "$RUNNER_TEMP/nightly-dist/macos-aarch64" --plan .unsigned-plan/plan.json --output .unsigned-handoff
|
||||
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
id: upload
|
||||
with:
|
||||
name: nightly-unsigned-macos-aarch64-${{ github.run_id }}-${{ github.run_attempt }}
|
||||
path: .unsigned-handoff/*
|
||||
include-hidden-files: true
|
||||
if-no-files-found: error
|
||||
retention-days: 14
|
||||
attest-macos:
|
||||
needs: build-macos
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
permissions:
|
||||
contents: read
|
||||
actions: read
|
||||
id-token: write
|
||||
attestations: write
|
||||
steps:
|
||||
# Fresh runner: no app checkout, hooks, payload execution or restored cache.
|
||||
- name: Bind defining workflow without loading application code
|
||||
env:
|
||||
DEFINING_REPOSITORY: ${{ job.workflow_repository }}
|
||||
DEFINING_SHA: ${{ job.workflow_sha }}
|
||||
run: |
|
||||
python3 -I -B -c "import os,re; p=os.environ['TOOLING_REVISION']; assert re.fullmatch('[0-9a-f]{40}',p) and p!='0'*40; assert os.environ['DEFINING_REPOSITORY']=='storytold/craft-common-actions'; assert os.environ['DEFINING_SHA']==p"
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
repository: ${{ job.workflow_repository }}
|
||||
ref: ${{ job.workflow_sha }}
|
||||
path: .nightly-tools
|
||||
persist-credentials: false
|
||||
- name: Require the actual compiler artifact ID and independent compiler hash
|
||||
env:
|
||||
COMPILER_ARTIFACT: ${{ needs.build-macos.outputs.artifact-id }}
|
||||
COMPILER_SHA256: ${{ needs.build-macos.outputs.unsigned-sha256 }}
|
||||
run: |
|
||||
test "$(git -C .nightly-tools rev-parse HEAD)" = "$TOOLING_REVISION"
|
||||
python3 -B .nightly-tools/scripts/nightly_artifacts.py download-contract --artifact-id "$COMPILER_ARTIFACT" --expected-sha256 "$COMPILER_SHA256"
|
||||
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
|
||||
with:
|
||||
artifact-ids: ${{ needs.build-macos.outputs.artifact-id }}
|
||||
path: .unsigned
|
||||
merge-multiple: true
|
||||
digest-mismatch: error
|
||||
- name: Independently hash the exact compiler payload and recompute its source identity
|
||||
id: subject
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
EXPECTED_COMPILER_SHA256: ${{ needs.build-macos.outputs.unsigned-sha256 }}
|
||||
run: |
|
||||
python3 -I -B .nightly-tools/scripts/nightly_release_entry.py main-subject --platform macos-aarch64 --directory .unsigned
|
||||
- name: Attest actual independently hashed unsigned payload, never a caller digest
|
||||
uses: actions/attest-build-provenance@96278af6caaf10aea03fd8d33a09a777ca52d62f
|
||||
with:
|
||||
subject-path: ${{ steps.subject.outputs.subject-path }}
|
||||
build-linux:
|
||||
# Linux joins the same producer run as Windows (one release, every admitted platform).
|
||||
# Off unless the caller lists linux-x86_64; no secrets, environment, OIDC, cache or version mutation.
|
||||
needs: [git-sources, select-platforms]
|
||||
if: contains(fromJSON(needs.select-platforms.outputs.platforms), 'linux-x86_64') && inputs.app-name == 'photocraft' && github.repository == 'storytold/photocraft' && github.ref == 'refs/heads/main'
|
||||
runs-on: ubuntu-22.04
|
||||
timeout-minutes: 90
|
||||
permissions:
|
||||
contents: read
|
||||
actions: read
|
||||
outputs:
|
||||
artifact-id: ${{ steps.upload.outputs.artifact-id }}
|
||||
unsigned-sha256: ${{ steps.seal.outputs.unsigned-sha256 }}
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
CARGO_INCREMENTAL: 0
|
||||
RUST_BACKTRACE: 1
|
||||
steps:
|
||||
- name: Select Python for nightly helpers
|
||||
uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6
|
||||
with:
|
||||
python-version: '3.13'
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
|
||||
with:
|
||||
egress-policy: audit
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
ref: ${{ github.sha }}
|
||||
persist-credentials: false
|
||||
- name: Bind immutable defining workflow before any shared code
|
||||
env:
|
||||
DEFINING_REPOSITORY: ${{ job.workflow_repository }}
|
||||
DEFINING_SHA: ${{ job.workflow_sha }}
|
||||
run: |
|
||||
python3 -I -B -c "import os,re; p=os.environ['TOOLING_REVISION']; assert re.fullmatch('[0-9a-f]{40}',p) and p!='0'*40; assert os.environ['DEFINING_REPOSITORY']=='storytold/craft-common-actions'; assert os.environ['DEFINING_SHA']==p"
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
repository: ${{ job.workflow_repository }}
|
||||
ref: ${{ job.workflow_sha }}
|
||||
path: .nightly-tools
|
||||
persist-credentials: false
|
||||
- name: Prepare exact original-run identity without editing source
|
||||
id: plan
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
test "$(git -C .nightly-tools rev-parse HEAD)" = "$TOOLING_REVISION"
|
||||
test "$(git rev-parse HEAD)" = "$GITHUB_SHA"
|
||||
test "$(uname -m)" = x86_64
|
||||
python3 -I -B .nightly-tools/scripts/nightly_release_entry.py main-plan --platform linux-x86_64 --output .unsigned-plan
|
||||
- uses: storytold/craft-common-actions/actions/checkout-craft-fonts@f5141455aac7b2eb4708aa259d8ffcdf10fde939
|
||||
with:
|
||||
ref: ${{ inputs.craft-fonts-ref }}
|
||||
- uses: storytold/craft-common-actions/actions/checkout-craft-i18n@f5141455aac7b2eb4708aa259d8ffcdf10fde939
|
||||
- uses: storytold/craft-common-actions/actions/install-linux-deps@f5141455aac7b2eb4708aa259d8ffcdf10fde939
|
||||
with:
|
||||
deb-arch: amd64
|
||||
nfpm-version: 2.47.0
|
||||
- id: rust
|
||||
uses: storytold/craft-common-actions/actions/rust-channel@f5141455aac7b2eb4708aa259d8ffcdf10fde939
|
||||
with:
|
||||
targets: x86_64-unknown-linux-gnu
|
||||
- uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0
|
||||
with:
|
||||
toolchain: ${{ steps.rust.outputs.toolchain }}
|
||||
targets: ${{ steps.rust.outputs.targets }}
|
||||
components: ${{ steps.rust.outputs.components }}
|
||||
- name: Compile unsigned package only
|
||||
env:
|
||||
PHOTOCRAFT_BUILD_CHANNEL: nightly-v1
|
||||
PHOTOCRAFT_VERSION: ${{ steps.plan.outputs.version }}
|
||||
PHOTOCRAFT_BUILD_SHA: ${{ steps.plan.outputs.source-commit }}
|
||||
PHOTOCRAFT_BUILD_DATE: ${{ steps.plan.outputs.build-date }}
|
||||
CARGO_TARGET_DIR: ${{ runner.temp }}/nightly-targets
|
||||
DIST: ${{ runner.temp }}/nightly-dist/linux-x86_64
|
||||
CRAFT_FONTS_DIR: ${{ github.workspace }}/craft-fonts
|
||||
CRAFT_FONTS_REQUIRED: '1'
|
||||
run: bash packaging/linux/nightly.sh --arch x86_64
|
||||
- name: Inventory and smoke only in the credentialless compiler job
|
||||
env:
|
||||
EXACT_VERSION: ${{ steps.plan.outputs.version }}
|
||||
EXACT_ASSET: ${{ steps.plan.outputs.asset }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
python3 -B .nightly-tools/scripts/nightly_unix.py unpack-private \
|
||||
--pending .nightly-tools/nightly-unix-pending.json --platform linux-x86_64 \
|
||||
--version "$EXACT_VERSION" --archive "$RUNNER_TEMP/nightly-dist/linux-x86_64/$EXACT_ASSET" \
|
||||
--output "$RUNNER_TEMP/nightly-compiler-smoke"
|
||||
python3 -B .nightly-tools/scripts/nightly_smoke.py \
|
||||
--executable "$RUNNER_TEMP/nightly-compiler-smoke/photocraft" \
|
||||
--profile-root "$RUNNER_TEMP/nightly-compiler-profile" --version "$EXACT_VERSION"
|
||||
- name: Seal only the exact unsigned compiler bytes
|
||||
id: seal
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: python3 -I -B .nightly-tools/scripts/nightly_release_entry.py main-seal --platform linux-x86_64 --directory "$RUNNER_TEMP/nightly-dist/linux-x86_64" --plan .unsigned-plan/plan.json --output .unsigned-handoff
|
||||
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
id: upload
|
||||
with:
|
||||
name: nightly-unsigned-linux-x86_64-${{ github.run_id }}-${{ github.run_attempt }}
|
||||
path: .unsigned-handoff/*
|
||||
include-hidden-files: true
|
||||
if-no-files-found: error
|
||||
retention-days: 14
|
||||
attest-linux:
|
||||
needs: build-linux
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
permissions:
|
||||
contents: read
|
||||
actions: read
|
||||
id-token: write
|
||||
attestations: write
|
||||
outputs:
|
||||
unsigned-sha256: ${{ steps.subject.outputs.unsigned-sha256 }}
|
||||
steps:
|
||||
# Fresh runner: no app checkout, hooks, payload execution or restored cache.
|
||||
- name: Bind defining workflow without loading application code
|
||||
env:
|
||||
DEFINING_REPOSITORY: ${{ job.workflow_repository }}
|
||||
DEFINING_SHA: ${{ job.workflow_sha }}
|
||||
run: |
|
||||
python3 -I -B -c "import os,re; p=os.environ['TOOLING_REVISION']; assert re.fullmatch('[0-9a-f]{40}',p) and p!='0'*40; assert os.environ['DEFINING_REPOSITORY']=='storytold/craft-common-actions'; assert os.environ['DEFINING_SHA']==p"
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
repository: ${{ job.workflow_repository }}
|
||||
ref: ${{ job.workflow_sha }}
|
||||
path: .nightly-tools
|
||||
persist-credentials: false
|
||||
- name: Require the actual compiler artifact ID and independent compiler hash
|
||||
env:
|
||||
COMPILER_ARTIFACT: ${{ needs.build-linux.outputs.artifact-id }}
|
||||
COMPILER_SHA256: ${{ needs.build-linux.outputs.unsigned-sha256 }}
|
||||
run: |
|
||||
test "$(git -C .nightly-tools rev-parse HEAD)" = "$TOOLING_REVISION"
|
||||
python3 -B .nightly-tools/scripts/nightly_artifacts.py download-contract --artifact-id "$COMPILER_ARTIFACT" --expected-sha256 "$COMPILER_SHA256"
|
||||
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
|
||||
with:
|
||||
artifact-ids: ${{ needs.build-linux.outputs.artifact-id }}
|
||||
path: .unsigned
|
||||
merge-multiple: true
|
||||
digest-mismatch: error
|
||||
- name: Independently hash the exact compiler payload and recompute its source identity
|
||||
id: subject
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
EXPECTED_COMPILER_SHA256: ${{ needs.build-linux.outputs.unsigned-sha256 }}
|
||||
run: python3 -I -B .nightly-tools/scripts/nightly_release_entry.py main-subject --platform linux-x86_64 --directory .unsigned
|
||||
- name: Attest actual independently hashed unsigned payload, never a caller digest
|
||||
uses: actions/attest-build-provenance@96278af6caaf10aea03fd8d33a09a777ca52d62f
|
||||
with:
|
||||
|
||||
@@ -50,6 +50,10 @@ on:
|
||||
description: "Opt in to production-signed nightly artifacts (and their publication). Off unless the caller sets true; a caller existing is not consent to sign."
|
||||
type: boolean
|
||||
default: false
|
||||
windows-publisher-subject:
|
||||
description: "Reviewed literal exact Authenticode publisher subject in caller source (public); empty refuses Windows signing"
|
||||
type: string
|
||||
default: ''
|
||||
|
||||
outputs:
|
||||
artifact-id:
|
||||
@@ -100,7 +104,7 @@ jobs:
|
||||
AZURE_SIGNING_ENDPOINT: ${{ secrets.AZURE_SIGNING_ENDPOINT != '' }}
|
||||
AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT != '' }}
|
||||
AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE != '' }}
|
||||
PUBLISHER: ${{ vars.NIGHTLY_WINDOWS_PUBLISHER_SUBJECT }}
|
||||
PUBLISHER: ${{ inputs.windows-publisher-subject }}
|
||||
run: |
|
||||
python3 -I -B - <<'PY'
|
||||
import os
|
||||
@@ -353,7 +357,7 @@ jobs:
|
||||
permissions:
|
||||
contents: read
|
||||
env:
|
||||
NIGHTLY_WINDOWS_PUBLISHER_SUBJECT: ${{ vars.NIGHTLY_WINDOWS_PUBLISHER_SUBJECT }}
|
||||
NIGHTLY_WINDOWS_PUBLISHER_SUBJECT: ${{ inputs.windows-publisher-subject }}
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
|
||||
|
||||
+172
-33
@@ -19,6 +19,20 @@ on:
|
||||
required: false
|
||||
AZURE_CERT_PROFILE:
|
||||
required: false
|
||||
APPLE_CERTIFICATE:
|
||||
required: false
|
||||
APPLE_CERTIFICATE_PASSWORD:
|
||||
required: false
|
||||
KEYCHAIN_PASSWORD:
|
||||
required: false
|
||||
APPLE_ID:
|
||||
required: false
|
||||
APPLE_PASSWORD:
|
||||
required: false
|
||||
APPLE_TEAM_ID:
|
||||
required: false
|
||||
LINUX_SIGNING_KEY:
|
||||
required: false
|
||||
inputs:
|
||||
force:
|
||||
type: boolean
|
||||
@@ -39,10 +53,22 @@ on:
|
||||
craft-fonts-ref:
|
||||
type: string
|
||||
default: bfcbf714e45a3ea8e98f88ab2b7971372a576414
|
||||
linux-signing-fingerprint:
|
||||
description: "Reviewed full uppercase primary fingerprint of the stable Linux key, committed in caller source; never a repository variable"
|
||||
type: string
|
||||
default: ''
|
||||
production-signing:
|
||||
description: "Opt in to production-signed nightly artifacts (and their publication). Off unless the caller sets true; a caller existing is not consent to sign."
|
||||
type: boolean
|
||||
default: false
|
||||
apple-team-id:
|
||||
description: "Reviewed literal Apple Developer team ID in caller source (public; stable's team). Empty refuses macOS signing."
|
||||
type: string
|
||||
default: ''
|
||||
windows-publisher-subject:
|
||||
description: "Reviewed literal exact Authenticode publisher subject in caller source (public); empty refuses Windows signing"
|
||||
type: string
|
||||
default: ''
|
||||
permissions:
|
||||
contents: read
|
||||
env:
|
||||
@@ -162,6 +188,7 @@ jobs:
|
||||
identity-artifact-id: ${{ needs.identity.outputs.artifact-id }}
|
||||
identity-sha256: ${{ needs.identity.outputs.sha256 }}
|
||||
craft-fonts-ref: ${{ inputs.craft-fonts-ref }}
|
||||
windows-publisher-subject: ${{ inputs.windows-publisher-subject }}
|
||||
secrets:
|
||||
WINDOWS_CERTIFICATE: ${{ secrets.WINDOWS_CERTIFICATE }}
|
||||
WINDOWS_CERTIFICATE_PASSWORD: ${{ secrets.WINDOWS_CERTIFICATE_PASSWORD }}
|
||||
@@ -173,7 +200,8 @@ jobs:
|
||||
AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }}
|
||||
|
||||
build-linux:
|
||||
if: ${{ false }} # Pending native source, never tuple admission or execution authority.
|
||||
# Same opt-in as Windows: no signing, staging or Linux secret use unless the caller sets production-signing.
|
||||
if: needs.identity.outputs.ready == 'true' && needs.identity.outputs.build == 'true' && inputs.production-signing == true
|
||||
needs: identity
|
||||
permissions:
|
||||
contents: read
|
||||
@@ -188,10 +216,13 @@ jobs:
|
||||
identity-sha256: ${{ needs.identity.outputs.sha256 }}
|
||||
platform: linux-x86_64
|
||||
craft-fonts-ref: ${{ inputs.craft-fonts-ref }}
|
||||
linux-signing-fingerprint: ${{ inputs.linux-signing-fingerprint }}
|
||||
secrets:
|
||||
LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }}
|
||||
|
||||
build-macos:
|
||||
if: ${{ false }} # Pending native source, never tuple admission or execution authority.
|
||||
needs: identity
|
||||
if: needs.identity.outputs.ready == 'true' && needs.identity.outputs.build == 'true' && inputs.production-signing == true
|
||||
permissions:
|
||||
contents: read
|
||||
uses: $/.github/workflows/nightly-unix.yml
|
||||
@@ -205,6 +236,14 @@ jobs:
|
||||
identity-sha256: ${{ needs.identity.outputs.sha256 }}
|
||||
platform: macos-aarch64
|
||||
craft-fonts-ref: ${{ inputs.craft-fonts-ref }}
|
||||
apple-team-id: ${{ inputs.apple-team-id }}
|
||||
secrets:
|
||||
APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
|
||||
APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
|
||||
KEYCHAIN_PASSWORD: ${{ secrets.KEYCHAIN_PASSWORD }}
|
||||
APPLE_ID: ${{ secrets.APPLE_ID }}
|
||||
APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
|
||||
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
|
||||
|
||||
status:
|
||||
if: always()
|
||||
@@ -218,36 +257,41 @@ jobs:
|
||||
env:
|
||||
IDENTITY_RESULT: ${{ needs.identity.result }}
|
||||
WINDOWS_RESULT: ${{ needs.build-windows.result }}
|
||||
MACOS_RESULT: ${{ needs.build-macos.result }}
|
||||
LINUX_RESULT: ${{ needs.build-linux.result }}
|
||||
STAGING_RESULT: ${{ needs.stage-nightly.result }}
|
||||
BUILD_REQUESTED: ${{ needs.identity.outputs.build }}
|
||||
PRODUCTION_SIGNING: ${{ inputs.production-signing }}
|
||||
run: |
|
||||
{
|
||||
echo '## Dedicated nightly source candidate'
|
||||
printf 'Identity/preflight: `%s`. Windows build: `%s`. Build requested: `%s`.\n' "$IDENTITY_RESULT" "$WINDOWS_RESULT" "$BUILD_REQUESTED"
|
||||
printf 'Identity/preflight: `%s`. Windows build: `%s`. Linux build: `%s`. macOS build: `%s`. Build requested: `%s`.\n' "$IDENTITY_RESULT" "$WINDOWS_RESULT" "$LINUX_RESULT" "$MACOS_RESULT" "$BUILD_REQUESTED"
|
||||
printf 'Packet staging: `%s`.\n' "$STAGING_RESULT"
|
||||
printf 'Production signing opted in by the caller: `%s`.\n' "$PRODUCTION_SIGNING"
|
||||
echo 'Named policy refusal is in the identity step summary; a failed/red check is not bypassed.'
|
||||
echo 'Legacy diagnostics have a separate workflow/run and cannot contribute artifacts here.'
|
||||
echo 'Windows requires verified signing; Linux/macOS rows are pending and disabled; skipped native jobs are not platform coverage.'
|
||||
echo 'Windows and macOS require verified signing (macOS: Developer ID, notarized, stapled); skipped native jobs are not platform coverage.'
|
||||
echo 'Unchanged-source skip applies to this installable producer only. Diagnostics run independently.'
|
||||
echo 'Publication and attestation are literally disabled; no native/quality/admission proof is implied.'
|
||||
} >> "$GITHUB_STEP_SUMMARY"
|
||||
test "$IDENTITY_RESULT" = success
|
||||
if [ "$BUILD_REQUESTED" = true ] && [ "$PRODUCTION_SIGNING" = true ]; then
|
||||
test "$WINDOWS_RESULT" = success
|
||||
test "$LINUX_RESULT" = success
|
||||
test "$MACOS_RESULT" = success
|
||||
test "$STAGING_RESULT" = success
|
||||
fi
|
||||
|
||||
stage-nightly:
|
||||
if: >-
|
||||
inputs.production-signing == true &&
|
||||
needs.identity.outputs.ready == 'true' && needs.build-windows.result == 'success' && needs.identity.outputs.build == 'true' &&
|
||||
needs.identity.outputs.ready == 'true' && needs.build-windows.result == 'success' && needs.build-linux.result == 'success' && needs.build-macos.result == 'success' &&
|
||||
needs.identity.outputs.build == 'true' &&
|
||||
github.repository == 'storytold/photocraft' && github.ref == 'refs/heads/main' &&
|
||||
((github.event_name == 'schedule' && github.run_attempt == '1') ||
|
||||
((github.event_name == 'schedule' || github.event_name == 'workflow_dispatch') &&
|
||||
contains(fromJSON(inputs.manual-actors), github.triggering_actor)))
|
||||
needs: [identity, build-windows]
|
||||
needs: [identity, build-windows, build-linux, build-macos]
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 60
|
||||
permissions:
|
||||
@@ -256,7 +300,9 @@ jobs:
|
||||
artifact-id: ${{ steps.upload.outputs.artifact-id }}
|
||||
sha256: ${{ steps.seal.outputs.sha256 }}
|
||||
env:
|
||||
NIGHTLY_WINDOWS_PUBLISHER_SUBJECT: ${{ vars.NIGHTLY_WINDOWS_PUBLISHER_SUBJECT }}
|
||||
NIGHTLY_WINDOWS_PUBLISHER_SUBJECT: ${{ inputs.windows-publisher-subject }}
|
||||
NIGHTLY_APPLE_TEAM_ID: ${{ inputs.apple-team-id }}
|
||||
NIGHTLY_LINUX_SIGNING_FINGERPRINT: ${{ inputs.linux-signing-fingerprint }}
|
||||
steps:
|
||||
- name: Read exact application source
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
@@ -308,20 +354,20 @@ jobs:
|
||||
env:
|
||||
NIGHTLY_MANUAL_ACTORS: ${{ inputs.manual-actors }}
|
||||
run: python -I -B .nightly-tools/scripts/nightly_invocation.py
|
||||
- name: Require exact signer receipt ID and independent signer hash
|
||||
- name: Require exact Windows signer receipt ID and independent signer hash
|
||||
shell: bash
|
||||
env:
|
||||
RECEIPT_ID: ${{ needs.build-windows.outputs.receipt-artifact-id }}
|
||||
RECEIPT_SHA256: ${{ needs.build-windows.outputs.receipt-sha256 }}
|
||||
run: python3 -B .nightly-tools/scripts/nightly_artifacts.py download-contract --artifact-id "$RECEIPT_ID" --expected-sha256 "$RECEIPT_SHA256"
|
||||
- name: Download original signer receipt by exact ID
|
||||
- name: Download original Windows signer receipt by exact ID
|
||||
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333
|
||||
with:
|
||||
artifact-ids: ${{ needs.build-windows.outputs.receipt-artifact-id }}
|
||||
path: .nightly-signing
|
||||
path: .nightly-signing-windows-x86_64
|
||||
merge-multiple: true
|
||||
digest-mismatch: error
|
||||
- name: Recheck original unsigned to final signed provenance before consuming package
|
||||
- name: Recheck original unsigned to final signed Windows provenance before consuming package
|
||||
env:
|
||||
RECEIPT_SHA256: ${{ needs.build-windows.outputs.receipt-sha256 }}
|
||||
IDENTITY_SHA256: ${{ needs.identity.outputs.sha256 }}
|
||||
@@ -329,20 +375,77 @@ jobs:
|
||||
SIGNED_SHA256: ${{ needs.build-windows.outputs.zip-sha256 }}
|
||||
ASSET: ${{ needs.build-windows.outputs.asset }}
|
||||
run: |
|
||||
python3 -B .nightly-tools/scripts/nightly_signing.py verify-receipt --platform windows-x86_64 --receipt-directory .nightly-signing --receipt-sha256 "$RECEIPT_SHA256" --asset "$ASSET" --identity-sha256 "${IDENTITY_SHA256}" --unsigned-sha256 "$UNSIGNED_SHA256" --final-sha256 "$SIGNED_SHA256"
|
||||
python3 -B .nightly-tools/scripts/nightly_signing.py verify-receipt --platform windows-x86_64 \
|
||||
--receipt-directory .nightly-signing-windows-x86_64 --receipt-sha256 "$RECEIPT_SHA256" \
|
||||
--asset "$ASSET" --identity-sha256 "${IDENTITY_SHA256}" \
|
||||
--unsigned-sha256 "$UNSIGNED_SHA256" --final-sha256 "$SIGNED_SHA256"
|
||||
- name: Require exact macOS signer receipt ID and independent signer hash
|
||||
shell: bash
|
||||
env:
|
||||
RECEIPT_ID: ${{ needs.build-macos.outputs.receipt-artifact-id }}
|
||||
RECEIPT_SHA256: ${{ needs.build-macos.outputs.receipt-sha256 }}
|
||||
run: python3 -B .nightly-tools/scripts/nightly_artifacts.py download-contract --artifact-id "$RECEIPT_ID" --expected-sha256 "$RECEIPT_SHA256"
|
||||
- name: Download original macOS signer receipt by exact ID
|
||||
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333
|
||||
with:
|
||||
artifact-ids: ${{ needs.build-macos.outputs.receipt-artifact-id }}
|
||||
path: .nightly-signing-macos-aarch64
|
||||
merge-multiple: true
|
||||
digest-mismatch: error
|
||||
- name: Recheck original unsigned to final signed macOS provenance before consuming package
|
||||
env:
|
||||
RECEIPT_SHA256: ${{ needs.build-macos.outputs.receipt-sha256 }}
|
||||
IDENTITY_SHA256: ${{ needs.identity.outputs.sha256 }}
|
||||
UNSIGNED_SHA256: ${{ needs.build-macos.outputs.unsigned-sha256 }}
|
||||
SIGNED_SHA256: ${{ needs.build-macos.outputs.sha256 }}
|
||||
ASSET: ${{ needs.build-macos.outputs.asset }}
|
||||
run: |
|
||||
python3 -B .nightly-tools/scripts/nightly_signing.py verify-receipt --platform macos-aarch64 \
|
||||
--receipt-directory .nightly-signing-macos-aarch64 --receipt-sha256 "$RECEIPT_SHA256" \
|
||||
--asset "$ASSET" --identity-sha256 "${IDENTITY_SHA256}" \
|
||||
--unsigned-sha256 "$UNSIGNED_SHA256" --final-sha256 "$SIGNED_SHA256"
|
||||
- name: Require exact Linux signer receipt ID and independent signer hash
|
||||
shell: bash
|
||||
env:
|
||||
RECEIPT_ID: ${{ needs.build-linux.outputs.receipt-artifact-id }}
|
||||
RECEIPT_SHA256: ${{ needs.build-linux.outputs.receipt-sha256 }}
|
||||
run: python3 -B .nightly-tools/scripts/nightly_artifacts.py download-contract --artifact-id "$RECEIPT_ID" --expected-sha256 "$RECEIPT_SHA256"
|
||||
- name: Download original Linux signer receipt by exact ID
|
||||
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333
|
||||
with:
|
||||
artifact-ids: ${{ needs.build-linux.outputs.receipt-artifact-id }}
|
||||
path: .nightly-signing-linux-x86_64
|
||||
merge-multiple: true
|
||||
digest-mismatch: error
|
||||
- name: Recheck original unsigned to final signed Linux provenance before consuming package
|
||||
env:
|
||||
RECEIPT_SHA256: ${{ needs.build-linux.outputs.receipt-sha256 }}
|
||||
IDENTITY_SHA256: ${{ needs.identity.outputs.sha256 }}
|
||||
UNSIGNED_SHA256: ${{ needs.build-linux.outputs.unsigned-sha256 }}
|
||||
SIGNED_SHA256: ${{ needs.build-linux.outputs.sha256 }}
|
||||
ASSET: ${{ needs.build-linux.outputs.asset }}
|
||||
run: |
|
||||
python3 -B .nightly-tools/scripts/nightly_signing.py verify-receipt --platform linux-x86_64 \
|
||||
--receipt-directory .nightly-signing-linux-x86_64 --receipt-sha256 "$RECEIPT_SHA256" \
|
||||
--asset "$ASSET" --identity-sha256 "${IDENTITY_SHA256}" \
|
||||
--unsigned-sha256 "$UNSIGNED_SHA256" --final-sha256 "$SIGNED_SHA256"
|
||||
- name: Require exact numeric IDs and independent producer hashes before download
|
||||
shell: bash
|
||||
env:
|
||||
IDENTITY_ID: ${{ needs.identity.outputs.artifact-id }}
|
||||
IDENTITY_SHA256: ${{ needs.identity.outputs.sha256 }}
|
||||
ZIP_ID: ${{ needs.build-windows.outputs.artifact-id }}
|
||||
ZIP_SHA256: ${{ needs.build-windows.outputs.zip-sha256 }}
|
||||
SIGNER_RECEIPT_SHA256: ${{ needs.build-windows.outputs.receipt-sha256 }}
|
||||
ORIGINAL_UNSIGNED_SHA256: ${{ needs.build-windows.outputs.unsigned-sha256 }}
|
||||
WINDOWS_ID: ${{ needs.build-windows.outputs.artifact-id }}
|
||||
WINDOWS_SHA256: ${{ needs.build-windows.outputs.zip-sha256 }}
|
||||
MACOS_ID: ${{ needs.build-macos.outputs.artifact-id }}
|
||||
MACOS_SHA256: ${{ needs.build-macos.outputs.sha256 }}
|
||||
LINUX_ID: ${{ needs.build-linux.outputs.artifact-id }}
|
||||
LINUX_SHA256: ${{ needs.build-linux.outputs.sha256 }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
python -B .nightly-tools/scripts/nightly_artifacts.py download-contract --artifact-id "$LINUX_ID" --expected-sha256 "$LINUX_SHA256"
|
||||
python -B .nightly-tools/scripts/nightly_artifacts.py download-contract --artifact-id "$IDENTITY_ID" --expected-sha256 "$IDENTITY_SHA256"
|
||||
python -B .nightly-tools/scripts/nightly_artifacts.py download-contract --artifact-id "$ZIP_ID" --expected-sha256 "$ZIP_SHA256"
|
||||
python -B .nightly-tools/scripts/nightly_artifacts.py download-contract --artifact-id "$WINDOWS_ID" --expected-sha256 "$WINDOWS_SHA256"
|
||||
python -B .nightly-tools/scripts/nightly_artifacts.py download-contract --artifact-id "$MACOS_ID" --expected-sha256 "$MACOS_SHA256"
|
||||
- name: Download exact identity artifact ID, never a name replacement
|
||||
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
|
||||
with:
|
||||
@@ -350,37 +453,72 @@ jobs:
|
||||
path: .nightly-input
|
||||
merge-multiple: true
|
||||
digest-mismatch: error
|
||||
- name: Download exact final signed ZIP artifact ID, never a name replacement
|
||||
- name: Download exact final signed Windows ZIP artifact ID, never a name replacement
|
||||
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
|
||||
with:
|
||||
artifact-ids: ${{ needs.build-windows.outputs.artifact-id }}
|
||||
path: .nightly-build
|
||||
path: .nightly-build-windows-x86_64
|
||||
merge-multiple: true
|
||||
digest-mismatch: error
|
||||
- name: Verify independent producer bytes before staging
|
||||
- name: Download exact final signed Linux package and detached signature by artifact ID
|
||||
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
|
||||
with:
|
||||
artifact-ids: ${{ needs.build-linux.outputs.artifact-id }}
|
||||
path: .nightly-build-linux-x86_64
|
||||
merge-multiple: true
|
||||
digest-mismatch: error
|
||||
- name: Reverify Linux bytes and signature against the reviewed source key, never the bundled export
|
||||
env:
|
||||
RECEIPT_SHA256: ${{ needs.build-linux.outputs.receipt-sha256 }}
|
||||
IDENTITY_SHA256: ${{ needs.identity.outputs.sha256 }}
|
||||
UNSIGNED_SHA256: ${{ needs.build-linux.outputs.unsigned-sha256 }}
|
||||
SIGNED_SHA256: ${{ needs.build-linux.outputs.sha256 }}
|
||||
ASSET: ${{ needs.build-linux.outputs.asset }}
|
||||
run: |
|
||||
python3 -B .nightly-tools/scripts/nightly_signing.py verify-receipt --platform linux-x86_64 \
|
||||
--receipt-directory .nightly-signing-linux-x86_64 --receipt-sha256 "$RECEIPT_SHA256" \
|
||||
--asset "$ASSET" --identity-sha256 "${IDENTITY_SHA256}" \
|
||||
--unsigned-sha256 "$UNSIGNED_SHA256" --final-sha256 "$SIGNED_SHA256" \
|
||||
--package-directory .nightly-build-linux-x86_64 --source .
|
||||
- name: Download exact final notarized macOS ZIP artifact ID, never a name replacement
|
||||
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
|
||||
with:
|
||||
artifact-ids: ${{ needs.build-macos.outputs.artifact-id }}
|
||||
path: .nightly-build-macos-aarch64
|
||||
merge-multiple: true
|
||||
digest-mismatch: error
|
||||
- name: Verify independent producer bytes, then stage every admitted platform together
|
||||
env:
|
||||
IDENTITY_SHA256: ${{ needs.identity.outputs.sha256 }}
|
||||
ZIP_SHA256: ${{ needs.build-windows.outputs.zip-sha256 }}
|
||||
SIGNER_RECEIPT_SHA256: ${{ needs.build-windows.outputs.receipt-sha256 }}
|
||||
ORIGINAL_UNSIGNED_SHA256: ${{ needs.build-windows.outputs.unsigned-sha256 }}
|
||||
ASSET: ${{ needs.build-windows.outputs.asset }}
|
||||
WINDOWS_SHA256: ${{ needs.build-windows.outputs.zip-sha256 }}
|
||||
WINDOWS_ASSET: ${{ needs.build-windows.outputs.asset }}
|
||||
MACOS_SHA256: ${{ needs.build-macos.outputs.sha256 }}
|
||||
MACOS_ASSET: ${{ needs.build-macos.outputs.asset }}
|
||||
LINUX_ASSET: ${{ needs.build-linux.outputs.asset }}
|
||||
APP_NAME: ${{ inputs.app-name }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
python3 -B .nightly-tools/scripts/nightly_artifacts.py verify --kind identity --directory .nightly-input --expected-sha256 "$IDENTITY_SHA256"
|
||||
python3 -B .nightly-tools/scripts/nightly_artifacts.py verify --kind zip --directory .nightly-build --asset "$ASSET" --expected-sha256 "$ZIP_SHA256"
|
||||
python3 -B .nightly-tools/scripts/nightly_artifacts.py verify --kind zip --directory .nightly-build-windows-x86_64 --asset "$WINDOWS_ASSET" --expected-sha256 "$WINDOWS_SHA256"
|
||||
python3 -B .nightly-tools/scripts/nightly_artifacts.py verify --kind zip --directory .nightly-build-macos-aarch64 --asset "$MACOS_ASSET" --expected-sha256 "$MACOS_SHA256"
|
||||
mkdir .nightly-build
|
||||
cp -- ".nightly-build-windows-x86_64/$WINDOWS_ASSET" ".nightly-build-macos-aarch64/$MACOS_ASSET" .nightly-build/
|
||||
# Linux ships the verified tar.gz and its detached .asc only; the bundled key export is never staged.
|
||||
cp -- ".nightly-build-linux-x86_64/$LINUX_ASSET" ".nightly-build-linux-x86_64/$LINUX_ASSET.asc" .nightly-build/
|
||||
python3 -B .nightly-tools/scripts/nightly_feed.py stage-v2 \
|
||||
--registry .nightly-tools/nightly-apps.json --app "$APP_NAME" \
|
||||
--identity .nightly-input/nightly-identity.json --policy .nightly-input/nightly-producer-policy.json \
|
||||
--artifacts .nightly-build --output .nightly-publish
|
||||
- name: Bind the staged manifest/hash set and final signed producer ZIP
|
||||
- name: Bind the staged manifest/hash set and every final signed producer ZIP
|
||||
id: seal
|
||||
env:
|
||||
ASSET: ${{ needs.build-windows.outputs.asset }}
|
||||
ZIP_SHA256: ${{ needs.build-windows.outputs.zip-sha256 }}
|
||||
SIGNER_RECEIPT_SHA256: ${{ needs.build-windows.outputs.receipt-sha256 }}
|
||||
ORIGINAL_UNSIGNED_SHA256: ${{ needs.build-windows.outputs.unsigned-sha256 }}
|
||||
run: python3 -B .nightly-tools/scripts/nightly_artifacts.py seal --kind packet --directory .nightly-publish --asset "$ASSET" --zip-sha256 "$ZIP_SHA256"
|
||||
WINDOWS_ASSET: ${{ needs.build-windows.outputs.asset }}
|
||||
WINDOWS_SHA256: ${{ needs.build-windows.outputs.zip-sha256 }}
|
||||
MACOS_ASSET: ${{ needs.build-macos.outputs.asset }}
|
||||
MACOS_SHA256: ${{ needs.build-macos.outputs.sha256 }}
|
||||
LINUX_ASSET: ${{ needs.build-linux.outputs.asset }}
|
||||
LINUX_SHA256: ${{ needs.build-linux.outputs.sha256 }}
|
||||
run: python3 -B .nightly-tools/scripts/nightly_artifacts.py seal --kind packet --directory .nightly-publish --asset "$WINDOWS_ASSET,$LINUX_ASSET,$MACOS_ASSET" --zip-sha256 "$WINDOWS_SHA256,$LINUX_SHA256,$MACOS_SHA256"
|
||||
- name: Upload the stage-producer-bound packet
|
||||
id: upload
|
||||
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
@@ -391,6 +529,7 @@ jobs:
|
||||
if-no-files-found: error
|
||||
retention-days: 14
|
||||
|
||||
|
||||
attest-nightly:
|
||||
if: ${{ false }} # Actual attestation/publication needs separate explicit authorization.
|
||||
needs: [identity, status, build-windows, stage-nightly]
|
||||
@@ -402,7 +541,7 @@ jobs:
|
||||
id-token: write
|
||||
attestations: write
|
||||
env:
|
||||
NIGHTLY_WINDOWS_PUBLISHER_SUBJECT: ${{ vars.NIGHTLY_WINDOWS_PUBLISHER_SUBJECT }}
|
||||
NIGHTLY_WINDOWS_PUBLISHER_SUBJECT: ${{ inputs.windows-publisher-subject }}
|
||||
steps:
|
||||
- name: Read exact application source
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
@@ -540,7 +679,7 @@ jobs:
|
||||
actions: read
|
||||
checks: read
|
||||
env:
|
||||
NIGHTLY_WINDOWS_PUBLISHER_SUBJECT: ${{ vars.NIGHTLY_WINDOWS_PUBLISHER_SUBJECT }}
|
||||
NIGHTLY_WINDOWS_PUBLISHER_SUBJECT: ${{ inputs.windows-publisher-subject }}
|
||||
steps:
|
||||
- name: Read exact application source
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
|
||||
+3
-3
@@ -1,12 +1,12 @@
|
||||
# Private Unix producer source (v6)
|
||||
|
||||
Linux/x86_64 comes first; macOS/aarch64 follows only after Windows proof and Linux qualification. No native run, signing action, workflow activation, publication, schedule or admission is authorized by this source packet.
|
||||
Update (nightly launch): macOS/aarch64 is admitted with Windows behind production signing; see docs/nightly-release-ref-signing.md. The historical text below describes the earlier pending state. No native run, signing action, workflow activation, publication, schedule or admission is authorized by this source packet.
|
||||
|
||||
## Owner agreement
|
||||
|
||||
Photo and Launcher agreed the two rows in `nightly-unix-pending.json`. This is a separate strict **pending-capability** schema: `nightly_feed.py`, the active registry, staging and publisher never consume it. Existing Photo Windows feed admission and E4 inputs/wrapper remain unchanged. The initial Unix-only scope was expanded by the adversarial disposition: new policy, Windows packaged-version smoke and shared provenance/permission wiring are also present. Stable release bytes and actual frozen E4 inputs remain untouched. See `../../V6-PRIVATE.md`.
|
||||
|
||||
* Linux: `linux/x86_64/tar_gz`, Rust `x86_64-unknown-linux-gnu`, root `photocraft`, `photocraft-{version}-linux-x86_64-nightly.tar.gz`.
|
||||
* Linux (feed-admitted with Windows, production signing still caller opt-in; not runtime-qualified): `linux/x86_64/tar_gz`, Rust `x86_64-unknown-linux-gnu`, root `photocraft`, `photocraft-{version}-linux-x86_64-nightly.tar.gz`.
|
||||
* Mac: `macos/aarch64/portable_zip`, Rust `aarch64-apple-darwin`, one `PhotoCraft Nightly.app/Contents/MacOS/PhotoCraft`, `photocraft-{version}-macos-aarch64-nightly.zip`.
|
||||
* Both: package `ai.storyteller.photocraft.nightly`, profile contract `nightly` version 1, no associations. Launcher alone constructs literal `--launch-profile nightly-v1 --profile-root <persistent nightly data>/profiles/photocraft -- <files>`. The root is persistent, not an installation/rollback directory. App-specific stable XDG config/data/cache/state and Library subtrees/installations are the boundaries, **not whole shared OS bases**. The producer does not access profiles or construct a launcher command from feed text.
|
||||
|
||||
@@ -20,7 +20,7 @@ Photo and Launcher agreed the two rows in `nightly-unix-pending.json`. This is a
|
||||
|
||||
Archive processing streams 1 MiB blocks, at most 10,000 members, path depth 32, 8 GiB per compressed asset/member and 16 GiB expanded payload. JSON/plist is 256 KiB. ZIP central-directory allocation is bounded at 8 MiB before ZipFile construction; ZIP64/split archives are refused. TAR metadata is limited to 256 KiB per read and 8 MiB cumulative, including chained PAX/long-name records; oversized reads/seeks are refused before library allocation. Complexity is O(payload bytes + member count * bounded path depth), with bounded metadata and no retained whole payload. Private unpack requires a new explicit absolute scratch directory; failed scratch is never a feed or eligible artifact, and must not be executed after a failed check.
|
||||
|
||||
## Mac signing remains closed
|
||||
## Mac signing (superseded)
|
||||
|
||||
The default `check` and all Mac extraction/build paths refuse while production signing/team-ID/notarization policy is pending. There is no secret input, environment switch, unsigned/ad-hoc fallback, fake team or self-asserted signature proof. `inventory` can inspect synthetic Mac fixture bytes but always returns `signature_verified: false`, `runtime_qualified: false`, `feed_admitted: false`. It is not the signed-plist verification step. A possible future explicitly authorized private-local ad-hoc mode would need separate app/operator agreement, local-only outputs and refusal by production/admission; this packet does not implement or grant that execution mode.
|
||||
|
||||
|
||||
@@ -1,10 +1,86 @@
|
||||
# Windows release-ref nightly signer source
|
||||
# Release-ref nightly signer source (Windows, Linux and macOS, one release)
|
||||
|
||||
This is a separate source implementation, not activation or release qualification.
|
||||
The existing stable `release.yml`, legacy candidate v1/v2 policy parsers, signing adapter and public
|
||||
pruning behavior are unchanged. No production policy is installed by this repository.
|
||||
PhotoCraft's prepared callers remain literally disabled until reviewed promotion.
|
||||
|
||||
## Policy v3: one release for every admitted platform
|
||||
|
||||
Live admission now requires `craft-nightly-release-policy/v3`. It keeps every v2
|
||||
field except `platform`, `unsigned_artifact_name` and `windows_publisher_subject`,
|
||||
which move into a per-platform map:
|
||||
|
||||
```json
|
||||
"platforms": {
|
||||
"windows-x86_64": {"unsigned_artifact_name": "nightly-unsigned-windows-x86_64",
|
||||
"trust": {"publisher_subject": "<exact Authenticode subject>"}},
|
||||
"macos-aarch64": {"unsigned_artifact_name": "nightly-unsigned-macos-aarch64",
|
||||
"trust": {"apple_team_id": "<stable's ten-character team>"}},
|
||||
"linux-x86_64": {"unsigned_artifact_name": "nightly-unsigned-linux-x86_64",
|
||||
"trust": {"fingerprint": "2B76741B414AAD6CD33E631213A005C0B9D7C3ED"}}
|
||||
}
|
||||
```
|
||||
|
||||
The producer caller must request the same three platforms in the one run the signer
|
||||
admits, for example:
|
||||
|
||||
```yaml
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@<reviewed SHA>
|
||||
with:
|
||||
platforms: '["windows-x86_64","linux-x86_64","macos-aarch64"]'
|
||||
```
|
||||
|
||||
`platforms` is validated once (`select-platforms`): a non-empty JSON array of
|
||||
distinct supported IDs, never a bare string.
|
||||
|
||||
The map's keys must equal the photocraft targets admitted in `nightly-apps.json`.
|
||||
A nightly release carries every admitted platform or nothing: one failed or skipped
|
||||
platform job stops publication for that night, Windows included. v1 and v2 stay
|
||||
valid for authenticated history only (`craft-nightly-release-publication/v1`);
|
||||
new releases record `craft-nightly-release-publication/v2` with one
|
||||
`craft-nightly-signing/v3` receipt per platform. Requests become
|
||||
`craft-nightly-release-request/v2` with an exact `artifacts` map, one producer
|
||||
artifact per platform, each re-read live and bound to its platform's kind.
|
||||
|
||||
Platform plug-ins live in `scripts/nightly_release_platforms.py` (Windows, macOS)
|
||||
and `scripts/nightly_release_linux.py` (Linux). Each signs one validated payload
|
||||
in its own protected job, receives only its own secrets, and is re-verified
|
||||
keylessly before a receipt exists. The trust value is the identity native
|
||||
verification must report; a plug-in's claim alone is never accepted.
|
||||
|
||||
Producer (`nightly-unsigned.yml`, main): the caller lists `platforms`
|
||||
(default `["windows-x86_64"]`). macOS builds on `macos-15-xlarge` with
|
||||
`bash packaging/macos/nightly.sh --arch aarch64`, no secrets or environment, runs
|
||||
the inventory and the ad-hoc `--version` smoke there, then hands off the ZIP as
|
||||
`<asset>.unsigned.zip` to a fresh Ubuntu attester. The release signer requires every
|
||||
admitted platform's artifact from the one producer run.
|
||||
|
||||
Signer (`nightly-release.yml`, release branch):
|
||||
|
||||
| Job | Runner | Environment / secrets | Role |
|
||||
| --- | --- | --- | --- |
|
||||
| validate | windows-latest | none | admits once, downloads each platform's exact artifact ID into `.unsigned/<platform>`, runs trusted `gh attestation verify` per payload |
|
||||
| sign-windows | windows-latest | `release`: PFX/Azure names | unchanged Authenticode route |
|
||||
| sign-macos | macos-15 | `release`: the six stable `APPLE_*`/`KEYCHAIN_PASSWORD` names | app `packaging/macos/nightly-sign.sh` from the release checkout: stable `import-cert.sh`, `codesign --options runtime --timestamp`, `notarytool submit --apple-id --password --team-id --wait` (Accepted only), `stapler staple`; 5400 s budget |
|
||||
| verify-macos | macos-15 | none | keyless: thin arm64, `Identifier=ai.storyteller.photocraft.nightly`, Developer ID authority, exact team, hardened runtime, secure timestamp, `codesign --verify --strict --deep`, `stapler validate`, Gatekeeper `source=Notarized Developer ID` from the reviewed team |
|
||||
| smoke-macos | macos-15 | none, contents read only | after the digest equals verify-macos's output, runs the app's `nightly-verify.sh --expect signed` (`--version` of the shipped, hardened-runtime bytes) |
|
||||
| sign-linux | ubuntu-22.04 | `release`: `LINUX_SIGNING_KEY` in the sign step only | stable OpenPGP detached `<asset>.asc`, tar bytes unchanged |
|
||||
| verify-linux | ubuntu-22.04 | none | keyless gpgv against the reviewed source key, bound to the policy fingerprint |
|
||||
| publish | windows-latest | none | runs unless the workflow is cancelled (`!cancelled()`); requires every admitted platform's jobs to succeed, rechecks each per-platform bundle digest and receipt, verifies Windows natively, binds macOS to verify-macos's exact digest, attests every final asset and publishes one release |
|
||||
|
||||
The macOS route copies stable's: same `release` environment, same secret names,
|
||||
same Apple ID + app-specific password notarization (not an API key). The nightly
|
||||
bundle ID differs (`ai.storyteller.photocraft.nightly`) but the team must be
|
||||
stable's. Final ZIPs are created without resource forks or extended attributes so
|
||||
a Launcher extractor cannot break the seal.
|
||||
|
||||
Activation prerequisites added by macOS: Photo's `packaging/macos/nightly.sh`,
|
||||
`nightly-sign.sh`, `nightly-verify.sh` and `import-cert.sh` must exist in both the
|
||||
main producer source and the protected release checkout; the reviewed v3 policy
|
||||
must carry the real Apple team; the caller must list `macos-aarch64`. None of this
|
||||
has run on a Mac or against Apple's services from this repository.
|
||||
|
||||
## Trust boundaries
|
||||
|
||||
- `nightly-unsigned.yml` is reusable only. A credentialless main compiler preserves
|
||||
@@ -162,3 +238,37 @@ Pausing must work through existing workflow controls without a release push. Thi
|
||||
source change authorizes no release push/build/dispatch/signing/activation/settings
|
||||
or secrets changes. Shared signing identity incidents can affect stable trust too;
|
||||
reconcile the shared identity/credentials and affected outputs, not just one nightly.
|
||||
|
||||
## Linux x86_64 plug-in
|
||||
|
||||
`scripts/nightly_release_linux.py` plugs Linux into the multi-platform v3 signer
|
||||
with the stable OpenPGP route, not a new scheme. Policy trust is
|
||||
`{"fingerprint": "<full uppercase primary>"}`; for PhotoCraft that is the stable
|
||||
ArtCraft Linux Release Signing Key, primary
|
||||
`2B76741B414AAD6CD33E631213A005C0B9D7C3ED` (signing subkey
|
||||
`568DC1F68F8FAECC797F3C7B006DAF6BB0EF334E`). The protected release checkout
|
||||
must contain exactly that one public key at `.github/nightly-linux-signing-key.asc`.
|
||||
|
||||
- Producer: `nightly-unsigned.yml` `build-linux` (ubuntu-22.04, no secrets,
|
||||
environment or OIDC) runs only when the caller's `platforms` list includes
|
||||
`linux-x86_64`. It builds `bash packaging/linux/nightly.sh --arch x86_64`,
|
||||
inventories and smokes the GUI in the compiler job, and hands off
|
||||
`photocraft-<v>-linux-x86_64-nightly.unsigned.tar.gz`; `attest-linux` attests
|
||||
it on a fresh runner.
|
||||
- `sign-linux` (ubuntu, `release` environment): guard first, then the single sign
|
||||
step receives `LINUX_SIGNING_KEY`. The plug-in inventories the tarball as data
|
||||
before importing the key (links, CLI, install hooks or a non-x86_64 GUI refuse),
|
||||
signs a detached ASCII-armored `<asset>.asc` in a private temporary keyring,
|
||||
and re-verifies keylessly. Tar bytes never change (`BYTES_MAY_BE_UNCHANGED`).
|
||||
The only published support file is `<asset>.asc` (it is the feed v2
|
||||
`signature` row). No in-release key export is shipped: trust is the reviewed
|
||||
key, and every recorded support file must be a public asset for later
|
||||
history checks.
|
||||
- `verify-linux` (fresh, keyless): exact two-file inventory and size/SHA-256
|
||||
bindings, data-only tar inventory, and gpgv against the reviewed source key with
|
||||
one good SHA-2 binary signature bound to the primary fingerprint. Verification
|
||||
refuses to run with `LINUX_SIGNING_KEY` present.
|
||||
|
||||
Tests (`tests/test_nightly_release_linux.py`) use real GnuPG with throwaway keys
|
||||
of the stable shape and the published stable key/signature as fixtures. They are
|
||||
not a hosted run, a production-key signature or Launcher install proof.
|
||||
+33
-15
@@ -3,9 +3,9 @@
|
||||
Nothing in this change configures GitHub, uses real signing credentials, runs a
|
||||
native build, publishes an attestation/release, or enables a schedule. Those
|
||||
remain publisher/user actions. Historical unsigned Windows proof is not proof of
|
||||
the final signed bytes. Linux and macOS build callers and native jobs stay
|
||||
literally disabled. Registry tuples, frozen fixtures and native truth gates are
|
||||
unchanged.
|
||||
the final signed bytes. The Linux and macOS build and signer jobs are opt-in: they
|
||||
run only when the app caller sets `production-signing: true`. Main-route
|
||||
attestation and publication remain hard-disabled (literal `false`).
|
||||
|
||||
## Signing boundary
|
||||
|
||||
@@ -70,18 +70,20 @@ or job env, checkout/build/smoke steps, or downstream publishing jobs.
|
||||
|
||||
| Platform | Existing secret names (exact) | Required nonsecret trust policy |
|
||||
| --- | --- | --- |
|
||||
| Windows PFX | `WINDOWS_CERTIFICATE` (base64 PFX), `WINDOWS_CERTIFICATE_PASSWORD` | `NIGHTLY_WINDOWS_PUBLISHER_SUBJECT` repository variable, exact full subject accepted by Windows policy |
|
||||
| Windows PFX | `WINDOWS_CERTIFICATE` (base64 PFX), `WINDOWS_CERTIFICATE_PASSWORD` | reviewed `windows-publisher-subject` caller input (main route) or the v3 policy's `publisher_subject` (release route), committed source, no repository variable; exact full subject accepted by Windows policy |
|
||||
| Windows alternative | all of `AZURE_TENANT_ID`, `AZURE_CLIENT_ID`, `AZURE_CLIENT_SECRET`, `AZURE_SIGNING_ENDPOINT`, `AZURE_SIGNING_ACCOUNT`, `AZURE_CERT_PROFILE` | same exact publisher subject; trust the valid chain, not one rotating leaf |
|
||||
| macOS | all of `APPLE_CERTIFICATE` (base64 Developer ID P12), `APPLE_CERTIFICATE_PASSWORD`, `KEYCHAIN_PASSWORD`, `APPLE_ID`, `APPLE_PASSWORD` (app-specific), `APPLE_TEAM_ID` | `NIGHTLY_APPLE_TEAM_ID` repository variable; exact ten-character team must match signing configuration |
|
||||
| Linux | `LINUX_SIGNING_KEY` (existing ASCII-armored, unprotected OpenPGP signing key/subkey) | reviewed app-source `.github/nightly-linux-signing-key.asc`, exactly one primary public key, plus `NIGHTLY_LINUX_SIGNING_FINGERPRINT` repository variable with its independently reviewed full uppercase primary fingerprint |
|
||||
| macOS | all of `APPLE_CERTIFICATE` (base64 Developer ID P12), `APPLE_CERTIFICATE_PASSWORD`, `KEYCHAIN_PASSWORD`, `APPLE_ID`, `APPLE_PASSWORD` (app-specific), `APPLE_TEAM_ID` | reviewed `apple-team-id` caller input (main route) or the v3 policy's `apple_team_id` (release route), both committed source, no repository variable; exact ten-character team must match `APPLE_TEAM_ID` |
|
||||
| Linux | `LINUX_SIGNING_KEY` (existing ASCII-armored, unprotected OpenPGP signing key/subkey) | reviewed app-source `.github/nightly-linux-signing-key.asc`, exactly one primary public key, plus the `linux-signing-fingerprint` caller input committed in reviewed caller source (never a repository variable) with its independently reviewed full uppercase primary fingerprint |
|
||||
|
||||
Repository variables are needed for downstream receipt rechecks outside the
|
||||
protected environment. Changes require normal reviewed publisher policy. No
|
||||
The Windows subject and Apple team are public, so they come from committed,
|
||||
reviewed source (caller inputs on the main route, the v3 policy on the release
|
||||
route), not repository variables; downstream receipt rechecks read the same input.
|
||||
Changes require normal reviewed publisher policy. No
|
||||
actual subject, Apple team, public key, fingerprint, credentials, reviewers or
|
||||
GitHub settings are supplied by this source draft. Missing policy/configuration
|
||||
fails closed. A partially configured PFX must not silently select Azure instead.
|
||||
|
||||
## macOS aarch64: authored path, not admission
|
||||
## macOS aarch64: admitted, behind production signing
|
||||
|
||||
The pending Mac build job remains on the native Arm runner and validates the
|
||||
pending aarch64 bundle inventory. Before compilation it explicitly requires
|
||||
@@ -108,10 +110,18 @@ team, hardened runtime, secure timestamp, signature integrity, stapled ticket
|
||||
and Gatekeeper assessment without executing payload. Ad-hoc, missing signatures
|
||||
or notarization never fall back to success.
|
||||
|
||||
The actual Photo nightly Mac adapter and native proof are incomplete. The old
|
||||
`nightly_unix.py require_build_policy` Mac refusal deliberately remains too;
|
||||
removing it is a later source/native policy decision, not a result of authoring
|
||||
signer YAML. No macOS tuple is admitted or staged into the current feed.
|
||||
macOS is now admitted to the registry with Windows (one release carries both).
|
||||
The macOS producer, presence preflight and signer jobs run only when the app caller
|
||||
sets `production-signing: true` and selects `macos-aarch64`; the producer also runs
|
||||
the ad-hoc `--version` smoke in its secret-free job. `nightly_unix.py` no longer
|
||||
refuses Mac builds. Main-route `stage-nightly` requires the Windows, Linux and macOS
|
||||
jobs to succeed and stages one packet: the signed Windows ZIP, the notarized macOS
|
||||
ZIP, the Linux tar.gz and its detached `.asc` (the bundled key export is never staged),
|
||||
plus `NIGHTLY.json` and `SHA256SUMS.txt`; the packet seal binds every asset and the
|
||||
`.asc`. Main-route attestation and publication remain literally off. Verification now
|
||||
also requires the exact nightly `Identifier` and Gatekeeper's
|
||||
`source=Notarized Developer ID` from the reviewed team. No native Mac run has
|
||||
happened from this repository.
|
||||
|
||||
## Linux: use the stable OpenPGP scheme, not a new one
|
||||
|
||||
@@ -148,8 +158,16 @@ expired-policy signatures. Never bootstrap trust from `release-signing-key.asc`
|
||||
in the same release/feed, even if a manifest hash agrees. Signature asset name,
|
||||
size and hash must be bound by agreed `craft-nightly/v2` artifact.signature Download metadata (same release, exact `<archive>.asc`, 16 KiB cap), checksum lines and release asset digest, with verification before unpack/swap. No v1/debug fallback is permitted.
|
||||
Rotation needs a separately reviewed trust update, not a feed-supplied new key.
|
||||
The current feed schema and Launcher do not implement this contract; Linux
|
||||
remains unadmitted, with no claim of signed-install or native proof. A future
|
||||
Shared actions now admit `linux-x86_64` to the feed registry next to Windows (one
|
||||
release carries every admitted target; see the release-ref doc). The main-route
|
||||
Linux producer and signer jobs are gated by the caller's `production-signing`
|
||||
opt-in like Windows, and `LINUX_SIGNING_KEY` is declared and forwarded by name at
|
||||
`nightly.yml` → `nightly-unix.yml` → `nightly-signing-unix.yml`, never inherited.
|
||||
Verification uses gpgv with only the reviewed key and requires exactly one good,
|
||||
unexpired, unrevoked SHA-2 binary-document signature whose VALIDSIG primary is
|
||||
the reviewed fingerprint (the stable key signs with its subkey). The Launcher
|
||||
contract above is still separate work; admission here is no signed-install or
|
||||
native runtime proof. A future
|
||||
Linux publisher must carry/verify the signature support and any signed checksum
|
||||
metadata too, not just reuse the current Windows-only three-file packet.
|
||||
|
||||
|
||||
@@ -28,6 +28,13 @@ jobs:
|
||||
AZURE_SIGNING_ENDPOINT: ${{ secrets.AZURE_SIGNING_ENDPOINT }}
|
||||
AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }}
|
||||
AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }}
|
||||
APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
|
||||
APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
|
||||
KEYCHAIN_PASSWORD: ${{ secrets.KEYCHAIN_PASSWORD }}
|
||||
APPLE_ID: ${{ secrets.APPLE_ID }}
|
||||
APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
|
||||
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
|
||||
LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }}
|
||||
with:
|
||||
tooling-revision: REVIEWED_PUBLISHED_TOOLING_SHA_REQUIRED
|
||||
app-name: photocraft
|
||||
@@ -35,3 +42,6 @@ jobs:
|
||||
force: false
|
||||
manual-actors: '[]' # Manual runs and all re-runs stay denied until separately reviewed.
|
||||
production-signing: false # Nothing is signed or staged until explicit signing/publication approval sets true.
|
||||
windows-publisher-subject: REVIEWED_STABLE_WINDOWS_PUBLISHER_SUBJECT_REQUIRED # Exact public Authenticode subject; reviewed here, not a repo variable.
|
||||
apple-team-id: REVIEWED_STABLE_APPLE_TEAM_ID_REQUIRED # Public ten-character team that signs stable; reviewed here, not a repo variable.
|
||||
linux-signing-fingerprint: 2B76741B414AAD6CD33E631213A005C0B9D7C3ED # Public stable Linux primary key; must match .github/nightly-linux-signing-key.asc.
|
||||
+29
-1
@@ -86,7 +86,7 @@
|
||||
},
|
||||
"photocraft": {
|
||||
"default_branch": "main",
|
||||
"note": "Private E1-E5 candidate only: Photo nightly-v1 Windows x86_64 GUI ZIP. Publication hard-disabled; native isolation qualification is still required.",
|
||||
"note": "Photo nightly-v1 Windows x86_64 GUI ZIP, Linux x86_64 GUI tar.gz (OpenPGP detached .asc, stable key) and macOS aarch64 notarized app ZIP, published together in one release. Production signing and publication stay off until the app caller opts in.",
|
||||
"repository": "storytold/photocraft",
|
||||
"targets": [
|
||||
{
|
||||
@@ -102,6 +102,34 @@
|
||||
"format": "portable_zip",
|
||||
"os": "windows"
|
||||
}
|
||||
},
|
||||
{
|
||||
"asset_pattern": "photocraft-{version}-linux-x86_64-nightly.tar.gz",
|
||||
"isolation": {
|
||||
"associations": "none",
|
||||
"package_identity": "ai.storyteller.photocraft.nightly",
|
||||
"profile_contract": "nightly",
|
||||
"profile_version": 1
|
||||
},
|
||||
"target": {
|
||||
"arch": "x86_64",
|
||||
"format": "tar_gz",
|
||||
"os": "linux"
|
||||
}
|
||||
},
|
||||
{
|
||||
"asset_pattern": "photocraft-{version}-macos-aarch64-nightly.zip",
|
||||
"isolation": {
|
||||
"associations": "none",
|
||||
"package_identity": "ai.storyteller.photocraft.nightly",
|
||||
"profile_contract": "nightly",
|
||||
"profile_version": 1
|
||||
},
|
||||
"target": {
|
||||
"arch": "aarch64",
|
||||
"format": "portable_zip",
|
||||
"os": "macos"
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
|
||||
@@ -17,8 +17,8 @@
|
||||
"profile_version": 1,
|
||||
"associations": "none"
|
||||
},
|
||||
"status": "private-source-pending",
|
||||
"feed_admitted": false,
|
||||
"status": "feed-admitted",
|
||||
"feed_admitted": true,
|
||||
"runtime_qualified": false
|
||||
},
|
||||
"macos-aarch64": {
|
||||
@@ -36,8 +36,8 @@
|
||||
"profile_version": 1,
|
||||
"associations": "none"
|
||||
},
|
||||
"status": "private-source-pending",
|
||||
"feed_admitted": false,
|
||||
"status": "feed-admitted",
|
||||
"feed_admitted": true,
|
||||
"runtime_qualified": false
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,13 +17,30 @@ def download_contract(artifact_id,expected_sha256):
|
||||
n.require(int(artifact_id)<=9007199254740991,'artifact ID exceeds exact JavaScript numeric transport range')
|
||||
n.require(isinstance(expected_sha256,str) and SHA256.fullmatch(expected_sha256), 'independent producer SHA256 required')
|
||||
|
||||
LINUX_SUFFIX='-linux-x86_64-nightly.tar.gz'
|
||||
|
||||
def asset_names(asset,kind):
|
||||
"""One exact ZIP for a build boundary; a packet may list every admitted platform (comma-separated).
|
||||
|
||||
Only a packet may carry the admitted Linux tar.gz, always with its detached .asc.
|
||||
"""
|
||||
n.require(isinstance(asset,str),'exact nightly ZIP asset required')
|
||||
names=asset.split(',') if kind=='packet' else [asset]
|
||||
n.require(0<len(names)<=8 and len(set(names))==len(names) and
|
||||
all(n.NAME.fullmatch(name) and 'nightly' in name and
|
||||
(name.endswith('.zip') or (kind=='packet' and name.endswith(LINUX_SUFFIX))) for name in names),'exact nightly ZIP asset required')
|
||||
return names
|
||||
|
||||
def packet_signatures(assets):
|
||||
return {name+'.asc' for name in assets if name.endswith(LINUX_SUFFIX)}
|
||||
|
||||
def inventory(directory,kind,asset=None):
|
||||
directory=Path(directory)
|
||||
n.require(directory.is_dir() and not directory.is_symlink(),'artifact directory must be a regular directory')
|
||||
if kind=='identity': expected=IDENTITY_FILES
|
||||
if kind=='identity': expected=IDENTITY_FILES; assets=set()
|
||||
else:
|
||||
n.require(isinstance(asset,str) and n.NAME.fullmatch(asset) and 'nightly' in asset and asset.endswith('.zip'),'exact nightly ZIP asset required')
|
||||
expected={asset} if kind=='zip' else {asset,'NIGHTLY.json','SHA256SUMS.txt'}
|
||||
assets=asset_names(asset,kind)
|
||||
expected=set(assets) if kind=='zip' else set(assets)|{'NIGHTLY.json','SHA256SUMS.txt'}|packet_signatures(assets)
|
||||
n.require(kind in ('identity','zip','packet'),'unknown artifact boundary')
|
||||
# Stop before retaining an attacker-controlled unbounded inventory.
|
||||
actual=set()
|
||||
@@ -33,7 +50,7 @@ def inventory(directory,kind,asset=None):
|
||||
n.require(actual==expected,'missing artifact file')
|
||||
metadata={}; total=0
|
||||
for name in sorted(expected):
|
||||
if name!=asset:
|
||||
if name not in assets:
|
||||
stream,info=n.regular_file(directory,name)
|
||||
with stream:
|
||||
n.require(info.st_size<=n.MAX_JSON_BYTES,'artifact metadata exceeds bound')
|
||||
@@ -58,10 +75,13 @@ def verify(directory,kind,expected_sha256,asset=None,zip_sha256=None):
|
||||
n.require(isinstance(expected_sha256,str) and SHA256.fullmatch(expected_sha256),'independent producer SHA256 required')
|
||||
n.require(fingerprint(directory,kind,asset)==expected_sha256,kind+' artifact differs from its independent producer output')
|
||||
if kind=='packet':
|
||||
n.require(isinstance(zip_sha256,str) and SHA256.fullmatch(zip_sha256),'original ZIP producer binding required')
|
||||
# The ZIP fingerprint is the original build job's hash, not a packet claim.
|
||||
_,digest=n.digest_file(directory,asset)
|
||||
n.require(digest==zip_sha256,'packet ZIP differs from original build producer output')
|
||||
names=asset_names(asset,kind)
|
||||
hashes=zip_sha256.split(',') if isinstance(zip_sha256,str) else []
|
||||
n.require(len(hashes)==len(names) and all(SHA256.fullmatch(value) for value in hashes),'original ZIP producer binding required')
|
||||
# Each ZIP fingerprint is its original build job's hash, not a packet claim.
|
||||
for name,expected in zip(names,hashes):
|
||||
_,digest=n.digest_file(directory,name)
|
||||
n.require(digest==expected,'packet ZIP differs from original build producer output')
|
||||
return True
|
||||
|
||||
def verify_chain(identity_directory,packet_directory,identity_sha256,packet_sha256,zip_sha256,asset):
|
||||
|
||||
+392
-123
@@ -1,5 +1,5 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Windows release-ref bridge. Artifacts are data; execution context stays real.
|
||||
"""Release-ref bridge for every admitted platform. Artifacts are data; execution context stays real.
|
||||
|
||||
The reusable workflows, not caller JSON, establish the executable/gh verifier
|
||||
and independent job-output hash trust roots. v1/v2 main-only CLIs stay unchanged.
|
||||
@@ -20,12 +20,15 @@ from urllib.parse import quote
|
||||
import nightly_feed as n
|
||||
import nightly_ownership_receipt as ownership
|
||||
import nightly_policy as p
|
||||
import nightly_release_platforms as plat
|
||||
import nightly_release_request as r
|
||||
import nightly_candidate as c
|
||||
import nightly_signing as signing
|
||||
import publish_nightly as pub
|
||||
|
||||
MARKER = "craft-nightly-release-publication/v1:"
|
||||
MARKER_V2 = "craft-nightly-release-publication/v2:"
|
||||
METADATA_SUFFIX = ".json" # Bundle metadata is always JSON; payload archives (.zip/.tar.gz/.asc) are not.
|
||||
BUNDLE_FILES = {"request.json", "quality.json", "plan.json", "unsigned.json", "unsigned-claims.json"}
|
||||
PUBLISH_STEP = "Publish the signed nightly and preserve ownership"
|
||||
|
||||
@@ -76,20 +79,42 @@ class SonarTransport:
|
||||
connection.close()
|
||||
|
||||
|
||||
def identity_plan(registry, producer, stable):
|
||||
def identity_plan_v1(registry, producer, stable):
|
||||
"""Frozen Windows-only plan of craft-nightly-release-publication/v1 history."""
|
||||
ident, version = n.identity(registry, "photocraft", producer["repository"],
|
||||
producer["source_commit"], stable["version"], producer["run_id"],
|
||||
producer["run_attempt"], p.timestamp(producer["created_at"]))
|
||||
n.require(n.app_record(registry, "photocraft")["targets"] == [
|
||||
__import__("nightly_windows").PHOTO_TARGET], "reviewed Windows target required")
|
||||
asset = "photocraft-"+version+"-windows-x86_64-nightly.zip"
|
||||
return {"schema": "craft-nightly-unsigned-plan/v1", "identity": {**ident, "version": version, "ready": True},
|
||||
"stable_base": copy.deepcopy(stable), "asset": asset, "unsigned_asset": asset[:-4]+".unsigned.zip"}
|
||||
|
||||
|
||||
def unsigned_manifest(plan, producer, payload_sha256):
|
||||
def identity_plan(registry, producer, stable, platforms=None):
|
||||
"""One release for every admitted platform; history may pass its recorded set."""
|
||||
ident, version = n.identity(registry, "photocraft", producer["repository"],
|
||||
producer["source_commit"], stable["version"], producer["run_id"],
|
||||
producer["run_attempt"], p.timestamp(producer["created_at"]))
|
||||
if platforms is None:
|
||||
platforms = plat.registry_platforms(registry)
|
||||
n.require(isinstance(platforms, list) and platforms == sorted(set(platforms)) and platforms, "invalid platform set")
|
||||
rows = {}
|
||||
for platform in platforms:
|
||||
names = plat.plugin(platform).assets(version)
|
||||
n.fields(names, {"asset", "unsigned_asset", "built_asset"}, "platform asset names")
|
||||
n.require(all(isinstance(value, str) and n.NAME.fullmatch(value) and "nightly" in value for value in names.values()) and
|
||||
names["asset"] != names["unsigned_asset"] and names["built_asset"] in (names["asset"], names["unsigned_asset"]),
|
||||
"unsafe platform asset names")
|
||||
rows[platform] = names
|
||||
every = [name for row in rows.values() for name in (row["asset"], row["unsigned_asset"])]
|
||||
n.require(len(every) == len(set(every)), "platform asset names collide")
|
||||
return {"schema": "craft-nightly-unsigned-plan/v2", "identity": {**ident, "version": version, "ready": True},
|
||||
"stable_base": copy.deepcopy(stable), "platforms": rows}
|
||||
|
||||
|
||||
def unsigned_manifest(plan, producer, platform, payload_sha256):
|
||||
r.hash_value(payload_sha256)
|
||||
return {"schema": "craft-nightly-unsigned/v1", "plan": copy.deepcopy(plan),
|
||||
n.require(platform in plan["platforms"], "platform absent from plan")
|
||||
return {"schema": "craft-nightly-unsigned/v2", "platform": platform, "plan": copy.deepcopy(plan),
|
||||
"producer": {key: producer[key] for key in ("repository", "source_commit", "run_id", "run_attempt", "tooling_revision")},
|
||||
"unsigned_sha256": payload_sha256}
|
||||
|
||||
@@ -118,7 +143,9 @@ def finite_files(directory, names):
|
||||
n.require(actual == names, "missing bundle file")
|
||||
total, result = 0, {}
|
||||
for name in sorted(names):
|
||||
if not name.endswith(".zip"):
|
||||
# Only explicit JSON metadata gets the 256 KiB bound. Payloads (Windows/macOS .zip, the
|
||||
# Linux .tar.gz and its .asc) keep the per-asset bound in regular_file plus the aggregate bound.
|
||||
if name.endswith(METADATA_SUFFIX):
|
||||
stream, info = n.regular_file(directory, name)
|
||||
stream.close()
|
||||
n.require(info.st_size <= n.MAX_JSON_BYTES, "oversized bundle metadata")
|
||||
@@ -129,55 +156,56 @@ def finite_files(directory, names):
|
||||
return result
|
||||
|
||||
|
||||
def bundle_hash(directory, asset, *, signed=False):
|
||||
n.require(isinstance(asset, str) and n.NAME.fullmatch(asset) and "nightly" in asset and asset.endswith(".zip"), "exact ZIP asset required")
|
||||
names = BUNDLE_FILES | {asset} | ({"signing.json"} if signed else set())
|
||||
return r.digest({"schema": "craft-nightly-release-bundle/v1", "signed": signed,
|
||||
"files": finite_files(directory, names)})
|
||||
def bundle_names(extra, *, signed=False):
|
||||
extra = set(extra)
|
||||
n.require(extra and all(isinstance(name, str) and n.NAME.fullmatch(name) and name not in BUNDLE_FILES | {"signing.json"}
|
||||
for name in extra), "exact bundle payload names required")
|
||||
return BUNDLE_FILES | extra | ({"signing.json"} if signed else set())
|
||||
|
||||
|
||||
def verify_bundle(directory, expected_sha256, asset, *, signed=False):
|
||||
def bundle_hash(directory, extra, *, signed=False):
|
||||
"""Finite JSON + exact payload/support inventory; extra is every non-JSON file."""
|
||||
if isinstance(extra, str):
|
||||
extra = {extra}
|
||||
names = bundle_names(extra, signed=signed)
|
||||
return r.digest({"schema": "craft-nightly-release-bundle/v1",
|
||||
"signed": signed, "files": finite_files(directory, names)})
|
||||
|
||||
|
||||
def verify_bundle(directory, expected_sha256, extra, *, signed=False):
|
||||
r.hash_value(expected_sha256)
|
||||
n.require(bundle_hash(directory, asset, signed=signed) == expected_sha256, "independent trusted-job bundle digest differs")
|
||||
n.require(bundle_hash(directory, extra, signed=signed) == expected_sha256, "independent trusted-job bundle digest differs")
|
||||
return {name[:-5]: n.bounded_json(Path(directory)/name) for name in BUNDLE_FILES | ({"signing.json"} if signed else set())}
|
||||
|
||||
|
||||
def validated_names(plan):
|
||||
return {row["unsigned_asset"] for row in plan["platforms"].values()}
|
||||
|
||||
|
||||
def signed_names(receipt, plan):
|
||||
"""Names of one platform's signed bundle, read from its yet-unauthenticated receipt."""
|
||||
n.require(isinstance(receipt, dict) and receipt.get("platform") in plan["platforms"], "signed receipt platform unknown")
|
||||
support = r.support_binding(receipt.get("support"))
|
||||
return {plan["platforms"][receipt["platform"]]["asset"], *support}
|
||||
|
||||
|
||||
def verify_signed_bundle(directory, expected_sha256, platform):
|
||||
"""Hash the exact signed bundle first; only then trust any JSON inside it."""
|
||||
directory = n.owned_path(directory)
|
||||
unverified = {name: n.bounded_json(directory/(name+".json")) for name in ("plan", "signing")}
|
||||
n.require(unverified["signing"].get("platform") == platform, "signed bundle platform differs")
|
||||
extra = signed_names(unverified["signing"], unverified["plan"])
|
||||
state = verify_bundle(directory, expected_sha256, extra, signed=True)
|
||||
n.require(state["signing"]["platform"] == platform, "signed bundle platform differs")
|
||||
return state
|
||||
|
||||
|
||||
def ordinal(producer):
|
||||
return {**producer, "id": producer["run_id"], "number": producer["run_number"], "attempt": producer["run_attempt"]}
|
||||
|
||||
|
||||
def previous_publication(api, registry, policy, current_request, rows):
|
||||
"""Authenticate historical protected-release evidence; never execute old code.
|
||||
|
||||
Like v1 ownership evidence, Actions metadata is source-owned evidence, not an
|
||||
independent tag-creator signature. Immutable nightly tags/releases are an
|
||||
activation prerequisite. Pruning remains off and has no path through here.
|
||||
"""
|
||||
release = p.newest_nightly(rows)
|
||||
if release is None:
|
||||
return None # Complete bounded release enumeration + stable base authenticates bootstrap.
|
||||
body = release.get("body", "")
|
||||
if MARKER not in body:
|
||||
prior = p.verify_prior(api, registry, release) # Frozen legacy historical parser, no process-env substitution.
|
||||
return {"identity": prior["identity"], "run": prior["run"]}
|
||||
n.require(isinstance(body, str) and body.count(MARKER) == 1, "ambiguous previous-publication marker")
|
||||
prior = loads(body.split(MARKER, 1)[1].encode())
|
||||
n.fields(prior, {"schema", "request", "plan", "quality", "signing"}, "published release policy")
|
||||
n.require(prior["schema"] == "craft-nightly-release-publication/v1", "unknown prior publication")
|
||||
request = prior["request"]; signer = request["signer"]; producer = request["producer"]
|
||||
old_sha = r.commit(signer["source_commit"])
|
||||
current_sha = current_request["signer"]["source_commit"]
|
||||
lineage = api.request("GET", f"/compare/{old_sha}...{current_sha}")
|
||||
n.require(lineage.get("status") in ("ahead", "identical") and lineage.get("behind_by") == 0 and
|
||||
lineage.get("merge_base_commit", {}).get("sha") == old_sha, "prior signer is not in trusted release history")
|
||||
blob = api.request("GET", "/contents/.github/nightly-signing-policy.json?ref="+old_sha)
|
||||
n.require(blob.get("encoding") == "base64" and type(blob.get("size")) is int and
|
||||
0 < blob["size"] <= n.MAX_JSON_BYTES and isinstance(blob.get("content"), str), "missing bounded prior protected policy")
|
||||
raw = base64.b64decode(blob["content"].replace("\n", ""), validate=True)
|
||||
n.require(len(raw) == blob["size"], "prior policy size differs")
|
||||
old_policy = loads(raw); r.request_contract(old_policy, request)
|
||||
n.require(old_policy["repository"] == policy["repository"] and old_policy["repository_id"] == policy["repository_id"] and
|
||||
old_policy["signer_workflow_path"] == policy["signer_workflow_path"], "historical trust root differs")
|
||||
def verified_history_roles(api, policy, request):
|
||||
signer = request["signer"]
|
||||
for name in ("producer", "signer"):
|
||||
role = request[name]; branch = "release" if name == "signer" else "main"
|
||||
run = api.request("GET", f"/actions/runs/{role['run_id']}/attempts/{role['run_attempt']}")
|
||||
@@ -194,17 +222,94 @@ def previous_publication(api, registry, policy, current_request, rows):
|
||||
publishers = [job for job in jobs if job.get("status") == "completed" and job.get("conclusion") == "success" and
|
||||
any(step.get("name") == PUBLISH_STEP and step.get("conclusion") == "success" for step in job.get("steps", []))]
|
||||
n.require(len(publishers) == 1, "prior successful publication step absent/ambiguous")
|
||||
plan = identity_plan(registry, producer, prior["plan"]["stable_base"])
|
||||
|
||||
|
||||
def prior_policy(api, policy, request, current_request):
|
||||
old_sha = r.commit(request["signer"]["source_commit"])
|
||||
current_sha = current_request["signer"]["source_commit"]
|
||||
lineage = api.request("GET", f"/compare/{old_sha}...{current_sha}")
|
||||
n.require(lineage.get("status") in ("ahead", "identical") and lineage.get("behind_by") == 0 and
|
||||
lineage.get("merge_base_commit", {}).get("sha") == old_sha, "prior signer is not in trusted release history")
|
||||
blob = api.request("GET", "/contents/.github/nightly-signing-policy.json?ref="+old_sha)
|
||||
n.require(blob.get("encoding") == "base64" and type(blob.get("size")) is int and
|
||||
0 < blob["size"] <= n.MAX_JSON_BYTES and isinstance(blob.get("content"), str), "missing bounded prior protected policy")
|
||||
raw = base64.b64decode(blob["content"].replace("\n", ""), validate=True)
|
||||
n.require(len(raw) == blob["size"], "prior policy size differs")
|
||||
old_policy = loads(raw); r.request_contract(old_policy, request)
|
||||
n.require(old_policy["repository"] == policy["repository"] and old_policy["repository_id"] == policy["repository_id"] and
|
||||
old_policy["signer_workflow_path"] == policy["signer_workflow_path"], "historical trust root differs")
|
||||
return old_policy
|
||||
|
||||
|
||||
def prior_assets(api, release, expected):
|
||||
"""Every recorded final/support file must be the exact public asset digest."""
|
||||
assets = api.request("GET", f"/releases/{release['id']}/assets?per_page=100")
|
||||
n.require(isinstance(assets, list) and 0 < len(assets) < 100 and all(isinstance(asset, dict) for asset in assets), "prior asset inventory missing/incomplete/bounded")
|
||||
for name, digest in expected.items():
|
||||
payloads = [asset for asset in assets if asset.get("name") == name]
|
||||
n.require(len(payloads) == 1 and payloads[0].get("digest") == "sha256:"+digest, "prior final asset digest differs")
|
||||
|
||||
|
||||
def previous_publication(api, registry, policy, current_request, rows):
|
||||
"""Authenticate historical protected-release evidence; never execute old code.
|
||||
|
||||
Like v1 ownership evidence, Actions metadata is source-owned evidence, not an
|
||||
independent tag-creator signature. Immutable nightly tags/releases are an
|
||||
activation prerequisite. Pruning remains off and has no path through here.
|
||||
"""
|
||||
release = p.newest_nightly(rows)
|
||||
if release is None:
|
||||
return None # Complete bounded release enumeration + stable base authenticates bootstrap.
|
||||
body = release.get("body", "")
|
||||
n.require(isinstance(body, str), "invalid prior release body")
|
||||
if MARKER_V2 in body:
|
||||
n.require(body.count(MARKER_V2) == 1 and MARKER not in body, "ambiguous previous-publication marker")
|
||||
prior = loads(body.split(MARKER_V2, 1)[1].encode())
|
||||
n.fields(prior, {"schema", "request", "plan", "quality", "signing"}, "published release policy")
|
||||
n.require(prior["schema"] == "craft-nightly-release-publication/v2", "unknown prior publication")
|
||||
request = prior["request"]; producer = request["producer"]
|
||||
old_policy = prior_policy(api, policy, request, current_request)
|
||||
n.require(old_policy["schema"] == r.LIVE_POLICY, "v2 publication requires v3 policy")
|
||||
verified_history_roles(api, old_policy, request)
|
||||
platforms = r.policy_platforms(old_policy)
|
||||
plan = identity_plan(registry, producer, prior["plan"]["stable_base"], platforms)
|
||||
n.require(plan == prior["plan"] and plan["identity"]["tag"] == release["tag_name"], "prior source/version identity differs")
|
||||
n.require(isinstance(prior["signing"], dict) and sorted(prior["signing"]) == platforms, "prior platform receipts differ")
|
||||
expected_assets = {}
|
||||
for platform in platforms:
|
||||
old = prior["signing"][platform]
|
||||
n.fields(old, r.RECEIPT_V3_FIELDS, "prior platform receipt")
|
||||
receipt = r.release_receipt_v3(old_policy, request, platform, old["unsigned_sha256"], old["final_sha256"],
|
||||
r.trusted_signer(old_policy, platform), old["support"])
|
||||
n.require(old == receipt, "prior two-role receipt differs")
|
||||
n.require(set(receipt["support"]) == plat.required_support(platform, plan["platforms"][platform]["asset"]),
|
||||
"prior platform support set differs from its required detached signature files")
|
||||
expected_assets[plan["platforms"][platform]["asset"]] = receipt["final_sha256"]
|
||||
for name, item in receipt["support"].items():
|
||||
expected_assets[name] = item["sha256"]
|
||||
ref = api.request("GET", "/git/ref/tags/"+quote(release["tag_name"], safe=""))
|
||||
n.require(ref.get("object", {}).get("type") == "commit" and ref["object"].get("sha") == producer["source_commit"], "prior tag source differs")
|
||||
prior_assets(api, release, expected_assets)
|
||||
return {"identity": plan["identity"], "run": ordinal(producer)}
|
||||
if MARKER not in body:
|
||||
prior = p.verify_prior(api, registry, release) # Frozen legacy historical parser, no process-env substitution.
|
||||
return {"identity": prior["identity"], "run": prior["run"]}
|
||||
n.require(body.count(MARKER) == 1, "ambiguous previous-publication marker")
|
||||
prior = loads(body.split(MARKER, 1)[1].encode())
|
||||
n.fields(prior, {"schema", "request", "plan", "quality", "signing"}, "published release policy")
|
||||
n.require(prior["schema"] == "craft-nightly-release-publication/v1", "unknown prior publication")
|
||||
request = prior["request"]; producer = request["producer"]
|
||||
old_policy = prior_policy(api, policy, request, current_request)
|
||||
n.require(old_policy["schema"] != r.LIVE_POLICY, "v1 publication requires v1/v2 policy")
|
||||
verified_history_roles(api, old_policy, request)
|
||||
plan = identity_plan_v1(registry, producer, prior["plan"]["stable_base"])
|
||||
n.require(plan == prior["plan"] and plan["identity"]["tag"] == release["tag_name"], "prior source/version identity differs")
|
||||
expected_receipt = r.release_receipt(old_policy, request, prior["signing"]["unsigned_sha256"],
|
||||
prior["signing"]["final_sha256"], old_policy["windows_publisher_subject"])
|
||||
n.require(prior["signing"] == expected_receipt, "prior two-role receipt differs")
|
||||
ref = api.request("GET", "/git/ref/tags/"+quote(release["tag_name"], safe=""))
|
||||
n.require(ref.get("object", {}).get("type") == "commit" and ref["object"].get("sha") == producer["source_commit"], "prior tag source differs")
|
||||
assets = api.request("GET", f"/releases/{release['id']}/assets?per_page=100")
|
||||
n.require(isinstance(assets, list) and 0 < len(assets) < 100 and all(isinstance(asset, dict) for asset in assets), "prior asset inventory missing/incomplete/bounded")
|
||||
payloads = [asset for asset in assets if asset.get("name") == plan["asset"]]
|
||||
n.require(len(payloads) == 1 and payloads[0].get("digest") == "sha256:"+expected_receipt["final_sha256"], "prior final asset digest differs")
|
||||
prior_assets(api, release, {plan["asset"]: expected_receipt["final_sha256"]})
|
||||
return {"identity": plan["identity"], "run": ordinal(producer)}
|
||||
|
||||
|
||||
@@ -212,6 +317,8 @@ def publication_state(api, registry, policy, request):
|
||||
rows = p.releases(api)
|
||||
stable = p.stable_base(rows)
|
||||
plan = identity_plan(registry, request["producer"], stable)
|
||||
# All-or-nothing: the protected policy must sign exactly the admitted registry set.
|
||||
n.require(sorted(plan["platforms"]) == r.policy_platforms(policy), "protected policy platforms differ from admitted registry targets")
|
||||
previous = previous_publication(api, registry, policy, request, rows)
|
||||
if previous is not None:
|
||||
if previous["run"]["source_commit"] == request["producer"]["source_commit"]:
|
||||
@@ -242,12 +349,26 @@ def revalidate(policy, state, environment, api, sonar, registry, *, now):
|
||||
return True
|
||||
|
||||
|
||||
def verified_unsigned(policy, state, directory, *, runner=subprocess.run):
|
||||
def platform_directories(directory, platforms):
|
||||
"""Exactly one downloaded directory per admitted platform, nothing else."""
|
||||
directory = n.owned_path(directory)
|
||||
n.require(directory.is_dir() and not directory.is_symlink(), "regular platform directory required")
|
||||
actual = set()
|
||||
for path in directory.iterdir():
|
||||
n.require(len(actual) < len(platforms) and path.name in platforms and path.is_dir() and not path.is_symlink(),
|
||||
"unexpected platform directory")
|
||||
actual.add(path.name)
|
||||
n.require(actual == set(platforms), "missing platform directory")
|
||||
return {platform: directory/platform for platform in sorted(platforms)}
|
||||
|
||||
|
||||
def verified_unsigned(policy, state, platform, directory, *, runner=subprocess.run):
|
||||
"""Run trusted gh itself; downloaded JSON is never verification evidence."""
|
||||
plan, request = state["plan"], state["request"]
|
||||
finite_files(directory, {plan["unsigned_asset"], "unsigned.json"})
|
||||
_, digest = n.digest_file(directory, plan["unsigned_asset"])
|
||||
manifest = unsigned_manifest(plan, request["producer"], digest)
|
||||
names = plan["platforms"][platform]
|
||||
finite_files(directory, {names["unsigned_asset"], "unsigned.json"})
|
||||
_, digest = n.digest_file(directory, names["unsigned_asset"])
|
||||
manifest = unsigned_manifest(plan, request["producer"], platform, digest)
|
||||
n.require(n.bounded_json(Path(directory)/"unsigned.json") == manifest, "unsigned source/version/hash differs")
|
||||
version = runner(["gh", "--version"], check=True, capture_output=True, timeout=30).stdout.decode()
|
||||
r.require_gh_version(version)
|
||||
@@ -255,7 +376,7 @@ def verified_unsigned(policy, state, directory, *, runner=subprocess.run):
|
||||
with tempfile.TemporaryDirectory(prefix="nightly-gh-verify-", dir=os.environ["RUNNER_TEMP"]) as temporary:
|
||||
evidence = Path(temporary)/"verified.json"
|
||||
with evidence.open("xb") as stream:
|
||||
runner(["gh", "attestation", "verify", str(Path(directory, plan["unsigned_asset"]).resolve()),
|
||||
runner(["gh", "attestation", "verify", str(Path(directory, names["unsigned_asset"]).resolve()),
|
||||
"--repo", policy["repository"], "--signer-workflow", workflow,
|
||||
"--signer-digest", policy["producer_tooling_revision"], "--source-ref", "refs/heads/main",
|
||||
"--source-digest", request["producer"]["source_commit"], "--deny-self-hosted-runners", "--format", "json"],
|
||||
@@ -264,68 +385,182 @@ def verified_unsigned(policy, state, directory, *, runner=subprocess.run):
|
||||
return manifest, claims
|
||||
|
||||
|
||||
def stage_bundle(output, state, directory, manifest, claims):
|
||||
def stage_bundle(output, state, directories, manifests, claims):
|
||||
"""One validated bundle: shared admission JSON plus every platform's unsigned payload."""
|
||||
n.fields(state, {"request", "quality", "plan"}, "validator state")
|
||||
asset = state["plan"]["unsigned_asset"]
|
||||
n.require(isinstance(asset, str) and n.NAME.fullmatch(asset), "unsafe unsigned asset basename")
|
||||
plan = state["plan"]
|
||||
n.require(set(directories) == set(manifests) == set(claims) == set(plan["platforms"]), "platform validation incomplete")
|
||||
# Every derived destination name is checked before the output directory exists.
|
||||
n.require(all(isinstance(row["unsigned_asset"], str) and n.NAME.fullmatch(row["unsigned_asset"]) for row in plan["platforms"].values()),
|
||||
"unsafe unsigned asset basename")
|
||||
output = owned_output(output); output.mkdir(parents=True, exist_ok=False)
|
||||
for name, value in {**state, "unsigned": manifest, "unsigned-claims": claims}.items():
|
||||
for name, value in {**state, "unsigned": manifests, "unsigned-claims": claims}.items():
|
||||
write_json(output/(name+".json"), value)
|
||||
stream, _ = n.regular_file(directory, asset)
|
||||
with stream, (output/asset).open("xb") as destination:
|
||||
shutil.copyfileobj(stream, destination, 1024*1024)
|
||||
n.require(n.digest_file(output, asset)[1] == claims["payload_sha256"], "staged payload changed")
|
||||
return bundle_hash(output, asset)
|
||||
for platform, directory in sorted(directories.items()):
|
||||
asset = plan["platforms"][platform]["unsigned_asset"]
|
||||
n.require(isinstance(asset, str) and n.NAME.fullmatch(asset), "unsafe unsigned asset basename")
|
||||
stream, _ = n.regular_file(directory, asset)
|
||||
with stream, (output/asset).open("xb") as destination:
|
||||
shutil.copyfileobj(stream, destination, 1024*1024)
|
||||
n.require(n.digest_file(output, asset)[1] == claims[platform]["payload_sha256"], "staged payload changed")
|
||||
return bundle_hash(output, validated_names(plan))
|
||||
|
||||
|
||||
def native_sign(policy, state, directory, source, output, environment):
|
||||
def require_unsigned_binding(policy, state, platform, directory):
|
||||
plan, request = state["plan"], state["request"]
|
||||
r.request_contract(policy, request)
|
||||
n.require(state["unsigned-claims"]["request_sha256"] == r.digest(request) and
|
||||
state["unsigned-claims"]["payload_sha256"] == state["unsigned"]["unsigned_sha256"], "unsigned claims binding differs")
|
||||
n.require(n.digest_file(directory, plan["unsigned_asset"])[1] == state["unsigned"]["unsigned_sha256"], "unsigned bytes changed")
|
||||
n.require(platform in plan["platforms"] and sorted(state["unsigned"]) == sorted(state["unsigned-claims"]) == sorted(plan["platforms"]),
|
||||
"platform absent from validated bundle")
|
||||
manifest, claims = state["unsigned"][platform], state["unsigned-claims"][platform]
|
||||
n.require(manifest == unsigned_manifest(plan, request["producer"], platform, manifest["unsigned_sha256"]) and
|
||||
claims["request_sha256"] == r.digest(request) and claims["payload_sha256"] == manifest["unsigned_sha256"],
|
||||
"unsigned claims binding differs")
|
||||
if directory is not None:
|
||||
n.require(n.digest_file(directory, plan["platforms"][platform]["unsigned_asset"])[1] == manifest["unsigned_sha256"], "unsigned bytes changed")
|
||||
return manifest["unsigned_sha256"]
|
||||
|
||||
|
||||
def native_sign(policy, state, platform, directory, source, output, environment):
|
||||
"""Sign exactly one platform; the plug-in re-verifies keylessly before any receipt."""
|
||||
plan = state["plan"]
|
||||
unsigned_sha256 = require_unsigned_binding(policy, state, platform, directory)
|
||||
names = plan["platforms"][platform]
|
||||
output = owned_output(output)
|
||||
n.require(n.NAME.fullmatch(plan["asset"]) and n.NAME.fullmatch(plan["unsigned_asset"]), "unsafe native asset basename")
|
||||
n.require(n.NAME.fullmatch(names["asset"]) and n.NAME.fullmatch(names["unsigned_asset"]), "unsafe native asset basename")
|
||||
output.mkdir(parents=True, exist_ok=False)
|
||||
env = {**environment, "NIGHTLY_WINDOWS_PUBLISHER_SUBJECT": policy["windows_publisher_subject"]}
|
||||
signing.adapter("windows-x86_64", source)
|
||||
signing.require_config("windows-x86_64", env)
|
||||
signer = signing.sign_windows(source, Path(directory)/plan["unsigned_asset"], output/plan["asset"], env, plan["identity"]["version"])
|
||||
receipt = r.release_receipt(policy, request, state["unsigned"]["unsigned_sha256"], n.digest_file(output, plan["asset"])[1], signer)
|
||||
trust = policy["platforms"][platform]["trust"]
|
||||
module = plat.plugin(platform)
|
||||
with tempfile.TemporaryDirectory(prefix="nightly-sign-out-", dir=n.owned_path(environment["RUNNER_TEMP"])) as temporary:
|
||||
signed = Path(temporary)/"signed"; signed.mkdir()
|
||||
result = module.sign(trust, Path(directory)/names["unsigned_asset"], signed, Path(source).resolve(), environment, plan["identity"]["version"])
|
||||
n.fields(result, {"verified_signer", "support"}, "platform signing result")
|
||||
support = r.support_binding(result["support"])
|
||||
n.require(sorted(path.name for path in signed.iterdir()) == sorted({names["asset"], *support}), "platform signer output inventory differs")
|
||||
for name, item in support.items():
|
||||
n.require(n.digest_file(signed, name) == (item["size"], item["sha256"]), "signing support differs from plug-in binding")
|
||||
n.require(require_unsigned_binding(policy, state, platform, directory) == unsigned_sha256, "unsigned bytes changed during signing")
|
||||
for name in sorted({names["asset"], *support}):
|
||||
stream, _ = n.regular_file(signed, name)
|
||||
with stream, (output/name).open("xb") as destination:
|
||||
shutil.copyfileobj(stream, destination, 1024*1024)
|
||||
receipt = r.release_receipt_v3(policy, state["request"], platform, unsigned_sha256,
|
||||
n.digest_file(output, names["asset"])[1], result["verified_signer"], support)
|
||||
for name in support:
|
||||
n.require(n.digest_file(output, name)[1] == support[name]["sha256"], "signing support changed while copying")
|
||||
for name in BUNDLE_FILES:
|
||||
write_json(output/name, state[name[:-5]])
|
||||
write_json(output/"signing.json", receipt)
|
||||
return bundle_hash(output, plan["asset"], signed=True)
|
||||
return bundle_hash(output, {names["asset"], *support}, signed=True)
|
||||
|
||||
|
||||
def verify_final(policy, state, directory, environment):
|
||||
def expected_platform_receipt(policy, state, platform, directory):
|
||||
plan, receipt = state["plan"], state["signing"]
|
||||
n.require(receipt == r.release_receipt(policy, state["request"], state["unsigned"]["unsigned_sha256"],
|
||||
n.digest_file(directory, plan["asset"])[1], policy["windows_publisher_subject"]), "final two-role receipt differs")
|
||||
with tempfile.TemporaryDirectory(prefix="nightly-final-verify-", dir=environment["RUNNER_TEMP"]) as temporary:
|
||||
root = signing.windows_unpack(Path(directory)/plan["asset"], Path(temporary)/"payload")
|
||||
subject = signing.windows_verify(root, {**environment, "NIGHTLY_WINDOWS_PUBLISHER_SUBJECT": policy["windows_publisher_subject"]}, plan["identity"]["version"])
|
||||
n.require(subject == policy["windows_publisher_subject"], "final native signer differs")
|
||||
unsigned_sha256 = require_unsigned_binding(policy, state, platform, None)
|
||||
support = r.support_binding(receipt.get("support"))
|
||||
expected = r.release_receipt_v3(policy, state["request"], platform, unsigned_sha256,
|
||||
n.digest_file(directory, plan["platforms"][platform]["asset"])[1], r.trusted_signer(policy, platform), support)
|
||||
n.require(receipt == expected, "final two-role receipt differs")
|
||||
n.require(set(support) == plat.required_support(platform, plan["platforms"][platform]["asset"]),
|
||||
"platform support set differs from its required detached signature files")
|
||||
for name, item in support.items():
|
||||
n.require(n.digest_file(directory, name) == (item["size"], item["sha256"]), "signing support differs from receipt")
|
||||
return receipt
|
||||
|
||||
|
||||
def verify_platform(policy, state, platform, directory, source, environment):
|
||||
"""Fresh keyless verification of one platform's final bytes.
|
||||
|
||||
The signed bundle also carries its authenticated admission JSON. Plug-ins verify
|
||||
an exact package-only copy (final asset plus recorded support), rechecked against
|
||||
the receipt after copying, so strict plug-in inventories stay strict.
|
||||
"""
|
||||
receipt = expected_platform_receipt(policy, state, platform, directory)
|
||||
module = plat.plugin(platform)
|
||||
asset = state["plan"]["platforms"][platform]["asset"]
|
||||
expected = {asset: receipt["final_sha256"], **{name: item["sha256"] for name, item in receipt["support"].items()}}
|
||||
with tempfile.TemporaryDirectory(prefix="nightly-verify-package-", dir=n.owned_path(environment["RUNNER_TEMP"])) as temporary:
|
||||
package = Path(temporary)/"package"; package.mkdir()
|
||||
for name, digest in sorted(expected.items()):
|
||||
n.require(n.NAME.fullmatch(name), "unsafe package file name")
|
||||
stream, _ = n.regular_file(directory, name)
|
||||
with stream, (package/name).open("xb") as destination:
|
||||
shutil.copyfileobj(stream, destination, 1024*1024)
|
||||
n.require(n.digest_file(package, name)[1] == digest, "package copy differs from signer receipt")
|
||||
signer = module.verify(policy["platforms"][platform]["trust"], package, asset,
|
||||
receipt["support"], Path(source).resolve(), plat.keyless(environment), state["plan"]["identity"]["version"])
|
||||
n.require(signer == receipt["verified_signer"], "fresh native verification differs from signer receipt")
|
||||
return receipt["final_sha256"]
|
||||
|
||||
|
||||
SHARED_STATE = ("request", "quality", "plan", "unsigned", "unsigned-claims")
|
||||
|
||||
|
||||
def signed_states(policy, directory, environment):
|
||||
"""Every admitted platform's independently hashed signed bundle, sharing one admission."""
|
||||
platforms = r.policy_platforms(policy)
|
||||
directories = platform_directories(directory, platforms)
|
||||
states = {}
|
||||
for platform, path in directories.items():
|
||||
expected = environment.get("SIGNED_BUNDLE_SHA256_"+plat.secret_key(platform), "")
|
||||
states[platform] = verify_signed_bundle(path, expected, platform)
|
||||
first = states[platforms[0]]
|
||||
n.require(all({key: state[key] for key in SHARED_STATE} == {key: first[key] for key in SHARED_STATE}
|
||||
for state in states.values()), "platform signers used different admissions")
|
||||
shared = {key: first[key] for key in SHARED_STATE}
|
||||
shared["signing"] = {platform: state["signing"] for platform, state in states.items()}
|
||||
return shared, directories
|
||||
|
||||
|
||||
def verify_final(policy, state, directories, source, environment):
|
||||
"""Windows natively here; other platforms only by their fresh verifier's exact digest."""
|
||||
for platform, directory in directories.items():
|
||||
platform_state = {**state, "signing": state["signing"][platform]}
|
||||
receipt = expected_platform_receipt(policy, platform_state, platform, directory)
|
||||
if platform == "windows-x86_64":
|
||||
n.require(verify_platform(policy, platform_state, platform, directory, source, environment) == receipt["final_sha256"], "Windows final verification differs")
|
||||
else:
|
||||
verified = environment.get("VERIFIED_FINAL_SHA256_"+plat.secret_key(platform), "")
|
||||
n.require(r.SHA256.fullmatch(verified or "") and verified == receipt["final_sha256"],
|
||||
"fresh platform verifier did not verify these exact final bytes")
|
||||
return True
|
||||
|
||||
|
||||
def publish(policy, state, directory, packet, ownership, api, guard, registry):
|
||||
def combine(state, directories, output):
|
||||
"""Flat final package directory: every platform's final asset and support files."""
|
||||
output = owned_output(output); output.mkdir(parents=True, exist_ok=False)
|
||||
for platform, directory in sorted(directories.items()):
|
||||
receipt = state["signing"][platform]
|
||||
for name in sorted({state["plan"]["platforms"][platform]["asset"], *receipt["support"]}):
|
||||
n.require(not (output/name).exists(), "duplicate combined file")
|
||||
stream, _ = n.regular_file(directory, name)
|
||||
with stream, (output/name).open("xb") as destination:
|
||||
shutil.copyfileobj(stream, destination, 1024*1024)
|
||||
expected = receipt["final_sha256"] if name == state["plan"]["platforms"][platform]["asset"] else receipt["support"][name]["sha256"]
|
||||
n.require(n.digest_file(output, name)[1] == expected, "combined file changed")
|
||||
return output
|
||||
|
||||
|
||||
def publish(policy, state, combined, packet, ownership, api, guard, registry):
|
||||
"""Only new immutable nightlies; public-but-unreconciled state is never retried."""
|
||||
packet = owned_output(packet)
|
||||
ownership = owned_output(ownership)
|
||||
plan = state["plan"]; prepared = plan["identity"]
|
||||
ident = {key: value for key, value in prepared.items() if key not in {"version", "ready"}}
|
||||
feed = n.build_feed_v2(registry, ident, prepared["version"], directory)
|
||||
n.stage_feed(feed, directory, packet)
|
||||
feed = n.build_feed_v2(registry, ident, prepared["version"], combined)
|
||||
n.stage_feed_v2(registry, ident, prepared["version"], feed, combined, packet)
|
||||
# History later requires every recorded support file to be public; never publish less.
|
||||
staged = {path.name for path in Path(packet).iterdir()}
|
||||
n.require(all({plan["platforms"][platform]["asset"], *receipt["support"]} <= staged
|
||||
for platform, receipt in state["signing"].items()), "signed support file would not be published")
|
||||
metadata = {path.name: n.digest_file(packet, path.name) for path in Path(packet).iterdir()}
|
||||
publication = {"schema": "craft-nightly-release-publication/v1", "request": state["request"],
|
||||
publication = {"schema": "craft-nightly-release-publication/v2", "request": state["request"],
|
||||
"plan": plan, "quality": state["quality"], "signing": state["signing"]}
|
||||
from nightly_ownership_receipt import reserve
|
||||
confirmed = []; result = None
|
||||
try:
|
||||
with reserve(ownership, filename="ownership.pending.json") as stream:
|
||||
result = pub.publish_packet(api, ident, metadata, packet, guard=guard, policy=publication,
|
||||
policy_marker=MARKER, on_published=lambda release: confirmed.append(release))
|
||||
policy_marker=MARKER_V2, on_published=lambda release: confirmed.append(release))
|
||||
receipt = {"schema": "craft-nightly-ownership/v2", "app": "photocraft", "repository": ident["repository"],
|
||||
"tag": ident["tag"], "source_commit": ident["source_commit"], "release_id": result["id"],
|
||||
"producer": state["request"]["producer"], "signer": state["request"]["signer"],
|
||||
@@ -375,11 +610,16 @@ def outputs(values):
|
||||
stream.write(key+"="+value+"\n")
|
||||
|
||||
|
||||
def plan_outputs(plan):
|
||||
return {"asset": plan["asset"], "unsigned-asset": plan["unsigned_asset"],
|
||||
"version": plan["identity"]["version"], "source-commit": plan["identity"]["source_commit"],
|
||||
def plan_outputs(plan, platform=None):
|
||||
values = {"version": plan["identity"]["version"], "source-commit": plan["identity"]["source_commit"],
|
||||
"platforms": ",".join(sorted(plan["platforms"])),
|
||||
"build-date": __import__("datetime").datetime.fromtimestamp(plan["identity"]["published_at"],
|
||||
__import__("datetime").timezone.utc).strftime("%Y-%m-%d")}
|
||||
if platform is not None:
|
||||
n.require(platform in plan["platforms"], "platform absent from plan")
|
||||
names = plan["platforms"][platform]
|
||||
values.update({"asset": names["asset"], "unsigned-asset": names["unsigned_asset"], "built-asset": names["built_asset"]})
|
||||
return values
|
||||
|
||||
|
||||
def git_read(root, arguments):
|
||||
@@ -413,16 +653,23 @@ def source_policy(source, environment):
|
||||
def main():
|
||||
import argparse
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("mode", choices=("main-plan", "main-seal", "main-subject", "admit", "validate", "guard", "sign", "final", "publish"))
|
||||
for name in ("source", "directory", "output", "plan", "state", "asset", "expected-sha256", "producer-run-id", "producer-run-attempt", "packet", "ownership"):
|
||||
parser.add_argument("mode", choices=("main-plan", "main-seal", "main-subject", "admit", "validate", "guard", "sign",
|
||||
"verify-platform", "final", "publish"))
|
||||
for name in ("source", "directory", "output", "plan", "state", "platform", "expected-sha256", "producer-run-id",
|
||||
"producer-run-attempt", "packet", "ownership", "combined"):
|
||||
parser.add_argument("--"+name)
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
env = os.environ; registry = n.bounded_json(Path(__file__).resolve().parent.parent/"nightly-apps.json")
|
||||
if args.platform is not None:
|
||||
n.require(args.platform in plat.SUPPORTED, "unsupported release-ref platform")
|
||||
if args.mode.startswith("main-"):
|
||||
n.require(args.platform, "exact producer platform required")
|
||||
repository = n.trusted_context(registry, "photocraft", env)["repository"]
|
||||
api = pub.HTTPTransport(repository, env.get("GH_TOKEN", ""))
|
||||
plan, producer = unsigned_plan(api, registry, env)
|
||||
n.require(args.platform in plan["platforms"], "platform is not an admitted registry target")
|
||||
names = plan["platforms"][args.platform]
|
||||
if args.mode == "main-plan":
|
||||
n.require(args.output, "new plan output required")
|
||||
output = owned_output(args.output); output.mkdir(parents=True, exist_ok=False)
|
||||
@@ -430,60 +677,81 @@ def main():
|
||||
elif args.mode == "main-seal":
|
||||
n.require(args.plan and args.output and args.directory, "build handoff paths required")
|
||||
n.require(n.bounded_json(args.plan) == plan, "producer/stable identity changed during compilation")
|
||||
_, digest = n.digest_file(args.directory, plan["unsigned_asset"])
|
||||
manifest = unsigned_manifest(plan, producer, digest)
|
||||
_, digest = n.digest_file(args.directory, names["built_asset"])
|
||||
manifest = unsigned_manifest(plan, producer, args.platform, digest)
|
||||
output = owned_output(args.output); output.mkdir(parents=True, exist_ok=False)
|
||||
stream, _ = n.regular_file(args.directory, plan["unsigned_asset"])
|
||||
with stream, (output/plan["unsigned_asset"]).open("xb") as destination:
|
||||
stream, _ = n.regular_file(args.directory, names["built_asset"])
|
||||
with stream, (output/names["unsigned_asset"]).open("xb") as destination:
|
||||
shutil.copyfileobj(stream, destination, 1024*1024)
|
||||
n.require(n.digest_file(output, plan["unsigned_asset"])[1] == digest, "producer ZIP changed while copying")
|
||||
n.require(n.digest_file(output, names["unsigned_asset"])[1] == digest, "producer payload changed while copying")
|
||||
write_json(output/"unsigned.json", manifest)
|
||||
outputs({"unsigned-sha256": digest})
|
||||
else:
|
||||
n.require(args.directory, "exact compiler artifact directory required")
|
||||
finite_files(args.directory, {plan["unsigned_asset"], "unsigned.json"})
|
||||
_, digest = n.digest_file(args.directory, plan["unsigned_asset"])
|
||||
n.require(n.bounded_json(Path(args.directory)/"unsigned.json") == unsigned_manifest(plan, producer, digest), "compiler manifest differs from independent current-run identity")
|
||||
finite_files(args.directory, {names["unsigned_asset"], "unsigned.json"})
|
||||
_, digest = n.digest_file(args.directory, names["unsigned_asset"])
|
||||
n.require(n.bounded_json(Path(args.directory)/"unsigned.json") == unsigned_manifest(plan, producer, args.platform, digest), "compiler manifest differs from independent current-run identity")
|
||||
n.require(digest == env.get("EXPECTED_COMPILER_SHA256"), "payload differs from independent compiler-job digest")
|
||||
outputs({"subject-path": str(Path(args.directory, plan["unsigned_asset"]).resolve()), "unsigned-sha256": digest})
|
||||
outputs(plan_outputs(plan)); return
|
||||
outputs({"subject-path": str(Path(args.directory, names["unsigned_asset"]).resolve()), "unsigned-sha256": digest})
|
||||
outputs(plan_outputs(plan, args.platform)); return
|
||||
n.require(args.source, "actual protected release checkout required")
|
||||
policy = source_policy(args.source, env)
|
||||
n.require(policy["schema"] == r.LIVE_POLICY, "live release-ref signing requires policy v3")
|
||||
api = pub.HTTPTransport(policy["repository"], env.get("GH_TOKEN", "")); sonar = SonarTransport()
|
||||
if args.mode == "admit":
|
||||
n.require(args.output and args.producer_run_id and args.producer_run_attempt, "producer inputs and new admission directory required")
|
||||
state = initial_admission(policy, env, args.producer_run_id, args.producer_run_attempt, api, sonar, registry, now=int(time.time()))
|
||||
output = owned_output(args.output); output.mkdir(parents=True, exist_ok=False)
|
||||
for key, value in state.items(): write_json(output/(key+".json"), value)
|
||||
outputs({**plan_outputs(state["plan"]), "admitted": "true", "artifact-id": state["request"]["artifact"]["id"],
|
||||
"wrapper-sha256": state["request"]["artifact"]["wrapper_sha256"]})
|
||||
values = {**plan_outputs(state["plan"]), "admitted": "true",
|
||||
"platforms": json.dumps(sorted(state["plan"]["platforms"]), separators=(",", ":"))}
|
||||
for platform, item in state["request"]["artifacts"].items():
|
||||
values["artifact-id-"+platform] = item["id"]
|
||||
outputs(values)
|
||||
return
|
||||
if args.mode == "validate":
|
||||
n.require(args.state and args.directory and args.output, "fixed admission, downloaded payload and new bundle paths required")
|
||||
n.require(args.state and args.directory and args.output, "fixed admission, downloaded payloads and new bundle paths required")
|
||||
state = {key: n.bounded_json(Path(args.state)/(key+".json")) for key in ("request", "quality", "plan")}
|
||||
revalidate(policy, state, env, api, sonar, registry, now=int(time.time()))
|
||||
manifest, claims = verified_unsigned(policy, state, args.directory)
|
||||
directories = platform_directories(args.directory, sorted(state["plan"]["platforms"]))
|
||||
manifests, claims = {}, {}
|
||||
for platform, directory in directories.items():
|
||||
manifests[platform], claims[platform] = verified_unsigned(policy, state, platform, directory)
|
||||
revalidate(policy, state, env, api, sonar, registry, now=int(time.time()))
|
||||
digest = stage_bundle(args.output, state, args.directory, manifest, claims)
|
||||
outputs({**plan_outputs(state["plan"]), "bundle-sha256": digest, "unsigned-sha256": manifest["unsigned_sha256"]})
|
||||
digest = stage_bundle(args.output, state, directories, manifests, claims)
|
||||
outputs({**plan_outputs(state["plan"]), "bundle-sha256": digest})
|
||||
return
|
||||
n.require(args.directory and args.asset and args.expected_sha256, "independent exact trusted-job bundle binding required")
|
||||
signed = args.mode in ("final", "publish")
|
||||
state = verify_bundle(args.directory, args.expected_sha256, args.asset, signed=signed)
|
||||
revalidate(policy, state, env, api, sonar, registry, now=int(time.time()))
|
||||
if args.mode == "guard": return
|
||||
if args.mode == "sign":
|
||||
if args.mode in ("guard", "sign"):
|
||||
n.require(args.directory and args.platform and args.expected_sha256, "independent exact trusted-job bundle binding required")
|
||||
unverified = n.bounded_json(Path(args.directory)/"plan.json")
|
||||
state = verify_bundle(args.directory, args.expected_sha256, validated_names(unverified))
|
||||
n.require(args.platform in state["plan"]["platforms"], "platform absent from validated bundle")
|
||||
require_unsigned_binding(policy, state, args.platform, args.directory)
|
||||
revalidate(policy, state, env, api, sonar, registry, now=int(time.time()))
|
||||
if args.mode == "guard": return
|
||||
n.require(args.output, "new signed output required")
|
||||
digest = native_sign(policy, state, args.directory, args.source, args.output, env)
|
||||
outputs({**plan_outputs(state["plan"]), "bundle-sha256": digest,
|
||||
"final-sha256": n.digest_file(args.output, state["plan"]["asset"])[1]})
|
||||
digest = native_sign(policy, state, args.platform, args.directory, args.source, args.output, env)
|
||||
outputs({**plan_outputs(state["plan"], args.platform), "bundle-sha256": digest,
|
||||
"final-sha256": n.digest_file(args.output, state["plan"]["platforms"][args.platform]["asset"])[1]})
|
||||
return
|
||||
verify_final(policy, state, args.directory, env)
|
||||
if args.mode == "verify-platform":
|
||||
n.require(args.directory and args.platform and args.expected_sha256, "independent exact signed bundle binding required")
|
||||
state = verify_signed_bundle(args.directory, args.expected_sha256, args.platform)
|
||||
revalidate(policy, state, env, api, sonar, registry, now=int(time.time()))
|
||||
outputs({"final-sha256": verify_platform(policy, state, args.platform, args.directory, args.source, env),
|
||||
"asset": state["plan"]["platforms"][args.platform]["asset"]})
|
||||
return
|
||||
n.require(args.directory, "signed platform directories required")
|
||||
state, directories = signed_states(policy, args.directory, env)
|
||||
revalidate(policy, state, env, api, sonar, registry, now=int(time.time()))
|
||||
verify_final(policy, state, directories, args.source, env)
|
||||
if args.mode == "final":
|
||||
outputs({"subject-path": str(Path(args.directory, state["plan"]["asset"]).resolve())}); return
|
||||
n.require(args.packet and args.ownership, "new packet/ownership paths required")
|
||||
outputs({"subject-path": ",".join(str(Path(directories[platform], state["plan"]["platforms"][platform]["asset"]).resolve())
|
||||
for platform in sorted(directories))}); return
|
||||
n.require(args.packet and args.ownership and args.combined, "new combined/packet/ownership paths required")
|
||||
combined = combine(state, directories, args.combined)
|
||||
guard = lambda: revalidate(policy, state, env, api, sonar, registry, now=int(time.time()))
|
||||
result = publish(policy, state, args.directory, args.packet, args.ownership, api, guard, registry)
|
||||
result = publish(policy, state, combined, args.packet, args.ownership, api, guard, registry)
|
||||
publication_outputs(result)
|
||||
except UpToDate as error:
|
||||
if args.mode != "admit":
|
||||
@@ -494,7 +762,8 @@ def main():
|
||||
parser.exit(2, str(error)+"\n")
|
||||
except (n.InvalidNightly, pub.APIError, http.client.HTTPException, OSError, ValueError, KeyError, TypeError,
|
||||
subprocess.SubprocessError, RecursionError) as error:
|
||||
parser.exit(1, "release-ref nightly refused: "+str(error)+"; never overwrite/delete/retry an existing tag or release\n")
|
||||
message = "signing/verification process failed" if isinstance(error, subprocess.SubprocessError) else str(error)
|
||||
parser.exit(1, "release-ref nightly refused: "+message+"; never overwrite/delete/retry an existing tag or release\n")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Linux release-ref plug-in: the stable OpenPGP detached .asc route, not a new scheme.
|
||||
|
||||
The tar.gz bytes never change; signing adds `<asset>.asc` and the stable
|
||||
`release-signing-key.asc` public export. Public trust is the reviewed
|
||||
`.github/nightly-linux-signing-key.asc` in the protected release checkout plus the
|
||||
policy fingerprint, never a downloaded key. Payload bytes are inventoried as data
|
||||
and never extracted or executed here. LINUX_SIGNING_KEY reaches only `sign`.
|
||||
"""
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shutil
|
||||
import tempfile
|
||||
import nightly_feed as n
|
||||
import nightly_signing as signing
|
||||
import nightly_unix as u
|
||||
|
||||
PLATFORM = "linux-x86_64"
|
||||
METHOD = "openpgp-detached"
|
||||
TARGET = {"os": "linux", "arch": "x86_64", "format": "tar_gz"}
|
||||
TRUST_FIELDS = {"fingerprint"}
|
||||
BYTES_MAY_BE_UNCHANGED = True
|
||||
PUBLIC_KEY = ".github/nightly-linux-signing-key.asc"
|
||||
PUBLIC_EXPORT = "release-signing-key.asc"
|
||||
MAX_SIGNATURE_BYTES = 16384
|
||||
SECRETS = ("LINUX_SIGNING_KEY",)
|
||||
CONTEXT = ("PATH", "HOME", "LANG", "LC_ALL", "TMPDIR", "RUNNER_TEMP", "GITHUB_WORKSPACE")
|
||||
FINGERPRINT = re.compile(r"(?:[A-F0-9]{40}|[A-F0-9]{64})")
|
||||
|
||||
|
||||
def validate_trust(trust):
|
||||
"""Exact reviewed trust: the full uppercase primary fingerprint, nothing else."""
|
||||
n.require(isinstance(trust, dict), "Linux trust must be an object")
|
||||
n.fields(trust, TRUST_FIELDS, "Linux trust")
|
||||
n.require(isinstance(trust["fingerprint"], str) and FINGERPRINT.fullmatch(trust["fingerprint"]),
|
||||
"Linux trust requires the full uppercase primary key fingerprint")
|
||||
return trust
|
||||
|
||||
|
||||
def pending():
|
||||
return n.bounded_json(Path(__file__).resolve().parent.parent/"nightly-unix-pending.json")
|
||||
|
||||
|
||||
def assets(version):
|
||||
u.canonical_version(version)
|
||||
row = u.pending_contract(pending(), PLATFORM)
|
||||
n.require(row["target"] == TARGET, "Linux plug-in target differs from the owner contract")
|
||||
asset = row["asset_pattern"].replace("{version}", version)
|
||||
n.require(n.NAME.fullmatch(asset) and asset.endswith("-linux-x86_64-nightly.tar.gz"), "invalid Linux nightly asset")
|
||||
# nightly.sh writes the final name into DIST; main-seal copies it to the unsigned handoff name.
|
||||
return {"asset": asset, "built_asset": asset, "unsigned_asset": asset[:-len(".tar.gz")]+".unsigned.tar.gz"}
|
||||
|
||||
|
||||
def support_names(asset):
|
||||
# Only the detached signature is published support. The feed stages assets and their
|
||||
# .asc; trust comes from reviewed source, so no in-release key export is shipped
|
||||
# (a recorded support file that is never published would also fail history checks).
|
||||
return {asset+".asc"}
|
||||
|
||||
|
||||
def keyless(environment):
|
||||
n.require(not any(environment.get(name) for name in SECRETS), "Linux verification must run without signing credentials")
|
||||
return {key: value for key, value in environment.items() if key not in SECRETS}
|
||||
|
||||
|
||||
def support_binding(directory, asset):
|
||||
result = {}
|
||||
for name in sorted(support_names(asset)):
|
||||
size, digest = n.digest_file(directory, name)
|
||||
n.require(0 < size <= MAX_SIGNATURE_BYTES, "Linux signature support exceeds bound")
|
||||
result[name] = {"size": size, "sha256": digest}
|
||||
return result
|
||||
|
||||
|
||||
def published_key_matches(directory, fingerprint, source, environment):
|
||||
"""The published stable-name export must be exactly the reviewed key, not merely parse."""
|
||||
with tempfile.TemporaryDirectory(prefix="nightly-gpg-export-", dir=n.owned_path(environment["RUNNER_TEMP"])) as temporary:
|
||||
published, reviewed = Path(temporary)/"published", Path(temporary)/"reviewed"
|
||||
published.mkdir(mode=0o700); reviewed.mkdir(mode=0o700)
|
||||
try:
|
||||
actual = signing.linux_public_keyring(Path(directory)/PUBLIC_EXPORT, fingerprint, published).read_bytes()
|
||||
expected = signing.linux_public_keyring(Path(source)/PUBLIC_KEY, fingerprint, reviewed).read_bytes()
|
||||
finally:
|
||||
signing.stop_gpg_agent(published); signing.stop_gpg_agent(reviewed)
|
||||
n.require(actual == expected, "published release-signing-key.asc differs from the reviewed public key")
|
||||
|
||||
|
||||
def verify(trust, directory, asset, support, source, environment, version):
|
||||
"""Keyless: exact inventory and bytes, data-only tar inventory, gpgv against reviewed source key."""
|
||||
fingerprint = validate_trust(trust)["fingerprint"]
|
||||
environment = keyless(environment)
|
||||
names = assets(version)
|
||||
directory = n.owned_path(directory)
|
||||
n.require(asset == names["asset"], "Linux asset differs from immutable identity")
|
||||
n.require(directory.is_dir() and not directory.is_symlink(), "signed Linux directory required")
|
||||
expected = {asset} | support_names(asset)
|
||||
actual = set()
|
||||
for path in directory.iterdir():
|
||||
n.require(len(actual) < len(expected) and path.name in expected, "unexpected signed Linux inventory")
|
||||
actual.add(path.name)
|
||||
n.require(actual == expected, "missing signed Linux package or detached-signature support")
|
||||
n.require(isinstance(support, dict) and set(support) == support_names(asset), "Linux signature support inventory mismatch")
|
||||
for name, item in support.items():
|
||||
n.fields(item, {"size", "sha256"}, "Linux signature support binding")
|
||||
n.require(support_binding(directory, asset) == support, "Linux signature support differs from signer binding")
|
||||
signing.adapter(PLATFORM, source)
|
||||
u.verify_archive(pending(), PLATFORM, directory/asset, version)
|
||||
signer = signing.verify_linux_signature(Path(source)/PUBLIC_KEY, directory/(asset+".asc"), directory/asset,
|
||||
fingerprint, environment)
|
||||
n.require(signer == fingerprint, "verified Linux signer differs from reviewed trust")
|
||||
return signer
|
||||
|
||||
|
||||
def sign(trust, unsigned, output, source, environment, version):
|
||||
"""Sign data only. The secret reaches gpg in a private temporary keyring and nothing else."""
|
||||
fingerprint = validate_trust(trust)["fingerprint"]
|
||||
names = assets(version)
|
||||
unsigned, output = n.owned_path(unsigned), n.owned_path(output)
|
||||
n.require(unsigned.name == names["unsigned_asset"], "unsigned Linux handoff differs from immutable identity")
|
||||
n.require(output.is_dir() and not output.is_symlink() and not any(output.iterdir()), "signed output must be an existing empty directory")
|
||||
n.require(isinstance(environment.get("LINUX_SIGNING_KEY"), str) and environment["LINUX_SIGNING_KEY"],
|
||||
"LINUX_SIGNING_KEY required; no unsigned fallback")
|
||||
# gpg sees only what it needs: no GitHub token or other platforms' credentials.
|
||||
env = {key: environment[key] for key in CONTEXT if isinstance(environment.get(key), str)}
|
||||
env.update(LINUX_SIGNING_KEY=environment["LINUX_SIGNING_KEY"], NIGHTLY_LINUX_SIGNING_FINGERPRINT=fingerprint)
|
||||
signing.require_config(PLATFORM, env)
|
||||
signing.adapter(PLATFORM, source)
|
||||
_, before = n.digest_file(unsigned.parent, unsigned.name)
|
||||
with tempfile.TemporaryDirectory(prefix="nightly-linux-stage-", dir=n.owned_path(environment["RUNNER_TEMP"])) as temporary:
|
||||
staged = Path(temporary)/names["asset"]
|
||||
stream, _ = n.regular_file(unsigned.parent, unsigned.name)
|
||||
with stream, staged.open("xb") as destination:
|
||||
shutil.copyfileobj(stream, destination, 1024*1024)
|
||||
n.require(n.digest_file(staged.parent, staged.name)[1] == before, "unsigned Linux bytes changed while staging")
|
||||
# Inventory before any key is imported: links, CLI, install hooks or a non-x86_64 GUI refuse.
|
||||
u.verify_archive(pending(), PLATFORM, staged, version)
|
||||
signed = Path(temporary)/"signed"; signed.mkdir()
|
||||
signer = signing.sign_linux(source, staged, signed/names["asset"], env)
|
||||
n.require(signer == fingerprint, "Linux signer differs from reviewed trust")
|
||||
# sign_linux also writes the stable-name public export; it is trust-free and not shipped here.
|
||||
published_key_matches(signed, fingerprint, source, keyless_copy(environment))
|
||||
for name in sorted({names["asset"]} | support_names(names["asset"])):
|
||||
stream, _ = n.regular_file(signed, name)
|
||||
with stream, (output/name).open("xb") as destination:
|
||||
shutil.copyfileobj(stream, destination, 1024*1024)
|
||||
n.require(n.digest_file(unsigned.parent, unsigned.name)[1] == before and
|
||||
n.digest_file(output, names["asset"])[1] == before, "Linux detached signing must not change tar.gz bytes")
|
||||
support = support_binding(output, names["asset"])
|
||||
verified = verify(trust, output, names["asset"], support, source, keyless_copy(environment), version)
|
||||
return {"verified_signer": verified, "support": support}
|
||||
|
||||
|
||||
def keyless_copy(environment):
|
||||
return {key: value for key, value in environment.items() if key not in SECRETS}
|
||||
@@ -0,0 +1,219 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Per-platform release-ref signing plug-ins (policy v3).
|
||||
|
||||
Each plug-in signs ONE validated unsigned payload inside the protected signer job
|
||||
and re-verifies the final bytes without credentials. Plug-ins never execute
|
||||
payload code. Windows and macOS live here; Linux is the separately owned
|
||||
``nightly_release_linux`` module with the same interface:
|
||||
|
||||
PLATFORM, METHOD, TARGET, TRUST_FIELDS, BYTES_MAY_BE_UNCHANGED,
|
||||
validate_trust(trust) -> trust
|
||||
assets(version) -> {"asset", "unsigned_asset", "built_asset"}
|
||||
sign(trust, unsigned, output, source, environment, version) -> {"verified_signer", "support"}
|
||||
verify(trust, directory, asset, support, source, environment, version) -> verified_signer
|
||||
"""
|
||||
import importlib
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shutil
|
||||
import tempfile
|
||||
import types
|
||||
import nightly_feed as n
|
||||
import nightly_signing as signing
|
||||
|
||||
SUPPORTED = ("linux-x86_64", "macos-aarch64", "windows-x86_64")
|
||||
ISOLATION = {"associations": "none", "package_identity": "ai.storyteller.photocraft.nightly",
|
||||
"profile_contract": "nightly", "profile_version": 1}
|
||||
# Every value any plug-in may receive as a credential. Verification never sees them.
|
||||
SECRET_NAMES = frozenset(signing.WINDOWS_SECRETS + signing.AZURE_SECRETS + signing.APPLE_SECRETS +
|
||||
("LINUX_SIGNING_KEY", "GH_TOKEN", "GITHUB_TOKEN", "ACTIONS_RUNTIME_TOKEN",
|
||||
"ACTIONS_ID_TOKEN_REQUEST_TOKEN"))
|
||||
# notarytool --wait --timeout 1h plus stapler/spctl retries, as the stable route allows.
|
||||
MAC_SIGN_TIMEOUT = 5400
|
||||
PENDING = Path(__file__).resolve().parent.parent/"nightly-unix-pending.json"
|
||||
|
||||
|
||||
def keyless(environment):
|
||||
"""Verification environment: every credential stripped, even empty ones."""
|
||||
return {key: value for key, value in environment.items() if key not in SECRET_NAMES}
|
||||
|
||||
|
||||
def credentialed(environment, names):
|
||||
"""Signing environment: only this platform's own secrets plus non-secret context."""
|
||||
return {**keyless(environment), **{key: environment[key] for key in names if key in environment}}
|
||||
|
||||
|
||||
def single_trust(trust, fields_):
|
||||
n.fields(trust, set(fields_), "platform trust")
|
||||
n.require(len(trust) == 1, "platform trust must have exactly one value")
|
||||
value = next(iter(trust.values()))
|
||||
n.require(isinstance(value, str) and 0 < len(value) <= 2048 and
|
||||
not any(c in value for c in "\r\n\0"), "invalid platform trust value")
|
||||
return value
|
||||
|
||||
|
||||
def standard_assets(platform, version, extension):
|
||||
n.require(isinstance(version, str) and len(version) <= 128 and
|
||||
re.fullmatch(r"[0-9]+\.[0-9]+\.[0-9]+-nightly\.[0-9]{8}\.[1-9][0-9]*\.[1-9][0-9]*\.g[0-9a-f]{12}", version),
|
||||
"noncanonical immutable nightly version")
|
||||
asset = "photocraft-"+version+"-"+platform+"-nightly"+extension
|
||||
unsigned = asset[:-len(extension)]+".unsigned"+extension
|
||||
n.require(n.NAME.fullmatch(asset) and n.NAME.fullmatch(unsigned), "unsafe platform asset name")
|
||||
return {"asset": asset, "unsigned_asset": unsigned}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- Windows
|
||||
def _windows_trust(trust):
|
||||
single_trust(trust, {"publisher_subject"})
|
||||
return trust
|
||||
|
||||
|
||||
def _windows_assets(version):
|
||||
names = standard_assets("windows-x86_64", version, ".zip")
|
||||
# package.ps1 -Nightly -BuildOnly already writes the .unsigned.zip name.
|
||||
return {**names, "built_asset": names["unsigned_asset"]}
|
||||
|
||||
|
||||
def _windows_env(trust, environment):
|
||||
return {**environment, "NIGHTLY_WINDOWS_PUBLISHER_SUBJECT": trust["publisher_subject"]}
|
||||
|
||||
|
||||
def _windows_sign(trust, unsigned, output, source, environment, version):
|
||||
env = _windows_env(trust, credentialed(environment, signing.WINDOWS_SECRETS+signing.AZURE_SECRETS))
|
||||
signing.adapter("windows-x86_64", source)
|
||||
signing.require_config("windows-x86_64", env)
|
||||
asset = _windows_assets(version)["asset"]
|
||||
signer = signing.sign_windows(source, unsigned, Path(output)/asset, env, version)
|
||||
n.require(signer == trust["publisher_subject"], "native verified signer differs from protected publisher subject")
|
||||
n.require(WINDOWS.verify(trust, output, asset, {}, source, keyless(environment), version) == signer, "keyless re-verification differs")
|
||||
return {"verified_signer": signer, "support": {}}
|
||||
|
||||
|
||||
def _windows_verify(trust, directory, asset, support, source, environment, version):
|
||||
n.require(support == {} and asset == _windows_assets(version)["asset"], "unexpected Windows signing support")
|
||||
env = _windows_env(trust, keyless(environment))
|
||||
with tempfile.TemporaryDirectory(prefix="nightly-final-verify-", dir=n.owned_path(env["RUNNER_TEMP"])) as temporary:
|
||||
root = signing.windows_unpack(Path(directory)/asset, Path(temporary)/"payload")
|
||||
subject = signing.windows_verify(root, env, version)
|
||||
n.require(subject == trust["publisher_subject"], "final native signer differs")
|
||||
return subject
|
||||
|
||||
|
||||
WINDOWS = types.SimpleNamespace(
|
||||
PLATFORM="windows-x86_64", METHOD="authenticode",
|
||||
TARGET={"os": "windows", "arch": "x86_64", "format": "portable_zip"},
|
||||
TRUST_FIELDS=frozenset({"publisher_subject"}), BYTES_MAY_BE_UNCHANGED=False,
|
||||
validate_trust=_windows_trust, assets=_windows_assets, sign=_windows_sign, verify=_windows_verify)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- macOS
|
||||
def _mac_trust(trust):
|
||||
team = single_trust(trust, {"apple_team_id"})
|
||||
n.require(re.fullmatch(r"[A-Z0-9]{10}", team), "Apple team ID must be the exact ten-character team")
|
||||
return trust
|
||||
|
||||
|
||||
def _mac_assets(version):
|
||||
names = standard_assets("macos-aarch64", version, ".zip")
|
||||
# packaging/macos/nightly.sh writes the final name; the handoff renames it.
|
||||
return {**names, "built_asset": names["asset"]}
|
||||
|
||||
|
||||
def _mac_inventory(archive, version, temporary):
|
||||
"""Inventory-only check of the unsigned payload under its exact asset name."""
|
||||
import nightly_unix as u
|
||||
copy = Path(temporary)/_mac_assets(version)["asset"]
|
||||
shutil.copyfile(archive, copy)
|
||||
u.verify_archive(n.bounded_json(PENDING), "macos-aarch64", copy, version)
|
||||
return copy
|
||||
|
||||
|
||||
def _mac_sign(trust, unsigned, output, source, environment, version):
|
||||
"""Stable route: import-cert.sh, codesign runtime+timestamp, notarytool, stapler.
|
||||
|
||||
The app-owned nightly-sign.sh does the Apple work with only the six stable
|
||||
APPLE_*/KEYCHAIN_PASSWORD values; it never builds or runs payload code.
|
||||
"""
|
||||
team = trust["apple_team_id"]
|
||||
env = {**credentialed(environment, signing.APPLE_SECRETS), "NIGHTLY_APPLE_TEAM_ID": team}
|
||||
signing.adapter("macos-aarch64", source)
|
||||
signing.require_config("macos-aarch64", env)
|
||||
asset = _mac_assets(version)["asset"]
|
||||
final = n.owned_path(Path(output)/asset)
|
||||
n.require(not final.exists() and not final.is_symlink(), "final Mac output must be new")
|
||||
with tempfile.TemporaryDirectory(prefix="nightly-mac-sign-", dir=n.owned_path(env["RUNNER_TEMP"])) as temporary:
|
||||
staged = _mac_inventory(unsigned, version, temporary)
|
||||
signing.command(["/bin/bash", Path(source).resolve()/"packaging/macos/nightly-sign.sh",
|
||||
"--arch", "aarch64", "--input", staged.resolve(), "--output", final.resolve()], env=env,
|
||||
timeout=MAC_SIGN_TIMEOUT)
|
||||
n.require(sorted(path.name for path in Path(output).iterdir()) == [asset], "Mac signer wrote unexpected files")
|
||||
signer = MACOS.verify(trust, output, asset, {}, source, keyless(environment), version)
|
||||
return {"verified_signer": signer, "support": {}}
|
||||
|
||||
|
||||
def _mac_verify(trust, directory, asset, support, source, environment, version):
|
||||
n.require(support == {} and asset == _mac_assets(version)["asset"], "unexpected Mac signing support")
|
||||
env = {**keyless(environment), "NIGHTLY_APPLE_TEAM_ID": trust["apple_team_id"]}
|
||||
with tempfile.TemporaryDirectory(prefix="nightly-mac-verify-", dir=n.owned_path(env["RUNNER_TEMP"])) as temporary:
|
||||
team = signing.mac_verify(Path(directory)/asset, version, n.bounded_json(PENDING), env, Path(temporary)/"payload")
|
||||
n.require(team == trust["apple_team_id"], "final Mac signer team differs")
|
||||
return team
|
||||
|
||||
|
||||
MACOS = types.SimpleNamespace(
|
||||
PLATFORM="macos-aarch64", METHOD="developer-id-notarized",
|
||||
TARGET={"os": "macos", "arch": "aarch64", "format": "portable_zip"},
|
||||
TRUST_FIELDS=frozenset({"apple_team_id"}), BYTES_MAY_BE_UNCHANGED=False,
|
||||
validate_trust=_mac_trust, assets=_mac_assets, sign=_mac_sign, verify=_mac_verify)
|
||||
|
||||
|
||||
def plugin(platform):
|
||||
n.require(platform in SUPPORTED, "unsupported release-ref platform")
|
||||
if platform == "windows-x86_64":
|
||||
return WINDOWS
|
||||
if platform == "macos-aarch64":
|
||||
return MACOS
|
||||
try:
|
||||
module = importlib.import_module("nightly_release_linux")
|
||||
except ImportError as error:
|
||||
raise n.Unavailable("reviewed Linux release plug-in missing") from error
|
||||
n.require(getattr(module, "PLATFORM", None) == platform, "Linux plug-in identity differs")
|
||||
return module
|
||||
|
||||
|
||||
def required_support(platform, asset):
|
||||
"""Exact published support files a platform's final asset needs (Linux: its detached .asc)."""
|
||||
names = getattr(plugin(platform), "support_names", None)
|
||||
return set(names(asset)) if names is not None else set()
|
||||
|
||||
|
||||
def expected_signer(platform, trust):
|
||||
"""The protected trust value IS the identity native verification must report."""
|
||||
module = plugin(platform)
|
||||
module.validate_trust(trust)
|
||||
n.require(set(trust) == set(module.TRUST_FIELDS), "platform trust fields differ")
|
||||
return single_trust(trust, module.TRUST_FIELDS)
|
||||
|
||||
|
||||
def registry_platforms(registry):
|
||||
"""Admitted photocraft targets as platform keys; every one must have a plug-in."""
|
||||
result = []
|
||||
for item in n.app_record(registry, "photocraft")["targets"]:
|
||||
n.fields(item, {"target", "asset_pattern", "isolation"}, "target registry")
|
||||
target = item["target"]
|
||||
n.require(isinstance(target, dict) and set(target) == {"os", "arch", "format"}, "invalid target registry")
|
||||
platform = str(target["os"])+"-"+str(target["arch"])
|
||||
module = plugin(platform)
|
||||
names = module.assets("0.0.0-nightly.20260101.1.1.g000000000000")
|
||||
expected_pattern = names["asset"].replace("0.0.0-nightly.20260101.1.1.g000000000000", "{version}")
|
||||
n.require(target == module.TARGET and item["asset_pattern"] == expected_pattern and
|
||||
item["isolation"] == ISOLATION, "registry row differs from reviewed platform plug-in")
|
||||
n.require(platform not in result, "duplicate admitted platform")
|
||||
result.append(platform)
|
||||
n.require(result, "no admitted release-ref platform")
|
||||
return sorted(result)
|
||||
|
||||
|
||||
def secret_key(platform):
|
||||
n.require(platform in SUPPORTED, "unsupported release-ref platform")
|
||||
return platform.upper().replace("-", "_")
|
||||
@@ -23,11 +23,18 @@ POLICY_V1_FIELDS = {'schema', 'repository', 'repository_id', 'producer_workflow_
|
||||
'manual_actors', 'platform', 'max_age_seconds', 'candidate_policy',
|
||||
'unsigned_artifact_name', 'max_artifact_bytes', 'windows_publisher_subject'}
|
||||
POLICY_FIELDS = POLICY_V1_FIELDS | {'automatic_signer_actors'}
|
||||
# v3: one release for every admitted platform; per-platform artifact kind and trust.
|
||||
POLICY_V3_FIELDS = (POLICY_FIELDS - {'platform', 'unsigned_artifact_name', 'windows_publisher_subject'}) | {'platforms'}
|
||||
PLATFORM_POLICY_FIELDS = {'unsigned_artifact_name', 'trust'}
|
||||
LIVE_POLICY = 'craft-nightly-release-policy/v3'
|
||||
ROLE_FIELDS = {'repository', 'source_commit', 'run_id', 'run_attempt', 'run_number',
|
||||
'workflow_id', 'workflow_path', 'created_at', 'tooling_revision', 'event',
|
||||
'triggering_actor', 'run_started_at'}
|
||||
ARTIFACT_FIELDS = {'id', 'name', 'size_in_bytes', 'wrapper_sha256', 'created_at', 'expires_at'}
|
||||
REQUEST_FIELDS = {'schema', 'repository', 'policy_sha256', 'producer', 'signer', 'artifact'}
|
||||
REQUEST_V2_FIELDS = (REQUEST_FIELDS - {'artifact'}) | {'artifacts'}
|
||||
RECEIPT_V3_FIELDS = {'schema', 'platform', 'method', 'repository', 'policy_sha256', 'request_sha256',
|
||||
'producer', 'signer', 'artifact', 'unsigned_sha256', 'final_sha256', 'verified_signer', 'support'}
|
||||
|
||||
|
||||
def digest(value):
|
||||
@@ -61,11 +68,14 @@ def identifier(value):
|
||||
|
||||
def validate_policy(policy):
|
||||
n.require(isinstance(policy, dict) and policy.get('schema') in
|
||||
('craft-nightly-release-policy/v1', 'craft-nightly-release-policy/v2'), 'unknown release policy schema')
|
||||
n.fields(policy, POLICY_V1_FIELDS if policy['schema'] == 'craft-nightly-release-policy/v1' else POLICY_FIELDS,
|
||||
'release policy')
|
||||
n.require(policy['release_branch'] == 'release' and policy['platform'] == 'windows-x86_64',
|
||||
'unreviewed release policy')
|
||||
('craft-nightly-release-policy/v1', 'craft-nightly-release-policy/v2', LIVE_POLICY), 'unknown release policy schema')
|
||||
n.fields(policy, {'craft-nightly-release-policy/v1': POLICY_V1_FIELDS, 'craft-nightly-release-policy/v2': POLICY_FIELDS,
|
||||
LIVE_POLICY: POLICY_V3_FIELDS}[policy['schema']], 'release policy')
|
||||
n.require(policy['release_branch'] == 'release', 'unreviewed release policy')
|
||||
if policy['schema'] == LIVE_POLICY:
|
||||
validate_platforms(policy['platforms'])
|
||||
else:
|
||||
n.require(policy['platform'] == 'windows-x86_64', 'unreviewed release policy')
|
||||
n.require(isinstance(policy['repository'], str) and
|
||||
re.fullmatch(r'storytold/[A-Za-z0-9][A-Za-z0-9._-]{0,127}', policy['repository']),
|
||||
'unreviewed repository')
|
||||
@@ -77,22 +87,51 @@ def validate_policy(policy):
|
||||
n.require(isinstance(ref, str) and re.fullmatch(
|
||||
r'[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+/\.github/workflows/[A-Za-z0-9_-]+\.ya?ml@[0-9a-f]{40}', ref)
|
||||
and ref.rsplit('@', 1)[1] == policy['producer_tooling_revision'], 'unpinned reusable producer')
|
||||
subject = policy['windows_publisher_subject']
|
||||
n.require(isinstance(subject, str) and 0 < len(subject) <= 2048 and
|
||||
not any(c in subject for c in '\r\n\0'), 'invalid protected Windows publisher subject')
|
||||
if policy['schema'] != LIVE_POLICY:
|
||||
subject = policy['windows_publisher_subject']
|
||||
n.require(isinstance(subject, str) and 0 < len(subject) <= 2048 and
|
||||
not any(c in subject for c in '\r\n\0'), 'invalid protected Windows publisher subject')
|
||||
n.require(isinstance(policy['unsigned_artifact_name'], str) and
|
||||
n.NAME.fullmatch(policy['unsigned_artifact_name']), 'invalid unsigned artifact kind')
|
||||
actor_sets(policy)
|
||||
n.require(type(policy['max_age_seconds']) is int and 0 < policy['max_age_seconds'] <= 604800,
|
||||
'invalid producer age bound')
|
||||
n.require(type(policy['max_artifact_bytes']) is int and
|
||||
0 < policy['max_artifact_bytes'] <= n.MAX_TOTAL_BYTES, 'invalid artifact size bound')
|
||||
n.require(isinstance(policy['unsigned_artifact_name'], str) and
|
||||
n.NAME.fullmatch(policy['unsigned_artifact_name']), 'invalid unsigned artifact kind')
|
||||
n.require(isinstance(policy['candidate_policy'], dict) and
|
||||
policy['candidate_policy'].get('schema') == 'craft-nightly-candidate-policy/v3',
|
||||
'explicit candidate v3 policy required; no fallback')
|
||||
return policy
|
||||
|
||||
|
||||
def validate_platforms(platforms):
|
||||
"""Exact per-platform artifact kind and one protected trust value each."""
|
||||
import nightly_release_platforms as plat
|
||||
n.require(isinstance(platforms, dict) and 0 < len(platforms) <= len(plat.SUPPORTED), 'invalid platform map')
|
||||
for platform, entry in platforms.items():
|
||||
n.require(platform in plat.SUPPORTED, 'unreviewed release-ref platform')
|
||||
n.fields(entry, PLATFORM_POLICY_FIELDS, 'platform policy')
|
||||
n.require(entry['unsigned_artifact_name'] == 'nightly-unsigned-'+platform, 'unsigned artifact kind must be nightly-unsigned-<platform>')
|
||||
plat.expected_signer(platform, entry['trust'])
|
||||
return sorted(platforms)
|
||||
|
||||
|
||||
def policy_platforms(policy):
|
||||
"""Platforms one signer run must sign; v1/v2 history is Windows-only."""
|
||||
if policy['schema'] == LIVE_POLICY:
|
||||
return sorted(policy['platforms'])
|
||||
return ['windows-x86_64']
|
||||
|
||||
|
||||
def trusted_signer(policy, platform):
|
||||
if policy['schema'] == LIVE_POLICY:
|
||||
import nightly_release_platforms as plat
|
||||
n.require(platform in policy['platforms'], 'platform absent from protected policy')
|
||||
return plat.expected_signer(platform, policy['platforms'][platform]['trust'])
|
||||
n.require(platform == 'windows-x86_64', 'history policy is Windows-only')
|
||||
return policy['windows_publisher_subject']
|
||||
|
||||
|
||||
def repository(policy, value):
|
||||
n.require(isinstance(value, dict) and value.get('full_name') == policy['repository'] and
|
||||
type(value.get('id')) is int and value['id'] == policy['repository_id'], 'repository identity differs')
|
||||
@@ -103,7 +142,7 @@ def actor_sets(policy):
|
||||
manual = invocation.manual_actors(json.dumps(policy['manual_actors']))
|
||||
if policy['schema'] == 'craft-nightly-release-policy/v1':
|
||||
return manual, set()
|
||||
n.require(policy['schema'] == 'craft-nightly-release-policy/v2', 'unknown actor policy schema')
|
||||
n.require(policy['schema'] in ('craft-nightly-release-policy/v2', LIVE_POLICY), 'unknown actor policy schema')
|
||||
automatic = invocation.manual_actors(json.dumps(policy['automatic_signer_actors']))
|
||||
n.require(not manual & automatic, 'manual and automatic signer actor lists overlap')
|
||||
return manual, automatic
|
||||
@@ -180,16 +219,21 @@ def active(api, role_data):
|
||||
row.get('state') == 'active', 'workflow paused/deleted/identity changed')
|
||||
|
||||
|
||||
def artifact_name(policy, producer):
|
||||
def artifact_name(policy, producer, platform='windows-x86_64'):
|
||||
"""Fixed reviewed kind plus authenticated run/attempt, never a caller pattern."""
|
||||
prefix = policy['unsigned_artifact_name']
|
||||
if policy['schema'] == LIVE_POLICY:
|
||||
n.require(platform in policy['platforms'], 'platform absent from protected policy')
|
||||
prefix = policy['platforms'][platform]['unsigned_artifact_name']
|
||||
else:
|
||||
n.require(platform == 'windows-x86_64', 'history policy is Windows-only')
|
||||
prefix = policy['unsigned_artifact_name']
|
||||
n.require(isinstance(prefix, str) and n.NAME.fullmatch(prefix), 'invalid unsigned artifact kind')
|
||||
for key in ('run_id', 'run_attempt'): n.positive(producer[key], key)
|
||||
return prefix+'-'+str(producer['run_id'])+'-'+str(producer['run_attempt'])
|
||||
|
||||
|
||||
def artifact(policy, row, producer, now):
|
||||
n.require(isinstance(row, dict) and row.get('name') == artifact_name(policy, producer) and
|
||||
def artifact(policy, row, producer, now, platform='windows-x86_64'):
|
||||
n.require(isinstance(row, dict) and row.get('name') == artifact_name(policy, producer, platform) and
|
||||
row.get('expired') is False, 'unsigned artifact missing/expired/wrong kind')
|
||||
n.positive(row.get('id'), 'artifact ID'); n.positive(row.get('size_in_bytes'), 'artifact bytes')
|
||||
n.require(row['size_in_bytes'] <= policy['max_artifact_bytes'], 'artifact exceeds bound')
|
||||
@@ -217,7 +261,8 @@ def validate_request(policy, environment, producer_run_id, producer_run_attempt,
|
||||
early snapshot before it downloads anything, then checks both boundaries.
|
||||
"""
|
||||
validate_policy(policy)
|
||||
n.require(policy['schema'] == 'craft-nightly-release-policy/v2', 'live admission requires role-scoped release policy v2')
|
||||
n.require(policy['schema'] == LIVE_POLICY, 'live admission requires per-platform release policy v3; v1/v2 are history only')
|
||||
platforms = policy_platforms(policy)
|
||||
n.positive(now, 'current UTC epoch')
|
||||
producer_id, producer_attempt = identifier(producer_run_id), identifier(producer_run_attempt)
|
||||
n.require(environment.get('GITHUB_REPOSITORY') == policy['repository'] and
|
||||
@@ -244,7 +289,8 @@ def validate_request(policy, environment, producer_run_id, producer_run_attempt,
|
||||
before_artifacts(copy.deepcopy(producer)) # Failure prevents all artifact reads.
|
||||
# Run artifact API has no attempt selector. Creation bounds are supplementary;
|
||||
# the signed invocationId below supplies the indispensable attempt proof.
|
||||
selected = []; seen = set(); total = None
|
||||
selected = {platform: [] for platform in platforms}; seen = set(); total = None
|
||||
names = {artifact_name(policy, producer, platform): platform for platform in platforms}
|
||||
for page in range(1, p.MAX_PAGES+1):
|
||||
reply = api.request('GET', f'/actions/runs/{producer_id}/artifacts?per_page={p.PAGE_SIZE}&page={page}')
|
||||
rows = reply.get('artifacts') if isinstance(reply, dict) else None
|
||||
@@ -257,26 +303,32 @@ def validate_request(policy, environment, producer_run_id, producer_run_attempt,
|
||||
n.require(isinstance(row, dict), 'invalid artifact row')
|
||||
n.positive(row.get('id'), 'artifact ID')
|
||||
n.require(row['id'] not in seen, 'duplicate artifact ID'); seen.add(row['id'])
|
||||
if row.get('name') == artifact_name(policy, producer): selected.append(artifact(policy, row, producer, now))
|
||||
if row.get('name') in names:
|
||||
platform = names[row['name']]
|
||||
selected[platform].append(artifact(policy, row, producer, now, platform))
|
||||
# Stop once the reported total is read, including on the last allowed full page.
|
||||
if len(rows) < p.PAGE_SIZE or len(seen) == total: break
|
||||
else: raise n.Unavailable('artifact pagination bound reached')
|
||||
n.require(len(seen) == total and len(selected) == 1, 'missing/ambiguous/incomplete unsigned artifact')
|
||||
chosen = selected[0]
|
||||
n.require(artifact(policy, api.request('GET', f"/actions/artifacts/{chosen['id']}"), producer, now) == chosen,
|
||||
'live artifact substituted')
|
||||
n.require(len(seen) == total and all(len(rows) == 1 for rows in selected.values()),
|
||||
'missing/ambiguous/incomplete unsigned artifact for an admitted platform')
|
||||
chosen = {platform: rows[0] for platform, rows in selected.items()}
|
||||
for platform, item in chosen.items():
|
||||
n.require(artifact(policy, api.request('GET', f"/actions/artifacts/{item['id']}"), producer, now, platform) == item,
|
||||
'live artifact substituted')
|
||||
n.require(read_role(api, policy, producer_id, producer_attempt) == producer and
|
||||
read_role(api, policy, signer_id, signer_attempt, signer=True, producer=producer) == signer, 'admission changed during reads')
|
||||
active(api, producer); active(api, signer)
|
||||
p.require_newest_run(api, {'run': {**producer, 'id': producer_id,
|
||||
'attempt': producer_attempt, 'number': producer['run_number']}})
|
||||
return {'schema': 'craft-nightly-release-request/v1', 'repository': policy['repository'],
|
||||
'policy_sha256': digest(policy), 'producer': producer, 'signer': signer, 'artifact': chosen}
|
||||
return {'schema': 'craft-nightly-release-request/v2', 'repository': policy['repository'],
|
||||
'policy_sha256': digest(policy), 'producer': producer, 'signer': signer, 'artifacts': chosen}
|
||||
|
||||
|
||||
def request_contract(policy, request):
|
||||
validate_policy(policy); n.fields(request, REQUEST_FIELDS, 'release request')
|
||||
n.require(request['schema'] == 'craft-nightly-release-request/v1' and
|
||||
validate_policy(policy)
|
||||
live = policy['schema'] == LIVE_POLICY
|
||||
n.fields(request, REQUEST_V2_FIELDS if live else REQUEST_FIELDS, 'release request')
|
||||
n.require(request['schema'] == ('craft-nightly-release-request/v2' if live else 'craft-nightly-release-request/v1') and
|
||||
request['repository'] == policy['repository'] and request['policy_sha256'] == digest(policy),
|
||||
'request policy binding differs')
|
||||
for name in ('producer', 'signer'):
|
||||
@@ -297,13 +349,27 @@ def request_contract(policy, request):
|
||||
n.require(p.timestamp(row['created_at']) <= p.timestamp(row['run_started_at']), 'role timestamps differ')
|
||||
require_actor(policy, row['event'], row['run_attempt'], row['triggering_actor'],
|
||||
signer=name == 'signer', producer=producer, reason='role current actor not authorized')
|
||||
item = request['artifact']; n.fields(item, ARTIFACT_FIELDS, 'artifact binding')
|
||||
n.positive(item['id'], 'artifact ID'); n.positive(item['size_in_bytes'], 'artifact bytes')
|
||||
n.require(item['name'] == artifact_name(policy, producer) and
|
||||
item['size_in_bytes'] <= policy['max_artifact_bytes'] and
|
||||
p.timestamp(producer['run_started_at']) <= p.timestamp(item['created_at']) < p.timestamp(item['expires_at']),
|
||||
'artifact request binding differs')
|
||||
hash_value(item['wrapper_sha256'])
|
||||
items = request['artifacts'] if live else {'windows-x86_64': request['artifact']}
|
||||
n.require(isinstance(items, dict) and sorted(items) == policy_platforms(policy), 'artifact platform set differs')
|
||||
ids = set()
|
||||
for platform, item in items.items():
|
||||
n.fields(item, ARTIFACT_FIELDS, 'artifact binding')
|
||||
n.positive(item['id'], 'artifact ID'); n.positive(item['size_in_bytes'], 'artifact bytes')
|
||||
n.require(item['id'] not in ids, 'duplicate artifact binding'); ids.add(item['id'])
|
||||
n.require(item['name'] == artifact_name(policy, producer, platform) and
|
||||
item['size_in_bytes'] <= policy['max_artifact_bytes'] and
|
||||
p.timestamp(producer['run_started_at']) <= p.timestamp(item['created_at']) < p.timestamp(item['expires_at']),
|
||||
'artifact request binding differs')
|
||||
hash_value(item['wrapper_sha256'])
|
||||
|
||||
|
||||
def request_artifact(policy, request, platform):
|
||||
request_contract(policy, request)
|
||||
if policy['schema'] == LIVE_POLICY:
|
||||
n.require(platform in request['artifacts'], 'platform absent from request')
|
||||
return request['artifacts'][platform]
|
||||
n.require(platform == 'windows-x86_64', 'history request is Windows-only')
|
||||
return request['artifact']
|
||||
|
||||
|
||||
def require_gh_version(version_output):
|
||||
@@ -389,3 +455,36 @@ def release_receipt(policy, request, unsigned_sha256, final_sha256, verified_sig
|
||||
'signer': copy.deepcopy(request['signer']), 'artifact': copy.deepcopy(request['artifact']),
|
||||
'unsigned_sha256': unsigned_sha256, 'final_sha256': final_sha256,
|
||||
'verified_signer': verified_signer}
|
||||
|
||||
|
||||
def support_binding(support):
|
||||
"""Finite signature support files (Linux .asc and public export); none for Windows/macOS."""
|
||||
n.require(isinstance(support, dict) and len(support) <= 4, 'invalid signing support inventory')
|
||||
for name, item in support.items():
|
||||
n.require(isinstance(name, str) and n.NAME.fullmatch(name), 'unsafe signing support name')
|
||||
n.fields(item, {'size', 'sha256'}, 'signing support binding')
|
||||
n.require(type(item['size']) is int and 0 < item['size'] <= n.MAX_JSON_BYTES, 'invalid signing support size')
|
||||
hash_value(item['sha256'])
|
||||
return support
|
||||
|
||||
|
||||
def release_receipt_v3(policy, request, platform, unsigned_sha256, final_sha256, verified_signer, support):
|
||||
"""One platform's two-role receipt, formatted only after native/keyless verification.
|
||||
|
||||
Like v2 it authenticates nothing by itself; every consumer rebuilds it from the
|
||||
protected policy, revalidated request and independently hashed bytes.
|
||||
"""
|
||||
import nightly_release_platforms as plat
|
||||
n.require(policy['schema'] == LIVE_POLICY, 'v3 receipts require policy v3')
|
||||
item = request_artifact(policy, request, platform)
|
||||
hash_value(unsigned_sha256); hash_value(final_sha256); support_binding(support)
|
||||
module = plat.plugin(platform)
|
||||
n.require(module.BYTES_MAY_BE_UNCHANGED or unsigned_sha256 != final_sha256,
|
||||
'signing did not change the package; unsigned fallback refused')
|
||||
n.require(isinstance(verified_signer, str) and verified_signer == trusted_signer(policy, platform),
|
||||
'native verified signer differs from protected platform trust')
|
||||
return {'schema': 'craft-nightly-signing/v3', 'platform': platform, 'method': module.METHOD,
|
||||
'repository': policy['repository'], 'policy_sha256': digest(policy), 'request_sha256': digest(request),
|
||||
'producer': copy.deepcopy(request['producer']), 'signer': copy.deepcopy(request['signer']),
|
||||
'artifact': copy.deepcopy(item), 'unsigned_sha256': unsigned_sha256, 'final_sha256': final_sha256,
|
||||
'verified_signer': verified_signer, 'support': copy.deepcopy(support)}
|
||||
+123
-49
@@ -29,25 +29,39 @@ AZURE_SECRETS = ('AZURE_TENANT_ID', 'AZURE_CLIENT_ID', 'AZURE_CLIENT_SECRET',
|
||||
'AZURE_SIGNING_ENDPOINT', 'AZURE_SIGNING_ACCOUNT', 'AZURE_CERT_PROFILE')
|
||||
APPLE_SECRETS = ('APPLE_CERTIFICATE', 'APPLE_CERTIFICATE_PASSWORD', 'KEYCHAIN_PASSWORD',
|
||||
'APPLE_ID', 'APPLE_PASSWORD', 'APPLE_TEAM_ID')
|
||||
# Never handed to verification tools; signing calls alone receive their own credentials.
|
||||
SECRET_NAMES = frozenset(WINDOWS_SECRETS + AZURE_SECRETS + APPLE_SECRETS +
|
||||
('LINUX_SIGNING_KEY', 'GH_TOKEN', 'GITHUB_TOKEN', 'ACTIONS_RUNTIME_TOKEN',
|
||||
'ACTIONS_ID_TOKEN_REQUEST_TOKEN', 'ACTIONS_ID_TOKEN_REQUEST_URL'))
|
||||
FIELDS = {'schema', 'platform', 'method', 'identity_sha256', 'unsigned_sha256', 'final_sha256',
|
||||
'source_commit', 'tooling_revision', 'run_id', 'run_attempt', 'asset', 'signer', 'verified', 'support'}
|
||||
|
||||
|
||||
def command(argv, *, stdin=None, env=None):
|
||||
def command(argv, *, stdin=None, env=None, timeout=3900):
|
||||
# Only fixed trusted system tools/app source scripts, never payload executables.
|
||||
tools = {'pwsh', '/bin/bash', '/usr/bin/ditto', '/usr/bin/lipo', '/usr/bin/codesign',
|
||||
'/usr/bin/xcrun', '/usr/sbin/spctl', '/usr/bin/gpg', '/usr/bin/gpgv'}
|
||||
'/usr/bin/xcrun', '/usr/sbin/spctl', '/usr/bin/gpg', '/usr/bin/gpgv', '/usr/bin/gpgconf'}
|
||||
arguments = [str(value.absolute()) if isinstance(value, Path) else str(value) for value in argv]
|
||||
n.require(arguments and arguments[0] in tools, 'unreviewed signing executable')
|
||||
n.require(all(not any(char in value for char in '\0\r\n') for value in arguments),
|
||||
'signing arguments contain control characters')
|
||||
result = subprocess.run(arguments, input=stdin, env=env, check=True,
|
||||
stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=3900)
|
||||
stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=timeout)
|
||||
n.require(len(result.stdout) <= n.MAX_JSON_BYTES and len(result.stderr) <= n.MAX_JSON_BYTES,
|
||||
'signing tool output exceeds bound')
|
||||
return result.stdout.decode('utf-8-sig').strip()
|
||||
|
||||
|
||||
def verification_env(environment=None):
|
||||
"""Explicit subprocess env for verification: the caller's environment minus every signing secret/token.
|
||||
|
||||
Passing env= always (never None) stops tools inheriting a signer process's ambient credentials.
|
||||
"""
|
||||
source = os.environ if environment is None else environment
|
||||
return {key: value for key, value in source.items() if isinstance(value, str) and key not in SECRET_NAMES and
|
||||
not re.search(r'(TOKEN|SECRET|PASSWORD|PRIVATE_KEY|CERTIFICATE)', key.upper())}
|
||||
|
||||
|
||||
def sha(path):
|
||||
path = Path(path)
|
||||
return n.digest_file(path.parent, path.name)[1]
|
||||
@@ -154,7 +168,7 @@ def windows_verify(root, environment, version):
|
||||
n.require(publisher and not any(c in publisher for c in '\r\n\0'), 'configured exact Windows publisher subject required')
|
||||
script = Path(__file__).with_name('nightly_signing_windows.ps1').resolve()
|
||||
return command(['pwsh', '-NoProfile', '-File', script, '-Mode', 'verify', '-Root', n.owned_path(root),
|
||||
'-ExpectedPublisher', publisher, '-ExpectedVersion', version])
|
||||
'-ExpectedPublisher', publisher, '-ExpectedVersion', version], env=verification_env(environment))
|
||||
|
||||
|
||||
def repack_windows(root, archive):
|
||||
@@ -188,22 +202,32 @@ def mac_verify(archive, version, pending, environment, output):
|
||||
# inventory has already forbidden links, traversal, extra roots and special files.
|
||||
output = n.owned_path(output)
|
||||
n.require(not output.exists(), 'Mac verification directory must be new')
|
||||
command(['/usr/bin/ditto', '-x', '-k', archive, output])
|
||||
clean = verification_env(environment) # Keeps PATH/HOME/TMPDIR/LANG/DEVELOPER_DIR, never signing secrets.
|
||||
# Unpack like the Launcher: no resource forks or extended attributes restored.
|
||||
command(['/usr/bin/ditto', '-x', '-k', '--norsrc', '--noextattr', archive, output], env=clean)
|
||||
app = Path(output)/'PhotoCraft Nightly.app'
|
||||
executable = app/'Contents/MacOS/PhotoCraft'
|
||||
n.require(command(['/usr/bin/lipo', '-archs', executable]) == 'arm64', 'Mac GUI must be thin aarch64')
|
||||
command(['/usr/bin/codesign', '--verify', '--strict', '--deep', app])
|
||||
n.require(command(['/usr/bin/lipo', '-archs', executable], env=clean) == 'arm64', 'Mac GUI must be thin aarch64')
|
||||
command(['/usr/bin/codesign', '--verify', '--strict', '--deep', app], env=clean)
|
||||
# codesign -d writes details to stderr, merged explicitly in this one tool.
|
||||
details = subprocess.run(['/usr/bin/codesign', '-d', '--verbose=4', str(app)],
|
||||
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, check=True, timeout=60).stdout.decode()
|
||||
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, check=True, timeout=60, env=clean).stdout.decode()
|
||||
n.require(len(details) <= n.MAX_JSON_BYTES and
|
||||
'\nIdentifier='+u.ISOLATION['package_identity']+'\n' in '\n'+details+'\n' and
|
||||
'\nAuthority=Developer ID Application:' in '\n'+details and
|
||||
'\nTeamIdentifier='+team+'\n' in '\n'+details and
|
||||
re.search(r'^Timestamp=.+$', details, re.M) and
|
||||
hardened_runtime(details),
|
||||
'Mac requires Developer ID, exact team, secure timestamp and hardened runtime')
|
||||
command(['/usr/bin/xcrun', 'stapler', 'validate', app])
|
||||
assessment = command(['/usr/sbin/spctl', '--assess', '--type', 'execute', app])
|
||||
'Mac requires nightly identifier, Developer ID, exact team, secure timestamp and hardened runtime')
|
||||
command(['/usr/bin/xcrun', 'stapler', 'validate', app], env=clean)
|
||||
# spctl reports its verdict on stderr; require Gatekeeper's notarized source, not just exit 0.
|
||||
assessment = subprocess.run(['/usr/sbin/spctl', '--assess', '--type', 'execute', '-vv', str(app)],
|
||||
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, check=True, timeout=120, env=clean).stdout.decode()
|
||||
lines = assessment.splitlines()
|
||||
n.require(len(assessment) <= n.MAX_JSON_BYTES and lines and lines[0].endswith(': accepted') and
|
||||
'source=Notarized Developer ID' in lines and
|
||||
any(line.startswith('origin=Developer ID Application: ') and line.endswith('('+team+')') for line in lines),
|
||||
'Gatekeeper must accept the app as notarized Developer ID from the reviewed team')
|
||||
return team
|
||||
|
||||
|
||||
@@ -269,24 +293,79 @@ def verify_package(directory, receipt, source, environment, *, packet=False):
|
||||
n.require(path.stat().st_size == binding['size'] and sha(path) == binding['sha256'], 'signature support differs from signer receipt')
|
||||
if receipt['platform'] == 'linux-x86_64':
|
||||
adapter('linux-x86_64', source)
|
||||
with tempfile.TemporaryDirectory(prefix='nightly-gpg-verify-', dir=n.owned_path(environment['RUNNER_TEMP'])) as temporary:
|
||||
keyring = Path(temporary)/'trusted.gpg'
|
||||
public = n.owned_path(Path(source)/'.github/nightly-linux-signing-key.asc')
|
||||
# No automatic key retrieval, no trust in downloaded release-signing-key.asc.
|
||||
command(['/usr/bin/gpg', '--homedir', temporary, '--batch', '--import', public])
|
||||
listing = command(['/usr/bin/gpg', '--homedir', temporary, '--batch', '--with-colons', '--list-keys'])
|
||||
fingerprints = [line.split(':')[9] for line in listing.splitlines() if line.startswith('fpr:')]
|
||||
n.require(sum(line.startswith('pub:') for line in listing.splitlines()) == 1 and fingerprints and
|
||||
fingerprints[0] == receipt['signer'] == environment.get('NIGHTLY_LINUX_SIGNING_FINGERPRINT'),
|
||||
'Linux signer differs from independently reviewed public key/fingerprint')
|
||||
binary = subprocess.run(['/usr/bin/gpg', '--homedir', temporary, '--batch', '--export', fingerprints[0]],
|
||||
stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True, timeout=60).stdout
|
||||
keyring.write_bytes(binary)
|
||||
command(['/usr/bin/gpgv', '--homedir', temporary, '--keyring', keyring,
|
||||
directory/(receipt['asset']+'.asc'), directory/receipt['asset']])
|
||||
n.require(receipt['signer'] == environment.get('NIGHTLY_LINUX_SIGNING_FINGERPRINT'),
|
||||
'Linux signer differs from independently reviewed public key/fingerprint')
|
||||
# No automatic key retrieval, no trust in downloaded release-signing-key.asc.
|
||||
verify_linux_signature(Path(source)/'.github/nightly-linux-signing-key.asc', directory/(receipt['asset']+'.asc'),
|
||||
directory/receipt['asset'], receipt['signer'], environment)
|
||||
return True
|
||||
|
||||
|
||||
LINUX_HASH_ALGORITHMS = {'8', '9', '10'} # OpenPGP SHA-256, SHA-384, SHA-512 only.
|
||||
|
||||
|
||||
def stop_gpg_agent(homedir):
|
||||
"""Never leave an agent (possibly holding the signing key) behind a temporary homedir."""
|
||||
try:
|
||||
command(['/usr/bin/gpgconf', '--homedir', Path(homedir), '--kill', 'all'], env=verification_env())
|
||||
except (OSError, subprocess.SubprocessError, n.InvalidNightly):
|
||||
pass # Best effort: the homedir is removed next, which also ends a live agent.
|
||||
|
||||
|
||||
def linux_public_keyring(public_key, fingerprint, homedir, environment=None):
|
||||
"""Import exactly one reviewed public primary into a fresh homedir; return a gpgv keyring.
|
||||
|
||||
Trust comes from reviewed source and the independently reviewed fingerprint,
|
||||
never from a downloaded release-signing-key.asc. No automatic key retrieval.
|
||||
"""
|
||||
public_key, homedir = n.owned_path(public_key), Path(homedir)
|
||||
n.require(re.fullmatch(r'(?:[A-F0-9]{40}|[A-F0-9]{64})', fingerprint or ''),
|
||||
'independently reviewed full Linux primary fingerprint required')
|
||||
n.require(public_key.is_file() and not public_key.is_symlink() and
|
||||
0 < public_key.stat().st_size <= n.MAX_JSON_BYTES, 'reviewed Linux public key missing or exceeds bound')
|
||||
clean = verification_env(environment)
|
||||
command(['/usr/bin/gpg', '--homedir', homedir, '--batch', '--import', public_key], env=clean)
|
||||
listing = command(['/usr/bin/gpg', '--homedir', homedir, '--batch', '--with-colons', '--list-keys'], env=clean)
|
||||
lines = listing.splitlines()
|
||||
primaries = [lines[index+1].split(':')[9] for index, line in enumerate(lines)
|
||||
if line.startswith('pub:') and index+1 < len(lines) and lines[index+1].startswith('fpr:')]
|
||||
n.require(sum(line.startswith('pub:') for line in lines) == 1 and primaries == [fingerprint],
|
||||
'Linux signer differs from independently reviewed public key/fingerprint')
|
||||
keyring = homedir/'trusted.gpg'
|
||||
binary = subprocess.run(['/usr/bin/gpg', '--homedir', str(homedir), '--batch', '--export', fingerprint],
|
||||
stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True, timeout=60, env=clean).stdout
|
||||
n.require(0 < len(binary) <= n.MAX_JSON_BYTES, 'reviewed Linux public key export missing or exceeds bound')
|
||||
keyring.write_bytes(binary)
|
||||
return keyring
|
||||
|
||||
|
||||
def verify_linux_signature(public_key, signature, payload, fingerprint, environment):
|
||||
"""gpgv over exact bytes with only the reviewed key; one good signature bound to the primary."""
|
||||
signature = n.owned_path(signature)
|
||||
n.require(signature.is_file() and not signature.is_symlink() and 0 < signature.stat().st_size <= 16384,
|
||||
'Linux detached signature missing or exceeds 16KiB')
|
||||
raw = signature.read_bytes()
|
||||
n.require(raw.startswith(b'-----BEGIN PGP SIGNATURE-----') and raw.rstrip().endswith(b'-----END PGP SIGNATURE-----') and
|
||||
all(byte < 128 for byte in raw), 'expected ASCII-armored detached OpenPGP signature')
|
||||
with tempfile.TemporaryDirectory(prefix='nightly-gpgv-', dir=n.owned_path(environment['RUNNER_TEMP'])) as temporary:
|
||||
homedir = Path(temporary)/'public'; homedir.mkdir(mode=0o700)
|
||||
try:
|
||||
keyring = linux_public_keyring(public_key, fingerprint, homedir, environment)
|
||||
status = command(['/usr/bin/gpgv', '--homedir', homedir, '--status-fd', '1', '--keyring', keyring,
|
||||
signature, n.owned_path(payload)], env=verification_env(environment))
|
||||
finally:
|
||||
stop_gpg_agent(homedir)
|
||||
records = [line.split()[1:] for line in status.splitlines() if line.startswith('[GNUPG:] ')]
|
||||
kinds = [record[0] for record in records if record]
|
||||
n.require(not {'BADSIG', 'ERRSIG', 'EXPSIG', 'EXPKEYSIG', 'REVKEYSIG', 'NO_PUBKEY'} & set(kinds) and
|
||||
kinds.count('NEWSIG') <= 1 and kinds.count('GOODSIG') == 1 and kinds.count('VALIDSIG') == 1,
|
||||
'exactly one good, unexpired, unrevoked Linux signature required')
|
||||
valid = next(record for record in records if record and record[0] == 'VALIDSIG')
|
||||
n.require(len(valid) == 11 and valid[10] == fingerprint and valid[8] in LINUX_HASH_ALGORITHMS and valid[9] == '00',
|
||||
'Linux signature is not a binary-document signature by the reviewed primary with SHA-2')
|
||||
return fingerprint
|
||||
|
||||
|
||||
def sign_windows(source, archive, output, environment, version):
|
||||
with tempfile.TemporaryDirectory(prefix='nightly-sign-', dir=n.owned_path(environment['RUNNER_TEMP'])) as temporary:
|
||||
payload = windows_unpack(archive, Path(temporary)/'payload')
|
||||
@@ -306,32 +385,26 @@ def sign_linux(source, archive, output, environment):
|
||||
archive, output = n.owned_path(archive), n.owned_path(output)
|
||||
trusted_key = n.owned_path(Path(source)/'.github/nightly-linux-signing-key.asc')
|
||||
n.require(trusted_key.stat().st_size <= n.MAX_JSON_BYTES, 'reviewed Linux public key exceeds bound')
|
||||
fingerprint = environment.get('NIGHTLY_LINUX_SIGNING_FINGERPRINT', '')
|
||||
with tempfile.TemporaryDirectory(prefix='nightly-gpg-', dir=n.owned_path(environment['RUNNER_TEMP'])) as temporary:
|
||||
secret, public = Path(temporary)/'secret', Path(temporary)/'public'
|
||||
secret.mkdir(mode=0o700); public.mkdir(mode=0o700)
|
||||
env = {**environment, 'GNUPGHOME': str(secret)}
|
||||
# Public trust is reviewed app source, NEVER downloaded from artifact/release.
|
||||
command(['/usr/bin/gpg', '--homedir', public, '--batch', '--import', trusted_key])
|
||||
listed = command(['/usr/bin/gpg', '--homedir', public, '--batch', '--with-colons', '--list-keys'])
|
||||
primaries = [line.split(':')[9] for line in listed.splitlines() if line.startswith('fpr:')]
|
||||
n.require(sum(line.startswith('pub:') for line in listed.splitlines()) == 1 and primaries,
|
||||
'exactly one reviewed Linux public primary key required')
|
||||
fingerprint = primaries[0]
|
||||
n.require(fingerprint == environment.get('NIGHTLY_LINUX_SIGNING_FINGERPRINT'),
|
||||
'Linux public key differs from independently reviewed full primary fingerprint')
|
||||
command(['/usr/bin/gpg', '--batch', '--import'], stdin=environment['LINUX_SIGNING_KEY'].encode(), env=env)
|
||||
shutil.copyfile(archive, output)
|
||||
signature = Path(str(output)+'.asc')
|
||||
command(['/usr/bin/gpg', '--batch', '--yes', '--pinentry-mode', 'error', '--local-user', fingerprint,
|
||||
'--armor', '--detach-sign', '-o', signature, output], env=env)
|
||||
keyring = Path(temporary)/'release-signing-key.gpg'
|
||||
# Binary export for gpgv; ASCII public export follows stable asset naming.
|
||||
exported = subprocess.run(['/usr/bin/gpg', '--homedir', str(public), '--batch', '--export', fingerprint],
|
||||
stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True, timeout=60).stdout
|
||||
keyring.write_bytes(exported)
|
||||
command(['/usr/bin/gpgv', '--homedir', public, '--keyring', keyring, signature, output])
|
||||
armored = command(['/usr/bin/gpg', '--homedir', public, '--batch', '--armor', '--export', fingerprint])
|
||||
(Path(output).parent/'release-signing-key.asc').write_text(armored+'\n')
|
||||
try:
|
||||
# Public trust is reviewed app source, NEVER downloaded from artifact/release.
|
||||
linux_public_keyring(trusted_key, fingerprint, public, environment)
|
||||
command(['/usr/bin/gpg', '--batch', '--import'], stdin=environment['LINUX_SIGNING_KEY'].encode(), env=env)
|
||||
shutil.copyfile(archive, output)
|
||||
signature = Path(str(output)+'.asc')
|
||||
command(['/usr/bin/gpg', '--batch', '--yes', '--pinentry-mode', 'error', '--local-user', fingerprint,
|
||||
'--armor', '--detach-sign', '-o', signature, output], env=env)
|
||||
# Verification never uses the secret keyring: only the reviewed public key.
|
||||
verify_linux_signature(trusted_key, signature, output, fingerprint, environment)
|
||||
armored = command(['/usr/bin/gpg', '--homedir', public, '--batch', '--armor', '--export', fingerprint],
|
||||
env=verification_env(environment))
|
||||
(Path(output).parent/'release-signing-key.asc').write_text(armored+'\n')
|
||||
finally:
|
||||
stop_gpg_agent(secret); stop_gpg_agent(public)
|
||||
return fingerprint
|
||||
|
||||
|
||||
@@ -387,7 +460,8 @@ def main():
|
||||
# App owns reuse of import-cert.sh + release codesign/notarytool/stapler;
|
||||
# this never invokes stable package.sh (it executes bundled CLI code).
|
||||
command(['/bin/bash', str(Path(args.source).resolve()/'packaging/macos/nightly-sign.sh'),
|
||||
'--arch', 'aarch64', '--input', Path(args.archive).resolve(), '--output', output.resolve()], env=dict(os.environ))
|
||||
'--arch', 'aarch64', '--input', Path(args.archive).resolve(), '--output', output.resolve()], env=dict(os.environ),
|
||||
timeout=5400)
|
||||
with tempfile.TemporaryDirectory(prefix='nightly-mac-verify-', dir=n.owned_path(os.environ['RUNNER_TEMP'])) as temporary:
|
||||
signer = mac_verify(output, args.version, n.bounded_json(args.pending), os.environ, Path(temporary)/'payload')
|
||||
n.require(sha(args.archive) == args.unsigned_sha256, 'original unsigned build bytes changed during signing')
|
||||
|
||||
+24
-5
@@ -36,19 +36,38 @@ CONTRACTS = {
|
||||
"asset_pattern":"photocraft-{version}-macos-aarch64-nightly.zip"},
|
||||
}
|
||||
|
||||
# Admitted rows ship with Windows (one release, every admitted platform); admission is not runtime qualification.
|
||||
ADMISSION = {
|
||||
"linux-x86_64": {"status":"feed-admitted", "feed_admitted":True, "runtime_qualified":False},
|
||||
"macos-aarch64": {"status":"feed-admitted", "feed_admitted":True, "runtime_qualified":False},
|
||||
}
|
||||
|
||||
def pending_contract(pending, platform):
|
||||
n.fields(pending, {"schema","app","capabilities"}, "pending producer registry")
|
||||
n.require(pending["schema"] == "craft-nightly-pending-producers/v1" and pending["app"] == "photocraft", "unreviewed pending registry")
|
||||
n.require(isinstance(pending["capabilities"],dict) and set(pending["capabilities"]) == set(CONTRACTS), "unreviewed pending target set")
|
||||
n.require(platform in CONTRACTS, "unsupported private Unix target")
|
||||
row = pending["capabilities"][platform]
|
||||
expected = {**CONTRACTS[platform], "isolation":ISOLATION, "status":"private-source-pending", "feed_admitted":False, "runtime_qualified":False}
|
||||
n.require(row == expected and type(row["isolation"]["profile_version"]) is int and row["feed_admitted"] is False and row["runtime_qualified"] is False, "pending row differs from owner contract or attempts admission")
|
||||
expected = {**CONTRACTS[platform], "isolation":ISOLATION, **ADMISSION[platform]}
|
||||
n.require(row == expected and type(row["isolation"]["profile_version"]) is int and row["feed_admitted"] is ADMISSION[platform]["feed_admitted"] and row["runtime_qualified"] is False, "pending row differs from owner contract or attempts admission")
|
||||
return row
|
||||
|
||||
def registry_target(row):
|
||||
return {"asset_pattern":row["asset_pattern"],"isolation":row["isolation"],"target":row["target"]}
|
||||
|
||||
def require_registry_admission(registry, platform, row):
|
||||
"""Admitted rows must appear exactly once in the active registry; pending rows never."""
|
||||
targets = n.app_record(registry,"photocraft")["targets"]
|
||||
matches = [item for item in targets if isinstance(item,dict) and item.get("target") == row["target"]]
|
||||
if row["feed_admitted"]:
|
||||
n.require(matches == [registry_target(row)], "admitted Unix target missing from or differing in the feed registry")
|
||||
else:
|
||||
n.require(not matches, "pending Unix target must not appear in the feed registry")
|
||||
|
||||
def check_prepared(registry, pending, platform, prepared, cargo, version, environment, target_base, dist, policy):
|
||||
row = pending_contract(pending,platform)
|
||||
n.trusted_context(registry,"photocraft",environment)
|
||||
require_registry_admission(registry,platform,row)
|
||||
n.fields(prepared,{"schema","channel","app","repository","tag","source_commit","published_at","version","ready"},"prepared identity")
|
||||
manifest=n.bounded_bytes(cargo,MAX_METADATA,'manifest')
|
||||
tomllib.loads(manifest.decode('utf-8')) # source manifest is bounded/valid; not the identity base
|
||||
@@ -66,12 +85,12 @@ def check_prepared(registry, pending, platform, prepared, cargo, version, enviro
|
||||
"build_date":dt.datetime.fromtimestamp(prepared["published_at"],dt.timezone.utc).strftime("%Y-%m-%d"),
|
||||
"rust_target":row["rust_target"],"entrypoint":row["entrypoint"],
|
||||
"target_leaf":str(target_base/"nightly-v1"/platform),"dist":str(dist),
|
||||
"private_only":True,"feed_admitted":False,"runtime_qualified":False}
|
||||
"private_only":not row["feed_admitted"],"feed_admitted":row["feed_admitted"],"runtime_qualified":False}
|
||||
|
||||
def require_build_policy(platform):
|
||||
# macOS compiles and smokes its ad-hoc (linker) signed GUI in the secret-free
|
||||
# producer job only; Developer ID/notarization is the separate release signer's job.
|
||||
n.require(platform in CONTRACTS,"unsupported private Unix target")
|
||||
if platform == "macos-aarch64":
|
||||
raise n.Unavailable("Mac production signing/team-ID/notarization policy is pending; no ad-hoc or unsigned execution fallback")
|
||||
|
||||
def canonical_version(version):
|
||||
n.require(isinstance(version,str) and len(version)<=128 and re.fullmatch(r'(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)-nightly\.([0-9]{8})\.[1-9][0-9]*\.[1-9][0-9]*\.g[0-9a-f]{12}',version), "noncanonical immutable nightly version")
|
||||
|
||||
@@ -22,12 +22,24 @@ CONTEXT_FIELDS = {"GITHUB_EVENT_NAME", "GITHUB_REF", "GITHUB_REPOSITORY",
|
||||
"GITHUB_SHA", "GITHUB_RUN_ID", "GITHUB_RUN_ATTEMPT"}
|
||||
|
||||
|
||||
def reviewed_windows_target(record):
|
||||
"""The exact Windows row, alone or beside other reviewed platform rows (one release)."""
|
||||
targets = record["targets"]
|
||||
if targets == [PHOTO_TARGET]:
|
||||
return type(targets[0]["isolation"]["profile_version"]) is int
|
||||
import nightly_release_platforms as plat
|
||||
try:
|
||||
platforms = plat.registry_platforms({"schema": "craft-nightly-registry/v1", "apps": {"photocraft": record}})
|
||||
except ValueError:
|
||||
return False
|
||||
rows = [item for item in targets if item == PHOTO_TARGET]
|
||||
return "windows-x86_64" in platforms and len(rows) == 1 and type(rows[0]["isolation"]["profile_version"]) is int
|
||||
|
||||
|
||||
def validate_prepared(registry, app, prepared, cargo, version, environment, policy=None):
|
||||
n.require(app == "photocraft", "no Windows nightly adapter for this app")
|
||||
record = n.trusted_context(registry, app, environment)
|
||||
n.require(record["targets"] == [PHOTO_TARGET] and
|
||||
type(record["targets"][0]["isolation"]["profile_version"]) is int,
|
||||
"unreviewed Windows target contract")
|
||||
n.require(reviewed_windows_target(record), "unreviewed Windows target contract")
|
||||
n.fields(prepared, {"schema", "channel", "app", "repository", "tag", "source_commit",
|
||||
"published_at", "version", "ready"}, "prepared identity")
|
||||
n.require(prepared["ready"] is True, "prepared capability unavailable")
|
||||
|
||||
@@ -140,8 +140,8 @@ def verify_ref(ref, ident):
|
||||
def publish_packet(api, ident, metadata, directory, guard=None, policy=None, *, on_published=None, policy_marker=None):
|
||||
"""Only mutates the draft returned from OUR create call in this invocation."""
|
||||
if policy_marker is not None:
|
||||
n.require(policy_marker=="craft-nightly-release-publication/v1:" and isinstance(policy,dict) and
|
||||
policy.get("schema")=="craft-nightly-release-publication/v1","unreviewed publication marker/schema")
|
||||
n.require(policy_marker in ("craft-nightly-release-publication/v1:","craft-nightly-release-publication/v2:") and
|
||||
isinstance(policy,dict) and policy.get("schema")==policy_marker[:-1],"unreviewed publication marker/schema")
|
||||
# Legacy no-policy calls exist only for frozen offline fixture generation.
|
||||
# The sole CLI always supplies the v6 live guard and bound policy below.
|
||||
n.require(guard is not None or not isinstance(api,HTTPTransport),"live transport requires a reviewed v6 publication guard")
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
# Stable PhotoCraft Linux OpenPGP fixture
|
||||
|
||||
Public, already-published bytes from the PhotoCraft v0.23.1 stable release:
|
||||
`release-signing-key.asc` (ArtCraft Linux Release Signing Key, primary
|
||||
2B76741B414AAD6CD33E631213A005C0B9D7C3ED, signing subkey
|
||||
568DC1F68F8FAECC797F3C7B006DAF6BB0EF334E), `SHA256SUMS.txt` and its detached
|
||||
`SHA256SUMS.txt.asc`. No secret material. Tests use them to show the nightly
|
||||
verifier accepts the real stable key shape (certify-only primary, separate
|
||||
signing subkey) and binds the signature to the primary fingerprint.
|
||||
@@ -0,0 +1,50 @@
|
||||
4eb051274dd320dee65cbba8c0337ac02571fedbcbd242385cc96fe30e94bfc4 photocraft-0.23.1-freebsd-aarch64.tar.gz
|
||||
75ab8fd294fb82b88d36e48e237297f07bb410a3004206adeca71118ad5b2eeb photocraft-0.23.1-freebsd-x86_64.tar.gz
|
||||
e43d4debbe66cf0ea27626097f2756848176a5540a3de59252c85dd3c7698246 photocraft-0.23.1-linux-aarch64.AppImage
|
||||
3cc051c0ceb53214f8d597d29b7ee4a633ab16bfc0bc4222d25e252aa9361c27 photocraft-0.23.1-linux-aarch64.AppImage.asc
|
||||
2efbd42dec446b8bab9791d5c20716d270de89ec50fa96447ba4364621ba51c5 photocraft-0.23.1-linux-aarch64.AppImage.zsync
|
||||
1edd7e6c1ae2c087ee6b7a99bcdd25665e48dc80c0ab771cc23eb380603b8982 photocraft-0.23.1-linux-aarch64.AppImage.zsync.asc
|
||||
ee297409f1efc0a0b648eb0b44b0c879e3cc5408dc149ffda1e630a5a204f388 photocraft-0.23.1-linux-aarch64.deb
|
||||
16092c9f98bbea70c1b3ede200765396b5302544822104af9ee9a160a695e80f photocraft-0.23.1-linux-aarch64.deb.asc
|
||||
0f1ac08924c876b86e093ada9e8693f95b55be613d5ee7896d4d3d72c5d66786 photocraft-0.23.1-linux-aarch64.flatpak
|
||||
6bf5a56226a1790cfb84aa99bae80d1af9dcb2126fdbe7e6cc5190fc29a04427 photocraft-0.23.1-linux-aarch64.flatpak.asc
|
||||
b6e98ea0be894bbd2c9a35acbed1a6aa2cbc87294f9f9cc1010efad4bdbda93c photocraft-0.23.1-linux-aarch64.oci-manifest.json
|
||||
021d76288734aeb0d189f454a222401c0b905b7d67b076e5ca29ea9827728a3f photocraft-0.23.1-linux-aarch64.oci.sig
|
||||
3acff2bd3c7e815496d505fb463f540ea3124557a32fbbaeb13942cc80e900f8 photocraft-0.23.1-linux-aarch64.pkg.tar.zst
|
||||
30216a0bceb0d98da40e09475dadf7531c8208686d359ee570299bc7ca04a6e8 photocraft-0.23.1-linux-aarch64.pkg.tar.zst.sig
|
||||
10349d21e52c62cd847a6992c306f123913beeaf25217c9b817a038f96734716 photocraft-0.23.1-linux-aarch64.rpm
|
||||
44bce8a6ab3d7b7ec7034124ca4e090c7f300b6c585dc83104caf16d73689fcf photocraft-0.23.1-linux-aarch64.rpm.asc
|
||||
fcc81c38ae62c72fa9f4fd1ec3d18396493ba261662792d6995cc35905ce71d2 photocraft-0.23.1-linux-aarch64.tar.gz
|
||||
5a6204e045b334c8531fa3ab15cd5db08e13f980c8ca6df5203f4e65404aeb68 photocraft-0.23.1-linux-aarch64.tar.gz.asc
|
||||
b3adf0584865cd8722bd0c48f30273f38ab4234f6326ee1aff17e18e883b7a62 photocraft-0.23.1-linux-riscv64.deb
|
||||
5f3e072b1fd9c440904ac95da8c1f6b21a7277978cd8d003edf275d433cf6123 photocraft-0.23.1-linux-riscv64.deb.asc
|
||||
2df8f0eeb540634bb26f64382e35a547417080d8e360c57b398ac270f652ff57 photocraft-0.23.1-linux-riscv64.rpm
|
||||
76f367ca86ab10c813b1293329186db4afb35eac42621adb102c4b2c31fbc4ce photocraft-0.23.1-linux-riscv64.rpm.asc
|
||||
35e370e3672631d8e73930cc66916009c95d084b6e877866a161c70e0dc77d79 photocraft-0.23.1-linux-riscv64.tar.gz
|
||||
5a35cd6af78342493edb768738bbbeff9ead53a1e18ea511c6fe344b2c9a5ade photocraft-0.23.1-linux-riscv64.tar.gz.asc
|
||||
05747b3e527e1e0a0c1de39970361cf38c8fca7e8d3e3601ef2082fb0e6dd17f photocraft-0.23.1-linux-x86_64.AppImage
|
||||
4fda29f0c784094c89e3d8ddb8cc319cb5bdd4d8af9f9302ad9f793713b93425 photocraft-0.23.1-linux-x86_64.AppImage.asc
|
||||
58898af5629e782298045a83a74b9b5801806f17f3300a04dcd42db88f937d15 photocraft-0.23.1-linux-x86_64.AppImage.zsync
|
||||
a57e518992327e5b62e56a0b15e656996cc23443652c2740b013558b7afb8d45 photocraft-0.23.1-linux-x86_64.AppImage.zsync.asc
|
||||
baabdcdbe46df2f72ccf6ecc2e98be00fbc33dbd4c1cd9426362a89a4b95f673 photocraft-0.23.1-linux-x86_64.deb
|
||||
88e96d6b732d1863b0e63668bf1ededdaae8ed7cfb6ab4f751fbb3e44acdb5ea photocraft-0.23.1-linux-x86_64.deb.asc
|
||||
5c9deb58f07bd54f323a5d985bed295b4c5b15789e02651e2f203d5e8ef211a5 photocraft-0.23.1-linux-x86_64.flatpak
|
||||
3aea55a4751eb05f9d2649a9d50bd13b44fd2c0fe70390f0d99d8be2213445b8 photocraft-0.23.1-linux-x86_64.flatpak.asc
|
||||
2f3c5c19f988bbc78e910e1904eb1b537bd3092a54dc2a0e12513710923ec8c9 photocraft-0.23.1-linux-x86_64.oci-manifest.json
|
||||
75f08c561476887c6d6c9293a8fa8e715ffd7f261304df5c2f2dcf23a6baeef5 photocraft-0.23.1-linux-x86_64.oci.sig
|
||||
6f55b05a7880a6db38374ac7985730304bcc9b499dae0f18f9d2dbd6bbb8d201 photocraft-0.23.1-linux-x86_64.pkg.tar.zst
|
||||
fbb0a056363e497ba8555b6645abf45690c5e97972383154657b321f7d84cb9d photocraft-0.23.1-linux-x86_64.pkg.tar.zst.sig
|
||||
6de9029b7ae426e3fff794840095b47471b16e0937086da22aa6178466c15636 photocraft-0.23.1-linux-x86_64.rpm
|
||||
08bc044e2907e41f86e7e154d7c64905860f9b78059da23661488922b716fe20 photocraft-0.23.1-linux-x86_64.rpm.asc
|
||||
4383aef67a07cc370ad250a6ed60015205d3e6c463faf3ff4b0f67b8178ccfc8 photocraft-0.23.1-linux-x86_64.tar.gz
|
||||
ce93bd2ca30585c7ecc9c7a9484c9c89a564a03f5eb281d66a5cc885486de42d photocraft-0.23.1-linux-x86_64.tar.gz.asc
|
||||
606a52917188c65dc71709781180a0e3244e0f3b7f40b2f5b80170e87364420d photocraft-0.23.1-macos-universal.dmg
|
||||
f02f0e754072836355b4aa8c46496fb0acff18a5fc780084bb4a40a2d9e1ab76 photocraft-0.23.1-windows-arm64-portable.zip
|
||||
5542e387a5f35b22e60544ff38e3485bbebe480af3775d9c4d0b9a909ba70526 photocraft-0.23.1-windows-arm64-symbols.zip
|
||||
d5fb081eaab54316b224cc1518e6ebace96b711b059828f4b397cc04e530611c photocraft-0.23.1-windows-arm64.msi
|
||||
6317e764ecfa804227c38079311bea489283ab383ef040c81ef2fd6d86bd60b1 photocraft-0.23.1-windows-x64-portable.zip
|
||||
61ceb478aa01d4dee19cb9fe2e1fe6367ca1a5974a20771c954885c21ba2bdd5 photocraft-0.23.1-windows-x64-symbols.zip
|
||||
de757802d8a12a41718ba24248c281d83f3bbecd64c5230f46f10c7f62070671 photocraft-0.23.1-windows-x64.msi
|
||||
a6ecdc6d4add02881642bda0a0b191b4974118651f2ec5641dc71b2c3ff4b752 photocraft-cli-0.23.1-macos-universal.zip
|
||||
3a498eb517bca6cec89f9c6b1fc6448269a05428c8a3a4637c16817da157f03c photocraft-web-0.23.1.zip
|
||||
8e6925a173d6a7134118da099948de4d9eeec7c1c0770998aec33c9d3f484740 release-signing-key.asc
|
||||
@@ -0,0 +1,7 @@
|
||||
-----BEGIN PGP SIGNATURE-----
|
||||
|
||||
iHUEABYKAB0WIQRWjcH2j4+uzHl/PHsAba9rsO8zTgUCavU0jAAKCRAAba9rsO8z
|
||||
TjQcAQDBbNTCipPrKuo8MzmtDUF9GMb4YIkjQBfqvWdZyIiBMgEAmIUtznxoiFXr
|
||||
0P+4o4eUy+hS9MtXX8NKZweLWWVkFQ4=
|
||||
=sTmI
|
||||
-----END PGP SIGNATURE-----
|
||||
@@ -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-----
|
||||
@@ -56,7 +56,8 @@ class ReleasedPatternTests(unittest.TestCase):
|
||||
version='0.23.1-nightly.20261120.1234.1.g'+'a'*12
|
||||
active=json.loads((ROOT/'nightly-apps.json').read_text())['apps']['photocraft']['targets']
|
||||
pending=json.loads((ROOT/'nightly-unix-pending.json').read_text())['capabilities']
|
||||
return [row['asset_pattern'].replace('{version}',version) for row in active]+[row['asset_pattern'].replace('{version}',version) for row in pending.values()]
|
||||
names=[row['asset_pattern'].replace('{version}',version) for row in active]+[row['asset_pattern'].replace('{version}',version) for row in pending.values()]
|
||||
return sorted(set(names)) # Admitted Linux is in both the registry and its capability row.
|
||||
def test_current_windows_nightly_does_not_match_old_installer_or_zip(self):
|
||||
names=self.names(); self.assertEqual(len(names),3)
|
||||
for arch in ('X64','X86','Arm64'): self.assertIsNone(pick(names,'Windows',arch))
|
||||
|
||||
@@ -17,14 +17,27 @@ import nightly_artifacts as bindings
|
||||
import test_nightly_policy as fixture
|
||||
|
||||
|
||||
def windows_only_registry(registry=None):
|
||||
"""Frozen single-target registry for the Windows-only main-route attestation and
|
||||
local E3/E4 packet paths. The live registry admits macOS as well; those multi-platform
|
||||
releases go through the release-ref signer, and main-route attestation refuses them."""
|
||||
import copy as _copy, json as _json
|
||||
registry = _copy.deepcopy(registry) if registry is not None else _json.loads((ROOT/'nightly-apps.json').read_text())
|
||||
photo = registry['apps']['photocraft']
|
||||
photo['targets'] = [row for row in photo['targets'] if row['target']['os'] == 'windows']
|
||||
return registry
|
||||
|
||||
|
||||
class AttestationTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.case=fixture.PolicyTests('test_green_gate_is_read_only_and_exact_source'); self.case.setUp()
|
||||
self.case.registry=windows_only_registry(self.case.registry)
|
||||
self.temp=tempfile.TemporaryDirectory(); self.addCleanup(self.temp.cleanup)
|
||||
self.root=Path(self.temp.name).resolve()
|
||||
self.ownership={'GITHUB_WORKSPACE':str(ROOT.resolve()),'RUNNER_TEMP':str(self.root)}
|
||||
ownership=patch.dict(os.environ,self.ownership); ownership.start(); self.addCleanup(ownership.stop)
|
||||
self.assets=self.root/'assets'; self.assets.mkdir(); self.packet=self.root/'packet'
|
||||
self.registry_path=self.root/'nightly-apps.json'; self.registry_path.write_text(json.dumps(self.case.registry))
|
||||
self.filename=self.case.registry['apps']['photocraft']['targets'][0]['asset_pattern'].replace('{version}',self.case.prepared['version'])
|
||||
self.data=b'SYNTHETIC PACKAGE BYTES, NOT A ZIP OR EXECUTABLE'
|
||||
(self.assets/self.filename).write_bytes(self.data)
|
||||
@@ -74,7 +87,7 @@ class AttestationTests(unittest.TestCase):
|
||||
receipt_dir=self.root/'signer';receipt_dir.mkdir(exist_ok=True)
|
||||
data=signing.receipt_data('windows-x86_64',self.filename,self.binding['identity_sha256'],'b'*64,self.binding['zip_sha256'],env['NIGHTLY_WINDOWS_PUBLISHER_SUBJECT'],env)
|
||||
receipt_path=receipt_dir/'nightly-signing.json';receipt_path.write_text(json.dumps(data))
|
||||
argv=['fixture','--registry',str(ROOT/'nightly-apps.json'),'--identity',str(self.identity/'nightly-identity.json'),
|
||||
argv=['fixture','--registry',str(self.registry_path),'--identity',str(self.identity/'nightly-identity.json'),
|
||||
'--policy',str(self.identity/'nightly-producer-policy.json'),'--directory',str(self.packet),'--config',str(self.config),
|
||||
'--identity-sha256',self.binding['identity_sha256'],'--packet-sha256',self.binding['packet_sha256'],
|
||||
'--zip-sha256',self.binding['zip_sha256'],'--asset',self.filename,
|
||||
|
||||
@@ -215,7 +215,11 @@ class NightlyTests(unittest.TestCase):
|
||||
self.assertGreaterEqual(len(production["apps"]), 18)
|
||||
self.assertEqual(len(production["apps"]), 19)
|
||||
self.assertEqual([name for name, row in production["apps"].items() if row["targets"]], ["photocraft"])
|
||||
self.assertEqual(len(production["apps"]["photocraft"]["targets"]), 1)
|
||||
# One release carries every admitted platform: Windows, Linux and the notarized macOS app.
|
||||
self.assertEqual([row["target"] for row in production["apps"]["photocraft"]["targets"]],
|
||||
[{"os": "windows", "arch": "x86_64", "format": "portable_zip"},
|
||||
{"os": "linux", "arch": "x86_64", "format": "tar_gz"},
|
||||
{"os": "macos", "arch": "aarch64", "format": "portable_zip"}])
|
||||
|
||||
def test_positive_synthetic_descriptor_hash_size_url_and_units(self):
|
||||
self.ready()
|
||||
|
||||
+326
-64
@@ -14,6 +14,9 @@ ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT/"scripts"))
|
||||
import nightly_release as b
|
||||
import test_nightly_release_request as fixtures
|
||||
WINDOWS, MAC, LINUX = "windows-x86_64", "macos-aarch64", "linux-x86_64"
|
||||
LINUX_FINGERPRINT = "0123456789ABCDEF0123456789ABCDEF01234567"
|
||||
SYNTHETIC_ASC = b"-----BEGIN PGP SIGNATURE-----\n\nc3ludGhldGljIGZpeHR1cmUsIG5vdCBhIHJlYWwgc2lnbmF0dXJl\n-----END PGP SIGNATURE-----\n" # Shape-only detached signature; not a real OpenPGP signature.
|
||||
|
||||
|
||||
class PacketAPI(fixtures.API):
|
||||
@@ -74,16 +77,27 @@ class BridgeTests(unittest.TestCase):
|
||||
self.root = Path(self.tmp.name)
|
||||
self.addCleanup(patch.stopall)
|
||||
patch.dict(os.environ, {"RUNNER_TEMP": str(self.root)}).start()
|
||||
self.env["RUNNER_TEMP"] = str(self.root)
|
||||
|
||||
def payload(self):
|
||||
directory = self.root/"payload"; directory.mkdir()
|
||||
(directory/self.plan["unsigned_asset"]).write_bytes(b"synthetic unsigned bytes, not an executable")
|
||||
digest = b.n.digest_file(directory, self.plan["unsigned_asset"])[1]
|
||||
manifest = b.unsigned_manifest(self.plan, self.request["producer"], digest)
|
||||
b.write_json(directory/"unsigned.json", manifest)
|
||||
return directory, manifest
|
||||
def payloads(self):
|
||||
"""One downloaded directory per admitted platform, as the validator lays them out."""
|
||||
self.payload_count = getattr(self, "payload_count", 0)+1
|
||||
root = self.root/("payload" if self.payload_count == 1 else "payload-"+str(self.payload_count)); root.mkdir()
|
||||
directories, manifests = {}, {}
|
||||
for platform, names in self.plan["platforms"].items():
|
||||
directory = root/platform; directory.mkdir()
|
||||
(directory/names["unsigned_asset"]).write_bytes(b"synthetic unsigned bytes for "+platform.encode()+b", not an executable")
|
||||
digest = b.n.digest_file(directory, names["unsigned_asset"])[1]
|
||||
manifests[platform] = b.unsigned_manifest(self.plan, self.request["producer"], platform, digest)
|
||||
b.write_json(directory/"unsigned.json", manifests[platform])
|
||||
directories[platform] = directory
|
||||
return root, directories, manifests
|
||||
|
||||
def verified(self, directory, *, version="2.102.0", failure=False, alter=None):
|
||||
def payload(self, platform=WINDOWS):
|
||||
_, directories, manifests = self.payloads()
|
||||
return directories[platform], manifests[platform]
|
||||
|
||||
def verified(self, directory, *, platform=WINDOWS, version="2.102.0", failure=False, alter=None):
|
||||
calls = []
|
||||
def runner(argv, **kwargs):
|
||||
calls.append((argv, kwargs))
|
||||
@@ -91,18 +105,24 @@ class BridgeTests(unittest.TestCase):
|
||||
return types.SimpleNamespace(stdout=("gh version "+version+" (fixture)\n").encode())
|
||||
if failure: raise subprocess.CalledProcessError(1, argv)
|
||||
result = self.fx.result()
|
||||
result[0]["verificationResult"]["statement"]["subject"][0]["digest"]["sha256"] = b.n.digest_file(directory, self.plan["unsigned_asset"])[1]
|
||||
result[0]["verificationResult"]["statement"]["subject"][0]["digest"]["sha256"] = b.n.digest_file(directory, self.plan["platforms"][platform]["unsigned_asset"])[1]
|
||||
if alter: alter(result)
|
||||
kwargs["stdout"].write(json.dumps(result).encode())
|
||||
return types.SimpleNamespace(returncode=0)
|
||||
result = b.verified_unsigned(self.policy, self.state, directory, runner=runner)
|
||||
result = b.verified_unsigned(self.policy, self.state, platform, directory, runner=runner)
|
||||
return result, calls
|
||||
|
||||
def validated(self):
|
||||
_, directories, _ = self.payloads()
|
||||
manifests, claims = {}, {}
|
||||
for platform, directory in directories.items():
|
||||
(manifests[platform], claims[platform]), _ = self.verified(directory, platform=platform)
|
||||
return directories, manifests, claims
|
||||
|
||||
def bundle(self):
|
||||
directory, manifest = self.payload()
|
||||
(manifest, claims), _ = self.verified(directory)
|
||||
output = self.root/"bundle"
|
||||
digest = b.stage_bundle(output, self.state, directory, manifest, claims)
|
||||
directories, manifests, claims = self.validated()
|
||||
output = self.root/("bundle" if self.payload_count == 1 else "bundle-"+str(self.payload_count))
|
||||
digest = b.stage_bundle(output, self.state, directories, manifests, claims)
|
||||
return output, digest
|
||||
|
||||
def test_output_capability_allows_only_workspace_and_runner_temp_descendants(self):
|
||||
@@ -130,15 +150,15 @@ class BridgeTests(unittest.TestCase):
|
||||
self.assertFalse((target/"metadata.json").exists())
|
||||
|
||||
def test_unowned_bundle_and_native_outputs_refuse_before_native_or_public_mutation(self):
|
||||
directory, manifest = self.payload()
|
||||
(_, claims), _ = self.verified(directory)
|
||||
state = {**self.state, "unsigned": manifest, "unsigned-claims": claims}
|
||||
directories, manifests, claims = self.validated()
|
||||
directory = directories[WINDOWS]
|
||||
state = {**self.state, "unsigned": manifests, "unsigned-claims": claims}
|
||||
workspace = self.root/"owned"; workspace.mkdir()
|
||||
with patch.dict(os.environ, {"GITHUB_WORKSPACE": str(workspace), "RUNNER_TEMP": str(workspace)}), patch.object(b.signing, "sign_windows") as native, patch.object(b.pub, "publish_packet") as publish:
|
||||
with patch.dict(os.environ, {"GITHUB_WORKSPACE": str(workspace), "RUNNER_TEMP": str(workspace)}), patch.object(b.plat.signing, "sign_windows") as native, patch.object(b.pub, "publish_packet") as publish:
|
||||
with self.assertRaisesRegex(ValueError, "owned"):
|
||||
b.stage_bundle(self.root/"escaped-bundle", self.state, directory, manifest, claims)
|
||||
b.stage_bundle(self.root/"escaped-bundle", self.state, directories, manifests, claims)
|
||||
with self.assertRaisesRegex(ValueError, "owned"):
|
||||
b.native_sign(self.policy, state, directory, self.root, self.root/"escaped-signed", {})
|
||||
b.native_sign(self.policy, state, WINDOWS, directory, self.root, self.root/"escaped-signed", {})
|
||||
with self.assertRaisesRegex(ValueError, "owned"):
|
||||
b.publish(self.policy, state, directory, self.root/"escaped-packet", self.root/"ownership.json", None, lambda: True, self.registry)
|
||||
native.assert_not_called(); publish.assert_not_called()
|
||||
@@ -147,12 +167,11 @@ class BridgeTests(unittest.TestCase):
|
||||
self.assertFalse((self.root/"escaped-packet").exists())
|
||||
|
||||
def test_bundle_metadata_keys_and_asset_names_cannot_become_output_paths(self):
|
||||
directory, manifest = self.payload()
|
||||
(_, claims), _ = self.verified(directory)
|
||||
for extra in ({**self.state, "../escape": {}},
|
||||
{**self.state, "plan": {**self.plan, "unsigned_asset": "../escape.zip"}}):
|
||||
directories, manifests, claims = self.validated()
|
||||
escaped = copy.deepcopy(self.plan); escaped["platforms"][MAC]["unsigned_asset"] = "../escape.zip"
|
||||
for extra in ({**self.state, "../escape": {}}, {**self.state, "plan": escaped}):
|
||||
with self.subTest(state=extra), self.assertRaises(ValueError):
|
||||
b.stage_bundle(self.root/"rejected-bundle", extra, directory, manifest, claims)
|
||||
b.stage_bundle(self.root/"rejected-bundle", extra, directories, manifests, claims)
|
||||
self.assertFalse((self.root/"rejected-bundle").exists())
|
||||
|
||||
def test_identity_uses_original_main_role_without_spoofing_real_release_sha(self):
|
||||
@@ -212,7 +231,7 @@ class BridgeTests(unittest.TestCase):
|
||||
self.assertNotEqual(Path(kwargs["stdout"].name).parent, directory)
|
||||
self.assertTrue(kwargs["check"])
|
||||
self.assertEqual(claims["payload_sha256"], manifest["unsigned_sha256"])
|
||||
self.assertNotEqual(claims["payload_sha256"], self.request["artifact"]["wrapper_sha256"])
|
||||
self.assertNotEqual(claims["payload_sha256"], self.request["artifacts"][WINDOWS]["wrapper_sha256"])
|
||||
|
||||
def test_old_or_failed_gh_cannot_be_replaced_with_a_verified_boolean(self):
|
||||
directory, _ = self.payload()
|
||||
@@ -233,36 +252,46 @@ class BridgeTests(unittest.TestCase):
|
||||
|
||||
def test_bundle_independent_hash_covers_metadata_and_exact_payload_inventory(self):
|
||||
directory, digest = self.bundle()
|
||||
state = b.verify_bundle(directory, digest, self.plan["unsigned_asset"])
|
||||
state = b.verify_bundle(directory, digest, b.validated_names(self.plan))
|
||||
self.assertEqual(state["request"], self.request)
|
||||
(directory/"request.json").write_text(json.dumps({**self.request, "repository": "other/repo"}))
|
||||
with self.assertRaisesRegex(ValueError, "bundle digest"):
|
||||
b.verify_bundle(directory, digest, self.plan["unsigned_asset"])
|
||||
b.verify_bundle(directory, digest, b.validated_names(self.plan))
|
||||
|
||||
def test_bundle_extra_files_or_symlinks_refuse(self):
|
||||
directory, digest = self.bundle()
|
||||
(directory/"evil.ps1").write_text("must not run")
|
||||
with self.assertRaises(ValueError): b.verify_bundle(directory, digest, self.plan["unsigned_asset"])
|
||||
with self.assertRaises(ValueError): b.verify_bundle(directory, digest, b.validated_names(self.plan))
|
||||
(directory/"evil.ps1").unlink()
|
||||
path = directory/"quality.json"; path.unlink(); path.symlink_to(directory/"request.json")
|
||||
with self.assertRaises(ValueError): b.verify_bundle(directory, digest, self.plan["unsigned_asset"])
|
||||
with self.assertRaises(ValueError): b.verify_bundle(directory, digest, b.validated_names(self.plan))
|
||||
|
||||
def test_native_wrapper_uses_release_source_and_records_real_roles_and_three_digests(self):
|
||||
directory, digest = self.bundle()
|
||||
state = b.verify_bundle(directory, digest, self.plan["unsigned_asset"])
|
||||
calls = []
|
||||
state = b.verify_bundle(directory, digest, b.validated_names(self.plan))
|
||||
calls = []; subject = self.policy["platforms"][WINDOWS]["trust"]["publisher_subject"]
|
||||
def native(source, archive, output, env, version):
|
||||
calls.append((source, archive, env, version))
|
||||
Path(output).write_bytes(b"synthetic signed bytes, not native qualification")
|
||||
return self.policy["windows_publisher_subject"]
|
||||
with patch.object(b.signing, "adapter") as adapter, patch.object(b.signing, "require_config") as config, patch.object(b.signing, "sign_windows", side_effect=native):
|
||||
return subject
|
||||
env = {**self.env, "WINDOWS_CERTIFICATE": "synthetic", "APPLE_CERTIFICATE": "must-not-reach-windows", "LINUX_SIGNING_KEY": "nope"}
|
||||
with patch.object(b.plat.signing, "adapter") as adapter, patch.object(b.plat.signing, "require_config") as config, patch.object(b.plat.signing, "sign_windows", side_effect=native), patch.object(b.plat.WINDOWS, "verify", return_value=subject) as verify:
|
||||
output = self.root/"signed"
|
||||
signed_digest = b.native_sign(self.policy, state, directory, "TRUSTED_RELEASE_ONLY", output, self.env)
|
||||
signed = b.verify_bundle(output, signed_digest, self.plan["asset"], signed=True)
|
||||
adapter.assert_called_once_with("windows-x86_64", "TRUSTED_RELEASE_ONLY")
|
||||
signed_digest = b.native_sign(self.policy, state, WINDOWS, directory, self.root, output, env)
|
||||
signed = b.verify_signed_bundle(output, signed_digest, WINDOWS)
|
||||
self.assertEqual(signed, b.verify_bundle(output, signed_digest, {self.plan["platforms"][WINDOWS]["asset"]}, signed=True))
|
||||
adapter.assert_called_once_with("windows-x86_64", self.root.resolve())
|
||||
config.assert_called_once()
|
||||
self.assertEqual(calls[0][0], "TRUSTED_RELEASE_ONLY")
|
||||
self.assertEqual(calls[0][0], self.root.resolve())
|
||||
# Only the platform's own secret reaches the Windows backend; foreign platform keys do not.
|
||||
self.assertEqual(calls[0][2]["WINDOWS_CERTIFICATE"], "synthetic")
|
||||
self.assertNotIn("APPLE_CERTIFICATE", calls[0][2]); self.assertNotIn("LINUX_SIGNING_KEY", calls[0][2])
|
||||
self.assertEqual(calls[0][2]["NIGHTLY_WINDOWS_PUBLISHER_SUBJECT"], subject)
|
||||
# The keyless re-verification receives no credentials at all.
|
||||
self.assertNotIn("WINDOWS_CERTIFICATE", verify.call_args.args[5])
|
||||
receipt = signed["signing"]
|
||||
self.assertEqual((receipt["schema"], receipt["platform"]), ("craft-nightly-signing/v3", WINDOWS))
|
||||
self.assertEqual(receipt["artifact"], self.request["artifacts"][WINDOWS])
|
||||
self.assertEqual(receipt["producer"]["source_commit"], "a"*40)
|
||||
self.assertEqual(receipt["signer"]["source_commit"], "d"*40)
|
||||
self.assertEqual(len({receipt["artifact"]["wrapper_sha256"], receipt["unsigned_sha256"], receipt["final_sha256"]}), 3)
|
||||
@@ -294,15 +323,34 @@ class BridgeTests(unittest.TestCase):
|
||||
with self.assertRaises(ValueError): b.source_policy(source, {**env, "GITHUB_SHA": "f"*40})
|
||||
with self.assertRaises(ValueError): b.git_read(source, ["push"])
|
||||
|
||||
def history(self):
|
||||
request = copy.deepcopy(self.request)
|
||||
receipt = b.r.release_receipt(self.policy, request, "1"*64, "2"*64, self.policy["windows_publisher_subject"])
|
||||
publication = {"schema": "craft-nightly-release-publication/v1", "request": request,
|
||||
"plan": self.plan, "quality": self.state["quality"], "signing": receipt}
|
||||
def history(self, *, live=False, missing_signature=False):
|
||||
"""Frozen v1 Windows-only publication (legacy v2 policy), or a v2 all-platform one."""
|
||||
if live:
|
||||
policy, request = self.policy, copy.deepcopy(self.request)
|
||||
linux_asc = self.plan["platforms"][LINUX]["asset"]+".asc"
|
||||
support = {LINUX: {linux_asc: {"size": len(SYNTHETIC_ASC), "sha256": hashlib.sha256(SYNTHETIC_ASC).hexdigest()}}}
|
||||
if missing_signature: support = {}
|
||||
signing = {platform: b.r.release_receipt_v3(policy, request, platform, "1"*64, str(index+2)*64,
|
||||
b.r.trusted_signer(policy, platform), support.get(platform, {})) for index, platform in enumerate(sorted(self.plan["platforms"]))}
|
||||
publication = {"schema": "craft-nightly-release-publication/v2", "request": request,
|
||||
"plan": self.plan, "quality": self.state["quality"], "signing": signing}
|
||||
body = b.MARKER_V2+json.dumps(publication)
|
||||
assets = [{"name": self.plan["platforms"][platform]["asset"], "digest": "sha256:"+receipt["final_sha256"]}
|
||||
for platform, receipt in signing.items()]
|
||||
if not missing_signature:
|
||||
assets.append({"name": linux_asc, "digest": "sha256:"+hashlib.sha256(SYNTHETIC_ASC).hexdigest()})
|
||||
else:
|
||||
policy = self.fx.legacy_policy(); request = self.fx.legacy_request(policy)
|
||||
receipt = b.r.release_receipt(policy, request, "1"*64, "2"*64, policy["windows_publisher_subject"])
|
||||
plan = b.identity_plan_v1(self.registry, request["producer"], self.plan["stable_base"])
|
||||
publication = {"schema": "craft-nightly-release-publication/v1", "request": request,
|
||||
"plan": plan, "quality": self.state["quality"], "signing": receipt}
|
||||
body = b.MARKER+json.dumps(publication)
|
||||
assets = [{"name": plan["asset"], "digest": "sha256:"+"2"*64}]
|
||||
release = {"id": 7, "tag_name": self.plan["identity"]["tag"], "target_commitish": "a"*40,
|
||||
"draft": False, "prerelease": True, "body": b.MARKER+json.dumps(publication)}
|
||||
"draft": False, "prerelease": True, "body": body}
|
||||
rows = {"/compare/"+"d"*40+"..."+"d"*40: {"status": "identical", "behind_by": 0, "merge_base_commit": {"sha": "d"*40}}}
|
||||
raw = json.dumps(self.policy).encode()
|
||||
raw = json.dumps(policy).encode()
|
||||
rows["/contents/.github/nightly-signing-policy.json?ref="+"d"*40] = {
|
||||
"encoding": "base64", "size": len(raw), "content": b.base64.b64encode(raw).decode()}
|
||||
for run_id in (100, 200):
|
||||
@@ -313,7 +361,7 @@ class BridgeTests(unittest.TestCase):
|
||||
"jobs": [{"id": 9, "status": "completed", "conclusion": "success",
|
||||
"steps": [{"name": b.PUBLISH_STEP, "conclusion": "success"}]}]}
|
||||
rows["/git/ref/tags/"+release["tag_name"]] = {"object": {"type": "commit", "sha": "a"*40}}
|
||||
rows["/releases/7/assets?per_page=100"] = [{"name": self.plan["asset"], "digest": "sha256:"+"2"*64}]
|
||||
rows["/releases/7/assets?per_page=100"] = assets
|
||||
return fixtures.API(rows), release
|
||||
|
||||
def test_previous_publication_authenticates_both_roles_protected_policy_step_tag_and_digest(self):
|
||||
@@ -342,9 +390,9 @@ class BridgeTests(unittest.TestCase):
|
||||
failed["conclusion"] = "success"
|
||||
|
||||
|
||||
def test_previous_v1_policy_stays_historical_under_current_v2_live_policy(self):
|
||||
def test_previous_v1_policy_stays_historical_under_current_v3_live_policy(self):
|
||||
api, release = self.history()
|
||||
old = copy.deepcopy(self.policy); old['schema'] = 'craft-nightly-release-policy/v1'
|
||||
old = self.fx.legacy_policy(); old['schema'] = 'craft-nightly-release-policy/v1'
|
||||
del old['automatic_signer_actors']; old['manual_actors'] = ['github-actions[bot]']
|
||||
publication = json.loads(release['body'].split(b.MARKER, 1)[1])
|
||||
publication['request']['policy_sha256'] = b.r.digest(old)
|
||||
@@ -356,7 +404,7 @@ class BridgeTests(unittest.TestCase):
|
||||
'encoding':'base64', 'size':len(raw), 'content':b.base64.b64encode(raw).decode()}
|
||||
previous = b.previous_publication(api, self.registry, self.policy, self.request, [release])
|
||||
self.assertEqual(previous['identity'], self.plan['identity'])
|
||||
self.assertEqual(self.policy['schema'], 'craft-nightly-release-policy/v2')
|
||||
self.assertEqual(self.policy['schema'], 'craft-nightly-release-policy/v3')
|
||||
|
||||
def test_previous_publication_refuses_history_run_step_tag_digest_and_pagination_substitution(self):
|
||||
mutations = [
|
||||
@@ -391,28 +439,43 @@ class BridgeTests(unittest.TestCase):
|
||||
legacy.assert_called_once_with(None, self.registry, release)
|
||||
|
||||
def test_missing_native_config_refuses_before_native_signer_execution(self):
|
||||
directory, digest = self.bundle(); state = b.verify_bundle(directory, digest, self.plan["unsigned_asset"])
|
||||
with patch.object(b.signing, "adapter"), patch.object(b.signing, "sign_windows") as native:
|
||||
directory, digest = self.bundle(); state = b.verify_bundle(directory, digest, b.validated_names(self.plan))
|
||||
with patch.object(b.plat.signing, "adapter"), patch.object(b.plat.signing, "sign_windows") as native:
|
||||
with self.assertRaisesRegex(ValueError, "complete Windows"):
|
||||
b.native_sign(self.policy, state, directory, "TRUSTED_RELEASE_ONLY", self.root/"signed", self.env)
|
||||
b.native_sign(self.policy, state, WINDOWS, directory, self.root, self.root/"signed", self.env)
|
||||
native.assert_not_called()
|
||||
with patch.object(b.plat.signing, "adapter"), patch.object(b.plat.signing, "command") as command:
|
||||
# The release environment's Windows secrets never satisfy the Apple requirement.
|
||||
env = {**self.env, "WINDOWS_CERTIFICATE": "x", "WINDOWS_CERTIFICATE_PASSWORD": "y"}
|
||||
with self.assertRaisesRegex(ValueError, "six Apple"):
|
||||
b.native_sign(self.policy, state, MAC, directory, self.root, self.root/"signed-mac", env)
|
||||
command.assert_not_called()
|
||||
|
||||
def publication_fixture(self):
|
||||
(self.root/self.plan["asset"]).write_bytes(b"synthetic signed bytes, not native qualification")
|
||||
digest = b.n.digest_file(self.root, self.plan["asset"])[1]
|
||||
receipt = b.r.release_receipt(self.policy, self.request, "1"*64, digest, self.policy["windows_publisher_subject"])
|
||||
state = {**self.state, "signing": receipt}
|
||||
combined = self.root/"combined"; combined.mkdir()
|
||||
signing = {}
|
||||
for platform, names in sorted(self.plan["platforms"].items()):
|
||||
(combined/names["asset"]).write_bytes(b"synthetic signed bytes for "+platform.encode()+b", not native qualification")
|
||||
digest = b.n.digest_file(combined, names["asset"])[1]
|
||||
support = {}
|
||||
if platform == LINUX: # Linux publishes the detached .asc beside the unchanged tar.gz.
|
||||
(combined/(names["asset"]+".asc")).write_bytes(SYNTHETIC_ASC)
|
||||
size, asc = b.n.digest_file(combined, names["asset"]+".asc")
|
||||
support = {names["asset"]+".asc": {"size": size, "sha256": asc}}
|
||||
signing[platform] = b.r.release_receipt_v3(self.policy, self.request, platform, "1"*64, digest,
|
||||
b.r.trusted_signer(self.policy, platform), support)
|
||||
state = {**self.state, "signing": signing}
|
||||
return state, self.root/"packet"
|
||||
|
||||
def publication_api(self):
|
||||
history, _ = self.history()
|
||||
history, _ = self.history(live=True)
|
||||
return PacketAPI(history.rows)
|
||||
|
||||
def test_verified_publication_fsync_failure_warns_without_canonical_receipt_and_next_run_continues(self):
|
||||
state, packet = self.publication_fixture(); api = self.publication_api()
|
||||
ownership = self.root/"ownership"
|
||||
with patch.object(b.os, "fsync", side_effect=OSError("synthetic fsync failure")), patch.object(b, "bookkeeping_warning") as warning:
|
||||
result = b.publish(self.policy, state, self.root, packet, ownership, api, lambda: True, self.registry)
|
||||
result = b.publish(self.policy, state, self.root/"combined", packet, ownership, api, lambda: True, self.registry)
|
||||
self.assertEqual(result["id"], 7); self.assertFalse(result["draft"])
|
||||
self.assertEqual(len([write for write in api.writes if write[:2] == ("PATCH", "/releases/7")]), 1)
|
||||
warning.assert_called_once()
|
||||
@@ -461,7 +524,7 @@ class BridgeTests(unittest.TestCase):
|
||||
if failure == "promotion": raise OSError("synthetic promotion failed")
|
||||
return replace(source, destination)
|
||||
with self.subTest(failure=failure), patch("nightly_ownership_receipt.reserve", side_effect=faulty_reserve), patch.object(b.os, "replace", side_effect=promote), patch.object(b, "bookkeeping_warning") as warning:
|
||||
result = b.publish(self.policy, state, self.root, self.root/("packet-"+failure), ownership, api, lambda: True, self.registry)
|
||||
result = b.publish(self.policy, state, self.root/"combined", self.root/("packet-"+failure), ownership, api, lambda: True, self.registry)
|
||||
self.assertEqual(result["id"], 7); warning.assert_called_once()
|
||||
self.assertFalse((ownership/"ownership.json").exists())
|
||||
self.assertTrue((ownership/"ownership.pending.json").exists())
|
||||
@@ -491,7 +554,7 @@ class BridgeTests(unittest.TestCase):
|
||||
self.assertEqual(Path(destination), ownership/"ownership.json")
|
||||
return replace(source, destination)
|
||||
with patch("nightly_ownership_receipt.reserve", side_effect=observe), patch.object(b.os, "fsync", side_effect=fsync), patch.object(b.os, "replace", side_effect=promote), patch.object(b, "bookkeeping_warning") as warning:
|
||||
result = b.publish(self.policy, state, self.root, packet, ownership, api, lambda: True, self.registry)
|
||||
result = b.publish(self.policy, state, self.root/"combined", packet, ownership, api, lambda: True, self.registry)
|
||||
self.assertEqual(result["id"], 7); self.assertEqual(calls, ["fsync", "promote"])
|
||||
warning.assert_not_called()
|
||||
self.assertFalse((ownership/"ownership.pending.json").exists())
|
||||
@@ -508,7 +571,7 @@ class BridgeTests(unittest.TestCase):
|
||||
ownership = self.root/("ownership-"+failure)
|
||||
with self.subTest(failure=failure), patch.object(b, "bookkeeping_warning") as warning:
|
||||
with self.assertRaises(b.pub.PublishedWithoutReceipt):
|
||||
b.publish(self.policy, state, self.root, self.root/("packet-"+failure), ownership, api, lambda: True, self.registry)
|
||||
b.publish(self.policy, state, self.root/"combined", self.root/("packet-"+failure), ownership, api, lambda: True, self.registry)
|
||||
self.assertFalse(api.release["draft"])
|
||||
self.assertFalse((ownership/"ownership.json").exists())
|
||||
warning.assert_not_called()
|
||||
@@ -523,7 +586,7 @@ class BridgeTests(unittest.TestCase):
|
||||
return True
|
||||
ownership = self.root/("ownership-"+str(failed_gate))
|
||||
with self.subTest(failed_gate=failed_gate), self.assertRaisesRegex(ValueError, "guard refusal"):
|
||||
b.publish(self.policy, state, self.root, self.root/("packet-"+str(failed_gate)), ownership, api, guard, self.registry)
|
||||
b.publish(self.policy, state, self.root/"combined", self.root/("packet-"+str(failed_gate)), ownership, api, guard, self.registry)
|
||||
self.assertFalse((ownership/"ownership.json").exists())
|
||||
self.assertFalse(any(write[0] == "PATCH" for write in api.writes))
|
||||
|
||||
@@ -536,7 +599,7 @@ class BridgeTests(unittest.TestCase):
|
||||
return original(value, *args, **kwargs)
|
||||
dumps.side_effect = serialize
|
||||
with patch.object(b, "bookkeeping_warning") as warning, self.assertRaises(b.pub.PublishedWithoutReceipt):
|
||||
b.publish(self.policy, state, self.root, packet, self.root/"ownership", api, lambda: True, self.registry)
|
||||
b.publish(self.policy, state, self.root/"combined", packet, self.root/"ownership", api, lambda: True, self.registry)
|
||||
warning.assert_not_called()
|
||||
self.assertFalse((self.root/"ownership"/"ownership.json").exists())
|
||||
|
||||
@@ -544,7 +607,7 @@ class BridgeTests(unittest.TestCase):
|
||||
state, packet = self.publication_fixture()
|
||||
with patch.object(b.pub, "publish_packet", side_effect=OSError("synthetic before publication")):
|
||||
with self.assertRaisesRegex(OSError, "before publication"):
|
||||
b.publish(self.policy, state, self.root, packet, self.root/"ownership", None, lambda: True, self.registry)
|
||||
b.publish(self.policy, state, self.root/"combined", packet, self.root/"ownership", None, lambda: True, self.registry)
|
||||
|
||||
def test_postpublication_GITHUB_OUTPUT_IO_warns_but_non_IO_errors_still_fail(self):
|
||||
with patch.object(b, "outputs", side_effect=OSError("synthetic output failed")), patch.object(b, "bookkeeping_warning") as warning:
|
||||
@@ -593,4 +656,203 @@ class BridgeTests(unittest.TestCase):
|
||||
with self.subTest(path=path), self.assertRaises(ValueError): plan(path)
|
||||
|
||||
|
||||
# ---- policy v3 / one release for every admitted platform -------------------------
|
||||
|
||||
def test_plan_names_every_admitted_platform_and_refuses_unreviewed_rows(self):
|
||||
self.assertEqual(sorted(self.plan["platforms"]), [LINUX, MAC, WINDOWS])
|
||||
linux = self.plan["platforms"][LINUX]; version = self.plan["identity"]["version"]
|
||||
self.assertEqual(linux, {"asset": "photocraft-"+version+"-linux-x86_64-nightly.tar.gz", "built_asset": "photocraft-"+version+"-linux-x86_64-nightly.tar.gz",
|
||||
"unsigned_asset": "photocraft-"+version+"-linux-x86_64-nightly.unsigned.tar.gz"})
|
||||
mac = self.plan["platforms"][MAC]; version = self.plan["identity"]["version"]
|
||||
self.assertEqual(mac["asset"], "photocraft-"+version+"-macos-aarch64-nightly.zip")
|
||||
self.assertEqual(mac["built_asset"], mac["asset"]) # nightly.sh writes the feed name
|
||||
self.assertEqual(mac["unsigned_asset"], "photocraft-"+version+"-macos-aarch64-nightly.unsigned.zip")
|
||||
self.assertEqual(self.plan["platforms"][WINDOWS]["built_asset"], self.plan["platforms"][WINDOWS]["unsigned_asset"])
|
||||
for mutate in (lambda row: row["target"].update(arch="x86_64"), lambda row: row["isolation"].update(associations="stable"),
|
||||
lambda row: row.update(asset_pattern="photocraft-{version}-macos-aarch64.zip")):
|
||||
registry = copy.deepcopy(self.registry)
|
||||
mutate([row for row in registry["apps"]["photocraft"]["targets"] if row["target"]["os"] == "macos"][0])
|
||||
with self.subTest(mutate=mutate), self.assertRaises(ValueError):
|
||||
b.identity_plan(registry, self.request["producer"], self.plan["stable_base"])
|
||||
|
||||
def test_protected_policy_must_sign_exactly_the_admitted_registry_platforms(self):
|
||||
policy = copy.deepcopy(self.policy); del policy["platforms"][MAC]
|
||||
with patch.object(b.p, "releases", return_value=[]), patch.object(b.p, "stable_base", return_value=self.plan["stable_base"]):
|
||||
with self.assertRaisesRegex(ValueError, "admitted registry targets"):
|
||||
b.publication_state(None, self.registry, policy, self.request)
|
||||
|
||||
def test_validator_needs_exactly_one_downloaded_directory_per_platform(self):
|
||||
root, directories, _ = self.payloads()
|
||||
self.assertEqual(b.platform_directories(root, [LINUX, MAC, WINDOWS]), directories)
|
||||
with self.assertRaisesRegex(ValueError, "unexpected platform directory"): b.platform_directories(root, [MAC, WINDOWS])
|
||||
(root/"freebsd-x86_64").mkdir()
|
||||
with self.assertRaisesRegex(ValueError, "unexpected platform directory"): b.platform_directories(root, [LINUX, MAC, WINDOWS])
|
||||
(root/"freebsd-x86_64").rmdir(); import shutil; shutil.rmtree(directories[MAC])
|
||||
with self.assertRaisesRegex(ValueError, "missing platform directory"): b.platform_directories(root, [LINUX, MAC, WINDOWS])
|
||||
|
||||
def test_unsigned_manifest_is_bound_to_its_platform(self):
|
||||
directory, manifest = self.payload(MAC)
|
||||
self.assertEqual(manifest["platform"], MAC)
|
||||
(directory/"unsigned.json").unlink()
|
||||
b.write_json(directory/"unsigned.json", {**manifest, "platform": WINDOWS})
|
||||
with self.assertRaisesRegex(ValueError, "source/version/hash"):
|
||||
self.verified(directory, platform=MAC)
|
||||
|
||||
def mac_signer_fixture(self, *, extra=False, unchanged=False, verified="SYNTH12345"):
|
||||
directory, digest = self.bundle()
|
||||
state = b.verify_bundle(directory, digest, b.validated_names(self.plan))
|
||||
calls = {}
|
||||
source = self.root/"release-source"
|
||||
for name in ("nightly.sh", "nightly-sign.sh", "import-cert.sh"):
|
||||
(source/"packaging/macos").mkdir(parents=True, exist_ok=True); (source/"packaging/macos"/name).write_text("# synthetic")
|
||||
def command(argv, *, env=None, timeout=3900, stdin=None):
|
||||
calls.update(argv=[str(value) for value in argv], env=dict(env), timeout=timeout)
|
||||
output = Path(argv[argv.index("--output")+1]); source_zip = Path(argv[argv.index("--input")+1])
|
||||
output.write_bytes(source_zip.read_bytes() if unchanged else b"synthetic notarized bytes, not native qualification")
|
||||
if extra: (output.parent/"keychain-leftover").write_text("x")
|
||||
return ""
|
||||
def verify(archive, version, pending, env, payload):
|
||||
calls["verify_env"] = dict(env); calls["verified_archive"] = Path(archive)
|
||||
return verified
|
||||
env = {**self.env, **{name: "synthetic-"+name for name in b.plat.signing.APPLE_SECRETS},
|
||||
"APPLE_TEAM_ID": "SYNTH12345", "WINDOWS_CERTIFICATE": "must-not-reach-apple", "GH_TOKEN": "must-not-reach-apple"}
|
||||
return state, directory, source, env, calls, command, verify
|
||||
|
||||
def test_mac_signer_passes_only_apple_secrets_exact_asset_name_and_notarization_budget(self):
|
||||
state, directory, source, env, calls, command, verify = self.mac_signer_fixture()
|
||||
with patch.object(b.plat.signing, "command", side_effect=command), patch.object(b.plat.signing, "mac_verify", side_effect=verify), \
|
||||
patch("nightly_unix.verify_archive", return_value={}) as inventory:
|
||||
digest = b.native_sign(self.policy, state, MAC, directory, source, self.root/"signed-mac", env)
|
||||
names = self.plan["platforms"][MAC]
|
||||
self.assertEqual(calls["argv"][:2], ["/bin/bash", str(source.resolve()/"packaging/macos/nightly-sign.sh")])
|
||||
self.assertEqual(Path(calls["argv"][calls["argv"].index("--input")+1]).name, names["asset"])
|
||||
self.assertEqual(calls["timeout"], b.plat.MAC_SIGN_TIMEOUT); self.assertGreaterEqual(b.plat.MAC_SIGN_TIMEOUT, 5400)
|
||||
for name in b.plat.signing.APPLE_SECRETS: self.assertIn(name, calls["env"])
|
||||
for name in ("WINDOWS_CERTIFICATE", "GH_TOKEN"): self.assertNotIn(name, calls["env"])
|
||||
self.assertEqual(calls["env"]["NIGHTLY_APPLE_TEAM_ID"], "SYNTH12345")
|
||||
# Keyless re-verification: no Apple secret reaches the verifier.
|
||||
self.assertFalse(set(b.plat.signing.APPLE_SECRETS) & set(calls["verify_env"]))
|
||||
inventory.assert_called_once()
|
||||
signed = b.verify_signed_bundle(self.root/"signed-mac", digest, MAC)
|
||||
receipt = signed["signing"]
|
||||
self.assertEqual((receipt["platform"], receipt["method"], receipt["verified_signer"]), (MAC, "developer-id-notarized", "SYNTH12345"))
|
||||
self.assertEqual(receipt["artifact"], self.request["artifacts"][MAC])
|
||||
self.assertEqual(sorted(path.name for path in (self.root/"signed-mac").iterdir()),
|
||||
sorted(b.BUNDLE_FILES | {"signing.json", names["asset"]}))
|
||||
|
||||
def test_mac_signer_refuses_extra_output_unchanged_bytes_or_other_team(self):
|
||||
for kwargs, reason in (({"extra": True}, "unexpected files"), ({"unchanged": True}, "unsigned fallback"),
|
||||
({"verified": "OTHER12345"}, "team differs")):
|
||||
state, directory, source, env, calls, command, verify = self.mac_signer_fixture(**kwargs)
|
||||
output = self.root/("signed-"+reason.replace(" ", "-"))
|
||||
with self.subTest(reason=reason), patch.object(b.plat.signing, "command", side_effect=command), \
|
||||
patch.object(b.plat.signing, "mac_verify", side_effect=verify), patch("nightly_unix.verify_archive", return_value={}), \
|
||||
self.assertRaisesRegex(ValueError, reason):
|
||||
b.native_sign(self.policy, state, MAC, directory, source, output, env)
|
||||
self.assertFalse((output/"signing.json").exists())
|
||||
|
||||
def signed_tree(self):
|
||||
"""Both platforms' signed bundles laid out as the publisher downloads them."""
|
||||
directory, digest = self.bundle()
|
||||
state = b.verify_bundle(directory, digest, b.validated_names(self.plan))
|
||||
root = self.root/"signed"; root.mkdir(); env = {"RUNNER_TEMP": str(self.root)}
|
||||
trust = {WINDOWS: "CN=Synthetic fixture only", MAC: "SYNTH12345", LINUX: LINUX_FINGERPRINT}
|
||||
for platform in (WINDOWS, MAC, LINUX):
|
||||
def sign(trust_value, unsigned, output, source, environment, version, platform=platform):
|
||||
asset = self.plan["platforms"][platform]["asset"]
|
||||
(Path(output)/asset).write_bytes(b"signed "+platform.encode())
|
||||
support = {}
|
||||
if platform == LINUX:
|
||||
(Path(output)/(asset+".asc")).write_bytes(SYNTHETIC_ASC)
|
||||
size, digest = b.n.digest_file(output, asset+".asc")
|
||||
support = {asset+".asc": {"size": size, "sha256": digest}}
|
||||
return {"verified_signer": trust[platform], "support": support}
|
||||
with patch.object(b.plat.plugin(platform), "sign", side_effect=sign):
|
||||
env["SIGNED_BUNDLE_SHA256_"+b.plat.secret_key(platform)] = b.native_sign(
|
||||
self.policy, state, platform, directory, self.root, root/platform, {**self.env, "RUNNER_TEMP": str(self.root)})
|
||||
mac_final = b.n.digest_file(root/MAC, self.plan["platforms"][MAC]["asset"])[1]
|
||||
env["VERIFIED_FINAL_SHA256_MACOS_AARCH64"] = mac_final
|
||||
env["VERIFIED_FINAL_SHA256_LINUX_X86_64"] = b.n.digest_file(root/LINUX, self.plan["platforms"][LINUX]["asset"])[1]
|
||||
return root, env
|
||||
|
||||
def test_publisher_binds_each_platform_bundle_native_windows_and_fresh_mac_verifier(self):
|
||||
root, env = self.signed_tree()
|
||||
shared, directories = b.signed_states(self.policy, root, env)
|
||||
self.assertEqual(sorted(shared["signing"]), [LINUX, MAC, WINDOWS])
|
||||
with patch.object(b.plat.WINDOWS, "verify", return_value="CN=Synthetic fixture only") as windows:
|
||||
self.assertTrue(b.verify_final(self.policy, shared, directories, self.root, env))
|
||||
windows.assert_called_once()
|
||||
with patch.object(b.plat.MACOS, "verify", side_effect=AssertionError("macOS is verified on its own fresh runner")), \
|
||||
patch.object(b.plat.WINDOWS, "verify", return_value="CN=Synthetic fixture only"):
|
||||
for key, value in (("VERIFIED_FINAL_SHA256_MACOS_AARCH64", ""), ("VERIFIED_FINAL_SHA256_MACOS_AARCH64", "0"*64)):
|
||||
with self.subTest(key=key, value=value), self.assertRaisesRegex(ValueError, "fresh platform verifier"):
|
||||
b.verify_final(self.policy, shared, directories, self.root, {**env, key: value})
|
||||
for key in ("SIGNED_BUNDLE_SHA256_MACOS_AARCH64", "SIGNED_BUNDLE_SHA256_WINDOWS_X86_64"):
|
||||
with self.subTest(missing=key), self.assertRaises(ValueError):
|
||||
b.signed_states(self.policy, root, {**env, key: ""})
|
||||
(root/MAC/"signing.json").write_text(json.dumps({**shared["signing"][MAC], "final_sha256": "0"*64}))
|
||||
with self.assertRaisesRegex(ValueError, "bundle digest"):
|
||||
b.signed_states(self.policy, root, env)
|
||||
|
||||
def test_publisher_refuses_platform_bundles_from_different_admissions_or_missing_platforms(self):
|
||||
root, env = self.signed_tree()
|
||||
import shutil
|
||||
shutil.rmtree(root/MAC)
|
||||
with self.assertRaisesRegex(ValueError, "missing platform directory"): b.signed_states(self.policy, root, env)
|
||||
# Re-sign macOS against a different quality snapshot: the shared admission must be identical.
|
||||
root2 = self.root/"second"; root2.mkdir()
|
||||
self.root, original = root2, self.root
|
||||
try:
|
||||
root, env = self.signed_tree()
|
||||
quality = json.loads((root/MAC/"quality.json").read_text()); quality["synthetic"] = "different"
|
||||
(root/MAC/"quality.json").write_text(json.dumps(quality, sort_keys=True, separators=(",", ":"))+"\n")
|
||||
# Recompute that bundle's job digest as if its own signer produced it.
|
||||
env["SIGNED_BUNDLE_SHA256_MACOS_AARCH64"] = b.bundle_hash(root/MAC, {self.plan["platforms"][MAC]["asset"]}, signed=True)
|
||||
with self.assertRaisesRegex(ValueError, "different admissions"): b.signed_states(self.policy, root, env)
|
||||
finally:
|
||||
self.root = original
|
||||
|
||||
def test_combined_release_carries_every_platform_and_round_trips_as_history(self):
|
||||
state, packet = self.publication_fixture(); api = self.publication_api()
|
||||
result = b.publish(self.policy, state, self.root/"combined", packet, self.root/"ownership", api, lambda: True, self.registry)
|
||||
self.assertEqual(result["id"], 7)
|
||||
feed = json.loads((packet/"NIGHTLY.json").read_text())
|
||||
self.assertEqual(feed["schema"], "craft-nightly/v2")
|
||||
self.assertEqual(sorted(row["target"]["os"] for row in feed["artifacts"]), ["linux", "macos", "windows"])
|
||||
linux = self.plan["platforms"][LINUX]["asset"]
|
||||
self.assertEqual([row["signature"]["name"] for row in feed["artifacts"] if row["target"]["os"] == "linux"], [linux+".asc"])
|
||||
self.assertEqual(sorted(name for _, name, _ in [w for w in api.writes if w[0] == "UPLOAD"]),
|
||||
sorted([self.plan["platforms"][MAC]["asset"], self.plan["platforms"][WINDOWS]["asset"], linux, linux+".asc",
|
||||
"NIGHTLY.json", "SHA256SUMS.txt"]))
|
||||
self.assertIn(b.MARKER_V2, api.release["body"]); self.assertNotIn(b.MARKER, api.release["body"])
|
||||
prior = b.previous_publication(api, self.registry, self.policy, self.request, [api.release])
|
||||
self.assertEqual(prior["identity"], self.plan["identity"])
|
||||
# A substituted macOS public asset digest invalidates the whole history entry.
|
||||
for asset in api.assets:
|
||||
if asset["name"] == self.plan["platforms"][MAC]["asset"]: asset["digest"] = "sha256:"+"0"*64
|
||||
with self.assertRaisesRegex(ValueError, "final asset digest"):
|
||||
b.previous_publication(api, self.registry, self.policy, self.request, [api.release])
|
||||
|
||||
def test_live_v2_history_requires_the_linux_detached_signature(self):
|
||||
# A receipt that simply omits Linux support must not authenticate history (the feed requires the .asc).
|
||||
api, release = self.history(live=True, missing_signature=True)
|
||||
with self.assertRaisesRegex(ValueError, "support"):
|
||||
b.previous_publication(api, self.registry, self.policy, self.request, [release])
|
||||
|
||||
def test_live_v2_history_requires_v3_policy_and_exact_receipts(self):
|
||||
api, release = self.history(live=True)
|
||||
self.assertEqual(b.previous_publication(api, self.registry, self.policy, self.request, [release])["identity"], self.plan["identity"])
|
||||
publication = json.loads(release["body"].split(b.MARKER_V2, 1)[1])
|
||||
for mutate in (lambda pub: pub["signing"][MAC].update(verified_signer="OTHER12345"),
|
||||
lambda pub: pub["signing"].pop(MAC),
|
||||
lambda pub: pub["signing"][MAC].update(method="authenticode")):
|
||||
changed = copy.deepcopy(publication); mutate(changed)
|
||||
bad = {**release, "body": b.MARKER_V2+json.dumps(changed)}
|
||||
with self.subTest(mutate=mutate), self.assertRaises(ValueError):
|
||||
b.previous_publication(api, self.registry, self.policy, self.request, [bad])
|
||||
both = {**release, "body": release["body"]+b.MARKER}
|
||||
with self.assertRaisesRegex(ValueError, "ambiguous"):
|
||||
b.previous_publication(api, self.registry, self.policy, self.request, [both])
|
||||
|
||||
|
||||
if __name__ == "__main__": unittest.main()
|
||||
@@ -0,0 +1,171 @@
|
||||
"""End-to-end three-platform release-ref run on synthetic provider data.
|
||||
|
||||
Drives Windows, Linux and macOS through admission, per-platform download layout,
|
||||
validation (fake gh verifier), signing (faked Windows/macOS native signers, REAL
|
||||
GnuPG for Linux with a throwaway key), fresh per-platform verification, the
|
||||
publisher's final checks, combined publication and the next night's history check.
|
||||
It exists to catch "this can never succeed" integration gaps between jobs.
|
||||
Not a hosted run, a production signature or Launcher proof.
|
||||
"""
|
||||
import io
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import sys
|
||||
import tarfile
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT/'scripts')); sys.path.insert(0, str(ROOT/'tests'))
|
||||
import test_nightly_release as bridge
|
||||
import test_nightly_release_linux as gnupg
|
||||
b = bridge.b
|
||||
WINDOWS, MAC, LINUX = bridge.WINDOWS, bridge.MAC, bridge.LINUX
|
||||
SUBJECT, TEAM = "CN=Synthetic fixture only", "SYNTH12345"
|
||||
LARGE = 3*b.n.MAX_JSON_BYTES # Comfortably above the metadata bound.
|
||||
|
||||
|
||||
@unittest.skipUnless(Path(gnupg.GPG).exists(), 'GnuPG is required for the real Linux route')
|
||||
class ThreePlatformRunTests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.keys = tempfile.TemporaryDirectory(prefix='nightly-e2e-keys-')
|
||||
cls.fingerprint, cls.public, cls.secret = gnupg.make_key(Path(cls.keys.name)/'release', 'fixture-release')
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
gnupg.stop_agents(Path(cls.keys.name)); cls.keys.cleanup()
|
||||
|
||||
def setUp(self):
|
||||
self.bt = bridge.BridgeTests('test_plan_names_every_admitted_platform_and_refuses_unreviewed_rows')
|
||||
self.bt.setUp(); self.addCleanup(self.bt.doCleanups)
|
||||
bt = self.bt
|
||||
# The reviewed Linux trust is the throwaway key; rebind the request/plan to that policy.
|
||||
bt.fx.policy['platforms'][LINUX]['trust']['fingerprint'] = self.fingerprint
|
||||
bt.policy = bt.fx.policy; bt.request = bt.fx.invoke()
|
||||
bt.plan = b.identity_plan(bt.registry, bt.request['producer'], bt.plan['stable_base'])
|
||||
bt.state = {'request': bt.request, 'quality': bt.state['quality'], 'plan': bt.plan}
|
||||
self.root = bt.root
|
||||
patch.dict(os.environ, {'GITHUB_WORKSPACE': str(ROOT), 'RUNNER_TEMP': str(self.root)}).start()
|
||||
patch.object(b.plat.signing, 'command', side_effect=gnupg.real_command).start()
|
||||
patch.object(b.plat.signing.subprocess, 'run', side_effect=gnupg.real_run).start()
|
||||
self.source = self.root/'release-source'; (self.source/'.github').mkdir(parents=True)
|
||||
(self.source/'.github/nightly-linux-signing-key.asc').write_bytes(self.public)
|
||||
self.env = {**bt.env, 'RUNNER_TEMP': str(self.root), 'PATH': os.environ.get('PATH', '')}
|
||||
|
||||
def downloaded(self):
|
||||
"""The validate job's layout: one exact directory per admitted platform under .unsigned."""
|
||||
root = self.root/'unsigned'; root.mkdir()
|
||||
for platform, names in self.bt.plan['platforms'].items():
|
||||
directory = root/platform; directory.mkdir()
|
||||
if platform == LINUX:
|
||||
with tarfile.open(directory/names['unsigned_asset'], 'w:gz') as out:
|
||||
# Real nightlies are megabytes: an incompressible member keeps the archive well above
|
||||
# the 256 KiB metadata bound, generated here and never committed.
|
||||
for name, data in (('photocraft', gnupg.ELF), ('LICENSE', b'synthetic notice'),
|
||||
('resources/payload.bin', os.urandom(LARGE))):
|
||||
member = tarfile.TarInfo(name); member.mode = 0o755; member.size = len(data)
|
||||
out.addfile(member, io.BytesIO(data))
|
||||
else:
|
||||
(directory/names['unsigned_asset']).write_bytes(b'synthetic unsigned '+platform.encode())
|
||||
digest = b.n.digest_file(directory, names['unsigned_asset'])[1]
|
||||
b.write_json(directory/'unsigned.json', b.unsigned_manifest(self.bt.plan, self.bt.request['producer'], platform, digest))
|
||||
return root
|
||||
|
||||
def test_windows_linux_and_macos_run_end_to_end_and_round_trip_as_history(self):
|
||||
bt, policy = self.bt, self.bt.policy
|
||||
platforms = b.r.policy_platforms(policy)
|
||||
self.assertEqual(platforms, [LINUX, MAC, WINDOWS])
|
||||
# validate: every admitted platform was downloaded into its own directory.
|
||||
directories = b.platform_directories(self.downloaded(), platforms)
|
||||
linux_unsigned = directories[LINUX]/bt.plan['platforms'][LINUX]['unsigned_asset']
|
||||
self.assertGreater(linux_unsigned.stat().st_size, b.n.MAX_JSON_BYTES)
|
||||
manifests, claims = {}, {}
|
||||
for platform, directory in directories.items():
|
||||
(manifests[platform], claims[platform]), _ = bt.verified(directory, platform=platform)
|
||||
validated = self.root/'validated'
|
||||
bundle_digest = b.stage_bundle(validated, bt.state, directories, manifests, claims)
|
||||
state = b.verify_bundle(validated, bundle_digest, b.validated_names(bt.plan))
|
||||
# sign: one protected job per platform, each with only its own secret.
|
||||
signed_root = self.root/'signed'; signed_root.mkdir()
|
||||
publish_env = {'RUNNER_TEMP': str(self.root)}
|
||||
def windows_native(source, archive, output, env, version):
|
||||
Path(output).write_bytes(b'synthetic Authenticode-signed ZIP'); return SUBJECT
|
||||
def mac_native(trust, unsigned, output, source, environment, version):
|
||||
(Path(output)/bt.plan['platforms'][MAC]['asset']).write_bytes(b'synthetic notarized app ZIP')
|
||||
return {'verified_signer': TEAM, 'support': {}}
|
||||
with patch.object(b.plat.signing, 'adapter'), patch.object(b.plat.signing, 'require_config'), \
|
||||
patch.object(b.plat.signing, 'sign_windows', side_effect=windows_native), \
|
||||
patch.object(b.plat.WINDOWS, 'verify', return_value=SUBJECT), \
|
||||
patch.object(b.plat.plugin(MAC), 'sign', side_effect=mac_native):
|
||||
for platform, secrets in ((WINDOWS, {'WINDOWS_CERTIFICATE': 'synthetic', 'WINDOWS_CERTIFICATE_PASSWORD': 'synthetic'}),
|
||||
(MAC, {'APPLE_CERTIFICATE': 'synthetic'}),
|
||||
(LINUX, {'LINUX_SIGNING_KEY': self.secret})):
|
||||
digest = b.native_sign(policy, state, platform, validated, self.source, signed_root/platform, {**self.env, **secrets})
|
||||
publish_env['SIGNED_BUNDLE_SHA256_'+b.plat.secret_key(platform)] = digest
|
||||
# verify-<os>: fresh keyless verifiers for Linux (real gpgv route) and macOS (faked native tools).
|
||||
for platform in (LINUX, MAC):
|
||||
signed_state = b.verify_signed_bundle(signed_root/platform, publish_env['SIGNED_BUNDLE_SHA256_'+b.plat.secret_key(platform)], platform)
|
||||
with patch.object(b.plat.plugin(MAC), 'verify', return_value=TEAM):
|
||||
final = b.verify_platform(policy, signed_state, platform, signed_root/platform, self.source, self.env)
|
||||
publish_env['VERIFIED_FINAL_SHA256_'+b.plat.secret_key(platform)] = final
|
||||
# publish: shared admission, native Windows check, fresh verifier digests, combined release.
|
||||
shared, signed_dirs = b.signed_states(policy, signed_root, publish_env)
|
||||
self.assertEqual(sorted(shared['signing']), [LINUX, MAC, WINDOWS])
|
||||
with patch.object(b.plat.WINDOWS, 'verify', return_value=SUBJECT):
|
||||
self.assertTrue(b.verify_final(policy, shared, signed_dirs, self.source, {**self.env, **publish_env}))
|
||||
combined = b.combine(shared, signed_dirs, self.root/'combined')
|
||||
linux_asset = bt.plan['platforms'][LINUX]['asset']
|
||||
self.assertEqual(sorted(path.name for path in combined.iterdir()),
|
||||
sorted([bt.plan['platforms'][WINDOWS]['asset'], bt.plan['platforms'][MAC]['asset'], linux_asset, linux_asset+'.asc']))
|
||||
api = bt.publication_api()
|
||||
result = b.publish(policy, shared, combined, self.root/'packet', self.root/'ownership', api, lambda: True, bt.registry)
|
||||
self.assertEqual(result['id'], 7)
|
||||
uploads = sorted(name for kind, name, _ in api.writes if kind == 'UPLOAD')
|
||||
self.assertIn(linux_asset+'.asc', uploads)
|
||||
# The next night authenticates this release as history, including the Linux detached signature.
|
||||
prior = b.previous_publication(api, bt.registry, policy, bt.request, [api.release])
|
||||
self.assertEqual(prior['identity'], bt.plan['identity'])
|
||||
api.assets[:] = [asset for asset in api.assets if asset['name'] != linux_asset+'.asc']
|
||||
with self.assertRaises(ValueError):
|
||||
b.previous_publication(api, bt.registry, policy, bt.request, [api.release])
|
||||
|
||||
|
||||
|
||||
class BundleBoundTests(unittest.TestCase):
|
||||
"""Payload archives keep the asset/aggregate bounds; only explicit metadata gets the JSON bound."""
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory(); self.addCleanup(self.temp.cleanup)
|
||||
self.root = Path(self.temp.name).resolve()
|
||||
patch.dict(os.environ, {'GITHUB_WORKSPACE': str(self.root), 'RUNNER_TEMP': str(self.root)}).start()
|
||||
self.addCleanup(patch.stopall)
|
||||
|
||||
def test_large_linux_and_macos_payloads_pass_but_large_metadata_refuses(self):
|
||||
names = {'photocraft-1.2.3-nightly.20261122.100.1.gaaaaaaaaaaaa-linux-x86_64-nightly.unsigned.tar.gz',
|
||||
'photocraft-1.2.3-nightly.20261122.100.1.gaaaaaaaaaaaa-macos-aarch64-nightly.unsigned.zip', 'unsigned.json'}
|
||||
for name in names:
|
||||
(self.root/name).write_bytes(os.urandom(LARGE) if not name.endswith('.json') else b'{}')
|
||||
listed = b.finite_files(self.root, names)
|
||||
self.assertTrue(all(listed[name]['size'] == LARGE for name in names if not name.endswith('.json')))
|
||||
(self.root/'unsigned.json').write_bytes(b' '*(b.n.MAX_JSON_BYTES+1))
|
||||
with self.assertRaisesRegex(ValueError, 'oversized bundle metadata'):
|
||||
b.finite_files(self.root, names)
|
||||
(self.root/'unsigned.json').write_bytes(b'{}'); (self.root/'extra.bin').write_bytes(b'x')
|
||||
with self.assertRaisesRegex(ValueError, 'unexpected bundle file'):
|
||||
b.finite_files(self.root, names)
|
||||
(self.root/'extra.bin').unlink()
|
||||
with patch.object(b.n, 'MAX_TOTAL_BYTES', 2*LARGE), self.assertRaisesRegex(ValueError, 'aggregate bundle bound'):
|
||||
b.finite_files(self.root, names)
|
||||
|
||||
def test_signed_linux_bundle_with_large_tarball_hashes(self):
|
||||
asset = 'photocraft-1.2.3-nightly.20261122.100.1.gaaaaaaaaaaaa-linux-x86_64-nightly.tar.gz'
|
||||
(self.root/asset).write_bytes(os.urandom(LARGE)); (self.root/(asset+'.asc')).write_bytes(bridge.SYNTHETIC_ASC)
|
||||
for name in b.BUNDLE_FILES | {'signing.json'}:
|
||||
(self.root/name).write_bytes(b'{}')
|
||||
self.assertRegex(b.bundle_hash(self.root, {asset, asset+'.asc'}, signed=True), '^[0-9a-f]{64}$')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,550 @@
|
||||
"""Linux release-ref plug-in with REAL GnuPG and throwaway keys; no production credentials.
|
||||
|
||||
Keys are generated per test run (certify-only ed25519 primary plus a signing
|
||||
subkey, the stable key's shape). The stable public key and one stable signature
|
||||
are public fixtures. gpgv is used when installed; otherwise the exact gpgv call is
|
||||
translated to `gpg --verify` with the same isolated keyring and status output.
|
||||
"""
|
||||
import copy
|
||||
import io
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shutil
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import tarfile
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT/'scripts'))
|
||||
import nightly_feed as n
|
||||
import nightly_signing as s
|
||||
import nightly_release_linux as linux
|
||||
|
||||
RUN = subprocess.run # s.subprocess is this module: keep the real one before patching.
|
||||
GPG = shutil.which('gpg') or '/usr/bin/gpg'
|
||||
GPGV = shutil.which('gpgv')
|
||||
STABLE = ROOT/'tests/fixtures/photocraft-stable-linux-openpgp'
|
||||
STABLE_FINGERPRINT = '2B76741B414AAD6CD33E631213A005C0B9D7C3ED'
|
||||
VERSION = '0.23.1-nightly.20261120.1234.1.gaaaaaaaaaaaa'
|
||||
ELF = b'\x7fELF\x02\x01\x01' + b'\x00'*9 + struct.pack('<HHI', 2, 62, 1) + b'\x00'*40
|
||||
|
||||
|
||||
def real_command(argv, *, stdin=None, env=None):
|
||||
"""The production allowlist and bounds, with gpg/gpgv mapped to this host's binaries."""
|
||||
arguments = [str(value.absolute()) if isinstance(value, Path) else str(value) for value in argv]
|
||||
assert arguments[0] in ('/usr/bin/gpg', '/usr/bin/gpgv', '/usr/bin/gpgconf'), arguments[0]
|
||||
if arguments[0] == '/usr/bin/gpgconf':
|
||||
arguments[0] = shutil.which('gpgconf') or '/usr/bin/gpgconf'
|
||||
elif arguments[0] == '/usr/bin/gpgv' and GPGV is None:
|
||||
rest = arguments[1:]
|
||||
homedir = rest[rest.index('--homedir')+1]; keyring = rest[rest.index('--keyring')+1]
|
||||
signature, payload = rest[-2:]
|
||||
arguments = [GPG, '--homedir', homedir, '--batch', '--no-default-keyring', '--keyring', keyring,
|
||||
'--trust-model', 'always', '--status-fd', '1', '--verify', signature, payload]
|
||||
elif arguments[0] in ('/usr/bin/gpg', '/usr/bin/gpgv'):
|
||||
arguments[0] = GPGV if arguments[0] == '/usr/bin/gpgv' else GPG
|
||||
result = RUN(arguments, input=stdin, env=env, check=True, stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE, timeout=120)
|
||||
return result.stdout.decode('utf-8-sig').strip()
|
||||
|
||||
|
||||
def real_run(argv, **kwargs):
|
||||
argv = [GPG if str(argv[0]) == '/usr/bin/gpg' else argv[0], *argv[1:]]
|
||||
return RUN(argv, **kwargs)
|
||||
|
||||
|
||||
def gpg(homedir, *arguments, stdin=None):
|
||||
return RUN([GPG, '--homedir', str(homedir), '--batch', *arguments], input=stdin, check=True,
|
||||
stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=120).stdout
|
||||
|
||||
|
||||
def agent_lines():
|
||||
"""Full gpg-agent command lines: Linux procps needs -af; macOS/BSD pgrep needs -fl (-a means ancestors there)."""
|
||||
flag = '-fl' if sys.platform == 'darwin' or 'bsd' in sys.platform else '-af'
|
||||
return RUN(['pgrep', flag, 'gpg-agent'], capture_output=True, text=True).stdout
|
||||
|
||||
|
||||
def stop_agents(root):
|
||||
"""Stop every test gpg-agent under root; QA cannot retire hosts with unknown agents running."""
|
||||
for home in Path(root).iterdir():
|
||||
RUN(['gpgconf', '--homedir', str(home), '--kill', 'all'], check=False, capture_output=True)
|
||||
import signal, time
|
||||
for _ in range(50):
|
||||
pids = [int(line.split()[0]) for line in agent_lines().splitlines() if str(root) in line]
|
||||
if not pids:
|
||||
return
|
||||
for pid in pids:
|
||||
try: os.kill(pid, signal.SIGTERM)
|
||||
except ProcessLookupError: pass
|
||||
time.sleep(0.1)
|
||||
|
||||
|
||||
def make_key(homedir, name):
|
||||
homedir.mkdir(mode=0o700)
|
||||
gpg(homedir, '--passphrase', '', '--pinentry-mode', 'loopback', '--quick-gen-key', name+' <'+name+'@example.invalid>', 'ed25519', 'cert', 'never')
|
||||
listing = gpg(homedir, '--with-colons', '--list-keys').decode()
|
||||
primary = [line.split(':')[9] for line in listing.splitlines() if line.startswith('fpr:')][0]
|
||||
gpg(homedir, '--passphrase', '', '--pinentry-mode', 'loopback', '--quick-add-key', primary, 'ed25519', 'sign', 'never')
|
||||
return primary, gpg(homedir, '--armor', '--export', primary), gpg(homedir, '--armor', '--export-secret-keys', primary).decode()
|
||||
|
||||
|
||||
@unittest.skipUnless(Path(GPG).exists(), 'GnuPG is required for the real OpenPGP route')
|
||||
class LinuxReleasePluginTests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.keys = tempfile.TemporaryDirectory(prefix='nightly-keys-')
|
||||
root = Path(cls.keys.name)
|
||||
cls.fingerprint, cls.public, cls.secret = make_key(root/'reviewed', 'fixture-release')
|
||||
cls.other_fingerprint, cls.other_public, cls.other_secret = make_key(root/'attacker', 'fixture-attacker')
|
||||
cls.attacker_home = root/'attacker'
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
stop_agents(Path(cls.keys.name))
|
||||
cls.keys.cleanup()
|
||||
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory(prefix='nightly-linux-'); self.addCleanup(self.temp.cleanup)
|
||||
self.root = Path(self.temp.name).resolve()
|
||||
owned = patch.dict(os.environ, {'GITHUB_WORKSPACE': str(ROOT), 'RUNNER_TEMP': str(self.root)})
|
||||
owned.start(); self.addCleanup(owned.stop)
|
||||
for target, replacement in ((s, 'command'),):
|
||||
patcher = patch.object(target, replacement, side_effect=real_command); patcher.start(); self.addCleanup(patcher.stop)
|
||||
patcher = patch.object(s.subprocess, 'run', side_effect=real_run); patcher.start(); self.addCleanup(patcher.stop)
|
||||
self.source = self.root/'release-source'; (self.source/'.github').mkdir(parents=True)
|
||||
(self.source/linux.PUBLIC_KEY).write_bytes(self.public)
|
||||
self.names = linux.assets(VERSION)
|
||||
self.trust = {'fingerprint': self.fingerprint}
|
||||
self.env = {'RUNNER_TEMP': str(self.root), 'PATH': os.environ.get('PATH', ''), 'LINUX_SIGNING_KEY': self.secret}
|
||||
|
||||
def tar(self, rows=None):
|
||||
path = self.root/self.names['unsigned_asset']
|
||||
with tarfile.open(path, 'w:gz') as out:
|
||||
for name, data, kind in rows or [('photocraft', ELF, 'file'), ('LICENSE', b'synthetic notice', 'file')]:
|
||||
member = tarfile.TarInfo(name); member.mode = 0o755
|
||||
if kind == 'link':
|
||||
member.type = tarfile.SYMTYPE; member.linkname = 'photocraft'; out.addfile(member)
|
||||
else:
|
||||
member.size = len(data); out.addfile(member, io.BytesIO(data))
|
||||
return path
|
||||
|
||||
def signed(self):
|
||||
unsigned = self.tar(); output = self.root/'signed'; output.mkdir()
|
||||
result = linux.sign(self.trust, unsigned, output, self.source, self.env, VERSION)
|
||||
return unsigned, output, result
|
||||
|
||||
def keyless(self):
|
||||
return {key: value for key, value in self.env.items() if key != 'LINUX_SIGNING_KEY'}
|
||||
|
||||
def test_trust_is_exact_full_uppercase_primary_fingerprint(self):
|
||||
self.assertEqual(linux.validate_trust({'fingerprint': STABLE_FINGERPRINT}), {'fingerprint': STABLE_FINGERPRINT})
|
||||
for bad in ({}, {'fingerprint': STABLE_FINGERPRINT.lower()}, {'fingerprint': STABLE_FINGERPRINT[-16:]},
|
||||
{'fingerprint': STABLE_FINGERPRINT, 'subkey': 'x'}, {'fingerprint': ' '+STABLE_FINGERPRINT}, [STABLE_FINGERPRINT]):
|
||||
with self.subTest(trust=bad), self.assertRaises(n.InvalidNightly): linux.validate_trust(bad)
|
||||
|
||||
def test_assets_follow_the_owner_contract_and_unsigned_handoff_name(self):
|
||||
self.assertEqual(self.names, {'asset': 'photocraft-'+VERSION+'-linux-x86_64-nightly.tar.gz',
|
||||
'built_asset': 'photocraft-'+VERSION+'-linux-x86_64-nightly.tar.gz',
|
||||
'unsigned_asset': 'photocraft-'+VERSION+'-linux-x86_64-nightly.unsigned.tar.gz'})
|
||||
for bad in ('0.23.1', '0.23.1-nightly.20261120.1234.1.gAAAAAAAAAAAA', '../0.23.1-nightly.20261120.1234.1.gaaaaaaaaaaaa'):
|
||||
with self.subTest(version=bad), self.assertRaises(n.InvalidNightly): linux.assets(bad)
|
||||
self.assertEqual(linux.TARGET, {'os': 'linux', 'arch': 'x86_64', 'format': 'tar_gz'})
|
||||
self.assertTrue(linux.BYTES_MAY_BE_UNCHANGED); self.assertEqual(linux.METHOD, 'openpgp-detached')
|
||||
|
||||
def test_real_sign_then_keyless_verify_binds_subkey_signature_to_reviewed_primary(self):
|
||||
unsigned, output, result = self.signed()
|
||||
asset = self.names['asset']
|
||||
self.assertEqual(result['verified_signer'], self.fingerprint)
|
||||
self.assertEqual(set(result['support']), {asset+'.asc'}) # Only published support; trust is reviewed source.
|
||||
self.assertEqual(sorted(path.name for path in output.iterdir()), sorted([asset, asset+'.asc']))
|
||||
self.assertEqual((output/asset).read_bytes(), unsigned.read_bytes()) # Detached: tar.gz bytes unchanged.
|
||||
status = gpg(self.attacker_home.parent/'reviewed', '--status-fd', '1', '--verify', str(output/(asset+'.asc')), str(output/asset)).decode()
|
||||
valid = [line.split() for line in status.splitlines() if line.startswith('[GNUPG:] VALIDSIG')][0]
|
||||
self.assertNotEqual(valid[2], self.fingerprint); self.assertEqual(valid[-1], self.fingerprint) # subkey signed, primary bound
|
||||
self.assertNotIn(self.secret.encode(), b''.join(path.read_bytes() for path in output.iterdir()))
|
||||
self.assertNotIn(b'PRIVATE KEY', b''.join(path.read_bytes() for path in output.iterdir()))
|
||||
self.assertEqual(linux.verify(self.trust, output, asset, result['support'], self.source, self.keyless(), VERSION), self.fingerprint)
|
||||
self.assertFalse([path for path in self.root.iterdir() if path.name.startswith(('nightly-gpg', 'nightly-linux-stage'))])
|
||||
import time
|
||||
for _ in range(30): # gpgconf --kill is asynchronous; allow up to 3 s, never kill here.
|
||||
agents = agent_lines()
|
||||
if str(self.root) not in agents: break
|
||||
time.sleep(0.1)
|
||||
self.assertNotIn(str(self.root), agents) # No agent (possibly holding the key) outlives signing.
|
||||
|
||||
def test_gpg_never_receives_tokens_or_other_platform_credentials(self):
|
||||
seen = []
|
||||
def spy(argv, **kwargs):
|
||||
seen.append(dict(kwargs.get('env') or {}))
|
||||
return real_command(argv, **kwargs)
|
||||
unsigned = self.tar(); output = self.root/'signed'; output.mkdir()
|
||||
env = {**self.env, 'GH_TOKEN': 'synthetic-token', 'WINDOWS_CERTIFICATE': 'synthetic', 'APPLE_PASSWORD': 'synthetic'}
|
||||
with patch.object(s, 'command', side_effect=spy):
|
||||
linux.sign(self.trust, unsigned, output, self.source, env, VERSION)
|
||||
self.assertTrue(seen)
|
||||
for item in seen:
|
||||
self.assertFalse({'GH_TOKEN', 'WINDOWS_CERTIFICATE', 'APPLE_PASSWORD'} & set(item))
|
||||
|
||||
def test_agent_listing_includes_full_command_lines(self):
|
||||
home = self.root/'listing-home'; home.mkdir(mode=0o700)
|
||||
try:
|
||||
gpg(home, '--list-keys')
|
||||
RUN(['gpg-connect-agent', '--homedir', str(home), '/bye'], capture_output=True, check=False)
|
||||
self.assertIn(str(home), agent_lines()) # Otherwise a surviving agent could never fail the check.
|
||||
finally:
|
||||
stop_agents(self.root)
|
||||
|
||||
def test_verify_refuses_signing_credentials_in_its_environment(self):
|
||||
_, output, result = self.signed()
|
||||
with self.assertRaisesRegex(n.InvalidNightly, 'without signing credentials'):
|
||||
linux.verify(self.trust, output, self.names['asset'], result['support'], self.source, self.env, VERSION)
|
||||
|
||||
def test_tampered_payload_or_signature_is_refused(self):
|
||||
_, output, result = self.signed(); asset = self.names['asset']
|
||||
original = (output/asset).read_bytes()
|
||||
with tarfile.open(output/asset, 'w:gz') as out:
|
||||
for name, data in (('photocraft', ELF+b'\x00'), ('LICENSE', b'synthetic notice')):
|
||||
member = tarfile.TarInfo(name); member.mode = 0o755; member.size = len(data); out.addfile(member, io.BytesIO(data))
|
||||
with self.assertRaises((n.InvalidNightly, subprocess.CalledProcessError)):
|
||||
linux.verify(self.trust, output, asset, result['support'], self.source, self.keyless(), VERSION)
|
||||
(output/asset).write_bytes(original)
|
||||
signature = (output/(asset+'.asc')).read_bytes()
|
||||
(output/(asset+'.asc')).write_bytes(signature.replace(b'\n=', b'\n=A', 1) if b'\n=' in signature else signature[:-40]+signature[-39:])
|
||||
support = {**result['support'], asset+'.asc': {'size': (output/(asset+'.asc')).stat().st_size, 'sha256': s.sha(output/(asset+'.asc'))}}
|
||||
with self.assertRaises((n.InvalidNightly, subprocess.CalledProcessError)):
|
||||
linux.verify(self.trust, output, asset, support, self.source, self.keyless(), VERSION)
|
||||
|
||||
def test_valid_signature_by_another_key_is_refused_even_if_bytes_are_rebound(self):
|
||||
_, output, result = self.signed(); asset = self.names['asset']
|
||||
signature = output/(asset+'.asc'); signature.unlink()
|
||||
gpg(self.attacker_home, '--armor', '--detach-sign', '-o', str(signature), str(output/asset))
|
||||
support = {**result['support'], asset+'.asc': {'size': signature.stat().st_size, 'sha256': s.sha(signature)}}
|
||||
with self.assertRaises((n.InvalidNightly, subprocess.CalledProcessError)):
|
||||
linux.verify(self.trust, output, asset, support, self.source, self.keyless(), VERSION)
|
||||
|
||||
def test_in_release_key_export_is_not_shipped_or_accepted_as_trust(self):
|
||||
_, output, result = self.signed(); asset = self.names['asset']
|
||||
(output/'release-signing-key.asc').write_bytes(self.other_public)
|
||||
with patch.object(s, 'command', side_effect=AssertionError('no tools for an unexpected inventory')), \
|
||||
self.assertRaisesRegex(n.InvalidNightly, 'unexpected signed Linux inventory'):
|
||||
linux.verify(self.trust, output, asset, result['support'], self.source, self.keyless(), VERSION)
|
||||
support = {**result['support'], 'release-signing-key.asc': {'size': len(self.other_public), 'sha256': s.sha(output/'release-signing-key.asc')}}
|
||||
with self.assertRaises(n.InvalidNightly):
|
||||
linux.verify(self.trust, output, asset, support, self.source, self.keyless(), VERSION)
|
||||
|
||||
def test_support_bindings_inventory_and_size_are_exact(self):
|
||||
_, output, result = self.signed(); asset = self.names['asset']
|
||||
for name in (asset+'.asc',):
|
||||
support = copy.deepcopy(result['support']); support[name]['sha256'] = '0'*64
|
||||
with self.subTest(name=name), patch.object(s, 'command', side_effect=AssertionError('no tools before binding')), \
|
||||
self.assertRaisesRegex(n.InvalidNightly, 'support differs'):
|
||||
linux.verify(self.trust, output, asset, support, self.source, self.keyless(), VERSION)
|
||||
with self.assertRaisesRegex(n.InvalidNightly, 'support inventory'):
|
||||
linux.verify(self.trust, output, asset, {}, self.source, self.keyless(), VERSION)
|
||||
(output/'extra.txt').write_text('x')
|
||||
with self.assertRaisesRegex(n.InvalidNightly, 'unexpected signed Linux inventory'):
|
||||
linux.verify(self.trust, output, asset, result['support'], self.source, self.keyless(), VERSION)
|
||||
|
||||
def test_trust_fingerprint_must_match_the_reviewed_source_key(self):
|
||||
unsigned = self.tar(); output = self.root/'signed'; output.mkdir()
|
||||
with self.assertRaisesRegex(n.InvalidNightly, 'reviewed public key/fingerprint'):
|
||||
linux.sign({'fingerprint': self.other_fingerprint}, unsigned, output, self.source, self.env, VERSION)
|
||||
self.assertEqual(list(output.iterdir()), [])
|
||||
(self.source/linux.PUBLIC_KEY).write_bytes(self.public+self.other_public) # two primaries: refuse
|
||||
with self.assertRaisesRegex(n.InvalidNightly, 'reviewed public key/fingerprint'):
|
||||
linux.sign(self.trust, unsigned, output, self.source, self.env, VERSION)
|
||||
|
||||
def test_secret_for_another_key_cannot_produce_an_accepted_signature(self):
|
||||
unsigned = self.tar(); output = self.root/'signed'; output.mkdir()
|
||||
with self.assertRaises((n.InvalidNightly, subprocess.CalledProcessError)):
|
||||
linux.sign(self.trust, unsigned, output, self.source, {**self.env, 'LINUX_SIGNING_KEY': self.other_secret}, VERSION)
|
||||
|
||||
def test_missing_secret_or_unsafe_payload_refuses_before_any_key_use(self):
|
||||
unsigned = self.tar(); output = self.root/'signed'; output.mkdir()
|
||||
with patch.object(s, 'command', side_effect=AssertionError('no gpg without the secret')), \
|
||||
self.assertRaisesRegex(n.InvalidNightly, 'LINUX_SIGNING_KEY required'):
|
||||
linux.sign(self.trust, unsigned, output, self.source, self.keyless(), VERSION)
|
||||
for rows in ([('photocraft', ELF, 'file'), ('photocraft-cli', ELF, 'file')],
|
||||
[('photocraft', ELF, 'file'), ('run', b'', 'link')],
|
||||
[('photocraft', b'MZ'+b'\x00'*62, 'file')],
|
||||
[('photocraft', ELF, 'file'), ('install.sh', b'#!/bin/sh', 'file')]):
|
||||
unsigned.unlink(); self.tar(rows)
|
||||
imported = []
|
||||
def guard(argv, **kwargs):
|
||||
if '--import' in [str(a) for a in argv] and kwargs.get('stdin'): imported.append(True)
|
||||
return real_command(argv, **kwargs)
|
||||
with self.subTest(rows=[r[0] for r in rows]), patch.object(s, 'command', side_effect=guard), self.assertRaises(n.InvalidNightly):
|
||||
linux.sign(self.trust, unsigned, output, self.source, self.env, VERSION)
|
||||
self.assertEqual(imported, []); self.assertEqual(list(output.iterdir()), [])
|
||||
|
||||
def test_unsigned_name_and_empty_owned_output_are_required(self):
|
||||
unsigned = self.tar(); output = self.root/'signed'; output.mkdir()
|
||||
renamed = unsigned.with_name(self.names['asset']); unsigned.rename(renamed)
|
||||
with self.assertRaisesRegex(n.InvalidNightly, 'unsigned Linux handoff'):
|
||||
linux.sign(self.trust, renamed, output, self.source, self.env, VERSION)
|
||||
renamed.rename(unsigned); (output/'stale').write_text('x')
|
||||
with self.assertRaisesRegex(n.InvalidNightly, 'empty directory'):
|
||||
linux.sign(self.trust, unsigned, output, self.source, self.env, VERSION)
|
||||
with tempfile.TemporaryDirectory() as outside, self.assertRaises(n.InvalidNightly):
|
||||
linux.sign(self.trust, unsigned, Path(outside), self.source, self.env, VERSION)
|
||||
|
||||
def test_real_stable_key_and_signature_pass_the_same_strict_verifier(self):
|
||||
work = self.root/'stable'; work.mkdir()
|
||||
for name in ('SHA256SUMS.txt', 'SHA256SUMS.txt.asc'): shutil.copyfile(STABLE/name, work/name)
|
||||
self.assertEqual(s.verify_linux_signature(STABLE/'release-signing-key.asc', work/'SHA256SUMS.txt.asc', work/'SHA256SUMS.txt',
|
||||
STABLE_FINGERPRINT, self.keyless()), STABLE_FINGERPRINT)
|
||||
with self.assertRaisesRegex(n.InvalidNightly, 'reviewed public key/fingerprint'):
|
||||
s.verify_linux_signature(STABLE/'release-signing-key.asc', work/'SHA256SUMS.txt.asc', work/'SHA256SUMS.txt',
|
||||
'568DC1F68F8FAECC797F3C7B006DAF6BB0EF334E', self.keyless()) # subkey is not the trust root
|
||||
(work/'SHA256SUMS.txt').write_bytes((STABLE/'SHA256SUMS.txt').read_bytes()+b'\n')
|
||||
with self.assertRaises((n.InvalidNightly, subprocess.CalledProcessError)):
|
||||
s.verify_linux_signature(STABLE/'release-signing-key.asc', work/'SHA256SUMS.txt.asc', work/'SHA256SUMS.txt',
|
||||
STABLE_FINGERPRINT, self.keyless())
|
||||
|
||||
|
||||
class LinuxStatusParserTests(unittest.TestCase):
|
||||
"""gpgv status policy over mocked tool output (the real path is covered above)."""
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory(); self.addCleanup(self.temp.cleanup)
|
||||
self.root = Path(self.temp.name).resolve()
|
||||
owned = patch.dict(os.environ, {'GITHUB_WORKSPACE': str(self.root), 'RUNNER_TEMP': str(self.root)})
|
||||
owned.start(); self.addCleanup(owned.stop)
|
||||
(self.root/'key.asc').write_text('reviewed public fixture')
|
||||
(self.root/'a.tar.gz').write_bytes(b'payload')
|
||||
(self.root/'a.tar.gz.asc').write_text('-----BEGIN PGP SIGNATURE-----\nfixture\n-----END PGP SIGNATURE-----\n')
|
||||
self.fpr = 'C'*40
|
||||
|
||||
def verify(self, status):
|
||||
def fake(argv, **kwargs):
|
||||
if '--list-keys' in argv: return 'pub:-:255:22:X:0:::-:::cSC:\nfpr:::::::::'+self.fpr+':\nsub:-:255:22:Y:0::::::s:\nfpr:::::::::'+'D'*40+':'
|
||||
return status if str(argv[0]) == '/usr/bin/gpgv' else ''
|
||||
completed = subprocess.CompletedProcess(['gpg'], 0, b'binary key', b'')
|
||||
with patch.object(s, 'command', side_effect=fake), patch.object(s.subprocess, 'run', return_value=completed):
|
||||
return s.verify_linux_signature(self.root/'key.asc', self.root/'a.tar.gz.asc', self.root/'a.tar.gz', self.fpr, {'RUNNER_TEMP': str(self.root)})
|
||||
|
||||
def line(self, primary=None, hashalgo='10', sigclass='00'):
|
||||
return '[GNUPG:] VALIDSIG '+'D'*40+' 2026-11-23 1 0 4 0 22 '+hashalgo+' '+sigclass+' '+(primary or self.fpr)
|
||||
|
||||
def test_one_good_sha2_binary_signature_by_the_primary_is_required(self):
|
||||
good = '[GNUPG:] NEWSIG\n[GNUPG:] GOODSIG D fixture\n'+self.line()
|
||||
self.assertEqual(self.verify(good), self.fpr)
|
||||
for bad in (good.replace('GOODSIG', 'EXPKEYSIG'), good+'\n[GNUPG:] REVKEYSIG D fixture',
|
||||
good+'\n[GNUPG:] NEWSIG\n[GNUPG:] GOODSIG D fixture\n'+self.line(),
|
||||
'[GNUPG:] NEWSIG\n[GNUPG:] GOODSIG D fixture\n'+self.line(primary='E'*40),
|
||||
'[GNUPG:] NEWSIG\n[GNUPG:] GOODSIG D fixture\n'+self.line(hashalgo='2'),
|
||||
'[GNUPG:] NEWSIG\n[GNUPG:] GOODSIG D fixture\n'+self.line(sigclass='01'),
|
||||
'[GNUPG:] NEWSIG\n[GNUPG:] GOODSIG D fixture', '', good+'\n[GNUPG:] ERRSIG x'):
|
||||
with self.subTest(status=bad), self.assertRaises(n.InvalidNightly): self.verify(bad)
|
||||
|
||||
def test_signature_shape_and_size_are_checked_before_any_tool(self):
|
||||
for content in (b'not armored', b'-----BEGIN PGP SIGNATURE-----\n'+b'A'*16400+b'\n-----END PGP SIGNATURE-----\n',
|
||||
'-----BEGIN PGP SIGNATURE-----\n\u00e9\n-----END PGP SIGNATURE-----\n'.encode()):
|
||||
(self.root/'a.tar.gz.asc').write_bytes(content)
|
||||
with self.subTest(size=len(content)), patch.object(s, 'command', side_effect=AssertionError('no tool')), \
|
||||
self.assertRaises(n.InvalidNightly):
|
||||
s.verify_linux_signature(self.root/'key.asc', self.root/'a.tar.gz.asc', self.root/'a.tar.gz', self.fpr, {'RUNNER_TEMP': str(self.root)})
|
||||
|
||||
|
||||
def job_block(source, name):
|
||||
tail = source.split('\n '+name+':\n', 1)[1]
|
||||
block = re.split(r'^ [a-z][a-z0-9_-]*:\n', tail, maxsplit=1, flags=re.M)[0]
|
||||
return '\n'.join(line for line in block.splitlines() if not line.lstrip().startswith('#'))+'\n'
|
||||
|
||||
|
||||
def steps(block):
|
||||
return re.split(r'(?=^ - )', block.split(' steps:\n', 1)[1], flags=re.M)[1:]
|
||||
|
||||
|
||||
class LinuxReleaseWorkflowTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.release = (ROOT/'.github/workflows/nightly-release.yml').read_text()
|
||||
self.unsigned = (ROOT/'.github/workflows/nightly-unsigned.yml').read_text()
|
||||
|
||||
def test_linux_secret_reaches_only_the_single_protected_sign_step(self):
|
||||
self.assertEqual(self.release.count('secrets.LINUX_SIGNING_KEY'), 1)
|
||||
sign = job_block(self.release, 'sign-linux')
|
||||
self.assertIn(' environment: release\n', sign)
|
||||
self.assertIn('runs-on: ubuntu-', sign)
|
||||
holders = [step for step in steps(sign) if 'secrets.' in step]
|
||||
self.assertEqual(len(holders), 1)
|
||||
self.assertEqual(re.findall(r'secrets\.([A-Z_]+)', holders[0]), ['LINUX_SIGNING_KEY'])
|
||||
self.assertIn('nightly_release_entry.py sign --platform linux-x86_64', holders[0])
|
||||
ordered = [index for index, step in enumerate(steps(sign)) if 'nightly_release_entry.py guard --platform linux-x86_64' in step]
|
||||
self.assertEqual(len(ordered), 1)
|
||||
self.assertLess(ordered[0], steps(sign).index(holders[0]))
|
||||
self.assertNotIn('secrets: inherit', self.release)
|
||||
for forbidden in ('nightly.sh', 'cargo ', 'packaging/', 'unpack-private', 'nightly_smoke.py', ': write'):
|
||||
self.assertNotIn(forbidden, sign)
|
||||
self.assertEqual(sign.count('persist-credentials: false'), 2)
|
||||
|
||||
def test_linux_jobs_require_admission_platform_and_real_release_dispatch(self):
|
||||
for name in ('sign-linux', 'verify-linux'):
|
||||
condition = job_block(self.release, name).split(' runs-on:', 1)[0]
|
||||
with self.subTest(job=name):
|
||||
self.assertIn("contains(fromJSON(needs.validate.outputs.platforms), 'linux-x86_64')", condition)
|
||||
for fragment in ("github.repository == 'storytold/photocraft'", "github.event_name == 'workflow_dispatch'",
|
||||
"github.ref == 'refs/heads/release'", "github.ref_type == 'branch'"):
|
||||
self.assertIn(fragment, condition)
|
||||
self.assertNotIn('||', condition)
|
||||
self.assertIn("needs.validate.outputs.admitted == 'true'", job_block(self.release, 'sign-linux'))
|
||||
self.assertIn("needs.sign-linux.result == 'success'", job_block(self.release, 'verify-linux'))
|
||||
|
||||
def test_fresh_verifier_is_keyless_and_uses_only_the_exact_signer_artifact(self):
|
||||
verify = job_block(self.release, 'verify-linux')
|
||||
self.assertNotIn('environment:', verify); self.assertNotIn('secrets.', verify); self.assertNotIn(': write', verify)
|
||||
self.assertIn('artifact-ids: ${{ needs.sign-linux.outputs.artifact-id }}', verify)
|
||||
self.assertIn('verify-platform --platform linux-x86_64', verify)
|
||||
self.assertIn('--expected-sha256 "$EXPECTED_BUNDLE_SHA256"', verify)
|
||||
self.assertIn('EXPECTED_BUNDLE_SHA256: ${{ needs.sign-linux.outputs.bundle-sha256 }}', verify)
|
||||
for name in ('sign-linux', 'verify-linux'):
|
||||
block = job_block(self.release, name)
|
||||
self.assertIn("craft-nightly-release-policy/v3", block)
|
||||
self.assertIn("'linux-x86_64' in config['platforms']", block)
|
||||
self.assertIn('ref: ${{ job.workflow_sha }}', block)
|
||||
self.assertIn('test "$(git -C .release-source rev-parse HEAD)" = "$GITHUB_SHA"', block)
|
||||
|
||||
def test_linux_producer_is_opt_in_secretless_and_attested_separately(self):
|
||||
self.assertIn("default: '[\"windows-x86_64\"]'", self.unsigned) # Windows-only callers stay unchanged.
|
||||
build = job_block(self.unsigned, 'build-linux')
|
||||
self.assertIn("contains(fromJSON(needs.select-platforms.outputs.platforms), 'linux-x86_64')", build.split(' runs-on:', 1)[0])
|
||||
self.assertIn("github.ref == 'refs/heads/main'", build.split(' runs-on:', 1)[0])
|
||||
for forbidden in ('secrets.', 'environment:', 'id-token', ': write', 'cache', 'cargo xtask version set', '--skip-build'):
|
||||
self.assertNotIn(forbidden, build)
|
||||
self.assertIn('bash packaging/linux/nightly.sh --arch x86_64', build)
|
||||
self.assertIn('PHOTOCRAFT_BUILD_CHANNEL: nightly-v1', build)
|
||||
self.assertIn('main-plan --platform linux-x86_64', build)
|
||||
self.assertIn('main-seal --platform linux-x86_64', build)
|
||||
self.assertIn('name: nightly-unsigned-linux-x86_64-${{ github.run_id }}-${{ github.run_attempt }}', build)
|
||||
self.assertLess(build.index('unpack-private'), build.index('main-seal'))
|
||||
attest = job_block(self.unsigned, 'attest-linux')
|
||||
self.assertIn('needs: build-linux', attest)
|
||||
self.assertNotIn('ref: ${{ github.sha }}', attest) # No application checkout beside OIDC.
|
||||
self.assertIn('id-token: write', attest); self.assertIn('main-subject --platform linux-x86_64', attest)
|
||||
self.assertIn('EXPECTED_COMPILER_SHA256: ${{ needs.build-linux.outputs.unsigned-sha256 }}', attest)
|
||||
self.assertNotIn('secrets.', self.unsigned)
|
||||
|
||||
def test_publish_requires_both_linux_jobs_and_binds_their_digests(self):
|
||||
publish = job_block(self.release, 'publish')
|
||||
needs = re.search(r' needs: \[([^\]]*)\]', publish).group(1).replace(' ', '').split(',')
|
||||
self.assertIn('sign-linux', needs); self.assertIn('verify-linux', needs)
|
||||
self.assertIn("(!contains(fromJSON(needs.validate.outputs.platforms), 'linux-x86_64') || "
|
||||
"(needs.sign-linux.result == 'success' && needs.verify-linux.result == 'success')) &&", publish)
|
||||
self.assertIn('artifact-ids: ${{ needs.sign-linux.outputs.artifact-id }}', publish)
|
||||
self.assertIn('path: .signed/linux-x86_64', publish)
|
||||
for name in ('SIGNED_BUNDLE_SHA256_LINUX_X86_64: ${{ needs.sign-linux.outputs.bundle-sha256 }}',
|
||||
'VERIFIED_FINAL_SHA256_LINUX_X86_64: ${{ needs.verify-linux.outputs.final-sha256 }}'):
|
||||
self.assertEqual(publish.count(name), 2) # final and publish steps
|
||||
self.assertNotIn('secrets.', publish); self.assertNotIn('environment:', publish)
|
||||
|
||||
|
||||
def test_validator_downloads_every_supported_platform_artifact_exactly(self):
|
||||
validate = job_block(self.release, 'validate')
|
||||
downloads = [step for step in steps(validate) if 'actions/download-artifact@' in step]
|
||||
platforms = ('linux-x86_64', 'macos-aarch64', 'windows-x86_64')
|
||||
self.assertEqual(len(downloads), len(platforms))
|
||||
for platform in platforms:
|
||||
matching = [step for step in downloads if 'path: .unsigned/'+platform+'\n' in step]
|
||||
with self.subTest(platform=platform):
|
||||
self.assertEqual(len(matching), 1)
|
||||
step = matching[0]
|
||||
self.assertIn("if: steps.admit.outputs.admitted == 'true' && contains(fromJSON(steps.admit.outputs.platforms), '"+platform+"')", step)
|
||||
self.assertIn('artifact-ids: ${{ steps.admit.outputs.artifact-id-'+platform+' }}', step)
|
||||
self.assertIn('run-id: ${{ inputs.producer_run_id }}', step)
|
||||
self.assertIn('digest-mismatch: error', step)
|
||||
self.assertLess(validate.index('path: .unsigned/linux-x86_64'), validate.index('nightly_release_entry.py validate'))
|
||||
|
||||
def test_publish_stops_when_the_run_is_cancelled(self):
|
||||
condition = job_block(self.release, 'publish').split(' runs-on:', 1)[0]
|
||||
self.assertNotIn('always()', condition)
|
||||
self.assertIn("!cancelled() && needs.validate.result == 'success'", condition)
|
||||
|
||||
def test_producer_platform_selection_is_validated_once_as_an_exact_list(self):
|
||||
select = job_block(self.unsigned, 'select-platforms')
|
||||
self.assertNotIn('fromJSON(inputs.platforms)', self.unsigned.split(' select-platforms:\n', 1)[1].split(' steps:', 1)[0])
|
||||
for name in ('build', 'attest', 'build-macos', 'attest-macos', 'build-linux', 'attest-linux'):
|
||||
block = job_block(self.unsigned, name).split(' runs-on:', 1)[0]
|
||||
with self.subTest(job=name):
|
||||
self.assertNotIn('fromJSON(inputs.platforms)', block)
|
||||
for name, platform in (('build', 'windows-x86_64'), ('build-macos', 'macos-aarch64'), ('build-linux', 'linux-x86_64')):
|
||||
block = job_block(self.unsigned, name).split(' runs-on:', 1)[0]
|
||||
self.assertIn("contains(fromJSON(needs.select-platforms.outputs.platforms), '"+platform+"')", block)
|
||||
self.assertIn('select-platforms', block.split('needs:', 1)[1].split('\n', 1)[0])
|
||||
script = select.split("python3 -I -B - <<'PY'\n", 1)[1].split(' PY\n', 1)[0]
|
||||
script = '\n'.join(line[10:] for line in script.splitlines())
|
||||
def run_select(value):
|
||||
with tempfile.TemporaryDirectory() as temporary:
|
||||
output = Path(temporary)/'out'
|
||||
result = RUN([sys.executable, '-I', '-B', '-c', script], env={'PLATFORMS': value, 'GITHUB_OUTPUT': str(output),
|
||||
'PATH': os.environ.get('PATH', '')}, capture_output=True, text=True)
|
||||
return result.returncode, output.read_text() if output.exists() else ''
|
||||
self.assertEqual(run_select('["windows-x86_64","linux-x86_64"]'), (0, 'platforms=["linux-x86_64","windows-x86_64"]\n'))
|
||||
self.assertEqual(run_select('["windows-x86_64"]'), (0, 'platforms=["windows-x86_64"]\n'))
|
||||
for bad in ('"not-linux-x86_64"', '"linux-x86_64"', '[]', '["linux-x86_64","linux-x86_64"]', '["freebsd-x86_64"]',
|
||||
'[["linux-x86_64"]]', '{"linux-x86_64": true}', 'linux-x86_64', '["linux-x86_64 "]', '[1]'):
|
||||
with self.subTest(value=bad):
|
||||
code, out = run_select(bad)
|
||||
self.assertNotEqual(code, 0); self.assertEqual(out, '')
|
||||
|
||||
|
||||
class VerificationEnvironmentTests(unittest.TestCase):
|
||||
"""Verification subprocesses get an explicit env with every signing secret and token removed."""
|
||||
SECRETS = {'LINUX_SIGNING_KEY': 'k', 'WINDOWS_CERTIFICATE': 'c', 'WINDOWS_CERTIFICATE_PASSWORD': 'p', 'AZURE_CLIENT_SECRET': 'a',
|
||||
'APPLE_CERTIFICATE': 'm', 'APPLE_PASSWORD': 'q', 'KEYCHAIN_PASSWORD': 'r', 'GH_TOKEN': 't', 'GITHUB_TOKEN': 'u',
|
||||
'ACTIONS_ID_TOKEN_REQUEST_TOKEN': 'v', 'ACTIONS_RUNTIME_TOKEN': 'w'}
|
||||
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory(); self.addCleanup(self.temp.cleanup)
|
||||
self.root = Path(self.temp.name).resolve()
|
||||
patch.dict(os.environ, {**self.SECRETS, 'GITHUB_WORKSPACE': str(self.root), 'RUNNER_TEMP': str(self.root)}).start()
|
||||
self.addCleanup(patch.stopall)
|
||||
self.calls = []
|
||||
|
||||
def fake(self, outputs):
|
||||
def run(argv, **kwargs):
|
||||
self.calls.append((list(map(str, argv)), kwargs.get('env', 'INHERITED')))
|
||||
out = next((value for key, value in outputs.items() if key in ' '.join(map(str, argv))), '')
|
||||
return subprocess.CompletedProcess(argv, 0, out.encode(), b'')
|
||||
return run
|
||||
|
||||
def assert_clean(self):
|
||||
self.assertTrue(self.calls)
|
||||
for argv, env in self.calls:
|
||||
with self.subTest(argv=argv[:2]):
|
||||
self.assertIsInstance(env, dict) # Never inherited from the signer process.
|
||||
self.assertFalse(set(self.SECRETS) & set(env))
|
||||
self.assertEqual(env.get('PATH'), os.environ.get('PATH'))
|
||||
|
||||
def test_windows_native_verification_never_inherits_signing_secrets(self):
|
||||
env = {**os.environ, 'NIGHTLY_WINDOWS_PUBLISHER_SUBJECT': 'CN=Fixture'}
|
||||
with patch.object(s.subprocess, 'run', side_effect=self.fake({'pwsh': 'CN=Fixture'})):
|
||||
self.assertEqual(s.windows_verify(self.root, env, '1.2.3-nightly.20261120.1.1.gaaaaaaaaaaaa'), 'CN=Fixture')
|
||||
self.assert_clean()
|
||||
|
||||
def test_mac_native_verification_never_inherits_signing_secrets(self):
|
||||
details = ('Identifier=ai.storyteller.photocraft.nightly\nAuthority=Developer ID Application: Fixture\nTeamIdentifier=ABCDEFGHIJ\n'
|
||||
'Timestamp=Fixture\nCodeDirectory v=20500 flags=0x10000(runtime) hashes=x\n')
|
||||
verdict = 'app: accepted\nsource=Notarized Developer ID\norigin=Developer ID Application: Fixture (ABCDEFGHIJ)'
|
||||
env = {**os.environ, 'NIGHTLY_APPLE_TEAM_ID': 'ABCDEFGHIJ', 'DEVELOPER_DIR': '/Applications/Xcode.app'}
|
||||
archive = self.root/'mac.zip'; archive.write_bytes(b'synthetic')
|
||||
with patch.object(s.u, 'verify_archive'), patch.object(s.subprocess, 'run', side_effect=self.fake({'lipo': 'arm64', 'codesign -d': details, 'spctl': verdict})):
|
||||
self.assertEqual(s.mac_verify(archive, '1.2.3-nightly.20261120.1.1.gaaaaaaaaaaaa', {}, env, self.root/'payload'), 'ABCDEFGHIJ')
|
||||
self.assert_clean()
|
||||
self.assertTrue(all(env.get('DEVELOPER_DIR') == '/Applications/Xcode.app' for _, env in self.calls))
|
||||
|
||||
def test_linux_signature_verification_never_inherits_signing_secrets(self):
|
||||
fpr = 'C'*40
|
||||
(self.root/'key.asc').write_text('reviewed public fixture'); (self.root/'a.tar.gz').write_bytes(b'payload')
|
||||
(self.root/'a.tar.gz.asc').write_text('-----BEGIN PGP SIGNATURE-----\nfixture\n-----END PGP SIGNATURE-----\n')
|
||||
status = '[GNUPG:] NEWSIG\n[GNUPG:] GOODSIG D fixture\n[GNUPG:] VALIDSIG '+'D'*40+' 2026-11-23 1 0 4 0 22 10 00 '+fpr
|
||||
listing = 'pub:-:255:22:X:0:::-:::cSC:\nfpr:::::::::'+fpr+':'
|
||||
with patch.object(s.subprocess, 'run', side_effect=self.fake({'--list-keys': listing, 'gpgv': status, '--export': 'binary key'})):
|
||||
self.assertEqual(s.verify_linux_signature(self.root/'key.asc', self.root/'a.tar.gz.asc', self.root/'a.tar.gz', fpr, dict(os.environ)), fpr)
|
||||
self.assert_clean()
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,47 @@
|
||||
"""Platform plug-in registry: secret isolation, trust shape and registry binding. Synthetic only."""
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import unittest
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT/"scripts"))
|
||||
import nightly_release_platforms as plat
|
||||
|
||||
|
||||
class PlatformPluginTests(unittest.TestCase):
|
||||
def test_live_registry_admits_exactly_reviewed_plugin_rows(self):
|
||||
registry = json.loads((ROOT/"nightly-apps.json").read_text())
|
||||
platforms = plat.registry_platforms(registry)
|
||||
self.assertIn("windows-x86_64", platforms); self.assertIn("macos-aarch64", platforms)
|
||||
self.assertEqual(platforms, sorted(platforms))
|
||||
|
||||
def test_keyless_strips_every_platform_secret_and_signing_gets_only_its_own(self):
|
||||
env = {name: "x" for name in plat.SECRET_NAMES}; env.update(PATH="/usr/bin", RUNNER_TEMP="/r")
|
||||
self.assertEqual(plat.keyless(env), {"PATH": "/usr/bin", "RUNNER_TEMP": "/r"})
|
||||
apple = plat.credentialed(env, plat.signing.APPLE_SECRETS)
|
||||
self.assertEqual(set(apple) - {"PATH", "RUNNER_TEMP"}, set(plat.signing.APPLE_SECRETS))
|
||||
for name in ("WINDOWS_CERTIFICATE", "AZURE_CLIENT_SECRET", "LINUX_SIGNING_KEY", "GH_TOKEN", "ACTIONS_ID_TOKEN_REQUEST_TOKEN"):
|
||||
self.assertNotIn(name, apple)
|
||||
|
||||
def test_trust_values_are_exact_and_single(self):
|
||||
self.assertEqual(plat.expected_signer("macos-aarch64", {"apple_team_id": "ABCDE12345"}), "ABCDE12345")
|
||||
self.assertEqual(plat.expected_signer("windows-x86_64", {"publisher_subject": "CN=x"}), "CN=x")
|
||||
for platform, trust in (("macos-aarch64", {"apple_team_id": "abcde12345"}), ("macos-aarch64", {"apple_team_id": "ABCDE1234"}),
|
||||
("macos-aarch64", {"apple_team_id": "ABCDE12345", "extra": "x"}), ("macos-aarch64", {}),
|
||||
("windows-x86_64", {"publisher_subject": ""}), ("windows-x86_64", {"publisher_subject": "CN=a\nb"}),
|
||||
("windows-x86_64", {"apple_team_id": "ABCDE12345"}), ("freebsd-x86_64", {"x": "y"})):
|
||||
with self.subTest(platform=platform, trust=trust), self.assertRaises(ValueError):
|
||||
plat.expected_signer(platform, trust)
|
||||
|
||||
def test_asset_names_are_exact_and_distinct(self):
|
||||
version = "1.2.3-nightly.20261123.100.1.gaaaaaaaaaaaa"
|
||||
mac = plat.MACOS.assets(version)
|
||||
self.assertEqual(mac, {"asset": "photocraft-"+version+"-macos-aarch64-nightly.zip",
|
||||
"unsigned_asset": "photocraft-"+version+"-macos-aarch64-nightly.unsigned.zip",
|
||||
"built_asset": "photocraft-"+version+"-macos-aarch64-nightly.zip"})
|
||||
for bad in ("1.2.3", "../1.2.3-nightly.20261123.100.1.gaaaaaaaaaaaa", "1.2.3-nightly.20261123.0.1.gaaaaaaaaaaaa"):
|
||||
with self.subTest(bad=bad), self.assertRaises(ValueError): plat.MACOS.assets(bad)
|
||||
self.assertGreaterEqual(plat.MAC_SIGN_TIMEOUT, 5400)
|
||||
|
||||
|
||||
if __name__ == "__main__": unittest.main()
|
||||
@@ -6,6 +6,9 @@ import unittest
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT/'scripts'))
|
||||
import nightly_release_request as r
|
||||
WINDOWS_KIND = 'nightly-unsigned-windows-x86_64'
|
||||
MAC_KIND = 'nightly-unsigned-macos-aarch64'
|
||||
LINUX_KIND = 'nightly-unsigned-linux-x86_64'
|
||||
|
||||
|
||||
class API:
|
||||
@@ -28,7 +31,7 @@ class API:
|
||||
|
||||
class RequestTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.policy = {'schema': 'craft-nightly-release-policy/v2', 'repository': 'storytold/photocraft',
|
||||
self.policy = {'schema': 'craft-nightly-release-policy/v3', 'repository': 'storytold/photocraft',
|
||||
'repository_id': 123, 'producer_workflow_id': 91,
|
||||
'producer_workflow_path': '.github/workflows/nightly.yml',
|
||||
'producer_tooling_revision': 'b'*40,
|
||||
@@ -36,10 +39,17 @@ class RequestTests(unittest.TestCase):
|
||||
'signer_workflow_path': '.github/workflows/nightly-sign.yml', 'signer_tooling_revision': 'c'*40,
|
||||
# Synthetic dispatcher identity is explicitly reviewed, never implicitly trusted.
|
||||
'release_branch': 'release', 'manual_actors': [],
|
||||
'automatic_signer_actors': ['github-actions[bot]'], 'platform': 'windows-x86_64',
|
||||
'windows_publisher_subject': 'CN=Synthetic fixture only',
|
||||
'automatic_signer_actors': ['github-actions[bot]'],
|
||||
'max_age_seconds': 86400, 'candidate_policy': {'schema': 'craft-nightly-candidate-policy/v3'},
|
||||
'unsigned_artifact_name': 'nightly-unsigned-windows-x86_64', 'max_artifact_bytes': 1000000}
|
||||
'max_artifact_bytes': 1000000,
|
||||
# One release for every admitted platform; synthetic trust values only.
|
||||
'platforms': {
|
||||
'windows-x86_64': {'unsigned_artifact_name': 'nightly-unsigned-windows-x86_64',
|
||||
'trust': {'publisher_subject': 'CN=Synthetic fixture only'}},
|
||||
'macos-aarch64': {'unsigned_artifact_name': 'nightly-unsigned-macos-aarch64',
|
||||
'trust': {'apple_team_id': 'SYNTH12345'}},
|
||||
'linux-x86_64': {'unsigned_artifact_name': 'nightly-unsigned-linux-x86_64',
|
||||
'trust': {'fingerprint': '0123456789ABCDEF0123456789ABCDEF01234567'}}}}
|
||||
self.env = {'GITHUB_REPOSITORY': 'storytold/photocraft', 'GITHUB_REPOSITORY_ID': '123',
|
||||
'GITHUB_REF': 'refs/heads/release', 'GITHUB_REF_TYPE': 'branch',
|
||||
'GITHUB_EVENT_NAME': 'workflow_dispatch', 'GITHUB_RUN_ID': '200', 'GITHUB_RUN_ATTEMPT': '1',
|
||||
@@ -56,17 +66,21 @@ class RequestTests(unittest.TestCase):
|
||||
signer = {**copy.deepcopy(producer), 'id': 200, 'run_number': 20, 'workflow_id': 92,
|
||||
'head_sha': 'd'*40, 'head_branch': 'release', 'path': self.policy['signer_workflow_path'],
|
||||
'event': 'workflow_dispatch', 'status': 'in_progress', 'conclusion': None}
|
||||
self.item = {'id': 300, 'name': self.policy['unsigned_artifact_name']+'-100-1', 'expired': False,
|
||||
self.item = {'id': 300, 'name': WINDOWS_KIND+'-100-1', 'expired': False,
|
||||
'size_in_bytes': 512, 'digest': 'sha256:'+'e'*64, 'created_at': '2026-11-22T00:01:00Z',
|
||||
'expires_at': '2026-11-29T00:00:00Z',
|
||||
'workflow_run': {'id': 100, 'repository_id': 123, 'head_repository_id': 123,
|
||||
'head_sha': 'a'*40, 'head_branch': 'main'}}
|
||||
self.mac_item = {**copy.deepcopy(self.item), 'id': 302, 'name': MAC_KIND+'-100-1', 'digest': 'sha256:'+'c'*64}
|
||||
self.linux_item = {**copy.deepcopy(self.item), 'id': 304, 'name': LINUX_KIND+'-100-1', 'digest': 'sha256:'+'4'*64}
|
||||
rows = {'/actions/runs/100': producer, '/actions/runs/100/attempts/1': copy.deepcopy(producer),
|
||||
'/actions/runs/200': signer, '/actions/runs/200/attempts/1': copy.deepcopy(signer),
|
||||
'/actions/workflows/91': {'id': 91, 'path': producer['path'], 'state': 'active'},
|
||||
'/actions/workflows/92': {'id': 92, 'path': signer['path'], 'state': 'active'},
|
||||
'/actions/runs/100/artifacts?per_page=20&page=1': {'total_count': 1, 'artifacts': [self.item]},
|
||||
'/actions/runs/100/artifacts?per_page=20&page=1': {'total_count': 3, 'artifacts': [self.item, self.mac_item, self.linux_item]},
|
||||
'/actions/artifacts/300': copy.deepcopy(self.item),
|
||||
'/actions/artifacts/302': copy.deepcopy(self.mac_item),
|
||||
'/actions/artifacts/304': copy.deepcopy(self.linux_item),
|
||||
'newest': {'workflow_runs': [copy.deepcopy(producer)]}}
|
||||
self.api = API(rows)
|
||||
self.now = r.p.timestamp('2026-11-22T01:00:00Z')
|
||||
@@ -74,6 +88,20 @@ class RequestTests(unittest.TestCase):
|
||||
def invoke(self):
|
||||
return r.validate_request(self.policy, self.env, '100', '1', self.api, now=self.now)
|
||||
|
||||
def legacy_policy(self):
|
||||
"""Frozen v2 (Windows-only) shape: history only, never live admission."""
|
||||
old = {key: copy.deepcopy(value) for key, value in self.policy.items() if key != 'platforms'}
|
||||
old.update(schema='craft-nightly-release-policy/v2', platform='windows-x86_64',
|
||||
windows_publisher_subject='CN=Synthetic fixture only', unsigned_artifact_name=WINDOWS_KIND)
|
||||
return old
|
||||
|
||||
def legacy_request(self, policy=None):
|
||||
"""A v1 request bound to the legacy policy, built from a live v3 request."""
|
||||
policy = policy or self.legacy_policy(); request = copy.deepcopy(self.invoke())
|
||||
request['schema'] = 'craft-nightly-release-request/v1'; request['policy_sha256'] = r.digest(policy)
|
||||
request['artifact'] = request.pop('artifacts')['windows-x86_64']
|
||||
return request
|
||||
|
||||
def modify_run(self, which, key, value):
|
||||
for suffix in (f'/actions/runs/{which}', f'/actions/runs/{which}/attempts/1'):
|
||||
self.api.rows[suffix][key] = copy.deepcopy(value)
|
||||
@@ -104,7 +132,11 @@ class RequestTests(unittest.TestCase):
|
||||
request = self.invoke()
|
||||
self.assertEqual(request['producer']['source_commit'], 'a'*40)
|
||||
self.assertEqual(request['signer']['source_commit'], 'd'*40)
|
||||
self.assertEqual(request['artifact']['wrapper_sha256'], 'e'*64)
|
||||
self.assertEqual(request['schema'], 'craft-nightly-release-request/v2')
|
||||
self.assertEqual(request['artifacts']['windows-x86_64']['wrapper_sha256'], 'e'*64)
|
||||
self.assertEqual(request['artifacts']['macos-aarch64']['wrapper_sha256'], 'c'*64)
|
||||
self.assertEqual(request['artifacts']['linux-x86_64']['wrapper_sha256'], '4'*64)
|
||||
self.assertEqual(sorted(request['artifacts']), ['linux-x86_64', 'macos-aarch64', 'windows-x86_64'])
|
||||
self.assertTrue(all(method == 'GET' and not suffix.endswith('/zip') for method,suffix in self.api.calls))
|
||||
self.assertEqual(self.env['GITHUB_SHA'], 'd'*40)
|
||||
|
||||
@@ -197,7 +229,8 @@ class RequestTests(unittest.TestCase):
|
||||
with self.subTest(role=name,attempt=attempt):
|
||||
retained=copy.deepcopy(original)
|
||||
retained[name].update(event='workflow_dispatch',run_attempt=attempt)
|
||||
retained['artifact']['name']=r.artifact_name(self.policy,retained['producer'])
|
||||
for platform in retained['artifacts']:
|
||||
retained['artifacts'][platform]['name']=r.artifact_name(self.policy,retained['producer'],platform)
|
||||
r.request_contract(self.policy,retained) # Reviewed manual actor still passes.
|
||||
retained[name]['triggering_actor']='unapproved'
|
||||
with self.assertRaisesRegex(ValueError,'role current actor not authorized'):
|
||||
@@ -276,7 +309,8 @@ class RequestTests(unittest.TestCase):
|
||||
with self.assertRaisesRegex(ValueError,'role current actor not authorized'):
|
||||
r.request_contract(self.policy,request)
|
||||
request['producer'].update(event='schedule',run_attempt=2)
|
||||
request['artifact']['name']=r.artifact_name(self.policy,request['producer'])
|
||||
for platform in request['artifacts']:
|
||||
request['artifacts'][platform]['name']=r.artifact_name(self.policy,request['producer'],platform)
|
||||
with self.assertRaisesRegex(ValueError,'role current actor not authorized'):
|
||||
r.request_contract(self.policy,request)
|
||||
|
||||
@@ -302,18 +336,18 @@ class RequestTests(unittest.TestCase):
|
||||
with self.assertRaisesRegex(ValueError,'actor not authorized'): self.invoke()
|
||||
|
||||
def test_frozen_v1_historical_contract_is_explicit_and_never_a_live_fallback(self):
|
||||
request=self.invoke()
|
||||
old=copy.deepcopy(self.policy); old['schema']='craft-nightly-release-policy/v1'
|
||||
old=self.legacy_policy(); old['schema']='craft-nightly-release-policy/v1'
|
||||
del old['automatic_signer_actors']; old['manual_actors']=['github-actions[bot]']
|
||||
request['policy_sha256']=r.digest(old)
|
||||
request=self.legacy_request(old)
|
||||
r.validate_policy(old); r.request_contract(old,request)
|
||||
receipt=r.release_receipt(old,request,'f'*64,'1'*64,old['windows_publisher_subject'])
|
||||
self.assertEqual(receipt['policy_sha256'],r.digest(old))
|
||||
request['producer']['event']='workflow_dispatch'
|
||||
r.request_contract(old,request) # Explicit historical v1 broad manual grant stays broad.
|
||||
self.api.calls.clear()
|
||||
with self.assertRaisesRegex(ValueError,'live admission requires.*v2'):
|
||||
r.validate_request(old,self.env,100,1,self.api,now=self.now)
|
||||
for history in (old, self.legacy_policy()):
|
||||
with self.assertRaisesRegex(ValueError,'live admission requires.*v3'):
|
||||
r.validate_request(history,self.env,100,1,self.api,now=self.now)
|
||||
self.assertEqual(self.api.calls,[])
|
||||
with self.assertRaises(ValueError): r.validate_policy({**old,'automatic_signer_actors':[]})
|
||||
old['manual_actors']=[]; request['policy_sha256']=r.digest(old)
|
||||
@@ -322,8 +356,8 @@ class RequestTests(unittest.TestCase):
|
||||
|
||||
def test_missing_expired_substituted_oversized_cross_attempt_artifacts(self):
|
||||
for key,value in [('expired',True), ('expires_at','2026-11-22T00:30:00Z'),
|
||||
('name','nightly-signed'), ('name',self.policy['unsigned_artifact_name']+'-100-2'),
|
||||
('name',self.policy['unsigned_artifact_name']+'-101-1'), ('size_in_bytes',1000001), ('size_in_bytes',0),
|
||||
('name','nightly-signed'), ('name',WINDOWS_KIND+'-100-2'),
|
||||
('name',WINDOWS_KIND+'-101-1'), ('name',MAC_KIND+'-100-1'), ('size_in_bytes',1000001), ('size_in_bytes',0),
|
||||
('created_at','2026-11-21T00:00:00Z'), ('digest',None), ('digest','sha256:bad'),
|
||||
('workflow_run',{'id':999})]:
|
||||
with self.subTest(key=key):
|
||||
@@ -337,8 +371,8 @@ class RequestTests(unittest.TestCase):
|
||||
|
||||
def test_artifact_list_ambiguity_duplicates_missing_and_incomplete_totals(self):
|
||||
key='/actions/runs/100/artifacts?per_page=20&page=1'
|
||||
for rows,total in [([],0),([self.item,self.item],2),([self.item],2),
|
||||
([self.item,{**self.item,'id':301}],2),([self.item],401)]:
|
||||
for rows,total in [([],0),([self.item,self.item],2),([self.item],2),([self.item],1),([self.mac_item],1),
|
||||
([self.item,self.mac_item,{**self.item,'id':301}],3),([self.item,self.mac_item],401)]:
|
||||
self.api.rows[key]={'artifacts':rows,'total_count':total}
|
||||
with self.assertRaises(ValueError): self.invoke()
|
||||
|
||||
@@ -412,7 +446,8 @@ class RequestTests(unittest.TestCase):
|
||||
with self.subTest(path=path), self.assertRaises(ValueError): self.verify(result)
|
||||
|
||||
def test_receipt_has_two_roles_three_distinct_digest_boundaries_and_no_boolean_proof(self):
|
||||
request=self.invoke(); receipt=r.release_receipt(self.policy,request,'f'*64,'1'*64,'CN=Synthetic fixture only')
|
||||
legacy=self.legacy_policy(); request=self.legacy_request(legacy); self.policy=legacy
|
||||
receipt=r.release_receipt(self.policy,request,'f'*64,'1'*64,'CN=Synthetic fixture only')
|
||||
self.assertEqual(receipt['schema'],'craft-nightly-signing/v2')
|
||||
self.assertEqual(receipt['producer']['source_commit'],'a'*40)
|
||||
self.assertEqual(receipt['signer']['source_commit'],'d'*40)
|
||||
@@ -433,12 +468,18 @@ class RequestTests(unittest.TestCase):
|
||||
self.api.rows[f'/actions/runs/{which}/attempts/2']=copy.deepcopy(self.api.rows[f'/actions/runs/{which}'])
|
||||
self.env.update(GITHUB_RUN_ATTEMPT='2', GITHUB_TRIGGERING_ACTOR='approved')
|
||||
self.api.rows['newest']['workflow_runs']=[copy.deepcopy(self.api.rows['/actions/runs/100'])]
|
||||
rerun_item={**copy.deepcopy(self.item),'id':301,'name':self.policy['unsigned_artifact_name']+'-100-2'}
|
||||
rerun_item={**copy.deepcopy(self.item),'id':301,'name':WINDOWS_KIND+'-100-2'}
|
||||
rerun_mac={**copy.deepcopy(self.mac_item),'id':303,'name':MAC_KIND+'-100-2'}
|
||||
rerun_linux={**copy.deepcopy(self.linux_item),'id':305,'name':LINUX_KIND+'-100-2'}
|
||||
self.api.rows['/actions/artifacts/301']=rerun_item
|
||||
self.api.rows['/actions/runs/100/artifacts?per_page=20&page=1']={'total_count':2,'artifacts':[self.item,rerun_item]}
|
||||
self.api.rows['/actions/artifacts/303']=rerun_mac
|
||||
self.api.rows['/actions/artifacts/305']=rerun_linux
|
||||
self.api.rows['/actions/runs/100/artifacts?per_page=20&page=1']={'total_count':6,'artifacts':[self.item,rerun_item,self.mac_item,rerun_mac,self.linux_item,rerun_linux]}
|
||||
request=r.validate_request(self.policy,self.env,100,2,self.api,now=self.now)
|
||||
self.assertEqual(request['artifact']['id'],301)
|
||||
self.assertEqual(self.item['name'],self.policy['unsigned_artifact_name']+'-100-1')
|
||||
self.assertEqual(request['artifacts']['windows-x86_64']['id'],301)
|
||||
self.assertEqual(request['artifacts']['macos-aarch64']['id'],303)
|
||||
self.assertEqual(request['artifacts']['linux-x86_64']['id'],305)
|
||||
self.assertEqual(self.item['name'],WINDOWS_KIND+'-100-1')
|
||||
self.assertEqual(request['producer']['run_attempt'],2)
|
||||
self.assertEqual(request['signer']['run_attempt'],2)
|
||||
with self.assertRaisesRegex(ValueError,'exact invocation'):
|
||||
@@ -499,8 +540,10 @@ class RequestTests(unittest.TestCase):
|
||||
def test_protected_publisher_subject_has_strict_nonempty_bounded_literal_shape(self):
|
||||
for subject in (None, True, '', 'x'*2049, 'CN=bad\rsubject', 'CN=bad\nsubject', 'CN=bad\0subject'):
|
||||
with self.subTest(subject=subject):
|
||||
policy={**self.policy,'windows_publisher_subject':subject}
|
||||
policy=copy.deepcopy(self.policy); policy['platforms']['windows-x86_64']['trust']['publisher_subject']=subject
|
||||
with self.assertRaises(ValueError): r.validate_policy(policy)
|
||||
legacy={**self.legacy_policy(),'windows_publisher_subject':subject}
|
||||
with self.assertRaises(ValueError): r.validate_policy(legacy)
|
||||
|
||||
def test_old_schemas_unknown_fields_and_unpatched_verifier_never_fall_back(self):
|
||||
extra={**self.policy,'unreviewed':True}
|
||||
@@ -533,11 +576,11 @@ class RequestTests(unittest.TestCase):
|
||||
def test_complete_artifact_inventory_on_the_last_allowed_full_page_is_accepted(self):
|
||||
limit = r.p.MAX_PAGES*r.p.PAGE_SIZE
|
||||
rows = [{**copy.deepcopy(self.item), 'id': 1000+index, 'name': 'other-'+str(index)} for index in range(limit-1)]
|
||||
rows.insert(limit//2, copy.deepcopy(self.item))
|
||||
rows.insert(limit//2, copy.deepcopy(self.item)); rows[limit//3] = copy.deepcopy(self.linux_item); rows[-1] = copy.deepcopy(self.mac_item)
|
||||
for page in range(1, r.p.MAX_PAGES+1):
|
||||
self.api.rows[f'/actions/runs/100/artifacts?per_page={r.p.PAGE_SIZE}&page={page}'] = {'total_count': limit,
|
||||
'artifacts': rows[(page-1)*r.p.PAGE_SIZE:page*r.p.PAGE_SIZE]}
|
||||
self.assertEqual(self.invoke()['artifact']['id'], 300)
|
||||
self.assertEqual(self.invoke()['artifacts']['windows-x86_64']['id'], 300)
|
||||
self.assertFalse(any(path.endswith(f'&page={r.p.MAX_PAGES+1}') for _, path in self.api.calls))
|
||||
# A full page that still leaves the reported total unread keeps refusing.
|
||||
last = f'/actions/runs/100/artifacts?per_page={r.p.PAGE_SIZE}&page={r.p.MAX_PAGES}'
|
||||
@@ -545,4 +588,70 @@ class RequestTests(unittest.TestCase):
|
||||
with self.assertRaisesRegex(ValueError, 'incomplete'): self.invoke()
|
||||
|
||||
|
||||
def test_v3_policy_requires_exact_platform_map_kinds_and_single_trust_values(self):
|
||||
r.validate_policy(self.policy)
|
||||
self.assertEqual(r.policy_platforms(self.policy), ['linux-x86_64', 'macos-aarch64', 'windows-x86_64'])
|
||||
mutations = [
|
||||
lambda pol: pol['platforms'].clear(),
|
||||
lambda pol: pol['platforms'].update({'freebsd-x86_64': copy.deepcopy(pol['platforms']['windows-x86_64'])}),
|
||||
lambda pol: pol['platforms']['macos-aarch64'].update(unsigned_artifact_name=WINDOWS_KIND),
|
||||
lambda pol: pol['platforms']['macos-aarch64'].update(unsigned_artifact_name='nightly-unsigned'),
|
||||
lambda pol: pol['platforms']['macos-aarch64'].update(extra=True),
|
||||
lambda pol: pol['platforms']['macos-aarch64']['trust'].update(apple_team_id='short'),
|
||||
lambda pol: pol['platforms']['macos-aarch64']['trust'].update(apple_team_id='synth12345'),
|
||||
lambda pol: pol['platforms']['macos-aarch64']['trust'].update(apple_team_id='SYNTH12345\n'),
|
||||
lambda pol: pol['platforms']['macos-aarch64']['trust'].update(publisher_subject='CN=x'),
|
||||
lambda pol: pol['platforms']['macos-aarch64'].update(trust={'publisher_subject': 'CN=x'}),
|
||||
lambda pol: pol['platforms']['windows-x86_64'].update(trust={'apple_team_id': 'SYNTH12345'}),
|
||||
lambda pol: pol.update(platform='windows-x86_64'),
|
||||
lambda pol: pol.update(windows_publisher_subject='CN=x'),
|
||||
lambda pol: pol.update(unsigned_artifact_name=WINDOWS_KIND),
|
||||
lambda pol: pol.pop('platforms'),
|
||||
]
|
||||
for index, mutate in enumerate(mutations):
|
||||
policy = copy.deepcopy(self.policy); mutate(policy)
|
||||
with self.subTest(index=index), self.assertRaises(ValueError): r.validate_policy(policy)
|
||||
|
||||
def test_each_admitted_platform_needs_its_own_exact_artifact_and_live_reread(self):
|
||||
key = '/actions/runs/100/artifacts?per_page=20&page=1'
|
||||
self.api.rows[key] = {'total_count': 1, 'artifacts': [self.item]}
|
||||
with self.assertRaisesRegex(ValueError, 'admitted platform'): self.invoke()
|
||||
self.api.rows[key] = {'total_count': 2, 'artifacts': [self.item, self.mac_item]}
|
||||
with self.assertRaisesRegex(ValueError, 'admitted platform'): self.invoke() # Linux artifact missing.
|
||||
self.api.rows[key] = {'total_count': 3, 'artifacts': [self.item, self.mac_item, self.linux_item]}
|
||||
self.api.rows['/actions/artifacts/302']['digest'] = 'sha256:'+'9'*64
|
||||
with self.assertRaisesRegex(ValueError, 'substituted'): self.invoke()
|
||||
self.api.rows['/actions/artifacts/302'] = copy.deepcopy(self.mac_item)
|
||||
request = self.invoke()
|
||||
swapped = copy.deepcopy(request)
|
||||
swapped['artifacts']['windows-x86_64'], swapped['artifacts']['macos-aarch64'] = (
|
||||
swapped['artifacts']['macos-aarch64'], swapped['artifacts']['windows-x86_64'])
|
||||
with self.assertRaisesRegex(ValueError, 'artifact request binding'): r.request_contract(self.policy, swapped)
|
||||
missing = copy.deepcopy(request); del missing['artifacts']['macos-aarch64']
|
||||
with self.assertRaisesRegex(ValueError, 'platform set'): r.request_contract(self.policy, missing)
|
||||
legacy = copy.deepcopy(request); legacy['schema'] = 'craft-nightly-release-request/v1'
|
||||
with self.assertRaises(ValueError): r.request_contract(self.policy, legacy)
|
||||
|
||||
def test_v3_receipt_binds_platform_trust_method_support_and_artifact(self):
|
||||
request = self.invoke()
|
||||
mac = r.release_receipt_v3(self.policy, request, 'macos-aarch64', 'f'*64, '1'*64, 'SYNTH12345', {})
|
||||
self.assertEqual((mac['schema'], mac['platform'], mac['method']), ('craft-nightly-signing/v3', 'macos-aarch64', 'developer-id-notarized'))
|
||||
self.assertEqual(mac['artifact'], request['artifacts']['macos-aarch64'])
|
||||
win = r.release_receipt_v3(self.policy, request, 'windows-x86_64', 'f'*64, '1'*64, 'CN=Synthetic fixture only', {})
|
||||
self.assertEqual(win['method'], 'authenticode')
|
||||
for platform, signer in (('macos-aarch64', 'OTHER12345'), ('macos-aarch64', 'CN=Synthetic fixture only'),
|
||||
('windows-x86_64', 'SYNTH12345'), ('macos-aarch64', None), ('linux-x86_64', 'SYNTH12345')):
|
||||
with self.subTest(platform=platform, signer=signer), self.assertRaises(ValueError):
|
||||
r.release_receipt_v3(self.policy, request, platform, 'f'*64, '1'*64, signer, {})
|
||||
# Windows and macOS signing must change bytes: no unsigned fallback.
|
||||
with self.assertRaisesRegex(ValueError, 'unsigned fallback'):
|
||||
r.release_receipt_v3(self.policy, request, 'macos-aarch64', 'f'*64, 'f'*64, 'SYNTH12345', {})
|
||||
for support in ({'../x': {'size': 1, 'sha256': '1'*64}}, {'x.asc': {'size': 0, 'sha256': '1'*64}},
|
||||
{'x.asc': {'size': 1, 'sha256': 'bad'}}, {'x.asc': {'size': 1}}, []):
|
||||
with self.subTest(support=support), self.assertRaises(ValueError):
|
||||
r.release_receipt_v3(self.policy, request, 'macos-aarch64', 'f'*64, '1'*64, 'SYNTH12345', support)
|
||||
with self.assertRaisesRegex(ValueError, 'policy v3'):
|
||||
r.release_receipt_v3(self.legacy_policy(), self.legacy_request(), 'windows-x86_64', 'f'*64, '1'*64, 'CN=Synthetic fixture only', {})
|
||||
|
||||
|
||||
if __name__ == '__main__': unittest.main()
|
||||
@@ -31,30 +31,43 @@ class ReleaseWorkflowTests(unittest.TestCase):
|
||||
|
||||
def test_main_build_and_attester_are_separate_and_credential_bound(self):
|
||||
graph = jobs(self.unsigned)
|
||||
self.assertEqual(set(graph), {"git-sources", "build", "attest"})
|
||||
self.assertIn("needs: git-sources", graph["build"])
|
||||
self.assertEqual(set(graph), {"select-platforms", "git-sources", "build", "attest", "build-macos", "attest-macos", "build-linux", "attest-linux"})
|
||||
self.assertEqual(graph["select-platforms"].count("secrets."), 0); self.assertIn("permissions: {}", graph["select-platforms"])
|
||||
self.assertIn("cargo metadata --locked", graph["git-sources"])
|
||||
self.assertIn("-Nightly -BuildOnly", graph["build"])
|
||||
self.assertIn("nightly_smoke.py", graph["build"])
|
||||
for name in ("git-sources", "build"):
|
||||
for forbidden in ("secrets.", "id-token:", "attestations:", "environment:", "actions/cache", "save-cache", "restore-cache"):
|
||||
self.assertNotIn(forbidden, graph[name])
|
||||
attester = graph["attest"]
|
||||
self.assertIn("needs: build", attester)
|
||||
self.assertIn("id-token: write", attester)
|
||||
self.assertIn("EXPECTED_COMPILER_SHA256: ${{ needs.build.outputs.unsigned-sha256 }}", attester)
|
||||
self.assertIn("repository: ${{ job.workflow_repository }}", attester)
|
||||
for forbidden in ("secrets.", "environment:", "nightly_smoke.py", "package.ps1", "actions/cache", "persist-credentials: true"):
|
||||
self.assertNotIn(forbidden, attester)
|
||||
self.assertIn("bash packaging/macos/nightly.sh --arch aarch64", graph["build-macos"])
|
||||
self.assertIn("default: '[\"windows-x86_64\"]'", self.unsigned)
|
||||
for build, attest, platform in (("build", "attest", "windows-x86_64"), ("build-macos", "attest-macos", "macos-aarch64")):
|
||||
self.assertIn("needs: [git-sources, select-platforms]", graph[build])
|
||||
self.assertIn("contains(fromJSON(needs.select-platforms.outputs.platforms), '"+platform+"')", graph[build])
|
||||
self.assertNotIn("fromJSON(inputs.platforms)", graph[build])
|
||||
self.assertIn("nightly_smoke.py", graph[build])
|
||||
for mode in ("main-plan", "main-seal"):
|
||||
self.assertIn("nightly_release_entry.py "+mode+" --platform "+platform, graph[build])
|
||||
self.assertIn("name: nightly-unsigned-"+platform+"-${{ github.run_id }}-${{ github.run_attempt }}", graph[build])
|
||||
for forbidden in ("secrets.", "id-token:", "attestations:", "environment:", "actions/cache", "save-cache", "restore-cache", "APPLE_", "KEYCHAIN"):
|
||||
self.assertNotIn(forbidden, graph[build])
|
||||
attester = graph[attest]
|
||||
self.assertIn("needs: "+build, attester)
|
||||
self.assertIn("id-token: write", attester)
|
||||
self.assertIn("EXPECTED_COMPILER_SHA256: ${{ needs."+build+".outputs.unsigned-sha256 }}", attester)
|
||||
self.assertIn("main-subject --platform "+platform, attester)
|
||||
self.assertIn("repository: ${{ job.workflow_repository }}", attester)
|
||||
for forbidden in ("secrets.", "environment:", "nightly_smoke.py", "package.ps1", "nightly.sh", "actions/cache", "persist-credentials: true"):
|
||||
self.assertNotIn(forbidden, attester)
|
||||
for forbidden in ("secrets.", "environment:"):
|
||||
self.assertNotIn(forbidden, graph["git-sources"])
|
||||
|
||||
def test_release_queue_is_constant_not_input_ref_or_candidate_sharded(self):
|
||||
self.assertIn("concurrency:\n group: craft-release-ref-signer-photocraft\n cancel-in-progress: false\n queue: max", self.release)
|
||||
graph = jobs(self.release)
|
||||
self.assertEqual(set(graph), {"validate", "sign", "publish"})
|
||||
self.assertIn("needs: validate", graph["sign"])
|
||||
self.assertIn("needs.validate.outputs.admitted == 'true'", graph["sign"])
|
||||
self.assertEqual(graph["validate"].count("if: steps.admit.outputs.admitted == 'true'"), 3)
|
||||
self.assertIn("needs: sign", graph["publish"])
|
||||
self.assertEqual(set(graph), {"validate", "sign-windows", "sign-macos", "verify-macos", "smoke-macos", "sign-linux", "verify-linux", "publish"})
|
||||
for name, platform in (("sign-windows", "windows-x86_64"), ("sign-macos", "macos-aarch64")):
|
||||
self.assertIn("needs: validate", graph[name])
|
||||
self.assertIn("needs.validate.outputs.admitted == 'true' && contains(fromJSON(needs.validate.outputs.platforms), '"+platform+"')", graph[name])
|
||||
self.assertIn("--platform "+platform, graph[name])
|
||||
self.assertEqual(graph["validate"].count("if: steps.admit.outputs.admitted == 'true'"), 5) # 3 downloads, validate, upload
|
||||
self.assertIn("needs: [validate, sign-windows, sign-macos, verify-macos, smoke-macos, sign-linux, verify-linux]", graph["publish"])
|
||||
|
||||
def test_each_release_job_checks_the_real_official_release_dispatch(self):
|
||||
for block in jobs(self.release).values():
|
||||
@@ -62,32 +75,42 @@ class ReleaseWorkflowTests(unittest.TestCase):
|
||||
self.assertIn(required, block)
|
||||
self.assertNotIn("actions/cache", block)
|
||||
self.assertNotIn("secrets: inherit", block)
|
||||
self.assertIn("config['schema']=='craft-nightly-release-policy/v2'", block)
|
||||
self.assertIn("config['schema']=='craft-nightly-release-policy/v3'", block)
|
||||
self.assertNotIn("config['schema']=='craft-nightly-release-policy/v1'", block)
|
||||
self.assertNotIn("config['schema']=='craft-nightly-release-policy/v2'", block)
|
||||
self.assertNotIn("GITHUB_SHA:", block)
|
||||
self.assertNotIn("GITHUB_REF:", block)
|
||||
|
||||
def test_quality_snapshot_precedes_cross_run_artifact_download(self):
|
||||
validator = jobs(self.release)["validate"]
|
||||
self.assertLess(validator.index("nightly_release_entry.py admit"), validator.index("uses: actions/download-artifact@"))
|
||||
for required in ("run-id: ${{ inputs.producer_run_id }}", "artifact-ids: ${{ steps.admit.outputs.artifact-id }}", "digest-mismatch: error"):
|
||||
for required in ("run-id: ${{ inputs.producer_run_id }}", "artifact-ids: ${{ steps.admit.outputs.artifact-id-windows-x86_64 }}",
|
||||
"artifact-ids: ${{ steps.admit.outputs.artifact-id-macos-aarch64 }}", "path: .unsigned/windows-x86_64",
|
||||
"path: .unsigned/macos-aarch64", "digest-mismatch: error"):
|
||||
self.assertIn(required, validator)
|
||||
self.assertEqual(validator.count("merge-multiple: true"), 3) # one exact download per supported platform
|
||||
|
||||
def test_only_signer_has_release_environment_and_only_leaf_step_exports_keys(self):
|
||||
graph = jobs(self.release)
|
||||
for name in ("validate", "publish"):
|
||||
for name in ("validate", "verify-macos", "smoke-macos", "publish"):
|
||||
self.assertNotRegex(graph[name], r"(?m)^ environment:")
|
||||
self.assertNotRegex(graph[name], r"\$\{\{\s*secrets\.")
|
||||
signer = graph["sign"]
|
||||
self.assertIn("environment: release", signer)
|
||||
self.assertNotIn("id-token:", signer)
|
||||
self.assertNotIn("contents: write", signer)
|
||||
guard = signer.index("nightly_release_entry.py guard")
|
||||
keys = signer.index("secrets.WINDOWS_CERTIFICATE")
|
||||
leaf = signer.index("- name: Sign data only")
|
||||
self.assertLess(guard, leaf)
|
||||
self.assertLess(leaf, keys)
|
||||
self.assertNotIn("secrets.", signer[:leaf])
|
||||
for name, key, leaf_name, foreign in (("sign-windows", "secrets.WINDOWS_CERTIFICATE", "- name: Sign data only", "APPLE_"),
|
||||
("sign-macos", "secrets.APPLE_CERTIFICATE", "- name: Sign, notarize and staple data only", "WINDOWS_")):
|
||||
signer = graph[name]
|
||||
self.assertIn("environment: release", signer)
|
||||
self.assertNotIn("id-token:", signer)
|
||||
self.assertNotIn("contents: write", signer)
|
||||
self.assertNotIn(foreign, signer)
|
||||
guard = signer.index("nightly_release_entry.py guard")
|
||||
keys = signer.index(key)
|
||||
leaf = signer.index(leaf_name)
|
||||
self.assertLess(guard, leaf)
|
||||
self.assertLess(leaf, keys)
|
||||
self.assertNotIn("secrets.", signer[:leaf])
|
||||
# Exactly the six stable Apple names, from the same `release` environment as stable.
|
||||
self.assertEqual(sorted(set(re.findall(r"secrets\.([A-Z_]+)", graph["sign-macos"]))),
|
||||
sorted(["APPLE_CERTIFICATE", "APPLE_CERTIFICATE_PASSWORD", "KEYCHAIN_PASSWORD", "APPLE_ID", "APPLE_PASSWORD", "APPLE_TEAM_ID"]))
|
||||
|
||||
def test_publisher_reverifies_before_attesting_and_keeps_ownership_on_failure(self):
|
||||
publisher = jobs(self.release)["publish"]
|
||||
@@ -144,14 +167,45 @@ class ReleaseWorkflowTests(unittest.TestCase):
|
||||
self.assertEqual(block.count("cargo metadata --locked"), 1)
|
||||
|
||||
def test_only_the_sign_step_of_the_signer_references_secrets(self):
|
||||
signer = jobs(self.release)["sign"]
|
||||
steps = re.findall(r"(?ms)^ - (?:name: ([^\n]+)|uses: [^\n]+)\n(.*?)(?=^ - |\Z)", signer)
|
||||
self.assertGreater(len(steps), 3)
|
||||
with_secrets = [name for name, block in steps if "secrets." in block]
|
||||
self.assertEqual(with_secrets, ["Sign data only through protected existing Windows adapter"])
|
||||
self.assertNotIn("secrets.", signer.split(" steps:\n", 1)[0])
|
||||
guard = signer.index("nightly_release_entry.py guard")
|
||||
self.assertLess(guard, signer.index("- name: Sign data only"))
|
||||
for name, step in (("sign-windows", "Sign data only through protected existing Windows adapter"),
|
||||
("sign-macos", "Sign, notarize and staple data only through the protected app macOS adapter")):
|
||||
signer = jobs(self.release)[name]
|
||||
steps = re.findall(r"(?ms)^ - (?:name: ([^\n]+)|uses: [^\n]+)\n(.*?)(?=^ - |\Z)", signer)
|
||||
self.assertGreater(len(steps), 3)
|
||||
with_secrets = [name for name, block in steps if "secrets." in block]
|
||||
self.assertEqual(with_secrets, [step])
|
||||
self.assertNotIn("secrets.", signer.split(" steps:\n", 1)[0])
|
||||
guard = signer.index("nightly_release_entry.py guard")
|
||||
self.assertLess(guard, signer.index("- name: "+step))
|
||||
|
||||
def test_macos_verifier_and_smoke_are_fresh_keyless_and_bound_to_exact_signed_bytes(self):
|
||||
graph = jobs(self.release)
|
||||
verify, smoke = graph["verify-macos"], graph["smoke-macos"]
|
||||
self.assertIn("needs: [validate, sign-macos]", verify)
|
||||
self.assertIn("artifact-ids: ${{ needs.sign-macos.outputs.artifact-id }}", verify)
|
||||
self.assertIn("verify-platform --source .release-source --platform macos-aarch64", verify)
|
||||
self.assertIn("EXPECTED_BUNDLE_SHA256: ${{ needs.sign-macos.outputs.bundle-sha256 }}", verify)
|
||||
self.assertIn("needs: [validate, sign-macos, verify-macos]", smoke)
|
||||
self.assertIn(" permissions:\n contents: read\n steps:", smoke)
|
||||
for forbidden in ("GH_TOKEN", "github.token", "secrets.", "environment:", "nightly-tools", "id-token"):
|
||||
self.assertNotIn(forbidden, smoke)
|
||||
# The signed app runs only after its bytes equal the keyless verifier's exact digest.
|
||||
self.assertLess(smoke.index('test "$(shasum -a 256 "$final"'), smoke.index("nightly-verify.sh --input"))
|
||||
self.assertIn("FINAL_SHA256: ${{ needs.verify-macos.outputs.final-sha256 }}", smoke)
|
||||
self.assertIn("bash .release-source/packaging/macos/nightly-verify.sh --input \"$final\" --expect signed --team \"$team\"", smoke)
|
||||
self.assertIn("HEAD:.github/nightly-signing-policy.json", smoke)
|
||||
|
||||
def test_publish_requires_every_admitted_platform_and_binds_each_digest(self):
|
||||
publisher = jobs(self.release)["publish"]
|
||||
self.assertNotIn("always() &&", publisher.split(" runs-on:", 1)[0]) # a cancel must stop release writes
|
||||
for required in ("!cancelled() && needs.validate.result == 'success' && needs.validate.outputs.admitted == 'true'",
|
||||
"(!contains(fromJSON(needs.validate.outputs.platforms), 'windows-x86_64') || needs.sign-windows.result == 'success')",
|
||||
"(!contains(fromJSON(needs.validate.outputs.platforms), 'macos-aarch64') || (needs.sign-macos.result == 'success' && needs.verify-macos.result == 'success' && needs.smoke-macos.result == 'success'))",
|
||||
"SIGNED_BUNDLE_SHA256_WINDOWS_X86_64: ${{ needs.sign-windows.outputs.bundle-sha256 }}",
|
||||
"SIGNED_BUNDLE_SHA256_MACOS_AARCH64: ${{ needs.sign-macos.outputs.bundle-sha256 }}",
|
||||
"VERIFIED_FINAL_SHA256_MACOS_AARCH64: ${{ needs.verify-macos.outputs.final-sha256 }}",
|
||||
"path: .signed/windows-x86_64", "path: .signed/macos-aarch64", "--combined .combined"):
|
||||
self.assertIn(required, publisher)
|
||||
|
||||
def test_publish_job_budget_leaves_the_tolerant_ownership_upload_its_own_bound(self):
|
||||
# A job-level timeout cancels the job and fails success-only history, so every
|
||||
|
||||
@@ -24,17 +24,22 @@ class WorkflowReviewTests(unittest.TestCase):
|
||||
common=(ROOT/'.github/workflows/nightly.yml').read_text()
|
||||
windows=(ROOT/'.github/workflows/nightly-windows.yml').read_text()
|
||||
caller=(ROOT/'examples/photocraft-nightly.yml').read_text()
|
||||
for source in (common,windows):
|
||||
apple={'APPLE_CERTIFICATE','APPLE_CERTIFICATE_PASSWORD','KEYCHAIN_PASSWORD','APPLE_ID','APPLE_PASSWORD','APPLE_TEAM_ID'}
|
||||
for source,extra in ((common,apple|{'LINUX_SIGNING_KEY'}),(windows,set())):
|
||||
declarations=source.split(' secrets:\n',1)[1].split(' inputs:',1)[0]
|
||||
self.assertEqual(set(re.findall(r'^ ([A-Z_]+):',declarations,re.M)),WINDOWS_NAMES)
|
||||
self.assertEqual(declarations.count('required: false'),8)
|
||||
for source in (job(common,'build-windows'),job(caller,'nightly')):
|
||||
self.assertEqual(set(re.findall(r'^ ([A-Z_]+):',declarations,re.M)),WINDOWS_NAMES|extra)
|
||||
self.assertEqual(declarations.count('required: false'),8+len(extra))
|
||||
for source,extra in ((job(common,'build-windows'),set()),(job(caller,'nightly'),apple|{'LINUX_SIGNING_KEY'})):
|
||||
forwarded=re.findall(r'^ ([A-Z_]+): \$\{\{ secrets\.([A-Z_]+) \}\}',source,re.M)
|
||||
self.assertEqual(set(forwarded),{(name,name) for name in WINDOWS_NAMES})
|
||||
self.assertEqual(set(forwarded),{(name,name) for name in WINDOWS_NAMES|extra})
|
||||
for source in (common,windows,caller):
|
||||
self.assertNotIn('secrets: inherit',source)
|
||||
for name in ('build-linux','build-macos'):
|
||||
self.assertNotIn('secrets:',job(common,name))
|
||||
# macOS receives exactly the six stable Apple names; never the Windows set or inherit.
|
||||
self.assertEqual(set(re.findall(r'^ ([A-Z_]+): \$\{\{ secrets\.([A-Z_]+) \}\}',job(common,'build-macos'),re.M)),
|
||||
{(name,name) for name in apple})
|
||||
# Linux receives exactly its one existing stable secret name; never the Windows set or inherit.
|
||||
self.assertEqual(re.findall(r'^ ([A-Z_]+): \$\{\{ secrets\.([A-Z_]+) \}\}',job(common,'build-linux'),re.M),
|
||||
[('LINUX_SIGNING_KEY','LINUX_SIGNING_KEY')])
|
||||
self.assertNotIn('secrets.',job(windows,'build'))
|
||||
self.assertNotIn('environment:',job(windows,'build'))
|
||||
|
||||
@@ -52,12 +57,11 @@ class WorkflowReviewTests(unittest.TestCase):
|
||||
for name in ('nightly-unix.yml','nightly-signing-unix.yml'):
|
||||
source=(ROOT/'.github/workflows'/name).read_text()
|
||||
linux=job(source,'linux')
|
||||
if name=='nightly-unix.yml':
|
||||
self.assertIn('if: ${{ false }}',linux)
|
||||
else:
|
||||
self.assertIn("github.repository == 'storytold/photocraft'",linux)
|
||||
self.assertIn("github.ref == 'refs/heads/main'",linux)
|
||||
self.assertIn('if: ${{ false }}',job((ROOT/'.github/workflows/nightly.yml').read_text(),'build-linux'))
|
||||
self.assertNotIn('${{ false }}',linux.split(' steps:',1)[0])
|
||||
self.assertIn("inputs.production-signing == true",linux)
|
||||
self.assertIn("github.repository == 'storytold/photocraft'",linux)
|
||||
self.assertIn("github.ref == 'refs/heads/main'",linux)
|
||||
self.assertIn("inputs.production-signing == true",job((ROOT/'.github/workflows/nightly.yml').read_text(),'build-linux'))
|
||||
self.assertIn("python-version: '3.13'",linux)
|
||||
self.assertRegex(linux,r'actions/setup-python@[0-9a-f]{40}')
|
||||
self.assertLess(linux.index('actions/setup-python@'),linux.index('python3'))
|
||||
|
||||
@@ -278,8 +278,9 @@ class SigningTests(unittest.TestCase):
|
||||
# The boundary confines the verification directory, not bundle contents: framework
|
||||
# links are produced by ditto and judged only by codesign/stapler/spctl (mocked here).
|
||||
output=self.root/'mac verify'/'payload'; output.parent.mkdir()
|
||||
details=('Authority=Developer ID Application: Fixture (ABCDE12345)\nTeamIdentifier=ABCDE12345\n'
|
||||
details=('Identifier=ai.storyteller.photocraft.nightly\nAuthority=Developer ID Application: Fixture (ABCDE12345)\nTeamIdentifier=ABCDE12345\n'
|
||||
'Timestamp=Nov 22, 2026\nCodeDirectory v=20500 flags=0x10000(runtime) hashes=x\n')
|
||||
gatekeeper='/x: accepted\nsource=Notarized Developer ID\norigin=Developer ID Application: Fixture (ABCDE12345)\n'
|
||||
calls=[]
|
||||
def tool(argv,**kwargs):
|
||||
calls.append(Path(str(argv[0])).name)
|
||||
@@ -289,12 +290,14 @@ class SigningTests(unittest.TestCase):
|
||||
versions=app/'Contents/Frameworks/Fixture.framework/Versions'; (versions/'A').mkdir(parents=True)
|
||||
(versions/'Current').symlink_to('A',target_is_directory=True)
|
||||
return 'arm64' if argv[0]=='/usr/bin/lipo' else ''
|
||||
completed=s.subprocess.CompletedProcess([],0,details.encode(),b'')
|
||||
def system(argv,**kwargs):
|
||||
calls.append(Path(str(argv[0])).name)
|
||||
return s.subprocess.CompletedProcess(argv,0,(gatekeeper if argv[0]=='/usr/sbin/spctl' else details).encode(),b'')
|
||||
with patch.object(s.u,'verify_archive',return_value={}),patch.object(s,'command',side_effect=tool),\
|
||||
patch.object(s.subprocess,'run',return_value=completed):
|
||||
patch.object(s.subprocess,'run',side_effect=system):
|
||||
self.assertEqual(s.mac_verify(self.archive,'v',{},{'NIGHTLY_APPLE_TEAM_ID':'ABCDE12345'},output),'ABCDE12345')
|
||||
self.assertTrue((output/'PhotoCraft Nightly.app/Contents/Frameworks/Fixture.framework/Versions/Current').is_symlink())
|
||||
self.assertEqual(calls,['ditto','lipo','codesign','xcrun','spctl'])
|
||||
self.assertEqual(calls,['ditto','lipo','codesign','codesign','xcrun','spctl'])
|
||||
link=self.root/'mac-link'; link.symlink_to(self.root,target_is_directory=True)
|
||||
with patch.object(s.u,'verify_archive',return_value={}),patch.object(s,'command',side_effect=AssertionError('no tool')),\
|
||||
self.assertRaises(ValueError):
|
||||
@@ -327,7 +330,10 @@ class SigningTests(unittest.TestCase):
|
||||
calls.append([str(x) for x in argv])
|
||||
if '--list-keys' in argv: return 'pub:u:255:22:fixture:0:0:::::\nfpr:::::::::'+fingerprint+':\n'
|
||||
if '--detach-sign' in argv:
|
||||
Path(argv[argv.index('-o')+1]).write_text('synthetic detached signature, not real signing')
|
||||
Path(argv[argv.index('-o')+1]).write_text('-----BEGIN PGP SIGNATURE-----\nsynthetic, not real signing\n-----END PGP SIGNATURE-----\n')
|
||||
if str(argv[0])=='/usr/bin/gpgv':
|
||||
return ('[GNUPG:] NEWSIG\n[GNUPG:] GOODSIG 0123456789ABCDEF fixture\n'
|
||||
'[GNUPG:] VALIDSIG '+'B'*40+' 2026-11-23 1 0 4 0 22 10 00 '+fingerprint+'\n')
|
||||
if '--armor' in argv and '--export' in argv: return 'synthetic public key'
|
||||
return ''
|
||||
completed=s.subprocess.CompletedProcess(['mock'],0,b'binary public fixture',b'')
|
||||
@@ -339,7 +345,9 @@ class SigningTests(unittest.TestCase):
|
||||
self.assertTrue((output.parent/'release-signing-key.asc').is_file())
|
||||
self.assertTrue(any(argv[0]=='/usr/bin/gpgv' for argv in calls))
|
||||
self.assertTrue(any('--pinentry-mode' in argv and '--armor' in argv and '--detach-sign' in argv for argv in calls))
|
||||
self.assertTrue(all(argv[0] in ('/usr/bin/gpg','/usr/bin/gpgv') for argv in calls))
|
||||
self.assertTrue(all(argv[0] in ('/usr/bin/gpg','/usr/bin/gpgv','/usr/bin/gpgconf') for argv in calls))
|
||||
stopped=[argv[2] for argv in calls if argv[0]=='/usr/bin/gpgconf' and argv[3:]==['--kill','all']]
|
||||
self.assertTrue(any(path.endswith('/secret') for path in stopped)) # The agent that held the key is stopped.
|
||||
|
||||
def test_linux_signature_and_public_key_bytes_are_bound_and_rechecked(self):
|
||||
package=self.root/'signed'; package.mkdir(); asset='photocraft-fixture-linux-x86_64-nightly.tar.gz'
|
||||
@@ -357,23 +365,35 @@ class SigningTests(unittest.TestCase):
|
||||
|
||||
def test_mac_system_verification_requires_developer_id_team_runtime_timestamp_and_staple(self):
|
||||
archive=self.root/'mac.zip'; archive.write_bytes(b'synthetic zip')
|
||||
details='Authority=Developer ID Application: Fixture\nTeamIdentifier=ABCDEFGHIJ\nTimestamp=Fixture\nCodeDirectory v=20500 flags=0x10000(runtime) hashes=fixture\n'
|
||||
details=('Identifier=ai.storyteller.photocraft.nightly\nAuthority=Developer ID Application: Fixture\nTeamIdentifier=ABCDEFGHIJ\n'
|
||||
'Timestamp=Fixture\nCodeDirectory v=20500 flags=0x10000(runtime) hashes=fixture\n')
|
||||
gatekeeper='/x/PhotoCraft Nightly.app: accepted\nsource=Notarized Developer ID\norigin=Developer ID Application: Fixture (ABCDEFGHIJ)\n'
|
||||
def process(argv,**kw):
|
||||
return 'arm64' if str(argv[0])=='/usr/bin/lipo' else ''
|
||||
def system(codesign,spctl):
|
||||
def run(argv,**kw):
|
||||
return s.subprocess.CompletedProcess(argv,0,(spctl if argv[0]=='/usr/sbin/spctl' else codesign).encode(),b'')
|
||||
return run
|
||||
env={**self.env,'NIGHTLY_APPLE_TEAM_ID':'ABCDEFGHIJ'}
|
||||
for index,bad in enumerate((details.replace('Developer ID Application:','Ad Hoc:'),details.replace('ABCDEFGHIJ','OTHERTEAM1'),
|
||||
details.replace('Timestamp=Fixture\n',''),details.replace('(runtime)','(adhoc)'))):
|
||||
completed=s.subprocess.CompletedProcess(['mock'],0,bad.encode(),b'')
|
||||
details.replace('Timestamp=Fixture\n',''),details.replace('(runtime)','(adhoc)'),
|
||||
details.replace('photocraft.nightly','photocraft'),details.replace('Identifier=ai.storyteller.photocraft.nightly\n',''))):
|
||||
with self.subTest(index=index),patch.object(s.u,'verify_archive'),patch.object(s,'command',side_effect=process),\
|
||||
patch.object(s.subprocess,'run',return_value=completed),self.assertRaisesRegex(ValueError,'Developer ID'):
|
||||
patch.object(s.subprocess,'run',side_effect=system(bad,gatekeeper)),self.assertRaisesRegex(ValueError,'Developer ID'):
|
||||
s.mac_verify(archive,self.case.prepared['version'],{},env,self.root/f'mac-payload{index}')
|
||||
completed=s.subprocess.CompletedProcess(['mock'],0,details.encode(),b'')
|
||||
# Exit 0 from spctl alone is not enough: Gatekeeper must say notarized, from the reviewed team.
|
||||
for index,bad in enumerate((gatekeeper.replace('Notarized Developer ID','Developer ID'),gatekeeper.replace('(ABCDEFGHIJ)','(OTHERTEAM1)'),
|
||||
gatekeeper.replace(': accepted',': rejected'),'')):
|
||||
with self.subTest(gatekeeper=index),patch.object(s.u,'verify_archive'),patch.object(s,'command',side_effect=process),\
|
||||
patch.object(s.subprocess,'run',side_effect=system(details,bad)),self.assertRaisesRegex(ValueError,'Gatekeeper'):
|
||||
s.mac_verify(archive,self.case.prepared['version'],{},env,self.root/f'mac-gatekeeper{index}')
|
||||
with patch.object(s.u,'verify_archive'),patch.object(s,'command',side_effect=process) as tools,\
|
||||
patch.object(s.subprocess,'run',return_value=completed):
|
||||
patch.object(s.subprocess,'run',side_effect=system(details,gatekeeper)) as system_tools:
|
||||
self.assertEqual(s.mac_verify(archive,self.case.prepared['version'],{},env,self.root/'mac-payload'),'ABCDEFGHIJ')
|
||||
self.assertEqual([call.args[0][0] for call in system_tools.call_args_list],['/usr/bin/codesign','/usr/sbin/spctl'])
|
||||
commands=[call.args[0] for call in tools.call_args_list]
|
||||
self.assertIn('--noextattr',commands[0]); self.assertIn('--norsrc',commands[0])
|
||||
self.assertTrue(any('stapler' in argv and 'validate' in argv for argv in commands))
|
||||
self.assertTrue(any(argv[0]=='/usr/sbin/spctl' for argv in commands))
|
||||
self.assertFalse(any(Path(str(argv[0])).name=='PhotoCraft' for argv in commands))
|
||||
|
||||
|
||||
@@ -420,7 +440,14 @@ class SigningWorkflowTests(unittest.TestCase):
|
||||
self.assertTrue('id: sign' in step,'actual secrets outside isolated signing step')
|
||||
|
||||
def test_final_signed_hash_and_receipt_rechecked_at_all_publish_boundaries(self):
|
||||
self.assertEqual(self.main.count('nightly_signing.py verify-receipt'),3)
|
||||
# Windows: stage, attest, publish. macOS: stage. Linux: stage receipt, then receipt plus
|
||||
# gpgv package recheck against reviewed source (main-route attestation/publication stay off).
|
||||
self.assertEqual(self.main.count('nightly_signing.py verify-receipt'),6)
|
||||
self.assertEqual(self.main.count('verify-receipt --platform macos-aarch64'),1)
|
||||
self.assertEqual(self.main.count('verify-receipt --platform linux-x86_64'),2)
|
||||
self.assertEqual(self.main.count('--package-directory .nightly-build-linux-x86_64 --source .'),1)
|
||||
self.assertEqual(self.main.count('artifact-ids: ${{ needs.build-linux.outputs.receipt-artifact-id }}'),1)
|
||||
self.assertEqual(self.main.count('artifact-ids: ${{ needs.build-macos.outputs.receipt-artifact-id }}'),1)
|
||||
self.assertEqual(self.main.count('artifact-ids: ${{ needs.build-windows.outputs.receipt-artifact-id }}'),3)
|
||||
self.assertIn('ZIP_SHA256: ${{ needs.build-windows.outputs.zip-sha256 }}',self.main)
|
||||
self.assertIn('UNSIGNED_SHA256: ${{ needs.build-windows.outputs.unsigned-sha256 }}',self.main)
|
||||
@@ -429,13 +456,48 @@ class SigningWorkflowTests(unittest.TestCase):
|
||||
self.assertIn('path: .nightly-signed/',signer)
|
||||
|
||||
def test_unix_native_guards_publish_and_attestation_remain_literal_off(self):
|
||||
for job in ('build-linux','build-macos','attest-nightly','publish-nightly'):
|
||||
for job in ('attest-nightly','publish-nightly'):
|
||||
self.assertIn('if: ${{ false }}',self.main.split(' '+job+':\n',1)[1].split(' needs:',1)[0])
|
||||
for job in ('linux','macos'):
|
||||
self.assertIn('if: ${{ false }}',self.unix.split(' '+job+':\n',1)[1].split(' needs:',1)[0])
|
||||
# Linux and macOS run only when the app caller opts in to production signing.
|
||||
for job in ('build-linux','build-macos'):
|
||||
self.assertIn("if: needs.identity.outputs.ready == 'true' && needs.identity.outputs.build == 'true' && inputs.production-signing == true",
|
||||
self.main.split(' '+job+':\n',1)[1].split(' uses:',1)[0])
|
||||
for job,platform in (('linux','linux-x86_64'),('linux-signing-config','linux-x86_64'),('sign-linux','linux-x86_64'),
|
||||
('macos','macos-aarch64'),('macos-signing-config','macos-aarch64'),('sign-macos','macos-aarch64')):
|
||||
block=self.unix.split(' '+job+':\n',1)[1].split(' steps:',1)[0].split(' uses:',1)[0]
|
||||
self.assertNotIn('${{ false }}',block)
|
||||
self.assertIn('inputs.production-signing == true',block)
|
||||
self.assertIn("inputs.platform == '"+platform+"'",block)
|
||||
self.assertIn('nightly_signing.py adapter --platform macos-aarch64',self.unix)
|
||||
self.assertNotIn('schedule:',self.main)
|
||||
|
||||
def test_public_signer_identities_are_reviewed_caller_source_never_repository_variables(self):
|
||||
for name in ('nightly.yml','nightly-windows.yml','nightly-unix.yml','nightly-signing-unix.yml','nightly-release.yml','nightly-unsigned.yml'):
|
||||
source=(ROOT/'.github/workflows'/name).read_text()
|
||||
self.assertNotIn('vars.NIGHTLY_APPLE_TEAM_ID',source)
|
||||
self.assertNotIn('vars.NIGHTLY_WINDOWS_PUBLISHER_SUBJECT',source)
|
||||
self.assertNotIn('vars.NIGHTLY_LINUX_SIGNING_FINGERPRINT',source)
|
||||
# Linux: reviewed caller input threaded to the presence check, the signer and the stage recheck.
|
||||
self.assertIn('linux-signing-fingerprint: ${{ inputs.linux-signing-fingerprint }}',self.main.split(' build-linux:\n',1)[1].split(' build-macos:\n',1)[0])
|
||||
self.assertIn('NIGHTLY_LINUX_SIGNING_FINGERPRINT: ${{ inputs.linux-signing-fingerprint }}',self.main.split(' stage-nightly:\n',1)[1])
|
||||
self.assertIn('FINGERPRINT: ${{ inputs.linux-signing-fingerprint }}',self.unix.split(' linux-signing-config:\n',1)[1].split(' macos-signing-config:\n',1)[0])
|
||||
self.assertIn('linux-signing-fingerprint: ${{ inputs.linux-signing-fingerprint }}',self.unix.split(' sign-linux:\n',1)[1].split(' sign-macos:\n',1)[0])
|
||||
self.assertIn('NIGHTLY_LINUX_SIGNING_FINGERPRINT: ${{ inputs.linux-signing-fingerprint }}',self.sign_unix.split(' linux:\n',1)[1].split(' macos:\n',1)[0])
|
||||
self.assertIn('linux-signing-fingerprint: 2B76741B414AAD6CD33E631213A005C0B9D7C3ED',(ROOT/'examples/photocraft-nightly.yml').read_text())
|
||||
# Windows: caller input threaded to the signer, its presence check and every main-route recheck.
|
||||
self.assertEqual(self.main.count('NIGHTLY_WINDOWS_PUBLISHER_SUBJECT: ${{ inputs.windows-publisher-subject }}'),3)
|
||||
self.assertIn('windows-publisher-subject: ${{ inputs.windows-publisher-subject }}',self.main.split(' build-windows:\n',1)[1].split(' build-linux:\n',1)[0])
|
||||
self.assertIn('PUBLISHER: ${{ inputs.windows-publisher-subject }}',self.windows)
|
||||
self.assertIn('NIGHTLY_WINDOWS_PUBLISHER_SUBJECT: ${{ inputs.windows-publisher-subject }}',self.windows)
|
||||
self.assertIn('NIGHTLY_APPLE_TEAM_ID: ${{ inputs.apple-team-id }}',self.main)
|
||||
self.assertIn('apple-team-id: ${{ inputs.apple-team-id }}',self.main.split(' build-macos:\n',1)[1].split(' status:\n',1)[0])
|
||||
self.assertIn('TEAM: ${{ inputs.apple-team-id }}',self.unix.split(' macos-signing-config:\n',1)[1])
|
||||
self.assertIn('apple-team-id: ${{ inputs.apple-team-id }}',self.unix.split(' sign-macos:\n',1)[1])
|
||||
self.assertIn('NIGHTLY_APPLE_TEAM_ID: ${{ inputs.apple-team-id }}',self.sign_unix.split(' macos:\n',1)[1])
|
||||
caller=(ROOT/'examples/photocraft-nightly.yml').read_text()
|
||||
self.assertIn('apple-team-id: REVIEWED_STABLE_APPLE_TEAM_ID_REQUIRED',caller)
|
||||
self.assertIn('windows-publisher-subject: REVIEWED_STABLE_WINDOWS_PUBLISHER_SUBJECT_REQUIRED',caller)
|
||||
|
||||
def test_required_app_signer_no_unsigned_fallback_and_no_leaf_pin(self):
|
||||
script=(ROOT/'scripts/nightly_signing_windows.ps1').read_text()
|
||||
self.assertIn('-Required -CheckOnly',script); self.assertIn('-Required -Files',script)
|
||||
|
||||
+94
-21
@@ -91,19 +91,45 @@ class UnixProducerTests(unittest.TestCase):
|
||||
return destination
|
||||
|
||||
def test_exact_owner_rows_do_not_change_windows_admission(self):
|
||||
for platform in u.CONTRACTS:
|
||||
result=u.pending_contract(self.pending,platform)
|
||||
self.assertFalse(result['feed_admitted']); self.assertFalse(result['runtime_qualified'])
|
||||
self.assertEqual(self.registry['apps']['photocraft']['targets'][0]['target'],{'os':'windows','arch':'x86_64','format':'portable_zip'})
|
||||
self.assertEqual(len(self.registry['apps']['photocraft']['targets']),1)
|
||||
mac=u.pending_contract(self.pending,'macos-aarch64')
|
||||
self.assertTrue(mac['feed_admitted']); self.assertEqual(mac['status'],'feed-admitted')
|
||||
self.assertFalse(mac['runtime_qualified']) # Admission is not runtime qualification.
|
||||
linux=u.pending_contract(self.pending,'linux-x86_64')
|
||||
self.assertTrue(linux['feed_admitted']); self.assertEqual(linux['status'],'feed-admitted')
|
||||
self.assertFalse(linux['runtime_qualified'])
|
||||
targets=self.registry['apps']['photocraft']['targets']
|
||||
self.assertEqual(targets[0]['target'],{'os':'windows','arch':'x86_64','format':'portable_zip'})
|
||||
self.assertEqual([row for row in targets if row['target']['os']=='macos'],[u.registry_target(mac)])
|
||||
self.assertEqual([row for row in targets if row['target']['os']=='linux'],[u.registry_target(linux)])
|
||||
self.assertTrue(all(not row['targets'] for name,row in self.registry['apps'].items() if name!='photocraft'))
|
||||
|
||||
def test_admitted_linux_row_must_match_the_feed_registry_exactly(self):
|
||||
self.assertTrue(self.check()['feed_admitted'])
|
||||
def linux_index(rows): return [row['target']['os'] for row in rows].index('linux')
|
||||
for mutate in (lambda rows:rows.pop(linux_index(rows)),
|
||||
lambda rows:rows[linux_index(rows)].update(asset_pattern='photocraft-{version}-linux-x86_64.tar.gz'),
|
||||
lambda rows:rows[linux_index(rows)]['isolation'].update(associations='stable'),
|
||||
lambda rows:rows.append(copy.deepcopy(rows[linux_index(rows)]))):
|
||||
registry=copy.deepcopy(self.registry); mutate(registry['apps']['photocraft']['targets'])
|
||||
with self.subTest(registry=registry['apps']['photocraft']['targets']),self.assertRaisesRegex(n.InvalidNightly,'feed registry|duplicate|target'):
|
||||
u.require_registry_admission(registry,'linux-x86_64',u.pending_contract(self.pending,'linux-x86_64'))
|
||||
|
||||
def test_a_pending_row_must_stay_out_of_the_feed_registry(self):
|
||||
pending=copy.deepcopy(self.pending); pending['capabilities']['linux-x86_64'].update(status='private-source-pending',feed_admitted=False)
|
||||
with patch.dict(u.ADMISSION,{'linux-x86_64':{'status':'private-source-pending','feed_admitted':False,'runtime_qualified':False}}):
|
||||
row=u.pending_contract(pending,'linux-x86_64')
|
||||
with self.assertRaisesRegex(n.InvalidNightly,'pending Unix target'):
|
||||
u.require_registry_admission(self.registry,'linux-x86_64',row)
|
||||
|
||||
def test_pending_admission_or_contract_mutations_are_refused(self):
|
||||
for section,key,value in [('', 'feed_admitted',True),('', 'runtime_qualified',True),('', 'status','ready'),
|
||||
for section,key,value in [('', 'feed_admitted',False),('', 'feed_admitted',1),('', 'runtime_qualified',True),('', 'status','ready'),('', 'status','private-source-pending'),
|
||||
('target','arch','aarch64'),('isolation','profile_version',True),('isolation','associations','stable')]:
|
||||
pending=copy.deepcopy(self.pending); row=pending['capabilities']['linux-x86_64']
|
||||
(row[section] if section else row)[key]=value
|
||||
with self.subTest(key=key),self.assertRaises(n.InvalidNightly): u.pending_contract(pending,'linux-x86_64')
|
||||
with self.subTest(key=key,value=value),self.assertRaises(n.InvalidNightly): u.pending_contract(pending,'linux-x86_64')
|
||||
for key,value in [('feed_admitted',False),('status','private-source-pending'),('runtime_qualified',True)]:
|
||||
pending=copy.deepcopy(self.pending); pending['capabilities']['macos-aarch64'][key]=value
|
||||
with self.subTest(mac=key),self.assertRaises(n.InvalidNightly): u.pending_contract(pending,'macos-aarch64')
|
||||
|
||||
def test_exact_source_identity_and_disjoint_nightly_leaf_without_writes(self):
|
||||
before=self.cargo.read_bytes(); original=copy.deepcopy(self.prepared)
|
||||
@@ -111,7 +137,7 @@ class UnixProducerTests(unittest.TestCase):
|
||||
result=self.check()
|
||||
self.assertEqual(result['target_leaf'],str(self.root/'targets/nightly-v1/linux-x86_64'))
|
||||
self.assertEqual(result['asset'],u.CONTRACTS['linux-x86_64']['asset_pattern'].replace('{version}',self.version))
|
||||
self.assertFalse(result['feed_admitted']); self.assertTrue(result['private_only'])
|
||||
self.assertTrue(result['feed_admitted']); self.assertFalse(result['private_only']); self.assertFalse(result['runtime_qualified'])
|
||||
self.assertEqual(self.cargo.read_bytes(),before); self.assertEqual(self.prepared,original)
|
||||
self.assertFalse((self.root/'targets').exists()); self.assertFalse((self.root/'dist').exists())
|
||||
|
||||
@@ -129,14 +155,26 @@ class UnixProducerTests(unittest.TestCase):
|
||||
(self.root/'link').symlink_to(self.root,target_is_directory=True)
|
||||
with self.assertRaises(n.InvalidNightly): self.check(target_base=self.root/'link')
|
||||
|
||||
def test_mac_planning_is_not_permission_to_build_or_extract(self):
|
||||
def test_admitted_mac_builds_and_extracts_privately_but_is_never_signature_proof(self):
|
||||
result=self.check(platform='macos-aarch64')
|
||||
self.assertFalse(result['feed_admitted'])
|
||||
with self.assertRaises(n.Unavailable): u.require_build_policy('macos-aarch64')
|
||||
archive=self.mac(); output=self.root/'no-mac-extraction'
|
||||
with patch.object(n,'regular_file',side_effect=AssertionError('unavailable Mac extraction must not open an archive')):
|
||||
with self.assertRaises(n.Unavailable): u.verify_archive(self.pending,'macos-aarch64',archive,self.version,output)
|
||||
self.assertFalse(output.exists())
|
||||
self.assertTrue(result['feed_admitted']); self.assertFalse(result['runtime_qualified']); self.assertFalse(result['private_only'])
|
||||
self.assertIsNone(u.require_build_policy('macos-aarch64'))
|
||||
with self.assertRaises(n.InvalidNightly): u.require_build_policy('freebsd-x86_64')
|
||||
archive=self.mac(); output=self.root/'mac-extraction'
|
||||
unpacked=u.verify_archive(self.pending,'macos-aarch64',archive,self.version,output)
|
||||
self.assertFalse(unpacked['signature_verified']); self.assertFalse(unpacked['runtime_qualified'])
|
||||
self.assertTrue((output/'PhotoCraft Nightly.app/Contents/MacOS/PhotoCraft').is_file())
|
||||
|
||||
def test_admitted_mac_row_must_match_the_feed_registry_exactly(self):
|
||||
for mutate in (lambda rows:[rows.remove(row) for row in list(rows) if row['target']['os']=='macos'],
|
||||
lambda rows:[row.update(asset_pattern='photocraft-{version}-macos-aarch64.zip') for row in rows if row['target']['os']=='macos'],
|
||||
lambda rows:rows.append(copy.deepcopy(rows[-1]))):
|
||||
registry=copy.deepcopy(self.registry); mutate(registry['apps']['photocraft']['targets'])
|
||||
with self.subTest(mutate=mutate),self.assertRaises(n.InvalidNightly):
|
||||
u.require_registry_admission(registry,'macos-aarch64',u.pending_contract(self.pending,'macos-aarch64'))
|
||||
for key,value in [('feed_admitted',False),('status','private-source-pending'),('runtime_qualified',True),('feed_admitted',1)]:
|
||||
pending=copy.deepcopy(self.pending); pending['capabilities']['macos-aarch64'][key]=value
|
||||
with self.subTest(mac=key),self.assertRaises(n.InvalidNightly): u.pending_contract(pending,'macos-aarch64')
|
||||
|
||||
def test_literal_version_output_only_normalizes_line_endings(self):
|
||||
for end in ('\n','\r\n','\r'): u.verify_version_output(f'PhotoCraft {self.version} (nightly-v1)'+end,self.version)
|
||||
@@ -260,12 +298,28 @@ class UnixWorkflowTests(unittest.TestCase):
|
||||
|
||||
def test_native_workflows_are_explicitly_disabled_and_do_not_publish_or_sign(self):
|
||||
source=(ROOT/'.github/workflows/nightly-unix.yml').read_text()
|
||||
for job in ('git-sources', 'linux', 'macos', 'linux-signing-config', 'macos-signing-config'):
|
||||
for job in ('git-sources', 'linux', 'linux-signing-config', 'macos', 'macos-signing-config'):
|
||||
block=source.split(' '+job+':\n',1)[1].split(' steps:',1)[0]
|
||||
self.assertIn('if: ${{ false }}',block)
|
||||
self.assertNotIn('${{ false }}',block)
|
||||
self.assertIn("inputs.production-signing == true && inputs.app-name == 'photocraft' && github.repository == 'storytold/photocraft' &&",block)
|
||||
self.assertIn("github.ref == 'refs/heads/main'",block)
|
||||
if job!='git-sources': self.assertIn("inputs.platform == '"+('linux-x86_64' if job.startswith('linux') else 'macos-aarch64')+"' && ",block)
|
||||
for job in ('linux', 'macos'):
|
||||
self.assert_unprivileged_build(source,job)
|
||||
for forbidden in ('secrets:','contents: write','packages: write','schedule:','workflow_dispatch:','cargo xtask version set','--skip-build','--ad-hoc','import-cert.sh','publish_nightly.py'):
|
||||
# The only secrets are the six stable Apple names and LINUX_SIGNING_KEY: declared, presence-checked
|
||||
# in the environment job, and forwarded explicitly to the isolated signer; never to the build.
|
||||
apple=['APPLE_CERTIFICATE','APPLE_CERTIFICATE_PASSWORD','KEYCHAIN_PASSWORD','APPLE_ID','APPLE_PASSWORD','APPLE_TEAM_ID']
|
||||
self.assertEqual(sorted(set(re.findall(r'secrets\.([A-Z_]+)',source))-{'LINUX_SIGNING_KEY'}),sorted(apple))
|
||||
self.assertNotIn('secrets.',source.split(' macos:\n',1)[1].split(' linux-signing-config:\n',1)[0])
|
||||
forwarded=source.split(' sign-macos:\n',1)[1]
|
||||
self.assertEqual(re.findall(r'^ ([A-Z_]+): \$\{\{ secrets\.([A-Z_]+) \}\}',forwarded,re.M),[(name,name) for name in apple])
|
||||
names=[name for name in re.findall(r'secrets\.[A-Z_]+',source) if not name.startswith(('secrets.APPLE_','secrets.KEYCHAIN_'))]
|
||||
self.assertEqual(names,['secrets.LINUX_SIGNING_KEY','secrets.LINUX_SIGNING_KEY'])
|
||||
self.assertIn('secrets.LINUX_SIGNING_KEY',source.split(' linux-signing-config:\n',1)[1].split(' macos-signing-config:\n',1)[0])
|
||||
self.assertIn('secrets.LINUX_SIGNING_KEY',source.split(' sign-linux:\n',1)[1].split(' sign-macos:\n',1)[0])
|
||||
self.assertIn("LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY != '' }}",source)
|
||||
self.assertNotIn('secrets: inherit',source)
|
||||
for forbidden in ('contents: write','packages: write','schedule:','workflow_dispatch:','cargo xtask version set','--skip-build','--ad-hoc','import-cert.sh','publish_nightly.py'):
|
||||
self.assertNotIn(forbidden,source)
|
||||
self.assertIn('uses: $/.github/workflows/nightly-signing-unix.yml', source)
|
||||
self.assertIn('ref: ${{ github.sha }}',source)
|
||||
@@ -279,14 +333,33 @@ class UnixWorkflowTests(unittest.TestCase):
|
||||
self.assertIn('--version',source)
|
||||
self.assertIn('private-nightly-smoke-',source)
|
||||
|
||||
def test_linux_secret_is_explicitly_forwarded_at_every_boundary_and_used_only_to_sign(self):
|
||||
main=(ROOT/'.github/workflows/nightly.yml').read_text()
|
||||
unix=(ROOT/'.github/workflows/nightly-unix.yml').read_text()
|
||||
signer=(ROOT/'.github/workflows/nightly-signing-unix.yml').read_text()
|
||||
for source in (main,unix,signer):
|
||||
declarations=source.split(' workflow_call:\n',1)[1].split(' inputs:',1)[0]
|
||||
self.assertIn(' LINUX_SIGNING_KEY:\n required: false\n',declarations)
|
||||
self.assertNotIn('secrets: inherit',source)
|
||||
linux=signer.split(' linux:\n',1)[1].split(' macos:\n',1)[0]
|
||||
holders=[step for step in re.split(r'(?=^ - )',linux,flags=re.M) if 'secrets.' in step]
|
||||
self.assertEqual(len(holders),1)
|
||||
self.assertIn('LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }}',holders[0])
|
||||
self.assertIn('nightly_signing.py sign --platform linux-x86_64',holders[0])
|
||||
self.assertIn(' environment: nightly-signing\n',linux)
|
||||
|
||||
def test_existing_dry_run_mac_exclusion_is_not_new_coverage_or_target_admission(self):
|
||||
release=(ROOT/'.github/workflows/release.yml').read_text()
|
||||
mac=release.split(' macos:\n',1)[1].split(' windows:\n',1)[0]
|
||||
self.assertIn('if: ${{ !inputs.dry-run }}',mac)
|
||||
source=(ROOT/'.github/workflows/nightly.yml').read_text()
|
||||
for platform,next_job in [('linux','macos'),('macos','status')]:
|
||||
section=source.split(' build-'+platform+':\n',1)[1].split(' '+('build-'+next_job if next_job!='status' else 'status')+':\n',1)[0]
|
||||
self.assertIn('if: ${{ false }}',section)
|
||||
linux=source.split(' build-linux:\n',1)[1].split(' build-macos:\n',1)[0]
|
||||
self.assertIn("if: needs.identity.outputs.ready == 'true' && needs.identity.outputs.build == 'true' && inputs.production-signing == true",linux)
|
||||
self.assertIn('LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }}',linux)
|
||||
self.assertNotIn('APPLE_',linux); self.assertNotIn('WINDOWS_',linux)
|
||||
section=source.split(' build-macos:\n',1)[1].split(' status:\n',1)[0]
|
||||
self.assertIn("if: needs.identity.outputs.ready == 'true' && needs.identity.outputs.build == 'true' && inputs.production-signing == true",section)
|
||||
self.assertNotIn('WINDOWS_',section); self.assertNotIn('LINUX_',section)
|
||||
self.assertIn('skipped native jobs are not platform coverage',source)
|
||||
self.assertIn('if: ${{ false }}',source.split(' publish-nightly:\n',1)[1])
|
||||
stage=source.split(' stage-nightly:\n',1)[1].split(' publish-nightly:\n',1)[0]
|
||||
|
||||
@@ -17,6 +17,7 @@ from unittest.mock import patch
|
||||
import zipfile
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "scripts"))
|
||||
spec = importlib.util.spec_from_file_location("nightly_feed", ROOT / "scripts/nightly_feed.py")
|
||||
n = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(n)
|
||||
@@ -33,7 +34,11 @@ class WindowsCandidateTests(unittest.TestCase):
|
||||
self.root = Path(self.temp.name).resolve()
|
||||
ownership = patch.dict(os.environ, {"GITHUB_WORKSPACE": str(ROOT.resolve()), "RUNNER_TEMP": str(self.root)})
|
||||
ownership.start(); self.addCleanup(ownership.stop)
|
||||
self.registry = json.loads((ROOT / "nightly-apps.json").read_text())
|
||||
# Frozen Windows-only E3/E4 local packet path; the live registry also admits macOS.
|
||||
self.live_registry = json.loads((ROOT / "nightly-apps.json").read_text())
|
||||
self.registry = copy.deepcopy(self.live_registry)
|
||||
self.registry["apps"]["photocraft"]["targets"] = [row for row in self.registry["apps"]["photocraft"]["targets"]
|
||||
if row["target"]["os"] == "windows"]
|
||||
self.context = {"GITHUB_EVENT_NAME": "workflow_dispatch", "GITHUB_REF": "refs/heads/main",
|
||||
"GITHUB_REPOSITORY": "storytold/photocraft", "GITHUB_SHA": "a" * 40,
|
||||
"GITHUB_RUN_ID": "1234", "GITHUB_RUN_ATTEMPT": "1"}
|
||||
@@ -67,9 +72,20 @@ class WindowsCandidateTests(unittest.TestCase):
|
||||
golden = json.loads((ROOT / "tests/fixtures/photocraft-windows-x86_64-target.json").read_text())
|
||||
self.assertEqual(golden, expected)
|
||||
self.assertEqual(w.PHOTO_TARGET, golden)
|
||||
self.assertEqual(self.registry["apps"]["photocraft"]["targets"], [golden])
|
||||
self.assertEqual(len(self.registry["apps"]), 19)
|
||||
self.assertTrue(all(not row["targets"] for app, row in self.registry["apps"].items() if app != "photocraft"))
|
||||
live = self.live_registry["apps"]["photocraft"]["targets"]
|
||||
self.assertEqual([row for row in live if row["target"]["os"] == "windows"], [golden])
|
||||
self.assertEqual(sorted(row["target"]["os"] for row in live), ["linux", "macos", "windows"])
|
||||
self.assertEqual(len(self.live_registry["apps"]), 19)
|
||||
self.assertTrue(all(not row["targets"] for app, row in self.live_registry["apps"].items() if app != "photocraft"))
|
||||
# The Windows adapter accepts its exact row beside reviewed platform rows, never a changed one.
|
||||
self.check(registry=self.live_registry)
|
||||
changed = copy.deepcopy(self.live_registry)
|
||||
for row in changed["apps"]["photocraft"]["targets"]:
|
||||
if row["target"]["os"] == "macos": row["isolation"]["associations"] = "stable"
|
||||
with self.assertRaises(n.InvalidNightly): self.check(registry=changed)
|
||||
changed = copy.deepcopy(self.live_registry)
|
||||
changed["apps"]["photocraft"]["targets"].append(copy.deepcopy(golden))
|
||||
with self.assertRaises(n.InvalidNightly): self.check(registry=changed)
|
||||
|
||||
def test_preflight_returns_only_fixed_build_metadata_without_source_mutation(self):
|
||||
before = self.cargo.read_bytes()
|
||||
|
||||
Reference in new issue
Block a user