agix-base 0.5.0

Agix — foundation types, traits, and context
Documentation
//! What a session's calls are judged and its grants kept by, held together.

use std::sync::Arc;

use super::{Grant, GrantError, PathDenials, PathGuard, PermissionGrants, PermissionPolicy};

/// A session's permission: the policy its calls are judged by and where the
/// allows it is handed are kept. With no `grants` nothing is kept, so nobody
/// is offered an "allow every time". With no `paths` the engine writes
/// nowhere on its own judgment — a plugin command's `writes` cover nothing, a
/// rewind restores no file — and no narrow-only grant is kept.
#[derive(Clone)]
#[non_exhaustive]
pub struct PermissionSet {
    pub policy: Arc<dyn PermissionPolicy>,
    pub grants: Option<Arc<dyn PermissionGrants>>,
    pub path_denials: Option<Arc<dyn PathDenials>>,
    pub paths: Option<Arc<dyn PathGuard>>,
}

impl PermissionSet {
    /// One value that both decides and keeps grants, so what it is granted
    /// changes what it decides. It carries no path guard: add one with
    /// [`Self::with_paths`] (the permission engine's `permissions::session_set`
    /// does both).
    pub fn of<P: PermissionPolicy + PermissionGrants + PathDenials + 'static>(p: Arc<P>) -> Self {
        Self {
            policy: p.clone(),
            grants: Some(p.clone()),
            path_denials: Some(p),
            paths: None,
        }
    }

    pub fn without_grants(policy: Arc<dyn PermissionPolicy>) -> Self {
        Self {
            policy,
            grants: None,
            path_denials: None,
            paths: None,
        }
    }

    pub fn with_paths(mut self, paths: Arc<dyn PathGuard>) -> Self {
        self.paths = Some(paths);
        self
    }

    /// This set with its calls judged by `policy` and its walks by
    /// `path_denials`, keeping everything else it holds.
    pub fn wrapping(
        &self,
        policy: Arc<dyn PermissionPolicy>,
        path_denials: Option<Arc<dyn PathDenials>>,
    ) -> Self {
        Self {
            policy,
            path_denials,
            ..self.clone()
        }
    }

    /// Whether `grant` may be kept: a narrow-only grant only where the path
    /// guard finds it narrow, so none where there is no guard.
    pub fn admits(&self, grant: &Grant) -> Result<(), GrantError> {
        match (&grant.narrow_only, &self.paths) {
            (None, _) => Ok(()),
            (Some(_), Some(paths)) => paths.admits(grant),
            (Some(_), None) => Err(GrantError::too_broad(grant)),
        }
    }
}