use merry_runtime::{
HostIntegration, PathAccess, PathAccessRule, PathAccessRuleSource, ProcessActionIntent,
ProcessRunnerError,
};
use serde::{Deserialize, Serialize};
use std::{
env, fs,
io::Read,
path::{Path, PathBuf},
process::Command,
sync::atomic::{AtomicBool, Ordering},
};
use crate::process_runner::{WorkspaceProcessEnvironment, process_current_dir};
use crate::resolve_host_path;
mod seatbelt;
const HELPER_ENV: &str = "MERRY_SANDBOX_HELPER";
const POLICY_ENV: &str = "MERRY_SANDBOX_POLICY";
const STDIN_POLICY_SENTINEL: &str = "stdin";
const SETUP_EXIT_CODE: i32 = 126;
static SELF_EXEC_HELPER_REGISTERED: AtomicBool = AtomicBool::new(false);
const READ_ONLY_DIRECTORIES: &[&str] = &[
"/usr",
"/bin",
"/sbin",
"/lib",
"/lib64",
"/opt",
"/nix/store",
"/nix/var/nix/profiles",
"/run/current-system/sw",
"/home/linuxbrew/.linuxbrew",
"/proc",
"/sys",
"/etc/ld.so.conf.d",
"/etc/ssl",
"/etc/ca-certificates",
"/etc/pki",
"/etc/alternatives",
];
const READ_ONLY_FILES: &[&str] = &[
"/etc/ld.so.cache",
"/etc/ld.so.conf",
"/etc/resolv.conf",
"/etc/hosts",
"/etc/nsswitch.conf",
"/etc/protocols",
"/etc/services",
"/etc/gai.conf",
"/etc/mime.types",
"/etc/passwd",
"/etc/group",
"/etc/localtime",
"/etc/gitconfig",
];
const READ_WRITE_DIRECTORIES: &[&str] = &["/tmp", "/var/tmp", "/dev", "/dev/shm", "/dev/pts"];
#[cfg(target_os = "macos")]
const MACOS_READ_ONLY_DIRECTORIES: &[&str] = &[
"/System",
"/Library",
"/private/etc",
"/private/var/select",
"/Applications/Xcode.app",
];
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct SandboxLaunch {
program: String,
args: Vec<String>,
cwd: String,
env: Vec<(String, String)>,
remove_env: Vec<String>,
network: bool,
read_only: Vec<String>,
read_write: Vec<String>,
#[serde(default)]
deny: Vec<String>,
#[serde(default)]
read_only_overrides: Vec<String>,
#[serde(default)]
required_paths: Vec<String>,
}
impl SandboxLaunch {
pub(crate) fn network(&self) -> bool {
self.network
}
#[cfg(test)]
pub(crate) fn read_only(&self) -> &[String] {
&self.read_only
}
#[cfg(test)]
pub(crate) fn read_write(&self) -> &[String] {
&self.read_write
}
#[cfg(test)]
pub(crate) fn env(&self) -> &[(String, String)] {
&self.env
}
pub(crate) fn remove_env(&self) -> &[String] {
&self.remove_env
}
}
#[must_use]
pub fn sandbox_helper_requested() -> bool {
SELF_EXEC_HELPER_REGISTERED.store(true, Ordering::Release);
env::var_os(HELPER_ENV).is_some() && env::var_os(POLICY_ENV).is_some()
}
pub fn sandbox_helper_main() -> ! {
if let Err(error) = apply_and_exec() {
eprintln!("merry-sandbox: {error}");
std::process::exit(SETUP_EXIT_CODE);
}
unreachable!("sandbox helper exec returns only on failure");
}
pub fn probe_workspace_sandbox() -> Result<(), String> {
#[cfg(target_os = "linux")]
{
linux::probe()
}
#[cfg(target_os = "macos")]
{
seatbelt::probe()
}
#[cfg(not(any(target_os = "linux", target_os = "macos")))]
{
Err(format!(
"workspace sandbox is unavailable on {}",
std::env::consts::OS
))
}
}
pub(crate) fn prepare_launch(
intent: &ProcessActionIntent,
cwd_root: &Path,
environment: &WorkspaceProcessEnvironment,
network_allowed: bool,
path_rules: &[PathAccessRule],
required_rules: &[PathAccessRule],
workspace_writable: bool,
) -> Result<SandboxLaunch, ProcessRunnerError> {
let Some((program, args)) = intent.argv().split_first() else {
return Err(ProcessRunnerError::infrastructure(
"validated process argv was unexpectedly empty",
));
};
let cwd = process_current_dir(Some(cwd_root), intent);
let resolved_root = resolve_host_path(cwd_root);
let resolved_cwd = resolve_host_path(&cwd);
if resolved_cwd != resolved_root && !resolved_cwd.starts_with(&resolved_root) {
return Err(ProcessRunnerError::infrastructure(format!(
"process cwd `{}` resolves outside the workspace root `{}`",
cwd.display(),
resolved_root.display()
)));
}
let (read_only, read_write) =
filesystem_grants(cwd_root, environment, path_rules, workspace_writable);
ensure_exclusions_are_enforceable(
cwd_root,
environment.temporary_directory(),
&read_only,
&read_write,
path_rules,
workspace_writable,
)?;
let mut remove_env = vec![HELPER_ENV.to_owned(), POLICY_ENV.to_owned()];
for name in environment.env_isolation().resolve_removed_names() {
if let Some(name) = name.to_str()
&& !name.contains('\0')
&& !remove_env.iter().any(|existing| existing == name)
{
remove_env.push(name.to_owned());
}
}
let mut env = vec![
(
"PATH".to_owned(),
os_to_string(environment.path_value(), "PATH")?,
),
(
"HOME".to_owned(),
path_to_string(environment.home_path(), "HOME")?,
),
(
"TMPDIR".to_owned(),
path_to_string(environment.temporary_directory(), "TMPDIR")?,
),
(
"PWD".to_owned(),
path_to_string(&resolved_cwd, "process cwd")?,
),
];
for (name, value) in environment.environment_overrides() {
let name = os_to_string(name, "sandbox process environment name")?;
let value = os_to_string(value, "sandbox process environment value")?;
env.retain(|(existing, _)| existing != &name);
if !environment
.env_isolation()
.is_explicitly_removed(std::ffi::OsStr::new(&name))
{
remove_env.retain(|existing| existing != &name);
}
env.push((name, value));
}
append_host_integration_env(environment, &mut env, &mut remove_env)?;
let deny = denied_paths(path_rules);
let read_only_overrides = product_read_only_paths(path_rules);
let required_paths = required_permission_review_paths(required_rules, &read_only, &read_write);
Ok(SandboxLaunch {
program: program.clone(),
args: args.to_vec(),
cwd: path_to_string(&resolved_cwd, "process cwd")?,
env,
remove_env,
network: network_allowed,
read_only: strings_from_paths(&read_only)?,
read_write: strings_from_paths(&read_write)?,
deny: strings_from_paths(&deny)?,
read_only_overrides: strings_from_paths(&read_only_overrides)?,
required_paths: strings_from_paths(&required_paths)?,
})
}
pub(crate) fn helper_program() -> Result<PathBuf, ProcessRunnerError> {
let explicit = explicit_helper_program();
let current = env::current_exe().ok();
let self_exec_registered = SELF_EXEC_HELPER_REGISTERED.load(Ordering::Acquire);
#[cfg(target_os = "linux")]
let proc_self_exe_exists = Path::new("/proc/self/exe").exists();
#[cfg(not(target_os = "linux"))]
let proc_self_exe_exists = false;
resolve_helper_program(
explicit,
current.as_deref(),
self_exec_registered,
proc_self_exe_exists,
)
}
fn resolve_helper_program(
explicit: Option<PathBuf>,
current_exe: Option<&Path>,
self_exec_registered: bool,
proc_self_exe_exists: bool,
) -> Result<PathBuf, ProcessRunnerError> {
if let Some(path) = explicit {
return Ok(path);
}
if let Some(current) = current_exe
&& let Some(profile_dir) = cargo_test_profile_dir(current)
{
let helper = profile_dir.join("merry-sandbox-helper");
if helper.is_file() {
return Ok(helper);
}
return Err(ProcessRunnerError::infrastructure(format!(
"sandbox helper binary `{}` was not found; build it first with `cargo build -p merry-process --bin merry-sandbox-helper` or set {HELPER_ENV} (refusing to re-exec test binary `{}`)",
helper.display(),
current.display()
)));
}
if !self_exec_registered {
return Err(ProcessRunnerError::infrastructure(format!(
"workspace sandbox helper is unavailable: current executable did not register `merry_process::sandbox_helper_requested()` at startup; build `merry-sandbox-helper` or set {HELPER_ENV} to a helper binary path"
)));
}
if cfg!(target_os = "linux") && proc_self_exe_exists {
return Ok(PathBuf::from("/proc/self/exe"));
}
if let Some(current) = current_exe {
return Ok(current.to_path_buf());
}
Err(ProcessRunnerError::infrastructure(
"could not resolve current executable for workspace sandbox helper",
))
}
pub(crate) fn explicit_helper_program() -> Option<PathBuf> {
env::var_os(HELPER_ENV)
.filter(|value| Path::new(value).is_file())
.map(PathBuf::from)
}
#[cfg(target_os = "macos")]
pub(crate) fn direct_seatbelt_command(launch: &SandboxLaunch) -> tokio::process::Command {
seatbelt::build_tokio_command(launch)
}
pub(crate) fn encode_policy(launch: &SandboxLaunch) -> Result<Vec<u8>, ProcessRunnerError> {
serde_json::to_vec(launch).map_err(|source| {
ProcessRunnerError::infrastructure(format!("failed to encode sandbox policy: {source}"))
})
}
pub(crate) fn policy_env_name() -> &'static str {
POLICY_ENV
}
pub(crate) fn policy_stdin_sentinel() -> &'static str {
STDIN_POLICY_SENTINEL
}
pub(crate) fn helper_env_name() -> &'static str {
HELPER_ENV
}
pub(crate) fn setup_failure(stderr: &[u8]) -> Option<String> {
let text = String::from_utf8_lossy(stderr);
text.lines()
.find(|line| line.starts_with("merry-sandbox:"))
.map(|line| line.trim().to_owned())
}
fn apply_and_exec() -> Result<(), String> {
let policy_source =
env::var(POLICY_ENV).map_err(|_| "sandbox helper was started without a policy")?;
if policy_source != STDIN_POLICY_SENTINEL {
return Err("sandbox helper only accepts policies streamed over stdin".to_owned());
}
let mut bytes = Vec::new();
std::io::stdin()
.read_to_end(&mut bytes)
.map_err(|source| format!("failed to read sandbox policy from stdin: {source}"))?;
redirect_stdin_to_dev_null()?;
let launch: SandboxLaunch = serde_json::from_slice(&bytes)
.map_err(|source| format!("sandbox policy is invalid: {source}"))?;
apply_confinement(&launch)?;
let mut command = Command::new(&launch.program);
command.args(&launch.args).current_dir(&launch.cwd);
for (name, value) in &launch.env {
command.env(name, value);
}
for name in &launch.remove_env {
command.env_remove(name);
}
command.env_remove(HELPER_ENV);
command.env_remove(POLICY_ENV);
let error = command.exec_error();
Err(format!("failed to execute `{}`: {error}", launch.program))
}
fn redirect_stdin_to_dev_null() -> Result<(), String> {
let dev_null = fs::File::open("/dev/null")
.map_err(|source| format!("failed to open /dev/null for sandbox stdin: {source}"))?;
rustix::stdio::dup2_stdin(&dev_null)
.map_err(|source| format!("failed to redirect sandbox stdin to /dev/null: {source}"))?;
Ok(())
}
fn apply_confinement(launch: &SandboxLaunch) -> Result<(), String> {
#[cfg(target_os = "linux")]
{
linux::apply(launch)
}
#[cfg(target_os = "macos")]
{
seatbelt::apply(launch)
}
#[cfg(not(any(target_os = "linux", target_os = "macos")))]
{
let _ = launch;
Err(format!(
"workspace sandbox is unavailable on {}",
std::env::consts::OS
))
}
}
pub(crate) fn check_sandbox_rules(
cwd_root: &Path,
environment: &WorkspaceProcessEnvironment,
path_rules: &[PathAccessRule],
workspace_writable: bool,
) -> Result<(), ProcessRunnerError> {
let (read_only, read_write) =
filesystem_grants(cwd_root, environment, path_rules, workspace_writable);
ensure_exclusions_are_enforceable(
cwd_root,
environment.temporary_directory(),
&read_only,
&read_write,
path_rules,
workspace_writable,
)
}
fn filesystem_grants(
cwd_root: &Path,
environment: &WorkspaceProcessEnvironment,
path_rules: &[PathAccessRule],
workspace_writable: bool,
) -> (Vec<PathBuf>, Vec<PathBuf>) {
let mut read_write = Vec::new();
let mut read_only = Vec::new();
if workspace_writable {
push_directory(&mut read_write, cwd_root);
} else {
push_directory(&mut read_only, cwd_root);
}
for path in READ_WRITE_DIRECTORIES {
let path = Path::new(path);
if path.exists() || !cfg!(target_os = "macos") {
push_directory(&mut read_write, path);
}
}
push_directory(&mut read_write, environment.temporary_directory());
for path in READ_ONLY_DIRECTORIES {
push_if_exists(&mut read_only, Path::new(path));
}
#[cfg(target_os = "macos")]
for path in MACOS_READ_ONLY_DIRECTORIES {
push_if_exists(&mut read_only, Path::new(path));
}
for path in READ_ONLY_FILES {
push_if_exists(&mut read_only, Path::new(path));
}
let xdg_config_home = env::var_os("XDG_CONFIG_HOME").map(PathBuf::from);
push_git_user_files(
&mut read_only,
environment.home_path(),
xdg_config_home.as_deref(),
path_rules,
);
for rule in path_rules {
if rule.review_required() || rule.access() == PathAccess::Deny {
continue;
}
let path = resolve_host_path(rule.path());
if rule.source() == PathAccessRuleSource::DefaultDevelopmentBaseline && !path.exists() {
continue;
}
match rule.access() {
PathAccess::ReadWrite => push_path(&mut read_write, &path),
PathAccess::ReadOnly => push_path(&mut read_only, &path),
PathAccess::Deny => {}
}
}
for path in environment.sandbox_socket_paths() {
let path = resolve_host_path(&path);
if !blocked_by_policy(&path, path_rules) {
push_path(&mut read_write, &path);
}
}
for path in environment.ssh_known_hosts_paths() {
if !blocked_by_policy(&path, path_rules) {
push_if_exists(&mut read_only, &path);
}
}
for path in environment.gpg_public_keyrings() {
if !blocked_by_policy(&path, path_rules) {
push_if_exists(&mut read_only, &path);
}
}
(read_only, read_write)
}
fn blocked_by_policy(path: &Path, rules: &[PathAccessRule]) -> bool {
let path = resolve_host_path(path);
rules.iter().any(|rule| {
let blocked = rule.access() == PathAccess::Deny || rule.review_required();
if !blocked {
return false;
}
let rule_path = resolve_host_path(rule.path());
path == rule_path || path.starts_with(&rule_path)
})
}
fn denied_paths(rules: &[PathAccessRule]) -> Vec<PathBuf> {
let mut paths = Vec::new();
for rule in rules {
if rule.access() == PathAccess::Deny && !rule.review_required() {
push_path(&mut paths, &resolve_host_path(rule.path()));
}
}
paths
}
fn product_read_only_paths(rules: &[PathAccessRule]) -> Vec<PathBuf> {
let mut paths = Vec::new();
for rule in rules {
if rule.access() == PathAccess::ReadOnly
&& rule.source() == PathAccessRuleSource::ProductReadOnly
&& !rule.review_required()
{
push_path(&mut paths, &resolve_host_path(rule.path()));
}
}
paths
}
fn ensure_exclusions_are_enforceable(
workspace: &Path,
temporary_directory: &Path,
read_only: &[PathBuf],
read_write: &[PathBuf],
rules: &[PathAccessRule],
workspace_writable: bool,
) -> Result<(), ProcessRunnerError> {
let mut conflicts = Vec::new();
for rule in rules {
let excludes = rule.access() == PathAccess::Deny || rule.review_required();
if !excludes {
continue;
}
let path = resolve_host_path(rule.path());
let covered = read_write
.iter()
.chain(read_only.iter())
.find(|grant| path == **grant || path.starts_with(grant));
if let Some(grant) = covered {
if rule.review_required()
&& grant == &path
&& rules.iter().any(|candidate| {
candidate.source() == PathAccessRuleSource::PermissionReview
&& !candidate.review_required()
&& candidate.access() != PathAccess::Deny
&& resolve_host_path(candidate.path()) == path
})
{
continue;
}
if rule.source() == PathAccessRuleSource::ProductPrivate && !rule.review_required() {
tracing::warn!(
private_path = %path.display(),
allowed_path = %grant.display(),
"allowed sandbox directory covers Merry private directory; continuing per user grant (Linux Landlock cannot exclude subdirectories from an allowed parent)"
);
continue;
}
conflicts.push(sandbox_rule_conflict(
rule,
&path,
grant,
workspace,
temporary_directory,
rules,
workspace_writable,
));
}
}
if conflicts.is_empty() {
Ok(())
} else {
Err(ProcessRunnerError::infrastructure(conflicts.join(" ")))
}
}
fn sandbox_rule_conflict(
rule: &PathAccessRule,
path: &Path,
grant: &Path,
workspace: &Path,
temporary_directory: &Path,
rules: &[PathAccessRule],
workspace_writable: bool,
) -> String {
format!(
"conflicting sandbox rules: {} is inside {}. {}",
blocked_rule_label(rule, path),
allowed_directory_label(
grant,
workspace,
temporary_directory,
rules,
workspace_writable
),
conflict_fix(rule, path, grant, workspace, rules, workspace_writable)
)
}
fn blocked_rule_label(rule: &PathAccessRule, path: &Path) -> String {
if rule.review_required() {
return format!("review_paths entry `{}`", path.display());
}
match rule.source() {
PathAccessRuleSource::TrustedGlobalConfig => {
format!("deny_paths entry `{}`", path.display())
}
_ => format!("denied path `{}`", path.display()),
}
}
fn allowed_directory_label(
grant: &Path,
workspace: &Path,
temporary_directory: &Path,
rules: &[PathAccessRule],
workspace_writable: bool,
) -> String {
if grant == resolve_host_path(workspace) {
return if workspace_writable {
format!("the writable workspace `{}`", grant.display())
} else {
format!("the read-only workspace `{}`", grant.display())
};
}
if READ_WRITE_DIRECTORIES.iter().any(|directory| {
let directory = Path::new(directory);
directory == grant || resolve_host_path(directory) == grant
}) {
return format!(
"`{}`, which every sandboxed command can write",
grant.display()
);
}
if let Some(rule) = rules.iter().find(|rule| {
!rule.review_required()
&& rule.access() != PathAccess::Deny
&& resolve_host_path(rule.path()) == grant
}) {
return match (rule.source(), rule.access()) {
(PathAccessRuleSource::TrustedGlobalConfig, PathAccess::ReadWrite) => {
format!("readwrite_paths entry `{}`", grant.display())
}
(PathAccessRuleSource::TrustedGlobalConfig, PathAccess::ReadOnly) => {
format!("readonly_paths entry `{}`", grant.display())
}
(PathAccessRuleSource::DefaultDevelopmentBaseline, PathAccess::ReadWrite) => {
format!("the writable build directory `{}`", grant.display())
}
(PathAccessRuleSource::DefaultDevelopmentBaseline, PathAccess::ReadOnly) => {
format!("the readable toolchain directory `{}`", grant.display())
}
(PathAccessRuleSource::PermissionReview, PathAccess::ReadWrite) => {
format!("the approved writable path `{}`", grant.display())
}
(PathAccessRuleSource::PermissionReview, PathAccess::ReadOnly) => {
format!("the approved readable path `{}`", grant.display())
}
(PathAccessRuleSource::DurableMemory, PathAccess::ReadWrite) => {
format!("the writable memory directory `{}`", grant.display())
}
(PathAccessRuleSource::ProductConfig, PathAccess::ReadWrite) => {
format!(
"Merry's writable config/skills directory `{}`",
grant.display()
)
}
(PathAccessRuleSource::ProductReadOnly, PathAccess::ReadOnly) => {
format!(
"Merry's read-only config/state directory `{}`",
grant.display()
)
}
_ => format!("allowed directory `{}`", grant.display()),
};
}
if grant == resolve_host_path(temporary_directory) {
return format!(
"TMPDIR `{}`, which every sandboxed command can write",
grant.display()
);
}
format!("allowed directory `{}`", grant.display())
}
fn conflict_fix(
rule: &PathAccessRule,
path: &Path,
grant: &Path,
workspace: &Path,
rules: &[PathAccessRule],
workspace_writable: bool,
) -> String {
let key = if rule.review_required() {
"review_paths"
} else {
"deny_paths"
};
if grant == resolve_host_path(workspace) {
let reason = if workspace_writable {
"The workspace stays writable, so a path inside it cannot be blocked."
} else {
"The workspace is granted read-only, so a path inside it cannot be blocked."
};
return format!("Remove `{}` from {key}. {reason}", path.display());
}
let parent_is_configured_write = rules.iter().any(|candidate| {
candidate.source() == PathAccessRuleSource::TrustedGlobalConfig
&& candidate.access() == PathAccess::ReadWrite
&& !candidate.review_required()
&& resolve_host_path(candidate.path()) == grant
});
if rule.review_required() && parent_is_configured_write {
return format!(
"Remove `{}` from review_paths, or remove `{}` from readwrite_paths.",
path.display(),
grant.display()
);
}
format!(
"Remove `{}` from {key}. It has to be outside `{}`.",
path.display(),
grant.display()
)
}
fn required_permission_review_paths(
rules: &[PathAccessRule],
read_only: &[PathBuf],
read_write: &[PathBuf],
) -> Vec<PathBuf> {
let mut required = Vec::new();
for rule in rules {
if rule.source() != PathAccessRuleSource::PermissionReview
|| rule.review_required()
|| rule.access() == PathAccess::Deny
{
continue;
}
let path = resolve_host_path(rule.path());
let covered_by_strict_parent = match rule.access() {
PathAccess::ReadWrite => read_write
.iter()
.any(|grant| *grant != path && path.starts_with(grant)),
PathAccess::ReadOnly => read_write
.iter()
.chain(read_only.iter())
.any(|grant| *grant != path && path.starts_with(grant)),
PathAccess::Deny => false,
};
if !covered_by_strict_parent {
push_path(&mut required, &path);
}
}
required
}
fn append_host_integration_env(
environment: &WorkspaceProcessEnvironment,
env: &mut Vec<(String, String)>,
remove_env: &mut Vec<String>,
) -> Result<(), ProcessRunnerError> {
if !environment.integration_enabled(HostIntegration::SshAgent) {
remove_env.push("SSH_AUTH_SOCK".to_owned());
}
if !environment.integration_enabled(HostIntegration::SessionBus) {
remove_env.push("DBUS_SESSION_BUS_ADDRESS".to_owned());
}
if !environment.integration_enabled(HostIntegration::GpgAgent) {
remove_env.push("GNUPGHOME".to_owned());
}
for (name, value) in environment.integration_environment() {
env.retain(|(existing, _)| existing != &name);
remove_env.retain(|existing| existing != &name);
env.push((name, value));
}
Ok(())
}
fn push_git_user_files(
read_only: &mut Vec<PathBuf>,
home: &Path,
xdg_config_home: Option<&Path>,
rules: &[PathAccessRule],
) {
for path in git_user_file_candidates(home, absolute_xdg_config_home(xdg_config_home)) {
if blocked_by_policy(&path, rules) {
continue;
}
push_if_exists(read_only, &path);
}
}
fn git_user_file_candidates(home: &Path, xdg_config_home: Option<&Path>) -> Vec<PathBuf> {
let mut paths = vec![home.join(".gitconfig")];
for root in [
Some(home.join(".config")),
xdg_config_home.map(Path::to_path_buf),
]
.into_iter()
.flatten()
{
let git = root.join("git");
for name in ["config", "ignore", "attributes"] {
paths.push(git.join(name));
}
}
paths
}
fn absolute_xdg_config_home(value: Option<&Path>) -> Option<&Path> {
value.filter(|path| path.is_absolute())
}
fn push_directory(paths: &mut Vec<PathBuf>, path: &Path) {
push_path(paths, &resolve_host_path(path));
}
fn push_if_exists(paths: &mut Vec<PathBuf>, path: &Path) {
if path.exists() {
push_path(paths, &resolve_host_path(path));
}
}
fn push_path(paths: &mut Vec<PathBuf>, path: &Path) {
if path.as_os_str().is_empty() || paths.iter().any(|existing| existing == path) {
return;
}
paths.push(path.to_path_buf());
}
fn strings_from_paths(paths: &[PathBuf]) -> Result<Vec<String>, ProcessRunnerError> {
paths
.iter()
.map(|path| path_to_string(path, "sandbox path"))
.collect()
}
fn path_to_string(path: &Path, label: &str) -> Result<String, ProcessRunnerError> {
path.to_str()
.filter(|value| !value.chars().any(char::is_control))
.map(ToOwned::to_owned)
.ok_or_else(|| {
ProcessRunnerError::infrastructure(format!(
"{label} `{}` must be valid UTF-8 without control characters",
path.display()
))
})
}
fn os_to_string(value: &std::ffi::OsStr, label: &str) -> Result<String, ProcessRunnerError> {
value
.to_str()
.filter(|text| !text.contains('\0'))
.map(ToOwned::to_owned)
.ok_or_else(|| ProcessRunnerError::infrastructure(format!("{label} must be valid UTF-8")))
}
fn cargo_test_profile_dir(current: &Path) -> Option<&Path> {
let parent = current.parent()?;
if parent.file_name()? == "deps" {
parent.parent()
} else if parent.file_name()? == "out" {
let build_dir = parent.parent()?.parent()?.parent()?;
if build_dir.file_name()? != "build" {
return None;
}
build_dir.parent()
} else {
None
}
}
trait CommandExec {
fn exec_error(&mut self) -> std::io::Error;
}
impl CommandExec for Command {
fn exec_error(&mut self) -> std::io::Error {
#[cfg(unix)]
{
use std::os::unix::process::CommandExt;
self.exec()
}
#[cfg(not(unix))]
{
std::io::Error::other("workspace sandbox helper requires a Unix host")
}
}
}
#[cfg(target_os = "linux")]
mod linux;
#[cfg(all(test, any(target_os = "linux", target_os = "macos")))]
mod tests;