cedrus-core 0.2.0

Business logic and authorization engine for Cedrus.
Documentation
#![doc = include_str!("../README.md")]
#![allow(clippy::result_large_err)]
#![allow(clippy::ptr_arg)]

use std::{collections::HashMap, error::Error, fmt, hash::Hash};

use cedrus_cedar::{EntityUid, EntityValue, Policy, PolicyId, SlotId, TemplateLink};
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
use uuid::Uuid;

use crate::{cache::CacheError, db::DatabaseError};

pub const DEFAULT_LIMIT: usize = 1000;

/// Predefined base roles.
#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
pub enum CedrusRole {
    Admin,
    Editor,
    #[default]
    Viewer,
}

impl std::fmt::Display for CedrusRole {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            CedrusRole::Admin => write!(f, "Admin"),
            CedrusRole::Editor => write!(f, "Editor"),
            CedrusRole::Viewer => write!(f, "Viewer"),
        }
    }
}

/// Unified Role enum: Preset (Admin, Editor, Viewer) or Custom (action list).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
#[serde(tag = "type", content = "value")]
pub enum Role {
    /// Uses a predefined role (Admin, Editor, Viewer)
    Preset(CedrusRole),
    /// Uses a custom role with specific actions
    Custom(Vec<String>),
}

impl Default for Role {
    fn default() -> Self {
        Role::Preset(CedrusRole::default())
    }
}

impl std::fmt::Display for Role {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Role::Preset(base) => write!(f, "preset:{}", base),
            Role::Custom(actions) => write!(f, "custom:[{}]", actions.join(", ")),
        }
    }
}

/// Builds a Cedar TemplateLink for a given principal (User or ApiKey) and resource (Project).
pub fn build_template_link(
    template_id: &str,
    link_id: &str,
    principal_type: &str,
    principal_id: impl Into<String>,
    project_id: &Uuid,
) -> TemplateLink {
    let template_id = PolicyId::from(template_id.to_string());
    let new_id = PolicyId::from(link_id.to_string());

    let principal_value = EntityValue::EntityUid(EntityUid::new(
        principal_type.to_string(),
        principal_id.into(),
    ));
    let resource_value = EntityValue::EntityUid(EntityUid::new(
        "Project".to_string(),
        project_id.to_string(),
    ));

    let values = HashMap::from([
        (SlotId::Principal, principal_value),
        (SlotId::Resource, resource_value),
    ]);

    TemplateLink::new(template_id, new_id, values)
}

/// Builds a Cedar static Policy for a custom role for a given principal (User or ApiKey) and resource (Project).
pub fn build_custom_static_policy(
    policy_id: &str,
    principal_type: &str,
    principal_id: impl Into<String>,
    project_id: &Uuid,
    actions: &[String],
) -> Policy {
    let action_entities: Vec<serde_json::Value> = actions
        .iter()
        .map(|act| {
            serde_json::json!({
                "type": "Action",
                "id": act
            })
        })
        .collect();

    let json_val = serde_json::json!({
        "effect": "permit",
        "principal": {
            "op": "==",
            "entity": {
                "type": principal_type,
                "id": principal_id.into()
            }
        },
        "action": {
            "op": "in",
            "entities": action_entities
        },
        "resource": {
            "op": "==",
            "entity": {
                "type": "Project",
                "id": project_id.to_string()
            }
        },
        "conditions": [
            {
                "kind": "when",
                "body": {
                    "==": {
                        "left": {
                            ".": {
                                "left": { "Var": "principal" },
                                "attr": "enabled"
                            }
                        },
                        "right": { "Value": true }
                    }
                }
            }
        ],
        "annotations": {
            "id": policy_id
        }
    });

    serde_json::from_value(json_val).expect("Failed to build custom static policy JSON")
}

#[derive(Debug, Default, Clone, Serialize, Deserialize, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct PageList<T> {
    pub items: Vec<T>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub bookmark: Option<String>,
}

impl<T> PageList<T> {
    pub fn new(items: Vec<T>, bookmark: Option<String>) -> Self {
        Self { items, bookmark }
    }
}

