feat(nightly): wire craft-nightly for self-isolated nightly launches (#4906)

This commit is contained in:
Dylan M. Taylor authored and GitHub committed 2026-11-29 13:48:48 -05:00
1 parent 5f22c7c01c
commit be07bd69fd
7 files changed
+326 -722

No files matched your search

Generated
+9
View File
@@ -1216,6 +1216,14 @@ dependencies = [
"serde_json",
]
[[package]]
name = "craft-nightly"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=1f6c3a21f85ed96f8fd4ddd5a959d4e1edbedb24#1f6c3a21f85ed96f8fd4ddd5a959d4e1edbedb24"
dependencies = [
"winsafe",
]
[[package]]
name = "craft-odf"
version = "0.1.0"
@@ -2845,6 +2853,7 @@ version = "0.20.0"
dependencies = [
"arboard",
"chrono",
"craft-nightly",
"craft-print",
"craft-update",
"eframe",
+1
View File
@@ -53,6 +53,7 @@ craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9
craft-xls = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
craft-drawingml = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
craft-mcp-server = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "=0.1.0" }
craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "1f6c3a21f85ed96f8fd4ddd5a959d4e1edbedb24", version = "0.1.0" }
# foundation
thiserror = "2"
+2
View File
@@ -30,6 +30,8 @@ winresource = "0.1"
winit = { version = "0.30", default-features = false, features = ["x11", "wayland-csd-adwaita-notitle"] }
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
# Nightly self-isolation, launch protocol, and security fence (storytold/craft-libs).
craft-nightly = { workspace = true }
# Same craft-libs revision as the workspace's craft-update and craft-window (see the root
# Cargo.toml).
craft-print = { workspace = true }
+5 -32
View File
@@ -1,24 +1,12 @@
//! Build-time channel is distinct from a launch selector: a runtime environment cannot promote a
//! stable build, and a nightly build cannot be talked out of its profile.
use crate::launch_profile::Profile;
//! stable build, and a nightly build always stays isolated in its nightly 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!(gridcraft_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 GridCraft Nightly from ArtCraft Launcher".into()),
(BuildFlavor::Stable, true) => Err("This is a stable GridCraft build; nightly-v1 requires the nightly build".into()),
_ => Ok(()),
}
}
pub fn needs_native_error(flavor: BuildFlavor, desktop_session: bool) -> bool {
desktop_session && flavor == BuildFlavor::NightlyV1
}
@@ -36,7 +24,8 @@ pub fn version(flavor: BuildFlavor, stable: &str) -> String {
#[cfg(test)]
mod tests {
use super::*;
use super::{BuildFlavor, needs_native_error, version, version_query};
#[test]
fn only_a_nightly_desktop_refusal_requests_a_native_dialog() {
assert!(needs_native_error(BuildFlavor::NightlyV1, true));
@@ -45,22 +34,6 @@ mod tests {
assert!(!needs_native_error(BuildFlavor::Stable, false));
}
#[test]
fn nightly_build_without_a_profile_is_refused_before_startup() {
let started = std::cell::Cell::new(false);
let result = require_profile(BuildFlavor::NightlyV1, &Profile::Stable).map(|()| started.set(true));
assert!(result.unwrap_err().contains("ArtCraft Launcher"));
assert!(!started.get());
}
#[test]
fn stable_and_nightly_flavors_accept_only_their_own_profile() {
let nightly = Profile::NightlyV1(std::path::PathBuf::from("already validated root"));
assert!(require_profile(BuildFlavor::Stable, &Profile::Stable).is_ok());
assert!(require_profile(BuildFlavor::Stable, &nightly).is_err());
assert!(require_profile(BuildFlavor::NightlyV1, &nightly).is_ok());
}
#[test]
fn nightly_version_query_is_unambiguous_and_never_reinterprets_file_arguments() {
assert_eq!(version(BuildFlavor::Stable, "0.19.1"), "0.19.1");
+83 -171
View File
@@ -1,131 +1,43 @@
//! Launcher-owned nightly-v1 bootstrap, selected before logging, updates, fonts or saved state.
//! Stable launches keep their original arguments and directory policy. No environment mutation.
//!
//! The protocol is the Launcher's, as PhotoCraft's is: `--launch-profile nightly-v1` with
//! `--profile-root <absolute>` as separate tokens, then `--` and the files. Everything after `--`
//! is a file, even when it looks like a profile flag. `--version` (and the Launcher's
//! `--launch-profile nightly-v1 --profile-root <abs> --version`) is answered by `main` before any
//! of this can create a directory, open a log or start a window.
//! Nightly-v1 bootstrap backed by `craft-nightly`, selected before logging, updates, fonts or saved
//! state. Direct launches of a nightly build self-isolate into
//! `craft_nightly::canonical_profile_root("gridcraft")`, while ArtCraft Launcher may still pass
//! `--launch-profile nightly-v1 --profile-root <absolute> -- <files...>`. Stable launches keep
//! their original arguments and directory policy.
use std::ffi::OsString;
use std::path::{Component, Path, PathBuf};
use std::sync::OnceLock;
pub const VERSION: &str = "nightly-v1";
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Profile {
Stable,
NightlyV1(PathBuf),
}
impl Profile {
pub fn is_nightly(&self) -> bool {
matches!(self, Self::NightlyV1(_))
}
pub fn root(&self) -> Option<&Path> {
match self {
Self::Stable => None,
Self::NightlyV1(root) => Some(root),
}
}
}
#[derive(Debug, PartialEq, Eq)]
pub struct Launch {
pub profile: Profile,
pub args: Vec<OsString>,
}
static PROFILE: OnceLock<Profile> = OnceLock::new();
pub use craft_nightly::Profile;
/// Returns the process-wide profile installed by `craft_nightly::prepare_launch`, defaulting to
/// [`Profile::Stable`] before startup selection.
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".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".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());
}
/// Restores the `--` option terminator when `craft_nightly::parse_startup` consumed it after an
/// explicit `--launch-profile` / `--profile-root` header, so downstream argument parsing keeps
/// treating every launcher-supplied tail token (such as a file named `--control`) as a filename.
pub fn restore_launcher_separator(raw_args: &[OsString], passthrough_args: Vec<OsString>) -> Vec<OsString> {
let separator_index = raw_args.len().checked_sub(passthrough_args.len() + 1);
if let Some(index) = separator_index
&& raw_args.get(index).is_some_and(|arg| arg == "--")
{
return std::iter::once(OsString::from("--")).chain(passthrough_args).collect();
}
match (selector, root) {
(None, None) => Ok(Launch { profile: Profile::Stable, args }),
(Some(version), Some(root)) if version == VERSION => {
if !delimiter || !other.is_empty() {
return Err("nightly-v1 accepts only its selector/root followed by -- and file names".into());
}
let root = PathBuf::from(root);
if !root.is_absolute() || root.components().any(|c| matches!(c, Component::ParentDir)) {
return Err("the nightly profile root must be absolute and contain no parent traversal".into());
}
Ok(Launch { profile: Profile::NightlyV1(root), args: std::iter::once(OsString::from("--")).chain(files).collect() })
}
(Some(_), Some(_)) => Err("unsupported launch profile (expected nightly-v1)".into()),
_ => Err("--launch-profile and --profile-root must be supplied together".into()),
}
}
/// The Launcher's version check: the selector/root pair followed by exactly `--version` (or `-V`),
/// answered like a plain version query. Only [`parse`]'s lexical checks apply; the root is never
/// validated or touched, and `-- --version` stays a file name.
pub fn version_query(args: &[OsString]) -> bool {
let Some((last, pair)) = args.split_last() else { return false };
if last != "--version" && last != "-V" {
return false;
}
let lexical = pair.iter().cloned().chain(std::iter::once(OsString::from("--"))).collect();
matches!(parse(lexical), Ok(Launch { profile: Profile::NightlyV1(_), args }) if args.len() == 1)
}
/// Validation finishes before the caller's first startup effect. Stable never calls the nightly
/// root validator, so its old 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)
passthrough_args
}
#[cfg(test)]
mod tests {
use super::*;
use std::cell::Cell;
use std::ffi::OsString;
use std::path::{Path, PathBuf};
use craft_nightly::{
BuildFlavor, NIGHTLY_V1_CONTRACT, Profile, ProfileError, StartupOptions, canonical_profile_root, launch_arguments, parse_startup,
};
use super::restore_launcher_separator;
use crate::profile_root;
fn args(values: &[&str]) -> Vec<OsString> {
values.iter().map(OsString::from).collect()
@@ -136,88 +48,88 @@ mod tests {
}
fn nightly() -> Vec<OsString> {
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--"])
launch_arguments(Path::new(absolute()), &[])
}
#[test]
fn stable_arguments_and_directory_policy_are_unchanged() {
let spec = profile_root::app_spec();
for argv in [args(&[]), args(&["sales.xlsx"]), args(&["--control", "7979"]), args(&["--", "--launch-profile", "book.xlsx"])] {
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.iter().cloned(), &StartupOptions::default()).unwrap();
assert_eq!(launch.profile, Profile::Stable);
assert_eq!(restore_launcher_separator(&argv, launch.passthrough_args), argv);
}
}
#[test]
fn direct_nightly_launch_self_isolates_into_canonical_root_and_preserves_args() {
let spec = profile_root::app_spec();
let expected_root = canonical_profile_root("gridcraft").expect("canonical root");
let argv = args(&["sales.xlsx", "--sample", "budget"]);
let launch = parse_startup(BuildFlavor::NightlyV1, &spec, argv.iter().cloned(), &StartupOptions::default()).unwrap();
assert_eq!(launch.profile, Profile::NightlyV1(expected_root));
assert!(launch.profile.is_nightly());
assert_eq!(restore_launcher_separator(&argv, launch.passthrough_args), argv);
}
#[test]
fn exact_selector_and_root_are_parsed_without_reinterpreting_file_names() {
let spec = profile_root::app_spec();
let mut argv = nightly();
argv.extend(args(&["--profile-root", "a file with spaces.xlsx", "--version"]));
let launch = parse(argv).unwrap();
let launch = parse_startup(BuildFlavor::NightlyV1, &spec, argv.iter().cloned(), &StartupOptions::default()).unwrap();
assert_eq!(launch.profile, Profile::NightlyV1(PathBuf::from(absolute())));
assert_eq!(launch.args, args(&["--", "--profile-root", "a file with spaces.xlsx", "--version"]));
assert_eq!(
restore_launcher_separator(&argv, launch.passthrough_args),
args(&["--", "--profile-root", "a file with spaces.xlsx", "--version"])
);
}
#[test]
fn missing_duplicate_unknown_and_conflicting_profile_arguments_are_refused() {
fn stable_build_refuses_nightly_launch_flags() {
let spec = profile_root::app_spec();
let result = parse_startup(BuildFlavor::Stable, &spec, nightly(), &StartupOptions::default());
assert!(matches!(result, Err(ProfileError::NightlyFlagsInStableBuild)));
}
#[test]
fn missing_duplicate_unknown_and_misplaced_profile_arguments_are_refused() {
let spec = profile_root::app_spec();
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", "/one/../two", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", "", "--"]),
args(&["--launch-profile=nightly-v1", "--profile-root", absolute(), "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "sales.xlsx", "--"]),
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(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "sales.xlsx", "--profile-root", absolute()]),
args(&["sales.xlsx", "--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute()]),
] {
assert!(parse(argv.clone()).is_err(), "{argv:?}");
assert!(parse_startup(BuildFlavor::NightlyV1, &spec, argv.clone(), &StartupOptions::default()).is_err(), "{argv:?}");
}
assert!(parse(args(&["--launch-profile", "--profile-root", absolute(), "--"])).is_err(), "a flag is not a value");
}
#[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 launcher_version_queries_are_recognized_without_touching_the_profile() {
let spec = profile_root::app_spec();
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(), "--control", "7979", "--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(&["--profile-root", absolute(), "--launch-profile", NIGHTLY_V1_CONTRACT, "-V"]),
launch_arguments(Path::new(absolute()), &args(&["--version"])),
launch_arguments(Path::new(absolute()), &args(&["-V"])),
] {
assert!(!version_query(&argv), "{argv:?}");
let launch = parse_startup(BuildFlavor::NightlyV1, &spec, argv.clone(), &StartupOptions::default()).unwrap();
assert!(launch.is_version_query(), "{argv:?}");
}
for argv in [
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--help"]),
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--control", "7979", "--version"]),
launch_arguments(Path::new(absolute()), &args(&["sales.xlsx", "--version"])),
] {
let launch = parse_startup(BuildFlavor::NightlyV1, &spec, argv.clone(), &StartupOptions::default()).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());
}
#[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());
}
}
+40 -29
View File
@@ -304,46 +304,47 @@ fn report_launch_profile_error(error: &str) {
fn prepare_launch() -> Option<Vec<std::ffi::OsString>> {
let argv: Vec<std::ffi::OsString> = std::env::args_os().skip(1).collect();
let nightly_build = build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1;
// Plain `--version`, or the Launcher's `--launch-profile nightly-v1 --profile-root <dir>
// --version`: answered before root validation, process identity, IPC or any window (a dialog
// here would hang a headless runner and fail a Linux build).
if nightly_build && (build_flavor::version_query(&argv) || launch_profile::version_query(&argv)) {
// Plain `--version` / `-V` on a nightly build is answered before any profile resolution,
// process identity, IPC, or window (a dialog here would hang a headless runner and fail a
// Linux build, and `--version` must still work when HOME / LOCALAPPDATA is unset).
if nightly_build && build_flavor::version_query(&argv) {
use std::io::Write as _;
let version = build_flavor::version(build_flavor::COMPILED, env!("GRIDCRAFT_BUILT_VERSION"));
let _ = writeln!(std::io::stdout(), "{} {version}", gridcraft_ui_egui::channel::name_for(gridcraft_ui_egui::channel::Channel::Stable));
return None;
}
let early = launch_profile::parse(argv)
.and_then(|launch| {
build_flavor::require_profile(build_flavor::COMPILED, &launch.profile)?;
initialize_nightly_process_identity().map_err(|error| error.to_string())?;
Ok(launch)
})
.and_then(|launch| {
launch_profile::prepare(launch, |root| {
launch_profile::validate_root(root, |key| std::env::var_os(key), std::env::current_exe().ok().as_deref())
})
})
let spec = profile_root::app_spec();
let launch = craft_nightly::prepare_launch(build_flavor::COMPILED, &spec, argv.iter().cloned(), &craft_nightly::StartupOptions::default())
.unwrap_or_else(|error| {
report_launch_profile_error(&error);
report_launch_profile_error(&error.to_string());
std::process::exit(2)
});
// Launcher's `--launch-profile nightly-v1 --profile-root <dir> [--] --version`:
// `craft_nightly::prepare_launch` performs no filesystem preparation and installs no profile.
if nightly_build && launch.is_version_query() {
use std::io::Write as _;
let version = build_flavor::version(build_flavor::COMPILED, env!("GRIDCRAFT_BUILT_VERSION"));
let _ = writeln!(std::io::stdout(), "{} {version}", gridcraft_ui_egui::channel::name_for(gridcraft_ui_egui::channel::Channel::Stable));
return None;
}
if let Err(error) = initialize_nightly_process_identity() {
report_launch_profile_error(&error.to_string());
std::process::exit(2);
}
let channel =
if early.profile.is_nightly() { gridcraft_ui_egui::channel::Channel::NightlyV1 } else { gridcraft_ui_egui::channel::Channel::Stable };
if let Err(error) =
launch_profile::install(early.profile).and_then(|()| gridcraft_ui_egui::channel::select(channel, env!("GRIDCRAFT_BUILT_VERSION")))
{
if launch.profile.is_nightly() { gridcraft_ui_egui::channel::Channel::NightlyV1 } else { gridcraft_ui_egui::channel::Channel::Stable };
if let Err(error) = gridcraft_ui_egui::channel::select(channel, env!("GRIDCRAFT_BUILT_VERSION")) {
report_launch_profile_error(&error);
std::process::exit(2);
}
Some(early.args)
Some(launch_profile::restore_launcher_separator(&argv, launch.passthrough_args))
}
/// The app's own command line, once the launch profile's tokens are gone: `--control`,
/// `--control-token`, `--sample` and the files to open. `--` ends the options, and everything after
/// it is a file, even a name that reads like one — that is how the Launcher hands a nightly its
/// documents (`launch_profile::parse` puts the separator first), so the separator itself is never
/// opened as a file.
/// documents (`launch_profile::restore_launcher_separator` preserves the separator first), so the
/// separator itself is never opened as a file.
#[derive(Debug, Default, PartialEq)]
struct DesktopArgs {
control_port: Option<u16>,
@@ -660,8 +661,9 @@ mod launch_separator_tests {
use crate::build_flavor::BuildFlavor;
/// The profile root a Launcher run is started with: absolute for the platform the test runs on.
/// `launch_profile::parse` refuses a root that is relative there, and a POSIX path has no drive
/// or UNC prefix, so it is not absolute on Windows - where CI runs these tests too.
/// `craft_nightly::validate_and_prepare_root` refuses a root that is relative there, and a
/// POSIX path has no drive or UNC prefix, so it is not absolute on Windows - where CI runs
/// these tests too.
fn launcher_root() -> &'static str {
if cfg!(windows) { r"C:\NightlyData\profiles\gridcraft" } else { "/nightly-data/profiles/gridcraft" }
}
@@ -671,15 +673,24 @@ mod launch_separator_tests {
let mut argv: Vec<std::ffi::OsString> =
["--launch-profile", "nightly-v1", "--profile-root", launcher_root(), "--"].iter().map(std::ffi::OsString::from).collect();
argv.extend(tail.iter().map(std::ffi::OsString::from));
launch_profile::parse(argv).unwrap().args.iter().map(|a| a.to_string_lossy().into_owned()).collect()
let launch = craft_nightly::parse_startup(
BuildFlavor::NightlyV1,
&profile_root::app_spec(),
argv.iter().cloned(),
&craft_nightly::StartupOptions::default(),
)
.unwrap();
launch_profile::restore_launcher_separator(&argv, launch.passthrough_args).iter().map(|a| a.to_string_lossy().into_owned()).collect()
}
#[test]
fn the_other_platforms_root_spelling_is_refused_as_relative() {
let foreign = if cfg!(windows) { "/nightly-data/profiles/gridcraft" } else { r"C:\NightlyData\profiles\gridcraft" };
let argv: Vec<std::ffi::OsString> =
["--launch-profile", "nightly-v1", "--profile-root", foreign, "--"].iter().map(std::ffi::OsString::from).collect();
assert!(launch_profile::parse(argv).is_err(), "a root that is not absolute on this platform must be refused");
let result = craft_nightly::validate_and_prepare_root(std::path::Path::new(foreign), &profile_root::app_spec());
assert!(
matches!(result, Err(craft_nightly::ProfileError::RelativeProfileRoot(_))),
"a root that is not absolute on this platform must be refused"
);
}
#[test]
+186 -490
View File
@@ -1,37 +1,91 @@
//! GridCraft's nightly profile fences: no stable fallback, no migration and no change to the
//! process environment. Every stable place a GridCraft build keeps user state is refused as a
//! nightly root, in both directions, so the two channels can never share a file.
//! GridCraft's nightly profile specification and control-directory boundary, backed by
//! `craft-nightly`. Every stable place a GridCraft build keeps user state or installs is fenced off
//! so the two channels can never share a file.
use std::ffi::OsString;
use std::path::{Component, Path, PathBuf};
/// The folder the Windows build writes its control-channel token to (`gridcraft_mcp`).
const WINDOWS_TOKEN_DIR: &str = ".gridcraft";
use craft_nightly::AppProfileSpec;
/// The subfolder of the profile the nightly control-channel token goes to, when one runs.
pub const CONTROL_DIR: &str = "Control";
const PROFILE_FOLDERS: [&str; 2] = [CONTROL_DIR, "logs"];
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Platform {
Windows,
Linux,
Mac,
/// Returns GridCraft's `craft-nightly` isolation specification, preserving every stable data,
/// token, Flatpak, and installer boundary.
pub fn app_spec() -> AppProfileSpec {
AppProfileSpec {
app_id: "gridcraft",
display_name: "GridCraft",
stable_dir_names: &["gridcraft", "GridCraft"],
stable_package_id: gridcraft_ui_egui::channel::APP_ID,
nightly_package_id: gridcraft_ui_egui::channel::NIGHTLY_PACKAGE_ID,
profile_root_env: None,
forbidden_env_vars: &[],
portable_markers: &[],
folder_only_entries: &PROFILE_FOLDERS,
extra_forbidden_roots: extra_forbidden_roots(|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),
// FreeBSD, the BSDs and anything else have no nightly channel.
_ => Err("nightly-v1 is not defined for this operating system".into()),
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);
if path.is_absolute() && !path.components().any(|c| matches!(c, Component::ParentDir)) { Some(path) } else { None }
}
/// Platform-specific stable install, token, Flatpak, and macOS state paths beyond the standard OS
/// config/data/cache directories already fenced by `craft-nightly`.
fn extra_forbidden_roots(env: impl Fn(&str) -> Option<OsString>) -> Vec<PathBuf> {
#[cfg(target_os = "windows")]
{
// `gridcraft_mcp`'s control-channel token folder and both MSI install folders
// (`install-policy.wxi`).
let mut roots = Vec::new();
if let Some(local) = non_empty_abs(&env, "LOCALAPPDATA") {
roots.push(local.join("Programs").join("ArtCraft").join("GridCraft"));
}
if let Some(profile) = non_empty_abs(&env, "USERPROFILE") {
roots.push(profile.join(".gridcraft"));
}
for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] {
if let Some(base) = non_empty_abs(&env, key) {
roots.push(base.join("ArtCraft").join("GridCraft"));
}
}
roots
}
fn ignores_case(self) -> bool {
self != Self::Linux
#[cfg(all(unix, not(target_os = "macos")))]
{
let mut roots: Vec<PathBuf> = ["/usr/bin/gridcraft", "/usr/local/bin/gridcraft", "/opt/gridcraft"].into_iter().map(PathBuf::from).collect();
// The stable Flatpak keeps its data in its own per-app folder.
if let Some(home) = non_empty_abs(&env, "HOME") {
roots.push(home.join(".var/app/ai.storyteller.gridcraft"));
}
roots
}
#[cfg(target_os = "macos")]
{
let mut roots = vec![PathBuf::from("/Applications/GridCraft.app")];
if let Some(home) = non_empty_abs(&env, "HOME") {
let library = home.join("Library");
roots.push(library.join("Preferences/ai.storyteller.gridcraft.plist"));
roots.push(library.join("Saved Application State/ai.storyteller.gridcraft.savedState"));
roots.push(home.join("Applications/GridCraft.app"));
}
roots
}
#[cfg(not(any(unix, target_os = "windows")))]
{
let _ = env;
Vec::new()
}
}
@@ -42,18 +96,6 @@ fn absolute(path: PathBuf, label: &str) -> Result<PathBuf, String> {
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> {
@@ -76,88 +118,12 @@ fn canonical_future(path: &Path) -> Result<PathBuf, String> {
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 => {
// `apps/gridcraft/src/main.rs` (ui.json, prefs.json and logs) and `gridcraft_mcp`'s
// token folder, plus both MSI install folders (`install-policy.wxi`).
let mut roots = ["APPDATA", "LOCALAPPDATA"]
.into_iter()
.map(|key| required_base(env, key).map(|p| p.join("GridCraft")))
.collect::<Result<Vec<_>, _>>()?;
roots.push(required_base(env, "LOCALAPPDATA")?.join("Programs").join("ArtCraft").join("GridCraft"));
roots.push(required_base(env, "USERPROFILE")?.join(WINDOWS_TOKEN_DIR));
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("GridCraft"));
}
}
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("gridcraft")))
.collect::<Result<Vec<_>, _>>()?;
roots.extend(["/usr/bin/gridcraft", "/usr/local/bin/gridcraft", "/opt/gridcraft"].map(PathBuf::from));
// The stable Flatpak keeps its data in its own per-app folder.
roots.push(required_base(env, "HOME")?.join(".var/app/ai.storyteller.gridcraft"));
// `gridcraft_mcp`'s token folder when no XDG runtime directory is set.
roots.push(required_base(env, "HOME")?.join(".cache").join("gridcraft"));
roots
}
Platform::Mac => {
let home = required_base(env, "HOME")?;
let library = home.join("Library");
vec![
library.join("Application Support/GridCraft"),
library.join("Caches/GridCraft"),
library.join("Caches/ai.storyteller.gridcraft"),
library.join("Preferences/GridCraft"),
library.join("Preferences/ai.storyteller.gridcraft.plist"),
library.join("Saved Application State/ai.storyteller.gridcraft.savedState"),
home.join("Applications/GridCraft.app"),
PathBuf::from("/Applications/GridCraft.app"),
]
}
};
roots.push(installation_boundary(platform, exe)?);
roots.into_iter().map(|p| canonical_future(&p)).collect()
}
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 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"));
}
// A regular file in a folder's place is not a folder: the readers and sweepers that follow would
// fail halfway, so refuse it while the profile is still being validated.
match std::fs::symlink_metadata(&child) {
Ok(metadata) if !metadata.file_type().is_dir() => {
return Err(format!("the nightly {label} must be a directory, not a file or an alias"));
@@ -169,442 +135,172 @@ fn private_subdirectory(root: &Path, name: impl AsRef<Path>, label: &str) -> Res
Ok(child)
}
/// Every existing entry directly in the profile (settings, logs and so on) must resolve inside it,
/// so a link there cannot point Nightly's writes at the stable app's data.
fn entries_stay_inside(root: &Path) -> Result<(), String> {
let entries = match std::fs::read_dir(root) {
Ok(entries) => entries,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
Err(error) => return Err(format!("cannot inspect the nightly profile: {error}")),
};
for entry in entries {
let entry = entry.map_err(|e| format!("cannot inspect the nightly profile: {e}"))?;
let path = entry.path();
let metadata = std::fs::symlink_metadata(&path).map_err(|e| format!("cannot inspect the nightly profile: {e}"))?;
// Settings and session state are ordinary files, not directories. Keep the existing
// directory-boundary check for folders (including the known folder-only entries).
let folder_only = PROFILE_FOLDERS.iter().any(|name| entry.file_name().eq_ignore_ascii_case(name));
if metadata.is_file() && !folder_only {
private_regular_file(&path, &metadata)?;
} else {
private_subdirectory(root, entry.file_name(), "profile entry")?;
}
}
Ok(())
}
/// Persisted files must have their own ordinary file identity, not an alias to other data.
fn private_regular_file(path: &Path, metadata: &std::fs::Metadata) -> Result<(), String> {
#[cfg(unix)]
{
use std::os::unix::fs::MetadataExt as _;
if metadata.nlink() != 1 {
return Err("the nightly profile file must not be shared".into());
}
}
#[cfg(windows)]
{
use winsafe::{HFILE, co};
let (file, _) = HFILE::CreateFile(
path.to_str().ok_or("the nightly profile file path is not textual")?,
co::GENERIC::default(),
Some(co::FILE_SHARE::READ | co::FILE_SHARE::WRITE | co::FILE_SHARE::DELETE),
None,
co::DISPOSITION::OPEN_EXISTING,
co::FILE_ATTRIBUTE::NORMAL,
Some(co::FILE_FLAG::OPEN_REPARSE_POINT),
None,
None,
)
.map_err(|e| e.to_string())?;
let info = file.GetFileInformationByHandle().map_err(|e| e.to_string())?;
if info.dwFileAttributes.has(co::FILE_ATTRIBUTE::REPARSE_POINT | co::FILE_ATTRIBUTE::DIRECTORY) {
return Err("the nightly profile file must not be an alias or directory".into());
}
if info.nNumberOfLinks != 1 {
return Err("the nightly profile file must not be shared".into());
}
}
let _ = (path, metadata);
Ok(())
}
/// Where a nightly control-channel token goes: `<profile>/Control`, created lazily by
/// `gridcraft_mcp` if a control server is ever started. Resolving it never creates anything.
pub fn control_directory(root: &Path) -> Result<PathBuf, String> {
private_subdirectory(root, CONTROL_DIR, "control folder")
}
/// The app's own exclusive writable probe: create a file inside the profile, then remove it.
pub fn ensure_writable(root: &Path) -> std::io::Result<()> {
static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
// A crashed launch can leave a probe with this name behind: take the next one instead of
// failing, and remove only the file this call created, never someone else's.
loop {
let probe =
root.join(format!(".gridcraft-nightly-writable-{}-{}", std::process::id(), NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)));
match std::fs::OpenOptions::new().write(true).create_new(true).open(&probe) {
Ok(_) => return std::fs::remove_file(&probe),
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
Err(error) => return Err(error),
}
}
}
/// The writable hook is injected so filesystem boundary tests exercise the real policy without
/// starting the app or changing global state.
pub fn validate(
root: &Path,
env: impl Fn(&str) -> Option<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")?;
if platform != Platform::Windows
&& let Some(id) = env("FLATPAK_ID").filter(|value| !value.is_empty())
&& id.to_string_lossy().as_ref() != gridcraft_ui_egui::channel::NIGHTLY_PACKAGE_ID
{
// `packaging/linux/flatpak-bundle.sh` builds GridCraft Nightly as its own Flatpak
// (`ai.storyteller.gridcraft.nightly`), whose sandbox is already a private home, so that one
// instance may carry a profile. Any other, the stable app's included, could point it at
// another installation's tree; these rows are otherwise native tar/app-bundle launches.
return Err(format!(
"nightly-v1 can only run inside its own Flatpak instance ({}), not {}",
gridcraft_ui_egui::channel::NIGHTLY_PACKAGE_ID,
id.to_string_lossy()
));
}
let chosen = canonical_future(root)?;
let exe = absolute(exe.ok_or("cannot establish the installation boundary")?.to_path_buf(), "the executable")?;
let forbidden = forbidden_roots(platform, &env, &exe)?;
if forbidden.iter().any(|stable| overlaps(&chosen, stable, platform)) {
return Err("the nightly root must not overlap stable data or an installation".into());
}
// Existing aliases under the profile must not redirect a subfolder elsewhere.
control_directory(&chosen)?;
entries_stay_inside(&chosen)?;
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());
}
control_directory(&confirmed)?;
entries_stay_inside(&confirmed)?;
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::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
struct Fixture {
use craft_nightly::{ProfileError, validate_and_prepare_root};
use super::{CONTROL_DIR, PROFILE_FOLDERS, app_spec, control_directory, extra_forbidden_roots};
struct TempDir {
root: PathBuf,
env: BTreeMap<String, OsString>,
exe: PathBuf,
}
impl Fixture {
fn new() -> Self {
impl TempDir {
fn new(label: &str) -> Self {
static NEXT: AtomicU64 = AtomicU64::new(0);
let root = loop {
let candidate =
std::env::temp_dir().join(format!("gridcraft-profile-policy-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
std::env::temp_dir().join(format!("gridcraft-profile-{label}-{}-{}", 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/gridcraft");
std::fs::create_dir_all(&home).unwrap();
std::fs::create_dir_all(exe.parent().unwrap()).unwrap();
std::fs::write(&exe, b"fixture executable, never run").unwrap();
let env = [("HOME", home.clone()), ("USERPROFILE", home), ("APPDATA", root.join("roaming")), ("LOCALAPPDATA", root.join("local"))]
.into_iter()
.map(|(key, value)| (key.into(), value.into_os_string()))
.collect();
Self { root, env, exe }
Self { root }
}
fn get(&self, key: &str) -> Option<OsString> {
self.env.get(key).cloned()
}
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)
}
fn home(&self) -> PathBuf {
PathBuf::from(self.get("HOME").unwrap())
fn path(&self) -> &Path {
&self.root
}
}
impl Drop for Fixture {
impl Drop for TempDir {
fn drop(&mut self) {
// Only the directory successfully created by this fixture is owned for removal.
std::fs::remove_dir_all(&self.root).unwrap();
let _ = std::fs::remove_dir_all(&self.root);
}
}
#[test]
fn every_stable_data_root_is_refused_on_its_own_platform() {
let mut fixture = Fixture::new();
// Windows: APPDATA\GridCraft (settings and logs), LOCALAPPDATA\GridCraft, the per-user
// and per-machine install folders and the control-token folder.
for key in ["APPDATA", "LOCALAPPDATA"] {
let stable = PathBuf::from(fixture.get(key).unwrap()).join("GridCraft");
for candidate in [stable.clone(), stable.join("nightly")] {
assert!(fixture.check(Platform::Windows, &candidate).unwrap_err().contains("overlap"), "{key}");
}
assert!(!stable.exists());
fn app_spec_preserves_gridcraft_identifiers_and_folder_entries() {
let spec = app_spec();
assert_eq!(spec.app_id, "gridcraft");
assert_eq!(spec.display_name, "GridCraft");
assert_eq!(spec.stable_dir_names, &["gridcraft", "GridCraft"]);
assert_eq!(spec.stable_package_id, gridcraft_ui_egui::channel::APP_ID);
assert_eq!(spec.nightly_package_id, gridcraft_ui_egui::channel::NIGHTLY_PACKAGE_ID);
assert_eq!(spec.profile_root_env, None);
assert!(spec.forbidden_env_vars.is_empty());
assert!(spec.portable_markers.is_empty());
assert_eq!(spec.folder_only_entries, &PROFILE_FOLDERS);
}
#[test]
fn extra_forbidden_roots_include_platform_install_and_state_paths() {
let tmp = TempDir::new("extra-roots");
let home = tmp.path().join("home");
let local = tmp.path().join("local");
let program_files = tmp.path().join("program-files");
let env: BTreeMap<&str, OsString> = [
("HOME", home.clone().into_os_string()),
("USERPROFILE", home.clone().into_os_string()),
("LOCALAPPDATA", local.clone().into_os_string()),
("ProgramFiles", program_files.clone().into_os_string()),
]
.into_iter()
.collect();
let roots = extra_forbidden_roots(|key| env.get(key).cloned());
#[cfg(target_os = "windows")]
{
assert!(roots.contains(&local.join("Programs").join("ArtCraft").join("GridCraft")));
assert!(roots.contains(&home.join(".gridcraft")));
assert!(roots.contains(&program_files.join("ArtCraft").join("GridCraft")));
}
assert!(
fixture
.check(Platform::Windows, &PathBuf::from(fixture.get("LOCALAPPDATA").unwrap()).join("Programs/ArtCraft/GridCraft/nightly"))
.is_err()
);
assert!(fixture.check(Platform::Windows, &fixture.home().join(".gridcraft/nightly")).is_err());
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());
assert!(fixture.check(Platform::Windows, &base.join("ArtCraft/GridCraft/nightly")).is_err(), "{key}");
assert!(!base.join("ArtCraft/GridCraft").exists());
#[cfg(all(unix, not(target_os = "macos")))]
{
assert!(roots.contains(&PathBuf::from("/usr/bin/gridcraft")));
assert!(roots.contains(&PathBuf::from("/usr/local/bin/gridcraft")));
assert!(roots.contains(&PathBuf::from("/opt/gridcraft")));
assert!(roots.contains(&home.join(".var/app/ai.storyteller.gridcraft")));
}
// Linux: the four XDG folders, then the stable Flatpak row and the token folder.
for key in ["XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME"] {
fixture.env.insert(key.into(), fixture.root.join(key).into_os_string());
#[cfg(target_os = "macos")]
{
assert!(roots.contains(&home.join("Library/Preferences/ai.storyteller.gridcraft.plist")));
assert!(roots.contains(&home.join("Library/Saved Application State/ai.storyteller.gridcraft.savedState")));
assert!(roots.contains(&home.join("Applications/GridCraft.app")));
assert!(roots.contains(&PathBuf::from("/Applications/GridCraft.app")));
}
for key in ["XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME"] {
let stable = PathBuf::from(fixture.get(key).unwrap()).join("gridcraft");
std::fs::create_dir_all(&stable).unwrap();
std::fs::write(stable.join("stable-sentinel"), b"stable bytes").unwrap();
for candidate in [stable.clone(), stable.join("nightly"), stable.parent().unwrap().to_path_buf()] {
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("overlap"), "{key}");
}
assert_eq!(std::fs::read(stable.join("stable-sentinel")).unwrap(), b"stable bytes");
let _ = (&local, &program_files);
}
#[test]
fn nightly_profile_reopens_after_saving_settings_and_enforces_folder_entries() {
let tmp = TempDir::new("reopen");
let private = tmp.path().join("nightly-profile");
let spec = app_spec();
assert_eq!(validate_and_prepare_root(&private, &spec).unwrap(), private);
for name in ["ui.json", "prefs.json", "nightly-session.lock", "nightly-session.json"] {
std::fs::write(private.join(name), b"saved profile data").unwrap();
}
assert!(fixture.check(Platform::Linux, &fixture.home().join(".var/app/ai.storyteller.gridcraft/data")).is_err());
assert!(fixture.check(Platform::Linux, &fixture.home().join(".var/app/ai.storyteller.launcher/nightly")).is_ok());
assert!(fixture.check(Platform::Linux, Path::new("/usr/bin/gridcraft/../gridcraft-nightly")).is_err(), "parent traversal is refused");
// macOS: the four Library rows and the bundle itself.
for suffix in [
"Application Support/GridCraft",
"Caches/GridCraft",
"Preferences/GridCraft",
"Saved Application State/ai.storyteller.gridcraft.savedState",
] {
assert!(fixture.check(Platform::Mac, &fixture.home().join("Library").join(suffix).join("nightly")).is_err(), "{suffix}");
for name in PROFILE_FOLDERS {
std::fs::create_dir(private.join(name)).unwrap();
}
assert_eq!(validate_and_prepare_root(&private, &spec).unwrap(), private);
assert_eq!(std::fs::read(private.join("ui.json")).unwrap(), b"saved profile data");
for name in PROFILE_FOLDERS {
let path = private.join(name);
std::fs::remove_dir(&path).unwrap();
std::fs::write(&path, b"not a directory").unwrap();
assert!(
matches!(validate_and_prepare_root(&private, &spec), Err(ProfileError::ExpectedDirectoryEntry(_))),
"{name} must stay a directory"
);
std::fs::remove_file(&path).unwrap();
std::fs::create_dir(&path).unwrap();
}
}
#[test]
fn the_launcher_profile_row_is_accepted_on_every_platform() {
let fixture = Fixture::new();
let data = fixture.root.join("Launcher/nightly/profiles/gridcraft");
for platform in [Platform::Windows, Platform::Linux, Platform::Mac] {
assert_eq!(fixture.check(platform, &data).unwrap(), data);
}
assert!(
fixture
.check(
Platform::Linux,
&PathBuf::from(fixture.get("LOCALAPPDATA").unwrap()).join("Programs/ArtCraft/ArtCraftLauncher/nightly/gridcraft")
)
.is_ok(),
"the Launcher's own folder is not GridCraft's install"
);
}
fn extra_forbidden_root_overlap_and_traversal_are_refused() {
let tmp = TempDir::new("forbidden");
let forbidden = tmp.path().join("stable-boundary");
let mut spec = app_spec();
spec.extra_forbidden_roots.push(forbidden.clone());
#[test]
fn overlap_check_handles_ancestor_descendant_and_prefix_lookalikes() {
let fixture = Fixture::new();
let root = fixture.home().join("nightly/profiles/gridcraft");
for platform in [Platform::Windows, Platform::Linux, Platform::Mac] {
assert!(overlaps(&root, &root.join("Control"), platform));
assert!(overlaps(&root.join("Control"), &root, platform));
assert!(!overlaps(&root, &root.with_file_name("gridcraft-other"), platform));
}
}
assert!(matches!(validate_and_prepare_root(&forbidden, &spec), Err(ProfileError::ForbiddenRootOverlap { .. })));
assert!(matches!(validate_and_prepare_root(&forbidden.join("nightly"), &spec), Err(ProfileError::ForbiddenRootOverlap { .. })));
assert!(!forbidden.exists());
#[test]
fn the_install_folder_of_the_running_build_is_refused() {
let fixture = Fixture::new();
for platform in [Platform::Windows, Platform::Linux, Platform::Mac] {
assert!(fixture.check(platform, &fixture.exe.parent().unwrap().join("profile")).is_err());
}
}
#[test]
fn mac_fences_the_whole_bundle_not_just_its_macos_folder() {
let mut fixture = Fixture::new();
fixture.exe = fixture.root.join("install/GridCraft Nightly.app/Contents/MacOS/GridCraft");
std::fs::create_dir_all(fixture.exe.parent().unwrap()).unwrap();
std::fs::write(&fixture.exe, b"fixture executable, never run").unwrap();
let inside_resources = fixture.exe.parent().unwrap().parent().unwrap().join("Resources/profile");
assert!(fixture.check(Platform::Mac, &inside_resources).unwrap_err().contains("overlap"));
assert!(!inside_resources.exists());
assert!(fixture.check(Platform::Mac, &fixture.home().join("Library/Application Support/ArtCraft/nightly/profiles/gridcraft")).is_ok());
}
#[test]
fn ambiguous_environment_and_non_native_sandbox_are_refused_before_creation() {
let mut fixture = Fixture::new();
let candidate = fixture.home().join("nightly/profiles/gridcraft");
fixture.env.insert("XDG_CACHE_HOME".into(), "relative/cache".into());
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("absolute"));
fixture.env.remove("XDG_CACHE_HOME");
fixture.env.insert("FLATPAK_ID".into(), "ai.storyteller.gridcraft".into());
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("Flatpak"));
fixture.env.remove("FLATPAK_ID");
fixture.env.remove("HOME");
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("HOME"));
assert!(!candidate.exists());
}
#[test]
fn only_the_nightly_s_own_flatpak_instance_may_carry_a_profile() {
let mut fixture = Fixture::new();
let root = fixture.root.join("flatpak profile");
for (id, accepted) in [
(gridcraft_ui_egui::channel::NIGHTLY_PACKAGE_ID, true),
// The stable Flatpak, and a lookalike that only shares the prefix, stay refused.
("ai.storyteller.gridcraft", false),
("ai.storyteller.gridcraft.nightly-v1", false),
("io.github.other.Gridcraft", false),
] {
fixture.env.insert("FLATPAK_ID".into(), id.into());
let result = fixture.check(Platform::Linux, &root);
assert_eq!(result.is_ok(), accepted, "{id}");
let _ = std::fs::remove_dir_all(&root);
}
}
#[test]
fn failed_write_probe_never_falls_back_to_stable() {
let fixture = Fixture::new();
let candidate = fixture.home().join("nightly/profiles/gridcraft");
let result = fixture.check_with(Platform::Linux, &candidate, |_| Err(std::io::Error::other("read-only mount")));
assert!(result.unwrap_err().contains("not writable"));
assert!(candidate.is_dir(), "a created profile is not rolled back onto stable data");
assert!(!fixture.home().join(".config/gridcraft").exists());
}
#[test]
fn a_file_in_place_of_the_profile_is_refused() {
let fixture = Fixture::new();
let candidate = fixture.root.join("not-a-directory");
std::fs::write(&candidate, b"a file, not a profile").unwrap();
assert!(fixture.check(Platform::Linux, &candidate).is_err());
assert_eq!(std::fs::read(&candidate).unwrap(), b"a file, not a profile");
}
#[cfg(unix)]
#[test]
fn profile_entry_aliases_must_stay_inside_the_profile() {
let fixture = Fixture::new();
let stable = fixture.home().join(".config/gridcraft");
std::fs::create_dir_all(&stable).unwrap();
std::fs::write(stable.join("ui.json"), b"stable settings").unwrap();
for name in ["ui.json", "logs", "Control", "profile"] {
let private = fixture.root.join(format!("nightly-{name}"));
std::fs::create_dir(&private).unwrap();
std::os::unix::fs::symlink(&stable, private.join(name)).unwrap();
let probed = std::cell::Cell::new(false);
let result = fixture.check_with(Platform::Linux, &private, |_| {
probed.set(true);
Ok(())
});
assert!(result.is_err(), "{name} must not lead outside the profile");
assert!(!probed.get());
}
let private = fixture.root.join("nightly-inside");
std::fs::create_dir_all(private.join("real-logs")).unwrap();
std::fs::write(private.join("ui.json"), b"{}").unwrap();
std::os::unix::fs::symlink(private.join("real-logs"), private.join("logs")).unwrap();
assert!(fixture.check(Platform::Linux, &private).is_ok(), "links that stay inside are fine");
assert_eq!(std::fs::read(stable.join("ui.json")).unwrap(), b"stable settings");
assert_eq!(std::fs::read_dir(&stable).unwrap().count(), 1);
}
#[cfg(unix)]
#[test]
fn a_control_folder_alias_cannot_redirect_the_token_outside_the_profile() {
let fixture = Fixture::new();
let outside = fixture.home().join("shared-tokens");
std::fs::create_dir_all(&outside).unwrap();
let private = fixture.root.join("nightly-control");
std::fs::create_dir(&private).unwrap();
std::os::unix::fs::symlink(&outside, private.join(CONTROL_DIR)).unwrap();
assert!(control_directory(&private).is_err());
assert!(fixture.check(Platform::Linux, &private).is_err());
assert_eq!(std::fs::read_dir(&outside).unwrap().count(), 0);
assert!(matches!(validate_and_prepare_root(Path::new("relative/profile"), &spec), Err(ProfileError::RelativeProfileRoot(_))));
assert!(matches!(validate_and_prepare_root(&tmp.path().join("a/../b"), &spec), Err(ProfileError::ParentTraversalInProfileRoot(_))));
}
#[test]
fn the_control_folder_is_a_private_lazy_subfolder() {
let fixture = Fixture::new();
let private = fixture.check(Platform::Linux, &fixture.home().join("nightly/profile")).unwrap();
let tmp = TempDir::new("control");
let private = validate_and_prepare_root(&tmp.path().join("nightly-profile"), &app_spec()).unwrap();
let control = control_directory(&private).unwrap();
assert!(control.starts_with(&private) && control != private);
assert!(!control.exists(), "resolving it must not create it");
assert_eq!(control.file_name().unwrap(), CONTROL_DIR);
}
#[cfg(unix)]
#[test]
fn the_writable_probe_leaves_nothing_behind() {
let fixture = Fixture::new();
let private = fixture.check(Platform::Linux, &fixture.home().join("nightly/profile")).unwrap();
ensure_writable(&private).unwrap();
assert_eq!(std::fs::read_dir(&private).unwrap().count(), 0);
}
fn a_control_folder_alias_cannot_redirect_the_token_outside_the_profile() {
let tmp = TempDir::new("control-symlink");
let outside = tmp.path().join("shared-tokens");
std::fs::create_dir_all(&outside).unwrap();
let private = tmp.path().join("nightly-control");
std::fs::create_dir(&private).unwrap();
std::os::unix::fs::symlink(&outside, private.join(CONTROL_DIR)).unwrap();
#[test]
fn nightly_profile_reopens_after_saving_settings_and_session_state() {
let fixture = Fixture::new();
for platform in [Platform::Mac, Platform::Linux, Platform::Windows] {
let private = fixture.root.join(format!("nightly-reopen-{platform:?}"));
assert_eq!(fixture.check(platform, &private).unwrap(), private);
for name in ["ui.json", "prefs.json", "nightly-session.lock", "nightly-session.json"] {
std::fs::write(private.join(name), b"saved profile data").unwrap();
}
for name in PROFILE_FOLDERS {
std::fs::create_dir(private.join(name)).unwrap();
}
assert_eq!(fixture.check(platform, &private).unwrap(), private);
assert_eq!(std::fs::read(private.join("ui.json")).unwrap(), b"saved profile data");
for name in PROFILE_FOLDERS {
let path = private.join(name);
std::fs::remove_dir(&path).unwrap();
std::fs::write(&path, b"not a directory").unwrap();
assert!(fixture.check(platform, &private).is_err(), "{name} must stay a directory");
std::fs::remove_file(&path).unwrap();
std::fs::create_dir(&path).unwrap();
}
}
assert!(control_directory(&private).is_err());
assert!(matches!(validate_and_prepare_root(&private, &app_spec()), Err(ProfileError::SymlinkEntry(_))));
assert_eq!(std::fs::read_dir(&outside).unwrap().count(), 0);
}
}