diff --git a/.github/nightly-signing-policy.json b/.github/nightly-signing-policy.json new file mode 100644 index 0000000000..c40512741c --- /dev/null +++ b/.github/nightly-signing-policy.json @@ -0,0 +1,115 @@ +{ + "schema": "craft-nightly-release-policy/v3", + "repository": "storytold/pdfcraft", + "repository_id": 1398086162, + "producer_workflow_id": null, + "producer_workflow_path": ".github/workflows/nightly.yml", + "producer_tooling_revision": "main", + "producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@main", + "signer_workflow_path": ".github/workflows/nightly-sign.yml", + "signer_tooling_revision": "main", + "release_branch": "nightly-signer", + "manual_actors": [ + "bflatastic", + "dylanmtaylor", + "echelon", + "FredApps", + "skylartaylor" + ], + "max_age_seconds": 86400, + "candidate_policy": { + "schema": "craft-nightly-candidate-policy/v3", + "epoch": "pdfcraft-nightly-20261129-initial", + "repository": "storytold/pdfcraft", + "branch": "main", + "required_workflows": [ + { + "workflow_id": 372163538, + "workflow_path": ".github/workflows/ci.yml", + "jobs": [ + { + "name": "gate / gate (ubuntu-24.04)", + "app_id": 15368, + "applicability": "required" + } + ] + } + ], + "sonar": { + "organization": "storytold", + "project": "storytold_pdfcraft", + "app_id": 12526, + "check_name": "SonarCloud Code Analysis", + "details_url": "https://sonarcloud.io/dashboard?id=storytold_pdfcraft&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" + }, + "package_formats": [ + "appimage", + "arch", + "deb", + "flatpak", + "oci", + "rpm" + ] + }, + "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 0000000000..6c528c13be --- /dev/null +++ b/.github/workflows/nightly-sign.yml @@ -0,0 +1,59 @@ +name: PdfCraft release-ref nightly signer + +# Enabled for supervised manual dispatch on the dedicated nightly-signer branch, which only ever +# fast-forwards to reviewed main commits (never the stable release branch). +# A reusable callee does not change context; this must be a real top-level signer-branch 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: pdfcraft-nightly-release + cancel-in-progress: false + +jobs: + release: + # Actual context guards: official repository, manual dispatch, real nightly-signer branch. + if: >- + github.repository == 'storytold/pdfcraft' && + github.event_name == 'workflow_dispatch' && + github.ref == 'refs/heads/nightly-signer' && 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@main + with: + tooling-revision: main + app-name: pdfcraft + producer_run_id: ${{ inputs.producer_run_id }} + producer_run_attempt: ${{ inputs.producer_run_attempt }} + secrets: + APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }} + APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }} + KEYCHAIN_PASSWORD: ${{ secrets.KEYCHAIN_PASSWORD }} + APPLE_ID: ${{ secrets.APPLE_ID }} + APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }} + APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }} + AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }} + AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }} + AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }} + AZURE_SIGNING_ENDPOINT: ${{ secrets.AZURE_SIGNING_ENDPOINT }} + AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }} + AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }} + LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }} + # No secrets: inherit or raw platform values in this caller. Only the isolated native + # callee job may bind the release environment and export its keys; that environment must + # admit nightly-signer alongside release before the first dispatch. diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml new file mode 100644 index 0000000000..b269b4af49 --- /dev/null +++ b/.github/workflows/nightly.yml @@ -0,0 +1,33 @@ +name: PdfCraft unsigned nightly + +# Enabled for supervised manual runs by the reviewed manual actor only; no schedule yet. +# A later explicit opt-in may add a cadence (and turn on nightly-dispatch.yml with it). +on: + workflow_dispatch: + +permissions: + contents: read + +jobs: + unsigned: + # Actual context guards only; no inherited/platform secrets. + if: >- + github.repository == 'storytold/pdfcraft' && + 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@main + with: + tooling-revision: main + app-name: pdfcraft + manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]' + craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 + # One producer run builds every listed platform for one all-or-nothing release. + platforms: '["windows-x86_64","linux-x86_64","macos-aarch64"]' + linux-package-formats: '["deb","rpm","appimage","flatpak","oci","arch"]' diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 8049433060..c4dd3bfd95 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -4,7 +4,7 @@ Every asset PdfCraft includes, bundles or uses to build its published material, with its author, source and licence. The policy is in [AGENTS.md](AGENTS.md) §1. The machine-readable list, with the SHA-256 of every asset, is [ATTRIBUTION.toml](ATTRIBUTION.toml). Licence texts are kept beside the assets and summarised in [NOTICE](NOTICE). -## In this repository (140) +## In this repository (144) | Asset | Title | Author | Licence | Source | Used for | |---|---|---|---|---|---| @@ -107,6 +107,10 @@ Every asset PdfCraft includes, bundles or uses to build its published material, | `assets/app-icon/pdfcraft-1024.png` | PdfCraft app icon, 1024 px on Apple's icon grid | PdfCraft contributors (drawn by the project owner in ArtCraft) | MIT OR Apache-2.0 | Contributor-original (see assets/app-icon/README.md) | Runtime window/Dock icon on macOS (apps/pdfcraft/src/main.rs) | | `assets/app-icon/pdfcraft.icns` | PdfCraft app icon (macOS .icns) | PdfCraft contributors (drawn by the project owner in ArtCraft) | MIT OR Apache-2.0 | Contributor-original (see assets/app-icon/README.md) | macOS app bundle icon | | `assets/app-icon/pdfcraft.ico` | PdfCraft app icon (Windows .ico, 16-256 px) | PdfCraft contributors (drawn by the project owner in ArtCraft) | MIT OR Apache-2.0 | Contributor-original (see assets/app-icon/README.md) | Embedded in pdfcraft.exe by apps/pdfcraft/build.rs (Explorer, taskbar, Start menu, Alt-Tab) | +| `assets/app-icon/pdfcraft-nightly-1024.png` | PdfCraft Nightly app icon, 1024 px on Apple's icon grid | PdfCraft contributors (derived from assets/app-icon/pdfcraft-1024.png) | MIT OR Apache-2.0 | Contributor-original (see assets/app-icon/nightly-provenance.json) | Runtime window/Dock icon for PdfCraft Nightly on macOS (apps/pdfcraft/src/main.rs) | +| `assets/app-icon/pdfcraft-nightly.icns` | PdfCraft Nightly app icon (macOS .icns) | PdfCraft contributors (derived from assets/app-icon/pdfcraft-1024.png) | MIT OR Apache-2.0 | Contributor-original (see assets/app-icon/nightly-provenance.json) | macOS PdfCraft Nightly app bundle icon (packaging/macos/nightly.sh) | +| `assets/app-icon/pdfcraft-nightly.ico` | PdfCraft Nightly app icon (Windows .ico, 16-256 px) | PdfCraft contributors (derived from assets/app-icon/pdfcraft-1024.png) | MIT OR Apache-2.0 | Contributor-original (see assets/app-icon/nightly-provenance.json) | Embedded in Nightly pdfcraft.exe by apps/pdfcraft/build.rs | +| `assets/app-icon/pdfcraft-nightly.png` | PdfCraft Nightly app icon (256 px PNG) | PdfCraft contributors (derived from assets/app-icon/pdfcraft-1024.png) | MIT OR Apache-2.0 | Contributor-original (see assets/app-icon/nightly-provenance.json) | Runtime window icon and Linux/AppImage/Flatpak icon for PdfCraft Nightly | | `assets/app-icon/pdfcraft-document.svg` | PdfCraft PDF document icon (master vector) | Lucide Icons and Contributors (document outline); PdfCraft contributors (PDF badge, lettering and composition) | ISC AND (MIT OR Apache-2.0) | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/file-text.svg); contributor-original composition (assets/app-icon/README.md) | Master artwork for the Windows PDF file type icon; rendered by packaging/icons.sh, without fonts or external images | | `assets/app-icon/pdfcraft-document.ico` | PdfCraft PDF document icon (Windows .ico, 16-256 px) | Lucide Icons and Contributors (document outline); PdfCraft contributors (PDF badge, lettering and composition) | ISC AND (MIT OR Apache-2.0) | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/file-text.svg); contributor-original composition (assets/app-icon/README.md) | Embedded in pdfcraft.exe as resource 2; the Windows installer uses it for PdfCraft.Document and Applications/pdfcraft.exe PDF file associations | | `assets/app-icon/hicolor/16x16/apps/ai.storyteller.pdfcraft.png` | PdfCraft app icon, 16 px | PdfCraft contributors (drawn by the project owner in ArtCraft) | MIT OR Apache-2.0 | Contributor-original (see assets/app-icon/README.md) | Linux hicolor theme icon (packaging/linux/ai.storyteller.pdfcraft.desktop) | diff --git a/ATTRIBUTION.toml b/ATTRIBUTION.toml index 9612d0e0c6..88136e3abb 100644 --- a/ATTRIBUTION.toml +++ b/ATTRIBUTION.toml @@ -1649,6 +1649,50 @@ kind = "icon" usage = "Embedded in pdfcraft.exe by apps/pdfcraft/build.rs (Explorer, taskbar, Start menu, Alt-Tab)" sha256 = "709271d66e07710a3f785ea21b0c85c5228eaf8bebe5058bc0f71f9ef20749eb" +[[asset]] +path = "assets/app-icon/pdfcraft-nightly-1024.png" +title = "PdfCraft Nightly app icon, 1024 px on Apple's icon grid" +author = "PdfCraft contributors (derived from assets/app-icon/pdfcraft-1024.png)" +source = "Contributor-original (see assets/app-icon/nightly-provenance.json)" +licence = "MIT OR Apache-2.0" +licence_file = "assets/app-icon/LICENSE.txt" +kind = "icon" +usage = "Runtime window/Dock icon for PdfCraft Nightly on macOS (apps/pdfcraft/src/main.rs)" +sha256 = "7a9ef45c0a3239584f28517740587a8ab029c11bd1462ea708e5875c96e2fe53" + +[[asset]] +path = "assets/app-icon/pdfcraft-nightly.icns" +title = "PdfCraft Nightly app icon (macOS .icns)" +author = "PdfCraft contributors (derived from assets/app-icon/pdfcraft-1024.png)" +source = "Contributor-original (see assets/app-icon/nightly-provenance.json)" +licence = "MIT OR Apache-2.0" +licence_file = "assets/app-icon/LICENSE.txt" +kind = "icon" +usage = "macOS PdfCraft Nightly app bundle icon (packaging/macos/nightly.sh)" +sha256 = "51392518f539474c67aa3aa6e119eb814ea9aa221e0841baf90f8ebb1c168e8d" + +[[asset]] +path = "assets/app-icon/pdfcraft-nightly.ico" +title = "PdfCraft Nightly app icon (Windows .ico, 16-256 px)" +author = "PdfCraft contributors (derived from assets/app-icon/pdfcraft-1024.png)" +source = "Contributor-original (see assets/app-icon/nightly-provenance.json)" +licence = "MIT OR Apache-2.0" +licence_file = "assets/app-icon/LICENSE.txt" +kind = "icon" +usage = "Embedded in Nightly pdfcraft.exe by apps/pdfcraft/build.rs" +sha256 = "b984192f9417a11a5f7fbfdbaaaf1a1f2a33cb714e7fa2079aa4be01ac2f6c17" + +[[asset]] +path = "assets/app-icon/pdfcraft-nightly.png" +title = "PdfCraft Nightly app icon (256 px PNG)" +author = "PdfCraft contributors (derived from assets/app-icon/pdfcraft-1024.png)" +source = "Contributor-original (see assets/app-icon/nightly-provenance.json)" +licence = "MIT OR Apache-2.0" +licence_file = "assets/app-icon/LICENSE.txt" +kind = "icon" +usage = "Runtime window icon and Linux/AppImage/Flatpak icon for PdfCraft Nightly" +sha256 = "d73ed05f534074cd0cc267fcfcac07b66919331d4331c060521721b77e00b800" + [[asset]] path = "assets/app-icon/pdfcraft-document.svg" title = "PdfCraft PDF document icon (master vector)" diff --git a/Cargo.lock b/Cargo.lock index 1febcc137a..0d003beaef 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6164,6 +6164,7 @@ dependencies = [ "pdfcraft-ui-egui", "pollster 1.0.1", "raw-window-handle", + "rfd", "serde_json", "uds_windows", "wayland-client", diff --git a/apps/pdfcraft/Cargo.toml b/apps/pdfcraft/Cargo.toml index be9cd9a4ea..2dd4be282d 100644 --- a/apps/pdfcraft/Cargo.toml +++ b/apps/pdfcraft/Cargo.toml @@ -26,6 +26,8 @@ egui = { workspace = true, features = ["default_fonts", "monochrome_emoji_fonts" serde_json = { workspace = true } # Records from every crate go to standard error and the log file (`craft_platform::logs`). log = { workspace = true } +# Native error dialog when a Nightly build is launched outside the Launcher. +rfd = { workspace = true } [target.'cfg(target_os = "macos")'.dependencies] # Finder double-click / Open With / Dock drops arrive as Apple events (#73); this small audited @@ -58,7 +60,7 @@ winit = { version = "0.30", default-features = false, features = ["wayland"] } # Which GPU drives which display (EnumDisplayDevices), so the window is drawn on the GPU that # shows it (issue #378). Safe wrappers over Win32; only the `user` feature (which brings `kernel` with it), # and `advapi` for the session id that names the single-instance socket (#3338). -winsafe = { version = "0.0.29", default-features = false, features = ["user", "advapi"] } +winsafe = { version = "0.0.29", default-features = false, features = ["user", "advapi", "shell"] } # Single instance (#282): later launches hand their files to the running app over a Unix domain # socket. `std` has no Unix sockets on Windows, and calling Winsock directly needs unsafe, which # our workspace forbids. Already in the lockfile through zbus; pinned exactly, review before bumping. diff --git a/apps/pdfcraft/build.rs b/apps/pdfcraft/build.rs index b6892e7b9d..409ad99217 100644 --- a/apps/pdfcraft/build.rs +++ b/apps/pdfcraft/build.rs @@ -2,10 +2,16 @@ //! shows in Explorer, the taskbar, the Start menu and Alt-Tab. A separate PDF document icon //! uses resource ID 2; the installer references it as `pdfcraft.exe,-2`. //! -//! 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 `PDFCRAFT_REQUIRE_WINRES=1` turns it -//! into an error (for release builds). +//! The build channel comes from `PDFCRAFT_BUILD_CHANNEL`: `nightly-v1` compiles a Nightly build +//! with its own icon and version, `stable`/unset is the stable build, and anything else is refused +//! rather than silently producing a stable binary with a nightly name. +//! +//! On every other target the Windows resource step does nothing. A missing resource compiler is a +//! warning, so a cross-compile from macOS or Linux still links, unless `PDFCRAFT_REQUIRE_WINRES=1` +//! turns it into an error (for release builds). +#[path = "src/build_channel.rs"] +mod build_channel; #[path = "src/windows_manifest.rs"] mod windows_manifest; @@ -18,10 +24,41 @@ const DELAY_LOADED: [&str; 2] = ["windows.data.pdf.dll", "prntvpt.dll"]; fn main() { println!("cargo:rerun-if-changed=build.rs"); + println!("cargo:rerun-if-changed=src/build_channel.rs"); println!("cargo:rerun-if-changed=../../assets/app-icon/pdfcraft.ico"); + println!("cargo:rerun-if-changed=../../assets/app-icon/pdfcraft-nightly.ico"); println!("cargo:rerun-if-changed=../../assets/app-icon/pdfcraft-document.ico"); println!("cargo:rerun-if-changed=src/windows_manifest.rs"); println!("cargo:rerun-if-env-changed=PDFCRAFT_REQUIRE_WINRES"); + println!("cargo:rerun-if-env-changed=PDFCRAFT_BUILD_SHA"); + println!("cargo:rerun-if-env-changed=PDFCRAFT_BUILD_CHANNEL"); + println!("cargo:rerun-if-env-changed=PDFCRAFT_VERSION"); + println!("cargo:rustc-check-cfg=cfg(pdfcraft_nightly_v1)"); + let nightly = match std::env::var("PDFCRAFT_BUILD_CHANNEL").as_deref() { + Ok("nightly-v1") => { + println!("cargo:rustc-cfg=pdfcraft_nightly_v1"); + true + } + // An empty value (an unset CI input) means the default stable build. + Ok("stable" | "") | Err(std::env::VarError::NotPresent) => false, + _ => { + eprintln!("unsupported PDFCRAFT_BUILD_CHANNEL (expected stable or nightly-v1)"); + std::process::exit(1); + } + }; + let built_version = if nightly { + match std::env::var("PDFCRAFT_VERSION") { + Ok(version) if build_channel::is_nightly_version(&version) => version, + _ => { + eprintln!("nightly-v1 requires an explicit PDFCRAFT_VERSION feed identity"); + std::process::exit(1); + } + } + } else { + std::env::var("CARGO_PKG_VERSION").unwrap_or_default() + }; + println!("cargo:rustc-env=PDFCRAFT_BUILT_VERSION={built_version}"); + if std::env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("windows") { return; } @@ -32,14 +69,19 @@ fn main() { println!("cargo:rustc-link-arg-bins=delayimp.lib"); } let mut res = winresource::WindowsResource::new(); - res.set_icon("../../assets/app-icon/pdfcraft.ico") - .set_icon_with_id("../../assets/app-icon/pdfcraft-document.ico", "2") + res.set_icon(build_channel::windows_icon_path(nightly)) .set_manifest(windows_manifest::WINDOWS_MANIFEST) - .set("ProductName", "PdfCraft") - .set("FileDescription", "PdfCraft PDF workbench") + .set("ProductName", if nightly { "PdfCraft Nightly" } else { "PdfCraft" }) + .set("FileDescription", if nightly { "PdfCraft Nightly PDF workbench" } else { "PdfCraft PDF workbench" }) .set("LegalCopyright", "Copyright (c) the PdfCraft contributors. MIT OR Apache-2.0.") .set("OriginalFilename", "pdfcraft.exe") .set("InternalName", "pdfcraft"); + if nightly { + // The Launcher verifies the PE ProductVersion against the exact feed identity, not FileVersion. + res.set("ProductVersion", &built_version); + } else { + res.set_icon_with_id("../../assets/app-icon/pdfcraft-document.ico", "2"); + } if let Err(e) = res.compile() { if std::env::var_os("PDFCRAFT_REQUIRE_WINRES").is_some() { println!("cargo::error=embedding Windows resources failed: {e}"); diff --git a/apps/pdfcraft/src/build_channel.rs b/apps/pdfcraft/src/build_channel.rs new file mode 100644 index 0000000000..d71d40f0dc --- /dev/null +++ b/apps/pdfcraft/src/build_channel.rs @@ -0,0 +1,57 @@ +//! The build-time nightly identity shared by the build script and its pure regression tests. + +pub fn is_nightly_version(version: &str) -> bool { + let Some((base, suffix)) = version.split_once("-nightly.") else { return false }; + let digits = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit()); + let base: Vec<_> = base.split('.').collect(); + let parts: Vec<_> = suffix.split('.').collect(); + base.len() == 3 + && base.iter().all(|s| digits(s)) + && parts.len() == 4 + && parts[0].len() == 8 + && digits(parts[0]) + && digits(parts[1]) + && digits(parts[2]) + && parts[3].strip_prefix('g').is_some_and(|sha| sha.len() == 12 && sha.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))) +} + +pub fn windows_icon_path(nightly: bool) -> &'static str { + if nightly { "../../assets/app-icon/pdfcraft-nightly.ico" } else { "../../assets/app-icon/pdfcraft.ico" } +} + +#[cfg(test)] +mod tests { + use super::{is_nightly_version, windows_icon_path}; + + #[test] + fn windows_resource_uses_the_flavor_specific_icon_without_changing_stable() { + assert_eq!(windows_icon_path(false), "../../assets/app-icon/pdfcraft.ico"); + assert_eq!(windows_icon_path(true), "../../assets/app-icon/pdfcraft-nightly.ico"); + } + + #[test] + fn explicit_feed_identity_is_required_for_a_nightly_build() { + assert!(is_nightly_version("0.22.0-nightly.20261129.17.1.gabcdef012345")); + for invalid in [ + "", + "0.22.0", + "0.22.0-nightly", + "0.22.0-nightly.20261129", + "0.22.0-nightly.20261129.17.1.gABCDEF012345", + "0.22.0-nightly.20261129.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.22.0-nightly.20261129.1.1.gabcdef012345", + "0.22.0-nightly.20261129.1.1.gabcdef012345/other", + "0.22.0-nightly.20261129.1.1.gabcdef012345\ncargo:rustc-cfg=other", + ] { + assert!(!is_nightly_version(invalid)); + } + } +} diff --git a/apps/pdfcraft/src/build_flavor.rs b/apps/pdfcraft/src/build_flavor.rs new file mode 100644 index 0000000000..b435dd9690 --- /dev/null +++ b/apps/pdfcraft/src/build_flavor.rs @@ -0,0 +1,77 @@ +//! Build-time channel is distinct from a launch selector. A runtime environment cannot promote a stable build. + +use std::ffi::OsString; + +use crate::launch_profile::Profile; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum BuildFlavor { + Stable, + NightlyV1, +} + +pub const COMPILED: BuildFlavor = if cfg!(pdfcraft_nightly_v1) { BuildFlavor::NightlyV1 } else { BuildFlavor::Stable }; + +pub fn require_profile(flavor: BuildFlavor, profile: &Profile) -> Result<(), String> { + match (flavor, profile.is_nightly()) { + (BuildFlavor::NightlyV1, false) => Err("Open PdfCraft Nightly from ArtCraft Launcher".into()), + (BuildFlavor::Stable, true) => Err("This is a stable PdfCraft 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") +} + +#[cfg_attr(not(test), allow(dead_code))] +pub fn version(flavor: BuildFlavor, stable: &str) -> String { + match flavor { + BuildFlavor::Stable => stable.to_owned(), + BuildFlavor::NightlyV1 => format!("{stable} (nightly-v1)"), + } +} + +#[cfg(test)] +mod tests { + use super::{BuildFlavor, needs_native_error, require_profile, version, version_query}; + use crate::launch_profile::Profile; + + #[test] + fn only_a_nightly_desktop_refusal_requests_a_native_dialog() { + assert!(needs_native_error(BuildFlavor::NightlyV1, true)); + assert!(!needs_native_error(BuildFlavor::NightlyV1, false)); + assert!(!needs_native_error(BuildFlavor::Stable, true)); + assert!(!needs_native_error(BuildFlavor::Stable, false)); + } + + #[test] + fn nightly_build_without_a_profile_is_refused_before_startup() { + let started = std::cell::Cell::new(false); + let result = require_profile(BuildFlavor::NightlyV1, &Profile::Stable).map(|()| started.set(true)); + assert!(result.unwrap_err().contains("ArtCraft Launcher")); + assert!(!started.get()); + } + + #[test] + fn stable_and_nightly_flavors_accept_only_their_own_profile() { + let nightly = Profile::NightlyV1(std::path::PathBuf::from("already validated root")); + assert!(require_profile(BuildFlavor::Stable, &Profile::Stable).is_ok()); + assert!(require_profile(BuildFlavor::Stable, &nightly).is_err()); + assert!(require_profile(BuildFlavor::NightlyV1, &nightly).is_ok()); + } + + #[test] + fn nightly_version_query_is_unambiguous_and_never_reinterprets_file_arguments() { + assert_eq!(version(BuildFlavor::Stable, "0.22.0"), "0.22.0"); + assert_eq!(version(BuildFlavor::NightlyV1, "0.22.0"), "0.22.0 (nightly-v1)"); + assert!(version_query(&["--version".into()])); + assert!(version_query(&["-V".into()])); + assert!(!version_query(&["--".into(), "--version".into()])); + assert!(!version_query(&[])); + } +} diff --git a/apps/pdfcraft/src/launch_profile.rs b/apps/pdfcraft/src/launch_profile.rs new file mode 100644 index 0000000000..bb7a475b71 --- /dev/null +++ b/apps/pdfcraft/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. +pub fn validate_root(root: &Path, env: impl Fn(&str) -> Option, exe: Option<&Path>) -> Result { + crate::profile_root::validate(root, env, exe, crate::profile_root::probe_writable) +} + +#[cfg(test)] +mod tests { + use super::{Launch, Profile, VERSION, parse, prepare, version_query}; + use std::cell::Cell; + use std::ffi::OsString; + use std::path::PathBuf; + + fn args(values: &[&str]) -> Vec { + values.iter().map(OsString::from).collect() + } + + fn absolute() -> &'static str { + if cfg!(windows) { r"C:\NightlyData\profiles\pdfcraft" } else { "/nightly-data/profiles/pdfcraft" } + } + + fn nightly() -> Vec { + args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--"]) + } + + #[test] + fn stable_arguments_and_directory_policy_are_unchanged() { + for argv in [args(&[]), args(&["--new-window", "a.pdf"]), args(&["--", "--launch-profile", "file.pdf"])] { + 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", "document with spaces.pdf"])); + let launch = parse(argv).unwrap(); + assert_eq!(launch.profile, Profile::NightlyV1(PathBuf::from(absolute()))); + assert_eq!(launch.args, args(&["--", "--profile-root", "document with spaces.pdf"])); + } + + #[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-window", "--"]), + 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-window", "--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:?}"); + } + 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()); + assert_eq!(super::current(), &Profile::Stable); + assert!(super::validate_root(std::path::Path::new("relative"), |_| None, None).is_err()); + } +} diff --git a/apps/pdfcraft/src/main.rs b/apps/pdfcraft/src/main.rs index 02f10ce7e2..a387760837 100644 --- a/apps/pdfcraft/src/main.rs +++ b/apps/pdfcraft/src/main.rs @@ -40,7 +40,14 @@ use pdfcraft_ui_egui::PdfCraftApp; #[cfg(target_os = "macos")] mod apple_events; +#[cfg(test)] +mod build_channel; +mod build_flavor; mod compositor_gpu; +mod launch_profile; +mod nightly_session; +mod process_identity; +mod profile_root; mod reopen; mod single_instance; mod startup; @@ -50,6 +57,7 @@ mod windows_manifest; /// Freedesktop app id: the `.desktop` file name and the hicolor icon name. const APP_ID: &str = "ai.storyteller.pdfcraft"; +const NIGHTLY_APP_ID: &str = "ai.storyteller.pdfcraft.nightly"; /// The app icon (assets/app-icon/README.md). macOS gets the version on Apple's icon grid, with a /// transparent margin; Windows and Linux get the full-bleed tile. @@ -58,6 +66,99 @@ const APP_ICON_PNG: &[u8] = include_bytes!("../../../assets/app-icon/pdfcraft-10 #[cfg(not(target_os = "macos"))] const APP_ICON_PNG: &[u8] = include_bytes!("../../../assets/app-icon/hicolor/256x256/apps/ai.storyteller.pdfcraft.png"); +#[cfg(target_os = "macos")] +const NIGHTLY_APP_ICON_PNG: &[u8] = include_bytes!("../../../assets/app-icon/pdfcraft-nightly-1024.png"); +#[cfg(not(target_os = "macos"))] +const NIGHTLY_APP_ICON_PNG: &[u8] = include_bytes!("../../../assets/app-icon/pdfcraft-nightly.png"); + +fn is_nightly() -> bool { + launch_profile::current().is_nightly() +} + +fn app_id() -> &'static str { + if is_nightly() { NIGHTLY_APP_ID } else { APP_ID } +} + +fn app_title() -> &'static str { + if is_nightly() { "PdfCraft Nightly" } else { "PdfCraft" } +} + +fn app_icon_png() -> &'static [u8] { + if is_nightly() { NIGHTLY_APP_ICON_PNG } else { APP_ICON_PNG } +} + +fn built_version() -> &'static str { + env!("PDFCRAFT_BUILT_VERSION") +} + +fn nightly_version_line() -> String { + format!("PdfCraft {} (nightly-v1)", built_version()) +} + +fn initialize_nightly_process_identity() -> Result<(), String> { + process_identity::initialize(build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1, NIGHTLY_APP_ID) +} + +fn refusal_dialog(flavor: build_flavor::BuildFlavor, desktop_session: bool, macos: bool) -> bool { + build_flavor::needs_native_error(flavor, desktop_session) && !macos +} + +fn report_launch_profile_error(error: &str) { + let _ = std::io::Write::write_fmt(&mut std::io::stderr(), format_args!("PdfCraft launch profile: {error}\n")); + let desktop_session = cfg!(windows) + || cfg!(target_os = "macos") + || (cfg!(target_os = "linux") && ["DISPLAY", "WAYLAND_DISPLAY"].into_iter().any(|key| std::env::var_os(key).is_some_and(|v| !v.is_empty()))); + if refusal_dialog(build_flavor::COMPILED, desktop_session, cfg!(target_os = "macos")) { + if let Err(err) = initialize_nightly_process_identity() { + let _ = std::io::Write::write_fmt(&mut std::io::stderr(), format_args!("PdfCraft launch profile: {err}\n")); + return; + } + let _ = rfd::MessageDialog::new() + .set_title("PdfCraft Nightly") + .set_description(error) + .set_level(rfd::MessageLevel::Error) + .set_buttons(rfd::MessageButtons::Ok) + .show(); + } +} + +/// Select the immutable launch profile before logging, updates, fonts or saved state, and answer +/// the version query before any of that: `None` means the query has been answered. +fn prepare_launch() -> Option> { + let argv: Vec<_> = std::env::args_os().skip(1).collect(); + if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && (build_flavor::version_query(&argv) || launch_profile::version_query(&argv)) + { + let _ = std::io::Write::write_fmt(&mut std::io::stdout().lock(), format_args!("{}\n", nightly_version_line())); + return None; + } + let early = launch_profile::parse(argv) + .and_then(|launch| { + build_flavor::require_profile(build_flavor::COMPILED, &launch.profile)?; + initialize_nightly_process_identity()?; + Ok(launch) + }) + .and_then(|launch| { + launch_profile::prepare(launch, |root| { + launch_profile::validate_root(root, |key| std::env::var_os(key), std::env::current_exe().ok().as_deref()) + }) + }) + .unwrap_or_else(|error| { + report_launch_profile_error(&error); + std::process::exit(2) + }); + if let Some(root) = early.profile.root() + && let Err(error) = pdfcraft_ui_egui::settings::install_nightly_profile_root(root.to_path_buf()) + { + report_launch_profile_error(&error); + std::process::exit(2); + } + if let Err(error) = launch_profile::install(early.profile) { + report_launch_profile_error(&error); + std::process::exit(2); + } + Some(early.args) +} + /// What `-h` / `--help` prints (#4076): a hint, not the full option list (that is this file's /// doc comment and the README). Scripts want `pdfcraft-cli`, which never opens a window. const USAGE: &str = "\ @@ -104,7 +205,7 @@ fn portable() -> bool { /// folder is left alone when the new one already exists or the move fails. A portable copy leaves /// the per-user folders alone. fn migrate_legacy_folders() { - if portable() { + if is_nightly() || portable() { return; } let mut moves = vec![(eframe::storage_dir("PrintCraft"), eframe::storage_dir("PdfCraft"))]; @@ -165,9 +266,12 @@ fn main() -> eframe::Result { } // aws-lc detects the CPU's features here, where it used to before `main` (`init_crypto`). pdfcraft_engine::sign::init_crypto(); + let Some(raw_args) = prepare_launch() else { return Ok(()) }; // Windows: the update helper is a copy of this program started with `--finish-update`. #[cfg(windows)] - if let Some(result) = craft_update::self_update::finish(&pdfcraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::>()) { + if !is_nightly() + && let Some(result) = craft_update::self_update::finish(&pdfcraft_ui_egui::UPDATE_APP, &raw_args) + { std::process::exit(i32::from(result.is_err())); } // First, so the panic hook and every start-up warning are recorded. @@ -193,7 +297,14 @@ fn main() -> eframe::Result { let _ = std::io::Write::write_fmt(&mut std::io::stderr(), format_args!("pdfcraft: {report}\n")); } })); - let mut startup = startup::Arguments::parse(std::env::args().skip(1)); + let mut startup = if is_nightly() { + // Nightly-v1 already parsed `--launch-profile ... --profile-root ... -- [files...]`; + // every token after the leading `--` is a literal file path. + let files = raw_args.into_iter().skip(1).map(|a| craft::platform::default_app::path_from_arg(a.to_string_lossy().into_owned())).collect(); + startup::Arguments { files, ..Default::default() } + } else { + startup::Arguments::parse(raw_args.into_iter().map(|a| a.to_string_lossy().into_owned())) + }; if startup.version { return print_and_exit(&format!("pdfcraft {}", pdfcraft_engine::build_info::version())); } @@ -204,18 +315,29 @@ fn main() -> eframe::Result { let may_hand_off = startup.may_hand_off(); let startup::Arguments { files, options, control_port, control_token, control_token_file, create_images, combine, two_paged, .. } = startup; // A bad control configuration stops the launch before any window opens. - let control = match control_options(control_port, control_token, control_token_file) { - Ok(control) => control, - Err(message) => usage_error(&message), + // Nightly disables the control server so inherited stable env vars cannot open one. + let control = if is_nightly() { + None + } else { + match control_options(control_port, control_token, control_token_file) { + Ok(control) => control, + Err(message) => usage_error(&message), + } }; migrate_legacy_folders(); // The log file stays in the data folder; opened after the arguments (so `--version` leaves // no file behind) and after the PrintCraft migration (which a fresh folder would block). // Records logged until now are written to it first. - let data_dir = if portable() { settings_dir() } else { eframe::storage_dir("PdfCraft") }; + let data_dir = if let Some(root) = launch_profile::current().root() { + Some(root.to_path_buf()) + } else if portable() { + settings_dir() + } else { + eframe::storage_dir("PdfCraft") + }; if let (Some(logger), Some(dir)) = (logger, data_dir) { match logger.attach_dir(&dir.join("logs")) { - Ok(path) => log::info!("PdfCraft {}, log file {}", pdfcraft_engine::build_info::version(), path.display()), + Ok(path) => log::info!("{} {}, log file {}", app_title(), built_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}"), } @@ -227,11 +349,28 @@ fn main() -> eframe::Result { // Absolute for this instance too: links relative to a document resolve against its folder, // never the working directory. let files = single_instance::absolute(&files); - let instance = match single_instance::claim(&files, may_hand_off, combine) { + let instance = match single_instance::claim(&files, may_hand_off, combine, launch_profile::current().root()) { single_instance::Claim::HandedOff => return Ok(()), single_instance::Claim::Primary(server) => Some(server), single_instance::Claim::Alone => None, }; + let (nightly_watch, previous_unclean) = + match nightly_session::Session::begin_with_health(launch_profile::current().root(), built_version(), option_env!("PDFCRAFT_BUILD_SHA")) { + Ok((watch, unavailable)) => { + if unavailable { + log::warn!("another PdfCraft Nightly holds this profile's session lease; this window keeps no health record"); + } + let unclean = watch.as_ref().is_some_and(nightly_session::Session::previous_unclean); + (std::sync::Arc::new(std::sync::Mutex::new(watch)), unclean) + } + Err(error) => { + log::warn!("Nightly session state: {error}"); + (std::sync::Arc::new(std::sync::Mutex::new(None)), false) + } + }; + if previous_unclean { + log::warn!("the previous PdfCraft Nightly ended without finishing its session record"); + } // Who draws the window frame: the platform and Preferences ▸ Use system title bar decide, // unless `PDFCRAFT_TITLEBAR` overrides them. The store is read here and opened again by the // app (each window attempt opens its own: the OpenGL retry runs the creator again). @@ -247,7 +386,7 @@ fn main() -> eframe::Result { let frame = craft::window::policy::decide_for(craft::window::Prefix::new("PDFCRAFT"), craft::window::policy::Backend::from_env(), title_bar); let lang = startup_lang(saved_lang.as_deref(), &options); let choice = renderer_choice(std::env::var("PDFCRAFT_RENDERER").ok().as_deref()); - let launch = Launch { files, options, control, create_images, combine, frame, lang, two_paged }; + let launch = Launch { files, options, control, create_images, combine, frame, lang, two_paged, nightly_watch: nightly_watch.clone() }; // Finder, Open With and the Dock deliver files as Apple events, not arguments; catch the one // that launched us as well as later ones. Lives until the event loop returns. #[cfg(target_os = "macos")] @@ -256,7 +395,7 @@ fn main() -> eframe::Result { let started = Rc::new(Cell::new(false)); let first = if choice == RendererChoice::Gl { eframe::Renderer::Glow } else { eframe::Renderer::Wgpu }; let result = eframe::run_native( - "PdfCraft", + app_title(), native_options(launch.integrated(), first), app_creator( launch.clone(), @@ -266,7 +405,7 @@ fn main() -> eframe::Result { &apple_events, ), ); - match result { + let final_result = match result { // Only a renderer that couldn't start: without a window or display at all, OpenGL can't // help either, and winit's own error says more. Err(e @ eframe::Error::Wgpu(_)) if retry_with_gl(choice, started.get()) => { @@ -274,11 +413,11 @@ fn main() -> eframe::Result { // usually still works there, so that's better than quitting. log::error!("the GPU renderer (wgpu) didn't start: {e}. Starting with OpenGL instead; set PDFCRAFT_RENDERER=gl to skip wgpu."); eframe::run_native( - "PdfCraft", + app_title(), native_options(launch.integrated(), eframe::Renderer::Glow), app_creator( launch, - started, + Rc::clone(&started), instance.as_ref(), #[cfg(target_os = "macos")] &apple_events, @@ -286,7 +425,9 @@ fn main() -> eframe::Result { ) } other => other, - } + }; + nightly_session::finish_once(&nightly_watch, started.get()); + final_result } /// Which renderer to start with, from `PDFCRAFT_RENDERER`. @@ -358,12 +499,12 @@ fn retry_with_gl(choice: RendererChoice, app_started: bool) -> bool { /// The window and renderer settings for one run. fn native_options(integrated: bool, renderer: eframe::Renderer) -> eframe::NativeOptions { let mut viewport = egui::ViewportBuilder::default() - .with_title("PdfCraft") + .with_title(app_title()) .with_inner_size([1440.0, 920.0]) .with_min_inner_size(pdfcraft_ui_egui::MIN_WINDOW_SIZE) .with_drag_and_drop(true) - // Wayland app id: matches packaging/linux/ai.storyteller.pdfcraft.desktop. - .with_app_id(APP_ID); + // Wayland app id: matches packaging/linux/ai.storyteller.pdfcraft.desktop (or .nightly). + .with_app_id(app_id()); // eframe replaces ICON_BIG with a system-sized icon on its first active frame. // An explicitly empty icon disables that setter (None selects eframe's default). // Windows installs both sizes directly through winit in app_creator instead. @@ -373,7 +514,7 @@ fn native_options(integrated: bool, renderer: eframe::Renderer) -> eframe::Nativ } // Dock, taskbar, Alt-Tab and launcher icon when running unbundled. #[cfg(not(target_os = "windows"))] - match eframe::icon_data::from_png_bytes(APP_ICON_PNG) { + match eframe::icon_data::from_png_bytes(app_icon_png()) { Ok(icon) => viewport = viewport.with_icon(icon), Err(e) => log::warn!("app icon: {e}"), } @@ -413,6 +554,7 @@ struct Launch { /// The language the interface starts in, whose fonts are installed with the runtime. lang: pdfcraft_ui_egui::i18n::Lang, two_paged: bool, + nightly_watch: nightly_session::Shared, } impl Launch { @@ -444,7 +586,7 @@ fn install_runtime( let system = craft::ui::runtime::env::SystemReader::start(move || ctx.request_repaint()); let spec = InstallSpec::new(ShellInfo::default().backend(Backend::from_env()), std::sync::Arc::new(SystemWindows)) .system(system) - .app_id(APP_ID) + .app_id(app_id()) .frame(frame); craft::ui::shell::embed::install(&cc.egui_ctx, spec, &pdfcraft_ui_egui::fonts::ui_fonts(lang)) .map(drop) @@ -483,7 +625,7 @@ fn install_taskbar_icon(png: &[u8], set: impl FnOnce(winit::window::Icon)) { #[cfg(target_os = "windows")] fn set_taskbar_icon(window: &winit::window::Window) { use winit::platform::windows::{IconExtWindows as _, WindowExtWindows as _}; - install_taskbar_icon(APP_ICON_PNG, |icon| window.set_taskbar_icon(Some(icon))); + install_taskbar_icon(app_icon_png(), |icon| window.set_taskbar_icon(Some(icon))); // The title bar's icon: the small image drawn for this scale in the exe's own icon (build.rs). let side = (16.0 * window.scale_factor()).round().clamp(16.0, 256.0) as u32; match winit::window::Icon::from_resource(1, Some(winit::dpi::PhysicalSize::new(side, side))) { @@ -499,7 +641,7 @@ fn app_creator<'a>( instance: Option<&'a single_instance::Server>, #[cfg(target_os = "macos")] apple_events: &'a apple_events::AppleEvents, ) -> eframe::AppCreator<'a> { - let Launch { files, options, control, create_images, combine, frame, lang, two_paged } = launch; + let Launch { files, options, control, create_images, combine, frame, lang, two_paged, nightly_watch } = launch; Box::new(move |cc| { started.set(true); install_runtime(cc, frame, lang)?; @@ -516,6 +658,8 @@ fn app_creator<'a>( #[cfg(target_os = "macos")] let apple_events_poll = apple_events.connect(intake.sender(), &cc.egui_ctx); let mut app = PdfCraftApp::with_intake(&cc.egui_ctx, intake); + let exit_watch = nightly_watch.clone(); + app.at_exit = Some(Box::new(move || nightly_session::finish_once(&exit_watch, true))); #[cfg(target_os = "macos")] { app.os_events = Some(apple_events_poll); @@ -531,7 +675,7 @@ fn app_creator<'a>( if let Some(window) = cc.winit_window() { set_taskbar_icon(window); } - app.set_startup_update_check(true); + app.set_startup_update_check(!is_nightly()); app.printer_source = Some(pdfcraft_ui_egui::system_printers()); app.two_sided_source = Some(pdfcraft_ui_egui::system_two_sided()); app.os_key_store_ids = cfg!(any(target_os = "macos", target_os = "windows")); @@ -839,3 +983,31 @@ fn pick_adapter(adapters: &[(u32, u32, eframe::wgpu::DeviceType)], displays: &[D #[cfg(test)] mod tests; + +#[cfg(test)] +mod nightly_bootstrap_tests { + use super::{ + APP_ICON_PNG, APP_ID, app_icon_png, app_id, app_title, built_version, initialize_nightly_process_identity, is_nightly, nightly_version_line, + refusal_dialog, + }; + use crate::build_flavor::BuildFlavor; + + #[test] + fn stable_defaults_and_nightly_version_line() { + assert!(!is_nightly()); + assert_eq!(app_id(), APP_ID); + assert_eq!(app_title(), "PdfCraft"); + assert_eq!(app_icon_png(), APP_ICON_PNG); + assert!(!built_version().is_empty()); + assert_eq!(nightly_version_line(), format!("PdfCraft {} (nightly-v1)", built_version())); + assert!(initialize_nightly_process_identity().is_ok()); + } + + #[test] + fn refusal_dialog_never_blocks_macos_or_headless_or_stable() { + assert!(refusal_dialog(BuildFlavor::NightlyV1, true, false)); + assert!(!refusal_dialog(BuildFlavor::NightlyV1, true, true)); + assert!(!refusal_dialog(BuildFlavor::NightlyV1, false, false)); + assert!(!refusal_dialog(BuildFlavor::Stable, true, false)); + } +} diff --git a/apps/pdfcraft/src/nightly_session.rs b/apps/pdfcraft/src/nightly_session.rs new file mode 100644 index 0000000000..6b96923f91 --- /dev/null +++ b/apps/pdfcraft/src/nightly_session.rs @@ -0,0 +1,230 @@ +//! App-private Nightly session health, not telemetry or a Launcher protocol. +//! A live owner holds a separate persistent lease; secondary launches never rewrite its record. +//! Dropping the guard does not clear the marker. Only the app's controlled return path does. + +use std::fs::{File, OpenOptions}; +use std::io::{self, Read, Write as _}; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex, PoisonError}; + +const RECORD: &str = "nightly-session.json"; +const LEASE: &str = "nightly-session.lock"; +const MAX_METADATA_BYTES: usize = 256; + +pub struct Session { + _lease: File, + path: PathBuf, + own_record: Vec, + 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), + } +} + +/// The owner's session, shared by the app's exit hook (macOS) and the code after the event loop. +pub type Shared = Arc>>; + +/// The controlled return ([`Session::finish`]) by whichever path comes first; later calls do nothing. +pub fn finish_once(shared: &Shared, unclean_notice_shown: bool) { + let watch = shared.lock().unwrap_or_else(PoisonError::into_inner).take(); + if let Some(watch) = watch + && let Err(error) = watch.finish(unclean_notice_shown) + { + log::warn!("Nightly session state was left intact: {error}"); + } +} + +fn write_atomic_no_follow(path: &Path, bytes: &[u8]) -> io::Result<()> { + match std::fs::symlink_metadata(path) { + Ok(metadata) if !metadata.file_type().is_file() => { + return Err(io::Error::other("Nightly session state must be a regular file, not an alias or directory")); + } + Ok(_) => {} + Err(error) if error.kind() == io::ErrorKind::NotFound => {} + Err(error) => return Err(error), + } + let dir = path.parent().unwrap_or_else(|| Path::new(".")); + for attempt in 0..32_u32 { + let temporary = dir.join(format!(".{}.{}-{attempt}.tmp", path.file_name().unwrap_or_default().to_string_lossy(), std::process::id())); + let mut file = match OpenOptions::new().write(true).create_new(true).open(&temporary) { + Ok(file) => file, + Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue, + Err(error) => return Err(error), + }; + let written = file.write_all(bytes).and_then(|()| file.sync_all()); + drop(file); + if let Err(error) = written { + let _ = std::fs::remove_file(&temporary); + return Err(error); + } + return match std::fs::rename(&temporary, path) { + Ok(()) => Ok(()), + Err(error) => { + let _ = std::fs::remove_file(&temporary); + Err(error) + } + }; + } + Err(io::Error::other("no free temporary name for the Nightly session state")) +} + +impl Session { + 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)) + } + + pub fn begin(root: Option<&Path>, version: &str, commit: Option<&str>) -> io::Result> { + let Some(root) = root else { return Ok(None) }; + if version.len() > MAX_METADATA_BYTES || commit.is_some_and(|c| c.len() > MAX_METADATA_BYTES) { + return Err(io::Error::new(io::ErrorKind::InvalidInput, "Nightly session provenance exceeds its metadata bound")); + } + let lease_path = root.join(LEASE); + let _ = 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, + })) + .map_err(io::Error::other)?; + write_atomic_no_follow(&path, &own_record)?; + Ok(Some(Self { _lease: lease, path, own_record, previous_unclean })) + } + + pub fn previous_unclean(&self) -> bool { + self.previous_unclean + } + + pub fn finish(self, unclean_notice_shown: bool) -> io::Result<()> { + if self.previous_unclean && !unclean_notice_shown { + return Ok(()); + } + self.complete() + } + + 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).saturating_add(1)).read_to_end(&mut current)?; + if current != self.own_record { + return Err(io::Error::other("Nightly session record was replaced by another writer")); + } + std::fs::remove_file(&self.path) + } +} + +#[cfg(test)] +mod tests { + use super::{LEASE, MAX_METADATA_BYTES, RECORD, Session, Shared, finish_once}; + use std::path::PathBuf; + use std::sync::atomic::{AtomicU64, Ordering}; + use std::sync::{Arc, Mutex}; + + static COUNTER: AtomicU64 = AtomicU64::new(0); + + struct Fixture(PathBuf); + + impl Fixture { + fn new() -> Self { + let n = COUNTER.fetch_add(1, Ordering::Relaxed); + let dir = std::env::temp_dir().join(format!("pdfcraft-nightly-session-{}-{n}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + Self(dir) + } + } + + impl Drop for Fixture { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + + #[test] + fn clean_exit_clears_record_and_unclean_drop_leaves_it() { + let fixture = Fixture::new(); + let first = Session::begin(Some(&fixture.0), "first", Some("abc")).unwrap().unwrap(); + assert!(!first.previous_unclean()); + assert!(Session::begin(Some(&fixture.0), "busy", None).unwrap().is_none()); + first.complete().unwrap(); + assert!(!fixture.0.join(RECORD).exists()); + let dropped = Session::begin(Some(&fixture.0), "dropped", None).unwrap().unwrap(); + drop(dropped); + let next = Session::begin(Some(&fixture.0), "next", None).unwrap().unwrap(); + assert!(next.previous_unclean()); + next.finish(false).unwrap(); + assert!(fixture.0.join(RECORD).exists()); + let final_run = Session::begin(Some(&fixture.0), "final", None).unwrap().unwrap(); + assert!(final_run.previous_unclean()); + final_run.finish(true).unwrap(); + assert!(!fixture.0.join(RECORD).exists()); + } + + #[test] + fn finish_once_runs_only_once() { + let fixture = Fixture::new(); + let shared: Shared = Arc::new(Mutex::new(Session::begin(Some(&fixture.0), "quitting", None).unwrap())); + finish_once(&shared, false); + assert!(!fixture.0.join(RECORD).exists()); + let successor = Session::begin(Some(&fixture.0), "successor", None).unwrap().unwrap(); + 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); + successor.complete().unwrap(); + } + + #[test] + fn provenance_is_bounded() { + let fixture = Fixture::new(); + assert!(Session::begin(Some(&fixture.0), &"x".repeat(MAX_METADATA_BYTES + 1), None).is_err()); + assert!(Session::begin(None, "", None).unwrap().is_none()); + assert_eq!(LEASE, "nightly-session.lock"); + } + + #[test] + fn begin_with_health_reports_busy_and_complete_refuses_replaced_record() { + let fixture = Fixture::new(); + let (owner, unavailable) = Session::begin_with_health(Some(&fixture.0), "owner", Some("123")).unwrap(); + assert!(!unavailable); + let owner = owner.unwrap(); + let (secondary, sec_unavailable) = Session::begin_with_health(Some(&fixture.0), "secondary", None).unwrap(); + assert!(secondary.is_none()); + assert!(sec_unavailable); + std::fs::write(fixture.0.join(RECORD), b"foreign writer").unwrap(); + assert!(owner.complete().is_err()); + assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), b"foreign writer"); + } + + #[cfg(unix)] + #[test] + fn symlink_record_or_lease_is_refused() { + let fixture = Fixture::new(); + let target = fixture.0.join("outside.txt"); + std::fs::write(&target, b"keep").unwrap(); + for name in [LEASE, RECORD] { + let link = fixture.0.join(name); + std::os::unix::fs::symlink(&target, &link).unwrap(); + assert!(Session::begin(Some(&fixture.0), "nightly", None).is_err()); + assert_eq!(std::fs::read(&target).unwrap(), b"keep"); + std::fs::remove_file(&link).unwrap(); + } + } +} diff --git a/apps/pdfcraft/src/process_identity.rs b/apps/pdfcraft/src/process_identity.rs new file mode 100644 index 0000000000..1b67b5218c --- /dev/null +++ b/apps/pdfcraft/src/process_identity.rs @@ -0,0 +1,65 @@ +//! Set the immutable nightly Windows identity before any native window or COM service. +//! Stable deliberately leaves its implicit shortcut/path identity unchanged. + +use std::sync::OnceLock; + +pub fn initialize(nightly: bool, app_id: &str) -> Result<(), String> { + configure(nightly && cfg!(windows), app_id, |id| { + static RESULT: OnceLock> = OnceLock::new(); + RESULT + .get_or_init(|| { + #[cfg(windows)] + { + winsafe::SetCurrentProcessExplicitAppUserModelID(id) + .map_err(|error| format!("cannot set the nightly Windows identity: {error}"))?; + let actual = winsafe::GetCurrentProcessExplicitAppUserModelID() + .map_err(|error| format!("cannot read back the nightly Windows identity: {error}"))?; + if actual != id { + return Err("the native Windows identity did not match the selected nightly channel".into()); + } + Ok(()) + } + #[cfg(not(windows))] + { + let _ = id; + Ok(()) + } + }) + .clone() + }) +} + +fn configure(explicit_nightly: bool, app_id: &str, set: impl FnOnce(&str) -> Result<(), String>) -> Result<(), String> { + if explicit_nightly { set(app_id) } else { Ok(()) } +} + +#[cfg(test)] +mod tests { + use super::configure; + + #[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()); + assert!(super::initialize(false, "nightly-id").is_ok()); + } +} diff --git a/apps/pdfcraft/src/profile_root.rs b/apps/pdfcraft/src/profile_root.rs new file mode 100644 index 0000000000..73583db29e --- /dev/null +++ b/apps/pdfcraft/src/profile_root.rs @@ -0,0 +1,484 @@ +//! App-owned nightly profile fences; no stable fallback, migration or process environment changes. + +use std::ffi::OsString; +use std::path::{Component, Path, PathBuf}; + +const PORTABLE_DATA_DIR: &str = "PdfCraftData"; +const PORTABLE_MARKERS: [&str; 2] = ["portable.txt", "PdfCraft.portable"]; + +/// The app id of the nightly Flatpak bundle (`packaging/linux/flatpak-bundle.sh`): the one Flatpak +/// instance whose sandbox is this channel's own. +pub const NIGHTLY_FLATPAK_ID: &str = "ai.storyteller.pdfcraft.nightly"; + +/// The app id eframe derives stable's storage folder from. +const EFRAME_APP_ID: &str = "ai.storyteller.pdfcraft"; + +/// The subfolder autosave and recovery write inside a nightly profile. +pub const AUTOSAVE: &str = "autosave"; + +const PROFILE_FOLDERS: [&str; 5] = [AUTOSAVE, "logs", "single-instance", "dictionary", "Digital IDs"]; + +#[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(); + match (platform.ignores_case(), value.to_str()) { + (true, Some(text)) => OsString::from(text.to_lowercase()), + _ => value.to_os_string(), + } + }) + .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 + && let Some(bundle) = exe.ancestors().find(|p| p.extension().is_some_and(|ext| ext.eq_ignore_ascii_case("app"))) + { + return Ok(bundle.to_path_buf()); + } + Ok(parent.to_path_buf()) +} + +/// Every stable PdfCraft data root of this platform, plus the install folders and the running +/// install ([`installation_boundary`]). +fn forbidden_roots(platform: Platform, env: &impl Fn(&str) -> Option, exe: &Path) -> Result, String> { + let mut roots = match platform { + Platform::Windows => { + let mut roots = Vec::new(); + for key in ["APPDATA", "LOCALAPPDATA"] { + let base = required_base(env, key)?; + roots.push(base.join("PdfCraft")); + roots.push(base.join("PrintCraft")); + } + roots.push(required_base(env, "APPDATA")?.join(EFRAME_APP_ID)); + 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("PdfCraft")); + } + } + 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("pdfcraft"))) + .collect::, _>>()?; + let data = xdg_base(env, "XDG_DATA_HOME", ".local/share")?; + roots.push(data.join("PdfCraft")); + roots.push(data.join("PrintCraft")); + roots.push(data.join(EFRAME_APP_ID)); + roots.extend(["/usr/bin/pdfcraft", "/usr/local/bin/pdfcraft", "/opt/pdfcraft"].map(PathBuf::from)); + roots.push(required_base(env, "HOME")?.join(".var/app/ai.storyteller.pdfcraft")); + roots + } + Platform::Mac => { + let home = required_base(env, "HOME")?; + let library = home.join("Library"); + vec![ + library.join("Application Support/PdfCraft"), + library.join("Application Support/PrintCraft"), + library.join("Caches/PdfCraft"), + library.join("Caches/ai.storyteller.pdfcraft"), + library.join("Application Support").join(EFRAME_APP_ID), + library.join("Preferences/PdfCraft"), + library.join("Preferences/ai.storyteller.pdfcraft.plist"), + library.join("Saved Application State/ai.storyteller.pdfcraft.savedState"), + home.join("Applications/PdfCraft.app"), + PathBuf::from("/Applications/PdfCraft.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")); + } + match std::fs::symlink_metadata(&child) { + Ok(metadata) if !metadata.file_type().is_dir() => { + return Err(format!("the nightly {label} must be a directory, not a file or an alias")); + } + Ok(_) => {} + Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} + Err(error) => return Err(format!("cannot inspect the nightly {label}: {error}")), + } + 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}"))?; + let path = entry.path(); + let metadata = std::fs::symlink_metadata(&path).map_err(|e| format!("cannot inspect the nightly profile: {e}"))?; + // Settings and session state are ordinary files, not directories. Keep the existing + // directory-boundary check for folders (including the known folder-only entries). + let folder_only = PROFILE_FOLDERS.iter().any(|name| entry.file_name().eq_ignore_ascii_case(name)); + if metadata.is_file() && !folder_only { + private_regular_file(&path, &metadata)?; + } else { + private_subdirectory(root, entry.file_name(), "profile entry")?; + } + } + Ok(()) +} + +/// Persisted files must have their own ordinary file identity, not an alias to other data. +fn private_regular_file(path: &Path, metadata: &std::fs::Metadata) -> Result<(), String> { + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt as _; + if metadata.nlink() != 1 { + return Err("the nightly profile file must not be shared".into()); + } + } + #[cfg(windows)] + { + use winsafe::{HFILE, co}; + let (file, _) = HFILE::CreateFile( + path.to_str().ok_or("the nightly profile file path is not textual")?, + co::GENERIC::default(), + Some(co::FILE_SHARE::READ | co::FILE_SHARE::WRITE | co::FILE_SHARE::DELETE), + None, + co::DISPOSITION::OPEN_EXISTING, + co::FILE_ATTRIBUTE::NORMAL, + Some(co::FILE_FLAG::OPEN_REPARSE_POINT), + None, + None, + ) + .map_err(|e| e.to_string())?; + let info = file.GetFileInformationByHandle().map_err(|e| e.to_string())?; + if info.dwFileAttributes.has(co::FILE_ATTRIBUTE::REPARSE_POINT | co::FILE_ATTRIBUTE::DIRECTORY) { + return Err("the nightly profile file must not be an alias or directory".into()); + } + if info.nNumberOfLinks != 1 { + return Err("the nightly profile file must not be shared".into()); + } + } + let _ = (path, metadata); + Ok(()) +} + +/// Recognise the shared portable data namespace in both the supplied and resolved path. +fn is_portable_layout(path: &Path, platform: Platform) -> bool { + let matches_portable_dir = |component: &std::ffi::OsStr| { + if platform.ignores_case() { component.eq_ignore_ascii_case(PORTABLE_DATA_DIR) } else { component == PORTABLE_DATA_DIR } + }; + if path.components().any(|component| matches_portable_dir(component.as_os_str())) { + return true; + } + path.ancestors().any(|dir| PORTABLE_MARKERS.iter().any(|marker| std::fs::symlink_metadata(dir.join(marker)).is_ok())) +} + +/// Exclusive writability probe inside the validated profile directory. +pub fn probe_writable(dir: &Path) -> std::io::Result<()> { + for attempt in 0..32_u32 { + let probe = dir.join(format!(".pdfcraft-nightly-probe-{}-{attempt}.tmp", std::process::id())); + match std::fs::OpenOptions::new().write(true).create_new(true).open(&probe) { + Ok(file) => { + drop(file); + let _ = std::fs::remove_file(&probe); + return Ok(()); + } + Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue, + Err(error) => return Err(error), + } + } + Err(std::io::Error::other("could not create a unique probe file in the nightly profile")) +} + +/// Validate and prepare the private nightly profile root before any startup side effects. +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")?; + let chosen = canonical_future(root)?; + if let Some(configured) = env("PDFCRAFT_CONFIG_DIR").filter(|v| !v.is_empty()) { + let configured = canonical_future(&absolute(PathBuf::from(configured), "PDFCRAFT_CONFIG_DIR")?)?; + if !configured.starts_with(&chosen) { + return Err("nightly-v1 cannot be combined with PDFCRAFT_CONFIG_DIR outside its own profile".into()); + } + } + if platform != Platform::Windows + && let Some(id) = env("FLATPAK_ID").filter(|v| !v.is_empty()) + && id.to_string_lossy() != NIGHTLY_FLATPAK_ID + { + return Err("nightly-v1 cannot inherit another Flatpak app's instance; launch through the native Launcher".into()); + } + if is_portable_layout(root, platform) || is_portable_layout(&chosen, platform) { + return Err("the nightly root must not use a portable PdfCraft installation or its PdfCraftData 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()); + } + entries_stay_inside(&chosen)?; + private_subdirectory(&chosen, AUTOSAVE, "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, AUTOSAVE, "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::{NIGHTLY_FLATPAK_ID, PROFILE_FOLDERS, Platform, probe_writable, validate_for}; + use std::collections::BTreeMap; + use std::ffi::OsString; + use std::path::{Path, PathBuf}; + use std::sync::atomic::{AtomicU64, Ordering}; + + static COUNTER: AtomicU64 = AtomicU64::new(0); + + struct Fixture { + root: PathBuf, + env: BTreeMap, + exe: PathBuf, + } + + impl Fixture { + fn new() -> Self { + let n = COUNTER.fetch_add(1, Ordering::Relaxed); + let dir = std::env::temp_dir().join(format!("pdfcraft-profile-root-{}-{n}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let root = std::fs::canonicalize(&dir).unwrap(); + let home = root.join("home"); + let appdata = root.join("roaming"); + let local = root.join("local"); + let install = root.join("install"); + for d in [&home, &appdata, &local, &install] { + std::fs::create_dir_all(d).unwrap(); + } + let mut env = BTreeMap::new(); + env.insert("HOME".into(), home.into_os_string()); + env.insert("APPDATA".into(), appdata.into_os_string()); + env.insert("LOCALAPPDATA".into(), local.into_os_string()); + let exe = install.join(if cfg!(windows) { "pdfcraft.exe" } else { "pdfcraft" }); + Self { root, env, exe } + } + + fn home(&self) -> PathBuf { + PathBuf::from(self.env.get("HOME").unwrap()) + } + + fn get(&self, key: &str) -> Option { + self.env.get(key).cloned() + } + + fn check(&self, platform: Platform, candidate: &Path) -> Result { + validate_for(platform, candidate, |key| self.get(key), Some(&self.exe), probe_writable) + } + } + + impl Drop for Fixture { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.root); + } + } + + #[test] + fn nightly_profile_reopens_after_saving_settings_and_session_state() { + let fixture = Fixture::new(); + for platform in [Platform::Mac, Platform::Linux, Platform::Windows] { + let private = fixture.root.join(format!("nightly-reopen-{platform:?}")); + assert_eq!(fixture.check(platform, &private).unwrap(), private); + for name in ["app.ron", "config.toml", "nightly-session.lock", "nightly-session.json"] { + std::fs::write(private.join(name), b"saved profile data").unwrap(); + } + for name in PROFILE_FOLDERS { + std::fs::create_dir(private.join(name)).unwrap(); + } + assert_eq!(fixture.check(platform, &private).unwrap(), private); + assert_eq!(std::fs::read(private.join("app.ron")).unwrap(), b"saved profile data"); + for name in PROFILE_FOLDERS { + let path = private.join(name); + std::fs::remove_dir(&path).unwrap(); + std::fs::write(&path, b"not a directory").unwrap(); + assert!(fixture.check(platform, &private).is_err(), "{name} must stay a directory"); + std::fs::remove_file(&path).unwrap(); + std::fs::create_dir(&path).unwrap(); + } + } + } + + #[test] + fn stable_roots_and_portable_layouts_are_refused() { + let fixture = Fixture::new(); + let stable_linux = fixture.home().join(".config/pdfcraft"); + assert!(fixture.check(Platform::Linux, &stable_linux).unwrap_err().contains("overlap")); + let stable_win = PathBuf::from(fixture.env.get("APPDATA").unwrap()).join("PdfCraft"); + assert!(fixture.check(Platform::Windows, &stable_win).unwrap_err().contains("overlap")); + assert!(fixture.check(Platform::Windows, &stable_win.with_file_name("pdfcraft")).is_err()); + let portable = fixture.root.join("portable/PdfCraftData"); + assert!(fixture.check(Platform::Linux, &portable).unwrap_err().contains("portable")); + let valid = fixture.root.join("local/ArtCraftLauncher/nightly/profiles/pdfcraft"); + assert_eq!(fixture.check(Platform::Windows, &valid).unwrap(), valid); + } + + #[test] + fn config_dir_and_flatpak_are_refused_unless_owned() { + let mut fixture = Fixture::new(); + let private = fixture.root.join("nightly-config"); + fixture.env.insert("PDFCRAFT_CONFIG_DIR".into(), fixture.root.join("custom").into_os_string()); + assert!(fixture.check(Platform::Linux, &private).unwrap_err().contains("PDFCRAFT_CONFIG_DIR")); + fixture.env.insert("PDFCRAFT_CONFIG_DIR".into(), private.clone().into_os_string()); + assert_eq!(fixture.check(Platform::Linux, &private).unwrap(), private); + fixture.env.remove("PDFCRAFT_CONFIG_DIR"); + fixture.env.insert("FLATPAK_ID".into(), "ai.storyteller.pdfcraft".into()); + assert!(fixture.check(Platform::Linux, &private).unwrap_err().contains("Flatpak")); + fixture.env.insert("FLATPAK_ID".into(), NIGHTLY_FLATPAK_ID.into()); + let fp = fixture.home().join(".var/app/ai.storyteller.pdfcraft.nightly/data/pdfcraft-nightly"); + assert_eq!(fixture.check(Platform::Linux, &fp).unwrap(), fp); + } + + #[cfg(unix)] + #[test] + fn a_dangling_entry_inside_the_profile_is_refused_before_writes() { + let fixture = Fixture::new(); + let outside = fixture.root.join("outside"); + std::fs::create_dir_all(&outside).unwrap(); + let private = fixture.root.join("nightly-dangling"); + std::fs::create_dir(&private).unwrap(); + std::os::unix::fs::symlink(outside.join("missing"), private.join("logs")).unwrap(); + assert!(fixture.check(Platform::Linux, &private).is_err()); + assert_eq!(std::fs::read_dir(&outside).unwrap().count(), 0); + } + + #[test] + fn mac_fences_bundle_and_library_and_validate_checks_writability() { + let mut fixture = Fixture::new(); + let bundle = fixture.root.join("Apps/PdfCraft Nightly.app"); + let exe = bundle.join("Contents/MacOS/PdfCraft"); + std::fs::create_dir_all(exe.parent().unwrap()).unwrap(); + fixture.exe = exe; + assert!(fixture.check(Platform::Mac, &bundle.join("Contents/Resources/profile")).unwrap_err().contains("overlap")); + let mac_stable = fixture.home().join("Library/Application Support/PdfCraft"); + assert!(fixture.check(Platform::Mac, &mac_stable).unwrap_err().contains("overlap")); + let valid = fixture.root.join("mac-private-profile"); + assert_eq!(fixture.check(Platform::Mac, &valid).unwrap(), valid); + let unwritable = fixture.root.join("unwritable-profile"); + let err = validate_for(Platform::Linux, &unwritable, |key| fixture.get(key), Some(&fixture.exe), |_| Err(std::io::Error::other("read-only"))) + .unwrap_err(); + assert!(err.contains("not writable")); + let via_validate = super::validate(&fixture.root.join("current-os-profile"), |key| fixture.get(key), Some(&fixture.exe), probe_writable); + assert!(via_validate.is_ok()); + } + + #[cfg(unix)] + #[test] + fn hardlinked_profile_file_is_refused() { + let fixture = Fixture::new(); + let private = fixture.root.join("nightly-hardlink"); + assert_eq!(fixture.check(Platform::Linux, &private).unwrap(), private); + let external = fixture.root.join("external.ron"); + std::fs::write(&external, b"shared").unwrap(); + std::fs::hard_link(&external, private.join("app.ron")).unwrap(); + assert!(fixture.check(Platform::Linux, &private).unwrap_err().contains("shared")); + } +} diff --git a/apps/pdfcraft/src/single_instance.rs b/apps/pdfcraft/src/single_instance.rs index a238c79bcb..af3a7e4d64 100644 --- a/apps/pdfcraft/src/single_instance.rs +++ b/apps/pdfcraft/src/single_instance.rs @@ -159,26 +159,29 @@ pub fn absolute(paths: &[String]) -> Vec { /// Decide what this launch does. `files` are absolute ([`absolute`]); `may_hand_off` is false /// when the launch asked for anything besides opening (or, with `combine`, combining) files, so /// it gets its own window. -pub fn claim(files: &[String], may_hand_off: bool, combine: bool) -> Claim { +pub fn claim(files: &[String], may_hand_off: bool, combine: bool, profile_root: Option<&std::path::Path>) -> Claim { #[cfg(any(windows, all(unix, not(target_os = "macos"))))] { - match socket_path() { + match socket_path(profile_root) { Some(path) => claim_at(&path, files, may_hand_off, combine), None => Claim::Alone, } } #[cfg(not(any(windows, all(unix, not(target_os = "macos")))))] { - let _ = (files, may_hand_off, combine); + let _ = (files, may_hand_off, combine, profile_root); Claim::Alone } } -/// The socket in `%LOCALAPPDATA%\PdfCraft` (beside the crash-recovery folder); none when -/// `%LOCALAPPDATA%` is unset. +/// The socket in `%LOCALAPPDATA%\PdfCraft` (beside the crash-recovery folder), or inside the +/// nightly profile's `single-instance` folder when running isolated; none when `%LOCALAPPDATA%` is unset. #[cfg(windows)] -fn socket_path() -> Option { +fn socket_path(profile_root: Option<&std::path::Path>) -> Option { let name = socket_name(session_id(), std::env::var("SESSIONNAME").ok().as_deref()); + if let Some(root) = profile_root { + return Some(root.join("single-instance").join(name)); + } // %LOCALAPPDATA% is private to the user's sign-in, so other accounts can't receive this // user's file paths or send it files to open. A portable copy uses it too (#889), under its // own name so it never hands files to an installed copy (which keeps its settings elsewhere). @@ -187,12 +190,15 @@ fn socket_path() -> Option { std::env::var_os("LOCALAPPDATA").filter(|v| !v.is_empty()).map(|d| std::path::PathBuf::from(d).join("PdfCraft").join(name)) } -/// The socket in `$XDG_RUNTIME_DIR/pdfcraft`; none when `$XDG_RUNTIME_DIR` is unset. Never `/tmp` -/// instead: other accounts can create files there, and so could listen in this user's place. +/// The socket in `$XDG_RUNTIME_DIR/pdfcraft`, or inside the nightly profile's `single-instance` +/// folder when running isolated; none when `$XDG_RUNTIME_DIR` is unset. #[cfg(all(unix, not(target_os = "macos")))] -fn socket_path() -> Option { +fn socket_path(profile_root: Option<&std::path::Path>) -> Option { let var = |k: &str| std::env::var(k).ok().filter(|v| !v.is_empty()); let name = display_socket_name(var("WAYLAND_DISPLAY").or_else(|| var("DISPLAY")).as_deref()); + if let Some(root) = profile_root { + return Some(root.join("single-instance").join(name)); + } // The XDG base directory spec makes it the user's own (mode 0700), so the folder inside it is // out of other accounts' reach whatever the umask. var("XDG_RUNTIME_DIR").map(|d| std::path::PathBuf::from(d).join("pdfcraft").join(name)) @@ -540,4 +546,12 @@ mod tests { assert!(std::fs::symlink_metadata(&path).is_ok(), "the socket file stays behind"); assert!(matches!(claim_at(&path, &["C:\\a.pdf".into()], true, false), Claim::Primary(_))); } + + #[cfg(any(windows, all(unix, not(target_os = "macos"))))] + #[test] + fn nightly_profile_root_isolates_the_single_instance_socket() { + let root = std::env::temp_dir().join(format!("pdfcraft-si-nightly-{}", std::process::id())); + let path = socket_path(Some(&root)).unwrap(); + assert_eq!(path.parent(), Some(root.join("single-instance").as_path())); + } } diff --git a/assets/app-icon/nightly-provenance.json b/assets/app-icon/nightly-provenance.json new file mode 100644 index 0000000000..3ac24defd4 --- /dev/null +++ b/assets/app-icon/nightly-provenance.json @@ -0,0 +1,24 @@ +{ + "schema": "craft-nightly-icon-provenance/v1", + "app": "pdfcraft", + "channel": "nightly-v1", + "source": { + "master": "assets/app-icon/pdfcraft-1024.png", + "note": "The stable 1024 master, padded as its designer made it; the nightly files are derived from it, never upscaled from a smaller icon." + }, + "transform": { + "summary": "The app mark (white/light strokes and their antialiasing) is copied unchanged; only the background square is deepened.", + "background": { + "from": "#b70228", + "to": "#710118", + "rule": "A pixel whose channel distance from the stable background is at most 180 is scaled by 0.62; fully transparent pixels and every other colour are left as they were." + } + }, + "outputs": { + "pdfcraft-nightly.png": "256 px PNG of the icon the Linux tar carries as pdfcraft-nightly.png", + "pdfcraft-nightly-1024.png": "the padded 1024 master the icns is generated from", + "pdfcraft-nightly.ico": "16, 24, 32, 48, 64, 128 and 256 px PNG entries, the Windows executable and window icon", + "pdfcraft-nightly.icns": "icp4 icp5 icp6 ic07 ic08 ic09 ic10 PNG entries for the macOS bundle (CFBundleIconFile pdfcraft-nightly)" + }, + "not_done_here": "No badge, crescent or N was added, and the stable pdfcraft.png/.ico/.icns files are untouched." +} diff --git a/assets/app-icon/pdfcraft-nightly-1024.png b/assets/app-icon/pdfcraft-nightly-1024.png new file mode 100644 index 0000000000..cad0c50217 Binary files /dev/null and b/assets/app-icon/pdfcraft-nightly-1024.png differ diff --git a/assets/app-icon/pdfcraft-nightly.icns b/assets/app-icon/pdfcraft-nightly.icns new file mode 100644 index 0000000000..6f83b1074c Binary files /dev/null and b/assets/app-icon/pdfcraft-nightly.icns differ diff --git a/assets/app-icon/pdfcraft-nightly.ico b/assets/app-icon/pdfcraft-nightly.ico new file mode 100644 index 0000000000..0055d411d8 Binary files /dev/null and b/assets/app-icon/pdfcraft-nightly.ico differ diff --git a/assets/app-icon/pdfcraft-nightly.png b/assets/app-icon/pdfcraft-nightly.png new file mode 100644 index 0000000000..4fcac4c02d Binary files /dev/null and b/assets/app-icon/pdfcraft-nightly.png differ diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 5ac28b3757..2a08326250 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -369,6 +369,7 @@ impl PdfCraftApp { session_keeper: Default::default(), reload_changed_files: true, update_check_at_start: true, + at_exit: None, show_secured_notice: true, text_links: true, always_default_view: false, @@ -711,7 +712,12 @@ impl eframe::App for PdfCraftApp { /// Starts an update that waits for the exit. On macOS the process ends before the app is dropped. fn on_exit(&mut self, _gl: Option<&eframe::glow::Context>) { #[cfg(not(target_arch = "wasm32"))] - self.updater.start_pending_update(); + if !crate::settings::is_nightly() { + self.updater.start_pending_update(); + } + if let Some(at_exit) = self.at_exit.take() { + at_exit(); + } } /// Each frame's work before drawing: the update check, opens, control-channel requests, the diff --git a/crates/ui-egui/src/app/settings.rs b/crates/ui-egui/src/app/settings.rs index e36656bd74..57a022add8 100644 --- a/crates/ui-egui/src/app/settings.rs +++ b/crates/ui-egui/src/app/settings.rs @@ -247,6 +247,33 @@ impl Settings for PdfCraftSettings { /// The settings store the app reads its preferences from and writes them to. pub type Store = craft::settings::SettingsStore; +#[cfg(not(target_arch = "wasm32"))] +static NIGHTLY_PROFILE_ROOT: std::sync::OnceLock = std::sync::OnceLock::new(); + +/// Pin settings, recovery, dictionary and digital IDs to the validated Nightly profile root. +/// Must be called once at startup before [`resolution`] or [`open`]. +#[cfg(not(target_arch = "wasm32"))] +pub fn install_nightly_profile_root(root: PathBuf) -> Result<(), String> { + NIGHTLY_PROFILE_ROOT.set(root).map_err(|_| "the nightly profile root was already installed".into()) +} + +/// The validated Nightly profile root, when running in isolated `nightly-v1` mode. +pub fn nightly_profile_root() -> Option<&'static std::path::Path> { + #[cfg(not(target_arch = "wasm32"))] + { + NIGHTLY_PROFILE_ROOT.get().map(PathBuf::as_path) + } + #[cfg(target_arch = "wasm32")] + { + None + } +} + +/// Whether this process runs in the isolated Nightly channel. +pub fn is_nightly() -> bool { + nightly_profile_root().is_some() +} + /// How the data folder was chosen (portable marker, environment, platform folder). Resolved once: /// it is a fact of how the app was installed, and the settings store opens at the same folder. /// Native only: the web has no folder rules. @@ -256,15 +283,22 @@ pub fn resolution() -> &'static craft::settings::Resolved { static RESOLVED: std::sync::OnceLock = std::sync::OnceLock::new(); RESOLVED.get_or_init(|| { let portable = Portable { markers: PdfCraftSettings::PORTABLE_MARKERS, dir: PdfCraftSettings::PORTABLE_DIR }; - paths::resolve_named(PdfCraftSettings::APP_ID, PdfCraftSettings::FOLDER_NAME, &portable, &craft::settings::Location::Auto, &Probe::default()) + let location = match nightly_profile_root() { + Some(root) => craft::settings::Location::Dir(root.to_path_buf()), + None => craft::settings::Location::Auto, + }; + paths::resolve_named(PdfCraftSettings::APP_ID, PdfCraftSettings::FOLDER_NAME, &portable, &location, &Probe::default()) }) } /// The data folder beside the executable, when a portable marker sits there and the folder can be -/// written; `None` otherwise, and always on the web. +/// written; `None` otherwise, and always on the web or in isolated Nightly mode. pub fn portable_dir() -> Option { #[cfg(not(target_arch = "wasm32"))] { + if is_nightly() { + return None; + } let resolved = resolution(); if resolved.rule == craft::settings::Rule::Portable { resolved.dir.clone() } else { None } } @@ -275,7 +309,8 @@ pub fn portable_dir() -> Option { } /// Opens the settings store at the folder [`resolution`] chose (in memory when it chose none), -/// importing the last release's `app.ron` on first run; on the web, over the browser's storage. +/// importing the last release's `app.ron` on first run (never in isolated Nightly mode); on the web, +/// over the browser's storage. pub fn open() -> Store { #[cfg(not(target_arch = "wasm32"))] let options = { @@ -283,7 +318,7 @@ pub fn open() -> Store { Some(dir) => craft::settings::Location::Dir(dir.clone()), None => craft::settings::Location::Memory, }; - craft::settings::OpenOptions::new(location).legacy(legacy_files()) + if is_nightly() { craft::settings::OpenOptions::new(location) } else { craft::settings::OpenOptions::new(location).legacy(legacy_files()) } }; #[cfg(target_arch = "wasm32")] let options = craft::settings::OpenOptions::new(craft::settings::Location::Dir(PathBuf::from(PdfCraftSettings::APP_ID))) diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 9405eea394..8e88867b5e 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -438,6 +438,8 @@ pub struct PdfCraftApp { /// Preferences: ask for a newer release when the desktop app starts (#5737). Off, the app /// asks only from Help ▸ Check for updates. pub update_check_at_start: bool, + /// Optional host cleanup invoked once in `eframe::App::on_exit` (e.g. Nightly session record). + pub at_exit: Option>, /// Preferences: tell the user, above the pages, that a document is secured (its security /// settings restrict changes). Off only hides that notice (#4035); kept in the settings. pub show_secured_notice: bool, diff --git a/crates/ui-egui/src/persist/recovery.rs b/crates/ui-egui/src/persist/recovery.rs index 56b22171c3..cd4c95b07e 100644 --- a/crates/ui-egui/src/persist/recovery.rs +++ b/crates/ui-egui/src/persist/recovery.rs @@ -30,6 +30,9 @@ pub const AUTOSAVE_SECS: f64 = 60.0; /// `%LOCALAPPDATA%\PdfCraft\Recovery` on Windows, `$XDG_DATA_HOME/pdfcraft/recovery` elsewhere). /// What a crash left there is adopted into the current folder. pub fn default_dir() -> Option { + if let Some(root) = crate::settings::nightly_profile_root() { + return Some(root.join("autosave")); + } if let Some(dir) = crate::settings::portable_dir() { return Some(dir.join("Recovery")); } @@ -47,6 +50,9 @@ pub fn default_dir() -> Option { /// into it. The app's constructor takes it through its services. #[cfg(not(target_arch = "wasm32"))] pub(crate) fn prepare_platform_recovery_dir() -> Option { + if let Some(root) = crate::settings::nightly_profile_root() { + return Some(root.join("autosave")); + } let portable = crate::settings::portable_dir(); let mode = if portable.is_some() { SettingsMode::SelfContained } else { SettingsMode::Platform }; let dir = recovery_dir("PdfCraft", "pdfcraft", portable.as_deref(), mode, |k| std::env::var_os(k))?; @@ -61,6 +67,9 @@ pub(crate) fn prepare_platform_recovery_dir() -> Option { /// `…/PdfCraft/Dictionary` in the platform's per-user data folder. `None` where files are not /// kept (the web build). pub fn default_dictionary_dir() -> Option { + if let Some(root) = crate::settings::nightly_profile_root() { + return Some(root.join("dictionary")); + } if let Some(dir) = crate::settings::portable_dir() { return Some(dir.join("Dictionary")); } diff --git a/crates/ui-egui/src/platform/macos_association.rs b/crates/ui-egui/src/platform/macos_association.rs index b3798568e2..902134e93e 100644 --- a/crates/ui-egui/src/platform/macos_association.rs +++ b/crates/ui-egui/src/platform/macos_association.rs @@ -104,6 +104,10 @@ pub(crate) fn repair(path: &Path) { use std::collections::HashSet; use std::sync::{Arc, Mutex, OnceLock, PoisonError, mpsc}; + if crate::settings::is_nightly() { + return; + } + if !objc2::available!(macos = 12.0) || objc2::MainThreadMarker::new().is_none() || !path.extension().is_some_and(|e| e.eq_ignore_ascii_case("pdf")) diff --git a/packaging/linux/flatpak-bundle.sh b/packaging/linux/flatpak-bundle.sh index 0534b3194e..9f4de56cb7 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.pdfcraft +FLATPAK_ID="$APP_ID" +# The remote indexes both app IDs on the stable ref branch; IDs isolate installations. +FLATPAK_BRANCH=stable +if [[ "${PDFCRAFT_BUILD_CHANNEL:-}" == nightly-v1 || "$VERSION" == *-nightly* ]]; then + FLATPAK_ID="$APP_ID.nightly" +fi FLATHUB=https://dl.flathub.org/repo/flathub.flatpakrepo TEST=1 @@ -52,33 +58,73 @@ rm -rf "$WORK" mkdir -p "$WORK/stage" tar -xzf "$TARBALL" -C "$WORK/stage" --strip-components=1 [[ -x "$WORK/stage/bin/pdfcraft" ]] || { echo "error: $TARBALL has no bin/pdfcraft" >&2; exit 1; } -cp "$HERE/flatpak/$APP_ID.bundle.yml" "$WORK/$APP_ID.yml" +if [[ "$FLATPAK_ID" != "$APP_ID" ]]; then + mv "$WORK/stage/bin/pdfcraft" "$WORK/stage/bin/pdfcraft-bin" + cat >"$WORK/stage/bin/pdfcraft" <<'WRAPPER' +#!/bin/sh +# The bundled nightly starts the GUI with this channel's own launch profile. The sandbox's own +# data folder belongs to the nightly app id, so the profile stays inside it. +set -eu +case "${1-}" in + # The Launcher already named the profile (its version query does too); never pass it twice. A + # plain version query answers without touching any profile. + --launch-profile | --version | -V) exec /app/libexec/pdfcraft "$@" ;; +esac +profile_base="${XDG_DATA_HOME:-${HOME:?HOME is required}/.var/app/ai.storyteller.pdfcraft.nightly/data}" +exec /app/libexec/pdfcraft \ + --launch-profile nightly-v1 --profile-root "$profile_base/pdfcraft-nightly" -- "$@" +WRAPPER + chmod 755 "$WORK/stage/bin/pdfcraft" + sed -e "s|^Icon=$APP_ID$|Icon=$FLATPAK_ID|" \ + -e "s|^Name=PdfCraft$|Name=PdfCraft Nightly|" \ + -e 's|^StartupWMClass=.*|StartupWMClass=ai.storyteller.pdfcraft.nightly|' \ + -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|PdfCraft|PdfCraft 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" + rm -rf "$WORK/stage/share/icons/hicolor" + NIGHTLY_ICON="$ROOT/assets/app-icon/pdfcraft-nightly.png" + [[ -f "$NIGHTLY_ICON" ]] || NIGHTLY_ICON="$ROOT/assets/app-icon/hicolor/256x256/apps/$APP_ID.png" + install -Dm644 "$NIGHTLY_ICON" \ + "$WORK/stage/share/icons/hicolor/256x256/apps/$FLATPAK_ID.png" + sed -e "s|ai\.storyteller\.pdfcraft|$FLATPAK_ID|g" \ + -e 's|- install -Dm755 bin/pdfcraft /app/bin/pdfcraft|- install -Dm755 bin/pdfcraft-bin /app/libexec/pdfcraft\n - install -Dm755 bin/pdfcraft /app/bin/pdfcraft|' \ + "$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=pdfcraft-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 /app/share/pdfcraft/models' + flatpak info --user "$FLATPAK_ID" + flatpak run --command=pdfcraft-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 /app/share/pdfcraft/models' # Informational: printing runs lp/lpstat, which the freedesktop runtime doesn't ship (see the # manifest's finish-args). Says so if a runtime update ever adds them. - flatpak run --command=sh "$APP_ID" -c 'command -v lp lpstat' || echo "note: no lp/lpstat in the runtime, so printing is unavailable in the Flatpak" + flatpak run --command=sh "$FLATPAK_ID" -c 'command -v lp lpstat' || echo "note: no lp/lpstat in the runtime, so printing is unavailable in the Flatpak" fi echo "==> done" ls -lh "$OUT" diff --git a/packaging/linux/nfpm.yaml b/packaging/linux/nfpm.yaml index 646eb61a36..7a93fbd554 100644 --- a/packaging/linux/nfpm.yaml +++ b/packaging/linux/nfpm.yaml @@ -3,7 +3,7 @@ # exports VERSION, RELEASE and NFPM_ARCH. # # nfpm package -f packaging/linux/nfpm.yaml -p deb -t dist/release/ -name: pdfcraft +name: ${NFPM_NAME} arch: ${NFPM_ARCH} platform: linux version: ${VERSION} @@ -67,12 +67,15 @@ overrides: - xdg-desktop-portal contents: - - src: ${STAGE}/usr/bin/pdfcraft - dst: /usr/bin/pdfcraft + - src: ${STAGE}/usr/bin/${NFPM_BIN} + dst: /usr/bin/${NFPM_BIN} file_info: { mode: 0755 } - - src: ${STAGE}/usr/bin/pdfcraft-cli - dst: /usr/bin/pdfcraft-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 0000000000..1bab48ab74 --- /dev/null +++ b/packaging/linux/nightly-arch-launch.sh @@ -0,0 +1,13 @@ +#!/bin/sh +# The Arch Nightly launcher: the GUI starts with this channel's own launch profile, so the AUR +# package never reads or writes stable's settings, window state or recovery files. +set -eu + +real_bin="$(dirname "$0")/.pdfcraft-nightly/pdfcraft" +case "${1-}" in + # The Launcher already named the profile (its version query does too); never pass it twice. A + # plain version query answers without touching any profile. + --launch-profile | --profile-root | --version | -V) exec "$real_bin" "$@" ;; +esac +profile_base="${XDG_DATA_HOME:-${HOME:?HOME is required}/.local/share}" +exec "$real_bin" --launch-profile nightly-v1 --profile-root "$profile_base/pdfcraft-nightly" -- "$@" diff --git a/packaging/linux/nightly-arch-tar-test.sh b/packaging/linux/nightly-arch-tar-test.sh new file mode 100755 index 0000000000..de3b7fbb33 --- /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 PdfCraft. +set -euo pipefail + +HERE="$(cd "$(dirname "$0")" && pwd)" +work="$(mktemp -d)" +trap 'rm -rf "$work"' EXIT +stage="$work/source" +dst="$work/dist" +base=pdfcraft-0.0.1-nightly.1-linux-x86_64 +mkdir -p "$stage/bin" "$dst" "$work/extract" + +# A local argv/env recorder stands in for the compiled binaries. It never opens a UI. +cat >"$stage/bin/pdfcraft" <<'RECORDER' +#!/bin/sh +printf 'config=<%s>\n' "${PDFCRAFT_CONFIG_DIR:-}" +for arg in "$@"; do + printf '<%s>\n' "$arg" +done +RECORDER +chmod 755 "$stage/bin/pdfcraft" +cp "$stage/bin/pdfcraft" "$stage/bin/pdfcraft-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/pdfcraft" "$bin/pdfcraft-nightly" +mv "$bin/pdfcraft-cli" "$bin/pdfcraft-nightly-cli" + +test ! -e "$stage/bin/.pdfcraft-nightly" +cmp "$stage/bin/pdfcraft" "$bin/.pdfcraft-nightly/pdfcraft" +cmp "$stage/bin/pdfcraft-cli" "$bin/pdfcraft-nightly-cli" +export HOME="$work/home with space" +unset XDG_DATA_HOME PDFCRAFT_CONFIG_DIR +expect() { + expected="$1" + shift + actual=$(PATH="$bin:$PATH" pdfcraft-nightly "$@") + if [[ "$actual" != "$expected" ]]; then + printf 'expected:\n%s\nactual:\n%s\n' "$expected" "$actual" >&2 + exit 1 + fi +} +# The launcher names the profile the flavor's way and keeps every argument after the delimiter. +launch() { + local profile="$1" + shift + printf 'config=<>\n<--launch-profile>\n\n<--profile-root>\n<%s>\n<-->\n' "$profile" + for file in "$@"; do printf '<%s>\n' "$file"; done +} +expect "$(launch "$HOME/.local/share/pdfcraft-nightly" 'sample.dxf')" sample.dxf +export XDG_DATA_HOME="$work/xdg with space" +expect "$(launch "$XDG_DATA_HOME/pdfcraft-nightly" 'drawing with spaces.dxf' '--other-name.dxf')" \ + 'drawing with spaces.dxf' '--other-name.dxf' +# A version query answers with the plain argument, so it needs no profile at all. +expect "$(printf 'config=<>\n<--version>\n')" --version +expect "$(printf 'config=<>\n<-V>\n')" -V +# The Launcher's own form is passed through once, never doubled. +expect "$(printf 'config=<>\n<--launch-profile>\n\n<--profile-root>\n<%s>\n<--version>\n' "$work/launcher root")" \ + --launch-profile nightly-v1 --profile-root "$work/launcher root" --version +# A PDFCRAFT_CONFIG_DIR from an older wrapper is neither honoured nor rewritten: the profile is the +# launcher's, and the flavor refuses a variable outside it. +PDFCRAFT_CONFIG_DIR="$work/explicit with space" \ + expect "$(launch "$XDG_DATA_HOME/pdfcraft-nightly" 'sample.dxf' | sed '1s|.*|config=<'"$work"'/explicit with space>|')" \ + sample.dxf + +echo "PASS: Arch Nightly handoff starts the flavor's profile and preserves launch arguments" diff --git a/packaging/linux/nightly-arch-tar.sh b/packaging/linux/nightly-arch-tar.sh new file mode 100755 index 0000000000..e9a2f5d53e --- /dev/null +++ b/packaging/linux/nightly-arch-tar.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Stage the PdfCraft 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/.pdfcraft-nightly" +mv "$stage/bin/pdfcraft" "$stage/bin/.pdfcraft-nightly/pdfcraft" +cp "$here/nightly-arch-launch.sh" "$stage/bin/pdfcraft" +chmod 755 "$stage/bin/pdfcraft" +tar -C "$work" -czf "$destination/$basename.tar.gz" "$basename" +echo "wrote $destination/$basename.tar.gz" diff --git a/packaging/linux/nightly-launch.sh b/packaging/linux/nightly-launch.sh new file mode 100755 index 0000000000..19807131f7 --- /dev/null +++ b/packaging/linux/nightly-launch.sh @@ -0,0 +1,16 @@ +#!/bin/sh +# Nightly launcher generated by craft-common-actions scripts/nightly-launcher.sh.in. Do not edit: +# the shared nightly producer accepts this file only byte for byte as rendered for the app. +set -eu +dir=$(CDPATH='' cd -- "$(dirname -- "$0")" && pwd -P) +readonly dir +target="$dir/pdfcraft-bin" +readonly target +profile_root="${XDG_DATA_HOME:-$HOME/.local/share}/ai.storyteller.pdfcraft.nightly" +readonly profile_root +case "${1-}" in + # The ArtCraft Launcher passes its own profile and per-install root; the app validates the pair. + --launch-profile) exec "$target" "$@" ;; + --version | -V) exec "$target" --launch-profile nightly-v1 --profile-root "$profile_root" --version ;; +esac +exec "$target" --launch-profile nightly-v1 --profile-root "$profile_root" -- "$@" diff --git a/packaging/linux/nightly.sh b/packaging/linux/nightly.sh new file mode 100755 index 0000000000..29a364c61a --- /dev/null +++ b/packaging/linux/nightly.sh @@ -0,0 +1,31 @@ +#!/usr/bin/env bash +# App-owned GUI-only nightly tar: no FUSE/AppImage, CLI, association or install hooks. +set -euo pipefail +ARCH= +while [[ $# -gt 0 ]]; do + case "$1" in + --arch) [[ $# -ge 2 ]] || { echo 'missing --arch value' >&2; exit 2; }; ARCH="$2"; shift 2 ;; + -h|--help) echo 'Usage: nightly.sh --arch x86_64'; exit 0 ;; + *) echo "unsupported nightly argument: $1" >&2; exit 2 ;; + esac +done +[[ "$ARCH" == x86_64 && "$(uname -s)" == Linux ]] || { echo 'only native Linux x86_64 nightly packaging is supported' >&2; exit 2; } +# shellcheck source=../nightly-common.sh +. "$(dirname "${BASH_SOURCE[0]}")/../nightly-common.sh" +nightly_init linux "$ARCH" x86_64-unknown-linux-gnu +OUTPUT="$DIST/pdfcraft-$VERSION-linux-x86_64-nightly.tar.gz" +[[ ! -e "$OUTPUT" && ! -L "$OUTPUT" ]] || nightly_die 'refusing to replace an existing nightly archive' +nightly_build_gui +STAGE="$NIGHTLY_WORK/stage" +mkdir -p "$STAGE" +# The kit's flat tar layout: `pdfcraft` is the launcher people run and `pdfcraft-bin` the GUI it +# starts with this channel's own profile, so an unpacked copy never writes stable's settings. +cp "$NIGHTLY_GUI" "$STAGE/pdfcraft-bin" +chmod 755 "$STAGE/pdfcraft-bin" +cp "$ROOT/packaging/linux/nightly-launch.sh" "$STAGE/pdfcraft" +chmod 755 "$STAGE/pdfcraft" +cp "$ROOT/assets/app-icon/pdfcraft-nightly.png" "$STAGE/pdfcraft-nightly.png" +nightly_copy_notices "$STAGE" +# The private mktemp cwd is the helper authority root, not a CLI path parent. +(cd "$NIGHTLY_WORK" && python3 "$ROOT/packaging/nightly-archive.py" linux stage archive.tar.gz) +nightly_publish_archive "$NIGHTLY_WORK/archive.tar.gz" "$OUTPUT" diff --git a/packaging/linux/package.sh b/packaging/linux/package.sh index fd486c392b..a524fdfe4c 100755 --- a/packaging/linux/package.sh +++ b/packaging/linux/package.sh @@ -30,10 +30,12 @@ APP_ID=ai.storyteller.pdfcraft SKIP_BUILD=0 FORMATS="appimage deb rpm tar cli" +ARCH_TAR_DIR="" while [[ $# -gt 0 ]]; do case "$1" in --skip-build) SKIP_BUILD=1; shift ;; --formats) FORMATS="$2"; shift 2 ;; + --arch-tar-dir) ARCH_TAR_DIR="$2"; shift 2 ;; -h | --help) sed -n '2,24p' "$0"; exit 0 ;; *) echo "unknown argument: $1" >&2; exit 2 ;; esac @@ -47,10 +49,20 @@ case "$ARCH" in *) echo "unsupported architecture $ARCH" >&2; exit 2 ;; esac export PDFCRAFT_MAINTAINER="${PDFCRAFT_MAINTAINER:-PdfCraft maintainers }" +IS_NIGHTLY=0 +if [[ "${PDFCRAFT_BUILD_CHANNEL:-}" == nightly-v1 || "$VERSION" == *-nightly* ]]; then + IS_NIGHTLY=1 + export PDFCRAFT_BUILD_CHANNEL=nightly-v1 +fi LABEL_SUFFIX="${PDFCRAFT_BUILD_LABEL:+-$PDFCRAFT_BUILD_LABEL}" BASENAME="pdfcraft-$VERSION$LABEL_SUFFIX-linux-$ARCH" -echo "==> PdfCraft $VERSION$LABEL_SUFFIX 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 "==> PdfCraft $VERSION$LABEL_SUFFIX for Linux $ARCH ($FORMATS, channel=${PDFCRAFT_BUILD_CHANNEL:-stable})" if [[ "$SKIP_BUILD" = 0 ]]; then if [[ -n "${CROSS_TARGET:-}" ]]; then @@ -69,6 +81,11 @@ install -Dm755 "$BIN/pdfcraft" "$STAGE/usr/bin/pdfcraft" install -Dm755 "$BIN/pdfcraft-cli" "$STAGE/usr/bin/pdfcraft-cli" "${CROSS_COMPILE:-}strip" "$STAGE/usr/bin/pdfcraft" "$STAGE/usr/bin/pdfcraft-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.pdfcraft.nightly|' \ + "$STAGE/usr/share/applications/$APP_ID.desktop" >"$STAGE/usr/share/applications/$APP_ID.desktop.tmp" + mv "$STAGE/usr/share/applications/$APP_ID.desktop.tmp" "$STAGE/usr/share/applications/$APP_ID.desktop" +fi install -Dm644 "$HERE/$APP_ID.mime.xml" "$STAGE/usr/share/mime/packages/$APP_ID.xml" mkdir -p "$STAGE/usr/share/metainfo" sed -e "s/@VERSION@/$VERSION/g" -e "s/@DATE@/$PDFCRAFT_BUILD_DATE/g" \ @@ -119,14 +136,97 @@ if has cli; then echo "wrote $DIST/$CLI_NAME.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/docs/install/)" >&2; exit 1; } export VERSION export RELEASE="1${PDFCRAFT_BUILD_LABEL:+.$PDFCRAFT_BUILD_LABEL}" export NFPM_ARCH="$DEB_ARCH" + NFPM_STAGE="$STAGE" + export NFPM_NAME="pdfcraft" + export NFPM_BIN="pdfcraft" + export NFPM_CLI="pdfcraft-cli" + if [[ "$IS_NIGHTLY" = 1 ]]; then + NIGHTLY_DESK_ID="$APP_ID.nightly" + export NFPM_NAME="pdfcraft-nightly" + export NFPM_BIN="pdfcraft-nightly" + export NFPM_CLI="pdfcraft-nightly-cli" + NFPM_STAGE="$WORK/nfpm-root" + rm -rf "$NFPM_STAGE" + cp -R "$STAGE" "$NFPM_STAGE" + install -Dm755 "$NFPM_STAGE/usr/bin/pdfcraft" "$NFPM_STAGE/usr/lib/pdfcraft-nightly/pdfcraft" + cat >"$NFPM_STAGE/usr/bin/$NFPM_BIN" <<'WRAPPER' +#!/bin/sh +# Start the Nightly GUI the flavor's way: this channel's own launch profile, so an installed +# nightly never reads or writes stable's settings, window state or recovery files. +set -eu +case "${1-}" in + # The Launcher already named the profile (its version query does too); never pass it twice. A + # plain version query answers without touching any profile. + --launch-profile | --version | -V) exec /usr/lib/pdfcraft-nightly/pdfcraft "$@" ;; +esac +profile_base="${XDG_DATA_HOME:-${HOME:?HOME is required}/.local/share}" +exec /usr/lib/pdfcraft-nightly/pdfcraft \ + --launch-profile nightly-v1 --profile-root "$profile_base/pdfcraft-nightly" -- "$@" +WRAPPER + chmod 755 "$NFPM_STAGE/usr/bin/$NFPM_BIN" + rm -f "$NFPM_STAGE/usr/bin/pdfcraft" + install -m755 "$NFPM_STAGE/usr/bin/pdfcraft-cli" "$NFPM_STAGE/usr/lib/pdfcraft-nightly/pdfcraft-cli" + cat >"$NFPM_STAGE/usr/bin/$NFPM_CLI" <<'CLI_WRAPPER' +#!/bin/sh +# The Nightly CLI keeps its settings in the same channel folder as the GUI. +set -eu +if [ "${PDFCRAFT_CONFIG_DIR+x}" != x ]; then + profile_base="${XDG_DATA_HOME:-${HOME:?HOME is required}/.local/share}" + PDFCRAFT_CONFIG_DIR="$profile_base/pdfcraft-nightly" + export PDFCRAFT_CONFIG_DIR +fi +exec /usr/lib/pdfcraft-nightly/pdfcraft-cli "$@" +CLI_WRAPPER + chmod 755 "$NFPM_STAGE/usr/bin/$NFPM_CLI" + rm -f "$NFPM_STAGE/usr/bin/pdfcraft-cli" + mv "$NFPM_STAGE/usr/share/doc/pdfcraft" "$NFPM_STAGE/usr/share/doc/$NFPM_NAME" + if [[ -d "$NFPM_STAGE/usr/share/pdfcraft" ]]; then + mv "$NFPM_STAGE/usr/share/pdfcraft" "$NFPM_STAGE/usr/share/$NFPM_NAME" + fi + sed -e "s#^Exec=pdfcraft\([[:space:]]\|$\)#Exec=$NFPM_BIN\1#" \ + -e "s|^TryExec=pdfcraft$|TryExec=$NFPM_BIN|" \ + -e "s|^Icon=$APP_ID$|Icon=$NIGHTLY_DESK_ID|" \ + -e "s|^Name=PdfCraft$|Name=PdfCraft 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|PdfCraft|PdfCraft Nightly|g" \ + -e "s|$APP_ID.desktop|$NIGHTLY_DESK_ID.desktop|g" \ + -e "s|$APP_ID|$NIGHTLY_DESK_ID|g" \ + -e "s|pdfcraft|$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" + rm -rf "$NFPM_STAGE/usr/share/icons/hicolor" + NIGHTLY_ICON="$ROOT/assets/app-icon/pdfcraft-nightly.png" + [[ -f "$NIGHTLY_ICON" ]] || NIGHTLY_ICON="$ROOT/assets/app-icon/hicolor/256x256/apps/$APP_ID.png" + install -Dm644 "$NIGHTLY_ICON" \ + "$NFPM_STAGE/usr/share/icons/hicolor/256x256/apps/$NIGHTLY_DESK_ID.png" + fi # nfpm expands env vars in fields like `version` and `arch`, but not in `contents[].src`. - sed "s|\${STAGE}|$STAGE|g" "$HERE/nfpm.yaml" >"$WORK/nfpm.yaml" + 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 @@ -153,10 +253,49 @@ if has appimage; then fi APPDIR="$WORK/PdfCraft.AppDir" cp -R "$STAGE" "$APPDIR" - ln -s usr/bin/pdfcraft "$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" + cat >"$APPDIR/AppRun" <<'APPRUN' +#!/bin/sh +# The nightly AppImage runs this launcher rather than a symlink to the binary, so an extracted or +# integrated AppImage starts with this channel's own launch profile too. +set -eu +APPDIR="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)" +case "${1-}" in + # The Launcher already named the profile (its version query does too); never pass it twice. A + # plain version query answers without touching any profile. + --launch-profile | --version | -V) exec "$APPDIR/usr/bin/pdfcraft" "$@" ;; +esac +profile_base="${XDG_DATA_HOME:-${HOME:?HOME is required}/.local/share}" +exec "$APPDIR/usr/bin/pdfcraft" \ + --launch-profile nightly-v1 --profile-root "$profile_base/pdfcraft-nightly" -- "$@" +APPRUN + chmod 755 "$APPDIR/AppRun" + sed -e "s|^Icon=$APP_ID$|Icon=$APPIMAGE_ID|" \ + -e "s|^Name=PdfCraft$|Name=PdfCraft 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" + sed -e "s|$APP_ID|$APPIMAGE_ID|g" \ + -e "s|PdfCraft|PdfCraft Nightly|g" \ + -e "s|$APP_ID.desktop|$APPIMAGE_ID.desktop|g" \ + -e "s|$APP_ID|$APPIMAGE_ID|g" \ + "$APPDIR/usr/share/metainfo/$APP_ID.metainfo.xml" >"$APPDIR/usr/share/metainfo/$APPIMAGE_ID.metainfo.xml" + rm -f "$APPDIR/usr/share/metainfo/$APP_ID.metainfo.xml" + rm -rf "$APPDIR/usr/share/icons/hicolor" + NIGHTLY_ICON="$ROOT/assets/app-icon/pdfcraft-nightly.png" + [[ -f "$NIGHTLY_ICON" ]] || NIGHTLY_ICON="$ROOT/assets/app-icon/hicolor/256x256/apps/$APP_ID.png" + install -Dm644 "$NIGHTLY_ICON" \ + "$APPDIR/usr/share/icons/hicolor/256x256/apps/$APPIMAGE_ID.png" + cp "$NIGHTLY_ICON" "$APPDIR/$APPIMAGE_ID.png" + ln -s "$APPIMAGE_ID.png" "$APPDIR/.DirIcon" + else + ln -s usr/bin/pdfcraft "$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 @@ -197,7 +336,11 @@ 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/pdfcraft}" - UPDATE_INFO="gh-releases-zsync|${REPO%%/*}|${REPO#*/}|latest|pdfcraft-*-linux-$ARCH.AppImage.zsync" + if [[ "$IS_NIGHTLY" = 0 ]]; then + UPDATE_INFO="gh-releases-zsync|${REPO%%/*}|${REPO#*/}|latest|pdfcraft-*-linux-$ARCH.AppImage.zsync" + else + UPDATE_INFO="gh-releases-zsync|${REPO%%/*}|${REPO#*/}|latest-pre|pdfcraft-*-linux-$ARCH.AppImage.zsync" + 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. diff --git a/packaging/macos/nightly-lib.sh b/packaging/macos/nightly-lib.sh new file mode 100644 index 0000000000..3aeafb9815 --- /dev/null +++ b/packaging/macos/nightly-lib.sh @@ -0,0 +1,110 @@ +# shellcheck shell=bash +# Shared checks for the Apple-silicon Nightly scripts (nightly.sh, nightly-sign.sh, nightly-verify.sh). +# Stable packaging (package.sh, verify.sh) does not source this file. The text checks take tool output +# as arguments, so packaging/macos/nightly_sign_tests.py runs them without macOS. + +MAC_NIGHTLY_APP='PdfCraft Nightly.app' +MAC_NIGHTLY_ID='ai.storyteller.pdfcraft.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" =~ ^pdfcraft-(.+)-macos-aarch64-nightly\.zip$ ]] || return 1 + version="${BASH_REMATCH[1]}" + [[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+-nightly\.[0-9]{8}\.[0-9]+\.[0-9]+\.g[0-9a-f]{12}$ ]] || return 1 + printf '%s\n' "$version" +} + +# Every signing and notarization value is set, and the team is one Apple team ID. No ad-hoc fallback. +mac_nightly_require_secrets() { + local name + for name in "${MAC_NIGHTLY_SECRETS[@]}"; do + [[ -n "${!name:-}" ]] || mac_nightly_die "$name is not set: Nightly signing and notarization are required, with no ad-hoc fallback" + done + [[ "$APPLE_TEAM_ID" =~ ^[A-Z0-9]{10}$ ]] || mac_nightly_die 'APPLE_TEAM_ID is not an Apple team ID' + if [[ -n "${NIGHTLY_APPLE_TEAM_ID:-}" && "$NIGHTLY_APPLE_TEAM_ID" != "$APPLE_TEAM_ID" ]]; then + mac_nightly_die 'the signing team differs from the reviewed Nightly team (NIGHTLY_APPLE_TEAM_ID)' + fi +} + +# One line of `security find-identity -v -p codesigning`: the identity is a Developer ID Application of the team. +mac_nightly_identity_is_team() { + local line="$1" identity="$2" team="$3" + [[ "$line" == *" $identity "* && "$line" == *'"Developer ID Application: '*" ($team)\""* ]] +} + +# `codesign -d --verbose=2` of the signed bundle: the Nightly identifier, a Developer ID Application of the +# team, a secure timestamp and the hardened runtime (the checks of verify.sh, made strict). +mac_nightly_check_signature() { + local details="$1" team="$2" ok=0 + grep -Fqx "Identifier=$MAC_NIGHTLY_ID" <<<"$details" || { echo "error: the bundle is not signed as $MAC_NIGHTLY_ID" >&2; ok=1; } + grep -q '^Authority=Developer ID Application:' <<<"$details" || { echo 'error: not signed with a Developer ID Application identity' >&2; ok=1; } + grep -qx "TeamIdentifier=$team" <<<"$details" || { echo 'error: signed by a different team' >&2; ok=1; } + grep -q '^Timestamp=' <<<"$details" || { echo 'error: the signature has no secure timestamp' >&2; ok=1; } + grep -Eq '^CodeDirectory .*flags=0x[0-9a-f]+\([^)]*runtime' <<<"$details" || { echo 'error: not signed with the hardened runtime' >&2; ok=1; } + return "$ok" +} + +# `spctl --assess --type execute -vv`: Gatekeeper accepts the bundle as notarized. +mac_nightly_check_assessment() { + grep -q 'accepted' <<<"$1" && grep -qx 'source=Notarized Developer ID' <<<"$1" +} + +# Before anything is unpacked: every ZIP entry is a regular file or directory inside the one Nightly +# bundle, with no absolute path, `..`, backslash or empty component, and no link or special file. +mac_nightly_check_zip_entries() { + python3 -I - "$1" "$MAC_NIGHTLY_APP" <<'PY' || mac_nightly_die 'the archive has an entry outside the bundle, a link or a special file' +import stat, sys, zipfile +archive, app = sys.argv[1:] +with zipfile.ZipFile(archive) as z: + for info in z.infolist(): + name = info.filename + parts = name.rstrip("/").split("/") + mode = info.external_attr >> 16 + if (name.startswith("/") or "\\" in name or "\0" in name or parts[0] != app + or any(part in ("", ".", "..") for part in parts) + or stat.S_IFMT(mode) not in (0, stat.S_IFREG, stat.S_IFDIR)): + sys.exit(f"refused entry: {name!r}") +PY +} + +# An unpacked payload directory holds exactly the GUI-only Nightly bundle: one thin arm64 PdfCraft +# 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")" == PdfCraft ]] || mac_nightly_die 'Contents/MacOS must hold only the PdfCraft GUI (no CLI)' + [[ -f "$app/Contents/MacOS/PdfCraft" && -x "$app/Contents/MacOS/PdfCraft" ]] || mac_nightly_die 'missing executable GUI' + [[ "$(lipo -archs "$app/Contents/MacOS/PdfCraft")" == arm64 ]] || mac_nightly_die 'the GUI must be thin arm64' + plist="$app/Contents/Info.plist" + for key in CFBundleIdentifier CFBundleExecutable PdfCraftVersion; 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" == PdfCraft ]] ;; + PdfCraftVersion) [[ "$value" == "$version" ]] ;; + esac || mac_nightly_die "Info.plist $key is not the prepared Nightly identity" + done + for key in CFBundleDocumentTypes CFBundleURLTypes UTExportedTypeDeclarations UTImportedTypeDeclarations; do + if plutil -extract "$key" xml1 -o - "$plist" >/dev/null 2>&1; then mac_nightly_die "Nightly declares $key"; fi + done +} + +# `stapler validate` asks Apple's CloudKit service, which sometimes drops the connection (error 68) +# though the ticket is there (verify.sh). +mac_nightly_validate_staple() { + local target="$1" attempt + for attempt in 1 2 3 4 5; do + xcrun stapler validate "$target" && return 0 + [[ "$attempt" = 5 ]] || sleep $((attempt * 20)) + done + return 1 +} diff --git a/packaging/macos/nightly-sign.sh b/packaging/macos/nightly-sign.sh new file mode 100755 index 0000000000..58210f621c --- /dev/null +++ b/packaging/macos/nightly-sign.sh @@ -0,0 +1,141 @@ +#!/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/pdfcraft--macos-aarch64-nightly.zip \ +# --output /abs//pdfcraft--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%/}/pdfcraft-nightly-sign.XXXXXX")" +KEYCHAIN="" +cleanup() { + if [[ -n "$KEYCHAIN" && -e "$KEYCHAIN" ]]; then security delete-keychain "$KEYCHAIN" >/dev/null 2>&1 || rm -f -- "$KEYCHAIN"; fi + rm -rf -- "$WORK" +} +trap cleanup EXIT + +# ---- identity: import-cert.sh, into this run's private directory ------------------------------ +# An empty GITHUB_ENV makes it print the identity instead of exporting it to later steps. +imported="$(GITHUB_ENV='' RUNNER_TEMP="$WORK" DIST="$WORK/dist" bash "$HERE/import-cert.sh")" +IDENTITY="$(sed -n 's/^MACOS_SIGN_IDENTITY=//p' <<<"$imported")" +KEYCHAIN="$(sed -n 's/^MACOS_KEYCHAIN=//p' <<<"$imported")" +[[ "$IDENTITY" =~ ^[0-9A-F]{40}$ && "$KEYCHAIN" == "$WORK"/pdfcraft-signing.*/pdfcraft-signing.keychain-db && "$KEYCHAIN" != *'/../'* ]] \ + || mac_nightly_die 'import-cert.sh did not import a signing identity' +mac_nightly_identity_is_team "$(security find-identity -v -p codesigning "$KEYCHAIN" | grep -F " $IDENTITY " || true)" "$IDENTITY" "$APPLE_TEAM_ID" \ + || mac_nightly_die "the imported identity is not a Developer ID Application of team $APPLE_TEAM_ID" +echo "==> PdfCraft 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/PdfCraft" +sign --options runtime --entitlements "$HERE/entitlements.plist" "$APP" +codesign --verify --strict --deep --verbose=2 "$APP" +ditto -c -k --keepParent "$APP" "$WORK/notarize.zip" +notarize "$WORK/notarize.zip" +# The ticket goes into the bundle (Contents/CodeResources): the Launcher's extract restores no xattrs. +staple "$APP" + +# ---- the final archive, checked as the Launcher unpacks it ----------------------------------------- +ditto -c -k --norsrc --noextattr --noacl --keepParent "$APP" "$WORK/final.zip" +ditto -x -k --norsrc --noextattr "$WORK/final.zip" "$WORK/check" +mac_nightly_check_bundle "$WORK/check" "$VERSION" +CHECK="$WORK/check/$MAC_NIGHTLY_APP" +codesign --verify --strict --deep --verbose=2 "$CHECK" +mac_nightly_check_signature "$(codesign -d --verbose=2 "$CHECK" 2>&1)" "$APPLE_TEAM_ID" \ + || mac_nightly_die 'the signed bundle is not the required Developer ID signature' +mac_nightly_validate_staple "$CHECK" || mac_nightly_die 'no notarization ticket is stapled into the bundle' +# spctl's lookup can lag a few seconds behind notarytool's "Accepted" (verify.sh). +for attempt in 1 2 3 4 5; do + assessment="$(spctl --assess --type execute -vv "$CHECK" 2>&1)" || true + mac_nightly_check_assessment "$assessment" && break + [[ "$attempt" = 5 ]] || sleep 10 +done +printf '%s\n' "$assessment" +mac_nightly_check_assessment "$assessment" || mac_nightly_die 'Gatekeeper does not accept the bundle as notarized' + +nightly_publish_archive "$WORK/final.zip" "$OUTPUT" diff --git a/packaging/macos/nightly-verify.sh b/packaging/macos/nightly-verify.sh new file mode 100755 index 0000000000..9a32647dd5 --- /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/pdfcraft--macos-aarch64-nightly.zip --expect signed [--team ID] +# nightly-verify.sh --input /abs/pdfcraft--macos-aarch64-nightly.zip --expect unsigned +# +# Both: the archive holds only the GUI-only Nightly bundle with the exact PdfCraftVersion, 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 `PdfCraft (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}}/pdfcraft-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/PdfCraft" "$@" 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" == "PdfCraft $VERSION (nightly-v1)" ]] || mac_nightly_die "the version query ($*) reports '$out', not PdfCraft $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): PdfCraft $VERSION (nightly-v1), plain and in the Launcher's profile form" diff --git a/packaging/macos/nightly.sh b/packaging/macos/nightly.sh new file mode 100755 index 0000000000..3bf6addf54 --- /dev/null +++ b/packaging/macos/nightly.sh @@ -0,0 +1,52 @@ +#!/usr/bin/env bash +# App-owned GUI-only Nightly for Apple silicon, compile step only (no signing material): +# +# $DIST/pdfcraft--macos-aarch64-nightly.zip PdfCraft Nightly.app, unsigned +# +# Usage: packaging/macos/nightly.sh --arch aarch64 +# +# Required env (nightly-common.sh): PDFCRAFT_BUILD_CHANNEL=nightly-v1, PDFCRAFT_VERSION, +# PDFCRAFT_BUILD_SHA, PDFCRAFT_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/pdfcraft-$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/docs" +cp "$NIGHTLY_GUI" "$APP/Contents/MacOS/PdfCraft" +chmod 755 "$APP/Contents/MacOS/PdfCraft" +cp "$ROOT/assets/app-icon/pdfcraft-nightly.icns" "$APP/Contents/Resources/pdfcraft-nightly.icns" +# Launcher admits notices under Resources/docs, not beside the icon. +nightly_copy_notices "$APP/Contents/Resources/docs" +# 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 "$PDFCRAFT_BUILD_SHA") +plutil -lint "$APP/Contents/Info.plist" +printf 'APPL????' >"$APP/Contents/PkgInfo" +mac_nightly_check_bundle "$NIGHTLY_WORK/stage" "$VERSION" + +# No resource forks, extended attributes or ACLs: the Launcher restores none, so nothing may depend on them. +ditto -c -k --norsrc --noextattr --noacl --keepParent "$APP" "$NIGHTLY_WORK/archive.zip" +nightly_publish_archive "$NIGHTLY_WORK/archive.zip" "$OUTPUT" diff --git a/packaging/macos/nightly_plist.py b/packaging/macos/nightly_plist.py new file mode 100755 index 0000000000..5bff4ba1ca --- /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.pdfcraft.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="PdfCraft Nightly", + CFBundleName="PdfCraft Nightly", + CFBundleIdentifier=IDENTIFIER, + CFBundleExecutable="PdfCraft", + CFBundleIconFile="pdfcraft-nightly", + CFBundleShortVersionString=match[1], + CFBundleVersion=match[1], + PdfCraftVersion=version, + PdfCraftBuildCommit=commit, + ) + return plistlib.dumps(data, fmt=plistlib.FMT_XML, sort_keys=False) + + +def write_plist(template: Path, destination: Path, version: str, commit: str) -> None: + with OwnedBuildRoot() as root: + content = render(root.read_bytes(template, MAX_TEMPLATE_BYTES), version, commit) + with root.create(destination) as stream: + stream.write(content) + stream.flush() + os.fsync(stream.fileno()) + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--template", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--version", required=True) + parser.add_argument("--source-commit", required=True) + args = parser.parse_args() + write_plist(args.template, args.output, args.version, args.source_commit) + + +if __name__ == "__main__": + main() diff --git a/packaging/macos/nightly_plist_tests.py b/packaging/macos/nightly_plist_tests.py new file mode 100755 index 0000000000..45c5a6343a --- /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.pdfcraft.nightly") + self.assertEqual(rendered["CFBundleExecutable"], "PdfCraft") + self.assertEqual(rendered["PdfCraftVersion"], VERSION) + self.assertEqual(rendered["PdfCraftBuildCommit"], COMMIT) + self.assertTrue(VERSION.startswith(rendered["CFBundleVersion"] + "-nightly.")) + for key in ("LSMinimumSystemVersion", "LSApplicationCategoryType", "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["PdfCraftVersion"], VERSION) + self.assertEqual(result["PdfCraftBuildCommit"], 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())["PdfCraftVersion"], VERSION) + + +if __name__ == "__main__": + unittest.main() diff --git a/packaging/macos/nightly_sign_tests.py b/packaging/macos/nightly_sign_tests.py new file mode 100755 index 0000000000..66e871430b --- /dev/null +++ b/packaging/macos/nightly_sign_tests.py @@ -0,0 +1,505 @@ +#!/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. The unsigned producer also runs with a stub GUI build. These +check the scripts and bundle layout, not native signing, notarization or Mac execution.""" +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"pdfcraft-{VERSION}-macos-aarch64-nightly.zip" +APP = "PdfCraft Nightly.app" +APP_NOTICES = ("README.md", "LICENSE-MIT", "LICENSE-APACHE", "NOTICE", "ATTRIBUTION.md") +OPTIONAL_NOTICES = ("LICENSE", "COPYRIGHT") +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.pdfcraft.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/PdfCraft" + exe.write_text(gui or f"#!/bin/sh\ntouch {self.ran}\necho 'PdfCraft {version} (nightly-v1)'\n") + exe.chmod(0o755) + (app / "Contents/Resources/pdfcraft-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 package(self, font_licences): + """Drive the real producer from a clean fixture checkout, without Cargo or Apple tools.""" + source = HERE.parents[1] + checkout = self.root / "source" + checkout.mkdir() + notices = APP_NOTICES + tuple(name for name in OPTIONAL_NOTICES if (source / name).is_file()) + for relative in (*notices, "packaging/env.sh", "packaging/nightly-common.sh", "packaging/nightly_paths.py", + "packaging/macos/nightly.sh", "packaging/macos/nightly-lib.sh", + "packaging/macos/Info.plist.in", "packaging/macos/nightly_plist.py", + "assets/app-icon/pdfcraft-nightly.icns"): + target = checkout / relative + target.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(source / relative, target) + env = self.env(**dict.fromkeys(SECRETS)) + + def git(*args): + return subprocess.run(["git", "-c", "core.hooksPath=/dev/null", "-c", "commit.gpgsign=false", *args], + cwd=checkout, env=env, check=True, capture_output=True, text=True, timeout=30).stdout + + git("init", "-q") + git("add", "--", ".") + git("-c", "user.name=Fixture", "-c", "user.email=fixture@example.invalid", "commit", "-qm", "Packaging fixture") + commit = git("rev-parse", "HEAD").strip() + version = VERSION[:-12] + commit[:12] + # Generated licence text exercises the copier without depending on a font checkout. + fonts = self.root / "craft-fonts" + for family, data in font_licences.items(): + licence = fonts / "fonts" / family / "OFL.txt" + licence.parent.mkdir(parents=True) + licence.write_bytes(data) + # The existing cargo stub fails for every invocation. Only this producer fixture emits a GUI. + (self.bin / "cargo").write_text( + '#!/bin/sh\nset -eu\n' + 'gui="$CARGO_TARGET_DIR/aarch64-apple-darwin/release/pdfcraft"\n' + 'mkdir -p "$(dirname "$gui")"\n' + "printf \"#!/bin/sh\\necho 'PdfCraft %s (nightly-v1)'\\n\" \"$PDFCRAFT_VERSION\" >\"$gui\"\n", + ) + result = self.run(checkout / "packaging/macos/nightly.sh", "--arch", "aarch64", **dict.fromkeys(SECRETS), + DIST=str(self.dist), CARGO_TARGET_DIR=str(self.root / "target"), CRAFT_FONTS_DIR=str(fonts), + PDFCRAFT_BUILD_CHANNEL="nightly-v1", PDFCRAFT_VERSION=version, + PDFCRAFT_BUILD_SHA=commit, PDFCRAFT_BUILD_DATE="2026-11-23") + assert result.returncode == 0, result.stdout + return self.dist / ASSET.replace(VERSION, version) + + 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.pdfcraft.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"pdfcraft-0.23.1-macos-aarch64.zip", f"pdfcraft-{VERSION}-macos-universal-nightly.zip", + f"pdfcraft-{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=pdfcraft-1234\nSignature=adhoc\nTeamIdentifier=not set\n", + DETAILS.replace("ai.storyteller.pdfcraft.nightly", "ai.storyteller.pdfcraft"), + DETAILS.replace("ai.storyteller.pdfcraft.nightly", "aiXstorytellerXpdfcraftXnightly")): + with self.subTest(broken=broken): + self.assertNotEqual(lib("mac_nightly_check_signature", broken, TEAM)[0], 0) + self.assertNotEqual(lib("mac_nightly_check_signature", DETAILS, "ZZZZZ99999")[0], 0, "another team") + + def test_gatekeeper_must_accept_the_bundle_as_notarized(self): + self.assertEqual(lib("mac_nightly_check_assessment", "x.app: accepted\nsource=Notarized Developer ID\n")[0], 0) + for text in ("x.app: accepted\nsource=Developer ID\n", "x.app: rejected\nsource=Unnotarized Developer ID\n"): + with self.subTest(text=text): + self.assertNotEqual(lib("mac_nightly_check_assessment", text)[0], 0) + + def test_the_imported_identity_must_be_a_developer_id_of_the_team(self): + line = f' 1) {IDENTITY} "Developer ID Application: Generated Fixture ({TEAM})"' + self.assertEqual(lib("mac_nightly_identity_is_team", line, IDENTITY, TEAM)[0], 0) + self.assertNotEqual(lib("mac_nightly_identity_is_team", line, IDENTITY, "ZZZZZ99999")[0], 0) + self.assertNotEqual(lib("mac_nightly_identity_is_team", line.replace("Developer ID Application", "Apple Development"), IDENTITY, TEAM)[0], 0) + + +class Sign(unittest.TestCase): + def setUp(self): + self.f = Fixture(self) + self.f.bundle() + self.unsigned = self.f.input.read_bytes() + + def assert_refused_untouched(self, result, signed=False): + self.assertNotEqual(result.returncode, 0, result.stdout) + self.assertFalse(self.f.output.exists()) + self.assertEqual(self.f.input.read_bytes(), self.unsigned) + self.assertFalse(self.f.ran.exists(), "the payload must never run in the signing step") + names = [call[0] for call in self.f.calls()] + self.assertNotIn("cargo", names) + if not signed: + self.assertNotIn("codesign", names) + self.assertNotIn("xcrun", names) + self.assertEqual(list(self.f.temp.iterdir()), [], "the work directory and keychain are removed") + + def test_signs_notarizes_and_staples_without_running_the_payload(self): + result = self.f.sign() + self.assertEqual(result.returncode, 0, result.stdout) + self.assertFalse(self.f.hijacked.exists(), "helpers run isolated (python3 -I) beside the secrets") + calls = self.f.calls() + names = [call[0] for call in calls] + self.assertNotIn("cargo", names) + self.assertFalse(self.f.ran.exists(), "the payload must never run in the signing step") + self.assertEqual(self.f.input.read_bytes(), self.unsigned) + signs = [call for call in calls if call[0] == "codesign" and "--sign" in call] + self.assertEqual([Path(call[-1]).name for call in signs], ["PdfCraft", APP], "inside-out: executable, then bundle") + for call in signs: + for flag in ("--force", "--timestamp", "runtime", str(HERE / "entitlements.plist"), IDENTITY): + self.assertIn(flag, call) + order = [" ".join(call[:3]) for call in calls] + submit = order.index("xcrun notarytool submit") + staple = order.index("xcrun stapler staple") + self.assertLess(max(i for i, call in enumerate(calls) if call[0] == "codesign" and "--sign" in call), submit) + self.assertLess(submit, staple) + final = [i for i, call in enumerate(calls) if call[0] == "ditto" and "-c" in call][-1] + self.assertLess(staple, final, "the final archive carries the stapled ticket") + self.assertIn("--noextattr", calls[final]) + self.assertIn(["security", "delete-keychain"], [call[:2] for call in calls]) + self.assertEqual(list(self.f.temp.iterdir()), [], "the work directory and keychain are removed") + with zipfile.ZipFile(self.f.output) as z: + names = set(z.namelist()) + self.assertIn(f"{APP}/Contents/CodeResources", names, "stapled ticket inside the bundle") + self.assertIn(f"{APP}/Contents/_CodeSignature/CodeResources", names) + self.assertTrue(all(name.startswith(APP) for name in names)) + mode = z.getinfo(f"{APP}/Contents/MacOS/PdfCraft").external_attr >> 16 + self.assertTrue(mode & stat.S_IXUSR) + + def test_every_signing_and_notarization_secret_is_required(self): + for name in SECRETS: + with self.subTest(missing=name): + self.assert_refused_untouched(self.f.sign(**{name: None})) + self.assertEqual(self.f.calls(), [], "no tool runs before the configuration is complete") + self.assert_refused_untouched(self.f.sign(NIGHTLY_APPLE_TEAM_ID="ZZZZZ99999")) + self.assert_refused_untouched(self.f.sign(APPLE_TEAM_ID="not-a-team")) + + def test_refuses_another_team_s_identity(self): + self.assert_refused_untouched(self.f.sign(SHIM_TEAM="ZZZZZ99999")) + + def test_never_replaces_an_output_or_renames_the_asset(self): + self.f.output.write_bytes(b"generated existing artifact") + result = self.f.sign() + self.assertNotEqual(result.returncode, 0) + self.assertEqual(self.f.output.read_bytes(), b"generated existing artifact") + self.f.output.unlink() + renamed = self.f.run("nightly-sign.sh", "--arch", "aarch64", "--input", self.f.input, "--output", self.f.signed / "other.zip") + self.assertNotEqual(renamed.returncode, 0) + relative = self.f.run("nightly-sign.sh", "--arch", "aarch64", "--input", self.f.input.name, "--output", self.f.output) + self.assertNotEqual(relative.returncode, 0) + self.assertEqual(list(self.f.signed.iterdir()), []) + + def test_refuses_a_payload_that_is_not_the_exact_gui_only_nightly(self): + cases = { + "cli": dict(extra={"Contents/MacOS/pdfcraft-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 'PdfCraft {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 'PdfCraft 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 'PdfCraft {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_unsigned_archive_has_launcher_layout_and_keeps_all_notices(self): + f = Fixture(self) + fonts = {"fixture-one": b"generated font notice one", "fixture-two": b"generated font notice two"} + archive = f.package(fonts) + source = HERE.parents[1] + resources = f"{APP}/Contents/Resources" + icon = "pdfcraft-nightly.icns" + notice_files = {name: (source / name).read_bytes() for name in APP_NOTICES} + notice_files.update({name: (source / name).read_bytes() for name in OPTIONAL_NOTICES if (source / name).is_file()}) + notice_files.update({f"OFL-{family}.txt": data for family, data in fonts.items()}) + # Shipped Launcher v0.20.3 accepts these leaves only in Resources/docs, except for the root icon. + expected_files = {f"{resources}/docs/{name}": data for name, data in notice_files.items()} + expected_files[f"{resources}/{icon}"] = (source / "assets/app-icon" / icon).read_bytes() + contents = f"{APP}/Contents" + gui = f"{contents}/MacOS/PdfCraft" + with zipfile.ZipFile(archive) as zipped: + entries = zipped.infolist() + names = {entry.filename for entry in entries} + self.assertEqual(len(entries), len({name.casefold() for name in names}), "unique paths, ignoring case") + self.assertEqual({entry.filename for entry in entries if not entry.is_dir()}, + set(expected_files) | {gui, f"{contents}/Info.plist", f"{contents}/PkgInfo"}) + self.assertTrue({entry.filename for entry in entries if entry.is_dir()} <= { + f"{APP}/", f"{contents}/", f"{contents}/MacOS/", f"{resources}/", f"{resources}/docs/"}) + for path, data in expected_files.items(): + with self.subTest(path=path): + self.assertEqual(zipped.read(path), data) + mode = zipped.getinfo(path).external_attr >> 16 + self.assertTrue(stat.S_ISREG(mode)) + self.assertFalse(mode & 0o111) + mode = zipped.getinfo(gui).external_attr >> 16 + self.assertTrue(stat.S_ISREG(mode) and mode & stat.S_IXUSR) + result = f.run("nightly-verify.sh", "--input", archive, "--expect", "unsigned", **dict.fromkeys(SECRETS)) + self.assertEqual(result.returncode, 0, result.stdout) + + 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"}, + PDFCRAFT_BUILD_CHANNEL="nightly-v1", PDFCRAFT_VERSION=VERSION) + self.assertNotEqual(result.returncode, 0) + self.assertIn(name, result.stdout) + self.assertNotIn("cargo", [call[0] for call in f.calls()]) + + +if __name__ == "__main__": + unittest.main() diff --git a/packaging/nightly-archive-tests.py b/packaging/nightly-archive-tests.py new file mode 100755 index 0000000000..2f642d3152 --- /dev/null +++ b/packaging/nightly-archive-tests.py @@ -0,0 +1,229 @@ +#!/usr/bin/env python3 +"""Synthetic app-owned archive/output tests; no native build or executable launch.""" +import gzip +import importlib.util +import os +import runpy +import sys +from unittest import mock +from pathlib import Path +import subprocess +import tarfile +import tempfile +import unittest + +HERE = Path(__file__).resolve().parent +SPEC = importlib.util.spec_from_file_location("photo_nightly_archive", HERE / "nightly-archive.py") +ARCHIVE = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(ARCHIVE) + + +class ArchivePolicy(unittest.TestCase): + def setUp(self): + self.scratch = tempfile.TemporaryDirectory() + self.addCleanup(self.scratch.cleanup) + self.root = Path(self.scratch.name).resolve() + previous = Path.cwd() + os.chdir(self.root) + self.addCleanup(os.chdir, previous) + self.stage = self.root / "stage" + self.stage.mkdir() + self.output = self.root / "nightly.tar.gz" + self.required = {"pdfcraft", "pdfcraft-bin", "pdfcraft-nightly.png", "README.md", "LICENSE-MIT", "LICENSE-APACHE", "NOTICE", "ATTRIBUTION.md"} + for name in self.required: + (self.stage / name).write_bytes(b"generated fixture: " + name.encode()) + (self.stage / "pdfcraft").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("pdfcraft").read(), (self.stage / "pdfcraft").read_bytes()) + with gzip.open(self.output, "rb") as stream: + while (header := stream.read(512)) != bytes(512): + self.assertEqual(len(header), 512) + self.assertIn(header[156:157], {b"0", b"\0"}) + self.assertEqual(header[257:263], b"ustar\0") + size = int(header[124:136].rstrip(b"\0 ").lstrip(b" ") or b"0", 8) + stream.read(((size + 511) // 512) * 512) + + def test_each_required_member_is_required_before_output(self): + for name in self.required: + with self.subTest(name=name): + content = (self.stage / name).read_bytes() + (self.stage / name).unlink() + with self.assertRaisesRegex(ValueError, "required"): + ARCHIVE.linux_archive(self.stage, self.output) + self.assertFalse(self.output.exists()) + (self.stage / name).write_bytes(content) + + def test_unexpected_cli_portable_or_installer_member_refuses(self): + for name in ["pdfcraft-cli", "portable.txt", "pdfcraft.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 / "pdfcraft-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 / "pdfcraft-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 0000000000..5ddd43a9e9 --- /dev/null +++ b/packaging/nightly-archive.py @@ -0,0 +1,131 @@ +#!/usr/bin/env python3 +"""Flat Linux archive policy, invoked from its private owned build cwd. + +The stage and archive must both remain under that independently chosen root. +No native build, platform signing, or malicious-same-UID sandbox is implied. +""" +import grp +import gzip +import os +import pathlib +import pwd +import re +import stat +import sys +import tarfile + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) +from nightly_paths import OwnedBuildRoot + +APP_DOCS = {"README.md", "LICENSE", "LICENSE-MIT", "LICENSE-APACHE", "COPYRIGHT", "NOTICE", "ATTRIBUTION.md"} +MAX_MEMBER_BYTES = 512 * 1024 * 1024 +MAX_TOTAL_BYTES = 1024 * 1024 * 1024 +MAX_MEMBERS = 128 + + +def notice(name): + return name in APP_DOCS or re.fullmatch(r"OFL-[A-Za-z0-9_.-]+\.txt", name) is not None + + +def checked_entries(root, stage): + entries = sorted(root.children(stage, MAX_MEMBERS), key=lambda item: item.name) + folded = set() + total = 0 + for entry in entries: + name = entry.name + # `pdfcraft` is the launcher and `pdfcraft-bin` the GUI it starts with the private profile. + if name not in {"pdfcraft", "pdfcraft-bin", "pdfcraft-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 = {"pdfcraft", "pdfcraft-bin", "pdfcraft-nightly.png", "README.md", "LICENSE-MIT", "LICENSE-APACHE", "NOTICE", "ATTRIBUTION.md"} + if not required.issubset({item.name for item in entries}): + raise ValueError("required GUI/icon/notices missing") + return entries + + +def member_info(stage_root, name, incoming): + """Header for one stage file, built from the file this run opened rather than from the archive. + + Members are flat names that resolve directly inside the stage they came from. + """ + if os.path.isabs(name) or os.path.basename(name) != name or name in ("", ".", ".."): + raise ValueError(f"nightly member name must be a flat file name: {name}") + destination = os.path.realpath(os.path.join(stage_root, name)) + if not destination.startswith(stage_root + os.sep) or os.path.dirname(destination) != stage_root: + raise ValueError(f"nightly member resolves outside its stage: {name}") + status = os.fstat(incoming.fileno()) + if not stat.S_ISREG(status.st_mode): + raise ValueError(f"nightly member must be a regular file: {name}") + # The same fields TarFile.gettarinfo records for a regular file. + info = tarfile.TarInfo(os.path.basename(destination)) + info.type = tarfile.REGTYPE + info.mode = stat.S_IMODE(status.st_mode) + info.uid, info.gid = status.st_uid, status.st_gid + info.size = status.st_size + info.mtime = status.st_mtime + try: + info.uname = pwd.getpwuid(status.st_uid).pw_name + except KeyError: + pass + try: + info.gname = grp.getgrgid(status.st_gid).gr_name + except KeyError: + pass + return info + + +def verify_headers(root, output): + # Bounded ordinary headers, not a transparent PAX/GNU-normalizing reader. + total = 0 + count = 0 + with root.reader(output, MAX_TOTAL_BYTES) as incoming, gzip.GzipFile(fileobj=incoming) as stream: + while True: + header = stream.read(512) + if header == b"\0" * 512: + break + if len(header) != 512 or header[156:157] not in {b"0", b"\0"}: + raise ValueError("non-ordinary TAR record was emitted") + size = int(header[124:136].rstrip(b"\0 ").lstrip(b" ") or b"0", 8) + count += 1 + total += size + if count > MAX_MEMBERS or size > MAX_MEMBER_BYTES or total > MAX_TOTAL_BYTES: + raise ValueError("archive exceeds its bounded member budget") + remaining = ((size + 511) // 512) * 512 + while remaining: + chunk = stream.read(min(remaining, 1024 * 1024)) + if not chunk: + raise ValueError("truncated TAR member") + remaining -= len(chunk) + + +def linux_archive(stage, output): + with OwnedBuildRoot() as root: + entries = checked_entries(root, stage) + stage_root = os.path.realpath(os.path.join(root.directory, stage)) + total = 0 + with root.create(output) as outgoing: + with tarfile.open(fileobj=outgoing, mode="w:gz", format=tarfile.USTAR_FORMAT) as archive: + for entry in entries: + with root.reader(entry, MAX_MEMBER_BYTES) as incoming: + info = member_info(stage_root, entry.name, incoming) + total += info.size + if info.size > MAX_MEMBER_BYTES or total > MAX_TOTAL_BYTES: + raise ValueError("nightly stage grew beyond its read bound") + archive.addfile(info, incoming) + outgoing.flush() + os.fsync(outgoing.fileno()) + verify_headers(root, output) + + +if __name__ == "__main__": + if len(sys.argv) != 4 or sys.argv[1] != "linux": + raise SystemExit("usage: nightly-archive.py linux STAGE OUTPUT (from owned private build cwd)") + linux_archive(pathlib.Path(sys.argv[2]), pathlib.Path(sys.argv[3])) diff --git a/packaging/nightly-common.sh b/packaging/nightly-common.sh new file mode 100644 index 0000000000..e8f6128f4b --- /dev/null +++ b/packaging/nightly-common.sh @@ -0,0 +1,104 @@ +# 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 + [[ "${PDFCRAFT_BUILD_CHANNEL:-}" == nightly-v1 ]] || nightly_die 'PDFCRAFT_BUILD_CHANNEL must be nightly-v1' + [[ "${PDFCRAFT_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' + [[ "${PDFCRAFT_BUILD_SHA:-}" =~ ^[0-9a-f]{40}$ ]] || nightly_die 'an exact source commit is required' + [[ "${PDFCRAFT_VERSION##*.g}" == "${PDFCRAFT_BUILD_SHA:0:12}" ]] || nightly_die 'version/source commit mismatch' + [[ "${PDFCRAFT_BUILD_DATE:-}" =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}$ ]] || nightly_die 'the original run-created UTC date is required' + date_digits="${PDFCRAFT_VERSION#*-nightly.}" + date_digits="${date_digits%%.*}" + [[ "${PDFCRAFT_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)" == "$PDFCRAFT_BUILD_SHA" ]] || nightly_die 'prepared source is not the checked-out commit' + [[ -z "$(git -C "$ROOT" status --porcelain)" ]] || nightly_die 'nightly packaging requires the frozen clean source' + if [[ -n "${CRAFT_FONTS_DIR:-}" && ! -d "$CRAFT_FONTS_DIR/fonts" ]]; then + nightly_die 'declared CRAFT_FONTS_DIR has no fonts directory' + fi + # env.sh retains the established notice copier. Required values above prohibit its stable fallbacks. + # shellcheck source=env.sh + . "$ROOT/packaging/env.sh" + export CARGO_TARGET_DIR="$CARGO_TARGET_DIR/nightly-v1/$os-$arch" + NIGHTLY_RUST_TARGET="$target" + mkdir -p "$CARGO_TARGET_DIR" + NIGHTLY_WORK="$(mktemp -d "$CARGO_TARGET_DIR/nightly-package.XXXXXX")" + trap 'rm -rf -- "$NIGHTLY_WORK"' EXIT +} + +# Compile only: macOS runs the version query after signing. The flavor's `build.rs` compiles the +# channel from `PDFCRAFT_BUILD_CHANNEL` and embeds `PDFCRAFT_VERSION` (it does not read the +# PhotoCraft-style `PDFCRAFT_OVERRIDE_VERSION`, so both are passed explicitly rather than inherited). +nightly_compile_gui() { + # Signing material never reaches compilation (the Windows -CheckBuildEnvironment rule). + nightly_refuse_signing_env + (cd "$ROOT" && PDFCRAFT_BUILD_CHANNEL=nightly-v1 PDFCRAFT_VERSION="$VERSION" \ + cargo build --release --locked -p pdfcraft --target "$NIGHTLY_RUST_TARGET") + NIGHTLY_GUI="$CARGO_TARGET_DIR/$NIGHTLY_RUST_TARGET/release/pdfcraft" + [[ -f "$NIGHTLY_GUI" && ! -L "$NIGHTLY_GUI" ]] || nightly_die 'the owned GUI build did not produce a regular executable' + [[ "$(git -C "$ROOT" rev-parse HEAD)" == "$PDFCRAFT_BUILD_SHA" && -z "$(git -C "$ROOT" status --porcelain)" ]] || nightly_die 'source changed during the build' +} + +# The flavor prints exactly what it is -- `PdfCraft (nightly-v1)` -- so the check +# compares that line, not a substring a stable binary could also print. The Launcher's query form is +# answered from the same parse, before any root is validated, so it must leave the root uncreated. +nightly_build_gui() { + nightly_compile_gui + local actual expected query_root + expected="PdfCraft $VERSION (nightly-v1)" + actual="$("$NIGHTLY_GUI" --version)" || nightly_die 'side-effect-free nightly version verification failed' + [[ "$actual" == "$expected" ]] || nightly_die "the built identity is not the prepared nightly: $actual" + query_root="$NIGHTLY_WORK/launcher-query-profile" + actual="$("$NIGHTLY_GUI" --launch-profile nightly-v1 --profile-root "$query_root" --version)" \ + || nightly_die 'the Launcher version query did not answer' + [[ "$actual" == "$expected" ]] || nightly_die "the Launcher version query did not report the prepared identity: $actual" + [[ ! -e "$query_root" && ! -L "$query_root" ]] || nightly_die 'the Launcher version query touched the profile root' + [[ "$(git -C "$ROOT" rev-parse HEAD)" == "$PDFCRAFT_BUILD_SHA" && -z "$(git -C "$ROOT" status --porcelain)" ]] || nightly_die 'source changed during the version query' +} + +# Signing material never reaches compilation (the Windows -CheckBuildEnvironment rule). +nightly_refuse_signing_env() { + local name + # The signing names release.yml passes, for every platform, and import-cert.sh's outputs. + for name in APPLE_CERTIFICATE APPLE_CERTIFICATE_PASSWORD KEYCHAIN_PASSWORD APPLE_ID APPLE_PASSWORD APPLE_TEAM_ID \ + MACOS_SIGN_IDENTITY MACOS_KEYCHAIN WINDOWS_CERTIFICATE WINDOWS_CERTIFICATE_PASSWORD AZURE_TENANT_ID AZURE_CLIENT_ID \ + AZURE_CLIENT_SECRET AZURE_SIGNING_ENDPOINT AZURE_SIGNING_ACCOUNT AZURE_CERT_PROFILE LINUX_SIGNING_KEY; do + [[ -z "${!name:-}" ]] || nightly_die "compilation must not receive signing configuration ($name); sign in the separate trusted step" + done +} + +nightly_copy_notices() { + local destination="$1" required + for required in README.md LICENSE-MIT LICENSE-APACHE NOTICE ATTRIBUTION.md; do + [[ -f "$ROOT/$required" && ! -L "$ROOT/$required" ]] || nightly_die "missing regular app notice: $required" + done + copy_docs "$destination" +} + +nightly_publish_archive() { + # Exclusive creation: never replace an existing artifact, even if another writer raced the preflight. + python3 -I - "$1" "$2" <<'PY' +import os, shutil, sys +source, destination = sys.argv[1:] +created = False +try: + # Open the input first: a missing source must not leave an empty final artifact. + with open(source, 'rb') as incoming: + with open(destination, 'xb') as output: + created = True + shutil.copyfileobj(incoming, output, length=1024 * 1024) + output.flush() + os.fsync(output.fileno()) +except BaseException: + if created: + os.unlink(destination) + raise +PY + printf 'Nightly artifact: %s\n' "$2" +} diff --git a/packaging/nightly-launcher-tests.py b/packaging/nightly-launcher-tests.py new file mode 100755 index 0000000000..a9139f11b9 --- /dev/null +++ b/packaging/nightly-launcher-tests.py @@ -0,0 +1,238 @@ +#!/usr/bin/env python3 +"""Every Linux Nightly launcher starts the GUI the flavor's way; no build, no window. + +The plain tar's `pdfcraft` is the canonical shared template +(craft-common-actions scripts/nightly-launcher.sh.in), which the nightly producer accepts byte for +byte: it always starts `pdfcraft-bin` beside itself on the nightly-v1 profile under the app's +package identity, answers a version query with one plain `--version` and wraps everything else. The +deb/rpm wrapper, the AppImage `AppRun`, the Flatpak wrapper and the Arch handoff are generated by +this app's own scripts and keep their own profile folder; each must hand the binary the one protocol +the flavor accepts -- `--launch-profile nightly-v1 --profile-root -- files...` -- and pass a +version query through untouched. +""" +from pathlib import Path +import shutil +import subprocess +import tempfile +import unittest + +HERE = Path(__file__).resolve().parent +LINUX = HERE / "linux" +PROFILE = "pdfcraft-nightly" +# The tar launcher is the canonical template, so its profile folder is the nightly package identity. +TEMPLATE_IDENTITY = "ai.storyteller.pdfcraft.nightly" +RECORDER = '#!/bin/sh\nfor arg in "$@"; do printf "<%s>\\n" "$arg"; done\n' +CONFIG_RECORDER = ( + '#!/bin/sh\nprintf "config=%s\\n" "${PDFCRAFT_CONFIG_DIR+<$PDFCRAFT_CONFIG_DIR>}"\n' + 'for arg in "$@"; do printf "<%s>\\n" "$arg"; done\n' +) + + +def heredoc(script, marker, needle): + """The one heredoc body in `script` delimited by `marker` that contains `needle`.""" + text = Path(script).read_text(encoding="utf-8") + bodies = [] + start = 0 + while (opening := text.find("<<'%s'" % marker, start)) != -1: + body_start = text.index("\n", opening) + 1 + body_end = text.index("\n%s\n" % marker, body_start) + bodies.append(text[body_start:body_end] + "\n") + start = body_end + 1 + matched = [body for body in bodies if needle in body] + if len(matched) != 1: + raise AssertionError(f"expected one {marker} heredoc with {needle!r} in {script}, found {len(matched)}") + return matched[0] + + +class Launcher(unittest.TestCase): + def setUp(self): + scratch = tempfile.TemporaryDirectory() + self.addCleanup(scratch.cleanup) + self.root = Path(scratch.name).resolve() + self.home = self.root / "home with space" + self.home.mkdir() + self.real = self.root / "pdfcraft-real" + self.real.write_text(RECORDER, encoding="utf-8") + self.real.chmod(0o755) + + def launcher(self, name, body): + path = self.root / name + path.write_text(body, encoding="utf-8") + path.chmod(0o755) + return path + + def generated(self, script, marker, needle, replacement): + body = heredoc(script, marker, needle) + return self.launcher("pdfcraft-nightly", body.replace(needle, str(replacement))) + + def recording(self, launcher, *args, env=None): + environment = {"PATH": "/usr/bin:/bin", "HOME": str(self.home), **(env or {})} + result = subprocess.run([str(launcher), *args], capture_output=True, text=True, env=environment, timeout=60) + self.assertEqual(result.returncode, 0, result.stderr) + return [line[1:-1] for line in result.stdout.splitlines() if line.startswith("<")] + + def profile_base(self, env=None, fallback=(".local", "share")): + return Path((env or {}).get("XDG_DATA_HOME") or self.home.joinpath(*fallback)) / PROFILE + + def assert_starts_the_profile(self, launcher, env=None, fallback=(".local", "share")): + root = str(self.profile_base(env, fallback)) + files = ["drawing.dxf", "with spaces and -- dashes.dxf"] + self.assertEqual( + self.recording(launcher, *files, env=env), + ["--launch-profile", "nightly-v1", "--profile-root", root, "--", *files], + launcher, + ) + self.assertEqual(self.recording(launcher, env=env), ["--launch-profile", "nightly-v1", "--profile-root", root, "--"]) + for flag in ("--version", "-V"): + self.assertEqual(self.recording(launcher, flag, env=env), [flag], launcher) + query = ["--launch-profile", "nightly-v1", "--profile-root", str(self.root / "launcher root"), "--version"] + self.assertEqual(self.recording(launcher, *query, env=env), query, "a Launcher query is passed through once") + + # -- the flat tar: the canonical shared launcher template ----------------------------------- + def template(self): + """The tar's launcher as the shared template renders it for this app: PdfCraft Nightly's + package identity is its profile folder, and `pdfcraft-bin` sits beside the script.""" + (self.root / "pdfcraft-bin").write_text(RECORDER, encoding="utf-8") + (self.root / "pdfcraft-bin").chmod(0o755) + return self.launcher("pdfcraft", (LINUX / "nightly-launch.sh").read_text(encoding="utf-8")) + + def template_profile(self, env=None): + return Path((env or {}).get("XDG_DATA_HOME") or self.home / ".local" / "share") / TEMPLATE_IDENTITY + + def test_the_plain_tar_launcher_is_the_shared_template(self): + launcher = LINUX / "nightly-launch.sh" + self.assertIn("# Nightly launcher generated by craft-common-actions scripts/nightly-launcher.sh.in.", + launcher.read_text(encoding="utf-8")) + self.assertIn('target="$dir/pdfcraft-bin"', launcher.read_text(encoding="utf-8")) + self.assertIn(' --launch-profile) exec "$target" "$@" ;;', launcher.read_text(encoding="utf-8")) + self.assertIn('}/ai.storyteller.pdfcraft.nightly"', launcher.read_text(encoding="utf-8")) + + def test_the_plain_tar_launcher_starts_the_profile(self): + command = self.template() + files = ["drawing.dxf", "with spaces and -- dashes.dxf"] + root = str(self.template_profile()) + self.assertEqual(self.recording(command, *files), + ["--launch-profile", "nightly-v1", "--profile-root", root, "--", *files]) + self.assertEqual(self.recording(command), ["--launch-profile", "nightly-v1", "--profile-root", root, "--"]) + xdg = {"XDG_DATA_HOME": str(self.root / "xdg with space")} + self.assertEqual(self.recording(command, "drawing.dxf", env=xdg), + ["--launch-profile", "nightly-v1", "--profile-root", str(self.template_profile(xdg)), + "--", "drawing.dxf"]) + + def test_the_template_answers_its_version_query_with_one_plain_argument(self): + # Both spellings reach the GUI as `--version`: the template never forwards `-V`. + command = self.template() + env = {"XDG_DATA_HOME": str(self.root / "xdg")} + root = str(self.template_profile(env)) + for flag in ("--version", "-V"): + with self.subTest(flag=flag): + self.assertEqual(self.recording(command, flag, env=env), + ["--launch-profile", "nightly-v1", "--profile-root", root, "--version"]) + + def test_the_launchers_own_profile_line_passes_through_untouched(self): + # The ArtCraft Launcher starts the tar's entry point with its own profile pair and per-install + # root; the template hands that line to the GUI unchanged. + command = self.template() + managed = str(self.root / "launcher root") + for supplied in (["--launch-profile", "nightly-v1", "--profile-root", managed, "--"], + ["--launch-profile", "nightly-v1", "--profile-root", managed, "--", "drawing.dxf"], + ["--launch-profile"]): + with self.subTest(supplied=supplied): + self.assertEqual(self.recording(command, *supplied), supplied) + + def test_every_other_line_still_gets_the_templates_own_profile(self): + # Only a line that opens with `--launch-profile` exactly is the Launcher's: a `--profile-root` + # first, the `=` spelling, or any other argument is wrapped in the fixed profile. + command = self.template() + root = str(self.template_profile()) + for arguments in (["--profile-root", str(self.root / "launcher root"), "--"], + ["--launch-profile=nightly-v1"], ["--help"]): + with self.subTest(arguments=arguments): + self.assertEqual(self.recording(command, *arguments), + ["--launch-profile", "nightly-v1", "--profile-root", root, "--", *arguments]) + + def test_the_template_refuses_a_missing_gui(self): + command = self.template() + (self.root / "pdfcraft-bin").unlink() + for args in ([], ["--version"]): + with self.subTest(args=args): + result = subprocess.run([str(command), *args], capture_output=True, text=True, timeout=60, + env={"PATH": "/usr/bin:/bin", "HOME": str(self.home)}) + self.assertNotEqual(result.returncode, 0, result.stdout) + self.assertEqual(result.stdout, "") + + def test_the_template_resolves_its_own_folder_physically(self): + # `dir` is the directory the script is reached through, resolved with `pwd -P`: a symlinked + # folder path still finds the GUI beside the real file. + command = self.template() + link = self.root / "linked" / "bin" + link.parent.mkdir() + link.symlink_to(command.parent) + root = str(self.template_profile()) + self.assertEqual(self.recording(link / "pdfcraft", "drawing.dxf"), + ["--launch-profile", "nightly-v1", "--profile-root", root, "--", "drawing.dxf"]) + + def test_the_template_needs_a_data_folder_before_it_starts_anything(self): + command = self.template() + result = subprocess.run([str(command)], capture_output=True, text=True, timeout=60, + env={"PATH": "/usr/bin:/bin"}) + self.assertNotEqual(result.returncode, 0) + self.assertEqual(result.stdout, "") + self.assertIn("HOME", result.stderr) + + def test_the_arch_launcher_starts_the_profile(self): + (self.root / ".pdfcraft-nightly").mkdir() + shutil.copy(self.real, self.root / ".pdfcraft-nightly" / "pdfcraft") + installed = self.launcher("pdfcraft-nightly", (LINUX / "nightly-arch-launch.sh").read_text(encoding="utf-8")) + self.assert_starts_the_profile(installed) + self.assert_starts_the_profile(installed, {"XDG_DATA_HOME": str(self.root / "xdg with space")}) + + def test_the_deb_and_rpm_wrapper_starts_the_profile(self): + generated = self.generated(LINUX / "package.sh", "WRAPPER", "/usr/lib/pdfcraft-nightly/pdfcraft", self.real) + self.assert_starts_the_profile(generated) + self.assert_starts_the_profile(generated, {"XDG_DATA_HOME": str(self.root / "xdg with space")}) + + def test_the_appimage_apprun_starts_the_profile(self): + appdir = self.root / "PdfCraft.AppDir" + (appdir / "usr/bin").mkdir(parents=True) + shutil.copy(self.real, appdir / "usr/bin" / "pdfcraft") + apprun = self.launcher("AppRun", heredoc(LINUX / "package.sh", "APPRUN", "$APPDIR/usr/bin/pdfcraft")) + shutil.move(str(apprun), str(appdir / "AppRun")) + self.assert_starts_the_profile(appdir / "AppRun") + self.assert_starts_the_profile(appdir / "AppRun", {"XDG_DATA_HOME": str(self.root / "xdg with space")}) + + def test_the_nightly_cli_keeps_its_settings_in_the_profile(self): + body = heredoc(LINUX / "package.sh", "CLI_WRAPPER", "/usr/lib/pdfcraft-nightly/pdfcraft-cli") + cli = self.launcher("pdfcraft-nightly-cli", body.replace("/usr/lib/pdfcraft-nightly/pdfcraft-cli", str(self.real))) + self.real.write_text(CONFIG_RECORDER, encoding="utf-8") + self.real.chmod(0o755) + # A downstream process sees the variable the CLI wrapper exported. + def recorded(*args, config=None, xdg=None): + environment = {"PATH": "/usr/bin:/bin", "HOME": str(self.home)} + if xdg is not None: + environment["XDG_DATA_HOME"] = xdg + if config is not None: + environment["PDFCRAFT_CONFIG_DIR"] = config + result = subprocess.run([str(cli), *args], capture_output=True, text=True, env=environment, timeout=60) + self.assertEqual(result.returncode, 0, result.stderr) + lines = result.stdout.splitlines() + return lines[0], lines[1:] + + base = Path(str(self.home / ".local" / "share")) / PROFILE + self.assertEqual(recorded("convert", "in.dxf"), (f"config=<{base}>", ["", ""])) + self.assertEqual(recorded("convert", xdg=str(self.root / "xdg with space"))[0], f"config=<{self.root}/xdg with space/{PROFILE}>") + # An explicitly empty value still means "no settings folder", and an explicit one is kept. + self.assertEqual(recorded("run")[0], f"config=<{base}>") + self.assertEqual(recorded("run", config="")[0], "config=<>") + self.assertEqual(recorded("run", config=str(self.root / "explicit"))[0], f"config=<{self.root}/explicit>") + + def test_the_flatpak_wrapper_starts_the_profile(self): + generated = self.generated(LINUX / "flatpak-bundle.sh", "WRAPPER", "/app/libexec/pdfcraft", self.real) + # Inside the bundle XDG_DATA_HOME is the nightly app's own sandbox folder. + sandbox = self.home / ".var/app/ai.storyteller.pdfcraft.nightly/data" + self.assert_starts_the_profile(generated, {"XDG_DATA_HOME": str(sandbox)}) + self.assert_starts_the_profile(generated, fallback=(".var", "app", "ai.storyteller.pdfcraft.nightly", "data")) + + +if __name__ == "__main__": + unittest.main() diff --git a/packaging/nightly-release-tests.py b/packaging/nightly-release-tests.py new file mode 100755 index 0000000000..dd26b6a681 --- /dev/null +++ b/packaging/nightly-release-tests.py @@ -0,0 +1,800 @@ +#!/usr/bin/env python3 +"""Local contract tests for PdfCraft's nightly producer, signer, and policy.""" +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" + +# The dedicated signer branch the installed policy names and the signer guard requires. +SIGNER_BRANCH = "nightly-signer" + +NIGHTLY_PLATFORMS = ("windows-x86_64", "linux-x86_64", "macos-aarch64") +# The pinned shared registry enables Windows, Linux and macOS for PdfCraft. +SIGNER_SECRETS = { + "AZURE_CERT_PROFILE", "AZURE_CLIENT_ID", "AZURE_CLIENT_SECRET", "AZURE_SIGNING_ACCOUNT", + "AZURE_SIGNING_ENDPOINT", "AZURE_TENANT_ID", "LINUX_SIGNING_KEY", "APPLE_CERTIFICATE", + "APPLE_CERTIFICATE_PASSWORD", "APPLE_ID", "APPLE_PASSWORD", "APPLE_TEAM_ID", "KEYCHAIN_PASSWORD", +} +# Each platform's one trust field in policy v3, and the public stable identity it must name. +NIGHTLY_TRUST = { + "windows-x86_64": ("publisher_subject", + "CN=Learning Machines Inc, O=Learning Machines Inc, L=Atlanta, S=Georgia, C=US"), + "linux-x86_64": ("fingerprint", "2B76741B414AAD6CD33E631213A005C0B9D7C3ED"), + "macos-aarch64": ("apple_team_id", "DJ6XS33FX8"), +} + +# Mirrors the storytold release-managers team (id 19837241) minus echelon-robot. +# Update by PR, in the caller and the policy, when the team changes. +RELEASE_MANAGERS = ["bflatastic", "dylanmtaylor", "echelon", "FredApps", "skylartaylor"] + + +def assert_nightly_serialization(source): + """Fail closed unless this app's plain root concurrency block retains its contract.""" + lines = source.splitlines() + roots = [index for index, line in enumerate(lines) if line.startswith("concurrency:")] + if len(roots) != 1 or lines[roots[0]] != "concurrency:": + raise ValueError("one plain root concurrency block is required") + values = {} + for line in lines[roots[0] + 1:]: + if not line.strip() or line.lstrip().startswith("#"): + continue + if not line[0].isspace(): + break + row = re.fullmatch(r" (group|cancel-in-progress): ([^#]+?)(?: +#.*)?", line) + if row is None or row[1] in values: + raise ValueError("malformed or duplicate nightly concurrency entry") + values[row[1]] = row[2].rstrip() + if values != {"group": "pdfcraft-nightly-release", "cancel-in-progress": "false"}: + raise ValueError("nightly serialization must use its stable group and no cancellation") + + +def caller_entries(lines, indent): + """Split the callers' plain YAML block entries; refuse other forms at checked levels.""" + entries = {} + children = None + for line in lines: + if children is not None and line.startswith(" " * (indent + 1)): + children.append(line) + continue + row = re.fullmatch(r" " * indent + r"([A-Za-z0-9_-]+):(?: (.*))?", line) + if row is None or row[1] in entries: + raise ValueError("malformed or duplicate caller mapping entry") + children = [] + entries[row[1]] = row[2], children + return entries + + +def assert_caller_secrets(source, job_name, names): + """Check the actual caller's root, job and secret blocks without a YAML dependency.""" + lines = [line for line in source.splitlines() if line.strip() and not line.lstrip().startswith("#")] + root = caller_entries(lines, 0) + job_marker, job_lines = root.pop("jobs", (None, [])) + jobs = caller_entries(job_lines, 2) + if job_marker is not None or set(jobs) != {job_name} or jobs[job_name][0] is not None: + raise ValueError("the caller must have one plain job block") + job = caller_entries(jobs[job_name][1], 4) + if "environment" in job or "environment" in root or "secrets" in root: + raise ValueError("only the native callee may bind the environment") + if names: + if "secrets" not in job: + raise ValueError("signer requires an explicit target-specific secret map") + mode, secret_lines = job.pop("secrets") + expected = {name: ("${{ secrets." + name + " }}", []) for name in names} + if mode is not None or caller_entries(secret_lines, 6) != expected: + raise ValueError("signer must forward exactly the reviewed same-name secret references") + elif "secrets" in job: + raise ValueError("unsigned caller must not pass secrets") + for value, children in (*root.values(), *job.values()): + outside_map = "\n".join([value or "", *children]) + # Scan all remaining text: quoted braces can appear before a secret reference. + if re.search(r"(?im)^\s*environment:|\bsecrets\b", outside_map): + raise ValueError("secret bindings belong only in the signer map") + + +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: (\S+)$", + (ROOT / ".github/workflows" / name).read_text())[0] + + +class TrustedSourcePreparation(unittest.TestCase): + def test_one_producer_and_one_signer_job_carry_every_platform(self): + for name, job in (("nightly.yml", "unsigned"), ("nightly-sign.yml", "release")): + jobs = (ROOT / ".github/workflows" / name).read_text().split("\njobs:\n", 1)[1] + with self.subTest(workflow=name): + self.assertEqual(re.findall(r"(?m)^ ([^\s#][^:]*):", jobs), [job], + "a platform is a list entry, not a separately activatable job") + signer = (ROOT / ".github/workflows/nightly-sign.yml").read_text() + self.assertNotRegex(signer, r"(?m)^\s*platforms?:", "the release policy, not the caller, admits platforms") + + def test_malformed_or_narrowed_platform_lists_are_rejected(self): + source = (ROOT / ".github/workflows/nightly.yml").read_text() + current = "platforms: '[\"windows-x86_64\",\"linux-x86_64\",\"macos-aarch64\"]'" + self.assertIn(current, source) + for new in ("platforms: '[\"linux-x86_64\"]'", + "platforms: '[\"linux-x86_64\",\"macos-aarch64\"]'", + "platforms: '[\"windows-x86_64\",\"linux-x86_64\",\"linux-x86_64\"]'", + "platforms: '[\"windows-x86_64\",\"macos-x86_64\"]'", + "platforms: '[\"windows-x86_64\",\"linux-arm64\"]'", + "platforms: '[\"windows-x86_64\", \"linux-x86_64\"]'", + "platforms: [\"windows-x86_64\",\"linux-x86_64\"]", + "platforms: ${{ vars.NIGHTLY_PLATFORMS }}", + "platforms: '{\"windows-x86_64\":1}'", + current + "\n " + current): + with self.subTest(change=new), self.assertRaises(ValueError): + producer_platforms(source.replace(current, new)) + with self.assertRaises(ValueError): + producer_platforms(source.replace(" " + current + "\n", "")) + + def test_continuation_lines_of_any_scalar_form_reach_the_guard_checks(self): + for name, workflow in (("nightly.yml", "nightly.yml"), ("nightly-sign.yml", "nightly-sign.yml")): + source = (ROOT / ".github/workflows" / workflow).read_text() + expected = NightlyEnabledCallers.GUARDS[name] + guard = re.search(r"(?m)^ if: >-\n(?: [^\n]*\n)+", source)[0] + for replacement in (guard + " || true\n", " if: " + expected + "\n || true\n"): + jobs = source.replace(guard, replacement).split("\njobs:\n", 1)[1] + with self.subTest(workflow=name, replacement=replacement[-30:]): + (indicator, expression), = job_conditions(jobs) + self.assertFalse(indicator == ">-" and " ".join(expression.split()) == expected) + + def test_no_nightly_schedule_is_registered(self): + for name, event in (("nightly.yml", "workflow_dispatch"), + ("nightly-sign.yml", "workflow_dispatch")): + source = (ROOT / ".github/workflows" / name).read_text() + events = source.split("\non:\n", 1)[1].split("\npermissions:", 1)[0] + triggers = [line for line in events.splitlines() if line.startswith(" ") + and not line.startswith(" ") and line.strip() and not line.lstrip().startswith("#")] + with self.subTest(workflow=name): + self.assertEqual(triggers, [f" {event}:"], "schedule/activation needs explicit review") + + def test_signer_serialization_contract_is_enforced(self): + assert_nightly_serialization((ROOT / ".github/workflows/nightly-sign.yml").read_text()) + + def test_weakened_or_malformed_serialization_is_rejected(self): + source = (ROOT / ".github/workflows/nightly-sign.yml").read_text() + for old, new in ( + ("cancel-in-progress: false", "cancel-in-progress: true"), + ("cancel-in-progress: false", "cancel-in-progress: ${{ github.event_name == 'push' }}"), + ("cancel-in-progress: false\n", ""), + ("cancel-in-progress: false", "cancel-in-progress: false\n queue: max"), + ("group: pdfcraft-nightly-release", "group: ${{ github.run_id }}"), + ("group: pdfcraft-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:#]*:") + + def test_signer_forwards_exactly_the_reviewed_secret_names(self): + signer = (ROOT / ".github/workflows/nightly-sign.yml").read_text() + assert_caller_secrets(signer, "release", SIGNER_SECRETS) + + def test_signer_refuses_missing_extra_alias_duplicate_or_inherited_secrets(self): + signer = (ROOT / ".github/workflows/nightly-sign.yml").read_text() + header = " secrets:\n" + linux = " LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }}\n" + self.assertIn(linux, signer) + mutations = { + "missing name": signer.replace(linux, ""), + "extra name": signer + " EXTRA: ${{ secrets.EXTRA }}\n", + "renamed source": signer.replace(linux, linux.replace("secrets.LINUX_SIGNING_KEY", "secrets.APPLE_ID")), + "duplicate name": signer.replace(linux, linux + linux), + "duplicate map": signer + header + linux, + "quoted duplicate map": signer + ' "secrets": inherit\n', + "inherit": signer.split(header)[0] + " secrets: inherit\n", + "yaml alias": signer.replace(linux, " LINUX_SIGNING_KEY: *other\n"), + "yaml merge": signer + " <<: *other\n", + "environment": signer + " environment: release\n", + "secret outside map": signer.replace("${{ inputs.producer_run_id }}", "${{ secrets.APPLE_ID }}"), + } + for change, source in mutations.items(): + with self.subTest(change=change), self.assertRaises(ValueError): + assert_caller_secrets(source, "release", SIGNER_SECRETS) + + def test_unsigned_caller_has_no_secrets(self): + producer = (ROOT / ".github/workflows/nightly.yml").read_text() + assert_caller_secrets(producer, "unsigned", set()) + for suffix in (" secrets: {}\n", " secrets: inherit\n", + " secrets:\n EXTRA: ${{ secrets.EXTRA }}\n", + " extra: ${{ secrets['EXTRA'] }}\n", " secrets: inherit\n"): + with self.subTest(suffix=suffix), self.assertRaises(ValueError): + assert_caller_secrets(producer + suffix, "unsigned", set()) + + def test_unsigned_caller_refuses_secret_after_format_brace(self): + producer = (ROOT / ".github/workflows/nightly.yml").read_text() + # This inert fixture is never dispatched; the brace is part of the format string. + env = "env:\n EXAMPLE: ${{ format('value {0}', secrets.EXAMPLE_ONLY) }}\n\n" + source = producer.replace("jobs:\n", env + "jobs:\n", 1) + with self.assertRaisesRegex(ValueError, "secret bindings belong only in the signer map"): + assert_caller_secrets(source, "unsigned", set()) + + +class NightlyTrustAnchors(unittest.TestCase): + """The public stable identities each platform's signed nightly must carry.""" + + 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.assertEqual(pins.pop(), "main", "pin storytold/craft-common-actions to @main") + + +class NightlyEnabledCallers(unittest.TestCase): + """Producer and signer run only in their exact context, for the reviewed manual actor.""" + + GUARDS = { + "nightly.yml": "github.repository == 'storytold/pdfcraft' && github.ref == 'refs/heads/main' && " + "github.ref_type == 'branch' && (github.event_name == 'schedule' || " + "github.event_name == 'workflow_dispatch')", + "nightly-sign.yml": "github.repository == 'storytold/pdfcraft' && github.event_name == 'workflow_dispatch' && " + "github.ref == 'refs/heads/" + SIGNER_BRANCH + "' && github.ref_type == 'branch'", + } + + def test_enabled_jobs_keep_exact_context_guards(self): + for name, expected in self.GUARDS.items(): + jobs = (ROOT / ".github/workflows" / name).read_text().split("\njobs:\n", 1)[1] + guards = job_conditions(jobs) + with self.subTest(workflow=name): + self.assertEqual(len(guards), 1) + indicator, expression = guards[0] + self.assertEqual(indicator, ">-") + self.assertEqual(" ".join(expression.split()), expected, "guards may only change with review") + + def test_manual_actors_are_the_release_managers_in_caller_and_policy(self): + source = (ROOT / ".github/workflows/nightly.yml").read_text() + policy = json.loads(INSTALLED_POLICY.read_text()) + self.assertEqual(reviewed_manual_actors(source, policy), RELEASE_MANAGERS) + self.assertEqual(policy["automatic_signer_actors"], [], "no automatic signer without a schedule") + + def test_an_actor_outside_the_release_managers_is_refused(self): + source = (ROOT / ".github/workflows/nightly.yml").read_text() + policy = json.loads(INSTALLED_POLICY.read_text()) + caller = json.dumps(RELEASE_MANAGERS, separators=(",", ":")) + widened = sorted(RELEASE_MANAGERS + ["echelon-robot"], key=str.lower) + for change in ("caller", "policy", "both", "order", "case"): + mutated_source, mutated_policy = source, copy.deepcopy(policy) + if change in ("caller", "both"): + mutated_source = source.replace(caller, json.dumps(widened, separators=(",", ":"))) + if change in ("policy", "both"): + mutated_policy["manual_actors"] = widened + if change == "order": + mutated_policy["manual_actors"] = list(reversed(RELEASE_MANAGERS)) + if change == "case": + mutated_policy["manual_actors"] = [login.lower() for login in RELEASE_MANAGERS] + with self.subTest(change=change), self.assertRaises(ValueError): + reviewed_manual_actors(mutated_source, mutated_policy) + + +def push_block(source): + """The whole `push:` mapping, blank lines and nested keys included. + + A blank line does not end a YAML mapping, so the block is delimited by indentation rather than + by contiguous non-empty lines; a path filter after a blank line stays visible to the check. + """ + lines = source.splitlines() + for index, line in enumerate(lines): + if re.fullmatch(r" push:.*", line): + block = [] + for follow in lines[index + 1:]: + if follow.strip() and not follow.startswith(" "): + break + block.append(follow) + return "\n".join(block) + return None + + +class NightlyInstalledPolicy(unittest.TestCase): + """The installed v3 policy matches the callers, the repository and its documented sources.""" + + def setUp(self): + self.assertFalse(INSTALLED_POLICY.is_symlink()) + self.policy = json.loads(INSTALLED_POLICY.read_text()) + + def test_exact_v3_fields_and_repository_identity(self): + expected = {"schema", "repository", "repository_id", "producer_workflow_id", + "producer_workflow_path", "producer_tooling_revision", "producer_workflow_ref", + "signer_workflow_path", "signer_tooling_revision", "release_branch", "manual_actors", + "automatic_signer_actors", "max_age_seconds", "candidate_policy", + "max_artifact_bytes", "platforms"} + self.assertEqual(set(self.policy), expected) + self.assertEqual(self.policy["schema"], "craft-nightly-release-policy/v3") + self.assertEqual(self.policy["repository"], "storytold/pdfcraft") + self.assertEqual(self.policy["release_branch"], SIGNER_BRANCH, "the signer runs on its dedicated branch") + # Both read from the GitHub API (the repository and nightly.yml's registration on main). + self.assertIs(type(self.policy["repository_id"]), int) + self.assertGreater(self.policy["repository_id"], 0) + # producer_workflow_id is null until nightly.yml lands on main, then a positive int. + producer_id = self.policy["producer_workflow_id"] + if producer_id is not None: + self.assertIs(type(producer_id), int) + self.assertGreater(producer_id, 0) + self.assertNotEqual(producer_id, + self.policy["candidate_policy"]["required_workflows"][0]["workflow_id"], + "the producer is not its own quality workflow") + + def test_paths_and_tooling_match_the_callers(self): + pin = caller_pin("nightly.yml") + self.assertEqual(caller_pin("nightly-sign.yml"), pin) + self.assertEqual(self.policy["producer_workflow_path"], ".github/workflows/nightly.yml") + self.assertEqual(self.policy["signer_workflow_path"], ".github/workflows/nightly-sign.yml") + self.assertEqual(self.policy["producer_tooling_revision"], pin) + self.assertEqual(self.policy["signer_tooling_revision"], pin) + self.assertEqual(self.policy["producer_workflow_ref"], + "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@" + pin) + + def test_platforms_equal_the_producer(self): + built = producer_platforms((ROOT / ".github/workflows/nightly.yml").read_text()) + self.assertEqual(built, list(NIGHTLY_PLATFORMS)) + self.assertEqual(set(self.policy["platforms"]), set(built)) + + def test_bounds(self): + self.assertIs(type(self.policy["max_age_seconds"]), int) + self.assertTrue(0 < self.policy["max_age_seconds"] <= 604800) + self.assertIs(type(self.policy["max_artifact_bytes"]), int) + self.assertTrue(0 < self.policy["max_artifact_bytes"] <= 16 * 1024 ** 3) + + def test_candidate_workflows_run_on_every_main_push(self): + candidate = self.policy["candidate_policy"] + self.assertEqual(set(candidate), {"schema", "epoch", "repository", "branch", "required_workflows", "sonar"}) + self.assertEqual(candidate["schema"], "craft-nightly-candidate-policy/v3") + self.assertEqual((candidate["repository"], candidate["branch"]), ("storytold/pdfcraft", "main")) + self.assertTrue(isinstance(candidate["epoch"], str) and 0 < len(candidate["epoch"]) <= 128) + rows = candidate["required_workflows"] + self.assertTrue(rows) + for row in rows: + with self.subTest(workflow=row["workflow_path"]): + self.assertEqual(set(row), {"workflow_id", "workflow_path", "jobs"}) + self.assertIs(type(row["workflow_id"]), int) + self.assertNotEqual(row["workflow_path"], self.policy["producer_workflow_path"]) + source = (ROOT / row["workflow_path"]).read_text() + push = push_block(source) + self.assertIsNotNone(push, "a required workflow must run on main pushes") + self.assertIn("branches: [main]", push) + self.assertNotRegex(push, r"(?m)^\s+paths(?:-ignore)?:", "a path filter would leave candidates without a run") + names = [job["name"] for job in row["jobs"]] + self.assertEqual(len(names), len(set(names))) + for job in row["jobs"]: + self.assertEqual(set(job), {"name", "app_id", "applicability"}) + self.assertEqual((job["app_id"], job["applicability"]), (15368, "required")) + + def test_a_path_filter_after_a_blank_line_is_still_rejected(self): + workflow = "on:\n push:\n branches: [main]\n\n paths: ['src/**']\n workflow_dispatch: {}\n" + block = push_block(workflow) + self.assertIsNotNone(block) + self.assertIn("branches: [main]", block) + self.assertRegex(block, r"(?m)^\s+paths(?:-ignore)?:") + for ignored in ("paths: ['src/**']", "paths-ignore: ['docs/**']"): + with self.subTest(ignored=ignored): + variant = workflow.replace(ignored.split(":")[0] + ": ['src/**']", ignored) + self.assertRegex(push_block(variant), r"(?m)^\s+paths(?:-ignore)?:", + "a quoted or unquoted filter must not hide behind a blank line") + + def test_sonar_identity_and_reviewed_scope(self): + sonar = self.policy["candidate_policy"]["sonar"] + properties = dict(line.split("=", 1) for line in (ROOT / "sonar-project.properties").read_text().splitlines() + if line and not line.startswith("#")) + self.assertEqual(sonar["organization"], properties["sonar.organization"]) + self.assertEqual(sonar["project"], properties["sonar.projectKey"]) + self.assertEqual((sonar["app_id"], sonar["check_name"]), (12526, "SonarCloud Code Analysis")) + self.assertEqual(sonar["details_url"], "https://sonarcloud.io/dashboard?id=" + sonar["project"] + "&branch=main") + accepted = {"bugs": "BUG", "vulnerabilities": "VULNERABILITY", "code_smells": "CODE_SMELL", + "security_rating": "VULNERABILITY", "new_security_rating": "VULNERABILITY"} + self.assertEqual({accepted[c["metric"]] for c in sonar["accepted_conditions"]}, set(sonar["issue_types"])) + metrics = [c["metric"] for c in sonar["accepted_conditions"] + sonar["required_conditions"]] + self.assertEqual(len(metrics), len(set(metrics))) + keys = [item["key"] for item in sonar["debt"]] + self.assertEqual(len(keys), len(set(keys))) + for item in sonar["debt"]: + with self.subTest(issue=item["key"]): + self.assertEqual(set(item), {"key", "rule", "component", "type", "severity", "hash"}) + self.assertTrue(item["component"].startswith(sonar["project"] + ":")) + self.assertIn(item["type"], sonar["issue_types"]) + self.assertRegex(item["hash"], r"^[0-9a-f]{32}$") + + def test_sonar_policy_keeps_the_shared_candidate_contract(self): + """The Sonar shape craft-common-actions' candidate contract() admits, refused here first. + + An empty issue scope, an accepted condition outside the reviewed issue types, a metric in both + lists, a missing live gate condition or a widened security bound is refused at admission, so + this suite must catch it before a nightly run can. `debt` stays empty, so any unresolved + vulnerability on main is still refused; accepting the new-code rating only records the + reviewed A threshold instead of demanding a clean rating the live gate does not. + """ + sonar = self.policy["candidate_policy"]["sonar"] + accepted = {"bugs": "BUG", "vulnerabilities": "VULNERABILITY", "code_smells": "CODE_SMELL", + "security_rating": "VULNERABILITY", "new_security_rating": "VULNERABILITY"} + gate = {"new_reliability_rating", "new_security_rating", "new_maintainability_rating", + "new_coverage", "new_duplicated_lines_density", "new_security_hotspots_reviewed"} + self.assertTrue(sonar["issue_types"], "an empty issue scope is refused as unreviewed") + self.assertEqual(len(sonar["issue_types"]), len(set(sonar["issue_types"]))) + metrics = {} + for field in ("accepted_conditions", "required_conditions"): + for condition in sonar[field]: + with self.subTest(field=field, metric=condition.get("metric")): + expected = {"metric", "comparator", "error_threshold"} + if field == "accepted_conditions": + expected.add("maximum") + self.assertEqual(set(condition), expected) + self.assertNotIn(condition["metric"], metrics, "one condition per gate metric") + metrics[condition["metric"]] = condition + self.assertIn(condition["comparator"], ("GT", "LT")) + self.assertRegex(condition["error_threshold"], r"^(?:0|[1-9][0-9]*)(?:\.[0-9]+)?$") + if field != "accepted_conditions": + continue + self.assertIn(condition["metric"], accepted, "an accepted metric outside the reviewed map") + self.assertIn(accepted[condition["metric"]], sonar["issue_types"], + "an accepted failure must lie inside the reviewed issue scope") + self.assertEqual(condition["comparator"], "GT") + self.assertRegex(condition["maximum"], r"^(?:0|[1-9][0-9]*)(?:\.[0-9]+)?$") + maximum = float(condition["maximum"]) + if condition["metric"] in ("security_rating", "new_security_rating"): + self.assertEqual(int(maximum), maximum, "the A..E bound is a whole rating") + self.assertTrue(1 <= maximum <= 5, "the security bound stays A..E") + self.assertEqual(condition["error_threshold"], "1", "the reviewed A threshold stays") + else: + self.assertLessEqual(maximum, len(sonar["debt"]), "accepted failures exceed the reviewed debt") + self.assertEqual({accepted[c["metric"]] for c in sonar["accepted_conditions"]}, set(sonar["issue_types"]), + "accepted conditions and reviewed issue types must cover the same scope") + self.assertEqual(set(metrics), gate, "every live gate condition stays gated exactly once") + + +SHARED = "storytold/craft-common-actions/.github/workflows/" +# App workflows reviewed to call the shared stable release.yml. That callee must carry the +# stable-only environment guard (dry runs and non-release refs bind no environment); the +# nightly-signer settings scan checks the resolved callee before creating or advancing the branch. +REVIEWED_STABLE_RELEASE_CALLERS = {"release.yml"} + + +def app_workflows(): + return {path.name: path.read_text() for path in sorted((ROOT / ".github/workflows").glob("*.y*ml"))} + + +WORKFLOW_KEY = re.compile(r'''("(?:[^"\\]|\\.)*"|'(?:[^']|'')*'|[^\s'"#{}\[\],:&*!|>%@`?-][^:#,{}]*?|-[^\s:#][^:#,{}]*?)\s*:(?:\s+(.*))?$''') + + +def _workflow_key(text): + if text.startswith('"'): + return None if "\\" in text else text[1:-1] + if text.startswith("'"): + return text[1:-1].replace("''", "'") + return text + + +def _workflow_value(text): + """A one-line scalar value without its comment and quotes; None when escaped or unterminated.""" + text = text.strip() + if text.startswith('"'): + quoted = re.match(r'"((?:[^"\\]|\\.)*)"\s*(?:#.*)?$', text) + return None if quoted is None or "\\" in quoted.group(1) else quoted.group(1) + if text.startswith("'"): + quoted = re.match(r"'((?:[^']|'')*)'\s*(?:#.*)?$", text) + return None if quoted is None else quoted.group(1).replace("''", "'") + return re.split(r"\s+#", text, maxsplit=1)[0].strip() + + +def _strip_comment(text): + """(text without its comment, unterminated) using a quote-aware scan. + + As in YAML, a quote opens a quoted scalar only where a scalar starts (line start or after + `:`, `-`, `,`, `{` or `[`), and a `#` starts a comment only outside quotes, at the start or + after whitespace. + """ + quote, index = None, 0 + while index < len(text): + char = text[index] + if quote == '"': + if char == "\\": + index += 2 + continue + if char == '"': + quote = None + elif quote == "'": + if char == "'": + if text[index + 1:index + 2] == "'": + index += 2 + continue + quote = None + elif char in "\"'" and text[:index].rstrip()[-1:] in ("", ":", "-", ",", "{", "["): + quote = char + elif char == "#" and (index == 0 or text[index - 1] in " \t"): + return text[:index].rstrip(), False + index += 1 + return text.rstrip(), quote is not None + + +FLOW_QUOTED = re.compile(r"\"(?:[^\"\\]|\\.)*\"|'(?:[^']|'')*'") +FLOW_FORBIDDEN_KEYS = {"environment", "uses"} + + +def workflow_entries(source): + """Every mapping entry in a workflow, plus the YAML forms this reader refuses. + + A narrow reader, not a YAML parser (none ships with the runner's Python). Each entry is + (line, key, value, multiline): plain, single- and double-quoted keys and one-line values in + block and simple one-line flow mappings. Block scalar bodies are skipped, and an entry whose + value is a block scalar or continues on the next lines is marked multiline. It refuses whatever + could hide a key from it: escaped double-quoted keys, explicit `?` keys, merge keys, anchors, + aliases, tags, tab indentation and nested or multi-line flow. + """ + lines = source.splitlines() + entries, refused, block = [], [], None + + def continues(index, indent): + for follow in lines[index + 1:]: + stripped = follow.strip() + if not stripped or stripped.startswith("#"): + continue + deeper = len(follow) - len(follow.lstrip(" ")) > indent + return deeper and not stripped.startswith("- ") and WORKFLOW_KEY.match(stripped) is None + return False + + for index, raw in enumerate(lines): + number = index + 1 + stripped = raw.strip() + indent = len(raw) - len(raw.lstrip(" ")) + if block is not None: + if not stripped or indent > block: + continue + block = None + if not stripped or stripped.startswith("#"): + continue + if "\t" in raw[:indent + 1]: + refused.append(f"line {number}: tab indentation"); continue + body, unterminated = _strip_comment(stripped) + if unterminated: + refused.append(f"line {number}: unterminated or multi-line quoted scalar"); continue + if not body: + continue + while body.startswith("- "): + body = body[2:].lstrip() + if body == "?" or body.startswith("? "): + refused.append(f"line {number}: explicit key"); continue + match = WORKFLOW_KEY.match(body) + value = body + if match is not None: + key, value = _workflow_key(match.group(1)), match.group(2) or "" + if key is None: + refused.append(f"line {number}: escaped double-quoted key"); continue + if key == "<<": + refused.append(f"line {number}: merge key"); continue + plain = re.sub(r"\$\{\{.*?\}\}", "", value).strip() + bare = re.sub(r"\"(?:[^\"\\]|\\.)*\"|'(?:[^']|'')*'", "''", plain) + if re.match(r"[&*!]", plain): + refused.append(f"line {number}: anchor, alias or tag") + is_block = re.fullmatch(r"[|>][0-9+-]*", plain) is not None + if match is not None: + entries.append((number, key, _workflow_value(value), + is_block or ((value == "" or not is_block) and continues(index, indent)))) + if "{" in bare and bare != "{}": + masked = re.fullmatch(r"\{([^{}\[\]]*)\}", FLOW_QUOTED.sub("''", value.strip())) + flow = re.fullmatch(r"\{([^{}\[\]]*)\}", value.strip()) + if any(set(scalar[1:-1]) & set("#{}[],") for scalar in FLOW_QUOTED.findall(value)): + refused.append(f"line {number}: flow mapping quoted scalar with # or flow punctuation") + elif masked is None or flow is None: + refused.append(f"line {number}: nested or multi-line flow mapping") + else: + # The masked text only proves the shape: a quoted key ("uses", 'environment') keeps + # its identity, so the entries are read from the original mapping text, never ''. + for item in flow.group(1).split(","): + entry = WORKFLOW_KEY.match(item.strip()) + key = _workflow_key(entry.group(1)) if entry else None + if key is None: + refused.append(f"line {number}: unreadable flow mapping entry") + elif key in FLOW_FORBIDDEN_KEYS: + refused.append(f"line {number}: {key} in a flow mapping (must be block style)") + else: + entries.append((number, key, _workflow_value(entry.group(2) or ""), False)) + if match is not None and is_block: + block = indent + return entries, refused + + +def workflow_keys(source): + """(line, key) for every mapping entry, plus the refused YAML forms.""" + entries, refused = workflow_entries(source) + return [(number, key) for number, key, _, _ in entries], refused + + +SHARED_CALLEE = re.compile(r"storytold/craft-common-actions/\.github/workflows/([\w.-]+\.ya?ml)@(\S+)", re.IGNORECASE) +INSPECTED_KEYS = {"environment", "uses"} + + +def trust_closure_problems(workflows): + """The nightly-signer trust-closure scan over app workflow sources; empty when the tree is safe. + + Every key it inspects comes from workflow_entries(), never a regex over the raw text. + """ + problems, stable_callers, signer_calls = [], set(), 0 + for name, source in workflows.items(): + entries, refused = workflow_entries(source) + problems.extend(name + " uses YAML the scan cannot read (" + reason + ")" for reason in refused) + for number, key, value, multiline in entries: + if key not in INSPECTED_KEYS: + continue + if key == "environment": + problems.append(f"{name} binds an environment directly (line {number})") + continue + if value is None or multiline: + problems.append(f"{name} has a uses value the scan cannot read (line {number})") + continue + callee = SHARED_CALLEE.fullmatch(value) + if callee is None: + if re.search(r"craft-common-actions", value, re.IGNORECASE) and re.search(r"workflows/(nightly-)?release\.ya?ml", value, re.IGNORECASE): + problems.append(f"{name} has an unrecognised shared release caller (line {number})") + continue + workflow, ref = callee.group(1), callee.group(2) + if workflow.lower() in ("nightly-release.yml", "nightly-release.yaml"): + if name == "nightly-sign.yml": + signer_calls += 1 + if name != "nightly-sign.yml" or ref != "main": + problems.append(name + " calls nightly-release.yml@" + ref) + if workflow.lower() in ("release.yml", "release.yaml"): + stable_callers.add(name) + if ref != "main" and not re.fullmatch(r"[0-9a-f]{40}", ref): + problems.append(name + " calls release.yml@" + ref + "; use @main or a reviewed full SHA") + if stable_callers != REVIEWED_STABLE_RELEASE_CALLERS: + problems.append("shared release.yml callers are " + ", ".join(sorted(stable_callers))) + if signer_calls != 1: + problems.append("nightly-sign.yml must call nightly-release.yml exactly once") + return problems + + +class NightlySignerBranchTrustClosure(unittest.TestCase): + """On refs/heads/nightly-signer, only the pinned signer caller may reach an environment.""" + + def test_trust_closure_scan_passes_on_this_tree(self): + self.assertEqual(trust_closure_problems(app_workflows()), []) + + def test_trust_closure_scan_refuses_each_route_into_an_environment(self): + tree = app_workflows() + bad = { + "a workflow binds an environment": {**tree, "extra.yml": "jobs:\n x:\n runs-on: ubuntu-latest\n environment: release\n"}, + "a double-quoted environment key": {**tree, "extra.yml": 'jobs:\n x:\n runs-on: ubuntu-latest\n "environment": release\n'}, + "a single-quoted environment key": {**tree, "extra.yml": "jobs:\n x:\n runs-on: ubuntu-latest\n 'environment' : release\n"}, + "an environment mapping": {**tree, "extra.yml": "jobs:\n x:\n runs-on: ubuntu-latest\n environment:\n name: release\n"}, + "an environment in a flow mapping": {**tree, "extra.yml": "jobs:\n x: {runs-on: ubuntu-latest, environment: release}\n"}, + "an escaped key": {**tree, "extra.yml": 'jobs:\n x:\n runs-on: ubuntu-latest\n "environ\\u006dent": release\n'}, + "a merge key": {**tree, "extra.yml": "base: &b\n runs-on: ubuntu-latest\njobs:\n x:\n <<: *b\n"}, + "an explicit key": {**tree, "extra.yml": "jobs:\n x:\n ? environment\n : release\n"}, + "a nested flow mapping": {**tree, "extra.yml": "jobs:\n x: {steps: [{run: a}]}\n"}, + "a double-quoted uses key copying the signer": {**tree, "extra.yml": 'jobs:\n x:\n "uses": ' + SHARED + "nightly-release.yml@" + "a" * 40 + "\n"}, + "a single-quoted uses key": {**tree, "extra.yml": "jobs:\n x:\n 'uses': " + SHARED + "nightly-release.yml@" + "a" * 40 + "\n"}, + "a quoted uses value": {**tree, "extra.yml": 'jobs:\n x:\n uses: "' + SHARED + "nightly-release.yml@" + "a" * 40 + '"\n'}, + "uses in a flow mapping": {**tree, "extra.yml": "jobs:\n x: {uses: " + SHARED + "nightly-release.yml@" + "a" * 40 + "}\n"}, + "a differently cased owner": {**tree, "extra.yml": "jobs:\n x:\n uses: Storytold/Craft-Common-Actions/.github/workflows/nightly-release.yml@" + "a" * 40 + "\n"}, + "a folded uses value": {**tree, "extra.yml": "jobs:\n x:\n uses: >-\n " + SHARED + "nightly-release.yml@" + "a" * 40 + "\n"}, + "a continued uses value": {**tree, "extra.yml": "jobs:\n x:\n uses: " + SHARED + "\n nightly-release.yml@" + "a" * 40 + "\n"}, + "a quoted second signer call": {**tree, "nightly-sign.yml": tree["nightly-sign.yml"] + " again:\n \"uses\": " + SHARED + "nightly-release.yml@" + "a" * 40 + "\n"}, + "a hash inside a quoted flow scalar": {**tree, "extra.yml": 'jobs:\n x: {name: "a} # b", runs-on: ubuntu-latest, environment: release, steps: []}\n'}, + "a single-quoted hash in a flow scalar": {**tree, "extra.yml": "jobs:\n x: {name: 'a # b', runs-on: ubuntu-latest}\n"}, + "a comma inside a quoted flow scalar": {**tree, "extra.yml": 'jobs:\n x: {name: "a, environment: release", runs-on: ubuntu-latest}\n'}, + "a bracket inside a quoted flow scalar": {**tree, "extra.yml": 'jobs:\n x: {name: "[a]", runs-on: ubuntu-latest}\n'}, + "an unterminated quote": {**tree, "extra.yml": 'jobs:\n x:\n name: "a\n b"\n runs-on: ubuntu-latest\n'}, + "environment in any flow mapping": {**tree, "extra.yml": "jobs:\n x:\n runs-on: ubuntu-latest\n with: {environment: release}\n"}, + "a double-quoted environment key in a flow mapping": {**tree, "extra.yml": 'jobs:\n x:\n runs-on: ubuntu-latest\n with: {"environment": release}\n'}, + "a single-quoted environment key in a flow mapping": {**tree, "extra.yml": "jobs:\n x:\n runs-on: ubuntu-latest\n with: {'environment': release}\n"}, + "a double-quoted uses key in a flow mapping": {**tree, "extra.yml": 'jobs:\n x: {"uses": ' + SHARED + "nightly-release.yml@" + "a" * 40 + "}\n"}, + "uses in any flow mapping": {**tree, "extra.yml": "jobs:\n x:\n steps:\n - {uses: actions/checkout@v4}\n"}, + "another caller of the signer": {**tree, "extra.yml": "jobs:\n x:\n uses: " + SHARED + "nightly-release.yml@" + "a" * 40 + "\n"}, + "a signer caller on a non-main branch or tag ref": {**tree, "nightly-sign.yml": tree["nightly-sign.yml"].replace("nightly-release.yml@main", "nightly-release.yml@v1")}, + "a new stable release caller": {**tree, "extra.yml": "jobs:\n x:\n uses: " + SHARED + "release.yml@main\n"}, + "a stable caller on a branch or tag ref": {**tree, "release.yml": tree["release.yml"].replace(SHARED + "release.yml@main", SHARED + "release.yml@v1")}, + } + for label, workflows in bad.items(): + with self.subTest(case=label): + self.assertTrue(trust_closure_problems(workflows)) + + def test_quoted_keys_in_a_flow_mapping_are_read_not_masked(self): + entries, refused = workflow_entries('jobs:\n x: {runs-on: ubuntu-latest, "name": build}\n') + self.assertEqual(refused, []) + self.assertIn((2, "name", "build", False), entries, "a quoted key keeps its identity") + self.assertIn((2, "runs-on", "ubuntu-latest", False), entries) + _, refused = workflow_entries("jobs:\n x: {runs-on: ubuntu-latest, 'environment': release}\n") + self.assertEqual(refused, ["line 2: environment in a flow mapping (must be block style)"]) + + def test_signer_guard_and_policy_name_the_same_branch(self): + app = json.loads(INSTALLED_POLICY.read_text())["repository"].split("/", 1)[1] + sign = (ROOT / ".github/workflows/nightly-sign.yml").read_text() + (_, guard), = job_conditions(sign.split("\njobs:\n", 1)[1]) + self.assertIn("github.ref == 'refs/heads/" + SIGNER_BRANCH + "'", guard) + self.assertNotIn("refs/heads/release", sign, "the signer no longer runs on the stable branch") + self.assertEqual(re.findall(r"(?m)^ app-name: (\S+)$", sign), [app], "the shared signer needs the reviewed registry app") + self.assertEqual(json.loads(INSTALLED_POLICY.read_text())["release_branch"], SIGNER_BRANCH) + + +if __name__ == "__main__": + unittest.main(verbosity=2) diff --git a/packaging/nightly-tests.py b/packaging/nightly-tests.py new file mode 100755 index 0000000000..4d1d569ead --- /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 ( + ("photo_archive_suite", "nightly-archive-tests.py"), + ("photo_launcher_suite", "nightly-launcher-tests.py"), + ("photo_plist_suite", "macos/nightly_plist_tests.py"), + ("photo_release_dispatch_suite", "nightly-release-tests.py"), + ("photo_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 0000000000..792198589e --- /dev/null +++ b/packaging/nightly_paths.py @@ -0,0 +1,139 @@ +"""POSIX packaging I/O rooted at a caller-owned private working directory. + +The build launcher chooses cwd independently of file arguments (Linux uses its +mktemp directory). This is not a sandbox against root or a malicious same-UID +caller, and inode-check/unlink cleanup is not an atomic replacement-race primitive. +""" +import contextlib +import os +from pathlib import Path +import stat + + +def _component(name): + # A descriptor-relative open must name exactly one entry in its directory. + if not name or name in (".", "..") or os.path.basename(name) != name: + raise ValueError("build path components must be single names") + return os.path.basename(name) + + +class OwnedBuildRoot: + def __enter__(self): + self.directory = Path.cwd() + self.fd = os.open(".", os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) + info = os.fstat(self.fd) + if info.st_uid != os.geteuid() or stat.S_IMODE(info.st_mode) & 0o077: + os.close(self.fd) + raise ValueError("packaging cwd must be an owned private build directory") + return self + + def __exit__(self, *_error): + os.close(self.fd) + + def _relative(self, path): + path = Path(path) + try: + relative = path.relative_to(self.directory) if path.is_absolute() else path + except ValueError as error: + raise ValueError("path is outside the owned build directory") from error + if not relative.parts or ".." in relative.parts: + raise ValueError("empty or parent-traversing build path") + # Check an independently selected root, never the supplied filename's parent. + try: + parent = (self.directory / relative).parent.resolve(strict=True) + except OSError as error: + raise ValueError("build path parent must exist") from error + if not parent.is_relative_to(self.directory): + raise ValueError("resolved path escapes the owned build directory") + return relative + + def _checked_parts(self, path): + relative = self._relative(path) + root = os.path.realpath(self.directory) + lexical = os.path.join(root, *relative.parts) + target = os.path.realpath(lexical) + if target == root or os.path.commonpath([root, target]) != root: + raise ValueError("resolved path escapes the owned build directory") + if target != lexical: + raise ValueError("build path must not pass through symlinks or aliases") + return [_component(part) for part in os.path.relpath(target, root).split(os.sep)] + + def _parent(self, path): + parts = self._checked_parts(path) + current = os.dup(self.fd) + try: + for part in parts[:-1]: + next_fd = os.open(_component(part), os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=current) + os.close(current) + current = next_fd + return current, parts[-1] + except OSError as error: + os.close(current) + raise ValueError("build path parents must be non-symlink directories") from error + + @contextlib.contextmanager + def reader(self, path, limit): + parent, name = self._parent(path) + try: + try: + descriptor = os.open(_component(name), os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=parent) + except OSError as error: + raise ValueError("build input must be a regular file without aliases") from error + finally: + os.close(parent) + info = os.fstat(descriptor) + if not stat.S_ISREG(info.st_mode) or info.st_size > limit: + os.close(descriptor) + raise ValueError("build input must be a regular file within its read bound") + with os.fdopen(descriptor, "rb") as stream: + yield stream + + def read_bytes(self, path, limit): + with self.reader(path, limit) as stream: + data = stream.read(limit + 1) + if len(data) > limit: + raise ValueError("build input grew beyond its read bound") + return data + + def children(self, path, limit): + relative = self._relative(path) + parent, name = self._parent(path) + try: + try: + descriptor = os.open(_component(name), os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=parent) + except OSError as error: + raise ValueError("build stage must be a non-symlink directory") from error + finally: + os.close(parent) + try: + entries = [] + with os.scandir(descriptor) as iterator: + for entry in iterator: + if len(entries) >= limit: + raise ValueError("too many build stage members") + entries.append(self.directory / relative / entry.name) + return entries + finally: + os.close(descriptor) + + @contextlib.contextmanager + def create(self, path): + parent, name = self._parent(path) + name = _component(name) + try: + descriptor = os.open(name, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o666, dir_fd=parent) + info = os.fstat(descriptor) + identity = (info.st_dev, info.st_ino) + try: + with os.fdopen(descriptor, "wb") as stream: + yield stream + except BaseException: + try: + current = os.stat(name, dir_fd=parent, follow_symlinks=False) + if (current.st_dev, current.st_ino) == identity: + os.unlink(_component(name), dir_fd=parent) + except FileNotFoundError: + pass + raise + finally: + os.close(parent) diff --git a/packaging/windows/nightly-package-tests.ps1 b/packaging/windows/nightly-package-tests.ps1 new file mode 100644 index 0000000000..b7a00f6090 --- /dev/null +++ b/packaging/windows/nightly-package-tests.ps1 @@ -0,0 +1,95 @@ +param([Parameter(Mandatory=$true)][string] $FixtureRoot) +. (Join-Path $PSScriptRoot 'nightly.ps1') -FunctionsOnly +function Assert([bool] $Value, [string] $Message) { if (-not $Value) { throw $Message } } +$spec = Get-NightlyArchiveSpec '0.23.1-nightly.20261120.17.1.gabcdef012345' 'x64' +Assert ($spec.Archive -eq 'pdfcraft-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 'pdfcraft.exe') 'nightly must not ship the unqualified CLI' +Assert ($spec.AppId -eq 'ai.storyteller.pdfcraft.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 'PdfCraft Nightly' 'PdfCraft 0.23.1-nightly.20261120.17.1.gabcdef012345 (nightly-v1)' '0.23.1-nightly.20261120.17.1.gabcdef012345' +foreach ($pair in @(@('PdfCraft', 'PdfCraft 0.23.1 (nightly-v1)'), @('PdfCraft Nightly', 'PdfCraft 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/pdfcraft/src/main.rs') +) +foreach ($case in $cases) { + $refused = $false + try { Assert-NightlySource $case[1] $case[2] $case[3] $case[4] $case[5] } catch { $refused = $true } + Assert $refused "source identity accepted: $($case[0])" +} +Write-Output 'nightly packaging spec, target/version refusal, source identity and flavor-binding tests passed' + +# Exercise the SAME production notice copier with the real repository layout, then inspect a ZIP. +if (-not $FixtureRoot -or -not [IO.Path]::IsPathRooted($FixtureRoot)) { throw 'supply an owned absolute -FixtureRoot for the notices/ZIP regression' } +$testRoot = Join-Path $FixtureRoot ("nightly-notices-" + [Guid]::NewGuid().ToString('N')) +try { + $repo = Join-Path $testRoot 'app' + $fontRepo = Join-Path $testRoot 'craft-fonts' + $family = Join-Path $fontRepo 'fonts\ExampleFamily' + $stage = Join-Path $testRoot 'stage' + New-Item -ItemType Directory -Force -Path $repo, $family, $stage | Out-Null + $rootNames = @('README.md', 'LICENSE', 'LICENSE-MIT', 'LICENSE-APACHE', 'NOTICE', 'ATTRIBUTION.md') + foreach ($name in $rootNames) { Set-Content -LiteralPath (Join-Path $repo $name) -Value "root-notice-$name" } + Set-Content -LiteralPath (Join-Path $family 'OFL.txt') -Value 'font-notice-example' + Copy-NightlyNotices $repo $fontRepo $stage + foreach ($name in @($rootNames) + @('OFL-ExampleFamily.txt')) { + Assert (Test-Path -LiteralPath (Join-Path $stage $name)) "missing staged notice $name" + } + $zip = Join-Path $testRoot 'notices.zip' + Compress-Archive -Path (Join-Path $stage '*') -DestinationPath $zip + $archive = [IO.Compression.ZipFile]::OpenRead($zip) + try { + $names = @($archive.Entries | ForEach-Object { $_.FullName }) + foreach ($name in @($rootNames) + @('OFL-ExampleFamily.txt')) { Assert ($name -in $names) "missing archived notice $name" } + foreach ($forbidden in @('portable.txt', 'pdfcraft-cli.exe')) { Assert ($forbidden -notin $names) "unexpected payload $forbidden" } + $entry = $archive.GetEntry('OFL-ExampleFamily.txt') + $reader = [IO.StreamReader]::new($entry.Open()) + try { Assert ($reader.ReadToEnd().Contains('font-notice-example')) 'wrong font license bytes in ZIP' } finally { $reader.Dispose() } + } finally { $archive.Dispose() } +} finally { + if (Test-Path -LiteralPath $testRoot) { Remove-Item -LiteralPath $testRoot -Recurse -Force } +} +Write-Output 'nightly mock-repository root and font notices are present in stage and ZIP' + +# The source state comes from git itself: the checked-out commit, then a dirty tree. +$gitRoot = Join-Path $FixtureRoot ("nightly-source-" + [Guid]::NewGuid().ToString('N')) +try { + New-Item -ItemType Directory -Force -Path $gitRoot | Out-Null + git -C $gitRoot init -q; git -C $gitRoot -c user.name=fixture -c user.email=fixture@invalid commit -q --allow-empty -m fixture + if ($LASTEXITCODE -ne 0) { throw 'cannot create the git fixture' } + $head = (git -C $gitRoot rev-parse HEAD).Trim() + $state = Get-NightlySourceState $gitRoot + Assert ($state.Head -ceq $head -and -not $state.Status) 'clean checkout not reported as clean at HEAD' + $version = '0.23.1-nightly.20261120.17.1.g' + $head.Substring(0, 12) + Assert-NightlySource $version $head '2026-11-20' $state.Head $state.Status + Set-Content -LiteralPath (Join-Path $gitRoot 'untracked.txt') -Value 'dirty' + $state = Get-NightlySourceState $gitRoot + $refused = $false + try { Assert-NightlySource $version $head '2026-11-20' $state.Head $state.Status } catch { $refused = $true } + Assert $refused 'a dirty checkout was accepted' +} finally { + if (Test-Path -LiteralPath $gitRoot) { Remove-Item -LiteralPath $gitRoot -Recurse -Force } +} +Write-Output 'nightly source state is read from git and a dirty checkout is refused' diff --git a/packaging/windows/nightly-signing-tests.ps1 b/packaging/windows/nightly-signing-tests.ps1 new file mode 100644 index 0000000000..7375946ba9 --- /dev/null +++ b/packaging/windows/nightly-signing-tests.ps1 @@ -0,0 +1,104 @@ +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' } +# The source preflight runs `git` in the real checkout; this fixture owns its own identity, so the +# stub answers for the fixture commit instead of whatever this working copy happens to be at. +function global:git { + param([Parameter(ValueFromRemainingArguments=$true)][object[]] $Arguments) + $joined = ($Arguments | ForEach-Object { "$_" }) -join ' ' + if ($joined -match 'rev-parse HEAD$') { $global:LASTEXITCODE = 0; return ('a' * 40) } + if ($joined -match 'status --porcelain$') { $global:LASTEXITCODE = 0; return '' } + throw "the fixture must not run git: $joined" +} +function global:Invoke-WebRequest { throw 'fixture must not perform signing downloads' } +$global:SigningFixtureCargoCalls = 0 +# The caller's own values, restored in `finally`: this script may run inside a developer's session. +$savedEnvironment = foreach ($name in ($names + @('PDFCRAFT_VERSION', 'PDFCRAFT_BUILD_SHA', 'PDFCRAFT_BUILD_DATE'))) { + [pscustomobject]@{ Name = $name; Value = [Environment]::GetEnvironmentVariable($name) } +} +if (-not [IO.Path]::IsPathRooted($FixtureRoot)) { throw 'use an owned absolute FixtureRoot' } +$root = Join-Path $FixtureRoot ('signing-policy-' + [Guid]::NewGuid().ToString('N')) +New-Item -ItemType Directory -Path $root | Out-Null +$version = '0.23.1-nightly.20261121.12345.1.gaaaaaaaaaaaa' +$env:PDFCRAFT_VERSION = $version +# The preflight's other two identities: the fixture commit the version names, and its run date. +$env:PDFCRAFT_BUILD_SHA = 'a' * 40 +$env:PDFCRAFT_BUILD_DATE = '2026-11-21' +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 { + # Put back exactly what the caller had (an unset variable is restored as unset), and drop the + # command mocks: a `function global:` binding outlives this script and outranks the real program. + foreach ($entry in $savedEnvironment) { [Environment]::SetEnvironmentVariable($entry.Name, $entry.Value) } + foreach ($mock in @('cargo', 'git', 'Invoke-WebRequest')) { + Remove-Item -LiteralPath "function:global:$mock" -ErrorAction SilentlyContinue + } + Remove-Item -LiteralPath $root -Recurse -Force +} diff --git a/packaging/windows/nightly.ps1 b/packaging/windows/nightly.ps1 new file mode 100644 index 0000000000..7a5fabeb41 --- /dev/null +++ b/packaging/windows/nightly.ps1 @@ -0,0 +1,132 @@ +<# First nightly target only: Windows x86_64 GUI ZIP. No MSI, CLI, portable marker or association registration. #> +param( + [string] $Arch = 'x64', + [string] $Version, + [string] $Target, + [string] $TargetDir, + [string] $Dist, + [switch] $SkipBuild, + [switch] $BuildOnly, + [switch] $FunctionsOnly +) +$ErrorActionPreference = 'Stop' + +function Get-NightlyArchiveSpec([string] $Version, [string] $Arch) { + if ($Arch -ne 'x64') { throw 'nightly-v1 supports only Windows x86_64' } + if (-not $Version -or $Version -cnotmatch '^\d+\.\d+\.\d+-nightly\.\d{8}\.\d+\.\d+\.g[0-9a-f]{12}\z') { throw 'invalid nightly artifact version' } + return @{ + Archive = "pdfcraft-$Version-windows-x86_64-nightly.zip" + UnsignedArchive = "pdfcraft-$Version-windows-x86_64-nightly.unsigned.zip" + Executables = @('pdfcraft.exe') + Channel = 'nightly-v1' + AppId = 'ai.storyteller.pdfcraft.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 (PDFCRAFT_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 (PDFCRAFT_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 'PdfCraft Nightly' -or $VersionOutput -cne "PdfCraft $ExpectedVersion (nightly-v1)") { + throw 'the executable is not the compiled nightly-v1 flavor' + } +} + + +function Copy-NightlyNotices([string] $RepositoryRoot, [string] $FontRepository, [string] $Destination) { + foreach ($name in 'README.md', 'LICENSE', 'LICENSE-MIT', 'LICENSE-APACHE', 'NOTICE', 'ATTRIBUTION.md') { + $source = Join-Path $RepositoryRoot $name + if (Test-Path -LiteralPath $source) { Copy-Item -LiteralPath $source -Destination $Destination } + } + if ($FontRepository) { + $fonts = Join-Path $FontRepository 'fonts' + if (-not (Test-Path -LiteralPath $fonts -PathType Container)) { throw 'CRAFT_FONTS_DIR has no fonts directory for the bundled notices' } + foreach ($family in Get-ChildItem -LiteralPath $fonts -Directory) { + $license = Join-Path $family.FullName 'OFL.txt' + if (Test-Path -LiteralPath $license) { Copy-Item -LiteralPath $license -Destination (Join-Path $Destination "OFL-$($family.Name).txt") } + } + } +} + +if ($FunctionsOnly) { return } +if (-not $env:PDFCRAFT_VERSION -or $Version -cne $env:PDFCRAFT_VERSION) { throw 'nightly-v1 requires explicit PDFCRAFT_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:PDFCRAFT_BUILD_SHA $env:PDFCRAFT_BUILD_DATE $Source.Head $Source.Status +$oldChannel = $env:PDFCRAFT_BUILD_CHANNEL +try { + # `build.rs` reads PDFCRAFT_VERSION (already required above), not a PhotoCraft-style override. + $env:PDFCRAFT_BUILD_CHANNEL = 'nightly-v1' + $env:PDFCRAFT_REQUIRE_WINRES = '1' + $env:CARGO_TARGET_X86_64_PC_WINDOWS_MSVC_RUSTFLAGS = '-C target-feature=+crt-static' + # Into the directory the archive steps read (`$TargetDir`), not Cargo's default. + cargo build --release --locked -p pdfcraft --target $Target --target-dir $TargetDir + if ($LASTEXITCODE -ne 0) { throw "nightly cargo build failed: $LASTEXITCODE" } +} finally { + $env:PDFCRAFT_BUILD_CHANNEL = $oldChannel +} +$Source = Get-NightlySourceState $Root +try { Assert-NightlySource $Version $env:PDFCRAFT_BUILD_SHA $env:PDFCRAFT_BUILD_DATE $Source.Head $Source.Status } +catch { throw "source changed during the build: $_" } +$Exe = Join-Path $TargetDir "$Target\release\pdfcraft.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 'PdfCraft 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 'pdfcraft.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 ('pdfcraft.exe' -notin $Names -or 'pdfcraft-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 e9b9e4432b..36ab474905 100644 --- a/packaging/windows/package.ps1 +++ b/packaging/windows/package.ps1 @@ -25,9 +25,12 @@ param( # -SkipBuild only: the existing binaries were built without CRAFT_FONTS_DIR, so they embed no # craft-fonts faces. Without CRAFT_FONTS_DIR this assertion is required: package.ps1 cannot # otherwise know whether the binaries need the fonts' OFL notices. - [switch] $BuiltWithoutCraftFonts + [switch] $BuiltWithoutCraftFonts, + [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 if ($BuiltWithoutCraftFonts -and -not $SkipBuild) { @@ -69,7 +72,14 @@ if (-not $env:PDFCRAFT_BUILD_DATE) { $env:PDFCRAFT_BUILD_DATE = (Get-Date).ToUni Write-Output "PdfCraft $Version for Windows $Arch ($Target)" +# A nightly build is a separate channel: it delegates to nightly.ps1 before any stable packaging. +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:PDFCRAFT_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' diff --git a/packaging/windows/sign.ps1 b/packaging/windows/sign.ps1 index d56e0e65ea..020e63211a 100644 --- a/packaging/windows/sign.ps1 +++ b/packaging/windows/sign.ps1 @@ -9,17 +9,22 @@ 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). .EXAMPLE - pwsh packaging/windows/sign.ps1 dist/pdfcraft.exe dist/Pdfcraft.msi + pwsh packaging/windows/sign.ps1 dist/pdfcraft.exe dist/PdfCraft.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,29 @@ 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) { + # Signing material must never reach compilation. Prints nothing when the environment is clean. + 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 @@ -56,8 +85,8 @@ if (-not $haveCert -and -not $haveAzure) { $script:SignTool = Find-SignTool $common = @('sign', '/v', '/fd', 'SHA256', '/td', 'SHA256', '/d', 'PdfCraft', '/du', 'https://github.com/storytold/pdfcraft') -$tmp = Join-Path ([IO.Path]::GetTempPath()) "pdfcraft-sign-$([IO.Path]::GetRandomFileName())" -New-Item -ItemType Directory -Path $tmp | Out-Null +$tmp = Join-Path ([IO.Path]::GetTempPath()) "pdfcraft-sign-$PID" +New-Item -ItemType Directory -Force -Path $tmp | Out-Null try { if ($haveCert) { @@ -73,15 +102,8 @@ try { Write-Output "Signing with Azure Trusted Signing ($env:AZURE_SIGNING_ACCOUNT / $env:AZURE_CERT_PROFILE): $($Files -join ', ')" # The dlib authenticates with DefaultAzureCredential, which reads AZURE_TENANT_ID, # AZURE_CLIENT_ID and AZURE_CLIENT_SECRET from the environment. - $trustedSigningVersion = '1.0.95' - $trustedSigningSha256 = '3bfcf1e0a3cb42af1692f0a8ed45c15de070c2de86f28a59b2795d904d8a920f' $pkg = Join-Path $tmp 'trusted-signing.zip' - $uri = "https://api.nuget.org/v3-flatcontainer/microsoft.trusted.signing.client/$trustedSigningVersion/microsoft.trusted.signing.client.$trustedSigningVersion.nupkg" - Invoke-WebRequest -Uri $uri -OutFile $pkg - $actualHash = (Get-FileHash -Path $pkg -Algorithm SHA256).Hash.ToLowerInvariant() - if ($actualHash -ne $trustedSigningSha256) { - throw "Microsoft.Trusted.Signing.Client $trustedSigningVersion checksum mismatch" - } + Invoke-WebRequest -Uri 'https://www.nuget.org/api/v2/package/Microsoft.Trusted.Signing.Client' -OutFile $pkg Expand-Archive -Path $pkg -DestinationPath (Join-Path $tmp 'client') -Force $dlib = Get-ChildItem -Path (Join-Path $tmp 'client') -Recurse -Filter Azure.CodeSigning.Dlib.dll | Where-Object { $_.FullName -match '\\x64\\' } | Select-Object -First 1 @@ -96,6 +118,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 7d0926a248..de94fe00b9 100644 --- a/sonar-project.properties +++ b/sonar-project.properties @@ -1,5 +1,6 @@ sonar.projectKey=storytold_pdfcraft sonar.organization=storytold +sonar.coverage.exclusions=packaging/** # vendor/ holds third-party crates carried with small, marked patches (vendor/README.md). # They are kept close to upstream so each copy can be dropped once upstream releases the