aKode fase 5: rinomina interna (crate akode-*, akode-rs/, akode-cli/, binario akode, AKODE_*, ~/.akode, snapshot)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
273
akode-rs/exec-server/tests/exec_process/shell_snapshot.rs
Normal file
273
akode-rs/exec-server/tests/exec_process/shell_snapshot.rs
Normal file
@@ -0,0 +1,273 @@
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
use test_case::test_case;
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum SnapshotSandbox {
|
||||
None,
|
||||
WorkspaceWrite,
|
||||
DenyFdPath,
|
||||
}
|
||||
|
||||
pub(super) struct StartupProcesses(pub(super) std::path::PathBuf);
|
||||
|
||||
impl Drop for StartupProcesses {
|
||||
fn drop(&mut self) {
|
||||
if let Ok(contents) = std::fs::read_to_string(&self.0) {
|
||||
for pid in contents
|
||||
.split_whitespace()
|
||||
.filter_map(|pid| pid.parse::<i32>().ok())
|
||||
{
|
||||
if pid > 0 {
|
||||
// SAFETY: these PIDs were written by our startup profile.
|
||||
unsafe { libc::kill(pid, libc::SIGKILL) };
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test_case("bash"; "bash")]
|
||||
#[cfg_attr(target_os = "macos", test_case("zsh"; "zsh"))]
|
||||
#[tokio::test]
|
||||
async fn shell_snapshot_preserves_successful_startup_output_and_services(
|
||||
shell: &str,
|
||||
) -> Result<()> {
|
||||
let context = create_process_context(/*use_remote*/ false).await?;
|
||||
let home = TempDir::new()?;
|
||||
let _service = StartupProcesses(home.path().join("service-pid"));
|
||||
std::fs::write(
|
||||
home.path().join(format!(".{shell}rc")),
|
||||
"printf x >> \"$HOME/captures\"\n/bin/sleep 30 >/dev/null 2>&1 &\nexport SNAPSHOT_SERVICE_PID=$!\nprintf '%s' \"$SNAPSHOT_SERVICE_PID\" > \"$HOME/service-pid\"\nexec > >(/bin/sleep 0.2; /bin/cat)\nprofile_helper() { printf 'captured:%s' \"$1\"; }\n",
|
||||
)?;
|
||||
for index in 0..2 {
|
||||
let started = context
|
||||
.backend
|
||||
.start(ExecParams {
|
||||
metadata: Default::default(),
|
||||
process_id: format!("startup-capture-{index}").into(),
|
||||
argv: vec![
|
||||
format!("/bin/{shell}"),
|
||||
"-lc".to_string(),
|
||||
format!(
|
||||
"[ \"$SNAPSHOT_SERVICE_PID\" = \"$(/bin/cat \"$HOME/service-pid\")\" ] || exit 41\ncase \"$(/bin/ps -o stat= -p \"$SNAPSHOT_SERVICE_PID\")\" in ''|*Z*) exit 42;; esac\nprofile_helper {index}"
|
||||
),
|
||||
],
|
||||
cwd: PathUri::from_host_native_path(home.path())?,
|
||||
env: HashMap::from([
|
||||
(
|
||||
"HOME".to_string(),
|
||||
home.path().to_string_lossy().into_owned(),
|
||||
),
|
||||
("PATH".to_string(), "/usr/bin:/bin".to_string()),
|
||||
]),
|
||||
env_policy: None,
|
||||
shell_snapshot: Some(ShellSnapshotRequest {
|
||||
scope_id: "startup-capture".to_string(),
|
||||
shell: ShellInfo {
|
||||
name: shell.to_string(),
|
||||
path: format!("/bin/{shell}"),
|
||||
},
|
||||
}),
|
||||
tty: false,
|
||||
pipe_stdin: false,
|
||||
arg0: Some("akode-linux-sandbox".to_string()),
|
||||
sandbox: None,
|
||||
enforce_managed_network: false,
|
||||
managed_network: None,
|
||||
network_proxy: None,
|
||||
})
|
||||
.await?;
|
||||
assert_eq!(
|
||||
collect_process_output_from_events(started.process).await?,
|
||||
(format!("captured:{index}"), String::new(), Some(0), true)
|
||||
);
|
||||
}
|
||||
assert_eq!(std::fs::read_to_string(home.path().join("captures"))?, "x");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test_case("bash", false, SnapshotSandbox::None; "bash")]
|
||||
#[test_case("bash", true, SnapshotSandbox::None; "bash_tty")]
|
||||
#[cfg_attr(target_os = "macos", test_case("zsh", false, SnapshotSandbox::None; "zsh"))]
|
||||
#[cfg_attr(target_os = "macos", test_case("zsh", true, SnapshotSandbox::None; "zsh_tty"))]
|
||||
#[test_case("bash", false, SnapshotSandbox::DenyFdPath; "blocked_descriptor_path")]
|
||||
#[cfg_attr(target_os = "macos", test_case("zsh", false, SnapshotSandbox::DenyFdPath; "zsh_blocked_descriptor_path"))]
|
||||
#[cfg_attr(target_os = "macos", test_case("zsh", true, SnapshotSandbox::DenyFdPath; "zsh_blocked_descriptor_path_tty"))]
|
||||
#[test_case("bash", false, SnapshotSandbox::WorkspaceWrite; "bash_protected_transport")]
|
||||
#[test_case("bash", true, SnapshotSandbox::WorkspaceWrite; "bash_protected_transport_tty")]
|
||||
#[cfg_attr(target_os = "macos", test_case("zsh", false, SnapshotSandbox::WorkspaceWrite; "zsh_protected_transport"))]
|
||||
#[cfg_attr(target_os = "macos", test_case("zsh", true, SnapshotSandbox::WorkspaceWrite; "zsh_protected_transport_tty"))]
|
||||
#[serial_test::serial(remote_exec_server)]
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn shell_snapshot_concurrent_replays_keep_independent_readers(
|
||||
shell: &str,
|
||||
tty: bool,
|
||||
sandbox_mode: SnapshotSandbox,
|
||||
) -> Result<()> {
|
||||
let deny_fd_path = sandbox_mode == SnapshotSandbox::DenyFdPath;
|
||||
let use_sandbox = sandbox_mode != SnapshotSandbox::None;
|
||||
if use_sandbox
|
||||
&& let Some(warning) = akode_sandboxing::system_bwrap_warning(
|
||||
&PermissionProfile::read_only(),
|
||||
&std::env::current_dir()?,
|
||||
)
|
||||
{
|
||||
eprintln!("skipping sandbox test: {warning}");
|
||||
return Ok(());
|
||||
}
|
||||
let context = if sandbox_mode == SnapshotSandbox::WorkspaceWrite {
|
||||
let (exe, linux_sandbox) = current_test_binary_helper_paths()?;
|
||||
let environment = Environment::create(
|
||||
/*exec_server_url*/ None,
|
||||
akode_exec_server::ExecServerRuntimeOptions::new(exe, linux_sandbox)?,
|
||||
akode_http_client::HttpClientFactory::new(
|
||||
akode_http_client::OutboundProxyPolicy::ReqwestDefault,
|
||||
),
|
||||
)?;
|
||||
ProcessContext {
|
||||
backend: environment.get_exec_backend(),
|
||||
_server: None,
|
||||
}
|
||||
} else {
|
||||
create_process_context(deny_fd_path).await?
|
||||
};
|
||||
let home = TempDir::new()?;
|
||||
let cwd = PathUri::from_host_native_path(home.path())?;
|
||||
// Keep full-size state in a function, below the 512 KiB state + environment cap.
|
||||
// The blocked-path case still exercises the smaller environment fallback.
|
||||
let payload_len = if deny_fd_path { 1 } else { 480 * 1024 };
|
||||
let payload = "x".repeat(payload_len);
|
||||
let source = if shell == "bash" {
|
||||
"${BASH_SOURCE[0]}"
|
||||
} else {
|
||||
"${(%):-%x}"
|
||||
};
|
||||
let source_check = if deny_fd_path {
|
||||
String::new()
|
||||
} else {
|
||||
format!("case \"{source}\" in /dev/fd/*) ;; *) return 42 ;; esac; ")
|
||||
};
|
||||
let aliases = if shell == "zsh" {
|
||||
"module_path=()\nsetopt RC_QUOTES\nalias snapshot_quoted=\"printf '%s|' 'one''two'\"\nalias eval='exit 44'\nalias case='exit 45'\n"
|
||||
} else {
|
||||
""
|
||||
};
|
||||
std::fs::write(
|
||||
home.path().join(format!(".{shell}rc")),
|
||||
format!(
|
||||
"printf x >> \"$HOME/captures\"\nprofile_helper() {{ {source_check}local payload='{payload}'; [ \"${{#payload}}\" = {payload_len} ] || return 43; printf 'restored:%s' \"$1\"; }}\nexec() {{ exit 41; }}\nset -u\n{aliases}"
|
||||
),
|
||||
)?;
|
||||
let protected_file =
|
||||
tempfile::NamedTempFile::new_in(akode_uds::prepare_shared_daemon_socket_directory()?)?;
|
||||
std::fs::write(protected_file.path(), "protected")?;
|
||||
let command = if sandbox_mode == SnapshotSandbox::WorkspaceWrite {
|
||||
// Broad /tmp grants must not expose the file while it still has a name.
|
||||
"if /bin/cat \"$SNAPSHOT_TRANSPORT_PROBE\" >/dev/null 2>&1 || (printf poisoned >> \"$SNAPSHOT_TRANSPORT_PROBE\") 2>/dev/null || /bin/mv \"$SNAPSHOT_TRANSPORT_PROBE\" \"$HOME/stolen\" 2>/dev/null; then exit 44; fi\n"
|
||||
} else {
|
||||
""
|
||||
};
|
||||
let replay_checks = if shell == "zsh" {
|
||||
"eval snapshot_quoted\n[[ -o rcquotes ]] || exit 46\n"
|
||||
} else {
|
||||
""
|
||||
};
|
||||
let command =
|
||||
format!("{command}IFS= read -r line\n{replay_checks}profile_helper \"$line\"; exit 7");
|
||||
let sandbox = if use_sandbox {
|
||||
let mut policy = FileSystemSandboxPolicy::read_only();
|
||||
policy.entries.push(FileSystemSandboxEntry::new(
|
||||
cwd.clone().into(),
|
||||
FileSystemAccessMode::Write,
|
||||
));
|
||||
if deny_fd_path {
|
||||
policy.entries.push(FileSystemSandboxEntry::new(
|
||||
PathUri::from_host_native_path("/dev/fd")?.into(),
|
||||
FileSystemAccessMode::Deny,
|
||||
));
|
||||
} else {
|
||||
policy.entries.push(FileSystemSandboxEntry::new(
|
||||
PathUri::from_host_native_path(std::fs::canonicalize("/tmp")?)?.into(),
|
||||
FileSystemAccessMode::Write,
|
||||
));
|
||||
}
|
||||
Some(FileSystemSandboxContext::from_permission_profile(
|
||||
PermissionProfile::from_runtime_permissions(&policy, NetworkSandboxPolicy::Restricted),
|
||||
cwd.clone(),
|
||||
))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let commands = (0..8).map(|index| {
|
||||
let backend = &context.backend;
|
||||
let cwd = cwd.clone();
|
||||
let home = home.path();
|
||||
let sandbox = sandbox.clone();
|
||||
let command = command.clone();
|
||||
let protected_path = protected_file.path();
|
||||
async move {
|
||||
let started = backend
|
||||
.start(ExecParams {
|
||||
metadata: Default::default(),
|
||||
process_id: format!("parallel-{index}").into(),
|
||||
argv: vec![format!("/bin/{shell}"), "-lc".to_string(), command],
|
||||
cwd,
|
||||
env: HashMap::new(),
|
||||
env_policy: Some(ExecEnvPolicy {
|
||||
inherit: ShellEnvironmentPolicyInherit::None,
|
||||
ignore_default_excludes: false,
|
||||
exclude: Vec::new(),
|
||||
r#set: HashMap::from([
|
||||
("HOME".to_string(), home.to_string_lossy().into_owned()),
|
||||
("PATH".to_string(), "/usr/bin:/bin".to_string()),
|
||||
(
|
||||
"SNAPSHOT_TRANSPORT_PROBE".to_string(),
|
||||
protected_path.to_string_lossy().into_owned(),
|
||||
),
|
||||
]),
|
||||
include_only: Vec::new(),
|
||||
}),
|
||||
shell_snapshot: Some(ShellSnapshotRequest {
|
||||
scope_id: "parallel".to_string(),
|
||||
shell: ShellInfo {
|
||||
name: shell.to_string(),
|
||||
path: format!("/bin/{shell}"),
|
||||
},
|
||||
}),
|
||||
tty,
|
||||
pipe_stdin: true,
|
||||
arg0: None,
|
||||
sandbox,
|
||||
enforce_managed_network: false,
|
||||
managed_network: None,
|
||||
network_proxy: None,
|
||||
})
|
||||
.await?;
|
||||
started
|
||||
.process
|
||||
.write(format!("input-{index}\n").into_bytes())
|
||||
.await?;
|
||||
let (output, errors, status, closed) =
|
||||
collect_process_output_from_events(started.process).await?;
|
||||
assert!(
|
||||
output.ends_with(&format!("restored:input-{index}")),
|
||||
"{output:?}"
|
||||
);
|
||||
if shell == "zsh" {
|
||||
assert!(
|
||||
output.ends_with(&format!("one'two|restored:input-{index}")),
|
||||
"{output:?}"
|
||||
);
|
||||
}
|
||||
assert_eq!((errors, status, closed), (String::new(), Some(7), true));
|
||||
Ok::<_, anyhow::Error>(())
|
||||
}
|
||||
});
|
||||
for result in futures::future::join_all(commands).await {
|
||||
result?;
|
||||
}
|
||||
assert_eq!(std::fs::read_to_string(home.path().join("captures"))?, "x");
|
||||
assert_eq!(std::fs::read_to_string(protected_file.path())?, "protected");
|
||||
Ok(())
|
||||
}
|
||||
300
akode-rs/exec-server/tests/exec_process/windows_sandbox.rs
Normal file
300
akode-rs/exec-server/tests/exec_process/windows_sandbox.rs
Normal file
@@ -0,0 +1,300 @@
|
||||
//! Shared Windows sandbox behavior over the real exec-server RPC connection.
|
||||
|
||||
use super::*;
|
||||
use akode_exec_server::ExecEnvPolicy;
|
||||
use akode_protocol::config_types::ShellEnvironmentPolicyInherit;
|
||||
use akode_protocol::models::PermissionProfile;
|
||||
use akode_protocol::permissions::FileSystemAccessMode;
|
||||
use akode_protocol::permissions::FileSystemPath;
|
||||
use akode_protocol::permissions::FileSystemSandboxEntry;
|
||||
use akode_protocol::permissions::FileSystemSandboxPolicy;
|
||||
use akode_protocol::permissions::FileSystemSpecialPath;
|
||||
use akode_protocol::permissions::NetworkSandboxPolicy;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test_case::test_case(false; "invalid_disabled_proxy")]
|
||||
#[test_case::test_case(true; "valid_enabled_proxy")]
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
#[serial_test::serial(remote_exec_server)]
|
||||
async fn native_windows_skips_owned_proxy_before_brokering(proxy_enabled: bool) -> Result<()> {
|
||||
use akode_network_proxy::NetworkProxyConfig;
|
||||
use akode_network_proxy::RemoteNetworkProxyConfig;
|
||||
use akode_network_proxy::RemoteNetworkProxyLaunchConfig;
|
||||
|
||||
const API_KEY: &str = "sk-proj-executor-only-0000000000000000000000000000000000";
|
||||
let context = create_process_context(/*use_remote*/ true).await?;
|
||||
let mut proxy = RemoteNetworkProxyConfig::from_effective_config(&NetworkProxyConfig {
|
||||
enabled: proxy_enabled,
|
||||
..NetworkProxyConfig::default()
|
||||
})?;
|
||||
proxy.enable_credential_masking(Default::default());
|
||||
let started = context
|
||||
.backend
|
||||
.start(ExecParams {
|
||||
metadata: None,
|
||||
process_id: ProcessId::from("native-windows-owned-proxy"),
|
||||
argv: vec![
|
||||
std::env::var("ComSpec")?,
|
||||
"/d".into(),
|
||||
"/c".into(),
|
||||
"if defined HTTP_PROXY (exit /b 1) else if defined AKODE_NETWORK_PROXY_ACTIVE (exit /b 2) else (echo %CALLER_VALUE% %OPENAI_API_KEY%)".into(),
|
||||
],
|
||||
cwd: PathUri::from_host_native_path(std::env::current_dir()?)?,
|
||||
env: HashMap::from([
|
||||
("HTTP_PROXY".into(), "http://127.0.0.1:1".into()),
|
||||
("SystemRoot".into(), std::env::var("SystemRoot")?),
|
||||
("AKODE_NETWORK_PROXY_ACTIVE".into(), "1".into()),
|
||||
("OPENAI_API_KEY".into(), API_KEY.into()),
|
||||
("CALLER_VALUE".into(), "preserved".into()),
|
||||
]),
|
||||
env_policy: None,
|
||||
shell_snapshot: None,
|
||||
tty: false,
|
||||
pipe_stdin: false,
|
||||
arg0: None,
|
||||
sandbox: None,
|
||||
enforce_managed_network: false,
|
||||
managed_network: None,
|
||||
network_proxy: Some(RemoteNetworkProxyLaunchConfig::new(proxy)),
|
||||
})
|
||||
.await?;
|
||||
let (stdout, stderr, code, exited) = collect_process_output_from_events_with_timeout(
|
||||
started.process,
|
||||
Duration::from_secs(/*secs*/ 30),
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(
|
||||
(stdout.trim(), stderr, code, exited),
|
||||
(
|
||||
format!("preserved {API_KEY}").as_str(),
|
||||
String::new(),
|
||||
Some(0),
|
||||
true
|
||||
)
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Windows alias casing must not prevent fallback when the primary runtime is absent from PATH.
|
||||
#[test_case::test_case("pwsh.exe"; "lowercase_pwsh")]
|
||||
#[test_case::test_case("PWSH.exe"; "uppercase_pwsh")]
|
||||
#[test_case::test_case("powershell.exe"; "lowercase_powershell")]
|
||||
#[test_case::test_case("PowerShell.exe"; "mixed_case_powershell")]
|
||||
#[cfg_attr(not(windows), ignore = "requires a native Windows sandbox")]
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
#[serial_test::serial(remote_exec_server)]
|
||||
async fn powershell_alias_falls_back_without_primary_runtime_over_rpc(
|
||||
shell_name: &str,
|
||||
) -> Result<()> {
|
||||
crate::skip_if_mxc_unavailable!(Ok(()));
|
||||
let root = TempDir::new()?;
|
||||
let system32 = std::path::PathBuf::from(std::env::var("SystemRoot")?).join("System32");
|
||||
let server =
|
||||
common::exec_server::exec_server_with_env([("PATH", system32.as_os_str())], &[]).await?;
|
||||
let environment = Environment::create_for_tests(Some(server.websocket_url().to_owned()))?;
|
||||
let cwd = PathUri::from_host_native_path(root.path())?;
|
||||
let mut sandbox = FileSystemSandboxContext::from_permission_profile(
|
||||
PermissionProfile::read_only(),
|
||||
cwd.clone(),
|
||||
);
|
||||
sandbox.windows_sandbox_selection = akode_exec_server::WindowsSandboxSelection::Mxc;
|
||||
let started = environment
|
||||
.get_exec_backend()
|
||||
.start(ExecParams {
|
||||
process_id: ProcessId::from("windows-powershell-fallback"),
|
||||
metadata: None,
|
||||
argv: vec![
|
||||
root.path()
|
||||
.join("WindowsApps")
|
||||
.join(shell_name)
|
||||
.to_string_lossy()
|
||||
.into_owned(),
|
||||
"-NoProfile".to_owned(),
|
||||
"-Command".to_owned(),
|
||||
"if (!$env:SystemDrive -or !$env:LOCALAPPDATA -or !$env:USERPROFILE -or !$env:PATH) { throw 'missing Windows defaults' }; Write-Output 'fallback-ok'".to_owned(),
|
||||
],
|
||||
cwd,
|
||||
env_policy: None,
|
||||
shell_snapshot: None,
|
||||
env: HashMap::new(),
|
||||
tty: false,
|
||||
pipe_stdin: false,
|
||||
arg0: None,
|
||||
sandbox: Some(sandbox),
|
||||
enforce_managed_network: false,
|
||||
managed_network: None,
|
||||
network_proxy: None,
|
||||
})
|
||||
.await?;
|
||||
assert_eq!(
|
||||
started.sandbox_type,
|
||||
Some(akode_sandboxing::SandboxType::WindowsMxc)
|
||||
);
|
||||
let (stdout, stderr, exit_code, exited) = collect_process_output_from_events_with_timeout(
|
||||
started.process,
|
||||
Duration::from_secs(/*secs*/ 30),
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(
|
||||
(stdout.trim(), stderr, exit_code, exited),
|
||||
("fallback-ok", String::new(), Some(0), true)
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test_case::test_case(WindowsSandboxSelection::Mxc, akode_sandboxing::SandboxType::WindowsMxc; "mxc")]
|
||||
#[test_case::test_case(WindowsSandboxSelection::Elevated, akode_sandboxing::SandboxType::WindowsRestrictedToken; "elevated")]
|
||||
#[cfg_attr(not(windows), ignore = "requires a native Windows sandbox")]
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
#[serial_test::serial(remote_exec_server)]
|
||||
async fn tmpdir_uses_command_environment_over_rpc(
|
||||
selection: WindowsSandboxSelection,
|
||||
expected_type: akode_sandboxing::SandboxType,
|
||||
) -> Result<()> {
|
||||
if selection == WindowsSandboxSelection::Mxc {
|
||||
crate::skip_if_mxc_unavailable!(Ok(()));
|
||||
}
|
||||
#[cfg(windows)]
|
||||
let _account_guard = if selection == WindowsSandboxSelection::Elevated {
|
||||
let guard = akode_windows_sandbox_test_support::WindowsSandboxAccountTestGuard::acquire()?;
|
||||
// The RPC server re-enters this test executable, as in file_system_windows.
|
||||
let executable = std::env::current_exe()?;
|
||||
let resources = executable
|
||||
.parent()
|
||||
.context("Windows test executable should have a parent directory")?
|
||||
.join("akode-resources");
|
||||
if let Err(error) = std::fs::create_dir_all(&resources)
|
||||
&& !(error.kind() == std::io::ErrorKind::PermissionDenied && resources.is_dir())
|
||||
{
|
||||
return Err(error).context("create Windows sandbox test resources");
|
||||
}
|
||||
for name in ["akode-windows-sandbox-setup", "akode-command-runner"] {
|
||||
let source = akode_utils_cargo_bin::cargo_bin(name)?;
|
||||
let destination = resources.join(std::path::Path::new(name).with_extension("exe"));
|
||||
if let Err(error) = akode_utils_cargo_bin::copy_executable(&source, &destination)
|
||||
&& !(error.kind() == std::io::ErrorKind::PermissionDenied && destination.is_file())
|
||||
{
|
||||
return Err(error).with_context(|| format!("stage Windows sandbox helper {name}"));
|
||||
}
|
||||
}
|
||||
Some(guard)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let root = TempDir::new()?;
|
||||
let command_temp = root.path().join("command temp");
|
||||
let server_temp = root.path().join("server temp");
|
||||
std::fs::create_dir(&command_temp)?;
|
||||
std::fs::create_dir(&server_temp)?;
|
||||
let outside = server_temp.join("outside.txt");
|
||||
std::fs::write(&outside, "original")?;
|
||||
let server = common::exec_server::exec_server_with_env(
|
||||
[
|
||||
("TEMP", server_temp.as_os_str()),
|
||||
("TMP", server_temp.as_os_str()),
|
||||
],
|
||||
&[],
|
||||
)
|
||||
.await?;
|
||||
let environment = Environment::create_for_tests(Some(server.websocket_url().to_owned()))?;
|
||||
let cwd = PathUri::from_host_native_path(root.path())?;
|
||||
let fs = FileSystemSandboxPolicy::restricted(vec![
|
||||
FileSystemSandboxEntry::new(
|
||||
FileSystemPath::Special {
|
||||
value: FileSystemSpecialPath::Root,
|
||||
},
|
||||
FileSystemAccessMode::Read,
|
||||
),
|
||||
FileSystemSandboxEntry::new(
|
||||
FileSystemPath::Special {
|
||||
value: FileSystemSpecialPath::Tmpdir,
|
||||
},
|
||||
FileSystemAccessMode::Write,
|
||||
),
|
||||
]);
|
||||
let mut sandbox = FileSystemSandboxContext::from_permission_profile(
|
||||
PermissionProfile::from_runtime_permissions(&fs, NetworkSandboxPolicy::Restricted),
|
||||
cwd.clone(),
|
||||
);
|
||||
sandbox.windows_sandbox_selection = selection;
|
||||
let env = HashMap::from([
|
||||
("SystemRoot".to_owned(), std::env::var("SystemRoot")?),
|
||||
(
|
||||
"ALLOWED_FILE".to_owned(),
|
||||
format!("\"{}\"", command_temp.join("allowed.txt").display()),
|
||||
),
|
||||
(
|
||||
"OUTSIDE_FILE".to_owned(),
|
||||
format!("\"{}\"", outside.display()),
|
||||
),
|
||||
]);
|
||||
// Raw params have no TEMP. The executor must finish the env policy before
|
||||
// resolving permissions. No inheritance: omitted TMP must not grant server_temp.
|
||||
let mut configured_temp = HashMap::from([(
|
||||
"TEMP".to_owned(),
|
||||
command_temp.to_string_lossy().into_owned(),
|
||||
)]);
|
||||
if selection == WindowsSandboxSelection::Mxc {
|
||||
configured_temp.insert(
|
||||
"TMP".to_owned(),
|
||||
command_temp.to_string_lossy().into_owned(),
|
||||
);
|
||||
}
|
||||
let started = environment
|
||||
.get_exec_backend()
|
||||
.start(ExecParams {
|
||||
process_id: ProcessId::from("windows-sandbox-temp"),
|
||||
metadata: None,
|
||||
argv: vec![
|
||||
r"C:\Windows\System32\cmd.exe".to_owned(),
|
||||
"/D".to_owned(),
|
||||
"/S".to_owned(),
|
||||
"/C".to_owned(),
|
||||
"echo CHILD-TEMP:%TEMP% & echo allowed>%ALLOWED_FILE% & echo modified>%OUTSIDE_FILE% & exit /b 0".to_owned(),
|
||||
],
|
||||
cwd,
|
||||
env_policy: Some(ExecEnvPolicy {
|
||||
inherit: ShellEnvironmentPolicyInherit::None,
|
||||
ignore_default_excludes: false,
|
||||
exclude: Vec::new(),
|
||||
r#set: configured_temp,
|
||||
include_only: Vec::new(),
|
||||
}),
|
||||
shell_snapshot: None,
|
||||
env,
|
||||
tty: false,
|
||||
pipe_stdin: false,
|
||||
arg0: None,
|
||||
sandbox: Some(sandbox),
|
||||
enforce_managed_network: false,
|
||||
managed_network: None,
|
||||
network_proxy: None,
|
||||
})
|
||||
.await?;
|
||||
assert_eq!(started.sandbox_type, Some(expected_type));
|
||||
let (stdout, stderr, code, exited) = collect_process_output_from_events_with_timeout(
|
||||
started.process,
|
||||
Duration::from_secs(/*secs*/ 30),
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(
|
||||
(stdout.trim(), code, exited),
|
||||
(
|
||||
format!("CHILD-TEMP:{}", command_temp.display()).as_str(),
|
||||
Some(0),
|
||||
true
|
||||
),
|
||||
"unexpected launch result, stderr: {stderr}"
|
||||
);
|
||||
assert_eq!(
|
||||
(
|
||||
std::fs::read_to_string(command_temp.join("allowed.txt"))?
|
||||
.trim_end()
|
||||
.to_owned(),
|
||||
std::fs::read_to_string(outside)?
|
||||
),
|
||||
("allowed".to_owned(), "original".to_owned())
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
Reference in New Issue
Block a user