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

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

gate test shard 1/5 (and the Sonar scan that reads its coverage) fails on crates/ui-egui/src/doc_windows/tests.rs `a_document_made_current_in_presentation_mode_comes_to_the_front_after_it`, which main fails too (CI run 45581083304); this PR touches no ui-egui code.

Co-authored-by: Dylan M. Taylor <dylan@dylanmtaylor.com>
This commit is contained in:
Dylan M. Taylor
2026-11-25 07:01:37 -05:00
committed by GitHub
parent 58031f541b
commit 8b0b808857
65 changed files with 5831 additions and 132 deletions
+135
View File
@@ -0,0 +1,135 @@
{
"schema": "craft-nightly-release-policy/v3",
"repository": "storytold/vectorcraft",
"repository_id": 1398097510,
"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": "vectorcraft-nightly-20261124",
"repository": "storytold/vectorcraft",
"branch": "main",
"required_workflows": [
{
"workflow_id": 380135806,
"workflow_path": ".github/workflows/ci.yml",
"jobs": [
{
"name": "gate / select legs",
"app_id": 15368,
"applicability": "required"
},
{
"name": "gate / cache warm (ubuntu-24.04)",
"app_id": 15368,
"applicability": "required"
},
{
"name": "gate / test 1/5 (ubuntu-24.04)",
"app_id": 15368,
"applicability": "required"
},
{
"name": "gate / test 2/5 (ubuntu-24.04)",
"app_id": 15368,
"applicability": "required"
},
{
"name": "gate / test 3/5 (ubuntu-24.04)",
"app_id": 15368,
"applicability": "required"
},
{
"name": "gate / test 4/5 (ubuntu-24.04)",
"app_id": 15368,
"applicability": "required"
},
{
"name": "gate / test 5/5 (ubuntu-24.04)",
"app_id": 15368,
"applicability": "required"
},
{
"name": "gate / gate (ubuntu-24.04)",
"app_id": 15368,
"applicability": "required"
}
]
}
],
"sonar": {
"organization": "storytold",
"project": "storytold_vectorcraft",
"app_id": 12526,
"check_name": "SonarCloud Code Analysis",
"details_url": "https://sonarcloud.io/dashboard?id=storytold_vectorcraft&branch=main",
"issue_types": [
"VULNERABILITY"
],
"accepted_conditions": [],
"required_conditions": [
{
"metric": "new_reliability_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"
}
}
}
}
+72
View File
@@ -0,0 +1,72 @@
name: Nightly check
# The app-side Nightly pieces, checked without a feed run: the Python suites that read the archive,
# plist and signing scripts, the workflow contracts, and (on Windows) the packaging and signing
# PowerShell suites. The producer itself is .github/workflows/nightly.yml; the Apple-silicon bundle
# is built and verified by nightly-macos.yml behind the `full-ci` label.
on:
push:
branches: [main, release]
paths: [".github/workflows/nightly*.yml", "packaging/**", "apps/vectorcraft/**", "crates/ui-egui/src/os_window.rs"]
pull_request:
paths: [".github/workflows/nightly*.yml", "packaging/**", "apps/vectorcraft/**", "crates/ui-egui/src/os_window.rs"]
workflow_dispatch:
permissions:
contents: read
concurrency:
group: nightly-check-${{ github.ref }}
cancel-in-progress: true
jobs:
synthetic:
name: Packaging suites and script syntax
runs-on: ubuntu-latest
timeout-minutes: 20
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: Run the synthetic suites
run: python3 packaging/nightly-tests.py
- name: Parse every nightly shell script
run: |
set -euo pipefail
for script in packaging/nightly-common.sh packaging/linux/nightly.sh packaging/linux/nightly-launch.sh \
packaging/linux/nightly-arch-tar.sh packaging/macos/nightly.sh \
packaging/macos/nightly-lib.sh packaging/macos/nightly-sign.sh packaging/macos/nightly-verify.sh; do
bash -n "$script"
done
- name: Shellcheck
run: |
set -euo pipefail
sudo apt-get update -qq
sudo apt-get install -y -qq shellcheck
shellcheck -x -P packaging packaging/nightly-common.sh packaging/linux/nightly.sh \
packaging/linux/nightly-launch.sh \
packaging/macos/nightly.sh packaging/macos/nightly-lib.sh packaging/macos/nightly-sign.sh \
packaging/macos/nightly-verify.sh
windows:
name: Windows packaging and signing suites
runs-on: windows-latest
timeout-minutes: 20
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: Nightly packaging suite
shell: pwsh
run: ./packaging/windows/nightly-package-tests.ps1 -FixtureRoot $env:RUNNER_TEMP
- name: Nightly signing suite
shell: pwsh
run: ./packaging/windows/nightly-signing-tests.ps1 -FixtureRoot $env:RUNNER_TEMP
+90
View File
@@ -0,0 +1,90 @@
name: Nightly macOS build
# Builds the unsigned Apple-silicon VectorCraft Nightly (packaging/macos/nightly.sh) on a hosted
# macOS runner and checks the archive as the Launcher unpacks it, ending with the bundle's version
# query (packaging/macos/nightly-verify.sh --expect unsigned). No secrets and no environment: the real
# Nightly is signed and notarized by the shared release-ref signer (craft-common-actions), which calls
# packaging/macos/nightly-sign.sh.
on:
# macOS runners are shared with release builds and have a monthly minute cap: pull requests run
# this only with the `full-ci` label, never by changed paths. `labeled` so adding it starts a run.
pull_request:
types: [opened, synchronize, reopened, labeled]
workflow_dispatch:
permissions:
contents: read
# A newer push to a labelled PR cancels its older run. Any event that will not build (no `full-ci`
# label, or another label added) gets a group of its own, so it never cancels a real build.
concurrency:
group: nightly-macos-${{ 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:
build:
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: 120
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
fetch-depth: 0
# The release's pin (release.yml craft-fonts-ref), so the bundle's notices match a shipped build.
- name: Check out craft-fonts
uses: storytold/craft-common-actions/actions/checkout-craft-fonts@main
with:
ref: b076417b5880bd4154bd22f00695b1d28c6bea83
- id: rust
uses: storytold/craft-common-actions/actions/rust-channel@main
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 }}
# A version of the prepared Nightly form for this commit; the real one comes from the feed's
# identity job. Only nightly.sh's input checks read it.
- 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 "VECTORCRAFT_BUILD_SHA=$sha"
echo "VECTORCRAFT_BUILD_DATE=$date"
echo "VECTORCRAFT_VERSION=$base-nightly.${date//-/}.$GITHUB_RUN_NUMBER.$GITHUB_RUN_ATTEMPT.g${sha:0:12}"
} >>"$GITHUB_ENV"
- name: Build the unsigned Nightly bundle
env:
VECTORCRAFT_BUILD_CHANNEL: nightly-v1
CARGO_TARGET_DIR: ${{ runner.temp }}/nightly-targets
DIST: ${{ runner.temp }}/nightly-dist
CRAFT_FONTS_DIR: ${{ github.workspace }}/craft-fonts
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/vectorcraft-$VECTORCRAFT_VERSION-macos-aarch64-nightly.zip"
# Keeps the verified unsigned zip briefly for keyless signer tests and hand testing. Unsigned only.
- name: Keep the unsigned archive
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: vectorcraft-nightly-macos-aarch64-unsigned
path: ${{ runner.temp }}/nightly-dist/vectorcraft-${{ env.VECTORCRAFT_VERSION }}-macos-aarch64-nightly.zip
if-no-files-found: error
retention-days: 7
compression-level: 0
+42
View File
@@ -0,0 +1,42 @@
name: VectorCraft 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: vectorcraft-nightly-release
cancel-in-progress: false
jobs:
release:
# Actual context guards: official repository, manual dispatch, real release branch.
if: >-
github.repository == 'storytold/vectorcraft' &&
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: VectorCraft unsigned nightly
# Enabled for supervised manual runs by the reviewed manual actor only; no schedule yet.
# A later explicit opt-in may add a cadence (and turn on nightly-dispatch.yml with it).
on:
workflow_dispatch:
permissions:
contents: read
jobs:
unsigned:
# Actual context guards only; no inherited/platform secrets.
if: >-
github.repository == 'storytold/vectorcraft' &&
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: vectorcraft
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"]'
+7
View File
@@ -7,3 +7,10 @@ plan/
.DS_Store
# A craft-fonts checkout for CRAFT_FONTS_DIR (CI and release workflows check it out here)
/craft-fonts
# The Python packaging helpers' bytecode: `nightly-archive.py` imports `nightly_paths`, and the
# producer's clean-tree check runs after a local packaging run would have written it.
__pycache__/
# The shared nightly workflow's scratch checkouts and inputs: the producer requires a clean tree.
/.nightly-tools
/.nightly-input
/craft-i18n
+4
View File
@@ -51,6 +51,10 @@ Generated-in-code art is original and has no file to list. This covers the defau
| `assets/app-icon/hicolor/scalable/apps/ai.storyteller.vectorcraft.svg` | Project owner (ArtCraft team) | Original artwork drawn in ArtCraft for VectorCraft, vectorised and rendered by `packaging/icons.sh` | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | App icon (engraved dragon) |
| `assets/app-icon/vectorcraft-1024.png` | Project owner (ArtCraft team) | Original artwork drawn in ArtCraft for VectorCraft, vectorised and rendered by `packaging/icons.sh` | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | App icon (engraved dragon) |
| `assets/app-icon/vectorcraft-macos-512.png` | Project owner (ArtCraft team) | Original artwork drawn in ArtCraft for VectorCraft, vectorised and rendered by `packaging/icons.sh` | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | App icon (engraved dragon) |
| `assets/app-icon/vectorcraft-nightly-1024.png` | Project owner (ArtCraft team) | Recoloured from the stable app tile by `packaging/nightly-icons.py`, original artwork drawn in ArtCraft for VectorCraft | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | Nightly `.app` master: the full tile with Apple's margin, 1024 px |
| `assets/app-icon/vectorcraft-nightly.icns` | Project owner (ArtCraft team) | Recoloured from the stable app tile by `packaging/nightly-icons.py`, original artwork drawn in ArtCraft for VectorCraft | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | Nightly macOS icon set, 16 to 1024 px |
| `assets/app-icon/vectorcraft-nightly.ico` | Project owner (ArtCraft team) | Recoloured from the stable app tile by `packaging/nightly-icons.py`, original artwork drawn in ArtCraft for VectorCraft | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | Nightly Windows icons, 16 to 256 px |
| `assets/app-icon/vectorcraft-nightly.png` | Project owner (ArtCraft team) | Recoloured from the stable app tile by `packaging/nightly-icons.py`, original artwork drawn in ArtCraft for VectorCraft | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | Nightly feed art and window icon, 1024 px |
| `assets/app-icon/vectorcraft-small.svg` | Project owner (ArtCraft team) | Original artwork drawn in ArtCraft for VectorCraft, vectorised and rendered by `packaging/icons.sh` | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | App icon (engraved dragon) |
| `assets/app-icon/vectorcraft.icns` | Project owner (ArtCraft team) | Original artwork drawn in ArtCraft for VectorCraft, vectorised and rendered by `packaging/icons.sh` | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | App icon (engraved dragon) |
| `assets/app-icon/vectorcraft.ico` | Project owner (ArtCraft team) | Original artwork drawn in ArtCraft for VectorCraft, vectorised and rendered by `packaging/icons.sh` | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | App icon (engraved dragon) |
+1 -1
View File
@@ -45,7 +45,7 @@ winreg = "0.55"
# GPU that shows it: drawing on a GPU without a monitor reset the display driver. Safe wrappers over
# Win32 (MIT); the `user` feature is User32.dll only. Only the wgpu renderer chooses an adapter.
winsafe = { version = "0.0.29", default-features = false, features = ["user"], optional = true }
winsafe = { version = "0.0.29", default-features = false, features = ["user", "shell"], optional = true }
# Waits for Direct3D 12's adapter list before the window starts (src/gpu.rs, #4150). MIT OR
# Apache-2.0, already in the build through eframe.
pollster = "1"
+61 -9
View File
@@ -1,24 +1,67 @@
//! Windows only: embed the app icon and version info (VERSIONINFO) into `vectorcraft.exe`.
//! Windows only: embed the app icon and version info (VERSIONINFO) into `vectorcraft.exe`. Everywhere,
//! fix the build's channel and the version it reports.
//!
//! On every other target this does nothing. A missing resource compiler is a warning, so a
//! cross-compile from macOS or Linux still links, unless `VECTORCRAFT_REQUIRE_WINRES=1` turns it into
//! an error (for release builds).
//! `VECTORCRAFT_BUILD_CHANNEL=nightly-v1` makes a Nightly build and needs an exact feed identity in
//! `VECTORCRAFT_VERSION` (the shared nightly workflow's name) or `VECTORCRAFT_OVERRIDE_VERSION` (what
//! this app's own packaging passes to cargo): `X.Y.Z-nightly.YYYYMMDD.<run>.<attempt>.g<sha12>`. Unset,
//! empty or `stable` means the stable build; anything else is an error.
//!
//! On non-Windows targets the resource half does nothing. A missing resource compiler is a warning, so
//! a cross-compile from macOS or Linux still links, unless `VECTORCRAFT_REQUIRE_WINRES=1` turns it into
//! an error (for release and nightly builds).
#[path = "src/build_channel.rs"]
mod build_channel;
fn main() -> Result<(), String> {
println!("cargo:rerun-if-changed=build.rs");
println!("cargo:rerun-if-changed=../../assets/app-icon/vectorcraft.ico");
println!("cargo:rerun-if-env-changed=VECTORCRAFT_REQUIRE_WINRES");
println!("cargo:rustc-check-cfg=cfg(vectorcraft_nightly_v1)");
println!("cargo:rerun-if-env-changed=VECTORCRAFT_BUILD_CHANNEL");
println!("cargo:rerun-if-env-changed=VECTORCRAFT_VERSION");
println!("cargo:rerun-if-env-changed=VECTORCRAFT_OVERRIDE_VERSION");
let nightly = match std::env::var("VECTORCRAFT_BUILD_CHANNEL").as_deref() {
Ok("nightly-v1") => {
println!("cargo:rustc-cfg=vectorcraft_nightly_v1");
true
}
// An empty value (an unset CI input) means the default stable build.
Ok("stable" | "") | Err(std::env::VarError::NotPresent) => false,
Ok(other) => return Err(format!("unsupported VECTORCRAFT_BUILD_CHANNEL {other:?} (expected stable or nightly-v1)")),
Err(std::env::VarError::NotUnicode(_)) => return Err("VECTORCRAFT_BUILD_CHANNEL is not valid Unicode".to_string()),
};
// The stable build reports its package version, as it always has.
let built_version = if nightly {
match feed_identity() {
Some(version) if build_channel::is_nightly_version(&version) => version,
_ => {
return Err(
"nightly-v1 requires an explicit VECTORCRAFT_VERSION feed identity (X.Y.Z-nightly.YYYYMMDD.<run>.<attempt>.g<sha12>)".to_string()
);
}
}
} else {
std::env::var("CARGO_PKG_VERSION").unwrap_or_default()
};
println!("cargo:rustc-env=VECTORCRAFT_BUILT_VERSION={built_version}");
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("windows") {
return Ok(());
}
println!("cargo:rerun-if-changed=../../assets/app-icon/vectorcraft.ico");
println!("cargo:rerun-if-changed=../../assets/app-icon/vectorcraft-nightly.ico");
println!("cargo:rerun-if-env-changed=VECTORCRAFT_REQUIRE_WINRES");
let mut res = winresource::WindowsResource::new();
res.set_icon("../../assets/app-icon/vectorcraft.ico")
.set("ProductName", "VectorCraft")
.set("FileDescription", "VectorCraft vector illustration editor")
res.set_icon(build_channel::windows_icon_path(nightly))
.set("ProductName", if nightly { "VectorCraft Nightly" } else { "VectorCraft" })
.set("FileDescription", if nightly { "VectorCraft Nightly vector illustration editor" } else { "VectorCraft vector illustration editor" })
.set("CompanyName", "Learning Machines LLC")
.set("LegalCopyright", "Copyright (c) the VectorCraft authors. MIT OR Apache-2.0.")
.set("OriginalFilename", "vectorcraft.exe")
.set("InternalName", "vectorcraft");
if nightly {
// The Launcher verifies the PE ProductVersion against the exact feed identity, not FileVersion.
res.set("ProductVersion", &built_version);
}
if let Err(e) = res.compile() {
if std::env::var_os("VECTORCRAFT_REQUIRE_WINRES").is_some() {
return Err(format!("embedding Windows resources failed: {e}"));
@@ -27,3 +70,12 @@ fn main() -> Result<(), String> {
}
Ok(())
}
/// The feed identity from `VECTORCRAFT_VERSION`, else `VECTORCRAFT_OVERRIDE_VERSION`: the shared
/// nightly workflow sets the first, this app's own packaging scripts the second.
fn feed_identity() -> Option<String> {
["VECTORCRAFT_VERSION", "VECTORCRAFT_OVERRIDE_VERSION"]
.into_iter()
.filter_map(|name| std::env::var(name).ok().filter(|value| !value.is_empty()))
.next()
}
+5
View File
@@ -1,5 +1,6 @@
#[cfg(all(target_os = "macos", feature = "accessibility", feature = "wgpu"))]
use super::gpu;
use super::nightly_session;
use super::prefs::{flush, save_tick};
#[cfg(not(target_os = "macos"))]
use super::single_instance;
@@ -95,6 +96,10 @@ impl eframe::App for App {
// A ready update installs once the process has exited. The macOS exit below skips
// dropping the app, so the helper is started here.
self.app.start_pending_update();
// Every quit reaches this hook, including a macOS Cmd+Q, which ends the process inside
// AppKit's terminate before `run_native` returns: the nightly session record is finished
// here, and the return path after the event loop is then a no-op.
nightly_session::finish_once();
// Dropping the app can wait for the clipboard handles to let go: the windows leave the
// screen first (`quit_windows`).
#[cfg(not(any(target_os = "macos", windows)))]
+58
View File
@@ -0,0 +1,58 @@
//! The build-time nightly identity shared by the build script and its pure regression tests.
/// A nightly feed identity: `X.Y.Z-nightly.YYYYMMDD.<run>.<attempt>.g<sha12>`, exactly.
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/vectorcraft-nightly.ico" } else { "../../assets/app-icon/vectorcraft.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/vectorcraft.ico");
assert_eq!(windows_icon_path(true), "../../assets/app-icon/vectorcraft-nightly.ico");
}
#[test]
fn explicit_feed_identity_is_required_for_a_nightly_build() {
assert!(is_nightly_version("0.24.1-nightly.20261124.17.1.gabcdef012345"));
for invalid in [
"",
"0.24.1",
"0.24.1-nightly",
"0.24.1-nightly.20261124",
"0.24.1-nightly.20261124.17.1.gABCDEF012345",
"0.24.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.24.1-nightly.20261124.1.1.gabcdef012345",
"0.24.1-nightly.20261124.1.1.gabcdef012345/other",
"0.24.1-nightly.20261124.1.1.gabcdef012345\ncargo:rustc-cfg=other",
] {
assert!(!is_nightly_version(invalid));
}
}
}
+76
View File
@@ -0,0 +1,76 @@
//! Build-time channel is distinct from a launch selector. A runtime environment cannot promote a
//! stable build, and a nightly build refuses to start without its profile.
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!(vectorcraft_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 VectorCraft Nightly from ArtCraft Launcher".to_string()),
(BuildFlavor::Stable, true) => Err("This is a stable VectorCraft build; nightly-v1 requires the nightly build".to_string()),
_ => Ok(()),
}
}
pub fn needs_native_error(flavor: BuildFlavor, desktop_session: bool) -> bool {
desktop_session && flavor == BuildFlavor::NightlyV1
}
/// `--version` and `-V` on their own, before any other argument is read.
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_string(),
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());
assert!(require_profile(BuildFlavor::NightlyV1, &Profile::Stable).is_err());
}
#[test]
fn nightly_version_query_is_unambiguous_and_never_reinterprets_file_arguments() {
assert_eq!(version(BuildFlavor::Stable, "0.24.1"), "0.24.1");
assert_eq!(version(BuildFlavor::NightlyV1, "0.24.1"), "0.24.1 (nightly-v1)");
assert!(version_query(&["--version".into()]));
assert!(version_query(&["-V".into()]));
assert!(!version_query(&["--".into(), "--version".into()]));
assert!(!version_query(&[]));
}
}
+1 -1
View File
@@ -683,7 +683,7 @@ impl Startup {
return LeftOut::default();
}
};
let (record, crash) = StartRecord::begin(previous, env!("CARGO_PKG_VERSION"), preference_name(preference));
let (record, crash) = StartRecord::begin(previous, vectorcraft_ui_egui::os_window::version(), preference_name(preference));
let left_out = record.left_out(crash.clone(), explicit);
match &crash {
Some(Crash::Adapter { key, name }) => {
+1 -1
View File
@@ -137,7 +137,7 @@ impl Facts {
let or_unknown = |v: &Option<String>| v.clone().unwrap_or_else(|| "unknown".to_string());
format!(
"VectorCraft {} on {} {}\nWindow system: {}; desktop: {}; session type: {}; Flatpak: {}\nGraphics: {}; {}\n",
env!("CARGO_PKG_VERSION"),
vectorcraft_ui_egui::os_window::version(),
std::env::consts::OS,
std::env::consts::ARCH,
self.window_system,
+272
View File
@@ -0,0 +1,272 @@
//! Launcher-owned nightly-v1 bootstrap. Selected before logging, updates, fonts or saved state.
//! Stable launches retain their original arguments and directory policy.
//!
//! The protocol is `vectorcraft --launch-profile nightly-v1 --profile-root <abs> -- [files…]`: the
//! selector and the root are separate tokens, exactly once each, and everything after `--` is a file
//! even when it looks like one of them. The Launcher's version check
//! (`… --version`) is answered before the root is validated or touched.
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".to_string())
}
/// Recognize only the agreed literal selector/root pair before `--`. 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".to_string());
}
let value = iter.next().filter(|v| !v.is_empty()).ok_or_else(|| "the profile selector/root needs a value".to_string())?;
if value.to_string_lossy().starts_with("--") {
return Err("the profile selector/root needs a value".to_string());
}
*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".to_string());
} 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".to_string());
}
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".to_string());
}
Ok(Launch { profile: Profile::NightlyV1(root), args: std::iter::once(OsString::from("--")).chain(files).collect() })
}
(Some(_), Some(_)) => Err("unsupported launch profile (expected nightly-v1)".to_string()),
_ => Err("--launch-profile and --profile-root must be supplied together".to_string()),
}
}
/// 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)
}
/// Validation finishes before the caller's first startup effect. Stable never calls the nightly root
/// validator, so its portable and 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::prefs_dir::profile::ensure_writable)
}
/// The arguments a child of this process starts with: a nightly launch hands its profile on, so the
/// child opens the same private profile instead of being refused ("Open VectorCraft Nightly…"), and
/// `--` keeps a file whose name starts with '-' a file. Stable's child arguments are unchanged.
pub fn child_args(files: &[String]) -> Vec<OsString> {
child_args_for(current(), files)
}
fn child_args_for(profile: &Profile, files: &[String]) -> Vec<OsString> {
let mut args: Vec<OsString> = match profile {
Profile::Stable => Vec::new(),
Profile::NightlyV1(root) => {
vec![OsString::from("--launch-profile"), OsString::from(VERSION), OsString::from("--profile-root"), root.clone().into_os_string()]
}
};
args.push(OsString::from("--"));
args.extend(files.iter().map(OsString::from));
args
}
#[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\vectorcraft" } else { "/nightly-data/profiles/vectorcraft" }
}
fn nightly() -> Vec<OsString> {
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--"])
}
#[test]
fn stable_arguments_and_directory_policy_are_unchanged() {
for argv in [args(&[]), args(&["--new-instance", "a.svg"]), args(&["--", "--launch-profile", "file.svg"])] {
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", "art with spaces.svg"]));
let launch = parse(argv).unwrap();
assert_eq!(launch.profile, Profile::NightlyV1(PathBuf::from(absolute())));
assert_eq!(launch.args, args(&["--", "--profile-root", "art with spaces.svg"]));
}
#[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", "../escape", "--"]),
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.clone()).is_err(), "{argv:?}");
}
}
#[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".to_string())).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());
}
#[test]
fn a_joined_flag_form_is_refused() {
for joined in [format!("--launch-profile={VERSION}"), format!("--profile-root={}", absolute())] {
let argv = vec![OsString::from(joined), OsString::from("--")];
assert!(parse(argv).is_err());
}
}
#[test]
fn a_stable_child_gets_the_file_delimiter_only() {
let child = child_args_for(&Profile::Stable, &["a file.svg".to_string(), "--looks-like-a-flag".to_string()]);
assert_eq!(child, args(&["--", "a file.svg", "--looks-like-a-flag"]));
}
#[test]
fn a_nightly_child_inherits_the_selected_profile() {
let root = PathBuf::from(absolute());
let child = child_args_for(&Profile::NightlyV1(root.clone()), &["art.svg".to_string()]);
let expected = vec![
OsString::from("--launch-profile"),
OsString::from(VERSION),
OsString::from("--profile-root"),
root.into_os_string(),
OsString::from("--"),
OsString::from("art.svg"),
];
assert_eq!(child, expected);
// The child's own parse finds the same profile and the file list.
let launch = parse(child).unwrap();
assert!(launch.profile.is_nightly());
assert_eq!(launch.args, args(&["--", "art.svg"]));
}
}
+234 -40
View File
@@ -28,6 +28,9 @@
#![cfg_attr(all(target_os = "windows", not(debug_assertions)), windows_subsystem = "windows")]
mod automation_args;
#[cfg(test)]
mod build_channel;
mod build_flavor;
mod clipboard;
#[cfg(feature = "wgpu")]
mod compositor_gpu;
@@ -36,6 +39,7 @@ mod display_profile;
#[cfg(feature = "wgpu")]
mod gpu;
mod hang_watch;
mod launch_profile;
#[cfg(target_os = "linux")]
mod linux_stylus;
mod logging;
@@ -46,11 +50,14 @@ mod mac_fonts;
mod mac_tablet;
#[cfg(target_os = "macos")]
mod mac_window;
mod nightly_session;
#[cfg(target_os = "macos")]
mod open_documents;
mod prefs_dir;
mod presentation;
mod printing;
mod process_identity;
mod profile_root;
#[cfg(not(any(target_os = "macos", windows)))]
mod quit_windows;
#[cfg(not(target_os = "macos"))]
@@ -101,9 +108,6 @@ use prefs::{load_prefs, log_dir, open_store, prefs_enabled};
const DEFAULT_SIZE: [f32; 2] = [1440.0, 900.0];
const MIN_SIZE: [f32; 2] = [800.0, 500.0];
/// The app id every OS window carries; it matches `packaging/linux/ai.storyteller.vectorcraft.desktop`.
const WINDOW_APP_ID: &str = "ai.storyteller.vectorcraft";
/// The window, Dock, taskbar and app-switcher icon (`assets/app-icon/`, see its README). macOS gets
/// the version with Apple's transparent margin; elsewhere the full-bleed tile. The app ID matches
/// `packaging/linux/ai.storyteller.vectorcraft.desktop` so Wayland docks find the launcher icon.
@@ -137,7 +141,7 @@ fn adapter_summary(info: &eframe::wgpu::AdapterInfo) -> String {
fn native_options(custom_titlebar: bool) -> eframe::NativeOptions {
eframe::NativeOptions {
viewport: egui::ViewportBuilder::default()
.with_title("VectorCraft")
.with_title(vectorcraft_ui_egui::os_window::name())
.with_inner_size(DEFAULT_SIZE)
.with_min_inner_size(MIN_SIZE)
.with_drag_and_drop(true)
@@ -146,11 +150,35 @@ fn native_options(custom_titlebar: bool) -> eframe::NativeOptions {
.with_titlebar_shown(false)
.with_title_shown(false)
.with_icon(app_icon())
.with_app_id(WINDOW_APP_ID),
.with_app_id(vectorcraft_ui_egui::os_window::app_id()),
// A nightly keeps its own window state in its private profile; a stable build lets eframe
// keep it where it always did.
persistence_path: nightly_window_state(),
..Default::default()
}
}
/// Where eframe keeps its own saved state, if its persistence feature is ever on: a folder of its
/// own inside the nightly profile ([`nightly_root`]), never the file craft's window placement is in
/// (`<profile>/window.json`, which eframe would treat as a folder) and never the stable app's.
fn nightly_window_state() -> Option<std::path::PathBuf> {
nightly_root().map(|root| root.join("eframe"))
}
/// The saved window placement (the framework's `window.json`): beside the preferences, as it always
/// was, or inside a nightly's private profile so the two channels never move each other's windows.
fn placement_store() -> Store {
match nightly_root() {
Some(root) => Store::at(&root.join(craft::window::restore::FILE_NAME)),
None => Store::open("vectorcraft"),
}
}
/// This launch's private Nightly profile, when it is one.
fn nightly_root() -> Option<&'static std::path::Path> {
launch_profile::current().root()
}
struct App {
app: VectorcraftApp,
/// The preferences, written through [`prefs::save_tick`] and on exit.
@@ -277,7 +305,14 @@ fn read_command_line(
"--new-instance" => new_instance = true,
"--safe-mode" => safe_mode = true,
"--version" => {
println!("vectorcraft {}", env!("CARGO_PKG_VERSION"));
// A nightly says what it is, like the early answer; a stable build's line is unchanged.
let line = match build_flavor::COMPILED {
build_flavor::BuildFlavor::Stable => format!("vectorcraft {}\n", vectorcraft_ui_egui::os_window::version()),
build_flavor::BuildFlavor::NightlyV1 => {
format!("VectorCraft {}\n", build_flavor::version(build_flavor::COMPILED, vectorcraft_ui_egui::os_window::version()))
}
};
let _ = std::io::Write::write_all(&mut std::io::stdout(), line.as_bytes());
return Err(std::process::ExitCode::SUCCESS);
}
// Before anything starts, like `--version`: from a terminal or an agent's shell the app
@@ -332,12 +367,158 @@ fn opens_through_xwayland(pref: Option<&str>) -> bool {
true
}
fn main() -> std::process::ExitCode {
// Windows: the update helper is a copy of this program started with `--finish-update`.
#[cfg(windows)]
if let Some(result) = craft::update::self_update::finish(&vectorcraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::<Vec<_>>()) {
/// The nightly channel this build is, as a string for the log.
fn channel_name() -> &'static str {
match build_flavor::COMPILED {
build_flavor::BuildFlavor::Stable => "stable",
build_flavor::BuildFlavor::NightlyV1 => launch_profile::VERSION,
}
}
/// Says why a nightly launch was refused, then exits 2. A window could not have shown it yet: this
/// app has no message box of its own before eframe starts (its dialogs are egui windows), so the
/// text goes to standard error, which a Launcher launch records. The desktop-session test still
/// decides whether a daily user would have seen it, for the message's wording.
fn report_launch_profile_error(error: &str) {
eprintln!("VectorCraft launch profile: {error}");
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) {
eprintln!("VectorCraft Nightly: open it from ArtCraft Launcher, which starts it in its own profile");
}
}
/// Selects the immutable launch profile before any startup service or side effect, and returns the
/// arguments the rest of `main` reads. `None` means the process ends here (`--version` answered).
fn prepare_launch() -> Option<Vec<std::ffi::OsString>> {
// The trusted Launcher protocol is decided before the logger, updates, fonts or any saved state.
let argv: Vec<_> = std::env::args_os().skip(1).collect();
// A nightly answers its version before root validation, process identity, IPC or any window:
// plain `--version`/`-V`, or the Launcher's `--launch-profile nightly-v1 --profile-root <dir>
// --version`. A stable build leaves the answer to `read_command_line`, exactly as before.
if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && (build_flavor::version_query(&argv) || launch_profile::version_query(&argv))
{
use std::io::Write as _;
let line = format!("VectorCraft {}\n", build_flavor::version(build_flavor::COMPILED, env!("VECTORCRAFT_BUILT_VERSION")));
let _ = std::io::stdout().write_all(line.as_bytes());
return None;
}
let early = launch_profile::parse(argv)
.and_then(|launch| {
build_flavor::require_profile(build_flavor::COMPILED, &launch.profile)?;
Ok(launch)
})
.and_then(|launch| {
launch_profile::prepare(launch, |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 nightly = early.profile.is_nightly();
let identity =
if nightly { vectorcraft_ui_egui::os_window::LaunchIdentity::NightlyV1 } else { vectorcraft_ui_egui::os_window::LaunchIdentity::Stable };
let install = launch_profile::install(early.profile).and_then(|()| {
// Every data path follows the selected profile from here on: settings, logs, recovery, the
// user's libraries, plug-ins, caches and the single-instance record.
if let Some(root) = launch_profile::current().root() {
prefs_dir::profile::install_data_root(root.to_path_buf())?;
}
vectorcraft_ui_egui::os_window::select_identity(identity)
});
if let Err(error) = install {
report_launch_profile_error(&error);
std::process::exit(2);
}
if let Err(error) = vectorcraft_ui_egui::os_window::set_version(env!("VECTORCRAFT_BUILT_VERSION")) {
report_launch_profile_error(&error);
std::process::exit(2);
}
// A nightly's taskbar identity, before the first window: otherwise Windows groups it with the
// stable app and the Launcher's own entry.
if let Err(error) =
process_identity::initialize(nightly, vectorcraft_ui_egui::os_window::id_for(vectorcraft_ui_egui::os_window::LaunchIdentity::NightlyV1))
{
report_launch_profile_error(&error.to_string());
// The window's identity, not the profile, failed: main's own failure status (1).
std::process::exit(1);
}
Some(early.args)
}
/// The arguments the rest of `main` reads: a nightly's profile tokens were consumed by
/// `prepare_launch`, so what is left is `--` and the files to open. A stable launch reads its
/// arguments exactly as it always did.
fn launch_arguments(nightly: bool, arguments: &[std::ffi::OsString]) -> Vec<String> {
if nightly { arguments.iter().map(|a| a.to_string_lossy().into_owned()).collect() } else { std::env::args().skip(1).collect() }
}
/// The control channel's port, and the token's notice with the token itself.
type ControlChannel = (Option<u16>, Option<(String, String)>);
/// Port and token of the control channel, or the message to print. A nightly is started by the
/// Launcher, never by an agent, so the channel and its inherited environment stay off: no token
/// file is read and nothing listens.
fn control_channel(control: &automation_args::ControlArg, nightly: bool) -> Result<ControlChannel, String> {
if nightly {
if control.options().port.is_some() || std::env::var_os("VECTORCRAFT_CONTROL_PORT").is_some() {
eprintln!("vectorcraft: the control channel is off in a nightly build");
}
return Ok((None, None));
}
let options = ControlOptions::resolve(control.options(), &EnvNames::for_app("VECTORCRAFT")).map_err(|e| e.to_string())?;
let port = options.port;
// Read before the window opens: a token file that can't be read keeps the app from starting
// rather than leaving the channel open without one.
let token = port.map(|_| options.server_token()).transpose().map_err(|e| e.to_string())?;
Ok((port, token.map(|token| (options.token_notice(&token), token))))
}
/// A nightly's own session record: whether the previous session did not finish normally, to be
/// reported once the window is up. This session is cleared only on a controlled return (`on_exit`,
/// or the code after the event loop). Stable keeps no record.
fn previous_nightly_session_was_unclean(nightly: bool) -> bool {
if !nightly {
return false;
}
match nightly_session::begin(nightly_root(), vectorcraft_ui_egui::os_window::version(), None) {
Ok(unclean) => unclean,
Err(e) => {
log::warn!("Nightly session health is unavailable: {e}");
false
}
}
}
/// The first log lines: the version and channel, then a nightly's profile root.
fn log_startup(nightly: bool) {
log::info!("VectorCraft {} ({})", vectorcraft_ui_egui::os_window::version(), channel_name());
if nightly {
log::info!("nightly profile: {}", nightly_root().map(|root| root.display().to_string()).unwrap_or_default());
}
}
/// Windows: the update helper is a copy of this program started with `--finish-update`. Nightly is
/// updated by the Launcher, so it never starts one (`build_flavor` keeps its updater off).
#[cfg(windows)]
fn finish_pending_update(nightly: bool) {
if !nightly
&& let Some(result) = craft::update::self_update::finish(&vectorcraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::<Vec<_>>())
{
std::process::exit(i32::from(result.is_err()));
}
}
fn main() -> std::process::ExitCode {
// The launch profile first: a nightly build without one is refused here, before the update
// helper, the logger, fonts or any saved state, and `--version` is answered here too.
let Some(arguments) = prepare_launch() else { return std::process::ExitCode::SUCCESS };
let nightly = launch_profile::current().is_nightly();
#[cfg(windows)]
finish_pending_update(nightly);
// Before any thread starts: the pointer must find a cursor theme on Wayland (#2450).
#[cfg(target_os = "linux")]
cursor_theme::apply();
@@ -348,32 +529,21 @@ fn main() -> std::process::ExitCode {
let mut roots_args =
automation_args::AutomationArgs::new(root_env("VECTORCRAFT_AUTOMATION_READ_ROOT"), root_env("VECTORCRAFT_AUTOMATION_WRITE_ROOT"));
let mut presentation = presentation::Overrides::default();
let given = launch_arguments(nightly, &arguments);
let CommandLine { files: command_line_files, in_window_menus, new_instance, safe_mode: safe_mode_flag } =
match read_command_line(std::env::args().skip(1), &mut control, &mut roots_args, &mut presentation) {
match read_command_line(given.into_iter(), &mut control, &mut roots_args, &mut presentation) {
Ok(command_line) => command_line,
Err(code) => return code,
};
let automation_args::AutomationArgs { read_roots, write_roots, .. } = roots_args;
// After the arguments: the flags and `--version` win over a bad environment value.
let control_options = match ControlOptions::resolve(control.options(), &EnvNames::for_app("VECTORCRAFT")) {
Ok(options) => options,
Err(e) => {
eprintln!("vectorcraft: {e}");
return std::process::ExitCode::FAILURE;
}
};
let control_port = control_options.port;
// Read before the window opens: a token file that can't be read keeps the app from starting
// rather than leaving the channel open without one.
let control_token = match control_port.map(|_| control_options.server_token()).transpose() {
Ok(token) => token.map(|token| (control_options.token_notice(&token), token)),
Err(e) => {
eprintln!("vectorcraft: {e}");
return std::process::ExitCode::FAILURE;
}
};
let (control_port, control_token) = control_channel(&control, nightly).unwrap_or_else(|message| {
eprintln!("vectorcraft: {message}");
std::process::exit(1)
});
// Before desktop services, so every start-up warning is recorded (`logging`).
let logger = logging::install();
log_startup(nightly);
// Files opened from the file manager while VectorCraft runs open in its window (#4892). Before
// the log file is attached: a launch that hands its files over leaves the running app's log be.
#[cfg(not(target_os = "macos"))]
@@ -401,13 +571,14 @@ fn main() -> std::process::ExitCode {
if let Some(logger) = logger {
match log_dir().filter(|_| prefs_enabled()) {
Some(dir) => match logger.attach_dir(&dir) {
Ok(path) => log::info!("VectorCraft {}, log file {}", env!("CARGO_PKG_VERSION"), path.display()),
Ok(path) => log::info!("VectorCraft {}, log file {}", vectorcraft_ui_egui::os_window::version(), path.display()),
// Standard error only by now (`attach_dir` gave up on the file); unlike `eprintln!`, never panics.
Err(e) => log::warn!("no log file: {e}"),
},
None => logger.no_file(),
}
}
let previous_nightly_unclean = previous_nightly_session_was_unclean(nightly);
// The report a session left when it was closed while it did not answer (`hang_watch`).
let previous_hang = log_dir().filter(|_| prefs_enabled()).and_then(|dir| hang_watch::take_previous(&dir));
if let Some(report) = &previous_hang {
@@ -591,11 +762,11 @@ fn main() -> std::process::ExitCode {
let run = |options: eframe::NativeOptions, app_creator: eframe::AppCreator<'_>| {
#[cfg(target_os = "linux")]
{
linux_stylus::run_native("VectorCraft", options, app_creator)
linux_stylus::run_native(vectorcraft_ui_egui::os_window::name(), options, app_creator)
}
#[cfg(not(target_os = "linux"))]
{
eframe::run_native("VectorCraft", options, app_creator)
eframe::run_native(vectorcraft_ui_egui::os_window::name(), options, app_creator)
}
};
let outcome = vectorcraft_engine::guard::catch_panic(|| {
@@ -605,8 +776,8 @@ fn main() -> std::process::ExitCode {
let ctx = &cc.egui_ctx;
let winit_window = cc.winit_window().cloned();
let spec = InstallSpec::new(shell_info, Arc::new(SystemWindows))
.app_id(WINDOW_APP_ID)
.placement(Arc::new(Mutex::new(Store::open("vectorcraft"))))
.app_id(vectorcraft_ui_egui::os_window::app_id())
.placement(Arc::new(Mutex::new(placement_store())))
.frame(decision);
let spec = match start_pen(&winit_window) {
Some(pen) => spec.pen(pen),
@@ -621,11 +792,15 @@ fn main() -> std::process::ExitCode {
};
let (files, file_panels) = file_service(wake, folders);
let files = Arc::new(files);
craft::host::Host::builder(AppInfo { id: "vectorcraft", name: "VectorCraft", version: env!("CARGO_PKG_VERSION") })
.i18n(vectorcraft_ui_egui::i18n::shared())
.settings(Arc::new(settings.clone()))
.files(files.clone())
.install(ctx);
craft::host::Host::builder(AppInfo {
id: vectorcraft_ui_egui::os_window::SETTINGS_APP_ID,
name: vectorcraft_ui_egui::os_window::name(),
version: vectorcraft_ui_egui::os_window::version(),
})
.i18n(vectorcraft_ui_egui::i18n::shared())
.settings(Arc::new(settings.clone()))
.files(files.clone())
.install(ctx);
let mut session = Session::new();
// The profiles loaded before come back before the preferences name any of them.
prefs_dir::attach_profile_store(&mut session);
@@ -646,7 +821,9 @@ fn main() -> std::process::ExitCode {
prefs_dir::attach_script_data(&mut session);
let mut app = VectorcraftApp::new(session, services(winit_window.clone()));
app.adopt_context(&cc.egui_ctx);
app.set_startup_update_check(true);
// A nightly is updated by the Launcher: it never checks for a stable release, which
// would install this program's own updater over the nightly build.
app.set_startup_update_check(!nightly);
load_prefs(&mut app, &settings);
safe_mode::after_start(&mut app, stopped);
// The saved PDF presets live in their own folder (also read by vectorcraft-cli),
@@ -741,6 +918,17 @@ fn main() -> std::process::ExitCode {
if previous_hang.is_some() && app.ui.status.is_empty() {
vectorcraft_ui_egui::troubleshooting::last_session_stopped(&mut app);
}
// The previous nightly session did not finish normally: say so once, in the window
// that is now up, and only then let a clean exit clear the record.
if previous_nightly_unclean {
// A graphics, plug-in or hang message may be up already: keep it, as above.
if app.ui.status.is_empty() {
app.status(
"The previous VectorCraft Nightly session did not finish normally. Nothing has been sent anywhere; Help › About has this build's version for a bug report",
);
}
nightly_session::mark_notice_shown();
}
let mut control_server = None;
if let (Some(port), Some((notice, token))) = (control_port, control_token) {
match server::listen(port, token, craft::ui::runtime::windows::WindowHost::of(&cc.egui_ctx)) {
@@ -803,7 +991,13 @@ fn main() -> std::process::ExitCode {
)
});
// The window is gone: later launches start their own app, including the one a graphics
// failure starts again below.
// failure starts again below. A nightly's session record is finished here, by the controlled
// return, before a successor can take the profile; on macOS the window's own `on_exit` already
// did it (a Dock quit ends the process inside AppKit), so this is then a no-op. A run that
// reports a startup error has still returned in a controlled way (that error is logged and
// exits FAILURE below), so only a caught panic keeps the record for the next launch to report;
// it then also frees the lease for the successor this run may still start.
nightly_session::finish_after(outcome.is_ok());
#[cfg(not(target_os = "macos"))]
single_instance::resign();
// The process ends normally from here: this launch didn't stop while a plug-in was loading.
+297
View File
@@ -0,0 +1,297 @@
//! App-private Nightly session health, not telemetry and not 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::{Mutex, PoisonError};
const RECORD: &str = "nightly-session.json";
const LEASE: &str = "nightly-session.lock";
const MAX_METADATA_BYTES: usize = 256;
static SESSION: Mutex<Option<Session>> = Mutex::new(None);
/// Set once a window has posted the interruption notice; until then the record must survive.
static NOTICE_SHOWN: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
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),
}
}
/// Replace `path` with `bytes` without ever following a link at the destination: the temporary file
/// is created fresh in the same folder and renamed over the name, and a rename replaces the link
/// itself, never its target. A destination that is not a regular file is refused.
fn atomic_write_no_follow(path: &Path, bytes: &[u8]) -> io::Result<()> {
// A destination that is a folder or a link is refused before anything is written.
regular_or_missing(path)?;
let dir = path.parent().ok_or_else(|| io::Error::other("Nightly session state has no folder"))?;
std::fs::create_dir_all(dir)?;
let name = path.file_name().map(|name| name.to_string_lossy().into_owned()).unwrap_or_default();
let temporary = dir.join(format!(".{name}.{}.tmp", std::process::id()));
let _ = std::fs::remove_file(&temporary);
let mut options = OpenOptions::new();
options.write(true).create_new(true);
#[cfg(unix)]
std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
let written = options.open(&temporary).and_then(|mut file| {
use std::io::Write as _;
file.write_all(bytes)?;
file.sync_all()?;
std::fs::rename(&temporary, path)
});
if written.is_err() {
// Best effort: the temporary file is all there is to clean up.
let _ = std::fs::remove_file(&temporary);
}
if written.is_ok()
&& let Ok(handle) = File::open(dir)
{
// The rename is durable once its folder is.
let _ = handle.sync_all();
}
written
}
impl Session {
/// This launch's record: `None` for a stable build or when another window of the same profile
/// owns it. The 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()),
}))?;
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, or the hand-off to a second window), 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, including a handled startup error. Clear before a successor
/// can take the profile. An unwind, abort, forced exit or killed process never calls this.
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)
}
}
/// Starts this launch's record, keeping it until [`finish_once`]. A profile another window already
/// owns gets no record (`Ok(false)` and no notice); a failure to record is reported, never fatal.
pub fn begin(root: Option<&Path>, version: &str, commit: Option<&str>) -> Result<bool, String> {
let session = Session::begin(root, version, commit).map_err(|e| e.to_string())?;
let previous_unclean = session.as_ref().is_some_and(Session::previous_unclean);
*SESSION.lock().unwrap_or_else(PoisonError::into_inner) = session;
Ok(previous_unclean)
}
/// A window showed the interruption notice: a controlled return now clears the record.
pub fn mark_notice_shown() {
NOTICE_SHOWN.store(true, std::sync::atomic::Ordering::Relaxed);
}
/// The controlled return, by whichever path comes first (the window's `on_exit`, which every quit
/// reaches, or the code after the event loop). Later calls do nothing.
pub fn finish_once() {
let shown = NOTICE_SHOWN.load(std::sync::atomic::Ordering::Relaxed);
let watch = SESSION.lock().unwrap_or_else(PoisonError::into_inner).take();
if let Some(watch) = watch
&& let Err(error) = watch.finish(shown)
{
log::warn!("Nightly session state was left intact: {error}");
}
}
/// The end of a launch: a controlled return clears the record ([`finish_once`]); an abnormal one
/// (a caught panic) keeps it for the next launch to report and only frees the lease, so the
/// successor a graphics restart starts can take the profile.
pub fn finish_after(clean: bool) {
if clean { finish_once() } else { release() }
}
/// An abnormal end: the record stays, the lease is dropped. Later calls do nothing.
fn release() {
drop(SESSION.lock().unwrap_or_else(PoisonError::into_inner).take());
}
#[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!("vectorcraft-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() == std::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 stable_has_no_session_side_effects() {
let fixture = Fixture::new();
assert!(Session::begin(None, "0.24.1", None).unwrap().is_none());
assert_eq!(std::fs::read_dir(&fixture.0).unwrap().count(), 0);
}
#[test]
fn a_busy_secondary_reports_nothing_and_keeps_the_owner_record() {
let fixture = Fixture::new();
let first = Session::begin(Some(&fixture.0), "nightly", Some("owned-commit")).unwrap().unwrap();
let record = 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(), record, "a busy secondary must not replace the owner's 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());
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 or abnormal 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());
// The window failed before the app callback: no notice was shown.
let failed = Session::begin(Some(&fixture.0), "failed", None).unwrap().unwrap();
assert!(failed.previous_unclean());
failed.finish(false).unwrap();
let retry = Session::begin(Some(&fixture.0), "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");
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 an_abnormal_end_keeps_the_record_but_frees_the_lease() {
let fixture = Fixture::new();
assert!(!begin(Some(&fixture.0), "nightly", Some("panicked")).unwrap());
finish_after(false);
// A second end is a no-op, and the record stays for the next launch to report.
finish_after(false);
assert!(fixture.0.join(RECORD).exists(), "a caught panic leaves its record");
let successor = Session::begin(Some(&fixture.0), "successor", None).unwrap().unwrap();
assert!(successor.previous_unclean(), "the successor reports the interruption");
successor.finish(true).unwrap();
assert!(!fixture.0.join(RECORD).exists());
// A controlled return still clears the record it recorded.
assert!(!begin(Some(&fixture.0), "clean", None).unwrap());
finish_after(true);
assert!(!fixture.0.join(RECORD).exists(), "a controlled return clears its record");
}
#[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);
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();
}
#[cfg(unix)]
#[test]
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(), "{name}");
assert_eq!(std::fs::read(&external).unwrap(), b"stable bytes");
std::fs::remove_file(alias).unwrap();
}
}
}
+82
View File
@@ -0,0 +1,82 @@
//! Set the immutable nightly Windows identity (the taskbar group and jump-list id) before any native
//! window or COM service. Stable deliberately leaves its implicit shortcut identity unchanged, so the
//! MSI's shortcuts keep matching it.
use std::sync::OnceLock;
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum IdentityError {
Configuration(String),
}
impl std::fmt::Display for IdentityError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Configuration(message) => f.write_str(message),
}
}
}
impl std::error::Error for IdentityError {}
pub fn initialize(nightly: bool, app_id: &str) -> Result<(), IdentityError> {
// winsafe arrives with the wgpu renderer, which every desktop package builds with.
configure(nightly && cfg!(windows) && cfg!(feature = "wgpu"), app_id, |id| {
static RESULT: OnceLock<Result<(), String>> = OnceLock::new();
RESULT
.get_or_init(|| {
#[cfg(all(windows, feature = "wgpu"))]
{
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".to_string());
}
Ok(())
}
#[cfg(not(all(windows, feature = "wgpu")))]
{
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".to_string())).map(|()| started.set(true));
assert_eq!(result.unwrap_err(), "native identity refused");
assert!(!started.get());
}
}
+85 -23
View File
@@ -1,6 +1,9 @@
//! Native profile paths. Isolated profiles never migrate preferences from a user's old profile.
//!
//! In order:
//! 0. The profile root a nightly launch selected ([`install_data_root`]): the Launcher's private
//! folder, which every one of the app's settings, logs, recovery copies, plug-ins, caches and
//! single-instance records then follows, with no legacy migration.
//! 1. `VECTORCRAFT_CONFIG_DIR`, when set (tests, agents, custom setups).
//! 2. **Portable mode** (#1366), as in PhotoCraft: a marker file ([`PORTABLE_MARKERS`]) in the
//! install folder puts the settings in `VectorCraftData` beside it, so a portable copy leaves
@@ -24,14 +27,45 @@ pub const PORTABLE_MARKERS: [&str; 2] = ["portable.txt", "VectorCraft.portable"]
/// The settings folder created in the install folder in portable mode.
pub const PORTABLE_DATA_DIR: &str = "VectorCraftData";
/// The settings folder of VectorCraft, or of DrawCraft (`legacy`).
pub fn prefs_dir(legacy: bool) -> Option<PathBuf> {
prefs_dir_with(std::env::consts::OS, legacy, |key| std::env::var_os(key), portable_dir)
/// The profile root this process was launched with, if any: a nightly launch's private folder.
static DATA_ROOT: OnceLock<PathBuf> = OnceLock::new();
/// Makes `root` this process's settings folder and everything under it, once, before anything reads
/// a path. The desktop calls it from `prepare_launch` with the root it validated; the command line
/// tool never does, so it keeps resolving the user's own folder.
// The desktop installs it from `prepare_launch`; `vectorcraft-cli` includes this file and never does.
#[allow(dead_code)]
pub(crate) fn install_data_root(root: PathBuf) -> Result<(), String> {
if !root.is_absolute() {
return Err("the data root must be absolute".to_string());
}
DATA_ROOT.set(root).map_err(|_| "the data root was already installed".to_string())
}
/// `portable` is the portable settings folder, if any: only asked for when no override is set and
/// preferences are in use.
fn prefs_dir_with(os: &str, legacy: bool, env: impl Fn(&str) -> Option<OsString>, portable: impl FnOnce() -> Option<PathBuf>) -> Option<PathBuf> {
/// The installed profile root, if this launch has one.
pub(crate) fn data_root() -> Option<&'static Path> {
DATA_ROOT.get().map(PathBuf::as_path)
}
/// The settings folder of VectorCraft, or of DrawCraft (`legacy`).
pub fn prefs_dir(legacy: bool) -> Option<PathBuf> {
prefs_dir_with(std::env::consts::OS, legacy, |key| std::env::var_os(key), portable_dir, data_root())
}
/// `portable` is the portable settings folder, if any: only asked for when neither the launch's
/// profile nor an override is set and preferences are in use.
fn prefs_dir_with(
os: &str,
legacy: bool,
env: impl Fn(&str) -> Option<OsString>,
portable: impl FnOnce() -> Option<PathBuf>,
root: Option<&Path>,
) -> Option<PathBuf> {
// A nightly launch's private profile wins over everything, and a run of DrawCraft's legacy
// folder is never read into it.
if let Some(root) = root {
return (!legacy).then(|| root.to_path_buf());
}
if let Some(root) = env("VECTORCRAFT_CONFIG_DIR") {
// Never fall back to DrawCraft's real profile when the isolated file does not exist.
return (!legacy && !root.is_empty()).then(|| PathBuf::from(root));
@@ -125,8 +159,9 @@ fn portable_dir_in(install_dir: &Path, previous: Option<&Path>) -> Result<Option
Ok(Some(data))
}
/// Create `dir` and prove a file can be written in it (a folder can exist yet be read-only).
fn ensure_writable(dir: &Path) -> std::io::Result<()> {
/// Create `dir` and prove a file can be written in it (a folder can exist yet be read-only). The
/// nightly profile validator wires this same probe in ([`crate::profile_root`]).
pub(crate) fn ensure_writable(dir: &Path) -> std::io::Result<()> {
std::fs::create_dir_all(dir)?;
let probe = dir.join(format!(".write-test-{}", std::process::id()));
std::fs::write(&probe, b"")?;
@@ -230,26 +265,26 @@ mod tests {
let env = |key: &str| {
if key == "VECTORCRAFT_CONFIG_DIR" { Some("/isolated".into()) } else { environment(key) }
};
assert_eq!(prefs_dir_with(os, false, env, installed), Some("/isolated".into()));
assert_eq!(prefs_dir_with(os, true, env, installed), None);
assert_eq!(prefs_dir_with(os, false, env, installed, None), Some("/isolated".into()));
assert_eq!(prefs_dir_with(os, true, env, installed, None), None);
}
}
#[test]
fn empty_override_does_not_fall_back_to_user_files() {
let env = |key: &str| if key == "VECTORCRAFT_CONFIG_DIR" { Some(OsString::new()) } else { environment(key) };
assert_eq!(prefs_dir_with("macos", false, env, installed), None);
assert_eq!(prefs_dir_with("macos", true, env, installed), None);
assert_eq!(prefs_dir_with("macos", false, env, installed, None), None);
assert_eq!(prefs_dir_with("macos", true, env, installed, None), None);
}
#[test]
fn unset_override_keeps_platform_paths_and_legacy_migration() {
assert_eq!(prefs_dir_with("macos", false, environment, installed), Some("/user/Library/Application Support/VectorCraft".into()));
assert_eq!(prefs_dir_with("macos", true, environment, installed), Some("/user/Library/Application Support/DrawCraft".into()));
assert_eq!(prefs_dir_with("windows", false, environment, installed), Some("/roaming/VectorCraft".into()));
assert_eq!(prefs_dir_with("linux", false, environment, installed), Some("/xdg-config/vectorcraft".into()));
assert_eq!(prefs_dir_with("macos", false, environment, installed, None), Some("/user/Library/Application Support/VectorCraft".into()));
assert_eq!(prefs_dir_with("macos", true, environment, installed, None), Some("/user/Library/Application Support/DrawCraft".into()));
assert_eq!(prefs_dir_with("windows", false, environment, installed, None), Some("/roaming/VectorCraft".into()));
assert_eq!(prefs_dir_with("linux", false, environment, installed, None), Some("/xdg-config/vectorcraft".into()));
assert_eq!(
prefs_dir_with("linux", true, |key| if key == "HOME" { environment(key) } else { None }, installed),
prefs_dir_with("linux", true, |key| if key == "HOME" { environment(key) } else { None }, installed, None),
Some("/user/.config/drawcraft".into())
);
}
@@ -258,9 +293,9 @@ mod tests {
fn portable_mode_keeps_the_settings_beside_the_executable_and_skips_the_drawcraft_profile() {
let portable = || Some(PathBuf::from("/usb/VectorCraft/VectorCraftData"));
for os in ["macos", "windows", "linux"] {
assert_eq!(prefs_dir_with(os, false, environment, portable), Some("/usb/VectorCraft/VectorCraftData".into()), "{os}");
assert_eq!(prefs_dir_with(os, false, environment, portable, None), Some("/usb/VectorCraft/VectorCraftData".into()), "{os}");
// A portable copy is self-contained: the one-time read of DrawCraft's old settings is skipped.
assert_eq!(prefs_dir_with(os, true, environment, portable), None, "{os}");
assert_eq!(prefs_dir_with(os, true, environment, portable, None), None, "{os}");
}
}
@@ -268,16 +303,16 @@ mod tests {
fn the_config_dir_override_wins_over_portable_mode_without_probing_it() {
let env = |key: &str| if key == "VECTORCRAFT_CONFIG_DIR" { Some("/isolated".into()) } else { environment(key) };
let portable = || -> Option<PathBuf> { panic!("the portable folder is not looked for under VECTORCRAFT_CONFIG_DIR") };
assert_eq!(prefs_dir_with("windows", false, env, portable), Some("/isolated".into()));
assert_eq!(prefs_dir_with("windows", true, env, portable), None);
assert_eq!(prefs_dir_with("windows", false, env, portable, None), Some("/isolated".into()));
assert_eq!(prefs_dir_with("windows", true, env, portable, None), None);
}
#[test]
fn a_run_without_preferences_never_looks_for_the_portable_folder() {
let env = |key: &str| if key == "VECTORCRAFT_NO_PREFS" { Some("1".into()) } else { environment(key) };
let portable = || -> Option<PathBuf> { panic!("the portable folder is not looked for under VECTORCRAFT_NO_PREFS") };
assert_eq!(prefs_dir_with("windows", false, env, portable), Some("/roaming/VectorCraft".into()));
assert_eq!(prefs_dir_with("windows", true, env, portable), Some("/roaming/DrawCraft".into()));
assert_eq!(prefs_dir_with("windows", false, env, portable, None), Some("/roaming/VectorCraft".into()));
assert_eq!(prefs_dir_with("windows", true, env, portable, None), Some("/roaming/DrawCraft".into()));
}
#[test]
@@ -407,4 +442,31 @@ mod tests {
let _ = std::fs::remove_dir_all(&from);
let _ = std::fs::remove_dir_all(&to);
}
#[test]
fn the_launch_profile_root_wins_over_every_other_rule_without_touching_the_disk() {
let root = Path::new("/launcher/profiles/vectorcraft");
let portable = || -> Option<PathBuf> { panic!("the portable folder is not looked for under a profile root") };
for os in ["macos", "windows", "linux"] {
for override_dir in [None, Some("/isolated")] {
let env = |key: &str| if key == "VECTORCRAFT_CONFIG_DIR" { override_dir.map(OsString::from) } else { environment(key) };
assert_eq!(prefs_dir_with(os, false, env, portable, Some(root)), Some(root.to_path_buf()), "{os}");
// A nightly profile never takes DrawCraft's old settings over.
assert_eq!(prefs_dir_with(os, true, env, portable, Some(root)), None, "{os}");
}
}
}
/// Installs the process-wide root: the one test that may, since a `OnceLock` is set once per
/// process (nextest gives every test its own).
#[test]
fn the_installed_root_is_used_once_and_must_be_absolute() {
let dir = temp("installed-root");
assert!(install_data_root(PathBuf::from("relative/root")).is_err(), "a relative root is refused");
install_data_root(dir.to_path_buf()).unwrap();
assert_eq!(data_root(), Some(&*dir));
assert_eq!(prefs_dir(false), Some(dir.to_path_buf()));
assert!(install_data_root(PathBuf::from("/elsewhere")).is_err(), "a second install is refused");
assert_eq!(data_root(), Some(&*dir), "the first root stays");
}
}
+568
View File
@@ -0,0 +1,568 @@
//! App-owned nightly profile fences: a profile every one of VectorCraft's data paths is redirected
//! into ([`crate::prefs_dir::profile::install_data_root`]), and that never overlaps stable's folders, a portable
//! copy or an installation.
use std::ffi::OsString;
use std::path::{Component, Path, PathBuf};
use crate::prefs_dir::profile::PORTABLE_DATA_DIR;
#[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),
other => Err(format!("nightly-v1 is not defined for this operating system ({other})")),
}
}
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 an 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_else(|| "the profile root has no existing ancestor".to_string())?.to_os_string());
parent = parent.parent().ok_or_else(|| "the profile root has no existing ancestor".to_string())?;
}
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)
}
/// A stable entry point may be a dangling link once its target is uninstalled. Its own name is still
/// the fence, so only the folder it lives in is resolved: a link that cannot be resolved would refuse
/// every launch, a valid private profile included.
fn canonical_future_entry(path: &Path) -> Result<PathBuf, String> {
let parent = path.parent().ok_or_else(|| "an entry point has no folder".to_string())?;
let name = path.file_name().ok_or_else(|| "an entry point has no name".to_string())?;
Ok(canonical_future(parent)?.join(name))
}
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_else(|| "cannot establish the installation boundary".to_string())?;
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())
}
/// Every folder a stable VectorCraft keeps user state in, on `platform`: the settings folder each
/// platform convention and the portable layout use, the eframe window state, the logs, the recovery
/// copies, the plug-ins, the caches, the install folders and the entry points. A nightly profile that
/// overlapped any of them would read, rewrite or prune stable's own state.
fn forbidden_roots(platform: Platform, env: &impl Fn(&str) -> Option<OsString>, exe: &Path) -> Result<Vec<PathBuf>, String> {
let mut roots = match platform {
Platform::Windows => {
// The settings folder (`profile.rs`) and the eframe window state, which eframe puts under
// `%APPDATA%\ai.storyteller.vectorcraft\data` (the window id).
let mut roots = ["APPDATA", "LOCALAPPDATA"]
.into_iter()
.map(|key| required_base(env, key).map(|p| p.join("VectorCraft")))
.collect::<Result<Vec<_>, _>>()?;
roots.push(required_base(env, "APPDATA")?.join("ai.storyteller.vectorcraft"));
// 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("VectorCraft"));
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("VectorCraft"));
}
}
roots
}
Platform::Linux => {
let mut roots =
[("XDG_CONFIG_HOME", ".config"), ("XDG_DATA_HOME", ".local/share"), ("XDG_CACHE_HOME", ".cache"), ("XDG_STATE_HOME", ".local/state")]
.into_iter()
.map(|(key, fallback)| xdg_base(env, key, fallback).map(|p| p.join("vectorcraft")))
.collect::<Result<Vec<_>, _>>()?;
// The eframe window state, under the lowercased window id.
roots.push(xdg_base(env, "XDG_DATA_HOME", ".local/share")?.join("ai.storyteller.vectorcraft"));
roots.push(required_base(env, "HOME")?.join(".config").join("VectorCraft"));
// The same folders at their HOME defaults: an XDG override moves this launch's own paths,
// not stable's, which stays where a launch without the override finds it.
for (directory, app) in
[(".config", "vectorcraft"), (".local/share", "vectorcraft"), (".cache", "vectorcraft"), (".local/state", "vectorcraft")]
{
roots.push(required_base(env, "HOME")?.join(directory).join(app));
}
// The stable Flatpak keeps its data in its own per-app folder.
roots.push(required_base(env, "HOME")?.join(".var/app/ai.storyteller.vectorcraft"));
roots
}
Platform::Mac => {
let home = required_base(env, "HOME")?;
let library = home.join("Library");
vec![
library.join("Application Support/VectorCraft"),
library.join("Application Support/ai.storyteller.vectorcraft"),
library.join("Caches/VectorCraft"),
library.join("Caches/ai.storyteller.vectorcraft"),
library.join("Preferences/VectorCraft"),
library.join("Preferences/ai.storyteller.vectorcraft.plist"),
library.join("Saved Application State/ai.storyteller.vectorcraft.savedState"),
home.join("Applications/VectorCraft.app"),
PathBuf::from("/Applications/VectorCraft.app"),
]
}
};
roots.push(installation_boundary(platform, exe)?);
let mut fences = roots.into_iter().map(|p| canonical_future(&p)).collect::<Result<Vec<_>, _>>()?;
if platform == Platform::Linux {
for entry in ["/usr/bin/vectorcraft", "/usr/local/bin/vectorcraft", "/opt/vectorcraft"] {
fences.push(canonical_future_entry(Path::new(entry))?);
}
}
Ok(fences)
}
fn private_subdirectory(root: &Path, name: impl AsRef<Path>, label: &str) -> 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"));
}
Ok(child)
}
/// Every existing entry directly in the profile (settings, logs, the user's libraries 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) -> 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")?;
}
Ok(())
}
/// Recognise the shared portable data namespace in both the supplied and the resolved path. Up to
/// the chosen folder itself, a marker only counts beside a VectorCraft executable, so an unrelated
/// `portable.txt` higher up (in a user folder or at a drive root) does not refuse the profile.
fn is_portable_layout(path: &Path, platform: Platform) -> bool {
path.ancestors().enumerate().any(|(depth, ancestor)| {
crate::prefs_dir::profile::PORTABLE_MARKERS.iter().any(|marker| ancestor.join(marker).is_file())
&& (depth == 0 || ["vectorcraft.exe", "vectorcraft"].iter().any(|exe| ancestor.join(exe).is_file()))
}) || path.components().any(|component| match component {
Component::Normal(name) if platform.ignores_case() => name.to_string_lossy().eq_ignore_ascii_case(PORTABLE_DATA_DIR),
Component::Normal(name) => name == PORTABLE_DATA_DIR,
_ => false,
})
}
/// The writable hook is the app's own exclusive probe ([`crate::prefs_dir::profile::ensure_writable`]). Keeping
/// it injected lets the boundary tests exercise the real policy without starting the app.
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")?;
if env("VECTORCRAFT_CONFIG_DIR").is_some_and(|v| !v.is_empty()) {
return Err("nightly-v1 cannot be combined with VECTORCRAFT_CONFIG_DIR".to_string());
}
// The app turns preferences off whenever the variable is present, empty value included.
if env("VECTORCRAFT_NO_PREFS").is_some() {
// A run without preferences keeps nothing: its own profile would stay unused and the app
// would log to standard error only, so it is never a nightly launch.
return Err("nightly-v1 cannot inherit VECTORCRAFT_NO_PREFS".to_string());
}
let nightly_flatpak = vectorcraft_ui_egui::os_window::NIGHTLY_PACKAGE_ID;
if platform != Platform::Windows
&& let Some(id) = env("FLATPAK_ID").filter(|value| !value.is_empty())
&& id.to_string_lossy().as_ref() != nightly_flatpak
{
// `packaging/linux/flatpak-bundle.sh` builds VectorCraft Nightly as its own Flatpak
// (`ai.storyteller.vectorcraft.nightly`), whose sandbox is already a private home. Any other
// instance, the stable app's included, would put this profile inside another app's tree.
return Err(format!("nightly-v1 can only run inside its own Flatpak instance ({nightly_flatpak}), not {}", id.to_string_lossy()));
}
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 VectorCraft installation or its VectorCraftData settings folder".to_string());
}
let exe = absolute(exe.ok_or_else(|| "cannot establish the installation boundary".to_string())?.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".to_string());
}
// Data Recovery can read, adopt, overwrite and sweep entries: never let its alias leave the
// private profile.
private_subdirectory(&chosen, "Data Recovery", "recovery folder")?;
entries_stay_inside(&chosen)?;
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".to_string());
}
private_subdirectory(&confirmed, "Data Recovery", "recovery folder")?;
entries_stay_inside(&confirmed)?;
writable(&confirmed).map_err(|e| format!("the nightly profile is not writable: {e}"))?;
Ok(confirmed)
}
#[cfg(test)]
mod tests {
use super::*;
use std::cell::Cell;
use std::collections::BTreeMap;
use std::sync::atomic::{AtomicU64, Ordering};
/// An owned fixture tree: a home, a roaming/local app-data pair and an install folder, so the
/// fence can be checked for every platform on any host.
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!("vectorcraft-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/vectorcraft");
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 home(&self) -> PathBuf {
PathBuf::from(self.get("HOME").unwrap())
}
fn check(&self, platform: Platform, root: &Path) -> Result<PathBuf, String> {
self.check_with(platform, root, |_| Ok(()))
}
fn check_with(&self, platform: Platform, root: &Path, writable: impl FnOnce(&Path) -> std::io::Result<()>) -> Result<PathBuf, String> {
validate_for(platform, root, |key| self.get(key), Some(&self.exe), writable)
}
}
impl Drop for Fixture {
fn drop(&mut self) {
// Only the directory this fixture created is owned for removal.
std::fs::remove_dir_all(&self.root).unwrap();
}
}
const PLATFORMS: [Platform; 3] = [Platform::Windows, Platform::Linux, Platform::Mac];
#[test]
fn a_private_profile_is_accepted_on_every_platform() {
let fixture = Fixture::new();
for platform in PLATFORMS {
let root = fixture.root.join(format!("nightly profiles/{platform:?}/vectorcraft"));
let resolved = fixture.check(platform, &root).unwrap();
assert!(resolved.is_dir(), "{platform:?}");
assert_eq!(resolved, std::fs::canonicalize(root).unwrap(), "{platform:?}");
std::fs::remove_dir_all(fixture.root.join("nightly profiles")).unwrap();
}
}
#[test]
fn stable_settings_folders_are_refused_on_every_platform() {
let fixture = Fixture::new();
let stable = [
(Platform::Windows, fixture.get("APPDATA").map(|v| PathBuf::from(v).join("VectorCraft"))),
(Platform::Windows, fixture.get("APPDATA").map(|v| PathBuf::from(v).join("ai.storyteller.vectorcraft"))),
(Platform::Windows, fixture.get("LOCALAPPDATA").map(|v| PathBuf::from(v).join("VectorCraft"))),
(Platform::Windows, fixture.get("LOCALAPPDATA").map(|v| PathBuf::from(v).join("Programs/ArtCraft/VectorCraft"))),
(Platform::Linux, Some(fixture.home().join(".config/vectorcraft"))),
(Platform::Linux, Some(fixture.home().join(".local/share/vectorcraft"))),
(Platform::Linux, Some(fixture.home().join(".local/share/ai.storyteller.vectorcraft"))),
(Platform::Linux, Some(fixture.home().join(".cache/vectorcraft"))),
(Platform::Linux, Some(fixture.home().join(".var/app/ai.storyteller.vectorcraft"))),
(Platform::Mac, Some(fixture.home().join("Library/Application Support/VectorCraft"))),
(Platform::Mac, Some(fixture.home().join("Library/Application Support/ai.storyteller.vectorcraft"))),
(Platform::Mac, Some(fixture.home().join("Library/Preferences/ai.storyteller.vectorcraft.plist"))),
];
for (platform, stable) in stable {
let stable = stable.unwrap();
for candidate in [stable.clone(), stable.join("nested nightly")] {
let probed = Cell::new(false);
let result = fixture.check_with(platform, &candidate, |_| {
probed.set(true);
Ok(())
});
assert!(result.is_err(), "{platform:?} accepted {candidate:?}");
assert!(!probed.get(), "a refused root is rejected before the writable probe");
}
}
}
#[test]
fn the_install_folder_and_the_entry_points_are_refused() {
let fixture = Fixture::new();
for platform in PLATFORMS {
let install = fixture.exe.parent().unwrap();
assert!(fixture.check(platform, install).is_err(), "{platform:?}: the install folder");
assert!(fixture.check(platform, &install.join("NightlyData")).is_err(), "{platform:?}: inside the install");
}
}
#[test]
fn an_inherited_config_or_no_prefs_override_is_refused() {
let fixture = Fixture::new();
let root = fixture.root.join("nightly");
for (key, value) in [
("VECTORCRAFT_CONFIG_DIR", "/elsewhere"),
("VECTORCRAFT_NO_PREFS", "1"),
// The app turns preferences off on presence, so an empty value is a run too.
("VECTORCRAFT_NO_PREFS", ""),
("FLATPAK_ID", "ai.storyteller.vectorcraft"),
] {
for platform in PLATFORMS {
let result = validate_for(
platform,
&root,
|name| if name == key { Some(value.into()) } else { fixture.get(name) },
Some(&fixture.exe),
|_| Ok(()),
);
let refused = result.is_err();
// A Flatpak instance only keeps the stable app's sockets on native Unix packages.
assert_eq!(refused, !(key == "FLATPAK_ID" && platform == Platform::Windows), "{key} on {platform:?}");
if refused {
assert!(!root.exists(), "a refused launch creates nothing ({key} on {platform:?})");
} else if root.exists() {
// The accepted case validated the root, which creates it: start the next one clean.
std::fs::remove_dir_all(&root).expect("remove the accepted launch's root");
}
}
}
}
#[test]
fn only_the_nightly_s_own_flatpak_instance_may_carry_a_profile() {
let fixture = Fixture::new();
let root = fixture.root.join("flatpak profile");
for (id, accepted) in
[(vectorcraft_ui_egui::os_window::NIGHTLY_PACKAGE_ID, true), ("ai.storyteller.vectorcraft", false), ("io.other.App", false)]
{
let result = validate_for(
Platform::Linux,
&root,
|name| if name == "FLATPAK_ID" { Some(id.into()) } else { fixture.get(name) },
Some(&fixture.exe),
|_| Ok(()),
);
assert_eq!(result.is_ok(), accepted, "{id}");
let _ = std::fs::remove_dir_all(&root);
}
}
#[test]
fn a_portable_copy_and_its_data_folder_are_refused() {
let fixture = Fixture::new();
let portable = fixture.root.join("portable copy");
let data = portable.join(crate::prefs_dir::profile::PORTABLE_DATA_DIR);
std::fs::create_dir_all(&data).unwrap();
std::fs::write(portable.join("portable.txt"), b"owned portable fixture").unwrap();
std::fs::write(data.join("config.toml"), b"stable settings must not change").unwrap();
for platform in PLATFORMS {
for candidate in [&data, &data.join("nested nightly")] {
let probed = Cell::new(false);
let result = fixture.check_with(platform, candidate, |_| {
probed.set(true);
Ok(())
});
assert!(result.is_err(), "{platform:?} accepted {candidate:?}");
assert!(!probed.get());
assert!(!data.join("nested nightly").exists());
assert_eq!(std::fs::read(data.join("config.toml")).unwrap(), b"stable settings must not change");
}
}
// A merely similar name is not the portable settings folder.
let similar = fixture.root.join("VectorCraftData-backup-name/nightly");
assert!(fixture.check(Platform::Linux, &similar).is_ok());
}
#[cfg(unix)]
#[test]
fn a_link_inside_the_profile_cannot_redirect_recovery_or_a_library() {
let fixture = Fixture::new();
let root = fixture.root.join("nightly");
std::fs::create_dir_all(&root).unwrap();
let external = fixture.root.join("stable-document");
std::fs::write(&external, b"stable bytes").unwrap();
for name in ["Data Recovery", "Swatches"] {
let alias = root.join(name);
std::os::unix::fs::symlink(&external, &alias).unwrap();
assert!(fixture.check(Platform::Linux, &root).is_err(), "{name} alias");
std::fs::remove_file(&alias).unwrap();
}
assert_eq!(std::fs::read(&external).unwrap(), b"stable bytes");
}
#[cfg(unix)]
#[test]
fn a_dangling_link_or_a_linked_ancestor_is_refused() {
let fixture = Fixture::new();
let elsewhere = fixture.root.join("elsewhere");
std::fs::create_dir_all(&elsewhere).unwrap();
let linked = fixture.root.join("nightly");
std::os::unix::fs::symlink(&elsewhere, &linked).unwrap();
// Canonical resolution keeps a link's target: a profile reached through one is fine, but it
// is judged (and named) as its target, so nothing is written under the link.
let resolved = fixture.check(Platform::Linux, &linked).unwrap();
assert_eq!(resolved, std::fs::canonicalize(&elsewhere).unwrap());
std::fs::remove_file(&linked).unwrap();
let dangling = fixture.root.join("dangling/nightly");
std::fs::create_dir_all(dangling.parent().unwrap()).unwrap();
std::os::unix::fs::symlink(fixture.root.join("missing"), dangling.parent().unwrap().join("nightly")).unwrap();
assert!(fixture.check(Platform::Linux, &dangling).is_err());
}
#[test]
fn a_home_settings_folder_is_fenced_even_when_the_xdg_override_moves_elsewhere() {
let fixture = Fixture::new();
let xdg = fixture.root.join("override");
std::fs::create_dir_all(&xdg).unwrap();
let config = fixture.home().join(".config/vectorcraft");
let data = fixture.home().join(".local/share/vectorcraft");
for stable in [config.clone(), data.clone()] {
for candidate in [stable.clone(), stable.join("nested nightly")] {
let result = validate_for(
Platform::Linux,
&candidate,
|name| match name {
"XDG_CONFIG_HOME" | "XDG_DATA_HOME" => Some(xdg.clone().into_os_string()),
_ => fixture.get(name),
},
Some(&fixture.exe),
|_| Ok(()),
);
assert!(result.is_err(), "accepted {candidate:?} with the XDG folders moved to {xdg:?}");
}
}
assert!(!config.exists() && !data.exists(), "a refused root creates nothing");
}
#[cfg(unix)]
#[test]
fn a_dangling_entry_point_keeps_its_fence_instead_of_refusing_every_launch() {
let fixture = Fixture::new();
let bin = fixture.root.join("entry/bin");
std::fs::create_dir_all(&bin).unwrap();
let entry = bin.join("vectorcraft");
std::os::unix::fs::symlink(fixture.root.join("uninstalled target"), &entry).unwrap();
// The shared resolver refuses the dangling link, as a profile root must be.
assert!(canonical_future(&entry).is_err());
assert_eq!(canonical_future_entry(&entry).unwrap(), std::fs::canonicalize(&bin).unwrap().join("vectorcraft"));
}
#[test]
fn an_unwritable_profile_is_refused_after_the_probe_and_never_used() {
let fixture = Fixture::new();
let root = fixture.root.join("nightly");
let result = fixture.check_with(Platform::Linux, &root, |_| Err(std::io::Error::other("read-only")));
assert!(result.unwrap_err().contains("not writable"));
}
#[test]
fn the_platform_case_rules_are_the_file_systems_ones() {
let fixture = Fixture::new();
let upper = fixture.root.join("NIGHTLY");
assert!(fixture.check(Platform::Linux, &upper).is_ok());
let stable_mac = fixture.home().join("library/application support/vectorcraft");
assert!(fixture.check(Platform::Mac, &stable_mac).is_err(), "macOS compares folders case-insensitively");
}
}
+3 -2
View File
@@ -144,10 +144,11 @@ pub fn launch_with_plug_ins(files: &[String]) -> io::Result<()> {
}
/// The command [`launch_with_plug_ins`] runs: `exe -- files…`, so a file whose name starts with '-'
/// stays a file.
/// stays a file. A nightly launch hands its profile on first (`launch_profile::child_args`), or the
/// child would refuse to start without one.
fn app_with_plug_ins(exe: &Path, files: &[String]) -> std::process::Command {
let mut command = std::process::Command::new(exe);
command.arg("--").args(files);
command.args(super::launch_profile::child_args(files));
command
}
+11
View File
@@ -31,6 +31,10 @@ artwork. Licence: see `LICENSE.txt`.
| `vectorcraft.ico` | Windows icon, 16 to 256 px | `apps/vectorcraft/build.rs` (embedded in the `.exe`) |
| `hicolor/<size>/apps/ai.storyteller.vectorcraft.png` | Linux theme icons, 16 to 512 px; the 256 one is also the runtime icon on Windows and Linux, the 128 one the brand mark in the app bar and About box (`crates/ui-egui/src/brand.rs`) | `packaging/linux/ai.storyteller.vectorcraft.desktop` |
| `hicolor/scalable/apps/ai.storyteller.vectorcraft.svg` | Linux scalable icon | as above |
| `vectorcraft-nightly.png` | the full tile with a deeper field, 1024 px | the Nightly feed's art (`packaging/nightly-icons.py`) |
| `vectorcraft-nightly-1024.png` | the same tile with Apple's margin, 1024 px | the Nightly `.app` master |
| `vectorcraft-nightly.ico` | Windows icons for the Nightly executable, 16 to 256 px | `apps/vectorcraft/build.rs` when built for `nightly-v1` |
| `vectorcraft-nightly.icns` | macOS icon set for the Nightly `.app`, 16 to 1024 px | `packaging/macos/nightly.sh` |
## How it reaches each OS
@@ -47,3 +51,10 @@ artwork. Licence: see `LICENSE.txt`.
Edit or replace `vectorcraft.svg` (and `vectorcraft-small.svg`), then run `packaging/icons.sh`
(needs `resvg`; `iconutil` on macOS for the `.icns`). It writes every PNG, the `.ico` (via
`cargo xtask ico`) and the `.icns`.
The Nightly art comes from the committed stable art, not from a new drawing: `python3
packaging/nightly-icons.py` solves each pixel's field contribution from the three-colour palette
(`#e8573f`, `#0b0b0c`, `#efe9dc`), adds the deeper field (`#a83a24`) and leaves the figure (ink and
paper) exactly as it was, then scales every frame natively with ffmpeg and packs the `.ico` (32bpp
BGRA frames with AND masks up to 128, a PNG frame for 256) and the `.icns` (PNG frames). No badge,
no crescent and no letter: the field alone says Nightly.
Binary file not shown.

