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 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#[derive(Debug, Clone)]
179pub struct SessionPermissionedProcessRunnerFactory<Factory> {
180 permissions: ProcessSessionPermissions,
181 backend: Factory,
182}
183
184impl<Factory> SessionPermissionedProcessRunnerFactory<Factory> {
185 #[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;