feat(nightly): wire craft-nightly for self-isolated direct launch (#10088)

* feat(nightly): wire craft-nightly for self-isolated direct launch

* fix(nightly): answer plain version before resolving profile root

* test(nightly): retain exact version and saved profile coverage
This commit is contained in:
Dylan M. Taylor authored and GitHub committed 2026-11-29 22:04:23 -05:00
1 parent 4f95a30c98
commit 970b34a727
8 files changed
+315 -909

No files matched your search

Generated
+9
View File
@@ -1816,6 +1816,14 @@ dependencies = [
"encoding_rs",
]
[[package]]
name = "craft-nightly"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=1f6c3a21f85ed96f8fd4ddd5a959d4e1edbedb24#1f6c3a21f85ed96f8fd4ddd5a959d4e1edbedb24"
dependencies = [
"winsafe",
]
[[package]]
name = "craft-pages"
version = "0.1.0"
@@ -8522,6 +8530,7 @@ dependencies = [
"chrono",
"clipboard-win",
"craft",
"craft-nightly",
"eframe",
"egui",
"egui_extras",
+2
View File
@@ -53,6 +53,8 @@ craft = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db
craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
# Nightly profile isolation, launch protocol, and security fence.
craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "1f6c3a21f85ed96f8fd4ddd5a959d4e1edbedb24" }
# internal
vectorcraft-geom = { path = "crates/geom" }
vectorcraft-color = { path = "crates/color" }
+1
View File
@@ -22,6 +22,7 @@ vectorcraft-text = { workspace = true }
# frame policy and placement store (so VectorCraft matches the rest on Linux, see #217), printing and
# the update client.
craft = { workspace = true, features = ["ui", "ui-app", "settings", "automation", "platform", "window", "dialogs", "print", "update"] }
craft-nightly = { workspace = true }
eframe = { workspace = true, features = ["clipboard", "default_fonts", "wayland", "x11"] }
egui = { workspace = true }
egui_extras = { workspace = true }
+13 -51
View File
@@ -1,30 +1,13 @@
//! Build-time channel is distinct from a launch selector. A runtime environment cannot promote a
//! stable build, and a nightly build refuses to start without its profile.
use crate::launch_profile::Profile;
use std::ffi::OsString;
//! stable build, and a nightly build self-isolates into its canonical nightly profile root (or the
//! profile root supplied by ArtCraft Launcher).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BuildFlavor {
Stable,
NightlyV1,
}
pub use craft_nightly::BuildFlavor;
pub const COMPILED: BuildFlavor = if cfg!(vectorcraft_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 VectorCraft Nightly from ArtCraft Launcher".to_string()),
(BuildFlavor::Stable, true) => Err("This is a stable VectorCraft build; nightly-v1 requires the nightly build".to_string()),
_ => Ok(()),
}
}
pub fn needs_native_error(flavor: BuildFlavor, desktop_session: bool) -> bool {
desktop_session && flavor == BuildFlavor::NightlyV1
}
/// `--version` and `-V` on their own, before any other argument is read.
pub fn version_query(args: &[OsString]) -> bool {
/// An exact plain version query, before resolving any profile or environment paths.
pub fn version_query(args: &[std::ffi::OsString]) -> bool {
matches!(args, [arg] if arg == "--version" || arg == "-V")
}
@@ -37,40 +20,19 @@ pub fn version(flavor: BuildFlavor, stable: &str) -> String {
#[cfg(test)]
mod tests {
use super::*;
use super::{BuildFlavor, version, version_query};
#[test]
fn only_a_nightly_desktop_refusal_requests_a_native_dialog() {
assert!(needs_native_error(BuildFlavor::NightlyV1, true));
assert!(!needs_native_error(BuildFlavor::NightlyV1, false));
assert!(!needs_native_error(BuildFlavor::Stable, true));
assert!(!needs_native_error(BuildFlavor::Stable, false));
}
#[test]
fn nightly_build_without_a_profile_is_refused_before_startup() {
let started = std::cell::Cell::new(false);
let result = require_profile(BuildFlavor::NightlyV1, &Profile::Stable).map(|()| started.set(true));
assert!(result.unwrap_err().contains("ArtCraft Launcher"));
assert!(!started.get());
}
#[test]
fn stable_and_nightly_flavors_accept_only_their_own_profile() {
let nightly = Profile::NightlyV1(std::path::PathBuf::from("already validated root"));
assert!(require_profile(BuildFlavor::Stable, &Profile::Stable).is_ok());
assert!(require_profile(BuildFlavor::Stable, &nightly).is_err());
assert!(require_profile(BuildFlavor::NightlyV1, &nightly).is_ok());
assert!(require_profile(BuildFlavor::NightlyV1, &Profile::Stable).is_err());
}
#[test]
fn nightly_version_query_is_unambiguous_and_never_reinterprets_file_arguments() {
assert_eq!(version(BuildFlavor::Stable, "0.24.1"), "0.24.1");
assert_eq!(version(BuildFlavor::NightlyV1, "0.24.1"), "0.24.1 (nightly-v1)");
fn plain_version_query_is_exact() {
assert!(version_query(&["--version".into()]));
assert!(version_query(&["-V".into()]));
assert!(!version_query(&["--".into(), "--version".into()]));
assert!(!version_query(&[]));
}
#[test]
fn version_labels_nightly_without_changing_stable() {
assert_eq!(version(BuildFlavor::Stable, "0.24.1"), "0.24.1");
assert_eq!(version(BuildFlavor::NightlyV1, "0.24.1"), "0.24.1 (nightly-v1)");
}
}
+82 -203
View File
@@ -1,130 +1,28 @@
//! Launcher-owned nightly-v1 bootstrap. Selected before logging, updates, fonts or saved state.
//! Stable launches retain their original arguments and directory policy.
//!
//! The protocol is `vectorcraft --launch-profile nightly-v1 --profile-root <abs> -- [files…]`: the
//! selector and the root are separate tokens, exactly once each, and everything after `--` is a file
//! even when it looks like one of them. The Launcher's version check
//! (`… --version`) is answered before the root is validated or touched.
//! Nightly-v1 bootstrap backed by [`craft_nightly`]. Selected before logging, updates, fonts or
//! saved state. Stable launches retain their original arguments and directory policy; direct
//! nightly launches self-isolate into [`craft_nightly::canonical_profile_root`], while ArtCraft
//! Launcher can supply `--launch-profile nightly-v1 --profile-root <abs> -- [args…]`.
use std::ffi::OsString;
use std::path::{Component, Path, PathBuf};
use std::sync::OnceLock;
pub const VERSION: &str = "nightly-v1";
pub use craft_nightly::NIGHTLY_V1_CONTRACT as VERSION;
use craft_nightly::{BuildFlavor, Launch, Profile, ProfileError, StartupOptions};
#[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();
static STABLE: Profile = Profile::Stable;
pub fn current() -> &'static Profile {
PROFILE.get().unwrap_or(&Profile::Stable)
craft_nightly::current().unwrap_or(&STABLE)
}
pub fn install(profile: Profile) -> Result<(), String> {
PROFILE.set(profile).map_err(|_| "the launch profile was already selected".to_string())
}
/// Recognize only the agreed literal selector/root pair before `--`. 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".to_string());
}
let value = iter.next().filter(|v| !v.is_empty()).ok_or_else(|| "the profile selector/root needs a value".to_string())?;
if value.to_string_lossy().starts_with("--") {
return Err("the profile selector/root needs a value".to_string());
}
*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".to_string());
} 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".to_string());
}
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".to_string());
}
Ok(Launch { profile: Profile::NightlyV1(root), args: std::iter::once(OsString::from("--")).chain(files).collect() })
}
(Some(_), Some(_)) => Err("unsupported launch profile (expected nightly-v1)".to_string()),
_ => Err("--launch-profile and --profile-root must be supplied together".to_string()),
}
}
/// The Launcher's version check: the selector/root pair followed by exactly `--version` (or `-V`),
/// answered like a plain version query. Only [`parse`]'s lexical checks apply; the root is never
/// validated or touched, and `-- --version` stays a file name.
pub fn version_query(args: &[OsString]) -> bool {
let Some((last, pair)) = args.split_last() else { return false };
if last != "--version" && last != "-V" {
return false;
}
let lexical = pair.iter().cloned().chain(std::iter::once(OsString::from("--"))).collect();
matches!(parse(lexical), Ok(Launch { profile: Profile::NightlyV1(_), args }) if args.len() == 1)
}
/// Validation finishes before the caller's first startup effect. Stable never calls the nightly root
/// validator, so its portable and 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::prefs_dir::profile::ensure_writable)
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())
}
/// The arguments a child of this process starts with: a nightly launch hands its profile on, so the
/// child opens the same private profile instead of being refused ("Open VectorCraft Nightly…"), and
/// `--` keeps a file whose name starts with '-' a file. Stable's child arguments are unchanged.
/// Only `single_instance` starts a child, and macOS does not build it.
/// child opens the same private profile, and `--` keeps a file whose name starts with '-' a file.
/// Stable's child arguments are unchanged. Only `single_instance` starts a child, and macOS does
/// not build it.
#[cfg(not(target_os = "macos"))]
pub fn child_args(files: &[String]) -> Vec<OsString> {
child_args_for(current(), files)
@@ -132,21 +30,24 @@ pub fn child_args(files: &[String]) -> Vec<OsString> {
#[cfg(not(target_os = "macos"))]
fn child_args_for(profile: &Profile, files: &[String]) -> Vec<OsString> {
let mut args: Vec<OsString> = match profile {
Profile::Stable => Vec::new(),
Profile::NightlyV1(root) => {
vec![OsString::from("--launch-profile"), OsString::from(VERSION), OsString::from("--profile-root"), root.clone().into_os_string()]
}
};
args.push(OsString::from("--"));
args.extend(files.iter().map(OsString::from));
args
let delimited: Vec<OsString> = std::iter::once(OsString::from("--")).chain(files.iter().map(OsString::from)).collect();
match profile {
Profile::Stable => delimited,
Profile::NightlyV1(root) => craft_nightly::launch_arguments(root, &delimited),
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::cell::Cell;
use std::ffi::OsString;
use std::path::PathBuf;
use craft_nightly::{BuildFlavor, Profile, ProfileError, StartupOptions, canonical_profile_root, parse_startup};
use super::VERSION;
#[cfg(not(target_os = "macos"))]
use super::child_args_for;
use crate::profile_root::app_profile_spec;
fn args(values: &[&str]) -> Vec<OsString> {
values.iter().map(OsString::from).collect()
@@ -156,95 +57,72 @@ mod tests {
if cfg!(windows) { r"C:\NightlyData\profiles\vectorcraft" } else { "/nightly-data/profiles/vectorcraft" }
}
fn nightly() -> Vec<OsString> {
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--"])
}
#[test]
fn stable_arguments_and_directory_policy_are_unchanged() {
fn stable_arguments_are_unchanged_and_nightly_flags_are_refused() {
let spec = app_profile_spec();
for argv in [args(&[]), args(&["--new-instance", "a.svg"]), args(&["--", "--launch-profile", "file.svg"])] {
let launch = prepare(parse(argv.clone()).unwrap(), |_| panic!("stable must never validate a nightly root")).unwrap();
assert_eq!(launch, Launch { profile: Profile::Stable, args: argv });
let launch = parse_startup(BuildFlavor::Stable, &spec, argv.clone(), &StartupOptions::default()).unwrap();
assert_eq!(launch.profile, Profile::Stable);
assert_eq!(launch.passthrough_args, argv);
}
let nightly_flags = args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--"]);
let err = parse_startup(BuildFlavor::Stable, &spec, nightly_flags, &StartupOptions::default()).unwrap_err();
assert!(matches!(err, ProfileError::NightlyFlagsInStableBuild));
}
#[test]
fn exact_version_and_root_are_parsed_without_reinterpreting_file_names() {
let mut argv = nightly();
argv.extend(args(&["--profile-root", "art with spaces.svg"]));
let launch = parse(argv).unwrap();
fn nightly_direct_launch_self_isolates_into_canonical_profile_root() {
let spec = app_profile_spec();
let expected_root = canonical_profile_root("vectorcraft").unwrap();
let empty = parse_startup(BuildFlavor::NightlyV1, &spec, Vec::new(), &StartupOptions::default()).unwrap();
assert_eq!(empty.profile, Profile::NightlyV1(expected_root.clone()));
assert!(empty.passthrough_args.is_empty());
let with_args = parse_startup(BuildFlavor::NightlyV1, &spec, args(&["--safe-mode", "art.svg"]), &StartupOptions::default()).unwrap();
assert_eq!(with_args.profile, Profile::NightlyV1(expected_root));
assert_eq!(with_args.passthrough_args, args(&["--safe-mode", "art.svg"]));
}
#[test]
fn explicit_launcher_arguments_preserve_profile_root_and_user_args() {
let spec = app_profile_spec();
let argv = args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--", "--profile-root", "art with spaces.svg"]);
let launch = parse_startup(BuildFlavor::NightlyV1, &spec, argv, &StartupOptions::default()).unwrap();
assert_eq!(launch.profile, Profile::NightlyV1(PathBuf::from(absolute())));
assert_eq!(launch.args, args(&["--", "--profile-root", "art with spaces.svg"]));
assert_eq!(launch.passthrough_args, args(&["--profile-root", "art with spaces.svg"]));
}
#[test]
fn missing_duplicate_unknown_and_conflicting_profile_arguments_are_refused() {
for argv in [
args(&["--launch-profile", VERSION]),
args(&["--profile-root", absolute()]),
args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--"]),
args(&["--launch-profile", VERSION, "--launch-profile", VERSION, "--profile-root", absolute(), "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--profile-root", absolute(), "--"]),
args(&["--launch-profile", VERSION, "--profile-root", "relative", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", "../escape", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", "", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--new-instance", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute()]),
] {
assert!(parse(argv.clone()).is_err(), "{argv:?}");
}
}
#[test]
fn the_launcher_version_check_is_a_version_query_only_in_its_exact_form() {
let pair = &["--launch-profile", VERSION, "--profile-root", absolute()];
let reversed = &["--profile-root", absolute(), "--launch-profile", VERSION];
fn version_queries_are_recognized_plain_and_via_launcher() {
let spec = app_profile_spec();
for flag in ["--version", "-V"] {
for form in [pair, reversed] {
let mut argv = args(form);
argv.push(flag.into());
assert!(version_query(&argv), "{argv:?}");
for argv in [
args(&[flag]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), flag]),
args(&["--profile-root", absolute(), "--launch-profile", VERSION, flag]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--", flag]),
] {
let launch = parse_startup(BuildFlavor::NightlyV1, &spec, argv.clone(), &StartupOptions::default()).unwrap();
assert!(launch.is_version_query(), "{argv:?}");
}
}
for argv in [
args(&["--version"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--", "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--new-instance", "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--version"]),
args(&["--version", "--launch-profile", VERSION, "--profile-root", absolute()]),
args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", "relative", "--version"]),
args(&["--launch-profile", VERSION, "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--help"]),
] {
assert!(!version_query(&argv), "{argv:?}");
}
// Outside the query the strict protocol still refuses the version flag.
assert!(parse(args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version"])).is_err());
}
#[test]
fn failed_root_validation_never_reaches_startup_or_falls_back_to_stable() {
let reached = Cell::new(false);
let result = prepare(parse(nightly()).unwrap(), |_| Err("read-only or unsafe profile".to_string())).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());
}
#[test]
fn a_joined_flag_form_is_refused() {
for joined in [format!("--launch-profile={VERSION}"), format!("--profile-root={}", absolute())] {
let argv = vec![OsString::from(joined), OsString::from("--")];
assert!(parse(argv).is_err());
fn version_and_document_arguments_are_not_a_version_only_query() {
let spec = app_profile_spec();
for flag in ["--version", "-V"] {
for argv in [
args(&[flag, "art with spaces.svg"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), flag, "art with spaces.svg"]),
args(&["--profile-root", absolute(), "--launch-profile", VERSION, flag, "art with spaces.svg"]),
] {
let launch = parse_startup(BuildFlavor::NightlyV1, &spec, argv, &StartupOptions::default()).unwrap();
assert!(!launch.is_version_query());
assert_eq!(launch.passthrough_args, args(&[flag, "art with spaces.svg"]));
}
}
}
@@ -258,6 +136,7 @@ mod tests {
#[cfg(not(target_os = "macos"))]
#[test]
fn a_nightly_child_inherits_the_selected_profile() {
let spec = app_profile_spec();
let root = PathBuf::from(absolute());
let child = child_args_for(&Profile::NightlyV1(root.clone()), &["art.svg".to_string()]);
let expected = vec![
@@ -266,12 +145,12 @@ mod tests {
OsString::from("--profile-root"),
root.into_os_string(),
OsString::from("--"),
OsString::from("--"),
OsString::from("art.svg"),
];
assert_eq!(child, expected);
// The child's own parse finds the same profile and the file list.
let launch = parse(child).unwrap();
let launch = parse_startup(BuildFlavor::NightlyV1, &spec, child, &StartupOptions::default()).unwrap();
assert!(launch.profile.is_nightly());
assert_eq!(launch.args, args(&["--", "art.svg"]));
assert_eq!(launch.passthrough_args, args(&["--", "art.svg"]));
}
}
+33 -43
View File
@@ -384,58 +384,47 @@ fn channel_name() -> &'static str {
/// Says why a nightly launch was refused, then exits 2. A window could not have shown it yet: this
/// app has no message box of its own before eframe starts (its dialogs are egui windows), so the
/// text goes to standard error, which a Launcher launch records. The desktop-session test still
/// decides whether a daily user would have seen it, for the message's wording.
/// text goes to standard error, which a Launcher launch records.
fn report_launch_profile_error(error: &str) {
eprintln!("VectorCraft launch profile: {error}");
let desktop_session = cfg!(windows)
|| cfg!(target_os = "macos")
|| (cfg!(target_os = "linux") && ["DISPLAY", "WAYLAND_DISPLAY"].into_iter().any(|key| std::env::var_os(key).is_some_and(|v| !v.is_empty())));
if build_flavor::needs_native_error(build_flavor::COMPILED, desktop_session) {
eprintln!("VectorCraft Nightly: open it from ArtCraft Launcher, which starts it in its own profile");
}
}
fn write_nightly_version() {
use std::io::Write as _;
let line = format!("VectorCraft {}\n", build_flavor::version(build_flavor::COMPILED, env!("VECTORCRAFT_BUILT_VERSION")));
let _ = std::io::stdout().write_all(line.as_bytes());
}
/// Selects the immutable launch profile before any startup service or side effect, and returns the
/// arguments the rest of `main` reads. `None` means the process ends here (`--version` answered).
fn prepare_launch() -> Option<Vec<std::ffi::OsString>> {
// The trusted Launcher protocol is decided before the logger, updates, fonts or any saved state.
// The launch profile is decided before the logger, updates, fonts or any saved state.
let argv: Vec<_> = std::env::args_os().skip(1).collect();
// A nightly answers its version before root validation, process identity, IPC or any window:
// plain `--version`/`-V`, or the Launcher's `--launch-profile nightly-v1 --profile-root <dir>
// --version`. A stable build leaves the answer to `read_command_line`, exactly as before.
if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && (build_flavor::version_query(&argv) || launch_profile::version_query(&argv))
{
use std::io::Write as _;
let line = format!("VectorCraft {}\n", build_flavor::version(build_flavor::COMPILED, env!("VECTORCRAFT_BUILT_VERSION")));
let _ = std::io::stdout().write_all(line.as_bytes());
// A plain nightly version query does not even need the OS home/data root to resolve.
if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && build_flavor::version_query(&argv) {
write_nightly_version();
return None;
}
let early = launch_profile::prepare_launch(build_flavor::COMPILED, argv).unwrap_or_else(|error| {
report_launch_profile_error(&error.to_string());
std::process::exit(2)
});
// A launcher version query also exits before process identity, IPC or any window.
// `craft_nightly::prepare_launch` skips root preparation for version queries.
// A stable build leaves the answer to `read_command_line`, exactly as before.
if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && early.is_version_query() {
write_nightly_version();
return None;
}
let early = launch_profile::parse(argv)
.and_then(|launch| {
build_flavor::require_profile(build_flavor::COMPILED, &launch.profile)?;
Ok(launch)
})
.and_then(|launch| {
launch_profile::prepare(launch, |root| {
launch_profile::validate_root(root, |key| std::env::var_os(key), std::env::current_exe().ok().as_deref())
})
})
.unwrap_or_else(|error| {
report_launch_profile_error(&error);
std::process::exit(2)
});
let nightly = early.profile.is_nightly();
let identity =
if nightly { vectorcraft_ui_egui::os_window::LaunchIdentity::NightlyV1 } else { vectorcraft_ui_egui::os_window::LaunchIdentity::Stable };
let install = launch_profile::install(early.profile).and_then(|()| {
// Every data path follows the selected profile from here on: settings, logs, recovery, the
// user's libraries, plug-ins, caches and the single-instance record.
if let Some(root) = launch_profile::current().root() {
prefs_dir::profile::install_data_root(root.to_path_buf())?;
}
vectorcraft_ui_egui::os_window::select_identity(identity)
});
// Every data path follows the selected profile from here on: settings, logs, recovery, the
// user's libraries, plug-ins, caches and the single-instance record.
let install = launch_profile::current()
.root()
.map_or(Ok(()), |root| prefs_dir::profile::install_data_root(root.to_path_buf()))
.and_then(|()| vectorcraft_ui_egui::os_window::select_identity(identity));
if let Err(error) = install {
report_launch_profile_error(&error);
std::process::exit(2);
@@ -453,11 +442,11 @@ fn prepare_launch() -> Option<Vec<std::ffi::OsString>> {
// The window's identity, not the profile, failed: main's own failure status (1).
std::process::exit(1);
}
Some(early.args)
Some(early.passthrough_args)
}
/// The arguments the rest of `main` reads: a nightly's profile tokens were consumed by
/// `prepare_launch`, so what is left is `--` and the files to open. A stable launch reads its
/// `prepare_launch`, leaving any user flags and files to open. A stable launch reads its
/// arguments exactly as it always did.
fn launch_arguments(nightly: bool, arguments: &[std::ffi::OsString]) -> Vec<String> {
if nightly { arguments.iter().map(|a| a.to_string_lossy().into_owned()).collect() } else { std::env::args().skip(1).collect() }
@@ -520,8 +509,9 @@ fn finish_pending_update(nightly: bool) {
}
fn main() -> std::process::ExitCode {
// The launch profile first: a nightly build without one is refused here, before the update
// helper, the logger, fonts or any saved state, and `--version` is answered here too.
// The launch profile first: a nightly build self-isolates or uses the Launcher's profile here,
// before the update helper, the logger, fonts or any saved state, and `--version` is answered
// here too.
let Some(arguments) = prepare_launch() else { return std::process::ExitCode::SUCCESS };
let nightly = launch_profile::current().is_nightly();
#[cfg(windows)]
+173 -610
View File
@@ -1,264 +1,17 @@
//! App-owned nightly profile fences: a profile every one of VectorCraft's data paths is redirected
//! into ([`crate::prefs_dir::profile::install_data_root`]), and that never overlaps stable's folders, a portable
//! copy or an installation.
//! App-owned nightly profile specification for [`craft_nightly`]: describes VectorCraft's stable
//! directories, forbidden environment variables, portable markers, folder-only profile entries, and
//! extra installation/package boundaries so a nightly profile never overlaps stable state.
use std::ffi::OsString;
use std::path::{Component, Path, PathBuf};
use std::path::{Path, PathBuf};
use crate::prefs_dir::profile::PORTABLE_DATA_DIR;
use craft_nightly::AppProfileSpec;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Platform {
Windows,
Linux,
Mac,
}
use crate::prefs_dir::profile::{PORTABLE_DATA_DIR, PORTABLE_MARKERS};
impl Platform {
fn current() -> Result<Self, String> {
match std::env::consts::OS {
"windows" => Ok(Self::Windows),
"linux" => Ok(Self::Linux),
"macos" => Ok(Self::Mac),
other => Err(format!("nightly-v1 is not defined for this operating system ({other})")),
}
}
const STABLE_DIR_NAMES: [&str; 2] = ["VectorCraft", "vectorcraft"];
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 an 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_else(|| "the profile root has no existing ancestor".to_string())?.to_os_string());
parent = parent.parent().ok_or_else(|| "the profile root has no existing ancestor".to_string())?;
}
Err(error) => return Err(format!("cannot inspect the profile boundary: {error}")),
}
}
let mut resolved = std::fs::canonicalize(parent).map_err(|e| format!("cannot resolve the profile boundary: {e}"))?;
for part in missing.into_iter().rev() {
resolved.push(part);
}
Ok(resolved)
}
/// A stable entry point may be a dangling link once its target is uninstalled. Its own name is still
/// the fence, so only the folder it lives in is resolved: a link that cannot be resolved would refuse
/// every launch, a valid private profile included.
fn canonical_future_entry(path: &Path) -> Result<PathBuf, String> {
let parent = path.parent().ok_or_else(|| "an entry point has no folder".to_string())?;
let name = path.file_name().ok_or_else(|| "an entry point has no name".to_string())?;
Ok(canonical_future(parent)?.join(name))
}
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_else(|| "cannot establish the installation boundary".to_string())?;
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())
}
/// Every folder a stable VectorCraft keeps user state in, on `platform`: the settings folder each
/// platform convention and the portable layout use, the eframe window state, the logs, the recovery
/// copies, the plug-ins, the caches, the install folders and the entry points. A nightly profile that
/// overlapped any of them would read, rewrite or prune stable's own state.
fn forbidden_roots(platform: Platform, env: &impl Fn(&str) -> Option<OsString>, exe: &Path) -> Result<Vec<PathBuf>, String> {
let mut roots = match platform {
Platform::Windows => {
// The settings folder (`profile.rs`) and the eframe window state, which eframe puts under
// `%APPDATA%\ai.storyteller.vectorcraft\data` (the window id).
let mut roots = ["APPDATA", "LOCALAPPDATA"]
.into_iter()
.map(|key| required_base(env, key).map(|p| p.join("VectorCraft")))
.collect::<Result<Vec<_>, _>>()?;
roots.push(required_base(env, "APPDATA")?.join("ai.storyteller.vectorcraft"));
// 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("VectorCraft"));
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("VectorCraft"));
}
}
roots
}
Platform::Linux => {
let mut roots =
[("XDG_CONFIG_HOME", ".config"), ("XDG_DATA_HOME", ".local/share"), ("XDG_CACHE_HOME", ".cache"), ("XDG_STATE_HOME", ".local/state")]
.into_iter()
.map(|(key, fallback)| xdg_base(env, key, fallback).map(|p| p.join("vectorcraft")))
.collect::<Result<Vec<_>, _>>()?;
// The eframe window state, under the lowercased window id.
roots.push(xdg_base(env, "XDG_DATA_HOME", ".local/share")?.join("ai.storyteller.vectorcraft"));
roots.push(required_base(env, "HOME")?.join(".config").join("VectorCraft"));
// The same folders at their HOME defaults: an XDG override moves this launch's own paths,
// not stable's, which stays where a launch without the override finds it.
for (directory, app) in
[(".config", "vectorcraft"), (".local/share", "vectorcraft"), (".cache", "vectorcraft"), (".local/state", "vectorcraft")]
{
roots.push(required_base(env, "HOME")?.join(directory).join(app));
}
// The stable Flatpak keeps its data in its own per-app folder.
roots.push(required_base(env, "HOME")?.join(".var/app/ai.storyteller.vectorcraft"));
roots
}
Platform::Mac => {
let home = required_base(env, "HOME")?;
let library = home.join("Library");
vec![
library.join("Application Support/VectorCraft"),
library.join("Application Support/ai.storyteller.vectorcraft"),
library.join("Caches/VectorCraft"),
library.join("Caches/ai.storyteller.vectorcraft"),
library.join("Preferences/VectorCraft"),
library.join("Preferences/ai.storyteller.vectorcraft.plist"),
library.join("Saved Application State/ai.storyteller.vectorcraft.savedState"),
home.join("Applications/VectorCraft.app"),
PathBuf::from("/Applications/VectorCraft.app"),
]
}
};
roots.push(installation_boundary(platform, exe)?);
let mut fences = roots.into_iter().map(|p| canonical_future(&p)).collect::<Result<Vec<_>, _>>()?;
if platform == Platform::Linux {
for entry in ["/usr/bin/vectorcraft", "/usr/local/bin/vectorcraft", "/opt/vectorcraft"] {
fences.push(canonical_future_entry(Path::new(entry))?);
}
}
Ok(fences)
}
fn private_subdirectory(root: &Path, name: impl AsRef<Path>, label: &str) -> Result<PathBuf, String> {
let chosen = canonical_future(&absolute(root.to_path_buf(), "the nightly profile root")?)?;
let target = chosen.join(name);
match std::fs::symlink_metadata(&target) {
Ok(metadata) if !metadata.is_dir() => {
return Err(format!("the nightly {label} must be a directory inside its selected profile"));
}
Ok(_) => {}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
Err(error) => return Err(format!("cannot inspect the nightly {label}: {error}")),
}
let child = canonical_future(&target)?;
if child == chosen || !child.starts_with(&chosen) {
return Err(format!("the nightly {label} must stay inside its selected profile"));
}
Ok(child)
}
/// Every existing entry directly in the profile (settings, logs, the user's libraries and so on) must
/// resolve inside it, so a link there cannot point Nightly's writes at another app's data.
fn entries_stay_inside(root: &Path) -> Result<(), String> {
let entries = match std::fs::read_dir(root) {
Ok(entries) => entries,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
Err(error) => return Err(format!("cannot inspect the nightly profile: {error}")),
};
for entry in entries {
let entry = entry.map_err(|e| format!("cannot inspect the nightly profile: {e}"))?;
let path = entry.path();
let metadata = std::fs::symlink_metadata(&path).map_err(|e| format!("cannot inspect the nightly profile: {e}"))?;
// Settings and session state are ordinary files, not directories. Keep the existing
// directory-boundary check for folders (including the known folder-only entries).
let folder_only = PROFILE_FOLDERS.iter().any(|name| entry.file_name().eq_ignore_ascii_case(name));
if metadata.is_file() && !folder_only {
private_regular_file(&path, &metadata)?;
} else {
private_subdirectory(root, entry.file_name(), "profile entry")?;
}
}
Ok(())
}
/// Persisted files must have their own ordinary file identity, not an alias to other data.
fn private_regular_file(path: &Path, metadata: &std::fs::Metadata) -> Result<(), String> {
#[cfg(unix)]
{
use std::os::unix::fs::MetadataExt as _;
if metadata.nlink() != 1 {
return Err("the nightly profile file must not be shared".into());
}
}
#[cfg(all(windows, feature = "wgpu"))]
{
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) || info.dwFileAttributes.has(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());
}
}
#[cfg(all(windows, not(feature = "wgpu")))]
{
use std::os::windows::fs::MetadataExt as _;
const FILE_ATTRIBUTE_DIRECTORY: u32 = 0x10;
const FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x400;
if metadata.file_attributes() & (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_REPARSE_POINT) != 0 {
return Err("the nightly profile file must not be an alias or directory".into());
}
}
let _ = (path, metadata);
Ok(())
}
const FORBIDDEN_ENV_VARS: [&str; 2] = ["VECTORCRAFT_CONFIG_DIR", "VECTORCRAFT_NO_PREFS"];
const PROFILE_FOLDERS: [&str; 18] = [
"Data Recovery",
@@ -281,397 +34,207 @@ const PROFILE_FOLDERS: [&str; 18] = [
"Libraries",
];
/// Recognise the shared portable data namespace in both the supplied and the resolved path. Up to
/// the chosen folder itself, a marker only counts beside a VectorCraft executable, so an unrelated
/// `portable.txt` higher up (in a user folder or at a drive root) does not refuse the profile.
fn is_portable_layout(path: &Path, platform: Platform) -> bool {
path.ancestors().enumerate().any(|(depth, ancestor)| {
crate::prefs_dir::profile::PORTABLE_MARKERS.iter().any(|marker| ancestor.join(marker).is_file())
&& (depth == 0 || ["vectorcraft.exe", "vectorcraft"].iter().any(|exe| ancestor.join(exe).is_file()))
}) || path.components().any(|component| match component {
Component::Normal(name) if platform.ignores_case() => name.to_string_lossy().eq_ignore_ascii_case(PORTABLE_DATA_DIR),
Component::Normal(name) => name == PORTABLE_DATA_DIR,
_ => false,
})
/// Builds VectorCraft's [`AppProfileSpec`] for [`craft_nightly`].
pub fn app_profile_spec() -> AppProfileSpec {
AppProfileSpec {
app_id: vectorcraft_ui_egui::os_window::SETTINGS_APP_ID,
display_name: vectorcraft_ui_egui::os_window::APP_NAME,
stable_dir_names: &STABLE_DIR_NAMES,
stable_package_id: vectorcraft_ui_egui::os_window::APP_ID,
nightly_package_id: vectorcraft_ui_egui::os_window::NIGHTLY_PACKAGE_ID,
profile_root_env: None,
forbidden_env_vars: &FORBIDDEN_ENV_VARS,
portable_markers: &PORTABLE_MARKERS,
folder_only_entries: &PROFILE_FOLDERS,
extra_forbidden_roots: extra_forbidden_roots(),
}
}
/// The writable hook is the app's own exclusive probe ([`crate::prefs_dir::profile::ensure_writable`]). Keeping
/// it injected lets the boundary tests exercise the real policy without starting the app.
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 non_empty_abs(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 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")?;
if env("VECTORCRAFT_CONFIG_DIR").is_some_and(|v| !v.is_empty()) {
return Err("nightly-v1 cannot be combined with VECTORCRAFT_CONFIG_DIR".to_string());
}
// The app turns preferences off whenever the variable is present, empty value included.
if env("VECTORCRAFT_NO_PREFS").is_some() {
// A run without preferences keeps nothing: its own profile would stay unused and the app
// would log to standard error only, so it is never a nightly launch.
return Err("nightly-v1 cannot inherit VECTORCRAFT_NO_PREFS".to_string());
}
let nightly_flatpak = vectorcraft_ui_egui::os_window::NIGHTLY_PACKAGE_ID;
if platform != Platform::Windows
&& let Some(id) = env("FLATPAK_ID").filter(|value| !value.is_empty())
&& id.to_string_lossy().as_ref() != nightly_flatpak
fn extra_forbidden_roots() -> Vec<PathBuf> {
extra_forbidden_roots_with(|key| std::env::var_os(key), std::env::current_exe().ok().as_deref())
}
fn extra_forbidden_roots_with(env: impl Fn(&str) -> Option<OsString>, exe: Option<&Path>) -> Vec<PathBuf> {
let mut roots = Vec::new();
#[cfg(target_os = "windows")]
{
// `packaging/linux/flatpak-bundle.sh` builds VectorCraft Nightly as its own Flatpak
// (`ai.storyteller.vectorcraft.nightly`), whose sandbox is already a private home. Any other
// instance, the stable app's included, would put this profile inside another app's tree.
return Err(format!("nightly-v1 can only run inside its own Flatpak instance ({nightly_flatpak}), not {}", id.to_string_lossy()));
if let Some(local) = non_empty_abs(&env, "LOCALAPPDATA") {
roots.push(local.join("Programs").join("ArtCraft").join("VectorCraft"));
}
for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] {
if let Some(base) = non_empty_abs(&env, key) {
roots.push(base.join("ArtCraft").join("VectorCraft"));
}
}
}
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 VectorCraft installation or its VectorCraftData settings folder".to_string());
}
let exe = absolute(exe.ok_or_else(|| "cannot establish the installation boundary".to_string())?.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".to_string());
}
// Data Recovery can read, adopt, overwrite and sweep entries: never let its alias leave the
// private profile.
private_subdirectory(&chosen, "Data Recovery", "recovery folder")?;
entries_stay_inside(&chosen)?;
let mut create = std::fs::DirBuilder::new();
create.recursive(true);
#[cfg(unix)]
#[cfg(all(unix, not(target_os = "macos")))]
{
use std::os::unix::fs::DirBuilderExt as _;
create.mode(0o700);
if let Some(home) = non_empty_abs(&env, "HOME") {
roots.push(home.join(".var").join("app").join(vectorcraft_ui_egui::os_window::APP_ID));
}
for entry in ["/usr/bin/vectorcraft", "/usr/local/bin/vectorcraft", "/opt/vectorcraft"] {
roots.push(PathBuf::from(entry));
}
}
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".to_string());
#[cfg(target_os = "macos")]
{
if let Some(home) = non_empty_abs(&env, "HOME") {
let library = home.join("Library");
roots.push(library.join("Preferences").join(format!("{}.plist", vectorcraft_ui_egui::os_window::APP_ID)));
roots.push(library.join("Saved Application State").join(format!("{}.savedState", vectorcraft_ui_egui::os_window::APP_ID)));
roots.push(home.join("Applications").join("VectorCraft.app"));
}
roots.push(PathBuf::from("/Applications/VectorCraft.app"));
}
private_subdirectory(&confirmed, "Data Recovery", "recovery folder")?;
entries_stay_inside(&confirmed)?;
writable(&confirmed).map_err(|e| format!("the nightly profile is not writable: {e}"))?;
Ok(confirmed)
if let Some(exe) = exe {
if let Some(parent) = exe.parent() {
roots.push(parent.join(PORTABLE_DATA_DIR));
}
#[cfg(target_os = "macos")]
if let Some(bundle_parent) = exe.ancestors().find(|p| p.extension().is_some_and(|ext| ext.eq_ignore_ascii_case("app"))).and_then(Path::parent)
{
roots.push(bundle_parent.join(PORTABLE_DATA_DIR));
}
}
roots
}
#[cfg(test)]
mod tests {
use super::*;
use std::cell::Cell;
use std::collections::BTreeMap;
use std::sync::atomic::{AtomicU64, Ordering};
use std::ffi::OsString;
use std::fs;
#[cfg(unix)]
use std::path::PathBuf;
/// An owned fixture tree: a home, a roaming/local app-data pair and an install folder, so the
/// fence can be checked for every platform on any host.
struct Fixture {
root: PathBuf,
env: BTreeMap<String, OsString>,
exe: PathBuf,
}
use craft_nightly::validate_and_prepare_root;
impl Fixture {
fn new() -> Self {
static NEXT: AtomicU64 = AtomicU64::new(0);
let root = loop {
let candidate =
std::env::temp_dir().join(format!("vectorcraft-profile-policy-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
match std::fs::create_dir(&candidate) {
Ok(()) => break std::fs::canonicalize(candidate).unwrap(),
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
Err(error) => panic!("cannot create owned fixture: {error}"),
}
};
let home = root.join("home");
let exe = root.join("install/vectorcraft");
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 home(&self) -> PathBuf {
PathBuf::from(self.get("HOME").unwrap())
}
fn check(&self, platform: Platform, root: &Path) -> Result<PathBuf, String> {
self.check_with(platform, root, |_| Ok(()))
}
fn check_with(&self, platform: Platform, root: &Path, writable: impl FnOnce(&Path) -> std::io::Result<()>) -> Result<PathBuf, String> {
validate_for(platform, root, |key| self.get(key), Some(&self.exe), writable)
}
}
impl Drop for Fixture {
fn drop(&mut self) {
// Only the directory this fixture created is owned for removal.
std::fs::remove_dir_all(&self.root).unwrap();
}
}
const PLATFORMS: [Platform; 3] = [Platform::Windows, Platform::Linux, Platform::Mac];
use super::{FORBIDDEN_ENV_VARS, PROFILE_FOLDERS, STABLE_DIR_NAMES, app_profile_spec, extra_forbidden_roots_with};
use crate::prefs_dir::profile::{PORTABLE_DATA_DIR, PORTABLE_MARKERS};
#[test]
fn a_private_profile_is_accepted_on_every_platform() {
let fixture = Fixture::new();
for platform in PLATFORMS {
let root = fixture.root.join(format!("nightly profiles/{platform:?}/vectorcraft"));
let resolved = fixture.check(platform, &root).unwrap();
assert!(resolved.is_dir(), "{platform:?}");
assert_eq!(resolved, std::fs::canonicalize(root).unwrap(), "{platform:?}");
std::fs::remove_dir_all(fixture.root.join("nightly profiles")).unwrap();
}
fn spec_preserves_vectorcraft_invariants() {
let spec = app_profile_spec();
assert_eq!(spec.app_id, "vectorcraft");
assert_eq!(spec.display_name, "VectorCraft");
assert_eq!(spec.stable_dir_names, &STABLE_DIR_NAMES);
assert_eq!(spec.stable_package_id, "ai.storyteller.vectorcraft");
assert_eq!(spec.nightly_package_id, "ai.storyteller.vectorcraft.nightly");
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, &PROFILE_FOLDERS);
}
#[test]
fn stable_settings_folders_are_refused_on_every_platform() {
let fixture = Fixture::new();
let stable = [
(Platform::Windows, fixture.get("APPDATA").map(|v| PathBuf::from(v).join("VectorCraft"))),
(Platform::Windows, fixture.get("APPDATA").map(|v| PathBuf::from(v).join("ai.storyteller.vectorcraft"))),
(Platform::Windows, fixture.get("LOCALAPPDATA").map(|v| PathBuf::from(v).join("VectorCraft"))),
(Platform::Windows, fixture.get("LOCALAPPDATA").map(|v| PathBuf::from(v).join("Programs/ArtCraft/VectorCraft"))),
(Platform::Linux, Some(fixture.home().join(".config/vectorcraft"))),
(Platform::Linux, Some(fixture.home().join(".local/share/vectorcraft"))),
(Platform::Linux, Some(fixture.home().join(".local/share/ai.storyteller.vectorcraft"))),
(Platform::Linux, Some(fixture.home().join(".cache/vectorcraft"))),
(Platform::Linux, Some(fixture.home().join(".var/app/ai.storyteller.vectorcraft"))),
(Platform::Mac, Some(fixture.home().join("Library/Application Support/VectorCraft"))),
(Platform::Mac, Some(fixture.home().join("Library/Application Support/ai.storyteller.vectorcraft"))),
(Platform::Mac, Some(fixture.home().join("Library/Preferences/ai.storyteller.vectorcraft.plist"))),
];
for (platform, stable) in stable {
let stable = stable.unwrap();
for candidate in [stable.clone(), stable.join("nested nightly")] {
let probed = Cell::new(false);
let result = fixture.check_with(platform, &candidate, |_| {
probed.set(true);
Ok(())
});
assert!(result.is_err(), "{platform:?} accepted {candidate:?}");
assert!(!probed.get(), "a refused root is rejected before the writable probe");
}
}
}
fn extra_forbidden_roots_fences_platform_installs_and_portable_data() {
let tmp = tempfile::tempdir().unwrap();
let home = tmp.path().join("home");
let exe = tmp.path().join("install/vectorcraft");
let roots = extra_forbidden_roots_with(
|key| match key {
"HOME" | "LOCALAPPDATA" | "ProgramFiles" => Some(home.clone().into_os_string()),
_ => None,
},
Some(&exe),
);
assert!(roots.contains(&tmp.path().join("install").join(PORTABLE_DATA_DIR)));
#[test]
fn the_install_folder_and_the_entry_points_are_refused() {
let fixture = Fixture::new();
for platform in PLATFORMS {
let install = fixture.exe.parent().unwrap();
assert!(fixture.check(platform, install).is_err(), "{platform:?}: the install folder");
assert!(fixture.check(platform, &install.join("NightlyData")).is_err(), "{platform:?}: inside the install");
}
}
#[test]
fn an_inherited_config_or_no_prefs_override_is_refused() {
let fixture = Fixture::new();
let root = fixture.root.join("nightly");
for (key, value) in [
("VECTORCRAFT_CONFIG_DIR", "/elsewhere"),
("VECTORCRAFT_NO_PREFS", "1"),
// The app turns preferences off on presence, so an empty value is a run too.
("VECTORCRAFT_NO_PREFS", ""),
("FLATPAK_ID", "ai.storyteller.vectorcraft"),
] {
for platform in PLATFORMS {
let result = validate_for(
platform,
&root,
|name| if name == key { Some(value.into()) } else { fixture.get(name) },
Some(&fixture.exe),
|_| Ok(()),
);
let refused = result.is_err();
// A Flatpak instance only keeps the stable app's sockets on native Unix packages.
assert_eq!(refused, !(key == "FLATPAK_ID" && platform == Platform::Windows), "{key} on {platform:?}");
if refused {
assert!(!root.exists(), "a refused launch creates nothing ({key} on {platform:?})");
} else if root.exists() {
// The accepted case validated the root, which creates it: start the next one clean.
std::fs::remove_dir_all(&root).expect("remove the accepted launch's root");
}
}
}
}
#[test]
fn only_the_nightly_s_own_flatpak_instance_may_carry_a_profile() {
let fixture = Fixture::new();
let root = fixture.root.join("flatpak profile");
for (id, accepted) in
[(vectorcraft_ui_egui::os_window::NIGHTLY_PACKAGE_ID, true), ("ai.storyteller.vectorcraft", false), ("io.other.App", false)]
#[cfg(target_os = "windows")]
{
let result = validate_for(
Platform::Linux,
&root,
|name| if name == "FLATPAK_ID" { Some(id.into()) } else { fixture.get(name) },
Some(&fixture.exe),
|_| Ok(()),
);
assert_eq!(result.is_ok(), accepted, "{id}");
let _ = std::fs::remove_dir_all(&root);
assert!(roots.contains(&home.join("Programs").join("ArtCraft").join("VectorCraft")));
assert!(roots.contains(&home.join("ArtCraft").join("VectorCraft")));
}
#[cfg(all(unix, not(target_os = "macos")))]
{
assert!(roots.contains(&home.join(".var/app/ai.storyteller.vectorcraft")));
assert!(roots.contains(&PathBuf::from("/usr/bin/vectorcraft")));
assert!(roots.contains(&PathBuf::from("/usr/local/bin/vectorcraft")));
assert!(roots.contains(&PathBuf::from("/opt/vectorcraft")));
}
#[cfg(target_os = "macos")]
{
assert!(roots.contains(&home.join("Library/Preferences/ai.storyteller.vectorcraft.plist")));
assert!(roots.contains(&home.join("Library/Saved Application State/ai.storyteller.vectorcraft.savedState")));
assert!(roots.contains(&home.join("Applications/VectorCraft.app")));
assert!(roots.contains(&PathBuf::from("/Applications/VectorCraft.app")));
}
}
#[test]
fn a_portable_copy_and_its_data_folder_are_refused() {
let fixture = Fixture::new();
let portable = fixture.root.join("portable copy");
let data = portable.join(crate::prefs_dir::profile::PORTABLE_DATA_DIR);
std::fs::create_dir_all(&data).unwrap();
std::fs::write(portable.join("portable.txt"), b"owned portable fixture").unwrap();
std::fs::write(data.join("config.toml"), b"stable settings must not change").unwrap();
for platform in PLATFORMS {
for candidate in [&data, &data.join("nested nightly")] {
let probed = Cell::new(false);
let result = fixture.check_with(platform, candidate, |_| {
probed.set(true);
Ok(())
});
assert!(result.is_err(), "{platform:?} accepted {candidate:?}");
assert!(!probed.get());
assert!(!data.join("nested nightly").exists());
assert_eq!(std::fs::read(data.join("config.toml")).unwrap(), b"stable settings must not change");
}
fn nightly_profile_reopens_after_saving_settings_and_enforces_folder_only_entries() {
let tmp = tempfile::tempdir().unwrap();
let private = tmp.path().join("nightly-reopen");
let mut spec = app_profile_spec();
spec.forbidden_env_vars = &[];
let canonical = validate_and_prepare_root(&private, &spec).unwrap();
assert_eq!(canonical, fs::canonicalize(&private).unwrap());
for name in ["config.toml", "instance.json", "Color Settings.json", "app.ron"] {
fs::write(canonical.join(name), b"saved profile data").unwrap();
}
for name in PROFILE_FOLDERS {
fs::create_dir(canonical.join(name)).unwrap();
}
assert_eq!(validate_and_prepare_root(&private, &spec).unwrap(), canonical);
for name in ["config.toml", "instance.json", "Color Settings.json", "app.ron"] {
assert_eq!(fs::read(canonical.join(name)).unwrap(), b"saved profile data", "{name} remains intact after reopen");
}
for name in PROFILE_FOLDERS {
let path = canonical.join(name);
fs::remove_dir(&path).unwrap();
fs::write(&path, b"not a directory").unwrap();
assert!(validate_and_prepare_root(&private, &spec).is_err(), "{name} must stay a directory");
fs::remove_file(&path).unwrap();
fs::create_dir(&path).unwrap();
}
// A merely similar name is not the portable settings folder.
let similar = fixture.root.join("VectorCraftData-backup-name/nightly");
assert!(fixture.check(Platform::Linux, &similar).is_ok());
}
#[cfg(unix)]
#[test]
fn a_link_inside_the_profile_cannot_redirect_recovery_or_a_library() {
let fixture = Fixture::new();
let root = fixture.root.join("nightly");
std::fs::create_dir_all(&root).unwrap();
let external = fixture.root.join("stable-document");
std::fs::write(&external, b"stable bytes").unwrap();
fn symlink_inside_profile_is_refused() {
let tmp = tempfile::tempdir().unwrap();
let private = tmp.path().join("nightly");
fs::create_dir_all(&private).unwrap();
let external = tmp.path().join("stable-document");
fs::write(&external, b"stable bytes").unwrap();
let mut spec = app_profile_spec();
spec.forbidden_env_vars = &[];
for name in ["Data Recovery", "Swatches"] {
let alias = root.join(name);
let alias = private.join(name);
std::os::unix::fs::symlink(&external, &alias).unwrap();
assert!(fixture.check(Platform::Linux, &root).is_err(), "{name} alias");
std::fs::remove_file(&alias).unwrap();
assert!(validate_and_prepare_root(&private, &spec).is_err(), "{name} alias");
fs::remove_file(&alias).unwrap();
}
assert_eq!(std::fs::read(&external).unwrap(), b"stable bytes");
}
#[cfg(unix)]
#[test]
fn a_dangling_link_or_a_linked_ancestor_is_refused() {
let fixture = Fixture::new();
let elsewhere = fixture.root.join("elsewhere");
std::fs::create_dir_all(&elsewhere).unwrap();
let linked = fixture.root.join("nightly");
std::os::unix::fs::symlink(&elsewhere, &linked).unwrap();
// Canonical resolution keeps a link's target: a profile reached through one is fine, but it
// is judged (and named) as its target, so nothing is written under the link.
let resolved = fixture.check(Platform::Linux, &linked).unwrap();
assert_eq!(resolved, std::fs::canonicalize(&elsewhere).unwrap());
std::fs::remove_file(&linked).unwrap();
let dangling = fixture.root.join("dangling/nightly");
std::fs::create_dir_all(dangling.parent().unwrap()).unwrap();
std::os::unix::fs::symlink(fixture.root.join("missing"), dangling.parent().unwrap().join("nightly")).unwrap();
assert!(fixture.check(Platform::Linux, &dangling).is_err());
assert_eq!(fs::read(&external).unwrap(), b"stable bytes");
}
#[test]
fn a_home_settings_folder_is_fenced_even_when_the_xdg_override_moves_elsewhere() {
let fixture = Fixture::new();
let xdg = fixture.root.join("override");
std::fs::create_dir_all(&xdg).unwrap();
let config = fixture.home().join(".config/vectorcraft");
let data = fixture.home().join(".local/share/vectorcraft");
for stable in [config.clone(), data.clone()] {
for candidate in [stable.clone(), stable.join("nested nightly")] {
let result = validate_for(
Platform::Linux,
&candidate,
|name| match name {
"XDG_CONFIG_HOME" | "XDG_DATA_HOME" => Some(xdg.clone().into_os_string()),
_ => fixture.get(name),
},
Some(&fixture.exe),
|_| Ok(()),
);
assert!(result.is_err(), "accepted {candidate:?} with the XDG folders moved to {xdg:?}");
}
}
assert!(!config.exists() && !data.exists(), "a refused root creates nothing");
}
#[cfg(unix)]
#[test]
fn a_dangling_entry_point_keeps_its_fence_instead_of_refusing_every_launch() {
let fixture = Fixture::new();
let bin = fixture.root.join("entry/bin");
std::fs::create_dir_all(&bin).unwrap();
let entry = bin.join("vectorcraft");
std::os::unix::fs::symlink(fixture.root.join("uninstalled target"), &entry).unwrap();
// The shared resolver refuses the dangling link, as a profile root must be.
assert!(canonical_future(&entry).is_err());
assert_eq!(canonical_future_entry(&entry).unwrap(), std::fs::canonicalize(&bin).unwrap().join("vectorcraft"));
}
#[test]
fn an_unwritable_profile_is_refused_after_the_probe_and_never_used() {
let fixture = Fixture::new();
let root = fixture.root.join("nightly");
let result = fixture.check_with(Platform::Linux, &root, |_| Err(std::io::Error::other("read-only")));
assert!(result.unwrap_err().contains("not writable"));
}
#[test]
fn nightly_profile_reopens_after_saving_settings_and_session_state() {
let fixture = Fixture::new();
for platform in PLATFORMS {
let private = fixture.root.join(format!("nightly-reopen-{platform:?}"));
assert_eq!(fixture.check(platform, &private).unwrap(), private);
for name in ["config.toml", "instance.json", "Color Settings.json", "app.ron"] {
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("config.toml")).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 the_platform_case_rules_are_the_file_systems_ones() {
let fixture = Fixture::new();
let upper = fixture.root.join("NIGHTLY");
assert!(fixture.check(Platform::Linux, &upper).is_ok());
let stable_mac = fixture.home().join("library/application support/vectorcraft");
assert!(fixture.check(Platform::Mac, &stable_mac).is_err(), "macOS compares folders case-insensitively");
fn non_empty_abs_ignores_empty_and_relative_values() {
let env = |key: &str| match key {
"EMPTY" => Some(OsString::new()),
"RELATIVE" => Some(OsString::from("relative/path")),
_ => None,
};
assert!(super::non_empty_abs(&env, "EMPTY").is_none());
assert!(super::non_empty_abs(&env, "RELATIVE").is_none());
assert!(super::non_empty_abs(&env, "MISSING").is_none());
}
}
+2 -2
View File
@@ -155,8 +155,8 @@ pub fn launch_with_plug_ins(files: &[String]) -> io::Result<()> {
}
/// The command [`launch_with_plug_ins`] runs: `exe -- files…`, so a file whose name starts with '-'
/// stays a file. A nightly launch hands its profile on first (`launch_profile::child_args`), or the
/// child would refuse to start without one.
/// stays a file. A nightly launch hands its profile on first (`launch_profile::child_args`), so the
/// child opens the same private profile.
fn app_with_plug_ins(exe: &Path, files: &[String]) -> std::process::Command {
let mut command = std::process::Command::new(exe);
command.args(super::launch_profile::child_args(files));