From 40497d7ecaa5ba33536d2b11565e2748f914fc30 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 29 Nov 2026 13:48:49 -0500 Subject: [PATCH] Adopt craft-nightly for self-isolated nightly builds (#1943) --- Cargo.lock | 9 + Cargo.toml | 1 + apps/soundcraft/Cargo.toml | 1 + apps/soundcraft/src/build_flavor.rs | 32 +- apps/soundcraft/src/config.rs | 8 +- apps/soundcraft/src/launch_profile.rs | 397 +++++++++------ apps/soundcraft/src/main.rs | 43 +- apps/soundcraft/src/profile_root.rs | 705 -------------------------- 8 files changed, 264 insertions(+), 932 deletions(-) delete mode 100644 apps/soundcraft/src/profile_root.rs diff --git a/Cargo.lock b/Cargo.lock index c786a28a7..576c59491 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1478,6 +1478,14 @@ dependencies = [ "encoding_rs", ] +[[package]] +name = "craft-nightly" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=1f6c3a21f85ed96f8fd4ddd5a959d4e1edbedb24#1f6c3a21f85ed96f8fd4ddd5a959d4e1edbedb24" +dependencies = [ + "winsafe", +] + [[package]] name = "craft-pdf" version = "0.1.0" @@ -5976,6 +5984,7 @@ dependencies = [ "chrono", "clap", "craft-audio", + "craft-nightly", "craft-update", "eframe", "egui", diff --git a/Cargo.toml b/Cargo.toml index d2422fb88..93b8920ee 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -79,6 +79,7 @@ craft-scraft-format = { version = "0.1.0", git = "https://github.com/storytold/c # craft-update: app-specific pretend versions apply to startup and manual checks. craft-update = { version = "=0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", features = ["ui"] } craft-mcp-server = { version = "=0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" } +craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "1f6c3a21f85ed96f8fd4ddd5a959d4e1edbedb24" } # ui craft-ui = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" } diff --git a/apps/soundcraft/Cargo.toml b/apps/soundcraft/Cargo.toml index 41e972216..909c72c61 100644 --- a/apps/soundcraft/Cargo.toml +++ b/apps/soundcraft/Cargo.toml @@ -17,6 +17,7 @@ asio = ["soundcraft-playback/asio"] [dependencies] soundcraft-engine.workspace = true craft-audio.workspace = true +craft-nightly.workspace = true soundcraft-ui-egui.workspace = true soundcraft-playback.workspace = true soundcraft-automation.workspace = true diff --git a/apps/soundcraft/src/build_flavor.rs b/apps/soundcraft/src/build_flavor.rs index a1d551640..f1a0b02ec 100644 --- a/apps/soundcraft/src/build_flavor.rs +++ b/apps/soundcraft/src/build_flavor.rs @@ -1,23 +1,10 @@ //! Build-time channel is distinct from a launch selector. A runtime environment cannot promote a stable build. -use crate::launch_profile::Profile; + +pub use craft_nightly::BuildFlavor; use std::ffi::OsString; -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum BuildFlavor { - Stable, - NightlyV1, -} - pub const COMPILED: BuildFlavor = if cfg!(soundcraft_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 SoundCraft Nightly from ArtCraft Launcher".into()), - (BuildFlavor::Stable, true) => Err("This is a stable SoundCraft build; nightly-v1 requires the nightly build".into()), - _ => Ok(()), - } -} - pub fn needs_native_error(flavor: BuildFlavor, desktop_session: bool) -> bool { desktop_session && flavor == BuildFlavor::NightlyV1 } @@ -36,6 +23,7 @@ pub fn version(flavor: BuildFlavor, stable: &str) -> String { #[cfg(test)] mod tests { use super::*; + #[test] fn only_a_nightly_desktop_refusal_requests_a_native_dialog() { assert!(needs_native_error(BuildFlavor::NightlyV1, true)); @@ -44,20 +32,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 nightly_version_query_is_unambiguous_and_never_reinterprets_file_arguments() { assert_eq!(version(BuildFlavor::Stable, "0.20.1"), "0.20.1"); diff --git a/apps/soundcraft/src/config.rs b/apps/soundcraft/src/config.rs index 02826979e..25e8d4e7c 100644 --- a/apps/soundcraft/src/config.rs +++ b/apps/soundcraft/src/config.rs @@ -10,12 +10,6 @@ use soundcraft_ui_egui::docking; pub(crate) const PORTABLE_MARKER: &str = "portable.txt"; pub(crate) const PORTABLE_DATA_DIR: &str = "SoundCraftData"; -/// The portable marker in `dir`, if it is a regular file (never a link or a directory). -pub(crate) fn portable_marker(dir: &std::path::Path) -> Option { - let marker = dir.join(PORTABLE_MARKER); - std::fs::symlink_metadata(&marker).ok().filter(|m| m.file_type().is_file()).map(|_| marker) -} - #[derive(Clone, Copy)] enum Platform { Mac, @@ -44,7 +38,7 @@ pub fn resolve_config_dir(get: impl Fn(&str) -> Option) -> Option Option, exe_dir: Option<&Path>, nightly: Option<&Path>) -> Option { - // The compiled Nightly flavor cannot run without a profile (`build_flavor::require_profile`), + // The compiled Nightly flavor always selects an isolated profile (`launch_profile::prepare`), // so this is the complete settings folder and never falls back to Stable data. if let Some(root) = nightly { return Some(root.to_path_buf()); diff --git a/apps/soundcraft/src/launch_profile.rs b/apps/soundcraft/src/launch_profile.rs index 1c302ba8a..57cc4e54a 100644 --- a/apps/soundcraft/src/launch_profile.rs +++ b/apps/soundcraft/src/launch_profile.rs @@ -1,214 +1,275 @@ -//! 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 and profile fencing via `craft-nightly`. +//! +//! Selected before logging, updates, fonts or saved state. Direct launches of a nightly build +//! self-isolate into `craft_nightly::canonical_profile_root("soundcraft")`; launcher launches +//! pass `--launch-profile nightly-v1 --profile-root -- `. Stable builds keep +//! their original arguments and directory policy. use std::ffi::OsString; -use std::path::{Component, Path, PathBuf}; -use std::sync::OnceLock; +use std::path::PathBuf; -pub const VERSION: &str = "nightly-v1"; +use craft_nightly::{AppProfileSpec, Launch, Profile, ProfileError, StartupOptions}; -#[derive(Clone, Debug, PartialEq, Eq)] -pub enum Profile { - Stable, - NightlyV1(PathBuf), -} +use crate::build_flavor; -impl Profile { - pub fn is_nightly(&self) -> bool { - matches!(self, Self::NightlyV1(_)) - } +const APP_ID: &str = "soundcraft"; +const DISPLAY_NAME: &str = "SoundCraft"; +const STABLE_DIR_NAMES: &[&str] = &["soundcraft", "SoundCraft"]; +const STABLE_PACKAGE_ID: &str = "ai.storyteller.soundcraft"; +const NIGHTLY_PACKAGE_ID: &str = "ai.storyteller.soundcraft.nightly"; +const FORBIDDEN_ENV_VARS: &[&str] = &[crate::env::CONFIG_DIR]; +const PORTABLE_MARKERS: &[&str] = &[crate::config::PORTABLE_MARKER]; +const FOLDER_ONLY_ENTRIES: &[&str] = &["Autosave", "Presets", "logs"]; - pub fn root(&self) -> Option<&Path> { - match self { - Self::Stable => None, - Self::NightlyV1(root) => Some(root), - } - } -} - -#[derive(Debug, PartialEq, Eq)] -pub struct Launch { - pub profile: Profile, - pub args: Vec, -} - -static PROFILE: OnceLock = OnceLock::new(); +static STABLE: Profile = Profile::Stable; pub fn current() -> &'static Profile { - PROFILE.get().unwrap_or(&Profile::Stable) + craft_nightly::current().unwrap_or(&STABLE) } -pub fn install(profile: Profile) -> Result<(), String> { - PROFILE.set(profile).map_err(|_| "the launch profile was already selected".into()) +fn non_empty_abs_env(env: &impl Fn(&str) -> Option, key: &str) -> Option { + let value = env(key)?; + if value.is_empty() { + return None; + } + let path = PathBuf::from(value); + path.is_absolute().then_some(path) } -/// 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; +fn extra_forbidden_roots_with(env: impl Fn(&str) -> Option) -> Vec { + let mut roots = Vec::new(); + + #[cfg(target_os = "windows")] + { + // The MSI's default per-user and per-machine folders (install-policy.wxi). + if let Some(local) = non_empty_abs_env(&env, "LOCALAPPDATA") { + roots.push(local.join("Programs").join("ArtCraft").join("SoundCraft")); } - 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()); + if let Some(profile) = non_empty_abs_env(&env, "USERPROFILE") { + roots.push(profile.join("AppData").join("Local").join("Programs").join("ArtCraft").join("SoundCraft")); + } + for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] { + if let Some(base) = non_empty_abs_env(&env, key) { + roots.push(base.join("ArtCraft").join("SoundCraft")); } - 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() }) + + #[cfg(all(unix, not(target_os = "macos")))] + { + roots.extend(["/usr/bin/soundcraft", "/usr/local/bin/soundcraft", "/opt/soundcraft"].map(PathBuf::from)); + // The stable Flatpak keeps its data in its own per-app folder. + if let Some(home) = non_empty_abs_env(&env, "HOME") { + roots.push(home.join(".var/app/ai.storyteller.soundcraft")); } - (Some(_), Some(_)) => Err("unsupported launch profile (expected nightly-v1)".into()), - _ => Err("--launch-profile and --profile-root must be supplied together".into()), + } + + #[cfg(target_os = "macos")] + { + roots.push(PathBuf::from("/Applications/SoundCraft.app")); + if let Some(home) = non_empty_abs_env(&env, "HOME") { + let library = home.join("Library"); + roots.push(library.join("Preferences/ai.storyteller.soundcraft.plist")); + roots.push(library.join("Saved Application State/ai.storyteller.soundcraft.savedState")); + roots.push(home.join("Applications/SoundCraft.app")); + } + } + + #[cfg(not(any(unix, target_os = "windows")))] + let _ = env; + + roots +} + +fn spec_with(env: impl Fn(&str) -> Option) -> AppProfileSpec { + AppProfileSpec { + app_id: APP_ID, + display_name: DISPLAY_NAME, + stable_dir_names: STABLE_DIR_NAMES, + stable_package_id: STABLE_PACKAGE_ID, + nightly_package_id: NIGHTLY_PACKAGE_ID, + profile_root_env: None, + forbidden_env_vars: FORBIDDEN_ENV_VARS, + portable_markers: PORTABLE_MARKERS, + folder_only_entries: FOLDER_ONLY_ENTRIES, + extra_forbidden_roots: extra_forbidden_roots_with(env), } } -/// 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) +pub fn spec() -> AppProfileSpec { + spec_with(|key| std::env::var_os(key)) } -/// Validation finishes before the caller's first startup effect. Stable never calls the nightly -/// root validator, so its old portable/config resolution stays unchanged. -pub fn prepare(mut launch: Launch, validate: impl FnOnce(&Path) -> Result) -> Result { - if let Profile::NightlyV1(root) = &launch.profile { - launch.profile = Profile::NightlyV1(validate(root)?); - } - Ok(launch) -} - -/// Resolve the selected private root before the caller's first startup effect. -pub fn validate_root(root: &Path, env: impl Fn(&str) -> Option, exe: Option<&Path>) -> Result { - // SoundCraft keeps no Documents agent folder and has no craft-settings data/cache roots: one - // settings folder holds ui.json, Autosave/, Presets/ and logs/, and `config::writable` is the - // app's existing exclusive write probe. - crate::profile_root::validate(root, env, exe, crate::config::writable) +pub fn prepare(args: impl IntoIterator) -> Result { + craft_nightly::prepare_launch(build_flavor::COMPILED, &spec(), args, &StartupOptions::new()) } #[cfg(test)] mod tests { use super::*; - use std::cell::Cell; + use craft_nightly::{BuildFlavor, NIGHTLY_V1_CONTRACT, canonical_profile_root, launch_arguments, parse_startup, validate_and_prepare_root}; + use std::path::Path; + use std::sync::atomic::{AtomicU64, Ordering}; + fn args(values: &[&str]) -> Vec { values.iter().map(OsString::from).collect() } + fn absolute() -> &'static str { if cfg!(windows) { r"C:\NightlyData\profiles\soundcraft" } else { "/nightly-data/profiles/soundcraft" } } - fn nightly() -> Vec { - args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--"]) - } - #[test] - fn stable_arguments_and_directory_policy_are_unchanged() { - for argv in [args(&[]), args(&["--new-instance", "a.psd"]), args(&["--", "--launch-profile", "file.psd"])] { - 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 }); - } - } + struct TempDir(PathBuf); - #[test] - fn exact_version_and_root_are_parsed_without_reinterpreting_file_names() { - let mut argv = nightly(); - argv.extend(args(&["--profile-root", "image with spaces.psd"])); - let launch = parse(argv).unwrap(); - assert_eq!(launch.profile, Profile::NightlyV1(PathBuf::from(absolute()))); - assert_eq!(launch.args, args(&["--", "--profile-root", "image with spaces.psd"])); - } - - #[test] - fn missing_duplicate_unknown_and_conflicting_profile_arguments_are_refused() { - for argv in [ - args(&["--launch-profile", VERSION]), - args(&["--profile-root", absolute()]), - args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--"]), - args(&["--launch-profile", VERSION, "--launch-profile", VERSION, "--profile-root", absolute(), "--"]), - args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--profile-root", absolute(), "--"]), - args(&["--launch-profile", VERSION, "--profile-root", "relative", "--"]), - args(&["--launch-profile", VERSION, "--profile-root", "", "--"]), - args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--new-instance", "--"]), - args(&["--launch-profile", VERSION, "--profile-root", absolute()]), - ] { - assert!(parse(argv).is_err()); - } - } - - #[test] - fn the_launcher_version_check_is_a_version_query_only_in_its_exact_form() { - let pair = &["--launch-profile", VERSION, "--profile-root", absolute()]; - let reversed = &["--profile-root", absolute(), "--launch-profile", VERSION]; - for flag in ["--version", "-V"] { - for form in [pair, reversed] { - let mut argv = args(form); - argv.push(flag.into()); - assert!(version_query(&argv), "{argv:?}"); + impl TempDir { + fn new(prefix: &str) -> Self { + static NEXT: AtomicU64 = AtomicU64::new(0); + let base = std::fs::canonicalize(std::env::temp_dir()).unwrap_or_else(|_| std::env::temp_dir()); + loop { + let candidate = base.join(format!("{prefix}-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed))); + match std::fs::create_dir(&candidate) { + Ok(()) => return Self(candidate), + Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue, + Err(error) => panic!("cannot create temp dir: {error}"), + } } } - for argv in [ - args(&["--version"]), - args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--", "--version"]), - args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--"]), - args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--new-instance", "--version"]), - args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--version"]), - args(&["--version", "--launch-profile", VERSION, "--profile-root", absolute()]), - args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--version"]), - args(&["--launch-profile", VERSION, "--profile-root", "relative", "--version"]), - args(&["--launch-profile", VERSION, "--version"]), - args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--help"]), - ] { - assert!(!version_query(&argv), "{argv:?}"); + + fn path(&self) -> &Path { + &self.0 + } + } + + impl Drop for TempDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); } - // Outside the query the strict protocol still refuses the version flag. - assert!(parse(args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version"])).is_err()); } #[test] - fn failed_root_validation_never_reaches_startup_or_falls_back_to_stable() { - let reached = Cell::new(false); - let result = prepare(parse(nightly()).unwrap(), |_| Err("read-only or unsafe profile".into())).map(|_| reached.set(true)); - assert!(result.is_err()); - assert!(!reached.get()); + fn soundcraft_spec_preserves_stable_fences_and_folder_entries() { + let spec = spec(); + assert_eq!(spec.app_id, "soundcraft"); + assert_eq!(spec.display_name, "SoundCraft"); + assert_eq!(spec.stable_dir_names, &["soundcraft", "SoundCraft"]); + assert_eq!(spec.stable_package_id, "ai.storyteller.soundcraft"); + assert_eq!(spec.nightly_package_id, "ai.storyteller.soundcraft.nightly"); + assert_eq!(spec.profile_root_env, None); + assert_eq!(spec.forbidden_env_vars, &["SOUNDCRAFT_CONFIG_DIR"]); + assert_eq!(spec.portable_markers, &["portable.txt"]); + assert_eq!(spec.folder_only_entries, &["Autosave", "Presets", "logs"]); } #[test] - fn successful_root_validation_keeps_the_persistent_root_not_the_binary_tag() { - let checked = PathBuf::from(absolute()).join("checked"); - let launch = prepare(parse(nightly()).unwrap(), |_| Ok(checked.clone())).unwrap(); - assert_eq!(launch.profile.root(), Some(checked.as_path())); - assert!(launch.profile.is_nightly()); + fn direct_nightly_launch_self_isolates_into_canonical_profile_root() { + let spec = spec(); + let expected_root = canonical_profile_root("soundcraft").unwrap(); + let argv = args(&["--demo", "song.scraft"]); + let launch = parse_startup(BuildFlavor::NightlyV1, &spec, argv.clone(), &StartupOptions::new()).unwrap(); + assert_eq!(launch.profile, Profile::NightlyV1(expected_root)); + assert_eq!(launch.passthrough_args, argv); + assert!(launch.leading_flags.is_empty()); + } + + #[test] + fn explicit_launcher_invocation_round_trips_and_preserves_file_arguments() { + let spec = spec(); + let root = PathBuf::from(absolute()); + let user_args = args(&["--profile-root", "session with spaces.scraft"]); + let argv = launch_arguments(&root, &user_args); + let launch = parse_startup(BuildFlavor::NightlyV1, &spec, argv, &StartupOptions::new()).unwrap(); + assert_eq!(launch.profile, Profile::NightlyV1(root)); + assert_eq!(launch.passthrough_args, user_args); + } + + #[test] + fn stable_build_keeps_arguments_and_refuses_nightly_flags() { + let spec = spec(); + for argv in [args(&[]), args(&["--demo", "a.scraft"]), args(&["--", "--launch-profile", "file.scraft"])] { + let launch = parse_startup(BuildFlavor::Stable, &spec, argv.clone(), &StartupOptions::new()).unwrap(); + assert_eq!(launch.profile, Profile::Stable); + assert_eq!(launch.passthrough_args, argv); + } + let nightly = launch_arguments(Path::new(absolute()), &[]); + assert!(matches!(parse_startup(BuildFlavor::Stable, &spec, nightly, &StartupOptions::new()), Err(ProfileError::NightlyFlagsInStableBuild))); + } + + #[test] + fn version_queries_are_recognized_for_plain_and_launcher_invocations() { + let spec = spec(); + for flag in ["--version", "-V"] { + let plain = parse_startup(BuildFlavor::NightlyV1, &spec, args(&[flag]), &StartupOptions::new()).unwrap(); + assert!(plain.is_version_query()); + + let launcher = parse_startup( + BuildFlavor::NightlyV1, + &spec, + args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), flag]), + &StartupOptions::new(), + ) + .unwrap(); + assert!(launcher.is_version_query()); + } + } + + #[test] + fn nightly_profile_reopens_with_saved_state_and_enforces_folder_only_entries() { + let dir = TempDir::new("soundcraft-nightly-reopen"); + let root = dir.path().join("profile"); + let spec = spec(); + + let prepared = validate_and_prepare_root(&root, &spec).unwrap(); + assert_eq!(prepared, root); + + for file in ["ui.json", "nightly-session.lock", "nightly-session.json"] { + std::fs::write(prepared.join(file), b"saved profile data").unwrap(); + } + for folder in FOLDER_ONLY_ENTRIES { + std::fs::create_dir(prepared.join(folder)).unwrap(); + } + assert_eq!(validate_and_prepare_root(&root, &spec).unwrap(), prepared); + + let autosave = prepared.join("Autosave"); + std::fs::remove_dir(&autosave).unwrap(); + std::fs::write(&autosave, b"not a directory").unwrap(); + assert!(matches!(validate_and_prepare_root(&root, &spec), Err(ProfileError::ExpectedDirectoryEntry(_)))); + } + + #[test] + fn extra_forbidden_roots_fence_soundcraft_install_locations() { + let dir = TempDir::new("soundcraft-extra-fence"); + let custom_forbidden = dir.path().join("forbidden-install"); + let mut spec = spec(); + spec.extra_forbidden_roots.push(custom_forbidden.clone()); + assert!(matches!(validate_and_prepare_root(&custom_forbidden.join("nightly"), &spec), Err(ProfileError::ForbiddenRootOverlap { .. }))); + } + + #[test] + fn platform_extra_forbidden_roots_include_expected_paths() { + let home = if cfg!(windows) { r"C:\Users\tester" } else { "/Users/tester" }; + let local = if cfg!(windows) { r"C:\Users\tester\AppData\Local" } else { "/unused" }; + let program_files = if cfg!(windows) { r"C:\Program Files" } else { "/unused" }; + let spec = spec_with(|key| match key { + "HOME" | "USERPROFILE" => Some(OsString::from(home)), + "LOCALAPPDATA" => Some(OsString::from(local)), + "ProgramFiles" => Some(OsString::from(program_files)), + _ => None, + }); + #[cfg(target_os = "windows")] + { + assert!(spec.extra_forbidden_roots.contains(&PathBuf::from(local).join("Programs").join("ArtCraft").join("SoundCraft"))); + assert!(spec.extra_forbidden_roots.contains(&PathBuf::from(program_files).join("ArtCraft").join("SoundCraft"))); + } + #[cfg(all(unix, not(target_os = "macos")))] + { + assert!(spec.extra_forbidden_roots.contains(&PathBuf::from("/opt/soundcraft"))); + assert!(spec.extra_forbidden_roots.contains(&PathBuf::from(home).join(".var/app/ai.storyteller.soundcraft"))); + } + #[cfg(target_os = "macos")] + { + assert!(spec.extra_forbidden_roots.contains(&PathBuf::from("/Applications/SoundCraft.app"))); + assert!(spec.extra_forbidden_roots.contains(&PathBuf::from(home).join("Library/Preferences/ai.storyteller.soundcraft.plist"))); + } + let _ = (home, local, program_files, &spec); } } diff --git a/apps/soundcraft/src/main.rs b/apps/soundcraft/src/main.rs index 1ed738946..a3246abc3 100644 --- a/apps/soundcraft/src/main.rs +++ b/apps/soundcraft/src/main.rs @@ -26,7 +26,6 @@ mod logging; mod native_menu; mod nightly_session; mod process_identity; -mod profile_root; mod switch; use env::Env; @@ -251,36 +250,34 @@ fn report_launch_profile_error(error: &str) { fn prepare_launch() -> Option> { // The trusted Launcher protocol is decided before the logger, updates, fonts or saved state. let argv: Vec<_> = std::env::args_os().skip(1).collect(); - // Plain `--version`, or the Launcher's `--launch-profile nightly-v1 --profile-root - // --version`: answered before root validation, process identity, IPC or any window, as - // `SoundCraft (nightly-v1)` on standard output with nothing on standard error. - if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && (build_flavor::version_query(&argv) || launch_profile::version_query(&argv)) - { + // Plain `--version` / `-V` on Nightly: answered before canonical root resolution, validation, + // process identity, IPC or any window, even in environments without HOME/LOCALAPPDATA. + if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && build_flavor::version_query(&argv) { use std::io::Write as _; let _ = writeln!(std::io::stdout(), "SoundCraft {}", build_flavor::version(build_flavor::COMPILED, env!("SOUNDCRAFT_BUILT_VERSION"))); return None; } - let early = launch_profile::parse(argv) - .and_then(|launch| { - build_flavor::require_profile(build_flavor::COMPILED, &launch.profile)?; - initialize_nightly_process_identity().map_err(|error| error.to_string())?; - Ok(launch) - }) - .and_then(|launch| { - launch_profile::prepare(launch, |root| { - launch_profile::validate_root(root, |key| std::env::var_os(key), std::env::current_exe().ok().as_deref()) - }) - }) - .unwrap_or_else(|error| { - report_launch_profile_error(&error); - std::process::exit(2) - }); + let early = launch_profile::prepare(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::prepare_launch` 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(), "SoundCraft {}", build_flavor::version(build_flavor::COMPILED, env!("SOUNDCRAFT_BUILT_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) = launch_profile::install(early.profile).and_then(|()| os_window::select_identity(identity)) { + if let Err(error) = os_window::select_identity(identity) { report_launch_profile_error(&error); std::process::exit(2); } - Some(early.args) + Some(early.passthrough_args) } fn main() -> eframe::Result { diff --git a/apps/soundcraft/src/profile_root.rs b/apps/soundcraft/src/profile_root.rs deleted file mode 100644 index 8fccb7ee4..000000000 --- a/apps/soundcraft/src/profile_root.rs +++ /dev/null @@ -1,705 +0,0 @@ -//! App-owned nightly profile fences; no stable fallback, migration or process environment changes. - -use std::ffi::OsString; - -use crate::config::{PORTABLE_DATA_DIR, portable_marker}; -use std::path::{Component, Path, PathBuf}; - -/// The Nightly Flatpak's own app id (packaging/linux/flatpak-bundle.sh). Inside that instance the -/// sandbox is the isolation, so it is the one Flatpak whose environment a Nightly launch accepts. -const NIGHTLY_FLATPAK_ID: &str = "ai.storyteller.soundcraft.nightly"; - -#[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 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) -} - -fn overlaps(a: &Path, b: &Path, platform: Platform) -> bool { - let parts = |p: &Path| { - p.components() - .map(|c| { - let value = c.as_os_str().to_string_lossy().into_owned(); - if platform.ignores_case() { value.to_lowercase() } else { value } - }) - .collect::>() - }; - let (a, b) = (parts(a), parts(b)); - a.starts_with(&b) || b.starts_with(&a) -} - -fn installation_boundary(platform: Platform, exe: &Path) -> Result { - let parent = exe.parent().ok_or("cannot establish the installation boundary")?; - if platform == Platform::Mac { - // A profile in Resources is still inside the versioned install, not beside MacOS. - if let Some(bundle) = exe.ancestors().find(|p| p.extension().is_some_and(|ext| ext.eq_ignore_ascii_case("app"))) { - return Ok(bundle.to_path_buf()); - } - } - Ok(parent.to_path_buf()) -} - -fn forbidden_roots(platform: Platform, env: &impl Fn(&str) -> Option, exe: &Path) -> Result, String> { - let mut roots = match platform { - Platform::Windows => { - let mut roots = ["APPDATA", "LOCALAPPDATA"] - .into_iter() - .map(|key| required_base(env, key).map(|p| p.join("SoundCraft"))) - .collect::, _>>()?; - // The MSI's default per-user and per-machine folders (install-policy.wxi). A custom - // install folder is not known here; the executable's own folder is fenced below. - roots.push(required_base(env, "LOCALAPPDATA")?.join("Programs").join("ArtCraft").join("SoundCraft")); - for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] { - if let Some(base) = env(key).filter(|v| !v.is_empty()) { - roots.push(absolute(PathBuf::from(base), key)?.join("ArtCraft").join("SoundCraft")); - } - } - 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("soundcraft"))) - .collect::, _>>()?; - roots.extend(["/usr/bin/soundcraft", "/usr/local/bin/soundcraft", "/opt/soundcraft"].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.soundcraft")); - roots - } - Platform::Mac => { - let home = required_base(env, "HOME")?; - let library = home.join("Library"); - vec![ - library.join("Application Support/SoundCraft"), - library.join("Caches/SoundCraft"), - library.join("Caches/ai.storyteller.soundcraft"), - library.join("Preferences/SoundCraft"), - library.join("Preferences/ai.storyteller.soundcraft.plist"), - library.join("Saved Application State/ai.storyteller.soundcraft.savedState"), - home.join("Applications/SoundCraft.app"), - PathBuf::from("/Applications/SoundCraft.app"), - ] - } - }; - roots.push(installation_boundary(platform, exe)?); - roots.into_iter().map(|p| canonical_future(&p)).collect() -} - -fn private_subdirectory(root: &Path, name: impl AsRef, label: &str) -> Result { - let chosen = canonical_future(&absolute(root.to_path_buf(), "the nightly profile root")?)?; - let child = canonical_future(&chosen.join(name))?; - if child == chosen || !child.starts_with(&chosen) { - return Err(format!("the nightly {label} must stay inside its selected profile")); - } - match std::fs::symlink_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 (Presets, logs, settings and so on) must resolve -/// inside it, so a link there cannot point Nightly's writes at another app's data. -fn entries_stay_inside(root: &Path) -> Result<(), String> { - let entries = match std::fs::read_dir(root) { - Ok(entries) => entries, - Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()), - Err(error) => return Err(format!("cannot inspect the nightly profile: {error}")), - }; - for entry in entries { - let entry = entry.map_err(|e| format!("cannot inspect the nightly profile: {e}"))?; - let path = entry.path(); - let metadata = std::fs::symlink_metadata(&path).map_err(|e| format!("cannot inspect the nightly profile: {e}"))?; - // Settings and session state are ordinary files, not directories. Keep the existing - // directory-boundary check for folders (including the known folder-only entries). - let folder_only = PROFILE_FOLDERS.iter().any(|name| entry.file_name().eq_ignore_ascii_case(name)); - if metadata.is_file() && !folder_only { - private_regular_file(&path, &metadata)?; - } else { - private_subdirectory(root, entry.file_name(), "profile entry")?; - } - } - Ok(()) -} - -/// Persisted files must have their own ordinary file identity, not an alias to other data. -fn private_regular_file(path: &Path, metadata: &std::fs::Metadata) -> Result<(), String> { - #[cfg(unix)] - { - 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. -/// This is not an inventory of arbitrary custom Stable overrides or a Launcher ownership proof. -fn is_portable_layout(path: &Path, platform: Platform) -> bool { - // A folder under a portable copy belongs to that copy too. Above the chosen folder itself, a - // marker only counts beside a SoundCraft executable, so an unrelated portable.txt higher up - // (in a user folder or at a drive root) does not refuse the profile. - path.ancestors().enumerate().any(|(depth, ancestor)| { - portable_marker(ancestor).is_some() && (depth == 0 || ["soundcraft.exe", "soundcraft"].iter().any(|exe| ancestor.join(exe).is_file())) - }) || path.components().any(|component| match component { - Component::Normal(name) if platform.ignores_case() => name.to_string_lossy().eq_ignore_ascii_case(PORTABLE_DATA_DIR), - Component::Normal(name) => name == PORTABLE_DATA_DIR, - _ => false, - }) -} - -/// The writable hook is the app's existing exclusive probe. Keeping it injected lets filesystem -/// boundary tests exercise the real policy without starting the app or changing global state. -pub fn validate( - root: &Path, - env: impl Fn(&str) -> Option, - exe: Option<&Path>, - writable: impl FnOnce(&Path) -> std::io::Result<()>, -) -> Result { - validate_for(Platform::current()?, root, env, exe, writable) -} - -fn validate_for( - platform: Platform, - root: &Path, - env: impl Fn(&str) -> Option, - exe: Option<&Path>, - writable: impl FnOnce(&Path) -> std::io::Result<()>, -) -> Result { - absolute(root.to_path_buf(), "the nightly profile root")?; - if env("SOUNDCRAFT_CONFIG_DIR").is_some_and(|v| !v.is_empty()) { - // The Launcher protocol is the one root the app validates. A wrapper that isolates with - // the stable override variable instead passes the profile explicitly; the message names - // that, because this is what a Linux nightly launcher hits when it exports the variable. - return Err( - "nightly-v1 cannot be combined with SOUNDCRAFT_CONFIG_DIR; pass --launch-profile nightly-v1 --profile-root -- instead".into() - ); - } - // These rows are native tar/app-bundle launches, not a Flatpak package. Inheriting its - // runtime socket namespace could point another profile at the stable app's socket. The - // Nightly Flatpak is the exception: its own app id is the sandbox, so $HOME and the XDG - // folders in there are already this package's own. - if platform != Platform::Windows - && let Some(instance) = env("FLATPAK_ID").filter(|v| !v.is_empty()) - && instance.to_string_lossy() != NIGHTLY_FLATPAK_ID - { - return Err("nightly-v1 native packages cannot inherit a Flatpak instance; launch through the native Launcher".into()); - } - let chosen = canonical_future(root)?; - if is_portable_layout(root, platform) || is_portable_layout(&chosen, platform) { - return Err("the nightly root must not use a portable SoundCraft installation or its SoundCraftData settings folder".into()); - } - let exe = absolute(exe.ok_or("cannot establish the installation boundary")?.to_path_buf(), "the executable")?; - let forbidden = forbidden_roots(platform, &env, &exe)?; - if forbidden.iter().any(|stable| overlaps(&chosen, stable, platform)) { - return Err("the nightly root must not overlap stable data or an installation".into()); - } - entries_stay_inside(&chosen)?; - // Autosave is swept and rewritten on start and Presets are written in place: never let either - // alias leave this private profile, including toward a Stable portable directory we cannot know. - private_subdirectory(&chosen, "Autosave", "autosave folder")?; - private_subdirectory(&chosen, "Presets", "presets folder")?; - let mut create = std::fs::DirBuilder::new(); - create.recursive(true); - #[cfg(unix)] - { - use std::os::unix::fs::DirBuilderExt as _; - create.mode(0o700); - } - create.create(&chosen).map_err(|e| format!("cannot create the nightly profile: {e}"))?; - let confirmed = std::fs::canonicalize(&chosen).map_err(|e| format!("cannot resolve the created nightly profile: {e}"))?; - if confirmed != chosen || forbidden.iter().any(|stable| overlaps(&confirmed, stable, platform)) { - return Err("the nightly profile changed while it was being validated".into()); - } - private_subdirectory(&confirmed, "Autosave", "autosave folder")?; - private_subdirectory(&confirmed, "Presets", "presets folder")?; - entries_stay_inside(&confirmed)?; - writable(&confirmed).map_err(|e| format!("the nightly profile is not writable: {e}"))?; - Ok(confirmed) -} - -const PROFILE_FOLDERS: [&str; 3] = ["Autosave", "Presets", "logs"]; - -#[cfg(test)] -mod tests { - use super::*; - use std::collections::BTreeMap; - use std::sync::atomic::{AtomicU64, Ordering}; - - struct Fixture { - root: PathBuf, - env: BTreeMap, - exe: PathBuf, - } - - impl Fixture { - fn new() -> Self { - static NEXT: AtomicU64 = AtomicU64::new(0); - let root = loop { - let candidate = - std::env::temp_dir().join(format!("soundcraft-profile-policy-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed))); - match std::fs::create_dir(&candidate) { - Ok(()) => break std::fs::canonicalize(candidate).unwrap(), - Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue, - Err(error) => panic!("cannot create owned fixture: {error}"), - } - }; - let home = root.join("home"); - let exe = root.join("install/soundcraft"); - std::fs::create_dir_all(&home).unwrap(); - std::fs::create_dir_all(exe.parent().unwrap()).unwrap(); - std::fs::write(&exe, b"fixture executable, never run").unwrap(); - let env = [("HOME", home), ("APPDATA", root.join("roaming")), ("LOCALAPPDATA", root.join("local"))] - .into_iter() - .map(|(key, value)| (key.into(), value.into_os_string())) - .collect(); - Self { root, env, exe } - } - - fn get(&self, key: &str) -> Option { - self.env.get(key).cloned() - } - - fn check(&self, platform: Platform, root: &Path) -> Result { - validate_for( - platform, - root, - |key| self.get(key), - Some(&self.exe), - |dir| { - let probe = dir.join("exclusive-test-probe"); - let file = std::fs::OpenOptions::new().write(true).create_new(true).open(&probe)?; - drop(file); - std::fs::remove_file(probe) - }, - ) - } - - fn home(&self) -> PathBuf { - PathBuf::from(self.get("HOME").unwrap()) - } - } - - 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(); - } - } - - #[test] - fn portable_settings_from_another_install_are_refused_before_any_probe() { - let fixture = Fixture::new(); - let stable_install = fixture.root.join("stable portable install"); - let stable_data = stable_install.join(PORTABLE_DATA_DIR); - std::fs::create_dir_all(&stable_data).unwrap(); - std::fs::write(stable_install.join("portable.txt"), b"owned portable fixture").unwrap(); - std::fs::write(stable_data.join("settings.json"), b"stable settings must not change").unwrap(); - for platform in [Platform::Windows, Platform::Linux, Platform::Mac] { - for candidate in [&stable_data, &stable_data.join("nested nightly")] { - let probed = std::cell::Cell::new(false); - let result = validate_for( - platform, - candidate, - |key| fixture.get(key), - Some(&fixture.exe), - |_| { - probed.set(true); - Ok(()) - }, - ); - assert!(result.is_err(), "a different portable install is not a private Nightly profile"); - assert!(!probed.get(), "reject portable data before a writable probe"); - assert!(!stable_data.join("nested nightly").exists()); - assert_eq!(std::fs::read(stable_data.join("settings.json")).unwrap(), b"stable settings must not change"); - assert_eq!(std::fs::read_dir(&stable_data).unwrap().count(), 1); - } - } - let private = fixture.root.join("SoundCraftData-backup-name/nightly"); - assert!(fixture.check(Platform::Linux, &private).is_ok(), "a merely similar name is not a portable settings component"); - } - - #[cfg(unix)] - #[test] - fn autosave_aliases_cannot_redirect_to_stable_missing_or_profile_root_data() { - let fixture = Fixture::new(); - let stable = fixture.home().join(".local/state/soundcraft"); - 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("Autosave")).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(), "Autosave 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("Autosave")).unwrap(); - assert!(fixture.check(Platform::Linux, &private).is_err(), "Autosave cannot treat all profile settings as autosaves"); - 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 autosave_alias_to_a_private_subfolder_keeps_the_profile_usable() { - let fixture = Fixture::new(); - let private = fixture.root.join("nightly-private"); - let autosave = private.join("private-recovery"); - std::fs::create_dir_all(&autosave).unwrap(); - std::os::unix::fs::symlink(&autosave, private.join("Autosave")).unwrap(); - assert!(fixture.check(Platform::Linux, &private).is_ok()); - assert_eq!(std::fs::canonicalize(private.join("Autosave")).unwrap(), autosave); - } - - #[test] - fn overlap_check_handles_ancestor_descendant_and_prefix_lookalikes() { - let fixture = Fixture::new(); - let root = fixture.home().join("nightly/profiles/soundcraft"); - for platform in [Platform::Windows, Platform::Linux, Platform::Mac] { - assert!(overlaps(&root, &root.join("Autosave"), platform)); - assert!(overlaps(&root.join("Autosave"), &root, platform)); - assert!(!overlaps(&root, &root.with_file_name("soundcraft-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("soundcraft"); - 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/soundcraft"); - assert_eq!(fixture.check(Platform::Linux, &nightly).unwrap(), nightly); - assert_eq!(std::fs::read_dir(nightly).unwrap().count(), 0); - } - - #[test] - fn nightly_profile_reopens_after_saving_settings_and_session_state() { - let fixture = Fixture::new(); - for platform in [Platform::Mac, Platform::Linux, Platform::Windows] { - let private = fixture.root.join(format!("nightly-reopen-{platform:?}")); - assert_eq!(fixture.check(platform, &private).unwrap(), private); - for name in ["ui.json", "nightly-session.lock", "nightly-session.json"] { - std::fs::write(private.join(name), b"saved profile data").unwrap(); - } - for name in PROFILE_FOLDERS { - std::fs::create_dir(private.join(name)).unwrap(); - } - assert_eq!(fixture.check(platform, &private).unwrap(), private); - assert_eq!(std::fs::read(private.join("ui.json")).unwrap(), b"saved profile data"); - for name in PROFILE_FOLDERS { - let path = private.join(name); - std::fs::remove_dir(&path).unwrap(); - std::fs::write(&path, b"not a directory").unwrap(); - assert!(fixture.check(platform, &private).is_err(), "{name} must stay a directory"); - std::fs::remove_file(&path).unwrap(); - std::fs::create_dir(&path).unwrap(); - } - } - } - - #[test] - fn mac_fences_only_app_library_subtrees_and_the_entire_bundle() { - let mut fixture = Fixture::new(); - fixture.exe = fixture.root.join("install/SoundCraft Nightly.app/Contents/MacOS/SoundCraft"); - 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/SoundCraft", - "Caches/SoundCraft", - "Caches/ai.storyteller.soundcraft", - "Preferences/SoundCraft", - "Saved Application State/ai.storyteller.soundcraft.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/soundcraft"); - 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("SoundCraft"); - 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/soundcraft")).is_ok()); - } - - #[test] - fn windows_default_msi_install_folders_are_fenced() { - let mut fixture = Fixture::new(); - let local = PathBuf::from(fixture.get("LOCALAPPDATA").unwrap()); - let per_user = local.join("Programs").join("ArtCraft").join("SoundCraft"); - assert!(fixture.check(Platform::Windows, &per_user.join("nightly")).unwrap_err().contains("overlap")); - for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] { - let base = fixture.root.join(format!("machine {key}")); - fixture.env.insert(key.into(), base.clone().into_os_string()); - let machine = base.join("ArtCraft").join("SoundCraft"); - assert!(fixture.check(Platform::Windows, &machine.join("nightly")).unwrap_err().contains("overlap")); - assert!(!machine.exists()); - } - let sibling = local.join("Programs").join("ArtCraft").join("ArtCraftLauncher").join("nightly").join("soundcraft"); - assert!(fixture.check(Platform::Windows, &sibling).is_ok(), "the Launcher's own Programs sibling is not SoundCraft'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/PC"); - std::fs::create_dir_all(&portable).unwrap(); - std::fs::write(portable.join("portable.txt"), b"stable portable copy").unwrap(); - std::fs::write(portable.join("soundcraft.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 SoundCraft executable sits beside is someone else's file. - let unrelated = fixture.root.join("user folder"); - std::fs::create_dir_all(&unrelated).unwrap(); - std::fs::write(unrelated.join("portable.txt"), b"another app's marker").unwrap(); - assert!(fixture.check(Platform::Windows, &unrelated.join("Launcher/nightly/soundcraft")).is_ok()); - } - - #[test] - fn linux_fences_the_stable_flatpak_data_folder() { - let fixture = Fixture::new(); - let flatpak = fixture.home().join(".var/app/ai.storyteller.soundcraft"); - for candidate in [flatpak.clone(), flatpak.join("data/nightly")] { - assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("overlap")); - } - assert!(!flatpak.exists()); - assert!(fixture.check(Platform::Linux, &fixture.home().join(".var/app/ai.storyteller.launcher/nightly")).is_ok()); - } - - #[cfg(unix)] - #[test] - fn any_profile_entry_alias_must_stay_inside_the_profile() { - let fixture = Fixture::new(); - let stable = fixture.home().join(".config/soundcraft/Presets"); - std::fs::create_dir_all(&stable).unwrap(); - std::fs::write(stable.join("stable-preset"), b"stable preset bytes").unwrap(); - for name in ["Presets", "logs", "settings.json"] { - let private = fixture.root.join(format!("nightly-{name}")); - std::fs::create_dir(&private).unwrap(); - std::os::unix::fs::symlink(&stable, private.join(name)).unwrap(); - let probed = std::cell::Cell::new(false); - let result = validate_for( - Platform::Linux, - &private, - |key| fixture.get(key), - Some(&fixture.exe), - |_| { - probed.set(true); - Ok(()) - }, - ); - assert!(result.is_err(), "{name} must not lead outside the profile"); - assert!(!probed.get()); - } - let private = fixture.root.join("nightly-inside"); - std::fs::create_dir_all(private.join("real-presets")).unwrap(); - std::fs::write(private.join("settings.json"), b"{}").unwrap(); - std::os::unix::fs::symlink(private.join("real-presets"), private.join("Presets")).unwrap(); - assert!(fixture.check(Platform::Linux, &private).is_ok(), "regular files and links that stay inside are fine"); - assert_eq!(std::fs::read(stable.join("stable-preset")).unwrap(), b"stable preset bytes"); - assert_eq!(std::fs::read_dir(&stable).unwrap().count(), 1); - } - - #[test] - fn ambiguous_environment_and_non_native_sandbox_are_refused_before_creation() { - let mut fixture = Fixture::new(); - let candidate = fixture.home().join("nightly/profiles/soundcraft"); - 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("SOUNDCRAFT_CONFIG_DIR".into(), fixture.home().join("custom-stable").into_os_string()); - assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("SOUNDCRAFT_CONFIG_DIR")); - fixture.env.remove("SOUNDCRAFT_CONFIG_DIR"); - fixture.env.insert("FLATPAK_ID".into(), "ai.storyteller.soundcraft".into()); - assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("Flatpak")); - // The Nightly Flatpak is its own instance: the profile inside it is a sandbox-local folder. - fixture.env.insert("FLATPAK_ID".into(), "ai.storyteller.soundcraft.nightly".into()); - let sandboxed = fixture.home().join(".var/app/ai.storyteller.soundcraft.nightly/config/soundcraft-nightly"); - assert_eq!(fixture.check(Platform::Linux, &sandboxed).unwrap(), sandboxed); - fixture.env.remove("FLATPAK_ID"); - fixture.env.remove("HOME"); - assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("HOME")); - assert!(!candidate.exists()); - } - - #[test] - fn non_directory_and_failed_write_probe_never_fall_back_to_stable() { - let fixture = Fixture::new(); - let file = fixture.home().join("not-a-directory"); - std::fs::write(&file, b"do not replace me").unwrap(); - assert!(fixture.check(Platform::Linux, &file).is_err()); - assert_eq!(std::fs::read(file).unwrap(), b"do not replace me"); - let candidate = fixture.home().join("nightly"); - let calls = std::cell::Cell::new(0); - let result = validate_for( - Platform::Linux, - &candidate, - |key| fixture.get(key), - Some(&fixture.exe), - |_| { - calls.set(calls.get() + 1); - Err(std::io::Error::new(std::io::ErrorKind::PermissionDenied, "injected write refusal")) - }, - ); - assert!(result.unwrap_err().contains("not writable")); - assert_eq!(calls.get(), 1); - assert!(!fixture.home().join(".config/soundcraft").exists()); - } - - #[cfg(unix)] - #[test] - fn symlink_and_dangling_aliases_cannot_create_or_modify_stable_data() { - use std::os::unix::fs::symlink; - let fixture = Fixture::new(); - let stable = fixture.home().join(".config/soundcraft"); - 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"); - } -}