Skip to main content

merry_process/process_runner/
permissions.rs

1use super::{background::BackgroundSupervisor, environment::WorkspaceProcessEnvironment};
2use crate::resolve_host_path;
3use merry_core::CapabilityPolicy;
4use merry_runtime::{
5    HostIntegration, PathAccess, PathAccessDecision, PathAccessRule, PathAccessRuleSource,
6    PathDenialReason, PermissionRequest, PermissionedProcessRunnerFactory,
7    PreparedProcessPermission, ProcessActionIntent, ProcessPathGrant, ProcessPathGrantConstraint,
8    ProcessRunner, ProcessRunnerError, ProcessSessionPermissionSnapshot,
9    ProcessSessionPermissionView, ProcessSessionPermissions, RequestedCapability,
10    SessionPermissionedProcessRunnerFactory, WorkspaceAccessPolicy,
11};
12use std::{
13    path::{Path, PathBuf},
14    sync::Arc,
15};
16
17/// Host-process runner that confines each process action.
18///
19/// Linux applies Landlock and, unless the action was granted network, a seccomp
20/// filter. macOS applies a Seatbelt profile. The Merry process itself stays
21/// unrestricted.
22#[derive(Debug, Clone)]
23pub struct WorkspaceProcessRunner {
24    pub(super) cwd_root: PathBuf,
25    pub(super) environment: WorkspaceProcessEnvironment,
26    pub(super) network_allowed: bool,
27    pub(super) path_rules: Vec<PathAccessRule>,
28    /// Paths explicitly requested by this action (never inherited from earlier
29    /// session-retained grants) that Landlock must verify exist before exec.
30    pub(super) action_required_rules: Vec<PathAccessRule>,
31    pub(super) session_permissions: Option<ProcessSessionPermissionView>,
32    pub(super) configuration_error: Option<String>,
33    workspace_writable: bool,
34    /// Keeps background children after `run` returns. Session drop kills them.
35    pub(super) background: BackgroundSupervisor,
36}
37
38impl WorkspaceProcessRunner {
39    /// Creates a per-action workspace runner rooted at a workspace path.
40    #[must_use]
41    pub fn new_at_workspace_root(root: impl Into<PathBuf>) -> Self {
42        Self {
43            cwd_root: root.into(),
44            environment: WorkspaceProcessEnvironment::from_current_process(),
45            network_allowed: false,
46            path_rules: Vec::new(),
47            action_required_rules: Vec::new(),
48            session_permissions: None,
49            configuration_error: None,
50            workspace_writable: true,
51            background: BackgroundSupervisor::new(),
52        }
53    }
54
55    pub(crate) fn with_background(mut self, background: BackgroundSupervisor) -> Self {
56        self.background = background;
57        self
58    }
59
60    /// Keeps the workspace readable and not writable.
61    ///
62    /// Baseline paths such as `/tmp` stay writable. This does not turn the
63    /// sandbox off.
64    #[must_use]
65    pub fn read_only_workspace(mut self) -> Self {
66        self.workspace_writable = false;
67        self
68    }
69
70    /// Sets the environment layout visible to child processes.
71    #[must_use]
72    pub fn with_environment(mut self, environment: WorkspaceProcessEnvironment) -> Self {
73        self.environment = environment;
74        self
75    }
76
77    /// Allows network access for child process actions.
78    #[must_use]
79    pub fn allow_network(mut self) -> Self {
80        self.network_allowed = true;
81        self
82    }
83
84    /// Installs trusted path rules for child process actions.
85    #[must_use]
86    pub fn with_path_rules(mut self, rules: impl IntoIterator<Item = PathAccessRule>) -> Self {
87        self.path_rules = rules.into_iter().collect();
88        self
89    }
90
91    /// Shares session-scoped approved capabilities with the permissioned runner factory.
92    #[must_use]
93    pub fn with_session_permissions(mut self, permissions: ProcessSessionPermissions) -> Self {
94        self.session_permissions = Some(permissions.view());
95        self
96    }
97
98    /// Rejects allow-list conflicts before a session can run a command.
99    ///
100    /// # Errors
101    ///
102    /// Returns the same conflict `plan_for` would return for these rules when a
103    /// deny, review, or private path sits inside an allowed directory.
104    pub(crate) fn ensure_sandbox_rules(&self) -> Result<(), ProcessRunnerError> {
105        if let Some(message) = self.configuration_error.clone() {
106            return Err(ProcessRunnerError::infrastructure(message));
107        }
108        let environment = self.environment.validate_for_workspace(&self.cwd_root)?;
109        let path_rules = normalize_path_rules(self.path_rules.clone());
110        crate::confinement::check_sandbox_rules(
111            &self.cwd_root,
112            &environment,
113            &path_rules,
114            &self.action_required_rules,
115            self.workspace_writable,
116        )
117    }
118
119    pub(super) fn plan_for(
120        &self,
121        intent: &ProcessActionIntent,
122    ) -> Result<crate::confinement::SandboxLaunch, ProcessRunnerError> {
123        if let Some(message) = self.configuration_error.clone() {
124            return Err(ProcessRunnerError::infrastructure(message));
125        }
126        let environment = self.environment.validate_for_workspace(&self.cwd_root)?;
127        let session_snapshot = self
128            .session_permissions
129            .as_ref()
130            .map(ProcessSessionPermissionView::snapshot)
131            .transpose()?;
132        let mut environment = environment;
133        let mut path_rules = self.path_rules.clone();
134        let mut effective_network = self.network_allowed;
135        if let Some(snapshot) = session_snapshot {
136            path_rules.extend(snapshot.path_rules().iter().cloned());
137            environment =
138                environment.with_host_integrations(snapshot.host_integrations().iter().copied());
139            if snapshot.network_allowed() {
140                effective_network = true;
141            }
142        }
143        path_rules = normalize_path_rules(path_rules);
144        crate::confinement::prepare_launch(
145            intent,
146            &self.cwd_root,
147            &environment,
148            effective_network,
149            &path_rules,
150            &self.action_required_rules,
151            self.workspace_writable,
152        )
153    }
154}
155
156/// Builds a workspace runner from an approved permission request.
157///
158/// Filesystem access stays governed by the configured path rules and the
159/// session-scoped capabilities explicitly retained by the runtime. Ordinary
160/// paths, host integrations, and outbound network are retained only when
161/// approved with [`merry_core::ApprovalScope::Session`]; explicitly reviewed
162/// paths and protected metadata remain strictly action-scoped.
163#[derive(Debug, Clone)]
164pub struct WorkspaceProcessRunnerFactory {
165    pub(super) cwd_root: PathBuf,
166    pub(super) environment: WorkspaceProcessEnvironment,
167    pub(super) path_rules: Vec<PathAccessRule>,
168    network_policy: CapabilityPolicy,
169    denied_host_integrations: Vec<HostIntegration>,
170    pub(super) session_permissions: Option<ProcessSessionPermissionView>,
171    workspace_writable: bool,
172    /// Shared by every runner this factory builds. `runner_for` drops its
173    /// runner when the tool call returns, so background children cannot live
174    /// only on that runner.
175    background: BackgroundSupervisor,
176}
177
178impl WorkspaceProcessRunnerFactory {
179    /// Creates a workspace-sandbox runner factory rooted at a workspace path.
180    #[must_use]
181    pub fn new_at_workspace_root(root: impl Into<PathBuf>) -> Self {
182        Self {
183            cwd_root: root.into(),
184            environment: WorkspaceProcessEnvironment::from_current_process(),
185            path_rules: Vec::new(),
186            network_policy: CapabilityPolicy::Ask,
187            denied_host_integrations: Vec::new(),
188            session_permissions: None,
189            workspace_writable: true,
190            background: BackgroundSupervisor::new(),
191        }
192    }
193
194    pub(crate) fn with_background(mut self, background: BackgroundSupervisor) -> Self {
195        self.background = background;
196        self
197    }
198
199    /// Keeps the workspace readable and not writable for every child runner.
200    #[must_use]
201    pub fn read_only_workspace(mut self) -> Self {
202        self.workspace_writable = false;
203        self
204    }
205
206    /// Sets the environment layout used by every materialized child runner.
207    #[must_use]
208    pub fn with_environment(mut self, environment: WorkspaceProcessEnvironment) -> Self {
209        self.environment = environment;
210        self
211    }
212
213    /// Installs trusted path rules shared by each materialized runner.
214    #[must_use]
215    pub fn with_path_rules(mut self, rules: impl IntoIterator<Item = PathAccessRule>) -> Self {
216        self.path_rules = rules.into_iter().collect();
217        self
218    }
219
220    /// Sets the three-state network policy (`deny`, `ask`, or `allow`).
221    #[must_use]
222    pub fn with_network_policy(mut self, policy: CapabilityPolicy) -> Self {
223        self.network_policy = policy;
224        self
225    }
226
227    /// Sets whether network capability requests can proceed to review.
228    ///
229    /// Defaults to true (`Ask`) without preauthorizing access. False (`Deny`)
230    /// rejects requests during validation and materialization, including direct
231    /// runner creation.
232    #[must_use]
233    pub fn with_network_requests_allowed(mut self, allowed: bool) -> Self {
234        self.network_policy = if allowed {
235            CapabilityPolicy::Ask
236        } else {
237            CapabilityPolicy::Deny
238        };
239        self
240    }
241
242    /// Sets host integrations hard-denied (`deny`) by configuration.
243    #[must_use]
244    pub fn with_denied_host_integrations(
245        mut self,
246        denied: impl IntoIterator<Item = HostIntegration>,
247    ) -> Self {
248        self.denied_host_integrations = denied.into_iter().collect();
249        self
250    }
251
252    /// Attaches a read-only capability view and returns the runtime-owned
253    /// retention decorator. Configure backend-specific options before attaching it.
254    #[must_use]
255    pub fn with_session_permissions(
256        mut self,
257        permissions: ProcessSessionPermissions,
258    ) -> SessionPermissionedProcessRunnerFactory<Self> {
259        self.session_permissions = Some(permissions.view());
260        permissions.with_factory(self)
261    }
262
263    fn access_policy(&self) -> WorkspaceAccessPolicy {
264        WorkspaceAccessPolicy::new(&self.cwd_root, self.workspace_writable)
265            .with_static_rules(self.path_rules.iter().cloned())
266    }
267
268    fn requested_path_rules_for_request(
269        &self,
270        request: &PermissionRequest,
271        policy: &WorkspaceAccessPolicy,
272        snapshot: &ProcessSessionPermissionSnapshot,
273    ) -> Result<(Vec<PathAccessRule>, Vec<PathAccessRule>), ProcessRunnerError> {
274        let mut new_rules = Vec::new();
275        let mut action_required = Vec::new();
276        for capability in request.requested() {
277            let RequestedCapability::Path(requested) = capability else {
278                continue;
279            };
280            let path = materialize_requested_path(&self.cwd_root, requested.path());
281            let effective_access =
282                effective_requested_path_access(policy, &path, requested.access(), snapshot)?;
283            let rule = PathAccessRule::new(
284                path.clone(),
285                effective_access,
286                PathAccessRuleSource::PermissionReview,
287            );
288            action_required.push(rule.clone());
289            if !policy.explicit_rules_cover(&path, effective_access, Some(snapshot)) {
290                new_rules.push(rule);
291            }
292        }
293        Ok((new_rules, action_required))
294    }
295
296    fn requested_host_integrations_for_request(
297        &self,
298        request: &PermissionRequest,
299    ) -> Vec<HostIntegration> {
300        request
301            .requested()
302            .iter()
303            .filter_map(|capability| match capability {
304                RequestedCapability::HostIntegration(integration) => Some(*integration),
305                _ => None,
306            })
307            .collect()
308    }
309
310    pub(super) fn build_runner(&self, request: &PermissionRequest) -> WorkspaceProcessRunner {
311        match self.prepare_runner(request) {
312            Ok((runner, _)) => runner,
313            Err(error) => {
314                let mut runner = WorkspaceProcessRunner::new_at_workspace_root(&self.cwd_root);
315                runner.configuration_error = Some(error.to_string());
316                runner.background = self.background.clone();
317                runner
318            }
319        }
320    }
321
322    fn prepare_runner(
323        &self,
324        request: &PermissionRequest,
325    ) -> Result<(WorkspaceProcessRunner, Vec<ProcessPathGrant>), ProcessRunnerError> {
326        self.validate_network_request(request)?;
327        let mut environment = self.environment.validate_for_workspace(&self.cwd_root)?;
328        let integrations = self.requested_host_integrations_for_request(request);
329        self.validate_denied_host_integrations(&integrations)?;
330        environment.validate_requested_host_integrations(&integrations)?;
331        let snapshot = self
332            .session_permissions
333            .as_ref()
334            .map(ProcessSessionPermissionView::snapshot)
335            .transpose()?
336            .unwrap_or_default();
337        let policy = self.access_policy();
338        let mut path_rules = self.path_rules.clone();
339        path_rules.extend(snapshot.path_rules().iter().cloned());
340        path_rules = normalize_path_rules(path_rules);
341        let (requested_rules, action_required_rules) =
342            self.requested_path_rules_for_request(request, &policy, &snapshot)?;
343        let grants = requested_rules
344            .iter()
345            .map(|rule| {
346                let eval = policy.evaluate_path(rule.path(), rule.access(), None, &[]);
347                let constraint = if eval.git_metadata || eval.protected_target {
348                    ProcessPathGrantConstraint::ProtectedMetadata
349                } else {
350                    ProcessPathGrantConstraint::Ordinary
351                };
352                ProcessPathGrant::new(
353                    PathAccessRule::new(
354                        resolve_host_path(rule.path()),
355                        rule.access(),
356                        rule.source(),
357                    ),
358                    constraint,
359                )
360            })
361            .collect();
362        path_rules.extend(requested_rules);
363        path_rules = normalize_path_rules(path_rules);
364        environment = environment
365            .with_host_integrations(integrations)
366            .with_host_integrations(snapshot.host_integrations().iter().copied());
367        let mut runner = WorkspaceProcessRunner::new_at_workspace_root(self.cwd_root.clone())
368            .with_environment(environment)
369            .with_path_rules(path_rules);
370        if !self.workspace_writable {
371            runner = runner.read_only_workspace();
372        }
373        if request.requests_network()
374            || self.network_policy.is_preauthorized()
375            || snapshot.network_allowed()
376        {
377            runner = runner.allow_network();
378        }
379        runner.action_required_rules = action_required_rules;
380        runner.session_permissions = self.session_permissions.clone();
381        runner.background = self.background.clone();
382        runner.ensure_sandbox_rules()?;
383        Ok((runner, grants))
384    }
385
386    /// Enforces the capability ceiling before review, grants, or runner construction.
387    fn validate_network_request(
388        &self,
389        request: &PermissionRequest,
390    ) -> Result<(), ProcessRunnerError> {
391        if request.requests_network() && self.network_policy.is_denied() {
392            return Err(ProcessRunnerError::infrastructure(
393                "network requests are disabled by the configured process capability ceiling",
394            ));
395        }
396        Ok(())
397    }
398
399    fn validate_denied_host_integrations(
400        &self,
401        requested: &[HostIntegration],
402    ) -> Result<(), ProcessRunnerError> {
403        for integration in requested {
404            if self.denied_host_integrations.contains(integration) {
405                return Err(ProcessRunnerError::infrastructure(format!(
406                    "host integration `{}` is disabled by configured permission policy",
407                    integration.as_str()
408                )));
409            }
410        }
411        Ok(())
412    }
413}
414
415impl PermissionedProcessRunnerFactory for WorkspaceProcessRunnerFactory {
416    fn validate_request(&self, request: &PermissionRequest) -> Result<(), ProcessRunnerError> {
417        self.prepare_runner(request).map(|_| ())
418    }
419
420    fn request_capabilities_are_satisfied(
421        &self,
422        request: &PermissionRequest,
423    ) -> Result<bool, ProcessRunnerError> {
424        self.validate_network_request(request)?;
425        let environment = self.environment.validate_for_workspace(&self.cwd_root)?;
426        let snapshot = self
427            .session_permissions
428            .as_ref()
429            .map(ProcessSessionPermissionView::snapshot)
430            .transpose()?
431            .unwrap_or_default();
432
433        let requested_integrations = self.requested_host_integrations_for_request(request);
434        self.validate_denied_host_integrations(&requested_integrations)?;
435        environment.validate_requested_host_integrations(&requested_integrations)?;
436        let network_satisfied =
437            self.network_policy.is_preauthorized() || snapshot.network_allowed();
438        if request.requests_network() && !network_satisfied {
439            return Ok(false);
440        }
441
442        let mut available_integrations = environment.host_integrations.clone();
443        available_integrations.extend(snapshot.host_integrations().iter().copied());
444        available_integrations.sort_unstable();
445        available_integrations.dedup();
446        if requested_integrations
447            .iter()
448            .any(|integration| !available_integrations.contains(integration))
449        {
450            return Ok(false);
451        }
452
453        let policy = self.access_policy();
454        for capability in request.requested() {
455            let satisfied = match capability {
456                RequestedCapability::Network => network_satisfied,
457                RequestedCapability::NetworkDomain(domain) => {
458                    network_satisfied || snapshot.allows_domain(domain)
459                }
460                RequestedCapability::HostIntegration(_) => true,
461                RequestedCapability::Path(requested) => {
462                    let path = materialize_requested_path(&self.cwd_root, requested.path());
463                    policy
464                        .evaluate_directory_grant(&path, requested.access(), Some(&snapshot), &[])
465                        .decision
466                        == PathAccessDecision::Allow
467                }
468            };
469            if !satisfied {
470                return Ok(false);
471            }
472        }
473        Ok(true)
474    }
475
476    fn targets_protected_metadata(&self, request: &PermissionRequest) -> bool {
477        let policy = self.access_policy();
478        request.requested().iter().any(|capability| {
479            let RequestedCapability::Path(requested) = capability else {
480                return false;
481            };
482            let path = materialize_requested_path(&self.cwd_root, requested.path());
483            policy.is_protected_target(&path, requested.access())
484        })
485    }
486
487    fn runner_for(&self, request: &PermissionRequest) -> Arc<dyn ProcessRunner> {
488        Arc::new(self.build_runner(request))
489    }
490
491    fn prepare_approved_request(
492        &self,
493        request: &PermissionRequest,
494    ) -> Result<PreparedProcessPermission, ProcessRunnerError> {
495        let (runner, grants) = self.prepare_runner(request)?;
496        Ok(PreparedProcessPermission::new(Arc::new(runner), grants))
497    }
498}
499
500fn materialize_requested_path(root: &Path, requested: &str) -> PathBuf {
501    let path = Path::new(requested);
502    if path.is_absolute() {
503        path.to_path_buf()
504    } else {
505        root.join(path)
506    }
507}
508
509fn effective_requested_path_access(
510    policy: &WorkspaceAccessPolicy,
511    requested_path: &Path,
512    requested_access: PathAccess,
513    snapshot: &ProcessSessionPermissionSnapshot,
514) -> Result<PathAccess, ProcessRunnerError> {
515    let resolved = resolve_host_path(requested_path);
516    let eval = policy.evaluate_directory_grant(&resolved, requested_access, Some(snapshot), &[]);
517    match eval.denial_reason {
518        Some(PathDenialReason::UserHardDeny) => {
519            let blocking = policy
520                .blocking_rule_path(&resolved, requested_access)
521                .unwrap_or_else(|| resolved.clone());
522            Err(ProcessRunnerError::infrastructure(format!(
523                "requested path `{}` is denied by configured path policy `{}`",
524                resolved.display(),
525                blocking.display()
526            )))
527        }
528        Some(PathDenialReason::CoversDeniedDescendant) => {
529            let blocking = policy
530                .blocking_rule_path(&resolved, requested_access)
531                .unwrap_or_else(|| resolved.clone());
532            Err(ProcessRunnerError::infrastructure(format!(
533                "requested path `{}` covers denied path `{}`; narrow the request so it excludes protected paths",
534                resolved.display(),
535                blocking.display()
536            )))
537        }
538        Some(PathDenialReason::CoversProtectedReadOnlyDescendant) => {
539            let blocking = policy
540                .blocking_rule_path(&resolved, requested_access)
541                .unwrap_or_else(|| resolved.clone());
542            Err(ProcessRunnerError::infrastructure(format!(
543                "requested writable path `{}` covers Merry protected read-only path `{}`; request write access on `{}` directly or narrow the request",
544                resolved.display(),
545                blocking.display(),
546                blocking.display()
547            )))
548        }
549        Some(PathDenialReason::UserReadOnlyCeiling) => {
550            // Explicit global read-only rules are a hard ceiling. Git metadata
551            // baselines and Merry's default `ProductReadOnly` directories are
552            // intentionally different: a reviewed action may temporarily overlay
553            // them directly, but the grant is never session-persistent.
554            Ok(PathAccess::ReadOnly)
555        }
556        Some(PathDenialReason::ReadOnlyWorkspace | PathDenialReason::InvalidAccess) | None => {
557            Ok(requested_access)
558        }
559    }
560}
561
562fn normalize_path_rules(rules: Vec<PathAccessRule>) -> Vec<PathAccessRule> {
563    let mut merged =
564        std::collections::BTreeMap::<PathBuf, (PathAccess, PathAccessRuleSource)>::new();
565    for rule in rules {
566        let access = rule.access();
567        let key = resolve_host_path(rule.path());
568        let entry = merged.entry(key).or_insert((access, rule.source()));
569        (entry.0, entry.1) = merged_path_rule(entry.0, entry.1, access, rule.source());
570    }
571    let mut rules = merged
572        .into_iter()
573        .map(|(path, (access, source))| PathAccessRule::new(path, access, source))
574        .collect::<Vec<_>>();
575    rules.sort_by(|left, right| {
576        path_depth(left.path())
577            .cmp(&path_depth(right.path()))
578            .then_with(|| left.path().cmp(right.path()))
579    });
580    rules
581}
582
583fn merged_path_rule(
584    left_access: PathAccess,
585    left_source: PathAccessRuleSource,
586    right_access: PathAccess,
587    right_source: PathAccessRuleSource,
588) -> (PathAccess, PathAccessRuleSource) {
589    let left_is_hard_deny =
590        left_access == PathAccess::Deny && left_source != PathAccessRuleSource::ProductPrivate;
591    let right_is_hard_deny =
592        right_access == PathAccess::Deny && right_source != PathAccessRuleSource::ProductPrivate;
593    if left_is_hard_deny {
594        return (left_access, left_source);
595    }
596    if right_is_hard_deny {
597        return (right_access, right_source);
598    }
599    if left_access == PathAccess::Deny && right_source == PathAccessRuleSource::PermissionReview {
600        return (right_access, right_source);
601    }
602    if right_access == PathAccess::Deny && left_source == PathAccessRuleSource::PermissionReview {
603        return (left_access, left_source);
604    }
605    if left_access == PathAccess::Deny {
606        return (left_access, left_source);
607    }
608    if right_access == PathAccess::Deny {
609        return (right_access, right_source);
610    }
611
612    let left_is_hard_read_only = left_access == PathAccess::ReadOnly
613        && left_source == PathAccessRuleSource::TrustedGlobalConfig;
614    let right_is_hard_read_only = right_access == PathAccess::ReadOnly
615        && right_source == PathAccessRuleSource::TrustedGlobalConfig;
616    if left_is_hard_read_only {
617        return (left_access, left_source);
618    }
619    if right_is_hard_read_only {
620        return (right_access, right_source);
621    }
622
623    // Built-in ProductReadOnly protection beats saved workspace paths so a
624    // hand-edited workspace-permissions.json can never escalate writes into
625    // `$XDG_CONFIG_HOME/merry` or `$XDG_STATE_HOME/merry`.
626    if left_access == PathAccess::ReadOnly
627        && left_source == PathAccessRuleSource::ProductReadOnly
628        && right_source == PathAccessRuleSource::WorkspacePermissions
629    {
630        return (left_access, left_source);
631    }
632    if right_access == PathAccess::ReadOnly
633        && right_source == PathAccessRuleSource::ProductReadOnly
634        && left_source == PathAccessRuleSource::WorkspacePermissions
635    {
636        return (right_access, right_source);
637    }
638
639    let left_is_reviewed_write = left_access == PathAccess::ReadWrite
640        && left_source == PathAccessRuleSource::PermissionReview;
641    let right_is_reviewed_write = right_access == PathAccess::ReadWrite
642        && right_source == PathAccessRuleSource::PermissionReview;
643    if left_is_reviewed_write {
644        return (left_access, left_source);
645    }
646    if right_is_reviewed_write {
647        return (right_access, right_source);
648    }
649
650    match (left_access, right_access) {
651        (PathAccess::ReadWrite, _) => (left_access, left_source),
652        (_, PathAccess::ReadWrite) => (right_access, right_source),
653        _ => (PathAccess::ReadOnly, left_source),
654    }
655}
656
657fn path_depth(path: &Path) -> usize {
658    path.components().count()
659}