From dce2f8906226e57584dfff0aeb42245b6ab475ff Mon Sep 17 00:00:00 2001 From: skylartaylor Date: Sun, 22 Nov 2026 17:09:59 +0100 Subject: [PATCH] Keep Nightly profiles isolated and startup resilient --- apps/photocraft/src/launch_args.rs | 38 +++++++++ apps/photocraft/src/launch_profile.rs | 37 +++++++++ apps/photocraft/src/main.rs | 10 +-- apps/photocraft/src/nightly_session.rs | 25 ++++++ apps/photocraft/src/profile_root.rs | 111 ++++++++++++++++++++++++- 5 files changed, 212 insertions(+), 9 deletions(-) diff --git a/apps/photocraft/src/launch_args.rs b/apps/photocraft/src/launch_args.rs index 83715f8918..e54f423d9c 100644 --- a/apps/photocraft/src/launch_args.rs +++ b/apps/photocraft/src/launch_args.rs @@ -152,6 +152,13 @@ pub(crate) fn command() -> Command { .mut_args(blank_env_is_unset) } +/// Nightly has no control server. Its unused inherited port must not prevent a window from +/// opening; Stable retains its existing environment/usage-error behavior. +pub(crate) fn command_for_profile(nightly: bool) -> Command { + let command = command(); + if nightly { command.mut_arg("control", |arg| arg.env(None::<&str>)) } else { command } +} + /// Parse the launch arguments (without the binary name) with `cmd`, from [`command`]. Old macOS /// passes a process serial number (`-psn_…`) when launched from Finder: it is dropped first, unless /// it comes after `--`. A bad value from a variable is a usage error naming the variable. @@ -216,6 +223,37 @@ mod tests { e.to_string() } + #[test] + fn nightly_ignores_only_the_unused_control_port_environment() { + const CHILD: &str = "PHOTOCRAFT_TEST_CONTROL_PORT_CHILD"; + if let Ok(profile) = std::env::var(CHILD) { + let nightly = profile == "nightly"; + let result = parse(command_for_profile(nightly), Vec::::new()); + if nightly { + assert!(result.is_ok(), "unused invalid control-port environment must not block Nightly"); + assert!(result.unwrap().control.is_none()); + assert!(parse(command_for_profile(true), ["--control", "70000"].map(OsString::from)).is_err(), "explicit invalid values remain invalid"); + } else { + assert_eq!(result.err().unwrap().exit_code(), 2, "Stable preserves its invalid-environment error"); + } + return; + } + for profile in ["stable", "nightly"] { + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "launch_args::tests::nightly_ignores_only_the_unused_control_port_environment", "--nocapture"]) + .env(CHILD, profile) + .env("PHOTOCRAFT_CONTROL_PORT", "not-a-port") + .env_remove("PHOTOCRAFT_CONTROL_TOKEN") + .env_remove("PHOTOCRAFT_CONTROL_TOKEN_FILE") + .env_remove("PHOTOCRAFT_AUTOMATION_READ_ROOT") + .env_remove("PHOTOCRAFT_AUTOMATION_WRITE_ROOT") + .env_remove("PHOTOCRAFT_IN_WINDOW_MENUS") + .output() + .unwrap(); + assert!(output.status.success(), "{profile}: {}", String::from_utf8_lossy(&output.stdout)); + } + } + #[test] fn control_port_rejects_unparseable_values_naming_them() { // Out of range, negative and empty values fail, naming the value (#701); a following diff --git a/apps/photocraft/src/launch_profile.rs b/apps/photocraft/src/launch_profile.rs index ca318509db..00b80447e1 100644 --- a/apps/photocraft/src/launch_profile.rs +++ b/apps/photocraft/src/launch_profile.rs @@ -90,6 +90,22 @@ pub fn parse(args: Vec) -> Result { } } +/// The existing renderer retry is signalled by its process-local failure marker. Ordinary +/// Launcher calls still use the strict selector/root protocol; this is not authentication. +pub fn parse_startup(args: Vec, compatibility_retry: bool) -> Result { + if !compatibility_retry || args.first().is_none_or(|arg| arg != "--safe-gpu") { + return parse(args); + } + let mut launch = parse(args[1..].to_vec())?; + if launch.profile.is_nightly() { + launch.args.insert(0, OsString::from("--safe-gpu")); + Ok(launch) + } else { + // Stable's argument order and parser remain unchanged. + parse(args) + } +} + /// 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 { @@ -119,6 +135,27 @@ mod tests { args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--"]) } + #[test] + fn internal_cpu_retry_preserves_the_nightly_root_and_literal_files() { + let mut argv = args(&["--safe-gpu"]); + argv.extend(nightly()); + argv.extend(args(&["document with spaces.psd", "--safe-gpu", "--profile-root"])); + let launch = parse_startup(argv.clone(), true).unwrap(); + assert_eq!(launch.profile, Profile::NightlyV1(PathBuf::from(absolute()))); + assert_eq!(launch.args, args(&["--safe-gpu", "--", "document with spaces.psd", "--safe-gpu", "--profile-root"])); + assert!(parse_startup(argv, false).is_err(), "an ordinary invocation must not gain extra protocol flags"); + } + + #[test] + fn retry_cannot_bypass_invalid_profiles_or_change_stable_arguments() { + let stable = args(&["--safe-gpu", "--new-instance", "stable.psd"]); + assert_eq!(parse_startup(stable.clone(), true).unwrap(), Launch { profile: Profile::Stable, args: stable }); + let mut duplicate = args(&["--safe-gpu", "--safe-gpu"]); + duplicate.extend(nightly()); + assert!(parse_startup(duplicate, true).is_err()); + assert!(parse_startup(args(&["--safe-gpu", "--launch-profile", VERSION, "--profile-root", "relative", "--"]), true).is_err()); + } + #[test] fn stable_arguments_and_directory_policy_are_unchanged() { for argv in [args(&[]), args(&["--new-instance", "a.psd"]), args(&["--", "--launch-profile", "file.psd"])] { diff --git a/apps/photocraft/src/main.rs b/apps/photocraft/src/main.rs index 9382a9e776..783b6e3e2d 100644 --- a/apps/photocraft/src/main.rs +++ b/apps/photocraft/src/main.rs @@ -447,7 +447,7 @@ fn prepare_launch() -> Option> { let _ = writeln!(std::io::stdout(), "PhotoCraft {}", build_flavor::version(build_flavor::COMPILED, env!("PHOTOCRAFT_BUILT_VERSION"))); return None; } - let early = launch_profile::parse(argv) + let early = launch_profile::parse_startup(argv, std::env::var_os("PHOTOCRAFT_GPU_STARTUP_FAILURE").is_some()) .and_then(|launch| { build_flavor::require_profile(build_flavor::COMPILED, &launch.profile)?; initialize_nightly_process_identity().map_err(|error| error.to_string())?; @@ -492,10 +492,10 @@ fn main() -> eframe::Result { // The system font scan can take seconds (minutes on some Macs): run it off the UI thread. photocraft_ui_egui::type_tool::warm_fonts(); // `--help` and `--version` print to standard output and exit 0. A usage error (an unknown - // option, a missing or bad value, a bad PHOTOCRAFT_CONTROL_PORT: issues #701, #6429, #6431) + // option, a missing or bad value, a bad PHOTOCRAFT_CONTROL_PORT for Stable: issues #701, #6429, #6431) // names the argument on standard error and exits 2, so a launcher sees the failure. Neither // panics when the stream is closed or a pipe (`photocraft --help | head -1`). - let launch = launch_args::parse(launch_args::command(), arguments).unwrap_or_else(|e| e.exit()); + let launch = launch_args::parse(launch_args::command_for_profile(launch_profile::current().is_nightly()), arguments).unwrap_or_else(|e| e.exit()); let launch_args::FileNames { openable: files, unreadable: unreadable_paths } = launch.file_names(); let launch_args::LaunchArgs { files: _, @@ -641,12 +641,12 @@ fn main() -> eframe::Result { let started_sentinel = sentinel.clone(); // After primary IPC claim, before entering the window loop. Stable and secondaries do not // own a Nightly record. No document names, paths or diagnostic payload is collected. - let (nightly_session, session_health_warning) = match nightly_session::Session::begin( + let (nightly_session, session_health_warning) = match nightly_session::Session::begin_with_health( launch_profile::current().root(), photocraft_engine::build_info::VERSION, photocraft_engine::build_info::git_sha(), ) { - Ok(watch) => (watch, false), + Ok(state) => state, Err(error) => { log::warn!("Nightly session health is unavailable: {error}"); (None, true) diff --git a/apps/photocraft/src/nightly_session.rs b/apps/photocraft/src/nightly_session.rs index 7079a35ccf..58698cf650 100644 --- a/apps/photocraft/src/nightly_session.rs +++ b/apps/photocraft/src/nightly_session.rs @@ -27,6 +27,14 @@ fn regular_or_missing(path: &Path) -> io::Result { } impl Session { + /// The warning belongs to this window: a busy secondary has no health-record coverage, + /// while Stable and a lease-owning Nightly window preserve their existing result. + pub fn begin_with_health(root: Option<&Path>, version: &str, commit: Option<&str>) -> io::Result<(Option, bool)> { + let watch = Self::begin(root, version, commit)?; + let unavailable = root.is_some() && watch.is_none(); + Ok((watch, unavailable)) + } + /// `None` is stable or another owner of this profile. Neither case touches the record. /// The supplied root must already be the validated private Nightly profile. pub fn begin(root: Option<&Path>, version: &str, commit: Option<&str>) -> io::Result> { @@ -100,6 +108,23 @@ mod tests { } } + #[test] + fn busy_secondary_reports_unavailable_without_replacing_the_owner_record() { + let _no_spawns = crate::no_child_spawns(); + let fixture = Fixture::new(); + let (stable, warning) = Session::begin_with_health(None, "stable", None).unwrap(); + assert!(stable.is_none() && !warning); + let (first, warning) = Session::begin_with_health(Some(&fixture.0), "nightly", Some("owned-commit")).unwrap(); + assert!(!warning); + let first = first.unwrap(); + let record = std::fs::read(fixture.0.join(RECORD)).unwrap(); + let (secondary, warning) = Session::begin_with_health(Some(&fixture.0), "secondary", None).unwrap(); + assert!(secondary.is_none() && warning, "a secondary window cannot claim recorded exit/crash coverage"); + assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), record); + first.complete().unwrap(); + assert!(!fixture.0.join(RECORD).exists()); + } + #[test] fn controlled_completion_is_clean_but_an_unfinished_owner_is_reported_next_time() { let _no_spawns = crate::no_child_spawns(); diff --git a/apps/photocraft/src/profile_root.rs b/apps/photocraft/src/profile_root.rs index 54d89def0e..fb80c9b1ca 100644 --- a/apps/photocraft/src/profile_root.rs +++ b/apps/photocraft/src/profile_root.rs @@ -1,6 +1,8 @@ //! App-owned nightly profile fences; no stable fallback, migration or process environment changes. use std::ffi::OsString; + +use photocraft_automation::app_dirs::{PORTABLE_DATA_DIR, portable_marker}; use std::path::{Component, Path, PathBuf}; #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -127,12 +129,27 @@ fn forbidden_roots(platform: Platform, env: &impl Fn(&str) -> Option, /// never falls back to the stable Documents folder. The SDK creates it lazily if a default is /// actually needed; explicit user-chosen document roots keep their existing semantics. pub fn agent_directory(root: &Path) -> Result { + private_subdirectory(root, "AgentFiles", "default agent folder") +} + +fn private_subdirectory(root: &Path, name: &str, label: &str) -> Result { let chosen = canonical_future(&absolute(root.to_path_buf(), "the nightly profile root")?)?; - let agent = canonical_future(&chosen.join("AgentFiles"))?; - if agent == chosen || !agent.starts_with(&chosen) { - return Err("the nightly default agent folder must stay inside its selected profile".into()); + 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")); } - Ok(agent) + Ok(child) +} + +/// 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 { + portable_marker(path).is_some() + || 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 @@ -165,6 +182,9 @@ fn validate_for( 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 PhotoCraft installation or its PhotoCraftData settings folder".into()); + } let exe = absolute(exe.ok_or("cannot establish the installation boundary")?.to_path_buf(), "the executable")?; let mut forbidden = forbidden_roots(platform, &env, &exe)?; if let Some(agent) = stable_agent { @@ -177,6 +197,9 @@ fn validate_for( } // Existing aliases under the profile must not redirect the default agent workspace elsewhere. agent_directory(&chosen)?; + // Recovery can read, adopt, overwrite and sweep entries. Never let its alias leave this + // private profile, including toward a Stable portable directory not in our known roots. + private_subdirectory(&chosen, "Recovery", "recovery folder")?; let mut create = std::fs::DirBuilder::new(); create.recursive(true); #[cfg(unix)] @@ -190,6 +213,7 @@ fn validate_for( return Err("the nightly profile changed while it was being validated".into()); } agent_directory(&confirmed)?; + private_subdirectory(&confirmed, "Recovery", "recovery folder")?; writable(&confirmed).map_err(|e| format!("the nightly profile is not writable: {e}"))?; Ok(confirmed) } @@ -261,6 +285,85 @@ mod tests { } } + #[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(photocraft_automation::app_dirs::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), + None, + |_| { + 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("PhotoCraftData-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 recovery_aliases_cannot_redirect_to_stable_missing_or_profile_root_data() { + let fixture = Fixture::new(); + let stable = fixture.home().join(".local/state/photocraft/Recovery"); + std::fs::create_dir_all(&stable).unwrap(); + std::fs::write(stable.join("stable-autosave"), b"stable recovery bytes").unwrap(); + for (index, target) in [stable.clone(), fixture.root.join("missing recovery target")].into_iter().enumerate() { + let private = fixture.root.join(format!("nightly-{index}")); + std::fs::create_dir(&private).unwrap(); + std::os::unix::fs::symlink(&target, private.join("Recovery")).unwrap(); + let probed = std::cell::Cell::new(false); + let result = validate_for( + Platform::Linux, + &private, + |key| fixture.get(key), + Some(&fixture.exe), + None, + |_| { + probed.set(true); + Ok(()) + }, + ); + assert!(result.is_err(), "Recovery must not escape the private profile or follow a dangling alias"); + assert!(!probed.get()); + } + let private = fixture.root.join("nightly-self"); + std::fs::create_dir(&private).unwrap(); + std::os::unix::fs::symlink(&private, private.join("Recovery")).unwrap(); + assert!(fixture.check(Platform::Linux, &private).is_err(), "Recovery cannot treat all profile settings as recovery entries"); + assert_eq!(std::fs::read(stable.join("stable-autosave")).unwrap(), b"stable recovery bytes"); + assert_eq!(std::fs::read_dir(stable).unwrap().count(), 1); + } + + #[cfg(unix)] + #[test] + fn recovery_alias_to_a_private_subfolder_keeps_the_profile_usable() { + let fixture = Fixture::new(); + let private = fixture.root.join("nightly-private"); + let recovery = private.join("private-recovery"); + std::fs::create_dir_all(&recovery).unwrap(); + std::os::unix::fs::symlink(&recovery, private.join("Recovery")).unwrap(); + assert!(fixture.check(Platform::Linux, &private).is_ok()); + assert_eq!(std::fs::canonicalize(private.join("Recovery")).unwrap(), recovery); + } + #[test] fn agent_default_is_private_lazy_and_preserves_stable_documents() { let fixture = Fixture::new();