Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/schema.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ production configs and the dev schema when working on experimental features:

"process": {
"commandLine": "python app.py", // Required: command to execute
"cwd": "C:\\workspace", // Working directory
"cwd": "C:\\workspace", // Working directory (optional; sandboxed backends may default it to a granted path)
"env": ["MY_VAR=value"], // Environment variables as KEY=VALUE
"timeout": 30000 // Timeout in ms (0 = no timeout)
},
Expand Down
6 changes: 4 additions & 2 deletions src/backends/appcontainer/common/src/appcontainer_runner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -941,8 +941,10 @@ impl AppContainerScriptRunner {
// --- Build command line ---
let mut cmd_line_wide = string_util::to_wide(&request.script_code);

let working_dir_wide = string_util::to_wide(&request.working_directory);
let working_dir_pcwstr = if request.working_directory.is_empty() {
// Empty falls back to a granted path (see `resolved_working_directory`).
let working_directory = request.resolved_working_directory().unwrap_or_default();
Comment thread
caarlos0 marked this conversation as resolved.
let working_dir_wide = string_util::to_wide(working_directory);
let working_dir_pcwstr = if working_directory.is_empty() {
PCWSTR::null()
} else {
PCWSTR(working_dir_wide.as_ptr())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -678,12 +678,13 @@ impl BaseContainerRunner {
// 3. Build the command line (passed directly, same as AppContainerScriptRunner).
let mut cmd_wide = string_util::to_wide(&request.script_code);

// Working directory (NULL falls back to the current directory).
// Empty falls back to a granted path (see `resolved_working_directory`).
let working_directory = request.resolved_working_directory().unwrap_or_default();
let cwd_wide;
let cwd_ptr = if request.working_directory.is_empty() {
let cwd_ptr = if working_directory.is_empty() {
ptr::null()
} else {
cwd_wide = string_util::to_wide(&request.working_directory);
cwd_wide = string_util::to_wide(working_directory);
cwd_wide.as_ptr()
};

Expand Down
59 changes: 59 additions & 0 deletions src/core/wxc_common/src/models.rs
Original file line number Diff line number Diff line change
Expand Up @@ -739,6 +739,29 @@ pub struct ExecutionRequest {
pub dry_run: bool,
}

impl ExecutionRequest {
/// Resolve the working directory for the sandboxed child: an explicit
/// `working_directory`, else the first `readwrite` path, else the first
/// `readonly` path, else `None`.
///
/// Backends that must not let the child inherit the host process's cwd use
/// this to fall back to a policy-granted path. It matters most on Windows:
/// a `NULL` current directory makes `CreateProcessW` inherit the parent's
/// cwd, and when the AppContainer token can't open it the kernel silently
/// resets the child to the drive root (`C:\`) instead of failing the launch.
/// The path is not checked for existence, so the launch can still fail.
pub fn resolved_working_directory(&self) -> Option<&str> {
if !self.working_directory.is_empty() {
return Some(self.working_directory.as_str());
}
self.policy
.readwrite_paths
.first()
.or_else(|| self.policy.readonly_paths.first())
.map(String::as_str)
}
}

/// Distinguishes whether an error occurred during process creation (launch)
/// or after the process started but exited with a failure code.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
Expand Down Expand Up @@ -819,6 +842,42 @@ mod tests {
use super::*;
use serde_json::json;

fn request_with_paths(readwrite: &[&str], readonly: &[&str]) -> ExecutionRequest {
ExecutionRequest {
policy: ContainerPolicy {
readwrite_paths: readwrite.iter().map(|s| s.to_string()).collect(),
readonly_paths: readonly.iter().map(|s| s.to_string()).collect(),
..Default::default()
},
..Default::default()
}
}

#[test]
fn resolved_working_directory_prefers_explicit_value() {
let mut req = request_with_paths(&["C:\\rw"], &["C:\\ro"]);
req.working_directory = "C:\\explicit".to_string();
assert_eq!(req.resolved_working_directory(), Some("C:\\explicit"));
}

#[test]
fn resolved_working_directory_falls_back_to_first_readwrite() {
let req = request_with_paths(&["C:\\rw1", "C:\\rw2"], &["C:\\ro"]);
assert_eq!(req.resolved_working_directory(), Some("C:\\rw1"));
}

#[test]
fn resolved_working_directory_falls_back_to_first_readonly() {
let req = request_with_paths(&[], &["C:\\ro1", "C:\\ro2"]);
assert_eq!(req.resolved_working_directory(), Some("C:\\ro1"));
}

#[test]
fn resolved_working_directory_none_when_no_dir_and_no_paths() {
let req = request_with_paths(&[], &[]);
assert_eq!(req.resolved_working_directory(), None);
}

#[test]
fn script_response_backend_unavailable_round_trips() {
let r = ScriptResponse {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,23 @@
//! been built or the host is missing process prerequisites. They therefore
//! never red-fail on incapable CI, but lock in behavior on a prepared box.
//!
//! Scope note: env/cwd inheritance is intentionally not characterized here β€”
//! the AppContainer "clean environment" model differs from the Unix backends,
//! and the PR's env/cwd regressions were Seatbelt-specific. These tests cover
//! the universally-meaningful contracts: exit-code propagation, stdout capture,
//! and timeout enforcement.
//! Scope note: env inheritance is intentionally not characterized here β€” the
//! AppContainer "clean environment" model differs from the Unix backends. cwd
//! *is* characterized (see the two `*_process_cwd*` tests below), because both
//! Windows runners resolve an empty `process.cwd` to a policy-granted path
//! rather than passing `NULL` to the launch API.
//!
//! Tier note: the ProcessContainer tier (BaseContainer vs AppContainer+DACL) is
//! **not** independently selectable from a config β€” the dispatcher derives it
//! purely from host capability, and the `MXC_FORCE_TIER` seam is `cfg(test)`-only
//! so it has no effect on the production `wxc-exec.exe`. These tests therefore
//! exercise whichever tier the prepared lane resolves to; running them on both a
//! BaseContainer-capable and a downlevel host covers both tiers.
#![cfg(target_os = "windows")]

use std::fs;
use std::path::PathBuf;

use serde_json::json;
use wxc_e2e_tests::{
has_platform_exec, host_prepped_optin, run_platform_config_value, CommandResult,
Expand All @@ -44,6 +54,17 @@ fn config(label: &str, command_line: &str) -> serde_json::Value {
})
}

/// Create a unique temporary directory for cwd characterization.
fn unique_tempdir(tag: &str) -> PathBuf {
let nanos = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos();
let dir = std::env::temp_dir().join(format!("mxc-char-pc-{tag}-{nanos}"));
fs::create_dir_all(&dir).expect("create temp dir");
dir
}

/// Skip (rather than fail) when the local host cannot launch a sandboxed
/// process despite the opt-in being set (e.g. missing runtime prerequisites).
fn skip_if_missing_prereq(result: &CommandResult) -> bool {
Expand Down Expand Up @@ -134,3 +155,96 @@ fn processcontainer_timeout_kills_before_completion() {
result.wall_time_ms
);
}

/// REGRESSION GUARD (both Windows runners).
///
/// With an empty `process.cwd`, neither ProcessContainer runner may pass a
/// `NULL` current directory to the launch API: the child would then inherit the
/// launcher's cwd, and when the sandbox token can't open it the kernel silently
/// resets the child to the drive root (`C:\`). Instead the runners resolve the
/// cwd via `ExecutionRequest::resolved_working_directory()` β€” the first
/// `readwritePaths` entry.
///
/// The unit tests on that resolver only cover path *selection*; they would still
/// pass if a runner ignored it and passed `NULL`. This test observes the child's
/// actual cwd by having it create a file through a *relative* path and checking
/// which directory it lands in.
///
/// `launch_dir` is the launcher's cwd and is *also* a granted readwrite path, so
/// a `NULL`-cwd regression would be openable by the token and the probe would
/// land there β€” making the two outcomes distinguishable.
#[test]
fn processcontainer_runs_in_first_readwrite_path_when_process_cwd_empty() {
if !ready() {
return;
}
let write_dir = unique_tempdir("cwd-write");
let launch_dir = unique_tempdir("cwd-launch");
let probe = "char_cwd_default_probe.txt";
let mut cfg = config("cwd-default", &format!("cmd /c echo CHAR_OK> {probe}"));
cfg["filesystem"] = json!({
"readwritePaths": [write_dir.to_string_lossy(), launch_dir.to_string_lossy()]
});
let result =
run_platform_config_value("processcontainer cwd default", &cfg, &[], Some(&launch_dir));
let in_launch = launch_dir.join(probe).exists();
let in_write = write_dir.join(probe).exists();
let _ = fs::remove_dir_all(&launch_dir);
let _ = fs::remove_dir_all(&write_dir);
if skip_if_missing_prereq(&result) {
return;
}
assert_eq!(
result.code,
Some(0),
"run failed:\n{}",
result.combined_output()
);
assert!(
in_write && !in_launch,
"expected the probe in the first readwrite policy path {} (resolved cwd \
with empty process.cwd); in_write={in_write} in_launch={in_launch}\n{}",
write_dir.display(),
result.combined_output()
);
}

/// Locks in that an explicit `process.cwd` still wins over the policy-path
/// fallback introduced by `resolved_working_directory()`.
#[test]
fn processcontainer_honors_explicit_process_cwd() {
if !ready() {
return;
}
let explicit_dir = unique_tempdir("cwd-explicit");
let other_dir = unique_tempdir("cwd-other");
let probe = "char_cwd_explicit_probe.txt";
let mut cfg = config("cwd-explicit", &format!("cmd /c echo CHAR_OK> {probe}"));
cfg["process"]["cwd"] = json!(explicit_dir.to_string_lossy());
// `other_dir` is listed first so the fallback would resolve to it; the
// explicit cwd must take precedence.
cfg["filesystem"] = json!({
"readwritePaths": [other_dir.to_string_lossy(), explicit_dir.to_string_lossy()]
});
let result = run_platform_config_value("processcontainer cwd explicit", &cfg, &[], None);
let in_explicit = explicit_dir.join(probe).exists();
let in_other = other_dir.join(probe).exists();
let _ = fs::remove_dir_all(&explicit_dir);
let _ = fs::remove_dir_all(&other_dir);
if skip_if_missing_prereq(&result) {
return;
}
assert_eq!(
result.code,
Some(0),
"run failed:\n{}",
result.combined_output()
);
assert!(
in_explicit && !in_other,
"expected the probe file in the explicit process.cwd {}; \
in_explicit={in_explicit} in_other={in_other}\n{}",
explicit_dir.display(),
result.combined_output()
);
}
Loading