Skip to main content

base/interface/permission/
set.rs

1//! What a session's calls are judged and its grants kept by, held together.
2
3use std::sync::Arc;
4
5use super::{Grant, GrantError, PathDenials, PathGuard, PermissionGrants, PermissionPolicy};
6
7/// A session's permission: the policy its calls are judged by and where the
8/// allows it is handed are kept. With no `grants` nothing is kept, so nobody
9/// is offered an "allow every time". With no `paths` the engine writes
10/// nowhere on its own judgment — a plugin command's `writes` cover nothing, a
11/// rewind restores no file — and no narrow-only grant is kept.
12#[derive(Clone)]
13#[non_exhaustive]
14pub struct PermissionSet {
15    pub policy: Arc<dyn PermissionPolicy>,
16    pub grants: Option<Arc<dyn PermissionGrants>>,
17    pub path_denials: Option<Arc<dyn PathDenials>>,
18    pub paths: Option<Arc<dyn PathGuard>>,
19}
20
21impl PermissionSet {
22    /// One value that both decides and keeps grants, so what it is granted
23    /// changes what it decides. It carries no path guard: add one with
24    /// [`Self::with_paths`] (the permission engine's `permissions::session_set`
25    /// does both).
26    pub fn of<P: PermissionPolicy + PermissionGrants + PathDenials + 'static>(p: Arc<P>) -> Self {
27        Self {
28            policy: p.clone(),
29            grants: Some(p.clone()),
30            path_denials: Some(p),
31            paths: None,
32        }
33    }
34
35    pub fn without_grants(policy: Arc<dyn PermissionPolicy>) -> Self {
36        Self {
37            policy,
38            grants: None,
39            path_denials: None,
40            paths: None,
41        }
42    }
43
44    pub fn with_paths(mut self, paths: Arc<dyn PathGuard>) -> Self {
45        self.paths = Some(paths);
46        self
47    }
48
49    /// This set with its calls judged by `policy` and its walks by
50    /// `path_denials`, keeping everything else it holds.
51    pub fn wrapping(
52        &self,
53        policy: Arc<dyn PermissionPolicy>,
54        path_denials: Option<Arc<dyn PathDenials>>,
55    ) -> Self {
56        Self {
57            policy,
58            path_denials,
59            ..self.clone()
60        }
61    }
62
63    /// Whether `grant` may be kept: a narrow-only grant only where the path
64    /// guard finds it narrow, so none where there is no guard.
65    pub fn admits(&self, grant: &Grant) -> Result<(), GrantError> {
66        match (&grant.narrow_only, &self.paths) {
67            (None, _) => Ok(()),
68            (Some(_), Some(paths)) => paths.admits(grant),
69            (Some(_), None) => Err(GrantError::too_broad(grant)),
70        }
71    }
72}