Skip to main content

merry_process/
lib.rs

1//! Host-process adapters for Merry's provider-neutral process contract.
2//!
3//! [`merry_runtime`] owns process intent, admission, permission requests, and
4//! execution evidence. This crate owns the host-facing runner selection and
5//! binds the runners used by one runtime owner to one [`ProcessSession`]. A
6//! platform can replace the concrete backend without changing coding
7//! composition or runtime call sites.
8
9#[cfg(any(target_os = "linux", target_os = "macos"))]
10mod confinement;
11#[cfg(not(any(target_os = "linux", target_os = "macos")))]
12#[path = "confinement/unsupported.rs"]
13mod confinement;
14mod gpg;
15mod host_path;
16mod host_resources;
17mod process_runner;
18
19pub use confinement::{probe_workspace_sandbox, sandbox_helper_main, sandbox_helper_requested};
20pub use gpg::GpgAgentSockets;
21pub use host_path::resolve_host_path;
22pub use host_resources::{HostPathKind, HostPathMetadata, ssh_known_hosts};
23
24pub use process_runner::{TokioProcessRunner, action_process_path};
25
26#[cfg(any(target_os = "linux", target_os = "macos"))]
27pub use process_runner::{
28    ProcessSessionPermissions, WorkspaceProcessEnvironment, WorkspaceProcessRunner,
29    WorkspaceProcessRunnerFactory,
30};
31
32use merry_runtime::{
33    AcceptedLocalWorkspaceProcessAdmission, HostIntegration, PathAccessRule, PermissionRequest,
34    PermissionedProcessRunnerFactory, ProcessRunner, ProcessRunnerError,
35    ProcessSessionPermissionView,
36};
37use std::{
38    ffi::OsString,
39    path::{Path, PathBuf},
40    sync::Arc,
41};
42use thiserror::Error;
43
44/// Semantic process backend behavior requested by an application surface.
45///
46/// The selected behavior is intentionally independent of the operating system.
47/// A platform backend may implement [`Isolated`](Self::Isolated) with its
48/// native mechanism or report that the behavior is unavailable; callers do not
49/// need to name Landlock, seccomp, or another concrete mechanism.
50#[derive(Debug, Clone, Copy, PartialEq, Eq)]
51pub enum ProcessBackendMode {
52    /// Run actions in the host process environment, subject to runtime policy.
53    Host,
54    /// Request the platform's isolated local-process behavior.
55    Isolated,
56}
57
58/// Errors raised while selecting or constructing a host-process backend.
59///
60/// Execution failures remain [`merry_runtime::ProcessRunnerError`]. This error
61/// belongs to the adapter layer because it also represents a platform backend
62/// that is not available for the requested semantic mode.
63#[derive(Debug, Error, Clone, PartialEq, Eq)]
64pub enum ProcessBackendError {
65    /// The concrete runner rejected its configuration.
66    #[error("process backend configuration failed: {source}")]
67    Runner {
68        /// The runner configuration failure.
69        #[source]
70        source: ProcessRunnerError,
71    },
72    /// The requested isolated behavior has no implementation on this target.
73    #[error(
74        "isolated local process backend is unavailable on target operating system `{target_os}`"
75    )]
76    UnsupportedIsolation {
77        /// Rust's target-operating-system identifier.
78        target_os: &'static str,
79    },
80}
81
82impl From<ProcessRunnerError> for ProcessBackendError {
83    fn from(source: ProcessRunnerError) -> Self {
84        Self::Runner { source }
85    }
86}
87
88/// One process execution boundary used by a runtime instance.
89///
90/// The admission and both runner capabilities are kept together so callers
91/// cannot accidentally pair a runner with a permission factory from another
92/// backend configuration. Child runtimes obtain their process session through
93/// [`ProcessBackend::new_session`] or [`ProcessBackend::new_session_with`],
94/// whose backend controls session isolation.
95#[derive(Clone)]
96pub struct ProcessSession {
97    admission: AcceptedLocalWorkspaceProcessAdmission,
98    runner: Arc<dyn ProcessRunner>,
99    permissioned_factory: Arc<dyn PermissionedProcessRunnerFactory>,
100    permission_view: Option<ProcessSessionPermissionView>,
101}
102
103impl ProcessSession {
104    /// Creates a session from an explicit, trusted adapter boundary.
105    ///
106    /// Production callers should select [`LocalProcessBackend::new`] so the
107    /// admission, runner, and reviewed-action factory are produced by one
108    /// backend implementation. This constructor exists for adapters and
109    /// deterministic fixtures that already own all three components.
110    #[must_use]
111    pub fn from_parts(
112        admission: AcceptedLocalWorkspaceProcessAdmission,
113        runner: Arc<dyn ProcessRunner>,
114        permissioned_factory: Arc<dyn PermissionedProcessRunnerFactory>,
115    ) -> Self {
116        Self {
117            admission,
118            runner,
119            permissioned_factory,
120            permission_view: None,
121        }
122    }
123
124    /// Attaches a read-only view of this session's retained permissions so child
125    /// runtimes may inherit already-approved ordinary capabilities without
126    /// mutating the parent session.
127    #[must_use]
128    pub fn with_permission_view(mut self, view: ProcessSessionPermissionView) -> Self {
129        self.permission_view = Some(view);
130        self
131    }
132
133    /// Returns the runtime admission selected for this process boundary.
134    #[must_use]
135    pub const fn admission(&self) -> AcceptedLocalWorkspaceProcessAdmission {
136        self.admission
137    }
138
139    /// Returns the runner for ordinary process actions.
140    #[must_use]
141    pub fn runner(&self) -> Arc<dyn ProcessRunner> {
142        Arc::clone(&self.runner)
143    }
144
145    /// Returns the factory for reviewed process actions.
146    #[must_use]
147    pub fn permissioned_factory(&self) -> Arc<dyn PermissionedProcessRunnerFactory> {
148        Arc::clone(&self.permissioned_factory)
149    }
150
151    /// Returns a read-only view of capabilities retained by this session, when
152    /// backed by a session-scoped permission store.
153    #[must_use]
154    pub fn permission_view(&self) -> Option<ProcessSessionPermissionView> {
155        self.permission_view.clone()
156    }
157}
158
159/// Request options for deriving a scoped [`ProcessSession`] from a [`ProcessBackend`].
160#[derive(Debug, Clone)]
161pub struct ProcessSessionRequest {
162    workspace_root: Option<PathBuf>,
163    workspace_writable: bool,
164    inherited_permissions: Option<ProcessSessionPermissionView>,
165    extra_path_rules: Vec<PathAccessRule>,
166}
167
168impl Default for ProcessSessionRequest {
169    fn default() -> Self {
170        Self {
171            workspace_root: None,
172            workspace_writable: true,
173            inherited_permissions: None,
174            extra_path_rules: Vec::new(),
175        }
176    }
177}
178
179impl ProcessSessionRequest {
180    /// Creates a default session request inheriting the backend's workspace root
181    /// and writability.
182    #[must_use]
183    pub fn new() -> Self {
184        Self::default()
185    }
186
187    /// Overrides the workspace root directory for the new session (for example,
188    /// an isolated git worktree).
189    #[must_use]
190    pub fn with_workspace_root(mut self, workspace_root: impl Into<PathBuf>) -> Self {
191        self.workspace_root = Some(workspace_root.into());
192        self
193    }
194
195    /// Keeps the workspace readable and not writable for isolated actions in
196    /// this session.
197    #[must_use]
198    pub fn read_only_workspace(mut self) -> Self {
199        self.workspace_writable = false;
200        self
201    }
202
203    /// Sets whether isolated actions in this session may write inside the
204    /// workspace root.
205    ///
206    /// A request cannot widen a backend that was already configured read-only.
207    #[must_use]
208    pub fn with_workspace_writable(mut self, writable: bool) -> Self {
209        self.workspace_writable = writable;
210        self
211    }
212
213    /// Seeds the new session with a read-only snapshot of an existing session's
214    /// approved ordinary capabilities.
215    #[must_use]
216    pub fn with_inherited_permissions(mut self, view: ProcessSessionPermissionView) -> Self {
217        self.inherited_permissions = Some(view);
218        self
219    }
220
221    /// Appends additional filesystem rules for the new session.
222    #[must_use]
223    pub fn with_extra_path_rules(
224        mut self,
225        rules: impl IntoIterator<Item = PathAccessRule>,
226    ) -> Self {
227        self.extra_path_rules = rules.into_iter().collect();
228        self
229    }
230
231    /// Returns the optional workspace root override.
232    #[must_use]
233    pub fn workspace_root(&self) -> Option<&Path> {
234        self.workspace_root.as_deref()
235    }
236
237    /// Returns whether the caller requested workspace writability.
238    #[must_use]
239    pub const fn workspace_writable(&self) -> bool {
240        self.workspace_writable
241    }
242
243    /// Returns the optional inherited permission view.
244    #[must_use]
245    pub fn inherited_permissions(&self) -> Option<&ProcessSessionPermissionView> {
246        self.inherited_permissions.as_ref()
247    }
248
249    /// Returns any extra filesystem access rules attached to this request.
250    #[must_use]
251    pub fn extra_path_rules(&self) -> &[PathAccessRule] {
252        &self.extra_path_rules
253    }
254}
255
256/// Stable host-process backend boundary consumed by coding composition.
257///
258/// The trait deliberately says nothing about how a platform enforces the
259/// selected behavior. Linux confines each action with Landlock and seccomp.
260/// Other targets report that isolation is unavailable instead of silently
261/// running on the host.
262pub trait ProcessBackend: Send + Sync {
263    /// Creates the process session for one runtime owner.
264    ///
265    /// Each call returns a session with the backend's configured admission and
266    /// runner capabilities. Backends may use a fresh session-scoped capability
267    /// store for every call, which keeps parent and child runtime state isolated.
268    fn new_session(&self) -> ProcessSession;
269
270    /// Creates a process session configured with scoped request options.
271    ///
272    /// The default implementation delegates to [`Self::new_session`] for custom
273    /// test or adapter backends that do not vary session parameters.
274    ///
275    /// # Errors
276    ///
277    /// Returns a [`ProcessBackendError`] when the requested workspace root,
278    /// sandbox rules, or inherited permissions cannot be validated.
279    fn new_session_with(
280        &self,
281        _request: ProcessSessionRequest,
282    ) -> Result<ProcessSession, ProcessBackendError> {
283        Ok(self.new_session())
284    }
285}
286
287/// Inputs shared by local process backend implementations.
288#[derive(Debug, Clone)]
289pub struct ProcessBackendOptions {
290    /// Trusted filesystem rules installed for isolated actions.
291    path_rules: Vec<PathAccessRule>,
292    /// Isolated-session capability ceiling, not a grant to an ordinary runner.
293    network_requests_allowed: bool,
294    /// When false, the workspace itself is readable and not writable.
295    workspace_writable: bool,
296    /// Host integrations the embedding application authorizes for isolated actions.
297    host_integrations: Vec<HostIntegration>,
298    gpg_agent_sockets: Option<GpgAgentSockets>,
299    /// Environment assignments validated and applied by the host backend.
300    environment_overrides: Vec<(OsString, OsString)>,
301}
302
303impl Default for ProcessBackendOptions {
304    fn default() -> Self {
305        Self {
306            path_rules: Vec::new(),
307            network_requests_allowed: true,
308            workspace_writable: true,
309            host_integrations: Vec::new(),
310            gpg_agent_sockets: None,
311            environment_overrides: Vec::new(),
312        }
313    }
314}
315
316impl ProcessBackendOptions {
317    /// Creates default options without preauthorized process capabilities.
318    #[must_use]
319    pub fn new() -> Self {
320        Self::default()
321    }
322
323    /// Sets trusted filesystem rules installed for isolated actions.
324    #[must_use]
325    pub fn with_path_rules(mut self, path_rules: impl IntoIterator<Item = PathAccessRule>) -> Self {
326        self.path_rules = path_rules.into_iter().collect();
327        self
328    }
329
330    /// Sets whether isolated process sessions may request network capability.
331    ///
332    /// Defaults to true, which still requires approval for each action. False
333    /// rejects network requests before review. Explicit host execution is not
334    /// isolated and is not restricted by this ceiling.
335    #[must_use]
336    pub fn with_network_requests_allowed(mut self, allowed: bool) -> Self {
337        self.network_requests_allowed = allowed;
338        self
339    }
340
341    /// Keeps the workspace readable and not writable for isolated actions.
342    ///
343    /// Baseline paths such as `/tmp` stay writable. Host execution ignores this.
344    #[must_use]
345    pub fn read_only_workspace(mut self) -> Self {
346        self.workspace_writable = false;
347        self
348    }
349
350    /// Sets host integrations the embedding application authorizes.
351    ///
352    /// The embedding application owns this decision; the backend treats the
353    /// listed integrations as part of the ordinary action baseline instead of
354    /// requiring a per-action request for them. Merry's CLI derives the list
355    /// from user-trusted global configuration, which preauthorizes the inner
356    /// action sandbox; project-local configuration never does. Endpoint
357    /// validation and path policy still apply per action, so a `deny_paths`
358    /// entry can keep a listed integration masked when it is not inside a
359    /// broader grant.
360    #[must_use]
361    pub fn with_host_integrations(
362        mut self,
363        host_integrations: impl IntoIterator<Item = HostIntegration>,
364    ) -> Self {
365        self.host_integrations = host_integrations.into_iter().collect();
366        self
367    }
368
369    /// Installs explicitly discovered native and auxiliary GnuPG socket paths.
370    #[must_use]
371    pub fn with_gpg_agent_sockets(mut self, sockets: GpgAgentSockets) -> Self {
372        self.gpg_agent_sockets = Some(sockets);
373        self
374    }
375
376    /// Sets environment assignments that the backend validates before applying.
377    #[must_use]
378    pub fn with_environment_overrides(
379        mut self,
380        environment_overrides: impl IntoIterator<Item = (OsString, OsString)>,
381    ) -> Self {
382        self.environment_overrides = environment_overrides.into_iter().collect();
383        self
384    }
385
386    /// Returns the trusted filesystem rules installed for isolated actions.
387    #[must_use]
388    pub fn path_rules(&self) -> &[PathAccessRule] {
389        &self.path_rules
390    }
391
392    /// Returns whether isolated sessions may request, not preauthorize, network access.
393    #[must_use]
394    pub fn network_requests_allowed(&self) -> bool {
395        self.network_requests_allowed
396    }
397
398    /// Returns host integrations already approved by the embedding application.
399    #[must_use]
400    pub fn host_integrations(&self) -> &[HostIntegration] {
401        &self.host_integrations
402    }
403
404    /// Returns the validated environment assignments applied by the backend.
405    #[must_use]
406    pub fn environment_overrides(&self) -> &[(OsString, OsString)] {
407        &self.environment_overrides
408    }
409}
410
411/// Current local host-process backend.
412///
413/// The backend owns the current host implementation choice. Its public
414/// session contract is intentionally independent of that choice, so adding a
415/// platform-specific backend does not change coding profile or runtime APIs.
416#[derive(Clone)]
417pub struct LocalProcessBackend {
418    new_session: Arc<dyn Fn() -> ProcessSession + Send + Sync>,
419    new_session_with: Arc<
420        dyn Fn(ProcessSessionRequest) -> Result<ProcessSession, ProcessBackendError> + Send + Sync,
421    >,
422}
423
424impl LocalProcessBackend {
425    /// Creates a fixed backend from one already constructed session.
426    ///
427    /// This is intended for trusted adapters and deterministic test fixtures.
428    /// Platform-selected production backends should use [`Self::new`] so the
429    /// admission is created together with the concrete enforcement strategy.
430    #[must_use]
431    pub fn from_session(session: ProcessSession) -> Self {
432        let child_session = session.clone();
433        let scoped_session = session;
434        Self {
435            new_session: Arc::new(move || child_session.clone()),
436            new_session_with: Arc::new(move |_request| Ok(scoped_session.clone())),
437        }
438    }
439
440    #[cfg(test)]
441    fn from_parts(
442        admission: AcceptedLocalWorkspaceProcessAdmission,
443        runner: Arc<dyn ProcessRunner>,
444        permissioned_factory: Arc<dyn PermissionedProcessRunnerFactory>,
445    ) -> Self {
446        Self::from_session(ProcessSession::from_parts(
447            admission,
448            runner,
449            permissioned_factory,
450        ))
451    }
452
453    /// Creates a platform-selected local process backend.
454    ///
455    /// # Errors
456    ///
457    /// Returns a [`ProcessBackendError`] when the selected backend cannot be
458    /// configured or the requested isolated behavior is unavailable.
459    pub fn new(
460        workspace_root: impl Into<PathBuf>,
461        mode: ProcessBackendMode,
462        options: ProcessBackendOptions,
463    ) -> Result<Self, ProcessBackendError> {
464        match mode {
465            ProcessBackendMode::Host => Self::unrestricted(workspace_root, options),
466            ProcessBackendMode::Isolated => Self::sandboxed(workspace_root, options),
467        }
468    }
469
470    /// Creates the current host-process implementation without an inner
471    /// operating-system sandbox.
472    ///
473    /// # Errors
474    ///
475    /// Returns a [`ProcessBackendError::Runner`] when an environment override
476    /// cannot be validated by the host runner.
477    pub fn unrestricted(
478        workspace_root: impl Into<PathBuf>,
479        options: ProcessBackendOptions,
480    ) -> Result<Self, ProcessBackendError> {
481        let workspace_root = workspace_root.into();
482        let environment_overrides = options.environment_overrides;
483        let runner = Arc::new(
484            TokioProcessRunner::new_at_workspace_root(workspace_root.clone())
485                .with_environment_overrides(environment_overrides.clone())?,
486        );
487        let permissioned_factory = Arc::new(UnrestrictedPermissionedProcessRunnerFactory::new(
488            Arc::clone(&runner) as Arc<dyn ProcessRunner>,
489        ));
490        let default_session = ProcessSession::from_parts(
491            AcceptedLocalWorkspaceProcessAdmission::accept_host(),
492            runner,
493            permissioned_factory,
494        );
495        let fallback_session = default_session.clone();
496        Ok(Self {
497            new_session: Arc::new(move || default_session.clone()),
498            new_session_with: Arc::new(move |request| {
499                let Some(root_override) = request.workspace_root else {
500                    return Ok(fallback_session.clone());
501                };
502                let runner = Arc::new(
503                    TokioProcessRunner::new_at_workspace_root(root_override)
504                        .with_environment_overrides(environment_overrides.clone())?,
505                );
506                let permissioned_factory =
507                    Arc::new(UnrestrictedPermissionedProcessRunnerFactory::new(
508                        Arc::clone(&runner) as Arc<dyn ProcessRunner>,
509                    ));
510                Ok(ProcessSession::from_parts(
511                    AcceptedLocalWorkspaceProcessAdmission::accept_host(),
512                    runner,
513                    permissioned_factory,
514                ))
515            }),
516        })
517    }
518
519    /// Creates the current isolated local-process implementation.
520    ///
521    /// On Linux, each action is confined with Landlock and, unless that action
522    /// was granted network, a seccomp filter. On macOS, each action is confined
523    /// with a Seatbelt profile. Other targets return
524    /// [`ProcessBackendError::UnsupportedIsolation`].
525    ///
526    /// # Errors
527    ///
528    /// Returns a [`ProcessBackendError`] when the workspace or sandbox
529    /// environment is invalid, a configured path cannot be enforced, or this
530    /// target has no isolated backend.
531    #[cfg(any(target_os = "linux", target_os = "macos"))]
532    pub fn sandboxed(
533        workspace_root: impl Into<PathBuf>,
534        options: ProcessBackendOptions,
535    ) -> Result<Self, ProcessBackendError> {
536        let workspace_root = workspace_root.into();
537        let mut environment = WorkspaceProcessEnvironment::from_current_process()
538            .with_host_integrations(options.host_integrations)
539            .with_overrides(options.environment_overrides)?
540            .validate_for_workspace(&workspace_root)?;
541        if let Some(sockets) = options.gpg_agent_sockets {
542            environment = environment.with_gpg_agent_sockets(sockets);
543        }
544        let mut rules_runner =
545            WorkspaceProcessRunner::new_at_workspace_root(workspace_root.clone())
546                .with_environment(environment.clone())
547                .with_path_rules(options.path_rules.iter().cloned());
548        if !options.workspace_writable {
549            rules_runner = rules_runner.read_only_workspace();
550        }
551        rules_runner.ensure_sandbox_rules()?;
552        Ok(Self::from_sandboxed_parts(
553            workspace_root,
554            environment,
555            options.path_rules,
556            options.network_requests_allowed,
557            options.workspace_writable,
558        ))
559    }
560
561    #[cfg(not(any(target_os = "linux", target_os = "macos")))]
562    pub fn sandboxed(
563        workspace_root: impl Into<PathBuf>,
564        options: ProcessBackendOptions,
565    ) -> Result<Self, ProcessBackendError> {
566        let _ = (workspace_root.into(), options);
567        Err(ProcessBackendError::UnsupportedIsolation {
568            target_os: std::env::consts::OS,
569        })
570    }
571
572    #[cfg(any(target_os = "linux", target_os = "macos"))]
573    fn from_sandboxed_parts(
574        workspace_root: PathBuf,
575        environment: WorkspaceProcessEnvironment,
576        path_rules: Vec<PathAccessRule>,
577        network_requests_allowed: bool,
578        workspace_writable: bool,
579    ) -> Self {
580        let child_workspace_root = workspace_root.clone();
581        let child_environment = environment.clone();
582        let child_path_rules = path_rules.clone();
583        let scoped_workspace_root = workspace_root;
584        let scoped_environment = environment;
585        let scoped_path_rules = path_rules;
586        Self {
587            new_session: Arc::new(move || {
588                Self::sandboxed_session(
589                    &child_workspace_root,
590                    &child_environment,
591                    &child_path_rules,
592                    network_requests_allowed,
593                    workspace_writable,
594                    ProcessSessionPermissions::new(),
595                )
596            }),
597            new_session_with: Arc::new(move |request| {
598                let target_root = request
599                    .workspace_root
600                    .as_deref()
601                    .unwrap_or(&scoped_workspace_root);
602                // Intersection: a scoped session can narrow a writable backend
603                // to read-only, never widen a read-only backend to writable.
604                let effective_writable = workspace_writable && request.workspace_writable;
605                let session_permissions = match request.inherited_permissions.as_ref() {
606                    Some(view) => ProcessSessionPermissions::from_inherited_view(view)?,
607                    None => ProcessSessionPermissions::new(),
608                };
609                let mut combined_rules =
610                    Vec::with_capacity(scoped_path_rules.len() + request.extra_path_rules.len());
611                combined_rules.extend(scoped_path_rules.iter().cloned());
612                combined_rules.extend(request.extra_path_rules);
613                let validated_env = if request.workspace_root.is_some() {
614                    scoped_environment
615                        .clone()
616                        .validate_for_workspace(target_root)?
617                } else {
618                    scoped_environment.clone()
619                };
620                if request.workspace_root.is_some() || !combined_rules.is_empty() {
621                    let mut rules_runner =
622                        WorkspaceProcessRunner::new_at_workspace_root(target_root)
623                            .with_environment(validated_env.clone())
624                            .with_path_rules(combined_rules.iter().cloned());
625                    if !effective_writable {
626                        rules_runner = rules_runner.read_only_workspace();
627                    }
628                    rules_runner.ensure_sandbox_rules()?;
629                }
630                Ok(Self::sandboxed_session(
631                    target_root,
632                    &validated_env,
633                    &combined_rules,
634                    network_requests_allowed,
635                    effective_writable,
636                    session_permissions,
637                ))
638            }),
639        }
640    }
641
642    #[cfg(any(target_os = "linux", target_os = "macos"))]
643    fn sandboxed_session(
644        workspace_root: &Path,
645        environment: &WorkspaceProcessEnvironment,
646        path_rules: &[PathAccessRule],
647        network_requests_allowed: bool,
648        workspace_writable: bool,
649        session_permissions: ProcessSessionPermissions,
650    ) -> ProcessSession {
651        let permission_view = session_permissions.view();
652        let background = crate::process_runner::BackgroundSupervisor::new();
653        let mut runner = WorkspaceProcessRunner::new_at_workspace_root(workspace_root)
654            .with_environment(environment.clone())
655            .with_path_rules(path_rules.iter().cloned())
656            .with_background(background.clone());
657        let mut permissioned_factory =
658            WorkspaceProcessRunnerFactory::new_at_workspace_root(workspace_root)
659                .with_environment(environment.clone())
660                .with_path_rules(path_rules.iter().cloned())
661                .with_network_requests_allowed(network_requests_allowed)
662                .with_background(background);
663        if !workspace_writable {
664            runner = runner.read_only_workspace();
665            permissioned_factory = permissioned_factory.read_only_workspace();
666        }
667        let runner = runner.with_session_permissions(session_permissions.clone());
668        let permissioned_factory =
669            permissioned_factory.with_session_permissions(session_permissions);
670        ProcessSession::from_parts(
671            AcceptedLocalWorkspaceProcessAdmission::accept_local_workspace(),
672            Arc::new(runner),
673            Arc::new(permissioned_factory),
674        )
675        .with_permission_view(permission_view)
676    }
677}
678
679impl ProcessBackend for LocalProcessBackend {
680    fn new_session(&self) -> ProcessSession {
681        (self.new_session)()
682    }
683
684    fn new_session_with(
685        &self,
686        request: ProcessSessionRequest,
687    ) -> Result<ProcessSession, ProcessBackendError> {
688        (self.new_session_with)(request)
689    }
690}
691
692/// Permissioned runner factory for the explicit host-process backend.
693///
694/// The host backend already exposes the process to the operating system, so a
695/// reviewed capability request reuses its runner. Runtime admission and action
696/// evidence remain active around the returned runner.
697#[derive(Clone)]
698pub struct UnrestrictedPermissionedProcessRunnerFactory {
699    runner: Arc<dyn ProcessRunner>,
700}
701
702impl UnrestrictedPermissionedProcessRunnerFactory {
703    /// Creates a factory that reuses the host-process runner.
704    #[must_use]
705    pub fn new(runner: Arc<dyn ProcessRunner>) -> Self {
706        Self { runner }
707    }
708}
709
710impl PermissionedProcessRunnerFactory for UnrestrictedPermissionedProcessRunnerFactory {
711    fn runner_for(&self, _request: &PermissionRequest) -> Arc<dyn ProcessRunner> {
712        Arc::clone(&self.runner)
713    }
714}
715
716#[cfg(test)]
717mod tests {
718    #[cfg(not(any(target_os = "linux", target_os = "macos")))]
719    use super::ProcessBackendError;
720    use super::{
721        LocalProcessBackend, ProcessBackend, ProcessBackendMode, ProcessBackendOptions,
722        TokioProcessRunner,
723    };
724    use merry_runtime::{
725        AcceptedLocalWorkspaceProcessAdmission, PermissionedProcessRunnerFactory, ProcessRunner,
726        StaticPermissionedProcessRunnerFactory,
727    };
728    #[cfg(any(target_os = "linux", target_os = "macos"))]
729    use std::path::PathBuf;
730    use std::sync::Arc;
731
732    #[test]
733    fn session_keeps_admission_with_runner_capabilities() {
734        let runner: Arc<dyn ProcessRunner> = Arc::new(TokioProcessRunner::new());
735        let factory: Arc<dyn PermissionedProcessRunnerFactory> = Arc::new(
736            StaticPermissionedProcessRunnerFactory::new(Arc::clone(&runner)),
737        );
738        let admission = AcceptedLocalWorkspaceProcessAdmission::accept_host();
739        let backend = LocalProcessBackend::from_parts(admission, runner, factory);
740
741        assert_eq!(backend.new_session().admission(), admission);
742    }
743
744    #[test]
745    fn backend_mode_is_semantic_and_does_not_encode_a_platform() {
746        assert_ne!(ProcessBackendMode::Host, ProcessBackendMode::Isolated);
747    }
748
749    #[cfg(any(target_os = "linux", target_os = "macos"))]
750    #[test]
751    fn backend_selection_binds_admission_to_the_selected_behavior() {
752        let temp = tempfile::tempdir().expect("temporary workspace should be created");
753        let host = LocalProcessBackend::new(
754            temp.path(),
755            ProcessBackendMode::Host,
756            ProcessBackendOptions::new(),
757        )
758        .expect("host backend should build");
759        assert_eq!(
760            host.new_session().admission().sandbox_profile(),
761            merry_runtime::LocalWorkspaceProcessSandboxProfile::Host
762        );
763
764        let isolated = LocalProcessBackend::new(
765            temp.path(),
766            ProcessBackendMode::Isolated,
767            ProcessBackendOptions::new(),
768        )
769        .expect("isolated backend should build before process execution");
770        assert_eq!(
771            isolated.new_session().admission().sandbox_profile(),
772            merry_runtime::LocalWorkspaceProcessSandboxProfile::LocalWorkspace
773        );
774        assert_eq!(
775            isolated.new_session().admission().sandbox_profile(),
776            merry_runtime::LocalWorkspaceProcessSandboxProfile::LocalWorkspace
777        );
778    }
779
780    #[cfg(not(any(target_os = "linux", target_os = "macos")))]
781    #[test]
782    fn isolated_backend_reports_unavailable_platform() {
783        let temp = tempfile::tempdir().expect("temporary workspace should be created");
784        let Err(error) = LocalProcessBackend::new(
785            temp.path(),
786            ProcessBackendMode::Isolated,
787            ProcessBackendOptions::new(),
788        ) else {
789            panic!("isolated backend should report unsupported platforms");
790        };
791
792        assert!(matches!(
793            error,
794            ProcessBackendError::UnsupportedIsolation { .. }
795        ));
796    }
797
798    #[test]
799    fn backend_options_default_to_no_host_overrides() {
800        let options = ProcessBackendOptions::new();
801        assert!(options.path_rules().is_empty());
802        assert!(options.host_integrations().is_empty());
803        assert!(options.environment_overrides().is_empty());
804        assert!(options.workspace_writable);
805    }
806
807    #[cfg(any(target_os = "linux", target_os = "macos"))]
808    #[test]
809    fn sandboxed_backend_allows_user_grant_covering_product_private_directory() {
810        use merry_runtime::{PathAccess, PathAccessRule, PathAccessRuleSource};
811
812        let workspace = tempfile::tempdir().expect("workspace");
813        let parent = PathBuf::from("/var/merry-path-check");
814        let private = parent.join("merry/providers");
815        let options = ProcessBackendOptions::new().with_path_rules([
816            PathAccessRule::new(
817                parent,
818                PathAccess::ReadOnly,
819                PathAccessRuleSource::TrustedGlobalConfig,
820            ),
821            PathAccessRule::new(
822                private,
823                PathAccess::Deny,
824                PathAccessRuleSource::ProductPrivate,
825            ),
826        ]);
827
828        LocalProcessBackend::sandboxed(workspace.path(), options)
829            .expect("explicit user grant covering a ProductPrivate path must not block startup");
830    }
831
832    #[cfg(any(target_os = "linux", target_os = "macos"))]
833    #[tokio::test(flavor = "current_thread")]
834    async fn new_session_with_read_only_workspace_and_inherited_permissions_stays_isolated() {
835        use crate::{
836            ProcessSessionRequest,
837            process_runner::tests::{fixture_root, permission_request},
838        };
839        use merry_runtime::{
840            ProcessActionIntent, ProcessEnvPolicy, ProcessExitStatus, ProcessRunnerContext,
841        };
842        use serde_json::json;
843
844        let root = tempfile::tempdir_in(fixture_root()).expect("fixture root outside /tmp");
845        let workspace = root.path().join("workspace");
846        let extra = root.path().join("extra");
847        std::fs::create_dir_all(&workspace).expect("workspace dir");
848        std::fs::create_dir_all(&extra).expect("extra dir");
849        std::fs::write(workspace.join("hello.txt"), "hi\n").expect("seed workspace");
850        std::fs::write(extra.join("shared.txt"), "from-extra\n").expect("seed extra");
851
852        let backend = LocalProcessBackend::sandboxed(&workspace, ProcessBackendOptions::new())
853            .expect("isolated backend should build");
854        let parent_session = backend.new_session();
855        let parent_view = parent_session
856            .permission_view()
857            .expect("sandboxed session should expose a permission view");
858
859        // Grant the parent session read access to `extra` via an approved request.
860        let grant_request = permission_request(json!({
861            "requested": {
862                "paths": [{
863                    "path": extra.display().to_string(),
864                    "access": "ro"
865                }]
866            },
867            "for_action": { "command": "true", "cwd": "." }
868        }));
869        let _ = parent_session
870            .permissioned_factory()
871            .runner_for(&grant_request);
872
873        let child_session = backend
874            .new_session_with(
875                ProcessSessionRequest::new()
876                    .read_only_workspace()
877                    .with_inherited_permissions(parent_view.clone()),
878            )
879            .expect("read-only child session should build");
880        let child_view = child_session
881            .permission_view()
882            .expect("child session should expose its own permission view");
883        assert_eq!(
884            child_view
885                .snapshot()
886                .expect("child snapshot")
887                .path_rules()
888                .len(),
889            parent_view
890                .snapshot()
891                .expect("parent snapshot")
892                .path_rules()
893                .len(),
894            "child should inherit parent's approved ordinary path grants"
895        );
896
897        // Child can read inside workspace & inherited extra dir, and cannot write workspace.
898        let read_intent = ProcessActionIntent::new(
899            vec![
900                "sh".to_owned(),
901                "-c".to_owned(),
902                format!("cat hello.txt && cat {}/shared.txt", extra.display()),
903            ],
904            None,
905            ProcessEnvPolicy::empty(),
906            None,
907            4096,
908            4096,
909        )
910        .expect("valid read intent");
911        let read_out = child_session
912            .runner()
913            .run(
914                read_intent,
915                ProcessRunnerContext::new(tokio_util::sync::CancellationToken::new()),
916            )
917            .await
918            .expect("read command should run in read-only sandbox");
919        assert_eq!(
920            read_out.status(),
921            ProcessExitStatus::Exited(0),
922            "stderr: {}",
923            read_out.stderr_text()
924        );
925        assert!(read_out.stdout_text().contains("hi"));
926        assert!(read_out.stdout_text().contains("from-extra"));
927
928        let write_intent = ProcessActionIntent::new(
929            vec![
930                "sh".to_owned(),
931                "-c".to_owned(),
932                "touch should-fail.txt".to_owned(),
933            ],
934            None,
935            ProcessEnvPolicy::empty(),
936            None,
937            4096,
938            4096,
939        )
940        .expect("valid write intent");
941        let write_out = child_session
942            .runner()
943            .run(
944                write_intent,
945                ProcessRunnerContext::new(tokio_util::sync::CancellationToken::new()),
946            )
947            .await
948            .expect("write command should execute and be refused by OS sandbox");
949        assert_ne!(write_out.status(), ProcessExitStatus::Exited(0));
950        assert!(!workspace.join("should-fail.txt").exists());
951
952        // Child's extra grant must not leak back to parent.
953        let child_only_dir = root.path().join("child-only");
954        std::fs::create_dir_all(&child_only_dir).expect("child only dir");
955        let child_grant_request = permission_request(json!({
956            "requested": {
957                "paths": [{
958                    "path": child_only_dir.display().to_string(),
959                    "access": "ro"
960                }]
961            },
962            "for_action": { "command": "true", "cwd": "." }
963        }));
964        let _ = child_session
965            .permissioned_factory()
966            .runner_for(&child_grant_request);
967        assert_eq!(
968            parent_view
969                .snapshot()
970                .expect("parent snapshot")
971                .path_rules()
972                .len(),
973            1,
974            "child-only grants must not mutate parent session permissions"
975        );
976    }
977}