diff --git a/.github/nightly-linux-signing-key.asc b/.github/nightly-linux-signing-key.asc new file mode 100644 index 0000000000..a1c1f31e8d --- /dev/null +++ b/.github/nightly-linux-signing-key.asc @@ -0,0 +1,16 @@ +-----BEGIN PGP PUBLIC KEY BLOCK----- + +mDMEaulK1xYJKwYBBAHaRw8BAQdAqHJeDCjY6Hx5FTn/hW+aqu6V394ubLk0Zj3C +bftDwFm0IkFydENyYWZ0IExpbnV4IFJlbGVhc2UgU2lnbmluZyBLZXmIkwQTFgoA +OxYhBCt2dBtBSq1s0z5jEhOgBcC518PtBQJq6UrXAhsBBQsJCAcCAiICBhUKCQgL +AgQWAgMBAh4HAheAAAoJEBOgBcC518PtGeUA/RjvULBTLlccc+2wtJkfjSnCV+cf +PUMEGmW7XkZWkk51AP9w2A/WLv+79nREWEpZzI8LGK5EjrNazP+sY0l7j5rFCLgz +BGrpStcWCSsGAQQB2kcPAQEHQPl7XkQ1gWsvSPf/T9b4m/UHcjJjBpSOtpYlWR56 +er5RiO8EGBYKACAWIQQrdnQbQUqtbNM+YxIToAXAudfD7QUCaulK1wIbAgCBCRAT +oAXAudfD7XYgBBkWCgAdFiEEVo3B9o+Prsx5fzx7AG2va7DvM04FAmrpStcACgkQ +AG2va7DvM07taQEA4d2VFkKRIP0g9TrE86KpnuXPap+LKqe0tfIxpdf9YxIA/0Wo +9H/iG8nH++nxC087p3HE0S+0UovxqkhXJLSr8B4JDOoA/iLRpqTdYmk6fVXMyPJo +SkOVuwZIGS6VgBdSQP0e2P2YAP41L5OoSvwdQIG3/uNrM+ieqpYeM597/hCLFs5A +ga/qCA== +=3wGQ +-----END PGP PUBLIC KEY BLOCK----- diff --git a/.github/nightly-signing-policy.json b/.github/nightly-signing-policy.json new file mode 100644 index 0000000000..02d5129b1c --- /dev/null +++ b/.github/nightly-signing-policy.json @@ -0,0 +1,107 @@ +{ + "schema": "craft-nightly-release-policy/v3", + "repository": "storytold/gridcraft", + "repository_id": 1408285582, + "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": "gridcraft-nightly-20261124", + "repository": "storytold/gridcraft", + "branch": "main", + "required_workflows": [ + { + "workflow_id": 380135773, + "workflow_path": ".github/workflows/ci.yml", + "jobs": [ + { + "name": "gate / gate (ubuntu-24.04)", + "app_id": 15368, + "applicability": "required" + } + ] + } + ], + "sonar": { + "organization": "storytold", + "project": "storytold_gridcraft", + "app_id": 12526, + "check_name": "SonarCloud Code Analysis", + "details_url": "https://sonarcloud.io/dashboard?id=storytold_gridcraft&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" + } + } + } +} diff --git a/.github/workflows/actions.lock b/.github/workflows/actions.lock index 6917bde73b..b463b78c5c 100644 --- a/.github/workflows/actions.lock +++ b/.github/workflows/actions.lock @@ -9,6 +9,8 @@ workflows: '.github/workflows/lockfile.yml': - 'actions/checkout@v7.0.1' - 'step-security/harden-runner@v2.22.4' + '.github/workflows/nightly-sign.yml': [] + '.github/workflows/nightly.yml': [] '.github/workflows/nix.yml': [] '.github/workflows/packaging-lint.yml': - 'actions/checkout@v7.0.1' diff --git a/.github/workflows/nightly-sign.yml b/.github/workflows/nightly-sign.yml new file mode 100644 index 0000000000..4430db0945 --- /dev/null +++ b/.github/workflows/nightly-sign.yml @@ -0,0 +1,42 @@ +name: GridCraft 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: gridcraft-nightly-release + cancel-in-progress: false + +jobs: + release: + # Actual context guards: official repository, manual dispatch, real release branch. + if: >- + github.repository == 'storytold/gridcraft' && + 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. diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml new file mode 100644 index 0000000000..a201ce8588 --- /dev/null +++ b/.github/workflows/nightly.yml @@ -0,0 +1,34 @@ +name: GridCraft unsigned nightly + +# Enabled for supervised manual runs by the reviewed manual actor only; no schedule yet. +# A later explicit opt-in may add a cadence (and turn on nightly-dispatch.yml with it). +on: + workflow_dispatch: + +permissions: + contents: read + +jobs: + unsigned: + # Actual context guards only; no inherited/platform secrets. + if: >- + github.repository == 'storytold/gridcraft' && + 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: gridcraft + manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]' + craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 + # One producer run builds every listed platform for one all-or-nothing release. The pin is the + # craft-common-actions main commit that merged #339 (bounded lineage compares), on top of the + # Linux/macOS signer (#342). + platforms: '["windows-x86_64","linux-x86_64","macos-aarch64"]' diff --git a/.github/workflows/packaging-lint.yml b/.github/workflows/packaging-lint.yml index 1633071003..a50fde9d8e 100644 --- a/.github/workflows/packaging-lint.yml +++ b/.github/workflows/packaging-lint.yml @@ -5,9 +5,9 @@ name: Packaging lint on: push: branches: [main, release] - paths: [".github/workflows/**", "packaging/**", "assets/app-icon/**"] + paths: [".github/workflows/**", ".github/nightly-linux-signing-key.asc", "packaging/**", "assets/app-icon/**", "sonar-project.properties"] pull_request: - paths: [".github/workflows/**", "packaging/**", "assets/app-icon/**"] + paths: [".github/workflows/**", ".github/nightly-linux-signing-key.asc", "packaging/**", "assets/app-icon/**", "sonar-project.properties"] workflow_dispatch: permissions: @@ -22,6 +22,25 @@ jobs: # Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos. uses: storytold/craft-common-actions/.github/workflows/packaging-lint.yml@main + nightly-source-contract: + name: Nightly source contracts (no build or signing) + runs-on: ubuntu-latest + timeout-minutes: 5 + permissions: + contents: read + steps: + - name: Harden runner + uses: step-security/harden-runner@v2.22.4 + with: + egress-policy: audit + - uses: actions/checkout@v7.0.1 + with: + persist-credentials: false + - name: Run the synthetic nightly packaging suites + run: python3 packaging/nightly-tests.py + - name: Check the committed nightly icons still match their provenance + run: python3 packaging/nightly-icons.py --check + windows-install-policy: timeout-minutes: 10 name: Windows installation policy (no app build) diff --git a/.gitignore b/.gitignore index ab3202793a..f283435092 100644 --- a/.gitignore +++ b/.gitignore @@ -8,3 +8,9 @@ plan/ /.claude/ /target-*/ /craft-fonts/ + +# Checked out inside the workspace by the shared nightly workflows (craft-common-actions). +/.nightly-tools +/.nightly-input +/craft-i18n +__pycache__/ diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index d63b32f16c..297e07ba09 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -38,6 +38,12 @@ Generated-in-code art is original and has no file to list: the UI icon set (`cra | `assets/app-icon/hicolor/256x256/apps/ai.storyteller.gridcraft.png` | GridCraft contributors | original (hand-written SVG; `packaging/icons.sh`) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | Placeholder icon, Linux hicolor render | | `assets/app-icon/hicolor/512x512/apps/ai.storyteller.gridcraft.png` | GridCraft contributors | original (hand-written SVG; `packaging/icons.sh`) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | Placeholder icon, Linux hicolor render | | `assets/app-icon/hicolor/scalable/apps/ai.storyteller.gridcraft.svg` | GridCraft contributors | original (hand-written SVG; `packaging/icons.sh`) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | Placeholder icon, copy of gridcraft.svg | +| `assets/app-icon/gridcraft-nightly.svg` | GridCraft contributors | original (the stable placeholder artwork with only its field colour deepened; `packaging/nightly-icons.py`) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | Nightly (nightly-v1) icon master | +| `assets/app-icon/gridcraft-nightly.png` | GridCraft contributors | original (rendered from `gridcraft-nightly.svg`; `packaging/nightly-icons.py`) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | Nightly icon, 256 px (Linux tar and runtime window icon) | +| `assets/app-icon/gridcraft-nightly-1024.png` | GridCraft contributors | original (rendered from `gridcraft-nightly.svg` on the 824/1024 Mac grid; `packaging/nightly-icons.py`) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | Nightly icon, padded Mac master | +| `assets/app-icon/gridcraft-nightly.icns` | GridCraft contributors | original (PNG slots packed from `gridcraft-nightly.svg` renders; `packaging/nightly-icons.py`) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | Nightly macOS bundle icon | +| `assets/app-icon/gridcraft-nightly.ico` | GridCraft contributors | original (rendered from `gridcraft-nightly.svg`; `packaging/nightly-icons.py`) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | Nightly Windows exe icon | +| `assets/app-icon/nightly-provenance.json` | GridCraft contributors | original (written by `packaging/nightly-icons.py`) | MIT OR Apache-2.0 | Hashes and method of the nightly icon derivatives | | `assets/app-icon/README.md` | GridCraft contributors | original | MIT OR Apache-2.0 | Icon documentation | | `assets/app-icon/LICENSE.txt` | (licence text) | original | — | Licence of the app icon files | | `docs/images/hero-sales.png` | GridCraft contributors | screenshot of GridCraft rendered offscreen (`crates/ui-egui/examples/snapshot.rs`) showing an original sample workbook | MIT OR Apache-2.0 | README screenshot; no third-party content | diff --git a/Cargo.lock b/Cargo.lock index 89e57014b1..53def46152 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2876,6 +2876,7 @@ dependencies = [ "serde_json", "winit", "winresource", + "winsafe", ] [[package]] diff --git a/README.md b/README.md index a58f4fb195..9e624bc01c 100644 --- a/README.md +++ b/README.md @@ -165,6 +165,10 @@ directives, e.g. `RUST_LOG=debug` or `RUST_LOG=warn,gridcraft_engine=debug` (a t matches a prefix: `gridcraft*=debug`). Runs with `GRIDCRAFT_NO_PREFS` set (no saved settings) log to standard error only. +The `nightly-v1` channel keeps all of that in its own profile instead, which the Launcher names +(`--launch-profile nightly-v1 --profile-root `); a nightly build refuses to start without one, +so a Nightly run never touches the stable app's settings, prefs or logs. + ## For agents: MCP, CLI and the control channel ```sh diff --git a/apps/gridcraft-cli/src/main.rs b/apps/gridcraft-cli/src/main.rs index 2c49c60334..d049757270 100644 --- a/apps/gridcraft-cli/src/main.rs +++ b/apps/gridcraft-cli/src/main.rs @@ -65,12 +65,35 @@ fn stdout_failed(e: std::io::Error) -> ! { std::process::exit(1); } +/// The first Launcher-profile argument in `args`, in either its separate or `=` form. Only the +/// tokens a shell would see before `--` count: after it they are file names. +fn launch_profile_argument(args: &[std::ffi::OsString]) -> Option { + for arg in args { + if arg == "--" { + return None; + } + let text = arg.to_string_lossy(); + for flag in ["--launch-profile", "--profile-root"] { + if text == flag || text.starts_with(&format!("{flag}=")) { + return Some(flag.to_string()); + } + } + } + None +} + fn main() -> ExitCode { // A confined launcher run (and its probes) comes first, before anything else starts. let raw: Vec = std::env::args_os().skip(1).collect(); if let Some(code) = gridcraft_sandbox::handle_args(&raw) { return ExitCode::from(u8::try_from(code).unwrap_or(1)); } + // The nightly profile protocol belongs to the desktop app: the Launcher's selector is not a + // CLI option, and a CLI that silently ignored it would act on the wrong files. + if let Some(flag) = launch_profile_argument(&raw) { + eprintln!("gridcraft-cli: {flag} belongs to the GridCraft desktop app, not this CLI"); + return ExitCode::from(2); + } let args: Vec = std::env::args().skip(1).collect(); let rest = args.get(1..).unwrap_or_default(); let r = match args.first().map(String::as_str) { @@ -590,6 +613,22 @@ mod tests { #![allow(clippy::unwrap_used)] use super::*; + /// The Launcher's nightly selector belongs to the desktop app; the CLI says so and exits 2 + /// rather than acting on whatever it thinks the file list is. + #[test] + fn launcher_profile_arguments_are_refused_in_both_forms_and_only_before_the_delimiter() { + let args = |values: &[&str]| values.iter().map(std::ffi::OsString::from).collect::>(); + assert_eq!(launch_profile_argument(&args(&["--launch-profile", "nightly-v1"])).as_deref(), Some("--launch-profile")); + assert_eq!(launch_profile_argument(&args(&["--profile-root", "/tmp/p", "info", "a.xlsx"])).as_deref(), Some("--profile-root")); + assert_eq!(launch_profile_argument(&args(&["--profile-root=/tmp/p"])).as_deref(), Some("--profile-root")); + assert_eq!(launch_profile_argument(&args(&["info", "--launch-profile=nightly-v1"])).as_deref(), Some("--launch-profile")); + // After `--` they are file names, exactly as the desktop app parses them. + assert_eq!(launch_profile_argument(&args(&["--", "--launch-profile", "nightly-v1"])), None); + assert_eq!(launch_profile_argument(&args(&["--", "--profile-root=/tmp/p"])), None); + assert_eq!(launch_profile_argument(&args(&["info", "a.xlsx", "--json"])), None); + assert_eq!(launch_profile_argument(&[]), None); + } + #[test] fn parses_commands() { assert_eq!(parse_command("home.bold={\"range\":\"A1\"}").unwrap(), Some(("home.bold".into(), json!({"range": "A1"})))); diff --git a/apps/gridcraft/Cargo.toml b/apps/gridcraft/Cargo.toml index 3dfdb70243..60f62caca1 100644 --- a/apps/gridcraft/Cargo.toml +++ b/apps/gridcraft/Cargo.toml @@ -46,6 +46,8 @@ arboard = { workspace = true, features = ["image-data", "wayland-data-control"] [target.'cfg(target_os = "windows")'.dependencies] # Blocks on the start-up DirectX 12 adapter probe (`graphics.rs`); already in the tree via eframe. pollster = "1" +# The explicit AppUserModelID the nightly channel sets before its first window (`process_identity.rs`). +winsafe = { version = "0.0.29", features = ["user", "shell"] } [target.'cfg(target_os = "macos")'.dependencies] muda = { version = "0.21", default-features = false } diff --git a/apps/gridcraft/build.rs b/apps/gridcraft/build.rs index 95d8da38d9..5d3b8a6a58 100644 --- a/apps/gridcraft/build.rs +++ b/apps/gridcraft/build.rs @@ -1,25 +1,67 @@ //! Windows only: embed the app icon and version info (VERSIONINFO) into `gridcraft.exe`, so it //! shows in Explorer, the taskbar, the Start menu and Alt-Tab. //! -//! On every other target this does nothing. A missing resource compiler is a warning, so a -//! cross-compile from macOS or Linux still links, unless `GRIDCRAFT_REQUIRE_WINRES=1` turns it -//! into an error (for release builds). +//! On every other target this does nothing but the channel work. A missing resource compiler is a +//! warning, so a cross-compile from macOS or Linux still links, unless `GRIDCRAFT_REQUIRE_WINRES=1` +//! turns it into an error (for release builds). +//! +//! The nightly channel is a build-time decision: `GRIDCRAFT_BUILD_CHANNEL=nightly-v1` sets +//! `cfg(gridcraft_nightly_v1)` and requires the prepared `GRIDCRAFT_VERSION` feed identity, which +//! becomes the executable's `ProductVersion` (the Launcher checks that, not `FileVersion`) and the +//! version the app answers `--version` with. Anything else than `stable`, empty or `nightly-v1` +//! is a build error, so a typo cannot silently ship the wrong channel. + +#[path = "src/build_channel.rs"] +mod build_channel; fn main() { println!("cargo:rerun-if-changed=build.rs"); + println!("cargo:rerun-if-env-changed=GRIDCRAFT_BUILD_CHANNEL"); + println!("cargo:rustc-check-cfg=cfg(gridcraft_nightly_v1)"); + let nightly = match std::env::var("GRIDCRAFT_BUILD_CHANNEL").as_deref() { + Ok("nightly-v1") => { + println!("cargo:rustc-cfg=gridcraft_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 GRIDCRAFT_BUILD_CHANNEL (expected stable or nightly-v1)"); + std::process::exit(1); + } + }; println!("cargo:rerun-if-changed=../../assets/app-icon/gridcraft.ico"); + println!("cargo:rerun-if-changed=../../assets/app-icon/gridcraft-nightly.ico"); println!("cargo:rerun-if-env-changed=GRIDCRAFT_REQUIRE_WINRES"); + println!("cargo:rerun-if-env-changed=GRIDCRAFT_VERSION"); + let built_version = if nightly { + match std::env::var("GRIDCRAFT_VERSION") { + Ok(version) if build_channel::is_nightly_version(&version) => version, + _ => { + eprintln!("nightly-v1 requires an explicit GRIDCRAFT_VERSION feed identity"); + std::process::exit(1); + } + } + } else { + std::env::var("CARGO_PKG_VERSION").unwrap_or_default() + }; + println!("cargo:rustc-env=GRIDCRAFT_BUILT_VERSION={built_version}"); + if std::env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("windows") { return; } let mut res = winresource::WindowsResource::new(); - res.set_icon("../../assets/app-icon/gridcraft.ico") - .set("ProductName", "GridCraft") - .set("FileDescription", "GridCraft spreadsheet") + res.set_icon(build_channel::windows_icon_path(nightly)) + .set("ProductName", if nightly { "GridCraft Nightly" } else { "GridCraft" }) + .set("FileDescription", if nightly { "GridCraft Nightly spreadsheet" } else { "GridCraft spreadsheet" }) .set("CompanyName", "Learning Machines LLC") .set("LegalCopyright", "Copyright (c) the GridCraft authors. MIT OR Apache-2.0.") .set("OriginalFilename", "gridcraft.exe") .set("InternalName", "gridcraft"); + if nightly { + // The Launcher compares the PE ProductVersion with the exact feed identity. + res.set("ProductVersion", &built_version); + } if let Err(e) = res.compile() { if std::env::var_os("GRIDCRAFT_REQUIRE_WINRES").is_some() { eprintln!("embedding Windows resources failed: {e}"); diff --git a/apps/gridcraft/src/app_dirs.rs b/apps/gridcraft/src/app_dirs.rs new file mode 100644 index 0000000000..241f0ccab6 --- /dev/null +++ b/apps/gridcraft/src/app_dirs.rs @@ -0,0 +1,92 @@ +//! The one place a GridCraft data root is resolved, so the nightly profile and the platform +//! default can never disagree. +//! +//! Everything the desktop writes about the user lives under [`config_dir`]: `ui.json`, +//! `prefs.json` and `logs/` (see `logging`). The control channel's token folder is resolved by +//! `gridcraft_mcp` from the same root at start-up. Nothing else in the app persists user state. +//! A nightly takes its root from the Launcher's validated profile and nothing else, so stable has +//! no environment override of its own: the platform's published folder is the whole story. + +use std::ffi::OsString; +use std::path::PathBuf; + +fn default_config_dir(platform: &str, env: &impl Fn(&str) -> Option) -> Option { + match platform { + "macos" => env("HOME").map(|h| PathBuf::from(h).join("Library/Application Support/GridCraft")), + "windows" => env("APPDATA").map(|a| PathBuf::from(a).join("GridCraft")), + _ => env("XDG_CONFIG_HOME") + .filter(|v| !v.is_empty()) + .map(PathBuf::from) + .or_else(|| env("HOME").map(|h| PathBuf::from(h).join(".config"))) + .map(|c| c.join("gridcraft")), + } +} + +/// The folder the settings and the log files live in. +pub fn config_dir_for(platform: &str, env: &impl Fn(&str) -> Option, nightly_root: Option<&std::path::Path>) -> Option { + match nightly_root { + // The profile was already validated (absolute, fenced, writable) before this runs. + Some(root) => Some(root.to_path_buf()), + None => default_config_dir(platform, env), + } +} + +pub fn config_dir() -> Option { + config_dir_for(std::env::consts::OS, &|key| std::env::var_os(key), crate::launch_profile::current().root()) +} + +/// Where the log files live: `logs` in the settings folder, next to `ui.json`. +pub fn log_dir() -> Option { + Some(config_dir()?.join("logs")) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::collections::BTreeMap; + + fn env(pairs: &[(&str, &str)]) -> impl Fn(&str) -> Option { + let map: BTreeMap = pairs.iter().map(|(k, v)| ((*k).to_string(), OsString::from(v))).collect(); + move |key| map.get(key).cloned() + } + + #[test] + fn each_platform_keeps_its_published_folder() { + // The base is joined with the host's own separator, so these hold on any machine the gate + // runs on: what each platform publishes is the folder name, not how the host spells a slash. + let appdata = PathBuf::from(r"C:\Users\u\AppData\Roaming"); + assert_eq!(config_dir_for("windows", &env(&[("APPDATA", &appdata.to_string_lossy())]), None), Some(appdata.join("GridCraft"))); + let home = PathBuf::from("/home/u"); + assert_eq!( + config_dir_for("macos", &env(&[("HOME", &home.to_string_lossy())]), None), + Some(home.join("Library/Application Support/GridCraft")) + ); + assert_eq!(config_dir_for("linux", &env(&[("HOME", &home.to_string_lossy())]), None), Some(home.join(".config").join("gridcraft"))); + assert_eq!( + config_dir_for("linux", &env(&[("XDG_CONFIG_HOME", "/xdg"), ("HOME", &home.to_string_lossy())]), None), + Some(PathBuf::from("/xdg").join("gridcraft")) + ); + assert_eq!(config_dir_for("linux", &env(&[("XDG_CONFIG_HOME", "")]), None), None); + } + + #[test] + fn an_empty_xdg_config_home_falls_back_to_the_home_folder() { + let home = PathBuf::from("/home/u"); + let home_str = home.to_string_lossy().into_owned(); + assert_eq!( + config_dir_for("linux", &env(&[("XDG_CONFIG_HOME", ""), ("HOME", &home_str)]), None), + Some(home.join(".config").join("gridcraft")) + ); + assert_eq!( + config_dir_for("linux", &env(&[("XDG_CONFIG_HOME", "/xdg"), ("HOME", &home_str)]), None), + Some(PathBuf::from("/xdg").join("gridcraft")) + ); + } + + #[test] + fn the_nightly_profile_is_the_whole_answer() { + let profile = std::path::Path::new("/var/lib/gridcraft-nightly/profile"); + assert_eq!(config_dir_for("linux", &env(&[("XDG_CONFIG_HOME", "/xdg"), ("HOME", "/home/u")]), Some(profile)), Some(profile.to_path_buf())); + assert_eq!(config_dir_for("linux", &env(&[("HOME", "/home/u")]), Some(profile)).unwrap().join("logs"), profile.join("logs")); + } +} diff --git a/apps/gridcraft/src/build_channel.rs b/apps/gridcraft/src/build_channel.rs new file mode 100644 index 0000000000..322f540eec --- /dev/null +++ b/apps/gridcraft/src/build_channel.rs @@ -0,0 +1,55 @@ +//! 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/gridcraft-nightly.ico" } else { "../../assets/app-icon/gridcraft.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/gridcraft.ico"); + assert_eq!(windows_icon_path(true), "../../assets/app-icon/gridcraft-nightly.ico"); + } + + #[test] + fn explicit_feed_identity_is_required_for_a_nightly_build() { + assert!(is_nightly_version("0.19.1-nightly.20261124.7.1.gabcdef012345")); + for invalid in [ + "", + "0.19.1", + "0.19.1-nightly", + "0.19.1-nightly.20261124", + "0.19.1-nightly.20261124.7.1.gABCDEF012345", + "0.19.1-nightly.20261124.7.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.19.1-nightly.20261124.1.1.gabcdef012345", + "0.19.1-nightly.20261124.1.1.gabcdef012345/other", + "0.19.1-nightly.20261124.1.1.gabcdef012345\ncargo:rustc-cfg=other", + ] { + assert!(!is_nightly_version(invalid)); + } + } +} diff --git a/apps/gridcraft/src/build_flavor.rs b/apps/gridcraft/src/build_flavor.rs new file mode 100644 index 0000000000..485bd3bc6d --- /dev/null +++ b/apps/gridcraft/src/build_flavor.rs @@ -0,0 +1,73 @@ +//! Build-time channel is distinct from a launch selector: a runtime environment cannot promote a +//! stable build, and a nightly build cannot be talked out of its profile. +use crate::launch_profile::Profile; +use std::ffi::OsString; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum BuildFlavor { + Stable, + NightlyV1, +} + +pub const COMPILED: BuildFlavor = if cfg!(gridcraft_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 GridCraft Nightly from ArtCraft Launcher".into()), + (BuildFlavor::Stable, true) => Err("This is a stable GridCraft 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.19.1"), "0.19.1"); + assert_eq!(version(BuildFlavor::NightlyV1, "0.19.1"), "0.19.1 (nightly-v1)"); + assert!(version_query(&["--version".into()])); + assert!(version_query(&["-V".into()])); + assert!(!version_query(&["--".into(), "--version".into()])); + assert!(!version_query(&[])); + } +} diff --git a/apps/gridcraft/src/launch_profile.rs b/apps/gridcraft/src/launch_profile.rs new file mode 100644 index 0000000000..a25e5077b4 --- /dev/null +++ b/apps/gridcraft/src/launch_profile.rs @@ -0,0 +1,223 @@ +//! Launcher-owned nightly-v1 bootstrap, selected before logging, updates, fonts or saved state. +//! Stable launches keep their original arguments and directory policy. No environment mutation. +//! +//! The protocol is the Launcher's, as PhotoCraft's is: `--launch-profile nightly-v1` with +//! `--profile-root ` as separate tokens, then `--` and the files. Everything after `--` +//! is a file, even when it looks like a profile flag. `--version` (and the Launcher's +//! `--launch-profile nightly-v1 --profile-root --version`) is answered by `main` before any +//! of this can create a directory, open a log or start a window. + +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, +} + +static PROFILE: OnceLock = OnceLock::new(); + +pub fn current() -> &'static Profile { + PROFILE.get().unwrap_or(&Profile::Stable) +} + +pub fn install(profile: Profile) -> Result<(), String> { + PROFILE.set(profile).map_err(|_| "the launch profile was already selected".to_string()) +} + +/// Recognize only the agreed literal selector/root pair before `--`. No filesystem or startup hook +/// runs here. +pub fn parse(args: Vec) -> Result { + 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 config resolution stays unchanged. +pub fn prepare(mut launch: Launch, validate: impl FnOnce(&Path) -> Result) -> Result { + 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, exe: Option<&Path>) -> Result { + 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 { + values.iter().map(OsString::from).collect() + } + + fn absolute() -> &'static str { + if cfg!(windows) { r"C:\NightlyData\profiles\gridcraft" } else { "/nightly-data/profiles/gridcraft" } + } + + fn nightly() -> Vec { + args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--"]) + } + + #[test] + fn stable_arguments_and_directory_policy_are_unchanged() { + for argv in [args(&[]), args(&["sales.xlsx"]), args(&["--control", "7979"]), args(&["--", "--launch-profile", "book.xlsx"])] { + 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_selector_and_root_are_parsed_without_reinterpreting_file_names() { + let mut argv = nightly(); + argv.extend(args(&["--profile-root", "a file with spaces.xlsx", "--version"])); + let launch = parse(argv).unwrap(); + assert_eq!(launch.profile, Profile::NightlyV1(PathBuf::from(absolute()))); + assert_eq!(launch.args, args(&["--", "--profile-root", "a file with spaces.xlsx", "--version"])); + } + + #[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", "/one/../two", "--"]), + args(&["--launch-profile", VERSION, "--profile-root", "", "--"]), + args(&["--launch-profile=nightly-v1", "--profile-root", absolute(), "--"]), + args(&["--launch-profile", VERSION, "--profile-root", absolute(), "sales.xlsx", "--"]), + args(&["--launch-profile", VERSION, "--profile-root", absolute()]), + ] { + assert!(parse(argv.clone()).is_err(), "{argv:?}"); + } + assert!(parse(args(&["--launch-profile", "--profile-root", absolute(), "--"])).is_err(), "a flag is not a value"); + } + + #[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", "7979", "--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()); + } +} diff --git a/apps/gridcraft/src/main.rs b/apps/gridcraft/src/main.rs index 824d654b1f..9da2a92121 100644 --- a/apps/gridcraft/src/main.rs +++ b/apps/gridcraft/src/main.rs @@ -9,16 +9,25 @@ #![cfg_attr(all(target_os = "windows", not(debug_assertions)), windows_subsystem = "windows")] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +mod app_dirs; #[cfg(target_os = "macos")] mod apple_events; +// The build channel's own parser and icon-path tests (build.rs compiles the same file by path). +#[cfg(test)] +mod build_channel; +mod build_flavor; mod control_server; #[cfg(any(target_os = "windows", target_os = "macos", test))] mod graphics; +mod launch_profile; mod logging; #[cfg(target_os = "macos")] mod native_menu; +mod nightly_session; mod opener; mod print; +mod process_identity; +mod profile_root; use std::cell::RefCell; use std::rc::Rc; @@ -29,45 +38,63 @@ use gridcraft_ui_egui::{Services, SheetApp}; use serde_json::json; /// The app, its native window per workbook window, and (macOS) the menu bar and Finder events. -struct App(SheetApp, DocWindows, #[cfg(target_os = "macos")] Option, #[cfg(target_os = "macos")] fmv_macos_events::Inbox); +/// The session record and its notice flag are only meaningful in the nightly channel. +struct App { + app: SheetApp, + windows: DocWindows, + #[cfg(target_os = "macos")] + menu: Option, + #[cfg(target_os = "macos")] + apple_events: fmv_macos_events::Inbox, + /// The Nightly session record, shared with the exit hook and the return path. + nightly: nightly_session::Shared, + /// Whether this window already told the user the previous session did not finish. + nightly_notice_shown: bool, +} impl eframe::App for App { fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) { #[cfg(target_os = "macos")] { - if self.2.is_none() && std::env::var_os("GRIDCRAFT_NO_NATIVE_MENU").is_none() { - self.2 = Some(native_menu::NativeMenu::install(ctx)); + if self.menu.is_none() && std::env::var_os("GRIDCRAFT_NO_NATIVE_MENU").is_none() { + self.menu = Some(native_menu::NativeMenu::install(ctx)); } - if let Some(m) = &mut self.2 { - m.poll(&mut self.0, ctx, self.1.focused_viewport()); + if let Some(m) = &mut self.menu { + m.poll(&mut self.app, ctx, self.windows.focused_viewport()); } - apple_events::poll(&self.3, &mut self.0, ctx); + apple_events::poll(&self.apple_events, &mut self.app, ctx); } - self.0.logic(ctx); - self.1.logic(&mut self.0, ctx); - self.0.close_path(ctx); + self.app.logic(ctx); + self.windows.logic(&mut self.app, ctx); + self.app.close_path(ctx); } /// Forwards raw input to the shared app, then opens every non-empty dropped file path as a workbook. fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) { - self.0.raw_input_hook(ctx, raw); - self.0.before_input(ctx); + self.app.raw_input_hook(ctx, raw); + self.app.before_input(ctx); // Files dropped on the window open as workbooks. for f in std::mem::take(&mut raw.dropped_files) { if let Some(p) = f.path().to_str().map(str::to_string).filter(|p| !p.is_empty()) { - self.0.open_path(&p); + self.app.open_path(&p); } } } fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) { gridcraft_ui_egui::framework::before_ui(ui.ctx(), &*frame); - self.1.show(&mut self.0, ui); + self.windows.show(&mut self.app, ui); } fn on_exit(&mut self) { print::finish_pending_jobs(); - save_prefs(&self.0); + save_prefs(&self.app); // A ready update installs once the process has exited. The macOS exit below skips - // dropping the app, so the helper is started here. - self.0.start_pending_update(); + // dropping the app, so the helper is started here. A nightly has no updater at all. + if gridcraft_ui_egui::channel::stable_services_allowed() { + self.app.start_pending_update(); + } + // The Nightly session record is finished here: every way of quitting reaches `on_exit`, + // and on macOS AppKit's terminate ends the process right after it, so nothing after + // `eframe::run_native` can run there. `finish_once` makes the later call a no-op. + nightly_session::finish_once(&self.nightly, self.nightly_notice_shown); // macOS (#117): end the process here, before eframe tears the window down. AccessKit's // macOS adapter subclasses the window's content view and restores its class on teardown; // AppKit's Touch Bar support observes that view (KVO), so in the next display cycle @@ -81,17 +108,10 @@ impl eframe::App for App { } } +/// The settings folder: the validated nightly profile, else the platform's own folder +/// (`app_dirs`). Every writer of user state goes through it. fn config_dir() -> Option { - if cfg!(target_os = "macos") { - std::env::var_os("HOME").map(|h| std::path::PathBuf::from(h).join("Library/Application Support/GridCraft")) - } else if cfg!(windows) { - std::env::var_os("APPDATA").map(|a| std::path::PathBuf::from(a).join("GridCraft")) - } else { - std::env::var_os("XDG_CONFIG_HOME") - .map(std::path::PathBuf::from) - .or_else(|| std::env::var_os("HOME").map(|h| std::path::PathBuf::from(h).join(".config"))) - .map(|c| c.join("gridcraft")) - } + app_dirs::config_dir() } /// Runs without preferences (`GRIDCRAFT_NO_PREFS`, agents' test runs) neither read nor write @@ -102,7 +122,7 @@ fn prefs_enabled() -> bool { /// Where the log files live: `logs` in the settings folder, next to `ui.json` (see `logging`). fn log_dir() -> Option { - Some(config_dir()?.join("logs")) + app_dirs::log_dir() } fn load_prefs(app: &mut SheetApp) { @@ -241,13 +261,97 @@ fn icon() -> Option { Some(egui::IconData { width: img.width(), height: img.height(), rgba: img.into_raw() }) } +fn initialize_nightly_process_identity() -> Result<(), process_identity::IdentityError> { + process_identity::initialize( + build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1, + gridcraft_ui_egui::channel::id_for(gridcraft_ui_egui::channel::Channel::NightlyV1), + ) +} + +/// Tell a desktop user why a nightly launch was refused. A headless form (`--version` on a runner) +/// never gets here: the version query is answered before this and before any profile work. +fn report_launch_profile_error(error: &str) { + eprintln!("GridCraft launch profile: {error}"); + let desktop_session = cfg!(windows) + || cfg!(target_os = "macos") + || (cfg!(target_os = "linux") && ["DISPLAY", "WAYLAND_DISPLAY"].into_iter().any(|key| std::env::var_os(key).is_some_and(|v| !v.is_empty()))); + if build_flavor::needs_native_error(build_flavor::COMPILED, desktop_session) { + if let Err(error) = initialize_nightly_process_identity() { + eprintln!("GridCraft launch profile: {error}"); + return; + } + #[cfg(any(windows, target_os = "linux", target_os = "macos"))] + let _ = rfd::MessageDialog::new() + .set_title("GridCraft Nightly") + .set_description(error) + .set_level(rfd::MessageLevel::Error) + .set_buttons(rfd::MessageButtons::Ok) + .show(); + } +} + +/// Select the immutable launch channel and profile before any startup service or side effect. +/// `None` means the answer was printed (`--version`) and the process is done. +fn prepare_launch() -> Option> { + let argv: Vec = std::env::args_os().skip(1).collect(); + let nightly_build = build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1; + // Plain `--version`, or the Launcher's `--launch-profile nightly-v1 --profile-root + // --version`: answered before root validation, process identity, IPC or any window (a dialog + // here would hang a headless runner and fail a Linux build). + if nightly_build && (build_flavor::version_query(&argv) || launch_profile::version_query(&argv)) { + use std::io::Write as _; + let version = build_flavor::version(build_flavor::COMPILED, env!("GRIDCRAFT_BUILT_VERSION")); + let _ = writeln!(std::io::stdout(), "{} {version}", gridcraft_ui_egui::channel::name_for(gridcraft_ui_egui::channel::Channel::Stable)); + return None; + } + let early = launch_profile::parse(argv) + .and_then(|launch| { + build_flavor::require_profile(build_flavor::COMPILED, &launch.profile)?; + initialize_nightly_process_identity().map_err(|error| error.to_string())?; + Ok(launch) + }) + .and_then(|launch| { + launch_profile::prepare(launch, |root| { + launch_profile::validate_root(root, |key| std::env::var_os(key), std::env::current_exe().ok().as_deref()) + }) + }) + .unwrap_or_else(|error| { + report_launch_profile_error(&error); + std::process::exit(2) + }); + let channel = + if early.profile.is_nightly() { gridcraft_ui_egui::channel::Channel::NightlyV1 } else { gridcraft_ui_egui::channel::Channel::Stable }; + if let Err(error) = + launch_profile::install(early.profile).and_then(|()| gridcraft_ui_egui::channel::select(channel, env!("GRIDCRAFT_BUILT_VERSION"))) + { + report_launch_profile_error(&error); + std::process::exit(2); + } + Some(early.args) +} + fn main() -> eframe::Result<()> { - // A confined launcher run (`gridcraft_sandbox::launch_command`) comes before everything else: - // it opens no window, writes no log, and becomes the program it confines. + // A confined launcher run (`gridcraft_sandbox::launch_command`, which a Python cell starts from + // this same executable) comes before everything else: it opens no window, writes no log, and + // becomes the program it confines. It must stay ahead of the launch profile, or a nightly build + // would refuse its own sandbox helper. let raw: Vec = std::env::args_os().skip(1).collect(); if let Some(code) = gridcraft_sandbox::handle_args(&raw) { std::process::exit(code); } + // Then the Launcher protocol and the version query (see `prepare_launch`). + let Some(arguments) = prepare_launch() else { return Ok(()) }; + // A nightly profile owns its control tokens as well, so even a nightly build that is asked + // for a control server can never write the stable app's token file. + if let Some(root) = launch_profile::current().root() { + match profile_root::control_directory(root).and_then(gridcraft_mcp::control_auth::set_token_root) { + Ok(()) => {} + Err(error) => { + report_launch_profile_error(&error); + std::process::exit(2); + } + } + } // First, so the panic hook and every start-up warning are recorded (`logging`). let logger = logging::install(); // Commands catch their panics (`Session::execute`), but the default hook only prints to @@ -268,21 +372,32 @@ fn main() -> eframe::Result<()> { let _ = std::io::Write::write_fmt(&mut std::io::stderr(), format_args!("gridcraft: {report}\n")); } })); - let args: Vec = std::env::args().skip(1).collect(); + let args: Vec = arguments.iter().map(|a| a.to_string_lossy().into_owned()).collect(); + let nightly = gridcraft_ui_egui::channel::current() == gridcraft_ui_egui::channel::Channel::NightlyV1; // The restart helper a self-update spawns: it finishes the swap and relaunches, then exits. - if let Some(done) = craft_update::self_update::finish(&gridcraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::>()) { + // A nightly has no updater, so it never runs this and never inherits a stable swap. + if !nightly + && let Some(done) = craft_update::self_update::finish(&gridcraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::>()) + { if let Err(e) = done { eprintln!("GridCraft update helper failed: {e}"); std::process::exit(1); } return Ok(()); } - if args.iter().any(|a| a == "--version" || a == "-V") { - println!("GridCraft {}", env!("CARGO_PKG_VERSION")); + // Before `--` only: everything after it is a file, even one named `--version`. + if arguments.iter().take_while(|a| *a != "--").any(|a| a == "--version" || a == "-V") { + println!("GridCraft {}", gridcraft_ui_egui::channel::version()); return Ok(()); } - let mut control_port: Option = std::env::var("GRIDCRAFT_CONTROL_PORT").ok().and_then(|p| p.parse().ok()); - let mut control_token: Option = std::env::var("GRIDCRAFT_CONTROL_TOKEN").ok(); + // The control channel is a stable-only service: a nightly window owns no port, writes no + // token and never inherits the stable app's `GRIDCRAFT_CONTROL_PORT`/`GRIDCRAFT_CONTROL_TOKEN`. + if nightly && args.iter().any(|a| a == "--control" || a == "--control-token") { + eprintln!("GridCraft Nightly: the control channel is not part of the nightly channel"); + std::process::exit(2); + } + let mut control_port: Option = (!nightly).then(|| std::env::var("GRIDCRAFT_CONTROL_PORT").ok().and_then(|p| p.parse().ok())).flatten(); + let mut control_token: Option = (!nightly).then(|| std::env::var("GRIDCRAFT_CONTROL_TOKEN").ok()).flatten(); let mut sample: Option = None; let mut files: Vec = Vec::new(); let mut i = 0; @@ -312,7 +427,9 @@ fn main() -> eframe::Result<()> { if let Some(logger) = logger { match log_dir().filter(|_| prefs_enabled()) { Some(dir) => match logger.attach_dir(&dir) { - Ok(path) => log::info!("GridCraft {}, log file {}", env!("CARGO_PKG_VERSION"), path.display()), + Ok(path) => { + log::info!("{} {}, log file {}", gridcraft_ui_egui::channel::name(), gridcraft_ui_egui::channel::version(), path.display()) + } // Standard error only by now (`attach_dir` gave up on the file); unlike `eprintln!`, never panics. Err(e) => log::warn!("no log file: {e}"), }, @@ -327,7 +444,11 @@ fn main() -> eframe::Result<()> { } let mut app = SheetApp::new(session, services()); app.watch_desktop_theme(); - app.start_update_check(); + // The updater is a stable-only service: a nightly is installed, replaced and updated by the + // Launcher, so it never checks for one, never prompts and never writes craft-update's state. + if !nightly { + app.start_update_check(); + } let control_port = control_port; load_prefs(&mut app); // Stamp the startup workbook's author from the persisted user name. @@ -335,6 +456,30 @@ fn main() -> eframe::Result<()> { app.session.new_workbook(); } app.after_engine(); // Show warnings from the sample. + // Nightly session health: the record is written before the window exists and finished by + // `on_exit`. A record left by an interrupted run is reported once, then cleared on the next + // clean quit. + let session_watch = std::sync::Arc::new(std::sync::Mutex::new(None)); + let mut nightly_notice_shown = false; + match nightly_session::Session::begin_with_health(launch_profile::current().root(), env!("GRIDCRAFT_BUILT_VERSION")) { + Ok((watch, unavailable)) => { + if let Some(watch) = &watch + && watch.previous_unclean() + { + app.notice = Some(gridcraft_ui_egui::Notice { + text: "The last GridCraft Nightly session did not finish cleanly. Your saved workbooks are as you left them; only unsaved changes are affected.".into(), + kind: gridcraft_ui_egui::NoticeKind::Warning, + action: None, + }); + nightly_notice_shown = true; + } + if unavailable { + log::warn!("this window shares a GridCraft Nightly profile another window owns; its exit is not recorded"); + } + *session_watch.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = watch; + } + Err(error) => log::warn!("Nightly session state was not written: {error}"), + } // Files named on the command line (a double-click on Windows and Linux) open as File › Open // opens them: a password-protected one asks for its password, and errors are shown, not // only logged. Each replaces the untouched blank Book1, as a file opened from Finder does. @@ -344,11 +489,16 @@ fn main() -> eframe::Result<()> { // Linux/BSD: Excel's layout — no window-manager title bar above ours; our title bar carries the // window controls. `GRIDCRAFT_SYSTEM_TITLEBAR=1` keeps the system frame. app.window_controls = cfg!(not(any(target_os = "macos", target_os = "windows"))) && std::env::var_os("GRIDCRAFT_SYSTEM_TITLEBAR").is_none(); + // The window carries its channel's name and OS app id: a nightly window is never mistaken for + // the stable one by a dock, a window manager rule or the taskbar (Windows AUMID above). A + // Flatpak package carries its own id instead, which is what its .desktop file and portal name. + let window_app_id = + std::env::var("FLATPAK_ID").ok().filter(|id| !id.is_empty()).unwrap_or_else(|| gridcraft_ui_egui::channel::app_id().to_string()); let mut viewport = egui::ViewportBuilder::default() - .with_title("GridCraft") + .with_title(gridcraft_ui_egui::channel::default_title()) .with_inner_size([1440.0, 900.0]) .with_min_inner_size([640.0, 420.0]) - .with_app_id("ai.storyteller.gridcraft") + .with_app_id(window_app_id) .with_drag_and_drop(true) .with_decorations(!app.window_controls); if cfg!(target_os = "macos") { @@ -387,7 +537,7 @@ fn main() -> eframe::Result<()> { let pending = std::cell::Cell::new(Some(app)); let run = |options: eframe::NativeOptions| { eframe::run_native( - "GridCraft", + gridcraft_ui_egui::channel::name(), options, Box::new(|cc| { let Some(mut app) = pending.take() else { @@ -402,14 +552,16 @@ fn main() -> eframe::Result<()> { } } let windows = DocWindows::new(&mut app, window_builder.clone(), DocWindows::platform_quits_with_last_window()); - Ok(Box::new(App( + Ok(Box::new(App { app, windows, #[cfg(target_os = "macos")] - None, + menu: None, #[cfg(target_os = "macos")] - apple_events.connect(&cc.egui_ctx), - ))) + apple_events: apple_events.connect(&cc.egui_ctx), + nightly: session_watch.clone(), + nightly_notice_shown, + })) }), ) }; @@ -417,7 +569,7 @@ fn main() -> eframe::Result<()> { // A graphics error before the app existed: start once more with the other backend (eframe // reuses its event loop for the second run). Errors after that, or from winit, are returned. #[cfg(target_os = "windows")] - if let Err(eframe::Error::Wgpu(e)) = &result + let result = if let Err(eframe::Error::Wgpu(e)) = &result && let Some(app) = pending.take() && let Some(backends) = graphics::fallback_backends(backend_override, first_backends) { @@ -425,8 +577,14 @@ fn main() -> eframe::Result<()> { pending.set(Some(app)); let mut options = retry_options; graphics::configure_backends(&mut options, backends); - return run(options); - } + run(options) + } else { + result + }; + // A start that failed before the app existed never reached `on_exit`, and on the platforms + // where the event loop returns this is also the end of a clean exit. `finish_once` makes the + // second of the two calls a no-op, so a successor's record is never touched. + nightly_session::finish_once(&session_watch, nightly_notice_shown); result } diff --git a/apps/gridcraft/src/nightly_session.rs b/apps/gridcraft/src/nightly_session.rs new file mode 100644 index 0000000000..597bb4b2a8 --- /dev/null +++ b/apps/gridcraft/src/nightly_session.rs @@ -0,0 +1,310 @@ +//! App-private Nightly session health, not telemetry and not a Launcher protocol. +//! +//! A live owner holds a separate persistent lease; secondary launches never rewrite its record. +//! Dropping the guard does not clear the marker: only the app's controlled return path does, and +//! on macOS that path is `on_exit` (a ⌘Q ends the process inside AppKit's terminate, after +//! `on_exit`, so nothing after `eframe::run_native` runs there). + +use std::fs::{File, OpenOptions}; +use std::io::{self, Read, Write}; +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, + previous_unclean: bool, +} + +fn regular_or_missing(path: &Path) -> io::Result { + 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 following a link at the destination: the temporary file is +/// created exclusively beside it and renamed over it, so a planted link is replaced, not written +/// through. `gridcraft_engine::io::write_file` does the same for workbooks; the session record is +/// the app's own file and must not depend on the engine's script sandbox policy. +fn atomic_write_no_follow(path: &Path, bytes: &[u8]) -> io::Result<()> { + let name = path.file_name().ok_or_else(|| io::Error::other("the session record has no file name"))?; + let mut tmp_name = std::ffi::OsString::from("."); + tmp_name.push(name); + tmp_name.push(".new"); + let tmp = path.with_file_name(tmp_name); + match std::fs::remove_file(&tmp) { + Ok(()) => {} + Err(error) if error.kind() == io::ErrorKind::NotFound => {} + Err(error) => return Err(error), + } + let write = (|| -> io::Result<()> { + let mut options = OpenOptions::new(); + options.write(true).create_new(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt as _; + options.mode(0o600); + } + let mut file = options.open(&tmp)?; + file.write_all(bytes)?; + file.sync_all()?; + drop(file); + std::fs::rename(&tmp, path) + })(); + if write.is_err() { + let _ = std::fs::remove_file(&tmp); + } + write +} + +/// The owner's session, shared by the app's exit hook and the return path. +pub type Shared = Arc>>; + +/// 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) -> io::Result<(Option, bool)> { + let watch = Self::begin(root, version)?; + 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) -> io::Result> { + let Some(root) = root else { return Ok(None) }; + if version.is_empty() || version.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)?; + // The commit is read back from the version (`…g`), never invented here. + let commit = gridcraft_ui_egui::channel::commit_for(version); + let own_record = serde_json::to_vec(&serde_json::json!({ + "schema_version": 1, + "channel": "nightly-v1", + "version": version, + "commit": commit, + }))?; + 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 failed start before the app existed), the record is left for the next owner. + pub fn finish(self, unclean_notice_shown: bool) -> io::Result<()> { + if self.previous_unclean && !unclean_notice_shown { + return Ok(()); + } + self.complete() + } + + /// Clear the record this owner wrote, and only that one. An unwind, abort, forced exit or killed + /// process never calls this. + pub fn complete(self) -> io::Result<()> { + if !regular_or_missing(&self.path)? { + return Ok(()); + } + let mut current = Vec::new(); + File::open(&self.path)?.take(self.own_record.len() as u64 + 1).read_to_end(&mut current)?; + if current != self.own_record { + return Err(io::Error::other("Nightly session state changed; leaving it intact")); + } + std::fs::remove_file(&self.path) + } +} + +#[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!("gridcraft-nightly-session-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed))); + match std::fs::create_dir(&path) { + Ok(()) => return Self(path), + Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue, + Err(error) => panic!("cannot create owned fixture: {error}"), + } + } + } + } + impl Drop for Fixture { + fn drop(&mut self) { + std::fs::remove_dir_all(&self.0).unwrap(); + } + } + + fn version() -> &'static str { + "0.19.1-nightly.20261124.7.1.gabcdef012345" + } + + #[test] + fn busy_secondary_reports_unavailable_without_replacing_the_owner_record() { + let fixture = Fixture::new(); + let (stable, warning) = Session::begin_with_health(None, "stable").unwrap(); + assert!(stable.is_none() && !warning); + let (first, warning) = Session::begin_with_health(Some(&fixture.0), version()).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), version()).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), version()).unwrap().unwrap(); + assert!(!first.previous_unclean()); + let own = std::fs::read(fixture.0.join(RECORD)).unwrap(); + assert!(Session::begin(Some(&fixture.0), version()).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), version()).unwrap().unwrap(); + assert!(!unfinished.previous_unclean()); + drop(unfinished); // Abnormal-path ownership release, not a controlled completion. + let next = Session::begin(Some(&fixture.0), version()).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), version()).unwrap().unwrap()); + // The renderer failed before the app existed: no notice was shown. + let failed = Session::begin(Some(&fixture.0), version()).unwrap().unwrap(); + assert!(failed.previous_unclean()); + failed.finish(false).unwrap(); + // The retry (or the next start) still sees the interruption and shows it. + let retry = Session::begin(Some(&fixture.0), version()).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), version()).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), version()).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"); + let successor = Session::begin(Some(&fixture.0), version()).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), version()).unwrap().unwrap(); + std::fs::write(fixture.0.join(RECORD), b"replacement owned by someone else").unwrap(); + assert!(watch.complete().is_err()); + assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), b"replacement owned by someone else"); + } + + #[test] + fn provenance_is_bounded_and_never_collects_documents_paths_or_diagnostics() { + let fixture = Fixture::new(); + assert!(Session::begin(Some(&fixture.0), &"x".repeat(MAX_METADATA_BYTES + 1)).is_err()); + assert_eq!(std::fs::read_dir(&fixture.0).unwrap().count(), 0); + assert!(Session::begin(None, "").unwrap().is_none(), "stable has no session-health side effects"); + let watch = Session::begin(Some(&fixture.0), version()).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::>(); + assert_eq!(fields, ["channel", "commit", "schema_version", "version"].into_iter().collect()); + assert_eq!(data["commit"], "abcdef012345", "the commit comes from the version, not the environment"); + watch.complete().unwrap(); + } + + #[test] + fn a_version_without_a_commit_does_not_invent_one() { + let fixture = Fixture::new(); + let watch = Session::begin(Some(&fixture.0), "0.19.1").unwrap().unwrap(); + let data: serde_json::Value = serde_json::from_slice(&std::fs::read(fixture.0.join(RECORD)).unwrap()).unwrap(); + assert!(data["commit"].is_null()); + 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), version()).is_err()); + assert_eq!(std::fs::read(&external).unwrap(), b"stable bytes"); + std::fs::remove_file(alias).unwrap(); + } + } + + #[test] + #[cfg(unix)] + fn replacing_a_planted_record_link_writes_our_own_file_only() { + let fixture = Fixture::new(); + let external = fixture.0.join("stable-document"); + std::fs::write(&external, b"stable bytes").unwrap(); + std::os::unix::fs::symlink(&external, fixture.0.join(RECORD)).unwrap(); + // regular_or_missing refuses an alias outright; the temporary writer is what a first write + // uses, and it never follows one either. + assert!(Session::begin(Some(&fixture.0), version()).is_err()); + // The link is at RECORD itself: writing there must replace the alias, not follow it. + atomic_write_no_follow(&fixture.0.join(RECORD), b"ours").unwrap(); + assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), b"ours"); + assert!(!fixture.0.join(RECORD).is_symlink(), "the alias must be replaced, not written through"); + assert_eq!(std::fs::read(&external).unwrap(), b"stable bytes"); + assert!(!fixture.0.join(".nightly-session.json.new").exists()); + } +} diff --git a/apps/gridcraft/src/process_identity.rs b/apps/gridcraft/src/process_identity.rs new file mode 100644 index 0000000000..23ce47653c --- /dev/null +++ b/apps/gridcraft/src/process_identity.rs @@ -0,0 +1,81 @@ +//! Set the immutable nightly Windows identity before any native window or COM service. +//! Stable deliberately leaves its implicit shortcut/path identity unchanged, so the MSI's +//! advertised shortcuts keep matching it. + +use std::sync::OnceLock; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct IdentityError(String); + +impl std::fmt::Display for IdentityError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.0) + } +} + +impl std::error::Error for IdentityError {} + +pub fn initialize(nightly: bool, app_id: &str) -> Result<(), IdentityError> { + configure(nightly && cfg!(windows), app_id, |id| { + static RESULT: OnceLock> = OnceLock::new(); + RESULT + .get_or_init(|| { + #[cfg(windows)] + { + winsafe::SetCurrentProcessExplicitAppUserModelID(id) + .map_err(|error| format!("cannot set the nightly Windows identity: {error}"))?; + let actual = winsafe::GetCurrentProcessExplicitAppUserModelID() + .map_err(|error| format!("cannot read back the nightly Windows identity: {error}"))?; + if actual != id { + return Err("the native Windows identity did not match the selected nightly channel".into()); + } + Ok(()) + } + #[cfg(not(windows))] + { + let _ = id; + Ok(()) + } + }) + .clone() + }) + .map_err(IdentityError) +} + +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()); + } + + #[test] + fn a_non_nightly_build_never_reaches_the_windows_api() { + assert!(initialize(false, "nightly-id").is_ok()); + } +} diff --git a/apps/gridcraft/src/profile_root.rs b/apps/gridcraft/src/profile_root.rs new file mode 100644 index 0000000000..d911a3fa46 --- /dev/null +++ b/apps/gridcraft/src/profile_root.rs @@ -0,0 +1,528 @@ +//! GridCraft's nightly profile fences: no stable fallback, no migration and no change to the +//! process environment. Every stable place a GridCraft build keeps user state is refused as a +//! nightly root, in both directions, so the two channels can never share a file. + +use std::ffi::OsString; +use std::path::{Component, Path, PathBuf}; + +/// The folder the Windows build writes its control-channel token to (`gridcraft_mcp`). +const WINDOWS_TOKEN_DIR: &str = ".gridcraft"; +/// The subfolder of the profile the nightly control-channel token goes to, when one runs. +pub const CONTROL_DIR: &str = "Control"; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Platform { + Windows, + Linux, + Mac, +} + +impl Platform { + fn current() -> Result { + match std::env::consts::OS { + "windows" => Ok(Self::Windows), + "linux" => Ok(Self::Linux), + "macos" => Ok(Self::Mac), + // FreeBSD, the BSDs and anything else have no nightly channel. + _ => 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 { + 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, key: &str) -> Result { + 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, key: &str, fallback: &str) -> Result { + match env(key).filter(|v| !v.is_empty()) { + Some(value) => absolute(PathBuf::from(value), key), + None => Ok(required_base(env, "HOME")?.join(fallback)), + } +} + +/// Resolve existing ancestors before creating anything. A dangling link or an inaccessible +/// ancestor is not a missing directory that may be replaced or followed later. +fn canonical_future(path: &Path) -> Result { + 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::>() + }; + let (a, b) = (parts(a), parts(b)); + a.starts_with(&b) || b.starts_with(&a) +} + +fn installation_boundary(platform: Platform, exe: &Path) -> Result { + let parent = exe.parent().ok_or("cannot establish the installation boundary")?; + if platform == Platform::Mac { + // A profile in Resources is still inside the versioned install, not beside MacOS. + if let Some(bundle) = exe.ancestors().find(|p| p.extension().is_some_and(|ext| ext.eq_ignore_ascii_case("app"))) { + return Ok(bundle.to_path_buf()); + } + } + Ok(parent.to_path_buf()) +} + +fn forbidden_roots(platform: Platform, env: &impl Fn(&str) -> Option, exe: &Path) -> Result, String> { + let mut roots = match platform { + Platform::Windows => { + // `apps/gridcraft/src/main.rs` (ui.json, prefs.json and logs) and `gridcraft_mcp`'s + // token folder, plus both MSI install folders (`install-policy.wxi`). + let mut roots = ["APPDATA", "LOCALAPPDATA"] + .into_iter() + .map(|key| required_base(env, key).map(|p| p.join("GridCraft"))) + .collect::, _>>()?; + roots.push(required_base(env, "LOCALAPPDATA")?.join("Programs").join("ArtCraft").join("GridCraft")); + roots.push(required_base(env, "USERPROFILE")?.join(WINDOWS_TOKEN_DIR)); + 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("GridCraft")); + } + } + roots + } + Platform::Linux => { + let mut roots = + [("XDG_CONFIG_HOME", ".config"), ("XDG_DATA_HOME", ".local/share"), ("XDG_CACHE_HOME", ".cache"), ("XDG_STATE_HOME", ".local/state")] + .into_iter() + .map(|(key, fallback)| xdg_base(env, key, fallback).map(|p| p.join("gridcraft"))) + .collect::, _>>()?; + roots.extend(["/usr/bin/gridcraft", "/usr/local/bin/gridcraft", "/opt/gridcraft"].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.gridcraft")); + // `gridcraft_mcp`'s token folder when no XDG runtime directory is set. + roots.push(required_base(env, "HOME")?.join(".cache").join("gridcraft")); + roots + } + Platform::Mac => { + let home = required_base(env, "HOME")?; + let library = home.join("Library"); + vec![ + library.join("Application Support/GridCraft"), + library.join("Caches/GridCraft"), + library.join("Caches/ai.storyteller.gridcraft"), + library.join("Preferences/GridCraft"), + library.join("Preferences/ai.storyteller.gridcraft.plist"), + library.join("Saved Application State/ai.storyteller.gridcraft.savedState"), + home.join("Applications/GridCraft.app"), + PathBuf::from("/Applications/GridCraft.app"), + ] + } + }; + roots.push(installation_boundary(platform, exe)?); + roots.into_iter().map(|p| canonical_future(&p)).collect() +} + +fn private_subdirectory(root: &Path, name: impl AsRef, label: &str) -> Result { + let chosen = canonical_future(&absolute(root.to_path_buf(), "the nightly profile root")?)?; + let child = canonical_future(&chosen.join(name))?; + if child == chosen || !child.starts_with(&chosen) { + return Err(format!("the nightly {label} must stay inside its selected profile")); + } + Ok(child) +} + +/// Every existing entry directly in the profile (settings, logs and so on) must resolve inside it, +/// so a link there cannot point Nightly's writes at the stable 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(()) +} + +/// Where a nightly control-channel token goes: `/Control`, created lazily by +/// `gridcraft_mcp` if a control server is ever started. Resolving it never creates anything. +pub fn control_directory(root: &Path) -> Result { + private_subdirectory(root, CONTROL_DIR, "control folder") +} + +/// The app's own exclusive writable probe: create a file inside the profile, then remove it. +pub fn ensure_writable(root: &Path) -> std::io::Result<()> { + static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + // A crashed launch can leave a probe with this name behind: take the next one instead of + // failing, and remove only the file this call created, never someone else's. + loop { + let probe = + root.join(format!(".gridcraft-nightly-writable-{}-{}", std::process::id(), NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed))); + match std::fs::OpenOptions::new().write(true).create_new(true).open(&probe) { + Ok(_) => return std::fs::remove_file(&probe), + Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue, + Err(error) => return Err(error), + } + } +} + +/// 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, + exe: Option<&Path>, + writable: impl FnOnce(&Path) -> std::io::Result<()>, +) -> Result { + validate_for(Platform::current()?, root, env, exe, writable) +} + +fn validate_for( + platform: Platform, + root: &Path, + env: impl Fn(&str) -> Option, + exe: Option<&Path>, + writable: impl FnOnce(&Path) -> std::io::Result<()>, +) -> Result { + absolute(root.to_path_buf(), "the nightly profile root")?; + if platform != Platform::Windows + && let Some(id) = env("FLATPAK_ID").filter(|value| !value.is_empty()) + && id.to_string_lossy().as_ref() != gridcraft_ui_egui::channel::NIGHTLY_PACKAGE_ID + { + // `packaging/linux/flatpak-bundle.sh` builds GridCraft Nightly as its own Flatpak + // (`ai.storyteller.gridcraft.nightly`), whose sandbox is already a private home, so that one + // instance may carry a profile. Any other, the stable app's included, could point it at + // another installation's tree; these rows are otherwise native tar/app-bundle launches. + return Err(format!( + "nightly-v1 can only run inside its own Flatpak instance ({}), not {}", + gridcraft_ui_egui::channel::NIGHTLY_PACKAGE_ID, + id.to_string_lossy() + )); + } + let chosen = canonical_future(root)?; + 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()); + } + // Existing aliases under the profile must not redirect a subfolder elsewhere. + control_directory(&chosen)?; + entries_stay_inside(&chosen)?; + let mut create = std::fs::DirBuilder::new(); + create.recursive(true); + #[cfg(unix)] + { + use std::os::unix::fs::DirBuilderExt as _; + create.mode(0o700); + } + create.create(&chosen).map_err(|e| format!("cannot create the nightly profile: {e}"))?; + let confirmed = std::fs::canonicalize(&chosen).map_err(|e| format!("cannot resolve the created nightly profile: {e}"))?; + if confirmed != chosen || forbidden.iter().any(|stable| overlaps(&confirmed, stable, platform)) { + return Err("the nightly profile changed while it was being validated".into()); + } + control_directory(&confirmed)?; + 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}; + + struct Fixture { + root: PathBuf, + env: BTreeMap, + exe: PathBuf, + } + + impl Fixture { + fn new() -> Self { + static NEXT: AtomicU64 = AtomicU64::new(0); + let root = loop { + let candidate = + std::env::temp_dir().join(format!("gridcraft-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/gridcraft"); + 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.clone()), ("USERPROFILE", 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 { + self.env.get(key).cloned() + } + + fn check(&self, platform: Platform, root: &Path) -> Result { + self.check_with(platform, root, |_| Ok(())) + } + + fn check_with(&self, platform: Platform, root: &Path, writable: impl FnOnce(&Path) -> std::io::Result<()>) -> Result { + validate_for(platform, root, |key| self.get(key), Some(&self.exe), writable) + } + + 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 every_stable_data_root_is_refused_on_its_own_platform() { + let mut fixture = Fixture::new(); + // Windows: APPDATA\GridCraft (settings and logs), LOCALAPPDATA\GridCraft, the per-user + // and per-machine install folders and the control-token folder. + for key in ["APPDATA", "LOCALAPPDATA"] { + let stable = PathBuf::from(fixture.get(key).unwrap()).join("GridCraft"); + for candidate in [stable.clone(), stable.join("nightly")] { + assert!(fixture.check(Platform::Windows, &candidate).unwrap_err().contains("overlap"), "{key}"); + } + assert!(!stable.exists()); + } + assert!( + fixture + .check(Platform::Windows, &PathBuf::from(fixture.get("LOCALAPPDATA").unwrap()).join("Programs/ArtCraft/GridCraft/nightly")) + .is_err() + ); + assert!(fixture.check(Platform::Windows, &fixture.home().join(".gridcraft/nightly")).is_err()); + 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()); + assert!(fixture.check(Platform::Windows, &base.join("ArtCraft/GridCraft/nightly")).is_err(), "{key}"); + assert!(!base.join("ArtCraft/GridCraft").exists()); + } + // Linux: the four XDG folders, then the stable Flatpak row and the token folder. + 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"] { + let stable = PathBuf::from(fixture.get(key).unwrap()).join("gridcraft"); + std::fs::create_dir_all(&stable).unwrap(); + std::fs::write(stable.join("stable-sentinel"), b"stable bytes").unwrap(); + for candidate in [stable.clone(), stable.join("nightly"), stable.parent().unwrap().to_path_buf()] { + assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("overlap"), "{key}"); + } + assert_eq!(std::fs::read(stable.join("stable-sentinel")).unwrap(), b"stable bytes"); + } + assert!(fixture.check(Platform::Linux, &fixture.home().join(".var/app/ai.storyteller.gridcraft/data")).is_err()); + assert!(fixture.check(Platform::Linux, &fixture.home().join(".var/app/ai.storyteller.launcher/nightly")).is_ok()); + assert!(fixture.check(Platform::Linux, Path::new("/usr/bin/gridcraft/../gridcraft-nightly")).is_err(), "parent traversal is refused"); + // macOS: the four Library rows and the bundle itself. + for suffix in [ + "Application Support/GridCraft", + "Caches/GridCraft", + "Preferences/GridCraft", + "Saved Application State/ai.storyteller.gridcraft.savedState", + ] { + assert!(fixture.check(Platform::Mac, &fixture.home().join("Library").join(suffix).join("nightly")).is_err(), "{suffix}"); + } + } + + #[test] + fn the_launcher_profile_row_is_accepted_on_every_platform() { + let fixture = Fixture::new(); + let data = fixture.root.join("Launcher/nightly/profiles/gridcraft"); + for platform in [Platform::Windows, Platform::Linux, Platform::Mac] { + assert_eq!(fixture.check(platform, &data).unwrap(), data); + } + assert!( + fixture + .check( + Platform::Linux, + &PathBuf::from(fixture.get("LOCALAPPDATA").unwrap()).join("Programs/ArtCraft/ArtCraftLauncher/nightly/gridcraft") + ) + .is_ok(), + "the Launcher's own folder is not GridCraft's install" + ); + } + + #[test] + fn overlap_check_handles_ancestor_descendant_and_prefix_lookalikes() { + let fixture = Fixture::new(); + let root = fixture.home().join("nightly/profiles/gridcraft"); + for platform in [Platform::Windows, Platform::Linux, Platform::Mac] { + assert!(overlaps(&root, &root.join("Control"), platform)); + assert!(overlaps(&root.join("Control"), &root, platform)); + assert!(!overlaps(&root, &root.with_file_name("gridcraft-other"), platform)); + } + } + + #[test] + fn the_install_folder_of_the_running_build_is_refused() { + let fixture = Fixture::new(); + for platform in [Platform::Windows, Platform::Linux, Platform::Mac] { + assert!(fixture.check(platform, &fixture.exe.parent().unwrap().join("profile")).is_err()); + } + } + + #[test] + fn mac_fences_the_whole_bundle_not_just_its_macos_folder() { + let mut fixture = Fixture::new(); + fixture.exe = fixture.root.join("install/GridCraft Nightly.app/Contents/MacOS/GridCraft"); + std::fs::create_dir_all(fixture.exe.parent().unwrap()).unwrap(); + std::fs::write(&fixture.exe, b"fixture executable, never run").unwrap(); + 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()); + assert!(fixture.check(Platform::Mac, &fixture.home().join("Library/Application Support/ArtCraft/nightly/profiles/gridcraft")).is_ok()); + } + + #[test] + fn ambiguous_environment_and_non_native_sandbox_are_refused_before_creation() { + let mut fixture = Fixture::new(); + let candidate = fixture.home().join("nightly/profiles/gridcraft"); + 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("FLATPAK_ID".into(), "ai.storyteller.gridcraft".into()); + assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("Flatpak")); + fixture.env.remove("FLATPAK_ID"); + fixture.env.remove("HOME"); + assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("HOME")); + assert!(!candidate.exists()); + } + + #[test] + fn only_the_nightly_s_own_flatpak_instance_may_carry_a_profile() { + let mut fixture = Fixture::new(); + let root = fixture.root.join("flatpak profile"); + for (id, accepted) in [ + (gridcraft_ui_egui::channel::NIGHTLY_PACKAGE_ID, true), + // The stable Flatpak, and a lookalike that only shares the prefix, stay refused. + ("ai.storyteller.gridcraft", false), + ("ai.storyteller.gridcraft.nightly-v1", false), + ("io.github.other.Gridcraft", false), + ] { + fixture.env.insert("FLATPAK_ID".into(), id.into()); + let result = fixture.check(Platform::Linux, &root); + assert_eq!(result.is_ok(), accepted, "{id}"); + let _ = std::fs::remove_dir_all(&root); + } + } + + #[test] + fn failed_write_probe_never_falls_back_to_stable() { + let fixture = Fixture::new(); + let candidate = fixture.home().join("nightly/profiles/gridcraft"); + let result = fixture.check_with(Platform::Linux, &candidate, |_| Err(std::io::Error::other("read-only mount"))); + assert!(result.unwrap_err().contains("not writable")); + assert!(candidate.is_dir(), "a created profile is not rolled back onto stable data"); + assert!(!fixture.home().join(".config/gridcraft").exists()); + } + + #[test] + fn a_file_in_place_of_the_profile_is_refused() { + let fixture = Fixture::new(); + let candidate = fixture.root.join("not-a-directory"); + std::fs::write(&candidate, b"a file, not a profile").unwrap(); + assert!(fixture.check(Platform::Linux, &candidate).is_err()); + assert_eq!(std::fs::read(&candidate).unwrap(), b"a file, not a profile"); + } + + #[cfg(unix)] + #[test] + fn profile_entry_aliases_must_stay_inside_the_profile() { + let fixture = Fixture::new(); + let stable = fixture.home().join(".config/gridcraft"); + std::fs::create_dir_all(&stable).unwrap(); + std::fs::write(stable.join("ui.json"), b"stable settings").unwrap(); + for name in ["ui.json", "logs", "Control", "profile"] { + 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 = fixture.check_with(Platform::Linux, &private, |_| { + 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-logs")).unwrap(); + std::fs::write(private.join("ui.json"), b"{}").unwrap(); + std::os::unix::fs::symlink(private.join("real-logs"), private.join("logs")).unwrap(); + assert!(fixture.check(Platform::Linux, &private).is_ok(), "links that stay inside are fine"); + assert_eq!(std::fs::read(stable.join("ui.json")).unwrap(), b"stable settings"); + assert_eq!(std::fs::read_dir(&stable).unwrap().count(), 1); + } + + #[cfg(unix)] + #[test] + fn a_control_folder_alias_cannot_redirect_the_token_outside_the_profile() { + let fixture = Fixture::new(); + let outside = fixture.home().join("shared-tokens"); + std::fs::create_dir_all(&outside).unwrap(); + let private = fixture.root.join("nightly-control"); + std::fs::create_dir(&private).unwrap(); + std::os::unix::fs::symlink(&outside, private.join(CONTROL_DIR)).unwrap(); + assert!(control_directory(&private).is_err()); + assert!(fixture.check(Platform::Linux, &private).is_err()); + assert_eq!(std::fs::read_dir(&outside).unwrap().count(), 0); + } + + #[test] + fn the_control_folder_is_a_private_lazy_subfolder() { + let fixture = Fixture::new(); + let private = fixture.check(Platform::Linux, &fixture.home().join("nightly/profile")).unwrap(); + let control = control_directory(&private).unwrap(); + assert!(control.starts_with(&private) && control != private); + assert!(!control.exists(), "resolving it must not create it"); + assert_eq!(control.file_name().unwrap(), CONTROL_DIR); + } + + #[test] + fn the_writable_probe_leaves_nothing_behind() { + let fixture = Fixture::new(); + let private = fixture.check(Platform::Linux, &fixture.home().join("nightly/profile")).unwrap(); + ensure_writable(&private).unwrap(); + assert_eq!(std::fs::read_dir(&private).unwrap().count(), 0); + } +} diff --git a/assets/app-icon/README.md b/assets/app-icon/README.md index 349dcfd5ab..b77585ff12 100644 --- a/assets/app-icon/README.md +++ b/assets/app-icon/README.md @@ -50,3 +50,16 @@ ID and `packaging/linux/ai.storyteller.gridcraft.desktop`. Edit `gridcraft.svg`, then run `packaging/icons.sh`. It needs `resvg`, and `iconutil` for the `.icns` (macOS only). It packs the `.ico` with `cargo xtask ico`. + +## Nightly channel + +The nightly (`nightly-v1`) derivatives keep the artwork, geometry and the Mac padding unchanged and +change only the field colour: `#1f9d55` in the stable icon, `#14532d` in +`gridcraft-nightly.svg`. There is no letter, badge or crescent; the app and the Launcher name the +channel in text (`GridCraft Nightly`, the `ai.storyteller.gridcraft.nightly-v1` window id). + +`gridcraft-nightly.svg` is the vector master. `packaging/nightly-icons.py` renders every frame from +it at its own size (never an upscale) and packs the nine-frame ICO and the eleven-slot ICNS; it +uses `resvg` when present, else a headless Chrome. Each output's SHA-256, the palette and the +method are recorded in [`nightly-provenance.json`](nightly-provenance.json), and +`python3 packaging/nightly-icons.py --check` verifies the committed files still match it. diff --git a/assets/app-icon/gridcraft-nightly-1024.png b/assets/app-icon/gridcraft-nightly-1024.png new file mode 100644 index 0000000000..7017cd5af9 Binary files /dev/null and b/assets/app-icon/gridcraft-nightly-1024.png differ diff --git a/assets/app-icon/gridcraft-nightly.icns b/assets/app-icon/gridcraft-nightly.icns new file mode 100644 index 0000000000..72a1668ed6 Binary files /dev/null and b/assets/app-icon/gridcraft-nightly.icns differ diff --git a/assets/app-icon/gridcraft-nightly.ico b/assets/app-icon/gridcraft-nightly.ico new file mode 100644 index 0000000000..446c0cedab Binary files /dev/null and b/assets/app-icon/gridcraft-nightly.ico differ diff --git a/assets/app-icon/gridcraft-nightly.png b/assets/app-icon/gridcraft-nightly.png new file mode 100644 index 0000000000..0fb30ce01b Binary files /dev/null and b/assets/app-icon/gridcraft-nightly.png differ diff --git a/assets/app-icon/gridcraft-nightly.svg b/assets/app-icon/gridcraft-nightly.svg new file mode 100644 index 0000000000..1966f77a7d --- /dev/null +++ b/assets/app-icon/gridcraft-nightly.svg @@ -0,0 +1,30 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/assets/app-icon/nightly-provenance.json b/assets/app-icon/nightly-provenance.json new file mode 100644 index 0000000000..d34aea93fb --- /dev/null +++ b/assets/app-icon/nightly-provenance.json @@ -0,0 +1,56 @@ +{ + "title": "GridCraft nightly deep-background icons", + "author": "@skylartaylor", + "license": "MIT OR Apache-2.0", + "inputs": [ + { + "path": "assets/app-icon/gridcraft-nightly.svg", + "sha256": "671748d45b785a840cf6ad062024c008e4704edc8925bed986dac2558438516b", + "purpose": "vector master for every frame" + }, + { + "path": "assets/app-icon/gridcraft.svg", + "sha256": "a4c55f2f52893b319862b610c006af83da9f097a4112b5a982b8ba95f43d2850", + "purpose": "stable artwork this is derived from" + } + ], + "method": { + "kind": "vector render of the project-owned artwork with only its field colour deepened", + "stable_field": "#1f9d55", + "nightly_field": "#14532d", + "unchanged": "ink #0b0b0c, paper #efe9dc, every path, stroke width and the 824/1024 Mac padding", + "sizes": "each frame rendered at its own size, never upscaled", + "renderer": "chrome", + "generator": "packaging/nightly-icons.py" + }, + "outputs": { + "gridcraft-nightly.png": "f06a2507dbd07c307d3b3e46eb2b7d849c29cc51f56114d61091d68d9d59e0d0", + "gridcraft-nightly-1024.png": "914314b91dd214132bc017503d88197ca1537fab0de144a59cc65e03a03be400", + "gridcraft-nightly.ico": "20cdb98a65c157f1db67800d439730b2c5dd564722d615d2b9483dc948f6e751", + "gridcraft-nightly.icns": "e8fb90269660151b8ab1370bbd7194f5bae29888aa44959cf4c48110dcdebe9a" + }, + "ico_frame_sizes": [ + 16, + 20, + 24, + 32, + 40, + 48, + 64, + 128, + 256 + ], + "icns_png_slots": { + "icp4": 16, + "icp5": 32, + "ic11": 32, + "icp6": 64, + "ic12": 64, + "ic07": 128, + "ic08": 256, + "ic13": 256, + "ic09": 512, + "ic14": 512, + "ic10": 1024 + } +} diff --git a/crates/mcp/src/control_auth.rs b/crates/mcp/src/control_auth.rs index 7ff589353d..b3fcabf582 100644 --- a/crates/mcp/src/control_auth.rs +++ b/crates/mcp/src/control_auth.rs @@ -68,10 +68,26 @@ pub fn check_first_line(line: &str, token: &str) -> Result { } } -/// Where the app writes the token it made for `port`, and where clients look for it: a folder -/// only the user can open (`$XDG_RUNTIME_DIR/gridcraft`, else `~/.cache/gridcraft`; on Windows -/// `%USERPROFILE%\.gridcraft`), file `control-.token`. `None` when no such folder is known. -pub fn token_path(port: u16) -> Option { +/// An app-selected folder for the tokens, set once before any window exists. The nightly channel +/// points it at its own private profile, so a nightly control server can never write the stable +/// app's token (and two channels can never authenticate each other). +static TOKEN_ROOT: std::sync::OnceLock = std::sync::OnceLock::new(); + +/// Choose the token folder for this process. Only a desktop app that owns its data root calls +/// this; a client (`gridcraft-cli`, the MCP bridge) keeps reading the app's own folder. +pub fn set_token_root(dir: PathBuf) -> Result<(), String> { + if !dir.is_absolute() { + return Err("the control token folder must be absolute".into()); + } + TOKEN_ROOT.set(dir).map_err(|_| "the control token folder was already selected".to_string()) +} + +/// The folder tokens go in: [`set_token_root`]'s when an app chose one, else the user's own. +pub fn token_root() -> Option { + TOKEN_ROOT.get().cloned().or_else(default_token_root) +} + +fn default_token_root() -> Option { let dir = if cfg!(windows) { PathBuf::from(std::env::var_os("USERPROFILE").filter(|v| !v.is_empty())?).join(".gridcraft") } else if let Some(run) = std::env::var_os("XDG_RUNTIME_DIR").filter(|v| !v.is_empty()) { @@ -79,7 +95,14 @@ pub fn token_path(port: u16) -> Option { } else { PathBuf::from(std::env::var_os("HOME").filter(|v| !v.is_empty())?).join(".cache").join("gridcraft") }; - Some(dir.join(format!("control-{port}.token"))) + Some(dir) +} + +/// Where the app writes the token it made for `port`, and where clients look for it: a folder +/// only the user can open (`$XDG_RUNTIME_DIR/gridcraft`, else `~/.cache/gridcraft`; on Windows +/// `%USERPROFILE%\.gridcraft`), file `control-.token`. `None` when no such folder is known. +pub fn token_path(port: u16) -> Option { + Some(token_root()?.join(format!("control-{port}.token"))) } /// The port of a control address (`127.0.0.1:7979` → 7979). diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index 3b1b71f066..9027fc5032 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -512,6 +512,15 @@ fn control_auth_handshake_and_compare() { assert_eq!(hex(&[0x00, 0xab, 0xff]), "00abff"); } +#[test] +fn a_relative_token_root_is_refused_before_it_is_selected() { + // The app may point the tokens at its own private profile, but only at an absolute folder: a + // relative one would resolve against whatever directory the process was started in. (A + // successful selection is process-wide, so this test only exercises the refusal.) + assert!(crate::control_auth::set_token_root(std::path::PathBuf::from("relative/tokens")).is_err()); + assert!(crate::control_auth::set_token_root(std::path::PathBuf::from("")).is_err()); +} + #[cfg(unix)] #[test] fn control_token_file_is_private() { diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 2678860b5e..a899df1721 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -164,6 +164,7 @@ impl SheetApp { } let Some(d) = self.session.active() else { return }; let title = format!("{}{}", d.display_title(), if d.is_dirty() { " — Edited" } else { "" }); + let title = crate::channel::window_title(&title); if self.grid.last_title.as_deref() != Some(title.as_str()) { ctx.send_viewport_cmd(egui::ViewportCommand::Title(title.clone())); self.grid.last_title = Some(title); diff --git a/crates/ui-egui/src/app/prefs.rs b/crates/ui-egui/src/app/prefs.rs index d57a163284..47dfe1b9bd 100644 --- a/crates/ui-egui/src/app/prefs.rs +++ b/crates/ui-egui/src/app/prefs.rs @@ -29,13 +29,22 @@ impl SheetApp { /// Look for a newer release once, in the background, as the desktop app starts (a no-op on the /// web). A found release opens the update prompt; nothing is shown when GridCraft is current. + /// A nightly channel has no update feed of its own: the Launcher installs and replaces it. pub fn start_update_check(&mut self) { #[cfg(not(target_arch = "wasm32"))] - updates_ui::start(self, false); + if crate::channel::stable_services_allowed() { + updates_ui::start(self, false); + } } /// Help ▸ Check for Updates…: look now, and say so when GridCraft is up to date or the check fails. pub fn check_for_updates(&mut self) { + // Never from the nightly channel: a check would download into, and record in, the stable + // app's folders, and an install would replace a Launcher-managed copy. + if !crate::channel::stable_services_allowed() { + self.message = Some((crate::channel::name().into(), "GridCraft Nightly is updated by ArtCraft Launcher.".into())); + return; + } #[cfg(not(target_arch = "wasm32"))] updates_ui::start(self, true); #[cfg(target_arch = "wasm32")] diff --git a/crates/ui-egui/src/backstage.rs b/crates/ui-egui/src/backstage.rs index 5ad23932cf..453c9bee90 100644 --- a/crates/ui-egui/src/backstage.rs +++ b/crates/ui-egui/src/backstage.rs @@ -793,11 +793,11 @@ fn account(app: &mut SheetApp, ui: &mut Ui) { let t = Tokens::get(ui.ctx()); let lang = app.ui.language; section(ui, lang, "Product Information"); - ui.label(RichText::new("GridCraft").font(theme::ui_bold(16.0)).color(t.text)); + ui.label(RichText::new(crate::channel::name()).font(theme::ui_bold(16.0)).color(t.text)); ui.add_space(8.0); egui::Grid::new("backstage_account").num_columns(2).spacing(vec2(18.0, 8.0)).show(ui, |ui| { for (label, value) in - [("Version", env!("CARGO_PKG_VERSION").to_string()), ("Platform", platform()), ("Licence", env!("CARGO_PKG_LICENSE").to_string())] + [("Version", crate::channel::version().to_string()), ("Platform", platform()), ("Licence", env!("CARGO_PKG_LICENSE").to_string())] { ui.label(RichText::new(lang.tr(label)).color(t.text_dim)); ui.label(value); diff --git a/crates/ui-egui/src/channel.rs b/crates/ui-egui/src/channel.rs new file mode 100644 index 0000000000..4a19d72dff --- /dev/null +++ b/crates/ui-egui/src/channel.rs @@ -0,0 +1,167 @@ +//! The compiled channel this process belongs to: its OS identity, its window titles and the +//! version the Help ▸ About and File ▸ Account views show. +//! +//! The desktop selects it once, before any window exists (`prepare_launch`), so a launch cannot +//! change it later and nothing here is a user preference. A stable build keeps its old identity +//! and titles byte for byte; the nightly build carries its own app id so docks, window managers +//! and the taskbar keep the two channels apart. + +use std::sync::OnceLock; +use std::sync::atomic::{AtomicU8, Ordering}; + +/// The stable window/Wayland app id, matching the `.desktop` file and the hicolor icon name. +pub const APP_ID: &str = "ai.storyteller.gridcraft"; +/// The nightly window id and Windows AUMID. +pub const NIGHTLY_APP_ID: &str = "ai.storyteller.gridcraft.nightly-v1"; +/// The nightly Flatpak package (and macOS bundle) identity, `packaging/linux/flatpak-bundle.sh`. +/// A different string from [`NIGHTLY_APP_ID`] on purpose: inside its sandbox the Flatpak names the +/// window after the package id, which is what its `.desktop` file and portal entry carry. +pub const NIGHTLY_PACKAGE_ID: &str = "ai.storyteller.gridcraft.nightly"; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Channel { + Stable, + NightlyV1, +} + +static SELECTED: AtomicU8 = AtomicU8::new(0); +static VERSION: OnceLock<&'static str> = OnceLock::new(); + +/// Fix the channel and its version for this process, once. `version` is the build's own identity +/// (`GRIDCRAFT_BUILT_VERSION` from `build.rs`), not a value read from the environment at runtime. +pub fn select(channel: Channel, version: &'static str) -> Result<(), String> { + let value = match channel { + Channel::Stable => 1, + Channel::NightlyV1 => 2, + }; + SELECTED.compare_exchange(0, value, Ordering::AcqRel, Ordering::Acquire).map_err(|_| "the channel was already selected".to_string())?; + VERSION.set(version).map_err(|_| "the channel version was already selected".to_string()) +} + +pub fn current() -> Channel { + if SELECTED.load(Ordering::Acquire) == 2 { Channel::NightlyV1 } else { Channel::Stable } +} + +pub const fn id_for(channel: Channel) -> &'static str { + match channel { + Channel::Stable => APP_ID, + Channel::NightlyV1 => NIGHTLY_APP_ID, + } +} + +pub fn app_id() -> &'static str { + id_for(current()) +} + +pub const fn name_for(channel: Channel) -> &'static str { + match channel { + Channel::Stable => "GridCraft", + Channel::NightlyV1 => "GridCraft Nightly", + } +} + +pub fn name() -> &'static str { + name_for(current()) +} + +/// The title of a window that shows no document yet: the channel's own name. +pub fn default_title() -> &'static str { + name() +} + +/// Only a stable build runs the stable-only services (the updater, the shared suite state). +pub const fn stable_services_for(channel: Channel) -> bool { + matches!(channel, Channel::Stable) +} + +pub fn stable_services_allowed() -> bool { + stable_services_for(current()) +} + +/// The version to show: the selected build's own identity, else the crate version (a web build, +/// or a shell that never selected a channel). +pub fn version_for(channel: Channel, configured: Option<&'static str>) -> &'static str { + match (channel, configured) { + (Channel::NightlyV1, Some(version)) => version, + _ => env!("CARGO_PKG_VERSION"), + } +} + +pub fn version() -> &'static str { + version_for(current(), VERSION.get().copied()) +} + +/// The commit a nightly was built from, read back from its version (`…g`), if any. +/// +/// The producer writes the sha in lower case (the version pattern every nightly job enforces), so an +/// upper-case one is a malformed version rather than a commit: nothing is read back for it. +pub fn commit_for(version: &str) -> Option<&str> { + let (_, suffix) = version.split_once("-nightly.")?; + let (_, sha) = suffix.rsplit_once(".g")?; + (sha.len() == 12 && sha.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))).then_some(sha) +} + +pub fn commit() -> Option<&'static str> { + (current() == Channel::NightlyV1).then_some(version()).and_then(commit_for) +} + +/// A window title that names the channel whenever a document is shown in it. A stable window keeps +/// exactly the title it always had; a nightly one appends its channel, so two windows on the same +/// workbook are never mistaken for each other in the taskbar or the window menu. +pub fn window_title_for(channel: Channel, base: &str) -> String { + match channel { + Channel::Stable => base.to_string(), + Channel::NightlyV1 => format!("{base} \u{2014} {}", name_for(channel)), + } +} + +pub fn window_title(base: &str) -> String { + window_title_for(current(), base) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_two_channels_have_distinct_ids_and_names() { + assert_eq!(id_for(Channel::Stable), "ai.storyteller.gridcraft"); + assert_eq!(id_for(Channel::NightlyV1), "ai.storyteller.gridcraft.nightly-v1"); + assert_ne!(id_for(Channel::Stable), id_for(Channel::NightlyV1)); + // Three strings, not two: the Flatpak package id is not the window id, and neither is stable's. + assert_eq!(NIGHTLY_PACKAGE_ID, "ai.storyteller.gridcraft.nightly"); + assert_ne!(NIGHTLY_PACKAGE_ID, id_for(Channel::NightlyV1)); + assert_ne!(NIGHTLY_PACKAGE_ID, id_for(Channel::Stable)); + assert_eq!(name_for(Channel::Stable), "GridCraft"); + assert_eq!(name_for(Channel::NightlyV1), "GridCraft Nightly"); + assert!(stable_services_for(Channel::Stable)); + assert!(!stable_services_for(Channel::NightlyV1)); + } + + #[test] + fn stable_titles_and_version_are_unchanged() { + for base in ["Book1", "Book1 — Edited", "", "sales.xlsx"] { + assert_eq!(window_title_for(Channel::Stable, base), base); + } + assert_eq!(version_for(Channel::Stable, Some("0.19.1-nightly.20261124.7.1.gabcdef012345")), env!("CARGO_PKG_VERSION")); + assert_eq!(version_for(Channel::Stable, None), env!("CARGO_PKG_VERSION")); + } + + #[test] + fn nightly_titles_name_the_channel_and_keep_the_document() { + assert_eq!(window_title_for(Channel::NightlyV1, "Book1"), "Book1 \u{2014} GridCraft Nightly"); + assert_eq!(window_title_for(Channel::NightlyV1, ""), " \u{2014} GridCraft Nightly"); + let nightly = "0.19.1-nightly.20261124.7.1.gabcdef012345"; + assert_eq!(version_for(Channel::NightlyV1, Some(nightly)), nightly); + assert_eq!(version_for(Channel::NightlyV1, None), env!("CARGO_PKG_VERSION"), "a nightly build without its own version is not invented"); + } + + #[test] + fn the_commit_is_read_back_only_from_a_nightly_version() { + assert_eq!(commit_for("0.19.1-nightly.20261124.7.1.gabcdef012345"), Some("abcdef012345")); + assert_eq!(commit_for("0.19.1"), None); + assert_eq!(commit_for("0.19.1-nightly.20261124.7.1"), None); + assert_eq!(commit_for("0.19.1-nightly.20261124.7.1.gABCDEF012345"), None, "versions are lower-case"); + assert_eq!(commit_for("0.19.1-nightly.20261124.7.1.gabcdef01234"), None); + } +} diff --git a/crates/ui-egui/src/dialogs/about.rs b/crates/ui-egui/src/dialogs/about.rs index a95878e924..c48c624923 100644 --- a/crates/ui-egui/src/dialogs/about.rs +++ b/crates/ui-egui/src/dialogs/about.rs @@ -15,8 +15,11 @@ pub(super) fn about(ui: &mut egui::Ui, d: &mut Dialog) { "Contributors" => crate::credits::contributors_ui(ui), "Models" => crate::credits::models_ui(ui), _ => { - ui.heading("GridCraft"); - ui.label(format!("Version {}", env!("CARGO_PKG_VERSION"))); + ui.heading(crate::channel::name()); + ui.label(format!("Version {}", crate::channel::version())); + if let Some(commit) = crate::channel::commit() { + ui.label(egui::RichText::new(format!("Built from {commit}")).small()); + } ui.add_space(4.0); ui.label("A clean-room, open-source, Rust-native spreadsheet. Part of ArtCraft."); ui.hyperlink_to("getartcraft.com/apps/gridcraft", "https://getartcraft.com/apps/gridcraft"); diff --git a/crates/ui-egui/src/doc_windows.rs b/crates/ui-egui/src/doc_windows.rs index 904563c3b5..daee990999 100644 --- a/crates/ui-egui/src/doc_windows.rs +++ b/crates/ui-egui/src/doc_windows.rs @@ -255,7 +255,9 @@ fn visible_windows(app: &SheetApp) -> Vec { fn window_title(app: &SheetApp, window: u64) -> String { let title = app.session.window_title(window).unwrap_or_default(); let dirty = app.session.window(window).and_then(|w| app.session.documents().iter().find(|d| d.uid == w.doc_uid)).is_some_and(|d| d.is_dirty()); - if dirty { format!("{title} — Edited") } else { title } + let title = if dirty { format!("{title} — Edited") } else { title }; + // Nightly says which channel the window belongs to; stable titles are unchanged. + crate::channel::window_title(&title) } /// Outer rectangles for `n` windows arranged within `bounds` as View › Arrange All's `arrange` diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 1513264d90..b2ff778744 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -19,6 +19,7 @@ pub mod backstage; mod border_preview; mod capture; mod cell_pictures; +pub mod channel; mod chartcache; pub mod chartview; pub mod code_editor; diff --git a/docs/nightly-release-preparation.md b/docs/nightly-release-preparation.md new file mode 100644 index 0000000000..1517a514ff --- /dev/null +++ b/docs/nightly-release-preparation.md @@ -0,0 +1,139 @@ +# Windows, Linux and macOS release-ref nightly: supervised manual go-live + +**Enabled for supervised manual runs, not yet qualified.** The producer (`nightly.yml`, main) and the +signer (`nightly-sign.yml`, release) keep only their exact context guards and run when one of the reviewed +manual actors dispatches them. There is no schedule yet. The installed policy +[`.github/nightly-signing-policy.json`](../.github/nightly-signing-policy.json) is the v3 policy +adapted from `storytold/photocraft#16594`. Once `nightly.yml` lands on `main`, populate +`producer_workflow_id` before promoting the policy to `release`, read with: + +```bash +gh api repos/storytold/gridcraft/actions/workflows/nightly.yml --jq .id +``` + +The callers pass no platform secrets. The unsigned reusable caller's maximum OIDC/attestation +permissions are for its isolated attester; its compiler narrows to contents and Actions read +only, with no OIDC, attestation write, release environment or platform signing secrets. +Shared tooling is pinned to `605d58766e8f536564da8fc81d3676ac86816dea`, the craft-common-actions +main commit that merged [#339](https://github.com/storytold/craft-common-actions/pull/339) (bounded +lineage compares and an issue reread at the end of candidate admission) on top of +[#342](https://github.com/storytold/craft-common-actions/pull/342) (policy v3, the `platforms` input +and the Linux and macOS legs). Both callers name it in `uses` and `tooling-revision`. A pin is reviewed +source availability, not provider, queue, native signing or crypto qualification. +Existing stable workflows are unchanged. + +**First runs.** The first runs are manual dispatches in this order: `nightly.yml` on main (only a +listed manual actor passes the producer's plan step), then `nightly-sign.yml` on `release` with that +producer run ID and attempt, by a listed manual actor. + +**Manual actors.** `bflatastic`, `dylanmtaylor`, `echelon`, `FredApps` and `skylartaylor`, in the +producer's `manual-actors` and the policy's `manual_actors`. The list mirrors the release-managers +team (id 19837241), leaving out `echelon-robot`; update it by PR in both places when the team changes. + +**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 + +Read on 2026-11-24; re-read anything that may have moved (and populate `producer_workflow_id` and +any Sonar debt snapshot) before the policy is promoted to `release`. + +| Field | Value | Source | +|---|---|---| +| `repository_id` | `1408285582` | `gh api repos/storytold/gridcraft --jq .id` | +| `producer_workflow_id` | `null` (pending `main` registration) | Read with `gh api repos/storytold/gridcraft/actions/workflows/nightly.yml --jq .id` after `nightly.yml` lands on `main` | +| `producer_tooling_revision`, `signer_tooling_revision`, `producer_workflow_ref` | `605d5876…` (craft-common-actions #339) | The callers' pin | +| `manual_actors` / `automatic_signer_actors` | the five release managers / `[]` | release-managers team (id 19837241) members who can push; equals the producer caller's `manual-actors` | +| `max_age_seconds`, `max_artifact_bytes` | `86400`, `2147483648` | Go-live checklist | +| `platforms` | three rows | Suite stable identities (Windows Authenticode publisher subject, Linux OpenPGP release key fingerprint, macOS Apple Developer ID team `DJ6XS33FX8`) | +| `candidate_policy.required_workflows` | CI (`ci.yml`, workflow `380135773`), 1 job (`gate / gate (ubuntu-24.04)`) | Workflow list API and recent green main push run | +| `candidate_policy.sonar` | `storytold` / `storytold_gridcraft`, app `12526` | `sonar-project.properties`; the SonarCloud check on main commits | +| Sonar `issue_types` / `debt` | `VULNERABILITY` / `[]` | Refresh from `api/issues/search` on main before promoting to `release` | + +## Ownership and interface + +- `.github/workflows/nightly.yml`: default-main registration of the unsigned producer, named + `GridCraft 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 (`gridcraft-nightly-release`) is distinct + from stable, cancellation is off and `queue: max` must be hosted-qualified. The caller itself passes no + credentials; only the shared callee's sign jobs bind the `release` environment. +- Shared reusable entrypoints are `nightly-unsigned.yml` and `nightly-release.yml` in + `storytold/craft-common-actions`. Both must resolve to a **real reviewed public immutable + commit**; the defining workflow SHA and tooling input must match. + +## Local regression checks + +`python3 packaging/nightly-release-tests.py` verifies the GridCraft nightly source contract: +- Both callers share one pinned 40-hex commit in `uses` and `tooling-revision`. +- No cache actions, cache setup options, `environment:`, or `secrets` appear in the callers. +- No nightly schedule is registered. +- Producer and signer keep their exact context guards (every `if:` form and continuation line is read). +- Manual actors are exactly the reviewed release managers in both `nightly.yml` and `.github/nightly-signing-policy.json`, with `automatic_signer_actors` empty. +- Root serialization in `nightly-sign.yml` remains literal (`group: gridcraft-nightly-release`, `cancel-in-progress: false`); it carries no `queue:` key while actionlint 1.7.12 rejects that key, and the value is re-added when the hosted queue is qualified. +- Installed policy v3 fields, bounds, platforms, candidate workflows, and Sonar identity match `sonar-project.properties` and the callers. + +## GridCraft's nightly-v1 flavor (the same branch) + +On top of the callers above, this branch makes the app a real `nightly-v1` channel: a nightly build is a +separate identity with its own data root, and every format starts it through the flavor's launch +protocol. None of this changes stable's behavior or the callers' authority. + +**Identity and version line.** `build.rs` maps `GRIDCRAFT_BUILD_CHANNEL=nightly-v1` to +`cfg(gridcraft_nightly_v1)` and refuses any other value; a nightly build requires the prepared +`GRIDCRAFT_VERSION` and answers `--version` with exactly `GridCraft (nightly-v1)` — plain, +and in the Launcher's `--launch-profile nightly-v1 --profile-root --version` form, before any +root validation, logging, window or token. `packaging/nightly-common.sh`, `macos/nightly-verify.sh` +and `windows/nightly.ps1` compare that exact line, so the packaged scripts and the binary cannot +disagree. Stable still prints its Cargo version. + +**Data root.** A nightly starts from `--launch-profile nightly-v1 --profile-root -- files…` +(separate tokens, refused in any other form) and keeps settings, prefs, logs and the control token +inside that folder; `profile_root` refuses the stable rows in both directions, a relative or +traversing root, a root that resolves through a link into a fenced folder, an inherited +`FLATPAK_ID` other than `ai.storyteller.gridcraft.nightly`, and the running installation. Users get +`${XDG_DATA_HOME:-$HOME/.local/share}/gridcraft-nightly/profile`, a sibling of stable's +`/gridcraft`, never an ancestor. + +**Every Linux format ships a launcher, and each passes an already-supplied profile through.** + +| Format | Launcher | GUI | Data root | +|---|---|---|---| +| deb/rpm | `/usr/bin/gridcraft-nightly` | `/usr/lib/gridcraft-nightly/gridcraft` | `/gridcraft-nightly/profile` | +| AppImage | `AppRun` (a script) and `usr/bin/gridcraft-nightly` | `usr/bin/gridcraft` | same | +| flat nightly tar | `gridcraft` | `gridcraft-bin` | same | +| plain tree tarball | `bin/gridcraft-nightly` | `bin/gridcraft` | same | +| Arch handoff | `bin/gridcraft-nightly` | `.gridcraft-nightly/gridcraft` | same | +| Flatpak bundle | `/app/bin/gridcraft-nightly` | `/app/bin/gridcraft` | the sandbox's own `~/.local/share` | + +The flat nightly tar uses the kit's standard layout: `` is the launcher people run and +`-bin` is the GUI ELF it starts, so the shared Unix verifier can keep requiring `gridcraft` +as the entrypoint. No launcher falls back to a relative or world-writable path for the GUI, and a +candidate that is the launcher itself is never started. + +**macOS and Windows.** `GridCraft Nightly.app` (`CFBundleIdentifier +ai.storyteller.gridcraft.nightly`, associations removed) is built and verified unsigned on main and +signed/notarized in the release signer; Windows gets a GUI-only x86_64 `.unsigned.zip` with the AUMID +`ai.storyteller.gridcraft.nightly-v1`, no MSI, no CLI and no portable marker. Both refuse signing +material during compilation. + +**Local checks.** `python3 packaging/nightly-tests.py` runs every synthetic suite in one pass: the +flat-archive policy, the macOS plist and sign/verify suites, the Linux launch and staging suites and +`packaging/nightly-release-tests.py`. `python3 packaging/nightly-icons.py --check` proves the +committed nightly icons still match `assets/app-icon/nightly-provenance.json`. `packaging-lint.yml` +runs both in its `nightly-source-contract` job. None of these compile the app or touch a key. + +**Still unqualified.** No hosted producer or signer run, no native signing, no Flatpak build and no +Linux/macOS desktop QA beside a stable install have happened for this flavor; the Rust unit tests +have only been type-checked where no capacity was available. Treat the first supervised run as the +first real qualification. diff --git a/packaging/icons.sh b/packaging/icons.sh index c6f325e3dd..f2d61c3a65 100755 --- a/packaging/icons.sh +++ b/packaging/icons.sh @@ -58,4 +58,7 @@ if command -v iconutil >/dev/null; then else echo "warning: iconutil not found (macOS only); gridcraft.icns not regenerated" >&2 fi +# The nightly channel's set: same artwork, deeper field; every frame rendered at its own size. +python3 "$ROOT/packaging/nightly-icons.py" + echo "icons written to $DIR" diff --git a/packaging/linux/flatpak-bundle.sh b/packaging/linux/flatpak-bundle.sh index 5ee85b3c55..9d276e92d7 100755 --- a/packaging/linux/flatpak-bundle.sh +++ b/packaging/linux/flatpak-bundle.sh @@ -17,6 +17,12 @@ set -euo pipefail . "$(dirname "${BASH_SOURCE[0]}")/../env.sh" HERE="$ROOT/packaging/linux" APP_ID=ai.storyteller.gridcraft +FLATPAK_ID="$APP_ID" +# The remote indexes both app IDs on the stable ref branch; IDs isolate installations. +FLATPAK_BRANCH=stable +if [[ "${GRIDCRAFT_BUILD_CHANNEL:-}" == nightly-v1 || "$VERSION" == *-nightly* ]]; then + FLATPAK_ID="$APP_ID.nightly" +fi FLATHUB=https://dl.flathub.org/repo/flathub.flatpakrepo TEST=1 @@ -52,29 +58,79 @@ rm -rf "$WORK" mkdir -p "$WORK/stage" tar -xzf "$TARBALL" -C "$WORK/stage" --strip-components=1 [[ -x "$WORK/stage/bin/gridcraft" ]] || { echo "error: $TARBALL has no bin/gridcraft" >&2; exit 1; } -cp "$HERE/flatpak/$APP_ID.bundle.yml" "$WORK/$APP_ID.yml" +if [[ "$FLATPAK_ID" != "$APP_ID" ]]; then + # The sandbox's own Flatpak id names the window (main.rs) and its data folder is already private, + # but the GUI still needs its launch profile: this launcher passes it, and the desktop entry and + # the manifest's one command name the launcher instead of the binary. + cat >"$WORK/stage/bin/gridcraft-nightly" <<'LAUNCHER' +#!/bin/sh +# GridCraft Nightly inside its own Flatpak: the launch profile is this app's private data folder. +set -eu +if [ -z "${XDG_DATA_HOME:-}" ] && [ -z "${HOME:-}" ]; then + echo "gridcraft-nightly: XDG_DATA_HOME and HOME are both unset, so there is no Nightly data folder" >&2 + exit 2 +fi +case "${1-}" in + --launch-profile | --profile-root) exec /app/bin/gridcraft "$@" ;; +esac +if [ "$#" -eq 1 ] && { [ "${1-}" = "--version" ] || [ "${1-}" = "-V" ]; }; then + exec /app/bin/gridcraft "$@" +fi +exec /app/bin/gridcraft --launch-profile nightly-v1 --profile-root "${XDG_DATA_HOME:-$HOME/.local/share}/gridcraft-nightly/profile" -- "$@" +LAUNCHER + chmod 755 "$WORK/stage/bin/gridcraft-nightly" + sed -e "s#^Exec=gridcraft\([[:space:]]\|$\)#Exec=gridcraft-nightly\1#" \ + -e "s|^TryExec=gridcraft$|TryExec=gridcraft-nightly|" \ + -e "s|^Icon=$APP_ID$|Icon=$FLATPAK_ID|" \ + -e "s|^Name=GridCraft$|Name=GridCraft Nightly|" \ + -e "s|^StartupWMClass=.*|StartupWMClass=$FLATPAK_ID|" \ + -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|$APP_ID|$FLATPAK_ID|g" \ + -e "s|GridCraft|GridCraft Nightly|g" \ + -e "s|$APP_ID.desktop|$FLATPAK_ID.desktop|g" \ + -e "s|$APP_ID|$FLATPAK_ID|g" \ + -e "s|gridcraft|gridcraft-nightly|g" \ + -e '//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" + mv "$WORK/stage/share/mime/packages/$APP_ID.xml" "$WORK/stage/share/mime/packages/$FLATPAK_ID.xml" + rm -rf "$WORK/stage/share/icons/hicolor" + NIGHTLY_ICON="$ROOT/assets/app-icon/gridcraft-nightly.png" + [[ -f "$NIGHTLY_ICON" ]] || NIGHTLY_ICON="$ROOT/assets/app-icon/hicolor/256x256/apps/$APP_ID.png" + install -Dm644 "$NIGHTLY_ICON" \ + "$WORK/stage/share/icons/hicolor/256x256/apps/$FLATPAK_ID.png" + # The manifest installs and runs the launcher; `command:` is what `flatpak run` starts. + sed -e "s|ai\.storyteller\.gridcraft|$FLATPAK_ID|g" \ + -e "s|^command: gridcraft$|command: gridcraft-nightly|" \ + -e "s|^ - install -Dm755 bin/gridcraft-cli /app/bin/gridcraft-cli$|&\n - install -Dm755 bin/gridcraft-nightly /app/bin/gridcraft-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" - flatpak run --command=gridcraft-cli "$APP_ID" --version - flatpak run --command=sh "$APP_ID" -c 'ls /app/share/applications /app/share/metainfo /app/share/mime/packages /app/share/icons/hicolor/scalable/apps' + flatpak info --user "$FLATPAK_ID" + flatpak run --command=gridcraft-cli "$FLATPAK_ID" --version + flatpak run --command=sh "$FLATPAK_ID" -c 'ls /app/share/applications /app/share/metainfo /app/share/mime/packages /app/share/icons/hicolor/*/apps' fi echo "==> done" ls -lh "$OUT" diff --git a/packaging/linux/nfpm.yaml b/packaging/linux/nfpm.yaml index 5e8c3a11a7..feee02f4d8 100644 --- a/packaging/linux/nfpm.yaml +++ b/packaging/linux/nfpm.yaml @@ -3,7 +3,7 @@ # exports VERSION and NFPM_ARCH. # # nfpm package -f packaging/linux/nfpm.yaml -p deb -t dist/release/ -name: gridcraft +name: ${NFPM_NAME} arch: ${NFPM_ARCH} platform: linux version: ${VERSION} @@ -55,11 +55,14 @@ overrides: - xdg-desktop-portal contents: - - src: ${STAGE}/usr/bin/gridcraft - dst: /usr/bin/gridcraft + - src: ${STAGE}/usr/lib/gridcraft-nightly/gridcraft + dst: /usr/lib/gridcraft-nightly/gridcraft file_info: { mode: 0755 } - - src: ${STAGE}/usr/bin/gridcraft-cli - dst: /usr/bin/gridcraft-cli + - src: ${STAGE}/usr/bin/${NFPM_BIN} + dst: /usr/bin/${NFPM_BIN} + file_info: { mode: 0755 } + - src: ${STAGE}/usr/bin/${NFPM_CLI} + dst: /usr/bin/${NFPM_CLI} file_info: { mode: 0755 } - src: ${STAGE}/usr/share/ dst: /usr/share/ diff --git a/packaging/linux/nightly-arch-launch.sh b/packaging/linux/nightly-arch-launch.sh new file mode 100755 index 0000000000..ef22eea051 --- /dev/null +++ b/packaging/linux/nightly-arch-launch.sh @@ -0,0 +1,21 @@ +#!/bin/sh +# GridCraft Nightly for the Arch handoff: the GUI lives in .gridcraft-nightly/ beside this +# launcher. The launch profile is the only data root a nightly build accepts, and it holds the +# settings, logs, the control token and the session record, so no XDG variable has to move. +set -eu + +real_bin="$(dirname "$0")/.gridcraft-nightly/gridcraft" +# The Launcher's protocol and a bare version query name their own root and never read the default +# one, so they are dispatched before the guard that a default-root launch needs. +case "${1-}" in + --launch-profile | --profile-root) exec "$real_bin" "$@" ;; +esac +if [ "$#" -eq 1 ] && { [ "${1-}" = "--version" ] || [ "${1-}" = "-V" ]; }; then + exec "$real_bin" "$@" +fi +if [ -z "${XDG_DATA_HOME:-}" ] && [ -z "${HOME:-}" ]; then + echo "gridcraft-nightly: XDG_DATA_HOME and HOME are both unset, so there is no Nightly data folder" >&2 + exit 2 +fi +exec "$real_bin" --launch-profile nightly-v1 \ + --profile-root "${XDG_DATA_HOME:-$HOME/.local/share}/gridcraft-nightly/profile" -- "$@" diff --git a/packaging/linux/nightly-arch-tar-test.sh b/packaging/linux/nightly-arch-tar-test.sh new file mode 100755 index 0000000000..ebc6f6d4ae --- /dev/null +++ b/packaging/linux/nightly-arch-tar-test.sh @@ -0,0 +1,65 @@ +#!/usr/bin/env bash +# Validate the staged Arch launcher without building or opening GridCraft. +set -euo pipefail + +HERE="$(cd "$(dirname "$0")" && pwd)" +work="$(mktemp -d)" +trap 'rm -rf "$work"' EXIT +stage="$work/source" +dst="$work/dist" +base=gridcraft-0.0.1-nightly.1-linux-x86_64 +mkdir -p "$stage/bin" "$dst" "$work/extract" + +# A local argv recorder stands in for the compiled binaries. It never opens a UI. +cat >"$stage/bin/gridcraft" <<'RECORDER' +#!/bin/sh +printf '<%s>\n' "$@" +RECORDER +chmod 755 "$stage/bin/gridcraft" +cp "$stage/bin/gridcraft" "$stage/bin/gridcraft-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/gridcraft" "$bin/gridcraft-nightly" +mv "$bin/gridcraft-cli" "$bin/gridcraft-nightly-cli" + +test ! -e "$stage/bin/.gridcraft-nightly" +cmp "$stage/bin/gridcraft" "$bin/.gridcraft-nightly/gridcraft" +cmp "$stage/bin/gridcraft-cli" "$bin/gridcraft-nightly-cli" + +# The launcher starts the GUI through the flavor's launch profile, its only data root. +data="$work/data" +profile="$data/gridcraft-nightly/profile" +expect() { + expected="$1" + shift + actual=$(XDG_DATA_HOME="$data" PATH="$bin:$PATH" gridcraft-nightly "$@") + if [[ "$actual" != "$expected" ]]; then + printf 'expected:\n%s\nactual:\n%s\n' "$expected" "$actual" >&2 + exit 1 + fi +} +nightly_argv() { + printf '<%s>\n' --launch-profile nightly-v1 --profile-root "$profile" -- +} +expect "$(nightly_argv)" +expect "$(nightly_argv; printf '<%s>\n' 'workbook with spaces.xlsx' '--other-name.xlsx')" \ + 'workbook with spaces.xlsx' '--other-name.xlsx' +# A bare version query and the Launcher's own protocol pass straight through. +expect '<--version>' --version +expect '<-V>' -V +expect "$(printf '<%s>\n' --launch-profile nightly-v1 --profile-root "$work/launcher" -- 'book.xlsx')" \ + --launch-profile nightly-v1 --profile-root "$work/launcher" -- 'book.xlsx' +# A profile needs a data folder: the launcher refuses instead of writing into /. +status=0 +env -u XDG_DATA_HOME -u HOME PATH="$bin:$PATH" gridcraft-nightly book.xlsx >/dev/null 2>&1 || status=$? +[[ "$status" -eq 2 ]] || { printf 'expected exit 2 without XDG_DATA_HOME/HOME, got %s\n' "$status" >&2; exit 1; } +test ! -e "$data/gridcraft-nightly" +test ! -e "$work/launcher" + +echo "PASS: Arch Nightly handoff preserves launcher layout, profile selection and arguments" diff --git a/packaging/linux/nightly-arch-tar.sh b/packaging/linux/nightly-arch-tar.sh new file mode 100755 index 0000000000..cc5dfc4a9b --- /dev/null +++ b/packaging/linux/nightly-arch-tar.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Stage the GridCraft 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/.gridcraft-nightly" +mv "$stage/bin/gridcraft" "$stage/bin/.gridcraft-nightly/gridcraft" +cp "$here/nightly-arch-launch.sh" "$stage/bin/gridcraft" +chmod 755 "$stage/bin/gridcraft" +tar -C "$work" -czf "$destination/$basename.tar.gz" "$basename" +echo "wrote $destination/$basename.tar.gz" diff --git a/packaging/linux/nightly-launch.sh b/packaging/linux/nightly-launch.sh new file mode 100755 index 0000000000..48e120705b --- /dev/null +++ b/packaging/linux/nightly-launch.sh @@ -0,0 +1,35 @@ +#!/bin/sh +# GridCraft Nightly launcher for a moved tree: an AppImage (AppRun and usr/bin), the plain nightly +# tar, or a distro tarball's usr/bin. The launch profile is the only data root a nightly build +# accepts, so this is what keeps a Nightly run out of the stable app's settings, prefs and logs. +set -eu +here="$(cd "$(dirname "$0")" && pwd)" +# Where each placement keeps the GUI it starts: the AppImage (and any installed tree) has it in +# usr/bin/gridcraft; the flat nightly tar names it gridcraft-bin beside this launcher; a plain +# tree tarball keeps it beside its bin/gridcraft-nightly. A candidate that is this same file is +# never started, so a launcher can not recurse into itself. +self="$here/$(basename "$0")" +real="" +for candidate in "$here/usr/bin/gridcraft" "$here/gridcraft-bin" "$here/gridcraft"; do + if [ -x "$candidate" ] && [ ! "$candidate" -ef "$self" ]; then + real="$candidate" + break + fi +done +if [ -z "$real" ]; then + echo "gridcraft-nightly: no GridCraft binary beside $0 (usr/bin/gridcraft, gridcraft-bin)" >&2 + exit 2 +fi +# A bare version query and the Launcher's own protocol pass straight through: neither needs a data +# folder of this script's own, so neither may be refused for a HOME it never reads. +case "${1-}" in + --launch-profile | --profile-root) exec "$real" "$@" ;; +esac +if [ "$#" -eq 1 ] && { [ "${1-}" = "--version" ] || [ "${1-}" = "-V" ]; }; then + exec "$real" "$@" +fi +if [ -z "${XDG_DATA_HOME:-}" ] && [ -z "${HOME:-}" ]; then + echo "gridcraft-nightly: XDG_DATA_HOME and HOME are both unset, so there is no Nightly data folder" >&2 + exit 2 +fi +exec "$real" --launch-profile nightly-v1 --profile-root "${XDG_DATA_HOME:-$HOME/.local/share}/gridcraft-nightly/profile" -- "$@" diff --git a/packaging/linux/nightly-linux-launch-tests.py b/packaging/linux/nightly-linux-launch-tests.py new file mode 100644 index 0000000000..dff5ad53f1 --- /dev/null +++ b/packaging/linux/nightly-linux-launch-tests.py @@ -0,0 +1,263 @@ +#!/usr/bin/env python3 +"""The Linux launch profile, staged the way each format ships it; no cargo build, no GUI, no network. + +What is checked, all synthetic: + * `nightly-launch.sh` (the AppImage and tar launcher) passes the flavor's own tokens and nothing else; + * `package.sh` stages the deb/rpm, AppImage and tar launchers and a nightly desktop entry, and + leaves a stable tree exactly as it was. `nfpm`, `appimagetool` and `strip` are stubs on PATH. +""" +import os +from pathlib import Path +import shutil +import subprocess +import tarfile +import tempfile +import unittest + +ROOT = Path(__file__).resolve().parents[2] +LAUNCHER = ROOT / "packaging/linux/nightly-launch.sh" +PACKAGE = ROOT / "packaging/linux/package.sh" +NIGHTLY_VERSION = "0.19.1-nightly.20261124.7.1.gabcdef012345" +PROFILE = "gridcraft-nightly/profile" + +RECORDER = """#!/bin/sh +printf '<%s>\\n' "$@" +""" + + +def run(argv, cwd, env, check=True): + return subprocess.run(argv, cwd=cwd, env=env, check=check, capture_output=True, text=True) + + +class MovedTreeLauncher(unittest.TestCase): + """nightly-launch.sh as AppRun and as an unpacked tar's launcher.""" + + def setUp(self): + self.scratch = tempfile.TemporaryDirectory() + self.addCleanup(self.scratch.cleanup) + self.root = Path(self.scratch.name) + self.data = self.root / "data" + self.env = {"PATH": os.environ["PATH"], "XDG_DATA_HOME": str(self.data)} + + def install(self, layout): + """Each placement puts the GUI and this launcher where its format does. + + appdir: AppRun at the root, GUI in usr/bin (also usr/bin/gridcraft-nightly). + tar: the kit's flat tar, `gridcraft` launcher beside the `gridcraft-bin` GUI. + tree: a plain tree tarball, bin/gridcraft-nightly beside bin/gridcraft. + """ + tree = self.root / layout + binary, launcher_name = { + "appdir": (tree / "usr/bin/gridcraft", tree / "AppRun"), + "tar": (tree / "gridcraft-bin", tree / "gridcraft"), + "tree": (tree / "bin/gridcraft", tree / "bin/gridcraft-nightly"), + }[layout] + binary.parent.mkdir(parents=True) + binary.write_text(RECORDER) + binary.chmod(0o755) + shutil.copy2(LAUNCHER, launcher_name) + launcher_name.chmod(0o755) + return launcher_name + + def query(self, launcher, *args): + return run([str(launcher), *args], cwd=self.root, env=self.env) + + def tokens(self): + return ["<--launch-profile>", "", "<--profile-root>", f"<{self.data / PROFILE}>", "<-->"] + + def test_every_layout_starts_the_gui_through_the_launch_profile(self): + for layout in ("appdir", "tar", "tree"): + with self.subTest(layout=layout): + launcher = self.install(layout) + self.assertEqual(self.query(launcher).stdout.splitlines(), self.tokens()) + self.assertEqual( + self.query(launcher, "workbook with spaces.xlsx", "--other-name.xlsx").stdout.splitlines(), + self.tokens() + ["", "<--other-name.xlsx>"], + ) + + def test_a_bare_version_query_and_the_launcher_protocol_pass_through(self): + launcher = self.install("appdir") + for args in (["--version"], ["-V"], ["--launch-profile", "nightly-v1", "--profile-root", "/launcher", "--", "book.xlsx"]): + with self.subTest(args=args): + self.assertEqual(self.query(launcher, *args).stdout.splitlines(), [f"<{arg}>" for arg in args]) + + def test_a_missing_data_folder_or_binary_refuses_before_running_anything(self): + launcher = self.install("appdir") + refused = run([str(launcher), "book.xlsx"], cwd=self.root, env={"PATH": os.environ["PATH"]}, check=False) + self.assertEqual(refused.returncode, 2) + self.assertIn("XDG_DATA_HOME and HOME are both unset", refused.stderr) + (self.root / "appdir/usr/bin/gridcraft").unlink() + missing = run([str(launcher)], cwd=self.root, env=self.env, check=False) + self.assertEqual(missing.returncode, 2) + self.assertIn("no GridCraft binary", missing.stderr) + self.assertFalse(self.data.exists(), "a refused launch creates no data folder") + + def test_a_flat_tar_launcher_never_starts_itself(self): + launcher = self.install("tar") + (self.root / "tar/gridcraft-bin").unlink() + refused = run([str(launcher)], cwd=self.root, env=self.env, check=False) + self.assertEqual(refused.returncode, 2) + self.assertIn("no GridCraft binary", refused.stderr) + + def test_the_launcher_is_portable_shell(self): + run(["sh", "-n", str(LAUNCHER)], cwd=self.root, env=self.env) + self.assertTrue(LAUNCHER.read_text().startswith("#!/bin/sh\n")) + + +class FlatNightlyTar(unittest.TestCase): + """nightly.sh needs a release build, so its staging and the archive policy are source-guarded.""" + + def test_the_flat_tar_stages_the_kit_layout(self): + source = (ROOT / "packaging/linux/nightly.sh").read_text() + self.assertIn('cp "$NIGHTLY_GUI" "$STAGE/gridcraft-bin"', source, "the GUI is -bin") + self.assertIn('"$ROOT/packaging/linux/nightly-launch.sh" "$STAGE/gridcraft"', source, "the launcher is ") + self.assertNotIn('"$STAGE/gridcraft-nightly"', source, "the flat tar's launcher is gridcraft") + policy = (ROOT / "packaging/nightly-archive.py").read_text() + self.assertIn('{"gridcraft", "gridcraft-bin", "gridcraft-nightly.png"}', policy) + self.assertIn('required = {"gridcraft", "gridcraft-bin", "gridcraft-nightly.png"', policy) + launcher = LAUNCHER.read_text() + self.assertIn('"$here/gridcraft-bin"', launcher, "the launcher starts the GUI the tar ships") + + +class StagedFormats(unittest.TestCase): + """package.sh with stub binaries, a stub nfpm and a stub strip.""" + + def setUp(self): + self.scratch = tempfile.TemporaryDirectory() + self.addCleanup(self.scratch.cleanup) + self.root = Path(self.scratch.name) + self.target = self.root / "target" + self.dist = self.root / "dist" + self.stubs = self.root / "stubs" + for directory in (self.target / "release", self.dist, self.stubs): + directory.mkdir(parents=True, exist_ok=True) + for name in ("gridcraft", "gridcraft-cli"): + binary = self.target / "release" / name + binary.write_text(RECORDER) + binary.chmod(0o755) + # `strip` would refuse the recorder scripts; the real one is a no-op for a non-ELF file too. + (self.stubs / "strip").write_text("#!/bin/sh\nexit 0\n") + (self.stubs / "strip").chmod(0o755) + (self.stubs / "nfpm").write_text( + '#!/bin/sh\n' + 'while [ "$#" -gt 0 ]; do [ "$1" = "-f" ] && cp "$2" "$STUB_NFPM_DIR/rendered.yaml"; shift; done\n' + 'exit 0\n' + ) + (self.stubs / "nfpm").chmod(0o755) + self.env = { + "PATH": f"{self.stubs}:{os.environ['PATH']}", + "HOME": os.environ.get("HOME", str(self.root)), + "CARGO_TARGET_DIR": str(self.target), + "DIST": str(self.dist), + "STUB_NFPM_DIR": str(self.root), + "GRIDCRAFT_BUILD_DATE": "2026-11-24", + "GRIDCRAFT_BUILD_SHA": "a" * 40, + } + + def stage(self, formats="deb tar", **extra): + env = dict(self.env, **extra) + run(["bash", str(PACKAGE), "--skip-build", "--formats", formats], cwd=ROOT, env=env) + return self.target / "linux-package" + + def nightly(self): + return self.stage(GRIDCRAFT_BUILD_CHANNEL="nightly-v1", GRIDCRAFT_VERSION=NIGHTLY_VERSION) + + def test_nightly_deb_installs_a_launcher_and_the_gui_beside_it(self): + work = self.nightly() + stage = work / "nfpm-root" + launcher = stage / "usr/bin/gridcraft-nightly" + gui = stage / "usr/lib/gridcraft-nightly/gridcraft" + self.assertTrue(self.executable(launcher)) + self.assertTrue(self.executable(gui)) + self.assertFalse((stage / "usr/bin/gridcraft").exists(), "the GUI moved out of usr/bin") + self.assertTrue(self.executable(stage / "usr/bin/gridcraft-nightly-cli")) + text = launcher.read_text() + self.assertIn('exec "/usr/lib/gridcraft-nightly/gridcraft" --launch-profile nightly-v1', text) + self.assertIn(f"/{PROFILE}", text) + self.assertEqual(gui.read_text(), RECORDER, "the packaged GUI is the built binary, unchanged") + rendered = (self.root / "rendered.yaml").read_text() + self.assertIn(f"src: {stage}/usr/lib/gridcraft-nightly/gridcraft", rendered) + self.assertIn("dst: /usr/lib/gridcraft-nightly/gridcraft", rendered) + self.assertIn("file_info: { mode: 0755 }", rendered) + + def test_nightly_desktop_and_metainfo_are_the_nightly_identity(self): + work = self.nightly() + applications = work / "nfpm-root/usr/share/applications" + desktop = applications / "ai.storyteller.gridcraft.nightly-v1.desktop" + self.assertEqual(sorted(p.name for p in applications.iterdir()), [desktop.name]) + text = desktop.read_text() + self.assertIn("Exec=gridcraft-nightly %F\n", text) + self.assertIn("TryExec=gridcraft-nightly\n", text) + self.assertIn("StartupWMClass=ai.storyteller.gridcraft.nightly-v1\n", text) + self.assertIn("Name=GridCraft Nightly\n", text) + self.assertNotIn("MimeType=", text) + metainfo = (work / "nfpm-root/usr/share/metainfo/ai.storyteller.gridcraft.nightly-v1.metainfo.xml").read_text() + self.assertNotIn("", metainfo) + self.assertIn("gridcraft-nightly", metainfo) + + def test_nightly_tar_ships_the_launcher_beside_the_binary(self): + self.nightly() + archive = self.dist / f"gridcraft-{NIGHTLY_VERSION}-linux-x86_64.tar.gz" + with tarfile.open(archive) as tar: + names = {member.name.split("/", 1)[-1] for member in tar.getmembers()} + launcher = tar.extractfile("gridcraft-%s-linux-x86_64/bin/gridcraft-nightly" % NIGHTLY_VERSION).read().decode() + binary = tar.extractfile("gridcraft-%s-linux-x86_64/bin/gridcraft" % NIGHTLY_VERSION).read().decode() + desktop = tar.extractfile("gridcraft-%s-linux-x86_64/share/applications/ai.storyteller.gridcraft.desktop" % NIGHTLY_VERSION).read().decode() + self.assertIn("bin/gridcraft", names) + self.assertEqual(binary, RECORDER) + self.assertEqual(launcher, LAUNCHER.read_text()) + self.assertIn("Exec=gridcraft-nightly %F\n", desktop) + self.assertIn("Name=GridCraft Nightly\n", desktop) + self.assertNotIn("MimeType=", desktop) + + def test_a_stable_tree_is_unchanged(self): + work = self.stage() + stage = work / "root" + self.assertEqual(stage, work / "root", "a stable build packages its one stage") + self.assertTrue(self.executable(stage / "usr/bin/gridcraft")) + self.assertTrue(self.executable(stage / "usr/bin/gridcraft-cli")) + self.assertFalse((stage / "usr/bin/gridcraft-nightly").exists()) + self.assertFalse((stage / "usr/lib").exists()) + rendered = (self.root / "rendered.yaml").read_text() + self.assertNotIn("gridcraft-nightly", rendered) + self.assertIn(f"src: {stage}/usr/bin/gridcraft\n", rendered) + desktop = (stage / "usr/share/applications/ai.storyteller.gridcraft.desktop").read_text() + self.assertIn("Exec=gridcraft %F\n", desktop) + self.assertIn("MimeType=", desktop) + with tarfile.open(self.dist / "gridcraft-0.19.1-linux-x86_64.tar.gz") as tar: + names = {member.name.split("/", 1)[-1] for member in tar.getmembers()} + self.assertIn("bin/gridcraft", names) + self.assertNotIn("bin/gridcraft-nightly", names) + + def test_nightly_appimage_runs_its_launcher_as_apprun(self): + tool = self.stubs / "appimagetool" + tool.write_text("#!/bin/sh\nprintf '%s\\n' \"$@\" >\"$STUB_NFPM_DIR/appimagetool.argv\"\n") + tool.chmod(0o755) + (self.stubs / "runtime").write_text("runtime fixture") + work = self.stage( + "appimage", + GRIDCRAFT_BUILD_CHANNEL="nightly-v1", + GRIDCRAFT_VERSION=NIGHTLY_VERSION, + APPIMAGETOOL=str(tool), + APPIMAGE_RUNTIME=str(self.stubs / "runtime"), + ) + appdir = work / "GridCraft.AppDir" + self.assertTrue(self.executable(appdir / "AppRun")) + self.assertEqual((appdir / "AppRun").read_text(), LAUNCHER.read_text(), "AppRun is the launcher, not a symlink") + self.assertFalse((appdir / "AppRun").is_symlink()) + self.assertEqual((appdir / "usr/bin/gridcraft-nightly").read_text(), LAUNCHER.read_text()) + self.assertEqual((appdir / "usr/bin/gridcraft").read_text(), RECORDER, "the binary stays in usr/bin") + desktop = (appdir / "usr/share/applications/ai.storyteller.gridcraft.nightly-v1.desktop").read_text() + self.assertIn("Exec=gridcraft-nightly %F\n", desktop) + self.assertIn("TryExec=gridcraft-nightly\n", desktop) + self.assertIn("StartupWMClass=ai.storyteller.gridcraft.nightly-v1\n", desktop) + self.assertNotIn("MimeType=", desktop) + + def executable(self, path): + self.assertTrue(path.is_file(), f"{path} is not a file") + self.assertTrue(os.access(path, os.X_OK), f"{path} is not executable") + return True + + +if __name__ == "__main__": + unittest.main() diff --git a/packaging/linux/nightly.sh b/packaging/linux/nightly.sh new file mode 100755 index 0000000000..9839623801 --- /dev/null +++ b/packaging/linux/nightly.sh @@ -0,0 +1,33 @@ +#!/usr/bin/env bash +# App-owned GUI-only nightly tar: no FUSE/AppImage, CLI, association or install hooks. +set -euo pipefail +ARCH= +while [[ $# -gt 0 ]]; do + case "$1" in + --arch) [[ $# -ge 2 ]] || { echo 'missing --arch value' >&2; exit 2; }; ARCH="$2"; shift 2 ;; + -h|--help) echo 'Usage: nightly.sh --arch x86_64'; exit 0 ;; + *) echo "unsupported nightly argument: $1" >&2; exit 2 ;; + esac +done +[[ "$ARCH" == x86_64 && "$(uname -s)" == Linux ]] || { echo 'only native Linux x86_64 nightly packaging is supported' >&2; exit 2; } +# shellcheck source=../nightly-common.sh +. "$(dirname "${BASH_SOURCE[0]}")/../nightly-common.sh" +nightly_init linux "$ARCH" x86_64-unknown-linux-gnu +OUTPUT="$DIST/gridcraft-$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 kit's tar layout: `gridcraft` is the launcher people run and `gridcraft-bin` is the GUI it +# starts. An unpacked archive is isolated too, because the GUI refuses to start without a launch +# profile and the launcher is the only thing that supplies one. +cp "$NIGHTLY_GUI" "$STAGE/gridcraft-bin" +chmod 755 "$STAGE/gridcraft-bin" +cp "$ROOT/packaging/linux/nightly-launch.sh" "$STAGE/gridcraft" +chmod 755 "$STAGE/gridcraft" +# The nightly channel's own icon (deeper field); the archive member name stays as the helper requires. +cp "$ROOT/assets/app-icon/gridcraft-nightly.png" "$STAGE/gridcraft-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" diff --git a/packaging/linux/package.sh b/packaging/linux/package.sh index 466610d5c9..58b9c5faa9 100755 --- a/packaging/linux/package.sh +++ b/packaging/linux/package.sh @@ -5,9 +5,14 @@ # $DIST/gridcraft--linux-.AppImage.zsync delta updates (needs zsyncmake) # $DIST/gridcraft--linux-.deb Debian, Ubuntu, Mint, Pop!_OS, ... # $DIST/gridcraft--linux-.rpm Fedora, openSUSE, RHEL, ... -# $DIST/gridcraft--linux-.tar.gz plain FHS-style tree (bin/, share/) +# $DIST/gridcraft--linux-.tar.gz plain tree (bin/, share/) # -# Usage: packaging/linux/package.sh [--skip-build] [--formats "appimage deb rpm tar"] +# A nightly build (`GRIDCRAFT_BUILD_CHANNEL=nightly-v1`) starts through the flavor's launcher in +# every format: usr/bin/gridcraft-nightly (deb/rpm, beside the GUI in usr/lib), the AppImage's +# AppRun script, and bin/gridcraft-nightly in the plain tree tarball. A nightly build refuses to +# start without `--launch-profile nightly-v1 --profile-root `, so every format ships one. +# +# 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 and the AppImage # runtime for the AppImage (pinned downloads into $CARGO_TARGET_DIR, or APPIMAGETOOL and @@ -22,10 +27,16 @@ APP_ID=ai.storyteller.gridcraft 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,18p' "$0"; exit 0 ;; *) echo "unknown argument: $1" >&2; exit 2 ;; esac @@ -39,9 +50,20 @@ case "$ARCH" in *) echo "unsupported architecture $ARCH" >&2; exit 2 ;; esac export GRIDCRAFT_MAINTAINER="${GRIDCRAFT_MAINTAINER:-GridCraft maintainers }" +IS_NIGHTLY=0 +if [[ "${GRIDCRAFT_BUILD_CHANNEL:-}" == nightly-v1 || "$VERSION" == *-nightly* ]]; then + IS_NIGHTLY=1 + export GRIDCRAFT_BUILD_CHANNEL=nightly-v1 + export GRIDCRAFT_OVERRIDE_VERSION="$VERSION" +fi BASENAME="gridcraft-$VERSION-linux-$ARCH" -echo "==> GridCraft $VERSION for Linux $ARCH ($FORMATS)" +if [[ -n "$ARCH_TAR_DIR" && "$IS_NIGHTLY" != 1 ]]; then + echo "error: --arch-tar-dir is only for Nightly builds" >&2 + exit 2 +fi + +echo "==> GridCraft $VERSION for Linux $ARCH ($FORMATS, channel=${GRIDCRAFT_BUILD_CHANNEL:-stable})" if [[ "$SKIP_BUILD" = 0 ]]; then if [[ -n "${CROSS_TARGET:-}" ]]; then @@ -60,6 +82,11 @@ install -Dm755 "$BIN/gridcraft" "$STAGE/usr/bin/gridcraft" install -Dm755 "$BIN/gridcraft-cli" "$STAGE/usr/bin/gridcraft-cli" "${CROSS_COMPILE:-}strip" "$STAGE/usr/bin/gridcraft" "$STAGE/usr/bin/gridcraft-cli" 2>/dev/null || true install -Dm644 "$HERE/$APP_ID.desktop" "$STAGE/usr/share/applications/$APP_ID.desktop" +if [[ "$IS_NIGHTLY" = 1 ]]; then + sed -e 's|^StartupWMClass=.*|StartupWMClass=ai.storyteller.gridcraft.nightly-v1|' \ + "$STAGE/usr/share/applications/$APP_ID.desktop" >"$STAGE/usr/share/applications/$APP_ID.desktop.tmp" + mv "$STAGE/usr/share/applications/$APP_ID.desktop.tmp" "$STAGE/usr/share/applications/$APP_ID.desktop" +fi install -Dm644 "$HERE/$APP_ID.mime.xml" "$STAGE/usr/share/mime/packages/$APP_ID.xml" mkdir -p "$STAGE/usr/share/metainfo" sed -e "s/@VERSION@/$VERSION/g" -e "s/@DATE@/$GRIDCRAFT_BUILD_DATE/g" \ @@ -81,21 +108,124 @@ has() { case " $FORMATS " in *" $format "*) return 0 ;; *) return 1 ;; esac } +# The deb/rpm launcher: /usr/bin/gridcraft-nightly starts the GUI from /usr/lib with this channel's +# own launch profile. A nightly build refuses to start without one, and the profile is the only +# data root it accepts, so a distro package can never share the stable app's settings, prefs or logs. +nightly_launcher() { + local destination="$1" real_bin="$2" + cat >"$destination" <&2 + exit 2 +fi +case "\${1-}" in + --launch-profile | --profile-root) exec "$real_bin" "\$@" ;; +esac +if [ "\$#" -eq 1 ] && { [ "\${1-}" = "--version" ] || [ "\${1-}" = "-V" ]; }; then + exec "$real_bin" "\$@" +fi +exec "$real_bin" --launch-profile nightly-v1 --profile-root "\${XDG_DATA_HOME:-\$HOME/.local/share}/gridcraft-nightly/profile" -- "\$@" +LAUNCHER + chmod 755 "$destination" +} + # ---- .tar.gz ------------------------------------------------------------------------------------ if has tar; then mkdir -p "$WORK/tar" cp -R "$STAGE/usr" "$WORK/tar/$BASENAME" + if [[ "$IS_NIGHTLY" = 1 ]]; then + # An unpacked nightly tar is isolated too: bin/gridcraft stays the binary, and the launcher + # beside it is how it starts (the binary itself refuses to run without a launch profile). + install -Dm755 "$HERE/nightly-launch.sh" "$WORK/tar/$BASENAME/bin/gridcraft-nightly" + TAR_DESK="$WORK/tar/$BASENAME/share/applications/$APP_ID.desktop" + sed -e "s#^Exec=gridcraft\([[:space:]]\|$\)#Exec=gridcraft-nightly\1#" \ + -e "s|^TryExec=gridcraft$|TryExec=gridcraft-nightly|" \ + -e "s|^Name=GridCraft$|Name=GridCraft Nightly|" \ + -e '/^MimeType=/d' \ + "$TAR_DESK" >"$TAR_DESK.tmp" + mv "$TAR_DESK.tmp" "$TAR_DESK" + 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="gridcraft" + export NFPM_BIN="gridcraft" + export NFPM_CLI="gridcraft-cli" + if [[ "$IS_NIGHTLY" = 1 ]]; then + NIGHTLY_DESK_ID="$APP_ID.nightly-v1" + export NFPM_NAME="gridcraft-nightly" + export NFPM_BIN="gridcraft-nightly" + export NFPM_CLI="gridcraft-nightly-cli" + NFPM_STAGE="$WORK/nfpm-root" + rm -rf "$NFPM_STAGE" + cp -R "$STAGE" "$NFPM_STAGE" + # The GUI keeps its name under /usr/lib; /usr/bin/-nightly is its launcher (see + # nightly_launcher), so the desktop entry never starts a binary that refuses to run. + install -Dm755 "$NFPM_STAGE/usr/bin/gridcraft" "$NFPM_STAGE/usr/lib/gridcraft-nightly/gridcraft" + rm -f "$NFPM_STAGE/usr/bin/gridcraft" + nightly_launcher "$NFPM_STAGE/usr/bin/$NFPM_BIN" /usr/lib/gridcraft-nightly/gridcraft + mv "$NFPM_STAGE/usr/bin/gridcraft-cli" "$NFPM_STAGE/usr/bin/$NFPM_CLI" + mv "$NFPM_STAGE/usr/share/doc/gridcraft" "$NFPM_STAGE/usr/share/doc/$NFPM_NAME" + sed -e "s#^Exec=gridcraft\([[:space:]]\|$\)#Exec=$NFPM_BIN\1#" \ + -e "s|^TryExec=gridcraft$|TryExec=$NFPM_BIN|" \ + -e "s|^Icon=$APP_ID$|Icon=$NIGHTLY_DESK_ID|" \ + -e "s|^Name=GridCraft$|Name=GridCraft 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|$APP_ID|$NIGHTLY_DESK_ID|g" \ + -e "s|GridCraft|GridCraft Nightly|g" \ + -e "s|$APP_ID.desktop|$NIGHTLY_DESK_ID.desktop|g" \ + -e "s|$APP_ID|$NIGHTLY_DESK_ID|g" \ + -e "s|gridcraft|$NFPM_BIN|g" \ + -e "s|gridcraft-cli|$NFPM_CLI|g" \ + -e '//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" + # The nightly files are different files: validate those too, not only the stable ones above. + if command -v desktop-file-validate >/dev/null; then + desktop-file-validate "$NFPM_STAGE/usr/share/applications/$NIGHTLY_DESK_ID.desktop" + fi + if command -v appstreamcli >/dev/null; then + appstreamcli validate --no-net --explain "$NFPM_STAGE/usr/share/metainfo/$NIGHTLY_DESK_ID.metainfo.xml" + fi + rm -rf "$NFPM_STAGE/usr/share/mime" + rm -rf "$NFPM_STAGE/usr/share/icons/hicolor" + NIGHTLY_ICON="$ROOT/assets/app-icon/gridcraft-nightly.png" + [[ -f "$NIGHTLY_ICON" ]] || NIGHTLY_ICON="$ROOT/assets/app-icon/hicolor/256x256/apps/$APP_ID.png" + install -Dm644 "$NIGHTLY_ICON" \ + "$NFPM_STAGE/usr/share/icons/hicolor/256x256/apps/$NIGHTLY_DESK_ID.png" + fi # nfpm expands env vars in fields like `version` and `arch`, but not in `contents[].src`. - sed "s|\${STAGE}|$STAGE|g" "$HERE/nfpm.yaml" >"$WORK/nfpm.yaml" + # A nightly package keeps its GUI under /usr/lib behind usr/bin/gridcraft-nightly (see + # nightly_launcher). A stable tree has no such file, so this three-line entry is dropped and the + # rendered file stays exactly what main renders. + DROP_LIB_ENTRY= + # shellcheck disable=SC2016 + [[ -e "$NFPM_STAGE/usr/lib/gridcraft-nightly/gridcraft" ]] || DROP_LIB_ENTRY='\|^ - src: \${STAGE}/usr/lib/gridcraft-nightly/gridcraft|,+2d;' + # shellcheck disable=SC2016 + sed "${DROP_LIB_ENTRY}s|\${STAGE}|$NFPM_STAGE|g;s|\${NFPM_BIN}|$NFPM_BIN|g;s|\${NFPM_CLI}|$NFPM_CLI|g" "$HERE/nfpm.yaml" >"$WORK/nfpm.yaml" for fmt in deb rpm; do if has "$fmt"; then (cd "$ROOT" && nfpm package -f "$WORK/nfpm.yaml" -p "$fmt" -t "$DIST/$BASENAME.$fmt"); fi done @@ -131,10 +261,33 @@ if has appimage; then } APPDIR="$WORK/GridCraft.AppDir" cp -R "$STAGE" "$APPDIR" - ln -s usr/bin/gridcraft "$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 + # A script, not the stable symlink: AppRun starts the GUI through its launch profile, and the + # desktop entry names the same launcher for integrations that read it. + install -Dm755 "$HERE/nightly-launch.sh" "$APPDIR/AppRun" + install -Dm755 "$HERE/nightly-launch.sh" "$APPDIR/usr/bin/gridcraft-nightly" + APPIMAGE_ID="$APP_ID.nightly-v1" + sed -e "s#^Exec=gridcraft\([[:space:]]\|$\)#Exec=gridcraft-nightly\1#" \ + -e "s|^TryExec=gridcraft$|TryExec=gridcraft-nightly|" \ + -e "s|^Icon=$APP_ID$|Icon=$APPIMAGE_ID|" \ + -e "s|^Name=GridCraft$|Name=GridCraft Nightly|" \ + -e '/^MimeType=/d' \ + "$APPDIR/usr/share/applications/$APP_ID.desktop" >"$APPDIR/usr/share/applications/$APPIMAGE_ID.desktop" + rm -f "$APPDIR/usr/share/applications/$APP_ID.desktop" + cp "$APPDIR/usr/share/applications/$APPIMAGE_ID.desktop" "$APPDIR/$APPIMAGE_ID.desktop" + rm -rf "$APPDIR/usr/share/icons/hicolor" + NIGHTLY_ICON="$ROOT/assets/app-icon/gridcraft-nightly.png" + [[ -f "$NIGHTLY_ICON" ]] || NIGHTLY_ICON="$ROOT/assets/app-icon/hicolor/256x256/apps/$APP_ID.png" + install -Dm644 "$NIGHTLY_ICON" \ + "$APPDIR/usr/share/icons/hicolor/256x256/apps/$APPIMAGE_ID.png" + cp "$NIGHTLY_ICON" "$APPDIR/$APPIMAGE_ID.png" + ln -s "$APPIMAGE_ID.png" "$APPDIR/.DirIcon" + else + ln -s usr/bin/gridcraft "$APPDIR/AppRun" + cp "$HERE/$APP_ID.desktop" "$APPDIR/$APP_ID.desktop" + cp "$ROOT/assets/app-icon/hicolor/256x256/apps/$APP_ID.png" "$APPDIR/$APP_ID.png" + ln -s "$APP_ID.png" "$APPDIR/.DirIcon" + fi TOOL="${APPIMAGETOOL:-$(command -v appimagetool || true)}" if [[ -z "$TOOL" ]] && [[ -z "$APPIMAGETOOL_SHA256" ]]; then @@ -160,7 +313,11 @@ if has appimage; then fi # Absolute, because appimagetool runs in $DIST below (CARGO_TARGET_DIR, APPIMAGETOOL or # APPIMAGE_RUNTIME may be relative, e.g. target/agent-). - OUT="$(cd "$DIST" && pwd)/$BASENAME.AppImage" + APPIMAGE_BASENAME="$BASENAME" + if [[ "$IS_NIGHTLY" = 1 && "$VERSION" != *-nightly* ]]; then + APPIMAGE_BASENAME="gridcraft-$VERSION-nightly-linux-$ARCH" + fi + OUT="$(cd "$DIST" && pwd)/$APPIMAGE_BASENAME.AppImage" APPDIR="$(cd "$APPDIR" && pwd)" TOOL="$(cd "$(dirname "$TOOL")" && pwd)/$(basename "$TOOL")" RUNTIME="$(cd "$(dirname "$RUNTIME")" && pwd)/$(basename "$RUNTIME")" @@ -171,11 +328,20 @@ if has appimage; then # each AppImage on GitHub Releases. `latest` is the newest published release that is not a # pre-release. A fork's builds point at its own releases through GITHUB_REPOSITORY. REPO="${GITHUB_REPOSITORY:-storytold/gridcraft}" - UPDATE_INFO="gh-releases-zsync|${REPO%%/*}|${REPO#*/}|latest|gridcraft-*-linux-$ARCH.AppImage.zsync" + UPDATE_ARGS=() + if [[ "$IS_NIGHTLY" = 0 ]]; then + UPDATE_INFO="gh-releases-zsync|${REPO%%/*}|${REPO#*/}|latest|gridcraft-*-linux-$ARCH.AppImage.zsync" + UPDATE_ARGS=(-u "$UPDATE_INFO") + else + # Nightly releases are GitHub pre-releases (`latest` only selects stable releases), so point + # zsync update metadata at pre-release tags matching `-nightly` rather than stable `latest`. + UPDATE_INFO="gh-releases-zsync|${REPO%%/*}|${REPO#*/}|latest-pre|gridcraft-*-nightly*-linux-$ARCH.AppImage.zsync" + UPDATE_ARGS=(-u "$UPDATE_INFO") + fi # Extract-and-run: works without FUSE (containers, CI). The output embeds the static runtime, # so users don't need libfuse2 either. With zsyncmake on the host (CI installs the zsync # package) appimagetool also writes the .zsync, into its working directory, hence the cd. - (cd "$DIST" && ARCH="$ARCH" APPIMAGE_EXTRACT_AND_RUN=1 "$TOOL" --no-appstream --runtime-file "$RUNTIME" -u "$UPDATE_INFO" "$APPDIR" "$OUT") + (cd "$DIST" && ARCH="$ARCH" APPIMAGE_EXTRACT_AND_RUN=1 "$TOOL" --no-appstream --runtime-file "$RUNTIME" "${UPDATE_ARGS[@]}" "$APPDIR" "$OUT") echo "wrote $OUT" if [[ -s "$OUT.zsync" ]]; then echo "wrote $OUT.zsync" diff --git a/packaging/macos/nightly-lib.sh b/packaging/macos/nightly-lib.sh new file mode 100755 index 0000000000..7097426fe2 --- /dev/null +++ b/packaging/macos/nightly-lib.sh @@ -0,0 +1,117 @@ +# 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='GridCraft Nightly.app' +MAC_NIGHTLY_ID='ai.storyteller.gridcraft.nightly' +# The release environment's names, as stable release.yml passes them (packaging/macos/import-cert.sh). +MAC_NIGHTLY_SECRETS=(APPLE_CERTIFICATE APPLE_CERTIFICATE_PASSWORD KEYCHAIN_PASSWORD APPLE_ID APPLE_PASSWORD APPLE_TEAM_ID) + +mac_nightly_die() { printf 'error: %s\n' "$*" >&2; exit 2; } + +# The exact prepared version from the feed asset name, or failure. +mac_nightly_version_from_asset() { + local name="$1" version + [[ "$name" =~ ^gridcraft-(.+)-macos-aarch64-nightly\.zip$ ]] || return 1 + version="${BASH_REMATCH[1]}" + [[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+-nightly\.[0-9]{8}\.[0-9]+\.[0-9]+\.g[0-9a-f]{12}$ ]] || return 1 + printf '%s\n' "$version" +} + +# Every signing and notarization value is set, and the team is one Apple team ID. No ad-hoc fallback. +mac_nightly_require_secrets() { + local name + for name in "${MAC_NIGHTLY_SECRETS[@]}"; do + [[ -n "${!name:-}" ]] || mac_nightly_die "$name is not set: Nightly signing and notarization are required, with no ad-hoc fallback" + done + [[ "$APPLE_TEAM_ID" =~ ^[A-Z0-9]{10}$ ]] || mac_nightly_die 'APPLE_TEAM_ID is not an Apple team ID' + if [[ -n "${NIGHTLY_APPLE_TEAM_ID:-}" && "$NIGHTLY_APPLE_TEAM_ID" != "$APPLE_TEAM_ID" ]]; then + mac_nightly_die 'the signing team differs from the reviewed Nightly team (NIGHTLY_APPLE_TEAM_ID)' + fi +} + +# The keychain import-cert.sh reports: a regular file inside this run's private WORK. This app's +# import-cert.sh creates it in a fresh directory of its own, so the path is not predicted here. +mac_nightly_keychain_is_ours() { + local keychain="$1" work="$2" + [[ -n "$keychain" && "$keychain" == "$work"/* && -f "$keychain" && ! -L "$keychain" ]] +} + +# 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 GridCraft +# 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")" == GridCraft ]] || mac_nightly_die 'Contents/MacOS must hold only the GridCraft GUI (no CLI)' + [[ -f "$app/Contents/MacOS/GridCraft" && -x "$app/Contents/MacOS/GridCraft" ]] || mac_nightly_die 'missing executable GUI' + [[ "$(lipo -archs "$app/Contents/MacOS/GridCraft")" == arm64 ]] || mac_nightly_die 'the GUI must be thin arm64' + plist="$app/Contents/Info.plist" + for key in CFBundleIdentifier CFBundleExecutable GridCraftVersion; 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" == GridCraft ]] ;; + GridCraftVersion) [[ "$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 +} diff --git a/packaging/macos/nightly-sign.sh b/packaging/macos/nightly-sign.sh new file mode 100755 index 0000000000..6d252e744f --- /dev/null +++ b/packaging/macos/nightly-sign.sh @@ -0,0 +1,144 @@ +#!/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/gridcraft--macos-aarch64-nightly.zip \ +# --output /abs//gridcraft--macos-aarch64-nightly.zip +# +# Input: the unsigned archive nightly.sh made. Output: the same bundle signed with the Developer ID and +# hardened runtime, notarized, with the ticket stapled into the bundle, zipped without extended +# attributes. Writes only that file, never replacing one; the temporary keychain and work directory +# are removed on every exit. +# +# Env (all required, no ad-hoc or unnotarized fallback): APPLE_CERTIFICATE, APPLE_CERTIFICATE_PASSWORD, +# KEYCHAIN_PASSWORD, APPLE_ID, APPLE_PASSWORD, APPLE_TEAM_ID; optional NIGHTLY_APPLE_TEAM_ID (must +# equal APPLE_TEAM_ID) and RUNNER_TEMP (work directory base). +# +# Never compiles, and never runs anything from the payload: the version query runs on the signed +# bundle in a job without secrets (nightly-verify.sh). +set -euo pipefail +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +# shellcheck source=nightly-lib.sh +. "$HERE/nightly-lib.sh" +# shellcheck source=../nightly-common.sh +. "$HERE/../nightly-common.sh" + +ARCH='' INPUT='' OUTPUT='' +while [[ $# -gt 0 ]]; do + case "$1" in + --arch | --input | --output) + [[ $# -ge 2 ]] || mac_nightly_die "missing $1 value" + case "$1" in --arch) ARCH="$2" ;; --input) INPUT="$2" ;; --output) OUTPUT="$2" ;; esac + shift 2 ;; + -h | --help) sed -n '2,18p' "$0"; exit 0 ;; + *) mac_nightly_die "unsupported argument: $1" ;; + esac +done +[[ "$ARCH" == aarch64 ]] || mac_nightly_die 'only --arch aarch64 is supported' +[[ "$INPUT" == /* && "$OUTPUT" == /* ]] || mac_nightly_die '--input and --output must be absolute paths' +NAME="$(basename -- "$INPUT")" +VERSION="$(mac_nightly_version_from_asset "$NAME")" || mac_nightly_die 'the input is not a prepared Nightly archive name' +[[ "$(basename -- "$OUTPUT")" == "$NAME" ]] || mac_nightly_die 'the output must keep the archive name' +[[ -f "$INPUT" && ! -L "$INPUT" ]] || mac_nightly_die 'the input must be a regular file' +[[ ! -e "$OUTPUT" && ! -L "$OUTPUT" ]] || mac_nightly_die 'refusing to replace an existing output' +[[ -d "$(dirname -- "$OUTPUT")" && ! -L "$(dirname -- "$OUTPUT")" ]] || mac_nightly_die 'the output directory must exist' +mac_nightly_require_secrets +[[ "$(uname -s)" == Darwin ]] || mac_nightly_die 'signing needs macOS (codesign, notarytool, stapler)' + +# This app's import-cert.sh creates its keychain inside a fresh directory of its own +# (`mktemp -d "$BASE/gridcraft-signing.XXXXXXXX"/gridcraft-signing.keychain-db`), so the name is +# read back from it instead of being predicted here; it must still live inside this run's WORK. +BASE="${RUNNER_TEMP:-${TMPDIR:-/tmp}}" +WORK="$(mktemp -d "${BASE%/}/gridcraft-nightly-sign.XXXXXX")" +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. +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' +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 "==> GridCraft 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/GridCraft" +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" diff --git a/packaging/macos/nightly-verify.sh b/packaging/macos/nightly-verify.sh new file mode 100755 index 0000000000..1e137b3a56 --- /dev/null +++ b/packaging/macos/nightly-verify.sh @@ -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/gridcraft--macos-aarch64-nightly.zip --expect signed [--team ID] +# nightly-verify.sh --input /abs/gridcraft--macos-aarch64-nightly.zip --expect unsigned +# +# Both: the archive holds only the GUI-only Nightly bundle with the exact GridCraftVersion, 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 --version` (the shared producer +# smoke): each must exit 0 within 15 seconds, print exactly `GridCraft (nightly-v1)` and +# write nothing to standard error. +set -euo pipefail +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +# shellcheck source=nightly-lib.sh +. "$HERE/nightly-lib.sh" + +INPUT='' EXPECT='' TEAM="${NIGHTLY_APPLE_TEAM_ID:-}" +while [[ $# -gt 0 ]]; do + case "$1" in + --input | --expect | --team) + [[ $# -ge 2 ]] || mac_nightly_die "missing $1 value" + case "$1" in --input) INPUT="$2" ;; --expect) EXPECT="$2" ;; --team) TEAM="$2" ;; esac + shift 2 ;; + -h | --help) sed -n '2,15p' "$0"; exit 0 ;; + *) mac_nightly_die "unsupported argument: $1" ;; + esac +done +for name in "${MAC_NIGHTLY_SECRETS[@]}" MACOS_SIGN_IDENTITY MACOS_KEYCHAIN; do + [[ -z "${!name:-}" ]] || mac_nightly_die "refusing to run the payload with signing material in the environment ($name)" +done +[[ "$EXPECT" == signed || "$EXPECT" == unsigned ]] || mac_nightly_die '--expect must be signed or unsigned' +[[ "$EXPECT" == unsigned || "$TEAM" =~ ^[A-Z0-9]{10}$ ]] || mac_nightly_die 'a signed check needs the Apple team ID (--team or NIGHTLY_APPLE_TEAM_ID)' +[[ "$INPUT" == /* && -f "$INPUT" && ! -L "$INPUT" ]] || mac_nightly_die '--input must be an absolute regular file' +VERSION="$(mac_nightly_version_from_asset "$(basename -- "$INPUT")")" || mac_nightly_die 'the input is not a prepared Nightly archive name' +[[ "$(uname -s)" == Darwin && "$(uname -m)" == arm64 ]] || mac_nightly_die 'needs an Apple silicon Mac' + +WORK="$(mktemp -d "${RUNNER_TEMP:-${TMPDIR:-/tmp}}/gridcraft-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/GridCraft" "$@" 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" == "GridCraft $VERSION (nightly-v1)" ]] || mac_nightly_die "the version query ($*) reports '$out', not GridCraft $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): GridCraft $VERSION (nightly-v1), plain and in the Launcher's profile form" diff --git a/packaging/macos/nightly.sh b/packaging/macos/nightly.sh new file mode 100755 index 0000000000..aa1f60fce5 --- /dev/null +++ b/packaging/macos/nightly.sh @@ -0,0 +1,51 @@ +#!/usr/bin/env bash +# App-owned GUI-only Nightly for Apple silicon, compile step only (no signing material): +# +# $DIST/gridcraft--macos-aarch64-nightly.zip GridCraft Nightly.app, unsigned +# +# Usage: packaging/macos/nightly.sh --arch aarch64 +# +# Required env (nightly-common.sh): GRIDCRAFT_BUILD_CHANNEL=nightly-v1, GRIDCRAFT_VERSION, +# GRIDCRAFT_BUILD_SHA, GRIDCRAFT_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/gridcraft-$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/GridCraft" +chmod 755 "$APP/Contents/MacOS/GridCraft" +cp "$ROOT/assets/app-icon/gridcraft-nightly.icns" "$APP/Contents/Resources/gridcraft-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 "$GRIDCRAFT_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" diff --git a/packaging/macos/nightly_plist.py b/packaging/macos/nightly_plist.py new file mode 100755 index 0000000000..e926399f0b --- /dev/null +++ b/packaging/macos/nightly_plist.py @@ -0,0 +1,69 @@ +#!/usr/bin/env python3 +"""Nightly metadata: run from a private owned build cwd with a staged template. + +All file arguments must stay beneath that cwd; this is not native/signing acceptance. +""" +import argparse +import datetime +import os +from pathlib import Path +import plistlib +import re +import sys + +# The shared helper location is fixed by this script, not by CLI file arguments. +sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) +from nightly_paths import OwnedBuildRoot + +MAX_TEMPLATE_BYTES = 256 * 1024 + +IDENTIFIER = "ai.storyteller.gridcraft.nightly" +ASSOCIATIONS = ("CFBundleDocumentTypes", "CFBundleURLTypes", "UTExportedTypeDeclarations", "UTImportedTypeDeclarations") +VERSION = re.compile(r"([0-9]+\.[0-9]+\.[0-9]+)-nightly\.([0-9]{8})\.[0-9]+\.[0-9]+\.g([0-9a-f]{12})\Z") + + +def render(template: bytes, version: str, commit: str) -> bytes: + match = VERSION.fullmatch(version) + if not match or not re.fullmatch(r"[0-9a-f]{40}", commit) or match[3] != commit[:12]: + raise ValueError("exact prepared Nightly version and matching source commit are required") + datetime.datetime.strptime(match[2], "%Y%m%d") + data = plistlib.loads(template) + if not isinstance(data, dict) or data.get("CFBundlePackageType") != "APPL": + raise ValueError("expected the app-owned application plist template") + for key in ASSOCIATIONS: + data.pop(key, None) + data.update( + CFBundleDisplayName="GridCraft Nightly", + CFBundleName="GridCraft Nightly", + CFBundleIdentifier=IDENTIFIER, + CFBundleExecutable="GridCraft", + CFBundleIconFile="gridcraft-nightly", + CFBundleShortVersionString=match[1], + CFBundleVersion=match[1], + GridCraftVersion=version, + GridCraftBuildCommit=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() diff --git a/packaging/macos/nightly_plist_tests.py b/packaging/macos/nightly_plist_tests.py new file mode 100755 index 0000000000..469e715b44 --- /dev/null +++ b/packaging/macos/nightly_plist_tests.py @@ -0,0 +1,202 @@ +#!/usr/bin/env python3 +"""Generated metadata/sentinel fixtures; no native binary, signature, archive or network.""" +import importlib.util +import os +from pathlib import Path +import plistlib +import runpy +import sys +from unittest import mock +import tempfile +import unittest + +HERE = Path(__file__).resolve().parent +SPEC = importlib.util.spec_from_file_location("photo_nightly_plist", HERE / "nightly_plist.py") +POLICY = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(POLICY) +COMMIT = "a" * 40 +VERSION = "0.23.1-nightly.20261121.12345.1.g" + COMMIT[:12] + + +class NightlyMetadata(unittest.TestCase): + def setUp(self): + self.directory = tempfile.TemporaryDirectory() + self.addCleanup(self.directory.cleanup) + self.root = Path(self.directory.name).resolve() + previous = Path.cwd() + os.chdir(self.root) + self.addCleanup(os.chdir, previous) + self.template = self.root / "Info.plist.in" + self.original = (HERE / "Info.plist.in").read_bytes() + self.template.write_bytes(self.original) + self.output = self.root / "Info.plist" + + def test_nightly_transform_removes_associations_without_changing_stable_or_platform_metadata(self): + stable = plistlib.loads(self.original) + stable["CFBundleURLTypes"] = [{"CFBundleURLSchemes": ["generated-test-scheme"]}] + prepared = plistlib.dumps(stable) + self.template.write_bytes(prepared) + POLICY.write_plist(self.template, self.output, VERSION, COMMIT) + rendered = plistlib.loads(self.output.read_bytes()) + for key in POLICY.ASSOCIATIONS: + self.assertNotIn(key, rendered) + self.assertNotEqual(rendered["CFBundleIdentifier"], stable["CFBundleIdentifier"]) + self.assertEqual(rendered["CFBundleIdentifier"], "ai.storyteller.gridcraft.nightly") + self.assertEqual(rendered["CFBundleExecutable"], "GridCraft") + self.assertEqual(rendered["GridCraftVersion"], VERSION) + self.assertEqual(rendered["GridCraftBuildCommit"], COMMIT) + self.assertTrue(VERSION.startswith(rendered["CFBundleVersion"] + "-nightly.")) + for key in ("LSMinimumSystemVersion", "CFBundleLocalizations", "NSHighResolutionCapable", "NSHumanReadableCopyright"): + self.assertEqual(rendered[key], stable[key]) + self.assertEqual(self.template.read_bytes(), prepared) + self.assertEqual((HERE / "Info.plist.in").read_bytes(), self.original) + + def test_bad_identity_or_template_refuses_before_creating_output(self): + for version, commit in (("0.23.1", COMMIT), (VERSION, "b" * 40), (VERSION, "not-a-commit"), (VERSION.replace("20261121", "20261399"), COMMIT)): + with self.subTest(version=version, commit=commit): + with self.assertRaises(ValueError): + POLICY.write_plist(self.template, self.output, version, commit) + self.assertFalse(self.output.exists()) + self.assertEqual(self.template.read_bytes(), self.original) + self.template.write_bytes(plistlib.dumps({"CFBundlePackageType": "generated-not-an-app"})) + with self.assertRaises(ValueError): + POLICY.write_plist(self.template, self.output, VERSION, COMMIT) + self.assertFalse(self.output.exists()) + + def test_cli_writes_the_requested_identity_without_replacing_the_template(self): + helper = HERE / "nightly_plist.py" + argv = [str(helper), "--template", str(self.template), "--output", str(self.output), "--version", VERSION, "--source-commit", COMMIT] + with mock.patch.object(sys, "argv", argv): + runpy.run_path(str(helper), run_name="__main__") + result = plistlib.loads(self.output.read_bytes()) + self.assertEqual(result["GridCraftVersion"], VERSION) + self.assertEqual(result["GridCraftBuildCommit"], 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())["GridCraftVersion"], VERSION) + + +if __name__ == "__main__": + unittest.main() diff --git a/packaging/macos/nightly_sign_tests.py b/packaging/macos/nightly_sign_tests.py new file mode 100755 index 0000000000..0a4535206a --- /dev/null +++ b/packaging/macos/nightly_sign_tests.py @@ -0,0 +1,445 @@ +#!/usr/bin/env python3 +"""The macOS Nightly signing and verification scripts, run on any POSIX host against generated +fixtures and stand-in Apple tools (codesign, notarytool, stapler, spctl, security, ditto, plutil, +lipo) that log their arguments. This proves the scripts' order, refusals and cleanup; it is not a +real signature, notarization or Mac run.""" +import base64 +import importlib.util +import json +import os +from pathlib import Path +import plistlib +import shutil +import stat +import subprocess +import sys +import tempfile +import textwrap +import time +import unittest +import zipfile + +HERE = Path(__file__).resolve().parent +SPEC = importlib.util.spec_from_file_location("photo_mac_nightly_plist", HERE / "nightly_plist.py") +PLIST = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(PLIST) +COMMIT = "b" * 40 +VERSION = "0.23.1-nightly.20261123.4567.1.g" + COMMIT[:12] +ASSET = f"gridcraft-{VERSION}-macos-aarch64-nightly.zip" +APP = "GridCraft 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 "") +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.gridcraft.nightly\n" + "CodeDirectory v=20500 size=1 flags=0x10000(runtime) hashes=1+7 location=embedded\n" + "Authority=Developer ID Application: Generated Fixture (%s)\n" + "Timestamp=23 Nov 2026 at 17:00:00\nTeamIdentifier=%s\n" % (target, team, team)) +elif name == "xcrun": + if args[:2] == ["notarytool", "submit"]: + print(json.dumps({"id": "generated-id", "status": os.environ.get("SHIM_NOTARY", "Accepted")})) + elif args[:2] == ["stapler", "staple"]: + (Path(args[2]) / "Contents/CodeResources").write_bytes(b"ticket") + elif args[:2] == ["stapler", "validate"]: + sys.exit(0 if (Path(args[2]) / "Contents/CodeResources").is_file() else 1) +elif name == "spctl": + sys.stderr.write("%s: accepted\nsource=Notarized Developer ID\n" % args[-1]) +elif name == "cargo": + sys.exit(1) +# sleep: the retry waits pass at once. +""" + +TOOLS = ("uname", "lipo", "ditto", "plutil", "security", "codesign", "xcrun", "spctl", "cargo", "sleep") + + +class Fixture: + def __init__(self, test): + self.directory = tempfile.TemporaryDirectory() + test.addCleanup(self.directory.cleanup) + self.root = Path(self.directory.name).resolve() + self.bin = self.root / "bin" + self.bin.mkdir() + shim = self.bin / "shim.py" + shim.write_text(SHIM) + for tool in TOOLS: + path = self.bin / tool + path.write_text(f"#!{sys.executable}\nimport sys\nsys.argv[0] = {str(path)!r}\nexec(compile(open({str(shim)!r}).read(), 'shim', 'exec'), {{'__name__': '__main__'}})\n") + path.chmod(0o755) + self.log = self.root / "tools.log" + self.ran = self.root / "payload-ran" + self.temp = self.root / "runner-temp" + self.temp.mkdir() + self.dist = self.root / "unsigned" + self.dist.mkdir() + self.signed = self.root / "signed" + self.signed.mkdir() + self.input = self.dist / ASSET + self.output = self.signed / ASSET + # Every script runs from a directory with modules a Python helper must not import (-I). + self.cwd = self.root / "cwd" + self.cwd.mkdir() + self.hijacked = self.root / "hijacked" + for module in ("shutil", "zipfile", "stat"): + (self.cwd / f"{module}.py").write_text(f"open({str(self.hijacked)!r}, 'a').write({module!r})\n") + + def add_entry(self, info, data=b""): + """Append one raw entry to the input archive.""" + with zipfile.ZipFile(self.input, "a") as z: + z.writestr(info, data) + + def bundle(self, version=VERSION, extra=None, gui=None): + """The archive nightly.sh makes: the real template through the real plist helper.""" + stage = self.root / "stage" + shutil.rmtree(stage, ignore_errors=True) + app = stage / APP + (app / "Contents/MacOS").mkdir(parents=True) + (app / "Contents/Resources").mkdir() + exe = app / "Contents/MacOS/GridCraft" + exe.write_text(gui or f"#!/bin/sh\ntouch {self.ran}\necho 'GridCraft {version} (nightly-v1)'\n") + exe.chmod(0o755) + (app / "Contents/Resources/gridcraft-nightly.icns").write_bytes(b"generated icon") + rendered = PLIST.render((HERE / "Info.plist.in").read_bytes(), version, COMMIT) + (app / "Contents/Info.plist").write_bytes(rendered) + for relative, data in (extra or {}).items(): + (app / relative).write_bytes(data) + (app / relative).chmod(0o755) + if self.input.exists(): + self.input.unlink() + with zipfile.ZipFile(self.input, "x") as z: + for path in sorted([app] + list(app.rglob("*"))): + arc = (Path(APP) / path.relative_to(app)).as_posix() + info = zipfile.ZipInfo(arc + ("/" if path.is_dir() else "")) + info.external_attr = (path.stat().st_mode & 0xFFFF) << 16 + z.writestr(info, b"" if path.is_dir() else path.read_bytes()) + return self.input + + def env(self, **changes): + env = {"PATH": f"{self.bin}:{os.environ['PATH']}", "HOME": str(self.root), "SHIM_LOG": str(self.log), + "SHIM_TEAM": TEAM, "SHIM_IDENTITY": IDENTITY, "RUNNER_TEMP": str(self.temp), **SECRETS} + env.update(changes) + return {key: value for key, value in env.items() if value is not None} + + def run(self, script, *args, **env): + if self.log.exists(): + self.log.unlink() + return subprocess.run(["bash", str(HERE / script), *map(str, args)], env=self.env(**env), cwd=self.cwd, + stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, timeout=120) + + def sign(self, **env): + return self.run("nightly-sign.sh", "--arch", "aarch64", "--input", self.input, "--output", self.output, **env) + + def calls(self): + if not self.log.exists(): + return [] + return [json.loads(line) for line in self.log.read_text().splitlines()] + + +def lib(function, *args): + """Run one nightly-lib.sh function; returns (exit status, stdout).""" + script = f'. {str(HERE / "nightly-lib.sh")!r}; {function} "$@"' + result = subprocess.run(["bash", "-c", script, "lib", *args], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True) + return result.returncode, result.stdout.strip() + + +DETAILS = (f"Identifier=ai.storyteller.gridcraft.nightly\nCodeDirectory v=20500 size=1 flags=0x10000(runtime) hashes=1\n" + f"Authority=Developer ID Application: Generated Fixture ({TEAM})\nAuthority=Developer ID Certification Authority\n" + f"Timestamp=23 Nov 2026\nTeamIdentifier={TEAM}\n") + + +class Checks(unittest.TestCase): + def test_the_version_comes_only_from_a_prepared_nightly_asset_name(self): + self.assertEqual(lib("mac_nightly_version_from_asset", ASSET), (0, VERSION)) + for name in (f"gridcraft-0.23.1-macos-aarch64.zip", f"gridcraft-{VERSION}-macos-universal-nightly.zip", + f"gridcraft-{VERSION}-linux-x86_64-nightly.tar.gz", ASSET.replace(".g", ".x"), "../" + ASSET): + with self.subTest(name=name): + self.assertNotEqual(lib("mac_nightly_version_from_asset", name)[0], 0) + + def test_signature_needs_every_part_of_the_developer_id_signature(self): + self.assertEqual(lib("mac_nightly_check_signature", DETAILS, TEAM)[0], 0) + for broken in (DETAILS.replace("flags=0x10000(runtime)", "flags=0x0(none)"), + DETAILS.replace("Timestamp=23 Nov 2026\n", "Signed Time=23 Nov 2026\n"), + "Identifier=gridcraft-1234\nSignature=adhoc\nTeamIdentifier=not set\n", + DETAILS.replace("ai.storyteller.gridcraft.nightly", "ai.storyteller.gridcraft"), + DETAILS.replace("ai.storyteller.gridcraft.nightly", "aiXstorytellerXgridcraftXnightly")): + with self.subTest(broken=broken): + self.assertNotEqual(lib("mac_nightly_check_signature", broken, TEAM)[0], 0) + self.assertNotEqual(lib("mac_nightly_check_signature", DETAILS, "ZZZZZ99999")[0], 0, "another team") + + def test_gatekeeper_must_accept_the_bundle_as_notarized(self): + self.assertEqual(lib("mac_nightly_check_assessment", "x.app: accepted\nsource=Notarized Developer ID\n")[0], 0) + for text in ("x.app: accepted\nsource=Developer ID\n", "x.app: rejected\nsource=Unnotarized Developer ID\n"): + with self.subTest(text=text): + self.assertNotEqual(lib("mac_nightly_check_assessment", text)[0], 0) + + def test_the_signing_keychain_must_be_a_regular_file_inside_the_run(self): + # This app's import-cert.sh makes its own directory for the keychain, so the night's + # script accepts any path inside WORK - and nothing outside it, and no link. + with tempfile.TemporaryDirectory() as work: + work = Path(work).resolve() + nested = work / "gridcraft-signing.fixture" + nested.mkdir() + keychain = nested / "gridcraft-signing.keychain-db" + keychain.write_bytes(b"generated fixture") + self.assertEqual(lib("mac_nightly_keychain_is_ours", keychain, work)[0], 0) + outside = Path(tempfile.mkdtemp()) / "gridcraft-signing.keychain-db" + self.addCleanup(shutil.rmtree, outside.parent) + outside.write_bytes(b"generated fixture") + self.assertNotEqual(lib("mac_nightly_keychain_is_ours", outside, work)[0], 0, "another directory's keychain") + self.assertNotEqual(lib("mac_nightly_keychain_is_ours", work / "missing.keychain-db", work)[0], 0) + self.assertNotEqual(lib("mac_nightly_keychain_is_ours", "", work)[0], 0) + link = work / "linked.keychain-db" + link.symlink_to(keychain) + self.assertNotEqual(lib("mac_nightly_keychain_is_ours", link, work)[0], 0, "a link is not the keychain it points at") + + 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], ["GridCraft", APP], "inside-out: executable, then bundle") + for call in signs: + for flag in ("--force", "--timestamp", "runtime", str(HERE / "entitlements.plist"), IDENTITY): + self.assertIn(flag, call) + order = [" ".join(call[:3]) for call in calls] + submit = order.index("xcrun notarytool submit") + staple = order.index("xcrun stapler staple") + self.assertLess(max(i for i, call in enumerate(calls) if call[0] == "codesign" and "--sign" in call), submit) + self.assertLess(submit, staple) + final = [i for i, call in enumerate(calls) if call[0] == "ditto" and "-c" in call][-1] + self.assertLess(staple, final, "the final archive carries the stapled ticket") + self.assertIn("--noextattr", calls[final]) + self.assertIn(["security", "delete-keychain"], [call[:2] for call in calls]) + self.assertEqual(list(self.f.temp.iterdir()), [], "the work directory and keychain are removed") + with zipfile.ZipFile(self.f.output) as z: + names = set(z.namelist()) + self.assertIn(f"{APP}/Contents/CodeResources", names, "stapled ticket inside the bundle") + self.assertIn(f"{APP}/Contents/_CodeSignature/CodeResources", names) + self.assertTrue(all(name.startswith(APP) for name in names)) + mode = z.getinfo(f"{APP}/Contents/MacOS/GridCraft").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/gridcraft-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 'GridCraft {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 'GridCraft 0.23.1 (stable)'\n") + self.assertNotEqual(self.verify("--expect", "unsigned").returncode, 0) + + def test_the_launcher_profile_form_must_answer_promptly_and_cleanly(self): + answer = f"echo 'GridCraft {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"}, + GRIDCRAFT_BUILD_CHANNEL="nightly-v1", GRIDCRAFT_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() diff --git a/packaging/nightly-archive-tests.py b/packaging/nightly-archive-tests.py new file mode 100755 index 0000000000..9487b31904 --- /dev/null +++ b/packaging/nightly-archive-tests.py @@ -0,0 +1,231 @@ +#!/usr/bin/env python3 +"""Synthetic app-owned archive/output tests; no native build or executable launch.""" +import gzip +import importlib.util +import os +import runpy +import sys +from unittest import mock +from pathlib import Path +import subprocess +import tarfile +import tempfile +import unittest + +HERE = Path(__file__).resolve().parent +SPEC = importlib.util.spec_from_file_location("photo_nightly_archive", HERE / "nightly-archive.py") +ARCHIVE = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(ARCHIVE) + + +class ArchivePolicy(unittest.TestCase): + def setUp(self): + self.scratch = tempfile.TemporaryDirectory() + self.addCleanup(self.scratch.cleanup) + self.root = Path(self.scratch.name).resolve() + previous = Path.cwd() + os.chdir(self.root) + self.addCleanup(os.chdir, previous) + self.stage = self.root / "stage" + self.stage.mkdir() + self.output = self.root / "nightly.tar.gz" + # The kit's tar layout: `gridcraft` runs, `gridcraft-bin` is the GUI it starts. + self.required = {"gridcraft", "gridcraft-bin", "gridcraft-nightly.png", "README.md", "LICENSE-MIT", "LICENSE-APACHE", "NOTICE", "ATTRIBUTION.md"} + for name in self.required: + (self.stage / name).write_bytes(b"generated fixture: " + name.encode()) + (self.stage / "gridcraft").chmod(0o755) + (self.stage / "gridcraft-bin").chmod(0o755) + + def test_flat_regular_ustar_with_all_notices(self): + (self.stage / "OFL-Font.txt").write_text("generated fixture license", encoding="utf-8") + ARCHIVE.linux_archive(self.stage, self.output) + with tarfile.open(self.output) as archive: + self.assertEqual({m.name for m in archive}, self.required | {"OFL-Font.txt"}) + self.assertTrue(all(m.isfile() and not m.pax_headers for m in archive)) + self.assertEqual(archive.extractfile("gridcraft").read(), (self.stage / "gridcraft").read_bytes()) + with gzip.open(self.output, "rb") as stream: + while (header := stream.read(512)) != bytes(512): + self.assertEqual(len(header), 512) + self.assertIn(header[156:157], {b"0", b"\0"}) + self.assertEqual(header[257:263], b"ustar\0") + size = int(header[124:136].rstrip(b"\0 ").lstrip(b" ") or b"0", 8) + stream.read(((size + 511) // 512) * 512) + + def test_each_required_member_is_required_before_output(self): + for name in self.required: + with self.subTest(name=name): + content = (self.stage / name).read_bytes() + (self.stage / name).unlink() + with self.assertRaisesRegex(ValueError, "required"): + ARCHIVE.linux_archive(self.stage, self.output) + self.assertFalse(self.output.exists()) + (self.stage / name).write_bytes(content) + + def test_unexpected_cli_portable_or_installer_member_refuses(self): + for name in ["gridcraft-cli", "portable.txt", "gridcraft.desktop", "gridcraft-nightly"]: + with self.subTest(name=name): + bad = self.stage / name + bad.write_bytes(b"generated fixture") + with self.assertRaisesRegex(ValueError, "unexpected"): + ARCHIVE.linux_archive(self.stage, self.output) + self.assertFalse(self.output.exists()) + bad.unlink() + + def test_symlink_refuses_before_output(self): + icon = self.stage / "gridcraft-nightly.png" + icon.unlink() + icon.symlink_to(self.stage / "README.md") + with self.assertRaisesRegex(ValueError, "regular file|symlinks or aliases"): + ARCHIVE.linux_archive(self.stage, self.output) + self.assertFalse(self.output.exists()) + + def test_directory_refuses_before_output(self): + icon = self.stage / "gridcraft-nightly.png" + icon.unlink() + icon.mkdir() + with self.assertRaisesRegex(ValueError, "regular file"): + ARCHIVE.linux_archive(self.stage, self.output) + self.assertFalse(self.output.exists()) + + def test_long_notice_refuses_before_output(self): + (self.stage / ("OFL-" + "x" * 100 + ".txt")).write_bytes(b"fixture") + with self.assertRaisesRegex(ValueError, "short regular"): + ARCHIVE.linux_archive(self.stage, self.output) + self.assertFalse(self.output.exists()) + + def test_case_colliding_notices_refuse_before_output(self): + for name in ["OFL-Font.txt", "OFL-font.txt"]: + (self.stage / name).write_bytes(b"fixture") + with self.assertRaisesRegex(ValueError, "case-colliding"): + ARCHIVE.linux_archive(self.stage, self.output) + self.assertFalse(self.output.exists()) + + def test_cli_dispatches_only_the_supported_archive_kind(self): + helper = HERE / "nightly-archive.py" + with mock.patch.object(sys, "argv", [str(helper), "linux", str(self.stage), str(self.output)]): + runpy.run_path(str(helper), run_name="__main__") + with tarfile.open(self.output) as archive: + self.assertEqual({member.name for member in archive}, self.required) + refused = self.root / "refused.tar.gz" + for args in ([str(helper)], [str(helper), "unknown", str(self.stage), str(refused)]): + with self.subTest(args=args), mock.patch.object(sys, "argv", args): + with self.assertRaises(SystemExit): + runpy.run_path(str(helper), run_name="__main__") + self.assertFalse(refused.exists()) + + def test_existing_archive_is_unchanged(self): + self.output.write_bytes(b"owned earlier artifact") + with self.assertRaises(FileExistsError): + ARCHIVE.linux_archive(self.stage, self.output) + self.assertEqual(self.output.read_bytes(), b"owned earlier artifact") + + + def test_archive_output_outside_build_root_refuses(self): + with tempfile.TemporaryDirectory() as external: + output = Path(external) / "nightly.tar.gz" + with self.assertRaises(ValueError): + ARCHIVE.linux_archive(self.stage, output) + self.assertFalse(output.exists()) + + def test_archive_stage_outside_build_root_refuses(self): + with tempfile.TemporaryDirectory() as external: + stage = Path(external) + for name in self.required: + (stage / name).write_bytes(b"generated external fixture") + with self.assertRaises(ValueError): + ARCHIVE.linux_archive(stage, self.output) + self.assertFalse(self.output.exists()) + + def test_archive_stage_alias_refuses(self): + alias = self.root / "stage-alias" + alias.symlink_to(self.stage, target_is_directory=True) + with self.assertRaises(ValueError): + ARCHIVE.linux_archive(alias, self.output) + self.assertFalse(self.output.exists()) + + def test_archive_output_parent_alias_refuses(self): + with tempfile.TemporaryDirectory() as external: + alias = self.root / "output-alias" + alias.symlink_to(external, target_is_directory=True) + with self.assertRaises(ValueError): + ARCHIVE.linux_archive(self.stage, alias / "nightly.tar.gz") + self.assertFalse((Path(external) / "nightly.tar.gz").exists()) + + def test_archive_parent_traversal_refuses(self): + with tempfile.TemporaryDirectory(dir=self.root.parent) as external: + output = Path("..") / Path(external).name / "nightly.tar.gz" + with self.assertRaises(ValueError): + ARCHIVE.linux_archive(self.stage, output) + self.assertFalse((Path(external) / "nightly.tar.gz").exists()) + + def test_nonflat_member_name_refuses(self): + stage_root = os.path.realpath(self.stage) + with open(self.stage / "README.md", "rb") as incoming: + for bad in ("../escape", "/absolute", "nested/name", "x/../README.md", "", ".", ".."): + with self.subTest(name=bad), self.assertRaises(ValueError): + ARCHIVE.member_info(stage_root, bad, incoming) + + def test_member_header_matches_what_gettarinfo_records(self): + stage_root = os.path.realpath(self.stage) + for name in sorted(self.required): + with self.subTest(name=name), open(self.stage / name, "rb") as incoming: + ours = ARCHIVE.member_info(stage_root, name, incoming) + with tarfile.open(fileobj=__import__("io").BytesIO(), mode="w") as reference: + theirs = reference.gettarinfo(fileobj=incoming, arcname=name) + self.assertEqual(ours.get_info(), theirs.get_info()) + + def test_member_read_budget_refuses_before_output(self): + (self.stage / "OFL-Large.txt").write_bytes(b"x" * 65) + with mock.patch.object(ARCHIVE, "MAX_MEMBER_BYTES", 64, create=True): + with self.assertRaises(ValueError): + ARCHIVE.linux_archive(self.stage, self.output) + self.assertFalse(self.output.exists()) + + + def test_member_growth_is_rechecked_before_copy_and_output_is_cleaned(self): + growing = self.stage / "OFL-Growing.txt" + growing.write_bytes(b"x" * 32) + original = ARCHIVE.member_info + + def grow_before_stat(stage_root, name, incoming): + if name == growing.name: + growing.write_bytes(b"x" * 65) + return original(stage_root, name, incoming) + + with mock.patch.object(ARCHIVE, "MAX_MEMBER_BYTES", 64), \ + mock.patch.object(ARCHIVE, "member_info", grow_before_stat): + with self.assertRaises(ValueError): + ARCHIVE.linux_archive(self.stage, self.output) + self.assertFalse(self.output.exists()) + + +class ExclusiveOutput(unittest.TestCase): + def setUp(self): + self.scratch = tempfile.TemporaryDirectory() + self.addCleanup(self.scratch.cleanup) + self.root = Path(self.scratch.name) + self.source = self.root / "input archive" + self.output = self.root / "final archive" + self.source.write_bytes(b"generated archive fixture" * 1024) + + def publish(self): + return subprocess.run(["bash", "-c", 'set -euo pipefail; source "$1"; nightly_publish_archive "$2" "$3"', "test", str(HERE / "nightly-common.sh"), str(self.source), str(self.output)], capture_output=True, text=True, timeout=15) + + def test_success_copies_exact_bytes(self): + result = self.publish() + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(self.output.read_bytes(), self.source.read_bytes()) + + def test_existing_output_is_never_replaced(self): + self.output.write_bytes(b"existing artifact") + self.assertNotEqual(self.publish().returncode, 0) + self.assertEqual(self.output.read_bytes(), b"existing artifact") + + def test_missing_source_does_not_leave_a_fake_empty_artifact(self): + self.source.unlink() + self.assertNotEqual(self.publish().returncode, 0) + self.assertFalse(self.output.exists()) + + +if __name__ == "__main__": + unittest.main() diff --git a/packaging/nightly-archive.py b/packaging/nightly-archive.py new file mode 100644 index 0000000000..490bf19336 --- /dev/null +++ b/packaging/nightly-archive.py @@ -0,0 +1,132 @@ +#!/usr/bin/env python3 +"""Flat Linux archive policy, invoked from its private owned build cwd. + +The stage and archive must both remain under that independently chosen root. +No native build, platform signing, or malicious-same-UID sandbox is implied. +""" +import grp +import gzip +import os +import pathlib +import pwd +import re +import stat +import sys +import tarfile + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) +from nightly_paths import OwnedBuildRoot + +APP_DOCS = {"README.md", "LICENSE", "LICENSE-MIT", "LICENSE-APACHE", "COPYRIGHT", "NOTICE", "ATTRIBUTION.md"} +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 + # `gridcraft` is the launcher and `gridcraft-bin` the GUI it starts (nightly.sh); the icon + # and the notices are the rest of the flat archive. + if name not in {"gridcraft", "gridcraft-bin", "gridcraft-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()) + required = {"gridcraft", "gridcraft-bin", "gridcraft-nightly.png", "README.md", "LICENSE-MIT", "LICENSE-APACHE", "NOTICE", "ATTRIBUTION.md"} + if not required.issubset({item.name for item in entries}): + raise ValueError("required GUI/icon/notices missing") + return entries + + +def member_info(stage_root, name, incoming): + """Header for one stage file, built from the file this run opened rather than from the archive. + + Members are flat names that resolve directly inside the stage they came from. + """ + if os.path.isabs(name) or os.path.basename(name) != name or name in ("", ".", ".."): + raise ValueError(f"nightly member name must be a flat file name: {name}") + destination = os.path.realpath(os.path.join(stage_root, name)) + if not destination.startswith(stage_root + os.sep) or os.path.dirname(destination) != stage_root: + raise ValueError(f"nightly member resolves outside its stage: {name}") + status = os.fstat(incoming.fileno()) + if not stat.S_ISREG(status.st_mode): + raise ValueError(f"nightly member must be a regular file: {name}") + # The same fields TarFile.gettarinfo records for a regular file. + info = tarfile.TarInfo(os.path.basename(destination)) + info.type = tarfile.REGTYPE + info.mode = stat.S_IMODE(status.st_mode) + info.uid, info.gid = status.st_uid, status.st_gid + info.size = status.st_size + info.mtime = status.st_mtime + try: + info.uname = pwd.getpwuid(status.st_uid).pw_name + except KeyError: + pass + try: + info.gname = grp.getgrgid(status.st_gid).gr_name + except KeyError: + pass + return info + + +def verify_headers(root, output): + # Bounded ordinary headers, not a transparent PAX/GNU-normalizing reader. + total = 0 + count = 0 + with root.reader(output, MAX_TOTAL_BYTES) as incoming, gzip.GzipFile(fileobj=incoming) as stream: + while True: + header = stream.read(512) + if header == b"\0" * 512: + break + if len(header) != 512 or header[156:157] not in {b"0", b"\0"}: + raise ValueError("non-ordinary TAR record was emitted") + size = int(header[124:136].rstrip(b"\0 ").lstrip(b" ") or b"0", 8) + count += 1 + total += size + if count > MAX_MEMBERS or size > MAX_MEMBER_BYTES or total > MAX_TOTAL_BYTES: + raise ValueError("archive exceeds its bounded member budget") + remaining = ((size + 511) // 512) * 512 + while remaining: + chunk = stream.read(min(remaining, 1024 * 1024)) + if not chunk: + raise ValueError("truncated TAR member") + remaining -= len(chunk) + + +def linux_archive(stage, output): + with OwnedBuildRoot() as root: + entries = checked_entries(root, stage) + stage_root = os.path.realpath(os.path.join(root.directory, stage)) + total = 0 + with root.create(output) as outgoing: + with tarfile.open(fileobj=outgoing, mode="w:gz", format=tarfile.USTAR_FORMAT) as archive: + for entry in entries: + with root.reader(entry, MAX_MEMBER_BYTES) as incoming: + info = member_info(stage_root, entry.name, incoming) + total += info.size + if info.size > MAX_MEMBER_BYTES or total > MAX_TOTAL_BYTES: + raise ValueError("nightly stage grew beyond its read bound") + archive.addfile(info, incoming) + outgoing.flush() + os.fsync(outgoing.fileno()) + verify_headers(root, output) + + +if __name__ == "__main__": + if len(sys.argv) != 4 or sys.argv[1] != "linux": + raise SystemExit("usage: nightly-archive.py linux STAGE OUTPUT (from owned private build cwd)") + linux_archive(pathlib.Path(sys.argv[2]), pathlib.Path(sys.argv[3])) diff --git a/packaging/nightly-common.sh b/packaging/nightly-common.sh new file mode 100644 index 0000000000..69460ad2b5 --- /dev/null +++ b/packaging/nightly-common.sh @@ -0,0 +1,97 @@ +# 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 + [[ "${GRIDCRAFT_BUILD_CHANNEL:-}" == nightly-v1 ]] || nightly_die 'GRIDCRAFT_BUILD_CHANNEL must be nightly-v1' + [[ "${GRIDCRAFT_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' + [[ "${GRIDCRAFT_BUILD_SHA:-}" =~ ^[0-9a-f]{40}$ ]] || nightly_die 'an exact source commit is required' + [[ "${GRIDCRAFT_VERSION##*.g}" == "${GRIDCRAFT_BUILD_SHA:0:12}" ]] || nightly_die 'version/source commit mismatch' + [[ "${GRIDCRAFT_BUILD_DATE:-}" =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}$ ]] || nightly_die 'the original run-created UTC date is required' + date_digits="${GRIDCRAFT_VERSION#*-nightly.}" + date_digits="${date_digits%%.*}" + [[ "${GRIDCRAFT_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)" == "$GRIDCRAFT_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() { + # `build.rs` reads GRIDCRAFT_VERSION (it bakes it as GRIDCRAFT_BUILT_VERSION, the value the + # binary answers `--version` with), so the prepared identity is passed explicitly here as well as + # through the inherited environment; VERSION is that same value (see env.sh). + nightly_refuse_signing_env + (cd "$ROOT" && GRIDCRAFT_VERSION="$VERSION" GRIDCRAFT_OVERRIDE_VERSION="$VERSION" cargo build --release --locked -p gridcraft --target "$NIGHTLY_RUST_TARGET") + NIGHTLY_GUI="$CARGO_TARGET_DIR/$NIGHTLY_RUST_TARGET/release/gridcraft" + [[ -f "$NIGHTLY_GUI" && ! -L "$NIGHTLY_GUI" ]] || nightly_die 'the owned GUI build did not produce a regular executable' + [[ "$(git -C "$ROOT" rev-parse HEAD)" == "$GRIDCRAFT_BUILD_SHA" && -z "$(git -C "$ROOT" status --porcelain)" ]] || nightly_die 'source changed during the build' +} + +nightly_build_gui() { + nightly_compile_gui + local actual + actual="$("$NIGHTLY_GUI" --version)" || nightly_die 'side-effect-free nightly version verification failed' + # Exactly what the flavor prints (`build_flavor::version` in apps/gridcraft): the prepared + # version followed by the build channel. A stable build prints the Cargo version instead. + [[ "$actual" == "GridCraft $VERSION (nightly-v1)" ]] \ + || nightly_die "the built identity is '$actual', not 'GridCraft $VERSION (nightly-v1)'" + [[ "$(git -C "$ROOT" rev-parse HEAD)" == "$GRIDCRAFT_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" +} + +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" +} diff --git a/packaging/nightly-icons.py b/packaging/nightly-icons.py new file mode 100755 index 0000000000..c0a67608a1 --- /dev/null +++ b/packaging/nightly-icons.py @@ -0,0 +1,227 @@ +#!/usr/bin/env python3 +"""Render the GridCraft Nightly icon set from assets/app-icon/gridcraft-nightly.svg. + +The stable set is made by packaging/icons.sh (resvg + `cargo xtask ico` + iconutil). This does the +same for the Nightly channel, with the same geometry: Windows and Linux use the full-bleed tile, +macOS uses the 824/1024 padded tile. Every frame is rendered at its own size; nothing is upscaled. + +Needs one vector renderer: `resvg` (what icons.sh uses), else a headless Chrome +(`chrome-headless-shell` or `chromium`/`google-chrome`) drawing the SVG on a transparent page at +device scale 1. The `.ico` and `.icns` containers are written here so the set needs no macOS. + +Usage: packaging/nightly-icons.py [--renderer auto|resvg|chrome] [--check] + +--check verifies the committed files still match assets/app-icon/nightly-provenance.json and that +each PNG/ICO/ICNS member has the size its slot says, without rendering anything. +""" +import argparse +import hashlib +import html +import json +import os +from pathlib import Path +import shutil +import struct +import subprocess +import sys +import tempfile +import zlib + +ROOT = Path(__file__).resolve().parents[1] +ICONS = ROOT / "assets" / "app-icon" +SVG = ICONS / "gridcraft-nightly.svg" +# The macOS tile is the full-bleed 512-square viewBox widened so the body fills 824 of 1024 px. +MAC_VIEWBOX = 'viewBox="-62.136 -62.136 636.272 636.272"' +ICO_SIZES = (16, 20, 24, 32, 40, 48, 64, 128, 256) +# The ICNS slots iconutil writes, and macOS still reads. +ICNS_SLOTS = ( + ("icp4", 16), ("icp5", 32), ("ic11", 32), ("icp6", 64), ("ic12", 64), ("ic07", 128), + ("ic08", 256), ("ic13", 256), ("ic09", 512), ("ic14", 512), ("ic10", 1024), +) +MAC_PNG_SIZES = (16, 32, 64, 128, 256, 512, 1024) +CHROME_NAMES = ("chrome-headless-shell", "chromium", "chromium-browser", "google-chrome", "google-chrome-stable") + + +def die(message): + raise SystemExit(f"nightly-icons: {message}") + + +def renderer_argv(kind): + if kind in ("auto", "resvg"): + found = shutil.which("resvg") + if found: + return ("resvg", found) + if kind == "resvg": + die("resvg not found (brew install resvg / cargo install resvg)") + for name in CHROME_NAMES: + found = shutil.which(name) + if found: + return ("chrome", found) + die("no vector renderer found: install resvg, or a headless Chrome") + + +def render_resvg(resvg, svg_text, size, out): + with tempfile.TemporaryDirectory() as work: + source = Path(work) / "icon.svg" + source.write_text(svg_text) + subprocess.run([resvg, "-w", str(size), "-h", str(size), str(source), str(out)], check=True, stdin=subprocess.DEVNULL) + + +def render_chrome(chrome, svg_text, size, out): + # The SVG's width/height attributes fix the document size; the page is exactly that. + start = svg_text.index("", start) + tag = svg_text[start:end] + for attribute in (' width="512"', ' height="512"'): + tag = tag.replace(attribute, "") + tag = f'{tag} width="{size}" height="{size}"' + page = ( + "" + + svg_text[:start] + tag + svg_text[end:] + + "" + ) + with tempfile.TemporaryDirectory() as work: + document = Path(work) / "icon.html" + document.write_text(page) + subprocess.run( + [chrome, "--headless", "--disable-gpu", "--hide-scrollbars", "--no-first-run", + "--default-background-color=00000000", "--force-device-scale-factor=1", + f"--window-size={size},{size}", f"--screenshot={out}", document.as_uri()], + check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + ) + + +def png_size(data): + if data[:8] != b"\x89PNG\r\n\x1a\n" or data[12:16] != b"IHDR": + die("renderer wrote something that is not a PNG") + return struct.unpack(">II", data[16:24]) + + +def has_alpha(data): + # IHDR colour type 6 is RGBA; a renderer that dropped alpha would flatten the padding. + return data[25] == 6 + + +def pack_ico(pngs): + body = bytearray(struct.pack(" 256: + die(f"ico frames must be square and at most 256 px, got {width}x{height}") + body += struct.pack("I", len(data) + 8) + data + return b"icns" + struct.pack(">I", len(body) + 8) + bytes(body) + + +def mac_svg(svg_text): + if 'viewBox="0 0 512 512"' not in svg_text: + die("gridcraft-nightly.svg must keep the full-bleed 0 0 512 512 viewBox") + return svg_text.replace('viewBox="0 0 512 512"', MAC_VIEWBOX) + + +def digest(path): + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def render_all(kind): + renderer, program = renderer_argv(kind) + svg_text = SVG.read_text() + padded = mac_svg(svg_text) + with tempfile.TemporaryDirectory() as work: + work = Path(work) + + def draw(source, size, name): + if not source.strip(): + die(f"empty SVG for {name}") + out = work / "tile.svg" + out.write_text(source) + (render_resvg if renderer == "resvg" else render_chrome)(program, source, size, work / name) + data = (work / name).read_bytes() + if png_size(data) != (size, size): + die(f"{name}: expected {size}x{size}, got {png_size(data)}") + if not has_alpha(data): + die(f"{name}: the render has no alpha channel") + return data + + # Full-bleed tile: the Linux tar icon (256) and the Windows ICO frames. + tile = {size: draw(svg_text, size, f"tile-{size}.png") for size in sorted({256} | set(ICO_SIZES))} + (ICONS / "gridcraft-nightly.png").write_bytes(tile[256]) + (ICONS / "gridcraft-nightly.ico").write_bytes(pack_ico([tile[size] for size in ICO_SIZES])) + # Padded macOS tile: the 1024 master, the ICNS slots and the runtime Dock render. + mac = {size: draw(padded, size, f"mac-{size}.png") for size in MAC_PNG_SIZES} + (ICONS / "gridcraft-nightly-1024.png").write_bytes(mac[1024]) + (ICONS / "gridcraft-nightly.icns").write_bytes(pack_icns([(kind, mac[size]) for kind, size in ICNS_SLOTS])) + write_provenance(renderer) + + +def write_provenance(renderer): + outputs = ("gridcraft-nightly.png", "gridcraft-nightly-1024.png", "gridcraft-nightly.ico", "gridcraft-nightly.icns") + provenance = { + "title": "GridCraft nightly deep-background icons", + "author": "@skylartaylor", + "license": "MIT OR Apache-2.0", + "inputs": [ + {"path": "assets/app-icon/gridcraft-nightly.svg", "sha256": digest(SVG), "purpose": "vector master for every frame"}, + {"path": "assets/app-icon/gridcraft.svg", "sha256": digest(ICONS / "gridcraft.svg"), "purpose": "stable artwork this is derived from"}, + ], + "method": { + "kind": "vector render of the project-owned artwork with only its field colour deepened", + "stable_field": "#1f9d55", + "nightly_field": "#14532d", + "unchanged": "ink #0b0b0c, paper #efe9dc, every path, stroke width and the 824/1024 Mac padding", + "sizes": "each frame rendered at its own size, never upscaled", + "renderer": renderer, + "generator": "packaging/nightly-icons.py", + }, + "outputs": {name: digest(ICONS / name) for name in outputs}, + "ico_frame_sizes": list(ICO_SIZES), + "icns_png_slots": {kind: size for kind, size in ICNS_SLOTS}, + } + (ICONS / "nightly-provenance.json").write_text(json.dumps(provenance, indent=2) + "\n") + + +def check(): + provenance = json.loads((ICONS / "nightly-provenance.json").read_text()) + ok = True + for name, expected in provenance["outputs"].items(): + actual = digest(ICONS / name) + if actual != expected: + print(f"mismatch: assets/app-icon/{name} is {actual}, provenance says {expected}", file=sys.stderr) + ok = False + ico = (ICONS / "gridcraft-nightly.ico").read_bytes() + count = struct.unpack("I", icns[4:8])[0] != len(icns): + print("mismatch: the ICNS header does not cover the file", file=sys.stderr) + ok = False + return 0 if ok else 1 + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--renderer", choices=("auto", "resvg", "chrome"), default="auto") + parser.add_argument("--check", action="store_true") + args = parser.parse_args() + if args.check: + return check() + render_all(args.renderer) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/packaging/nightly-release-tests.py b/packaging/nightly-release-tests.py new file mode 100755 index 0000000000..ca9301cbfd --- /dev/null +++ b/packaging/nightly-release-tests.py @@ -0,0 +1,464 @@ +#!/usr/bin/env python3 +"""Nightly source-contract regression tests for GridCraft; local checks, not live API/crypto evidence.""" +import base64 +import copy +import hashlib +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"] + +# The Linux leg's public release key, as the protected release checkout must carry it. +LINUX_KEY = ROOT / ".github/nightly-linux-signing-key.asc" + + +def openpgp_primary_fingerprints(armored): + """Return the v4 fingerprint of every primary public-key packet in one armored block. + + A narrow reader for the committed public key, not a general OpenPGP parser: anything other + than one well-formed public-key block, or any secret material, refuses. + """ + lines = armored.strip().splitlines() + if lines[:1] != ["-----BEGIN PGP PUBLIC KEY BLOCK-----"] or lines[-1:] != ["-----END PGP PUBLIC KEY BLOCK-----"]: + raise ValueError("exactly one armored public key block is required") + body = lines[1:-1] + if "" not in body: + raise ValueError("armor header separator missing") + body = body[body.index("") + 1:] + if not body or not body[-1].startswith("="): + raise ValueError("armor checksum missing") + data = base64.b64decode("".join(body[:-1]), validate=True) + fingerprints, offset = [], 0 + while offset < len(data): + header = data[offset] + if not header & 0x80: + raise ValueError("invalid packet header") + if header & 0x40: + tag, offset = header & 0x3F, offset + 1 + first = data[offset] + if first < 192: + length, offset = first, offset + 1 + elif first < 224: + length, offset = ((first - 192) << 8) + data[offset + 1] + 192, offset + 2 + elif first == 255: + length, offset = int.from_bytes(data[offset + 1:offset + 5], "big"), offset + 5 + else: + raise ValueError("partial packet lengths are not a public key") + else: + tag, kind, offset = (header >> 2) & 0x0F, header & 0x03, offset + 1 + if kind == 3: + raise ValueError("indeterminate packet length") + size = 1 << kind + length, offset = int.from_bytes(data[offset:offset + size], "big"), offset + size + packet = data[offset:offset + length] + if len(packet) != length: + raise ValueError("truncated packet") + if tag == 5 or tag == 7: + raise ValueError("secret key material must never be committed") + if tag == 6: + if packet[:1] != b"\x04": + raise ValueError("only v4 primary keys are expected") + fingerprints.append(hashlib.sha1(b"\x99" + length.to_bytes(2, "big") + packet).hexdigest().upper()) + offset += length + return fingerprints + + +def 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": "gridcraft-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; a narrow source guard, not YAML.""" + rows = re.findall(r"(?m)^ platforms: (.*)$", source) + if len(rows) != 1: + raise ValueError("exactly one producer platform list is required") + literal = re.fullmatch(r"'(\[[^']*\])'", rows[0]) + if literal is None: + raise ValueError("the platform list must be one single-quoted literal") + platforms = json.loads(literal[1]) + if not isinstance(platforms, list) or json.dumps(platforms, separators=(",", ":")) != literal[1]: + raise ValueError("the platform list must be compact JSON") + if len(set(platforms)) != len(platforms) or not set(platforms) <= set(NIGHTLY_PLATFORMS): + raise ValueError("platforms must be distinct known nightly targets") + if "windows-x86_64" not in platforms: + raise ValueError("the Windows row stays in the producer") + return platforms + + +def reviewed_manual_actors(caller_source, policy): + """The one reviewed manual-actor list, identical in the producer caller and the policy.""" + rows = re.findall(r"(?m)^ manual-actors: '(\[[^']*\])'$", caller_source) + if len(rows) != 1: + raise ValueError("exactly one literal manual-actors list is required") + caller = json.loads(rows[0]) + if caller != policy["manual_actors"]: + raise ValueError("caller and policy must grant the same actors in the same order") + if caller != RELEASE_MANAGERS: + raise ValueError("manual actors must be exactly the reviewed release managers") + if caller != sorted(caller, key=str.lower) or len({login.lower() for login in caller}) != len(caller): + raise ValueError("manual actors must be distinct and sorted case-insensitively") + if set(caller) & {login for login in policy["automatic_signer_actors"]}: + raise ValueError("manual and automatic actors overlap") + return caller + + +def caller_pin(name): + return re.findall(r"(?m)^ tooling-revision: ([0-9a-f]{40})$", (ROOT / ".github/workflows" / name).read_text())[0] + + +class TrustedSourcePreparation(unittest.TestCase): + def test_one_producer_and_one_signer_job_carry_every_platform(self): + for name, job in (("nightly.yml", "unsigned"), ("nightly-sign.yml", "release")): + jobs = (ROOT / ".github/workflows" / name).read_text().split("\njobs:\n", 1)[1] + with self.subTest(workflow=name): + self.assertEqual(re.findall(r"(?m)^ ([^\s#][^:]*):", jobs), [job], + "a platform is a list entry, not a separately activatable job") + signer = (ROOT / ".github/workflows/nightly-sign.yml").read_text() + self.assertNotRegex(signer, r"(?m)^\s*platforms?:", "the release policy, not the caller, admits platforms") + + def test_malformed_or_narrowed_platform_lists_are_rejected(self): + source = (ROOT / ".github/workflows/nightly.yml").read_text() + current = "platforms: '[\"windows-x86_64\",\"linux-x86_64\",\"macos-aarch64\"]'" + self.assertIn(current, source) + for new in ("platforms: '[\"linux-x86_64\"]'", + "platforms: '[\"linux-x86_64\",\"macos-aarch64\"]'", + "platforms: '[\"windows-x86_64\",\"linux-x86_64\",\"linux-x86_64\"]'", + "platforms: '[\"windows-x86_64\",\"macos-x86_64\"]'", + "platforms: '[\"windows-x86_64\",\"linux-arm64\"]'", + "platforms: '[\"windows-x86_64\", \"linux-x86_64\"]'", + "platforms: [\"windows-x86_64\",\"linux-x86_64\"]", + "platforms: ${{ vars.NIGHTLY_PLATFORMS }}", + "platforms: '{\"windows-x86_64\":1}'", + current + "\n " + current): + with self.subTest(change=new), self.assertRaises(ValueError): + producer_platforms(source.replace(current, new)) + with self.assertRaises(ValueError): + producer_platforms(source.replace(" " + current + "\n", "")) + + def test_continuation_lines_of_any_scalar_form_reach_the_guard_checks(self): + for name, 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: false\n queue: max"), + ("cancel-in-progress: false", "cancel-in-progress: true"), + ("cancel-in-progress: false", "cancel-in-progress: ${{ github.event_name == 'push' }}"), + ("cancel-in-progress: false\n", ""), + ("group: gridcraft-nightly-release", "group: ${{ github.run_id }}"), + ("group: gridcraft-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_sonar_classifies_only_the_exact_packaging_fixture_runners(self): + source = (ROOT / "sonar-project.properties").read_text() + self.assertEqual(re.findall(r"(?m)^sonar.sources=(.*)$", source), ["."]) + self.assertEqual(re.findall(r"(?m)^sonar.tests=(.*)$", source), ["packaging"]) + inclusions = re.findall(r"(?m)^sonar.test.inclusions=(.*)$", source) + self.assertEqual(len(inclusions), 1) + entries = inclusions[0].split(",") + expected = {"packaging/nightly-tests.py", "packaging/nightly-archive-tests.py", + "packaging/linux/nightly-linux-launch-tests.py", + "packaging/macos/nightly_plist_tests.py", "packaging/macos/nightly_sign_tests.py", + "packaging/windows/nightly-package-tests.ps1", + "packaging/windows/nightly-signing-tests.ps1", "packaging/nightly-release-tests.py"} + self.assertEqual(set(entries), expected, "classify exact fixtures, never production helpers or wildcard scope") + self.assertEqual(len(entries), len(expected), "duplicate fixture classification") + + def test_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) + + def test_both_callers_use_one_shared_pin_in_uses_and_tooling_revision(self): + pins = set() + for name, callee in (("nightly.yml", "nightly-unsigned.yml"), ("nightly-sign.yml", "nightly-release.yml")): + source = (ROOT / ".github/workflows" / name).read_text() + uses = re.findall(r"(?m)^ uses: storytold/craft-common-actions/\.github/workflows/" + + re.escape(callee) + r"@(\S+)$", source) + tooling = re.findall(r"(?m)^ tooling-revision: (\S+)$", source) + with self.subTest(workflow=name): + self.assertEqual(len(uses), 1) + self.assertEqual(tooling, uses, "the defining workflow SHA and tooling input must match") + pins.update(uses) + self.assertEqual(len(pins), 1, "producer and signer must pin the same shared commit") + self.assertRegex(pins.pop(), r"^[0-9a-f]{40}$", "pin a full immutable commit, never a branch or placeholder") + + +class NightlyEnabledCallers(unittest.TestCase): + """Producer and signer run only in their exact context, for the reviewed manual actor.""" + + GUARDS = { + "nightly.yml": "github.repository == 'storytold/gridcraft' && github.ref == 'refs/heads/main' && " + "github.ref_type == 'branch' && (github.event_name == 'schedule' || " + "github.event_name == 'workflow_dispatch')", + "nightly-sign.yml": "github.repository == 'storytold/gridcraft' && github.event_name == 'workflow_dispatch' && " + "github.ref == 'refs/heads/release' && github.ref_type == 'branch'", + } + + def test_enabled_jobs_keep_exact_context_guards(self): + for name, expected in self.GUARDS.items(): + jobs = (ROOT / ".github/workflows" / name).read_text().split("\njobs:\n", 1)[1] + guards = job_conditions(jobs) + with self.subTest(workflow=name): + self.assertEqual(len(guards), 1) + indicator, expression = guards[0] + self.assertEqual(indicator, ">-") + self.assertEqual(" ".join(expression.split()), expected, "guards may only change with review") + + def test_manual_actors_are_the_release_managers_in_caller_and_policy(self): + source = (ROOT / ".github/workflows/nightly.yml").read_text() + policy = json.loads(INSTALLED_POLICY.read_text()) + self.assertEqual(reviewed_manual_actors(source, policy), RELEASE_MANAGERS) + self.assertEqual(policy["automatic_signer_actors"], [], "no automatic signer without a schedule") + + def test_an_actor_outside_the_release_managers_is_refused(self): + source = (ROOT / ".github/workflows/nightly.yml").read_text() + policy = json.loads(INSTALLED_POLICY.read_text()) + caller = json.dumps(RELEASE_MANAGERS, separators=(",", ":")) + widened = sorted(RELEASE_MANAGERS + ["echelon-robot"], key=str.lower) + for change in ("caller", "policy", "both", "order", "case"): + mutated_source, mutated_policy = source, copy.deepcopy(policy) + if change in ("caller", "both"): + mutated_source = source.replace(caller, json.dumps(widened, separators=(",", ":"))) + if change in ("policy", "both"): + mutated_policy["manual_actors"] = widened + if change == "order": + mutated_policy["manual_actors"] = list(reversed(RELEASE_MANAGERS)) + if change == "case": + mutated_policy["manual_actors"] = [login.lower() for login in RELEASE_MANAGERS] + with self.subTest(change=change), self.assertRaises(ValueError): + reviewed_manual_actors(mutated_source, mutated_policy) + + +def push_block(source): + """The whole `push:` mapping, blank lines and nested keys included. + + A blank line does not end a YAML mapping, so the block is delimited by indentation rather than + by contiguous non-empty lines; a path filter after a blank line stays visible to the check. + """ + lines = source.splitlines() + for index, line in enumerate(lines): + if re.fullmatch(r" push:.*", line): + block = [] + for follow in lines[index + 1:]: + if follow.strip() and not follow.startswith(" "): + break + block.append(follow) + return "\n".join(block) + return None + + +class NightlyInstalledPolicy(unittest.TestCase): + """The installed v3 policy matches the callers, the repository and its documented sources.""" + + def setUp(self): + self.assertFalse(INSTALLED_POLICY.is_symlink()) + self.policy = json.loads(INSTALLED_POLICY.read_text()) + + def test_exact_v3_fields_and_repository_identity(self): + expected = {"schema", "repository", "repository_id", "producer_workflow_id", + "producer_workflow_path", "producer_tooling_revision", "producer_workflow_ref", + "signer_workflow_path", "signer_tooling_revision", "release_branch", "manual_actors", + "automatic_signer_actors", "max_age_seconds", "candidate_policy", + "max_artifact_bytes", "platforms"} + self.assertEqual(set(self.policy), expected) + self.assertEqual(self.policy["schema"], "craft-nightly-release-policy/v3") + self.assertEqual(self.policy["repository"], "storytold/gridcraft") + self.assertEqual(self.policy["release_branch"], "release") + self.assertIs(type(self.policy["repository_id"]), int) + self.assertGreater(self.policy["repository_id"], 0) + # producer_workflow_id is null until nightly.yml is registered on main; once set, must be a positive int. + if self.policy["producer_workflow_id"] is not None: + self.assertIs(type(self.policy["producer_workflow_id"]), int) + self.assertGreater(self.policy["producer_workflow_id"], 0) + self.assertNotEqual(self.policy["producer_workflow_id"], + self.policy["candidate_policy"]["required_workflows"][0]["workflow_id"], + "the producer is not its own quality workflow") + + def test_paths_and_tooling_match_the_callers(self): + pin = caller_pin("nightly.yml") + self.assertEqual(caller_pin("nightly-sign.yml"), pin) + self.assertEqual(self.policy["producer_workflow_path"], ".github/workflows/nightly.yml") + self.assertEqual(self.policy["signer_workflow_path"], ".github/workflows/nightly-sign.yml") + self.assertEqual(self.policy["producer_tooling_revision"], pin) + self.assertEqual(self.policy["signer_tooling_revision"], pin) + self.assertEqual(self.policy["producer_workflow_ref"], + "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@" + pin) + + def test_platforms_and_trust_anchors_match_producer(self): + built = producer_platforms((ROOT / ".github/workflows/nightly.yml").read_text()) + self.assertEqual(built, list(NIGHTLY_PLATFORMS)) + self.assertEqual(set(self.policy["platforms"]), set(built)) + for platform, (field, value) in NIGHTLY_TRUST.items(): + row = self.policy["platforms"][platform] + with self.subTest(platform=platform): + self.assertEqual(set(row), {"unsigned_artifact_name", "trust"}) + self.assertEqual(row["unsigned_artifact_name"], f"nightly-unsigned-{platform}") + self.assertEqual(row["trust"], {field: value}) + + def test_committed_linux_key_is_exactly_the_one_the_policy_trusts(self): + self.assertFalse(LINUX_KEY.is_symlink(), "the key file must be a regular committed file") + armored = LINUX_KEY.read_text(encoding="ascii") + self.assertEqual(armored.count("-----BEGIN PGP"), 1, "exactly one armored block") + self.assertEqual(openpgp_primary_fingerprints(armored), + [self.policy["platforms"]["linux-x86_64"]["trust"]["fingerprint"]], + "exactly one primary key, and it is the release key the policy trusts") + + def test_key_reader_refuses_secret_or_extra_material(self): + armored = LINUX_KEY.read_text(encoding="ascii") + for change in (armored.replace("PUBLIC KEY BLOCK", "PRIVATE KEY BLOCK"), + armored.replace("-----END PGP PUBLIC KEY BLOCK-----\n", ""), + "Comment: extra\n" + armored): + with self.subTest(change=change[:40]), self.assertRaises(ValueError): + openpgp_primary_fingerprints(change) + + def test_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/gridcraft", "main")) + self.assertTrue(isinstance(candidate["epoch"], str) and 0 < len(candidate["epoch"]) <= 128) + rows = candidate["required_workflows"] + self.assertTrue(rows) + for row in rows: + with self.subTest(workflow=row["workflow_path"]): + self.assertEqual(set(row), {"workflow_id", "workflow_path", "jobs"}) + self.assertIs(type(row["workflow_id"]), int) + self.assertNotEqual(row["workflow_path"], self.policy["producer_workflow_path"]) + source = (ROOT / row["workflow_path"]).read_text() + push = push_block(source) + self.assertIsNotNone(push, "a required workflow must run on main pushes") + self.assertIn("branches: [main]", push) + self.assertNotRegex(push, r"(?m)^\s+paths(?:-ignore)?:", "a path filter would leave candidates without a run") + names = [job["name"] for job in row["jobs"]] + self.assertEqual(len(names), len(set(names))) + for job in row["jobs"]: + self.assertEqual(set(job), {"name", "app_id", "applicability"}) + self.assertEqual((job["app_id"], job["applicability"]), (15368, "required")) + + def test_a_path_filter_after_a_blank_line_is_still_rejected(self): + workflow = "on:\n push:\n branches: [main]\n\n paths: ['src/**']\n workflow_dispatch: {}\n" + block = push_block(workflow) + self.assertIsNotNone(block) + self.assertIn("branches: [main]", block) + self.assertRegex(block, r"(?m)^\s+paths(?:-ignore)?:") + for ignored in ("paths: ['src/**']", "paths-ignore: ['docs/**']"): + with self.subTest(ignored=ignored): + variant = workflow.replace(ignored.split(":")[0] + ": ['src/**']", ignored) + self.assertRegex(push_block(variant), r"(?m)^\s+paths(?:-ignore)?:", + "a quoted or unquoted filter must not hide behind a blank line") + + def test_sonar_identity_and_reviewed_scope(self): + sonar = self.policy["candidate_policy"]["sonar"] + properties = dict(line.split("=", 1) for line in (ROOT / "sonar-project.properties").read_text().splitlines() + if line and not line.startswith("#")) + self.assertEqual(sonar["organization"], properties["sonar.organization"]) + self.assertEqual(sonar["project"], properties["sonar.projectKey"]) + self.assertEqual((sonar["app_id"], sonar["check_name"]), (12526, "SonarCloud Code Analysis")) + self.assertEqual(sonar["details_url"], "https://sonarcloud.io/dashboard?id=" + sonar["project"] + "&branch=main") + accepted = {"bugs": "BUG", "vulnerabilities": "VULNERABILITY", "code_smells": "CODE_SMELL", + "security_rating": "VULNERABILITY", "new_security_rating": "VULNERABILITY"} + self.assertEqual({accepted[c["metric"]] for c in sonar["accepted_conditions"]}, set(sonar["issue_types"])) + metrics = [c["metric"] for c in sonar["accepted_conditions"] + sonar["required_conditions"]] + self.assertEqual(len(metrics), len(set(metrics))) + keys = [item["key"] for item in sonar["debt"]] + self.assertEqual(len(keys), len(set(keys))) + for item in sonar["debt"]: + with self.subTest(issue=item["key"]): + self.assertEqual(set(item), {"key", "rule", "component", "type", "severity", "hash"}) + self.assertTrue(item["component"].startswith(sonar["project"] + ":")) + self.assertIn(item["type"], sonar["issue_types"]) + self.assertRegex(item["hash"], r"^[0-9a-f]{32}$") + + +if __name__ == "__main__": + unittest.main(verbosity=2) diff --git a/packaging/nightly-tests.py b/packaging/nightly-tests.py new file mode 100755 index 0000000000..684239f495 --- /dev/null +++ b/packaging/nightly-tests.py @@ -0,0 +1,26 @@ +#!/usr/bin/env python3 +"""Run the synthetic nightly packaging suites together; no app build, no signing, no 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 ( + ("gridcraft_archive_suite", "nightly-archive-tests.py"), + ("gridcraft_plist_suite", "macos/nightly_plist_tests.py"), + ("gridcraft_release_dispatch_suite", "nightly-release-tests.py"), + ("gridcraft_mac_sign_suite", "macos/nightly_sign_tests.py"), + ("gridcraft_linux_launch_suite", "linux/nightly-linux-launch-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()) diff --git a/packaging/nightly_paths.py b/packaging/nightly_paths.py new file mode 100644 index 0000000000..792198589e --- /dev/null +++ b/packaging/nightly_paths.py @@ -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) diff --git a/packaging/windows/nightly-package-tests.ps1 b/packaging/windows/nightly-package-tests.ps1 new file mode 100644 index 0000000000..15c6ac9964 --- /dev/null +++ b/packaging/windows/nightly-package-tests.ps1 @@ -0,0 +1,95 @@ +param([Parameter(Mandatory=$true)][string] $FixtureRoot) +. (Join-Path $PSScriptRoot 'nightly.ps1') -FunctionsOnly +function Assert([bool] $Value, [string] $Message) { if (-not $Value) { throw $Message } } +$spec = Get-NightlyArchiveSpec '0.23.1-nightly.20261120.17.1.gabcdef012345' 'x64' +Assert ($spec.Archive -eq 'gridcraft-0.23.1-nightly.20261120.17.1.gabcdef012345-windows-x86_64-nightly.zip') 'wrong nightly artifact name' +Assert ($spec.Executables.Count -eq 1 -and $spec.Executables[0] -eq 'gridcraft.exe') 'nightly must not ship the unqualified CLI' +Assert ($spec.AppId -eq 'ai.storyteller.gridcraft.nightly-v1') 'nightly identity is not distinct' +foreach ($arch in @('x86', 'arm64')) { + $refused = $false + try { Get-NightlyArchiveSpec '0.23.1' $arch | Out-Null } catch { $refused = $true } + Assert $refused 'unsupported target was accepted' +} +foreach ($bad in @('', '0.23.1', '../other', '0.23.1/elsewhere')) { + $refused = $false + try { Get-NightlyArchiveSpec $bad 'x64' | Out-Null } catch { $refused = $true } + Assert $refused 'unsafe artifact version was accepted' +} +Assert-NightlyFlavor 'GridCraft Nightly' 'GridCraft 0.23.1-nightly.20261120.17.1.gabcdef012345 (nightly-v1)' '0.23.1-nightly.20261120.17.1.gabcdef012345' +foreach ($pair in @(@('GridCraft', 'GridCraft 0.23.1 (nightly-v1)'), @('GridCraft Nightly', 'GridCraft 0.23.1'))) { + $refused = $false + try { Assert-NightlyFlavor $pair[0] $pair[1] '0.23.1-nightly.20261120.17.1.gabcdef012345' } catch { $refused = $true } + Assert $refused 'stable or mismatched build flavor was accepted' +} +$sha = 'abcdef0123456789abcdef0123456789abcdef01' +$good = '0.23.1-nightly.20261120.17.1.gabcdef012345' +Assert-NightlySource $good $sha '2026-11-20' $sha '' +$cases = @( + @('missing commit', $good, '', '2026-11-20', $sha, ''), + @('short commit', $good, 'abcdef012345', '2026-11-20', $sha, ''), + @('uppercase commit', $good, $sha.ToUpper(), '2026-11-20', $sha.ToUpper(), ''), + @('version names another commit', '0.23.1-nightly.20261120.17.1.g000000000000', $sha, '2026-11-20', $sha, ''), + @('missing date', $good, $sha, '', $sha, ''), + @('date differs from version', $good, $sha, '2026-11-21', $sha, ''), + @('other commit checked out', $good, $sha, '2026-11-20', ('0' * 40), ''), + @('dirty tree', $good, $sha, '2026-11-20', $sha, ' M apps/gridcraft/src/main.rs') +) +foreach ($case in $cases) { + $refused = $false + try { Assert-NightlySource $case[1] $case[2] $case[3] $case[4] $case[5] } catch { $refused = $true } + Assert $refused "source identity accepted: $($case[0])" +} +Write-Output 'nightly packaging spec, target/version refusal, source identity and flavor-binding tests passed' + +# Exercise the SAME production notice copier with the real repository layout, then inspect a ZIP. +if (-not $FixtureRoot -or -not [IO.Path]::IsPathRooted($FixtureRoot)) { throw 'supply an owned absolute -FixtureRoot for the notices/ZIP regression' } +$testRoot = Join-Path $FixtureRoot ("nightly-notices-" + [Guid]::NewGuid().ToString('N')) +try { + $repo = Join-Path $testRoot 'app' + $fontRepo = Join-Path $testRoot 'craft-fonts' + $family = Join-Path $fontRepo 'fonts\ExampleFamily' + $stage = Join-Path $testRoot 'stage' + New-Item -ItemType Directory -Force -Path $repo, $family, $stage | Out-Null + $rootNames = @('README.md', 'LICENSE', 'LICENSE-MIT', 'LICENSE-APACHE', 'NOTICE', 'ATTRIBUTION.md') + foreach ($name in $rootNames) { Set-Content -LiteralPath (Join-Path $repo $name) -Value "root-notice-$name" } + Set-Content -LiteralPath (Join-Path $family 'OFL.txt') -Value 'font-notice-example' + Copy-NightlyNotices $repo $fontRepo $stage + foreach ($name in @($rootNames) + @('OFL-ExampleFamily.txt')) { + Assert (Test-Path -LiteralPath (Join-Path $stage $name)) "missing staged notice $name" + } + $zip = Join-Path $testRoot 'notices.zip' + Compress-Archive -Path (Join-Path $stage '*') -DestinationPath $zip + $archive = [IO.Compression.ZipFile]::OpenRead($zip) + try { + $names = @($archive.Entries | ForEach-Object { $_.FullName }) + foreach ($name in @($rootNames) + @('OFL-ExampleFamily.txt')) { Assert ($name -in $names) "missing archived notice $name" } + foreach ($forbidden in @('portable.txt', 'gridcraft-cli.exe')) { Assert ($forbidden -notin $names) "unexpected payload $forbidden" } + $entry = $archive.GetEntry('OFL-ExampleFamily.txt') + $reader = [IO.StreamReader]::new($entry.Open()) + try { Assert ($reader.ReadToEnd().Contains('font-notice-example')) 'wrong font license bytes in ZIP' } finally { $reader.Dispose() } + } finally { $archive.Dispose() } +} finally { + if (Test-Path -LiteralPath $testRoot) { Remove-Item -LiteralPath $testRoot -Recurse -Force } +} +Write-Output 'nightly mock-repository root and font notices are present in stage and ZIP' + +# The source state comes from git itself: the checked-out commit, then a dirty tree. +$gitRoot = Join-Path $FixtureRoot ("nightly-source-" + [Guid]::NewGuid().ToString('N')) +try { + New-Item -ItemType Directory -Force -Path $gitRoot | Out-Null + git -C $gitRoot init -q; git -C $gitRoot -c user.name=fixture -c user.email=fixture@invalid commit -q --allow-empty -m fixture + if ($LASTEXITCODE -ne 0) { throw 'cannot create the git fixture' } + $head = (git -C $gitRoot rev-parse HEAD).Trim() + $state = Get-NightlySourceState $gitRoot + Assert ($state.Head -ceq $head -and -not $state.Status) 'clean checkout not reported as clean at HEAD' + $version = '0.23.1-nightly.20261120.17.1.g' + $head.Substring(0, 12) + Assert-NightlySource $version $head '2026-11-20' $state.Head $state.Status + Set-Content -LiteralPath (Join-Path $gitRoot 'untracked.txt') -Value 'dirty' + $state = Get-NightlySourceState $gitRoot + $refused = $false + try { Assert-NightlySource $version $head '2026-11-20' $state.Head $state.Status } catch { $refused = $true } + Assert $refused 'a dirty checkout was accepted' +} finally { + if (Test-Path -LiteralPath $gitRoot) { Remove-Item -LiteralPath $gitRoot -Recurse -Force } +} +Write-Output 'nightly source state is read from git and a dirty checkout is refused' diff --git a/packaging/windows/nightly-signing-tests.ps1 b/packaging/windows/nightly-signing-tests.ps1 new file mode 100644 index 0000000000..d45a0f83d6 --- /dev/null +++ b/packaging/windows/nightly-signing-tests.ps1 @@ -0,0 +1,83 @@ +param( + [Parameter(Mandatory=$true)][string] $FixtureRoot, + [string] $PackagingRoot = $PSScriptRoot, + [switch] $PhaseGuardOnly +) +$ErrorActionPreference = 'Stop' +. (Join-Path $PackagingRoot 'nightly.ps1') -FunctionsOnly +$sign = Join-Path $PackagingRoot 'sign.ps1' +$names = @('WINDOWS_CERTIFICATE','WINDOWS_CERTIFICATE_PASSWORD','AZURE_TENANT_ID','AZURE_CLIENT_ID','AZURE_CLIENT_SECRET','AZURE_SIGNING_ENDPOINT','AZURE_SIGNING_ACCOUNT','AZURE_CERT_PROFILE') +function Clear-SigningFixtures { foreach ($name in $names) { [Environment]::SetEnvironmentVariable($name, $null) } } +function Assert-Policy([bool] $Value, [string] $Message) { if (-not $Value) { throw $Message } } +function Invoke-Refusal([scriptblock] $Operation, [string] $Message) { + $errorText = '' + try { & $Operation | Out-Null } catch { $errorText = $_.Exception.Message } + Assert-Policy ($errorText.Contains($Message)) "expected refusal: $Message; got: $errorText" +} +function global:cargo { $global:SigningFixtureCargoCalls++; throw 'FIXTURE_COMPILER_BOUNDARY' } +function global:Invoke-WebRequest { throw 'fixture must not perform signing downloads' } +$global:SigningFixtureCargoCalls = 0 +if (-not [IO.Path]::IsPathRooted($FixtureRoot)) { throw 'use an owned absolute FixtureRoot' } +$root = Join-Path $FixtureRoot ('signing-policy-' + [Guid]::NewGuid().ToString('N')) +New-Item -ItemType Directory -Path $root | Out-Null +$version = '0.23.1-nightly.20261121.12345.1.gaaaaaaaaaaaa' +$env:GRIDCRAFT_VERSION = $version +function Invoke-Build([switch] $BuildOnly) { + $arguments = @{Arch='x64';Version=$version;Target='x86_64-pc-windows-msvc';TargetDir=$root;Dist=(Join-Path $root 'dist')} + if ($BuildOnly) { $arguments.BuildOnly = $true } + & (Join-Path $PackagingRoot 'nightly.ps1') @arguments +} +try { + Clear-SigningFixtures + Invoke-Refusal { Invoke-Build } 'requires -BuildOnly' + Assert-Policy ($global:SigningFixtureCargoCalls -eq 0) 'default mode invoked Cargo' + Write-Output 'PASS: explicit-build-phase-required' + if ($PhaseGuardOnly) { return } + + foreach ($name in @('WINDOWS_CERTIFICATE','WINDOWS_CERTIFICATE_PASSWORD','AZURE_CLIENT_SECRET')) { + Clear-SigningFixtures + [Environment]::SetEnvironmentVariable($name, 'generated-fixture-not-a-secret') + Invoke-Refusal { Invoke-Build -BuildOnly } 'Compilation must not receive signing credentials' + Assert-Policy ($global:SigningFixtureCargoCalls -eq 0) 'key-bearing compilation reached Cargo' + } + Write-Output 'PASS: credentials-rejected-before-compilation' + + Clear-SigningFixtures + Invoke-Refusal { Invoke-Build -BuildOnly } 'FIXTURE_COMPILER_BOUNDARY' + Assert-Policy ($global:SigningFixtureCargoCalls -eq 1) 'clean compilation did not reach the mocked compiler boundary' + Assert-Policy (-not (Test-Path (Join-Path $root 'dist'))) 'mocked compilation produced an artifact' + Write-Output 'PASS: secret-free-build-reaches-only-mocked-boundary' + + Clear-SigningFixtures + Invoke-Refusal { & $sign -Required -CheckOnly } 'Nightly signing is required' + $env:AZURE_CLIENT_SECRET = 'generated-partial-fixture' + Invoke-Refusal { & $sign -Required -CheckOnly } 'Nightly signing is required' + Write-Output 'PASS: required-signer-refuses-missing-and-partial-configuration' + + Clear-SigningFixtures + $env:WINDOWS_CERTIFICATE = 'generated-presence-fixture-not-a-certificate' + & $sign -Required -CheckOnly + Clear-SigningFixtures + foreach ($name in $names | Where-Object { $_.StartsWith('AZURE_') }) { [Environment]::SetEnvironmentVariable($name, 'generated-presence-fixture') } + & $sign -Required -CheckOnly + Clear-SigningFixtures + Write-Output 'PASS: supported-configuration-presence-without-signing' + + # Load the policy function without signing. These objects are not crypto evidence. + . $sign -CheckOnly + foreach ($value in @($null, [pscustomobject]@{Status='NotSigned';SignerCertificate='fixture'}, [pscustomobject]@{Status='HashMismatch';SignerCertificate='fixture'}, [pscustomobject]@{Status='Valid';SignerCertificate=$null})) { + Invoke-Refusal { Assert-AuthenticodeSignature $value } 'valid Authenticode signature' + } + Assert-AuthenticodeSignature ([pscustomobject]@{Status='Valid';SignerCertificate='generated-public-certificate-placeholder'}) + Write-Output 'PASS: required-signature-policy-rejects-invalid-or-missing-signer' + + $file = Join-Path $root 'owned-sentinel.exe' + [IO.File]::WriteAllText($file, 'generated sentinel, not a real executable') + $before = (Get-FileHash -LiteralPath $file -Algorithm SHA256).Hash + & $sign -Files $file + Assert-Policy ((Get-FileHash -LiteralPath $file -Algorithm SHA256).Hash -ceq $before) 'optional stable policy changed unsigned bytes' + Write-Output 'PASS: stable-optional-policy-preserves-owned-bytes' +} finally { + Clear-SigningFixtures + Remove-Item -LiteralPath $root -Recurse -Force +} diff --git a/packaging/windows/nightly.ps1 b/packaging/windows/nightly.ps1 new file mode 100644 index 0000000000..1d2312d9c3 --- /dev/null +++ b/packaging/windows/nightly.ps1 @@ -0,0 +1,133 @@ +<# First nightly target only: Windows x86_64 GUI ZIP. No MSI, CLI, portable marker or association registration. #> +param( + [string] $Arch = 'x64', + [string] $Version, + [string] $Target, + [string] $TargetDir, + [string] $Dist, + [switch] $SkipBuild, + [switch] $BuildOnly, + [switch] $FunctionsOnly +) +$ErrorActionPreference = 'Stop' + +function Get-NightlyArchiveSpec([string] $Version, [string] $Arch) { + if ($Arch -ne 'x64') { throw 'nightly-v1 supports only Windows x86_64' } + if (-not $Version -or $Version -cnotmatch '^\d+\.\d+\.\d+-nightly\.\d{8}\.\d+\.\d+\.g[0-9a-f]{12}\z') { throw 'invalid nightly artifact version' } + return @{ + Archive = "gridcraft-$Version-windows-x86_64-nightly.zip" + UnsignedArchive = "gridcraft-$Version-windows-x86_64-nightly.unsigned.zip" + Executables = @('gridcraft.exe') + Channel = 'nightly-v1' + AppId = 'ai.storyteller.gridcraft.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 (GRIDCRAFT_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 (GRIDCRAFT_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 'GridCraft Nightly' -or $VersionOutput -cne "GridCraft $ExpectedVersion (nightly-v1)") { + throw 'the executable is not the compiled nightly-v1 flavor' + } +} + + +function Copy-NightlyNotices([string] $RepositoryRoot, [string] $FontRepository, [string] $Destination) { + foreach ($name in 'README.md', 'LICENSE', 'LICENSE-MIT', 'LICENSE-APACHE', 'NOTICE', 'ATTRIBUTION.md') { + $source = Join-Path $RepositoryRoot $name + if (Test-Path -LiteralPath $source) { Copy-Item -LiteralPath $source -Destination $Destination } + } + if ($FontRepository) { + $fonts = Join-Path $FontRepository 'fonts' + if (-not (Test-Path -LiteralPath $fonts -PathType Container)) { throw 'CRAFT_FONTS_DIR has no fonts directory for the bundled notices' } + foreach ($family in Get-ChildItem -LiteralPath $fonts -Directory) { + $license = Join-Path $family.FullName 'OFL.txt' + if (Test-Path -LiteralPath $license) { Copy-Item -LiteralPath $license -Destination (Join-Path $Destination "OFL-$($family.Name).txt") } + } + } +} + +if ($FunctionsOnly) { return } +if (-not $env:GRIDCRAFT_VERSION -or $Version -cne $env:GRIDCRAFT_VERSION) { throw 'nightly-v1 requires explicit GRIDCRAFT_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:GRIDCRAFT_BUILD_SHA $env:GRIDCRAFT_BUILD_DATE $Source.Head $Source.Status +# build.rs reads GRIDCRAFT_BUILD_CHANNEL and GRIDCRAFT_VERSION from the environment: that pair is +# what makes this executable the nightly flavor with the prepared identity, and no other. +$oldChannel = $env:GRIDCRAFT_BUILD_CHANNEL +try { + $env:GRIDCRAFT_BUILD_CHANNEL = 'nightly-v1' + $env:GRIDCRAFT_REQUIRE_WINRES = '1' + $env:CARGO_TARGET_X86_64_PC_WINDOWS_MSVC_RUSTFLAGS = '-C target-feature=+crt-static' + # Into the directory the archive steps read (`$TargetDir`), not Cargo's default. + cargo build --release --locked -p gridcraft --target $Target --target-dir $TargetDir + if ($LASTEXITCODE -ne 0) { throw "nightly cargo build failed: $LASTEXITCODE" } +} finally { + $env:GRIDCRAFT_BUILD_CHANNEL = $oldChannel +} +$Source = Get-NightlySourceState $Root +try { Assert-NightlySource $Version $env:GRIDCRAFT_BUILD_SHA $env:GRIDCRAFT_BUILD_DATE $Source.Head $Source.Status } +catch { throw "source changed during the build: $_" } +$Exe = Join-Path $TargetDir "$Target\release\gridcraft.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 'GridCraft 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 'gridcraft.exe') +# Signing happens only in the separate trusted step, using sign.ps1 -Required. +# The intermediate's filename cannot satisfy the feed-ready archive contract. +Copy-NightlyNotices $Root $env:CRAFT_FONTS_DIR $Stage +if ((Get-ChildItem -LiteralPath $Stage -Filter '*.exe').Count -ne 1 -or (Test-Path (Join-Path $Stage 'portable.txt'))) { + throw 'nightly stage contains an unexpected executable or portable fallback marker' +} +New-Item -ItemType Directory -Force -Path $Dist | Out-Null +$Zip = Join-Path $Dist $Spec.UnsignedArchive +if (Test-Path -LiteralPath $Zip) { throw 'Nightly output already exists; refusing to replace prepared artifact bytes' } +Compress-Archive -Path (Join-Path $Stage '*') -DestinationPath $Zip +$Archive = [System.IO.Compression.ZipFile]::OpenRead($Zip) +try { + $Names = @($Archive.Entries | ForEach-Object { $_.FullName }) + if ('gridcraft.exe' -notin $Names -or 'gridcraft-cli.exe' -in $Names -or 'portable.txt' -in $Names) { + throw 'nightly ZIP payload violates the GUI-only profile contract' + } +} finally { $Archive.Dispose() } +Write-Output "Nightly build intermediate (not publishable): $Zip ($VersionOutput)" diff --git a/packaging/windows/package.ps1 b/packaging/windows/package.ps1 index 9a1303064a..386dcfebc7 100644 --- a/packaging/windows/package.ps1 +++ b/packaging/windows/package.ps1 @@ -21,9 +21,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) { @@ -50,11 +53,21 @@ $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:GRIDCRAFT_BUILD_SHA) { $env:GRIDCRAFT_BUILD_SHA = (git -C $Root rev-parse HEAD 2>$null) } -if (-not $env:GRIDCRAFT_BUILD_DATE) { $env:GRIDCRAFT_BUILD_DATE = (Get-Date).ToUniversalTime().ToString('yyyy-MM-dd') } +# A nightly requires the prepared commit and original run date explicitly; nightly.ps1 checks both. +if (-not $Nightly) { + if (-not $env:GRIDCRAFT_BUILD_SHA) { $env:GRIDCRAFT_BUILD_SHA = (git -C $Root rev-parse HEAD 2>$null) } + if (-not $env:GRIDCRAFT_BUILD_DATE) { $env:GRIDCRAFT_BUILD_DATE = (Get-Date).ToUniversalTime().ToString('yyyy-MM-dd') } +} Write-Output "GridCraft $Version for Windows $Arch ($Target)" +# The nightly channel is its own producer: a GUI-only intermediate for the trusted signing job, never +# this MSI/portable/CLI contract. +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) { # Static CRT: no VC++ redistributable needed. Scoped to the target so host build scripts and # proc-macros are unaffected. @@ -83,6 +96,11 @@ foreach ($check in @(@('gridcraft.exe', 2), @('gridcraft-cli.exe', 3))) { if ($h.Subsystem -ne $check[1]) { throw "$($check[0]) has PE subsystem $($h.Subsystem), expected $($check[1])" } Write-Output "ok $($check[0]): $Arch, PE subsystem $($h.Subsystem)" } +# The nightly flavor has its own identity; shipping it as the stable app would hand a nightly window +# the stable taskbar identity, data folder and update channel (#16335). +if ((Get-Item -LiteralPath (Join-Path $Bin 'gridcraft.exe')).VersionInfo.ProductName -eq 'GridCraft 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 diff --git a/packaging/windows/sign.ps1 b/packaging/windows/sign.ps1 index 222d5705b2..fe7d9e39c9 100644 --- a/packaging/windows/sign.ps1 +++ b/packaging/windows/sign.ps1 @@ -13,16 +13,28 @@ 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). + Nightly callers require signing with -Required and can check the signing configuration with + -Required -CheckOnly. Compilation uses the separate -CheckBuildEnvironment mode, which never + imports keys. .EXAMPLE pwsh packaging/windows/sign.ps1 dist/gridcraft.exe dist/gridcraft.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 +56,30 @@ 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) { + # Compilation must never see a key: the nightly producer calls this before cargo, and the trusted + # signing job is a separate operation with its own environment. + 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 +127,10 @@ try { Invoke-SignTool ($common + @('/tr', $ts, '/dlib', $dlib.FullName, '/dmdf', $metadata) + $Files) } Invoke-SignTool (@('verify', '/pa', '/v') + $Files) + if ($Required) { + # signtool verify alone can pass while the authenticode state is anything but Valid. + foreach ($file in $Files) { Assert-AuthenticodeSignature (Get-AuthenticodeSignature -LiteralPath $file) } + } } finally { Remove-Item -Recurse -Force $tmp -ErrorAction SilentlyContinue diff --git a/sonar-project.properties b/sonar-project.properties index 4eed7fd86c..5b67372365 100644 --- a/sonar-project.properties +++ b/sonar-project.properties @@ -1,9 +1,17 @@ sonar.projectKey=storytold_gridcraft sonar.organization=storytold +# `sonar.tests` turns off the CLI's default scope, so `sonar.sources=.` must name the production +# tree explicitly; without it Sonar indexes the packaging fixtures and nothing else (L5). +sonar.sources=. +sonar.tests=packaging +# Only these are test runners: the helpers they exercise stay production code. +sonar.test.inclusions=packaging/nightly-tests.py,packaging/nightly-archive-tests.py,packaging/linux/nightly-linux-launch-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 + # The region table is one record per locale with the same field names and many shared values # (month names, formats); that repetition is data, not copy-pasted logic. sonar.cpd.exclusions=crates/core/src/region.rs +sonar.coverage.exclusions=packaging/** # githubactions:S7637 asks for every action to be pinned to a commit SHA. A workflow covered by # .github/workflows/actions.lock runs the commit the lockfile records, so its tag refs are pinned