From 5600be65561d9bc38cf6c0fe6df910c2cdbd346f Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 29 Nov 2026 13:48:49 -0500 Subject: [PATCH] Use craft-nightly for nightly profile self-isolation and security fence (#911) --- Cargo.lock | 9 + Cargo.toml | 2 + apps/texturecraft/Cargo.toml | 2 + apps/texturecraft/src/build_flavor.rs | 32 +- apps/texturecraft/src/launch_profile.rs | 255 +++------ apps/texturecraft/src/main.rs | 40 +- apps/texturecraft/src/profile_root.rs | 668 ++++++------------------ 7 files changed, 277 insertions(+), 731 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 01e17558..2c2a5d6c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1324,6 +1324,14 @@ dependencies = [ "serde", ] +[[package]] +name = "craft-nightly" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=1f6c3a21f85ed96f8fd4ddd5a959d4e1edbedb24#1f6c3a21f85ed96f8fd4ddd5a959d4e1edbedb24" +dependencies = [ + "winsafe", +] + [[package]] name = "craft-pdf" version = "0.1.0" @@ -5949,6 +5957,7 @@ dependencies = [ "craft-host", "craft-image-codecs", "craft-menu", + "craft-nightly", "craft-update", "eframe", "egui", diff --git a/Cargo.toml b/Cargo.toml index bb398c92..2a15ba96 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -89,6 +89,8 @@ craft-menu = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a craft-host = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" } # The theme mode the app hands the runtime (crates/ui-egui/src/framework.rs). craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" } +# Nightly profile isolation, launch protocol, and security fence (apps/texturecraft). +craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "1f6c3a21f85ed96f8fd4ddd5a959d4e1edbedb24" } # egui 0.37 and winit: the suite's forks (storytold/egui, storytold/winit), as craft-libs pins them. [patch.crates-io] diff --git a/apps/texturecraft/Cargo.toml b/apps/texturecraft/Cargo.toml index ab29d036..c9be2510 100644 --- a/apps/texturecraft/Cargo.toml +++ b/apps/texturecraft/Cargo.toml @@ -25,6 +25,8 @@ log = { workspace = true } rfd = { workspace = true } # Pass the selected window backend to the title bar and UI runtime craft-host = { workspace = true } +# Nightly profile isolation, launch protocol, and security fence. +craft-nightly = { workspace = true } # Reads the saved System title bar setting before the window opens (eframe's settings format). ron = "0.12" diff --git a/apps/texturecraft/src/build_flavor.rs b/apps/texturecraft/src/build_flavor.rs index 294f1e19..9330b7d8 100644 --- a/apps/texturecraft/src/build_flavor.rs +++ b/apps/texturecraft/src/build_flavor.rs @@ -1,14 +1,9 @@ //! The build-time channel, which is distinct from a launch selector: no runtime environment can //! promote a stable build into the Nightly one. -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; /// `TEXTURECRAFT_BUILD_CHANNEL=nightly-v1` at compile time (`build.rs`). pub const COMPILED: BuildFlavor = if cfg!(texturecraft_nightly_v1) { BuildFlavor::NightlyV1 } else { BuildFlavor::Stable }; @@ -17,15 +12,6 @@ pub const COMPILED: BuildFlavor = if cfg!(texturecraft_nightly_v1) { BuildFlavor /// workspace version (`build.rs` bakes it so both flavors read it the same way). pub const BUILT_VERSION: &str = env!("TEXTURECRAFT_VERSION"); -/// A nightly build starts only with its profile, and a stable build only without one. -pub fn require_profile(flavor: BuildFlavor, profile: &Profile) -> Result<(), String> { - match (flavor, profile.is_nightly()) { - (BuildFlavor::NightlyV1, false) => Err("Open TextureCraft Nightly from ArtCraft Launcher".into()), - (BuildFlavor::Stable, true) => Err("This is a stable TextureCraft build; nightly-v1 requires the nightly build".into()), - _ => Ok(()), - } -} - /// A refused nightly start explains itself in a native dialog: a release Windows build has no /// console, and a Dock launch on macOS has none either. pub fn needs_native_error(flavor: BuildFlavor, desktop_session: bool) -> bool { @@ -58,22 +44,6 @@ mod tests { assert!(!needs_native_error(BuildFlavor::Stable, false)); } - #[test] - fn nightly_build_without_a_profile_is_refused_before_startup() { - let started = std::cell::Cell::new(false); - let result = require_profile(BuildFlavor::NightlyV1, &Profile::Stable).map(|()| started.set(true)); - assert!(result.unwrap_err().contains("ArtCraft Launcher")); - assert!(!started.get()); - } - - #[test] - fn stable_and_nightly_flavors_accept_only_their_own_profile() { - let nightly = Profile::NightlyV1(std::path::PathBuf::from("already validated root")); - assert!(require_profile(BuildFlavor::Stable, &Profile::Stable).is_ok()); - assert!(require_profile(BuildFlavor::Stable, &nightly).is_err()); - assert!(require_profile(BuildFlavor::NightlyV1, &nightly).is_ok()); - } - #[test] fn the_nightly_version_line_is_exact_and_says_its_channel() { let nightly = version(BuildFlavor::NightlyV1); diff --git a/apps/texturecraft/src/launch_profile.rs b/apps/texturecraft/src/launch_profile.rs index 84f5061f..9e29c559 100644 --- a/apps/texturecraft/src/launch_profile.rs +++ b/apps/texturecraft/src/launch_profile.rs @@ -1,126 +1,30 @@ -//! The Launcher's nightly-v1 bootstrap, selected before logging, updates, fonts or saved state. -//! Stable launches keep their arguments and directory policy unchanged, and no environment is -//! mutated: the profile is a value this process reads, not a variable it exports. +//! The Launcher's nightly-v1 bootstrap and direct-launch self-isolation, backed by `craft-nightly`. +//! +//! Selected before logging, updates, fonts or saved state. Stable launches keep their arguments and +//! directory policy unchanged, and no environment is mutated: the profile is a value this process +//! reads, not a variable it exports. 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}; 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()) -} - -/// 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 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::ensure_writable) +/// Parse startup arguments for `flavor`, validate and prepare the isolated nightly profile root +/// (self-isolating into `craft_nightly::canonical_profile_root("texturecraft")` on direct nightly +/// launches, or using the explicit `--launch-profile nightly-v1 --profile-root ` pair), and +/// install the resolved [`Profile`] into the process-wide `OnceLock`. +pub fn prepare(flavor: BuildFlavor, args: Vec) -> 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::path::PathBuf; fn args(values: &[&str]) -> Vec { values.iter().map(OsString::from).collect() @@ -130,88 +34,93 @@ mod tests { if cfg!(windows) { r"C:\NightlyData\profiles\texturecraft" } else { "/nightly-data/profiles/texturecraft" } } - fn nightly() -> Vec { - args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--"]) - } - #[test] - fn stable_arguments_and_directory_policy_are_unchanged() { + fn stable_arguments_are_unchanged_and_nightly_flags_are_refused() { + let spec = crate::profile_root::spec(); for argv in [args(&[]), args(&["model.glb"]), args(&["--gpu", "nvidia"]), args(&["--", "--launch-profile", "model.glb"])] { - 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 = craft_nightly::parse_startup(BuildFlavor::Stable, &spec, argv.clone(), &StartupOptions::new()).unwrap(); + assert_eq!(launch.profile, Profile::Stable); + assert_eq!(launch.passthrough_args, argv); } + + let nightly_flags = args(&["--launch-profile", craft_nightly::NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--"]); + let err = craft_nightly::parse_startup(BuildFlavor::Stable, &spec, nightly_flags, &StartupOptions::new()).unwrap_err(); + assert!(matches!(err, ProfileError::NightlyFlagsInStableBuild)); } #[test] - fn exact_version_and_root_are_parsed_without_reinterpreting_file_names() { - let mut argv = nightly(); - argv.extend(args(&["--profile-root", "model with spaces.glb"])); - let launch = parse(argv).unwrap(); + fn direct_nightly_launch_self_isolates_to_canonical_root_and_preserves_args() { + let spec = crate::profile_root::spec(); + let expected_root = craft_nightly::canonical_profile_root(crate::profile_root::APP_ID).expect("canonical profile root"); + let argv = args(&["model.glb", "--gpu", "nvidia"]); + + let launch = craft_nightly::parse_startup(BuildFlavor::NightlyV1, &spec, argv.clone(), &StartupOptions::new()).unwrap(); + assert_eq!(launch.profile, Profile::NightlyV1(expected_root)); + assert!(launch.profile.is_nightly()); + assert_eq!(launch.passthrough_args, argv); + assert!(!launch.is_version_query()); + } + + #[test] + fn explicit_launcher_flags_override_canonical_root_and_preserve_files() { + let spec = crate::profile_root::spec(); + let argv = args(&[ + craft_nightly::LAUNCH_PROFILE_FLAG, + craft_nightly::NIGHTLY_V1_CONTRACT, + craft_nightly::PROFILE_ROOT_FLAG, + absolute(), + "--", + "--profile-root", + "model with spaces.glb", + ]); + + let launch = craft_nightly::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", "model with spaces.glb"])); + assert_eq!(launch.passthrough_args, args(&["--profile-root", "model with spaces.glb"])); } #[test] - fn missing_duplicate_unknown_and_conflicting_profile_arguments_are_refused() { + fn invalid_profile_arguments_are_refused() { + let spec = crate::profile_root::spec(); for argv in [ - args(&["--launch-profile", VERSION]), + args(&["--launch-profile", craft_nightly::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(), "--gpu", "nvidia", "--"]), - args(&["--launch-profile", VERSION, "--profile-root", absolute()]), - args(&["--launch-profile=nightly-v1", "--profile-root", absolute(), "--"]), - args(&["--launch-profile", VERSION, "--profile-root=/nightly-data/profiles/texturecraft", "--"]), + args(&[ + "--launch-profile", + craft_nightly::NIGHTLY_V1_CONTRACT, + "--launch-profile", + craft_nightly::NIGHTLY_V1_CONTRACT, + "--profile-root", + absolute(), + "--", + ]), + args(&["--launch-profile", craft_nightly::NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--profile-root", absolute(), "--"]), + args(&["--launch-profile", craft_nightly::NIGHTLY_V1_CONTRACT, "--profile-root", "", "--"]), + args(&["--gpu", "nvidia", "--launch-profile", craft_nightly::NIGHTLY_V1_CONTRACT, "--profile-root", absolute()]), ] { - assert!(parse(argv.clone()).is_err(), "{argv:?}"); + assert!(craft_nightly::parse_startup(BuildFlavor::NightlyV1, &spec, argv.clone(), &StartupOptions::new()).is_err(), "{argv:?}"); } } #[test] - fn the_launcher_version_check_is_a_version_query_only_in_its_exact_form() { - let pair = &["--launch-profile", VERSION, "--profile-root", absolute()]; - let reversed = &["--profile-root", absolute(), "--launch-profile", VERSION]; + fn version_queries_are_recognized_plain_and_via_launcher() { + let spec = crate::profile_root::spec(); for flag in ["--version", "-V"] { - for form in [pair, reversed] { - let mut argv = args(form); - argv.push(flag.into()); - assert!(version_query(&argv), "{argv:?}"); - } - } - for argv in [ - args(&["--version"]), - args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--", "--version"]), - args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--"]), - args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--gpu", "nvidia", "--version"]), - args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--version"]), - args(&["--version", "--launch-profile", VERSION, "--profile-root", absolute()]), - args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--version"]), - args(&["--launch-profile", VERSION, "--profile-root", "relative", "--version"]), - args(&["--launch-profile", VERSION, "--version"]), - args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--help"]), - ] { - assert!(!version_query(&argv), "{argv:?}"); - } - // Outside the query the strict protocol still refuses the version flag. - assert!(parse(args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version"])).is_err()); - } + let plain = craft_nightly::parse_startup(BuildFlavor::NightlyV1, &spec, args(&[flag]), &StartupOptions::new()).unwrap(); + assert!(plain.is_version_query(), "plain {flag}"); - #[test] - fn failed_root_validation_never_reaches_startup_or_falls_back_to_stable() { - let reached = Cell::new(false); - let result = prepare(parse(nightly()).unwrap(), |_| Err("read-only or unsafe profile".into())).map(|_| reached.set(true)); - assert!(result.is_err()); - assert!(!reached.get()); - } + let launcher = craft_nightly::parse_startup( + BuildFlavor::NightlyV1, + &spec, + args(&["--launch-profile", craft_nightly::NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), flag]), + &StartupOptions::new(), + ) + .unwrap(); + assert!(launcher.is_version_query(), "launcher {flag}"); + } - #[test] - fn successful_root_validation_keeps_the_persistent_root_not_the_binary_tag() { - let checked = PathBuf::from(absolute()).join("checked"); - let launch = prepare(parse(nightly()).unwrap(), |_| Ok(checked.clone())).unwrap(); - assert_eq!(launch.profile.root(), Some(checked.as_path())); - assert!(launch.profile.is_nightly()); + let file_named_version = craft_nightly::parse_startup(BuildFlavor::NightlyV1, &spec, args(&["--", "--version"]), &StartupOptions::new()).unwrap(); + assert!(!file_named_version.is_version_query()); } } diff --git a/apps/texturecraft/src/main.rs b/apps/texturecraft/src/main.rs index 678c0a8c..0255487b 100644 --- a/apps/texturecraft/src/main.rs +++ b/apps/texturecraft/src/main.rs @@ -291,33 +291,31 @@ fn report_launch_profile_error(error: &str) { } } -/// Select the immutable launch profile before any startup service or side effect, and answer the -/// Launcher's version queries before root validation, logging, IPC or a window. `None` means the -/// launch is already answered and the process returns. +/// Select the immutable launch profile before any startup service or side effect, and answer +/// version queries before root validation, logging, IPC or a window. `None` means the launch is +/// already answered and the process returns. fn prepare_launch() -> Option> { let argv: Vec = std::env::args_os().skip(1).collect(); - // Plain `--version`, or the Launcher's `--launch-profile nightly-v1 --profile-root - // --version`: both are answered here, with nothing but standard output written. - if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && (build_flavor::version_query(&argv) || launch_profile::version_query(&argv)) { + // Plain `--version` / `-V` is answered immediately with nothing but standard output written, + // even in a minimal environment without home/data variables. + if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && build_flavor::version_query(&argv) { + use std::io::Write as _; + let _ = writeln!(std::io::stdout(), "{}", build_flavor::version(build_flavor::COMPILED)); + return None; + } + let early = launch_profile::prepare(build_flavor::COMPILED, argv).unwrap_or_else(|error| { + report_launch_profile_error(&error.to_string()); + std::process::exit(2) + }); + // Launcher's `--launch-profile nightly-v1 --profile-root --version`: `craft-nightly` + // skips root validation and profile installation for version queries. + if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && early.is_version_query() { use std::io::Write as _; let _ = writeln!(std::io::stdout(), "{}", build_flavor::version(build_flavor::COMPILED)); return None; } - let early = launch_profile::parse(argv) - .and_then(|launch| { - build_flavor::require_profile(build_flavor::COMPILED, &launch.profile)?; - initialize_nightly_process_identity().map_err(|error| error.to_string())?; - Ok(launch) - }) - .and_then(|launch| { - launch_profile::prepare(launch, |root| launch_profile::validate_root(root, |key| std::env::var_os(key), std::env::current_exe().ok().as_deref())) - }) - .unwrap_or_else(|error| { - report_launch_profile_error(&error); - std::process::exit(2) - }); let identity = if early.profile.is_nightly() { LaunchIdentity::NightlyV1 } else { LaunchIdentity::Stable }; - if let Err(error) = launch_profile::install(early.profile).and_then(|()| os_window::select_identity(identity)) { + if let Err(error) = initialize_nightly_process_identity().map_err(|error| error.to_string()).and_then(|()| os_window::select_identity(identity)) { report_launch_profile_error(&error); std::process::exit(2); } @@ -326,7 +324,7 @@ fn prepare_launch() -> Option> { texturecraft_ui_egui::set_data_root(root.clone()); texturecraft_ui_egui::os_window::set_display_version(build_flavor::BUILT_VERSION.to_owned()); } - Some(early.args) + Some(early.passthrough_args) } /// The launch arguments as text. A Nightly protocol argument is a path the app opens, so a value diff --git a/apps/texturecraft/src/profile_root.rs b/apps/texturecraft/src/profile_root.rs index db10fdae..7ab39c60 100644 --- a/apps/texturecraft/src/profile_root.rs +++ b/apps/texturecraft/src/profile_root.rs @@ -1,567 +1,223 @@ -//! App-owned nightly profile fences; no stable fallback, migration or process environment changes. +//! App-owned nightly profile specification backed by `craft-nightly`. //! -//! A Nightly profile has to hold *all* of its user state: eframe's `app.ron`/`ui.json`, the error -//! log, session logs, autosave copies, smart materials, layouts, templates, brush and export -//! presets. Anything that resolves to a stable folder would read and prune Stable's files, so the -//! root is refused when it overlaps one of them, when an entry inside it is an alias that leaves it, -//! or when it is not writable. +//! A Nightly profile holds *all* of its user state: eframe's `app.ron`/`ui.json`, the error log, +//! session logs, autosave copies, smart materials, layouts, templates, brush and export presets. +//! `craft-nightly` enforces the security fence, symlink/hardlink checks, `0o700` hardening, and +//! writability probe using the TextureCraft-specific boundaries declared here. use std::ffi::OsString; -use std::path::{Component, Path, PathBuf}; +use std::path::PathBuf; -/// The folder names the launch checks use for this app in each platform's location. +use craft_nightly::AppProfileSpec; + +/// Canonical lowercase app identifier used for the default nightly profile path. +pub const APP_ID: &str = "texturecraft"; +/// Human-readable application name and stable folder name. const BRAND: &str = "TextureCraft"; -/// The bundle identifier of the stable package (macOS library folders, the Linux Flatpak). -const STABLE_ID: &str = "ai.storyteller.texturecraft"; -/// The package id of the Nightly Flatpak bundle (`packaging/linux/flatpak-bundle.sh`). Inside that -/// sandbox `FLATPAK_ID` is always set, so this exact id is the one a Nightly native launch accepts. -const NIGHTLY_ID: &str = "ai.storyteller.texturecraft.nightly"; /// eframe lowercases its folder name on Linux (`file_storage.rs`), so Stable's real settings folder /// is `$XDG_DATA_HOME/texturecraft`, not the capitalised `TextureCraft` the app is called. const LINUX_STORAGE_BRAND: &str = "texturecraft"; - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum Platform { - Windows, - Linux, - Mac, -} - -impl Platform { - fn current() -> Result { - match std::env::consts::OS { - "windows" => Ok(Self::Windows), - "linux" => Ok(Self::Linux), - "macos" => Ok(Self::Mac), - _ => Err("nightly-v1 is not defined for this operating system".into()), - } - } - - fn ignores_case(self) -> bool { - self != Self::Linux - } -} - -fn absolute(path: PathBuf, label: &str) -> Result { - if !path.is_absolute() || path.components().any(|c| matches!(c, Component::ParentDir)) { - return Err(format!("{label} must be absolute and contain no parent traversal")); - } - Ok(path) -} - -fn required_base(env: &impl Fn(&str) -> Option, key: &str) -> Result { - let value = env(key).filter(|v| !v.is_empty()).ok_or_else(|| format!("cannot establish the stable {key} boundary"))?; - absolute(PathBuf::from(value), key) -} - -fn xdg_base(env: &impl Fn(&str) -> Option, key: &str, fallback: &str) -> Result { - match env(key).filter(|v| !v.is_empty()) { - Some(value) => absolute(PathBuf::from(value), key), - None => Ok(required_base(env, "HOME")?.join(fallback)), - } -} - -/// Resolve existing ancestors before creating anything. A dangling link or an inaccessible ancestor -/// is not a missing directory that may be replaced or followed later. -fn canonical_future(path: &Path) -> Result { - let mut parent = path; - let mut missing = Vec::new(); - loop { - match std::fs::symlink_metadata(parent) { - Ok(_) => break, - Err(error) if error.kind() == std::io::ErrorKind::NotFound => { - missing.push(parent.file_name().ok_or("the profile root has no existing ancestor")?.to_os_string()); - parent = parent.parent().ok_or("the profile root has no existing ancestor")?; - } - Err(error) => return Err(format!("cannot inspect the profile boundary: {error}")), - } - } - let mut resolved = std::fs::canonicalize(parent).map_err(|e| format!("cannot resolve the profile boundary: {e}"))?; - for part in missing.into_iter().rev() { - resolved.push(part); - } - Ok(resolved) -} - -/// Whether one path is the other or contains it (in either direction), compared component by -/// component and folded the way the platform's filesystem folds names. `TextureCraft2` is not -/// inside `TextureCraft`. -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) -} - -/// The running install: never let the profile live inside it (it would be replaced or removed by -/// the next update). -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 bundle, 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()) -} - -/// The default data folder, `Documents/TextureCraft`, as the app's own resolver builds it -/// (`crate::data_folder("")`): `USERPROFILE` on Windows and `HOME` elsewhere, then `Documents`. -fn default_data_folder(platform: Platform, env: &impl Fn(&str) -> Option) -> Result { - let home = match platform { - Platform::Windows => required_base(env, "USERPROFILE")?, - _ => required_base(env, "HOME")?, - }; - Ok(home.join("Documents").join(BRAND)) -} - -fn forbidden_roots(platform: Platform, env: &impl Fn(&str) -> Option, exe: &Path) -> Result, String> { - let mut roots = match platform { - Platform::Windows => { - // eframe's settings folder (`%APPDATA%\TextureCraft`), its local counterpart, and the MSI's - // per-machine and any per-user install folders. A custom install folder is covered by the - // executable's own folder below. - let mut roots = ["APPDATA", "LOCALAPPDATA"].into_iter().map(|key| required_base(env, key).map(|p| p.join(BRAND))).collect::, _>>()?; - roots.push(required_base(env, "LOCALAPPDATA")?.join("Programs").join("ArtCraft").join(BRAND)); - 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(BRAND)); - } - } - roots - } - Platform::Linux => { - // The four XDG roots carry eframe's settings, caches and state under the app's name. - 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(BRAND))) - .collect::, _>>()?; - // eframe's own folder for this app on Linux, which is what holds Stable's `app.ron`, - // `ui.json` and `errors.log`: it folds the name, so it is the lowercase one. - roots.push(xdg_base(env, "XDG_DATA_HOME", ".local/share")?.join(LINUX_STORAGE_BRAND)); - roots.extend(["/usr/bin/texturecraft", "/usr/local/bin/texturecraft", "/opt/texturecraft"].map(PathBuf::from)); - // The stable Flatpak keeps its own per-app data folder. - roots.push(required_base(env, "HOME")?.join(format!(".var/app/{STABLE_ID}"))); - roots - } - Platform::Mac => { - let home = required_base(env, "HOME")?; - let library = home.join("Library"); - vec![ - library.join("Application Support").join(BRAND), - library.join("Caches").join(BRAND), - library.join("Caches").join(STABLE_ID), - library.join("Preferences").join(BRAND), - library.join("Preferences").join(format!("{STABLE_ID}.plist")), - library.join("Saved Application State").join(format!("{STABLE_ID}.savedState")), - home.join("Applications").join(format!("{BRAND}.app")), - PathBuf::from("/Applications").join(format!("{BRAND}.app")), - ] - } - }; - // The user's own documents folder is Stable's default data folder on every platform; a profile - // there would share autosaves, smart materials and presets with it. - roots.push(default_data_folder(platform, env)?); - roots.push(installation_boundary(platform, exe)?); - roots.into_iter().map(|p| canonical_future(&p)).collect() -} - -/// An entry inside the profile must resolve inside it, so a link planted there cannot point -/// Nightly's writes at another app's files. -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 entry = chosen.join(name); - let metadata = std::fs::symlink_metadata(&entry).map_err(|e| format!("cannot inspect the nightly {label}: {e}"))?; - if !metadata.is_dir() { - return Err(format!("the nightly {label} must be a directory inside its selected profile")); - } - let child = canonical_future(&entry)?; - if child == chosen || !child.starts_with(&chosen) { - return Err(format!("the nightly {label} must stay inside its selected profile")); - } - Ok(child) -} +/// The bundle identifier of the stable package (macOS library folders, the Linux Flatpak). +const STABLE_ID: &str = "ai.storyteller.texturecraft"; +/// The package id of the Nightly Flatpak bundle (`packaging/linux/flatpak-bundle.sh`). +const NIGHTLY_ID: &str = "ai.storyteller.texturecraft.nightly"; /// Known folder-only entries directly inside a Nightly profile. -const PROFILE_FOLDERS: [&str; 10] = ["autosave", "logs", "cache", "library", "layouts", "templates", "brushes", "export", "export-presets", "Samples"]; +const PROFILE_FOLDERS: &[&str] = &["autosave", "logs", "cache", "library", "layouts", "templates", "brushes", "export", "export-presets", "Samples"]; -/// Every existing entry directly in the profile (autosave, logs, library and so on) must resolve -/// inside it. -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(()) +/// Build TextureCraft's `craft_nightly::AppProfileSpec` from the current process environment. +pub fn spec() -> AppProfileSpec { + spec_with_env(|key| std::env::var_os(key)) } -/// 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()); - } +/// Build TextureCraft's `craft_nightly::AppProfileSpec` using a custom environment lookup. +pub fn spec_with_env(env: impl Fn(&str) -> Option) -> AppProfileSpec { + AppProfileSpec { + app_id: APP_ID, + display_name: BRAND, + stable_dir_names: &[BRAND, LINUX_STORAGE_BRAND], + stable_package_id: STABLE_ID, + nightly_package_id: NIGHTLY_ID, + profile_root_env: None, + forbidden_env_vars: &[], + portable_markers: &[], + folder_only_entries: PROFILE_FOLDERS, + extra_forbidden_roots: extra_forbidden_roots(&env), } - #[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(()) } -/// The app's writable probe: create a file exclusively in the profile and remove it again. -pub fn ensure_writable(dir: &Path) -> std::io::Result<()> { - let probe = dir.join("exclusive-write-probe"); - let file = std::fs::OpenOptions::new().write(true).create_new(true).open(&probe)?; - drop(file); - std::fs::remove_file(probe) +fn non_empty_abs_env(env: &impl Fn(&str) -> Option, key: &str) -> Option { + let value = env(key).filter(|v| !v.is_empty())?; + let path = PathBuf::from(value); + path.is_absolute().then_some(path) } -/// Refuse a stable folder, the running install or an alias, create a missing root with owner-only -/// access where the platform has it, and return the resolved root to use. -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) -} +/// Platform-specific stable data and install roots beyond the OS config/data/cache dirs that +/// `craft-nightly` already fences from `stable_dir_names` and `stable_package_id`. +fn extra_forbidden_roots(env: &impl Fn(&str) -> Option) -> Vec { + let mut roots = Vec::new(); -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")?; - // A native package must not carry another app's Flatpak namespace, and the Nightly bundle must - // be able to start inside its own sandbox, where the runtime always sets `FLATPAK_ID`. Its - // `~/.var/app/` sandbox is separate from stable's, so only other ids are refused. - if platform != Platform::Windows - && let Some(id) = env("FLATPAK_ID").filter(|v| !v.is_empty()) - && id != NIGHTLY_ID + // The user's own Documents folder is Stable's default data folder on every platform; a profile + // there would share autosaves, smart materials and presets with it. + #[cfg(target_os = "windows")] + if let Some(home) = non_empty_abs_env(env, "USERPROFILE") { + roots.push(home.join("Documents").join(BRAND)); + } + #[cfg(not(target_os = "windows"))] + if let Some(home) = non_empty_abs_env(env, "HOME") { + roots.push(home.join("Documents").join(BRAND)); + } + + #[cfg(target_os = "windows")] { - return Err("nightly-v1 only runs inside its own Flatpak; launch through the native Launcher or the Nightly bundle".into()); + if let Some(local) = non_empty_abs_env(env, "LOCALAPPDATA") { + roots.push(local.join("Programs").join("ArtCraft").join(BRAND)); + } + for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] { + if let Some(base) = non_empty_abs_env(env, key) { + roots.push(base.join(BRAND)); + } + } } - let chosen = canonical_future(root)?; - let exe = absolute(exe.ok_or("cannot establish the installation boundary")?.to_path_buf(), "the executable")?; - let forbidden = forbidden_roots(platform, &env, &exe)?; - if forbidden.iter().any(|stable| overlaps(&chosen, stable, platform)) { - return Err("the nightly root must not overlap stable data or an installation".into()); - } - // Existing aliases under the profile must not redirect any of its folders elsewhere. - entries_stay_inside(&chosen)?; - let mut create = std::fs::DirBuilder::new(); - create.recursive(true); - #[cfg(unix)] + + #[cfg(target_os = "linux")] { - use std::os::unix::fs::DirBuilderExt as _; - create.mode(0o700); + roots.extend(["/usr/bin/texturecraft", "/usr/local/bin/texturecraft", "/opt/texturecraft"].map(PathBuf::from)); + if let Some(home) = non_empty_abs_env(env, "HOME") { + roots.push(home.join(format!(".var/app/{STABLE_ID}"))); + } } - 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()); + + #[cfg(target_os = "macos")] + { + if let Some(home) = non_empty_abs_env(env, "HOME") { + let library = home.join("Library"); + roots.push(library.join("Preferences").join(format!("{STABLE_ID}.plist"))); + roots.push(library.join("Saved Application State").join(format!("{STABLE_ID}.savedState"))); + roots.push(home.join("Applications").join(format!("{BRAND}.app"))); + } + roots.push(PathBuf::from("/Applications").join(format!("{BRAND}.app"))); } - entries_stay_inside(&confirmed)?; - writable(&confirmed).map_err(|e| format!("the nightly profile is not writable: {e}"))?; - Ok(confirmed) + + roots } #[cfg(test)] mod tests { 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, + struct TempDir { + path: PathBuf, } - impl Fixture { - fn new() -> Self { + impl TempDir { + fn new(label: &str) -> Self { static NEXT: AtomicU64 = AtomicU64::new(0); - let root = loop { - let candidate = - std::env::temp_dir().join(format!("texturecraft-profile-policy-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed))); + let base = std::fs::canonicalize(std::env::temp_dir()).unwrap_or_else(|_| std::env::temp_dir()); + let path = loop { + let candidate = base.join(format!("texturecraft-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(), + Ok(()) => break candidate, Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue, Err(error) => panic!("cannot create owned fixture: {error}"), } }; - let home = root.join("home"); - let exe = root.join("install/texturecraft"); - 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.clone()), ("USERPROFILE", 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 { path } } - 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), ensure_writable) - } - - fn home(&self) -> PathBuf { - PathBuf::from(self.get("HOME").unwrap()) - } - - fn profile(&self, name: &str) -> PathBuf { - self.root.join("profiles").join(name) + fn path(&self) -> &Path { + &self.path } } - impl Drop for Fixture { + impl Drop for TempDir { fn drop(&mut self) { - // Only the directory this fixture created is owned for removal. - std::fs::remove_dir_all(&self.root).unwrap(); + let _ = std::fs::remove_dir_all(&self.path); } } #[test] - fn a_fresh_private_profile_is_created_and_returned_resolved() { - let fixture = Fixture::new(); - let profile = fixture.profile("nightly"); - for platform in [Platform::Windows, Platform::Linux, Platform::Mac] { - assert_eq!(fixture.check(platform, &profile).unwrap(), profile); - assert!(profile.is_dir()); - std::fs::remove_dir_all(&profile).ok(); + fn spec_declares_texturecraft_ids_folders_and_extra_forbidden_roots() { + let tmp = TempDir::new("spec"); + let home = tmp.path().join("home"); + let mut env = BTreeMap::new(); + env.insert("HOME", home.clone().into_os_string()); + env.insert("USERPROFILE", home.clone().into_os_string()); + env.insert("LOCALAPPDATA", tmp.path().join("local").into_os_string()); + env.insert("ProgramFiles", tmp.path().join("Program Files").into_os_string()); + + let spec = spec_with_env(|key| env.get(key).cloned()); + assert_eq!(spec.app_id, "texturecraft"); + assert_eq!(spec.display_name, "TextureCraft"); + assert_eq!(spec.stable_dir_names, &["TextureCraft", "texturecraft"]); + assert_eq!(spec.stable_package_id, "ai.storyteller.texturecraft"); + assert_eq!(spec.nightly_package_id, "ai.storyteller.texturecraft.nightly"); + assert_eq!(spec.profile_root_env, None); + assert!(spec.forbidden_env_vars.is_empty()); + assert!(spec.portable_markers.is_empty()); + assert_eq!(spec.folder_only_entries, PROFILE_FOLDERS); + assert!(spec.extra_forbidden_roots.contains(&home.join("Documents").join(BRAND))); + + #[cfg(target_os = "linux")] + { + assert!(spec.extra_forbidden_roots.contains(&PathBuf::from("/usr/bin/texturecraft"))); + assert!(spec.extra_forbidden_roots.contains(&PathBuf::from("/opt/texturecraft"))); + assert!(spec.extra_forbidden_roots.contains(&home.join(format!(".var/app/{STABLE_ID}")))); + } + #[cfg(target_os = "macos")] + { + assert!(spec.extra_forbidden_roots.contains(&home.join(format!("Library/Preferences/{STABLE_ID}.plist")))); + assert!(spec.extra_forbidden_roots.contains(&home.join(format!("Library/Saved Application State/{STABLE_ID}.savedState")))); + assert!(spec.extra_forbidden_roots.contains(&home.join(format!("Applications/{BRAND}.app")))); + assert!(spec.extra_forbidden_roots.contains(&PathBuf::from(format!("/Applications/{BRAND}.app")))); + } + #[cfg(target_os = "windows")] + { + assert!(spec.extra_forbidden_roots.contains(&tmp.path().join("local/Programs/ArtCraft").join(BRAND))); + assert!(spec.extra_forbidden_roots.contains(&tmp.path().join("Program Files").join(BRAND))); } } #[test] - fn every_stable_data_folder_of_each_platform_is_refused_before_any_probe() { - let fixture = Fixture::new(); - let home = fixture.home(); - let candidates: Vec<(Platform, PathBuf)> = vec![ - (Platform::Windows, PathBuf::from(fixture.get("APPDATA").unwrap()).join(BRAND)), - (Platform::Windows, PathBuf::from(fixture.get("LOCALAPPDATA").unwrap()).join(BRAND)), - (Platform::Windows, PathBuf::from(fixture.get("LOCALAPPDATA").unwrap()).join("Programs/ArtCraft").join(BRAND)), - (Platform::Windows, home.join("Documents").join(BRAND)), - (Platform::Linux, home.join(".config").join(BRAND)), - (Platform::Linux, home.join(".local/share").join(BRAND)), - (Platform::Linux, home.join(".local/share").join(LINUX_STORAGE_BRAND)), - (Platform::Linux, home.join(".cache").join(BRAND)), - (Platform::Linux, home.join(".local/state").join(BRAND)), - (Platform::Linux, home.join("Documents").join(BRAND)), - (Platform::Linux, PathBuf::from("/usr/bin/texturecraft")), - (Platform::Linux, PathBuf::from("/opt/texturecraft")), - (Platform::Linux, home.join(format!(".var/app/{STABLE_ID}"))), - (Platform::Mac, home.join("Library/Application Support").join(BRAND)), - (Platform::Mac, home.join("Library/Caches").join(BRAND)), - (Platform::Mac, home.join("Library/Preferences").join(format!("{STABLE_ID}.plist"))), - (Platform::Mac, home.join("Library/Saved Application State").join(format!("{STABLE_ID}.savedState"))), - (Platform::Mac, home.join("Documents").join(BRAND)), - (Platform::Mac, PathBuf::from(format!("/Applications/{BRAND}.app"))), - ]; - for (platform, stable) in candidates { - for candidate in [stable.clone(), stable.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(), "{platform:?} accepted {}", candidate.display()); - assert!(!probed.get(), "a refused root must not be probed: {}", candidate.display()); - } + fn nightly_profile_reopens_and_enforces_folder_only_entries() { + let tmp = TempDir::new("reopen"); + let private = tmp.path().join("nightly-profile"); + let spec = spec_with_env(|_| None); + + let canonical = validate_and_prepare_root(&private, &spec).expect("fresh private profile"); + assert_eq!(canonical, private); + for name in ["app.ron", "ui.json", "errors.log", "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!(validate_and_prepare_root(&private, &spec).expect("reopen populated profile"), 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!(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(); } } #[test] - fn the_running_install_is_fenced_on_every_platform() { - let fixture = Fixture::new(); - for platform in [Platform::Windows, Platform::Linux, Platform::Mac] { - let inside = fixture.exe.parent().unwrap().join("profile"); - assert!(fixture.check(platform, &inside).is_err(), "{platform:?} let the profile inside the install"); - } - } + fn documents_data_folder_is_refused() { + let tmp = TempDir::new("documents"); + let home = tmp.path().join("home"); + let documents_stable = home.join("Documents").join(BRAND); + let spec = spec_with_env(|key| matches!(key, "HOME" | "USERPROFILE").then(|| home.clone().into_os_string())); - #[test] - fn lookalike_names_are_not_overlaps_but_case_folding_is() { - let fixture = Fixture::new(); - let documents = fixture.home().join("Documents"); - assert!(fixture.check(Platform::Linux, &documents.join("TextureCraft2")).is_ok(), "a neighbor with a suffix is a different folder"); - assert!(fixture.check(Platform::Linux, &documents.join("texturecraft")).is_ok(), "Linux folds names exactly"); - for platform in [Platform::Windows, Platform::Mac] { - assert!(fixture.check(platform, &documents.join("texturecraft")).is_err(), "{platform:?} must fold case"); - } - } - - #[test] - fn relative_parent_traversal_and_empty_roots_are_refused() { - let fixture = Fixture::new(); - for root in [PathBuf::from("relative/profile"), PathBuf::from("/nightly/../stable"), PathBuf::from("")] { - assert!(fixture.check(Platform::Linux, &root).is_err(), "{}", root.display()); - } - } - - #[test] - fn only_the_nightly_flatpak_may_start_with_its_own_id() { - let fixture = Fixture::new(); - let profile = fixture.profile("flatpak"); - assert!(fixture.check(Platform::Linux, &profile).is_ok()); - std::fs::remove_dir_all(&profile).ok(); - let check_with = |id: &str, candidate: &Path| { - let id = OsString::from(id); - validate_for( - Platform::Linux, - candidate, - |key| if key == "FLATPAK_ID" { Some(id.clone()) } else { fixture.get(key) }, - Some(&fixture.exe), - ensure_writable, - ) - }; - // Stable's id, its window id and an unrelated app's id are all refusals. - for id in [STABLE_ID, "ai.storyteller.texturecraft.nightly-v1", "org.example.other"] { - assert!(check_with(id, &profile).is_err(), "{id} was accepted"); - } - // The Nightly bundle's own id is the sandbox the Nightly package runs in: accepted, with the - // profile its wrapper names inside it (`${XDG_DATA_HOME}/TextureCraft-Nightly`). - let sandbox = fixture.home().join(format!(".var/app/{NIGHTLY_ID}")); - let sandboxed = sandbox.join(".local/share/TextureCraft-Nightly"); - assert_eq!(check_with(NIGHTLY_ID, &sandboxed).expect("the Nightly Flatpak may start"), sandboxed); - std::fs::remove_dir_all(&sandbox).ok(); - } - - #[test] - #[cfg(unix)] - fn an_entry_that_leaves_the_profile_is_refused() { - let fixture = Fixture::new(); - let profile = fixture.profile("aliased"); - let outside = fixture.root.join("somewhere else"); - std::fs::create_dir_all(&profile).unwrap(); - std::fs::create_dir_all(&outside).unwrap(); - std::os::unix::fs::symlink(&outside, profile.join("autosave")).unwrap(); - assert!(fixture.check(Platform::Linux, &profile).is_err(), "a link out of the profile must be refused"); - // A dangling link is not a missing folder that may be created. - std::fs::remove_file(profile.join("autosave")).unwrap(); - std::os::unix::fs::symlink(profile.join("missing"), profile.join("logs")).unwrap(); - assert!(fixture.check(Platform::Linux, &profile).is_err()); - std::fs::remove_file(profile.join("logs")).unwrap(); - // A plain folder inside it is fine. - std::fs::create_dir(profile.join("autosave")).unwrap(); - assert!(fixture.check(Platform::Linux, &profile).is_ok()); - } - - #[test] - fn a_failed_write_probe_never_falls_back_to_stable() { - let fixture = Fixture::new(); - let profile = fixture.profile("read only"); - let reached = std::cell::Cell::new(false); - let result = validate_for( - Platform::Linux, - &profile, - |key| fixture.get(key), - Some(&fixture.exe), - |_| { - reached.set(true); - Err(std::io::Error::other("read-only filesystem")) - }, - ); - assert!(result.is_err()); - assert!(reached.get()); - assert!(result.unwrap_err().contains("not writable")); - // The app must not then use the stable folder: it simply refuses to start. - assert!(fixture.check(Platform::Linux, &fixture.home().join("Documents").join(BRAND)).is_err()); - } - - #[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", "ui.json", "errors.log", "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] - #[cfg(unix)] - fn a_profile_whose_existing_ancestor_is_a_link_resolves_before_the_fence() { - let fixture = Fixture::new(); - let real = fixture.root.join("real profiles"); - std::fs::create_dir_all(&real).unwrap(); - let link = fixture.root.join("linked"); - std::os::unix::fs::symlink(&real, &link).unwrap(); - // A link to a private folder is fine, and the resolved root is what the app uses. - let resolved = fixture.check(Platform::Linux, &link.join("nightly")).unwrap(); - assert_eq!(resolved, real.join("nightly")); + assert!(matches!(validate_and_prepare_root(&documents_stable, &spec), Err(ProfileError::ForbiddenRootOverlap { .. }))); + assert!(matches!(validate_and_prepare_root(&documents_stable.join("nested"), &spec), Err(ProfileError::ForbiddenRootOverlap { .. }))); } }