footing 0.1.13

Feature-gated foundations for Rust backend services
Documentation
//! Authenticated principal identity and authority normalization.

use std::fmt;

use serde::{Deserialize, Serialize};

use super::error::PermissionError;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
#[serde(rename_all = "snake_case")]
/// Classification of principal.
pub enum PrincipalKind {
    /// Indicates user.
    User,
    /// Indicates client.
    Client,
    /// Indicates service account.
    ServiceAccount,
}

#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(try_from = "PrincipalWire")]
/// Represents principal.
pub struct Principal {
    id: String,
    kind: PrincipalKind,
    tenant_id: Option<String>,
    roles: Vec<String>,
    scopes: Vec<String>,
}

impl fmt::Debug for Principal {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("Principal")
            .field("id", &"[REDACTED]")
            .field("kind", &self.kind)
            .field("tenant_id", &self.tenant_id.as_ref().map(|_| "[REDACTED]"))
            .field("role_count", &self.roles.len())
            .field("scope_count", &self.scopes.len())
            .finish()
    }
}

const MAX_PRINCIPAL_IDENTIFIER_LENGTH: usize = 256;
const MAX_AUTHORITY_LENGTH: usize = 128;

impl Principal {
    /// Creates a new instance.
    pub fn new(id: impl Into<String>, kind: PrincipalKind) -> Result<Self, PermissionError> {
        Ok(Self {
            id: normalize_principal_identifier(id, "principal id")?,
            kind,
            tenant_id: None,
            roles: Vec::new(),
            scopes: Vec::new(),
        })
    }

    /// Creates user.
    pub fn user(id: impl Into<String>) -> Result<Self, PermissionError> {
        Self::new(id, PrincipalKind::User)
    }

    /// Creates client.
    pub fn client(id: impl Into<String>) -> Result<Self, PermissionError> {
        Self::new(id, PrincipalKind::Client)
    }

    /// Creates service account.
    pub fn service_account(id: impl Into<String>) -> Result<Self, PermissionError> {
        Self::new(id, PrincipalKind::ServiceAccount)
    }

    /// Configures tenant identifier and returns the updated value.
    pub fn with_tenant_id(mut self, tenant_id: impl Into<String>) -> Result<Self, PermissionError> {
        self.tenant_id = normalize_optional_principal_identifier(tenant_id, "tenant id")?;
        Ok(self)
    }

    /// Configures roles and returns the updated value.
    pub fn with_roles(
        mut self,
        roles: impl IntoIterator<Item = impl Into<String>>,
    ) -> Result<Self, PermissionError> {
        self.roles = normalize_authority_values(roles)?;
        Ok(self)
    }

    /// Configures scopes and returns the updated value.
    pub fn with_scopes(
        mut self,
        scopes: impl IntoIterator<Item = impl Into<String>>,
    ) -> Result<Self, PermissionError> {
        self.scopes = normalize_authority_values(scopes)?;
        Ok(self)
    }

    /// Adds role.
    pub fn add_role(&mut self, role: impl Into<String>) -> Result<(), PermissionError> {
        push_unique(&mut self.roles, normalize_authority_value(role)?);
        Ok(())
    }

    /// Adds scope.
    pub fn add_scope(&mut self, scope: impl Into<String>) -> Result<(), PermissionError> {
        push_unique(&mut self.scopes, normalize_authority_value(scope)?);
        Ok(())
    }

    /// Removes role.
    pub fn remove_role(&mut self, role: &str) -> bool {
        let role = role.trim();
        let previous_len = self.roles.len();
        self.roles.retain(|item| item != role);
        self.roles.len() != previous_len
    }

    /// Removes scope.
    pub fn remove_scope(&mut self, scope: &str) -> bool {
        let scope = scope.trim();
        let previous_len = self.scopes.len();
        self.scopes.retain(|item| item != scope);
        self.scopes.len() != previous_len
    }

    /// Clears roles.
    pub fn clear_roles(&mut self) {
        self.roles.clear();
    }

    /// Clears scopes.
    pub fn clear_scopes(&mut self) {
        self.scopes.clear();
    }

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

    #[must_use]
    /// Returns the kind.
    pub const fn kind(&self) -> PrincipalKind {
        self.kind
    }

    #[must_use]
    /// Returns the tenant identifier.
    pub fn tenant_id(&self) -> Option<&str> {
        self.tenant_id.as_deref()
    }

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

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

    #[must_use]
    /// Returns whether this value has role.
    pub fn has_role(&self, role: &str) -> bool {
        let role = role.trim();
        if role.is_empty() {
            return false;
        }

        self.roles.iter().any(|item| item == role)
    }

