From 05874efd9a591461a5f9f730b657127185b9fb46 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 29 Nov 2026 13:48:48 -0500 Subject: [PATCH 1/4] feat(nightly): wire craft-nightly for direct-launch self-isolation (#2451) * feat(nightly): wire craft-nightly for direct-launch self-isolation * fix(nightly): wrap std::env::var_os in closure for HRTB bound * fix(nightly): answer standalone version probes before profile resolution --- Cargo.lock | 9 + Cargo.toml | 2 + apps/deckcraft/Cargo.toml | 1 + apps/deckcraft/src/app_dirs.rs | 66 +-- apps/deckcraft/src/build_flavor.rs | 74 +-- apps/deckcraft/src/launch_profile.rs | 240 ++------ apps/deckcraft/src/main.rs | 44 +- apps/deckcraft/src/profile_root.rs | 815 ++++++--------------------- 8 files changed, 312 insertions(+), 939 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 14a2dd6a5..a033b57a5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1272,6 +1272,14 @@ dependencies = [ "encoding_rs", ] +[[package]] +name = "craft-nightly" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=1f6c3a21f85ed96f8fd4ddd5a959d4e1edbedb24#1f6c3a21f85ed96f8fd4ddd5a959d4e1edbedb24" +dependencies = [ + "winsafe", +] + [[package]] name = "craft-opc" version = "0.1.0" @@ -1770,6 +1778,7 @@ dependencies = [ "arboard", "chrono", "cpal", + "craft-nightly", "craft-update", "deckcraft-engine", "deckcraft-media", diff --git a/Cargo.toml b/Cargo.toml index 56a167d41..77128e920 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -23,6 +23,8 @@ craft-drawingml = { git = "https://github.com/storytold/craft-libs", rev = "8fa4 craft-pptx = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" } # Shared MCP stdio framing and protocol constants (craft-libs#778). craft-mcp-server = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" } +# Nightly profile isolation, launch protocol, and security fence. +craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "1f6c3a21f85ed96f8fd4ddd5a959d4e1edbedb24", version = "=0.1.0" } # internal deckcraft-geom = { path = "crates/geom" } deckcraft-color = { path = "crates/color" } diff --git a/apps/deckcraft/Cargo.toml b/apps/deckcraft/Cargo.toml index f4afdaf33..f61236749 100644 --- a/apps/deckcraft/Cargo.toml +++ b/apps/deckcraft/Cargo.toml @@ -11,6 +11,7 @@ default-run = "deckcraft" workspace = true [dependencies] +craft-nightly = { workspace = true } deckcraft-engine = { workspace = true } deckcraft-ui-egui = { workspace = true } deckcraft-media = { workspace = true } diff --git a/apps/deckcraft/src/app_dirs.rs b/apps/deckcraft/src/app_dirs.rs index caa250c0e..a97e8ed48 100644 --- a/apps/deckcraft/src/app_dirs.rs +++ b/apps/deckcraft/src/app_dirs.rs @@ -8,29 +8,19 @@ //! `%APPDATA%\DeckCraft`, Linux `$XDG_CONFIG_HOME/deckcraft` or `~/.config/deckcraft`. //! //! DeckCraft has no portable mode and no `DECKCRAFT_CONFIG_DIR` override, so the stable resolution -//! is exactly the one `main.rs` used before the Nightly channel; the fence module -//! ([`crate::profile_root`]) still refuses a `DeckCraftData` folder or a `portable.txt` beside a -//! DeckCraft executable, which a hand-made portable copy could carry. +//! is exactly the one `main.rs` used before the Nightly channel; the `craft-nightly` fence +//! ([`crate::profile_root`]) still refuses a `portable.txt` marker beside a nightly executable. use std::ffi::OsString; -use std::path::{Path, PathBuf}; +use std::path::PathBuf; use std::sync::OnceLock; -/// The portable data folder name a hand-made portable copy could use. No DeckCraft package -/// writes it, but the fence refuses a profile inside one (see [`crate::profile_root`]). -pub const PORTABLE_DATA_DIR: &str = "DeckCraftData"; - /// The marker file of a portable copy, beside its executable. pub const PORTABLE_MARKERS: [&str; 1] = ["portable.txt"]; -/// The portable marker in `dir`, when it is a regular file. -pub fn portable_marker(dir: &Path) -> Option { - PORTABLE_MARKERS.iter().map(|name| dir.join(name)).find(|path| path.is_file()) -} - #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Mode { - /// The profile root chosen by the Launcher (`--launch-profile nightly-v1`). + /// The isolated Nightly profile root (from `--launch-profile nightly-v1` or direct self-isolation). Override, /// The platform convention (stable). Platform, @@ -95,26 +85,6 @@ pub fn user_dictionary() -> Option { user_dictionary_for(current()) } -/// The app's exclusive write probe: a new file created in `dir` and removed again. It never falls -/// back to another directory, so the Nightly validator can refuse a root it cannot write. -pub fn ensure_writable(dir: &Path) -> std::io::Result<()> { - // A probe left behind by an interrupted launch must not make a writable profile look - // unwritable, so each attempt uses a fresh name and a collision tries the next one. - // `create_new` still guarantees a create rather than a truncation. - for attempt in 0..8u32 { - let probe = dir.join(format!(".deckcraft-write-probe-{}-{attempt}", std::process::id())); - match std::fs::OpenOptions::new().write(true).create_new(true).open(&probe) { - Ok(file) => { - drop(file); - return std::fs::remove_file(probe); - } - Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue, - Err(error) => return Err(error), - } - } - Err(std::io::Error::new(std::io::ErrorKind::AlreadyExists, "no free write-probe name in the profile")) -} - #[cfg(test)] mod tests { use super::*; @@ -158,32 +128,4 @@ mod tests { assert!(std::ptr::eq(resolved, current())); assert_eq!(resolved.dir, config_dir()); } - - #[test] - fn permanent_probe_does_not_replace_an_existing_entry() { - let dir = std::env::temp_dir().join(format!("deckcraft-writable-{}-{}", std::process::id(), line!())); - std::fs::create_dir_all(&dir).unwrap(); - let probe = |attempt: u32| dir.join(format!(".deckcraft-write-probe-{}-{attempt}", std::process::id())); - // An entry already at the probe's name must never be truncated: the probe takes the next - // free name, and it removes only the file it created. - std::fs::write(probe(0), b"someone else's file").unwrap(); - ensure_writable(&dir).unwrap(); - assert_eq!(std::fs::read(probe(0)).unwrap(), b"someone else's file"); - assert!(!probe(1).exists()); - // Every name taken is an error, not a truncation of any of them. - for attempt in 0..8 { - std::fs::write(probe(attempt), b"someone else's file").unwrap(); - } - assert!(ensure_writable(&dir).is_err(), "no free probe name is reported, not truncated"); - for attempt in 0..8 { - assert_eq!(std::fs::read(probe(attempt)).unwrap(), b"someone else's file", "{attempt}"); - } - for attempt in 0..8 { - std::fs::remove_file(probe(attempt)).unwrap(); - } - // A folder whose stale probes were cleared is writable, and the probe leaves nothing behind. - ensure_writable(&dir).unwrap(); - assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 0); - std::fs::remove_dir_all(&dir).unwrap(); - } } diff --git a/apps/deckcraft/src/build_flavor.rs b/apps/deckcraft/src/build_flavor.rs index fb05b758c..04b16966d 100644 --- a/apps/deckcraft/src/build_flavor.rs +++ b/apps/deckcraft/src/build_flavor.rs @@ -1,31 +1,13 @@ //! Build-time channel is distinct from a launch selector. A runtime environment cannot promote a stable build. -use crate::launch_profile::Profile; -use std::ffi::OsString; -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum BuildFlavor { - Stable, - NightlyV1, -} +pub use craft_nightly::BuildFlavor; pub const COMPILED: BuildFlavor = if cfg!(deckcraft_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 DeckCraft Nightly from ArtCraft Launcher".into()), - (BuildFlavor::Stable, true) => Err("This is a stable DeckCraft build; nightly-v1 requires the nightly build".into()), - _ => Ok(()), - } -} - pub fn needs_native_error(flavor: BuildFlavor, desktop_session: bool) -> bool { desktop_session && flavor == BuildFlavor::NightlyV1 } -pub fn version_query(args: &[OsString]) -> bool { - matches!(args, [arg] if arg == "--version" || arg == "-V") -} - pub fn version(flavor: BuildFlavor, stable: &str) -> String { match flavor { BuildFlavor::Stable => stable.to_owned(), @@ -35,7 +17,10 @@ pub fn version(flavor: BuildFlavor, stable: &str) -> String { #[cfg(test)] mod tests { + use std::ffi::OsString; + use super::*; + #[test] fn only_a_nightly_desktop_refusal_requests_a_native_dialog() { assert!(needs_native_error(BuildFlavor::NightlyV1, true)); @@ -45,28 +30,51 @@ mod tests { } #[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()); + fn nightly_direct_launch_self_isolates_into_canonical_profile_root() { + let spec = crate::profile_root::spec(); + let expected_root = craft_nightly::canonical_profile_root(crate::profile_root::APP_ID).unwrap(); + let launch = craft_nightly::parse_startup( + BuildFlavor::NightlyV1, + &spec, + [OsString::from("--sample"), OsString::from("deck.pptx")], + &crate::launch_profile::startup_options(), + ) + .unwrap(); + assert_eq!(launch.profile, craft_nightly::Profile::NightlyV1(expected_root)); + assert_eq!(launch.passthrough_args, [OsString::from("--sample"), OsString::from("deck.pptx")]); } #[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()); + fn stable_flavor_rejects_nightly_launch_flags() { + let spec = crate::profile_root::spec(); + let root = if cfg!(windows) { r"C:\NightlyData\profiles\deckcraft" } else { "/nightly-data/profiles/deckcraft" }; + let result = craft_nightly::parse_startup( + BuildFlavor::Stable, + &spec, + [ + OsString::from(craft_nightly::LAUNCH_PROFILE_FLAG), + OsString::from(craft_nightly::NIGHTLY_V1_CONTRACT), + OsString::from(craft_nightly::PROFILE_ROOT_FLAG), + OsString::from(root), + ], + &crate::launch_profile::startup_options(), + ); + assert!(matches!(result, Err(craft_nightly::ProfileError::NightlyFlagsInStableBuild))); } #[test] fn nightly_version_query_is_unambiguous_and_never_reinterprets_file_arguments() { + let spec = crate::profile_root::spec(); + let opts = crate::launch_profile::startup_options(); assert_eq!(version(BuildFlavor::Stable, "0.19.0"), "0.19.0"); assert_eq!(version(BuildFlavor::NightlyV1, "0.19.0"), "0.19.0 (nightly-v1)"); - assert!(version_query(&["--version".into()])); - assert!(version_query(&["-V".into()])); - assert!(!version_query(&["--".into(), "--version".into()])); - assert!(!version_query(&[])); + assert!(craft_nightly::parse_startup(BuildFlavor::NightlyV1, &spec, [OsString::from("--version")], &opts).unwrap().is_version_query()); + assert!(craft_nightly::parse_startup(BuildFlavor::NightlyV1, &spec, [OsString::from("-V")], &opts).unwrap().is_version_query()); + assert!( + !craft_nightly::parse_startup(BuildFlavor::NightlyV1, &spec, [OsString::from("--"), OsString::from("--version")], &opts) + .unwrap() + .is_version_query() + ); + assert!(!craft_nightly::parse_startup(BuildFlavor::NightlyV1, &spec, Vec::::new(), &opts).unwrap().is_version_query()); } } diff --git a/apps/deckcraft/src/launch_profile.rs b/apps/deckcraft/src/launch_profile.rs index fd95c757a..ce42b27e8 100644 --- a/apps/deckcraft/src/launch_profile.rs +++ b/apps/deckcraft/src/launch_profile.rs @@ -1,221 +1,105 @@ -//! 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. +//! Nightly-v1 bootstrap powered by `craft-nightly`. Selected before logging, updates, fonts or +//! saved state. Stable launches retain their original arguments and directory policy; direct +//! nightly launches self-isolate into [`craft_nightly::canonical_profile_root`]. 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(); +use craft_nightly::{BuildFlavor, Launch, Profile, ProfileError, StartupOptions}; pub fn current() -> &'static Profile { - PROFILE.get().unwrap_or(&Profile::Stable) + craft_nightly::current().unwrap_or(&Profile::Stable) } -pub fn install(profile: Profile) -> Result<(), String> { - PROFILE.set(profile).map_err(|_| "the launch profile was already selected".into()) +pub fn startup_options() -> StartupOptions { + StartupOptions::new() } -/// 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 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::app_dirs::ensure_writable) +/// Parses startup arguments for `flavor`, validates and prepares the isolated profile root when +/// running as [`BuildFlavor::NightlyV1`], and installs the resolved profile process-wide. +pub fn prepare(flavor: BuildFlavor, args: impl IntoIterator) -> Result { + let spec = crate::profile_root::spec(); + craft_nightly::prepare_launch(flavor, &spec, args, &startup_options()) } #[cfg(test)] mod tests { + use std::path::PathBuf; + + use craft_nightly::{LAUNCH_PROFILE_FLAG, NIGHTLY_V1_CONTRACT, PROFILE_ROOT_FLAG, canonical_profile_root, parse_startup}; + use super::*; - use std::cell::Cell; + fn args(values: &[&str]) -> Vec { values.iter().map(OsString::from).collect() } + fn absolute() -> &'static str { if cfg!(windows) { r"C:\NightlyData\profiles\deckcraft" } else { "/nightly-data/profiles/deckcraft" } } - fn nightly() -> Vec { - args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--"]) - } - - /// The process installs one profile; later answers are read-only and a second install fails. - #[test] - fn the_process_installs_its_profile_once() { - assert_eq!(current(), &Profile::Stable, "an unselected process is a stable launch"); - assert!(install(Profile::Stable).is_ok()); - assert_eq!(current(), &Profile::Stable); - assert!(install(Profile::Stable).is_err()); - } #[test] - fn stable_arguments_and_directory_policy_are_unchanged() { + fn stable_arguments_and_profile_are_unchanged() { + let spec = crate::profile_root::spec(); for argv in [args(&[]), args(&["--sample", "a.pptx"]), args(&["--", "--launch-profile", "file.pptx"])] { - 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 }); + let launch = parse_startup(BuildFlavor::Stable, &spec, argv.clone(), &startup_options()).unwrap(); + assert_eq!(launch.profile, Profile::Stable); + assert_eq!(launch.passthrough_args, argv); } } #[test] - fn exact_version_and_root_are_parsed_without_reinterpreting_file_names() { - let mut argv = nightly(); - argv.extend(args(&["--profile-root", "talk with spaces.pptx"])); - let launch = parse(argv).unwrap(); + fn explicit_launcher_arguments_are_parsed_without_reinterpreting_file_names() { + let spec = crate::profile_root::spec(); + let argv = args(&[LAUNCH_PROFILE_FLAG, NIGHTLY_V1_CONTRACT, PROFILE_ROOT_FLAG, absolute(), "--", "--profile-root", "talk with spaces.pptx"]); + let launch = parse_startup(BuildFlavor::NightlyV1, &spec, argv, &startup_options()).unwrap(); assert_eq!(launch.profile, Profile::NightlyV1(PathBuf::from(absolute()))); - assert_eq!(launch.args, args(&["--", "--profile-root", "talk with spaces.pptx"])); + assert_eq!(launch.passthrough_args, args(&["--profile-root", "talk with spaces.pptx"])); } #[test] - fn missing_duplicate_unknown_and_conflicting_profile_arguments_are_refused() { - for argv in [ - args(&["--launch-profile", VERSION]), - args(&["--profile-root", absolute()]), - args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--"]), - args(&["--launch-profile", VERSION, "--launch-profile", VERSION, "--profile-root", absolute(), "--"]), - args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--profile-root", absolute(), "--"]), - args(&["--launch-profile", VERSION, "--profile-root", "relative", "--"]), - args(&["--launch-profile", VERSION, "--profile-root", "", "--"]), - args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--control", "4242", "--"]), - args(&["--launch-profile", VERSION, "--profile-root", absolute()]), - args(&["--launch-profile=nightly-v1", "--profile-root", absolute(), "--"]), - ] { - assert!(parse(argv).is_err()); - } + fn direct_nightly_launch_self_isolates_and_preserves_user_args() { + let spec = crate::profile_root::spec(); + let expected_root = canonical_profile_root(crate::profile_root::APP_ID).unwrap(); + let launch = parse_startup(BuildFlavor::NightlyV1, &spec, args(&["--show", "deck.ppsx"]), &startup_options()).unwrap(); + assert_eq!(launch.profile, Profile::NightlyV1(expected_root)); + assert_eq!(launch.passthrough_args, args(&["--show", "deck.ppsx"])); } #[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:?}"); - } - } + fn launcher_and_plain_version_queries_are_recognized() { + let spec = crate::profile_root::spec(); for argv in [ args(&["--version"]), - args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--", "--version"]), - args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--"]), - args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--control", "1", "--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"]), + args(&["-V"]), + args(&[LAUNCH_PROFILE_FLAG, NIGHTLY_V1_CONTRACT, PROFILE_ROOT_FLAG, absolute(), "--version"]), + args(&[PROFILE_ROOT_FLAG, absolute(), LAUNCH_PROFILE_FLAG, NIGHTLY_V1_CONTRACT, "-V"]), + args(&[LAUNCH_PROFILE_FLAG, NIGHTLY_V1_CONTRACT, PROFILE_ROOT_FLAG, absolute(), "--", "--version"]), ] { - assert!(!version_query(&argv), "{argv:?}"); + let launch = parse_startup(BuildFlavor::NightlyV1, &spec, argv.clone(), &startup_options()).unwrap(); + assert!(launch.is_version_query(), "{argv:?}"); + } + for argv in [ + args(&[LAUNCH_PROFILE_FLAG, NIGHTLY_V1_CONTRACT, PROFILE_ROOT_FLAG, absolute(), "--version", "--version"]), + args(&[LAUNCH_PROFILE_FLAG, NIGHTLY_V1_CONTRACT, PROFILE_ROOT_FLAG, absolute(), "--help"]), + ] { + let launch = parse_startup(BuildFlavor::NightlyV1, &spec, argv.clone(), &startup_options()).unwrap(); + assert!(!launch.is_version_query(), "{argv:?}"); } - // Outside the query the strict protocol still refuses the version flag. - assert!(parse(args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version"])).is_err()); } #[test] - fn failed_root_validation_never_reaches_startup_or_falls_back_to_stable() { - let reached = Cell::new(false); - let result = prepare(parse(nightly()).unwrap(), |_| Err("read-only or unsafe profile".into())).map(|_| reached.set(true)); - assert!(result.is_err()); - assert!(!reached.get()); - } - - #[test] - fn successful_root_validation_keeps_the_persistent_root_not_the_binary_tag() { - let checked = PathBuf::from(absolute()).join("checked"); - let launch = prepare(parse(nightly()).unwrap(), |_| Ok(checked.clone())).unwrap(); - assert_eq!(launch.profile.root(), Some(checked.as_path())); - assert!(launch.profile.is_nightly()); + fn missing_duplicate_unknown_and_misplaced_profile_arguments_are_refused() { + let spec = crate::profile_root::spec(); + for argv in [ + args(&[LAUNCH_PROFILE_FLAG, NIGHTLY_V1_CONTRACT]), + args(&[PROFILE_ROOT_FLAG, absolute()]), + args(&[LAUNCH_PROFILE_FLAG, "future-v2", PROFILE_ROOT_FLAG, absolute(), "--"]), + args(&[LAUNCH_PROFILE_FLAG, NIGHTLY_V1_CONTRACT, LAUNCH_PROFILE_FLAG, NIGHTLY_V1_CONTRACT, PROFILE_ROOT_FLAG, absolute(), "--"]), + args(&[LAUNCH_PROFILE_FLAG, NIGHTLY_V1_CONTRACT, PROFILE_ROOT_FLAG, absolute(), PROFILE_ROOT_FLAG, absolute(), "--"]), + args(&[LAUNCH_PROFILE_FLAG, NIGHTLY_V1_CONTRACT, PROFILE_ROOT_FLAG, "", "--"]), + args(&["--sample", LAUNCH_PROFILE_FLAG, NIGHTLY_V1_CONTRACT, PROFILE_ROOT_FLAG, absolute()]), + ] { + assert!(parse_startup(BuildFlavor::NightlyV1, &spec, argv.clone(), &startup_options()).is_err(), "{argv:?}"); + } } } diff --git a/apps/deckcraft/src/main.rs b/apps/deckcraft/src/main.rs index 7641870b6..43ac2854e 100644 --- a/apps/deckcraft/src/main.rs +++ b/apps/deckcraft/src/main.rs @@ -212,42 +212,44 @@ fn app_icon() -> Option { /// Select the immutable launch profile before any startup service or side effect. fn prepare_launch() -> Option> { - // The trusted Launcher protocol is decided before logger/crash/update/font/prefs access. + // The trusted Launcher protocol (or direct nightly self-isolation) is decided before + // logger/crash/update/font/prefs access. let argv: Vec<_> = std::env::args_os().skip(1).collect(); - // Plain `--version`, or the Launcher's `--launch-profile nightly-v1 --profile-root - // --version`: answered before root validation, process identity, IPC or any window. - if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && (build_flavor::version_query(&argv) || launch_profile::version_query(&argv)) + // Preserve standalone version probes in environments without a resolvable profile directory. + if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 + && argv.len() == 1 + && argv.first().is_some_and(|arg| arg == "--version" || arg == "-V") { use std::io::Write as _; let _ = writeln!(std::io::stdout(), "DeckCraft {}", build_flavor::version(build_flavor::COMPILED, deckcraft_ui_egui::flavor::version())); return None; } - let early = launch_profile::parse(argv) - .and_then(|launch| { - build_flavor::require_profile(build_flavor::COMPILED, &launch.profile)?; - initialize_nightly_process_identity().map_err(|error| error.to_string())?; - Ok(launch) - }) - .and_then(|launch| { - launch_profile::prepare(launch, |root| { - launch_profile::validate_root(root, |key| std::env::var_os(key), std::env::current_exe().ok().as_deref()) - }) - }) - .unwrap_or_else(|error| { - report_launch_profile_error(&error); - std::process::exit(2) - }); + let early = launch_profile::prepare(build_flavor::COMPILED, argv).unwrap_or_else(|error| { + report_launch_profile_error(&error.to_string()); + std::process::exit(2) + }); + // Plain `--version`, or the Launcher's `--launch-profile nightly-v1 --profile-root + // [--] --version`: answered before process identity, IPC or any window. + if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && early.is_version_query() { + use std::io::Write as _; + let _ = writeln!(std::io::stdout(), "DeckCraft {}", build_flavor::version(build_flavor::COMPILED, deckcraft_ui_egui::flavor::version())); + return None; + } + if let Err(error) = initialize_nightly_process_identity() { + report_launch_profile_error(&error.to_string()); + std::process::exit(2); + } let identity = if early.profile.is_nightly() { deckcraft_ui_egui::os_window::LaunchIdentity::NightlyV1 } else { deckcraft_ui_egui::os_window::LaunchIdentity::Stable }; - if let Err(error) = launch_profile::install(early.profile).and_then(|()| deckcraft_ui_egui::os_window::select_identity(identity)) { + if let Err(error) = deckcraft_ui_egui::os_window::select_identity(identity) { report_launch_profile_error(&error); std::process::exit(2); } - Some(early.args) + Some(early.passthrough_args) } fn initialize_nightly_process_identity() -> Result<(), process_identity::IdentityError> { diff --git a/apps/deckcraft/src/profile_root.rs b/apps/deckcraft/src/profile_root.rs index 5dcad5dbb..7641cf840 100644 --- a/apps/deckcraft/src/profile_root.rs +++ b/apps/deckcraft/src/profile_root.rs @@ -1,697 +1,222 @@ -//! App-owned nightly profile fences; no stable fallback, migration or process environment changes. +//! DeckCraft's nightly profile specification and extra forbidden-root fence for `craft-nightly`. use std::ffi::OsString; +use std::path::PathBuf; -use crate::app_dirs::{PORTABLE_DATA_DIR, portable_marker}; -use std::path::{Component, Path, PathBuf}; +use craft_nightly::AppProfileSpec; -/// The DeckCraft Nightly Flatpak app id (`packaging/linux/flatpak-bundle.sh`), the one Flatpak -/// instance a Nightly profile may inherit. -pub const NIGHTLY_FLATPAK_ID: &str = "ai.storyteller.deckcraft.nightly"; +/// Canonical application identifier for DeckCraft nightly profile isolation. +pub const APP_ID: &str = "deckcraft"; -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum Platform { - Windows, - Linux, - Mac, +const STABLE_DIR_NAMES: &[&str] = &["DeckCraft", "deckcraft"]; +const FOLDER_ONLY_ENTRIES: &[&str] = &["Recovery", "Dictionaries", crate::logging::LOG_DIR]; + +/// Builds DeckCraft's [`AppProfileSpec`] for `craft-nightly`, preserving DeckCraft's exact +/// stable directory names, portable markers, folder-only entries, and OS-specific extra +/// forbidden roots. +pub fn spec() -> AppProfileSpec { + spec_with(|k| std::env::var_os(k)) } -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 spec_with(env: impl Fn(&str) -> Option) -> AppProfileSpec { + AppProfileSpec { + app_id: APP_ID, + display_name: "DeckCraft", + stable_dir_names: STABLE_DIR_NAMES, + stable_package_id: "ai.storyteller.deckcraft", + nightly_package_id: "ai.storyteller.deckcraft.nightly", + profile_root_env: None, + forbidden_env_vars: &[], + portable_markers: &crate::app_dirs::PORTABLE_MARKERS, + folder_only_entries: FOLDER_ONLY_ENTRIES, + extra_forbidden_roots: extra_forbidden_roots(env), + } +} + +#[cfg(any(unix, target_os = "windows"))] +fn non_empty_abs(env: &impl Fn(&str) -> Option, key: &str) -> Option { + let value = env(key)?; + if value.is_empty() { + return None; + } + let path = PathBuf::from(value); + path.is_absolute().then_some(path) +} + +fn extra_forbidden_roots(env: impl Fn(&str) -> Option) -> Vec { + #[cfg(target_os = "windows")] + { + let mut roots = Vec::new(); + // The MSI's default per-user and per-machine folders (install-policy.wxi). + if let Some(local) = non_empty_abs(&env, "LOCALAPPDATA") { + roots.push(local.join("Programs").join("ArtCraft").join("DeckCraft")); } - } - - 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")?; + for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] { + if let Some(base) = non_empty_abs(&env, key) { + roots.push(base.join("ArtCraft").join("DeckCraft")); } - Err(error) => return Err(format!("cannot inspect the profile boundary: {error}")), } + roots } - let mut resolved = std::fs::canonicalize(parent).map_err(|e| format!("cannot resolve the profile boundary: {e}"))?; - for part in missing.into_iter().rev() { - resolved.push(part); - } - Ok(resolved) -} - -fn overlaps(a: &Path, b: &Path, platform: Platform) -> bool { - let parts = |p: &Path| { - p.components() - .map(|c| { - let value = c.as_os_str().to_string_lossy().into_owned(); - if platform.ignores_case() { value.to_lowercase() } else { value } - }) - .collect::>() - }; - let (a, b) = (parts(a), parts(b)); - a.starts_with(&b) || b.starts_with(&a) -} - -fn installation_boundary(platform: Platform, exe: &Path) -> Result { - let parent = exe.parent().ok_or("cannot establish the installation boundary")?; - if platform == Platform::Mac { - // A profile in Resources is still inside the versioned install, not beside MacOS. - if let Some(bundle) = exe.ancestors().find(|p| p.extension().is_some_and(|ext| ext.eq_ignore_ascii_case("app"))) { - return Ok(bundle.to_path_buf()); - } - } - Ok(parent.to_path_buf()) -} - -fn forbidden_roots(platform: Platform, env: &impl Fn(&str) -> Option, exe: &Path) -> Result, String> { - let mut roots = match platform { - Platform::Windows => { - let mut roots = ["APPDATA", "LOCALAPPDATA"] - .into_iter() - .map(|key| required_base(env, key).map(|p| p.join("DeckCraft"))) - .collect::, _>>()?; - // The MSI's default per-user and per-machine folders (install-policy.wxi). A custom - // install folder is not known here; the executable's own folder is fenced below. - roots.push(required_base(env, "LOCALAPPDATA")?.join("Programs").join("ArtCraft").join("DeckCraft")); - 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("DeckCraft")); - } - } - 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("deckcraft"))) - .collect::, _>>()?; - roots.extend(["/usr/bin/deckcraft", "/usr/local/bin/deckcraft", "/opt/deckcraft"].map(PathBuf::from)); - // The stable Flatpak keeps its data in its own per-app folder. - roots.push(required_base(env, "HOME")?.join(".var/app/ai.storyteller.deckcraft")); - roots - } - Platform::Mac => { - let home = required_base(env, "HOME")?; + #[cfg(target_os = "macos")] + { + let mut roots = vec![PathBuf::from("/Applications/DeckCraft.app")]; + if let Some(home) = non_empty_abs(&env, "HOME") { let library = home.join("Library"); - vec![ - library.join("Application Support/DeckCraft"), - library.join("Caches/DeckCraft"), - library.join("Caches/ai.storyteller.deckcraft"), - library.join("Preferences/DeckCraft"), - library.join("Preferences/ai.storyteller.deckcraft.plist"), - library.join("Saved Application State/ai.storyteller.deckcraft.savedState"), - home.join("Applications/DeckCraft.app"), - PathBuf::from("/Applications/DeckCraft.app"), - ] + roots.push(library.join("Preferences/ai.storyteller.deckcraft.plist")); + roots.push(library.join("Saved Application State/ai.storyteller.deckcraft.savedState")); + roots.push(home.join("Applications/DeckCraft.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")); + roots } - Ok(child) -} - -/// Every existing entry directly in the profile (Dictionaries, 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() { - if folder_only { - return Err(format!("the nightly {} must be a directory", entry.file_name().to_string_lossy())); - } - private_regular_file(&path, &metadata)?; - } else { - private_subdirectory(root, entry.file_name(), "profile entry")?; - } - } - // The one nested file Nightly writes itself: a link at Dictionaries/user.dic would append - // "add to dictionary" words to the stable app's file instead of this profile's. - private_subdirectory(root, std::path::Path::new("Dictionaries").join("user.dic"), "user dictionary")?; - 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)] + #[cfg(all(unix, not(target_os = "macos")))] { - use std::os::unix::fs::MetadataExt as _; - if metadata.nlink() != 1 { - return Err("the nightly profile file must not be shared".into()); + let mut roots = vec![PathBuf::from("/usr/bin/deckcraft"), PathBuf::from("/usr/local/bin/deckcraft"), PathBuf::from("/opt/deckcraft")]; + // The stable Flatpak keeps its data in its own per-app folder. + if let Some(home) = non_empty_abs(&env, "HOME") { + roots.push(home.join(".var/app/ai.storyteller.deckcraft")); } + roots } - #[cfg(windows)] + #[cfg(not(any(unix, target_os = "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 _ = env; + Vec::new() } - let _ = (path, metadata); - Ok(()) } -/// Recognise a portable data namespace in both the supplied and resolved path. DeckCraft ships no -/// portable package, so this only refuses a hand-made copy; it is not an inventory of arbitrary -/// custom Stable overrides or a Launcher ownership proof. -fn is_portable_layout(path: &Path, platform: Platform) -> bool { - // Above the chosen folder itself, a marker only counts beside a DeckCraft executable, so an - // unrelated portable.txt higher up (in a user folder or at a drive root) does not refuse it. - path.ancestors().enumerate().any(|(depth, ancestor)| { - portable_marker(ancestor).is_some() && (depth == 0 || ["deckcraft.exe", "deckcraft"].iter().any(|exe| ancestor.join(exe).is_file())) - }) || path.components().any(|component| match component { - Component::Normal(name) if platform.ignores_case() => name.to_string_lossy().eq_ignore_ascii_case(PORTABLE_DATA_DIR), - Component::Normal(name) => name == PORTABLE_DATA_DIR, - _ => false, - }) -} - -/// The writable hook is the app's existing exclusive probe. Keeping it injected lets filesystem -/// boundary tests exercise the real policy without starting the app or changing global state. -pub fn validate( - root: &Path, - env: impl Fn(&str) -> Option, - exe: Option<&Path>, - writable: impl FnOnce(&Path) -> std::io::Result<()>, -) -> Result { - validate_for(Platform::current()?, root, env, exe, writable) -} - -fn validate_for( - platform: Platform, - root: &Path, - env: impl Fn(&str) -> Option, - exe: Option<&Path>, - writable: impl FnOnce(&Path) -> std::io::Result<()>, -) -> Result { - absolute(root.to_path_buf(), "the nightly profile root")?; - if let Some(id) = env("FLATPAK_ID").filter(|v| !v.is_empty()) { - // The native tar and app-bundle rows are not Flatpak packages: inheriting a Flatpak - // runtime could point another profile at the stable app's data. DeckCraft Nightly's own - // Flatpak (packaging/linux/flatpak-bundle.sh) is the one allowed instance, matched by its - // exact id; the stable id and any other app are refused. - if platform == Platform::Windows || id != NIGHTLY_FLATPAK_ID { - return Err("nightly-v1 accepts only the DeckCraft Nightly Flatpak instance; launch through the native Launcher".into()); - } - } - let chosen = canonical_future(root)?; - if is_portable_layout(root, platform) || is_portable_layout(&chosen, platform) { - return Err("the nightly root must not use a portable DeckCraft copy or its DeckCraftData 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)?; - // Recovery can read, adopt, overwrite and sweep entries. Never let its alias leave this - // private profile, including toward a Stable portable directory not in our known roots. - private_subdirectory(&chosen, "Recovery", "recovery folder")?; - private_subdirectory(&chosen, "Dictionaries", "dictionary folder")?; - let mut create = std::fs::DirBuilder::new(); - create.recursive(true); - #[cfg(unix)] - { - use std::os::unix::fs::DirBuilderExt as _; - create.mode(0o700); - } - create.create(&chosen).map_err(|e| format!("cannot create the nightly profile: {e}"))?; - let confirmed = std::fs::canonicalize(&chosen).map_err(|e| format!("cannot resolve the created nightly profile: {e}"))?; - if confirmed != chosen || forbidden.iter().any(|stable| overlaps(&confirmed, stable, platform)) { - return Err("the nightly profile changed while it was being validated".into()); - } - private_subdirectory(&confirmed, "Recovery", "recovery folder")?; - private_subdirectory(&confirmed, "Dictionaries", "dictionary folder")?; - entries_stay_inside(&confirmed)?; - writable(&confirmed).map_err(|e| format!("the nightly profile is not writable: {e}"))?; - Ok(confirmed) -} - -const PROFILE_FOLDERS: [&str; 3] = ["Recovery", "Dictionaries", crate::logging::LOG_DIR]; - #[cfg(test)] mod tests { - use super::*; use std::collections::BTreeMap; + use std::path::Path; use std::sync::atomic::{AtomicU64, Ordering}; - struct Fixture { - root: PathBuf, - env: BTreeMap, - exe: PathBuf, - } + use craft_nightly::{ProfileError, validate_and_prepare_root}; - impl Fixture { - fn new() -> Self { + use super::*; + + struct TempDir(PathBuf); + + impl TempDir { + fn new(label: &str) -> Self { static NEXT: AtomicU64 = AtomicU64::new(0); let root = loop { - let candidate = - std::env::temp_dir().join(format!("deckcraft-profile-policy-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed))); + let candidate = std::env::temp_dir().join(format!( + "deckcraft-profile-spec-{label}-{}-{}", + std::process::id(), + NEXT.fetch_add(1, Ordering::Relaxed) + )); match std::fs::create_dir(&candidate) { Ok(()) => break std::fs::canonicalize(candidate).unwrap(), Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue, - Err(error) => panic!("cannot create owned fixture: {error}"), + Err(error) => panic!("cannot create temp dir: {error}"), } }; - let home = root.join("home"); - let exe = root.join("install/deckcraft"); - std::fs::create_dir_all(&home).unwrap(); - std::fs::create_dir_all(exe.parent().unwrap()).unwrap(); - std::fs::write(&exe, b"fixture executable, never run").unwrap(); - let env = [("HOME", home), ("APPDATA", root.join("roaming")), ("LOCALAPPDATA", root.join("local"))] - .into_iter() - .map(|(key, value)| (key.into(), value.into_os_string())) - .collect(); - Self { root, env, exe } + Self(root) } - fn get(&self, key: &str) -> Option { - self.env.get(key).cloned() - } - - fn check(&self, platform: Platform, root: &Path) -> Result { - validate_for( - platform, - root, - |key| self.get(key), - Some(&self.exe), - |dir| { - let probe = dir.join("exclusive-test-probe"); - let file = std::fs::OpenOptions::new().write(true).create_new(true).open(&probe)?; - drop(file); - std::fs::remove_file(probe) - }, - ) - } - - fn home(&self) -> PathBuf { - PathBuf::from(self.get("HOME").unwrap()) + fn path(&self) -> &Path { + &self.0 } } - impl Drop for Fixture { + impl Drop for TempDir { fn drop(&mut self) { - // Only the directory successfully created by this fixture is owned for removal. - std::fs::remove_dir_all(&self.root).unwrap(); + let _ = std::fs::remove_dir_all(&self.0); } } #[test] - fn portable_settings_from_another_install_are_refused_before_any_probe() { - let fixture = Fixture::new(); - let stable_install = fixture.root.join("stable portable install"); - let stable_data = stable_install.join(PORTABLE_DATA_DIR); - std::fs::create_dir_all(&stable_data).unwrap(); - std::fs::write(stable_install.join("portable.txt"), b"owned portable fixture").unwrap(); - std::fs::write(stable_data.join("settings.json"), b"stable settings must not change").unwrap(); - for platform in [Platform::Windows, Platform::Linux, Platform::Mac] { - for candidate in [&stable_data, &stable_data.join("nested nightly")] { - let probed = std::cell::Cell::new(false); - let result = validate_for( - platform, - candidate, - |key| fixture.get(key), - Some(&fixture.exe), - |_| { - probed.set(true); - Ok(()) - }, - ); - assert!(result.is_err(), "a different portable install is not a private Nightly profile"); - assert!(!probed.get(), "reject portable data before a writable probe"); - assert!(!stable_data.join("nested nightly").exists()); - assert_eq!(std::fs::read(stable_data.join("settings.json")).unwrap(), b"stable settings must not change"); - } + fn spec_preserves_deckcraft_isolation_constants() { + let s = spec(); + assert_eq!(s.app_id, "deckcraft"); + assert_eq!(s.display_name, "DeckCraft"); + assert_eq!(s.stable_dir_names, &["DeckCraft", "deckcraft"]); + assert_eq!(s.stable_package_id, "ai.storyteller.deckcraft"); + assert_eq!(s.nightly_package_id, "ai.storyteller.deckcraft.nightly"); + assert_eq!(s.profile_root_env, None); + assert!(s.forbidden_env_vars.is_empty()); + assert_eq!(s.portable_markers, &["portable.txt"]); + assert_eq!(s.folder_only_entries, &["Recovery", "Dictionaries", "logs"]); + } + + #[test] + fn extra_forbidden_roots_cover_platform_install_and_stable_paths() { + let mut env = BTreeMap::::new(); + if cfg!(target_os = "windows") { + env.insert("LOCALAPPDATA".into(), r"C:\Users\me\AppData\Local".into()); + env.insert("ProgramFiles".into(), r"C:\Program Files".into()); + } else { + env.insert("HOME".into(), "/home/me".into()); } - let private = fixture.root.join("DeckCraftData-backup-name/nightly"); - assert!(fixture.check(Platform::Linux, &private).is_ok(), "a merely similar name is not a portable settings component"); + let roots = extra_forbidden_roots(|key| env.get(key).cloned()); + #[cfg(target_os = "windows")] + { + assert!(roots.contains(&PathBuf::from(r"C:\Users\me\AppData\Local\Programs\ArtCraft\DeckCraft"))); + assert!(roots.contains(&PathBuf::from(r"C:\Program Files\ArtCraft\DeckCraft"))); + } + #[cfg(target_os = "macos")] + { + assert!(roots.contains(&PathBuf::from("/Applications/DeckCraft.app"))); + assert!(roots.contains(&PathBuf::from("/home/me/Applications/DeckCraft.app"))); + assert!(roots.contains(&PathBuf::from("/home/me/Library/Preferences/ai.storyteller.deckcraft.plist"))); + assert!(roots.contains(&PathBuf::from("/home/me/Library/Saved Application State/ai.storyteller.deckcraft.savedState"))); + } + #[cfg(all(unix, not(target_os = "macos")))] + { + assert!(roots.contains(&PathBuf::from("/usr/bin/deckcraft"))); + assert!(roots.contains(&PathBuf::from("/usr/local/bin/deckcraft"))); + assert!(roots.contains(&PathBuf::from("/opt/deckcraft"))); + assert!(roots.contains(&PathBuf::from("/home/me/.var/app/ai.storyteller.deckcraft"))); + } + } + + #[test] + fn valid_profile_root_reopens_and_enforces_folder_only_entries() { + let tmp = TempDir::new("reopen"); + let profile = tmp.path().join("nightly-profile"); + let s = spec(); + + let prepared = validate_and_prepare_root(&profile, &s).unwrap(); + assert_eq!(prepared, profile); + + for file_name in ["ui.json", "prefs.json", "nightly-session.lock", "nightly-session.json"] { + std::fs::write(prepared.join(file_name), b"saved profile data").unwrap(); + } + for dir_name in FOLDER_ONLY_ENTRIES { + std::fs::create_dir(prepared.join(dir_name)).unwrap(); + } + assert_eq!(validate_and_prepare_root(&profile, &s).unwrap(), prepared); + + for dir_name in FOLDER_ONLY_ENTRIES { + let entry = prepared.join(dir_name); + std::fs::remove_dir(&entry).unwrap(); + std::fs::write(&entry, b"not a directory").unwrap(); + assert!(matches!(validate_and_prepare_root(&profile, &s), Err(ProfileError::ExpectedDirectoryEntry(_)))); + std::fs::remove_file(&entry).unwrap(); + std::fs::create_dir(&entry).unwrap(); + } + } + + #[test] + fn relative_and_traversal_profile_roots_are_refused() { + let tmp = TempDir::new("lexical"); + let s = spec(); + assert!(matches!(validate_and_prepare_root(Path::new("relative/nightly"), &s), Err(ProfileError::RelativeProfileRoot(_)))); + assert!(matches!(validate_and_prepare_root(&tmp.path().join("nightly/../escape"), &s), Err(ProfileError::ParentTraversalInProfileRoot(_)))); } #[cfg(unix)] #[test] - fn recovery_aliases_cannot_redirect_to_stable_missing_or_profile_root_data() { - let fixture = Fixture::new(); - let stable = fixture.home().join(".local/share/deckcraft/recovery"); - std::fs::create_dir_all(&stable).unwrap(); - std::fs::write(stable.join("stable-autosave"), b"stable recovery bytes").unwrap(); - for (index, target) in [stable.clone(), fixture.root.join("missing recovery target")].into_iter().enumerate() { - let private = fixture.root.join(format!("nightly-{index}")); - std::fs::create_dir(&private).unwrap(); - std::os::unix::fs::symlink(&target, private.join("Recovery")).unwrap(); - let probed = std::cell::Cell::new(false); - let result = validate_for( - Platform::Linux, - &private, - |key| fixture.get(key), - Some(&fixture.exe), - |_| { - probed.set(true); - Ok(()) - }, - ); - assert!(result.is_err(), "Recovery must not escape the private profile or follow a dangling alias"); - assert!(!probed.get()); - } - let private = fixture.root.join("nightly-self"); - std::fs::create_dir(&private).unwrap(); - std::os::unix::fs::symlink(&private, private.join("Recovery")).unwrap(); - assert!(fixture.check(Platform::Linux, &private).is_err(), "Recovery cannot treat all profile settings as recovery entries"); - assert_eq!(std::fs::read(stable.join("stable-autosave")).unwrap(), b"stable recovery bytes"); - } + fn symlink_inside_profile_root_is_refused() { + let tmp = TempDir::new("symlink"); + let outside = tmp.path().join("outside"); + let profile = tmp.path().join("nightly-profile"); + std::fs::create_dir_all(&outside).unwrap(); + std::fs::create_dir_all(&profile).unwrap(); + std::os::unix::fs::symlink(&outside, profile.join("Recovery")).unwrap(); - #[cfg(unix)] - #[test] - fn recovery_alias_to_a_private_subfolder_keeps_the_profile_usable() { - let fixture = Fixture::new(); - let private = fixture.root.join("nightly-private"); - let recovery = private.join("private-recovery"); - std::fs::create_dir_all(&recovery).unwrap(); - std::os::unix::fs::symlink(&recovery, private.join("Recovery")).unwrap(); - assert!(fixture.check(Platform::Linux, &private).is_ok()); - assert_eq!(std::fs::canonicalize(private.join("Recovery")).unwrap(), recovery); - } - - /// The public entry point reads the host platform and refuses a relative root before probing. - #[cfg(target_os = "linux")] - #[test] - fn the_public_validator_uses_the_host_platform_and_creates_only_the_profile() { - let fixture = Fixture::new(); - let root = fixture.home().join("nightly/profiles/deckcraft"); - let created = validate(&root, |key| fixture.get(key), Some(&fixture.exe), crate::app_dirs::ensure_writable) - .expect("a private profile under HOME is valid on Linux"); - assert_eq!(created, root); - assert!(created.is_dir()); - let probed = std::cell::Cell::new(false); - let refused = validate( - Path::new("relative/profile"), - |key| fixture.get(key), - Some(&fixture.exe), - |_| { - probed.set(true); - Ok(()) - }, - ); - assert!(refused.is_err()); - assert!(!probed.get(), "a relative root is refused before the write probe"); - } - - #[test] - fn overlap_check_handles_ancestor_descendant_and_prefix_lookalikes() { - let fixture = Fixture::new(); - let root = fixture.home().join("nightly/profiles/deckcraft"); - for platform in [Platform::Windows, Platform::Linux, Platform::Mac] { - assert!(overlaps(&root, &root.join("Recovery"), platform)); - assert!(overlaps(&root.join("Recovery"), &root, platform)); - assert!(!overlaps(&root, &root.with_file_name("deckcraft-other"), platform)); - } - } - - #[test] - fn linux_fences_app_xdg_subtrees_but_allows_launcher_sibling() { - let mut fixture = Fixture::new(); - for key in ["XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME"] { - fixture.env.insert(key.into(), fixture.root.join(key).into_os_string()); - } - for key in ["XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME"] { - let stable = PathBuf::from(fixture.get(key).unwrap()).join("deckcraft"); - std::fs::create_dir_all(&stable).unwrap(); - std::fs::write(stable.join("stable-sentinel"), b"stable bytes").unwrap(); - for candidate in [stable.clone(), stable.join("nightly"), stable.parent().unwrap().to_path_buf()] { - assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("overlap")); - } - assert_eq!(std::fs::read(stable.join("stable-sentinel")).unwrap(), b"stable bytes"); - } - let data = PathBuf::from(fixture.get("XDG_DATA_HOME").unwrap()); - let nightly = data.join("ArtCraftLauncher/nightly/profiles/deckcraft"); - assert_eq!(fixture.check(Platform::Linux, &nightly).unwrap(), nightly); - assert_eq!(std::fs::read_dir(nightly).unwrap().count(), 0); - } - - #[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 ["ui.json", "prefs.json", "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("ui.json")).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 mac_fences_only_app_library_subtrees_and_the_entire_bundle() { - let mut fixture = Fixture::new(); - fixture.exe = fixture.root.join("install/DeckCraft Nightly.app/Contents/MacOS/DeckCraft"); - std::fs::create_dir_all(fixture.exe.parent().unwrap()).unwrap(); - std::fs::write(&fixture.exe, b"fixture executable, never run").unwrap(); - let library = fixture.home().join("Library"); - for suffix in [ - "Application Support/DeckCraft", - "Caches/DeckCraft", - "Caches/ai.storyteller.deckcraft", - "Preferences/DeckCraft", - "Saved Application State/ai.storyteller.deckcraft.savedState", - ] { - let stable = library.join(suffix); - assert!(fixture.check(Platform::Mac, &stable.join("nightly")).unwrap_err().contains("overlap")); - assert!(!stable.exists()); - } - let inside_resources = fixture.exe.parent().unwrap().parent().unwrap().join("Resources/profile"); - assert!(fixture.check(Platform::Mac, &inside_resources).unwrap_err().contains("overlap")); - assert!(!inside_resources.exists()); - let valid = library.join("Application Support/ArtCraftLauncher/nightly/profiles/deckcraft"); - assert_eq!(fixture.check(Platform::Mac, &valid).unwrap(), valid); - } - - #[test] - fn windows_roaming_local_and_install_fences_remain_active() { - let fixture = Fixture::new(); - for key in ["APPDATA", "LOCALAPPDATA"] { - let stable = PathBuf::from(fixture.get(key).unwrap()).join("DeckCraft"); - assert!(fixture.check(Platform::Windows, &stable.join("nightly")).unwrap_err().contains("overlap")); - assert!(!stable.exists()); - } - assert!(fixture.check(Platform::Windows, &fixture.exe.parent().unwrap().join("profile")).is_err()); - assert!(fixture.check(Platform::Windows, &fixture.root.join("Launcher/profiles/deckcraft")).is_ok()); - } - - #[test] - fn windows_default_msi_install_folders_are_fenced() { - let mut fixture = Fixture::new(); - let local = PathBuf::from(fixture.get("LOCALAPPDATA").unwrap()); - let per_user = local.join("Programs").join("ArtCraft").join("DeckCraft"); - assert!(fixture.check(Platform::Windows, &per_user.join("nightly")).unwrap_err().contains("overlap")); - for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] { - let base = fixture.root.join(format!("machine {key}")); - fixture.env.insert(key.into(), base.clone().into_os_string()); - let machine = base.join("ArtCraft").join("DeckCraft"); - assert!(fixture.check(Platform::Windows, &machine.join("nightly")).unwrap_err().contains("overlap")); - assert!(!machine.exists()); - } - let sibling = local.join("Programs").join("ArtCraft").join("ArtCraftLauncher").join("nightly").join("deckcraft"); - assert!(fixture.check(Platform::Windows, &sibling).is_ok(), "the Launcher's own Programs sibling is not DeckCraft's install"); - } - - #[test] - fn folders_under_a_stable_portable_copy_are_refused_before_any_probe() { - let fixture = Fixture::new(); - let portable = fixture.root.join("D/DC"); - std::fs::create_dir_all(&portable).unwrap(); - std::fs::write(portable.join("portable.txt"), b"stable portable copy").unwrap(); - std::fs::write(portable.join("deckcraft.exe"), b"stable portable executable, never run").unwrap(); - for platform in [Platform::Windows, Platform::Linux, Platform::Mac] { - for candidate in [portable.join("nightly"), portable.join("deeper/nightly")] { - let probed = std::cell::Cell::new(false); - let result = validate_for( - platform, - &candidate, - |key| fixture.get(key), - Some(&fixture.exe), - |_| { - probed.set(true); - Ok(()) - }, - ); - assert!(result.unwrap_err().contains("portable")); - assert!(!probed.get()); - assert!(!candidate.exists()); - } - } - // A portable.txt that no DeckCraft executable sits beside is someone else's file. - let unrelated = fixture.root.join("user folder"); - std::fs::create_dir_all(&unrelated).unwrap(); - std::fs::write(unrelated.join("portable.txt"), b"another app's marker").unwrap(); - assert!(fixture.check(Platform::Windows, &unrelated.join("Launcher/nightly/deckcraft")).is_ok()); - } - - #[test] - fn linux_fences_the_stable_flatpak_data_folder() { - let fixture = Fixture::new(); - let flatpak = fixture.home().join(".var/app/ai.storyteller.deckcraft"); - for candidate in [flatpak.clone(), flatpak.join("data/nightly")] { - assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("overlap")); - } - assert!(!flatpak.exists()); - assert!(fixture.check(Platform::Linux, &fixture.home().join(".var/app/ai.storyteller.launcher/nightly")).is_ok()); - } - - #[cfg(unix)] - #[test] - fn any_profile_entry_alias_must_stay_inside_the_profile() { - let fixture = Fixture::new(); - let stable = fixture.home().join(".config/deckcraft/logs"); - std::fs::create_dir_all(&stable).unwrap(); - std::fs::write(stable.join("stable-log"), b"stable log bytes").unwrap(); - for name in ["Dictionaries", "logs", "ui.json"] { - let private = fixture.root.join(format!("nightly-{name}")); - std::fs::create_dir(&private).unwrap(); - std::os::unix::fs::symlink(&stable, private.join(name)).unwrap(); - let probed = std::cell::Cell::new(false); - let result = validate_for( - Platform::Linux, - &private, - |key| fixture.get(key), - Some(&fixture.exe), - |_| { - probed.set(true); - Ok(()) - }, - ); - assert!(result.is_err(), "{name} must not lead outside the profile"); - assert!(!probed.get()); - } - let private = fixture.root.join("nightly-inside"); - std::fs::create_dir_all(private.join("real-dictionaries")).unwrap(); - std::fs::write(private.join("ui.json"), b"{}").unwrap(); - std::os::unix::fs::symlink(private.join("real-dictionaries"), private.join("Dictionaries")).unwrap(); - assert!(fixture.check(Platform::Linux, &private).is_ok(), "regular files and links that stay inside are fine"); - assert_eq!(std::fs::read(stable.join("stable-log")).unwrap(), b"stable log bytes"); - } - - #[test] - fn ambiguous_environment_and_non_native_sandbox_are_refused_before_creation() { - let mut fixture = Fixture::new(); - let candidate = fixture.home().join("nightly/profiles/deckcraft"); - fixture.env.insert("XDG_CACHE_HOME".into(), "relative/cache".into()); - assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("absolute")); - fixture.env.remove("XDG_CACHE_HOME"); - // The stable Flatpak instance, or any other app's, is not a Nightly launch. - fixture.env.insert("FLATPAK_ID".into(), "ai.storyteller.deckcraft".into()); - assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("Flatpak")); - fixture.env.insert("FLATPAK_ID".into(), "org.example.other".into()); - assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("Flatpak")); - // DeckCraft Nightly's own Flatpak is the one allowed instance. - fixture.env.insert("FLATPAK_ID".into(), NIGHTLY_FLATPAK_ID.into()); - assert!(fixture.check(Platform::Linux, &candidate).is_ok()); - fixture.env.remove("FLATPAK_ID"); - fixture.env.remove("HOME"); - assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("HOME")); - } - - #[test] - fn non_directory_and_failed_write_probe_never_fall_back_to_stable() { - let fixture = Fixture::new(); - let file = fixture.home().join("not-a-directory"); - std::fs::write(&file, b"regular file").unwrap(); - assert!(fixture.check(Platform::Linux, &file.join("nightly")).is_err()); - let candidate = fixture.home().join("nightly/profiles/deckcraft"); - let result = validate_for( - Platform::Linux, - &candidate, - |key| fixture.get(key), - Some(&fixture.exe), - |_| Err(std::io::Error::new(std::io::ErrorKind::PermissionDenied, "read-only")), - ); - assert!(result.unwrap_err().contains("not writable")); - assert!(!candidate.join("Recovery").exists(), "a failed probe leaves no stable fallback behind"); - } - - #[test] - fn relative_roots_and_parent_traversal_are_refused() { - let fixture = Fixture::new(); - for candidate in [PathBuf::from("relative/nightly"), fixture.home().join("nightly/../escape")] { - assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("absolute")); - } + let s = spec(); + assert!(matches!(validate_and_prepare_root(&profile, &s), Err(ProfileError::SymlinkEntry(_)))); } } From d3fce58facfdbf8354806daf6fd8776768dd77fa Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 29 Nov 2026 15:15:13 -0500 Subject: [PATCH 2/4] test(nightly): preserve saved state and refuse invalid profile startup (#2458) --- apps/deckcraft/src/profile_root.rs | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/apps/deckcraft/src/profile_root.rs b/apps/deckcraft/src/profile_root.rs index 7641cf840..5da30dffe 100644 --- a/apps/deckcraft/src/profile_root.rs +++ b/apps/deckcraft/src/profile_root.rs @@ -187,6 +187,9 @@ mod tests { std::fs::create_dir(prepared.join(dir_name)).unwrap(); } assert_eq!(validate_and_prepare_root(&profile, &s).unwrap(), prepared); + for name in ["ui.json", "prefs.json", "nightly-session.lock", "nightly-session.json"] { + assert_eq!(std::fs::read(prepared.join(name)).unwrap(), b"saved profile data", "{name} changed when reopening"); + } for dir_name in FOLDER_ONLY_ENTRIES { let entry = prepared.join(dir_name); @@ -198,6 +201,19 @@ mod tests { } } + #[test] + fn a_non_directory_profile_stops_startup_without_installing_a_profile() { + let temp = TempDir::new("invalid-root"); + let root = temp.path().join("ordinary-file"); + std::fs::write(&root, b"existing file").unwrap(); + let argv = craft_nightly::launch_arguments(&root, &[]); + assert!(craft_nightly::current().is_none()); + let result = crate::launch_profile::prepare(craft_nightly::BuildFlavor::NightlyV1, argv); + assert!(matches!(result, Err(ProfileError::NotADirectory(_)))); + assert!(craft_nightly::current().is_none()); + assert_eq!(std::fs::read(root).unwrap(), b"existing file"); + } + #[test] fn relative_and_traversal_profile_roots_are_refused() { let tmp = TempDir::new("lexical"); From 06bb0be9595918f041df78126e0486b3c2734f97 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 29 Nov 2026 15:47:10 -0500 Subject: [PATCH 3/4] ci(sonarcloud): give each main commit its own concurrency group (#2459) --- .github/workflows/sonarcloud.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/sonarcloud.yml b/.github/workflows/sonarcloud.yml index 285fd642f..d0d3ce111 100644 --- a/.github/workflows/sonarcloud.yml +++ b/.github/workflows/sonarcloud.yml @@ -10,7 +10,7 @@ permissions: contents: read concurrency: - group: sonarcloud-${{ github.ref }} + group: ${{ github.ref == 'refs/heads/main' && format('sonarcloud-main-{0}', github.sha) || format('sonarcloud-{0}', github.ref) }} # A push to main is the run that publishes coverage; superseded runs there would never finish. cancel-in-progress: ${{ github.ref != 'refs/heads/main' }} From 03365c2d7f5b26c26f96689a6b1a1778c8d789b4 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 29 Nov 2026 16:39:11 -0500 Subject: [PATCH 4/4] Enable automated nightly schedule (01:00 UTC) and Stage 2 signer dispatch (#2433) * Enable scheduled nightly builds and automatic Stage 2 signer dispatch * ci: update actions lockfile for nightly-dispatch.yml --- .github/nightly-signing-policy.json | 4 +- .github/workflows/actions.lock | 1 + .github/workflows/nightly-dispatch.yml | 72 ++++++++++++++++++++++++++ .github/workflows/nightly.yml | 6 ++- packaging/nightly-release-tests.py | 40 +++++++++++--- 5 files changed, 113 insertions(+), 10 deletions(-) create mode 100644 .github/workflows/nightly-dispatch.yml diff --git a/.github/nightly-signing-policy.json b/.github/nightly-signing-policy.json index cc13648ef..0eb1d65f8 100644 --- a/.github/nightly-signing-policy.json +++ b/.github/nightly-signing-policy.json @@ -88,7 +88,9 @@ } }, "max_artifact_bytes": 2147483648, - "automatic_signer_actors": [], + "automatic_signer_actors": [ + "github-actions[bot]" + ], "platforms": { "windows-x86_64": { "unsigned_artifact_name": "nightly-unsigned-windows-x86_64", diff --git a/.github/workflows/actions.lock b/.github/workflows/actions.lock index 5f9a6d7f1..6bcf04a45 100644 --- a/.github/workflows/actions.lock +++ b/.github/workflows/actions.lock @@ -11,6 +11,7 @@ workflows: '.github/workflows/lockfile.yml': - 'actions/checkout@v7.0.1' - 'step-security/harden-runner@v2.22.4' + '.github/workflows/nightly-dispatch.yml': [] '.github/workflows/nightly-macos.yml': - 'actions/checkout@v7.0.1' - 'step-security/harden-runner@v2.22.4' diff --git a/.github/workflows/nightly-dispatch.yml b/.github/workflows/nightly-dispatch.yml new file mode 100644 index 000000000..cd8166a73 --- /dev/null +++ b/.github/workflows/nightly-dispatch.yml @@ -0,0 +1,72 @@ +name: Dispatch release-ref nightly + +# Transport only, never authorization. No checkout, payload parsing or release environment. +on: + workflow_run: + workflows: [DeckCraft unsigned nightly] + types: [completed] + branches: [main] + +permissions: {} + +jobs: + dispatch: + # Actual context guards only; no checkout, release environment or platform secrets. + if: >- + github.repository == 'storytold/deckcraft' && + github.event_name == 'workflow_run' + runs-on: ubuntu-latest + timeout-minutes: 5 + permissions: + actions: write + steps: + - name: Dispatch only the exact completed producer run and attempt + shell: python + env: + GH_TOKEN: ${{ github.token }} + run: | + import json + import os + import urllib.request + + def require(value, message): + if not value: + raise RuntimeError(message) + + # These filters reduce noise; the protected signer-branch validator repeats admission + # against authenticated API metadata and required attestation/quality evidence. + require(os.environ.get('GITHUB_REPOSITORY') == 'storytold/deckcraft', 'wrong repository') + require(os.environ.get('GITHUB_EVENT_NAME') == 'workflow_run', 'wrong event') + with open(os.environ['GITHUB_EVENT_PATH'], encoding='utf-8') as stream: + event = json.load(stream) + require(event.get('action') == 'completed', 'producer is not complete') + require(event.get('repository', {}).get('full_name') == 'storytold/deckcraft', 'wrong event repository') + producer = event.get('workflow_run', {}) + require(producer.get('head_repository', {}).get('full_name') == 'storytold/deckcraft', 'foreign producer') + require(producer.get('path') == '.github/workflows/nightly.yml', 'wrong producer path') + require(producer.get('head_branch') == 'main', 'wrong producer branch') + require(producer.get('status') == 'completed' and producer.get('conclusion') == 'success', 'producer did not succeed') + # First scheduled attempt only; reviewed manual/re-run authority belongs to release policy. + require(producer.get('event') == 'schedule', 'not an automatic scheduled producer') + run_id, attempt = producer.get('id'), producer.get('run_attempt') + require(type(run_id) is int and run_id > 0, 'invalid producer run id') + require(type(attempt) is int and attempt == 1, 'invalid automatic producer attempt') + body = json.dumps({'ref': 'refs/heads/nightly-signer', 'inputs': { + 'producer_run_id': str(run_id), 'producer_run_attempt': str(attempt) + }}).encode('utf-8') + request = urllib.request.Request( + 'https://api.github.com/repos/storytold/deckcraft/actions/workflows/nightly-sign.yml/dispatches', + data=body, method='POST', headers={ + 'Authorization': 'Bearer ' + os.environ['GH_TOKEN'], + 'Accept': 'application/vnd.github+json', + 'Content-Type': 'application/json', + 'X-GitHub-Api-Version': '2022-11-28', + 'User-Agent': 'deckcraft-nightly-dispatch' + }) + class NoRedirect(urllib.request.HTTPRedirectHandler): + def redirect_request(self, req, fp, code, msg, headers, newurl): + raise RuntimeError('dispatch redirects are forbidden') + # One bounded request, no retry: duplicate transport is not publication authority. + with urllib.request.build_opener(NoRedirect()).open(request, timeout=20) as response: + require(response.status == 204, 'dispatch was not accepted') + print('Dispatched producer run/attempt to the release-ref validator; not a signing result.') diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index cc006fcf3..68d193e7a 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -1,8 +1,10 @@ name: DeckCraft 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). +# Runs on the reviewed nightly schedule (01:00 UTC) and for supervised manual runs +# by the reviewed manual actors. Completed scheduled runs are forwarded by nightly-dispatch.yml. on: + schedule: + - cron: '0 1 * * *' workflow_dispatch: permissions: diff --git a/packaging/nightly-release-tests.py b/packaging/nightly-release-tests.py index 1b597f963..a4df007c3 100755 --- a/packaging/nightly-release-tests.py +++ b/packaging/nightly-release-tests.py @@ -184,7 +184,7 @@ class TrustedSourcePreparation(unittest.TestCase): producer_platforms(source.replace(" " + current + "\n", "")) def test_continuation_lines_of_any_scalar_form_reach_the_guard_checks(self): - for name in ("nightly.yml", "nightly-sign.yml"): + for name in ("nightly.yml", "nightly-sign.yml", "nightly-dispatch.yml"): source = (ROOT / ".github/workflows" / name).read_text() expected = NightlyEnabledCallers.GUARDS[name] guard = re.search(r"(?m)^ if: >-\n(?: [^\n]*\n)+", source)[0] @@ -194,15 +194,39 @@ class TrustedSourcePreparation(unittest.TestCase): (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")): + def test_nightly_triggers_match_reviewed_schedule_and_dispatch(self): + expected = { + "nightly.yml": [" schedule:", " workflow_dispatch:"], + "nightly-sign.yml": [" workflow_dispatch:"], + "nightly-dispatch.yml": [" workflow_run:"], + } + for name, expected_triggers in expected.items(): 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") + self.assertEqual(triggers, expected_triggers, "schedule/activation needs explicit review") + producer = (ROOT / ".github/workflows/nightly.yml").read_text() + self.assertEqual(re.findall(r"(?m)^ - cron: (.+)$", producer), ["'0 1 * * *'"], + "nightly schedule must stay pinned to 01:00 UTC") + producer_name = re.findall(r"(?m)^name: (.+)$", producer) + dispatch = (ROOT / ".github/workflows/nightly-dispatch.yml").read_text() + self.assertEqual(producer_name, ["DeckCraft unsigned nightly"]) + self.assertIn(f" workflows: [{producer_name[0]}]\n", dispatch) + self.assertIn(" types: [completed]\n", dispatch) + self.assertIn(" branches: [main]\n", dispatch) + + def test_dispatch_workflow_stays_transport_only(self): + dispatch = (ROOT / ".github/workflows/nightly-dispatch.yml").read_text() + assert_caller_secrets(dispatch, "dispatch", set()) + self.assertIn("\npermissions: {}\n", dispatch) + self.assertNotRegex(dispatch, r"(?m)^\s*(?:-\s*)?uses:") + self.assertIn(f"'ref': 'refs/heads/{SIGNER_BRANCH}'", dispatch) + self.assertIn("https://api.github.com/repos/storytold/deckcraft/actions/workflows/nightly-sign.yml/dispatches", + dispatch) + self.assertIn("require(producer.get('event') == 'schedule'", dispatch) + self.assertIn("require(type(attempt) is int and attempt == 1", dispatch) def test_signer_serialization_contract_is_enforced(self): assert_nightly_serialization((ROOT / ".github/workflows/nightly-sign.yml").read_text()) @@ -232,7 +256,7 @@ class TrustedSourcePreparation(unittest.TestCase): 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"): + for name in ("nightly.yml", "nightly-sign.yml", "nightly-dispatch.yml"): source = (ROOT / ".github/workflows" / name).read_text() executable = "\n".join(line for line in source.splitlines() if not line.lstrip().startswith("#")) @@ -307,6 +331,7 @@ class NightlyEnabledCallers(unittest.TestCase): "github.event_name == 'workflow_dispatch')", "nightly-sign.yml": "github.repository == 'storytold/deckcraft' && github.event_name == 'workflow_dispatch' && " "github.ref == 'refs/heads/" + SIGNER_BRANCH + "' && github.ref_type == 'branch'", + "nightly-dispatch.yml": "github.repository == 'storytold/deckcraft' && github.event_name == 'workflow_run'", } def test_enabled_jobs_keep_exact_context_guards(self): @@ -323,7 +348,8 @@ class NightlyEnabledCallers(unittest.TestCase): 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") + self.assertEqual(policy["automatic_signer_actors"], ["github-actions[bot]"], + "automatic signer actor must be github-actions[bot]") def test_an_actor_outside_the_release_managers_is_refused(self): source = (ROOT / ".github/workflows/nightly.yml").read_text()