cedrus-core 0.2.0

Business logic and authorization engine for Cedrus.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
use std::collections::{HashMap, HashSet};

use cedrus_cedar::{Entity, EntityUid, entity::EntityAttr};
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
use uuid::Uuid;

use crate::{CedrusRole, Role};

pub const PROJECT_ENTITY_TYPE: &str = "Project";
pub const APIKEY_ENTITY_TYPE: &str = "ApiKey";
pub const GROUP_ENTITY_TYPE: &str = "Group";
pub const USER_ENTITY_TYPE: &str = "User";

pub const PARENT_UID: &str = "Application::Cedrus";

const ATTR_ENABLED: &str = "enabled";
const ATTR_OWNER: &str = "owner";
const TAG_NAME: &str = "name";

fn default_true() -> bool {
    true
}

use crate::project::is::OpenIdConnectTokenSelection;

pub mod is {
    use super::*;

    #[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq, ToSchema)]
    #[schema(as = identitysource::CognitoGroupConfiguration)]
    #[serde(rename_all = "camelCase")]
    pub struct CognitoGroupConfiguration {
        pub group_entity_type: String,
    }

    #[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq, ToSchema)]
    #[schema(as = identitysource::CognitoUserPoolConfiguration)]
    #[serde(rename_all = "camelCase")]
    pub struct CognitoUserPoolConfiguration {
        pub user_pool_arn: String,
        pub client_ids: Vec<String>,
        pub group_configuration: Option<CognitoGroupConfiguration>,
    }

    impl CognitoUserPoolConfiguration {
        pub fn iss(&self) -> String {
            let parts: Vec<&str> = self.user_pool_arn.split(':').collect();
            let region = parts.get(3).expect("Invalid user pool ARN");
            let user_pool_id = self
                .user_pool_arn
                .split('/')
                .next_back()
                .expect("Invalid user pool ARN")
                .to_string();

            format!("https://cognito-idp.{region}.amazonaws.com/{user_pool_id}")
        }

        pub fn url_keys(&self) -> String {
            let parts: Vec<&str> = self.user_pool_arn.split(':').collect();
            let region = parts.get(3).expect("Invalid user pool ARN");
            let user_pool_id = self
                .user_pool_arn
                .split('/')
                .next_back()
                .expect("Invalid user pool ARN")
                .to_string();

            format!(
                "https://cognito-idp.{region}.amazonaws.com/{user_pool_id}/.well-known/jwks.json"
            )
        }

        pub fn prefix(&self) -> String {
            self.user_pool_arn
                .split('/')
                .next_back()
                .expect("Invalid user pool ARN")
                .to_string()
        }
    }

    #[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq, ToSchema)]
    #[schema(as = identitysource::OpenIdConnectAccessTokenConfiguration)]
    #[serde(rename_all = "camelCase", default)]
    pub struct OpenIdConnectAccessTokenConfiguration {
        #[serde(skip_serializing_if = "Vec::is_empty")]
        pub audiences: Vec<String>,
        #[serde(skip_serializing_if = "Option::is_none")]
        pub principal_id_claim: Option<String>,
    }

    #[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq, ToSchema)]
    #[schema(as = identitysource::OpenIdConnectIdentityTokenConfiguration)]
    #[serde(rename_all = "camelCase", default)]
    pub struct OpenIdConnectIdentityTokenConfiguration {
        #[serde(skip_serializing_if = "Vec::is_empty")]
        pub client_ids: Vec<String>,
        #[serde(skip_serializing_if = "Option::is_none")]
        pub principal_id_claim: Option<String>,
    }

    #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, ToSchema)]
    #[schema(as = identitysource::OpenIdConnectTokenSelection)]
    #[serde(rename_all = "camelCase")]
    pub enum OpenIdConnectTokenSelection {
        AccessTokenOnly(OpenIdConnectAccessTokenConfiguration),
        IdentityTokenOnly(OpenIdConnectIdentityTokenConfiguration),
    }

    impl Default for OpenIdConnectTokenSelection {
        fn default() -> Self {
            OpenIdConnectTokenSelection::AccessTokenOnly(
                OpenIdConnectAccessTokenConfiguration::default(),
            )
        }
    }

    #[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq, ToSchema)]
    #[schema(as = identitysource::OpenIdConnectGroupConfiguration)]
    #[serde(rename_all = "camelCase")]
    pub struct OpenIdConnectGroupConfiguration {
        pub group_claim: String,
        pub group_entity_type: String,
    }

    #[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq, ToSchema)]
    #[schema(as = identitysource::OpenIdConnectConfiguration)]
    #[serde(rename_all = "camelCase")]
    pub struct OpenIdConnectConfiguration {
        pub issuer: String,
        pub token_selection: OpenIdConnectTokenSelection,
        #[serde(skip_serializing_if = "Option::is_none")]
        pub entity_id_prefix: Option<String>,
        #[serde(skip_serializing_if = "Option::is_none")]
        pub group_configuration: Option<OpenIdConnectGroupConfiguration>,
    }