    #[must_use]
    /// Returns whether this value has any role.
    pub fn has_any_role<'a>(&self, roles: impl IntoIterator<Item = &'a str>) -> bool {
        roles.into_iter().any(|role| self.has_role(role))
    }

    #[must_use]
    /// Returns whether this value has all roles.
    pub fn has_all_roles<'a>(&self, roles: impl IntoIterator<Item = &'a str>) -> bool {
        let mut roles = roles.into_iter().peekable();
        roles.peek().is_some() && roles.all(|role| self.has_role(role))
    }

    #[must_use]
    /// Returns whether this value has scope.
    pub fn has_scope(&self, scope: &str) -> bool {
        let scope = scope.trim();
        if scope.is_empty() {
            return false;
        }

        self.scopes
            .iter()
            .any(|item| item == scope || item == "*" || scope_matches(item, scope))
    }

    #[must_use]
    /// Returns whether this value has any scope.
    pub fn has_any_scope<'a>(&self, scopes: impl IntoIterator<Item = &'a str>) -> bool {
        scopes.into_iter().any(|scope| self.has_scope(scope))
    }

    #[must_use]
    /// Returns whether this value has all scopes.
    pub fn has_all_scopes<'a>(&self, scopes: impl IntoIterator<Item = &'a str>) -> bool {
        let mut scopes = scopes.into_iter().peekable();
        scopes.peek().is_some() && scopes.all(|scope| self.has_scope(scope))
    }

    #[must_use]
    /// Returns whether this value is user.
    pub fn is_user(&self) -> bool {
        self.kind == PrincipalKind::User
    }

    #[must_use]
    /// Returns whether this value is client.
    pub fn is_client(&self) -> bool {
        self.kind == PrincipalKind::Client
    }

    #[must_use]
    /// Returns whether this value is service account.
    pub fn is_service_account(&self) -> bool {
        self.kind == PrincipalKind::ServiceAccount
    }
}

#[derive(Deserialize)]
struct PrincipalWire {
    id: String,
    kind: PrincipalKind,
    #[serde(default)]
    tenant_id: Option<String>,
    #[serde(default)]
    roles: Vec<String>,
    #[serde(default)]
    scopes: Vec<String>,
}

impl TryFrom<PrincipalWire> for Principal {
    type Error = PermissionError;

    fn try_from(value: PrincipalWire) -> Result<Self, Self::Error> {
        let mut principal = Self::new(value.id, value.kind)?;
        if let Some(tenant_id) = value.tenant_id {
            principal = principal.with_tenant_id(tenant_id)?;
        }

        principal.with_roles(value.roles)?.with_scopes(value.scopes)
    }
}

fn scope_matches(granted: &str, required: &str) -> bool {
    granted.strip_suffix(":*").is_some_and(|prefix| {
        required
            .strip_prefix(prefix)
            .is_some_and(|suffix| suffix.starts_with(':'))
    })
}

fn push_unique(items: &mut Vec<String>, value: String) {
    if !items.iter().any(|item| item == &value) {
        items.push(value);
    }
}

fn normalize(value: impl Into<String>) -> String {
    value.into().trim().to_owned()
}

fn normalize_principal_identifier(
    value: impl Into<String>,
    field: &'static str,
) -> Result<String, PermissionError> {
    let value = normalize(value);
    validate_principal_identifier(&value, field)?;
    Ok(value)
}

fn normalize_optional_principal_identifier(
    value: impl Into<String>,
    field: &'static str,
) -> Result<Option<String>, PermissionError> {
    let value = normalize(value);
    if value.is_empty() {
        return Ok(None);
    }

    validate_principal_identifier(&value, field)?;
    Ok(Some(value))
}

fn validate_principal_identifier(value: &str, field: &'static str) -> Result<(), PermissionError> {
    if value.is_empty() {
        return Err(PermissionError::InvalidPrincipal(format!(
            "{field} must not be empty"
        )));
    }

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

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

    Ok(())
}

fn normalize_authority_value(value: impl Into<String>) -> Result<String, PermissionError> {
    let value = normalize(value);
    validate_authority(&value).map_err(PermissionError::InvalidAuthority)?;
    Ok(value)
}

fn normalize_authority_values(
    values: impl IntoIterator<Item = impl Into<String>>,
) -> Result<Vec<String>, PermissionError> {
    let mut normalized = Vec::new();
    for value in values {
        push_unique(&mut normalized, normalize_authority_value(value)?);
    }
    Ok(normalized)
}

pub(super) fn normalize_policy_authority(
    value: impl Into<String>,
    name: &'static str,
) -> Result<String, PermissionError> {
    let value = normalize(value);
    validate_authority(&value).map_err(|message| {
        PermissionError::InvalidPolicy(format!("{name} is invalid: {message}"))
    })?;
    Ok(value)
}

pub(super) fn normalize_policy_authorities(
    values: impl IntoIterator<Item = impl Into<String>>,
    name: &'static str,
) -> Result<Vec<String>, PermissionError> {
    let mut normalized = Vec::new();
    for value in values {
        push_unique(&mut normalized, normalize_policy_authority(value, name)?);
    }

    if normalized.is_empty() {
        return Err(PermissionError::InvalidPolicy(format!(
            "{name} requires at least one value"
        )));
    }

    Ok(normalized)
}

fn validate_authority(value: &str) -> Result<(), String> {
    if value.is_empty() {
        return Err("must not be empty".to_owned());
    }

    if value.len() > MAX_AUTHORITY_LENGTH {
        return Err(format!("must not exceed {MAX_AUTHORITY_LENGTH} bytes"));
    }

    if value.chars().any(char::is_whitespace) || value.chars().any(char::is_control) {
        return Err("must not contain whitespace or control characters".to_owned());
    }

    Ok(())
}