From cda0d046a74ecd5197b99ea24d05a55f014b77c1 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 29 Nov 2026 13:48:49 -0500 Subject: [PATCH] feat: use craft-nightly for nightly profile isolation (#4266) * feat: use craft-nightly for nightly profile isolation * fix(nightly): answer bare version queries before profile resolution * test: update version query unit test in main.rs for craft-nightly --- Cargo.lock | 9 + Cargo.toml | 1 + apps/effectcraft/Cargo.toml | 1 + apps/effectcraft/src/build_flavor.rs | 43 +- apps/effectcraft/src/crash_report.rs | 16 +- apps/effectcraft/src/launch_profile.rs | 230 +++----- apps/effectcraft/src/main.rs | 64 +- apps/effectcraft/src/profile_root.rs | 780 +++++-------------------- 8 files changed, 264 insertions(+), 880 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index d79dc2910..5c1947241 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1669,6 +1669,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-pcraft-format" version = "0.1.0" @@ -2464,6 +2472,7 @@ version = "0.26.0" dependencies = [ "chrono", "cpal", + "craft-nightly", "craft-update", "effectcraft-engine", "effectcraft-host", diff --git a/Cargo.toml b/Cargo.toml index 7e86ae717..d5b26c096 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -33,6 +33,7 @@ craft-doc = { version = "0.1.0", git = "https://github.com/storytold/craft-libs" craft-vectorcraft-format = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" } # craft-update: app-specific pretend versions apply to startup and manual checks. craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", features = ["ui"] } +craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "1f6c3a21f85ed96f8fd4ddd5a959d4e1edbedb24" } # internal effectcraft-time = { path = "crates/time" } effectcraft-geom = { path = "crates/geom" } diff --git a/apps/effectcraft/Cargo.toml b/apps/effectcraft/Cargo.toml index 528233d74..d921f1065 100644 --- a/apps/effectcraft/Cargo.toml +++ b/apps/effectcraft/Cargo.toml @@ -10,6 +10,7 @@ default-run = "effectcraft" workspace = true [dependencies] +craft-nightly = { workspace = true } effectcraft-engine = { workspace = true } effectcraft-host = { workspace = true } effectcraft-ui-egui = { workspace = true } diff --git a/apps/effectcraft/src/build_flavor.rs b/apps/effectcraft/src/build_flavor.rs index 80ac8fb28..3364538aa 100644 --- a/apps/effectcraft/src/build_flavor.rs +++ b/apps/effectcraft/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!(effectcraft_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 EffectCraft Nightly from ArtCraft Launcher".into()), - (BuildFlavor::Stable, true) => Err("This is a stable EffectCraft 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(), @@ -41,7 +23,8 @@ pub fn version_line(flavor: BuildFlavor, version: &str) -> String { #[cfg(test)] mod tests { - use super::*; + use super::{BuildFlavor, needs_native_error, version, version_line}; + #[test] fn only_a_nightly_desktop_refusal_requests_a_native_dialog() { assert!(needs_native_error(BuildFlavor::NightlyV1, true)); @@ -51,21 +34,7 @@ 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()); - } - #[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() { + fn nightly_version_line_is_unambiguous() { assert_eq!(version(BuildFlavor::Stable, "0.23.1"), "0.23.1"); assert_eq!(version(BuildFlavor::NightlyV1, "0.23.1"), "0.23.1 (nightly-v1)"); // The exact line the Launcher, the shared smoke test and the macOS verifier expect. @@ -74,9 +43,5 @@ mod tests { "EffectCraft 0.25.1-nightly.20261124.41.1.gabcdef012345 (nightly-v1)" ); assert_eq!(version_line(BuildFlavor::Stable, "0.25.1"), "EffectCraft 0.25.1"); - assert!(version_query(&["--version".into()])); - assert!(version_query(&["-V".into()])); - assert!(!version_query(&["--".into(), "--version".into()])); - assert!(!version_query(&[])); } } diff --git a/apps/effectcraft/src/crash_report.rs b/apps/effectcraft/src/crash_report.rs index b80e02372..622226ae3 100644 --- a/apps/effectcraft/src/crash_report.rs +++ b/apps/effectcraft/src/crash_report.rs @@ -131,7 +131,7 @@ pub fn helper_args(id: &str, log: Option<&Path>, reports: &Path, interactive: bo } /// Whether these arguments ask for the internal helper rather than a session. `main` must answer -/// this before the launch-profile bootstrap, which refuses a Nightly start with no profile. +/// this before the launch-profile bootstrap so the helper never prepares a Nightly profile root. pub fn is_helper(args: &[OsString]) -> bool { args.first().map(OsString::as_os_str) == Some(OsStr::new(FLAG)) } @@ -460,20 +460,18 @@ mod tests { assert!(path.is_file(), "report did not arrive: {}", path.display()); } - /// The helper re-runs this program with no profile tokens, so the Nightly flavor refuses that - /// argv as a bare start: `main` must answer the helper before the launch-profile bootstrap. + /// The helper re-runs this program with no profile tokens, so `main` must answer the helper + /// before the launch-profile bootstrap initializes a Nightly profile root. #[test] fn the_helper_command_line_is_recognized_before_the_launch_profile_bootstrap() { let dir = folder(); let args = helper_args("7-9", None, dir.as_path(), true); assert!(is_helper(&args)); assert!(args.iter().all(|arg| arg != "--launch-profile" && arg != "--profile-root")); - let parsed = crate::launch_profile::parse(args.to_vec()).unwrap(); - assert_eq!(parsed.profile, crate::launch_profile::Profile::Stable, "no profile tokens in the helper's argv"); - assert!( - crate::build_flavor::require_profile(crate::build_flavor::BuildFlavor::NightlyV1, &parsed.profile).is_err(), - "a Nightly build refuses the helper's argv as a session" - ); + let stable = crate::launch_profile::parse(crate::build_flavor::BuildFlavor::Stable, args.to_vec()).unwrap(); + assert_eq!(stable.profile, craft_nightly::Profile::Stable, "no profile tokens in the helper's argv"); + let nightly = crate::launch_profile::parse(crate::build_flavor::BuildFlavor::NightlyV1, args.to_vec()).unwrap(); + assert!(nightly.profile.is_nightly(), "otherwise Nightly bootstrap would self-isolate the helper"); // A session's own command line is never the helper's, before or after `--`. for session in [vec![], vec![OsString::from("--")], vec![OsString::from("--"), OsString::from(FLAG)]] { assert!(!is_helper(&session), "{session:?}"); diff --git a/apps/effectcraft/src/launch_profile.rs b/apps/effectcraft/src/launch_profile.rs index 055c8f970..314654aaf 100644 --- a/apps/effectcraft/src/launch_profile.rs +++ b/apps/effectcraft/src/launch_profile.rs @@ -1,212 +1,112 @@ -//! 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("effectcraft")`. use std::ffi::OsString; -use std::path::{Component, Path, PathBuf}; -use std::sync::OnceLock; +use std::path::Path; -pub const VERSION: &str = "nightly-v1"; +use craft_nightly::{BuildFlavor, Launch, ProfileError, StartupOptions}; -#[derive(Clone, Debug, PartialEq, Eq)] -pub enum Profile { - Stable, - NightlyV1(PathBuf), +pub fn current_root() -> Option<&'static Path> { + craft_nightly::current_root() } -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), - } - } +pub fn prepare(flavor: BuildFlavor, args: impl IntoIterator) -> Result { + craft_nightly::prepare_launch(flavor, &crate::profile_root::spec(), args, &StartupOptions::default()) } -#[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, effectcraft_host::app_dirs::ensure_writable) +#[cfg(test)] +pub fn parse(flavor: BuildFlavor, args: impl IntoIterator) -> Result { + craft_nightly::parse_startup(flavor, &crate::profile_root::spec(), args, &StartupOptions::default()) } #[cfg(test)] mod tests { - use super::*; - use std::cell::Cell; + use std::ffi::OsString; + use std::path::PathBuf; + + use craft_nightly::{BuildFlavor, Profile, ProfileError, canonical_profile_root}; + + use super::parse; + use crate::profile_root::APP_ID; + fn args(values: &[&str]) -> Vec { values.iter().map(OsString::from).collect() } + fn absolute() -> &'static str { if cfg!(windows) { r"C:\NightlyData\profiles\effectcraft" } else { "/nightly-data/profiles/effectcraft" } } + fn nightly() -> Vec { - args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--"]) + args(&["--launch-profile", "nightly-v1", "--profile-root", absolute(), "--"]) } #[test] fn stable_arguments_and_directory_policy_are_unchanged() { for argv in [args(&[]), args(&["--demo", "a.ecproj"]), args(&["--", "--launch-profile", "file.ecproj"])] { - 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(BuildFlavor::Stable, argv.clone()).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() { + fn stable_build_refuses_nightly_protocol_flags() { + let err = parse(BuildFlavor::Stable, nightly()).unwrap_err(); + assert!(matches!(err, ProfileError::NightlyFlagsInStableBuild)); + } + + #[test] + fn direct_nightly_launch_self_isolates_into_canonical_root_and_preserves_args() { + let expected_root = canonical_profile_root(APP_ID).unwrap(); + let user_args = args(&["--demo", "project.ecproj"]); + let launch = parse(BuildFlavor::NightlyV1, user_args.clone()).unwrap(); + assert_eq!(launch.profile, Profile::NightlyV1(expected_root)); + assert!(launch.profile.is_nightly()); + assert_eq!(launch.passthrough_args, user_args); + assert!(!launch.is_version_query()); + } + + #[test] + fn explicit_nightly_flags_override_canonical_root_and_preserve_file_names() { let mut argv = nightly(); argv.extend(args(&["--profile-root", "project with spaces.ecproj"])); - let launch = parse(argv).unwrap(); + let launch = parse(BuildFlavor::NightlyV1, argv).unwrap(); assert_eq!(launch.profile, Profile::NightlyV1(PathBuf::from(absolute()))); - assert_eq!(launch.args, args(&["--", "--profile-root", "project with spaces.ecproj"])); + assert_eq!(launch.passthrough_args, args(&["--profile-root", "project with spaces.ecproj"])); } #[test] - fn missing_duplicate_unknown_and_conflicting_profile_arguments_are_refused() { + fn missing_duplicate_unknown_and_misplaced_profile_arguments_are_refused() { for argv in [ - args(&["--launch-profile", VERSION]), + args(&["--launch-profile", "nightly-v1"]), 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", "--"]), - args(&["--launch-profile", VERSION, "--profile-root", absolute()]), - args(&[&format!("--launch-profile={VERSION}"), "--profile-root", absolute(), "--"]), + args(&["--launch-profile", "nightly-v1", "--launch-profile", "nightly-v1", "--profile-root", absolute(), "--"]), + args(&["--launch-profile", "nightly-v1", "--profile-root", absolute(), "--profile-root", absolute(), "--"]), + args(&["--launch-profile", "nightly-v1", "--profile-root", "", "--"]), + args(&["project.ecproj", "--profile-root", absolute()]), ] { - assert!(parse(argv).is_err()); + assert!(parse(BuildFlavor::NightlyV1, argv.clone()).is_err(), "{argv:?}"); } } #[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]; + fn version_queries_are_recognized_plain_and_via_launcher() { for flag in ["--version", "-V"] { - for form in [pair, reversed] { - let mut argv = args(form); - argv.push(flag.into()); - assert!(version_query(&argv), "{argv:?}"); - } - } - for argv in [ - args(&["--version"]), - args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--", "--version"]), - args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--"]), - args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--new-instance", "--version"]), - args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--version"]), - args(&["--version", "--launch-profile", VERSION, "--profile-root", absolute()]), - args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--version"]), - args(&["--launch-profile", VERSION, "--profile-root", "relative", "--version"]), - args(&["--launch-profile", VERSION, "--version"]), - args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--help"]), - ] { - assert!(!version_query(&argv), "{argv:?}"); - } - // Outside the query the strict protocol still refuses the version flag. - assert!(parse(args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version"])).is_err()); - } + let plain = parse(BuildFlavor::NightlyV1, args(&[flag])).unwrap(); + assert!(plain.is_version_query(), "plain {flag}"); - #[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()); - } + let launcher_plain = parse(BuildFlavor::NightlyV1, args(&["--launch-profile", "nightly-v1", "--profile-root", absolute(), flag])).unwrap(); + assert!(launcher_plain.is_version_query(), "launcher {flag}"); - #[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()); + let launcher_delimited = + parse(BuildFlavor::NightlyV1, args(&["--launch-profile", "nightly-v1", "--profile-root", absolute(), "--", flag])).unwrap(); + assert!(launcher_delimited.is_version_query(), "launcher -- {flag}"); + } + + let not_version = parse(BuildFlavor::NightlyV1, args(&["--launch-profile", "nightly-v1", "--profile-root", absolute(), "--help"])).unwrap(); + assert!(!not_version.is_version_query()); } } diff --git a/apps/effectcraft/src/main.rs b/apps/effectcraft/src/main.rs index 99f8f00ec..3e5289f37 100644 --- a/apps/effectcraft/src/main.rs +++ b/apps/effectcraft/src/main.rs @@ -111,43 +111,34 @@ fn report_launch_profile_error(error: &str) { } } -/// Whether this launch only asks for the version: the plain `--version`/`-V` query, or the -/// Launcher's profile preamble followed by it. The shared smoke test and the macOS verifier ask -/// the second form, and it answers without validating or touching the profile root. -fn version_query(argv: &[std::ffi::OsString]) -> bool { - build_flavor::version_query(argv) || launch_profile::version_query(argv) -} - /// Select the immutable launch profile, its data roots and its window identity before any startup /// service or side effect. `None` means the version query answered and the process is done. fn prepare_launch() -> Option> { - // The trusted Launcher protocol is decided before logging, the crash helper, fonts or prefs. + // The launch profile is decided before logging, the crash helper, fonts or prefs. let argv: Vec<_> = std::env::args_os().skip(1).collect(); - if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && version_query(&argv) { + // A bare version query is independent of profile-directory environment. + if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && matches!(argv.as_slice(), [arg] if arg == "--version" || arg == "-V") { + use std::io::Write as _; + let _ = writeln!(std::io::stdout(), "{}", build_flavor::version_line(build_flavor::COMPILED, env!("EFFECTCRAFT_BUILT_VERSION"))); + return None; + } + let early = launch_profile::prepare(build_flavor::COMPILED, argv).unwrap_or_else(|error| { + report_launch_profile_error(&error.to_string()); + std::process::exit(2) + }); + if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && early.is_version_query() { use std::io::Write as _; let _ = writeln!(std::io::stdout(), "{}", build_flavor::version_line(build_flavor::COMPILED, env!("EFFECTCRAFT_BUILT_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 identity = if early.profile.is_nightly() { effectcraft_ui_egui::channel::LaunchIdentity::NightlyV1 } else { effectcraft_ui_egui::channel::LaunchIdentity::Stable }; - let installed = launch_profile::install(early.profile) + let installed = initialize_nightly_process_identity() + .map_err(|error| error.to_string()) .and_then(|()| effectcraft_ui_egui::channel::select_identity(identity)) // One place redirects every data root: the settings folder (host) and, through it, logs, // Plug-ins, window state, recovery and the crash reports. - .and_then(|()| match launch_profile::current().root() { + .and_then(|()| match early.profile.root() { None => Ok(()), Some(root) => { let root = root.to_path_buf(); @@ -166,7 +157,7 @@ fn prepare_launch() -> Option> { std::process::exit(2); } effectcraft_ui_egui::channel::set_build_identity(env!("EFFECTCRAFT_BUILT_VERSION"), build_commit()); - Some(early.args) + Some(early.passthrough_args) } /// Whether a stable-only startup service may run: the updater, the control channel and the @@ -322,8 +313,7 @@ fn start_helpers_if_opted_in(session: &mut effectcraft_engine::Session) { /// reports startup failure through `startup_failed`. Returns the event loop's result. fn main() -> eframe::Result { // This program's own crash-reporter helper re-runs it with no profile tokens, so its mode is - // answered before the launch-profile bootstrap, which would refuse it as a bare Nightly start - // (a dialog, a 3 s readiness timeout and no crash reporting on every launch). + // answered before the launch-profile bootstrap so it never initializes a Nightly profile root. let raw: Vec = std::env::args_os().skip(1).collect(); if crash_report::maybe_run(&raw, |description| { file_dialogs::message("EffectCraft diagnostic report", description.to_owned()); @@ -437,7 +427,7 @@ fn run_desktop(reporter: &crash_report::Shutdown, arguments: &[std::ffi::OsStrin // A Nightly session records its own health in its private profile: a live lease plus an // unclean-exit record that the next owner reports. Stable has no such record. let (nightly_session, session_health_warning) = - match nightly_session::Session::begin_with_health(launch_profile::current().root(), env!("EFFECTCRAFT_BUILT_VERSION"), build_commit()) { + match nightly_session::Session::begin_with_health(launch_profile::current_root(), env!("EFFECTCRAFT_BUILT_VERSION"), build_commit()) { Ok(state) => state, Err(error) => { log::warn!("Nightly session health is unavailable: {error}"); @@ -852,24 +842,30 @@ mod tests { fn argv(values: &[&str]) -> Vec { values.iter().map(std::ffi::OsString::from).collect() } + fn is_nightly_version_query(query: Vec) -> bool { + crate::launch_profile::parse(crate::build_flavor::BuildFlavor::NightlyV1, query).is_ok_and(|launch| launch.is_version_query()) + } let root = if cfg!(windows) { r"C:\NightlyData\profiles\effectcraft" } else { "/nightly-data/profiles/effectcraft" }; - assert!(super::version_query(&argv(&["--version"]))); - assert!(super::version_query(&argv(&["-V"]))); - for form in [&["--launch-profile", "nightly-v1", "--profile-root", root][..], &["--profile-root", root, "--launch-profile", "nightly-v1"][..]] { + assert!(is_nightly_version_query(argv(&["--version"]))); + assert!(is_nightly_version_query(argv(&["-V"]))); + for form in [ + &["--launch-profile", "nightly-v1", "--profile-root", root][..], + &["--profile-root", root, "--launch-profile", "nightly-v1"][..], + &["--launch-profile", "nightly-v1", "--profile-root", root, "--"][..], + ] { for flag in ["--version", "-V"] { let mut query = argv(form); query.push(flag.into()); - assert!(super::version_query(&query), "{query:?}"); + assert!(is_nightly_version_query(query.clone()), "{query:?}"); } } for query in [ - argv(&["--launch-profile", "nightly-v1", "--profile-root", root, "--", "--version"]), argv(&["--launch-profile", "nightly-v1", "--profile-root", root]), argv(&["--launch-profile", "future-v2", "--profile-root", root, "--version"]), argv(&["--demo"]), argv(&[]), ] { - assert!(!super::version_query(&query), "{query:?}"); + assert!(!is_nightly_version_query(query.clone()), "{query:?}"); } } diff --git a/apps/effectcraft/src/profile_root.rs b/apps/effectcraft/src/profile_root.rs index 15d81ebd2..d7fd4e879 100644 --- a/apps/effectcraft/src/profile_root.rs +++ b/apps/effectcraft/src/profile_root.rs @@ -1,678 +1,192 @@ -//! App-owned nightly profile fences; no stable fallback, migration or process environment changes. +//! EffectCraft's `craft-nightly` isolation specification: stable paths, environment guards, +//! portable markers, folder-only entries, and platform-specific extra forbidden roots. use std::ffi::OsString; -use std::path::{Component, Path, PathBuf}; +use std::path::PathBuf; -use effectcraft_host::app_dirs::{PORTABLE_DATA_DIR, portable_marker}; +use craft_nightly::AppProfileSpec; +use effectcraft_host::app_dirs::PORTABLE_MARKERS; -/// The bundle id of EffectCraft's own Nightly Flatpak (`packaging/linux/flatpak-bundle.sh`). Its -/// sandbox is a separate installation; every other Flatpak instance (the stable app's included) -/// would point the profile at another install's state. -pub const NIGHTLY_FLATPAK_ID: &str = "ai.storyteller.effectcraft.nightly"; +pub const APP_ID: &str = "effectcraft"; +const DISPLAY_NAME: &str = "EffectCraft"; +const STABLE_DIR_NAMES: &[&str] = &["effectcraft", "EffectCraft"]; +const STABLE_PACKAGE_ID: &str = "ai.storyteller.effectcraft"; +const NIGHTLY_PACKAGE_ID: &str = "ai.storyteller.effectcraft.nightly"; +const FORBIDDEN_ENV_VARS: &[&str] = &["EFFECTCRAFT_CONFIG_DIR"]; +const FOLDER_ONLY_ENTRIES: &[&str] = &["Logs", "Plug-ins", "models", "helpers", "Caches", "Presets", "Scripts"]; -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum Platform { - Windows, - Linux, - Mac, +pub fn spec() -> AppProfileSpec { + spec_with_env(|key| std::env::var_os(key)) } -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(env: impl Fn(&str) -> Option) -> AppProfileSpec { + AppProfileSpec { + app_id: APP_ID, + display_name: DISPLAY_NAME, + stable_dir_names: STABLE_DIR_NAMES, + stable_package_id: STABLE_PACKAGE_ID, + nightly_package_id: NIGHTLY_PACKAGE_ID, + profile_root_env: None, + forbidden_env_vars: FORBIDDEN_ENV_VARS, + portable_markers: &PORTABLE_MARKERS, + folder_only_entries: FOLDER_ONLY_ENTRIES, + extra_forbidden_roots: extra_forbidden_roots(&env), + } +} + +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 { + let mut roots = Vec::new(); + + // The stable app's folder under Documents (`presets_dir` keeps `Presets` there, from HOME, + // else USERPROFILE). Fence the whole folder so Nightly never shares stable presets. + if let Some(home) = non_empty_abs(env, "HOME").or_else(|| non_empty_abs(env, "USERPROFILE")) { + roots.push(home.join("Documents").join("EffectCraft")); + } + + #[cfg(target_os = "windows")] + { + // 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 by craft-nightly. + if let Some(local) = non_empty_abs(env, "LOCALAPPDATA").or_else(|| non_empty_abs(env, "USERPROFILE").map(|p| p.join("AppData").join("Local"))) { + roots.push(local.join("Programs").join("ArtCraft").join("EffectCraft")); } - } - - 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("EffectCraft")); } - Err(error) => return Err(format!("cannot inspect the profile boundary: {error}")), } } - let mut resolved = std::fs::canonicalize(parent).map_err(|e| format!("cannot resolve the profile boundary: {e}"))?; - for part in missing.into_iter().rev() { - resolved.push(part); - } - Ok(resolved) -} -fn overlaps(a: &Path, b: &Path, platform: Platform) -> bool { - let parts = |p: &Path| { - p.components() - .map(|c| { - let value = c.as_os_str().to_string_lossy().into_owned(); - if platform.ignores_case() { value.to_lowercase() } else { value } - }) - .collect::>() - }; - let (a, b) = (parts(a), parts(b)); - a.starts_with(&b) || b.starts_with(&a) -} - -fn installation_boundary(platform: Platform, exe: &Path) -> Result { - let parent = exe.parent().ok_or("cannot establish the installation boundary")?; - if platform == Platform::Mac { - // A profile in Resources is still inside the versioned install, not beside MacOS. - if let Some(bundle) = exe.ancestors().find(|p| p.extension().is_some_and(|ext| ext.eq_ignore_ascii_case("app"))) { - return Ok(bundle.to_path_buf()); + #[cfg(all(unix, not(target_os = "macos")))] + { + roots.extend(["/usr/bin/effectcraft", "/usr/local/bin/effectcraft", "/opt/effectcraft"].map(PathBuf::from)); + // 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.effectcraft")); } } - 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 => { - // Settings and crash recovery live in the roaming folder; the disk cache, media cache - // and conformed audio in the local one (crates/render/src/disk_cache.rs). - let mut roots = - ["APPDATA", "LOCALAPPDATA"].into_iter().map(|key| required_base(env, key).map(|p| p.join("EffectCraft"))).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("EffectCraft")); - 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("EffectCraft")); - } - } - 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("effectcraft"))) - .collect::, _>>()?; - roots.extend(["/usr/bin/effectcraft", "/usr/local/bin/effectcraft", "/opt/effectcraft"].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.effectcraft")); - roots - } - Platform::Mac => { - let home = required_base(env, "HOME")?; + #[cfg(target_os = "macos")] + { + if let Some(home) = non_empty_abs(env, "HOME") { let library = home.join("Library"); - vec![ - library.join("Application Support/EffectCraft"), - library.join("Caches/EffectCraft"), - library.join("Caches/ai.storyteller.effectcraft"), - library.join("Preferences/EffectCraft"), - library.join("Preferences/ai.storyteller.effectcraft.plist"), - library.join("Saved Application State/ai.storyteller.effectcraft.savedState"), - home.join("Applications/EffectCraft.app"), - PathBuf::from("/Applications/EffectCraft.app"), - ] + roots.push(library.join("Preferences/ai.storyteller.effectcraft.plist")); + roots.push(library.join("Saved Application State/ai.storyteller.effectcraft.savedState")); + roots.push(home.join("Applications/EffectCraft.app")); } - }; - // The stable app's folder under Documents (`presets_dir` keeps `Presets` there, from HOME, else - // USERPROFILE). Fence the whole folder: a Nightly root at, above or inside it would share the - // stable app's presets, and any Nightly root below Documents/EffectCraft is not this channel's. - if let Some(home) = env("HOME").filter(|v| !v.is_empty()).or_else(|| env("USERPROFILE").filter(|v| !v.is_empty())) { - roots.push(absolute(PathBuf::from(home), "HOME")?.join("Documents").join("EffectCraft")); + roots.push(PathBuf::from("/Applications/EffectCraft.app")); } - roots.push(installation_boundary(platform, exe)?); - roots.into_iter().map(|p| canonical_future(&p)).collect() -} -/// Every existing entry directly in the profile (settings, Plug-ins, Logs 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(()) + roots } -/// 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(()) -} - -fn private_subdirectory(root: &Path, name: impl AsRef, label: &str) -> Result { - let entry = canonical_future(&root.join(name))?; - if entry == root || !entry.starts_with(root) { - return Err(format!("the nightly {label} must stay inside its selected profile")); - } - if !entry.is_dir() { - return Err(format!("the nightly {label} must be a directory")); - } - Ok(entry) -} - -/// Recognise the shared portable data namespace in both the supplied and resolved path. -/// This is not an inventory of arbitrary custom Stable overrides or a Launcher ownership proof. -fn is_portable_layout(path: &Path, platform: Platform) -> bool { - // A folder under a portable copy belongs to that copy too. Above the chosen folder itself, a - // marker only counts beside an EffectCraft executable, so an unrelated portable.txt higher up - // (in a user folder or at a drive root) does not refuse the profile. - path.ancestors().enumerate().any(|(depth, ancestor)| { - portable_marker(ancestor).is_some() && (depth == 0 || ["effectcraft.exe", "effectcraft"].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 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 env("EFFECTCRAFT_CONFIG_DIR").is_some_and(|v| !v.is_empty()) { - return Err("nightly-v1 cannot be combined with EFFECTCRAFT_CONFIG_DIR".into()); - } - // The Nightly ships its own Flatpak, so that one sandbox may carry a profile. Any other - // instance (the stable app's, or a foreign one) names another installation's state. - if let Some(instance) = env("FLATPAK_ID").filter(|value| !value.is_empty()) - && instance.to_string_lossy() != NIGHTLY_FLATPAK_ID - { - return Err(format!("nightly-v1 accepts only the {NIGHTLY_FLATPAK_ID} Flatpak instance; launch the Nightly from its own package")); - } - 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 EffectCraft installation or its EffectCraftData settings folder".into()); - } - let exe = absolute(exe.ok_or("cannot establish the installation boundary")?.to_path_buf(), "the executable")?; - let forbidden = forbidden_roots(platform, &env, &exe)?; - if forbidden.iter().any(|stable| overlaps(&chosen, stable, platform)) { - return Err("the nightly root must not overlap stable data or an installation".into()); - } - // Existing aliases under the profile must not redirect any of the app's writes elsewhere. - entries_stay_inside(&chosen)?; - let mut create = std::fs::DirBuilder::new(); - create.recursive(true); - #[cfg(unix)] - { - use std::os::unix::fs::DirBuilderExt as _; - create.mode(0o700); - } - create.create(&chosen).map_err(|e| format!("cannot create the nightly profile: {e}"))?; - let confirmed = std::fs::canonicalize(&chosen).map_err(|e| format!("cannot resolve the created nightly profile: {e}"))?; - if confirmed != chosen || forbidden.iter().any(|stable| overlaps(&confirmed, stable, platform)) { - return Err("the nightly profile changed while it was being validated".into()); - } - entries_stay_inside(&confirmed)?; - writable(&confirmed).map_err(|e| format!("the nightly profile is not writable: {e}"))?; - Ok(confirmed) -} - -const PROFILE_FOLDERS: [&str; 7] = ["Logs", "Plug-ins", "models", "helpers", "Caches", "Presets", "Scripts"]; - #[cfg(test)] mod tests { - use super::*; - use effectcraft_host::app_dirs::PORTABLE_MARKERS; use std::collections::BTreeMap; - use std::sync::atomic::{AtomicU64, Ordering}; + use std::ffi::OsString; - struct Fixture { - root: PathBuf, - env: BTreeMap, - exe: PathBuf, - } + use craft_nightly::{ProfileError, validate_and_prepare_root}; + use effectcraft_host::app_dirs::PORTABLE_MARKERS; - impl Fixture { - fn new() -> Self { - static NEXT: AtomicU64 = AtomicU64::new(0); - let root = loop { - let candidate = - std::env::temp_dir().join(format!("effectcraft-profile-policy-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed))); - match std::fs::create_dir(&candidate) { - Ok(()) => break std::fs::canonicalize(candidate).unwrap(), - Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue, - Err(error) => panic!("cannot create owned fixture: {error}"), - } - }; - let home = root.join("home"); - let exe = root.join("install/effectcraft"); - 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 } + use super::{APP_ID, FOLDER_ONLY_ENTRIES, FORBIDDEN_ENV_VARS, NIGHTLY_PACKAGE_ID, STABLE_DIR_NAMES, STABLE_PACKAGE_ID, spec_with_env}; + + #[test] + fn spec_preserves_effectcraft_constants_and_extra_forbidden_roots() { + let temp = tempfile::tempdir().unwrap(); + let base = std::fs::canonicalize(temp.path()).unwrap(); + let home = base.join("home"); + let local = base.join("local"); + let program_files = base.join("program-files"); + + let mut env = BTreeMap::<&str, OsString>::new(); + env.insert("HOME", home.clone().into_os_string()); + env.insert("LOCALAPPDATA", local.clone().into_os_string()); + env.insert("ProgramFiles", program_files.clone().into_os_string()); + + let spec = spec_with_env(|key| env.get(key).cloned()); + assert_eq!(spec.app_id, APP_ID); + assert_eq!(spec.display_name, "EffectCraft"); + assert_eq!(spec.stable_dir_names, STABLE_DIR_NAMES); + assert_eq!(spec.stable_package_id, STABLE_PACKAGE_ID); + assert_eq!(spec.nightly_package_id, NIGHTLY_PACKAGE_ID); + assert_eq!(spec.profile_root_env, None); + assert_eq!(spec.forbidden_env_vars, FORBIDDEN_ENV_VARS); + assert_eq!(spec.portable_markers, &PORTABLE_MARKERS); + assert_eq!(spec.folder_only_entries, FOLDER_ONLY_ENTRIES); + assert!(spec.extra_forbidden_roots.contains(&home.join("Documents").join("EffectCraft"))); + + #[cfg(all(unix, not(target_os = "macos")))] + { + assert!(spec.extra_forbidden_roots.contains(&std::path::PathBuf::from("/usr/bin/effectcraft"))); + assert!(spec.extra_forbidden_roots.contains(&std::path::PathBuf::from("/usr/local/bin/effectcraft"))); + assert!(spec.extra_forbidden_roots.contains(&std::path::PathBuf::from("/opt/effectcraft"))); + assert!(spec.extra_forbidden_roots.contains(&home.join(".var/app/ai.storyteller.effectcraft"))); } - fn get(&self, key: &str) -> Option { - self.env.get(key).cloned() + #[cfg(target_os = "macos")] + { + let library = home.join("Library"); + assert!(spec.extra_forbidden_roots.contains(&library.join("Preferences/ai.storyteller.effectcraft.plist"))); + assert!(spec.extra_forbidden_roots.contains(&library.join("Saved Application State/ai.storyteller.effectcraft.savedState"))); + assert!(spec.extra_forbidden_roots.contains(&home.join("Applications/EffectCraft.app"))); + assert!(spec.extra_forbidden_roots.contains(&std::path::PathBuf::from("/Applications/EffectCraft.app"))); } - fn check(&self, platform: Platform, root: &Path) -> Result { - validate_for( - platform, - root, - |key| self.get(key), - Some(&self.exe), - |dir| { - let probe = dir.join("exclusive-test-probe"); - let file = std::fs::OpenOptions::new().write(true).create_new(true).open(&probe)?; - drop(file); - std::fs::remove_file(probe) - }, - ) - } - - fn home(&self) -> PathBuf { - PathBuf::from(self.get("HOME").unwrap()) - } - } - - impl Drop for Fixture { - fn drop(&mut self) { - // Only the directory successfully created by this fixture is owned for removal. - std::fs::remove_dir_all(&self.root).unwrap(); + #[cfg(target_os = "windows")] + { + assert!(spec.extra_forbidden_roots.contains(&local.join("Programs").join("ArtCraft").join("EffectCraft"))); + assert!(spec.extra_forbidden_roots.contains(&program_files.join("ArtCraft").join("EffectCraft"))); } } #[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_MARKERS[0]), 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"); - } - } - let private = fixture.root.join("EffectCraftData-backup-name/nightly"); - assert!(fixture.check(Platform::Linux, &private).is_ok(), "a merely similar name is not a portable settings component"); - } + fn nightly_profile_validates_reopens_and_enforces_folder_only_and_extra_fences() { + let temp = tempfile::tempdir().unwrap(); + let base = std::fs::canonicalize(temp.path()).unwrap(); + let fake_home = base.join("home"); + std::fs::create_dir_all(&fake_home).unwrap(); - #[cfg(unix)] - #[test] - fn settings_aliases_cannot_redirect_to_stable_missing_or_profile_root_data() { - let fixture = Fixture::new(); - let stable = fixture.home().join(".config/effectcraft/Plug-ins"); - std::fs::create_dir_all(&stable).unwrap(); - std::fs::write(stable.join("stable-plugin.wasm"), b"stable plugin bytes").unwrap(); - for (index, target) in [stable.clone(), fixture.root.join("missing 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("Plug-ins")).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(), "a profile entry must not escape the 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("Logs")).unwrap(); - assert!(fixture.check(Platform::Linux, &private).is_err(), "an entry cannot resolve to the profile itself"); - assert_eq!(std::fs::read(stable.join("stable-plugin.wasm")).unwrap(), b"stable plugin bytes"); - } + let mut env = BTreeMap::<&str, OsString>::new(); + env.insert("HOME", fake_home.clone().into_os_string()); + let spec = spec_with_env(|key| env.get(key).cloned()); - #[cfg(unix)] - #[test] - fn an_alias_to_a_private_subfolder_keeps_the_profile_usable() { - let fixture = Fixture::new(); - let private = fixture.root.join("nightly-private"); - let logs = private.join("private-logs"); - std::fs::create_dir_all(&logs).unwrap(); - std::os::unix::fs::symlink(&logs, private.join("Logs")).unwrap(); - assert!(fixture.check(Platform::Linux, &private).is_ok()); - assert_eq!(std::fs::canonicalize(private.join("Logs")).unwrap(), logs); - } + // Stable Documents/EffectCraft fence is enforced before directory creation. + let presets_overlap = fake_home.join("Documents/EffectCraft/nightly"); + assert!(matches!(validate_and_prepare_root(&presets_overlap, &spec), Err(ProfileError::ForbiddenRootOverlap { .. }))); + assert!(!presets_overlap.exists()); - #[test] - fn overlap_check_handles_ancestor_descendant_and_prefix_lookalikes() { - let fixture = Fixture::new(); - let root = fixture.home().join("nightly/profiles/effectcraft"); - for platform in [Platform::Windows, Platform::Linux, Platform::Mac] { - assert!(overlaps(&root, &root.join("Plug-ins"), platform)); - assert!(overlaps(&root.join("Plug-ins"), &root, platform)); - assert!(!overlaps(&root, &root.with_file_name("effectcraft-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("effectcraft"); - 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/effectcraft"); - 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 ["settings.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("settings.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/EffectCraft Nightly.app/Contents/MacOS/EffectCraft"); - 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/EffectCraft", - "Caches/EffectCraft", - "Caches/ai.storyteller.effectcraft", - "Preferences/EffectCraft", - "Saved Application State/ai.storyteller.effectcraft.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/effectcraft"); - 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("EffectCraft"); - 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/effectcraft")).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("EffectCraft"); - 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("EffectCraft"); - 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("effectcraft"); - assert!(fixture.check(Platform::Windows, &sibling).is_ok(), "the Launcher's own Programs sibling is not EffectCraft'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/EC"); - std::fs::create_dir_all(&portable).unwrap(); - std::fs::write(portable.join(PORTABLE_MARKERS[1]), b"stable portable copy").unwrap(); - std::fs::write(portable.join("effectcraft.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 marker that no EffectCraft 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_MARKERS[0]), b"another app's marker").unwrap(); - assert!(fixture.check(Platform::Windows, &unrelated.join("Launcher/nightly/effectcraft")).is_ok()); - } - - #[test] - fn the_stable_presets_folder_is_fenced_on_every_platform() { - let fixture = Fixture::new(); - let documents = fixture.home().join("Documents"); - for platform in [Platform::Windows, Platform::Linux, Platform::Mac] { - for candidate in [documents.join("EffectCraft"), documents.join("EffectCraft/Presets"), documents.join("EffectCraft/nightly")] { - assert!(fixture.check(platform, &candidate).unwrap_err().contains("overlap"), "{platform:?} {candidate:?}"); - assert!(!candidate.exists()); - } - } - assert!(fixture.check(Platform::Linux, &documents.join("EffectCraft Nightly")).is_ok(), "a sibling folder stays valid"); - } - - #[test] - fn linux_fences_the_stable_flatpak_data_folder() { - let fixture = Fixture::new(); - let flatpak = fixture.home().join(".var/app/ai.storyteller.effectcraft"); - 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()); - } - - #[test] - fn ambiguous_environment_and_non_native_sandbox_are_refused_before_creation() { - let mut fixture = Fixture::new(); - let candidate = fixture.home().join("nightly/profiles/effectcraft"); - fixture.env.insert("XDG_CACHE_HOME".into(), "relative/cache".into()); - assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("absolute")); - fixture.env.remove("XDG_CACHE_HOME"); - fixture.env.insert("EFFECTCRAFT_CONFIG_DIR".into(), fixture.home().join("custom-stable").into_os_string()); - assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("EFFECTCRAFT_CONFIG_DIR")); - fixture.env.remove("EFFECTCRAFT_CONFIG_DIR"); - fixture.env.insert("FLATPAK_ID".into(), "ai.storyteller.effectcraft".into()); - assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("Flatpak")); - fixture.env.remove("FLATPAK_ID"); - fixture.env.remove("HOME"); - assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("HOME")); - assert!(!candidate.exists()); - } - - #[test] - fn only_the_nightly_s_own_flatpak_instance_may_carry_a_profile() { - // Inside packaging/linux/flatpak-bundle.sh's sandbox, $HOME is this app id's own folder, so - // the launcher's profile is the Nightly's state and nothing else is reachable through it. - let mut fixture = Fixture::new(); - fixture.env.insert("FLATPAK_ID".into(), NIGHTLY_FLATPAK_ID.into()); - let candidate = fixture.home().join(".local/share/effectcraft-nightly"); - assert_eq!(fixture.check(Platform::Linux, &candidate).unwrap(), std::fs::canonicalize(&candidate).unwrap()); - fixture.env.remove("FLATPAK_ID"); - for refused in ["ai.storyteller.effectcraft", "ai.storyteller.effectcraft.nightly-v1", "org.example.other"] { - let mut other = Fixture::new(); - other.env.insert("FLATPAK_ID".into(), refused.into()); - let refused_root = other.home().join(".local/share/effectcraft-nightly"); - assert!(other.check(Platform::Linux, &refused_root).unwrap_err().contains("Flatpak"), "{refused}"); - assert!(!refused_root.exists()); - } - } - - #[test] - fn non_directory_and_failed_write_probe_never_fall_back_to_stable() { - let fixture = Fixture::new(); - let file = fixture.home().join("not-a-directory"); - std::fs::write(&file, b"occupied").unwrap(); - assert!(fixture.check(Platform::Linux, &file).is_err()); - let refused = fixture.home().join("read-only-profile"); - assert!( - validate_for( - Platform::Linux, - &refused, - |key| fixture.get(key), - Some(&fixture.exe), - |_| { Err(std::io::Error::new(std::io::ErrorKind::PermissionDenied, "synthetic read-only profile")) } - ) - .unwrap_err() - .contains("not writable") - ); - assert!(!fixture.home().join(".config/effectcraft").exists(), "no stable fallback was created"); - } - - #[test] - fn created_profile_is_private_and_resolved() { - let fixture = Fixture::new(); - let target = fixture.home().join("nightly/profiles/effectcraft"); - let resolved = fixture.check(Platform::Linux, &target).unwrap(); - assert_eq!(resolved, target); + // Valid isolated root is created (0o700 on Unix) and reopens cleanly with settings + folders. + let profile = base.join("nightly/profiles/effectcraft"); + let resolved = validate_and_prepare_root(&profile, &spec).unwrap(); + assert_eq!(resolved, profile); assert!(resolved.is_dir()); #[cfg(unix)] { use std::os::unix::fs::PermissionsExt as _; assert_eq!(std::fs::metadata(&resolved).unwrap().permissions().mode() & 0o777, 0o700); } + + for name in ["settings.json", "nightly-session.lock", "nightly-session.json"] { + std::fs::write(resolved.join(name), b"saved profile data").unwrap(); + } + for name in FOLDER_ONLY_ENTRIES { + std::fs::create_dir(resolved.join(name)).unwrap(); + } + assert_eq!(validate_and_prepare_root(&profile, &spec).unwrap(), resolved); + + // Replacing a folder-only entry with a regular file is refused. + let logs = resolved.join("Logs"); + std::fs::remove_dir(&logs).unwrap(); + std::fs::write(&logs, b"not a directory").unwrap(); + assert!(matches!(validate_and_prepare_root(&profile, &spec), Err(ProfileError::ExpectedDirectoryEntry(_)))); } }