diff --git a/Cargo.lock b/Cargo.lock index 9cb124cf..4b55c4b9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1223,6 +1223,15 @@ dependencies = [ "encoding_rs", ] +[[package]] +name = "craft-nightly" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=8945bdb09b36245a1d442438ce8876377ef430d0#8945bdb09b36245a1d442438ce8876377ef430d0" +dependencies = [ + "uds_windows", + "winsafe", +] + [[package]] name = "craft-pdf" version = "0.1.0" @@ -3604,6 +3613,7 @@ version = "0.4.1" dependencies = [ "craft-atomic", "craft-menu", + "craft-nightly", "craft-update", "craft-window", "eframe", diff --git a/Cargo.toml b/Cargo.toml index 92921ee8..18760ac4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -120,6 +120,8 @@ craft-window = { git = "https://github.com/storytold/craft-libs", rev = "d701080 craft-update = { git = "https://github.com/storytold/craft-libs", rev = "d7010805175ba1190d521b2565852bdda39e632c", features = ["ui"] } # Atomic persistence, at the suite's current revision craft-atomic = { git = "https://github.com/storytold/craft-libs", rev = "d7010805175ba1190d521b2565852bdda39e632c" } +# Nightly profile isolation, launch protocol, and security fence: storytold/craft-libs, MIT OR Apache-2.0 +craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "8945bdb09b36245a1d442438ce8876377ef430d0" } craft-png = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "d7010805175ba1190d521b2565852bdda39e632c" } # Parse the optional shared font catalog at build time; the font repository is not a dependency craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "d7010805175ba1190d521b2565852bdda39e632c" } diff --git a/apps/materialcraft/Cargo.toml b/apps/materialcraft/Cargo.toml index 8a9610af..d3cd947e 100644 --- a/apps/materialcraft/Cargo.toml +++ b/apps/materialcraft/Cargo.toml @@ -24,6 +24,8 @@ thiserror = { workspace = true } rfd = { workspace = true } # The Nightly session record is written atomically (src/nightly_session.rs). craft-atomic = { workspace = true } +# Nightly profile isolation, launch protocol, and security fence (src/launch_profile.rs, src/profile_root.rs). +craft-nightly = { workspace = true } # The window frame's choice applies before the window exists. craft-window = { workspace = true, features = ["ui"] } diff --git a/apps/materialcraft/src/build_flavor.rs b/apps/materialcraft/src/build_flavor.rs index 2229e6f1..c914f511 100644 --- a/apps/materialcraft/src/build_flavor.rs +++ b/apps/materialcraft/src/build_flavor.rs @@ -1,31 +1,18 @@ //! 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!(materialcraft_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 MaterialCraft Nightly from ArtCraft Launcher".into()), - (BuildFlavor::Stable, true) => Err("This is a stable MaterialCraft build; nightly-v1 requires the nightly build".into()), - _ => Ok(()), - } +/// The packaging/version probe must work even when no profile location can be resolved. +pub fn version_query(args: &[std::ffi::OsString]) -> bool { + matches!(args, [arg] if arg == "--version" || arg == "-V") } 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(), @@ -36,6 +23,15 @@ pub fn version(flavor: BuildFlavor, stable: &str) -> String { #[cfg(test)] mod tests { use super::*; + + #[test] + fn plain_version_queries_are_unambiguous() { + assert!(super::version_query(&["--version".into()])); + assert!(super::version_query(&["-V".into()])); + assert!(!super::version_query(&["--".into(), "--version".into()])); + assert!(!super::version_query(&["--version".into(), "example".into()])); + } + #[test] fn only_a_nightly_desktop_refusal_requests_a_native_dialog() { assert!(needs_native_error(BuildFlavor::NightlyV1, true)); @@ -45,28 +41,31 @@ mod tests { } #[test] - fn nightly_build_without_a_profile_is_refused_before_startup() { - let started = std::cell::Cell::new(false); - let result = require_profile(BuildFlavor::NightlyV1, &Profile::Stable).map(|()| started.set(true)); - assert!(result.unwrap_err().contains("ArtCraft Launcher")); - assert!(!started.get()); + fn nightly_build_self_isolates_on_direct_launch_without_launcher_flags() { + let expected = craft_nightly::canonical_profile_root(crate::profile_root::APP_ID).unwrap(); + let launch = crate::launch_profile::parse_startup(BuildFlavor::NightlyV1, Vec::new()).unwrap(); + assert_eq!(launch.profile, craft_nightly::Profile::NightlyV1(expected)); + assert!(launch.passthrough_args.is_empty()); } #[test] - fn stable_and_nightly_flavors_accept_only_their_own_profile() { - let nightly = Profile::NightlyV1(std::path::PathBuf::from("already validated root")); - assert!(require_profile(BuildFlavor::Stable, &Profile::Stable).is_ok()); - assert!(require_profile(BuildFlavor::Stable, &nightly).is_err()); - assert!(require_profile(BuildFlavor::NightlyV1, &nightly).is_ok()); + fn stable_flavor_rejects_nightly_flags_while_nightly_accepts_them() { + let root = if cfg!(windows) { r"C:\NightlyData\profiles\materialcraft" } else { "/nightly-data/profiles/materialcraft" }; + let nightly_args = craft_nightly::launch_arguments(std::path::Path::new(root), &[]); + + let stable = crate::launch_profile::parse_startup(BuildFlavor::Stable, Vec::new()).unwrap(); + assert_eq!(stable.profile, craft_nightly::Profile::Stable); + + let stable_with_flags = crate::launch_profile::parse_startup(BuildFlavor::Stable, nightly_args.clone()); + assert!(matches!(stable_with_flags, Err(craft_nightly::ProfileError::NightlyFlagsInStableBuild))); + + let nightly = crate::launch_profile::parse_startup(BuildFlavor::NightlyV1, nightly_args).unwrap(); + assert_eq!(nightly.profile, craft_nightly::Profile::NightlyV1(std::path::PathBuf::from(root))); } #[test] - fn nightly_version_query_is_unambiguous_and_never_reinterprets_file_arguments() { + fn nightly_version_format_is_unambiguous() { assert_eq!(version(BuildFlavor::Stable, "0.4.1"), "0.4.1"); assert_eq!(version(BuildFlavor::NightlyV1, "0.4.1"), "0.4.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/materialcraft/src/launch_profile.rs b/apps/materialcraft/src/launch_profile.rs index e073dac0..81597ac8 100644 --- a/apps/materialcraft/src/launch_profile.rs +++ b/apps/materialcraft/src/launch_profile.rs @@ -1,213 +1,96 @@ -//! 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("materialcraft")`. use std::ffi::OsString; -use std::path::{Component, Path, PathBuf}; -use std::sync::OnceLock; -pub const VERSION: &str = "nightly-v1"; - -#[derive(Clone, Debug, PartialEq, Eq)] -pub enum Profile { - Stable, - NightlyV1(PathBuf), -} - -impl Profile { - pub fn is_nightly(&self) -> bool { - matches!(self, Self::NightlyV1(_)) - } - - pub fn root(&self) -> Option<&Path> { - match self { - Self::Stable => None, - Self::NightlyV1(root) => Some(root), - } - } -} - -#[derive(Debug, PartialEq, Eq)] -pub struct Launch { - pub profile: Profile, - pub args: Vec, -} - -static PROFILE: OnceLock = OnceLock::new(); +pub use craft_nightly::{BuildFlavor, Launch, Profile, ProfileError, StartupOptions}; +/// Returns the active process-wide launch profile (defaulting to [`Profile::Stable`] before +/// initialization, such as in unit tests). pub fn current() -> &'static Profile { - PROFILE.get().unwrap_or(&Profile::Stable) + craft_nightly::current().unwrap_or(&Profile::Stable) } -pub fn install(profile: Profile) -> Result<(), String> { - PROFILE.set(profile).map_err(|_| "the launch profile was already selected".into()) +/// Parses startup arguments for `flavor`, validates and prepares the isolated profile root when +/// running as [`BuildFlavor::NightlyV1`], and installs the resolved [`Profile`] process-wide. +/// Version queries return without touching the filesystem or installing a profile. +pub fn prepare_launch(flavor: BuildFlavor, args: impl IntoIterator) -> Result { + let spec = crate::profile_root::spec(); + craft_nightly::prepare_launch(flavor, &spec, args, &StartupOptions::default()) } -/// 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 data-directory resolution stays unchanged. -pub fn prepare(mut launch: Launch, validate: impl FnOnce(&Path) -> Result) -> Result { - if let Profile::NightlyV1(root) = &launch.profile { - launch.profile = Profile::NightlyV1(validate(root)?); - } - Ok(launch) -} - -/// Resolve the selected private root before the caller's first startup effect. -pub fn validate_root(root: &Path, env: impl Fn(&str) -> Option, exe: Option<&Path>) -> Result { - crate::profile_root::validate(root, env, exe, crate::profile_root::probe_writable) +#[cfg(test)] +pub fn parse_startup(flavor: BuildFlavor, args: impl IntoIterator) -> Result { + let spec = crate::profile_root::spec(); + craft_nightly::parse_startup(flavor, &spec, args, &StartupOptions::default()) } #[cfg(test)] mod tests { use super::*; - use std::cell::Cell; + use std::path::{Path, PathBuf}; + fn args(values: &[&str]) -> Vec { values.iter().map(OsString::from).collect() } + fn absolute() -> &'static str { if cfg!(windows) { r"C:\NightlyData\profiles\materialcraft" } else { "/nightly-data/profiles/materialcraft" } } - fn nightly() -> Vec { - args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--"]) - } #[test] fn stable_arguments_and_directory_policy_are_unchanged() { for argv in [args(&[]), args(&["a.sbs"]), args(&["--", "--launch-profile", "file.sbs"])] { - let launch = prepare(parse(argv.clone()).unwrap(), |_| panic!("stable must never validate a nightly root")).unwrap(); - assert_eq!(launch, Launch { profile: Profile::Stable, args: argv }); + let launch = parse_startup(BuildFlavor::Stable, 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() { - let mut argv = nightly(); - argv.extend(args(&["--profile-root", "graph with spaces.sbs"])); - let launch = parse(argv).unwrap(); - assert_eq!(launch.profile, Profile::NightlyV1(PathBuf::from(absolute()))); - assert_eq!(launch.args, args(&["--", "--profile-root", "graph with spaces.sbs"])); + fn direct_nightly_launch_self_isolates_and_preserves_user_arguments() { + let expected = craft_nightly::canonical_profile_root(crate::profile_root::APP_ID).unwrap(); + let launch = parse_startup(BuildFlavor::NightlyV1, args(&["graph.sbs", "--empty"])).unwrap(); + assert_eq!(launch.profile, Profile::NightlyV1(expected)); + assert_eq!(launch.passthrough_args, args(&["graph.sbs", "--empty"])); } #[test] - fn missing_duplicate_unknown_and_conflicting_profile_arguments_are_refused() { + fn launcher_arguments_round_trip_without_reinterpreting_file_names() { + let argv = craft_nightly::launch_arguments(Path::new(absolute()), &args(&["--profile-root", "graph with spaces.sbs"])); + let launch = parse_startup(BuildFlavor::NightlyV1, argv).unwrap(); + assert_eq!(launch.profile, Profile::NightlyV1(PathBuf::from(absolute()))); + assert_eq!(launch.passthrough_args, args(&["--profile-root", "graph with spaces.sbs"])); + } + + #[test] + fn missing_duplicate_unknown_and_misplaced_profile_arguments_are_refused() { + let ver = craft_nightly::NIGHTLY_V1_CONTRACT; for argv in [ - args(&["--launch-profile", VERSION]), + args(&["--launch-profile", ver]), 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(&["--launch-profile=", VERSION, "--profile-root", absolute(), "--"]), - args(&["--launch-profile", VERSION, "--profile-root=", absolute(), "--"]), + args(&["--launch-profile", ver, "--launch-profile", ver, "--profile-root", absolute(), "--"]), + args(&["--launch-profile", ver, "--profile-root", absolute(), "--profile-root", absolute(), "--"]), + args(&["--launch-profile", ver, "--profile-root", "", "--"]), + args(&["file.sbs", "--launch-profile", ver, "--profile-root", absolute()]), ] { - assert!(parse(argv).is_err()); + assert!(parse_startup(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_for_plain_and_launcher_invocations() { + let ver = craft_nightly::NIGHTLY_V1_CONTRACT; for flag in ["--version", "-V"] { - for form in [pair, reversed] { - let mut argv = args(form); - argv.push(flag.into()); - assert!(version_query(&argv), "{argv:?}"); - } + assert!(parse_startup(BuildFlavor::NightlyV1, args(&[flag])).unwrap().is_version_query()); + assert!(parse_startup(BuildFlavor::NightlyV1, args(&["--launch-profile", ver, "--profile-root", absolute(), flag])).unwrap().is_version_query()); + assert!(parse_startup(BuildFlavor::NightlyV1, args(&["--profile-root", absolute(), "--launch-profile", ver, flag])).unwrap().is_version_query()); } - 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", "--version"]), - args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--version"]), - args(&["--version", "--launch-profile", VERSION, "--profile-root", absolute()]), - args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--version"]), - args(&["--launch-profile", VERSION, "--profile-root", "relative", "--version"]), - args(&["--launch-profile", VERSION, "--version"]), - args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--help"]), - ] { - assert!(!version_query(&argv), "{argv:?}"); - } - // Outside the query the strict protocol still refuses the version flag. - assert!(parse(args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version"])).is_err()); - } - - #[test] - fn failed_root_validation_never_reaches_startup_or_falls_back_to_stable() { - let reached = Cell::new(false); - let result = prepare(parse(nightly()).unwrap(), |_| Err("read-only or unsafe profile".into())).map(|_| reached.set(true)); - assert!(result.is_err()); - assert!(!reached.get()); - } - - #[test] - fn successful_root_validation_keeps_the_persistent_root_not_the_binary_tag() { - let checked = PathBuf::from(absolute()).join("checked"); - let launch = prepare(parse(nightly()).unwrap(), |_| Ok(checked.clone())).unwrap(); - assert_eq!(launch.profile.root(), Some(checked.as_path())); - assert!(launch.profile.is_nightly()); + assert!(!parse_startup(BuildFlavor::NightlyV1, args(&["--", "--version"])).unwrap().is_version_query()); + assert!(!parse_startup(BuildFlavor::NightlyV1, args(&["--version", "graph.sbs"])).unwrap().is_version_query()); + assert!(!parse_startup(BuildFlavor::NightlyV1, args(&[])).unwrap().is_version_query()); + assert!(parse_startup(BuildFlavor::NightlyV1, args(&["--launch-profile", ver, "--version"])).is_err()); } } diff --git a/apps/materialcraft/src/main.rs b/apps/materialcraft/src/main.rs index 26072631..8615488b 100644 --- a/apps/materialcraft/src/main.rs +++ b/apps/materialcraft/src/main.rs @@ -1,8 +1,9 @@ //! MaterialCraft desktop app //! Usage: `materialcraft [package.sbs] [--control ] [--empty] [--version]` //! -//! A Nightly build takes the Launcher's protocol instead: -//! `materialcraft --launch-profile nightly-v1 --profile-root -- [files…]`, and answers +//! A Nightly build self-isolates into `craft_nightly::canonical_profile_root("materialcraft")` +//! on direct launch, and also accepts ArtCraft Launcher's protocol: +//! `materialcraft --launch-profile nightly-v1 --profile-root -- [files…]`, answering //! `… --version` before any profile, window or logging work. #![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] #![forbid(unsafe_code)] @@ -152,13 +153,6 @@ fn report_launch_profile_error(error: &str) { } } -/// A Nightly answers a version query before any profile work: the plain `--version`/`-V` that -/// packaging scripts and workflows run, or the Launcher's own -/// `--launch-profile nightly-v1 --profile-root --version`. Stable keeps its own startup. -fn early_version_query(flavor: build_flavor::BuildFlavor, argv: &[std::ffi::OsString]) -> bool { - flavor == build_flavor::BuildFlavor::NightlyV1 && (build_flavor::version_query(argv) || launch_profile::version_query(argv)) -} - /// The usage text a plain `--help`/`-h` prints, before anything needs a profile. fn print_usage() { println!("{}\n\nUsage: materialcraft [package.sbs] [--control ] [--empty]", version()); @@ -170,11 +164,16 @@ fn early_help_query(argv: &[std::ffi::OsString]) -> bool { matches!(argv, [only] if matches!(only.to_str(), Some("--help" | "-h"))) } +/// Preserves the Launcher's `--` separator when forwarding arguments to `parse_args`. +fn forwarded_args(launch: &launch_profile::Launch) -> Vec { + launch.passthrough_args_with_launcher_separator() +} + /// Select the immutable launch profile before any startup service or side effect. fn prepare_launch() -> Option> { - // The trusted Launcher protocol is decided before logging, updates, fonts or saved state. + // The launch profile is decided before logging, updates, fonts or saved state. let argv: Vec<_> = std::env::args_os().skip(1).collect(); - if early_version_query(build_flavor::COMPILED, &argv) { + if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && build_flavor::version_query(&argv) { println!("{}", version()); return None; } @@ -182,19 +181,18 @@ fn prepare_launch() -> Option> { print_usage(); return None; } - let early = launch_profile::parse(argv) - .and_then(|launch| { - build_flavor::require_profile(build_flavor::COMPILED, &launch.profile)?; - initialize_nightly_process_identity().map_err(|error| error.to_string())?; - Ok(launch) - }) - .and_then(|launch| { - launch_profile::prepare(launch, |root| launch_profile::validate_root(root, |key| std::env::var_os(key), std::env::current_exe().ok().as_deref())) - }) - .unwrap_or_else(|error| { - report_launch_profile_error(&error); - std::process::exit(2) - }); + let early = launch_profile::prepare_launch(build_flavor::COMPILED, argv).unwrap_or_else(|error| { + report_launch_profile_error(&error.to_string()); + std::process::exit(2) + }); + if early.is_version_query() { + println!("{}", version()); + return None; + } + if let Err(error) = initialize_nightly_process_identity() { + report_launch_profile_error(&error.to_string()); + std::process::exit(2); + } let identity = if early.profile.is_nightly() { os_window::LaunchIdentity::NightlyV1 } else { os_window::LaunchIdentity::Stable }; if let Err(error) = os_window::select_identity(identity).and_then(|()| match early.profile.root() { Some(root) => materialcraft_ui_egui::data_root::install(root.to_path_buf()), @@ -203,12 +201,8 @@ fn prepare_launch() -> Option> { report_launch_profile_error(&error); std::process::exit(2); } - if let Err(error) = launch_profile::install(early.profile) { - report_launch_profile_error(&error); - std::process::exit(2); - } - Some(early.args) + Some(forwarded_args(&early)) } /// Where this launch keeps its window layout and settings: the private profile for a Nightly, @@ -351,28 +345,54 @@ mod tests { assert!(parse_args(&args(&["--unknown"])).is_err()); } + /// Launcher-forwarded files cross `parse_startup` into `parse_args` with their `--` + /// boundary intact, so the first file wins and leading-dash names are opened as paths. + #[test] + fn launcher_forwarded_files_keep_their_separator_into_parse_args() { + let args = |values: &[&str]| values.iter().map(std::ffi::OsString::from).collect::>(); + let nightly = build_flavor::BuildFlavor::NightlyV1; + let root = if cfg!(windows) { r"C:\nightly-data\profiles\materialcraft" } else { "/nightly-data/profiles/materialcraft" }; + + let argv = craft_nightly::launch_arguments(std::path::Path::new(root), &args(&["first.sbs", "second.sbs"])); + let launch = launch_profile::parse_startup(nightly, argv).expect("launcher startup"); + let parsed = parse_args(&forwarded_args(&launch)).expect("first file wins").expect("startup"); + assert_eq!(parsed.file.as_deref(), Some("first.sbs")); + assert_eq!(parsed.control, None); + + for leading_dash in ["-graph.sbs", "--unknown"] { + let argv = craft_nightly::launch_arguments(std::path::Path::new(root), &args(&[leading_dash])); + let launch = launch_profile::parse_startup(nightly, argv).expect("launcher startup"); + let parsed = parse_args(&forwarded_args(&launch)).expect("leading-dash file path").expect("startup"); + assert_eq!(parsed.file.as_deref(), Some(leading_dash)); + assert_eq!(parsed.control, None); + } + + // Direct launches without `--` still reject unknown options. + let direct = launch_profile::parse_startup(nightly, args(&["--unknown"])).expect("direct startup"); + assert!(parse_args(&forwarded_args(&direct)).is_err()); + } + /// The one line every packaging script and workflow compares, in both accepted forms. #[test] fn a_nightly_answers_plain_and_launcher_version_queries() { let args = |values: &[&str]| values.iter().map(std::ffi::OsString::from).collect::>(); let nightly = build_flavor::BuildFlavor::NightlyV1; - assert!(early_version_query(nightly, &args(&["--version"]))); - assert!(early_version_query(nightly, &args(&["-V"]))); + assert!(launch_profile::parse_startup(nightly, args(&["--version"])).unwrap().is_version_query()); + assert!(launch_profile::parse_startup(nightly, args(&["-V"])).unwrap().is_version_query()); // A profile root is an absolute path on its own platform; `/...` is not absolute on Windows. let root = if cfg!(windows) { r"C:\nightly-data\profiles\materialcraft" } else { "/nightly-data/profiles/materialcraft" }; let launcher = args(&["--launch-profile", "nightly-v1", "--profile-root", root]); for flag in ["--version", "-V"] { let mut argv = launcher.clone(); argv.push(flag.into()); - assert!(early_version_query(nightly, &argv), "{flag}"); + assert!(launch_profile::parse_startup(nightly, argv).unwrap().is_version_query(), "{flag}"); } - // Everything else keeps the ordinary startup: another build channel, a file named - // `--version`, an incomplete protocol, and the option that only looks like a query. - assert!(!early_version_query(build_flavor::BuildFlavor::Stable, &args(&["--version"]))); - assert!(!early_version_query(nightly, &args(&["--", "--version"]))); - assert!(!early_version_query(nightly, &args(&["--version", "graph.sbs"]))); - assert!(!early_version_query(nightly, &args(&["--launch-profile", "nightly-v1", "--version"]))); - assert!(!early_version_query(nightly, &[])); + // Everything else keeps the ordinary startup: a file named `--version`, an incomplete + // protocol, and options that only look like a query. + assert!(!launch_profile::parse_startup(nightly, args(&["--", "--version"])).unwrap().is_version_query()); + assert!(!launch_profile::parse_startup(nightly, args(&["--version", "graph.sbs"])).unwrap().is_version_query()); + assert!(launch_profile::parse_startup(nightly, args(&["--launch-profile", "nightly-v1", "--version"])).is_err()); + assert!(!launch_profile::parse_startup(nightly, args(&[])).unwrap().is_version_query()); } #[test] diff --git a/apps/materialcraft/src/profile_root.rs b/apps/materialcraft/src/profile_root.rs index a087c845..08cf1e69 100644 --- a/apps/materialcraft/src/profile_root.rs +++ b/apps/materialcraft/src/profile_root.rs @@ -1,345 +1,80 @@ -//! App-owned nightly profile fences; no stable fallback, migration or process environment changes. +//! MaterialCraft-specific nightly profile specification for `craft-nightly`. use std::ffi::OsString; +use std::path::PathBuf; -use std::path::{Component, Path, PathBuf}; +use craft_nightly::AppProfileSpec; + +/// Canonical lowercase app identifier shared with ArtCraft Launcher. +pub const APP_ID: &str = "materialcraft"; -/// A marker beside an executable that makes the stable copy portable (`craft_update`'s convention). -const PORTABLE_MARKER: &str = "portable.txt"; -/// The data folder a portable copy keeps beside itself. -const PORTABLE_DATA_DIR: &str = "MaterialCraftData"; -/// The folder `Documents/MaterialCraft` holds the stable autosaves in. -const USER_DATA_DIR: &str = "MaterialCraft"; /// The private recovery folder inside the nightly profile (the same name the stable app's autosave /// folder takes under its Documents folder). const RECOVERY: &str = materialcraft_ui_egui::data_root::RECOVERY; -/// Known folder-only entries directly inside the nightly profile. -const PROFILE_FOLDERS: [&str; 2] = [RECOVERY, "cache"]; -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum Platform { - Windows, - Linux, - Mac, +/// Returns MaterialCraft's [`AppProfileSpec`] populated from the current process environment. +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 ignores_case(self) -> bool { - self != Self::Linux +fn spec_with_env(env: &impl Fn(&str) -> Option) -> AppProfileSpec { + AppProfileSpec { + app_id: APP_ID, + display_name: "MaterialCraft", + stable_dir_names: &["materialcraft", "MaterialCraft"], + stable_package_id: "ai.storyteller.materialcraft", + nightly_package_id: "ai.storyteller.materialcraft.nightly", + profile_root_env: None, + forbidden_env_vars: &["MATERIALCRAFT_DATA_DIR", "MATERIALCRAFT_CACHE_DIR", "MATERIALCRAFT_NO_PREFS"], + portable_markers: &["portable.txt"], + folder_only_entries: &[RECOVERY, "cache", "cache/previews"], + extra_forbidden_roots: extra_forbidden_roots(env), } } -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")); +fn non_empty_abs(env: &impl Fn(&str) -> Option, key: &str) -> Option { + let value = env(key)?; + if value.is_empty() { + return None; } - Ok(path) + let path = PathBuf::from(value); + if path.is_absolute() { Some(path) } else { None } } -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)), +fn extra_forbidden_roots(env: &impl Fn(&str) -> Option) -> Vec { + let mut roots = Vec::new(); + // Stable Documents/MaterialCraft folder holding autosaves and exported documents. + if let Some(home) = non_empty_abs(env, "USERPROFILE").or_else(|| non_empty_abs(env, "HOME")) { + roots.push(home.join("Documents").join("MaterialCraft")); } -} - -/// 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")?; + #[cfg(target_os = "windows")] + { + // The MSI's default per-machine folder (materialcraft.wxs). + for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] { + if let Some(base) = non_empty_abs(env, key) { + roots.push(base.join("MaterialCraft")); } - 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/materialcraft", "/usr/local/bin/materialcraft", "/opt/materialcraft"].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.materialcraft")); } } - Ok(parent.to_path_buf()) -} - -/// The stable folder holding autosaves and exported documents in the user's Documents folder. -/// It is resolved the same way `user_directory::user_dir` resolves it: `USERPROFILE` on Windows, -/// `HOME` elsewhere. -fn documents_boundary(env: &impl Fn(&str) -> Option) -> Result { - let home = match env("USERPROFILE").filter(|value| !value.is_empty()) { - Some(value) => absolute(PathBuf::from(value), "USERPROFILE")?, - None => required_base(env, "HOME")?, - }; - Ok(home.join("Documents").join(USER_DATA_DIR)) -} - -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(USER_DATA_DIR))).collect::, _>>()?; - // The MSI's default per-machine folder (materialcraft.wxs). A custom install folder is - // not known here; the executable's own folder is fenced below. - 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(USER_DATA_DIR)); - } - } - 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("materialcraft"))) - .collect::, _>>()?; - roots.extend(["/usr/bin/materialcraft", "/usr/local/bin/materialcraft", "/opt/materialcraft"].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.materialcraft")); - 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/MaterialCraft"), - library.join("Caches/materialcraft"), - library.join("Caches/ai.storyteller.materialcraft"), - library.join("Preferences/MaterialCraft"), - library.join("Preferences/ai.storyteller.materialcraft.plist"), - library.join("Saved Application State/ai.storyteller.materialcraft.savedState"), - home.join("Applications/MaterialCraft.app"), - PathBuf::from("/Applications/MaterialCraft.app"), - ] + roots.push(library.join("Preferences/ai.storyteller.materialcraft.plist")); + roots.push(library.join("Saved Application State/ai.storyteller.materialcraft.savedState")); + roots.push(home.join("Applications/MaterialCraft.app")); } - }; - roots.push(documents_boundary(env)?); - 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.push(PathBuf::from("/Applications/MaterialCraft.app")); } - 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) -} - -/// Every existing entry directly in the profile (Recovery, app.ron, cache 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")?; - } - } - // The preview cache is the one nested destination Nightly writes and clears on its own: a link - // at cache/previews would put its thumbnails in, and clear, the stable app's cache instead. - private_subdirectory(root, std::path::Path::new("cache").join("previews"), "preview cache")?; - Ok(()) -} - -/// Persisted files must have their own ordinary file identity, not an alias to other data. -fn private_regular_file(path: &Path, metadata: &std::fs::Metadata) -> Result<(), String> { - #[cfg(unix)] - { - use std::os::unix::fs::MetadataExt as _; - if metadata.nlink() != 1 { - return Err("the nightly profile file must not be shared".into()); - } - } - #[cfg(windows)] - { - use winsafe::{HFILE, co}; - let (file, _) = HFILE::CreateFile( - path.to_str().ok_or("the nightly profile file path is not textual")?, - co::GENERIC::default(), - Some(co::FILE_SHARE::READ | co::FILE_SHARE::WRITE | co::FILE_SHARE::DELETE), - None, - co::DISPOSITION::OPEN_EXISTING, - co::FILE_ATTRIBUTE::NORMAL, - Some(co::FILE_FLAG::OPEN_REPARSE_POINT), - None, - None, - ) - .map_err(|e| e.to_string())?; - let info = file.GetFileInformationByHandle().map_err(|e| e.to_string())?; - if info.dwFileAttributes.has(co::FILE_ATTRIBUTE::REPARSE_POINT | co::FILE_ATTRIBUTE::DIRECTORY) { - return Err("the nightly profile file must not be an alias or directory".into()); - } - if info.nNumberOfLinks != 1 { - return Err("the nightly profile file must not be shared".into()); - } - } - let _ = (path, metadata); - Ok(()) -} - -/// Recognise the shared portable data namespace in both the supplied and resolved path. -fn is_portable_layout(path: &Path, platform: Platform) -> bool { - // A folder under a portable copy belongs to that copy too. Above the chosen folder itself, a - // marker only counts beside a MaterialCraft executable, so an unrelated portable.txt higher up - // (in a user folder or at a drive root) does not refuse the profile. - path.ancestors().enumerate().any(|(depth, ancestor)| { - ancestor.join(PORTABLE_MARKER).is_file() && (depth == 0 || ["materialcraft.exe", "materialcraft"].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 app's exclusive writable probe: create a file only this process can make and remove it. -pub fn probe_writable(dir: &Path) -> std::io::Result<()> { - let probe = dir.join(format!(".nightly-write-probe-{}", std::process::id())); - std::fs::OpenOptions::new().write(true).create_new(true).open(&probe)?; - std::fs::remove_file(probe) -} - -/// The writable hook is the app's exclusive probe. Keeping it injected lets filesystem boundary -/// tests exercise the real policy without starting the app or changing global state. -pub fn validate( - root: &Path, - env: impl Fn(&str) -> Option, - exe: Option<&Path>, - writable: impl FnOnce(&Path) -> std::io::Result<()>, -) -> Result { - validate_for(Platform::current()?, root, env, exe, writable) -} - -fn validate_for( - platform: Platform, - root: &Path, - env: impl Fn(&str) -> Option, - exe: Option<&Path>, - writable: impl FnOnce(&Path) -> std::io::Result<()>, -) -> Result { - absolute(root.to_path_buf(), "the nightly profile root")?; - // Each of these redirects or disables state the profile is supposed to own. - for (key, why) in [ - ("MATERIALCRAFT_DATA_DIR", "the autosaves, recovery copies and saved layout"), - ("MATERIALCRAFT_CACHE_DIR", "the preview cache"), - ("MATERIALCRAFT_NO_PREFS", "the saved preferences and window layout"), - ] { - if env(key).is_some_and(|v| !v.is_empty()) { - return Err(format!("nightly-v1 cannot be combined with {key}, which would take {why} outside its private profile")); - } - } - if platform != Platform::Windows - && let Some(id) = env("FLATPAK_ID").filter(|v| !v.is_empty()) - { - // A Flatpak's data folder and runtime socket namespace belong to its app id. The nightly - // bundle has an id of its own ([`NIGHTLY_FLATPAK_ID`], named by - // `packaging/linux/flatpak-bundle.sh`), so its profile is already the sandbox's own; any - // other instance is the stable app's (or another app's), whose socket this profile must - // not inherit. - if id.to_string_lossy().as_ref() != NIGHTLY_FLATPAK_ID { - return Err("nightly-v1 cannot inherit another Flatpak app's instance; launch through the native Launcher".into()); - } - } - let chosen = canonical_future(root)?; - if is_portable_layout(root, platform) || is_portable_layout(&chosen, platform) { - return Err("the nightly root must not use a portable MaterialCraft installation or its MaterialCraftData 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()); - } - // Recovery can read, adopt, overwrite and sweep entries. Never let its alias leave this - // private profile, including toward a stable Documents folder not in our known roots. - private_subdirectory(&chosen, RECOVERY, "recovery folder")?; - 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()); - } - 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) -} - -/// The app id of the nightly Flatpak bundle (`packaging/linux/flatpak-bundle.sh`): the one Flatpak -/// instance whose sandbox is this channel's own. The window identity (`os_window`) and the bundle id -/// differ on purpose, as they do for stable. -pub const NIGHTLY_FLATPAK_ID: &str = "ai.storyteller.materialcraft.nightly"; - -/// The nightly autosave folder: numbered recovery copies of the open package. Only the unix -/// symlink test reads it, so a Windows test build would have no caller (`-D dead-code`). -#[cfg(all(test, unix))] -pub fn recovery_dir(root: &Path) -> Result { - private_subdirectory(root, RECOVERY, "recovery folder") + roots } #[cfg(test)] diff --git a/apps/materialcraft/src/profile_root.test.rs b/apps/materialcraft/src/profile_root.test.rs index 6b3b7830..cea0f13e 100644 --- a/apps/materialcraft/src/profile_root.test.rs +++ b/apps/materialcraft/src/profile_root.test.rs @@ -1,11 +1,11 @@ use super::*; +use craft_nightly::{ProfileError, validate_and_prepare_root}; use std::collections::BTreeMap; +use std::path::Path; use std::sync::atomic::{AtomicU64, Ordering}; struct Fixture { root: PathBuf, - env: BTreeMap, - exe: PathBuf, } impl Fixture { @@ -19,416 +19,149 @@ impl Fixture { Err(error) => panic!("cannot create owned fixture: {error}"), } }; - let home = root.join("home"); - let exe = root.join("install/materialcraft"); - std::fs::create_dir_all(&home).unwrap(); - std::fs::create_dir_all(exe.parent().unwrap()).unwrap(); - std::fs::write(&exe, b"fixture executable, never run").unwrap(); - let env = [("HOME", home), ("APPDATA", root.join("roaming")), ("LOCALAPPDATA", root.join("local"))] - .into_iter() - .map(|(key, value)| (key.into(), value.into_os_string())) - .collect(); - Self { root, env, exe } + Self { root } } - fn get(&self, key: &str) -> Option { - self.env.get(key).cloned() + fn path(&self) -> &Path { + &self.root } - - fn check(&self, platform: Platform, root: &Path) -> Result { - validate_for(platform, root, |key| self.get(key), Some(&self.exe), probe_owned) - } - - fn home(&self) -> PathBuf { - PathBuf::from(self.get("HOME").unwrap()) - } -} - -/// The production probe against an owned directory. -fn probe_owned(dir: &Path) -> std::io::Result<()> { - probe_writable(dir) } 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(); + let _ = std::fs::remove_dir_all(&self.root); } } #[test] -fn the_stable_documents_folder_holding_autosaves_is_fenced_everywhere() { +fn materialcraft_profile_spec_preserves_fencing_configuration() { + let spec = spec(); + assert_eq!(spec.app_id, "materialcraft"); + assert_eq!(spec.display_name, "MaterialCraft"); + assert_eq!(spec.stable_dir_names, &["materialcraft", "MaterialCraft"]); + assert_eq!(spec.stable_package_id, "ai.storyteller.materialcraft"); + assert_eq!(spec.nightly_package_id, "ai.storyteller.materialcraft.nightly"); + assert_eq!(spec.profile_root_env, None); + assert_eq!(spec.forbidden_env_vars, &["MATERIALCRAFT_DATA_DIR", "MATERIALCRAFT_CACHE_DIR", "MATERIALCRAFT_NO_PREFS"]); + assert_eq!(spec.portable_markers, &["portable.txt"]); + assert_eq!(spec.folder_only_entries, &[RECOVERY, "cache", "cache/previews"]); +} + +#[test] +fn extra_forbidden_roots_include_documents_and_platform_boundaries() { let fixture = Fixture::new(); - let documents = fixture.home().join("Documents/MaterialCraft"); + let home = fixture.path().join("home"); + let mut env = BTreeMap::::new(); + env.insert("HOME".into(), home.clone().into_os_string()); + #[cfg(target_os = "windows")] + { + env.insert("USERPROFILE".into(), home.clone().into_os_string()); + env.insert("ProgramFiles".into(), fixture.path().join("ProgramFiles").into_os_string()); + } + let spec = spec_with_env(&|key| env.get(key).cloned()); + assert!(spec.extra_forbidden_roots.contains(&home.join("Documents").join("MaterialCraft"))); + #[cfg(all(unix, not(target_os = "macos")))] + { + assert!(spec.extra_forbidden_roots.contains(&PathBuf::from("/usr/bin/materialcraft"))); + assert!(spec.extra_forbidden_roots.contains(&PathBuf::from("/usr/local/bin/materialcraft"))); + assert!(spec.extra_forbidden_roots.contains(&PathBuf::from("/opt/materialcraft"))); + assert!(spec.extra_forbidden_roots.contains(&home.join(".var/app/ai.storyteller.materialcraft"))); + } + #[cfg(target_os = "macos")] + { + assert!(spec.extra_forbidden_roots.contains(&home.join("Library/Preferences/ai.storyteller.materialcraft.plist"))); + assert!(spec.extra_forbidden_roots.contains(&home.join("Library/Saved Application State/ai.storyteller.materialcraft.savedState"))); + assert!(spec.extra_forbidden_roots.contains(&home.join("Applications/MaterialCraft.app"))); + assert!(spec.extra_forbidden_roots.contains(&PathBuf::from("/Applications/MaterialCraft.app"))); + } + #[cfg(target_os = "windows")] + { + assert!(spec.extra_forbidden_roots.contains(&fixture.path().join("ProgramFiles").join("MaterialCraft"))); + } +} + +#[test] +fn nightly_profile_creates_reopens_and_enforces_folder_only_entries() { + let fixture = Fixture::new(); + let spec = spec(); + let private = fixture.path().join("nightly-reopen"); + + assert_eq!(validate_and_prepare_root(&private, &spec).unwrap(), private); + for name in ["app.ron", "nightly-session.lock", "nightly-session.json"] { + std::fs::write(private.join(name), b"saved profile data").unwrap(); + } + for name in [RECOVERY, "cache"] { + std::fs::create_dir(private.join(name)).unwrap(); + } + assert_eq!(validate_and_prepare_root(&private, &spec).unwrap(), private); + assert_eq!(std::fs::read(private.join("app.ron")).unwrap(), b"saved profile data"); + + for name in [RECOVERY, "cache"] { + let path = private.join(name); + std::fs::remove_dir(&path).unwrap(); + std::fs::write(&path, b"not a directory").unwrap(); + assert!(matches!(validate_and_prepare_root(&private, &spec), Err(ProfileError::ExpectedDirectoryEntry(_))), "{name} must stay a directory"); + std::fs::remove_file(&path).unwrap(); + std::fs::create_dir(&path).unwrap(); + } + + let previews = private.join("cache/previews"); + std::fs::create_dir(&previews).unwrap(); + assert_eq!(validate_and_prepare_root(&private, &spec).unwrap(), private); + std::fs::remove_dir(&previews).unwrap(); + std::fs::write(&previews, b"not a directory").unwrap(); + assert!(matches!(validate_and_prepare_root(&private, &spec), Err(ProfileError::ExpectedDirectoryEntry(_)))); +} + +#[test] +fn stable_documents_and_extra_forbidden_roots_are_fenced() { + let fixture = Fixture::new(); + let documents = fixture.path().join("home/Documents/MaterialCraft"); std::fs::create_dir_all(documents.join("autosave")).unwrap(); - std::fs::write(documents.join("autosave").join("1.mcraft"), b"stable autosave bytes").unwrap(); - for platform in [Platform::Windows, Platform::Linux, Platform::Mac] { - for candidate in [documents.clone(), documents.join("nightly"), documents.join("autosave/nightly")] { - let existed = candidate.exists(); - 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("overlap")); - assert!(!probed.get(), "reject stable data before the writable probe"); - // The stable folder itself exists (the fixture made it); validation must never create - // the ones below it. - assert_eq!(candidate.exists(), existed, "{}", candidate.display()); - } + std::fs::write(documents.join("autosave/1.mcraft"), b"stable autosave bytes").unwrap(); + + let mut env = BTreeMap::::new(); + env.insert("HOME".into(), fixture.path().join("home").into_os_string()); + #[cfg(target_os = "windows")] + env.insert("USERPROFILE".into(), fixture.path().join("home").into_os_string()); + let spec = spec_with_env(&|key| env.get(key).cloned()); + + for candidate in [documents.clone(), documents.join("nightly"), documents.join("autosave/nightly")] { + let existed = candidate.exists(); + assert!(matches!(validate_and_prepare_root(&candidate, &spec), Err(ProfileError::ForbiddenRootOverlap { .. }))); + assert_eq!(candidate.exists(), existed, "{}", candidate.display()); } - assert_eq!(std::fs::read(documents.join("autosave").join("1.mcraft")).unwrap(), b"stable autosave bytes"); + assert_eq!(std::fs::read(documents.join("autosave/1.mcraft")).unwrap(), b"stable autosave bytes"); } #[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("MaterialCraftData"); - std::fs::create_dir_all(&stable_data).unwrap(); - std::fs::write(stable_install.join(PORTABLE_MARKER), b"owned portable fixture").unwrap(); - std::fs::write(stable_data.join("app.ron"), 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("app.ron")).unwrap(), b"stable settings must not change"); - assert_eq!(std::fs::read_dir(&stable_data).unwrap().count(), 1); - } - } - let private = fixture.root.join("MaterialCraftData-backup-name/nightly"); - assert!(fixture.check(Platform::Linux, &private).is_ok(), "a merely similar name is not a portable settings component"); +fn relative_and_parent_traversal_roots_are_refused() { + let spec = spec(); + assert!(matches!(validate_and_prepare_root(Path::new("relative/nightly"), &spec), Err(ProfileError::RelativeProfileRoot(_)))); + let traversal = if cfg!(windows) { Path::new(r"C:\nightly\..\escape") } else { Path::new("/nightly/../escape") }; + assert!(matches!(validate_and_prepare_root(traversal, &spec), Err(ProfileError::ParentTraversalInProfileRoot(_)))); } #[cfg(unix)] #[test] -fn recovery_aliases_cannot_redirect_to_stable_missing_or_profile_root_data() { - let fixture = Fixture::new(); - let stable = fixture.home().join("Documents/MaterialCraft/autosave"); - 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"); - assert_eq!(std::fs::read_dir(&stable).unwrap().count(), 1); -} - -#[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); - assert_eq!(recovery_dir(&std::fs::canonicalize(&private).unwrap()).unwrap(), recovery); -} - -#[test] -fn overlap_check_handles_ancestor_descendant_and_prefix_lookalikes() { - let fixture = Fixture::new(); - let root = fixture.home().join("nightly/profiles/materialcraft"); - 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("materialcraft-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("materialcraft"); - 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/materialcraft"); - 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 ["app.ron", "nightly-session.lock", "nightly-session.json"] { - std::fs::write(private.join(name), b"saved profile data").unwrap(); - } - for name in PROFILE_FOLDERS { - std::fs::create_dir(private.join(name)).unwrap(); - } - assert_eq!(fixture.check(platform, &private).unwrap(), private); - assert_eq!(std::fs::read(private.join("app.ron")).unwrap(), b"saved profile data"); - for name in PROFILE_FOLDERS { - let path = private.join(name); - std::fs::remove_dir(&path).unwrap(); - std::fs::write(&path, b"not a directory").unwrap(); - assert!(fixture.check(platform, &private).is_err(), "{name} must stay a directory"); - std::fs::remove_file(&path).unwrap(); - std::fs::create_dir(&path).unwrap(); - } - } -} - -#[test] -fn mac_fences_only_app_library_subtrees_and_the_entire_bundle() { - let mut fixture = Fixture::new(); - fixture.exe = fixture.root.join("install/MaterialCraft Nightly.app/Contents/MacOS/MaterialCraft"); - 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/MaterialCraft", - "Caches/materialcraft", - "Caches/ai.storyteller.materialcraft", - "Preferences/MaterialCraft", - "Saved Application State/ai.storyteller.materialcraft.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/materialcraft"); - 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("MaterialCraft"); - 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/materialcraft")).is_ok()); -} - -#[test] -fn windows_default_msi_install_folders_are_fenced() { - let mut fixture = Fixture::new(); - 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("MaterialCraft"); - assert!(fixture.check(Platform::Windows, &machine.join("nightly")).unwrap_err().contains("overlap")); - assert!(!machine.exists()); - } - let local = PathBuf::from(fixture.get("LOCALAPPDATA").unwrap()); - let sibling = local.join("Programs").join("ArtCraft").join("ArtCraftLauncher").join("nightly").join("materialcraft"); - assert!(fixture.check(Platform::Windows, &sibling).is_ok(), "the Launcher's own Programs sibling is not MaterialCraft'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/MC"); - std::fs::create_dir_all(&portable).unwrap(); - std::fs::write(portable.join(PORTABLE_MARKER), b"stable portable copy").unwrap(); - std::fs::write(portable.join("materialcraft.exe"), b"stable portable executable, never run").unwrap(); - for platform in [Platform::Windows, Platform::Linux, Platform::Mac] { - for candidate in [portable.join("nightly"), portable.join("deeper/nightly")] { - let probed = std::cell::Cell::new(false); - let result = validate_for( - platform, - &candidate, - |key| fixture.get(key), - Some(&fixture.exe), - |_| { - probed.set(true); - Ok(()) - }, - ); - assert!(result.unwrap_err().contains("portable")); - assert!(!probed.get()); - assert!(!candidate.exists()); - } - } - // A portable.txt that no MaterialCraft 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_MARKER), b"another app's marker").unwrap(); - assert!(fixture.check(Platform::Windows, &unrelated.join("Launcher/nightly/materialcraft")).is_ok()); -} - -#[test] -fn linux_fences_the_stable_flatpak_data_folder() { - let fixture = Fixture::new(); - let flatpak = fixture.home().join(".var/app/ai.storyteller.materialcraft"); - for candidate in [flatpak.clone(), flatpak.join("data/nightly")] { - assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("overlap")); - } - assert!(!flatpak.exists()); - assert!(fixture.check(Platform::Linux, &fixture.home().join(".var/app/ai.storyteller.launcher/nightly")).is_ok()); -} - -#[cfg(unix)] -#[test] -fn any_profile_entry_alias_must_stay_inside_the_profile() { - let fixture = Fixture::new(); - let stable = fixture.home().join(".local/share/materialcraft/app.ron"); - std::fs::create_dir_all(stable.parent().unwrap()).unwrap(); - std::fs::write(&stable, b"stable layout bytes").unwrap(); - for name in ["app.ron", "cache", RECOVERY] { - let private = fixture.root.join(format!("nightly-{name}")); - std::fs::create_dir(&private).unwrap(); - std::os::unix::fs::symlink(&stable, private.join(name)).unwrap(); - let probed = std::cell::Cell::new(false); - let result = validate_for( - Platform::Linux, - &private, - |key| fixture.get(key), - Some(&fixture.exe), - |_| { - probed.set(true); - Ok(()) - }, - ); - assert!(result.is_err(), "{name} must not lead outside the profile"); - assert!(!probed.get()); - } - let private = fixture.root.join("nightly-inside"); - std::fs::create_dir_all(private.join("real-cache")).unwrap(); - std::fs::write(private.join("app.ron"), b"{}").unwrap(); - std::os::unix::fs::symlink(private.join("real-cache"), private.join("cache")).unwrap(); - assert!(fixture.check(Platform::Linux, &private).is_ok(), "regular files and links that stay inside are fine"); - assert_eq!(std::fs::read(&stable).unwrap(), b"stable layout bytes"); -} - -#[test] -fn ambiguous_environment_and_non_native_sandbox_are_refused_before_creation() { - let mut fixture = Fixture::new(); - let candidate = fixture.home().join("nightly/profiles/materialcraft"); - 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("MATERIALCRAFT_CACHE_DIR".into(), fixture.home().join("custom-cache").into_os_string()); - assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("MATERIALCRAFT_CACHE_DIR")); - fixture.env.remove("MATERIALCRAFT_CACHE_DIR"); - fixture.env.insert("MATERIALCRAFT_NO_PREFS".into(), "1".into()); - assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("MATERIALCRAFT_NO_PREFS")); - fixture.env.remove("MATERIALCRAFT_NO_PREFS"); - // The stable build accepts this variable; a nightly profile must not be moved by it. - fixture.env.insert("MATERIALCRAFT_DATA_DIR".into(), fixture.home().join("custom-data").into_os_string()); - assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("MATERIALCRAFT_DATA_DIR")); - fixture.env.remove("MATERIALCRAFT_DATA_DIR"); - for inherited in ["ai.storyteller.materialcraft", "org.freedesktop.other"] { - fixture.env.insert("FLATPAK_ID".into(), inherited.into()); - assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("Flatpak"), "{inherited}"); - fixture.env.remove("FLATPAK_ID"); - } - fixture.env.remove("HOME"); - assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("HOME")); - assert!(!candidate.exists()); -} - -/// The nightly bundle runs under an app id of its own, so its sandbox data folder is this channel's -/// data root; that one instance is accepted, and its profile stays inside it. -#[test] -fn the_nightly_flatpaks_own_instance_accepts_its_own_profile() { - let mut fixture = Fixture::new(); - fixture.env.insert("FLATPAK_ID".into(), NIGHTLY_FLATPAK_ID.into()); - let private = fixture.home().join(".var/app/ai.storyteller.materialcraft.nightly/data/materialcraft-nightly"); - assert_eq!(fixture.check(Platform::Linux, &private).unwrap(), private); - // Stable's Flatpak folder is still fenced even inside the nightly instance. - let stable = fixture.home().join(".var/app/ai.storyteller.materialcraft"); - assert!(fixture.check(Platform::Linux, &stable).unwrap_err().contains("overlap")); -} - -#[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(".local/share/materialcraft").exists()); -} - -#[cfg(unix)] -#[test] -fn symlink_and_dangling_aliases_cannot_create_or_modify_stable_data() { +fn symlink_and_hardlink_entries_inside_profile_are_refused() { use std::os::unix::fs::symlink; + let fixture = Fixture::new(); - let stable = fixture.home().join(".local/share/materialcraft"); - 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"); + let spec = spec(); + let outside = fixture.path().join("outside"); + std::fs::create_dir_all(&outside).unwrap(); + let outside_file = outside.join("stable.ron"); + std::fs::write(&outside_file, b"stable bytes").unwrap(); + + let with_symlink = fixture.path().join("nightly-symlink"); + std::fs::create_dir(&with_symlink).unwrap(); + symlink(&outside_file, with_symlink.join("app.ron")).unwrap(); + assert!(matches!(validate_and_prepare_root(&with_symlink, &spec), Err(ProfileError::SymlinkEntry(_)))); + + let with_hardlink = fixture.path().join("nightly-hardlink"); + std::fs::create_dir(&with_hardlink).unwrap(); + std::fs::hard_link(&outside_file, with_hardlink.join("app.ron")).unwrap(); + assert!(matches!(validate_and_prepare_root(&with_hardlink, &spec), Err(ProfileError::HardlinkedEntry { nlink: 2, .. }))); + assert_eq!(std::fs::read(&outside_file).unwrap(), b"stable bytes"); }