    #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, ToSchema)]
    #[schema(as = identitysource::Configuration)]
    #[serde(rename_all = "camelCase")]
    pub enum Configuration {
        CognitoUserPoolConfiguration(CognitoUserPoolConfiguration),
        OpenIdConnectConfiguration(OpenIdConnectConfiguration),
    }

    impl Default for Configuration {
        fn default() -> Self {
            Configuration::CognitoUserPoolConfiguration(CognitoUserPoolConfiguration::default())
        }
    }
}

#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct IdentitySource {
    pub principal_entity_type: String,
    pub configuration: is::Configuration,
}

impl IdentitySource {
    pub fn prefix(&self) -> String {
        match &self.configuration {
            is::Configuration::CognitoUserPoolConfiguration(config) => config
                .user_pool_arn
                .split('/')
                .next_back()
                .expect("Invalid user pool ARN")
                .to_string(),
            is::Configuration::OpenIdConnectConfiguration(config) => {
                match config.entity_id_prefix {
                    Some(ref val) => val.clone(),
                    None => config.issuer.replace("http://", "").replace("https://", ""),
                }
            }
        }
    }

    pub fn id_claim(&self) -> String {
        match &self.configuration {
            is::Configuration::CognitoUserPoolConfiguration(_) => "sub".to_string(),
            is::Configuration::OpenIdConnectConfiguration(conf) => match &conf.token_selection {
                OpenIdConnectTokenSelection::AccessTokenOnly(token) => {
                    match &token.principal_id_claim {
                        Some(val) => val.clone(),
                        None => "sub".to_string(),
                    }
                }
                OpenIdConnectTokenSelection::IdentityTokenOnly(token) => {
                    match &token.principal_id_claim {
                        Some(val) => val.clone(),
                        None => "sub".to_string(),
                    }
                }
            },
        }
    }

    pub fn group_claim(&self) -> Option<String> {
        match &self.configuration {
            is::Configuration::CognitoUserPoolConfiguration(_) => {
                Some("cognito:groups".to_string())
            }
            is::Configuration::OpenIdConnectConfiguration(conf) => conf
                .group_configuration
                .as_ref()
                .map(|group| group.group_claim.clone()),
        }
    }

    pub fn group_entity_type(&self) -> Option<String> {
        match &self.configuration {
            is::Configuration::CognitoUserPoolConfiguration(conf) => conf
                .group_configuration
                .as_ref()
                .map(|group| group.group_entity_type.clone()),
            is::Configuration::OpenIdConnectConfiguration(conf) => conf
                .group_configuration
                .as_ref()
                .map(|group| group.group_entity_type.clone()),
        }
    }
}

#[derive(Debug, Default, Clone, Serialize, Deserialize, ToSchema, PartialEq, Eq)]
#[serde(rename_all = "camelCase", default)]
pub struct ApiKey {
    pub id: Uuid,
    pub key: String,
    pub name: String,
    #[serde(default = "default_true")]
    pub enabled: bool,
    pub project_id: Uuid,
    pub owner: EntityUid,
    pub role: Role,
    pub expires_at: Option<chrono::DateTime<chrono::Utc>>,
    pub created_at: chrono::DateTime<chrono::Utc>,
    pub updated_at: chrono::DateTime<chrono::Utc>,
}

impl ApiKey {
    pub fn new(
        id: Uuid,
        key: String,
        name: String,
        project_id: Uuid,
        owner: EntityUid,
        role: Role,
        expires_at: Option<chrono::DateTime<chrono::Utc>>,
    ) -> Self {
        let now = chrono::Utc::now();

        Self {
            id,
            key,
            name,
            enabled: true,
            project_id,
            owner,
            role,
            expires_at,
            created_at: now,
            updated_at: now,
        }
    }

    /// Checks if the API key has expired at the given timestamp `now`.
    pub fn is_expired_at(&self, now: chrono::DateTime<chrono::Utc>) -> bool {
        self.expires_at.is_some_and(|expires| now >= expires)
    }

    /// Checks if the API key has expired at the current time (`chrono::Utc::now()`).
    pub fn is_expired(&self) -> bool {
        self.is_expired_at(chrono::Utc::now())
    }

    /// Entity UID for Cedar: ApiKey::"project_id|apikey_id"
    pub fn entity_uid(&self) -> EntityUid {
        EntityUid::new(
            APIKEY_ENTITY_TYPE.to_string(),
            format!("{}|{}", self.project_id, self.id),
        )
    }

    /// Cedar Entity representation for ApiKey
    pub fn entity(&self) -> Entity {
        let uid = self.entity_uid();
        let attrs = HashMap::from([(ATTR_ENABLED.to_string(), EntityAttr::Boolean(self.enabled))]);
        let parents = HashSet::from([EntityUid::from(PARENT_UID)]);
        let tags = HashMap::from([(TAG_NAME.to_string(), EntityAttr::String(self.name.clone()))]);

        Entity::new_with_tags(uid, attrs, parents, tags)
    }

    /// Policy/TemplateLink ID for Cedar
    pub fn policy_id(&self) -> String {
        format!("apikey_{}_{}", self.project_id, self.id)
    }

