Skip to main content

merry_process/process_runner/
permissions.rs

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