diff --git a/Cargo.lock b/Cargo.lock index e701b0632..d780844ed 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1605,6 +1605,14 @@ dependencies = [ "serde", ] +[[package]] +name = "craft-nightly" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=9949e08d6f29b6c4462f14af1d5007acac163dbf#9949e08d6f29b6c4462f14af1d5007acac163dbf" +dependencies = [ + "winsafe", +] + [[package]] name = "craft-pdf" version = "0.1.0" @@ -2771,6 +2779,7 @@ dependencies = [ "chrono", "craft-control", "craft-menu", + "craft-nightly", "craft-settings", "craft-update", "craft-window", diff --git a/Cargo.toml b/Cargo.toml index e470e8740..d8239ba64 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -67,6 +67,8 @@ craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "9949e08d6 craft-menu = { git = "https://github.com/storytold/craft-libs", rev = "9949e08d6f29b6c4462f14af1d5007acac163dbf" } # Where the settings live: the suite's folder rules, portable mode included (craft-libs). craft-settings = { git = "https://github.com/storytold/craft-libs", rev = "9949e08d6f29b6c4462f14af1d5007acac163dbf" } +# Nightly profile isolation, launch protocol, and security fence (craft-libs). +craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "9949e08d6f29b6c4462f14af1d5007acac163dbf" } # Penpot export container only; JSON values cross this boundary, not shared model types. craft-penpot = { git = "https://github.com/storytold/craft-libs", rev = "9949e08d6f29b6c4462f14af1d5007acac163dbf" } diff --git a/apps/figcraft/Cargo.toml b/apps/figcraft/Cargo.toml index e34519ed6..12c1ab281 100644 --- a/apps/figcraft/Cargo.toml +++ b/apps/figcraft/Cargo.toml @@ -21,6 +21,8 @@ figcraft-text = { workspace = true } craft-window = { workspace = true } # The suite's settings folder: `FIGCRAFT_CONFIG_DIR`, a portable marker, then the platform folder. craft-settings = { workspace = true } +# Shared nightly profile isolation, launch protocol, and security fence. +craft-nightly = { workspace = true } # The control channel's token and the ArtCraft Launcher's agents switch (src/agents.rs). craft-control = { workspace = true } chrono = { workspace = true } diff --git a/apps/figcraft/src/build_flavor.rs b/apps/figcraft/src/build_flavor.rs index 9a75783f7..795f5d705 100644 --- a/apps/figcraft/src/build_flavor.rs +++ b/apps/figcraft/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!(figcraft_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 FigCraft Nightly from ArtCraft Launcher".into()), - (BuildFlavor::Stable, true) => Err("This is a stable FigCraft 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,8 @@ pub fn version(flavor: BuildFlavor, stable: &str) -> String { #[cfg(test)] mod tests { - use super::*; + use super::{BuildFlavor, needs_native_error, version}; + #[test] fn only_a_nightly_desktop_refusal_requests_a_native_dialog() { assert!(needs_native_error(BuildFlavor::NightlyV1, true)); @@ -45,26 +28,8 @@ 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_string_is_distinct_from_stable() { assert_eq!(version(BuildFlavor::Stable, "0.18.1"), "0.18.1"); assert_eq!(version(BuildFlavor::NightlyV1, "0.18.1"), "0.18.1 (nightly-v1)"); - assert!(version_query(&["--version".into()])); - assert!(version_query(&["-V".into()])); - assert!(!version_query(&["--".into(), "--version".into()])); - assert!(!version_query(&[])); } } diff --git a/apps/figcraft/src/launch_profile.rs b/apps/figcraft/src/launch_profile.rs index a0adc8619..908748dd3 100644 --- a/apps/figcraft/src/launch_profile.rs +++ b/apps/figcraft/src/launch_profile.rs @@ -1,215 +1,131 @@ -//! 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 profile bootstrap backed by `craft-nightly`. Selected before logging, updates, +//! fonts or saved state. Direct launches of a nightly build self-isolate into +//! `craft_nightly::canonical_profile_root("figcraft")`; explicit `--launch-profile nightly-v1 +//! --profile-root ` overrides it. Stable launches retain their original arguments and +//! directory policy. use std::ffi::OsString; -use std::path::{Component, Path, PathBuf}; -use std::sync::OnceLock; -pub const VERSION: &str = "nightly-v1"; +use craft_nightly::StartupOptions; +pub use craft_nightly::{Launch, Profile, ProfileError}; -#[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(); +static STABLE: Profile = Profile::Stable; pub fn current() -> &'static Profile { - PROFILE.get().unwrap_or(&Profile::Stable) + craft_nightly::current().unwrap_or(&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. -/// -/// Every other flag is refused for a nightly launch, which is how Nightly stays away from the -/// control channel and the automation roots the stable app can be started with. -pub fn parse(args: Vec) -> Result { - let mut selector = None; - let mut root = None; - let mut other = Vec::new(); - let mut files = Vec::new(); - let mut iter = args.iter(); - let mut delimiter = false; - while let Some(arg) = iter.next() { - if arg == "--" { - delimiter = true; - files.extend(iter.cloned()); - break; - } - if arg == "--launch-profile" || arg == "--profile-root" { - let slot = if arg == "--launch-profile" { &mut selector } else { &mut root }; - if slot.is_some() { - return Err("the profile selector and root must each occur exactly once".into()); - } - let value = iter.next().filter(|v| !v.is_empty()).ok_or("the profile selector/root needs a value")?; - if value.to_string_lossy().starts_with("--") { - return Err("the profile selector/root needs a value".into()); - } - *slot = Some(value.clone()); - } else if arg.to_string_lossy().starts_with("--launch-profile=") || arg.to_string_lossy().starts_with("--profile-root=") { - return Err("the nightly protocol requires separate literal selector/root argument tokens".into()); - } else { - other.push(arg.clone()); - } - } - match (selector, root) { - (None, None) => Ok(Launch { profile: Profile::Stable, args }), - (Some(version), Some(root)) if version == VERSION => { - if !delimiter || !other.is_empty() { - return Err("nightly-v1 accepts only its selector/root followed by -- and file names".into()); - } - let root = PathBuf::from(root); - if !root.is_absolute() || root.components().any(|c| matches!(c, Component::ParentDir)) { - return Err("the nightly profile root must be absolute and contain no parent traversal".into()); - } - Ok(Launch { profile: Profile::NightlyV1(root), args: std::iter::once(OsString::from("--")).chain(files).collect() }) - } - (Some(_), Some(_)) => Err("unsupported launch profile (expected nightly-v1)".into()), - _ => Err("--launch-profile and --profile-root must be supplied together".into()), - } -} - -/// The Launcher's version check: the selector/root pair followed by exactly `--version` (or `-V`), -/// answered like a plain version query. Only [`parse`]'s lexical checks apply; the root is never -/// validated or touched, and `-- --version` stays a file name. -pub fn version_query(args: &[OsString]) -> bool { - let Some((last, pair)) = args.split_last() else { return false }; - if last != "--version" && last != "-V" { - return false; - } - let lexical = pair.iter().cloned().chain(std::iter::once(OsString::from("--"))).collect(); - matches!(parse(lexical), Ok(Launch { profile: Profile::NightlyV1(_), args }) if args.len() == 1) -} - -/// Validation finishes before the caller's first startup effect. Stable never calls the nightly -/// root validator, so its old portable/config resolution stays unchanged. -pub fn prepare(mut launch: Launch, validate: impl FnOnce(&Path) -> Result) -> Result { - if let Profile::NightlyV1(root) = &launch.profile { - launch.profile = Profile::NightlyV1(validate(root)?); - } - Ok(launch) -} - -/// Resolve the selected private root before the caller's first startup effect. -pub fn validate_root(root: &Path, env: impl Fn(&str) -> Option, exe: Option<&Path>) -> Result { - crate::profile_root::validate(root, env, exe, crate::profile_root::ensure_writable) +pub fn prepare(flavor: crate::build_flavor::BuildFlavor, args: impl IntoIterator) -> Result { + let spec = crate::profile_root::spec(); + craft_nightly::prepare_launch(flavor, &spec, args, &StartupOptions::new()) } #[cfg(test)] mod tests { - use super::*; - use std::cell::Cell; + use std::ffi::OsString; + use std::path::PathBuf; + + use craft_nightly::{NIGHTLY_V1_CONTRACT, StartupOptions, canonical_profile_root, parse_startup}; + + use super::{Profile, ProfileError, current, prepare}; + use crate::build_flavor::BuildFlavor; + use crate::profile_root; + fn args(values: &[&str]) -> Vec { values.iter().map(OsString::from).collect() } + fn absolute() -> &'static str { if cfg!(windows) { r"C:\NightlyData\profiles\figcraft" } else { "/nightly-data/profiles/figcraft" } } - fn nightly() -> Vec { - args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--"]) + + #[test] + fn direct_nightly_launch_self_isolates_to_canonical_profile_root_and_preserves_args() { + let spec = profile_root::spec_with(|_| None); + let expected = canonical_profile_root(profile_root::APP_ID).unwrap(); + let launch = parse_startup(BuildFlavor::NightlyV1, &spec, args(&["a.figcraft", "b.figcraft"]), &StartupOptions::new()).unwrap(); + assert_eq!(launch.profile, Profile::NightlyV1(expected)); + assert!(launch.profile.is_nightly()); + assert_eq!(launch.passthrough_args, args(&["a.figcraft", "b.figcraft"])); + assert!(!launch.is_version_query()); } #[test] - fn stable_arguments_and_directory_policy_are_unchanged() { - for argv in [args(&[]), args(&["--control", "8765", "a.figcraft"]), args(&["--", "--launch-profile", "file.figcraft"])] { - let launch = prepare(parse(argv.clone()).unwrap(), |_| panic!("stable must never validate a nightly root")).unwrap(); - assert_eq!(launch, Launch { profile: Profile::Stable, args: argv }); - } - } - - #[test] - fn exact_version_and_root_are_parsed_without_reinterpreting_file_names() { - let mut argv = nightly(); - argv.extend(args(&["--profile-root", "image with spaces.figcraft"])); - let launch = parse(argv).unwrap(); + fn explicit_nightly_flags_override_canonical_root_and_preserve_file_names() { + let spec = profile_root::spec_with(|_| None); + let argv = + args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--", "--profile-root", "image with spaces.figcraft"]); + let launch = parse_startup(BuildFlavor::NightlyV1, &spec, argv, &StartupOptions::new()).unwrap(); assert_eq!(launch.profile, Profile::NightlyV1(PathBuf::from(absolute()))); - assert_eq!(launch.args, args(&["--", "--profile-root", "image with spaces.figcraft"])); + assert_eq!(launch.passthrough_args, args(&["--profile-root", "image with spaces.figcraft"])); } #[test] - fn missing_duplicate_unknown_and_conflicting_profile_arguments_are_refused() { + fn stable_build_keeps_arguments_and_refuses_nightly_flags() { + let spec = profile_root::spec_with(|_| None); + for argv in [args(&[]), args(&["--control", "8765", "a.figcraft"]), args(&["--", "--launch-profile", "file.figcraft"])] { + let launch = parse_startup(BuildFlavor::Stable, &spec, argv.clone(), &StartupOptions::new()).unwrap(); + assert_eq!(launch.profile, Profile::Stable); + assert_eq!(launch.passthrough_args, argv); + } + let nightly = args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--"]); + assert!(matches!(parse_startup(BuildFlavor::Stable, &spec, nightly, &StartupOptions::new()), Err(ProfileError::NightlyFlagsInStableBuild))); + } + + #[test] + fn missing_duplicate_unsupported_and_misplaced_profile_flags_are_refused() { + let spec = profile_root::spec_with(|_| None); for argv in [ - args(&["--launch-profile", VERSION]), + args(&["--launch-profile", NIGHTLY_V1_CONTRACT]), 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", "8765", "--"]), - args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--automation-write-root", "/tmp", "--"]), - args(&["--launch-profile", VERSION, "--profile-root", absolute()]), + args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--"]), + args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--profile-root", absolute(), "--"]), + args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", "", "--"]), + args(&["a.figcraft", "--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute()]), ] { - assert!(parse(argv).is_err()); + assert!(parse_startup(BuildFlavor::NightlyV1, &spec, argv, &StartupOptions::new()).is_err()); } } #[test] - fn the_launcher_version_check_is_a_version_query_only_in_its_exact_form() { - let pair = &["--launch-profile", VERSION, "--profile-root", absolute()]; - let reversed = &["--profile-root", absolute(), "--launch-profile", VERSION]; - for flag in ["--version", "-V"] { - for form in [pair, reversed] { - let mut argv = args(form); - argv.push(flag.into()); - assert!(version_query(&argv), "{argv:?}"); - } - } + fn version_queries_are_recognized_for_direct_and_launcher_invocations() { + let spec = profile_root::spec_with(|_| None); 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", "8765", "--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", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--version"]), + args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "-V"]), + args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--", "--version"]), + args(&["--profile-root", absolute(), "--launch-profile", NIGHTLY_V1_CONTRACT, "--version"]), ] { - assert!(!version_query(&argv), "{argv:?}"); + let launch = parse_startup(BuildFlavor::NightlyV1, &spec, argv.clone(), &StartupOptions::new()).unwrap(); + assert!(launch.is_version_query(), "{argv:?}"); + } + for argv in [args(&[]), args(&["--", "--version"]), args(&["a.figcraft"])] { + let launch = parse_startup(BuildFlavor::NightlyV1, &spec, argv.clone(), &StartupOptions::new()).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()); + fn ordinary_file_arguments_do_not_turn_a_launcher_invocation_into_a_version_query() { + let spec = profile_root::spec_with(|_| None); + for tail in [&["--version", "drawing.figcraft"][..], &["--", "drawing.figcraft", "notes.figcraft"][..], &["--version", "--"][..]] { + let mut argv = args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute()]); + argv.extend(args(tail)); + let parsed = parse_startup(BuildFlavor::NightlyV1, &spec, argv, &StartupOptions::new()).unwrap(); + assert!(!parsed.is_version_query()); + } } #[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 current_defaults_to_stable_and_prepare_handles_version_query_without_installing() { + assert_eq!(current(), &Profile::Stable); + let version = prepare(BuildFlavor::NightlyV1, args(&["--version"])).unwrap(); + assert!(version.is_version_query()); + assert_eq!(current(), &Profile::Stable); + let rejected = prepare(BuildFlavor::Stable, args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--"])); + assert!(matches!(rejected, Err(ProfileError::NightlyFlagsInStableBuild))); } } diff --git a/apps/figcraft/src/main.rs b/apps/figcraft/src/main.rs index 068d49ac1..1660dcf04 100644 --- a/apps/figcraft/src/main.rs +++ b/apps/figcraft/src/main.rs @@ -236,34 +236,50 @@ fn report_launch_profile_error(error: &str) -> ! { std::process::exit(2) } +/// Whether `argv` begins with explicit `--launch-profile`/`--profile-root` flags followed +/// immediately by `--` (which `craft-nightly` strips from `passthrough_args`). +fn has_launcher_delimiter(argv: &[std::ffi::OsString]) -> bool { + let mut i = 0; + let mut saw_flag = false; + while let Some(arg) = argv.get(i).and_then(|a| a.to_str()) { + if arg == craft_nightly::LAUNCH_PROFILE_FLAG || arg == craft_nightly::PROFILE_ROOT_FLAG { + saw_flag = true; + i += 2; + } else if arg.starts_with("--launch-profile=") || arg.starts_with("--profile-root=") { + saw_flag = true; + i += 1; + } else { + return saw_flag && arg == "--"; + } + } + false +} + /// Select the immutable launch profile before any startup service or side effect, and answer the /// version query first: `None` means the query did (there is nothing left to start). /// -/// Stable keeps its arguments and its directory policy untouched; only a Nightly build answers the -/// Launcher's `--launch-profile nightly-v1 --profile-root --version` form. +/// Stable keeps its arguments and its directory policy untouched; a Nightly build self-isolates +/// into `craft_nightly::canonical_profile_root("figcraft")` on direct launch or uses the +/// Launcher's `--launch-profile nightly-v1 --profile-root ` override. fn prepare_launch() -> Option> { let argv: Vec<_> = std::env::args_os().skip(1).collect(); let nightly_build = build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1; - if nightly_build && (build_flavor::version_query(&argv) || launch_profile::version_query(&argv)) { + // A bare version query must not resolve HOME or LOCALAPPDATA. + if nightly_build && matches!(argv.as_slice(), [arg] if arg == "--version" || arg == "-V") { + use std::io::Write as _; + let _ = writeln!(std::io::stdout(), "FigCraft {}", build_flavor::version(build_flavor::COMPILED, env!("FIGCRAFT_BUILT_VERSION"))); + return None; + } + let launcher_delimited = nightly_build && has_launcher_delimiter(&argv); + let early = launch_profile::prepare(build_flavor::COMPILED, argv).unwrap_or_else(|error| report_launch_profile_error(&error.to_string())); + if nightly_build && early.is_version_query() { // Before root validation, logging, the update helper, fonts or any window: a runner reads // this line and the process ends. Nothing else may be printed here. use std::io::Write as _; let _ = writeln!(std::io::stdout(), "FigCraft {}", build_flavor::version(build_flavor::COMPILED, env!("FIGCRAFT_BUILT_VERSION"))); return None; } - let early = launch_profile::parse(argv) - .and_then(|launch| { - build_flavor::require_profile(build_flavor::COMPILED, &launch.profile)?; - initialize_nightly_identity()?; - Ok(launch) - }) - .and_then(|launch| { - launch_profile::prepare(launch, |root| { - launch_profile::validate_root(root, |key| std::env::var_os(key), std::env::current_exe().ok().as_deref()) - }) - }) - .unwrap_or_else(|error| report_launch_profile_error(&error)); - if let Err(error) = launch_profile::install(early.profile) { + if let Err(error) = initialize_nightly_identity() { report_launch_profile_error(&error); } if let Some(root) = launch_profile::current().root() { @@ -273,7 +289,12 @@ fn prepare_launch() -> Option> { // fonts inside its own profile instead. figcraft_engine::fonts::download::use_store_dir(root.join("Fonts")); } - Some(early.args) + let args = if launcher_delimited { + std::iter::once(std::ffi::OsString::from("--")).chain(early.passthrough_args).collect() + } else { + early.passthrough_args + }; + Some(args) } fn open_startup_files(app: &mut FigApp, files: &[String]) { @@ -699,3 +720,24 @@ mod refusal_dialog_tests { assert!(!refusal_dialog(BuildFlavor::Stable, true, false), "only a nightly refusal explains itself in a box"); } } + +#[cfg(test)] +mod launcher_delimiter_tests { + use std::ffi::OsString; + + use super::has_launcher_delimiter; + + fn args(values: &[&str]) -> Vec { + values.iter().map(OsString::from).collect() + } + + #[test] + fn recognizes_delimiter_immediately_after_nightly_header_flags() { + assert!(has_launcher_delimiter(&args(&["--launch-profile", "nightly-v1", "--profile-root", "/tmp/p", "--", "a.figcraft"]))); + assert!(has_launcher_delimiter(&args(&["--launch-profile=nightly-v1", "--profile-root=/tmp/p", "--"]))); + assert!(!has_launcher_delimiter(&args(&["--launch-profile", "nightly-v1", "--profile-root", "/tmp/p", "a.figcraft", "--", "b.figcraft"]))); + assert!(!has_launcher_delimiter(&args(&["--launch-profile", "nightly-v1", "--profile-root", "/tmp/p"]))); + assert!(!has_launcher_delimiter(&args(&["--", "a.figcraft"]))); + assert!(!has_launcher_delimiter(&args(&[]))); + } +} diff --git a/apps/figcraft/src/profile_root.rs b/apps/figcraft/src/profile_root.rs index 4861a2832..25e54daa4 100644 --- a/apps/figcraft/src/profile_root.rs +++ b/apps/figcraft/src/profile_root.rs @@ -1,787 +1,314 @@ -//! App-owned nightly profile fences; no stable fallback, migration or process environment changes. +//! FigCraft-specific nightly profile isolation spec for `craft-nightly`. use std::ffi::OsString; -use std::path::{Component, Path, PathBuf}; +use std::path::PathBuf; + +use craft_nightly::AppProfileSpec; + +pub const APP_ID: &str = "figcraft"; +pub const DISPLAY_NAME: &str = "FigCraft"; +pub const STABLE_DIR_NAMES: &[&str] = &["FigCraft", "figcraft"]; +pub const STABLE_PACKAGE_ID: &str = "ai.storyteller.figcraft"; +pub const NIGHTLY_PACKAGE_ID: &str = "ai.storyteller.figcraft.nightly"; +pub const FORBIDDEN_ENV_VARS: &[&str] = &["FIGCRAFT_CONFIG_DIR"]; +/// The portable marker FigCraft already uses (`craft_settings::Portable::DEFAULT`): a `portable` +/// file beside the executable keeps settings in `config/` beside it. +pub const PORTABLE_MARKERS: &[&str] = &["portable"]; +pub const FOLDER_ONLY_ENTRIES: &[&str] = &["Recovery", "Plugins", "Fonts", "logs"]; -/// The portable marker and folder FigCraft already uses (`craft_settings::Portable::DEFAULT`): a -/// `portable` file beside the executable keeps the settings in `config/` beside it. -const PORTABLE_MARKER: &str = "portable"; -/// The Nightly's own Flatpak id: its sandbox is its own, so it is not the stable app's instance. -const NIGHTLY_FLATPAK_ID: &str = "ai.storyteller.figcraft.nightly"; /// The Linux wrapper's record of an XDG base it overrode (`FIGCRAFT_STABLE_XDG_CONFIG_HOME`, ...). +#[cfg(all(unix, not(target_os = "macos")))] const STABLE_XDG_KEY_PREFIX: &str = "FIGCRAFT_STABLE_"; -/// What a portable copy holds beside its marker. -const PORTABLE_EXES: [&str; 3] = ["figcraft.exe", "figcraft", "FigCraft.app"]; -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum Platform { - Windows, - Linux, - Mac, +pub fn spec() -> AppProfileSpec { + spec_with(|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()), +pub fn spec_with(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), + } +} + +#[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 per-user folder (figcraft.wxs installs under ArtCraft). + if let Some(local) = non_empty_abs(env, "LOCALAPPDATA") { + roots.push(local.join("Programs").join("ArtCraft").join("FigCraft")); } - } - - 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("FigCraft")); } - 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()) -} - -/// Every stable data root of this app (the settings folder `services::config_dir` uses, the -/// installer's folders), so a nightly profile can never read or sweep stable user state. -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("FigCraft"))) - .collect::, _>>()?; - // The MSI's per-user folder (figcraft.wxs installs under ArtCraft). 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("FigCraft")); - 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("FigCraft")); - } - } - roots - } - Platform::Linux => { - // The settings folder is `/FigCraft`; the other XDG folders hold no - // FigCraft state today, but a copy that starts writing there must not become readable. - // The Linux wrapper (`packaging/linux/nightly-launch.sh`) points XDG_CONFIG_HOME and - // XDG_DATA_HOME at per-channel folders and passes the bases in effect before that - // override as STABLE_XDG_KEY_PREFIX + key, so the stable folders under them stay fenced. - let mut roots = Vec::new(); - for (key, fallback) in - [("XDG_CONFIG_HOME", ".config"), ("XDG_DATA_HOME", ".local/share"), ("XDG_CACHE_HOME", ".cache"), ("XDG_STATE_HOME", ".local/state")] - { - let mut bases = vec![xdg_base(env, key, fallback)?]; - let stable_key = format!("{STABLE_XDG_KEY_PREFIX}{key}"); - if let Some(value) = env(&stable_key).filter(|v| !v.is_empty()) { - bases.push(absolute(PathBuf::from(value), &stable_key)?); - } - for base in bases { - roots.push(base.join("FigCraft")); - roots.push(base.join("figcraft")); - } - } - roots.extend(["/usr/bin/figcraft", "/usr/local/bin/figcraft", "/opt/figcraft"].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.figcraft")); - roots - } - Platform::Mac => { - let home = required_base(env, "HOME")?; + #[cfg(target_os = "macos")] + { + let mut roots = vec![PathBuf::from("/Applications/FigCraft.app")]; + if let Some(home) = non_empty_abs(env, "HOME") { let library = home.join("Library"); - vec![ - library.join("Application Support/FigCraft"), - library.join("Caches/FigCraft"), - library.join("Preferences/FigCraft"), - library.join("Preferences/ai.storyteller.figcraft.plist"), - library.join("Saved Application State/ai.storyteller.figcraft.savedState"), - home.join("Applications/FigCraft.app"), - PathBuf::from("/Applications/FigCraft.app"), - ] + roots.push(library.join("Preferences/ai.storyteller.figcraft.plist")); + roots.push(library.join("Saved Application State/ai.storyteller.figcraft.savedState")); + roots.push(home.join("Applications/FigCraft.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 } - match std::fs::metadata(&child) { - Ok(metadata) if !metadata.is_dir() => return Err(format!("the nightly {label} must be a directory")), - Ok(_) => {} - Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} - Err(error) => return Err(format!("cannot inspect the nightly {label}: {error}")), - } - Ok(child) -} -const PROFILE_FOLDERS: [&str; 4] = ["Recovery", "Plugins", "Fonts", "logs"]; - -/// Every existing entry directly in the profile (Plugins, logs, settings and so on) must resolve -/// inside it, so a link there cannot point Nightly's writes at another app's data. -fn entries_stay_inside(root: &Path) -> Result<(), String> { - let entries = match std::fs::read_dir(root) { - Ok(entries) => entries, - Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()), - Err(error) => return Err(format!("cannot inspect the nightly profile: {error}")), - }; - for entry in entries { - let entry = entry.map_err(|e| format!("cannot inspect the nightly profile: {e}"))?; - let path = entry.path(); - let metadata = std::fs::symlink_metadata(&path).map_err(|e| format!("cannot inspect the nightly profile: {e}"))?; - // Settings and session state are ordinary files, not directories. Keep the existing - // directory-boundary check for folders (including the known folder-only entries). - let folder_only = PROFILE_FOLDERS.iter().any(|name| entry.file_name().eq_ignore_ascii_case(name)); - if metadata.is_file() && !folder_only { - private_regular_file(&path, &metadata)?; - } else { - private_subdirectory(root, entry.file_name(), "profile entry")?; - } - } - Ok(()) -} - -/// Persisted files must have their own ordinary file identity, not an alias to other data. -fn private_regular_file(path: &Path, metadata: &std::fs::Metadata) -> Result<(), String> { - #[cfg(unix)] + #[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()); - } - } - #[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(()) -} - -/// A portable FigCraft copy: the marker file beside the executable (or the `.app` on macOS). -fn portable_copy(dir: &Path) -> bool { - dir.join(PORTABLE_MARKER).is_file() && PORTABLE_EXES.iter().any(|exe| dir.join(exe).exists()) -} - -/// The portable layout in both the supplied and resolved path: the chosen folder itself or any -/// ancestor is a portable copy. A marker only counts beside a FigCraft executable, so an unrelated -/// `portable` file higher up (in a user folder or at a drive root) does not refuse the profile, and -/// a folder merely named `config` (the XDG configuration folder holds the Launcher's profiles) is -/// not a portable settings folder. -fn is_portable_layout(path: &Path) -> bool { - path.ancestors().any(portable_copy) -} - -/// The app's exclusive write probe: the nightly profile must be writable without touching any -/// stable folder, and a failed probe never falls back to the stable settings folder. Each attempt -/// uses a fresh name, so a probe left by a killed run (or a concurrent one) never blocks a writable -/// profile, and only the entry this attempt created is removed. -pub fn ensure_writable(dir: &Path) -> std::io::Result<()> { - use std::sync::atomic::{AtomicU64, Ordering}; - static NEXT: AtomicU64 = AtomicU64::new(0); - let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_nanos()); - for _ in 0..16 { - let probe = dir.join(format!("nightly-write-probe-{}-{nanos}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed))); - match std::fs::OpenOptions::new().write(true).create_new(true).open(&probe) { - Ok(file) => { - drop(file); - return std::fs::remove_file(probe); + let mut roots = vec![PathBuf::from("/usr/bin/figcraft"), PathBuf::from("/usr/local/bin/figcraft"), PathBuf::from("/opt/figcraft")]; + // The Linux wrapper (`packaging/linux/nightly-launch.sh`) points XDG_CONFIG_HOME and + // XDG_DATA_HOME at per-channel folders and passes the bases in effect before that override + // as STABLE_XDG_KEY_PREFIX + key, so the stable folders under them stay fenced. + for key in ["XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME"] { + let stable_key = format!("{STABLE_XDG_KEY_PREFIX}{key}"); + if let Some(base) = non_empty_abs(env, &stable_key) { + for name in STABLE_DIR_NAMES { + roots.push(base.join(name)); + } } - 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 fresh name for the nightly write probe")) -} - -/// The writable hook is injected so filesystem boundary tests exercise the real policy without -/// starting the app or changing global state. -pub fn validate( - root: &Path, - env: impl Fn(&str) -> Option, - exe: Option<&Path>, - writable: impl FnOnce(&Path) -> std::io::Result<()>, -) -> Result { - validate_for(Platform::current()?, root, env, exe, writable) -} - -fn validate_for( - platform: Platform, - root: &Path, - env: impl Fn(&str) -> Option, - exe: Option<&Path>, - writable: impl FnOnce(&Path) -> std::io::Result<()>, -) -> Result { - absolute(root.to_path_buf(), "the nightly profile root")?; - if env("FIGCRAFT_CONFIG_DIR").is_some_and(|v| !v.is_empty()) { - return Err("nightly-v1 cannot be combined with FIGCRAFT_CONFIG_DIR".into()); - } - if platform != Platform::Windows { - // A native tar/app-bundle launch must not inherit another app's Flatpak runtime namespace, - // which could point this profile at the stable app's socket. The Nightly's own Flatpak - // bundle (ai.storyteller.figcraft.nightly) is a separate sandbox and is allowed. - let flatpak = env("FLATPAK_ID").filter(|v| !v.is_empty()); - if let Some(id) = flatpak - && id != NIGHTLY_FLATPAK_ID - { - return Err("nightly-v1 cannot inherit another app's Flatpak instance; use its own package or the native Launcher".into()); + // 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").join(STABLE_PACKAGE_ID)); } + roots } - let chosen = canonical_future(root)?; - if is_portable_layout(root) || is_portable_layout(&chosen) { - return Err("the nightly root must not use a portable FigCraft installation or its config 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 folder not in our known roots. - private_subdirectory(&chosen, "Recovery", "recovery folder")?; - let mut create = std::fs::DirBuilder::new(); - create.recursive(true); - #[cfg(unix)] + + #[cfg(not(any(unix, target_os = "windows")))] { - use std::os::unix::fs::DirBuilderExt as _; - create.mode(0o700); + let _ = env; + Vec::new() } - create.create(&chosen).map_err(|e| format!("cannot create the nightly profile: {e}"))?; - let confirmed = std::fs::canonicalize(&chosen).map_err(|e| format!("cannot resolve the created nightly profile: {e}"))?; - if confirmed != chosen || forbidden.iter().any(|stable| overlaps(&confirmed, stable, platform)) { - return Err("the nightly profile changed while it was being validated".into()); - } - private_subdirectory(&confirmed, "Recovery", "recovery folder")?; - entries_stay_inside(&confirmed)?; - writable(&confirmed).map_err(|e| format!("the nightly profile is not writable: {e}"))?; - Ok(confirmed) } #[cfg(test)] mod tests { - use super::*; use std::collections::BTreeMap; + use std::ffi::OsString; + use std::path::PathBuf; use std::sync::atomic::{AtomicU64, Ordering}; - /// The portable settings folder beside a portable copy's executable. - const PORTABLE_DIR: &str = "config"; + use craft_nightly::{ProfileError, validate_and_prepare_root}; - struct Fixture { - root: PathBuf, - env: BTreeMap, - exe: PathBuf, - } + use super::{ + APP_ID, DISPLAY_NAME, FOLDER_ONLY_ENTRIES, FORBIDDEN_ENV_VARS, NIGHTLY_PACKAGE_ID, PORTABLE_MARKERS, STABLE_DIR_NAMES, STABLE_PACKAGE_ID, + spec, spec_with, + }; - impl Fixture { - fn new() -> Self { + 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!("figcraft-profile-policy-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed))); + let candidate = std::env::temp_dir().join(format!( + "figcraft-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/figcraft"); - std::fs::create_dir_all(&home).unwrap(); - std::fs::create_dir_all(exe.parent().unwrap()).unwrap(); - std::fs::write(&exe, b"fixture executable, never run").unwrap(); - let env = [("HOME", home), ("APPDATA", root.join("roaming")), ("LOCALAPPDATA", root.join("local"))] - .into_iter() - .map(|(key, value)| (key.into(), value.into_os_string())) - .collect(); - Self { root, env, exe } - } - - fn get(&self, key: &str) -> Option { - self.env.get(key).cloned() - } - - fn check(&self, platform: Platform, root: &Path) -> Result { - validate_for( - platform, - root, - |key| self.get(key), - Some(&self.exe), - |dir| { - let probe = dir.join("exclusive-test-probe"); - let file = std::fs::OpenOptions::new().write(true).create_new(true).open(&probe)?; - drop(file); - std::fs::remove_file(probe) - }, - ) - } - - fn home(&self) -> PathBuf { - PathBuf::from(self.get("HOME").unwrap()) + Self(root) } } - 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 a_portable_copy_and_its_config_folder_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_DIR); - std::fs::create_dir_all(&stable_data).unwrap(); - std::fs::write(stable_install.join(PORTABLE_MARKER), b"owned portable fixture").unwrap(); - std::fs::write(stable_install.join("figcraft.exe"), b"portable copy, never run").unwrap(); - std::fs::write(stable_data.join("state.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("state.json")).unwrap(), b"stable settings must not change"); - } - } - let private = fixture.root.join("figcraft-data-backup/nightly"); - assert!(fixture.check(Platform::Linux, &private).is_ok(), "a merely similar name is not a portable copy"); + fn spec_preserves_figcraft_isolation_policy() { + let isolated = spec_with(|_| None); + assert_eq!(isolated.app_id, APP_ID); + assert_eq!(isolated.display_name, DISPLAY_NAME); + assert_eq!(isolated.stable_dir_names, STABLE_DIR_NAMES); + assert_eq!(isolated.stable_package_id, STABLE_PACKAGE_ID); + assert_eq!(isolated.nightly_package_id, NIGHTLY_PACKAGE_ID); + assert_eq!(isolated.profile_root_env, None); + assert_eq!(isolated.forbidden_env_vars, FORBIDDEN_ENV_VARS); + assert_eq!(isolated.portable_markers, PORTABLE_MARKERS); + assert_eq!(isolated.folder_only_entries, FOLDER_ONLY_ENTRIES); + assert_eq!(spec().app_id, APP_ID); } - #[cfg(unix)] + #[cfg(all(unix, not(target_os = "macos")))] #[test] - fn recovery_aliases_cannot_redirect_to_stable_missing_or_profile_root_data() { - let fixture = Fixture::new(); - let stable = fixture.home().join(".config/FigCraft/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"); - } - - #[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); - } - - #[test] - fn the_stable_settings_folder_and_its_ancestors_are_refused() { - let fixture = Fixture::new(); - // Each platform fences the folder its own stable build resolves (`services::platform_dir`): - // `%APPDATA%` on Windows, `~/.config` on Linux and Application Support on macOS. - let stable_folders = [ - (Platform::Windows, fixture.root.join("roaming/FigCraft")), - (Platform::Linux, fixture.home().join(".config/FigCraft")), - (Platform::Mac, fixture.home().join("Library/Application Support/FigCraft")), - ]; - for (platform, stable) in stable_folders { - std::fs::create_dir_all(&stable).unwrap(); - std::fs::write(stable.join("state.json"), b"stable settings").unwrap(); - for root in [stable.clone(), stable.join("nightly")] { - let calls = std::cell::Cell::new(0); - let result = validate_for( - platform, - &root, - |key| fixture.get(key), - Some(&fixture.exe), - |_| { - calls.set(calls.get() + 1); - Ok(()) - }, - ); - assert!(result.unwrap_err().contains("overlap")); - assert_eq!(calls.get(), 0); - } - assert_eq!(std::fs::read(stable.join("state.json")).unwrap(), b"stable settings"); - } - } - - #[test] - fn overlap_check_handles_ancestor_descendant_and_prefix_lookalikes() { - let fixture = Fixture::new(); - let root = fixture.home().join("nightly/profiles/figcraft"); - 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("figcraft-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"] { - for name in ["FigCraft", "figcraft"] { - let stable = PathBuf::from(fixture.get(key).unwrap()).join(name); - 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")] { - 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/figcraft"); - 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 ["state.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("state.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/FigCraft Nightly.app/Contents/MacOS/FigCraft"); - 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/FigCraft", - "Caches/FigCraft", - "Preferences/FigCraft", - "Preferences/ai.storyteller.figcraft.plist", - "Saved Application State/ai.storyteller.figcraft.savedState", + fn linux_extra_forbidden_roots_preserve_wrapper_stable_xdg_and_flatpak_fences() { + let env: BTreeMap<&str, OsString> = [ + ("HOME", "/home/tester".into()), + ("FIGCRAFT_STABLE_XDG_CONFIG_HOME", "/stable/config".into()), + ("FIGCRAFT_STABLE_XDG_DATA_HOME", "/stable/data".into()), + ("FIGCRAFT_STABLE_XDG_CACHE_HOME", "".into()), + ("FIGCRAFT_STABLE_XDG_STATE_HOME", "relative/state".into()), + ] + .into_iter() + .collect(); + let spec = spec_with(|k| env.get(k).cloned()); + for expected in [ + "/usr/bin/figcraft", + "/usr/local/bin/figcraft", + "/opt/figcraft", + "/stable/config/FigCraft", + "/stable/config/figcraft", + "/stable/data/FigCraft", + "/stable/data/figcraft", + "/home/tester/.var/app/ai.storyteller.figcraft", ] { - let stable = library.join(suffix); - assert!(fixture.check(Platform::Mac, &stable.join("nightly")).unwrap_err().contains("overlap")); - assert!(!stable.exists()); + assert!(spec.extra_forbidden_roots.contains(&PathBuf::from(expected)), "missing {expected}"); + } + assert!(!spec.extra_forbidden_roots.contains(&PathBuf::from("relative/state/FigCraft"))); + assert!(!spec.extra_forbidden_roots.contains(&PathBuf::from("FigCraft"))); + } + + #[cfg(target_os = "macos")] + #[test] + fn macos_extra_forbidden_roots_preserve_stable_bundle_and_library_fences() { + let env: BTreeMap<&str, OsString> = [("HOME", "/Users/tester".into())].into_iter().collect(); + let spec = spec_with(|k| env.get(k).cloned()); + for expected in [ + "/Applications/FigCraft.app", + "/Users/tester/Applications/FigCraft.app", + "/Users/tester/Library/Preferences/ai.storyteller.figcraft.plist", + "/Users/tester/Library/Saved Application State/ai.storyteller.figcraft.savedState", + ] { + assert!(spec.extra_forbidden_roots.contains(&PathBuf::from(expected)), "missing {expected}"); + } + } + + #[cfg(target_os = "windows")] + #[test] + fn windows_extra_forbidden_roots_preserve_msi_install_fences() { + let env: BTreeMap<&str, OsString> = [ + ("LOCALAPPDATA", r"C:\Users\tester\AppData\Local".into()), + ("ProgramW6432", r"C:\Program Files".into()), + ("ProgramFiles", r"C:\Program Files".into()), + ("ProgramFiles(x86)", r"C:\Program Files (x86)".into()), + ] + .into_iter() + .collect(); + let spec = spec_with(|k| env.get(k).cloned()); + for expected in [ + r"C:\Users\tester\AppData\Local\Programs\ArtCraft\FigCraft", + r"C:\Program Files\ArtCraft\FigCraft", + r"C:\Program Files (x86)\ArtCraft\FigCraft", + ] { + assert!(spec.extra_forbidden_roots.contains(&PathBuf::from(expected)), "missing {expected}"); } - 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/figcraft"); - 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("FigCraft"); - 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/figcraft")).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("FigCraft"); - 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("FigCraft"); - 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("figcraft"); - assert!(fixture.check(Platform::Windows, &sibling).is_ok(), "the Launcher's own Programs sibling is not FigCraft's install"); - } - - #[test] - fn a_marker_that_no_figcraft_copy_sits_beside_is_someone_elses_file() { - let fixture = Fixture::new(); - let unrelated = fixture.root.join("user folder"); - std::fs::create_dir_all(&unrelated).unwrap(); - std::fs::write(unrelated.join(PORTABLE_MARKER), b"another app's marker").unwrap(); - assert!(fixture.check(Platform::Windows, &unrelated.join("Launcher/nightly/figcraft")).is_ok()); - // Beside a FigCraft executable, the same marker makes it a portable copy. - std::fs::write(unrelated.join("figcraft.exe"), b"portable copy, never run").unwrap(); - assert!(fixture.check(Platform::Windows, &unrelated.join("nightly")).unwrap_err().contains("portable")); - } - - #[cfg(unix)] - #[test] - fn linux_wrapper_override_keeps_the_stable_xdg_folders_fenced() { - let mut fixture = Fixture::new(); - // What the wrapper exports with XDG_CONFIG_HOME and XDG_DATA_HOME unset. - let (config_base, data_base) = (fixture.home().join(".config"), fixture.home().join(".local/share")); - for (key, base) in [("XDG_CONFIG_HOME", &config_base), ("XDG_DATA_HOME", &data_base)] { - fixture.env.insert(key.into(), base.join("figcraft-nightly").into_os_string()); - fixture.env.insert(format!("{STABLE_XDG_KEY_PREFIX}{key}"), base.clone().into_os_string()); - } - let stable = config_base.join("FigCraft"); - std::fs::create_dir_all(&stable).unwrap(); - std::fs::write(stable.join("state.json"), b"stable settings").unwrap(); - let profile = data_base.join("figcraft-nightly/profile"); - std::fs::create_dir_all(profile.parent().unwrap()).unwrap(); - std::os::unix::fs::symlink(&stable, &profile).unwrap(); - assert!(fixture.check(Platform::Linux, &profile).unwrap_err().contains("overlap")); - assert_eq!(std::fs::read_dir(&stable).unwrap().count(), 1, "nothing is written into the stable folder"); - std::fs::remove_file(&profile).unwrap(); - assert_eq!(fixture.check(Platform::Linux, &profile).unwrap(), profile, "a normal Nightly profile stays valid"); + fn a_non_directory_profile_root_stops_figcraft_startup() { + let tmp = TempDir::new("invalid-root"); + let invalid = tmp.0.join("not-a-directory"); + std::fs::write(&invalid, b"ordinary file").unwrap(); + let argv = [ + OsString::from("--launch-profile"), + OsString::from(craft_nightly::NIGHTLY_V1_CONTRACT), + OsString::from("--profile-root"), + invalid.into_os_string(), + ]; + assert!(crate::launch_profile::prepare(crate::build_flavor::BuildFlavor::NightlyV1, argv).is_err()); + assert!(craft_nightly::current().is_none(), "a failed launch must not install any profile"); } #[test] fn a_leftover_write_probe_does_not_block_a_writable_profile() { - let fixture = Fixture::new(); - let dir = fixture.home().join("nightly"); - std::fs::create_dir_all(&dir).unwrap(); - std::fs::write(dir.join("nightly-write-probe"), b"left by a killed run").unwrap(); - ensure_writable(&dir).unwrap(); - ensure_writable(&dir).unwrap(); - let names: Vec<_> = std::fs::read_dir(&dir).unwrap().flatten().map(|e| e.file_name()).collect(); - assert_eq!(names, ["nightly-write-probe"], "only this attempt's own probe is removed"); + let tmp = TempDir::new("leftover-probe"); + let spec = spec_with(|_| None); + let profile = validate_and_prepare_root(&tmp.0.join("profile"), &spec).unwrap(); + let previous = profile.join("nightly-write-probe"); + std::fs::write(&previous, b"left by a previous run").unwrap(); + assert_eq!(validate_and_prepare_root(&profile, &spec).unwrap(), profile); + assert_eq!(validate_and_prepare_root(&profile, &spec).unwrap(), profile); + assert_eq!(std::fs::read(&previous).unwrap(), b"left by a previous run"); + assert_eq!(std::fs::read_dir(&profile).unwrap().count(), 1); } #[test] - fn linux_fences_the_stable_flatpak_data_folder() { - let fixture = Fixture::new(); - let flatpak = fixture.home().join(".var/app/ai.storyteller.figcraft"); - for candidate in [flatpak.clone(), flatpak.join("data/nightly")] { - assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("overlap")); + fn nightly_profile_reopens_with_saved_preferences_and_session_state() { + use std::sync::{Arc, Mutex}; + + let tmp = TempDir::new("saved-state"); + let original = tmp.0.join("private-profile"); + let spec = spec_with(|_| None); + let prepared = validate_and_prepare_root(&original, &spec).unwrap(); + + let prefs = figcraft_engine::Prefs { user_name: "Nightly user".into(), ..Default::default() }; + crate::services::write_prefs(&prepared, &prefs); + let session = crate::nightly_session::Session::begin(Some(&prepared), "0.18.1", None).unwrap().unwrap(); + assert!(!session.previous_unclean()); + session.complete().unwrap(); + for name in FOLDER_ONLY_ENTRIES { + std::fs::create_dir(prepared.join(name)).unwrap(); } - assert!(!flatpak.exists()); - assert!(fixture.check(Platform::Linux, &fixture.home().join(".var/app/ai.storyteller.launcher/nightly")).is_ok()); + // The next launch selects exactly the same root and loads the saved preferences. + let reopened = validate_and_prepare_root(&original, &spec).unwrap(); + assert_eq!(reopened, prepared); + let loaded = crate::services::Desktop::load_from(Some(reopened.clone()), Arc::new(Mutex::new(None))); + assert_eq!(loaded.prefs.unwrap().user_name, "Nightly user"); + let next = crate::nightly_session::Session::begin(Some(&reopened), "0.18.2", None).unwrap().unwrap(); + assert!(!next.previous_unclean()); + next.complete().unwrap(); } - #[cfg(unix)] #[test] - fn any_profile_entry_alias_must_stay_inside_the_profile() { - let fixture = Fixture::new(); - let stable = fixture.home().join(".config/FigCraft/Plugins"); - std::fs::create_dir_all(&stable).unwrap(); - std::fs::write(stable.join("stable-plugin"), b"stable plugin bytes").unwrap(); - for name in ["Plugins", "logs", "state.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()); + fn profile_root_validation_enforces_folder_only_entries_and_extra_forbidden_roots() { + let tmp = TempDir::new("validate"); + let forbidden = tmp.0.join("stable-install"); + let profile = tmp.0.join("nightly-profile"); + let mut spec = spec_with(|_| None); + spec.extra_forbidden_roots.push(forbidden.clone()); + + assert!(matches!(validate_and_prepare_root(&forbidden, &spec), Err(ProfileError::ForbiddenRootOverlap { .. }))); + + let prepared = validate_and_prepare_root(&profile, &spec).unwrap(); + assert_eq!(prepared, profile); + + for name in ["state.json", "nightly-session.lock", "nightly-session.json"] { + std::fs::write(profile.join(name), b"saved profile data").unwrap(); } - let private = fixture.root.join("nightly-inside"); - std::fs::create_dir_all(private.join("real-plugins")).unwrap(); - std::fs::write(private.join("state.json"), b"{}").unwrap(); - std::os::unix::fs::symlink(private.join("real-plugins"), private.join("Plugins")).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-plugin")).unwrap(), b"stable plugin bytes"); - } + for name in FOLDER_ONLY_ENTRIES { + std::fs::create_dir(profile.join(name)).unwrap(); + } + assert_eq!(validate_and_prepare_root(&profile, &spec).unwrap(), profile); - #[test] - fn ambiguous_environment_and_non_native_sandbox_are_refused_before_creation() { - let mut fixture = Fixture::new(); - let candidate = fixture.home().join("nightly/profiles/figcraft"); - 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("FIGCRAFT_CONFIG_DIR".into(), fixture.home().join("custom-stable").into_os_string()); - assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("FIGCRAFT_CONFIG_DIR")); - fixture.env.remove("FIGCRAFT_CONFIG_DIR"); - fixture.env.insert("FLATPAK_ID".into(), "ai.storyteller.figcraft".into()); - assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("Flatpak")); - // The Nightly's own Flatpak bundle is a separate sandbox: its profile is allowed. - fixture.env.insert("FLATPAK_ID".into(), NIGHTLY_FLATPAK_ID.into()); - assert!(fixture.check(Platform::Linux, &fixture.home().join("nightly/profile")).is_ok()); - fixture.env.remove("FLATPAK_ID"); - fixture.env.remove("HOME"); - assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("HOME")); - assert!(!candidate.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"do not replace me").unwrap(); - assert!(fixture.check(Platform::Linux, &file).is_err()); - assert_eq!(std::fs::read(file).unwrap(), b"do not replace me"); - let candidate = fixture.home().join("nightly"); - let calls = std::cell::Cell::new(0); - let result = validate_for( - Platform::Linux, - &candidate, - |key| fixture.get(key), - Some(&fixture.exe), - |_| { - calls.set(calls.get() + 1); - Err(std::io::Error::new(std::io::ErrorKind::PermissionDenied, "injected write refusal")) - }, - ); - assert!(result.unwrap_err().contains("not writable")); - assert_eq!(calls.get(), 1); - assert!(!fixture.home().join(".config/FigCraft").exists()); - } - - #[cfg(unix)] - #[test] - fn symlink_and_dangling_aliases_cannot_create_or_modify_stable_data() { - use std::os::unix::fs::symlink; - let fixture = Fixture::new(); - let stable = fixture.home().join(".config/FigCraft"); - std::fs::create_dir_all(&stable).unwrap(); - std::fs::write(stable.join("sentinel"), b"untouched").unwrap(); - let alias = fixture.home().join("alias"); - symlink(&stable, &alias).unwrap(); - assert!(fixture.check(Platform::Linux, &alias.join("nightly")).unwrap_err().contains("overlap")); - let missing = fixture.home().join("missing-target"); - let dangling = fixture.home().join("dangling"); - symlink(&missing, &dangling).unwrap(); - assert!(fixture.check(Platform::Linux, &dangling.join("nightly")).is_err()); - assert!(!missing.exists()); - assert!(!stable.join("nightly").exists()); - assert_eq!(std::fs::read(stable.join("sentinel")).unwrap(), b"untouched"); + for name in FOLDER_ONLY_ENTRIES { + let path = profile.join(name); + std::fs::remove_dir(&path).unwrap(); + std::fs::write(&path, b"not a directory").unwrap(); + assert!(matches!(validate_and_prepare_root(&profile, &spec), Err(ProfileError::ExpectedDirectoryEntry(_)))); + std::fs::remove_file(&path).unwrap(); + std::fs::create_dir(&path).unwrap(); + } } }