Harden nightly artifact and publication boundaries

Correct review findings across signing handoffs, artifact transport, policy evidence, extraction and publisher receipts. Pause privileged legacy diagnostics without changing stable releases. Keep pruning disabled and record quota-bounded proof work as an activation prerequisite.
This commit is contained in:
skylartaylor committed 2026-11-22 05:45:36 +01:00
1 parent 1a6d3ad609
commit eddc138cd2
37 files changed
+1004 -178

No files matched your search

+2 -22
View File
@@ -1,4 +1,4 @@
name: Independent legacy nightly diagnostics (not installable)
name: Independent nightly metadata (legacy packaging paused)
# Separate workflow RUN. Never called by the Photo installable producer.
on:
workflow_call:
@@ -99,24 +99,4 @@ jobs:
- name: Explain independent diagnostic trust and scope
run: |
echo 'Diagnostic-only metadata, ready=false. No publication policy/API catalog or installable adapter is required.' >> "$GITHUB_STEP_SUMMARY"
echo 'Legacy mutable helper actions and write-permission ceiling remain isolated in this separate diagnostic run.' >> "$GITHUB_STEP_SUMMARY"
diagnostic:
needs: metadata
permissions:
contents: write
packages: write
uses: $/.github/workflows/release.yml
with:
app-name: ${{ inputs.app-name }}
app-title: ${{ inputs.app-title }}
version: ${{ needs.metadata.outputs.version }}
craft-fonts-ref: ${{ inputs.craft-fonts-ref }}
web-craft-fonts: ${{ inputs.web-craft-fonts }}
contributors-artifact: ${{ inputs.contributors-artifact }}
has-web: ${{ inputs.has-web }}
has-riscv64: ${{ inputs.has-riscv64 }}
has-freebsd: ${{ inputs.has-freebsd }}
has-arch: ${{ inputs.has-arch }}
has-server: ${{ inputs.has-server }}
dry-run: true
publish: false
echo 'Legacy packaging diagnostics are paused until Flatpak packaging can run without package-write permission.' >> "$GITHUB_STEP_SUMMARY"
@@ -63,6 +63,10 @@ jobs:
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:
@@ -160,6 +164,7 @@ jobs:
id: upload
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9
with:
include-hidden-files: true
name: signed-nightly-linux-x86_64-${{ github.run_id }}-${{ github.run_attempt }}
path: .nightly-signed/*
if-no-files-found: error
@@ -168,6 +173,7 @@ jobs:
id: receipt
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9
with:
include-hidden-files: true
name: nightly-signing-linux-x86_64-${{ github.run_id }}-${{ github.run_attempt }}
path: .nightly-signing/nightly-signing.json
if-no-files-found: error
@@ -293,6 +299,7 @@ jobs:
id: upload
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9
with:
include-hidden-files: true
name: signed-nightly-macos-aarch64-${{ github.run_id }}-${{ github.run_attempt }}
path: .nightly-signed/*
if-no-files-found: error
@@ -301,6 +308,7 @@ jobs:
id: receipt
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9
with:
include-hidden-files: true
name: nightly-signing-macos-aarch64-${{ github.run_id }}-${{ github.run_attempt }}
path: .nightly-signing/nightly-signing.json
if-no-files-found: error
+4
View File
@@ -102,6 +102,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:
+19
View File
@@ -4,6 +4,23 @@ name: Private nightly Windows artifact
# Deliberate extraction of the existing Windows setup, NOT a full release matrix.
on:
workflow_call:
secrets:
WINDOWS_CERTIFICATE:
required: false
WINDOWS_CERTIFICATE_PASSWORD:
required: false
AZURE_TENANT_ID:
required: false
AZURE_CLIENT_ID:
required: false
AZURE_CLIENT_SECRET:
required: false
AZURE_SIGNING_ENDPOINT:
required: false
AZURE_SIGNING_ACCOUNT:
required: false
AZURE_CERT_PROFILE:
required: false
inputs:
tooling-revision:
description: "Reviewed published shared-tooling SHA; must match the app-owned publication policy"
@@ -447,6 +464,7 @@ jobs:
id: upload
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9
with:
include-hidden-files: true
name: signed-nightly-windows-x86_64-${{ github.run_id }}-${{ github.run_attempt }}
path: .nightly-signed/${{ steps.contract.outputs.asset }}
if-no-files-found: error
@@ -455,6 +473,7 @@ jobs:
id: receipt
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9
with:
include-hidden-files: true
name: nightly-signing-windows-x86_64-${{ github.run_id }}-${{ github.run_attempt }}
path: .nightly-signing/nightly-signing.json
if-no-files-found: error
+37 -2
View File
@@ -2,6 +2,23 @@ name: Dedicated Photo nightly producer (private source)
# GitHub.com only. Protected isolated signing; no diagnostic matrix or enabled schedule.
on:
workflow_call:
secrets:
WINDOWS_CERTIFICATE:
required: false
WINDOWS_CERTIFICATE_PASSWORD:
required: false
AZURE_TENANT_ID:
required: false
AZURE_CLIENT_ID:
required: false
AZURE_CLIENT_SECRET:
required: false
AZURE_SIGNING_ENDPOINT:
required: false
AZURE_SIGNING_ACCOUNT:
required: false
AZURE_CERT_PROFILE:
required: false
inputs:
force:
type: boolean
@@ -109,6 +126,7 @@ jobs:
id: upload
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
include-hidden-files: true
name: nightly-identity-${{ github.run_id }}-${{ github.run_attempt }}
path: .nightly-input/*
if-no-files-found: error
@@ -127,6 +145,15 @@ jobs:
identity-artifact-id: ${{ needs.identity.outputs.artifact-id }}
identity-sha256: ${{ needs.identity.outputs.sha256 }}
craft-fonts-ref: ${{ inputs.craft-fonts-ref }}
secrets:
WINDOWS_CERTIFICATE: ${{ secrets.WINDOWS_CERTIFICATE }}
WINDOWS_CERTIFICATE_PASSWORD: ${{ secrets.WINDOWS_CERTIFICATE_PASSWORD }}
AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }}
AZURE_SIGNING_ENDPOINT: ${{ secrets.AZURE_SIGNING_ENDPOINT }}
AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }}
AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }}
build-linux:
if: ${{ false }} # Pending native source, never tuple admission or execution authority.
@@ -160,7 +187,7 @@ jobs:
status:
if: always()
needs: [identity, build-windows, build-linux, build-macos]
needs: [identity, build-windows, build-linux, build-macos, stage-nightly]
runs-on: ubuntu-latest
timeout-minutes: 5
permissions:
@@ -170,11 +197,13 @@ jobs:
env:
IDENTITY_RESULT: ${{ needs.identity.result }}
WINDOWS_RESULT: ${{ needs.build-windows.result }}
STAGING_RESULT: ${{ needs.stage-nightly.result }}
BUILD_REQUESTED: ${{ needs.identity.outputs.build }}
run: |
{
echo '## Dedicated nightly source candidate'
printf 'Identity/preflight: `%s`. Windows build: `%s`. Build requested: `%s`.\n' "$IDENTITY_RESULT" "$WINDOWS_RESULT" "$BUILD_REQUESTED"
printf 'Packet staging: `%s`.\n' "$STAGING_RESULT"
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.'
@@ -182,7 +211,10 @@ jobs:
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 ]; then test "$WINDOWS_RESULT" = success; fi
if [ "$BUILD_REQUESTED" = true ]; then
test "$WINDOWS_RESULT" = success
test "$STAGING_RESULT" = success
fi
stage-nightly:
if: >-
@@ -322,6 +354,7 @@ jobs:
id: upload
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
include-hidden-files: true
name: nightly-packet-${{ github.run_id }}-${{ github.run_attempt }}
path: .nightly-publish/*
if-no-files-found: error
@@ -590,6 +623,7 @@ jobs:
id: ownership-upload
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
include-hidden-files: true
name: ${{ steps.publish.outputs.ownership-artifact-name }}
path: .nightly-ownership/ownership.json
if-no-files-found: error
@@ -614,6 +648,7 @@ jobs:
id: prune-plan-upload
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
include-hidden-files: true
name: nightly-prune-plan-${{ github.run_id }}-${{ github.run_attempt }}
path: .nightly-prune-plan/plan.json
if-no-files-found: error
+22 -9
View File
@@ -41,7 +41,8 @@ is not authority to activate any of them.
5. A refresh must call `validate_baseline_refresh(previous, updated, policy, api)` with
the actual previously approved immutable v2 snapshot, then preserve that review
history. Never substitute a candidate's claimed previous document. Coverage
changes require an explicit separate policy migration and equivalence review;
changes, including managed-check additions/removals or workflow replacements,
require an explicit separate policy migration and equivalence review;
they cannot pass through the normal refresh helper. The setup controller must
enforce this helper; the runtime has no trusted policy-history storage itself.
The helper authenticates up to 20 intervening first-parent main revisions,
@@ -97,11 +98,14 @@ authenticated responses, never these values.
`required_checks` is the complete covered independent Actions job inventory,
including jobs reviewed red: it is **not** a candidate-derived ignore list.
Names must be unique; each is additionally authenticated through the exact job's
Names must be unique within each authenticated workflow; equal display names
in different workflow IDs are distinct obligations. Each is additionally authenticated through the exact job's
`check_run_url`, the check ID/app ID/source, the run/attempt, workflow ID/path/blob,
trusted repository and main event. There may be 1–128 jobs and 1–32 workflows.
Each baseline job/check ID appears once. Baseline results are only `success` or
`failure`, and `success` mandates `green_required: true`.
Each baseline job/check ID appears once. Ordinary baseline results are only
`success` or `failure`, and `success` mandates `green_required: true`. The sole
reviewed `skipped` exception is the explicit `manual-input-only` adapter described
below; it does not count as passing coverage.
The prepared policy adds `quality_policy_sha256` (64 lowercase hex characters)
to the existing exact v6 policy fields. The identity/feed format is unchanged.
@@ -114,8 +118,12 @@ old published policies need not match a newer reviewed config to prove ordering.
Every preflight and both existing publication guards reconstruct a fresh witness
through the authenticated fixed-host transport. No untrusted witness JSON is
accepted. The witness is bounded to 256 GET requests and a 120-second collection
accepted. The witness is bounded to 640 GET requests and a 120-second collection
budget (plus existing transport timeouts; preflight retains its real alarm).
Counted 32-workflow/128-job two-SHA synthetic paths used 607/617 GETs, including
final rechecks. Excessive history still refuses. This per-witness cap does not
prove the combined preflight/publication flow fits the repository's hourly API
quota; a refusal is never permission to skip authentication.
Inventories use pages of 20, at most 20 pages each, with stable exact integer
`total_count`, complete final-page coverage and duplicate-ID rejection. The
attempt-history bound is 20 attempts per run; hitting any bound refuses rather
@@ -142,7 +150,11 @@ job without throwing away its other passing job obligations.
| missing/unknown/unreviewed skipped/pending/cancelled | any | any | refuse |
Historical successful jobs on either exact main revision (all bounded trusted runs
and attempts, exact-ID check reads) also set the live green floor. A later red
and attempts, exact-ID check reads) also set the live green floor, including
completed successful jobs in a cancelled or partial historical attempt. Unknown
or incomplete historical jobs grant no positive evidence; selected baseline and
candidate runs still require their complete inventory and aggregate validation.
A later red
rerun cannot hide an earlier successful main result. A refresh must preserve every
previous `green_required` bit; when its new baseline succeeds the bit must become
true. Authenticated refresh history prevents jumping over a recovered main revision,
@@ -158,8 +170,9 @@ workflow ID. There is intentionally no general skip/neutral/external allowlist.
At the end, select the latest roots again (no rerun/run-number race), check witness
expiry again, and re-read main at the exact candidate SHA. The final publication
guard rechecks main again immediately before the preserved last active-producer
read. The existing serialized final same-head checks remain. GitHub offers no
guard rechecks main, then the active producer, then the newest producer run as
its final remote observation. A no-API baseline-expiry check follows that read.
The existing serialized final same-head checks remain. GitHub offers no
atomic transaction spanning these reads and a release mutation: a subsequent
administrator change remains a cooperative race, not an atomic lock guarantee.
@@ -189,7 +202,7 @@ Focused local command (run through the normal task allocator with 1 GiB and SSD
TMPDIR):
```
python3 -m unittest discover -s candidate/craft-common-actions/tests -p 'test_nightly_policy*.py' -v
python3 -B -m unittest discover -s tests -p 'test_nightly_policy*.py' -v
```
These are synthetic/API-fake regression and adversarial tests, not authenticated
+9 -7
View File
@@ -9,13 +9,15 @@ uses the app-owned `packaging/windows/package.ps1 -Arch x64 -Nightly` entry.
PHOTOCRAFT_BUILD_CHANNEL=nightly-v1 and the validated prepared identity version
are explicit build-step env; the script owns the locked HEIF-enabled compiler,
GUI-only packaging, licenses and flavor checks. No stable dry-run ZIP is used.
The existing release.yml is byte-identical. When the source/tooling/stable-base
key changes or manual force is requested, its full diagnostic dry-run still runs
for Photo (including MSI/other-OS release-breakage guards). Unchanged-source skip
covers both diagnostics and native packages; the isolated nightly build is
additional, never a replacement. Status reports
both results and requires diagnostic success plus registered-nightly success.
No stable release mode is changed.
The existing release.yml is byte-identical. The installable producer never calls
it or combines diagnostic results with its status. The independent
`nightly-diagnostics.yml` workflow currently validates metadata only: its legacy
packaging call is paused because Flatpak packaging would otherwise receive a
package-write token even during a dry run. MSI/other-OS legacy packaging coverage
is not provided by this metadata-only workflow. Restoring it requires a separate
read-only packaging/privileged publication split in the stable workflow.
Unchanged-source skip applies only to the installable producer. No stable release
mode is changed.
Staging only downloads this run's exact dedicated nightly Windows artifact.
nightly_feed.build_feed and stage_feed are local filesystem-only functions.
+15 -4
View File
@@ -42,11 +42,13 @@ The commands below are **not run live by this work**:
```text
python3 scripts/nightly_prune.py plan --registry nightly-apps.json --app photocraft --current-release-id RELEASE_ID --bot-id BOT_ID --config ownership-policy.json
python3 scripts/nightly_prune.py apply --registry nightly-apps.json --app photocraft --current-release-id RELEASE_ID --bot-id BOT_ID --config ownership-policy.json --plan prune-plan.json --checkpoint prune-checkpoint.json --approve-first-run
python3 scripts/nightly_prune.py apply --registry nightly-apps.json --app photocraft --current-release-id RELEASE_ID --bot-id BOT_ID --config ownership-policy.json --plan prune-plan.json --checkpoint prune-checkpoint.json --checkpoint-artifact-id CHECKPOINT_ARTIFACT_ID --checkpoint-artifact-sha256 CHECKPOINT_ARTIFACT_SHA256 --approve-first-run
```
Save plan stdout to `prune-plan.json` before apply. The exact plan and its
immutable Actions artifact must be preserved on failure. The integrated CLI
Save plan stdout to `prune-plan.json`, then upload those exact bytes as the
trusted checkpoint artifact in the current run and attempt before apply. Pass its
exact artifact ID and digest from that trusted upload step, not values claimed by
the plan. The exact plan and immutable Actions artifact must be preserved on failure. The integrated CLI
accepts only a checkpoint authenticated to its **current run and attempt**.
A later Actions attempt/run cannot resume the original checkpoint. A fresh
plan enumerates releases, not orphan refs, and cannot rediscover a release
@@ -61,12 +63,21 @@ authenticated cross-attempt recovery/recheckpoint route and a full
CLI/checkpoint boundary regression have landed and been reviewed. This is an
additional implementation prerequisite before the separately approved first
live publication/pruning timing, not a request to change the keep-seven policy.
A quota-bounded ownership frontier/deletion batch is also required: the offline
49-history proof-path regression needs 1,404 authenticated requests before the
first DELETE, exceeding a normal 1,000-request/hour repository token quota.
Do not enable the current full-reproof algorithm or weaken candidate ownership
checks to make it fit. This quota design is a separate owned follow-up, not a
performance fix claimed by the current correction.
## Receipt emitted by the publisher owner
Only after exclusive ref creation returned **201**, exact ref readback, draft
asset digest verification, successful publication and final ref verification,
write a single `ownership.json` with these exact fields:
finish writing a single `ownership.json` with these exact fields. The publisher
reserves its new directory and opens the exclusive output file before its first
API mutation. A receipt failure after confirmed publication exits with a distinct
reconciliation error; it must never trigger a second publication/create attempt:
```json
{
@@ -36,7 +36,7 @@ Before activation, publisher/user must configure these exact values from indepen
- `NIGHTLY_REVIEWED_POLICY_SHA256`: canonical digest of independently reviewed `.github/nightly-publication-policy.json` v2 policy. Its baseline must be current main or immediate first parent, fresh within24h, with authenticated complete job/check identities and a retained monotone green-floor review history. Never set it by blindly hashing candidate-controlled policy in the same untrusted run. Manual-input-only skipped jobs and the external Sonar app now have bounded reviewed applicability adapters; the exact fresh policy still needs review and unknown checks remain blocked.
- `NIGHTLY_BOT_ID`: authenticated numeric release bot actor ID, matching the reviewed `.github/nightly-pruning-policy.json` ownership policy. That file additionally binds actual numeric repository/workflow IDs, exact caller workflow/publish job/Publish and Upload nightly ownership receipt step names, reusable tooling workflow path and reviewed historical tooling SHAs. Example IDs in documentation are not deployable values. No caller-controlled body/login/string becomes deletion authority.
Caller-side environment secrets are resolved by the callee’s explicit `environment: nightly-signing`; no blanket secret forwarding is required. Do not assume environment-only values are available to a caller that merely forwards `secrets.NAME`. Keep actual key values scoped to the protected signing step, and verify the protected environment/configuration context on the hosted run.
The callee’s explicit `environment: nightly-signing` selects the protected environment, but does not replace named forwarding: each caller must pass the permitted names, and each called workflow must declare them. The app caller and `nightly.yml` explicitly forward only `WINDOWS_CERTIFICATE`, `WINDOWS_CERTIFICATE_PASSWORD`, `AZURE_TENANT_ID`, `AZURE_CLIENT_ID`, `AZURE_CLIENT_SECRET`, `AZURE_SIGNING_ENDPOINT`, `AZURE_SIGNING_ACCOUNT` and `AZURE_CERT_PROFILE`. There is no blanket `secrets: inherit`. GitHub supports forwarding a name that exists only in the callee job’s environment; omitting that handoff resolves it to an empty string. Audit name scopes without reading values, and stop for review if same-name repository/organization secrets could expose a fallback to compiler jobs; never implicitly move/delete stable secrets. Keep key values out of compiler processes and verify the protected environment/configuration context on the hosted run. See [GitHub’s current reusable-workflow documentation](https://docs.github.com/en/actions/how-tos/reuse-automations/reuse-workflows#passing-inputs-and-secrets-to-a-reusable-workflow).
## First manual run remains off
+11 -4
View File
@@ -54,10 +54,17 @@ normal human review. Decide reviewer/automation policy before enabling any
schedule: protected configuration and signer jobs can require separate reviews.
Do not remove protection merely to make scheduled runs unattended.
The callee signing job explicitly names this environment. GitHub resolves its
environment secrets there; no blanket `secrets: inherit` and no caller-secret
forwarding is required for this design. See GitHub's reusable-workflow docs,
“Passing inputs and secrets to a reusable workflow”, environment-secret warning.
The callee signing job explicitly names this environment. Each reusable-workflow
boundary must also declare and explicitly forward the permitted secret names;
without that handoff, GitHub resolves an environment-only secret to an empty
string. The Windows recipe forwards only the PFX pair and six Azure names at
both app → nightly and nightly → Windows boundaries. Do not use blanket
`secrets: inherit`. Future Unix caller qualification must include its own explicit
named contract. See [GitHub's reusable-workflow secret rules](https://docs.github.com/en/actions/how-tos/reuse-automations/reuse-workflows#passing-inputs-and-secrets-to-a-reusable-workflow).
Before activation, audit secret-name scopes without reading values: same-name
repository/organization secrets must not leak into compiler jobs through this
contract. Stop and review any collision; do not delete or migrate existing stable
signing secrets implicitly.
Actual secret values appear only in each platform's signing step, not workflow
or job env, checkout/build/smoke steps, or downstream publishing jobs.
+2 -3
View File
@@ -8,12 +8,11 @@ permissions: {}
jobs:
diagnostic:
permissions:
contents: write
packages: write
contents: read
uses: storytold/craft-common-actions/.github/workflows/nightly-diagnostics.yml@REVIEWED_PUBLISHED_TOOLING_SHA_REQUIRED
with:
tooling-revision: REVIEWED_PUBLISHED_TOOLING_SHA_REQUIRED
app-name: photocraft
app-title: PhotoCraft
# Known unadmitted apps use their own catalog app-name/app-title here.
# All legacy platform/fonts/credits inputs remain available on the callee.
# Metadata only; legacy packaging diagnostics are paused pending read-only Flatpak jobs.
+9
View File
@@ -23,6 +23,15 @@ jobs:
id-token: write
attestations: write
uses: storytold/craft-common-actions/.github/workflows/nightly.yml@REVIEWED_PUBLISHED_TOOLING_SHA_REQUIRED
secrets:
WINDOWS_CERTIFICATE: ${{ secrets.WINDOWS_CERTIFICATE }}
WINDOWS_CERTIFICATE_PASSWORD: ${{ secrets.WINDOWS_CERTIFICATE_PASSWORD }}
AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }}
AZURE_SIGNING_ENDPOINT: ${{ secrets.AZURE_SIGNING_ENDPOINT }}
AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }}
AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }}
with:
tooling-revision: REVIEWED_PUBLISHED_TOOLING_SHA_REQUIRED
app-name: photocraft
+4 -3
View File
@@ -20,11 +20,12 @@ def subject(registry,prepared,policy,directory,environment,*,signed=False):
'digest':'sha256:'+metadata[filename][1],'source_commit':ident['source_commit']}
def guarded_subject(api,registry,prepared,policy,directory,environment,config,*,identity_directory,identity_sha256,packet_sha256,zip_sha256,asset,signed=False):
def guarded_subject(api,registry,prepared,policy,directory,environment,config,*,identity_directory,identity_sha256,packet_sha256,zip_sha256,asset,signed=False,package_verifier=None):
"""Only two read-only active-state GETs; no signing, attestation or writes."""
import nightly_artifacts as bindings
p.validate_prepared(registry,prepared,policy,environment,config)
p.require_active_workflow(api,config,policy) # Before packet hashing/subject work.
if package_verifier is not None: package_verifier()
bindings.verify_chain(identity_directory,directory,identity_sha256,packet_sha256,zip_sha256,asset)
result=subject(registry,prepared,policy,directory,environment,signed=signed)
# LAST API read before main can expose any subject output. Cooperative,
@@ -52,12 +53,12 @@ def main():
p.publication_contract(config,policy) # Approved exact producer identity before token.
import nightly_signing as signing
checked=signing.verify_receipt(args.signing_receipt_directory,args.signing_receipt_sha256,"windows-x86_64",args.asset,args.identity_sha256,args.unsigned_sha256,args.zip_sha256,os.environ)
signing.verify_package(args.directory,checked,".",os.environ,packet=True)
repository=p.trusted_repository(registry,prepared['app'],os.environ)
api=publisher.HTTPTransport(repository,os.environ.get('GH_TOKEN',''))
result=guarded_subject(api,registry,prepared,policy,args.directory,os.environ,config,
identity_directory=Path(args.identity).parent,identity_sha256=args.identity_sha256,
packet_sha256=args.packet_sha256,zip_sha256=args.zip_sha256,asset=args.asset,signed=True)
packet_sha256=args.packet_sha256,zip_sha256=args.zip_sha256,asset=args.asset,signed=True,
package_verifier=lambda: signing.verify_package(args.directory,checked,".",os.environ,packet=True))
if output:=os.environ.get('GITHUB_OUTPUT'):
with open(output,'a') as stream:
for key,value in result.items():
+5 -1
View File
@@ -12,7 +12,11 @@ def diagnostic(registry,app,cargo,environment):
n.trusted_context(registry,app,environment)
raw=n.bounded_bytes(cargo,n.MAX_JSON_BYTES,'diagnostic Cargo metadata')
manifest=tomllib.loads(raw.decode())
base=manifest.get('workspace',{}).get('package',{}).get('version',manifest.get('package',{}).get('version'))
workspace=manifest.get('workspace',{}); package=manifest.get('package',{})
n.require(isinstance(workspace,dict) and isinstance(package,dict),'Cargo workspace and package must be tables')
workspace_package=workspace.get('package',{})
n.require(isinstance(workspace_package,dict),'Cargo workspace.package must be a table')
base=workspace_package.get('version',package.get('version'))
n.require(isinstance(base,str),'diagnostic Cargo version missing')
base=base.split('-',1)[0].split('+',1)[0]
n.require(n.BASE.fullmatch(base),'diagnostic Cargo base must be canonical')
+45 -10
View File
@@ -8,6 +8,7 @@ without overwrite, only after exclusive ref creation and verified publication.
It is not a platform-signed assertion of the tag creator. Missing historical
pins, origin metadata, timing, digest or receipts fail closed.
"""
import datetime as dt
import hashlib
import http.client
import io
@@ -47,8 +48,19 @@ def artifact_name(receipt):
def receipt_for(release):
previous = policy.body_policy(release.get("body"))
identity, run = previous["identity"], previous["run"]
try:
previous = policy.body_policy(release.get("body"))
except (ValueError, RecursionError) as error:
raise n.InvalidNightly("malformed historical policy marker") from error
n.require(isinstance(previous, dict), "malformed historical policy marker")
identity, run = previous.get("identity"), previous.get("run")
n.require(isinstance(identity, dict) and isinstance(run, dict), "missing historical identity/run")
for key in ("app", "repository"):
n.require(isinstance(identity.get(key), str) and bool(identity[key]), "invalid historical identity " + key)
for key in ("id", "attempt"):
n.positive(run.get(key), "historical run " + key)
pin = previous.get("tooling_revision")
n.require(isinstance(pin, str) and n.HEX40.fullmatch(pin) and pin != "0" * 40, "invalid historical tooling revision")
return {"schema": SCHEMA, "app": identity["app"], "repository": identity["repository"], "tag": release["tag_name"],
"source_commit": release["target_commitish"], "release_id": release["id"], "run_id": run["id"],
"run_attempt": run["attempt"], "tooling_revision": previous["tooling_revision"]}
@@ -126,13 +138,25 @@ def read_receipt(raw):
raise n.InvalidNightly("invalid ownership receipt archive/JSON") from error
def download_artifact(api, artifact_id):
def download_artifact(api, artifact_id, *, max_bytes=MAX_ARCHIVE):
# Transport exceptions may embed a signed URL. Never expose their text or
# chained traceback to the CLI; ordinary API status errors remain distinct.
try:
return _download_artifact(api, artifact_id, max_bytes=max_bytes)
except n.InvalidNightly:
raise
except (http.client.HTTPException, OSError, ValueError):
raise n.Unavailable("artifact download transport failed") from None
def _download_artifact(api, artifact_id, *, max_bytes):
"""One authenticated API redirect, then one token-free signed blob GET.
The redirect is never returned/logged. Unknown hosts, ports, redirects,
responses or oversized archives stop without following arbitrary origins.
"""
n.positive(artifact_id, "artifact ID")
n.positive(max_bytes, "artifact download bound")
connection = http.client.HTTPSConnection("api.github.com", timeout=30)
try:
connection.request("GET", api.prefix + f"/actions/artifacts/{artifact_id}/zip", headers={
@@ -142,7 +166,7 @@ def download_artifact(api, artifact_id):
if response.status != 302:
raise APIError(response.status)
location = response.getheader("Location")
n.require(isinstance(location, str) and 0 < len(location) <= 8192 and not any(ord(char) < 32 for char in location), "invalid artifact redirect")
n.require(isinstance(location, str) and 0 < len(location) <= 8192 and all(33 <= ord(char) <= 126 for char in location), "invalid artifact redirect")
target = urlsplit(location)
n.require(target.scheme == "https" and target.port in (None, 443) and not target.username and not target.password and not target.fragment
and isinstance(target.hostname, str) and re.fullmatch(r"productionresultssa[0-9]+\.blob\.core\.windows\.net", target.hostname)
@@ -155,13 +179,24 @@ def download_artifact(api, artifact_id):
response = blob.getresponse()
if response.status != 200:
raise APIError(response.status)
raw = response.read(MAX_ARCHIVE + 1)
n.require(len(raw) <= MAX_ARCHIVE, "ownership archive exceeds bound")
raw = response.read(max_bytes + 1)
n.require(len(raw) <= max_bytes, "artifact archive exceeds bound")
return raw
finally:
blob.close()
def actions_timestamp(value):
"""Parse Actions job/step instants locally, retaining subsecond precision."""
n.require(isinstance(value, str) and re.fullmatch(
r"[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(?:\.[0-9]{1,6})?(?:Z|[+-](?:[01][0-9]|2[0-3]):[0-5][0-9])", value),
"invalid Actions ownership timestamp")
try:
return dt.datetime.fromisoformat(value.replace("Z", "+00:00")).astimezone(dt.timezone.utc)
except (ValueError, OverflowError) as error:
raise n.InvalidNightly("invalid Actions ownership timestamp") from error
class ActionsOwnership:
"""Authenticated run evidence plus an explicit reviewed-source assumption.
@@ -211,9 +246,9 @@ class ActionsOwnership:
n.require(step.get("status") == "completed" and step.get("conclusion") == "success", "ownership step did not succeed")
n.positive(step.get("number"), "ownership step number")
n.require(publish["number"] < upload["number"], "receipt uploaded before publication")
job_start, job_end = policy.timestamp(job.get("started_at")), policy.timestamp(job.get("completed_at"))
publish_start, publish_end = policy.timestamp(publish.get("started_at")), policy.timestamp(publish.get("completed_at"))
upload_start, upload_end = policy.timestamp(upload.get("started_at")), policy.timestamp(upload.get("completed_at"))
job_start, job_end = actions_timestamp(job.get("started_at")), actions_timestamp(job.get("completed_at"))
publish_start, publish_end = actions_timestamp(publish.get("started_at")), actions_timestamp(publish.get("completed_at"))
upload_start, upload_end = actions_timestamp(upload.get("started_at")), actions_timestamp(upload.get("completed_at"))
n.require(job_start <= publish_start <= publish_end <= upload_start <= upload_end <= job_end, "ownership step chronology differs")
artifacts = bounded_list(api, f"/actions/runs/{run_id}/artifacts", "artifacts")
artifacts = [artifact for artifact in artifacts if artifact.get("name") == artifact_name(expected)]
@@ -231,7 +266,7 @@ class ActionsOwnership:
n.require(isinstance(origin, dict) and origin.get("id") == run_id and origin.get("repository_id") == config["repository_id"]
and origin.get("head_repository_id") == config["repository_id"] and origin.get("head_sha") == expected["source_commit"]
and origin.get("head_branch") == "main", "artifact run/repository/source differs")
created, updated = policy.timestamp(artifact.get("created_at")), policy.timestamp(artifact.get("updated_at"))
created, updated = actions_timestamp(artifact.get("created_at")), actions_timestamp(artifact.get("updated_at"))
n.require(upload_start <= created <= upload_end and created <= updated <= job_end, "artifact was not created during trusted upload step")
raw = api.download_artifact(artifact["id"])
n.require(isinstance(raw, bytes) and len(raw) == artifact["size_in_bytes"] and hashlib.sha256(raw).hexdigest() == digest[7:], "ownership ZIP differs from authenticated API digest")
+19 -6
View File
@@ -1,5 +1,6 @@
"""Emit finite source-bound Actions ownership evidence; not an independent tag-creator attestation."""
import json
from contextlib import contextmanager
import os
from pathlib import Path
import re
@@ -24,13 +25,25 @@ def receipt(ident, release, environment):
'tag':ident['tag'],'source_commit':ident['source_commit'],'release_id':release['id'],
'run_id':int(run),'run_attempt':int(attempt),'tooling_revision':tooling}
def emit(ident, release, environment, directory):
data = receipt(ident,release,environment)
output=Path(directory); n.require(not output.exists() and not output.is_symlink(),'ownership output must be new')
@contextmanager
def reserve(directory):
output=Path(directory)
n.require(not output.exists() and not output.is_symlink(),'ownership output must be new')
output.mkdir(parents=True,exist_ok=False)
path=output/'ownership.json'
with path.open('x',encoding='utf-8') as stream:
json.dump(data,stream,sort_keys=True,separators=(',',':'));stream.write('\n');stream.flush();os.fsync(stream.fileno())
with (output/'ownership.json').open('x',encoding='utf-8') as stream:
yield stream
def emit(ident, release, environment, directory, *, reserved_stream=None):
data = receipt(ident,release,environment)
if reserved_stream is None:
with reserve(directory) as stream:
return emit(ident,release,environment,directory,reserved_stream=stream)
path=Path(directory)/'ownership.json'
n.require(not reserved_stream.closed and reserved_stream.writable() and
Path(reserved_stream.name).absolute()==path.absolute(),'ownership reservation differs')
json.dump(data,reserved_stream,sort_keys=True,separators=(',',':'))
reserved_stream.write('\n');reserved_stream.flush();os.fsync(reserved_stream.fileno())
if destination:=environment.get('GITHUB_OUTPUT'):
with open(destination,'a',encoding='utf-8') as stream:
stream.write('release-id='+str(data['release_id'])+'\nownership-artifact-name=nightly-ownership-'+data['app']+'-'+str(data['run_id'])+'-'+str(data['run_attempt'])+'\n')
+58 -37
View File
@@ -21,6 +21,9 @@ MAX_PAGES=20
PAGE_SIZE=20
MAX_CHECKS=32
MAX_BASELINE_CHECKS=128
# Fits the counted 32-workflow/128-job normal witness; excessive history still
# fails closed, and the independent 120-second wall-clock cap is unchanged.
MAX_BASELINE_READS=640
ZERO='0'*40
STABLE=re.compile(r'v?((?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*))(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?')
NIGHTLY=re.compile(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})')
@@ -220,6 +223,7 @@ def validate_baseline_refresh(previous,updated,policy,api=None):
"""
publication_contract(updated,policy)
n.require(baseline_mode(previous) and baseline_mode(updated),'refresh needs two v2 reviewed policies')
n.require(managed_contract(previous['apps']['photocraft'])==managed_contract(updated['apps']['photocraft']),'managed coverage changed; explicit policy migration required')
old_external=external_contract(previous['apps']['photocraft'],policy)
new_external=external_contract(updated['apps']['photocraft'],policy)
ext_key=lambda item:(item['provider'],item['name'],item['app_id'],item['details_url'])
@@ -241,7 +245,7 @@ def validate_baseline_refresh(previous,updated,policy,api=None):
class BaselineReads:
"""One read-only, bounded live witness; no cached/unsigned witness input."""
def __init__(self,api):
self.api=api; self.remaining=256; self.deadline=time.monotonic()+120
self.api=api; self.remaining=MAX_BASELINE_READS; self.deadline=time.monotonic()+120
def request(self,method,path):
n.require(method=='GET' and path.startswith('/') and not path.startswith('//'),'baseline API reads only')
n.require(self.remaining>0 and time.monotonic()<self.deadline,'baseline API request/time budget reached')
@@ -307,6 +311,34 @@ def complete_quality_run(run,failed):
n.require(run.get('status')=='completed' and run.get('conclusion')==('failure' if failed else 'success'),'independent workflow incomplete or aggregate result differs from witnessed jobs')
def quality_job_check_id(policy,job):
match=re.fullmatch(r'https://api.github.com/repos/'+re.escape(policy['run']['repository'])+r'/check-runs/([1-9][0-9]*)',job.get('check_run_url',''))
n.require(match is not None,'job lacks fixed-host check identity')
return int(match.group(1))
def verify_quality_job(policy,sha,run,item,job,check,baseline=False,reviewed_at=None):
for key in ('id','run_id','run_attempt'): n.positive(job.get(key),'quality job '+key)
n.require(job['run_id']==run['id'] and job['run_attempt']==run['run_attempt'] and job.get('head_sha')==sha,'job source/attempt differs')
check_id=quality_job_check_id(policy,job)
n.require(isinstance(check,dict) and check.get('name')==item['name'] and type(check.get('app',{}).get('id')) is int and check['app']['id']==item['app_id'] and check.get('head_sha')==sha,'job/check/app identity differs')
expected_url=f"https://github.com/{policy['run']['repository']}/actions/runs/{run['id']}/job/{job['id']}"
n.require(check.get('details_url')==expected_url,'check URL does not identify authenticated job/run')
inactive=manual_only(item)
if inactive:
n.require(run['event'] in ('push','schedule') and job.get('conclusion')=='skipped',
'reviewed manual-input-only job is not proven inapplicable on this event')
n.require(job.get('status')=='completed' and job.get('conclusion') in (('skipped',) if inactive else ('success','failure')) and check.get('status')=='completed' and check.get('conclusion')==job['conclusion'],'missing/pending/skipped/cancelled/unknown job result')
started=timestamp(check.get('started_at')); completed=timestamp(job.get('completed_at'))
n.require(timestamp(run['created_at'])<=started<=completed<=time.time(),'inconsistent/future job witness timestamps')
if baseline:
n.require(job['id']==item['baseline_job_id'] and check_id==item['baseline_check_id'],'reviewed baseline job/check changed')
n.require(timestamp(run['created_at'])<=reviewed_at and timestamp(job['completed_at'])<=reviewed_at,'baseline evidence postdates review')
# A reviewed success never becomes an exemption on later failure.
n.require(item['baseline_conclusion']!='success' or job['conclusion']=='success','baseline success regressed; refresh without lowering green floor')
return check_id,job['conclusion']
def verify_quality_jobs(api,policy,sha,run,wanted,checks,baseline=False,reviewed_at=None):
jobs=bounded_rows(api,f"/actions/runs/{run['id']}/attempts/{run['run_attempt']}/jobs?filter=all",'jobs')
n.require(len(jobs)==len(wanted),'workflow job coverage drift/missing jobs')
@@ -318,28 +350,9 @@ def verify_quality_jobs(api,policy,sha,run,wanted,checks,baseline=False,reviewed
n.require(set(by_name)=={item['name'] for item in wanted},'workflow job coverage drift')
for item in wanted:
job=by_name[item['name']]
for key in ('id','run_id','run_attempt'): n.positive(job.get(key),'quality job '+key)
n.require(job['run_id']==run['id'] and job['run_attempt']==run['run_attempt'] and job.get('head_sha')==sha,'job source/attempt differs')
url=job.get('check_run_url','')
match=re.fullmatch(r'https://api.github.com/repos/'+re.escape(policy['run']['repository'])+r'/check-runs/([1-9][0-9]*)',url)
n.require(match is not None,'job lacks fixed-host check identity')
check_id=int(match.group(1)); check=checks.get(check_id)
n.require(isinstance(check,dict) and check.get('name')==item['name'] and type(check.get('app',{}).get('id')) is int and check['app']['id']==item['app_id'] and check.get('head_sha')==sha,'job/check/app identity differs')
expected_url=f"https://github.com/{policy['run']['repository']}/actions/runs/{run['id']}/job/{job['id']}"
n.require(check.get('details_url')==expected_url,'check URL does not identify authenticated job/run')
inactive=manual_only(item)
if inactive:
n.require(run['event'] in ('push','schedule') and job.get('conclusion')=='skipped',
'reviewed manual-input-only job is not proven inapplicable on this event')
n.require(job.get('status')=='completed' and job.get('conclusion') in (('skipped',) if inactive else ('success','failure')) and check.get('status')=='completed' and check.get('conclusion')==job['conclusion'],'missing/pending/skipped/cancelled/unknown job result')
started=timestamp(check.get('started_at')); completed=timestamp(job.get('completed_at'))
n.require(timestamp(run['created_at'])<=started<=completed<=time.time(),'inconsistent/future job witness timestamps')
if baseline:
n.require(job['id']==item['baseline_job_id'] and check_id==item['baseline_check_id'],'reviewed baseline job/check changed')
n.require(timestamp(run['created_at'])<=reviewed_at and timestamp(job['completed_at'])<=reviewed_at,'baseline evidence postdates review')
# A reviewed success never becomes an exemption on later failure.
n.require(item['baseline_conclusion']!='success' or job['conclusion']=='success','baseline success regressed; refresh without lowering green floor')
used.add(check_id); results[item['name']]=job['conclusion']
check_id=quality_job_check_id(policy,job)
check_id,result=verify_quality_job(policy,sha,run,item,job,checks.get(check_id),baseline,reviewed_at)
used.add(check_id); results[item['name']]=result
complete_quality_run(run,any(value=='failure' for value in results.values()))
return results,used
@@ -394,19 +407,22 @@ def historical_green_jobs(api,policy,sha,wanted,current,current_results):
run=api.request('GET',f"/actions/runs/{root['id']}/attempts/{attempt}")
trusted_quality_run(run,policy,sha,wanted[0])
n.require(run['id']==root['id'] and run['run_attempt']==attempt and run['run_number']==root['run_number'],'historical attempt identity differs')
if run.get('status')!='completed' or run.get('conclusion') not in ('success','failure'): continue
jobs=bounded_rows(api,f"/actions/runs/{run['id']}/attempts/{attempt}/jobs?filter=all",'jobs')
checks={}
by_name={}
for job in jobs:
match=re.fullmatch(r'https://api.github.com/repos/'+re.escape(policy['run']['repository'])+r'/check-runs/([1-9][0-9]*)',job.get('check_run_url',''))
n.require(match is not None,'historical job lacks authenticated check identity')
check_id=int(match.group(1)); check=api.request('GET',f'/check-runs/{check_id}')
n.require(isinstance(check,dict),'invalid historical check')
n.positive(check.get('id'),'historical check ID')
n.require(check['id']==check_id,'historical check identity differs')
checks[check_id]=check
results,_=verify_quality_jobs(api,policy,sha,run,wanted,checks)
greens.update(name for name,value in results.items() if value=='success')
name=job.get('name')
n.require(isinstance(name,str) and name not in by_name,'ambiguous historical workflow job identity')
by_name[name]=job
for item in wanted:
job=by_name.get(item['name'])
# A cancelled/partial aggregate cannot erase an already completed
# success. Other historical results never grant an exemption.
if job is None or job.get('status')!='completed' or job.get('conclusion')!='success': continue
check_id=quality_job_check_id(policy,job)
check=api.request('GET',f'/check-runs/{check_id}')
n.require(isinstance(check,dict) and type(check.get('id')) is int and check['id']==check_id,'historical check identity differs')
verify_quality_job(policy,sha,run,item,job,check)
greens.add(item['name'])
n.require(current['id'] in seen,'current run absent from history')
return greens
@@ -791,10 +807,12 @@ def publication_gate(api,registry,config,prepared,policy,environment):
n.require(stable_base(rows)==policy['stable_base'],'published stable base changed; prepare a new attempt')
previous=newest_nightly(rows)
if previous is not None: freshness(policy,verify_prior(api,registry,previous))
# This is the LAST API read in either live guard, immediately before the
# caller can mutate. Cooperative pause, not an administrator-atomic lock.
if baseline_mode(config): require_main_head(api,policy)
require_active_workflow(api,config,policy)
# Observe run order after every other remote check, immediately before the
# caller can mutate. Cooperative checks, not an administrator-atomic lock.
require_newest_run(api,policy)
if baseline_mode(config): baseline_contract(config_row(config,'photocraft',policy['tooling_revision'])[0],policy)
return True
@@ -843,7 +861,10 @@ def main():
value=str(prepared[key]).lower() if isinstance(prepared[key],bool) else str(prepared[key])
n.require('\n' not in value and '\r' not in value,'invalid output'); destination.write(f'{key}={value}\n')
destination.write('build='+str(build).lower()+'\n')
summary('preflight passed', 'Exact-source approved Actions checks satisfy the reviewed quality policy; dedicated workflow is active. Build='+str(build)+'. No external SonarCloud adapter is inferred.')
if args.mode=='prepare':
summary('preflight passed', 'Exact-source approved Actions checks satisfy the reviewed quality policy; dedicated workflow is active. Build='+str(build)+'. No external SonarCloud adapter is inferred.')
else:
summary('local validation passed', 'Prepared identity and policy sidecars passed local validation. CI results and producer workflow state were not queried. Build='+str(build)+'.')
print(json.dumps({'identity':prepared,'build':build,'feed_admitted':False},sort_keys=True))
except (n.InvalidNightly,APIError,OSError,ValueError,TypeError,KeyError) as error:
summary('refused',error)
+42 -14
View File
@@ -15,7 +15,8 @@ from urllib.parse import quote, unquote
import nightly_feed as n
import nightly_policy as policy
from publish_nightly import APIError, HTTPTransport
from nightly_ownership import AmbiguousOwnership
from nightly_ownership import AmbiguousOwnership, MAX_ARCHIVE
from nightly_prune_checkpoint import MAX_PLAN_BYTES
SCHEMA = "craft-nightly-prune/v1"
KEEP = 7
@@ -45,9 +46,9 @@ class PublicationProvenance:
class PruneTransport(HTTPTransport):
"""Keep publisher transport unchanged; DELETE requires an exact empty 204."""
def download_artifact(self, artifact_id):
def download_artifact(self, artifact_id, *, max_bytes=MAX_ARCHIVE):
from nightly_ownership import download_artifact
return download_artifact(self, artifact_id)
return download_artifact(self, artifact_id, max_bytes=max_bytes)
def exchange(self, host, method, path, **kwargs):
if method != "DELETE":
@@ -91,7 +92,9 @@ def parse_tag(tag):
def optional(api, path):
try:
return api.request("GET", path)
reply = api.request("GET", path)
n.require(isinstance(reply, dict), "successful optional lookup must return an object")
return reply
except APIError as error:
if error.status == 404:
return None
@@ -150,6 +153,15 @@ def shape(release, app, bot_id):
def prove(api, registry, app, release, bot_id, provenance, absent_release=False):
shape(release, app, bot_id)
repository = n.app_record(registry, app)["repository"]
# Validate untrusted local marker data before any authenticated proof reads.
# Keep this catch narrow: transport failures/ambiguity must abort the plan.
try:
previous = policy.body_policy(release.get("body"))
policy.validate_prepared(registry, previous["identity"], previous, policy.prior_environment(previous))
except n.InvalidNightly:
raise
except (KeyError, TypeError, ValueError, RecursionError, OverflowError) as error:
raise n.InvalidNightly("malformed historical policy marker") from error
# A persisted snapshot never grants authority. The adapter must independently
# reauthenticate the original publication even in release-gone recovery.
n.require(provenance.verify(api, repository, copy.deepcopy(release), bot_id) is True,
@@ -203,12 +215,15 @@ def plan(api, registry, app, current_release_id, bot_id, provenance=None):
historical = [row for row in proven if row["id"] != current_release_id]
kept = [current[0]] + historical[:KEEP - 1]
candidates = list(reversed(historical[KEEP - 1:]))[:MAX_REMOVALS]
return {"schema": SCHEMA, "app": app, "repository": repository, "bot_id": bot_id,
"current": snapshot(current[0]), "keep": [row["id"] for row in kept],
"candidates": [snapshot(row) for row in candidates], "retained": retained}
result = {"schema": SCHEMA, "app": app, "repository": repository, "bot_id": bot_id,
"current": snapshot(current[0]), "keep": [row["id"] for row in kept],
"candidates": [snapshot(row) for row in candidates], "retained": retained}
encode_plan(result) # Refuse before stdout/upload if the checkpoint cannot fit.
return result
def validate_plan(previous, registry):
encode_plan(previous)
n.fields(previous, {"schema", "app", "repository", "bot_id", "current", "keep", "candidates", "retained"}, "prune plan")
n.require(previous["schema"] == SCHEMA and previous["repository"] == n.app_record(registry, previous["app"])["repository"], "plan repository/schema mismatch")
n.positive(previous["bot_id"], "approved bot ID")
@@ -284,13 +299,15 @@ def execute(api, registry, previous, *, approved=False, provenance=None, checkpo
return {"completed_release_ids": completed}
def save_checkpoint(path, previous):
def save_checkpoint(path, previous, *, raw=None):
"""Atomic local receipt; caller must retain it outside temporary build roots."""
from pathlib import Path
destination = Path(path)
temporary = destination.with_name(destination.name + ".new")
with open(temporary, "x", encoding="utf-8") as stream:
json.dump(previous, stream, sort_keys=True)
raw = encode_plan(previous) if raw is None else raw
n.require(parse_plan_bytes(raw) == previous, "local checkpoint bytes differ from validated plan")
with open(temporary, "xb") as stream:
stream.write(raw)
stream.flush(); os.fsync(stream.fileno())
os.replace(temporary, destination)
descriptor = os.open(destination.parent, os.O_RDONLY)
@@ -300,8 +317,18 @@ def save_checkpoint(path, previous):
os.close(descriptor)
def encode_plan(previous):
raw = (json.dumps(previous, sort_keys=True) + "\n").encode("utf-8")
n.require(len(raw) <= MAX_PLAN_BYTES, "prune plan exceeds checkpoint byte budget")
return raw
def read_plan(path):
raw = n.bounded_bytes(path, 4 * 1024 * 1024, "prune plan")
return parse_plan_bytes(n.bounded_bytes(path, MAX_PLAN_BYTES, "prune plan"))
def parse_plan_bytes(raw):
n.require(isinstance(raw, bytes) and 0 < len(raw) <= MAX_PLAN_BYTES, "prune plan exceeds bound")
def unique(pairs):
value = {}
for key, item in pairs:
@@ -332,7 +359,8 @@ def main():
n.require(provenance.config["repository"] == repository and provenance.config["bot_id"] == args.bot_id, "ownership config/app/bot mismatch")
if args.mode == "apply":
n.require(args.approve_first_run is True and args.config and args.plan and args.checkpoint and args.checkpoint_artifact_id and args.checkpoint_artifact_sha256, "live apply is off: explicit approval, reviewed ownership config, plan and durable checkpoint required")
previous = read_plan(args.plan)
plan_bytes = n.bounded_bytes(args.plan, MAX_PLAN_BYTES, "prune plan")
previous = parse_plan_bytes(plan_bytes)
validate_plan(previous, registry)
n.require(previous["app"] == args.app and previous["current"]["id"] == args.current_release_id and previous["bot_id"] == args.bot_id, "plan differs from CLI publication context")
api = PruneTransport(repository, os.environ.get("GH_TOKEN", ""))
@@ -340,8 +368,8 @@ def main():
result = plan(api, registry, args.app, args.current_release_id, args.bot_id, provenance)
else:
from nightly_prune_checkpoint import verify as verify_durable
verify_durable(api,provenance.config,previous,args.checkpoint_artifact_id,args.checkpoint_artifact_sha256,os.environ)
result = execute(api, registry, previous, approved=True, provenance=provenance, checkpoint=lambda value: save_checkpoint(args.checkpoint, value))
verify_durable(api,provenance.config,plan_bytes,args.checkpoint_artifact_id,args.checkpoint_artifact_sha256,os.environ)
result = execute(api, registry, previous, approved=True, provenance=provenance, checkpoint=lambda value: save_checkpoint(args.checkpoint, value, raw=plan_bytes))
print(json.dumps(result, sort_keys=True))
except (n.InvalidNightly, APIError, OSError, ValueError, KeyError, TypeError, zipfile.BadZipFile) as error:
parser.exit(1, f"nightly pruning stopped: {error}\n")
+12 -8
View File
@@ -7,9 +7,13 @@ import stat
import zipfile
import nightly_feed as n
import nightly_policy as p
from nightly_ownership import MAX_ARCHIVE
# Separate budgets: a prune plan includes bounded inventory diagnostics, not
# just the tiny ownership receipt. Leave room for stored ZIP member overhead.
MAX_PLAN_BYTES = 4 * 1024 * 1024
MAX_CHECKPOINT_ARCHIVE = MAX_PLAN_BYTES + 64 * 1024
def verify(api, config, plan, artifact_id, archive_sha256, environment):
def verify(api, config, plan_bytes, artifact_id, archive_sha256, environment):
n.require(isinstance(plan_bytes, bytes) and 0 < len(plan_bytes) <= MAX_PLAN_BYTES, 'local prune plan exceeds bound')
n.require(isinstance(artifact_id,str) and re.fullmatch('[1-9][0-9]{0,18}',artifact_id), 'exact uploaded plan artifact ID required')
n.require(isinstance(archive_sha256,str) and re.fullmatch('[0-9a-f]{64}',archive_sha256), 'independent plan upload digest required')
n.require(environment.get('GITHUB_REPOSITORY')==config['repository'] and environment.get('GITHUB_REF')=='refs/heads/main' and environment.get('GITHUB_EVENT_NAME') in {'schedule','workflow_dispatch'}, 'untrusted prune checkpoint context')
@@ -22,22 +26,22 @@ def verify(api, config, plan, artifact_id, archive_sha256, environment):
pin=environment.get('TOOLING_REVISION','');n.require(pin in config['allowed_tooling_revisions'], 'checkpoint tooling pin unreviewed')
refs=run.get('referenced_workflows');n.require(isinstance(refs,list) and len(refs)<=32 and sum(isinstance(row,dict) and row.get('path')==config['tooling_workflow_path']+'@'+pin and row.get('sha')==pin for row in refs)==1, 'checkpoint defining workflow differs')
artifact=api.request('GET',f'/actions/artifacts/{artifact_id}')
n.require(artifact.get('id')==int(artifact_id) and artifact.get('name')==f'nightly-prune-plan-{run_id}-{attempt}' and artifact.get('expired') is False and type(artifact.get('size_in_bytes')) is int and 0<artifact['size_in_bytes']<=MAX_ARCHIVE and artifact.get('digest')=='sha256:'+archive_sha256, 'uploaded plan metadata differs')
n.require(artifact.get('id')==int(artifact_id) and artifact.get('name')==f'nightly-prune-plan-{run_id}-{attempt}' and artifact.get('expired') is False and type(artifact.get('size_in_bytes')) is int and 0<artifact['size_in_bytes']<=MAX_CHECKPOINT_ARCHIVE and artifact.get('digest')=='sha256:'+archive_sha256, 'uploaded plan metadata differs')
origin=artifact.get('workflow_run',{})
n.require(origin.get('id')==int(run_id) and origin.get('repository_id')==config['repository_id'] and origin.get('head_repository_id')==config['repository_id'] and origin.get('head_sha')==sha and origin.get('head_branch')=='main', 'uploaded plan origin differs')
n.require(p.timestamp(run['created_at'])<=p.timestamp(artifact['created_at'])<=p.timestamp(artifact['updated_at']), 'uploaded plan predates this run')
raw=api.download_artifact(int(artifact_id))
n.require(isinstance(raw,bytes) and len(raw)==artifact['size_in_bytes'] and hashlib.sha256(raw).hexdigest()==archive_sha256, 'uploaded plan archive differs')
raw=api.download_artifact(int(artifact_id), max_bytes=MAX_CHECKPOINT_ARCHIVE)
n.require(isinstance(raw,bytes) and len(raw)<=MAX_CHECKPOINT_ARCHIVE and len(raw)==artifact['size_in_bytes'] and hashlib.sha256(raw).hexdigest()==archive_sha256, 'uploaded plan archive differs')
with zipfile.ZipFile(io.BytesIO(raw)) as archive:
entries=archive.infolist();n.require(len(entries)==1,'checkpoint contains extra files')
member=entries[0];n.require(member.filename=='plan.json' and not member.is_dir() and not member.flag_bits & 1 and stat.S_IFMT(member.external_attr>>16) in (0,stat.S_IFREG) and 0<member.file_size<=64*1024,'invalid checkpoint member')
member=entries[0];n.require(member.filename=='plan.json' and not member.is_dir() and not member.flag_bits & 1 and stat.S_IFMT(member.external_attr>>16) in (0,stat.S_IFREG) and 0<member.file_size<=MAX_PLAN_BYTES,'invalid checkpoint member')
data=archive.read(member)
def unique(pairs):
result={}
for key,value in pairs:
n.require(key not in result,'duplicate checkpoint key');result[key]=value
return result
loaded=json.loads(data.decode('utf-8'),object_pairs_hook=unique,parse_constant=lambda _: (_ for _ in ()).throw(n.InvalidNightly('nonfinite checkpoint JSON')))
n.require(loaded==plan,'durable checkpoint differs from exact local prune plan')
json.loads(data.decode('utf-8'),object_pairs_hook=unique,parse_constant=lambda _: (_ for _ in ()).throw(n.InvalidNightly('nonfinite checkpoint JSON')))
n.require(data==plan_bytes,'durable checkpoint differs from exact local prune plan bytes')
n.require(api.request('GET',f'/actions/artifacts/{artifact_id}')==artifact,'checkpoint changed during verification')
return True
+1
View File
@@ -18,6 +18,7 @@ def smoke(executable,profile_root,version):
executable=Path(executable); profile_root=Path(profile_root)
n.require(executable.is_absolute() and executable.is_file() and not executable.is_symlink(),'explicit packaged GUI executable required')
n.require(profile_root.is_absolute() and not profile_root.exists() and not profile_root.is_symlink(),'fresh absolute isolated smoke profile required')
executable=executable.resolve(); profile_root=profile_root.resolve()
n.require(executable.parent not in profile_root.parents and profile_root not in executable.parents,'smoke profile must be separate from the installation')
profile_root.mkdir(parents=True,exist_ok=False)
# No shell, descriptor-provided selector, startup files, version override or stable fallback.
+18 -3
View File
@@ -12,9 +12,11 @@ import os
from pathlib import Path, PurePosixPath
import plistlib
import re
import shutil
import stat
import struct
import tarfile
import tempfile
import tomllib
import zipfile
import nightly_feed as n
@@ -127,10 +129,12 @@ def verify_archive(pending,platform,archive,version,output=None):
if out is not None: require_build_policy(platform)
raw, info = n.regular_file(archive.parent,archive.name)
names=set(); files=set(); required_dirs=set(); total=0; entry_header=None; plist=None; executable=False
staging=None
try:
if out is not None:
n.require(out.is_absolute() and not out.exists() and not out.is_symlink(),"unpack output must be a new absolute directory")
out.mkdir(parents=True,exist_ok=False)
out.parent.mkdir(parents=True,exist_ok=True)
staging=Path(tempfile.mkdtemp(prefix=".nightly-unpack-",dir=out.parent))
def consume(name,size,is_dir,mode,read):
nonlocal total,entry_header,plist,executable
n.require(not name.endswith('/') or is_dir,"regular file has directory spelling")
@@ -149,7 +153,7 @@ def verify_archive(pending,platform,archive,version,output=None):
n.require(type(size) is int and 0<=size<=n.MAX_ASSET_BYTES,"member exceeds size bound")
total+=size
n.require(total<=n.MAX_TOTAL_BYTES,"expanded payload exceeds bound")
destination=out/name if out is not None else None
destination=staging/name if staging is not None else None
if is_dir:
n.require(size==0,"directory contains payload")
if destination is not None: destination.mkdir(parents=True,exist_ok=True)
@@ -187,6 +191,12 @@ def verify_archive(pending,platform,archive,version,output=None):
finally:
reader.metadata=True
if stream is not None: stream.close()
# TAR stops at its end marker; gzip integrity is checked only at EOF.
limit=n.MAX_TOTAL_BYTES + MAX_CENTRAL_DIRECTORY
while True:
block=expanded.read(min(CHUNK,limit-expanded.tell()+1))
n.require(expanded.tell()<=limit,"expanded archive exceeds bound")
if not block: break
else:
with raw:
zip_metadata_bound(raw,info.st_size)
@@ -210,9 +220,14 @@ def verify_archive(pending,platform,archive,version,output=None):
n.require(not any(plist.get(key) for key in ('CFBundleDocumentTypes','CFBundleURLTypes','UTExportedTypeDeclarations','UTImportedTypeDeclarations')),"Mac document/URL associations forbidden")
after=archive.stat(follow_symlinks=False)
n.require((info.st_dev,info.st_ino,info.st_size,info.st_mtime_ns)==(after.st_dev,after.st_ino,after.st_size,after.st_mtime_ns),"archive changed during inspection")
if staging is not None:
n.require(not out.exists() and not out.is_symlink(),"unpack output must remain a new directory")
staging.rename(out)
staging=None
return {'members':len(names),'expanded_bytes':total,'entrypoint':row['entrypoint'],'inventory_only':True,'feed_admitted':False,'runtime_qualified':False,'signature_verified':False}
finally:
raw.close()
if staging is not None: shutil.rmtree(staging)
def main():
parser=argparse.ArgumentParser(description=__doc__)
@@ -243,7 +258,7 @@ def main():
n.require(args.mode!='inventory' or args.output is None,'inventory never extracts')
result=verify_archive(pending,args.platform,args.archive,args.version,args.output)
print(json.dumps(result,sort_keys=True))
except (n.InvalidNightly,OSError,ValueError,KeyError,TypeError,RecursionError,tarfile.TarError,zipfile.BadZipFile,plistlib.InvalidFileException) as error:
except (n.InvalidNightly,OSError,EOFError,ValueError,KeyError,TypeError,RecursionError,tarfile.TarError,zipfile.BadZipFile,plistlib.InvalidFileException) as error:
parser.exit(78 if isinstance(error,n.Unavailable) else 1,f'private Unix nightly unavailable: {error}\n')
if __name__=='__main__': main()
+1
View File
@@ -46,6 +46,7 @@ def validate_prepared(registry, app, prepared, cargo, version, environment, poli
def stage_local(registry, app, prepared, cargo, context, source_receipt, artifacts, output):
# Explicit local replay context, NOT a claim this run/tag/URL exists on GitHub.
n.require(Path(cargo).name == "Cargo.toml", "E3 receipt binds only Cargo.toml")
n.fields(context, CONTEXT_FIELDS, "local E4 context")
n.require(all(isinstance(value, str) for value in context.values()), "context values must be strings")
validate_prepared(registry, app, prepared, cargo, prepared["version"], context)
+26 -3
View File
@@ -186,6 +186,26 @@ def publish_packet(api, ident, metadata, directory, guard=None, policy=None):
return result
class PublishedWithoutReceipt(n.InvalidNightly):
"""Publication is confirmed; creating the release again is not a recovery path."""
def publish_with_receipt(api, ident, metadata, directory, *, guard, policy, environment, ownership_directory):
from nightly_ownership_receipt import reserve, emit
result = None
try:
with reserve(ownership_directory) as stream:
result = publish_packet(api, ident, metadata, directory,guard=guard,policy=policy)
emit(ident,result,environment,ownership_directory,reserved_stream=stream)
except (n.InvalidNightly, OSError, ValueError, TypeError, KeyError) as error:
if result is not None:
raise PublishedWithoutReceipt(
f"release {result['id']} is public; ownership receipt reconciliation required; "
"do not recreate or retry publication") from error
raise
return result
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--registry", required=True); parser.add_argument("--app", required=True)
@@ -213,11 +233,14 @@ def main():
ident, metadata = prepare_packet(registry, prepared, args.directory, os.environ, signed=True)
api = HTTPTransport(ident["repository"], os.environ.get("GH_TOKEN", ""))
guard=lambda: v6.publication_gate(api,registry,config,prepared,policy,os.environ)
result = publish_packet(api, ident, metadata, args.directory,guard=guard,policy=policy)
from nightly_ownership_receipt import emit
emit(ident,result,os.environ,args.ownership_directory)
result = publish_with_receipt(api, ident, metadata, args.directory,guard=guard,policy=policy,
environment=os.environ,ownership_directory=args.ownership_directory)
print(json.dumps({"release_id": result["id"], "tag": ident["tag"], "source_commit": ident["source_commit"],
"actual_published_at": result["published_at"], "build_identity_at": ident["published_at"]}))
except PublishedWithoutReceipt as error:
from nightly_policy import summary
summary('publication confirmed; ownership receipt reconciliation required',error)
parser.exit(2,f"{error}\n")
except (n.InvalidNightly, APIError, OSError, ValueError, TypeError, KeyError) as error:
from nightly_policy import summary
summary('publication refused',error)
+14 -4
View File
@@ -1,5 +1,7 @@
"""Synthetic finite files only; no artifact service, token or native execution."""
import contextlib
import hashlib
import io
import json
from pathlib import Path
import sys
@@ -72,9 +74,15 @@ class ArtifactBindingTests(unittest.TestCase):
import nightly_attestation as attestation
common=['--registry','must-not-read','--identity',str(self.identity/'nightly-identity.json'),'--policy','must-not-read','--directory',str(self.packet),'--asset',self.asset,'--identity-sha256','0'*64,'--packet-sha256',self.ph,'--zip-sha256',self.zh,'--signing-receipt-directory','must-not-read','--signing-receipt-sha256','a'*64,'--unsigned-sha256','b'*64]
for module,extra in ((publisher,['--app','photocraft','--config','must-not-read','--ownership-directory','must-not-create']),(attestation,['--config','must-not-read'])):
with self.subTest(module=module.__name__),patch.object(sys,'argv',['fixture',*common,*extra]),patch.object(publisher,'HTTPTransport',side_effect=AssertionError('credential/transport forbidden')):
errors=io.StringIO()
with self.subTest(module=module.__name__),patch.object(sys,'argv',['fixture',*common,*extra]), \
patch.object(publisher,'HTTPTransport',side_effect=AssertionError('credential/transport forbidden')) as transport, \
patch.object(module.n,'bounded_json',side_effect=AssertionError('metadata read before binding')) as metadata, \
contextlib.redirect_stderr(errors):
with self.assertRaises(SystemExit) as exit: module.main()
self.assertEqual(exit.exception.code,1)
self.assertIn('identity artifact differs from its independent producer output',errors.getvalue())
metadata.assert_not_called(); transport.assert_not_called()
def test_wrong_packet_name_or_absent_original_zip_hash_refuses(self):
with self.assertRaises(ValueError): a.verify(self.packet,'packet',self.ph,'other-nightly.zip',self.zh)
@@ -104,8 +112,10 @@ class WorkflowBoundaryTests(unittest.TestCase):
for workflow in ('nightly-windows.yml','nightly-unix.yml'):
self.assertIn('uses: $/.github/workflows/'+workflow,source)
diagnostic=(ROOT/'.github/workflows/nightly-diagnostics.yml').read_text()
self.assertIn('uses: $/.github/workflows/release.yml',diagnostic)
self.assertIn('dry-run: true',diagnostic); self.assertIn('publish: false',diagnostic)
self.assertNotIn('uses: $/.github/workflows/release.yml',diagnostic)
self.assertNotIn(': write',diagnostic)
self.assertIn('contents: read',diagnostic)
self.assertIn('scripts/nightly_diagnostic.py',diagnostic)
self.assertNotIn('nightly-publication-policy.json',diagnostic)
self.assertNotIn('nightly_policy.py',diagnostic)
self.assertNotIn('GH_TOKEN',diagnostic)
@@ -113,7 +123,7 @@ class WorkflowBoundaryTests(unittest.TestCase):
caller=(ROOT/'examples/photocraft-nightly.yml').read_text()
for scope in ('contents: write','actions: read','checks: read','id-token: write','attestations: write'): self.assertIn(scope,caller)
self.assertNotIn('packages: write',caller)
self.assertNotIn('secrets:',caller)
self.assertNotIn('secrets: inherit',caller)
native=(ROOT/'.github/workflows/nightly-windows.yml').read_text()
for scope in ('contents: write','id-token: write','attestations: write','packages: write'): self.assertNotIn(scope,native)
source=(ROOT/'.github/workflows/nightly.yml').read_text()
+9
View File
@@ -84,6 +84,15 @@ class AttestationTests(unittest.TestCase):
(self.packet/'NIGHTLY.json').write_bytes(saved_descriptor);(self.packet/'SHA256SUMS.txt').write_bytes(saved_sums)
self.binding['packet_sha256']=saved_packet_hash
return output
def test_cli_pause_refuses_before_native_package_verification(self):
import nightly_signing as signing
self.case.api.workflow['state']='disabled_manually'
with patch.object(signing,'verify_package',side_effect=AssertionError('package verification forbidden')), self.assertRaises(SystemExit) as result:
self.cli()
self.assertEqual(result.exception.code,1)
self.assertEqual(self.case.api.calls,[('GET','/actions/workflows/91')])
self.assertFalse((self.root/'github-output').exists())
def test_active_reads_bracket_unchanged_chain_and_pure_subject_with_get_only(self):
events=[]; request=self.case.api.request; verify=bindings.verify_chain; pure=a.subject
def read(method,path,data=None):
+20
View File
@@ -117,3 +117,23 @@ class ApplicabilityTests(unittest.TestCase):
return None
self.api.hook=changed
with self.assertRaisesRegex(ValueError,'inventory changed'):self.gate()
def test_normal_refresh_preserves_managed_contract_even_when_no_check_exists(self):
declaration={'provider':'github-dependabot-updates','name':'Dependabot','app_id':15368,'workflow_id':88,'workflow_path':'dynamic/dependabot/dependabot-updates'}
self.row['baseline']['reviewed_at']='2026-11-21T12:01:00Z'
for old,new in (([declaration],None),(None,[declaration]),([declaration],[{**declaration,'workflow_id':89}])):
previous=copy.deepcopy(self.config)
previous['apps']['photocraft']['baseline']['reviewed_at']='2026-11-21T12:00:00Z'
if old is None: previous['apps']['photocraft'].pop('managed_checks',None)
else: previous['apps']['photocraft']['managed_checks']=copy.deepcopy(old)
if new is None: self.row.pop('managed_checks',None)
else: self.row['managed_checks']=copy.deepcopy(new)
self.bind()
with self.subTest(old=old,new=new),self.assertRaisesRegex(ValueError,'managed coverage changed'):
p.validate_baseline_refresh(previous,self.config,self.policy,self.api)
def test_omitted_and_empty_managed_refresh_contracts_are_equivalent(self):
previous=copy.deepcopy(self.config)
self.row['managed_checks']=[];self.row['baseline']['reviewed_at']='2026-11-21T12:01:00Z';self.bind()
self.assertTrue(p.validate_baseline_refresh(previous,self.config,self.policy,self.api))
previous['apps']['photocraft']['managed_checks']=[];self.row.pop('managed_checks');self.bind()
self.assertTrue(p.validate_baseline_refresh(previous,self.config,self.policy,self.api))
+21
View File
@@ -1,4 +1,6 @@
"""No API/socket/policy for known unadmitted apps or separate Photo diagnostics."""
import contextlib
import io
import json
from pathlib import Path
import socket
@@ -30,6 +32,25 @@ class DiagnosticTests(unittest.TestCase):
for field,value in [('GITHUB_REF','refs/heads/other'),('GITHUB_EVENT_NAME','pull_request'),('GITHUB_REPOSITORY','fork/photocraft')]:
with self.subTest(field=field),self.assertRaises(ValueError): d.diagnostic(self.registry,'photocraft',self.cargo,{**self.env('photocraft'),field:value})
with self.assertRaises(ValueError): d.diagnostic(self.registry,'unknown',self.cargo,self.env('unknown'))
def test_workspace_and_package_only_versions_remain_supported(self):
for manifest,base in [('[workspace.package]\nversion="1.2.3"\n','1.2.3'),
('[package]\nversion="2.3.4"\n','2.3.4'),
('[workspace.package]\nversion="1.2.3"\n[package]\nversion="2.3.4"\n','1.2.3')]:
self.cargo.write_text(manifest)
with self.subTest(manifest=manifest):
self.assertTrue(d.diagnostic(self.registry,'photocraft',self.cargo,self.env('photocraft'))['version'].startswith(base+'-nightly.'))
def test_non_table_cargo_sections_are_cli_refusals_without_tracebacks(self):
for manifest in ('workspace=true\n','package=true\n','[workspace]\npackage=true\n',
'workspace=[]\n','package="invalid"\n'):
self.cargo.write_text(manifest); errors=io.StringIO()
args=['fixture','--registry',str(ROOT/'nightly-apps.json'),'--app','photocraft','--cargo',str(self.cargo)]
with self.subTest(manifest=manifest),patch.object(sys,'argv',args),patch.dict(d.os.environ,self.env('photocraft')),contextlib.redirect_stderr(errors),self.assertRaises(SystemExit) as exited:
d.main()
self.assertEqual(exited.exception.code,1)
self.assertIn('diagnostic metadata refused: Cargo',errors.getvalue())
self.assertIn('table',errors.getvalue()); self.assertNotIn('Traceback',errors.getvalue())
def test_missing_or_oversized_diagnostic_version_refuses(self):
for contents in ('[workspace]\n', 'x'*(d.n.MAX_JSON_BYTES+1)):
self.cargo.write_text(contents)
+64 -11
View File
@@ -34,36 +34,36 @@ def archive(receipt, name="ownership.json", extra=None, text=None):
class ReceiptAPI(FakeAPI):
def __init__(self):
self.row = release(1)
def __init__(self, run_id=1):
self.row = release(run_id)
super().__init__([self.row])
self.receipt = o.receipt_for(self.row)
self.raw = archive(self.receipt)
self.run = copy.deepcopy(self.runs[1])
self.run = copy.deepcopy(self.runs[run_id])
self.run.update(status="completed", conclusion="failure", repository={"id": 42, "full_name": CONFIG["repository"]},
head_repository={"id": 42, "full_name": CONFIG["repository"]},
referenced_workflows=[{"path": CONFIG["tooling_workflow_path"] + "@" + PIN, "sha": PIN, "ref": PIN}])
self.job = {"id": 101, "name": CONFIG["publish_job_name"], "run_id": 1, "run_attempt": 1, "head_sha": SHA,
self.job = {"id": 100 * (run_id - 1) + 101, "name": CONFIG["publish_job_name"], "run_id": run_id, "run_attempt": 1, "head_sha": SHA,
"status": "completed", "conclusion": "success", "started_at": "2026-11-21T00:00:01Z", "completed_at": "2026-11-21T00:01:00Z",
"steps": [{"name": CONFIG["publish_step_name"], "number": 8, "status": "completed", "conclusion": "success",
"started_at": "2026-11-21T00:00:02Z", "completed_at": "2026-11-21T00:00:20Z"},
{"name": CONFIG["upload_step_name"], "number": 9, "status": "completed", "conclusion": "success",
"started_at": "2026-11-21T00:00:21Z", "completed_at": "2026-11-21T00:00:40Z"}]}
self.artifact = {"id": 201, "name": o.artifact_name(self.receipt), "expired": False, "size_in_bytes": len(self.raw),
self.artifact = {"id": 100 * (run_id - 1) + 201, "name": o.artifact_name(self.receipt), "expired": False, "size_in_bytes": len(self.raw),
"digest": "sha256:" + hashlib.sha256(self.raw).hexdigest(), "created_at": "2026-11-21T00:00:30Z", "updated_at": "2026-11-21T00:00:31Z",
"workflow_run": {"id": 1, "repository_id": 42, "head_repository_id": 42, "head_branch": "main", "head_sha": SHA}}
"workflow_run": {"id": run_id, "repository_id": 42, "head_repository_id": 42, "head_branch": "main", "head_sha": SHA}}
self.jobs, self.artifacts = [self.job], [self.artifact]
self.artifact_readback = None
self.downloads = []
def request(self, method, suffix, data=None):
if method == "GET" and suffix == "/actions/runs/1/attempts/1":
if method == "GET" and suffix == f"/actions/runs/{self.row['id']}/attempts/1":
self.calls.append((method, suffix)); return copy.deepcopy(self.run)
if method == "GET" and suffix.startswith("/actions/runs/1/attempts/1/jobs?"):
if method == "GET" and suffix.startswith(f"/actions/runs/{self.row['id']}/attempts/1/jobs?"):
self.calls.append((method, suffix)); return {"total_count": len(self.jobs), "jobs": copy.deepcopy(self.jobs)}
if method == "GET" and suffix.startswith("/actions/runs/1/artifacts?"):
if method == "GET" and suffix.startswith(f"/actions/runs/{self.row['id']}/artifacts?"):
self.calls.append((method, suffix)); return {"total_count": len(self.artifacts), "artifacts": copy.deepcopy(self.artifacts)}
if method == "GET" and suffix == "/actions/artifacts/201":
if method == "GET" and suffix == f"/actions/artifacts/{self.artifact['id']}":
self.calls.append((method, suffix)); return copy.deepcopy(self.artifact_readback or self.artifact)
return super().request(method, suffix, data)
@@ -94,6 +94,32 @@ class OwnershipTests(unittest.TestCase):
self.api.job["conclusion"] = "failure" # Later pruning step failed, but receipt steps succeeded.
self.assertTrue(self.verify())
def test_malformed_receipt_marker_raises_invalid_metadata_not_keyerror(self):
for marker in ("{}", "null", "[]", "{", '{"identity": null, "run": {}}'):
row = {**self.api.row, "body": o.policy.MARKER + marker}
with self.subTest(marker=marker), self.assertRaises(n.InvalidNightly):
o.receipt_for(row)
def test_offsets_and_subseconds_preserve_exact_chronology(self):
self.api.job["steps"][0].update(started_at="2026-11-20T16:00:02.000-08:00", completed_at="2026-11-20T16:00:20.250-08:00")
self.api.job["steps"][1].update(started_at="2026-11-21T01:00:20.251+01:00", completed_at="2026-11-21T00:00:40.000Z")
self.assertTrue(self.verify())
self.api.job["steps"][1]["started_at"] = "2026-11-21T01:00:20.249+01:00"
with self.assertRaisesRegex(n.InvalidNightly, "chronology"):
self.verify()
for timestamp in ("2026-11-21T00:00:02", "2026-02-30T00:00:02Z", "2026-11-21T00:00:02+00:99", "2026-11-21T00:00:02.0000001Z"):
with self.subTest(timestamp=timestamp), self.assertRaises(n.InvalidNightly):
o.actions_timestamp(timestamp)
# Do not widen the shared producer timestamp contract.
with self.assertRaises(n.InvalidNightly):
o.policy.timestamp("2026-11-21T00:00:02.000+00:00")
def test_job_attempt_still_requires_exact_authenticated_value(self):
del self.api.job["run_attempt"]
with self.assertRaisesRegex(n.InvalidNightly, "ownership job run_attempt"):
self.verify()
self.assertEqual(self.api.downloads, [])
def test_wrong_repository_fork_run_attempt_event_workflow_or_source(self):
mutations = [lambda api: api.run.update(id=2), lambda api: api.run.update(run_attempt=2),
lambda api: api.run.update(status="in_progress"), lambda api: api.run.update(head_sha="c"*40),
@@ -187,6 +213,32 @@ class OwnershipTests(unittest.TestCase):
with self.subTest(mode=mode), self.assertRaises(n.InvalidNightly): o.bounded_list(api, "/jobs", "jobs")
if mode == "full": self.assertEqual(len(api.calls), o.MAX_PAGES)
def test_signed_blob_transport_errors_never_expose_signed_url(self):
api = type("Transport", (), {"prefix": "/repos/storytold/photocraft", "token": "FAKE_TOKEN"})()
secret = "private-signature-fixture"
origin = "https://productionresultssa4.blob.core.windows.net/"
for suffix in ("a b?sig="+secret, "a?sig="+secret+"\x7f", "a?sig="+secret+"é"):
with self.subTest(suffix=suffix), patch.object(o.http.client, "HTTPSConnection") as connection:
response = connection.return_value.getresponse.return_value
response.status = 302; response.getheader.return_value = origin + suffix
with self.assertRaises(n.InvalidNightly) as refused:
o.download_artifact(api, 201)
self.assertNotIn(secret, str(refused.exception))
self.assertEqual(connection.call_count, 1)
from unittest.mock import MagicMock
for failure in (o.http.client.InvalidURL, o.http.client.HTTPException, OSError, ValueError):
with self.subTest(failure=failure), patch.object(o.http.client, "HTTPSConnection") as connection:
auth, blob = MagicMock(), MagicMock()
connection.side_effect = [auth, blob]
auth.getresponse.return_value.status = 302
auth.getresponse.return_value.getheader.return_value = origin + "a%20b?sig=" + secret
blob.request.side_effect = failure(origin + "?sig=" + secret)
with self.assertRaises(n.Unavailable) as refused:
o.download_artifact(api, 201)
self.assertNotIn(secret, str(refused.exception))
self.assertTrue(refused.exception.__suppress_context__)
blob.close.assert_called_once()
def test_signed_blob_redirect_is_bounded_and_never_receives_github_token(self):
api = type("Transport", (), {"prefix": "/repos/storytold/photocraft", "token": "FAKE_TOKEN"})()
with patch.object(o.http.client, "HTTPSConnection") as connection:
@@ -195,11 +247,12 @@ class OwnershipTests(unittest.TestCase):
blob = MagicMock()
connection.side_effect = [auth, blob]
auth.getresponse.return_value.status = 302
auth.getresponse.return_value.getheader.return_value = "https://productionresultssa4.blob.core.windows.net/a?sig=fixture"
auth.getresponse.return_value.getheader.return_value = "https://productionresultssa4.blob.core.windows.net/a%20b?sig=fixture"
blob.getresponse.return_value.status = 200; blob.getresponse.return_value.read.return_value = b"zip"
self.assertEqual(o.download_artifact(api, 201), b"zip")
self.assertEqual(auth.request.call_args.kwargs["headers"]["Authorization"], "Bearer FAKE_TOKEN")
self.assertNotIn("Authorization", blob.request.call_args.kwargs["headers"])
self.assertEqual(blob.request.call_args.args[1], "/a%20b?sig=fixture")
for url in ("http://productionresultssa4.blob.core.windows.net/a", "https://attacker.blob.core.windows.net/a", "https://api.github.com/evil", "https://productionresultssa4.blob.core.windows.net:444/a", "https://u:p@productionresultssa4.blob.core.windows.net/a", "https://productionresultssa4.blob.core.windows.net/a#f"):
with self.subTest(url=url), patch.object(o.http.client, "HTTPSConnection") as connection:
response = connection.return_value.getresponse.return_value
+20 -2
View File
@@ -42,6 +42,23 @@ class PolicyTests(unittest.TestCase):
self.ci={**self.run,'id':3456,'workflow_id':72,'path':'.github/workflows/fixture-ci.yml','event':'push','status':'completed','conclusion':'success'}
self.api=FixtureAPI(self)
def gate(self): return p.publication_gate(self.api,self.registry,self.config,self.prepared,self.policy,self.env)
def test_verify_cli_reports_only_local_sidecar_validation(self):
import io
import os
import publish_nightly
paths={'registry':self.registry,'config':self.config,'identity':self.prepared,'policy':self.policy}
argv=['nightly_policy.py','verify','--registry','registry','--config','config','--app','photocraft','--identity','identity','--policy','policy']
with patch.object(sys,'argv',argv),patch.dict(os.environ,self.env,clear=True), \
patch.object(n,'bounded_json',side_effect=paths.__getitem__), \
patch.object(p,'summary') as report,patch.object(publish_nightly,'HTTPTransport') as transport, \
patch.object(sys,'stdout',io.StringIO()):
p.main()
transport.assert_not_called()
label,body=report.call_args.args
self.assertEqual(label,'local validation passed')
self.assertIn('were not queried',body)
self.assertNotIn('workflow is active',body)
def test_stable_numeric_semver_not_cargo_or_release_api_order(self):
rows=[dict(self.stable,id=34,tag_name='v0.9.0'),self.stable,dict(self.stable,id=35,tag_name='v0.24.0+build.2'),dict(self.stable,id=36,tag_name='v99.0.0',draft=True),dict(self.stable,id=37,tag_name='v88.0.0-beta',prerelease=True)]
self.assertEqual(p.stable_base(rows)['version'],'0.24.0')
@@ -211,9 +228,10 @@ class PolicyTests(unittest.TestCase):
with self.subTest(change=change),self.assertRaisesRegex(ValueError,'publication paused'): self.gate()
self.api.workflow={}
with self.assertRaises(ValueError): p.preflight(self.api,self.config,self.policy)
def test_fresh_active_read_is_last_in_every_publication_guard(self):
def test_fresh_run_order_read_follows_final_active_check(self):
self.assertTrue(self.gate())
self.assertEqual(self.api.calls[-1],('GET','/actions/workflows/91'))
self.assertEqual(self.api.calls[-2],('GET','/actions/workflows/91'))
self.assertTrue(self.api.calls[-1][1].startswith('/actions/workflows/91/runs?'))
self.api.workflow['state']='disabled_manually'
with self.assertRaisesRegex(ValueError,'paused'): self.gate()
self.assertEqual(self.api.calls[-1],('GET','/actions/workflows/91'))
+127 -1
View File
@@ -180,7 +180,8 @@ class BaselineTests(unittest.TestCase):
with self.assertRaisesRegex(ValueError,'main head moved'): self.gate()
def test_publication_gate_keeps_last_active_and_fresh_same_head_check(self):
self.assertTrue(p.publication_gate(self.api,self.registry,self.config,self.prepared,self.policy,self.env))
self.assertEqual(self.api.calls[-2:],[('GET','/git/ref/heads/main'),('GET','/actions/workflows/91')])
self.assertEqual(self.api.calls[-3:-1],[('GET','/git/ref/heads/main'),('GET','/actions/workflows/91')])
self.assertTrue(self.api.calls[-1][1].startswith('/actions/workflows/91/runs?'))
def test_config_digest_survives_serialization_and_prior_validation(self):
restored=json.loads(json.dumps(self.policy))
p.validate_prepared(self.registry,self.prepared,restored,self.env,self.config)
@@ -202,6 +203,63 @@ class BaselineTests(unittest.TestCase):
for url in ('https://api.github.com.evil/repos/storytold/photocraft/check-runs/200','http://api.github.com/repos/storytold/photocraft/check-runs/200','https://api.github.com/repos/fork/photocraft/check-runs/200'):
self.job['check_run_url']=url
with self.subTest(url=url),self.assertRaisesRegex(ValueError,'fixed-host'): self.gate()
def expand_policy_workflows(self,counts):
template=copy.deepcopy(self.wanted)
self.row['required_checks']=[]; self.row['baseline']['runs']=[]
self.api.runs={1234:self.run}; self.api.jobs={}; self.api.checks={}
paths={}
for index,count in enumerate(counts):
workflow=100+index; path=f'.github/workflows/fixture-{workflow}.yml'; paths[workflow]=path
for sha,run_template,job_template,check_template,run_id in (
('c'*40,self.base_run,self.base_job,self.base_check,10000+index),
('a'*40,self.ci,self.job,self.check,20000+index)):
run={**run_template,'id':run_id,'workflow_id':workflow,'path':path}
self.api.runs[run_id]=run; jobs=[]
if sha=='c'*40:
self.row['baseline']['runs'].append({'workflow_id':workflow,'id':run_id,'attempt':1,'number':16})
for number in range(count):
ident=run_id*1000+number; check_id=ident+100000000; name=f'quality {index}/{number}'
job={**job_template,'id':ident,'run_id':run_id,'name':name,'check_run_url':f'https://api.github.com/repos/storytold/photocraft/check-runs/{check_id}'}
check={**check_template,'id':check_id,'name':name,'details_url':f'https://github.com/storytold/photocraft/actions/runs/{run_id}/job/{ident}'}
jobs.append(job); self.api.checks[check_id]=check
if sha=='c'*40:
self.row['required_checks'].append({**template,'name':name,'workflow_id':workflow,'workflow_path':path,'baseline_job_id':ident,'baseline_check_id':check_id})
self.api.jobs[(run_id,1)]=jobs
def hook(path):
parsed=urlsplit(path); query=parse_qs(parsed.query)
match=re.fullmatch(r'/actions/workflows/([0-9]+)(/runs)?',parsed.path)
if match and int(match[1]) in paths:
workflow=int(match[1])
if not match[2]: return {'id':workflow,'path':paths[workflow],'state':'active'}
rows=[run for run in self.api.runs.values() if run['workflow_id']==workflow and run['head_sha']==query['head_sha'][0]]
page=int(query['page'][0]); size=int(query['per_page'][0])
return {'total_count':len(rows),'workflow_runs':rows[(page-1)*size:page*size]}
self.api.hook=hook; self.bind()
def test_supported_32_workflow_128_job_normal_witness_fits_read_budget(self):
self.expand_policy_workflows([4]*32)
self.assertTrue(self.gate())
self.assertEqual(len(self.api.calls),607)
self.assertLess(len(self.api.calls),p.MAX_BASELINE_READS)
def test_supported_policy_with_more_job_pages_retains_final_rechecks(self):
self.expand_policy_workflows([20]*5+[2]+[1]*26)
self.assertTrue(self.gate())
self.assertEqual(len(self.api.calls),617)
self.assertEqual(sum(path.startswith('/actions/workflows/100/runs?') for _,path in self.api.calls),6)
def test_read_limit_is_hard_and_deadline_remains_120_seconds(self):
class API:
calls=0
def request(self,method,path): self.calls+=1; return {}
api=API()
with patch.object(p.time,'monotonic',return_value=0):
bounded=p.BaselineReads(api)
self.assertEqual(bounded.deadline,120)
for _ in range(p.MAX_BASELINE_READS): bounded.request('GET','/fixture')
with self.assertRaisesRegex(ValueError,'budget reached'): bounded.request('GET','/fixture')
self.assertEqual(api.calls,p.MAX_BASELINE_READS)
with patch.object(p.time,'monotonic',side_effect=[0,0,120]):
bounded=p.BaselineReads(api)
with self.assertRaisesRegex(ValueError,'time budget reached during read'): bounded.request('GET','/fixture')
def test_read_budget_and_deadline_fail_closed(self):
budget=p.BaselineReads(self.api); budget.remaining=0
with self.assertRaisesRegex(ValueError,'budget reached'): budget.request('GET','/git/ref/heads/main')
@@ -233,6 +291,74 @@ class BaselineTests(unittest.TestCase):
if path=='/check-runs/202': return old_check
self.api.hook=hook
with self.assertRaisesRegex(ValueError,'baseline-green'): self.gate()
def historical_run(self,conclusion='cancelled'):
self.baseline_red(); self.candidate_red()
old={**self.ci,'id':2444,'run_number':16,'conclusion':conclusion}
job={**self.job,'id':97,'run_id':2444,'conclusion':'success','check_run_url':'https://api.github.com/repos/storytold/photocraft/check-runs/202'}
check={**self.check,'id':202,'conclusion':'success','details_url':'https://github.com/storytold/photocraft/actions/runs/2444/job/97'}
self.api.runs[2444]=old; self.api.jobs[(2444,1)]=[job]
self.api.hook=lambda path:check if path=='/check-runs/202' else None
return old,job,check
def test_completed_success_survives_cancelled_or_unknown_historical_aggregate(self):
for conclusion in ('cancelled','timed_out',None):
with self.subTest(conclusion=conclusion):
self.historical_run(conclusion)
with self.assertRaisesRegex(ValueError,'baseline-green'): self.gate()
self.assertIn(('GET','/check-runs/202'),self.api.calls)
def test_cancelled_partial_history_retains_success_without_full_inventory(self):
self.historical_run()
self.api.jobs[(2444,1)].append({'name':'unfinished sibling','status':'completed','conclusion':'cancelled'})
with self.assertRaisesRegex(ValueError,'baseline-green'): self.gate()
def test_cancelled_historical_job_cannot_supply_success_or_failure_exemption(self):
_,job,_=self.historical_run()
for result in ('cancelled','skipped',None):
job['conclusion']=result
self.assertTrue(self.gate()) # Only the selected, reviewed red jobs permit failure.
self.api.jobs[(3456,1)]=[]
with self.assertRaisesRegex(ValueError,'coverage'): self.gate()
def test_historical_success_keeps_job_check_source_and_attempt_authentication(self):
_,job,check=self.historical_run()
for obj,key,value in ((job,'head_sha','e'*40),(job,'run_attempt',2),(job,'run_id',1111),
(check,'app',{'id':999}),(check,'head_sha','e'*40),
(check,'id',999),(check,'conclusion','cancelled'),
(check,'details_url','https://github.com/storytold/photocraft/actions/runs/2444/job/999')):
original=copy.deepcopy(obj[key]); obj[key]=value
with self.subTest(key=key,value=value),self.assertRaises(ValueError): self.gate()
obj[key]=original
def test_cancelled_prior_attempt_keeps_completed_success(self):
self.baseline_red(); self.candidate_red(); self.ci['run_attempt']=2; self.job['run_attempt']=2
self.api.jobs[(3456,2)]=[self.job]
self.api.jobs[(3456,1)]=[{**self.job,'id':97,'run_attempt':1,'conclusion':'success','check_run_url':'https://api.github.com/repos/storytold/photocraft/check-runs/202'}]
check={**self.check,'id':202,'conclusion':'success','details_url':'https://github.com/storytold/photocraft/actions/runs/3456/job/97'}
def hook(path):
if path=='/check-runs/202': return check
if path=='/actions/runs/3456/attempts/1': return {**self.ci,'run_attempt':1,'conclusion':'cancelled'}
self.api.hook=hook
with self.assertRaisesRegex(ValueError,'baseline-green'): self.gate()
def test_selected_cancelled_aggregate_is_still_refused(self):
self.ci['conclusion']='cancelled'
with self.assertRaisesRegex(ValueError,'aggregate result differs'): self.gate()
def test_publication_expiry_is_rechecked_after_last_remote_read(self):
reads=[0]
def hook(path):
if path.startswith('/actions/workflows/91/runs?'):
reads[0]+=1
if reads[0]==2: p.time.time.return_value=p.timestamp(self.row['baseline']['expires_at'])
self.api.hook=hook
with self.assertRaisesRegex(ValueError,'stale/future'):
p.publication_gate(self.api,self.registry,self.config,self.prepared,self.policy,self.env)
self.assertEqual(reads[0],2)
self.assertTrue(self.api.calls[-1][1].startswith('/actions/workflows/91/runs?'))
def test_newer_run_appearing_during_final_active_read_is_refused(self):
paused=[False]
def hook(path):
if path=='/actions/workflows/91': paused[0]=True
if paused[0] and path.startswith('/actions/workflows/91/runs?'):
return {'total_count':2,'workflow_runs':[self.run,{**self.run,'id':12,'run_number':18}]}
self.api.hook=hook
with self.assertRaisesRegex(ValueError,'newer trusted workflow ordinal'):
p.publication_gate(self.api,self.registry,self.config,self.prepared,self.policy,self.env)
def test_schema_rejects_extra_keys_and_non_boolean_floor(self):
self.wanted['green_required']=1; self.bind()
with self.assertRaisesRegex(ValueError,'green floor'): self.gate()
+71
View File
@@ -5,6 +5,7 @@ import io
import json
from pathlib import Path
import sys
import tempfile
import unittest
from unittest.mock import patch
@@ -133,6 +134,76 @@ class PruneTests(unittest.TestCase):
return p.execute(self.api, self.registry, plan or self.plan(), approved=True,
provenance=self.proof, checkpoint=self.saved.append, **kwargs)
def test_malformed_historical_policy_is_retained_without_hiding_other_candidates(self):
malformed = ["{}", "null", "[]", "{", '{"identity": null, "run": {}}']
for key in ("identity", "run", "stable_base", "tooling_revision"):
body = policy.body_policy(self.rows[0]["body"])
del body[key]
malformed.append(json.dumps(body))
for key in ("id", "attempt", "event", "repository", "workflow_path", "source_commit", "created_at"):
body = policy.body_policy(self.rows[0]["body"])
body["run"][key] = []
malformed.append(json.dumps(body))
for marker in malformed:
self.setUp()
self.api.rows[0]["body"] = policy.MARKER + marker
with self.subTest(marker=marker):
previous = self.plan()
self.assertIn(1, [row["release_id"] for row in previous["retained"]])
self.assertNotIn(1, self.proof.calls)
self.assertIn(2, self.proof.calls)
self.assertEqual(self.api.deletes(), [])
def test_successful_null_or_nonobject_lookup_is_never_absence(self):
api = type("Lookup", (), {})()
for value in (None, [], "null", 1, False):
api.request = lambda *args: value
with self.subTest(value=value), self.assertRaisesRegex(n.InvalidNightly, "must return an object"):
p.optional(api, "/releases/1")
api.request = lambda *args: {}
self.assertEqual(p.optional(api, "/releases/1"), {})
def absent(*args): raise p.APIError(404)
api.request = absent
self.assertIsNone(p.optional(api, "/releases/1"))
def test_null_after_release_delete_preserves_tag_and_later_candidate(self):
previous = self.plan()
original = self.api.request
def null_after_delete(method, path, data=None):
if method == "GET" and path == "/releases/1" and not any(row["id"] == 1 for row in self.api.rows):
return None
return original(method, path, data)
self.api.request = null_after_delete
with self.assertRaisesRegex(n.InvalidNightly, "must return an object"):
self.execute(previous)
self.assertEqual(self.api.deletes(), [("DELETE", "/releases/1")])
self.assertIn(self.rows[0]["tag_name"], self.api.refs)
def test_large_retained_diagnostics_fit_shared_plan_budget(self):
unrelated = [{"id": run, "tag_name": "x" * 195 + str(run)} for run in range(100, 450)]
self.api.rows.extend(unrelated)
previous = self.plan()
raw = p.encode_plan(previous)
self.assertGreater(len(raw), 64 * 1024)
self.assertLessEqual(len(raw), p.MAX_PLAN_BYTES)
self.assertEqual(p.parse_plan_bytes(raw), previous)
self.assertEqual([row["id"] for row in previous["candidates"]], [1, 2])
with patch.object(p, "MAX_PLAN_BYTES", len(raw) - 1), self.assertRaisesRegex(n.InvalidNightly, "checkpoint byte budget"):
self.plan()
self.assertEqual(self.api.deletes(), [])
def test_local_checkpoint_preserves_verified_bytes_and_rejects_different_plan(self):
previous = self.plan()
raw = (json.dumps(previous, indent=2) + "\n").encode()
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / "checkpoint.json"
p.save_checkpoint(path, previous, raw=raw)
self.assertEqual(path.read_bytes(), raw)
with self.assertRaisesRegex(n.InvalidNightly, "bytes differ"):
p.save_checkpoint(path, {**previous, "bot_id": BOT + 1}, raw=raw)
self.assertEqual(path.read_bytes(), raw)
self.assertFalse(path.with_suffix(".json.new").exists())
def test_keep_seven_oldest_first_release_then_tag(self):
previous = self.plan()
self.assertEqual(previous["keep"], [9, 8, 7, 6, 5, 4, 3])
+56 -4
View File
@@ -3,16 +3,19 @@ import hashlib
import io
import json
from pathlib import Path
from unittest.mock import patch
import sys
import unittest
import zipfile
ROOT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(ROOT/'scripts'))
import nightly_prune_checkpoint as c
import nightly_prune as p
import nightly_feed as n
class CheckpointTests(unittest.TestCase):
def setUp(self):
self.env={'GITHUB_REPOSITORY':'storytold/photocraft','GITHUB_REF':'refs/heads/main','GITHUB_EVENT_NAME':'workflow_dispatch','GITHUB_SHA':'a'*40,'GITHUB_RUN_ID':'123','GITHUB_RUN_ATTEMPT':'1','TOOLING_REVISION':'b'*40}
self.config={'repository':'storytold/photocraft','repository_id':1,'producer_workflow_id':2,'producer_workflow_path':'.github/workflows/nightly.yml','tooling_workflow_path':'storytold/craft-common-actions/.github/workflows/nightly.yml','allowed_tooling_revisions':['b'*40]}
self.plan={'schema':'test plan fixture','keep':[7],'candidates':[]};self.raw=self.archive(json.dumps(self.plan))
self.plan={'schema':'test plan fixture','keep':[7],'candidates':[]};self.plan_bytes=json.dumps(self.plan).encode();self.raw=self.archive(self.plan_bytes)
self.digest=hashlib.sha256(self.raw).hexdigest()
self.run={'id':123,'run_attempt':1,'workflow_id':2,'path':'.github/workflows/nightly.yml','head_branch':'main','head_sha':'a'*40,'event':'workflow_dispatch','repository':{'id':1,'full_name':'storytold/photocraft'},'head_repository':{'id':1,'full_name':'storytold/photocraft'},'referenced_workflows':[{'path':self.config['tooling_workflow_path']+'@'+'b'*40,'sha':'b'*40}],'created_at':'2026-11-21T12:00:00Z'}
self.artifact={'id':3,'name':'nightly-prune-plan-123-1','expired':False,'size_in_bytes':len(self.raw),'digest':'sha256:'+self.digest,'workflow_run':{'id':123,'repository_id':1,'head_repository_id':1,'head_sha':'a'*40,'head_branch':'main'},'created_at':'2026-11-21T12:01:00Z','updated_at':'2026-11-21T12:01:00Z'}
@@ -27,8 +30,8 @@ class CheckpointTests(unittest.TestCase):
self.calls.append((method,path));self.assertEqual(method,'GET')
if path.startswith('/actions/runs/'):return copy.deepcopy(self.run)
return copy.deepcopy(self.artifact)
def download_artifact(self,ident):self.assertEqual(ident,3);return self.raw
def verify(self,plan=None):return c.verify(self,self.config,self.plan if plan is None else plan,'3',self.digest,self.env)
def download_artifact(self,ident, *, max_bytes):self.assertEqual(ident,3);self.assertEqual(max_bytes,c.MAX_CHECKPOINT_ARCHIVE);return self.raw
def verify(self,plan_bytes=None):return c.verify(self,self.config,self.plan_bytes if plan_bytes is None else plan_bytes,'3',self.digest,self.env)
def test_exact_uploaded_plan_readback_before_mutation(self):
self.assertTrue(self.verify());self.assertEqual(self.calls[-1],('GET','/actions/artifacts/3'))
def test_wrong_run_attempt_source_repo_or_workflow_refuses(self):
@@ -42,7 +45,7 @@ class CheckpointTests(unittest.TestCase):
with self.subTest(key=key),self.assertRaises(ValueError):self.verify()
self.artifact=original
def test_exact_plan_equality_not_just_digest_shape(self):
with self.assertRaises(ValueError):self.verify({'different':'plan'})
with self.assertRaises(ValueError):self.verify(b'{"different":"plan"}')
def test_duplicate_json_and_extra_member_refuse(self):
for raw in [self.archive('{"x":1,"x":2}'),self.archive(json.dumps(self.plan),extra=True)]:
self.raw=raw;self.digest=hashlib.sha256(raw).hexdigest();self.artifact.update(size_in_bytes=len(raw),digest='sha256:'+self.digest)
@@ -50,6 +53,55 @@ class CheckpointTests(unittest.TestCase):
def test_changed_download_bytes_refuse(self):
self.raw+=b'x'
with self.assertRaises(ValueError):self.verify()
def set_archive(self, data):
self.raw=self.archive(data);self.digest=hashlib.sha256(self.raw).hexdigest()
self.artifact.update(size_in_bytes=len(self.raw),digest='sha256:'+self.digest)
def test_reindented_reordered_or_newline_changed_local_bytes_refuse(self):
for data in (json.dumps(self.plan,indent=2).encode(),json.dumps(self.plan,sort_keys=True).encode(),self.plan_bytes+b'\n'):
self.assertEqual(json.loads(data),self.plan)
with self.subTest(data=data),self.assertRaisesRegex(ValueError,'exact local prune plan bytes'):self.verify(data)
def test_large_plan_above_ownership_receipt_bound_is_supported(self):
self.plan_bytes=p.encode_plan({'retained':[{'tag':'x'*400+str(i)} for i in range(350)]})
self.set_archive(self.plan_bytes)
self.assertGreater(len(self.plan_bytes),128*1024)
self.assertTrue(self.verify())
def test_exact_maximum_plan_member_is_supported(self):
self.plan_bytes += b' '*(c.MAX_PLAN_BYTES-len(self.plan_bytes))
self.set_archive(self.plan_bytes)
self.assertLessEqual(len(self.raw),c.MAX_CHECKPOINT_ARCHIVE)
self.assertTrue(self.verify())
def test_member_and_archive_budgets_are_independently_enforced(self):
self.set_archive(b'x'*(c.MAX_PLAN_BYTES+1))
with self.assertRaisesRegex(ValueError,'invalid checkpoint member'):self.verify()
self.setUp();self.artifact['size_in_bytes']=c.MAX_CHECKPOINT_ARCHIVE+1
with self.assertRaisesRegex(ValueError,'uploaded plan metadata'):self.verify()
self.setUp()
with self.assertRaisesRegex(ValueError,'local prune plan exceeds bound'):self.verify(b'x'*(c.MAX_PLAN_BYTES+1))
self.assertEqual(self.calls,[])
def test_exact_local_bytes_used_by_cli_validation_checkpoint_and_execution(self):
from test_nightly_ownership import CONFIG
from test_nightly_prune import BOT, FakeAPI, MockProvenance, release
registry=json.loads((ROOT/'nightly-apps.json').read_text())
rows=[release(i) for i in range(1,10)]
previous=p.plan(FakeAPI(rows),registry,'photocraft',9,BOT,MockProvenance(rows))
self.plan_bytes=(json.dumps(previous,indent=2)+'\n').encode()
self.set_archive(self.plan_bytes)
self.config={**CONFIG,**self.config}
args=['nightly_prune.py','apply','--registry','registry.json','--app','photocraft','--current-release-id','9','--bot-id',str(BOT),'--config','ownership.json','--plan','input.json','--checkpoint','saved.json','--approve-first-run','--checkpoint-artifact-id','3','--checkpoint-artifact-sha256',self.digest]
def apply(api,registry,loaded,**kwargs):
self.assertEqual(loaded,previous)
kwargs['checkpoint'](loaded)
return {'completed_release_ids':[]}
with patch.object(sys,'argv',args),patch.object(p.n,'bounded_json',side_effect=[registry,self.config]),patch.object(p.n,'bounded_bytes',return_value=self.plan_bytes) as local_read,patch.object(p,'PruneTransport',return_value=self),patch.object(p,'execute',side_effect=apply) as execute,patch.object(p,'save_checkpoint') as checkpoint,patch.dict(p.os.environ,self.env),patch('sys.stdout',new_callable=io.StringIO):
p.main()
local_read.assert_called_once_with('input.json',p.MAX_PLAN_BYTES,'prune plan')
execute.assert_called_once()
checkpoint.assert_called_once_with('saved.json',previous,raw=self.plan_bytes)
self.calls=[]
with patch.object(sys,'argv',args),patch.object(p.n,'bounded_json',side_effect=[registry,self.config]),patch.object(p.n,'bounded_bytes',return_value=self.plan_bytes+b' '),patch.object(p,'PruneTransport',return_value=self),patch.object(p,'execute') as execute,patch.dict(p.os.environ,self.env),patch('sys.stderr',new_callable=io.StringIO),self.assertRaises(SystemExit) as stop:
p.main()
self.assertEqual(stop.exception.code,1)
execute.assert_not_called()
def test_cli_requires_durable_upload_before_execute(self):
source=(ROOT/'scripts/nightly_prune.py').read_text();self.assertIn('--checkpoint-artifact-id',source);self.assertLess(source.index('verify_durable(api,'),source.index('result = execute(api,'))
source=(ROOT/'.github/workflows/nightly.yml').read_text();self.assertIn('Upload nightly prune plan before any deletion',source);self.assertIn('if: ${{ false }} # Separate hard-off',source)
+116
View File
@@ -0,0 +1,116 @@
"""Synthetic boundary regressions for the private PR315 review correction."""
import json
from pathlib import Path
import re
import sys
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_ownership_receipt as ownership
import publish_nightly as publisher
WINDOWS_NAMES={'WINDOWS_CERTIFICATE','WINDOWS_CERTIFICATE_PASSWORD','AZURE_TENANT_ID','AZURE_CLIENT_ID','AZURE_CLIENT_SECRET','AZURE_SIGNING_ENDPOINT','AZURE_SIGNING_ACCOUNT','AZURE_CERT_PROFILE'}
def job(source,name):
tail=source.split(' '+name+':\n',1)[1]
return re.split(r'^ [a-z][a-z0-9_-]*:\n',tail,maxsplit=1,flags=re.M)[0]
class WorkflowReviewTests(unittest.TestCase):
def test_explicit_eight_name_contract_at_each_windows_boundary(self):
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):
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')):
forwarded=re.findall(r'^ ([A-Z_]+): \$\{\{ secrets\.([A-Z_]+) \}\}',source,re.M)
self.assertEqual(set(forwarded),{(name,name) for name in WINDOWS_NAMES})
for source in (common,windows,caller):
self.assertNotIn('secrets: inherit',source)
for name in ('build-linux','build-macos'):
self.assertNotIn('secrets:',job(common,name))
self.assertNotIn('secrets.',job(windows,'build'))
self.assertNotIn('environment:',job(windows,'build'))
def test_hidden_staging_uploads_are_explicitly_enabled(self):
count=0
for name in ('nightly.yml','nightly-windows.yml','nightly-signing-unix.yml'):
source=(ROOT/'.github/workflows'/name).read_text()
for step in re.split(r'(?=^ - )',source,flags=re.M):
if 'uses: actions/upload-artifact@' in step and re.search(r'^\s+path:.*\.nightly|^\s+\.nightly',step,re.M):
count+=1
self.assertIn('include-hidden-files: true',step)
self.assertGreaterEqual(count,10)
def test_linux_helpers_select_supported_python_without_enabling_jobs(self):
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.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'))
def test_diagnostics_have_no_nested_build_or_write_token(self):
source=(ROOT/'.github/workflows/nightly-diagnostics.yml').read_text()
self.assertNotIn('release.yml',source)
self.assertNotIn('packages:',source)
self.assertNotIn(': write',source)
self.assertIn('Legacy packaging diagnostics are paused',source)
example=(ROOT/'examples/nightly-diagnostics.yml').read_text()
self.assertNotIn(': write',example)
def test_status_requires_requested_packet_staging(self):
source=job((ROOT/'.github/workflows/nightly.yml').read_text(),'status')
self.assertIn('build-macos, stage-nightly]',source)
self.assertIn('STAGING_RESULT: ${{ needs.stage-nightly.result }}',source)
self.assertIn('test "$STAGING_RESULT" = success',source)
class PublicationReceiptReviewTests(unittest.TestCase):
def setUp(self):
self.temp=tempfile.TemporaryDirectory();self.addCleanup(self.temp.cleanup)
self.output=Path(self.temp.name)/'ownership'
registry=json.loads((ROOT/'nightly-apps.json').read_text())
self.ident,_=n.identity(registry,'photocraft','storytold/photocraft','a'*40,'1.2.3',123,1,1795190400)
self.env={'GITHUB_REPOSITORY':'storytold/photocraft','GITHUB_REF':'refs/heads/main','GITHUB_EVENT_NAME':'workflow_dispatch','GITHUB_SHA':'a'*40,'GITHUB_RUN_ID':'123','GITHUB_RUN_ATTEMPT':'1','TOOLING_REVISION':'b'*40}
self.release={'id':7,'tag_name':self.ident['tag'],'target_commitish':'a'*40,'prerelease':True,'draft':False}
def publish(self):
return publisher.publish_with_receipt(object(),self.ident,{},'unused',guard=lambda:True,policy={},environment=self.env,ownership_directory=self.output)
def test_existing_output_refuses_before_publication_and_preserves_bytes(self):
self.output.mkdir();(self.output/'keep').write_bytes(b'unchanged')
with patch.object(publisher,'publish_packet') as publish,self.assertRaisesRegex(ValueError,'must be new'):
self.publish()
publish.assert_not_called();self.assertEqual((self.output/'keep').read_bytes(),b'unchanged')
def test_unwritable_output_refuses_before_publication(self):
with patch.object(Path,'open',side_effect=PermissionError('synthetic unwritable destination')),patch.object(publisher,'publish_packet') as publish,self.assertRaises(PermissionError):
self.publish()
publish.assert_not_called()
def test_receipt_is_opened_before_publication_and_written_after_success(self):
def confirm(*args,**kwargs):
self.assertTrue((self.output/'ownership.json').is_file())
self.assertEqual((self.output/'ownership.json').read_bytes(),b'')
return self.release
with patch.object(publisher,'publish_packet',side_effect=confirm) as publish:
self.assertEqual(self.publish(),self.release)
publish.assert_called_once()
self.assertEqual(json.loads((self.output/'ownership.json').read_text())['release_id'],7)
def test_post_publication_receipt_failure_has_distinct_reconciliation_state(self):
with patch.object(publisher,'publish_packet',return_value=self.release) as publish,patch.object(ownership,'emit',side_effect=OSError('synthetic disk full')),self.assertRaisesRegex(publisher.PublishedWithoutReceipt,'release 7 is public.*reconciliation.*do not recreate'):
self.publish()
publish.assert_called_once()
def test_pre_publication_gate_failure_is_not_reported_as_confirmed_public(self):
with patch.object(publisher,'publish_packet',side_effect=n.InvalidNightly('synthetic gate refusal')),self.assertRaisesRegex(n.InvalidNightly,'gate refusal') as result:
self.publish()
self.assertNotIsInstance(result.exception,publisher.PublishedWithoutReceipt)
if __name__=='__main__':unittest.main()
+17 -8
View File
@@ -5,6 +5,7 @@ import hashlib
import io
import json
import os
import re
from pathlib import Path
import stat
import struct
@@ -335,17 +336,25 @@ class SigningWorkflowTests(unittest.TestCase):
self.assertNotIn('${{ secrets.WINDOWS_CERTIFICATE }}',config)
self.assertIn('needs: signing-config',self.windows)
def assert_protected_signer(self,source,job):
block=re.split(r'\n [A-Za-z0-9_-]+:\n',source.split(' '+job+':\n',1)[1],maxsplit=1)[0]
self.assertIn('environment: nightly-signing',block)
for guard in ("github.repository == 'storytold/photocraft'","github.ref == 'refs/heads/main'",
"github.event_name == 'schedule'","github.event_name == 'workflow_dispatch'"):
self.assertIn(guard,block)
self.assertNotIn('cargo build',block); self.assertNotIn('nightly_smoke.py',block)
self.assertNotIn('secrets: inherit',block)
self.assertIn('job.workflow_sha',block); self.assertIn('digest-mismatch: error',block)
def test_clean_signer_uses_protected_environment_and_literal_trust_guard(self):
for source,jobs in ((self.windows,('windows',)),(self.sign_unix,('linux','macos'))):
for job in jobs:
block=source.split(' '+job+':\n',1)[1]
self.assertIn('environment: nightly-signing',block)
for guard in ("github.repository == 'storytold/photocraft'","github.ref == 'refs/heads/main'",
"github.event_name == 'schedule'","github.event_name == 'workflow_dispatch'"):
self.assertIn(guard,block)
self.assertNotIn('cargo build',block); self.assertNotIn('nightly_smoke.py',block)
self.assertNotIn('secrets: inherit',block)
self.assertIn('job.workflow_sha',block); self.assertIn('digest-mismatch: error',block)
with self.subTest(job=job): self.assert_protected_signer(source,job)
def test_linux_cannot_borrow_the_macos_protected_environment(self):
mutated=self.sign_unix.replace(' environment: nightly-signing\n','',1)
self.assertIn('environment: nightly-signing',mutated) # macOS still has it.
with self.assertRaises(AssertionError): self.assert_protected_signer(mutated,'linux')
def test_actual_secret_values_are_only_scoped_to_signing_steps(self):
for source in (self.windows,self.sign_unix):
+17
View File
@@ -46,6 +46,23 @@ class SmokeTests(unittest.TestCase):
start.assert_not_called()
with patch.object(s.subprocess,'Popen') as start,self.assertRaises(ValueError): s.smoke(self.exe,self.exe.parent/'profile',self.version)
start.assert_not_called()
def test_resolved_installation_ancestry_refuses_symlinked_parent_before_creation(self):
alias=self.root/'alias'; alias.symlink_to(self.exe.parent,target_is_directory=True)
profile=alias/'fresh-profile'
with patch.object(s.subprocess,'Popen') as start,self.assertRaisesRegex(ValueError,'separate from the installation'):
s.smoke(self.exe,profile,self.version)
start.assert_not_called(); self.assertFalse(profile.exists())
with patch.object(s.subprocess,'Popen') as start,self.assertRaisesRegex(ValueError,'separate from the installation'):
s.smoke(alias/self.exe.name,self.exe.parent/'fresh-profile',self.version)
start.assert_not_called()
def test_resolved_separate_sibling_profile_is_still_allowed(self):
sibling=self.root/'profiles'; sibling.mkdir()
alias=self.root/'alias'; alias.symlink_to(sibling,target_is_directory=True)
self.profile=alias/'fresh-profile'
self.assertTrue(self.invoke()['exact_version_and_flavor'])
self.assertEqual(self.argv[4],str(sibling/'fresh-profile'))
def test_timeout_kills_only_the_owned_mock_process(self):
process=types.SimpleNamespace(returncode=None,killed=False)
process.poll=lambda: process.returncode
+65 -2
View File
@@ -1,11 +1,14 @@
"""Self-authored synthetic archives; no app, runtime, signature or E4 proof."""
import contextlib
import copy
import gzip
import importlib.util
import io
import json
import os
from pathlib import Path
import plistlib
import re
import socket
import stat
import struct
@@ -138,6 +141,53 @@ class UnixProducerTests(unittest.TestCase):
self.assertEqual(result['members'],2)
with self.assertRaises(n.InvalidNightly): u.verify_archive(self.pending,'linux-x86_64',archive,self.version,output)
def test_unpack_is_published_only_after_validation_and_failures_are_retryable(self):
output=self.root/'unpacked'
for extra,payload in [([('PHOTOCRAFT',b'bad','file')],self.elf),([],b'not elf')]:
archive=self.tar(extra=extra,payload=payload)
original=u.member_name
def inspect(name):
self.assertFalse(output.exists())
return original(name)
with patch.object(u,'member_name',side_effect=inspect),self.assertRaises(n.InvalidNightly):
u.verify_archive(self.pending,'linux-x86_64',archive,self.version,output)
self.assertFalse(output.exists())
self.assertFalse(list(self.root.glob('.nightly-unpack-*')))
u.verify_archive(self.pending,'linux-x86_64',self.tar(),self.version,output)
self.assertEqual((output/'photocraft').read_bytes(),self.elf)
self.assertFalse(list(self.root.glob('.nightly-unpack-*')))
def test_linux_gzip_crc_length_and_eof_are_checked_before_unpack_publication(self):
archive=self.tar(); original=archive.read_bytes(); output=self.root/'unpacked'
for label,data in [('crc',original[:-8]+bytes([original[-8]^1])+original[-7:]),
('length',original[:-4]+bytes([original[-4]^1])+original[-3:]),
('trailer',original[:-8]),('eof',original[:-1])]:
archive.write_bytes(data)
with self.subTest(label=label),self.assertRaises((OSError,EOFError)):
u.verify_archive(self.pending,'linux-x86_64',archive,self.version,output)
self.assertFalse(output.exists())
self.assertFalse(list(self.root.glob('.nightly-unpack-*')))
archive.write_bytes(original)
u.verify_archive(self.pending,'linux-x86_64',archive,self.version,output)
def test_linux_gzip_truncated_trailer_is_a_cli_refusal_not_a_traceback(self):
archive=self.tar(); archive.write_bytes(archive.read_bytes()[:-8]); errors=io.StringIO()
args=['fixture','inventory','--pending',str(ROOT/'nightly-unix-pending.json'),
'--platform','linux-x86_64','--version',self.version,'--archive',str(archive)]
with patch.object(sys,'argv',args),contextlib.redirect_stderr(errors),self.assertRaises(SystemExit) as exited:
u.main()
self.assertEqual(exited.exception.code,1)
self.assertIn('private Unix nightly unavailable:',errors.getvalue())
self.assertNotIn('Traceback',errors.getvalue())
def test_linux_gzip_drain_is_bounded_including_padding_after_tar_end(self):
archive=self.tar(); expanded=gzip.decompress(archive.read_bytes())
with patch.object(n,'MAX_TOTAL_BYTES',1024),patch.object(u,'MAX_CENTRAL_DIRECTORY',len(expanded)-1024):
u.verify_archive(self.pending,'linux-x86_64',archive,self.version)
archive.write_bytes(gzip.compress(expanded+b'\0'))
with self.assertRaisesRegex(n.InvalidNightly,'expanded archive exceeds bound'):
u.verify_archive(self.pending,'linux-x86_64',archive,self.version)
def test_linux_wrong_arch_missing_executable_or_symlink_is_refused(self):
for payload,mode in [(b'not elf',0o755),(self.macho,0o755),(self.elf,0o644)]:
with self.subTest(mode=mode),self.assertRaises(n.InvalidNightly): u.verify_archive(self.pending,'linux-x86_64',self.tar(payload=payload,mode=mode),self.version)
@@ -182,14 +232,27 @@ class UnixProducerTests(unittest.TestCase):
with self.assertRaises(n.InvalidNightly): u.zip_metadata_bound(io.BytesIO(data),len(data))
class UnixWorkflowTests(unittest.TestCase):
def assert_unprivileged_build(self,source,job):
build=re.split(r'\n [A-Za-z0-9_-]+:\n',source.split(' '+job+':\n',1)[1],maxsplit=1)[0]
self.assertIn(' steps:',build)
self.assertNotIn('secrets.',build); self.assertNotIn('environment:',build)
def test_build_isolation_assertions_cover_the_job_body_not_only_its_if(self):
source=(ROOT/'.github/workflows/nightly-unix.yml').read_text()
for job in ('linux','macos'):
for forbidden in ('environment: nightly-signing','env: ${{ secrets.FIXTURE }}'):
start=source.index(' '+job+':\n')
mutated=source[:start]+source[start:].replace(' steps:',' '+forbidden+'\n steps:',1)
with self.subTest(job=job,forbidden=forbidden),self.assertRaises(AssertionError):
self.assert_unprivileged_build(mutated,job)
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'):
block=source.split(' '+job+':\n',1)[1].split(' steps:',1)[0]
self.assertIn('if: ${{ false }}',block)
for job in ('linux', 'macos'):
build=source.split(' '+job+':\n',1)[1].split('\n ',1)[0]
self.assertNotIn('secrets.',build); self.assertNotIn('environment:',build)
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'):
self.assertNotIn(forbidden,source)
self.assertIn('uses: $/.github/workflows/nightly-signing-unix.yml', source)
+17 -9
View File
@@ -135,6 +135,16 @@ class WindowsCandidateTests(unittest.TestCase):
with self.assertRaises(FileExistsError):
w.stage_local(self.registry, "photocraft", self.prepared, self.cargo, self.context, self.source_receipt, self.artifacts, staged)
def test_noncanonical_manifest_is_refused_before_identity_derivation(self):
alternate=self.root/'Alternate.toml'
alternate.write_text('[workspace.package]\nversion = "2.3.4"\n')
prepared=n.prepare(self.registry,'photocraft',alternate,self.prepared['published_at'],self.context)
output=self.root/'must-not-exist'
with patch.object(w,'validate_prepared',side_effect=AssertionError('must reject before identity derivation')) as validate:
with self.assertRaisesRegex(n.InvalidNightly,'E3 receipt binds only Cargo.toml'):
w.stage_local(self.registry,'photocraft',prepared,alternate,self.context,self.source_receipt,self.artifacts,output)
validate.assert_not_called(); self.assertFalse(output.exists())
def test_missing_nightly_zip_never_uses_a_stable_dry_run_zip(self):
(self.artifacts / self.asset).unlink()
(self.artifacts / "photocraft-1.2.3-windows-x64-portable.zip").write_bytes(b"stable")
@@ -164,17 +174,13 @@ class WindowsCandidateTests(unittest.TestCase):
class WorkflowSourceTests(unittest.TestCase):
# Safety-contract wiring checks requested for this cross-workflow source-only slice.
# These do not substitute for actionlint, hosted execution or Windows checks.
def test_release_postimage_is_byte_identical_and_windows_setup_is_bounded_extraction(self):
release = (ROOT / ".github/workflows/release.yml").read_bytes()
self.assertEqual(hashlib.sha256(release).hexdigest(), "83a8ddd749d3637ac64a3cc46c69f4be4ce1391c343ea28c0acc7b95d1fa58c5")
def test_windows_setup_is_bounded_extraction(self):
source = (ROOT / ".github/workflows/nightly-windows.yml").read_text()
for action in ("actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1",
"step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f"):
self.assertIn(action, source)
self.assertIn(action, release.decode())
for action in ("checkout-craft-fonts","checkout-craft-i18n","rust-channel"):
self.assertIn("actions/"+action+"@f5141455aac7b2eb4708aa259d8ffcdf10fde939",source)
self.assertIn("actions/"+action+"@main",release.decode()) # stable workflow is not rewritten
self.assertIn("cargo metadata --locked", source)
self.assertIn("no Windows nightly adapter", (ROOT / "scripts/nightly_windows.py").read_text())
build = source.split(' build:\n', 1)[1].split('\n # Fresh runner:', 1)[0]
@@ -205,10 +211,12 @@ class WorkflowSourceTests(unittest.TestCase):
source = (ROOT / ".github/workflows/nightly.yml").read_text()
diagnostic = (ROOT / ".github/workflows/nightly-diagnostics.yml").read_text()
self.assertNotIn('release.yml',source)
self.assertIn('uses: $/.github/workflows/release.yml',diagnostic)
self.assertIn('dry-run: true',diagnostic); self.assertIn('publish: false',diagnostic)
self.assertIn('has-freebsd: ${{ inputs.has-freebsd }}',diagnostic)
self.assertIn('contributors-artifact: ${{ inputs.contributors-artifact }}',diagnostic)
self.assertNotIn('uses: $/.github/workflows/release.yml',diagnostic)
self.assertNotIn(': write',diagnostic)
self.assertIn('contents: read',diagnostic)
self.assertIn('scripts/nightly_diagnostic.py',diagnostic)
self.assertNotIn('nightly_policy.py',diagnostic)
self.assertNotIn('GH_TOKEN',diagnostic)
windows=source.split(' build-windows:',1)[1].split(' build-linux:',1)[0]
self.assertIn("if: needs.identity.outputs.ready == 'true'",windows)
self.assertIn('uses: $/.github/workflows/nightly-windows.yml',windows)