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

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

Co-authored-by: Dylan M. Taylor <dylan@dylanmtaylor.com>
This commit is contained in:
Dylan M. Taylor
2026-11-24 18:55:17 -06:00
committed by GitHub
parent c01d391df7
commit ef2a9eeefc
66 changed files with 5519 additions and 82 deletions
+107
View File
@@ -0,0 +1,107 @@
{
"schema": "craft-nightly-release-policy/v3",
"repository": "storytold/figcraft",
"repository_id": 1412112308,
"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": "figcraft-nightly-20261124-initial",
"repository": "storytold/figcraft",
"branch": "main",
"required_workflows": [
{
"workflow_id": 379864519,
"workflow_path": ".github/workflows/ci.yml",
"jobs": [
{
"name": "gate / gate (ubuntu-24.04)",
"app_id": 15368,
"applicability": "required"
}
]
}
],
"sonar": {
"organization": "storytold",
"project": "storytold_figcraft",
"app_id": 12526,
"check_name": "SonarCloud Code Analysis",
"details_url": "https://sonarcloud.io/dashboard?id=storytold_figcraft&branch=main",
"issue_types": [
"VULNERABILITY"
],
"accepted_conditions": [
{
"metric": "new_security_rating",
"comparator": "GT",
"error_threshold": "1",
"maximum": "5"
}
],
"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"
}
}
}
}
+30
View File
@@ -9,6 +9,14 @@ workflows:
'.github/workflows/lockfile.yml':
- 'actions/checkout@v7.0.1'
- 'step-security/harden-runner@v2.22.4'
'.github/workflows/nightly-macos.yml':
- 'actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1'
- 'actions/upload-artifact@v7.0.2'
- 'step-security/dtolnay-rust-toolchain@v1.0.0'
- 'step-security/harden-runner@v2.22.4'
- 'storytold/craft-common-actions@f5141455aac7b2eb4708aa259d8ffcdf10fde939'
'.github/workflows/nightly-sign.yml': []
'.github/workflows/nightly.yml': []
'.github/workflows/nix.yml': []
'.github/workflows/packaging-lint.yml':
- 'actions/checkout@v7.0.1'
@@ -17,13 +25,35 @@ workflows:
'.github/workflows/sonarcloud.yml': []
'.github/workflows/windows-arm64.yml': []
dependencies:
'actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1':
ref: 'v7.0.1'
commit: 'sha1-3d3c42e5aac5ba805825da76410c181273ba90b1'
owner_id: 44036562
repo_id: 197814629
'actions/checkout@v7.0.1':
ref: 'v7.0.1'
commit: 'sha1-3d3c42e5aac5ba805825da76410c181273ba90b1'
owner_id: 44036562
repo_id: 197814629
'actions/upload-artifact@v7.0.2':
ref: 'v7.0.2'
commit: 'sha1-cf430e030ddbb5b0abf93d22962f4752f3646cd9'
owner_id: 44036562
repo_id: 192625955
'step-security/dtolnay-rust-toolchain@v1.0.0':
ref: 'v1.0.0'
commit: 'sha1-8dd607977d06adf4ed49b190381e74c17a9dd25f'
owner_id: 88700172
repo_id: 1249865941
'step-security/harden-runner@v2.22.4':
ref: 'v2.22.4'
commit: 'sha1-1d88384fd173af6ecb012dfd0264a306b711241a'
owner_id: 88700172
repo_id: 422287306
'storytold/craft-common-actions@f5141455aac7b2eb4708aa259d8ffcdf10fde939':
ref: 'main'
commit: 'sha1-f5141455aac7b2eb4708aa259d8ffcdf10fde939'
owner_id: 76897702
repo_id: 1414429108
uses:
- 'actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1'
+92
View File
@@ -0,0 +1,92 @@
name: Nightly macOS build
# Builds the unsigned Apple-silicon FigCraft 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: 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: 90
env:
CARGO_TERM_COLOR: always
CARGO_INCREMENTAL: 0
RUST_BACKTRACE: 1
steps:
- name: Harden runner
uses: step-security/harden-runner@v2.22.4
with:
egress-policy: audit
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
# The same craft-fonts commit the Nightly producer pins (nightly.yml craft-fonts-ref), so the
# bundle's notices and fonts match a shipped build.
- name: Check out craft-fonts
uses: storytold/craft-common-actions/actions/checkout-craft-fonts@f5141455aac7b2eb4708aa259d8ffcdf10fde939
with:
ref: 37827adc41fd165f9a9234ac40f94dbad353aa69
- uses: storytold/craft-common-actions/actions/checkout-craft-i18n@f5141455aac7b2eb4708aa259d8ffcdf10fde939
- id: rust
uses: storytold/craft-common-actions/actions/rust-channel@f5141455aac7b2eb4708aa259d8ffcdf10fde939
with:
targets: aarch64-apple-darwin
- uses: step-security/dtolnay-rust-toolchain@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 "FIGCRAFT_BUILD_SHA=$sha"
echo "FIGCRAFT_BUILD_DATE=$date"
echo "FIGCRAFT_VERSION=$base-nightly.${date//-/}.$GITHUB_RUN_NUMBER.$GITHUB_RUN_ATTEMPT.g${sha:0:12}"
} >>"$GITHUB_ENV"
- name: Build the unsigned Nightly bundle
env:
FIGCRAFT_BUILD_CHANNEL: nightly-v1
CARGO_TARGET_DIR: ${{ runner.temp }}/nightly-targets
DIST: ${{ runner.temp }}/nightly-dist
CRAFT_FONTS_DIR: ${{ github.workspace }}/craft-fonts
CRAFT_FONTS_REQUIRED: "1"
run: bash packaging/macos/nightly.sh --arch aarch64
- name: Check the archive and the bundle's version
run: bash packaging/macos/nightly-verify.sh --expect unsigned --input "$RUNNER_TEMP/nightly-dist/figcraft-$FIGCRAFT_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@v7.0.2
with:
name: figcraft-nightly-macos-aarch64-unsigned
path: ${{ runner.temp }}/nightly-dist/figcraft-${{ env.FIGCRAFT_VERSION }}-macos-aarch64-nightly.zip
if-no-files-found: error
retention-days: 7
compression-level: 0
+42
View File
@@ -0,0 +1,42 @@
name: FigCraft 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: figcraft-nightly-release
cancel-in-progress: false
jobs:
release:
# Actual context guards: official repository, manual dispatch, real release branch.
if: >-
github.repository == 'storytold/figcraft' &&
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: FigCraft unsigned nightly
# Enabled for supervised manual runs by the reviewed manual actors only; no schedule yet.
# A later explicit opt-in may add a cadence (and a completion dispatcher with it).
on:
workflow_dispatch:
permissions:
contents: read
jobs:
unsigned:
# Actual context guards only; no inherited/platform secrets.
if: >-
github.repository == 'storytold/figcraft' &&
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: figcraft
manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]'
craft-fonts-ref: 37827adc41fd165f9a9234ac40f94dbad353aa69
# 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"]'
+9
View File
@@ -11,3 +11,12 @@ plans/
*.profraw
.cache/
.vscode/
# Checked out by the shared nightly workflows into the workspace (nightly-common.sh runs from a
# clean tree, so they must not show up as untracked files).
# Python caches from the packaging suites.
__pycache__/
/.nightly-tools
/.nightly-input
/craft-i18n
/craft-fonts
+2 -1
View File
@@ -40,7 +40,8 @@ craft-update = { workspace = true }
windows = { version = "0.62", default-features = false, features = ["UI_ViewManagement", "System_UserProfile", "Foundation_Collections", "Gaming_Input"] }
# The custom title bar's window styles (src/window_frame.rs): safe Win32 wrappers (MIT); the `user`
# feature is User32.dll only. Same version as DesignCraft and PhotoCraft.
winsafe = { version = "0.0.29", default-features = false, features = ["user"] }
# `shell` is the process identity the Nightly sets for its own taskbar group (process_identity.rs).
winsafe = { version = "0.0.29", default-features = false, features = ["user", "shell"] }
# The system colour scheme (org.freedesktop.portal.Settings): winit reports no theme on Linux and
# the BSDs, so the interface's "system" mode follows the portal's instead. zbus comes in through
+62 -5
View File
@@ -1,19 +1,76 @@
//! Windows: embed the icon and version info in figcraft.exe and size its main thread's stack
//! (no-op elsewhere).
//! (no-op elsewhere). Also bakes the build channel and the version the app reports.
//!
//! The channel comes from `FIGCRAFT_BUILD_CHANNEL`: unset, empty or `stable` is the stable build;
//! `nightly-v1` needs an explicit `FIGCRAFT_VERSION` (or the wrappers' `FIGCRAFT_OVERRIDE_VERSION`)
//! that names the exact feed identity. A missing resource compiler stays a warning unless
//! `FIGCRAFT_REQUIRE_WINRES=1` (set by the packaging scripts) makes it an error.
#[path = "src/build_channel.rs"]
mod build_channel;
fn main() {
println!("cargo::rerun-if-changed=build.rs");
println!("cargo::rustc-check-cfg=cfg(windows_slim_errors)");
println!("cargo::rustc-check-cfg=cfg(figcraft_nightly_v1)");
println!("cargo::rerun-if-changed=../../assets/app-icon/figcraft.ico");
println!("cargo::rerun-if-changed=../../assets/app-icon/figcraft-nightly.ico");
println!("cargo::rerun-if-env-changed=FIGCRAFT_BUILD_CHANNEL");
println!("cargo::rerun-if-env-changed=FIGCRAFT_VERSION");
println!("cargo::rerun-if-env-changed=FIGCRAFT_OVERRIDE_VERSION");
println!("cargo::rerun-if-env-changed=FIGCRAFT_REQUIRE_WINRES");
let nightly = match std::env::var("FIGCRAFT_BUILD_CHANNEL").as_deref() {
Ok("nightly-v1") => {
println!("cargo::rustc-cfg=figcraft_nightly_v1");
true
}
// An empty value (an unset CI input) means the default stable build.
Ok("stable" | "") | Err(std::env::VarError::NotPresent) => false,
_ => {
eprintln!("unsupported FIGCRAFT_BUILD_CHANNEL (expected stable or nightly-v1)");
std::process::exit(1);
}
};
let built_version = if nightly {
// `packaging/nightly-common.sh` and `packaging/windows/nightly.ps1` pass the prepared
// version as FIGCRAFT_OVERRIDE_VERSION; a caller that already set FIGCRAFT_VERSION works too.
let supplied = std::env::var("FIGCRAFT_OVERRIDE_VERSION").ok().filter(|v| !v.is_empty()).or_else(|| std::env::var("FIGCRAFT_VERSION").ok());
match supplied {
Some(version) if build_channel::is_nightly_version(&version) => version,
_ => {
eprintln!("nightly-v1 requires an explicit FIGCRAFT_VERSION (or FIGCRAFT_OVERRIDE_VERSION) feed identity");
std::process::exit(1);
}
}
} else {
std::env::var("CARGO_PKG_VERSION").unwrap_or_default()
};
println!("cargo::rustc-env=FIGCRAFT_BUILT_VERSION={built_version}");
let target_os = std::env::var("CARGO_CFG_TARGET_OS").unwrap_or_default();
if target_os == "windows" {
let mut res = winresource::WindowsResource::new();
let ico = "../../assets/app-icon/figcraft.ico";
let ico = build_channel::windows_icon_path(nightly);
if std::path::Path::new(ico).exists() {
res.set_icon(ico);
}
res.set("ProductName", "FigCraft");
res.set("FileDescription", "FigCraft");
res.set("CompanyName", "ArtCraft");
res.set("ProductName", if nightly { "FigCraft Nightly" } else { "FigCraft" })
.set("FileDescription", if nightly { "FigCraft Nightly interface design and prototyping" } else { "FigCraft" })
.set("CompanyName", "ArtCraft")
.set("OriginalFilename", "figcraft.exe")
.set("InternalName", "figcraft");
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("FIGCRAFT_REQUIRE_WINRES").is_some() {
// The workspace denies `clippy::panic`, build scripts included: stop the build with
// the reason on stderr, as the channel check above does.
eprintln!("embedding Windows resources failed: {e}");
std::process::exit(1);
}
println!("cargo::warning=winresource: {e}");
}
// Windows starts the main thread with 1 MB of stack, Linux and macOS with 8 MB. Layers
+56
View File
@@ -0,0 +1,56 @@
//! The build-time nightly identity shared by the build script and its pure regression tests.
pub fn is_nightly_version(version: &str) -> bool {
let Some((base, suffix)) = version.split_once("-nightly.") else { return false };
let digits = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit());
let base: Vec<_> = base.split('.').collect();
let parts: Vec<_> = suffix.split('.').collect();
base.len() == 3
&& base.iter().all(|s| digits(s))
&& parts.len() == 4
&& parts[0].len() == 8
&& digits(parts[0])
&& digits(parts[1])
&& digits(parts[2])
&& parts[3].strip_prefix('g').is_some_and(|sha| sha.len() == 12 && sha.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)))
}
pub fn windows_icon_path(nightly: bool) -> &'static str {
if nightly { "../../assets/app-icon/figcraft-nightly.ico" } else { "../../assets/app-icon/figcraft.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/figcraft.ico");
assert_eq!(windows_icon_path(true), "../../assets/app-icon/figcraft-nightly.ico");
}
#[test]
fn explicit_feed_identity_is_required_for_a_nightly_build() {
assert!(is_nightly_version("0.18.1-nightly.20261120.17.1.gabcdef012345"));
for invalid in [
"",
"0.18.1",
"0.18.1-nightly",
"0.18.1-nightly.20261120",
"0.18.1-nightly.20261120.17.1.gABCDEF012345",
"0.18.1-nightly.20261120.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.18.1-nightly.20261120.1.1.gabcdef012345",
"0.18.1-nightly.20261120.1.1.gabcdef012345/other",
"0.18.1-nightly.20261120.1.1.gabcdef012345\ncargo:rustc-cfg=other",
] {
assert!(!is_nightly_version(invalid));
}
}
}
+70
View File
@@ -0,0 +1,70 @@
//! Build-time channel is distinct from a launch selector. A runtime environment cannot promote a stable build.
use crate::launch_profile::Profile;
use std::ffi::OsString;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BuildFlavor {
Stable,
NightlyV1,
}
pub const COMPILED: BuildFlavor = if cfg!(figcraft_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 FigCraft Nightly from ArtCraft Launcher".into()),
(BuildFlavor::Stable, true) => Err("This is a stable FigCraft build; nightly-v1 requires the nightly build".into()),
_ => Ok(()),
}
}
pub fn needs_native_error(flavor: BuildFlavor, desktop_session: bool) -> bool {
desktop_session && flavor == BuildFlavor::NightlyV1
}
pub fn version_query(args: &[OsString]) -> bool {
matches!(args, [arg] if arg == "--version" || arg == "-V")
}
pub fn version(flavor: BuildFlavor, stable: &str) -> String {
match flavor {
BuildFlavor::Stable => stable.to_owned(),
BuildFlavor::NightlyV1 => format!("{stable} (nightly-v1)"),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn only_a_nightly_desktop_refusal_requests_a_native_dialog() {
assert!(needs_native_error(BuildFlavor::NightlyV1, true));
assert!(!needs_native_error(BuildFlavor::NightlyV1, false));
assert!(!needs_native_error(BuildFlavor::Stable, true));
assert!(!needs_native_error(BuildFlavor::Stable, false));
}
#[test]
fn nightly_build_without_a_profile_is_refused_before_startup() {
let started = std::cell::Cell::new(false);
let result = require_profile(BuildFlavor::NightlyV1, &Profile::Stable).map(|()| started.set(true));
assert!(result.unwrap_err().contains("ArtCraft Launcher"));
assert!(!started.get());
}
#[test]
fn stable_and_nightly_flavors_accept_only_their_own_profile() {
let nightly = Profile::NightlyV1(std::path::PathBuf::from("already validated root"));
assert!(require_profile(BuildFlavor::Stable, &Profile::Stable).is_ok());
assert!(require_profile(BuildFlavor::Stable, &nightly).is_err());
assert!(require_profile(BuildFlavor::NightlyV1, &nightly).is_ok());
}
#[test]
fn nightly_version_query_is_unambiguous_and_never_reinterprets_file_arguments() {
assert_eq!(version(BuildFlavor::Stable, "0.18.1"), "0.18.1");
assert_eq!(version(BuildFlavor::NightlyV1, "0.18.1"), "0.18.1 (nightly-v1)");
assert!(version_query(&["--version".into()]));
assert!(version_query(&["-V".into()]));
assert!(!version_query(&["--".into(), "--version".into()]));
assert!(!version_query(&[]));
}
}
+215
View File
@@ -0,0 +1,215 @@
//! Launcher-owned nightly-v1 bootstrap. Selected before logging, updates, fonts or saved state.
//! Stable launches retain their original arguments and directory policy. No environment mutation.
use std::ffi::OsString;
use std::path::{Component, Path, PathBuf};
use std::sync::OnceLock;
pub const VERSION: &str = "nightly-v1";
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Profile {
Stable,
NightlyV1(PathBuf),
}
impl Profile {
pub fn is_nightly(&self) -> bool {
matches!(self, Self::NightlyV1(_))
}
pub fn root(&self) -> Option<&Path> {
match self {
Self::Stable => None,
Self::NightlyV1(root) => Some(root),
}
}
}
#[derive(Debug, PartialEq, Eq)]
pub struct Launch {
pub profile: Profile,
pub args: Vec<OsString>,
}
static PROFILE: OnceLock<Profile> = OnceLock::new();
pub fn current() -> &'static Profile {
PROFILE.get().unwrap_or(&Profile::Stable)
}
pub fn install(profile: Profile) -> Result<(), String> {
PROFILE.set(profile).map_err(|_| "the launch profile was already selected".into())
}
/// Recognize only the agreed literal selector/root pair before `--`. Everything after it is
/// a file, even when it looks like a profile flag. No filesystem or startup hook runs here.
///
/// Every other flag is refused for a nightly launch, which is how Nightly stays away from the
/// control channel and the automation roots the stable app can be started with.
pub fn parse(args: Vec<OsString>) -> Result<Launch, String> {
let mut selector = None;
let mut root = None;
let mut other = Vec::new();
let mut files = Vec::new();
let mut iter = args.iter();
let mut delimiter = false;
while let Some(arg) = iter.next() {
if arg == "--" {
delimiter = true;
files.extend(iter.cloned());
break;
}
if arg == "--launch-profile" || arg == "--profile-root" {
let slot = if arg == "--launch-profile" { &mut selector } else { &mut root };
if slot.is_some() {
return Err("the profile selector and root must each occur exactly once".into());
}
let value = iter.next().filter(|v| !v.is_empty()).ok_or("the profile selector/root needs a value")?;
if value.to_string_lossy().starts_with("--") {
return Err("the profile selector/root needs a value".into());
}
*slot = Some(value.clone());
} else if arg.to_string_lossy().starts_with("--launch-profile=") || arg.to_string_lossy().starts_with("--profile-root=") {
return Err("the nightly protocol requires separate literal selector/root argument tokens".into());
} else {
other.push(arg.clone());
}
}
match (selector, root) {
(None, None) => Ok(Launch { profile: Profile::Stable, args }),
(Some(version), Some(root)) if version == VERSION => {
if !delimiter || !other.is_empty() {
return Err("nightly-v1 accepts only its selector/root followed by -- and file names".into());
}
let root = PathBuf::from(root);
if !root.is_absolute() || root.components().any(|c| matches!(c, Component::ParentDir)) {
return Err("the nightly profile root must be absolute and contain no parent traversal".into());
}
Ok(Launch { profile: Profile::NightlyV1(root), args: std::iter::once(OsString::from("--")).chain(files).collect() })
}
(Some(_), Some(_)) => Err("unsupported launch profile (expected nightly-v1)".into()),
_ => Err("--launch-profile and --profile-root must be supplied together".into()),
}
}
/// The Launcher's version check: the selector/root pair followed by exactly `--version` (or `-V`),
/// answered like a plain version query. Only [`parse`]'s lexical checks apply; the root is never
/// validated or touched, and `-- --version` stays a file name.
pub fn version_query(args: &[OsString]) -> bool {
let Some((last, pair)) = args.split_last() else { return false };
if last != "--version" && last != "-V" {
return false;
}
let lexical = pair.iter().cloned().chain(std::iter::once(OsString::from("--"))).collect();
matches!(parse(lexical), Ok(Launch { profile: Profile::NightlyV1(_), args }) if args.len() == 1)
}
/// Validation finishes before the caller's first startup effect. Stable never calls the nightly
/// root validator, so its old portable/config resolution stays unchanged.
pub fn prepare(mut launch: Launch, validate: impl FnOnce(&Path) -> Result<PathBuf, String>) -> Result<Launch, String> {
if let Profile::NightlyV1(root) = &launch.profile {
launch.profile = Profile::NightlyV1(validate(root)?);
}
Ok(launch)
}
/// Resolve the selected private root before the caller's first startup effect.
pub fn validate_root(root: &Path, env: impl Fn(&str) -> Option<OsString>, exe: Option<&Path>) -> Result<PathBuf, String> {
crate::profile_root::validate(root, env, exe, crate::profile_root::ensure_writable)
}
#[cfg(test)]
mod tests {
use super::*;
use std::cell::Cell;
fn args(values: &[&str]) -> Vec<OsString> {
values.iter().map(OsString::from).collect()
}
fn absolute() -> &'static str {
if cfg!(windows) { r"C:\NightlyData\profiles\figcraft" } else { "/nightly-data/profiles/figcraft" }
}
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(&["--control", "8765", "a.figcraft"]), args(&["--", "--launch-profile", "file.figcraft"])] {
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", "image with spaces.figcraft"]));
let launch = parse(argv).unwrap();
assert_eq!(launch.profile, Profile::NightlyV1(PathBuf::from(absolute())));
assert_eq!(launch.args, args(&["--", "--profile-root", "image with spaces.figcraft"]));
}
#[test]
fn missing_duplicate_unknown_and_conflicting_profile_arguments_are_refused() {
for argv in [
args(&["--launch-profile", VERSION]),
args(&["--profile-root", absolute()]),
args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--"]),
args(&["--launch-profile", VERSION, "--launch-profile", VERSION, "--profile-root", absolute(), "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--profile-root", absolute(), "--"]),
args(&["--launch-profile", VERSION, "--profile-root", "relative", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", "", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--control", "8765", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--automation-write-root", "/tmp", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute()]),
] {
assert!(parse(argv).is_err());
}
}
#[test]
fn the_launcher_version_check_is_a_version_query_only_in_its_exact_form() {
let pair = &["--launch-profile", VERSION, "--profile-root", absolute()];
let reversed = &["--profile-root", absolute(), "--launch-profile", VERSION];
for flag in ["--version", "-V"] {
for form in [pair, reversed] {
let mut argv = args(form);
argv.push(flag.into());
assert!(version_query(&argv), "{argv:?}");
}
}
for argv in [
args(&["--version"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--", "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--control", "8765", "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--version"]),
args(&["--version", "--launch-profile", VERSION, "--profile-root", absolute()]),
args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", "relative", "--version"]),
args(&["--launch-profile", VERSION, "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--help"]),
] {
assert!(!version_query(&argv), "{argv:?}");
}
// Outside the query the strict protocol still refuses the version flag.
assert!(parse(args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version"])).is_err());
}
#[test]
fn failed_root_validation_never_reaches_startup_or_falls_back_to_stable() {
let reached = Cell::new(false);
let result = prepare(parse(nightly()).unwrap(), |_| Err("read-only or unsafe profile".into())).map(|_| reached.set(true));
assert!(result.is_err());
assert!(!reached.get());
}
#[test]
fn successful_root_validation_keeps_the_persistent_root_not_the_binary_tag() {
let checked = PathBuf::from(absolute()).join("checked");
let launch = prepare(parse(nightly()).unwrap(), |_| Ok(checked.clone())).unwrap();
assert_eq!(launch.profile.root(), Some(checked.as_path()));
assert!(launch.profile.is_nightly());
}
}
+190 -14
View File
@@ -23,9 +23,17 @@ compile_error!("Windows GNU builds must set windows_slim_errors to keep UI Autom
#[cfg(target_os = "macos")]
mod apple_events;
mod args;
// The build script includes the same file for the icon and version it embeds.
#[cfg(test)]
mod build_channel;
mod build_flavor;
mod control_server;
mod gamepad;
mod graphics;
mod launch_profile;
mod nightly_session;
mod process_identity;
mod profile_root;
mod recovery;
mod services;
mod startup;
@@ -69,6 +77,15 @@ struct App {
/// Documents and quit requests from Finder, the Dock and Open With.
#[cfg(target_os = "macos")]
apple_events: fmv_macos_events::Inbox,
/// The Nightly session record this window owns: finished on the controlled exit, where macOS
/// ends the process and `run_native` never returns.
nightly: crate::nightly_session::Shared,
/// Set once this window drew the interrupted-session notice in a frame.
nightly_notice: Arc<std::sync::atomic::AtomicBool>,
/// The interrupted-session notice is queued but no frame has drawn it yet. Until one does, the
/// earlier session's record stays for the next start to report (a renderer failure before the
/// first frame must not acknowledge it).
nightly_notice_pending: bool,
}
impl eframe::App for App {
@@ -127,6 +144,11 @@ impl eframe::App for App {
fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) {
let ctx = ui.ctx().clone();
services::parented(frame, || with_app(|fig| figcraft_ui_egui::windows::guard(fig, &ctx, |fig| fig.ui(ui))));
// This frame drew the queued interrupted-session notice: the interruption is now reported.
if self.nightly_notice_pending {
self.nightly_notice_pending = false;
self.nightly_notice.store(true, std::sync::atomic::Ordering::Relaxed);
}
}
fn on_exit(&mut self) {
@@ -138,6 +160,10 @@ impl eframe::App for App {
// thread-local, and the process can end without dropping it.
fig.start_pending_update();
});
// The controlled exit: on macOS this is the only path that runs (Cmd+Q ends the process
// inside AppKit after `on_exit`), so the Nightly session record is finished here. The
// call after `run_native` is the no-op fallback for a start that created no window.
crate::nightly_session::finish_once(&self.nightly, self.nightly_notice.load(std::sync::atomic::Ordering::Relaxed));
// Everything is kept: end before the windows' teardown, where AppKit's Touch Bar support
// throws on the content view AccessKit restores (craft-libs#3, #781).
#[cfg(target_os = "macos")]
@@ -145,15 +171,118 @@ impl eframe::App for App {
}
}
/// The Windows taskbar identity of the Nightly: distinct from stable's, so both can be open.
const NIGHTLY_WINDOW_ID: &str = "ai.storyteller.figcraft.nightly-v1";
/// The window and Wayland/X11 app id: the Nightly's own, so its window is not the stable app's.
fn window_app_id() -> &'static str {
if launch_profile::current().is_nightly() { NIGHTLY_WINDOW_ID } else { "ai.storyteller.figcraft" }
}
/// Whether a desktop session can show a dialog (a headless run has no one to ask).
fn desktop_session() -> bool {
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())))
}
fn initialize_nightly_identity() -> Result<(), String> {
process_identity::initialize(build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1, NIGHTLY_WINDOW_ID)
}
/// Say why a launch profile was refused: in a dialog for a Nightly started from the desktop (its
/// release build has no console), and on standard error in every case. Always exits 2.
fn report_launch_profile_error(error: &str) -> ! {
eprintln!("FigCraft launch profile: {error}");
if build_flavor::needs_native_error(build_flavor::COMPILED, desktop_session()) {
if let Err(error) = initialize_nightly_identity() {
eprintln!("FigCraft launch profile: {error}");
} else {
let _ = rfd::MessageDialog::new()
.set_title("FigCraft Nightly")
.set_description(error)
.set_level(rfd::MessageLevel::Error)
.set_buttons(rfd::MessageButtons::Ok)
.show();
}
}
std::process::exit(2)
}
/// Select the immutable launch profile before any startup service or side effect, and answer the
/// version query first: `None` means the query did (there is nothing left to start).
///
/// Stable keeps its arguments and its directory policy untouched; only a Nightly build answers the
/// Launcher's `--launch-profile nightly-v1 --profile-root <dir> --version` form.
fn prepare_launch() -> Option<Vec<std::ffi::OsString>> {
let argv: Vec<_> = std::env::args_os().skip(1).collect();
let nightly_build = build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1;
if nightly_build && (build_flavor::version_query(&argv) || launch_profile::version_query(&argv)) {
// Before root validation, logging, the update helper, fonts or any window: a runner reads
// this line and the process ends. Nothing else may be printed here.
use std::io::Write as _;
let _ = writeln!(std::io::stdout(), "FigCraft {}", build_flavor::version(build_flavor::COMPILED, env!("FIGCRAFT_BUILT_VERSION")));
return None;
}
let early = launch_profile::parse(argv)
.and_then(|launch| {
build_flavor::require_profile(build_flavor::COMPILED, &launch.profile)?;
initialize_nightly_identity()?;
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));
if let Err(error) = launch_profile::install(early.profile) {
report_launch_profile_error(&error);
}
if let Some(root) = launch_profile::current().root() {
// Everything that names or finds the app now names the Nightly, from the first frame on.
figcraft_ui_egui::channel::install_nightly(env!("FIGCRAFT_BUILT_VERSION"), option_env!("FIGCRAFT_BUILD_SHA"));
// The suite's font store is shared with the stable app: the Nightly installs and reads its
// fonts inside its own profile instead.
figcraft_engine::fonts::download::use_store_dir(root.join("Fonts"));
}
Some(early.args)
}
fn main() -> eframe::Result {
// Windows: the update helper is a copy of this program started with `--finish-update`.
// The launch profile comes before the logger, the update helper, fonts and saved state.
let Some(arguments) = prepare_launch() else { return Ok(()) };
let nightly = launch_profile::current().is_nightly();
// Windows: the update helper is a copy of this program started with `--finish-update`. The
// Nightly has none: the Launcher owns its version.
#[cfg(windows)]
if let Some(result) = craft_update::self_update::finish(&figcraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::<Vec<_>>()) {
if !nightly
&& let Some(result) = craft_update::self_update::finish(&figcraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::<Vec<_>>())
{
std::process::exit(i32::from(result.is_err()));
}
env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("warn")).init();
let args: Vec<String> = std::env::args().skip(1).collect();
if args.iter().any(|a| a == "--version" || a == "-V") {
let args: Vec<String> = if nightly {
// The launcher hands these over after `--`, which `parse` takes as file names verbatim (that
// is what keeps a file called `--screenshot` a file). "Open with" and a drop onto the
// launcher pass `file://` URLs (`%U`), so decode those here as a plain argument would be;
// every other name stays exactly as given.
arguments
.iter()
.map(|a| {
let arg = a.to_string_lossy();
match args::file_url_path(&arg) {
Some(path) => path,
None => arg.into_owned(),
}
})
.collect()
} else {
std::env::args().skip(1).collect()
};
// A stable build answers `--version` anywhere, as it always did; the Nightly's forms were
// answered before any startup effect (`prepare_launch`).
if !nightly && args.iter().any(|a| a == "--version" || a == "-V") {
println!(
"FigCraft {}{}",
env!("CARGO_PKG_VERSION"),
@@ -179,7 +308,9 @@ fn main() -> eframe::Result {
std::process::exit(2);
}
};
let port = args.control.or_else(|| std::env::var("FIGCRAFT_CONTROL_PORT").ok().and_then(|p| p.parse().ok()));
// The control channel is the stable app's (agents, automation): a Nightly never opens one,
// and never inherits the environment variable that would.
let port = if nightly { None } else { args.control.or_else(|| std::env::var("FIGCRAFT_CONTROL_PORT").ok().and_then(|p| p.parse().ok())) };
// System fonts: index them in the background, then wake the UI (an idle window draws no frames)
// to lay text out again with them.
let ctx_slot: Arc<Mutex<Option<egui::Context>>> = Arc::new(Mutex::new(None));
@@ -229,9 +360,12 @@ fn main() -> eframe::Result {
// Plugins installed from a server's plugin directory live with the user's settings.
session.plugins.install_dir = services::config_dir().map(|d| d.join("Plugins"));
// Invite links open this app (Windows registers per user at run time; installed builds by
// default, never a build from source unless asked).
session.live.links = figcraft_collab_net::links::system();
session.invite_links_startup();
// default, never a build from source unless asked). Registering is the stable app's, so a
// Nightly links nothing and never touches the registration.
if !nightly {
session.live.links = figcraft_collab_net::links::system();
session.invite_links_startup();
}
let first_run = svc.prefs.is_none() && args.join.is_none();
if session.docs.is_empty() && opens_new_file(first_run, session.prefs.start_on_home, port.is_some()) {
let _ = session.execute("file.new", &json!({}));
@@ -240,7 +374,12 @@ fn main() -> eframe::Result {
// open (no frame then).
figcraft_ui_egui::i18n::set(&session.prefs.language, figcraft_ui_egui::Services::system_language(&svc).as_deref());
let mut fig = FigApp::new(session, Box::new(svc));
fig.set_startup_update_check(true);
if nightly {
// The Launcher keeps the Nightly on the version it installed.
fig.disable_updates();
} else {
fig.set_startup_update_check(true);
}
fig.automation_roots = roots;
fig.ui.home = false;
// Files named on the command line are the user's too: their missing fonts are listed.
@@ -260,8 +399,8 @@ fn main() -> eframe::Result {
// The app id is the Wayland app_id and the X11 window class on Linux: the desktop entry's name
// and StartupWMClass (FreeBSD's package matches the binary's name instead).
let mut viewport = egui::ViewportBuilder::default()
.with_title("FigCraft")
.with_app_id("ai.storyteller.figcraft")
.with_title(figcraft_ui_egui::channel::name())
.with_app_id(window_app_id())
.with_inner_size([1440.0, 900.0])
.with_min_inner_size([800.0, 500.0])
.with_drag_and_drop(true);
@@ -283,6 +422,34 @@ fn main() -> eframe::Result {
// Counts the frames drawn, which tells a window that failed starting up from one that ran.
let window = ctx_slot.clone();
figcraft_ui_egui::windows::install(fig);
// Nightly session health: written before the window loop and finished on the controlled exit.
// A secondary window of the same profile records nothing (no document names or diagnostics).
let (nightly_record, health_warning) = match nightly_session::Session::begin_with_health(
launch_profile::current().root(),
env!("FIGCRAFT_BUILT_VERSION"),
option_env!("FIGCRAFT_BUILD_SHA").filter(|sha| !sha.is_empty()),
) {
Ok(state) => state,
Err(error) => {
log::warn!("Nightly session health is unavailable: {error}");
(None, true)
}
};
let previous_unclean = nightly_record.as_ref().is_some_and(nightly_session::Session::previous_unclean);
let nightly_notice = Arc::new(std::sync::atomic::AtomicBool::new(false));
if previous_unclean || health_warning {
let message = if previous_unclean {
"The previous FigCraft Nightly session did not finish normally. You can report a problem from About. No diagnostics have been sent."
} else {
"FigCraft Nightly could not record its session health in its private profile. You can still edit, but detecting an abnormal exit is unavailable."
};
with_app(|fig| fig.toast(message));
}
// Acknowledged only when a frame draws the notice (`App::ui`), never by queueing it here.
let nightly_notice_pending = previous_unclean;
let nightly_record: nightly_session::Shared = Arc::new(Mutex::new(nightly_record));
let exit_record = nightly_record.clone();
let exit_notice = nightly_notice.clone();
// Registered before the event loop starts, so it catches the Finder event that launched the app
// as well as later ones. Lives until the event loop returns; the app creator only borrows it.
#[cfg(target_os = "macos")]
@@ -290,7 +457,7 @@ fn main() -> eframe::Result {
#[cfg(target_os = "macos")]
let apple_events = &apple_events;
let result = eframe::run_native(
"FigCraft",
figcraft_ui_egui::channel::name(),
options,
Box::new(|cc| {
if let Some(state) = &cc.wgpu_render_state {
@@ -303,7 +470,7 @@ fn main() -> eframe::Result {
// asks just as it does for the close button. Failure keeps winit's menu: the app
// runs, but ⌘Q ends it without asking.
#[cfg(target_os = "macos")]
if let Err(e) = craft_menu::mac::install_app_menu(&cc.egui_ctx, "FigCraft") {
if let Err(e) = craft_menu::mac::install_app_menu(&cc.egui_ctx, figcraft_ui_egui::channel::name()) {
log::warn!("app menu: kept winit's Quit, which ends the app without asking: {e}");
}
Ok(Box::new(App {
@@ -311,6 +478,9 @@ fn main() -> eframe::Result {
ctx_slot,
title: String::new(),
recovery,
nightly: exit_record,
nightly_notice: exit_notice,
nightly_notice_pending,
// The custom title bar's undecorated window must stay borderless, or its caption
// and border offset the content and the pointer on some Windows systems (#1343).
window_frame: window_frame::WindowFrame::new(custom_titlebar),
@@ -320,8 +490,14 @@ fn main() -> eframe::Result {
}),
);
let frames = window.lock().unwrap_or_else(std::sync::PoisonError::into_inner).as_ref().map_or(0, egui::Context::cumulative_frame_nr);
// The fallback for a start that never reached `on_exit`; elsewhere the exit hook did it. It runs
// before the graphics handoff: on Unix the fallback `exec`s the restarted window from inside
// `graphics.finish`, so a record finished after it would never be written and the restarted
// window would report an unclean exit (and a Windows restart races the lease instead). A
// renderer handoff is a controlled completion (`nightly_session::complete`).
nightly_session::finish_once(&nightly_record, nightly_notice.load(std::sync::atomic::Ordering::Relaxed));
// Start again on other graphics, or say why instead of quitting silently: release builds on
// Windows have no console.
// Windows have no console. A handoff start does not reach the window here.
graphics.finish(result, frames, port.is_some())
}
+295
View File
@@ -0,0 +1,295 @@
//! App-private Nightly session health, not telemetry or a Launcher protocol.
//! A live owner holds a separate persistent lease; secondary launches never rewrite its record.
//! Dropping the guard does not clear the marker. Only the app's controlled return path does.
use std::fs::{File, OpenOptions};
use std::io::{self, Read, Write as _};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, PoisonError};
const RECORD: &str = "nightly-session.json";
const LEASE: &str = "nightly-session.lock";
const MAX_METADATA_BYTES: usize = 256;
pub struct Session {
_lease: File,
path: PathBuf,
own_record: Vec<u8>,
previous_unclean: bool,
}
fn regular_or_missing(path: &Path) -> io::Result<bool> {
match std::fs::symlink_metadata(path) {
Ok(metadata) if metadata.file_type().is_file() && !metadata.file_type().is_symlink() => Ok(true),
Ok(_) => Err(io::Error::other("Nightly session state must be a regular file, not an alias or directory")),
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false),
Err(error) => Err(error),
}
}
/// Replace `path` with `bytes` without ever following a link at the destination: the caller's
/// session record must not be able to change a file outside the profile. The temporary file is
/// created exclusively in the same folder, so the rename replaces the name, never its target.
fn atomic_write_no_follow(path: &Path, bytes: &[u8]) -> io::Result<()> {
let folder = path.parent().ok_or_else(|| io::Error::other("the session record has no folder"))?;
let name = path.file_name().ok_or_else(|| io::Error::other("the session record has no name"))?;
let mut temporary = folder.to_path_buf().join(name);
temporary.set_extension("json.tmp");
match std::fs::symlink_metadata(&temporary) {
// A leftover from a killed run: this owns the folder, and a link there is not followed.
Ok(metadata) if metadata.file_type().is_symlink() || metadata.file_type().is_file() => std::fs::remove_file(&temporary)?,
Ok(_) => return Err(io::Error::other("the session record's temporary path is a directory")),
Err(error) if error.kind() == io::ErrorKind::NotFound => {}
Err(error) => return Err(error),
}
let mut options = OpenOptions::new();
options.write(true).create_new(true);
#[cfg(unix)]
std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
let mut file = options.open(&temporary)?;
let written = file.write_all(bytes).and_then(|()| file.sync_all());
drop(file);
if let Err(error) = written.and_then(|()| std::fs::rename(&temporary, path)) {
let _ = std::fs::remove_file(&temporary);
return Err(error);
}
if let Ok(folder) = File::open(folder) {
let _ = folder.sync_all();
}
Ok(())
}
/// The owner's session, shared by the app's exit hook (macOS) and the code after the event loop.
/// On macOS every quit ends the process inside AppKit's terminate, after eframe's `on_exit` and
/// before `eframe::run_native` could return, so the exit hook finishes it there; the return path
/// still runs for a start that created no window.
pub type Shared = Arc<Mutex<Option<Session>>>;
/// The controlled return ([`Session::finish`]) by whichever path comes first; later calls do nothing.
pub fn finish_once(shared: &Shared, unclean_notice_shown: bool) {
let watch = shared.lock().unwrap_or_else(PoisonError::into_inner).take();
if let Some(watch) = watch
&& let Err(error) = watch.finish(unclean_notice_shown)
{
log::warn!("Nightly session state was left intact: {error}");
}
}
impl Session {
/// The warning belongs to this window: a busy secondary has no health-record coverage,
/// while Stable and a lease-owning Nightly window preserve their existing result.
pub fn begin_with_health(root: Option<&Path>, version: &str, commit: Option<&str>) -> io::Result<(Option<Self>, bool)> {
let watch = Self::begin(root, version, commit)?;
let unavailable = root.is_some() && watch.is_none();
Ok((watch, unavailable))
}
/// `None` is stable or another owner of this profile. Neither case touches the record.
/// The supplied root must already be the validated private Nightly profile.
pub fn begin(root: Option<&Path>, version: &str, commit: Option<&str>) -> io::Result<Option<Self>> {
let Some(root) = root else { return Ok(None) };
if version.is_empty() || version.len() > MAX_METADATA_BYTES || commit.is_some_and(|value| value.len() > MAX_METADATA_BYTES) {
return Err(io::Error::new(io::ErrorKind::InvalidInput, "Nightly session provenance is missing or too large"));
}
let lease_path = root.join(LEASE);
regular_or_missing(&lease_path)?;
let lease = OpenOptions::new().read(true).write(true).create(true).truncate(false).open(lease_path)?;
match lease.try_lock() {
Ok(()) => {}
Err(std::fs::TryLockError::WouldBlock) => return Ok(None),
Err(std::fs::TryLockError::Error(error)) => return Err(error),
}
let path = root.join(RECORD);
let previous_unclean = regular_or_missing(&path)?;
let own_record = serde_json::to_vec(&serde_json::json!({
"schema_version": 1,
"channel": "nightly-v1",
"version": version,
"commit": commit.filter(|value| !value.is_empty()),
}))?;
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), the record is left for the next owner
/// to report; otherwise this is [`Self::complete`].
pub fn finish(self, unclean_notice_shown: bool) -> io::Result<()> {
if self.previous_unclean && !unclean_notice_shown {
return Ok(());
}
self.complete()
}
/// Controlled event-loop completion includes a handled startup error/renderer handoff, not only
/// exit 0. An unwind, abort, forced exit or killed process never calls this method.
pub fn complete(self) -> io::Result<()> {
if !regular_or_missing(&self.path)? {
return Ok(());
}
let mut current = Vec::new();
File::open(&self.path)?.take(self.own_record.len() as u64 + 1).read_to_end(&mut current)?;
if current != self.own_record {
return Err(io::Error::other("Nightly session state changed; leaving it intact"));
}
std::fs::remove_file(&self.path)
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicU64, Ordering};
struct Fixture(PathBuf);
impl Fixture {
fn new() -> Self {
static NEXT: AtomicU64 = AtomicU64::new(0);
loop {
let path =
std::env::temp_dir().join(format!("figcraft-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 busy_secondary_reports_unavailable_without_replacing_the_owner_record() {
let fixture = Fixture::new();
let (stable, warning) = Session::begin_with_health(None, "stable", None).unwrap();
assert!(stable.is_none() && !warning);
let (first, warning) = Session::begin_with_health(Some(&fixture.0), "nightly", Some("owned-commit")).unwrap();
assert!(!warning);
let first = first.unwrap();
let record = std::fs::read(fixture.0.join(RECORD)).unwrap();
let (secondary, warning) = Session::begin_with_health(Some(&fixture.0), "secondary", None).unwrap();
assert!(secondary.is_none() && warning, "a secondary window cannot claim recorded exit/crash coverage");
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), record);
first.complete().unwrap();
assert!(!fixture.0.join(RECORD).exists());
}
#[test]
fn controlled_completion_is_clean_but_an_unfinished_owner_is_reported_next_time() {
let fixture = Fixture::new();
let first = Session::begin(Some(&fixture.0), "first", Some("recorded-commit")).unwrap().unwrap();
assert!(!first.previous_unclean());
let own = std::fs::read(fixture.0.join(RECORD)).unwrap();
assert!(Session::begin(Some(&fixture.0), "secondary", None).unwrap().is_none());
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), own, "a busy secondary must not replace the owner's record");
first.complete().unwrap();
assert!(!fixture.0.join(RECORD).exists());
let unfinished = Session::begin(Some(&fixture.0), "second", None).unwrap().unwrap();
assert!(!unfinished.previous_unclean());
drop(unfinished); // Unwind/abnormal-path ownership release, not a controlled completion.
let next = Session::begin(Some(&fixture.0), "third", None).unwrap().unwrap();
assert!(next.previous_unclean());
next.complete().unwrap();
assert!(!fixture.0.join(RECORD).exists());
}
#[test]
fn an_interruption_no_window_showed_survives_a_handled_startup_failure() {
let fixture = Fixture::new();
drop(Session::begin(Some(&fixture.0), "crashed", None).unwrap().unwrap());
// Renderer initialization failed before the app callback: no notice was shown.
let failed = Session::begin(Some(&fixture.0), "gpu-failed", None).unwrap().unwrap();
assert!(failed.previous_unclean());
failed.finish(false).unwrap();
let retry = Session::begin(Some(&fixture.0), "renderer-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 the_exit_hook_and_the_return_path_finish_the_session_once() {
let fixture = Fixture::new();
let shared: Shared = Arc::new(Mutex::new(Session::begin(Some(&fixture.0), "quitting", None).unwrap()));
// The exit hook (macOS quit: the only path that runs there).
finish_once(&shared, false);
assert!(!fixture.0.join(RECORD).exists(), "a quit that ran the exit hook is a clean exit");
// Elsewhere the return path runs too, by then possibly after a successor took the profile.
let successor = Session::begin(Some(&fixture.0), "successor", None).unwrap().unwrap();
assert!(!successor.previous_unclean());
let record = std::fs::read(fixture.0.join(RECORD)).unwrap();
finish_once(&shared, false);
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), record, "the second finish must not touch a successor's record");
successor.complete().unwrap();
}
#[test]
fn 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_document_paths_or_diagnostics() {
let fixture = Fixture::new();
assert!(Session::begin(Some(&fixture.0), &"x".repeat(MAX_METADATA_BYTES + 1), None).is_err());
assert_eq!(std::fs::read_dir(&fixture.0).unwrap().count(), 0);
assert!(Session::begin(None, "", None).unwrap().is_none(), "stable has no session-health side effects");
let watch = Session::begin(Some(&fixture.0), "nightly", None).unwrap().unwrap();
let data: serde_json::Value = serde_json::from_slice(&std::fs::read(fixture.0.join(RECORD)).unwrap()).unwrap();
let fields = data.as_object().unwrap().keys().map(String::as_str).collect::<std::collections::BTreeSet<_>>();
assert_eq!(fields, ["schema_version", "channel", "version", "commit"].into_iter().collect());
assert!(data["commit"].is_null(), "missing provenance must not be invented");
watch.complete().unwrap();
}
#[test]
#[cfg(unix)]
fn reserved_state_aliases_do_not_modify_external_files() {
let fixture = Fixture::new();
let external = fixture.0.join("stable-document");
std::fs::write(&external, b"stable bytes").unwrap();
for name in [LEASE, RECORD] {
let alias = fixture.0.join(name);
std::os::unix::fs::symlink(&external, &alias).unwrap();
assert!(Session::begin(Some(&fixture.0), "nightly", None).is_err());
assert_eq!(std::fs::read(&external).unwrap(), b"stable bytes");
std::fs::remove_file(alias).unwrap();
}
}
#[test]
#[cfg(unix)]
fn the_record_writer_refuses_links_at_the_destination_and_at_its_temporary_name() {
let fixture = Fixture::new();
let external = fixture.0.join("outside.json");
std::fs::write(&external, b"outside bytes").unwrap();
let destination = fixture.0.join(RECORD);
std::os::unix::fs::symlink(&external, &destination).unwrap();
atomic_write_no_follow(&destination, b"nightly bytes").unwrap();
assert_eq!(std::fs::read(&external).unwrap(), b"outside bytes", "the link's target is never written");
assert_eq!(std::fs::read(&destination).unwrap(), b"nightly bytes");
let mut temporary = destination.clone();
temporary.set_extension("json.tmp");
std::os::unix::fs::symlink(&external, &temporary).unwrap();
atomic_write_no_follow(&destination, b"next bytes").unwrap();
assert_eq!(std::fs::read(&external).unwrap(), b"outside bytes", "a planted temporary link is not followed");
assert_eq!(std::fs::read(&destination).unwrap(), b"next bytes");
}
}
+63
View File
@@ -0,0 +1,63 @@
//! Set the immutable nightly Windows identity before any native window or COM service.
//! Stable deliberately leaves its implicit shortcut/path identity unchanged.
use std::sync::OnceLock;
pub fn initialize(nightly: bool, app_id: &str) -> Result<(), String> {
configure(nightly && cfg!(windows), app_id, |id| {
static RESULT: OnceLock<Result<(), String>> = OnceLock::new();
RESULT
.get_or_init(|| {
#[cfg(windows)]
{
winsafe::SetCurrentProcessExplicitAppUserModelID(id)
.map_err(|error| format!("cannot set the nightly Windows identity: {error}"))?;
let actual = winsafe::GetCurrentProcessExplicitAppUserModelID()
.map_err(|error| format!("cannot read back the nightly Windows identity: {error}"))?;
if actual != id {
return Err("the native Windows identity did not match the selected nightly channel".into());
}
Ok(())
}
#[cfg(not(windows))]
{
let _ = id;
Ok(())
}
})
.clone()
})
}
fn configure(explicit_nightly: bool, app_id: &str, set: impl FnOnce(&str) -> Result<(), String>) -> Result<(), String> {
if explicit_nightly { set(app_id) } else { Ok(()) }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn stable_does_not_call_the_explicit_identity_api() {
configure(false, "nightly-id", |_| panic!("stable identity must remain implicit")).unwrap();
}
#[test]
fn nightly_applies_the_supplied_identity_once() {
let calls = std::cell::Cell::new(0);
configure(true, "nightly-id", |id| {
assert_eq!(id, "nightly-id");
calls.set(calls.get() + 1);
Ok(())
})
.unwrap();
assert_eq!(calls.get(), 1);
}
#[test]
fn native_identity_failure_is_returned_instead_of_starting_a_window() {
let started = std::cell::Cell::new(false);
let result = configure(true, "nightly-id", |_| Err("native identity refused".into())).map(|()| started.set(true));
assert_eq!(result.unwrap_err(), "native identity refused");
assert!(!started.get());
}
}
+709
View File
@@ -0,0 +1,709 @@
//! App-owned nightly profile fences; no stable fallback, migration or process environment changes.
use std::ffi::OsString;
use std::path::{Component, Path, PathBuf};
/// The portable marker and folder FigCraft already uses (`craft_settings::Portable::DEFAULT`): a
/// `portable` file beside the executable keeps the settings in `config/` beside it.
const PORTABLE_MARKER: &str = "portable";
/// The Nightly's own Flatpak id: its sandbox is its own, so it is not the stable app's instance.
const NIGHTLY_FLATPAK_ID: &str = "ai.storyteller.figcraft.nightly";
/// The Linux wrapper's record of an XDG base it overrode (`FIGCRAFT_STABLE_XDG_CONFIG_HOME`, ...).
const STABLE_XDG_KEY_PREFIX: &str = "FIGCRAFT_STABLE_";
/// What a portable copy holds beside its marker.
const PORTABLE_EXES: [&str; 3] = ["figcraft.exe", "figcraft", "FigCraft.app"];
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Platform {
Windows,
Linux,
Mac,
}
impl Platform {
fn current() -> Result<Self, String> {
match std::env::consts::OS {
"windows" => Ok(Self::Windows),
"linux" => Ok(Self::Linux),
"macos" => Ok(Self::Mac),
_ => Err("nightly-v1 is not defined for this operating system".into()),
}
}
fn ignores_case(self) -> bool {
self != Self::Linux
}
}
fn absolute(path: PathBuf, label: &str) -> Result<PathBuf, String> {
if !path.is_absolute() || path.components().any(|c| matches!(c, Component::ParentDir)) {
return Err(format!("{label} must be absolute and contain no parent traversal"));
}
Ok(path)
}
fn required_base(env: &impl Fn(&str) -> Option<OsString>, key: &str) -> Result<PathBuf, String> {
let value = env(key).filter(|v| !v.is_empty()).ok_or_else(|| format!("cannot establish the stable {key} boundary"))?;
absolute(PathBuf::from(value), key)
}
fn xdg_base(env: &impl Fn(&str) -> Option<OsString>, key: &str, fallback: &str) -> Result<PathBuf, String> {
match env(key).filter(|v| !v.is_empty()) {
Some(value) => absolute(PathBuf::from(value), key),
None => Ok(required_base(env, "HOME")?.join(fallback)),
}
}
/// Resolve existing ancestors before creating anything. A dangling link or inaccessible ancestor
/// is not a missing directory that may be replaced or followed later.
fn canonical_future(path: &Path) -> Result<PathBuf, String> {
let mut parent = path;
let mut missing = Vec::new();
loop {
match std::fs::symlink_metadata(parent) {
Ok(_) => break,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
missing.push(parent.file_name().ok_or("the profile root has no existing ancestor")?.to_os_string());
parent = parent.parent().ok_or("the profile root has no existing ancestor")?;
}
Err(error) => return Err(format!("cannot inspect the profile boundary: {error}")),
}
}
let mut resolved = std::fs::canonicalize(parent).map_err(|e| format!("cannot resolve the profile boundary: {e}"))?;
for part in missing.into_iter().rev() {
resolved.push(part);
}
Ok(resolved)
}
fn overlaps(a: &Path, b: &Path, platform: Platform) -> bool {
let parts = |p: &Path| {
p.components()
.map(|c| {
let value = c.as_os_str().to_string_lossy().into_owned();
if platform.ignores_case() { value.to_lowercase() } else { value }
})
.collect::<Vec<_>>()
};
let (a, b) = (parts(a), parts(b));
a.starts_with(&b) || b.starts_with(&a)
}
fn installation_boundary(platform: Platform, exe: &Path) -> Result<PathBuf, String> {
let parent = exe.parent().ok_or("cannot establish the installation boundary")?;
if platform == Platform::Mac {
// A profile in Resources is still inside the versioned install, not beside MacOS.
if let Some(bundle) = exe.ancestors().find(|p| p.extension().is_some_and(|ext| ext.eq_ignore_ascii_case("app"))) {
return Ok(bundle.to_path_buf());
}
}
Ok(parent.to_path_buf())
}
/// Every stable data root of this app (the settings folder `services::config_dir` uses, the
/// installer's folders), so a nightly profile can never read or sweep stable user 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 => {
let mut roots = ["APPDATA", "LOCALAPPDATA"]
.into_iter()
.map(|key| required_base(env, key).map(|p| p.join("FigCraft")))
.collect::<Result<Vec<_>, _>>()?;
// The MSI's per-user folder (figcraft.wxs installs under ArtCraft). 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("FigCraft"));
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("FigCraft"));
}
}
roots
}
Platform::Linux => {
// The settings folder is `<platform config>/FigCraft`; the other XDG folders hold no
// FigCraft state today, but a copy that starts writing there must not become readable.
// The Linux wrapper (`packaging/linux/nightly-launch.sh`) points XDG_CONFIG_HOME and
// XDG_DATA_HOME at per-channel folders and passes the bases in effect before that
// override as STABLE_XDG_KEY_PREFIX + key, so the stable folders under them stay fenced.
let mut roots = Vec::new();
for (key, fallback) in
[("XDG_CONFIG_HOME", ".config"), ("XDG_DATA_HOME", ".local/share"), ("XDG_CACHE_HOME", ".cache"), ("XDG_STATE_HOME", ".local/state")]
{
let mut bases = vec![xdg_base(env, key, fallback)?];
let stable_key = format!("{STABLE_XDG_KEY_PREFIX}{key}");
if let Some(value) = env(&stable_key).filter(|v| !v.is_empty()) {
bases.push(absolute(PathBuf::from(value), &stable_key)?);
}
for base in bases {
roots.push(base.join("FigCraft"));
roots.push(base.join("figcraft"));
}
}
roots.extend(["/usr/bin/figcraft", "/usr/local/bin/figcraft", "/opt/figcraft"].map(PathBuf::from));
// The stable Flatpak keeps its data in its own per-app folder.
roots.push(required_base(env, "HOME")?.join(".var/app/ai.storyteller.figcraft"));
roots
}
Platform::Mac => {
let home = required_base(env, "HOME")?;
let library = home.join("Library");
vec![
library.join("Application Support/FigCraft"),
library.join("Caches/FigCraft"),
library.join("Preferences/FigCraft"),
library.join("Preferences/ai.storyteller.figcraft.plist"),
library.join("Saved Application State/ai.storyteller.figcraft.savedState"),
home.join("Applications/FigCraft.app"),
PathBuf::from("/Applications/FigCraft.app"),
]
}
};
roots.push(installation_boundary(platform, exe)?);
roots.into_iter().map(|p| canonical_future(&p)).collect()
}
fn private_subdirectory(root: &Path, name: impl AsRef<Path>, label: &str) -> 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 (Plugins, logs, settings 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(())
}
/// A portable FigCraft copy: the marker file beside the executable (or the `.app` on macOS).
fn portable_copy(dir: &Path) -> bool {
dir.join(PORTABLE_MARKER).is_file() && PORTABLE_EXES.iter().any(|exe| dir.join(exe).exists())
}
/// The portable layout in both the supplied and resolved path: the chosen folder itself or any
/// ancestor is a portable copy. A marker only counts beside a FigCraft executable, so an unrelated
/// `portable` file higher up (in a user folder or at a drive root) does not refuse the profile, and
/// a folder merely named `config` (the XDG configuration folder holds the Launcher's profiles) is
/// not a portable settings folder.
fn is_portable_layout(path: &Path) -> bool {
path.ancestors().any(portable_copy)
}
/// The app's exclusive write probe: the nightly profile must be writable without touching any
/// stable folder, and a failed probe never falls back to the stable settings folder. Each attempt
/// uses a fresh name, so a probe left by a killed run (or a concurrent one) never blocks a writable
/// profile, and only the entry this attempt created is removed.
pub fn ensure_writable(dir: &Path) -> std::io::Result<()> {
use std::sync::atomic::{AtomicU64, Ordering};
static NEXT: AtomicU64 = AtomicU64::new(0);
let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_nanos());
for _ in 0..16 {
let probe = dir.join(format!("nightly-write-probe-{}-{nanos}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
match std::fs::OpenOptions::new().write(true).create_new(true).open(&probe) {
Ok(file) => {
drop(file);
return std::fs::remove_file(probe);
}
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
Err(error) => return Err(error),
}
}
Err(std::io::Error::new(std::io::ErrorKind::AlreadyExists, "no fresh name for the nightly write probe"))
}
/// The writable hook is injected so filesystem boundary tests exercise the real policy without
/// starting the app or changing global state.
pub fn validate(
root: &Path,
env: impl Fn(&str) -> Option<OsString>,
exe: Option<&Path>,
writable: impl FnOnce(&Path) -> std::io::Result<()>,
) -> Result<PathBuf, String> {
validate_for(Platform::current()?, root, env, exe, writable)
}
fn validate_for(
platform: Platform,
root: &Path,
env: impl Fn(&str) -> Option<OsString>,
exe: Option<&Path>,
writable: impl FnOnce(&Path) -> std::io::Result<()>,
) -> Result<PathBuf, String> {
absolute(root.to_path_buf(), "the nightly profile root")?;
if env("FIGCRAFT_CONFIG_DIR").is_some_and(|v| !v.is_empty()) {
return Err("nightly-v1 cannot be combined with FIGCRAFT_CONFIG_DIR".into());
}
if platform != Platform::Windows {
// A native tar/app-bundle launch must not inherit another app's Flatpak runtime namespace,
// which could point this profile at the stable app's socket. The Nightly's own Flatpak
// bundle (ai.storyteller.figcraft.nightly) is a separate sandbox and is allowed.
let flatpak = env("FLATPAK_ID").filter(|v| !v.is_empty());
if let Some(id) = flatpak
&& id != NIGHTLY_FLATPAK_ID
{
return Err("nightly-v1 cannot inherit another app's Flatpak instance; use its own package or the native Launcher".into());
}
}
let chosen = canonical_future(root)?;
if is_portable_layout(root) || is_portable_layout(&chosen) {
return Err("the nightly root must not use a portable FigCraft installation or its config folder".into());
}
let exe = absolute(exe.ok_or("cannot establish the installation boundary")?.to_path_buf(), "the executable")?;
let forbidden = forbidden_roots(platform, &env, &exe)?;
if forbidden.iter().any(|stable| overlaps(&chosen, stable, platform)) {
return Err("the nightly root must not overlap stable data or an installation".into());
}
entries_stay_inside(&chosen)?;
// Recovery can read, adopt, overwrite and sweep entries. Never let its alias leave this
// private profile, including toward a stable portable folder not in our known roots.
private_subdirectory(&chosen, "Recovery", "recovery folder")?;
let mut create = std::fs::DirBuilder::new();
create.recursive(true);
#[cfg(unix)]
{
use std::os::unix::fs::DirBuilderExt as _;
create.mode(0o700);
}
create.create(&chosen).map_err(|e| format!("cannot create the nightly profile: {e}"))?;
let confirmed = std::fs::canonicalize(&chosen).map_err(|e| format!("cannot resolve the created nightly profile: {e}"))?;
if confirmed != chosen || forbidden.iter().any(|stable| overlaps(&confirmed, stable, platform)) {
return Err("the nightly profile changed while it was being validated".into());
}
private_subdirectory(&confirmed, "Recovery", "recovery folder")?;
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::collections::BTreeMap;
use std::sync::atomic::{AtomicU64, Ordering};
/// The portable settings folder beside a portable copy's executable.
const PORTABLE_DIR: &str = "config";
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!("figcraft-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/figcraft");
std::fs::create_dir_all(&home).unwrap();
std::fs::create_dir_all(exe.parent().unwrap()).unwrap();
std::fs::write(&exe, b"fixture executable, never run").unwrap();
let env = [("HOME", home), ("APPDATA", root.join("roaming")), ("LOCALAPPDATA", root.join("local"))]
.into_iter()
.map(|(key, value)| (key.into(), value.into_os_string()))
.collect();
Self { root, env, exe }
}
fn get(&self, key: &str) -> Option<OsString> {
self.env.get(key).cloned()
}
fn check(&self, platform: Platform, root: &Path) -> Result<PathBuf, String> {
validate_for(
platform,
root,
|key| self.get(key),
Some(&self.exe),
|dir| {
let probe = dir.join("exclusive-test-probe");
let file = std::fs::OpenOptions::new().write(true).create_new(true).open(&probe)?;
drop(file);
std::fs::remove_file(probe)
},
)
}
fn home(&self) -> PathBuf {
PathBuf::from(self.get("HOME").unwrap())
}
}
impl Drop for Fixture {
fn drop(&mut self) {
// Only the directory successfully created by this fixture is owned for removal.
std::fs::remove_dir_all(&self.root).unwrap();
}
}
#[test]
fn a_portable_copy_and_its_config_folder_are_refused_before_any_probe() {
let fixture = Fixture::new();
let stable_install = fixture.root.join("stable portable install");
let stable_data = stable_install.join(PORTABLE_DIR);
std::fs::create_dir_all(&stable_data).unwrap();
std::fs::write(stable_install.join(PORTABLE_MARKER), b"owned portable fixture").unwrap();
std::fs::write(stable_install.join("figcraft.exe"), b"portable copy, never run").unwrap();
std::fs::write(stable_data.join("state.json"), b"stable settings must not change").unwrap();
for platform in [Platform::Windows, Platform::Linux, Platform::Mac] {
for candidate in [&stable_data, &stable_data.join("nested nightly")] {
let probed = std::cell::Cell::new(false);
let result = validate_for(
platform,
candidate,
|key| fixture.get(key),
Some(&fixture.exe),
|_| {
probed.set(true);
Ok(())
},
);
assert!(result.is_err(), "a different portable install is not a private Nightly profile");
assert!(!probed.get(), "reject portable data before a writable probe");
assert!(!stable_data.join("nested nightly").exists());
assert_eq!(std::fs::read(stable_data.join("state.json")).unwrap(), b"stable settings must not change");
}
}
let private = fixture.root.join("figcraft-data-backup/nightly");
assert!(fixture.check(Platform::Linux, &private).is_ok(), "a merely similar name is not a portable copy");
}
#[cfg(unix)]
#[test]
fn recovery_aliases_cannot_redirect_to_stable_missing_or_profile_root_data() {
let fixture = Fixture::new();
let stable = fixture.home().join(".config/FigCraft/Recovery");
std::fs::create_dir_all(&stable).unwrap();
std::fs::write(stable.join("stable-autosave"), b"stable recovery bytes").unwrap();
for (index, target) in [stable.clone(), fixture.root.join("missing recovery target")].into_iter().enumerate() {
let private = fixture.root.join(format!("nightly-{index}"));
std::fs::create_dir(&private).unwrap();
std::os::unix::fs::symlink(&target, private.join("Recovery")).unwrap();
let probed = std::cell::Cell::new(false);
let result = validate_for(
Platform::Linux,
&private,
|key| fixture.get(key),
Some(&fixture.exe),
|_| {
probed.set(true);
Ok(())
},
);
assert!(result.is_err(), "Recovery must not escape the private profile or follow a dangling alias");
assert!(!probed.get());
}
let private = fixture.root.join("nightly-self");
std::fs::create_dir(&private).unwrap();
std::os::unix::fs::symlink(&private, private.join("Recovery")).unwrap();
assert!(fixture.check(Platform::Linux, &private).is_err(), "Recovery cannot treat all profile settings as recovery entries");
assert_eq!(std::fs::read(stable.join("stable-autosave")).unwrap(), b"stable recovery bytes");
}
#[cfg(unix)]
#[test]
fn recovery_alias_to_a_private_subfolder_keeps_the_profile_usable() {
let fixture = Fixture::new();
let private = fixture.root.join("nightly-private");
let recovery = private.join("private-recovery");
std::fs::create_dir_all(&recovery).unwrap();
std::os::unix::fs::symlink(&recovery, private.join("Recovery")).unwrap();
assert!(fixture.check(Platform::Linux, &private).is_ok());
assert_eq!(std::fs::canonicalize(private.join("Recovery")).unwrap(), recovery);
}
#[test]
fn the_stable_settings_folder_and_its_ancestors_are_refused() {
let fixture = Fixture::new();
// Each platform fences the folder its own stable build resolves (`services::platform_dir`):
// `%APPDATA%` on Windows, `~/.config` on Linux and Application Support on macOS.
let stable_folders = [
(Platform::Windows, fixture.root.join("roaming/FigCraft")),
(Platform::Linux, fixture.home().join(".config/FigCraft")),
(Platform::Mac, fixture.home().join("Library/Application Support/FigCraft")),
];
for (platform, stable) in stable_folders {
std::fs::create_dir_all(&stable).unwrap();
std::fs::write(stable.join("state.json"), b"stable settings").unwrap();
for root in [stable.clone(), stable.join("nightly")] {
let calls = std::cell::Cell::new(0);
let result = validate_for(
platform,
&root,
|key| fixture.get(key),
Some(&fixture.exe),
|_| {
calls.set(calls.get() + 1);
Ok(())
},
);
assert!(result.unwrap_err().contains("overlap"));
assert_eq!(calls.get(), 0);
}
assert_eq!(std::fs::read(stable.join("state.json")).unwrap(), b"stable settings");
}
}
#[test]
fn overlap_check_handles_ancestor_descendant_and_prefix_lookalikes() {
let fixture = Fixture::new();
let root = fixture.home().join("nightly/profiles/figcraft");
for platform in [Platform::Windows, Platform::Linux, Platform::Mac] {
assert!(overlaps(&root, &root.join("Recovery"), platform));
assert!(overlaps(&root.join("Recovery"), &root, platform));
assert!(!overlaps(&root, &root.with_file_name("figcraft-other"), platform));
}
}
#[test]
fn linux_fences_app_xdg_subtrees_but_allows_launcher_sibling() {
let mut fixture = Fixture::new();
for key in ["XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME"] {
fixture.env.insert(key.into(), fixture.root.join(key).into_os_string());
}
for key in ["XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME"] {
for name in ["FigCraft", "figcraft"] {
let stable = PathBuf::from(fixture.get(key).unwrap()).join(name);
std::fs::create_dir_all(&stable).unwrap();
std::fs::write(stable.join("stable-sentinel"), b"stable bytes").unwrap();
for candidate in [stable.clone(), stable.join("nightly")] {
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("overlap"));
}
assert_eq!(std::fs::read(stable.join("stable-sentinel")).unwrap(), b"stable bytes");
}
}
let data = PathBuf::from(fixture.get("XDG_DATA_HOME").unwrap());
let nightly = data.join("ArtCraftLauncher/nightly/profiles/figcraft");
assert_eq!(fixture.check(Platform::Linux, &nightly).unwrap(), nightly);
assert_eq!(std::fs::read_dir(nightly).unwrap().count(), 0);
}
#[test]
fn mac_fences_only_app_library_subtrees_and_the_entire_bundle() {
let mut fixture = Fixture::new();
fixture.exe = fixture.root.join("install/FigCraft Nightly.app/Contents/MacOS/FigCraft");
std::fs::create_dir_all(fixture.exe.parent().unwrap()).unwrap();
std::fs::write(&fixture.exe, b"fixture executable, never run").unwrap();
let library = fixture.home().join("Library");
for suffix in [
"Application Support/FigCraft",
"Caches/FigCraft",
"Preferences/FigCraft",
"Preferences/ai.storyteller.figcraft.plist",
"Saved Application State/ai.storyteller.figcraft.savedState",
] {
let stable = library.join(suffix);
assert!(fixture.check(Platform::Mac, &stable.join("nightly")).unwrap_err().contains("overlap"));
assert!(!stable.exists());
}
let inside_resources = fixture.exe.parent().unwrap().parent().unwrap().join("Resources/profile");
assert!(fixture.check(Platform::Mac, &inside_resources).unwrap_err().contains("overlap"));
assert!(!inside_resources.exists());
let valid = library.join("Application Support/ArtCraftLauncher/nightly/profiles/figcraft");
assert_eq!(fixture.check(Platform::Mac, &valid).unwrap(), valid);
}
#[test]
fn windows_roaming_local_and_install_fences_remain_active() {
let fixture = Fixture::new();
for key in ["APPDATA", "LOCALAPPDATA"] {
let stable = PathBuf::from(fixture.get(key).unwrap()).join("FigCraft");
assert!(fixture.check(Platform::Windows, &stable.join("nightly")).unwrap_err().contains("overlap"));
assert!(!stable.exists());
}
assert!(fixture.check(Platform::Windows, &fixture.exe.parent().unwrap().join("profile")).is_err());
assert!(fixture.check(Platform::Windows, &fixture.root.join("Launcher/profiles/figcraft")).is_ok());
}
#[test]
fn windows_default_msi_install_folders_are_fenced() {
let mut fixture = Fixture::new();
let local = PathBuf::from(fixture.get("LOCALAPPDATA").unwrap());
let per_user = local.join("Programs").join("ArtCraft").join("FigCraft");
assert!(fixture.check(Platform::Windows, &per_user.join("nightly")).unwrap_err().contains("overlap"));
for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] {
let base = fixture.root.join(format!("machine {key}"));
fixture.env.insert(key.into(), base.clone().into_os_string());
let machine = base.join("ArtCraft").join("FigCraft");
assert!(fixture.check(Platform::Windows, &machine.join("nightly")).unwrap_err().contains("overlap"));
assert!(!machine.exists());
}
let sibling = local.join("Programs").join("ArtCraft").join("ArtCraftLauncher").join("nightly").join("figcraft");
assert!(fixture.check(Platform::Windows, &sibling).is_ok(), "the Launcher's own Programs sibling is not FigCraft's install");
}
#[test]
fn a_marker_that_no_figcraft_copy_sits_beside_is_someone_elses_file() {
let fixture = Fixture::new();
let unrelated = fixture.root.join("user folder");
std::fs::create_dir_all(&unrelated).unwrap();
std::fs::write(unrelated.join(PORTABLE_MARKER), b"another app's marker").unwrap();
assert!(fixture.check(Platform::Windows, &unrelated.join("Launcher/nightly/figcraft")).is_ok());
// Beside a FigCraft executable, the same marker makes it a portable copy.
std::fs::write(unrelated.join("figcraft.exe"), b"portable copy, never run").unwrap();
assert!(fixture.check(Platform::Windows, &unrelated.join("nightly")).unwrap_err().contains("portable"));
}
#[cfg(unix)]
#[test]
fn linux_wrapper_override_keeps_the_stable_xdg_folders_fenced() {
let mut fixture = Fixture::new();
// What the wrapper exports with XDG_CONFIG_HOME and XDG_DATA_HOME unset.
let (config_base, data_base) = (fixture.home().join(".config"), fixture.home().join(".local/share"));
for (key, base) in [("XDG_CONFIG_HOME", &config_base), ("XDG_DATA_HOME", &data_base)] {
fixture.env.insert(key.into(), base.join("figcraft-nightly").into_os_string());
fixture.env.insert(format!("{STABLE_XDG_KEY_PREFIX}{key}"), base.clone().into_os_string());
}
let stable = config_base.join("FigCraft");
std::fs::create_dir_all(&stable).unwrap();
std::fs::write(stable.join("state.json"), b"stable settings").unwrap();
let profile = data_base.join("figcraft-nightly/profile");
std::fs::create_dir_all(profile.parent().unwrap()).unwrap();
std::os::unix::fs::symlink(&stable, &profile).unwrap();
assert!(fixture.check(Platform::Linux, &profile).unwrap_err().contains("overlap"));
assert_eq!(std::fs::read_dir(&stable).unwrap().count(), 1, "nothing is written into the stable folder");
std::fs::remove_file(&profile).unwrap();
assert_eq!(fixture.check(Platform::Linux, &profile).unwrap(), profile, "a normal Nightly profile stays valid");
}
#[test]
fn a_leftover_write_probe_does_not_block_a_writable_profile() {
let fixture = Fixture::new();
let dir = fixture.home().join("nightly");
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("nightly-write-probe"), b"left by a killed run").unwrap();
ensure_writable(&dir).unwrap();
ensure_writable(&dir).unwrap();
let names: Vec<_> = std::fs::read_dir(&dir).unwrap().flatten().map(|e| e.file_name()).collect();
assert_eq!(names, ["nightly-write-probe"], "only this attempt's own probe is removed");
}
#[test]
fn linux_fences_the_stable_flatpak_data_folder() {
let fixture = Fixture::new();
let flatpak = fixture.home().join(".var/app/ai.storyteller.figcraft");
for candidate in [flatpak.clone(), flatpak.join("data/nightly")] {
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("overlap"));
}
assert!(!flatpak.exists());
assert!(fixture.check(Platform::Linux, &fixture.home().join(".var/app/ai.storyteller.launcher/nightly")).is_ok());
}
#[cfg(unix)]
#[test]
fn any_profile_entry_alias_must_stay_inside_the_profile() {
let fixture = Fixture::new();
let stable = fixture.home().join(".config/FigCraft/Plugins");
std::fs::create_dir_all(&stable).unwrap();
std::fs::write(stable.join("stable-plugin"), b"stable plugin bytes").unwrap();
for name in ["Plugins", "logs", "state.json"] {
let private = fixture.root.join(format!("nightly-{name}"));
std::fs::create_dir(&private).unwrap();
std::os::unix::fs::symlink(&stable, private.join(name)).unwrap();
let probed = std::cell::Cell::new(false);
let result = validate_for(
Platform::Linux,
&private,
|key| fixture.get(key),
Some(&fixture.exe),
|_| {
probed.set(true);
Ok(())
},
);
assert!(result.is_err(), "{name} must not lead outside the profile");
assert!(!probed.get());
}
let private = fixture.root.join("nightly-inside");
std::fs::create_dir_all(private.join("real-plugins")).unwrap();
std::fs::write(private.join("state.json"), b"{}").unwrap();
std::os::unix::fs::symlink(private.join("real-plugins"), private.join("Plugins")).unwrap();
assert!(fixture.check(Platform::Linux, &private).is_ok(), "regular files and links that stay inside are fine");
assert_eq!(std::fs::read(stable.join("stable-plugin")).unwrap(), b"stable plugin bytes");
}
#[test]
fn ambiguous_environment_and_non_native_sandbox_are_refused_before_creation() {
let mut fixture = Fixture::new();
let candidate = fixture.home().join("nightly/profiles/figcraft");
fixture.env.insert("XDG_CACHE_HOME".into(), "relative/cache".into());
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("absolute"));
fixture.env.remove("XDG_CACHE_HOME");
fixture.env.insert("FIGCRAFT_CONFIG_DIR".into(), fixture.home().join("custom-stable").into_os_string());
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("FIGCRAFT_CONFIG_DIR"));
fixture.env.remove("FIGCRAFT_CONFIG_DIR");
fixture.env.insert("FLATPAK_ID".into(), "ai.storyteller.figcraft".into());
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("Flatpak"));
// The Nightly's own Flatpak bundle is a separate sandbox: its profile is allowed.
fixture.env.insert("FLATPAK_ID".into(), NIGHTLY_FLATPAK_ID.into());
assert!(fixture.check(Platform::Linux, &fixture.home().join("nightly/profile")).is_ok());
fixture.env.remove("FLATPAK_ID");
fixture.env.remove("HOME");
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("HOME"));
assert!(!candidate.exists());
}
#[test]
fn non_directory_and_failed_write_probe_never_fall_back_to_stable() {
let fixture = Fixture::new();
let file = fixture.home().join("not-a-directory");
std::fs::write(&file, b"do not replace me").unwrap();
assert!(fixture.check(Platform::Linux, &file).is_err());
assert_eq!(std::fs::read(file).unwrap(), b"do not replace me");
let candidate = fixture.home().join("nightly");
let calls = std::cell::Cell::new(0);
let result = validate_for(
Platform::Linux,
&candidate,
|key| fixture.get(key),
Some(&fixture.exe),
|_| {
calls.set(calls.get() + 1);
Err(std::io::Error::new(std::io::ErrorKind::PermissionDenied, "injected write refusal"))
},
);
assert!(result.unwrap_err().contains("not writable"));
assert_eq!(calls.get(), 1);
assert!(!fixture.home().join(".config/FigCraft").exists());
}
#[cfg(unix)]
#[test]
fn symlink_and_dangling_aliases_cannot_create_or_modify_stable_data() {
use std::os::unix::fs::symlink;
let fixture = Fixture::new();
let stable = fixture.home().join(".config/FigCraft");
std::fs::create_dir_all(&stable).unwrap();
std::fs::write(stable.join("sentinel"), b"untouched").unwrap();
let alias = fixture.home().join("alias");
symlink(&stable, &alias).unwrap();
assert!(fixture.check(Platform::Linux, &alias.join("nightly")).unwrap_err().contains("overlap"));
let missing = fixture.home().join("missing-target");
let dangling = fixture.home().join("dangling");
symlink(&missing, &dangling).unwrap();
assert!(fixture.check(Platform::Linux, &dangling.join("nightly")).is_err());
assert!(!missing.exists());
assert!(!stable.join("nightly").exists());
assert_eq!(std::fs::read(stable.join("sentinel")).unwrap(), b"untouched");
}
}
+11 -2
View File
@@ -31,9 +31,18 @@ pub struct Desktop {
/// folder names), and craft-settings' app id: `FIGCRAFT_CONFIG_DIR` names another folder.
const APP_ID: &str = "FigCraft";
/// Where the preferences, recovery copies and installed plugins live ([`settings_dir`]).
/// Where the preferences, recovery copies and installed plugins live ([`settings_dir`]), or the
/// Nightly's private profile.
pub fn config_dir() -> Option<PathBuf> {
settings_dir(&craft_settings::Probe { platform_config_dir: platform_dir(), ..Default::default() })
config_dir_for(crate::launch_profile::current(), &craft_settings::Probe { platform_config_dir: platform_dir(), ..Default::default() })
}
/// The data root this launch uses: every piece of user state (the preferences and recent files,
/// the recovery copies, the installed plugins) hangs off it, so a Nightly build keeps all of it in
/// the profile the Launcher handed it and the stable app's folder is never read or written.
/// Stable resolves the folder exactly as it always did.
pub(crate) fn config_dir_for(profile: &crate::launch_profile::Profile, probe: &craft_settings::Probe) -> Option<PathBuf> {
profile.root().map(Path::to_path_buf).or_else(|| settings_dir(probe))
}
/// The platform's config folder, read from the environment as before: `%APPDATA%` on Windows,
+23 -1
View File
@@ -9,7 +9,8 @@ use std::sync::{Arc, Mutex};
use craft_settings::Probe;
use figcraft_engine::Prefs;
use crate::services::{Desktop, settings_dir, write_prefs};
use crate::launch_profile::Profile;
use crate::services::{Desktop, config_dir_for, settings_dir, write_prefs};
/// A fresh temporary folder with an `app` folder (the executable's) and an `appdata` folder (the
/// platform's config folder).
@@ -99,3 +100,24 @@ fn without_a_platform_folder_there_are_no_settings() {
assert_eq!(settings_dir(&probe(&root, None, None)), None, "not the current directory");
let _ = std::fs::remove_dir_all(&root);
}
/// A Nightly keeps every part of its user state in the profile the Launcher validated, whatever
/// the stable rules would say: the preferences, the recovery copies and the plugins all hang off
/// this one folder (`config_dir`), so the stable app's folder is never read or written.
#[test]
fn a_nightly_profile_replaces_every_stable_data_root() {
let root = root("nightly");
let profile = root.join("profiles").join("figcraft");
let stable = root.join("appdata").join("FigCraft");
write_prefs(&stable, &prefs("stable user"));
// The portable marker would decide for a stable start; the profile decides instead.
std::fs::write(root.join("app").join("portable"), "").unwrap();
let rules = probe(&root, Some(root.join("appdata")), None);
assert_eq!(config_dir_for(&Profile::Stable, &rules), Some(root.join("app").join("config")));
let nightly = Profile::NightlyV1(profile.clone());
assert_eq!(config_dir_for(&nightly, &rules), Some(profile.clone()));
assert_eq!(nightly.root(), Some(profile.as_path()));
assert_eq!(loaded_name(profile), None, "the stable preferences are not carried over");
assert_eq!(loaded_name(stable), Some("stable user".into()), "and they stay where they were");
let _ = std::fs::remove_dir_all(&root);
}
+20
View File
@@ -39,3 +39,23 @@ image is not kept in this repo. License: see `LICENSE.txt`.
Replace `figcraft.svg` (and `figcraft-small.svg`), then run `cargo xtask icon`. It needs `resvg`
(`cargo install resvg`).
## Nightly icons
The Nightly build ships the same chameleon on a deeper field (`#019668`), so the two icons are
told apart at 16 px without a badge, crescent or letter. Nothing is upscaled: `figcraft-1024.png`
is the only input, each frame is an area average of it, and only the field's contribution to each
pixel moves (ink, paper, shading and alpha are untouched).
- `figcraft-nightly.png`: the 512 px frame the Linux packages use.
- `figcraft-nightly-<size>.png` (16–1024): the frames; `packaging/macos/nightly.sh` copies the
committed `figcraft-nightly.icns` into the bundle instead of building one on the runner.
- `figcraft-nightly.ico`: 32bpp DIB frames for 16–128 px and a PNG frame for 256; embedded in the
Nightly `.exe` by `apps/figcraft/build.rs`.
- `figcraft-nightly.icns`: PNG slots for 16–1024, including the @2x ones.
- `nightly-provenance.json`: the input and output hashes, the palette, the method and the
generator's own hash.
Regenerate with `python3 packaging/nightly-icons.py` (no image tool needed); `--check` reports
whether the committed files still match. `packaging/nightly-icon-tests.py` checks both containers,
the PNG CRCs and the provenance record.
Binary file not shown.

After

Width:  |  Height:  |  Size: 219 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 634 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 47 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 231 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.9 KiB

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 144 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 121 KiB

+58
View File
@@ -0,0 +1,58 @@
{
"title": "FigCraft nightly deep-background icons",
"author": "@skylartaylor",
"license": "MIT OR Apache-2.0",
"source_commit": "e2f19109c34cc1679ef1ef7421e484629c5de996",
"inputs": [
{
"path": "assets/app-icon/figcraft-1024.png",
"sha256": "e10adf0347b54ff05fce3baa707b7ca36e6d6cd47a35aa46a1f1c9c01390c598",
"purpose": "the padded macOS-grid master; every frame is an area average of it, none is upscaled"
}
],
"method": {
"kind": "generated derivative of the project-owned icon (packaging/nightly-icons.py)",
"original_palette": {
"ink": "#0b0b0c",
"paper": "#efe9dc",
"background": "#02da96"
},
"nightly_background": "#019668",
"transform": "Solve each pixel's field contribution from the palette (ink and paper are neutral, the field is saturated; the least-squares weight of the two colour differences), move that contribution to the deeper field and leave ink, paper, shading and alpha exactly as they are. The frames at 1024, 512, 256, 128, 64, 48, 32 and 16 px are premultiplied area averages of the master (the 48 px one is a fractional 21.33:1, not a crop). Windows frames are 32bpp DIBs up to 128 px plus one 256 px PNG; the macOS slots are PNG payloads. No badge, crescent or letter.",
"generator_sha256": "d8573ec68f3aed8269fee9d99db5fdaffa1a8c5d82a948f5d874af70bb218bcc"
},
"outputs": {
"assets/app-icon/figcraft-nightly-1024.png": "318da484eeb40dcd58dc3d70606e6efc044017c5421966cb3d6aee75f649491f",
"assets/app-icon/figcraft-nightly.png": "eb81423ad00afc91689c0cf4cd4d52aa3a2ebc60ca2dad41c52907c7490656c4",
"assets/app-icon/figcraft-nightly-256.png": "979401b2fb1f899052a3c8f9e9fab44305af823520b935f8fcf6f01f4aeca23f",
"assets/app-icon/figcraft-nightly-128.png": "9b8bb0bd3efbb93333540df7cf0592a3ae11691ea74a0da1bbcdeb75d7a95d52",
"assets/app-icon/figcraft-nightly-64.png": "4ef7d60239bc1521c8d71ad032396b51e045393d08c4228a632ab3693803cd0b",
"assets/app-icon/figcraft-nightly-48.png": "96fc32d251ab4f9688d0343ef805f92a53ca828e4c7a7de86b201f64602bce59",
"assets/app-icon/figcraft-nightly-32.png": "aac4f94dfcb310b9058a6ea66abacac034ead1e0366f0e6e347eb3d6b6ee47d5",
"assets/app-icon/figcraft-nightly-16.png": "3508f7d6124095a6a2c44ac55f41fffb1a495d25e3e4365afc4d1a2899cf7cfc",
"assets/app-icon/figcraft-nightly.ico": "7113c2a841e70ae15d4be47ec21e13fb7f5f62a99f461f3408ccbb0874ac6f63",
"assets/app-icon/figcraft-nightly.icns": "7f8fa9156c1b07d778e24094d047fbb3436e8f574ca49d74be905802ca063aff"
},
"ico_frame_sizes": [
16,
32,
48,
64,
128,
256
],
"icns_png_slots": {
"icp4": 16,
"icp5": 32,
"ic11": 32,
"icp6": 64,
"ic12": 64,
"ic07": 128,
"ic08": 256,
"ic13": 256,
"ic09": 512,
"ic14": 512,
"ic10": 1024
},
"validation": "The provenance hashes, the PNG CRCs and dimensions, and both container member lists are checked by packaging/nightly-icon-tests.py. Visual comparison against the stable icon was reviewed at 256, 48 and 16 px. Explorer, Finder and iconutil qualification of the packed containers remains unrun (no Windows or macOS host here)."
}
+71
View File
@@ -0,0 +1,71 @@
//! Which build channel this binary is: the stable app, or the Launcher-managed Nightly.
//!
//! The desktop app installs the Nightly identity once, before the first window, from its build
//! flavor ([`build_flavor`](crate) in the app crate) and the version it was built with. Everything
//! that names the app to the user (the window title, About) reads it here, so the two channels are
//! never mixed up in a caption or a taskbar. The web build and the tests keep the stable identity.
use std::sync::OnceLock;
struct Channel {
nightly: bool,
/// The version bundled into this build: the exact prepared Nightly version, else the Cargo one.
version: String,
/// The commit the Nightly was built from; `None` for the stable build.
commit: Option<String>,
}
static CHANNEL: OnceLock<Channel> = OnceLock::new();
fn channel() -> &'static Channel {
CHANNEL.get_or_init(|| Channel { nightly: false, version: crate::dialogs::VERSION.to_string(), commit: None })
}
/// Install the Nightly identity, once, with the version and commit the app was built with. Later
/// calls keep the first: a window cannot promote itself to another channel at run time.
pub fn install_nightly(version: impl Into<String>, commit: Option<impl Into<String>>) {
let _ = CHANNEL.set(Channel { nightly: true, version: version.into(), commit: commit.map(Into::into).filter(|c| !c.is_empty()) });
}
pub fn is_nightly() -> bool {
channel().nightly
}
/// The app's name: the window title, About and the launcher's dialog say "FigCraft Nightly" for
/// the Nightly build, so a window is never mistaken for the stable app's.
pub fn name() -> &'static str {
if is_nightly() { "FigCraft Nightly" } else { "FigCraft" }
}
/// The commit this Nightly was built from, for its About window and a bug report.
pub fn commit() -> Option<&'static str> {
channel().commit.as_deref()
}
/// A one-line identity for About and a bug report: the channel, and the commit a Nightly was
/// built from.
pub fn describe() -> String {
match (is_nightly(), commit()) {
(true, Some(commit)) => format!("{} · commit {commit}", name()),
_ => name().to_string(),
}
}
/// The bundled version as shown, tagged with the channel when it is the Nightly's.
pub fn version() -> String {
let version = &channel().version;
if is_nightly() { format!("{version} (nightly-v1)") } else { version.clone() }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn without_an_installed_identity_the_app_is_the_stable_one() {
// The other tests and the web build never install an identity.
assert!(!is_nightly());
assert_eq!(name(), "FigCraft");
assert_eq!(version(), crate::dialogs::VERSION);
}
}
+9 -1
View File
@@ -147,7 +147,15 @@ fn about_body(ui: &mut egui::Ui, t: &Tokens) {
ui.vertical(|ui| {
let (wordmark, _) = ui.allocate_exact_size(vec2(130.0, 23.0), Sense::hover());
crate::theme::paint_wordmark(ui.painter(), egui::pos2(wordmark.min.x, wordmark.center().y), 18.0, t);
ui.label(RichText::new(trf("Version {version}", &[("version", &VERSION)])).color(t.text_secondary));
let version = crate::channel::version();
ui.label(RichText::new(trf("Version {version}", &[("version", &version)])).color(t.text_secondary));
// Which channel this is, and where to report a problem with it: a Nightly is not the
// stable app, and its reports need the commit it was built from.
if crate::channel::is_nightly() {
let build = crate::channel::describe();
ui.label(RichText::new(build).color(t.text_secondary).font(regular(11.0)));
ui.hyperlink_to("Report a problem", "https://github.com/storytold/figcraft/issues/new/choose");
}
});
});
ui.add_space(12.0);
+51 -25
View File
@@ -10,8 +10,9 @@ use craft_update::updater::{Action, Status, Updater};
use craft_update::{CheckResultDialog, CheckResultResponse};
pub(crate) struct Runtime {
/// The updater; `None` for the Launcher-managed Nightly, which never updates itself.
#[cfg(not(target_arch = "wasm32"))]
updater: Updater,
updater: Option<Updater>,
/// The desktop app turns the check at start on; tests and the web build leave it off.
#[cfg(not(target_arch = "wasm32"))]
startup_check: bool,
@@ -32,7 +33,7 @@ impl Default for Runtime {
fn default() -> Self {
Self {
#[cfg(not(target_arch = "wasm32"))]
updater: Updater::new(&crate::UPDATE_APP, env!("CARGO_PKG_VERSION")),
updater: Some(Updater::new(&crate::UPDATE_APP, env!("CARGO_PKG_VERSION"))),
#[cfg(not(target_arch = "wasm32"))]
startup_check: false,
#[cfg(not(target_arch = "wasm32"))]
@@ -58,16 +59,31 @@ impl FigApp {
/// when it exits, before it ends the process; later calls do nothing.
#[cfg(not(target_arch = "wasm32"))]
pub fn start_pending_update(&mut self) {
self.updates_rt.updater.start_pending_update();
if let Some(updater) = self.updates_rt.updater.as_mut() {
updater.start_pending_update();
}
}
/// Never check for or install an update: the Launcher owns the Nightly's version. The desktop
/// app calls this before the first frame of a Nightly build, so nothing here reads or writes
/// the update pins.
#[cfg(not(target_arch = "wasm32"))]
pub fn disable_updates(&mut self) {
self.updates_rt.updater = None;
self.updates_rt.startup_check = false;
self.updates_rt.check_requested = false;
}
}
pub(crate) fn check(app: &mut FigApp) {
#[cfg(not(target_arch = "wasm32"))]
{
app.updates_rt.check_requested = true;
if let Some(ctx) = &app.updates_rt.repaint {
ctx.request_repaint();
// A build without an updater has no check to run (the Nightly is updated by the Launcher).
if app.updates_rt.updater.is_some() {
app.updates_rt.check_requested = true;
if let Some(ctx) = &app.updates_rt.repaint {
ctx.request_repaint();
}
}
}
#[cfg(target_arch = "wasm32")]
@@ -82,12 +98,15 @@ pub(crate) fn tick(app: &mut FigApp, ctx: &egui::Context) {
{
let rt = &mut app.updates_rt;
rt.repaint = Some(ctx.clone());
if std::mem::take(&mut rt.check_requested) {
rt.updater.check_now(ctx);
} else if rt.startup_check {
rt.updater.check_at_start(ctx);
let check_requested = std::mem::take(&mut rt.check_requested);
let startup_check = rt.startup_check;
let Some(updater) = rt.updater.as_mut() else { return };
if check_requested {
updater.check_now(ctx);
} else if startup_check {
updater.check_at_start(ctx);
}
rt.updater.tick(ctx);
updater.tick(ctx);
}
#[cfg(target_arch = "wasm32")]
let _ = (app, ctx);
@@ -106,21 +125,28 @@ pub(crate) fn show(app: &mut FigApp, ctx: &egui::Context) {
{
// The updater asks to close only when no document has unsaved changes; the install starts when the app exits.
let clean = !app.session.docs.iter().any(|d| d.is_dirty());
match app.updates_rt.updater.show_if(ctx, clean) {
Action::OpenUrl(url) => ctx.open_url(egui::OpenUrl::new_tab(url)),
// The whole application, not just the window that drew the prompt: the root window's guarded close.
Action::Close => ctx.send_viewport_cmd_to(egui::ViewportId::ROOT, egui::ViewportCommand::Close),
Action::None => {}
}
let rt = &mut app.updates_rt;
if result_window_shows(rt.updater.status(), rt.updater.prompt_open()) {
match CheckResultDialog::new(&crate::UPDATE_APP, env!("CARGO_PKG_VERSION")).show(ctx, rt.updater.status()) {
CheckResultResponse::None => {}
CheckResultResponse::Close => rt.updater.dismiss_status(),
CheckResultResponse::CheckAgain => rt.check_requested = true,
// The next `show_if` asks the window to close once no document has unsaved changes.
CheckResultResponse::RestartToUpdate => rt.updater.restart_to_update(),
let mut check_again = false;
let mut restart_to_update = false;
if let Some(updater) = app.updates_rt.updater.as_mut() {
match updater.show_if(ctx, clean) {
Action::OpenUrl(url) => ctx.open_url(egui::OpenUrl::new_tab(url)),
// The whole application, not just the window that drew the prompt: the root window's guarded close.
Action::Close => ctx.send_viewport_cmd_to(egui::ViewportId::ROOT, egui::ViewportCommand::Close),
Action::None => {}
}
if result_window_shows(updater.status(), updater.prompt_open()) {
match CheckResultDialog::new(&crate::UPDATE_APP, env!("CARGO_PKG_VERSION")).show(ctx, updater.status()) {
CheckResultResponse::None => {}
CheckResultResponse::Close => updater.dismiss_status(),
CheckResultResponse::CheckAgain => check_again = true,
// The next `show_if` asks the window to close once no document has unsaved changes.
CheckResultResponse::RestartToUpdate => restart_to_update = true,
}
}
}
app.updates_rt.check_requested |= check_again;
if restart_to_update && let Some(updater) = app.updates_rt.updater.as_mut() {
updater.restart_to_update();
}
}
+1
View File
@@ -17,6 +17,7 @@ pub const UPDATE_APP: craft_update::app::App = craft_update::app::App {
pub mod a11y;
pub mod bidi;
pub mod canvas;
pub mod channel;
pub mod cjk;
pub mod control;
pub mod dialogs;
+5
View File
@@ -338,6 +338,8 @@ fn help_button(app: &mut FigApp, ui: &mut Ui, canvas: Rect, pill: Rect, t: &Toke
ui.painter().circle_filled(hr.center(), 16.0, t.panel);
ui.painter().text(hr.center(), Align2::CENTER_CENTER, "?", crate::theme::regular(15.0), t.text);
crate::right::menu_popup(&hresp).show(|ui| {
// The Nightly has no update check: the Launcher keeps it on the version it installed.
let checks = !crate::channel::is_nightly();
for (l, c) in [
(tr("Getting started"), "help.gettingStarted"),
(tr("Keyboard shortcuts"), "help.shortcuts"),
@@ -345,6 +347,9 @@ fn help_button(app: &mut FigApp, ui: &mut Ui, canvas: Rect, pill: Rect, t: &Toke
(tr("Check for updates…"), "help.checkForUpdates"),
(tr("About FigCraft"), "help.about"),
] {
if c == "help.checkForUpdates" && !checks {
continue;
}
if crate::right::menu_item(ui, l, crate::shortcuts::shortcut(c).unwrap_or("")) {
crate::menus::invoke(app, c);
ui.close();
+5 -2
View File
@@ -190,9 +190,12 @@ pub(crate) fn fail_input_acks(app: &mut FigApp, viewport: ViewportId) {
}
fn title_of(ds: Option<&DocState>) -> String {
// The Nightly names itself in the caption and the taskbar, so two windows of the same file are
// never mistaken for each other (see `channel`).
let app = crate::channel::name();
match ds {
Some(ds) => format!("{}{} – FigCraft", ds.doc.name, if ds.is_dirty() { " •" } else { "" }),
None => "FigCraft".into(),
Some(ds) => format!("{}{} – {app}", ds.doc.name, if ds.is_dirty() { " •" } else { "" }),
None => app.into(),
}
}
+125
View File
@@ -0,0 +1,125 @@
# 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 or automatic completion dispatcher yet. The installed
policy [`.github/nightly-signing-policy.json`](../.github/nightly-signing-policy.json) is the v3 policy
for FigCraft. Once `nightly.yml` reaches `main`, populate `producer_workflow_id` before promoting the
policy to `release` by reading:
```bash
gh api repos/storytold/figcraft/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.
**The shared-workflow port is a prerequisite.** At this pin both reusable workflows admit only
PhotoCraft: `nightly-unsigned.yml` requires `inputs.app-name == 'photocraft'` and
`github.repository == 'storytold/photocraft'` on its build jobs, and `nightly-release.yml` requires the
same repository in `validate` and every signing job (its concurrency group is
`craft-release-ref-signer-photocraft`). A FigCraft dispatch therefore builds and signs nothing until
`storytold/craft-common-actions` admits `storytold/figcraft`. No dispatch can produce a release before
that port, and both callers' `uses`, `tooling-revision` and the policy pins must move to the same
reviewed revision together. The port is craft-common-actions #363 ("run the shared nightly pipeline
for any reviewed registry app"); until it merges these callers are inert.
**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.
**Admission timing.** The candidate check reads the newest CI run on the candidate commit and
main's latest finished Sonar analysis, so when to dispatch matters:
- Pick a quiet `main`, wait for its CI and SonarCloud analysis to finish green, then dispatch the
producer and, once it succeeds, the signer, before another `main` push lands a newer analysis.
**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), 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
| Field | Value | Source |
|---|---|---|
| `repository_id` | `1412112308` | `gh api repos/storytold/figcraft --jq .id` |
| `producer_workflow_id` | `null` (pending `nightly.yml` on `main`) | `gh api repos/storytold/figcraft/actions/workflows/nightly.yml --jq .id` once merged to `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; equals the producer caller's `manual-actors` |
| `max_age_seconds`, `max_artifact_bytes` | `86400`, `2147483648` | Go-live checklist |
| `platforms` | three rows | Storytold stable signing identities (`windows-x86_64`, `linux-x86_64`, `macos-aarch64`) |
| `candidate_policy.required_workflows` | CI (`ci.yml`, workflow `379864519`), `gate / gate (ubuntu-24.04)` | Workflow list API and latest `main` push CI run |
| `candidate_policy.sonar` | `storytold` / `storytold_figcraft`, app `12526` | `sonar-project.properties` |
| Sonar `issue_types` / `debt` | `VULNERABILITY` / `[]` | Refresh from SonarCloud before promoting policy to `release` |
The candidate check refuses whenever main's unresolved vulnerability set differs from `debt`, whether
an issue is new or fixed, and whenever a required condition fails or a listed CI job is renamed. Refresh
those values and `producer_workflow_id` in the same reviewed change that promotes the policy to `release`.
## Ownership and interface
- `.github/workflows/nightly.yml`: default-main registration of the unsigned producer, named
`FigCraft 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 (`figcraft-nightly-release`) is
distinct from stable and cancellation is off. 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.
- `packaging/windows/sign.ps1 -Required` is the app-owned Windows adapter. Invoke it only from the
immutable **release execution SHA** checkout, never the producer's main source or extracted archive.
## App-side entry points and the nightly profile
The producer's platform legs call these app-owned producers, each of which refuses signing material in
the compilation step:
| Platform | Producer | Signed by |
|---|---|---|
| Windows | `pwsh packaging/windows/package.ps1 -Arch x64 -Nightly -BuildOnly` (through `packaging/windows/nightly.ps1`) | `packaging/windows/sign.ps1 -Required` in the release-ref signer |
| Linux | `bash packaging/linux/nightly.sh --arch x86_64` | the shared signer's detached `.asc` (`.github/nightly-linux-signing-key.asc`) |
| macOS | `bash packaging/macos/nightly.sh --arch aarch64` | `packaging/macos/nightly-sign.sh`, checked by `packaging/macos/nightly-verify.sh` |
Inputs, all required: `FIGCRAFT_BUILD_CHANNEL=nightly-v1`, `FIGCRAFT_VERSION`
(`X.Y.Z-nightly.YYYYMMDD.<run>.<attempt>.g<sha12>`), `FIGCRAFT_BUILD_SHA` (40 hex) and
`FIGCRAFT_BUILD_DATE` (the run's UTC date), with an absolute `CARGO_TARGET_DIR` and `DIST`;
`CRAFT_FONTS_DIR`/`CRAFT_FONTS_REQUIRED=1` are optional. The build script refuses a nightly without
an exact version, so the feed identity and the binary cannot disagree. `packaging/nightly-common.sh`
runs `<> --version` after the build and expects `FigCraft <version> (nightly-v1)`; the Launcher's form
`--launch-profile nightly-v1 --profile-root <dir> --version` is answered before any window opens.
**The profile.** A nightly build refuses to start without `--launch-profile nightly-v1
--profile-root <absolute dir>` and keeps every piece of user state there: preferences and recent
files, recovery copies, installed plugins and the suite's font store. It never reads or writes
`~/.config/FigCraft` (macOS: `~/Library/Application Support/FigCraft`, Windows: `%APPDATA%\FigCraft`),
a portable copy's `config/`, or the shared `craft-fonts` store; the validator refuses a root that
overlaps any stable folder, a link or an alias. The Linux formats reach it through one launcher
(`packaging/linux/nightly-launch.sh`) that every package format installs as its entry point, with the
profile at `$XDG_DATA_HOME/figcraft-nightly/profile`.
## Local regression checks
`python3 packaging/nightly-release-tests.py` verifies the nightly workflow and policy contracts locally:
- Exact context guards on `nightly.yml` and `nightly-sign.yml` (reading every `if:` form and continuation line).
- No registered nightly schedule (`workflow_dispatch` only).
- Signer root concurrency serialization (`figcraft-nightly-release`, `cancel-in-progress: false`).
- No cache actions, cache setup options, `environment:`, or `secrets:` in the app callers.
- Matching `uses` and `tooling-revision` 40-hex commit pin across both callers and the installed policy.
- Exact `manual_actors` match between `nightly.yml` and `.github/nightly-signing-policy.json`, with empty `automatic_signer_actors`.
- Policy v3 schema, platform list/trust anchor shapes, required CI workflow check, and `sonar-project.properties` alignment.
+15
View File
@@ -10,6 +10,21 @@ if grep -rniE 'photoshop|psd|photocraft|vectorcraft|illustrator|adobe|figma' pac
exit 1
fi
# The Nightly's app-side synthetic suites: the icon containers and provenance, the macOS metadata
# and signing scripts against stand-in Apple tools, the caller contracts, and the Arch tarball. No
# app build, no signing material and no network.
python3 -I packaging/nightly-tests.py
bash packaging/linux/nightly-launch-test.sh
bash packaging/linux/nightly-arch-tar-test.sh
# Every Nightly shell script must parse: a quoting slip breaks bash -n, and nothing else would
# catch it until a runner started the script for real.
for script in packaging/nightly-common.sh packaging/linux/nightly.sh packaging/linux/nightly-launch.sh \
packaging/linux/nightly-launch-test.sh \
packaging/linux/nightly-arch-tar.sh packaging/macos/nightly-lib.sh packaging/macos/nightly.sh \
packaging/macos/nightly-sign.sh packaging/macos/nightly-verify.sh; do
bash -n "$script"
done
python3 - <<'PYEOF'
import yaml
manifests = []
+52 -8
View File
@@ -18,6 +18,12 @@ set -euo pipefail
. "$(dirname "${BASH_SOURCE[0]}")/../env.sh"
HERE="$ROOT/packaging/linux"
APP_ID=ai.storyteller.figcraft
FLATPAK_ID="$APP_ID"
# The remote indexes both app IDs on the stable ref branch; IDs isolate installations.
FLATPAK_BRANCH=stable
if [[ "${FIGCRAFT_BUILD_CHANNEL:-}" == nightly-v1 || "$VERSION" == *-nightly* ]]; then
FLATPAK_ID="$APP_ID.nightly"
fi
FLATHUB=https://dl.flathub.org/repo/flathub.flatpakrepo
TEST=1
@@ -53,30 +59,68 @@ rm -rf "$WORK"
mkdir -p "$WORK/stage"
tar -xzf "$TARBALL" -C "$WORK/stage" --strip-components=1
[[ -x "$WORK/stage/bin/figcraft" ]] || { echo "error: $TARBALL has no bin/figcraft" >&2; exit 1; }
cp "$HERE/flatpak/$APP_ID.bundle.yml" "$WORK/$APP_ID.yml"
if [[ "$FLATPAK_ID" != "$APP_ID" ]]; then
NIGHTLY_ICON="$ROOT/assets/app-icon/figcraft-nightly.png"
[[ -f "$NIGHTLY_ICON" ]] || NIGHTLY_ICON="$ROOT/assets/app-icon/hicolor/256x256/apps/$APP_ID.png"
# The window's app id is the flavor's (WindowId), which is not the bundle's own id.
sed -e "s|^Icon=$APP_ID$|Icon=$FLATPAK_ID|" \
-e "s|^Name=FigCraft$|Name=FigCraft Nightly|" \
-e "s|^StartupWMClass=.*|StartupWMClass=$FLATPAK_ID-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>FigCraft</name>|<name>FigCraft Nightly</name>|g" \
-e "s|<launchable type=\"desktop-id\">$APP_ID.desktop</launchable>|<launchable type=\"desktop-id\">$FLATPAK_ID.desktop</launchable>|g" \
-e "s|<icon type=\"stock\">$APP_ID</icon>|<icon type=\"stock\">$FLATPAK_ID</icon>|g" \
-e "s|<binary>figcraft</binary>|<binary>figcraft-nightly</binary>|g" \
-e '/<mediatype>/d' \
"$WORK/stage/share/metainfo/$APP_ID.metainfo.xml" >"$WORK/stage/share/metainfo/$FLATPAK_ID.metainfo.xml"
rm -f "$WORK/stage/share/metainfo/$APP_ID.metainfo.xml"
# No document associations for a Nightly: it never takes a file type from the stable app.
rm -rf "$WORK/stage/share/mime"
rm -rf "$WORK/stage/share/icons/hicolor"
install -Dm644 "$NIGHTLY_ICON" \
"$WORK/stage/share/icons/hicolor/256x256/apps/$FLATPAK_ID.png"
sed -e "s|ai\.storyteller\.figcraft|$FLATPAK_ID|g" \
-e "s|^command: figcraft$|command: figcraft-nightly|" \
-e "s|^ - install -Dm644 share/mime/packages/.*$||" \
-e "s|^ - install -Dm755 bin/figcraft /app/bin/figcraft$| - install -Dm755 bin/figcraft /app/bin/figcraft\n - install -Dm755 bin/figcraft-nightly /app/bin/figcraft-nightly|" \
"$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"
if [[ -x "$WORK/stage/bin/figcraft-cli" ]]; then smoke=figcraft-cli; else smoke=figcraft; fi
flatpak run --command="$smoke" "$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/256x256/apps'
flatpak info --user "$FLATPAK_ID"
# The Nightly bundle installs the launcher (its desktop entry's command) and no document types, so
# its query goes through that launcher and its file list has no share/mime to look for.
paths='/app/share/applications /app/share/metainfo /app/share/icons/hicolor/*/apps'
if [[ "$FLATPAK_ID" != "$APP_ID" ]]; then
smoke=figcraft-nightly
else
paths="$paths /app/share/mime/packages"
if [[ -x "$WORK/stage/bin/figcraft-cli" ]]; then smoke=figcraft-cli; else smoke=figcraft; fi
fi
flatpak run --command="$smoke" "$FLATPAK_ID" --version
flatpak run --command=sh "$FLATPAK_ID" -c "ls $paths"
fi
echo "==> done"
ls -lh "$OUT"
+8 -5
View File
@@ -4,7 +4,7 @@
# NFPM_ARCH and FIGCRAFT_MAINTAINER.
#
# nfpm package -f packaging/linux/nfpm.yaml -p deb -t dist/release/
name: figcraft
name: ${NFPM_NAME}
arch: ${NFPM_ARCH}
platform: linux
version: ${VERSION}
@@ -70,12 +70,15 @@ overrides:
- xdg-desktop-portal
contents:
- src: ${STAGE}/usr/bin/figcraft
dst: /usr/bin/figcraft
- src: ${STAGE}/usr/bin/${NFPM_BIN}
dst: /usr/bin/${NFPM_BIN}
file_info: { mode: 0755 }
- src: ${STAGE}/usr/bin/figcraft-cli #cli
dst: /usr/bin/figcraft-cli #cli
- src: ${STAGE}/usr/bin/${NFPM_CLI} #cli
dst: /usr/bin/${NFPM_CLI} #cli
file_info: { mode: 0755 } #cli
- src: ${STAGE}/usr/lib/
dst: /usr/lib/
type: tree
- src: ${STAGE}/usr/share/
dst: /usr/share/
type: tree
+68
View File
@@ -0,0 +1,68 @@
#!/usr/bin/env bash
# Validate the staged Arch launcher without building or opening FigCraft.
set -euo pipefail
HERE="$(cd "$(dirname "$0")" && pwd)"
work="$(mktemp -d)"
trap 'rm -rf "$work"' EXIT
stage="$work/source"
dst="$work/dist"
base=figcraft-0.0.1-nightly.1-linux-x86_64
mkdir -p "$stage/bin" "$dst" "$work/extract"
# A local argv + XDG recorder stands in for the compiled binaries. It never opens a UI.
cat >"$stage/bin/figcraft" <<'RECORDER'
#!/bin/sh
printf 'CONFIG=%s\nDATA=%s\n' "${XDG_CONFIG_HOME:-}" "${XDG_DATA_HOME:-}"
printf '<%s>\n' "$@"
RECORDER
chmod 755 "$stage/bin/figcraft"
cp "$stage/bin/figcraft" "$stage/bin/figcraft-cli"
bash "$HERE/nightly-arch-tar.sh" "$stage" "$work/stage" "$dst" "$base"
tar -xzf "$dst/$base.tar.gz" -C "$work/extract"
bin="$work/extract/$base/bin"
# Simulate the existing Arch bin-tree copy and public launcher rename.
mkdir -p "$work/installed"
cp -R "$bin" "$work/installed/bin"
bin="$work/installed/bin"
mv "$bin/figcraft" "$bin/figcraft-nightly"
mv "$bin/figcraft-cli" "$bin/figcraft-nightly-cli"
[[ ! -e "$stage/bin/.figcraft-nightly" ]]
cmp "$stage/bin/figcraft" "$bin/.figcraft-nightly/figcraft"
cmp "$stage/bin/figcraft-cli" "$bin/figcraft-nightly-cli"
export HOME="$work/home with space"
unset XDG_CONFIG_HOME XDG_DATA_HOME
# The launcher starts the GUI on the Launcher's nightly-v1 profile under the per-channel data dir,
# so the profile it passes must be the one the flavor's fence accepts.
# Every argument the launcher adds, printed the way the recorder shows them.
profile_at() {
printf -- '<--launch-profile>\n<nightly-v1>\n<--profile-root>\n<%s/profile>\n<-->' "$1"
}
expect() {
expected="$1"
shift
actual=$(PATH="$bin:$PATH" figcraft-nightly "$@")
if [[ "$actual" != "$expected" ]]; then
printf 'expected:\n%s\nactual:\n%s\n' "$expected" "$actual" >&2
exit 1
fi
}
expect "$(printf 'CONFIG=%s\nDATA=%s\n%s' "$HOME/.config/figcraft-nightly" "$HOME/.local/share/figcraft-nightly" "$(profile_at "$HOME/.local/share/figcraft-nightly")")"
export XDG_CONFIG_HOME="$work/xdg config with space"
export XDG_DATA_HOME="$work/xdg data with space"
expect "$(printf 'CONFIG=%s\nDATA=%s\n%s\n<%s>\n<%s>\n' "$XDG_CONFIG_HOME/figcraft-nightly" "$XDG_DATA_HOME/figcraft-nightly" \
"$(profile_at "$XDG_DATA_HOME/figcraft-nightly")" 'design with spaces.figcraft' '--other-name.figcraft')" \
'design with spaces.figcraft' '--other-name.figcraft'
# A version query is answered by the GUI itself: no profile directory is created for it.
expect "$(printf 'CONFIG=%s\nDATA=%s\n<--version>\n' "$XDG_CONFIG_HOME" "$XDG_DATA_HOME")" --version
expect "$(printf 'CONFIG=%s\nDATA=%s\n<-V>\n' "$XDG_CONFIG_HOME" "$XDG_DATA_HOME")" -V
# The Launcher's own protocol passes through untouched: never a second pair, and the caller's
# folders are left as they were.
expect "$(printf 'CONFIG=%s\nDATA=%s\n<--launch-profile>\n<nightly-v1>\n<--profile-root>\n<%s>\n<-->\n<%s>\n' \
"$XDG_CONFIG_HOME" "$XDG_DATA_HOME" "$work/launcher profile" 'a.figcraft')" \
--launch-profile nightly-v1 --profile-root "$work/launcher profile" -- 'a.figcraft'
[[ ! -e "$XDG_DATA_HOME/figcraft-nightly" ]] || { echo "FAIL: a version query created the profile" >&2; exit 1; }
echo "PASS: Arch Nightly handoff starts the nightly-v1 profile and preserves launch arguments"
+20
View File
@@ -0,0 +1,20 @@
#!/usr/bin/env bash
# Stage the FigCraft 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/.figcraft-nightly"
mv "$stage/bin/figcraft" "$stage/bin/.figcraft-nightly/figcraft"
awk -v real='"$(dirname "$0")/.figcraft-nightly/figcraft"' '{ gsub(/@REAL_BIN@/, real); print }' \
"$here/nightly-launch.sh" >"$stage/bin/figcraft"
chmod 755 "$stage/bin/figcraft"
tar -C "$work" -czf "$destination/$basename.tar.gz" "$basename"
echo "wrote $destination/$basename.tar.gz"
+87
View File
@@ -0,0 +1,87 @@
#!/usr/bin/env bash
# The nightly launcher (packaging/linux/nightly-launch.sh) in each form the formats install it:
# beside the GUI as figcraft-bin in a tarball, at /usr/lib in a package, inside an AppImage, and the
# Launcher's own protocol passed through. Runs in a second with a recording stub; it builds nothing
# and opens no window.
set -euo pipefail
HERE="$(cd "$(dirname "$0")" && pwd)"
work="$(mktemp -d)"
trap 'rm -rf "$work"' EXIT
mkdir -p "$work/bin" "$work/deb/usr/lib/figcraft-nightly" "$work/app" "$work/home with space"
recorder() {
cat >"$1" <<'RECORDER'
#!/bin/sh
printf 'CONFIG=%s\nDATA=%s\n' "${XDG_CONFIG_HOME:-}" "${XDG_DATA_HOME:-}"
printf '<%s>\n' "$@"
RECORDER
chmod 755 "$1"
}
install_launcher() {
awk -v real="$2" '{ gsub(/@REAL_BIN@/, real); print }' "$HERE/nightly-launch.sh" >"$1"
chmod 755 "$1"
}
# The tarball's standard layout: `figcraft` is the launcher and the GUI beside it is `figcraft-bin`.
recorder "$work/bin/figcraft-bin"
# shellcheck disable=SC2016 # $(dirname "$0") stays literal in the launcher: it resolves at run time
install_launcher "$work/bin/figcraft" '"$(dirname "$0")/figcraft-bin"'
# deb/rpm: the wrapper at /usr/bin, the GUI under /usr/lib. The absolute path cannot resolve in a
# test, so this form is checked by its text (and by the packaging tests that stage a package).
install_launcher "$work/deb/figcraft-nightly" '/usr/lib/figcraft-nightly/figcraft'
grep -Fxq 'real_bin=/usr/lib/figcraft-nightly/figcraft' "$work/deb/figcraft-nightly" \
|| { echo "the package wrapper does not start the packaged GUI" >&2; exit 1; }
# AppImage: AppRun runs the launcher, which starts the GUI in the AppDir's usr/bin.
mkdir -p "$work/app/usr/bin"
recorder "$work/app/usr/bin/figcraft"
install_launcher "$work/app/figcraft-nightly" "\"$work/app/usr/bin/figcraft\""
export HOME="$work/home with space"
unset XDG_CONFIG_HOME XDG_DATA_HOME
profile="$HOME/.local/share/figcraft-nightly/profile"
check() {
local launcher="$1" want="$2"
shift 2
local actual
actual="$("$launcher" "$@")"
[[ "$actual" == "$want" ]] || { printf '%s %s: unexpected launch\nwant:\n%s\ngot:\n%s\n' "${launcher#"$work"/}" "$*" "$want" "$actual" >&2; exit 1; }
}
for launcher in "$work/bin/figcraft" "$work/app/figcraft-nightly"; do
# A plain launch starts the nightly profile and passes the files after the delimiter.
check "$launcher" "$(printf 'CONFIG=%s\nDATA=%s\n<--launch-profile>\n<nightly-v1>\n<--profile-root>\n<%s>\n<-->\n<design with spaces.figcraft>\n<--other-name.figcraft>\n' \
"$HOME/.config/figcraft-nightly" "$HOME/.local/share/figcraft-nightly" "$profile")" \
'design with spaces.figcraft' '--other-name.figcraft'
# A delimiter the caller already wrote is not doubled.
check "$launcher" "$(printf 'CONFIG=%s\nDATA=%s\n<--launch-profile>\n<nightly-v1>\n<--profile-root>\n<%s>\n<-->\n<%s>\n' \
"$HOME/.config/figcraft-nightly" "$HOME/.local/share/figcraft-nightly" "$profile" 'a.figcraft')" \
-- 'a.figcraft'
# The Launcher's own protocol passes through untouched, in either order, with no second pair and
# without exporting this channel's folders over the root it named.
check "$launcher" "$(printf 'CONFIG=\nDATA=\n<--launch-profile>\n<nightly-v1>\n<--profile-root>\n<%s>\n<-->\n<%s>\n' \
"$work/launcher profile" 'chosen.figcraft')" \
--launch-profile nightly-v1 --profile-root "$work/launcher profile" -- 'chosen.figcraft'
check "$launcher" "$(printf 'CONFIG=\nDATA=\n<--profile-root>\n<%s>\n<-->\n' "$work/launcher profile")" \
--profile-root "$work/launcher profile" --
# A version query goes straight to the GUI: no exports, no profile, nothing created.
for flag in --version -V; do
check "$launcher" "$(printf 'CONFIG=\nDATA=\n<%s>\n' "$flag")" "$flag"
done
[[ ! -e "$profile" ]] || { echo "${launcher#"$work"/}: a version or Launcher launch created the profile" >&2; exit 1; }
done
# The wrapper hands the GUI the XDG bases it overrode, so the stable folders under them stay fenced.
stable_recorder="$work/bin/stable-bases"
cat >"$stable_recorder" <<'RECORDER'
#!/bin/sh
printf 'STABLE_CONFIG=%s\nSTABLE_DATA=%s\n' "${FIGCRAFT_STABLE_XDG_CONFIG_HOME:-}" "${FIGCRAFT_STABLE_XDG_DATA_HOME:-}"
RECORDER
chmod 755 "$stable_recorder"
install_launcher "$work/bin/stable-launch" "\"$stable_recorder\""
check "$work/bin/stable-launch" "$(printf 'STABLE_CONFIG=%s\nSTABLE_DATA=%s\n' "$HOME/.config" "$HOME/.local/share")"
XDG_CONFIG_HOME="$work/xdg config" XDG_DATA_HOME="$work/xdg data" \
check "$work/bin/stable-launch" "$(printf 'STABLE_CONFIG=%s\nSTABLE_DATA=%s\n' "$work/xdg config" "$work/xdg data")"
echo "PASS: the nightly launcher starts the nightly-v1 profile in every form and passes a supplied one through"
+35
View File
@@ -0,0 +1,35 @@
#!/bin/sh
# FigCraft Nightly launch wrapper, shared by every nightly Linux format (the flat .tar.gz, the Arch
# handoff, the deb/rpm and the AppImage entry). It starts the GUI on the Launcher's nightly-v1
# profile under a per-channel directory, so a nightly install never reads or writes the stable
# app's settings, recovery copies, plugins, font store or session state.
#
# The GUI binary this starts is substituted where the script is installed: beside the script as
# figcraft-bin in a tarball, $APPDIR/usr/bin/figcraft in an AppImage, /usr/lib/figcraft-nightly/… in
# a deb/rpm, and bin/.figcraft-nightly/figcraft in the Arch handoff.
#
# The Launcher speaks this same protocol (`--launch-profile nightly-v1 --profile-root <dir> --`),
# so its command line passes straight through rather than being wrapped in a second pair. A bare
# `--version` or `-V` goes straight to the binary too: the answer must be the plain version line,
# and a version query never creates the profile. Everything else starts the nightly profile.
set -eu
real_bin=@REAL_BIN@
case "${1:-}" in
--launch-profile | --profile-root | --version | -V) exec "$real_bin" "$@" ;;
esac
config_base="${XDG_CONFIG_HOME:-${HOME:?HOME is required}/.config}"
data_base="${XDG_DATA_HOME:-${HOME:?HOME is required}/.local/share}"
# The bases in effect before the override below: the GUI's profile fence still refuses the stable
# FigCraft folders under them (profile_root.rs reads FIGCRAFT_STABLE_<key>).
export FIGCRAFT_STABLE_XDG_CONFIG_HOME="$config_base"
export FIGCRAFT_STABLE_XDG_DATA_HOME="$data_base"
# Belt and braces for anything that still asks the process environment for a folder.
export XDG_CONFIG_HOME="$config_base/figcraft-nightly"
export XDG_DATA_HOME="$data_base/figcraft-nightly"
# One profile per channel, chosen here only: a caller cannot point the Nightly at another folder,
# so the fence the GUI applies can never be handed the stable app's config or data directory.
profile="$XDG_DATA_HOME/profile"
# A `--` the caller wrote already separates the files from the options: drop it, so the app is
# handed exactly one and no file name arrives as `--`.
if [ "${1:-}" = "--" ]; then shift; fi
exec "$real_bin" --launch-profile nightly-v1 --profile-root "$profile" -- "$@"
+34
View File
@@ -0,0 +1,34 @@
#!/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; }
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=../nightly-common.sh
. "$(dirname "${BASH_SOURCE[0]}")/../nightly-common.sh"
nightly_init linux "$ARCH" x86_64-unknown-linux-gnu
OUTPUT="$DIST/figcraft-$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: the archive's entry point `figcraft` is the shared launcher, which
# starts the GUI on the Launcher's nightly-v1 profile, and the GUI itself sits beside it as
# `figcraft-bin`. An unpacked tar is isolated too, even when started straight from its folder.
cp "$NIGHTLY_GUI" "$STAGE/figcraft-bin"
chmod 755 "$STAGE/figcraft-bin"
awk -v real='"$(dirname "$0")/figcraft-bin"' '{ gsub(/@REAL_BIN@/, real); print }' \
"$HERE/nightly-launch.sh" >"$STAGE/figcraft"
chmod 755 "$STAGE/figcraft"
cp "$ROOT/assets/app-icon/figcraft-nightly.png" "$STAGE/figcraft-nightly.png"
nightly_copy_notices "$STAGE"
# The private mktemp cwd is the helper authority root, not a CLI path parent.
(cd "$NIGHTLY_WORK" && python3 "$ROOT/packaging/nightly-archive.py" linux stage archive.tar.gz)
nightly_publish_archive "$NIGHTLY_WORK/archive.tar.gz" "$OUTPUT"
+169 -10
View File
@@ -9,7 +9,7 @@
#
# figcraft-cli is built and shipped next to figcraft once apps/figcraft-cli exists.
#
# Usage: packaging/linux/package.sh [--skip-build] [--formats "appimage deb rpm tar"]
# Usage: packaging/linux/package.sh [--skip-build] [--formats "appimage deb rpm tar"] [--arch-tar-dir DIRECTORY]
#
# Needs: cargo; nfpm for deb/rpm (https://nfpm.goreleaser.com); appimagetool for the AppImage
# (downloaded into $CARGO_TARGET_DIR if missing). Build on an old distro (CI: Ubuntu 22.04,
@@ -33,10 +33,16 @@ verify_sha256() {
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,15p' "$0"; exit 0 ;;
*) echo "unknown argument: $1" >&2; exit 2 ;;
esac
@@ -50,9 +56,20 @@ case "$ARCH" in
*) echo "unsupported architecture $ARCH" >&2; exit 2 ;;
esac
export FIGCRAFT_MAINTAINER="${FIGCRAFT_MAINTAINER:-FigCraft maintainers <figcraft@storyteller.ai>}"
IS_NIGHTLY=0
if [[ "${FIGCRAFT_BUILD_CHANNEL:-}" == nightly-v1 || "$VERSION" == *-nightly* ]]; then
IS_NIGHTLY=1
export FIGCRAFT_BUILD_CHANNEL=nightly-v1
export FIGCRAFT_OVERRIDE_VERSION="$VERSION"
fi
BASENAME="figcraft-$VERSION-linux-$ARCH"
echo "==> FigCraft $VERSION for Linux $ARCH ($FORMATS; ${BINS[*]})"
if [[ -n "$ARCH_TAR_DIR" && "$IS_NIGHTLY" != 1 ]]; then
echo "error: --arch-tar-dir is only for Nightly builds" >&2
exit 2
fi
echo "==> FigCraft $VERSION for Linux $ARCH ($FORMATS; ${BINS[*]}; channel=${FIGCRAFT_BUILD_CHANNEL:-stable})"
if [[ "$SKIP_BUILD" = 0 ]]; then
(cd "$ROOT" && cargo build --release --locked "${CARGO_PKGS[@]}" ${CROSS_TARGET:+--target "$CROSS_TARGET"})
@@ -68,9 +85,39 @@ for bin in "${BINS[@]}"; do
"${CROSS_COMPILE:-}strip" "$STAGE/usr/bin/$bin" 2>/dev/null || true
done
install -Dm644 "$HERE/$APP_ID.desktop" "$STAGE/usr/share/applications/$APP_ID.desktop"
install -Dm644 "$HERE/$APP_ID.mime.xml" "$STAGE/usr/share/mime/packages/$APP_ID.xml"
if [[ "$IS_NIGHTLY" = 1 ]]; then
# The nightly entry point is the shared launcher (packaging/linux/nightly-launch.sh): every
# format starts the GUI on the Launcher's nightly-v1 profile, so nothing reads or writes the
# stable app's user state. The deb/rpm wrapper and the AppImage entry below specialise its path.
awk -v real='"$(dirname "$0")/figcraft"' '{ gsub(/@REAL_BIN@/, real); print }' \
"$HERE/nightly-launch.sh" >"$STAGE/usr/bin/figcraft-nightly"
chmod 755 "$STAGE/usr/bin/figcraft-nightly"
# The entry starts the launcher, names the Nightly and registers no file types (a Nightly never
# takes a document association from the stable app). `#` delimits, so \(...\|...\) is alternation.
sed -e 's|^StartupWMClass=.*|StartupWMClass=ai.storyteller.figcraft.nightly-v1|' \
-e "s#^Exec=figcraft\([[:space:]]\|$\)#Exec=figcraft-nightly\1#" \
-e "s|^TryExec=figcraft$|TryExec=figcraft-nightly|" \
-e "s|^Name=FigCraft$|Name=FigCraft Nightly|" \
-e '/^MimeType=/d' \
"$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
# No document associations for a Nightly: the mime package, the desktop's MimeType lines and the
# metainfo mediatypes all stay out, so it never takes a file type from the stable app.
if [[ "$IS_NIGHTLY" = 0 ]]; then
install -Dm644 "$HERE/$APP_ID.mime.xml" "$STAGE/usr/share/mime/packages/$APP_ID.xml"
fi
mkdir -p "$STAGE/usr/share/metainfo"
sed -e "s/@VERSION@/$VERSION/g" -e "s/@DATE@/$FIGCRAFT_BUILD_DATE/g" \
# The AppStream metadata carries the Nightly's name and launcher and no document types. Its id,
# launchable and icon keep the stable values here: the deb/rpm, the AppImage and the Flatpak each
# rename them to the id they actually install (and the Flatpak's differs from the AppImage's).
META_NIGHTLY=()
if [[ "$IS_NIGHTLY" = 1 ]]; then
META_NIGHTLY=(-e "s|<name>FigCraft</name>|<name>FigCraft Nightly</name>|g"
-e 's|<binary>figcraft</binary>|<binary>figcraft-nightly</binary>|g'
-e '/<mediatype>/d')
fi
sed -e "s/@VERSION@/$VERSION/g" -e "s/@DATE@/$FIGCRAFT_BUILD_DATE/g" "${META_NIGHTLY[@]}" \
"$HERE/$APP_ID.metainfo.xml.in" >"$STAGE/usr/share/metainfo/$APP_ID.metainfo.xml"
mkdir -p "$STAGE/usr/share/icons"
cp -R "$ROOT/assets/app-icon/hicolor" "$STAGE/usr/share/icons/"
@@ -90,20 +137,82 @@ has() { local format="$1"; case " $FORMATS " in *" $format "*) return 0 ;; *) re
if has tar; then
mkdir -p "$WORK/tar"
cp -R "$STAGE/usr" "$WORK/tar/$BASENAME"
# GUI only: a Nightly has no CLI (the stable tarball keeps shipping it).
if [[ "$IS_NIGHTLY" = 1 ]]; then rm -f "$WORK/tar/$BASENAME/bin/figcraft-cli"; fi
tar -C "$WORK/tar" -czf "$DIST/$BASENAME.tar.gz" "$BASENAME"
echo "wrote $DIST/$BASENAME.tar.gz"
fi
# The Arch handoff keeps the same basename as the plain tarball in a separate directory.
# Flatpak, OCI and direct tar consumers still get the original binary, not this launcher.
if [[ -n "$ARCH_TAR_DIR" ]]; then
mkdir -p "$ARCH_TAR_DIR"
if [[ "$(cd "$ARCH_TAR_DIR" && pwd -P)" == "$(cd "$DIST" && pwd -P)" ]]; then
echo "error: the Arch tar directory must differ from the release directory" >&2
exit 2
fi
bash "$HERE/nightly-arch-tar.sh" "$STAGE/usr" "$WORK/arch-tar" "$ARCH_TAR_DIR" "$BASENAME"
fi
# ---- .deb / .rpm --------------------------------------------------------------------------------
if has deb || has rpm; then
command -v nfpm >/dev/null || { echo "error: nfpm not found (https://nfpm.goreleaser.com/install/)" >&2; exit 1; }
export VERSION
export NFPM_ARCH="$DEB_ARCH"
NFPM_STAGE="$STAGE"
export NFPM_NAME="figcraft"
export NFPM_BIN="figcraft"
export NFPM_CLI="figcraft-cli"
if [[ "$IS_NIGHTLY" = 1 ]]; then
NIGHTLY_DESK_ID="$APP_ID.nightly-v1"
NIGHTLY_ICON="$ROOT/assets/app-icon/figcraft-nightly.png"
[[ -f "$NIGHTLY_ICON" ]] || NIGHTLY_ICON="$ROOT/assets/app-icon/hicolor/256x256/apps/$APP_ID.png"
export NFPM_NAME="figcraft-nightly"
export NFPM_BIN="figcraft-nightly"
export NFPM_CLI="figcraft-nightly-cli"
NFPM_STAGE="$WORK/nfpm-root"
rm -rf "$NFPM_STAGE"
cp -R "$STAGE" "$NFPM_STAGE"
install -Dm755 "$NFPM_STAGE/usr/bin/figcraft" "$NFPM_STAGE/usr/lib/figcraft-nightly/figcraft"
# The shared launcher (packaging/linux/nightly-launch.sh) starts the GUI on the Launcher's
# nightly-v1 profile, so the package never reads or writes the stable app's user state.
awk -v real='/usr/lib/figcraft-nightly/figcraft' '{ gsub(/@REAL_BIN@/, real); print }' \
"$HERE/nightly-launch.sh" >"$NFPM_STAGE/usr/bin/$NFPM_BIN"
chmod 755 "$NFPM_STAGE/usr/bin/$NFPM_BIN"
rm -f "$NFPM_STAGE/usr/bin/figcraft"
if [[ "$HAS_CLI" = 1 ]]; then
mv "$NFPM_STAGE/usr/bin/figcraft-cli" "$NFPM_STAGE/usr/bin/$NFPM_CLI"
fi
mv "$NFPM_STAGE/usr/share/doc/figcraft" "$NFPM_STAGE/usr/share/doc/$NFPM_NAME"
sed -e "s#^Exec=figcraft\([[:space:]]\|$\)#Exec=$NFPM_BIN\1#" \
-e "s|^TryExec=figcraft$|TryExec=$NFPM_BIN|" \
-e "s|^Icon=$APP_ID$|Icon=$NIGHTLY_DESK_ID|" \
-e "s|^Name=FigCraft$|Name=FigCraft 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>FigCraft</name>|<name>FigCraft 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>figcraft</binary>|<binary>$NFPM_BIN</binary>|g" \
-e '/<mediatype>/d' \
"$NFPM_STAGE/usr/share/metainfo/$APP_ID.metainfo.xml" >"$NFPM_STAGE/usr/share/metainfo/$NIGHTLY_DESK_ID.metainfo.xml"
rm -f "$NFPM_STAGE/usr/share/metainfo/$APP_ID.metainfo.xml"
rm -rf "$NFPM_STAGE/usr/share/mime"
rm -rf "$NFPM_STAGE/usr/share/icons/hicolor"
install -Dm644 "$NIGHTLY_ICON" \
"$NFPM_STAGE/usr/share/icons/hicolor/256x256/apps/$NIGHTLY_DESK_ID.png"
fi
# nfpm expands env vars in fields like `version` and `arch`, but not in `contents[].src`.
# Without the CLI, drop its `#cli` lines.
DROP_LIB_TREE=
# shellcheck disable=SC2016
[[ -d "$NFPM_STAGE/usr/lib" ]] || DROP_LIB_TREE='\|^ - src: \${STAGE}/usr/lib/|,+2d;'
cli_filter='/#cli$/d'
[[ "$HAS_CLI" = 1 ]] && cli_filter='s/ #cli$//'
sed -e "s|\${STAGE}|$STAGE|g" -e "$cli_filter" "$HERE/nfpm.yaml" >"$WORK/nfpm.yaml"
# shellcheck disable=SC2016
sed -e "${DROP_LIB_TREE}s|\${STAGE}|$NFPM_STAGE|g;s|\${NFPM_BIN}|$NFPM_BIN|g;s|\${NFPM_CLI}|$NFPM_CLI|g" -e "$cli_filter" "$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
@@ -135,9 +244,50 @@ if has appimage; then
# app_id to our icon instead of the generic Wayland logo (opt-out env in the
# script header). Logic is covered by packaging/linux/apprun-test.sh.
install -Dm755 "$HERE/AppRun" "$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"
NIGHTLY_ICON="$ROOT/assets/app-icon/figcraft-nightly.png"
[[ -f "$NIGHTLY_ICON" ]] || NIGHTLY_ICON="$ROOT/assets/app-icon/hicolor/256x256/apps/$APP_ID.png"
# AppRun runs the staged launcher (`usr/bin/figcraft-nightly`, which starts the GUI beside it).
# Its `$(dirname "$0")` form resolves the same way under the AppImage runtime and an extracted
# AppDir, and never needs the runtime's `$APPDIR` to be exported.
# shellcheck disable=SC2016
awk -v old_id="$APP_ID" -v new_id="$APPIMAGE_ID" '
$0 == "DESK_ID=" old_id { print "DESK_ID=" new_id; next }
$0 == "exec \"$APPDIR/usr/bin/figcraft\" \"$@\"" {
print "exec \"$APPDIR/usr/bin/figcraft-nightly\" \"$@\""
next
}
{ print }
' "$APPDIR/AppRun" >"$APPDIR/AppRun.tmp"
mv "$APPDIR/AppRun.tmp" "$APPDIR/AppRun"
chmod 755 "$APPDIR/AppRun"
sed -e "s|^Icon=$APP_ID$|Icon=$APPIMAGE_ID|" \
-e "s|^Name=FigCraft$|Name=FigCraft 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"
# No document associations for a Nightly: the mime package, the desktop's MimeType lines (above)
# and the metainfo mediatypes all stay out, so it never takes a file type from the stable app.
rm -rf "$APPDIR/usr/share/mime"
sed -e "s|<id>$APP_ID</id>|<id>$APPIMAGE_ID</id>|g" \
-e "s|<launchable type=\"desktop-id\">$APP_ID.desktop</launchable>|<launchable type=\"desktop-id\">$APPIMAGE_ID.desktop</launchable>|g" \
-e "s|<icon type=\"stock\">$APP_ID</icon>|<icon type=\"stock\">$APPIMAGE_ID</icon>|g" \
-e "s|<binary>figcraft</binary>|<binary>figcraft-nightly</binary>|g" \
-e '/<mediatype>/d' \
"$APPDIR/usr/share/metainfo/$APP_ID.metainfo.xml" >"$APPDIR/usr/share/metainfo/$APPIMAGE_ID.metainfo.xml"
rm -f "$APPDIR/usr/share/metainfo/$APP_ID.metainfo.xml"
rm -rf "$APPDIR/usr/share/icons/hicolor"
install -Dm644 "$NIGHTLY_ICON" \
"$APPDIR/usr/share/icons/hicolor/256x256/apps/$APPIMAGE_ID.png"
cp "$NIGHTLY_ICON" "$APPDIR/$APPIMAGE_ID.png"
ln -s "$APPIMAGE_ID.png" "$APPDIR/.DirIcon"
else
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
@@ -178,11 +328,20 @@ if has appimage; then
# next to 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/figcraft}"
UPDATE_INFO="gh-releases-zsync|${REPO%%/*}|${REPO#*/}|latest|figcraft-*-linux-$ARCH.AppImage.zsync"
UPDATE_ARGS=()
if [[ "$IS_NIGHTLY" = 0 ]]; then
UPDATE_INFO="gh-releases-zsync|${REPO%%/*}|${REPO#*/}|latest|figcraft-*-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 (`latest-pre`) rather than stable `latest`.
UPDATE_INFO="gh-releases-zsync|${REPO%%/*}|${REPO#*/}|latest-pre|figcraft-*-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"
+128
View File
@@ -0,0 +1,128 @@
# 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='FigCraft Nightly.app'
MAC_NIGHTLY_ID='ai.storyteller.figcraft.nightly'
# The GUI's file name inside the bundle (CFBundleExecutable / CFBundleIconFile name their own).
MAC_NIGHTLY_EXE='FigCraft'
# The version key this app's Info.plist.in carries (package.sh substitutes it too).
MAC_NIGHTLY_VERSION_KEY='FigCraftVersion'
# 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" =~ ^figcraft-(.+)-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
}
# This app's import-cert.sh makes its own private directory under RUNNER_TEMP and puts the keychain
# inside it, so the path is not fixed: accept only a regular file of this run, named for the app,
# below the private work directory (and never through a link).
mac_nightly_keychain_is_ours() {
local keychain="$1" work="$2" parent
[[ -n "$keychain" && "$keychain" == /* && ! -L "$keychain" && -f "$keychain" ]] || return 1
case "$keychain" in
"$work"/figcraft-signing.keychain-db | "$work"/*/figcraft-signing.keychain-db) ;;
*) return 1 ;;
esac
parent="$(dirname -- "$keychain")"
[[ "$parent" == "$work" || "$parent" == "$work"/* ]] && [[ ! -L "$parent" ]]
}
# 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 FigCraft
# 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")" == "$MAC_NIGHTLY_EXE" ]] || mac_nightly_die 'Contents/MacOS must hold only the FigCraft GUI (no CLI)'
[[ -f "$app/Contents/MacOS/$MAC_NIGHTLY_EXE" && -x "$app/Contents/MacOS/$MAC_NIGHTLY_EXE" ]] || mac_nightly_die 'missing executable GUI'
[[ "$(lipo -archs "$app/Contents/MacOS/$MAC_NIGHTLY_EXE")" == arm64 ]] || mac_nightly_die 'the GUI must be thin arm64'
plist="$app/Contents/Info.plist"
for key in CFBundleIdentifier CFBundleExecutable "$MAC_NIGHTLY_VERSION_KEY"; 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" == "$MAC_NIGHTLY_EXE" ]] ;;
"$MAC_NIGHTLY_VERSION_KEY") [[ "$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/figcraft-<version>-macos-aarch64-nightly.zip \
# --output /abs/<dir>/figcraft-<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,19p' "$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%/}/figcraft-nightly-sign.XXXXXX")"
KEYCHAIN=''
cleanup() {
if [[ -n "$KEYCHAIN" && -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. It makes
# its own private directory under RUNNER_TEMP, so the keychain path comes from its output.
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 "==> FigCraft 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/$MAC_NIGHTLY_EXE"
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/figcraft-<version>-macos-aarch64-nightly.zip --expect signed [--team ID]
# nightly-verify.sh --input /abs/figcraft-<version>-macos-aarch64-nightly.zip --expect unsigned
#
# Both: the archive holds only the GUI-only Nightly bundle with the exact FigCraftVersion, 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 `FigCraft <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,16p' "$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}}/figcraft-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/$MAC_NIGHTLY_EXE" "$@" 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" == "FigCraft $VERSION (nightly-v1)" ]] || mac_nightly_die "the version query ($*) reports '$out', not FigCraft $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): FigCraft $VERSION (nightly-v1), plain and in the Launcher's profile form"
+51
View File
@@ -0,0 +1,51 @@
#!/usr/bin/env bash
# App-owned GUI-only Nightly for Apple silicon, compile step only (no signing material):
#
# $DIST/figcraft-<version>-macos-aarch64-nightly.zip FigCraft Nightly.app, unsigned
#
# Usage: packaging/macos/nightly.sh --arch aarch64
#
# Required env (nightly-common.sh): FIGCRAFT_BUILD_CHANNEL=nightly-v1, FIGCRAFT_VERSION,
# FIGCRAFT_BUILD_SHA, FIGCRAFT_BUILD_DATE, absolute CARGO_TARGET_DIR and DIST; CRAFT_FONTS_DIR optional.
#
# Not publishable by itself: the trusted step (nightly-sign.sh) signs, notarizes and staples it. No CLI,
# DMG, document or URL types, and no stable package.sh. The bundle is not run here; the version query
# runs on the signed bundle (nightly-verify.sh).
set -euo pipefail
ARCH=
while [[ $# -gt 0 ]]; do
case "$1" in
--arch) [[ $# -ge 2 ]] || { echo 'missing --arch value' >&2; exit 2; }; ARCH="$2"; shift 2 ;;
-h|--help) sed -n '2,13p' "$0"; exit 0 ;;
*) echo "unsupported nightly argument: $1" >&2; exit 2 ;;
esac
done
[[ "$ARCH" == aarch64 && "$(uname -s)" == Darwin && "$(uname -m)" == arm64 ]] || { echo 'only native macOS aarch64 nightly packaging is supported' >&2; exit 2; }
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
. "$HERE/../nightly-common.sh"
. "$HERE/nightly-lib.sh"
nightly_refuse_signing_env
nightly_init macos "$ARCH" aarch64-apple-darwin
# Keep in sync with LSMinimumSystemVersion in Info.plist.in (as package.sh).
export MACOSX_DEPLOYMENT_TARGET=11.0
OUTPUT="$DIST/figcraft-$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/$MAC_NIGHTLY_EXE"
chmod 755 "$APP/Contents/MacOS/$MAC_NIGHTLY_EXE"
cp "$ROOT/assets/app-icon/figcraft-nightly.icns" "$APP/Contents/Resources/figcraft-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 "$FIGCRAFT_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"
+74
View File
@@ -0,0 +1,74 @@
#!/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.figcraft.nightly"
# This app's template keys: CFBundleExecutable, CFBundleIconFile and the version key are its own.
EXECUTABLE = "FigCraft"
ICON = "figcraft-nightly"
VERSION_KEY = "FigCraftVersion"
COMMIT_KEY = "FigCraftBuildCommit"
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="FigCraft Nightly",
CFBundleName="FigCraft Nightly",
CFBundleIdentifier=IDENTIFIER,
CFBundleExecutable=EXECUTABLE,
CFBundleIconFile=ICON,
CFBundleShortVersionString=match[1],
CFBundleVersion=match[1],
)
data[VERSION_KEY] = version
data[COMMIT_KEY] = 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()
+205
View File
@@ -0,0 +1,205 @@
#!/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("fig_nightly_plist", HERE / "nightly_plist.py")
POLICY = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(POLICY)
COMMIT = "a" * 40
VERSION = "0.18.1-nightly.20261124.12345.1.g" + COMMIT[:12]
# The template keys this app carries: its own version and commit keys, and these platform ones.
PLATFORM_KEYS = ("LSMinimumSystemVersion", "NSHighResolutionCapable", "NSHumanReadableCopyright", "LSApplicationCategoryType")
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.figcraft.nightly")
self.assertEqual(rendered["CFBundleExecutable"], "FigCraft")
self.assertEqual(rendered["CFBundleIconFile"], "figcraft-nightly")
self.assertEqual(rendered["FigCraftVersion"], VERSION)
self.assertEqual(rendered["FigCraftBuildCommit"], COMMIT)
self.assertTrue(VERSION.startswith(rendered["CFBundleVersion"] + "-nightly."))
for key in PLATFORM_KEYS:
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.18.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["FigCraftVersion"], VERSION)
self.assertEqual(result["FigCraftBuildCommit"], COMMIT)
self.assertEqual(self.template.read_bytes(), self.original)
def test_template_alias_or_nonfile_refuses_before_output(self):
alias = self.root / "template-alias"
alias.symlink_to(self.template)
for template in (alias, self.root, self.root / "missing-template"):
with self.subTest(template=template), self.assertRaises(ValueError):
POLICY.write_plist(template, self.output, VERSION, COMMIT)
self.assertFalse(self.output.exists())
self.assertEqual(self.template.read_bytes(), self.original)
def test_failed_write_cleans_owned_output_but_preserves_a_replacement(self):
sentinel = b"generated replacement artifact"
for disposition in ("owned", "missing", "replacement"):
with self.subTest(disposition=disposition):
if self.output.exists():
self.output.unlink()
def fail_sync(_descriptor):
# macOS/Linux allow unlink of an open file: exercise the real
# cleanup ownership check, not a mocked inode comparison.
if disposition != "owned":
self.output.unlink()
if disposition == "replacement":
self.output.write_bytes(sentinel)
raise OSError("generated fsync failure")
with mock.patch.object(POLICY.os, "fsync", side_effect=fail_sync), self.assertRaises(OSError):
POLICY.write_plist(self.template, self.output, VERSION, COMMIT)
if disposition == "replacement":
self.assertEqual(self.output.read_bytes(), sentinel)
else:
self.assertFalse(self.output.exists())
self.assertEqual(self.template.read_bytes(), self.original)
def test_exclusive_output_preserves_existing_bytes_and_symlink_targets(self):
sentinel = b"generated owned sentinel, not an existing app or user file"
self.output.write_bytes(sentinel)
with self.assertRaises(FileExistsError):
POLICY.write_plist(self.template, self.output, VERSION, COMMIT)
self.assertEqual(self.output.read_bytes(), sentinel)
self.output.unlink()
external = self.root / "sentinel"
external.write_bytes(sentinel)
self.output.symlink_to(external)
with self.assertRaisesRegex(ValueError, "symlinks or aliases"):
POLICY.write_plist(self.template, self.output, VERSION, COMMIT)
self.assertEqual(external.read_bytes(), sentinel)
self.assertTrue(self.output.is_symlink())
def test_template_outside_build_root_refuses_before_output(self):
with tempfile.TemporaryDirectory() as external:
template = Path(external) / "Info.plist.in"
template.write_bytes(self.original)
with self.assertRaises(ValueError):
POLICY.write_plist(template, self.output, VERSION, COMMIT)
self.assertFalse(self.output.exists())
self.assertEqual(template.read_bytes(), self.original)
def test_output_outside_build_root_refuses_before_write(self):
with tempfile.TemporaryDirectory() as external:
output = Path(external) / "Info.plist"
with self.assertRaises(ValueError):
POLICY.write_plist(self.template, output, VERSION, COMMIT)
self.assertFalse(output.exists())
def test_parent_traversal_refuses_even_to_an_owned_sibling(self):
with tempfile.TemporaryDirectory(dir=self.root.parent) as external:
output = Path("..") / Path(external).name / "Info.plist"
with self.assertRaises(ValueError):
POLICY.write_plist(self.template, output, VERSION, COMMIT)
self.assertFalse((Path(external) / "Info.plist").exists())
def test_symlinked_output_parent_refuses(self):
with tempfile.TemporaryDirectory() as external:
alias = self.root / "alias"
alias.symlink_to(external, target_is_directory=True)
with self.assertRaises(ValueError):
POLICY.write_plist(self.template, alias / "Info.plist", VERSION, COMMIT)
self.assertFalse((Path(external) / "Info.plist").exists())
def test_template_read_is_bounded_before_output(self):
self.template.write_bytes(plistlib.dumps({"CFBundlePackageType": "APPL", "fixture": "x" * 300000}))
with self.assertRaises(ValueError):
POLICY.write_plist(self.template, self.output, VERSION, COMMIT)
self.assertFalse(self.output.exists())
def test_nonprivate_build_root_refuses(self):
self.root.chmod(0o755)
try:
with self.assertRaises(ValueError):
POLICY.write_plist(self.template, self.output, VERSION, COMMIT)
self.assertFalse(self.output.exists())
finally:
self.root.chmod(0o700)
def test_output_keeps_normal_new_file_permissions_inside_private_root(self):
previous = os.umask(0o022)
try:
reference = self.root / "reference"
reference.write_bytes(b"generated ordinary output")
POLICY.write_plist(self.template, self.output, VERSION, COMMIT)
finally:
os.umask(previous)
self.assertEqual(self.output.stat().st_mode & 0o777, reference.stat().st_mode & 0o777)
def test_open_parent_anchor_prevents_a_later_alias_redirect(self):
parent = self.root / "stage"
parent.mkdir()
retained = self.root / "retained-stage"
destination = parent / "Info.plist"
original = POLICY.OwnedBuildRoot._parent
with tempfile.TemporaryDirectory() as external:
def swap_after_parent_open(root, path):
descriptor, name = original(root, path)
if Path(path) == destination:
parent.rename(retained)
parent.symlink_to(external, target_is_directory=True)
return descriptor, name
with mock.patch.object(POLICY.OwnedBuildRoot, "_parent", swap_after_parent_open):
POLICY.write_plist(self.template, destination, VERSION, COMMIT)
self.assertFalse((Path(external) / "Info.plist").exists())
self.assertEqual(plistlib.loads((retained / "Info.plist").read_bytes())["FigCraftVersion"], VERSION)
if __name__ == "__main__":
unittest.main()
+453
View File
@@ -0,0 +1,453 @@
#!/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 time
import unittest
import zipfile
HERE = Path(__file__).resolve().parent
SPEC = importlib.util.spec_from_file_location("fig_mac_nightly_plist", HERE / "nightly_plist.py")
PLIST = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(PLIST)
COMMIT = "b" * 40
VERSION = "0.18.1-nightly.20261124.4567.1.g" + COMMIT[:12]
ASSET = f"figcraft-{VERSION}-macos-aarch64-nightly.zip"
APP = "FigCraft Nightly.app"
TEAM = "ABCDE12345"
IDENTITY = "0123456789ABCDEF0123456789ABCDEF01234567"
SECRETS = {
"APPLE_CERTIFICATE": base64.b64encode(b"generated fixture, not a certificate").decode(),
"APPLE_CERTIFICATE_PASSWORD": "generated-fixture",
"KEYCHAIN_PASSWORD": "generated-fixture",
"APPLE_ID": "fixture@example.invalid",
"APPLE_PASSWORD": "generated-fixture",
"APPLE_TEAM_ID": TEAM,
}
# One stand-in for every Apple tool, dispatched on its own name. Each logs its argv as a JSON line.
SHIM = r"""
import json, os, plistlib, sys, zipfile
from pathlib import Path
name = Path(sys.argv[0]).name
args = sys.argv[1:]
with open(os.environ["SHIM_LOG"], "a") as log:
log.write(json.dumps([name] + args) + "\n")
team = os.environ.get("SHIM_TEAM", "")
if name == "uname":
print({"-s": "Darwin", "-m": "arm64"}.get(args[0], "Darwin"))
elif name == "lipo":
print("arm64")
elif name == "ditto":
paths = [a for a in args if not a.startswith("-")]
src, dst = paths
if "-x" in args:
with zipfile.ZipFile(src) as z:
for info in z.infolist():
target = Path(dst) / info.filename
if info.is_dir():
target.mkdir(parents=True, exist_ok=True)
continue
target.parent.mkdir(parents=True, exist_ok=True)
target.write_bytes(z.read(info))
mode = (info.external_attr >> 16) & 0o777
if mode:
target.chmod(mode)
else:
root = Path(src)
with zipfile.ZipFile(dst, "x") as z:
for path in sorted([root] + list(root.rglob("*"))):
arc = (Path(root.name) / path.relative_to(root)).as_posix()
if path.is_dir():
z.writestr(zipfile.ZipInfo(arc + "/"), b"")
else:
info = zipfile.ZipInfo(arc)
info.external_attr = (path.stat().st_mode & 0xFFFF) << 16
z.writestr(info, path.read_bytes())
elif name == "plutil":
if args[0] == "-lint":
sys.exit(0)
key, fmt, source = args[1], args[2], args[-1]
data = sys.stdin.read() if source == "-" else Path(source).read_bytes()
value = json.loads(data) if source == "-" else plistlib.loads(data)
if key not in value:
sys.exit(1)
print(value[key] if fmt == "raw" else "<present/>")
elif name == "security":
verb = args[0]
if verb == "create-keychain":
Path(args[-1]).write_bytes(b"keychain")
elif verb == "find-identity":
print(' 1) %s "Developer ID Application: Generated Fixture (%s)"' % (os.environ["SHIM_IDENTITY"], team))
print(" 1 valid identities found")
elif verb == "delete-keychain":
Path(args[-1]).unlink()
elif name == "codesign":
target = Path(args[-1])
if "--sign" in args and target.suffix == ".app":
(target / "Contents/_CodeSignature").mkdir(exist_ok=True)
(target / "Contents/_CodeSignature/CodeResources").write_bytes(b"sealed")
if "-d" in args:
sys.stderr.write("Executable=%s\nIdentifier=ai.storyteller.figcraft.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=24 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/FigCraft"
exe.write_text(gui or f"#!/bin/sh\ntouch {self.ran}\necho 'FigCraft {version} (nightly-v1)'\n")
exe.chmod(0o755)
(app / "Contents/Resources/figcraft-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=180)
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.figcraft.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=24 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"figcraft-0.18.1-macos-aarch64.zip", f"figcraft-{VERSION}-macos-universal-nightly.zip",
f"figcraft-{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=24 Nov 2026\n", "Signed Time=24 Nov 2026\n"),
"Identifier=figcraft-1234\nSignature=adhoc\nTeamIdentifier=not set\n",
DETAILS.replace("ai.storyteller.figcraft.nightly", "ai.storyteller.figcraft"),
DETAILS.replace("ai.storyteller.figcraft.nightly", "aiXstorytellerXfigcraftXnightly")):
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_this_run_owns_only_a_keychain_named_for_the_app_inside_it(self):
with tempfile.TemporaryDirectory() as work:
# import-cert.sh puts the keychain in its own mktemp directory below the run directory.
nested = Path(work) / "figcraft-signing.AbCdEf"
nested.mkdir()
ours = nested / "figcraft-signing.keychain-db"
ours.write_bytes(b"keychain")
self.assertEqual(lib("mac_nightly_keychain_is_ours", str(ours), work)[0], 0)
direct = Path(work) / "figcraft-signing.keychain-db"
direct.write_bytes(b"keychain")
self.assertEqual(lib("mac_nightly_keychain_is_ours", str(direct), work)[0], 0)
for label, path in (("another app's name", nested / "figcraft-ui-signing.keychain-db"),
("outside the run", str(Path(work).parent / "figcraft-signing.keychain-db")),
("a directory", str(nested)),
("missing", str(nested / "missing.keychain-db")),
("empty", "")):
if label == "another app's name":
Path(path).write_bytes(b"keychain")
with self.subTest(label=label):
self.assertNotEqual(lib("mac_nightly_keychain_is_ours", path, work)[0], 0)
link = nested / "figcraft-signing.keychain-db"
link.unlink()
link.symlink_to(direct)
self.assertNotEqual(lib("mac_nightly_keychain_is_ours", str(link), work)[0], 0, "never through a link")
def test_gatekeeper_must_accept_the_bundle_as_notarized(self):
self.assertEqual(lib("mac_nightly_check_assessment", "x.app: accepted\nsource=Notarized Developer ID\n")[0], 0)
for text in ("x.app: accepted\nsource=Developer ID\n", "x.app: rejected\nsource=Unnotarized Developer ID\n"):
with self.subTest(text=text):
self.assertNotEqual(lib("mac_nightly_check_assessment", text)[0], 0)
def test_the_imported_identity_must_be_a_developer_id_of_the_team(self):
line = f' 1) {IDENTITY} "Developer ID Application: Generated Fixture ({TEAM})"'
self.assertEqual(lib("mac_nightly_identity_is_team", line, IDENTITY, TEAM)[0], 0)
self.assertNotEqual(lib("mac_nightly_identity_is_team", line, IDENTITY, "ZZZZZ99999")[0], 0)
self.assertNotEqual(lib("mac_nightly_identity_is_team", line.replace("Developer ID Application", "Apple Development"), IDENTITY, TEAM)[0], 0)
class Sign(unittest.TestCase):
def setUp(self):
self.f = Fixture(self)
self.f.bundle()
self.unsigned = self.f.input.read_bytes()
def assert_refused_untouched(self, result, signed=False):
self.assertNotEqual(result.returncode, 0, result.stdout)
self.assertFalse(self.f.output.exists())
self.assertEqual(self.f.input.read_bytes(), self.unsigned)
self.assertFalse(self.f.ran.exists(), "the payload must never run in the signing step")
names = [call[0] for call in self.f.calls()]
self.assertNotIn("cargo", names)
if not signed:
self.assertNotIn("codesign", names)
self.assertNotIn("xcrun", names)
self.assertEqual(list(self.f.temp.iterdir()), [], "the work directory and keychain are removed")
def test_signs_notarizes_and_staples_without_running_the_payload(self):
result = self.f.sign()
self.assertEqual(result.returncode, 0, result.stdout)
self.assertFalse(self.f.hijacked.exists(), "helpers run isolated (python3 -I) beside the secrets")
calls = self.f.calls()
names = [call[0] for call in calls]
self.assertNotIn("cargo", names)
self.assertFalse(self.f.ran.exists(), "the payload must never run in the signing step")
self.assertEqual(self.f.input.read_bytes(), self.unsigned)
signs = [call for call in calls if call[0] == "codesign" and "--sign" in call]
self.assertEqual([Path(call[-1]).name for call in signs], ["FigCraft", 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)
# The keychain is the one import-cert.sh made in its own directory of this run.
keychains = [call[call.index("--keychain") + 1] for call in signs]
self.assertTrue(all(Path(path).name == "figcraft-signing.keychain-db" for path in keychains), keychains)
self.assertTrue(all(Path(path).is_relative_to(self.f.temp) for path in keychains), keychains)
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/FigCraft").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/figcraft-cli": b"generated cli"}),
"version": dict(version=VERSION.replace("4567", "4568")),
}
for label, change in cases.items():
with self.subTest(label=label):
self.f.bundle(**change)
self.unsigned = self.f.input.read_bytes()
self.assert_refused_untouched(self.f.sign())
def test_refuses_links_traversal_and_foreign_entries_before_unpacking(self):
link = zipfile.ZipInfo(f"{APP}/Contents/Resources/link")
link.external_attr = (stat.S_IFLNK | 0o777) << 16
fifo = zipfile.ZipInfo(f"{APP}/Contents/Resources/fifo")
fifo.external_attr = (stat.S_IFIFO | 0o644) << 16
for label, info in (("link", link), ("special", fifo), ("traversal", zipfile.ZipInfo(f"{APP}/../outside")),
("absolute", zipfile.ZipInfo("/tmp/outside")), ("foreign root", zipfile.ZipInfo("Other.app/x"))):
with self.subTest(label=label):
self.f.bundle()
self.f.add_entry(info, b"/etc/passwd")
self.unsigned = self.f.input.read_bytes()
result = self.f.sign()
self.assert_refused_untouched(result)
self.assertNotIn("ditto", [call[0] for call in self.f.calls()], "refused before unpacking")
def test_a_rejected_notarization_publishes_nothing_and_removes_the_keychain(self):
result = self.f.sign(SHIM_NOTARY="Invalid")
self.assert_refused_untouched(result, signed=True)
self.assertIn(["xcrun", "notarytool", "log"], [call[:3] for call in self.f.calls()])
self.assertNotIn(["xcrun", "stapler", "staple"], [call[:3] for call in self.f.calls()])
class Verify(unittest.TestCase):
def setUp(self):
self.f = Fixture(self)
def verify(self, *args, **env):
return self.f.run("nightly-verify.sh", "--input", self.f.input, *args, **{name: None for name in SECRETS}, **env)
def test_asks_the_gui_its_version_with_an_empty_environment(self):
self.f.bundle(gui=f"#!/bin/sh\n[ -z \"$INHERITED\" ] || exit 9\necho 'FigCraft {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 'FigCraft 0.18.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 'FigCraft {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"},
FIGCRAFT_BUILD_CHANNEL="nightly-v1", FIGCRAFT_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()
+135
View File
@@ -0,0 +1,135 @@
#!/usr/bin/env python3
"""Flat Linux archive policy, invoked from its private owned build cwd.
The stage and archive must both remain under that independently chosen root.
No native build, platform signing, or malicious-same-UID sandbox is implied.
"""
import grp
import gzip
import os
import pathlib
import pwd
import re
import stat
import sys
import tarfile
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
from nightly_paths import OwnedBuildRoot
APP_DOCS = {"README.md", "LICENSE", "LICENSE-MIT", "LICENSE-APACHE", "COPYRIGHT", "NOTICE", "ATTRIBUTION.md"}
MAX_MEMBER_BYTES = 512 * 1024 * 1024
MAX_TOTAL_BYTES = 1024 * 1024 * 1024
MAX_MEMBERS = 128
def notice(name):
return name in APP_DOCS or re.fullmatch(r"OFL-[A-Za-z0-9_.-]+\.txt", name) is not None
def checked_entries(root, stage):
entries = sorted(root.children(stage, MAX_MEMBERS), key=lambda item: item.name)
folded = set()
total = 0
for entry in entries:
name = entry.name
if name not in {"figcraft", "figcraft-bin", "figcraft-nightly.png"} and not notice(name):
raise ValueError(f"unexpected nightly member: {name}")
if len(name.encode("utf-8")) > 100:
raise ValueError(f"nightly member must be a short regular file: {name}")
with root.reader(entry, MAX_MEMBER_BYTES) as stream:
total += os.fstat(stream.fileno()).st_size
if total > MAX_TOTAL_BYTES:
raise ValueError("nightly stage exceeds its read bound")
if name.casefold() in folded:
raise ValueError(f"case-colliding nightly member: {name}")
folded.add(name.casefold())
# The standard nightly layout: figcraft is the launcher that starts the GUI on the Launcher's
# nightly-v1 profile (packaging/linux/nightly-launch.sh), and figcraft-bin is that GUI, so an
# unpacked archive is isolated too.
required = {"figcraft", "figcraft-bin", "figcraft-nightly.png", "README.md", "LICENSE-MIT", "LICENSE-APACHE", "NOTICE", "ATTRIBUTION.md"}
if not required.issubset({item.name for item in entries}):
raise ValueError("required GUI/icon/notices missing")
return entries
def member_info(stage_root, name, incoming):
"""Header for one stage file, built from the file this run opened rather than from the archive.
Members are flat names that resolve directly inside the stage they came from.
"""
if os.path.isabs(name) or os.path.basename(name) != name or name in ("", ".", ".."):
raise ValueError(f"nightly member name must be a flat file name: {name}")
destination = os.path.realpath(os.path.join(stage_root, name))
if not destination.startswith(stage_root + os.sep) or os.path.dirname(destination) != stage_root:
raise ValueError(f"nightly member resolves outside its stage: {name}")
status = os.fstat(incoming.fileno())
if not stat.S_ISREG(status.st_mode):
raise ValueError(f"nightly member must be a regular file: {name}")
# The same fields TarFile.gettarinfo records for a regular file.
# The header keeps the validated stage name, not the resolved one: a stage symlink must
# never rename a member or leave a required name out of the archive.
info = tarfile.TarInfo(name)
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]))
+93
View File
@@ -0,0 +1,93 @@
# 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
[[ "${FIGCRAFT_BUILD_CHANNEL:-}" == nightly-v1 ]] || nightly_die 'FIGCRAFT_BUILD_CHANNEL must be nightly-v1'
[[ "${FIGCRAFT_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'
[[ "${FIGCRAFT_BUILD_SHA:-}" =~ ^[0-9a-f]{40}$ ]] || nightly_die 'an exact source commit is required'
[[ "${FIGCRAFT_VERSION##*.g}" == "${FIGCRAFT_BUILD_SHA:0:12}" ]] || nightly_die 'version/source commit mismatch'
[[ "${FIGCRAFT_BUILD_DATE:-}" =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}$ ]] || nightly_die 'the original run-created UTC date is required'
date_digits="${FIGCRAFT_VERSION#*-nightly.}"
date_digits="${date_digits%%.*}"
[[ "${FIGCRAFT_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)" == "$FIGCRAFT_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() {
# The guard sits here as well as in the entrypoints: no caller may compile with signing material.
nightly_refuse_signing_env
(cd "$ROOT" && FIGCRAFT_OVERRIDE_VERSION="$VERSION" cargo build --release --locked -p figcraft --target "$NIGHTLY_RUST_TARGET")
NIGHTLY_GUI="$CARGO_TARGET_DIR/$NIGHTLY_RUST_TARGET/release/figcraft"
[[ -f "$NIGHTLY_GUI" && ! -L "$NIGHTLY_GUI" ]] || nightly_die 'the owned GUI build did not produce a regular executable'
[[ "$(git -C "$ROOT" rev-parse HEAD)" == "$FIGCRAFT_BUILD_SHA" && -z "$(git -C "$ROOT" status --porcelain)" ]] || nightly_die 'source changed during the build'
}
nightly_build_gui() {
nightly_compile_gui
local actual
actual="$("$NIGHTLY_GUI" --version)" || nightly_die 'side-effect-free nightly version verification failed'
[[ "$actual" == "FigCraft $VERSION (nightly-v1)" ]] || nightly_die 'the built version/flavor is not the prepared identity'
[[ "$(git -C "$ROOT" rev-parse HEAD)" == "$FIGCRAFT_BUILD_SHA" && -z "$(git -C "$ROOT" status --porcelain)" ]] || nightly_die 'source changed during the version query'
}
# Signing material never reaches compilation (the Windows -CheckBuildEnvironment rule).
nightly_refuse_signing_env() {
local name
# The signing names release.yml passes, for every platform, and import-cert.sh's outputs.
for name in APPLE_CERTIFICATE APPLE_CERTIFICATE_PASSWORD KEYCHAIN_PASSWORD APPLE_ID APPLE_PASSWORD APPLE_TEAM_ID \
MACOS_SIGN_IDENTITY MACOS_KEYCHAIN WINDOWS_CERTIFICATE WINDOWS_CERTIFICATE_PASSWORD AZURE_TENANT_ID AZURE_CLIENT_ID \
AZURE_CLIENT_SECRET AZURE_SIGNING_ENDPOINT AZURE_SIGNING_ACCOUNT AZURE_CERT_PROFILE LINUX_SIGNING_KEY; do
[[ -z "${!name:-}" ]] || nightly_die "compilation must not receive signing configuration ($name); sign in the separate trusted step"
done
}
nightly_copy_notices() {
local destination="$1" required
for required in README.md LICENSE-MIT LICENSE-APACHE NOTICE ATTRIBUTION.md; do
[[ -f "$ROOT/$required" && ! -L "$ROOT/$required" ]] || nightly_die "missing regular app notice: $required"
done
copy_docs "$destination"
cp "$ROOT/ATTRIBUTION.md" "$destination/"
}
nightly_publish_archive() {
# Exclusive creation: never replace an existing artifact, even if another writer raced the preflight.
python3 -I - "$1" "$2" <<'PY'
import os, shutil, sys
source, destination = sys.argv[1:]
created = False
try:
# Open the input first: a missing source must not leave an empty final artifact.
with open(source, 'rb') as incoming:
with open(destination, 'xb') as output:
created = True
shutil.copyfileobj(incoming, output, length=1024 * 1024)
output.flush()
os.fsync(output.fileno())
except BaseException:
if created:
os.unlink(destination)
raise
PY
printf 'Nightly artifact: %s\n' "$2"
}
+123
View File
@@ -0,0 +1,123 @@
#!/usr/bin/env python3
"""The Nightly icons: the generator's output, the containers Windows and macOS read, and the
provenance record. No image tool, app build or signing is involved."""
import hashlib
import importlib.util
import json
import struct
import unittest
import zlib
from pathlib import Path
HERE = Path(__file__).resolve().parent
ROOT = HERE.parent
ICONS = ROOT / "assets/app-icon"
SPEC = importlib.util.spec_from_file_location("figcraft_nightly_icons", HERE / "nightly-icons.py")
ICON = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(ICON)
PROVENANCE = json.loads((ICONS / "nightly-provenance.json").read_text())
def png_size(data):
if data[:8] != b"\x89PNG\r\n\x1a\n" or data[12:16] != b"IHDR":
raise ValueError("not a PNG")
return struct.unpack(">II", data[16:24])
class Containers(unittest.TestCase):
def test_ico_holds_every_frame_at_the_size_it_names(self):
data = (ICONS / "figcraft-nightly.ico").read_bytes()
reserved, kind, count = struct.unpack("<HHH", data[:6])
self.assertEqual((reserved, kind), (0, 1))
self.assertEqual(count, len(ICON.ICO_DIB_SIZES) + len(ICON.ICO_PNG_SIZES))
sizes = []
for index in range(count):
width, height, colours, _, planes, bits, length, offset = struct.unpack("<BBBBHHII", data[6 + 16 * index : 22 + 16 * index])
self.assertEqual((colours, planes, bits), (0, 1, 32))
self.assertEqual(width, height)
sizes.append(256 if width == 0 else width)
blob = data[offset : offset + length]
self.assertEqual(len(blob), length)
if width == 0:
self.assertEqual(png_size(blob), (256, 256), "the 256 px frame is a PNG")
else:
header = struct.unpack("<IiiHHIIiiII", blob[:40])
self.assertEqual(header[0], 40, "a BITMAPINFOHEADER")
self.assertEqual((header[1], header[2]), (width, width * 2), "the doubled height covers the AND mask")
self.assertEqual(header[4], 32)
self.assertEqual(len(blob), 40 + width * width * 4 + ((width + 31) // 32) * 4 * width)
self.assertEqual(sizes, list(ICON.ICO_DIB_SIZES) + list(ICON.ICO_PNG_SIZES))
def test_icns_holds_every_png_slot_at_its_size(self):
data = (ICONS / "figcraft-nightly.icns").read_bytes()
self.assertEqual(data[:4], b"icns")
self.assertEqual(struct.unpack(">I", data[4:8])[0], len(data))
offset = 8
found = {}
while offset < len(data):
kind = data[offset : offset + 4]
(length,) = struct.unpack(">I", data[offset + 4 : offset + 8])
blob = data[offset + 8 : offset + length]
self.assertEqual(png_size(blob), (ICON_SIZE[kind],) * 2, kind)
self.assertNotIn(kind, found, "a duplicated slot")
found[kind] = offset
offset += length
self.assertEqual(set(found), {kind for kind, _ in ICON.ICNS_SLOTS})
def test_png_frames_are_well_formed_and_distinct_sizes(self):
for size in ICON.PNG_SIZES:
path = ICONS / ICON.file_name(size)
data = path.read_bytes()
self.assertEqual(png_size(data), (size, size), path.name)
# Decompressing the frames proves the CRCs and the zlib stream are intact.
offset, idat = 8, b""
while offset < len(data):
(length,) = struct.unpack(">I", data[offset : offset + 4])
kind = data[offset + 4 : offset + 8]
body = data[offset + 8 : offset + 8 + length]
self.assertEqual(zlib.crc32(kind + body) & 0xFFFFFFFF, struct.unpack(">I", data[offset + 8 + length : offset + 12 + length])[0])
if kind == b"IDAT":
idat += body
offset += 12 + length
self.assertEqual(len(zlib.decompress(idat)), (size * 4 + 1) * size, path.name)
def test_the_nightly_field_is_deeper_and_the_palette_is_the_committed_one(self):
self.assertEqual(ICON.PALETTE_FIELD, (0x02, 0xDA, 0x96), "the stable icon's field colour")
self.assertEqual(ICON.NIGHTLY_FIELD, tuple(bytes.fromhex(PROVENANCE["method"]["nightly_background"].lstrip("#"))))
stable = json.loads((ICONS / "nightly-provenance.json").read_text())["method"]["original_palette"]["background"]
self.assertEqual(stable, "#02da96")
self.assertLess(sum(ICON.NIGHTLY_FIELD), sum(ICON.PALETTE_FIELD), "a deeper field, not a brighter one")
def test_the_committed_files_are_what_the_generator_makes(self):
for name, data in ICON.build().items():
committed = (ICONS / name).read_bytes()
self.assertEqual(committed, data, name)
class Provenance(unittest.TestCase):
def test_every_recorded_input_and_output_matches_its_sha256(self):
for entry in PROVENANCE["inputs"]:
path = ROOT / entry["path"]
self.assertEqual(hashlib.sha256(path.read_bytes()).hexdigest(), entry["sha256"], entry["path"])
for name, digest in PROVENANCE["outputs"].items():
path = ROOT / name
self.assertEqual(hashlib.sha256(path.read_bytes()).hexdigest(), digest, name)
generated = {f"assets/app-icon/{name}" for name in ICON.build()}
self.assertEqual(set(PROVENANCE["outputs"]), generated, "every generated file is recorded")
def test_the_record_names_the_generator_that_made_the_bytes(self):
generator = HERE / "nightly-icons.py"
self.assertEqual(hashlib.sha256(generator.read_bytes()).hexdigest(), PROVENANCE["method"]["generator_sha256"])
self.assertEqual(PROVENANCE["ico_frame_sizes"], list(ICON.ICO_DIB_SIZES) + list(ICON.ICO_PNG_SIZES))
self.assertEqual(PROVENANCE["icns_png_slots"], {kind.decode(): size for kind, size in ICON.ICNS_SLOTS})
def test_the_slots_match_the_frames_they_name(self):
self.assertEqual(sorted(PROVENANCE["ico_frame_sizes"]), [16, 32, 48, 64, 128, 256])
# The sizes the committed .icns slots carry, as the container test reads them.
ICON_SIZE = {kind: size for kind, size in ICON.ICNS_SLOTS}
if __name__ == "__main__":
unittest.main()
+276
View File
@@ -0,0 +1,276 @@
#!/usr/bin/env python3
"""Derive the Nightly app icons from the committed stable master, with no image tools needed.
The Nightly uses the same chameleon on a deeper field, so the two icons are told apart at 16 px
without a badge, crescent or letter. Nothing is upscaled: the 1024 px render (the real padded
macOS-grid master) is the only input, and every smaller frame is an area average of it, so each
size is rendered from the full detail.
The background contribution of every pixel is solved from the palette's three colours (ink and
paper are neutral, the field is saturated), the field colour is moved and the ink, paper, shading
and alpha are left exactly as they are.
python3 packaging/nightly-icons.py [--check]
`--check` writes nothing and reports whether the committed files match what this script makes.
"""
import argparse
import hashlib
import struct
import sys
import zlib
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
ICONS = ROOT / "assets/app-icon"
MASTER = ICONS / "figcraft-1024.png"
PALETTE_FIELD = (0x02, 0xda, 0x96) # FigCraft green, the committed field
NIGHTLY_FIELD = (0x01, 0x96, 0x68) # the same field, deeper: one third of the way to black
MASTER_SIZE = 1024
# Windows frames: 32bpp DIBs up to 128 px (what every resource compiler and Explorer accepts) and
# one PNG frame for 256. macOS: PNG payloads per slot, including the @2x slots iconutil expects.
ICO_DIB_SIZES = (16, 32, 48, 64, 128)
ICO_PNG_SIZES = (256,)
ICNS_SLOTS = ((b"icp4", 16), (b"icp5", 32), (b"ic11", 32), (b"icp6", 64), (b"ic12", 64), (b"ic07", 128), (b"ic08", 256), (b"ic13", 256), (b"ic09", 512), (b"ic14", 512), (b"ic10", 1024))
PNG_SIZES = (1024, 512, 256, 128, 64, 48, 32, 16)
def read_png(path):
"""The image's width, height and RGBA rows of an 8-bit PNG (no interlace)."""
data = path.read_bytes()
if data[:8] != b"\x89PNG\r\n\x1a\n":
raise ValueError(f"{path} is not a PNG")
offset, header, idat = 8, None, bytearray()
while offset < len(data):
(length,) = struct.unpack(">I", data[offset : offset + 4])
kind = data[offset + 4 : offset + 8]
body = data[offset + 8 : offset + 8 + length]
offset += 12 + length
if kind == b"IHDR":
header = struct.unpack(">IIBBBBB", body)
elif kind == b"IDAT":
idat += body
elif kind == b"IEND":
break
if header is None:
raise ValueError(f"{path} has no IHDR")
width, height, depth, colour, compression, filtering, interlace = header
if depth != 8 or compression != 0 or filtering != 0 or interlace != 0 or colour not in (2, 6):
raise ValueError(f"{path}: expected a non-interlaced 8-bit RGB or RGBA PNG")
channels = 4 if colour == 6 else 3
stride = width * channels
raw = zlib.decompress(bytes(idat))
if len(raw) != (stride + 1) * height:
raise ValueError(f"{path}: unexpected pixel data length")
rows, previous = [], bytearray(stride)
for y in range(height):
start = y * (stride + 1)
filter_type = raw[start]
line = bytearray(raw[start + 1 : start + 1 + stride])
unfilter(filter_type, line, previous, channels)
rows.append(bytes(line))
previous = line
if channels == 3:
rows = [bytes(component for x in range(width) for component in (*row[3 * x : 3 * x + 3], 255)) for row in rows]
return width, height, rows
def unfilter(filter_type, line, previous, bpp):
if filter_type == 0:
return
if filter_type == 1:
for i in range(bpp, len(line)):
line[i] = (line[i] + line[i - bpp]) & 0xFF
elif filter_type == 2:
for i in range(len(line)):
line[i] = (line[i] + previous[i]) & 0xFF
elif filter_type == 3:
for i in range(len(line)):
left = line[i - bpp] if i >= bpp else 0
line[i] = (line[i] + ((left + previous[i]) >> 1)) & 0xFF
elif filter_type == 4:
for i in range(len(line)):
left = line[i - bpp] if i >= bpp else 0
up = previous[i]
upleft = previous[i - bpp] if i >= bpp else 0
estimate = left + up - upleft
pa, pb, pc = abs(estimate - left), abs(estimate - up), abs(estimate - upleft)
predictor = left if pa <= pb and pa <= pc else (up if pb <= pc else upleft)
line[i] = (line[i] + predictor) & 0xFF
else:
raise ValueError(f"unknown PNG filter type {filter_type}")
def deepen(row, width):
"""One row of the master's RGBA with only the field colour moved."""
delta = (NIGHTLY_FIELD[0] - PALETTE_FIELD[0], NIGHTLY_FIELD[1] - PALETTE_FIELD[1], NIGHTLY_FIELD[2] - PALETTE_FIELD[2])
between = (PALETTE_FIELD[0] - PALETTE_FIELD[1], PALETTE_FIELD[1] - PALETTE_FIELD[2])
denominator = between[0] * between[0] + between[1] * between[1]
out = bytearray(row)
for x in range(width):
i = x * 4
alpha = row[i + 3]
if alpha == 0:
continue
red, green, blue = row[i], row[i + 1], row[i + 2]
# ink and paper are neutral, so a pixel's saturation is exactly its field contribution
weight = ((red - green) * between[0] + (green - blue) * between[1]) / denominator
if weight <= 0:
continue
weight = min(weight, 1.0)
for channel in range(3):
out[i + channel] = min(255, max(0, round(row[i + channel] + weight * delta[channel])))
return bytes(out)
def taps(width, size):
"""For each output index: the source indices it covers and their fractional weights."""
scale = width / size
out = []
for index in range(size):
low, high = index * scale, (index + 1) * scale
first, last = int(low), min(width, int(high) + (1 if high > int(high) else 0))
weights = [(source, min(high, source + 1) - max(low, source)) for source in range(first, last)]
total = sum(weight for _, weight in weights)
out.append([(source, weight / total) for source, weight in weights if weight > 0])
return out
def average(rows, width, size):
"""The area average of the `width`-square image into `size` square rows, in premultiplied alpha.
Any ratio works (a 48 px frame is 21.33 source pixels wide), so every size is a true average of
the master rather than a crop or a nearest sample.
"""
if width == size:
return rows
columns = taps(width, size)
# Horizontal pass: premultiplied RGBA per output column.
horizontal = []
for row in rows:
line = []
for weights in columns:
red = green = blue = alpha = 0.0
for source, weight in weights:
i = source * 4
a = row[i + 3]
red += row[i] * a * weight
green += row[i + 1] * a * weight
blue += row[i + 2] * a * weight
alpha += a * weight
line.append((red, green, blue, alpha))
horizontal.append(line)
out = []
for weights in taps(width, size):
row = bytearray(size * 4)
for x in range(size):
red = green = blue = alpha = 0.0
for source, weight in weights:
r, g, b, a = horizontal[source][x]
red += r * weight
green += g * weight
blue += b * weight
alpha += a * weight
i = x * 4
if alpha > 0:
row[i] = min(255, round(red / alpha))
row[i + 1] = min(255, round(green / alpha))
row[i + 2] = min(255, round(blue / alpha))
row[i + 3] = min(255, round(alpha))
out.append(bytes(row))
return out
def dib(rows, size):
"""A 32bpp bottom-up DIB frame with its 1bpp AND mask, as Explorer and rc.exe expect."""
header = struct.pack("<IiiHHIIiiII", 40, size, size * 2, 1, 32, 0, size * size * 4, 0, 0, 0, 0)
pixels = bytearray()
for y in range(size - 1, -1, -1):
line = rows[y]
for x in range(size):
i = x * 4
pixels += bytes((line[i + 2], line[i + 1], line[i], line[i + 3]))
mask_row = ((size + 31) // 32) * 4
mask = bytearray(mask_row * size)
for y in range(size):
line = rows[y]
target = (size - 1 - y) * mask_row
for x in range(size):
if line[x * 4 + 3] == 0:
mask[target + (x // 8)] |= 0x80 >> (x % 8)
return header + bytes(pixels) + bytes(mask)
def ico(frames):
count = len(frames)
header = struct.pack("<HHH", 0, 1, count)
offset = 6 + 16 * count
entries, blobs = bytearray(), bytearray()
for size, blob in frames:
dimension = 0 if size >= 256 else size
entries += struct.pack("<BBBBHHII", dimension, dimension, 0, 0, 1, 32, len(blob), offset)
blobs += blob
offset += len(blob)
return header + bytes(entries) + bytes(blobs)
def icns(payloads):
body = bytearray()
for kind, size in ICNS_SLOTS:
blob = payloads[size]
body += kind + struct.pack(">I", len(blob) + 8) + blob
return b"icns" + struct.pack(">I", len(body) + 8) + bytes(body)
def build():
width, height, rows = read_png(MASTER)
if (width, height) != (MASTER_SIZE, MASTER_SIZE):
raise ValueError(f"{MASTER} must be {MASTER_SIZE}x{MASTER_SIZE}, not {width}x{height}")
deep = [deepen(row, width) for row in rows]
rendered = {size: average(deep, width, size) for size in PNG_SIZES}
files = {}
for size in PNG_SIZES:
files[file_name(size)] = png_bytes(rendered[size], size)
files["figcraft-nightly.ico"] = ico([(size, dib(rendered[size], size)) for size in ICO_DIB_SIZES] + [(size, files[file_name(size)]) for size in ICO_PNG_SIZES])
files["figcraft-nightly.icns"] = icns({size: files[file_name(size)] for _, size in ICNS_SLOTS})
return files
def file_name(size):
"""The committed file a frame of `size` px lives in (the 512 one is the plain nightly PNG)."""
return "figcraft-nightly.png" if size == 512 else f"figcraft-nightly-{size}.png"
def png_bytes(rows, size):
def chunk(kind, body):
return struct.pack(">I", len(body)) + kind + body + struct.pack(">I", zlib.crc32(kind + body) & 0xFFFFFFFF)
raw = b"".join(b"\x00" + row for row in rows)
return (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", size, size, 8, 6, 0, 0, 0)) + chunk(b"IDAT", zlib.compress(raw, 9)) + chunk(b"IEND", b""))
def main():
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("--check", action="store_true", help="report differences instead of writing")
args = parser.parse_args()
files = build()
stale = []
for name, data in sorted(files.items()):
path = ICONS / name
if args.check:
if not path.exists() or path.read_bytes() != data:
stale.append(name)
continue
path.write_bytes(data)
print(f"{name}: {hashlib.sha256(data).hexdigest()}")
if args.check:
if stale:
print("out of date: " + ", ".join(stale), file=sys.stderr)
return 1
print("the committed nightly icons match this script")
return 0
if __name__ == "__main__":
sys.exit(main())
+368
View File
@@ -0,0 +1,368 @@
#!/usr/bin/env python3
"""Nightly workflow and policy contract regression tests (local static checks, not live API/crypto evidence)."""
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")
values[row[1]] = row[2].rstrip()
if values != {"group": "figcraft-nightly-release", "cancel-in-progress": "false"}:
raise ValueError("nightly serialization must use its stable group and no cancellation")
def job_conditions(jobs):
"""Each job-level `if:` as (block indicator or None, the whole expression YAML would read)."""
lines = jobs.splitlines()
found = []
for index, line in enumerate(lines):
head = re.fullmatch(r" if:(?: (.*))?", line)
if head is None:
continue
value = (head[1] or "").strip()
continuation = []
for follow in lines[index + 1:]:
if follow.strip() and len(follow) - len(follow.lstrip(" ")) <= 4:
break
continuation.append(follow.strip())
indicator = value if re.fullmatch(r"[>|][+-]?", value) else None
parts = continuation if indicator else [value] + continuation
found.append((indicator, " ".join(part for part in parts if part)))
return found
def producer_platforms(source):
"""Read the one producer job's literal platform list."""
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, workflow in (("nightly.yml", "nightly.yml"), ("nightly-sign.yml", "nightly-sign.yml")):
source = (ROOT / ".github/workflows" / workflow).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_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: true"),
("cancel-in-progress: false", "cancel-in-progress: ${{ github.event_name == 'push' }}"),
("cancel-in-progress: false\n", ""),
("cancel-in-progress: false", "cancel-in-progress: false\n cancel-in-progress: false"),
("group: figcraft-nightly-release", "group: ${{ github.run_id }}"),
("group: figcraft-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 actors."""
GUARDS = {
"nightly.yml": "github.repository == 'storytold/figcraft' && github.ref == 'refs/heads/main' && "
"github.ref_type == 'branch' && (github.event_name == 'schedule' || "
"github.event_name == 'workflow_dispatch')",
"nightly-sign.yml": "github.repository == 'storytold/figcraft' && 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)
class NightlyInstalledPolicy(unittest.TestCase):
"""The installed v3 policy matches the callers, the repository and its documented sources."""
EXPECTED_KEYS = {
"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",
}
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):
self.assertEqual(set(self.policy), self.EXPECTED_KEYS)
self.assertEqual(self.policy["schema"], "craft-nightly-release-policy/v3")
self.assertEqual(self.policy["repository"], "storytold/figcraft")
self.assertEqual(self.policy["release_branch"], "release")
self.assertIs(type(self.policy["repository_id"]), int)
self.assertGreater(self.policy["repository_id"], 0)
# producer_workflow_id is None until nightly.yml is registered on main.
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), "one release carries Windows, Linux and macOS")
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/figcraft", "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 = re.search(r"(?m)^ push:\n((?: .*\n)+)", source)
self.assertIsNotNone(push, "a required workflow must run on main pushes")
self.assertIn(" branches: [main]\n", push[1])
self.assertNotRegex(push[1], r"paths", "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_sonar_identity_and_reviewed_scope(self):
sonar = self.policy["candidate_policy"]["sonar"]
properties = dict(line.split("=", 1) for line in (ROOT / "sonar-project.properties").read_text().splitlines()
if line and not line.startswith("#"))
self.assertEqual(sonar["organization"], properties["sonar.organization"])
self.assertEqual(sonar["project"], properties["sonar.projectKey"])
self.assertEqual((sonar["app_id"], sonar["check_name"]), (12526, "SonarCloud Code Analysis"))
self.assertEqual(sonar["details_url"], "https://sonarcloud.io/dashboard?id=" + sonar["project"] + "&branch=main")
accepted = {"bugs": "BUG", "vulnerabilities": "VULNERABILITY", "code_smells": "CODE_SMELL",
"security_rating": "VULNERABILITY", "new_security_rating": "VULNERABILITY"}
self.assertEqual({accepted[c["metric"]] for c in sonar["accepted_conditions"]}, set(sonar["issue_types"]))
metrics = [c["metric"] for c in sonar["accepted_conditions"] + sonar["required_conditions"]]
self.assertEqual(len(metrics), len(set(metrics)))
keys = [item["key"] for item in sonar["debt"]]
self.assertEqual(len(keys), len(set(keys)))
for item in sonar["debt"]:
with self.subTest(issue=item["key"]):
self.assertEqual(set(item), {"key", "rule", "component", "type", "severity", "hash"})
self.assertTrue(item["component"].startswith(sonar["project"] + ":"))
self.assertIn(item["type"], sonar["issue_types"])
self.assertRegex(item["hash"], r"^[0-9a-f]{32}$")
if __name__ == "__main__":
unittest.main(verbosity=2)
+25
View File
@@ -0,0 +1,25 @@
#!/usr/bin/env python3
"""Run the app-side synthetic Nightly suites together; no app build, signing or network."""
import importlib.util
from pathlib import Path
import unittest
def main() -> int:
here = Path(__file__).resolve().parent
suite = unittest.TestSuite()
for name, relative in (
("fig_icon_suite", "nightly-icon-tests.py"),
("fig_plist_suite", "macos/nightly_plist_tests.py"),
("fig_release_dispatch_suite", "nightly-release-tests.py"),
("fig_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.18.1-nightly.20261124.17.1.gabcdef012345' 'x64'
Assert ($spec.Archive -eq 'figcraft-0.18.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 'figcraft.exe') 'nightly must not ship the CLI'
Assert ($spec.AppId -eq 'ai.storyteller.figcraft.nightly-v1') 'nightly identity is not distinct'
foreach ($arch in @('x86', 'arm64')) {
$refused = $false
try { Get-NightlyArchiveSpec '0.18.1' $arch | Out-Null } catch { $refused = $true }
Assert $refused 'unsupported target was accepted'
}
foreach ($bad in @('', '0.18.1', '../other', '0.18.1/elsewhere')) {
$refused = $false
try { Get-NightlyArchiveSpec $bad 'x64' | Out-Null } catch { $refused = $true }
Assert $refused 'unsafe artifact version was accepted'
}
Assert-NightlyFlavor 'FigCraft Nightly' 'FigCraft 0.18.1-nightly.20261124.17.1.gabcdef012345 (nightly-v1)' '0.18.1-nightly.20261124.17.1.gabcdef012345'
foreach ($pair in @(@('FigCraft', 'FigCraft 0.18.1 (nightly-v1)'), @('FigCraft Nightly', 'FigCraft 0.18.1'))) {
$refused = $false
try { Assert-NightlyFlavor $pair[0] $pair[1] '0.18.1-nightly.20261124.17.1.gabcdef012345' } catch { $refused = $true }
Assert $refused 'stable or mismatched build flavor was accepted'
}
$sha = 'abcdef0123456789abcdef0123456789abcdef01'
$good = '0.18.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.18.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/figcraft/src/main.rs')
)
foreach ($case in $cases) {
$refused = $false
try { Assert-NightlySource $case[1] $case[2] $case[3] $case[4] $case[5] } catch { $refused = $true }
Assert $refused "source identity accepted: $($case[0])"
}
Write-Output 'nightly packaging spec, target/version refusal, source identity and flavor-binding tests passed'
# Exercise the SAME production notice copier with the real repository layout, then inspect a ZIP.
if (-not $FixtureRoot -or -not [IO.Path]::IsPathRooted($FixtureRoot)) { throw 'supply an owned absolute -FixtureRoot for the notices/ZIP regression' }
$testRoot = Join-Path $FixtureRoot ("nightly-notices-" + [Guid]::NewGuid().ToString('N'))
try {
$repo = Join-Path $testRoot 'app'
$fontRepo = Join-Path $testRoot 'craft-fonts'
$family = Join-Path $fontRepo 'fonts\ExampleFamily'
$stage = Join-Path $testRoot 'stage'
New-Item -ItemType Directory -Force -Path $repo, $family, $stage | Out-Null
$rootNames = @('README.md', 'LICENSE', 'LICENSE-MIT', 'LICENSE-APACHE', 'NOTICE', 'ATTRIBUTION.md')
foreach ($name in $rootNames) { Set-Content -LiteralPath (Join-Path $repo $name) -Value "root-notice-$name" }
Set-Content -LiteralPath (Join-Path $family 'OFL.txt') -Value 'font-notice-example'
Copy-NightlyNotices $repo $fontRepo $stage
foreach ($name in @($rootNames) + @('OFL-ExampleFamily.txt')) {
Assert (Test-Path -LiteralPath (Join-Path $stage $name)) "missing staged notice $name"
}
$zip = Join-Path $testRoot 'notices.zip'
Compress-Archive -Path (Join-Path $stage '*') -DestinationPath $zip
$archive = [IO.Compression.ZipFile]::OpenRead($zip)
try {
$names = @($archive.Entries | ForEach-Object { $_.FullName })
foreach ($name in @($rootNames) + @('OFL-ExampleFamily.txt')) { Assert ($name -in $names) "missing archived notice $name" }
foreach ($forbidden in @('portable', 'figcraft-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.18.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,90 @@
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 fixture mocks Cargo, but nightly.ps1 checks the same source identity a packaging run does:
# the version names this checkout's commit and the run's UTC date, and the tree is clean. Deriving
# them here keeps the fixture reaching the mocked compiler instead of failing in source validation.
$sha = "$(git -C $PSScriptRoot rev-parse HEAD)".Trim()
$runDate = (Get-Date).ToUniversalTime().ToString('yyyyMMdd')
$version = "0.18.1-nightly.$runDate.12345.1.g$($sha.Substring(0, 12))"
$env:FIGCRAFT_VERSION = $version
$env:FIGCRAFT_BUILD_SHA = $sha
$env:FIGCRAFT_BUILD_DATE = "$($runDate.Substring(0, 4))-$($runDate.Substring(4, 2))-$($runDate.Substring(6, 2))"
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
}
+135
View File
@@ -0,0 +1,135 @@
<# 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 = "figcraft-$Version-windows-x86_64-nightly.zip"
UnsignedArchive = "figcraft-$Version-windows-x86_64-nightly.unsigned.zip"
Executables = @('figcraft.exe')
Channel = 'nightly-v1'
AppId = 'ai.storyteller.figcraft.nightly-v1'
}
}
# The same source identity the Linux helper enforces (nightly-common.sh): the version names the
# commit being built, the date is the original run's, and the tree is clean.
function Assert-NightlySource([string] $Version, [string] $Sha, [string] $BuildDate, [string] $Head, [string] $Status) {
if ($Sha -cnotmatch '^[0-9a-f]{40}\z') { throw 'an exact source commit is required (FIGCRAFT_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 (FIGCRAFT_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 'FigCraft Nightly' -or $VersionOutput -cne "FigCraft $ExpectedVersion (nightly-v1)") {
throw 'the executable is not the compiled nightly-v1 flavor'
}
}
function Copy-NightlyNotices([string] $RepositoryRoot, [string] $FontRepository, [string] $Destination) {
foreach ($name in 'README.md', 'LICENSE', 'LICENSE-MIT', 'LICENSE-APACHE', 'NOTICE', 'ATTRIBUTION.md') {
$source = Join-Path $RepositoryRoot $name
if (Test-Path -LiteralPath $source) { Copy-Item -LiteralPath $source -Destination $Destination }
}
if ($FontRepository) {
$fonts = Join-Path $FontRepository 'fonts'
if (-not (Test-Path -LiteralPath $fonts -PathType Container)) { throw 'CRAFT_FONTS_DIR has no fonts directory for the bundled notices' }
foreach ($family in Get-ChildItem -LiteralPath $fonts -Directory) {
$license = Join-Path $family.FullName 'OFL.txt'
if (Test-Path -LiteralPath $license) { Copy-Item -LiteralPath $license -Destination (Join-Path $Destination "OFL-$($family.Name).txt") }
}
}
}
if ($FunctionsOnly) { return }
# The prepared version comes from the nightly callers: `FIGCRAFT_VERSION` (packaging/env.sh) or the
# override `packaging/nightly-common.sh` hands the compiler. The Cargo version is never a fallback.
$Prepared = if ($env:FIGCRAFT_OVERRIDE_VERSION) { $env:FIGCRAFT_OVERRIDE_VERSION } else { $env:FIGCRAFT_VERSION }
if (-not $Prepared -or $Version -cne $Prepared) { throw 'nightly-v1 requires explicit FIGCRAFT_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:FIGCRAFT_BUILD_SHA $env:FIGCRAFT_BUILD_DATE $Source.Head $Source.Status
$oldChannel = $env:FIGCRAFT_BUILD_CHANNEL
$oldVersionOverride = $env:FIGCRAFT_OVERRIDE_VERSION
try {
$env:FIGCRAFT_BUILD_CHANNEL = 'nightly-v1'
$env:FIGCRAFT_OVERRIDE_VERSION = $Version
$env:FIGCRAFT_REQUIRE_WINRES = '1'
$env:CARGO_TARGET_X86_64_PC_WINDOWS_MSVC_RUSTFLAGS = '-C target-feature=+crt-static'
cargo build --release --locked -p figcraft --target $Target
if ($LASTEXITCODE -ne 0) { throw "nightly cargo build failed: $LASTEXITCODE" }
} finally {
$env:FIGCRAFT_BUILD_CHANNEL = $oldChannel
$env:FIGCRAFT_OVERRIDE_VERSION = $oldVersionOverride
}
$Source = Get-NightlySourceState $Root
try { Assert-NightlySource $Version $env:FIGCRAFT_BUILD_SHA $env:FIGCRAFT_BUILD_DATE $Source.Head $Source.Status }
catch { throw "source changed during the build: $_" }
$Exe = Join-Path $TargetDir "$Target\release\figcraft.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 'FigCraft 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 'figcraft.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'))) {
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 ('figcraft.exe' -notin $Names -or 'figcraft-cli.exe' -in $Names -or 'portable' -in $Names) {
throw 'nightly ZIP payload violates the GUI-only profile contract'
}
} finally { $Archive.Dispose() }
Write-Output "Nightly build intermediate (not publishable): $Zip ($VersionOutput)"
+23 -3
View File
@@ -24,9 +24,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) {
@@ -53,8 +56,11 @@ $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:FIGCRAFT_BUILD_SHA) { $env:FIGCRAFT_BUILD_SHA = (git -C $Root rev-parse HEAD 2>$null) }
if (-not $env:FIGCRAFT_BUILD_DATE) { $env:FIGCRAFT_BUILD_DATE = (Get-Date).ToUniversalTime().ToString('yyyy-MM-dd') }
# Nightly requires the prepared commit and original run date explicitly; nightly.ps1 checks both.
if (-not $Nightly) {
if (-not $env:FIGCRAFT_BUILD_SHA) { $env:FIGCRAFT_BUILD_SHA = (git -C $Root rev-parse HEAD 2>$null) }
if (-not $env:FIGCRAFT_BUILD_DATE) { $env:FIGCRAFT_BUILD_DATE = (Get-Date).ToUniversalTime().ToString('yyyy-MM-dd') }
}
# The headless CLI ships next to the app once apps/figcraft-cli exists.
$HasCli = Test-Path (Join-Path $Root 'apps\figcraft-cli\Cargo.toml')
@@ -62,11 +68,22 @@ $Bins = @('figcraft'); if ($HasCli) { $Bins += 'figcraft-cli' }
Write-Output "FigCraft $Version for Windows $Arch ($Target): $($Bins -join ', ')"
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) {
# The stable channel, explicitly: a leftover nightly value in the environment must not build a
# Nightly executable into this package.
$env:FIGCRAFT_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'
[Environment]::SetEnvironmentVariable($flagVar, '-C target-feature=+crt-static')
# Fail the build (rather than warn) if the icon/VERSIONINFO can't be embedded: the MSI, the
# Launcher's ProductVersion check and the taskbar name all read them.
$env:FIGCRAFT_REQUIRE_WINRES = '1'
$pkgs = @(); foreach ($b in $Bins) { $pkgs += @('-p', $b) }
Invoke-Native "cargo build ($Target)" { cargo build --release --locked @pkgs --target $Target }
}
@@ -90,6 +107,9 @@ foreach ($check in $checks) {
if ($h.Subsystem -ne $check[1]) { throw "$($check[0]) has PE subsystem $($h.Subsystem), expected $($check[1])" }
Write-Output "ok $($check[0]): $Arch, PE subsystem $($h.Subsystem)"
}
if ((Get-Item -LiteralPath (Join-Path $Bin 'figcraft.exe')).VersionInfo.ProductName -eq 'FigCraft Nightly') {
throw 'a nightly executable cannot be packaged as stable'
}
$Stage = Join-Path $TargetDir "windows-package\$Arch"
Remove-Item -Recurse -Force $Stage -ErrorAction SilentlyContinue
New-Item -ItemType Directory -Force -Path $Stage | Out-Null
+36 -5
View File
@@ -9,7 +9,9 @@
AZURE_SIGNING_ENDPOINT (e.g. https://eus.codesigning.azure.net),
AZURE_SIGNING_ACCOUNT, AZURE_CERT_PROFILE
With neither, it prints a warning and leaves the files unsigned (exit code 0), so test builds
still produce installers.
still produce installers. Nightly callers require signing with -Required and can check the
signing configuration with -Required -CheckOnly. Compilation uses the separate
-CheckBuildEnvironment mode, without importing signing keys.
This is the one place to adapt when the signing setup changes (an HSM/cloud key, a different
timestamp server, ...). Optional overrides: WINDOWS_TIMESTAMP_URL, SIGNTOOL (path to signtool.exe).
@@ -18,11 +20,20 @@
pwsh packaging/windows/sign.ps1 dist/figcraft.exe dist/FigCraft.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
+10
View File
@@ -4,6 +4,16 @@ sonar.organization=storytold
# Pinned integration-test fonts are data, not source code for analysis.
sonar.exclusions=craft-fonts/**
# Setting test roots disables the CLI default; keep all production sources analyzed. These exact
# fixture runners are the Nightly's tests, not production code; the packaging code they exercise
# stays analyzed (do not exclude the directory).
sonar.sources=.
sonar.tests=packaging
sonar.test.inclusions=packaging/nightly-tests.py,packaging/nightly-icon-tests.py,packaging/macos/nightly_plist_tests.py,packaging/macos/nightly_sign_tests.py,packaging/windows/nightly-package-tests.ps1,packaging/windows/nightly-signing-tests.ps1,packaging/nightly-release-tests.py
# Packaging scripts and their unittest suites are not measured by Rust coverage.
sonar.coverage.exclusions=packaging/**
# S4790 (weak hash): a .fig file names each image by the SHA-1 of its bytes (20 bytes, the only
# length readers accept). It is an identifier the format fixes, not a security choice.
sonar.issue.ignore.multicriteria=fig_image_sha1,gha-lockfile