footing 0.1.18

Feature-gated foundations for Rust backend services
Documentation
//! Permission requests, decisions, and checkers.

use async_trait::async_trait;
use serde::{Deserialize, Serialize};

use super::{error::PermissionError, model::Principal};

const MAX_PERMISSION_PART_LENGTH: usize = 256;

fn normalize_permission_part(
    value: impl Into<String>,
    field: &'static str,
) -> Result<String, PermissionError> {
    let value = value.into().trim().to_owned();
    if value.is_empty() {
        return Err(PermissionError::InvalidPolicy(format!(
            "{field} must not be empty"
        )));
    }

    if value.len() > MAX_PERMISSION_PART_LENGTH {
        return Err(PermissionError::InvalidPolicy(format!(
            "{field} must not exceed {MAX_PERMISSION_PART_LENGTH} bytes"
        )));
    }

    if value.chars().any(char::is_control) {
        return Err(PermissionError::InvalidPolicy(format!(
            "{field} must not contain control characters"
        )));
    }

    Ok(value)
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(try_from = "PermissionRequestWire")]
/// A request describing permission.
pub struct PermissionRequest {
    action: String,
    resource: String,
}

impl PermissionRequest {
    /// Creates a new instance.
    pub fn new(
        action: impl Into<String>,
        resource: impl Into<String>,
    ) -> Result<Self, PermissionError> {
        let action = normalize_permission_part(action, "permission action")?;
        let resource = normalize_permission_part(resource, "permission resource")?;

        Ok(Self { action, resource })
    }

    #[must_use]
    /// Returns the action.
    pub fn action(&self) -> &str {
        &self.action
    }

    #[must_use]
    /// Returns the resource.
    pub fn resource(&self) -> &str {
        &self.resource
    }
}

#[derive(Debug, Deserialize)]
struct PermissionRequestWire {
    action: String,
    resource: String,
}

impl TryFrom<PermissionRequestWire> for PermissionRequest {
    type Error = PermissionError;

    fn try_from(value: PermissionRequestWire) -> Result<Self, Self::Error> {
        Self::new(value.action, value.resource)
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
#[serde(rename_all = "snake_case")]
/// Decision produced by permission.
pub enum PermissionDecision {
    /// The operation is allowed.
    Allow,
    /// The operation is denied.
    Deny,
}

impl PermissionDecision {
    #[must_use]
    /// Returns whether this value is allowed.
    pub const fn is_allowed(self) -> bool {
        matches!(self, Self::Allow)
    }

    /// Ensures allowed.
    pub fn ensure_allowed(self) -> Result<(), PermissionError> {
        if self.is_allowed() {
            Ok(())
        } else {
            Err(PermissionError::Denied)
        }
    }
}

/// Defines the contract for permission checker.
#[async_trait]
pub trait PermissionChecker: Send + Sync {
    /// Evaluates this check.
    async fn check(
        &self,
        principal: &Principal,
        request: &PermissionRequest,
    ) -> Result<PermissionDecision, PermissionError>;

    /// Checks the requested permission and converts denial into an error.
    async fn ensure_allowed(
        &self,
        principal: &Principal,
        request: &PermissionRequest,
    ) -> Result<(), PermissionError> {
        self.check(principal, request).await?.ensure_allowed()
    }
}