    /// Returns the Cedar template ID for an ApiKey with a preset role.
    pub fn template_id(&self) -> Option<&'static str> {
        match &self.role {
            Role::Preset(base) => Some(match base {
                CedrusRole::Admin => "AdminRole",
                CedrusRole::Editor => "EditorRole",
                CedrusRole::Viewer => "ViewerRole",
            }),
            Role::Custom(_) => None,
        }
    }
}

#[derive(Debug, Default, Clone, Serialize, Deserialize, ToSchema, PartialEq, Eq)]
#[serde(rename_all = "camelCase", default)]
pub struct Project {
    pub id: Uuid,
    #[serde(skip_serializing_if = "String::is_empty")]
    pub name: String,

    #[serde(default = "default_true")]
    pub enabled: bool,

    pub owner: EntityUid,

    pub created_at: chrono::DateTime<chrono::Utc>,
    pub updated_at: chrono::DateTime<chrono::Utc>,
}

impl Project {
    pub fn new(id: Uuid, name: String, owner: EntityUid) -> Self {
        let now = chrono::Utc::now();

        Self {
            id,
            name,
            enabled: true,
            owner,
            created_at: now,
            updated_at: now,
        }
    }

    pub fn entity_uid(id: Uuid) -> EntityUid {
        EntityUid::new(PROJECT_ENTITY_TYPE.to_string(), id.to_string())
    }

    pub fn entity(&self) -> Entity {
        let uid = EntityUid::new(PROJECT_ENTITY_TYPE.to_string(), self.id.to_string());
        let attrs = HashMap::from([
            (ATTR_ENABLED.to_string(), EntityAttr::Boolean(true)),
            (
                ATTR_OWNER.to_string(),
                EntityAttr::EntityUid(self.owner.clone()),
            ),
        ]);
        let parents = HashSet::from([EntityUid::from(PARENT_UID)]);
        let tags = HashMap::from([(TAG_NAME.to_string(), EntityAttr::String(self.name.clone()))]);

        Entity::new_with_tags(uid, attrs, parents, tags)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_api_key_expiration() {
        let now = chrono::Utc::now();
        let past = now - chrono::Duration::hours(1);
        let future = now + chrono::Duration::hours(1);

        let owner = EntityUid::new("User".to_string(), "user-123".to_string());
        let key_no_expiry = ApiKey::new(
            Uuid::nil(),
            "key-1".to_string(),
            "No Expiry".to_string(),
            Uuid::nil(),
            owner.clone(),
            Role::default(),
            None,
        );
        assert!(!key_no_expiry.is_expired_at(now));

        let key_expired = ApiKey::new(
            Uuid::nil(),
            "key-2".to_string(),
            "Expired".to_string(),
            Uuid::nil(),
            owner.clone(),
            Role::default(),
            Some(past),
        );
        assert!(key_expired.is_expired_at(now));

        let key_valid = ApiKey::new(
            Uuid::nil(),
            "key-3".to_string(),
            "Valid".to_string(),
            Uuid::nil(),
            owner,
            Role::default(),
            Some(future),
        );
        assert!(!key_valid.is_expired_at(now));
    }

    #[test]
    fn test_api_key_serde_backward_compatibility() {
        let json_without_expires_at = r#"{
            "id": "00000000-0000-0000-0000-000000000000",
            "key": "test_key",
            "name": "Legacy Key",
            "projectId": "00000000-0000-0000-0000-000000000000",
            "owner": { "type": "User", "id": "owner" },
            "role": { "type": "Preset", "value": "Viewer" },
            "createdAt": "2026-01-01T00:00:00Z",
            "updatedAt": "2026-01-01T00:00:00Z"
        }"#;

        let api_key: ApiKey = serde_json::from_str(json_without_expires_at).unwrap();
        assert_eq!(api_key.expires_at, None);
        assert!(api_key.enabled);
        assert!(!api_key.is_expired());
    }

    #[test]
    fn test_api_key_entity() {
        let owner = EntityUid::new("User".to_string(), "owner".to_string());
        let mut api_key = ApiKey::new(
            Uuid::nil(),
            "key".to_string(),
            "My Key".to_string(),
            Uuid::nil(),
            owner,
            Role::default(),
            None,
        );
        let entity = api_key.entity();
        assert_eq!(
            entity.attrs().get("enabled"),
            Some(&EntityAttr::Boolean(true))
        );

        api_key.enabled = false;
        let entity_disabled = api_key.entity();
        assert_eq!(
            entity_disabled.attrs().get("enabled"),
            Some(&EntityAttr::Boolean(false))
        );
    }

    #[test]
    fn test_project_name_validation() {
        let owner = EntityUid::new("User".to_string(), "owner".to_string());
        let project_empty = Project::new(Uuid::nil(), "".to_string(), owner.clone());
        assert!(project_empty.name.trim().is_empty());

        let project_whitespace = Project::new(Uuid::nil(), "   ".to_string(), owner.clone());
        assert!(project_whitespace.name.trim().is_empty());

        let project_valid = Project::new(Uuid::nil(), "My Project".to_string(), owner);
        assert!(!project_valid.name.trim().is_empty());
    }
}