Skip to main content

cedrus_core/
lib.rs

1#![doc = include_str!("../README.md")]
2#![allow(clippy::result_large_err)]
3#![allow(clippy::ptr_arg)]
4
5use std::{collections::HashMap, error::Error, fmt, hash::Hash};
6
7use cedrus_cedar::{EntityUid, EntityValue, Policy, PolicyId, SlotId, TemplateLink};
8use serde::{Deserialize, Serialize};
9use utoipa::ToSchema;
10use uuid::Uuid;
11
12use crate::{cache::CacheError, db::DatabaseError};
13
14pub const DEFAULT_LIMIT: usize = 1000;
15
16/// Predefined base roles.
17#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
18pub enum CedrusRole {
19    Admin,
20    Editor,
21    #[default]
22    Viewer,
23}
24
25impl std::fmt::Display for CedrusRole {
26    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
27        match self {
28            CedrusRole::Admin => write!(f, "Admin"),
29            CedrusRole::Editor => write!(f, "Editor"),
30            CedrusRole::Viewer => write!(f, "Viewer"),
31        }
32    }
33}
34
35/// Unified Role enum: Preset (Admin, Editor, Viewer) or Custom (action list).
36#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
37#[serde(tag = "type", content = "value")]
38pub enum Role {
39    /// Uses a predefined role (Admin, Editor, Viewer)
40    Preset(CedrusRole),
41    /// Uses a custom role with specific actions
42    Custom(Vec<String>),
43}
44
45impl Default for Role {
46    fn default() -> Self {
47        Role::Preset(CedrusRole::default())
48    }
49}
50
51impl std::fmt::Display for Role {
52    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
53        match self {
54            Role::Preset(base) => write!(f, "preset:{}", base),
55            Role::Custom(actions) => write!(f, "custom:[{}]", actions.join(", ")),
56        }
57    }
58}
59
60/// Builds a Cedar TemplateLink for a given principal (User or ApiKey) and resource (Project).
61pub fn build_template_link(
62    template_id: &str,
63    link_id: &str,
64    principal_type: &str,
65    principal_id: impl Into<String>,
66    project_id: &Uuid,
67) -> TemplateLink {
68    let template_id = PolicyId::from(template_id.to_string());
69    let new_id = PolicyId::from(link_id.to_string());
70
71    let principal_value = EntityValue::EntityUid(EntityUid::new(
72        principal_type.to_string(),
73        principal_id.into(),
74    ));
75    let resource_value = EntityValue::EntityUid(EntityUid::new(
76        "Project".to_string(),
77        project_id.to_string(),
78    ));
79
80    let values = HashMap::from([
81        (SlotId::Principal, principal_value),
82        (SlotId::Resource, resource_value),
83    ]);
84
85    TemplateLink::new(template_id, new_id, values)
86}
87
88/// Builds a Cedar static Policy for a custom role for a given principal (User or ApiKey) and resource (Project).
89pub fn build_custom_static_policy(
90    policy_id: &str,
91    principal_type: &str,
92    principal_id: impl Into<String>,
93    project_id: &Uuid,
94    actions: &[String],
95) -> Policy {
96    let action_entities: Vec<serde_json::Value> = actions
97        .iter()
98        .map(|act| {
99            serde_json::json!({
100                "type": "Action",
101                "id": act
102            })
103        })
104        .collect();
105
106    let json_val = serde_json::json!({
107        "effect": "permit",
108        "principal": {
109            "op": "==",
110            "entity": {
111                "type": principal_type,
112                "id": principal_id.into()
113            }
114        },
115        "action": {
116            "op": "in",
117            "entities": action_entities
118        },
119        "resource": {
120            "op": "==",
121            "entity": {
122                "type": "Project",
123                "id": project_id.to_string()
124            }
125        },
126        "conditions": [
127            {
128                "kind": "when",
129                "body": {
130                    "==": {
131                        "left": {
132                            ".": {
133                                "left": { "Var": "principal" },
134                                "attr": "enabled"
135                            }
136                        },
137                        "right": { "Value": true }
138                    }
139                }
140            }
141        ],
142        "annotations": {
143            "id": policy_id
144        }
145    });
146
147    serde_json::from_value(json_val).expect("Failed to build custom static policy JSON")
148}
149
150#[derive(Debug, Default, Clone, Serialize, Deserialize, ToSchema)]
151#[serde(rename_all = "camelCase")]
152pub struct PageList<T> {
153    pub items: Vec<T>,
154    #[serde(skip_serializing_if = "Option::is_none")]
155    pub bookmark: Option<String>,
156}
157
158impl<T> PageList<T> {
159    pub fn new(items: Vec<T>, bookmark: Option<String>) -> Self {
160        Self { items, bookmark }
161    }
162}
163
164#[derive(Debug, Default, Clone, Serialize, Deserialize, ToSchema)]
165#[serde(rename_all = "camelCase")]
166pub struct PageHash<K, V>
167where
168    K: Eq + Hash,
169{
170    pub items: HashMap<K, V>,
171    #[serde(skip_serializing_if = "Option::is_none")]
172    pub bookmark: Option<String>,
173}
174
175impl<K, V> PageHash<K, V>
176where
177    K: Eq + Hash,
178{
179    pub fn new(items: HashMap<K, V>, bookmark: Option<String>) -> Self {
180        Self { items, bookmark }
181    }
182}
183
184// The kinds of errors we can hit in our application.
185#[derive(Debug)]
186pub enum CedrusError {
187    BadRequest,
188    NotFound,
189
190    DatabaseError(DatabaseError),
191    CacheError(CacheError),
192
193    SerdeJsonError(serde_json::Error),
194    SchemaError(cedar_policy::SchemaError),
195    EntitiesError(cedar_policy::entities_errors::EntitiesError),
196    PolicyFromJsonError(cedar_policy::PolicyFromJsonError),
197    PolicyToJsonError(cedar_policy::PolicyToJsonError),
198    PolicySetError(cedar_policy::PolicySetError),
199    ContextJsonError(cedar_policy::ContextJsonError),
200    RequestValidationError(cedar_policy::RequestValidationError),
201}
202
203impl Error for CedrusError {}
204
205impl fmt::Display for CedrusError {
206    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
207        match *self {
208            CedrusError::BadRequest => write!(f, "Bad request"),
209            CedrusError::NotFound => write!(f, "Not found"),
210            CedrusError::DatabaseError(ref err) => err.fmt(f),
211            CedrusError::CacheError(ref err) => err.fmt(f),
212            CedrusError::SerdeJsonError(ref err) => err.fmt(f),
213            CedrusError::SchemaError(ref err) => err.fmt(f),
214            CedrusError::EntitiesError(ref err) => err.fmt(f),
215            CedrusError::PolicyFromJsonError(ref err) => err.fmt(f),
216            CedrusError::PolicyToJsonError(ref err) => err.fmt(f),
217            CedrusError::PolicySetError(ref err) => err.fmt(f),
218            CedrusError::ContextJsonError(ref err) => err.fmt(f),
219            CedrusError::RequestValidationError(ref err) => err.fmt(f),
220        }
221    }
222}
223
224impl From<DatabaseError> for CedrusError {
225    fn from(error: DatabaseError) -> Self {
226        Self::DatabaseError(error)
227    }
228}
229
230impl From<CacheError> for CedrusError {
231    fn from(error: CacheError) -> Self {
232        Self::CacheError(error)
233    }
234}
235
236impl From<serde_json::Error> for CedrusError {
237    fn from(error: serde_json::Error) -> Self {
238        Self::SerdeJsonError(error)
239    }
240}
241
242impl From<cedar_policy::SchemaError> for CedrusError {
243    fn from(error: cedar_policy::SchemaError) -> Self {
244        Self::SchemaError(error)
245    }
246}
247
248impl From<cedar_policy::entities_errors::EntitiesError> for CedrusError {
249    fn from(error: cedar_policy::entities_errors::EntitiesError) -> Self {
250        Self::EntitiesError(error)
251    }
252}
253
254impl From<cedar_policy::PolicyFromJsonError> for CedrusError {
255    fn from(error: cedar_policy::PolicyFromJsonError) -> Self {
256        Self::PolicyFromJsonError(error)
257    }
258}
259
260impl From<cedar_policy::PolicyToJsonError> for CedrusError {
261    fn from(error: cedar_policy::PolicyToJsonError) -> Self {
262        Self::PolicyToJsonError(error)
263    }
264}
265
266impl From<cedar_policy::PolicySetError> for CedrusError {
267    fn from(error: cedar_policy::PolicySetError) -> Self {
268        Self::PolicySetError(error)
269    }
270}
271
272impl From<cedar_policy::ContextJsonError> for CedrusError {
273    fn from(error: cedar_policy::ContextJsonError) -> Self {
274        Self::ContextJsonError(error)
275    }
276}
277
278impl From<cedar_policy::RequestValidationError> for CedrusError {
279    fn from(error: cedar_policy::RequestValidationError) -> Self {
280        Self::RequestValidationError(error)
281    }
282}
283
284pub mod cache;
285pub mod cedrus;
286pub mod db;
287pub mod project;