packaging(linux): support co-installable nightly packages (#5225)

Linux nightly packaging by @dylanmtaylor, with the per-app Nightly flavor commits stacked on his branch.

The red 'SonarCloud' code-scanning check is a stale alert (S5443 /tmp in packaging/linux/test_install.py) on a line fixed in 6c3eafdb; SonarCloud's own quality gate passes on this head, and the alert should close once main is re-analysed.

Co-authored-by: Dylan M. Taylor <dylan@dylanmtaylor.com>
This commit is contained in:
Dylan M. Taylor
2026-11-25 05:50:13 -05:00
committed by GitHub
parent 740adb32cc
commit 2d1d1b6920
85 changed files with 6991 additions and 85 deletions
+6
View File
@@ -0,0 +1,6 @@
# actionlint 1.7.12 predates GitHub's queue key. Only this exact false positive is suppressed;
# Packaging lint's independent source-contract job enforces the values.
paths:
.github/workflows/nightly-sign.yml:
ignore:
- '^unexpected key "queue" for "concurrency" section\. expected one of "cancel-in-progress", "group"$'
+16
View File
@@ -0,0 +1,16 @@
-----BEGIN PGP PUBLIC KEY BLOCK-----
mDMEaulK1xYJKwYBBAHaRw8BAQdAqHJeDCjY6Hx5FTn/hW+aqu6V394ubLk0Zj3C
bftDwFm0IkFydENyYWZ0IExpbnV4IFJlbGVhc2UgU2lnbmluZyBLZXmIkwQTFgoA
OxYhBCt2dBtBSq1s0z5jEhOgBcC518PtBQJq6UrXAhsBBQsJCAcCAiICBhUKCQgL
AgQWAgMBAh4HAheAAAoJEBOgBcC518PtGeUA/RjvULBTLlccc+2wtJkfjSnCV+cf
PUMEGmW7XkZWkk51AP9w2A/WLv+79nREWEpZzI8LGK5EjrNazP+sY0l7j5rFCLgz
BGrpStcWCSsGAQQB2kcPAQEHQPl7XkQ1gWsvSPf/T9b4m/UHcjJjBpSOtpYlWR56
er5RiO8EGBYKACAWIQQrdnQbQUqtbNM+YxIToAXAudfD7QUCaulK1wIbAgCBCRAT
oAXAudfD7XYgBBkWCgAdFiEEVo3B9o+Prsx5fzx7AG2va7DvM04FAmrpStcACgkQ
AG2va7DvM07taQEA4d2VFkKRIP0g9TrE86KpnuXPap+LKqe0tfIxpdf9YxIA/0Wo
9H/iG8nH++nxC087p3HE0S+0UovxqkhXJLSr8B4JDOoA/iLRpqTdYmk6fVXMyPJo
SkOVuwZIGS6VgBdSQP0e2P2YAP41L5OoSvwdQIG3/uNrM+ieqpYeM597/hCLFs5A
ga/qCA==
=3wGQ
-----END PGP PUBLIC KEY BLOCK-----
+103
View File
@@ -0,0 +1,103 @@
{
"schema": "craft-nightly-release-policy/v3",
"repository": "storytold/filmcraft",
"repository_id": 1398091865,
"producer_workflow_id": null,
"producer_workflow_path": ".github/workflows/nightly.yml",
"producer_tooling_revision": "605d58766e8f536564da8fc81d3676ac86816dea",
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@605d58766e8f536564da8fc81d3676ac86816dea",
"signer_workflow_path": ".github/workflows/nightly-sign.yml",
"signer_tooling_revision": "605d58766e8f536564da8fc81d3676ac86816dea",
"release_branch": "release",
"manual_actors": [
"bflatastic",
"dylanmtaylor",
"echelon",
"FredApps",
"skylartaylor"
],
"max_age_seconds": 86400,
"candidate_policy": {
"schema": "craft-nightly-candidate-policy/v3",
"epoch": "filmcraft-nightly-20261124-sonar-clean",
"repository": "storytold/filmcraft",
"branch": "main",
"required_workflows": [
{
"workflow_id": 380135784,
"workflow_path": ".github/workflows/ci.yml",
"jobs": [
{
"name": "gate / gate (ubuntu-24.04)",
"app_id": 15368,
"applicability": "required"
}
]
}
],
"sonar": {
"organization": "storytold",
"project": "storytold_filmcraft",
"app_id": 12526,
"check_name": "SonarCloud Code Analysis",
"details_url": "https://sonarcloud.io/dashboard?id=storytold_filmcraft&branch=main",
"issue_types": [],
"accepted_conditions": [],
"required_conditions": [
{
"metric": "new_reliability_rating",
"comparator": "GT",
"error_threshold": "1"
},
{
"metric": "new_security_rating",
"comparator": "GT",
"error_threshold": "1"
},
{
"metric": "new_maintainability_rating",
"comparator": "GT",
"error_threshold": "1"
},
{
"metric": "new_coverage",
"comparator": "LT",
"error_threshold": "80"
},
{
"metric": "new_duplicated_lines_density",
"comparator": "GT",
"error_threshold": "3"
},
{
"metric": "new_security_hotspots_reviewed",
"comparator": "LT",
"error_threshold": "100"
}
],
"debt": []
}
},
"max_artifact_bytes": 2147483648,
"automatic_signer_actors": [],
"platforms": {
"windows-x86_64": {
"unsigned_artifact_name": "nightly-unsigned-windows-x86_64",
"trust": {
"publisher_subject": "CN=Learning Machines Inc, O=Learning Machines Inc, L=Atlanta, S=Georgia, C=US"
}
},
"linux-x86_64": {
"unsigned_artifact_name": "nightly-unsigned-linux-x86_64",
"trust": {
"fingerprint": "2B76741B414AAD6CD33E631213A005C0B9D7C3ED"
}
},
"macos-aarch64": {
"unsigned_artifact_name": "nightly-unsigned-macos-aarch64",
"trust": {
"apple_team_id": "DJ6XS33FX8"
}
}
}
}
+222
View File
@@ -0,0 +1,222 @@
name: Nightly build check
# Builds the unsigned FilmCraft Nightly for all three platforms on hosted runners and checks the
# archive exactly as the Launcher unpacks it (packaging/*/nightly.sh, then the version query in
# the Launcher's form). No secrets and no environment: the real Nightly is signed by the shared
# release-ref signer (craft-common-actions), which calls the app's own signing scripts.
#
# macOS minutes are metered: that leg runs only for a pull request with the `full-ci` label or on
# dispatch, one app at a time, on the standard runner (never an xlarge).
on:
pull_request:
types: [opened, synchronize, reopened, labeled]
workflow_dispatch:
permissions:
contents: read
concurrency:
group: nightly-build-${{ github.event_name == 'pull_request' && contains(github.event.pull_request.labels.*.name, 'full-ci') && (github.event.action != 'labeled' || github.event.label.name == 'full-ci') && github.ref || github.run_id }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
windows:
name: Nightly GUI ZIP (x86_64, unsigned)
if: >-
github.event_name == 'workflow_dispatch' ||
(contains(github.event.pull_request.labels.*.name, 'full-ci') &&
(github.event.action != 'labeled' || github.event.label.name == 'full-ci'))
runs-on: windows-latest
timeout-minutes: 90
env:
CARGO_TERM_COLOR: always
CARGO_INCREMENTAL: 0
steps:
- name: Harden runner
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
with:
egress-policy: audit
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Check out craft-fonts
uses: storytold/craft-common-actions/actions/checkout-craft-fonts@f5141455aac7b2eb4708aa259d8ffcdf10fde939
with:
ref: b076417b5880bd4154bd22f00695b1d28c6bea83
- uses: storytold/craft-common-actions/actions/checkout-craft-i18n@f5141455aac7b2eb4708aa259d8ffcdf10fde939
- id: rust
uses: storytold/craft-common-actions/actions/rust-channel@f5141455aac7b2eb4708aa259d8ffcdf10fde939
with:
targets: x86_64-pc-windows-msvc
- uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0
with:
toolchain: ${{ steps.rust.outputs.toolchain }}
targets: ${{ steps.rust.outputs.targets }}
components: ${{ steps.rust.outputs.components }}
- name: Prepare a Nightly identity for this commit
shell: pwsh
run: |
# The version lives in [workspace.package] version (no python3 on the Windows image).
$inPkg = $false
$base = $null
foreach ($line in Get-Content -LiteralPath 'Cargo.toml') {
if ($line -match '^\s*\[') { $inPkg = ($line.Trim() -eq '[workspace.package]'); continue }
if ($inPkg -and $line -match '^\s*version\s*=\s*"([^"]+)"') { $base = ($Matches[1] -split '-')[0]; break }
}
if (-not $base) { throw 'could not read [workspace.package] version from Cargo.toml' }
$sha = (git rev-parse HEAD).Trim()
$date = (Get-Date).ToUniversalTime().ToString('yyyy-MM-dd')
@(
"FILMCRAFT_BUILD_SHA=$sha"
"FILMCRAFT_BUILD_DATE=$date"
"FILMCRAFT_VERSION=${base}-nightly.$($date.Replace('-', '')).$env:GITHUB_RUN_NUMBER.$env:GITHUB_RUN_ATTEMPT.g$($sha.Substring(0, 12))"
) | Out-File -FilePath $env:GITHUB_ENV -Append -Encoding utf8
- name: Build the unsigned Nightly ZIP
shell: pwsh
env:
CARGO_TARGET_DIR: ${{ runner.temp }}/nightly-targets
DIST: ${{ runner.temp }}/nightly-dist
CRAFT_FONTS_DIR: ${{ github.workspace }}/craft-fonts
CRAFT_FONTS_REQUIRED: "1"
run: ./packaging/windows/package.ps1 -Arch x64 -Nightly -BuildOnly
- name: Synthetic Windows packaging contracts
shell: pwsh
run: |
$fixtures = Join-Path $env:RUNNER_TEMP 'nightly-fixtures'
New-Item -ItemType Directory -Force -Path $fixtures | Out-Null
./packaging/windows/nightly-package-tests.ps1 -FixtureRoot $fixtures
./packaging/windows/nightly-signing-tests.ps1 -FixtureRoot $fixtures
- name: Keep the unsigned intermediate
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: filmcraft-nightly-windows-x86_64-unsigned
path: ${{ runner.temp }}/nightly-dist/filmcraft-${{ env.FILMCRAFT_VERSION }}-windows-x86_64-nightly.unsigned.zip
if-no-files-found: error
retention-days: 7
compression-level: 0
linux:
name: Nightly tar (x86_64, unsigned)
if: >-
github.event_name == 'workflow_dispatch' ||
(contains(github.event.pull_request.labels.*.name, 'full-ci') &&
(github.event.action != 'labeled' || github.event.label.name == 'full-ci'))
runs-on: ubuntu-latest
timeout-minutes: 90
env:
CARGO_TERM_COLOR: always
CARGO_INCREMENTAL: 0
steps:
- name: Harden runner
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
with:
egress-policy: audit
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Check out craft-fonts
uses: storytold/craft-common-actions/actions/checkout-craft-fonts@f5141455aac7b2eb4708aa259d8ffcdf10fde939
with:
ref: b076417b5880bd4154bd22f00695b1d28c6bea83
- uses: storytold/craft-common-actions/actions/checkout-craft-i18n@f5141455aac7b2eb4708aa259d8ffcdf10fde939
- id: rust
uses: storytold/craft-common-actions/actions/rust-channel@f5141455aac7b2eb4708aa259d8ffcdf10fde939
- uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0
with:
toolchain: ${{ steps.rust.outputs.toolchain }}
components: ${{ steps.rust.outputs.components }}
- name: Install the Linux build dependencies
run: sudo apt-get update && sudo apt-get install --yes --no-install-recommends libasound2-dev libxkbcommon-dev libwayland-dev
- name: Prepare a Nightly identity for this commit
run: |
set -euo pipefail
base="$(python3 -c 'import tomllib; print(tomllib.load(open("Cargo.toml", "rb"))["workspace"]["package"]["version"].split("-")[0])')"
sha="$(git rev-parse HEAD)"
date="$(date -u +%Y-%m-%d)"
{
echo "FILMCRAFT_BUILD_SHA=$sha"
echo "FILMCRAFT_BUILD_DATE=$date"
echo "FILMCRAFT_VERSION=$base-nightly.${date//-/}.$GITHUB_RUN_NUMBER.$GITHUB_RUN_ATTEMPT.g${sha:0:12}"
} >>"$GITHUB_ENV"
- name: Build the unsigned Nightly tar
env:
FILMCRAFT_BUILD_CHANNEL: nightly-v1
CARGO_TARGET_DIR: ${{ runner.temp }}/nightly-targets
DIST: ${{ runner.temp }}/nightly-dist
CRAFT_FONTS_DIR: ${{ github.workspace }}/craft-fonts
CRAFT_FONTS_REQUIRED: "1"
run: bash packaging/linux/nightly.sh --arch x86_64
- name: Check the archive and the version query
run: bash packaging/linux/nightly-check.sh --input "$RUNNER_TEMP/nightly-dist/filmcraft-$FILMCRAFT_VERSION-linux-x86_64-nightly.tar.gz"
- name: Keep the unsigned archive
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: filmcraft-nightly-linux-x86_64-unsigned
path: ${{ runner.temp }}/nightly-dist/filmcraft-${{ env.FILMCRAFT_VERSION }}-linux-x86_64-nightly.tar.gz
if-no-files-found: error
retention-days: 7
compression-level: 0
macos:
name: Nightly .app (aarch64, unsigned)
if: >-
github.event_name == 'workflow_dispatch' ||
(contains(github.event.pull_request.labels.*.name, 'full-ci') &&
(github.event.action != 'labeled' || github.event.label.name == 'full-ci'))
runs-on: macos-15
timeout-minutes: 90
env:
CARGO_TERM_COLOR: always
CARGO_INCREMENTAL: 0
RUST_BACKTRACE: 1
steps:
- name: Harden runner
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
with:
egress-policy: audit
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Check out craft-fonts
uses: storytold/craft-common-actions/actions/checkout-craft-fonts@f5141455aac7b2eb4708aa259d8ffcdf10fde939
with:
ref: b076417b5880bd4154bd22f00695b1d28c6bea83
- uses: storytold/craft-common-actions/actions/checkout-craft-i18n@f5141455aac7b2eb4708aa259d8ffcdf10fde939
- id: rust
uses: storytold/craft-common-actions/actions/rust-channel@f5141455aac7b2eb4708aa259d8ffcdf10fde939
with:
targets: aarch64-apple-darwin
- uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0
with:
toolchain: ${{ steps.rust.outputs.toolchain }}
targets: ${{ steps.rust.outputs.targets }}
components: ${{ steps.rust.outputs.components }}
- name: Prepare a Nightly identity for this commit
run: |
set -euo pipefail
base="$(python3 -c 'import tomllib; print(tomllib.load(open("Cargo.toml", "rb"))["workspace"]["package"]["version"].split("-")[0])')"
sha="$(git rev-parse HEAD)"
date="$(date -u +%Y-%m-%d)"
{
echo "FILMCRAFT_BUILD_SHA=$sha"
echo "FILMCRAFT_BUILD_DATE=$date"
echo "FILMCRAFT_VERSION=$base-nightly.${date//-/}.$GITHUB_RUN_NUMBER.$GITHUB_RUN_ATTEMPT.g${sha:0:12}"
} >>"$GITHUB_ENV"
- name: Build the unsigned Nightly bundle
env:
FILMCRAFT_BUILD_CHANNEL: nightly-v1
CARGO_TARGET_DIR: ${{ runner.temp }}/nightly-targets
DIST: ${{ runner.temp }}/nightly-dist
CRAFT_FONTS_DIR: ${{ github.workspace }}/craft-fonts
CRAFT_FONTS_REQUIRED: "1"
run: bash packaging/macos/nightly.sh --arch aarch64
- name: Check the archive and the bundle's version
run: bash packaging/macos/nightly-verify.sh --expect unsigned --input "$RUNNER_TEMP/nightly-dist/filmcraft-$FILMCRAFT_VERSION-macos-aarch64-nightly.zip"
- name: Keep the unsigned archive
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: filmcraft-nightly-macos-aarch64-unsigned
path: ${{ runner.temp }}/nightly-dist/filmcraft-${{ env.FILMCRAFT_VERSION }}-macos-aarch64-nightly.zip
if-no-files-found: error
retention-days: 7
compression-level: 0
+72
View File
@@ -0,0 +1,72 @@
name: Dispatch release-ref nightly
# Transport only, never authorization. No checkout, payload parsing or release environment.
on:
workflow_run:
workflows: [FilmCraft unsigned nightly]
types: [completed]
branches: [main]
permissions: {}
jobs:
dispatch:
# SOURCE PREPARATION: literal off until immutable shared tooling and policy qualification.
if: >-
false && github.repository == 'storytold/filmcraft' &&
github.event_name == 'workflow_run'
runs-on: ubuntu-latest
timeout-minutes: 5
permissions:
actions: write
steps:
- name: Dispatch only the exact completed producer run and attempt
shell: python
env:
GH_TOKEN: ${{ github.token }}
run: |
import json
import os
import urllib.request
def require(value, message):
if not value:
raise RuntimeError(message)
# These filters reduce noise; the protected release validator repeats admission
# against authenticated API metadata and required attestation/quality evidence.
require(os.environ.get('GITHUB_REPOSITORY') == 'storytold/filmcraft', 'wrong repository')
require(os.environ.get('GITHUB_EVENT_NAME') == 'workflow_run', 'wrong event')
with open(os.environ['GITHUB_EVENT_PATH'], encoding='utf-8') as stream:
event = json.load(stream)
require(event.get('action') == 'completed', 'producer is not complete')
require(event.get('repository', {}).get('full_name') == 'storytold/filmcraft', 'wrong event repository')
producer = event.get('workflow_run', {})
require(producer.get('head_repository', {}).get('full_name') == 'storytold/filmcraft', 'foreign producer')
require(producer.get('path') == '.github/workflows/nightly.yml', 'wrong producer path')
require(producer.get('head_branch') == 'main', 'wrong producer branch')
require(producer.get('status') == 'completed' and producer.get('conclusion') == 'success', 'producer did not succeed')
# First scheduled attempt only; reviewed manual/re-run authority belongs to release policy.
require(producer.get('event') == 'schedule', 'not an automatic scheduled producer')
run_id, attempt = producer.get('id'), producer.get('run_attempt')
require(type(run_id) is int and run_id > 0, 'invalid producer run id')
require(type(attempt) is int and attempt == 1, 'invalid automatic producer attempt')
body = json.dumps({'ref': 'release', 'inputs': {
'producer_run_id': str(run_id), 'producer_run_attempt': str(attempt)
}}).encode('utf-8')
request = urllib.request.Request(
'https://api.github.com/repos/storytold/filmcraft/actions/workflows/nightly-sign.yml/dispatches',
data=body, method='POST', headers={
'Authorization': 'Bearer ' + os.environ['GH_TOKEN'],
'Accept': 'application/vnd.github+json',
'Content-Type': 'application/json',
'X-GitHub-Api-Version': '2022-11-28',
'User-Agent': 'filmcraft-nightly-dispatch'
})
class NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
raise RuntimeError('dispatch redirects are forbidden')
# One bounded request, no retry: duplicate transport is not publication authority.
with urllib.request.build_opener(NoRedirect()).open(request, timeout=20) as response:
require(response.status == 204, 'dispatch was not accepted')
print('Dispatched producer run/attempt to the release-ref validator; not a signing result.')
+42
View File
@@ -0,0 +1,42 @@
name: FilmCraft release-ref nightly signer
# Enabled for supervised manual dispatch on release. Main/release contents must match.
# A reusable callee does not change context; this must be a real top-level release dispatch.
on:
workflow_dispatch:
inputs:
producer_run_id:
description: Exact untrusted producer Actions run ID
required: true
type: string
producer_run_attempt:
description: Exact untrusted producer Actions run attempt
required: true
type: string
permissions: {}
concurrency:
group: filmcraft-nightly-release
cancel-in-progress: false
jobs:
release:
# Actual context guards: official repository, manual dispatch, real release branch.
if: >-
github.repository == 'storytold/filmcraft' &&
github.event_name == 'workflow_dispatch' &&
github.ref == 'refs/heads/release' && github.ref_type == 'branch'
permissions:
contents: write
actions: read
checks: read
attestations: write
id-token: write
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@605d58766e8f536564da8fc81d3676ac86816dea
with:
tooling-revision: 605d58766e8f536564da8fc81d3676ac86816dea
producer_run_id: ${{ inputs.producer_run_id }}
producer_run_attempt: ${{ inputs.producer_run_attempt }}
# No secrets: inherit or raw platform values in this caller. Only the isolated native
# callee job may bind the existing release environment and export keys in its signing step.
+34
View File
@@ -0,0 +1,34 @@
name: FilmCraft unsigned nightly
# Enabled for supervised manual runs by the reviewed manual actors only; no schedule yet.
# A later explicit opt-in may add a cadence (and a scheduled completion dispatcher with it).
on:
workflow_dispatch:
permissions:
contents: read
jobs:
unsigned:
# Actual context guards only; no inherited/platform secrets.
if: >-
github.repository == 'storytold/filmcraft' &&
github.ref == 'refs/heads/main' && github.ref_type == 'branch' &&
(github.event_name == 'schedule' || github.event_name == 'workflow_dispatch')
# Maximum for the reusable workflow. Its compiler narrows to contents/actions read;
# no OIDC, attestation write, release environment or platform secrets in compilation.
permissions:
contents: read
actions: read
attestations: write
id-token: write
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@605d58766e8f536564da8fc81d3676ac86816dea
with:
tooling-revision: 605d58766e8f536564da8fc81d3676ac86816dea
app-name: filmcraft
manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]'
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
# One producer run builds every listed platform for one all-or-nothing release. The pin is the
# craft-common-actions main commit that merged #339 (bounded lineage compares), on top of the
# Linux/macOS signer (#342).
platforms: '["windows-x86_64","linux-x86_64","macos-aarch64"]'
+24 -2
View File
@@ -5,9 +5,9 @@ name: Packaging lint
on:
push:
branches: [main, release]
paths: [".github/workflows/**", "packaging/**", "assets/app-icon/**"]
paths: [".github/workflows/**", ".github/actionlint.yaml", "packaging/**", "assets/app-icon/**", "docs/nightly-signing-policy.example.json", ".github/nightly-signing-policy.json", ".github/nightly-linux-signing-key.asc", "sonar-project.properties"]
pull_request:
paths: [".github/workflows/**", "packaging/**", "assets/app-icon/**"]
paths: [".github/workflows/**", ".github/actionlint.yaml", "packaging/**", "assets/app-icon/**", "docs/nightly-signing-policy.example.json", ".github/nightly-signing-policy.json", ".github/nightly-linux-signing-key.asc", "sonar-project.properties"]
workflow_dispatch:
permissions:
@@ -49,3 +49,25 @@ jobs:
- name: Build and check non-executable installer fixtures
shell: pwsh
run: ./packaging/windows/test-install-policy.ps1 -OutputDirectory (Join-Path $env:RUNNER_TEMP 'craft-install-policy-tests')
nightly-source-contract:
name: Nightly source contracts (no build or signing)
runs-on: ubuntu-latest
timeout-minutes: 5
permissions:
contents: read
steps:
- name: Harden runner
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
with:
egress-policy: audit
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Enforce nightly serialization and synthetic packaging contracts
run: python3 packaging/nightly-tests.py
- name: Check the Linux Nightly launchers (no build, argv recorders only)
run: |
bash packaging/linux/nightly-launch-test.sh
bash packaging/linux/apprun-test.sh
bash packaging/linux/nightly-arch-tar-test.sh
+5
View File
@@ -7,3 +7,8 @@ plan/
.DS_Store
.claude/worktrees/
__pycache__/
# Checked out inside the workspace by the shared nightly workflows (craft-common-actions).
/.nightly-tools
/.nightly-input
/craft-i18n
/craft-fonts
+5
View File
@@ -48,6 +48,11 @@ iconography, images or other Adobe assets; open licences only; every asset attri
| `assets/app-icon/filmcraft-macos-512.png` | Brandon Thomas (FilmCraft owner) | Original work: FilmCraft app icon (owl with ear tufts), drawn by the owner in ArtCraft and vectorised; macOS runtime Dock icon (512 px) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) |
| `assets/app-icon/filmcraft.icns` | Brandon Thomas (FilmCraft owner) | Original work: FilmCraft app icon (owl with ear tufts), drawn by the owner in ArtCraft and vectorised; macOS .icns | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) |
| `assets/app-icon/filmcraft.ico` | Brandon Thomas (FilmCraft owner) | Original work: FilmCraft app icon (owl with ear tufts), drawn by the owner in ArtCraft and vectorised; Windows .ico (16-256 px) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) |
| `assets/app-icon/filmcraft-nightly.png` | Brandon Thomas (FilmCraft owner) | Derived from the FilmCraft app icon: only the background contribution is recoloured for the Nightly channel (deep field `#3c2a63`); artwork, alpha and padding unchanged; native 256 px | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) |
| `assets/app-icon/filmcraft-nightly-1024.png` | Brandon Thomas (FilmCraft owner) | Nightly recolour of `filmcraft-1024.png`; 1024 px master on the Apple icon grid | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) |
| `assets/app-icon/filmcraft-nightly.ico` | Brandon Thomas (FilmCraft owner) | Nightly recolour of the FilmCraft app icon, Windows .ico (16-256 px); embedded in `filmcraft.exe` for the nightly channel only | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) |
| `assets/app-icon/filmcraft-nightly.icns` | Brandon Thomas (FilmCraft owner) | Nightly recolour of the FilmCraft app icon, macOS .icns (16-1024 px PNG slots) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) |
| `assets/app-icon/filmcraft-nightly-macos-512.png` | Brandon Thomas (FilmCraft owner) | Nightly recolour of `filmcraft-macos-512.png`; the runtime Dock icon of FilmCraft Nightly | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) |
| `assets/app-icon/hicolor/16x16/apps/ai.storyteller.filmcraft.png` | Brandon Thomas (FilmCraft owner) | Original work: FilmCraft app icon (owl with ear tufts), drawn by the owner in ArtCraft and vectorised; Linux hicolor theme 16 px | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) |
| `assets/app-icon/hicolor/24x24/apps/ai.storyteller.filmcraft.png` | Brandon Thomas (FilmCraft owner) | Original work: FilmCraft app icon (owl with ear tufts), drawn by the owner in ArtCraft and vectorised; Linux hicolor theme 24 px | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) |
| `assets/app-icon/hicolor/32x32/apps/ai.storyteller.filmcraft.png` | Brandon Thomas (FilmCraft owner) | Original work: FilmCraft app icon (owl with ear tufts), drawn by the owner in ArtCraft and vectorised; Linux hicolor theme 32 px | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) |
Generated
+3
View File
@@ -2856,6 +2856,7 @@ dependencies = [
"egui",
"filmcraft-engine",
"filmcraft-export",
"filmcraft-format",
"filmcraft-gpu",
"filmcraft-platform",
"filmcraft-project",
@@ -2873,9 +2874,11 @@ dependencies = [
"rfd",
"serde_json",
"sys-locale",
"thiserror 2.0.21",
"winit",
"winreg",
"winresource",
"winsafe",
"zbus",
]
+27 -1
View File
@@ -315,9 +315,20 @@ async fn main() {
}
}
/// The desktop app's private Launcher protocol. The CLI is never started with it, so refuse it
/// before parsing (both token and `=` forms) instead of reporting an unknown option.
fn desktop_launch_profile_argument(arg: &str) -> bool {
["--launch-profile", "--profile-root"].iter().any(|flag| arg == *flag || arg.strip_prefix(flag).is_some_and(|rest| rest.starts_with('=')))
}
async fn cli() {
let raw: Vec<String> = std::env::args_os().skip(1).map(|a| a.to_string_lossy().into_owned()).collect();
if let Some(found) = raw.iter().find(|arg| desktop_launch_profile_argument(arg)) {
eprintln!("filmcraft-cli: {found} belongs to the FilmCraft desktop app's Launcher profile; the CLI has no launch profile");
std::process::exit(2);
}
// `std::env::args` panics on an argument that is not Unicode (a Linux file name in Latin-1)
let a = Args::parse(std::env::args_os().skip(1).map(|a| a.to_string_lossy().into_owned()));
let a = Args::parse(raw);
// `--help` anywhere (`filmcraft-cli --help`, `filmcraft-cli export --help`) prints the reference:
// the parser takes it as a flag option, so it never reaches the subcommand match.
if a.flag("--help") {
@@ -819,3 +830,18 @@ mod format_tests {
assert_eq!(super::format_for("noext"), None);
}
}
#[cfg(test)]
mod launch_profile_tests {
use super::desktop_launch_profile_argument;
#[test]
fn the_desktop_launcher_protocol_is_refused_in_both_forms() {
for arg in ["--launch-profile", "--launch-profile=nightly-v1", "--profile-root", "--profile-root=/tmp/nightly"] {
assert!(desktop_launch_profile_argument(arg), "{arg}");
}
for arg in ["--version", "-V", "--data-dir", "--profile", "--launch", "profile-root"] {
assert!(!desktop_launch_profile_argument(arg), "{arg}");
}
}
}
+7
View File
@@ -21,12 +21,16 @@ neural-voices = ["filmcraft-engine/neural-voices"]
craft-control-protocol = { workspace = true }
filmcraft-engine = { workspace = true }
filmcraft-export = { workspace = true }
# The durable no-follow session record (nightly_session.rs).
filmcraft-format = { workspace = true }
filmcraft-project = { workspace = true }
filmcraft-render = { workspace = true }
filmcraft-time = { workspace = true }
filmcraft-gpu = { workspace = true }
filmcraft-ui-egui = { workspace = true }
filmcraft-platform = { workspace = true }
# process_identity.rs's identity error; the workspace's own thiserror.
thiserror = { workspace = true }
egui = { workspace = true }
eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit", "clipboard", "wayland", "x11"] }
serde_json = { workspace = true }
@@ -72,3 +76,6 @@ craft-update = { workspace = true }
# graphics/probe.rs: the display drivers' names and versions, so a driver update tests the
# graphics start again (MIT).
winreg = "0.55"
# process_identity.rs: the explicit AppUserModelID a nightly install needs for its own taskbar
# identity, separate from stable (MIT).
winsafe = { version = "0.0.29", features = ["user", "shell"] }
+70 -10
View File
@@ -1,30 +1,85 @@
//! Windows only: embed the app icon and version info (VERSIONINFO) into `filmcraft.exe`, so it
//! shows in Explorer, the taskbar, the Start menu and Alt-Tab.
//! shows in Explorer, the taskbar, the Start menu and Alt-Tab. Also selects the build channel.
//!
//! On every other target this does nothing (`winresource` is only a build-dependency on Windows
//! hosts). A missing resource compiler is a warning, unless `FILMCRAFT_REQUIRE_WINRES=1` (for
//! release builds) turns it into an error.
//! On every other target the resource step does nothing (`winresource` is only a build-dependency
//! on Windows hosts). A missing resource compiler is a warning, unless `FILMCRAFT_REQUIRE_WINRES=1`
//! (for release and nightly builds) turns it into an error.
// `windows_icon_path` is only called by the `#[cfg(windows)]` resource step below, so a Linux or
// macOS `cargo clippy -- -D warnings` would fail on it without this.
#[cfg_attr(not(windows), allow(dead_code))]
#[path = "src/build_channel.rs"]
mod build_channel;
fn main() {
println!("cargo:rerun-if-changed=build.rs");
println!("cargo:rerun-if-changed=../../assets/app-icon/filmcraft.ico");
println!("cargo:rerun-if-changed=../../assets/app-icon/filmcraft-nightly.ico");
println!("cargo:rerun-if-env-changed=FILMCRAFT_REQUIRE_WINRES");
println!("cargo:rerun-if-env-changed=FILMCRAFT_BUILD_CHANNEL");
println!("cargo:rerun-if-env-changed=FILMCRAFT_VERSION");
println!("cargo:rustc-check-cfg=cfg(filmcraft_nightly_v1)");
let nightly = match std::env::var("FILMCRAFT_BUILD_CHANNEL").as_deref() {
Ok("nightly-v1") => {
println!("cargo:rustc-cfg=filmcraft_nightly_v1");
true
}
// An empty value (an unset CI input) means the default stable build.
Ok("stable" | "") | Err(std::env::VarError::NotPresent) => false,
_ => {
eprintln!("unsupported FILMCRAFT_BUILD_CHANNEL (expected stable or nightly-v1)");
std::process::exit(1);
}
};
println!("cargo:rerun-if-env-changed=FILMCRAFT_BUILD_SHA");
println!("cargo:rerun-if-env-changed=FILMCRAFT_BUILD_DATE");
// The version the binary reports: the exact nightly feed identity, or the workspace version.
let built_version = if nightly {
let version = match std::env::var("FILMCRAFT_VERSION") {
Ok(version) if build_channel::is_nightly_version(&version) => version,
_ => {
eprintln!("nightly-v1 requires an explicit FILMCRAFT_VERSION feed identity");
std::process::exit(1);
}
};
// The feed identity names the commit and the original run's date: refuse a build whose
// prepared values do not agree, so a rebuilt or relabelled tree cannot ship as Nightly.
let sha = std::env::var("FILMCRAFT_BUILD_SHA").unwrap_or_default();
let date = std::env::var("FILMCRAFT_BUILD_DATE").unwrap_or_default();
let hex = |s: &str| s.len() == 40 && s.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b));
let digits = |s: &str| s.len() == 10 && s.bytes().all(|b| b.is_ascii_digit() || b == b'-');
let version_date = version.split("-nightly.").nth(1).and_then(|rest| rest.split('.').next()).unwrap_or_default();
if !hex(&sha) || sha.get(..12) != version.rsplit(".g").next() || !digits(&date) || date.replace('-', "") != version_date {
eprintln!("nightly-v1 requires FILMCRAFT_BUILD_SHA and FILMCRAFT_BUILD_DATE matching FILMCRAFT_VERSION");
std::process::exit(1);
}
println!("cargo:rustc-env=FILMCRAFT_BUILT_COMMIT={sha}");
version
} else {
std::env::var("CARGO_PKG_VERSION").unwrap_or_default()
};
println!("cargo:rustc-env=FILMCRAFT_BUILT_VERSION={built_version}");
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("windows") {
return;
}
windows::embed_resources();
windows::embed_resources(nightly, &built_version);
}
#[cfg(windows)]
mod windows {
pub fn embed_resources() {
pub fn embed_resources(nightly: bool, version: &str) {
let mut res = winresource::WindowsResource::new();
res.set_icon("../../assets/app-icon/filmcraft.ico")
.set("ProductName", "FilmCraft")
.set("FileDescription", "FilmCraft video editor")
res.set_icon(super::build_channel::windows_icon_path(nightly))
.set("ProductName", if nightly { "FilmCraft Nightly" } else { "FilmCraft" })
.set("FileDescription", if nightly { "FilmCraft Nightly video editor" } else { "FilmCraft video editor" })
.set("LegalCopyright", "Copyright (c) the FilmCraft contributors. MIT OR Apache-2.0.")
.set("OriginalFilename", "filmcraft.exe")
.set("InternalName", "filmcraft");
if nightly {
// The Launcher verifies the PE ProductVersion against the exact feed identity, not FileVersion.
res.set("ProductVersion", version);
}
if let Err(e) = res.compile() {
if std::env::var_os("FILMCRAFT_REQUIRE_WINRES").is_some() {
panic!("embedding Windows resources failed: {e}");
@@ -37,7 +92,12 @@ mod windows {
/// Cross-compiling for Windows from macOS or Linux: `winresource` is not available on this host.
#[cfg(not(windows))]
mod windows {
pub fn embed_resources() {
pub fn embed_resources(_nightly: bool, _version: &str) {
// The release and nightly builds require the icon and the PE `ProductVersion` the Launcher
// verifies, so a cross-build that cannot embed them fails instead of shipping without.
if std::env::var_os("FILMCRAFT_REQUIRE_WINRES").is_some() {
panic!("FILMCRAFT_REQUIRE_WINRES=1 needs a Windows host: a cross-compiled filmcraft.exe has no icon or ProductVersion");
}
println!("cargo:warning=filmcraft.exe built without icon/version resources (cross-compiled from a non-Windows host)");
}
}
+54
View File
@@ -0,0 +1,54 @@
//! The build-time nightly identity shared by the build script and its pure regression tests.
pub fn is_nightly_version(version: &str) -> bool {
let Some((base, suffix)) = version.split_once("-nightly.") else { return false };
let digits = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit());
let base: Vec<_> = base.split('.').collect();
let parts: Vec<_> = suffix.split('.').collect();
base.len() == 3
&& base.iter().all(|s| digits(s))
&& parts.len() == 4
&& parts[0].len() == 8
&& digits(parts[0])
&& digits(parts[1])
&& digits(parts[2])
&& parts[3].strip_prefix('g').is_some_and(|sha| sha.len() == 12 && sha.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)))
}
pub fn windows_icon_path(nightly: bool) -> &'static str {
if nightly { "../../assets/app-icon/filmcraft-nightly.ico" } else { "../../assets/app-icon/filmcraft.ico" }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn windows_resource_uses_the_flavor_specific_icon_without_changing_stable() {
assert_eq!(windows_icon_path(false), "../../assets/app-icon/filmcraft.ico");
assert_eq!(windows_icon_path(true), "../../assets/app-icon/filmcraft-nightly.ico");
}
#[test]
fn explicit_feed_identity_is_required_for_a_nightly_build() {
assert!(is_nightly_version("0.21.1-nightly.20261124.17.1.gabcdef012345"));
for invalid in [
"",
"0.21.1",
"0.21.1-nightly",
"0.21.1-nightly.20261124",
"0.21.1-nightly.20261124.17.1.gABCDEF012345",
"0.21.1-nightly.20261124.17.1.gabcdef012345\n",
] {
assert!(!is_nightly_version(invalid), "{invalid:?}");
}
}
#[test]
fn version_cannot_inject_a_path_or_an_extra_build_directive() {
for invalid in [
"../0.21.1-nightly.20261124.1.1.gabcdef012345",
"0.21.1-nightly.20261124.1.1.gabcdef012345/other",
"0.21.1-nightly.20261124.1.1.gabcdef012345\ncargo:rustc-cfg=other",
] {
assert!(!is_nightly_version(invalid));
}
}
}
+70
View File
@@ -0,0 +1,70 @@
//! Build-time channel is distinct from a launch selector. A runtime environment cannot promote a stable build.
use crate::launch_profile::Profile;
use std::ffi::OsString;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BuildFlavor {
Stable,
NightlyV1,
}
pub const COMPILED: BuildFlavor = if cfg!(filmcraft_nightly_v1) { BuildFlavor::NightlyV1 } else { BuildFlavor::Stable };
pub fn require_profile(flavor: BuildFlavor, profile: &Profile) -> Result<(), String> {
match (flavor, profile.is_nightly()) {
(BuildFlavor::NightlyV1, false) => Err("Open FilmCraft Nightly from ArtCraft Launcher".into()),
(BuildFlavor::Stable, true) => Err("This is a stable FilmCraft build; nightly-v1 requires the nightly build".into()),
_ => Ok(()),
}
}
pub fn needs_native_error(flavor: BuildFlavor, desktop_session: bool) -> bool {
desktop_session && flavor == BuildFlavor::NightlyV1
}
pub fn version_query(args: &[OsString]) -> bool {
matches!(args, [arg] if arg == "--version" || arg == "-V")
}
pub fn version(flavor: BuildFlavor, stable: &str) -> String {
match flavor {
BuildFlavor::Stable => stable.to_owned(),
BuildFlavor::NightlyV1 => format!("{stable} (nightly-v1)"),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn only_a_nightly_desktop_refusal_requests_a_native_dialog() {
assert!(needs_native_error(BuildFlavor::NightlyV1, true));
assert!(!needs_native_error(BuildFlavor::NightlyV1, false));
assert!(!needs_native_error(BuildFlavor::Stable, true));
assert!(!needs_native_error(BuildFlavor::Stable, false));
}
#[test]
fn nightly_build_without_a_profile_is_refused_before_startup() {
let started = std::cell::Cell::new(false);
let result = require_profile(BuildFlavor::NightlyV1, &Profile::Stable).map(|()| started.set(true));
assert!(result.unwrap_err().contains("ArtCraft Launcher"));
assert!(!started.get());
}
#[test]
fn stable_and_nightly_flavors_accept_only_their_own_profile() {
let nightly = Profile::NightlyV1(std::path::PathBuf::from("already validated root"));
assert!(require_profile(BuildFlavor::Stable, &Profile::Stable).is_ok());
assert!(require_profile(BuildFlavor::Stable, &nightly).is_err());
assert!(require_profile(BuildFlavor::NightlyV1, &nightly).is_ok());
}
#[test]
fn nightly_version_query_is_unambiguous_and_never_reinterprets_file_arguments() {
assert_eq!(version(BuildFlavor::Stable, "0.21.1"), "0.21.1");
assert_eq!(version(BuildFlavor::NightlyV1, "0.21.1"), "0.21.1 (nightly-v1)");
assert!(version_query(&["--version".into()]));
assert!(version_query(&["-V".into()]));
assert!(!version_query(&["--".into(), "--version".into()]));
assert!(!version_query(&[]));
}
}
+8 -3
View File
@@ -22,6 +22,11 @@
//! Every failure is logged and skipped — a missing dev icon must never stop the app
//! ([`AGENTS.md`](/AGENTS.md) rule 13, "never crash").
/// Reverse-DNS app id of the entry installed here: the `.desktop` file name and the hicolor icon
/// name. A window takes its own id from the channel before it exists
/// (`filmcraft_ui_egui::os_window`), so this dev entry is always the stable one's.
const APP_ID: &str = filmcraft_ui_egui::os_window::APP_ID;
/// Install the user-level desktop entry and icons for a source-tree run (Linux).
pub fn ensure_dev_desktop_entry() {
// Packaged and sandboxed runs never write into the user's profile: an AppImage mounts at a
@@ -43,7 +48,7 @@ pub fn ensure_dev_desktop_entry() {
/// Install missing files; `Ok` whether anything was written or an entry already existed.
fn ensure() -> Result<(), DevIconError> {
let file_name = format!("{}.desktop", crate::APP_ID);
let file_name = format!("{}.desktop", APP_ID);
let user_dir = user_data_dir()?;
let exe = std::env::current_exe().map_err(DevIconError::Io)?;
// Not `to_string_lossy`: a substituted U+FFFD would install an `Exec` that can never start
@@ -73,7 +78,7 @@ fn ensure() -> Result<(), DevIconError> {
break; // a dev entry from another checkout: fall through and rewrite it
}
for size in ICON_SIZES {
let rel = std::path::Path::new("hicolor").join(format!("{size}x{size}")).join("apps").join(format!("{}.png", crate::APP_ID));
let rel = std::path::Path::new("hicolor").join(format!("{size}x{size}")).join("apps").join(format!("{}.png", APP_ID));
let dest = user_dir.join("icons").join(&rel);
if !dest.is_file()
&& let Some(parent) = dest.parent()
@@ -90,7 +95,7 @@ fn ensure() -> Result<(), DevIconError> {
}
let applications = user_dir.join("applications");
std::fs::create_dir_all(&applications).map_err(DevIconError::Io)?;
let body = desktop_file_content(crate::APP_ID, "FilmCraft", exe);
let body = desktop_file_content(APP_ID, "FilmCraft", exe);
std::fs::write(applications.join(&file_name), body).map_err(DevIconError::Io)?;
Ok(())
}
+6
View File
@@ -426,6 +426,12 @@ pub fn choose(start: &mut GraphicsStart, forced: bool, explicit_backend: bool, l
choose_with(start, forced, log_file, &exe, &display_drivers(), |exe, mode| {
let mut cmd = Command::new(exe);
cmd.arg(CHILD_ARG).arg(mode.name());
// A Nightly start hands its private profile to the test child: the child refuses to run
// without one (it is the same program with the same protocol), and its graphics record
// must not land in stable's data folder.
if let Some(root) = crate::launch_profile::current().root() {
cmd.args(["--launch-profile", crate::launch_profile::VERSION, "--profile-root"]).arg(root).arg("--");
}
run_test(cmd, TIMEOUT)
})
}
+281
View File
@@ -0,0 +1,281 @@
//! Launcher-owned nightly-v1 bootstrap. Selected before logging, updates, fonts or saved state.
//! Stable launches retain their original arguments and directory policy. No environment mutation.
use std::ffi::OsString;
use std::path::{Component, Path, PathBuf};
use std::sync::OnceLock;
pub const VERSION: &str = "nightly-v1";
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Profile {
Stable,
NightlyV1(PathBuf),
}
impl Profile {
pub fn is_nightly(&self) -> bool {
matches!(self, Self::NightlyV1(_))
}
pub fn root(&self) -> Option<&Path> {
match self {
Self::Stable => None,
Self::NightlyV1(root) => Some(root),
}
}
}
#[derive(Debug, PartialEq, Eq)]
pub struct Launch {
pub profile: Profile,
pub args: Vec<OsString>,
}
static PROFILE: OnceLock<Profile> = OnceLock::new();
pub fn current() -> &'static Profile {
PROFILE.get().unwrap_or(&Profile::Stable)
}
pub fn install(profile: Profile) -> Result<(), String> {
PROFILE.set(profile).map_err(|_| "the launch profile was already selected".into())
}
/// Recognize only the agreed literal selector/root pair before `--`. Everything after it is
/// a file, even when it looks like a profile flag. No filesystem or startup hook runs here.
pub fn parse(args: Vec<OsString>) -> Result<Launch, String> {
let mut selector = None;
let mut root = None;
let mut other = Vec::new();
let mut files = Vec::new();
let mut iter = args.iter();
let mut delimiter = false;
while let Some(arg) = iter.next() {
if arg == "--" {
delimiter = true;
files.extend(iter.cloned());
break;
}
if arg == "--launch-profile" || arg == "--profile-root" {
let slot = if arg == "--launch-profile" { &mut selector } else { &mut root };
if slot.is_some() {
return Err("the profile selector and root must each occur exactly once".into());
}
let value = iter.next().filter(|v| !v.is_empty()).ok_or("the profile selector/root needs a value")?;
if value.to_string_lossy().starts_with("--") {
return Err("the profile selector/root needs a value".into());
}
*slot = Some(value.clone());
} else if arg.to_string_lossy().starts_with("--launch-profile=") || arg.to_string_lossy().starts_with("--profile-root=") {
return Err("the nightly protocol requires separate literal selector/root argument tokens".into());
} else {
other.push(arg.clone());
}
}
match (selector, root) {
(None, None) => Ok(Launch { profile: Profile::Stable, args }),
(Some(version), Some(root)) if version == VERSION => {
if !delimiter || !other.is_empty() {
return Err("nightly-v1 accepts only its selector/root followed by -- and file names".into());
}
let root = PathBuf::from(root);
if !root.is_absolute() || root.components().any(|c| matches!(c, Component::ParentDir)) {
return Err("the nightly profile root must be absolute and contain no parent traversal".into());
}
Ok(Launch { profile: Profile::NightlyV1(root), args: std::iter::once(OsString::from("--")).chain(files).collect() })
}
(Some(_), Some(_)) => Err("unsupported launch profile (expected nightly-v1)".into()),
_ => Err("--launch-profile and --profile-root must be supplied together".into()),
}
}
/// The Launcher's version check: the selector/root pair followed by exactly `--version` (or `-V`),
/// answered like a plain version query. Only [`parse`]'s lexical checks apply; the root is never
/// validated or touched, and `-- --version` stays a file name.
pub fn version_query(args: &[OsString]) -> bool {
let Some((last, pair)) = args.split_last() else { return false };
if last != "--version" && last != "-V" {
return false;
}
let lexical = pair.iter().cloned().chain(std::iter::once(OsString::from("--"))).collect();
matches!(parse(lexical), Ok(Launch { profile: Profile::NightlyV1(_), args }) if args.len() == 1)
}
/// The graphics retry is signalled by its process-local relaunch marker
/// (`FILMCRAFT_GRAPHICS_RELAUNCHED`) and re-executes this program with an internal
/// `--graphics <mode>` before the file delimiter. Ordinary Launcher calls still use the strict
/// selector/root protocol; this is not authentication.
pub fn parse_startup(args: Vec<OsString>, compatibility_retry: bool) -> Result<Launch, String> {
let Some(mode) = compatibility_retry.then(|| internal_graphics(&args)).flatten() else { return parse(args) };
let mut launch = parse(without_graphics(&args))?;
if launch.profile.is_nightly() {
launch.args.splice(0..0, [OsString::from("--graphics"), mode]);
Ok(launch)
} else {
// Stable's argument order and parser remain unchanged.
parse(args)
}
}
/// The `--graphics <mode>` pair the retry inserted before the file delimiter, if it is there once.
fn internal_graphics(args: &[OsString]) -> Option<OsString> {
let delimiter = args.iter().position(|arg| arg == "--").unwrap_or(args.len());
let mut found = None;
let mut iter = args[..delimiter].iter();
while let Some(arg) = iter.next() {
if arg == "--graphics" {
if found.is_some() {
return None;
}
found = Some(iter.next()?.clone());
}
}
found
}
/// `args` without the internal `--graphics <mode>` pair before the file delimiter. Everything
/// after `--` is a file name, even one spelled `--graphics`.
fn without_graphics(args: &[OsString]) -> Vec<OsString> {
let mut out = Vec::with_capacity(args.len());
let mut iter = args.iter();
while let Some(arg) = iter.next() {
if arg == "--" {
out.push(arg.clone());
out.extend(iter.by_ref().cloned());
} else if arg == "--graphics" {
let _ = iter.next();
} else {
out.push(arg.clone());
}
}
out
}
/// Validation finishes before the caller's first startup effect. Stable never calls the nightly
/// root validator, so its old portable/config resolution stays unchanged.
pub fn prepare(mut launch: Launch, validate: impl FnOnce(&Path) -> Result<PathBuf, String>) -> Result<Launch, String> {
if let Profile::NightlyV1(root) = &launch.profile {
launch.profile = Profile::NightlyV1(validate(root)?);
}
Ok(launch)
}
/// Resolve the selected private root before the caller's first startup effect.
pub fn validate_root(root: &Path, env: impl Fn(&str) -> Option<OsString>, exe: Option<&Path>) -> Result<PathBuf, String> {
crate::profile_root::validate(root, env, exe, crate::profile_root::ensure_writable)
}
#[cfg(test)]
mod tests {
use super::*;
use std::cell::Cell;
fn args(values: &[&str]) -> Vec<OsString> {
values.iter().map(OsString::from).collect()
}
fn absolute() -> &'static str {
if cfg!(windows) { r"C:\NightlyData\profiles\filmcraft" } else { "/nightly-data/profiles/filmcraft" }
}
fn nightly() -> Vec<OsString> {
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--"])
}
#[test]
fn internal_graphics_retry_preserves_the_nightly_root_and_literal_files() {
let mut argv = args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--graphics", "dx12", "--"]);
argv.extend(args(&["project with spaces.fcproj", "--graphics", "--profile-root"]));
let launch = parse_startup(argv.clone(), true).unwrap();
assert_eq!(launch.profile, Profile::NightlyV1(PathBuf::from(absolute())));
assert_eq!(launch.args, args(&["--graphics", "dx12", "--", "project with spaces.fcproj", "--graphics", "--profile-root"]));
assert!(parse_startup(argv, false).is_err(), "an ordinary invocation must not gain extra protocol flags");
}
#[test]
fn retry_cannot_bypass_invalid_profiles_or_change_stable_arguments() {
let stable = args(&["--graphics", "dx12", "--new-instance", "stable.fcproj"]);
assert_eq!(parse_startup(stable.clone(), true).unwrap(), Launch { profile: Profile::Stable, args: stable });
let mut duplicate = args(&["--graphics", "dx12", "--graphics", "software"]);
duplicate.extend(nightly());
assert!(parse_startup(duplicate, true).is_err());
assert!(parse_startup(args(&["--graphics", "dx12", "--launch-profile", VERSION, "--profile-root", "relative", "--"]), true).is_err());
}
#[test]
fn stable_arguments_and_directory_policy_are_unchanged() {
for argv in [args(&[]), args(&["--new-instance", "a.fcproj"]), args(&["--", "--launch-profile", "file.fcproj"])] {
let launch = prepare(parse(argv.clone()).unwrap(), |_| panic!("stable must never validate a nightly root")).unwrap();
assert_eq!(launch, Launch { profile: Profile::Stable, args: argv });
}
}
#[test]
fn exact_version_and_root_are_parsed_without_reinterpreting_file_names() {
let mut argv = nightly();
argv.extend(args(&["--profile-root", "project with spaces.fcproj"]));
let launch = parse(argv).unwrap();
assert_eq!(launch.profile, Profile::NightlyV1(PathBuf::from(absolute())));
assert_eq!(launch.args, args(&["--", "--profile-root", "project with spaces.fcproj"]));
}
#[test]
fn missing_duplicate_unknown_and_conflicting_profile_arguments_are_refused() {
for argv in [
args(&["--launch-profile", VERSION]),
args(&["--profile-root", absolute()]),
args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--"]),
args(&["--launch-profile", VERSION, "--launch-profile", VERSION, "--profile-root", absolute(), "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--profile-root", absolute(), "--"]),
args(&["--launch-profile", VERSION, "--profile-root", "relative", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", "", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--new-instance", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute()]),
] {
assert!(parse(argv).is_err());
}
}
#[test]
fn the_launcher_version_check_is_a_version_query_only_in_its_exact_form() {
let pair = &["--launch-profile", VERSION, "--profile-root", absolute()];
let reversed = &["--profile-root", absolute(), "--launch-profile", VERSION];
for flag in ["--version", "-V"] {
for form in [pair, reversed] {
let mut argv = args(form);
argv.push(flag.into());
assert!(version_query(&argv), "{argv:?}");
}
}
for argv in [
args(&["--version"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--", "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--new-instance", "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--version"]),
args(&["--version", "--launch-profile", VERSION, "--profile-root", absolute()]),
args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", "relative", "--version"]),
args(&["--launch-profile", VERSION, "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--help"]),
] {
assert!(!version_query(&argv), "{argv:?}");
}
// Outside the query the strict protocol still refuses the version flag.
assert!(parse(args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version"])).is_err());
}
#[test]
fn failed_root_validation_never_reaches_startup_or_falls_back_to_stable() {
let reached = Cell::new(false);
let result = prepare(parse(nightly()).unwrap(), |_| Err("read-only or unsafe profile".into())).map(|_| reached.set(true));
assert!(result.is_err());
assert!(!reached.get());
}
#[test]
fn successful_root_validation_keeps_the_persistent_root_not_the_binary_tag() {
let checked = PathBuf::from(absolute()).join("checked");
let launch = prepare(parse(nightly()).unwrap(), |_| Ok(checked.clone())).unwrap();
assert_eq!(launch.profile.root(), Some(checked.as_path()));
assert!(launch.profile.is_nightly());
}
}
+244 -21
View File
@@ -28,16 +28,23 @@ mod appearance;
mod args;
mod audio;
mod audio_in;
#[cfg(test)]
mod build_channel;
mod build_flavor;
mod control_server;
#[cfg(target_os = "linux")]
mod dev_icon;
mod file_filters;
mod graphics;
mod launch_profile;
mod logging;
#[cfg(target_os = "macos")]
mod native_color;
#[cfg(target_os = "macos")]
mod native_menu;
mod nightly_session;
mod process_identity;
mod profile_root;
mod window_raise;
use args::{Cli, Launch};
@@ -49,17 +56,19 @@ use serde_json::json;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
/// Reverse-DNS app id: Linux `.desktop` file, hicolor icon name and Wayland app id.
const APP_ID: &str = "ai.storyteller.filmcraft";
/// The window, Dock, taskbar and app-switcher icon (`assets/app-icon/`, regenerated by
/// `packaging/icons.sh`). macOS gets the tile inside Apple's transparent margin so it matches the
/// size of other Dock icons; Windows and Linux get the full-bleed tile.
fn app_icon() -> egui::IconData {
#[cfg(target_os = "macos")]
let png: &[u8] = include_bytes!("../../../assets/app-icon/filmcraft-macos-512.png");
let (stable, nightly): (&[u8], &[u8]) =
(include_bytes!("../../../assets/app-icon/filmcraft-macos-512.png"), include_bytes!("../../../assets/app-icon/filmcraft-nightly-macos-512.png"));
#[cfg(not(target_os = "macos"))]
let png: &[u8] = include_bytes!("../../../assets/app-icon/hicolor/256x256/apps/ai.storyteller.filmcraft.png");
let (stable, nightly): (&[u8], &[u8]) = (
include_bytes!("../../../assets/app-icon/hicolor/256x256/apps/ai.storyteller.filmcraft.png"),
include_bytes!("../../../assets/app-icon/filmcraft-nightly.png"),
);
let png = if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 { nightly } else { stable };
eframe::icon_data::from_png_bytes(png).unwrap_or_default()
}
@@ -75,19 +84,129 @@ fn tell(text: &str, error: bool) {
#[cfg(all(target_os = "windows", not(debug_assertions)))]
{
let level = if error { rfd::MessageLevel::Error } else { rfd::MessageLevel::Info };
let _ = rfd::MessageDialog::new().set_level(level).set_title("FilmCraft").set_description(text).show();
let _ = rfd::MessageDialog::new().set_level(level).set_title(filmcraft_ui_egui::os_window::name()).set_description(text).show();
}
}
/// The exact version this build reports: the prepared nightly identity, or the workspace version.
fn version_text() -> &'static str {
env!("FILMCRAFT_BUILT_VERSION")
}
/// The commit the nightly identity was prepared from, when the build was given one.
fn built_commit() -> Option<&'static str> {
option_env!("FILMCRAFT_BUILT_COMMIT")
}
fn initialize_nightly_process_identity() -> Result<(), process_identity::IdentityError> {
let app_id = filmcraft_ui_egui::os_window::id_for(filmcraft_ui_egui::os_window::LaunchIdentity::NightlyV1);
process_identity::initialize(build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1, app_id)
}
/// Say why a nightly launch profile was refused: in the log, and on a desktop session also in a
/// native dialog (a Dock or Start Menu start has no console to read).
fn report_launch_profile_error(error: &str) {
eprintln!("{} launch profile: {error}", filmcraft_ui_egui::os_window::name());
let desktop_session = cfg!(windows)
|| cfg!(target_os = "macos")
|| (cfg!(target_os = "linux") && ["DISPLAY", "WAYLAND_DISPLAY"].into_iter().any(|key| std::env::var_os(key).is_some_and(|v| !v.is_empty())));
if build_flavor::needs_native_error(build_flavor::COMPILED, desktop_session) {
if let Err(error) = initialize_nightly_process_identity() {
eprintln!("filmcraft launch profile: {error}");
return;
}
let _ = rfd::MessageDialog::new()
.set_title(filmcraft_ui_egui::os_window::name())
.set_description(error)
.set_level(rfd::MessageLevel::Error)
.set_buttons(rfd::MessageButtons::Ok)
.show();
}
}
/// Select the immutable launch profile before any startup service or side effect, and give the
/// data directory (and every path derived from it) the profile's root.
///
/// Returns the arguments the rest of the start parses, or `None` when this was a version query.
fn prepare_launch() -> Option<Vec<std::ffi::OsString>> {
let argv: Vec<std::ffi::OsString> = std::env::args_os().skip(1).collect();
// Plain `--version`/`-V`, or the Launcher's `--launch-profile nightly-v1 --profile-root <dir>
// --version`: answered before root validation, process identity, logging or any window.
if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && (build_flavor::version_query(&argv) || launch_profile::version_query(&argv)) {
use std::io::Write as _;
let _ = writeln!(std::io::stdout(), "FilmCraft {}", build_flavor::version(build_flavor::COMPILED, version_text()));
return None;
}
// The graphics test child is an internal re-entry of this same program
// (`--test-graphics-start <mode>` [profile tokens]): its mode and root come from the parent,
// never from the environment.
let internal = argv.first().is_some_and(|arg| arg == graphics::probe::CHILD_ARG);
let early = if internal {
let tail = argv.get(2..).unwrap_or_default().to_vec();
launch_profile::parse(tail).unwrap_or_else(|error| {
report_launch_profile_error(&error);
std::process::exit(2)
})
} else {
let retry = std::env::var_os("FILMCRAFT_GRAPHICS_RELAUNCHED").is_some();
launch_profile::parse_startup(argv.clone(), retry).unwrap_or_else(|error| {
report_launch_profile_error(&error);
std::process::exit(2)
})
};
let early = build_flavor::require_profile(build_flavor::COMPILED, &early.profile)
.and_then(|()| initialize_nightly_process_identity().map_err(|error| error.to_string()))
.and_then(|()| {
launch_profile::prepare(early, |root| launch_profile::validate_root(root, |key| std::env::var_os(key), std::env::current_exe().ok().as_deref()))
})
.unwrap_or_else(|error| {
report_launch_profile_error(&error);
std::process::exit(2)
});
let identity =
if early.profile.is_nightly() { filmcraft_ui_egui::os_window::LaunchIdentity::NightlyV1 } else { filmcraft_ui_egui::os_window::LaunchIdentity::Stable };
// Read the launch's own arguments before `install` takes the profile: `runnable_argv` borrows it.
let runnable = runnable_argv(internal, argv, &early);
if let Err(error) = launch_profile::install(early.profile).and_then(|()| filmcraft_ui_egui::os_window::select_identity(identity)) {
report_launch_profile_error(&error);
std::process::exit(2);
}
// Every data root below comes from `default_data_dir`, which the override now answers first:
// preferences, workspaces, presets, auto-save, recovery, logs, crash logs, caches and models.
if let Some(root) = launch_profile::current().root()
&& let Err(error) = filmcraft_engine::autosave::set_data_dir_override(root.to_path_buf())
{
report_launch_profile_error(&error);
std::process::exit(2);
}
let _ = filmcraft_ui_egui::os_window::set_display_version(match build_flavor::COMPILED {
build_flavor::BuildFlavor::Stable => version_text().to_owned(),
build_flavor::BuildFlavor::NightlyV1 => build_flavor::version(build_flavor::COMPILED, version_text()),
});
Some(runnable)
}
/// What `main` parses once the profile is selected. A Launcher start gets the profile's own tail
/// (`--` and the file names): the raw argv still holds `--launch-profile`/`--profile-root`, which
/// `args::parse` refuses as unknown options, so every Nightly GUI start would exit 2. The graphics
/// test child keeps its `--test-graphics-start <mode>` re-entry line, and ignores the tokens after
/// it ([`graphics::probe::child_main`]).
fn runnable_argv(internal: bool, argv: Vec<std::ffi::OsString>, launch: &launch_profile::Launch) -> Vec<std::ffi::OsString> {
if internal { argv } else { launch.args.clone() }
}
fn main() -> eframe::Result {
// Windows: the update helper is a copy of this program started with `--finish-update`.
let Some(arguments) = prepare_launch() else { return Ok(()) };
let nightly = launch_profile::current().is_nightly();
// Windows: the update helper is a copy of this program started with `--finish-update`. A
// Nightly is updated by ArtCraft Launcher, never by the stable updater.
#[cfg(windows)]
if let Some(result) = craft_update::self_update::finish(&filmcraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::<Vec<_>>()) {
if !nightly && let Some(result) = craft_update::self_update::finish(&filmcraft_ui_egui::UPDATE_APP, &arguments) {
std::process::exit(i32::from(result.is_err()));
}
// Windows: the graphics test start (graphics/probe.rs) is this program started with
// `--test-graphics-start <mode>`. It creates the device the window would, then exits.
let args: Vec<std::ffi::OsString> = std::env::args_os().skip(1).collect();
let args: Vec<std::ffi::OsString> = arguments.clone();
let test_setup = |mode| {
let mut options = native_options(false);
graphics::apply(&mut options, mode, eframe::wgpu::Backends::from_env());
@@ -99,15 +218,17 @@ fn main() -> eframe::Result {
// First, so the panic hook and every start-up record are logged (`logging`).
let logger = logging::install();
// lossy, so a value that is not Unicode is reported like any other bad port instead of ignored
let env_port = std::env::var_os("FILMCRAFT_CONTROL_PORT").map(|p| p.to_string_lossy().into_owned());
let launch = match args::parse(env_port, std::env::args_os().skip(1)) {
// A Nightly start inherits no stable control server: the Launcher protocol has no per-launch
// options, and a nightly must never share stable's socket or port.
let env_port = if nightly { None } else { std::env::var_os("FILMCRAFT_CONTROL_PORT").map(|p| p.to_string_lossy().into_owned()) };
let launch = match args::parse(env_port, arguments.clone()) {
Ok(Cli::Run(l)) => l,
Ok(Cli::Help) => {
tell(args::USAGE, false);
return Ok(());
}
Ok(Cli::Version) => {
tell(&format!("filmcraft {}\n", env!("CARGO_PKG_VERSION")), false);
tell(&format!("filmcraft {}\n", version_text()), false);
return Ok(());
}
Err(e) => {
@@ -115,9 +236,13 @@ fn main() -> eframe::Result {
std::process::exit(2);
}
};
if nightly && (launch.control_port.is_some() || launch.control_input_only) {
eprintln!("filmcraft: a nightly-v1 start does not start the stable control server; drive FilmCraft Nightly through ArtCraft Launcher");
std::process::exit(2);
}
let data_root = launch.data_dir.clone().or_else(default_data_dir);
let log_dir = data_root.as_ref().map(|d| d.join(logging::LOG_DIR));
log::info!("FilmCraft {} ({} {})", env!("CARGO_PKG_VERSION"), std::env::consts::OS, std::env::consts::ARCH);
log::info!("{} {} ({} {})", filmcraft_ui_egui::os_window::name(), version_text(), std::env::consts::OS, std::env::consts::ARCH);
// The log file lives next to the crash logs; opened after the arguments, so `--help`,
// `--version` and usage errors leave no file behind. Records logged until now go in first.
let mut log_file = None;
@@ -135,8 +260,12 @@ fn main() -> eframe::Result {
}
}
app_nap::disable();
// The dev desktop entry is stable-only state under the XDG data dir; a Nightly profile is
// fenced away from it and the Launcher owns its own entry.
#[cfg(target_os = "linux")]
dev_icon::ensure_dev_desktop_entry();
if !nightly {
dev_icon::ensure_dev_desktop_entry();
}
// Panics anywhere go to <data dir>/Logs/crash-<day>.log with a backtrace; the UI pass and
// frame workers catch them and keep running (see filmcraft_ui_egui::crash).
filmcraft_ui_egui::crash::install(log_dir);
@@ -163,6 +292,35 @@ fn main() -> eframe::Result {
if graphics.mode() == graphics::Mode::Default {
register_gpu_frame_renderer();
}
// Nightly session health: a private record, finished only on a controlled exit, so a start
// that never reached one (a crash, a kill, a driver hang) is reported next time. No document
// names, paths or diagnostics are collected. Stable starts (and a failed record) own none.
let (nightly_session, session_health_warning) =
match nightly_session::Session::begin_with_health(launch_profile::current().root(), version_text(), built_commit()) {
Ok(state) => state,
Err(error) => {
log::warn!("Nightly session health is unavailable: {error}");
(None, true)
}
};
let previous_nightly_unclean = nightly_session.as_ref().is_some_and(nightly_session::Session::previous_unclean);
// Set once a window posted the interruption notice; until then the record must survive.
let unclean_notice_shown = Arc::new(AtomicBool::new(false));
let nightly_session: nightly_session::Shared = Arc::new(std::sync::Mutex::new(nightly_session));
if launch_profile::current().is_nightly() {
// The app's exit hook is the controlled return on macOS, where every quit ends the process
// inside AppKit's terminate, after `on_exit` and before `run_native` returns.
let shared = nightly_session.clone();
let shown = unclean_notice_shown.clone();
filmcraft_ui_egui::exit_hook::set(Box::new(move || {
nightly_session::finish_once(&shared, shown.load(Ordering::Relaxed));
}));
}
let session_notice = launch_profile::current().is_nightly().then(|| SessionNotice {
previous_unclean: previous_nightly_unclean,
warning: session_health_warning,
shown: unclean_notice_shown.clone(),
});
// A panic in a FilmCraft started again for it saved the next mode for the next launch.
let mut next_saved = false;
let started = loop {
@@ -170,8 +328,8 @@ fn main() -> eframe::Result {
// Before eframe creates the wgpu instance (e.g. no OpenGL on Windows, see graphics.rs).
graphics::apply(&mut options, graphics.mode(), backend_override);
let app_created = Arc::new(AtomicBool::new(false));
let creator = app_creator(launch.clone(), graphics.clone(), Arc::clone(&app_created));
let run = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| eframe::run_native("FilmCraft", options, creator)));
let creator = app_creator(launch.clone(), graphics.clone(), Arc::clone(&app_created), session_notice.clone());
let run = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| eframe::run_native(filmcraft_ui_egui::os_window::name(), options, creator)));
let app_created = app_created.load(Ordering::Relaxed);
let result = match run {
Ok(result) => result,
@@ -192,6 +350,10 @@ fn main() -> eframe::Result {
// `run_native` returns at once, #2558): FilmCraft starts again in that mode, once.
if next_saved && std::env::var_os(RELAUNCHED).is_none() {
graphics.finish();
// The start that follows (this program in the next mode) must own the profile:
// a parent that keeps the lease makes it a busy secondary with no health
// record. Releasing is not a controlled finish, so the record stays for it.
nightly_session::release(&nightly_session);
match relaunch(graphics.mode()) {
Ok(code) => std::process::exit(code),
Err(e) => log::error!("can't start FilmCraft again in graphics mode {}: {e}", graphics.mode().name()),
@@ -215,6 +377,9 @@ fn main() -> eframe::Result {
};
// However it ended, this start no longer counts as one that died.
graphics.finish();
// A controlled return (including a handled startup error): finish the record here, once.
// On macOS a window that was created already finished it in the exit hook, so this is a no-op.
nightly_session::finish_once(&nightly_session, unclean_notice_shown.load(Ordering::Relaxed));
// The window could not be created (no usable GPU / graphics driver, no display): say so
// instead of exiting silently, and keep the reason in the crash log.
if let Err(e) = &started {
@@ -285,7 +450,7 @@ fn panic_text(panic: &(dyn std::any::Any + Send)) -> &str {
fn native_options(agent: bool) -> eframe::NativeOptions {
eframe::NativeOptions {
viewport: egui::ViewportBuilder::default()
.with_title("FilmCraft")
.with_title(filmcraft_ui_egui::os_window::name())
.with_inner_size([1600.0, 980.0])
.with_min_inner_size([900.0, 560.0])
.with_drag_and_drop(true)
@@ -296,18 +461,34 @@ fn native_options(agent: bool) -> eframe::NativeOptions {
.with_active(!agent)
.with_icon(app_icon())
// Wayland matches the window to `packaging/linux/ai.storyteller.filmcraft.desktop`.
.with_app_id(APP_ID),
.with_app_id(filmcraft_ui_egui::os_window::app_id()),
event_loop_builder: agent_event_loop(agent),
..Default::default()
}
}
/// What a Nightly window must say about the previous session (and that it cannot run the stable
/// updater). `shown` records that a window posted an earlier interruption's notice, so the record
/// is kept until someone has actually seen it.
#[derive(Clone)]
struct SessionNotice {
previous_unclean: bool,
warning: bool,
shown: Arc<AtomicBool>,
}
/// Creates the app once eframe has its window and graphics device; sets `created` when it runs,
/// and confirms the graphics mode once two frames have painted.
fn app_creator(launch: Launch, graphics: graphics::GraphicsStart, created: Arc<AtomicBool>) -> eframe::AppCreator<'static> {
fn app_creator(
launch: Launch,
graphics: graphics::GraphicsStart,
created: Arc<AtomicBool>,
session_notice: Option<SessionNotice>,
) -> eframe::AppCreator<'static> {
let Launch { control_port, control_input_only, files, demo, startup_flag, recover, data_dir, graphics: _ } = launch;
Box::new(move |cc| {
filmcraft_ui_egui::framework::install(&cc.egui_ctx, APP_ID).map_err(|error| format!("the UI runtime could not be installed: {error}"))?;
filmcraft_ui_egui::framework::install(&cc.egui_ctx, filmcraft_ui_egui::os_window::app_id())
.map_err(|error| format!("the UI runtime could not be installed: {error}"))?;
filmcraft_ui_egui::install_ime_reset_callbacks(&cc.egui_ctx);
created.store(true, Ordering::Relaxed);
// Start the control server before anything touches recovery state: `file.recover`
@@ -374,7 +555,23 @@ fn app_creator(launch: Launch, graphics: graphics::GraphicsStart, created: Arc<A
}
}
let mut app = FilmcraftApp::new(session);
app.set_startup_update_check(true);
app.set_startup_update_check(session_notice.is_none());
if let Some(health) = session_notice {
// Updated by ArtCraft Launcher, never by the stable updater.
app.disable_updates();
if health.previous_unclean || health.warning {
let message = if health.previous_unclean {
"The previous FilmCraft Nightly session did not finish normally. You can report a problem from About. No diagnostics have been sent."
} else {
"FilmCraft Nightly could not record session health in its private profile. You can still edit, but abnormal-exit detection is unavailable."
};
let mut notice = filmcraft_ui_egui::notices::Notice::new(filmcraft_ui_egui::os_window::name(), vec![message.to_owned()]);
// Cleared only once a kept pass drew the notice: closing before that keeps the
// interruption record for the next launch instead of dropping it unseen.
notice.shown = Some(health.shown.clone());
app.notice = Some(notice);
}
}
app.graphics_notice = notice;
if recover == Some(false) {
app.dialog = None;
@@ -692,6 +889,32 @@ fn project_patterns() -> Vec<String> {
#[cfg(test)]
mod tests {
/// A Launcher start hands `main` the profile's own tail: the raw argv (still holding
/// `--launch-profile`/`--profile-root`) made `args::parse` exit 2 on every Nightly window.
#[test]
fn a_nightly_launch_parses_the_prepared_tail_and_not_the_launcher_protocol() {
let os = |v: &[&str]| v.iter().map(std::ffi::OsString::from).collect::<Vec<_>>();
let root = if cfg!(windows) { r"C:\NightlyData\profiles\filmcraft" } else { "/nightly-data/profiles/filmcraft" };
let argv = os(&["--launch-profile", "nightly-v1", "--profile-root", root, "--", "cut.fcproj", "clip with spaces.mp4"]);
let launch = crate::launch_profile::parse(argv.clone()).unwrap();
let tail = super::runnable_argv(false, argv.clone(), &launch);
assert_eq!(tail, launch.args);
match crate::args::parse(None, tail) {
Ok(crate::args::Cli::Run(l)) => assert_eq!(l.files, ["cut.fcproj", "clip with spaces.mp4"]),
other => panic!("a nightly launch should start the app, got {other:?}"),
}
// A `--version` the Launcher appends after `--` stays a file name, as for stable.
let query = os(&["--launch-profile", "nightly-v1", "--profile-root", root, "--", "--version"]);
let launch = crate::launch_profile::parse(query.clone()).unwrap();
assert!(matches!(crate::args::parse(None, super::runnable_argv(false, query, &launch)), Ok(crate::args::Cli::Run(l)) if l.files == ["--version"]));
// The graphics test child keeps its re-entry head (`--test-graphics-start <mode>` first);
// the raw Launcher line stays what `args::parse` refuses.
let child = os(&["--test-graphics-start", "default", "--launch-profile", "nightly-v1", "--profile-root", root, "--"]);
let launch = crate::launch_profile::parse(child[2..].to_vec()).unwrap();
assert_eq!(super::runnable_argv(true, child.clone(), &launch), child);
assert!(crate::args::parse(None, argv).is_err(), "the raw Launcher line is not a FilmCraft command line");
}
/// The new start after a graphics panic keeps the arguments and picks the next mode, replacing a
/// `--graphics` that was given (#2558).
#[test]
+269
View File
@@ -0,0 +1,269 @@
//! App-private Nightly session health, not telemetry or a Launcher protocol.
//! A live owner holds a separate persistent lease; secondary launches never rewrite its record.
//! Dropping the guard does not clear the marker. Only the app's controlled return path does.
use std::fs::{File, OpenOptions};
use std::io::{self, Read};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, PoisonError};
const RECORD: &str = "nightly-session.json";
const LEASE: &str = "nightly-session.lock";
const MAX_METADATA_BYTES: usize = 256;
pub struct Session {
_lease: File,
path: PathBuf,
own_record: Vec<u8>,
previous_unclean: bool,
}
fn regular_or_missing(path: &Path) -> io::Result<bool> {
match std::fs::symlink_metadata(path) {
Ok(metadata) if metadata.file_type().is_file() && !metadata.file_type().is_symlink() => Ok(true),
Ok(_) => Err(io::Error::other("Nightly session state must be a regular file, not an alias or directory")),
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false),
Err(error) => Err(error),
}
}
/// The owner's session, shared by the app's exit hook (macOS) and the code after the event loop.
/// On macOS every quit ends the process inside AppKit's terminate, after eframe's `on_exit` and
/// before `eframe::run_native` could return, so the exit hook finishes it there; the return path
/// still runs for a start that created no window.
pub type Shared = Arc<Mutex<Option<Session>>>;
/// Release the private profile without completing it: a graphics-restart successor then owns the
/// lease and reports the interruption, instead of becoming a busy secondary with no record.
pub fn release(shared: &Shared) {
drop(shared.lock().unwrap_or_else(PoisonError::into_inner).take());
}
/// The controlled return ([`Session::finish`]) by whichever path comes first; later calls do nothing.
pub fn finish_once(shared: &Shared, unclean_notice_shown: bool) {
let watch = shared.lock().unwrap_or_else(PoisonError::into_inner).take();
if let Some(watch) = watch
&& let Err(error) = watch.finish(unclean_notice_shown)
{
log::warn!("Nightly session state was left intact: {error}");
}
}
impl Session {
/// The warning belongs to this window: a busy secondary has no health-record coverage,
/// while Stable and a lease-owning Nightly window preserve their existing result.
pub fn begin_with_health(root: Option<&Path>, version: &str, commit: Option<&str>) -> io::Result<(Option<Self>, bool)> {
let watch = Self::begin(root, version, commit)?;
let unavailable = root.is_some() && watch.is_none();
Ok((watch, unavailable))
}
/// `None` is stable or another owner of this profile. Neither case touches the record.
/// The supplied root must already be the validated private Nightly profile.
pub fn begin(root: Option<&Path>, version: &str, commit: Option<&str>) -> io::Result<Option<Self>> {
let Some(root) = root else { return Ok(None) };
if version.is_empty() || version.len() > MAX_METADATA_BYTES || commit.is_some_and(|value| value.len() > MAX_METADATA_BYTES) {
return Err(io::Error::new(io::ErrorKind::InvalidInput, "Nightly session provenance is missing or too large"));
}
let lease_path = root.join(LEASE);
regular_or_missing(&lease_path)?;
let lease = OpenOptions::new().read(true).write(true).create(true).truncate(false).open(lease_path)?;
match lease.try_lock() {
Ok(()) => {}
Err(std::fs::TryLockError::WouldBlock) => return Ok(None),
Err(std::fs::TryLockError::Error(error)) => return Err(error),
}
let path = root.join(RECORD);
let previous_unclean = regular_or_missing(&path)?;
let own_record = serde_json::to_vec(&serde_json::json!({
"schema_version": 1,
"channel": "nightly-v1",
"version": version,
"commit": commit.filter(|value| !value.is_empty()),
}))?;
// The app already uses this durable writer; a raced destination link is replaced, not followed.
filmcraft_format::atomic_write_no_follow(&path, &own_record)?;
Ok(Some(Self { _lease: lease, path, own_record, previous_unclean }))
}
pub fn previous_unclean(&self) -> bool {
self.previous_unclean
}
/// Controlled return. If an earlier session's interruption was detected but no window showed
/// it yet (a renderer failure before the app callback, including the CPU-retry handoff), the
/// record is left for the next owner to report; otherwise this is [`Self::complete`].
pub fn finish(self, unclean_notice_shown: bool) -> io::Result<()> {
if self.previous_unclean && !unclean_notice_shown {
return Ok(());
}
self.complete()
}
/// Controlled event-loop completion includes a handled startup error/CPU handoff, not only
/// exit0. Clear before releasing primary IPC so a successor cannot miss record ownership.
/// An unwind, abort, forced exit or killed process never calls this method.
pub fn complete(self) -> io::Result<()> {
if !regular_or_missing(&self.path)? {
return Ok(());
}
let mut current = Vec::new();
File::open(&self.path)?.take(self.own_record.len() as u64 + 1).read_to_end(&mut current)?;
if current != self.own_record {
return Err(io::Error::other("Nightly session state changed; leaving it intact"));
}
std::fs::remove_file(&self.path)
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicU64, Ordering};
struct Fixture(PathBuf);
impl Fixture {
fn new() -> Self {
static NEXT: AtomicU64 = AtomicU64::new(0);
loop {
let path = std::env::temp_dir().join(format!("film-nightly-session-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
match std::fs::create_dir(&path) {
Ok(()) => return Self(path),
Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue,
Err(error) => panic!("cannot create owned fixture: {error}"),
}
}
}
}
impl Drop for Fixture {
fn drop(&mut self) {
std::fs::remove_dir_all(&self.0).unwrap();
}
}
#[test]
fn busy_secondary_reports_unavailable_without_replacing_the_owner_record() {
let fixture = Fixture::new();
let (stable, warning) = Session::begin_with_health(None, "stable", None).unwrap();
assert!(stable.is_none() && !warning);
let (first, warning) = Session::begin_with_health(Some(&fixture.0), "nightly", Some("owned-commit")).unwrap();
assert!(!warning);
let first = first.unwrap();
let record = std::fs::read(fixture.0.join(RECORD)).unwrap();
let (secondary, warning) = Session::begin_with_health(Some(&fixture.0), "secondary", None).unwrap();
assert!(secondary.is_none() && warning, "a secondary window cannot claim recorded exit/crash coverage");
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), record);
first.complete().unwrap();
assert!(!fixture.0.join(RECORD).exists());
}
#[test]
fn controlled_completion_is_clean_but_an_unfinished_owner_is_reported_next_time() {
let fixture = Fixture::new();
let first = Session::begin(Some(&fixture.0), "first", Some("recorded-commit")).unwrap().unwrap();
assert!(!first.previous_unclean());
let own = std::fs::read(fixture.0.join(RECORD)).unwrap();
assert!(Session::begin(Some(&fixture.0), "secondary", None).unwrap().is_none());
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), own, "a busy secondary must not replace the owner's record");
first.complete().unwrap();
assert!(!fixture.0.join(RECORD).exists());
let unfinished = Session::begin(Some(&fixture.0), "second", None).unwrap().unwrap();
assert!(!unfinished.previous_unclean());
drop(unfinished); // Unwind/abnormal-path ownership release, not a controlled completion.
let next = Session::begin(Some(&fixture.0), "third", None).unwrap().unwrap();
assert!(next.previous_unclean());
next.complete().unwrap();
assert!(!fixture.0.join(RECORD).exists());
}
#[test]
fn an_interruption_no_window_showed_survives_a_handled_startup_failure() {
let fixture = Fixture::new();
drop(Session::begin(Some(&fixture.0), "crashed", None).unwrap().unwrap());
// Renderer initialization failed before the app callback: no notice was shown.
let failed = Session::begin(Some(&fixture.0), "gpu-failed", None).unwrap().unwrap();
assert!(failed.previous_unclean());
failed.finish(false).unwrap();
// The CPU retry (or the next start) still sees the interruption and shows it.
let retry = Session::begin(Some(&fixture.0), "cpu-retry", None).unwrap().unwrap();
assert!(retry.previous_unclean());
retry.finish(true).unwrap();
assert!(!fixture.0.join(RECORD).exists(), "a session that showed the notice clears its record");
// Without an earlier interruption, a handled failure still clears normally.
let clean = Session::begin(Some(&fixture.0), "clean", None).unwrap().unwrap();
assert!(!clean.previous_unclean());
clean.finish(false).unwrap();
assert!(!fixture.0.join(RECORD).exists());
}
#[test]
fn the_exit_hook_and_the_return_path_finish_the_session_once() {
let fixture = Fixture::new();
let shared: Shared = Arc::new(Mutex::new(Session::begin(Some(&fixture.0), "quitting", None).unwrap()));
// The exit hook (macOS quit: the only path that runs there).
finish_once(&shared, false);
assert!(!fixture.0.join(RECORD).exists(), "a quit that ran the exit hook is a clean exit");
// Elsewhere the return path runs too, by then possibly after a successor took the profile.
let successor = Session::begin(Some(&fixture.0), "successor", None).unwrap().unwrap();
assert!(!successor.previous_unclean());
let record = std::fs::read(fixture.0.join(RECORD)).unwrap();
finish_once(&shared, false);
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), record, "the second finish must not touch a successor's record");
successor.complete().unwrap();
}
#[test]
fn releasing_the_lease_hands_the_profile_to_a_successor_that_reports_the_interruption() {
let fixture = Fixture::new();
let shared: Shared = Arc::new(Mutex::new(Session::begin(Some(&fixture.0), "graphics-panic", None).unwrap()));
release(&shared);
// The successor (this program restarted in the next graphics mode) owns the profile at once:
// no "could not record session health" warning, and the interruption is still reported.
let (successor, warning) = Session::begin_with_health(Some(&fixture.0), "successor", None).unwrap();
assert!(!warning, "the released profile is not a busy secondary");
let successor = successor.unwrap();
assert!(successor.previous_unclean());
successor.finish(true).unwrap();
// The released owner's return path is a no-op, not a second completion.
finish_once(&shared, true);
assert!(!fixture.0.join(RECORD).exists());
}
#[test]
fn cleanup_never_removes_an_unknown_changed_record() {
let fixture = Fixture::new();
let watch = Session::begin(Some(&fixture.0), "nightly", None).unwrap().unwrap();
std::fs::write(fixture.0.join(RECORD), b"replacement owned by someone else").unwrap();
assert!(watch.complete().is_err());
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), b"replacement owned by someone else");
}
#[test]
fn provenance_is_bounded_and_never_collects_documents_paths_or_diagnostics() {
let fixture = Fixture::new();
assert!(Session::begin(Some(&fixture.0), &"x".repeat(MAX_METADATA_BYTES + 1), None).is_err());
assert_eq!(std::fs::read_dir(&fixture.0).unwrap().count(), 0);
assert!(Session::begin(None, "", None).unwrap().is_none(), "stable has no session-health side effects");
let watch = Session::begin(Some(&fixture.0), "nightly", None).unwrap().unwrap();
let data: serde_json::Value = serde_json::from_slice(&std::fs::read(fixture.0.join(RECORD)).unwrap()).unwrap();
let fields = data.as_object().unwrap().keys().map(String::as_str).collect::<std::collections::BTreeSet<_>>();
assert_eq!(fields, ["schema_version", "channel", "version", "commit"].into_iter().collect());
assert!(data["commit"].is_null(), "missing provenance must not be invented");
watch.complete().unwrap();
}
#[test]
#[cfg(unix)]
fn reserved_state_aliases_do_not_modify_external_files() {
let fixture = Fixture::new();
let external = fixture.0.join("stable-document");
std::fs::write(&external, b"stable bytes").unwrap();
for name in [LEASE, RECORD] {
let alias = fixture.0.join(name);
std::os::unix::fs::symlink(&external, &alias).unwrap();
assert!(Session::begin(Some(&fixture.0), "nightly", None).is_err());
assert_eq!(std::fs::read(&external).unwrap(), b"stable bytes");
std::fs::remove_file(alias).unwrap();
}
}
}
+69
View File
@@ -0,0 +1,69 @@
//! Set the immutable nightly Windows identity before any native window or COM service.
//! Stable deliberately leaves its implicit shortcut/path identity unchanged.
use std::sync::OnceLock;
#[derive(Clone, Debug, thiserror::Error)]
pub enum IdentityError {
#[error("{0}")]
Configuration(String),
}
pub fn initialize(nightly: bool, app_id: &str) -> Result<(), IdentityError> {
configure(nightly && cfg!(windows), app_id, |id| {
static RESULT: OnceLock<Result<(), String>> = OnceLock::new();
RESULT
.get_or_init(|| {
#[cfg(windows)]
{
winsafe::SetCurrentProcessExplicitAppUserModelID(id).map_err(|error| format!("cannot set the nightly Windows identity: {error}"))?;
let actual = winsafe::GetCurrentProcessExplicitAppUserModelID()
.map_err(|error| format!("cannot read back the nightly Windows identity: {error}"))?;
if actual != id {
return Err("the native Windows identity did not match the selected nightly channel".into());
}
Ok(())
}
#[cfg(not(windows))]
{
let _ = id;
Ok(())
}
})
.clone()
})
.map_err(IdentityError::Configuration)
}
fn configure(explicit_nightly: bool, app_id: &str, set: impl FnOnce(&str) -> Result<(), String>) -> Result<(), String> {
if explicit_nightly { set(app_id) } else { Ok(()) }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn stable_does_not_call_the_explicit_identity_api() {
configure(false, "nightly-id", |_| panic!("stable identity must remain implicit")).unwrap();
}
#[test]
fn nightly_applies_the_supplied_identity_once() {
let calls = std::cell::Cell::new(0);
configure(true, "nightly-id", |id| {
assert_eq!(id, "nightly-id");
calls.set(calls.get() + 1);
Ok(())
})
.unwrap();
assert_eq!(calls.get(), 1);
}
#[test]
fn native_identity_failure_is_returned_instead_of_starting_a_window() {
let started = std::cell::Cell::new(false);
let result = configure(true, "nightly-id", |_| Err("native identity refused".into())).map(|()| started.set(true));
assert_eq!(result.unwrap_err(), "native identity refused");
assert!(!started.get());
}
}
+639
View File
@@ -0,0 +1,639 @@
//! App-owned nightly profile fences; no stable fallback, migration or process environment changes.
use std::ffi::OsString;
use std::sync::atomic::{AtomicU64, Ordering};
use std::path::{Component, Path, PathBuf};
/// The portable marker `filmcraft_engine::autosave` looks for beside the executable.
const PORTABLE_MARKER: &str = "portable.txt";
/// The folder a portable install keeps its data in, beside that marker.
const PORTABLE_DATA_DIR: &str = "data";
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Platform {
Windows,
Linux,
Mac,
}
impl Platform {
fn current() -> Result<Self, String> {
match std::env::consts::OS {
"windows" => Ok(Self::Windows),
"linux" => Ok(Self::Linux),
"macos" => Ok(Self::Mac),
_ => Err("nightly-v1 is not defined for this operating system".into()),
}
}
fn ignores_case(self) -> bool {
self != Self::Linux
}
}
fn absolute(path: PathBuf, label: &str) -> Result<PathBuf, String> {
if !path.is_absolute() || path.components().any(|c| matches!(c, Component::ParentDir)) {
return Err(format!("{label} must be absolute and contain no parent traversal"));
}
Ok(path)
}
fn required_base(env: &impl Fn(&str) -> Option<OsString>, key: &str) -> Result<PathBuf, String> {
let value = env(key).filter(|v| !v.is_empty()).ok_or_else(|| format!("cannot establish the stable {key} boundary"))?;
absolute(PathBuf::from(value), key)
}
fn xdg_base(env: &impl Fn(&str) -> Option<OsString>, key: &str, fallback: &str) -> Result<PathBuf, String> {
match env(key).filter(|v| !v.is_empty()) {
Some(value) => absolute(PathBuf::from(value), key),
None => Ok(required_base(env, "HOME")?.join(fallback)),
}
}
/// Resolve existing ancestors before creating anything. A dangling link or inaccessible ancestor
/// is not a missing directory that may be replaced or followed later.
fn canonical_future(path: &Path) -> Result<PathBuf, String> {
let mut parent = path;
let mut missing = Vec::new();
loop {
match std::fs::symlink_metadata(parent) {
Ok(_) => break,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
missing.push(parent.file_name().ok_or("the profile root has no existing ancestor")?.to_os_string());
parent = parent.parent().ok_or("the profile root has no existing ancestor")?;
}
Err(error) => return Err(format!("cannot inspect the profile boundary: {error}")),
}
}
let mut resolved = std::fs::canonicalize(parent).map_err(|e| format!("cannot resolve the profile boundary: {e}"))?;
for part in missing.into_iter().rev() {
resolved.push(part);
}
Ok(resolved)
}
fn overlaps(a: &Path, b: &Path, platform: Platform) -> bool {
let parts = |p: &Path| {
p.components()
.map(|c| {
let value = c.as_os_str().to_string_lossy().into_owned();
if platform.ignores_case() { value.to_lowercase() } else { value }
})
.collect::<Vec<_>>()
};
let (a, b) = (parts(a), parts(b));
a.starts_with(&b) || b.starts_with(&a)
}
fn installation_boundary(platform: Platform, exe: &Path) -> Result<PathBuf, String> {
let parent = exe.parent().ok_or("cannot establish the installation boundary")?;
if platform == Platform::Mac {
// A profile in Resources is still inside the versioned install, not beside MacOS.
if let Some(bundle) = exe.ancestors().find(|p| p.extension().is_some_and(|ext| ext.eq_ignore_ascii_case("app"))) {
return Ok(bundle.to_path_buf());
}
}
Ok(parent.to_path_buf())
}
fn forbidden_roots(platform: Platform, env: &impl Fn(&str) -> Option<OsString>, exe: &Path) -> Result<Vec<PathBuf>, String> {
let mut roots = match platform {
Platform::Windows => {
// %APPDATA%\FilmCraft is the per-user data directory (autosave::default_data_dir);
// %LOCALAPPDATA%\FilmCraft is fenced as well, so no future local cache can land there.
let mut roots =
["APPDATA", "LOCALAPPDATA"].into_iter().map(|key| required_base(env, key).map(|p| p.join("FilmCraft"))).collect::<Result<Vec<_>, _>>()?;
// The MSI's default per-user and per-machine folders (install-policy.wxi). A custom
// install folder is not known here; the executable's own folder is fenced below.
roots.push(required_base(env, "LOCALAPPDATA")?.join("Programs").join("ArtCraft").join("FilmCraft"));
for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] {
if let Some(base) = env(key).filter(|v| !v.is_empty()) {
roots.push(absolute(PathBuf::from(base), key)?.join("ArtCraft").join("FilmCraft"));
}
}
roots
}
Platform::Linux => {
// The data directory is real; the config, cache and state roots are fenced so a
// future one cannot point Nightly at stable state. `~/.var/app` is the stable
// Flatpak's own per-app folder.
let mut roots =
[("XDG_DATA_HOME", ".local/share"), ("XDG_CONFIG_HOME", ".config"), ("XDG_CACHE_HOME", ".cache"), ("XDG_STATE_HOME", ".local/state")]
.into_iter()
.map(|(key, fallback)| xdg_base(env, key, fallback).map(|p| p.join("filmcraft")))
.collect::<Result<Vec<_>, _>>()?;
roots.extend(["/usr/bin/filmcraft", "/usr/local/bin/filmcraft", "/opt/filmcraft"].map(PathBuf::from));
let data = xdg_base(env, "XDG_DATA_HOME", ".local/share")?;
// Dev builds write a desktop entry and its hicolor icons into the XDG data dir
// (apps/filmcraft/src/dev_icon.rs); a Nightly profile is never inside them.
roots.push(data.join("applications").join("ai.storyteller.filmcraft.desktop"));
roots.push(data.join("icons").join("hicolor"));
roots.push(required_base(env, "HOME")?.join(".var/app/ai.storyteller.filmcraft"));
roots
}
Platform::Mac => {
let home = required_base(env, "HOME")?;
let library = home.join("Library");
vec![
library.join("Application Support/FilmCraft"),
library.join("Caches/FilmCraft"),
library.join("Caches/ai.storyteller.filmcraft"),
library.join("Preferences/FilmCraft"),
library.join("Preferences/ai.storyteller.filmcraft.plist"),
library.join("Saved Application State/ai.storyteller.filmcraft.savedState"),
home.join("Applications/FilmCraft.app"),
PathBuf::from("/Applications/FilmCraft.app"),
]
}
};
roots.push(installation_boundary(platform, exe)?);
roots.into_iter().map(|p| canonical_future(&p)).collect()
}
fn private_subdirectory(root: &Path, name: impl AsRef<Path>, label: &str, platform: Platform) -> Result<PathBuf, String> {
let chosen = canonical_future(&absolute(root.to_path_buf(), "the nightly profile root")?)?;
let child = canonical_future(&chosen.join(name))?;
if child == chosen || !child.starts_with(&chosen) {
return Err(format!("the nightly {label} must stay inside its selected profile"));
}
// The target's own ancestors decide this, not the profile's: an alias may otherwise point into
// a Stable portable install that happens to sit inside the selected profile.
if is_portable_layout(&child, platform) {
return Err(format!("the nightly {label} must not use a portable FilmCraft installation or its data folder"));
}
Ok(child)
}
/// Every existing entry directly in the profile (logs, preferences and so on) must resolve inside
/// it, so a link there cannot point Nightly's writes at another app's data.
fn entries_stay_inside(root: &Path, platform: Platform) -> Result<(), String> {
let entries = match std::fs::read_dir(root) {
Ok(entries) => entries,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
Err(error) => return Err(format!("cannot inspect the nightly profile: {error}")),
};
for entry in entries {
let entry = entry.map_err(|e| format!("cannot inspect the nightly profile: {e}"))?;
private_subdirectory(root, entry.file_name(), "profile entry", platform)?;
}
Ok(())
}
/// Recognise the portable data namespace in both the supplied and resolved path. A marker only
/// counts beside a FilmCraft executable (above the chosen folder itself), so an unrelated
/// `portable.txt` higher up does not refuse the profile.
///
/// A `data` component counts only when its parent holds the portable marker: the Nightly Flatpak's
/// own `~/.var/app/…/data/filmcraft-nightly/profile`, and any home with a `data` folder, are
/// ordinary per-user paths, not a portable install's data directory.
fn is_portable_layout(path: &Path, platform: Platform) -> bool {
path.ancestors().enumerate().any(|(depth, ancestor)| {
ancestor.join(PORTABLE_MARKER).is_file() && (depth == 0 || ["filmcraft.exe", "filmcraft", "FilmCraft"].iter().any(|exe| ancestor.join(exe).is_file()))
}) || path.ancestors().any(|ancestor| {
let named_data = ancestor.file_name().is_some_and(|name| {
if platform.ignores_case() { name.to_string_lossy().eq_ignore_ascii_case(PORTABLE_DATA_DIR) } else { name == PORTABLE_DATA_DIR }
});
named_data && ancestor.parent().is_some_and(|install| install.join(PORTABLE_MARKER).is_file())
})
}
/// The app's existing exclusive write probe: create and remove a file in the profile.
pub fn ensure_writable(dir: &Path) -> std::io::Result<()> {
// The name is unique to this validation: two windows may validate the same writable profile at
// once, and a shared name would make the second `create_new` fail with AlreadyExists.
static NEXT: AtomicU64 = AtomicU64::new(0);
let probe = dir.join(format!("exclusive-write-probe-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
let file = std::fs::OpenOptions::new().write(true).create_new(true).open(&probe)?;
drop(file);
std::fs::remove_file(probe)
}
/// The writable hook is injected so the boundary tests exercise the real policy without starting
/// the app or changing global state.
pub fn validate(
root: &Path,
env: impl Fn(&str) -> Option<OsString>,
exe: Option<&Path>,
writable: impl FnOnce(&Path) -> std::io::Result<()>,
) -> Result<PathBuf, String> {
validate_for(Platform::current()?, root, env, exe, writable)
}
fn validate_for(
platform: Platform,
root: &Path,
env: impl Fn(&str) -> Option<OsString>,
exe: Option<&Path>,
writable: impl FnOnce(&Path) -> std::io::Result<()>,
) -> Result<PathBuf, String> {
absolute(root.to_path_buf(), "the nightly profile root")?;
// The stable data-directory override would point every write outside the private profile.
if env("FILMCRAFT_DATA_DIR").is_some_and(|v| !v.is_empty()) {
return Err("nightly-v1 cannot be combined with FILMCRAFT_DATA_DIR".into());
}
if platform != Platform::Windows {
// A native Nightly package must not inherit a Flatpak runtime: its socket namespace could
// point this profile at another app's instance. The Nightly Flatpak itself is not that
// case -- its sandbox data is `~/.var/app/ai.storyteller.filmcraft.nightly`, separate from
// stable -- so exactly the app's own Nightly id is accepted and every other value refused.
if let Some(id) = env("FLATPAK_ID").filter(|value| !value.is_empty())
&& id.as_os_str() != std::ffi::OsStr::new(filmcraft_ui_egui::os_window::NIGHTLY_PACKAGE_ID)
{
return Err("nightly-v1 native packages cannot inherit a Flatpak instance; launch through the native Launcher".into());
}
}
let chosen = canonical_future(root)?;
if is_portable_layout(root, platform) || is_portable_layout(&chosen, platform) {
return Err("the nightly root must not use a portable FilmCraft installation or its data folder".into());
}
let exe = absolute(exe.ok_or("cannot establish the installation boundary")?.to_path_buf(), "the executable")?;
let forbidden = forbidden_roots(platform, &env, &exe)?;
if forbidden.iter().any(|stable| overlaps(&chosen, stable, platform)) {
return Err("the nightly root must not overlap stable data or an installation".into());
}
entries_stay_inside(&chosen, platform)?;
// Recovery can read, adopt, overwrite and sweep entries, and the log writer rotates files.
// Never let their aliases leave this private profile or alias portable data inside it.
private_subdirectory(&chosen, "Recovery", "recovery folder", platform)?;
private_subdirectory(&chosen, "Logs", "log folder", platform)?;
let mut create = std::fs::DirBuilder::new();
create.recursive(true);
#[cfg(unix)]
{
use std::os::unix::fs::DirBuilderExt as _;
create.mode(0o700);
}
create.create(&chosen).map_err(|e| format!("cannot create the nightly profile: {e}"))?;
let confirmed = std::fs::canonicalize(&chosen).map_err(|e| format!("cannot resolve the created nightly profile: {e}"))?;
if confirmed != chosen || forbidden.iter().any(|stable| overlaps(&confirmed, stable, platform)) {
return Err("the nightly profile changed while it was being validated".into());
}
private_subdirectory(&confirmed, "Recovery", "recovery folder", platform)?;
private_subdirectory(&confirmed, "Logs", "log folder", platform)?;
entries_stay_inside(&confirmed, platform)?;
writable(&confirmed).map_err(|e| format!("the nightly profile is not writable: {e}"))?;
Ok(confirmed)
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::BTreeMap;
use std::sync::atomic::{AtomicU64, Ordering};
struct Fixture {
root: PathBuf,
env: BTreeMap<String, OsString>,
exe: PathBuf,
}
impl Fixture {
fn new() -> Self {
static NEXT: AtomicU64 = AtomicU64::new(0);
let root = loop {
let candidate = std::env::temp_dir().join(format!("filmcraft-profile-policy-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
match std::fs::create_dir(&candidate) {
Ok(()) => break std::fs::canonicalize(candidate).unwrap(),
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
Err(error) => panic!("cannot create owned fixture: {error}"),
}
};
let home = root.join("home");
let exe = root.join("install/filmcraft");
std::fs::create_dir_all(&home).unwrap();
std::fs::create_dir_all(exe.parent().unwrap()).unwrap();
std::fs::write(&exe, b"fixture executable, never run").unwrap();
let env = [("HOME", home), ("APPDATA", root.join("roaming")), ("LOCALAPPDATA", root.join("local"))]
.into_iter()
.map(|(key, value)| (key.into(), value.into_os_string()))
.collect();
Self { root, env, exe }
}
fn get(&self, key: &str) -> Option<OsString> {
self.env.get(key).cloned()
}
fn check(&self, platform: Platform, root: &Path) -> Result<PathBuf, String> {
validate_for(platform, root, |key| self.get(key), Some(&self.exe), ensure_writable)
}
fn refuse(&self, platform: Platform, root: &Path) -> String {
let probed = std::cell::Cell::new(false);
let result = validate_for(
platform,
root,
|key| self.get(key),
Some(&self.exe),
|_| {
probed.set(true);
Ok(())
},
);
assert!(!probed.get(), "a refused root must never reach the writable probe");
result.unwrap_err()
}
fn home(&self) -> PathBuf {
PathBuf::from(self.get("HOME").unwrap())
}
}
impl Drop for Fixture {
fn drop(&mut self) {
std::fs::remove_dir_all(&self.root).unwrap();
}
}
#[test]
fn portable_settings_from_another_install_are_refused_before_any_probe() {
let fixture = Fixture::new();
let stable_install = fixture.root.join("stable portable install");
let stable_data = stable_install.join("data");
std::fs::create_dir_all(&stable_data).unwrap();
std::fs::write(stable_install.join("portable.txt"), b"owned portable fixture").unwrap();
std::fs::write(stable_data.join("preferences.json"), b"stable settings must not change").unwrap();
for platform in [Platform::Windows, Platform::Linux, Platform::Mac] {
for candidate in [&stable_data, &stable_data.join("nested nightly")] {
assert!(!fixture.refuse(platform, candidate).is_empty());
assert!(!stable_data.join("nested nightly").exists());
assert_eq!(std::fs::read(stable_data.join("preferences.json")).unwrap(), b"stable settings must not change");
}
}
// A portable marker with no FilmCraft executable beside it is someone else's file.
let unrelated = fixture.root.join("user folder");
std::fs::create_dir_all(&unrelated).unwrap();
std::fs::write(unrelated.join("portable.txt"), b"another app's marker").unwrap();
assert!(fixture.check(Platform::Windows, &unrelated.join("Launcher/nightly/filmcraft")).is_ok());
// A merely similar data folder name is not the portable namespace.
assert!(fixture.check(Platform::Linux, &fixture.root.join("data-backup/nightly")).is_ok());
}
#[test]
fn a_data_folder_beside_no_portable_marker_is_not_a_portable_install() {
let mut fixture = Fixture::new();
// The Nightly Flatpak's own sandbox data root is `…/ai.storyteller.filmcraft.nightly/data`,
// and a home may hold a plain `data` folder: neither is a portable install (#5225 review).
let plain = fixture.root.join("data/filmcraft-nightly/profile");
assert_eq!(fixture.check(Platform::Linux, &plain).unwrap(), plain);
let sandbox = fixture.home().join(".var/app/ai.storyteller.filmcraft.nightly/data/filmcraft-nightly/profile");
fixture.env.insert("FLATPAK_ID".into(), filmcraft_ui_egui::os_window::NIGHTLY_PACKAGE_ID.into());
assert_eq!(fixture.check(Platform::Linux, &sandbox).unwrap(), sandbox);
// Only the Nightly Flatpak's own id may inherit a sandbox; every other one is refused.
fixture.env.insert("FLATPAK_ID".into(), "ai.storyteller.filmcraft".into());
assert!(fixture.refuse(Platform::Linux, &sandbox).contains("Flatpak"));
}
#[test]
fn linux_fences_app_xdg_subtrees_but_allows_launcher_sibling() {
let mut fixture = Fixture::new();
for key in ["XDG_DATA_HOME", "XDG_CONFIG_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME"] {
fixture.env.insert(key.into(), fixture.root.join(key).into_os_string());
}
for key in ["XDG_DATA_HOME", "XDG_CONFIG_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME"] {
let stable = PathBuf::from(fixture.get(key).unwrap()).join("filmcraft");
std::fs::create_dir_all(&stable).unwrap();
std::fs::write(stable.join("stable-sentinel"), b"stable bytes").unwrap();
for candidate in [stable.clone(), stable.join("nightly"), stable.parent().unwrap().to_path_buf()] {
assert!(fixture.refuse(Platform::Linux, &candidate).contains("overlap"));
}
assert_eq!(std::fs::read(stable.join("stable-sentinel")).unwrap(), b"stable bytes");
}
let data = PathBuf::from(fixture.get("XDG_DATA_HOME").unwrap());
let nightly = data.join("ArtCraftLauncher/nightly/profiles/filmcraft");
assert_eq!(fixture.check(Platform::Linux, &nightly).unwrap(), nightly);
assert_eq!(std::fs::read_dir(nightly).unwrap().count(), 0);
}
#[test]
fn linux_fences_the_dev_desktop_entry_the_icon_theme_and_the_stable_flatpak() {
let mut fixture = Fixture::new();
let data = fixture.root.join("xdg-data");
fixture.env.insert("XDG_DATA_HOME".into(), data.clone().into_os_string());
for stable in [data.join("applications/ai.storyteller.filmcraft.desktop"), data.join("icons/hicolor")] {
assert!(fixture.refuse(Platform::Linux, &stable.join("nightly")).contains("overlap"));
}
let flatpak = fixture.home().join(".var/app/ai.storyteller.filmcraft");
for candidate in [flatpak.clone(), flatpak.join("data/nightly")] {
assert!(fixture.refuse(Platform::Linux, &candidate).contains("overlap"));
}
assert!(!flatpak.exists());
// These are POSIX absolute paths: on a Windows host `/usr/bin/...` has no root and fails the
// absolute-path check before the fence, so the case only means anything on unix.
#[cfg(unix)]
for install in ["/usr/bin/filmcraft", "/usr/local/bin/filmcraft", "/opt/filmcraft"] {
assert!(fixture.refuse(Platform::Linux, &PathBuf::from(install).join("profile")).contains("overlap"));
}
assert!(fixture.check(Platform::Linux, &fixture.home().join(".var/app/ai.storyteller.launcher/nightly")).is_ok());
}
#[test]
fn mac_fences_only_app_library_subtrees_and_the_entire_bundle() {
let mut fixture = Fixture::new();
fixture.exe = fixture.root.join("install/FilmCraft Nightly.app/Contents/MacOS/FilmCraft");
std::fs::create_dir_all(fixture.exe.parent().unwrap()).unwrap();
std::fs::write(&fixture.exe, b"fixture executable, never run").unwrap();
let library = fixture.home().join("Library");
for suffix in [
"Application Support/FilmCraft",
"Caches/FilmCraft",
"Caches/ai.storyteller.filmcraft",
"Preferences/FilmCraft",
"Preferences/ai.storyteller.filmcraft.plist",
"Saved Application State/ai.storyteller.filmcraft.savedState",
] {
let stable = library.join(suffix);
assert!(fixture.refuse(Platform::Mac, &stable.join("nightly")).contains("overlap"));
assert!(!stable.exists());
}
let inside_resources = fixture.exe.parent().unwrap().parent().unwrap().join("Resources/profile");
assert!(fixture.refuse(Platform::Mac, &inside_resources).contains("overlap"));
assert!(!inside_resources.exists());
for bundle in [fixture.home().join("Applications/FilmCraft.app"), PathBuf::from("/Applications/FilmCraft.app")] {
assert!(!fixture.refuse(Platform::Mac, &bundle.join("profile")).is_empty());
}
let valid = library.join("Application Support/ArtCraftLauncher/nightly/profiles/filmcraft");
assert_eq!(fixture.check(Platform::Mac, &valid).unwrap(), valid);
}
#[test]
fn windows_roaming_local_and_install_fences_remain_active() {
let fixture = Fixture::new();
for key in ["APPDATA", "LOCALAPPDATA"] {
let stable = PathBuf::from(fixture.get(key).unwrap()).join("FilmCraft");
assert!(fixture.refuse(Platform::Windows, &stable.join("nightly")).contains("overlap"));
assert!(!stable.exists());
}
assert!(!fixture.refuse(Platform::Windows, &fixture.exe.parent().unwrap().join("profile")).is_empty());
assert!(fixture.check(Platform::Windows, &fixture.root.join("Launcher/profiles/filmcraft")).is_ok());
}
#[test]
fn windows_default_msi_install_folders_are_fenced() {
let mut fixture = Fixture::new();
let local = PathBuf::from(fixture.get("LOCALAPPDATA").unwrap());
let per_user = local.join("Programs").join("ArtCraft").join("FilmCraft");
assert!(fixture.refuse(Platform::Windows, &per_user.join("nightly")).contains("overlap"));
for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] {
let base = fixture.root.join(format!("machine {key}"));
fixture.env.insert(key.into(), base.clone().into_os_string());
let machine = base.join("ArtCraft").join("FilmCraft");
assert!(fixture.refuse(Platform::Windows, &machine.join("nightly")).contains("overlap"));
assert!(!machine.exists());
}
let sibling = local.join("Programs").join("ArtCraft").join("ArtCraftLauncher").join("nightly").join("filmcraft");
assert!(fixture.check(Platform::Windows, &sibling).is_ok(), "the Launcher's own Programs sibling is not FilmCraft's install");
}
#[test]
fn overlap_check_handles_ancestor_descendant_and_prefix_lookalikes() {
let fixture = Fixture::new();
let root = fixture.home().join("nightly/profiles/filmcraft");
for platform in [Platform::Windows, Platform::Linux, Platform::Mac] {
assert!(overlaps(&root, &root.join("Recovery"), platform));
assert!(overlaps(&root.join("Recovery"), &root, platform));
assert!(!overlaps(&root, &root.with_file_name("filmcraft-other"), platform));
}
}
#[cfg(unix)]
#[test]
fn recovery_and_log_aliases_cannot_redirect_to_stable_missing_or_profile_root_data() {
let fixture = Fixture::new();
let stable = fixture.home().join(".local/share/filmcraft/Recovery");
std::fs::create_dir_all(&stable).unwrap();
std::fs::write(stable.join("stable-autosave"), b"stable recovery bytes").unwrap();
for (index, (name, target)) in
[("Recovery", stable.clone()), ("Logs", stable.clone()), ("Recovery", fixture.root.join("missing target"))].into_iter().enumerate()
{
let private = fixture.root.join(format!("nightly-{index}"));
std::fs::create_dir(&private).unwrap();
std::os::unix::fs::symlink(&target, private.join(name)).unwrap();
assert!(!fixture.refuse(Platform::Linux, &private).is_empty(), "{name} must not escape the private profile");
}
let private = fixture.root.join("nightly-self");
std::fs::create_dir(&private).unwrap();
std::os::unix::fs::symlink(&private, private.join("Recovery")).unwrap();
assert!(!fixture.refuse(Platform::Linux, &private).is_empty(), "Recovery cannot treat all profile settings as recovery entries");
assert_eq!(std::fs::read(stable.join("stable-autosave")).unwrap(), b"stable recovery bytes");
}
#[cfg(unix)]
#[test]
fn recovery_and_log_aliases_cannot_alias_a_portable_install_inside_the_profile() {
let fixture = Fixture::new();
for name in ["Recovery", "Logs"] {
// A Stable portable install nested in the selected profile: the alias target resolves
// inside the profile, so only the target's own ancestors can refuse it.
let private = fixture.root.join(format!("nightly-portable-{name}"));
let portable = private.join("downloads/stable");
let stable_data = portable.join("data");
std::fs::create_dir_all(stable_data.join(name)).unwrap();
std::fs::write(portable.join("portable.txt"), b"owned portable fixture").unwrap();
std::fs::write(portable.join("filmcraft"), b"fixture executable, never run").unwrap();
std::fs::write(stable_data.join("preferences.json"), b"stable settings must not change").unwrap();
std::os::unix::fs::symlink(stable_data.join(name), private.join(name)).unwrap();
assert!(fixture.refuse(Platform::Linux, &private).contains("portable"), "{name} must not alias portable data");
assert_eq!(std::fs::read(stable_data.join("preferences.json")).unwrap(), b"stable settings must not change");
}
// Ordinary nested directories stay accepted, as before.
let private = fixture.root.join("nightly-plain");
std::fs::create_dir_all(private.join("private-recovery")).unwrap();
std::os::unix::fs::symlink(private.join("private-recovery"), private.join("Recovery")).unwrap();
assert!(fixture.check(Platform::Linux, &private).is_ok());
}
#[test]
fn the_write_probe_does_not_collide_with_another_validation() {
let fixture = Fixture::new();
let dir = fixture.root.join("probe");
std::fs::create_dir(&dir).unwrap();
// A probe another window left in this profile must not refuse this launch.
std::fs::write(dir.join("exclusive-write-probe"), b"another validation").unwrap();
ensure_writable(&dir).unwrap();
assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 1, "this validation left no probe behind");
}
#[cfg(unix)]
#[test]
fn aliases_inside_the_private_profile_keep_it_usable() {
let fixture = Fixture::new();
let private = fixture.root.join("nightly-private");
let recovery = private.join("private-recovery");
let logs = private.join("private-logs");
std::fs::create_dir_all(&recovery).unwrap();
std::fs::create_dir_all(&logs).unwrap();
std::os::unix::fs::symlink(&recovery, private.join("Recovery")).unwrap();
std::os::unix::fs::symlink(&logs, private.join("Logs")).unwrap();
assert!(fixture.check(Platform::Linux, &private).is_ok());
}
#[cfg(unix)]
#[test]
fn any_profile_entry_alias_must_stay_inside_the_profile() {
let fixture = Fixture::new();
let stable = fixture.home().join(".local/share/filmcraft/effect-presets.json");
std::fs::create_dir_all(stable.parent().unwrap()).unwrap();
std::fs::write(&stable, b"stable preset bytes").unwrap();
for name in ["preferences.json", "workspaces.json", "Media Cache"] {
let private = fixture.root.join(format!("nightly-{name}"));
std::fs::create_dir(&private).unwrap();
std::os::unix::fs::symlink(&stable, private.join(name)).unwrap();
assert!(!fixture.refuse(Platform::Linux, &private).is_empty(), "{name} must not lead outside the profile");
}
let private = fixture.root.join("nightly-inside");
std::fs::create_dir_all(private.join("Cache")).unwrap();
std::fs::write(private.join("preferences.json"), b"{}").unwrap();
std::os::unix::fs::symlink(private.join("Cache"), private.join("Media Cache")).unwrap();
assert!(fixture.check(Platform::Linux, &private).is_ok(), "regular files and links that stay inside are fine");
assert_eq!(std::fs::read(&stable).unwrap(), b"stable preset bytes");
}
#[test]
fn ambiguous_environment_and_non_native_sandbox_are_refused_before_creation() {
let mut fixture = Fixture::new();
let candidate = fixture.home().join("nightly/profiles/filmcraft");
fixture.env.insert("XDG_CACHE_HOME".into(), "relative/cache".into());
assert!(fixture.refuse(Platform::Linux, &candidate).contains("absolute"));
fixture.env.remove("XDG_CACHE_HOME");
fixture.env.insert("FILMCRAFT_DATA_DIR".into(), fixture.home().join("custom-stable").into_os_string());
assert!(fixture.refuse(Platform::Linux, &candidate).contains("FILMCRAFT_DATA_DIR"));
fixture.env.remove("FILMCRAFT_DATA_DIR");
fixture.env.insert("FLATPAK_ID".into(), "ai.storyteller.filmcraft".into());
assert!(fixture.refuse(Platform::Linux, &candidate).contains("Flatpak"));
fixture.env.insert("FLATPAK_ID".into(), "ai.storyteller.filmcraft.nightly-v1".into());
assert!(fixture.refuse(Platform::Linux, &candidate).contains("Flatpak"));
// The Nightly Flatpak itself is a native Nightly: its sandbox is already separate.
fixture.env.insert("FLATPAK_ID".into(), "ai.storyteller.filmcraft.nightly".into());
let in_the_nightly_sandbox = fixture.home().join("nightly-flatpak/profile");
assert!(fixture.check(Platform::Linux, &in_the_nightly_sandbox).is_ok(), "the Nightly Flatpak must start");
fixture.env.remove("FLATPAK_ID");
fixture.env.remove("HOME");
assert!(fixture.refuse(Platform::Linux, &candidate).contains("HOME"));
assert!(!candidate.exists());
}
#[test]
fn failed_write_probe_never_falls_back_to_stable() {
let fixture = Fixture::new();
let candidate = fixture.home().join("nightly-profile");
let refused = validate_for(Platform::Linux, &candidate, |key| fixture.get(key), Some(&fixture.exe), |_| Err(std::io::Error::other("read-only")));
assert!(refused.unwrap_err().contains("not writable"));
// The directory was created (and is empty), but nothing fell back to a stable location.
assert_eq!(std::fs::read_dir(&candidate).unwrap().count(), 0);
assert!(!fixture.home().join(".local/share/filmcraft").exists());
}
#[test]
fn created_profile_is_owner_only_on_unix() {
let fixture = Fixture::new();
let private = fixture.check(Platform::Linux, &fixture.home().join("nightly/private")).unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt as _;
assert_eq!(std::fs::metadata(&private).unwrap().permissions().mode() & 0o777, 0o700);
}
assert!(private.is_dir());
}
}
+20
View File
@@ -55,3 +55,23 @@ The web app's `apps/filmcraft-web/web/favicon.png` (128 px) comes from the same
`packaging/icons.sh` (needs `resvg`; `iconutil` on macOS for the `.icns`; the `.ico` is packed by
`cargo xtask ico`). To change the artwork, replace `filmcraft.svg` and `filmcraft-small.svg`, then run the script. Every derived file needs its `.attribution` sidecar
and a row in `ATTRIBUTION.md`.
## Nightly channel
The nightly derivatives keep the foreground artwork, alpha and macOS padding unchanged. Only the
background contribution changes, from the FilmCraft violet (`#8b5cf6`) to the deeper Nightly field
(`#3c2a63`). There is no letter badge or crescent; the app and the Launcher also say the channel in
text.
| File | What |
|---|---|
| `filmcraft-nightly.png` | 256 px native icon: the Linux tar member and the runtime icon on Windows/Linux |
| `filmcraft-nightly.ico` | Windows icon, 16–256 px, embedded in `filmcraft.exe` by `build.rs` for the nightly channel only |
| `filmcraft-nightly-1024.png` | 1024 px master for the `.icns` slots |
| `filmcraft-nightly.icns` | macOS bundle icon (`CFBundleIconFile`) of `FilmCraft Nightly.app` |
| `filmcraft-nightly-macos-512.png` | Runtime Dock icon on macOS |
Input/output hashes and the palette recipe are recorded in
[`nightly-provenance.json`](nightly-provenance.json). Stable source files are not recoloured:
`packaging/macos/nightly.sh`, `packaging/linux/nightly.sh` and `packaging/windows/nightly.ps1`
select these files, and nothing in the stable package does.
Binary file not shown.

After

Width:  |  Height:  |  Size: 257 KiB

@@ -0,0 +1,8 @@
asset: filmcraft-nightly-1024.png
title: FilmCraft Nightly app icon, 1024 px
author: Brandon Thomas (FilmCraft owner), for the FilmCraft project; Nightly derivative by the FilmCraft port of the ArtCraft Nightly kit
source: original work (drawn by the owner in ArtCraft, then vectorised)
license: MIT OR Apache-2.0
license-file: assets/app-icon/LICENSE.txt
added: 2026-11-24 by Claude (agent) for Brandon Thomas
notes: Derived from filmcraft-1024.png with the same background-only recolour.
Binary file not shown.

After

Width:  |  Height:  |  Size: 71 KiB

@@ -0,0 +1,8 @@
asset: filmcraft-nightly-macos-512.png
title: FilmCraft Nightly runtime Dock icon (512 px)
author: Brandon Thomas (FilmCraft owner), for the FilmCraft project; Nightly derivative by the FilmCraft port of the ArtCraft Nightly kit
source: original work (drawn by the owner in ArtCraft, then vectorised)
license: MIT OR Apache-2.0
license-file: assets/app-icon/LICENSE.txt
added: 2026-11-24 by Claude (agent) for Brandon Thomas
notes: Derived from filmcraft-macos-512.png with the same background-only recolour; embedded as the runtime window icon on macOS.
Binary file not shown.
@@ -0,0 +1,8 @@
asset: filmcraft-nightly.icns
title: FilmCraft Nightly app icon, macOS .icns
author: Brandon Thomas (FilmCraft owner), for the FilmCraft project; Nightly derivative by the FilmCraft port of the ArtCraft Nightly kit
source: original work (drawn by the owner in ArtCraft, then vectorised)
license: MIT OR Apache-2.0
license-file: assets/app-icon/LICENSE.txt
added: 2026-11-24 by Claude (agent) for Brandon Thomas
notes: Eleven PNG slots packed from the recoloured 1024 px master (Apple icon grid); CFBundleIconFile of FilmCraft Nightly.app.
Binary file not shown.

After

Width:  |  Height:  |  Size: 64 KiB

@@ -0,0 +1,8 @@
asset: filmcraft-nightly.ico
title: FilmCraft Nightly app icon, Windows .ico (16-256 px)
author: Brandon Thomas (FilmCraft owner), for the FilmCraft project; Nightly derivative by the FilmCraft port of the ArtCraft Nightly kit
source: original work (drawn by the owner in ArtCraft, then vectorised)
license: MIT OR Apache-2.0
license-file: assets/app-icon/LICENSE.txt
added: 2026-11-24 by Claude (agent) for Brandon Thomas
notes: Nine PNG frames packed from the recoloured native master; embedded in filmcraft.exe by build.rs for the nightly channel only.
Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

@@ -0,0 +1,8 @@
asset: filmcraft-nightly.png
title: FilmCraft Nightly app icon, native 256 px
author: Brandon Thomas (FilmCraft owner), for the FilmCraft project; Nightly derivative by the FilmCraft port of the ArtCraft Nightly kit
source: original work (drawn by the owner in ArtCraft, then vectorised)
license: MIT OR Apache-2.0
license-file: assets/app-icon/LICENSE.txt
added: 2026-11-24 by Claude (agent) for Brandon Thomas
notes: Derived from filmcraft.svg's 256 px hicolor render: only the background contribution is recoloured (stable #8b5cf6 to the Nightly deep field #3c2a63); artwork, alpha and padding unchanged.
+65
View File
@@ -0,0 +1,65 @@
{
"title": "FilmCraft nightly deep-background icons",
"author": "@skylartaylor",
"license": "MIT OR Apache-2.0",
"source_commit": null,
"inputs": [
{
"path": "assets/app-icon/hicolor/256x256/apps/ai.storyteller.filmcraft.png",
"sha256": "f07f1390c0467ab7e357f7bc102658caed40ec931e3614b255031c6adf555a2b",
"purpose": "Windows/Linux native256 master"
},
{
"path": "assets/app-icon/filmcraft-1024.png",
"sha256": "c3c301e00618c2ae391815cfaf330488d45bcfc79584b9680c434e4cfb99e13f",
"purpose": "native 1024 px master for the .icns slots (not an upscale)"
},
{
"path": "assets/app-icon/filmcraft-macos-512.png",
"sha256": "7c406fc67a309ad230b748b4e418ec973070572ec054acfd13d72b4a7e09fdb6",
"purpose": "runtime macOS Dock icon master"
}
],
"method": {
"kind": "original code-generated derivative of the project-owned icon",
"original_palette": {
"ink": "#0b0b0c",
"paper": "#efe9dc",
"background": "#8b5cf6"
},
"nightly_background": "#3c2a63",
"transform": "Fit each pixel as a mixture of the three palette colours (least squares, clamped to the simplex) and change only the background contribution. Foreground detail, alpha and Mac padding are preserved byte for byte. Frame sizes are area-averaged in premultiplied alpha from the unchanged-resolution masters and packed into ICO/ICNS. No crescent, letter or badge."
},
"outputs": {
"filmcraft-nightly.png": "23c9759a41e11f2b4e55dd51e6eee625fd066ddf245fa87e8f3a094a55aa71bf",
"filmcraft-nightly.ico": "f130e590c84d45f98346e4f5dc86ea0eaa52b97138084c296f17c9220c385621",
"filmcraft-nightly-1024.png": "8a5b6f246d45256587d8a80881add5dcae3e25aff41ca72ec6530e0e99434d1c",
"filmcraft-nightly.icns": "62bf4c076de84a1a4564647441bb4077482afa97658f66a9e2b3883936c910a8",
"filmcraft-nightly-macos-512.png": "779fd833b25b40a4a9118f071551ed040dce8c55f186b787426da1bda3f1cb8e"
},
"ico_frame_sizes": [
16,
20,
24,
32,
40,
48,
64,
128,
256
],
"icns_png_slots": {
"icp4": 16,
"icp5": 32,
"ic11": 32,
"icp6": 64,
"ic12": 64,
"ic07": 128,
"ic08": 256,
"ic13": 256,
"ic09": 512,
"ic14": 512,
"ic10": 1024
},
"validation": "PNG CRCs and dimensions, ICO directory entries and ICNS slot lengths checked; the recolour leaves every foreground pixel identical (27 995 of 65 536 pixels in the 256 px master untouched) and maps the pure background colour to the Nightly field. Explorer/Finder/iconutil qualification remains unrun."
}
+28 -2
View File
@@ -500,11 +500,37 @@ pub fn portable_data_dir(exe_dir: &Path) -> Option<PathBuf> {
exe_dir.join(PORTABLE_MARKER).is_file().then(|| exe_dir.join("data"))
}
/// The data directory. `FILMCRAFT_DATA_DIR` overrides; a portable install ([`PORTABLE_MARKER`] next
/// to the executable) uses `<exe dir>/data`; otherwise the per-user directory:
/// The private data directory a hosted (Nightly) start selected before its first write.
///
/// One place, so every root derived from the data directory follows it: preferences, workspaces,
/// presets and shortcuts, auto-save and recovery, the media cache and the model downloads, and
/// (in the desktop app) the log folder. The launcher installs it once, before anything reads a
/// data path; nothing else may replace it.
static DATA_DIR_OVERRIDE: std::sync::OnceLock<PathBuf> = std::sync::OnceLock::new();
/// Install the data directory for this process. Fails when one is already selected, so a second,
/// different root cannot silently take over the session.
pub fn set_data_dir_override(root: PathBuf) -> Result<(), String> {
if root.as_os_str().is_empty() || !root.is_absolute() {
return Err("the selected data root must be an absolute path".into());
}
DATA_DIR_OVERRIDE.set(root).map_err(|_| "the data directory was already selected".to_owned())
}
/// The data directory in use, when one is selected (see [`set_data_dir_override`]).
pub fn data_dir_override() -> Option<&'static Path> {
DATA_DIR_OVERRIDE.get().map(PathBuf::as_path)
}
/// The data directory. A selected private root ([`set_data_dir_override`]) wins; otherwise
/// `FILMCRAFT_DATA_DIR` overrides; a portable install ([`PORTABLE_MARKER`] next to the executable)
/// uses `<exe dir>/data`; otherwise the per-user directory:
/// macOS `~/Library/Application Support/FilmCraft`, Windows `%APPDATA%\FilmCraft`,
/// elsewhere `$XDG_DATA_HOME/filmcraft` or `~/.local/share/filmcraft`.
pub fn default_data_dir() -> Option<PathBuf> {
if let Some(root) = data_dir_override() {
return Some(root.to_path_buf());
}
let env = |k: &str| std::env::var_os(k).filter(|v| !v.is_empty()).map(PathBuf::from);
if let Some(d) = env("FILMCRAFT_DATA_DIR") {
return Some(d);
+39
View File
@@ -0,0 +1,39 @@
//! The private data-directory hook a hosted (Nightly) start installs.
//!
//! This lives in its own test binary: the override is process-wide and must not leak into the
//! unit tests that exercise the per-user, portable and `FILMCRAFT_DATA_DIR` resolution. It is one
//! test on purpose — the hook can be selected once per process.
use filmcraft_engine::autosave;
use std::path::PathBuf;
fn temp(tag: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("filmcraft-data-override-{tag}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
dir
}
#[test]
fn the_private_root_is_selected_once_and_wins_over_every_other_root() {
// Before a selection, the ordinary resolution applies (never an empty path).
assert!(autosave::data_dir_override().is_none());
if let Some(path) = autosave::default_data_dir() {
assert!(!path.as_os_str().is_empty());
}
// A relative or empty root selects nothing.
assert!(autosave::set_data_dir_override(PathBuf::from("relative/profile")).is_err());
assert!(autosave::set_data_dir_override(PathBuf::from("")).is_err());
assert!(autosave::data_dir_override().is_none());
let dir = temp("selected");
// Nothing else resolves first: not the environment override, not a portable marker.
std::fs::write(dir.join(autosave::PORTABLE_MARKER), "").unwrap();
autosave::set_data_dir_override(dir.join("profile")).unwrap();
assert_eq!(autosave::data_dir_override(), Some(dir.join("profile").as_path()));
assert_eq!(autosave::default_data_dir(), Some(dir.join("profile")), "the private root wins over the portable marker");
// A second selection is refused instead of silently taking over.
assert!(autosave::set_data_dir_override(dir.join("second")).is_err());
assert_eq!(autosave::default_data_dir(), Some(dir.join("profile")));
let _ = std::fs::remove_dir_all(&dir);
}
+75
View File
@@ -66,6 +66,49 @@ pub fn atomic_write(path: &Path, data: &[u8]) -> io::Result<()> {
Ok(())
}
/// Replace `path` with `data` atomically without writing through an alias at the destination.
///
/// A link, directory or other special entry at `path` is refused (and left untouched) instead of
/// being followed, so a raced or planted alias cannot redirect the bytes into another app's file.
/// The staged file is owner-only (`0600`), since this is used for private application state.
#[cfg(not(target_arch = "wasm32"))]
pub fn atomic_write_no_follow(path: &Path, data: &[u8]) -> io::Result<()> {
match fs::symlink_metadata(path) {
Ok(metadata) if metadata.file_type().is_file() && !metadata.file_type().is_symlink() => {}
Ok(_) => return Err(io::Error::other("the destination must be a regular file, not an alias or directory")),
Err(e) if e.kind() == io::ErrorKind::NotFound => {}
Err(e) => return Err(e),
}
let tmp = temp_path(path);
let r = (|| {
let mut options = OpenOptions::new();
options.write(true).create_new(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt as _;
options.mode(0o600);
}
{
let mut f = options.open(&tmp)?;
f.write_all(data)?;
f.sync_all()?;
}
// `rename` replaces whatever entry holds the name (a link itself, never its target).
fs::rename(&tmp, path)
})();
if let Err(e) = r {
let _ = fs::remove_file(&tmp);
return Err(e);
}
sync_dir(&parent_dir(path));
Ok(())
}
#[cfg(target_arch = "wasm32")]
pub fn atomic_write_no_follow(_path: &Path, _data: &[u8]) -> io::Result<()> {
Err(io::Error::new(io::ErrorKind::Unsupported, "native file replacement is unavailable in the browser"))
}
/// Publish a complete new file without replacing an occupied final path, including a symlink.
/// Bytes are staged and synced in the destination directory before no-clobber publication.
/// A write failure leaves no partial final file; temporary-file cleanup is best effort.
@@ -229,6 +272,38 @@ mod tests {
fs::remove_dir_all(&d).unwrap();
}
#[cfg(unix)]
#[test]
fn no_follow_refuses_aliases_and_never_touches_their_target() {
let d = tmpdir("no-follow");
let external = d.join("stable-state");
fs::write(&external, b"stable bytes").unwrap();
let link = d.join("nightly-session.json");
std::os::unix::fs::symlink(&external, &link).unwrap();
assert!(atomic_write_no_follow(&link, b"replacement").is_err());
assert_eq!(fs::read(&external).unwrap(), b"stable bytes");
assert!(fs::symlink_metadata(&link).unwrap().file_type().is_symlink());
// A missing destination is written (a new file), never an error; a directory is refused.
fs::create_dir(d.join("sub")).unwrap();
assert!(atomic_write_no_follow(&d.join("sub"), b"x").is_err());
fs::remove_dir_all(&d).unwrap();
}
#[cfg(unix)]
#[test]
fn no_follow_replaces_a_regular_file_owner_only() {
use std::os::unix::fs::PermissionsExt as _;
let d = tmpdir("no-follow-replace");
let p = d.join("nightly-session.json");
fs::write(&p, b"old").unwrap();
fs::set_permissions(&p, fs::Permissions::from_mode(0o644)).unwrap();
atomic_write_no_follow(&p, b"new").unwrap();
assert_eq!(fs::read(&p).unwrap(), b"new");
assert_eq!(fs::metadata(&p).unwrap().permissions().mode() & 0o777, 0o600);
assert_eq!(fs::read_dir(&d).unwrap().count(), 1, "no staging file is left behind");
fs::remove_dir_all(&d).unwrap();
}
#[test]
fn missing_directory_is_an_error() {
let d = tmpdir("missing");
+1 -1
View File
@@ -51,7 +51,7 @@ use filmcraft_project::{Project, ProjectView};
#[cfg(test)]
use serde_json::Value;
pub use atomic::{atomic_write, atomic_write_new};
pub use atomic::{atomic_write, atomic_write_new, atomic_write_no_follow};
pub use craft_fcproj_format::{FORMAT_ID, FormatError, MIGRATIONS, Migration, OLDEST_SCHEMA, SCHEMA_VERSION, detect_version, migrate_with};
+7
View File
@@ -81,6 +81,7 @@ impl FilmcraftApp {
clock_start: web_time::Instant::now(),
ui_clock: 0.0,
ui_clock_offset: None,
notice: None,
#[cfg(test)]
test_now: None,
value_press: None,
@@ -398,6 +399,9 @@ impl FilmcraftApp {
self.cancel_value_drag(&ctx);
}
self.error_window(ui.ctx());
if std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| notices::show(self, ui.ctx()))).is_err() {
log::warn!("the notice window panicked");
}
if std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| graphics_notice::show(self, ui.ctx()))).is_err() {
// a broken notice must not take the session down: drop it
self.graphics_notice = None;
@@ -517,6 +521,9 @@ impl eframe::App for FilmcraftApp {
self.session.shutdown();
// An update waiting for the exit starts its install helper now.
crate::updates_ui::exiting(self);
// The one path macOS has: its quit ends the process after this, before `run_native`
// returns, so the Nightly session record is finished here (and once, everywhere else).
crate::exit_hook::run_once();
}
/// Eframe's UI entry: begin this pass's IME reset state, suspend custom controls when no
+42
View File
@@ -0,0 +1,42 @@
//! The app's exit hook: one closure that must run on every controlled exit.
//!
//! macOS ends the process inside AppKit's terminate, after eframe's `on_exit`, so anything that has
//! to happen on a clean quit (finishing the Nightly session record) goes here rather than after
//! `run_native`, which that path never reaches. It is taken once, so a second exit does nothing.
use std::sync::Mutex;
type Hook = Box<dyn FnOnce() + Send>;
static HOOK: Mutex<Option<Hook>> = Mutex::new(None);
/// Install the hook; a later call replaces nothing (the desktop app installs it once).
pub fn set(hook: Hook) {
*HOOK.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(hook);
}
/// Run the installed hook, if any. Only the first call runs it.
pub fn run_once() {
let hook = HOOK.lock().unwrap_or_else(std::sync::PoisonError::into_inner).take();
if let Some(hook) = hook {
hook();
}
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
#[test]
fn the_exit_hook_runs_once() {
let runs = Arc::new(AtomicU64::new(0));
let counted = runs.clone();
super::set(Box::new(move || {
counted.fetch_add(1, Ordering::Relaxed);
}));
super::run_once();
super::run_once();
assert_eq!(runs.load(Ordering::Relaxed), 1, "a second exit must not run the hook again");
}
}
+6
View File
@@ -48,6 +48,7 @@ pub mod crash;
pub mod credits;
pub mod dock;
mod dock_ui;
pub mod exit_hook;
mod legacy_dropdown;
/// Thumbnail textures kept before the least recently used are freed (each is up to 320 px wide).
const MAX_THUMB_TEXTURES: usize = 512;
@@ -63,6 +64,8 @@ mod ime_reset;
pub mod links;
pub mod menus;
pub mod native_dialogs;
pub mod notices;
pub mod os_window;
pub mod panels;
pub mod perf;
#[cfg(not(target_arch = "wasm32"))]
@@ -352,6 +355,9 @@ pub struct FilmcraftApp {
/// The window runs in a fallback graphics mode (set by the desktop host): a notice with a
/// button back to the default mode (see [`graphics_notice`]).
pub graphics_notice: Option<graphics_notice::GraphicsNotice>,
/// A plain notice the host posts (Nightly session health), shown above the status bar
/// until dismissed (see [`notices`]). Not a modal: a Launcher start has nobody to dismiss one.
pub notice: Option<notices::Notice>,
/// Fault injection for robustness tests: the next UI pass panics.
#[doc(hidden)]
pub panic_next_frame: bool,
+67
View File
@@ -0,0 +1,67 @@
//! A plain in-window notice above the status bar: a title, a few lines and Close.
//!
//! The Nightly channel uses it for session health ("the previous session did not finish
//! normally"), which must not be a modal dialog: a launch from the Launcher or a test runner has
//! nobody to dismiss one. Automation id: `notice`, and `notice.close`.
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use crate::{FilmcraftApp, i18n};
/// What to show. The lines are messages the host composed (Nightly-only, so not translated).
#[derive(Clone, Debug)]
pub struct Notice {
pub title: String,
pub lines: Vec<String>,
pub closed: bool,
/// Set by `show` once the notice reached a pass the host keeps, so a host-owned record is
/// cleared only after the window really displayed it (a close before then keeps it).
pub shown: Option<Arc<AtomicBool>>,
}
impl Notice {
pub fn new(title: impl Into<String>, lines: Vec<String>) -> Self {
Self { title: title.into(), lines, closed: false, shown: None }
}
}
pub(crate) fn show(app: &mut FilmcraftApp, ctx: &egui::Context) {
let Some(mut notice) = app.notice.take() else { return };
if notice.closed {
app.notice = Some(notice);
return;
}
let mut close = false;
let drawn = egui::Window::new("notice")
.id(egui::Id::unique("notice"))
.title_bar(false)
.collapsible(false)
.resizable(false)
.anchor(egui::Align2::RIGHT_BOTTOM, [-12.0, -32.0])
.show(ctx, |ui| {
ui.set_max_width(380.0);
ui.label(egui::RichText::new(&notice.title).strong());
ui.add_space(4.0);
for line in &notice.lines {
ui.label(line);
}
ui.add_space(6.0);
let label = i18n::t("Close");
let c = ui.button(label);
app.auto.add_response("notice.close", &c, label);
close = c.clicked();
});
if let Some(drawn) = drawn {
app.auto.add("notice", drawn.response.rect, &notice.title);
// Only a pass the host keeps counts: an early return before this pass (fonts not ready) or
// a discarded pass must not consume the record the notice reports.
if let Some(shown) = &notice.shown
&& !ctx.will_discard()
{
shown.store(true, Ordering::Relaxed);
}
}
notice.closed |= close;
app.notice = Some(notice);
}
+111
View File
@@ -0,0 +1,111 @@
//! The app id every FilmCraft OS window carries — the main window, and any extra window built
//! with [`builder`] — plus the immutable launch identity the desktop selects before any UI
//! service exists. Without an app id Wayland compositors' window rules and docks have nothing to
//! match, and a Nightly window would be indistinguishable from stable.
use std::sync::OnceLock;
/// Matches the `.desktop` file and hicolor icon name, so Wayland docks pick up the icon.
pub const APP_ID: &str = "ai.storyteller.filmcraft";
/// The nightly channel's window/Wayland app id. The package, bundle and Launcher identity is
/// [`NIGHTLY_PACKAGE_ID`] instead: two different strings, both are needed.
pub const NIGHTLY_V1_APP_ID: &str = "ai.storyteller.filmcraft.nightly-v1";
/// The Nightly package, bundle and Launcher id (also `FLATPAK_ID` inside its own sandbox).
pub const NIGHTLY_PACKAGE_ID: &str = "ai.storyteller.filmcraft.nightly";
/// Immutable startup identity. The desktop selects it before any UI/runtime service is created.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LaunchIdentity {
Stable,
NightlyV1,
}
static IDENTITY: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);
static DISPLAY_VERSION: OnceLock<String> = OnceLock::new();
pub fn select_identity(identity: LaunchIdentity) -> Result<(), String> {
let value = match identity {
LaunchIdentity::Stable => 1,
LaunchIdentity::NightlyV1 => 2,
};
IDENTITY
.compare_exchange(0, value, std::sync::atomic::Ordering::AcqRel, std::sync::atomic::Ordering::Acquire)
.map(|_| ())
.map_err(|_| "the window launch identity was already selected".into())
}
pub fn identity() -> LaunchIdentity {
if IDENTITY.load(std::sync::atomic::Ordering::Acquire) == 2 { LaunchIdentity::NightlyV1 } else { LaunchIdentity::Stable }
}
pub const fn id_for(identity: LaunchIdentity) -> &'static str {
match identity {
LaunchIdentity::Stable => APP_ID,
LaunchIdentity::NightlyV1 => NIGHTLY_V1_APP_ID,
}
}
pub fn app_id() -> &'static str {
id_for(identity())
}
pub const fn name_for(identity: LaunchIdentity) -> &'static str {
match identity {
LaunchIdentity::Stable => "FilmCraft",
LaunchIdentity::NightlyV1 => "FilmCraft Nightly",
}
}
pub fn name() -> &'static str {
name_for(identity())
}
/// The version the UI shows (About): the exact compiled identity, announced by the desktop app.
/// Without one (unit tests, the web build) it is this crate's version.
pub fn set_display_version(version: String) -> Result<(), String> {
DISPLAY_VERSION.set(version).map_err(|_| "the display version was already selected".into())
}
pub fn display_version() -> &'static str {
DISPLAY_VERSION.get().map_or(env!("CARGO_PKG_VERSION"), String::as_str)
}
/// A builder for an extra OS window, carrying the selected app id.
pub fn builder() -> egui::ViewportBuilder {
egui::ViewportBuilder::default().with_app_id(app_id())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn nightly_identity_is_distinct_from_stable() {
assert_eq!(id_for(LaunchIdentity::Stable), APP_ID);
assert_ne!(id_for(LaunchIdentity::NightlyV1), APP_ID);
assert_eq!(id_for(LaunchIdentity::NightlyV1), NIGHTLY_V1_APP_ID);
assert_ne!(name_for(LaunchIdentity::NightlyV1), name_for(LaunchIdentity::Stable));
}
#[test]
fn the_package_identity_and_the_window_identity_are_two_different_strings() {
// The bundle/package id the Launcher and macOS plist use, and the window/AUMID one.
assert_eq!("ai.storyteller.filmcraft.nightly-v1", NIGHTLY_V1_APP_ID);
assert_eq!("ai.storyteller.filmcraft.nightly", NIGHTLY_PACKAGE_ID);
assert_ne!(NIGHTLY_PACKAGE_ID, NIGHTLY_V1_APP_ID);
assert_ne!(NIGHTLY_PACKAGE_ID, APP_ID);
}
#[test]
fn extra_windows_carry_the_selected_app_id() {
assert_eq!(builder().app_id.as_deref(), Some(app_id()));
}
#[test]
fn the_about_version_falls_back_to_the_crate_version_until_selected() {
// Selection happens once per process, so this test only reads the default.
assert!(display_version() == env!("CARGO_PKG_VERSION") || display_version().contains("nightly"));
}
}
+2 -2
View File
@@ -475,8 +475,8 @@ fn about_tab(app: &mut FilmcraftApp, ui: &mut egui::Ui) {
let (r, _) = ui.allocate_exact_size(egui::vec2(ui.available_width(), 30.0), egui::Sense::hover());
crate::brand::paint_wordmark(ui, egui::pos2(r.min.x, r.center().y), 20.0, app.ui.dark);
ui.add_space(6.0);
ui.heading("FilmCraft");
ui.label(tlf!("Version {version}", version = env!("CARGO_PKG_VERSION")));
ui.heading(crate::os_window::name());
ui.label(tlf!("Version {version}", version = crate::os_window::display_version()));
ui.label(tl!("A clean-room, pure-Rust non-linear video editor. Part of the ArtCraft family."));
ui.add_space(10.0);
let mut link = |ui: &mut egui::Ui, id: &str, icon: Icon, label: &str, url: &str, primary: bool| {
+35
View File
@@ -20,6 +20,9 @@ pub(crate) struct Runtime {
/// The desktop app turns the check at start on; tests and the web build leave it off.
#[cfg(not(target_arch = "wasm32"))]
startup_check: bool,
/// The Nightly channel is updated by ArtCraft Launcher, never by this app's updater.
#[cfg(not(target_arch = "wasm32"))]
disabled: bool,
#[cfg(not(target_arch = "wasm32"))]
check_requested: bool,
/// The context of the last frame, to wake the UI when a check is queued from a menu callback.
@@ -38,6 +41,8 @@ impl Default for Runtime {
#[cfg(not(target_arch = "wasm32"))]
startup_check: false,
#[cfg(not(target_arch = "wasm32"))]
disabled: false,
#[cfg(not(target_arch = "wasm32"))]
check_requested: false,
#[cfg(not(target_arch = "wasm32"))]
repaint: None,
@@ -52,11 +57,22 @@ impl FilmcraftApp {
pub fn set_startup_update_check(&mut self, on: bool) {
self.updates_rt.startup_check = on;
}
/// Turn the updater off: a Nightly build is updated by ArtCraft Launcher, and offering stable
/// releases here would replace it with a different channel.
#[cfg(not(target_arch = "wasm32"))]
pub fn disable_updates(&mut self) {
self.updates_rt.disabled = true;
self.updates_rt.startup_check = false;
}
}
pub(crate) fn check(app: &mut FilmcraftApp) -> Result<Value, String> {
#[cfg(not(target_arch = "wasm32"))]
{
if app.updates_rt.disabled {
return Err("Updates are managed by ArtCraft Launcher.".into());
}
app.updates_rt.check_requested = true;
app.updates_rt.manual_window_open = true;
if let Some(ctx) = &app.updates_rt.repaint {
@@ -76,6 +92,9 @@ pub(crate) fn tick(app: &mut FilmcraftApp, ctx: &egui::Context) {
{
let rt = &mut app.updates_rt;
rt.repaint = Some(ctx.clone());
if rt.disabled {
return;
}
if std::mem::take(&mut rt.check_requested) {
rt.updater.check_now();
} else if rt.startup_check {
@@ -91,6 +110,9 @@ pub(crate) fn show(app: &mut FilmcraftApp, ui: &mut egui::Ui) {
let ctx = ui.ctx().clone();
#[cfg(not(target_arch = "wasm32"))]
{
if app.updates_rt.disabled {
return;
}
let ctx = &ctx;
// The restart helper is scheduled before the app closes, so no update starts over unsaved work.
let clean = !app.session.is_dirty();
@@ -328,3 +350,16 @@ mod tests {
assert!(!result_window_open(false, &Status::Idle, true), "a queued check does not open it");
}
}
#[cfg(all(test, not(target_arch = "wasm32")))]
mod nightly_tests {
/// A Nightly build is updated by ArtCraft Launcher: the stable updater must not run, and a
/// manual check says so instead of offering a release from another channel.
#[test]
fn a_nightly_app_never_asks_the_stable_updater() {
let mut app = crate::FilmcraftApp::new(filmcraft_engine::Session::default());
app.set_startup_update_check(true);
app.disable_updates();
assert!(super::check(&mut app).unwrap_err().contains("ArtCraft Launcher"));
}
}
+1
View File
@@ -51,6 +51,7 @@ mod native_windows_ui;
mod nest_editing_ui;
mod nest_rendering_ui;
mod nested_ui;
mod notice_ui;
mod open_project_prompt_ui;
mod panels_ui;
mod par_ui;
+100
View File
@@ -0,0 +1,100 @@
//! The Nightly session-health notice: posted inside the window (never a modal), listed for
//! automation, and dismissed by Close.
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{Sender, channel};
use egui_kittest::Harness;
use filmcraft_engine::Session;
use filmcraft_ui_egui::FilmcraftApp;
use filmcraft_ui_egui::control::ControlRequest;
use filmcraft_ui_egui::notices::Notice;
use serde_json::{Value, json};
struct Driver {
harness: Harness<'static, FilmcraftApp>,
tx: Sender<ControlRequest>,
}
impl Driver {
fn new(notice: Option<Notice>) -> Self {
let (tx, rx) = channel();
let mut app = FilmcraftApp::new(Session::default()).with_control(rx);
app.notice = notice;
// The window hosts the craft runtime now: a harness that drives frames without installing it
// headless panics ("the runtime plugin's hooks did not run for the previous pass").
let harness = Harness::builder().with_size(egui::vec2(1600.0, 980.0)).with_max_steps(10_000).build_eframe(move |cc| {
filmcraft_ui_egui::framework::install_headless(&cc.egui_ctx);
app
});
let mut d = Driver { harness, tx };
d.frames(4);
d
}
fn frames(&mut self, n: usize) {
for _ in 0..n {
let ctx = self.harness.ctx.clone();
let mut raw = std::mem::take(self.harness.input_mut());
eframe::App::raw_input_hook(self.harness.state_mut(), &ctx, &mut raw);
*self.harness.input_mut() = raw;
self.harness.step();
}
}
fn call(&mut self, method: &str, params: Value) -> Value {
let (req, reply) = ControlRequest::new(method, params.clone());
self.tx.send(req).unwrap();
for _ in 0..600 {
self.frames(1);
if let Ok(v) = reply.try_recv() {
return v;
}
}
panic!("no reply to {method} {params}");
}
fn ids(&mut self) -> Vec<String> {
let v = self.call("ui.elements", json!({"prefix": "notice"}));
assert_eq!(v["ok"], json!(true), "{v}");
v["result"].as_array().unwrap().iter().map(|e| e["id"].as_str().unwrap().to_string()).collect()
}
fn click(&mut self, id: &str) {
let v = self.call("ui.click", json!({"id": id}));
assert_eq!(v["ok"], json!(true), "{id}: {v}");
self.frames(3);
}
}
#[test]
fn the_notice_acknowledges_its_record_only_once_it_is_drawn() {
// The Nightly session-health record is cleared by this flag, so a window that closes before
// the notice reached a kept pass keeps the record for the next launch.
let drawn = Arc::new(AtomicBool::new(false));
let mut notice = Notice::new("FilmCraft Nightly", vec!["The previous FilmCraft Nightly session did not finish normally.".into()]);
notice.shown = Some(drawn.clone());
let mut d = Driver::new(Some(notice));
assert!(d.ids().iter().any(|id| id == "notice"));
assert!(drawn.load(Ordering::Relaxed), "a drawn notice acknowledges the interruption it reports");
let dismissed = Arc::new(AtomicBool::new(false));
let mut notice = Notice::new("FilmCraft Nightly", vec!["The previous FilmCraft Nightly session did not finish normally.".into()]);
notice.closed = true;
notice.shown = Some(dismissed.clone());
let _d = Driver::new(Some(notice));
assert!(!dismissed.load(Ordering::Relaxed), "a dismissed notice reports nothing and clears nothing");
}
#[test]
fn no_notice_without_a_session_health_message() {
let mut d = Driver::new(None);
assert!(d.ids().is_empty());
}
#[test]
fn the_notice_is_shown_and_close_dismisses_it() {
let mut d = Driver::new(Some(Notice::new("FilmCraft Nightly", vec!["The previous FilmCraft Nightly session did not finish normally.".into()])));
let ids = d.ids();
assert!(ids.iter().any(|id| id == "notice"), "{ids:?}");
assert!(ids.iter().any(|id| id == "notice.close"), "{ids:?}");
d.click("notice.close");
assert!(d.ids().is_empty(), "Close dismisses the notice for this session");
}
+257
View File
@@ -0,0 +1,257 @@
# Windows, Linux and macOS release-ref nightly: source preparation
This is the FilmCraft port of the ArtCraft Nightly kit (PhotoCraft #16335, #16559, #16459), landed on
top of the Linux packaging work (`storytold/filmcraft#5225`). The producer and signer are enabled for
supervised manual dispatch only: there is no schedule, `.github/nightly-signing-policy.json` is
installed with the five release managers as its only manual actors, and no run has signed or
published anything yet.
`packaging/nightly-tests.py` and `docs/nightly-signing-policy.example.json` are the source contract;
`packaging/nightly-release-tests.py` enforces it (one shared pin, one producer, one signer, exact
platform list, trust anchors, no cache/secrets in the callers' closure).
**Manually enabled, not qualified.** A run needs a release manager's dispatch: both callers keep
their exact context guards, the policy grants no automatic signer, and there is no schedule or
platform secret grant. Nothing has produced a qualified nightly, so the pipeline is still
unproven end to end. The unsigned reusable caller's maximum OIDC/attestation
permissions are for its isolated attester; its compiler narrows to contents and Actions read
only, with no OIDC, attestation write, release environment or platform signing secrets.
Shared tooling is pinned to `605d58766e8f536564da8fc81d3676ac86816dea`, the craft-common-actions
main commit that merged [#339](https://github.com/storytold/craft-common-actions/pull/339) (bounded
lineage compares and an issue reread at the end of candidate admission) on top of
[#342](https://github.com/storytold/craft-common-actions/pull/342) (policy v3, the `platforms` input
and the Linux and macOS legs). Both callers name it in `uses` and `tooling-revision`, and the
installed policy names it as both tooling revisions; the earlier pin, `077d4657` (#330), is
Windows-only. A pin is reviewed source availability, not provider, queue, native signing or crypto
qualification.
Existing stable workflows are unchanged.
**Platform rows.** The producer caller lists
`platforms: '["windows-x86_64","linux-x86_64","macos-aarch64"]'` on its single job: one producer run
builds every listed platform for one all-or-nothing release (one failed or
skipped platform stops that night's release, Windows included), and the release-ref signer admits
platforms only from the protected policy, so there is no separate Linux or macOS caller job and
the signer caller has no platform input. The shared Linux leg runs the app's
`packaging/linux/nightly.sh --arch x86_64` (GUI-only `filmcraft-<version>-linux-x86_64-nightly.tar.gz`)
and signs with the stable OpenPGP key; the macOS leg runs `packaging/macos/nightly.sh --arch aarch64`
unsigned on main, then `packaging/macos/nightly-sign.sh` (stable `import-cert.sh`, Developer ID,
hardened runtime, notarization and stapling) and `nightly-verify.sh` from the protected release
checkout. Those scripts are owned by FilmCraft's Linux and macOS packaging authors, not by these
callers. Neither leg has run on hosted runners: launch, profile isolation beside stable and the
Launcher install still need Linux and macOS desktop QA.
This is not a hosted no-key test, a native signing result or a working nightly feed.
## Ownership and interface
- `.github/workflows/nightly.yml`: manual-dispatch producer on default main, named
`FilmCraft unsigned nightly`, restricted to the five release managers; no signing secrets may be
passed or inherited.
- `.github/workflows/nightly-dispatch.yml`: completion transport. It accepts
only a successful same-repository/main first producer attempt, then sends only
`producer_run_id` and `producer_run_attempt` to the fixed `nightly-sign.yml` on `release`.
No checkout, artifact parsing, application code or release environment is used here.
Its filters are not authorization: a writer can edit main transport.
- `.github/nightly-linux-signing-key.asc`: the stable Linux release public key, byte for byte the
`release-signing-key.asc` published with the newest stable FilmCraft release (one ed25519 primary key,
`2B76741B414AAD6CD33E631213A005C0B9D7C3ED`, with one signing subkey). The shared Linux verifier
reads it from the protected release checkout, never from a release asset. Public material only.
- `.github/workflows/nightly-sign.yml`: manual-dispatch signer on `release`, intended to be identical
on main/release after reviewed promotion. It rejects wrong repository/event/actual branch,
including same-name tags. Its constant whole-run concurrency is distinct from stable,
cancellation is off and `queue: max` must be hosted-qualified. No credentials can be reached
by this preparation.
- Shared reusable entrypoints are `nightly-unsigned.yml` and `nightly-release.yml` in
`storytold/craft-common-actions`. Both must resolve to a **real reviewed public immutable
commit**; the defining workflow SHA and tooling input must match. The release callee's
request inputs are consistently `producer_run_id` and `producer_run_attempt`, while
`tooling-revision` keeps its existing hyphen spelling. Confirm the final landed interface
before any future pin update or activation. Unsigned inputs are `tooling-revision`, `app-name`,
`manual-actors` (default `[]`), `craft-fonts-ref` and `platforms`; FilmCraft's title is reviewed source,
not an `app-title` input. The reusable caller grants maximum permissions only; each
callee job must narrow them independently.
Shared code owns attestation validation, candidate quality, archive bounds, native signing,
role-separated receipts and publication. App code must not duplicate those parsers.
- The existing `packaging/windows/sign.ps1 -Required` is the app-owned Windows adapter.
Invoke it only from the immutable **release execution SHA** checkout, never the producer's
main source or extracted archive. Shared Windows tooling must own the flat GUI-only ZIP,
PE/inventory checks and post-sign verification; do not execute `nightly.ps1`, `package.ps1`
or the payload beside keys. No new wrapper is needed. `sign.ps1` is unchanged here.
## Missing real configuration (all activation blockers)
`.github/nightly-signing-policy.json` is deliberately absent: there is no authorizing root,
empty debt set or invented workflow ID, and installing it is a separate activation step. The adjacent
[`nightly-signing-policy.example.json`](nightly-signing-policy.example.json) is intentionally
invalid (`null` unresolved values), not installable configuration. Its `platforms` rows do carry
the reviewed public values: each fixed `nightly-unsigned-<platform>` artifact kind and stable's
identities, read from the newest stable FilmCraft release (Windows Authenticode leaf subject in Windows form,
the Linux release key's primary fingerprint, and the Developer ID team `DJ6XS33FX8` from the
macOS CLI's code signature). Install only independently
read, reviewed real values under explicit schema `craft-nightly-release-policy/v3` (v2 top-level fields
without `platform`, `unsigned_artifact_name` and `windows_publisher_subject`, plus a `platforms` map):
| Field | Required source of authority |
|---|---|
| `repository`, `repository_id` | Exact FilmCraft repository and authenticated numeric ID |
| `producer_workflow_id`, `producer_workflow_path` | Real default-branch registration ID and `.github/workflows/nightly.yml` |
| `producer_tooling_revision`, `producer_workflow_ref` | Approved shared unsigned producer/attester commit and exact reusable path at that commit |
| `signer_workflow_path`, `signer_tooling_revision` | `.github/workflows/nightly-sign.yml` and reviewed public shared signer commit |
| `release_branch`, `platforms` keys | `release`; exactly the producer's `platforms` list and the targets admitted in the shared registry (`windows-x86_64`, `linux-x86_64`, `macos-aarch64`) |
| `manual_actors` | Empty by default; reviewed manual producer/signer and rerun authority only |
| `automatic_signer_actors` | Empty by default; separate reviewed automatic-only authority for signer attempt 1 after authenticating a scheduled producer attempt 1; no manual producer or rerun grant |
| `max_age_seconds`, `max_artifact_bytes`, `platforms.<platform>.unsigned_artifact_name` | Reviewed bounded age/size and each platform's fixed unsigned artifact kind/prefix; actual upload/discovery name is that prefix + `-` + authenticated producer run ID + `-` + authenticated producer attempt, never a caller pattern or substitution |
| `candidate_policy` | Full reviewed `craft-nightly-candidate-policy/v3` with real required workflow/job/check/app IDs, Sonar organization/project/issue types/conditions and exact approved debt fingerprints; provider configuration is trusted as resolved, not a pinned scan inventory |
| `platforms.linux-x86_64.trust.fingerprint` | Full primary fingerprint of the stable Linux release key, independently reviewed; the release checkout must also hold exactly that one public key at `.github/nightly-linux-signing-key.asc`, and the existing `LINUX_SIGNING_KEY` must be in the `release` environment only |
| `platforms.macos-aarch64.trust.apple_team_id` | Stable's ten-character Developer ID team `DJ6XS33FX8`, read from the stable macOS code signature, whose leaf is `CN=Developer ID Application: Learning Machines LLC (DJ6XS33FX8), OU=DJ6XS33FX8, O=Learning Machines LLC`. The Windows certificate names a different entity, `Learning Machines Inc`; only the team ID `DJ6XS33FX8` is enforced on macOS. Never a repository variable. The six stable `APPLE_*`/`KEYCHAIN_PASSWORD` names must be in the `release` environment only |
| `platforms.windows-x86_64.trust.publisher_subject` | Exact independently reviewed protected policy string used by both signer and fresh credentialless Windows publisher; nonempty, at most 2048 characters, no CR/LF/NUL; verified native subject must match exactly, never an artifact/caller input |
Live admission requires explicit policy v3 once the shared parser lands it; v2 is single-platform
Windows only and is not silently migrated. Historical v1 retains its exact old fields and
broad manual-list semantics, and is not silently migrated or accepted for live admission. The
v2 actor lists are separate, bounded and case-normalized; overlaps refuse. An automatic-only
actor may authorize **only signer attempt 1**, after the validator authenticates a **scheduled
producer attempt 1**. That list grants no manual producer, producer rerun or signer rerun
authority. Those requests require the independently reviewed `manual_actors` list.
Before future automatic dispatch is activated, its identity needs explicit review for
`automatic_signer_actors`; no bot is implicitly trusted or installed here. Never union that
list into `manual_actors` or the unsigned caller's `manual-actors` input. Both example lists
and the caller input remain empty; this preparation does not populate or authorize policy.
### Post-publication recovery limitation
The pinned shared revision now prevents a narrowly scoped failure, not general recovery:
**only after the publisher returns through successful final verification** may an ownership
receipt I/O failure be reported without failing that already-verified publication. A public
PATCH callback alone is insufficient. Pending bytes become canonical `ownership.json` only
after successful write, flush/fsync and close; incomplete receipts supply no canonical
ownership or pruning authority. The optional ownership upload uses only that canonical
path, warns if missing and cannot by itself fail the publication job.
This does not repair historical failed attempts or reconcile runner loss, timeouts, uncertain
publication responses, or failed/incomplete final verification. Those cases remain stopped
for release-manager reviewed manual handling; re-running does not repair an old recorded
failure. No general authenticated reconciliation protocol, retry or public-state editing/
deletion authority is introduced. Manual handling of these remaining cases still needs
preactivation review and qualification. These are source behaviors, not hosted/crypto proof.
Confirm the shared parser's final exact fields; unknown/missing/null values must refuse.
Do not derive policy, code/tool paths, trust anchors or ignored debt from a candidate archive.
Independently pinned signing tools are also unresolved; configure them, and the trust values
above, only through the reviewed shared/release contract, never a guessed app value or an
override from main. The unchanged stable `release.yml` forwards Windows/Azure
secret names from caller scope, while the nightly signer forwards none. Before activation,
verify the existing `release` environment holds the required names and that repository or
organization scopes do not expose signing copies to main. Environment-only missing values
must fail closed; repository/org-only values or same-name scope collisions are blockers,
not permission to copy keys or change settings. No secret names/scopes or protection settings
were audited by this source change; no secret values were read.
## Bounded integration and acceptance
1. The callers reference the same reviewed public preview commit in `uses` and
`tooling-revision`. Activation is manual dispatch by a release manager only: never add a
schedule, an automatic signer or another actor without its own review. Future shared pin
updates require review of the exact public immutable source and interface. Do not claim
untested source as a working pipeline.
Do not temporarily call old same-run signing or use mutable `@main`/`@release` tooling.
Keep compiler permissions contents and Actions read only, with no OIDC, attestation write,
release environment or platform secrets. Only the isolated unsigned attester receives
its required Actions-read, attestation-write and OIDC, never platform keys. Re-run the
no-cache static check over **all** trusted jobs/callees, including setup-action cache options.
2. Register on main through normal review. Promote identical signer/policy/adapter contents
only during an already-intended stable sync, following [the release trust-closure review](releasing.md#cutting-a-release).
A release push can build/update a stable draft or refuse an already-published version;
this source change authorizes no push, skip-CI workaround or dummy version bump.
3. Hosted **no-platform-key**, separately authorized tests must establish actual release
dispatch context/permissions, queue retention/displacement, re-runs/current actor denial,
exact attestation `invocationId` run/attempt and immutable reusable identity. Test wrong
repository/ref/tag/event/actor, substituted run/attempt/artifact/transport ZIP/inner package,
missing/expired artifacts and all digest/claim mismatches. Transport archive SHA, unsigned
package SHA and final signed SHA are different roles, never interchangeable.
4. Candidate-v3 quality must prove exact C required latest runs/jobs and take the Sonar
snapshot first. Require coherent latest main-C revision/SCM at collection boundaries,
complete paginated branch issues scoped to reviewed issue types with count/end reread,
and the same analysis's gate and exact reviewed debt fingerprints. Profiles, rules,
scanner configuration and warnings are **trusted as resolved by the provider**, like
main CI; configuration changes can hide issues. This is not immutable scan-inventory
proof, full scan-scope enforcement or a warning-free-scan guarantee. The example has no
`sonar.scope` field; its exact Sonar fields match the shared candidate-v3 parser.
Debt may shrink only with analysis-driven FIXED lifecycle proof **and** independently
qualified exact-C source-hash absence; missing/manual/REMOVED/unchanged-source proofs
refuse. Cloud source-hash normalization remains unqualified, so a vanished approved debt
item currently **refuses**, rather than counting absence as a fix. Qualify the real hash
semantics and lifecycle APIs without new credentials before claiming that path works.
Current main M may advance past C only by verified ancestry; C must strictly advance the
previous authenticated publication P. Retained-snapshot revalidation currently refuses
once the latest Sonar analysis advances past C: no qualified historical issue/proof API
resolves that race. Do not promise publication survives a newer analysis. Repeat
admission/pause/quality/ancestry/newest-run checks before keys and publication.
5. Separately authorize first native Windows signing/publication, signature/publisher/timestamp
checks, Launcher install beside stable, launch/profile/version independence, rollback and
uninstall preservation, and corrupt/unsigned/wrong-publisher rejection. No Linux/macOS
coverage follows from Windows. Keep production/native/publication/prune switches off until
their own acceptance. Nightly assets remain prerelease, `make_latest:false`, with separate
nightly tags/reservations. Historical failures, uncertain/failed final verification and
runner loss retain the [manual-handling limits described above](#post-publication-recovery-limitation);
receipt-failure prevention does not supply general reconciliation.
Routine updates ride real stable windows, never automatic main-to-release copying. Pause or
cancel via existing nightly workflow controls without pushing release; urgent repairs need
one explicitly authorized bounded maintenance push. See the shared-identity incident note in
[the release guide](releasing.md#release-ref-nightly-preparation). No daily witness renewal or
per-run human approval is introduced by candidate-v3; provider gaps remain blockers.
## Linux Nightly launchers (on top of the Linux packaging PR)
A Nightly build refuses to start without its private profile, and refuses the stable
`FILMCRAFT_DATA_DIR` override, so every Linux format starts the GUI through the Launcher's literal
protocol `--launch-profile nightly-v1 --profile-root <dir> -- <files>`. The profile is
`${XDG_DATA_HOME:-$HOME/.local/share}/filmcraft-nightly/profile` (outside stable's folders and
outside the installed copy, which the app's own fence would reject). A first-argument `--version`
or `-V`, and an already-named protocol, pass through untouched, so version queries still answer.
| Format | Shape |
|---|---|
| deb/rpm | GUI in `/usr/lib/filmcraft-nightly/filmcraft`, launcher at `/usr/bin/filmcraft-nightly`, CLI at `/usr/bin/filmcraft-nightly-cli` |
| AppImage | `AppRun` is a script (never a symlink): desktop integration plus the profile launch; `package.sh` switches its `DESK_ID` and `CHANNEL` for Nightly |
| Arch handoff | `bin/filmcraft-nightly` launcher, GUI in `bin/.filmcraft-nightly/` |
| Flatpak | GUI in `/app/libexec/filmcraft`, launcher in `/app/bin/filmcraft`; the Nightly bundle id is the only `FLATPAK_ID` the fence accepts |
| plain tar | `filmcraft` launcher beside `filmcraft-bin`, and `install.sh` installs both |
Nightly packages claim no MIME associations (desktop and metainfo), ship the channel icon, and keep
the `filmcraft/neural-voices` feature the official package builds with.
`packaging/linux/nightly-launch-test.sh`, `apprun-test.sh` and `nightly-arch-tar-test.sh` check the
launchers with argv recorders (packaging lint runs them).
## Local regression checks
`python3 packaging/nightly-release-tests.py` executes the **actual inline dispatcher** with
synthetic, locally generated event fixtures and a mocked HTTPS opener. It verifies fixed
routing, refusal before contact and no retry; it does not contact GitHub or prove admission,
cryptography, native signing, hosted concurrency, or the shared candidate-v3 implementation.
It checks that the policy example's platforms equal the producer list, that each row names its
fixed artifact kind and stable identity, that `.github/nightly-linux-signing-key.asc` holds exactly
one public primary key whose fingerprint is the policy's, and that both callers share one pin in
`uses` and `tooling-revision`.
It also checks the installed policy against the callers (paths and tooling revisions, the
release managers as the only manual actors in both places, platforms, candidate workflows and the
Sonar identity). The same suite covers all three callers for the no-cache/no-platform-secret
boundary, holds each enabled job to its exact context guard, and refuses any registered nightly
schedule. It also rejects changed root serialization: the fixed FilmCraft nightly group and
`cancel-in-progress: false` must remain literal, and a `queue` entry, when present, must be `max`.
Mutation regressions reject invalid queue values, cancellation and request-dependent groups. Packaging lint runs this suite in its
independent contents-read-only `nightly-source-contract` job, including config-only changes;
it does not rely on the shared Bash packaging hook to run the guard.
The existing `.github/actionlint.yaml` suppresses only actionlint 1.7.12's anchored exact
unsupported-queue message for `.github/workflows/nightly-sign.yml`. This operator-requested
compatibility exception is not a blanket syntax waiver: other files/messages still fail,
and the mandatory source guard supplies the missing queue-value/serialization checks.
No tool fork or shared lint change is needed. This same-PR nonprivileged CI hook is the
narrow correction requested for the nightly source; stable/release execution is unchanged.
Run through the normal task allocator; report actionlint/PowerShell/native/hosted checks
separately and never treat a missing runtime as a pass.
+54
View File
@@ -0,0 +1,54 @@
{
"schema": "craft-nightly-release-policy/v3",
"repository": "storytold/filmcraft",
"repository_id": null,
"producer_workflow_id": null,
"producer_workflow_path": ".github/workflows/nightly.yml",
"producer_tooling_revision": null,
"producer_workflow_ref": null,
"signer_workflow_path": ".github/workflows/nightly-sign.yml",
"signer_tooling_revision": null,
"release_branch": "release",
"manual_actors": [],
"max_age_seconds": null,
"candidate_policy": {
"schema": "craft-nightly-candidate-policy/v3",
"epoch": null,
"repository": "storytold/filmcraft",
"branch": "main",
"required_workflows": null,
"sonar": {
"organization": null,
"project": null,
"app_id": null,
"check_name": null,
"details_url": null,
"issue_types": null,
"accepted_conditions": null,
"required_conditions": null,
"debt": null
}
},
"max_artifact_bytes": null,
"automatic_signer_actors": [],
"platforms": {
"windows-x86_64": {
"unsigned_artifact_name": "nightly-unsigned-windows-x86_64",
"trust": {
"publisher_subject": "CN=Learning Machines Inc, O=Learning Machines Inc, L=Atlanta, S=Georgia, C=US"
}
},
"linux-x86_64": {
"unsigned_artifact_name": "nightly-unsigned-linux-x86_64",
"trust": {
"fingerprint": "2B76741B414AAD6CD33E631213A005C0B9D7C3ED"
}
},
"macos-aarch64": {
"unsigned_artifact_name": "nightly-unsigned-macos-aarch64",
"trust": {
"apple_team_id": "DJ6XS33FX8"
}
}
}
}
+34 -1
View File
@@ -20,7 +20,22 @@ User-facing names say **FilmCraft**. Files, binaries and ids stay lowercase
Commit the change (`Cargo.toml` + `Cargo.lock`) through the normal review flow, as a
`Release: FilmCraft v0.3.0` commit whose message says what changed for users.
2. **Merge `main` into `release`** (or fast-forward it) and push. The workflow starts by itself.
2. **Review the release trust boundary, then merge `main` into `release`** (or fast-forward it)
and push. The stable workflow starts by itself. Compare the proposed tree with the
**previous trusted release**, not a manifest from main. Review and preserve:
- `.github/workflows/nightly-sign.yml`, `.github/nightly-signing-policy.json`, and
every transitive reusable workflow/action pin;
- `packaging/windows/sign.ps1`, its signing configuration, tool installers and imports;
- the macOS nightly signing scripts (`packaging/macos/nightly-sign.sh`, `nightly-verify.sh`,
`nightly-lib.sh`, `import-cert.sh`) and entitlements, and the Linux public key
`.github/nightly-linux-signing-key.asc`;
- **every other workflow that can reach the `release` environment**, including reusable
callees, dynamic environment selection and changed executable dependencies. A new
workflow outside the named nightly paths is not exempt.
Stop the sync if that closure is unreviewed. The intended signer-owned files are identical
on main and release after promotion; actual top-level repository/event/branch checks and
the existing environment restrictions provide authority, not permanent branch divergence.
3. **Wait for the draft.** When every job is done (macOS notarization is the slow part), the
Releases page has a draft `FilmCraft v0.3.0`, targeting the pushed commit, with every artifact
and `SHA256SUMS.txt`. The notes are generated from the merged pull requests.
@@ -183,3 +198,21 @@ warning, never a failed build.
| `APPLE_ID`, `APPLE_PASSWORD`, `APPLE_TEAM_ID` | notarization (`APPLE_PASSWORD` is an app-specific password) |
| `WINDOWS_CERTIFICATE`, `WINDOWS_CERTIFICATE_PASSWORD` | Windows signing with a `.pfx` |
| `AZURE_TENANT_ID`, `AZURE_CLIENT_ID`, `AZURE_CLIENT_SECRET`, `AZURE_SIGNING_ENDPOINT`, `AZURE_SIGNING_ACCOUNT`, `AZURE_CERT_PROFILE` | Windows signing with Azure Trusted Signing |
## Release-ref nightly preparation
The Windows, Linux and macOS source preparation is documented in
[`nightly-release-preparation.md`](nightly-release-preparation.md). It is not a qualified
signing or publication pipeline yet: `nightly.yml` and `nightly-sign.yml` are manual-dispatch only,
restricted to the five release managers by the installed `.github/nightly-signing-policy.json`,
with no schedule and no automatic signer; `nightly-dispatch.yml` only transports a completed
producer run. Stable `release.yml`, its schedule, tags, concurrency, environment values and rules
are unchanged.
`nightly-build.yml` is the secret-free hosted check (Windows and Linux always, macOS only behind
the `full-ci` label). The real Nightly is built by the shared producer and signed on `release` by
the shared signer, which calls this app's `packaging/macos/nightly-sign.sh` and
`packaging/windows/sign.ps1 -Required`.
Activation (the policy, the `release` promotion, any signing or environment setup) is a separate
reviewed change and needs the project owner's ok.
+87
View File
@@ -0,0 +1,87 @@
#!/bin/sh
# FilmCraft AppImage entry point (packaging/linux/AppRun; installed by package.sh).
#
# On Wayland the compositor resolves a window's dock icon by taking the window's app_id
# (ai.storyteller.filmcraft) and looking up an installed .desktop file. An AppImage installs
# nothing, so every AppImage run would otherwise show the generic "Wayland" icon. Best-effort
# desktop integration: on first run (and whenever the AppImage's path changes) install the
# .desktop entry and the hicolor icons into $XDG_DATA_HOME, then launch. Every failure here must
# leave the launch untouched. Opt out with FILMCRAFT_NO_DESKTOP_INTEGRATION=1.
set -u
APPDIR="$(dirname "$(readlink -f "$0")")"
DESK_ID=ai.storyteller.filmcraft
# package.sh rewrites this line (and DESK_ID) for a Nightly AppImage, which starts the app with the
# Launcher's private profile exactly as the deb, rpm, Arch, Flatpak and tarball launchers do.
CHANNEL=stable
integrate() {
case "${FILMCRAFT_NO_DESKTOP_INTEGRATION:-}" in
1 | true | yes) return 0 ;;
esac
# The AppImage runtime exports $APPIMAGE; without it (an extracted AppDir) there
# is no path to register and nothing to do.
appimage="${APPIMAGE:-}"
[ -n "$appimage" ] && [ -f "$appimage" ] || return 0
appimage="$(readlink -f "$appimage")" || return 0
# Exec= is parsed by the desktop: a path holding a quote, backquote, dollar, backslash,
# percent or a line break would need escaping (or could add lines), so skip integration.
case "$appimage" in
*[\"\`\$\\%]* | *'
'*) return 0 ;;
esac
home="${HOME:-}"
[ -n "$home" ] || return 0
data="${XDG_DATA_HOME:-$home/.local/share}"
src_desktop="$APPDIR/usr/share/applications/$DESK_ID.desktop"
[ -f "$src_desktop" ] || return 0
# Rewrite Exec to this AppImage (the binary is not on the host PATH) and drop
# TryExec, which would hide the entry; everything else is shipped as packaged.
apps="$data/applications"
mkdir -p "$apps" 2>/dev/null || return 0
tmp="$apps/.$DESK_ID.tmp.$$"
esc="$(printf '%s' "$appimage" | sed 's/[\\&|]/\\&/g')"
if sed -e "s|^Exec=.*|Exec=\"$esc\" %F|" -e '/^TryExec=/d' "$src_desktop" 2>/dev/null >"$tmp"; then
if cmp -s "$tmp" "$apps/$DESK_ID.desktop"; then
rm -f "$tmp"
else
if mv -f "$tmp" "$apps/$DESK_ID.desktop" 2>/dev/null; then
command -v update-desktop-database >/dev/null 2>&1 && update-desktop-database "$apps" >/dev/null 2>&1
else
rm -f "$tmp"
fi
fi
else
rm -f "$tmp"
return 0
fi
# Icons: per-file compare so an unchanged install costs a handful of cmp calls.
src_icons="$APPDIR/usr/share/icons/hicolor"
[ -d "$src_icons" ] || return 0
icons="$data/icons/hicolor"
(cd "$src_icons" && find . -type f) | while IFS= read -r rel; do
mkdir -p "$icons/$(dirname "$rel")" 2>/dev/null || continue
if ! cmp -s "$src_icons/$rel" "$icons/$rel"; then
cp "$src_icons/$rel" "$icons/$rel" 2>/dev/null || true
fi
done
}
integrate
# The Launcher's own protocol, a bare version query and the usage screen pass through untouched:
# the first already names its profile, the others must answer without one.
case "${1-}" in
--launch-profile | --profile-root | --version | -V | --help | -h) exec "$APPDIR/usr/bin/filmcraft" "$@" ;;
esac
if [ "$CHANNEL" = nightly-v1 ]; then
# A caller-written `--` already separates the files from the options: drop it, so the launcher's
# own separator never arrives as a file name.
if [ "${1-}" = -- ]; then shift; fi
exec "$APPDIR/usr/bin/filmcraft" --launch-profile nightly-v1 \
--profile-root "${XDG_DATA_HOME:-${HOME:-}/.local/share}/filmcraft-nightly/profile" -- "$@"
fi
exec "$APPDIR/usr/bin/filmcraft" "$@"
+122
View File
@@ -0,0 +1,122 @@
#!/usr/bin/env bash
# Smoke test for packaging/linux/AppRun: the AppImage's desktop integration writes and refreshes the
# host .desktop entry and icons, is idempotent, honours the opt-out and an unwritable HOME, always
# launches the app, and a Nightly AppImage starts it with the Launcher's private profile.
#
# Runs in seconds with no build (CI: .github/workflows/packaging-lint.yml).
set -euo pipefail
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ROOT="$(cd "$HERE/../.." && pwd)"
APP_ID=ai.storyteller.filmcraft
TMP="$(mktemp -d)"
trap 'rm -rf "$TMP"' EXIT
# Fake AppDir with the real AppRun, .desktop template, icons, and a stub binary.
APPDIR="$TMP/FilmCraft.AppDir"
mkdir -p "$APPDIR/usr/bin"
install -Dm755 "$HERE/AppRun" "$APPDIR/AppRun"
install -Dm644 "$HERE/$APP_ID.desktop" "$APPDIR/usr/share/applications/$APP_ID.desktop"
mkdir -p "$APPDIR/usr/share/icons"
cp -R "$ROOT/assets/app-icon/hicolor" "$APPDIR/usr/share/icons/"
printf '#!/bin/sh\necho "stub: $*"\n' >"$APPDIR/usr/bin/filmcraft"
chmod +x "$APPDIR/usr/bin/filmcraft"
APPIMAGE="$TMP/filmcraft test.AppImage" # spaces on purpose: Exec must stay quoted
: >"$APPIMAGE"
export APPIMAGE
export HOME="$TMP/home"
export XDG_DATA_HOME="$HOME/.local/share"
mkdir -p "$HOME"
fail() {
echo "FAIL: $*" >&2
exit 1
}
# 1. Launch works and passes arguments through.
out="$("$APPDIR/AppRun" open project.fcproj)" || fail "AppRun exited non-zero"
[[ "$out" = "stub: open project.fcproj" ]] || fail "arguments not forwarded: $out"
DESKTOP="$XDG_DATA_HOME/applications/$APP_ID.desktop"
[[ -f "$DESKTOP" ]] || fail "desktop entry not installed"
# 2. Exec rewritten to the AppImage (quoted, spaces intact), TryExec dropped,
# everything else preserved from the packaged entry.
expected_exec="Exec=\"$(readlink -f "$APPIMAGE")\" %F"
grep -Fxq "$expected_exec" "$DESKTOP" || fail "Exec not rewritten: $(grep '^Exec=' "$DESKTOP")"
grep -q '^TryExec=' "$DESKTOP" && fail "TryExec kept, the entry would be hidden"
grep -Fxq "Icon=$APP_ID" "$DESKTOP" || fail "Icon line lost"
grep -Fxq 'Categories=AudioVideo;Video;AudioVideoEditing;' "$DESKTOP" || fail "metadata lines lost"
if command -v desktop-file-validate >/dev/null; then
desktop-file-validate "$DESKTOP" || fail "generated desktop entry is invalid"
fi
# 3. Icons landed under the name the .desktop entry references.
for f in "16x16/apps/$APP_ID.png" "256x256/apps/$APP_ID.png" "scalable/apps/$APP_ID.svg"; do
[[ -f "$XDG_DATA_HOME/icons/hicolor/$f" ]] || fail "icon missing: $f"
done
# 4. Idempotent: a second launch must not rewrite anything (inode unchanged).
before="$(stat -c %i "$DESKTOP")"
out="$("$APPDIR/AppRun")" || fail "second launch exited non-zero"
[[ "$out" = "stub: " ]] || fail "second launch output: $out"
after="$(stat -c %i "$DESKTOP")"
[[ "$before" = "$after" ]] || fail "desktop entry rewritten although unchanged"
# 5. Moving the AppImage refreshes Exec.
mv "$APPIMAGE" "$TMP/moved.AppImage"
export APPIMAGE="$TMP/moved.AppImage"
"$APPDIR/AppRun" >/dev/null || fail "launch after move exited non-zero"
grep -Fxq "Exec=\"$(readlink -f "$APPIMAGE")\" %F" "$DESKTOP" || fail "Exec not refreshed after move"
# 6. Opt-out installs nothing.
rm -rf "$XDG_DATA_HOME"
FILMCRAFT_NO_DESKTOP_INTEGRATION=1 "$APPDIR/AppRun" >/dev/null || fail "opt-out launch exited non-zero"
[[ ! -e "$XDG_DATA_HOME" ]] || fail "opt-out still integrated"
# 7. An unwritable data dir never blocks the launch.
mkdir -p "$TMP/ro" && chmod a-w "$TMP/ro"
out="$(XDG_DATA_HOME="$TMP/ro/data" "$APPDIR/AppRun" out.fcproj)" || fail "launch blocked by unwritable data dir"
[[ "$out" = "stub: out.fcproj" ]] || fail "stub not run against unwritable data dir: $out"
chmod u+w "$TMP/ro"
# 8. No $APPIMAGE (extracted AppDir): launch only, nothing installed.
rm -rf "$XDG_DATA_HOME"
env -u APPIMAGE "$APPDIR/AppRun" >/dev/null || fail "extracted-AppDir launch exited non-zero"
[[ ! -e "$XDG_DATA_HOME" ]] || fail "integrated without $APPIMAGE"
# 9. A path that would need Exec escaping (here a `$`): launch only, nothing installed.
rm -rf "$XDG_DATA_HOME"
odd="$TMP/odd\$(id).AppImage"
: >"$odd"
out="$(APPIMAGE="$odd" "$APPDIR/AppRun" x)" || fail "launch with an odd path exited non-zero"
[[ "$out" = "stub: x" ]] || fail "odd path: $out"
[[ ! -e "$XDG_DATA_HOME" ]] || fail "integrated an AppImage path that needs escaping"
# 10. A Nightly AppImage (package.sh rewrites the DESK_ID and channel lines) starts the GUI with the
# Launcher's private profile; a version query still passes through untouched.
NIGHTLY_APPDIR="$TMP/Nightly.AppDir"
mkdir -p "$NIGHTLY_APPDIR/usr/bin"
install -Dm755 "$HERE/AppRun" "$NIGHTLY_APPDIR/AppRun"
cat >"$NIGHTLY_APPDIR/usr/bin/filmcraft" <<'RECORDER'
#!/bin/sh
printf '<%s>\n' "$@"
RECORDER
chmod +x "$NIGHTLY_APPDIR/usr/bin/filmcraft"
sed -i 's|^CHANNEL=stable$|CHANNEL=nightly-v1|' "$NIGHTLY_APPDIR/AppRun"
grep -qx 'CHANNEL=nightly-v1' "$NIGHTLY_APPDIR/AppRun" || fail "Nightly AppRun was not switched"
out="$(env -u APPIMAGE XDG_DATA_HOME="$TMP/nightly-data" "$NIGHTLY_APPDIR/AppRun" a.fcproj)" || fail "Nightly AppRun exited non-zero"
expected="$(printf '<%s>\n' --launch-profile nightly-v1 --profile-root "$TMP/nightly-data/filmcraft-nightly/profile" -- a.fcproj)"
[[ "$out" = "$expected" ]] || fail "Nightly AppRun did not use the Launcher profile: $out"
out="$(env -u APPIMAGE "$NIGHTLY_APPDIR/AppRun" --version)" || fail "Nightly version query exited non-zero"
[[ "$out" = "<--version>" ]] || fail "Nightly AppRun rewrote a version query: $out"
out="$(env -u APPIMAGE "$NIGHTLY_APPDIR/AppRun" --help)" || fail "Nightly usage query exited non-zero"
[[ "$out" = "<--help>" ]] || fail "Nightly AppRun rewrote a usage query: $out"
# A caller-written `--` is dropped: it must never arrive as a file name.
out="$(env -u APPIMAGE XDG_DATA_HOME="$TMP/nightly-data" "$NIGHTLY_APPDIR/AppRun" -- b.fcproj --version)" || fail "Nightly AppRun exited non-zero"
expected="$(printf '<%s>\n' --launch-profile nightly-v1 --profile-root "$TMP/nightly-data/filmcraft-nightly/profile" -- b.fcproj --version)"
[[ "$out" = "$expected" ]] || fail "Nightly AppRun kept a caller-written separator: $out"
echo "AppRun desktop integration ok"
+75 -7
View File
@@ -17,6 +17,12 @@ set -euo pipefail
. "$(dirname "${BASH_SOURCE[0]}")/../env.sh"
HERE="$ROOT/packaging/linux"
APP_ID=ai.storyteller.filmcraft
FLATPAK_ID="$APP_ID"
# The remote indexes both app IDs on the stable ref branch; IDs isolate installations.
FLATPAK_BRANCH=stable
if [[ "${FILMCRAFT_BUILD_CHANNEL:-}" == nightly-v1 || "$VERSION" == *-nightly* ]]; then
FLATPAK_ID="$APP_ID.nightly"
fi
FLATHUB=https://dl.flathub.org/repo/flathub.flatpakrepo
TEST=1
@@ -52,29 +58,91 @@ rm -rf "$WORK"
mkdir -p "$WORK/stage"
tar -xzf "$TARBALL" -C "$WORK/stage" --strip-components=1
[[ -x "$WORK/stage/bin/filmcraft" ]] || { echo "error: $TARBALL has no bin/filmcraft" >&2; exit 1; }
cp "$HERE/flatpak/$APP_ID.bundle.yml" "$WORK/$APP_ID.yml"
if [[ "$FLATPAK_ID" != "$APP_ID" ]]; then
# The GUI runs with the Launcher's private profile, as on every other Nightly format: inside the
# sandbox $XDG_DATA_HOME is this app's own per-app folder, so the profile never meets stable's.
# A Nightly tarball from package.sh already separates the launcher from the GUI; an older one
# does not. Either way this bundle installs its own launcher and the GUI in /app/libexec.
if [[ -e "$WORK/stage/bin/filmcraft-bin" ]]; then
rm -f "$WORK/stage/bin/filmcraft"
else
mv "$WORK/stage/bin/filmcraft" "$WORK/stage/bin/filmcraft-bin"
fi
cat >"$WORK/stage/bin/filmcraft" <<'WRAPPER'
#!/bin/sh
# FilmCraft Nightly: the GUI runs with the Launcher's private profile, which holds every per-user
# file (preferences, recovery autosaves, media cache, presets, logs, downloaded models).
set -eu
bin=/app/libexec/filmcraft
profile="${XDG_DATA_HOME:-${HOME:-}/.local/share}/filmcraft-nightly/profile"
# The Launcher's protocol, a bare version query and the usage screen pass through untouched.
case "${1-}" in
--launch-profile | --profile-root | --version | -V | --help | -h) exec "$bin" "$@" ;;
esac
# A caller-written `--` already separates the files from the options: drop it, so the launcher's
# own separator never arrives as a file name.
if [ "${1-}" = -- ]; then shift; fi
exec "$bin" --launch-profile nightly-v1 --profile-root "$profile" -- "$@"
WRAPPER
chmod 755 "$WORK/stage/bin/filmcraft"
NIGHTLY_ICON="$ROOT/assets/app-icon/filmcraft-nightly.png"
if [[ ! -f "$NIGHTLY_ICON" ]]; then
echo "error: the Nightly icon $NIGHTLY_ICON is missing" >&2
exit 2
fi
sed -e "s|^Icon=$APP_ID$|Icon=$FLATPAK_ID|" \
-e "s|^Name=FilmCraft$|Name=FilmCraft Nightly|" \
-e 's|^StartupWMClass=.*|StartupWMClass=ai.storyteller.filmcraft.nightly-v1|' \
-e '/^MimeType=/d' \
"$WORK/stage/share/applications/$APP_ID.desktop" >"$WORK/stage/share/applications/$FLATPAK_ID.desktop"
rm -f "$WORK/stage/share/applications/$APP_ID.desktop"
# The Nightly claims no associations, so its metainfo advertises none and it registers no MIME.
sed -e "s|<id>$APP_ID</id>|<id>$FLATPAK_ID</id>|g" \
-e "s|<name>FilmCraft</name>|<name>FilmCraft Nightly</name>|g" \
-e "s|<launchable type=\"desktop-id\">$APP_ID.desktop</launchable>|<launchable type=\"desktop-id\">$FLATPAK_ID.desktop</launchable>|g" \
-e "s|<icon type=\"stock\">$APP_ID</icon>|<icon type=\"stock\">$FLATPAK_ID</icon>|g" \
-e '/<mediatype>/d' \
"$WORK/stage/share/metainfo/$APP_ID.metainfo.xml" >"$WORK/stage/share/metainfo/$FLATPAK_ID.metainfo.xml"
rm -f "$WORK/stage/share/metainfo/$APP_ID.metainfo.xml"
rm -rf "$WORK/stage/share/mime"
rm -rf "$WORK/stage/share/icons/hicolor"
install -Dm644 "$NIGHTLY_ICON" "$WORK/stage/share/icons/hicolor/256x256/apps/$FLATPAK_ID.png"
# No MIME install, and no host-Flatpak updater talk-name: a Nightly never asks the stable updater
# (the app disables it), and the /app/libexec line is the GUI the launcher starts.
sed -e "s|ai\.storyteller\.filmcraft|$FLATPAK_ID|g" \
-e '/share\/mime\/packages\//d' \
-e '/--talk-name=org\.freedesktop\.Flatpak/d' \
-e 's|- install -Dm755 bin/filmcraft /app/bin/filmcraft|- install -Dm755 bin/filmcraft-bin /app/libexec/filmcraft\n - install -Dm755 bin/filmcraft /app/bin/filmcraft|' \
"$HERE/flatpak/$APP_ID.bundle.yml" >"$WORK/$FLATPAK_ID.yml"
else
cp "$HERE/flatpak/$APP_ID.bundle.yml" "$WORK/$FLATPAK_ID.yml"
fi
flatpak remote-add --user --if-not-exists flathub "$FLATHUB"
# --disable-rofiles-fuse: no FUSE in containers and CI runners.
flatpak-builder --user --install-deps-from=flathub --disable-rofiles-fuse --force-clean \
--default-branch=stable --repo="$WORK/repo" --state-dir="$WORK/state" "$WORK/build" "$WORK/$APP_ID.yml"
--default-branch="$FLATPAK_BRANCH" --repo="$WORK/repo" --state-dir="$WORK/state" "$WORK/build" "$WORK/$FLATPAK_ID.yml"
OUT="$DIST/$BASENAME.flatpak"
# --runtime-repo lets `flatpak install` fetch the freedesktop runtime from Flathub if missing.
flatpak build-bundle --runtime-repo="$FLATHUB" "$WORK/repo" "$OUT" "$APP_ID" stable
flatpak build-bundle --runtime-repo="$FLATHUB" "$WORK/repo" "$OUT" "$FLATPAK_ID" "$FLATPAK_BRANCH"
echo "wrote $OUT"
if [[ "$OCI" = 1 ]]; then
OUT_OCI="$DIST/$BASENAME-oci"
rm -rf "$OUT_OCI"
flatpak build-bundle --oci "$WORK/repo" "$OUT_OCI" "$APP_ID" stable
flatpak build-bundle --oci "$WORK/repo" "$OUT_OCI" "$FLATPAK_ID" "$FLATPAK_BRANCH"
echo "wrote OCI layout to $OUT_OCI"
fi
if [[ "$TEST" = 1 ]]; then
flatpak install --user -y --noninteractive --reinstall "$OUT"
flatpak info --user "$APP_ID"
flatpak run --command=filmcraft-cli "$APP_ID" --version
flatpak run --command=sh "$APP_ID" -c 'ls /app/share/applications /app/share/metainfo /app/share/mime/packages /app/share/icons/hicolor/scalable/apps'
flatpak info --user "$FLATPAK_ID"
flatpak run --command=filmcraft-cli "$FLATPAK_ID" --version
if [[ "$FLATPAK_ID" == "$APP_ID" ]]; then
flatpak run --command=sh "$FLATPAK_ID" -c 'ls /app/share/applications /app/share/metainfo /app/share/mime/packages /app/share/icons/hicolor/*/apps'
else
flatpak run --command=sh "$FLATPAK_ID" -c 'ls /app/share/applications /app/share/metainfo /app/share/icons/hicolor/*/apps && test ! -e /app/share/mime/packages && test -x /app/bin/filmcraft && test -x /app/libexec/filmcraft'
fi
fi
echo "==> done"
ls -lh "$OUT"
+51 -9
View File
@@ -30,36 +30,78 @@ for binary in filmcraft filmcraft-cli; do
[[ -f "$source_dir/bin/$binary" ]] || fail "missing bin/$binary; extract the complete tarball first"
done
[[ -f "$source_dir/share/applications/$app_id.desktop" ]] || fail 'missing desktop entry; extract the complete tarball first'
# A Nightly tarball ships its GUI as bin/filmcraft-bin beside the launcher that starts it with the
# Launcher's private profile. It installs under its own names, so a Stable install in the same
# prefix keeps its launcher, CLI, desktop entry and icons.
nightly=0
if [[ -f "$source_dir/bin/filmcraft-bin" ]]; then
nightly=1
product='FilmCraft Nightly'
launcher=filmcraft-nightly
cli=filmcraft-nightly-cli
doc=filmcraft-nightly
desktop_id="$app_id.nightly-v1"
else
product=FilmCraft
launcher=filmcraft
cli=filmcraft-cli
doc=filmcraft
desktop_id="$app_id"
fi
mkdir -p -- "$prefix/bin" "$prefix/share"
install -m755 -- "$source_dir/bin/filmcraft" "$prefix/bin/filmcraft"
install -m755 -- "$source_dir/bin/filmcraft-cli" "$prefix/bin/filmcraft-cli"
cp -R -- "$source_dir/share/." "$prefix/share/"
install -m755 -- "$source_dir/bin/filmcraft" "$prefix/bin/$launcher"
install -m755 -- "$source_dir/bin/filmcraft-cli" "$prefix/bin/$cli"
if [[ "$nightly" = 1 ]]; then
# Only the Nightly's own files here: Stable's desktop entry, icons and MIME database stay as they
# are, and the Nightly's entry gets its own icon name instead of replacing Stable's.
install -m755 -- "$source_dir/bin/filmcraft-bin" "$prefix/bin/filmcraft-bin"
if [[ -d "$source_dir/share/doc/filmcraft" ]]; then
mkdir -p -- "$prefix/share/doc/$doc"
cp -R -- "$source_dir/share/doc/filmcraft/." "$prefix/share/doc/$doc/"
fi
icon=
for candidate in "$source_dir/share/icons/hicolor/256x256/apps/$app_id.png" "$source_dir/share/icons/hicolor/"*/apps/"$app_id.png"; do
if [[ -f "$candidate" ]]; then icon="$candidate"; break; fi
done
[[ -z "$icon" ]] || install -Dm644 -- "$icon" "$prefix/share/icons/hicolor/256x256/apps/$desktop_id.png"
else
cp -R -- "$source_dir/share/." "$prefix/share/"
fi
# Use an absolute path so launching from the application menu does not depend on PATH.
# Escape the Exec argument, then the desktop entry's string value (two separate layers).
# https://specifications.freedesktop.org/desktop-entry/latest/exec-variables.html
exec_path="$(printf '%s' "$prefix/bin/filmcraft" | sed 's/[\\"`$]/\\&/g; s/\\/\\\\/g')"
try_path="$(printf '%s' "$prefix/bin/filmcraft" | sed 's/\\/\\\\/g')"
exec_path="$(printf '%s' "$prefix/bin/$launcher" | sed 's/[\\"`$]/\\&/g; s/\\/\\\\/g')"
try_path="$(printf '%s' "$prefix/bin/$launcher" | sed 's/\\/\\\\/g')"
while IFS= read -r line || [[ -n "$line" ]]; do
if [[ "$nightly" = 1 ]]; then
# The Nightly claims no associations, as in every other Nightly format, and its MIME database
# outside the install is Stable's.
case "$line" in
MimeType=*) continue ;;
"Name=FilmCraft") line="Name=$product" ;;
"Icon=$app_id") line="Icon=$desktop_id" ;;
esac
fi
case "$line" in
Exec=*) printf 'Exec="%s" %%F\n' "$exec_path" ;;
TryExec=*) printf 'TryExec=%s\n' "$try_path" ;;
*) printf '%s\n' "$line" ;;
esac
done <"$source_dir/share/applications/$app_id.desktop" >"$prefix/share/applications/$app_id.desktop"
done <"$source_dir/share/applications/$app_id.desktop" >"$prefix/share/applications/$desktop_id.desktop"
# Cache tools are optional; installing binaries must also work on minimal systems.
if command -v update-desktop-database >/dev/null 2>&1; then
update-desktop-database -q "$prefix/share/applications" || echo 'warning: desktop cache refresh failed' >&2
fi
if command -v update-mime-database >/dev/null 2>&1; then
if command -v update-mime-database >/dev/null 2>&1 && [[ -d "$prefix/share/mime" ]]; then
update-mime-database "$prefix/share/mime" || echo 'warning: MIME cache refresh failed' >&2
fi
if command -v gtk-update-icon-cache >/dev/null 2>&1; then
if command -v gtk-update-icon-cache >/dev/null 2>&1 && [[ -d "$prefix/share/icons/hicolor" ]]; then
gtk-update-icon-cache -q -t -f "$prefix/share/icons/hicolor" || echo 'warning: icon cache refresh failed' >&2
fi
printf 'Installed FilmCraft in %s\nLaunch it from the application menu or run "%s/bin/filmcraft".\n' "$prefix" "$prefix"
printf 'Installed %s in %s\nLaunch it from the application menu or run "%s/bin/%s".\n' "$product" "$prefix" "$prefix" "$launcher"
case ":${PATH:-}:" in
*":$prefix/bin:"*) ;;
*) printf 'For terminal commands, add %s/bin to your PATH.\n' "$prefix" ;;
+13 -7
View File
@@ -1,9 +1,12 @@
# .deb and .rpm packages (nfpm: https://nfpm.goreleaser.com). Run by package.sh, which stages
# the file tree, substitutes its path for ${STAGE} (nfpm doesn't expand env vars in `src`) and
# exports VERSION and NFPM_ARCH.
# exports VERSION, NFPM_ARCH, NFPM_NAME, NFPM_BIN and NFPM_CLI (the last three name the Nightly
# package's own files). A Nightly stage also has usr/lib/filmcraft-nightly/: the GUI, started by
# the /usr/bin launcher with the Launcher's private profile. By hand, all five are needed:
#
# nfpm package -f packaging/linux/nfpm.yaml -p deb -t dist/release/
name: filmcraft
# VERSION=1.2.3 NFPM_ARCH=amd64 NFPM_NAME=filmcraft NFPM_BIN=filmcraft \
# NFPM_CLI=filmcraft-cli nfpm package -f packaging/linux/nfpm.yaml -p deb -t dist/release/
name: ${NFPM_NAME}
arch: ${NFPM_ARCH}
platform: linux
version: ${VERSION}
@@ -61,12 +64,15 @@ overrides:
- xdg-desktop-portal
contents:
- src: ${STAGE}/usr/bin/filmcraft
dst: /usr/bin/filmcraft
- src: ${STAGE}/usr/bin/${NFPM_BIN}
dst: /usr/bin/${NFPM_BIN}
file_info: { mode: 0755 }
- src: ${STAGE}/usr/bin/filmcraft-cli
dst: /usr/bin/filmcraft-cli
- src: ${STAGE}/usr/bin/${NFPM_CLI}
dst: /usr/bin/${NFPM_CLI}
file_info: { mode: 0755 }
- src: ${STAGE}/usr/lib/
dst: /usr/lib/
type: tree
- src: ${STAGE}/usr/share/
dst: /usr/share/
type: tree
+18
View File
@@ -0,0 +1,18 @@
#!/bin/sh
# The FilmCraft Nightly launcher for the Arch handoff (packaging/linux/nightly-arch-tar.sh): the
# real GUI stays in .filmcraft-nightly/, and this starts it with the Launcher's private profile,
# as every other Nightly package does.
set -eu
bin="$(dirname "$0")/.filmcraft-nightly/filmcraft"
profile="${XDG_DATA_HOME:-${HOME:-}/.local/share}/filmcraft-nightly/profile"
# The Launcher's protocol, a bare version query and the usage screen pass through untouched: the
# first already names its profile, the others must answer without one.
case "${1-}" in
--launch-profile | --profile-root | --version | -V | --help | -h) exec "$bin" "$@" ;;
esac
# A caller-written `--` already separates the files from the options: drop it, so the launcher's
# own separator never arrives as a file name.
if [ "${1-}" = -- ]; then shift; fi
exec "$bin" --launch-profile nightly-v1 --profile-root "$profile" -- "$@"
+56
View File
@@ -0,0 +1,56 @@
#!/usr/bin/env bash
# Validate the staged Arch launcher without building or opening FilmCraft.
set -euo pipefail
HERE="$(cd "$(dirname "$0")" && pwd)"
work="$(mktemp -d)"
trap 'rm -rf "$work"' EXIT
stage="$work/source"
dst="$work/dist"
base=filmcraft-0.0.1-nightly.1-linux-x86_64
mkdir -p "$stage/bin" "$dst" "$work/extract"
# A local argv recorder stands in for the compiled binaries. It never opens a UI.
cat >"$stage/bin/filmcraft" <<'RECORDER'
#!/bin/sh
printf '<%s>\n' "$@"
RECORDER
chmod 755 "$stage/bin/filmcraft"
cp "$stage/bin/filmcraft" "$stage/bin/filmcraft-cli"
bash "$HERE/nightly-arch-tar.sh" "$stage" "$work/stage" "$dst" "$base"
tar -xzf "$dst/$base.tar.gz" -C "$work/extract"
bin="$work/extract/$base/bin"
# Simulate the existing Arch bin-tree copy and public launcher rename.
mkdir -p "$work/installed"
cp -R "$bin" "$work/installed/bin"
bin="$work/installed/bin"
mv "$bin/filmcraft" "$bin/filmcraft-nightly"
mv "$bin/filmcraft-cli" "$bin/filmcraft-nightly-cli"
[[ ! -e "$stage/bin/.filmcraft-nightly" ]]
cmp "$stage/bin/filmcraft" "$bin/.filmcraft-nightly/filmcraft"
cmp "$stage/bin/filmcraft-cli" "$bin/filmcraft-nightly-cli"
expect() {
expected="$1"
shift
actual=$(PATH="$bin:$PATH" filmcraft-nightly "$@")
if [[ "$actual" != "$expected" ]]; then
printf 'expected:\n%s\nactual:\n%s\n' "$expected" "$actual" >&2
exit 1
fi
}
# A launch starts the GUI with the Launcher's private profile, as the deb, rpm, AppImage, Flatpak
# and tarball launchers do; a version query and an existing protocol pass through untouched.
profile="${XDG_DATA_HOME:-${HOME:-}/.local/share}/filmcraft-nightly/profile"
expect "$(printf '<%s>\n' --launch-profile nightly-v1 --profile-root "$profile" -- 'clip with spaces.fcproj' '--other-name.fcproj')" \
'clip with spaces.fcproj' '--other-name.fcproj'
expect "$(printf '<%s>\n' --launch-profile nightly-v1 --profile-root "$profile" -- 'clip with spaces.fcproj')" \
-- 'clip with spaces.fcproj'
expect '<--version>' --version
expect '<-V>' -V
expect '<--help>' --help
expect "$(printf '<%s>\n' --launch-profile nightly-v1 --profile-root /launcher/profile --version)" \
--launch-profile nightly-v1 --profile-root /launcher/profile --version
echo "PASS: Arch Nightly handoff starts the GUI with the Launcher profile and preserves arguments"
+19
View File
@@ -0,0 +1,19 @@
#!/usr/bin/env bash
# Stage the FilmCraft Nightly-only handoff for the Arch packager.
set -euo pipefail
here="$(cd "$(dirname "$0")" && pwd)"
source_tree="$1"
work="$2"
destination="$3"
basename="$4"
stage="$work/$basename"
mkdir -p "$work"
cp -R "$source_tree" "$stage"
mkdir "$stage/bin/.filmcraft-nightly"
mv "$stage/bin/filmcraft" "$stage/bin/.filmcraft-nightly/filmcraft"
cp "$here/nightly-arch-launch.sh" "$stage/bin/filmcraft"
chmod 755 "$stage/bin/filmcraft"
tar -C "$work" -czf "$destination/$basename.tar.gz" "$basename"
echo "wrote $destination/$basename.tar.gz"
+77
View File
@@ -0,0 +1,77 @@
#!/usr/bin/env bash
# Check an x86_64 Linux Nightly tar as the Launcher unpacks it, then ask the GUI its version:
#
# packaging/linux/nightly-check.sh --input /abs/filmcraft-<version>-linux-x86_64-nightly.tar.gz
#
# The archive holds exactly the GUI-only Nightly: `filmcraft` (the launcher, mode 755),
# `filmcraft-bin` (the GUI it starts with the Launcher's private profile, mode 755), the channel
# icon and the notices, all flat regular files. The launcher then answers both version queries —
# plain and the Launcher's form `--launch-profile nightly-v1 --profile-root <fresh dir> --version`
# — with exactly `FilmCraft <version> (nightly-v1)` on standard output, nothing on standard error,
# exit 0, and without touching the profile root (the query runs before any profile or window work).
# No signing material may be in the environment: this runs the payload.
set -euo pipefail
INPUT=''
while [[ $# -gt 0 ]]; do
case "$1" in
--input) [[ $# -ge 2 ]] || { echo 'missing --input value' >&2; exit 2; }; INPUT="$2"; shift 2 ;;
-h | --help) sed -n '2,11p' "$0"; exit 0 ;;
*) echo "unsupported argument: $1" >&2; exit 2 ;;
esac
done
die() { printf 'error: %s\n' "$*" >&2; exit 2; }
for name in APPLE_CERTIFICATE APPLE_CERTIFICATE_PASSWORD KEYCHAIN_PASSWORD APPLE_ID APPLE_PASSWORD APPLE_TEAM_ID \
MACOS_SIGN_IDENTITY MACOS_KEYCHAIN WINDOWS_CERTIFICATE WINDOWS_CERTIFICATE_PASSWORD AZURE_TENANT_ID AZURE_CLIENT_ID \
AZURE_CLIENT_SECRET AZURE_SIGNING_ENDPOINT AZURE_SIGNING_ACCOUNT AZURE_CERT_PROFILE LINUX_SIGNING_KEY; do
[[ -z "${!name:-}" ]] || die "refusing to run the payload with signing material in the environment ($name)"
done
[[ "$INPUT" == /* && -f "$INPUT" && ! -L "$INPUT" ]] || die '--input must be an absolute regular file'
NAME="$(basename -- "$INPUT")"
[[ "$NAME" =~ ^filmcraft-([0-9]+\.[0-9]+\.[0-9]+-nightly\.[0-9]{8}\.[0-9]+\.[0-9]+\.g[0-9a-f]{12})-linux-x86_64-nightly\.tar\.gz$ ]] || die 'the input is not a prepared Nightly archive name'
VERSION="${BASH_REMATCH[1]}"
WORK="$(mktemp -d "${RUNNER_TEMP:-${TMPDIR:-/tmp}}/filmcraft-nightly-check.XXXXXX")"
trap 'rm -rf -- "$WORK"' EXIT
mkdir -p "$WORK/payload" "$WORK/home" "$WORK/profile"
# Flat members only: no directory entries, links or absolute names.
python3 -I - "$INPUT" <<'PY' || die 'the archive holds a member that is not a flat regular file'
import sys, tarfile
with tarfile.open(sys.argv[1], 'r:gz') as archive:
for member in archive.getmembers():
name = member.name
if member.isdir():
continue
if not member.isfile() or '/' in name.rstrip('/') or name.startswith('/') or '\\' in name:
sys.exit(f"refused member: {name!r}")
PY
tar -xzf "$INPUT" -C "$WORK/payload"
entries="$(ls -A "$WORK/payload")"
for name in filmcraft filmcraft-bin filmcraft-nightly.png LICENSE-MIT LICENSE-APACHE NOTICE ATTRIBUTION.md; do
[[ -f "$WORK/payload/$name" && ! -L "$WORK/payload/$name" ]] || die "the archive has no regular $name"
done
for name in $entries; do
case "$name" in
filmcraft | filmcraft-bin | filmcraft-nightly.png | README.md | LICENSE | LICENSE-MIT | LICENSE-APACHE | COPYRIGHT | NOTICE | ATTRIBUTION.md) ;;
OFL-*.txt) ;;
*) die "unexpected nightly member: $name" ;;
esac
done
for name in filmcraft filmcraft-bin; do
[[ -x "$WORK/payload/$name" && "$(stat -c '%a' "$WORK/payload/$name")" == 755 ]] || die "$name must be executable with mode 755"
done
# The shipped launcher is the one that injects the Launcher's private profile, not the bare GUI.
grep -q -- '--launch-profile nightly-v1' "$WORK/payload/filmcraft" || die 'the launcher does not start the GUI with the Launcher profile'
[[ -z "$(find "$WORK/payload" ! -type f ! -type d -print -quit)" ]] || die 'the archive contains links or special files'
query() {
local out
out="$(timeout 20 env -i HOME="$WORK/home" XDG_DATA_HOME="$WORK/home/.local/share" PATH=/usr/bin:/bin \
"$WORK/payload/filmcraft" "$@" 2>"$WORK/stderr")" || die "the version query ($*) failed or did not finish within 20 s"
[[ ! -s "$WORK/stderr" ]] || die "the version query ($*) wrote to standard error: $(head -c 2000 "$WORK/stderr")"
[[ "$out" == "FilmCraft $VERSION (nightly-v1)" ]] || die "the version query ($*) reports '$out', not FilmCraft $VERSION (nightly-v1)"
}
before="$(ls -A "$WORK/profile")"
query --version
query --launch-profile nightly-v1 --profile-root "$WORK/profile" --version
[[ "$(ls -A "$WORK/profile")" == "$before" ]] || die 'the version query created state in the profile root'
echo "==> verified: FilmCraft $VERSION (nightly-v1), plain and in the Launcher's profile form"
+68
View File
@@ -0,0 +1,68 @@
#!/usr/bin/env bash
# The launcher inside the plain Nightly tarball (packaging/linux/nightly-launch.sh): a launch adds
# the Launcher's private profile, a version query or an existing protocol passes through, and the
# fence's shape holds (absolute root, no parent traversal, outside this copy).
set -euo pipefail
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
work="$(mktemp -d)"
trap 'rm -rf "$work"' EXIT
mkdir -p "$work/tree"
# An argv recorder stands in for the GUI. It never opens a window.
cat >"$work/tree/filmcraft-bin" <<'RECORDER'
#!/bin/sh
printf '<%s>\n' "$@"
RECORDER
chmod 755 "$work/tree/filmcraft-bin"
cp "$HERE/nightly-launch.sh" "$work/tree/filmcraft"
profile="${XDG_DATA_HOME:-${HOME:-}/.local/share}/filmcraft-nightly/profile"
# The profile must be something the app's fence accepts: absolute, no parent traversal, and not
# inside the unpacked copy (the running install).
case "$profile" in
/*) ;;
*) echo "FAIL: the launcher profile is not absolute: $profile" >&2; exit 1 ;;
esac
case "/$profile/" in
*/../*) echo "FAIL: the launcher profile contains parent traversal" >&2; exit 1 ;;
esac
case "$profile/" in
"$work/tree/"*) echo "FAIL: the launcher profile is inside the unpacked copy" >&2; exit 1 ;;
esac
expect_launch() {
expected="$(printf '<%s>\n' --launch-profile nightly-v1 --profile-root "$profile" -- "$@")"
actual=$("$work/tree/filmcraft" "$@")
[[ "$actual" == "$expected" ]] || {
printf 'expected:\n%s\nactual:\n%s\n' "$expected" "$actual" >&2
exit 1
}
}
expect_forwarded() {
expected="$(printf '<%s>\n' "$@")"
actual=$("$work/tree/filmcraft" "$@")
[[ "$actual" == "$expected" ]] || {
printf 'expected:\n%s\nactual:\n%s\n' "$expected" "$actual" >&2
exit 1
}
}
expect_launch
expect_launch 'project with spaces.fcproj' '--other-name.fcproj'
# A caller-written `--` is dropped: the launcher's own separator must arrive once, never twice,
# and what follows the caller's separator stays a file name (here `--version`).
expected="$(printf '<%s>\n' --launch-profile nightly-v1 --profile-root "$profile" -- 'project with spaces.fcproj' --version)"
actual=$("$work/tree/filmcraft" -- 'project with spaces.fcproj' --version)
[[ "$actual" == "$expected" ]] || {
printf 'caller separator:\nexpected:\n%s\nactual:\n%s\n' "$expected" "$actual" >&2
exit 1
}
expect_forwarded --version
expect_forwarded -V
expect_forwarded --help
expect_forwarded -h
expect_forwarded --launch-profile nightly-v1 --profile-root /launcher/profile --version
expect_forwarded --launch-profile nightly-v1 --profile-root /launcher/profile -- a.fcproj
echo "PASS: tarball Nightly launcher starts the GUI with the Launcher profile and forwards files"
+23
View File
@@ -0,0 +1,23 @@
#!/bin/sh
# The entry point inside the Nightly tarball (packaging/linux/nightly.sh stages it as `filmcraft`,
# beside the GUI as `filmcraft-bin`), and the form every other Nightly Linux package installs.
#
# A Nightly build only starts with its private profile, and every package format passes the
# Launcher's literal protocol: `--launch-profile nightly-v1 --profile-root <dir> -- <files>`. The
# profile sits outside stable's folders (settings, recovery autosaves, media cache, presets, logs,
# models) and outside this unpacked copy, which the app's own fence would refuse.
set -eu
here="$(dirname "$(readlink -f "$0")")"
bin="$here/filmcraft-bin"
profile="${XDG_DATA_HOME:-${HOME:-}/.local/share}/filmcraft-nightly/profile"
# The Launcher's protocol, a bare version query and the usage screen pass through untouched: the
# first already names its profile, the others must answer without one.
case "${1-}" in
--launch-profile | --profile-root | --version | -V | --help | -h) exec "$bin" "$@" ;;
esac
# A caller-written `--` already separates the files from the options: drop it, so the launcher's
# own separator never arrives as a file name.
if [ "${1-}" = -- ]; then shift; fi
exec "$bin" --launch-profile nightly-v1 --profile-root "$profile" -- "$@"
+29
View File
@@ -0,0 +1,29 @@
#!/usr/bin/env bash
# App-owned GUI-only nightly tar: no FUSE/AppImage, CLI, association or install hooks.
set -euo pipefail
ARCH=
while [[ $# -gt 0 ]]; do
case "$1" in
--arch) [[ $# -ge 2 ]] || { echo 'missing --arch value' >&2; exit 2; }; ARCH="$2"; shift 2 ;;
-h|--help) echo 'Usage: nightly.sh --arch x86_64'; exit 0 ;;
*) echo "unsupported nightly argument: $1" >&2; exit 2 ;;
esac
done
[[ "$ARCH" == x86_64 && "$(uname -s)" == Linux ]] || { echo 'only native Linux x86_64 nightly packaging is supported' >&2; exit 2; }
. "$(dirname "${BASH_SOURCE[0]}")/../nightly-common.sh"
nightly_init linux "$ARCH" x86_64-unknown-linux-gnu
OUTPUT="$DIST/filmcraft-$VERSION-linux-x86_64-nightly.tar.gz"
[[ ! -e "$OUTPUT" && ! -L "$OUTPUT" ]] || nightly_die 'refusing to replace an existing nightly archive'
nightly_build_gui
STAGE="$NIGHTLY_WORK/stage"
mkdir -p "$STAGE"
# The GUI is `filmcraft-bin`; `filmcraft` is the launcher that starts it with the Launcher's private
# profile, so an unpacked tarball is isolated exactly like the deb, rpm, AppImage and Flatpak.
cp "$NIGHTLY_GUI" "$STAGE/filmcraft-bin"
chmod 755 "$STAGE/filmcraft-bin"
install -m755 "$ROOT/packaging/linux/nightly-launch.sh" "$STAGE/filmcraft"
cp "$ROOT/assets/app-icon/filmcraft-nightly.png" "$STAGE/filmcraft-nightly.png"
nightly_copy_notices "$STAGE"
# The private mktemp cwd is the helper authority root, not a CLI path parent.
(cd "$NIGHTLY_WORK" && python3 "$ROOT/packaging/nightly-archive.py" linux stage archive.tar.gz)
nightly_publish_archive "$NIGHTLY_WORK/archive.tar.gz" "$OUTPUT"
+170 -9
View File
@@ -7,7 +7,7 @@
# $DIST/filmcraft-<version>-linux-<arch>.rpm Fedora, openSUSE, RHEL, ...
# $DIST/filmcraft-<version>-linux-<arch>.tar.gz plain FHS-style tree (bin/, share/)
#
# Usage: packaging/linux/package.sh [--skip-build] [--formats "appimage deb rpm tar"]
# Usage: packaging/linux/package.sh [--skip-build] [--formats "appimage deb rpm tar"] [--arch-tar-dir DIRECTORY]
#
# Needs: cargo; nfpm for deb/rpm (https://nfpm.goreleaser.com); appimagetool for the AppImage
# (downloaded into $CARGO_TARGET_DIR if missing). Build on an old distro (CI: Ubuntu 22.04,
@@ -25,10 +25,16 @@ APP_ID=ai.storyteller.filmcraft
SKIP_BUILD=0
FORMATS="appimage deb rpm tar"
ARCH_TAR_DIR=
while [[ $# -gt 0 ]]; do
case "$1" in
--skip-build) SKIP_BUILD=1; shift ;;
--formats) FORMATS="$2"; shift 2 ;;
--arch-tar-dir)
[[ -n "${2:-}" ]] || { echo "error: --arch-tar-dir needs a directory" >&2; exit 2; }
ARCH_TAR_DIR="$2"
shift 2
;;
-h | --help) sed -n '2,21p' "$0"; exit 0 ;;
*) echo "unknown argument: $1" >&2; exit 2 ;;
esac
@@ -42,9 +48,33 @@ case "$ARCH" in
*) echo "unsupported architecture $ARCH" >&2; exit 2 ;;
esac
export FILMCRAFT_MAINTAINER="${FILMCRAFT_MAINTAINER:-FilmCraft maintainers <filmcraft@storyteller.ai>}"
IS_NIGHTLY=0
if [[ "${FILMCRAFT_BUILD_CHANNEL:-}" == nightly-v1 || "$VERSION" == *-nightly* ]]; then
IS_NIGHTLY=1
# The binary compiles the exact prepared identity (build.rs refuses anything else), so a
# Nightly package never invents a version: two different nights must never share one.
if [[ ! "$VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+-nightly\.[0-9]{8}\.[0-9]+\.[0-9]+\.g[0-9a-f]{12}$ ]]; then
echo "error: a Nightly package requires the prepared version identity" >&2
echo " (X.Y.Z-nightly.YYYYMMDD.RUN.ATTEMPT.gSHA12; set FILMCRAFT_VERSION and FILMCRAFT_BUILD_CHANNEL=nightly-v1)" >&2
exit 2
fi
export FILMCRAFT_BUILD_CHANNEL=nightly-v1
export FILMCRAFT_VERSION="$VERSION"
fi
# The Nightly channel's own icon; stable keeps the hicolor tree.
NIGHTLY_ICON="$ROOT/assets/app-icon/filmcraft-nightly.png"
if [[ "$IS_NIGHTLY" = 1 && ! -f "$NIGHTLY_ICON" ]]; then
echo "error: the Nightly icon $NIGHTLY_ICON is missing" >&2
exit 2
fi
BASENAME="filmcraft-$VERSION-linux-$ARCH"
echo "==> FilmCraft $VERSION for Linux $ARCH ($FORMATS)"
if [[ -n "$ARCH_TAR_DIR" && "$IS_NIGHTLY" != 1 ]]; then
echo "error: --arch-tar-dir is only for Nightly builds" >&2
exit 2
fi
echo "==> FilmCraft $VERSION for Linux $ARCH ($FORMATS, channel=${FILMCRAFT_BUILD_CHANNEL:-stable})"
if [[ "$SKIP_BUILD" = 0 ]]; then
if [[ -n "${CROSS_TARGET:-}" ]]; then
@@ -67,6 +97,11 @@ install -Dm755 "$BIN/filmcraft" "$STAGE/usr/bin/filmcraft"
install -Dm755 "$BIN/filmcraft-cli" "$STAGE/usr/bin/filmcraft-cli"
"${CROSS_COMPILE:-}strip" "$STAGE/usr/bin/filmcraft" "$STAGE/usr/bin/filmcraft-cli" 2>/dev/null || true
install -Dm644 "$HERE/$APP_ID.desktop" "$STAGE/usr/share/applications/$APP_ID.desktop"
if [[ "$IS_NIGHTLY" = 1 ]]; then
sed -e 's|^StartupWMClass=.*|StartupWMClass=ai.storyteller.filmcraft.nightly-v1|' \
"$STAGE/usr/share/applications/$APP_ID.desktop" >"$STAGE/usr/share/applications/$APP_ID.desktop.tmp"
mv "$STAGE/usr/share/applications/$APP_ID.desktop.tmp" "$STAGE/usr/share/applications/$APP_ID.desktop"
fi
install -Dm644 "$HERE/$APP_ID.mime.xml" "$STAGE/usr/share/mime/packages/$APP_ID.xml"
mkdir -p "$STAGE/usr/share/metainfo"
sed -e "s/@VERSION@/$VERSION/g" -e "s/@DATE@/$FILMCRAFT_BUILD_DATE/g" \
@@ -89,18 +124,95 @@ has() { local fmt="$1"; case " $FORMATS " in *" $fmt "*) return 0 ;; *) return 1
if has tar; then
mkdir -p "$WORK/tar"
cp -R "$STAGE/usr" "$WORK/tar/$BASENAME"
if [[ "$IS_NIGHTLY" = 1 ]]; then
# A Nightly binary only starts with its private profile, so an unpacked tarball gets the same
# launcher the other Nightly formats install: `filmcraft` starts `filmcraft-bin`.
mv "$WORK/tar/$BASENAME/bin/filmcraft" "$WORK/tar/$BASENAME/bin/filmcraft-bin"
install -Dm755 "$HERE/nightly-launch.sh" "$WORK/tar/$BASENAME/bin/filmcraft"
fi
install -m755 "$HERE/install.sh" "$WORK/tar/$BASENAME/install.sh"
tar -C "$WORK/tar" -czf "$DIST/$BASENAME.tar.gz" "$BASENAME"
echo "wrote $DIST/$BASENAME.tar.gz"
fi
# The Arch handoff keeps the same basename as the plain tarball in a separate directory.
# Flatpak, OCI and direct tar consumers still get the original binary, not this launcher.
if [[ -n "$ARCH_TAR_DIR" ]]; then
mkdir -p "$ARCH_TAR_DIR"
if [[ "$(cd "$ARCH_TAR_DIR" && pwd -P)" == "$(cd "$DIST" && pwd -P)" ]]; then
echo "error: the Arch tar directory must differ from the release directory" >&2
exit 2
fi
bash "$HERE/nightly-arch-tar.sh" "$STAGE/usr" "$WORK/arch-tar" "$ARCH_TAR_DIR" "$BASENAME"
fi
# ---- .deb / .rpm --------------------------------------------------------------------------------
if has deb || has rpm; then
command -v nfpm >/dev/null || { echo "error: nfpm not found (https://nfpm.goreleaser.com/install/)" >&2; exit 1; }
export VERSION
export NFPM_ARCH="$DEB_ARCH"
NFPM_STAGE="$STAGE"
export NFPM_NAME="filmcraft"
export NFPM_BIN="filmcraft"
export NFPM_CLI="filmcraft-cli"
if [[ "$IS_NIGHTLY" = 1 ]]; then
NIGHTLY_DESK_ID="$APP_ID.nightly-v1"
export NFPM_NAME="filmcraft-nightly"
export NFPM_BIN="filmcraft-nightly"
export NFPM_CLI="filmcraft-nightly-cli"
NFPM_STAGE="$WORK/nfpm-root"
rm -rf "$NFPM_STAGE"
cp -R "$STAGE" "$NFPM_STAGE"
# The GUI lives off PATH, outside the desktop entry and the icon lookup: /usr/bin/filmcraft-nightly
# is the launcher that starts it with the Launcher's private profile, as on every other format.
install -Dm755 "$NFPM_STAGE/usr/bin/filmcraft" "$NFPM_STAGE/usr/lib/filmcraft-nightly/filmcraft"
cat >"$NFPM_STAGE/usr/bin/$NFPM_BIN" <<'WRAPPER'
#!/bin/sh
# FilmCraft Nightly: the GUI runs with the Launcher's private profile, which holds every per-user
# file (preferences, recovery autosaves, media cache, presets, logs, downloaded models).
set -eu
bin=/usr/lib/filmcraft-nightly/filmcraft
profile="${XDG_DATA_HOME:-${HOME:-}/.local/share}/filmcraft-nightly/profile"
# The Launcher's protocol, a bare version query and the usage screen pass through untouched.
case "${1-}" in
--launch-profile | --profile-root | --version | -V | --help | -h) exec "$bin" "$@" ;;
esac
# A caller-written `--` already separates the files from the options: drop it, so the launcher's
# own separator never arrives as a file name.
if [ "${1-}" = -- ]; then shift; fi
exec "$bin" --launch-profile nightly-v1 --profile-root "$profile" -- "$@"
WRAPPER
chmod 755 "$NFPM_STAGE/usr/bin/$NFPM_BIN"
rm -f "$NFPM_STAGE/usr/bin/filmcraft"
mv "$NFPM_STAGE/usr/bin/filmcraft-cli" "$NFPM_STAGE/usr/bin/$NFPM_CLI"
mv "$NFPM_STAGE/usr/share/doc/filmcraft" "$NFPM_STAGE/usr/share/doc/$NFPM_NAME"
sed -e "s#^Exec=filmcraft\([[:space:]]\|$\)#Exec=$NFPM_BIN\1#" \
-e "s|^TryExec=filmcraft$|TryExec=$NFPM_BIN|" \
-e "s|^Icon=$APP_ID$|Icon=$NIGHTLY_DESK_ID|" \
-e "s|^Name=FilmCraft$|Name=FilmCraft Nightly|" \
-e '/^MimeType=/d' \
"$NFPM_STAGE/usr/share/applications/$APP_ID.desktop" >"$NFPM_STAGE/usr/share/applications/$NIGHTLY_DESK_ID.desktop"
rm -f "$NFPM_STAGE/usr/share/applications/$APP_ID.desktop"
sed -e "s|<id>$APP_ID</id>|<id>$NIGHTLY_DESK_ID</id>|g" \
-e "s|<name>FilmCraft</name>|<name>FilmCraft Nightly</name>|g" \
-e "s|<launchable type=\"desktop-id\">$APP_ID.desktop</launchable>|<launchable type=\"desktop-id\">$NIGHTLY_DESK_ID.desktop</launchable>|g" \
-e "s|<icon type=\"stock\">$APP_ID</icon>|<icon type=\"stock\">$NIGHTLY_DESK_ID</icon>|g" \
-e "s|<binary>filmcraft</binary>|<binary>$NFPM_BIN</binary>|g" \
-e '/<mediatype>/d' \
"$NFPM_STAGE/usr/share/metainfo/$APP_ID.metainfo.xml" >"$NFPM_STAGE/usr/share/metainfo/$NIGHTLY_DESK_ID.metainfo.xml"
rm -f "$NFPM_STAGE/usr/share/metainfo/$APP_ID.metainfo.xml"
rm -rf "$NFPM_STAGE/usr/share/mime"
# The Nightly claims no associations, so it registers none and ships its own icon.
rm -rf "$NFPM_STAGE/usr/share/icons/hicolor"
install -Dm644 "$NIGHTLY_ICON" "$NFPM_STAGE/usr/share/icons/hicolor/256x256/apps/$NIGHTLY_DESK_ID.png"
fi
# nfpm expands env vars in fields like `version` and `arch`, but not in `contents[].src`.
sed "s|\${STAGE}|$STAGE|g" "$HERE/nfpm.yaml" >"$WORK/nfpm.yaml"
DROP_LIB_TREE=
# shellcheck disable=SC2016
[[ -d "$NFPM_STAGE/usr/lib" ]] || DROP_LIB_TREE='\|^ - src: \${STAGE}/usr/lib/|,+2d;'
# The drop commands are a prefix of the first expression: with `-e` sed would read them as a file.
# shellcheck disable=SC2016
sed "${DROP_LIB_TREE}s|\${STAGE}|$NFPM_STAGE|g;s|\${NFPM_BIN}|$NFPM_BIN|g;s|\${NFPM_CLI}|$NFPM_CLI|g" "$HERE/nfpm.yaml" >"$WORK/nfpm.yaml"
for fmt in deb rpm; do
if has "$fmt"; then (cd "$ROOT" && nfpm package -f "$WORK/nfpm.yaml" -p "$fmt" -t "$DIST/$BASENAME.$fmt"); fi
done
@@ -124,10 +236,50 @@ if has appimage; then
esac
APPDIR="$WORK/FilmCraft.AppDir"
cp -R "$STAGE" "$APPDIR"
ln -s usr/bin/filmcraft "$APPDIR/AppRun"
cp "$HERE/$APP_ID.desktop" "$APPDIR/$APP_ID.desktop"
cp "$ROOT/assets/app-icon/hicolor/256x256/apps/$APP_ID.png" "$APPDIR/$APP_ID.png"
ln -s "$APP_ID.png" "$APPDIR/.DirIcon"
if [[ "$IS_NIGHTLY" = 1 ]]; then
APPIMAGE_ID="$APP_ID.nightly-v1"
# AppRun is a script here, not a symlink: it registers the Nightly's .desktop entry and icons
# in $XDG_DATA_HOME before launching, so Wayland compositors resolve the window's app_id to our
# icon (logic in packaging/linux/apprun-test.sh). Stable keeps its plain symlink below and, as
# before, installs nothing on start. The desktop id and the channel line below follow: a
# Nightly AppImage must start the app with the Launcher's private profile, not stable's folders
# (AppRun's tail does the exec).
install -Dm755 "$HERE/AppRun" "$APPDIR/AppRun"
awk -v old_id="$APP_ID" -v new_id="$APPIMAGE_ID" '
$0 == "DESK_ID=" old_id { print "DESK_ID=" new_id; next }
$0 == "CHANNEL=stable" { print "CHANNEL=nightly-v1"; next }
{ print }
' "$APPDIR/AppRun" >"$APPDIR/AppRun.tmp"
grep -qx 'CHANNEL=nightly-v1' "$APPDIR/AppRun.tmp" || {
echo "error: AppRun has no CHANNEL=stable line to switch for Nightly" >&2
exit 1
}
mv "$APPDIR/AppRun.tmp" "$APPDIR/AppRun"
chmod 755 "$APPDIR/AppRun"
sed -e "s|^Icon=$APP_ID$|Icon=$APPIMAGE_ID|" \
-e "s|^Name=FilmCraft$|Name=FilmCraft Nightly|" \
-e '/^MimeType=/d' \
"$APPDIR/usr/share/applications/$APP_ID.desktop" >"$APPDIR/usr/share/applications/$APPIMAGE_ID.desktop"
rm -f "$APPDIR/usr/share/applications/$APP_ID.desktop"
cp "$APPDIR/usr/share/applications/$APPIMAGE_ID.desktop" "$APPDIR/$APPIMAGE_ID.desktop"
# The Nightly claims no associations, so its metainfo must not advertise any either.
sed -e "s|<id>$APP_ID</id>|<id>$APPIMAGE_ID</id>|g" \
-e "s|<name>FilmCraft</name>|<name>FilmCraft Nightly</name>|g" \
-e "s|<launchable type=\"desktop-id\">$APP_ID.desktop</launchable>|<launchable type=\"desktop-id\">$APPIMAGE_ID.desktop</launchable>|g" \
-e "s|<icon type=\"stock\">$APP_ID</icon>|<icon type=\"stock\">$APPIMAGE_ID</icon>|g" \
-e '/<mediatype>/d' \
"$APPDIR/usr/share/metainfo/$APP_ID.metainfo.xml" >"$APPDIR/usr/share/metainfo/$APPIMAGE_ID.metainfo.xml"
rm -f "$APPDIR/usr/share/metainfo/$APP_ID.metainfo.xml"
rm -rf "$APPDIR/usr/share/icons/hicolor"
install -Dm644 "$NIGHTLY_ICON" "$APPDIR/usr/share/icons/hicolor/256x256/apps/$APPIMAGE_ID.png"
cp "$NIGHTLY_ICON" "$APPDIR/$APPIMAGE_ID.png"
ln -s "$APPIMAGE_ID.png" "$APPDIR/.DirIcon"
else
ln -s usr/bin/filmcraft "$APPDIR/AppRun"
cp "$HERE/$APP_ID.desktop" "$APPDIR/$APP_ID.desktop"
cp "$ROOT/assets/app-icon/hicolor/256x256/apps/$APP_ID.png" "$APPDIR/$APP_ID.png"
ln -s "$APP_ID.png" "$APPDIR/.DirIcon"
fi
if [[ -z "$RUNTIME_SHA256" ]]; then
echo "no pinned AppImage runtime for $ARCH" >&2
@@ -173,11 +325,20 @@ if has appimage; then
# each AppImage on GitHub Releases. `latest` is the newest published release that is not a
# pre-release. A fork's builds point at its own releases through GITHUB_REPOSITORY.
REPO="${GITHUB_REPOSITORY:-storytold/filmcraft}"
UPDATE_INFO="gh-releases-zsync|${REPO%%/*}|${REPO#*/}|latest|filmcraft-*-linux-$ARCH.AppImage.zsync"
UPDATE_ARGS=()
if [[ "$IS_NIGHTLY" = 0 ]]; then
UPDATE_INFO="gh-releases-zsync|${REPO%%/*}|${REPO#*/}|latest|filmcraft-*-linux-$ARCH.AppImage.zsync"
UPDATE_ARGS=(-u "$UPDATE_INFO")
else
# Nightly releases are GitHub pre-releases (`latest` only selects stable releases), so point
# zsync update metadata at pre-release tags matching `-nightly` rather than stable `latest`.
UPDATE_INFO="gh-releases-zsync|${REPO%%/*}|${REPO#*/}|latest-pre|filmcraft-*-nightly*-linux-$ARCH.AppImage.zsync"
UPDATE_ARGS=(-u "$UPDATE_INFO")
fi
# Extract-and-run: works without FUSE (containers, CI). The output embeds the static runtime,
# so users don't need libfuse2 either. With zsyncmake on the host (CI installs the zsync
# package) appimagetool also writes the .zsync, into its working directory, hence the cd.
(cd "$DIST" && ARCH="$ARCH" APPIMAGE_EXTRACT_AND_RUN=1 "$TOOL" --no-appstream --runtime-file "$RUNTIME" -u "$UPDATE_INFO" "$APPDIR" "$OUT")
(cd "$DIST" && ARCH="$ARCH" APPIMAGE_EXTRACT_AND_RUN=1 "$TOOL" --no-appstream --runtime-file "$RUNTIME" "${UPDATE_ARGS[@]}" "$APPDIR" "$OUT")
echo "wrote $OUT"
if [[ -s "$OUT.zsync" ]]; then
echo "wrote $OUT.zsync"
+73 -1
View File
@@ -85,9 +85,81 @@ class InstallTests(unittest.TestCase):
time.sleep(0.01)
self.assertEqual(launched.read_text().splitlines(), [str(prefix / "bin/filmcraft"), str(document)])
def test_a_nightly_bundle_keeps_an_installed_stable_tree(self):
prefix = self.root / "shared prefix"
stable = self.install("--prefix", prefix)
self.assertEqual(stable.returncode, 0, stable.stderr)
owned = {
path: path.read_bytes()
for path in (
prefix / "bin/filmcraft",
prefix / "bin/filmcraft-cli",
prefix / "share/applications" / f"{APP_ID}.desktop",
prefix / "share/icons/hicolor/test",
prefix / "share/mime/packages/test.xml",
)
}
nightly = self.root / "nightly bundle"
for path in ("bin", "share/applications", "share/icons/hicolor/256x256/apps", "share/doc/filmcraft"):
(nightly / path).mkdir(parents=True)
shutil.copyfile(HERE / "install.sh", nightly / "install.sh")
for name in ("filmcraft", "filmcraft-bin", "filmcraft-cli"):
binary = nightly / "bin" / name
binary.write_text("#!/bin/sh\necho 'nightly fixture'\n")
binary.chmod(0o755)
shutil.copyfile(
HERE / f"{APP_ID}.desktop", nightly / "share/applications" / f"{APP_ID}.desktop"
)
(nightly / "share/icons/hicolor/256x256/apps" / f"{APP_ID}.png").write_bytes(b"nightly icon")
(nightly / "share/doc/filmcraft/NOTICE").write_text("nightly notice\n")
result = subprocess.run(
["bash", str(nightly / "install.sh"), "--prefix", str(prefix)],
cwd=self.root, capture_output=True, text=True, timeout=30,
)
self.assertEqual(result.returncode, 0, result.stderr)
for path, content in owned.items():
self.assertEqual(path.read_bytes(), content, f"{path.name} belongs to the Stable install")
for name in ("filmcraft-nightly", "filmcraft-bin", "filmcraft-nightly-cli"):
self.assertTrue(os.access(prefix / "bin" / name, os.X_OK), name)
entry = prefix / "share/applications" / f"{APP_ID}.nightly-v1.desktop"
text = entry.read_text()
self.assertIn(f'Exec="{prefix}/bin/filmcraft-nightly" %F\n', text)
self.assertIn("Name=FilmCraft Nightly\n", text)
self.assertIn(f"Icon={APP_ID}.nightly-v1\n", text)
self.assertNotIn("MimeType=", text, "a Nightly entry claims no file associations")
self.assertTrue((prefix / "share/icons/hicolor/256x256/apps" / f"{APP_ID}.nightly-v1.png").is_file())
self.assertEqual((prefix / "share/doc/filmcraft-nightly/NOTICE").read_text(), "nightly notice\n")
def test_the_nightly_tarball_stages_what_the_installer_selects(self):
version = "0.0.1-nightly.20251124.1.1.g0123456789ab"
target = self.root / "nightly-target"
binaries = target / "release"
binaries.mkdir(parents=True)
for name in ("filmcraft", "filmcraft-cli"):
binary = binaries / name
binary.write_text("#!/bin/sh\necho 'FilmCraft fixture'\n")
binary.chmod(0o755)
dist = self.root / "nightly-dist"
result = subprocess.run(
["bash", str(HERE / "package.sh"), "--skip-build", "--formats", "tar"],
env={**os.environ, "CARGO_TARGET_DIR": str(target), "DIST": str(dist),
"FILMCRAFT_BUILD_CHANNEL": "nightly-v1", "FILMCRAFT_VERSION": version},
capture_output=True, text=True, timeout=120,
)
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
base = f"filmcraft-{version}-linux-x86_64"
with tarfile.open(dist / f"{base}.tar.gz") as archive:
names = set(archive.getnames())
# The installer picks the Nightly layout from the GUI beside the launcher, and rewrites the
# Stable-named entry it stages into the Nightly's own id.
self.assertIn(f"{base}/bin/filmcraft", names)
self.assertIn(f"{base}/bin/filmcraft-bin", names)
self.assertIn(f"{base}/share/applications/{APP_ID}.desktop", names)
def test_invalid_arguments_fail_before_writing(self):
for args in (("--prefix",), ("--prefix", "relative"), ("--prefix", "/"), ("--unknown",),
("--prefix", "///"), ("--prefix", "/tmp/../"), ("--prefix", str(self.bundle)),
("--prefix", "///"), ("--prefix", tempfile.gettempdir() + "/../"),
("--prefix", str(self.bundle)),
("--prefix", str(self.bundle / "nested")),
("--prefix", str(self.root / "bad=path")),
("--prefix", str(self.root / "bad%path")),
+110
View File
@@ -0,0 +1,110 @@
# shellcheck shell=bash
# Shared checks for the Apple-silicon Nightly scripts (nightly.sh, nightly-sign.sh, nightly-verify.sh).
# Stable packaging (package.sh, verify.sh) does not source this file. The text checks take tool output
# as arguments, so packaging/macos/nightly_sign_tests.py runs them without macOS.
MAC_NIGHTLY_APP='FilmCraft Nightly.app'
MAC_NIGHTLY_ID='ai.storyteller.filmcraft.nightly'
# The release environment's names, as stable release.yml passes them (packaging/macos/import-cert.sh).
MAC_NIGHTLY_SECRETS=(APPLE_CERTIFICATE APPLE_CERTIFICATE_PASSWORD KEYCHAIN_PASSWORD APPLE_ID APPLE_PASSWORD APPLE_TEAM_ID)
mac_nightly_die() { printf 'error: %s\n' "$*" >&2; exit 2; }
# The exact prepared version from the feed asset name, or failure.
mac_nightly_version_from_asset() {
local name="$1" version
[[ "$name" =~ ^filmcraft-(.+)-macos-aarch64-nightly\.zip$ ]] || return 1
version="${BASH_REMATCH[1]}"
[[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+-nightly\.[0-9]{8}\.[0-9]+\.[0-9]+\.g[0-9a-f]{12}$ ]] || return 1
printf '%s\n' "$version"
}
# Every signing and notarization value is set, and the team is one Apple team ID. No ad-hoc fallback.
mac_nightly_require_secrets() {
local name
for name in "${MAC_NIGHTLY_SECRETS[@]}"; do
[[ -n "${!name:-}" ]] || mac_nightly_die "$name is not set: Nightly signing and notarization are required, with no ad-hoc fallback"
done
[[ "$APPLE_TEAM_ID" =~ ^[A-Z0-9]{10}$ ]] || mac_nightly_die 'APPLE_TEAM_ID is not an Apple team ID'
if [[ -n "${NIGHTLY_APPLE_TEAM_ID:-}" && "$NIGHTLY_APPLE_TEAM_ID" != "$APPLE_TEAM_ID" ]]; then
mac_nightly_die 'the signing team differs from the reviewed Nightly team (NIGHTLY_APPLE_TEAM_ID)'
fi
}
# One line of `security find-identity -v -p codesigning`: the identity is a Developer ID Application of the team.
mac_nightly_identity_is_team() {
local line="$1" identity="$2" team="$3"
[[ "$line" == *" $identity "* && "$line" == *'"Developer ID Application: '*" ($team)\""* ]]
}
# `codesign -d --verbose=2` of the signed bundle: the Nightly identifier, a Developer ID Application of the
# team, a secure timestamp and the hardened runtime (the checks of verify.sh, made strict).
mac_nightly_check_signature() {
local details="$1" team="$2" ok=0
grep -Fqx "Identifier=$MAC_NIGHTLY_ID" <<<"$details" || { echo "error: the bundle is not signed as $MAC_NIGHTLY_ID" >&2; ok=1; }
grep -q '^Authority=Developer ID Application:' <<<"$details" || { echo 'error: not signed with a Developer ID Application identity' >&2; ok=1; }
grep -qx "TeamIdentifier=$team" <<<"$details" || { echo 'error: signed by a different team' >&2; ok=1; }
grep -q '^Timestamp=' <<<"$details" || { echo 'error: the signature has no secure timestamp' >&2; ok=1; }
grep -Eq '^CodeDirectory .*flags=0x[0-9a-f]+\([^)]*runtime' <<<"$details" || { echo 'error: not signed with the hardened runtime' >&2; ok=1; }
return "$ok"
}
# `spctl --assess --type execute -vv`: Gatekeeper accepts the bundle as notarized.
mac_nightly_check_assessment() {
grep -q 'accepted' <<<"$1" && grep -qx 'source=Notarized Developer ID' <<<"$1"
}
# Before anything is unpacked: every ZIP entry is a regular file or directory inside the one Nightly
# bundle, with no absolute path, `..`, backslash or empty component, and no link or special file.
mac_nightly_check_zip_entries() {
python3 -I - "$1" "$MAC_NIGHTLY_APP" <<'PY' || mac_nightly_die 'the archive has an entry outside the bundle, a link or a special file'
import stat, sys, zipfile
archive, app = sys.argv[1:]
with zipfile.ZipFile(archive) as z:
for info in z.infolist():
name = info.filename
parts = name.rstrip("/").split("/")
mode = info.external_attr >> 16
if (name.startswith("/") or "\\" in name or "\0" in name or parts[0] != app
or any(part in ("", ".", "..") for part in parts)
or stat.S_IFMT(mode) not in (0, stat.S_IFREG, stat.S_IFDIR)):
sys.exit(f"refused entry: {name!r}")
PY
}
# An unpacked payload directory holds exactly the GUI-only Nightly bundle: one thin arm64 FilmCraft
# executable, the Nightly identity and the exact version (no numeric fallback), no CLI, no links or special
# files, no document or URL types.
mac_nightly_check_bundle() {
local payload="$1" version="$2" app entries plist key value
app="$payload/$MAC_NIGHTLY_APP"
entries="$(ls -A "$payload")"
[[ "$entries" == "$MAC_NIGHTLY_APP" && -d "$app" && ! -L "$app" ]] || mac_nightly_die "the archive must hold exactly $MAC_NIGHTLY_APP"
[[ -z "$(find "$payload" ! -type f ! -type d -print -quit)" ]] || mac_nightly_die 'the bundle contains links or special files'
[[ "$(ls -A "$app/Contents/MacOS")" == FilmCraft ]] || mac_nightly_die 'Contents/MacOS must hold only the FilmCraft GUI (no CLI)'
[[ -f "$app/Contents/MacOS/FilmCraft" && -x "$app/Contents/MacOS/FilmCraft" ]] || mac_nightly_die 'missing executable GUI'
[[ "$(lipo -archs "$app/Contents/MacOS/FilmCraft")" == arm64 ]] || mac_nightly_die 'the GUI must be thin arm64'
plist="$app/Contents/Info.plist"
for key in CFBundleIdentifier CFBundleExecutable FilmCraftVersion; do
value="$(plutil -extract "$key" raw -o - "$plist")" || mac_nightly_die "Info.plist has no $key"
case "$key" in
CFBundleIdentifier) [[ "$value" == "$MAC_NIGHTLY_ID" ]] ;;
CFBundleExecutable) [[ "$value" == FilmCraft ]] ;;
FilmCraftVersion) [[ "$value" == "$version" ]] ;;
esac || mac_nightly_die "Info.plist $key is not the prepared Nightly identity"
done
for key in CFBundleDocumentTypes CFBundleURLTypes UTExportedTypeDeclarations UTImportedTypeDeclarations; do
if plutil -extract "$key" xml1 -o - "$plist" >/dev/null 2>&1; then mac_nightly_die "Nightly declares $key"; fi
done
}
# `stapler validate` asks Apple's CloudKit service, which sometimes drops the connection (error 68)
# though the ticket is there (verify.sh).
mac_nightly_validate_staple() {
local target="$1" attempt
for attempt in 1 2 3 4 5; do
xcrun stapler validate "$target" && return 0
[[ "$attempt" = 5 ]] || sleep $((attempt * 20))
done
return 1
}
+140
View File
@@ -0,0 +1,140 @@
#!/usr/bin/env bash
# Trusted signing step for the Apple-silicon Nightly, the stable release's macOS signing route
# (import-cert.sh, then package.sh's codesign, notarytool and stapler steps):
#
# nightly-sign.sh --arch aarch64 --input /abs/filmcraft-<version>-macos-aarch64-nightly.zip \
# --output /abs/<dir>/filmcraft-<version>-macos-aarch64-nightly.zip
#
# Input: the unsigned archive nightly.sh made. Output: the same bundle signed with the Developer ID and
# hardened runtime, notarized, with the ticket stapled into the bundle, zipped without extended
# attributes. Writes only that file, never replacing one; the temporary keychain and work directory
# are removed on every exit.
#
# Env (all required, no ad-hoc or unnotarized fallback): APPLE_CERTIFICATE, APPLE_CERTIFICATE_PASSWORD,
# KEYCHAIN_PASSWORD, APPLE_ID, APPLE_PASSWORD, APPLE_TEAM_ID; optional NIGHTLY_APPLE_TEAM_ID (must
# equal APPLE_TEAM_ID) and RUNNER_TEMP (work directory base).
#
# Never compiles, and never runs anything from the payload: the version query runs on the signed
# bundle in a job without secrets (nightly-verify.sh).
set -euo pipefail
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=nightly-lib.sh
. "$HERE/nightly-lib.sh"
# shellcheck source=../nightly-common.sh
. "$HERE/../nightly-common.sh"
ARCH='' INPUT='' OUTPUT=''
while [[ $# -gt 0 ]]; do
case "$1" in
--arch | --input | --output)
[[ $# -ge 2 ]] || mac_nightly_die "missing $1 value"
case "$1" in --arch) ARCH="$2" ;; --input) INPUT="$2" ;; --output) OUTPUT="$2" ;; esac
shift 2 ;;
-h | --help) sed -n '2,18p' "$0"; exit 0 ;;
*) mac_nightly_die "unsupported argument: $1" ;;
esac
done
[[ "$ARCH" == aarch64 ]] || mac_nightly_die 'only --arch aarch64 is supported'
[[ "$INPUT" == /* && "$OUTPUT" == /* ]] || mac_nightly_die '--input and --output must be absolute paths'
NAME="$(basename -- "$INPUT")"
VERSION="$(mac_nightly_version_from_asset "$NAME")" || mac_nightly_die 'the input is not a prepared Nightly archive name'
[[ "$(basename -- "$OUTPUT")" == "$NAME" ]] || mac_nightly_die 'the output must keep the archive name'
[[ -f "$INPUT" && ! -L "$INPUT" ]] || mac_nightly_die 'the input must be a regular file'
[[ ! -e "$OUTPUT" && ! -L "$OUTPUT" ]] || mac_nightly_die 'refusing to replace an existing output'
[[ -d "$(dirname -- "$OUTPUT")" && ! -L "$(dirname -- "$OUTPUT")" ]] || mac_nightly_die 'the output directory must exist'
mac_nightly_require_secrets
[[ "$(uname -s)" == Darwin ]] || mac_nightly_die 'signing needs macOS (codesign, notarytool, stapler)'
BASE="${RUNNER_TEMP:-${TMPDIR:-/tmp}}"
WORK="$(mktemp -d "${BASE%/}/filmcraft-nightly-sign.XXXXXX")"
KEYCHAIN="$WORK/filmcraft-signing.keychain-db"
cleanup() {
if [[ -e "$KEYCHAIN" ]]; then security delete-keychain "$KEYCHAIN" >/dev/null 2>&1 || rm -f -- "$KEYCHAIN"; fi
rm -rf -- "$WORK"
}
trap cleanup EXIT
# ---- identity: import-cert.sh, into this run's private directory ------------------------------
# An empty GITHUB_ENV makes it print the identity instead of exporting it to later steps.
imported="$(GITHUB_ENV='' RUNNER_TEMP="$WORK" DIST="$WORK/dist" bash "$HERE/import-cert.sh")"
IDENTITY="$(sed -n 's/^MACOS_SIGN_IDENTITY=//p' <<<"$imported")"
[[ "$IDENTITY" =~ ^[0-9A-F]{40}$ && "$(sed -n 's/^MACOS_KEYCHAIN=//p' <<<"$imported")" == "$KEYCHAIN" ]] \
|| mac_nightly_die 'import-cert.sh did not import a signing identity'
mac_nightly_identity_is_team "$(security find-identity -v -p codesigning "$KEYCHAIN" | grep -F " $IDENTITY " || true)" "$IDENTITY" "$APPLE_TEAM_ID" \
|| mac_nightly_die "the imported identity is not a Developer ID Application of team $APPLE_TEAM_ID"
echo "==> FilmCraft Nightly $VERSION for macOS (aarch64), identity: $IDENTITY"
# ---- the unsigned bundle ---------------------------------------------------------------------------
mac_nightly_check_zip_entries "$INPUT"
ditto -x -k --norsrc --noextattr "$INPUT" "$WORK/payload"
mac_nightly_check_bundle "$WORK/payload" "$VERSION"
APP="$WORK/payload/$MAC_NIGHTLY_APP"
# ---- package.sh's signing and notarization, with a required Developer ID ---------------------------
sign() {
codesign --force --sign "$IDENTITY" --keychain "$KEYCHAIN" --timestamp "$@"
}
notarize() {
local file="$1" out id status
echo "==> notarizing $(basename "$file") (this can take a few minutes)"
out="$(xcrun notarytool submit "$file" --apple-id "$APPLE_ID" --password "$APPLE_PASSWORD" \
--team-id "$APPLE_TEAM_ID" --wait --timeout 1h --output-format json)" || true
echo "$out"
id="$(printf '%s' "$out" | plutil -extract id raw -o - - 2>/dev/null || true)"
status="$(printf '%s' "$out" | plutil -extract status raw -o - - 2>/dev/null || true)"
if [[ "$status" != "Accepted" ]]; then
if [[ -n "$id" ]]; then
# Capped: the shared signer bounds a step's output at 256 KiB.
xcrun notarytool log "$id" --apple-id "$APPLE_ID" --password "$APPLE_PASSWORD" --team-id "$APPLE_TEAM_ID" | head -c 131072 || true
fi
echo "error: notarization of $(basename "$file") failed (status: ${status:-unknown})" >&2
exit 1
fi
}
# Stapling and validating both look the ticket up in Apple's CloudKit service, which can drop the
# connection right after notarization (error 68), so retry the pair (package.sh).
staple() {
local file="$1" attempt
for attempt in 1 2 3 4 5; do
if xcrun stapler staple "$file" && xcrun stapler validate "$file"; then
return
fi
if [[ "$attempt" = 5 ]]; then
echo "error: stapling $(basename "$file") failed after $attempt attempts" >&2
exit 1
fi
echo "stapling $(basename "$file") failed (attempt $attempt); retrying in $((attempt * 20))s" >&2
sleep $((attempt * 20))
done
}
# Inside-out: the executable, then the bundle (no --deep on the final signature).
sign --options runtime --entitlements "$HERE/entitlements.plist" "$APP/Contents/MacOS/FilmCraft"
sign --options runtime --entitlements "$HERE/entitlements.plist" "$APP"
codesign --verify --strict --deep --verbose=2 "$APP"
ditto -c -k --keepParent "$APP" "$WORK/notarize.zip"
notarize "$WORK/notarize.zip"
# The ticket goes into the bundle (Contents/CodeResources): the Launcher's extract restores no xattrs.
staple "$APP"
# ---- the final archive, checked as the Launcher unpacks it -----------------------------------------
ditto -c -k --norsrc --noextattr --noacl --keepParent "$APP" "$WORK/final.zip"
ditto -x -k --norsrc --noextattr "$WORK/final.zip" "$WORK/check"
mac_nightly_check_bundle "$WORK/check" "$VERSION"
CHECK="$WORK/check/$MAC_NIGHTLY_APP"
codesign --verify --strict --deep --verbose=2 "$CHECK"
mac_nightly_check_signature "$(codesign -d --verbose=2 "$CHECK" 2>&1)" "$APPLE_TEAM_ID" \
|| mac_nightly_die 'the signed bundle is not the required Developer ID signature'
mac_nightly_validate_staple "$CHECK" || mac_nightly_die 'no notarization ticket is stapled into the bundle'
# spctl's lookup can lag a few seconds behind notarytool's "Accepted" (verify.sh).
for attempt in 1 2 3 4 5; do
assessment="$(spctl --assess --type execute -vv "$CHECK" 2>&1)" || true
mac_nightly_check_assessment "$assessment" && break
[[ "$attempt" = 5 ]] || sleep 10
done
printf '%s\n' "$assessment"
mac_nightly_check_assessment "$assessment" || mac_nightly_die 'Gatekeeper does not accept the bundle as notarized'
nightly_publish_archive "$WORK/final.zip" "$OUTPUT"
+74
View File
@@ -0,0 +1,74 @@
#!/usr/bin/env bash
# Check an Apple-silicon Nightly archive as the Launcher unpacks it, then ask the GUI its version.
# For a job without signing material (it refuses to run with any), after nightly-sign.sh:
#
# nightly-verify.sh --input /abs/filmcraft-<version>-macos-aarch64-nightly.zip --expect signed [--team ID]
# nightly-verify.sh --input /abs/filmcraft-<version>-macos-aarch64-nightly.zip --expect unsigned
#
# Both: the archive holds only the GUI-only Nightly bundle with the exact FilmCraftVersion, unpacked
# without extended attributes. `signed` (the feed artifact): Developer ID of the team (--team, else
# NIGHTLY_APPLE_TEAM_ID), hardened runtime, secure timestamp, stapled ticket, Gatekeeper accepts it as
# notarized. `unsigned` (nightly.sh's compile output, e.g. pull-request CI) checks no signature.
# Last, the bundle's GUI answers its version query with an empty environment, both plainly and in the
# Launcher's form `--launch-profile nightly-v1 --profile-root <fresh dir> --version` (the shared producer
# smoke): each must exit 0 within 15 seconds, print exactly `FilmCraft <version> (nightly-v1)` and
# write nothing to standard error.
set -euo pipefail
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=nightly-lib.sh
. "$HERE/nightly-lib.sh"
INPUT='' EXPECT='' TEAM="${NIGHTLY_APPLE_TEAM_ID:-}"
while [[ $# -gt 0 ]]; do
case "$1" in
--input | --expect | --team)
[[ $# -ge 2 ]] || mac_nightly_die "missing $1 value"
case "$1" in --input) INPUT="$2" ;; --expect) EXPECT="$2" ;; --team) TEAM="$2" ;; esac
shift 2 ;;
-h | --help) sed -n '2,15p' "$0"; exit 0 ;;
*) mac_nightly_die "unsupported argument: $1" ;;
esac
done
for name in "${MAC_NIGHTLY_SECRETS[@]}" MACOS_SIGN_IDENTITY MACOS_KEYCHAIN; do
[[ -z "${!name:-}" ]] || mac_nightly_die "refusing to run the payload with signing material in the environment ($name)"
done
[[ "$EXPECT" == signed || "$EXPECT" == unsigned ]] || mac_nightly_die '--expect must be signed or unsigned'
[[ "$EXPECT" == unsigned || "$TEAM" =~ ^[A-Z0-9]{10}$ ]] || mac_nightly_die 'a signed check needs the Apple team ID (--team or NIGHTLY_APPLE_TEAM_ID)'
[[ "$INPUT" == /* && -f "$INPUT" && ! -L "$INPUT" ]] || mac_nightly_die '--input must be an absolute regular file'
VERSION="$(mac_nightly_version_from_asset "$(basename -- "$INPUT")")" || mac_nightly_die 'the input is not a prepared Nightly archive name'
[[ "$(uname -s)" == Darwin && "$(uname -m)" == arm64 ]] || mac_nightly_die 'needs an Apple silicon Mac'
WORK="$(mktemp -d "${RUNNER_TEMP:-${TMPDIR:-/tmp}}/filmcraft-nightly-verify.XXXXXX")"
trap 'rm -rf -- "$WORK"' EXIT
mac_nightly_check_zip_entries "$INPUT"
ditto -x -k --norsrc --noextattr "$INPUT" "$WORK/payload"
mac_nightly_check_bundle "$WORK/payload" "$VERSION"
APP="$WORK/payload/$MAC_NIGHTLY_APP"
if [[ "$EXPECT" == signed ]]; then
codesign --verify --strict --deep --verbose=2 "$APP"
mac_nightly_check_signature "$(codesign -d --verbose=2 "$APP" 2>&1)" "$TEAM" \
|| mac_nightly_die 'the bundle is not the required Developer ID signature'
mac_nightly_validate_staple "$APP" || mac_nightly_die 'no notarization ticket is stapled into the bundle'
for attempt in 1 2 3 4 5; do
assessment="$(spctl --assess --type execute -vv "$APP" 2>&1)" || true
mac_nightly_check_assessment "$assessment" && break
[[ "$attempt" = 5 ]] || sleep 10
done
printf '%s\n' "$assessment"
mac_nightly_check_assessment "$assessment" || mac_nightly_die 'Gatekeeper does not accept the bundle as notarized'
fi
# macOS has no timeout(1): perl's alarm survives its exec and ends a query that hangs (a dialog, say).
query() {
local out
out="$(env -i HOME="$WORK/home" TMPDIR="$WORK/tmp/" PATH=/usr/bin:/bin \
/usr/bin/perl -e 'alarm 15; exec @ARGV or die' "$APP/Contents/MacOS/FilmCraft" "$@" 2>"$WORK/stderr")" \
|| mac_nightly_die "the version query ($*) failed or did not finish within 15 s"
[[ ! -s "$WORK/stderr" ]] || mac_nightly_die "the version query ($*) wrote to standard error: $(head -c 2000 "$WORK/stderr")"
[[ "$out" == "FilmCraft $VERSION (nightly-v1)" ]] || mac_nightly_die "the version query ($*) reports '$out', not FilmCraft $VERSION (nightly-v1)"
}
mkdir -m 700 "$WORK/home" "$WORK/tmp" "$WORK/profile"
query --version
query --launch-profile nightly-v1 --profile-root "$WORK/profile" --version
echo "==> verified ($EXPECT): FilmCraft $VERSION (nightly-v1), plain and in the Launcher's profile form"
+51
View File
@@ -0,0 +1,51 @@
#!/usr/bin/env bash
# App-owned GUI-only Nightly for Apple silicon, compile step only (no signing material):
#
# $DIST/filmcraft-<version>-macos-aarch64-nightly.zip FilmCraft Nightly.app, unsigned
#
# Usage: packaging/macos/nightly.sh --arch aarch64
#
# Required env (nightly-common.sh): FILMCRAFT_BUILD_CHANNEL=nightly-v1, FILMCRAFT_VERSION,
# FILMCRAFT_BUILD_SHA, FILMCRAFT_BUILD_DATE, absolute CARGO_TARGET_DIR and DIST; CRAFT_FONTS_DIR optional.
#
# Not publishable by itself: the trusted step (nightly-sign.sh) signs, notarizes and staples it. No CLI,
# DMG, document or URL types, and no stable package.sh. The bundle is not run here; the version query
# runs on the signed bundle (nightly-verify.sh).
set -euo pipefail
ARCH=
while [[ $# -gt 0 ]]; do
case "$1" in
--arch) [[ $# -ge 2 ]] || { echo 'missing --arch value' >&2; exit 2; }; ARCH="$2"; shift 2 ;;
-h|--help) sed -n '2,13p' "$0"; exit 0 ;;
*) echo "unsupported nightly argument: $1" >&2; exit 2 ;;
esac
done
[[ "$ARCH" == aarch64 && "$(uname -s)" == Darwin && "$(uname -m)" == arm64 ]] || { echo 'only native macOS aarch64 nightly packaging is supported' >&2; exit 2; }
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
. "$HERE/../nightly-common.sh"
. "$HERE/nightly-lib.sh"
nightly_refuse_signing_env
nightly_init macos "$ARCH" aarch64-apple-darwin
# Keep in sync with LSMinimumSystemVersion in Info.plist.in (as package.sh).
export MACOSX_DEPLOYMENT_TARGET=11.0
OUTPUT="$DIST/filmcraft-$VERSION-macos-aarch64-nightly.zip"
[[ ! -e "$OUTPUT" && ! -L "$OUTPUT" ]] || nightly_die 'refusing to replace an existing nightly archive'
nightly_compile_gui
APP="$NIGHTLY_WORK/stage/$MAC_NIGHTLY_APP"
mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources"
cp "$NIGHTLY_GUI" "$APP/Contents/MacOS/FilmCraft"
chmod 755 "$APP/Contents/MacOS/FilmCraft"
cp "$ROOT/assets/app-icon/filmcraft-nightly.icns" "$APP/Contents/Resources/filmcraft-nightly.icns"
nightly_copy_notices "$APP/Contents/Resources"
# The private mktemp cwd is the helper authority root: stage the template inside it.
cp "$HERE/Info.plist.in" "$NIGHTLY_WORK/Info.plist.in"
(cd "$NIGHTLY_WORK" && python3 "$HERE/nightly_plist.py" --template Info.plist.in \
--output "stage/$MAC_NIGHTLY_APP/Contents/Info.plist" --version "$VERSION" --source-commit "$FILMCRAFT_BUILD_SHA")
plutil -lint "$APP/Contents/Info.plist"
printf 'APPL????' >"$APP/Contents/PkgInfo"
mac_nightly_check_bundle "$NIGHTLY_WORK/stage" "$VERSION"
# No resource forks, extended attributes or ACLs: the Launcher restores none, so nothing may depend on them.
ditto -c -k --norsrc --noextattr --noacl --keepParent "$APP" "$NIGHTLY_WORK/archive.zip"
nightly_publish_archive "$NIGHTLY_WORK/archive.zip" "$OUTPUT"
+69
View File
@@ -0,0 +1,69 @@
#!/usr/bin/env python3
"""Nightly metadata: run from a private owned build cwd with a staged template.
All file arguments must stay beneath that cwd; this is not native/signing acceptance.
"""
import argparse
import datetime
import os
from pathlib import Path
import plistlib
import re
import sys
# The shared helper location is fixed by this script, not by CLI file arguments.
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from nightly_paths import OwnedBuildRoot
MAX_TEMPLATE_BYTES = 256 * 1024
IDENTIFIER = "ai.storyteller.filmcraft.nightly"
ASSOCIATIONS = ("CFBundleDocumentTypes", "CFBundleURLTypes", "UTExportedTypeDeclarations", "UTImportedTypeDeclarations")
VERSION = re.compile(r"([0-9]+\.[0-9]+\.[0-9]+)-nightly\.([0-9]{8})\.[0-9]+\.[0-9]+\.g([0-9a-f]{12})\Z")
def render(template: bytes, version: str, commit: str) -> bytes:
match = VERSION.fullmatch(version)
if not match or not re.fullmatch(r"[0-9a-f]{40}", commit) or match[3] != commit[:12]:
raise ValueError("exact prepared Nightly version and matching source commit are required")
datetime.datetime.strptime(match[2], "%Y%m%d")
data = plistlib.loads(template)
if not isinstance(data, dict) or data.get("CFBundlePackageType") != "APPL":
raise ValueError("expected the app-owned application plist template")
for key in ASSOCIATIONS:
data.pop(key, None)
data.update(
CFBundleDisplayName="FilmCraft Nightly",
CFBundleName="FilmCraft Nightly",
CFBundleIdentifier=IDENTIFIER,
CFBundleExecutable="FilmCraft",
CFBundleIconFile="filmcraft-nightly",
CFBundleShortVersionString=match[1],
CFBundleVersion=match[1],
FilmCraftVersion=version,
FilmCraftBuildCommit=commit,
)
return plistlib.dumps(data, fmt=plistlib.FMT_XML, sort_keys=False)
def write_plist(template: Path, destination: Path, version: str, commit: str) -> None:
with OwnedBuildRoot() as root:
content = render(root.read_bytes(template, MAX_TEMPLATE_BYTES), version, commit)
with root.create(destination) as stream:
stream.write(content)
stream.flush()
os.fsync(stream.fileno())
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--template", type=Path, required=True)
parser.add_argument("--output", type=Path, required=True)
parser.add_argument("--version", required=True)
parser.add_argument("--source-commit", required=True)
args = parser.parse_args()
write_plist(args.template, args.output, args.version, args.source_commit)
if __name__ == "__main__":
main()
+202
View File
@@ -0,0 +1,202 @@
#!/usr/bin/env python3
"""Generated metadata/sentinel fixtures; no native binary, signature, archive or network."""
import importlib.util
import os
from pathlib import Path
import plistlib
import runpy
import sys
from unittest import mock
import tempfile
import unittest
HERE = Path(__file__).resolve().parent
SPEC = importlib.util.spec_from_file_location("photo_nightly_plist", HERE / "nightly_plist.py")
POLICY = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(POLICY)
COMMIT = "a" * 40
VERSION = "0.23.1-nightly.20261121.12345.1.g" + COMMIT[:12]
class NightlyMetadata(unittest.TestCase):
def setUp(self):
self.directory = tempfile.TemporaryDirectory()
self.addCleanup(self.directory.cleanup)
self.root = Path(self.directory.name).resolve()
previous = Path.cwd()
os.chdir(self.root)
self.addCleanup(os.chdir, previous)
self.template = self.root / "Info.plist.in"
self.original = (HERE / "Info.plist.in").read_bytes()
self.template.write_bytes(self.original)
self.output = self.root / "Info.plist"
def test_nightly_transform_removes_associations_without_changing_stable_or_platform_metadata(self):
stable = plistlib.loads(self.original)
stable["CFBundleURLTypes"] = [{"CFBundleURLSchemes": ["generated-test-scheme"]}]
prepared = plistlib.dumps(stable)
self.template.write_bytes(prepared)
POLICY.write_plist(self.template, self.output, VERSION, COMMIT)
rendered = plistlib.loads(self.output.read_bytes())
for key in POLICY.ASSOCIATIONS:
self.assertNotIn(key, rendered)
self.assertNotEqual(rendered["CFBundleIdentifier"], stable["CFBundleIdentifier"])
self.assertEqual(rendered["CFBundleIdentifier"], "ai.storyteller.filmcraft.nightly")
self.assertEqual(rendered["CFBundleExecutable"], "FilmCraft")
self.assertEqual(rendered["FilmCraftVersion"], VERSION)
self.assertEqual(rendered["FilmCraftBuildCommit"], COMMIT)
self.assertTrue(VERSION.startswith(rendered["CFBundleVersion"] + "-nightly."))
for key in ("LSMinimumSystemVersion", "CFBundleLocalizations", "NSHighResolutionCapable", "NSHumanReadableCopyright"):
self.assertEqual(rendered[key], stable[key])
self.assertEqual(self.template.read_bytes(), prepared)
self.assertEqual((HERE / "Info.plist.in").read_bytes(), self.original)
def test_bad_identity_or_template_refuses_before_creating_output(self):
for version, commit in (("0.23.1", COMMIT), (VERSION, "b" * 40), (VERSION, "not-a-commit"), (VERSION.replace("20261121", "20261399"), COMMIT)):
with self.subTest(version=version, commit=commit):
with self.assertRaises(ValueError):
POLICY.write_plist(self.template, self.output, version, commit)
self.assertFalse(self.output.exists())
self.assertEqual(self.template.read_bytes(), self.original)
self.template.write_bytes(plistlib.dumps({"CFBundlePackageType": "generated-not-an-app"}))
with self.assertRaises(ValueError):
POLICY.write_plist(self.template, self.output, VERSION, COMMIT)
self.assertFalse(self.output.exists())
def test_cli_writes_the_requested_identity_without_replacing_the_template(self):
helper = HERE / "nightly_plist.py"
argv = [str(helper), "--template", str(self.template), "--output", str(self.output), "--version", VERSION, "--source-commit", COMMIT]
with mock.patch.object(sys, "argv", argv):
runpy.run_path(str(helper), run_name="__main__")
result = plistlib.loads(self.output.read_bytes())
self.assertEqual(result["FilmCraftVersion"], VERSION)
self.assertEqual(result["FilmCraftBuildCommit"], COMMIT)
self.assertEqual(self.template.read_bytes(), self.original)
def test_template_alias_or_nonfile_refuses_before_output(self):
alias = self.root / "template-alias"
alias.symlink_to(self.template)
for template in (alias, self.root, self.root / "missing-template"):
with self.subTest(template=template), self.assertRaises(ValueError):
POLICY.write_plist(template, self.output, VERSION, COMMIT)
self.assertFalse(self.output.exists())
self.assertEqual(self.template.read_bytes(), self.original)
def test_failed_write_cleans_owned_output_but_preserves_a_replacement(self):
sentinel = b"generated replacement artifact"
for disposition in ("owned", "missing", "replacement"):
with self.subTest(disposition=disposition):
if self.output.exists():
self.output.unlink()
def fail_sync(_descriptor):
# macOS/Linux allow unlink of an open file: exercise the real
# cleanup ownership check, not a mocked inode comparison.
if disposition != "owned":
self.output.unlink()
if disposition == "replacement":
self.output.write_bytes(sentinel)
raise OSError("generated fsync failure")
with mock.patch.object(POLICY.os, "fsync", side_effect=fail_sync), self.assertRaises(OSError):
POLICY.write_plist(self.template, self.output, VERSION, COMMIT)
if disposition == "replacement":
self.assertEqual(self.output.read_bytes(), sentinel)
else:
self.assertFalse(self.output.exists())
self.assertEqual(self.template.read_bytes(), self.original)
def test_exclusive_output_preserves_existing_bytes_and_symlink_targets(self):
sentinel = b"generated owned sentinel, not an existing app or user file"
self.output.write_bytes(sentinel)
with self.assertRaises(FileExistsError):
POLICY.write_plist(self.template, self.output, VERSION, COMMIT)
self.assertEqual(self.output.read_bytes(), sentinel)
self.output.unlink()
external = self.root / "sentinel"
external.write_bytes(sentinel)
self.output.symlink_to(external)
with self.assertRaisesRegex(ValueError, "symlinks or aliases"):
POLICY.write_plist(self.template, self.output, VERSION, COMMIT)
self.assertEqual(external.read_bytes(), sentinel)
self.assertTrue(self.output.is_symlink())
def test_template_outside_build_root_refuses_before_output(self):
with tempfile.TemporaryDirectory() as external:
template = Path(external) / "Info.plist.in"
template.write_bytes(self.original)
with self.assertRaises(ValueError):
POLICY.write_plist(template, self.output, VERSION, COMMIT)
self.assertFalse(self.output.exists())
self.assertEqual(template.read_bytes(), self.original)
def test_output_outside_build_root_refuses_before_write(self):
with tempfile.TemporaryDirectory() as external:
output = Path(external) / "Info.plist"
with self.assertRaises(ValueError):
POLICY.write_plist(self.template, output, VERSION, COMMIT)
self.assertFalse(output.exists())
def test_parent_traversal_refuses_even_to_an_owned_sibling(self):
with tempfile.TemporaryDirectory(dir=self.root.parent) as external:
output = Path("..") / Path(external).name / "Info.plist"
with self.assertRaises(ValueError):
POLICY.write_plist(self.template, output, VERSION, COMMIT)
self.assertFalse((Path(external) / "Info.plist").exists())
def test_symlinked_output_parent_refuses(self):
with tempfile.TemporaryDirectory() as external:
alias = self.root / "alias"
alias.symlink_to(external, target_is_directory=True)
with self.assertRaises(ValueError):
POLICY.write_plist(self.template, alias / "Info.plist", VERSION, COMMIT)
self.assertFalse((Path(external) / "Info.plist").exists())
def test_template_read_is_bounded_before_output(self):
self.template.write_bytes(plistlib.dumps({"CFBundlePackageType": "APPL", "fixture": "x" * 300000}))
with self.assertRaises(ValueError):
POLICY.write_plist(self.template, self.output, VERSION, COMMIT)
self.assertFalse(self.output.exists())
def test_nonprivate_build_root_refuses(self):
self.root.chmod(0o755)
try:
with self.assertRaises(ValueError):
POLICY.write_plist(self.template, self.output, VERSION, COMMIT)
self.assertFalse(self.output.exists())
finally:
self.root.chmod(0o700)
def test_output_keeps_normal_new_file_permissions_inside_private_root(self):
previous = os.umask(0o022)
try:
reference = self.root / "reference"
reference.write_bytes(b"generated ordinary output")
POLICY.write_plist(self.template, self.output, VERSION, COMMIT)
finally:
os.umask(previous)
self.assertEqual(self.output.stat().st_mode & 0o777, reference.stat().st_mode & 0o777)
def test_open_parent_anchor_prevents_a_later_alias_redirect(self):
parent = self.root / "stage"
parent.mkdir()
retained = self.root / "retained-stage"
destination = parent / "Info.plist"
original = POLICY.OwnedBuildRoot._parent
with tempfile.TemporaryDirectory() as external:
def swap_after_parent_open(root, path):
descriptor, name = original(root, path)
if Path(path) == destination:
parent.rename(retained)
parent.symlink_to(external, target_is_directory=True)
return descriptor, name
with mock.patch.object(POLICY.OwnedBuildRoot, "_parent", swap_after_parent_open):
POLICY.write_plist(self.template, destination, VERSION, COMMIT)
self.assertFalse((Path(external) / "Info.plist").exists())
self.assertEqual(plistlib.loads((retained / "Info.plist").read_bytes())["FilmCraftVersion"], VERSION)
if __name__ == "__main__":
unittest.main()
+425
View File
@@ -0,0 +1,425 @@
#!/usr/bin/env python3
"""The macOS Nightly signing and verification scripts, run on any POSIX host against generated
fixtures and stand-in Apple tools (codesign, notarytool, stapler, spctl, security, ditto, plutil,
lipo) that log their arguments. This proves the scripts' order, refusals and cleanup; it is not a
real signature, notarization or Mac run."""
import base64
import importlib.util
import json
import os
from pathlib import Path
import plistlib
import shutil
import stat
import subprocess
import sys
import tempfile
import textwrap
import time
import unittest
import zipfile
HERE = Path(__file__).resolve().parent
SPEC = importlib.util.spec_from_file_location("photo_mac_nightly_plist", HERE / "nightly_plist.py")
PLIST = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(PLIST)
COMMIT = "b" * 40
VERSION = "0.23.1-nightly.20261123.4567.1.g" + COMMIT[:12]
ASSET = f"filmcraft-{VERSION}-macos-aarch64-nightly.zip"
APP = "FilmCraft Nightly.app"
TEAM = "ABCDE12345"
IDENTITY = "0123456789ABCDEF0123456789ABCDEF01234567"
SECRETS = {
"APPLE_CERTIFICATE": base64.b64encode(b"generated fixture, not a certificate").decode(),
"APPLE_CERTIFICATE_PASSWORD": "generated-fixture",
"KEYCHAIN_PASSWORD": "generated-fixture",
"APPLE_ID": "fixture@example.invalid",
"APPLE_PASSWORD": "generated-fixture",
"APPLE_TEAM_ID": TEAM,
}
# One stand-in for every Apple tool, dispatched on its own name. Each logs its argv as a JSON line.
SHIM = r"""
import json, os, plistlib, sys, zipfile
from pathlib import Path
name = Path(sys.argv[0]).name
args = sys.argv[1:]
with open(os.environ["SHIM_LOG"], "a") as log:
log.write(json.dumps([name] + args) + "\n")
team = os.environ.get("SHIM_TEAM", "")
if name == "uname":
print({"-s": "Darwin", "-m": "arm64"}.get(args[0], "Darwin"))
elif name == "lipo":
print("arm64")
elif name == "ditto":
paths = [a for a in args if not a.startswith("-")]
src, dst = paths
if "-x" in args:
with zipfile.ZipFile(src) as z:
for info in z.infolist():
target = Path(dst) / info.filename
if info.is_dir():
target.mkdir(parents=True, exist_ok=True)
continue
target.parent.mkdir(parents=True, exist_ok=True)
target.write_bytes(z.read(info))
mode = (info.external_attr >> 16) & 0o777
if mode:
target.chmod(mode)
else:
root = Path(src)
with zipfile.ZipFile(dst, "x") as z:
for path in sorted([root] + list(root.rglob("*"))):
arc = (Path(root.name) / path.relative_to(root)).as_posix()
if path.is_dir():
z.writestr(zipfile.ZipInfo(arc + "/"), b"")
else:
info = zipfile.ZipInfo(arc)
info.external_attr = (path.stat().st_mode & 0xFFFF) << 16
z.writestr(info, path.read_bytes())
elif name == "plutil":
if args[0] == "-lint":
sys.exit(0)
key, fmt, source = args[1], args[2], args[-1]
data = sys.stdin.read() if source == "-" else Path(source).read_bytes()
value = json.loads(data) if source == "-" else plistlib.loads(data)
if key not in value:
sys.exit(1)
print(value[key] if fmt == "raw" else "<present/>")
elif name == "security":
verb = args[0]
if verb == "create-keychain":
Path(args[-1]).write_bytes(b"keychain")
elif verb == "find-identity":
print(' 1) %s "Developer ID Application: Generated Fixture (%s)"' % (os.environ["SHIM_IDENTITY"], team))
print(" 1 valid identities found")
elif verb == "delete-keychain":
Path(args[-1]).unlink()
elif name == "codesign":
target = Path(args[-1])
if "--sign" in args and target.suffix == ".app":
(target / "Contents/_CodeSignature").mkdir(exist_ok=True)
(target / "Contents/_CodeSignature/CodeResources").write_bytes(b"sealed")
if "-d" in args:
sys.stderr.write("Executable=%s\nIdentifier=ai.storyteller.filmcraft.nightly\n"
"CodeDirectory v=20500 size=1 flags=0x10000(runtime) hashes=1+7 location=embedded\n"
"Authority=Developer ID Application: Generated Fixture (%s)\n"
"Timestamp=23 Nov 2026 at 17:00:00\nTeamIdentifier=%s\n" % (target, team, team))
elif name == "xcrun":
if args[:2] == ["notarytool", "submit"]:
print(json.dumps({"id": "generated-id", "status": os.environ.get("SHIM_NOTARY", "Accepted")}))
elif args[:2] == ["stapler", "staple"]:
(Path(args[2]) / "Contents/CodeResources").write_bytes(b"ticket")
elif args[:2] == ["stapler", "validate"]:
sys.exit(0 if (Path(args[2]) / "Contents/CodeResources").is_file() else 1)
elif name == "spctl":
sys.stderr.write("%s: accepted\nsource=Notarized Developer ID\n" % args[-1])
elif name == "cargo":
sys.exit(1)
# sleep: the retry waits pass at once.
"""
TOOLS = ("uname", "lipo", "ditto", "plutil", "security", "codesign", "xcrun", "spctl", "cargo", "sleep")
class Fixture:
def __init__(self, test):
self.directory = tempfile.TemporaryDirectory()
test.addCleanup(self.directory.cleanup)
self.root = Path(self.directory.name).resolve()
self.bin = self.root / "bin"
self.bin.mkdir()
shim = self.bin / "shim.py"
shim.write_text(SHIM)
for tool in TOOLS:
path = self.bin / tool
path.write_text(f"#!{sys.executable}\nimport sys\nsys.argv[0] = {str(path)!r}\nexec(compile(open({str(shim)!r}).read(), 'shim', 'exec'), {{'__name__': '__main__'}})\n")
path.chmod(0o755)
self.log = self.root / "tools.log"
self.ran = self.root / "payload-ran"
self.temp = self.root / "runner-temp"
self.temp.mkdir()
self.dist = self.root / "unsigned"
self.dist.mkdir()
self.signed = self.root / "signed"
self.signed.mkdir()
self.input = self.dist / ASSET
self.output = self.signed / ASSET
# Every script runs from a directory with modules a Python helper must not import (-I).
self.cwd = self.root / "cwd"
self.cwd.mkdir()
self.hijacked = self.root / "hijacked"
for module in ("shutil", "zipfile", "stat"):
(self.cwd / f"{module}.py").write_text(f"open({str(self.hijacked)!r}, 'a').write({module!r})\n")
def add_entry(self, info, data=b""):
"""Append one raw entry to the input archive."""
with zipfile.ZipFile(self.input, "a") as z:
z.writestr(info, data)
def bundle(self, version=VERSION, extra=None, gui=None):
"""The archive nightly.sh makes: the real template through the real plist helper."""
stage = self.root / "stage"
shutil.rmtree(stage, ignore_errors=True)
app = stage / APP
(app / "Contents/MacOS").mkdir(parents=True)
(app / "Contents/Resources").mkdir()
exe = app / "Contents/MacOS/FilmCraft"
exe.write_text(gui or f"#!/bin/sh\ntouch {self.ran}\necho 'FilmCraft {version} (nightly-v1)'\n")
exe.chmod(0o755)
(app / "Contents/Resources/filmcraft-nightly.icns").write_bytes(b"generated icon")
rendered = PLIST.render((HERE / "Info.plist.in").read_bytes(), version, COMMIT)
(app / "Contents/Info.plist").write_bytes(rendered)
for relative, data in (extra or {}).items():
(app / relative).write_bytes(data)
(app / relative).chmod(0o755)
if self.input.exists():
self.input.unlink()
with zipfile.ZipFile(self.input, "x") as z:
for path in sorted([app] + list(app.rglob("*"))):
arc = (Path(APP) / path.relative_to(app)).as_posix()
info = zipfile.ZipInfo(arc + ("/" if path.is_dir() else ""))
info.external_attr = (path.stat().st_mode & 0xFFFF) << 16
z.writestr(info, b"" if path.is_dir() else path.read_bytes())
return self.input
def env(self, **changes):
env = {"PATH": f"{self.bin}:{os.environ['PATH']}", "HOME": str(self.root), "SHIM_LOG": str(self.log),
"SHIM_TEAM": TEAM, "SHIM_IDENTITY": IDENTITY, "RUNNER_TEMP": str(self.temp), **SECRETS}
env.update(changes)
return {key: value for key, value in env.items() if value is not None}
def run(self, script, *args, **env):
if self.log.exists():
self.log.unlink()
return subprocess.run(["bash", str(HERE / script), *map(str, args)], env=self.env(**env), cwd=self.cwd,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, timeout=120)
def sign(self, **env):
return self.run("nightly-sign.sh", "--arch", "aarch64", "--input", self.input, "--output", self.output, **env)
def calls(self):
if not self.log.exists():
return []
return [json.loads(line) for line in self.log.read_text().splitlines()]
def lib(function, *args):
"""Run one nightly-lib.sh function; returns (exit status, stdout)."""
script = f'. {str(HERE / "nightly-lib.sh")!r}; {function} "$@"'
result = subprocess.run(["bash", "-c", script, "lib", *args], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True)
return result.returncode, result.stdout.strip()
DETAILS = (f"Identifier=ai.storyteller.filmcraft.nightly\nCodeDirectory v=20500 size=1 flags=0x10000(runtime) hashes=1\n"
f"Authority=Developer ID Application: Generated Fixture ({TEAM})\nAuthority=Developer ID Certification Authority\n"
f"Timestamp=23 Nov 2026\nTeamIdentifier={TEAM}\n")
class Checks(unittest.TestCase):
def test_the_version_comes_only_from_a_prepared_nightly_asset_name(self):
self.assertEqual(lib("mac_nightly_version_from_asset", ASSET), (0, VERSION))
for name in (f"filmcraft-0.23.1-macos-aarch64.zip", f"filmcraft-{VERSION}-macos-universal-nightly.zip",
f"filmcraft-{VERSION}-linux-x86_64-nightly.tar.gz", ASSET.replace(".g", ".x"), "../" + ASSET):
with self.subTest(name=name):
self.assertNotEqual(lib("mac_nightly_version_from_asset", name)[0], 0)
def test_signature_needs_every_part_of_the_developer_id_signature(self):
self.assertEqual(lib("mac_nightly_check_signature", DETAILS, TEAM)[0], 0)
for broken in (DETAILS.replace("flags=0x10000(runtime)", "flags=0x0(none)"),
DETAILS.replace("Timestamp=23 Nov 2026\n", "Signed Time=23 Nov 2026\n"),
"Identifier=filmcraft-1234\nSignature=adhoc\nTeamIdentifier=not set\n",
DETAILS.replace("ai.storyteller.filmcraft.nightly", "ai.storyteller.filmcraft"),
DETAILS.replace("ai.storyteller.filmcraft.nightly", "aiXstorytellerXfilmcraftXnightly")):
with self.subTest(broken=broken):
self.assertNotEqual(lib("mac_nightly_check_signature", broken, TEAM)[0], 0)
self.assertNotEqual(lib("mac_nightly_check_signature", DETAILS, "ZZZZZ99999")[0], 0, "another team")
def test_gatekeeper_must_accept_the_bundle_as_notarized(self):
self.assertEqual(lib("mac_nightly_check_assessment", "x.app: accepted\nsource=Notarized Developer ID\n")[0], 0)
for text in ("x.app: accepted\nsource=Developer ID\n", "x.app: rejected\nsource=Unnotarized Developer ID\n"):
with self.subTest(text=text):
self.assertNotEqual(lib("mac_nightly_check_assessment", text)[0], 0)
def test_the_imported_identity_must_be_a_developer_id_of_the_team(self):
line = f' 1) {IDENTITY} "Developer ID Application: Generated Fixture ({TEAM})"'
self.assertEqual(lib("mac_nightly_identity_is_team", line, IDENTITY, TEAM)[0], 0)
self.assertNotEqual(lib("mac_nightly_identity_is_team", line, IDENTITY, "ZZZZZ99999")[0], 0)
self.assertNotEqual(lib("mac_nightly_identity_is_team", line.replace("Developer ID Application", "Apple Development"), IDENTITY, TEAM)[0], 0)
class Sign(unittest.TestCase):
def setUp(self):
self.f = Fixture(self)
self.f.bundle()
self.unsigned = self.f.input.read_bytes()
def assert_refused_untouched(self, result, signed=False):
self.assertNotEqual(result.returncode, 0, result.stdout)
self.assertFalse(self.f.output.exists())
self.assertEqual(self.f.input.read_bytes(), self.unsigned)
self.assertFalse(self.f.ran.exists(), "the payload must never run in the signing step")
names = [call[0] for call in self.f.calls()]
self.assertNotIn("cargo", names)
if not signed:
self.assertNotIn("codesign", names)
self.assertNotIn("xcrun", names)
self.assertEqual(list(self.f.temp.iterdir()), [], "the work directory and keychain are removed")
def test_signs_notarizes_and_staples_without_running_the_payload(self):
result = self.f.sign()
self.assertEqual(result.returncode, 0, result.stdout)
self.assertFalse(self.f.hijacked.exists(), "helpers run isolated (python3 -I) beside the secrets")
calls = self.f.calls()
names = [call[0] for call in calls]
self.assertNotIn("cargo", names)
self.assertFalse(self.f.ran.exists(), "the payload must never run in the signing step")
self.assertEqual(self.f.input.read_bytes(), self.unsigned)
signs = [call for call in calls if call[0] == "codesign" and "--sign" in call]
self.assertEqual([Path(call[-1]).name for call in signs], ["FilmCraft", APP], "inside-out: executable, then bundle")
for call in signs:
for flag in ("--force", "--timestamp", "runtime", str(HERE / "entitlements.plist"), IDENTITY):
self.assertIn(flag, call)
order = [" ".join(call[:3]) for call in calls]
submit = order.index("xcrun notarytool submit")
staple = order.index("xcrun stapler staple")
self.assertLess(max(i for i, call in enumerate(calls) if call[0] == "codesign" and "--sign" in call), submit)
self.assertLess(submit, staple)
final = [i for i, call in enumerate(calls) if call[0] == "ditto" and "-c" in call][-1]
self.assertLess(staple, final, "the final archive carries the stapled ticket")
self.assertIn("--noextattr", calls[final])
self.assertIn(["security", "delete-keychain"], [call[:2] for call in calls])
self.assertEqual(list(self.f.temp.iterdir()), [], "the work directory and keychain are removed")
with zipfile.ZipFile(self.f.output) as z:
names = set(z.namelist())
self.assertIn(f"{APP}/Contents/CodeResources", names, "stapled ticket inside the bundle")
self.assertIn(f"{APP}/Contents/_CodeSignature/CodeResources", names)
self.assertTrue(all(name.startswith(APP) for name in names))
mode = z.getinfo(f"{APP}/Contents/MacOS/FilmCraft").external_attr >> 16
self.assertTrue(mode & stat.S_IXUSR)
def test_every_signing_and_notarization_secret_is_required(self):
for name in SECRETS:
with self.subTest(missing=name):
self.assert_refused_untouched(self.f.sign(**{name: None}))
self.assertEqual(self.f.calls(), [], "no tool runs before the configuration is complete")
self.assert_refused_untouched(self.f.sign(NIGHTLY_APPLE_TEAM_ID="ZZZZZ99999"))
self.assert_refused_untouched(self.f.sign(APPLE_TEAM_ID="not-a-team"))
def test_refuses_another_team_s_identity(self):
self.assert_refused_untouched(self.f.sign(SHIM_TEAM="ZZZZZ99999"))
def test_never_replaces_an_output_or_renames_the_asset(self):
self.f.output.write_bytes(b"generated existing artifact")
result = self.f.sign()
self.assertNotEqual(result.returncode, 0)
self.assertEqual(self.f.output.read_bytes(), b"generated existing artifact")
self.f.output.unlink()
renamed = self.f.run("nightly-sign.sh", "--arch", "aarch64", "--input", self.f.input, "--output", self.f.signed / "other.zip")
self.assertNotEqual(renamed.returncode, 0)
relative = self.f.run("nightly-sign.sh", "--arch", "aarch64", "--input", self.f.input.name, "--output", self.f.output)
self.assertNotEqual(relative.returncode, 0)
self.assertEqual(list(self.f.signed.iterdir()), [])
def test_refuses_a_payload_that_is_not_the_exact_gui_only_nightly(self):
cases = {
"cli": dict(extra={"Contents/MacOS/filmcraft-cli": b"generated cli"}),
"version": dict(version=VERSION.replace("4567", "4568")),
}
for label, change in cases.items():
with self.subTest(label=label):
self.f.bundle(**change)
self.unsigned = self.f.input.read_bytes()
self.assert_refused_untouched(self.f.sign())
def test_refuses_links_traversal_and_foreign_entries_before_unpacking(self):
link = zipfile.ZipInfo(f"{APP}/Contents/Resources/link")
link.external_attr = (stat.S_IFLNK | 0o777) << 16
fifo = zipfile.ZipInfo(f"{APP}/Contents/Resources/fifo")
fifo.external_attr = (stat.S_IFIFO | 0o644) << 16
for label, info in (("link", link), ("special", fifo), ("traversal", zipfile.ZipInfo(f"{APP}/../outside")),
("absolute", zipfile.ZipInfo("/tmp/outside")), ("foreign root", zipfile.ZipInfo("Other.app/x"))):
with self.subTest(label=label):
self.f.bundle()
self.f.add_entry(info, b"/etc/passwd")
self.unsigned = self.f.input.read_bytes()
result = self.f.sign()
self.assert_refused_untouched(result)
self.assertNotIn("ditto", [call[0] for call in self.f.calls()], "refused before unpacking")
def test_a_rejected_notarization_publishes_nothing_and_removes_the_keychain(self):
result = self.f.sign(SHIM_NOTARY="Invalid")
self.assert_refused_untouched(result, signed=True)
self.assertIn(["xcrun", "notarytool", "log"], [call[:3] for call in self.f.calls()])
self.assertNotIn(["xcrun", "stapler", "staple"], [call[:3] for call in self.f.calls()])
class Verify(unittest.TestCase):
def setUp(self):
self.f = Fixture(self)
def verify(self, *args, **env):
return self.f.run("nightly-verify.sh", "--input", self.f.input, *args, **{name: None for name in SECRETS}, **env)
def test_asks_the_gui_its_version_with_an_empty_environment(self):
self.f.bundle(gui=f"#!/bin/sh\n[ -z \"$INHERITED\" ] || exit 9\necho 'FilmCraft {VERSION} (nightly-v1)'\n")
result = self.verify("--expect", "unsigned", INHERITED="generated")
self.assertEqual(result.returncode, 0, result.stdout)
self.f.bundle(gui="#!/bin/sh\necho 'FilmCraft 0.23.1 (stable)'\n")
self.assertNotEqual(self.verify("--expect", "unsigned").returncode, 0)
def test_the_launcher_profile_form_must_answer_promptly_and_cleanly(self):
answer = f"echo 'FilmCraft {VERSION} (nightly-v1)'"
# The shared producer smoke's exact form, with a fresh profile directory.
exact = ('#!/bin/sh\nif [ "$1" = --launch-profile ]; then\n'
' [ "$#" = 5 ] && [ "$2" = nightly-v1 ] && [ "$3" = --profile-root ] && [ -d "$4" ] && [ "$5" = --version ] || exit 7\n'
f'fi\n{answer}\n')
self.f.bundle(gui=exact)
result = self.verify("--expect", "unsigned")
self.assertEqual(result.returncode, 0, result.stdout)
hangs = f'#!/bin/sh\n[ "$1" != --launch-profile ] || exec /bin/sleep 60\n{answer}\n'
self.f.bundle(gui=hangs)
started = time.monotonic()
result = self.verify("--expect", "unsigned")
self.assertNotEqual(result.returncode, 0)
self.assertIn("within 15 s", result.stdout)
self.assertLess(time.monotonic() - started, 45, "a hanging query is ended, not waited for")
noisy = f'#!/bin/sh\n[ "$1" != --launch-profile ] || echo refusal >&2\n{answer}\n'
self.f.bundle(gui=noisy)
result = self.verify("--expect", "unsigned")
self.assertNotEqual(result.returncode, 0)
self.assertIn("standard error", result.stdout)
def test_a_signed_check_needs_the_signature_ticket_and_team(self):
self.f.bundle()
self.assertNotEqual(self.verify("--expect", "signed").returncode, 0, "no team to check against")
self.assertNotEqual(self.verify("--expect", "signed", "--team", TEAM).returncode, 0, "no stapled ticket")
self.f.bundle(extra={"Contents/CodeResources": b"ticket"})
self.assertEqual(self.verify("--expect", "signed", "--team", TEAM).returncode, 0)
self.assertNotEqual(self.verify("--expect", "signed", "--team", TEAM, SHIM_TEAM="ZZZZZ99999").returncode, 0)
def test_refuses_to_run_the_payload_beside_signing_material(self):
self.f.bundle()
for name in ("APPLE_PASSWORD", "APPLE_CERTIFICATE", "MACOS_KEYCHAIN"):
with self.subTest(name=name):
result = self.f.run("nightly-verify.sh", "--input", self.f.input, "--expect", "unsigned",
**{**{key: None for key in SECRETS}, name: "generated"})
self.assertNotEqual(result.returncode, 0)
self.assertFalse(self.f.ran.exists())
self.assertEqual(self.f.calls(), [])
class Build(unittest.TestCase):
def test_compilation_refuses_signing_material_before_building(self):
f = Fixture(self)
for name in ("APPLE_CERTIFICATE", "APPLE_PASSWORD", "MACOS_SIGN_IDENTITY", "WINDOWS_CERTIFICATE", "AZURE_CLIENT_SECRET", "LINUX_SIGNING_KEY"):
with self.subTest(name=name):
result = f.run("nightly.sh", "--arch", "aarch64", **{**{key: None for key in SECRETS}, name: "generated"},
FILMCRAFT_BUILD_CHANNEL="nightly-v1", FILMCRAFT_VERSION=VERSION)
self.assertNotEqual(result.returncode, 0)
self.assertIn(name, result.stdout)
self.assertNotIn("cargo", [call[0] for call in f.calls()])
if __name__ == "__main__":
unittest.main()
+229
View File
@@ -0,0 +1,229 @@
#!/usr/bin/env python3
"""Synthetic app-owned archive/output tests; no native build or executable launch."""
import gzip
import importlib.util
import os
import runpy
import sys
from unittest import mock
from pathlib import Path
import subprocess
import tarfile
import tempfile
import unittest
HERE = Path(__file__).resolve().parent
SPEC = importlib.util.spec_from_file_location("photo_nightly_archive", HERE / "nightly-archive.py")
ARCHIVE = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(ARCHIVE)
class ArchivePolicy(unittest.TestCase):
def setUp(self):
self.scratch = tempfile.TemporaryDirectory()
self.addCleanup(self.scratch.cleanup)
self.root = Path(self.scratch.name).resolve()
previous = Path.cwd()
os.chdir(self.root)
self.addCleanup(os.chdir, previous)
self.stage = self.root / "stage"
self.stage.mkdir()
self.output = self.root / "nightly.tar.gz"
self.required = {"filmcraft", "filmcraft-bin", "filmcraft-nightly.png", "README.md", "LICENSE-MIT", "LICENSE-APACHE", "NOTICE", "ATTRIBUTION.md"}
for name in self.required:
(self.stage / name).write_bytes(b"generated fixture: " + name.encode())
(self.stage / "filmcraft").chmod(0o755)
def test_flat_regular_ustar_with_all_notices(self):
(self.stage / "OFL-Font.txt").write_text("generated fixture license", encoding="utf-8")
ARCHIVE.linux_archive(self.stage, self.output)
with tarfile.open(self.output) as archive:
self.assertEqual({m.name for m in archive}, self.required | {"OFL-Font.txt"})
self.assertTrue(all(m.isfile() and not m.pax_headers for m in archive))
self.assertEqual(archive.extractfile("filmcraft").read(), (self.stage / "filmcraft").read_bytes())
with gzip.open(self.output, "rb") as stream:
while (header := stream.read(512)) != bytes(512):
self.assertEqual(len(header), 512)
self.assertIn(header[156:157], {b"0", b"\0"})
self.assertEqual(header[257:263], b"ustar\0")
size = int(header[124:136].rstrip(b"\0 ").lstrip(b" ") or b"0", 8)
stream.read(((size + 511) // 512) * 512)
def test_each_required_member_is_required_before_output(self):
for name in self.required:
with self.subTest(name=name):
content = (self.stage / name).read_bytes()
(self.stage / name).unlink()
with self.assertRaisesRegex(ValueError, "required"):
ARCHIVE.linux_archive(self.stage, self.output)
self.assertFalse(self.output.exists())
(self.stage / name).write_bytes(content)
def test_unexpected_cli_portable_or_installer_member_refuses(self):
for name in ["filmcraft-cli", "portable.txt", "filmcraft.desktop"]:
with self.subTest(name=name):
bad = self.stage / name
bad.write_bytes(b"generated fixture")
with self.assertRaisesRegex(ValueError, "unexpected"):
ARCHIVE.linux_archive(self.stage, self.output)
self.assertFalse(self.output.exists())
bad.unlink()
def test_symlink_refuses_before_output(self):
icon = self.stage / "filmcraft-nightly.png"
icon.unlink()
icon.symlink_to(self.stage / "README.md")
with self.assertRaisesRegex(ValueError, "regular file|symlinks or aliases"):
ARCHIVE.linux_archive(self.stage, self.output)
self.assertFalse(self.output.exists())
def test_directory_refuses_before_output(self):
icon = self.stage / "filmcraft-nightly.png"
icon.unlink()
icon.mkdir()
with self.assertRaisesRegex(ValueError, "regular file"):
ARCHIVE.linux_archive(self.stage, self.output)
self.assertFalse(self.output.exists())
def test_long_notice_refuses_before_output(self):
(self.stage / ("OFL-" + "x" * 100 + ".txt")).write_bytes(b"fixture")
with self.assertRaisesRegex(ValueError, "short regular"):
ARCHIVE.linux_archive(self.stage, self.output)
self.assertFalse(self.output.exists())
def test_case_colliding_notices_refuse_before_output(self):
for name in ["OFL-Font.txt", "OFL-font.txt"]:
(self.stage / name).write_bytes(b"fixture")
with self.assertRaisesRegex(ValueError, "case-colliding"):
ARCHIVE.linux_archive(self.stage, self.output)
self.assertFalse(self.output.exists())
def test_cli_dispatches_only_the_supported_archive_kind(self):
helper = HERE / "nightly-archive.py"
with mock.patch.object(sys, "argv", [str(helper), "linux", str(self.stage), str(self.output)]):
runpy.run_path(str(helper), run_name="__main__")
with tarfile.open(self.output) as archive:
self.assertEqual({member.name for member in archive}, self.required)
refused = self.root / "refused.tar.gz"
for args in ([str(helper)], [str(helper), "unknown", str(self.stage), str(refused)]):
with self.subTest(args=args), mock.patch.object(sys, "argv", args):
with self.assertRaises(SystemExit):
runpy.run_path(str(helper), run_name="__main__")
self.assertFalse(refused.exists())
def test_existing_archive_is_unchanged(self):
self.output.write_bytes(b"owned earlier artifact")
with self.assertRaises(FileExistsError):
ARCHIVE.linux_archive(self.stage, self.output)
self.assertEqual(self.output.read_bytes(), b"owned earlier artifact")
def test_archive_output_outside_build_root_refuses(self):
with tempfile.TemporaryDirectory() as external:
output = Path(external) / "nightly.tar.gz"
with self.assertRaises(ValueError):
ARCHIVE.linux_archive(self.stage, output)
self.assertFalse(output.exists())
def test_archive_stage_outside_build_root_refuses(self):
with tempfile.TemporaryDirectory() as external:
stage = Path(external)
for name in self.required:
(stage / name).write_bytes(b"generated external fixture")
with self.assertRaises(ValueError):
ARCHIVE.linux_archive(stage, self.output)
self.assertFalse(self.output.exists())
def test_archive_stage_alias_refuses(self):
alias = self.root / "stage-alias"
alias.symlink_to(self.stage, target_is_directory=True)
with self.assertRaises(ValueError):
ARCHIVE.linux_archive(alias, self.output)
self.assertFalse(self.output.exists())
def test_archive_output_parent_alias_refuses(self):
with tempfile.TemporaryDirectory() as external:
alias = self.root / "output-alias"
alias.symlink_to(external, target_is_directory=True)
with self.assertRaises(ValueError):
ARCHIVE.linux_archive(self.stage, alias / "nightly.tar.gz")
self.assertFalse((Path(external) / "nightly.tar.gz").exists())
def test_archive_parent_traversal_refuses(self):
with tempfile.TemporaryDirectory(dir=self.root.parent) as external:
output = Path("..") / Path(external).name / "nightly.tar.gz"
with self.assertRaises(ValueError):
ARCHIVE.linux_archive(self.stage, output)
self.assertFalse((Path(external) / "nightly.tar.gz").exists())
def test_nonflat_member_name_refuses(self):
stage_root = os.path.realpath(self.stage)
with open(self.stage / "README.md", "rb") as incoming:
for bad in ("../escape", "/absolute", "nested/name", "x/../README.md", "", ".", ".."):
with self.subTest(name=bad), self.assertRaises(ValueError):
ARCHIVE.member_info(stage_root, bad, incoming)
def test_member_header_matches_what_gettarinfo_records(self):
stage_root = os.path.realpath(self.stage)
for name in sorted(self.required):
with self.subTest(name=name), open(self.stage / name, "rb") as incoming:
ours = ARCHIVE.member_info(stage_root, name, incoming)
with tarfile.open(fileobj=__import__("io").BytesIO(), mode="w") as reference:
theirs = reference.gettarinfo(fileobj=incoming, arcname=name)
self.assertEqual(ours.get_info(), theirs.get_info())
def test_member_read_budget_refuses_before_output(self):
(self.stage / "OFL-Large.txt").write_bytes(b"x" * 65)
with mock.patch.object(ARCHIVE, "MAX_MEMBER_BYTES", 64, create=True):
with self.assertRaises(ValueError):
ARCHIVE.linux_archive(self.stage, self.output)
self.assertFalse(self.output.exists())
def test_member_growth_is_rechecked_before_copy_and_output_is_cleaned(self):
growing = self.stage / "OFL-Growing.txt"
growing.write_bytes(b"x" * 32)
original = ARCHIVE.member_info
def grow_before_stat(stage_root, name, incoming):
if name == growing.name:
growing.write_bytes(b"x" * 65)
return original(stage_root, name, incoming)
with mock.patch.object(ARCHIVE, "MAX_MEMBER_BYTES", 64), \
mock.patch.object(ARCHIVE, "member_info", grow_before_stat):
with self.assertRaises(ValueError):
ARCHIVE.linux_archive(self.stage, self.output)
self.assertFalse(self.output.exists())
class ExclusiveOutput(unittest.TestCase):
def setUp(self):
self.scratch = tempfile.TemporaryDirectory()
self.addCleanup(self.scratch.cleanup)
self.root = Path(self.scratch.name)
self.source = self.root / "input archive"
self.output = self.root / "final archive"
self.source.write_bytes(b"generated archive fixture" * 1024)
def publish(self):
return subprocess.run(["bash", "-c", 'set -euo pipefail; source "$1"; nightly_publish_archive "$2" "$3"', "test", str(HERE / "nightly-common.sh"), str(self.source), str(self.output)], capture_output=True, text=True, timeout=15)
def test_success_copies_exact_bytes(self):
result = self.publish()
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(self.output.read_bytes(), self.source.read_bytes())
def test_existing_output_is_never_replaced(self):
self.output.write_bytes(b"existing artifact")
self.assertNotEqual(self.publish().returncode, 0)
self.assertEqual(self.output.read_bytes(), b"existing artifact")
def test_missing_source_does_not_leave_a_fake_empty_artifact(self):
self.source.unlink()
self.assertNotEqual(self.publish().returncode, 0)
self.assertFalse(self.output.exists())
if __name__ == "__main__":
unittest.main()
+131
View File
@@ -0,0 +1,131 @@
#!/usr/bin/env python3
"""Flat Linux archive policy, invoked from its private owned build cwd.
The stage and archive must both remain under that independently chosen root.
No native build, platform signing, or malicious-same-UID sandbox is implied.
"""
import grp
import gzip
import os
import pathlib
import pwd
import re
import stat
import sys
import tarfile
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
from nightly_paths import OwnedBuildRoot
APP_DOCS = {"README.md", "LICENSE", "LICENSE-MIT", "LICENSE-APACHE", "COPYRIGHT", "NOTICE", "ATTRIBUTION.md"}
MAX_MEMBER_BYTES = 512 * 1024 * 1024
MAX_TOTAL_BYTES = 1024 * 1024 * 1024
MAX_MEMBERS = 128
def notice(name):
return name in APP_DOCS or re.fullmatch(r"OFL-[A-Za-z0-9_.-]+\.txt", name) is not None
def checked_entries(root, stage):
entries = sorted(root.children(stage, MAX_MEMBERS), key=lambda item: item.name)
folded = set()
total = 0
for entry in entries:
name = entry.name
if name not in {"filmcraft", "filmcraft-bin", "filmcraft-nightly.png"} and not notice(name):
raise ValueError(f"unexpected nightly member: {name}")
if len(name.encode("utf-8")) > 100:
raise ValueError(f"nightly member must be a short regular file: {name}")
with root.reader(entry, MAX_MEMBER_BYTES) as stream:
total += os.fstat(stream.fileno()).st_size
if total > MAX_TOTAL_BYTES:
raise ValueError("nightly stage exceeds its read bound")
if name.casefold() in folded:
raise ValueError(f"case-colliding nightly member: {name}")
folded.add(name.casefold())
# `filmcraft` is the launcher and `filmcraft-bin` the GUI it starts with the Launcher profile.
required = {"filmcraft", "filmcraft-bin", "filmcraft-nightly.png", "README.md", "LICENSE-MIT", "LICENSE-APACHE", "NOTICE", "ATTRIBUTION.md"}
if not required.issubset({item.name for item in entries}):
raise ValueError("required GUI/icon/notices missing")
return entries
def member_info(stage_root, name, incoming):
"""Header for one stage file, built from the file this run opened rather than from the archive.
Members are flat names that resolve directly inside the stage they came from.
"""
if os.path.isabs(name) or os.path.basename(name) != name or name in ("", ".", ".."):
raise ValueError(f"nightly member name must be a flat file name: {name}")
destination = os.path.realpath(os.path.join(stage_root, name))
if not destination.startswith(stage_root + os.sep) or os.path.dirname(destination) != stage_root:
raise ValueError(f"nightly member resolves outside its stage: {name}")
status = os.fstat(incoming.fileno())
if not stat.S_ISREG(status.st_mode):
raise ValueError(f"nightly member must be a regular file: {name}")
# The same fields TarFile.gettarinfo records for a regular file.
info = tarfile.TarInfo(os.path.basename(destination))
info.type = tarfile.REGTYPE
info.mode = stat.S_IMODE(status.st_mode)
info.uid, info.gid = status.st_uid, status.st_gid
info.size = status.st_size
info.mtime = status.st_mtime
try:
info.uname = pwd.getpwuid(status.st_uid).pw_name
except KeyError:
pass
try:
info.gname = grp.getgrgid(status.st_gid).gr_name
except KeyError:
pass
return info
def verify_headers(root, output):
# Bounded ordinary headers, not a transparent PAX/GNU-normalizing reader.
total = 0
count = 0
with root.reader(output, MAX_TOTAL_BYTES) as incoming, gzip.GzipFile(fileobj=incoming) as stream:
while True:
header = stream.read(512)
if header == b"\0" * 512:
break
if len(header) != 512 or header[156:157] not in {b"0", b"\0"}:
raise ValueError("non-ordinary TAR record was emitted")
size = int(header[124:136].rstrip(b"\0 ").lstrip(b" ") or b"0", 8)
count += 1
total += size
if count > MAX_MEMBERS or size > MAX_MEMBER_BYTES or total > MAX_TOTAL_BYTES:
raise ValueError("archive exceeds its bounded member budget")
remaining = ((size + 511) // 512) * 512
while remaining:
chunk = stream.read(min(remaining, 1024 * 1024))
if not chunk:
raise ValueError("truncated TAR member")
remaining -= len(chunk)
def linux_archive(stage, output):
with OwnedBuildRoot() as root:
entries = checked_entries(root, stage)
stage_root = os.path.realpath(os.path.join(root.directory, stage))
total = 0
with root.create(output) as outgoing:
with tarfile.open(fileobj=outgoing, mode="w:gz", format=tarfile.USTAR_FORMAT) as archive:
for entry in entries:
with root.reader(entry, MAX_MEMBER_BYTES) as incoming:
info = member_info(stage_root, entry.name, incoming)
total += info.size
if info.size > MAX_MEMBER_BYTES or total > MAX_TOTAL_BYTES:
raise ValueError("nightly stage grew beyond its read bound")
archive.addfile(info, incoming)
outgoing.flush()
os.fsync(outgoing.fileno())
verify_headers(root, output)
if __name__ == "__main__":
if len(sys.argv) != 4 or sys.argv[1] != "linux":
raise SystemExit("usage: nightly-archive.py linux STAGE OUTPUT (from owned private build cwd)")
linux_archive(pathlib.Path(sys.argv[2]), pathlib.Path(sys.argv[3]))
+99
View File
@@ -0,0 +1,99 @@
# shellcheck shell=bash
# Shared setup for app-owned native nightly archives; stable packaging does not source this file.
nightly_die() { printf 'error: %s\n' "$*" >&2; exit 2; }
nightly_init() {
local os="$1" arch="$2" target="$3" date_digits
[[ "${FILMCRAFT_BUILD_CHANNEL:-}" == nightly-v1 ]] || nightly_die 'FILMCRAFT_BUILD_CHANNEL must be nightly-v1'
[[ "${FILMCRAFT_VERSION:-}" =~ ^[0-9]+\.[0-9]+\.[0-9]+-nightly\.[0-9]{8}\.[0-9]+\.[0-9]+\.g[0-9a-f]{12}$ ]] || nightly_die 'an exact prepared nightly version is required'
[[ "${FILMCRAFT_BUILD_SHA:-}" =~ ^[0-9a-f]{40}$ ]] || nightly_die 'an exact source commit is required'
[[ "${FILMCRAFT_VERSION##*.g}" == "${FILMCRAFT_BUILD_SHA:0:12}" ]] || nightly_die 'version/source commit mismatch'
[[ "${FILMCRAFT_BUILD_DATE:-}" =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}$ ]] || nightly_die 'the original run-created UTC date is required'
date_digits="${FILMCRAFT_VERSION#*-nightly.}"
date_digits="${date_digits%%.*}"
[[ "${FILMCRAFT_BUILD_DATE//-/}" == "$date_digits" ]] || nightly_die 'version/original-run date mismatch'
[[ "${CARGO_TARGET_DIR:-}" == /* && "$CARGO_TARGET_DIR" != / ]] || nightly_die 'an absolute owned CARGO_TARGET_DIR base is required'
[[ "${DIST:-}" == /* && "$DIST" != / ]] || nightly_die 'an absolute DIST output directory is required'
[[ "/$CARGO_TARGET_DIR/" != *'/../'* && "/$DIST/" != *'/../'* ]] || nightly_die 'output paths must not contain parent traversal'
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
[[ "$(git -C "$ROOT" rev-parse HEAD)" == "$FILMCRAFT_BUILD_SHA" ]] || nightly_die 'prepared source is not the checked-out commit'
[[ -z "$(git -C "$ROOT" status --porcelain)" ]] || nightly_die 'nightly packaging requires the frozen clean source'
if [[ -n "${CRAFT_FONTS_DIR:-}" && ! -d "$CRAFT_FONTS_DIR/fonts" ]]; then
nightly_die 'declared CRAFT_FONTS_DIR has no fonts directory'
fi
# env.sh retains the established notice copier. Required values above prohibit its stable fallbacks.
. "$ROOT/packaging/env.sh"
export CARGO_TARGET_DIR="$CARGO_TARGET_DIR/nightly-v1/$os-$arch"
NIGHTLY_RUST_TARGET="$target"
mkdir -p "$CARGO_TARGET_DIR"
NIGHTLY_WORK="$(mktemp -d "$CARGO_TARGET_DIR/nightly-package.XXXXXX")"
trap 'rm -rf -- "$NIGHTLY_WORK"' EXIT
}
# Compile only: macOS runs the version query after signing (packaging/macos/nightly-verify.sh).
nightly_compile_gui() {
# Signing material never reaches compilation (the Windows -CheckBuildEnvironment rule).
nightly_refuse_signing_env
# The same prepared identity the artifacts are named after: build.rs refuses a nightly whose
# version, commit and date disagree.
# The same features the official package builds with (packaging/linux/package.sh): without
# natural voices the Nightly would quietly have fewer voices than stable.
(cd "$ROOT" && FILMCRAFT_VERSION="$VERSION" FILMCRAFT_BUILD_CHANNEL=nightly-v1 cargo build --release --locked \
-p filmcraft --features filmcraft/neural-voices --target "$NIGHTLY_RUST_TARGET")
NIGHTLY_GUI="$CARGO_TARGET_DIR/$NIGHTLY_RUST_TARGET/release/filmcraft"
[[ -f "$NIGHTLY_GUI" && ! -L "$NIGHTLY_GUI" ]] || nightly_die 'the owned GUI build did not produce a regular executable'
[[ "$(git -C "$ROOT" rev-parse HEAD)" == "$FILMCRAFT_BUILD_SHA" && -z "$(git -C "$ROOT" status --porcelain)" ]] || nightly_die 'source changed during the build'
}
nightly_build_gui() {
nightly_compile_gui
local actual
actual="$("$NIGHTLY_GUI" --version)" || nightly_die 'side-effect-free nightly version verification failed'
[[ "$actual" == "FilmCraft $VERSION (nightly-v1)" ]] || nightly_die 'the built version/flavor is not the prepared identity'
[[ "$(git -C "$ROOT" rev-parse HEAD)" == "$FILMCRAFT_BUILD_SHA" && -z "$(git -C "$ROOT" status --porcelain)" ]] || nightly_die 'source changed during the version query'
}
# Signing material never reaches compilation (the Windows -CheckBuildEnvironment rule).
nightly_refuse_signing_env() {
local name
# The signing names release.yml passes, for every platform, and import-cert.sh's outputs.
for name in APPLE_CERTIFICATE APPLE_CERTIFICATE_PASSWORD KEYCHAIN_PASSWORD APPLE_ID APPLE_PASSWORD APPLE_TEAM_ID \
MACOS_SIGN_IDENTITY MACOS_KEYCHAIN WINDOWS_CERTIFICATE WINDOWS_CERTIFICATE_PASSWORD AZURE_TENANT_ID AZURE_CLIENT_ID \
AZURE_CLIENT_SECRET AZURE_SIGNING_ENDPOINT AZURE_SIGNING_ACCOUNT AZURE_CERT_PROFILE LINUX_SIGNING_KEY; do
[[ -z "${!name:-}" ]] || nightly_die "compilation must not receive signing configuration ($name); sign in the separate trusted step"
done
}
nightly_copy_notices() {
local destination="$1" required
for required in README.md LICENSE-MIT LICENSE-APACHE NOTICE ATTRIBUTION.md; do
[[ -f "$ROOT/$required" && ! -L "$ROOT/$required" ]] || nightly_die "missing regular app notice: $required"
done
copy_docs "$destination"
# `copy_docs` (env.sh) copies the licence and README only; nightly-archive.py and
# nightly-check.sh require ATTRIBUTION.md in the tar and the macOS bundle.
cp "$ROOT/ATTRIBUTION.md" "$destination/"
}
nightly_publish_archive() {
# Exclusive creation: never replace an existing artifact, even if another writer raced the preflight.
python3 -I - "$1" "$2" <<'PY'
import os, shutil, sys
source, destination = sys.argv[1:]
created = False
try:
# Open the input first: a missing source must not leave an empty final artifact.
with open(source, 'rb') as incoming:
with open(destination, 'xb') as output:
created = True
shutil.copyfileobj(incoming, output, length=1024 * 1024)
output.flush()
os.fsync(output.fileno())
except BaseException:
if created:
os.unlink(destination)
raise
PY
printf 'Nightly artifact: %s\n' "$2"
}
+764
View File
@@ -0,0 +1,764 @@
#!/usr/bin/env python3
"""Synthetic dispatcher regression fixtures; original local work, not live API/crypto evidence."""
import contextlib
import copy
import io
import json
import os
from pathlib import Path
import re
import tempfile
import textwrap
import base64
import hashlib
import unittest
from unittest.mock import patch
import urllib.error
ROOT = Path(__file__).resolve().parents[1]
DISPATCHER = ROOT / ".github/workflows/nightly-dispatch.yml"
def inline_scripts(path):
"""Read literal run blocks, not a substitute for YAML/actionlint validation."""
return [textwrap.dedent(block) for block in re.findall(
r"^ run: \|\n((?: .*\n|\n)+)", path.read_text(), re.MULTILINE)]
def assert_nightly_serialization(source):
"""Fail closed unless this app's plain root concurrency block retains its contract.
This is a deliberately narrow source guard, not a general YAML parser; actionlint
still checks all other syntax. Expressions, aliases and alternate block shapes
refuse rather than delegating queue-value validation to the old linter.
"""
lines = source.splitlines()
roots = [index for index, line in enumerate(lines) if line.startswith("concurrency:")]
if len(roots) != 1 or lines[roots[0]] != "concurrency:":
raise ValueError("one plain root concurrency block is required")
values = {}
for line in lines[roots[0] + 1:]:
if not line.strip() or line.lstrip().startswith("#"):
continue
if not line[0].isspace():
break
row = re.fullmatch(r" (group|cancel-in-progress|queue): ([^#]+?)(?: +#.*)?", line)
if row is None or row[1] in values:
raise ValueError("malformed or duplicate nightly concurrency entry")
values[row[1]] = row[2].rstrip()
allowed = {"group": "filmcraft-nightly-release", "cancel-in-progress": "false"}
if "queue" in values:
# Optional in the caller; when present it must keep GitHub's full queue, never coalesce.
if values["queue"] != "max":
raise ValueError("a nightly queue entry must be `max`")
allowed["queue"] = "max"
if values != allowed:
raise ValueError("nightly serialization must use its stable group and no cancellation")
def job_conditions(jobs):
"""Each job-level `if:` as (block indicator or None, the whole expression YAML would read)."""
lines = jobs.splitlines()
found = []
for index, line in enumerate(lines):
head = re.fullmatch(r" if:(?: (.*))?", line)
if head is None:
continue
value = (head[1] or "").strip()
continuation = []
for follow in lines[index + 1:]:
if follow.strip() and len(follow) - len(follow.lstrip(" ")) <= 4:
break
continuation.append(follow.strip())
indicator = value if re.fullmatch(r"[>|][+-]?", value) else None
parts = continuation if indicator else [value] + continuation
found.append((indicator, " ".join(part for part in parts if part)))
return found
def reviewed_manual_actors(caller_source, policy):
"""The one reviewed manual-actor list, identical in the producer caller and the policy."""
rows = re.findall(r"(?m)^ manual-actors: '(\[[^']*\])'$", caller_source)
if len(rows) != 1:
raise ValueError("exactly one literal manual-actors list is required")
caller = json.loads(rows[0])
if caller != policy["manual_actors"]:
raise ValueError("caller and policy must grant the same actors in the same order")
if caller != RELEASE_MANAGERS:
raise ValueError("manual actors must be exactly the reviewed release managers")
if caller != sorted(caller, key=str.lower) or len({login.lower() for login in caller}) != len(caller):
raise ValueError("manual actors must be distinct and sorted case-insensitively")
if set(caller) & {login for login in policy["automatic_signer_actors"]}:
raise ValueError("manual and automatic actors overlap")
return caller
def caller_pin(name):
return re.findall(r"(?m)^ tooling-revision: ([0-9a-f]{40})$",
(ROOT / ".github/workflows" / name).read_text())[0]
NIGHTLY_PLATFORMS = ("windows-x86_64", "linux-x86_64", "macos-aarch64")
# Each platform's one trust field in policy v3, and the public stable identity it must name.
NIGHTLY_TRUST = {
"windows-x86_64": ("publisher_subject",
"CN=Learning Machines Inc, O=Learning Machines Inc, L=Atlanta, S=Georgia, C=US"),
"linux-x86_64": ("fingerprint", "2B76741B414AAD6CD33E631213A005C0B9D7C3ED"),
"macos-aarch64": ("apple_team_id", "DJ6XS33FX8"),
}
LINUX_KEY = ROOT / ".github/nightly-linux-signing-key.asc"
# The installed v3 policy is Dylan's reviewed manual activation: manual dispatch only, no schedule.
INSTALLED_POLICY = ROOT / ".github/nightly-signing-policy.json"
# Mirrors the storytold release-managers team (id 19837241) minus echelon-robot.
# Update by PR, in the caller and the policy, when the team changes.
RELEASE_MANAGERS = ["bflatastic", "dylanmtaylor", "echelon", "FredApps", "skylartaylor"]
def openpgp_primary_fingerprints(armored):
"""Return the v4 fingerprints of every primary public-key packet in one armored block.
A narrow reader for the committed public key, not a general OpenPGP parser: anything
other than one well-formed public-key block refuses.
"""
lines = armored.strip().splitlines()
if lines[:1] != ["-----BEGIN PGP PUBLIC KEY BLOCK-----"] or lines[-1:] != ["-----END PGP PUBLIC KEY BLOCK-----"]:
raise ValueError("exactly one armored public key block is required")
body = lines[1:-1]
if "" not in body:
raise ValueError("armor header separator missing")
body = body[body.index("") + 1:]
if not body or not body[-1].startswith("="):
raise ValueError("armor checksum missing")
data = base64.b64decode("".join(body[:-1]), validate=True)
fingerprints, offset = [], 0
while offset < len(data):
header = data[offset]
if not header & 0x80:
raise ValueError("invalid packet header")
if header & 0x40:
tag, offset = header & 0x3F, offset + 1
first = data[offset]
if first < 192:
length, offset = first, offset + 1
elif first < 224:
length, offset = ((first - 192) << 8) + data[offset + 1] + 192, offset + 2
elif first == 255:
length, offset = int.from_bytes(data[offset + 1:offset + 5], "big"), offset + 5
else:
raise ValueError("partial packet lengths are not a public key")
else:
tag, kind, offset = (header >> 2) & 0x0F, header & 0x03, offset + 1
if kind == 3:
raise ValueError("indeterminate packet length")
size = 1 << kind
length, offset = int.from_bytes(data[offset:offset + size], "big"), offset + size
packet = data[offset:offset + length]
if len(packet) != length:
raise ValueError("truncated packet")
if tag == 5 or tag == 7:
raise ValueError("secret key material must never be committed")
if tag == 6:
if packet[:1] != b"\x04":
raise ValueError("only v4 primary keys are expected")
fingerprints.append(hashlib.sha1(b"\x99" + length.to_bytes(2, "big") + packet).hexdigest().upper())
offset += length
return fingerprints
def producer_platforms(source):
"""Read the one producer job's literal platform list; a narrow source guard, not YAML.
One producer run builds every listed platform for one all-or-nothing release, so the
list must be a compact JSON list of distinct known platforms that keeps Windows.
"""
rows = re.findall(r"(?m)^ platforms: (.*)$", source)
if len(rows) != 1:
raise ValueError("exactly one producer platform list is required")
literal = re.fullmatch(r"'(\[[^']*\])'", rows[0])
if literal is None:
raise ValueError("the platform list must be one single-quoted literal")
platforms = json.loads(literal[1])
if not isinstance(platforms, list) or json.dumps(platforms, separators=(",", ":")) != literal[1]:
raise ValueError("the platform list must be compact JSON")
if len(set(platforms)) != len(platforms) or not set(platforms) <= set(NIGHTLY_PLATFORMS):
raise ValueError("platforms must be distinct known nightly targets")
if "windows-x86_64" not in platforms:
raise ValueError("the Windows row stays in the producer")
return platforms
class Response:
status = 204
def __enter__(self):
return self
def __exit__(self, *args):
return False
class DispatchBoundary(unittest.TestCase):
def setUp(self):
# All generated metadata is synthetic, including the presence-only mock token.
self.event = {"action": "completed", "repository": {"full_name": "storytold/filmcraft"},
"workflow_run": {"id": 71, "run_attempt": 1, "status": "completed",
"conclusion": "success", "event": "schedule",
"path": ".github/workflows/nightly.yml", "head_branch": "main",
"head_repository": {"full_name": "storytold/filmcraft"}}}
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.event_path = Path(self.temp.name) / "event.json"
self.env = {"GITHUB_REPOSITORY": "storytold/filmcraft", "GITHUB_EVENT_NAME": "workflow_run",
"GITHUB_EVENT_PATH": str(self.event_path), "GH_TOKEN": "synthetic-not-a-token"}
scripts = inline_scripts(DISPATCHER)
if len(scripts) != 1:
raise RuntimeError("dispatcher must have one locally exercisable literal script")
self.program = compile(scripts[0], str(DISPATCHER), "exec")
def execute(self, event=None, env=None, failure=None, response=None):
self.event_path.write_text(json.dumps(self.event if event is None else event))
scope = {}
with patch.dict(os.environ, self.env if env is None else env, clear=True), \
patch("urllib.request.build_opener") as opener, \
contextlib.redirect_stdout(io.StringIO()):
opener.return_value.open.return_value = response or Response()
opener.return_value.open.side_effect = failure
try:
exec(self.program, scope)
except Exception as error:
return opener, scope, error
return opener, scope, None
def assert_refused(self, event=None, env=None):
opener, _, error = self.execute(event=event, env=env)
self.assertIsNotNone(error, "invalid transport must refuse")
opener.assert_not_called()
def test_only_fixed_release_destination_and_numeric_request_are_transported(self):
# Caller-selected source/ref/digest fields have no effect on the transmitted request.
self.event["workflow_run"].update({"ref": "main", "artifact_id": 999,
"sha256": "untrusted", "tooling": "untrusted"})
opener, _, error = self.execute()
self.assertIsNone(error)
opener.return_value.open.assert_called_once()
request = opener.return_value.open.call_args.args[0]
self.assertEqual(request.full_url,
"https://api.github.com/repos/storytold/filmcraft/actions/workflows/nightly-sign.yml/dispatches")
self.assertEqual(request.get_method(), "POST")
self.assertEqual(json.loads(request.data), {"ref": "release", "inputs": {
"producer_run_id": "71", "producer_run_attempt": "1"}})
self.assertGreater(opener.return_value.open.call_args.kwargs["timeout"], 0)
def test_wrong_top_level_context_refuses_before_network(self):
for key, value in (("GITHUB_REPOSITORY", "other/filmcraft"),
("GITHUB_EVENT_NAME", "workflow_dispatch")):
with self.subTest(key=key):
self.assert_refused(env={**self.env, key: value})
def test_foreign_or_noncompleted_events_refuse_before_network(self):
for key, value in (("action", "requested"),
("repository", {"full_name": "other/filmcraft"})):
with self.subTest(key=key):
self.assert_refused(event={**self.event, key: value})
def test_wrong_producer_identity_status_and_manual_retries_refuse(self):
for key, value in (("head_repository", {"full_name": "other/filmcraft"}),
("head_branch", "release"), ("head_branch", "refs/tags/main"),
("path", ".github/workflows/release.yml"), ("status", "in_progress"),
("conclusion", "failure"), ("conclusion", "cancelled"),
("event", "workflow_dispatch"), ("event", "pull_request"),
("run_attempt", 2)):
event = copy.deepcopy(self.event)
event["workflow_run"][key] = value
with self.subTest(key=key, value=value):
self.assert_refused(event=event)
def test_ids_are_not_coerced_from_strings_booleans_or_fractional_values(self):
for key in ("id", "run_attempt"):
for value in (None, False, True, 0, -1, 1.5, "1", "1;evil", [], {}):
event = copy.deepcopy(self.event)
event["workflow_run"][key] = value
with self.subTest(key=key, value=value):
self.assert_refused(event=event)
def test_missing_metadata_never_contacts_api(self):
for key in self.event["workflow_run"]:
event = copy.deepcopy(self.event)
del event["workflow_run"][key]
with self.subTest(key=key):
self.assert_refused(event=event)
def test_redirect_handler_refuses_instead_of_forwarding_authorization(self):
_, scope, error = self.execute()
self.assertIsNone(error)
with self.assertRaisesRegex(RuntimeError, "redirects are forbidden"):
scope["NoRedirect"]().redirect_request(None, None, 302, "found", {}, "https://untrusted.invalid")
def test_failed_http_request_is_not_retried_or_reported_successful(self):
for error in (TimeoutError("synthetic timeout"), urllib.error.URLError("synthetic failure")):
with self.subTest(error=type(error).__name__):
opener, _, caught = self.execute(failure=error)
self.assertIs(caught, error)
opener.return_value.open.assert_called_once()
response = Response()
response.status = 202
opener, _, error = self.execute(response=response)
self.assertIsNotNone(error)
opener.return_value.open.assert_called_once()
class TrustedSourcePreparation(unittest.TestCase):
def test_sonar_classifies_only_the_exact_packaging_fixture_runners(self):
source = (ROOT / "sonar-project.properties").read_text()
self.assertEqual(re.findall(r"(?m)^sonar.sources=(.*)$", source), ["."])
self.assertEqual(re.findall(r"(?m)^sonar.tests=(.*)$", source), ["packaging"])
inclusions = re.findall(r"(?m)^sonar.test.inclusions=(.*)$", source)
self.assertEqual(len(inclusions), 1)
entries = inclusions[0].split(",")
expected = {"packaging/nightly-tests.py", "packaging/nightly-archive-tests.py",
"packaging/macos/nightly_plist_tests.py", "packaging/macos/nightly_sign_tests.py",
"packaging/windows/nightly-package-tests.ps1",
"packaging/windows/nightly-signing-tests.ps1", "packaging/nightly-release-tests.py"}
self.assertEqual(set(entries), expected, "classify exact fixtures, never production helpers or wildcard scope")
self.assertEqual(len(entries), len(expected), "duplicate fixture classification")
def test_policy_example_keeps_explicit_v3_and_unresolved_authority(self):
policy = json.loads((ROOT / "docs/nightly-signing-policy.example.json").read_text())
expected = {"schema", "repository", "repository_id", "producer_workflow_id",
"producer_workflow_path", "producer_tooling_revision", "producer_workflow_ref",
"signer_workflow_path", "signer_tooling_revision", "release_branch", "manual_actors",
"automatic_signer_actors", "max_age_seconds", "candidate_policy",
"max_artifact_bytes", "platforms"}
self.assertEqual(set(policy), expected, "no single-platform v2 fields or implicit migration")
self.assertEqual(policy["schema"], "craft-nightly-release-policy/v3")
self.assertEqual(policy["manual_actors"], [])
self.assertEqual(policy["automatic_signer_actors"], [])
for key in ("repository_id", "producer_workflow_id", "producer_tooling_revision",
"producer_workflow_ref", "signer_tooling_revision", "max_age_seconds",
"max_artifact_bytes"):
with self.subTest(unresolved=key):
self.assertIsNone(policy[key], "the example must not invent production authority")
def test_policy_platforms_are_exactly_what_the_producer_builds(self):
policy = json.loads((ROOT / "docs/nightly-signing-policy.example.json").read_text())
built = producer_platforms((ROOT / ".github/workflows/nightly.yml").read_text())
self.assertEqual(built, list(NIGHTLY_PLATFORMS), "one release carries Windows, Linux and macOS")
self.assertEqual(set(policy["platforms"]), set(built), "a built platform without policy, or the reverse")
for platform, row in policy["platforms"].items():
field, _ = NIGHTLY_TRUST[platform]
with self.subTest(platform=platform):
self.assertEqual(set(row), {"unsigned_artifact_name", "trust"})
self.assertEqual(set(row["trust"]), {field}, "each platform has only its own trust anchor")
def test_candidate_example_has_exact_v3_fields_without_provider_scope_claim(self):
candidate = json.loads((ROOT / "docs/nightly-signing-policy.example.json").read_text())["candidate_policy"]
self.assertEqual(set(candidate), {"schema", "epoch", "repository", "branch", "required_workflows", "sonar"})
self.assertEqual(candidate["schema"], "craft-nightly-candidate-policy/v3")
self.assertIsNone(candidate["required_workflows"])
self.assertEqual(set(candidate["sonar"]), {"organization", "project", "app_id", "check_name",
"details_url", "issue_types", "accepted_conditions", "required_conditions", "debt"})
self.assertTrue(all(value is None for value in candidate["sonar"].values()), "real identity/debt is unresolved")
def test_one_producer_and_one_signer_job_carry_every_platform(self):
for name, job in (("nightly.yml", "unsigned"), ("nightly-sign.yml", "release")):
jobs = (ROOT / ".github/workflows" / name).read_text().split("\njobs:\n", 1)[1]
with self.subTest(workflow=name):
self.assertEqual(re.findall(r"(?m)^ ([^\s#][^:]*):", jobs), [job],
"a platform is a list entry, not a separately activatable job")
signer = (ROOT / ".github/workflows/nightly-sign.yml").read_text()
self.assertNotRegex(signer, r"(?m)^\s*platforms?:", "the release policy, not the caller, admits platforms")
def test_malformed_or_narrowed_platform_lists_are_rejected(self):
source = (ROOT / ".github/workflows/nightly.yml").read_text()
current = "platforms: '[\"windows-x86_64\",\"linux-x86_64\",\"macos-aarch64\"]'"
self.assertIn(current, source)
for new in ("platforms: '[\"linux-x86_64\"]'",
"platforms: '[\"linux-x86_64\",\"macos-aarch64\"]'",
"platforms: '[\"windows-x86_64\",\"linux-x86_64\",\"linux-x86_64\"]'",
"platforms: '[\"windows-x86_64\",\"macos-x86_64\"]'",
"platforms: '[\"windows-x86_64\",\"linux-arm64\"]'",
"platforms: '[\"windows-x86_64\", \"linux-x86_64\"]'",
"platforms: [\"windows-x86_64\",\"linux-x86_64\"]",
"platforms: ${{ vars.NIGHTLY_PLATFORMS }}",
"platforms: '{\"windows-x86_64\":1}'",
current + "\n " + current):
with self.subTest(change=new), self.assertRaises(ValueError):
producer_platforms(source.replace(current, new))
with self.assertRaises(ValueError):
producer_platforms(source.replace(" " + current + "\n", ""))
def test_no_nightly_schedule_is_registered(self):
for name, event in (("nightly.yml", "workflow_dispatch"),
("nightly-dispatch.yml", "workflow_run"),
("nightly-sign.yml", "workflow_dispatch")):
source = (ROOT / ".github/workflows" / name).read_text()
events = source.split("\non:\n", 1)[1].split("\npermissions:", 1)[0]
triggers = [line for line in events.splitlines() if line.startswith(" ")
and not line.startswith(" ") and line.strip() and not line.lstrip().startswith("#")]
with self.subTest(workflow=name):
self.assertEqual(triggers, [f" {event}:"], "schedule/activation needs explicit review")
def test_signer_serialization_contract_is_enforced(self):
assert_nightly_serialization((ROOT / ".github/workflows/nightly-sign.yml").read_text())
def test_weakened_or_malformed_serialization_is_rejected(self):
source = (ROOT / ".github/workflows/nightly-sign.yml").read_text()
for old, new in (
("cancel-in-progress: false", "cancel-in-progress: true"),
("cancel-in-progress: false", "cancel-in-progress: ${{ github.event_name == 'push' }}"),
("cancel-in-progress: false\n", ""),
("group: filmcraft-nightly-release", "group: ${{ github.run_id }}"),
("group: filmcraft-nightly-release", "group: release-${{ github.ref }}"),
("concurrency:\n", "concurrency: ${{ github.run_id }}\n"),
("concurrency:\n", " concurrency:\n"),
):
with self.subTest(change=new), self.assertRaises(ValueError):
assert_nightly_serialization(source.replace(old, new))
# The flavor's stricter form adds `queue: max`; a caller may omit it, never weaken it.
queued = source.replace("cancel-in-progress: false", "cancel-in-progress: false\n queue: max")
assert_nightly_serialization(queued)
for value in ("queue: single", "queue: invalid", "queue: ${{ github.run_id }}", "queue:"):
with self.subTest(queue=value), self.assertRaises(ValueError):
assert_nightly_serialization(queued.replace("queue: max", value))
duplicated = queued.replace("cancel-in-progress: false", "cancel-in-progress: false\n queue: max")
with self.assertRaises(ValueError):
assert_nightly_serialization(duplicated)
def test_no_cache_actions_or_cache_setup_options_in_app_trusted_closure(self):
# Required R3 static guard for app workflows only; activation must extend
# this check to every reviewed immutable shared trusted callee.
for name in ("nightly.yml", "nightly-sign.yml", "nightly-dispatch.yml"):
source = (ROOT / ".github/workflows" / name).read_text()
executable = "\n".join(line for line in source.splitlines()
if not line.lstrip().startswith("#"))
with self.subTest(workflow=name):
self.assertNotRegex(executable, r"(?im)^\s*(?:-\s*)?uses:\s*[^\n]*cache")
self.assertNotRegex(executable, r"(?im)^\s*[^\s:#]*cache[^\s:#]*:")
self.assertNotRegex(executable, r"(?im)^\s*(?:environment|secrets):")
self.assertNotIn("secrets.", executable)
class NightlyEnabledCallers(unittest.TestCase):
"""Producer and signer run only in their exact context, for the reviewed manual actors, with no schedule."""
GUARDS = {
"nightly.yml": "github.repository == 'storytold/filmcraft' && github.ref == 'refs/heads/main' && "
"github.ref_type == 'branch' && (github.event_name == 'schedule' || "
"github.event_name == 'workflow_dispatch')",
"nightly-sign.yml": "github.repository == 'storytold/filmcraft' && github.event_name == 'workflow_dispatch' && "
"github.ref == 'refs/heads/release' && github.ref_type == 'branch'",
}
def test_enabled_jobs_keep_exact_context_guards(self):
for name, expected in self.GUARDS.items():
jobs = (ROOT / ".github/workflows" / name).read_text().split("\njobs:\n", 1)[1]
guards = job_conditions(jobs)
with self.subTest(workflow=name):
self.assertEqual(len(guards), 1)
indicator, expression = guards[0]
self.assertEqual(indicator, ">-")
self.assertEqual(" ".join(expression.split()), expected, "guards may only change with review")
def test_continuation_lines_of_any_scalar_form_reach_the_guard_checks(self):
for name in ("nightly.yml", "nightly-sign.yml"):
source = (ROOT / ".github/workflows" / name).read_text()
expected = self.GUARDS[name]
guard = re.search(r"(?m)^ if: >-\n(?: [^\n]*\n)+", source)[0]
for replacement in (guard + " || true\n", " if: " + expected + "\n || true\n"):
jobs = source.replace(guard, replacement).split("\njobs:\n", 1)[1]
with self.subTest(workflow=name, replacement=replacement[-30:]):
(indicator, expression), = job_conditions(jobs)
self.assertFalse(indicator == ">-" and " ".join(expression.split()) == expected)
def test_manual_actors_are_the_release_managers_in_caller_and_policy(self):
source = (ROOT / ".github/workflows/nightly.yml").read_text()
policy = json.loads(INSTALLED_POLICY.read_text())
self.assertEqual(reviewed_manual_actors(source, policy), RELEASE_MANAGERS)
self.assertEqual(policy["automatic_signer_actors"], [], "no automatic signer without a schedule")
def test_an_actor_outside_the_release_managers_is_refused(self):
source = (ROOT / ".github/workflows/nightly.yml").read_text()
policy = json.loads(INSTALLED_POLICY.read_text())
caller = json.dumps(RELEASE_MANAGERS, separators=(",", ":"))
widened = sorted(RELEASE_MANAGERS + ["echelon-robot"], key=str.lower)
for change in ("caller", "policy", "both", "order", "case"):
mutated_source, mutated_policy = source, copy.deepcopy(policy)
if change in ("caller", "both"):
mutated_source = source.replace(caller, json.dumps(widened, separators=(",", ":")))
if change in ("policy", "both"):
mutated_policy["manual_actors"] = widened
if change == "order":
mutated_policy["manual_actors"] = list(reversed(RELEASE_MANAGERS))
if change == "case":
mutated_policy["manual_actors"] = [login.lower() for login in RELEASE_MANAGERS]
with self.subTest(change=change), self.assertRaises(ValueError):
reviewed_manual_actors(mutated_source, mutated_policy)
def push_block(source):
"""The whole `push:` mapping, blank lines and nested keys included.
A blank line does not end a YAML mapping, so the block is delimited by indentation rather than
by contiguous non-empty lines; a path filter after a blank line stays visible to the check.
"""
lines = source.splitlines()
for index, line in enumerate(lines):
if re.fullmatch(r" push:.*", line):
block = []
for follow in lines[index + 1:]:
if follow.strip() and not follow.startswith(" "):
break
block.append(follow)
return "\n".join(block)
return None
class NightlyInstalledPolicy(unittest.TestCase):
"""The installed v3 policy matches the callers, the repository and its documented sources."""
def setUp(self):
self.assertFalse(INSTALLED_POLICY.is_symlink())
self.policy = json.loads(INSTALLED_POLICY.read_text())
def test_exact_v3_fields_and_repository_identity(self):
expected = {"schema", "repository", "repository_id", "producer_workflow_id",
"producer_workflow_path", "producer_tooling_revision", "producer_workflow_ref",
"signer_workflow_path", "signer_tooling_revision", "release_branch", "manual_actors",
"automatic_signer_actors", "max_age_seconds", "candidate_policy",
"max_artifact_bytes", "platforms"}
self.assertEqual(set(self.policy), expected)
self.assertEqual(self.policy["schema"], "craft-nightly-release-policy/v3")
self.assertEqual(self.policy["repository"], "storytold/filmcraft")
self.assertEqual(self.policy["release_branch"], "release")
self.assertIs(type(self.policy["repository_id"]), int)
self.assertGreater(self.policy["repository_id"], 0)
# producer_workflow_id is null until nightly.yml is registered on main; once set, a positive int.
if self.policy["producer_workflow_id"] is not None:
self.assertIs(type(self.policy["producer_workflow_id"]), int)
self.assertGreater(self.policy["producer_workflow_id"], 0)
self.assertNotEqual(self.policy["producer_workflow_id"],
self.policy["candidate_policy"]["required_workflows"][0]["workflow_id"],
"the producer is not its own quality workflow")
def test_paths_and_tooling_match_the_callers(self):
pin = caller_pin("nightly.yml")
self.assertEqual(caller_pin("nightly-sign.yml"), pin)
self.assertEqual(self.policy["producer_workflow_path"], ".github/workflows/nightly.yml")
self.assertEqual(self.policy["signer_workflow_path"], ".github/workflows/nightly-sign.yml")
self.assertEqual(self.policy["producer_tooling_revision"], pin)
self.assertEqual(self.policy["signer_tooling_revision"], pin)
self.assertEqual(self.policy["producer_workflow_ref"],
"storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@" + pin)
def test_platforms_equal_the_producer(self):
built = producer_platforms((ROOT / ".github/workflows/nightly.yml").read_text())
self.assertEqual(built, list(NIGHTLY_PLATFORMS))
self.assertEqual(set(self.policy["platforms"]), set(built))
def test_bounds(self):
self.assertIs(type(self.policy["max_age_seconds"]), int)
self.assertTrue(0 < self.policy["max_age_seconds"] <= 604800)
self.assertIs(type(self.policy["max_artifact_bytes"]), int)
self.assertTrue(0 < self.policy["max_artifact_bytes"] <= 16 * 1024 ** 3)
def test_candidate_workflows_run_on_every_main_push(self):
candidate = self.policy["candidate_policy"]
self.assertEqual(set(candidate), {"schema", "epoch", "repository", "branch", "required_workflows", "sonar"})
self.assertEqual(candidate["schema"], "craft-nightly-candidate-policy/v3")
self.assertEqual((candidate["repository"], candidate["branch"]), ("storytold/filmcraft", "main"))
self.assertTrue(isinstance(candidate["epoch"], str) and 0 < len(candidate["epoch"]) <= 128)
rows = candidate["required_workflows"]
self.assertTrue(rows)
for row in rows:
with self.subTest(workflow=row["workflow_path"]):
self.assertEqual(set(row), {"workflow_id", "workflow_path", "jobs"})
self.assertIs(type(row["workflow_id"]), int)
self.assertNotEqual(row["workflow_path"], self.policy["producer_workflow_path"])
source = (ROOT / row["workflow_path"]).read_text()
push = push_block(source)
self.assertIsNotNone(push, "a required workflow must run on main pushes")
self.assertIn("branches: [main]", push)
self.assertNotRegex(push, r"(?m)^\s+paths(?:-ignore)?:", "a path filter would leave candidates without a run")
names = [job["name"] for job in row["jobs"]]
self.assertEqual(len(names), len(set(names)))
for job in row["jobs"]:
self.assertEqual(set(job), {"name", "app_id", "applicability"})
self.assertEqual((job["app_id"], job["applicability"]), (15368, "required"))
def test_a_path_filter_after_a_blank_line_is_still_rejected(self):
workflow = "on:\n push:\n branches: [main]\n\n paths: ['src/**']\n workflow_dispatch: {}\n"
block = push_block(workflow)
self.assertIsNotNone(block)
self.assertIn("branches: [main]", block)
self.assertRegex(block, r"(?m)^\s+paths(?:-ignore)?:")
for ignored in ("paths: ['src/**']", "paths-ignore: ['docs/**']"):
with self.subTest(ignored=ignored):
variant = workflow.replace(ignored.split(":")[0] + ": ['src/**']", ignored)
self.assertRegex(push_block(variant), r"(?m)^\s+paths(?:-ignore)?:",
"a quoted or unquoted filter must not hide behind a blank line")
def test_sonar_identity_and_reviewed_scope(self):
sonar = self.policy["candidate_policy"]["sonar"]
properties = dict(line.split("=", 1) for line in (ROOT / "sonar-project.properties").read_text().splitlines()
if line and not line.startswith("#"))
self.assertEqual(sonar["organization"], properties["sonar.organization"])
self.assertEqual(sonar["project"], properties["sonar.projectKey"])
self.assertEqual((sonar["app_id"], sonar["check_name"]), (12526, "SonarCloud Code Analysis"))
self.assertEqual(sonar["details_url"], "https://sonarcloud.io/dashboard?id=" + sonar["project"] + "&branch=main")
accepted = {"bugs": "BUG", "vulnerabilities": "VULNERABILITY", "code_smells": "CODE_SMELL",
"security_rating": "VULNERABILITY", "new_security_rating": "VULNERABILITY"}
self.assertEqual({accepted[c["metric"]] for c in sonar["accepted_conditions"]}, set(sonar["issue_types"]))
metrics = [c["metric"] for c in sonar["accepted_conditions"] + sonar["required_conditions"]]
self.assertEqual(len(metrics), len(set(metrics)))
keys = [item["key"] for item in sonar["debt"]]
self.assertEqual(len(keys), len(set(keys)))
for item in sonar["debt"]:
with self.subTest(issue=item["key"]):
self.assertEqual(set(item), {"key", "rule", "component", "type", "severity", "hash"})
self.assertTrue(item["component"].startswith(sonar["project"] + ":"))
self.assertIn(item["type"], sonar["issue_types"])
self.assertRegex(item["hash"], r"^[0-9a-f]{32}$")
class NightlyTrustAnchors(unittest.TestCase):
"""The public stable identities each platform's signed nightly must carry (all three platforms)."""
def setUp(self):
self.policy = json.loads(INSTALLED_POLICY.read_text())
def test_each_platform_row_names_its_fixed_artifact_kind_and_stable_identity(self):
self.assertEqual(set(self.policy["platforms"]), set(NIGHTLY_TRUST))
for platform, (field, value) in NIGHTLY_TRUST.items():
row = self.policy["platforms"][platform]
with self.subTest(platform=platform):
self.assertEqual(row["unsigned_artifact_name"], f"nightly-unsigned-{platform}",
"the artifact kind is fixed by platform, never a caller pattern")
self.assertEqual(row["trust"], {field: value}, "trust must be stable's public identity")
def test_trust_values_have_the_shapes_the_shared_signer_accepts(self):
rows = self.policy["platforms"]
self.assertRegex(rows["macos-aarch64"]["trust"]["apple_team_id"], r"^[A-Z0-9]{10}$")
self.assertRegex(rows["linux-x86_64"]["trust"]["fingerprint"], r"^[0-9A-F]{40}$")
subject = rows["windows-x86_64"]["trust"]["publisher_subject"]
self.assertTrue(0 < len(subject) <= 2048 and not set(subject) & {"\r", "\n", "\0"})
def test_committed_linux_key_is_exactly_the_one_stable_public_key(self):
self.assertFalse(LINUX_KEY.is_symlink(), "the key file must be a regular committed file")
armored = LINUX_KEY.read_text(encoding="ascii")
self.assertEqual(armored.count("-----BEGIN PGP"), 1, "exactly one armored block")
self.assertEqual(openpgp_primary_fingerprints(armored), [NIGHTLY_TRUST["linux-x86_64"][1]],
"exactly one primary key, and it is the stable release key the policy trusts")
def test_key_reader_refuses_secret_or_extra_material(self):
armored = LINUX_KEY.read_text(encoding="ascii")
for change in (armored.replace("PUBLIC KEY BLOCK", "PRIVATE KEY BLOCK"),
armored.replace("-----END PGP PUBLIC KEY BLOCK-----\n", ""),
"Comment: extra\n" + armored):
with self.subTest(change=change[:40]), self.assertRaises(ValueError):
openpgp_primary_fingerprints(change)
def test_both_callers_use_one_shared_pin_in_uses_and_tooling_revision(self):
pins = set()
for name, callee in (("nightly.yml", "nightly-unsigned.yml"), ("nightly-sign.yml", "nightly-release.yml")):
source = (ROOT / ".github/workflows" / name).read_text()
uses = re.findall(r"(?m)^ uses: storytold/craft-common-actions/\.github/workflows/"
+ re.escape(callee) + r"@(\S+)$", source)
tooling = re.findall(r"(?m)^ tooling-revision: (\S+)$", source)
with self.subTest(workflow=name):
self.assertEqual(len(uses), 1)
self.assertEqual(tooling, uses, "the defining workflow SHA and tooling input must match")
pins.update(uses)
self.assertEqual(len(pins), 1, "producer and signer must pin the same shared commit")
self.assertRegex(pins.pop(), r"^[0-9a-f]{40}$", "pin a full immutable commit, never a branch or placeholder")
class LinuxNightlyLaunchers(unittest.TestCase):
"""Source contracts for the Linux Nightly launchers (argv behaviour: the bash suites)."""
PROFILE = "${XDG_DATA_HOME:-${HOME:-}/.local/share}/filmcraft-nightly/profile"
def launchers(self):
package = (ROOT / "packaging/linux/package.sh").read_text()
heredocs = re.findall(r"<<'WRAPPER'\n(.*?)\nWRAPPER\n", package, re.DOTALL)
self.assertGreaterEqual(len(heredocs), 1, "the deb/rpm Nightly wrapper is missing")
files = {}
for name, path in (("tarball", "packaging/linux/nightly-launch.sh"),
("arch", "packaging/linux/nightly-arch-launch.sh"),
("apprun", "packaging/linux/AppRun"),
("flatpak", "packaging/linux/flatpak-bundle.sh")):
files[name] = (ROOT / path).read_text()
flatpak = re.findall(r"<<'WRAPPER'\n(.*?)\nWRAPPER\n", files["flatpak"], re.DOTALL)
self.assertEqual(len(flatpak), 1, "the Flatpak Nightly wrapper is missing")
files["flatpak"] = flatpak[0]
files["deb/rpm"] = "\n".join(heredocs)
return files
def test_every_linux_launcher_starts_the_gui_with_the_launcher_profile(self):
for name, source in self.launchers().items():
with self.subTest(launcher=name):
self.assertIn("--launch-profile nightly-v1", source)
self.assertIn(self.PROFILE, source, "one profile root, outside stable and the install")
self.assertIn('case "${1-}" in', source)
self.assertIn("--profile-root | --version | -V | --help | -h", source)
# A caller-written `--` is stripped: the launcher's own separator must never
# arrive at the app as a file name.
self.assertIn('if [ "${1-}" = -- ]; then shift; fi', source)
def test_no_linux_wrapper_routes_the_profile_through_the_environment(self):
# The flavor refuses FILMCRAFT_DATA_DIR with a nightly profile: a wrapper that exported it
# would make its own package exit 2.
offenders = [path.name for path in sorted((ROOT / "packaging/linux").iterdir())
if path.suffix in {".sh", ".yml", ".yaml"} and "FILMCRAFT_DATA_DIR" in path.read_text(errors="ignore")]
self.assertEqual(offenders, [], "the Launcher owns the Nightly root, not the environment")
def test_the_package_keeps_the_gui_off_path_and_the_mediatypes_off_the_entry(self):
package = (ROOT / "packaging/linux/package.sh").read_text()
self.assertIn("/usr/lib/filmcraft-nightly/filmcraft", package)
self.assertEqual(package.count("'/<mediatype>/d'"), 2, "the deb/rpm and AppImage metainfo")
self.assertIn("--features filmcraft/neural-voices", package)
self.assertIn("--features filmcraft/neural-voices", (ROOT / "packaging/nightly-common.sh").read_text(),
"the Nightly tar must keep the voices the official package builds with")
self.assertIn("--features filmcraft/neural-voices", (ROOT / "packaging/windows/nightly.ps1").read_text(),
"the Windows Nightly must keep the voices the official package builds with")
self.assertIn('Icon=$NIGHTLY_DESK_ID', package)
# The drop commands are a prefix of the first sed expression: `sed "$DROP_LIB_TREE" -e ...`
# reads an empty or command-shaped argument as an input file and dies.
self.assertNotIn('sed "$DROP_LIB_TREE"', package)
self.assertIn('sed "${DROP_LIB_TREE}s|', package)
self.assertIn('cp "$ROOT/ATTRIBUTION.md" "$destination/"', (ROOT / "packaging/nightly-common.sh").read_text(),
"the tar and the macOS bundle require ATTRIBUTION.md")
def test_the_appimage_apprun_is_a_script_only_for_nightly(self):
package = (ROOT / "packaging/linux/package.sh").read_text()
# Stable keeps Dylan's `ln -s usr/bin/filmcraft AppRun`: installing the script there would
# write desktop entries and icons on every stable start, which is new stable behaviour.
section = package[package.index(' APPDIR="$WORK/FilmCraft.AppDir"'):]
nightly, stable = section.split("\n else\n", 1)
self.assertIn('install -Dm755 "$HERE/AppRun" "$APPDIR/AppRun"', nightly, "the Nightly installs the AppRun script")
self.assertNotIn("ln -s usr/bin/filmcraft", nightly, "a Nightly AppRun must not be a symlink")
self.assertNotIn('install -Dm755 "$HERE/AppRun"', stable, "stable installs no desktop entry or icon on start")
self.assertIn('ln -s usr/bin/filmcraft "$APPDIR/AppRun"', stable)
self.assertIn('$0 == "CHANNEL=stable" { print "CHANNEL=nightly-v1"; next }', nightly)
apprun = ROOT / "packaging/linux/AppRun"
self.assertTrue(apprun.is_file() and not apprun.is_symlink())
self.assertTrue(apprun.stat().st_mode & 0o111, "AppRun must be executable")
def test_the_plain_nightly_tar_ships_the_launcher_beside_the_gui(self):
archive = (ROOT / "packaging/nightly-archive.py").read_text()
self.assertIn('{"filmcraft", "filmcraft-bin", "filmcraft-nightly.png"}', archive)
self.assertIn('"filmcraft", "filmcraft-bin", "filmcraft-nightly.png", "README.md"', archive)
self.assertIn('"$STAGE/filmcraft-bin"', (ROOT / "packaging/linux/nightly.sh").read_text())
check = (ROOT / "packaging/linux/nightly-check.sh").read_text()
self.assertIn("for name in filmcraft filmcraft-bin filmcraft-nightly.png", check)
def test_the_nightly_flatpak_install_keeps_the_launcher_and_drops_the_mime_tree(self):
source = (ROOT / "packaging/linux/flatpak-bundle.sh").read_text()
self.assertIn("/app/libexec/filmcraft", source)
self.assertIn("/share\\/mime\\/packages\\//d", source)
self.assertIn("--talk-name=org\\.freedesktop\\.Flatpak/d", source)
if __name__ == "__main__":
unittest.main(verbosity=2)
+25
View File
@@ -0,0 +1,25 @@
#!/usr/bin/env python3
"""Run the existing synthetic packaging suites together; no app build or signing."""
import importlib.util
from pathlib import Path
import unittest
def main() -> int:
here = Path(__file__).resolve().parent
suite = unittest.TestSuite()
for name, relative in (
("filmcraft_archive_suite", "nightly-archive-tests.py"),
("filmcraft_plist_suite", "macos/nightly_plist_tests.py"),
("filmcraft_release_dispatch_suite", "nightly-release-tests.py"),
("filmcraft_mac_sign_suite", "macos/nightly_sign_tests.py"),
):
spec = importlib.util.spec_from_file_location(name, here / relative)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
suite.addTests(unittest.defaultTestLoader.loadTestsFromModule(module))
return 0 if unittest.TextTestRunner(verbosity=2).run(suite).wasSuccessful() else 1
if __name__ == "__main__":
raise SystemExit(main())
+139
View File
@@ -0,0 +1,139 @@
"""POSIX packaging I/O rooted at a caller-owned private working directory.
The build launcher chooses cwd independently of file arguments (Linux uses its
mktemp directory). This is not a sandbox against root or a malicious same-UID
caller, and inode-check/unlink cleanup is not an atomic replacement-race primitive.
"""
import contextlib
import os
from pathlib import Path
import stat
def _component(name):
# A descriptor-relative open must name exactly one entry in its directory.
if not name or name in (".", "..") or os.path.basename(name) != name:
raise ValueError("build path components must be single names")
return os.path.basename(name)
class OwnedBuildRoot:
def __enter__(self):
self.directory = Path.cwd()
self.fd = os.open(".", os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
info = os.fstat(self.fd)
if info.st_uid != os.geteuid() or stat.S_IMODE(info.st_mode) & 0o077:
os.close(self.fd)
raise ValueError("packaging cwd must be an owned private build directory")
return self
def __exit__(self, *_error):
os.close(self.fd)
def _relative(self, path):
path = Path(path)
try:
relative = path.relative_to(self.directory) if path.is_absolute() else path
except ValueError as error:
raise ValueError("path is outside the owned build directory") from error
if not relative.parts or ".." in relative.parts:
raise ValueError("empty or parent-traversing build path")
# Check an independently selected root, never the supplied filename's parent.
try:
parent = (self.directory / relative).parent.resolve(strict=True)
except OSError as error:
raise ValueError("build path parent must exist") from error
if not parent.is_relative_to(self.directory):
raise ValueError("resolved path escapes the owned build directory")
return relative
def _checked_parts(self, path):
relative = self._relative(path)
root = os.path.realpath(self.directory)
lexical = os.path.join(root, *relative.parts)
target = os.path.realpath(lexical)
if target == root or os.path.commonpath([root, target]) != root:
raise ValueError("resolved path escapes the owned build directory")
if target != lexical:
raise ValueError("build path must not pass through symlinks or aliases")
return [_component(part) for part in os.path.relpath(target, root).split(os.sep)]
def _parent(self, path):
parts = self._checked_parts(path)
current = os.dup(self.fd)
try:
for part in parts[:-1]:
next_fd = os.open(_component(part), os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=current)
os.close(current)
current = next_fd
return current, parts[-1]
except OSError as error:
os.close(current)
raise ValueError("build path parents must be non-symlink directories") from error
@contextlib.contextmanager
def reader(self, path, limit):
parent, name = self._parent(path)
try:
try:
descriptor = os.open(_component(name), os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=parent)
except OSError as error:
raise ValueError("build input must be a regular file without aliases") from error
finally:
os.close(parent)
info = os.fstat(descriptor)
if not stat.S_ISREG(info.st_mode) or info.st_size > limit:
os.close(descriptor)
raise ValueError("build input must be a regular file within its read bound")
with os.fdopen(descriptor, "rb") as stream:
yield stream
def read_bytes(self, path, limit):
with self.reader(path, limit) as stream:
data = stream.read(limit + 1)
if len(data) > limit:
raise ValueError("build input grew beyond its read bound")
return data
def children(self, path, limit):
relative = self._relative(path)
parent, name = self._parent(path)
try:
try:
descriptor = os.open(_component(name), os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=parent)
except OSError as error:
raise ValueError("build stage must be a non-symlink directory") from error
finally:
os.close(parent)
try:
entries = []
with os.scandir(descriptor) as iterator:
for entry in iterator:
if len(entries) >= limit:
raise ValueError("too many build stage members")
entries.append(self.directory / relative / entry.name)
return entries
finally:
os.close(descriptor)
@contextlib.contextmanager
def create(self, path):
parent, name = self._parent(path)
name = _component(name)
try:
descriptor = os.open(name, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o666, dir_fd=parent)
info = os.fstat(descriptor)
identity = (info.st_dev, info.st_ino)
try:
with os.fdopen(descriptor, "wb") as stream:
yield stream
except BaseException:
try:
current = os.stat(name, dir_fd=parent, follow_symlinks=False)
if (current.st_dev, current.st_ino) == identity:
os.unlink(_component(name), dir_fd=parent)
except FileNotFoundError:
pass
raise
finally:
os.close(parent)
+17
View File
@@ -33,3 +33,20 @@ shortcut/menu behaviour, cancellation, rollback or uninstall. Those still requir
payload in an authorised clean Windows test environment. Cross-architecture metadata is not
execution evidence on those architectures. Existing open installer/association PRs must be
reconciled before publication. Nothing here changes macOS/Linux native packaging conventions.
## Nightly channel (no installer)
The Nightly is not an MSI: it is a single GUI-only ZIP (`filmcraft-<version>-windows-x86_64-nightly.zip`)
holding `filmcraft.exe` and the notices. It registers no shortcuts, file associations or uninstall
entry, and it keeps its data in the ArtCraft Launcher's private profile, not in `%APPDATA%\FilmCraft`.
```
pwsh packaging/windows/package.ps1 -Arch x64 -Nightly -BuildOnly
```
requires `FILMCRAFT_BUILD_CHANNEL=nightly-v1`, `FILMCRAFT_VERSION`, `FILMCRAFT_BUILD_SHA` and
`FILMCRAFT_BUILD_DATE` from the producer run, and writes `...-nightly.unsigned.zip`: the trusted
signer produces the publishable archive in a separate job. `package.ps1` without `-Nightly` refuses
an executable whose `ProductName` is `FilmCraft Nightly`, so a nightly build cannot be shipped as
the stable MSI or portable ZIP. `sign.ps1 -CheckBuildEnvironment` fails if any signing variable
reaches compilation.
@@ -0,0 +1,95 @@
param([Parameter(Mandatory=$true)][string] $FixtureRoot)
. (Join-Path $PSScriptRoot 'nightly.ps1') -FunctionsOnly
function Assert([bool] $Value, [string] $Message) { if (-not $Value) { throw $Message } }
$spec = Get-NightlyArchiveSpec '0.23.1-nightly.20261120.17.1.gabcdef012345' 'x64'
Assert ($spec.Archive -eq 'filmcraft-0.23.1-nightly.20261120.17.1.gabcdef012345-windows-x86_64-nightly.zip') 'wrong nightly artifact name'
Assert ($spec.Executables.Count -eq 1 -and $spec.Executables[0] -eq 'filmcraft.exe') 'nightly must not ship the unqualified CLI'
Assert ($spec.AppId -eq 'ai.storyteller.filmcraft.nightly-v1') 'nightly identity is not distinct'
foreach ($arch in @('x86', 'arm64')) {
$refused = $false
try { Get-NightlyArchiveSpec '0.23.1' $arch | Out-Null } catch { $refused = $true }
Assert $refused 'unsupported target was accepted'
}
foreach ($bad in @('', '0.23.1', '../other', '0.23.1/elsewhere')) {
$refused = $false
try { Get-NightlyArchiveSpec $bad 'x64' | Out-Null } catch { $refused = $true }
Assert $refused 'unsafe artifact version was accepted'
}
Assert-NightlyFlavor 'FilmCraft Nightly' 'FilmCraft 0.23.1-nightly.20261120.17.1.gabcdef012345 (nightly-v1)' '0.23.1-nightly.20261120.17.1.gabcdef012345'
foreach ($pair in @(@('FilmCraft', 'FilmCraft 0.23.1 (nightly-v1)'), @('FilmCraft Nightly', 'FilmCraft 0.23.1'))) {
$refused = $false
try { Assert-NightlyFlavor $pair[0] $pair[1] '0.23.1-nightly.20261120.17.1.gabcdef012345' } catch { $refused = $true }
Assert $refused 'stable or mismatched build flavor was accepted'
}
$sha = 'abcdef0123456789abcdef0123456789abcdef01'
$good = '0.23.1-nightly.20261120.17.1.gabcdef012345'
Assert-NightlySource $good $sha '2026-11-20' $sha ''
$cases = @(
@('missing commit', $good, '', '2026-11-20', $sha, ''),
@('short commit', $good, 'abcdef012345', '2026-11-20', $sha, ''),
@('uppercase commit', $good, $sha.ToUpper(), '2026-11-20', $sha.ToUpper(), ''),
@('version names another commit', '0.23.1-nightly.20261120.17.1.g000000000000', $sha, '2026-11-20', $sha, ''),
@('missing date', $good, $sha, '', $sha, ''),
@('date differs from version', $good, $sha, '2026-11-21', $sha, ''),
@('other commit checked out', $good, $sha, '2026-11-20', ('0' * 40), ''),
@('dirty tree', $good, $sha, '2026-11-20', $sha, ' M apps/filmcraft/src/main.rs')
)
foreach ($case in $cases) {
$refused = $false
try { Assert-NightlySource $case[1] $case[2] $case[3] $case[4] $case[5] } catch { $refused = $true }
Assert $refused "source identity accepted: $($case[0])"
}
Write-Output 'nightly packaging spec, target/version refusal, source identity and flavor-binding tests passed'
# Exercise the SAME production notice copier with the real repository layout, then inspect a ZIP.
if (-not $FixtureRoot -or -not [IO.Path]::IsPathRooted($FixtureRoot)) { throw 'supply an owned absolute -FixtureRoot for the notices/ZIP regression' }
$testRoot = Join-Path $FixtureRoot ("nightly-notices-" + [Guid]::NewGuid().ToString('N'))
try {
$repo = Join-Path $testRoot 'app'
$fontRepo = Join-Path $testRoot 'craft-fonts'
$family = Join-Path $fontRepo 'fonts\ExampleFamily'
$stage = Join-Path $testRoot 'stage'
New-Item -ItemType Directory -Force -Path $repo, $family, $stage | Out-Null
$rootNames = @('README.md', 'LICENSE', 'LICENSE-MIT', 'LICENSE-APACHE', 'NOTICE', 'ATTRIBUTION.md')
foreach ($name in $rootNames) { Set-Content -LiteralPath (Join-Path $repo $name) -Value "root-notice-$name" }
Set-Content -LiteralPath (Join-Path $family 'OFL.txt') -Value 'font-notice-example'
Copy-NightlyNotices $repo $fontRepo $stage
foreach ($name in @($rootNames) + @('OFL-ExampleFamily.txt')) {
Assert (Test-Path -LiteralPath (Join-Path $stage $name)) "missing staged notice $name"
}
$zip = Join-Path $testRoot 'notices.zip'
Compress-Archive -Path (Join-Path $stage '*') -DestinationPath $zip
$archive = [IO.Compression.ZipFile]::OpenRead($zip)
try {
$names = @($archive.Entries | ForEach-Object { $_.FullName })
foreach ($name in @($rootNames) + @('OFL-ExampleFamily.txt')) { Assert ($name -in $names) "missing archived notice $name" }
foreach ($forbidden in @('portable.txt', 'filmcraft-cli.exe')) { Assert ($forbidden -notin $names) "unexpected payload $forbidden" }
$entry = $archive.GetEntry('OFL-ExampleFamily.txt')
$reader = [IO.StreamReader]::new($entry.Open())
try { Assert ($reader.ReadToEnd().Contains('font-notice-example')) 'wrong font license bytes in ZIP' } finally { $reader.Dispose() }
} finally { $archive.Dispose() }
} finally {
if (Test-Path -LiteralPath $testRoot) { Remove-Item -LiteralPath $testRoot -Recurse -Force }
}
Write-Output 'nightly mock-repository root and font notices are present in stage and ZIP'
# The source state comes from git itself: the checked-out commit, then a dirty tree.
$gitRoot = Join-Path $FixtureRoot ("nightly-source-" + [Guid]::NewGuid().ToString('N'))
try {
New-Item -ItemType Directory -Force -Path $gitRoot | Out-Null
git -C $gitRoot init -q; git -C $gitRoot -c user.name=fixture -c user.email=fixture@invalid commit -q --allow-empty -m fixture
if ($LASTEXITCODE -ne 0) { throw 'cannot create the git fixture' }
$head = (git -C $gitRoot rev-parse HEAD).Trim()
$state = Get-NightlySourceState $gitRoot
Assert ($state.Head -ceq $head -and -not $state.Status) 'clean checkout not reported as clean at HEAD'
$version = '0.23.1-nightly.20261120.17.1.g' + $head.Substring(0, 12)
Assert-NightlySource $version $head '2026-11-20' $state.Head $state.Status
Set-Content -LiteralPath (Join-Path $gitRoot 'untracked.txt') -Value 'dirty'
$state = Get-NightlySourceState $gitRoot
$refused = $false
try { Assert-NightlySource $version $head '2026-11-20' $state.Head $state.Status } catch { $refused = $true }
Assert $refused 'a dirty checkout was accepted'
} finally {
if (Test-Path -LiteralPath $gitRoot) { Remove-Item -LiteralPath $gitRoot -Recurse -Force }
}
Write-Output 'nightly source state is read from git and a dirty checkout is refused'
@@ -0,0 +1,83 @@
param(
[Parameter(Mandatory=$true)][string] $FixtureRoot,
[string] $PackagingRoot = $PSScriptRoot,
[switch] $PhaseGuardOnly
)
$ErrorActionPreference = 'Stop'
. (Join-Path $PackagingRoot 'nightly.ps1') -FunctionsOnly
$sign = Join-Path $PackagingRoot 'sign.ps1'
$names = @('WINDOWS_CERTIFICATE','WINDOWS_CERTIFICATE_PASSWORD','AZURE_TENANT_ID','AZURE_CLIENT_ID','AZURE_CLIENT_SECRET','AZURE_SIGNING_ENDPOINT','AZURE_SIGNING_ACCOUNT','AZURE_CERT_PROFILE')
function Clear-SigningFixtures { foreach ($name in $names) { [Environment]::SetEnvironmentVariable($name, $null) } }
function Assert-Policy([bool] $Value, [string] $Message) { if (-not $Value) { throw $Message } }
function Invoke-Refusal([scriptblock] $Operation, [string] $Message) {
$errorText = ''
try { & $Operation | Out-Null } catch { $errorText = $_.Exception.Message }
Assert-Policy ($errorText.Contains($Message)) "expected refusal: $Message; got: $errorText"
}
function global:cargo { $global:SigningFixtureCargoCalls++; throw 'FIXTURE_COMPILER_BOUNDARY' }
function global:Invoke-WebRequest { throw 'fixture must not perform signing downloads' }
$global:SigningFixtureCargoCalls = 0
if (-not [IO.Path]::IsPathRooted($FixtureRoot)) { throw 'use an owned absolute FixtureRoot' }
$root = Join-Path $FixtureRoot ('signing-policy-' + [Guid]::NewGuid().ToString('N'))
New-Item -ItemType Directory -Path $root | Out-Null
$version = '0.23.1-nightly.20261121.12345.1.gaaaaaaaaaaaa'
$env:FILMCRAFT_VERSION = $version
function Invoke-Build([switch] $BuildOnly) {
$arguments = @{Arch='x64';Version=$version;Target='x86_64-pc-windows-msvc';TargetDir=$root;Dist=(Join-Path $root 'dist')}
if ($BuildOnly) { $arguments.BuildOnly = $true }
& (Join-Path $PackagingRoot 'nightly.ps1') @arguments
}
try {
Clear-SigningFixtures
Invoke-Refusal { Invoke-Build } 'requires -BuildOnly'
Assert-Policy ($global:SigningFixtureCargoCalls -eq 0) 'default mode invoked Cargo'
Write-Output 'PASS: explicit-build-phase-required'
if ($PhaseGuardOnly) { return }
foreach ($name in @('WINDOWS_CERTIFICATE','WINDOWS_CERTIFICATE_PASSWORD','AZURE_CLIENT_SECRET')) {
Clear-SigningFixtures
[Environment]::SetEnvironmentVariable($name, 'generated-fixture-not-a-secret')
Invoke-Refusal { Invoke-Build -BuildOnly } 'Compilation must not receive signing credentials'
Assert-Policy ($global:SigningFixtureCargoCalls -eq 0) 'key-bearing compilation reached Cargo'
}
Write-Output 'PASS: credentials-rejected-before-compilation'
Clear-SigningFixtures
Invoke-Refusal { Invoke-Build -BuildOnly } 'FIXTURE_COMPILER_BOUNDARY'
Assert-Policy ($global:SigningFixtureCargoCalls -eq 1) 'clean compilation did not reach the mocked compiler boundary'
Assert-Policy (-not (Test-Path (Join-Path $root 'dist'))) 'mocked compilation produced an artifact'
Write-Output 'PASS: secret-free-build-reaches-only-mocked-boundary'
Clear-SigningFixtures
Invoke-Refusal { & $sign -Required -CheckOnly } 'Nightly signing is required'
$env:AZURE_CLIENT_SECRET = 'generated-partial-fixture'
Invoke-Refusal { & $sign -Required -CheckOnly } 'Nightly signing is required'
Write-Output 'PASS: required-signer-refuses-missing-and-partial-configuration'
Clear-SigningFixtures
$env:WINDOWS_CERTIFICATE = 'generated-presence-fixture-not-a-certificate'
& $sign -Required -CheckOnly
Clear-SigningFixtures
foreach ($name in $names | Where-Object { $_.StartsWith('AZURE_') }) { [Environment]::SetEnvironmentVariable($name, 'generated-presence-fixture') }
& $sign -Required -CheckOnly
Clear-SigningFixtures
Write-Output 'PASS: supported-configuration-presence-without-signing'
# Load the policy function without signing. These objects are not crypto evidence.
. $sign -CheckOnly
foreach ($value in @($null, [pscustomobject]@{Status='NotSigned';SignerCertificate='fixture'}, [pscustomobject]@{Status='HashMismatch';SignerCertificate='fixture'}, [pscustomobject]@{Status='Valid';SignerCertificate=$null})) {
Invoke-Refusal { Assert-AuthenticodeSignature $value } 'valid Authenticode signature'
}
Assert-AuthenticodeSignature ([pscustomobject]@{Status='Valid';SignerCertificate='generated-public-certificate-placeholder'})
Write-Output 'PASS: required-signature-policy-rejects-invalid-or-missing-signer'
$file = Join-Path $root 'owned-sentinel.exe'
[IO.File]::WriteAllText($file, 'generated sentinel, not a real executable')
$before = (Get-FileHash -LiteralPath $file -Algorithm SHA256).Hash
& $sign -Files $file
Assert-Policy ((Get-FileHash -LiteralPath $file -Algorithm SHA256).Hash -ceq $before) 'optional stable policy changed unsigned bytes'
Write-Output 'PASS: stable-optional-policy-preserves-owned-bytes'
} finally {
Clear-SigningFixtures
Remove-Item -LiteralPath $root -Recurse -Force
}
+132
View File
@@ -0,0 +1,132 @@
<# First nightly target only: Windows x86_64 GUI ZIP. No MSI, CLI, portable marker or association registration. #>
param(
[string] $Arch = 'x64',
[string] $Version,
[string] $Target,
[string] $TargetDir,
[string] $Dist,
[switch] $SkipBuild,
[switch] $BuildOnly,
[switch] $FunctionsOnly
)
$ErrorActionPreference = 'Stop'
function Get-NightlyArchiveSpec([string] $Version, [string] $Arch) {
if ($Arch -ne 'x64') { throw 'nightly-v1 supports only Windows x86_64' }
if (-not $Version -or $Version -cnotmatch '^\d+\.\d+\.\d+-nightly\.\d{8}\.\d+\.\d+\.g[0-9a-f]{12}\z') { throw 'invalid nightly artifact version' }
return @{
Archive = "filmcraft-$Version-windows-x86_64-nightly.zip"
UnsignedArchive = "filmcraft-$Version-windows-x86_64-nightly.unsigned.zip"
Executables = @('filmcraft.exe')
Channel = 'nightly-v1'
AppId = 'ai.storyteller.filmcraft.nightly-v1'
}
}
# The same source identity the Linux helper enforces (nightly-common.sh): the version names the
# commit being built, the date is the original run's, and the tree is clean.
function Assert-NightlySource([string] $Version, [string] $Sha, [string] $BuildDate, [string] $Head, [string] $Status) {
if ($Sha -cnotmatch '^[0-9a-f]{40}\z') { throw 'an exact source commit is required (FILMCRAFT_BUILD_SHA)' }
if ($Version -cnotmatch '^\d+\.\d+\.\d+-nightly\.\d{8}\.\d+\.\d+\.g[0-9a-f]{12}\z') { throw 'invalid nightly artifact version' }
if ($Version.Substring($Version.Length - 12) -cne $Sha.Substring(0, 12)) { throw 'version/source commit mismatch' }
if ($BuildDate -cnotmatch '^\d{4}-\d{2}-\d{2}\z') { throw 'the original run-created UTC date is required (FILMCRAFT_BUILD_DATE)' }
$versionDate = ($Version -split '-nightly\.', 2)[1].Substring(0, 8)
if ($BuildDate.Replace('-', '') -cne $versionDate) { throw 'version/original-run date mismatch' }
if ($Head -cne $Sha) { throw 'prepared source is not the checked-out commit' }
if ($Status) { throw 'nightly packaging requires the frozen clean source' }
}
function Get-NightlySourceState([string] $RepositoryRoot) {
$head = git -C $RepositoryRoot rev-parse HEAD
if ($LASTEXITCODE -ne 0) { throw 'cannot read the checked-out commit' }
$status = git -C $RepositoryRoot status --porcelain
if ($LASTEXITCODE -ne 0) { throw 'cannot read the source tree status' }
return @{ Head = "$head".Trim(); Status = ($status | Out-String).Trim() }
}
function Assert-NightlyFlavor([string] $ProductName, [string] $VersionOutput, [string] $ExpectedVersion) {
if ($ProductName -ne 'FilmCraft Nightly' -or $VersionOutput -cne "FilmCraft $ExpectedVersion (nightly-v1)") {
throw 'the executable is not the compiled nightly-v1 flavor'
}
}
function Copy-NightlyNotices([string] $RepositoryRoot, [string] $FontRepository, [string] $Destination) {
foreach ($name in 'README.md', 'LICENSE', 'LICENSE-MIT', 'LICENSE-APACHE', 'NOTICE', 'ATTRIBUTION.md') {
$source = Join-Path $RepositoryRoot $name
if (Test-Path -LiteralPath $source) { Copy-Item -LiteralPath $source -Destination $Destination }
}
if ($FontRepository) {
$fonts = Join-Path $FontRepository 'fonts'
if (-not (Test-Path -LiteralPath $fonts -PathType Container)) { throw 'CRAFT_FONTS_DIR has no fonts directory for the bundled notices' }
foreach ($family in Get-ChildItem -LiteralPath $fonts -Directory) {
$license = Join-Path $family.FullName 'OFL.txt'
if (Test-Path -LiteralPath $license) { Copy-Item -LiteralPath $license -Destination (Join-Path $Destination "OFL-$($family.Name).txt") }
}
}
}
if ($FunctionsOnly) { return }
if (-not $env:FILMCRAFT_VERSION -or $Version -cne $env:FILMCRAFT_VERSION) { throw 'nightly-v1 requires explicit FILMCRAFT_VERSION, not the Cargo version fallback' }
$Spec = Get-NightlyArchiveSpec $Version $Arch
if ($SkipBuild) { throw 'nightly-v1 forbids -SkipBuild; the executable flavor must be built in this operation' }
if ($Target -ne 'x86_64-pc-windows-msvc') { throw 'nightly-v1 target must be x86_64-pc-windows-msvc' }
if (-not $BuildOnly) { throw 'Nightly compilation requires -BuildOnly; final archives are produced in the separate trusted signing job' }
# No key values may enter compilation. This produces an internal intermediate, not a feed artifact.
& (Join-Path $PSScriptRoot 'sign.ps1') -CheckBuildEnvironment
$Root = (Resolve-Path (Join-Path $PSScriptRoot '..\..')).Path
$Source = Get-NightlySourceState $Root
Assert-NightlySource $Version $env:FILMCRAFT_BUILD_SHA $env:FILMCRAFT_BUILD_DATE $Source.Head $Source.Status
$oldChannel = $env:FILMCRAFT_BUILD_CHANNEL
try {
$env:FILMCRAFT_BUILD_CHANNEL = 'nightly-v1'
$env:FILMCRAFT_REQUIRE_WINRES = '1'
$env:CARGO_TARGET_X86_64_PC_WINDOWS_MSVC_RUSTFLAGS = '-C target-feature=+crt-static'
# The same features the stable package and the Linux/macOS Nightly builds use (build.rs reads
# FILMCRAFT_VERSION itself; FILMCRAFT_OVERRIDE_VERSION was never read here).
cargo build --release --locked -p filmcraft --features filmcraft/neural-voices --target $Target
if ($LASTEXITCODE -ne 0) { throw "nightly cargo build failed: $LASTEXITCODE" }
} finally {
$env:FILMCRAFT_BUILD_CHANNEL = $oldChannel
}
$Source = Get-NightlySourceState $Root
try { Assert-NightlySource $Version $env:FILMCRAFT_BUILD_SHA $env:FILMCRAFT_BUILD_DATE $Source.Head $Source.Status }
catch { throw "source changed during the build: $_" }
$Exe = Join-Path $TargetDir "$Target\release\filmcraft.exe"
$pe = [System.IO.File]::ReadAllBytes($Exe)
if ($pe.Length -lt 64) { throw 'truncated nightly PE executable' }
$offset = [BitConverter]::ToInt32($pe, 0x3C)
if ($offset -lt 0 -or $offset -gt $pe.Length - 0x5E) { throw 'invalid nightly PE header offset' }
if ([BitConverter]::ToUInt16($pe, $offset + 4) -ne 0x8664 -or [BitConverter]::ToUInt16($pe, $offset + 0x5C) -ne 2) {
throw 'nightly executable must be x86_64 Windows GUI'
}
$VersionInfo = (Get-Item -LiteralPath $Exe).VersionInfo
$ProductName = $VersionInfo.ProductName
if ($VersionInfo.ProductVersion -cne $Version) { throw 'nightly PE ProductVersion differs from the feed identity' }
# Check the embedded build flavor before invoking even the side-effect-free version query.
if ($ProductName -ne 'FilmCraft Nightly') { throw 'nightly executable is missing the embedded build flavor' }
$VersionOutput = (& $Exe --version | Out-String).Trim()
if ($LASTEXITCODE -ne 0) { throw 'nightly --version query failed' }
Assert-NightlyFlavor $ProductName $VersionOutput $Version
$Stage = Join-Path $TargetDir 'windows-package\nightly-v1-x86_64'
if (Test-Path -LiteralPath $Stage) { Remove-Item -LiteralPath $Stage -Recurse -Force }
New-Item -ItemType Directory -Force -Path $Stage | Out-Null
Copy-Item -LiteralPath $Exe -Destination (Join-Path $Stage 'filmcraft.exe')
# Signing happens only in the separate trusted step, using sign.ps1 -Required.
# The intermediate's filename cannot satisfy the feed-ready archive contract.
Copy-NightlyNotices $Root $env:CRAFT_FONTS_DIR $Stage
if ((Get-ChildItem -LiteralPath $Stage -Filter '*.exe').Count -ne 1 -or (Test-Path (Join-Path $Stage 'portable.txt'))) {
throw 'nightly stage contains an unexpected executable or portable fallback marker'
}
New-Item -ItemType Directory -Force -Path $Dist | Out-Null
$Zip = Join-Path $Dist $Spec.UnsignedArchive
if (Test-Path -LiteralPath $Zip) { throw 'Nightly output already exists; refusing to replace prepared artifact bytes' }
Compress-Archive -Path (Join-Path $Stage '*') -DestinationPath $Zip
$Archive = [System.IO.Compression.ZipFile]::OpenRead($Zip)
try {
$Names = @($Archive.Entries | ForEach-Object { $_.FullName })
if ('filmcraft.exe' -notin $Names -or 'filmcraft-cli.exe' -in $Names -or 'portable.txt' -in $Names) {
throw 'nightly ZIP payload violates the GUI-only profile contract'
}
} finally { $Archive.Dispose() }
Write-Output "Nightly build intermediate (not publishable): $Zip ($VersionOutput)"
+23 -3
View File
@@ -21,9 +21,14 @@
#>
param(
[ValidateSet('x64', 'x86', 'arm64')] [string] $Arch = 'x64',
[switch] $SkipBuild
[switch] $SkipBuild,
# Nightly: the isolated GUI-only channel (packaging/windows/nightly.ps1). -BuildOnly stops at
# the unsigned intermediate, which is all that may be produced without the trusted signer.
[switch] $Nightly,
[switch] $BuildOnly
)
$ErrorActionPreference = 'Stop'
if ($BuildOnly -and -not $Nightly) { throw '-BuildOnly is only for secret-free nightly compilation' }
$Root = (Resolve-Path (Join-Path $PSScriptRoot '..\..')).Path
function Invoke-Native([string] $What, [scriptblock] $Block) {
@@ -50,11 +55,23 @@ $Dist = if ($env:DIST) { $env:DIST } else { Join-Path $Root 'dist\release' }
$TargetDir = if ($env:CARGO_TARGET_DIR) { $env:CARGO_TARGET_DIR } else { Join-Path $Root 'target' }
New-Item -ItemType Directory -Force -Path $Dist | Out-Null
if (-not $env:FILMCRAFT_BUILD_SHA) { $env:FILMCRAFT_BUILD_SHA = (git -C $Root rev-parse HEAD 2>$null) }
if (-not $env:FILMCRAFT_BUILD_DATE) { $env:FILMCRAFT_BUILD_DATE = (Get-Date).ToUniversalTime().ToString('yyyy-MM-dd') }
# Nightly requires the prepared commit and original run date explicitly; nightly.ps1 checks both.
if (-not $Nightly) {
if (-not $env:FILMCRAFT_BUILD_SHA) { $env:FILMCRAFT_BUILD_SHA = (git -C $Root rev-parse HEAD 2>$null) }
if (-not $env:FILMCRAFT_BUILD_DATE) { $env:FILMCRAFT_BUILD_DATE = (Get-Date).ToUniversalTime().ToString('yyyy-MM-dd') }
}
Write-Output "FilmCraft $Version for Windows $Arch ($Target)"
if ($Nightly) {
& (Join-Path $PSScriptRoot 'nightly.ps1') -Arch $Arch -Version $Version -Target $Target -TargetDir $TargetDir -Dist $Dist -SkipBuild:$SkipBuild -BuildOnly:$BuildOnly
return
}
if (-not $SkipBuild) {
# A stable package is never built from a nightly channel leftover in the environment.
$env:FILMCRAFT_BUILD_CHANNEL = 'stable'
}
if (-not $SkipBuild) {
# Static CRT: no VC++ redistributable needed. Scoped to the target so host build scripts and
# proc-macros are unaffected.
@@ -84,6 +101,9 @@ foreach ($check in @(@('filmcraft.exe', 2), @('filmcraft-cli.exe', 3))) {
if ($h.Subsystem -ne $check[1]) { throw "$($check[0]) has PE subsystem $($h.Subsystem), expected $($check[1])" }
Write-Output "ok $($check[0]): $Arch, PE subsystem $($h.Subsystem)"
}
if ((Get-Item -LiteralPath (Join-Path $Bin 'filmcraft.exe')).VersionInfo.ProductName -eq 'FilmCraft Nightly') {
throw 'a nightly executable cannot be packaged as stable'
}
$Stage = Join-Path $TargetDir "windows-package\$Arch"
Remove-Item -Recurse -Force $Stage -ErrorAction SilentlyContinue
New-Item -ItemType Directory -Force -Path $Stage | Out-Null
+36 -5
View File
@@ -9,7 +9,9 @@
AZURE_SIGNING_ENDPOINT (e.g. https://eus.codesigning.azure.net),
AZURE_SIGNING_ACCOUNT, AZURE_CERT_PROFILE
With neither, it prints a warning and leaves the files unsigned (exit code 0), so test builds
still produce installers.
still produce installers. Nightly callers require signing with -Required and can
check signing configuration with -Required -CheckOnly. Compilation uses the
separate -CheckBuildEnvironment mode, without importing signing keys.
This is the one place to adapt when the signing setup changes (an HSM/cloud key, a different
timestamp server, ...). Optional overrides: WINDOWS_TIMESTAMP_URL, SIGNTOOL (path to signtool.exe).
@@ -18,11 +20,20 @@
pwsh packaging/windows/sign.ps1 dist/filmcraft.exe dist/Filmcraft.msi
#>
param(
[Parameter(Mandatory = $true, ValueFromRemainingArguments = $true)]
[string[]] $Files
[Parameter(Position = 0, ValueFromRemainingArguments = $true)]
[string[]] $Files,
[switch] $Required,
[switch] $CheckOnly,
[switch] $CheckBuildEnvironment
)
$ErrorActionPreference = 'Stop'
function Assert-AuthenticodeSignature($Signature) {
if (-not $Signature -or [string]$Signature.Status -cne 'Valid' -or -not $Signature.SignerCertificate) {
throw 'Required signing must produce a valid Authenticode signature and signer certificate'
}
}
function Write-Warn([string] $Message) {
if ($env:GITHUB_ACTIONS) { Write-Output "::warning::$Message" } else { Write-Warning $Message }
}
@@ -44,11 +55,28 @@ function Invoke-SignTool([string[]] $Arguments) {
if ($LASTEXITCODE -ne 0) { throw "signtool $($Arguments[0]) failed with exit code $LASTEXITCODE" }
}
$Files = $Files | ForEach-Object { (Resolve-Path $_).Path }
$haveCert = [bool]$env:WINDOWS_CERTIFICATE
$azureVars = 'AZURE_TENANT_ID', 'AZURE_CLIENT_ID', 'AZURE_CLIENT_SECRET', 'AZURE_SIGNING_ENDPOINT', 'AZURE_SIGNING_ACCOUNT', 'AZURE_CERT_PROFILE'
if ($CheckBuildEnvironment) {
if ($Required -or $CheckOnly -or $Files) { throw '-CheckBuildEnvironment is separate from signing' }
$names = @('WINDOWS_CERTIFICATE', 'WINDOWS_CERTIFICATE_PASSWORD') + $azureVars
if ($names | Where-Object { [Environment]::GetEnvironmentVariable($_) }) {
throw 'Compilation must not receive signing credentials; use a separate trusted signing step'
}
return
}
$haveCert = [bool]$env:WINDOWS_CERTIFICATE
$haveAzure = -not ($azureVars | Where-Object { -not [Environment]::GetEnvironmentVariable($_) })
if ($Required -and -not $haveCert -and -not $haveAzure) {
throw 'Nightly signing is required: configure WINDOWS_CERTIFICATE or the complete existing Azure signing configuration'
}
if ($CheckOnly) {
if ($Files) { throw '-CheckOnly does not sign files' }
return
}
if (-not $Files) { throw 'At least one file is required for signing' }
$Files = $Files | ForEach-Object { (Resolve-Path $_).Path }
if (-not $haveCert -and -not $haveAzure) {
Write-Warn "Windows signing secrets not set (WINDOWS_CERTIFICATE or AZURE_*): leaving unsigned: $($Files -join ', ')"
exit 0
@@ -96,6 +124,9 @@ try {
Invoke-SignTool ($common + @('/tr', $ts, '/dlib', $dlib.FullName, '/dmdf', $metadata) + $Files)
}
Invoke-SignTool (@('verify', '/pa', '/v') + $Files)
if ($Required) {
foreach ($file in $Files) { Assert-AuthenticodeSignature (Get-AuthenticodeSignature -LiteralPath $file) }
}
}
finally {
Remove-Item -Recurse -Force $tmp -ErrorAction SilentlyContinue
+6 -1
View File
@@ -1,3 +1,8 @@
sonar.projectKey=storytold_filmcraft
sonar.organization=storytold
sonar.coverage.exclusions=**/tools/**,**/docs/**,**/examples/**
# Setting test roots disables the CLI default; keep all production sources analyzed.
sonar.sources=.
# These exact fixture runners are tests, not production code. Do not exclude helpers.
sonar.tests=packaging
sonar.test.inclusions=packaging/nightly-tests.py,packaging/nightly-archive-tests.py,packaging/macos/nightly_plist_tests.py,packaging/macos/nightly_sign_tests.py,packaging/windows/nightly-package-tests.ps1,packaging/windows/nightly-signing-tests.ps1,packaging/nightly-release-tests.py
sonar.coverage.exclusions=**/tools/**,**/docs/**,**/examples/**,packaging/**