Skip to main content

merry_runtime/process/
session_permissions.rs

1//! Runtime-owned capability retention, independent of host filesystem mechanics.
2
3use super::{
4    PermissionedProcessRunnerFactory, ProcessActionIntent, ProcessRunner, ProcessRunnerContext,
5    ProcessRunnerError, ProcessRunnerFuture,
6};
7use crate::{HostIntegration, PathAccess, PathAccessRule, PermissionRequest, RequestedCapability};
8use std::sync::{Arc, RwLock};
9
10/// Backend facts that constrain retention of an approved path capability.
11#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12pub enum ProcessPathGrantConstraint {
13    /// No additional path constraint was found by the backend.
14    Ordinary,
15    /// The path falls under an explicit per-action review declaration.
16    ReviewRequired,
17    /// The path belongs to metadata protected independently of ordinary grants.
18    ProtectedMetadata,
19}
20
21/// A normalized approved path and the constraints found while materializing it.
22#[derive(Debug, Clone)]
23pub struct ProcessPathGrant {
24    rule: PathAccessRule,
25    constraint: ProcessPathGrantConstraint,
26}
27
28/// An adapter's prepared action runner and normalized capability evidence.
29pub struct PreparedProcessPermission {
30    runner: Arc<dyn ProcessRunner>,
31    grants: Vec<ProcessPathGrant>,
32}
33
34impl PreparedProcessPermission {
35    /// Packages an already validated runner without retaining its grants.
36    #[must_use]
37    pub fn new(runner: Arc<dyn ProcessRunner>, grants: Vec<ProcessPathGrant>) -> Self {
38        Self { runner, grants }
39    }
40}
41
42impl ProcessPathGrant {
43    /// Constructs backend evidence; this does not grant or retain any authority.
44    #[must_use]
45    pub fn new(rule: PathAccessRule, constraint: ProcessPathGrantConstraint) -> Self {
46        Self { rule, constraint }
47    }
48}
49
50/// Immutable capabilities retained by one runtime session.
51#[derive(Debug, Clone, Default)]
52pub struct ProcessSessionPermissionSnapshot {
53    path_rules: Vec<PathAccessRule>,
54    host_integrations: Vec<HostIntegration>,
55}
56
57impl ProcessSessionPermissionSnapshot {
58    /// Returns normalized, session-scoped path grants.
59    #[must_use]
60    pub fn path_rules(&self) -> &[PathAccessRule] {
61        &self.path_rules
62    }
63
64    /// Returns explicitly approved native host integrations.
65    #[must_use]
66    pub fn host_integrations(&self) -> &[HostIntegration] {
67        &self.host_integrations
68    }
69}
70
71/// Read-only access supplied to process adapters; it cannot record a grant.
72#[derive(Debug, Clone)]
73pub struct ProcessSessionPermissionView {
74    state: Arc<RwLock<ProcessSessionPermissionSnapshot>>,
75}
76
77impl ProcessSessionPermissionView {
78    /// Captures capabilities for a preparation, failing closed on poisoned state.
79    pub fn snapshot(&self) -> Result<ProcessSessionPermissionSnapshot, ProcessRunnerError> {
80        self.state.read().map(|state| state.clone()).map_err(|_| {
81            ProcessRunnerError::infrastructure("runtime session permission state lock was poisoned")
82        })
83    }
84}
85
86/// Capability state owned by a single runtime session, never a global store.
87/// Network, explicitly reviewed paths, and protected metadata remain action-only.
88#[derive(Debug, Clone, Default)]
89pub struct ProcessSessionPermissions {
90    state: Arc<RwLock<ProcessSessionPermissionSnapshot>>,
91}
92
93impl ProcessSessionPermissions {
94    /// Creates an empty, independent session.
95    #[must_use]
96    pub fn new() -> Self {
97        Self::default()
98    }
99
100    /// Creates an independent session seeded with an immutable capability snapshot.
101    ///
102    /// Subsequent grants retained in the returned session stay isolated from any
103    /// parent or sibling sessions that produced the snapshot.
104    #[must_use]
105    pub fn from_snapshot(snapshot: ProcessSessionPermissionSnapshot) -> Self {
106        Self {
107            state: Arc::new(RwLock::new(snapshot)),
108        }
109    }
110
111    /// Creates an independent session seeded from a read-only parent permission view.
112    ///
113    /// # Errors
114    ///
115    /// Fails closed if the parent permission lock was poisoned.
116    pub fn from_inherited_view(
117        view: &ProcessSessionPermissionView,
118    ) -> Result<Self, ProcessRunnerError> {
119        Ok(Self::from_snapshot(view.snapshot()?))
120    }
121
122    /// Supplies a read-only view to an ordinary or permissioned process backend.
123    #[must_use]
124    pub fn view(&self) -> ProcessSessionPermissionView {
125        ProcessSessionPermissionView {
126            state: Arc::clone(&self.state),
127        }
128    }
129
130    /// Wraps an adapter with runtime-owned approval retention. The adapter must
131    /// consume this session's read-only view when constructing its runners.
132    #[must_use]
133    pub fn with_factory<Factory: PermissionedProcessRunnerFactory>(
134        self,
135        backend: Factory,
136    ) -> SessionPermissionedProcessRunnerFactory<Factory> {
137        SessionPermissionedProcessRunnerFactory {
138            permissions: self,
139            backend,
140        }
141    }
142
143    /// Clears all retained session-scoped path and host-integration grants.
144    ///
145    /// Used when a live session replaces its process sandbox configuration so
146    /// previously approved capabilities do not silently outlive a tightened
147    /// baseline.
148    ///
149    /// # Errors
150    ///
151    /// Fails closed if the session permission lock was poisoned.
152    pub fn clear(&self) -> Result<(), ProcessRunnerError> {
153        let mut state = self.state.write().map_err(|_| {
154            ProcessRunnerError::infrastructure("runtime session permission state lock was poisoned")
155        })?;
156        state.path_rules.clear();
157        state.host_integrations.clear();
158        Ok(())
159    }
160
161    fn retain(
162        &self,
163        request: &PermissionRequest,
164        grants: Vec<ProcessPathGrant>,
165    ) -> Result<(), ProcessRunnerError> {
166        let mut state = self.state.write().map_err(|_| {
167            ProcessRunnerError::infrastructure("runtime session permission state lock was poisoned")
168        })?;
169        state
170            .path_rules
171            .extend(grants.into_iter().filter_map(|grant| {
172                (grant.constraint == ProcessPathGrantConstraint::Ordinary
173                    && !grant.rule.review_required()
174                    && grant.rule.access() != PathAccess::Deny)
175                    .then_some(grant.rule)
176            }));
177        normalize_grants(&mut state.path_rules);
178        state
179            .host_integrations
180            .extend(
181                request
182                    .requested()
183                    .iter()
184                    .filter_map(|capability| match capability {
185                        RequestedCapability::HostIntegration(integration) => Some(*integration),
186                        _ => None,
187                    }),
188            );
189        state.host_integrations.sort_unstable();
190        state.host_integrations.dedup();
191        Ok(())
192    }
193}
194
195/// Runtime decorator that records approved capabilities, not OS mount policy.
196#[derive(Debug, Clone)]
197pub struct SessionPermissionedProcessRunnerFactory<Factory> {
198    permissions: ProcessSessionPermissions,
199    backend: Factory,
200}
201
202impl<Factory> SessionPermissionedProcessRunnerFactory<Factory> {
203    /// Returns the adapter for backend-specific inspection, without write access
204    /// to session permission state.
205    #[must_use]
206    pub fn backend(&self) -> &Factory {
207        &self.backend
208    }
209}
210
211impl<Factory: PermissionedProcessRunnerFactory> PermissionedProcessRunnerFactory
212    for SessionPermissionedProcessRunnerFactory<Factory>
213{
214    fn validate_request(&self, request: &PermissionRequest) -> Result<(), ProcessRunnerError> {
215        self.backend.validate_request(request)
216    }
217
218    fn request_capabilities_are_satisfied(
219        &self,
220        request: &PermissionRequest,
221    ) -> Result<bool, ProcessRunnerError> {
222        self.backend.request_capabilities_are_satisfied(request)
223    }
224
225    fn runner_for(&self, request: &PermissionRequest) -> Arc<dyn ProcessRunner> {
226        let result = self
227            .backend
228            .prepare_approved_request(request)
229            .and_then(|prepared| {
230                self.permissions.retain(request, prepared.grants)?;
231                Ok(prepared.runner)
232            });
233        match result {
234            Ok(runner) => runner,
235            Err(error) => Arc::new(RejectedRunner(error)),
236        }
237    }
238}
239
240struct RejectedRunner(ProcessRunnerError);
241
242impl ProcessRunner for RejectedRunner {
243    fn run<'a>(
244        &'a self,
245        _intent: ProcessActionIntent,
246        _context: ProcessRunnerContext,
247    ) -> ProcessRunnerFuture<'a> {
248        Box::pin(async { Err(self.0.clone()) })
249    }
250}
251
252fn normalize_grants(rules: &mut Vec<PathAccessRule>) {
253    rules.sort_by(|left, right| {
254        left.path()
255            .components()
256            .count()
257            .cmp(&right.path().components().count())
258            .then_with(|| left.path().cmp(right.path()))
259            .then_with(|| {
260                (left.access() != PathAccess::ReadWrite)
261                    .cmp(&(right.access() != PathAccess::ReadWrite))
262            })
263    });
264    let mut retained = Vec::with_capacity(rules.len());
265    for rule in rules.drain(..) {
266        if !retained.iter().any(|ancestor: &PathAccessRule| {
267            rule.path().starts_with(ancestor.path()) && ancestor.access().covers(rule.access())
268        }) {
269            retained.push(rule);
270        }
271    }
272    *rules = retained;
273}
274
275#[cfg(test)]
276mod tests;