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    fn retain(
144        &self,
145        request: &PermissionRequest,
146        grants: Vec<ProcessPathGrant>,
147    ) -> Result<(), ProcessRunnerError> {
148        let mut state = self.state.write().map_err(|_| {
149            ProcessRunnerError::infrastructure("runtime session permission state lock was poisoned")
150        })?;
151        state
152            .path_rules
153            .extend(grants.into_iter().filter_map(|grant| {
154                (grant.constraint == ProcessPathGrantConstraint::Ordinary
155                    && !grant.rule.review_required()
156                    && grant.rule.access() != PathAccess::Deny)
157                    .then_some(grant.rule)
158            }));
159        normalize_grants(&mut state.path_rules);
160        state
161            .host_integrations
162            .extend(
163                request
164                    .requested()
165                    .iter()
166                    .filter_map(|capability| match capability {
167                        RequestedCapability::HostIntegration(integration) => Some(*integration),
168                        _ => None,
169                    }),
170            );
171        state.host_integrations.sort_unstable();
172        state.host_integrations.dedup();
173        Ok(())
174    }
175}
176
177/// Runtime decorator that records approved capabilities, not OS mount policy.
178#[derive(Debug, Clone)]
179pub struct SessionPermissionedProcessRunnerFactory<Factory> {
180    permissions: ProcessSessionPermissions,
181    backend: Factory,
182}
183
184impl<Factory> SessionPermissionedProcessRunnerFactory<Factory> {
185    /// Returns the adapter for backend-specific inspection, without write access
186    /// to session permission state.
187    #[must_use]
188    pub fn backend(&self) -> &Factory {
189        &self.backend
190    }
191}
192
193impl<Factory: PermissionedProcessRunnerFactory> PermissionedProcessRunnerFactory
194    for SessionPermissionedProcessRunnerFactory<Factory>
195{
196    fn validate_request(&self, request: &PermissionRequest) -> Result<(), ProcessRunnerError> {
197        self.backend.validate_request(request)
198    }
199
200    fn request_capabilities_are_satisfied(
201        &self,
202        request: &PermissionRequest,
203    ) -> Result<bool, ProcessRunnerError> {
204        self.backend.request_capabilities_are_satisfied(request)
205    }
206
207    fn runner_for(&self, request: &PermissionRequest) -> Arc<dyn ProcessRunner> {
208        let result = self
209            .backend
210            .prepare_approved_request(request)
211            .and_then(|prepared| {
212                self.permissions.retain(request, prepared.grants)?;
213                Ok(prepared.runner)
214            });
215        match result {
216            Ok(runner) => runner,
217            Err(error) => Arc::new(RejectedRunner(error)),
218        }
219    }
220}
221
222struct RejectedRunner(ProcessRunnerError);
223
224impl ProcessRunner for RejectedRunner {
225    fn run<'a>(
226        &'a self,
227        _intent: ProcessActionIntent,
228        _context: ProcessRunnerContext,
229    ) -> ProcessRunnerFuture<'a> {
230        Box::pin(async { Err(self.0.clone()) })
231    }
232}
233
234fn normalize_grants(rules: &mut Vec<PathAccessRule>) {
235    rules.sort_by(|left, right| {
236        left.path()
237            .components()
238            .count()
239            .cmp(&right.path().components().count())
240            .then_with(|| left.path().cmp(right.path()))
241            .then_with(|| {
242                (left.access() != PathAccess::ReadWrite)
243                    .cmp(&(right.access() != PathAccess::ReadWrite))
244            })
245    });
246    let mut retained = Vec::with_capacity(rules.len());
247    for rule in rules.drain(..) {
248        if !retained.iter().any(|ancestor: &PathAccessRule| {
249            rule.path().starts_with(ancestor.path()) && ancestor.access().covers(rule.access())
250        }) {
251            retained.push(rule);
252        }
253    }
254    *rules = retained;
255}
256
257#[cfg(test)]
258mod tests;