#[derive(Debug, Default, Clone, Serialize, Deserialize, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct PageHash<K, V>
where
    K: Eq + Hash,
{
    pub items: HashMap<K, V>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub bookmark: Option<String>,
}

impl<K, V> PageHash<K, V>
where
    K: Eq + Hash,
{
    pub fn new(items: HashMap<K, V>, bookmark: Option<String>) -> Self {
        Self { items, bookmark }
    }
}

// The kinds of errors we can hit in our application.
#[derive(Debug)]
pub enum CedrusError {
    BadRequest,
    NotFound,

    DatabaseError(DatabaseError),
    CacheError(CacheError),

    SerdeJsonError(serde_json::Error),
    SchemaError(cedar_policy::SchemaError),
    EntitiesError(cedar_policy::entities_errors::EntitiesError),
    PolicyFromJsonError(cedar_policy::PolicyFromJsonError),
    PolicyToJsonError(cedar_policy::PolicyToJsonError),
    PolicySetError(cedar_policy::PolicySetError),
    ContextJsonError(cedar_policy::ContextJsonError),
    RequestValidationError(cedar_policy::RequestValidationError),
}

impl Error for CedrusError {}

impl fmt::Display for CedrusError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            CedrusError::BadRequest => write!(f, "Bad request"),
            CedrusError::NotFound => write!(f, "Not found"),
            CedrusError::DatabaseError(ref err) => err.fmt(f),
            CedrusError::CacheError(ref err) => err.fmt(f),
            CedrusError::SerdeJsonError(ref err) => err.fmt(f),
            CedrusError::SchemaError(ref err) => err.fmt(f),
            CedrusError::EntitiesError(ref err) => err.fmt(f),
            CedrusError::PolicyFromJsonError(ref err) => err.fmt(f),
            CedrusError::PolicyToJsonError(ref err) => err.fmt(f),
            CedrusError::PolicySetError(ref err) => err.fmt(f),
            CedrusError::ContextJsonError(ref err) => err.fmt(f),
            CedrusError::RequestValidationError(ref err) => err.fmt(f),
        }
    }
}

impl From<DatabaseError> for CedrusError {
    fn from(error: DatabaseError) -> Self {
        Self::DatabaseError(error)
    }
}

impl From<CacheError> for CedrusError {
    fn from(error: CacheError) -> Self {
        Self::CacheError(error)
    }
}

impl From<serde_json::Error> for CedrusError {
    fn from(error: serde_json::Error) -> Self {
        Self::SerdeJsonError(error)
    }
}

impl From<cedar_policy::SchemaError> for CedrusError {
    fn from(error: cedar_policy::SchemaError) -> Self {
        Self::SchemaError(error)
    }
}

impl From<cedar_policy::entities_errors::EntitiesError> for CedrusError {
    fn from(error: cedar_policy::entities_errors::EntitiesError) -> Self {
        Self::EntitiesError(error)
    }
}

impl From<cedar_policy::PolicyFromJsonError> for CedrusError {
    fn from(error: cedar_policy::PolicyFromJsonError) -> Self {
        Self::PolicyFromJsonError(error)
    }
}

impl From<cedar_policy::PolicyToJsonError> for CedrusError {
    fn from(error: cedar_policy::PolicyToJsonError) -> Self {
        Self::PolicyToJsonError(error)
    }
}

impl From<cedar_policy::PolicySetError> for CedrusError {
    fn from(error: cedar_policy::PolicySetError) -> Self {
        Self::PolicySetError(error)
    }
}

impl From<cedar_policy::ContextJsonError> for CedrusError {
    fn from(error: cedar_policy::ContextJsonError) -> Self {
        Self::ContextJsonError(error)
    }
}

impl From<cedar_policy::RequestValidationError> for CedrusError {
    fn from(error: cedar_policy::RequestValidationError) -> Self {
        Self::RequestValidationError(error)
    }
}

pub mod cache;
pub mod cedrus;
pub mod db;
pub mod project;