After

Width:  |  Height:  |  Size: 646 KiB

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 182 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 235 KiB

+5
View File
@@ -472,6 +472,11 @@ impl RecoveryStore for FolderStore {
Self::create_area(dir)?;
Self::own_area(dir)?;
}
// A read refuses a link (`read`), and a write must too: the atomic writer replaces the
// target of a link, which would put the copy over a file outside the store.
if std::fs::symlink_metadata(&f).is_ok_and(|m| m.file_type().is_symlink()) {
return Err(format!("{}: not a plain file", f.display()));
}
vectorcraft_format::write_atomic(&f, bytes).map_err(|e| Self::file_error(&f, &e))
}
fn remove(&self, name: &str) -> std::result::Result<(), String> {
+16
View File
@@ -571,6 +571,22 @@ fn the_folder_store_reads_no_linked_entries() {
let _ = std::fs::remove_dir_all(&base);
}
/// A write to an entry that is a link (the copy's metadata names it) must not follow it out of the
/// store: the file behind the link keeps its bytes.
#[cfg(unix)]
#[test]
fn the_folder_store_writes_no_linked_entries() {
let base = std::env::temp_dir().join(format!("vc-recovery-write-links-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&base);
let store = FolderStore::new(&base);
store.write("1-1/Untitled-1-1.vectorcraft", b"copy").unwrap();
std::fs::write(base.join("outside"), b"private").unwrap();
std::os::unix::fs::symlink(base.join("outside"), base.join("1-1").join("img")).unwrap();
assert!(store.write("1-1/img", b"copy").is_err());
assert_eq!(std::fs::read(base.join("outside")).unwrap(), b"private");
let _ = std::fs::remove_dir_all(&base);
}
/// A file where a folder of the store's path should be: the error names that file, not the area
/// folder or the copy below it, for a write, a lock, a read, a listing, a removal and a recovery
/// save.
+7 -3
View File
@@ -48,8 +48,12 @@ pub(crate) mod view;
pub use fonts::MAX_RECENT_FONTS;
/// VectorCraft as the framework's services know it: the settings folder, the name and the version.
const APP_INFO: AppInfo = AppInfo { id: "vectorcraft", name: "VectorCraft", version: env!("CARGO_PKG_VERSION") };
/// VectorCraft as the framework's services know it: the settings id, the name and the version.
/// A nightly build gives its own name and feed version; the id stays the stable one, since the
/// runtime keys a theme's `[apps.<id>]` pins on it.
fn app_info() -> AppInfo {
AppInfo { id: crate::os_window::SETTINGS_APP_ID, name: crate::os_window::name(), version: crate::os_window::version() }
}
/// Monotonic seconds of the app's clock, which recovery, the clipboard look and the frame rate
/// count in.
@@ -98,7 +102,7 @@ impl VectorcraftApp {
}
};
// PLAN: the hosts (hub-w3) replace `host` with the one they build (files, settings, jobs); every frame installs it through `frame_input`.
let host = Arc::new(Host::builder(APP_INFO).i18n(i18n::shared()).build());
let host = Arc::new(Host::builder(app_info()).i18n(i18n::shared()).build());
Self {
session,
ui: UiState::default(),
+12 -4
View File
@@ -137,8 +137,10 @@ pub fn app_bar(ui: &mut Ui, _cx: &mut BodyCx<'_>, app: &mut VectorcraftApp) {
// Both closures need the app; the bar runs them one after the other.
let start = |ui: &mut Ui, _: &mut BodyCx<'_>| leading(ui, &mut app.borrow_mut());
let end = |ui: &mut Ui, _: &mut BodyCx<'_>| trailing(ui, &mut app.borrow_mut());
// A nightly's window and Dock entry carry its own name, so they never read as the stable app's.
let title = if crate::os_window::stable_services_allowed() { tl!("VectorCraft") } else { crate::os_window::name() };
let _ = if titled {
TitleBar::new().surface(SurfaceKind::Background).show_titled(ui, Title::new(tl!("VectorCraft")), start, end)
TitleBar::new().surface(SurfaceKind::Background).show_titled(ui, Title::new(title), start, end)
} else {
TitleBar::new().surface(SurfaceKind::Background).show_fitted(ui, start, end)
};
@@ -146,13 +148,19 @@ pub fn app_bar(ui: &mut Ui, _cx: &mut BodyCx<'_>, app: &mut VectorcraftApp) {
/// The OS window title: the active document's name suffixed with the app name (a `*` prefix
/// marks unsaved changes, like the `*` in the document tabs), or just the app name with no
/// document open; in Safe Mode, followed by "(Safe Mode)".
/// document open; in Safe Mode, followed by "(Safe Mode)". The app name is the build's own
/// ([`crate::os_window::name`]): a nightly's window is not the stable app's.
pub fn window_title(app: &VectorcraftApp) -> String {
window_title_named(app, crate::os_window::name())
}
/// [`window_title`] with the app name given, so both channels' titles can be read in one build.
fn window_title_named(app: &VectorcraftApp, app_name: &str) -> String {
let title = app
.session
.active()
.map(|d| format!("{}{} \u{2014} VectorCraft", if d.is_dirty() { "*" } else { "" }, d.title()))
.unwrap_or_else(|| "VectorCraft".into());
.map(|d| format!("{}{} \u{2014} {app_name}", if d.is_dirty() { "*" } else { "" }, d.title()))
.unwrap_or_else(|| app_name.to_string());
if vectorcraft_plugins::safe_mode::active() { format!("{title} ({})", tl!("Safe Mode")) } else { title }
}
+12
View File
@@ -1554,6 +1554,18 @@ fn window_title_follows_the_active_file() {
);
}
/// A nightly's window carries the nightly name, with and without a document, so the stable app's
/// window and taskbar entry never read the same.
#[test]
fn a_nightly_window_title_carries_the_nightly_name() {
let mut app = crate::VectorcraftApp::new(Session::new(), Default::default());
let nightly = crate::os_window::name_for(crate::os_window::LaunchIdentity::NightlyV1);
assert_eq!(super::window_title_named(&app, nightly), "VectorCraft Nightly");
app.run("file.new", json!({"width": 100, "height": 100, "name": "foo.svg"})).unwrap();
let titled = super::window_title_named(&app, nightly);
assert!(titled.contains("foo.svg") && titled.ends_with("\u{2014} VectorCraft Nightly"), "{titled}");
}
/// The document tabs over `app`, with the same per-frame view synchronization as the app.
fn tabs_with_views(app: &mut crate::VectorcraftApp, ui: &mut egui::Ui) {
app.sync_views();
+1 -1
View File
@@ -76,7 +76,7 @@ pub fn about_info(app: &mut VectorcraftApp) -> AboutInfo {
built_with.push('\n');
built_with.push_str(&crate::i18n::fmt(tl!("Graphics: {adapter}"), &[("adapter", adapter.as_str())]));
}
let mut info = AboutInfo::new("VectorCraft", tl!("Open-source vector illustration in pure Rust."), env!("CARGO_PKG_VERSION"))
let mut info = AboutInfo::new(crate::os_window::name(), tl!("Open-source vector illustration in pure Rust."), crate::os_window::version())
.links(links)
.built_with(built_with)
.icon(crate::brand::image());
+1
View File
@@ -56,6 +56,7 @@ pub mod layout_migration;
pub mod menus;
pub mod opening;
mod original_editor;
pub mod os_window;
#[doc(hidden)]
pub use original_editor::Choice as OriginalEditorChoice;
mod page_glyphs;
+143
View File
@@ -0,0 +1,143 @@
//! The identity every VectorCraft OS window carries: the main window (`main.rs`), the runtime's
//! windows (`InstallSpec::app_id`) and the extra windows built with [`builder`], so docks show the
//! VectorCraft icon on them and Wayland compositors' window rules can match them. Without one the
//! app id is empty.
//!
//! The identity and the version are selected once, by the desktop app, before any window or UI
//! service exists ([`select_identity`], [`set_version`]). A library user (the web build, a test)
//! gets the stable identity and this crate's own version.
/// Matches the `.desktop` file and hicolor icon name, so Wayland docks pick up the icon.
pub const APP_ID: &str = "ai.storyteller.vectorcraft";
/// The craft-settings app id, which the runtime keys a theme's `[apps.<id>]` pins on: neither the
/// window id nor the channel, so it stays the same in both, and a user's theme keeps applying.
pub const SETTINGS_APP_ID: &str = "vectorcraft";
/// The package, macOS bundle and Linux archive identity of a nightly-v1 build; the window and the
/// Windows AUMID end in `.nightly-v1` instead (see [`NIGHTLY_APP_ID`]), so the two stay apart.
pub const NIGHTLY_PACKAGE_ID: &str = "ai.storyteller.vectorcraft.nightly";
/// The window, Dock and Wayland id of a nightly-v1 build.
pub const NIGHTLY_APP_ID: &str = "ai.storyteller.vectorcraft.nightly-v1";
/// Stable's name; `nightly`'s differs so the two are told apart in the Dock, the taskbar and menus.
pub const APP_NAME: &str = "VectorCraft";
pub const NIGHTLY_APP_NAME: &str = "VectorCraft Nightly";
/// Immutable startup identity. The desktop selects it before any UI or runtime service is created.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LaunchIdentity {
Stable,
NightlyV1,
}
/// 0: not selected yet (stable), 1: stable, 2: nightly.
static IDENTITY: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);
/// Selects the identity once; a second selection is an error rather than a silent change.
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".to_string())
}
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_APP_ID,
}
}
pub fn app_id() -> &'static str {
id_for(identity())
}
pub const fn name_for(identity: LaunchIdentity) -> &'static str {
match identity {
LaunchIdentity::Stable => APP_NAME,
LaunchIdentity::NightlyV1 => NIGHTLY_APP_NAME,
}
}
pub fn name() -> &'static str {
name_for(identity())
}
/// Whether the stable services (the updater, the control channel, the shared suite state) may run.
pub const fn stable_services_for(identity: LaunchIdentity) -> bool {
matches!(identity, LaunchIdentity::Stable)
}
pub fn stable_services_allowed() -> bool {
stable_services_for(identity())
}
/// The version the build was made with: the exact feed identity on a nightly, the package version
/// on a stable build (the host app hands it over from its build script).
static VERSION: std::sync::OnceLock<&'static str> = std::sync::OnceLock::new();
/// Sets the version once; a second call is an error rather than a silent change.
pub fn set_version(version: &'static str) -> Result<(), String> {
if version.is_empty() {
return Err("the built version is empty".to_string());
}
VERSION.set(version).map_err(|_| "the built version was already selected".to_string())
}
pub fn version() -> &'static str {
VERSION.get().copied().unwrap_or(env!("CARGO_PKG_VERSION"))
}
/// A builder for an extra OS window, carrying [`app_id`].
pub fn builder() -> egui::ViewportBuilder {
egui::ViewportBuilder::default().with_app_id(app_id())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_nightly_identity_is_distinct_and_never_enables_stable_services() {
assert_eq!(id_for(LaunchIdentity::Stable), APP_ID);
assert_ne!(id_for(LaunchIdentity::NightlyV1), APP_ID);
assert_ne!(name_for(LaunchIdentity::Stable), name_for(LaunchIdentity::NightlyV1));
assert!(stable_services_for(LaunchIdentity::Stable));
assert!(!stable_services_for(LaunchIdentity::NightlyV1));
}
#[test]
fn the_two_nightly_ids_are_the_contract_ones() {
// The package and bundle identity ends in `.nightly`; the window and AUMID in `.nightly-v1`.
assert_eq!(NIGHTLY_PACKAGE_ID, "ai.storyteller.vectorcraft.nightly");
assert_eq!(NIGHTLY_APP_ID, "ai.storyteller.vectorcraft.nightly-v1");
assert_ne!(NIGHTLY_PACKAGE_ID, NIGHTLY_APP_ID);
}
#[test]
fn the_settings_app_id_is_neither_the_window_id_nor_channel_specific() {
assert_eq!(SETTINGS_APP_ID, "vectorcraft");
assert_ne!(SETTINGS_APP_ID, APP_ID);
assert_ne!(SETTINGS_APP_ID, id_for(LaunchIdentity::NightlyV1));
}
#[test]
fn unselected_windows_carry_the_stable_app_id() {
assert_eq!(builder().app_id.as_deref(), Some(APP_ID));
}
#[test]
fn only_a_non_empty_version_is_kept() {
assert!(set_version("").is_err());
}
}
+2 -2
View File
@@ -20,7 +20,7 @@ pub const LAST_SESSION_STOPPED: &str =
pub fn text(app: &VectorcraftApp) -> String {
match &app.services.troubleshooting {
Some(text) => text(),
None => format!("VectorCraft {}\n", env!("CARGO_PKG_VERSION")),
None => format!("{} {}\n", crate::os_window::name(), crate::os_window::version()),
}
}
@@ -59,7 +59,7 @@ mod tests {
fn without_the_service_the_version_is_copied() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("help.copyTroubleshootingInfo", json!({})).unwrap();
assert_eq!(app.clipboard_out, Some(format!("VectorCraft {}\n", env!("CARGO_PKG_VERSION"))));
assert_eq!(app.clipboard_out, Some(format!("{} {}\n", crate::os_window::name(), crate::os_window::version())));
}
#[test]
+85 -14
View File
@@ -5,26 +5,45 @@ use serde_json::Value;
use crate::VectorcraftApp;
#[cfg(target_arch = "wasm32")]
use craft::ui::dialog::{Alert, HostedAlert};
#[cfg(not(target_arch = "wasm32"))]
use craft::update::stack_dialogs::{CheckChoice, UpdateCheckDialog, UpdatePromptDialog};
#[cfg(not(target_arch = "wasm32"))]
use craft::update::updater::{Action, Status, Updater};
/// Whether this build checks for, downloads and installs VectorCraft's releases itself. A nightly
/// does not: ArtCraft Launcher manages its updates, and the updater keeps its records, downloads
/// and logs in the stable app's folders (`%LOCALAPPDATA%\VectorCraft` on Windows), which the
/// profile fence refuses.
#[cfg(not(target_arch = "wasm32"))]
const fn app_updates_allowed_for(identity: crate::os_window::LaunchIdentity) -> bool {
crate::os_window::stable_services_for(identity)
}
#[cfg(not(target_arch = "wasm32"))]
pub(crate) struct Runtime {
updater: Updater,
/// This build's updater: absent in a nightly, which never checks, downloads or installs.
updater: Option<Updater>,
/// The desktop app turns the check at start on; tests leave it off.
startup_check: bool,
/// Whether a modal update dialog was open in the last pass.
was_modal: bool,
}
#[cfg(not(target_arch = "wasm32"))]
impl Runtime {
/// The runtime `identity` uses: a nightly keeps no updater at all, so no check, download,
/// install or record can start from it.
fn for_identity(identity: crate::os_window::LaunchIdentity) -> Self {
let updater = app_updates_allowed_for(identity).then(|| Updater::new(&crate::UPDATE_APP, env!("CARGO_PKG_VERSION")));
Self { updater, startup_check: false, was_modal: false }
}
}
#[cfg(not(target_arch = "wasm32"))]
impl Default for Runtime {
fn default() -> Self {
Self { updater: Updater::new(&crate::UPDATE_APP, env!("CARGO_PKG_VERSION")), startup_check: false, was_modal: false }
Self::for_identity(crate::os_window::identity())
}
}
@@ -40,7 +59,8 @@ impl VectorcraftApp {
/// there, since the app is then never dropped.
#[cfg(not(target_arch = "wasm32"))]
pub fn start_pending_update(&mut self) {
self.updates_rt.updater.start_pending_update();
let Some(updater) = self.updates_rt.updater.as_mut() else { return };
updater.start_pending_update();
}
}
@@ -55,11 +75,25 @@ pub(crate) fn check(app: &mut VectorcraftApp) -> Result<Value, String> {
let dialogs = app.dialogs().ok_or("no window")?;
#[cfg(not(target_arch = "wasm32"))]
{
let Some(updater) = app.updates_rt.updater.as_mut() else {
// A nightly's updates are the Launcher's: say so, rather than offer a stable release
// that would install over the profile this build has to stay inside.
dialogs.with(|h| {
// One notice is enough: a second Check while it is open shows nothing new.
if !h.is_open::<HostedAlert>() {
h.open(HostedAlert::new(Alert::new(
tl!("VectorCraft Updates").to_string(),
tl!("VectorCraft Nightly's updates come from ArtCraft Launcher.").to_string(),
)));
}
});
return Ok(Value::Null);
};
// An open result dialog shows the new status itself.
dialogs.with(|h| {
let _ = h.open_unless_open(check_dialog());
});
app.updates_rt.updater.check_now();
updater.check_now();
}
#[cfg(target_arch = "wasm32")]
dialogs.with(|h| {
@@ -76,15 +110,22 @@ pub(crate) fn check(app: &mut VectorcraftApp) -> Result<Value, String> {
pub(crate) fn tick(app: &mut VectorcraftApp, ctx: &egui::Context) {
#[cfg(not(target_arch = "wasm32"))]
{
let rt = &mut app.updates_rt;
if rt.startup_check {
rt.updater.check_at_start();
// A nightly keeps no updater: nothing here runs, so nothing checks, downloads or installs.
if app.updates_rt.updater.is_none() {
return;
}
rt.updater.tick(ctx);
if app.updates_rt.startup_check
&& let Some(updater) = app.updates_rt.updater.as_mut()
{
updater.check_at_start();
}
let Some(updater) = app.updates_rt.updater.as_mut() else { return };
updater.tick(ctx);
// An installation, and the close for a ready update, wait for unsaved and running work.
let safe = safe_to_close(app);
let Some(dialogs) = app.dialogs() else { return };
match dialogs.with(|h| app.updates_rt.updater.run(h, safe)) {
let Some(updater) = app.updates_rt.updater.as_mut() else { return };
match dialogs.with(|h| updater.run(h, safe)) {
Action::OpenUrl(url) => app.open_url(&url),
Action::Close => ctx.send_viewport_cmd(egui::ViewportCommand::Close),
_ => {}
@@ -123,7 +164,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) {
#[cfg(not(target_arch = "wasm32"))]
{
let Some(dialogs) = app.dialogs() else { return };
let updater = &mut app.updates_rt.updater;
let Some(updater) = app.updates_rt.updater.as_mut() else { return };
let status = updater.status().clone();
let prompt_open = updater.prompt_open();
let (answered, modal) = dialogs.with(|h| {
@@ -170,7 +211,7 @@ pub(crate) fn open_prompt_for_test(app: &mut VectorcraftApp) {
/// Closes the update prompt and the result dialog for a test in another module.
#[cfg(all(test, not(target_arch = "wasm32")))]
pub(crate) fn close_dialogs_for_test(app: &mut VectorcraftApp) {
app.updates_rt.updater = tests::isolated_updater(env!("CARGO_PKG_VERSION"), "closed");
app.updates_rt.updater = Some(tests::isolated_updater(env!("CARGO_PKG_VERSION"), "closed"));
// The dialogs are the host's: a new updater does not take them down.
if let (Some(ctx), Some(dialogs)) = (app.ui_ctx.clone(), app.dialogs()) {
dialogs.with(|h| {
@@ -205,8 +246,9 @@ mod tests {
#[cfg(not(target_arch = "wasm32"))]
pub(super) fn offer(app: &mut VectorcraftApp) {
app.updates_rt.updater = isolated_updater(env!("CARGO_PKG_VERSION"), "prompt");
offer_and_wait(&mut app.updates_rt.updater, release_99());
let mut updater = isolated_updater(env!("CARGO_PKG_VERSION"), "prompt");
offer_and_wait(&mut updater, release_99());
app.updates_rt.updater = Some(updater);
}
/// The release the tests offer.
@@ -255,6 +297,35 @@ mod tests {
app
}
/// A nightly keeps no updater: its check points at ArtCraft Launcher, and no frame or exit
/// hook starts a check, a download or an install.
#[test]
#[cfg(not(target_arch = "wasm32"))]
fn a_nightly_never_checks_downloads_or_installs_an_update() {
use crate::os_window::LaunchIdentity;
assert!(app_updates_allowed_for(LaunchIdentity::Stable));
assert!(!app_updates_allowed_for(LaunchIdentity::NightlyV1));
assert!(Runtime::for_identity(LaunchIdentity::NightlyV1).updater.is_none());
assert!(Runtime::for_identity(LaunchIdentity::Stable).updater.is_some());
let mut app = app_with_saved_object();
// A nightly's runtime has no updater at all, so not even the frame that gives the app its
// dialog host may start a check (`dialogs()` is `None` before that frame runs).
app.updates_rt.updater = None;
let ctx = crate::unsaved::ready_for_test(&mut app);
let opened = app.dialogs().expect("the frame gives the app its dialog host").with(|h| h.open_dialogs().len());
assert_eq!(opened, 0, "the first frame opens no update dialog in a nightly");
// Neither a frame nor the exit hook does anything at all.
tick(&mut app, &ctx);
pump(&mut app, &ctx);
app.start_pending_update();
let opened = app.dialogs().expect("the dialog host").with(|h| h.open_dialogs().len());
assert_eq!(opened, 0, "a nightly opens no update dialog on its own");
// Asked to check, it says who manages its updates instead of asking about a release.
check(&mut app).unwrap();
assert!(app.dialogs().unwrap().with(|h| h.is_open::<HostedAlert>()), "the check names ArtCraft Launcher");
}
#[test]
#[cfg(not(target_arch = "wasm32"))]
fn unsaved_changes_dialogs_and_running_work_hold_an_update_back() {
+145
View File
@@ -0,0 +1,145 @@
# Windows, Linux and macOS release-ref nightly: supervised manual go-live
**Enabled for supervised manual runs, not yet qualified.** The producer (`nightly.yml`, main) and the
signer (`nightly-sign.yml`, release) keep only their exact context guards and run when one of the reviewed
manual actors dispatches them. There is no schedule yet. The installed policy
[`.github/nightly-signing-policy.json`](../.github/nightly-signing-policy.json) is the v3
policy. Once `nightly.yml` reaches `main`, populate `producer_workflow_id` with its registration ID
before promoting the policy to `release`:
```bash
gh api repos/storytold/vectorcraft/actions/workflows/nightly.yml --jq .id
```
The callers pass no platform secrets. 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`. A pin is reviewed
source availability, not provider, queue, native signing or crypto qualification.
Existing stable workflows are unchanged.
**First runs.** The first runs are manual dispatches in this order: `nightly.yml` on main (only a
listed manual actor passes the producer's plan step), then `nightly-sign.yml` on `release` with that
producer run ID and attempt, by a listed manual actor.
**Manual actors.** `bflatastic`, `dylanmtaylor`, `echelon`, `FredApps` and `skylartaylor`, in the
producer's `manual-actors` and the policy's `manual_actors`. The list mirrors the release-managers
team (id 19837241), leaving out `echelon-robot`; update it by PR in both places when the team changes.
**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.
## Installed policy values and their sources
Read on 2026-11-24; re-read anything that may have moved (and populate `producer_workflow_id` after `nightly.yml` lands on `main`) before the policy is promoted to `release`.
| Field | Value | Source |
|---|---|---|
| `repository_id` | `1398097510` | `gh api repos/storytold/vectorcraft --jq .id` |
| `producer_workflow_id` | `null` (pending first registration on `main`) | Read via `gh api repos/storytold/vectorcraft/actions/workflows/nightly.yml --jq .id` once `nightly.yml` is on `main` |
| `producer_tooling_revision`, `signer_tooling_revision`, `producer_workflow_ref` | `605d5876…` (craft-common-actions #339) | The callers' pin |
| `manual_actors` / `automatic_signer_actors` | the five release managers / `[]` | release-managers team (id 19837241) members who can push; equals the producer caller's `manual-actors` |
| `max_age_seconds`, `max_artifact_bytes` | `86400`, `2147483648` | Go-live checklist |
| `platforms` | three rows | Learning Machines stable identities (Windows Authenticode publisher subject, Linux OpenPGP fingerprint, Apple Developer ID team `DJ6XS33FX8`) |
| `candidate_policy.required_workflows` | CI (`ci.yml`, workflow `380135806`), 8 jobs | Workflow list API; jobs that succeeded on recent main push runs |
| `candidate_policy.sonar` | `storytold` / `storytold_vectorcraft`, app `12526` | `sonar-project.properties`; the SonarCloud check on main commits |
## Ownership and interface
- `.github/workflows/nightly.yml`: default-main registration of the unsigned producer, named
`VectorCraft unsigned nightly`, enabled for manual dispatch by `manual-actors`; no signing secrets
may be passed or inherited.
- `.github/workflows/nightly-sign.yml`: top-level release registration, enabled for manual dispatch,
and identical on main and release after reviewed promotion. It rejects wrong repository/event/actual branch,
including same-name tags. Its constant whole-run concurrency (`vectorcraft-nightly-release`) is distinct
from stable, cancellation is off and `queue: max` must be hosted-qualified. The caller itself passes no
credentials; only the shared callee's sign jobs bind the `release` environment.
- 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.
## Local regression checks
`python3 packaging/nightly-release-tests.py` verifies the nightly workflow and policy source contracts:
- Exact context guards on `nightly.yml` and `nightly-sign.yml` (including multi-line continuation checks).
- Manual actors match the reviewed release-managers list in both `nightly.yml` and `.github/nightly-signing-policy.json`, with `automatic_signer_actors` empty.
- Both callers pin the same immutable `craft-common-actions` commit in `uses` and `tooling-revision`.
- No nightly schedule is registered, no cache actions or secrets appear in the app callers, and `nightly-sign.yml` retains its literal root `concurrency` block (`group: vectorcraft-nightly-release`, `cancel-in-progress: false`, `queue: max`).
- Policy v3 schema, platform rows, bounds, required main-push CI workflow, and SonarCloud project identity match `sonar-project.properties`.
## The app side of a Nightly build
The producer and signer call into this repository:
| Platform | Compile step (no secrets) | Trusted signing step (release checkout) | Check |
|---|---|---|---|
| Windows x86_64 | `pwsh packaging/windows/package.ps1 -Arch x64 -Nightly -BuildOnly` | `packaging/windows/sign.ps1 -Required` | `nightly.ps1`'s PE, ProductName and version checks |
| macOS aarch64 | `bash packaging/macos/nightly.sh --arch aarch64` | `packaging/macos/nightly-sign.sh` (with `import-cert.sh`, `entitlements.plist`, `nightly.sh`) | `packaging/macos/nightly-verify.sh --expect signed --team` |
| Linux x86_64 | `bash packaging/linux/nightly.sh --arch x86_64` | the shared Linux signer | the shared `nightly_unix.py` isolation checks |
The three platform-specific scripts share `packaging/nightly-common.sh` (input checks, the owned
compile, the notice copier, the exclusive publish) and `packaging/nightly_paths.py` (the private
build root every helper stays inside). `packaging/nightly-tests.py` runs the synthetic suites
(`nightly-archive-tests.py`, `linux/nightly-launch-tests.py`, `macos/nightly_plist_tests.py`,
`macos/nightly_sign_tests.py`, `nightly-release-tests.py`); `.github/workflows/nightly-check.yml`
runs them with the Windows PowerShell suites, and `.github/workflows/nightly-macos.yml` builds and
verifies the unsigned bundle behind the `full-ci` label.
Every Linux Nightly format starts the app the same way, through one launcher
(`packaging/linux/nightly-launch.sh`): the plain tar's `vectorcraft`, the deb/rpm's
`/usr/bin/vectorcraft-nightly`, the AppImage's `AppRun`, the Arch handoff's `bin/vectorcraft` and
the Flatpak's `/app/bin/vectorcraft`. It runs the GUI beside it (`<app>-bin`, the standard Nightly
layout; `/usr/lib/vectorcraft-nightly/vectorcraft-bin` for deb/rpm, `/app/libexec/vectorcraft-bin`
inside the Flatpak) with `--launch-profile nightly-v1 --profile-root <dir> -- "$@"`, and passes a
version query, help or the Launcher's own `--launch-profile` invocation straight through. The
Nightly tar therefore holds `vectorcraft` (launcher), `vectorcraft-bin` (GUI), `vectorcraft.png`
(the Nightly art) and the notices.
The build switch is `VECTORCRAFT_BUILD_CHANNEL=nightly-v1`, which `apps/vectorcraft/build.rs` turns
into `cfg(vectorcraft_nightly_v1)`; the identity is `VECTORCRAFT_VERSION`
(`X.Y.Z-nightly.YYYYMMDD.<run>.<attempt>.g<sha12>`), also accepted from
`VECTORCRAFT_OVERRIDE_VERSION`, which is the name this repository's packaging scripts already pass
to cargo. A nightly build without that identity refuses to build.
The executable answers `--version`, `-V` and the Launcher's `--launch-profile nightly-v1
--profile-root <abs> --version` before root validation, logging, IPC or any window, with exactly
`VectorCraft <version> (nightly-v1)`. A nightly without a profile is refused (exit 2) with the
message to open VectorCraft Nightly from ArtCraft Launcher; a stable build refuses the profile. That
refusal goes to standard error, which a Launcher launch records: a release build has no console, so
a Nightly started outside the Launcher exits 2 without a dialog. A native message box would need a
new dependency (the workspace denies `unsafe_code`, and a cross-platform dialog crate would change
`Cargo.lock`); the Launcher is the supported way in.
A nightly does not update itself: Help › Check for Updates says that ArtCraft Launcher manages
the Nightly's updates, and the startup check, the pending install and the updater itself are not
created (`updates_ui::Runtime` keeps no updater unless `os_window::stable_services_allowed()`). The
craft-update records, downloads and logs otherwise live in the stable app's folders, which the
profile fence refuses.
All user state of a nightly launch lives in the profile root the Launcher passes: `config.toml`,
`logs`, `Data Recovery`, `Plug-ins`, `Fonts`, the user's libraries and script data, the
single-instance record, the session record and the framework's `window.json` (the window's size
and position). eframe's own persistence is off in this build (its `persistence` feature is not
enabled, so no `app.ron` is written anywhere); if it is ever turned on, its state goes to
`<profile>/eframe`, a folder of its own, never to the `window.json` file.
`apps/vectorcraft/src/profile_root.rs` fences it off stable's folders, a portable copy and the
installation on every platform, and `apps/vectorcraft/src/profile.rs` (`install_data_root`) is the
one hook every data path follows.
## Activation prerequisite: the Sonar issue scope
The pinned candidate validator requires every entry in `candidate_policy.sonar.issue_types` to map
from a reviewed `accepted_conditions` row, and it requires the gate condition set to equal
`accepted_conditions` plus `required_conditions`. The installed policy lists `VULNERABILITY` with no
accepted condition, so it fails that contract before SonarCloud is read. Correct the policy in this
app's activation review with Skylar, together with the live gate conditions, before the first run:
the callers cannot run before that review anyway, because their `producer_workflow_id` stays null
until `nightly.yml` is registered on `main` and the signer is promoted to `release`.
+45 -8
View File
@@ -17,6 +17,12 @@ set -euo pipefail
. "$(dirname "${BASH_SOURCE[0]}")/../env.sh"
HERE="$ROOT/packaging/linux"
APP_ID=ai.storyteller.vectorcraft
FLATPAK_ID="$APP_ID"
# The remote indexes both app IDs on the stable ref branch; IDs isolate installations.
FLATPAK_BRANCH=stable
if [[ "${VECTORCRAFT_BUILD_CHANNEL:-}" == nightly-v1 || "$VERSION" == *-nightly* ]]; then
FLATPAK_ID="$APP_ID.nightly"
fi
FLATHUB=https://dl.flathub.org/repo/flathub.flatpakrepo
TEST=1
@@ -38,7 +44,11 @@ case "$ARCH" in
aarch64 | arm64) ARCH=aarch64 ;;
*) echo "unsupported architecture $ARCH" >&2; exit 2 ;;
esac
BASENAME="vectorcraft-$VERSION-linux-$ARCH"
if [[ "$FLATPAK_ID" != "$APP_ID" && "$VERSION" != *-nightly* ]]; then
BASENAME="vectorcraft-$VERSION-nightly-linux-$ARCH"
else
BASENAME="vectorcraft-$VERSION-linux-$ARCH"
fi
TARBALL="${TARBALL:-$DIST/$BASENAME.tar.gz}"
[[ -f "$TARBALL" ]] || { echo "error: $TARBALL not found (run packaging/linux/package.sh --formats tar first)" >&2; exit 1; }
for tool in flatpak flatpak-builder; do
@@ -52,29 +62,56 @@ rm -rf "$WORK"
mkdir -p "$WORK/stage"
tar -xzf "$TARBALL" -C "$WORK/stage" --strip-components=1
[[ -x "$WORK/stage/bin/vectorcraft" ]] || { echo "error: $TARBALL has no bin/vectorcraft" >&2; exit 1; }
cp "$HERE/flatpak/$APP_ID.bundle.yml" "$WORK/$APP_ID.yml"
if [[ "$FLATPAK_ID" != "$APP_ID" ]]; then
# The Nightly tar already carries the standard layout: `bin/vectorcraft` is the launcher and
# `bin/vectorcraft-bin` the GUI it starts. The sandbox's own HOME is the profile's base.
[[ -x "$WORK/stage/bin/vectorcraft-bin" ]] || { echo "error: $TARBALL is not a Nightly tar (no bin/vectorcraft-bin)" >&2; exit 1; }
sed -e "s|^Icon=$APP_ID$|Icon=$FLATPAK_ID|" \
-e "s|^Name=VectorCraft$|Name=VectorCraft Nightly|" \
-e 's|^StartupWMClass=.*|StartupWMClass=ai.storyteller.vectorcraft.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"
sed -e "s|<id>$APP_ID</id>|<id>$FLATPAK_ID</id>|g" \
-e "s|<name>VectorCraft</name>|<name>VectorCraft 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" \
"$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"
mv "$WORK/stage/share/mime/packages/$APP_ID.xml" "$WORK/stage/share/mime/packages/$FLATPAK_ID.xml"
rm -rf "$WORK/stage/share/icons/hicolor"
NIGHTLY_ICON="$ROOT/assets/app-icon/vectorcraft-nightly.png"
[[ -f "$NIGHTLY_ICON" ]] || NIGHTLY_ICON="$ROOT/assets/app-icon/hicolor/256x256/apps/$APP_ID.png"
install -Dm644 "$NIGHTLY_ICON" \
"$WORK/stage/share/icons/hicolor/256x256/apps/$FLATPAK_ID.png"
sed -e "s|ai\.storyteller\.vectorcraft|$FLATPAK_ID|g" \
-e 's|- install -Dm755 bin/vectorcraft /app/bin/vectorcraft|- install -Dm755 bin/vectorcraft-bin /app/libexec/vectorcraft-bin\n - install -Dm755 bin/vectorcraft /app/bin/vectorcraft|' \
"$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=vectorcraft-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=vectorcraft-cli "$FLATPAK_ID" --version
flatpak run --command=sh "$FLATPAK_ID" -c 'ls /app/share/applications /app/share/metainfo /app/share/mime/packages /app/share/icons/hicolor/*/apps'
fi
echo "==> done"
ls -lh "$OUT"
+8 -5
View File
@@ -3,7 +3,7 @@
# exports VERSION and NFPM_ARCH.
#
# nfpm package -f packaging/linux/nfpm.yaml -p deb -t dist/release/
name: vectorcraft
name: ${NFPM_NAME}
arch: ${NFPM_ARCH}
platform: linux
version: ${VERSION}
@@ -63,12 +63,15 @@ overrides:
- xdg-desktop-portal
contents:
- src: ${STAGE}/usr/bin/vectorcraft
dst: /usr/bin/vectorcraft
- src: ${STAGE}/usr/bin/${NFPM_BIN}
dst: /usr/bin/${NFPM_BIN}
file_info: { mode: 0755 }
- src: ${STAGE}/usr/bin/vectorcraft-cli
dst: /usr/bin/vectorcraft-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
+80
View File
@@ -0,0 +1,80 @@
#!/usr/bin/env bash
# Validate the staged Arch launcher without building or opening VectorCraft.
set -euo pipefail
HERE="$(cd "$(dirname "$0")" && pwd)"
work="$(mktemp -d)"
trap 'rm -rf "$work"' EXIT
stage="$work/source"
dst="$work/dist"
base=vectorcraft-0.0.1-nightly.1-linux-x86_64
mkdir -p "$stage/bin" "$dst" "$work/extract"
# A local argv/env recorder stands in for the compiled binaries. It never opens a UI. The shape is
# the one package.sh stages for the handoff: the GUI as `bin/vectorcraft-bin` and the launcher as
# `bin/vectorcraft`.
cat >"$stage/bin/vectorcraft-bin" <<'RECORDER'
#!/bin/sh
printf 'CONFIG=<%s>\n' "${VECTORCRAFT_CONFIG_DIR:-}"
for arg in "$@"; do
printf '<%s>\n' "$arg"
done
RECORDER
chmod 755 "$stage/bin/vectorcraft-bin"
cp "$stage/bin/vectorcraft-bin" "$stage/bin/vectorcraft-cli"
cp "$HERE/nightly-launch.sh" "$stage/bin/vectorcraft"
chmod 755 "$stage/bin/vectorcraft"
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"
# The standard Nightly layout: `bin/vectorcraft` is the launcher and `bin/.vectorcraft-nightly/
# vectorcraft-bin` the GUI it starts.
cmp "$HERE/nightly-launch.sh" "$bin/vectorcraft"
cmp "$stage/bin/vectorcraft-bin" "$bin/.vectorcraft-nightly/vectorcraft-bin"
[[ ! -e "$bin/vectorcraft-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/vectorcraft" "$bin/vectorcraft-nightly"
mv "$bin/vectorcraft-cli" "$bin/vectorcraft-nightly-cli"
[[ ! -e "$stage/bin/.vectorcraft-nightly" ]]
cmp "$HERE/nightly-launch.sh" "$bin/vectorcraft-nightly"
cmp "$stage/bin/vectorcraft-bin" "$bin/.vectorcraft-nightly/vectorcraft-bin"
cmp "$stage/bin/vectorcraft-cli" "$bin/vectorcraft-nightly-cli"
export HOME="$work/home with space"
unset XDG_DATA_HOME VECTORCRAFT_CONFIG_DIR
expect() {
expected="$1"
shift
actual=$(PATH="$bin:$PATH" vectorcraft-nightly "$@")
if [[ "$actual" != "$expected" ]]; then
printf 'expected:\n%s\nactual:\n%s\n' "$expected" "$actual" >&2
exit 1
fi
}
# The launcher hands the GUI its channel's profile (the Launcher's own protocol), and everything it
# was given becomes a file after `--`, even a name that looks like an option.
expect "$(printf 'CONFIG=<>\n<--launch-profile>\n<nightly-v1>\n<--profile-root>\n<%s>\n<-->\n' "$HOME/.local/share/vectorcraft-nightly")"
export XDG_DATA_HOME="$work/xdg with space"
expect "$(printf 'CONFIG=<>\n<--launch-profile>\n<nightly-v1>\n<--profile-root>\n<%s>\n<-->\n<%s>\n<%s>\n' \
"$XDG_DATA_HOME/vectorcraft-nightly" 'drawing with spaces.svg' '--other-name.svg')" \
'drawing with spaces.svg' '--other-name.svg'
# A version or help query reaches the GUI without a profile: it answers before any root exists.
expect "$(printf 'CONFIG=<>\n<--version>\n')" --version
expect "$(printf 'CONFIG=<>\n<-V>\n')" -V
expect "$(printf 'CONFIG=<>\n<--help>\n')" --help
# The Launcher's own invocation passes through untouched, and a caller-written delimiter is not doubled.
expect "$(printf 'CONFIG=<>\n<--launch-profile>\n<nightly-v1>\n<--profile-root>\n<%s>\n<--version>\n' "$work/launcher root")" \
--launch-profile nightly-v1 --profile-root "$work/launcher root" --version
expect "$(printf 'CONFIG=<>\n<--launch-profile>\n<nightly-v1>\n<--profile-root>\n<%s>\n<-->\n<%s>\n' \
"$XDG_DATA_HOME/vectorcraft-nightly" 'sample.svg')" -- sample.svg
# A VECTORCRAFT_CONFIG_DIR in the caller's environment is not turned into the profile: the launcher
# passes it through untouched, and the nightly build then refuses that variable.
unset XDG_DATA_HOME
VECTORCRAFT_CONFIG_DIR="$work/explicit with space" \
expect "$(printf 'CONFIG=<%s>\n<--launch-profile>\n<nightly-v1>\n<--profile-root>\n<%s>\n<-->\n<%s>\n' "$work/explicit with space" "$HOME/.local/share/vectorcraft-nightly" 'sample.svg')" sample.svg
echo "PASS: Arch Nightly handoff passes the nightly profile and preserves launch arguments"
+20
View File
@@ -0,0 +1,20 @@
#!/usr/bin/env bash
# Stage the VectorCraft 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/.vectorcraft-nightly"
# The GUI goes into the hidden folder; `bin/vectorcraft` below is the launcher that starts it.
mv "$stage/bin/vectorcraft-bin" "$stage/bin/.vectorcraft-nightly/vectorcraft-bin"
cp "$here/nightly-launch.sh" "$stage/bin/vectorcraft"
chmod 755 "$stage/bin/vectorcraft"
tar -C "$work" -czf "$destination/$basename.tar.gz" "$basename"
echo "wrote $destination/$basename.tar.gz"
+171
View File
@@ -0,0 +1,171 @@
#!/usr/bin/env python3
"""Synthetic launcher tests: every VectorCraft Nightly placement starts the GUI the flavor's way.
No build and no window: a recorder script stands in for the GUI, so the argv and environment the
launcher passes are read directly.
"""
import os
import subprocess
import sys
import tempfile
import unittest
from pathlib import Path
HERE = Path(__file__).resolve().parent
LAUNCHER = HERE / "nightly-launch.sh"
RECORDER = """#!/bin/sh
printf 'config=<%s>\n' "${VECTORCRAFT_CONFIG_DIR:-}"
for arg in "$@"; do
printf '<%s>\n' "$arg"
done
"""
# Where each format puts the launcher and the GUI beside it: the plain tar, the deb/rpm, the
# AppImage's AppRun, the Arch handoff and the Flatpak (see package.sh, nightly-arch-tar.sh and
# flatpak-bundle.sh).
PLACEMENTS = {
"tar": ("vectorcraft", "vectorcraft-bin"),
"deb-rpm": ("usr/bin/vectorcraft-nightly", "usr/lib/vectorcraft-nightly/vectorcraft-bin"),
"appimage": ("AppRun", "usr/bin/vectorcraft-bin"),
"arch": ("bin/vectorcraft", "bin/.vectorcraft-nightly/vectorcraft-bin"),
"flatpak": ("bin/vectorcraft", "libexec/vectorcraft-bin"),
}
class Launchers(unittest.TestCase):
def setUp(self):
self.scratch = tempfile.TemporaryDirectory()
self.addCleanup(self.scratch.cleanup)
self.root = Path(self.scratch.name).resolve()
self.home = self.root / "home with space"
self.home.mkdir()
self.env = {"HOME": str(self.home), "PATH": "/usr/bin:/bin"}
self.profile = f"{self.home}/.local/share/vectorcraft-nightly"
def place(self, name):
launcher_rel, gui_rel = PLACEMENTS[name]
launcher = self.root / name / launcher_rel
gui = self.root / name / gui_rel
gui.parent.mkdir(parents=True, exist_ok=True)
gui.write_text(RECORDER, encoding="utf-8")
gui.chmod(0o755)
launcher.parent.mkdir(parents=True, exist_ok=True)
launcher.write_bytes(LAUNCHER.read_bytes())
launcher.chmod(0o755)
return launcher, gui
def run_launcher(self, launcher, *args, env=None, extra_path=None, unset=()):
environment = dict(self.env, **(env or {}))
for name in unset:
environment.pop(name, None)
if extra_path:
environment["PATH"] = f"{extra_path}:{environment['PATH']}"
# Run from somewhere else entirely: the launcher resolves the GUI from its own location.
result = subprocess.run(
[str(launcher), *args],
cwd=str(self.root),
env=environment,
capture_output=True,
text=True,
timeout=30,
)
self.assertEqual(result.returncode, 0, f"{launcher.name} {args}: {result.stderr}")
return result.stdout.splitlines()
def expect(self, launcher, expected, *args, env=None, extra_path=None, unset=()):
lines = self.run_launcher(launcher, *args, env=env, extra_path=extra_path, unset=unset)
self.assertEqual(lines, expected, f"{launcher} {list(args)}")
def test_every_placement_starts_the_gui_with_the_channel_profile(self):
for name in PLACEMENTS:
with self.subTest(placement=name):
launcher, _ = self.place(name)
self.expect(
launcher,
["config=<>", "<--launch-profile>", "<nightly-v1>", "<--profile-root>", f"<{self.profile}>", "<-->"],
)
def test_files_keep_their_names_and_spaces_after_the_delimiter(self):
for name in PLACEMENTS:
with self.subTest(placement=name):
launcher, _ = self.place(name)
self.expect(
launcher,
["config=<>", "<--launch-profile>", "<nightly-v1>", "<--profile-root>", f"<{self.profile}>", "<-->", "<drawing with spaces.svg>", "<--other-name.svg>"],
"drawing with spaces.svg",
"--other-name.svg",
)
def test_the_profile_follows_xdg_data_home(self):
for name in PLACEMENTS:
with self.subTest(placement=name):
launcher, _ = self.place(name)
xdg = f"{self.root}/xdg with space"
self.expect(
launcher,
["config=<>", "<--launch-profile>", "<nightly-v1>", "<--profile-root>", f"<{xdg}/vectorcraft-nightly>", "<-->"],
env={"XDG_DATA_HOME": xdg},
)
def test_version_and_help_queries_reach_the_gui_unwrapped(self):
for name in PLACEMENTS:
for query in ("--version", "-V", "--help", "-h"):
with self.subTest(placement=name, query=query):
launcher, _ = self.place(name)
self.expect(launcher, ["config=<>", f"<{query}>"], query)
def test_a_version_or_help_query_answers_even_without_a_home(self):
# Nothing to build a default profile root from, but a query needs none.
for name in PLACEMENTS:
for query in ("--version", "--help"):
with self.subTest(placement=name, query=query):
launcher, _ = self.place(name)
self.expect(launcher, ["config=<>", f"<{query}>"], query, unset=("HOME", "XDG_DATA_HOME"))
def test_the_launchers_own_protocol_and_delimiter_pass_through(self):
for name in PLACEMENTS:
with self.subTest(placement=name):
launcher, _ = self.place(name)
root_arg = f"{self.root}/launcher root"
self.expect(
launcher,
["config=<>", "<--launch-profile>", "<nightly-v1>", "<--profile-root>", f"<{root_arg}>", "<--version>"],
"--launch-profile",
"nightly-v1",
"--profile-root",
root_arg,
"--version",
)
# A caller that already wrote the delimiter must not get a second one.
self.expect(
launcher,
["config=<>", "<--launch-profile>", "<nightly-v1>", "<--profile-root>", f"<{self.profile}>", "<-->", "<file.svg>"],
"--",
"file.svg",
)
def test_a_path_invocation_finds_the_gui_beside_it(self):
for name in PLACEMENTS:
with self.subTest(placement=name):
launcher, _ = self.place(name)
environment = dict(self.env, PATH=f"{launcher.parent}:/usr/bin:/bin")
result = subprocess.run([launcher.name], cwd=str(self.root), env=environment, capture_output=True, text=True, timeout=30)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(
result.stdout.splitlines(),
["config=<>", "<--launch-profile>", "<nightly-v1>", "<--profile-root>", f"<{self.profile}>", "<-->"],
)
def test_a_missing_gui_is_refused_rather_than_started_elsewhere(self):
for name in PLACEMENTS:
with self.subTest(placement=name):
launcher, gui = self.place(name)
gui.unlink()
result = subprocess.run([str(launcher)], cwd=str(self.root), env=self.env, capture_output=True, text=True, timeout=30)
self.assertEqual(result.returncode, 2, result.stderr)
self.assertIn("app binary is missing", result.stderr)
if __name__ == "__main__":
unittest.main()
+45
View File
@@ -0,0 +1,45 @@
#!/bin/sh
# The launcher every VectorCraft Nightly format starts: the same file in the plain tar (`vectorcraft`),
# the deb/rpm (`/usr/bin/vectorcraft-nightly`), the AppImage (`AppRun`), the Arch handoff
# (`bin/vectorcraft`) and the Flatpak (`/app/bin/vectorcraft`). It starts the GUI beside it
# (`<app>-bin`, the standard Nightly layout) in the nightly-v1 channel's own profile.
#
# An invocation that carries the Launcher's protocol, or a bare version or help query, goes straight
# to the GUI: it answers those before it validates a profile root, and it treats everything after
# `--` as a file. Everything else gets the channel's profile root and the `--` delimiter.
set -eu
case "$0" in
*/*) here="$(CDPATH='' cd -- "$(dirname -- "$0")" && pwd)" ;;
# Started from PATH: the program that ran is the one to look beside.
*) here="$(CDPATH='' cd -- "$(dirname -- "$(command -v -- "$0")")" && pwd)" ;;
esac
real_bin=
for candidate in \
"$here/vectorcraft-bin" \
"$here/usr/bin/vectorcraft-bin" \
"$here/.vectorcraft-nightly/vectorcraft-bin" \
"$here/../lib/vectorcraft-nightly/vectorcraft-bin" \
"$here/../libexec/vectorcraft-bin"; do
if [ -x "$candidate" ] && [ ! -d "$candidate" ]; then
real_bin="$candidate"
break
fi
done
[ -n "$real_bin" ] || {
echo 'VectorCraft Nightly: the app binary is missing beside this launcher' >&2
exit 2
}
case "${1:-}" in
# These branches need no profile root, so they answer even where HOME is unset.
--version | -V | --help | -h | --launch-profile) exec "$real_bin" "$@" ;;
esac
profile_root="${XDG_DATA_HOME:-${HOME:?HOME is required}/.local/share}/vectorcraft-nightly"
if [ "${1:-}" = "--" ]; then
# The caller supplied the file delimiter already: never send two.
shift
exec "$real_bin" --launch-profile nightly-v1 --profile-root "$profile_root" -- "$@"
fi
exec "$real_bin" --launch-profile nightly-v1 --profile-root "$profile_root" -- "$@"
+32
View File
@@ -0,0 +1,32 @@
#!/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; }
# shellcheck source=../nightly-common.sh
. "$(dirname "${BASH_SOURCE[0]}")/../nightly-common.sh"
nightly_init linux "$ARCH" x86_64-unknown-linux-gnu
OUTPUT="$DIST/vectorcraft-$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 standard Nightly layout: `<app>` is the launcher and `<app>-bin` the GUI it starts, so an
# unpacked tar is isolated like the packages and the shared smoke can query the entrypoint.
cp "$NIGHTLY_GUI" "$STAGE/vectorcraft-bin"
chmod 755 "$STAGE/vectorcraft-bin"
cp "$ROOT/packaging/linux/nightly-launch.sh" "$STAGE/vectorcraft"
chmod 755 "$STAGE/vectorcraft"
# The Nightly art, not stable's: with both channels open the two tars must not share an icon.
cp "$ROOT/assets/app-icon/vectorcraft-nightly.png" "$STAGE/vectorcraft.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"
+141 -10
View File
@@ -7,7 +7,7 @@
# $DIST/vectorcraft-<version>-linux-<arch>.rpm Fedora, openSUSE, RHEL, ...
# $DIST/vectorcraft-<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]
#
# Cross-compiling (release.yml's linux-riscv64 job): set CROSS_ARCH (riscv64), CROSS_TARGET (the Rust
# target), CROSS_COMPILE (the binutils prefix, for strip) and EMULATOR (e.g. qemu-riscv64, to
@@ -25,10 +25,16 @@ APP_ID=ai.storyteller.vectorcraft
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,19p' "$0"; exit 0 ;;
*) echo "unknown argument: $1" >&2; exit 2 ;;
esac
@@ -42,9 +48,24 @@ case "$ARCH" in
*) echo "unsupported architecture $ARCH" >&2; exit 2 ;;
esac
export VECTORCRAFT_MAINTAINER="${VECTORCRAFT_MAINTAINER:-VectorCraft maintainers <vectorcraft@storyteller.ai>}"
BASENAME="vectorcraft-$VERSION-linux-$ARCH"
IS_NIGHTLY=0
if [[ "${VECTORCRAFT_BUILD_CHANNEL:-}" == nightly-v1 || "$VERSION" == *-nightly* ]]; then
IS_NIGHTLY=1
export VECTORCRAFT_BUILD_CHANNEL=nightly-v1
export VECTORCRAFT_OVERRIDE_VERSION="$VERSION"
fi
if [[ "$IS_NIGHTLY" = 1 && "$VERSION" != *-nightly* ]]; then
BASENAME="vectorcraft-$VERSION-nightly-linux-$ARCH"
else
BASENAME="vectorcraft-$VERSION-linux-$ARCH"
fi
echo "==> VectorCraft $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 "==> VectorCraft $VERSION for Linux $ARCH ($FORMATS, channel=${VECTORCRAFT_BUILD_CHANNEL:-stable})"
if [[ "$SKIP_BUILD" = 0 ]]; then
if [[ -n "${CROSS_TARGET:-}" ]]; then
@@ -62,7 +83,18 @@ rm -rf "$WORK"
install -Dm755 "$BIN/vectorcraft" "$STAGE/usr/bin/vectorcraft"
install -Dm755 "$BIN/vectorcraft-cli" "$STAGE/usr/bin/vectorcraft-cli"
"${CROSS_COMPILE:-}strip" "$STAGE/usr/bin/vectorcraft" "$STAGE/usr/bin/vectorcraft-cli" 2>/dev/null || true
if [[ "$IS_NIGHTLY" = 1 ]]; then
# The standard Nightly layout, for every format this tree feeds (tar, deb/rpm, AppImage, Flatpak):
# `<app>` is the launcher and `<app>-bin` the GUI it starts in the channel's own profile.
mv "$STAGE/usr/bin/vectorcraft" "$STAGE/usr/bin/vectorcraft-bin"
install -Dm755 "$HERE/nightly-launch.sh" "$STAGE/usr/bin/vectorcraft"
fi
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.vectorcraft.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@/$VECTORCRAFT_BUILD_DATE/g" \
@@ -90,13 +122,82 @@ if has tar; then
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="vectorcraft"
export NFPM_BIN="vectorcraft"
export NFPM_CLI="vectorcraft-cli"
if [[ "$IS_NIGHTLY" = 1 ]]; then
NIGHTLY_DESK_ID="$APP_ID.nightly-v1"
export NFPM_NAME="vectorcraft-nightly"
export NFPM_BIN="vectorcraft-nightly"
export NFPM_CLI="vectorcraft-nightly-cli"
NFPM_STAGE="$WORK/nfpm-root"
rm -rf "$NFPM_STAGE"
cp -R "$STAGE" "$NFPM_STAGE"
install -Dm755 "$NFPM_STAGE/usr/bin/vectorcraft-bin" "$NFPM_STAGE/usr/lib/vectorcraft-nightly/vectorcraft-bin"
# The nightly is started the Launcher's way, with its own profile root: the same launcher every
# other format uses, which finds the GUI at ../lib/vectorcraft-nightly/vectorcraft-bin.
install -Dm755 "$HERE/nightly-launch.sh" "$NFPM_STAGE/usr/bin/$NFPM_BIN"
rm -f "$NFPM_STAGE/usr/bin/vectorcraft" "$NFPM_STAGE/usr/bin/vectorcraft-bin"
# The CLI is a separate program that keeps the environment override: it follows the same folder.
install -Dm755 "$NFPM_STAGE/usr/bin/vectorcraft-cli" "$NFPM_STAGE/usr/lib/vectorcraft-nightly/vectorcraft-cli"
cat >"$NFPM_STAGE/usr/bin/$NFPM_CLI" <<'CLI_WRAPPER'
#!/bin/sh
set -eu
if [ -z "${VECTORCRAFT_CONFIG_DIR+x}" ]; then
profile_base="${XDG_DATA_HOME:-${HOME:?HOME is required}/.local/share}"
export VECTORCRAFT_CONFIG_DIR="$profile_base/vectorcraft-nightly"
fi
exec /usr/lib/vectorcraft-nightly/vectorcraft-cli "$@"
CLI_WRAPPER
chmod 755 "$NFPM_STAGE/usr/bin/$NFPM_CLI"
mv "$NFPM_STAGE/usr/share/doc/vectorcraft" "$NFPM_STAGE/usr/share/doc/$NFPM_NAME"
sed -e "s#^Exec=vectorcraft\([[:space:]]\|$\)#Exec=$NFPM_BIN\1#" \
-e "s|^TryExec=vectorcraft$|TryExec=$NFPM_BIN|" \
-e "s|^Icon=$APP_ID$|Icon=$NIGHTLY_DESK_ID|" \
-e "s|^Name=VectorCraft$|Name=VectorCraft 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>VectorCraft</name>|<name>VectorCraft 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>vectorcraft</binary>|<binary>$NFPM_BIN</binary>|g" \
"$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"
rm -rf "$NFPM_STAGE/usr/share/icons/hicolor"
NIGHTLY_ICON="$ROOT/assets/app-icon/vectorcraft-nightly.png"
[[ -f "$NIGHTLY_ICON" ]] || NIGHTLY_ICON="$ROOT/assets/app-icon/hicolor/256x256/apps/$APP_ID.png"
install -Dm644 "$NIGHTLY_ICON" \
"$NFPM_STAGE/usr/share/icons/hicolor/256x256/apps/$NIGHTLY_DESK_ID.png"
# No stable command name stays in the tree: an installed nightly must not replace or conflict
# with the stable package's own /usr/bin/vectorcraft-cli.
rm -f "$NFPM_STAGE/usr/bin/vectorcraft-cli"
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;'
# 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
@@ -123,10 +224,30 @@ if has appimage; then
fi
APPDIR="$WORK/VectorCraft.AppDir"
cp -R "$STAGE" "$APPDIR"
ln -s usr/bin/vectorcraft "$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"
# A script, not a symlink: the same launcher every other format uses, which finds the GUI at
# usr/bin/vectorcraft-bin inside this AppDir.
install -Dm755 "$HERE/nightly-launch.sh" "$APPDIR/AppRun"
sed -e "s|^Icon=$APP_ID$|Icon=$APPIMAGE_ID|" \
-e "s|^Name=VectorCraft$|Name=VectorCraft 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"
rm -rf "$APPDIR/usr/share/icons/hicolor"
NIGHTLY_ICON="$ROOT/assets/app-icon/vectorcraft-nightly.png"
[[ -f "$NIGHTLY_ICON" ]] || NIGHTLY_ICON="$ROOT/assets/app-icon/hicolor/256x256/apps/$APP_ID.png"
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/vectorcraft "$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
TOOL="${APPIMAGETOOL:-$(command -v appimagetool || true)}"
if [[ -z "$TOOL" ]]; then
@@ -167,11 +288,21 @@ 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/vectorcraft}"
UPDATE_INFO="gh-releases-zsync|${REPO%%/*}|${REPO#*/}|latest|vectorcraft-*-linux-$ARCH.AppImage.zsync"
UPDATE_ARGS=()
if [[ "$IS_NIGHTLY" = 0 ]]; then
UPDATE_INFO="gh-releases-zsync|${REPO%%/*}|${REPO#*/}|latest|vectorcraft-*-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|vectorcraft-*-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"
+121
View File
@@ -0,0 +1,121 @@
# 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='VectorCraft Nightly.app'
MAC_NIGHTLY_ID='ai.storyteller.vectorcraft.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" =~ ^vectorcraft-(.+)-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
}
# The keychain this app's import-cert.sh made: a regular file inside this run's own work directory.
# Its name is the script's, not ours, and RUNNER_TEMP only decides where the folder is.
mac_nightly_keychain_is_ours() {
local keychain="$1" work="$2" file name
[[ "$keychain" == /* && -f "$keychain" && ! -L "$keychain" ]] || return 1
file="$(cd "$(dirname -- "$keychain")" && pwd)/$(basename -- "$keychain")" || return 1
[[ "$file" == "${work%/}/"* ]] || return 1
name="$(basename -- "$keychain")"
[[ "$name" =~ ^vectorcraft-signing([.][A-Za-z0-9]+)?[.]keychain-db$ ]]
}
# 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 VectorCraft
# 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")" == VectorCraft ]] || mac_nightly_die 'Contents/MacOS must hold only the VectorCraft GUI (no CLI)'
[[ -f "$app/Contents/MacOS/VectorCraft" && -x "$app/Contents/MacOS/VectorCraft" ]] || mac_nightly_die 'missing executable GUI'
[[ "$(lipo -archs "$app/Contents/MacOS/VectorCraft")" == arm64 ]] || mac_nightly_die 'the GUI must be thin arm64'
plist="$app/Contents/Info.plist"
for key in CFBundleIdentifier CFBundleExecutable VectorCraftVersion; 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" == VectorCraft ]] ;;
VectorCraftVersion) [[ "$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
}
+143
View File
@@ -0,0 +1,143 @@
#!/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/vectorcraft-<version>-macos-aarch64-nightly.zip \
# --output /abs/<dir>/vectorcraft-<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%/}/vectorcraft-nightly-sign.XXXXXX")"
KEYCHAIN="$WORK/vectorcraft-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. The
# keychain file is the app's to name: read it back and require it inside this run's directory.
imported="$(GITHUB_ENV='' RUNNER_TEMP="$WORK" DIST="$WORK/dist" bash "$HERE/import-cert.sh")"
IDENTITY="$(sed -n 's/^MACOS_SIGN_IDENTITY=//p' <<<"$imported")"
KEYCHAIN="$(sed -n 's/^MACOS_KEYCHAIN=//p' <<<"$imported")"
if [[ ! "$IDENTITY" =~ ^[0-9A-F]{40}$ ]] || ! mac_nightly_keychain_is_ours "$KEYCHAIN" "$WORK"; then
mac_nightly_die 'import-cert.sh did not import a signing identity into this run directory'
fi
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 "==> VectorCraft 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/VectorCraft"
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/vectorcraft-<version>-macos-aarch64-nightly.zip --expect signed [--team ID]
# nightly-verify.sh --input /abs/vectorcraft-<version>-macos-aarch64-nightly.zip --expect unsigned
#
# Both: the archive holds only the GUI-only Nightly bundle with the exact VectorCraftVersion, 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 `VectorCraft <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}}/vectorcraft-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/VectorCraft" "$@" 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" == "VectorCraft $VERSION (nightly-v1)" ]] || mac_nightly_die "the version query ($*) reports '$out', not VectorCraft $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): VectorCraft $VERSION (nightly-v1), plain and in the Launcher's profile form"
+53
View File
@@ -0,0 +1,53 @@
#!/usr/bin/env bash
# App-owned GUI-only Nightly for Apple silicon, compile step only (no signing material):
#
# $DIST/vectorcraft-<version>-macos-aarch64-nightly.zip VectorCraft Nightly.app, unsigned
#
# Usage: packaging/macos/nightly.sh --arch aarch64
#
# Required env (nightly-common.sh): VECTORCRAFT_BUILD_CHANNEL=nightly-v1, VECTORCRAFT_VERSION,
# VECTORCRAFT_BUILD_SHA, VECTORCRAFT_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)"
# shellcheck source=../nightly-common.sh
. "$HERE/../nightly-common.sh"
# shellcheck source=nightly-lib.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/vectorcraft-$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/VectorCraft"
chmod 755 "$APP/Contents/MacOS/VectorCraft"
cp "$ROOT/assets/app-icon/vectorcraft-nightly.icns" "$APP/Contents/Resources/vectorcraft-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 "$VECTORCRAFT_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.vectorcraft.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="VectorCraft Nightly",
CFBundleName="VectorCraft Nightly",
CFBundleIdentifier=IDENTIFIER,
CFBundleExecutable="VectorCraft",
CFBundleIconFile="vectorcraft-nightly",
CFBundleShortVersionString=match[1],
CFBundleVersion=match[1],
VectorCraftVersion=version,
VectorCraftBuildCommit=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()
+130
View File
@@ -0,0 +1,130 @@
#!/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("vector_nightly_plist", HERE / "nightly_plist.py")
POLICY = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(POLICY)
COMMIT = "a" * 40
VERSION = "0.24.1-nightly.20261124.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.vectorcraft.nightly")
self.assertEqual(rendered["CFBundleExecutable"], "VectorCraft")
self.assertEqual(rendered["CFBundleIconFile"], "vectorcraft-nightly")
self.assertEqual(rendered["VectorCraftVersion"], VERSION)
self.assertEqual(rendered["VectorCraftBuildCommit"], COMMIT)
self.assertTrue(VERSION.startswith(rendered["CFBundleVersion"] + "-nightly."))
# The keys this app's own template carries survive, with their stable values.
for key in ("LSMinimumSystemVersion", "CFBundleLocalizations", "NSHighResolutionCapable", "NSHumanReadableCopyright", "LSApplicationCategoryType"):
self.assertIn(key, stable)
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.24.1", COMMIT), (VERSION, "b" * 40), (VERSION, "not-a-commit"), (VERSION.replace("20261124", "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["VectorCraftVersion"], VERSION)
self.assertEqual(result["VectorCraftBuildCommit"], 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 and Linux allow unlinking an open file: exercise the real cleanup
# ownership check rather than 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()
target = self.root / "external-sentinel"
target.write_bytes(sentinel)
self.output.symlink_to(target)
# The owned-root writer refuses a symlinked destination before opening it.
with self.assertRaises(ValueError):
POLICY.write_plist(self.template, self.output, VERSION, COMMIT)
self.assertEqual(target.read_bytes(), sentinel)
self.assertEqual(self.template.read_bytes(), self.original)
if __name__ == "__main__":
unittest.main()
+448
View File
@@ -0,0 +1,448 @@
#!/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("vector_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"vectorcraft-{VERSION}-macos-aarch64-nightly.zip"
APP = "VectorCraft Nightly.app"
TEAM = "ABCDE12345"
IDENTITY = "0123456789ABCDEF0123456789ABCDEF01234567"
# Every fixture credential carries the same value, so no line here reads like a real one.
FIXTURE = "generated-fixture"
SECRETS = {
"APPLE_CERTIFICATE": base64.b64encode(b"generated fixture, not a certificate").decode(),
"APPLE_CERTIFICATE_PASSWORD": FIXTURE,
"KEYCHAIN_PASSWORD": FIXTURE,
"APPLE_ID": "fixture@example.invalid",
"APPLE_PASSWORD": 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.vectorcraft.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/VectorCraft"
exe.write_text(gui or f"#!/bin/sh\ntouch {self.ran}\necho 'VectorCraft {version} (nightly-v1)'\n")
exe.chmod(0o755)
(app / "Contents/Resources/vectorcraft-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.vectorcraft.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"vectorcraft-0.23.1-macos-aarch64.zip", f"vectorcraft-{VERSION}-macos-universal-nightly.zip",
f"vectorcraft-{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=vectorcraft-1234\nSignature=adhoc\nTeamIdentifier=not set\n",
DETAILS.replace("ai.storyteller.vectorcraft.nightly", "ai.storyteller.vectorcraft"),
DETAILS.replace("ai.storyteller.vectorcraft.nightly", "aiXstorytellerXvectorcraftXnightly")):
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_keychain_must_be_the_one_this_run_made_inside_its_work_directory(self):
with tempfile.TemporaryDirectory() as work, tempfile.TemporaryDirectory() as elsewhere:
ours = Path(work) / "vectorcraft-signing.keychain-db"
ours.write_bytes(b"generated keychain")
other_app = Path(work) / "another-app-signing.keychain-db"
other_app.write_bytes(b"generated keychain")
outside = Path(elsewhere) / "vectorcraft-signing.keychain-db"
outside.write_bytes(b"generated keychain")
link = Path(work) / "vectorcraft-signing.link.keychain-db"
link.symlink_to(ours)
directory = Path(work) / "vectorcraft-signing.dir.keychain-db"
directory.mkdir()
self.assertEqual(lib("mac_nightly_keychain_is_ours", ours, work)[0], 0)
# Another run's work directory, another app's name, a file outside, a link and a
# directory are each refused.
self.assertNotEqual(lib("mac_nightly_keychain_is_ours", ours, elsewhere)[0], 0, "judged against another work directory")
self.assertNotEqual(lib("mac_nightly_keychain_is_ours", other_app, work)[0], 0, "another app's keychain")
self.assertNotEqual(lib("mac_nightly_keychain_is_ours", outside, work)[0], 0, "outside the work directory")
self.assertNotEqual(lib("mac_nightly_keychain_is_ours", link, work)[0], 0, "a link")
self.assertNotEqual(lib("mac_nightly_keychain_is_ours", directory, work)[0], 0, "a directory")
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], ["VectorCraft", 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/VectorCraft").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/vectorcraft-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("/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 'VectorCraft {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 'VectorCraft 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 'VectorCraft {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"},
VECTORCRAFT_BUILD_CHANNEL="nightly-v1", VECTORCRAFT_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()
+248
View File
@@ -0,0 +1,248 @@
#!/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("vector_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"
# The Linux nightly helper's allowlist: the GUI, its icon and the app's notices.
# The standard Nightly layout: `vectorcraft` is the launcher and `vectorcraft-bin` the GUI.
self.required = {"vectorcraft", "vectorcraft-bin", "vectorcraft.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 / "vectorcraft").chmod(0o755)
(self.stage / "vectorcraft-bin").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("vectorcraft").read(), (self.stage / "vectorcraft").read_bytes())
self.assertEqual(archive.getmember("vectorcraft").mode & 0o777, 0o755)
# The entrypoint is the launcher; the GUI it starts is the executable member beside it.
self.assertEqual(archive.getmember("vectorcraft").mode & 0o777, 0o755)
self.assertEqual(archive.getmember("vectorcraft-bin").mode & 0o777, 0o755)
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 ["vectorcraft-cli", "portable.txt", "vectorcraft.desktop", "vectorcraft-nightly", "vectorcraft-nightly.png"]:
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 / "vectorcraft.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 / "vectorcraft.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")
first, second = self.stage / "OFL-Font.txt", self.stage / "OFL-font.txt"
if first.samefile(second):
# This volume ignores case, so the two names are one notice: there is no collision to
# refuse, and the archive carries that one.
ARCHIVE.linux_archive(self.stage, self.output)
with tarfile.open(self.output) as archive:
names = [member.name for member in archive]
self.assertEqual([name for name in names if name.lower() == "ofl-font.txt"], ["OFL-font.txt"])
return
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=30,
)
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()
+132
View File
@@ -0,0 +1,132 @@
#!/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", "ASSETS.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 {"vectorcraft", "vectorcraft-bin", "vectorcraft.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())
# The standard Nightly layout: `<app>` is the launcher script and `<app>-bin` the GUI it starts,
# which the shared smoke queries through the entrypoint.
required = {"vectorcraft", "vectorcraft-bin", "vectorcraft.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]))
+95
View File
@@ -0,0 +1,95 @@
# 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
[[ "${VECTORCRAFT_BUILD_CHANNEL:-}" == nightly-v1 ]] || nightly_die 'VECTORCRAFT_BUILD_CHANNEL must be nightly-v1'
[[ "${VECTORCRAFT_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'
[[ "${VECTORCRAFT_BUILD_SHA:-}" =~ ^[0-9a-f]{40}$ ]] || nightly_die 'an exact source commit is required'
[[ "${VECTORCRAFT_VERSION##*.g}" == "${VECTORCRAFT_BUILD_SHA:0:12}" ]] || nightly_die 'version/source commit mismatch'
[[ "${VECTORCRAFT_BUILD_DATE:-}" =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}$ ]] || nightly_die 'the original run-created UTC date is required'
date_digits="${VECTORCRAFT_VERSION#*-nightly.}"
date_digits="${date_digits%%.*}"
[[ "${VECTORCRAFT_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)" == "$VECTORCRAFT_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.
# shellcheck source=env.sh
. "$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
(cd "$ROOT" && VECTORCRAFT_OVERRIDE_VERSION="$VERSION" cargo build --release --locked -p vectorcraft --target "$NIGHTLY_RUST_TARGET")
NIGHTLY_GUI="$CARGO_TARGET_DIR/$NIGHTLY_RUST_TARGET/release/vectorcraft"
[[ -f "$NIGHTLY_GUI" && ! -L "$NIGHTLY_GUI" ]] || nightly_die 'the owned GUI build did not produce a regular executable'
[[ "$(git -C "$ROOT" rev-parse HEAD)" == "$VECTORCRAFT_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'
# Exactly what the flavor prints for a nightly build (apps/vectorcraft: build_flavor::version):
# a stable build prints "vectorcraft <cargo version>", which is never the prepared identity.
[[ "$actual" == "VectorCraft $VERSION (nightly-v1)" ]] || nightly_die "the built version/flavor is not the prepared identity (got: $actual)"
[[ "$(git -C "$ROOT" rev-parse HEAD)" == "$VECTORCRAFT_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"
cp "$ROOT/$required" "$destination/"
done
copy_font_licences "$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"
}
+227
View File
@@ -0,0 +1,227 @@
#!/usr/bin/env python3
"""Render VectorCraft's Nightly art from the committed app icon.
The field (the VectorCraft colour) goes a few shades deeper; the figure (ink and paper) is left
exactly as it is. The palette keeps the figure neutral (r = g = b), so the field's contribution to
each pixel is solved exactly instead of guessed per channel:
w = ((r-g)(Br-Bg) + (g-b)(Bg-Bb)) / |(Br-Bg, Bg-Bb)|^2
out = pixel + w * (B' - B)
Writes assets/app-icon/vectorcraft-nightly-1024.png (the padded macOS master, Apple's 824/1024 tile),
vectorcraft-nightly.png (the full tile), vectorcraft-nightly.ico and vectorcraft-nightly.icns.
Needs ffmpeg for scaling. Run from any folder: python3 packaging/nightly-icons.py
"""
import os
from pathlib import Path
import struct
import subprocess
import sys
import zlib
ROOT = Path(__file__).resolve().parents[1]
ART = ROOT / "assets/app-icon"
FIELD = (0xE8, 0x57, 0x3F)
NIGHTLY_FIELD = (0xA8, 0x3A, 0x24)
# Apple's margin: the tile is 824 of the 1024 canvas, centred.
MAC_TILE = 824
MAC_CANVAS = 1024
def read_png(path):
"""(width, height, RGBA bytes) of an 8-bit, non-interlaced PNG."""
data = path.read_bytes()
if data[:8] != b"\x89PNG\r\n\x1a\n":
raise ValueError(f"{path} is not a PNG")
at, chunks, width, height, depth, colour, _, interlace = 8, [], 0, 0, 8, 6, 0, 0
while at < len(data):
(length,) = struct.unpack(">I", data[at:at + 4])
kind = data[at + 4:at + 8]
body = data[at + 8:at + 8 + length]
at += 12 + length
if kind == b"IHDR":
width, height, depth, colour, _, _, interlace = struct.unpack(">IIBBBBB", body)
elif kind == b"IDAT":
chunks.append(body)
elif kind == b"IEND":
break
if depth != 8 or colour != 6 or interlace != 0:
raise ValueError(f"{path}: expected an 8-bit RGBA non-interlaced PNG")
raw = zlib.decompress(b"".join(chunks))
stride = width * 4
out = bytearray(height * stride)
previous = bytearray(stride)
at = 0
for row in range(height):
filter_kind = raw[at]
at += 1
line = bytearray(raw[at:at + stride])
at += stride
if filter_kind == 1:
for i in range(4, stride):
line[i] = (line[i] + line[i - 4]) & 0xFF
elif filter_kind == 2:
for i in range(stride):
line[i] = (line[i] + previous[i]) & 0xFF
elif filter_kind == 3:
for i in range(stride):
left = line[i - 4] if i >= 4 else 0
line[i] = (line[i] + ((left + previous[i]) >> 1)) & 0xFF
elif filter_kind == 4:
for i in range(stride):
a = line[i - 4] if i >= 4 else 0
b = previous[i]
c = previous[i - 4] if i >= 4 else 0
p = a + b - c
pa, pb, pc = abs(p - a), abs(p - b), abs(p - c)
predictor = a if pa <= pb and pa <= pc else (b if pb <= pc else c)
line[i] = (line[i] + predictor) & 0xFF
elif filter_kind != 0:
raise ValueError(f"{path}: unsupported PNG filter {filter_kind}")
out[row * stride:(row + 1) * stride] = line
previous = line
return width, height, bytes(out)
def write_png(path, width, height, rgba):
stride = width * 4
raw = bytearray()
for row in range(height):
raw.append(0)
raw += rgba[row * stride:(row + 1) * stride]
def chunk(kind, body):
return struct.pack(">I", len(body)) + kind + body + struct.pack(">I", zlib.crc32(kind + body) & 0xFFFFFFFF)
header = struct.pack(">IIBBBBB", width, height, 8, 6, 0, 0, 0)
path.write_bytes(b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", header) + chunk(b"IDAT", zlib.compress(bytes(raw), 9)) + chunk(b"IEND", b""))
def deepen(width, height, rgba):
"""The field a deeper shade, the figure (ink and paper) untouched, pixel for pixel."""
(br, bg, bb), (nr, ng, nb) = FIELD, NIGHTLY_FIELD
dr, dg = br - bg, bg - bb
norm = dr * dr + dg * dg
out = bytearray(len(rgba))
for i in range(0, len(rgba), 4):
r, g, b, a = rgba[i], rgba[i + 1], rgba[i + 2], rgba[i + 3]
if a == 0:
out[i:i + 4] = bytes((r, g, b, 0))
continue
w = ((r - g) * dr + (g - b) * dg) / norm
if w <= 0.0:
out[i:i + 4] = bytes((r, g, b, a))
continue
w = min(w, 1.0)
out[i:i + 4] = bytes((
min(255, max(0, round(r + w * (nr - br)))),
min(255, max(0, round(g + w * (ng - bg)))),
min(255, max(0, round(b + w * (nb - bb)))),
a,
))
return bytes(out)
def ffmpeg(*args):
result = subprocess.run(["ffmpeg", "-hide_banner", "-loglevel", "error", "-y", *map(str, args)], capture_output=True)
if result.returncode != 0:
raise SystemExit(f"ffmpeg failed: {result.stderr.decode(errors='replace')}")
def scaled(size, source, out):
ffmpeg("-i", source, "-vf", f"scale={size}:{size}:flags=lanczos", out)
def padded_master(tile_1024, out):
"""Apple's master: the 1024 tile at 824 px, centred on a transparent 1024 canvas (no upscale)."""
work = ART / ".nightly-work"
work.mkdir(exist_ok=True)
try:
tile = work / "tile-824.png"
scaled(MAC_TILE, tile_1024, tile)
ffmpeg("-f", "lavfi", "-i", f"color=c=black@0.0:s={MAC_CANVAS}x{MAC_CANVAS}:d=1,format=rgba",
"-i", tile, "-filter_complex", "[0][1]overlay=(W-w)/2:(H-h)/2:format=auto", "-frames:v", "1", out)
finally:
for leftover in work.iterdir():
leftover.unlink()
work.rmdir()
def icns(master, out):
"""A PNG-based .icns: every frame a native render of the master."""
frames = {16: b"icp4", 32: b"icp5", 64: b"icp6", 128: b"ic07", 256: b"ic08", 512: b"ic09", 1024: b"ic10"}
work = ART / ".nightly-work"
work.mkdir(exist_ok=True)
body = bytearray()
try:
for size, kind in frames.items():
frame = work / f"icns-{size}.png"
scaled(size, master, frame)
data = frame.read_bytes()
body += kind + struct.pack(">I", len(data) + 8) + data
finally:
for leftover in work.iterdir():
leftover.unlink()
work.rmdir()
out.write_bytes(b"icns" + struct.pack(">I", len(body) + 8) + bytes(body))
def ico(tile_1024, out):
"""Windows frames: 32bpp BGRA DIB with AND masks up to 128, a PNG frame only for 256."""
work = ART / ".nightly-work"
work.mkdir(exist_ok=True)
images = []
try:
for size in (16, 24, 32, 48, 64, 128, 256):
frame = work / f"ico-{size}.png"
scaled(size, tile_1024, frame)
if size == 256:
images.append((size, frame.read_bytes()))
continue
raw = work / f"ico-{size}.bgra"
ffmpeg("-i", frame, "-f", "rawvideo", "-pix_fmt", "bgra", raw)
pixels = raw.read_bytes()
mask_row = ((size + 31) // 32) * 4
header = struct.pack("<IiiHHIIiiII", 40, size, size * 2, 1, 32, 0, size * size * 4, 0, 0, 0, 0)
mask = bytearray()
for row in range(size - 1, -1, -1): # bottom-up, like the colour rows
bits = bytearray(mask_row)
for column in range(size):
alpha = pixels[(row * size + column) * 4 + 3]
if alpha == 0:
bits[column // 8] |= 0x80 >> (column % 8)
mask += bits
colour = bytearray()
for row in range(size - 1, -1, -1):
colour += pixels[row * size * 4:(row + 1) * size * 4]
images.append((size, header + bytes(colour) + bytes(mask)))
finally:
for leftover in work.iterdir():
leftover.unlink()
work.rmdir()
header = struct.pack("<HHH", 0, 1, len(images))
offset = 6 + 16 * len(images)
entries, bodies = bytearray(), bytearray()
for size, data in images:
entries += struct.pack("<BBBBHHII", size % 256, size % 256, 0, 0, 1, 32, len(data), offset)
bodies += data
offset += len(data)
out.write_bytes(header + bytes(entries) + bytes(bodies))
def main() -> int:
width, height, rgba = read_png(ART / "vectorcraft-1024.png")
if (width, height) != (1024, 1024):
raise SystemExit("the mastered tile must be 1024 square")
nightly = deepen(width, height, rgba)
tile = ART / "vectorcraft-nightly.png"
write_png(tile, width, height, nightly)
master = ART / "vectorcraft-nightly-1024.png"
padded_master(tile, master)
icns(master, ART / "vectorcraft-nightly.icns")
ico(tile, ART / "vectorcraft-nightly.ico")
for name in ("vectorcraft-nightly.png", "vectorcraft-nightly-1024.png", "vectorcraft-nightly.ico", "vectorcraft-nightly.icns"):
print(f"{name}: {(ART / name).stat().st_size} bytes")
return 0
if __name__ == "__main__":
sys.exit(main())
+430
View File
@@ -0,0 +1,430 @@
#!/usr/bin/env python3
"""Local regression checks for VectorCraft nightly workflow and signing-policy contracts."""
import copy
import json
from pathlib import Path
import re
import unittest
ROOT = Path(__file__).resolve().parents[1]
INSTALLED_POLICY = ROOT / ".github/nightly-signing-policy.json"
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"),
}
# 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 assert_nightly_serialization(source):
"""Fail closed unless this app's plain root concurrency block retains its contract."""
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): (.+)", line)
if row is None or row[1] in values:
raise ValueError("malformed or duplicate nightly concurrency entry")
# A trailing " #..." is a comment; any other '#' is not a value this contract has.
value, _, _comment = row[2].partition(" #")
if "#" in value:
raise ValueError("malformed nightly concurrency entry")
values[row[1]] = value.rstrip()
if values != {"group": "vectorcraft-nightly-release", "cancel-in-progress": "false"}:
raise ValueError("nightly serialization must use its stable group and no cancellation")
def literal_off(condition):
expression = " ".join(condition.split())
if expression.startswith("${{") and expression.endswith("}}"):
expression = expression[3:-2].strip()
if expression == "false":
return True
if not expression.startswith("false && "):
return False
expression = re.sub(r"'(?:''|[^'])*'", "''", expression)
depth = 0
for token in re.findall(r"\(|\)|\|\|", expression):
if token == "(":
depth += 1
elif token == ")":
depth -= 1
if depth < 0:
return False
elif depth == 0:
return False
return depth == 0
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 producer_platforms(source):
"""Read the one producer job's literal platform list; a narrow source guard, not YAML."""
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
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]
class TrustedSourcePreparation(unittest.TestCase):
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_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 = NightlyEnabledCallers.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_dormancy_guard_rejects_activation_and_top_level_or(self):
for condition in ("true", "vars.ENABLE_NIGHTLY", "false || true", "false && true || true",
"false && (true || true", "false && true) || true"):
with self.subTest(condition=condition):
self.assertFalse(literal_off(condition))
self.assertTrue(literal_off("${{ false }}"))
self.assertTrue(literal_off("false && (github.event_name == 'schedule' || github.event_name == 'workflow_dispatch')"))
def test_no_nightly_schedule_is_registered(self):
for name, event in (("nightly.yml", "workflow_dispatch"),
("nightly-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: false\n queue: max"),
("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: vectorcraft-nightly-release", "group: ${{ github.run_id }}"),
("group: vectorcraft-nightly-release", "group: release-${{ github.ref }}"),
("concurrency:\n", "concurrency: ${{ github.run_id }}\n"),
("concurrency:\n", " concurrency:\n"),
):
with self.subTest(change=new), self.assertRaises(ValueError):
assert_nightly_serialization(source.replace(old, new))
def test_no_cache_actions_or_cache_setup_options_in_app_trusted_closure(self):
for name in ("nightly.yml", "nightly-sign.yml"):
source = (ROOT / ".github/workflows" / name).read_text()
executable = "\n".join(line for line in source.splitlines()
if not line.lstrip().startswith("#"))
with self.subTest(workflow=name):
self.assertNotRegex(executable, r"(?im)^\s*(?:-\s*)?uses:\s*[^\n]*cache")
self.assertNotRegex(executable, r"(?im)^\s*[^\s:#]*cache[^\s:#]*:")
self.assertNotRegex(executable, r"(?im)^\s*(?:environment|secrets):")
self.assertNotIn("secrets.", executable)
class NightlyTrustAnchors(unittest.TestCase):
"""The public stable identities each platform's signed nightly must carry (all three platforms)."""
def setUp(self):
self.policy = json.loads(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) <= 1024 and not set(subject) & {"\r", "\n", "\0"})
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 NightlyEnabledCallers(unittest.TestCase):
"""Producer and signer run only in their exact context, for the reviewed manual actor."""
GUARDS = {
"nightly.yml": "github.repository == 'storytold/vectorcraft' && github.ref == 'refs/heads/main' && "
"github.ref_type == 'branch' && (github.event_name == 'schedule' || "
"github.event_name == 'workflow_dispatch')",
"nightly-sign.yml": "github.repository == 'storytold/vectorcraft' && 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_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/vectorcraft")
self.assertEqual(self.policy["release_branch"], "release")
self.assertIs(type(self.policy["repository_id"]), int)
self.assertGreater(self.policy["repository_id"], 0)
producer_id = self.policy["producer_workflow_id"]
if producer_id is not None:
self.assertIs(type(producer_id), int)
self.assertGreater(producer_id, 0)
self.assertNotEqual(producer_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/vectorcraft", "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"}
for cond in sonar["accepted_conditions"]:
self.assertIn(accepted[cond["metric"]], 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}$")
if __name__ == "__main__":
unittest.main(verbosity=2)
+26
View File
@@ -0,0 +1,26 @@
#!/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 (
("vector_archive_suite", "nightly-archive-tests.py"),
("vector_launcher_suite", "linux/nightly-launch-tests.py"),
("vector_plist_suite", "macos/nightly_plist_tests.py"),
("vector_release_dispatch_suite", "nightly-release-tests.py"),
("vector_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)
@@ -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.24.1-nightly.20261124.17.1.gabcdef012345' 'x64'
Assert ($spec.Archive -eq 'vectorcraft-0.24.1-nightly.20261124.17.1.gabcdef012345-windows-x86_64-nightly.zip') 'wrong nightly artifact name'
Assert ($spec.Executables.Count -eq 1 -and $spec.Executables[0] -eq 'vectorcraft.exe') 'nightly must not ship the unqualified CLI'
Assert ($spec.AppId -eq 'ai.storyteller.vectorcraft.nightly-v1') 'nightly identity is not distinct'
foreach ($arch in @('x86', 'arm64')) {
$refused = $false
try { Get-NightlyArchiveSpec '0.24.1' $arch | Out-Null } catch { $refused = $true }
Assert $refused 'unsupported target was accepted'
}
foreach ($bad in @('', '0.24.1', '../other', '0.24.1/elsewhere')) {
$refused = $false
try { Get-NightlyArchiveSpec $bad 'x64' | Out-Null } catch { $refused = $true }
Assert $refused 'unsafe artifact version was accepted'
}
Assert-NightlyFlavor 'VectorCraft Nightly' 'VectorCraft 0.24.1-nightly.20261124.17.1.gabcdef012345 (nightly-v1)' '0.24.1-nightly.20261124.17.1.gabcdef012345'
foreach ($pair in @(@('VectorCraft', 'VectorCraft 0.24.1 (nightly-v1)'), @('VectorCraft Nightly', 'VectorCraft 0.24.1'))) {
$refused = $false
try { Assert-NightlyFlavor $pair[0] $pair[1] '0.24.1-nightly.20261124.17.1.gabcdef012345' } catch { $refused = $true }
Assert $refused 'stable or mismatched build flavor was accepted'
}
$sha = 'abcdef0123456789abcdef0123456789abcdef01'
$good = '0.24.1-nightly.20261124.17.1.gabcdef012345'
Assert-NightlySource $good $sha '2026-11-24' $sha ''
$cases = @(
@('missing commit', $good, '', '2026-11-24', $sha, ''),
@('short commit', $good, 'abcdef012345', '2026-11-24', $sha, ''),
@('uppercase commit', $good, $sha.ToUpper(), '2026-11-24', $sha.ToUpper(), ''),
@('version names another commit', '0.24.1-nightly.20261124.17.1.g000000000000', $sha, '2026-11-24', $sha, ''),
@('missing date', $good, $sha, '', $sha, ''),
@('date differs from version', $good, $sha, '2026-11-25', $sha, ''),
@('other commit checked out', $good, $sha, '2026-11-24', ('0' * 40), ''),
@('dirty tree', $good, $sha, '2026-11-24', $sha, ' M apps/vectorcraft/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', 'ASSETS.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', 'vectorcraft-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.24.1-nightly.20261124.17.1.g' + $head.Substring(0, 12)
Assert-NightlySource $version $head '2026-11-24' $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-24' $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,93 @@
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
# The producer checks the prepared identity against the checked-out commit and the original run's
# date (`nightly.ps1` Assert-NightlySource) before it reaches Cargo, so the fixture names both. A
# made-up commit like `aaaa…` fails that check first, and the boundary case never runs.
$repo = (Resolve-Path (Join-Path $PackagingRoot '..\..')).Path
$head = "$(git -C $repo rev-parse HEAD)".Trim()
if ($LASTEXITCODE -ne 0 -or $head -cnotmatch '^[0-9a-f]{40}$') { throw 'the signing suite needs the checked-out commit' }
$stamp = '20261124'
$date = "$($stamp.Substring(0, 4))-$($stamp.Substring(4, 2))-$($stamp.Substring(6, 2))"
$version = "0.24.1-nightly.$stamp.12345.1.g$($head.Substring(0, 12))"
$env:VECTORCRAFT_VERSION = $version
$env:VECTORCRAFT_BUILD_SHA = $head
$env:VECTORCRAFT_BUILD_DATE = $date
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
}
+133
View File
@@ -0,0 +1,133 @@
<# 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 = "vectorcraft-$Version-windows-x86_64-nightly.zip"
UnsignedArchive = "vectorcraft-$Version-windows-x86_64-nightly.unsigned.zip"
Executables = @('vectorcraft.exe')
Channel = 'nightly-v1'
AppId = 'ai.storyteller.vectorcraft.nightly-v1'
}
}
# The same source identity the shell helpers enforce (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 (VECTORCRAFT_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 (VECTORCRAFT_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 'VectorCraft Nightly' -or $VersionOutput -cne "VectorCraft $ExpectedVersion (nightly-v1)") {
throw 'the executable is not the compiled nightly-v1 flavor'
}
}
function Copy-NightlyNotices([string] $RepositoryRoot, [string] $FontRepository, [string] $Destination) {
# ASSETS.md is the asset manifest ATTRIBUTION.md points at, so it ships beside it.
foreach ($name in 'README.md', 'LICENSE', 'LICENSE-MIT', 'LICENSE-APACHE', 'NOTICE', 'ATTRIBUTION.md', 'ASSETS.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:VECTORCRAFT_VERSION -or $Version -cne $env:VECTORCRAFT_VERSION) { throw 'nightly-v1 requires explicit VECTORCRAFT_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:VECTORCRAFT_BUILD_SHA $env:VECTORCRAFT_BUILD_DATE $Source.Head $Source.Status
$oldChannel = $env:VECTORCRAFT_BUILD_CHANNEL
$oldVersionOverride = $env:VECTORCRAFT_OVERRIDE_VERSION
try {
$env:VECTORCRAFT_BUILD_CHANNEL = 'nightly-v1'
$env:VECTORCRAFT_OVERRIDE_VERSION = $Version
$env:VECTORCRAFT_REQUIRE_WINRES = '1'
$env:CARGO_TARGET_X86_64_PC_WINDOWS_MSVC_RUSTFLAGS = '-C target-feature=+crt-static'
cargo build --release --locked -p vectorcraft --target $Target --target-dir $TargetDir
if ($LASTEXITCODE -ne 0) { throw "nightly cargo build failed: $LASTEXITCODE" }
} finally {
$env:VECTORCRAFT_BUILD_CHANNEL = $oldChannel
$env:VECTORCRAFT_OVERRIDE_VERSION = $oldVersionOverride
}
$Source = Get-NightlySourceState $Root
try { Assert-NightlySource $Version $env:VECTORCRAFT_BUILD_SHA $env:VECTORCRAFT_BUILD_DATE $Source.Head $Source.Status }
catch { throw "source changed during the build: $_" }
$Exe = Join-Path $TargetDir "$Target\release\vectorcraft.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 'VectorCraft 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 'vectorcraft.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 ('vectorcraft.exe' -notin $Names -or 'vectorcraft-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)"
+28 -3
View File
@@ -22,9 +22,12 @@
#>
param(
[ValidateSet('x64', 'x86', 'arm64')] [string] $Arch = 'x64',
[switch] $SkipBuild
[switch] $SkipBuild,
[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) {
@@ -51,12 +54,22 @@ $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:VECTORCRAFT_BUILD_SHA) { $env:VECTORCRAFT_BUILD_SHA = (git -C $Root rev-parse HEAD 2>$null) }
if (-not $env:VECTORCRAFT_BUILD_DATE) { $env:VECTORCRAFT_BUILD_DATE = (Get-Date).ToUniversalTime().ToString('yyyy-MM-dd') }
# A nightly requires the prepared commit and the original run date explicitly; nightly.ps1 checks both.
if (-not $Nightly) {
if (-not $env:VECTORCRAFT_BUILD_SHA) { $env:VECTORCRAFT_BUILD_SHA = (git -C $Root rev-parse HEAD 2>$null) }
if (-not $env:VECTORCRAFT_BUILD_DATE) { $env:VECTORCRAFT_BUILD_DATE = (Get-Date).ToUniversalTime().ToString('yyyy-MM-dd') }
}
Write-Output "VectorCraft $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 built from the stable channel, whatever the caller's environment says.
$env:VECTORCRAFT_BUILD_CHANNEL = 'stable'
# Static CRT: no VC++ redistributable needed. Scoped to the target so host build scripts and
# proc-macros are unaffected.
$flagVar = 'CARGO_TARGET_' + ($Target.ToUpper() -replace '-', '_') + '_RUSTFLAGS'
@@ -68,6 +81,18 @@ if (-not $SkipBuild) {
$Bin = Join-Path $TargetDir "$Target\release"
# A nightly executable can never be packaged as the stable app: its identity, its updates and its
# data folder are the nightly ones, and the MSI would install it over the stable installation.
$productName = (Get-Item -LiteralPath (Join-Path $Bin 'vectorcraft.exe')).VersionInfo.ProductName
if ($productName -eq 'VectorCraft Nightly') {
throw 'a VectorCraft Nightly executable cannot be packaged as stable (use package.ps1 -Nightly)'
}
# No VERSIONINFO at all reads as an empty name, and an executable built without the resource
# compiler (or taken from another source with -SkipBuild) must not reach the stable MSI that way.
if ($productName -cne 'VectorCraft') {
throw "the executable has no stable VERSIONINFO (ProductName '$productName'); rebuild with the resource compiler available"
}
# Check both binaries' PE headers before packaging. Machine (COFF header) must match -Arch, so an
# x64 build can never ship labelled arm64. Subsystem (optional header): 2 = Windows GUI, 3 = console.
# The app must be GUI (no console window opens with it); the CLI must stay console so its output
+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 the
signing configuration with -Required -CheckOnly. Compilation uses the separate
-CheckBuildEnvironment mode, which refuses any signing material without importing a key.
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/vectorcraft.exe dist/Vectorcraft.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
+1
View File
@@ -17,3 +17,4 @@ sonar.test.inclusions=**/tests/**,**/tests.rs,**/*_tests.rs,**/tests_*.rs
sonar.issue.ignore.multicriteria=pdf_md5
sonar.issue.ignore.multicriteria.pdf_md5.ruleKey=rust:S4790
sonar.issue.ignore.multicriteria.pdf_md5.resourceKey=crates/pdf/src/encrypt.rs
sonar.coverage.exclusions=packaging/**