mod baseline;
#[cfg(any(target_os = "linux", target_os = "macos"))]
mod confinement;
#[cfg(not(any(target_os = "linux", target_os = "macos")))]
#[path = "confinement/unsupported.rs"]
mod confinement;
mod gpg;
mod host_path;
mod host_resources;
mod process_runner;
pub use baseline::{default_development_path_rules, default_development_path_rules_with_env};
pub use confinement::{probe_workspace_sandbox, sandbox_helper_main, sandbox_helper_requested};
pub use gpg::GpgAgentSockets;
pub use host_path::resolve_host_path;
pub use host_resources::{HostPathKind, HostPathMetadata, ssh_known_hosts};
pub use process_runner::{
DEFAULT_REMOVED_ENV_PREFIX, ProcessEnvIsolation, ProcessSessionPermissions, TokioProcessRunner,
action_process_path,
};
#[cfg(any(target_os = "linux", target_os = "macos"))]
pub use process_runner::{
WorkspaceProcessEnvironment, WorkspaceProcessRunner, WorkspaceProcessRunnerFactory,
};
use merry_core::HostPathPolicy;
use merry_runtime::{
AcceptedLocalWorkspaceProcessAdmission, HostIntegration, PathAccess, PathAccessRule,
PathAccessRuleSource, PermissionRequest, PermissionedProcessRunnerFactory, ProcessRunner,
ProcessRunnerError, ProcessSessionPermissionView,
};
use std::{
ffi::OsString,
path::{Path, PathBuf},
sync::Arc,
};
use thiserror::Error;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ProcessBackendMode {
Host,
Isolated,
}
#[derive(Debug, Error, Clone, PartialEq, Eq)]
pub enum ProcessBackendError {
#[error("process backend configuration failed: {source}")]
Runner {
#[source]
source: ProcessRunnerError,
},
#[error(
"isolated local process backend is unavailable on target operating system `{target_os}`"
)]
UnsupportedIsolation {
target_os: &'static str,
},
}
impl From<ProcessRunnerError> for ProcessBackendError {
fn from(source: ProcessRunnerError) -> Self {
Self::Runner { source }
}
}
#[derive(Clone)]
pub struct ProcessSession {
admission: AcceptedLocalWorkspaceProcessAdmission,
runner: Arc<dyn ProcessRunner>,
permissioned_factory: Arc<dyn PermissionedProcessRunnerFactory>,
permission_view: Option<ProcessSessionPermissionView>,
}
impl ProcessSession {
#[must_use]
pub fn from_parts(
admission: AcceptedLocalWorkspaceProcessAdmission,
runner: Arc<dyn ProcessRunner>,
permissioned_factory: Arc<dyn PermissionedProcessRunnerFactory>,
) -> Self {
Self {
admission,
runner,
permissioned_factory,
permission_view: None,
}
}
#[must_use]
pub fn with_permission_view(mut self, view: ProcessSessionPermissionView) -> Self {
self.permission_view = Some(view);
self
}
#[must_use]
pub const fn admission(&self) -> AcceptedLocalWorkspaceProcessAdmission {
self.admission
}
#[must_use]
pub fn runner(&self) -> Arc<dyn ProcessRunner> {
Arc::clone(&self.runner)
}
#[must_use]
pub fn permissioned_factory(&self) -> Arc<dyn PermissionedProcessRunnerFactory> {
Arc::clone(&self.permissioned_factory)
}
#[must_use]
pub fn permission_view(&self) -> Option<ProcessSessionPermissionView> {
self.permission_view.clone()
}
}
#[derive(Debug, Clone)]
pub struct ProcessSessionRequest {
workspace_root: Option<PathBuf>,
workspace_writable: bool,
inherited_permissions: Option<ProcessSessionPermissionView>,
extra_path_rules: Vec<PathAccessRule>,
}
impl Default for ProcessSessionRequest {
fn default() -> Self {
Self {
workspace_root: None,
workspace_writable: true,
inherited_permissions: None,
extra_path_rules: Vec::new(),
}
}
}
impl ProcessSessionRequest {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn with_workspace_root(mut self, workspace_root: impl Into<PathBuf>) -> Self {
self.workspace_root = Some(workspace_root.into());
self
}
#[must_use]
pub fn read_only_workspace(mut self) -> Self {
self.workspace_writable = false;
self
}
#[must_use]
pub fn with_workspace_writable(mut self, writable: bool) -> Self {
self.workspace_writable = writable;
self
}
#[must_use]
pub fn with_inherited_permissions(mut self, view: ProcessSessionPermissionView) -> Self {
self.inherited_permissions = Some(view);
self
}
#[must_use]
pub fn with_extra_path_rules(
mut self,
rules: impl IntoIterator<Item = PathAccessRule>,
) -> Self {
self.extra_path_rules = rules.into_iter().collect();
self
}
#[must_use]
pub fn workspace_root(&self) -> Option<&Path> {
self.workspace_root.as_deref()
}
#[must_use]
pub const fn workspace_writable(&self) -> bool {
self.workspace_writable
}
#[must_use]
pub fn inherited_permissions(&self) -> Option<&ProcessSessionPermissionView> {
self.inherited_permissions.as_ref()
}
#[must_use]
pub fn extra_path_rules(&self) -> &[PathAccessRule] {
&self.extra_path_rules
}
}
pub trait ProcessBackend: Send + Sync {
fn new_session(&self) -> ProcessSession;
fn new_session_with(
&self,
_request: ProcessSessionRequest,
) -> Result<ProcessSession, ProcessBackendError> {
Ok(self.new_session())
}
}
#[derive(Debug, Clone)]
pub struct ProcessBackendOptions {
path_rules: Vec<PathAccessRule>,
network_requests_allowed: bool,
workspace_writable: bool,
host_integrations: Vec<HostIntegration>,
gpg_agent_sockets: Option<GpgAgentSockets>,
environment_overrides: Vec<(OsString, OsString)>,
env_isolation: ProcessEnvIsolation,
}
impl Default for ProcessBackendOptions {
fn default() -> Self {
Self {
path_rules: Vec::new(),
network_requests_allowed: true,
workspace_writable: true,
host_integrations: Vec::new(),
gpg_agent_sockets: None,
environment_overrides: Vec::new(),
env_isolation: ProcessEnvIsolation::default(),
}
}
}
impl ProcessBackendOptions {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn with_path_rules(mut self, path_rules: impl IntoIterator<Item = PathAccessRule>) -> Self {
self.path_rules = path_rules.into_iter().collect();
self
}
#[must_use]
pub fn extend_path_rules(
mut self,
path_rules: impl IntoIterator<Item = PathAccessRule>,
) -> Self {
self.path_rules.extend(path_rules);
self
}
#[must_use]
pub fn with_default_development_baseline(self, home: &Path) -> Self {
self.extend_path_rules(default_development_path_rules(home))
}
#[must_use]
pub fn with_host_path_policy(mut self, policy: &HostPathPolicy) -> Self {
for path in policy.product_writable_config() {
self.path_rules.push(PathAccessRule::new(
path.clone(),
PathAccess::ReadWrite,
PathAccessRuleSource::ProductConfig,
));
}
if let Some(memory_root) = policy.durable_memory_root() {
self.path_rules.push(PathAccessRule::new(
memory_root.to_path_buf(),
PathAccess::ReadWrite,
PathAccessRuleSource::DurableMemory,
));
}
for path in policy.product_readonly() {
self.path_rules.push(PathAccessRule::new(
path.clone(),
PathAccess::ReadOnly,
PathAccessRuleSource::ProductReadOnly,
));
}
for path in policy.denied() {
self.path_rules.push(PathAccessRule::new(
path.clone(),
PathAccess::Deny,
PathAccessRuleSource::ProductPrivate,
));
}
self
}
#[must_use]
pub fn with_network_requests_allowed(mut self, allowed: bool) -> Self {
self.network_requests_allowed = allowed;
self
}
#[must_use]
pub fn read_only_workspace(mut self) -> Self {
self.workspace_writable = false;
self
}
#[must_use]
pub fn with_host_integrations(
mut self,
host_integrations: impl IntoIterator<Item = HostIntegration>,
) -> Self {
self.host_integrations = host_integrations.into_iter().collect();
self
}
#[must_use]
pub fn with_gpg_agent_sockets(mut self, sockets: GpgAgentSockets) -> Self {
self.gpg_agent_sockets = Some(sockets);
self
}
#[must_use]
pub fn with_environment_overrides(
mut self,
environment_overrides: impl IntoIterator<Item = (OsString, OsString)>,
) -> Self {
self.environment_overrides = environment_overrides.into_iter().collect();
self
}
#[must_use]
pub fn with_env_isolation(mut self, env_isolation: ProcessEnvIsolation) -> Self {
self.env_isolation = env_isolation;
self
}
#[must_use]
pub fn path_rules(&self) -> &[PathAccessRule] {
&self.path_rules
}
#[must_use]
pub fn network_requests_allowed(&self) -> bool {
self.network_requests_allowed
}
#[must_use]
pub fn host_integrations(&self) -> &[HostIntegration] {
&self.host_integrations
}
#[must_use]
pub fn environment_overrides(&self) -> &[(OsString, OsString)] {
&self.environment_overrides
}
}
#[derive(Clone)]
pub struct LocalProcessBackend {
new_session: Arc<dyn Fn() -> ProcessSession + Send + Sync>,
new_session_with: Arc<
dyn Fn(ProcessSessionRequest) -> Result<ProcessSession, ProcessBackendError> + Send + Sync,
>,
}
impl LocalProcessBackend {
#[must_use]
pub fn from_session(session: ProcessSession) -> Self {
let child_session = session.clone();
let scoped_session = session;
Self {
new_session: Arc::new(move || child_session.clone()),
new_session_with: Arc::new(move |_request| Ok(scoped_session.clone())),
}
}
#[cfg(test)]
fn from_parts(
admission: AcceptedLocalWorkspaceProcessAdmission,
runner: Arc<dyn ProcessRunner>,
permissioned_factory: Arc<dyn PermissionedProcessRunnerFactory>,
) -> Self {
Self::from_session(ProcessSession::from_parts(
admission,
runner,
permissioned_factory,
))
}
pub fn new(
workspace_root: impl Into<PathBuf>,
mode: ProcessBackendMode,
options: ProcessBackendOptions,
) -> Result<Self, ProcessBackendError> {
Self::new_with_shared_state(workspace_root, mode, options, None, None)
}
fn new_with_shared_state(
workspace_root: impl Into<PathBuf>,
mode: ProcessBackendMode,
options: ProcessBackendOptions,
shared_background: Option<crate::process_runner::BackgroundSupervisor>,
shared_permissions: Option<ProcessSessionPermissions>,
) -> Result<Self, ProcessBackendError> {
match mode {
ProcessBackendMode::Host => Self::unrestricted_with_shared_state(
workspace_root,
options,
shared_background,
shared_permissions,
),
ProcessBackendMode::Isolated => Self::sandboxed_with_shared_state(
workspace_root,
options,
shared_background,
shared_permissions,
),
}
}
pub fn unrestricted(
workspace_root: impl Into<PathBuf>,
options: ProcessBackendOptions,
) -> Result<Self, ProcessBackendError> {
Self::unrestricted_with_shared_state(workspace_root, options, None, None)
}
fn unrestricted_with_shared_state(
workspace_root: impl Into<PathBuf>,
options: ProcessBackendOptions,
shared_background: Option<crate::process_runner::BackgroundSupervisor>,
shared_permissions: Option<ProcessSessionPermissions>,
) -> Result<Self, ProcessBackendError> {
let workspace_root = workspace_root.into();
let environment_overrides = options.environment_overrides;
let env_isolation = options.env_isolation;
let mut runner = TokioProcessRunner::new_at_workspace_root(workspace_root.clone())
.with_env_isolation(env_isolation.clone())?
.with_environment_overrides(environment_overrides.clone())?;
if let Some(background) = shared_background {
runner = runner.with_background(background);
}
let runner = Arc::new(runner);
let permissioned_factory = Arc::new(UnrestrictedPermissionedProcessRunnerFactory::new(
Arc::clone(&runner) as Arc<dyn ProcessRunner>,
));
let mut default_session = ProcessSession::from_parts(
AcceptedLocalWorkspaceProcessAdmission::accept_host(),
runner,
permissioned_factory,
);
if let Some(permissions) = shared_permissions {
default_session = default_session.with_permission_view(permissions.view());
}
let fallback_session = default_session.clone();
Ok(Self {
new_session: Arc::new(move || default_session.clone()),
new_session_with: Arc::new(move |request| {
let Some(root_override) = request.workspace_root else {
return Ok(fallback_session.clone());
};
let runner = Arc::new(
TokioProcessRunner::new_at_workspace_root(root_override)
.with_env_isolation(env_isolation.clone())?
.with_environment_overrides(environment_overrides.clone())?,
);
let permissioned_factory =
Arc::new(UnrestrictedPermissionedProcessRunnerFactory::new(
Arc::clone(&runner) as Arc<dyn ProcessRunner>,
));
Ok(ProcessSession::from_parts(
AcceptedLocalWorkspaceProcessAdmission::accept_host(),
runner,
permissioned_factory,
))
}),
})
}
pub fn sandboxed(
workspace_root: impl Into<PathBuf>,
options: ProcessBackendOptions,
) -> Result<Self, ProcessBackendError> {
Self::sandboxed_with_shared_state(workspace_root, options, None, None)
}
#[cfg(any(target_os = "linux", target_os = "macos"))]
fn sandboxed_with_shared_state(
workspace_root: impl Into<PathBuf>,
options: ProcessBackendOptions,
shared_background: Option<crate::process_runner::BackgroundSupervisor>,
shared_permissions: Option<ProcessSessionPermissions>,
) -> Result<Self, ProcessBackendError> {
let workspace_root = workspace_root.into();
let mut environment = WorkspaceProcessEnvironment::from_current_process()
.with_host_integrations(options.host_integrations)
.with_env_isolation(options.env_isolation)?
.with_overrides(options.environment_overrides)?
.validate_for_workspace(&workspace_root)?;
if let Some(sockets) = options.gpg_agent_sockets {
environment = environment.with_gpg_agent_sockets(sockets);
}
let mut rules_runner =
WorkspaceProcessRunner::new_at_workspace_root(workspace_root.clone())
.with_environment(environment.clone())
.with_path_rules(options.path_rules.iter().cloned());
if !options.workspace_writable {
rules_runner = rules_runner.read_only_workspace();
}
rules_runner.ensure_sandbox_rules()?;
Ok(Self::from_sandboxed_parts(
workspace_root,
environment,
options.path_rules,
options.network_requests_allowed,
options.workspace_writable,
shared_background,
shared_permissions,
))
}
#[cfg(not(any(target_os = "linux", target_os = "macos")))]
fn sandboxed_with_shared_state(
workspace_root: impl Into<PathBuf>,
options: ProcessBackendOptions,
shared_background: Option<crate::process_runner::BackgroundSupervisor>,
shared_permissions: Option<ProcessSessionPermissions>,
) -> Result<Self, ProcessBackendError> {
let _ = (
workspace_root.into(),
options,
shared_background,
shared_permissions,
);
Err(ProcessBackendError::UnsupportedIsolation {
target_os: std::env::consts::OS,
})
}
#[cfg(any(target_os = "linux", target_os = "macos"))]
fn from_sandboxed_parts(
workspace_root: PathBuf,
environment: WorkspaceProcessEnvironment,
path_rules: Vec<PathAccessRule>,
network_requests_allowed: bool,
workspace_writable: bool,
shared_background: Option<crate::process_runner::BackgroundSupervisor>,
shared_permissions: Option<ProcessSessionPermissions>,
) -> Self {
let child_workspace_root = workspace_root.clone();
let child_environment = environment.clone();
let child_path_rules = path_rules.clone();
let scoped_workspace_root = workspace_root;
let scoped_environment = environment;
let scoped_path_rules = path_rules;
Self {
new_session: Arc::new(move || {
Self::sandboxed_session(
&child_workspace_root,
&child_environment,
&child_path_rules,
network_requests_allowed,
workspace_writable,
shared_permissions.clone().unwrap_or_default(),
shared_background.clone().unwrap_or_default(),
)
}),
new_session_with: Arc::new(move |request| {
let target_root = request
.workspace_root
.as_deref()
.unwrap_or(&scoped_workspace_root);
let effective_writable = workspace_writable && request.workspace_writable;
let session_permissions = match request.inherited_permissions.as_ref() {
Some(view) => ProcessSessionPermissions::from_inherited_view(view)?,
None => ProcessSessionPermissions::new(),
};
let mut combined_rules =
Vec::with_capacity(scoped_path_rules.len() + request.extra_path_rules.len());
combined_rules.extend(scoped_path_rules.iter().cloned());
combined_rules.extend(request.extra_path_rules);
let validated_env = if request.workspace_root.is_some() {
scoped_environment
.clone()
.validate_for_workspace(target_root)?
} else {
scoped_environment.clone()
};
if request.workspace_root.is_some() || !combined_rules.is_empty() {
let mut rules_runner =
WorkspaceProcessRunner::new_at_workspace_root(target_root)
.with_environment(validated_env.clone())
.with_path_rules(combined_rules.iter().cloned());
if !effective_writable {
rules_runner = rules_runner.read_only_workspace();
}
rules_runner.ensure_sandbox_rules()?;
}
Ok(Self::sandboxed_session(
target_root,
&validated_env,
&combined_rules,
network_requests_allowed,
effective_writable,
session_permissions,
crate::process_runner::BackgroundSupervisor::new(),
))
}),
}
}
#[cfg(any(target_os = "linux", target_os = "macos"))]
fn sandboxed_session(
workspace_root: &Path,
environment: &WorkspaceProcessEnvironment,
path_rules: &[PathAccessRule],
network_requests_allowed: bool,
workspace_writable: bool,
session_permissions: ProcessSessionPermissions,
background: crate::process_runner::BackgroundSupervisor,
) -> ProcessSession {
let permission_view = session_permissions.view();
let mut runner = WorkspaceProcessRunner::new_at_workspace_root(workspace_root)
.with_environment(environment.clone())
.with_path_rules(path_rules.iter().cloned())
.with_background(background.clone());
let mut permissioned_factory =
WorkspaceProcessRunnerFactory::new_at_workspace_root(workspace_root)
.with_environment(environment.clone())
.with_path_rules(path_rules.iter().cloned())
.with_network_requests_allowed(network_requests_allowed)
.with_background(background);
if !workspace_writable {
runner = runner.read_only_workspace();
permissioned_factory = permissioned_factory.read_only_workspace();
}
let runner = runner.with_session_permissions(session_permissions.clone());
let permissioned_factory =
permissioned_factory.with_session_permissions(session_permissions);
ProcessSession::from_parts(
AcceptedLocalWorkspaceProcessAdmission::accept_local_workspace(),
Arc::new(runner),
Arc::new(permissioned_factory),
)
.with_permission_view(permission_view)
}
}
impl ProcessBackend for LocalProcessBackend {
fn new_session(&self) -> ProcessSession {
(self.new_session)()
}
fn new_session_with(
&self,
request: ProcessSessionRequest,
) -> Result<ProcessSession, ProcessBackendError> {
(self.new_session_with)(request)
}
}
pub struct LiveProcessBackend {
state: std::sync::RwLock<LocalProcessBackend>,
session_background: crate::process_runner::BackgroundSupervisor,
session_permissions: ProcessSessionPermissions,
}
impl LiveProcessBackend {
pub fn new(
workspace_root: impl Into<PathBuf>,
mode: ProcessBackendMode,
options: ProcessBackendOptions,
) -> Result<Self, ProcessBackendError> {
let session_background = crate::process_runner::BackgroundSupervisor::new();
let session_permissions = ProcessSessionPermissions::new();
let backend = LocalProcessBackend::new_with_shared_state(
workspace_root,
mode,
options,
Some(session_background.clone()),
Some(session_permissions.clone()),
)?;
Ok(Self {
state: std::sync::RwLock::new(backend),
session_background,
session_permissions,
})
}
#[must_use]
pub fn from_session(session: ProcessSession) -> Self {
Self {
state: std::sync::RwLock::new(LocalProcessBackend::from_session(session)),
session_background: crate::process_runner::BackgroundSupervisor::new(),
session_permissions: ProcessSessionPermissions::new(),
}
}
pub fn replace(
&self,
workspace_root: impl Into<PathBuf>,
mode: ProcessBackendMode,
options: ProcessBackendOptions,
) -> Result<ProcessSession, ProcessBackendError> {
let next = LocalProcessBackend::new_with_shared_state(
workspace_root,
mode,
options,
Some(self.session_background.clone()),
Some(self.session_permissions.clone()),
)?;
self.session_permissions.clear()?;
let next_session = next.new_session();
let mut guard = self
.state
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner);
*guard = next;
Ok(next_session)
}
}
impl ProcessBackend for LiveProcessBackend {
fn new_session(&self) -> ProcessSession {
self.state
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.new_session()
}
fn new_session_with(
&self,
request: ProcessSessionRequest,
) -> Result<ProcessSession, ProcessBackendError> {
self.state
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.new_session_with(request)
}
}
#[derive(Clone)]
pub struct UnrestrictedPermissionedProcessRunnerFactory {
runner: Arc<dyn ProcessRunner>,
}
impl UnrestrictedPermissionedProcessRunnerFactory {
#[must_use]
pub fn new(runner: Arc<dyn ProcessRunner>) -> Self {
Self { runner }
}
}
impl PermissionedProcessRunnerFactory for UnrestrictedPermissionedProcessRunnerFactory {
fn runner_for(&self, _request: &PermissionRequest) -> Arc<dyn ProcessRunner> {
Arc::clone(&self.runner)
}
}
#[cfg(test)]
mod tests;