1use super::{
4 PermissionedProcessRunnerFactory, ProcessActionIntent, ProcessRunner, ProcessRunnerContext,
5 ProcessRunnerError, ProcessRunnerFuture,
6};
7use crate::{HostIntegration, PathAccess, PathAccessRule, PermissionRequest, RequestedCapability};
8use merry_core::ApprovalScope;
9use std::{
10 fmt,
11 path::PathBuf,
12 sync::{Arc, RwLock},
13};
14
15#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
17pub struct SessionGrantId(u64);
18
19impl SessionGrantId {
20 #[must_use]
22 pub const fn as_u64(self) -> u64 {
23 self.0
24 }
25
26 #[must_use]
28 pub const fn from_u64(value: u64) -> Self {
29 Self(value)
30 }
31}
32
33impl fmt::Display for SessionGrantId {
34 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
35 write!(f, "grant-{}", self.0)
36 }
37}
38
39#[derive(Debug, Clone, PartialEq, Eq)]
41pub enum SessionPermissionGrantKind {
42 Path {
44 path: PathBuf,
46 access: PathAccess,
48 },
49 Network,
51 NetworkDomain(String),
53 HostIntegration(HostIntegration),
55}
56
57#[derive(Debug, Clone, PartialEq, Eq)]
59pub struct SessionPermissionGrant {
60 id: SessionGrantId,
61 kind: SessionPermissionGrantKind,
62}
63
64impl SessionPermissionGrant {
65 #[must_use]
67 pub const fn new(id: SessionGrantId, kind: SessionPermissionGrantKind) -> Self {
68 Self { id, kind }
69 }
70
71 #[must_use]
73 pub const fn id(&self) -> SessionGrantId {
74 self.id
75 }
76
77 #[must_use]
79 pub const fn kind(&self) -> &SessionPermissionGrantKind {
80 &self.kind
81 }
82}
83
84#[derive(Debug, Clone, Copy, PartialEq, Eq)]
86pub enum ProcessPathGrantConstraint {
87 Ordinary,
89 ProtectedMetadata,
91}
92
93#[derive(Debug, Clone)]
95pub struct ProcessPathGrant {
96 rule: PathAccessRule,
97 constraint: ProcessPathGrantConstraint,
98}
99
100pub struct PreparedProcessPermission {
102 runner: Arc<dyn ProcessRunner>,
103 grants: Vec<ProcessPathGrant>,
104}
105
106impl PreparedProcessPermission {
107 #[must_use]
109 pub fn new(runner: Arc<dyn ProcessRunner>, grants: Vec<ProcessPathGrant>) -> Self {
110 Self { runner, grants }
111 }
112}
113
114impl ProcessPathGrant {
115 #[must_use]
117 pub fn new(rule: PathAccessRule, constraint: ProcessPathGrantConstraint) -> Self {
118 Self { rule, constraint }
119 }
120}
121
122#[derive(Debug, Clone, Default)]
124pub struct ProcessSessionPermissionSnapshot {
125 path_rules: Vec<PathAccessRule>,
126 host_integrations: Vec<HostIntegration>,
127 network_allowed: bool,
128 allowed_domains: Vec<String>,
129 grants: Vec<SessionPermissionGrant>,
130}
131
132impl ProcessSessionPermissionSnapshot {
133 #[must_use]
135 pub fn path_rules(&self) -> &[PathAccessRule] {
136 &self.path_rules
137 }
138
139 #[must_use]
141 pub fn host_integrations(&self) -> &[HostIntegration] {
142 &self.host_integrations
143 }
144
145 #[must_use]
147 pub const fn network_allowed(&self) -> bool {
148 self.network_allowed
149 }
150
151 #[must_use]
153 pub fn allowed_domains(&self) -> &[String] {
154 &self.allowed_domains
155 }
156
157 #[must_use]
159 pub fn allows_domain(&self, host: &str) -> bool {
160 let Some(normalized) = crate::normalize_network_domain(host) else {
161 return false;
162 };
163 self.allowed_domains
164 .iter()
165 .any(|domain| domain == &normalized)
166 }
167
168 #[must_use]
170 pub fn grants(&self) -> &[SessionPermissionGrant] {
171 &self.grants
172 }
173}
174
175#[derive(Debug, Clone)]
176struct ProcessSessionPermissionState {
177 next_id: u64,
178 path_grants: Vec<(SessionGrantId, PathAccessRule)>,
179 host_integrations: Vec<(SessionGrantId, HostIntegration)>,
180 network_grant_id: Option<SessionGrantId>,
181 domain_grants: Vec<(SessionGrantId, String)>,
182}
183
184impl Default for ProcessSessionPermissionState {
185 fn default() -> Self {
186 Self {
187 next_id: 1,
188 path_grants: Vec::new(),
189 host_integrations: Vec::new(),
190 network_grant_id: None,
191 domain_grants: Vec::new(),
192 }
193 }
194}
195
196impl ProcessSessionPermissionState {
197 fn allocate_id(&mut self) -> SessionGrantId {
198 let id = SessionGrantId(self.next_id);
199 self.next_id = self.next_id.saturating_add(1);
200 id
201 }
202
203 fn from_snapshot(snapshot: ProcessSessionPermissionSnapshot) -> Self {
204 let mut state = Self::default();
205 if snapshot.network_allowed {
206 state.network_grant_id = Some(state.allocate_id());
207 }
208 state.retain_domains(snapshot.allowed_domains);
209 let mut integrations = snapshot.host_integrations;
210 integrations.sort_unstable();
211 integrations.dedup();
212 for integration in integrations {
213 let id = state.allocate_id();
214 state.host_integrations.push((id, integration));
215 }
216 for rule in snapshot.path_rules {
217 let id = state.allocate_id();
218 state.path_grants.push((id, rule));
219 }
220 normalize_grant_entries(&mut state.path_grants);
221 state
222 }
223
224 fn snapshot(&self) -> ProcessSessionPermissionSnapshot {
225 let path_rules = self
226 .path_grants
227 .iter()
228 .map(|(_, rule)| rule.clone())
229 .collect();
230 let host_integrations = self
231 .host_integrations
232 .iter()
233 .map(|(_, integration)| *integration)
234 .collect();
235 let network_allowed = self.network_grant_id.is_some();
236 let allowed_domains = self
237 .domain_grants
238 .iter()
239 .map(|(_, domain)| domain.clone())
240 .collect();
241 let grants = self.ordered_grants();
242 ProcessSessionPermissionSnapshot {
243 path_rules,
244 host_integrations,
245 network_allowed,
246 allowed_domains,
247 grants,
248 }
249 }
250
251 fn ordered_grants(&self) -> Vec<SessionPermissionGrant> {
252 let mut grants = Vec::with_capacity(
253 usize::from(self.network_grant_id.is_some())
254 + self.domain_grants.len()
255 + self.host_integrations.len()
256 + self.path_grants.len(),
257 );
258 if let Some(id) = self.network_grant_id {
259 grants.push(SessionPermissionGrant::new(
260 id,
261 SessionPermissionGrantKind::Network,
262 ));
263 }
264 for (id, domain) in &self.domain_grants {
265 grants.push(SessionPermissionGrant::new(
266 *id,
267 SessionPermissionGrantKind::NetworkDomain(domain.clone()),
268 ));
269 }
270 for &(id, integration) in &self.host_integrations {
271 grants.push(SessionPermissionGrant::new(
272 id,
273 SessionPermissionGrantKind::HostIntegration(integration),
274 ));
275 }
276 for (id, rule) in &self.path_grants {
277 grants.push(SessionPermissionGrant::new(
278 *id,
279 SessionPermissionGrantKind::Path {
280 path: rule.path().to_path_buf(),
281 access: rule.access(),
282 },
283 ));
284 }
285 grants
286 }
287
288 fn retain_path_rules(&mut self, incoming: impl IntoIterator<Item = PathAccessRule>) {
289 for rule in incoming {
290 if self.path_grants.iter().any(|(_, existing)| {
291 rule.path().starts_with(existing.path()) && existing.access().covers(rule.access())
292 }) {
293 continue;
294 }
295 let id = self.allocate_id();
296 self.path_grants.push((id, rule));
297 }
298 normalize_grant_entries(&mut self.path_grants);
299 }
300
301 fn retain_host_integration(&mut self, integration: HostIntegration) {
302 if self
303 .host_integrations
304 .iter()
305 .any(|(_, existing)| *existing == integration)
306 {
307 return;
308 }
309 let id = self.allocate_id();
310 self.host_integrations.push((id, integration));
311 self.host_integrations
312 .sort_unstable_by_key(|(_, item)| *item);
313 }
314
315 fn retain_network(&mut self) {
316 if self.network_grant_id.is_none() {
317 self.network_grant_id = Some(self.allocate_id());
318 }
319 }
320
321 fn retain_domains(&mut self, incoming: impl IntoIterator<Item = String>) {
322 for domain in incoming {
323 let Some(normalized) = crate::normalize_network_domain(&domain) else {
324 continue;
325 };
326 if self
327 .domain_grants
328 .iter()
329 .any(|(_, existing)| existing == &normalized)
330 {
331 continue;
332 }
333 let id = self.allocate_id();
334 self.domain_grants.push((id, normalized));
335 }
336 self.domain_grants
337 .sort_by(|(_, left), (_, right)| left.cmp(right));
338 }
339
340 fn revoke(&mut self, id: SessionGrantId) -> bool {
341 if self.network_grant_id == Some(id) {
342 self.network_grant_id = None;
343 return true;
344 }
345 if let Some(index) = self
346 .domain_grants
347 .iter()
348 .position(|(entry_id, _)| *entry_id == id)
349 {
350 self.domain_grants.remove(index);
351 return true;
352 }
353 if let Some(index) = self
354 .host_integrations
355 .iter()
356 .position(|(entry_id, _)| *entry_id == id)
357 {
358 self.host_integrations.remove(index);
359 return true;
360 }
361 if let Some(index) = self
362 .path_grants
363 .iter()
364 .position(|(entry_id, _)| *entry_id == id)
365 {
366 self.path_grants.remove(index);
367 return true;
368 }
369 false
370 }
371
372 fn clear(&mut self) {
373 self.path_grants.clear();
374 self.host_integrations.clear();
375 self.network_grant_id = None;
376 self.domain_grants.clear();
377 }
378}
379
380#[derive(Debug, Clone)]
382pub struct ProcessSessionPermissionView {
383 state: Arc<RwLock<ProcessSessionPermissionState>>,
384}
385
386impl ProcessSessionPermissionView {
387 pub fn snapshot(&self) -> Result<ProcessSessionPermissionSnapshot, ProcessRunnerError> {
389 self.state
390 .read()
391 .map(|state| state.snapshot())
392 .map_err(|_| {
393 ProcessRunnerError::infrastructure(
394 "runtime session permission state lock was poisoned",
395 )
396 })
397 }
398}
399
400#[derive(Debug, Clone, Default)]
407pub struct ProcessSessionPermissions {
408 state: Arc<RwLock<ProcessSessionPermissionState>>,
409}
410
411impl ProcessSessionPermissions {
412 #[must_use]
414 pub fn new() -> Self {
415 Self::default()
416 }
417
418 #[must_use]
423 pub fn from_snapshot(snapshot: ProcessSessionPermissionSnapshot) -> Self {
424 Self {
425 state: Arc::new(RwLock::new(ProcessSessionPermissionState::from_snapshot(
426 snapshot,
427 ))),
428 }
429 }
430
431 pub fn from_inherited_view(
437 view: &ProcessSessionPermissionView,
438 ) -> Result<Self, ProcessRunnerError> {
439 Ok(Self::from_snapshot(view.snapshot()?))
440 }
441
442 #[must_use]
444 pub fn view(&self) -> ProcessSessionPermissionView {
445 ProcessSessionPermissionView {
446 state: Arc::clone(&self.state),
447 }
448 }
449
450 pub fn grants(&self) -> Result<Vec<SessionPermissionGrant>, ProcessRunnerError> {
456 self.state
457 .read()
458 .map(|state| state.ordered_grants())
459 .map_err(|_| {
460 ProcessRunnerError::infrastructure(
461 "runtime session permission state lock was poisoned",
462 )
463 })
464 }
465
466 pub fn revoke(&self, id: SessionGrantId) -> Result<bool, ProcessRunnerError> {
475 let mut state = self.state.write().map_err(|_| {
476 ProcessRunnerError::infrastructure("runtime session permission state lock was poisoned")
477 })?;
478 Ok(state.revoke(id))
479 }
480
481 #[must_use]
484 pub fn with_factory<Factory: PermissionedProcessRunnerFactory>(
485 self,
486 backend: Factory,
487 ) -> SessionPermissionedProcessRunnerFactory<Factory> {
488 SessionPermissionedProcessRunnerFactory {
489 permissions: self,
490 backend,
491 }
492 }
493
494 pub fn clear(&self) -> Result<(), ProcessRunnerError> {
504 let mut state = self.state.write().map_err(|_| {
505 ProcessRunnerError::infrastructure("runtime session permission state lock was poisoned")
506 })?;
507 state.clear();
508 Ok(())
509 }
510
511 pub fn revoke_denied_capabilities(
520 &self,
521 network_denied: bool,
522 denied_host_integrations: &[HostIntegration],
523 ) -> Result<(), ProcessRunnerError> {
524 let mut state = self.state.write().map_err(|_| {
525 ProcessRunnerError::infrastructure("runtime session permission state lock was poisoned")
526 })?;
527 if network_denied {
528 state.network_grant_id = None;
529 state.domain_grants.clear();
530 }
531 if !denied_host_integrations.is_empty() {
532 state
533 .host_integrations
534 .retain(|(_, integration)| !denied_host_integrations.contains(integration));
535 }
536 Ok(())
537 }
538
539 pub fn retain_path_grants(
543 &self,
544 grants: Vec<ProcessPathGrant>,
545 ) -> Result<(), ProcessRunnerError> {
546 let mut state = self.state.write().map_err(|_| {
547 ProcessRunnerError::infrastructure("runtime session permission state lock was poisoned")
548 })?;
549 state.retain_path_rules(grants.into_iter().filter_map(|grant| {
550 (grant.constraint == ProcessPathGrantConstraint::Ordinary
551 && grant.rule.access() != PathAccess::Deny)
552 .then_some(grant.rule)
553 }));
554 Ok(())
555 }
556
557 pub fn retain_domain_grants(
560 &self,
561 domains: impl IntoIterator<Item = String>,
562 ) -> Result<(), ProcessRunnerError> {
563 let mut state = self.state.write().map_err(|_| {
564 ProcessRunnerError::infrastructure("runtime session permission state lock was poisoned")
565 })?;
566 state.retain_domains(domains);
567 Ok(())
568 }
569
570 fn retain(
571 &self,
572 request: &PermissionRequest,
573 grants: Vec<ProcessPathGrant>,
574 ) -> Result<(), ProcessRunnerError> {
575 let mut state = self.state.write().map_err(|_| {
576 ProcessRunnerError::infrastructure("runtime session permission state lock was poisoned")
577 })?;
578 state.retain_path_rules(grants.into_iter().filter_map(|grant| {
579 (grant.constraint == ProcessPathGrantConstraint::Ordinary
580 && grant.rule.access() != PathAccess::Deny)
581 .then_some(grant.rule)
582 }));
583 let mut domains = Vec::new();
584 for capability in request.requested() {
585 match capability {
586 RequestedCapability::HostIntegration(integration) => {
587 state.retain_host_integration(*integration);
588 }
589 RequestedCapability::NetworkDomain(domain) => {
590 domains.push(domain.clone());
591 }
592 RequestedCapability::Network | RequestedCapability::Path(_) => {}
593 }
594 }
595 if !domains.is_empty() {
596 state.retain_domains(domains);
597 }
598 if request.requests_network() {
599 state.retain_network();
600 }
601 Ok(())
602 }
603}
604
605#[derive(Debug, Clone)]
607pub struct SessionPermissionedProcessRunnerFactory<Factory> {
608 permissions: ProcessSessionPermissions,
609 backend: Factory,
610}
611
612impl<Factory> SessionPermissionedProcessRunnerFactory<Factory> {
613 #[must_use]
616 pub fn backend(&self) -> &Factory {
617 &self.backend
618 }
619}
620
621impl<Factory: PermissionedProcessRunnerFactory> PermissionedProcessRunnerFactory
622 for SessionPermissionedProcessRunnerFactory<Factory>
623{
624 fn validate_request(&self, request: &PermissionRequest) -> Result<(), ProcessRunnerError> {
625 self.backend.validate_request(request)
626 }
627
628 fn request_capabilities_are_satisfied(
629 &self,
630 request: &PermissionRequest,
631 ) -> Result<bool, ProcessRunnerError> {
632 self.backend.request_capabilities_are_satisfied(request)
633 }
634
635 fn targets_protected_metadata(&self, request: &PermissionRequest) -> bool {
636 self.backend.targets_protected_metadata(request)
637 }
638
639 fn runner_for(&self, request: &PermissionRequest) -> Arc<dyn ProcessRunner> {
640 self.runner_for_decision(request, ApprovalScope::Once)
641 }
642
643 fn runner_for_decision(
644 &self,
645 request: &PermissionRequest,
646 scope: ApprovalScope,
647 ) -> Arc<dyn ProcessRunner> {
648 let result = self
649 .backend
650 .prepare_approved_request(request)
651 .and_then(|prepared| {
652 if scope == ApprovalScope::Session {
653 self.permissions.retain(request, prepared.grants)?;
654 }
655 Ok(prepared.runner)
656 });
657 match result {
658 Ok(runner) => runner,
659 Err(error) => Arc::new(RejectedRunner(error)),
660 }
661 }
662}
663
664struct RejectedRunner(ProcessRunnerError);
665
666impl ProcessRunner for RejectedRunner {
667 fn run<'a>(
668 &'a self,
669 _intent: ProcessActionIntent,
670 _context: ProcessRunnerContext,
671 ) -> ProcessRunnerFuture<'a> {
672 Box::pin(async { Err(self.0.clone()) })
673 }
674}
675
676fn normalize_grant_entries(rules: &mut Vec<(SessionGrantId, PathAccessRule)>) {
677 rules.sort_by(|(left_id, left), (right_id, right)| {
678 left.path()
679 .components()
680 .count()
681 .cmp(&right.path().components().count())
682 .then_with(|| left.path().cmp(right.path()))
683 .then_with(|| {
684 (left.access() != PathAccess::ReadWrite)
685 .cmp(&(right.access() != PathAccess::ReadWrite))
686 })
687 .then_with(|| left_id.cmp(right_id))
688 });
689 let mut retained: Vec<(SessionGrantId, PathAccessRule)> = Vec::with_capacity(rules.len());
690 for (id, rule) in rules.drain(..) {
691 if !retained.iter().any(|(_, ancestor)| {
692 rule.path().starts_with(ancestor.path()) && ancestor.access().covers(rule.access())
693 }) {
694 retained.push((id, rule));
695 }
696 }
697 *rules = retained;
698}
699
700#[cfg(test)]
701mod tests;