mirror of
https://github.com/storytold/filmcraft.git
synced 2026-12-02 14:01:16 -05:00
feat(nightly): wire craft-nightly for self-isolating direct nightly launches (#5382)
* feat(nightly): wire craft-nightly for self-isolating direct nightly launches * refactor(nightly): extract reject_nightly_cli_overrides helper for clippy cognitive_complexity * fix(nightly): answer bare version queries before profile resolution * test(nightly): add unit tests for nightly CLI overrides, launch_arguments, and env filtering
This commit is contained in:
Generated
+9
@@ -1560,6 +1560,14 @@ dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[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"
|
||||
@@ -2851,6 +2859,7 @@ dependencies = [
|
||||
"chrono",
|
||||
"cpal",
|
||||
"craft-control-protocol",
|
||||
"craft-nightly",
|
||||
"craft-update",
|
||||
"eframe",
|
||||
"egui",
|
||||
|
||||
@@ -68,6 +68,7 @@ craft-jsonrpc = { version = "0.1.0", git = "https://github.com/storytold/craft-l
|
||||
craft-fcproj-format = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "33fb95c7189686cab2fc0a6dbc1882ce7237e2c2" }
|
||||
craft-font-catalog = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a4db799563c9ccd7217e1731ec34c58f6ba57248", default-features = false }
|
||||
craft-control-protocol = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a4db799563c9ccd7217e1731ec34c58f6ba57248" }
|
||||
craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "1f6c3a21f85ed96f8fd4ddd5a959d4e1edbedb24" }
|
||||
craft-y4m = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a4db799563c9ccd7217e1731ec34c58f6ba57248" }
|
||||
# Shared lossless JPEG decoding for DNG.
|
||||
craft-raw = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a4db799563c9ccd7217e1731ec34c58f6ba57248", default-features = false }
|
||||
|
||||
@@ -19,6 +19,7 @@ neural-voices = ["filmcraft-engine/neural-voices"]
|
||||
|
||||
[dependencies]
|
||||
craft-control-protocol = { workspace = true }
|
||||
craft-nightly = { workspace = true }
|
||||
filmcraft-engine = { workspace = true }
|
||||
filmcraft-export = { workspace = true }
|
||||
# The durable no-follow session record (nightly_session.rs).
|
||||
|
||||
@@ -1,31 +1,13 @@
|
||||
//! Build-time channel is distinct from a launch selector. A runtime environment cannot promote a stable build.
|
||||
use crate::launch_profile::Profile;
|
||||
use std::ffi::OsString;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum BuildFlavor {
|
||||
Stable,
|
||||
NightlyV1,
|
||||
}
|
||||
pub use craft_nightly::BuildFlavor;
|
||||
|
||||
pub const COMPILED: BuildFlavor = if cfg!(filmcraft_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 FilmCraft Nightly from ArtCraft Launcher".into()),
|
||||
(BuildFlavor::Stable, true) => Err("This is a stable FilmCraft build; nightly-v1 requires the nightly build".into()),
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn needs_native_error(flavor: BuildFlavor, desktop_session: bool) -> bool {
|
||||
desktop_session && flavor == BuildFlavor::NightlyV1
|
||||
}
|
||||
|
||||
pub fn version_query(args: &[OsString]) -> bool {
|
||||
matches!(args, [arg] if arg == "--version" || arg == "-V")
|
||||
}
|
||||
|
||||
pub fn version(flavor: BuildFlavor, stable: &str) -> String {
|
||||
match flavor {
|
||||
BuildFlavor::Stable => stable.to_owned(),
|
||||
@@ -35,7 +17,8 @@ pub fn version(flavor: BuildFlavor, stable: &str) -> String {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use super::{BuildFlavor, needs_native_error, version};
|
||||
|
||||
#[test]
|
||||
fn only_a_nightly_desktop_refusal_requests_a_native_dialog() {
|
||||
assert!(needs_native_error(BuildFlavor::NightlyV1, true));
|
||||
@@ -45,26 +28,8 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nightly_build_without_a_profile_is_refused_before_startup() {
|
||||
let started = std::cell::Cell::new(false);
|
||||
let result = require_profile(BuildFlavor::NightlyV1, &Profile::Stable).map(|()| started.set(true));
|
||||
assert!(result.unwrap_err().contains("ArtCraft Launcher"));
|
||||
assert!(!started.get());
|
||||
}
|
||||
#[test]
|
||||
fn stable_and_nightly_flavors_accept_only_their_own_profile() {
|
||||
let nightly = Profile::NightlyV1(std::path::PathBuf::from("already validated root"));
|
||||
assert!(require_profile(BuildFlavor::Stable, &Profile::Stable).is_ok());
|
||||
assert!(require_profile(BuildFlavor::Stable, &nightly).is_err());
|
||||
assert!(require_profile(BuildFlavor::NightlyV1, &nightly).is_ok());
|
||||
}
|
||||
#[test]
|
||||
fn nightly_version_query_is_unambiguous_and_never_reinterprets_file_arguments() {
|
||||
fn nightly_version_format_is_unambiguous() {
|
||||
assert_eq!(version(BuildFlavor::Stable, "0.21.1"), "0.21.1");
|
||||
assert_eq!(version(BuildFlavor::NightlyV1, "0.21.1"), "0.21.1 (nightly-v1)");
|
||||
assert!(version_query(&["--version".into()]));
|
||||
assert!(version_query(&["-V".into()]));
|
||||
assert!(!version_query(&["--".into(), "--version".into()]));
|
||||
assert!(!version_query(&[]));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -426,11 +426,10 @@ pub fn choose(start: &mut GraphicsStart, forced: bool, explicit_backend: bool, l
|
||||
choose_with(start, forced, log_file, &exe, &display_drivers(), |exe, mode| {
|
||||
let mut cmd = Command::new(exe);
|
||||
cmd.arg(CHILD_ARG).arg(mode.name());
|
||||
// A Nightly start hands its private profile to the test child: the child refuses to run
|
||||
// without one (it is the same program with the same protocol), and its graphics record
|
||||
// must not land in stable's data folder.
|
||||
// A Nightly start hands its private profile to the test child so its graphics record
|
||||
// stays in the same isolated profile and never lands in stable's data folder.
|
||||
if let Some(root) = crate::launch_profile::current().root() {
|
||||
cmd.args(["--launch-profile", crate::launch_profile::VERSION, "--profile-root"]).arg(root).arg("--");
|
||||
cmd.args(crate::launch_profile::launch_arguments(root, &[]));
|
||||
}
|
||||
run_test(cmd, TIMEOUT)
|
||||
})
|
||||
|
||||
@@ -1,281 +1,131 @@
|
||||
//! Launcher-owned nightly-v1 bootstrap. Selected before logging, updates, fonts or saved state.
|
||||
//! Stable launches retain their original arguments and directory policy. No environment mutation.
|
||||
//! Nightly-v1 bootstrap powered by `craft-nightly`. Selected before logging, updates, fonts or
|
||||
//! saved state. Direct nightly launches self-isolate into `craft_nightly::canonical_profile_root`
|
||||
//! while preserving user arguments; stable launches retain their original arguments and directory
|
||||
//! policy.
|
||||
|
||||
use std::ffi::OsString;
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
use std::sync::OnceLock;
|
||||
use std::path::Path;
|
||||
|
||||
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<OsString>,
|
||||
}
|
||||
|
||||
static PROFILE: OnceLock<Profile> = 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())
|
||||
pub fn prepare_launch(flavor: BuildFlavor, args: impl IntoIterator<Item = OsString>) -> Result<Launch, ProfileError> {
|
||||
let spec = crate::profile_root::app_profile_spec();
|
||||
craft_nightly::prepare_launch(flavor, &spec, args, &StartupOptions::default())
|
||||
}
|
||||
|
||||
/// Recognize only the agreed literal selector/root pair before `--`. Everything after it is
|
||||
/// a file, even when it looks like a profile flag. No filesystem or startup hook runs here.
|
||||
pub fn parse(args: Vec<OsString>) -> Result<Launch, String> {
|
||||
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()),
|
||||
}
|
||||
pub fn launch_arguments(root: &Path, user_args: &[OsString]) -> Vec<OsString> {
|
||||
craft_nightly::launch_arguments(root, user_args)
|
||||
}
|
||||
|
||||
/// 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)
|
||||
}
|
||||
|
||||
/// The graphics retry is signalled by its process-local relaunch marker
|
||||
/// (`FILMCRAFT_GRAPHICS_RELAUNCHED`) and re-executes this program with an internal
|
||||
/// `--graphics <mode>` before the file delimiter. Ordinary Launcher calls still use the strict
|
||||
/// selector/root protocol; this is not authentication.
|
||||
pub fn parse_startup(args: Vec<OsString>, compatibility_retry: bool) -> Result<Launch, String> {
|
||||
let Some(mode) = compatibility_retry.then(|| internal_graphics(&args)).flatten() else { return parse(args) };
|
||||
let mut launch = parse(without_graphics(&args))?;
|
||||
if launch.profile.is_nightly() {
|
||||
launch.args.splice(0..0, [OsString::from("--graphics"), mode]);
|
||||
Ok(launch)
|
||||
} else {
|
||||
// Stable's argument order and parser remain unchanged.
|
||||
parse(args)
|
||||
}
|
||||
}
|
||||
|
||||
/// The `--graphics <mode>` pair the retry inserted before the file delimiter, if it is there once.
|
||||
fn internal_graphics(args: &[OsString]) -> Option<OsString> {
|
||||
let delimiter = args.iter().position(|arg| arg == "--").unwrap_or(args.len());
|
||||
let mut found = None;
|
||||
let mut iter = args[..delimiter].iter();
|
||||
while let Some(arg) = iter.next() {
|
||||
if arg == "--graphics" {
|
||||
if found.is_some() {
|
||||
return None;
|
||||
}
|
||||
found = Some(iter.next()?.clone());
|
||||
}
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
/// `args` without the internal `--graphics <mode>` pair before the file delimiter. Everything
|
||||
/// after `--` is a file name, even one spelled `--graphics`.
|
||||
fn without_graphics(args: &[OsString]) -> Vec<OsString> {
|
||||
let mut out = Vec::with_capacity(args.len());
|
||||
let mut iter = args.iter();
|
||||
while let Some(arg) = iter.next() {
|
||||
if arg == "--" {
|
||||
out.push(arg.clone());
|
||||
out.extend(iter.by_ref().cloned());
|
||||
} else if arg == "--graphics" {
|
||||
let _ = iter.next();
|
||||
} else {
|
||||
out.push(arg.clone());
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// 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<PathBuf, String>) -> Result<Launch, String> {
|
||||
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<OsString>, exe: Option<&Path>) -> Result<PathBuf, String> {
|
||||
crate::profile_root::validate(root, env, exe, crate::profile_root::ensure_writable)
|
||||
#[cfg(test)]
|
||||
pub fn parse_startup(flavor: BuildFlavor, args: impl IntoIterator<Item = OsString>) -> Result<Launch, ProfileError> {
|
||||
let spec = crate::profile_root::app_profile_spec();
|
||||
craft_nightly::parse_startup(flavor, &spec, args, &StartupOptions::default())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::cell::Cell;
|
||||
use std::ffi::OsString;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use craft_nightly::{NIGHTLY_V1_CONTRACT, ProfileError, canonical_profile_root};
|
||||
|
||||
use super::{BuildFlavor, Launch, Profile, current, launch_arguments, parse_startup};
|
||||
|
||||
fn args(values: &[&str]) -> Vec<OsString> {
|
||||
values.iter().map(OsString::from).collect()
|
||||
}
|
||||
|
||||
fn absolute() -> &'static str {
|
||||
if cfg!(windows) { r"C:\NightlyData\profiles\filmcraft" } else { "/nightly-data/profiles/filmcraft" }
|
||||
}
|
||||
|
||||
fn nightly() -> Vec<OsString> {
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--"])
|
||||
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--"])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direct_nightly_launch_self_isolates_into_canonical_root_and_preserves_args() {
|
||||
let expected_root = canonical_profile_root(crate::profile_root::APP_ID).unwrap();
|
||||
let launch = parse_startup(BuildFlavor::NightlyV1, args(&["--empty", "cut.fcproj"])).unwrap();
|
||||
assert_eq!(launch.profile, Profile::NightlyV1(expected_root));
|
||||
assert!(launch.profile.is_nightly());
|
||||
assert_eq!(launch.passthrough_args, args(&["--empty", "cut.fcproj"]));
|
||||
assert!(launch.leading_flags.is_empty());
|
||||
assert!(!launch.is_version_query());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn internal_graphics_retry_preserves_the_nightly_root_and_literal_files() {
|
||||
let mut argv = args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--graphics", "dx12", "--"]);
|
||||
let mut argv = args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--graphics", "dx12", "--"]);
|
||||
argv.extend(args(&["project with spaces.fcproj", "--graphics", "--profile-root"]));
|
||||
let launch = parse_startup(argv.clone(), true).unwrap();
|
||||
let launch = parse_startup(BuildFlavor::NightlyV1, argv).unwrap();
|
||||
assert_eq!(launch.profile, Profile::NightlyV1(PathBuf::from(absolute())));
|
||||
assert_eq!(launch.args, args(&["--graphics", "dx12", "--", "project with spaces.fcproj", "--graphics", "--profile-root"]));
|
||||
assert!(parse_startup(argv, false).is_err(), "an ordinary invocation must not gain extra protocol flags");
|
||||
assert_eq!(launch.passthrough_args, args(&["--graphics", "dx12", "--", "project with spaces.fcproj", "--graphics", "--profile-root"]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retry_cannot_bypass_invalid_profiles_or_change_stable_arguments() {
|
||||
let stable = args(&["--graphics", "dx12", "--new-instance", "stable.fcproj"]);
|
||||
assert_eq!(parse_startup(stable.clone(), true).unwrap(), Launch { profile: Profile::Stable, args: stable });
|
||||
let mut duplicate = args(&["--graphics", "dx12", "--graphics", "software"]);
|
||||
duplicate.extend(nightly());
|
||||
assert!(parse_startup(duplicate, true).is_err());
|
||||
assert!(parse_startup(args(&["--graphics", "dx12", "--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.fcproj"]), args(&["--", "--launch-profile", "file.fcproj"])] {
|
||||
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 });
|
||||
fn stable_arguments_are_unchanged_and_nightly_flags_are_refused() {
|
||||
for argv in [args(&[]), args(&["--demo", "a.fcproj"]), args(&["--", "--launch-profile", "file.fcproj"])] {
|
||||
let launch = parse_startup(BuildFlavor::Stable, argv.clone()).unwrap();
|
||||
assert_eq!(launch, Launch { profile: Profile::Stable, passthrough_args: argv, leading_flags: Vec::new() });
|
||||
}
|
||||
assert!(matches!(parse_startup(BuildFlavor::Stable, nightly()), Err(ProfileError::NightlyFlagsInStableBuild)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exact_version_and_root_are_parsed_without_reinterpreting_file_names() {
|
||||
let mut argv = nightly();
|
||||
argv.extend(args(&["--profile-root", "project with spaces.fcproj"]));
|
||||
let launch = parse(argv).unwrap();
|
||||
let launch = parse_startup(BuildFlavor::NightlyV1, argv).unwrap();
|
||||
assert_eq!(launch.profile, Profile::NightlyV1(PathBuf::from(absolute())));
|
||||
assert_eq!(launch.args, args(&["--", "--profile-root", "project with spaces.fcproj"]));
|
||||
assert_eq!(launch.passthrough_args, args(&["--profile-root", "project with spaces.fcproj"]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_duplicate_unknown_and_conflicting_profile_arguments_are_refused() {
|
||||
fn missing_duplicate_unknown_and_misplaced_profile_arguments_are_refused() {
|
||||
for argv in [
|
||||
args(&["--launch-profile", VERSION]),
|
||||
args(&["--launch-profile", NIGHTLY_V1_CONTRACT]),
|
||||
args(&["--profile-root", absolute()]),
|
||||
args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--"]),
|
||||
args(&["--launch-profile", VERSION, "--launch-profile", VERSION, "--profile-root", absolute(), "--"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--profile-root", absolute(), "--"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", "relative", "--"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", "", "--"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--new-instance", "--"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute()]),
|
||||
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--"]),
|
||||
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--profile-root", absolute(), "--"]),
|
||||
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", "", "--"]),
|
||||
args(&["a.fcproj", "--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute()]),
|
||||
] {
|
||||
assert!(parse(argv).is_err());
|
||||
assert!(parse_startup(BuildFlavor::NightlyV1, argv.clone()).is_err(), "{argv:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_launcher_version_check_is_a_version_query_only_in_its_exact_form() {
|
||||
let pair = &["--launch-profile", VERSION, "--profile-root", absolute()];
|
||||
let reversed = &["--profile-root", absolute(), "--launch-profile", VERSION];
|
||||
for flag in ["--version", "-V"] {
|
||||
for form in [pair, reversed] {
|
||||
let mut argv = args(form);
|
||||
argv.push(flag.into());
|
||||
assert!(version_query(&argv), "{argv:?}");
|
||||
}
|
||||
}
|
||||
fn recognizes_plain_and_launcher_version_queries_without_reinterpreting_files() {
|
||||
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"]),
|
||||
args(&["-V"]),
|
||||
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--", "--version"]),
|
||||
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--", "-V"]),
|
||||
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--version"]),
|
||||
args(&["--profile-root", absolute(), "--launch-profile", NIGHTLY_V1_CONTRACT, "-V"]),
|
||||
] {
|
||||
assert!(!version_query(&argv), "{argv:?}");
|
||||
let launch = parse_startup(BuildFlavor::NightlyV1, argv.clone()).unwrap();
|
||||
assert!(launch.is_version_query(), "{argv:?}");
|
||||
}
|
||||
// Outside the query the strict protocol still refuses the version flag.
|
||||
assert!(parse(args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version"])).is_err());
|
||||
let file_named_version = parse_startup(BuildFlavor::NightlyV1, args(&["--", "--version"])).unwrap();
|
||||
assert!(!file_named_version.is_version_query());
|
||||
assert_eq!(file_named_version.passthrough_args, args(&["--", "--version"]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_root_validation_never_reaches_startup_or_falls_back_to_stable() {
|
||||
let reached = Cell::new(false);
|
||||
let result = prepare(parse(nightly()).unwrap(), |_| Err("read-only or unsafe profile".into())).map(|_| reached.set(true));
|
||||
assert!(result.is_err());
|
||||
assert!(!reached.get());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn successful_root_validation_keeps_the_persistent_root_not_the_binary_tag() {
|
||||
let checked = PathBuf::from(absolute()).join("checked");
|
||||
let launch = prepare(parse(nightly()).unwrap(), |_| Ok(checked.clone())).unwrap();
|
||||
assert_eq!(launch.profile.root(), Some(checked.as_path()));
|
||||
assert!(launch.profile.is_nightly());
|
||||
fn current_defaults_to_stable_and_launch_arguments_round_trip() {
|
||||
assert!(!current().is_nightly());
|
||||
assert!(current().root().is_none());
|
||||
let encoded = launch_arguments(Path::new(absolute()), &args(&["cut.fcproj"]));
|
||||
let parsed = parse_startup(BuildFlavor::NightlyV1, encoded).unwrap();
|
||||
assert_eq!(parsed.profile, Profile::NightlyV1(PathBuf::from(absolute())));
|
||||
assert_eq!(parsed.passthrough_args, args(&["cut.fcproj"]));
|
||||
}
|
||||
}
|
||||
|
||||
+81
-42
@@ -139,9 +139,8 @@ fn report_launch_profile_error(error: &str) {
|
||||
/// Returns the arguments the rest of the start parses, or `None` when this was a version query.
|
||||
fn prepare_launch() -> Option<Vec<std::ffi::OsString>> {
|
||||
let argv: Vec<std::ffi::OsString> = std::env::args_os().skip(1).collect();
|
||||
// Plain `--version`/`-V`, or the Launcher's `--launch-profile nightly-v1 --profile-root <dir>
|
||||
// --version`: answered before root validation, process identity, logging or any window.
|
||||
if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && (build_flavor::version_query(&argv) || launch_profile::version_query(&argv)) {
|
||||
// Bare version queries do not resolve a profile or depend on HOME/LOCALAPPDATA.
|
||||
if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && matches!(argv.as_slice(), [arg] if arg == "--version" || arg == "-V") {
|
||||
use std::io::Write as _;
|
||||
let _ = writeln!(std::io::stdout(), "FilmCraft {}", build_flavor::version(build_flavor::COMPILED, version_text()));
|
||||
return None;
|
||||
@@ -150,33 +149,25 @@ fn prepare_launch() -> Option<Vec<std::ffi::OsString>> {
|
||||
// (`--test-graphics-start <mode>` [profile tokens]): its mode and root come from the parent,
|
||||
// never from the environment.
|
||||
let internal = argv.first().is_some_and(|arg| arg == graphics::probe::CHILD_ARG);
|
||||
let early = if internal {
|
||||
let tail = argv.get(2..).unwrap_or_default().to_vec();
|
||||
launch_profile::parse(tail).unwrap_or_else(|error| {
|
||||
report_launch_profile_error(&error);
|
||||
std::process::exit(2)
|
||||
})
|
||||
} else {
|
||||
let retry = std::env::var_os("FILMCRAFT_GRAPHICS_RELAUNCHED").is_some();
|
||||
launch_profile::parse_startup(argv.clone(), retry).unwrap_or_else(|error| {
|
||||
report_launch_profile_error(&error);
|
||||
std::process::exit(2)
|
||||
})
|
||||
};
|
||||
let early = build_flavor::require_profile(build_flavor::COMPILED, &early.profile)
|
||||
.and_then(|()| initialize_nightly_process_identity().map_err(|error| error.to_string()))
|
||||
.and_then(|()| {
|
||||
launch_profile::prepare(early, |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 startup_args = if internal { argv.get(2..).unwrap_or_default().to_vec() } else { argv.clone() };
|
||||
let early = launch_profile::prepare_launch(build_flavor::COMPILED, startup_args).unwrap_or_else(|error| {
|
||||
report_launch_profile_error(&error.to_string());
|
||||
std::process::exit(2)
|
||||
});
|
||||
// Plain `--version`/`-V`, or the Launcher's `--launch-profile nightly-v1 --profile-root <dir>
|
||||
// -- --version`: answered before process identity, logging or any window.
|
||||
if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && !internal && early.is_version_query() {
|
||||
use std::io::Write as _;
|
||||
let _ = writeln!(std::io::stdout(), "FilmCraft {}", build_flavor::version(build_flavor::COMPILED, version_text()));
|
||||
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() { filmcraft_ui_egui::os_window::LaunchIdentity::NightlyV1 } else { filmcraft_ui_egui::os_window::LaunchIdentity::Stable };
|
||||
// Read the launch's own arguments before `install` takes the profile: `runnable_argv` borrows it.
|
||||
let runnable = runnable_argv(internal, argv, &early);
|
||||
if let Err(error) = launch_profile::install(early.profile).and_then(|()| filmcraft_ui_egui::os_window::select_identity(identity)) {
|
||||
if let Err(error) = filmcraft_ui_egui::os_window::select_identity(identity) {
|
||||
report_launch_profile_error(&error);
|
||||
std::process::exit(2);
|
||||
}
|
||||
@@ -192,16 +183,36 @@ fn prepare_launch() -> Option<Vec<std::ffi::OsString>> {
|
||||
build_flavor::BuildFlavor::Stable => version_text().to_owned(),
|
||||
build_flavor::BuildFlavor::NightlyV1 => build_flavor::version(build_flavor::COMPILED, version_text()),
|
||||
});
|
||||
Some(runnable)
|
||||
Some(runnable_argv(internal, argv, &early))
|
||||
}
|
||||
|
||||
/// What `main` parses once the profile is selected. A Launcher start gets the profile's own tail
|
||||
/// (`--` and the file names): the raw argv still holds `--launch-profile`/`--profile-root`, which
|
||||
/// What `main` parses once the profile is selected. A Launcher start gets the profile's own
|
||||
/// passthrough arguments: the raw argv still holds `--launch-profile`/`--profile-root`, which
|
||||
/// `args::parse` refuses as unknown options, so every Nightly GUI start would exit 2. The graphics
|
||||
/// test child keeps its `--test-graphics-start <mode>` re-entry line, and ignores the tokens after
|
||||
/// it ([`graphics::probe::child_main`]).
|
||||
fn runnable_argv(internal: bool, argv: Vec<std::ffi::OsString>, launch: &launch_profile::Launch) -> Vec<std::ffi::OsString> {
|
||||
if internal { argv } else { launch.args.clone() }
|
||||
if internal { argv } else { launch.leading_flags.iter().cloned().chain(launch.passthrough_args.iter().cloned()).collect() }
|
||||
}
|
||||
|
||||
fn nightly_cli_override_error(nightly: bool, launch: &Launch) -> Option<&'static str> {
|
||||
if !nightly {
|
||||
return None;
|
||||
}
|
||||
if launch.control_port.is_some() || launch.control_input_only {
|
||||
return Some("filmcraft: a nightly-v1 start does not start the stable control server; drive FilmCraft Nightly through ArtCraft Launcher");
|
||||
}
|
||||
if launch.data_dir.is_some() {
|
||||
return Some("filmcraft: nightly-v1 cannot be combined with --data-dir; use --launch-profile nightly-v1 --profile-root <dir>");
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn reject_nightly_cli_overrides(nightly: bool, launch: &Launch) {
|
||||
if let Some(error) = nightly_cli_override_error(nightly, launch) {
|
||||
eprintln!("{error}");
|
||||
std::process::exit(2);
|
||||
}
|
||||
}
|
||||
|
||||
fn main() -> eframe::Result {
|
||||
@@ -245,10 +256,7 @@ fn main() -> eframe::Result {
|
||||
std::process::exit(2);
|
||||
}
|
||||
};
|
||||
if nightly && (launch.control_port.is_some() || launch.control_input_only) {
|
||||
eprintln!("filmcraft: a nightly-v1 start does not start the stable control server; drive FilmCraft Nightly through ArtCraft Launcher");
|
||||
std::process::exit(2);
|
||||
}
|
||||
reject_nightly_cli_overrides(nightly, &launch);
|
||||
let data_root = launch.data_dir.clone().or_else(default_data_dir);
|
||||
let log_dir = data_root.as_ref().map(|d| d.join(logging::LOG_DIR));
|
||||
log::info!("{} {} ({} {})", filmcraft_ui_egui::os_window::name(), version_text(), std::env::consts::OS, std::env::consts::ARCH);
|
||||
@@ -916,25 +924,56 @@ mod tests {
|
||||
let os = |v: &[&str]| v.iter().map(std::ffi::OsString::from).collect::<Vec<_>>();
|
||||
let root = if cfg!(windows) { r"C:\NightlyData\profiles\filmcraft" } else { "/nightly-data/profiles/filmcraft" };
|
||||
let argv = os(&["--launch-profile", "nightly-v1", "--profile-root", root, "--", "cut.fcproj", "clip with spaces.mp4"]);
|
||||
let launch = crate::launch_profile::parse(argv.clone()).unwrap();
|
||||
let launch = crate::launch_profile::parse_startup(crate::build_flavor::BuildFlavor::NightlyV1, argv.clone()).unwrap();
|
||||
let tail = super::runnable_argv(false, argv.clone(), &launch);
|
||||
assert_eq!(tail, launch.args);
|
||||
assert_eq!(tail, launch.passthrough_args);
|
||||
match crate::args::parse(None, tail) {
|
||||
Ok(crate::args::Cli::Run(l)) => assert_eq!(l.files, ["cut.fcproj", "clip with spaces.mp4"]),
|
||||
other => panic!("a nightly launch should start the app, got {other:?}"),
|
||||
}
|
||||
// A `--version` the Launcher appends after `--` stays a file name, as for stable.
|
||||
// Launcher version queries are handled before startup; a direct `-- --version` stays a file name.
|
||||
let query = os(&["--launch-profile", "nightly-v1", "--profile-root", root, "--", "--version"]);
|
||||
let launch = crate::launch_profile::parse(query.clone()).unwrap();
|
||||
assert!(matches!(crate::args::parse(None, super::runnable_argv(false, query, &launch)), Ok(crate::args::Cli::Run(l)) if l.files == ["--version"]));
|
||||
let launch = crate::launch_profile::parse_startup(crate::build_flavor::BuildFlavor::NightlyV1, query).unwrap();
|
||||
assert!(launch.is_version_query());
|
||||
let direct_file = os(&["--", "--version"]);
|
||||
let launch = crate::launch_profile::parse_startup(crate::build_flavor::BuildFlavor::NightlyV1, direct_file.clone()).unwrap();
|
||||
assert!(!launch.is_version_query());
|
||||
assert!(
|
||||
matches!(crate::args::parse(None, super::runnable_argv(false, direct_file, &launch)), Ok(crate::args::Cli::Run(l)) if l.files == ["--version"])
|
||||
);
|
||||
// The graphics test child keeps its re-entry head (`--test-graphics-start <mode>` first);
|
||||
// the raw Launcher line stays what `args::parse` refuses.
|
||||
let child = os(&["--test-graphics-start", "default", "--launch-profile", "nightly-v1", "--profile-root", root, "--"]);
|
||||
let launch = crate::launch_profile::parse(child[2..].to_vec()).unwrap();
|
||||
let launch = crate::launch_profile::parse_startup(crate::build_flavor::BuildFlavor::NightlyV1, child[2..].to_vec()).unwrap();
|
||||
assert_eq!(super::runnable_argv(true, child.clone(), &launch), child);
|
||||
assert!(crate::args::parse(None, argv).is_err(), "the raw Launcher line is not a FilmCraft command line");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nightly_cli_overrides_are_refused_only_for_nightly_launches() {
|
||||
let parse_run = |argv: &[&str]| match crate::args::parse(None, argv.iter().map(std::ffi::OsString::from)) {
|
||||
Ok(crate::args::Cli::Run(launch)) => launch,
|
||||
other => panic!("expected Run launch, got {other:?}"),
|
||||
};
|
||||
let plain = parse_run(&["--empty"]);
|
||||
assert_eq!(super::nightly_cli_override_error(true, &plain), None);
|
||||
super::reject_nightly_cli_overrides(true, &plain);
|
||||
|
||||
let stable_overrides = parse_run(&["--control", "9886", "--control-input-only", "--data-dir", "/tmp/stable"]);
|
||||
assert_eq!(super::nightly_cli_override_error(false, &stable_overrides), None);
|
||||
super::reject_nightly_cli_overrides(false, &stable_overrides);
|
||||
|
||||
let control = parse_run(&["--control", "9886"]);
|
||||
assert!(super::nightly_cli_override_error(true, &control).unwrap().contains("control server"));
|
||||
|
||||
let mut input_only = plain.clone();
|
||||
input_only.control_input_only = true;
|
||||
assert!(super::nightly_cli_override_error(true, &input_only).unwrap().contains("control server"));
|
||||
|
||||
let data_dir = parse_run(&["--data-dir", "/tmp/custom"]);
|
||||
assert!(super::nightly_cli_override_error(true, &data_dir).unwrap().contains("--data-dir"));
|
||||
}
|
||||
|
||||
/// The new start after a graphics panic keeps the arguments and picks the next mode, replacing a
|
||||
/// `--graphics` that was given (#2558).
|
||||
#[test]
|
||||
|
||||
+168
-644
@@ -1,348 +1,121 @@
|
||||
//! App-owned nightly profile fences; no stable fallback, migration or process environment changes.
|
||||
//! FilmCraft-specific nightly profile isolation spec for `craft-nightly`.
|
||||
|
||||
use std::ffi::OsString;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::path::PathBuf;
|
||||
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
use craft_nightly::AppProfileSpec;
|
||||
|
||||
pub const APP_ID: &str = "filmcraft";
|
||||
pub const DISPLAY_NAME: &str = "FilmCraft";
|
||||
pub const STABLE_DIR_NAMES: &[&str] = &["filmcraft", "FilmCraft"];
|
||||
pub const FORBIDDEN_ENV_VARS: &[&str] = &["FILMCRAFT_DATA_DIR"];
|
||||
/// The portable marker `filmcraft_engine::autosave` looks for beside the executable.
|
||||
const PORTABLE_MARKER: &str = "portable.txt";
|
||||
/// The folder a portable install keeps its data in, beside that marker.
|
||||
const PORTABLE_DATA_DIR: &str = "data";
|
||||
pub const PORTABLE_MARKERS: &[&str] = &["portable.txt"];
|
||||
/// Folders that must remain directories inside the profile root.
|
||||
pub const FOLDER_ONLY_ENTRIES: &[&str] = &["Recovery", "Logs", "Media Cache"];
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Platform {
|
||||
Windows,
|
||||
Linux,
|
||||
Mac,
|
||||
/// Builds the FilmCraft [`AppProfileSpec`] using the current process environment.
|
||||
pub fn app_profile_spec() -> AppProfileSpec {
|
||||
app_profile_spec_with_env(|key| std::env::var_os(key))
|
||||
}
|
||||
|
||||
impl Platform {
|
||||
fn current() -> Result<Self, String> {
|
||||
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()),
|
||||
/// Builds the FilmCraft [`AppProfileSpec`] using an injected environment lookup.
|
||||
pub fn app_profile_spec_with_env(env: impl Fn(&str) -> Option<OsString>) -> AppProfileSpec {
|
||||
AppProfileSpec {
|
||||
app_id: APP_ID,
|
||||
display_name: DISPLAY_NAME,
|
||||
stable_dir_names: STABLE_DIR_NAMES,
|
||||
stable_package_id: filmcraft_ui_egui::os_window::APP_ID,
|
||||
nightly_package_id: filmcraft_ui_egui::os_window::NIGHTLY_PACKAGE_ID,
|
||||
profile_root_env: None,
|
||||
forbidden_env_vars: FORBIDDEN_ENV_VARS,
|
||||
portable_markers: PORTABLE_MARKERS,
|
||||
folder_only_entries: FOLDER_ONLY_ENTRIES,
|
||||
extra_forbidden_roots: extra_forbidden_roots(&env),
|
||||
}
|
||||
}
|
||||
|
||||
fn non_empty_abs_env(env: &impl Fn(&str) -> Option<OsString>, key: &str) -> Option<PathBuf> {
|
||||
let value = env(key)?;
|
||||
if value.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let path = PathBuf::from(value);
|
||||
path.is_absolute().then_some(path)
|
||||
}
|
||||
|
||||
fn extra_forbidden_roots(env: &impl Fn(&str) -> Option<OsString>) -> Vec<PathBuf> {
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
let mut roots = Vec::new();
|
||||
// The MSI's default per-user and per-machine folders (install-policy.wxi).
|
||||
let local =
|
||||
non_empty_abs_env(env, "LOCALAPPDATA").or_else(|| non_empty_abs_env(env, "USERPROFILE").map(|profile| profile.join("AppData").join("Local")));
|
||||
if let Some(local) = local {
|
||||
roots.push(local.join("Programs").join("ArtCraft").join("FilmCraft"));
|
||||
}
|
||||
}
|
||||
|
||||
fn ignores_case(self) -> bool {
|
||||
self != Self::Linux
|
||||
}
|
||||
}
|
||||
|
||||
fn absolute(path: PathBuf, label: &str) -> Result<PathBuf, String> {
|
||||
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<OsString>, key: &str) -> Result<PathBuf, String> {
|
||||
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<OsString>, key: &str, fallback: &str) -> Result<PathBuf, String> {
|
||||
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<PathBuf, String> {
|
||||
let mut parent = path;
|
||||
let mut missing = Vec::new();
|
||||
loop {
|
||||
match std::fs::symlink_metadata(parent) {
|
||||
Ok(_) => break,
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
|
||||
missing.push(parent.file_name().ok_or("the profile root has no existing ancestor")?.to_os_string());
|
||||
parent = parent.parent().ok_or("the profile root has no existing ancestor")?;
|
||||
for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] {
|
||||
if let Some(base) = non_empty_abs_env(env, key) {
|
||||
roots.push(base.join("ArtCraft").join("FilmCraft"));
|
||||
}
|
||||
Err(error) => return Err(format!("cannot inspect the profile boundary: {error}")),
|
||||
}
|
||||
roots
|
||||
}
|
||||
let mut resolved = std::fs::canonicalize(parent).map_err(|e| format!("cannot resolve the profile boundary: {e}"))?;
|
||||
for part in missing.into_iter().rev() {
|
||||
resolved.push(part);
|
||||
}
|
||||
Ok(resolved)
|
||||
}
|
||||
|
||||
fn overlaps(a: &Path, b: &Path, platform: Platform) -> bool {
|
||||
let parts = |p: &Path| {
|
||||
p.components()
|
||||
.map(|c| {
|
||||
let value = c.as_os_str().to_string_lossy().into_owned();
|
||||
if platform.ignores_case() { value.to_lowercase() } else { value }
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
let (a, b) = (parts(a), parts(b));
|
||||
a.starts_with(&b) || b.starts_with(&a)
|
||||
}
|
||||
|
||||
fn installation_boundary(platform: Platform, exe: &Path) -> Result<PathBuf, String> {
|
||||
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<OsString>, exe: &Path) -> Result<Vec<PathBuf>, String> {
|
||||
let mut roots = match platform {
|
||||
Platform::Windows => {
|
||||
// %APPDATA%\FilmCraft is the per-user data directory (autosave::default_data_dir);
|
||||
// %LOCALAPPDATA%\FilmCraft is fenced as well, so no future local cache can land there.
|
||||
let mut roots =
|
||||
["APPDATA", "LOCALAPPDATA"].into_iter().map(|key| required_base(env, key).map(|p| p.join("FilmCraft"))).collect::<Result<Vec<_>, _>>()?;
|
||||
// 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("FilmCraft"));
|
||||
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("FilmCraft"));
|
||||
}
|
||||
}
|
||||
roots
|
||||
}
|
||||
Platform::Linux => {
|
||||
// The data directory is real; the config, cache and state roots are fenced so a
|
||||
// future one cannot point Nightly at stable state. `~/.var/app` is the stable
|
||||
// Flatpak's own per-app folder.
|
||||
let mut roots =
|
||||
[("XDG_DATA_HOME", ".local/share"), ("XDG_CONFIG_HOME", ".config"), ("XDG_CACHE_HOME", ".cache"), ("XDG_STATE_HOME", ".local/state")]
|
||||
.into_iter()
|
||||
.map(|(key, fallback)| xdg_base(env, key, fallback).map(|p| p.join("filmcraft")))
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
roots.extend(["/usr/bin/filmcraft", "/usr/local/bin/filmcraft", "/opt/filmcraft"].map(PathBuf::from));
|
||||
let data = xdg_base(env, "XDG_DATA_HOME", ".local/share")?;
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
{
|
||||
let mut roots = vec![PathBuf::from("/usr/bin/filmcraft"), PathBuf::from("/usr/local/bin/filmcraft"), PathBuf::from("/opt/filmcraft")];
|
||||
let home = non_empty_abs_env(env, "HOME");
|
||||
let data = non_empty_abs_env(env, "XDG_DATA_HOME").or_else(|| home.as_ref().map(|h| h.join(".local").join("share")));
|
||||
if let Some(data) = data {
|
||||
// Dev builds write a desktop entry and its hicolor icons into the XDG data dir
|
||||
// (apps/filmcraft/src/dev_icon.rs); a Nightly profile is never inside them.
|
||||
roots.push(data.join("applications").join("ai.storyteller.filmcraft.desktop"));
|
||||
roots.push(data.join("icons").join("hicolor"));
|
||||
roots.push(required_base(env, "HOME")?.join(".var/app/ai.storyteller.filmcraft"));
|
||||
roots
|
||||
}
|
||||
Platform::Mac => {
|
||||
let home = required_base(env, "HOME")?;
|
||||
if let Some(home) = home {
|
||||
roots.push(home.join(".var/app/ai.storyteller.filmcraft"));
|
||||
}
|
||||
roots
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
let mut roots = vec![PathBuf::from("/Applications/FilmCraft.app")];
|
||||
if let Some(home) = non_empty_abs_env(env, "HOME") {
|
||||
let library = home.join("Library");
|
||||
vec![
|
||||
library.join("Application Support/FilmCraft"),
|
||||
library.join("Caches/FilmCraft"),
|
||||
library.join("Caches/ai.storyteller.filmcraft"),
|
||||
library.join("Preferences/FilmCraft"),
|
||||
library.join("Preferences/ai.storyteller.filmcraft.plist"),
|
||||
library.join("Saved Application State/ai.storyteller.filmcraft.savedState"),
|
||||
home.join("Applications/FilmCraft.app"),
|
||||
PathBuf::from("/Applications/FilmCraft.app"),
|
||||
]
|
||||
roots.push(library.join("Preferences/ai.storyteller.filmcraft.plist"));
|
||||
roots.push(library.join("Saved Application State/ai.storyteller.filmcraft.savedState"));
|
||||
roots.push(home.join("Applications/FilmCraft.app"));
|
||||
}
|
||||
};
|
||||
roots.push(installation_boundary(platform, exe)?);
|
||||
roots.into_iter().map(|p| canonical_future(&p)).collect()
|
||||
}
|
||||
|
||||
/// Folders that must remain directories inside the profile root.
|
||||
const PROFILE_FOLDERS: [&str; 3] = ["Recovery", "Logs", "Media Cache"];
|
||||
|
||||
fn private_subdirectory(root: &Path, name: impl AsRef<Path>, label: &str, platform: Platform) -> Result<PathBuf, String> {
|
||||
let chosen = canonical_future(&absolute(root.to_path_buf(), "the nightly profile root")?)?;
|
||||
let child = canonical_future(&chosen.join(name))?;
|
||||
if child == chosen || !child.starts_with(&chosen) {
|
||||
return Err(format!("the nightly {label} must stay inside its selected profile"));
|
||||
roots
|
||||
}
|
||||
// The target's own ancestors decide this, not the profile's: an alias may otherwise point into
|
||||
// a Stable portable install that happens to sit inside the selected profile.
|
||||
if is_portable_layout(&child, platform) {
|
||||
return Err(format!("the nightly {label} must not use a portable FilmCraft installation or its data folder"));
|
||||
}
|
||||
match std::fs::metadata(&child) {
|
||||
Ok(metadata) if !metadata.is_dir() => return Err(format!("the nightly {label} must be a directory")),
|
||||
Ok(_) => {}
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
|
||||
Err(error) => return Err(format!("cannot inspect the nightly {label}: {error}")),
|
||||
}
|
||||
Ok(child)
|
||||
}
|
||||
|
||||
/// Every existing entry directly in the profile (logs, preferences 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, platform: Platform) -> 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", platform)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Persisted files must have their own ordinary file identity, not an alias to other data.
|
||||
fn private_regular_file(path: &Path, metadata: &std::fs::Metadata) -> Result<(), String> {
|
||||
#[cfg(unix)]
|
||||
#[cfg(not(any(unix, target_os = "windows")))]
|
||||
{
|
||||
use std::os::unix::fs::MetadataExt as _;
|
||||
if metadata.nlink() != 1 {
|
||||
return Err("the nightly profile file must not be shared".into());
|
||||
}
|
||||
let _ = env;
|
||||
Vec::new()
|
||||
}
|
||||
#[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 portable data namespace in both the supplied and resolved path. A marker only
|
||||
/// counts beside a FilmCraft executable (above the chosen folder itself), so an unrelated
|
||||
/// `portable.txt` higher up does not refuse the profile.
|
||||
///
|
||||
/// A `data` component counts only when its parent holds the portable marker: the Nightly Flatpak's
|
||||
/// own `~/.var/app/…/data/filmcraft-nightly/profile`, and any home with a `data` folder, are
|
||||
/// ordinary per-user paths, not a portable install's data directory.
|
||||
fn is_portable_layout(path: &Path, platform: Platform) -> bool {
|
||||
path.ancestors().enumerate().any(|(depth, ancestor)| {
|
||||
ancestor.join(PORTABLE_MARKER).is_file() && (depth == 0 || ["filmcraft.exe", "filmcraft", "FilmCraft"].iter().any(|exe| ancestor.join(exe).is_file()))
|
||||
}) || path.ancestors().any(|ancestor| {
|
||||
let named_data = ancestor.file_name().is_some_and(|name| {
|
||||
if platform.ignores_case() { name.to_string_lossy().eq_ignore_ascii_case(PORTABLE_DATA_DIR) } else { name == PORTABLE_DATA_DIR }
|
||||
});
|
||||
named_data && ancestor.parent().is_some_and(|install| install.join(PORTABLE_MARKER).is_file())
|
||||
})
|
||||
}
|
||||
|
||||
/// The app's existing exclusive write probe: create and remove a file in the profile.
|
||||
pub fn ensure_writable(dir: &Path) -> std::io::Result<()> {
|
||||
// The name is unique to this validation: two windows may validate the same writable profile at
|
||||
// once, and a shared name would make the second `create_new` fail with AlreadyExists.
|
||||
static NEXT: AtomicU64 = AtomicU64::new(0);
|
||||
let probe = dir.join(format!("exclusive-write-probe-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
|
||||
let file = std::fs::OpenOptions::new().write(true).create_new(true).open(&probe)?;
|
||||
drop(file);
|
||||
std::fs::remove_file(probe)
|
||||
}
|
||||
|
||||
/// The writable hook is injected so the boundary tests exercise the real policy without starting
|
||||
/// the app or changing global state.
|
||||
pub fn validate(
|
||||
root: &Path,
|
||||
env: impl Fn(&str) -> Option<OsString>,
|
||||
exe: Option<&Path>,
|
||||
writable: impl FnOnce(&Path) -> std::io::Result<()>,
|
||||
) -> Result<PathBuf, String> {
|
||||
validate_for(Platform::current()?, root, env, exe, writable)
|
||||
}
|
||||
|
||||
fn validate_for(
|
||||
platform: Platform,
|
||||
root: &Path,
|
||||
env: impl Fn(&str) -> Option<OsString>,
|
||||
exe: Option<&Path>,
|
||||
writable: impl FnOnce(&Path) -> std::io::Result<()>,
|
||||
) -> Result<PathBuf, String> {
|
||||
absolute(root.to_path_buf(), "the nightly profile root")?;
|
||||
// The stable data-directory override would point every write outside the private profile.
|
||||
if env("FILMCRAFT_DATA_DIR").is_some_and(|v| !v.is_empty()) {
|
||||
return Err("nightly-v1 cannot be combined with FILMCRAFT_DATA_DIR".into());
|
||||
}
|
||||
if platform != Platform::Windows {
|
||||
// A native Nightly package must not inherit a Flatpak runtime: its socket namespace could
|
||||
// point this profile at another app's instance. The Nightly Flatpak itself is not that
|
||||
// case -- its sandbox data is `~/.var/app/ai.storyteller.filmcraft.nightly`, separate from
|
||||
// stable -- so exactly the app's own Nightly id is accepted and every other value refused.
|
||||
if let Some(id) = env("FLATPAK_ID").filter(|value| !value.is_empty())
|
||||
&& id.as_os_str() != std::ffi::OsStr::new(filmcraft_ui_egui::os_window::NIGHTLY_PACKAGE_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 FilmCraft installation or its data 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, platform)?;
|
||||
// Recovery can read, adopt, overwrite and sweep entries, and the log writer rotates files.
|
||||
// Never let their aliases leave this private profile or alias portable data inside it.
|
||||
private_subdirectory(&chosen, "Recovery", "recovery folder", platform)?;
|
||||
private_subdirectory(&chosen, "Logs", "log folder", platform)?;
|
||||
let mut create = std::fs::DirBuilder::new();
|
||||
create.recursive(true);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::DirBuilderExt as _;
|
||||
create.mode(0o700);
|
||||
}
|
||||
create.create(&chosen).map_err(|e| format!("cannot create the nightly profile: {e}"))?;
|
||||
let confirmed = std::fs::canonicalize(&chosen).map_err(|e| format!("cannot resolve the created nightly profile: {e}"))?;
|
||||
if confirmed != chosen || forbidden.iter().any(|stable| overlaps(&confirmed, stable, platform)) {
|
||||
return Err("the nightly profile changed while it was being validated".into());
|
||||
}
|
||||
private_subdirectory(&confirmed, "Recovery", "recovery folder", platform)?;
|
||||
private_subdirectory(&confirmed, "Logs", "log folder", platform)?;
|
||||
entries_stay_inside(&confirmed, platform)?;
|
||||
writable(&confirmed).map_err(|e| format!("the nightly profile is not writable: {e}"))?;
|
||||
Ok(confirmed)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::collections::BTreeMap;
|
||||
use std::ffi::OsString;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
struct Fixture {
|
||||
use craft_nightly::{ProfileError, validate_and_prepare_root};
|
||||
|
||||
use super::{
|
||||
APP_ID, DISPLAY_NAME, FOLDER_ONLY_ENTRIES, FORBIDDEN_ENV_VARS, PORTABLE_MARKERS, STABLE_DIR_NAMES, app_profile_spec_with_env, extra_forbidden_roots,
|
||||
};
|
||||
|
||||
struct TempDir {
|
||||
root: PathBuf,
|
||||
env: BTreeMap<String, OsString>,
|
||||
exe: PathBuf,
|
||||
}
|
||||
|
||||
impl Fixture {
|
||||
impl TempDir {
|
||||
fn new() -> Self {
|
||||
static NEXT: AtomicU64 = AtomicU64::new(0);
|
||||
let root = loop {
|
||||
@@ -353,366 +126,117 @@ mod tests {
|
||||
Err(error) => panic!("cannot create owned fixture: {error}"),
|
||||
}
|
||||
};
|
||||
let home = root.join("home");
|
||||
let exe = root.join("install/filmcraft");
|
||||
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<OsString> {
|
||||
self.env.get(key).cloned()
|
||||
}
|
||||
|
||||
fn check(&self, platform: Platform, root: &Path) -> Result<PathBuf, String> {
|
||||
validate_for(platform, root, |key| self.get(key), Some(&self.exe), ensure_writable)
|
||||
}
|
||||
|
||||
fn refuse(&self, platform: Platform, root: &Path) -> String {
|
||||
let probed = std::cell::Cell::new(false);
|
||||
let result = validate_for(
|
||||
platform,
|
||||
root,
|
||||
|key| self.get(key),
|
||||
Some(&self.exe),
|
||||
|_| {
|
||||
probed.set(true);
|
||||
Ok(())
|
||||
},
|
||||
);
|
||||
assert!(!probed.get(), "a refused root must never reach the writable probe");
|
||||
result.unwrap_err()
|
||||
}
|
||||
|
||||
fn home(&self) -> PathBuf {
|
||||
PathBuf::from(self.get("HOME").unwrap())
|
||||
Self { root }
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Fixture {
|
||||
impl Drop for TempDir {
|
||||
fn drop(&mut self) {
|
||||
std::fs::remove_dir_all(&self.root).unwrap();
|
||||
let _ = std::fs::remove_dir_all(&self.root);
|
||||
}
|
||||
}
|
||||
|
||||
#[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("data");
|
||||
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("preferences.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")] {
|
||||
assert!(!fixture.refuse(platform, candidate).is_empty());
|
||||
assert!(!stable_data.join("nested nightly").exists());
|
||||
assert_eq!(std::fs::read(stable_data.join("preferences.json")).unwrap(), b"stable settings must not change");
|
||||
}
|
||||
}
|
||||
// A portable marker with no FilmCraft executable beside it 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/filmcraft")).is_ok());
|
||||
// A merely similar data folder name is not the portable namespace.
|
||||
assert!(fixture.check(Platform::Linux, &fixture.root.join("data-backup/nightly")).is_ok());
|
||||
fn spec_preserves_filmcraft_security_fence_parameters() {
|
||||
let spec = app_profile_spec_with_env(|key| match key {
|
||||
"HOME" | "LOCALAPPDATA" => Some(OsString::from("")),
|
||||
"XDG_DATA_HOME" | "ProgramFiles" => Some(OsString::from("relative/path")),
|
||||
_ => None,
|
||||
});
|
||||
assert_eq!(spec.app_id, APP_ID);
|
||||
assert_eq!(spec.display_name, DISPLAY_NAME);
|
||||
assert_eq!(spec.stable_dir_names, STABLE_DIR_NAMES);
|
||||
assert_eq!(spec.stable_package_id, filmcraft_ui_egui::os_window::APP_ID);
|
||||
assert_eq!(spec.nightly_package_id, filmcraft_ui_egui::os_window::NIGHTLY_PACKAGE_ID);
|
||||
assert_eq!(spec.profile_root_env, None);
|
||||
assert_eq!(spec.forbidden_env_vars, FORBIDDEN_ENV_VARS);
|
||||
assert_eq!(spec.portable_markers, PORTABLE_MARKERS);
|
||||
assert_eq!(spec.folder_only_entries, FOLDER_ONLY_ENTRIES);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_data_folder_beside_no_portable_marker_is_not_a_portable_install() {
|
||||
let mut fixture = Fixture::new();
|
||||
// The Nightly Flatpak's own sandbox data root is `…/ai.storyteller.filmcraft.nightly/data`,
|
||||
// and a home may hold a plain `data` folder: neither is a portable install (#5225 review).
|
||||
let plain = fixture.root.join("data/filmcraft-nightly/profile");
|
||||
assert_eq!(fixture.check(Platform::Linux, &plain).unwrap(), plain);
|
||||
let sandbox = fixture.home().join(".var/app/ai.storyteller.filmcraft.nightly/data/filmcraft-nightly/profile");
|
||||
fixture.env.insert("FLATPAK_ID".into(), filmcraft_ui_egui::os_window::NIGHTLY_PACKAGE_ID.into());
|
||||
assert_eq!(fixture.check(Platform::Linux, &sandbox).unwrap(), sandbox);
|
||||
// Only the Nightly Flatpak's own id may inherit a sandbox; every other one is refused.
|
||||
fixture.env.insert("FLATPAK_ID".into(), "ai.storyteller.filmcraft".into());
|
||||
assert!(fixture.refuse(Platform::Linux, &sandbox).contains("Flatpak"));
|
||||
}
|
||||
fn extra_forbidden_roots_cover_platform_install_and_stable_artifacts() {
|
||||
let fixture = TempDir::new();
|
||||
let mut env: BTreeMap<String, OsString> = BTreeMap::new();
|
||||
let home = fixture.root.join("home");
|
||||
env.insert("HOME".into(), home.clone().into_os_string());
|
||||
env.insert("XDG_DATA_HOME".into(), fixture.root.join("xdg-data").into_os_string());
|
||||
env.insert("LOCALAPPDATA".into(), fixture.root.join("local").into_os_string());
|
||||
env.insert("ProgramFiles".into(), fixture.root.join("pf").into_os_string());
|
||||
env.insert("ProgramW6432".into(), fixture.root.join("pf64").into_os_string());
|
||||
env.insert("ProgramFiles(x86)".into(), fixture.root.join("pf86").into_os_string());
|
||||
|
||||
#[test]
|
||||
fn linux_fences_app_xdg_subtrees_but_allows_launcher_sibling() {
|
||||
let mut fixture = Fixture::new();
|
||||
for key in ["XDG_DATA_HOME", "XDG_CONFIG_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME"] {
|
||||
fixture.env.insert(key.into(), fixture.root.join(key).into_os_string());
|
||||
}
|
||||
for key in ["XDG_DATA_HOME", "XDG_CONFIG_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME"] {
|
||||
let stable = PathBuf::from(fixture.get(key).unwrap()).join("filmcraft");
|
||||
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.refuse(Platform::Linux, &candidate).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/filmcraft");
|
||||
assert_eq!(fixture.check(Platform::Linux, &nightly).unwrap(), nightly);
|
||||
assert_eq!(std::fs::read_dir(nightly).unwrap().count(), 0);
|
||||
}
|
||||
let roots = extra_forbidden_roots(&|key| env.get(key).cloned());
|
||||
|
||||
#[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 ["preferences.json", "workspaces.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("preferences.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 linux_fences_the_dev_desktop_entry_the_icon_theme_and_the_stable_flatpak() {
|
||||
let mut fixture = Fixture::new();
|
||||
let data = fixture.root.join("xdg-data");
|
||||
fixture.env.insert("XDG_DATA_HOME".into(), data.clone().into_os_string());
|
||||
for stable in [data.join("applications/ai.storyteller.filmcraft.desktop"), data.join("icons/hicolor")] {
|
||||
assert!(fixture.refuse(Platform::Linux, &stable.join("nightly")).contains("overlap"));
|
||||
}
|
||||
let flatpak = fixture.home().join(".var/app/ai.storyteller.filmcraft");
|
||||
for candidate in [flatpak.clone(), flatpak.join("data/nightly")] {
|
||||
assert!(fixture.refuse(Platform::Linux, &candidate).contains("overlap"));
|
||||
}
|
||||
assert!(!flatpak.exists());
|
||||
// These are POSIX absolute paths: on a Windows host `/usr/bin/...` has no root and fails the
|
||||
// absolute-path check before the fence, so the case only means anything on unix.
|
||||
#[cfg(unix)]
|
||||
for install in ["/usr/bin/filmcraft", "/usr/local/bin/filmcraft", "/opt/filmcraft"] {
|
||||
assert!(fixture.refuse(Platform::Linux, &PathBuf::from(install).join("profile")).contains("overlap"));
|
||||
}
|
||||
assert!(fixture.check(Platform::Linux, &fixture.home().join(".var/app/ai.storyteller.launcher/nightly")).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mac_fences_only_app_library_subtrees_and_the_entire_bundle() {
|
||||
let mut fixture = Fixture::new();
|
||||
fixture.exe = fixture.root.join("install/FilmCraft Nightly.app/Contents/MacOS/FilmCraft");
|
||||
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/FilmCraft",
|
||||
"Caches/FilmCraft",
|
||||
"Caches/ai.storyteller.filmcraft",
|
||||
"Preferences/FilmCraft",
|
||||
"Preferences/ai.storyteller.filmcraft.plist",
|
||||
"Saved Application State/ai.storyteller.filmcraft.savedState",
|
||||
] {
|
||||
let stable = library.join(suffix);
|
||||
assert!(fixture.refuse(Platform::Mac, &stable.join("nightly")).contains("overlap"));
|
||||
assert!(!stable.exists());
|
||||
}
|
||||
let inside_resources = fixture.exe.parent().unwrap().parent().unwrap().join("Resources/profile");
|
||||
assert!(fixture.refuse(Platform::Mac, &inside_resources).contains("overlap"));
|
||||
assert!(!inside_resources.exists());
|
||||
for bundle in [fixture.home().join("Applications/FilmCraft.app"), PathBuf::from("/Applications/FilmCraft.app")] {
|
||||
assert!(!fixture.refuse(Platform::Mac, &bundle.join("profile")).is_empty());
|
||||
}
|
||||
let valid = library.join("Application Support/ArtCraftLauncher/nightly/profiles/filmcraft");
|
||||
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("FilmCraft");
|
||||
assert!(fixture.refuse(Platform::Windows, &stable.join("nightly")).contains("overlap"));
|
||||
assert!(!stable.exists());
|
||||
}
|
||||
assert!(!fixture.refuse(Platform::Windows, &fixture.exe.parent().unwrap().join("profile")).is_empty());
|
||||
assert!(fixture.check(Platform::Windows, &fixture.root.join("Launcher/profiles/filmcraft")).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("FilmCraft");
|
||||
assert!(fixture.refuse(Platform::Windows, &per_user.join("nightly")).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("FilmCraft");
|
||||
assert!(fixture.refuse(Platform::Windows, &machine.join("nightly")).contains("overlap"));
|
||||
assert!(!machine.exists());
|
||||
}
|
||||
let sibling = local.join("Programs").join("ArtCraft").join("ArtCraftLauncher").join("nightly").join("filmcraft");
|
||||
assert!(fixture.check(Platform::Windows, &sibling).is_ok(), "the Launcher's own Programs sibling is not FilmCraft's install");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlap_check_handles_ancestor_descendant_and_prefix_lookalikes() {
|
||||
let fixture = Fixture::new();
|
||||
let root = fixture.home().join("nightly/profiles/filmcraft");
|
||||
for platform in [Platform::Windows, Platform::Linux, Platform::Mac] {
|
||||
assert!(overlaps(&root, &root.join("Recovery"), platform));
|
||||
assert!(overlaps(&root.join("Recovery"), &root, platform));
|
||||
assert!(!overlaps(&root, &root.with_file_name("filmcraft-other"), platform));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn recovery_and_log_aliases_cannot_redirect_to_stable_missing_or_profile_root_data() {
|
||||
let fixture = Fixture::new();
|
||||
let stable = fixture.home().join(".local/share/filmcraft/Recovery");
|
||||
std::fs::create_dir_all(&stable).unwrap();
|
||||
std::fs::write(stable.join("stable-autosave"), b"stable recovery bytes").unwrap();
|
||||
for (index, (name, target)) in
|
||||
[("Recovery", stable.clone()), ("Logs", stable.clone()), ("Recovery", fixture.root.join("missing target"))].into_iter().enumerate()
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
{
|
||||
let private = fixture.root.join(format!("nightly-{index}"));
|
||||
std::fs::create_dir(&private).unwrap();
|
||||
std::os::unix::fs::symlink(&target, private.join(name)).unwrap();
|
||||
assert!(!fixture.refuse(Platform::Linux, &private).is_empty(), "{name} must not escape the private profile");
|
||||
assert!(roots.contains(&PathBuf::from("/usr/bin/filmcraft")));
|
||||
assert!(roots.contains(&PathBuf::from("/usr/local/bin/filmcraft")));
|
||||
assert!(roots.contains(&PathBuf::from("/opt/filmcraft")));
|
||||
assert!(roots.contains(&fixture.root.join("xdg-data/applications/ai.storyteller.filmcraft.desktop")));
|
||||
assert!(roots.contains(&fixture.root.join("xdg-data/icons/hicolor")));
|
||||
assert!(roots.contains(&home.join(".var/app/ai.storyteller.filmcraft")));
|
||||
}
|
||||
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.refuse(Platform::Linux, &private).is_empty(), "Recovery cannot treat all profile settings as recovery entries");
|
||||
assert_eq!(std::fs::read(stable.join("stable-autosave")).unwrap(), b"stable recovery bytes");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn recovery_and_log_aliases_cannot_alias_a_portable_install_inside_the_profile() {
|
||||
let fixture = Fixture::new();
|
||||
for name in ["Recovery", "Logs"] {
|
||||
// A Stable portable install nested in the selected profile: the alias target resolves
|
||||
// inside the profile, so only the target's own ancestors can refuse it.
|
||||
let private = fixture.root.join(format!("nightly-portable-{name}"));
|
||||
let portable = private.join("downloads/stable");
|
||||
let stable_data = portable.join("data");
|
||||
std::fs::create_dir_all(stable_data.join(name)).unwrap();
|
||||
std::fs::write(portable.join("portable.txt"), b"owned portable fixture").unwrap();
|
||||
std::fs::write(portable.join("filmcraft"), b"fixture executable, never run").unwrap();
|
||||
std::fs::write(stable_data.join("preferences.json"), b"stable settings must not change").unwrap();
|
||||
std::os::unix::fs::symlink(stable_data.join(name), private.join(name)).unwrap();
|
||||
assert!(fixture.refuse(Platform::Linux, &private).contains("portable"), "{name} must not alias portable data");
|
||||
assert_eq!(std::fs::read(stable_data.join("preferences.json")).unwrap(), b"stable settings must not change");
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
assert!(roots.contains(&PathBuf::from("/Applications/FilmCraft.app")));
|
||||
assert!(roots.contains(&home.join("Applications/FilmCraft.app")));
|
||||
assert!(roots.contains(&home.join("Library/Preferences/ai.storyteller.filmcraft.plist")));
|
||||
assert!(roots.contains(&home.join("Library/Saved Application State/ai.storyteller.filmcraft.savedState")));
|
||||
}
|
||||
// Ordinary nested directories stay accepted, as before.
|
||||
let private = fixture.root.join("nightly-plain");
|
||||
std::fs::create_dir_all(private.join("private-recovery")).unwrap();
|
||||
std::os::unix::fs::symlink(private.join("private-recovery"), private.join("Recovery")).unwrap();
|
||||
assert!(fixture.check(Platform::Linux, &private).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_write_probe_does_not_collide_with_another_validation() {
|
||||
let fixture = Fixture::new();
|
||||
let dir = fixture.root.join("probe");
|
||||
std::fs::create_dir(&dir).unwrap();
|
||||
// A probe another window left in this profile must not refuse this launch.
|
||||
std::fs::write(dir.join("exclusive-write-probe"), b"another validation").unwrap();
|
||||
ensure_writable(&dir).unwrap();
|
||||
assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 1, "this validation left no probe behind");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn aliases_inside_the_private_profile_keep_it_usable() {
|
||||
let fixture = Fixture::new();
|
||||
let private = fixture.root.join("nightly-private");
|
||||
let recovery = private.join("private-recovery");
|
||||
let logs = private.join("private-logs");
|
||||
std::fs::create_dir_all(&recovery).unwrap();
|
||||
std::fs::create_dir_all(&logs).unwrap();
|
||||
std::os::unix::fs::symlink(&recovery, private.join("Recovery")).unwrap();
|
||||
std::os::unix::fs::symlink(&logs, private.join("Logs")).unwrap();
|
||||
assert!(fixture.check(Platform::Linux, &private).is_ok());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn any_profile_entry_alias_must_stay_inside_the_profile() {
|
||||
let fixture = Fixture::new();
|
||||
let stable = fixture.home().join(".local/share/filmcraft/effect-presets.json");
|
||||
std::fs::create_dir_all(stable.parent().unwrap()).unwrap();
|
||||
std::fs::write(&stable, b"stable preset bytes").unwrap();
|
||||
for name in ["preferences.json", "workspaces.json", "Media Cache"] {
|
||||
let private = fixture.root.join(format!("nightly-{name}"));
|
||||
std::fs::create_dir(&private).unwrap();
|
||||
std::os::unix::fs::symlink(&stable, private.join(name)).unwrap();
|
||||
assert!(!fixture.refuse(Platform::Linux, &private).is_empty(), "{name} must not lead outside the profile");
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
assert!(roots.contains(&fixture.root.join("local/Programs/ArtCraft/FilmCraft")));
|
||||
assert!(roots.contains(&fixture.root.join("pf/ArtCraft/FilmCraft")));
|
||||
assert!(roots.contains(&fixture.root.join("pf64/ArtCraft/FilmCraft")));
|
||||
assert!(roots.contains(&fixture.root.join("pf86/ArtCraft/FilmCraft")));
|
||||
}
|
||||
let private = fixture.root.join("nightly-inside");
|
||||
std::fs::create_dir_all(private.join("Cache")).unwrap();
|
||||
std::fs::write(private.join("preferences.json"), b"{}").unwrap();
|
||||
std::os::unix::fs::symlink(private.join("Cache"), private.join("Media Cache")).unwrap();
|
||||
assert!(fixture.check(Platform::Linux, &private).is_ok(), "regular files and links that stay inside are fine");
|
||||
assert_eq!(std::fs::read(&stable).unwrap(), b"stable preset bytes");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ambiguous_environment_and_non_native_sandbox_are_refused_before_creation() {
|
||||
let mut fixture = Fixture::new();
|
||||
let candidate = fixture.home().join("nightly/profiles/filmcraft");
|
||||
fixture.env.insert("XDG_CACHE_HOME".into(), "relative/cache".into());
|
||||
assert!(fixture.refuse(Platform::Linux, &candidate).contains("absolute"));
|
||||
fixture.env.remove("XDG_CACHE_HOME");
|
||||
fixture.env.insert("FILMCRAFT_DATA_DIR".into(), fixture.home().join("custom-stable").into_os_string());
|
||||
assert!(fixture.refuse(Platform::Linux, &candidate).contains("FILMCRAFT_DATA_DIR"));
|
||||
fixture.env.remove("FILMCRAFT_DATA_DIR");
|
||||
fixture.env.insert("FLATPAK_ID".into(), "ai.storyteller.filmcraft".into());
|
||||
assert!(fixture.refuse(Platform::Linux, &candidate).contains("Flatpak"));
|
||||
fixture.env.insert("FLATPAK_ID".into(), "ai.storyteller.filmcraft.nightly-v1".into());
|
||||
assert!(fixture.refuse(Platform::Linux, &candidate).contains("Flatpak"));
|
||||
// The Nightly Flatpak itself is a native Nightly: its sandbox is already separate.
|
||||
fixture.env.insert("FLATPAK_ID".into(), "ai.storyteller.filmcraft.nightly".into());
|
||||
let in_the_nightly_sandbox = fixture.home().join("nightly-flatpak/profile");
|
||||
assert!(fixture.check(Platform::Linux, &in_the_nightly_sandbox).is_ok(), "the Nightly Flatpak must start");
|
||||
fixture.env.remove("FLATPAK_ID");
|
||||
fixture.env.remove("HOME");
|
||||
assert!(fixture.refuse(Platform::Linux, &candidate).contains("HOME"));
|
||||
assert!(!candidate.exists());
|
||||
}
|
||||
fn nightly_profile_validates_hardens_and_reopens_with_settings_and_folders() {
|
||||
let fixture = TempDir::new();
|
||||
let private = fixture.root.join("nightly-profile");
|
||||
let spec = app_profile_spec_with_env(|_| None);
|
||||
|
||||
#[test]
|
||||
fn failed_write_probe_never_falls_back_to_stable() {
|
||||
let fixture = Fixture::new();
|
||||
let candidate = fixture.home().join("nightly-profile");
|
||||
let refused = validate_for(Platform::Linux, &candidate, |key| fixture.get(key), Some(&fixture.exe), |_| Err(std::io::Error::other("read-only")));
|
||||
assert!(refused.unwrap_err().contains("not writable"));
|
||||
// The directory was created (and is empty), but nothing fell back to a stable location.
|
||||
assert_eq!(std::fs::read_dir(&candidate).unwrap().count(), 0);
|
||||
assert!(!fixture.home().join(".local/share/filmcraft").exists());
|
||||
}
|
||||
let confirmed = validate_and_prepare_root(&private, &spec).unwrap();
|
||||
assert_eq!(confirmed, private);
|
||||
|
||||
#[test]
|
||||
fn created_profile_is_owner_only_on_unix() {
|
||||
let fixture = Fixture::new();
|
||||
let private = fixture.check(Platform::Linux, &fixture.home().join("nightly/private")).unwrap();
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt as _;
|
||||
assert_eq!(std::fs::metadata(&private).unwrap().permissions().mode() & 0o777, 0o700);
|
||||
assert_eq!(std::fs::metadata(&confirmed).unwrap().permissions().mode() & 0o777, 0o700);
|
||||
}
|
||||
assert!(private.is_dir());
|
||||
|
||||
for name in ["preferences.json", "workspaces.json", "nightly-session.lock", "nightly-session.json"] {
|
||||
std::fs::write(confirmed.join(name), b"saved profile data").unwrap();
|
||||
}
|
||||
for name in FOLDER_ONLY_ENTRIES {
|
||||
std::fs::create_dir(confirmed.join(name)).unwrap();
|
||||
}
|
||||
assert_eq!(validate_and_prepare_root(&private, &spec).unwrap(), private);
|
||||
|
||||
for name in FOLDER_ONLY_ENTRIES {
|
||||
let path = confirmed.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 extra_forbidden_roots_refuse_overlapping_profiles() {
|
||||
let fixture = TempDir::new();
|
||||
let forbidden = fixture.root.join("forbidden-install");
|
||||
let mut spec = app_profile_spec_with_env(|_| None);
|
||||
spec.extra_forbidden_roots.push(forbidden.clone());
|
||||
|
||||
let result = validate_and_prepare_root(&forbidden.join("nightly"), &spec);
|
||||
assert!(matches!(result, Err(ProfileError::ForbiddenRootOverlap { .. })));
|
||||
assert!(!forbidden.exists());
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user