merry_runtime/process/
session_permissions.rs1use super::{
4 PermissionedProcessRunnerFactory, ProcessActionIntent, ProcessRunner, ProcessRunnerContext,
5 ProcessRunnerError, ProcessRunnerFuture,
6};
7use crate::{HostIntegration, PathAccess, PathAccessRule, PermissionRequest, RequestedCapability};
8use std::sync::{Arc, RwLock};
9
10#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12pub enum ProcessPathGrantConstraint {
13 Ordinary,
15 ReviewRequired,
17 ProtectedMetadata,
19}
20
21#[derive(Debug, Clone)]
23pub struct ProcessPathGrant {
24 rule: PathAccessRule,
25 constraint: ProcessPathGrantConstraint,
26}
27
28pub struct PreparedProcessPermission {
30 runner: Arc<dyn ProcessRunner>,
31 grants: Vec<ProcessPathGrant>,
32}
33
34impl PreparedProcessPermission {
35 #[must_use]
37 pub fn new(runner: Arc<dyn ProcessRunner>, grants: Vec<ProcessPathGrant>) -> Self {
38 Self { runner, grants }
39 }
40}
41
42impl ProcessPathGrant {
43 #[must_use]
45 pub fn new(rule: PathAccessRule, constraint: ProcessPathGrantConstraint) -> Self {
46 Self { rule, constraint }
47 }
48}
49
50#[derive(Debug, Clone, Default)]
52pub struct ProcessSessionPermissionSnapshot {
53 path_rules: Vec<PathAccessRule>,
54 host_integrations: Vec<HostIntegration>,
55}
56
57impl ProcessSessionPermissionSnapshot {
58 #[must_use]
60 pub fn path_rules(&self) -> &[PathAccessRule] {
61 &self.path_rules
62 }
63
64 #[must_use]
66 pub fn host_integrations(&self) -> &[HostIntegration] {
67 &self.host_integrations
68 }
69}
70
71#[derive(Debug, Clone)]
73pub struct ProcessSessionPermissionView {
74 state: Arc<RwLock<ProcessSessionPermissionSnapshot>>,
75}
76
77impl ProcessSessionPermissionView {
78 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#[derive(Debug, Clone, Default)]
89pub struct ProcessSessionPermissions {
90 state: Arc<RwLock<ProcessSessionPermissionSnapshot>>,
91}
92
93impl ProcessSessionPermissions {
94 #[must_use]
96 pub fn new() -> Self {
97 Self::default()
98 }
99
100 #[must_use]
105 pub fn from_snapshot(snapshot: ProcessSessionPermissionSnapshot) -> Self {
106 Self {
107 state: Arc::new(RwLock::new(snapshot)),
108 }
109 }
110
111 pub fn from_inherited_view(
117 view: &ProcessSessionPermissionView,
118 ) -> Result<Self, ProcessRunnerError> {
119 Ok(Self::from_snapshot(view.snapshot()?))
120 }
121
122 #[must_use]
124 pub fn view(&self) -> ProcessSessionPermissionView {
125 ProcessSessionPermissionView {
126 state: Arc::clone(&self.state),
127 }
128 }
129
130 #[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 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#[derive(Debug, Clone)]
197pub struct SessionPermissionedProcessRunnerFactory<Factory> {
198 permissions: ProcessSessionPermissions,
199 backend: Factory,
200}
201
202impl<Factory> SessionPermissionedProcessRunnerFactory<Factory> {
203 #[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;