diff --git a/.github/nightly-linux-signing-key.asc b/.github/nightly-linux-signing-key.asc new file mode 100644 index 000000000..a1c1f31e8 --- /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 000000000..0effee5bc --- /dev/null +++ b/.github/nightly-signing-policy.json @@ -0,0 +1,107 @@ +{ + "schema": "craft-nightly-release-policy/v3", + "repository": "storytold/designcraft", + "repository_id": 1400018213, + "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": "designcraft-nightly-20261124-initial", + "repository": "storytold/designcraft", + "branch": "main", + "required_workflows": [ + { + "workflow_id": 380135818, + "workflow_path": ".github/workflows/ci.yml", + "jobs": [ + { + "name": "gate / gate (ubuntu-24.04)", + "app_id": 15368, + "applicability": "required" + } + ] + } + ], + "sonar": { + "organization": "storytold", + "project": "storytold_designcraft", + "app_id": 12526, + "check_name": "SonarCloud Code Analysis", + "details_url": "https://sonarcloud.io/dashboard?id=storytold_designcraft&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/nightly-sign.yml b/.github/workflows/nightly-sign.yml new file mode 100644 index 000000000..501a160ea --- /dev/null +++ b/.github/workflows/nightly-sign.yml @@ -0,0 +1,42 @@ +name: DesignCraft 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: designcraft-nightly-release + cancel-in-progress: false + +jobs: + release: + # Actual context guards: official repository, manual dispatch, real release branch. + if: >- + github.repository == 'storytold/designcraft' && + 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 000000000..bb9a97a40 --- /dev/null +++ b/.github/workflows/nightly.yml @@ -0,0 +1,34 @@ +name: DesignCraft unsigned nightly + +# Enabled for supervised manual runs by the reviewed manual actors only; no schedule yet. +# A later explicit opt-in may add a cadence (and 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/designcraft' && + 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: designcraft + 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 1771a35fe..badb33439 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/**", "packaging/**", "assets/app-icon/**", ".github/nightly-linux-signing-key.asc", "sonar-project.properties"] pull_request: - paths: [".github/workflows/**", "packaging/**", "assets/app-icon/**"] + paths: [".github/workflows/**", "packaging/**", "assets/app-icon/**", ".github/nightly-linux-signing-key.asc", "sonar-project.properties"] workflow_dispatch: permissions: @@ -49,3 +49,20 @@ jobs: - name: Build and check non-executable installer fixtures shell: pwsh run: ./packaging/windows/test-install-policy.ps1 -OutputDirectory (Join-Path $env:RUNNER_TEMP 'craft-install-policy-tests') + + nightly-source-contract: + name: Nightly source contracts (no build or signing) + runs-on: ubuntu-latest + timeout-minutes: 5 + permissions: + contents: read + steps: + - name: Harden runner + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Enforce nightly serialization and synthetic packaging contracts + run: python3 packaging/nightly-tests.py diff --git a/.gitignore b/.gitignore index d47b8f373..f52f202aa 100644 --- a/.gitignore +++ b/.gitignore @@ -9,3 +9,7 @@ plan/ /.claude/ /target-*/ /craft-fonts/ +/.nightly-tools +/.nightly-input +/craft-i18n +__pycache__/ diff --git a/ASSETS.md b/ASSETS.md index 4297ab421..4f60303a0 100644 --- a/ASSETS.md +++ b/ASSETS.md @@ -65,6 +65,11 @@ Generated-in-code art is original and has no file to list: the UI icon set (`cra | `assets/app-icon/hicolor/512x512/apps/ai.storyteller.designcraft.png` | DesignCraft project owner (drawn in ArtCraft) | rendered from `assets/app-icon/designcraft.svg` by `packaging/icons.sh` | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | App icon: calico cat in a polka-dot scarf (see `assets/app-icon/README.md`) | | `assets/app-icon/hicolor/64x64/apps/ai.storyteller.designcraft.png` | DesignCraft project owner (drawn in ArtCraft) | rendered from `assets/app-icon/designcraft.svg` by `packaging/icons.sh` | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | App icon: calico cat in a polka-dot scarf (see `assets/app-icon/README.md`) | | `assets/app-icon/hicolor/scalable/apps/ai.storyteller.designcraft.svg` | DesignCraft project owner (drawn in ArtCraft) | owner's ArtCraft drawing | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | App icon: calico cat in a polka-dot scarf (see `assets/app-icon/README.md`) | +| `assets/app-icon/designcraft-nightly.png` | DesignCraft project owner (artwork); nightly derivation generated for the nightlies lead | code-generated derivative of `assets/app-icon/designcraft.svg` with the deeper nightly field (method and hashes in `assets/app-icon/nightly-provenance.json`) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | Nightly window icon, tar icon and the 256 px base of the nightly ICO/ICNS | +| `assets/app-icon/designcraft-nightly-1024.png` | DesignCraft project owner (artwork); nightly derivation generated for the nightlies lead | derived from the native 1024 tile onto Apple's 824/1024 grid, never upscaled (see `assets/app-icon/nightly-provenance.json`) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | 1024 px nightly master for the ICNS | +| `assets/app-icon/designcraft-nightly.ico` | DesignCraft project owner (artwork); nightly derivation generated for the nightlies lead | packed 16–256 px frames of `assets/app-icon/designcraft-nightly.png` (see `assets/app-icon/nightly-provenance.json`) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | Windows nightly `designcraft.exe` icon, embedded by `apps/designcraft/build.rs` | +| `assets/app-icon/designcraft-nightly.icns` | DesignCraft project owner (artwork); nightly derivation generated for the nightlies lead | packed native-size frames of the nightly PNG masters (see `assets/app-icon/nightly-provenance.json`) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | macOS nightly bundle icon (`CFBundleIconFile`) | +| `assets/app-icon/nightly-provenance.json` | nightlies lead (generated record) | generated record of the nightly icon derivation (the generator itself is not committed); holds the input/output hashes, the palette fit and the container members | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | Provenance for the four nightly icon files above | | `docs/brand/artcraft-logo.svg`, `docs/brand/artcraft-logo.png` | ArtCraft / Storyteller | ArtCraft brand kit (project owner) | ArtCraft trademark, see docs/brand/LICENSE-brand.txt (not open source) | ArtCraft wordmark (README header) | | `docs/brand/artcraft-logo-white.svg`, `docs/brand/artcraft-logo-white.png` | ArtCraft / Storyteller | ArtCraft brand kit (project owner) | ArtCraft trademark, see docs/brand/LICENSE-brand.txt (not open source) | Wordmark for dark backgrounds | | `docs/brand/artcraft-mark.svg`, `docs/brand/artcraft-mark.png` | ArtCraft / Storyteller | ArtCraft brand kit (project owner) | ArtCraft trademark, see docs/brand/LICENSE-brand.txt (not open source) | The mark; its outline is drawn in code by `crates/ui-egui/src/about.rs` (About splash, start screen) | diff --git a/Cargo.lock b/Cargo.lock index e14ed9c22..b4a802771 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1787,6 +1787,7 @@ dependencies = [ "rfd", "serde", "serde_json", + "thiserror 2.0.21", "winit", "winresource", "winsafe", diff --git a/apps/designcraft-cli/src/main.rs b/apps/designcraft-cli/src/main.rs index 848929d53..7c031ba64 100644 --- a/apps/designcraft-cli/src/main.rs +++ b/apps/designcraft-cli/src/main.rs @@ -170,6 +170,17 @@ fn main() -> ExitCode { } } } + // The Launcher's nightly-v1 profile is a desktop-only contract. Never let its arguments fall + // through to the CLI's directory and credential discovery (which would read the stable + // profile), and answer before any subcommand parses them. A file name after `--` is a file. + if args + .iter() + .take_while(|arg| arg.as_str() != "--") + .any(|arg| arg == "--launch-profile" || arg == "--profile-root" || arg.starts_with("--launch-profile=") || arg.starts_with("--profile-root=")) + { + eprintln!("designcraft-cli: nightly-v1 is supported only by the DesignCraft desktop launcher protocol"); + return ExitCode::from(2); + } // ` --help` asks about that subcommand, which every parser but `script`'s read as an // unknown option (photocraft#423). It goes to stdout and succeeds, as `--help` does. // diff --git a/apps/designcraft/Cargo.toml b/apps/designcraft/Cargo.toml index b66041a04..359e00470 100644 --- a/apps/designcraft/Cargo.toml +++ b/apps/designcraft/Cargo.toml @@ -18,6 +18,8 @@ egui = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } log = { workspace = true } +# Non-exhaustive identity errors for the nightly process identity (`src/process_identity.rs`). +thiserror = { workspace = true } [build-dependencies] # Icon + VERSIONINFO for designcraft.exe; build.rs only uses it when the target is Windows. @@ -40,7 +42,7 @@ craft-update = { workspace = true } # that shows it; drawing on a GPU without a monitor reset the display driver. Safe wrappers over # Win32 (MIT); the `user` feature is User32.dll only. Also the window frame for the custom title # bar (src/window_frame.rs, window styles). -winsafe = { version = "0.0.29", default-features = false, features = ["user"] } +winsafe = { version = "0.0.29", default-features = false, features = ["user", "shell"] } [target.'cfg(target_os = "macos")'.dependencies] # The same winit as eframe; only the native termination opt-in is used. diff --git a/apps/designcraft/build.rs b/apps/designcraft/build.rs index f18ce9cf3..60abb38a7 100644 --- a/apps/designcraft/build.rs +++ b/apps/designcraft/build.rs @@ -1,29 +1,104 @@ -//! Windows only: embed the app icon and version info (VERSIONINFO) into `designcraft.exe`, so it -//! shows in Explorer, the taskbar, the Start menu and Alt-Tab. +//! Windows resources, and the build-time channel and version baked into the binary. //! -//! 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 `DESIGNCRAFT_REQUIRE_WINRES=1` turns it -//! into an error (for release builds). +//! `DESIGNCRAFT_BUILD_CHANNEL=nightly-v1` selects the Launcher's nightly-v1 flavor: it must come +//! with an exact `DESIGNCRAFT_VERSION` feed identity (`X.Y.Z-nightly.YYYYMMDD...g`) +//! plus the matching `DESIGNCRAFT_BUILD_SHA` and `DESIGNCRAFT_BUILD_DATE`. Unset, empty or `stable` +//! is the stable build; anything else is a build error, so a runtime environment cannot promote it. +//! +//! The icon and VERSIONINFO go into `designcraft.exe` only. A missing resource compiler is a +//! warning, so a cross-compile from macOS or Linux still links, unless `DESIGNCRAFT_REQUIRE_WINRES=1` +//! (set by the release workflow) turns it into an error. + +#[path = "src/build_channel.rs"] +mod build_channel; + +fn die(message: &str) -> ! { + eprintln!("{message}"); + std::process::exit(1); +} fn main() { println!("cargo:rerun-if-changed=build.rs"); + println!("cargo:rerun-if-env-changed=DESIGNCRAFT_BUILD_CHANNEL"); + println!("cargo:rerun-if-env-changed=DESIGNCRAFT_VERSION"); + println!("cargo:rerun-if-env-changed=DESIGNCRAFT_OVERRIDE_VERSION"); + println!("cargo:rerun-if-env-changed=DESIGNCRAFT_BUILD_SHA"); + println!("cargo:rerun-if-env-changed=DESIGNCRAFT_BUILD_DATE"); + println!("cargo:rustc-check-cfg=cfg(designcraft_nightly_v1)"); + let nightly = match std::env::var("DESIGNCRAFT_BUILD_CHANNEL").as_deref() { + Ok("nightly-v1") => { + println!("cargo:rustc-cfg=designcraft_nightly_v1"); + true + } + // An empty value (an unset CI input) means the default stable build. + Ok("stable" | "") | Err(std::env::VarError::NotPresent) => false, + // A non-UTF-8 value is as unusable as an unknown one: refuse it instead of guessing. + Ok(_) | Err(std::env::VarError::NotUnicode(_)) => die("unsupported DESIGNCRAFT_BUILD_CHANNEL (expected stable or nightly-v1)"), + }; + let built_version = if nightly { + // The shared workflow exports the prepared version as `DESIGNCRAFT_VERSION` and, for the + // binary, an override of the same value; both must agree when both are set. + let prepared = std::env::var("DESIGNCRAFT_VERSION").ok(); + let overridden = std::env::var("DESIGNCRAFT_OVERRIDE_VERSION").ok(); + if let (Some(prepared), Some(overridden)) = (&prepared, &overridden) + && prepared != overridden + { + die("DESIGNCRAFT_VERSION and DESIGNCRAFT_OVERRIDE_VERSION disagree"); + } + let Some(version) = overridden.or(prepared) else { + die("nightly-v1 requires an explicit DESIGNCRAFT_VERSION feed identity"); + }; + if !build_channel::is_nightly_version(&version) { + die("nightly-v1 requires DESIGNCRAFT_VERSION to be X.Y.Z-nightly.YYYYMMDD...g"); + } + let sha = std::env::var("DESIGNCRAFT_BUILD_SHA").unwrap_or_default(); + if sha.len() != 40 || !sha.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) { + die("nightly-v1 requires DESIGNCRAFT_BUILD_SHA to be the 40-hex source commit"); + } + if build_channel::nightly_commit(&version) != Some(&sha[..12]) { + die("DESIGNCRAFT_VERSION names a different commit than DESIGNCRAFT_BUILD_SHA"); + } + let date = std::env::var("DESIGNCRAFT_BUILD_DATE").unwrap_or_default(); + let digits: Vec = date.chars().filter(|c| c.is_ascii_digit()).collect(); + if date.len() != 10 || date.as_bytes()[4] != b'-' || date.as_bytes()[7] != b'-' || digits.iter().collect::() != date.replace('-', "") + { + die("nightly-v1 requires DESIGNCRAFT_BUILD_DATE as YYYY-MM-DD"); + } + if build_channel::nightly_date_digits(&version) != Some(&date.replace('-', "")) { + die("DESIGNCRAFT_VERSION names a different date than DESIGNCRAFT_BUILD_DATE"); + } + // A nightly-only name: `option_env!` reads the compiler's process environment, and stable + // packaging always exports DESIGNCRAFT_BUILD_SHA, which must not turn a Stable build nightly. + println!("cargo:rustc-env=DESIGNCRAFT_NIGHTLY_COMMIT={sha}"); + println!("cargo:rustc-env=DESIGNCRAFT_BUILD_DATE={date}"); + version + } else { + std::env::var("CARGO_PKG_VERSION").unwrap_or_default() + }; + // One compile-time identity for `--version`, About and the session record. + println!("cargo:rustc-env=DESIGNCRAFT_BUILT_VERSION={built_version}"); + println!("cargo:rerun-if-changed=../../assets/app-icon/designcraft.ico"); + println!("cargo:rerun-if-changed=../../assets/app-icon/designcraft-nightly.ico"); println!("cargo:rerun-if-env-changed=DESIGNCRAFT_REQUIRE_WINRES"); 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/designcraft.ico") - .set("ProductName", "DesignCraft") - .set("FileDescription", "DesignCraft page layout") + res.set_icon(build_channel::windows_icon_path(nightly)) + .set("ProductName", if nightly { "DesignCraft Nightly" } else { "DesignCraft" }) + .set("FileDescription", if nightly { "DesignCraft Nightly page layout" } else { "DesignCraft page layout" }) .set("CompanyName", "Learning Machines LLC") .set("LegalCopyright", "Copyright (c) the DesignCraft authors. MIT OR Apache-2.0.") .set("OriginalFilename", "designcraft.exe") .set("InternalName", "designcraft"); + if nightly { + // The Launcher checks the PE ProductVersion against the exact feed identity, not FileVersion. + res.set("ProductVersion", &built_version); + } if let Err(e) = res.compile() { if std::env::var_os("DESIGNCRAFT_REQUIRE_WINRES").is_some() { - eprintln!("embedding Windows resources failed: {e}"); - std::process::exit(1); + die(&format!("embedding Windows resources failed: {e}")); } println!("cargo:warning=designcraft.exe built without icon/version resources: {e}"); } diff --git a/apps/designcraft/src/build_channel.rs b/apps/designcraft/src/build_channel.rs new file mode 100644 index 000000000..b13d18c6c --- /dev/null +++ b/apps/designcraft/src/build_channel.rs @@ -0,0 +1,78 @@ +//! 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))) +} + +/// The `X.Y.Z-nightly.YYYYMMDD...g` feed version's date digits, or `None`. +/// Used by the build script; the app itself only needs the channel and icon rules. +#[allow(dead_code)] +pub fn nightly_date_digits(version: &str) -> Option<&str> { + let suffix = version.split_once("-nightly.")?.1; + suffix.split('.').next().filter(|date| date.len() == 8) +} + +/// The commit the feed version names, without its `g` prefix. +#[allow(dead_code)] +pub fn nightly_commit(version: &str) -> Option<&str> { + version.rsplit_once(".g").map(|(_, sha)| sha).filter(|sha| sha.len() == 12) +} + +pub fn windows_icon_path(nightly: bool) -> &'static str { + if nightly { "../../assets/app-icon/designcraft-nightly.ico" } else { "../../assets/app-icon/designcraft.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/designcraft.ico"); + assert_eq!(windows_icon_path(true), "../../assets/app-icon/designcraft-nightly.ico"); + } + + #[test] + fn explicit_feed_identity_is_required_for_a_nightly_build() { + assert!(is_nightly_version("0.2.1-nightly.20261124.17.1.gabcdef012345")); + for invalid in [ + "", + "0.2.1", + "0.2.1-nightly", + "0.2.1-nightly.20261124", + "0.2.1-nightly.20261124.17.1.gABCDEF012345", + "0.2.1-nightly.20261124.17.1.gabcdef012345\n", + ] { + assert!(!is_nightly_version(invalid), "{invalid:?}"); + } + } + + #[test] + fn version_cannot_inject_a_path_or_an_extra_build_directive() { + for invalid in [ + "../0.2.1-nightly.20261124.1.1.gabcdef012345", + "0.2.1-nightly.20261124.1.1.gabcdef012345/other", + "0.2.1-nightly.20261124.1.1.gabcdef012345\ncargo:rustc-cfg=other", + ] { + assert!(!is_nightly_version(invalid)); + } + } + + #[test] + fn the_feed_identity_yields_its_date_and_commit() { + assert_eq!(nightly_date_digits("0.2.1-nightly.20261124.17.1.gabcdef012345"), Some("20261124")); + assert_eq!(nightly_commit("0.2.1-nightly.20261124.17.1.gabcdef012345"), Some("abcdef012345")); + assert_eq!(nightly_date_digits("0.2.1"), None); + assert_eq!(nightly_commit("0.2.1"), None); + } +} diff --git a/apps/designcraft/src/build_flavor.rs b/apps/designcraft/src/build_flavor.rs new file mode 100644 index 000000000..0793f44ed --- /dev/null +++ b/apps/designcraft/src/build_flavor.rs @@ -0,0 +1,89 @@ +//! Build-time channel is distinct from a launch selector. A runtime environment cannot promote a stable build. +use crate::launch_profile::Profile; +use std::ffi::OsString; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum BuildFlavor { + Stable, + NightlyV1, +} + +pub const COMPILED: BuildFlavor = if cfg!(designcraft_nightly_v1) { BuildFlavor::NightlyV1 } else { BuildFlavor::Stable }; + +/// The version baked in by `build.rs`: the workspace version for stable, the exact feed identity for nightly. +pub const VERSION: &str = env!("DESIGNCRAFT_BUILT_VERSION"); + +/// The plain `designcraft --version` line, unchanged for stable. +pub const STABLE_VERSION_LINE: &str = concat!("designcraft ", env!("CARGO_PKG_VERSION")); + +pub fn require_profile(flavor: BuildFlavor, profile: &Profile) -> Result<(), String> { + match (flavor, profile.is_nightly()) { + (BuildFlavor::NightlyV1, false) => Err("Open DesignCraft Nightly from ArtCraft Launcher".into()), + (BuildFlavor::Stable, true) => Err("This is a stable DesignCraft 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") +} + +/// The line `--version` prints: ` (nightly-v1)` for nightly, stable's own form otherwise. +pub fn version_line(flavor: BuildFlavor, stable: &str, version: &str) -> String { + match flavor { + BuildFlavor::Stable => stable.to_owned(), + BuildFlavor::NightlyV1 => format!("DesignCraft {version} (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() { + let version = "0.2.1-nightly.20261124.17.1.gabcdef012345"; + assert_eq!(version_line(BuildFlavor::Stable, "designcraft 0.2.1", version), "designcraft 0.2.1"); + assert_eq!(version_line(BuildFlavor::NightlyV1, "designcraft 0.2.1", version), format!("DesignCraft {version} (nightly-v1)")); + assert!(version_query(&["--version".into()])); + assert!(version_query(&["-V".into()])); + assert!(!version_query(&["--".into(), "--version".into()])); + assert!(!version_query(&[])); + } + + #[test] + fn the_compiled_version_is_the_flavor_s_own() { + match COMPILED { + BuildFlavor::Stable => assert_eq!(VERSION, env!("CARGO_PKG_VERSION")), + BuildFlavor::NightlyV1 => assert!(crate::build_channel::is_nightly_version(VERSION), "{VERSION}"), + } + } +} diff --git a/apps/designcraft/src/launch_profile.rs b/apps/designcraft/src/launch_profile.rs new file mode 100644 index 000000000..f2b421433 --- /dev/null +++ b/apps/designcraft/src/launch_profile.rs @@ -0,0 +1,217 @@ +//! Launcher-owned nightly-v1 bootstrap. Selected before logging, updates, fonts or saved state. +//! Stable launches retain their original arguments and directory policy. No environment mutation. + +use std::ffi::OsString; +use std::path::{Component, Path, PathBuf}; +use std::sync::OnceLock; + +pub const VERSION: &str = "nightly-v1"; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Profile { + Stable, + NightlyV1(PathBuf), +} + +impl Profile { + pub fn is_nightly(&self) -> bool { + matches!(self, Self::NightlyV1(_)) + } + + pub fn root(&self) -> Option<&Path> { + match self { + Self::Stable => None, + Self::NightlyV1(root) => Some(root), + } + } +} + +#[derive(Debug, PartialEq, Eq)] +pub struct Launch { + pub profile: Profile, + pub args: Vec, +} + +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".into()) +} + +/// Recognize only the agreed literal selector/root pair before `--`. Everything after it is +/// a file, even when it looks like a profile flag. No filesystem or startup hook runs here. +pub fn parse(args: Vec) -> 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 portable/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. DesignCraft has no +/// agent SDK folder of its own, so the stable boundary is its settings folder, install folders and +/// portable data only. +pub fn validate_root(root: &Path, env: impl Fn(&str) -> Option, exe: Option<&Path>) -> Result { + crate::profile_root::validate(root, env, exe, crate::profile::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\designcraft" } else { "/nightly-data/profiles/designcraft" } + } + + fn nightly() -> Vec { + args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--"]) + } + + #[test] + fn stable_arguments_and_directory_policy_are_unchanged() { + for argv in [args(&[]), args(&["--sample", "a.idml"]), args(&["--", "--launch-profile", "file.designcraft"])] { + let launch = prepare(parse(argv.clone()).unwrap(), |_| panic!("stable must never validate a nightly root")).unwrap(); + assert_eq!(launch, Launch { profile: Profile::Stable, args: argv }); + } + } + + #[test] + fn exact_version_and_root_are_parsed_without_reinterpreting_file_names() { + let mut argv = nightly(); + argv.extend(args(&["--profile-root", "design with spaces.designcraft"])); + let launch = parse(argv).unwrap(); + assert_eq!(launch.profile, Profile::NightlyV1(PathBuf::from(absolute()))); + assert_eq!(launch.args, args(&["--", "--profile-root", "design with spaces.designcraft"])); + } + + #[test] + fn missing_duplicate_unknown_and_conflicting_profile_arguments_are_refused() { + for argv in [ + args(&["--launch-profile", VERSION]), + args(&["--profile-root", absolute()]), + args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--"]), + args(&["--launch-profile", VERSION, "--launch-profile", VERSION, "--profile-root", absolute(), "--"]), + args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--profile-root", absolute(), "--"]), + args(&["--launch-profile", VERSION, "--profile-root", "relative", "--"]), + args(&["--launch-profile", VERSION, "--profile-root", "", "--"]), + args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--new-instance", "--"]), + args(&["--launch-profile", VERSION, "--profile-root", absolute()]), + args(&["--launch-profile=", VERSION, "--profile-root", absolute(), "--"]), + ] { + assert!(parse(argv).is_err()); + } + } + + #[test] + fn the_launcher_version_check_is_a_version_query_only_in_its_exact_form() { + let pair = &["--launch-profile", VERSION, "--profile-root", absolute()]; + let reversed = &["--profile-root", absolute(), "--launch-profile", VERSION]; + for flag in ["--version", "-V"] { + for form in [pair, reversed] { + let mut argv = args(form); + argv.push(flag.into()); + assert!(version_query(&argv), "{argv:?}"); + } + } + for argv in [ + args(&["--version"]), + args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--", "--version"]), + args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--"]), + args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--new-instance", "--version"]), + args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--version"]), + args(&["--version", "--launch-profile", VERSION, "--profile-root", absolute()]), + args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--version"]), + args(&["--launch-profile", VERSION, "--profile-root", "relative", "--version"]), + args(&["--launch-profile", VERSION, "--version"]), + args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--help"]), + ] { + assert!(!version_query(&argv), "{argv:?}"); + } + // Outside the query the strict protocol still refuses the version flag. + assert!(parse(args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version"])).is_err()); + } + + #[test] + fn failed_root_validation_never_reaches_startup_or_falls_back_to_stable() { + let reached = Cell::new(false); + let result = prepare(parse(nightly()).unwrap(), |_| Err("read-only or unsafe profile".into())).map(|_| reached.set(true)); + assert!(result.is_err()); + assert!(!reached.get()); + } + + #[test] + fn successful_root_validation_keeps_the_persistent_root_not_the_binary_tag() { + let checked = PathBuf::from(absolute()).join("checked"); + let launch = prepare(parse(nightly()).unwrap(), |_| Ok(checked.clone())).unwrap(); + assert_eq!(launch.profile.root(), Some(checked.as_path())); + assert!(launch.profile.is_nightly()); + } +} diff --git a/apps/designcraft/src/main.rs b/apps/designcraft/src/main.rs index 82d1808f5..ef2a2e026 100644 --- a/apps/designcraft/src/main.rs +++ b/apps/designcraft/src/main.rs @@ -15,16 +15,24 @@ #[cfg(target_os = "macos")] mod apple_events; +// The build script includes this file by path; the crate needs it only for its tests. +#[cfg(test)] +mod build_channel; +mod build_flavor; mod clipboard_image; mod control_server; mod gpu; mod gpu_limits; +mod launch_profile; mod logging; #[cfg(target_os = "macos")] mod native_menu; +mod nightly_session; #[cfg(target_os = "macos")] mod pointer; +mod process_identity; mod profile; +mod profile_root; mod window_frame; use designcraft_engine::Session; @@ -48,6 +56,10 @@ struct App { /// (`gpu_limits::log_uncaptured_errors`). Until then wgpu's default handler panics, so a /// failing adapter still makes `gpu` start again on the next one. log_errors_after_startup: Option, + /// The Nightly session record's owner, finished on the one exit path (`on_exit`). + session: nightly_session::Shared, + /// Whether this window showed the previous Nightly session's unclean-exit notice. + unclean_notice_shown: bool, } impl eframe::App for App { @@ -107,6 +119,8 @@ impl eframe::App for App { fn on_exit(&mut self) { // A normal exit before the third frame is not a crash. self.startup.presented(); + // The one exit path, including macOS Dock Quit (`with_close_requested_on_terminate`). + nightly_session::finish_once(&self.session, self.unclean_notice_shown); if let Err(e) = preserve_documents_on_exit(&mut self.app) { log::error!("Couldn't preserve documents on exit: {e}"); eprintln!("designcraft: couldn't preserve documents on exit: {e}"); @@ -238,16 +252,18 @@ fn services() -> Services { } } -/// Desktop app ID: the Linux `.desktop` file name and hicolor icon name (Wayland matches windows by it). -const APP_ID: &str = "ai.storyteller.designcraft"; - /// The window, Dock, taskbar and Alt-Tab icon. macOS gets Apple's icon grid (transparent margin); /// elsewhere the full tile. Regenerate with `packaging/icons.sh`. fn app_icon() -> Option { + // The Nightly keeps the artwork on its deeper field, so a dock or window list shows the channel. #[cfg(target_os = "macos")] let png: &[u8] = include_bytes!("../../../assets/app-icon/designcraft-macos-512.png"); #[cfg(not(target_os = "macos"))] - let png: &[u8] = include_bytes!("../../../assets/app-icon/hicolor/256x256/apps/ai.storyteller.designcraft.png"); + let png: &[u8] = if designcraft_ui_egui::channel::is_nightly() { + include_bytes!("../../../assets/app-icon/designcraft-nightly.png") + } else { + include_bytes!("../../../assets/app-icon/hicolor/256x256/apps/ai.storyteller.designcraft.png") + }; eframe::icon_data::from_png_bytes(png).map_err(|e| log::warn!("app icon: {e}")).ok() } @@ -262,34 +278,178 @@ fn control_port_from(source: &str, value: Option) -> Option { port } +/// What [`prepare_launch`] decided before any start-up service ran. +struct Launched { + /// The arguments left for the ordinary parser (files, and `--` already removed). + args: Vec, + /// This is the Launcher's nightly-v1 build, started with its profile. + nightly: bool, + /// The Nightly session record's owner. + session: nightly_session::Shared, + /// The previous Nightly session did not end cleanly. + unclean: bool, + /// This window could not take the session record (a second Nightly is running). + session_unavailable: bool, +} + +fn desktop_session() -> bool { + cfg!(windows) + || cfg!(target_os = "macos") + || (cfg!(target_os = "linux") && ["DISPLAY", "WAYLAND_DISPLAY"].into_iter().any(|key| std::env::var_os(key).is_some_and(|v| !v.is_empty()))) +} + +/// A Nightly launch that is refused before the window: say why where the user looks. +#[allow(clippy::disallowed_types, reason = "native refusal before any window exists")] +fn report_launch_profile_error(error: &str) { + eprintln!("DesignCraft launch profile: {error}"); + if build_flavor::needs_native_error(build_flavor::COMPILED, desktop_session()) { + // Before any window exists, so this is not the in-frame dialog clippy.toml forbids. + let _ = rfd::MessageDialog::new() + .set_title("DesignCraft Nightly") + .set_description(error) + .set_level(rfd::MessageLevel::Error) + .set_buttons(rfd::MessageButtons::Ok) + .show(); + } +} + +/// Select the immutable launch profile before any start-up service or side effect: the version +/// answer first, then the profile, the Windows identity, the fenced root and the session record. +fn prepare_launch() -> Option { + let argv: Vec<_> = std::env::args_os().skip(1).collect(); + // Plain `--version`, or the Launcher's `--launch-profile nightly-v1 --profile-root + // --version`: answered before logging, root validation, process identity or any window. A + // headless runner otherwise hung on macOS and exited 2 on Linux. + if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && (build_flavor::version_query(&argv) || launch_profile::version_query(&argv)) + { + use std::io::Write as _; + let line = build_flavor::version_line(build_flavor::COMPILED, build_flavor::STABLE_VERSION_LINE, build_flavor::VERSION); + let _ = writeln!(std::io::stdout(), "{line}"); + return None; + } + let launch = launch_profile::parse(argv) + .and_then(|launch| { + build_flavor::require_profile(build_flavor::COMPILED, &launch.profile)?; + if launch.profile.is_nightly() { + process_identity::initialize(true, designcraft_ui_egui::channel::NIGHTLY_APP_ID).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 nightly = launch.profile.is_nightly(); + let channel = if nightly { designcraft_ui_egui::channel::Channel::NightlyV1 } else { designcraft_ui_egui::channel::Channel::Stable }; + if let Err(error) = launch_profile::install(launch.profile) + .and_then(|()| designcraft_ui_egui::channel::select(channel, build_flavor::VERSION, option_env!("DESIGNCRAFT_NIGHTLY_COMMIT"))) + { + report_launch_profile_error(&error); + std::process::exit(2); + } + let mut session = nightly_session::shared(); + let mut unclean = false; + let mut session_unavailable = false; + if nightly { + match nightly_session::Session::begin_with_health( + launch_profile::current().root(), + build_flavor::VERSION, + option_env!("DESIGNCRAFT_NIGHTLY_COMMIT"), + ) { + Ok((watch, unavailable)) => { + unclean = watch.as_ref().is_some_and(nightly_session::Session::previous_unclean); + session_unavailable = unavailable; + session = nightly_session::shared_with(watch); + } + Err(error) => { + // Standard error only: this runs before the log file exists. + eprintln!("designcraft: Nightly session state is unavailable: {error}"); + session_unavailable = true; + } + } + } + Some(Launched { args: launch.args, nightly, session, unclean, session_unavailable }) +} + +/// The ordinary command line, once the launch profile was selected. +#[derive(Default)] +struct AppCommand { + /// `--control ` (Stable only). + control_port: Option, + /// `--sample` (Stable only). + sample: bool, + /// A Stable `--version`/`-V`, answered before anything starts. + version: bool, + /// Documents to open, in the order they were named. + files: Vec, + /// The graphics backends a restart asked to skip ([`gpu::SKIP_ARG`]). + skip: Vec, +} + +/// Read the arguments left after the launch profile. A Nightly start's first argument is the +/// separator `launch_profile::parse` put there: it is never a document, and an option after it was +/// named by the Launcher as a file. Stable keeps its control, sample and version options and drops +/// a user's own separator, so a literal `--` is never opened as a document. +fn app_command(args: impl IntoIterator, nightly: bool) -> AppCommand { + let mut command = AppCommand::default(); + let mut args = args.into_iter(); + if nightly { + // `parse` puts the protocol's separator first; skipping it keeps a restart's `--gpu-skip=` + // (appended after that separator) in the ordinary arm below. + args.next(); + } + while let Some(a) = args.next() { + let text = a.to_string_lossy().into_owned(); + match text.as_str() { + "--" if !nightly => { + command.files.extend(args.map(|rest| rest.to_string_lossy().into_owned())); + break; + } + "--control" if !nightly => command.control_port = control_port_from("--control", args.next().map(|v| v.to_string_lossy().into_owned())), + "--sample" if !nightly => command.sample = true, + "--version" | "-V" if !nightly => { + command.version = true; + break; + } + _ => match gpu::skip_arg(&text) { + Some(list) => command.skip = list, + None => command.files.push(text), + }, + } + } + command +} + fn main() -> std::process::ExitCode { - // Windows: the update helper is a copy of this program started with `--finish-update`. + let Some(launch) = prepare_launch() else { return std::process::ExitCode::SUCCESS }; + // Windows: the update helper is a copy of this program started with `--finish-update`. A + // Nightly copy is installed and updated by the Launcher, so it never runs the updater. #[cfg(windows)] - if let Some(result) = craft_update::self_update::finish(&designcraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::>()) { + if !launch.nightly + && let Some(result) = craft_update::self_update::finish(&designcraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::>()) + { std::process::exit(i32::from(result.is_err())); } // First, so every start-up record (and the engine's panic hook, installed with the first // Session) is captured; see `logging`. let logger = logging::install(); - let mut control_port = control_port_from("DESIGNCRAFT_CONTROL_PORT", std::env::var("DESIGNCRAFT_CONTROL_PORT").ok()); - let mut files = Vec::new(); - let mut sample = false; - let mut skip = Vec::new(); - let mut args = std::env::args().skip(1); - while let Some(a) = args.next() { - match a.as_str() { - "--control" => control_port = control_port_from("--control", args.next()), - "--sample" => sample = true, - "--version" => { - println!("designcraft {}", env!("CARGO_PKG_VERSION")); - return std::process::ExitCode::SUCCESS; - } - _ => match gpu::skip_arg(&a) { - Some(list) => skip = list, - None => files.push(a), - }, - } + // A Nightly launch is handed files only; its control channel, sample document and graphics + // restart options are not part of the Launcher's protocol. + let command = app_command(launch.args, launch.nightly); + if command.version { + println!("{}", build_flavor::version_line(build_flavor::COMPILED, build_flavor::STABLE_VERSION_LINE, build_flavor::VERSION)); + return std::process::ExitCode::SUCCESS; } + // A Nightly start never takes the Stable control channel, even from the environment. + let control_port = command.control_port.or_else(|| { + if launch.nightly { None } else { control_port_from("DESIGNCRAFT_CONTROL_PORT", std::env::var("DESIGNCRAFT_CONTROL_PORT").ok()) } + }); + let AppCommand { sample, files, skip, .. } = command; // A portable.txt whose DesignCraftData folder cannot be written: the platform folders are used // instead (see `profile`), and the user is told, in the log and in the status bar. let portable_note = profile::unwritable_portable_dir().map(|dir| { @@ -300,14 +460,14 @@ fn main() -> std::process::ExitCode { // leaves no file behind. Records logged until now are written to it first. if let (Some(logger), Some(dir)) = (logger, profile::config_dir()) { match logger.attach_dir(&dir.join("logs")) { - Ok(path) => log::info!("DesignCraft {}, log file {}", env!("CARGO_PKG_VERSION"), path.display()), + Ok(path) => log::info!("{} {}, log file {}", designcraft_ui_egui::channel::name(), build_flavor::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}"), } } let mut options = eframe::NativeOptions { viewport: egui::ViewportBuilder::default() - .with_title("DesignCraft") + .with_title(designcraft_ui_egui::channel::name()) .with_inner_size([1440.0, 900.0]) .with_min_inner_size([900.0, 560.0]) .with_decorations(!cfg!(target_os = "windows")) @@ -320,7 +480,7 @@ fn main() -> std::process::ExitCode { system_font_fallback: false, ..Default::default() }; - options.viewport = options.viewport.with_app_id(APP_ID); + options.viewport = options.viewport.with_app_id(designcraft_ui_egui::channel::current().app_id()); if let Some(icon) = app_icon() { options.viewport = options.viewport.with_icon(icon); } @@ -385,10 +545,19 @@ fn main() -> std::process::ExitCode { #[cfg(target_os = "macos")] let events = &apple_events; let created = startup.clone(); + // What the app creator needs, copied out of `launch` so the closure does not borrow it. + let nightly = launch.nightly; + let session_unavailable = launch.session_unavailable; + let app_session = launch.session.clone(); + // The same record, for a start that created no window (the creator closure owns the Arc). + let exit_session = launch.session.clone(); + // Whether the previous Nightly session's notice reaches a window: always when one is shown, + // and the same answer for the exit paths below. + let unclean_notice_shown = launch.unclean; // A panic that ends the window (egui-wgpu's own) is caught here: never a crash. let run = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { eframe::run_native( - "DesignCraft", + designcraft_ui_egui::channel::name(), options, Box::new(move |cc| { let mut restarted = None; @@ -429,7 +598,12 @@ fn main() -> std::process::ExitCode { session.recovery_dir = profile::recovery_dir(); let recovered = session.execute("file.recovery.open", &serde_json::json!({})).ok(); let mut app = DesignApp::new(session, services()); - app.set_startup_update_check(true); + if nightly { + // Installed and updated by the Launcher: never check the stable feed from here. + app.set_updates_managed(Some("ArtCraft Launcher")); + } else { + app.set_startup_update_check(true); + } if let Some(line) = restarted.or_else(|| created.status_line()) { app.status(line); } @@ -442,6 +616,13 @@ fn main() -> std::process::ExitCode { if let Some(note) = portable_note { app.status(note); } + // Last, so the interruption is the line the user reads. Showing it is also what + // lets this session clear the record instead of passing it on. + if unclean_notice_shown { + app.status("DesignCraft Nightly did not close cleanly last time. Recovered documents are listed below."); + } else if session_unavailable && nightly { + log::warn!("another DesignCraft Nightly holds this profile's session record"); + } app.integrated_titlebar = cfg!(target_os = "macos"); app.custom_titlebar = cfg!(target_os = "windows"); // The custom title bar's undecorated window must stay borderless, or its caption @@ -472,6 +653,8 @@ fn main() -> std::process::ExitCode { movable: None, frames: 0, log_errors_after_startup: device, + session: app_session, + unclean_notice_shown, })) }), ) @@ -482,6 +665,9 @@ fn main() -> std::process::ExitCode { // Documents that arrived after the last frame, for a start again to open too. #[cfg(target_os = "macos")] startup.opening(apple_events.queued()); + // Normally `on_exit` already finished it; a graphics failure or a start without a window + // reaches this path instead, and the second call does nothing. + nightly_session::finish_once(&exit_session, unclean_notice_shown); match gpu::finish(run, &startup) { Ok(()) => std::process::ExitCode::SUCCESS, Err(e) => { @@ -509,6 +695,34 @@ mod tests { assert!(!super::KEEP_UI_PREFS.load(std::sync::atomic::Ordering::Relaxed), "ui.json can be saved once a copy is kept"); } + #[test] + fn the_launcher_separator_is_never_a_file_and_never_hides_a_named_document() { + let nightly = super::app_command(["--", "--version", "a.dc", "--control", "7979", "--sample"].map(std::ffi::OsString::from), true); + assert_eq!(nightly.files, ["--version", "a.dc", "--control", "7979", "--sample"]); + assert!(!nightly.version, "a flag after the separator is a document"); + assert_eq!(nightly.control_port, None); + assert!(!nightly.sample); + } + + #[test] + fn a_graphics_restart_after_the_separator_keeps_its_skip_list() { + let nightly = super::app_command(["--", "a.dc", "--gpu-skip=vulkan,gl"].map(std::ffi::OsString::from), true); + assert_eq!(nightly.files, ["a.dc"]); + assert_eq!(nightly.skip, ["vulkan", "gl"]); + } + + #[test] + fn stable_keeps_its_options_and_drops_a_user_separator() { + let stable = super::app_command(["--control", "7979", "--sample", "--", "--version"].map(std::ffi::OsString::from), false); + assert_eq!(stable.control_port, Some(7979)); + assert!(stable.sample); + assert_eq!(stable.files, ["--version"]); + assert!(!stable.version, "a flag after the separator is a document"); + let version = super::app_command([std::ffi::OsString::from("--version")], false); + assert!(version.version); + assert!(version.files.is_empty()); + } + #[test] fn control_port_values_that_are_not_ports_are_ignored() { assert_eq!(super::control_port_from("--control", Some("7979".into())), Some(7979)); diff --git a/apps/designcraft/src/nightly_session.rs b/apps/designcraft/src/nightly_session.rs new file mode 100644 index 000000000..4a40b7ace --- /dev/null +++ b/apps/designcraft/src/nightly_session.rs @@ -0,0 +1,285 @@ +//! App-private Nightly session health, not telemetry or a Launcher protocol. +//! A live owner holds a separate persistent lease; secondary launches never rewrite its record. +//! Dropping the guard does not clear the marker. Only the app's controlled return path does. + +use std::fs::{File, OpenOptions}; +use std::io::{self, Read, Write as _}; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex, PoisonError}; + +const RECORD: &str = "nightly-session.json"; +const LEASE: &str = "nightly-session.lock"; +const TEMPORARY: &str = "nightly-session.json.staging"; +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), + } +} + +/// Stage beside the destination and rename over it: a raced link at the record name is replaced, +/// never followed, and a reader sees either the old record or the whole new one. +fn write_record(root: &Path, name: &str, bytes: &[u8]) -> io::Result<()> { + let staging = root.join(format!("{TEMPORARY}.{}", std::process::id())); + let _ = std::fs::remove_file(&staging); + let mut file = OpenOptions::new().write(true).create_new(true).open(&staging)?; + let written = file.write_all(bytes).and_then(|()| file.sync_all()); + drop(file); + match written.and_then(|()| std::fs::rename(&staging, root.join(name))) { + Ok(()) => Ok(()), + Err(error) => { + let _ = std::fs::remove_file(&staging); + Err(error) + } + } +} + +/// The owner's session, shared by the window's exit path and the code after the event loop. +/// On macOS a quit ends the process inside AppKit's terminate, after eframe's `on_exit` and before +/// `eframe::run_native` could return, so `on_exit` finishes it there; the return path still runs +/// for a start that created no window. +pub type Shared = Arc>>; + +pub fn shared() -> Shared { + shared_with(None) +} + +pub fn shared_with(session: Option) -> Shared { + Arc::new(Mutex::new(session)) +} + +/// The controlled return ([`Session::finish`]) by whichever path comes first; later calls do nothing. +pub fn finish_once(shared: &Shared, unclean_notice_shown: bool) { + let watch = shared.lock().unwrap_or_else(PoisonError::into_inner).take(); + if let Some(watch) = watch + && let Err(error) = watch.finish(unclean_notice_shown) + { + log::warn!("Nightly session state was left intact: {error}"); + } +} + +impl Session { + /// The warning belongs to this window: a busy secondary has no health-record coverage, + /// while Stable and a lease-owning Nightly window preserve their existing result. + pub fn begin_with_health(root: Option<&Path>, version: &str, commit: Option<&str>) -> io::Result<(Option, bool)> { + let watch = Self::begin(root, version, commit)?; + let unavailable = root.is_some() && watch.is_none(); + Ok((watch, unavailable)) + } + + /// `None` is stable or another owner of this profile. Neither case touches the record. + /// The supplied root must already be the validated private Nightly profile. + pub fn begin(root: Option<&Path>, version: &str, commit: Option<&str>) -> io::Result> { + let Some(root) = root else { return Ok(None) }; + if version.is_empty() || version.len() > MAX_METADATA_BYTES || commit.is_some_and(|value| value.len() > MAX_METADATA_BYTES) { + return Err(io::Error::new(io::ErrorKind::InvalidInput, "Nightly session provenance is missing or too large")); + } + let lease_path = root.join(LEASE); + regular_or_missing(&lease_path)?; + let lease = OpenOptions::new().read(true).write(true).create(true).truncate(false).open(lease_path)?; + match lease.try_lock() { + Ok(()) => {} + Err(std::fs::TryLockError::WouldBlock) => return Ok(None), + Err(std::fs::TryLockError::Error(error)) => return Err(error), + } + let path = root.join(RECORD); + let previous_unclean = regular_or_missing(&path)?; + let own_record = serde_json::to_vec(&serde_json::json!({ + "schema_version": 1, + "channel": "nightly-v1", + "version": version, + "commit": commit.filter(|value| !value.is_empty()), + }))?; + write_record(root, RECORD, &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 graphics failure before the app callback), the record is left for the next owner + /// to report; otherwise this is [`Self::complete`]. + pub fn finish(self, unclean_notice_shown: bool) -> io::Result<()> { + if self.previous_unclean && !unclean_notice_shown { + return Ok(()); + } + self.complete() + } + + /// Controlled event-loop completion includes a handled start-up error, not only exit 0. + /// An unwind, abort, forced exit or killed process never calls this method. + pub fn complete(self) -> io::Result<()> { + if !regular_or_missing(&self.path)? { + return Ok(()); + } + let mut current = Vec::new(); + File::open(&self.path)?.take(self.own_record.len() as u64 + 1).read_to_end(&mut current)?; + if current != self.own_record { + return Err(io::Error::other("Nightly session state changed; leaving it intact")); + } + std::fs::remove_file(&self.path) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::atomic::{AtomicU64, Ordering}; + + struct Fixture(PathBuf); + impl Fixture { + fn new() -> Self { + static NEXT: AtomicU64 = AtomicU64::new(0); + loop { + let path = + std::env::temp_dir().join(format!("designcraft-nightly-session-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed))); + match std::fs::create_dir(&path) { + Ok(()) => return Self(path), + Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue, + Err(error) => panic!("cannot create owned fixture: {error}"), + } + } + } + } + impl Drop for Fixture { + fn drop(&mut self) { + std::fs::remove_dir_all(&self.0).unwrap(); + } + } + + #[test] + fn busy_secondary_reports_unavailable_without_replacing_the_owner_record() { + let fixture = Fixture::new(); + let (stable, warning) = Session::begin_with_health(None, "stable", None).unwrap(); + assert!(stable.is_none() && !warning); + let (first, warning) = Session::begin_with_health(Some(&fixture.0), "nightly", Some("owned-commit")).unwrap(); + assert!(!warning); + let first = first.unwrap(); + let record = std::fs::read(fixture.0.join(RECORD)).unwrap(); + let (secondary, warning) = Session::begin_with_health(Some(&fixture.0), "secondary", None).unwrap(); + assert!(secondary.is_none() && warning, "a secondary window cannot claim recorded exit/crash coverage"); + assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), record); + first.complete().unwrap(); + assert!(!fixture.0.join(RECORD).exists()); + } + + #[test] + fn controlled_completion_is_clean_but_an_unfinished_owner_is_reported_next_time() { + let fixture = Fixture::new(); + let first = Session::begin(Some(&fixture.0), "first", Some("recorded-commit")).unwrap().unwrap(); + assert!(!first.previous_unclean()); + let own = std::fs::read(fixture.0.join(RECORD)).unwrap(); + assert!(Session::begin(Some(&fixture.0), "secondary", None).unwrap().is_none()); + assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), own, "a busy secondary must not replace the owner's record"); + first.complete().unwrap(); + assert!(!fixture.0.join(RECORD).exists()); + let unfinished = Session::begin(Some(&fixture.0), "second", None).unwrap().unwrap(); + assert!(!unfinished.previous_unclean()); + drop(unfinished); // Unwind/abnormal-path ownership release, not a controlled completion. + let next = Session::begin(Some(&fixture.0), "third", None).unwrap().unwrap(); + assert!(next.previous_unclean()); + next.complete().unwrap(); + assert!(!fixture.0.join(RECORD).exists()); + } + + #[test] + fn an_interruption_no_window_showed_survives_a_handled_startup_failure() { + let fixture = Fixture::new(); + drop(Session::begin(Some(&fixture.0), "crashed", None).unwrap().unwrap()); + let failed = Session::begin(Some(&fixture.0), "gpu-failed", None).unwrap().unwrap(); + assert!(failed.previous_unclean()); + failed.finish(false).unwrap(); + let retry = Session::begin(Some(&fixture.0), "gpu-retry", None).unwrap().unwrap(); + assert!(retry.previous_unclean()); + retry.finish(true).unwrap(); + assert!(!fixture.0.join(RECORD).exists(), "a session that showed the notice clears its record"); + let clean = Session::begin(Some(&fixture.0), "clean", None).unwrap().unwrap(); + assert!(!clean.previous_unclean()); + clean.finish(false).unwrap(); + assert!(!fixture.0.join(RECORD).exists()); + } + + #[test] + fn the_exit_path_and_the_return_path_finish_the_session_once() { + let fixture = Fixture::new(); + let shared = shared(); + *shared.lock().unwrap() = Session::begin(Some(&fixture.0), "quitting", None).unwrap(); + finish_once(&shared, false); + assert!(!fixture.0.join(RECORD).exists(), "a quit that ran the exit path is a clean exit"); + let successor = Session::begin(Some(&fixture.0), "successor", None).unwrap().unwrap(); + assert!(!successor.previous_unclean()); + let record = std::fs::read(fixture.0.join(RECORD)).unwrap(); + finish_once(&shared, false); + assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), record, "the second finish must not touch a successor's record"); + successor.complete().unwrap(); + } + + #[test] + fn cleanup_never_removes_an_unknown_changed_record() { + let fixture = Fixture::new(); + let watch = Session::begin(Some(&fixture.0), "nightly", None).unwrap().unwrap(); + std::fs::write(fixture.0.join(RECORD), b"replacement owned by someone else").unwrap(); + assert!(watch.complete().is_err()); + assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), b"replacement owned by someone else"); + } + + #[test] + fn provenance_is_bounded_and_never_collects_documents_paths_or_diagnostics() { + let fixture = Fixture::new(); + assert!(Session::begin(Some(&fixture.0), &"x".repeat(MAX_METADATA_BYTES + 1), None).is_err()); + assert_eq!(std::fs::read_dir(&fixture.0).unwrap().count(), 0); + assert!(Session::begin(None, "", None).unwrap().is_none(), "stable has no session-health side effects"); + let watch = Session::begin(Some(&fixture.0), "nightly", None).unwrap().unwrap(); + let data: serde_json::Value = serde_json::from_slice(&std::fs::read(fixture.0.join(RECORD)).unwrap()).unwrap(); + let fields = data.as_object().unwrap().keys().map(String::as_str).collect::>(); + assert_eq!(fields, ["schema_version", "channel", "version", "commit"].into_iter().collect()); + assert!(data["commit"].is_null(), "missing provenance must not be invented"); + watch.complete().unwrap(); + assert_eq!(std::fs::read_dir(&fixture.0).unwrap().count(), 1, "only the lease remains"); + } + + #[test] + #[cfg(unix)] + fn reserved_state_aliases_do_not_modify_external_files() { + let fixture = Fixture::new(); + let external = fixture.0.join("stable-document"); + std::fs::write(&external, b"stable bytes").unwrap(); + for name in [LEASE, RECORD] { + let alias = fixture.0.join(name); + std::os::unix::fs::symlink(&external, &alias).unwrap(); + assert!(Session::begin(Some(&fixture.0), "nightly", None).is_err()); + assert_eq!(std::fs::read(&external).unwrap(), b"stable bytes"); + std::fs::remove_file(alias).unwrap(); + } + } + + #[test] + #[cfg(unix)] + fn a_raced_record_link_is_replaced_rather_than_followed() { + let fixture = Fixture::new(); + let external = fixture.0.join("stable-document"); + std::fs::write(&external, b"stable bytes").unwrap(); + // The record is absent when the owner begins, so the write path cannot refuse it; the + // rename over a link that appears afterwards must not follow it. + write_record(&fixture.0, RECORD, b"{}").unwrap(); + std::fs::remove_file(fixture.0.join(RECORD)).unwrap(); + std::os::unix::fs::symlink(&external, fixture.0.join(RECORD)).unwrap(); + write_record(&fixture.0, RECORD, b"nightly record").unwrap(); + assert_eq!(std::fs::read(&external).unwrap(), b"stable bytes"); + assert!(!std::fs::symlink_metadata(fixture.0.join(RECORD)).unwrap().file_type().is_symlink()); + assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), b"nightly record"); + } +} diff --git a/apps/designcraft/src/process_identity.rs b/apps/designcraft/src/process_identity.rs new file mode 100644 index 000000000..c74d63490 --- /dev/null +++ b/apps/designcraft/src/process_identity.rs @@ -0,0 +1,71 @@ +//! Set the immutable nightly Windows identity before any native window or COM service. +//! Stable deliberately leaves its implicit shortcut/path identity unchanged. + +use std::sync::OnceLock; + +#[derive(Clone, Debug, thiserror::Error)] +pub enum IdentityError { + #[error("{0}")] + Configuration(String), +} + +pub fn initialize(nightly: bool, app_id: &str) -> Result<(), IdentityError> { + configure(nightly && cfg!(windows), app_id, |id| { + static RESULT: OnceLock> = OnceLock::new(); + RESULT + .get_or_init(|| { + #[cfg(windows)] + { + winsafe::SetCurrentProcessExplicitAppUserModelID(id) + .map_err(|error| format!("cannot set the nightly Windows identity: {error}"))?; + let actual = winsafe::GetCurrentProcessExplicitAppUserModelID() + .map_err(|error| format!("cannot read back the nightly Windows identity: {error}"))?; + if actual != id { + return Err("the native Windows identity did not match the selected nightly channel".into()); + } + Ok(()) + } + #[cfg(not(windows))] + { + let _ = id; + Ok(()) + } + }) + .clone() + }) + .map_err(IdentityError::Configuration) +} + +fn configure(explicit_nightly: bool, app_id: &str, set: impl FnOnce(&str) -> Result<(), String>) -> Result<(), String> { + if explicit_nightly { set(app_id) } else { Ok(()) } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn stable_does_not_call_the_explicit_identity_api() { + configure(false, "nightly-id", |_| panic!("stable identity must remain implicit")).unwrap(); + } + + #[test] + fn nightly_applies_the_supplied_identity_once() { + let calls = std::cell::Cell::new(0); + configure(true, "nightly-id", |id| { + assert_eq!(id, "nightly-id"); + calls.set(calls.get() + 1); + Ok(()) + }) + .unwrap(); + assert_eq!(calls.get(), 1); + } + + #[test] + fn native_identity_failure_is_returned_instead_of_starting_a_window() { + let started = std::cell::Cell::new(false); + let result = configure(true, "nightly-id", |_| Err("native identity refused".into())).map(|()| started.set(true)); + assert_eq!(result.unwrap_err(), "native identity refused"); + assert!(!started.get()); + } +} diff --git a/apps/designcraft/src/profile.rs b/apps/designcraft/src/profile.rs index 1450e5077..0daa79665 100644 --- a/apps/designcraft/src/profile.rs +++ b/apps/designcraft/src/profile.rs @@ -5,13 +5,29 @@ use std::path::{Path, PathBuf}; /// A file with this name next to the executable makes the install portable: settings, logs and /// recovery data are kept in [`PORTABLE_DATA_DIR`] beside it. The Windows portable zip ships one. -const PORTABLE_MARKER: &str = "portable.txt"; -const PORTABLE_DATA_DIR: &str = "DesignCraftData"; +pub(crate) const PORTABLE_MARKER: &str = "portable.txt"; +pub(crate) const PORTABLE_DATA_DIR: &str = "DesignCraftData"; +/// The settings folder. A Launcher nightly profile replaces every data root at once: settings, +/// logs, GPU state and recovery all live under it, so the fence in `profile_root` covers the +/// whole of Nightly's user state (the engine's `Prefs`, `ui.json` and `recovery` included). pub fn config_dir() -> Option { + if let Some(root) = crate::launch_profile::current().root() { + return Some(root.to_path_buf()); + } config_dir_with(std::env::consts::OS, |key| std::env::var_os(key), executable_dir().as_deref()) } +/// Whether `dir` exists, or can be created, and takes a new file. The nightly profile validator +/// uses this same probe (`profile_root`), so a profile is accepted only where settings can land. +pub(crate) fn ensure_writable(dir: &Path) -> std::io::Result<()> { + std::fs::create_dir_all(dir)?; + let probe = dir.join(format!(".write-test-{}", std::process::id())); + let result = std::fs::OpenOptions::new().write(true).create_new(true).open(&probe).map(drop); + let _ = std::fs::remove_file(&probe); + result +} + fn config_dir_with(os: &str, env: impl Fn(&str) -> Option, exe_dir: Option<&Path>) -> Option { if let Some(root) = root_with(&env, exe_dir) { // An explicitly empty override must not fall back to the user's profile. @@ -50,13 +66,7 @@ fn marked_data_dir(exe_dir: &Path) -> Option { /// Whether `dir` exists, or can be created, and takes a new file: read-only attributes and /// permissions are only known by trying. fn writable(dir: &Path) -> bool { - if std::fs::create_dir_all(dir).is_err() { - return false; - } - let probe = dir.join(format!(".write-test-{}", std::process::id())); - let ok = std::fs::write(&probe, b"").is_ok(); - let _ = std::fs::remove_file(&probe); - ok + ensure_writable(dir).is_ok() } /// The data folder of a portable install that could not be used because it is not writable, for @@ -85,6 +95,10 @@ fn executable_dir() -> Option { } pub fn recovery_dir() -> Option { + if let Some(root) = crate::launch_profile::current().root() { + // Recovery stays inside the profile, including the per-run folder's lock. + return own_run(root.join("Recovery")); + } recovery_dir_with(root_with(|key| std::env::var_os(key), executable_dir().as_deref()), designcraft_engine::recovery::default_dir) .and_then(own_run) } diff --git a/apps/designcraft/src/profile_root.rs b/apps/designcraft/src/profile_root.rs new file mode 100644 index 000000000..1522d0070 --- /dev/null +++ b/apps/designcraft/src/profile_root.rs @@ -0,0 +1,492 @@ +//! App-owned nightly profile fences; no stable fallback, migration or process environment changes. + +use std::ffi::OsString; +use std::path::{Component, Path, PathBuf}; + +use crate::profile::{PORTABLE_DATA_DIR, PORTABLE_MARKER}; + +#[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), + _ => 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 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 => { + let mut roots = ["APPDATA", "LOCALAPPDATA"] + .into_iter() + .map(|key| required_base(env, key).map(|p| p.join("DesignCraft"))) + .collect::, _>>()?; + // The MSI's per-machine folder (install-policy.wxi, ProgramFiles6432Folder) and a + // per-user install folder. A custom folder is not known here; the executable's own + // folder is fenced below. + roots.push(required_base(env, "LOCALAPPDATA")?.join("Programs").join("ArtCraft").join("DesignCraft")); + 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("DesignCraft")); + } + } + 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("designcraft"))) + .collect::, _>>()?; + roots.extend(["/usr/bin/designcraft", "/usr/local/bin/designcraft", "/opt/designcraft"].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.designcraft")); + roots + } + Platform::Mac => { + let home = required_base(env, "HOME")?; + let library = home.join("Library"); + vec![ + library.join("Application Support/DesignCraft"), + library.join("Caches/DesignCraft"), + library.join("Caches/ai.storyteller.designcraft"), + library.join("Preferences/DesignCraft.plist"), + library.join("Preferences/ai.storyteller.designcraft.plist"), + library.join("Saved Application State/ai.storyteller.designcraft.savedState"), + home.join("Applications/DesignCraft.app"), + PathBuf::from("/Applications/DesignCraft.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 (logs, settings and so on) must resolve inside it, +/// so a link there cannot point Nightly's writes at another app's data. +fn entries_stay_inside(root: &Path) -> Result<(), String> { + let entries = match std::fs::read_dir(root) { + Ok(entries) => entries, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()), + Err(error) => return Err(format!("cannot inspect the nightly profile: {error}")), + }; + for entry in entries { + let entry = entry.map_err(|e| format!("cannot inspect the nightly profile: {e}"))?; + private_subdirectory(root, entry.file_name(), "profile entry")?; + } + Ok(()) +} + +/// Recognise the shared portable data namespace in both the supplied and resolved path. +/// This is not an inventory of arbitrary custom stable overrides or a Launcher ownership proof. +fn is_portable_layout(path: &Path, platform: Platform) -> bool { + // A folder under a portable copy belongs to that copy too. Above the chosen folder itself, a + // marker only counts beside a DesignCraft executable, so an unrelated portable.txt higher up + // (in a user folder or at a drive root) does not refuse the profile. + path.ancestors().enumerate().any(|(depth, ancestor)| { + ancestor.join(PORTABLE_MARKER).is_file() + && (depth == 0 || ["designcraft.exe", "designcraft", "DesignCraft.app"].iter().any(|exe| ancestor.join(exe).exists())) + }) || path.components().any(|component| match component { + Component::Normal(name) if platform.ignores_case() => name.to_string_lossy().eq_ignore_ascii_case(PORTABLE_DATA_DIR), + Component::Normal(name) => name == PORTABLE_DATA_DIR, + _ => false, + }) +} + +/// The writable hook is the app's existing probe (`profile::ensure_writable`). Keeping it injected +/// lets 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 env("DESIGNCRAFT_CONFIG_DIR").is_some_and(|v| !v.is_empty()) { + // The stable override would silently point every write at another app's data. + return Err("nightly-v1 cannot be combined with DESIGNCRAFT_CONFIG_DIR".into()); + } + // The nightly bundle's own sandbox is the one Flatpak that may reach this code: its per-app + // home is private. Any other id means a native package (or the stable bundle) started here, + // whose runtime socket namespace is not this profile's. + let foreign_sandbox = + env("FLATPAK_ID").filter(|value| !value.is_empty()).is_some_and(|id| id != designcraft_ui_egui::channel::NIGHTLY_PACKAGE_ID); + if platform != Platform::Windows && foreign_sandbox { + return Err("nightly-v1 starts only in its own Flatpak bundle, not inside another app's sandbox".into()); + } + let chosen = canonical_future(root)?; + if is_portable_layout(root, platform) || is_portable_layout(&chosen, platform) { + return Err("the nightly root must not use a portable DesignCraft installation or its DesignCraftData settings folder".into()); + } + let exe = absolute(exe.ok_or("cannot establish the installation boundary")?.to_path_buf(), "the executable")?; + let forbidden = forbidden_roots(platform, &env, &exe)?; + if forbidden.iter().any(|stable| overlaps(&chosen, stable, platform)) { + return Err("the nightly root must not overlap stable data or an installation".into()); + } + // Existing aliases under the profile must not redirect a write outside it. + entries_stay_inside(&chosen)?; + // Recovery can read, adopt, overwrite and sweep entries. Never let its alias leave this + // private profile, including toward a stable portable directory not in our known roots. + private_subdirectory(&chosen, "Recovery", "recovery folder")?; + let mut create = std::fs::DirBuilder::new(); + create.recursive(true); + #[cfg(unix)] + { + use std::os::unix::fs::DirBuilderExt as _; + create.mode(0o700); + } + create.create(&chosen).map_err(|e| format!("cannot create the nightly profile: {e}"))?; + let confirmed = std::fs::canonicalize(&chosen).map_err(|e| format!("cannot resolve the created nightly profile: {e}"))?; + if confirmed != chosen || forbidden.iter().any(|stable| overlaps(&confirmed, stable, platform)) { + return Err("the nightly profile changed while it was being validated".into()); + } + private_subdirectory(&confirmed, "Recovery", "recovery folder")?; + entries_stay_inside(&confirmed)?; + writable(&confirmed).map_err(|e| format!("the nightly profile is not writable: {e}"))?; + Ok(confirmed) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::collections::BTreeMap; + use std::sync::atomic::{AtomicU64, Ordering}; + + 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!("designcraft-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/designcraft"); + std::fs::create_dir_all(&home).unwrap(); + std::fs::create_dir_all(exe.parent().unwrap()).unwrap(); + std::fs::write(&exe, b"fixture executable, never run").unwrap(); + let env = [("HOME", home), ("APPDATA", root.join("roaming")), ("LOCALAPPDATA", root.join("local"))] + .into_iter() + .map(|(key, value)| (key.into(), value.into_os_string())) + .collect(); + Self { root, env, exe } + } + + fn get(&self, key: &str) -> Option { + self.env.get(key).cloned() + } + + fn check(&self, platform: Platform, root: &Path) -> Result { + validate_for( + platform, + root, + |key| self.get(key), + Some(&self.exe), + |dir| { + let probe = dir.join("exclusive-test-probe"); + let file = std::fs::OpenOptions::new().write(true).create_new(true).open(&probe)?; + drop(file); + std::fs::remove_file(probe) + }, + ) + } + + fn home(&self) -> PathBuf { + PathBuf::from(self.get("HOME").unwrap()) + } + } + + impl Drop for Fixture { + fn drop(&mut self) { + // Only the directory successfully created by this fixture is owned for removal. + std::fs::remove_dir_all(&self.root).unwrap(); + } + } + + #[test] + fn every_stable_data_root_is_refused_on_every_platform() { + let fixture = Fixture::new(); + let home = fixture.home(); + let cases = [ + (Platform::Windows, fixture.root.join("roaming/DesignCraft")), + (Platform::Windows, fixture.root.join("local/DesignCraft")), + (Platform::Windows, fixture.root.join("local/Programs/ArtCraft/DesignCraft")), + (Platform::Linux, home.join(".config/designcraft")), + (Platform::Linux, home.join(".local/share/designcraft")), + (Platform::Linux, home.join(".cache/designcraft")), + (Platform::Linux, home.join(".local/state/designcraft")), + (Platform::Linux, home.join(".var/app/ai.storyteller.designcraft")), + (Platform::Linux, PathBuf::from("/opt/designcraft")), + (Platform::Mac, home.join("Library/Application Support/DesignCraft")), + (Platform::Mac, home.join("Library/Caches/DesignCraft")), + (Platform::Mac, home.join("Library/Preferences/ai.storyteller.designcraft.plist")), + (Platform::Mac, home.join("Library/Saved Application State/ai.storyteller.designcraft.savedState")), + (Platform::Mac, home.join("Applications/DesignCraft.app")), + ]; + for (platform, stable) in cases { + for candidate in [stable.clone(), stable.join("nested nightly")] { + let probed = std::cell::Cell::new(false); + let result = validate_for( + platform, + &candidate, + |key| fixture.get(key), + Some(&fixture.exe), + |_| { + probed.set(true); + Ok(()) + }, + ); + assert!(result.is_err(), "{platform:?} accepted {candidate:?}"); + assert!(!probed.get(), "a refused root must not be probed for writing"); + } + } + } + + #[test] + fn the_installation_folder_and_grandparent_overlaps_are_refused() { + let fixture = Fixture::new(); + let install = fixture.exe.parent().unwrap().to_path_buf(); + for platform in [Platform::Windows, Platform::Linux, Platform::Mac] { + assert!(fixture.check(platform, &install).is_err(), "the install folder itself"); + assert!(fixture.check(platform, &install.join("profile")).is_err(), "a folder inside the install"); + assert!(fixture.check(platform, &fixture.root.join("nightly")).is_ok(), "a sibling of the install is private"); + } + } + + #[test] + fn prefix_and_case_lookalikes_are_not_stable_overlaps() { + let fixture = Fixture::new(); + for platform in [Platform::Windows, Platform::Linux, Platform::Mac] { + // `DesignCraftBackups` only starts with the stable folder's name. + assert!(fixture.check(platform, &fixture.home().join("Library/Application Support/DesignCraftBackups/nightly")).is_ok()); + assert!(fixture.check(platform, &fixture.root.join("data-craft/nightly")).is_ok()); + } + // Case folding differs by platform: Windows and macOS fold, Linux does not. + let folded = fixture.root.join("roaming/designcraft"); + assert!(fixture.check(Platform::Windows, &folded).is_err()); + assert!(fixture.check(Platform::Linux, &folded).is_ok(), "a different case is a different Linux path"); + } + + #[test] + fn portable_settings_from_another_install_are_refused_before_any_probe() { + let fixture = Fixture::new(); + let stable_install = fixture.root.join("stable portable install"); + let stable_data = stable_install.join(PORTABLE_DATA_DIR); + std::fs::create_dir_all(&stable_data).unwrap(); + std::fs::write(stable_install.join(PORTABLE_MARKER), b"owned portable fixture").unwrap(); + std::fs::write(stable_data.join("ui.json"), b"stable settings must not change").unwrap(); + for platform in [Platform::Windows, Platform::Linux, Platform::Mac] { + for candidate in [&stable_data, &stable_data.join("nested nightly")] { + let probed = std::cell::Cell::new(false); + let result = validate_for( + platform, + candidate, + |key| fixture.get(key), + Some(&fixture.exe), + |_| { + probed.set(true); + Ok(()) + }, + ); + assert!(result.is_err(), "a different portable install is not a private Nightly profile"); + assert!(!probed.get(), "reject portable data before a writable probe"); + assert!(!stable_data.join("nested nightly").exists()); + assert_eq!(std::fs::read(stable_data.join("ui.json")).unwrap(), b"stable settings must not change"); + } + } + let private = fixture.root.join("DesignCraftData-backup-name/nightly"); + assert!(fixture.check(Platform::Linux, &private).is_ok(), "a merely similar name is not a portable settings component"); + } + + #[test] + fn the_stable_settings_override_and_a_flatpak_instance_are_refused() { + let fixture = Fixture::new(); + let target = fixture.root.join("nightly"); + for value in ["/somewhere/else", ""] { + let env = |key: &str| if key == "DESIGNCRAFT_CONFIG_DIR" { Some(OsString::from(value)) } else { fixture.get(key) }; + let result = validate_for(Platform::Linux, &target, env, Some(&fixture.exe), |_| Ok(())); + if value.is_empty() { + assert!(result.is_ok(), "an empty override is not a stable data redirection"); + } else { + let error = result.unwrap_err(); + assert!(error.contains("DESIGNCRAFT_CONFIG_DIR"), "{error}"); + } + } + let flatpak = |key: &str| if key == "FLATPAK_ID" { Some(OsString::from("ai.storyteller.designcraft")) } else { fixture.get(key) }; + assert!(validate_for(Platform::Linux, &target, flatpak, Some(&fixture.exe), |_| Ok(())).is_err()); + assert!(validate_for(Platform::Windows, &target, flatpak, Some(&fixture.exe), |_| Ok(())).is_ok(), "Windows has no Flatpak namespace"); + // The nightly bundle's own sandbox is private; a lookalike id is still another app's. + let nightly_bundle = + |key: &str| if key == "FLATPAK_ID" { Some(OsString::from(designcraft_ui_egui::channel::NIGHTLY_PACKAGE_ID)) } else { fixture.get(key) }; + assert!(validate_for(Platform::Linux, &target, nightly_bundle, Some(&fixture.exe), |_| Ok(())).is_ok()); + let lookalike = + |key: &str| if key == "FLATPAK_ID" { Some(OsString::from("ai.storyteller.designcraft.nightly-v1")) } else { fixture.get(key) }; + assert!(validate_for(Platform::Linux, &target, lookalike, Some(&fixture.exe), |_| Ok(())).is_err()); + } + + #[cfg(unix)] + #[test] + fn recovery_aliases_cannot_redirect_to_stable_or_outward_data() { + let fixture = Fixture::new(); + let stable = fixture.home().join(".local/share/designcraft/Recovery"); + std::fs::create_dir_all(&stable).unwrap(); + std::fs::write(stable.join("stable-autosave"), b"stable recovery bytes").unwrap(); + for target in [stable.clone(), fixture.root.to_path_buf(), fixture.root.join("Recovery/../../elsewhere")] { + let profile = fixture.root.join(format!("profile-{}", target.file_name().unwrap().to_string_lossy().replace('.', "_"))); + std::fs::create_dir_all(&profile).unwrap(); + std::os::unix::fs::symlink(&target, profile.join("Recovery")).unwrap(); + assert!(fixture.check(Platform::Linux, &profile).is_err(), "{target:?}"); + assert_eq!(std::fs::read(stable.join("stable-autosave")).unwrap(), b"stable recovery bytes"); + } + } + + #[cfg(unix)] + #[test] + fn a_created_profile_is_private_and_a_failed_write_probe_never_falls_back() { + let fixture = Fixture::new(); + let probe = fixture.root.join("profile for probe"); + let error = validate_for(Platform::Linux, &probe, |key| fixture.get(key), Some(&fixture.exe), |_| Err(std::io::Error::other("read-only"))) + .unwrap_err(); + assert!(error.contains("not writable"), "{error}"); + use std::os::unix::fs::PermissionsExt; + assert_eq!(std::fs::metadata(&probe).unwrap().permissions().mode() & 0o777, 0o700); + } + + #[test] + fn relative_and_parent_traversing_are_refused_and_link_ancestors_are_resolved() { + let fixture = Fixture::new(); + for candidate in [PathBuf::from("relative/nightly"), fixture.root.join("a/../nightly")] { + assert!(fixture.check(Platform::Linux, &candidate).is_err(), "{candidate:?}"); + } + #[cfg(unix)] + { + let elsewhere = fixture.root.join("elsewhere"); + std::fs::create_dir_all(&elsewhere).unwrap(); + std::os::unix::fs::symlink(&elsewhere, fixture.root.join("linked")).unwrap(); + // `canonical_future` resolves the existing ancestors before anything is created, so a + // root reached through a link is validated and created at the link's real location. + // That location is what the fence checks, and it is where every write then lands. + let resolved = fixture.check(Platform::Linux, &fixture.root.join("linked/nightly")).unwrap(); + assert_eq!(resolved, std::fs::canonicalize(elsewhere.join("nightly")).unwrap()); + assert!(resolved.is_dir()); + assert_eq!(std::fs::canonicalize(fixture.root.join("linked")).unwrap(), elsewhere); + } + } + + #[test] + fn a_valid_profile_is_returned_resolved_and_created() { + let fixture = Fixture::new(); + let chosen = fixture.root.join("launcher data/profiles/designcraft"); + let resolved = fixture.check(Platform::Linux, &chosen).unwrap(); + assert_eq!(resolved, std::fs::canonicalize(&chosen).unwrap()); + assert!(resolved.is_dir()); + } +} diff --git a/assets/app-icon/README.md b/assets/app-icon/README.md index a1086577a..863662f73 100644 --- a/assets/app-icon/README.md +++ b/assets/app-icon/README.md @@ -46,3 +46,14 @@ The app ID is `ai.storyteller.designcraft`. It's used for the hicolor icon names Edit `designcraft.svg` (or `designcraft-small.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 + +`designcraft-nightly.png`, `-1024.png`, `.ico` and `.icns` are the Launcher Nightly's icons. They keep +the artwork, alpha and Mac padding unchanged and change only the background field, from the app +green `#7bb51c` to the deeper `#26400f`; there is no letter badge or crescent, and the app and the +Launcher identify the channel in text. The 1024 master is derived from the native 1024 tile onto +Apple's 824/1024 grid, never upscaled from 256. Hashes, the palette-fit method and the container +members are in [`nightly-provenance.json`](nightly-provenance.json); the stable files are not +recoloured. `build.rs` embeds `designcraft-nightly.ico` into a nightly `designcraft.exe`, and the +nightly bundle uses `designcraft-nightly.icns`. diff --git a/assets/app-icon/designcraft-nightly-1024.png b/assets/app-icon/designcraft-nightly-1024.png new file mode 100644 index 000000000..dcdb7d0c7 Binary files /dev/null and b/assets/app-icon/designcraft-nightly-1024.png differ diff --git a/assets/app-icon/designcraft-nightly.icns b/assets/app-icon/designcraft-nightly.icns new file mode 100644 index 000000000..4c2d9ce19 Binary files /dev/null and b/assets/app-icon/designcraft-nightly.icns differ diff --git a/assets/app-icon/designcraft-nightly.ico b/assets/app-icon/designcraft-nightly.ico new file mode 100644 index 000000000..4254fe811 Binary files /dev/null and b/assets/app-icon/designcraft-nightly.ico differ diff --git a/assets/app-icon/designcraft-nightly.png b/assets/app-icon/designcraft-nightly.png new file mode 100644 index 000000000..279fc86fc Binary files /dev/null and b/assets/app-icon/designcraft-nightly.png differ diff --git a/assets/app-icon/nightly-provenance.json b/assets/app-icon/nightly-provenance.json new file mode 100644 index 000000000..aa0748190 --- /dev/null +++ b/assets/app-icon/nightly-provenance.json @@ -0,0 +1,60 @@ +{ + "title": "DesignCraft nightly deep-background icons", + "author": "@nightlty-designcraft (generated for the nightlies lead)", + "license": "MIT OR Apache-2.0", + "source_commit": null, + "inputs": [ + { + "path": "assets/app-icon/hicolor/256x256/apps/ai.storyteller.designcraft.png", + "sha256": "b8407dae4f43d6f0503ec6c1df619cca34b358d8bb230c6b0d18c992aa5a7f61", + "purpose": "Windows/Linux native256 master" + }, + { + "path": "assets/app-icon/designcraft-1024.png", + "sha256": "5cf554e4ac5b9b02a5e3ef7f9491c421ac7cbdf902eb93834586eaacd3d0feca", + "purpose": "native 1024 master, padded onto Apple's 824/1024 grid for the Mac" + } + ], + "method": { + "kind": "code-generated derivative of the project-owned icon", + "original_palette": { + "ink": "#0b0b0c", + "paper": "#efe9dc", + "background": "#7bb51c" + }, + "nightly_background": "#26400f", + "transform": "Fit each pixel's ink/paper/background weights in the existing three-colour palette and rebuild it with the deeper field, keeping alpha and every foreground/detail pixel; derive the Mac 1024 master from the native 1024 tile on Apple's 824/1024 grid (not an upscale from 256) and pack native-size PNG frames into ICO/ICNS. No badge, crescent or letter.", + "generator_sha256": "a96dc21e32e581284f9b9cfc4fdf2b47cef2a06a2a8d3184274866f376131399" + }, + "outputs": { + "assets/app-icon/designcraft-nightly.png": "01a05015cda1ddf5117ab8e02b6e3cf6cf3106e90e41c91164b7245ad9d22c97", + "assets/app-icon/designcraft-nightly-1024.png": "91647d2cc680df2d416fc0fdb33afbaddc02b09090bdef80c466e58807c3ec17", + "assets/app-icon/designcraft-nightly.ico": "d100e87c2a98b4a981ddd927454fdef3bca962f490b347a13d5841fa30224d51", + "assets/app-icon/designcraft-nightly.icns": "189e20cd7db4014dd807b354abc5da57d894385dd190a630bd0932b626ffe8f2" + }, + "ico_frame_sizes": [ + 16, + 20, + 24, + 32, + 40, + 48, + 64, + 128, + 256 + ], + "icns_png_slots": { + "icp4": 16, + "icp5": 32, + "ic11": 32, + "icp6": 64, + "ic12": 64, + "ic07": 128, + "ic08": 256, + "ic13": 256, + "ic09": 512, + "ic14": 512, + "ic10": 1024 + }, + "validation": "Input/output hashes recorded; PNG dimensions and container members checked; the tiles were compared visually against the stable icon (same artwork, deeper field, Mac padding intact). Native Explorer/Finder/iconutil/app-package qualification remains unrun." +} diff --git a/crates/ui-egui/src/about.rs b/crates/ui-egui/src/about.rs index 90d6eb70f..eae44ea36 100644 --- a/crates/ui-egui/src/about.rs +++ b/crates/ui-egui/src/about.rs @@ -158,16 +158,24 @@ pub fn show(app: &mut DesignApp, ctx: &egui::Context) { let (r, _) = ui.allocate_exact_size(vec2(72.0, 72.0), Sense::hover()); paint_mark(ui, r, BRAND); ui.add_space(6.0); - ui.label(crate::rtl::widget( - ui, - egui::RichText::new(crate::i18n::tr(&app.ui.language, "DesignCraft")).font(semibold(26.0)).color(t.text_strong), - )); + // The channel's own name and version: DesignCraft (stable) or DesignCraft Nightly. + let channel = crate::channel::current(); + let app_name = match channel { + crate::channel::Channel::Stable => crate::i18n::tr(&app.ui.language, "DesignCraft").to_string(), + crate::channel::Channel::NightlyV1 => channel.name().to_string(), + }; + ui.label(crate::rtl::widget(ui, egui::RichText::new(app_name).font(semibold(26.0)).color(t.text_strong))); crate::rtl::label( ui, - egui::RichText::new(format!("{} {}", crate::i18n::tr(&app.ui.language, "Version"), env!("CARGO_PKG_VERSION"))) + egui::RichText::new(format!("{} {}", crate::i18n::tr(&app.ui.language, "Version"), crate::channel::version())) .size(12.0) .color(t.text_dim), ); + // A nightly build says which commit it was made from; the links below include Report an issue. + if let Some(commit) = crate::channel::commit() { + let short = commit.get(..12).unwrap_or(commit); + crate::rtl::label(ui, egui::RichText::new(format!("nightly-v1 · {short}")).size(11.0).color(t.text_dim)); + } ui.add_space(4.0); ui.label(crate::rtl::widget( ui, diff --git a/crates/ui-egui/src/channel.rs b/crates/ui-egui/src/channel.rs new file mode 100644 index 000000000..b5ad34e3e --- /dev/null +++ b/crates/ui-egui/src/channel.rs @@ -0,0 +1,120 @@ +//! The window and About identity of the selected channel: Stable, or the Launcher's nightly-v1. +//! +//! The desktop selects it once, before any window exists (`main.rs`), with the version the build +//! script baked in. The web build never selects one and stays stable. Every OS name (Wayland app +//! id, Windows AUMID, About, captions) comes from here, so the two channels cannot disagree. + +use std::sync::OnceLock; +use std::sync::atomic::{AtomicU8, Ordering}; + +/// The stable `.desktop` file name, hicolor icon name and Windows identity. +pub const APP_ID: &str = "ai.storyteller.designcraft"; +/// The nightly package, bundle and Launcher identity (`ai.storyteller.designcraft.nightly`). +pub const NIGHTLY_PACKAGE_ID: &str = "ai.storyteller.designcraft.nightly"; +/// The nightly window/Wayland app id and Windows AUMID; deliberately not the package id. +pub const NIGHTLY_APP_ID: &str = "ai.storyteller.designcraft.nightly-v1"; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Channel { + Stable, + NightlyV1, +} + +impl Channel { + pub fn is_nightly(self) -> bool { + self == Self::NightlyV1 + } + + /// The OS window identity: stable's `.desktop` name, or the nightly-v1 window id. + pub fn app_id(self) -> &'static str { + match self { + Self::Stable => APP_ID, + Self::NightlyV1 => NIGHTLY_APP_ID, + } + } + + /// The name About, captions and dialogs show. + pub fn name(self) -> &'static str { + match self { + Self::Stable => "DesignCraft", + Self::NightlyV1 => "DesignCraft Nightly", + } + } +} + +/// 0 = not selected (stable), 1 = stable, 2 = nightly-v1. +static SELECTED: AtomicU8 = AtomicU8::new(0); +static IDENTITY: OnceLock<(&'static str, Option<&'static str>)> = OnceLock::new(); + +/// Select the channel once, with the version and (nightly only) commit the build baked in. +pub fn select(channel: Channel, version: &'static str, commit: Option<&'static str>) -> Result<(), String> { + if version.is_empty() { + return Err("the build channel needs a version".into()); + } + if channel.is_nightly() != commit.is_some() { + return Err("only a nightly channel carries a source commit".into()); + } + let value = if channel.is_nightly() { 2 } else { 1 }; + SELECTED.compare_exchange(0, value, Ordering::AcqRel, Ordering::Acquire).map_err(|_| "the build channel was already selected".to_string())?; + IDENTITY.set((version, commit)).map_err(|_| "the build channel was already selected".to_string()) +} + +pub fn current() -> Channel { + if SELECTED.load(Ordering::Acquire) == 2 { Channel::NightlyV1 } else { Channel::Stable } +} + +pub fn is_nightly() -> bool { + current().is_nightly() +} + +pub fn name() -> &'static str { + current().name() +} + +/// The exact build version: the workspace version for stable, the feed identity for nightly. +pub fn version() -> &'static str { + IDENTITY.get().map_or(env!("CARGO_PKG_VERSION"), |(version, _)| *version) +} + +/// The 40-hex source commit of a nightly build, if the build was given one. +pub fn commit() -> Option<&'static str> { + IDENTITY.get().and_then(|(_, commit)| *commit) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A version and a commit must match the channel, and the errors are returned rather than + /// stored, so a refusal leaves the selection untouched. + #[test] + fn select_refuses_a_missing_version_and_a_commit_that_does_not_match_the_channel() { + assert_eq!(select(Channel::Stable, "", None).unwrap_err(), "the build channel needs a version"); + assert_eq!( + select(Channel::Stable, "0.2.1", Some("0123456789abcdef0123456789abcdef01234567")).unwrap_err(), + "only a nightly channel carries a source commit" + ); + assert_eq!( + select(Channel::NightlyV1, "0.2.1-nightly.20261124.17.1.gabcdef012345", None).unwrap_err(), + "only a nightly channel carries a source commit" + ); + assert_eq!(current(), Channel::Stable, "a refused selection leaves the channel as it was"); + } + + #[test] + fn the_default_is_the_stable_identity() { + assert_eq!(current(), Channel::Stable, "the web build and tests never select a channel"); + assert_eq!(name(), "DesignCraft"); + assert_eq!(version(), env!("CARGO_PKG_VERSION")); + assert_eq!(commit(), None); + } + + #[test] + fn the_nightly_identities_are_distinct_from_stable() { + assert_ne!(Channel::NightlyV1.app_id(), Channel::Stable.app_id()); + assert_ne!(NIGHTLY_PACKAGE_ID, NIGHTLY_APP_ID); + assert_eq!(Channel::Stable.app_id(), APP_ID); + assert_eq!(Channel::NightlyV1.name(), "DesignCraft Nightly"); + assert!(Channel::NightlyV1.is_nightly() && !Channel::Stable.is_nightly()); + } +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index e9f6c05df..8a9be6639 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -17,6 +17,7 @@ pub const UPDATE_APP: craft_update::app::App = craft_update::app::App { pub mod about; pub mod canvas; +pub mod channel; pub mod chrome; pub mod control; pub mod credits; diff --git a/crates/ui-egui/src/updates_ui.rs b/crates/ui-egui/src/updates_ui.rs index 5414a4815..9064eeeb9 100644 --- a/crates/ui-egui/src/updates_ui.rs +++ b/crates/ui-egui/src/updates_ui.rs @@ -25,6 +25,13 @@ pub(crate) struct Runtime { /// The web build has no updater; its Help ▸ Check for Updates opens a window with a fixed message. #[cfg(target_arch = "wasm32")] pub(crate) manual_window_open: bool, + /// A copy whose updates another program installs (a Launcher Nightly): Help ▸ Check for Updates + /// says so, and the updater never runs or offers a build that would replace this channel. + #[cfg(not(target_arch = "wasm32"))] + managed: Option<&'static str>, + /// The managed-copy message window is open. + #[cfg(not(target_arch = "wasm32"))] + managed_window_open: bool, } impl Default for Runtime { @@ -40,6 +47,10 @@ impl Default for Runtime { repaint: None, #[cfg(target_arch = "wasm32")] manual_window_open: false, + #[cfg(not(target_arch = "wasm32"))] + managed: None, + #[cfg(not(target_arch = "wasm32"))] + managed_window_open: false, } } } @@ -50,11 +61,36 @@ impl DesignApp { pub fn set_startup_update_check(&mut self, on: bool) { self.updates_rt.startup_check = on; } + + /// This copy's updates are installed by `who` (the Launcher for a Nightly): no check, no offer, + /// and Help ▸ Check for Updates explains who updates it. + #[cfg(not(target_arch = "wasm32"))] + pub fn set_updates_managed(&mut self, who: Option<&'static str>) { + self.updates_rt.managed = who; + if who.is_some() { + self.updates_rt.startup_check = false; + self.updates_rt.check_requested = false; + } + } + + /// Whether another program installs this copy's updates. + #[cfg(not(target_arch = "wasm32"))] + pub fn updates_managed(&self) -> bool { + self.updates_rt.managed.is_some() + } } pub(crate) fn check(app: &mut DesignApp) -> Result { #[cfg(not(target_arch = "wasm32"))] { + if app.updates_rt.managed.is_some() { + // Explain the Launcher instead of offering a build that would replace this channel. + app.updates_rt.managed_window_open = true; + if let Some(ctx) = &app.updates_rt.repaint { + ctx.request_repaint(); + } + return Ok(Value::Null); + } app.updates_rt.check_requested = true; if let Some(ctx) = &app.updates_rt.repaint { ctx.request_repaint(); @@ -73,6 +109,10 @@ pub(crate) fn tick(app: &mut DesignApp, ctx: &egui::Context) { { let rt = &mut app.updates_rt; rt.repaint = Some(ctx.clone()); + if rt.managed.is_some() { + // Never tick a managed copy's updater: it would offer the stable channel's build. + return; + } if std::mem::take(&mut rt.check_requested) { rt.updater.check_now(ctx); } else if rt.startup_check { @@ -95,6 +135,32 @@ fn result_window_shows(status: &Status, prompt_open: bool) -> bool { pub(crate) fn show(app: &mut DesignApp, ctx: &egui::Context) { #[cfg(not(target_arch = "wasm32"))] { + if let Some(who) = app.updates_rt.managed + && app.updates_rt.managed_window_open + { + let mut open = true; + let title = crate::i18n::tr(&app.ui.language, "DesignCraft Updates"); + let ok_label = crate::i18n::tr(&app.ui.language, "OK"); + egui::Window::new(title) + .open(&mut open) + .collapsible(false) + .resizable(false) + .pivot(egui::Align2::CENTER_CENTER) + .default_pos(ctx.content_rect().center()) + .show(ctx, |ui| { + ui.label(format!("Updates are managed by {who}.")); + ui.add_space(8.0); + if ui.button(ok_label).clicked() { + app.updates_rt.managed_window_open = false; + } + }); + if !open { + app.updates_rt.managed_window_open = false; + } + } + if app.updates_rt.managed.is_some() { + return; + } // The updater asks to close only when no document has unsaved changes; the install starts when the app exits. let clean = !app.session.documents().iter().any(|d| d.is_dirty()); match app.updates_rt.updater.show_if(ctx, clean) { @@ -144,6 +210,22 @@ mod tests { use super::*; use designcraft_engine::Session; + #[test] + #[cfg(not(target_arch = "wasm32"))] + fn a_managed_copy_never_checks_and_explains_who_updates_it() { + let mut app = DesignApp::new(Session::new(), Default::default()); + app.set_startup_update_check(true); + app.set_updates_managed(Some("ArtCraft Launcher")); + assert!(app.updates_managed()); + check(&mut app).unwrap(); + assert!(app.updates_rt.managed_window_open, "Help ▸ Check for Updates explains the Launcher"); + assert!(!app.updates_rt.check_requested, "a managed copy must not ask the stable feed"); + tick(&mut app, &egui::Context::default()); + assert!(!app.updates_rt.startup_check, "a managed copy never checks at start"); + app.set_updates_managed(None); + assert!(!app.updates_managed()); + } + #[test] fn default_runtime_is_idle() { let rt = Runtime::default(); diff --git a/docs/nightly-release-preparation.md b/docs/nightly-release-preparation.md new file mode 100644 index 000000000..53826e20d --- /dev/null +++ b/docs/nightly-release-preparation.md @@ -0,0 +1,89 @@ +# 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 and no automatic dispatch transport yet. The installed policy +[`.github/nightly-signing-policy.json`](../.github/nightly-signing-policy.json) is the v3 +policy for DesignCraft. Once `nightly.yml` lands on `main`, populate `producer_workflow_id` from: + +```bash +gh api repos/storytold/designcraft/actions/workflows/nightly.yml --jq .id +``` + +The callers pass no platform secrets. The unsigned reusable caller's maximum OIDC/attestation +permissions are for its isolated attester; its compiler narrows to contents and Actions read +only, with no OIDC, attestation write, release environment or platform signing secrets. +Shared tooling is pinned to `605d58766e8f536564da8fc81d3676ac86816dea`, the craft-common-actions +main commit that merged [#339](https://github.com/storytold/craft-common-actions/pull/339) (bounded +lineage compares and an issue reread at the end of candidate admission) on top of +[#342](https://github.com/storytold/craft-common-actions/pull/342) (policy v3, the `platforms` input +and the Linux and macOS legs). Both callers name it in `uses` and `tooling-revision`. A pin is reviewed +source availability, not provider, queue, native signing or crypto qualification. +Existing stable workflows are unchanged. + +**The shared-workflow port is a prerequisite.** At this pin both reusable workflows admit only +PhotoCraft: `nightly-unsigned.yml` requires `inputs.app-name == 'photocraft'` and +`github.repository == 'storytold/photocraft'` on its build jobs, and `nightly-release.yml` requires the +same repository in `validate` and every signing job (its concurrency group is +`craft-release-ref-signer-photocraft`). A DesignCraft dispatch therefore builds and signs nothing until +`storytold/craft-common-actions` admits `storytold/designcraft`. No dispatch can produce a release before +that port, and both callers' `uses`, `tooling-revision` and the policy pins must move to the same +reviewed revision together. The port is craft-common-actions #363 ("run the shared nightly pipeline for any +reviewed registry app"); until it merges these callers are inert. + +**First runs.** The first runs are manual dispatches in this order: `nightly.yml` on main (only a +listed manual actor passes the producer's plan step), then `nightly-sign.yml` on `release` with that +producer run ID and attempt, by a listed manual actor. + +**Manual actors.** `bflatastic`, `dylanmtaylor`, `echelon`, `FredApps` and `skylartaylor`, in the +producer's `manual-actors` and the policy's `manual_actors`. The list mirrors the release-managers +team (id 19837241), leaving out `echelon-robot`; update it by PR in both places when the team changes. + +**Admission timing.** The candidate check reads the newest CI run on the candidate commit and +main's latest finished Sonar analysis, so 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, Windows included), and the release-ref signer admits +platforms only from the protected policy, so there is no separate Linux or macOS caller job and +the signer caller has no platform input. + +## Installed policy values and their sources + +Read on 2026-11-24; re-read anything that may have moved (including `producer_workflow_id` after +`nightly.yml` reaches `main`, and SonarCloud debt/conditions) before the policy is promoted to `release`. + +| Field | Value | Source | +|---|---|---| +| `repository_id` | `1400018213` | `gh api repos/storytold/designcraft --jq .id` | +| `producer_workflow_id` | `null` (pending `main` merge) | Read `gh api repos/storytold/designcraft/actions/workflows/nightly.yml --jq .id` after `nightly.yml` reaches `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 | Storytold stable signing identities (`windows-x86_64`, `linux-x86_64`, `macos-aarch64`) | +| `candidate_policy.required_workflows` | CI (`ci.yml`, workflow `380135818`), `gate / gate (ubuntu-24.04)` | Workflow list API and recent `main` push runs | +| `candidate_policy.sonar` | `storytold` / `storytold_designcraft`, app `12526` | `sonar-project.properties` | + +## Ownership and interface + +- `.github/workflows/nightly.yml`: default-main registration of the unsigned producer, named + `DesignCraft 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 (`designcraft-nightly-release`, + `cancel-in-progress: false`, `queue: max`) is distinct from stable. 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 DesignCraft nightly callers and policy +contract locally: exact context guards, manual-actor parity, no registered schedule, no-cache and +no-platform-secret boundaries, signer root concurrency serialization, shared tooling pin parity, +and v3 policy structure/identities. diff --git a/packaging/linux/flatpak-bundle.sh b/packaging/linux/flatpak-bundle.sh index 40301a1fb..3a3f97a7c 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.designcraft +FLATPAK_ID="$APP_ID" +# The remote indexes both app IDs on the stable ref branch; IDs isolate installations. +FLATPAK_BRANCH=stable +if [[ "${DESIGNCRAFT_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,78 @@ rm -rf "$WORK" mkdir -p "$WORK/stage" tar -xzf "$TARBALL" -C "$WORK/stage" --strip-components=1 [[ -x "$WORK/stage/bin/designcraft" ]] || { echo "error: $TARBALL has no bin/designcraft" >&2; exit 1; } -cp "$HERE/flatpak/$APP_ID.bundle.yml" "$WORK/$APP_ID.yml" +if [[ "$FLATPAK_ID" != "$APP_ID" ]]; then + mv "$WORK/stage/bin/designcraft" "$WORK/stage/bin/designcraft-bin" + cat >"$WORK/stage/bin/designcraft" <<'WRAPPER' +#!/bin/sh +# Start the compiled nightly-v1 flavor inside the sandbox. The profile is the Launcher's protocol +# and stays in this bundle's own per-app home (ai.storyteller.designcraft.nightly), never the +# stable bundle's folder; the app refuses a DESIGNCRAFT_CONFIG_DIR override. +set -eu +real_bin=/app/libexec/designcraft +if [ "${1:-}" = "--launch-profile" ] || [ "${1:-}" = "--profile-root" ]; then + # The Launcher already supplied the protocol: pass its command line through untouched. + exec "$real_bin" "$@" +fi +if [ "${1:-}" = "--version" ] || [ "${1:-}" = "-V" ]; then + exec "$real_bin" "$@" +fi +profile_root="${XDG_DATA_HOME:-${HOME:?HOME is required}/.local/share}/designcraft-nightly" +if [ "${1:-}" = "--" ]; then + # The caller's own separator stays the only one. + exec "$real_bin" --launch-profile nightly-v1 --profile-root "$profile_root" "$@" +fi +exec "$real_bin" --launch-profile nightly-v1 --profile-root "$profile_root" -- "$@" +WRAPPER + chmod 755 "$WORK/stage/bin/designcraft" + sed -e "s|^Icon=$APP_ID$|Icon=$FLATPAK_ID|" \ + -e "s|^Name=DesignCraft$|Name=DesignCraft Nightly|" \ + -e 's|^StartupWMClass=.*|StartupWMClass=ai.storyteller.designcraft.nightly-v1|' \ + -e '/^MimeType=/d' \ + "$WORK/stage/share/applications/$APP_ID.desktop" >"$WORK/stage/share/applications/$FLATPAK_ID.desktop" + rm -f "$WORK/stage/share/applications/$APP_ID.desktop" + sed -e "s|$APP_ID|$FLATPAK_ID|g" \ + -e "s|DesignCraft|DesignCraft Nightly|g" \ + -e "s|$APP_ID.desktop|$FLATPAK_ID.desktop|g" \ + -e "s|$APP_ID|$FLATPAK_ID|g" \ + "$WORK/stage/share/metainfo/$APP_ID.metainfo.xml" >"$WORK/stage/share/metainfo/$FLATPAK_ID.metainfo.xml" + rm -f "$WORK/stage/share/metainfo/$APP_ID.metainfo.xml" + mv "$WORK/stage/share/mime/packages/$APP_ID.xml" "$WORK/stage/share/mime/packages/$FLATPAK_ID.xml" + NIGHTLY_ICON="$ROOT/assets/app-icon/designcraft-nightly.png" + if [[ ! -f "$NIGHTLY_ICON" ]]; then + NIGHTLY_ICON="$ROOT/assets/app-icon/hicolor/256x256/apps/$APP_ID.png" + fi + rm -rf "$WORK/stage/share/icons/hicolor" + install -Dm644 "$NIGHTLY_ICON" \ + "$WORK/stage/share/icons/hicolor/256x256/apps/$FLATPAK_ID.png" + sed -e "s|ai\.storyteller\.designcraft|$FLATPAK_ID|g" \ + -e 's|- install -Dm755 bin/designcraft /app/bin/designcraft|- install -Dm755 bin/designcraft-bin /app/libexec/designcraft\n - install -Dm755 bin/designcraft /app/bin/designcraft|' \ + "$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=designcraft-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=designcraft-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 d7d88a24c..ac4638de3 100644 --- a/packaging/linux/nfpm.yaml +++ b/packaging/linux/nfpm.yaml @@ -3,7 +3,7 @@ # exports VERSION and NFPM_ARCH. The Arch package is built by the release workflow's makepkg job. # # nfpm package -f packaging/linux/nfpm.yaml -p deb -t dist/release/ -name: designcraft +name: ${NFPM_NAME} arch: ${NFPM_ARCH} platform: linux version: ${VERSION} @@ -65,12 +65,15 @@ overrides: - xdg-desktop-portal contents: - - src: ${STAGE}/usr/bin/designcraft - dst: /usr/bin/designcraft + - src: ${STAGE}/usr/bin/${NFPM_BIN} + dst: /usr/bin/${NFPM_BIN} file_info: { mode: 0755 } - - src: ${STAGE}/usr/bin/designcraft-cli - dst: /usr/bin/designcraft-cli + - src: ${STAGE}/usr/bin/${NFPM_CLI} + dst: /usr/bin/${NFPM_CLI} file_info: { mode: 0755 } + - src: ${STAGE}/usr/lib/ + dst: /usr/lib/ + type: tree - src: ${STAGE}/usr/share/ dst: /usr/share/ type: tree diff --git a/packaging/linux/nightly-arch-launch.sh b/packaging/linux/nightly-arch-launch.sh new file mode 100755 index 000000000..3b43fc676 --- /dev/null +++ b/packaging/linux/nightly-arch-launch.sh @@ -0,0 +1,20 @@ +#!/bin/sh +# Start the compiled nightly-v1 flavor from the Arch package. The profile is the Launcher's +# protocol (the app refuses a DESIGNCRAFT_CONFIG_DIR override), so this launcher passes the same +# pair the Launcher will. +set -eu +here="$(CDPATH='' cd -- "$(dirname -- "$0")" && pwd)" +real_bin="$here/.designcraft-nightly/designcraft" +if [ "${1:-}" = "--launch-profile" ] || [ "${1:-}" = "--profile-root" ]; then + # The Launcher already supplied the protocol: pass its command line through untouched. + exec "$real_bin" "$@" +fi +if [ "${1:-}" = "--version" ] || [ "${1:-}" = "-V" ]; then + exec "$real_bin" "$@" +fi +profile_root="${XDG_DATA_HOME:-${HOME:?HOME is required}/.local/share}/designcraft-nightly" +if [ "${1:-}" = "--" ]; then + # The caller's own separator stays the only one. + exec "$real_bin" --launch-profile nightly-v1 --profile-root "$profile_root" "$@" +fi +exec "$real_bin" --launch-profile nightly-v1 --profile-root "$profile_root" -- "$@" diff --git a/packaging/linux/nightly-arch-tar-test.sh b/packaging/linux/nightly-arch-tar-test.sh new file mode 100755 index 000000000..3c9f98106 --- /dev/null +++ b/packaging/linux/nightly-arch-tar-test.sh @@ -0,0 +1,71 @@ +#!/usr/bin/env bash +# Validate the staged Arch launcher without building or opening DesignCraft. +set -euo pipefail + +HERE="$(cd "$(dirname "$0")" && pwd)" +work="$(mktemp -d)" +trap 'rm -rf "$work"' EXIT +stage="$work/source" +dst="$work/dist" +base=designcraft-0.0.1-nightly.1-linux-x86_64 +mkdir -p "$stage/bin" "$dst" "$work/extract" + +# A local argv recorder stands in for the compiled binary. It never opens a UI. +cat >"$stage/bin/designcraft" <<'RECORDER' +#!/bin/sh +printf 'DESIGNCRAFT_CONFIG_DIR=<%s>\n' "${DESIGNCRAFT_CONFIG_DIR-UNSET}" +for arg in "$@"; do + printf '<%s>\n' "$arg" +done +RECORDER +chmod 755 "$stage/bin/designcraft" +cp "$stage/bin/designcraft" "$stage/bin/designcraft-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/designcraft" "$bin/designcraft-nightly" +mv "$bin/designcraft-cli" "$bin/designcraft-nightly-cli" + +[[ ! -e "$stage/bin/.designcraft-nightly" ]] +cmp "$stage/bin/designcraft" "$bin/.designcraft-nightly/designcraft" +cmp "$stage/bin/designcraft-cli" "$bin/designcraft-nightly-cli" +export HOME="$work/home with space" +unset XDG_DATA_HOME DESIGNCRAFT_CONFIG_DIR +expect() { + expected="$1" + shift + actual=$(PATH="$bin:$PATH" designcraft-nightly "$@") + if [[ "$actual" != "$expected" ]]; then + printf 'expected:\n%s\nactual:\n%s\n' "$expected" "$actual" >&2 + exit 1 + fi +} +# The nightly profile is the Launcher's selector/root pair, never an environment override. +pair() { + printf 'DESIGNCRAFT_CONFIG_DIR=\n<--launch-profile>\n\n<--profile-root>\n<%s>\n<-->\n%s' "$1" "$2" +} +expect "$(pair "$HOME/.local/share/designcraft-nightly" '')" +export XDG_DATA_HOME="$work/xdg with space" +expect "$(pair "$XDG_DATA_HOME/designcraft-nightly" "$(printf '<%s>\n<%s>\n' 'doc with spaces.dc' '--other-name.dc')")" \ + 'doc with spaces.dc' '--other-name.dc' +# Version queries stay plain so a Launcher or a runner can ask before any profile exists. +expect "$(printf 'DESIGNCRAFT_CONFIG_DIR=\n<--version>\n')" --version +expect "$(printf 'DESIGNCRAFT_CONFIG_DIR=\n<-V>\n')" -V +# A caller that already uses the protocol (the Launcher) reaches the binary untouched. +expect "$(printf 'DESIGNCRAFT_CONFIG_DIR=\n<--launch-profile>\n\n<--profile-root>\n<%s>\n<-->\n<%s>\n' \ + "$work/launcher root" 'doc.dc')" \ + --launch-profile nightly-v1 --profile-root "$work/launcher root" -- doc.dc +# A caller's own separator stays the only one, and a flag after it is a document. +expect "$(pair "$XDG_DATA_HOME/designcraft-nightly" "$(printf '<%s>\n' '--version')")" -- --version +# The launcher never sets or clears the stable override itself: it passes the profile pair and +# leaves an inherited value alone, which the app then refuses with its own message. +DESIGNCRAFT_CONFIG_DIR="$work/explicit with space" expect \ + "$(printf 'DESIGNCRAFT_CONFIG_DIR=<%s>\n<--launch-profile>\n\n<--profile-root>\n<%s>\n<-->\n<%s>\n' \ + "$work/explicit with space" "$XDG_DATA_HOME/designcraft-nightly" 'sample.dc')" sample.dc + +echo "PASS: Arch Nightly handoff starts the flavor with the Launcher's profile and arguments" diff --git a/packaging/linux/nightly-arch-tar.sh b/packaging/linux/nightly-arch-tar.sh new file mode 100755 index 000000000..8bbe9f581 --- /dev/null +++ b/packaging/linux/nightly-arch-tar.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Stage the DesignCraft 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/.designcraft-nightly" +mv "$stage/bin/designcraft" "$stage/bin/.designcraft-nightly/designcraft" +cp "$here/nightly-arch-launch.sh" "$stage/bin/designcraft" +chmod 755 "$stage/bin/designcraft" +tar -C "$work" -czf "$destination/$basename.tar.gz" "$basename" +echo "wrote $destination/$basename.tar.gz" diff --git a/packaging/linux/nightly.sh b/packaging/linux/nightly.sh new file mode 100755 index 000000000..052645bc4 --- /dev/null +++ b/packaging/linux/nightly.sh @@ -0,0 +1,51 @@ +#!/usr/bin/env bash +# App-owned GUI-only nightly tar: no FUSE/AppImage, CLI, association or install hooks. +set -euo pipefail +ARCH= +while [[ $# -gt 0 ]]; do + case "$1" in + --arch) [[ $# -ge 2 ]] || { echo 'missing --arch value' >&2; exit 2; }; ARCH="$2"; shift 2 ;; + -h|--help) echo 'Usage: nightly.sh --arch x86_64'; exit 0 ;; + *) echo "unsupported nightly argument: $1" >&2; exit 2 ;; + esac +done +[[ "$ARCH" == x86_64 && "$(uname -s)" == Linux ]] || { echo 'only native Linux x86_64 nightly packaging is supported' >&2; exit 2; } +. "$(dirname "${BASH_SOURCE[0]}")/../nightly-common.sh" +nightly_init linux "$ARCH" x86_64-unknown-linux-gnu +OUTPUT="$DIST/designcraft-$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" +cp "$NIGHTLY_GUI" "$STAGE/designcraft-bin" +chmod 755 "$STAGE/designcraft-bin" +# An unpacked nightly starts the flavor the way every other Linux package does (the Launcher's +# selector/root pair), so it never falls back to stable's ~/.config/designcraft profile. +cat >"$STAGE/designcraft" <<'LAUNCHER' +#!/bin/sh +set -eu +here="$(CDPATH='' cd -- "$(dirname -- "$0")" && pwd)" +real_bin="$here/designcraft-bin" +if [ "${1:-}" = "--launch-profile" ] || [ "${1:-}" = "--profile-root" ]; then + # The Launcher already supplied the protocol: pass its command line through untouched. + exec "$real_bin" "$@" +fi +if [ "${1:-}" = "--version" ] || [ "${1:-}" = "-V" ]; then + exec "$real_bin" "$@" +fi +profile_root="${XDG_DATA_HOME:-${HOME:?HOME is required}/.local/share}/designcraft-nightly" +if [ "${1:-}" = "--" ]; then + # The caller's own separator stays the only one. + exec "$real_bin" --launch-profile nightly-v1 --profile-root "$profile_root" "$@" +fi +exec "$real_bin" --launch-profile nightly-v1 --profile-root "$profile_root" -- "$@" +LAUNCHER +chmod 755 "$STAGE/designcraft" +cp "$ROOT/assets/app-icon/designcraft-nightly.png" "$STAGE/designcraft-nightly.png" +nightly_copy_notices "$STAGE" +# The staged launcher must reach the built flavor, not just the binary it names. +packed_version="$("$STAGE/designcraft" --version)" || nightly_die 'the archive launcher could not start the built binary' +[[ "$packed_version" == "DesignCraft $VERSION (nightly-v1)" ]] || nightly_die 'the archive launcher is not the prepared nightly identity' +# 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 f6c3e9cc0..a83488e15 100755 --- a/packaging/linux/package.sh +++ b/packaging/linux/package.sh @@ -13,7 +13,7 @@ # it) and declares provides/conflicts against the AUR packages. Building a second one here under # the same asset name is what made the published package depend on upload order. # -# Usage: packaging/linux/package.sh [--skip-build] [--formats "appimage deb rpm tar"] +# Usage: packaging/linux/package.sh [--skip-build] [--formats "appimage deb rpm tar"] [--arch-tar-dir DIRECTORY] # # Needs: cargo; nfpm for deb/rpm (https://nfpm.goreleaser.com); appimagetool for the AppImage # (downloaded into $CARGO_TARGET_DIR if missing). Build on an old distro (CI: Ubuntu 22.04, @@ -27,10 +27,16 @@ APP_ID=ai.storyteller.designcraft 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,16p' "$0"; exit 0 ;; *) echo "unknown argument: $1" >&2; exit 2 ;; esac @@ -44,9 +50,20 @@ case "$ARCH" in *) echo "unsupported architecture $ARCH" >&2; exit 2 ;; esac export DESIGNCRAFT_MAINTAINER="${DESIGNCRAFT_MAINTAINER:-DesignCraft maintainers }" +IS_NIGHTLY=0 +if [[ "${DESIGNCRAFT_BUILD_CHANNEL:-}" == nightly-v1 || "$VERSION" == *-nightly* ]]; then + IS_NIGHTLY=1 + export DESIGNCRAFT_BUILD_CHANNEL=nightly-v1 + export DESIGNCRAFT_OVERRIDE_VERSION="$VERSION" +fi BASENAME="designcraft-$VERSION-linux-$ARCH" -echo "==> DesignCraft $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 "==> DesignCraft $VERSION for Linux $ARCH ($FORMATS, channel=${DESIGNCRAFT_BUILD_CHANNEL:-stable})" has() { local fmt="$1" @@ -75,6 +92,11 @@ install -Dm755 "$BIN/designcraft" "$STAGE/usr/bin/designcraft" install -Dm755 "$BIN/designcraft-cli" "$STAGE/usr/bin/designcraft-cli" "${CROSS_COMPILE:-}strip" "$STAGE/usr/bin/designcraft" "$STAGE/usr/bin/designcraft-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.designcraft.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" install -Dm644 "$HERE/$APP_ID.thumbnailer" "$STAGE/usr/share/thumbnailers/$APP_ID.thumbnailer" mkdir -p "$STAGE/usr/share/metainfo" @@ -100,13 +122,88 @@ if has tar; then echo "wrote $DIST/$BASENAME.tar.gz" fi +# The Arch handoff keeps the same basename as the plain tarball in a separate directory. +# Flatpak, OCI and direct tar consumers still get the original binary, not this launcher. +if [[ -n "$ARCH_TAR_DIR" ]]; then + mkdir -p "$ARCH_TAR_DIR" + if [[ "$(cd "$ARCH_TAR_DIR" && pwd -P)" == "$(cd "$DIST" && pwd -P)" ]]; then + echo "error: the Arch tar directory must differ from the release directory" >&2 + exit 2 + fi + bash "$HERE/nightly-arch-tar.sh" "$STAGE/usr" "$WORK/arch-tar" "$ARCH_TAR_DIR" "$BASENAME" +fi + # ---- .deb / .rpm -------------------------------------------------------------------------------- if has deb || has rpm; then command -v nfpm >/dev/null || { echo "error: nfpm not found (https://nfpm.goreleaser.com/install/)" >&2; exit 1; } export VERSION export NFPM_ARCH="$DEB_ARCH" + NFPM_STAGE="$STAGE" + export NFPM_NAME="designcraft" + export NFPM_BIN="designcraft" + export NFPM_CLI="designcraft-cli" + if [[ "$IS_NIGHTLY" = 1 ]]; then + NIGHTLY_DESK_ID="$APP_ID.nightly-v1" + export NFPM_NAME="designcraft-nightly" + export NFPM_BIN="designcraft-nightly" + export NFPM_CLI="designcraft-nightly-cli" + NFPM_STAGE="$WORK/nfpm-root" + rm -rf "$NFPM_STAGE" + cp -R "$STAGE" "$NFPM_STAGE" + install -Dm755 "$NFPM_STAGE/usr/bin/designcraft" "$NFPM_STAGE/usr/lib/designcraft-nightly/designcraft" + cat >"$NFPM_STAGE/usr/bin/$NFPM_BIN" <<'WRAPPER' +#!/bin/sh +# Start the compiled nightly-v1 flavor. Its profile is the Launcher's protocol (the app refuses a +# DESIGNCRAFT_CONFIG_DIR override), so this wrapper passes the same pair the Launcher will. +set -eu +real_bin=/usr/lib/designcraft-nightly/designcraft +if [ "${1:-}" = "--launch-profile" ] || [ "${1:-}" = "--profile-root" ]; then + # The Launcher already supplied the protocol: pass its command line through untouched. + exec "$real_bin" "$@" +fi +if [ "${1:-}" = "--version" ] || [ "${1:-}" = "-V" ]; then + exec "$real_bin" "$@" +fi +profile_root="${XDG_DATA_HOME:-${HOME:?HOME is required}/.local/share}/designcraft-nightly" +if [ "${1:-}" = "--" ]; then + # The caller's own separator stays the only one. + exec "$real_bin" --launch-profile nightly-v1 --profile-root "$profile_root" "$@" +fi +exec "$real_bin" --launch-profile nightly-v1 --profile-root "$profile_root" -- "$@" +WRAPPER + chmod 755 "$NFPM_STAGE/usr/bin/$NFPM_BIN" + rm -f "$NFPM_STAGE/usr/bin/designcraft" + mv "$NFPM_STAGE/usr/bin/designcraft-cli" "$NFPM_STAGE/usr/bin/$NFPM_CLI" + mv "$NFPM_STAGE/usr/share/doc/designcraft" "$NFPM_STAGE/usr/share/doc/$NFPM_NAME" + sed -e "s#^Exec=designcraft\([[:space:]]\|$\)#Exec=$NFPM_BIN\1#" \ + -e "s|^TryExec=designcraft$|TryExec=$NFPM_BIN|" \ + -e "s|^Icon=$APP_ID$|Icon=$NIGHTLY_DESK_ID|" \ + -e "s|^Name=DesignCraft$|Name=DesignCraft 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|DesignCraft|DesignCraft Nightly|g" \ + -e "s|$APP_ID.desktop|$NIGHTLY_DESK_ID.desktop|g" \ + -e "s|$APP_ID|$NIGHTLY_DESK_ID|g" \ + -e "s|designcraft|$NFPM_BIN|g" \ + "$NFPM_STAGE/usr/share/metainfo/$APP_ID.metainfo.xml" >"$NFPM_STAGE/usr/share/metainfo/$NIGHTLY_DESK_ID.metainfo.xml" + rm -f "$NFPM_STAGE/usr/share/metainfo/$APP_ID.metainfo.xml" + rm -rf "$NFPM_STAGE/usr/share/mime" "$NFPM_STAGE/usr/share/thumbnailers" + NIGHTLY_ICON="$ROOT/assets/app-icon/designcraft-nightly.png" + if [[ ! -f "$NIGHTLY_ICON" ]]; then + NIGHTLY_ICON="$ROOT/assets/app-icon/hicolor/256x256/apps/$APP_ID.png" + fi + rm -rf "$NFPM_STAGE/usr/share/icons/hicolor" + install -Dm644 "$NIGHTLY_ICON" \ + "$NFPM_STAGE/usr/share/icons/hicolor/256x256/apps/$NIGHTLY_DESK_ID.png" + fi # nfpm expands env vars in fields like `version` and `arch`, but not in `contents[].src`. - sed "s|\${STAGE}|$STAGE|g" "$HERE/nfpm.yaml" >"$WORK/nfpm.yaml" + DROP_LIB_TREE= + # shellcheck disable=SC2016 + [[ -d "$NFPM_STAGE/usr/lib" ]] || DROP_LIB_TREE='\|^ - src: \${STAGE}/usr/lib/|,+2d;' + # shellcheck disable=SC2016 + sed "${DROP_LIB_TREE}s|\${STAGE}|$NFPM_STAGE|g;s|\${NFPM_BIN}|$NFPM_BIN|g;s|\${NFPM_CLI}|$NFPM_CLI|g" "$HERE/nfpm.yaml" >"$WORK/nfpm.yaml" for fmt in deb rpm; do if has "$fmt"; then (cd "$ROOT" && nfpm package -f "$WORK/nfpm.yaml" -p "$fmt" -t "$DIST/$BASENAME.$fmt"); fi done @@ -125,10 +222,51 @@ if has appimage; then cp -R "$STAGE" "$APPDIR" # Keep sctk-adwaita's MIT notice in the AppImage. install -Dm644 "$ROOT/NOTICE" "$APPDIR/usr/share/doc/designcraft/NOTICE" - ln -s usr/bin/designcraft "$APPDIR/AppRun" - cp "$HERE/$APP_ID.desktop" "$APPDIR/$APP_ID.desktop" - cp "$ROOT/assets/app-icon/hicolor/256x256/apps/$APP_ID.png" "$APPDIR/$APP_ID.png" - ln -s "$APP_ID.png" "$APPDIR/.DirIcon" + if [[ "$IS_NIGHTLY" = 1 ]]; then + APPIMAGE_ID="$APP_ID.nightly-v1" + cat >"$APPDIR/AppRun" <<'APPRUN' +#!/bin/sh +# Start the compiled nightly-v1 flavor. A real file, never a symlink to the binary: the flavor +# needs the Launcher's profile pair, and the app refuses a DESIGNCRAFT_CONFIG_DIR override. +set -eu +APPDIR="${APPDIR:-$(cd "$(dirname "$0")" && pwd)}" +real_bin="$APPDIR/usr/bin/designcraft" +if [ "${1:-}" = "--launch-profile" ] || [ "${1:-}" = "--profile-root" ]; then + # The Launcher already supplied the protocol: pass its command line through untouched. + exec "$real_bin" "$@" +fi +if [ "${1:-}" = "--version" ] || [ "${1:-}" = "-V" ]; then + exec "$real_bin" "$@" +fi +profile_root="${XDG_DATA_HOME:-${HOME:?HOME is required}/.local/share}/designcraft-nightly" +if [ "${1:-}" = "--" ]; then + # The caller's own separator stays the only one. + exec "$real_bin" --launch-profile nightly-v1 --profile-root "$profile_root" "$@" +fi +exec "$real_bin" --launch-profile nightly-v1 --profile-root "$profile_root" -- "$@" +APPRUN + chmod 755 "$APPDIR/AppRun" + sed -e "s|^Icon=$APP_ID$|Icon=$APPIMAGE_ID|" \ + -e "s|^Name=DesignCraft$|Name=DesignCraft 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" + NIGHTLY_ICON="$ROOT/assets/app-icon/designcraft-nightly.png" + if [[ ! -f "$NIGHTLY_ICON" ]]; then + NIGHTLY_ICON="$ROOT/assets/app-icon/hicolor/256x256/apps/$APP_ID.png" + fi + rm -rf "$APPDIR/usr/share/icons/hicolor" + install -Dm644 "$NIGHTLY_ICON" \ + "$APPDIR/usr/share/icons/hicolor/256x256/apps/$APPIMAGE_ID.png" + cp "$NIGHTLY_ICON" "$APPDIR/$APPIMAGE_ID.png" + ln -s "$APPIMAGE_ID.png" "$APPDIR/.DirIcon" + else + ln -s usr/bin/designcraft "$APPDIR/AppRun" + cp "$HERE/$APP_ID.desktop" "$APPDIR/$APP_ID.desktop" + cp "$ROOT/assets/app-icon/hicolor/256x256/apps/$APP_ID.png" "$APPDIR/$APP_ID.png" + ln -s "$APP_ID.png" "$APPDIR/.DirIcon" + fi TOOL="${APPIMAGETOOL:-$(command -v appimagetool || true)}" if [[ -z "$TOOL" ]]; then @@ -155,11 +293,24 @@ 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/designcraft}" - UPDATE_INFO="gh-releases-zsync|${REPO%%/*}|${REPO#*/}|latest|designcraft-*-linux-$ARCH.AppImage.zsync" + UPDATE_ARGS=() + if [[ "$IS_NIGHTLY" = 0 ]]; then + UPDATE_INFO="gh-releases-zsync|${REPO%%/*}|${REPO#*/}|latest|designcraft-*-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 rather than stable `latest`. + NIGHTLY_ZSYNC_PATTERN="designcraft-*-nightly*-linux-$ARCH.AppImage.zsync" + if [[ "$VERSION" != *-nightly* ]]; then + NIGHTLY_ZSYNC_PATTERN="designcraft-*-linux-$ARCH.AppImage.zsync" + fi + UPDATE_INFO="gh-releases-zsync|${REPO%%/*}|${REPO#*/}|latest-pre|$NIGHTLY_ZSYNC_PATTERN" + 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 -u "$UPDATE_INFO" "$APPDIR" "$OUT") + (cd "$DIST" && ARCH="$ARCH" APPIMAGE_EXTRACT_AND_RUN=1 "$TOOL" --no-appstream "${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 000000000..21dc0a450 --- /dev/null +++ b/packaging/macos/nightly-lib.sh @@ -0,0 +1,170 @@ +# 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='DesignCraft Nightly.app' +MAC_NIGHTLY_ID='ai.storyteller.designcraft.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" =~ ^designcraft-(.+)-macos-aarch64-nightly\.zip$ ]] || return 1 + version="${BASH_REMATCH[1]}" + [[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+-nightly\.[0-9]{8}\.[0-9]+\.[0-9]+\.g[0-9a-f]{12}$ ]] || return 1 + printf '%s\n' "$version" +} + +# Every signing and notarization value is set, and the team is one Apple team ID. No ad-hoc fallback. +mac_nightly_require_secrets() { + local name + for name in "${MAC_NIGHTLY_SECRETS[@]}"; do + [[ -n "${!name:-}" ]] || mac_nightly_die "$name is not set: Nightly signing and notarization are required, with no ad-hoc fallback" + done + [[ "$APPLE_TEAM_ID" =~ ^[A-Z0-9]{10}$ ]] || mac_nightly_die 'APPLE_TEAM_ID is not an Apple team ID' + if [[ -n "${NIGHTLY_APPLE_TEAM_ID:-}" && "$NIGHTLY_APPLE_TEAM_ID" != "$APPLE_TEAM_ID" ]]; then + mac_nightly_die 'the signing team differs from the reviewed Nightly team (NIGHTLY_APPLE_TEAM_ID)' + fi +} + +# One line of `security find-identity -v -p codesigning`: the identity is a Developer ID Application of the team. +mac_nightly_identity_is_team() { + local line="$1" identity="$2" team="$3" + [[ "$line" == *" $identity "* && "$line" == *'"Developer ID Application: '*" ($team)\""* ]] +} + +# `codesign -d --verbose=2` of the signed bundle: the Nightly identifier, a Developer ID Application of the +# team, a secure timestamp and the hardened runtime (the checks of verify.sh, made strict). +mac_nightly_check_signature() { + local details="$1" team="$2" ok=0 + grep -Fqx "Identifier=$MAC_NIGHTLY_ID" <<<"$details" || { echo "error: the bundle is not signed as $MAC_NIGHTLY_ID" >&2; ok=1; } + grep -q '^Authority=Developer ID Application:' <<<"$details" || { echo 'error: not signed with a Developer ID Application identity' >&2; ok=1; } + grep -qx "TeamIdentifier=$team" <<<"$details" || { echo 'error: signed by a different team' >&2; ok=1; } + grep -q '^Timestamp=' <<<"$details" || { echo 'error: the signature has no secure timestamp' >&2; ok=1; } + grep -Eq '^CodeDirectory .*flags=0x[0-9a-f]+\([^)]*runtime' <<<"$details" || { echo 'error: not signed with the hardened runtime' >&2; ok=1; } + return "$ok" +} + +# `spctl --assess --type execute -vv`: Gatekeeper accepts the bundle as notarized. +mac_nightly_check_assessment() { + grep -q 'accepted' <<<"$1" && grep -qx 'source=Notarized Developer ID' <<<"$1" +} + +# Limits on an archive handed to `ditto -x`, set well above a normal Nightly bundle (the stable macOS +# app is about 280 MB packed) and low enough that a hostile archive cannot fill the runner's disk. +MAC_NIGHTLY_ZIP_MAX_ARCHIVE=$((1024 * 1024 * 1024)) +MAC_NIGHTLY_ZIP_MAX_EXPANDED=$((2 * 1024 * 1024 * 1024)) +MAC_NIGHTLY_ZIP_MAX_ENTRIES=20000 + +# 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. +# The archive is also bounded: its size, entry count and compressed bytes (so entries cannot overlap), +# and the bytes each entry really expands to, which are counted by inflating it here, not taken from +# the header that `ditto` would trust. Only stored and deflated entries are accepted. +mac_nightly_check_zip_entries() { + python3 -I - "$1" "$MAC_NIGHTLY_APP" "$MAC_NIGHTLY_ZIP_MAX_ARCHIVE" "$MAC_NIGHTLY_ZIP_MAX_EXPANDED" "$MAC_NIGHTLY_ZIP_MAX_ENTRIES" <<'PY' \ + || mac_nightly_die 'the archive has an entry outside the bundle, a link, a special file or more data than a Nightly bundle holds' +import os, stat, struct, sys, zipfile, zlib +archive, app = sys.argv[1:3] +max_archive, max_expanded, max_entries = map(int, sys.argv[3:6]) +if os.path.getsize(archive) > max_archive: + sys.exit("the archive is larger than a Nightly bundle") +CHUNK = 1 << 20 +with zipfile.ZipFile(archive) as z, open(archive, "rb") as raw: + infos = z.infolist() + if len(infos) > max_entries: + sys.exit(f"too many entries: {len(infos)}") + if sum(info.compress_size for info in infos) > os.path.getsize(archive): + sys.exit("entries share compressed data") + expanded = 0 + for info in infos: + 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}") + if info.is_dir(): + if info.file_size or info.compress_size: + sys.exit(f"directory with data: {name!r}") + continue + if not info.file_size and not info.compress_size: + continue + if info.compress_type not in (zipfile.ZIP_STORED, zipfile.ZIP_DEFLATED): + sys.exit(f"unsupported compression in {name!r}") + if info.file_size > max_expanded - expanded: + sys.exit("the archive expands to more than a Nightly bundle holds") + # Inflate the entry's own compressed bytes and count what comes out. + raw.seek(info.header_offset) + header = raw.read(30) + if len(header) != 30 or header[:4] != b"PK\x03\x04": + sys.exit(f"bad local header: {name!r}") + name_len, extra_len = struct.unpack(" 0 and not inflater.eof: + data = raw.read(min(CHUNK, left)) + if not data: + sys.exit(f"truncated entry: {name!r}") + left -= len(data) + pending = data + while pending: + out = inflater.decompress(pending, CHUNK) + total += len(out) + if total > info.file_size or total > max_expanded - expanded: + sys.exit(f"entry expands past its declared size: {name!r}") + pending = inflater.unconsumed_tail + if not inflater.eof or left or inflater.unused_data or total != info.file_size: + sys.exit(f"entry size does not match its data: {name!r}") + expanded += total +PY +} + +# An unpacked payload directory holds exactly the GUI-only Nightly bundle: one thin arm64 DesignCraft +# 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")" == DesignCraft ]] || mac_nightly_die 'Contents/MacOS must hold only the DesignCraft GUI (no CLI)' + [[ -f "$app/Contents/MacOS/DesignCraft" && -x "$app/Contents/MacOS/DesignCraft" ]] || mac_nightly_die 'missing executable GUI' + [[ "$(lipo -archs "$app/Contents/MacOS/DesignCraft")" == arm64 ]] || mac_nightly_die 'the GUI must be thin arm64' + plist="$app/Contents/Info.plist" + for key in CFBundleIdentifier CFBundleExecutable DesignCraftVersion; 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" == DesignCraft ]] ;; + DesignCraftVersion) [[ "$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 000000000..0c86f4bd6 --- /dev/null +++ b/packaging/macos/nightly-sign.sh @@ -0,0 +1,145 @@ +#!/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/designcraft--macos-aarch64-nightly.zip \ +# --output /abs//designcraft--macos-aarch64-nightly.zip +# +# Input: the unsigned archive nightly.sh made. Output: the same bundle signed with the Developer ID and +# hardened runtime, notarized, with the ticket stapled into the bundle, zipped without extended +# attributes. Writes only that file, never replacing one; the temporary keychain and work directory +# are removed on every exit. +# +# Env (all required, no ad-hoc or unnotarized fallback): APPLE_CERTIFICATE, APPLE_CERTIFICATE_PASSWORD, +# KEYCHAIN_PASSWORD, APPLE_ID, APPLE_PASSWORD, APPLE_TEAM_ID; optional NIGHTLY_APPLE_TEAM_ID (must +# equal APPLE_TEAM_ID) and RUNNER_TEMP (work directory base). +# +# Never compiles, and never runs anything from the payload: the version query runs on the signed +# bundle in a job without secrets (nightly-verify.sh). +set -euo pipefail +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +# shellcheck source=nightly-lib.sh +. "$HERE/nightly-lib.sh" +# shellcheck source=../nightly-common.sh +. "$HERE/../nightly-common.sh" + +ARCH='' INPUT='' OUTPUT='' +while [[ $# -gt 0 ]]; do + case "$1" in + --arch | --input | --output) + [[ $# -ge 2 ]] || mac_nightly_die "missing $1 value" + case "$1" in --arch) ARCH="$2" ;; --input) INPUT="$2" ;; --output) OUTPUT="$2" ;; esac + shift 2 ;; + -h | --help) sed -n '2,18p' "$0"; exit 0 ;; + *) mac_nightly_die "unsupported argument: $1" ;; + esac +done +[[ "$ARCH" == aarch64 ]] || mac_nightly_die 'only --arch aarch64 is supported' +[[ "$INPUT" == /* && "$OUTPUT" == /* ]] || mac_nightly_die '--input and --output must be absolute paths' +NAME="$(basename -- "$INPUT")" +VERSION="$(mac_nightly_version_from_asset "$NAME")" || mac_nightly_die 'the input is not a prepared Nightly archive name' +[[ "$(basename -- "$OUTPUT")" == "$NAME" ]] || mac_nightly_die 'the output must keep the archive name' +[[ -f "$INPUT" && ! -L "$INPUT" ]] || mac_nightly_die 'the input must be a regular file' +[[ ! -e "$OUTPUT" && ! -L "$OUTPUT" ]] || mac_nightly_die 'refusing to replace an existing output' +[[ -d "$(dirname -- "$OUTPUT")" && ! -L "$(dirname -- "$OUTPUT")" ]] || mac_nightly_die 'the output directory must exist' +mac_nightly_require_secrets +[[ "$(uname -s)" == Darwin ]] || mac_nightly_die 'signing needs macOS (codesign, notarytool, stapler)' + +BASE="${RUNNER_TEMP:-${TMPDIR:-/tmp}}" +WORK="$(mktemp -d "${BASE%/}/designcraft-nightly-sign.XXXXXX")" +# The keychain name is the one packaging/macos/import-cert.sh creates. +KEYCHAIN="$WORK/designcraft-signing.keychain-db" +cleanup() { + if [[ -e "$KEYCHAIN" ]]; then security delete-keychain "$KEYCHAIN" >/dev/null 2>&1 || rm -f -- "$KEYCHAIN"; fi + rm -rf -- "$WORK" +} +trap cleanup EXIT + +# ---- identity: import-cert.sh, into this run's private directory ------------------------------ +# An empty GITHUB_ENV makes it print the identity instead of exporting it to later steps. +imported="$(GITHUB_ENV='' RUNNER_TEMP="$WORK" DIST="$WORK/dist" bash "$HERE/import-cert.sh")" +IDENTITY="$(sed -n 's/^MACOS_SIGN_IDENTITY=//p' <<<"$imported")" +[[ "$IDENTITY" =~ ^[0-9A-F]{40}$ ]] || mac_nightly_die 'import-cert.sh did not import a signing identity' +# import-cert.sh opens its own private folder under this run's RUNNER_TEMP (designcraft-signing.XXXXXX) +# and names the keychain designcraft-signing.keychain-db there; it must stay inside this run. +KEYCHAIN="$(sed -n 's/^MACOS_KEYCHAIN=//p' <<<"$imported")" +[[ "$KEYCHAIN" == "$WORK"/* && -f "$KEYCHAIN" && ! -L "$KEYCHAIN" && "$KEYCHAIN" == */designcraft-signing.keychain-db ]] \ + || mac_nightly_die 'import-cert.sh did not keep its keychain in this run' +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 "==> DesignCraft 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/DesignCraft" +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 000000000..487018c12 --- /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/designcraft--macos-aarch64-nightly.zip --expect signed [--team ID] +# nightly-verify.sh --input /abs/designcraft--macos-aarch64-nightly.zip --expect unsigned +# +# Both: the archive holds only the GUI-only Nightly bundle with the exact DesignCraftVersion, 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 `DesignCraft (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}}/designcraft-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/DesignCraft" "$@" 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" == "DesignCraft $VERSION (nightly-v1)" ]] || mac_nightly_die "the version query ($*) reports '$out', not DesignCraft $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): DesignCraft $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 000000000..c5547d2b5 --- /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/designcraft--macos-aarch64-nightly.zip DesignCraft Nightly.app, unsigned +# +# Usage: packaging/macos/nightly.sh --arch aarch64 +# +# Required env (nightly-common.sh): DESIGNCRAFT_BUILD_CHANNEL=nightly-v1, DESIGNCRAFT_VERSION, +# DESIGNCRAFT_BUILD_SHA, DESIGNCRAFT_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/designcraft-$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/DesignCraft" +chmod 755 "$APP/Contents/MacOS/DesignCraft" +cp "$ROOT/assets/app-icon/designcraft-nightly.icns" "$APP/Contents/Resources/designcraft-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 "$DESIGNCRAFT_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 000000000..163fa0f9f --- /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.designcraft.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="DesignCraft Nightly", + CFBundleName="DesignCraft Nightly", + CFBundleIdentifier=IDENTIFIER, + CFBundleExecutable="DesignCraft", + CFBundleIconFile="designcraft-nightly", + CFBundleShortVersionString=match[1], + CFBundleVersion=match[1], + DesignCraftVersion=version, + DesignCraftBuildCommit=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 100644 index 000000000..fa5202b49 --- /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.designcraft.nightly") + self.assertEqual(rendered["CFBundleExecutable"], "DesignCraft") + self.assertEqual(rendered["DesignCraftVersion"], VERSION) + self.assertEqual(rendered["DesignCraftBuildCommit"], 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["DesignCraftVersion"], VERSION) + self.assertEqual(result["DesignCraftBuildCommit"], 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())["DesignCraftVersion"], 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 100644 index 000000000..33cf5cfbf --- /dev/null +++ b/packaging/macos/nightly_sign_tests.py @@ -0,0 +1,462 @@ +#!/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"designcraft-{VERSION}-macos-aarch64-nightly.zip" +APP = "DesignCraft 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.designcraft.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/DesignCraft" + exe.write_text(gui or f"#!/bin/sh\ntouch {self.ran}\necho 'DesignCraft {version} (nightly-v1)'\n") + exe.chmod(0o755) + (app / "Contents/Resources/designcraft-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.designcraft.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"designcraft-0.23.1-macos-aarch64.zip", f"designcraft-{VERSION}-macos-universal-nightly.zip", + f"designcraft-{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=designcraft-1234\nSignature=adhoc\nTeamIdentifier=not set\n", + DETAILS.replace("ai.storyteller.designcraft.nightly", "ai.storyteller.designcraft"), + DETAILS.replace("ai.storyteller.designcraft.nightly", "aiXstorytellerXdesigncraftXnightly")): + with self.subTest(broken=broken): + self.assertNotEqual(lib("mac_nightly_check_signature", broken, TEAM)[0], 0) + self.assertNotEqual(lib("mac_nightly_check_signature", DETAILS, "ZZZZZ99999")[0], 0, "another team") + + def test_gatekeeper_must_accept_the_bundle_as_notarized(self): + self.assertEqual(lib("mac_nightly_check_assessment", "x.app: accepted\nsource=Notarized Developer ID\n")[0], 0) + for text in ("x.app: accepted\nsource=Developer ID\n", "x.app: rejected\nsource=Unnotarized Developer ID\n"): + with self.subTest(text=text): + self.assertNotEqual(lib("mac_nightly_check_assessment", text)[0], 0) + + def test_the_imported_identity_must_be_a_developer_id_of_the_team(self): + line = f' 1) {IDENTITY} "Developer ID Application: Generated Fixture ({TEAM})"' + self.assertEqual(lib("mac_nightly_identity_is_team", line, IDENTITY, TEAM)[0], 0) + self.assertNotEqual(lib("mac_nightly_identity_is_team", line, IDENTITY, "ZZZZZ99999")[0], 0) + self.assertNotEqual(lib("mac_nightly_identity_is_team", line.replace("Developer ID Application", "Apple Development"), IDENTITY, TEAM)[0], 0) + + def zip_check(self, archive, **limits): + """The preflight alone, with the archive limits optionally lowered after the library is sourced.""" + lowered = "".join(f"{name}={value}; " for name, value in limits.items()) + script = f'. {str(HERE / "nightly-lib.sh")!r}; {lowered}mac_nightly_check_zip_entries "$1"' + return subprocess.run(["bash", "-c", script, "lib", str(archive)], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL).returncode + + def make_zip(self, directory, method=zipfile.ZIP_DEFLATED, files=None): + path = Path(directory) / "bundle.zip" + with zipfile.ZipFile(path, "w", method) as z: + for name, data in (files or {f"{APP}/Contents/MacOS/DesignCraft": b"x" * 4096, f"{APP}/Contents/Info.plist": b""}).items(): + z.writestr(zipfile.ZipInfo(name), data, compress_type=method) + return path + + def test_the_archive_is_bounded_before_anything_is_unpacked(self): + with tempfile.TemporaryDirectory() as directory: + for method in (zipfile.ZIP_STORED, zipfile.ZIP_DEFLATED): + with self.subTest(method=method): + path = self.make_zip(directory, method) + self.assertEqual(self.zip_check(path), 0, "a normal bundle is accepted") + self.assertNotEqual(self.zip_check(path, MAC_NIGHTLY_ZIP_MAX_ENTRIES=1), 0, "too many entries") + self.assertNotEqual(self.zip_check(path, MAC_NIGHTLY_ZIP_MAX_EXPANDED=1000), 0, "too much expanded data") + self.assertNotEqual(self.zip_check(path, MAC_NIGHTLY_ZIP_MAX_ARCHIVE=10), 0, "too large an archive") + bzip = self.make_zip(directory, zipfile.ZIP_BZIP2) + self.assertNotEqual(self.zip_check(bzip), 0, "only stored and deflated entries are inflated and counted") + + def test_an_entry_whose_header_understates_its_size_is_refused(self): + import struct + size = 3_000_000 + with tempfile.TemporaryDirectory() as directory: + path = self.make_zip(directory, files={f"{APP}/Contents/MacOS/DesignCraft": b"\0" * size}) + self.assertEqual(self.zip_check(path), 0) + data = bytearray(path.read_bytes()) + packed, understated = struct.pack("> 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/designcraft-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 'DesignCraft {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 'DesignCraft 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 'DesignCraft {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"}, + DESIGNCRAFT_BUILD_CHANNEL="nightly-v1", DESIGNCRAFT_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 100644 index 000000000..880b38dcc --- /dev/null +++ b/packaging/nightly-archive-tests.py @@ -0,0 +1,233 @@ +#!/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" + # DesignCraft ships no ATTRIBUTION.md (its credits are the About window's). + self.required = {"designcraft", "designcraft-bin", "designcraft-nightly.png", "README.md", "LICENSE-MIT", "LICENSE-APACHE", "NOTICE"} + for name in self.required: + (self.stage / name).write_bytes(b"generated fixture: " + name.encode()) + for executable in ("designcraft", "designcraft-bin"): + (self.stage / executable).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("designcraft").read(), (self.stage / "designcraft").read_bytes()) + # The launcher and the compiled binary are two distinct files in one flat archive. + self.assertNotEqual(archive.extractfile("designcraft").read(), archive.extractfile("designcraft-bin").read()) + 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 ["designcraft-cli", "portable.txt", "designcraft.desktop"]: + with self.subTest(name=name): + bad = self.stage / name + bad.write_bytes(b"generated fixture") + with self.assertRaisesRegex(ValueError, "unexpected"): + ARCHIVE.linux_archive(self.stage, self.output) + self.assertFalse(self.output.exists()) + bad.unlink() + + def test_symlink_refuses_before_output(self): + icon = self.stage / "designcraft-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 / "designcraft-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 100755 index 000000000..cbbfa72a2 --- /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 + if name not in {"designcraft", "designcraft-bin", "designcraft-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 = {"designcraft", "designcraft-bin", "designcraft-nightly.png", "README.md", "LICENSE-MIT", "LICENSE-APACHE", "NOTICE"} + if not required.issubset({item.name for item in entries}): + raise ValueError("required GUI/icon/notices missing") + return entries + + +def member_info(stage_root, name, incoming): + """Header for one stage file, built from the file this run opened rather than from the archive. + + Members are flat names that resolve directly inside the stage they came from. + """ + if os.path.isabs(name) or os.path.basename(name) != name or name in ("", ".", ".."): + raise ValueError(f"nightly member name must be a flat file name: {name}") + destination = os.path.realpath(os.path.join(stage_root, name)) + if not destination.startswith(stage_root + os.sep) or os.path.dirname(destination) != stage_root: + raise ValueError(f"nightly member resolves outside its stage: {name}") + status = os.fstat(incoming.fileno()) + if not stat.S_ISREG(status.st_mode): + raise ValueError(f"nightly member must be a regular file: {name}") + # The same fields TarFile.gettarinfo records for a regular file. + # The header keeps the validated stage name, not the resolved one: a stage symlink must + # never rename a member or leave a required name out of the archive. + info = tarfile.TarInfo(name) + info.type = tarfile.REGTYPE + info.mode = stat.S_IMODE(status.st_mode) + info.uid, info.gid = status.st_uid, status.st_gid + info.size = status.st_size + info.mtime = status.st_mtime + try: + info.uname = pwd.getpwuid(status.st_uid).pw_name + except KeyError: + pass + try: + info.gname = grp.getgrgid(status.st_gid).gr_name + except KeyError: + pass + return info + + +def verify_headers(root, output): + # Bounded ordinary headers, not a transparent PAX/GNU-normalizing reader. + total = 0 + count = 0 + with root.reader(output, MAX_TOTAL_BYTES) as incoming, gzip.GzipFile(fileobj=incoming) as stream: + while True: + header = stream.read(512) + if header == b"\0" * 512: + break + if len(header) != 512 or header[156:157] not in {b"0", b"\0"}: + raise ValueError("non-ordinary TAR record was emitted") + size = int(header[124:136].rstrip(b"\0 ").lstrip(b" ") or b"0", 8) + count += 1 + total += size + if count > MAX_MEMBERS or size > MAX_MEMBER_BYTES or total > MAX_TOTAL_BYTES: + raise ValueError("archive exceeds its bounded member budget") + remaining = ((size + 511) // 512) * 512 + while remaining: + chunk = stream.read(min(remaining, 1024 * 1024)) + if not chunk: + raise ValueError("truncated TAR member") + remaining -= len(chunk) + + +def linux_archive(stage, output): + with OwnedBuildRoot() as root: + entries = checked_entries(root, stage) + stage_root = os.path.realpath(os.path.join(root.directory, stage)) + total = 0 + with root.create(output) as outgoing: + with tarfile.open(fileobj=outgoing, mode="w:gz", format=tarfile.USTAR_FORMAT) as archive: + for entry in entries: + with root.reader(entry, MAX_MEMBER_BYTES) as incoming: + info = member_info(stage_root, entry.name, incoming) + total += info.size + if info.size > MAX_MEMBER_BYTES or total > MAX_TOTAL_BYTES: + raise ValueError("nightly stage grew beyond its read bound") + archive.addfile(info, incoming) + outgoing.flush() + os.fsync(outgoing.fileno()) + verify_headers(root, output) + + +if __name__ == "__main__": + if len(sys.argv) != 4 or sys.argv[1] != "linux": + raise SystemExit("usage: nightly-archive.py linux STAGE OUTPUT (from owned private build cwd)") + linux_archive(pathlib.Path(sys.argv[2]), pathlib.Path(sys.argv[3])) diff --git a/packaging/nightly-common.sh b/packaging/nightly-common.sh new file mode 100755 index 000000000..9c524433e --- /dev/null +++ b/packaging/nightly-common.sh @@ -0,0 +1,95 @@ +# shellcheck shell=bash +# Shared setup for app-owned native nightly archives; stable packaging does not source this file. + +nightly_die() { printf 'error: %s\n' "$*" >&2; exit 2; } + +nightly_init() { + local os="$1" arch="$2" target="$3" date_digits + [[ "${DESIGNCRAFT_BUILD_CHANNEL:-}" == nightly-v1 ]] || nightly_die 'DESIGNCRAFT_BUILD_CHANNEL must be nightly-v1' + [[ "${DESIGNCRAFT_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' + [[ "${DESIGNCRAFT_BUILD_SHA:-}" =~ ^[0-9a-f]{40}$ ]] || nightly_die 'an exact source commit is required' + [[ "${DESIGNCRAFT_VERSION##*.g}" == "${DESIGNCRAFT_BUILD_SHA:0:12}" ]] || nightly_die 'version/source commit mismatch' + [[ "${DESIGNCRAFT_BUILD_DATE:-}" =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}$ ]] || nightly_die 'the original run-created UTC date is required' + date_digits="${DESIGNCRAFT_VERSION#*-nightly.}" + date_digits="${date_digits%%.*}" + [[ "${DESIGNCRAFT_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)" == "$DESIGNCRAFT_BUILD_SHA" ]] || nightly_die 'prepared source is not the checked-out commit' + [[ -z "$(git -C "$ROOT" status --porcelain)" ]] || nightly_die 'nightly packaging requires the frozen clean source' + if [[ -n "${CRAFT_FONTS_DIR:-}" && ! -d "$CRAFT_FONTS_DIR/fonts" ]]; then + nightly_die 'declared CRAFT_FONTS_DIR has no fonts directory' + fi + # env.sh retains the established notice copier. Required values above prohibit its stable fallbacks. + . "$ROOT/packaging/env.sh" + export CARGO_TARGET_DIR="$CARGO_TARGET_DIR/nightly-v1/$os-$arch" + NIGHTLY_RUST_TARGET="$target" + mkdir -p "$CARGO_TARGET_DIR" + NIGHTLY_WORK="$(mktemp -d "$CARGO_TARGET_DIR/nightly-package.XXXXXX")" + trap 'rm -rf -- "$NIGHTLY_WORK"' EXIT +} + +# Compile only: the version query runs on the unpacked payload (Linux) or the signed bundle +# (macOS, packaging/macos/nightly-verify.sh). DesignCraft's GUI needs no optional features. +nightly_compile_gui() { + # The guard sits here as well as in the entrypoints: no caller may compile with signing material. + nightly_refuse_signing_env + (cd "$ROOT" && DESIGNCRAFT_BUILD_CHANNEL=nightly-v1 cargo build --release --locked -p designcraft --target "$NIGHTLY_RUST_TARGET") + NIGHTLY_GUI="$CARGO_TARGET_DIR/$NIGHTLY_RUST_TARGET/release/designcraft" + [[ -f "$NIGHTLY_GUI" && ! -L "$NIGHTLY_GUI" ]] || nightly_die 'the owned GUI build did not produce a regular executable' + [[ "$(git -C "$ROOT" rev-parse HEAD)" == "$DESIGNCRAFT_BUILD_SHA" && -z "$(git -C "$ROOT" status --porcelain)" ]] || nightly_die 'source changed during the build' +} + +nightly_build_gui() { + nightly_compile_gui + local actual + actual="$("$NIGHTLY_GUI" --version)" || nightly_die 'side-effect-free nightly version verification failed' + [[ "$actual" == "DesignCraft $VERSION (nightly-v1)" ]] || nightly_die 'the built version/flavor is not the prepared identity' + [[ "$(git -C "$ROOT" rev-parse HEAD)" == "$DESIGNCRAFT_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 +} + +# DesignCraft has no ATTRIBUTION.md of its own (its credits are the About window's), so the +# required app notices are the licence, the notice file and the readme; an ATTRIBUTION.md is copied +# when a checkout does have one. +nightly_copy_notices() { + local destination="$1" required + for required in README.md LICENSE-MIT LICENSE-APACHE NOTICE; 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-launcher-tests.py b/packaging/nightly-launcher-tests.py new file mode 100644 index 000000000..6c1f4363a --- /dev/null +++ b/packaging/nightly-launcher-tests.py @@ -0,0 +1,169 @@ +#!/usr/bin/env python3 +"""Synthetic contract for the Linux nightly launchers: no native build or executable launch. + +Every Linux nightly format (deb/rpm wrapper, AppImage AppRun, Arch launcher, Flatpak wrapper and +the unpacked tar) must start the compiled nightly-v1 flavor the Launcher's way, because the app +refuses a DESIGNCRAFT_CONFIG_DIR override and refuses a bare start as stable. +""" +import os +import re +import subprocess +import tempfile +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +LINUX = ROOT / "packaging/linux" +CHANNEL = ROOT / "crates/ui-egui/src/channel.rs" + +EXEC = 'exec "$real_bin" --launch-profile nightly-v1 --profile-root "$profile_root" -- "$@"' +PROFILE_ROOT = 'profile_root="${XDG_DATA_HOME:-${HOME:?HOME is required}/.local/share}/designcraft-nightly"' +PASSTHROUGH = 'if [ "${1:-}" = "--launch-profile" ] || [ "${1:-}" = "--profile-root" ]; then' + + +def body(path, marker): + lines = (ROOT / path).read_text(encoding="utf-8").splitlines() + opening = [index for index, line in enumerate(lines) if f"<<'{marker}'" in line] + if len(opening) != 1: + raise AssertionError(f"{path}: expected exactly one <<'{marker}' here-document") + end = lines.index(marker, opening[0] + 1) + return lines[opening[0] + 1:end] + + +def launchers(): + """(label, the launcher's own lines) for every Linux nightly start path.""" + return { + "deb/rpm wrapper": body("packaging/linux/package.sh", "WRAPPER"), + "AppImage AppRun": body("packaging/linux/package.sh", "APPRUN"), + "Arch launcher": (LINUX / "nightly-arch-launch.sh").read_text(encoding="utf-8").splitlines(), + "Flatpak wrapper": body("packaging/linux/flatpak-bundle.sh", "WRAPPER"), + "tar launcher": body("packaging/linux/nightly.sh", "LAUNCHER"), + } + + +def tar_launcher(scratch): + """The tar's launcher beside a recorder that prints its argv, one argument per line.""" + directory = Path(scratch) + launcher = directory / "designcraft" + launcher.write_text("\n".join(body("packaging/linux/nightly.sh", "LAUNCHER")) + "\n", encoding="utf-8") + launcher.chmod(0o755) + recorder = directory / "designcraft-bin" + recorder.write_text('#!/bin/sh\nfor arg in "$@"; do printf "<%s>\\n" "$arg"; done\n', encoding="utf-8") + recorder.chmod(0o755) + return directory, launcher + + +def constant(name): + source = CHANNEL.read_text(encoding="utf-8") + found = re.search(r'pub const ' + name + r': &str = "([^"]+)";', source) + if found is None: + raise AssertionError(f"channel.rs has no {name}") + return found.group(1) + + +class LinuxLaunchers(unittest.TestCase): + def test_every_format_execs_the_launcher_pair(self): + for label, lines in launchers().items(): + with self.subTest(launcher=label): + self.assertIn(EXEC, lines) + self.assertEqual(sum(line == EXEC for line in lines), 1, "one start path per format") + + def test_no_format_redirects_the_profile_through_the_stable_override(self): + for label, lines in launchers().items(): + with self.subTest(launcher=label): + redirected = [line for line in lines if not line.lstrip().startswith("#") and re.match(r"\s*(export\s+)?DESIGNCRAFT_CONFIG_DIR=", line)] + self.assertEqual(redirected, [], "a non-empty override is refused by the app") + + def test_the_version_query_is_answered_before_the_profile_prelude(self): + for label, lines in launchers().items(): + with self.subTest(launcher=label): + query = next(index for index, line in enumerate(lines) if '= "--version"' in line and '= "-V"' in line) + self.assertLess(query, lines.index(EXEC), "a headless runner asks for the version first") + + def test_every_format_uses_the_same_absolute_channel_profile(self): + for label, lines in launchers().items(): + with self.subTest(launcher=label): + self.assertIn(PROFILE_ROOT, lines) + + def test_the_nightly_window_id_is_the_packaged_desktop_class(self): + app_id = constant("NIGHTLY_APP_ID") + package = (LINUX / "package.sh").read_text(encoding="utf-8") + flatpak = (LINUX / "flatpak-bundle.sh").read_text(encoding="utf-8") + self.assertIn(f"StartupWMClass={app_id}", package) + self.assertIn(f"StartupWMClass={app_id}", flatpak) + # The stable entry keeps its own class, so the two windows never share one. + stable = (LINUX / "ai.storyteller.designcraft.desktop").read_text(encoding="utf-8") + self.assertIn(f"StartupWMClass={constant('APP_ID')}\n", stable) + + def test_the_flatpak_bundle_id_is_the_nightly_package_id(self): + flatpak = (LINUX / "flatpak-bundle.sh").read_text(encoding="utf-8") + self.assertIn('FLATPAK_ID="$APP_ID.nightly"', flatpak) + self.assertEqual(f"{constant('APP_ID')}.nightly", constant("NIGHTLY_PACKAGE_ID")) + + def test_the_tar_archive_carries_the_launcher_beside_its_binary(self): + policy = (ROOT / "packaging/nightly-archive.py").read_text(encoding="utf-8") + self.assertIn('{"designcraft", "designcraft-bin", "designcraft-nightly.png"}', policy) + self.assertIn('"designcraft-bin", "designcraft-nightly.png", "README.md"', policy) + nightly = (LINUX / "nightly.sh").read_text(encoding="utf-8") + self.assertIn('cp "$NIGHTLY_GUI" "$STAGE/designcraft-bin"', nightly) + + def test_every_format_passes_an_existing_profile_pair_through(self): + for label, lines in launchers().items(): + with self.subTest(launcher=label): + self.assertEqual(sum(line == PASSTHROUGH for line in lines), 1, "a caller's own profile pair is never doubled") + + def test_the_tar_launcher_passes_an_existing_profile_pair_through_untouched(self): + with tempfile.TemporaryDirectory() as scratch: + directory, launcher = tar_launcher(scratch) + supplied = ["--launch-profile", "nightly-v1", "--profile-root", "/launcher/root/designcraft", "--", "doc.dc", "--version"] + run = subprocess.run( + [str(launcher), *supplied], cwd="/", env={"HOME": str(directory), "PATH": "/usr/bin:/bin"}, capture_output=True, text=True, timeout=15 + ) + self.assertEqual(run.returncode, 0, run.stderr) + self.assertEqual(run.stdout.splitlines(), [f"<{arg}>" for arg in supplied], "the Launcher's protocol reached the binary unchanged") + + def test_the_tar_launcher_never_adds_a_second_separator(self): + with tempfile.TemporaryDirectory() as scratch: + directory, launcher = tar_launcher(scratch) + profile = directory / ".local/share/designcraft-nightly" + run = subprocess.run( + [str(launcher), "--", "--version"], cwd="/", env={"HOME": str(directory), "PATH": "/usr/bin:/bin"}, capture_output=True, text=True, timeout=15 + ) + self.assertEqual(run.returncode, 0, run.stderr) + self.assertEqual( + run.stdout.splitlines(), + ["<--launch-profile>", "", "<--profile-root>", f"<{profile}>", "<-->", "<--version>"], + "the caller's separator stays the only one, and a flag after it is a document", + ) + + def test_the_tar_launcher_starts_its_binary_with_the_profile_pair(self): + lines = body("packaging/linux/nightly.sh", "LAUNCHER") + with tempfile.TemporaryDirectory() as scratch: + directory = Path(scratch) + launcher = directory / "designcraft" + launcher.write_text("\n".join(lines) + "\n", encoding="utf-8") + launcher.chmod(0o755) + recorder = directory / "designcraft-bin" + recorder.write_text('#!/bin/sh\nfor arg in "$@"; do printf "<%s>\\n" "$arg"; done\n', encoding="utf-8") + recorder.chmod(0o755) + environment = {"HOME": str(directory), "PATH": "/usr/bin:/bin"} + run = subprocess.run([str(launcher), "doc with spaces.dc", "--other-name.dc"], cwd="/", env=environment, capture_output=True, text=True, timeout=15) + self.assertEqual(run.returncode, 0, run.stderr) + self.assertEqual( + run.stdout.splitlines(), + [ + "<--launch-profile>", + "", + "<--profile-root>", + f"<{directory / '.local/share/designcraft-nightly'}>", + "<-->", + "", + "<--other-name.dc>", + ], + ) + query = subprocess.run([str(launcher), "--version"], cwd="/", env=environment, capture_output=True, text=True, timeout=15) + self.assertEqual(query.stdout.splitlines(), ["<--version>"], "a version query reaches the binary untouched") + + +if __name__ == "__main__": + unittest.main() diff --git a/packaging/nightly-release-tests.py b/packaging/nightly-release-tests.py new file mode 100755 index 000000000..d425ba761 --- /dev/null +++ b/packaging/nightly-release-tests.py @@ -0,0 +1,423 @@ +#!/usr/bin/env python3 +"""Local nightly workflow and signing-policy contract tests for DesignCraft.""" +import copy +import json +from pathlib import Path +import re +import unittest + +ROOT = Path(__file__).resolve().parents[1] +INSTALLED_POLICY = ROOT / ".github/nightly-signing-policy.json" + +NIGHTLY_PLATFORMS = ("windows-x86_64", "linux-x86_64", "macos-aarch64") +NIGHTLY_TRUST = { + "windows-x86_64": ( + "publisher_subject", + "CN=Learning Machines Inc, O=Learning Machines Inc, L=Atlanta, S=Georgia, C=US", + ), + "linux-x86_64": ("fingerprint", "2B76741B414AAD6CD33E631213A005C0B9D7C3ED"), + "macos-aarch64": ("apple_team_id", "DJ6XS33FX8"), +} + +# Mirrors the storytold release-managers team (id 19837241) minus echelon-robot. +# Update by PR, in the caller and the policy, when the team changes. +RELEASE_MANAGERS = ["bflatastic", "dylanmtaylor", "echelon", "FredApps", "skylartaylor"] + + +def assert_nightly_serialization(source): + """Fail closed unless this app's plain root concurrency block retains its contract.""" + lines = source.splitlines() + roots = [index for index, line in enumerate(lines) if line.startswith("concurrency:")] + if len(roots) != 1 or lines[roots[0]] != "concurrency:": + raise ValueError("one plain root concurrency block is required") + values = {} + for line in lines[roots[0] + 1:]: + if not line.strip() or line.lstrip().startswith("#"): + continue + if not line[0].isspace(): + break + row = re.fullmatch(r" (group|cancel-in-progress): ([^#]+?)(?: +#.*)?", line) + if row is None or row[1] in values: + raise ValueError("malformed or duplicate nightly concurrency entry") + values[row[1]] = row[2].rstrip() + if values != { + "group": "designcraft-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 in ("nightly.yml", "nightly-sign.yml"): + source = (ROOT / ".github/workflows" / name).read_text() + expected = NightlyEnabledCallers.GUARDS[name] + guard = re.search(r"(?m)^ if: >-\n(?: [^\n]*\n)+", source)[0] + for replacement in (guard + " || true\n", " if: " + expected + "\n || true\n"): + jobs = source.replace(guard, replacement).split("\njobs:\n", 1)[1] + with self.subTest(workflow=name, replacement=replacement[-30:]): + (indicator, expression), = job_conditions(jobs) + self.assertFalse(indicator == ">-" and " ".join(expression.split()) == expected) + + def test_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: designcraft-nightly-release", "group: ${{ github.run_id }}"), + ("group: designcraft-nightly-release", "group: release-${{ github.ref }}"), + ("concurrency:\n", "concurrency: ${{ github.run_id }}\n"), + ("concurrency:\n", " concurrency:\n"), + ): + with self.subTest(change=new), self.assertRaises(ValueError): + assert_nightly_serialization(source.replace(old, new)) + + def test_no_cache_actions_or_cache_setup_options_in_app_trusted_closure(self): + for name in ("nightly.yml", "nightly-sign.yml"): + source = (ROOT / ".github/workflows" / name).read_text() + executable = "\n".join(line for line in source.splitlines() if not line.lstrip().startswith("#")) + with self.subTest(workflow=name): + self.assertNotRegex(executable, r"(?im)^\s*(?:-\s*)?uses:\s*[^\n]*cache") + self.assertNotRegex(executable, r"(?im)^\s*[^\s:#]*cache[^\s:#]*:") + self.assertNotRegex(executable, r"(?im)^\s*(?:environment|secrets):") + self.assertNotIn("secrets.", executable) + + +class NightlyTrustAnchors(unittest.TestCase): + """The public stable identities each platform's signed nightly must carry (all three platforms).""" + + def setUp(self): + self.policy = json.loads(INSTALLED_POLICY.read_text()) + + def test_each_platform_row_names_its_fixed_artifact_kind_and_stable_identity(self): + self.assertEqual(set(self.policy["platforms"]), set(NIGHTLY_TRUST)) + for platform, (field, value) in NIGHTLY_TRUST.items(): + row = self.policy["platforms"][platform] + with self.subTest(platform=platform): + self.assertEqual( + row["unsigned_artifact_name"], + f"nightly-unsigned-{platform}", + "the artifact kind is fixed by platform, never a caller pattern", + ) + self.assertEqual(row["trust"], {field: value}, "trust must be stable's public identity") + + def test_trust_values_have_the_shapes_the_shared_signer_accepts(self): + rows = self.policy["platforms"] + self.assertRegex(rows["macos-aarch64"]["trust"]["apple_team_id"], r"^[A-Z0-9]{10}$") + self.assertRegex(rows["linux-x86_64"]["trust"]["fingerprint"], r"^[0-9A-F]{40}$") + subject = rows["windows-x86_64"]["trust"]["publisher_subject"] + self.assertTrue(0 < len(subject) <= 1024 and not set(subject) & {"\r", "\n", "\0"}) + + def test_both_callers_use_one_shared_pin_in_uses_and_tooling_revision(self): + pins = set() + for name, callee in (("nightly.yml", "nightly-unsigned.yml"), ("nightly-sign.yml", "nightly-release.yml")): + source = (ROOT / ".github/workflows" / name).read_text() + uses = re.findall( + r"(?m)^ uses: storytold/craft-common-actions/\.github/workflows/" + + re.escape(callee) + + r"@(\S+)$", + source, + ) + tooling = re.findall(r"(?m)^ tooling-revision: (\S+)$", source) + with self.subTest(workflow=name): + self.assertEqual(len(uses), 1) + self.assertEqual(tooling, uses, "the defining workflow SHA and tooling input must match") + pins.update(uses) + self.assertEqual(len(pins), 1, "producer and signer must pin the same shared commit") + self.assertRegex(pins.pop(), r"^[0-9a-f]{40}$", "pin a full immutable commit, never a branch or placeholder") + + +class NightlyEnabledCallers(unittest.TestCase): + """Producer and signer run only in their exact context, for the reviewed manual actors.""" + + GUARDS = { + "nightly.yml": ( + "github.repository == 'storytold/designcraft' && github.ref == 'refs/heads/main' && " + "github.ref_type == 'branch' && (github.event_name == 'schedule' || " + "github.event_name == 'workflow_dispatch')" + ), + "nightly-sign.yml": ( + "github.repository == 'storytold/designcraft' && github.event_name == 'workflow_dispatch' && " + "github.ref == 'refs/heads/release' && github.ref_type == 'branch'" + ), + } + + def test_enabled_jobs_keep_exact_context_guards(self): + for name, expected in self.GUARDS.items(): + jobs = (ROOT / ".github/workflows" / name).read_text().split("\njobs:\n", 1)[1] + guards = job_conditions(jobs) + with self.subTest(workflow=name): + self.assertEqual(len(guards), 1) + indicator, expression = guards[0] + self.assertEqual(indicator, ">-") + self.assertEqual(" ".join(expression.split()), expected, "guards may only change with review") + + def test_manual_actors_are_the_release_managers_in_caller_and_policy(self): + source = (ROOT / ".github/workflows/nightly.yml").read_text() + policy = json.loads(INSTALLED_POLICY.read_text()) + self.assertEqual(reviewed_manual_actors(source, policy), RELEASE_MANAGERS) + self.assertEqual(policy["automatic_signer_actors"], [], "no automatic signer without a schedule") + + def test_an_actor_outside_the_release_managers_is_refused(self): + source = (ROOT / ".github/workflows/nightly.yml").read_text() + policy = json.loads(INSTALLED_POLICY.read_text()) + caller = json.dumps(RELEASE_MANAGERS, separators=(",", ":")) + widened = sorted(RELEASE_MANAGERS + ["echelon-robot"], key=str.lower) + for change in ("caller", "policy", "both", "order", "case"): + mutated_source, mutated_policy = source, copy.deepcopy(policy) + if change in ("caller", "both"): + mutated_source = source.replace(caller, json.dumps(widened, separators=(",", ":"))) + if change in ("policy", "both"): + mutated_policy["manual_actors"] = widened + if change == "order": + mutated_policy["manual_actors"] = list(reversed(RELEASE_MANAGERS)) + if change == "case": + mutated_policy["manual_actors"] = [login.lower() for login in RELEASE_MANAGERS] + with self.subTest(change=change), self.assertRaises(ValueError): + reviewed_manual_actors(mutated_source, mutated_policy) + + +class NightlyInstalledPolicy(unittest.TestCase): + """The installed v3 policy matches the callers, the repository and its documented sources.""" + + 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/designcraft") + 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 may be None until nightly.yml is registered on main. + wf_id = self.policy["producer_workflow_id"] + if wf_id is not None: + self.assertIs(type(wf_id), int) + self.assertGreater(wf_id, 0) + self.assertNotEqual( + wf_id, + self.policy["candidate_policy"]["required_workflows"][0]["workflow_id"], + "the producer is not its own quality workflow", + ) + + def test_paths_and_tooling_match_the_callers(self): + pin = caller_pin("nightly.yml") + self.assertEqual(caller_pin("nightly-sign.yml"), pin) + self.assertEqual(self.policy["producer_workflow_path"], ".github/workflows/nightly.yml") + self.assertEqual(self.policy["signer_workflow_path"], ".github/workflows/nightly-sign.yml") + self.assertEqual(self.policy["producer_tooling_revision"], pin) + self.assertEqual(self.policy["signer_tooling_revision"], pin) + self.assertEqual( + self.policy["producer_workflow_ref"], + "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@" + pin, + ) + + def test_platforms_equal_the_producer(self): + built = producer_platforms((ROOT / ".github/workflows/nightly.yml").read_text()) + self.assertEqual(built, list(NIGHTLY_PLATFORMS)) + self.assertEqual(set(self.policy["platforms"]), set(built)) + + def test_bounds(self): + self.assertIs(type(self.policy["max_age_seconds"]), int) + self.assertTrue(0 < self.policy["max_age_seconds"] <= 604800) + self.assertIs(type(self.policy["max_artifact_bytes"]), int) + self.assertTrue(0 < self.policy["max_artifact_bytes"] <= 16 * 1024**3) + + def test_candidate_workflows_run_on_every_main_push(self): + candidate = self.policy["candidate_policy"] + self.assertEqual( + set(candidate), + {"schema", "epoch", "repository", "branch", "required_workflows", "sonar"}, + ) + self.assertEqual(candidate["schema"], "craft-nightly-candidate-policy/v3") + self.assertEqual((candidate["repository"], candidate["branch"]), ("storytold/designcraft", "main")) + self.assertTrue(isinstance(candidate["epoch"], str) and 0 < len(candidate["epoch"]) <= 128) + rows = candidate["required_workflows"] + self.assertTrue(rows) + for row in rows: + with self.subTest(workflow=row["workflow_path"]): + self.assertEqual(set(row), {"workflow_id", "workflow_path", "jobs"}) + self.assertIs(type(row["workflow_id"]), int) + self.assertNotEqual(row["workflow_path"], self.policy["producer_workflow_path"]) + source = (ROOT / row["workflow_path"]).read_text() + push = re.search(r"(?m)^ push:\n((?: .*\n)+)", source) + self.assertIsNotNone(push, "a required workflow must run on main pushes") + self.assertIn(" branches: [main]\n", push[1]) + self.assertNotRegex(push[1], r"paths", "a path filter would leave candidates without a run") + names = [job["name"] for job in row["jobs"]] + self.assertEqual(len(names), len(set(names))) + for job in row["jobs"]: + self.assertEqual(set(job), {"name", "app_id", "applicability"}) + self.assertEqual((job["app_id"], job["applicability"]), (15368, "required")) + + def test_sonar_identity_and_reviewed_scope(self): + sonar = self.policy["candidate_policy"]["sonar"] + properties = dict( + line.split("=", 1) + for line in (ROOT / "sonar-project.properties").read_text().splitlines() + if line and not line.startswith("#") + ) + self.assertEqual(sonar["organization"], properties["sonar.organization"]) + self.assertEqual(sonar["project"], properties["sonar.projectKey"]) + self.assertEqual((sonar["app_id"], sonar["check_name"]), (12526, "SonarCloud Code Analysis")) + self.assertEqual( + sonar["details_url"], + "https://sonarcloud.io/dashboard?id=" + sonar["project"] + "&branch=main", + ) + accepted = { + "bugs": "BUG", + "vulnerabilities": "VULNERABILITY", + "code_smells": "CODE_SMELL", + "security_rating": "VULNERABILITY", + "new_security_rating": "VULNERABILITY", + } + self.assertEqual({accepted[c["metric"]] for c in sonar["accepted_conditions"]}, set(sonar["issue_types"])) + metrics = [c["metric"] for c in sonar["accepted_conditions"] + sonar["required_conditions"]] + self.assertEqual(len(metrics), len(set(metrics))) + keys = [item["key"] for item in sonar["debt"]] + self.assertEqual(len(keys), len(set(keys))) + for item in sonar["debt"]: + with self.subTest(issue=item["key"]): + self.assertEqual(set(item), {"key", "rule", "component", "type", "severity", "hash"}) + self.assertTrue(item["component"].startswith(sonar["project"] + ":")) + self.assertIn(item["type"], sonar["issue_types"]) + self.assertRegex(item["hash"], r"^[0-9a-f]{32}$") + + +if __name__ == "__main__": + unittest.main(verbosity=2) diff --git a/packaging/nightly-tests.py b/packaging/nightly-tests.py new file mode 100644 index 000000000..5b3ba68c8 --- /dev/null +++ b/packaging/nightly-tests.py @@ -0,0 +1,26 @@ +#!/usr/bin/env python3 +"""Run the existing synthetic packaging suites together; no app build or signing.""" +import importlib.util +from pathlib import Path +import unittest + + +def main() -> int: + here = Path(__file__).resolve().parent + suite = unittest.TestSuite() + for name, relative in ( + ("designcraft_archive_suite", "nightly-archive-tests.py"), + ("designcraft_launcher_suite", "nightly-launcher-tests.py"), + ("designcraft_plist_suite", "macos/nightly_plist_tests.py"), + ("designcraft_release_dispatch_suite", "nightly-release-tests.py"), + ("designcraft_mac_sign_suite", "macos/nightly_sign_tests.py"), + ): + spec = importlib.util.spec_from_file_location(name, here / relative) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + suite.addTests(unittest.defaultTestLoader.loadTestsFromModule(module)) + return 0 if unittest.TextTestRunner(verbosity=2).run(suite).wasSuccessful() else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/packaging/nightly_paths.py b/packaging/nightly_paths.py new file mode 100644 index 000000000..792198589 --- /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 000000000..91dc350a4 --- /dev/null +++ b/packaging/windows/nightly-package-tests.ps1 @@ -0,0 +1,96 @@ +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 'designcraft-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 'designcraft.exe') 'nightly must not ship the unqualified CLI' +Assert ($spec.AppId -eq 'ai.storyteller.designcraft.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 'DesignCraft Nightly' 'DesignCraft 0.23.1-nightly.20261120.17.1.gabcdef012345 (nightly-v1)' '0.23.1-nightly.20261120.17.1.gabcdef012345' +foreach ($pair in @(@('DesignCraft', 'DesignCraft 0.23.1 (nightly-v1)'), @('DesignCraft Nightly', 'DesignCraft 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/designcraft/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 + # DesignCraft has no LICENSE of its own: the same required set the production copier demands. + $rootNames = @('README.md', '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', 'designcraft-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 000000000..65c29d8cc --- /dev/null +++ b/packaging/windows/nightly-signing-tests.ps1 @@ -0,0 +1,90 @@ +param( + [Parameter(Mandatory=$true)][string] $FixtureRoot, + [string] $PackagingRoot = $PSScriptRoot, + [switch] $PhaseGuardOnly +) +$ErrorActionPreference = 'Stop' +. (Join-Path $PackagingRoot 'nightly.ps1') -FunctionsOnly +$sign = Join-Path $PackagingRoot 'sign.ps1' +$names = @('WINDOWS_CERTIFICATE','WINDOWS_CERTIFICATE_PASSWORD','AZURE_TENANT_ID','AZURE_CLIENT_ID','AZURE_CLIENT_SECRET','AZURE_SIGNING_ENDPOINT','AZURE_SIGNING_ACCOUNT','AZURE_CERT_PROFILE') +function Clear-SigningFixtures { foreach ($name in $names) { [Environment]::SetEnvironmentVariable($name, $null) } } +function Assert-Policy([bool] $Value, [string] $Message) { if (-not $Value) { throw $Message } } +function Invoke-Refusal([scriptblock] $Operation, [string] $Message) { + $errorText = '' + try { & $Operation | Out-Null } catch { $errorText = $_.Exception.Message } + Assert-Policy ($errorText.Contains($Message)) "expected refusal: $Message; got: $errorText" +} +function global:cargo { $global:SigningFixtureCargoCalls++; throw 'FIXTURE_COMPILER_BOUNDARY' } +function global:Invoke-WebRequest { throw 'fixture must not perform signing downloads' } +$global:SigningFixtureCargoCalls = 0 +if (-not [IO.Path]::IsPathRooted($FixtureRoot)) { throw 'use an owned absolute FixtureRoot' } +$root = Join-Path $FixtureRoot ('signing-policy-' + [Guid]::NewGuid().ToString('N')) +New-Item -ItemType Directory -Path $root | Out-Null +# The fixture mocks Cargo, but nightly.ps1 checks the same source identity a packaging run does: +# the version names this checkout's commit and the run's UTC date, and the tree is clean. Deriving +# them here keeps the fixture reaching the mocked compiler instead of failing in source validation. +$sha = "$(git -C $PSScriptRoot rev-parse HEAD)".Trim() +$runDate = (Get-Date).ToUniversalTime().ToString('yyyyMMdd') +$version = "0.23.1-nightly.$runDate.12345.1.g$($sha.Substring(0, 12))" +$env:DESIGNCRAFT_VERSION = $version +$env:DESIGNCRAFT_BUILD_SHA = $sha +$env:DESIGNCRAFT_BUILD_DATE = "$($runDate.Substring(0, 4))-$($runDate.Substring(4, 2))-$($runDate.Substring(6, 2))" +function Invoke-Build([switch] $BuildOnly) { + $arguments = @{Arch='x64';Version=$version;Target='x86_64-pc-windows-msvc';TargetDir=$root;Dist=(Join-Path $root 'dist')} + if ($BuildOnly) { $arguments.BuildOnly = $true } + & (Join-Path $PackagingRoot 'nightly.ps1') @arguments +} +try { + Clear-SigningFixtures + Invoke-Refusal { Invoke-Build } 'requires -BuildOnly' + Assert-Policy ($global:SigningFixtureCargoCalls -eq 0) 'default mode invoked Cargo' + Write-Output 'PASS: explicit-build-phase-required' + if ($PhaseGuardOnly) { return } + + foreach ($name in @('WINDOWS_CERTIFICATE','WINDOWS_CERTIFICATE_PASSWORD','AZURE_CLIENT_SECRET')) { + Clear-SigningFixtures + [Environment]::SetEnvironmentVariable($name, 'generated-fixture-not-a-secret') + Invoke-Refusal { Invoke-Build -BuildOnly } 'Compilation must not receive signing credentials' + Assert-Policy ($global:SigningFixtureCargoCalls -eq 0) 'key-bearing compilation reached Cargo' + } + Write-Output 'PASS: credentials-rejected-before-compilation' + + Clear-SigningFixtures + Invoke-Refusal { Invoke-Build -BuildOnly } 'FIXTURE_COMPILER_BOUNDARY' + Assert-Policy ($global:SigningFixtureCargoCalls -eq 1) 'clean compilation did not reach the mocked compiler boundary' + Assert-Policy (-not (Test-Path (Join-Path $root 'dist'))) 'mocked compilation produced an artifact' + Write-Output 'PASS: secret-free-build-reaches-only-mocked-boundary' + + Clear-SigningFixtures + Invoke-Refusal { & $sign -Required -CheckOnly } 'Nightly signing is required' + $env:AZURE_CLIENT_SECRET = 'generated-partial-fixture' + Invoke-Refusal { & $sign -Required -CheckOnly } 'Nightly signing is required' + Write-Output 'PASS: required-signer-refuses-missing-and-partial-configuration' + + Clear-SigningFixtures + $env:WINDOWS_CERTIFICATE = 'generated-presence-fixture-not-a-certificate' + & $sign -Required -CheckOnly + Clear-SigningFixtures + foreach ($name in $names | Where-Object { $_.StartsWith('AZURE_') }) { [Environment]::SetEnvironmentVariable($name, 'generated-presence-fixture') } + & $sign -Required -CheckOnly + Clear-SigningFixtures + Write-Output 'PASS: supported-configuration-presence-without-signing' + + # Load the policy function without signing. These objects are not crypto evidence. + . $sign -CheckOnly + foreach ($value in @($null, [pscustomobject]@{Status='NotSigned';SignerCertificate='fixture'}, [pscustomobject]@{Status='HashMismatch';SignerCertificate='fixture'}, [pscustomobject]@{Status='Valid';SignerCertificate=$null})) { + Invoke-Refusal { Assert-AuthenticodeSignature $value } 'valid Authenticode signature' + } + Assert-AuthenticodeSignature ([pscustomobject]@{Status='Valid';SignerCertificate='generated-public-certificate-placeholder'}) + Write-Output 'PASS: required-signature-policy-rejects-invalid-or-missing-signer' + + $file = Join-Path $root 'owned-sentinel.exe' + [IO.File]::WriteAllText($file, 'generated sentinel, not a real executable') + $before = (Get-FileHash -LiteralPath $file -Algorithm SHA256).Hash + & $sign -Files $file + Assert-Policy ((Get-FileHash -LiteralPath $file -Algorithm SHA256).Hash -ceq $before) 'optional stable policy changed unsigned bytes' + Write-Output 'PASS: stable-optional-policy-preserves-owned-bytes' +} finally { + Clear-SigningFixtures + Remove-Item -LiteralPath $root -Recurse -Force +} diff --git a/packaging/windows/nightly.ps1 b/packaging/windows/nightly.ps1 new file mode 100644 index 000000000..0226a269d --- /dev/null +++ b/packaging/windows/nightly.ps1 @@ -0,0 +1,143 @@ +<# 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 = "designcraft-$Version-windows-x86_64-nightly.zip" + UnsignedArchive = "designcraft-$Version-windows-x86_64-nightly.unsigned.zip" + Executables = @('designcraft.exe') + Channel = 'nightly-v1' + AppId = 'ai.storyteller.designcraft.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 (DESIGNCRAFT_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 (DESIGNCRAFT_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 'DesignCraft Nightly' -or $VersionOutput -cne "DesignCraft $ExpectedVersion (nightly-v1)") { + throw 'the executable is not the compiled nightly-v1 flavor' + } +} + +# DesignCraft has no LICENSE or ATTRIBUTION.md of its own, so the required notices are the readme, +# the two licences and NOTICE; LICENSE/COPYRIGHT/ATTRIBUTION.md are copied when a checkout has one. +function Copy-NightlyNotices([string] $RepositoryRoot, [string] $FontRepository, [string] $Destination) { + foreach ($name in 'README.md', 'LICENSE-MIT', 'LICENSE-APACHE', 'NOTICE') { + $source = Join-Path $RepositoryRoot $name + if (-not (Test-Path -LiteralPath $source -PathType Leaf)) { throw "missing app notice: $name" } + Copy-Item -LiteralPath $source -Destination $Destination + } + foreach ($optional in 'LICENSE', 'COPYRIGHT', 'ATTRIBUTION.md') { + $source = Join-Path $RepositoryRoot $optional + if (Test-Path -LiteralPath $source -PathType Leaf) { 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:DESIGNCRAFT_VERSION -or $Version -cne $env:DESIGNCRAFT_VERSION) { throw 'nightly-v1 requires explicit DESIGNCRAFT_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:DESIGNCRAFT_BUILD_SHA $env:DESIGNCRAFT_BUILD_DATE $Source.Head $Source.Status +$oldChannel = $env:DESIGNCRAFT_BUILD_CHANNEL +$oldVersion = $env:DESIGNCRAFT_VERSION +$oldOverride = $env:DESIGNCRAFT_OVERRIDE_VERSION +try { + $env:DESIGNCRAFT_BUILD_CHANNEL = 'nightly-v1' + # The build script accepts either name for the prepared version, and refuses a disagreement. + $env:DESIGNCRAFT_VERSION = $Version + $env:DESIGNCRAFT_OVERRIDE_VERSION = $Version + $env:DESIGNCRAFT_REQUIRE_WINRES = '1' + $env:CARGO_TARGET_X86_64_PC_WINDOWS_MSVC_RUSTFLAGS = '-C target-feature=+crt-static' + cargo build --release --locked -p designcraft --target $Target + if ($LASTEXITCODE -ne 0) { throw "nightly cargo build failed: $LASTEXITCODE" } +} finally { + $env:DESIGNCRAFT_BUILD_CHANNEL = $oldChannel + $env:DESIGNCRAFT_VERSION = $oldVersion + $env:DESIGNCRAFT_OVERRIDE_VERSION = $oldOverride +} +$Source = Get-NightlySourceState $Root +try { Assert-NightlySource $Version $env:DESIGNCRAFT_BUILD_SHA $env:DESIGNCRAFT_BUILD_DATE $Source.Head $Source.Status } +catch { throw "source changed during the build: $_" } +$Exe = Join-Path $TargetDir "$Target\release\designcraft.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 'DesignCraft 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 'designcraft.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 ('designcraft.exe' -notin $Names -or 'designcraft-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 922790512..a49203909 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,12 +53,22 @@ $Dist = if ($env:DIST) { $env:DIST } else { Join-Path $Root 'dist\release' } $TargetDir = if ($env:CARGO_TARGET_DIR) { $env:CARGO_TARGET_DIR } else { Join-Path $Root 'target' } New-Item -ItemType Directory -Force -Path $Dist | Out-Null -if (-not $env:DESIGNCRAFT_BUILD_SHA) { $env:DESIGNCRAFT_BUILD_SHA = (git -C $Root rev-parse HEAD 2>$null) } -if (-not $env:DESIGNCRAFT_BUILD_DATE) { $env:DESIGNCRAFT_BUILD_DATE = (Get-Date).ToUniversalTime().ToString('yyyy-MM-dd') } +# Nightly requires the prepared commit and original run date explicitly; nightly.ps1 checks both. +if (-not $Nightly) { + if (-not $env:DESIGNCRAFT_BUILD_SHA) { $env:DESIGNCRAFT_BUILD_SHA = (git -C $Root rev-parse HEAD 2>$null) } + if (-not $env:DESIGNCRAFT_BUILD_DATE) { $env:DESIGNCRAFT_BUILD_DATE = (Get-Date).ToUniversalTime().ToString('yyyy-MM-dd') } +} Write-Output "DesignCraft $Version for Windows $Arch ($Target)" +if ($Nightly) { + & (Join-Path $PSScriptRoot 'nightly.ps1') -Arch $Arch -Version $Version -Target $Target -TargetDir $TargetDir -Dist $Dist -SkipBuild:$SkipBuild -BuildOnly:$BuildOnly + return +} + if (-not $SkipBuild) { + $env:DESIGNCRAFT_BUILD_CHANNEL = 'stable' + # Static CRT: no VC++ redistributable needed. Scoped to the target so host build scripts and # proc-macros are unaffected. $flagVar = 'CARGO_TARGET_' + ($Target.ToUpper() -replace '-', '_') + '_RUSTFLAGS' @@ -83,6 +96,9 @@ foreach ($check in @(@('designcraft.exe', 2), @('designcraft-cli.exe', 3))) { if ($h.Subsystem -ne $check[1]) { throw "$($check[0]) has PE subsystem $($h.Subsystem), expected $($check[1])" } Write-Output "ok $($check[0]): $Arch, PE subsystem $($h.Subsystem)" } +if ((Get-Item -LiteralPath (Join-Path $Bin 'designcraft.exe')).VersionInfo.ProductName -eq 'DesignCraft 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 81efe520a..7f37f8805 100644 --- a/packaging/windows/sign.ps1 +++ b/packaging/windows/sign.ps1 @@ -9,7 +9,9 @@ AZURE_SIGNING_ENDPOINT (e.g. https://eus.codesigning.azure.net), AZURE_SIGNING_ACCOUNT, AZURE_CERT_PROFILE With neither, it prints a warning and leaves the files unsigned (exit code 0), so test builds - still produce installers. + still produce installers. Nightly callers require signing with -Required and can + check signing configuration with -Required -CheckOnly. Compilation uses the + separate -CheckBuildEnvironment mode, without importing signing keys. This is the one place to adapt when the signing setup changes (an HSM/cloud key, a different timestamp server, ...). Optional overrides: WINDOWS_TIMESTAMP_URL, SIGNTOOL (path to signtool.exe). @@ -18,8 +20,11 @@ pwsh packaging/windows/sign.ps1 dist/designcraft.exe dist/Designcraft.msi #> param( - [Parameter(Mandatory = $true, ValueFromRemainingArguments = $true)] - [string[]] $Files + [Parameter(Position = 0, ValueFromRemainingArguments = $true)] + [string[]] $Files, + [switch] $Required, + [switch] $CheckOnly, + [switch] $CheckBuildEnvironment ) $ErrorActionPreference = 'Stop' @@ -27,6 +32,12 @@ function Write-Warn([string] $Message) { if ($env:GITHUB_ACTIONS) { Write-Output "::warning::$Message" } else { Write-Warning $Message } } +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 Find-SignTool { if ($env:SIGNTOOL) { return $env:SIGNTOOL } $onPath = Get-Command signtool.exe -ErrorAction SilentlyContinue @@ -44,11 +55,28 @@ function Invoke-SignTool([string[]] $Arguments) { if ($LASTEXITCODE -ne 0) { throw "signtool $($Arguments[0]) failed with exit code $LASTEXITCODE" } } -$Files = $Files | ForEach-Object { (Resolve-Path $_).Path } -$haveCert = [bool]$env:WINDOWS_CERTIFICATE $azureVars = 'AZURE_TENANT_ID', 'AZURE_CLIENT_ID', 'AZURE_CLIENT_SECRET', 'AZURE_SIGNING_ENDPOINT', 'AZURE_SIGNING_ACCOUNT', 'AZURE_CERT_PROFILE' +if ($CheckBuildEnvironment) { + if ($Required -or $CheckOnly -or $Files) { throw '-CheckBuildEnvironment is separate from signing' } + $names = @('WINDOWS_CERTIFICATE', 'WINDOWS_CERTIFICATE_PASSWORD') + $azureVars + if ($names | Where-Object { [Environment]::GetEnvironmentVariable($_) }) { + throw 'Compilation must not receive signing credentials; use a separate trusted signing step' + } + return +} +$haveCert = [bool]$env:WINDOWS_CERTIFICATE $haveAzure = -not ($azureVars | Where-Object { -not [Environment]::GetEnvironmentVariable($_) }) +if ($Required -and -not $haveCert -and -not $haveAzure) { + throw 'Nightly signing is required: configure WINDOWS_CERTIFICATE or the complete existing Azure signing configuration' +} +if ($CheckOnly) { + if ($Files) { throw '-CheckOnly does not sign files' } + return +} +if (-not $Files) { throw 'At least one file is required for signing' } +$Files = $Files | ForEach-Object { (Resolve-Path $_).Path } + if (-not $haveCert -and -not $haveAzure) { Write-Warn "Windows signing secrets not set (WINDOWS_CERTIFICATE or AZURE_*): leaving unsigned: $($Files -join ', ')" exit 0 @@ -96,6 +124,9 @@ try { Invoke-SignTool ($common + @('/tr', $ts, '/dlib', $dlib.FullName, '/dmdf', $metadata) + $Files) } Invoke-SignTool (@('verify', '/pa', '/v') + $Files) + if ($Required) { + foreach ($file in $Files) { Assert-AuthenticodeSignature (Get-AuthenticodeSignature -LiteralPath $file) } + } } finally { Remove-Item -Recurse -Force $tmp -ErrorAction SilentlyContinue diff --git a/sonar-project.properties b/sonar-project.properties index f1095122d..92ba6637b 100644 --- a/sonar-project.properties +++ b/sonar-project.properties @@ -1,2 +1,3 @@ sonar.projectKey=storytold_designcraft sonar.organization=storytold +sonar.coverage.exclusions=packaging/**