use super::{background::BackgroundSupervisor, environment::WorkspaceProcessEnvironment};
use crate::resolve_host_path;
use merry_core::CapabilityPolicy;
use merry_runtime::{
HostIntegration, PathAccess, PathAccessDecision, PathAccessRule, PathAccessRuleSource,
PathDenialReason, PermissionRequest, PermissionedProcessRunnerFactory,
PreparedProcessPermission, ProcessActionIntent, ProcessPathGrant, ProcessPathGrantConstraint,
ProcessRunner, ProcessRunnerError, ProcessSessionPermissionSnapshot,
ProcessSessionPermissionView, ProcessSessionPermissions, RequestedCapability,
SessionPermissionedProcessRunnerFactory, WorkspaceAccessPolicy,
};
use std::{
path::{Path, PathBuf},
sync::Arc,
};
#[derive(Debug, Clone)]
pub struct WorkspaceProcessRunner {
pub(super) cwd_root: PathBuf,
pub(super) environment: WorkspaceProcessEnvironment,
pub(super) network_allowed: bool,
pub(super) path_rules: Vec<PathAccessRule>,
pub(super) action_required_rules: Vec<PathAccessRule>,
pub(super) session_permissions: Option<ProcessSessionPermissionView>,
pub(super) configuration_error: Option<String>,
workspace_writable: bool,
pub(super) background: BackgroundSupervisor,
}
impl WorkspaceProcessRunner {
#[must_use]
pub fn new_at_workspace_root(root: impl Into<PathBuf>) -> Self {
Self {
cwd_root: root.into(),
environment: WorkspaceProcessEnvironment::from_current_process(),
network_allowed: false,
path_rules: Vec::new(),
action_required_rules: Vec::new(),
session_permissions: None,
configuration_error: None,
workspace_writable: true,
background: BackgroundSupervisor::new(),
}
}
pub(crate) fn with_background(mut self, background: BackgroundSupervisor) -> Self {
self.background = background;
self
}
#[must_use]
pub fn read_only_workspace(mut self) -> Self {
self.workspace_writable = false;
self
}
#[must_use]
pub fn with_environment(mut self, environment: WorkspaceProcessEnvironment) -> Self {
self.environment = environment;
self
}
#[must_use]
pub fn allow_network(mut self) -> Self {
self.network_allowed = true;
self
}
#[must_use]
pub fn with_path_rules(mut self, rules: impl IntoIterator<Item = PathAccessRule>) -> Self {
self.path_rules = rules.into_iter().collect();
self
}
#[must_use]
pub fn with_session_permissions(mut self, permissions: ProcessSessionPermissions) -> Self {
self.session_permissions = Some(permissions.view());
self
}
pub(crate) fn ensure_sandbox_rules(&self) -> Result<(), ProcessRunnerError> {
if let Some(message) = self.configuration_error.clone() {
return Err(ProcessRunnerError::infrastructure(message));
}
let environment = self.environment.validate_for_workspace(&self.cwd_root)?;
let path_rules = normalize_path_rules(self.path_rules.clone());
crate::confinement::check_sandbox_rules(
&self.cwd_root,
&environment,
&path_rules,
&self.action_required_rules,
self.workspace_writable,
)
}
pub(super) fn plan_for(
&self,
intent: &ProcessActionIntent,
) -> Result<crate::confinement::SandboxLaunch, ProcessRunnerError> {
if let Some(message) = self.configuration_error.clone() {
return Err(ProcessRunnerError::infrastructure(message));
}
let environment = self.environment.validate_for_workspace(&self.cwd_root)?;
let session_snapshot = self
.session_permissions
.as_ref()
.map(ProcessSessionPermissionView::snapshot)
.transpose()?;
let mut environment = environment;
let mut path_rules = self.path_rules.clone();
let mut effective_network = self.network_allowed;
if let Some(snapshot) = session_snapshot {
path_rules.extend(snapshot.path_rules().iter().cloned());
environment =
environment.with_host_integrations(snapshot.host_integrations().iter().copied());
if snapshot.network_allowed() {
effective_network = true;
}
}
path_rules = normalize_path_rules(path_rules);
crate::confinement::prepare_launch(
intent,
&self.cwd_root,
&environment,
effective_network,
&path_rules,
&self.action_required_rules,
self.workspace_writable,
)
}
}
#[derive(Debug, Clone)]
pub struct WorkspaceProcessRunnerFactory {
pub(super) cwd_root: PathBuf,
pub(super) environment: WorkspaceProcessEnvironment,
pub(super) path_rules: Vec<PathAccessRule>,
network_policy: CapabilityPolicy,
denied_host_integrations: Vec<HostIntegration>,
pub(super) session_permissions: Option<ProcessSessionPermissionView>,
workspace_writable: bool,
background: BackgroundSupervisor,
}
impl WorkspaceProcessRunnerFactory {
#[must_use]
pub fn new_at_workspace_root(root: impl Into<PathBuf>) -> Self {
Self {
cwd_root: root.into(),
environment: WorkspaceProcessEnvironment::from_current_process(),
path_rules: Vec::new(),
network_policy: CapabilityPolicy::Ask,
denied_host_integrations: Vec::new(),
session_permissions: None,
workspace_writable: true,
background: BackgroundSupervisor::new(),
}
}
pub(crate) fn with_background(mut self, background: BackgroundSupervisor) -> Self {
self.background = background;
self
}
#[must_use]
pub fn read_only_workspace(mut self) -> Self {
self.workspace_writable = false;
self
}
#[must_use]
pub fn with_environment(mut self, environment: WorkspaceProcessEnvironment) -> Self {
self.environment = environment;
self
}
#[must_use]
pub fn with_path_rules(mut self, rules: impl IntoIterator<Item = PathAccessRule>) -> Self {
self.path_rules = rules.into_iter().collect();
self
}
#[must_use]
pub fn with_network_policy(mut self, policy: CapabilityPolicy) -> Self {
self.network_policy = policy;
self
}
#[must_use]
pub fn with_network_requests_allowed(mut self, allowed: bool) -> Self {
self.network_policy = if allowed {
CapabilityPolicy::Ask
} else {
CapabilityPolicy::Deny
};
self
}
#[must_use]
pub fn with_denied_host_integrations(
mut self,
denied: impl IntoIterator<Item = HostIntegration>,
) -> Self {
self.denied_host_integrations = denied.into_iter().collect();
self
}
#[must_use]
pub fn with_session_permissions(
mut self,
permissions: ProcessSessionPermissions,
) -> SessionPermissionedProcessRunnerFactory<Self> {
self.session_permissions = Some(permissions.view());
permissions.with_factory(self)
}
fn access_policy(&self) -> WorkspaceAccessPolicy {
WorkspaceAccessPolicy::new(&self.cwd_root, self.workspace_writable)
.with_static_rules(self.path_rules.iter().cloned())
}
fn requested_path_rules_for_request(
&self,
request: &PermissionRequest,
policy: &WorkspaceAccessPolicy,
snapshot: &ProcessSessionPermissionSnapshot,
) -> Result<(Vec<PathAccessRule>, Vec<PathAccessRule>), ProcessRunnerError> {
let mut new_rules = Vec::new();
let mut action_required = Vec::new();
for capability in request.requested() {
let RequestedCapability::Path(requested) = capability else {
continue;
};
let path = materialize_requested_path(&self.cwd_root, requested.path());
let effective_access =
effective_requested_path_access(policy, &path, requested.access(), snapshot)?;
let rule = PathAccessRule::new(
path.clone(),
effective_access,
PathAccessRuleSource::PermissionReview,
);
action_required.push(rule.clone());
if !policy.explicit_rules_cover(&path, effective_access, Some(snapshot)) {
new_rules.push(rule);
}
}
Ok((new_rules, action_required))
}
fn requested_host_integrations_for_request(
&self,
request: &PermissionRequest,
) -> Vec<HostIntegration> {
request
.requested()
.iter()
.filter_map(|capability| match capability {
RequestedCapability::HostIntegration(integration) => Some(*integration),
_ => None,
})
.collect()
}
pub(super) fn build_runner(&self, request: &PermissionRequest) -> WorkspaceProcessRunner {
match self.prepare_runner(request) {
Ok((runner, _)) => runner,
Err(error) => {
let mut runner = WorkspaceProcessRunner::new_at_workspace_root(&self.cwd_root);
runner.configuration_error = Some(error.to_string());
runner.background = self.background.clone();
runner
}
}
}
fn prepare_runner(
&self,
request: &PermissionRequest,
) -> Result<(WorkspaceProcessRunner, Vec<ProcessPathGrant>), ProcessRunnerError> {
self.validate_network_request(request)?;
let mut environment = self.environment.validate_for_workspace(&self.cwd_root)?;
let integrations = self.requested_host_integrations_for_request(request);
self.validate_denied_host_integrations(&integrations)?;
environment.validate_requested_host_integrations(&integrations)?;
let snapshot = self
.session_permissions
.as_ref()
.map(ProcessSessionPermissionView::snapshot)
.transpose()?
.unwrap_or_default();
let policy = self.access_policy();
let mut path_rules = self.path_rules.clone();
path_rules.extend(snapshot.path_rules().iter().cloned());
path_rules = normalize_path_rules(path_rules);
let (requested_rules, action_required_rules) =
self.requested_path_rules_for_request(request, &policy, &snapshot)?;
let grants = requested_rules
.iter()
.map(|rule| {
let eval = policy.evaluate_path(rule.path(), rule.access(), None, &[]);
let constraint = if eval.git_metadata || eval.protected_target {
ProcessPathGrantConstraint::ProtectedMetadata
} else {
ProcessPathGrantConstraint::Ordinary
};
ProcessPathGrant::new(
PathAccessRule::new(
resolve_host_path(rule.path()),
rule.access(),
rule.source(),
),
constraint,
)
})
.collect();
path_rules.extend(requested_rules);
path_rules = normalize_path_rules(path_rules);
environment = environment
.with_host_integrations(integrations)
.with_host_integrations(snapshot.host_integrations().iter().copied());
let mut runner = WorkspaceProcessRunner::new_at_workspace_root(self.cwd_root.clone())
.with_environment(environment)
.with_path_rules(path_rules);
if !self.workspace_writable {
runner = runner.read_only_workspace();
}
if request.requests_network()
|| self.network_policy.is_preauthorized()
|| snapshot.network_allowed()
{
runner = runner.allow_network();
}
runner.action_required_rules = action_required_rules;
runner.session_permissions = self.session_permissions.clone();
runner.background = self.background.clone();
runner.ensure_sandbox_rules()?;
Ok((runner, grants))
}
fn validate_network_request(
&self,
request: &PermissionRequest,
) -> Result<(), ProcessRunnerError> {
if request.requests_network() && self.network_policy.is_denied() {
return Err(ProcessRunnerError::infrastructure(
"network requests are disabled by the configured process capability ceiling",
));
}
Ok(())
}
fn validate_denied_host_integrations(
&self,
requested: &[HostIntegration],
) -> Result<(), ProcessRunnerError> {
for integration in requested {
if self.denied_host_integrations.contains(integration) {
return Err(ProcessRunnerError::infrastructure(format!(
"host integration `{}` is disabled by configured permission policy",
integration.as_str()
)));
}
}
Ok(())
}
}
impl PermissionedProcessRunnerFactory for WorkspaceProcessRunnerFactory {
fn validate_request(&self, request: &PermissionRequest) -> Result<(), ProcessRunnerError> {
self.prepare_runner(request).map(|_| ())
}
fn request_capabilities_are_satisfied(
&self,
request: &PermissionRequest,
) -> Result<bool, ProcessRunnerError> {
self.validate_network_request(request)?;
let environment = self.environment.validate_for_workspace(&self.cwd_root)?;
let snapshot = self
.session_permissions
.as_ref()
.map(ProcessSessionPermissionView::snapshot)
.transpose()?
.unwrap_or_default();
let requested_integrations = self.requested_host_integrations_for_request(request);
self.validate_denied_host_integrations(&requested_integrations)?;
environment.validate_requested_host_integrations(&requested_integrations)?;
let network_satisfied =
self.network_policy.is_preauthorized() || snapshot.network_allowed();
if request.requests_network() && !network_satisfied {
return Ok(false);
}
let mut available_integrations = environment.host_integrations.clone();
available_integrations.extend(snapshot.host_integrations().iter().copied());
available_integrations.sort_unstable();
available_integrations.dedup();
if requested_integrations
.iter()
.any(|integration| !available_integrations.contains(integration))
{
return Ok(false);
}
let policy = self.access_policy();
for capability in request.requested() {
let satisfied = match capability {
RequestedCapability::Network => network_satisfied,
RequestedCapability::NetworkDomain(domain) => {
network_satisfied || snapshot.allows_domain(domain)
}
RequestedCapability::HostIntegration(_) => true,
RequestedCapability::Path(requested) => {
let path = materialize_requested_path(&self.cwd_root, requested.path());
policy
.evaluate_directory_grant(&path, requested.access(), Some(&snapshot), &[])
.decision
== PathAccessDecision::Allow
}
};
if !satisfied {
return Ok(false);
}
}
Ok(true)
}
fn targets_protected_metadata(&self, request: &PermissionRequest) -> bool {
let policy = self.access_policy();
request.requested().iter().any(|capability| {
let RequestedCapability::Path(requested) = capability else {
return false;
};
let path = materialize_requested_path(&self.cwd_root, requested.path());
policy.is_protected_target(&path, requested.access())
})
}
fn runner_for(&self, request: &PermissionRequest) -> Arc<dyn ProcessRunner> {
Arc::new(self.build_runner(request))
}
fn prepare_approved_request(
&self,
request: &PermissionRequest,
) -> Result<PreparedProcessPermission, ProcessRunnerError> {
let (runner, grants) = self.prepare_runner(request)?;
Ok(PreparedProcessPermission::new(Arc::new(runner), grants))
}
}
fn materialize_requested_path(root: &Path, requested: &str) -> PathBuf {
let path = Path::new(requested);
if path.is_absolute() {
path.to_path_buf()
} else {
root.join(path)
}
}
fn effective_requested_path_access(
policy: &WorkspaceAccessPolicy,
requested_path: &Path,
requested_access: PathAccess,
snapshot: &ProcessSessionPermissionSnapshot,
) -> Result<PathAccess, ProcessRunnerError> {
let resolved = resolve_host_path(requested_path);
let eval = policy.evaluate_directory_grant(&resolved, requested_access, Some(snapshot), &[]);
match eval.denial_reason {
Some(PathDenialReason::UserHardDeny) => {
let blocking = policy
.blocking_rule_path(&resolved, requested_access)
.unwrap_or_else(|| resolved.clone());
Err(ProcessRunnerError::infrastructure(format!(
"requested path `{}` is denied by configured path policy `{}`",
resolved.display(),
blocking.display()
)))
}
Some(PathDenialReason::CoversDeniedDescendant) => {
let blocking = policy
.blocking_rule_path(&resolved, requested_access)
.unwrap_or_else(|| resolved.clone());
Err(ProcessRunnerError::infrastructure(format!(
"requested path `{}` covers denied path `{}`; narrow the request so it excludes protected paths",
resolved.display(),
blocking.display()
)))
}
Some(PathDenialReason::CoversProtectedReadOnlyDescendant) => {
let blocking = policy
.blocking_rule_path(&resolved, requested_access)
.unwrap_or_else(|| resolved.clone());
Err(ProcessRunnerError::infrastructure(format!(
"requested writable path `{}` covers Merry protected read-only path `{}`; request write access on `{}` directly or narrow the request",
resolved.display(),
blocking.display(),
blocking.display()
)))
}
Some(PathDenialReason::UserReadOnlyCeiling) => {
Ok(PathAccess::ReadOnly)
}
Some(PathDenialReason::ReadOnlyWorkspace | PathDenialReason::InvalidAccess) | None => {
Ok(requested_access)
}
}
}
fn normalize_path_rules(rules: Vec<PathAccessRule>) -> Vec<PathAccessRule> {
let mut merged =
std::collections::BTreeMap::<PathBuf, (PathAccess, PathAccessRuleSource)>::new();
for rule in rules {
let access = rule.access();
let key = resolve_host_path(rule.path());
let entry = merged.entry(key).or_insert((access, rule.source()));
(entry.0, entry.1) = merged_path_rule(entry.0, entry.1, access, rule.source());
}
let mut rules = merged
.into_iter()
.map(|(path, (access, source))| PathAccessRule::new(path, access, source))
.collect::<Vec<_>>();
rules.sort_by(|left, right| {
path_depth(left.path())
.cmp(&path_depth(right.path()))
.then_with(|| left.path().cmp(right.path()))
});
rules
}
fn merged_path_rule(
left_access: PathAccess,
left_source: PathAccessRuleSource,
right_access: PathAccess,
right_source: PathAccessRuleSource,
) -> (PathAccess, PathAccessRuleSource) {
let left_is_hard_deny =
left_access == PathAccess::Deny && left_source != PathAccessRuleSource::ProductPrivate;
let right_is_hard_deny =
right_access == PathAccess::Deny && right_source != PathAccessRuleSource::ProductPrivate;
if left_is_hard_deny {
return (left_access, left_source);
}
if right_is_hard_deny {
return (right_access, right_source);
}
if left_access == PathAccess::Deny && right_source == PathAccessRuleSource::PermissionReview {
return (right_access, right_source);
}
if right_access == PathAccess::Deny && left_source == PathAccessRuleSource::PermissionReview {
return (left_access, left_source);
}
if left_access == PathAccess::Deny {
return (left_access, left_source);
}
if right_access == PathAccess::Deny {
return (right_access, right_source);
}
let left_is_hard_read_only = left_access == PathAccess::ReadOnly
&& left_source == PathAccessRuleSource::TrustedGlobalConfig;
let right_is_hard_read_only = right_access == PathAccess::ReadOnly
&& right_source == PathAccessRuleSource::TrustedGlobalConfig;
if left_is_hard_read_only {
return (left_access, left_source);
}
if right_is_hard_read_only {
return (right_access, right_source);
}
if left_access == PathAccess::ReadOnly
&& left_source == PathAccessRuleSource::ProductReadOnly
&& right_source == PathAccessRuleSource::WorkspacePermissions
{
return (left_access, left_source);
}
if right_access == PathAccess::ReadOnly
&& right_source == PathAccessRuleSource::ProductReadOnly
&& left_source == PathAccessRuleSource::WorkspacePermissions
{
return (right_access, right_source);
}
let left_is_reviewed_write = left_access == PathAccess::ReadWrite
&& left_source == PathAccessRuleSource::PermissionReview;
let right_is_reviewed_write = right_access == PathAccess::ReadWrite
&& right_source == PathAccessRuleSource::PermissionReview;
if left_is_reviewed_write {
return (left_access, left_source);
}
if right_is_reviewed_write {
return (right_access, right_source);
}
match (left_access, right_access) {
(PathAccess::ReadWrite, _) => (left_access, left_source),
(_, PathAccess::ReadWrite) => (right_access, right_source),
_ => (PathAccess::ReadOnly, left_source),
}
}
fn path_depth(path: &Path) -> usize {
path.components().count()
}